licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
6421
@testset "Fminbox" begin # Quadratic objective function # For (A*x-b)^2/2 function quadratic!(g, x, A, b) AtAx = A'A*x v = dot(x, AtAx)/2 - dot(b'*A, x) if g !== nothing g .= AtAx .- A'b end return v end Random.seed!(1) N = 8 boxl = 2.0 # Generate a problem where the bounds-free solution lies outside of the chosen box function find_outbox(N, limit) outbox = false while !outbox # Random least squares problem A = randn(N,N) b = randn(N) # Useful calculation that can be re-used # Random starting point initial_x = A\b # The objective funcg! = (g, x) -> quadratic!(g, x, A, b) g = similar(initial_x) funcg!(g, initial_x) # Find the minimum _objective = OnceDifferentiable(x->funcg!(nothing, x), (g, x)->funcg!(g, x), funcg!, initial_x) results = optimize(_objective, initial_x, ConjugateGradient()) @test Optim.converged(results) results = optimize(_objective, Optim.minimizer(results), ConjugateGradient()) # restart to ensure high-precision convergence @test Optim.converged(results) opt_x = Optim.minimizer(results) @test norm(g) < 1e-4 if any(t -> abs(t) > boxl, opt_x) return _objective end end nothing end _objective = find_outbox(N, boxl) # fminbox l = fill(-boxl, N) u = fill(boxl, N) initial_x = (rand(N) .- 0.5) .* boxl for _optimizer in (ConjugateGradient(), GradientDescent(), LBFGS(), BFGS()) debug_printing && printstyled("Solver: ", summary(_optimizer), "\n", color=:green) results = optimize(_objective, l, u, initial_x, Fminbox(_optimizer)) @test Optim.converged(results) @test summary(results) == "Fminbox with $(summary(_optimizer))" opt_x = Optim.minimizer(results) NLSolversBase.gradient!(_objective, opt_x) g = NLSolversBase.gradient(_objective) # check first-order constrained optimality conditions for i = 1:N @test abs(g[i]) < 3e-3 || (opt_x[i] < -boxl+1e-3 && g[i] > 0) || (opt_x[i] > boxl-1e-3 && g[i] < 0) end end # Throw ArgumentError when initial guess is outside the box @test_throws ArgumentError optimize(_objective, l, u, 2u, Fminbox(GradientDescent())) # tests for #180 results = optimize(_objective, l, u, initial_x, Fminbox(), Optim.Options(outer_iterations = 2)) @test Optim.iterations(results) == 2 @test Optim.minimum(results) == _objective.f(Optim.minimizer(results)) # Warn when initial condition is not in the interior of the box initial_x = rand([-1,1],N)*boxl @test_logs (:warn, "Initial position cannot be on the boundary of the box. Moving elements to the interior.\nElement indices affected: [1, 2, 3, 4, 5, 6, 7, 8]") optimize(_objective, l, u, initial_x, Fminbox(), Optim.Options(outer_iterations = 1)) # might fail if changes are made to Optim.jl # TODO: come up with a better test #results = Optim.optimize(_objective, initial_x, l, u, Fminbox(); optimizer_o = Optim.Options(iterations = 2)) #@test Optim.iterations(results) == 470 @testset "simple input" begin function exponential(x) return exp((2.0 - x[1])^2) + exp((3.0 - x[2])^2) end function exponential_gradient!(storage, x) storage[1] = -2.0 * (2.0 - x[1]) * exp((2.0 - x[1])^2) storage[2] = -2.0 * (3.0 - x[2]) * exp((3.0 - x[2])^2) storage end function exponential_gradient(x) storage = similar(x) storage[1] = -2.0 * (2.0 - x[1]) * exp((2.0 - x[1])^2) storage[2] = -2.0 * (3.0 - x[2]) * exp((3.0 - x[2])^2) storage end initial_x = [0.0, 0.0] optimize(exponential, exponential_gradient!, initial_x, BFGS()) lb = fill(-0.1, 2) ub = fill(1.1, 2) od = OnceDifferentiable(exponential, initial_x) optimize(od, lb, ub, initial_x, Fminbox()) nd = NonDifferentiable(exponential, initial_x) optimize(nd, lb, ub, initial_x, Fminbox(NelderMead())) od_forward = OnceDifferentiable(exponential, initial_x; autodiff = :forward) optimize(od_forward, lb, ub, initial_x, Fminbox()) optimize(exponential, lb, ub, initial_x, Fminbox()) optimize(exponential, exponential_gradient!, lb, ub, initial_x, Fminbox()) optimize(od, lb, ub, initial_x) optimize(od_forward, lb, ub, initial_x) optimize(exponential, lb, ub, initial_x) optimize(exponential, exponential_gradient!, lb, ub, initial_x) @testset "inplace and autodiff keywords #616" begin optimize(exponential, lb, ub, initial_x, Fminbox()) optimize(exponential, lb, ub, initial_x, Fminbox(); autodiff = :finite) optimize(exponential, lb, ub, initial_x, Fminbox(); autodiff = :forward) optimize(exponential, exponential_gradient, lb, ub, initial_x, Fminbox(), inplace = false) end @testset "error for second order methods #616" begin @test_throws ArgumentError optimize(x->x, (G,x)->x, rand(1),rand(1),rand(1), Fminbox(Newton())) @test_throws ArgumentError optimize(x->x, (G,x)->x, rand(1),rand(1),rand(1), Fminbox(NewtonTrustRegion())) end @testset "allow for an Optim.Options to be passed #623" begin optimize(exponential, lb, ub, initial_x, Fminbox(), Optim.Options()) optimize(exponential, exponential_gradient!, lb, ub, initial_x, Fminbox(), Optim.Options()) @test_broken optimize(exponential, exponential_gradient, lb, ub, initial_x, Optim.Options()) end end end @testset "#631" begin # Fminbox evaluates outside the box #861 # https://github.com/JuliaNLSolvers/Optim.jl/issues/861 for m in (GradientDescent(), ConjugateGradient(), BFGS(), LBFGS()) optimize(x -> sqrt(x[1]), (g,x)->(g[1]=1/(2*sqrt(x[1]))), [0.0], [10.0], [1.0], Fminbox(m)) optimize(x -> sqrt(x[1]), [0.0], [10.0], [1.0], Fminbox(m); autodiff=:forwarddiff) end end @testset "#865" begin optimize(x -> sum(x), [0.,0.0], [2.0,2.0], [1.,1.0], Fminbox(NelderMead())) end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
335
@testset "SAMIN" begin prob = MVP.UnconstrainedProblems.examples["Himmelblau"] xtrue = prob.solutions f = OptimTestProblems.MultivariateProblems.objective(prob) x0 = prob.initial_x res = optimize(f, x0.-100., x0.+100.0, x0, Optim.SAMIN(), Optim.Options(iterations=1000000)) @test Optim.minimum(res) < 1e-6 end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
27421
@testset "Constraints" begin # Utility function for hand-setting the μ parameter function setstate!(state, μ, d, constraints, method) state.μ = μ Optim.update_fg!(d, constraints, state, method) Optim.update_h!(d, constraints, state, method) end @testset "Bounds parsing" begin b = Optim.ConstraintBounds([0.0, 0.5, 2.0], [1.0, 1.0, 2.0], [5.0, 3.8], [5.0, 4.0]) @test b.eqx == [3] @test b.valx == [2.0] @test b.ineqx == [1,1,2,2] @test b.σx == [1,-1,1,-1] @test b.bx == [0.0,1.0,0.5,1.0] @test b.eqc == [1] @test b.valc == [5] @test b.ineqc == [2,2] @test b.σc == [1,-1] @test b.bc == [3.8,4.0] io = IOBuffer() show(io, b) @test String(take!(io)) == "ConstraintBounds:\n Variables:\n x[3]=2.0\n x[1]≥0.0, x[1]≤1.0, x[2]≥0.5, x[2]≤1.0\n Linear/nonlinear constraints:\n c_1=5.0\n c_2≥3.8, c_2≤4.0" b = Optim.ConstraintBounds(Float64[], Float64[], [5.0, 3.8], [5.0, 4.0]) for fn in (:eqx, :valx, :ineqx, :σx, :bx) @test isempty(getfield(b, fn)) end @test b.eqc == [1] @test b.valc == [5] @test b.ineqc == [2,2] @test b.σc == [1,-1] @test b.bc == [3.8,4.0] ba = Optim.ConstraintBounds([], [], [5.0, 3.8], [5.0, 4.0]) @test eltype(ba) == Float64 @test_throws ArgumentError Optim.ConstraintBounds([0.0, 0.5, 2.0], [1.0, 1.0, 2.0], [5.0, 4.8], [5.0, 4.0]) @test_throws DimensionMismatch Optim.ConstraintBounds([0.0, 0.5, 2.0], [1.0, 1.0], [5.0, 4.8], [5.0, 4.0]) end @testset "IPNewton computations" begin # Compare hand-computed gradient against that from automatic differentiation function check_autodiff(d, bounds, x, cfun::Function, bstate, μ) c = cfun(x) J = Optim.NLSolversBase.ForwardDiff.jacobian(cfun, x) p = Optim.pack_vec(x, bstate) ftot! = (storage, p)->Optim.lagrangian_fgvec!(p, storage, gx, bgrad, d, bounds, x, c, J, bstate, μ) pgrad = similar(p) ftot!(pgrad, p) chunksize = min(8, length(p)) TD = Optim.NLSolversBase.ForwardDiff.Dual{Optim.ForwardDiff.Tag{Nothing,Float64},eltype(p),chunksize} xd = similar(x, TD) bstated = Optim.BarrierStateVars{TD}(bounds) pcmp = similar(p) ftot = p->Optim.lagrangian_vec(p, d, bounds, xd, cfun, bstated, μ) #ForwardDiff.gradient!(pcmp, ftot, p, Optim.ForwardDiff.{chunksize}()) Optim.NLSolversBase.ForwardDiff.gradient!(pcmp, ftot, p) @test pcmp ≈ pgrad end # Basic setup (using two objectives, one equal to zero and the other a Gaussian) μ = 0.2345678 d0 = TwiceDifferentiable(x->0.0, (g,x)->fill!(g, 0.0), (h,x)->fill!(h,0), rand(3)) A = randn(3,3); H = A'*A dg = TwiceDifferentiable(x->(x'*H*x)[1]/2, (g,x)->(g[:] = H*x), (h,x)->(h[:,:]=H), rand(3)) x = clamp.(randn(3), -0.99, 0.99) gx = similar(x) cfun = x->Float64[] c = Float64[] J = Array{Float64}(undef, 0,0) method = Optim.IPNewton(μ0 = μ) options = Optim.Options(; Optim.default_options(method)...) ## In the code, variable constraints are special-cased (for ## reasons of user-convenience and efficiency). It's ## important to check that the special-casing yields the same ## result as the general case. So in the first three ## constrained cases below, we compare variable constraints ## against the same kind of constraint applied generically. cvar! = (c, x) -> copyto!(c, x) cvarJ! = (J, x) -> copyto!(J, Matrix{Float64}(I, size(J)...)) cvarh! = (h, x, λ) -> h # h! adds to h, it doesn't replace it ## No constraints bounds = Optim.ConstraintBounds(Float64[], Float64[], Float64[], Float64[]) bstate = Optim.BarrierStateVars(bounds, x) bgrad = similar(bstate) f_x, L = Optim.lagrangian_fg!(gx, bgrad, dg, bounds, x, Float64[], Array{Float64}(undef, 0,0), bstate, μ) @test f_x == L == dg.f(x) @test gx == H*x constraints = TwiceDifferentiableConstraints( (c,x)->nothing, (J,x)->nothing, (H,x,λ)->nothing, bounds) state = Optim.initial_state(method, options, dg, constraints, x) @test Optim.gf(bounds, state) ≈ gx @test Optim.Hf(constraints, state) ≈ H stateconvert = convert(Optim.IPNewtonState{Float64, Vector{Float64}}, state) @test Optim.gf(bounds, stateconvert) ≈ gx @test Optim.Hf(constraints, stateconvert) ≈ H ## Pure equality constraints on variables xbar = fill(0.2, length(x)) bounds = Optim.ConstraintBounds(xbar, xbar, [], []) bstate = Optim.BarrierStateVars(bounds) rand!(bstate.λxE) bgrad = similar(bstate) f_x, L = Optim.lagrangian_fg!(gx, bgrad, d0, bounds, x, c, J, bstate, μ) @test f_x == 0 @test L ≈ dot(bstate.λxE, xbar-x) @test gx == -bstate.λxE @test bgrad.λxE == xbar-x # TODO: Fix autodiff check #check_autodiff(d0, bounds, x, cfun, bstate, μ) constraints = TwiceDifferentiableConstraints( (c,x)->nothing, (J,x)->nothing, (H,x,λ)->nothing, bounds) state = Optim.initial_state(method, options, d0, constraints, x) copyto!(state.bstate.λxE, bstate.λxE) setstate!(state, μ, d0, constraints, method) @test Optim.gf(bounds, state) ≈ [gx; xbar-x] n = length(x) eyen = Matrix{Float64}(I, n, n) @test Optim.Hf(constraints, state) ≈ [eyen -eyen; -eyen zeros(n,n)] # Now again using the generic machinery bounds = Optim.ConstraintBounds([], [], xbar, xbar) constraints = TwiceDifferentiableConstraints(cvar!, cvarJ!, cvarh!, bounds) state = Optim.initial_state(method, options, d0, constraints, x) copyto!(state.bstate.λcE, bstate.λxE) setstate!(state, μ, d0, constraints, method) @test Optim.gf(bounds, state) ≈ [gx; xbar-x] n = length(x) eyen = Matrix{Float64}(I, n, n) @test Optim.Hf(constraints, state) ≈ [eyen -eyen; -eyen zeros(n,n)] ## Nonnegativity constraints bounds = Optim.ConstraintBounds(zeros(length(x)), fill(Inf,length(x)), [], []) y = rand(length(x)) bstate = Optim.BarrierStateVars(bounds, y) rand!(bstate.λx) bgrad = similar(bstate) f_x, L = Optim.lagrangian_fg!(gx, bgrad, d0, bounds, y, Float64[], Array{Float64}(undef, 0,0), bstate, μ) @test f_x == 0 @test L ≈ -μ*sum(log, y) @test bgrad.slack_x == -μ./y + bstate.λx @test gx == -bstate.λx # TODO: Fix autodiff check #check_autodiff(d0, bounds, y, cfun, bstate, μ) constraints = TwiceDifferentiableConstraints( (c,x)->nothing, (J,x)->nothing, (H,x,λ)->nothing, bounds) state = Optim.initial_state(method, options, d0, constraints, y) setstate!(state, μ, d0, constraints, method) @test Optim.gf(bounds, state) ≈ -μ./y @test Optim.Hf(constraints, state) ≈ μ*Diagonal(1 ./ y.^2) # Now again using the generic machinery bounds = Optim.ConstraintBounds([], [], zeros(length(x)), fill(Inf,length(x))) constraints = TwiceDifferentiableConstraints(cvar!, cvarJ!, cvarh!, bounds) state = Optim.initial_state(method, options, d0, constraints, y) setstate!(state, μ, d0, constraints, method) @test Optim.gf(bounds, state) ≈ -μ./y @test Optim.Hf(constraints, state) ≈ μ*Diagonal(1 ./ y.^2) ## General inequality constraints on variables lb, ub = rand(length(x)).-2, rand(length(x)).+1 bounds = Optim.ConstraintBounds(lb, ub, [], []) bstate = Optim.BarrierStateVars(bounds, x) rand!(bstate.slack_x) # intentionally displace from the correct value rand!(bstate.λx) bgrad = similar(bstate) f_x, L = Optim.lagrangian_fg!(gx, bgrad, d0, bounds, x, Float64[], Array{Float64}(undef, 0,0), bstate, μ) @test f_x == 0 s = bounds.σx .* (x[bounds.ineqx] - bounds.bx) Ltarget = -μ*sum(log, bstate.slack_x) + dot(bstate.λx, bstate.slack_x - s) @test L ≈ Ltarget dx = similar(gx); fill!(dx, 0) for (i,j) in enumerate(bounds.ineqx) dx[j] -= bounds.σx[i]*bstate.λx[i] end @test gx ≈ dx @test bgrad.slack_x == -μ./bstate.slack_x + bstate.λx # TODO: Fix autodiff check #check_autodiff(d0, bounds, x, cfun, bstate, μ) constraints = TwiceDifferentiableConstraints( (c,x)->nothing, (J,x)->nothing, (H,x,λ)->nothing, bounds) state = Optim.initial_state(method, options, d0, constraints, x) copyto!(state.bstate.slack_x, bstate.slack_x) copyto!(state.bstate.λx, bstate.λx) setstate!(state, μ, d0, constraints, method) gxs, hxs = zeros(length(x)), zeros(length(x)) s, λ = state.bstate.slack_x, state.bstate.λx for (i,j) in enumerate(bounds.ineqx) # # Primal # gxs[j] += -2*μ*bounds.σx[i]/s[i] + μ*(x[j]-bounds.bx[i])/s[i]^2 # hxs[j] += μ/s[i]^2 # Primal-dual gstmp = -μ/s[i] + λ[i] gλtmp = s[i] - bounds.σx[i]*(x[j]-bounds.bx[i]) htmp = λ[i]/s[i] hxs[j] += htmp gxs[j] += bounds.σx[i]*(gstmp - λ[i]) - bounds.σx[i]*htmp*gλtmp end @test Optim.gf(bounds, state) ≈ gxs @test Optim.Hf(constraints, state) ≈ Diagonal(hxs) # Now again using the generic machinery bounds = Optim.ConstraintBounds([], [], lb, ub) constraints = TwiceDifferentiableConstraints(cvar!, cvarJ!, cvarh!, bounds) state = Optim.initial_state(method, options, d0, constraints, x) copyto!(state.bstate.slack_c, bstate.slack_x) copyto!(state.bstate.λc, bstate.λx) setstate!(state, μ, d0, constraints, method) @test Optim.gf(bounds, state) ≈ gxs @test Optim.Hf(constraints, state) ≈ Diagonal(hxs) ## Nonlinear equality constraints cfun = x->[x[1]^2+x[2]^2, x[2]*x[3]^2] cfun! = (c, x) -> copyto!(c, cfun(x)) cJ! = (J, x) -> copyto!(J, [2*x[1] 2*x[2] 0; 0 x[3]^2 2*x[2]*x[3]]) ch! = function(h, x, λ) h[1,1] += 2*λ[1] h[2,2] += 2*λ[1] h[3,3] += 2*λ[2]*x[2] end c = cfun(x) J = Optim.NLSolversBase.ForwardDiff.jacobian(cfun, x) Jtmp = similar(J); @test cJ!(Jtmp, x) ≈ J # just to check we did it right cbar = rand(length(c)) bounds = Optim.ConstraintBounds([], [], cbar, cbar) bstate = Optim.BarrierStateVars(bounds, x, c) rand!(bstate.λcE) bgrad = similar(bstate) f_x, L = Optim.lagrangian_fg!(gx, bgrad, d0, bounds, x, c, J, bstate, μ) @test f_x == 0 @test L ≈ dot(bstate.λcE, cbar-c) @test gx ≈ -J'*bstate.λcE @test bgrad.λcE == cbar-c # TODO: Fix autodiff check #check_autodiff(d0, bounds, x, cfun, bstate, μ) constraints = TwiceDifferentiableConstraints(cfun!, cJ!, ch!, bounds) state = Optim.initial_state(method, options, d0, constraints, x) copyto!(state.bstate.λcE, bstate.λcE) setstate!(state, μ, d0, constraints, method) heq = zeros(length(x), length(x)) ch!(heq, x, bstate.λcE) @test Optim.gf(bounds, state) ≈ [gx; cbar-c] @test Optim.Hf(constraints, state) ≈ [Matrix(cholesky(Positive, heq)) -J'; -J zeros(size(J,1), size(J,1))] ## Nonlinear inequality constraints bounds = Optim.ConstraintBounds([], [], .-rand(length(c)).-1, rand(length(c)).+2) bstate = Optim.BarrierStateVars(bounds, x, c) rand!(bstate.slack_c) # intentionally displace from the correct value rand!(bstate.λc) bgrad = similar(bstate) f_x, L = Optim.lagrangian_fg!(gx, bgrad, d0, bounds, x, c, J, bstate, μ) @test f_x == 0 Ltarget = -μ*sum(log, bstate.slack_c) + dot(bstate.λc, bstate.slack_c - bounds.σc.*(c[bounds.ineqc]-bounds.bc)) @test L ≈ Ltarget @test gx ≈ -J[bounds.ineqc,:]'*(bstate.λc.*bounds.σc) @test bgrad.slack_c == -μ./bstate.slack_c + bstate.λc @test bgrad.λc == bstate.slack_c - bounds.σc .* (c[bounds.ineqc] - bounds.bc) # TODO: Fix autodiff check #check_autodiff(d0, bounds, x, cfun, bstate, μ) constraints = TwiceDifferentiableConstraints(cfun!, cJ!, ch!, bounds) state = Optim.initial_state(method, options, d0, constraints, x) copyto!(state.bstate.slack_c, bstate.slack_c) copyto!(state.bstate.λc, bstate.λc) setstate!(state, μ, d0, constraints, method) hineq = zeros(length(x), length(x)) λ = zeros(size(J, 1)) for (i,j) in enumerate(bounds.ineqc) λ[j] += bstate.λc[i]*bounds.σc[i] end ch!(hineq, x, λ) JI = J[bounds.ineqc,:] # # Primal # hxx = μ*JI'*Diagonal(1 ./ bstate.slack_c.^2)*JI - hineq # gf = -JI'*(bounds.σc .* bstate.λc) + JI'*Diagonal(bounds.σc)*(bgrad.slack_c - μ(bgrad.λc ./ bstate.slack_c.^2)) # Primal-dual # hxx = full(cholesky(Positive, -hineq)) + JI'*Diagonal(bstate.λc./bstate.slack_c)*JI hxx = -hineq + JI'*Diagonal(bstate.λc./bstate.slack_c)*JI gf = -JI'*(bounds.σc .* bstate.λc) + JI'*Diagonal(bounds.σc)*(bgrad.slack_c - (bgrad.λc .* bstate.λc ./ bstate.slack_c)) @test Optim.gf(bounds, state) ≈ gf @test Optim.Hf(constraints, state) ≈ Matrix(cholesky(Positive, hxx, Val{true})) end @testset "IPNewton initialization" begin method = IPNewton() options = Optim.Options(; Optim.default_options(method)...) x = [1.0,0.1,0.3,0.4] ## A linear objective function (hessian is zero) f_g = [1.0,2.0,3.0,4.0] d = TwiceDifferentiable(x->dot(x, f_g), (g,x)->copyto!(g, f_g), (h,x)->fill!(h, 0), x) # Variable bounds constraints = TwiceDifferentiableConstraints([0.5, 0.0, -Inf, -Inf], [Inf, Inf, 1.0, 0.8]) state = Optim.initial_state(method, options, d, constraints, x) Optim.update_fg!(d, constraints, state, method) @test norm(f_g - state.g) ≈ 0.01*norm(f_g) # Nonlinear inequalities constraints = TwiceDifferentiableConstraints( (c,x)->(c[1]=x[1]*x[2]; c[2]=3*x[3]+x[4]^2), (J,x)->(J[:,:] = [x[2] x[1] 0 0; 0 0 3 2*x[4]]), (h,x,λ)->(h[4,4] += λ[2]*2), [], [], [0.05, 0.4], [0.15, 4.4]) @test Optim.isinterior(constraints, x) state = Optim.initial_state(method, options, d, constraints, x) Optim.update_fg!(d, constraints, state, method) @test norm(f_g - state.g) ≈ 0.01*norm(f_g) # Mixed equalities and inequalities constraints = TwiceDifferentiableConstraints( (c,x)->(c[1]=x[1]*x[2]; c[2]=3*x[3]+x[4]^2), (J,x)->(J .= [x[2] x[1] 0 0; 0 0 3 2*x[4]]), (h,x,λ)->(h[4,4] += λ[2]*2), [], [], [0.1, 0.4], [0.1, 4.4]) @test Optim.isfeasible(constraints, x) state = Optim.initial_state(method, options, d, constraints, x) Optim.update_fg!(d, constraints, state, method) J = zeros(2,4) constraints.jacobian!(J, x) eqnormal = vec(J[1,:]); eqnormal = eqnormal/norm(eqnormal) @test abs(dot(state.g, eqnormal)) < 1e-12 # orthogonal to equality constraint Pfg = f_g - dot(f_g, eqnormal)*eqnormal Pg = state.g - dot(state.g, eqnormal)*eqnormal @test norm(Pfg - Pg) ≈ 0.01*norm(Pfg) ## An objective function with a nonzero hessian hd = [1.0, 100.0, 0.01, 2.0] # diagonal terms of hessian d = TwiceDifferentiable(x->sum(hd.*x.^2)/2, (g,x)->copyto!(g, hd.*x), (h,x)->copyto!(h, Diagonal(hd)), x) NLSolversBase.gradient!(d, x) gx = NLSolversBase.gradient(d) hx = Diagonal(hd) # Variable bounds constraints = TwiceDifferentiableConstraints([0.5, 0.0, -Inf, -Inf], [Inf, Inf, 1.0, 0.8]) state = Optim.initial_state(method, options, d, constraints, x) Optim.update_fg!(d, constraints, state, method) @test abs(dot(gx, state.g)/dot(gx,gx) - 1) <= 0.011 Optim.update_h!(d, constraints, state, method) @test abs(dot(gx, state.H*gx)/dot(gx, hx*gx) - 1) <= 0.011 # Nonlinear inequalities constraints = TwiceDifferentiableConstraints( (c,x)->(c[1]=x[1]*x[2]; c[2]=3*x[3]+x[4]^2), (J,x)->(J[:,:] = [x[2] x[1] 0 0; 0 0 3 2*x[4]]), (h,x,λ)->(h[4,4] += λ[2]*2), [], [], [0.05, 0.4], [0.15, 4.4]) @test Optim.isinterior(constraints, x) state = Optim.initial_state(method, options, d, constraints, x) Optim.update_fg!(d, constraints, state, method) @test abs(dot(gx, state.g)/dot(gx,gx) - 1) <= 0.011 Optim.update_h!(d, constraints, state, method) @test abs(dot(gx, state.H*gx)/dot(gx, hx*gx) - 1) <= 0.011 # Mixed equalities and inequalities constraints = TwiceDifferentiableConstraints( (c,x)->(c[1]=x[1]*x[2]; c[2]=3*x[3]+x[4]^2), (J,x)->(J[:,:] = [x[2] x[1] 0 0; 0 0 3 2*x[4]]), (h,x,λ)->(h[4,4] += λ[2]*2), [], [], [0.1, 0.4], [0.1, 4.4]) @test Optim.isfeasible(constraints, x) state = Optim.initial_state(method, options, d, constraints, x) Optim.update_fg!(d, constraints, state, method) J = zeros(2,4) constraints.jacobian!(J, x) eqnormal = vec(J[1,:]); eqnormal = eqnormal/norm(eqnormal) @test abs(dot(state.g, eqnormal)) < 1e-12 # orthogonal to equality constraint Pgx = gx - dot(gx, eqnormal)*eqnormal @test abs(dot(Pgx, state.g)/dot(Pgx,Pgx) - 1) <= 0.011 Optim.update_h!(d, constraints, state, method) @test abs(dot(Pgx, state.H*Pgx)/dot(Pgx, hx*Pgx) - 1) <= 0.011 end @testset "IPNewton step" begin function autoqp(d, constraints, state) # Note that state must be fully up-to-date, and you must # have also called Optim.solve_step! p = Optim.pack_vec(state.x, state.bstate) chunksize = 1 #min(8, length(p)) # TODO: How do we deal with the new Tags in ForwardDiff? # TD = ForwardDiff.Dual{chunksize, eltype(y)} TD = Optim.NLSolversBase.ForwardDiff.Dual{Optim.NLSolversBase.ForwardDiff.Tag{Nothing,Float64}, eltype(p), chunksize} # TODO: It doesn't seem like it is possible to to create a dual where the values are duals? # TD2 = ForwardDiff.Dual{chunksize, ForwardDiff.Dual{chunksize, eltype(p)}} # TD2 = ForwardDiff.Dual{ForwardDiff.Tag{Nothing,Float64}, typeof(TD), chunksize} Tx = typeof(state.x) stated = convert(Optim.IPNewtonState{TD, Tx,1}, state) # TODO: Uncomment #stated2 = convert(Optim.IPNewtonState{TD2, Tx, 1}, state) ϕd = αs->Optim.lagrangian_linefunc(αs, d, constraints, stated) # TODO: Uncomment #ϕd2 = αs->Optim.lagrangian_linefunc(αs, d, constraints, stated2) #ForwardDiff.gradient(ϕd, zeros(4)), ForwardDiff.hessian(ϕd2, zeros(4)) Optim.NLSolversBase.ForwardDiff.gradient(ϕd, [0.0])#, ForwardDiff.hessian(ϕd2, [0.0]) end F = 1000 d = TwiceDifferentiable(x->F*x[1], (g, x) -> (g[1] = F), (h, x) -> (h[1,1] = 0), [0.0,]) μ = 1e-20 method = Optim.IPNewton(μ0=μ) options = Optim.Options(; Optim.default_options(method)...) x0 = μ/F*10 # minimum is at μ/F # Nonnegativity (the case that doesn't require slack variables) constraints = TwiceDifferentiableConstraints([0.0], []) state = Optim.initial_state(method, options, d, constraints, [x0]) qp = Optim.solve_step!(state, constraints, options) @test state.s[1] ≈ -(F-μ/x0)/(state.bstate.λx[1]/x0) # TODO: Fix ForwardDiff #g0, H0 = autoqp(d, constraints, state) @test qp[1] ≈ F*x0-μ*log(x0) # TODO: Fix ForwardDiff #@test [qp[2]] ≈ g0 #-(F-μ/x0)^2*x0^2/μ # TODO: Fix ForwardDiff #@test [qp[3]] ≈ H0 # μ/x0^2*(x0 - F*x0^2/μ)^2 bstate, bstep, bounds = state.bstate, state.bstep, constraints.bounds αmax = Optim.estimate_maxstep(Inf, state.x[bounds.ineqx].*bounds.σx, state.s[bounds.ineqx].*bounds.σx) ϕ = Optim.linesearch_anon(d, constraints, state, method) val0 = ϕ(0.0) val0 = isa(val0, Tuple) ? val0[1] : val0 @test val0 ≈ qp[1] α = method.linesearch!(ϕ, 1.0, αmax, qp) @test α > 1e-3 # TODO: Add linesearch_anon tests for IPNewton(linesearch! = backtracking_constrained) end @testset "Slack" begin σswap(σ, a, b) = σ == 1 ? (a, b) : (b, a) # Test that we achieve a high-precision minimum for fixed # μ. For anything other than nonnegativity/nonpositivity # constraints, this tests whether the slack variables are # solving the problem they were designed to address (the # possibility that adjacent floating-point numbers are too # widely spaced to accurately satisfy the KKT equations near a # boundary). F0 = 1000 μ = 1e-20 # smaller than eps(1.0) method = Optim.IPNewton(μ0=μ) options = Optim.Options(; Optim.default_options(method)...) for σ in (1, -1) F = σ*F0 # Nonnegativity/nonpositivity (the case that doesn't require slack variables) d = TwiceDifferentiable(x->F*x[1], (g, x) -> (g[1] = F), (h, x) -> (h[1,1] = 0), [0.0,]) constraints = TwiceDifferentiableConstraints(σswap(σ, [0.0], [])...) state = Optim.initial_state(method, options, d, constraints, [μ/F*10]) for i = 1:10 Optim.update_state!(d, constraints, state, method, options) state.μ = μ Optim.update_fg!(d, constraints, state, method) Optim.update_h!(d, constraints, state, method) end @test isapprox(first(state.x), μ/F, rtol=1e-4) # |x| ≥ 1, and check that we get slack precision better than eps(1.0) d = TwiceDifferentiable(x->F*(x[1]-σ), (g, x) -> (g[1] = F), (h, x) -> (h[1,1] = 0), [0.0,]) constraints = TwiceDifferentiableConstraints(σswap(σ, [Float64(σ)], [])...) state = Optim.initial_state(method, options, d, constraints, [(1+eps(1.0))*σ]) for i = 1:10 Optim.update_state!(d, constraints, state, method, options) state.μ = μ Optim.update_fg!(d, constraints, state, method) Optim.update_h!(d, constraints, state, method) end @test state.x[1] == σ @test state.bstate.slack_x[1] < eps(float(σ)) # |x| >= 1 using the linear/nonlinear constraints d = TwiceDifferentiable(x->F*(x[1]-σ), (g, x) -> (g[1] = F), (h, x) -> (h[1,1] = 0), [0.0,]) constraints = TwiceDifferentiableConstraints( (c,x)->(c[1] = x[1]), (J,x)->(J[1,1] = 1.0), (h,x,λ)->nothing, [], [], σswap(σ, [Float64(σ)], [])...) state = Optim.initial_state(method, options, d, constraints, [(1+eps(1.0))*σ]) for i = 1:10 Optim.update_state!(d, constraints, state, method, options) Optim.update_fg!(d, constraints, state, method) Optim.update_h!(d, constraints, state, method) end @test state.x[1] ≈ σ @test state.bstate.slack_c[1] < eps(float(σ)) end end @testset "Constrained optimization" begin # TODO: Add more problems mcvp = MVP.ConstrainedProblems.examples method = IPNewton() for (name, prob) in mcvp debug_printing && printstyled("Problem: ", name, "\n", color=:green) df = TwiceDifferentiable(MVP.objective(prob), MVP.gradient(prob), MVP.objective_gradient(prob), MVP.hessian(prob), prob.initial_x) cd = prob.constraintdata constraints = TwiceDifferentiableConstraints( cd.c!, cd.jacobian!, cd.h!, cd.lx, cd.ux, cd.lc, cd.uc) options = Optim.Options(; Optim.default_options(method)...) minval = NLSolversBase.value(df, prob.solutions) results = optimize(df,constraints, prob.initial_x, method, options) @test isa(summary(results), String) @test Optim.converged(results) @test Optim.minimum(results) < minval + sqrt(eps(minval)) debug_printing && printstyled("Iterations: $(Optim.iterations(results))\n", color=:red) debug_printing && printstyled("f-calls: $(Optim.f_calls(results))\n", color=:red) debug_printing && printstyled("g-calls: $(Optim.g_calls(results))\n", color=:red) debug_printing && printstyled("h-calls: $(Optim.h_calls(results))\n", color=:red) results = optimize(MVP.objective(prob),constraints, prob.initial_x, method, options) @test isa(summary(results), String) @test Optim.converged(results) @test Optim.minimum(results) < minval + sqrt(eps(minval)) end # Test constraints on both x and c prob = mcvp["HS9"] df = TwiceDifferentiable(MVP.objective(prob), MVP.gradient(prob), MVP.objective_gradient(prob), MVP.hessian(prob), prob.initial_x) cd = prob.constraintdata lx = [5,5]; ux = [15,15] constraints = TwiceDifferentiableConstraints( cd.c!, cd.jacobian!, cd.h!, lx, ux, cd.lc, cd.uc) options = Optim.Options(; Optim.default_options(method)...) xsol = [9.,12.] x0 = [12. 14.0] minval = NLSolversBase.value(df, xsol) results = optimize(df,constraints, [12, 14.0], method, options) @test isa(Optim.summary(results), String) @test Optim.converged(results) @test Optim.minimum(results) < minval + sqrt(eps(minval)) # Test the tracing # TODO: Update this when show_linesearch becomes part of Optim.Options method = IPNewton(show_linesearch = true) options = Optim.Options(iterations = 2, show_trace = true, extended_trace=true, store_trace = true; Optim.default_options(method)...) results = optimize(df,constraints, [12, 14.0], method, options) io = IOBuffer() show(io, results.trace) @test startswith(String(take!(io)), "Iter Lagrangian value Function value Gradient norm |==constr.| μ\n------ ---------------- -------------- -------------- -------------- --------\n") # TODO: Add test where we start with an infeasible point end end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
2080
@testset "Function counter" begin prob = OptimTestProblems.UnconstrainedProblems.examples["Rosenbrock"] let global fcount = 0 global fcounter function fcounter(reset::Bool = false) if reset fcount = 0 else fcount += 1 end fcount end global gcount = 0 global gcounter function gcounter(reset::Bool = false) if reset gcount = 0 else gcount += 1 end gcount end global hcount = 0 global hcounter function hcounter(reset::Bool = false) if reset hcount = 0 else hcount += 1 end hcount end end f(x) = begin fcounter() MVP.objective(prob)(x) end g!(out, x) = begin gcounter() MVP.gradient(prob)(out, x) end h!(out, x) = begin hcounter() MVP.hessian(prob)(out, x) end options = Optim.Options(; Optim.default_options(IPNewton())...) # TODO: Run this on backtrack_constrained as well (when we figure out what it does) for ls in [Optim.backtrack_constrained_grad,] #Optim.backtrack_constrained] fcounter(true); gcounter(true); hcounter(true) df = TwiceDifferentiable(f, g!, h!, prob.initial_x) infvec = fill(Inf, size(prob.initial_x)) # TODO: fix `optimize`so that empty constraints work #constraints = TwiceDifferentiableConstraints([], []) constraints = TwiceDifferentiableConstraints(-infvec, infvec) res = optimize(df, constraints, prob.initial_x, IPNewton(linesearch = ls), options) @test fcount == Optim.f_calls(res) @test gcount == Optim.g_calls(res) @test hcount == Optim.h_calls(res) end # TODO: Test a constrained problem # TODO: Test constraints call counter (if we need to make one) end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
1886
using Optim, Test @testset "#711" begin # make sure it doesn't try to promote df dof = 7 fun(x) = 0.0; x0 = fill(0.1, dof) df = TwiceDifferentiable(fun, x0) lx = fill(-1.2, dof); ux = fill(+1.2, dof) dfc = TwiceDifferentiableConstraints(lx, ux) res = optimize(df, dfc, x0, IPNewton(); autodiff=:forward) res = optimize(df, dfc, x0, IPNewton()) end @testset "#600" begin function exponential(x) return exp((2.0 - x[1])^2) + exp((3.0 - x[2])^2) end function exponential_gradient!(storage, x) storage[1] = -2.0 * (2.0 - x[1]) * exp((2.0 - x[1])^2) storage[2] = -2.0 * (3.0 - x[2]) * exp((3.0 - x[2])^2) storage end function exponential_hessian!(storage, x) Optim.NLSolversBase.ForwardDiff.hessian!(storage, exponential, x) end function exponential_gradient(x) storage = similar(x) storage[1] = -2.0 * (2.0 - x[1]) * exp((2.0 - x[1])^2) storage[2] = -2.0 * (3.0 - x[2]) * exp((3.0 - x[2])^2) storage end initial_x = [0.0, 0.0] optimize(exponential, exponential_gradient!, initial_x, BFGS()) lb = fill(-0.1, 2) ub = fill(1.1, 2) od = OnceDifferentiable(exponential, initial_x) optimize(od, lb, ub, initial_x, IPNewton()) optimize(od, lb, ub, initial_x, IPNewton(), Optim.Options()) optimize(exponential, lb, ub, initial_x, IPNewton()) optimize(exponential, lb, ub, initial_x, IPNewton(), Optim.Options()) optimize(exponential, exponential_gradient!, lb, ub, initial_x, IPNewton()) optimize(exponential, exponential_gradient!, lb, ub, initial_x, IPNewton(), Optim.Options()) optimize(exponential, exponential_gradient!, exponential_hessian!, lb, ub, initial_x, IPNewton()) optimize(exponential, exponential_gradient!, exponential_hessian!, lb, ub, initial_x, IPNewton(), Optim.Options()) optimize(TwiceDifferentiable(od, initial_x), lb, ub, initial_x) optimize(TwiceDifferentiable(od, initial_x), lb, ub, initial_x, Optim.Options()) end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
179
@testset "IPNewton Unconstrained" begin method = IPNewton() run_optim_tests_constrained(method; show_name=debug_printing, show_res=false, show_itcalls=debug_printing) end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
1702
@testset "Accelerated Gradient Descent" begin f(x) = x[1]^4 function g!(storage, x) storage[1] = 4 * x[1]^3 return end initial_x = [1.0] options = Optim.Options(show_trace = debug_printing, allow_f_increases=true) results = Optim.optimize(f, g!, initial_x, AcceleratedGradientDescent(), options) @test norm(Optim.minimum(results)) < 1e-6 @test summary(results) == "Accelerated Gradient Descent" # TODO: Check why skip problems fail skip = ("Trigonometric", "Large Polynomial", "Parabola", "Paraboloid Random Matrix", "Paraboloid Diagonal", "Extended Rosenbrock", "Penalty Function I", "Beale", "Extended Powell", ) run_optim_tests(AcceleratedGradientDescent(); skip = skip, convergence_exceptions = (("Rosenbrock", 1),("Rosenbrock", 2)), minimum_exceptions = (("Rosenbrock", 2),), minimizer_exceptions = (("Rosenbrock", 2),), iteration_exceptions = (("Powell", 1100), ("Rosenbrock", 10000), ("Polynomial", 1500), ("Fletcher-Powell", 10000), ("Extended Powell", 8000)), f_increase_exceptions = ("Hosaki", "Polynomial", "Powell", "Himmelblau", "Extended Powell", "Fletcher-Powell", "Quadratic Diagonal", "Rosenbrock"), show_name=debug_printing)#, #show_res = debug_printing) end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
1839
@testset "Adam" begin f(x) = x[1]^4 function g!(storage, x) storage[1] = 4 * x[1]^3 return end initial_x = [1.0] options = Optim.Options(show_trace = debug_printing, allow_f_increases=true, iterations=100_000) results = Optim.optimize(f, g!, initial_x, Adam(), options) @test norm(Optim.minimum(results)) < 1e-6 @test summary(results) == "Adam" # TODO: Check why skip problems fail skip = ("Large Polynomial", "Parabola", "Paraboloid Random Matrix", "Paraboloid Diagonal", "Penalty Function I", "Polynomial", "Powell", "Extended Powell", "Trigonometric", "Himmelblau", "Rosenbrock", "Extended Rosenbrock", "Quadratic Diagonal", "Beale", "Fletcher-Powell", "Exponential", ) run_optim_tests(Adam(); skip = skip, show_name = debug_printing) end @testset "AdaMax" begin f(x) = x[1]^4 function g!(storage, x) storage[1] = 4 * x[1]^3 return end initial_x = [1.0] options = Optim.Options(show_trace = debug_printing, allow_f_increases=true, iterations=100_000) results = Optim.optimize(f, g!, initial_x, AdaMax(), options) @test norm(Optim.minimum(results)) < 1e-6 @test summary(results) == "AdaMax" # TODO: Check why skip problems fail skip = ("Trigonometric", "Large Polynomial", "Parabola", "Paraboloid Random Matrix", "Paraboloid Diagonal", "Extended Rosenbrock", "Penalty Function I", "Beale", "Extended Powell", "Himmelblau", "Large Polynomial", "Polynomial", "Powell", "Exponential", ) run_optim_tests(AdaMax(); skip = skip, show_name=debug_printing, iteration_exceptions = (("Trigonometric", 1_000_000,),)) end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
330
@testset "BFGS" begin # Trigonometric gets stuck in a local minimum? skip = ("Trigonometric",) run_optim_tests(BFGS(); convergence_exceptions = (("Polynomial",1),), f_increase_exceptions = ("Extended Rosenbrock",), skip=skip, show_name = debug_printing) end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
2162
@testset "Conjugate Gradient" begin # TODO: Investigate the exceptions (could be they just need more iterations?) # Test Optim.cg for all differentiable functions in MultivariateProblems.UnconstrainedProblems.examples # Trigonometric gets stuck in a local minimum? skip = ("Trigonometric", "Extended Powell") run_optim_tests(ConjugateGradient(), skip=skip, convergence_exceptions = (("Powell", 1), ("Powell", 2), ("Polynomial", 1), ("Extended Rosenbrock", 1), ("Extended Powell", 1), ("Extended Powell", 2)), minimum_exceptions = (("Paraboloid Diagonal", 1)), minimizer_exceptions = (("Paraboloid Diagonal", 1), ("Extended Powell", 1), ("Extended Powell", 2)), f_increase_exceptions = (("Hosaki"),), iteration_exceptions = (("Paraboloid Diagonal", 10000),), show_name = debug_printing) @testset "matrix input" begin cg_objective(X, B) = sum(abs2, X .- B)/2 function cg_objective_gradient!(G, X, B) for i = 1:length(G) G[i] = X[i]-B[i] end end Random.seed!(1) B = rand(2,2) results = Optim.optimize(X -> cg_objective(X, B), (G, X) -> cg_objective_gradient!(G, X, B), rand(2,2), ConjugateGradient()) @test Optim.converged(results) @test Optim.minimum(results) < 1e-8 end @testset "Undefined beta_k behaviour" begin # Ref #669 # If y_k is zero, then betak is undefined. # Check that we don't produce NaNs f(x) = 100 - x[1] + exp(x[1] - 100) g!(grad, x) = grad[1] = -1 + exp(x[1] - 100) res = optimize(f, g!, [0.0], ConjugateGradient(alphaguess=LineSearches.InitialStatic(alpha=1.0), linesearch=LineSearches.BackTracking())) @test Optim.converged(res) @test Optim.minimum(res) ≈ 1.0 end end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
2053
@testset "Gradient Descent" begin run_optim_tests(GradientDescent(), skip = ("Trigonometric", "Powell", "Extended Powell", "Paraboloid Random Matrix",), f_increase_exceptions = ("Hosaki",), convergence_exceptions = (("Polynomial", 1), ("Polynomial", 2), ("Rosenbrock", 1), ("Rosenbrock", 2), ("Extended Rosenbrock", 1), ("Extended Rosenbrock", 2), ("Penalty Function I", 1), ("Penalty Function I", 2)), iteration_exceptions = (("Rosenbrock", 10000), ("Extended Rosenbrock", 12000), ("Fletcher-Powell", 10000), ("Paraboloid Diagonal", 10000), # ("Paraboloid Random Matrix", 20000), should be seeded ("Penalty Function I", 10000),), show_name = debug_printing) function f_gd_1(x) (x[1] - 5.0)^2 end function g_gd_1(storage, x) storage[1] = 2.0 * (x[1] - 5.0) end initial_x = [0.0] d = OnceDifferentiable(f_gd_1, g_gd_1, initial_x) results = Optim.optimize(d, initial_x, GradientDescent()) @test_throws ErrorException Optim.x_trace(results) @test Optim.g_converged(results) @test norm(Optim.minimizer(results) - [5.0]) < 0.01 @test summary(results) == "Gradient Descent" eta = 0.9 function f_gd_2(x) (1.0 / 2.0) * (x[1]^2 + eta * x[2]^2) end function g_gd_2(storage, x) storage[1] = x[1] storage[2] = eta * x[2] end d = OnceDifferentiable(f_gd_2, g_gd_2, [1.0, 1.0]) results = Optim.optimize(d, [1.0, 1.0], GradientDescent()) @test_throws ErrorException Optim.x_trace(results) @test Optim.g_converged(results) @test norm(Optim.minimizer(results) - [0.0, 0.0]) < 0.01 end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
514
@testset "L-BFGS" begin # Trigonometric gets stuck in a local minimum? skip = ("Trigonometric",) if Sys.WORD_SIZE == 32 iteration_exceptions = (("Extended Powell", 2000),) else iteration_exceptions = () end run_optim_tests(LBFGS(), f_increase_exceptions = ("Extended Rosenbrock",), skip=skip, iteration_exceptions = iteration_exceptions, show_name = debug_printing, ) end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
1061
@testset "Momentum Gradient Descent" begin # TODO: check the skips and exceptions, maybe it's enough to increase number of iterations? skip = ("Rosenbrock", "Extended Powell", "Extended Rosenbrock", "Trigonometric", "Penalty Function I", "Beale","Paraboloid Random Matrix") run_optim_tests(MomentumGradientDescent(), skip = skip, convergence_exceptions = (("Large Polynomial",1), ("Himmelblau",1), ("Fletcher-Powell", 1),("Fletcher-Powell", 2), ("Powell", 1)), minimum_exceptions = (("Large Polynomial", 1), ("Large Polynomial", 2)), iteration_exceptions = (("Paraboloid Diagonal", 10000), ("Powell", 10000)), f_increase_exceptions = ("Exponential", "Polynomial", "Paraboloid Random Matrix", "Hosaki"), show_name = debug_printing) end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
5790
using Optim, Test ## REMEMBER TO UPDATE TESTS FOR BOTH THE N-GMRES and the O-ACCEL TEST SETS @testset "N-GMRES" begin method = NGMRES solver = method() skip = ("Trigonometric", ) run_optim_tests(solver; skip = skip, iteration_exceptions = (("Penalty Function I", 10000), ("Paraboloid Random Matrix", 10000)), show_name = debug_printing) # Specialized tests prob = MVP.UnconstrainedProblems.examples["Rosenbrock"] df = OnceDifferentiable(MVP.objective(prob), MVP.gradient(prob), prob.initial_x) @test solver.nlpreconopts.iterations == 1 @test solver.nlpreconopts.allow_f_increases == true defopts = Optim.default_options(solver) @test defopts == (; allow_f_increases = true) state = Optim.initial_state(solver, Optim.Options(;defopts...), df, prob.initial_x) @test state.x === state.nlpreconstate.x @test state.x_previous === state.nlpreconstate.x_previous @test size(state.X) == (length(state.x), solver.wmax) @test size(state.R) == (length(state.x), solver.wmax) @test size(state.Q) == (solver.wmax, solver.wmax) @test size(state.ξ) == (solver.wmax,) @test state.curw == 1 @test size(state.A) == (solver.wmax, solver.wmax) @test length(state.b) == solver.wmax @test length(state.xA) == length(state.x) # Test that tracing doesn't throw errors res = optimize(df, prob.initial_x, solver, Optim.Options(extended_trace=true, store_trace=true; defopts...)) @test Optim.converged(res) # The bounds are due to different systems behaving differently # TODO: is it a bad idea to hardcode these? @test 64 < Optim.iterations(res) < 100 @test 234 < Optim.f_calls(res) < 310 @test 234 < Optim.g_calls(res) < 310 @test Optim.minimum(res) < 1e-10 @test_throws AssertionError method(manifold=Optim.Sphere(), nlprecon = GradientDescent()) for nlprec in (LBFGS, BFGS) solver = method(nlprecon=nlprec()) clear!(df) res = optimize(df, prob.initial_x, solver) if !Optim.converged(res) display(res) end @test Optim.converged(res) @test Optim.minimum(res) < 1e-10 end # O-ACCEL handles the InitialConstantChange functionality in a special way, # so we should test that it works well. for nlprec in (GradientDescent(), GradientDescent(alphaguess = LineSearches.InitialConstantChange())) solver = method(nlprecon = nlprec, alphaguess = LineSearches.InitialConstantChange()) clear!(df) res = optimize(df, prob.initial_x, solver) if !Optim.converged(res) display(res) end @test Optim.converged(res) @test Optim.minimum(res) < 1e-10 end end @testset "O-ACCEL" begin method = OACCEL solver = method() skip = ("Trigonometric", ) run_optim_tests(solver; skip = skip, iteration_exceptions = (("Penalty Function I", 10000), ), show_name = debug_printing) prob = MVP.UnconstrainedProblems.examples["Rosenbrock"] df = OnceDifferentiable(MVP.objective(prob), MVP.gradient(prob), prob.initial_x) @test solver.nlpreconopts.iterations == 1 @test solver.nlpreconopts.allow_f_increases == true defopts = Optim.default_options(solver) @test defopts == (;allow_f_increases = true) state = Optim.initial_state(solver, Optim.Options(;defopts...), df, prob.initial_x) @test state.x === state.nlpreconstate.x @test state.x_previous === state.nlpreconstate.x_previous @test size(state.X) == (length(state.x), solver.wmax) @test size(state.R) == (length(state.x), solver.wmax) @test size(state.Q) == (solver.wmax, solver.wmax) @test size(state.ξ) == (solver.wmax, 2) @test state.curw == 1 @test size(state.A) == (solver.wmax, solver.wmax) @test length(state.b) == solver.wmax @test length(state.xA) == length(state.x) # Test that tracing doesn't throw errors res = optimize(df, prob.initial_x, solver, Optim.Options(extended_trace=true, store_trace=true; defopts...)) @test Optim.converged(res) # The bounds are due to different systems behaving differently # TODO: is it a bad idea to hardcode these? @test 72 < Optim.iterations(res) < 100 @test 245 < Optim.f_calls(res) < 310 @test 245 < Optim.g_calls(res) < 310 @test Optim.minimum(res) < 1e-10 @test_throws AssertionError method(manifold=Optim.Sphere(), nlprecon = GradientDescent()) for nlprec in (LBFGS, BFGS) solver = method(nlprecon=nlprec()) clear!(df) res = optimize(df, prob.initial_x, solver) if !Optim.converged(res) display(res) end @test Optim.converged(res) @test Optim.minimum(res) < 1e-10 end # O-ACCEL handles the InitialConstantChange functionality in a special way, # so we should test that it works well. for nlprec in (GradientDescent(), GradientDescent(alphaguess = LineSearches.InitialConstantChange())) solver = method(nlprecon = nlprec, alphaguess = LineSearches.InitialConstantChange()) clear!(df) res = optimize(df, prob.initial_x, solver) if !Optim.converged(res) display(res) end @test Optim.converged(res) @test Optim.minimum(res) < 1e-10 end end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
2223
@testset "Krylov Trust Region" begin @testset "Toy test problem 1" begin # Test on actual optimization problems. function f(x::Vector) (x[1] - 5.0)^4 end function fg!(g, x) g[1] = 4.0 * (x[1] - 5.0)^3 f(x) end function fg2!(_f, g, x) g === nothing || (g[1] = 4.0 * (x[1] - 5.0)^3) _f === nothing || return f(x) end function hv!(Hv, x, v) Hv[1] = 12.0 * (x[1] - 5.0)^2 * v[1] end d = Optim.TwiceDifferentiableHV(f, fg!, hv!, [0.0]) d2 = Optim.TwiceDifferentiableHV(NLSolversBase.only_fg_and_hv!(fg2!, hv!), [0.0]) result = Optim.optimize(d, [0.0], Optim.KrylovTrustRegion()) @test norm(Optim.minimizer(result) - [5.0]) < 0.01 result = Optim.optimize(d2, [0.0], Optim.KrylovTrustRegion()) @test norm(Optim.minimizer(result) - [5.0]) < 0.01 end @testset "Toy test problem 2" begin eta = 0.9 function f2(x::Vector) 0.5 * (x[1]^2 + eta * x[2]^2) end function fg2!(storage::Vector, x::Vector) storage[:] = [x[1], eta * x[2]] f2(x) end function hv2!(Hv::Vector, x::Vector, v::Vector) Hv[:] = [1.0 0.0; 0.0 eta] * v end d2 = Optim.TwiceDifferentiableHV(f2, fg2!, hv2!, Float64[127, 921]) result = Optim.optimize(d2, Float64[127, 921], Optim.KrylovTrustRegion()) @test result.g_converged @test norm(Optim.minimizer(result) - [0.0, 0.0]) < 0.01 end @testset "Stock test problems" begin for (name, prob) in MultivariateProblems.UnconstrainedProblems.examples if prob.istwicedifferentiable hv!(storage::Vector, x::Vector, v::Vector) = begin n = length(x) H = Matrix{Float64}(undef, n, n) MVP.hessian(prob)(H, x) storage .= H * v end fg!(g::Vector, x::Vector) = begin MVP.gradient(prob)(g,x) MVP.objective(prob)(x) end ddf = Optim.TwiceDifferentiableHV(MVP.objective(prob), fg!, hv!, prob.initial_x) result = Optim.optimize(ddf, prob.initial_x, Optim.KrylovTrustRegion()) @test norm(Optim.minimizer(result) - prob.solutions) < 1e-2 end end end end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
1872
@testset "Newton" begin function f_1(x::Vector) (x[1] - 5.0)^4 end function g!_1(storage::Vector, x::Vector) storage[1] = 4.0 * (x[1] - 5.0)^3 end function h!_1(storage::Matrix, x::Vector) storage[1, 1] = 12.0 * (x[1] - 5.0)^2 end initial_x = [0.0] Optim.optimize(NonDifferentiable(f_1, initial_x), [0.0], Newton()) Optim.optimize(OnceDifferentiable(f_1, g!_1, initial_x), [0.0], Newton()) options = Optim.Options(store_trace = false, show_trace = false, extended_trace = true) results = Optim.optimize(f_1, g!_1, h!_1, [0.0], Newton(), options) @test_throws ErrorException Optim.x_trace(results) @test Optim.g_converged(results) @test norm(Optim.minimizer(results) - [5.0]) < 0.01 eta = 0.9 function f_2(x::Vector) (1.0 / 2.0) * (x[1]^2 + eta * x[2]^2) end function g!_2(storage::Vector, x::Vector) storage[1] = x[1] storage[2] = eta * x[2] end function h!_2(storage::Matrix, x::Vector) storage[1, 1] = 1.0 storage[1, 2] = 0.0 storage[2, 1] = 0.0 storage[2, 2] = eta end results = Optim.optimize(f_2, g!_2, h!_2, [127.0, 921.0], Newton()) @test_throws ErrorException Optim.x_trace(results) @test Optim.g_converged(results) @test norm(Optim.minimizer(results) - [0.0, 0.0]) < 0.01 @test summary(results) == "Newton's Method" @testset "newton in concave region" begin prob=MultivariateProblems.UnconstrainedProblems.examples["Himmelblau"] res = optimize(MVP.objective(prob), MVP.gradient(prob), MVP.hessian(prob), [0., 0.], Newton()) @test norm(Optim.minimizer(res) - prob.solutions) < 1e-9 end @testset "Optim problems" begin run_optim_tests(Newton(); skip = ("Trigonometric",), show_name = debug_printing) end end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
7008
using Optim, Test, Distributions, Random, LinearAlgebra @testset "Newton Trust Region" begin @testset "Subproblems I" begin # verify that solve_tr_subproblem! finds the minimum n = 2 gr = [-0.74637,0.52388] H = [0.945787 -3.07884; -3.07884 -1.27762] s = zeros(n) m, interior = Optim.solve_tr_subproblem!(gr, H, 1., s, max_iters=100) for j in 1:10 bad_s = rand(n) bad_s ./= norm(bad_s) # boundary model(s2) = (gr' * s2)[] + .5 * (s2' * H * s2)[] @test model(s) <= model(bad_s) + 1e-8 end end @testset "Subproblems II" begin # random Hessians--verify that solve_tr_subproblem! finds the minimum for i in 1:10000 n = rand(1:10) gr = randn(n) H = randn(n, n) H += H' s = zeros(n) m, interior = Optim.solve_tr_subproblem!(gr, H, 1., s, max_iters=100) model(s2) = (gr' * s2) + .5 * (s2' * H * s2) @test model(s) <= model(zeros(n)) + 1e-8 # origin for j in 1:10 bad_s = rand(n) bad_s ./= norm(bad_s) # boundary @test model(s) <= model(bad_s) + 1e-8 bad_s .*= rand() # interior @test model(s) <= model(bad_s) + 1e-8 end end end @testset "Test problems" begin ####################################### # First test the subproblem. Random.seed!(42) n = 5 H = rand(n, n) H = H' * H + 4 * I H_eig = eigen(H) U = H_eig.vectors gr = zeros(n) gr[1] = 1. s = zeros(Float64, n) true_s = -H \ gr s_norm2 = dot(true_s, true_s) true_m = dot(true_s, gr) + 0.5 * dot(true_s, H * true_s) # An interior solution delta = sqrt(s_norm2) + 1.0 m, interior, lambda, hard_case, reached_solution = Optim.solve_tr_subproblem!(gr, H, delta, s) @test interior @test !hard_case @test reached_solution @test abs(m - true_m) < 1e-12 @test norm(s - true_s) < 1e-12 @test abs(lambda) < 1e-12 # A boundary solution delta = 0.5 * sqrt(s_norm2) m, interior, lambda, hard_case, reached_solution = Optim.solve_tr_subproblem!(gr, H, delta, s) @test !interior @test !hard_case @test reached_solution @test m > true_m @test abs(norm(s) - delta) < 1e-12 @test lambda > 0 # A "hard case" where the gradient is orthogonal to the lowest eigenvector # Test the checking hard_case, lambda_index = Optim.check_hard_case_candidate([-1., 2., 3.], [0., 1., 1.]) @test hard_case @test lambda_index == 2 hard_case, lambda_index = Optim.check_hard_case_candidate([-1., -1., 3.], [0., 0., 1.]) @test hard_case @test lambda_index == 3 hard_case, lambda_index = Optim.check_hard_case_candidate([-1., -1., -1.], [0., 0., 0.]) @test hard_case @test lambda_index == 4 hard_case, lambda_index = Optim.check_hard_case_candidate([1., 2., 3.], [0., 1., 1.]) @test !hard_case hard_case, lambda_index = Optim.check_hard_case_candidate([-1., -1., -1.], [0., 0., 1.]) @test !hard_case hard_case, lambda_index = Optim.check_hard_case_candidate([-1., 2., 3.], [1., 1., 1.]) @test !hard_case # Now check an actual hard case problem L = fill(0.1, n) L[1] = -1. H = U * Matrix(Diagonal(L)) * U' H = 0.5 * (H' + H) @test issymmetric(H) gr = U[:,2][:] @test abs(dot(gr, U[:,1][:])) < 1e-12 true_s = -H \ gr s_norm2 = dot(true_s, true_s) true_m = dot(true_s, gr) + 0.5 * dot(true_s, H * true_s) delta = 0.5 * sqrt(s_norm2) m, interior, lambda, hard_case, reached_solution = Optim.solve_tr_subproblem!(gr, H, delta, s) @test !interior @test hard_case @test reached_solution @test abs(lambda + L[1]) < 1e-4 @test abs(norm(s) - delta) < 1e-12 ####################################### # Next, test on actual optimization problems. function f(x::Vector) (x[1] - 5.0)^4 end function g!(storage::Vector, x::Vector) storage[1] = 4.0 * (x[1] - 5.0)^3 end function h!(storage::Matrix, x::Vector) storage[1, 1] = 12.0 * (x[1] - 5.0)^2 end d = TwiceDifferentiable(f, g!, h!, [0.0,]) options = Optim.Options(store_trace = false, show_trace = false, extended_trace = true) results = Optim.optimize(d, [0.0], NewtonTrustRegion(), options) @test_throws ErrorException Optim.x_trace(results) @test length(results.trace) == 0 @test results.g_converged @test norm(Optim.minimizer(results) - [5.0]) < 0.01 @test summary(results) == "Newton's Method (Trust Region)" eta = 0.9 function f_2(x::Vector) 0.5 * (x[1]^2 + eta * x[2]^2) end function g!_2(storage::Vector, x::Vector) storage[1] = x[1] storage[2] = eta * x[2] end function h!_2(storage::Matrix, x::Vector) storage[1, 1] = 1.0 storage[1, 2] = 0.0 storage[2, 1] = 0.0 storage[2, 2] = eta end d = TwiceDifferentiable(f_2, g!_2, h!_2, Float64[127, 921]) results = Optim.optimize(d, Float64[127, 921], NewtonTrustRegion()) @test results.g_converged @test norm(Optim.minimizer(results) - [0.0, 0.0]) < 0.01 # Test Optim.newton for all twice differentiable functions in # MultivariateProblems.UnconstrainedProblems.examples @testset "Optim problems" begin run_optim_tests(NewtonTrustRegion(); skip = ("Trigonometric", ), show_name = debug_printing) end end @testset "PR #341" begin # verify that no PosDef exception is thrown Optim.solve_tr_subproblem!([0, 1.], [-1000 0; 0. -999], 1e-2, ones(2)) end @testset "Handle Inf without erroring" begin o = optimize(TwiceDifferentiable(t -> rand(), (g, t)->(g.=t.+10), (h,t)->NaN*t*t',ones(10)), ones(10), NewtonTrustRegion()) @test !(o.f_converged || o.g_converged || o.x_converged) end @testset "delta_min" begin c = (t, Δ, D, ke) -> t < Δ ? -(exp(-ke*t) - 1)*D/(ke*Δ) : -(exp(-ke*Δ) - 1)*D/(ke*Δ)*exp(-ke*(t-Δ)) ke₀ = 0.5 D₀ = 100.0 t₁ = 2.0 ll = Δ -> begin sum( map( zip( [0.5, 0.75, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 8.0], [19.90278833504542, 29.50697731718643, 42.106713695572836, 60.402701110755814, 72.78413106065605, 48.58414814304506, 36.134598474160484, 24.137636435583193, 3.2819695104173814] ) ) do (t,y) ct = c(t, Δ, D₀, ke₀) return logpdf(Normal(ct, ct*0.1), y) end ) end @test_throws DomainError Optim.optimize(t -> -ll(t[1]), [2.1], NewtonTrustRegion(delta_min=-1.0), Optim.Options(show_trace = false, allow_f_increases = false, g_tol = 1e-5)) Optim.optimize(t -> -ll(t[1]), [2.1], NewtonTrustRegion(delta_min=0.0), Optim.Options( show_trace = false, allow_f_increases = false, g_tol = 1e-5)) end end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
222
@testset "Grid Search" begin @test Optim.grid_search(x -> (1.0 - x)^2, [-1:0.1:1.0;]) == 1 end # Cartesian product over 2 dimensions. #grid_search(x -> (1.0 - x[1])^2 + (2.0 - x[2])^2, product[-1:0.1:1.0, -1:0.1:1.0])
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
1088
@testset "Nelder Mead" begin # Test Optim.nelder_mead for all functions except Large Polynomials in MultivariateProblems.UnconstrainedProblems.examples skip = ("Large Polynomial", "Extended Powell", "Quadratic Diagonal", "Extended Rosenbrock", "Paraboloid Diagonal", "Paraboloid Random Matrix", "Trigonometric", "Penalty Function I",) run_optim_tests(NelderMead(), convergence_exceptions = (("Powell", 1)), minimum_exceptions = (("Exponential", 1), ("Exponential", 2)), skip = skip, show_name = debug_printing) # Test if the trace is correctly stored. prob = MultivariateProblems.UnconstrainedProblems.examples["Rosenbrock"] res = Optim.optimize(MVP.objective(prob), prob.initial_x, method = NelderMead(), store_trace = true, extended_trace=true) @test ( length(unique(Optim.g_norm_trace(res))) != 1 || length(unique(Optim.f_trace(res))) != 1 ) && issorted(Optim.f_trace(res)[end:1]) @test !(res.trace[1].metadata["centroid"] === res.trace[end].metadata["centroid"]) end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
1288
@testset "Particle Swarm" begin # TODO: Run on MultivariateProblems.UnconstrainedProblems? Random.seed!(100) function f_s(x::Vector) (x[1] - 5.0)^4 end function rosenbrock_s(x::Vector) (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2 end initial_x = [0.0] upper = [100.0] lower = [-100.0] n_particles = 4 options = Optim.Options(iterations=100) res = Optim.optimize(f_s, initial_x, ParticleSwarm(lower, upper, n_particles), options) @test norm(Optim.minimizer(res) - [5.0]) < 0.1 initial_x = [0.0, 0.0] lower = [-20., -20.] upper = [20., 20.] n_particles = 5 options = Optim.Options(iterations=300) res = Optim.optimize(rosenbrock_s, initial_x, ParticleSwarm(lower, upper, n_particles), options) @test norm(Optim.minimizer(res) - [1.0, 1.0]) < 0.1 options = Optim.Options(iterations=300, show_trace=true, extended_trace=true, store_trace=true) res = Optim.optimize(rosenbrock_s, initial_x, ParticleSwarm(lower, upper, n_particles), options) @test summary(res) == "Particle Swarm" res = Optim.optimize(rosenbrock_s, initial_x, ParticleSwarm(n_particles = n_particles), options) @test summary(res) == "Particle Swarm" end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
773
@testset "Simulated Annealing" begin Random.seed!(1) function f_s(x::Vector) (x[1] - 5.0)^4 end options = Optim.Options(iterations=100_000) results = Optim.optimize(f_s, [0.0], SimulatedAnnealing(), options) @test norm(Optim.minimizer(results) - [5.0]) < 0.1 function rosenbrock_s(x::Vector) (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2 end options = Optim.Options(iterations=100_000) results = Optim.optimize(rosenbrock_s, [0.0, 0.0], SimulatedAnnealing(), options) @test norm(Optim.minimizer(results) - [1.0, 1.0]) < 0.1 options = Optim.Options(iterations=10, show_trace=true, store_trace=true, extended_trace=true) results = Optim.optimize(rosenbrock_s, [0.0, 0.0], SimulatedAnnealing(), options) end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
374
@testset "bigfloat initial convergence #720" begin f(x) = x[1]^2 x0 = BigFloat[0] obj = OnceDifferentiable(f, x0; autodiff=:forward) for method in (GradientDescent, BFGS, LBFGS, AcceleratedGradientDescent, MomentumGradientDescent, ConjugateGradient, Newton, NewtonTrustRegion, SimulatedAnnealing) result = Optim.optimize(f, x0, method()) end end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
185
@testset "Dual numbers" begin f(x,y) = x[1]^2+y[1]^2 g(param) = Optim.minimum(optimize(x->f(x,param), -1,1)) @test Optim.NLSolversBase.ForwardDiff.gradient(g, [1.0]) == [2.0] end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
379
@testset "#853" begin "Model parameter" struct yObj p end "Univariable Functor" function (s::yObj)(x) return x*s.p end "Multivariable Functor with array input" function (s::yObj)(x_v) return x_v[1]*s.p end model = yObj(1.0) Optim.optimize(model, -1, 2, [1.]) # already worked Optim.optimize(model, -1, 2) # didn't work Optim.optimize(model, -1., 2.) # didn't work end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
654
@testset "optimize" begin # Tests for PR #302 results = optimize(cos, 0, 2pi); @test norm(Optim.minimizer(results) - pi) < 0.01 results = optimize(cos, 0.0, 2pi); @test norm(Optim.minimizer(results) - pi) < 0.01 results = optimize(cos, 0, 2pi, Brent()); @test norm(Optim.minimizer(results) - pi) < 0.01 results = optimize(cos, 0.0, 2pi, Brent()); @test norm(Optim.minimizer(results) - pi) < 0.01 results = optimize(cos, 0, 2pi, method = Brent()); @test norm(Optim.minimizer(results) - pi) < 0.01 results = optimize(cos, 0.0, 2pi, method = Brent()); @test norm(Optim.minimizer(results) - pi) < 0.01 end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
1230
@testset "Brent's Method" begin for (name, prob) in OptimTestProblems.UnivariateProblems.examples for T in (Float64, BigFloat) results = optimize(prob.f, convert(Array{T}, prob.bounds)..., method = Brent()) @test Optim.converged(results) @test norm(Optim.minimizer(results) .- prob.minimizers) < 1e-7 end end ## corner cases - empty and zero-width brackets result = optimize(sqrt, 4.0, 4.0, method = Brent()) @test Optim.converged(result) @test Optim.minimizer(result) == 4.0 @test Optim.minimum(result) == 2.0 @test_throws ErrorException optimize(identity, 2.0, 1.0, Brent()) @test summary(result) == "Brent's Method" ## corner cases - largely flat functions result = optimize(x->sign(x), -2, 2) @test Optim.converged(result) @test Optim.minimum(result) == -1.0 result = optimize(x->sign(x), -1, 2) @test Optim.converged(result) @test Optim.minimum(result) == -1.0 result = optimize(x->sign(x), -2, 1) @test Optim.converged(result) @test Optim.minimum(result) == -1.0 result = Optim.optimize(x->sin(x), 0, 2π, Optim.Brent(); abs_tol=1e-4, store_trace=false, show_trace=true, iterations=2) end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
code
856
@testset "Golden Section" begin for (name, prob) in OptimTestProblems.UnivariateProblems.examples for T in (Float64, BigFloat) results = optimize(prob.f, convert(Array{T}, prob.bounds)..., method = GoldenSection()) @test Optim.converged(results) @test norm(Optim.minimizer(results) .- prob.minimizers) < 1e-7 end end ## corner cases - empty and zero-width brackets result = optimize(sqrt, 4.0, 4.0, method = GoldenSection()) @test Optim.converged(result) @test Optim.minimizer(result) == 4.0 @test Optim.minimum(result) == 2.0 @test_throws ErrorException optimize(identity, 2.0, 1.0, GoldenSection()) result = Optim.optimize(x->sin(x), 0, 2π, Optim.GoldenSection(); abs_tol=1e-4, store_trace=false, show_trace=true, iterations=2) end
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
1213
# Notes for Optim Contributors Welcome to Optim.jl, and thanks for showing an interest in our package. ## Before filing an issue Reporting a potential bug? Please be sure to include a [Minimal Working Example](https://en.wikipedia.org/wiki/Minimal_Working_Example) so the other contributors can get right at solving your issue. Including the version of Optim.jl you have installed and the exact version of Julia you are using is encouraged as well. ## Contributing code Contributing code? We welcome all bug fixes, documentation, and new features. However, before you spend several weeks learning all the kinks and corners of Optim.jl to contribute a new algorithm, it is adviced to reach out via an issue or through [gitter](https://gitter.im/JuliaNLSolvers/Optim.jl) to gauge the interest. While we want to provide as many good solvers to the end-users, we need to think about the over-all fit of the algorithm for Optim.jl, and the possibility of maintaining the extra code. If you want to contribute, but you don't have any ideas for a PR, feel free to take a look at the issues labelled [help wanted](https://github.com/JuliaNLSolvers/Optim.jl/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22).
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
4340
# Optim master release notes * Fix Preconditioning example for v1.0 syntax * Improve handling of alternative number types in univariate optimization * Add conditional likelihood example to docs * Improve Fminbox trace printing. # Optim v0.17.2 release notes * Fix some typos * Fix doc building # Optim v0.17.0 release notes * Drop support for Julia versions less 1.0. Optim v.17.1 is also out. # Optim v0.11.0 release notes * Optional scaling for inverse Hessian in L-BFGS * Support for initial step length guesses via LineSearches # Optim v0.10.0 release notes * Support for optimization on Riemannian manifolds * Support for optimization of functions of complex variables * New experimental KrylovTrustRegion method useful when cheap Hessian-vector products are available. * Improved support for BigFloats * Add doc strings to methods * Drop support for Julia versions less than v0.6.0-pre # Optim v0.9.0 release notes * Fminbox: If an initial guess is on the boundary of the box, the guess is moved inside the box and a warning is produced, as opposed to crashing with an error. * Significant changes to the Non-, Once-, and TwiceDifferentiable setup; these now hold temporaries relevant to the evaluation of objectives, gradients, and Hessians. They also hold f-, g-, and h_calls counters. * Refactor tests * Drop v0.4 support * Add limits to f-, g-, and h_calls * Improve trace for univariate optimization * Changed order of storage arrays and evaluation point arrays in gradient and Hessian calls * Skip v0.8.0 to allow fixes on Julia v0.5.0 # Optim v0.7.6 release notes * Fix deprecations for *Function constructors * Fix depwarns on Julia master (v0.6) * Update references to new JuliaNLSolvers home for Optim+family # Optim v0.7.5 release notes * Various bug fixes * Deprecate DifferentiableFunction, TwiceDifferentiable in favor of OnceDifferentiable, TwiceDifferentiable * widen some type annotations (e.g. allow for multidimensional arrays as inputs again) * introduce allow_f_increases keyword in Optim.Options to allow objective to increase between iterations * New option in Optim.Options: allow_f_increases. Defaults to false, but if set to true, the solver will not stop even if a step leads to an increase in the objective. * Newton and BFGS: set initial step length to one. See [328](https://github.com/JuliaOpt/Optim.jl/pull/328). # Optim v0.7.3 release notes * OptimizationOptions is now unexported, and has been renamed to Options. Must be accessed as Optim.Options as a result. * Bug fixes to Nelder-Mead tracing. * Keywords with ! in them have been deprecated to version without. For example, linesearch! -> linesearch. * Failures in a line search now terminates the optimization with a warning and status of non-convergence. The results can still be accessed, but `minimizer(res)` will not represent a local minimum. See [275](https://github.com/JuliaOpt/Optim.jl/pull/275). # Optim v0.7.0 release notes * Refactor code internally to clean up code and allow more flexible use Optim * Switch to new (v.0.3) ForwardDiff * Make minimizer/minimum transition final * Fix dispatch bug for univariate optimization. * The line search functionality has been separated into a new package [LineSearches.jl](https://github.com/anriseth/LineSearches.jl), see [277](https://github.com/JuliaOpt/Optim.jl/pull/277). * Make move to minimizer (the argmin) and minimum (objective at argmin) final: field names are now in sync with function based API. # Optim v0.6.1 release notes * Assess convergence in *g* before iterating to avoid line search errors if `initial_x` is a stationary point * Fix trace bug in LevenbergMarquardt. * Add ForwardDiff AD functionality to NewtonTrustRegion * Make documentation even more noticable in README.md # Optim v0.6.0 release notes * Various bug fixes * Added box constraints to Levenberg Marquardt * Changed old solver: Nelder-Mead w/ Adaptive parameters * Julia v0.5 deprecation fixes * Added NewtonTrustRegion solver [238](https://github.com/JuliaOpt/Optim.jl/pull/238) [245](https://github.com/JuliaOpt/Optim.jl/pull/245) * Added ParticleSwarm solver [218](https://github.com/JuliaOpt/Optim.jl/pull/218) * Added documentation generated by [Documenter.jl](https://github.com/JuliaDocs/Documenter.jl), see PR[225](https://github.com/JuliaOpt/Optim.jl/pull/225). * Added NEWS.md
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
5092
# Optim.jl [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://julianlsolvers.github.io/Optim.jl/stable) [![](https://img.shields.io/badge/docs-latest-blue.svg)](https://julianlsolvers.github.io/Optim.jl/dev) [![Build Status](https://github.com/JuliaNLSolvers/Optim.jl/actions/workflows/windows.yml/badge.svg)](https://github.com/JuliaNLSolvers/Optim.jl/actions/workflows/windows.yml) [![Build Status](https://github.com/JuliaNLSolvers/Optim.jl/actions/workflows/linux.yml/badge.svg)](https://github.com/JuliaNLSolvers/Optim.jl/actions/workflows/linux.yml) [![Build Status](https://github.com/JuliaNLSolvers/Optim.jl/actions/workflows/mac.yml/badge.svg)](https://github.com/JuliaNLSolvers/Optim.jl/actions/workflows/mac.yml) [![Codecov branch](https://img.shields.io/codecov/c/github/JuliaNLSolvers/Optim.jl/master.svg)](https://codecov.io/gh/JuliaNLSolvers/Optim.jl) [![JOSS](http://joss.theoj.org/papers/10.21105/joss.00615/status.svg)](https://doi.org/10.21105/joss.00615) Univariate and multivariate optimization in Julia. Optim.jl is part of the [JuliaNLSolvers](https://github.com/JuliaNLSolvers) family. ## Help and support For help and support, please post on the [Optimization (Mathematical)](https://discourse.julialang.org/c/domain/opt/13) section of the Julia discourse or the `#math-optimization` channel of the Julia [slack](https://julialang.org/slack/). ## Installation Install `Optim.jl` using the Julia package manager: ```julia import Pkg Pkg.add("Optim") ``` ## Documentation The online documentation is available at [https://julianlsolvers.github.io/Optim.jl/stable](https://julianlsolvers.github.io/Optim.jl/stable). ## Example To minimize the [Rosenbrock function](https://en.wikipedia.org/wiki/Rosenbrock_function), do: ```julia julia> using Optim julia> rosenbrock(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2 rosenbrock (generic function with 1 method) julia> result = optimize(rosenbrock, zeros(2), BFGS()) * Status: success * Candidate solution Final objective value: 5.471433e-17 * Found with Algorithm: BFGS * Convergence measures |x - x'| = 3.47e-07 ≰ 0.0e+00 |x - x'|/|x'| = 3.47e-07 ≰ 0.0e+00 |f(x) - f(x')| = 6.59e-14 ≰ 0.0e+00 |f(x) - f(x')|/|f(x')| = 1.20e+03 ≰ 0.0e+00 |g(x)| = 2.33e-09 ≤ 1.0e-08 * Work counters Seconds run: 0 (vs limit Inf) Iterations: 16 f(x) calls: 53 ∇f(x) calls: 53 julia> Optim.minimizer(result) 2-element Vector{Float64}: 0.9999999926033423 0.9999999852005355 julia> Optim.minimum(result) 5.471432670590216e-17 ``` To get information on the keywords used to construct method instances, use the Julia REPL help prompt (`?`) ```julia help?> LBFGS search: LBFGS LBFGS ≡≡≡≡≡ Constructor =========== LBFGS(; m::Integer = 10, alphaguess = LineSearches.InitialStatic(), linesearch = LineSearches.HagerZhang(), P=nothing, precondprep = (P, x) -> nothing, manifold = Flat(), scaleinvH0::Bool = true && (typeof(P) <: Nothing)) LBFGS has two special keywords; the memory length m, and the scaleinvH0 flag. The memory length determines how many previous Hessian approximations to store. When scaleinvH0 == true, then the initial guess in the two-loop recursion to approximate the inverse Hessian is the scaled identity, as can be found in Nocedal and Wright (2nd edition) (sec. 7.2). In addition, LBFGS supports preconditioning via the P and precondprep keywords. Description =========== The LBFGS method implements the limited-memory BFGS algorithm as described in Nocedal and Wright (sec. 7.2, 2006) and original paper by Liu & Nocedal (1989). It is a quasi-Newton method that updates an approximation to the Hessian using past approximations as well as the gradient. References ========== • Wright, S. J. and J. Nocedal (2006), Numerical optimization, 2nd edition. Springer • Liu, D. C. and Nocedal, J. (1989). "On the Limited Memory Method for Large Scale Optimization". Mathematical Programming B. 45 (3): 503–528 ``` ## Use with JuMP You can use Optim.jl with [JuMP.jl](https://github.com/jump-dev/JuMP.jl) as follows: ```julia julia> using JuMP, Optim julia> model = Model(Optim.Optimizer); julia> set_optimizer_attribute(model, "method", BFGS()) julia> @variable(model, x[1:2]); julia> @objective(model, Min, (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2) (x[1]² - 2 x[1] + 1) + (100.0 * ((-x[1]² + x[2]) ^ 2.0)) julia> optimize!(model) julia> objective_value(model) 3.7218241804173566e-21 julia> value.(x) 2-element Vector{Float64}: 0.9999999999373603 0.99999999986862 ``` ## Citation If you use `Optim.jl` in your work, please cite the following: ```tex @article{mogensen2018optim, author = {Mogensen, Patrick Kofod and Riseth, Asbj{\o}rn Nilsen}, title = {Optim: A mathematical optimization package for {Julia}}, journal = {Journal of Open Source Software}, year = {2018}, volume = {3}, number = {24}, pages = {615}, doi = {10.21105/joss.00615} } ```
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
3588
# Optim.jl Univariate and multivariate optimization in Julia. Optim.jl is part of the [JuliaNLSolvers](https://github.com/JuliaNLSolvers) family. | **Source** | **Build Status** | **Social** | **References to cite** | |:-:|:-:|:-:|:-:| | [![Source](https://img.shields.io/badge/GitHub-source-green.svg)](https://github.com/JuliaNLSolvers/Optim.jl) | [![Build Status](https://travis-ci.org/JuliaNLSolvers/Optim.jl.svg?branch=master)](https://travis-ci.org/JuliaNLSolvers/Optim.jl) | [![](https://badges.gitter.im/JuliaNLSolvers/Optim.jl.svg)](https://gitter.im/JuliaNLSolvers/Optim.jl) | [![JOSS](http://joss.theoj.org/papers/10.21105/joss.00615/status.svg)](https://doi.org/10.21105/joss.00615) | | [![Codecov branch](https://img.shields.io/codecov/c/github/JuliaNLSolvers/Optim.jl/master.svg)](https://codecov.io/gh/JuliaNLSolvers/Optim.jl) |[![Build Status](https://ci.appveyor.com/api/projects/status/prp8ygfp4rr9tafe?svg=true)](https://ci.appveyor.com/project/blegat/optim-jl) | | [![DOI](https://zenodo.org/badge/3933868.svg)](https://zenodo.org/badge/latestdoi/3933868) | ## What Optim is a Julia package for optimizing functions of various kinds. While there is some support for box constrained and Riemannian optimization, most of the solvers try to find an ``x`` that minimizes a function ``f(x)`` without any constraints. Thus, the main focus is on unconstrained optimization. The provided solvers, under certain conditions, will converge to a local minimum. In the case where a global minimum is desired we supply some methods such as (bounded) simulated annealing and particle swarm. For a dedicated package for global optimization techniques, see e.g. [BlackBoxOptim](https://github.com/robertfeldt/BlackBoxOptim.jl). ## Why There are many solvers available from both free and commercial sources, and many of them are accessible from Julia. Few of them are written in Julia. Performance-wise this is rarely a problem, as they are often written in either Fortran or C. However, solvers written directly in Julia does come with some advantages. When writing Julia software (packages) that require something to be optimized, the programmer can either choose to write their own optimization routine, or use one of the many available solvers. For example, this could be something from the [NLopt](https://github.com/JuliaOpt/NLopt.jl) suite. This means adding a dependency which is not written in Julia, and more assumptions have to be made as to the environment the user is in. Does the user have the proper compilers? Is it possible to use GPL'ed code in the project? Optim is released under the MIT license, and installation is a simple `Pkg.add`, so it really doesn't get much freer, easier, and lightweight than that. It is also true, that using a solver written in C or Fortran makes it impossible to leverage one of the main benefits of Julia: multiple dispatch. Since Optim is entirely written in Julia, we can currently use the dispatch system to ease the use of custom preconditioners. A planned feature along these lines is to allow for user controlled choice of solvers for various steps in the algorithm, entirely based on dispatch, and not predefined possibilities chosen by the developers of Optim. Being a Julia package also means that Optim has access to the automatic differentiation features through the packages in [JuliaDiff](http://www.juliadiff.org/). ## How The package is a registered package, and can be installed with `Pkg.add`. ```julia julia> using Pkg; Pkg.add("Optim") ``` or through the `pkg` REPL mode by typing ``` ] add Optim ```
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
1319
# Adam and AdaMax This page contains information about Adam and AdaMax. Notice, that these algorithms do not use line search algorithms, so some tuning of `alpha` may be necessary to obtain sufficiently fast convergence on your specific problem. ## Constructors ```julia Adam(; alpha=0.0001, beta_mean=0.9, beta_var=0.999, epsilon=1e-8) ``` where `alpha` is the step length or learning parameter. `beta_mean` and `beta_var` are exponential decay parameters for the first and second moments estimates. Setting these closer to 0 will cause past iterates to matter less for the current steps and setting them closer to 1 means emphasizing past iterates more. `epsilon` should rarely be changed, and just exists to avoid a division by 0. ```julia AdaMax(; alpha=0.002, beta_mean=0.9, beta_var=0.999, epsilon=1e-8) ``` where `alpha` is the step length or learning parameter. `beta_mean` and `beta_var` are exponential decay parameters for the first and second moments estimates. Setting these closer to 0 will cause past iterates to matter less for the current steps and setting them closer to 1 means emphasizing past iterates more. ## References Kingma, Diederik P., and Jimmy Ba. "Adam: A method for stochastic optimization." arXiv preprint arXiv:1412.6980 (2014).
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
156
# Brent's Method ## Constructor ## Description ## Example ## References R. P. Brent (2002) Algorithms for Minimization Without Derivatives. Dover edition.
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
2826
# Conjugate Gradient Descent ## Constructor ```julia ConjugateGradient(; alphaguess = LineSearches.InitialHagerZhang(), linesearch = LineSearches.HagerZhang(), eta = 0.4, P = nothing, precondprep = (P, x) -> nothing) ``` ## Description The `ConjugateGradient` method implements Hager and Zhang (2006) and elements from Hager and Zhang (2013). Notice, that the default `linesearch` is `HagerZhang` from LineSearches.jl. This line search is exactly the one proposed in Hager and Zhang (2006). The constant ``eta`` is used in determining the next step direction, and the default here deviates from the one used in the original paper (``0.01``). It needs to be a strictly positive number. ## Example Let's optimize the 2D Rosenbrock function. The function and gradient are given by ``` f(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2 function g!(storage, x) storage[1] = -2.0 * (1.0 - x[1]) - 400.0 * (x[2] - x[1]^2) * x[1] storage[2] = 200.0 * (x[2] - x[1]^2) end ``` we can then try to optimize this function from `x=[0.0, 0.0]` ``` julia> optimize(f, g!, zeros(2), ConjugateGradient()) Results of Optimization Algorithm * Algorithm: Conjugate Gradient * Starting Point: [0.0,0.0] * Minimizer: [1.000000002262018,1.0000000045408348] * Minimum: 5.144946e-18 * Iterations: 21 * Convergence: true * |x - x'| ≤ 0.0e+00: false |x - x'| = 2.09e-10 * |f(x) - f(x')| ≤ 0.0e+00 |f(x)|: false |f(x) - f(x')| = 1.55e+00 |f(x)| * |g(x)| ≤ 1.0e-08: true |g(x)| = 3.36e-09 * stopped by an increasing objective: false * Reached Maximum Number of Iterations: false * Objective Calls: 54 * Gradient Calls: 39 ``` We can compare this to the default first order solver in Optim.jl ``` julia> optimize(f, g!, zeros(2)) Results of Optimization Algorithm * Algorithm: L-BFGS * Starting Point: [0.0,0.0] * Minimizer: [0.9999999999373614,0.999999999868622] * Minimum: 7.645684e-21 * Iterations: 16 * Convergence: true * |x - x'| ≤ 0.0e+00: false |x - x'| = 3.48e-07 * |f(x) - f(x')| ≤ 0.0e+00 |f(x)|: false |f(x) - f(x')| = 9.03e+06 |f(x)| * |g(x)| ≤ 1.0e-08: true |g(x)| = 2.32e-09 * stopped by an increasing objective: false * Reached Maximum Number of Iterations: false * Objective Calls: 53 * Gradient Calls: 53 ``` We see that for this objective and starting point, `ConjugateGradient()` requires fewer gradient evaluations to reach convergence. ## References - W. W. Hager and H. Zhang (2006) Algorithm 851: CG_DESCENT, a conjugate gradient method with guaranteed descent. ACM Transactions on Mathematical Software 32: 113-137. - W. W. Hager and H. Zhang (2013), The Limited Memory Conjugate Gradient Method. SIAM Journal on Optimization, 23, pp. 2150-2168.
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
4653
# Complex optimization Optimization of functions defined on complex inputs (``\mathbb{C}^n \to \mathbb{R}``) is supported by simply passing a complex ``x`` as input. The algorithms supported are all those which can naturally be extended to work with complex numbers: simulated annealing and all the first-order methods. The gradient of a complex-to-real function is defined as the only vector ``g`` such that ```math f(x+h) = f(x) + \mbox{Re}(g' * h) + \mathcal{O}(h^2). ``` This is sometimes written ```math g = \frac{df}{d(z*)} = \frac{df}{d(\mbox{Re}(z))} + i \frac{df}{d(\mbox{Im(z)})}. ``` The gradient of a ``\mathbb{C}^n \to \mathbb{R}`` function is a ``\mathbb{C}^n \to \mathbb{C}^n`` map. Even if it is differentiable when seen as a function of ``\mathbb{R}^{2n}`` to ``\mathbb{R}^{2n}``, it might not be complex-differentiable. For instance, take ``f(z) = \mbox{Re}(z)^2``. Then ``g(z) = 2 \mbox{Re}(z)``, which is not complex-differentiable (holomorphic). Therefore, the Hessian of a ``\mathbb{C}^n \to \mathbb{R}`` function is in general not well-defined as a ``n \times n`` complex matrix (only as a ``2n \times 2n`` real matrix), and therefore second-order optimization algorithms are not applicable directly. To use second-order optimization, convert to real variables. ## Examples We show how to minimize a quadratic plus quartic function with the `LBFGS` optimization algorithm. ```jl using Random Random.seed!(0) # Set the seed for reproducibility # μ is the strength of the quartic. μ = 0 is just a quadratic problem n = 4 A = randn(n,n) + im*randn(n,n) A = A'A + I b = randn(n) + im*randn(n) μ = 1.0 fcomplex(x) = real(dot(x,A*x)/2 - dot(b,x)) + μ*sum(abs.(x).^4) gcomplex(x) = A*x-b + 4μ*(abs.(x).^2).*x gcomplex!(stor,x) = copyto!(stor,gcomplex(x)) x0 = randn(n)+im*randn(n) res = optimize(fcomplex, gcomplex!, x0, LBFGS()) ``` The output of the optimization is ``` Results of Optimization Algorithm * Algorithm: L-BFGS * Starting Point: [0.48155603952425174 - 1.477880724921868im,-0.3219431528959694 - 0.18542418173298963im, ...] * Minimizer: [0.14163543901272568 - 0.034929496785515886im,-0.1208600058040362 - 0.6125620908171383im, ...] * Minimum: -1.568997e+00 * Iterations: 16 * Convergence: true * |x - x'| ≤ 0.0e+00: false |x - x'| = 3.28e-09 * |f(x) - f(x')| ≤ 0.0e+00 |f(x)|: false |f(x) - f(x')| = -4.25e-16 |f(x)| * |g(x)| ≤ 1.0e-08: true |g(x)| = 6.33e-11 * Stopped by an increasing objective: false * Reached Maximum Number of Iterations: false * Objective Calls: 48 * Gradient Calls: 48 ``` Similarly, with `ConjugateGradient`. ``` julia res = optimize(fcomplex, gcomplex!, x0, ConjugateGradient()) ``` ``` Results of Optimization Algorithm * Algorithm: Conjugate Gradient * Starting Point: [0.48155603952425174 - 1.477880724921868im,-0.3219431528959694 - 0.18542418173298963im, ...] * Minimizer: [0.1416354378490425 - 0.034929499492595516im,-0.12086000949769983 - 0.6125620892675705im, ...] * Minimum: -1.568997e+00 * Iterations: 23 * Convergence: false * |x - x'| ≤ 0.0e+00: false |x - x'| = 8.54e-10 * |f(x) - f(x')| ≤ 0.0e+00 |f(x)|: false |f(x) - f(x')| = -4.25e-16 |f(x)| * |g(x)| ≤ 1.0e-08: false |g(x)| = 3.72e-08 * Stopped by an increasing objective: true * Reached Maximum Number of Iterations: false * Objective Calls: 51 * Gradient Calls: 29 ``` ### Differentation The finite difference methods used by `Optim` support real functions with complex inputs. ``` julia res = optimize(fcomplex, x0, LBFGS()) ``` ``` Results of Optimization Algorithm * Algorithm: L-BFGS * Starting Point: [0.48155603952425174 - 1.477880724921868im,-0.3219431528959694 - 0.18542418173298963im, ...] * Minimizer: [0.1416354390108624 - 0.034929496786122484im,-0.12086000580073922 - 0.6125620908025359im, ...] * Minimum: -1.568997e+00 * Iterations: 16 * Convergence: true * |x - x'| ≤ 0.0e+00: false |x - x'| = 3.28e-09 * |f(x) - f(x')| ≤ 0.0e+00 |f(x)|: true |f(x) - f(x')| = 0.00e+00 |f(x)| * |g(x)| ≤ 1.0e-08: true |g(x)| = 1.04e-10 * Stopped by an increasing objective: false * Reached Maximum Number of Iterations: false * Objective Calls: 48 * Gradient Calls: 48 ``` Automatic differentiation support for complex inputs may come when [Cassete.jl](https://github.com/JuliaDiff/Capstan.jl) is ready. ## References - Sorber, L., Barel, M. V., & Lathauwer, L. D. (2012). Unconstrained optimization of real functions in complex variables. SIAM Journal on Optimization, 22(3), 879-898. - Kreutz-Delgado, K. (2009). The complex gradient operator and the CR-calculus. arXiv preprint arXiv:0906.4835.
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
72
# Golden Section ## Constructor ## Description ## Example ## References
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
1291
# Gradient Descent ## Constructor ```julia GradientDescent(; alphaguess = LineSearches.InitialPrevious(), linesearch = LineSearches.HagerZhang(), P = nothing, precondprep = (P, x) -> nothing) ``` ## Description Gradient Descent a common name for a quasi-Newton solver. This means that it takes steps according to ```math x_{n+1} = x_n - P^{-1}\nabla f(x_n) ``` where ``P`` is a positive definite matrix. If ``P`` is the Hessian, we get Newton's method. In Gradient Descent, ``P`` is simply an appropriately dimensioned identity matrix, such that we go in the exact opposite direction of the gradient. This means that we do not use the curvature information from the Hessian, or an approximation of it. While it does seem quite logical to go in the opposite direction of the fastest increase in objective value, the procedure can be very slow if the problem is ill-conditioned. See the section on preconditioners for ways to remedy this when using Gradient Descent. As with the other quasi-Newton solvers in this package, a scalar ``\alpha`` is introduced as follows ```math x_{n+1} = x_n - \alpha P^{-1}\nabla f(x_n) ``` and is chosen by a linesearch algorithm such that each step gives sufficient descent. ## Example ## References
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
157
# Interior point Newton method ```@docs IPNewton ``` ## Examples - [Nonlinear constrained optimization in Optim](../examples/generated/ipnewton_basics.md)
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
2382
# (L-)BFGS This page contains information about BFGS and its limited memory version L-BFGS. ## Constructors ```julia BFGS(; alphaguess = LineSearches.InitialStatic(), linesearch = LineSearches.HagerZhang(), initial_invH = nothing, initial_stepnorm = nothing, manifold = Flat()) ``` `initial_invH` has a default value of `nothing`. If the user has a specific initial matrix they want to supply, it should be supplied as a function of an array similar to the initial point `x0`. If `initial_stepnorm` is set to a number `z`, the initial matrix will be the identity matrix scaled by `z` times the sup-norm of the gradient at the initial point `x0`. ```julia LBFGS(; m = 10, alphaguess = LineSearches.InitialStatic(), linesearch = LineSearches.HagerZhang(), P = nothing, precondprep = (P, x) -> nothing, manifold = Flat(), scaleinvH0::Bool = true && (typeof(P) <: Nothing)) ``` ## Description This means that it takes steps according to ```math x_{n+1} = x_n - P^{-1}\nabla f(x_n) ``` where ``P`` is a positive definite matrix. If ``P`` is the Hessian, we get Newton's method. In (L-)BFGS, the matrix is an approximation to the Hessian built using differences in the gradient across iterations. As long as the initial matrix is positive definite it is possible to show that all the follow matrices will be as well. The starting matrix could simply be the identity matrix, such that the first step is identical to the Gradient Descent algorithm, or even the actual Hessian. There are two versions of BFGS in the package: BFGS, and L-BFGS. The latter is different from the former because it doesn't use a complete history of the iterative procedure to construct ``P``, but rather only the latest ``m`` steps. It doesn't actually build the Hessian approximation matrix either, but computes the direction directly. This makes more suitable for large scale problems, as the memory requirement to store the relevant vectors will grow quickly in large problems. As with the other quasi-Newton solvers in this package, a scalar ``\alpha`` is introduced as follows ```math x_{n+1} = x_n - \alpha P^{-1}\nabla f(x_n) ``` and is chosen by a linesearch algorithm such that each step gives sufficient descent. ## Example ## References Wright, Stephen, and Jorge Nocedal (2006) "Numerical optimization." Springer
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
2794
# Line search ## Description The line search functionality has been moved to [LineSearches.jl](https://github.com/JuliaNLSolvers/LineSearches.jl). Line search is used to decide the step length along the direction computed by an optimization algorithm. The following `Optim` algorithms use line search: * Accelerated Gradient Descent * (L-)BFGS * Conjugate Gradient * Gradient Descent * Momentum Gradient Descent * Newton By default `Optim` calls the line search algorithm `HagerZhang()` provided by `LineSearches`. Different line search algorithms can be assigned with the `linesearch` keyword argument to the given algorithm. `LineSearches` also allows the user to decide how the initial step length for the line search algorithm is chosen. This is set with the `alphaguess` keyword argument for the `Optim` algorithm. The default procedure varies. ## Example This example compares two different line search algorithms on the Rosenbrock problem. First, run `Newton` with the default line search algorithm: ```julia using Optim, LineSearches prob = Optim.UnconstrainedProblems.examples["Rosenbrock"] algo_hz = Newton(;alphaguess = LineSearches.InitialStatic(), linesearch = LineSearches.HagerZhang()) res_hz = Optim.optimize(prob.f, prob.g!, prob.h!, prob.initial_x, method=algo_hz) ``` This gives the result ``` julia * Algorithm: Newton's Method * Starting Point: [0.0,0.0] * Minimizer: [0.9999999999999994,0.9999999999999989] * Minimum: 3.081488e-31 * Iterations: 14 * Convergence: true * |x - x'| ≤ 0.0e+00: false |x - x'| = 3.06e-09 * |f(x) - f(x')| ≤ 0.0e+00 |f(x)|: false |f(x) - f(x')| = 2.94e+13 |f(x)| * |g(x)| ≤ 1.0e-08: true |g(x)| = 1.11e-15 * stopped by an increasing objective: false * Reached Maximum Number of Iterations: false * Objective Calls: 44 * Gradient Calls: 44 * Hessian Calls: 14 ``` Now we can try `Newton` with the More-Thuente line search: ``` julia algo_mt = Newton(;alphaguess = LineSearches.InitialStatic(), linesearch = LineSearches.MoreThuente()) res_mt = Optim.optimize(prob.f, prob.g!, prob.h!, prob.initial_x, method=algo_mt) ``` This gives the following result, reducing the number of function and gradient calls: ``` julia Results of Optimization Algorithm * Algorithm: Newton's Method * Starting Point: [0.0,0.0] * Minimizer: [0.9999999999999992,0.999999999999998] * Minimum: 2.032549e-29 * Iterations: 14 * Convergence: true * |x - x'| ≤ 0.0e+00: false |x - x'| = 3.67e-08 * |f(x) - f(x')| ≤ 0.0e00 |f(x)|: false |f(x) - f(x')| = 1.66e+13 |f(x)| * |g(x)| ≤ 1.0e-08: true |g(x)| = 1.76e-13 * stopped by an increasing objective: false * Reached Maximum Number of Iterations: false * Objective Calls: 17 * Gradient Calls: 17 * Hessian Calls: 14 ``` ## References
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
1986
# Manifold optimization Optim.jl supports the minimization of functions defined on Riemannian manifolds, i.e. with simple constraints such as normalization and orthogonality. The basic idea of such algorithms is to project back ("retract") each iterate of an unconstrained minimization method onto the manifold. This is used by passing a `manifold` keyword argument to the optimizer. ## Howto Here is a simple test case where we minimize the Rayleigh quotient `<x, A x>` of a symmetric matrix `A` under the constraint `||x|| = 1`, finding an eigenvector associated with the lowest eigenvalue of `A`. ```julia n = 10 A = Diagonal(range(1, stop=2, length=n)) f(x) = dot(x,A*x)/2 g(x) = A*x g!(stor,x) = copyto!(stor,g(x)) x0 = randn(n) manif = Optim.Sphere() Optim.optimize(f, g!, x0, Optim.ConjugateGradient(manifold=manif)) ``` ## Supported solvers and manifolds All first-order optimization methods are supported. The following manifolds are currently supported: * Flat: Euclidean space, default. Standard unconstrained optimization. * Sphere: spherical constraint `||x|| = 1`, where `x` is a real or complex array of any dimension. * Stiefel: Stiefel manifold of N by n matrices with orthogonal columns, i.e. `X'*X = I` The following meta-manifolds construct manifolds out of pre-existing ones: * PowerManifold: identical copies of a specified manifold * ProductManifold: product of two (potentially different) manifolds See `test/multivariate/manifolds.jl` for usage examples. Implementing new manifolds is as simple as adding methods `project_tangent!(M::YourManifold,g,x)` and `retract!(M::YourManifold,x)`. If you implement another manifold or optimization method, please contribute a PR! ## References The Geometry of Algorithms with Orthogonality Constraints, Alan Edelman, Tomás A. Arias, Steven T. Smith, SIAM. J. Matrix Anal. & Appl., 20(2), 303–353 Optimization Algorithms on Matrix Manifolds, P.-A. Absil, R. Mahony, R. Sepulchre, Princeton University Press, 2008
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
6211
# Nelder-Mead Nelder-Mead is currently the standard algorithm when no derivatives are provided. ## Constructor ```julia NelderMead(; parameters = AdaptiveParameters(), initial_simplex = AffineSimplexer()) ``` The keywords in the constructor are used to control the following parts of the solver: * `parameters` is a an instance of either `AdaptiveParameters` or `FixedParameters`, and is used to generate parameters for the Nelder-Mead Algorithm. * `initial_simplex` is an instance of `AffineSimplexer`. See more details below. ## Description Our current implementation of the Nelder-Mead algorithm is based on Nelder and Mead (1965) and Gao and Han (2010). Gradient free methods can be a bit sensitive to starting values and tuning parameters, so it is a good idea to be careful with the defaults provided in Optim. Instead of using gradient information, Nelder-Mead is a direct search method. It keeps track of the function value at a number of points in the search space. Together, the points form a simplex. Given a simplex, we can perform one of four actions: reflect, expand, contract, or shrink. Basically, the goal is to iteratively replace the worst point with a better point. More information can be found in Nelder and Mead (1965), Lagarias, et al (1998) or Gao and Han (2010). The stopping rule is the same as in the original paper, and is the standard error of the function values at the vertices. To set the tolerance level for this convergence criterion, set the `g_tol` level as described in the Configurable Options section. When the solver finishes, we return a minimizer which is either the centroid or one of the vertices. The function value at the centroid adds a function evaluation, as we need to evaluate the objection at the centroid to choose the smallest function value. However, even if the function value at the centroid can be returned as the minimum, we do not trace it during the optimization iterations. This is to avoid too many evaluations of the objective function which can be computationally expensive. Typically, there should be no more than twice as many `f_calls` than `iterations`. Adding an evaluation at the centroid when tracing could considerably increase the total run-time of the algorithm. ### Specifying the initial simplex The default choice of `initial_simplex` is `AffineSimplexer()`. A simplex is represented by an ``(n+1)``-dimensional vector of ``n``-dimensional vectors. It is used together with the initial `x` to create the initial simplex. To construct the ``i``th vertex, it simply multiplies entry ``i`` in the initial vector with a constant `b`, and adds a constant `a`. This means that the ``i``th of the ``n`` additional vertices is of the form ```math (x_0^1, x_0^2, \ldots, x_0^i, \ldots, 0,0) + (0, 0, \ldots, x_0^i\cdot b+a,\ldots, 0,0) ``` If an ``x_0^i`` is zero, we need the ``a`` to make sure all vertices are unique. Generally, it is advised to start with a relatively large simplex. If a specific simplex is wanted, it is possible to construct the ``(n+1)``-vector of ``n``-dimensional vectors, and pass it to the solver using a new type definition and a new method for the function `simplexer`. For example, let us minimize the two-dimensional Rosenbrock function, and choose three vertices that have elements that are simply standard uniform draws. ```julia using Optim struct MySimplexer <: Optim.Simplexer end Optim.simplexer(S::MySimplexer, initial_x) = [rand(length(initial_x)) for i = 1:length(initial_x)+1] f(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2 optimize(f, [.0, .0], NelderMead(initial_simplex = MySimplexer())) ``` Say we want to implement the initial simplex as in Matlab's `fminsearch`. This is very close to the `AffineSimplexer` above, but with a small twist. Instead of always adding the `a`, a constant is only added to entries that are zero. If the entry is non-zero, five percent of the level is added. This might be implemented (by the user) as ```julia struct MatlabSimplexer{T} <: Optim.Simplexer a::T b::T end MatlabSimplexer(;a = 0.00025, b = 0.05) = MatlabSimplexer(a, b) function Optim.simplexer(S::MatlabSimplexer, initial_x::AbstractArray{T, N}) where {T, N} n = length(initial_x) initial_simplex = Array{T, N}[copy(initial_x) for i = 1:n+1] for j = 1:n initial_simplex[j+1][j] += initial_simplex[j+1][j] != zero(T) ? S.b * initial_simplex[j+1][j] : S.a end initial_simplex end ``` ### The parameters of Nelder-Mead The different types of steps in the algorithm are governed by four parameters: ``\alpha`` for the reflection, ``\beta`` for the expansion, ``\gamma`` for the contraction, and ``\delta`` for the shrink step. We default to the adaptive parameters scheme in Gao and Han (2010). These are based on the dimensionality of the problem, and are given by ```math \alpha = 1, \quad \beta = 1+2/n,\quad \gamma =0.75 - 1/2n,\quad \delta = 1-1/n ``` It is also possible to specify the original parameters from Nelder and Mead (1965) ```math \alpha = 1,\quad \beta = 2, \quad\gamma = 1/2, \quad\delta = 1/2 ``` by specifying `parameters = Optim.FixedParameters()`. For specifying custom values, `parameters = Optim.FixedParameters(α = a, β = b, γ = g, δ = d)` is used, where a, b, g, d are the chosen values. If another parameter specification is wanted, it is possible to create a custom sub-type of`Optim.NMParameters`, and add a method to the `parameters` function. It should take the new type as the first positional argument, and the dimensionality of `x` as the second positional argument, and return a 4-tuple of parameters. However, it will often be easier to simply supply the wanted parameters to `FixedParameters`. ## References Nelder, John A. and R. Mead (1965). "A simplex method for function minimization". Computer Journal 7: 308–313. doi:10.1093/comjnl/7.4.308. Lagarias, Jeffrey C., et al. "Convergence properties of the Nelder--Mead simplex method in low dimensions." SIAM Journal on optimization 9.1 (1998): 112-147. Gao, Fuchang and Lixing Han (2010). "Implementing the Nelder-Mead simplex algorithm with adaptive parameters". Computational Optimization and Applications [DOI 10.1007/s10589-010-9329-3]
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
2891
# Newton's Method ## Constructor ```julia Newton(; alphaguess = LineSearches.InitialStatic(), linesearch = LineSearches.HagerZhang()) ``` The constructor takes two keywords: * `linesearch = a(d, x, p, x_new, g_new, phi0, dphi0, c)`, a function performing line search, see the line search section. * `alphaguess = a(state, dphi0, d)`, a function for setting the initial guess for the line search algorithm, see the line search section. ## Description Newton's method for optimization has a long history, and is in some sense the gold standard in unconstrained optimization of smooth functions, at least from a theoretical viewpoint. The main benefit is that it has a quadratic rate of convergence near a local optimum. The main disadvantage is that the user has to provide a Hessian. This can be difficult, complicated, or simply annoying. It can also be computationally expensive to calculate it. Newton's method for optimization consists of applying Newton's method for solving systems of equations, where the equations are the first order conditions, saying that the gradient should equal the zero vector. ```math \nabla f(x) = 0 ``` A second order Taylor expansion of the left-hand side leads to the iterative scheme ```math x_{n+1} = x_n - H(x_n)^{-1}\nabla f(x_n) ``` where the inverse is not calculated directly, but the step size is instead calculated by solving ```math H(x) \textbf{s} = \nabla f(x_n). ``` This is equivalent to minimizing a quadratic model, ``m_k`` around the current ``x_n`` ```math m_k(s) = f(x_n) + \nabla f(x_n)^\top \textbf{s} + \frac{1}{2} \textbf{s}^\top H(x_n) \textbf{s} ``` For functions where ``H(x_n)`` is difficult, or computationally expensive to obtain, we might replace the Hessian with another positive definite matrix that approximates it. Such methods are called Quasi-Newton methods; see (L-)BFGS and Gradient Descent. In a sufficiently small neighborhood around the minimizer, Newton's method has quadratic convergence, but globally it might have slower convergence, or it might even diverge. To ensure convergence, a line search is performed for each ``\textbf{s}``. This amounts to replacing the step formula above with ```math x_{n+1} = x_n - \alpha \textbf{s} ``` and finding a scalar ``\alpha`` such that we get sufficient descent; see the line search section for more information. Additionally, if the function is locally concave, the step taken in the formulas above will go in a direction of ascent, as the Hessian will not be positive (semi)definite. To avoid this, we use a specialized method to calculate the step direction. If the Hessian is positive semidefinite then the method used is standard, but if it is not, a correction is made using the functionality in [PositiveFactorizations.jl](https://github.com/timholy/PositiveFactorizations.jl). ## Example show the example from the issue ## References
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
5257
# Newton's Method With a Trust Region ## Constructor ```julia NewtonTrustRegion(; initial_delta = 1.0, delta_hat = 100.0, eta = 0.1, rho_lower = 0.25, rho_upper = 0.75) ``` The constructor takes keywords that determine the initial and maximal size of the trust region, when to grow and shrink the region, and how close the function should be to the quadratic approximation. The notation follows chapter four of Numerical Optimization. Below, ```rho``` ``=\rho`` refers to the ratio of the actual function change to the change in the quadratic approximation for a given step. * `initial_delta:`The starting trust region radius * `delta_hat:` The largest allowable trust region radius * `eta:` When ```rho``` is at least ```eta```, accept the step. * `rho_lower: ` When ```rho``` is less than ```rho_lower```, shrink the trust region. * `rho_upper:` When ```rho``` is greater than ```rho_upper```, grow the trust region (though no greater than ```delta_hat```). ## Description Newton's method with a trust region is designed to take advantage of the second-order information in a function's Hessian, but with more stability than Newton's method when functions are not globally well-approximated by a quadratic. This is achieved by repeatedly minimizing quadratic approximations within a dynamically-sized "trust region" in which the function is assumed to be locally quadratic [1]. Newton's method optimizes a quadratic approximation to a function. When a function is well approximated by a quadratic (for example, near an optimum), Newton's method converges very quickly by exploiting the second-order information in the Hessian matrix. However, when the function is not well-approximated by a quadratic, either because the starting point is far from the optimum or the function has a more irregular shape, Newton steps can be erratically large, leading to distant, irrelevant areas of the space. Trust region methods use second-order information but restrict the steps to be within a "trust region" where the function is believed to be approximately quadratic. At iteration ``k``, a trust region method chooses a step ``p`` to minimize a quadratic approximation to the objective such that the step size is no larger than a given trust region size, ``\Delta_k``. ```math \underset{p\in\mathbb{R}^n}\min m_k(p) = f_k + g_k^T p + \frac{1}{2}p^T B_k p \quad\textrm{such that } ||p||\le \Delta_k ``` Here, ``p`` is the step to take at iteration ``k``, so that ``x_{k+1} = x_k + p``. In the definition of ``m_k(p)``, ``f_k = f(x_k)`` is the value at the previous location, ``g_k=\nabla f(x_k)`` is the gradient at the previous location, ``B_k = \nabla^2 f(x_k)`` is the Hessian matrix at the previous iterate, and ``||\cdot||`` is the Euclidian norm. If the trust region size, ``\Delta_k``, is large enough that the minimizer of the quadratic approximation ``m_k(p)`` has ``||p|| \le \Delta_k``, then the step is the same as an ordinary Newton step. However, if the unconstrained quadratic minimizer lies outside the trust region, then the minimizer to the constrained problem will occur on the boundary, i.e. we will have ``||p|| = \Delta_k``. It turns out that when the Cholesky decomposition of ``B_k`` can be computed, the optimal ``p`` can be found numerically with relative ease. ([1], section 4.3) This is the method currently used in Optim. It makes sense to adapt the trust region size, ``\Delta_k``, as one moves through the space and assesses the quality of the quadratic fit. This adaptation is controlled by the parameters ``\eta``, ``\rho_{lower}``, and ``\rho_{upper}``, which are parameters to the ```NewtonTrustRegion``` optimization method. For each step, we calculate ```math \rho_k := \frac{f(x_{k+1}) - f(x_k)}{m_k(p) - m_k(0)} ``` Intuitively, ``\rho_k`` measures the quality of the quadratic approximation: if ``\rho_k \approx 1``, then our quadratic approximation is reasonable. If ``p`` was on the boundary and ``\rho_k > \rho_{upper}``, then perhaps we can benefit from larger steps. In this case, for the next iteration we grow the trust region geometrically up to a maximum of ``\hat\Delta``: ```math \rho_k > \rho_{upper} \Rightarrow \Delta_{k+1} = \min(2 \Delta_k, \hat\Delta). ``` Conversely, if ``\rho_k < \rho_{lower}``, then we shrink the trust region geometrically: ``\rho_k < \rho_{lower} \Rightarrow \Delta_{k+1} = 0.25 \Delta_k``. Finally, we only accept a point if its decrease is appreciable compared to the quadratic approximation. Specifically, a step is only accepted ``\rho_k > \eta``. As long as we choose ``\eta`` to be less than ``\rho_{lower}``, we will shrink the trust region whenever we reject a step. Eventually, if the objective function is locally quadratic, ``\Delta_k`` will become small enough that a quadratic approximation will be accurate enough to make progress again. ## Example ```julia using Optim, OptimTestProblems prob = UnconstrainedProblems.examples["Rosenbrock"]; res = Optim.optimize(prob.f, prob.g!, prob.h!, prob.initial_x, NewtonTrustRegion()) ``` ## References [1] Nocedal, Jorge, and Stephen Wright. Numerical optimization. Springer Science & Business Media, 2006.
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
6013
# Acceleration methods: N-GMRES and O-ACCEL ## Constructors ```julia NGMRES(; alphaguess = LineSearches.InitialStatic(), linesearch = LineSearches.HagerZhang(), manifold = Flat(), wmax::Int = 10, ϵ0 = 1e-12, nlprecon = GradientDescent( alphaguess = LineSearches.InitialStatic(alpha=1e-4,scaled=true), linesearch = LineSearches.Static(), manifold = manifold), nlpreconopts = Options(iterations = 1, allow_f_increases = true), ) ``` ```julia OACCEL(;manifold::Manifold = Flat(), alphaguess = LineSearches.InitialStatic(), linesearch = LineSearches.HagerZhang(), nlprecon = GradientDescent( alphaguess = LineSearches.InitialStatic(alpha=1e-4,scaled=true), linesearch = LineSearches.Static(), manifold = manifold), nlpreconopts = Options(iterations = 1, allow_f_increases = true), ϵ0 = 1e-12, wmax::Int = 10) ``` ## Description These algorithms take a step given by the nonlinear preconditioner `nlprecon` and proposes an accelerated step on a subspace spanned by the previous `wmax` iterates. - N-GMRES accelerates based on a minimization of an approximation to the $\ell_2$ norm of the gradient. - O-ACCEL accelerates based on a minimization of a n approximation to the objective. N-GMRES was originally developed for solving nonlinear systems [1], and reduces to GMRES for linear problems. Application of the algorithm to optimization is covered, for example, in [2]. A description of O-ACCEL and its connection to N-GMRES can be found in [3]. *We recommend trying [LBFGS](lbfgs.md) on your problem before N-GMRES or O-ACCEL. All three algorithms have similar computational cost and memory requirements, however, L-BFGS is more efficient for many problems.* ## Example This example shows how to accelerate `GradientDescent` on the Extended Rosenbrock problem. First, we try to optimize using `GradientDescent`. ```julia using Optim, OptimTestProblems UP = UnconstrainedProblems prob = UP.examples["Extended Rosenbrock"] optimize(UP.objective(prob), UP.gradient(prob), prob.initial_x, GradientDescent()) ``` The algorithm does not converge within 1000 iterations. ``` Results of Optimization Algorithm * Algorithm: Gradient Descent * Starting Point: [-1.2,1.0, ...] * Minimizer: [0.8923389282461412,0.7961268644300445, ...] * Minimum: 2.898230e-01 * Iterations: 1000 * Convergence: false * |x - x'| ≤ 0.0e+00: false |x - x'| = 4.02e-04 * |f(x) - f(x')| ≤ 0.0e+00 |f(x)|: false |f(x) - f(x')| = 2.38e-03 |f(x)| * |g(x)| ≤ 1.0e-08: false |g(x)| = 8.23e-02 * Stopped by an increasing objective: false * Reached Maximum Number of Iterations: true * Objective Calls: 2525 * Gradient Calls: 2525 ``` Now, we use `OACCEL` to accelerate `GradientDescent`. ```julia # Default nonlinear procenditioner for `OACCEL` nlprecon = GradientDescent(alphaguess=LineSearches.InitialStatic(alpha=1e-4,scaled=true), linesearch=LineSearches.Static()) # Default size of subspace that OACCEL accelerates over is `wmax = 10` oacc10 = OACCEL(nlprecon=nlprecon, wmax=10) optimize(UP.objective(prob), UP.gradient(prob), prob.initial_x, oacc10) ``` This drastically improves the `GradientDescent` algorithm, converging in 87 iterations. ``` Results of Optimization Algorithm * Algorithm: O-ACCEL preconditioned with Gradient Descent * Starting Point: [-1.2,1.0, ...] * Minimizer: [1.0000000011361219,1.0000000022828495, ...] * Minimum: 3.255053e-17 * Iterations: 87 * Convergence: true * |x - x'| ≤ 0.0e+00: false |x - x'| = 6.51e-08 * |f(x) - f(x')| ≤ 0.0e+00 |f(x)|: false |f(x) - f(x')| = 7.56e+02 |f(x)| * |g(x)| ≤ 1.0e-08: true |g(x)| = 1.06e-09 * Stopped by an increasing objective: false * Reached Maximum Number of Iterations: false * Objective Calls: 285 * Gradient Calls: 285 ``` We can improve the acceleration further by changing the acceleration subspace size `wmax`. ```julia oacc5 = OACCEL(nlprecon=nlprecon, wmax=5) optimize(UP.objective(prob), UP.gradient(prob), prob.initial_x, oacc5) ``` Now, the O-ACCEL algorithm has accelerated `GradientDescent` to converge in 50 iterations. ``` Results of Optimization Algorithm * Algorithm: O-ACCEL preconditioned with Gradient Descent * Starting Point: [-1.2,1.0, ...] * Minimizer: [0.9999999999392858,0.9999999998784691, ...] * Minimum: 9.218164e-20 * Iterations: 50 * Convergence: true * |x - x'| ≤ 0.0e+00: false |x - x'| = 2.76e-07 * |f(x) - f(x')| ≤ 0.0e+00 |f(x)|: false |f(x) - f(x')| = 5.18e+06 |f(x)| * |g(x)| ≤ 1.0e-08: true |g(x)| = 4.02e-11 * Stopped by an increasing objective: false * Reached Maximum Number of Iterations: false * Objective Calls: 181 * Gradient Calls: 181 ``` As a final comparison, we can do the same with N-GMRES. ```julia ngmres5 = NGMRES(nlprecon=nlprecon, wmax=5) optimize(UP.objective(prob), UP.gradient(prob), prob.initial_x, ngmres5) ``` Again, this significantly improves the `GradientDescent` algorithm, and converges in 63 iterations. ``` Results of Optimization Algorithm * Algorithm: Nonlinear GMRES preconditioned with Gradient Descent * Starting Point: [-1.2,1.0, ...] * Minimizer: [0.9999999998534468,0.9999999997063993, ...] * Minimum: 5.375569e-19 * Iterations: 63 * Convergence: true * |x - x'| ≤ 0.0e+00: false |x - x'| = 9.94e-09 * |f(x) - f(x')| ≤ 0.0e+00 |f(x)|: false |f(x) - f(x')| = 1.29e+03 |f(x)| * |g(x)| ≤ 1.0e-08: true |g(x)| = 4.94e-11 * Stopped by an increasing objective: false * Reached Maximum Number of Iterations: false * Objective Calls: 222 * Gradient Calls: 222 ``` ## References [1] De Sterck. Steepest descent preconditioning for nonlinear GMRES optimization. NLAA, 2013. [2] Washio and Oosterlee. Krylov subspace acceleration for nonlinear multigrid schemes. ETNA, 1997. [3] Riseth. Objective acceleration for unconstrained optimization. 2018.
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
1194
# Particle Swarm ## Constructor ```julia ParticleSwarm(; lower = [], upper = [], n_particles = 0) ``` The constructor takes three keywords: * `lower = []`, a vector of lower bounds, unbounded below if empty or `Inf`'s * `upper = []`, a vector of upper bounds, unbounded above if empty or `Inf`'s * `n_particles = 0`, number of particles in the swarm, defaults to least three ## Description The Particle Swarm implementation in Optim.jl is the so-called Adaptive Particle Swarm algorithm in [1]. It attempts to improve global coverage and convergence by switching between four evolutionary states: exploration, exploitation, convergence, and jumping out. In the jumping out state it intentially tries to take the best particle and move it away from its (potentially and probably) local optimum, to improve the ability to find a global optimum. Of course, this comes a the cost of slower convergence, but hopefully converges to the global optimum as a result. ## References [1] Zhan, Zhang, and Chung. Adaptive particle swarm optimization, IEEE Transactions on Systems, Man, and Cybernetics, Part B: CyberneticsVolume 39, Issue 6, 2009, Pages 1362-1381 (2009)
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
2481
# Preconditioning The `GradientDescent`, `ConjugateGradient` and `LBFGS` methods support preconditioning. A preconditioner can be thought of as a change of coordinates under which the Hessian is better conditioned. With a good preconditioner substantially improved convergence is possible. A preconditioner `P`can be of any type as long as the following two methods are implemented: * `A_ldiv_B!(pgr, P, gr)` : apply `P` to a vector `gr` and store in `pgr` (intuitively, `pgr = P \ gr`) * `dot(x, P, y)` : the inner product induced by `P` (intuitively, `dot(x, P * y)`) Precisely what these operations mean, depends on how `P` is stored. Commonly, we store a matrix `P` which approximates the Hessian in some vague sense. In this case, * `A_ldiv_B!(pgr, P, gr) = copyto!(pgr, P \ A)` * `dot(x, P, y) = dot(x, P * y)` Finally, it is possible to update the preconditioner as the state variable `x` changes. This is done through `precondprep!` which is passed to the optimizers as kw-argument, e.g., ```jl method=ConjugateGradient(P = precond(100), precondprep! = precond(100)) ``` though in this case it would always return the same matrix. (See `fminbox.jl` for a more natural example.) Apart from preconditioning with matrices, `Optim.jl` provides a type `InverseDiagonal`, which represents a diagonal matrix by its inverse elements. ## Example Below, we see an example where a function is minimized without and with a preconditioner applied. ```jl using ForwardDiff, Optim, SparseArrays initial_x = zeros(100) plap(U; n = length(U)) = (n-1)*sum((0.1 .+ diff(U).^2).^2 ) - sum(U) / (n-1) plap1(x) = ForwardDiff.gradient(plap,x) precond(n) = spdiagm(-1 => -ones(n-1), 0 => 2ones(n), 1 => -ones(n-1)) * (n+1) f(x) = plap([0; x; 0]) g!(G, x) = copyto!(G, (plap1([0; x; 0]))[2:end-1]) result = Optim.optimize(f, g!, initial_x, method = ConjugateGradient(P = nothing)) result = Optim.optimize(f, g!, initial_x, method = ConjugateGradient(P = precond(100))) ``` The former optimize call converges at a slower rate than the latter. Looking at a plot of the 2D version of the function shows the problem. ![plap](./plap.png) The contours are shaped like ellipsoids, but we would rather want them to be circles. Using the preconditioner effectively changes the coordinates such that the contours becomes less ellipsoid-like. Benchmarking shows that using preconditioning provides an approximate speed-up factor of 15 in this 100 dimensional case. ## References
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
4732
# SAMIN ## Constructor ```julia SAMIN(; nt::Int = 5 # reduce temperature every nt*ns*dim(x_init) evaluations ns::Int = 5 # adjust bounds every ns*dim(x_init) evaluations rt::T = 0.9 # geometric temperature reduction factor: when temp changes, new temp is t=rt*t neps::Int = 5 # number of previous best values the final result is compared to f_tol::T = 1e-12 # the required tolerance level for function value comparisons x_tol::T = 1e-6 # the required tolerance level for x coverage_ok::Bool = false, # if false, increase temperature until initial parameter space is covered verbosity::Int = 0) # scalar: 0, 1, 2 or 3 (default = 0). ``` ## Description The `SAMIN` method implements the Simulated Annealing algorithm for problems with bounds constraints as described in Goffe et. al. (1994) and Goffe (1996). A key control parameter is rt, the geometric temperature reduction rate, which should be between zero and one. Setting rt lower will cause the algorithm to contract the search space more quickly, reducing the run time. Setting rt too low will cause the algorithm to narrow the search too quickly, and the true minimizer may be skipped over. If possible, run the algorithm multiple times to verify that the same solution is found each time. If this is not the case, increase rt. When in doubt, start with a conservative rt, for example, rt=0.95, and allow for a generous iteration limit. The algorithm requires lower and upper bounds on the parameters, although these bounds are often set rather wide, and are not necessarily meant to reflect constraints in the model, but rather bounds that enclose the parameter space. If the final `x`s are very close to the boundary (which can be checked by setting verbosity=1), it is a good idea to restart the optimizer with wider bounds, unless the bounds actually reflect hard constraints on `x`. ## Example This example shows a successful minimization: ```julia julia> using Optim, OptimTestProblems julia> prob = UnconstrainedProblems.examples["Rosenbrock"]; julia> res = Optim.optimize(prob.f, fill(-100.0, 2), fill(100.0, 2), prob.initial_x, SAMIN(), Optim.Options(iterations=10^6)) ================================================================================ SAMIN results ==> Normal convergence <== total number of objective function evaluations: 23701 Obj. value: 0.0000000000 parameter search width 1.00000 0.00000 1.00000 0.00000 ================================================================================ Results of Optimization Algorithm * Algorithm: SAMIN * Starting Point: [-1.2,1.0] * Minimizer: [0.9999999893140956,0.9999999765350857] * Minimum: 5.522977e-16 * Iterations: 23701 * Convergence: false * |x - x'| ≤ 0.0e+00: false |x - x'| = NaN * |f(x) - f(x')| ≤ 0.0e+00 |f(x)|: false |f(x) - f(x')| = NaN |f(x)| * |g(x)| ≤ 0.0e+00: false |g(x)| = NaN * Stopped by an increasing objective: false * Reached Maximum Number of Iterations: false * Objective Calls: 23701 * Gradient Calls: 0 ``` ## Example This example shows an unsuccessful minimization, because the cooling rate, rt=0.5, is too rapid: ```julia julia> using Optim, OptimTestProblems julia> prob = UnconstrainedProblems.examples["Rosenbrock"]; julia> res = Optim.optimize(prob.f, fill(-100.0, 2), fill(100.0, 2), prob.initial_x, SAMIN(rt=0.5), Optim.Options(iterations=10^6)) ================================================================================ SAMIN results ==> Normal convergence <== total number of objective function evaluations: 12051 Obj. value: 0.0011613045 parameter search width 0.96592 0.00000 0.93301 0.00000 ================================================================================ Results of Optimization Algorithm * Algorithm: SAMIN * Starting Point: [-1.2,1.0] * Minimizer: [0.9659220825756248,0.9330054696322896] * Minimum: 1.161304e-03 * Iterations: 12051 * Convergence: false * |x - x'| ≤ 0.0e+00: false |x - x'| = NaN * |f(x) - f(x')| ≤ 0.0e+00 |f(x)|: false |f(x) - f(x')| = NaN |f(x)| * |g(x)| ≤ 0.0e+00: false |g(x)| = NaN * Stopped by an increasing objective: false * Reached Maximum Number of Iterations: false * Objective Calls: 12051 * Gradient Calls: 0 ``` ## References - Goffe, et. al. (1994) "Global Optimization of Statistical Functions with Simulated Annealing", Journal of Econometrics, V. 60, N. 1/2. - Goffe, William L. (1996) "SIMANN: A Global Optimization Algorithm using Simulated Annealing " Studies in Nonlinear Dynamics & Econometrics, Oct96, Vol. 1 Issue 3.
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
2764
# Simulated Annealing ## Constructor ```julia SimulatedAnnealing(; neighbor = default_neighbor!, T = default_temperature, p = kirkpatrick) ``` The constructor takes three keywords: * `neighbor = a!(x_proposed, x_current)`, a mutating function of the current x, and the proposed x * `T = b(iteration)`, a function of the current iteration that returns a temperature * `p = c(f_proposal, f_current, T)`, a function of the current temperature, current function value and proposed function value that returns an acceptance probability ## Description Simulated Annealing is a derivative free method for optimization. It is based on the Metropolis-Hastings algorithm that was originally used to generate samples from a thermodynamics system, and is often used to generate draws from a posterior when doing Bayesian inference. As such, it is a probabilistic method for finding the minimum of a function, often over a quite large domains. For the historical reasons given above, the algorithm uses terms such as cooling, temperature, and acceptance probabilities. As the constructor shows, a simulated annealing implementation is characterized by a temperature, a neighbor function, and an acceptance probability. The temperature controls how volatile the changes in minimizer candidates are allowed to be, as it enters the acceptance probability. For example, the original Kirkpatrick et al. acceptance probability function can be written as follows ```julia p(f_proposal, f_current, T) = exp(-(f_proposal - f_current)/T) ``` A high temperature makes it more likely that a draw is accepted, by pushing acceptance probability to 1. As in the Metropolis-Hastings algorithm, we always accept a smaller function value, but we also sometimes accept a larger value. As the temperature decreases, we're more and more likely to only accept candidate `x`'s that lowers the function value. To obtain a new `f_proposal`, we need a neighbor function. A simple neighbor function adds a standard normal draw to each dimension of `x` ```julia function neighbor!(x_proposal::Array, x::Array) for i in eachindex(x) x_proposal[i] = x[i]+randn() end end ``` As we see, it is not really possible to disentangle the role of the different components of the algorithm. For example, both the functional form of the acceptance function, the temperature and (indirectly) the neighbor function determine if the next draw of `x` is accepted or not. The current implementation of Simulated Annealing is very rough. It lacks quite a few features which are normally part of a proper SA implementation. A better implementation is under way, see [this issue](https://github.com/JuliaNLSolvers/Optim.jl/issues/200). ## Example ## References
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
2422
## Notes for contributing We are always happy to get help from people who normally do not contribute to the package. However, to make the process run smoothly, we ask you to read this page before creating your pull request. That way it is more probable that your changes will be incorporated, and in the end it will mean less work for everyone. ### Things to consider When proposing a change to `Optim.jl`, there are a few things to consider. If you're in doubt feel free to reach out. A simple way to get in touch, is to join our [gitter channel](https://gitter.im/JuliaNLSolvers/Optim.jl). Before submitting a pull request, please consider the following bullets: * Did you remember to provide tests for your changes? If not, please do so, or ask for help. * Did your change add new functionality? Remember to add a section in the documentation. * Did you change existing code in a breaking way? Then remember to use Julia's deprecation tools to help users migrate to the new syntax. * Add a note in the NEWS.md file, so we can keep track of changes between versions. ### Adding a solver If you're contributing a new solver, you shouldn't need to touch any of the code in `src/optimize.jl`. You should rather add a file named (`solver` is the name of the solver) `solver.jl` in `src`, and make sure that you define an `Optimizer` subtype `struct Solver <: Optimizer end` with appropriate fields, a default constructor with a keyword for each field, a state type that holds all variables that are (re)used throughout the iterative procedure, an `initial_state` that initializes such a state, and an `update!` method that does the actual work. Say you want to contribute a solver called `Minim`, then your `src/minim.jl` file would look something like ``` struct Minim{IF, F<:Function, T} <: Optimizer alphaguess!::IF linesearch!::F minim_parameter::T end Minim(; alphaguess = LineSearches.InitialStatic(), linesearch = LineSearches.HagerZhang(), minim_parameter = 1.0) = Minim(linesearch, minim_parameter) type MinimState{T,N,G} x::AbstractArray{T,N} x_previous::AbstractArray{T,N} f_x_previous::T s::AbstractArray{T,N} @add_linesearch_fields() end function initial_state(method::Minim, options, d, initial_x) # prepare cache variables etc here end function update!{T}(d, state::MinimState{T}, method::Minim) # code for Minim here false # should the procedure force quit? end ```
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
3220
## Algorithm choice There are two main settings you must choose in Optim: the algorithm and the linesearch. ## Algorithms The first choice to be made is that of the order of the method. Zeroth-order methods do not have gradient information, and are very slow to converge, especially in high dimension. First-order methods do not have access to curvature information and can take a large number of iterations to converge for badly conditioned problems. Second-order methods can converge very quickly once in the vicinity of a minimizer. Of course, this enhanced performance comes at a cost: the objective function has to be differentiable, you have to supply gradients and Hessians, and, for second order methods, a linear system has to be solved at each step. If you can provide analytic gradients and Hessians, and the dimension of the problem is not too large, then second order methods are very efficient. The Newton method with trust region is the method of choice. When you do not have an explicit Hessian or when the dimension becomes large enough that the linear solve in the Newton method becomes the bottleneck, first order methods should be preferred. BFGS is a very efficient method, but also requires a linear system solve. LBFGS usually has a performance very close to that of BFGS, and avoids linear system solves (the parameter `m` can be tweaked: increasing it can improve the convergence, at the expense of memory and time spent in linear algebra operations). The conjugate gradient method usually converges less quickly than LBFGS, but requires less memory. Gradient descent should only be used for testing. Acceleration methods are experimental. When the objective function is non-differentiable or you do not want to use gradients, use zeroth-order methods. Nelder-Mead is currently the most robust. ## Linesearches Linesearches are used in every first- and second-order method except for the trust-region Newton method. Linesearch routines attempt to locate quickly an approximate minimizer of the univariate function ``\alpha \to f(x+ \alpha d)``, where ``d`` is the descent direction computed by the algorithm. They vary in how accurate this minimization is. Two good linesearches are BackTracking and HagerZhang, the former being less stringent than the latter. For well-conditioned objective functions and methods where the step is usually well-scaled (such as LBFGS or Newton), a rough linesearch such as BackTracking is usually the most performant. For badly behaved problems or when extreme accuracy is needed (gradients below the square root of the machine epsilon, about ``10^{-8}`` with `Float64`), the HagerZhang method proves more robust. An exception is the conjugate gradient method which requires an accurate linesearch to be efficient, and should be used with the HagerZhang linesearch. ## Summary As a very crude heuristic: For a low-dimensional problem with analytic gradients and Hessians, use the Newton method with trust region. For larger problems or when there is no analytic Hessian, use LBFGS, and tweak the parameter `m` if needed. If the function is non-differentiable, use Nelder-Mead. Use the HagerZhang linesearch for robustness and BackTracking for speed.
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
5282
## Configurable options There are several options that simply take on some default values if the user doesn't supply anything else than a function (and gradient) and a starting point. ### Solver options There quite a few different solvers available in Optim, and they are all listed below. Notice that the constructors are written without input here, but they generally take keywords to tweak the way they work. See the pages describing each solver for more detail. Requires only a function handle: * `NelderMead()` * `SimulatedAnnealing()` Requires a function and gradient (will be approximated if omitted): * `BFGS()` * `LBFGS()` * `ConjugateGradient()` * `GradientDescent()` * `MomentumGradientDescent()` * `AcceleratedGradientDescent()` Requires a function, a gradient, and a Hessian (cannot be omitted): * `Newton()` * `NewtonTrustRegion()` Box constrained minimization: * `Fminbox()` Special methods for bounded univariate optimization: * `Brent()` * `GoldenSection()` ### General Options In addition to the solver, you can alter the behavior of the Optim package by using the following keywords: * `x_tol`: Absolute tolerance in changes of the input vector `x`, in infinity norm. Defaults to `0.0`. * `f_tol`: Relative tolerance in changes of the objective value. Defaults to `0.0`. * `g_tol`: Absolute tolerance in the gradient, in infinity norm. Defaults to `1e-8`. For gradient free methods, this will control the main convergence tolerance, which is solver specific. * `f_calls_limit`: A soft upper limit on the number of objective calls. Defaults to `0` (unlimited). * `g_calls_limit`: A soft upper limit on the number of gradient calls. Defaults to `0` (unlimited). * `h_calls_limit`: A soft upper limit on the number of Hessian calls. Defaults to `0` (unlimited). * `allow_f_increases`: Allow steps that increase the objective value. Defaults to `false`. Note that, when setting this to `true`, the last iterate will be returned as the minimizer even if the objective increased. * `iterations`: How many iterations will run before the algorithm gives up? Defaults to `1_000`. * `store_trace`: Should a trace of the optimization algorithm's state be stored? Defaults to `false`. * `show_trace`: Should a trace of the optimization algorithm's state be shown on `stdout`? Defaults to `false`. * `extended_trace`: Save additional information. Solver dependent. Defaults to `false`. * `show_warnings`: Should warnings due to NaNs or Inf be shown? Defaults to `true`. * `trace_simplex`: Include the full simplex in the trace for `NelderMead`. Defaults to `false`. * `show_every`: Trace output is printed every `show_every`th iteration. * `callback`: A function to be called during tracing. A return value of `true` stops the `optimize` call. The callback function is called every `show_every`th iteration. If `store_trace` is false, the argument to the callback is of the type [`OptimizationState`](https://github.com/JuliaNLSolvers/Optim.jl/blob/a1035134ca1f3ebe855f1cde034e32683178225a/src/types.jl#L155), describing the state of the current iteration. If `store_trace` is true, the argument is a list of all the states from the first iteration to the current. * `time_limit`: A soft upper limit on the total run time. Defaults to `NaN` (unlimited). Box constrained optimization has additional keywords to alter the behavior of the outer solver: * `outer_x_tol`: Absolute tolerance in changes of the input vector `x`, in infinity norm. Defaults to `0.0`. * `outer_f_tol`: Relative tolerance in changes of the objective value. Defaults to `0.0`. * `outer_g_tol`: Absolute tolerance in the gradient, in infinity norm. Defaults to `1e-8`. For gradient free methods, this will control the main convergence tolerance, which is solver specific. * `allow_outer_f_increases`: Allow steps that increase the objective value. Defaults to `false`. Note that, when setting this to `true`, the last iterate will be returned as the minimizer even if the objective increased. * `outer_iterations`: How many iterations will run before the algorithm gives up? Defaults to `1_000`. If you specify `outer_iterations = 10` and `iterations = 100`, the outer algorithm will run for `10` iterations, and for each outer iteration the inner algorithm will run for `100` iterations. We currently recommend the statically dispatched interface by using the `Optim.Options` constructor: ```jl res = optimize(f, g!, [0.0, 0.0], GradientDescent(), Optim.Options(g_tol = 1e-12, iterations = 10, store_trace = true, show_trace = false, show_warnings = true)) ``` Another interface is also available, based directly on keywords: ```jl res = optimize(f, g!, [0.0, 0.0], method = GradientDescent(), g_tol = 1e-12, iterations = 10, store_trace = true, show_trace = false, show_warnings = true) ``` Notice the need to specify the method using a keyword if this syntax is used. This approach might be deprecated in the future, and as a result we recommend writing code that has to maintained using the `Optim.Options` approach.
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
4878
## Gradients and Hessians To use first- and second-order methods, you need to provide gradients and Hessians, either in-place or out-of-place. There are three main ways of specifying derivatives: analytic, finite-difference and automatic differentiation. ## Analytic This results in the fastest run times, but requires the user to perform the often tedious task of computing the derivatives by hand. The gradient of complicated objective functions (e.g. involving the solution of algebraic equations, differential equations, eigendecompositions, etc.) can be computed efficiently using the adjoint method (see e.g. [these lecture notes](https://math.mit.edu/~stevenj/18.336/adjoint.pdf)). In particular, assuming infinite memory, the gradient of a ``\mathbb{R}^N \to \mathbb{R}`` function ``f`` can always be computed with a runtime comparable with only one evaluation of ``f``, no matter how large ``N``. To use analytic derivatives, simply pass `g!` and `h!` functions to `optimize`. ## Finite differences This uses the functionality in [DiffEqDiffTools.jl](https://github.com/JuliaDiffEq/DiffEqDiffTools.jl) to compute gradients and Hessians through central finite differences: ``f'(x) \approx \frac{f(x+h)-f(x-h)}{2h}``. For a ``\mathbb{R}^N \to \mathbb{R}`` objective function ``f``, this requires ``2N`` evaluations of ``f``. It is therefore efficient in low dimensions but slow when ``N`` is large. It is also inaccurate: ``h`` is chosen equal to ``\epsilon^{1/3}`` where ``\epsilon`` is the machine epsilon (about ``10^{-16}`` for `Float64`) to balance the truncation and rounding errors, resulting in an error of ``\epsilon^{2/3}`` (about ``10^{-11}`` for `Float64`) for the derivative. Finite differences are on by default if gradients and Hessians are not supplied to the `optimize` call. ## Automatic differentiation Automatic differentiation techniques are a middle ground between finite differences and analytic computations. They are exact up to machine precision, and do not require intervention from the user. They come in two main flavors: [forward and reverse mode](https://en.wikipedia.org/wiki/Automatic_differentiation). Forward-mode automatic differentiation is relatively straightforward to implement by propagating the sensitivities of the input variables, and is often faster than finite differences. The disadvantage is that the objective function has to be written using only Julia code. Forward-mode automatic differentiation still requires a runtime comparable to ``N`` evaluations of ``f``, and is therefore costly in large dimensions, like finite differences. Reverse-mode automatic differentiation can be seen as an automatic implementation of the adjoint method mentioned above, and requires a runtime comparable to only one evaluation of ``f``. It is however considerably more complex to implement, requiring to record the execution of the program to then run it backwards, and incurs a larger overhead. Forward-mode automatic differentiation is supported through the [ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl) package by providing the `autodiff=:forward` keyword to `optimize`. Reverse-mode automatic differentiation is not supported explicitly yet (although you can use it by writing your own `g!` function). There are a number of implementations in Julia, such as [ReverseDiff.jl](https://github.com/JuliaDiff/ReverseDiff.jl). ## Example Let us consider the Rosenbrock example again. ```julia function f(x) return (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2 end function g!(G, x) G[1] = -2.0 * (1.0 - x[1]) - 400.0 * (x[2] - x[1]^2) * x[1] G[2] = 200.0 * (x[2] - x[1]^2) end function h!(H, x) H[1, 1] = 2.0 - 400.0 * x[2] + 1200.0 * x[1]^2 H[1, 2] = -400.0 * x[1] H[2, 1] = -400.0 * x[1] H[2, 2] = 200.0 end initial_x = zeros(2) ``` Let us see if BFGS and Newton's Method can solve this problem with the functions provided. ```jlcon julia> Optim.minimizer(optimize(f, g!, h!, initial_x, BFGS())) 2-element Array{Float64,1}: 1.0 1.0 julia> Optim.minimizer(optimize(f, g!, h!, initial_x, Newton())) 2-element Array{Float64,1}: 1.0 1.0 ``` This is indeed the case. Now let us use finite differences for BFGS. ```jlcon julia> Optim.minimizer(optimize(f, initial_x, BFGS())) 2-element Array{Float64,1}: 1.0 1.0 ``` Still looks good. Returning to automatic differentiation, let us try both solvers using this method. We enable [forward mode](https://github.com/JuliaDiff/ForwardDiff.jl) automatic differentiation by using the `autodiff = :forward` keyword. ```jlcon julia> Optim.minimizer(optimize(f, initial_x, BFGS(); autodiff = :forward)) 2-element Array{Float64,1}: 1.0 1.0 julia> Optim.minimizer(optimize(f, initial_x, Newton(); autodiff = :forward)) 2-element Array{Float64,1}: 1.0 1.0 ``` Indeed, the minimizer was found, without providing any gradients or Hessians.
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
10826
## Unconstrained Optimization To show how the Optim package can be used, we minimize the [Rosenbrock function](http://en.wikipedia.org/wiki/Rosenbrock_function), a classical test problem for numerical optimization. We'll assume that you've already installed the Optim package using Julia's package manager. First, we load Optim and define the Rosenbrock function: ```jl using Optim f(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2 ``` Once we've defined this function, we can find the minimizer (the input that minimizes the objective) and the minimum (the value of the objective at the minimizer) using any of our favorite optimization algorithms. With a function defined, we just specify an initial point `x` and call `optimize` with a starting point `x0`: ```jl x0 = [0.0, 0.0] optimize(f, x0) ``` *Note*: it is important to pass `initial_x` as an array. If your problem is one-dimensional, you have to wrap it in an array. An easy way to do so is to write `optimize(x->f(first(x)), [initial_x])` which make sure the input is an array, but the anonymous function automatically passes the first (and only) element onto your given `f`. Optim will default to using the Nelder-Mead method in the multivariate case, as we did not provide a gradient. This can also be explicitly specified using: ```jl optimize(f, x0, NelderMead()) ``` Other solvers are available. Below, we use L-BFGS, a quasi-Newton method that requires a gradient. If we pass `f` alone, Optim will construct an approximate gradient for us using central finite differencing: ```jl optimize(f, x0, LBFGS()) ``` For better performance and greater precision, you can pass your own gradient function. If your objective is written in all Julia code with no special calls to external (that is non-Julia) libraries, you can also use automatic differentiation, by using the `autodiff` keyword and setting it to `:forward`: ```julia optimize(f, x0, LBFGS(); autodiff = :forward) ``` For the Rosenbrock example, the analytical gradient can be shown to be: ```jl function g!(G, x) G[1] = -2.0 * (1.0 - x[1]) - 400.0 * (x[2] - x[1]^2) * x[1] G[2] = 200.0 * (x[2] - x[1]^2) end ``` Note, that the functions we're using to calculate the gradient (and later the Hessian `h!`) of the Rosenbrock function mutate a fixed-sized storage array, which is passed as an additional argument called `G` (or `H` for the Hessian) in these examples. By mutating a single array over many iterations, this style of function definition removes the sometimes considerable costs associated with allocating a new array during each call to the `g!` or `h!` functions. If you prefer to have your gradients simply accept an `x`, you can still use `optimize` by setting the `inplace` keyword to `false`: ```jl optimize(f, g, x0; inplace = false) ``` where `g` is a function of `x` only. Returning to our in-place version, you simply pass `g!` together with `f` from before to use the gradient: ```jl optimize(f, g!, x0, LBFGS()) ``` For some methods, like simulated annealing, the gradient will be ignored: ```jl optimize(f, g!, x0, SimulatedAnnealing()) ``` In addition to providing gradients, you can provide a Hessian function `h!` as well. In our current case this is: ```jl function h!(H, x) H[1, 1] = 2.0 - 400.0 * x[2] + 1200.0 * x[1]^2 H[1, 2] = -400.0 * x[1] H[2, 1] = -400.0 * x[1] H[2, 2] = 200.0 end ``` Now we can use Newton's method for optimization by running: ```jl optimize(f, g!, h!, x0) ``` Which defaults to `Newton()` since a Hessian function was provided. Like gradients, the Hessian function will be ignored if you use a method that does not require it: ```jl optimize(f, g!, h!, x0, LBFGS()) ``` Note that Optim will not generate approximate Hessians using finite differencing because of the potentially low accuracy of approximations to the Hessians. Other than Newton's method, none of the algorithms provided by the Optim package employ exact Hessians. ## Box Constrained Optimization A primal interior-point algorithm for simple "box" constraints (lower and upper bounds) is available. Reusing our Rosenbrock example from above, boxed minimization is performed as follows: ```jl lower = [1.25, -2.1] upper = [Inf, Inf] initial_x = [2.0, 2.0] inner_optimizer = GradientDescent() results = optimize(f, g!, lower, upper, initial_x, Fminbox(inner_optimizer)) ``` This performs optimization with a barrier penalty, successively scaling down the barrier coefficient and using the chosen `inner_optimizer` (`GradientDescent()` above) for convergence at each step. To change algorithm specific options, such as the line search algorithm, specify it directly in the `inner_optimizer` constructor: ``` lower = [1.25, -2.1] upper = [Inf, Inf] initial_x = [2.0, 2.0] # requires using LineSearches inner_optimizer = GradientDescent(linesearch=LineSearches.BackTracking(order=3)) results = optimize(f, g!, lower, upper, initial_x, Fminbox(inner_optimizer)) ``` This algorithm uses diagonal preconditioning to improve the accuracy, and hence is a good example of how to use `ConjugateGradient` or `LBFGS` with preconditioning. Other methods will currently not use preconditioning. Only the box constraints are used. If you can analytically compute the diagonal of the Hessian of your objective function, you may want to consider writing your own preconditioner. There are two iterations parameters: an outer iterations parameter used to control `Fminbox` and an inner iterations parameter used to control the inner optimizer. For example, the following restricts the optimization to 2 major iterations ```julia results = optimize(f, g!, lower, upper, initial_x, Fminbox(GradientDescent()), Optim.Options(outer_iterations = 2)) ``` In contrast, the following sets the maximum number of iterations for each `GradientDescent()` optimization to 2 ```julia results = optimize(f, g!, lower, upper, initial_x, Fminbox(GradientDescent()), Optim.Options(iterations = 2)) ``` ### Using second order information When the Hessian of the objective function is available it is possible to use the primal-dual algorithm implemented in `IPNewton`. The interface is similar ```julia results = optimize(f, lower, upper, initial_x, IPNewton()) results = optimize(f, g!, lower, upper, initial_x, IPNewton()) results = optimize(f, g!, h!, lower, upper, initial_x, IPNewton()) ``` ## Minimizing a univariate function on a bounded interval Minimization of univariate functions without derivatives is available through the `optimize` interface: ```jl optimize(f, lower, upper, method; kwargs...) ``` Notice the lack of initial `x`. A specific example is the following quadratic function. ```jl julia> f_univariate(x) = 2x^2+3x+1 f_univariate (generic function with 1 method) julia> optimize(f_univariate, -2.0, 1.0) Results of Optimization Algorithm * Algorithm: Brent's Method * Search Interval: [-2.000000, 1.000000] * Minimizer: -7.500000e-01 * Minimum: -1.250000e-01 * Iterations: 7 * Convergence: max(|x - x_upper|, |x - x_lower|) <= 2*(1.5e-08*|x|+2.2e-16): true * Objective Function Calls: 8 ``` The output shows that we provided an initial lower and upper bound, that there is a final minimizer and minimum, and that it used seven major iterations. Importantly, we also see that convergence was declared. The default method is Brent's method, which is one out of two available methods: * Brent's method, the default (can be explicitly selected with `Brent()`). * Golden section search, available with `GoldenSection()`. If we want to manually specify this method, we use the usual syntax as for multivariate optimization. ```jl optimize(f, lower, upper, Brent(); kwargs...) optimize(f, lower, upper, GoldenSection(); kwargs...) ``` Keywords are used to set options for this special type of optimization. In addition to the `iterations`, `store_trace`, `show_trace`, `show_warnings`, and `extended_trace` options, the following options are also available: * `rel_tol`: The relative tolerance used for determining convergence. Defaults to `sqrt(eps(T))`. * `abs_tol`: The absolute tolerance used for determining convergence. Defaults to `eps(T)`. ## Obtaining results After we have our results in `res`, we can use the API for getting optimization results. This consists of a collection of functions. They are not exported, so they have to be prefixed by `Optim.`. Say we do the following optimization: ```jl res = optimize(x->dot(x,[1 0. 0; 0 3 0; 0 0 1]*x), zeros(3)) ``` If we can't remember what method we used, we simply use ```jl summary(res) ``` which will return `"Nelder Mead"`. A bit more useful information is the minimizer and minimum of the objective functions, which can be found using ```jlcon julia> Optim.minimizer(res) 3-element Array{Float64,1}: -0.499921 -0.3333 -1.49994 julia> Optim.minimum(res) -2.8333333205768865 ``` ### Complete list of functions A complete list of functions can be found below. Defined for all methods: * `summary(res)` * `minimizer(res)` * `minimum(res)` * `iterations(res)` * `iteration_limit_reached(res)` * `trace(res)` * `x_trace(res)` * `f_trace(res)` * `f_calls(res)` * `converged(res)` Defined for univariate optimization: * `lower_bound(res)` * `upper_bound(res)` * `x_lower_trace(res)` * `x_upper_trace(res)` * `rel_tol(res)` * `abs_tol(res)` Defined for multivariate optimization: * `g_norm_trace(res)` * `g_calls(res)` * `x_converged(res)` * `f_converged(res)` * `g_converged(res)` * `initial_state(res)` ## Input types Most users will input `Vector`'s as their `initial_x`'s, and get an `Optim.minimizer(res)` out that is also a vector. For zeroth and first order methods, it is also possible to pass in matrices, or even higher dimensional arrays. The only restriction imposed by leaving the `Vector` case is, that it is no longer possible to use finite difference approximations or automatic differentiation. Second order methods (variants of Newton's method) do not support this more general input type. ## Notes on convergence flags and checks Currently, it is possible to access a minimizer using `Optim.minimizer(result)` even if all convergence flags are `false`. This means that the user has to be a bit careful when using the output from the solvers. It is advised to include checks for convergence if the minimizer or minimum is used to carry out further calculations. A related note is that first and second order methods makes a convergence check on the gradient before entering the optimization loop. This is done to prevent line search errors if `initial_x` is a stationary point. Notice, that this is only a first order check. If `initial_x` is any type of stationary point, `g_converged` will be true. This includes local minima, saddle points, and local maxima. If `iterations` is `0` and `g_converged` is `true`, the user needs to keep this point in mind.
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
11021
## Dealing with constant parameters In many applications, there may be factors that are relevant to the function evaluations, but are fixed throughout the optimization. An obvious example is using data in a likelihood function, but it could also be parameters we wish to hold constant. Consider a squared error loss function that depends on some data `x` and `y`, and parameters `betas`. As far as the solver is concerned, there should only be one input argument to the function we want to minimize, call it `sqerror`. The problem is that we want to optimize a function `sqerror` that really depends on three inputs, and two of them are constant throughout the optimization procedure. To do this, we need to define the variables `x` and `y` ```jl x = [1.0, 2.0, 3.0] y = 1.0 .+ 2.0 .* x .+ [-0.3, 0.3, -0.1] ``` We then simply define a function in three variables ```julia function sqerror(betas, X, Y) err = 0.0 for i in 1:length(X) pred_i = betas[1] + betas[2] * X[i] err += (Y[i] - pred_i)^2 end return err end ``` and then optimize the following anonymous function ```jl res = optimize(b -> sqerror(b, x, y), [0.0, 0.0]) ``` Alternatively, we can define a closure `sqerror(betas)` that is aware of the variables we just defined ```jl function sqerror(betas) err = 0.0 for i in 1:length(x) pred_i = betas[1] + betas[2] * x[i] err += (y[i] - pred_i)^2 end return err end ``` We can then optimize the `sqerror` function just like any other function ```jl res = optimize(sqerror, [0.0, 0.0]) ``` ## Avoid repeating computations Say you are optimizing a function ```julia f(x) = x[1]^2+x[2]^2 g!(storage, x) = copyto!(storage, [2x[1], 2x[2]]) ``` In this situation, no calculations from `f` could be reused in `g!`. However, sometimes there is a substantial similarity between the objective function, and gradient, and some calculations can be reused. To avoid repeating calculations, define functions `fg!` or `fgh!` that compute the objective function, the gradient and the Hessian (if needed) simultaneously. These functions internally can be written to avoid repeating common calculations. For example, here we define a function `fg!` to compute the objective function and the gradient, as required: ```julia function fg!(F, G, x) # do common computations here # ... if G !== nothing # code to compute gradient here # writing the result to the vector G # G .= ... end if F !== nothing # value = ... code to compute objective function return value end end ``` `Optim` will only call this function with an argument `G` that is `nothing` (if the gradient is not required) or a `Vector` that should be filled (in-place) with the gradient. This flexibility is convenient for algorithms that only use the gradient in some iterations but not in others. Now we call `optimize` with the following syntax: ```julia Optim.optimize(Optim.only_fg!(fg!), [0., 0.], Optim.LBFGS()) ``` Similarly, for a computation that requires the Hessian, we can write: ```julia function fgh!(F, G, H, x) G === nothing || # compute gradient and store in G H === nothing || # compute Hessian and store in H F === nothing || return f(x) nothing end Optim.optimize(Optim.only_fgh!(fgh!), [0., 0.], Optim.Newton()) ``` ## Provide gradients As mentioned in the general introduction, passing analytical gradients can have an impact on performance. To show an example of this, consider the separable extension of the Rosenbrock function in dimension 5000, see [SROSENBR](ftp://ftp.numerical.rl.ac.uk/pub/cutest/sif/SROSENBR.SIF) in CUTEst. Below, we use the gradients and objective functions from [mastsif](http://www.cuter.rl.ac.uk/Problems/mastsif.shtml) through [CUTEst.jl](https://github.com/JuliaSmoothOptimizers/CUTEst.jl). We only show the first five iterations of an attempt to minimize the function using Gradient Descent. ```jlcon julia> @time optimize(f, initial_x, GradientDescent(), Optim.Options(show_trace=true, iterations = 5)) Iter Function value Gradient norm 0 4.850000e+04 2.116000e+02 1 1.018734e+03 2.704951e+01 2 3.468449e+00 5.721261e-01 3 2.966899e+00 2.638790e-02 4 2.511859e+00 5.237768e-01 5 2.107853e+00 1.020287e-01 21.731129 seconds (1.61 M allocations: 63.434 MB, 0.03% gc time) Results of Optimization Algorithm * Algorithm: Gradient Descent * Starting Point: [1.2,1.0, ...] * Minimizer: [1.0287767703731154,1.058769439356144, ...] * Minimum: 2.107853e+00 * Iterations: 5 * Convergence: false * |x - x'| < 0.0: false * |f(x) - f(x')| / |f(x)| < 0.0: false * |g(x)| < 1.0e-08: false * Reached Maximum Number of Iterations: true * Objective Function Calls: 23 * Gradient Calls: 23 julia> @time optimize(f, g!, initial_x, GradientDescent(), Optim.Options(show_trace=true, iterations = 5)) Iter Function value Gradient norm 0 4.850000e+04 2.116000e+02 1 1.018769e+03 2.704998e+01 2 3.468488e+00 5.721481e-01 3 2.966900e+00 2.638792e-02 4 2.511828e+00 5.237919e-01 5 2.107802e+00 1.020415e-01 0.009889 seconds (915 allocations: 270.266 KB) Results of Optimization Algorithm * Algorithm: Gradient Descent * Starting Point: [1.2,1.0, ...] * Minimizer: [1.0287763814102757,1.05876866832087, ...] * Minimum: 2.107802e+00 * Iterations: 5 * Convergence: false * |x - x'| < 0.0: false * |f(x) - f(x')| / |f(x)| < 0.0: false * |g(x)| < 1.0e-08: false * Reached Maximum Number of Iterations: true * Objective Function Calls: 23 * Gradient Calls: 23 ``` The objective has obtained a value that is very similar between the two runs, but the run with the analytical gradient is way faster. It is possible that the finite differences code can be improved, but generally the optimization will be slowed down by all the function evaluations required to do the central finite differences calculations. ## Separating time spent in Optim's code and user provided functions Consider the Rosenbrock problem. ```julia using Optim, OptimTestProblems prob = UnconstrainedProblems.examples["Rosenbrock"]; ``` Say we optimize this function, and look at the total run time of `optimize` using the Newton Trust Region method, and we are surprised that it takes a long time to run. We then wonder if time is spent in Optim's own code (solving the sub-problem for example) or in evaluating the objective, gradient or hessian that we provided. Then it can be very useful to use the [TimerOutputs.jl](https://github.com/KristofferC/TimerOutputs.jl) package. This package allows us to run an over-all timer for `optimize`, and add individual timers for `f`, `g!`, and `h!`. Consider the example below, that is due to the author of the package (Kristoffer Carlsson). ```julia using TimerOutputs const to = TimerOutput() f(x ) = @timeit to "f" prob.f(x) g!(x, g) = @timeit to "g!" prob.g!(x, g) h!(x, h) = @timeit to "h!" prob.h!(x, h) begin reset_timer!(to) @timeit to "Trust Region" begin res = Optim.optimize(f, g!, h!, prob.initial_x, NewtonTrustRegion()) end show(to; allocations = false) end ``` We see that the time is actually *not* spent in our provided functions, but most of the time is spent in the code for the trust region method. ## Early stopping Sometimes it might be of interest to stop the optimizer early. The simplest way to do this is to set the `iterations` keyword in `Optim.Options` to some number. This will prevent the iteration counter exceeding some limit, with the standard value being 1000. Alternatively, it is possible to put a soft limit on the run time of the optimization procedure by setting the `time_limit` keyword in the `Optim.Options` constructor. ```julia using Optim, OptimTestProblems problem = UnconstrainedProblems.examples["Rosenbrock"] f = problem.f initial_x = problem.initial_x function slow(x) sleep(0.1) f(x) end start_time = time() optimize(slow, zeros(2), NelderMead(), Optim.Options(time_limit = 3.0)) ``` This will stop after about three seconds. If it is more important that we stop before the limit is reached, it is possible to use a callback with a simple model for predicting how much time will have passed when the next iteration is over. Consider the following code ```julia using Optim, OptimTestProblems problem = UnconstrainedProblems.examples["Rosenbrock"] f = problem.f initial_x = problem.initial_x function very_slow(x) sleep(.5) f(x) end start_time = time() time_to_setup = zeros(1) function advanced_time_control(x) println(" * Iteration: ", x.iteration) so_far = time()-start_time println(" * Time so far: ", so_far) if x.iteration == 0 time_to_setup .= time()-start_time else expected_next_time = so_far + (time()-start_time-time_to_setup[1])/(x.iteration) println(" * Next iteration ≈ ", expected_next_time) println() return expected_next_time < 13 ? false : true end println() false end optimize(very_slow, zeros(2), NelderMead(), Optim.Options(callback = advanced_time_control)) ``` It will try to predict the elapsed time after the next iteration is over, and stop now if it is expected to exceed the limit of 13 seconds. Running it, we get something like the following output ```jlcon julia> optimize(very_slow, zeros(2), NelderMead(), Optim.Options(callback = advanced_time_control)) * Iteration: 0 * Time so far: 2.219298839569092 * Iteration: 1 * Time so far: 3.4006409645080566 * Next iteration ≈ 4.5429909229278564 * Iteration: 2 * Time so far: 4.403923988342285 * Next iteration ≈ 5.476739525794983 * Iteration: 3 * Time so far: 5.407265901565552 * Next iteration ≈ 6.4569235642751055 * Iteration: 4 * Time so far: 5.909044027328491 * Next iteration ≈ 6.821732044219971 * Iteration: 5 * Time so far: 6.912338972091675 * Next iteration ≈ 7.843148183822632 * Iteration: 6 * Time so far: 7.9156060218811035 * Next iteration ≈ 8.85849153995514 * Iteration: 7 * Time so far: 8.918903827667236 * Next iteration ≈ 9.870419979095459 * Iteration: 8 * Time so far: 9.922197818756104 * Next iteration ≈ 10.880185931921005 * Iteration: 9 * Time so far: 10.925468921661377 * Next iteration ≈ 11.888488478130764 * Iteration: 10 * Time so far: 11.92870283126831 * Next iteration ≈ 12.895747828483582 * Iteration: 11 * Time so far: 12.932114839553833 * Next iteration ≈ 13.902462200684981 Results of Optimization Algorithm * Algorithm: Nelder-Mead * Starting Point: [0.0,0.0] * Minimizer: [0.23359374999999996,0.042187499999999996, ...] * Minimum: 6.291677e-01 * Iterations: 11 * Convergence: false * √(Σ(yᵢ-ȳ)²)/n < 1.0e-08: false * Reached Maximum Number of Iterations: false * Objective Function Calls: 24 ```
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
1.9.4
d9b79c4eed437421ac4285148fcadf42e0700e89
docs
4906
--- title: 'Optim: A mathematical optimization package for Julia' tags: - Optimization - Julia authors: - name: Patrick K Mogensen orcid: 0000-0002-4910-1932 affiliation: 1 - name: Asbjørn N Riseth orcid: 0000-0002-5861-7885 affiliation: 2 affiliations: - name: University of Copenhagen index: 1 - name: University of Oxford index: 2 date: 7 March 2018 bibliography: paper.bib --- # Summary [Optim](https://github.com/JuliaNLSolvers/Optim.jl/) provides a range of optimization capabilities written in the Julia programming language [@bezanson2017julia]. Our aim is to enable researchers, users, and other Julia packages to solve optimization problems without writing such algorithms themselves. The package supports optimization on manifolds, functions of complex numbers, and input types such as arbitrary precision vectors and matrices. We have implemented routines for derivative free, first-order, and second-order optimization methods. The user can provide derivatives themselves, or request that they are calculated using automatic differentiation or finite difference methods. The main focus of the package has currently been on unconstrained optimization, however, box-constrained optimization is supported, and a more comprehensive support for constraints is underway. Similar to Optim, the C library [NLopt](http://ab-initio.mit.edu/nlopt) [@johnson2018nlopt] contains a collection of nonlinear optimization routines. In Python, [scipy.optimize](https://docs.scipy.org/doc/scipy/reference/optimize.html) supports many of the same algorithms as Optim does, and [Pymanopt](https://pymanopt.github.io/) [@townsend2016pymanopt] is a toolbox for manifold optimization. Within the Julia community, the packages [BlackBoxOptim.jl](https://github.com/robertfeldt/BlackBoxOptim.jl) and [Optimize.jl](https://github.com/JuliaSmoothOptimizers/Optimize.jl) provide optimization capabilities focusing on derivative-free and large-scale smooth problems respectively. The packages [Convex.jl](https://github.com/JuliaOpt/Convex.jl) and [JuMP.jl](https://github.com/JuliaOpt/JuMP.jl) [@dunning2017jump] define modelling languages for which users can formulate optimization problems. In contrast to the previously mentioned optimization codes, Convex and JuMP work as abstraction layers between the user and solvers from a other packages. ## Optimization routines As of version 0.14, the following optimization routines are available. - Second-order methods * Newton * Newton with trust region * Hessian-vector with trust region - First-order methods * BFGS * L-BFGS (with linear preconditioning) * Conjugate gradient (with linear preconditioning) * Gradient descent (with linear preconditioning) - Acceleration methods * Nonlinear GMRES * Objective acceleration - Derivative-free methods * Nelder–Mead * Simulated annealing * Particle swarm - Interval bound univariate methods * Brent's method * Golden-section search The derivative based methods use line searches to assist convergence. Multiple line search algorithms are available, including interpolating backtracking and methods that aim to satisfy the Wolfe conditions. # Usage in research and industry The optimization routines in this package have been used in both industrial and academic contexts. For example, parts of the internal work in the company Ternary Intelligence Inc. [@ternary2017] rely on the package. Notably, an upcoming book on optimization [@mykel2018optimization] uses Optim for its examples. Optim has been used for a wide range of applications in academic research, including optimal control [@riseth2017comparison; @riseth2017dynamic], parameter estimation [@riseth2017operator; @rackauckas2017differentialequations; and @dony2018parametric], quantum physics [@damle2018variational], crystalline modelling [@chen2017qm; @braun2017effect], and the large-scale astronomical cataloguing project Celeste [@regier2015celeste; @regier2016celeste]. A new acceleration scheme for optimization [@riseth2017objective], and a preconditioning scheme for geometry optimisation [@packwood2016universal] have also been tested within the Optim framework. # Acknowledgements John Myles White initiated the development of the Optim code base in 2012. We owe much to him and Timothy Holy for creating a solid package for optimization that the rest of the Julia community could further improve upon. We would also like to thank everyone who has contributed with code and discussions to help improve the package. In particular, Antoine Levitt, Christoph Ortner, and Chris Rackauckas have been helpful in providing suggestions and code contributions towards more modularity and greater support for non-trivial inputs and decision spaces. # Funding Asbjørn Riseth is partially supported by the EPSRC research grant EP/L015803/1. # References
Optim
https://github.com/JuliaNLSolvers/Optim.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
code
926
push!(LOAD_PATH,"../src/") using Documenter, AuditoryStimuli makedocs( modules = [AuditoryStimuli], format = Documenter.HTML(prettyurls = get(ENV, "CI", nothing) == "true"), sitename = "AuditoryStimuli.jl", authors = "Robert Luke", pages = [ "Home" => "index.md", "Introduction / Tutorial" => "realtime-introduction.md", "Examples" => Any[ "Amplitude Modulated Noise" => "example-ssr.md", "Harmonic Stacks" => "example-hs.md", "Bandpass Noise" => "example-bpnoise.md", "Interaural Time Delay" => "example-itd.md", "ITD Modulation" => "example-itmfr.md", "Signal and Noise" => "example-signoise.md", ], "Advanced Usage" => "advanced.md", "API" => "api.md" ] ) deploydocs( repo = "github.com/rob-luke/AuditoryStimuli.jl.git", push_preview = true, devbranch = "main" )
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
code
3147
#= White noise generator with variable volume ========================================== This program generates white noise and plays it through your speakers. The volume of the white noise can be adjusted via a command prompt. Details ------- Noise is played. The user is asked to select an amplification from 1-9. When the user selects an amplification it is applied to the noise. The noise is ramped to the desired value. Simulatenously the user is asked for a new amplification. The amplification of the noise can be modified at any time, it does not have to have ramped all the way to the previously selected value. If the user selects a value other than 1-9 the noise is ramped off =# using PortAudio, Unitful, AuditoryStimuli, SampledSignals, Printf, DSP using Pipe: @pipe # ########################### # ## Helper functions # ########################### """ This function returns the port audio stream matching the requested card """ function get_soundcard_stream(soundcard::String="Fireface") a = PortAudio.devices() idx = [occursin(soundcard, d.name) for d in a] if sum(idx) > 1 error("Multiple soundcards with requested name ($soundcard) were found: $a") end name = a[findfirst(idx)].name println("Using device: $name") stream = PortAudioStream(name, 0, 2) end """ This function presents a prompt to the user and ensures the response is valid. If the response is valid it is returned. If not, it returns `quit`. """ function query_prompt(query, typ) print(query, ": ") choice = uppercase(strip(readline(stdin))) if ((ret = tryparse(typ, choice)) != nothing) && (0 < ret < 10) return ret elseif choice == "F" return "f" else println("A number between 1-9 was not entered... quiting") return "quit" end end # ########################### # ## Main program structure # ########################### responsetype = Bandpass(500, 4000; fs=48000) designmethod = Butterworth(4) zpg = digitalfilter(responsetype, designmethod) f1 = DSP.Filters.DF2TFilter(zpg) f2 = DSP.Filters.DF2TFilter(zpg) # Set up the audio pathway objects soundcard = get_soundcard_stream() noise_source = NoiseSource(Float64, 48000, 2, 0.2) amplify = Amplification(0.1, 0.01, 0.005) bandpass = AuditoryStimuli.Filter([f1, f2]) # Instansiate the audio stream in its own thread noise_stream = Threads.@spawn begin while amplify.current > 0.001 @pipe read(noise_source, 0.01u"s") |> modify(amplify, _) |> modify(bandpass, _) |> write(soundcard, _) end end # Main function while amplify.current> 0.001 a = query_prompt("Select amplification. 1(quiet) to 9(loud), or q(quit)", Float64) if a isa Number # Update the target amplifcation setproperty!(amplify, :target, a / 10.0) elseif a == "f" # Enable or disable the band pass filter setproperty!(bandpass, :enable, !bandpass.enable) else # Ramp the amplifcation to zero and then exit setproperty!(amplify, :target, 0.0) while amplify.current > 0.001; sleep(0.2); end println("Shuting down") end end close(soundcard)
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
code
6504
""" A Julia package for generating auditory stimuli. """ module AuditoryStimuli using DSP using SampledSignals using LinearAlgebra using Random using Logging using FFTW using Unitful using Plots using Parameters using Unitful: AbstractQuantity, AffineQuantity, DimensionlessQuantity import SampledSignals: nchannels, samplerate, unsafe_read! import Plots: plot export bandpass_noise, bandpass_filter, amplitude_modulate, ITD_modulate, set_RMS, ramp_on, ramp_off, set_ITD, PlotSpectroTemporal, NoiseSource, CorrelatedNoiseSource, SinusoidSource, DummySampleSink, Amplification, AmplitudeModulation, TimeDelay, samplerate, modify, plot, interaural_coherence, plot_cross_correlation # ######################################### # ##### Signal Generation # ######################################### include("SignalGenerators/NoiseSource.jl") include("SignalGenerators/CorrelatedNoiseSource.jl") include("SignalGenerators/SinusoidSource.jl") include("SignalGenerators/DummySampleSink.jl") # ######################################### # ##### Signal Modifiers # ######################################### include("SignalModifiers/Amplification.jl") include("SignalModifiers/BandpassFilter.jl") include("SignalModifiers/Modulation.jl") include("SignalModifiers/TimeDelay.jl") # ######################################### # ##### Signal Metrics # ######################################### include("SignalMetrics/InterauralCoherence.jl") # ######################################### # ##### Signal Plotting # ######################################### include("Plotting.jl") """ bandpass_noise(number_samples, number_channels, lower_bound, upper_bound, sample_rate; filter_order=14) Generates band pass noise with specified upper and lower bounds using a butterworth filter. """ function bandpass_noise(number_samples::Int, number_channels::Int, lower_bound::Number, upper_bound::Number, sample_rate::Number; filter_order::Int = 14) bandpass_filter(randn(number_samples, number_channels), lower_bound, upper_bound, sample_rate, filter_order=filter_order) end # ######################################### # ##### Signal Modifiers # ######################################### """ bandpass_filter(AbstractArray, lower_bound, upper_bound, sample_rate; filter_order=14) bandpass_filter(SampledSignal, lower_bound, upper_bound; filter_order=14) Signal will be filtered with bandpass butterworth filter between 'lower_bound' and `upper_bound` with filter of `filter_order`. """ function bandpass_filter(x::AbstractArray, lower_bound::Number, upper_bound::Number, sample_rate::Number; filter_order::Int = 14) responsetype = Bandpass(lower_bound, upper_bound; fs=sample_rate) designmethod = Butterworth(filter_order) filt(digitalfilter(responsetype, designmethod), x) end function bandpass_filter(x::SampledSignals.SampleBuf, lower_bound::typeof(1u"Hz"), upper_bound::typeof(1u"Hz"); filter_order::Int = 14) x.data = bandpass_filter(x.data, ustrip(lower_bound), ustrip(upper_bound), x.samplerate, filter_order=filter_order) x end """ amplitude_modulate(data, modulation_frequency, sample_rate; phase=π) Amplitude modulates the signal See [wikipedia](https://en.wikipedia.org/wiki/Amplitude_modulation) """ function amplitude_modulate(x::AbstractArray, modulation_frequency::Number, sample_rate::Number; phase::Number = π) t = 1:size(x, 1) t = t ./ sample_rate fits = mod(maximum(t), (1/modulation_frequency)) if !(isapprox(fits, 0, atol = 1e-5) || isapprox(fits, 1/modulation_frequency, atol = 1e-5) ) @warn("Not a complete modulation") end # println(maximum(t)) # println(1/modulation_frequency) # println(mod(maximum(t), (1/modulation_frequency))) M = 1 .* cos.(2 * π * modulation_frequency * t .+ phase) (1 .+ M) .* x; end function amplitude_modulate(x::SampledSignals.SampleBuf, modulation_frequency::typeof(1u"Hz"); phase::Number = π) amplitude_modulate(x, modulation_frequency * 1.0, phase=phase) end function amplitude_modulate(x::SampledSignals.SampleBuf, modulation_frequency::typeof(1.0u"Hz"); phase::Number = π) x.data = amplitude_modulate(x.data, ustrip(modulation_frequency), x.samplerate, phase=phase) x end """ ITD_modulate(data, modulation_frequency, ITD_1, ITD_2, samplerate) Modulate an applied ITD """ function ITD_modulate(x::AbstractArray, modulation_frequency::Number, ITD_1::Int, ITD_2::Int, sample_rate) @warn "Unvalidated code" t = 1:size(x, 1) t = t ./ sample_rate Ti = 1 / modulation_frequency switches = round.(Int, collect(0:Ti:maximum(t))*sample_rate) switches_starts = switches[1:1:end] switches_stops = switches[2:1:end] switch_samples = switches_stops[1] - switches_starts[1] for idx = 1:2:length(switches_starts)-1 x[switches_starts[idx]+1:switches_stops[idx], 1] = x[switches_starts[idx]+1+ITD_1:switches_stops[idx]+ITD_1, 1] .* tukey(switch_samples, 0.01) x[switches_stops[idx]+1:switches_stops[idx+1], 1] = x[switches_stops[idx]+1+ITD_2:switches_stops[idx+1]+ITD_2, 1] .* tukey(switch_samples, 0.01) end return x end """ set_RMS(data, desired_rms) Modify rms of signal to desired value """ function set_RMS(data::AbstractArray, desired_rms::Number) data / (rms(data) / desired_rms) end """ ramp_on(data, number_samples) Apply a linear ramp to start of signal """ function ramp_on(data::AbstractArray, number_samples::Int) data[1:number_samples, :] = LinRange(0, 1, number_samples) .* data[1:number_samples, :] return data end """ ramp_off(data, number_samples) Apply a linear ramp to end of signal """ function ramp_off(data::AbstractArray, number_samples::Int) data[end-number_samples+1:end, :] = LinRange(1, 0, number_samples) .* data[end-number_samples+1:end, :] return data end """ set_ITD(data, number_samples) Introduce an ITD of number_samples """ function set_ITD(data::AbstractArray, number_samples::Int) abs_number_samples = abs(number_samples) if number_samples > 0 data[:, 1] = [zeros(abs_number_samples, 1); data[1:end - abs_number_samples, 1]] elseif number_samples < 0 data[:, 2] = [zeros(abs_number_samples, 1); data[1:end - abs_number_samples, 2]] end return data end end # module
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
code
4596
using Plots using Statistics """ PlotSpectroTemporal(data, sample_rate) This function plots the time, spectrogram, and periodogram of a signal. """ function PlotSpectroTemporal(x::AbstractArray, sample_rate::Number; figure_size::Tuple=(750, 400), window = hamming, amplitude_limits = nothing, power_limits = nothing, time_limits = nothing, frequency_limits = [0, 1500], correlation_annotate = true, kwargs...) # Generate time vector t = 1:size(x, 1) t = t ./ sample_rate if time_limits == nothing time_limits = [0, maximum(t)] end # Calculate signal transforms spec = spectrogram(x[:, 1], 1024, 256, fs = sample_rate, window = window) peri1 = welch_pgram(x[:, 1], 2048, 512, fs = sample_rate) peri1_power = vector_pow2db(power(peri1)) if size(x, 2)>1; peri2 = welch_pgram(x[:, 2], 2048, 512, fs = sample_rate); end tfft = fft(x[:, 1]) # Extract required stats if isnothing(amplitude_limits) amplitude_limits = maximum(abs.(x)) amplitude_limits = (-amplitude_limits, amplitude_limits) end if isnothing(power_limits) idxs = (freq(peri1) .> frequency_limits[1]) .& (freq(peri1) .< frequency_limits[2]) power_limits = (minimum(peri1_power[idxs]), maximum(peri1_power[idxs])) end # Create plots spec_plot = heatmap(time(spec), freq(spec), power(spec), colorbar = false, xlab = "Time (s)", ylab = "Frequency (Hz)", ylims = frequency_limits, xlims = time_limits) peri_plot = plot(peri1_power, freq(peri1), yticks = [], xlab = "Power (dB)", lab = "", ylims = frequency_limits, xlims = power_limits) if size(x, 2)>1; peri_plot = plot!(vector_pow2db(power(peri2)), freq(peri2), yticks = [], xlab = "Power (dB)", lab = "", ylims = frequency_limits); end time_plot = plot(t, x, xticks = [], leg = false, ylab = "Amplitude", lab = "", ylims = amplitude_limits, xlims = time_limits) corr_plot = histogram(x, orientation = :h, ticks = [], leg = false, framestyle = :none, link = :none, bins=LinRange(amplitude_limits[1], amplitude_limits[2], 15), ylims = amplitude_limits) if ((size(x, 2)>1) & correlation_annotate) maximum_hist_val = maximum(corr_plot.series_list[2].plotattributes[:y][.~isnan.(corr_plot.series_list[2].plotattributes[:y])]) d = annotate!(0, 0.9 * maximum(amplitude_limits), text(string("Corr = ", round(cor(x)[2, 1], digits=3)),:left,8)) d = annotate!(0, -0.9 * maximum(amplitude_limits), text(string("Std = ", round(std(x), digits=3)),:left,8)) end # Return all plots in layout l = Plots.@layout [c{0.6w, 0.3h} d ; a{0.8w} b] return plot(time_plot, corr_plot, spec_plot, peri_plot, layout = l, size = figure_size, link = :none; kwargs...) end function vector_pow2db(a::Vector) for index = 1:size(a, 1) a[index] = pow2db(a[index]) end return a end function plot_cross_correlation(x::T; lags::AbstractQuantity=0u"s") where {T<:SampledSignals.SampleBuf} lags_seconds = lags |> u"s" |> ustrip lags_samples = Int(lags_seconds * x.samplerate) plot_cross_correlation(x.data, lags_samples, x.samplerate) end function plot_cross_correlation(x::T; lags::AbstractQuantity=0u"s") where {T<:DummySampleSink} lags_seconds = lags |> u"s" |> ustrip lags_samples = Int(lags_seconds * x.samplerate) plot_cross_correlation(x.buf, lags_samples, x.samplerate) end """ plot_cross_correlation(x::SampleBuf, lags::Unitful.Time) Plot the cross correlation of a two channel audio signal. Inputs ------ * `x` data in the form of SampledSignals.SampleBuf. Must be two channels of audio. * `lags` time range of lags to be used when plotting the cross correlation function. If lags=0, then the entire function will be used, effecively same as lags=Inf. Example ------- ```julia correlation = 0.6 source = CorrelatedNoiseSource(Float64, 48u"kHz", 2, 0.1, correlation) a = read(source, 3u"s") plot_cross_correlation(a, lags=4u"ms") ``` """ function plot_cross_correlation(x::Array{T, 2}, lags::Int, samplerate::Number) where {T<:Number} if lags == 0 lags = size(x, 1) - 1 end lags = round.(Int, -lags:1:lags) lag_times = lags ./ samplerate lag_times = lag_times .* 1.0u"s" plot(lag_times, crosscor(x[:, 1], x[:, 2], lags), label="", ylab="Cross Correlation", xlab="Lag", ylims=(-1, 1)) end
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
code
2187
""" CorrelatedNoiseSource(eltype, samplerate, nchannels, std, correlation) CorrelatedNoiseSource is a two-channel noise signal generator with controlled correlation between channels. Inputs ------ * `samplerate` specifies the sample rate of the signal. * `nchannels` specifies the number of channels of the signal. * `std` specifies the desired standard deviation of the signal. * `correlation` specifies the desired correlation between the signals. Output ------ * SampleSource object Example ------- ```julia source_object = CorrelatedNoiseSource(Float64, 48000, 2, 0.3, 0.75) cn = read(source_object, 480) # Specify number of samples of signal to generate cn = read(source_object, 50u"ms") # Specify length of time of signal to generate ``` """ mutable struct CorrelatedNoiseSource{T} <: SampleSource samplerate::Float64 nchannels::Int64 cholcov::Array{Float64} function CorrelatedNoiseSource(eltype, samplerate::Number, nchannels::Number, std::Number, corr::Number) @assert nchannels==2 "Only two channels are supported for CorrelatedNoiseSource" if corr < 1 correlation_matrix = [1.0 corr ; corr 1.0] standard_deviation = [std 0.0 ; 0.0 std] covariance_matrix = standard_deviation*correlation_matrix*standard_deviation cholcov = cholesky(covariance_matrix) cholcov = cholcov.U else cholcov = [std std ; 0 0] end new{eltype}(Float64(samplerate), Int64(nchannels), Array{Float64}(cholcov)) end CorrelatedNoiseSource(eltype, samplerate::Unitful.Frequency, nchannels::Number, std::Number, corr::Number) = CorrelatedNoiseSource(eltype, samplerate |> u"Hz" |> ustrip, nchannels, std, corr) end Base.eltype(::CorrelatedNoiseSource{T}) where T = T nchannels(source::CorrelatedNoiseSource) = source.nchannels samplerate(source::CorrelatedNoiseSource) = source.samplerate function unsafe_read!(source::CorrelatedNoiseSource, buf::Array, frameoffset, framecount) buf[1+frameoffset:framecount+frameoffset, 1:source.nchannels] = randn(framecount, source.nchannels) * source.cholcov framecount end
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
code
1883
# This code is from https://github.com/JuliaAudio/SampledSignals.jl/blob/2d078e86489232f77af3696f0ea6d0e34016e7b0/test/support/util.jl # Copyright (c) 2015: Spencer Russell. Released under the MIT "Expat" License. mutable struct DummySampleSink{T} <: SampleSink samplerate::Float64 buf::Array{T, 2} end DummySampleSink(eltype, samplerate::Number, channels::Int) = DummySampleSink{eltype}(samplerate, Array{eltype}(undef, 0, channels)) function DummySampleSink(eltype, samplerate::Union{typeof(1u"Hz"), typeof(1u"kHz"), typeof(1.0u"Hz"), typeof(1.0u"kHz")}, nchannels::Int) samplerate = ustrip(uconvert(u"Hz", samplerate)) DummySampleSink(eltype, samplerate, nchannels) end samplerate(sink::DummySampleSink) = sink.samplerate nchannels(sink::DummySampleSink) = size(sink.buf, 2) Base.eltype(sink::DummySampleSink{T}) where T = T function SampledSignals.unsafe_write(sink::DummySampleSink, buf::Array, frameoffset, framecount) eltype(buf) == eltype(sink) || error("buffer type ($(eltype(buf))) doesn't match sink type ($(eltype(sink)))") nchannels(buf) == nchannels(sink) || error("buffer channel count ($(nchannels(buf))) doesn't match sink channel count ($(nchannels(sink)))") sink.buf = vcat(sink.buf, view(buf, (1:framecount) .+ frameoffset, :)) framecount end # ###################### # Plotting # ###################### PlotSpectroTemporal(x::AuditoryStimuli.DummySampleSink; kwargs...) = PlotSpectroTemporal(x.buf, x.samplerate; kwargs...) function plot(x::AuditoryStimuli.DummySampleSink; xlab::String = "Time (s)", ylab::String = "Amplitude", kwargs...) t = 1:size(x.buf, 1) t = t ./ x.samplerate plot(t, x.buf, xlab = xlab, ylab = ylab; kwargs...) end
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
code
1503
""" NoiseSource(eltype, samplerate, nchannels, std=1) NoiseSource is a multi-channel noise signal generator. The noise on each channel is independent. Inputs ------ * `samplerate` specifies the sample rate of the signal specified in Hz. * `nchannels` specifies the number of channels of the signal. * `std` specifies the desired standard deviation of the signal. Output ------ * SampleSource object Example ------- ```julia source_object = NoiseSource(Float64, 48u"kHz", 2, 0.3) wn = read(source_object, 480) # Specify number of samples of signal to generate wn = read(source_object, 50u"ms") # Specify length of time of signal to generate ``` """ mutable struct NoiseSource{T} <: SampleSource samplerate::Float64 nchannels::Int64 std::Float64 function NoiseSource(eltype, samplerate::Number, nchannels::Int, std::Number=1) new{eltype}(samplerate, nchannels, std) end function NoiseSource(eltype, samplerate::Unitful.Frequency, nchannels::Int, std::Number=1) samplerate = ustrip(uconvert(u"Hz", samplerate)) NoiseSource(eltype, samplerate, nchannels, std) end end Base.eltype(::NoiseSource{T}) where T = T nchannels(source::NoiseSource) = source.nchannels samplerate(source::NoiseSource) = source.samplerate function unsafe_read!(source::NoiseSource, buf::Array, frameoffset, framecount) buf[1+frameoffset:framecount+frameoffset, 1:source.nchannels] = source.std .* randn(framecount, source.nchannels) framecount end
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
code
2129
""" SinusoidSource(eltype, samplerate, freqs) SinusoidSource is a single-channel sine-tone signal generator. `freqs` can be an array of frequencies for a multi-frequency source, or a single frequency for a single sinusoid source. Inputs ------ * `samplerate` specifies the sample rate of the signal. * `freqs` sinusoid frequencies to generate. Output ------ * SampleSource object Example ------- ```julia source_object = SinusoidSource(Float64, 48u"kHz", 200:200:2400) cn = read(source_object, 50u"ms") # Generate 50 ms of harmonic stack audio ``` """ mutable struct SinusoidSource{T} <: SampleSource samplerate::Float64 freqs::Vector{Float64} # in radians/sample phases::Vector{Float64} function SinusoidSource(eltype, samplerate::Number, freqs::Array) # convert frequencies from cycles/sec to rad/sample radfreqs = map(f->2pi*f/samplerate, freqs) new{eltype}(Float64(samplerate), radfreqs, zeros(length(freqs))) end SinusoidSource(eltype, samplerate, freq::StepRange) = SinusoidSource(eltype, samplerate, collect(freq)) SinusoidSource(eltype, samplerate::Number, freq::Real) = SinusoidSource(eltype, samplerate, [freq]) SinusoidSource(eltype, samplerate::Unitful.Frequency, freq::Real) = SinusoidSource(eltype, samplerate |> u"Hz" |> ustrip, [freq]) SinusoidSource(eltype, samplerate::Unitful.Frequency, freq::Array) = SinusoidSource(eltype, samplerate |> u"Hz" |> ustrip, freq) end Base.eltype(::SinusoidSource{T}) where T = T nchannels(source::SinusoidSource) = 1 samplerate(source::SinusoidSource) = source.samplerate function unsafe_read!(source::SinusoidSource, buf::Array, frameoffset, framecount) inc = 2pi / samplerate(source) for i in 1:framecount buf[i+frameoffset, 1] = 0 end for tone_idx in 1:length(source.freqs) tone_freq = source.freqs[tone_idx] tone_phas = source.phases[tone_idx] for i in 1:framecount buf[i+frameoffset, 1] += sin.(tone_phas) tone_phas += tone_freq end source.phases[tone_idx] = tone_phas end framecount end
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
code
1926
using StatsBase """ interaural_coherence(x::SampleBuf, lags::Unitful.Time) Compute the interaural coherence of a two channel sound signals. Interaural coherence (IAC) is commonly defined as the peak of the cross-correlation coefficient of the signals at the two ears [1, 2]. It is commonly computed over a restricted range of `lags` of the cross-correlation function. Inputs ------ * `x` data in the form of SampledSignals.SampleBuf. Must be two channels of audio. * `lags` time range of lags to be used for finding maximum in cross correlation function. If lags=0, then the entire function will be used, effecively same as lags=Inf. References ---------- 1. Chait, M., Poeppel, D., de Cheveigne, A., and Simon, J.Z. (2005). Human auditory cortical processing of changes in interaural correlation. J Neurosci 25, 8518-8527. 2. Aaronson, N.L., and Hartmann, W.M. (2010). Interaural coherence for noise bands: waveforms and envelopes. J Acoust Soc Am 127, 1367-1372. Example ------- ```julia correlation = 0.6 source = CorrelatedNoiseSource(Float64, 48000, 2, 0.1, correlation) a = read(source, 3u"s") @test interaural_coherence(a.data) ≈ correlation atol = 0.025 ``` """ function interaural_coherence(x::T; lags::AbstractQuantity=0u"s")::Float64 where {T<:SampledSignals.SampleBuf} lags_seconds = lags |> u"s" |> ustrip lags_samples = Int(lags_seconds * x.samplerate) interaural_coherence(x.data; lags=lags_samples) end function interaural_coherence(x::T; lags::AbstractQuantity=0u"s")::Float64 where {T<: DummySampleSink} lags_seconds = lags |> u"s" |> ustrip lags_samples = Int(lags_seconds * x.samplerate) interaural_coherence(x.buf; lags=lags_samples) end function interaural_coherence(x::Array{T, 2}; lags::Int=0)::Float64 where {T<:Number} if lags == 0 lags = size(x, 1) - 1 end cc = crosscor(x[:, 1], x[:, 2], -lags:lags) iac = maximum(cc) end
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
code
2282
""" Amplification(target, current, change_limit) Apply amplification to the signal. This modifier allows the user to specify a `target` linear amplification value that will be applied to the signal. The modifier will then change the amplification of the signal until the desired amplification is achieved. The rate at which the amplification can be changed per frame is parameterised by the `change_limit` parameter. To slowly ramp a signal to a desired value set the `target` amplification to the desired value, and the `change_limit` to a small value. To instantly change the signal set the `change_limit` to infinity and modify the `target` value. When initialising the modifier specify the desired starting point using the `current` parameter. You can access the exact amplification at any time by querying the `current` parameter. Inputs ------ * `target` desired linear amplification factor to be applied to signal. * `current` linear amplification currently applied to signal. Also used to specify the intial value for the process. * `change_limit` maximum change that can occur per frame. * `enable` enable the modifier, if false the signal will be passed through without modification. Example ------- ```julia amplify = Amplification(0.1, 0.0, 0.05) attenuated_sound = modify(amplify, original_sound) ``` """ @with_kw mutable struct Amplification target::Float64=0 # Desired scaling factor current::Float64=0 # Current scaling factor change_limit::Float64=Inf # Maximum change in scaling per frame enable::Bool=true # Enable or pass through the signal Amplification(a, b, c, d) = new(a, b, c, d) Amplification(a, b, c) = new(a, b, c, true) Amplification(a, b) = new(a, b, Inf, true) Amplification(a) = new(a, 0, Inf, true) end function modify(sink::Amplification, buf) if sink.enable # Determine if the currect scaling needs to be updated if sink.target != sink.current error = sink.target - sink.current error_sign = sign(error) abs_error = abs(error) sink.current = sink.current + (min(sink.change_limit, abs_error) * error_sign) end buf.data = buf.data .* sink.current end return buf end
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
code
885
using DSP """ Filter(filters) Apply filter to the signal Inputs ------ * `filters` array of DSP filter objects. Example ------- ```julia using DSP responsetype = Bandpass(500, 4000; fs=48000) designmethod = Butterworth(4) zpg = digitalfilter(responsetype, designmethod) f_left = DSP.Filters.DF2TFilter(zpg) f_right = DSP.Filters.DF2TFilter(zpg) bandpass = AuditoryStimuli.Filter([f_left, f_right]) filtered_sound = modify(bandpass, original_sound) ``` """ mutable struct Filter filter::Array{DSP.DF2TFilter, 1} # Filter object enable::Bool num_filters::Int end function Filter(filters::Any) AuditoryStimuli.Filter(filters, true, length(filters)) end function modify(sink::Filter, buf) if sink.enable for idx in 1:sink.num_filters buf.data[:, idx] = DSP.filt(sink.filter[idx], buf.data[:, idx]) end end return buf end
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
code
1504
""" AmplitudeModulation(rate, phase, depth) Apply amplitude modulation to the signal Inputs ------ * `rate` (Hz) desired modulation rate to be applied to signal. * `phase` phase of modulation to be applied to signal applied to signal. Defaults to pi so that modulation starts at a minimum. * `depth` modulation depth. Example ------- ```julia modulate = AmplitudeModulation(1u"Hz") modulated_sound = modify(modulate, original_sound) ``` """ @with_kw mutable struct AmplitudeModulation rate::typeof(1.0u"Hz")=0.0u"Hz" phase::Number=π depth::Number=1 enable::Bool=true time::Float64=0.0 AmplitudeModulation(a::AbstractQuantity, b, c, d, e) = new(a, b, c, d, e) AmplitudeModulation(a::AbstractQuantity, b, c, d) = new(a, b, c, d, 0.0) AmplitudeModulation(a::AbstractQuantity, b, c) = new(a, b, c, true, 0.0) AmplitudeModulation(a::AbstractQuantity, b) = new(a, b, 1, true, 0.0) AmplitudeModulation(a::AbstractQuantity) = new(a, π, 1, true, 0.0) end function AmplitudeModulation(a::Number, args...) @error "You must use units for modulation rate." end function modify(sink::AmplitudeModulation, buf) start_time = sink.time end_time = start_time + (size(buf, 1) / samplerate(buf)) if sink.enable t = range(start_time, stop=end_time, length=size(buf, 1)) M = 1 .* cos.(2 * π * ustrip(sink.rate) * t .+ sink.phase) .* sink.depth buf.data = (1 .+ M) .* buf.data end sink.time = end_time return buf end
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
code
2287
""" TimeDelay(channel, delay, enable, buffer) TimeDelay(channel, delay, enable, buffer; samplerate) Apply a time delay to a specific channel. Inputs ------ * `channel` which channel should have a time delay applied. * `delay` delay to be applied in samples or unit of time. * `enable` should the modifier be enabled. Defaults to true. * `buffer` initial values with which to pad the time delay. Defaults to zeros. * `samplerate` keyword argument required if delay is specified in unit of time. Example ------- ```julia itd = TimeDelay(2, 0.5u"ms", samplerate=48u"kHz") sound_with_itd = modify(itd, original_sound) ``` """ Base.@kwdef mutable struct TimeDelay channel::Int=1 delay::Int=0 enable::Bool=true buffer::Array=[] function TimeDelay(c::Int, d::AbstractQuantity, args...; samplerate::Number) if isa(samplerate, AbstractQuantity) samplerate= samplerate |> u"Hz" |> ustrip end delay_seconds = d |> u"s" |> ustrip delay_samples = delay_seconds * samplerate if round(delay_samples) != delay_samples @info "Not rounded number of samples $delay_samples" delay_samples = round(delay_samples) end delay_samples = Int(delay_samples) TimeDelay(c, delay_samples, args...) end function TimeDelay(c::Int, d::Int, e::Bool, b::Array) d >= 0 || error("Delay must be positive") length(b) == d || error("Length of buffer must match delay") return new(c, d, e, b) end function TimeDelay(c::Int, d::Int, e::Bool) d >= 0 || error("Delay must be positive") buffer = zeros(d, 1) return new(c, d, e, buffer) end function TimeDelay(c::Int, d::Int) d >= 0 || error("Delay must be positive") buffer = zeros(d, 1) return new(c, d, true, buffer) end function TimeDelay(c::Int) return new(c, 0, true, []) end end function modify(sink::TimeDelay, buf) if sink.enable && sink.delay != 0 new_buffer = buf.data[end-sink.delay+1:end, sink.channel] new_data = [sink.buffer; buf.data[1:end - sink.delay, sink.channel]] buf.data[:, sink.channel] = new_data sink.buffer = new_buffer end return buf end
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
code
25064
using AuditoryStimuli using Test using DSP using StatsBase using Statistics using Logging using Plots using Unitful using SampledSignals using Pipe using Images Fs = 48000 ENV["JULIA_DEBUG"] = "all" @testset "Offline Stimuli" begin @testset "Generator Functions" begin # ================================== @testset "One hit signal generation" begin @testset "Bandpass Noise" begin # Test different constructors bn = bandpass_noise(Fs * 30, 2, 300, 700, Fs) # Test data is actuall filtered for lower_bound = 500:500:1500 for upper_bound = 2000:500:3000 bn = bandpass_noise(Fs * 30, 2, lower_bound, upper_bound, Fs) @test size(bn, 1) == Fs * 30 spec = welch_pgram(bn[:, 1], fs=Fs) val, idx_lb = findmin(abs.(freq(spec) .- lower_bound)) val, idx_bl = findmin(abs.(freq(spec) .- (lower_bound - 250))) @test (amp2db(power(spec)[idx_lb]) - amp2db(power(spec)[idx_bl])) > 10 val, idx_ub = findmin(abs.(freq(spec) .- upper_bound)) val, idx_bu = findmin(abs.(freq(spec) .- (upper_bound + 250))) @test (amp2db(power(spec)[idx_ub]) - amp2db(power(spec)[idx_bu])) > 10 end end end end end @testset "Modifier Functions" begin # ================================== @testset "Filter Signals" begin @testset "Bandpass Butterworth" begin @testset "Abstract Arrays" begin # Test data is actuall filtered for lower_bound = 500:500:1500 for upper_bound = 2000:500:3000 x = randn(Fs*30, 2) bn = bandpass_filter(x, lower_bound, upper_bound, Fs) @test size(bn, 1) == Fs * 30 @test size(bn, 2) == 2 for channel = 1:2 spec = welch_pgram(bn[:, channel], fs=Fs) val, idx_lb = findmin(abs.(freq(spec) .- lower_bound)) val, idx_bl = findmin(abs.(freq(spec) .- (lower_bound - 250))) @test (amp2db(power(spec)[idx_lb]) - amp2db(power(spec)[idx_bl])) > 10 val, idx_ub = findmin(abs.(freq(spec) .- upper_bound)) val, idx_bu = findmin(abs.(freq(spec) .- (upper_bound + 250))) @test (amp2db(power(spec)[idx_ub]) - amp2db(power(spec)[idx_bu])) > 10 end end end end @testset "Sampled Signals" begin source = CorrelatedNoiseSource(Float64, 48000, 2, 1, 0.1) a = read(source, 48000) b = bandpass_filter(a, 300u"Hz", 700u"Hz") @test typeof(b) == typeof(a) @test typeof(b) == SampleBuf{Float64,2} end end end @testset "Modulate Signals" begin @testset "Amplitude Modulation" begin @testset "Abstract Arrays" begin for modulation_frequency = 1:1:10 x = randn(Fs, 1) @test_nowarn amplitude_modulate(x, modulation_frequency, Fs) end for modulation_frequency = 1.3:1:10 x = randn(Fs, 1) amplitude_modulate(x, modulation_frequency, Fs) @test_logs (:warn, "Not a complete modulation") amplitude_modulate(x, modulation_frequency, Fs) end end @testset "Sampled Signals" begin source = CorrelatedNoiseSource(Float64, 48000, 2, 1, 0.1) a = read(source, 48000) b = amplitude_modulate(a, 20u"Hz") @test typeof(b) == typeof(a) @test typeof(b) == SampleBuf{Float64,2} end end @testset "ITD Modulation" begin @testset "Abstract Arrays" begin source = CorrelatedNoiseSource(Float64, Fs, 2, 0.3, 0.99) cn = read(source, Fs * 1) bn = bandpass_filter(cn, 300, 700, Fs) mn = amplitude_modulate(bn, 40, Fs) im = ITD_modulate(mn, 8, 24, -24, Fs) source = CorrelatedNoiseSource(Float64, Fs, 2, 0.3, 0.99) cn = read(source, Fs * 1) bn = bandpass_filter(cn, 300, 700, Fs) mn = amplitude_modulate(bn, 40, Fs) im = ITD_modulate(mn, 8, 48, -48, Fs) end end end @testset "RMS" begin @testset "Abstract Arrays" begin for desired_rms = 01:0.1:1 bn = bandpass_noise(Fs * 30, 2, 300, 700, Fs) bn = set_RMS(bn, desired_rms) @test rms(bn) ≈ desired_rms end end @testset "Sampled Signals" begin for desired_rms = 01:0.1:1 source = CorrelatedNoiseSource(Float64, 48000, 2, 1, 0.5) bn = read(source, Fs * 30) bn = set_RMS(bn, desired_rms) @test rms(bn) ≈ desired_rms end end end @testset "Ramps" begin @testset "Ramp on" begin for ramp_length = [1, 2] bn = bandpass_noise(Fs * 5, 2, 300, 700, Fs) bn = ramp_on(bn, Fs * ramp_length) @test rms(bn[1:Fs, :]) < rms(bn[2*Fs:3*Fs, :]) end end @testset "Ramp off" begin for ramp_length = [1, 2] bn = bandpass_noise(Fs * 5, 2, 300, 700, Fs) bn = ramp_off(bn, Fs * ramp_length) @test rms(bn[end-Fs:end, :]) < rms(bn[2*Fs:3*Fs, :]) end end end @testset "ITD" begin for desired_itd = -100:10:100 source = CorrelatedNoiseSource(Float64, Fs, 2, 0.3, 0.9) cn = read(source, Fs * 5) bn = bandpass_filter(cn, 300, 700, Fs) bn = set_ITD(bn, desired_itd) lags = round.(Int, -150:1:150) c = crosscor(bn[:, 2], bn[:, 1], lags) x, idx = findmax(c) @test lags[idx] == desired_itd end end end @testset "Plotting" begin # ======================= @testset "SpectroTempral" begin source = CorrelatedNoiseSource(Float64, Fs, 2, 0.3, 0.99) cn = read(source, Fs * 1) bn = bandpass_filter(cn, 300, 700, Fs) mn = amplitude_modulate(bn, 40, Fs) im = ITD_modulate(mn, 8, 24, -24, Fs) p = PlotSpectroTemporal(im, 48000) @test isa(p, Plots.Plot) == true source = NoiseSource(Float64, 48000, 2, 0.1) sink = DummySampleSink(Float64, 48000, 2) some_data = read(source, 3.0u"s"/frames) @pipe read(source, 3.0u"s"/frames) |> write(sink, _) p = PlotSpectroTemporal(sink) @test isa(p, Plots.Plot) == true p = plot(sink) @test isa(p, Plots.Plot) == true p = plot_cross_correlation(sink) @test isa(p, Plots.Plot) == true p = plot_cross_correlation(sink, lags=0.1u"s") @test isa(p, Plots.Plot) == true p = plot_cross_correlation(some_data) @test isa(p, Plots.Plot) == true end end end # ======================= # Stream Processing # ======================= @testset "Online Stimuli" begin @testset "Generators" begin @testset "NoiseSource generator" begin # Test instansiation source = NoiseSource(Float64, 48.0u"kHz", 2) @test source.samplerate == 48000 @test source.samplerate == samplerate(source) source = NoiseSource(Float64, 48u"kHz", 2) @test source.samplerate == 48000 source = NoiseSource(Float64, 48000u"Hz", 2) @test source.samplerate == 48000 source = NoiseSource(Float64, 48000.1u"Hz", 2) @test source.samplerate == 48000.1 source = NoiseSource(Float64, 44100, 1) @test source.samplerate == 44100 source = NoiseSource(Float64, 48000, 2) @test source.samplerate == 48000 # Test read a = read(source, 48000) @test size(a) == (48000, 2) @test std(a) ≈ 1 atol = 0.01 a = read(source, 1u"s") @test size(a) == (48000, 2) @test std(a) ≈ 1 atol = 0.01 # Test result for deviation = 0.1:0.1:1.3 source = NoiseSource(Float64, 48000, 1, deviation) a = read(source, 48000*3) @test std(a) ≈ deviation atol = 0.01 end end @testset "CorrelatedNoiseSource generator" begin # Test instansiation source = CorrelatedNoiseSource(Float64, 48.0u"kHz", 2, 1, 0.1) @test source.samplerate == 48000 @test source.samplerate == samplerate(source) source = CorrelatedNoiseSource(Float64, 48u"kHz", 2, 1, 1) @test source.samplerate == 48000 source = CorrelatedNoiseSource(Float64, 46u"Hz", 2, 1, 1) @test source.samplerate == 46 source = CorrelatedNoiseSource(Float64, 44100.0u"Hz", 2, 1, 1) @test source.samplerate == 44100 # Test read source = CorrelatedNoiseSource(Float64, 48000, 2, 1, 0.1) a = read(source, 48000) @test size(a) == (48000, 2) @test std(a) ≈ 1 atol = 0.01 # Test behaviour for deviation = 0.1:0.2:1.3 for correlation = 0.0:0.2:1 source = CorrelatedNoiseSource(Float64, 48000, 2, deviation, correlation) a = read(source, 3u"s") @test std(a) ≈ deviation atol = 0.025 @test cor(a.data)[2, 1] ≈ correlation atol = 0.025 @test interaural_coherence(a.data) ≈ correlation atol = 0.025 end end end @testset "Harmonic Complex" begin # Test instansiation source = SinusoidSource(Float64, 48000u"Hz", 2) @test source.samplerate == 48000 source = SinusoidSource(Float64, 48000.7u"Hz", [100, 324, 55, 999]) @test source.samplerate == 48000.7 source = SinusoidSource(Float64, 48000, 300:300:3000) source = SinusoidSource(Float64, 48000, 2000) a = read(source, 48000) @test size(a) == (48000, 1) freqs = collect(200:200:2400.0) source = SinusoidSource(Float64, 48000, freqs) a = read(source, 48000) b = welch_pgram(vec(a.data), fs=a.samplerate) maxs_cart = Images.findlocalmaxima(power(b)) maxs = [idx[1] for idx in maxs_cart] maxs = maxs[power(b)[maxs] .> 0.02] @test freq(b)[maxs] == freqs end end @testset "Modifiers" begin @testset "Input / Output" begin desired_rms = 0.3 for num_channels = 1:2 for frames = [100, 50, 20] source = NoiseSource(Float64, Fs, num_channels, desired_rms) sink = DummySampleSink(Float64, 48000, num_channels) for idx = 1:frames @pipe read(source, 1.0u"s"/frames) |> write(sink, _) end @test size(sink.buf, 1) == 48000 @test size(sink.buf, 2) == num_channels @test rms(sink.buf) ≈ desired_rms atol = 0.01 end end source = NoiseSource(Float64, 96000u"Hz", 2, 0.1) @test source.samplerate == 96000 source = NoiseSource(Float64, 96u"kHz", 2) @test source.samplerate == 96000 sink = DummySampleSink(Float64, 48000u"Hz", 3) @test sink.samplerate == 48000 sink = DummySampleSink(Float64, 48000.0u"Hz", 3) @test sink.samplerate == 48000 sink = DummySampleSink(Float64, 48u"kHz", 4) @test sink.samplerate == 48000 sink = DummySampleSink(Float64, 48.0u"kHz", 4) @test sink.samplerate == 48000 end @testset "Amplification" begin # Test different ways of instanciating the modifier @test Amplification().target == 0 @test Amplification().current == 0 @test Amplification().change_limit == Inf @test Amplification().enable == true @test Amplification(1).target == 1.0 @test Amplification(1, 3).target == 1.0 @test Amplification(1, 3).current == 3.0 @test Amplification(1, 3, 4, false).change_limit == 4.0 @test Amplification(1, 3, 4, false).enable == false @test Amplification(target=3).target == 3 @test Amplification(current=3).current == 3 @test Amplification(change_limit=3).change_limit == 3 @test Amplification(enable=false).enable == false @test Amplification(enable=false, current=2).enable == false @test Amplification(enable=false, current=2).current == 2 # Ensure disabled does nothing source = NoiseSource(Float64, 48000, 2, 1) sink = DummySampleSink(Float64, 48000, 2) amp = Amplification(2, 3, 0.5, false) data = read(source, 1u"s") @pipe data |> modify(amp, _) |> write(sink, _) @test sink.buf == data.data desired_rms = 0.3 amp_mod = 0.1 num_channels = 1 @testset "Static" begin source = NoiseSource(Float64, Fs, num_channels, desired_rms) sink = DummySampleSink(Float64, 48000, num_channels) amp = Amplification(amp_mod, amp_mod, 0.005) for idx = 1:200 @pipe read(source, 0.01u"s") |> modify(amp, _) |> write(sink, _) end @test size(sink.buf, 1) == 96000 @test size(sink.buf, 2) == num_channels @test rms(sink.buf) ≈ desired_rms * amp_mod atol = 0.01 end @testset "Dynamic" begin source = NoiseSource(Float64, Fs, num_channels, desired_rms) sink = DummySampleSink(Float64, 48000, num_channels) amp = Amplification(target=amp_mod, current=amp_mod, change_limit=0.5) for idx = 1:200 if idx == 100 setproperty!(amp, :target, 1.0) end @pipe read(source, 0.01u"s") |> modify(amp, _) |> write(sink, _) end @test size(sink.buf, 1) == 96000 @test size(sink.buf, 2) == num_channels @test rms(sink.buf[1:48000]) ≈ desired_rms * amp_mod atol = 0.01 @test rms(sink.buf[48000:96000]) ≈ desired_rms atol = 0.01 end end @testset "Filtering" begin desired_rms = 0.3 amp_mod = 0.1 for num_channels = 1:2 @testset "Channels: $num_channels" begin source = NoiseSource(Float64, Fs, num_channels, desired_rms) sink = DummySampleSink(Float64, Fs, num_channels) lower_bound = 1000 upper_bound = 4000 responsetype = Bandpass(lower_bound, upper_bound; fs=Fs) designmethod = Butterworth(14) zpg = digitalfilter(responsetype, designmethod) f1 = DSP.Filters.DF2TFilter(zpg) f2 = DSP.Filters.DF2TFilter(zpg) filters = [f1] if num_channels == 2; filters = [filters[1], f2]; end bandpass = AuditoryStimuli.Filter(filters) for idx = 1:500 @pipe read(source, 0.01u"s") |> modify(bandpass, _) |> write(sink, _) end @test size(sink.buf, 1) == 48000 * 5 @test size(sink.buf, 2) == num_channels for chan = 1:num_channels spec = welch_pgram(sink.buf[:, chan], 12000, fs=Fs) val, idx_lb = findmin(abs.(freq(spec) .- lower_bound)) val, idx_bl = findmin(abs.(freq(spec) .- (lower_bound - 500))) @test (amp2db(power(spec)[idx_lb]) - amp2db(power(spec)[idx_bl])) > 10 val, idx_ub = findmin(abs.(freq(spec) .- upper_bound)) val, idx_bu = findmin(abs.(freq(spec) .- (upper_bound + 500))) @test (amp2db(power(spec)[idx_ub]) - amp2db(power(spec)[idx_bu])) > 10 end # Test turning filter off setproperty!(bandpass, :enable, false) for idx = 1:1500 @pipe read(source, 0.01u"s") |> modify(bandpass, _) |> write(sink, _) end @test size(sink.buf, 1) == 48000 * 20 @test size(sink.buf, 2) == num_channels for chan = 1:num_channels spec = welch_pgram(sink.buf[48000* 5:48000*20, chan], 12000, fs=Fs) val, idx_lb = findmin(abs.(freq(spec) .- lower_bound)) val, idx_bl = findmin(abs.(freq(spec) .- (lower_bound - 500))) @test (amp2db(power(spec)[idx_lb]) - amp2db(power(spec)[idx_bl])) < 6 val, idx_ub = findmin(abs.(freq(spec) .- upper_bound)) val, idx_bu = findmin(abs.(freq(spec) .- (upper_bound + 500))) @test (amp2db(power(spec)[idx_ub]) - amp2db(power(spec)[idx_bu])) < 6 end end end end @testset "Amplitude Modulation" begin for num_channels = 1:5 @testset "Channels: $num_channels" begin source = NoiseSource(Float64, Fs, num_channels) sink = DummySampleSink(Float64, 48000, num_channels) am = AmplitudeModulation(10u"Hz") for idx = 1:10 @pipe read(source, 0.01u"s") |> modify(am, _) |> write(sink, _) end @test size(sink.buf, 1) == 4800 @test size(sink.buf, 2) == num_channels start_mod = Statistics.sum(abs.(sink.buf[1:1000, :])) mid_mod = Statistics.sum(abs.(sink.buf[2000:3000, :])) end_mod = Statistics.sum(abs.(sink.buf[3800:4800, :])) @test mid_mod > start_mod @test mid_mod > end_mod # Test different ways of instanciating the modifier @test AmplitudeModulation(1u"MHz").rate == 1000000u"Hz" @test AmplitudeModulation(1u"kHz").rate == 1000u"Hz" @test AmplitudeModulation(1u"mHz").rate == 0.001u"Hz" @test AmplitudeModulation(10u"Hz").rate == 10u"Hz" @test AmplitudeModulation(1.0u"Hz").rate == 1u"Hz" @test AmplitudeModulation(10u"Hz", 0.0).rate == 10u"Hz" @test AmplitudeModulation(10.3u"Hz", 0.0).rate == 10.3u"Hz" @test AmplitudeModulation(10u"Hz", π).rate == 10u"Hz" @test AmplitudeModulation(10u"Hz", π, 0.0).rate == 10u"Hz" @test AmplitudeModulation(10u"Hz", π, 0.5).rate == 10u"Hz" @test AmplitudeModulation(10.8u"Hz", π, 0.5).rate == 10.8u"Hz" @test AmplitudeModulation(1.0u"kHz", π, 1.5).rate == 1000u"Hz" @test AmplitudeModulation(1.0u"kHz", π, 1.5, false).enable == false @test AmplitudeModulation(10u"Hz", π, 1.5).depth == 1.5 @test AmplitudeModulation(rate=3u"Hz").rate == 3.0u"Hz" @test AmplitudeModulation(phase=3).phase == 3 @test AmplitudeModulation(depth=0.5).depth == 0.5 # Test defaults @test AmplitudeModulation().rate == 0u"Hz" @test AmplitudeModulation().phase == π @test AmplitudeModulation().depth == 1 @test AmplitudeModulation().enable == true @test AmplitudeModulation().time == 0 # Test bad instansiation @test_logs (:error, "You must use units for modulation rate.") AmplitudeModulation(33) # Ensure disabled does nothing sink = DummySampleSink(Float64, 48000, num_channels) amp = AmplitudeModulation(enable=false) data = read(source, 1u"s") @pipe data |> modify(amp, _) |> write(sink, _) @test sink.buf == data.data end end end @testset "ITD" begin # Test instansiation @test TimeDelay().channel == 1 @test TimeDelay(2).channel == 2 @test TimeDelay(1, 22).delay == 22 @test TimeDelay(1, 22, false).delay == 22 @test TimeDelay(1, 22, false, ones(22, 1)).buffer == ones(22, 1) @test TimeDelay(delay=33, buffer=zeros(33, 1)).delay == 33 @test TimeDelay(channel=33).channel == 33 @test TimeDelay(enable=false, channel=3).channel == 3 @test TimeDelay(enable=false, channel=3).enable == false @test TimeDelay(2, 0.5u"ms", samplerate=48u"kHz").delay == 24 @test TimeDelay(2, 1u"ms", samplerate=48u"kHz").delay == 48 @test_logs (:info, "Not rounded number of samples 23.04") TimeDelay(2, 0.48u"ms", samplerate=48u"kHz") # Test correct behaiour for desired_itd = -100:10:100 source = CorrelatedNoiseSource(Float64, 48000, 2, 0.3, 1) if desired_itd >= 0 itd = TimeDelay(2, desired_itd) else itd = TimeDelay(1, -desired_itd) end sink = DummySampleSink(Float64, 48000, 2) for idx = 1:10 @pipe read(source, 0.1u"s") |> modify(itd, _) |> write(sink, _) end lags = round.(Int, -150:1:150) c = crosscor(sink.buf[:, 1], sink.buf[:, 2], lags) x, idx = findmax(c) @test lags[idx] == desired_itd end end end end @testset "Signal Metrics" begin @testset "Interaural Coherence" begin for correlation = 0.2:0.2:0.8 source = CorrelatedNoiseSource(Float64, 48000, 2, 0.4, correlation) a = read(source, 3u"s") @test interaural_coherence(a.data) ≈ correlation atol = 0.025 @test interaural_coherence(a.data, lags=100) ≈ correlation atol = 0.025 @test interaural_coherence(a) ≈ correlation atol = 0.025 @test interaural_coherence(a, lags=1u"s") ≈ correlation atol = 0.025 @test interaural_coherence(a, lags=1.0u"s") ≈ correlation atol = 0.025 @test interaural_coherence(a, lags=900u"ms") ≈ correlation atol = 0.025 end # Test still works when ITD applied correlation = 0.5 delay_samples = 100 delay_time = (delay_samples / 48000)u"s" source = CorrelatedNoiseSource(Float64, 48000, 2, 0.4, correlation) itd = TimeDelay(1, 22) sink = DummySampleSink(Float64, 48000, 2) @pipe read(source, 3u"s") |> modify(itd, _) |> write(sink, _) @test interaural_coherence(sink) ≈ correlation atol = 0.025 @test interaural_coherence(sink, lags=2*delay_time) ≈ correlation atol = 0.025 # Whereas if the range of lags doesnt encompas the maximum the iac will be # less than the global maximum @test interaural_coherence(sink, lags=0.1*delay_time) < (correlation - 0.1) end end
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
docs
1166
# Contributing to AuditoryStimuli.jl I warmly welcome any contributions from the community. This may take the form of feedback via the issues list, bug reports (also via the issues list), code submission (via pull requests). Please feel free to suggest features, or additional stimuli you are interested in. Or if you just want to show support, click the star button at the top of the page. This repository makes extensive use of GitHub actions. When you submit a pull request the continuous integration will kick in to gear. The code in your pull request will then be automatically tested against several version of Julia, and on several operating systems to ensure that it doesn't break anything. Additionally the documentation will be rebuilt based on your pull request. This will allow you to check that it renders correctly and your changes are realised. Further, a spell check will be performed on the pull request. Don't be disheartened if the continuous integration results come back with a red cross initially. You can push further changes to fix any issues that arise. And if you get stuck just ping @rob-luke and we will solve the issues together.
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
docs
1792
# AuditoryStimuli.jl goes beep and ssshhh ![Tests](https://github.com/rob-luke/AuditoryStimuli.jl/workflows/Tests/badge.svg) [![codecov.io](http://codecov.io/github/rob-luke/AuditoryStimuli.jl/coverage.svg?branch=master)](http://codecov.io/github/rob-luke/AuditoryStimuli.jl?branch=master) [![DOI](https://joss.theoj.org/papers/10.21105/joss.03613/status.svg)](https://doi.org/10.21105/joss.03613) Generate auditory stimuli for real-time applications. Specifically, stimuli that are used in auditory research. ## Stimuli This package provides low levels tools to build any stimulus. It also provides high level convenience functions and examples for common stimuli such as: * Amplitude modulated noise * Harmonic stacks or harmonic complexes * Binaural stimuli with user specified interaural correlation * Frequency following response stimuli * and more... ## Documentation https://rob-luke.github.io/AuditoryStimuli.jl ## Community guidelines I warmly welcome any contributions from the community. This may take the form of feedback via the issues list, bug reports (also via the issues list), code submission (via pull requests). Please feel free to suggest features, or additional stimuli you are interested in. Or if you just want to show support, click the star button at the top of the page. ## Acknowledgements This package is built on top of the excellent packages: * [SampledSignals](https://github.com/JuliaAudio/SampledSignals.jl) * [Unitful](https://github.com/ajkeller34/Unitful.jl) * [Plots](https://github.com/JuliaPlots/Plots.jl) If you use this package please cite: ```text Luke, R., (2021). AuditoryStimuli.jl: A Julia package for generating real-time auditory stimuli. Journal of Open Source Software, 6(65), 3613, https://doi.org/10.21105/joss.03613 ```
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
docs
705
--- name: Bug report about: Tell us about broken, incorrect, or inconsistent behavior. title: '' labels: BUG assignees: '' --- #### Describe the bug *Replace this text with a description of the bug.* #### Steps to reproduce *Replace this text with a code snippet or minimal working example [MWE] to replicate your problem. [MWE]: https://en.wikipedia.org/wiki/Minimal_Working_Example #### Expected results *Replace this text with a description of what you expected to happen.* #### Actual results *Replace this text with the actual output, traceback, screenshot, or other description of the results.* #### Additional information *Replace this text with the output of `using Pkg; Pkg.status()`.*
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
docs
522
--- name: Documentation about: Request a new tutorial, an improvement to an existing tutorial, or a new term in our glossary. title: '' labels: DOC assignees: '' --- *Please make the issue title a succinct description of your proposed change. For example: "add 'foo' to the glossary" or "add my favorite visualization to the signal in noise example".* #### Proposed documentation ehancement *Describe your proposed enhancement in detail. If you are requesting a new glossary term, please include a proposed definition.*
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
docs
853
--- name: Feature request about: Suggest additions or improvements to AuditoryStimuli.jl. title: '' labels: ENH assignees: '' --- #### Describe the new feature or enhancement *Please provide a clear and concise description of what you want to add or change.* #### Describe your proposed implementation *Describe how you think the feature or improvement should be implemented (e.g., as a new type on an existing type? as new capability added to an existing method?) If you're not sure, please delete this section and the next section.* #### Describe possible alternatives *If you've suggested an implementation above, list here any alternative implementations you can think of, and brief comments explaining why the chosen implementation is better.* #### Additional comments *Add any other context or screenshots about the feature request here.*
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
docs
634
# Advanced Usage The introduction provides a simple example but for efficient use the following considerations may be required. ## Threading Running the audio stream in its own thread so you can process user input or run other code in parallel. This is easily accomplished using `@spawn`, see: [example](https://github.com/rob-luke/AuditoryStimuli.jl/blob/master/examples/test_streamer.jl). ## Enabling/Disabling pipeline components Enable or disable processing rather than modifying the pipeline. Each modifier has an enable flag so that it can be disabled, when disabled the signal is simply passed through and not modified.
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
docs
590
# Library --- ```@meta CurrentModule = AuditoryStimuli ``` ## Module ```@docs AuditoryStimuli ``` ## Signal generators ```@docs NoiseSource CorrelatedNoiseSource SinusoidSource ``` ## Online signal modifiers ```@docs Amplification AuditoryStimuli.Filter AmplitudeModulation TimeDelay ``` ## Offline Signal modifiers ```@docs ramp_on ramp_off ``` ## Plotting ```@docs PlotSpectroTemporal plot_cross_correlation ``` ## Signal Metrics ```@docs interaural_coherence ``` ## Depreciated ```@docs bandpass_noise bandpass_filter amplitude_modulate ITD_modulate set_RMS set_ITD ```
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
docs
1868
# Example: Bandpass Noise In this example we geneate a bandpass noise signal. This common stimulus is used for determining hearing thresholds. ### Realtime Example In this example we process the audio in 10 millisecond frames. ```@example realtime using AuditoryStimuli, Unitful, Plots, Pipe, DSP default(size=(700, 300)) # hide using DisplayAs # hide # Specify the source, modifiers, and sink of our audio pipeline source = NoiseSource(Float64, 48u"kHz", 1) sink = DummySampleSink(Float64, 48u"kHz", 1) # Design the filter responsetype = Bandpass(300, 700; fs=48000) designmethod = Butterworth(14) zpg = digitalfilter(responsetype, designmethod) f_left = DSP.Filters.DF2TFilter(zpg) bp = AuditoryStimuli.Filter([f_left]) # Run real time audio processing for frame = 1:100 @pipe read(source, 0.01u"s") |> modify(bp, _) |> write(sink, _) end # Validate the audio pipeline output PlotSpectroTemporal(sink, frequency_limits = [0, 4000]) current() |> DisplayAs.PNG # hide ``` ### Offline Example It is also possible to generate the audio in an offline (all in one step) manner. This may be useful for creating wav files for use in simpler experiments. ```@example offline using AuditoryStimuli, Unitful, Plots, DSP, WAV default(size=(700, 300)) # hide using DisplayAs # hide # Specify the source, modifiers, and sink of our audio pipeline source = NoiseSource(Float64, 48u"kHz", 2, 0.2) # Design the filter responsetype = Bandpass(500, 4000; fs=48000) designmethod = Butterworth(4) zpg = digitalfilter(responsetype, designmethod) f_left = DSP.Filters.DF2TFilter(zpg) f_right = DSP.Filters.DF2TFilter(zpg) bp = AuditoryStimuli.Filter([f_left, f_right]) # Run real time audio processing audio = read(source, 1.0u"s") modulated_audio = modify(bp, audio) # Write the audio to disk as a wav file wavwrite(modulated_audio.data, "BP-noise.wav",Fs=48000) ```
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
docs
1812
# Example: Harmonic Stack Complex Harmonic stacks are often used to investigate pitch processing and streaming/grouping. Harmonic complexes contain a set of frequency components which are harmonics. In this example we generate a harmonic stack which is modulated at 15 Hz. ### Realtime Example In this example we process the audio in 10 millisecond frames. ```@example realtime using AuditoryStimuli, Unitful, Plots, Pipe, DSP default(size=(700, 300)) # hide using DisplayAs # hide # Specify the source, modifiers, and sink of our audio pipeline stack_frequencies = 200:200:2400 source = SinusoidSource(Float64, 48u"kHz", stack_frequencies) amp = Amplification(current=1/length(stack_frequencies), target=1/length(stack_frequencies), change_limit=1) am = AmplitudeModulation(15u"Hz") sink = DummySampleSink(Float64, 48u"kHz", 1) # Run real time audio processing for frame = 1:100 @pipe read(source, 0.01u"s") |> modify(amp, _) |> modify(am, _) |> write(sink, _) end # Validate the audio pipeline output PlotSpectroTemporal(sink, frequency_limits = [0, 3000], time_limits = [0.135, 0.33]) current() |> DisplayAs.PNG # hide ``` ### Offline Example It is also possible to generate the audio in an offline (all in one step) manner. This may be useful for creating wav files for use in simpler experiments. ```@example offline using AuditoryStimuli, Unitful, Plots, WAV default(size=(700, 300)) # hide using DisplayAs # hide stack_frequencies = 200:200:2400 source = SinusoidSource(Float64, 48u"kHz", stack_frequencies) am = AmplitudeModulation(15u"Hz") audio = read(source, 1.0u"s") modulated_audio = modify(am, audio) # Write the audio to disk as a wav file wavwrite(modulated_audio.data ./ length(stack_frequencies), "harmonic-stack.wav",Fs=48000) ```
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
docs
3438
# Example: Interaural Time Delay Stimuli with a delay applied to one ear causes the sound to be perceived as coming from a different direction [1]. These stimuli are commonly used to investigate source localisation algorithms [2]. [1] Grothe, Benedikt, Michael Pecka, and David McAlpine. "Mechanisms of sound localization in mammals." Physiological reviews 90.3 (2010): 983-1012. [2] Luke, R., & McAlpine, D. (2019, May). A spiking neural network approach to auditory source lateralisation. In ICASSP 2019-2019 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP) (pp. 1488-1492). IEEE. Chicago ### Realtime Example: Broadband Signal In this example we apply a 0.5 ms delay to the second channel (right ear). When presented over headphones this causes the sound to be perceived as arriving from the left, as the sound arrives at the left ear first. ```@example realtime using AuditoryStimuli, Unitful, Plots, Pipe, DSP default(size=(700, 300)) # hide using DisplayAs # hide source = CorrelatedNoiseSource(Float64, 48u"kHz", 2, 0.2, 1) itd_left = TimeDelay(2, 0.5u"ms", samplerate=48u"kHz") sink = DummySampleSink(Float64, 48u"kHz", 2) for frame = 1:100 @pipe read(source, 1/100u"s") |> modify(itd_left, _) |> write(sink, _) end # Validate the audio pipeline output plot(sink, label=["Left" "Right"]) current() |> DisplayAs.PNG # hide ``` The stimulus output can be validated by observing that the peak in the cross correlation function occurs at 0.5 ms. ```@example realtime plot_cross_correlation(sink, lags=2u"ms") current() |> DisplayAs.PNG # hide ``` ### Realtime Example: Narrowband Signal If we desire a narrowband signal with reduced coherence then we can still use the same functional blocks. ```@example realtime source = CorrelatedNoiseSource(Float64, 48u"kHz", 2, 0.2, 0.6) responsetype = Bandpass(300, 700; fs=48000) designmethod = Butterworth(14) zpg = digitalfilter(responsetype, designmethod) f_left = DSP.Filters.DF2TFilter(zpg) f_right = DSP.Filters.DF2TFilter(zpg) bp = AuditoryStimuli.Filter([f_left, f_right]) itd_left = TimeDelay(2, 1.25u"ms", samplerate=48u"kHz") sink = DummySampleSink(Float64, 48u"kHz", 2) for frame = 1:1000 @pipe read(source, 1/100u"s") |> modify(bp, _) |> modify(itd_left, _) |> write(sink, _) end plot(sink, label=["Left" "Right"]) current() |> DisplayAs.PNG # hide ``` As expected the cross-correlation function will now be damped, but the peak should still be equal to the correlation of the signals, and the peak shift should correspond to the applied time delay. ```@example realtime plot_cross_correlation(sink, lags=4u"ms") current() |> DisplayAs.PNG # hide ``` And we can use the convenience function to determine the interaural coherence (IAC) of the signal, which should be approximately 0.6 as set above. ```@example realtime interaural_coherence(sink) ``` Whereas if we used the naive correlation implementation from StatsBase we would be extracting the cross correlation value at zero. ```@example realtime using Statistics cor(sink.buf)[2, 1] ``` However, note that if we compute the IAC over a restricted range of lags then we will miss the peak and thus not report the global maximum. By default, as above, the entire range of available lags is used. So if we use only a 1 ms window, whereas the itd was 1.25 ms, the IAC will be under reported. ```@example realtime interaural_coherence(sink, lags=1u"ms") ```
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
docs
2259
# Example: Interaural Time Delay Modulation This stimuli has an ITD that is modulated from the left to right. This stimulus is used to elicit an interaural time delay following response, which has been related to spatial listening performance [1]. [1] Undurraga, J. A., Haywood, N. R., Marquardt, T., & McAlpine, D. (2016). Neural representation of interaural time differences in humans—An objective measure that matches behavioural performance. Journal of the Association for Research in Otolaryngology, 17(6), 591-607. ### Realtime Example This example contains several processing steps and a dynamically changing pipeline. A signal is generated which is identical in two channels. This signal is then bandpass filtered between 300 and 700 Hz, and is then modulated at 20 Hz. At the minimum of each modulation the ITD is switched from left to right leading with a 48 sample delay. ```@example realtime using AuditoryStimuli, Unitful, Plots, Pipe, DSP default(size=(700, 300)) # hide using DisplayAs # hide # Specify the source, modifiers, and sink of our audio pipeline source = CorrelatedNoiseSource(Float64, 48u"kHz", 2, 0.2, 1) sink = DummySampleSink(Float64, 48u"kHz", 2) am = AmplitudeModulation(20u"Hz") # Design the filter responsetype = Bandpass(300, 700; fs=48000) designmethod = Butterworth(14) zpg = digitalfilter(responsetype, designmethod) f_left = DSP.Filters.DF2TFilter(zpg) f_right = DSP.Filters.DF2TFilter(zpg) bp = AuditoryStimuli.Filter([f_left, f_right]) itd_left = TimeDelay(2, 1u"ms", true, samplerate=48u"kHz") itd_right = TimeDelay(1, 1u"ms", false, samplerate=48u"kHz") # Run real time audio processing for frame = 1:4 @pipe read(source, 1/20u"s") |> modify(bp, _) |> modify(am, _) |> modify(itd_left, _) |> modify(itd_right, _) |> write(sink, _) # For each modulation cycle switch between left and right leading ITD itd_left.enable = !itd_left.enable itd_right.enable = !itd_right.enable end # Validate the audio pipeline output plot(sink, label=["Left" "Right"]) current() |> DisplayAs.PNG # hide ``` In the figure above we observe that in the first and third modulation the signal is left leading, and that in the second and fourth cycle the signal is right leading.
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
docs
1292
# Example: Signal and Noise This example demonstrates how to produce a signal of interest and an additive noise signal. The noise signal is only applied during a specified time window. ### Realtime Example ```@example realtime using AuditoryStimuli, Unitful, Plots, Pipe, DSP default(size=(700, 300)) # hide using DisplayAs # hide # Specify the source, modifiers, and sink of our audio pipeline source = NoiseSource(Float64, 48u"kHz", 1, 1) noisesource = NoiseSource(Float64, 48u"kHz", 1, 1) sink = DummySampleSink(Float64, 48u"kHz", 1) am = AmplitudeModulation(40u"Hz") # Design the filter responsetype = Bandpass(1500, 2500; fs=48000) designmethod = Butterworth(14) zpg = digitalfilter(responsetype, designmethod) f_left = DSP.Filters.DF2TFilter(zpg) bp = AuditoryStimuli.Filter([f_left]) # Run real time audio processing for frame = 1:100 # Generate the signal of interest output = @pipe read(source, 0.01u"s") |> modify(bp, _) |> modify(am, _) # During 0.3-0.7s add a white noise to the output if 30 < frame < 70 output += read(noisesource, 0.01u"s") end # Write the output to device write(sink, output) end # Validate the audio pipeline output PlotSpectroTemporal(sink, frequency_limits = [0, 4000]) current() |> DisplayAs.PNG # hide ```
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
docs
1681
# Example: Amplitude Modulated Noise In this example we geneate a white noise signal which is modualted at 40 Hz. These signals are commonly used to ellicit auditory steady-state responses [1]. [1] Luke, R., Van Deun, L., Hofmann, M., Van Wieringen, A., & Wouters, J. (2015). Assessing temporal modulation sensitivity using electrically evoked auditory steady state responses. Hearing research, 324, 37-45. ### Realtime Example In this example we process the audio in 10 millisecond frames. ```@example realtime using AuditoryStimuli, Unitful, Plots, Pipe, DSP default(size=(700, 300)) # hide using DisplayAs # hide # Specify the source, modifiers, and sink of our audio pipeline source = NoiseSource(Float64, 48u"kHz", 1, 0.2) sink = DummySampleSink(Float64, 48u"kHz", 1) am = AmplitudeModulation(40u"Hz") # Run real time audio processing for frame = 1:100 @pipe read(source, 0.01u"s") |> modify(am, _) |> write(sink, _) end # Validate the audio pipeline output plot(sink, label="") current() |> DisplayAs.PNG # hide ``` ### Offline Example It is also possible to generate the audio in an offline (all in one step) manner. This may be useful for creating wav files for use in simpler experiments. ```@example offline using AuditoryStimuli, Unitful, Plots, WAV default(size=(700, 300)) # hide using DisplayAs # hide # Specify the source, modifiers, and sink of our audio pipeline source = NoiseSource(Float64, 48u"kHz", 1, 0.2) am = AmplitudeModulation(40u"Hz") # Run real time audio processing audio = read(source, 1.0u"s") modulated_audio = modify(am, audio) # Write the audio to disk as a wav file wavwrite(modulated_audio.data, "AM-noise.wav",Fs=48000) ```
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
docs
445
# AuditoryStimuli.jl A [Julia](http://julialang.org) package for generating auditory stimuli. --- ### Installation To install this package enter the package manager by pressing `]` at the julia prompt and enter: ```julia pkg> add AuditoryStimuli ``` ### Overview This package provides a framework for generating audio in real time. It can also be used to generate audio offline. Tutorials and examples are provided for both approaches.
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.1.4
f22064ca0431e912ad5e41f2697df1f5e722e0b5
docs
6319
# Real-Time Audio Processing In this tutorial the basics of real-time audio processing are introduced, and how you can generate real time audio with this package. It is common to process audio in small chunks of samples called frames. This is more efficient than processing signals on a sample by sample basis, yet allows dynamic adaptation of the audio signal. In this example we use a frame size of 1/100th of a second, or 480 samples when using a sample rate of 48 kHz. However, the frame size can be adjusted to suit your research needs. Real-time processing consists of a source, zero or more modifiers, and a sink. Sources generate the raw signal. Modifiers alter the signal. Sinks are a destination for the signals, typically a sound card, but in this example we use a buffer. First the required packages are loaded and the sample rate and number of audio channels is specified. This package makes extensive use of units to minimise the chance of coding mistakes, below the sample rate is specified in the unit of kHz. ```@example realtime using AuditoryStimuli, Unitful, Plots, Pipe, DSP using DisplayAs # hide sample_rate = 48u"kHz" audio_channels = 2 source_rms = 0.2 default(size=(700, 300)) # hide ``` ## Set up the signal pipeline components First we need a source. In this example a simple white noise source is used. The type of data (floats) is specified, as is the the sample rate, number of channels, and the RMS of each channel. ```@example realtime source = NoiseSource(Float64, sample_rate, audio_channels, source_rms) nothing # hide ``` A sink is also required. This would typically be a sound card, but that is not possible with a web page tutorial. Instead, for this website example a dummy sink is used, which simply saves the sample to a buffer. Dummy sink are also useful for validating our generated stimuli, as we can measure and plot the output. ```@example realtime sink = DummySampleSink(Float64, sample_rate, audio_channels) # But on a real system you would use something like # devices = PortAudio.devices() # println(devices) # sink = PortAudioStream(devices[3], sample_rate, audio_channels) ``` In this example a single signal modifier is used. This signal modifier simply adjusts the amplitude of the signal with a linear scaling. We specify the desired linear amplification to be 1.0, so no modification to the amplitude. However, we do not want the signal to jump from silent to full intensity, so we specify the current value of the amplitude as 0 (silent) and set the maximum increase per frame to be 0.05. This will ramp the signal from silent to full intensity. ```@example realtime amp = Amplification(current=0.0, target=1.0, change_limit=0.05) nothing # hide ``` ## Run the real-time audio pipeline To run the real-time processing we generate a pipeline and run it. We use the `pipe` notation to conveniently describe the audio pipeline. In this simple example we read a frame with duration 1/100th of a second from the source. The frame of white noise is piped through the amplitude modifier, and then piped in to the sink. Modifiers always take the modification object as the first argument, followed by an underscore to represent the piped data. Similarly, when writing the data to a sink, the sink is always the first argument, followed by an underscore to represent the piped data. The pipeline is run 100 times, resulting in 1 second of generated audio. ```@example realtime for frame = 1:100 @pipe read(source, 0.01u"s") |> modify(amp, _) |> write(sink, _) end ``` ## Verify processing was correctly applied We can plot the data from sink (as it was a DummySink, which is simply a buffer) to confirm the signal generated matches our expectations. As expected, we see below that two channels of audio are generated, that the signal is 1 second long, and that there is a ramp applied to the onset. ```@example realtime plot(sink) current() |> DisplayAs.PNG # hide ``` ## Apply a filter modifier A more advanced application is to use a filter as a modifier. The filter maintains its state between calls, so can be used for real-time audio processing. Below a bandpass filter is designed, for more details on filter design using the DSP package see [this documentation](https://docs.juliadsp.org/stable/filters/). ```@example realtime responsetype = Bandpass(500, 4000; fs=48000) designmethod = Butterworth(4) zpg = digitalfilter(responsetype, designmethod) nothing # hide ``` Once the filter is specified as a zero pole gain representation two filters are instantiated using this specification. A filter must be generated for each channel of audio. These DSP.Filters are then passed in to the AuditoryStimuli filter object for further use. ```@example realtime f_left = DSP.Filters.DF2TFilter(zpg) f_right = DSP.Filters.DF2TFilter(zpg) bandpass = AuditoryStimuli.Filter([f_left, f_right]) nothing # hide ``` Once the filters are designed and placed in an AuditoryStimuli.Filter object they can be used just like any other modifier. Below the filter is included in the pipeline and applied to 1 second of audio in 1/100th second frames. This example demonstrates how an arbitrary number of modifiers can be chained to create complex audio stimuli. ```@example realtime for frame = 1:100 @pipe read(source, 0.01u"s") |> modify(amp, _) |> modify(bandpass, _) |> write(sink, _) end ``` ## Modifying modifier parameters Further, the parameters of modifiers can be varied at any time. This can be handy to adapt your stimuli to user responses or feedback. Below the target amplification is updated to be set to zero. This effectively ramps off the signal. ```@example realtime setproperty!(amp, :target, 0.0) for frame = 1:20 @pipe read(source, 0.01u"s") |> modify(amp, _) |> modify(bandpass, _) |> write(sink, _) end nothing # hide ``` ## Verify output The entire signal (both the amplification, then the filtering sections) can be viewed using the convenience plotting function below. We observe that the signal is ramped on due to the amplification modifier. We can then see that at 1 second the spectral content of the signal was modified. And finally the signal is ramped off. ```@example realtime PlotSpectroTemporal(sink, figure_size=(700, 400), frequency_limits = [0, 8000]) current() |> DisplayAs.PNG # hide ```
AuditoryStimuli
https://github.com/rob-luke/AuditoryStimuli.jl.git
[ "MIT" ]
0.6.13
0102ab9be27a64b0963c77280a495c761e1a8c4f
code
711
using Documenter using TreeTools using BenchmarkTools makedocs( sitename = "TreeTools", format = Documenter.HTML(), modules = [TreeTools], pages = [ "Home" => "index.md", "Basic concepts" => "basic_concepts.md", "Reading and writing" => "IO.md", "Iteration" => "Iteration.md", "Useful functions" => "useful_functions.md", "Modifying the tree" => "modifying_the_tree.md", ] ) # Documenter can also automatically deploy documentation to gh-pages. # See "Hosting Documentation" and deploydocs() in the Documenter manual # for more information. #=deploydocs( repo = "<repository url>" )=# deploydocs( repo = "github.com/PierreBarrat/TreeTools.jl.git", )
TreeTools
https://github.com/PierreBarrat/TreeTools.jl.git
[ "MIT" ]
0.6.13
0102ab9be27a64b0963c77280a495c761e1a8c4f
code
1222
module TreeTools using Random ## Iteration import Base: eltype, iterate, IteratorEltype, IteratorSize, length ## Indexing import Base: eachindex, firstindex, get!, getindex, lastindex, setindex! ## Others import Base: ==, cat, convert, copy, count, delete!, hash, in, insert!, intersect import Base: isempty, isequal, keys, map, map!, setdiff, show, size import Base: union, union!, unique, unique!, write ## include("objects.jl") export Tree, TreeNode, TreeNodeData, MiscData export isleaf, isroot, isinternal export ancestor, children, branch_length, branch_length!, label, label! export data, data!, root include("methods.jl") export lca, node2tree, node2tree!, node_depth, distance, divtime, share_labels, is_ancestor include("iterators.jl") export POT, POTleaves, nodes, leaves, internals include("prunegraft.jl") export insert!, graft!, prune!, prunesubtree! include("reading.jl") export parse_newick_string, read_tree include("writing.jl") export write_newick, newick include("misc.jl") export print_tree, check_tree, print_tree_ascii include("splits.jl") export Split, SplitList export arecompatible, iscompatible include("simple_shapes.jl") export star_tree, balanced_binary_tree, ladder_tree end
TreeTools
https://github.com/PierreBarrat/TreeTools.jl.git
[ "MIT" ]
0.6.13
0102ab9be27a64b0963c77280a495c761e1a8c4f
code
4376
""" nodes(t; skiproot=false) leaves(t) internals(t; skiproot=false) Iterator over all nodes / leaves / internal nodes of a tree. If `skiproot`, the root node will be skipped by the iterator. # Note `length` cannot be called on `internals(t)` as the latter is based on `Iterators.filter`. A way to get the number of internal nodes of a tree is for example by calling `length(nodes(t)) - length(leaves(t))`. """ nodes, leaves, internals function nodes(t::Tree; skiproot = false) return if skiproot Iterators.filter(x -> !isroot(x), values(t.lnodes)) else values(t.lnodes) end end leaves(t::Tree) = values(t.lleaves) function internals(t::Tree; skiproot = false) return if skiproot Iterators.filter(x->!x.isleaf && !isroot(x), values(t.lnodes)) else Iterators.filter(x->!x.isleaf, values(t.lnodes)) end end nodes(f::Function, t::Tree) = filter(f, values(t.lnodes)) #= Post order traversal iterators =# abstract type POTIterator end Base.IteratorSize(::Type{POTIterator}) = Iterators.HasLength() Base.IteratorEltype(::Type{POTIterator}) = HasEltype() Base.iterate(itr::POTIterator) = firststate(itr, itr.root) """ struct POT{T<:TreeNodeData} <: POTIterator root::TreeNode{T} end """ struct POT{T<:TreeNodeData} <: POTIterator root::TreeNode{T} end Base.eltype(::Type{POT{T}}) where T = TreeNode{T} POT(t::Tree) = POT(t.root) function Base.length(iter::POT) return count(x->true, iter.root) end """ struct POTleaves{T<:TreeNodeData} <: POTIterator root::TreeNode{T} end """ struct POTleaves{T<:TreeNodeData} <: POTIterator root::TreeNode{T} end Base.eltype(::Type{POTleaves{T}}) where T = TreeNode{T} POTleaves(t::Tree) = POTleaves(t.root) function Base.length(iter::POTleaves) return count(isleaf, iter.root) end struct POTState{T<:TreeNodeData} n::TreeNode{T} i::Int # Position of n in list of siblings -- `n.anc.child[i]==n` direction::Symbol end """ - `state.n.isleaf`: go to sibling and down or ancestor and up (stop if root) - Otherwise: go to deepest child and up. """ function Base.iterate(itr::POTIterator, state::POTState) if state.direction == :down return go_down(itr, state) elseif state.direction == :up return go_up(itr, state) elseif state.direction == :stop return nothing end end function go_down(itr::POTIterator, state::POTState{T}) where T if state.n.isleaf # Go back to ancestor or sibling anyway if state.n.isroot || state.n == itr.root return (state.n, POTState{T}(n, 0, :stop)) elseif state.i < length(state.n.anc.child) # Go to sibling return (state.n, POTState{T}(state.n.anc.child[state.i+1], state.i+1, :down)) else # Go back to ancestor return (state.n, POTState{T}(state.n.anc, get_sibling_number(state.n.anc), :up)) end end return firststate(itr, state.n) # Go to deepest child of `n` end function go_up(itr::POT{T}, state::POTState{T}) where T if state.n.isroot || state.n == itr.root return (state.n, POTState{T}(state.n, 0, :stop)) elseif state.i < length(state.n.anc.child) # Go to sibling return (state.n, POTState{T}(state.n.anc.child[state.i+1], state.i+1, :down)) else # Go back to ancestor return (state.n, POTState{T}(state.n.anc, get_sibling_number(state.n.anc), :up)) end end function go_up(itr::POTleaves{T}, state::POTState{T}) where T if state.n.isleaf if state.n.isroot || state.n == itr.root return (state.n, POTState{T}(state.n, 0, :stop)) elseif state.i < length(state.n.anc.child) # Go to sibling return (state.n, POTState{T}(state.n.anc.child[state.i+1], state.i+1, :down)) else # Go back to ancestor return (state.n, POTState{T}(state.n.anc, get_sibling_number(state.n.anc), :up)) end else if state.n.isroot || state.n == itr.root return nothing elseif state.i < length(state.n.anc.child) # Go to sibling iterate(itr, POTState(state.n.anc.child[state.i+1], state.i+1, :down)) else # Go back to ancestor iterate(itr, POTState(state.n.anc, get_sibling_number(state.n.anc), :up)) end end end """ Go to deepest child of `a`. """ function firststate(itr::POTIterator, a::TreeNode{T}) where T if a.isleaf return iterate(itr, POTState{T}(a, 1, :up)) end firststate(itr, a.child[1]) end function get_sibling_number(n::TreeNode) if n.isroot return 0 end for (i,c) in enumerate(n.anc.child) if n == c return i end end @error "Could not find $(n.label) in children of $(n.anc.label)." end
TreeTools
https://github.com/PierreBarrat/TreeTools.jl.git
[ "MIT" ]
0.6.13
0102ab9be27a64b0963c77280a495c761e1a8c4f
code
28033
############################################################################################################### ################################# Trees from nodes, etc... ####################################### ############################################################################################################### """ node2tree(root::TreeNode{T}; label = default_tree_label(), force_new_labels=false) Create a `Tree` object from `root` with name `label`. If `force_new_labels`, a random string is added to node labels to make them unique. """ function node2tree( root::TreeNode{T}; label = default_tree_label(), force_new_labels = false ) where T if !isroot(root) @warn "Creating a tree from non-root node $(root.label)." end tree = Tree(root, Dict{String, TreeNode{T}}(), Dict{String, TreeNode{T}}(), label) node2tree_addnode!(tree, root; force_new_labels) return tree end function node2tree!(tree::Tree, root::TreeNode; force_new_labels=false) tree.root = root tree.lnodes = Dict{String, TreeNode}() tree.lleaves = Dict{String, TreeNode}() node2tree_addnode!(tree, root; force_new_labels) end """ function node2tree_addnode!(tree::Tree, node::TreeNode; safe = true) Add existing `node::TreeNode` and all of its children to `tree::Tree`. If `node` is a leaf node, also add it to `tree.lleaves`. ## Note on labels - throw error if `node.label` already exists in `tree`. Used `force_new_labels` to append a random string to label, making it unique. - if `node.label` can be interpreted as a bootstrap value, a random string is added to act as an actual label. See `?TreeTools.isbootstrap` for labels interpreted as bootstrap. This is only applied to internal nodes. """ function node2tree_addnode!(tree::Tree, node::TreeNode; force_new_labels=false) isbb = !isleaf(node) && isbootstrap(node.label) if isempty(node.label) || (in(node, tree) && force_new_labels) || isbb set_unique_label!(node, tree; delim="__") end if haskey(tree.lnodes, node.label) error("Node $(node.label) appears twice in tree. Use `force_new_labels`.") end tree.lnodes[node.label] = node if node.isleaf tree.lleaves[node.label] = node end for c in node.child node2tree_addnode!(tree, c; force_new_labels) end end """ isbootstrap(label::AbstractString) `label` is interpreted as a confidence value if `label` can be parsed as a decimal number (*e.g.* `"87"`, `"100"`, `"76.8"`, `"0.87"`" or `"1.0"`) Multiple confidence values separated by a `/` are also interpreted as such. - `"87.7/32"` will be interpreted as a confidence value - `"87.7/cool_node"` will not """ function isbootstrap(label::AbstractString) elements = split(label, '/') for e in elements if isnothing(tryparse(Float64, e)) return false end end return true end """ parse_bootstrap(label::AbstractString) **NOT IMPLEMENTED YET** Parse and return confidence value for `label`. Return `missing` if nothing could be parsed. `label` is interpreted as a bootstrap value if - `label` can be parsed as a <= 100 integer (*e.g.* `"87"` or `"100"`) - `label can be parsed as a <= 1 decimal number (*e.g.* `"0.87"`" or `"1.0"`) If label is of one of these forms and followed by a string of the form `__NAME`, it is also parsed. """ function parse_bootstrap(label::AbstractString) @warn "`parse_bootstrap` is not implemented yet, doing nothing and return `missing`." return missing end """ name_nodes!(t::Tree) Give a label to label-less nodes in `t`. """ function name_nodes!(t::Tree) name_nodes!(t.root, collect(keys(t.lnodes))) end function name_nodes!(r::TreeNode, labels ; i = 0) ii = i if r.isleaf && isempty(r.label) @warn "Label-less leaf node!" end if isempty(r.label) while in("NODE_$ii", labels) ii += 1 end r.label = "NODE_$ii" ii += 1 for c in r.child ii = name_nodes!(c, labels, i = ii) end end return ii end """ share_labels(tree1, tree2) Check if `tree1` and `tree2` share the same labels for leaf nodes. """ function share_labels(tree1, tree2) l1 = Set(l for l in keys(tree1.lleaves)) l2 = Set(l for l in keys(tree2.lleaves)) return l1 == l2 end """ map(f, t::Tree) map(f, r::TreeNode) """ Base.map(f, r::TreeNode) = map(f, POT(r)) Base.map(f, t::Tree) = map(f, t.root) """ map!(f, t::Tree) map!(f, r::TreeNode) In the `Tree` version, call `f(n)` on all nodes of `t`. In the `TreeNode` version, call `f(n)` on each node in the clade below `r`, `r` included. Useful if `f` changes its input. Return `nothing`. """ function Base.map!(f, r::TreeNode) for c in r.child map!(f, c) end f(r) return nothing end Base.map!(f, t::Tree) = map!(f, t.root) """ count(f, r::TreeNode) Call `f(n)` on each node in the clade below `r` and return the number of time it returns `true`. """ function Base.count(f, r::TreeNode) c = _count(f, 0, r) return c end Base.count(f, t::Tree) = count(f, t.root) function _count(f, c, r) if f(r) c += 1 end for n in r.child c += _count(f, 0, n) end return c end ############################################################################################################### ##################################### Copy tree with different NodeData ####################################### ############################################################################################################### function _copy(r::TreeNode, ::Type{T}) where T <: TreeNodeData !r.isroot && error("Copying non-root node.") data = _copy_data(T, r) child = if r.isleaf Array{TreeNode{T}, 1}(undef, 0) else Array{TreeNode{T}, 1}(undef, length(r.child)) end cr = TreeNode( data; anc=nothing, isleaf=r.isleaf, isroot=true, label=r.label, tau=r.tau, child=child ) for (i,c) in enumerate(r.child) _copy!(cr, c, i) end return cr end """ _copy!(an::TreeNode{T}, n::TreeNode) where T <: TreeNodeData Create a copy of `n` with node data type `T` and add it to the children of `an`. """ function _copy!(an::TreeNode{T}, n::TreeNode, i) where T <: TreeNodeData data = _copy_data(T, n) child = if n.isleaf Array{TreeNode{T}, 1}(undef, 0) else Array{TreeNode{T}, 1}(undef, length(n.child)) end cn = TreeNode( data; anc=an, isleaf=n.isleaf, isroot=n.isroot, label=n.label, tau=n.tau, child=child ) # Adding `cn` to the children of its ancestor `an` an.child[i] = cn # Copying children of `n` for (i,c) in enumerate(n.child) _copy!(cn, c, i) end return nothing end _copy_data(::Type{T}, n::TreeNode{T}) where T <: TreeNodeData = copy(n.data) _copy_data(::Type{T}, n::TreeNode) where T <: TreeNodeData = T() """ copy(t::Tree; force_new_tree_label = false, label=nothing) Make a copy of `t`. The copy can be modified without changing `t`. By default `tree.label` is also copied. If this is not desired `force_new_tree_label=true` will create create a copy of the tree with a new label. Alternatively a `label` can be set with the `label` argument. """ function Base.copy(t::Tree{T}; force_new_tree_label = false, label=nothing) where T <: TreeNodeData if force_new_tree_label node2tree(_copy(t.root, T)) else node2tree(_copy(t.root, T), label = isnothing(label) ? t.label : label) end end """ convert(Tree{T}, t::Tree) convert(T, t::Tree) Create a copy of `t` with data of type `T::TreeNodeData` at nodes (see ?`TreeNodeData`). """ Base.convert(::Type{Tree{T}}, t::Tree{T}) where T <: TreeNodeData = t function Base.convert(::Type{Tree{T}}, t::Tree; label=t.label) where T <: TreeNodeData return node2tree(_copy(t.root, T), label=label) end Base.convert(::Type{T}, t::Tree) where T <: TreeNodeData = convert(Tree{T}, t) ############################################################################################################### ################################################### Clades #################################################### ############################################################################################################### """ node_findroot(node::TreeNode ; maxdepth=1000) Return root of the tree to which `node` belongs. """ function node_findroot(node::TreeNode ; maxdepth=1000) temp = node it = 0 while !temp.isroot && it <= maxdepth temp = temp.anc it += 1 end if it > maxdepth @error("Could not find root after $maxdepth iterations.") error() end return temp end """ node_ancestor_list(node::TreeNode) Return array of all ancestors of `node` up to the root. """ function node_ancestor_list(node::TreeNode) list = [node.label] a = node while !a.isroot push!(list, a.anc.label) a = a.anc end return list end """ isclade(nodelist) isclade(nodelist::AbstractArray{<:AbstractString}, t::Tree) Check if `nodelist` is a clade. All nodes in `nodelist` should be leaves. """ function isclade(nodelist; safe=true) out = true if safe && !mapreduce(x->x.isleaf, *, nodelist, init=true) out = false else claderoot = lca(nodelist) # Now, checking if `clade` is the same as `nodelist` for c in POTleaves(claderoot) flag = false for n in nodelist if n.label==c.label flag = true break end end if !flag out = false break end end end return out end function isclade(nodelist::AbstractArray{<:AbstractString}, t::Tree) return isclade([t.lnodes[n] for n in nodelist]) end ############################################################################################################### ######################################## LCA, divtime, ... #################################################### ############################################################################################################### """ node_depth(node::TreeNode) Topologic distance from `node` to root. """ function node_depth(node::TreeNode) d = 0 _node = node while !_node.isroot _node = _node.anc d += 1 end return d end """ lca(i_node::TreeNode, j_node::TreeNode) Find and return lowest common ancestor of `i_node` and `j_node`. Idea is to go up in the tree in an asymmetric way on the side of the deeper node, until both are at equal distance from root. Then, problem is solved by going up in a symmetric way. (https://stackoverflow.com/questions/1484473/how-to-find-the-lowest-common-ancestor-of-two-nodes-in-any-binary-tree/6183069#6183069) """ function lca(i_node::TreeNode, j_node::TreeNode) if i_node.isroot return i_node elseif j_node.isroot return j_node end ii_node = i_node jj_node = j_node di = node_depth(ii_node) dj = node_depth(jj_node) while di != dj if di > dj ii_node = ii_node.anc di -=1 else jj_node = jj_node.anc dj -=1 end end while ii_node != jj_node ii_node = ii_node.anc jj_node = jj_node.anc end return ii_node end """ lca(nodelist) Find the common ancestor of all nodes in `nodelist`. `nodelist` is an iterable collection of `TreeNode` objects. """ function lca(nodelist::Vararg{<:TreeNode}) # Getting any element to start with ca = first(nodelist) for node in nodelist if !is_ancestor(ca, node) ca = lca(ca, node) end end return ca end lca(nodelist) = lca(nodelist...) """ lca(t::Tree, labels::Array{<:AbstractString,1}) lca(t::Tree, labels...) """ function lca(t::Tree, labels) ca = t.lnodes[first(labels)] for l in labels if !is_ancestor(ca, t.lnodes[l]) ca = lca(ca, t.lnodes[l]) end end return ca end lca(t::Tree, labels::Vararg{<:AbstractString}) = lca(t, collect(labels)) """ blca(nodelist::Vararg{<:TreeNode}) Return list of nodes just below `lca(nodelist)`. Useful for introducing splits in a tree. """ function blca(nodelist::Vararg{<:TreeNode}) r = lca(nodelist...) out = [] for n in nodelist a = n while a.anc != r a = a.anc end push!(out, a) end return out end """ distance(t::Tree, n1::AbstractString, n2::AbstractString; topological=false) distance(n1::TreeNode, n2::TreeNode; topological=false) Compute branch length distance between `n1` and `n2` by summing the `branch_length` values. If `topological`, the value `1.` is summed instead, counting the number of branches separating the two nodes (*Note*: the output is not an `Int`!). """ function distance(i_node::TreeNode, j_node::TreeNode; topological=false) a_node = lca(i_node, j_node) tau = 0. ii_node = i_node jj_node = j_node while ii_node != a_node tau += topological ? 1. : ii_node.tau ii_node = ii_node.anc end while jj_node != a_node tau += topological ? 1. : jj_node.tau jj_node = jj_node.anc end return tau end function distance(t::Tree, n1::AbstractString, n2::AbstractString; topological=false) return distance(t.lnodes[n1], t.lnodes[n2]; topological) end # for convenience with old functions -- should be removed eventually divtime(i_node, j_node) = distance(i_node, j_node) """ is_ancestor(t::Tree, a::AbstractString, n::AbstractString) is_ancestor(a::TreeNode, n::TreeNode) Check if `a` is an ancestor of `n`, in the sense that `ancestor(ancestor(...(node))) == a`. """ function is_ancestor(a::TreeNode, node::TreeNode) return if a == node true else isroot(node) ? false : is_ancestor(a, ancestor(node)) end end is_ancestor(t::Tree, a::AbstractString, n::AbstractString) = is_ancestor(t[a], t[n]) """ distance_to_deepest_leaf(n::TreeNode; topological=false) Distance from `n` to the deepest leaf in the clade below `n`. """ function distance_to_deepest_leaf(n::TreeNode; topological=false) return maximum(l -> distance(n, l; topological), POTleaves(n)) end tree_height(tree::Tree; kwargs...) = distance_to_deepest_leaf(tree.root; kwargs...) """ distance_to_shallowest_leaf(n::TreeNode; topological = false) Distance from `n` to the closest leaf in the clade below `n`. """ function distance_to_shallowest_leaf(n::TreeNode; topological = false) return minimum(l -> distance(n, l; topological), POTleaves(n)) end function distance_to_closest_leaf(tree::Tree, label::AbstractString; topological = false) return minimum(l -> distance(tree[label], l; topological), leaves(tree)) end ############################################################################################################### ######################################## Topology: root, binarize, ladderize... #################################################### ############################################################################################################### """ binarize!(t::Tree; time=0.) Make `t` binary by adding arbitrary internal nodes with branch length `time`. """ function binarize!(t::Tree; mode = :balanced, time = 0.) # I would like to implement `mode = :random` too in the future z = binarize!(t.root; mode, time) node2tree!(t, t.root) return z end function binarize!(n::TreeNode{T}; mode = :balanced, time = 0.) where T z = 0 if length(n.child) > 2 c_left, c_right = _partition(n.child, mode) for part in (c_left, c_right) if length(part) > 1 z += 1 nc = TreeNode(T(), label=make_random_label("BINARIZE")) for c in part prunenode!(c) graftnode!(nc, c) end graftnode!(n, nc; time) end end end for c in n.child z += binarize!(c; mode, time) end return z end function _partition(X, mode) # for now mode==:balanced all the time, so it's simple L = length(X) half = div(L,2) + mod(L,2) return X[1:half], X[(half+1):end] end #= root the tree to which `node` belongs at `node`. Base function for rooting. - If `node.isroot`, - Else if `newroot == nothing`, root the tree defined by `node` at `node`. Call `root!(node.anc; node)`. - Else, call `root!(node.anc; node)`, then change the ancestor of `node` to be `newroot`. =# function _root!(node::Union{TreeNode,Nothing}; newroot::Union{TreeNode, Nothing}=nothing) # Breaking cases if node.anc == nothing || node.isroot if !(node.anc == nothing && node.isroot) @warn "There was a problem with input tree: previous root node has an ancestor." elseif newroot != nothing i = findfirst(c->c.label==newroot.label, node.child) deleteat!(node.child, i) node.anc = newroot node.tau = newroot.tau node.isroot = false end else # Recursion if newroot == nothing # if node.isleaf # error("Cannot root on a leaf node") # end node.isroot = true _root!(node.anc, newroot=node) push!(node.child, node.anc) node.anc = nothing node.tau = missing else i = findfirst(c->c.label==newroot.label, node.child) deleteat!(node.child, i) _root!(node.anc, newroot=node) push!(node.child, node.anc) node.anc = newroot node.tau = newroot.tau end end end """ root!(tree::Tree, node::AbstractString; root_on_leaf, time=0.) Root `tree` at `tree.lnodes[node]`. Equivalent to outgroup rooting. If `time` is non-zero, root above `node` at height `time`, inserting a new node. """ function root!(tree::Tree, node::AbstractString; root_on_leaf = false, time = 0.) if isleaf(tree[node]) && !ismissing(time) && time == 0 if root_on_leaf # remove `node` from set of leaves delete!(tree.lleaves, node) tree[node].isleaf = false else error("Cannot root on a leaf node") end end new_root = if !ismissing(time) && time == 0 node else r = try insert!(tree, node; time) catch @error "Error inserting new root at height $time on branch above node $node" rethrow() end label(r) end _root!(tree.lnodes[new_root]) tree.root = tree.lnodes[new_root] remove_internal_singletons!(tree) # old root is potentially a singleton if label(tree.root) != new_root label!(tree, label(tree.root), new_root) end return nothing end """ root!(tree; method=:midpoint, topological = false) Root tree using `method`. Only implemented method is `:midpoint`. # Methods ## `:midpoint` Distance between nodes can be either topological (number of branches) or based on branch length. Does not create a polytomy at the root: if the midpoint is an already existing internal node (not the root), creates a new root node at infinitesimal distance below it. Midpoint rooting will exit without doing anything if - the distance between the two farthest leaves is `0`. This happens if all branch lengths are 0. - the current root is already the midpoint. ## `:model` Provide keyword argument `model::Tree`. Try to root `tree` like `model`. If the two trees only differ by rooting, they will have the same topology at the end of this. Else, tree will be rerooted but a warning will be given. """ function root!(tree; method=:midpoint, topological = false, model=nothing) if method == :midpoint root_midpoint!(tree; topological) elseif method == :model root_like_model!(tree, model) end return nothing end """ root_like_model!(tree, model::Tree) Try to root `tree` like `model`. If the two trees only differ by rooting, they will have the same topology at the end of this. Else, tree will be rerooted but a warning will be given. """ function root_like_model!(tree, model::Tree) @assert share_labels(tree, model) "Can only be used for trees that share leaves" # warn_1() = @warn """`tree` and `model` differ by more than rooting, but the rerooting \ algorithm nonetheless found a sensible root for `tree` and re-rooted. Maybe check what you're doing.""" # Look at the two splits below the root of `model` ... M1 = model |> root |> children |> first M2 = model |> root |> children |> last S1 = map(label, POTleaves(M1)) S2 = map(label, POTleaves(M2)) # ... and to what nodes they correspond in `tree` A1 = lca(tree, S1...) A2 = lca(tree, S2...) R, time = if !isroot(A1) && !isroot(A2) # if none of them is the root, then `tree` is already rooted correctly if SplitList(model) != SplitList(tree) @warn "Tree and model differ too much for rooting. Leaving input tree unchanged." end return nothing elseif isroot(A1) && isroot(A2) @warn "Tree and model differ too much for rooting. Leaving input tree unchanged." return nothing elseif isroot(A1) # else, we root on the ancestor of the one that is not the root # branch length is calculated proportionally from model time = distance(A2, ancestor(A2)) * distance(M2, ancestor(M2)) / distance(M1, M2) label(A2), time elseif isroot(A2) time = distance(A1, ancestor(A1)) * distance(M1, ancestor(M1)) / distance(M1, M2) label(A1), time end TreeTools.root!(tree, R; time) if SplitList(model) != SplitList(tree) warn_1() end return nothing end function root_midpoint!(t::Tree; topological = false) exit_warning = "Failed to midpoint root, tree unchanged" if length(leaves(t)) == 1 @warn "Can't midpoint root tree with only one leaf" @warn exit_warning return nothing end # Find the good branch b_l, b_h, L1, L2, fail = find_midpoint(t; topological) fail && (@warn exit_warning; return nothing) # The midpoint is between b_l and b_h == b_l.anc # L1 and L2 are the farthest apart leaves # It's on the side of L1 w.r. to the current root, that is we should be in the situation #= -- Root -- | | b_h | | | b_l | | | L1 L2 =# # If the midpoint is exactly on b_h and b_h is not the root, we introduce a singleton below to root on. d1 = distance(b_l, L1; topological) d2 = distance(b_l, L2; topological) @debug """ Midpoint on branch $(label(b_h)) --> $(label(b_l)). Farthest apart leaves: $(label(L1)) and $(label(L2)). Distances: L1 --> b_l: $(d1) // L2 --> b_h: $(distance(b_h, L2; topological)) """ @assert d1 <= d2 """ Issue with branch lengths. """ if isroot(b_h) && isapprox(abs(d1-d2), 2*distance(b_l, b_h; topological)) # The root is already the midpoint @debug """ Distances to previous root: $(L1.label) --> $(distance(t.root, L1; topological)) / $(L2.label) --> $(distance(t.root, L2; topological)) """ @debug "Previous root was already midpoint, leaving tree unchanged." else # Introducing a singleton that will act as the new root. τ = if topological # root halfway along the branch ismissing(b_l) ? missing : b_l.tau/2 else _τ = (d2-d1)/2 _τ = isapprox(_τ, b_l.tau) ? b_l.tau : _τ # if small numerical error, fix it end @assert ismissing(τ) || 0 <= τ <= b_l.tau """ Issue with time on the branch above midpoint. Got τ=$τ and expected `missing` or `0 <= τ <= `$(b_l.tau). """ R = insert!(t, b_l; time=τ, name=get_unique_label(t, "MIDPOINT_ROOT")) node2tree!(t, t.root) @debug "Introducing new root between $(b_l.label) and $(b_h.label)" @debug "Distances to R: $(L1.label) --> $(distance(R, L1; topological)) / $(L2.label) --> $(distance(R, L2; topological))" # Rooting on R root!(t, R.label) end return nothing end function find_midpoint(t::Tree{T}; topological = false) where T # Find pair of leaves with largest distance max_dist = -Inf L1 = "" L2 = "" for n1 in leaves(t), n2 in leaves(t) d = distance(n1, n2; topological) ismissing(d) && (@error "Can't midpoint root for tree with missing branch length."; error()) if d > max_dist && n1 != n2 max_dist = d L1, L2 = (n1.label, n2.label) end end @debug "Farthest leaves: $L1 & $L2 -- distance $max_dist" @assert L1 != L2 "Issue: farthest apart leaves have the same label." (isempty(L1) || isempty(L2)) && @warn "One of farthest apart leaves has an empty label." if max_dist == 0 || ismissing(max_dist) @warn "Null or missing branch lengths: cannot midpoint root." return first(nodes(t)), first(nodes(t)), first(nodes(t)), first(nodes(t)), true end # Find leaf farthest away from lca(L1, L2) A = lca(t, L1, L2).label d1 = distance(t, L1, A; topological) d2 = distance(t, L2, A; topological) @assert isapprox(d1 + d2, max_dist; rtol = 1e-10) # you never know ... L_ref = d1 > d2 ? t[L1] : t[L2] L_other = d1 > d2 ? t[L2] : t[L1] # Find middle branch: go up from leaf furthest from lca(L1, L2) # midpoint is between b_l and b_h b_l = nothing b_h = L_ref d = 0 it = 0 while d < max_dist/2 && !isroot(b_h) && it < 1e5 d += topological ? 1. : branch_length(b_h) b_l = isnothing(b_l) ? b_h : b_l.anc b_h = b_h.anc @assert b_h != A "Issue during midpoint rooting." it += 1 end it >= 1e5 && error("Tree too large to midpoint root (>1e5 levels) (or there was a bug)") @debug "Midpoint found between $(b_l.label) and $(b_h.label)" return b_l, b_h, L_ref, L_other, false end """ ladderize!(t::Tree) Ladderize `t` by placing nodes with largest clades left in the newick string. """ ladderize!(t::Tree) = ladderize!(t.root) function ladderize!(n::TreeNode) function _isless(v1::Tuple{Int, String}, v2::Tuple{Int, String}) if (v1[1] < v2[1]) || (v1[1] == v2[1] && v1[2] < v2[2]) return true else return false end end if n.isleaf return (1, n.label) else rank = Array{Any}(undef, length(n.child)) for (k, c) in enumerate(n.child) rank[k] = ladderize!(c) end n.child = n.child[sortperm(rank; lt= _isless)] return sum([r[1] for r in rank]), n.label end return nothing end ############################################################################################################### ######################################## Other #################################################### ############################################################################################################### """ branches_of_spanning_tree(t::Tree, leaves...) Return the set of branches of `t` spanning `leaves`. The output is a `Vector{String}` containing labels of nodes. The branch above each of these nodes is in the spanning tree. """ function branches_in_spanning_tree(t::Tree{T}, leaves::Vararg{String}) where T R = lca(t, leaves...) # root of the spanning tree visited = Dict{String, Bool}() for n in leaves a = t[n] while !haskey(visited, a.label) && a != R visited[a.label] = true a = t[a.label].anc end end return collect(keys(visited)) end branches_in_spanning_tree(t, leaves::Vector{String}) = branches_in_spanning_tree(t, leaves...) function branches_in_spanning_tree(t, leaves::Vararg{TreeNode}) return branches_in_spanning_tree(t, Iterators.map(x->x.label, leaves)...) end """ resolution_index(t::Tree) Compute a measure of how resolved `t` is: `R = (I-1) / (L-2)` where `I` is the number of internal nodes and `L` the number of leaves. A fully resolved tree has `R=1`. A star tree has `R=0`. Trees with only one leaf are also considered fully resolved. """ function resolution_index(t::Tree) if length(leaves(t)) == 1 || length(leaves(t)) == 2 # if tree only contains 1 or 2 leaves it is resolved return 1 else L = length(leaves(t)) I = length(nodes(t)) - L return (I-1) / (L-2) end end resolution_value(t::Tree) = resolution_index(t::Tree) const tree_distance_types = (:RF,) """ distance(t1::Tree, t2::Tree; type = :RF, normalize = false) Compute distance between two trees. See `TreeTools.tree_distance_types` for allowed types. If `normalize`, the distance is normalized to `[0,1]`. """ function distance(t1::Tree, t2::Tree; type = :RF, normalize = false) if Symbol(type) == :RF return RF_distance(t1, t2; normalize) else error("Unknown distance type $(type) - see `TreeTools.tree_distance_types`") end end """ RF_distance(t1::Tree, t2::Tree; normalize=false) Compute the Robinson–Foulds distance between `t1` and `t2`. RF distance is the sum of the number of splits present in `t1` and not `t2` and in `t2` and not `t1`. If `normalize`, the distance is normalized to `[0,1]`. """ function RF_distance(t1::Tree, t2::Tree; normalize=false) @assert share_labels(t1, t2) "Cannot compute RF distance for trees that do not share leaves" s1 = SplitList(t1) s2 = SplitList(t2) d = length(s1) + length(s2) - 2*length(TreeTools.intersect(s1, s2)) if !normalize || (length(s1) + length(s2) < 3) # can't normalize if both trees have only the root split return d else return d / (length(s1) + length(s2) - 2) end end function distance_matrix(t::Tree) # grossly unoptimized return [distance(n, m) for n in POTleaves(t), m in POTleaves(t)] end
TreeTools
https://github.com/PierreBarrat/TreeTools.jl.git
[ "MIT" ]
0.6.13
0102ab9be27a64b0963c77280a495c761e1a8c4f
code
10219
function Base.show(io::IO, ::MIME"text/plain", node::TreeNode) if !get(io, :compact, false) if isroot(node) println(io, "Node $(node.label) (root)") println(io, "Ancestor : `nothing` (root)") else println(io, "Node $(node.label): ") println(io, "Ancestor: $(node.anc.label), branch length = $(node.tau)") end print(io, "$(length(node.child)) children: $([x.label for x in node.child])") end return nothing end function Base.show(io::IO, node::TreeNode) print(io, "$(typeof(node)): $(node.label)") node.isroot && print(io, " (root)") return nothing end function Base.show(io::IO, t::Tree{T}) where T nn = length(nodes(t)) nl = length(leaves(t)) long = begin base = "Tree{$T}: " base *= nn > 1 ? "$nn nodes, " : "$nn node, " base *= nl > 1 ? "$nl leaves" : "$nl leaf" base end if length(long) < 0.8*displaysize(io)[2] print(io, long) return nothing end short = begin base = "Tree w. " base *= nl > 1 ? "$nl leaves" : "$nl leaf" base end print(io, short) return nothing end function Base.show(io::IO, ::MIME"text/plain", t::Tree; maxnodes=40) if length(nodes(t)) < maxnodes print_tree_ascii(io, t) else show(io, t) end end function print_tree_(io, node, cdepth; vindent=2, hindent=5, hoffset=0, maxdepth=5) hspace = "" for i in 1:hindent hspace *= "-" end offset = "" for i in 1:hoffset offset *= " " end if cdepth < maxdepth println(io, "$offset $hspace $(node.label):$(node.tau)") elseif cdepth == maxdepth if node.isleaf println(io, "$offset $hspace $(node.label):$(node.tau)") else println(io, "$offset $hspace $(node.label):$(node.tau) ...") end end # if cdepth <= maxdepth if !node.isleaf for c in node.child for i in 1:vindent cdepth < maxdepth && println(io, "$offset $(" "^hindent)|") end print_tree_( io, c, cdepth + 1; vindent, hindent, hoffset=hoffset+hindent, maxdepth ) end end # end end function print_tree(io, node::TreeNode; vindent=2, hindent=5, maxdepth=5) print_tree_(io, node, 1; vindent, hindent, hoffset=0, maxdepth) end function print_tree(io, t::Tree; vindent=2, hindent=5, maxdepth=5) return print_tree(io, t.root; vindent, hindent, maxdepth) end """ print_tree_ascii(io, t::Tree) Julia implementation of Bio.Phylo.draw_ascii function: https://github.com/biopython/biopython/blob/master/Bio/Phylo/_utils.py """ function print_tree_ascii(io, t::Tree) column_width = 80 taxa = [ node.label for node in POTleaves(t)] #need leaves in Post-Order Traversal max_label_width = maximum([length(taxon) for taxon in taxa]) drawing_width = column_width - max_label_width - 1 drawing_height = 2 * length(taxa) - 1 function get_col_positions(t::Tree) depths = [divtime(node, t.root) for node in values(t.lnodes)] # If there are no branch lengths, assume unit branch lengths if ismissing(maximum(depths)) println(io, "\n not all branch lengths known, assuming identical branch lengths") depths = [node_depth(node) for node in values(t.lnodes)] end # Potential drawing overflow due to rounding -- 1 char per tree layer fudge_margin = max(ceil(Int, log2(length(taxa))), 1) if maximum(depths)==0 cols_per_branch_unit = (drawing_width - fudge_margin) else cols_per_branch_unit = (drawing_width - fudge_margin) / maximum(depths) end return Dict(zip(keys(t.lnodes), round.(Int,depths*cols_per_branch_unit .+2.0))) end function get_row_positions(t::Tree) positions = Dict{Any, Int}(zip(taxa, 2 *(1:length(taxa)) ) ) function calc_row(clade::TreeNode) for subclade in clade.child if !haskey(positions, subclade.label) calc_row(subclade) end end if !haskey(positions, clade.label) positions[clade.label] = floor( Int, (positions[clade.child[1].label] + positions[clade.child[end].label])/2 ) end end calc_row(t.root) return positions end col_positions = get_col_positions(t) row_positions = get_row_positions(t) char_matrix = [[" " for x in 1:(drawing_width+1)] for y in 1:(drawing_height+1)] function draw_clade(clade::TreeNode, startcol::Int) thiscol = col_positions[clade.label] thisrow = row_positions[clade.label] # Draw a horizontal line for col in startcol:thiscol char_matrix[thisrow][col] = "_" end if !isempty(clade.child) # Draw a vertical line toprow = row_positions[clade.child[1].label] botrow = row_positions[clade.child[end].label] for row in (toprow+1):botrow char_matrix[row][thiscol] = "|" end # Short terminal branches need something to stop rstrip() if (col_positions[clade.child[1].label] - thiscol) < 2 char_matrix[toprow][thiscol] = "," end # Draw descendents for child in clade.child draw_clade(child, thiscol + 1) end end end draw_clade(t.root, 1) # Print the complete drawing for i in 1:length(char_matrix) line = rstrip(join(char_matrix[i])) # Add labels for terminal taxa in the right margin if i % 2 == 0 line = line * " " * strip(taxa[round(Int, i/2)]) #remove white space from labels to make more tidy end println(io, line) end end """ check_tree(t::Tree; strict=true) - Every non-leaf node should have at least one child (two if `strict`) - Every non-root node should have exactly one ancestor - If n.child[...] == c, c.anc == n is true - Tree has only one root """ function check_tree(tree::Tree; strict=true) labellist = Dict{String, Int}() nroot = 0 flag = true for n in nodes(tree) if !n.isleaf && length(n.child)==0 (flag = false) || (@warn "Node $(n.label) is non-leaf and has no child.") elseif !n.isroot && n.anc == nothing (flag = false) || (@warn "Node $(n.label) is non-root and has no ancestor.") elseif strict && length(n.child) == 1 if !(n.isroot && n.child[1].isleaf) (flag = false) || (@warn "Node $(n.label) has only one child.") end elseif length(n.child) == 0 && !haskey(tree.lleaves, n.label) (flag = false) || (@warn "Node $(n.label) has no child but is not in `tree.lleaves`") end for c in n.child if c.anc != n (flag = false) || (@warn "One child of $(n.label) does not satisfy `c.anc == n`.") end end if get(labellist, n.label, 0) == 0 labellist[n.label] = 1 else labellist[n.label] += 1 (flag = false) || (@warn "Label $(n.label) already exists!") end if n.isroot nroot += 1 end end if nroot > 1 (flag = false) || (@warn "Tree has multiple roots") elseif nroot ==0 (flag = false) || (@warn "Tree has no root") end return flag end default_tree_label(n=10) = randstring(n) make_random_label(base="NODE"; delim = "_") = make_random_label(base, 8; delim) make_random_label(base, i; delim = "_") = base * delim * randstring(i) function get_unique_label(t::Tree, base = "NODE"; delim = "_") label = make_random_label(base; delim) while haskey(t.lnodes, label) label = make_random_label(base; delim) end return label end function set_unique_label!(node::TreeNode, t::Tree; delim = "_") base = label(node) new_label = get_unique_label(t, base; delim) node.label = new_label end """ create_label(t::Tree, base="NODE") Create new node label in tree `t` with format `\$(base)_i` with `i::Int`. """ function create_label(t::Tree, base="NODE") label_init = 1 pattern = Regex(base) for n in values(t.lnodes) if match(pattern, n.label)!=nothing && parse(Int, n.label[length(base)+2:end]) >= label_init label_init = parse(Int, n.label[length(base)+2:end]) + 1 end end return "$(base)_$(label_init)" end """ map_dict_to_tree!(t::Tree{MiscData}, dat::Dict; symbol=false, key = nothing) Map data in `dat` to nodes of `t`. All node labels of `t` should be keys of `dat`. Entries of `dat` should be dictionaries, or iterable similarly, and are added to `n.data.dat`. If `!isnothing(key)`, only a specific key of `dat` is added. It's checked for by `k == key || Symbol(k) == key` for all keys `k` of `dat`. If `symbol`, data is added to nodes of `t` with symbols as keys. """ function map_dict_to_tree!(t::Tree{MiscData}, dat::Dict; symbol=false, key = nothing) for (name, n) in t.lnodes for (k,v) in dat[name] if !isnothing(key) && (k == key || Symbol(k) == key) n.data.dat[key] = v elseif isnothing(key) n.data.dat[symbol ? Symbol(k) : k] = v end end end nothing end """ map_dict_to_tree!(t::Tree{MiscData}, dat::Dict, key) Map data in `dat` to nodes of `t`. All node labels of `t` should be keys of `dat`. Entries of `dat` corresponding to `k` are added to `t.lnodes[k].data.dat[key]`. """ function map_dict_to_tree!(t::Tree{MiscData}, dat::Dict, key) for (name, n) in t.lnodes n.data.dat[key] = dat[name] end end """ rand_times!(t[, p]) Add random branch lengths to tree distributed according to `p` (default [0,1]). """ function rand_times!(t, p) for n in values(t.lnodes) if !n.isroot n.tau = rand(p) end end return nothing end function rand_times!(t) for n in values(t.lnodes) if !n.isroot n.tau = rand() end end return nothing end
TreeTools
https://github.com/PierreBarrat/TreeTools.jl.git
[ "MIT" ]
0.6.13
0102ab9be27a64b0963c77280a495c761e1a8c4f
code
5063
""" abstract type TreeNodeData Abstract supertype for data attached to the `dat` field of `TreeNode` objects. Implemented concrete types are - `EmptyData`: empty struct. Use if you do not have to attach data to nodes. - `MiscData`: contains a dictionary for attaching extra data to nodes. Also behaves like a `Dict` for indexing/iterating, *e.g.* `x.dat[key] == x[key]`. """ abstract type TreeNodeData end Base.copy(x::TreeNodeData) = deepcopy(x) """ struct MiscData <: TreeNodeData dat::Dict{Any,Any} end """ struct MiscData <: TreeNodeData dat::Dict{Any,Any} end MiscData(; dat=Dict()) = MiscData(dat) Base.iterate(d::MiscData) = iterate(d.dat) Base.iterate(d::MiscData, state) = iterate(d.dat, state) Base.eltype(::Type{MiscData}) = eltype(Dict{Any,Any}) Base.length(d::MiscData) = length(d.dat) Base.getindex(d::MiscData, i) = getindex(d.dat, i) Base.setindex!(d::MiscData, k, v) = setindex!(d.dat, k, v) Base.firstindex(d::MiscData, i) = firstindex(d.dat, i) Base.lastindex(d::MiscData, i) = lastindex(d.dat, i) Base.get!(d::MiscData, k, v) = get!(d.dat, k, v) Base.haskey(d::MiscData, k) = haskey(d.dat, k) Base.copy(d::MiscData) = MiscData(copy(d.dat)) """ struct EmptyData <: TreeNodeData """ struct EmptyData <: TreeNodeData end Base.copy(::EmptyData) = EmptyData() const DEFAULT_NODE_DATATYPE = EmptyData """ mutable struct TreeNode{T <: TreeNodeData} Structural information on the tree, *i.e.* topology and branch length. - `anc::Union{Nothing,TreeNode}`: Ancestor - `child::Array{TreeNode,1}`: List of children - `isleaf::Bool` - `isroot::Bool` - `tau::Union{Missing, Float64}` - `data::T` """ mutable struct TreeNode{T <: TreeNodeData} anc::Union{Nothing,TreeNode{T}} child::Array{TreeNode{T},1} isleaf::Bool isroot::Bool label::String tau::Union{Missing, Float64} data::T function TreeNode(anc, child, isleaf, isroot, label, tau, data::T) where T tau = !ismissing(tau) ? convert(Float64, tau) : missing return new{T}(anc, child, isleaf, isroot, label, tau, data) end end function TreeNode( data::T; anc = nothing, child = Array{TreeNode{T},1}(undef, 0), isleaf = true, isroot = true, label = make_random_label(), tau = missing, ) where T return TreeNode(anc, child, isleaf, isroot, label, tau, data) end function TreeNode(; data = DEFAULT_NODE_DATATYPE(), anc = nothing, child = Array{TreeNode{typeof(data)},1}(undef, 0), isleaf = true, isroot = true, label = make_random_label(), tau = missing, ) return TreeNode(anc, child, isleaf, isroot, label, tau, data) end """ ==(x::TreeNode, y::TreeNode) Equality of labels between `x` and `y`. """ function Base.isequal(x::TreeNode, y::TreeNode) return x.label == y.label end Base.:(==)(x::TreeNode, y::TreeNode) = isequal(x,y) Base.hash(x::TreeNode, h::UInt) = hash(x.label, h) children(n::TreeNode) = n.child function ancestor(n::TreeNode) @assert !isroot(n) "Trying to access the ancestor of root node $(label(n))" return n.anc end branch_length(n::TreeNode) = n.tau """ branch_length!(n::TreeNode, τ) Set the branch length above `n` to `τ`. """ branch_length!(n::TreeNode, τ::Union{Missing, Real}) = (n.tau = τ) label(n::TreeNode) = n.label isleaf(n) = n.isleaf isroot(n) = n.isroot isinternal(n) = !isleaf(n) data(n::TreeNode) = n.data """ data!(n::TreeNode{T}, dat::T) Set the the data field of `n` to `dat`. """ data!(n::TreeNode{T}, dat::T) where T = (n.data = dat) """ mutable struct Tree{T <: TreeNodeData} """ mutable struct Tree{T <: TreeNodeData} root::Union{Nothing, TreeNode{T}} lnodes::Dict{String, TreeNode{T}} lleaves::Dict{fieldtype(TreeNode{T}, :label), TreeNode{T}} label::String end function Tree( root::TreeNode{T}; lnodes = Dict{String, TreeNode{T}}(root.label => root), lleaves = Dict{fieldtype(TreeNode{T}, :label), TreeNode{T}}(root.label => root), label = default_tree_label() ) where T return Tree(root, lnodes, lleaves, label) end Tree() = Tree(TreeNode()) function Base.in(n::AbstractString, t::Tree; exclude_internals=false) exclude_internals ? haskey(t.lleaves, n) : haskey(t.lnodes, n) end Base.in(n::TreeNode, t::Tree; exclude_internals=false) = in(n.label, t; exclude_internals) Base.getindex(t::Tree, label) = getindex(t.lnodes, label) label(t::Tree) = t.label """ label!(t::Tree, label::AbstractString) Change the label of the `Tree` to `label`. """ label!(t::Tree, label::AbstractString) = (t.label = string(label)) """ label!(t::Tree, node::TreeNode, new_label::AbstractString) label!(t::Tree, old_label, new_label) Change the label of a `TreeNode` to `new_label`. """ function label!(tree::Tree, node::TreeNode, label::AbstractString) @assert in(node, tree) "Node $(node.label) is not in tree." @assert !in(label, tree) "Node $(label) is already in tree: can't rename $(node.label) like this." tree.lnodes[label] = node delete!(tree.lnodes, node.label) if node.isleaf tree.lleaves[label] = node delete!(tree.lleaves, node.label) end node.label = label return nothing end label!(t::Tree, old_label, new_label) = label!(t, t[old_label], new_label) root(t::Tree) = t.root
TreeTools
https://github.com/PierreBarrat/TreeTools.jl.git
[ "MIT" ]
0.6.13
0102ab9be27a64b0963c77280a495c761e1a8c4f
code
11908
""" prunenode!(node::TreeNode) Prune node `node` by detaching it from its ancestor. Return pruned `node` and its previous ancestor. """ function prunenode!(node::TreeNode) if node.isroot @warn "Trying to prune root: aborting" return node, TreeNode() end anc = node.anc for (i,c) in enumerate(anc.child) if c == node deleteat!(anc.child,i) break end end if isempty(anc.child) anc.isleaf = true end node.anc = nothing node.isroot = true return node, anc end """ prunenode(node::TreeNode) Prune node `node` by detaching it from its ancestor. Return pruned `node` and previous root `r`. The tree defined by `node` is copied before the operation and is not modified. """ function prunenode(node::TreeNode) if node.isroot @warn "Trying to prune root: aborting" node_ = deepcopy(node) return node_, node_ end node_ = deepcopy(node) r = node_findroot(node_) anc = node_.anc for (i,c) in enumerate(anc.child) if c == node_ deleteat!(anc.child,i) break end end node_.anc = nothing node_.isroot = true return node_, r end """ graftnode!(r::TreeNode, n::TreeNode ; tau=n.tau) Graft `n` on `r`. *Note*: this does not modify the `Tree` object. You could have to use `node2tree!` after, or call the `graft!` function. """ function graftnode!(r::TreeNode, n::TreeNode; time=n.tau) if !n.isroot || n.anc != nothing @error "Trying to graft non-root node $(n)." end push!(r.child, n) r.isleaf = false n.anc = r n.isroot = false n.tau = time return nothing end """ prunesubtree!(tree, node) prunesubtree!(tree, labels) Same as `prune!`, but returns the pruned node as a `TreeNode` and its previous ancestor. See `prune!` for details on `kwargs`. """ function prunesubtree!(tree, r::TreeNode; remove_singletons=true, create_leaf = :warn) # Checks if r.isroot error("Trying to prune root in tree $(label(tree))") elseif !in(r, tree) error("Node $(r.label) is not in tree $(tree.label). Cannot prune.") elseif length(children(ancestor(r))) == 1 if create_leaf == :warn @warn "Pruning node $(r.label) will create a new leaf $(ancestor(r).label)" elseif !create_leaf error("Pruning node $(r.label) will create a new leaf $(ancestor(r).label)") end end a = r.anc delnode(n) = begin delete!(tree.lnodes, n.label) if n.isleaf delete!(tree.lleaves, n.label) end end map!(delnode, r) prunenode!(r) if remove_singletons remove_internal_singletons!(tree, delete_time=false) end return r, a end prunesubtree!(t, r::AbstractString; kwargs...) = prunesubtree!(t, t[r]; kwargs...) function prunesubtree!(tree, labels::AbstractArray; clade_only=true, kwargs...) if clade_only && !isclade(labels, tree) error("Can't prune non-clade $labels") end r = lca(tree, labels) return prunesubtree!(tree, r; kwargs...) end function prunesubtree!(tree, label1, label2::Vararg{AbstractString}; kwargs...) return prunesubtree!(tree, vcat(label1, label2...); kwargs...) end """ prune!(tree, node; kwargs...) prune!(tree, labels::AbstractArray) prune!(tree, labels...) Prune `node` from `tree`. `node` can be a label or a `TreeNode`. Return the subtree defined by `node` as a `Tree` object as well as the previous ancestor of `node`. If a list of labels is provided, the MRCA of the corresponding nodes is pruned. ## kwargs - `remove_singletons`: remove singletons (internals with one child) in the tree after pruning. Default `true`. - `clade_only`: if a list of labels is provided, check that it corresponds to a clade before pruning. Default `true`. - `create_leaf`: if the ancestor of `r` has only one child (singleton), pruning `r` will create a leaf. If `create_leaf == :warn`, this will trigger a warning. If `create_leaf = false`, it will trigger an error. If `create_leaf = true`, then this is allowed. Default: `:warn`. ## Example ```jldoctest using TreeTools # hide tree = parse_newick_string("(A:1.,(B:1.,(X1:0.,X2:0.)X:5.)BX:1.)R;") prune!(tree, ["X1", "X2"]) map(label, nodes(tree)) # output 3-element Vector{String}: "B" "A" "R" ``` """ function prune!(t, r; kwargs...) r, a = prunesubtree!(t, r; kwargs...) return node2tree(r), a end function prune!(t, labels...; kwargs...) r, a = prunesubtree!(t, labels...; kwargs...) return node2tree(r), a end """ graft!(tree::Tree, n, r; graft_on_leaf=false, time=branch_length(n)) Graft `n` onto `r` and return the grafted node. `r` can be a label or a `TreeNode`, and should belong to `tree`. `n` can be a `TreeNode` or a `Tree`. In the latter case, `n` will be *copied* before being grafted. None of the nodes of the subtree of `n` should belong to `tree`. If `r` is a leaf and `graft_on_leaf` is set to `false` (default), will raise an error. """ function graft!( t::Tree{T}, n::TreeNode{T}, r::TreeNode; graft_on_leaf=false, time = branch_length(n), ) where T # checks if !graft_on_leaf && isleaf(r) error("Cannot graft: node $r is a leaf (got `graft_on_leaf=false`") elseif !isroot(n) && !isnothing(ancestor(n)) error("Cannot graft non-root node $(label(n))") end # checking that the subtree defined by `n` is not in `t` for c in POT(n) if in(c, t) error("Cannot graft node \"$(label(c))\": a node in tree $(label(t)) already has the same label.") end end # Handling tree dicts isleaf(r) && delete!(t.lleaves, label(r)) for c in POT(n) t.lnodes[label(c)] = c if isleaf(c) t.lleaves[label(c)] = c end end # grafting graftnode!(r, n; time) return n end function graft!(t::Tree{T}, n::TreeNode{R}, r::TreeNode; kwargs...) where T where R error( "Cannot graft node of type $(typeof(n)) on tree of type $(typeof(t)). Try to change node data type" ) end graft!(t, n::TreeNode, r::AbstractString; kwargs...) = graft!(t, n, t[r]; kwargs...) graft!(t1, t2::Tree, r; kwargs...) = graft!(t1, copy(t2).root, r; kwargs...) #= NOT TESTED -- TODO =# function __subtree_prune_regraft!( t::Tree, p::AbstractString, g::AbstractString; remove_singletons = true, graft_on_leaf = false, create_new_leaf = false, ) # Checks if !create_new_leaf && length(children(ancestor(t[p]))) == 1 error("Cannot prune node $p without creating a new leaf (got `create_new_leaf=false`)") elseif !graft_on_leaf && isleaf(t[g]) error("Cannot graft: node $g is a leaf (got `graft_on_leaf=false`)") end # prune n, a = prunenode!(t[p]) if isleaf(a) t.lleaves[label(a)] = a end # graft if isleaf(g) delete!(t.lleaves, g) end graft!(t, n, g) return nothing end """ insert_node!(c::TreeNode, a::TreeNode, s::TreeNode, time) Insert `s` between `a` and `c` at height `t`: `a --> s -- t --> c`. Return `s`. The relation `branch_length(s) + t == branch_length(c)` should hold. """ function insert_node!(c::TreeNode{T}, a::TreeNode{T}, s::TreeNode{T}, t::Missing) where T @assert ancestor(c) == a @assert ismissing(branch_length(c)) @assert ismissing(branch_length(s)) prunenode!(c) graftnode!(a, s) graftnode!(s, c) return s end function insert_node!(c::TreeNode{T}, a::TreeNode{T}, s::TreeNode{T}, t::Number) where T @assert ancestor(c) == a @assert branch_length(s) == branch_length(c) - t @assert branch_length(c) >= t prunenode!(c) branch_length!(c, t) graftnode!(a, s) graftnode!(s, c) return s end """ insert!(tree, node; name, time) Insert a singleton named `name` above `node`, at height `time` on the branch. Return the inserted singleton. `time` can be a `Number` or `missing`. """ function insert!( t::Tree{T}, n::TreeNode; name = get_unique_label(t), time = zero(branch_length(n)), ) where T # Checks nτ = branch_length(n) if isroot(n) error("Cannot insert node above root in tree $(label(t))") elseif ismissing(time) != ismissing(nτ) || (!ismissing(time) && time > nτ) error("Cannot insert node at height $time on branch with length $nτ") elseif in(name, t) error("node $name is already in tree $(label(t))") end # sτ = nτ - time s = TreeNode(; label=name, tau = sτ, data = T()) insert_node!(n, ancestor(n), s, time) t.lnodes[name] = s return s end insert!(t::Tree, n::AbstractString; kwargs...) = insert!(t, t[n]; kwargs...) """ delete_node!(node::TreeNode; delete_time = false) Delete `node`. If it is an internal node, its children are regrafted on `node.anc`. Returns the new `node.anc`. If `delete_time`, branch length above `node` is not added to the regrafted branch. Otherwise, the regrafted branch's length is unchanged. Return modified `node.anc`. Note that the previous node will still be in the dictionary `lnodes` and `lleaves` (if a leaf) and the print function will fail on the tree, to fully remove from the tree and apply the print function use `delete_node!(t::Tree, label)` """ function delete_node!(node::TreeNode; delete_time = false) node.isroot && error("Cannot delete root node") out = node.anc if node.isleaf prunenode!(node) else base_time = branch_length(node) for c in reverse(node.child) nc = prunenode!(c)[1] new_time = branch_length(nc) + (delete_time ? 0. : base_time) graftnode!(node.anc, nc, time = new_time) end prunenode!(node) end return out end """ delete!(tree::Tree, label; delete_time = false, remove_internal_singletons = true) Delete node `label` from `tree`. Children of `label` are regrafted onto its ancestor. If `delete_time`, the branch length above deleted node is also deleted, otherwise it is added to the regrafted branch. If `remove_internal_singletons`, internal singletons are removed after node is deleted. """ function delete!(t::Tree, label; delete_time = false, remove_internal_singletons = true) delete_node!(t.lnodes[label]; delete_time) delete!(t.lnodes, label) haskey(t.lleaves, label) && delete!(t.lleaves, label) remove_internal_singletons!(t; delete_time) return nothing end """ delete_null_branches!(tree::Tree; threshold=1e-10) Delete internal node with branch length smaller than `threshold`. Propagates recursively down the tree. For leaf nodes, set branch length to 0 if smaller than `threshold`. """ delete_null_branches!(tree::Tree; threshold=1e-10) = delete_branches!(n -> branch_length(n) < threshold, tree.root) function delete_branches!(f, n::TreeNode; keep_time=false) for c in copy(children(n)) # copy needed since `children(n)` is about to change delete_branches!(f, c; keep_time) end if !isroot(n) && f(n) if isleaf(n) # if `n` is a leaf, set its branch length to 0 n.tau = ismissing(n.tau) ? missing : 0. else delete_node!(n; delete_time = !keep_time) end end return n end """ delete_branches!(f, tree::Tree) delete_branches!(f, n::TreeNode) Delete branch above node `n` if `f(n)` returns `true` when called on node `n`. When called on a `Tree` propagates recursively down the tree. Only when called on a `Tree` will nodes be additionally deleted from the `lnodes` and `lleaves` dictionaries. If `keep_time`, the branch length of the deleted branches will be added to child branches. """ function delete_branches!(f, tree::Tree; keep_time=false) delete_branches!(f, tree.root) remove_internal_singletons!(tree) node2tree!(tree, tree.root) return nothing end """ remove_internal_singletons!(tree; delete_time = false) Remove nodes with one child. Root node is left as is. If `delete_time` is set to `false` (default), the length of branches above removed nodes is added to the branch length above their children. """ function remove_internal_singletons!(tree; delete_time = false) root = tree.root for n in nodes(tree) if length(n.child) == 1 if !n.isroot delete_node!(n; delete_time) delete!(tree.lnodes, n.label) end end end # If root itself is a singleton, prune its child if length(tree.root.child) == 1 && !tree.root.child[1].isleaf r = tree.root n = r.child[1] # n.anc = nothing n.isroot = true tree.root = n # for i in eachindex(children(r)) pop!(r.child) end delete!(tree.lnodes, label(r)) end return nothing end
TreeTools
https://github.com/PierreBarrat/TreeTools.jl.git
[ "MIT" ]
0.6.13
0102ab9be27a64b0963c77280a495c761e1a8c4f
code
7545
let n::Int64=0 global increment_n() = (n+=1) global reset_n() = (n=0) end let file::String = "" global get_nwk_file() = file # use for easy access when error global set_nwk_file(s) = (file=s) end """ read_tree( nwk_filename::AbstractString; node_data_type=DEFAULT_NODE_DATATYPE, label=default_tree_label(), force_new_labels=false ) read_tree( io::IO; node_data_type=DEFAULT_NODE_DATATYPE, label=default_tree_label(), force_new_labels=false ) Read Newick file and create a `Tree{node_data_type}` object from it. The input file can contain multiple Newick strings on different lines. The output will then be an array of `Tree` objects. The call `node_data_type()` must return a valid instance of a subtype of `TreeNodeData`. You can implement your own subtypes, or see `?TreeNodeData` for already implemented ones. Use `force_new_labels=true` to force the renaming of all internal nodes. By default the tree will be assigned a `default_tree_label()`, however the label of the tree can also be assigned with the `label` parameter. If you have a variable containing a Newick string and want to build a tree from it, use `parse_newick_string` instead. ## Note on labels The `Tree` type identifies nodes by their labels. This means that labels have to be unique. For this reason, the following is done when reading a tree: - if an internal node does not have a label, a unique one will be created of the form `"NODE_i"` - if a node has a label that was already found before in the tree, a random identifier will be appended to it to make it unique. Note that the identifier is created using `randstring(8)`, unicity is technically not guaranteed. - if `force_new_labels` is used, a unique identifier is appended to node labels - if node labels in the Newick file are identified as confidence/bootstrap values, a random identifier is appended to them, even if they're unique in the tree. See `?TreeTools.isbootstrap` to see which labels are identified as confidence values. """ function read_tree( io::IO; node_data_type=DEFAULT_NODE_DATATYPE, label=default_tree_label(), force_new_labels=false ) trees = map(Iterators.filter(!isempty, eachline(io))) do line t = parse_newick_string(line; node_data_type, label, force_new_labels) check_tree(t) t end return length(trees) == 1 ? trees[1] : trees end function read_tree( nwk_filename::AbstractString; node_data_type=DEFAULT_NODE_DATATYPE, label=default_tree_label(), force_new_labels=false ) return open(nwk_filename, "r") do io read_tree(io; node_data_type, label, force_new_labels) end end """ parse_newick_string( nw::AbstractString; node_data_type=DEFAULT_NODE_DATATYPE, force_new_labels=false ) Parse newick string into a tree. See `read_tree` for more informations. """ function parse_newick_string( nw::AbstractString; node_data_type=DEFAULT_NODE_DATATYPE, label=default_tree_label(), force_new_labels=false, strict_check = true, ) @assert nw[end] == ';' "Newick string does not end with ';'" reset_n() root = parse_newick(nw[1:end-1]; node_data_type) tree = node2tree(root; label, force_new_labels) check_tree(tree, strict = strict_check) return tree end """ read_newick(nwk_filename::AbstractString) Read Newick file `nwk_filename` and create a graph of `TreeNode` objects in the process. Return the root of said graph. `node2tree` or `read_tree` must be called to obtain a `Tree` object. """ function read_newick(nwk_filename::AbstractString; node_data_type=DEFAULT_NODE_DATATYPE) if !isa(node_data_type(), TreeNodeData) throw(ArgumentError("`node_data_type()` should return a valid instance of `TreeNodeData`")) end set_nwk_file(nwk_filename) nw = open(nwk_filename) do io readlines(io) end if length(nw) > 1 error("File $nwk_filename has more than one line.") elseif length(nw) == 0 error("File $nwk_filename is empty") end nw = nw[1] if nw[end] != ';' error("File $nwk_filename does not end with ';'") end nw = nw[1:end-1] reset_n() root = parse_newick(nw; node_data_type) return root end """ parse_newick(nw::AbstractString; node_data_type=DEFAULT_NODE_DATATYPE) Parse newick string into a `TreeNode`. """ function parse_newick(nw::AbstractString; node_data_type=DEFAULT_NODE_DATATYPE) if isempty(nw) error("Cannot parse empty Newick string.") end reset_n() root = TreeNode(node_data_type()) parse_newick!(nw, root, node_data_type) root.isroot = true # Rooting the tree with outer-most node of the newick string root.tau = missing return root end """ parse_newick!(nw::AbstractString, root::TreeNode) Parse the tree contained in Newick string `nw`, rooting it at `root`. """ function parse_newick!(nw::AbstractString, root::TreeNode, node_data_type) # Setting isroot to false. Special case of the root is handled in main calling function root.isroot = false # Getting label of the node, after last parenthesis parts = map(x->String(x), split(nw, ")")) lab, tau = nw_parse_name(String(parts[end])) if lab == "" lab = "NODE_$(increment_n())" elseif length(lab) > 1 && lab[1:2] == "[&" # Deal with extended newick annotations lab = "NODE_$(increment_n())" * lab end root.label, root.tau = (lab,tau) if length(parts) == 1 # Is a leaf. Subtree is empty root.isleaf = true else # Has children root.isleaf = false if parts[1][1] != '(' println(parts[1][1]) @error "Parenthesis mismatch around $(parts[1]). This may be caused by spaces in the newick string." error("$(get_nwk_file()): incorrect Newick format.") else parts[1] = parts[1][2:end] # Removing first bracket end children = join(parts[1:end-1], ")") # String containing children, now delimited with ',' l_children = nw_parse_children(children) # List of children (array of strings) for sc in l_children nc = TreeNode(node_data_type()) parse_newick!(sc, nc, node_data_type) # Will set everything right for subtree corresponding to nc nc.anc = root push!(root.child, nc) end end end """ nw_parse_children(s::AbstractString) Idea from http://stackoverflow.com/a/26809037 Split a string of children in newick format to an array of strings. ## Example `"A,(B,C),D"` --> `["A","(B,C)","D"]` """ function nw_parse_children(s::AbstractString) parcount = 0 annotation = false # For reading extended newick grammar, with [&key=val] after label l_children = [] current = "" cstart = 1 cend = 1 for (i,c) in enumerate("$(s),") if c == '[' annotation = true elseif c == ']' annotation = false elseif c == ',' && parcount == 0 && annotation == false cend = i-1 push!(l_children, s[cstart:cend]) cstart = i+1 else if c == '(' parcount +=1 elseif c == ')' parcount -=1 end end end return l_children end """ nw_parse_name(s::AbstractString) Parse Newick string of child into name and time to ancestor. Default value for missing time is `missing`. """ function nw_parse_name(s::AbstractString) if occursin(':', s) # Node has a time temp = split(s, ":") if length(temp) > 1 # Node also has a name, return both length(temp) != 2 && @warn("Unexpected format $s: may cause some issues") tau = (tau = tryparse(Float64,temp[2]); isnothing(tau) ? missing : tau) # Dealing with unparsable times return string(temp[1]), tau else # Return empty name tau = (tau = tryparse(Float64,temp[1]); isnothing(tau) ? missing : tau) # Dealing with unparsable times return "", tau end else # Node does not have a time, return string as name return s, missing end end
TreeTools
https://github.com/PierreBarrat/TreeTools.jl.git
[ "MIT" ]
0.6.13
0102ab9be27a64b0963c77280a495c761e1a8c4f
code
1839
""" star_tree(n, times) Create a star tree with `n` leaves. `times` can be an iterable of length `n` or a number/missing. """ function star_tree(n::Integer, time::Union{Missing, Real} = missing) return star_tree(n, Iterators.map(x -> time, 1:n)) end function star_tree(n::Integer, time_vals) @assert n > 0 "Number of leaves must be positive" @assert length(time_vals) == n "Number of leaves and times must match - \ Instead $n and $(length(time_vals))" tree = Tree(TreeNode(; label="root")) for (i, t) in enumerate(time_vals) graft!(tree, TreeNode(; label="$i", tau=t), "root"; graft_on_leaf=true) end return tree end """ ladder_tree(n[, t=missing]) Return a ladder tree with `n` leaves with total height `t`. For 4 leaves `A, B, C, D`, this would be `(A:t,(B:2t/3,(C:t/3,D:t/3)));`. The elementary branch length is `t/(n-1)` if `n>1`. """ function ladder_tree(n::Integer, T::Union{Missing, Real} = missing) # proceeds by recursively grafting asymetric shapes (An:(T-τ),Bn:τ) onto B_(n-1) @assert n > 0 "Number of leaves must be positive" if n == 1 return Tree(TreeNode(; tau = T)) end τ = ismissing(T) ? missing : T / (n-1) tree = Tree(TreeNode(; label = "root")) # first two nodes of the ladder graft!(tree, TreeNode(; label = "$n", tau=T), "root"; graft_on_leaf=true) node = graft!(tree, TreeNode(; tau=τ), "root") _ladder_tree!(tree, label(node), n-1, T-τ, τ) return tree end function _ladder_tree!(tree, node, n, T, τ) # graft the next leaf on node if n > 1 graft!(tree, TreeNode(; label = "$n", tau = T), node; graft_on_leaf=true) node = graft!(tree, TreeNode(; tau = τ), node) _ladder_tree!(tree, node, n-1, T-τ, τ) else label!(tree, node, "$n") end return nothing end
TreeTools
https://github.com/PierreBarrat/TreeTools.jl.git
[ "MIT" ]
0.6.13
0102ab9be27a64b0963c77280a495c761e1a8c4f
code
14528
############################################################# ########################### Split ########################### ############################################################# """ Split `dat::Array{Int,1}`: indices of leaves in the split """ struct Split dat::Array{Int,1} function Split(dat) if !issorted(dat) @error("`split.dat` must be sorted") end return new(dat) end end Split(L::Integer) = Split(fill(typemax(Int), L)) # Iteration Base.iterate(s::Split) = iterate(s.dat) Base.iterate(s::Split, i::Integer) = iterate(s.dat, i) Base.IteratorSize(::Type{Split}) = HasLength() Base.length(s::Split) = length(s.dat) Base.size(s::Split) = length(s) Base.IteratorEltype(::Type{Split}) = HasEltype() Base.eltype(::Type{Split}) = Int Base.eltype(::Split) = Int # Indexing Base.getindex(s::Split, i::Integer) = s.dat[i] # Equality Base.:(==)(s::Split, t::Split) = (s.dat == t.dat) """ isequal(s::Split, t::Split[, mask::Array{Bool,1}]) Test for equality between splits restricted to `mask`. """ function Base.isequal(s::Split, t::Split, mask::Array{Bool,1}) _in = max(length(s), length(t)) > 20 ? insorted : in for i in s if mask[i] && !_in(i, t.dat) return false end end for i in t if mask[i] && !_in(i, s.dat) return false end end return true end Base.isequal(s::Split, t::Split) = (s.dat == t.dat) Base.hash(s::Split, h::UInt) = hash(s.dat, h) function is_root_split(s::Split, mask::Array{Bool,1}) Lmask = sum(mask) Ls = 0 for i in s if mask[i] Ls += 1 end end return Ls == Lmask end """ isroot(s::Split, mask::Array{Bool,1}) Check if `s` is the root split when restricted to `mask`. """ isroot(s::Split, mask) = is_root_split(s, mask) function is_leaf_split(s::Split, mask::Array{Bool,1}) Ls = 0 for i in s if mask[i] Ls += 1 end if Ls > 1 return false end end return true end is_leaf_split(s) = (length(s) == 1) """ isleaf(s::Split) isleaf(s::Split, mask::Array{Bool,1}) Check if `s` is a leaf split. """ isleaf(s::Split) = is_leaf_split(s) isleaf(s::Split, mask) = is_leaf_split(s, mask) """ isempty(s::Split, mask::Array{Bool,1}) isempty(s::Split) """ function Base.isempty(s::Split, mask::Array{Bool,1}) Ls = 0 for i in s if mask[i] return false end end return true end Base.isempty(s::Split) = isempty(s.dat) """ joinsplits!(s::Split, t...) Join `t` to `s`. """ function joinsplits!(s::Split, t::Vararg{Split}) for x in t append!(s.dat, x.dat) end sort!(s.dat) unique!(s.dat) return nothing end # Same as above, but assume s is initialized with 0s, and start filling at index `i`. function _joinsplits!(s::Split, t::Split, i::Integer) for j in 1:length(t) s.dat[j + i - 1] = t.dat[j] end return nothing end """ joinsplits(s::Split, t::Split) Join `s` and `t`. Return resulting `Split`. """ function joinsplits(s::Split, t...) sc = Split(copy(s.dat)) joinsplits!(sc, t...) return sc end """ is_sub_split(s::Split, t::Split[, mask]) Check if `s` is a subsplit of `t`. """ function is_sub_split(s::Split, t::Split) _in = maximum(length(t)) > 20 ? insorted : in for i in s if !_in(i,t.dat) return false end end return true end function is_sub_split(s::Split, t::Split, mask) _in = maximum(length(t)) > 20 ? insorted : in for i in s if mask[i] && !_in(i,t.dat) return false end end return true end """ are_disjoint(s::Split, t::Split) are_disjoint(s::Split, t::Split, mask) Check if `s` and `t` share leaves. """ function are_disjoint(s::Split, t::Split) _in = maximum(length(t)) > 20 ? insorted : in for i in s if _in(i,t.dat) return false end end for i in t if _in(i,s.dat) return false end end return true end function are_disjoint(s::Split, t::Split, mask) _in = maximum(length(t)) > 20 ? insorted : in for i in s if mask[i] && _in(i,t.dat) return false end end for i in t if mask[i] && _in(i,s.dat) return false end end return true end ############################################################# ######################### SplitList ######################### ############################################################# """ SplitList{T} - `leaves::Array{T,1}`: labels of leaves - `splits::Array{Split,1}` - `mask::Array{Bool,1}`: subset of leaves for which splits apply. - `splitmap::Dict{T,Split}`: indicate the split corresponding to the branch above a node. Only initialized if built from a tree with labels on internal nodes. # Constructors SplitList(leaves::Array{T,1}) where T Empty `SplitList`. SplitList(t::Tree[, mask]) List of splits in `t`. `mask` defaults to ones. SplitList(r::TreeNode, leaves[, mask]) Compute the list of splits below `r`, including `r` itself. Assume that `r` is part of a tree with `leaves`. `mask` defaults to the set of leaves that are descendents of `r`. """ struct SplitList{T} leaves::Array{T,1} splits::Array{Split,1} mask::Array{Bool,1} splitmap::Dict{T,Split} ## Maps each leaf to the split it is in. function SplitList{T}(leaves::Array{T,1}, splits, mask, splitmap) where T if issorted(leaves) && allunique(leaves) return new(leaves, splits, mask, splitmap) else @error("Leaves must be sorted and unique") end end end function SplitList( leaves::Array{T,1}, splits::Array{Split,1}, mask::Array{Bool,1}, splitmap::Dict ) where T SplitList{T}(leaves, splits, mask, convert(Dict{T, Split}, splitmap)) end function SplitList(leaves::Array{T,1}) where T SplitList{T}( leaves, Array{Split,1}(undef,0), ones(Bool, length(leaves)), Dict{T, Split}() ) end # Iteration Base.iterate(S::SplitList) = iterate(S.splits) Base.iterate(S::SplitList, i::Integer) = iterate(S.splits, i) Base.IteratorSize(::Type{SplitList}) = HasLength() Base.length(S::SplitList) = length(S.splits) Base.IteratorEltype(::Type{SplitList}) = HasEltype() Base.eltype(::Type{SplitList}) = TreeTools.Split Base.eltype(::SplitList) = Split # Indexing Base.getindex(S::SplitList, i) = getindex(S.splits, i) Base.setindex!(S::SplitList, s::Split, i) = setindex!(S.splits, s, i) Base.firstindex(S::SplitList) = firstindex(S.splits) Base.lastindex(S::SplitList) = lastindex(S.splits) Base.eachindex(S::SplitList) = eachindex(S.splits) Base.isempty(S::SplitList) = isempty(S.splits) Base.keys(S::SplitList) = LinearIndices(S.splits) # Equality function Base.:(==)(S::SplitList, T::SplitList) S.leaves == T.leaves && sort(S.splits, by=x->x.dat) == sort(T.splits, by=x->x.dat) && S.mask == T.mask end Base.hash(S::SplitList, h::UInt) = hash(S.splits, h) function Base.cat(aS::Vararg{SplitList{T}}) where T if !mapreduce(S->S.leaves==aS[1].leaves && S.mask==aS[1].mask, *, aS, init=true) error("Split lists do not share leaves or masks") end catS = SplitList(aS[1].leaves, Array{Split,1}(undef,0), aS[1].mask, Dict{T, Split}()) for S in aS append!(catS.splits, S.splits) end unique!(catS.splits) return catS end """ isroot(S::SplitList, i) Is `S[i]` the root? """ isroot(S::SplitList, i) = isroot(S[i], S.mask) """ leaves(S::SplitList, i) Return array of leaves in `S.splits[i]`, taking `S.mask` into account. """ function leaves(S::SplitList, i) idx = S[i].dat[findall(i -> S.mask[i], S[i].dat)] return S.leaves[idx] end function SplitList(t::Tree, mask=ones(Bool, length(t.lleaves))) leaves = sort(collect(keys(t.lleaves))) leafmap = Dict(leaf=>i for (i,leaf) in enumerate(leaves)) return SplitList(t.root, leaves, mask, leafmap) end function SplitList(r::TreeNode, leaves) leaves_srt = !issorted(leaves) ? sort(leaves) : leaves leafmap = Dict(leaf=>i for (i,leaf) in enumerate(leaves_srt)) # Compute mask : leaves that are descendents or `r` mask = zeros(Bool, length(leaves_srt)) set_mask(n) = if n.isleaf mask[leafmap[n.label]] = true end map!(set_mask, r) # S = SplitList( leaves_srt, Array{Split,1}(undef,0), mask, Dict{eltype(leaves), Split}(), ) _splitlist!(S, r, leafmap) return S end function SplitList( r::TreeNode, leaves, mask, leafmap = Dict(leaf=>i for (i,leaf) in enumerate(sort(leaves))) ) !issorted(leaves) ? leaves_srt = sort(leaves) : leaves_srt = leaves S = SplitList( leaves_srt, Array{Split,1}(undef,0), mask, Dict{eltype(leaves_srt), Split}(), ) _splitlist!(S, r, leafmap) return S end """ _splitlist!(S::SplitList, r::TreeNode, leafmap::Dict) Compute the split defined by `r` and store it in S, by first calling `_splitlist!` on all children of `r` and joining resulting splits. Leaf-splits and root-split are not stored. """ function _splitlist!(S::SplitList, r::TreeNode, leafmap::Dict) if r.isleaf s = Split([leafmap[r.label]]) else L = 0 for c in r.child sc = _splitlist!(S, c, leafmap) L += length(sc) end s = Split(L) i = 1 for c in r.child if c.isleaf s.dat[i] = leafmap[c.label] i += 1 else sc = S.splitmap[c.label] _joinsplits!(s,sc,i) i += length(sc) end end sort!(s.dat) unique!(s.dat) push!(S.splits, s) S.splitmap[r.label] = s end return s end function Base.show(io::IO, S::SplitList) println(io, "SplitList of $(length(S)) splits") max_i = 20 for (i,s) in enumerate(S) if i > max_i println(io, "... ($(length(S)-max_i) more)") break end println(io, leaves(S,i)) end end Base.show(S::SplitList) = show(stdout, S) """ isequal(S::SplitList, i::Integer, j::Integer; mask=true) """ function Base.isequal(S::SplitList, i::Integer, j::Integer; mask=true) if mask return isequal(S.splits[i], S.splits[j], S.mask) else return S.splits[i] == S.splits[j] end end """ isequal(S::SplitList, A::AbstractArray) Is `[leaves(S,i) for i in ...]` equal to `A`? """ function Base.isequal(S::SplitList, A::AbstractArray) sort([leaves(S,i) for i in eachindex(S.splits)]) == sort(A) end ==(S::SplitList, A::AbstractArray) = isequal(S,A) """ arecompatible(s::Split, t::Split[, mask::Array{Bool}]) Are splits `s` and `t` compatible **in the cluster sense**. arecompatible(s::SplitList, i::Integer, j::Integer; mask=true) Are `s.splits[i]` and `s.splits[j]` compatible **in the cluster sense**? """ function arecompatible(s::Split, t::Split) if is_sub_split(s, t) || is_sub_split(t, s) return true elseif are_disjoint(s,t) return true else return false end end function arecompatible(s::Split, t::Split, mask::Array{Bool}) if is_sub_split(s, t, mask) || is_sub_split(t, s, mask) return true elseif are_disjoint(s, t, mask) return true else return false end end function arecompatible(s::SplitList, i::Integer, j::Integer; mask=true) if mask return arecompatible(s.splits[i], s.splits[j], s.mask) else return arecompatible(s.splits[i], s.splits[j]) end end """ iscompatible(s::Split, S::SplitList, mask=S.mask; usemask=true) Is `s` compatible with all splits in `S`? """ function iscompatible(s::Split, S::SplitList, mask=S.mask; usemask=true) for t in S if usemask && !arecompatible(s, t, mask) return false elseif !usemask && !arecompatible(s, t) return false end end return true end """ in(s, S::SplitList, mask=S.mask; usemask=true) Is `s` in `S`? """ function Base.in(s::Split, S::SplitList, mask=S.mask; usemask=true) for t in S if (!usemask && s == t) || (usemask && isequal(s, t, mask)) return true end end return false end """ setdiff(S::SplitList, T::SplitList, mask=:left) Return array of splits in S that are not in T. `mask` options: `:left`, `:right`, `:none`. """ function Base.setdiff(S::SplitList, T::SplitList, mask=:left) if mask == :none m = ones(Bool, length(S.leaves)) usemask = false elseif mask == :left m = S.mask usemask = true elseif mask == :right m = T.mask usemask = true else @error "Unrecognized `mask` kw-arg." end # U = SplitList(S.leaves) for s in S if ( !in(s, T, m; usemask) && !isroot(s, m) && !isleaf(s, m) && !isempty(s,m) ) push!(U.splits, s) end end return U end """ union(S::SplitList, T::SplitList, mask=:none) union!(S::SplitList, T::SplitList, mask=:none) Build a union of `Split`s. Ignore potential incompatibilities. Possible values of `mask` are `:none, :left, :right`. """ union, union! function Base.union!(S::SplitList, T::SplitList; mask=:none) if mask == :none m = ones(Bool, length(S.leaves)) elseif mask == :left m = S.mask elseif mask == :right m = T.mask else @error "Unrecognized `mask` kw-arg." end for t in T if !in(t, S, m) push!(S.splits, t) end end return S end function Base.union!(S::SplitList, T...; mask=:none) for t in T union!(S, t) end return S end function Base.union(S::SplitList, T...; mask=:none) if mask == :none m = ones(Bool, length(S.leaves)) elseif mask == :left m = S.mask elseif mask == :right m = T.mask else @error "Unrecognized `mask` kw-arg." end U = SplitList(copy(S.leaves)) union!(U, S, T...; mask) return U end """ intersect(S::SplitList, T::SplitList, mask=:none) Build an intersection of `Split`s. Possible values of `mask` are `:none, :left, :right`. """ function Base.intersect(S::SplitList, T::SplitList, mask=:none) if mask == :none m = ones(Bool, length(S.leaves)) elseif mask == :left m = S.mask elseif mask == :right m = T.mask else @error "Unrecognized `mask` kw-arg." end # U = SplitList(S.leaves) for s in S if in(s, T, m) push!(U.splits, s) end end return U end """ unique(S::SplitList; usemask=true) unique!(S::SplitList; usemask=true) """ unique, unique! function Base.unique!(S::SplitList; usemask=true) todel = Int64[] hashes = Dict{Array{Int,1}, Bool}() for (i,s) in enumerate(S) if haskey(hashes, s.dat) push!(todel, i) end hashes[s.dat] = true end deleteat!(S.splits, todel) end function Base.unique(S::SplitList; usemask=true) Sc = deepcopy(S) unique!(Sc, usemask=usemask) return Sc end """ clean!(S::SplitList, mask=S.mask; clean_leaves=true, clean_root=false ) Remove leaf and empty splits according to S.mask. Option to remove root. """ function clean!( S::SplitList, mask=S.mask; clean_leaves=true, clean_root=false ) idx = Int64[] for (i,s) in enumerate(S) if clean_leaves && isleaf(s, mask) push!(idx, i) elseif clean_root && isroot(s, mask) push!(idx, i) elseif isempty(s, mask) push!(idx, i) end end deleteat!(S.splits, idx) end ############################################################# ####################### Indexing Tree ####################### ############################################################# function Base.getindex(tree::Tree, S::SplitList, i::Int) return lca(tree, leaves(S, i)...) end
TreeTools
https://github.com/PierreBarrat/TreeTools.jl.git
[ "MIT" ]
0.6.13
0102ab9be27a64b0963c77280a495c761e1a8c4f
code
2957
const write_styles = (:newick) """ write(io::IO, t::Tree; style=:newick, internal_labels=true, write_root=true) write(filename::AbstractString, t::Tree, mode="w"; kwargs...) Write `t` to file or IO with format determined by `style`. If `internal_labels == false`, do not write labels of internal nodes in the string. """ function write(io::IO, t::Tree; style=:newick, internal_labels=true, write_root=true) return if style in (:newick, :Newick, "newick", "Newick") write_newick(io, t; internal_labels, write_root) else @error "Unknown write style $style. Allowed: $(write_styles)." error() end end function write( filename::AbstractString, t::Tree, mode::AbstractString = "w"; kwargs... ) return open(filename, mode) do io write(io, t; kwargs...) end end """ write(filename, trees...; style=:newick, internal_labels=true) Write each tree in `trees` in `filename`, separated by a newline '\n' character. """ function write( filename::AbstractString, trees::Vararg{Tree}; kwargs... ) return open(filename, "w") do io for (i,t) in enumerate(trees) write(io, t; kwargs...) i < length(trees) && write(io, '\n') end end end """ write_newick(io::IO, tree::Tree; kwargs...) write_newick(filename::AbstractString, tree::Tree, mode="w"; kwargs...) write_newick(tree::Tree; kwargs...) Write Newick string corresponding to `tree` to `io` or `filename`. If output is not provided, return the Newick string. If `internal_labels == false`, do not write labels of internal nodes in the string. """ function write_newick(io::IO, tree::Tree; kwargs...) return write(io, newick(tree; kwargs...) * "\n") end function write_newick( filename::AbstractString, tree::Tree, mode::AbstractString = "w"; kwargs... ) return open(filename, mode) do io write_newick(io, tree; kwargs...) end end """ newick(tree::Tree; internal_labels=true, write_root=true) Return the Newick string correpsonding to `tree`. If `internal_labels == false`, do not write labels of internal nodes in the string. If `!write_root`, do not write label and time for the root node (unrooted tree). """ write_newick(tree::Tree; kwargs...) = newick(tree; kwargs...) write_newick(node::TreeNode) = newick(node) newick(tree::Tree; kwargs...) = newick(tree.root; kwargs...) function newick(root::TreeNode; internal_labels = true, write_root=true) return _newick!("", root, internal_labels, write_root)*";" end function _newick!(s::String, root::TreeNode, internal_labels=true, write_root=true) if !isempty(root.child) s *= '(' # temp = sort(root.child, by=x->length(POTleaves(x))) for c in root.child s = _newick!(s, c, internal_labels) s *= ',' end s = s[1:end-1] # Removing trailing ',' s *= ')' end if isleaf(root) || (internal_labels && (!isroot(root) || write_root)) s *= root.label end if !ismissing(root.tau) && !isroot(root) s *= ':' s *= string(root.tau) end if isroot(root) && write_root s *= ":0" end return s end
TreeTools
https://github.com/PierreBarrat/TreeTools.jl.git
[ "MIT" ]
0.6.13
0102ab9be27a64b0963c77280a495c761e1a8c4f
code
923
using TreeTools using Test @testset verbose=true "TreeTools" begin @testset "IO" begin println("## IO") include("$(dirname(pathof(TreeTools)))/../test/IO/test.jl") end @testset "Objects" begin println("## Objects") include("$(dirname(pathof(TreeTools)))/../test/objects/test.jl") end @testset "Methods" begin println("## Methods") include("$(dirname(pathof(TreeTools)))/../test/methods/test.jl") end @testset "Prune/Graft" begin println("## Prune/Graft") include("prunegraft/test.jl") end @testset "Iterators" begin println("## Iterators") include("$(dirname(pathof(TreeTools)))/../test/iterators/test.jl") end @testset "Splits" begin println("## Splits") include("$(dirname(pathof(TreeTools)))/../test/splits/test.jl") end @testset "Simple shapes" begin println("## Shapes") include("$(dirname(pathof(TreeTools)))/../test/simple_shapes/test.jl") end end
TreeTools
https://github.com/PierreBarrat/TreeTools.jl.git
[ "MIT" ]
0.6.13
0102ab9be27a64b0963c77280a495c761e1a8c4f
code
922
# println("##### reading #####") using Test using TreeTools # Reading @testset "Basic" begin @test typeof(read_tree("$(dirname(pathof(TreeTools)))/../test/IO/trees.nwk")) <: Vector{<:Tree} @test typeof(read_tree("$(dirname(pathof(TreeTools)))/../test/IO/tree.nwk")) <: Tree @test isa(read_tree("$(dirname(pathof(TreeTools)))/../test/IO/tree.nwk"; node_data_type=MiscData), Tree{MiscData}) @test read_tree("$(dirname(pathof(TreeTools)))/../test/IO/tree.nwk"; label="test_tree").label == "test_tree" end # Writing @testset "Writing to file" begin tmp_file_name, tmp_file_io = mktemp() t1 = parse_newick_string("((D,A,B),C);") @test try write_newick(tmp_file_name, t1, "w"); true catch err false end @test try write_newick(tmp_file_io, t1); true catch err false end @test try write(tmp_file_name, t1); true catch err false end @test try write(tmp_file_io, t1); true catch err false end end
TreeTools
https://github.com/PierreBarrat/TreeTools.jl.git
[ "MIT" ]
0.6.13
0102ab9be27a64b0963c77280a495c761e1a8c4f
code
903
using Test using TreeTools # println("##### iterators #####") begin nwk = "(((A1:1,A2:1,B:1,C:1)i_2:0.5,(D1:0,D2:0)i_3:1.5)i_1:1,(E:1.5,(F:1.0,(G:0.,H:0.)i_6:0.5)i_5:1)i_4:1)i_r;" tree = parse_newick_string(nwk) tnodes = sort(["A1", "A2", "B", "C", "i_2", "D1", "D2", "i_3", "i_1", "E", "F", "G", "H", "i_6", "i_5", "i_4", "i_r"]) tleaves = sort(["A1", "A2", "B", "C", "D1", "D2", "E", "F", "G", "H"]) @testset "1" begin @test sort([x.label for x in POT(tree)]) == tnodes @test sort([x.label for x in TreeTools.POTleaves(tree)]) == tleaves end @testset "in" begin for n in nodes(tree) @test in(n, tree) @test in(n.label, tree) if !n.isleaf @test !in(n, tree; exclude_internals=true) end end end @testset "indexing in tree" begin for n in nodes(tree) @test tree[n.label] == tree.lnodes[n.label] end @test_throws KeyError tree["some_random_string"] end end
TreeTools
https://github.com/PierreBarrat/TreeTools.jl.git
[ "MIT" ]
0.6.13
0102ab9be27a64b0963c77280a495c761e1a8c4f
code
805
using Test using TreeTools print("empty node: \n") n = TreeNode() empty_t = node2tree(n); print_tree_ascii(IO, empty_t) print("single node: \n") t1 = parse_newick_string("A:1") print_tree_ascii(IO, t1) print("nodes with branch length: \n") t1 = parse_newick_string("(A:1, B:2)R:0") print_tree_ascii(IO, t1) print("unnamed nodes and no branch length: \n") t2 = parse_newick_string("(A:1,)") print_tree_ascii(IO, t2) print("unnamed node with branch length: \n") t2 = parse_newick_string("(A:1,:2):0") print_tree_ascii(IO, t2) print("node with no branch length: \n") t2 = parse_newick_string("(A:1, B)R") print_tree_ascii(IO, t2) print("tree with branch lengths from nwk file") t3 = node2tree(TreeTools.read_newick("$(dirname(pathof(TreeTools)))/../test/iterators/tree1.nwk")) print_tree_ascii(IO, t3)
TreeTools
https://github.com/PierreBarrat/TreeTools.jl.git