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.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
4114
@test isone(@inferred(StaticArrayInterface.known_first(typeof(static(1):2:10)))) @test isone(@inferred(StaticArrayInterface.known_last(typeof(static(-1):static(2):static(1))))) # CartesianIndices CI = CartesianIndices((static(1):static(2), static(1):static(2))) @test @inferred(StaticArrayInterface.known_last(typeof(CI))) == CartesianIndex(2, 2) @testset "length" begin @test @inferred(StaticArrayInterface.known_length(typeof(Static.OptionallyStaticStepRange(static(1), 2, 10)))) === nothing @test @inferred(StaticArrayInterface.known_length(typeof(Static.SOneTo{-10}()))) === 0 @test @inferred(StaticArrayInterface.known_length(typeof(Static.OptionallyStaticStepRange(static(1), static(1), static(10))))) === 10 @test @inferred(StaticArrayInterface.known_length(typeof(Static.OptionallyStaticStepRange(static(2), static(1), static(10))))) === 9 @test @inferred(StaticArrayInterface.known_length(typeof(Static.OptionallyStaticStepRange(static(2), static(2), static(10))))) === 5 @test @inferred(StaticArrayInterface.known_length(Int)) === 1 end @testset "indices" begin A23 = ones(2,3); SA23 = MArray(A23); A32 = ones(3,2); SA32 = MArray(A32); @test @inferred(StaticArrayInterface.indices(A23, (static(1),static(2)))) === (Base.Slice(StaticInt(1):2), Base.Slice(StaticInt(1):3)) @test @inferred(StaticArrayInterface.indices((A23, A32))) == 1:6 @test @inferred(StaticArrayInterface.indices((SA23, A32))) == 1:6 @test @inferred(StaticArrayInterface.indices((A23, SA32))) == 1:6 @test @inferred(StaticArrayInterface.indices((SA23, SA32))) == 1:6 @test @inferred(StaticArrayInterface.indices(A23)) == 1:6 @test @inferred(StaticArrayInterface.indices(SA23)) == 1:6 @test @inferred(StaticArrayInterface.indices(A23, 1)) == 1:2 @test @inferred(StaticArrayInterface.indices(SA23, StaticInt(1))) === Base.Slice(StaticInt(1):StaticInt(2)) @test @inferred(StaticArrayInterface.indices((A23, A32), (1, 2))) == 1:2 @test @inferred(StaticArrayInterface.indices((SA23, A32), (StaticInt(1), 2))) === Base.Slice(StaticInt(1):StaticInt(2)) @test @inferred(StaticArrayInterface.indices((A23, SA32), (1, StaticInt(2)))) === Base.Slice(StaticInt(1):StaticInt(2)) @test @inferred(StaticArrayInterface.indices((SA23, SA32), (StaticInt(1), StaticInt(2)))) === Base.Slice(StaticInt(1):StaticInt(2)) @test @inferred(StaticArrayInterface.indices((A23, A23), 1)) == 1:2 @test @inferred(StaticArrayInterface.indices((SA23, SA23), StaticInt(1))) === Base.Slice(StaticInt(1):StaticInt(2)) @test @inferred(StaticArrayInterface.indices((SA23, A23), StaticInt(1))) === Base.Slice(StaticInt(1):StaticInt(2)) @test @inferred(StaticArrayInterface.indices((A23, SA23), StaticInt(1))) === Base.Slice(StaticInt(1):StaticInt(2)) @test @inferred(StaticArrayInterface.indices((SA23, SA23), StaticInt(1))) === Base.Slice(StaticInt(1):StaticInt(2)) @test_throws ErrorException StaticArrayInterface.indices((A23, ones(3, 3)), 1) @test_throws ErrorException StaticArrayInterface.indices((A23, ones(3, 3)), (1, 2)) @test_throws ErrorException StaticArrayInterface.indices((SA23, ones(3, 3)), StaticInt(1)) @test_throws ErrorException StaticArrayInterface.indices((SA23, ones(3, 3)), (StaticInt(1), 2)) @test_throws ErrorException StaticArrayInterface.indices((SA23, SA23), (StaticInt(1), StaticInt(2))) @test size(similar(ones(2, 4), StaticArrayInterface.indices(ones(2, 4), 1), StaticArrayInterface.indices(ones(2, 4), 2))) == (2, 4) @test axes(StaticArrayInterface.indices(ones(2,2))) === (StaticInt(1):4,) @test axes(Base.Slice(StaticInt(2):4)) === (Base.IdentityUnitRange(StaticInt(2):4),) @test Base.axes1(StaticArrayInterface.indices(ones(2,2))) === StaticInt(1):4 @test Base.axes1(Base.Slice(StaticInt(2):4)) === Base.IdentityUnitRange(StaticInt(2):4) x = vec(A23); y = vec(A32); @test StaticArrayInterface.indices((x',y'),StaticInt(1)) === Base.Slice(StaticInt(1):StaticInt(1)) @test StaticArrayInterface.indices((x,y), StaticInt(2)) === Base.Slice(StaticInt(1):StaticInt(1)) end
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
625
using SafeTestsets, Pkg const GROUP = get(ENV, "GROUP", "All") @time begin if GROUP == "All" || GROUP == "Core" include("setup.jl") include("known_values.jl") include("array_index.jl") include("axes.jl") include("broadcast.jl") include("dimensions.jl") include("indexing.jl") include("ranges.jl") include("size.jl") include("stridelayout.jl") include("misc.jl") @time @safetestset "StaticArrays" begin include("staticarrays.jl") end @time @safetestset "OffsetArrays" begin include("offsetarrays.jl") end end end
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
2386
using StaticArrayInterface, Static, LinearAlgebra, Test struct MArray{T,N,R} <: DenseArray{T,N} parent::Array{T,N} indices::LinearIndices{N,R} end MArray(A::Array) = MArray(A, LinearIndices(map(s -> static(1):static(s), size(A)))) Base.parent(x::MArray) = x.parent Base.IndexStyle(::Type{<:MArray}) = IndexLinear() StaticArrayInterface.static_axes(x::MArray) = StaticArrayInterface.static_axes(x.indices) Base.axes(x::MArray) = StaticArrayInterface.static_axes(x) StaticArrayInterface.axes_types(T::Type{<:MArray}) = T.parameters[3] StaticArrayInterface.static_axes(x::MArray) = StaticArrayInterface.static_axes(x.indices) StaticArrayInterface.defines_strides(::Type{<:MArray}) = true Base.strides(x::MArray) = strides(parent(x)) function Base.getindex(x::MArray, inds...) @boundscheck checkbounds(x, inds...) @inbounds parent(x)[inds...] end Base.size(x::MArray) = map(Int, StaticArrayInterface.static_size(x)) struct NamedDimsWrapper{D,T,N,P<:AbstractArray{T,N}} <: StaticArrayInterface.AbstractArray2{T,N} dimnames::D parent::P NamedDimsWrapper(d::D, p::P) where {D,P} = new{D,eltype(P),ndims(p),P}(d, p) end StaticArrayInterface.is_forwarding_wrapper(::Type{<:NamedDimsWrapper}) = true Base.parent(x::NamedDimsWrapper) = getfield(x, :parent) StaticArrayInterface.parent_type(::Type{T}) where {P,T<:NamedDimsWrapper{<:Any,<:Any,<:Any,P}} = P StaticArrayInterface.dimnames(x::NamedDimsWrapper) = getfield(x, :dimnames) function StaticArrayInterface.known_dimnames(::Type{T}) where {L,T<:NamedDimsWrapper{L}} Static.known(L) end Base.parent(x::NamedDimsWrapper) = x.parent # Dummy array type with undetermined contiguity properties struct DummyZeros{T,N} <: AbstractArray{T,N} dims :: Dims{N} DummyZeros{T}(dims...) where {T} = new{T,length(dims)}(dims) end DummyZeros(dims...) = DummyZeros{Float64}(dims...) Base.size(x::DummyZeros) = x.dims Base.getindex(::DummyZeros{T}, inds...) where {T} = zero(T) struct Wrapper{T,N,P<:AbstractArray{T,N}} <: StaticArrayInterface.AbstractArray2{T,N} parent::P end StaticArrayInterface.parent_type(::Type{<:Wrapper{T,N,P}}) where {T,N,P} = P Base.parent(x::Wrapper) = x.parent StaticArrayInterface.is_forwarding_wrapper(::Type{<:Wrapper}) = true struct DenseWrapper{T,N,P<:AbstractArray{T,N}} <: DenseArray{T,N} end StaticArrayInterface.parent_type(::Type{DenseWrapper{T,N,P}}) where {T,N,P} = P
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
7043
@test @inferred(StaticArrayInterface.static_size(sv5)) === (StaticInt(5),) @test @inferred(StaticArrayInterface.static_size(v5)) === (5,) @test @inferred(StaticArrayInterface.static_size(A)) === (3, 4, 5) @test @inferred(StaticArrayInterface.static_size(Ap)) === (2, 5) @test @inferred(StaticArrayInterface.static_size(A)) === size(A) @test @inferred(StaticArrayInterface.static_size(Ap)) === size(Ap) @test @inferred(StaticArrayInterface.static_size(R)) === (StaticInt(2),) @test @inferred(StaticArrayInterface.static_size(Rnr)) === (StaticInt(4),) @test @inferred(StaticArrayInterface.known_length(Rnr)) === 4 @test @inferred(StaticArrayInterface.static_size(A2)) === (4, 3, 5) @test @inferred(StaticArrayInterface.static_size(A2r)) === (2, 3, 5) @test @inferred(StaticArrayInterface.static_size(view(rand(4), reshape(1:4, 2, 2)))) == (2, 2) @test @inferred(StaticArrayInterface.static_size(irev)) === (StaticInt(2), StaticInt(3), StaticInt(4)) @test @inferred(StaticArrayInterface.static_size(iprod)) === (StaticInt(2), StaticInt(3), StaticInt(4)) @test @inferred(StaticArrayInterface.static_size(iflat)) === (static(72),) @test @inferred(StaticArrayInterface.static_size(igen)) === (StaticInt(2), StaticInt(3), StaticInt(4)) @test @inferred(StaticArrayInterface.static_size(iacc)) === (StaticInt(2), StaticInt(3), StaticInt(4)) @test @inferred(StaticArrayInterface.static_size(ienum)) === (StaticInt(2), StaticInt(3), StaticInt(4)) @test @inferred(StaticArrayInterface.static_size(ipairs)) === (StaticInt(2), StaticInt(3), StaticInt(4)) @test @inferred(StaticArrayInterface.static_size(izip)) === (StaticInt(2), StaticInt(3), StaticInt(4)) @test @inferred(StaticArrayInterface.static_size(zip(S, A_trailingdim))) === (StaticInt(2), StaticInt(3), StaticInt(4), static(1)) @test @inferred(StaticArrayInterface.static_size(zip(A_trailingdim, S))) === (StaticInt(2), StaticInt(3), StaticInt(4), static(1)) @test @inferred(StaticArrayInterface.static_size(S)) === (StaticInt(2), StaticInt(3), StaticInt(4)) @test @inferred(StaticArrayInterface.static_size(Sp)) === (2, 2, StaticInt(3)) @test @inferred(StaticArrayInterface.static_size(Sp2)) === (2, StaticInt(3), StaticInt(2)) @test @inferred(StaticArrayInterface.static_size(S)) == size(S) @test @inferred(StaticArrayInterface.static_size(Sp)) == size(Sp) @test @inferred(StaticArrayInterface.static_size(parent(Sp2))) === (static(4), static(3), static(2)) @test @inferred(StaticArrayInterface.static_size(Sp2)) == size(Sp2) @test @inferred(StaticArrayInterface.static_size(Sp2, StaticInt(1))) === 2 @test @inferred(StaticArrayInterface.static_size(Sp2, StaticInt(2))) === StaticInt(3) @test @inferred(StaticArrayInterface.static_size(Sp2, StaticInt(3))) === StaticInt(2) @test @inferred(StaticArrayInterface.static_size(Wrapper(Sp2), StaticInt(3))) === StaticInt(2) @test @inferred(StaticArrayInterface.static_size(Diagonal([1, 2]))) == size(Diagonal([1, 2])) @test @inferred(StaticArrayInterface.static_size(Mp)) === (StaticInt(3), StaticInt(4)) @test @inferred(StaticArrayInterface.static_size(Mp2)) === (StaticInt(2), 2) @test @inferred(StaticArrayInterface.static_size(Mp)) == size(Mp) @test @inferred(StaticArrayInterface.static_size(Mp2)) == size(Mp2) @test @inferred(StaticArrayInterface.known_size(1)) === () @test @inferred(StaticArrayInterface.known_size(view(rand(4), reshape(1:4, 2, 2)))) == (nothing, nothing) @test @inferred(StaticArrayInterface.known_size(A)) === (nothing, nothing, nothing) @test @inferred(StaticArrayInterface.known_size(Ap)) === (nothing, nothing) @test @inferred(StaticArrayInterface.known_size(Wrapper(Ap))) === (nothing, nothing) @test @inferred(StaticArrayInterface.known_size(R)) === (2,) @test @inferred(StaticArrayInterface.known_size(Wrapper(R))) === (2,) @test @inferred(StaticArrayInterface.known_size(Rnr)) === (4,) @test @inferred(StaticArrayInterface.known_size(Rnr, static(1))) === 4 @test @inferred(StaticArrayInterface.known_size(Ar)) === (nothing, nothing, nothing,) @test @inferred(StaticArrayInterface.known_size(Ar, static(1))) === nothing @test @inferred(StaticArrayInterface.known_size(Ar, static(4))) === 1 @test @inferred(StaticArrayInterface.known_size(A2)) === (nothing, nothing, nothing) @test @inferred(StaticArrayInterface.known_size(A2r)) === (nothing, nothing, nothing) @test @inferred(StaticArrayInterface.known_size(irev)) === (2, 3, 4) @test @inferred(StaticArrayInterface.known_size(igen)) === (2, 3, 4) @test @inferred(StaticArrayInterface.known_size(iprod)) === (2, 3, 4) @test @inferred(StaticArrayInterface.known_size(iflat)) === (72,) @test @inferred(StaticArrayInterface.known_size(iacc)) === (2, 3, 4) @test @inferred(StaticArrayInterface.known_size(ienum)) === (2, 3, 4) @test @inferred(StaticArrayInterface.known_size(izip)) === (2, 3, 4) @test @inferred(StaticArrayInterface.known_size(ipairs)) === (2, 3, 4) @test @inferred(StaticArrayInterface.known_size(zip(S, A_trailingdim))) === (2, 3, 4, 1) @test @inferred(StaticArrayInterface.known_size(zip(A_trailingdim, S))) === (2, 3, 4, 1) @test @inferred(StaticArrayInterface.known_length(Iterators.flatten(((x, y) for x in 0:1 for y in 'a':'c')))) === nothing @test @inferred(StaticArrayInterface.known_size(S)) === (2, 3, 4) @test @inferred(StaticArrayInterface.known_size(Wrapper(S))) === (2, 3, 4) @test @inferred(StaticArrayInterface.known_size(Sp)) === (nothing, nothing, 3) @test @inferred(StaticArrayInterface.known_size(Wrapper(Sp))) === (nothing, nothing, 3) @test @inferred(StaticArrayInterface.known_size(Sp2)) === (nothing, 3, 2) @test @inferred(StaticArrayInterface.known_size(Sp2, StaticInt(1))) === nothing @test @inferred(StaticArrayInterface.known_size(Sp2, StaticInt(2))) === 3 @test @inferred(StaticArrayInterface.known_size(Sp2, StaticInt(3))) === 2 @test @inferred(StaticArrayInterface.known_size(Mp)) === (3, 4) @test @inferred(StaticArrayInterface.known_size(Mp2)) === (2, nothing) @testset "known_length" begin @test StaticArrayInterface.known_length(1:2) === nothing @test StaticArrayInterface.known_length((1,)) == 1 @test StaticArrayInterface.known_length((a=1, b=2)) == 2 @test StaticArrayInterface.known_length([]) === nothing @test StaticArrayInterface.known_length(CartesianIndex((1, 2, 3))) === 3 @test @inferred(StaticArrayInterface.known_length(NDIndex((1, 2, 3)))) === 3 itr = StaticInt(1):StaticInt(10) @inferred(StaticArrayInterface.known_length((i for i in itr))) == 10 end @testset "is_lazy_conjugate" begin a = rand(ComplexF64, 2) @test @inferred(StaticArrayInterface.is_lazy_conjugate(a)) == false b = a' @test @inferred(StaticArrayInterface.is_lazy_conjugate(b)) == true c = transpose(b) @test @inferred(StaticArrayInterface.is_lazy_conjugate(c)) == true d = c' @test @inferred(StaticArrayInterface.is_lazy_conjugate(d)) == false e = permutedims(d) @test @inferred(StaticArrayInterface.is_lazy_conjugate(e)) == false @test @inferred(StaticArrayInterface.is_lazy_conjugate([1, 2, 3]')) == false # We don't care about conj on `<:Real` end
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
1927
using StaticArrayInterface using LinearAlgebra using StaticArrays using Static using Test x = @SVector [1,2,3] @test @inferred(StaticArrayInterface.device(typeof(x))) === StaticArrayInterface.CPUTuple() x = @MVector [1,2,3] @test @inferred(StaticArrayInterface.device(typeof(x))) === StaticArrayInterface.CPUPointer() @test isone(StaticArrayInterface.known_first(typeof(StaticArrays.SOneTo(7)))) @test StaticArrayInterface.known_last(typeof(StaticArrays.SOneTo(7))) == 7 @test StaticArrayInterface.known_length(typeof(StaticArrays.SOneTo(7))) == 7 @test StaticArrayInterface.parent_type(SizedVector{1, Int, Vector{Int}}) <: Vector{Int} @test StaticArrayInterface.known_length(@inferred(StaticArrayInterface.indices(SOneTo(7)))) == 7 x = view(SArray{Tuple{3,3,3}}(ones(3,3,3)), :, SOneTo(2), 2) @test @inferred(StaticArrayInterface.known_length(x)) == 6 @test @inferred(StaticArrayInterface.known_length(x')) == 6 v = @SVector rand(8); A = @MMatrix rand(7, 6); T = SizedArray{Tuple{5,4,3}}(zeros(5,4,3)); @test @inferred(StaticArrayInterface.static_length(v)) === StaticInt(8) @test @inferred(StaticArrayInterface.static_length(A)) === StaticInt(42) @test @inferred(StaticArrayInterface.static_length(T)) === StaticInt(60) Am = @MMatrix rand(2,10); @test @inferred(StaticArrayInterface.static_strides(view(Am,1,:))) === (StaticInt(2),) @test @inferred(StaticArrayInterface.contiguous_axis(@SArray(zeros(2,2,2)))) === Static.StaticInt(1) @test @inferred(StaticArrayInterface.contiguous_axis_indicator(@SArray(zeros(2,2,2)))) == (true,false,false) @test @inferred(StaticArrayInterface.contiguous_batch_size(@SArray(zeros(2,2,2)))) === Static.StaticInt(0) @test @inferred(StaticArrayInterface.stride_rank(@SArray(zeros(2,2,2)))) == (1, 2, 3) @test @inferred(StaticArrayInterface.is_column_major(@SArray(zeros(2,2,2)))) === True() @test @inferred(StaticArrayInterface.dense_dims(@SArray(zeros(2,2,2)))) == (true,true,true)
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
28885
@testset "offsets" begin @test @inferred(StaticArrayInterface.known_offsets(A)) === (1, 1, 1) @test @inferred(StaticArrayInterface.known_offsets(Ap)) === (1, 1) @test @inferred(StaticArrayInterface.known_offsets(Ar)) === (1, 1, 1) @test @inferred(StaticArrayInterface.known_offsets(Ar, static(1))) === 1 @test @inferred(StaticArrayInterface.known_offsets(Ar, static(4))) === 1 @test @inferred(StaticArrayInterface.known_offsets(A2)) === (1, 1, 1) @test @inferred(StaticArrayInterface.known_offsets(A2r)) === (1, 1, 1) @test @inferred(StaticArrayInterface.offsets(A)) === (StaticInt(1), StaticInt(1), StaticInt(1)) @test @inferred(StaticArrayInterface.offsets(Ap)) === (StaticInt(1), StaticInt(1)) @test @inferred(StaticArrayInterface.offsets(Ar)) === (StaticInt(1), StaticInt(1), StaticInt(1)) @test @inferred(StaticArrayInterface.offsets(A2)) === (StaticInt(1), StaticInt(1), StaticInt(1)) @test @inferred(StaticArrayInterface.offsets(A2r)) === (StaticInt(1), StaticInt(1), StaticInt(1)) @test @inferred(StaticArrayInterface.offsets(S)) === (StaticInt(1), StaticInt(1), StaticInt(1)) @test @inferred(StaticArrayInterface.offsets(Sp)) === (StaticInt(1), StaticInt(1), StaticInt(1)) @test @inferred(StaticArrayInterface.offsets(Sp2)) === (StaticInt(1), StaticInt(1), StaticInt(1)) @test @inferred(StaticArrayInterface.known_offsets(S)) === (1, 1, 1) @test @inferred(StaticArrayInterface.known_offsets(Sp)) === (1, 1, 1) @test @inferred(StaticArrayInterface.known_offsets(Sp2)) === (1, 1, 1) @test @inferred(StaticArrayInterface.known_offsets(R)) === (1,) @test @inferred(StaticArrayInterface.known_offsets(Rnr)) === (1,) @test @inferred(StaticArrayInterface.known_offsets(1:10)) === (1,) end @testset "strides" begin @test @inferred(StaticArrayInterface.static_strides(A)) === (StaticInt(1), 3, 12) @test @inferred(StaticArrayInterface.static_strides(Ap)) === (StaticInt(1), 12) @test @inferred(StaticArrayInterface.static_strides(A)) == strides(A) @test @inferred(StaticArrayInterface.static_strides(Ap)) == strides(Ap) @test @inferred(StaticArrayInterface.static_strides(Ar)) === (StaticInt{1}(), 6, 24) @test @inferred(StaticArrayInterface.static_strides(A2)) === (StaticInt(1), 4, 12) @test @inferred(StaticArrayInterface.static_strides(A2r)) === (StaticInt(1), 2, 6) @test @inferred(StaticArrayInterface.static_strides(S)) === (StaticInt(1), StaticInt(2), StaticInt(6)) @test @inferred(StaticArrayInterface.static_strides(Sp)) === (StaticInt(6), StaticInt(1), StaticInt(2)) @test @inferred(StaticArrayInterface.static_strides(Sp2)) === (StaticInt(6), StaticInt(2), StaticInt(1)) @test @inferred(StaticArrayInterface.static_strides(view(Sp2, :, 1, 1)')) === (StaticInt(6), StaticInt(6)) @test @inferred(StaticArrayInterface.static_stride(Sp2, StaticInt(1))) === StaticInt(6) @test @inferred(StaticArrayInterface.static_stride(Sp2, StaticInt(2))) === StaticInt(2) @test @inferred(StaticArrayInterface.static_stride(Sp2, StaticInt(3))) === StaticInt(1) @test @inferred(StaticArrayInterface.static_strides(Mp)) === (StaticInt(2), StaticInt(6)) @test @inferred(StaticArrayInterface.static_strides(Mp2)) === (StaticInt(1), StaticInt(6)) @test @inferred(StaticArrayInterface.static_strides(Mp)) == strides(Mp) @test @inferred(StaticArrayInterface.static_strides(Mp2)) == strides(Mp2) @test_throws MethodError StaticArrayInterface.static_strides(DummyZeros(3,4)) @test @inferred(StaticArrayInterface.known_strides(A)) === (1, nothing, nothing) @test @inferred(StaticArrayInterface.known_strides(Ap)) === (1, nothing) @test @inferred(StaticArrayInterface.known_strides(Ar)) === (1, nothing, nothing) @test @inferred(StaticArrayInterface.known_strides(reshape(view(zeros(100), 1:60), (3,4,5)))) === (1, nothing, nothing) @test @inferred(StaticArrayInterface.known_strides(A2)) === (1, nothing, nothing) @test @inferred(StaticArrayInterface.known_strides(A2r)) === (1, nothing, nothing) @test @inferred(StaticArrayInterface.known_strides(S)) === (1, 2, 6) @test @inferred(StaticArrayInterface.known_strides(Sp)) === (6, 1, 2) @test @inferred(StaticArrayInterface.known_strides(Sp2)) === (6, 2, 1) @test @inferred(StaticArrayInterface.known_strides(Sp2, StaticInt(1))) === 6 @test @inferred(StaticArrayInterface.known_strides(Sp2, StaticInt(2))) === 2 @test @inferred(StaticArrayInterface.known_strides(Sp2, StaticInt(3))) === 1 @test @inferred(StaticArrayInterface.known_strides(Sp2, StaticInt(4))) === StaticArrayInterface.known_length(Sp2) @test @inferred(StaticArrayInterface.known_strides(view(Sp2, :, 1, 1)')) === (6, 6) end @testset "Static-Dynamic Size, Strides, and Offsets" begin colors = [(R = rand(), G = rand(), B = rand()) for i ∈ 1:100]; colormat = reinterpret(reshape, Float64, colors) @test @inferred(StaticArrayInterface.static_strides(colormat)) === (StaticInt(1), StaticInt(3)) @test @inferred(StaticArrayInterface.dense_dims(colormat)) === (True(),True()) @test @inferred(StaticArrayInterface.dense_dims(view(colormat,:,4))) === (True(),) @test @inferred(StaticArrayInterface.dense_dims(view(colormat,:,4:7))) === (True(),True()) @test @inferred(StaticArrayInterface.dense_dims(view(colormat,2:3,:))) === (True(),False()) Rr = reinterpret(reshape, Int32, R) @test @inferred(StaticArrayInterface.static_axes(Rr)) === (static(1):static(2), static(1):static(2)) @test @inferred(StaticArrayInterface.known_size(Rr)) === (2, 2) Sr = Wrapper(reinterpret(reshape, Complex{Int64}, S)) @test @inferred(StaticArrayInterface.static_axes(Sr)) == (static(1):static(3), static(1):static(4)) @test @inferred(StaticArrayInterface.known_size(Sr)) === (3, 4) @test @inferred(StaticArrayInterface.static_strides(Sr)) === (static(1), static(3)) Sr2 = reinterpret(reshape, Complex{Int64}, S); @test @inferred(StaticArrayInterface.dense_dims(Sr2)) === (True(),True()) @test @inferred(StaticArrayInterface.dense_dims(view(Sr2,:,2))) === (True(),) @test @inferred(StaticArrayInterface.dense_dims(view(Sr2,:,2:3))) === (True(),True()) @test @inferred(StaticArrayInterface.dense_dims(view(Sr2,2:3,:))) === (True(),False()) Ar2c = reinterpret(reshape, Complex{Float64}, view(rand(2, 5, 7), :, 2:4, 3:5)); @test @inferred(StaticArrayInterface.static_strides(Ar2c)) === (StaticInt(1), 5) Ar2cβ€² = reinterpret(reshape, Complex{Float64}, view(rand(4, 5, 7), Base.oneto(2), 2:4, 3:5)); @test @inferred(StaticArrayInterface.static_strides(Ar2cβ€²)) === (2, 10) Ar2cβ€³ = reinterpret(reshape, Complex{Float64}, view(rand(3, 5, 7), Base.oneto(2), 2:4, 3:5)); @test_throws ArgumentError StaticArrayInterface.static_strides(Ar2cβ€³) Ar2c_static = reinterpret(reshape, Complex{Float64}, view(MArray(rand(2, 5, 7)), :, 2:4, 3:5)); @test @inferred(StaticArrayInterface.static_strides(Ar2c_static)) === (StaticInt(1), StaticInt(5)) Ac2r = reinterpret(reshape, Float64, view(rand(ComplexF64, 5, 7), 2:4, 3:6)); @test @inferred(StaticArrayInterface.static_strides(Ac2r)) === (StaticInt(1), StaticInt(2), 10) Ac2r_static = reinterpret(reshape, Float64, view(MArray(rand(ComplexF64, 5, 7)), 2:4, 3:6)); @test @inferred(StaticArrayInterface.static_strides(Ac2r_static)) === (StaticInt(1), StaticInt(2), StaticInt(10)) Ac2t = reinterpret(reshape, Tuple{Float64,Float64}, view(rand(ComplexF64, 5, 7), 2:4, 3:6)); @test @inferred(StaticArrayInterface.static_strides(Ac2t)) === (StaticInt(1), 5) Ac2t_static = reinterpret(reshape, Tuple{Float64,Float64}, view(MArray(rand(ComplexF64, 5, 7)), 2:4, 3:6)); @test @inferred(StaticArrayInterface.static_strides(Ac2t_static)) === (StaticInt(1), StaticInt(5)) a = rand(Float32, 100, 2); b = reinterpret(Float64, view(a,:,1)); @test @inferred(StaticArrayInterface.contiguous_axis(a)) === StaticInt(1) @test @inferred(StaticArrayInterface.stride_rank(b)) === (StaticInt(1),) end @testset "Memory Layout" begin x = zeros(100); @test StaticArrayInterface.static_axes(Base.Broadcast.Broadcasted(+, (x, x'))) === (Base.OneTo(100), Base.OneTo(100)) # R = reshape(view(x, 1:100), (10,10)); # A = zeros(3,4,5); A = Wrapper(reshape(view(x, 1:60), (3,4,5))); B = A .== 0; D1 = view(A, 1:2:3, :, :); # first dimension is discontiguous D2 = view(A, :, 2:2:4, :); # first dimension is contiguous @test @inferred(StaticArrayInterface.defines_strides(x)) @test @inferred(StaticArrayInterface.defines_strides(A)) @test @inferred(StaticArrayInterface.defines_strides(D1)) @test !@inferred(StaticArrayInterface.defines_strides(view(A, :, [1,2],1))) @test @inferred(StaticArrayInterface.defines_strides(DenseWrapper{Int,2,Matrix{Int}})) @test @inferred(StaticArrayInterface.device(A)) === StaticArrayInterface.CPUPointer() @test @inferred(StaticArrayInterface.device(B)) === StaticArrayInterface.CPUIndex() @test @inferred(StaticArrayInterface.device(-1:19)) === StaticArrayInterface.CPUIndex() @test @inferred(StaticArrayInterface.device((1,2,3))) === StaticArrayInterface.CPUTuple() @test @inferred(StaticArrayInterface.device(PermutedDimsArray(A,(3,1,2)))) === StaticArrayInterface.CPUPointer() @test @inferred(StaticArrayInterface.device(view(A, 1, :, 2:4))) === StaticArrayInterface.CPUPointer() @test @inferred(StaticArrayInterface.device(view(A, 1, :, 2:4)')) === StaticArrayInterface.CPUPointer() @test isnothing(StaticArrayInterface.device("Hello, world!")) @test @inferred(StaticArrayInterface.device(DenseWrapper{Int,2,Matrix{Int}})) === StaticArrayInterface.CPUPointer() #= @btime StaticArrayInterface.contiguous_axis($(reshape(view(zeros(100), 1:60), (3,4,5)))) 0.047 ns (0 allocations: 0 bytes) =# @test @inferred(StaticArrayInterface.contiguous_axis(A)) === Static.StaticInt(1) @test @inferred(StaticArrayInterface.contiguous_axis(B)) === Static.StaticInt(1) @test @inferred(StaticArrayInterface.contiguous_axis(-1:19)) === Static.StaticInt(1) @test @inferred(StaticArrayInterface.contiguous_axis(D1)) === Static.StaticInt(-1) @test @inferred(StaticArrayInterface.contiguous_axis(D2)) === Static.StaticInt(1) @test @inferred(StaticArrayInterface.contiguous_axis(PermutedDimsArray(A,(3,1,2)))) === Static.StaticInt(2) @test @inferred(StaticArrayInterface.contiguous_axis(@view(PermutedDimsArray(A,(3,1,2))[2,1:2,:]))) === Static.StaticInt(1) @test @inferred(StaticArrayInterface.contiguous_axis(transpose(@view(PermutedDimsArray(A,(3,1,2))[2,1:2,:])))) === Static.StaticInt(2) @test @inferred(StaticArrayInterface.contiguous_axis(@view(PermutedDimsArray(A,(3,1,2))[2:3,1:2,:]))) === Static.StaticInt(2) @test @inferred(StaticArrayInterface.contiguous_axis(@view(PermutedDimsArray(A,(3,1,2))[2:3,2,:]))) === Static.StaticInt(-1) @test @inferred(StaticArrayInterface.contiguous_axis(PermutedDimsArray(@view(A[2,:,:]),(2,1)))) === Static.StaticInt(-1) @test @inferred(StaticArrayInterface.contiguous_axis(@view(PermutedDimsArray(A,(3,1,2))[2:3,2,:])')) === Static.StaticInt(-1) @test @inferred(StaticArrayInterface.contiguous_axis(@view(PermutedDimsArray(A,(3,1,2))[:,1:2,1])')) === Static.StaticInt(1) @test @inferred(StaticArrayInterface.contiguous_axis((3,4))) === StaticInt(1) @test @inferred(StaticArrayInterface.contiguous_axis(rand(4)')) === StaticInt(2) @test @inferred(StaticArrayInterface.contiguous_axis(view(@view(PermutedDimsArray(A,(3,1,2))[2:3,2,:])', :, 1)')) === StaticInt(-1) @test @inferred(StaticArrayInterface.contiguous_axis(reshape(DummyZeros(3,4), (4, 3)))) === nothing @test @inferred(StaticArrayInterface.contiguous_axis(DummyZeros(3,4))) === nothing @test @inferred(StaticArrayInterface.contiguous_axis(PermutedDimsArray(DummyZeros(3,4), (2, 1)))) === nothing @test @inferred(StaticArrayInterface.contiguous_axis(view(DummyZeros(3,4), 1, :))) === nothing @test @inferred(StaticArrayInterface.contiguous_axis(view(DummyZeros(3,4), 1, :)')) === nothing @test @inferred(StaticArrayInterface.contiguous_axis_indicator(A)) == (true,false,false) @test @inferred(StaticArrayInterface.contiguous_axis_indicator(B)) == (true,false,false) @test @inferred(StaticArrayInterface.contiguous_axis_indicator(-1:10)) == (true,) @test @inferred(StaticArrayInterface.contiguous_axis_indicator(PermutedDimsArray(A,(3,1,2)))) == (false,true,false) @test @inferred(StaticArrayInterface.contiguous_axis_indicator(@view(PermutedDimsArray(A,(3,1,2))[2,1:2,:]))) == (true,false) @test @inferred(StaticArrayInterface.contiguous_axis_indicator(@view(PermutedDimsArray(A,(3,1,2))[2,1:2,:])')) == (false,true) @test @inferred(StaticArrayInterface.contiguous_axis_indicator(@view(PermutedDimsArray(A,(3,1,2))[2:3,1:2,:]))) == (false,true,false) @test @inferred(StaticArrayInterface.contiguous_axis_indicator(@view(PermutedDimsArray(A,(3,1,2))[2:3,2,:]))) == (false,false) @test @inferred(StaticArrayInterface.contiguous_axis_indicator(@view(PermutedDimsArray(A,(3,1,2))[2:3,2,:])')) == (false,false) @test @inferred(StaticArrayInterface.contiguous_axis_indicator(@view(PermutedDimsArray(A,(3,1,2))[:,1:2,1])')) == (true,false) @test @inferred(StaticArrayInterface.contiguous_axis_indicator(@view(PermutedDimsArray(A,(3,1,2))[:,1:2,[1,3,4]]))) == (false,true,false) @test @inferred(StaticArrayInterface.contiguous_axis_indicator(DummyZeros(3,4))) === nothing @test @inferred(StaticArrayInterface.contiguous_batch_size(A)) === Static.StaticInt(0) @test @inferred(StaticArrayInterface.contiguous_batch_size(B)) === Static.StaticInt(0) @test @inferred(StaticArrayInterface.contiguous_batch_size(-1:18)) === Static.StaticInt(0) @test @inferred(StaticArrayInterface.contiguous_batch_size(PermutedDimsArray(A,(3,1,2)))) === Static.StaticInt(0) @test @inferred(StaticArrayInterface.contiguous_batch_size(@view(PermutedDimsArray(A,(3,1,2))[2,1:2,:]))) === Static.StaticInt(0) @test @inferred(StaticArrayInterface.contiguous_batch_size(@view(PermutedDimsArray(A,(3,1,2))[2,1:2,:])')) === Static.StaticInt(0) @test @inferred(StaticArrayInterface.contiguous_batch_size(@view(PermutedDimsArray(A,(3,1,2))[2:3,1:2,:]))) === Static.StaticInt(0) @test @inferred(StaticArrayInterface.contiguous_batch_size(@view(PermutedDimsArray(A,(3,1,2))[2:3,2,:]))) === Static.StaticInt(-1) @test @inferred(StaticArrayInterface.contiguous_batch_size(@view(PermutedDimsArray(A,(3,1,2))[2:3,2,:])')) === Static.StaticInt(-1) @test @inferred(StaticArrayInterface.contiguous_batch_size(@view(PermutedDimsArray(A,(3,1,2))[:,1:2,1])')) === Static.StaticInt(0) let u_base = randn(10, 10) u_view = view(u_base, 3, :) u_reshaped_view = reshape(u_view, 1, size(u_base, 2)) @test @inferred(StaticArrayInterface.contiguous_batch_size(u_view)) === Static.StaticInt(-1) @test @inferred(StaticArrayInterface.contiguous_batch_size(u_reshaped_view)) === Static.StaticInt(-1) end @test @inferred(StaticArrayInterface.stride_rank(A)) == (1,2,3) @test @inferred(StaticArrayInterface.stride_rank(B)) == (1,2,3) @test @inferred(StaticArrayInterface.stride_rank(-4:4)) == (1,) @test @inferred(StaticArrayInterface.stride_rank(view(A,:,:,1))) === (static(1), static(2)) @test @inferred(StaticArrayInterface.stride_rank(view(A,:,:,1))) === ((Static.StaticInt(1),Static.StaticInt(2))) @test @inferred(StaticArrayInterface.stride_rank(PermutedDimsArray(A,(3,1,2)))) == (3, 1, 2) @test @inferred(StaticArrayInterface.stride_rank(@view(PermutedDimsArray(A,(3,1,2))[2,1:2,:]))) == (1, 2) @test @inferred(StaticArrayInterface.stride_rank(@view(PermutedDimsArray(A,(3,1,2))[2,1:2,:])')) == (2, 1) @test @inferred(StaticArrayInterface.stride_rank(@view(PermutedDimsArray(A,(3,1,2))[2:3,1:2,:]))) == (3, 1, 2) @test @inferred(StaticArrayInterface.stride_rank(@view(PermutedDimsArray(A,(3,1,2))[2:3,2,:]))) == (3, 2) @test @inferred(StaticArrayInterface.stride_rank(@view(PermutedDimsArray(A,(3,1,2))[2:3,2,:])')) == (2, 3) @test @inferred(StaticArrayInterface.stride_rank(@view(PermutedDimsArray(A,(3,1,2))[:,1:2,1])')) == (1, 3) @test @inferred(StaticArrayInterface.stride_rank(@view(PermutedDimsArray(A,(3,1,2))[:,2,1])')) == (2, 1) @test @inferred(StaticArrayInterface.stride_rank(@view(PermutedDimsArray(A,(3,1,2))[:,1:2,[1,3,4]]))) == (3, 1, 2) @test @inferred(StaticArrayInterface.stride_rank(DummyZeros(3,4)')) === nothing @test @inferred(StaticArrayInterface.stride_rank(PermutedDimsArray(DummyZeros(3,4), (2, 1)))) === nothing @test @inferred(StaticArrayInterface.stride_rank(view(DummyZeros(3,4), 1, :))) === nothing uA = reinterpret(reshape, UInt64, A) @test @inferred(StaticArrayInterface.stride_rank(uA)) === StaticArrayInterface.stride_rank(A) rA = reinterpret(reshape, NTuple{3,Float64}, A) @test @inferred(StaticArrayInterface.stride_rank(rA)) === (static(1), static(2)) cA = copy(rA) rcA = reinterpret(reshape, Float64, cA) @test @inferred(StaticArrayInterface.stride_rank(rcA)) === StaticArrayInterface.stride_rank(A) #= @btime StaticArrayInterface.is_column_major($(PermutedDimsArray(A,(3,1,2)))) 0.047 ns (0 allocations: 0 bytes) @btime StaticArrayInterface.is_column_major($(StaticArrayInterface.is_column_major(@view(PermutedDimsArray(A,(3,1,2))[2,1:2,:])))) 0.047 ns (0 allocations: 0 bytes) @btime StaticArrayInterface.is_column_major($(StaticArrayInterface.is_column_major(@view(PermutedDimsArray(A,(3,1,2))[2,1:2,:])'))) 0.047 ns (0 allocations: 0 bytes) PermutedDimsArray(A,(3,1,2))[2:3,1:2,:]) @view(PermutedDimsArray(reshape(view(zeros(100), 1:60), (3,4,5)), (3,1,2)), 2:3, 1:2, :) =# @test @inferred(StaticArrayInterface.is_column_major(A)) === True() @test @inferred(StaticArrayInterface.is_column_major(B)) === True() @test @inferred(StaticArrayInterface.is_column_major(-4:7)) === False() @test @inferred(StaticArrayInterface.is_column_major(PermutedDimsArray(A,(3,1,2)))) === False() @test @inferred(StaticArrayInterface.is_column_major(@view(PermutedDimsArray(A,(3,1,2))[2,1:2,:]))) === True() @test @inferred(StaticArrayInterface.is_column_major(@view(PermutedDimsArray(A,(3,1,2))[2,1:2,:])')) === False() @test @inferred(StaticArrayInterface.is_column_major(@view(PermutedDimsArray(A,(3,1,2))[2:3,1:2,:]))) === False() @test @inferred(StaticArrayInterface.is_column_major(@view(PermutedDimsArray(A,(3,1,2))[2:3,2,:]))) === False() @test @inferred(StaticArrayInterface.is_column_major(@view(PermutedDimsArray(A,(3,1,2))[2:3,2,:])')) === True() @test @inferred(StaticArrayInterface.is_column_major(@view(PermutedDimsArray(A,(3,1,2))[:,1:2,1])')) === True() @test @inferred(StaticArrayInterface.is_column_major(@view(PermutedDimsArray(A,(3,1,2))[:,2,1])')) === False() @test @inferred(StaticArrayInterface.is_column_major(2.3)) === False() @test @inferred(StaticArrayInterface.dense_dims(A)) == (true,true,true) @test @inferred(StaticArrayInterface.dense_dims(B)) == (true,true,true) @test @inferred(StaticArrayInterface.dense_dims(-3:9)) == (true,) @test @inferred(StaticArrayInterface.dense_dims(PermutedDimsArray(A,(3,1,2)))) == (true,true,true) @test @inferred(StaticArrayInterface.dense_dims(@view(PermutedDimsArray(A,(3,1,2))[2,1:2,:]))) == (true,false) @test @inferred(StaticArrayInterface.dense_dims(@view(PermutedDimsArray(A,(3,1,2))[2,1:2,:])')) == (false,true) @test @inferred(StaticArrayInterface.dense_dims(@view(PermutedDimsArray(A,(3,1,2))[2:3,1:2,:]))) == (false,true,false) @test @inferred(StaticArrayInterface.dense_dims(@view(PermutedDimsArray(A,(3,1,2))[2:3,:,1:2]))) == (false,true,true) @test @inferred(StaticArrayInterface.dense_dims(@view(PermutedDimsArray(A,(3,1,2))[2:3,2,:]))) == (false,false) @test @inferred(StaticArrayInterface.dense_dims(@view(PermutedDimsArray(A,(3,1,2))[2:3,2,:])')) == (false,false) @test @inferred(StaticArrayInterface.dense_dims(@view(PermutedDimsArray(A,(3,1,2))[:,1:2,1])')) == (true,false) @test @inferred(StaticArrayInterface.dense_dims(@view(PermutedDimsArray(A,(3,1,2))[2:3,:,[1,2]]))) == (false,true,false) @test @inferred(StaticArrayInterface.dense_dims(@view(PermutedDimsArray(A,(3,1,2))[2:3,[1,2,3],:]))) == (false,false,false) @test @inferred(StaticArrayInterface.dense_dims(reshape(view(randn(10, 10, 10), 3, :, :), 1, 100))) == (false, false) # TODO Currently Wrapper can't function the same as Array because Array can change # the dimensions on reshape. We should be rewrapping the result in `Wrapper` but we # first need to develop a standard method for reconstructing arrays @test @inferred(StaticArrayInterface.dense_dims(vec(parent(A)))) == (true,) @test @inferred(StaticArrayInterface.dense_dims(vec(parent(A))')) == (true,true) @test @inferred(StaticArrayInterface.dense_dims(DummyZeros(3,4))) === nothing @test @inferred(StaticArrayInterface.dense_dims(DummyZeros(3,4)')) === nothing @test @inferred(StaticArrayInterface.dense_dims(PermutedDimsArray(DummyZeros(3,4), (2, 1)))) === nothing @test @inferred(StaticArrayInterface.dense_dims(view(DummyZeros(3,4), :, 1))) === nothing @test @inferred(StaticArrayInterface.dense_dims(view(DummyZeros(3,4), :, 1)')) === nothing @test @inferred(StaticArrayInterface.is_dense(A)) === @inferred(StaticArrayInterface.is_dense(A)) === @inferred(StaticArrayInterface.is_dense(PermutedDimsArray(A,(3,1,2)))) === @inferred(StaticArrayInterface.is_dense(Array{Float64,0}(undef))) === True() @test @inferred(StaticArrayInterface.is_dense(@view(PermutedDimsArray(A,(3,1,2))[2:3,1:2,:]))) === @inferred(StaticArrayInterface.is_dense(@view(PermutedDimsArray(A,(3,1,2))[2:3,:,[1,2]]))) === @inferred(StaticArrayInterface.is_dense(@view(PermutedDimsArray(A,(3,1,2))[2:3,[1,2,3],:]))) === False() C = Array{Int8}(undef, 2,2,2,2); doubleperm = PermutedDimsArray(PermutedDimsArray(C,(4,2,3,1)), (4,2,1,3)); @test collect(strides(C))[collect(StaticArrayInterface.stride_rank(doubleperm))] == collect(strides(doubleperm)) C1 = reinterpret(reshape, Float64, PermutedDimsArray(Array{Complex{Float64}}(undef, 3,4,5), (2,1,3))); C2 = reinterpret(reshape, Complex{Float64}, PermutedDimsArray(view(A,1:2,:,:), (1,3,2))); C3 = reinterpret(reshape, Complex{Float64}, PermutedDimsArray(Wrapper(reshape(view(x, 1:24), (2,3,4))), (1,3,2))); @test @inferred(StaticArrayInterface.defines_strides(C1)) @test @inferred(StaticArrayInterface.defines_strides(C2)) @test @inferred(StaticArrayInterface.defines_strides(C3)) @test @inferred(StaticArrayInterface.device(C1)) === StaticArrayInterface.CPUPointer() @test @inferred(StaticArrayInterface.device(C2)) === StaticArrayInterface.CPUPointer() @test @inferred(StaticArrayInterface.device(C3)) === StaticArrayInterface.CPUPointer() @test @inferred(StaticArrayInterface.contiguous_batch_size(C1)) === Static.StaticInt(0) @test @inferred(StaticArrayInterface.contiguous_batch_size(C2)) === Static.StaticInt(0) @test @inferred(StaticArrayInterface.contiguous_batch_size(C3)) === Static.StaticInt(0) @test @inferred(StaticArrayInterface.stride_rank(C1)) == (1,3,2,4) @test @inferred(StaticArrayInterface.stride_rank(C2)) == (2,1) @test @inferred(StaticArrayInterface.stride_rank(C3)) == (2,1) @test @inferred(StaticArrayInterface.contiguous_axis(C1)) === StaticInt(1) @test @inferred(StaticArrayInterface.contiguous_axis(C2)) === StaticInt(0) @test @inferred(StaticArrayInterface.contiguous_axis(C3)) === StaticInt(2) @test @inferred(StaticArrayInterface.contiguous_axis_indicator(C1)) == (true,false,false,false) @test @inferred(StaticArrayInterface.contiguous_axis_indicator(C2)) == (false,false) @test @inferred(StaticArrayInterface.contiguous_axis_indicator(C3)) == (false,true) @test @inferred(StaticArrayInterface.is_column_major(C1)) === False() @test @inferred(StaticArrayInterface.is_column_major(C2)) === False() @test @inferred(StaticArrayInterface.is_column_major(C3)) === False() @test @inferred(StaticArrayInterface.dense_dims(C1)) == (true,true,true,true) @test @inferred(StaticArrayInterface.dense_dims(C2)) == (false,false) @test @inferred(StaticArrayInterface.dense_dims(C3)) == (true,true) end @testset "Reinterpreted reshaped views" begin u_base = randn(1, 4, 4, 5); u_reinterpreted = reinterpret(Int8, view(u_base, 1:1, 1:4, 1:4, 1:5)) u_vectors = reshape(reinterpret(NTuple{1, eltype(u_base)}, u_base), Base.tail(size(u_base))...) u_view = view(u_vectors, 2, :, 3) u_view_reinterpreted = reinterpret(eltype(u_base), u_view) u_view_reshaped = reshape(u_view_reinterpreted, 1, length(u_view)) # See https://github.com/JuliaArrays/StaticArrayInterface.jl/issues/163 @test @inferred(StaticArrayInterface.static_strides(u_base)) === (StaticInt(1), 1, 4, 16) @test @inferred(StaticArrayInterface.static_strides(u_reinterpreted)) === (StaticInt(1), 8, 32, 128) @test @inferred(StaticArrayInterface.static_strides(u_vectors)) === (StaticInt(1), 4, 16) @test @inferred(StaticArrayInterface.static_strides(u_view)) === (4,) @test @inferred(StaticArrayInterface.static_strides(u_view_reinterpreted)) === (4,) @test @inferred(StaticArrayInterface.static_strides(u_view_reshaped)) === (4, 4) @test @inferred(StaticArrayInterface.static_axes(u_vectors)) isa StaticArrayInterface.axes_types(u_vectors) end @testset "Reshaped strides" begin a = randn(10, 10) @test @inferred(StaticArrayInterface.static_strides(reshape(view(a, :, 1:2:9), 2, 5, 5))) === (1, 2, 20) @test @inferred(StaticArrayInterface.static_strides(vec(view(a, 1, 1)))) === (static(1),) @test_throws ArgumentError StaticArrayInterface.static_strides(reshape(view(a, :, 1:2:9), 5, 5, 2)) a = MArray(randn(10, 10)) @test @inferred(StaticArrayInterface.static_strides(reshape(view(a, 1:9, 1:10), 3, 3, 2, 5))) === (1, 3, 10, 20) @test @inferred(StaticArrayInterface.static_strides(reshape(view(a, static(1):static(9), 1:10), 3, 3, 2, 5))) === (static(1), 3, 10, 20) @test @inferred(StaticArrayInterface.static_strides(reshape(view(a, :, 1:2:9), 2, 5, 5))) === (static(1), 2, 20) a = randn(2, 5, 3) @test @inferred(StaticArrayInterface.static_strides(vec(view(a, :, 1:5, 1:3)))) === (1,) @test @inferred(StaticArrayInterface.static_strides(reshape(view(a, :, 1:5, 1:3), 5, 2, 3))) === (1,5,10) @test @inferred(StaticArrayInterface.static_strides(vec(view(a, static(1):static(2), 1:5, 1:3)))) === (static(1),) @test @inferred(StaticArrayInterface.static_strides(reshape(view(a, static(1):static(2), 1:5, 1:3), 5, 2, 3))) === (static(1),5,10) a = MArray(randn(3, 5, 3)) @test @inferred(StaticArrayInterface.static_strides(vec(view(a, :, 1:5, 1:3)))) === (static(1),) @test @inferred(StaticArrayInterface.static_strides(reshape(view(a, static(1):static(3), static(1):static(4), 1:3), 2, 2, 3, 3))) === (static(1), 2, 4, 15) @test @inferred(StaticArrayInterface.static_strides(reshape(view(a, static(1):static(2), static(1):static(4), 1:3), 2, 2, 2, 3))) === (static(1), 3, 6, 15) @test @inferred(StaticArrayInterface.static_strides(reshape(view(a, static(1):static(2), static(1):static(1), 1:3), 2, 1, 3))) === (static(1), 2, 15) end @testset "Reshaped views" begin u_base = randn(10, 10) u_view = view(u_base, 3, :) u_reshaped_view1 = reshape(u_view, 1, :) u_reshaped_view2 = reshape(u_view, 2, :) @test @inferred(StaticArrayInterface.defines_strides(u_base)) @test @inferred(StaticArrayInterface.defines_strides(u_view)) @test @inferred(StaticArrayInterface.defines_strides(u_reshaped_view1)) @test @inferred(StaticArrayInterface.defines_strides(u_reshaped_view2)) # See https://github.com/JuliaArrays/StaticArrayInterface.jl/issues/160 @test @inferred(StaticArrayInterface.static_strides(u_base)) == (StaticInt(1), 10) @test @inferred(StaticArrayInterface.static_strides(u_view)) == (10,) @test @inferred(StaticArrayInterface.static_strides(u_reshaped_view1)) == (10, 10) @test @inferred(StaticArrayInterface.static_strides(u_reshaped_view2)) == (10, 20) # See https://github.com/JuliaArrays/StaticArrayInterface.jl/issues/157 @test @inferred(StaticArrayInterface.dense_dims(u_base)) == (True(), True()) @test @inferred(StaticArrayInterface.dense_dims(u_view)) == (False(),) @test @inferred(StaticArrayInterface.dense_dims(u_reshaped_view1)) == (False(), False()) @test @inferred(StaticArrayInterface.dense_dims(u_reshaped_view2)) == (False(), False()) end
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
docs
1971
# StaticArrayInterface.jl [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://docs.sciml.ai/StaticArrayInterface/stable/) [![CI](https://github.com/JuliaArrays/StaticArrayInterface.jl/workflows/CI/badge.svg)](https://github.com/JuliaArrays/StaticArrayInterface.jl/actions?query=workflow%3ACI) [![Build status](https://badge.buildkite.com/a2db252d92478e1d7196ee7454004efdfb6ab59496cbac91a2.svg?branch=master)](https://buildkite.com/julialang/StaticArrayInterface-dot-jl) [![codecov](https://codecov.io/gh/JuliaArrays/StaticArrayInterface.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/JuliaArrays/StaticArrayInterface.jl) The AbstractArray interface in Base Julia does not always enforce static guarantees. For example, if the size of an array is known at compile time, many of the indexing schemes are not specialized to make use of that size to build fully optimized code. In most cases a user should rely on the compiler to deduce the static properties and perform the optimization. However, some brave souls believe they can beat the compiler, and this library is for them. Functions like `known_length` return values using [Static.jl](https://github.com/SciML/Static.jl) which encode all of the information at the type level, which in turn forces the computation to occur at compile time. ## Is This Library About StaticArrays? No, not necessarily. StaticArrays.jl is one library about array types which have static compile time information. However, there are many other array types with static compile time information. The purpose of this library is to be able to write code generic to all of those libraries which also keep this property of enforcing the computation is at compile time by using the type space. ## Warning: Compile Times Because this library enforces things be done at compile time by encoding everything into types, using it will increase your compile times. You have been warned, now proceed (with caution).
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
docs
1722
# API ### Traits ```@docs StaticArrayInterface.contiguous_axis StaticArrayInterface.contiguous_axis_indicator StaticArrayInterface.contiguous_batch_size StaticArrayInterface.dimnames StaticArrayInterface.has_dimnames StaticArrayInterface.has_parent StaticArrayInterface.is_column_major StaticArrayInterface.is_lazy_conjugate StaticArrayInterface.is_splat_index StaticArrayInterface.known_dimnames StaticArrayInterface.known_first StaticArrayInterface.known_last StaticArrayInterface.known_length StaticArrayInterface.known_offset1 StaticArrayInterface.known_offsets StaticArrayInterface.known_size StaticArrayInterface.known_step StaticArrayInterface.known_strides ``` ### Functions ```@docs StaticArrayInterface.static_axes StaticArrayInterface.axes_types StaticArrayInterface.broadcast_axis StaticArrayInterface.deleteat StaticArrayInterface.dense_dims StaticArrayInterface.from_parent_dims StaticArrayInterface.getindex StaticArrayInterface.indices StaticArrayInterface.insert StaticArrayInterface.static_length StaticArrayInterface.lazy_axes StaticArrayInterface.offset1 StaticArrayInterface.offsets StaticArrayInterface.setindex! StaticArrayInterface.static_size StaticArrayInterface.static_strides StaticArrayInterface.to_axes StaticArrayInterface.to_axis StaticArrayInterface.to_dims StaticArrayInterface.to_index StaticArrayInterface.static_to_indices StaticArrayInterface.to_parent_dims StaticArrayInterface.unsafe_reconstruct ``` ### Types ```@docs StaticArrayInterface.BroadcastAxis StaticArrayInterface.LazyAxis StaticArrayInterface.OptionallyStaticStepRange StaticArrayInterface.OptionallyStaticUnitRange StaticArrayInterface.SOneTo StaticArrayInterface.SUnitRange StaticArrayInterface.StrideIndex ```
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
docs
12971
```@meta CurrentModule = StaticArrayInterface ``` # StaticArrayInterface Designs for new Base array interface primitives, used widely through scientific machine learning (SciML) and other organizations ## StaticArrayInterfaceCore StaticArrayInterfaceCore is a smaller set of the StaticArrayInterface setup which defines the subset which has no compile time impact. This for example includes simple functions like `StaticArrayInterfaceCore.zeromatrix` which have simple few dispatch definitions and no dependency on other libraries such as Static.jl. Notably, Static.jl currently has issues with invalidations (https://github.com/SciML/Static.jl/issues/52), and thus anything with static outputs are in the domain of StaticArrayInterface.jl proprer. ## Extenion Packages StaticArrayInterface.jl uses extension packages in order to add support for popular libraries to its interface functions. These packages are: - StaticArrays.jl - OffsetArrays.jl ## Inheriting Array Traits Creating an array type with unique behavior in Julia is often accomplished by creating a lazy wrapper around previously defined array types (e.g. [composition by inheritance](https://en.wikipedia.org/wiki/Composition_over_inheritance)). This allows the new array type to inherit functionality by redirecting methods to the parent array (e.g., `Base.size(x::Wrapper) = size(parent(x))`). Generic design limits the need to define an excessive number of methods like this. However, methods used to describe a type's traits often need to be explicitly defined for each trait method. If the the underlying data and access to it are unchanged by it's wrapper the [`StaticArrayInterface.is_forwarding_wrapper`](@ref) trait can signal to other trait methods to access its parent data structure. Supporting this for a new type only requires defines these methods: ```julia StaticArrayInterface.is_forwarding_wrapper(::Type{<:NewType}) = true StaticArrayInterface.parent_type(::Type{<:NewType}) = NewTypeParent Base.parent(x::NewType) = x.parent ``` For those authoring new trait methods, this may change the default definition from `has_trait(::Type{T}) where {T} = false`, to: ```julia function has_trait(::Type{T}) where {T} if is_forwarding_wrapper(T) return false else return has_trait(parent_type(T)) end end ``` Most traits in `StaticArrayInterface` are a variant on this pattern. If the trait in question may be altered by a wrapper array, this pattern should be altered or may be inappropriate. ## Static Traits The size along one or more dimensions of an array may be known at compile time. `StaticArrayInterface.known_size` is useful for extracting this information from array types and `StaticArrayInterface.static_size` is useful for extracting this information from an instance of an array. For example: ```julia julia> a = ones(3)'; julia> StaticArrayInterface.static_size(a) (static(1), 3) julia> StaticArrayInterface.known_size(typeof(a)) (1, nothing) ``` This is useful for dispatching on known information about the size of an array: ```julia fxn(x) = _fxn(StaticArrayInterface.static_size(x), x) _fxn(sz::Tuple{StaticInt{S1},StaticInt{S2}}, x) where {S1,S2} = ... _fxn(sz::Tuple{StaticInt{3},StaticInt{3}}, x) = ... _fxn(sz::Tuple{Int,StaticInt{S2}}, x) where {S2} = ... _fxn(sz::Tuple{StaticInt{S1},Int}, x) where {S1} = ... _fxn(sz::Tuple{Int,Int}, x) = ... ``` Methods should avoid forcing conversion to static sizes when dynamic sizes could potentially be returned. Fore example, `fxn(x) = _fxn(Static.static(StaticArrayInterface.static_size(x)), x)` would result in dynamic dispatch if `x` is an instance of `Matrix`. Additionally, `StaticArrayInterface.static_size` should only be used outside of generated functions to avoid possible world age issues. Generally, `StaticArrayInterface.static_size` uses the return of `known_size` to form a static value for those dimensions with known length and only queries dimensions corresponding to `nothing`. For example, the previous example had a known size of `(1, nothing)`. Therefore, `StaticArrayInterface.static_size` would have compile time information about the first dimension returned as `static(1)` and would only look up the size of the second dimension at run time. This means the above example `StaticArrayInterface.static_size(a)` would lower to code similar to this at compile time: `Static.StaticInt(1), Base.arraysize(x, 1)`. Generic support for `StaticArrayInterface.known_size` relies on calling `known_length` for each type returned from `axes_types`. Therefore, the recommended approach for supporting static sizing in newly defined array types is defining a new `axes_types` method. Static information related to subtypes of `AbstractRange` include `known_length`, `known_first`, `known_step`, and `known_last`. ## Dimensions Methods such as `size(x, dim)` need to map `dim` to the dimensions of `x`. Typically, `dim` is an `Int` with an invariant mapping to the dimensions of `x`. Some methods accept `:` or a tuple of dimensions as an argument. `StaticArrayInterface` also considers `StaticInt` a viable dimension argument. [`StaticArrayInterface.to_dims`](@ref) helps ensure that `dim` is converted to a viable dimension mapping in a manner that helps with type stability. For example, all `Integers` passed to `to_dims` are converted to `Int` (unless `dim` is a `StaticInt`). This is also useful for arrays that uniquely label dimensions, in which case `to_dims` serves as a safe point of hooking into existing methods with dimension arguments. `StaticArrayInterface` also defines native `Symbol` to `Int` and `StaticSymbol` to `StaticInt` mapping for arrays defining [`StaticArrayInterface.dimnames`](@ref). Methods requiring dimension specific arguments should use some variation of the following pattern. ```julia f(x, dim) = f(x, StaticArrayInterface.to_dims(x, dim)) f(x, dim::Int) = ... f(x, dim::StaticInt) = ... ``` If `x`'s first dimension is named `:dim_1` then calling `f(x, :dim_1)` would result in `f(x, 1)`. If users knew they always wanted to call `f(x, 2)` then they could define `h(x) = f(x, static(2))`, ensuring `f` passes along that information while compiling. New types defining dimension names can do something similar to: ```julia using Static using StaticArrayInterface struct StaticDimnames{dnames} end # where dnames::Tuple{Vararg{Symbol}} StaticArrayInterface.known_dimnames(::Type{StaticDimnames{dnames}}) where {dnames} = dnames StaticArrayInterface.dimnames(::StaticDimnames{dnames}) where {dnames} = static(dnames) struct DynamicDimnames{N} dimnames::NTuple{N,Symbol} end StaticArrayInterface.known_dimnames(::Type{DynamicDimnames{N}}) where {N} = ntuple(_-> nothing, Val(N)) StaticArrayInterface.dimnames(x::DynamicDimnames) = getfield(x, :dimnames) ``` Notice that `DynamicDimnames` returns `nothing` instead of a symbol for each dimension. This indicates dimension names are present for `DynamicDimnames` but that information is nothing at compile time. Dimension names should be appropriately propagated between nested arrays using `StaticArrayInterface.to_parent_dims`. This allows types such as `SubArray` and `PermutedDimsArray` to work with named dimensions. Similarly, other methods that return information corresponding to dimensions (e.g., `ArrayInterfce.size`, `StaticArrayInterface.static_axes`) use `to_parent_dims` to appropriately propagate parent information. ## Axes Where Julia's currently documented [array interface]( https://docs.julialang.org/en/v1/manual/interfaces/#man-interface-array) requires defining `Base.size`, StaticArrayInterface instead requires defining [`StaticArrayInterface.static_axes`](@ref) and [`StaticArrayInterface.axes_types`](@ref). `StaticArrayInterface.axes_types(::Type{T})` facilitates propagation of a number of traits known at compile time (e.g., `known_size`, `known_offsets`) and `StaticArrayInterface.static_axes(::AbstractArray)` replaces `Base.OneTo` with `StaticArrayInterface.OptionallyStaticUnitRange` in situations where static information would otherwise be lost. `StaticArrayInterface.static_axes(::AbstractArray, dim)` utilizes `to_dims`, [as described elsewhere](#dimensions). ### Simple Wrappers Let's say we have a new array type doesn't affect axes then this is as simple as: ```julia Base.axes(x::SimpleWrapper) = StaticArrayInterface.static_axes(parent(x)) Base.axes(x::SimpleWrapper, dim) = StaticArrayInterface.static_axes(parent(x), dim) StaticArrayInterface.axes_types(::Type{T}) where {T<:SimpleWrapper} = axes_types(parent_type(T)) ``` To reiterate, `StaticArrayInterface.static_axes` improves on `Base.axes` for few Base array types but is otherwise identical. Therefore, the first method simply ensures you don't have to define multiple parametric methods for your new type to preserve statically sized nested axes (e.g., `SimpleWrapper{T,N,<:Transpose{T,<:AbstractVector}}`). This is otherwise identical to standard inheritance by composition. ### When to Discard Axis Information Occasionally the parent array's axis information can't be preserved. For example, we can't map axis information from the parent array of `Base.ReshapedArray`. In this case we can simply build axes from the new size information. ```julia StaticArrayInterface.axes_types(T::Type{<:ReshapedArray}) = NTuple{ndims(T),OneTo{Int}} StaticArrayInterface.static_axes(A::ReshapedArray) = map(OneTo, size(A)) ``` ### New Axis Types `OffsetArray` changes the first index for each axis. It produces axes of type `IdOffsetRange`, which contains the value of the relative offset and the parent axis. ```julia using StaticArrayInterface: axes_types, parent_type, to_dims # Note that generating a `Tuple` type piecewise like may be type unstable and should be # tested using `Test.@inferred`. It's often necessary to use generated function # (`@generated`) or methods defined in Static.jl. @generated function StaticArrayInterface.axes_types(::Type{A}) where {A<:OffsetArray} out = Expr(:curly, :Tuple) P = parent_type(A) for dim in 1:ndims(A) # offset relative to parent array O = relative_known_offsets(A, dim) if O === nothing # offset is not known at compile time and is an `Int` push!(out.args, :(IdOffsetRange{Int, axes_types($P, $(static(dim)))})) else # offset is known, therefore it is a `StaticInt` push!(out.args, :(IdOffsetRange{StaticInt{$O}, axes_types($P, $(static(dim))})) end end end function Base.axes(A::OffsetArray) map(IdOffsetRange, StaticArrayInterface.static_axes(parent(A)), relative_offsets(A)) end function Base.axes(A::OffsetArray, dim) d = to_dims(A, dim) IdOffsetRange(StaticArrayInterface.static_axes(parent(A), d), relative_offsets(A, d)) end ``` Defining these two methods ensures that other array types that wrap `OffsetArray` and appropriately define these methods propagate offsets independent of any dependency on `OffsetArray`. It is entirely optional to define `StaticArrayInterface.static_size` for `OffsetArray` because the size can be derived from the axes. However, in this particularly case we should also define `StaticArrayInterface.static_size(A::OffsetArray) = StaticArrayInterface.static_size(parent(A))` because the relative offsets attached to `OffsetArray` do not change the size but may hide static sizes if using a relative offset that is defined with an `Int`. ## Processing Indices (`static_to_indices`) For most users, the only reason you should use `StaticArrayInterface.static_to_indices` over `Base.to_indices` is that it's faster and perhaps some of the more detailed benefits described in the [`to_indices`](@ref) doc string. For those interested in how this is accomplished, the following steps (beginning with the `to_indices(A::AbstractArray, I::Tuple)`) are used to accomplish this: 1. The number of dimensions that each indexing argument in `I` corresponds to is determined using using the [`ndims_index`](@ref) and [`is_splat_index`](@ref) traits. 2. A non-allocating reference to each axis of `A` is created (`lazy_axes(A) -> axs`). These are aligned to each the index arguments using information from the first step. For example, if an index argument maps to a single dimension then it is paired with `axs[dim]`. In the case of multiple dimensions it is paired with `CartesianIndices(axs[dim_1], ... axs[dim_n])`. These pairs are further processed using `to_index(axis, I[n])`. 3. Tuples returned from `to_index` are flattened out so that there are no nested tuples returned from `to_indices`. Entry points: * `static_to_indices(::ArrayType, indices)` : dispatch on unique array type `ArrayType` * `to_index(axis, ::IndexType)` : dispatch on a unique indexing type, `IndexType`. `StaticArrayInterface.ndims_index(::Type{IndexType})` should also be defined in this case. * `to_index(S::IndexStyle, axis, index)` : The index style `S` that corresponds to `axis`. This is
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.0.10
d37e67cd855d38efbc41b807f45d758eaaa82923
code
3000
using JDQMCFramework using Documenter using Literate using LinearAlgebra # generates script and notebook versions of tutorials based on literate example function build_examples(example_sources, destdir) assetsdir = joinpath(fill("..", length(splitpath(destdir)))..., "assets") destpath = joinpath(@__DIR__, "src", destdir) isdir(destpath) && rm(destpath; recursive=true) # Transform each Literate source file to Markdown for subsequent processing by # Documenter. for source in example_sources # Extract "example" from "path/example.jl" name = splitext(basename(source))[1] # Preprocess each example by adding a notebook download link at the top. The # relative path is hardcoded according to the layout of `gh-pages` branch, # which is set up by `Documenter.deploydocs`. function preprocess(str) """ # Download this example as [Jupyter notebook]($assetsdir/notebooks/$name.ipynb) or [Julia script]($assetsdir/scripts/$name.jl). """ * str end # Write to `src/$destpath/$name.md` Literate.markdown(source, destpath; preprocess, credit=false) end # Create Jupyter notebooks and Julia script for each Literate example. These # will be stored in the `assets/` directory of the hosted docs. for source in example_sources # Build notebooks Literate.notebook(source, notebooks_path; execute=false, credit=false) # Build julia scripts Literate.script(source, scripts_path; credit=false) end # Return paths `$destpath/$name.md` for each new Markdown file (relative to # `src/`) return map(example_sources) do source name = splitext(basename(source))[1] joinpath(destdir, "$name.md") end end # Remove existing Documenter `build` directory build_path = joinpath(@__DIR__, "build") isdir(build_path) && rm(build_path; recursive=true) # Create `build/assets` directories notebooks_path = joinpath(build_path, "assets", "notebooks") scripts_path = joinpath(build_path, "assets", "scripts") mkpath.([notebooks_path, scripts_path]) example_sources = filter(endswith(".jl"), readdir(pkgdir(JDQMCFramework, "examples"), join=true)) example_mds = build_examples(example_sources, "examples") makedocs(; clean = false, # Don't wipe files in `build/assets/` modules=[JDQMCFramework], authors="Benjamin Cohen-Stead <[email protected]>", repo="https://github.com/SmoQySuite/JDQMCFramework.jl/blob/{commit}{path}#{line}", sitename="JDQMCFramework.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://SmoQySuite.github.io/JDQMCFramework.jl", edit_link="master", assets=String[], ), pages=[ "Home" => "index.md", "API" => "api.md", "Examples" => example_mds, ] ) deploydocs(; repo="github.com/SmoQySuite/JDQMCFramework.jl.git", devbranch="master", )
JDQMCFramework
https://github.com/SmoQySuite/JDQMCFramework.jl.git
[ "MIT" ]
1.0.10
d37e67cd855d38efbc41b807f45d758eaaa82923
code
48616
# # Tutorial 1: Square Lattice Hubbard Model DQMC Simulation # # This tutorial implements a determinant quantum Monte Carlo (DQMC) simulation from "scratch" # using the [`JDQMCFramework.jl`](https://github.com/SmoQySuite/JDQMCFramework.jl.git) package, along with several others. # The purpose of this tutorial is to empower researchers to write their own lightweight DQMC codes # in order to address specific research needs that fall outside the scope of existing high-level # DQMC packages like [`SmoQyDQMC.jl`](https://github.com/SmoQySuite/SmoQyDQMC.jl.git), and to enable # rapid prototyping of algorithmic improvements to existing DQMC methods. # # This tutorial is relatively long as a lot goes into writing a full DQMC code. # However, in spite of the length, each step is relatively straightforward. # This is made possible by leveraging the functionality exported by # [`JDQMCFramework.jl`](https://github.com/SmoQySuite/JDQMCFramework.jl.git) and other packages. # For instance, the [`JDQMCFramework.jl`](https://github.com/SmoQySuite/JDQMCFramework.jl.git) package takes care of all the # numerical stabilization nonsense that is one of the most challenging parts of writing a DQMC code. # Also, implementing various correlation measurements in a DQMC simulation is typically very time consuming and challening, # as it requires working through arduous Wick's contractions, and then implementing each term. # Once again, this hurdle is largely avoided by leveraging the functionality exported by the # [`JDQMCMeasurements.jl`](https://github.com/SmoQySuite/JDQMCMeasurements.jl.git) package, # which implements a variety of standard correlation function measurements for arbitary lattice geometries. # # The repulsive Hubbard model Hamiltonian on a square lattice considered in this tutorial is given by # ```math # \hat{H} = -t \sum_{\sigma,\langle i,j\rangle} (\hat{c}^{\dagger}_{\sigma,i} \hat{c}^{\phantom \dagger}_{\sigma,j} + {\rm h.c.}) # + U \sum_i (\hat{n}_{\uparrow,i}-\tfrac{1}{2})(\hat{n}_{\downarrow,i}-\tfrac{1}{2}) - \mu \sum_{\sigma,i} \hat{n}_{\sigma,i}, # ``` # where ``\hat{c}^\dagger_{\sigma,i} (\hat{c}^{\phantom \dagger}_{\sigma,i})`` creates (annihilates) a spin ``\sigma`` # electron on site ``i`` in the lattice, and ``\hat{n}_{\sigma,i} = \hat{c}^\dagger_{\sigma,i} \hat{c}^{\phantom \dagger}_{\sigma,i}`` # is the spin-``\sigma`` electron number operator for site ``i``. In the above Hamiltonian, ``t`` is the nearest neighbor hopping integral, # ``\mu`` is the chemical potential, and ``U > 0`` controls the strength of the on-site Hubbard repulsion. # Lastly, if ``\mu = 0.0,`` then the Hamiltonian is particle-hole symmetric, ensuring the system is half-filled ``(\langle n_\sigma \rangle = \tfrac{1}{2})`` # and that there is no sign problem. In the case of ``\mu \ne 0`` there will be a sign problem. # # The script version of this tutorial, which can be downloaded using the link found at the top of this page, # can be run with the command # ``` # julia square_hubbard.jl # ``` # in a terminal. This tutorial can also be downloaded as a notebook at the top of this page. # # We begin by importing the relevant packages we will need to use in this example. # Note that to run this tutorial you will need to install all the required Julia packages. # However, this is straightforward as all the packages used in this tutorial are registered # with the Julia [General](https://github.com/JuliaRegistries/General.git) # package registry. This means they can all be easily installed with the Julia package manager # using the `add` command in the same way that the [`JDQMCFramework.jl`](https://github.com/SmoQySuite/JDQMCFramework.jl.git) # package is installed. ## Import relevant standard template libraries. using Random using LinearAlgebra ## Provides framework for implementing DQMC code. import JDQMCFramework as jdqmcf ## Exports methods for measuring various correlation functions in a DQMC simulation. import JDQMCMeasurements as jdqmcm ## Exports types and methods for representing lattice geometries. import LatticeUtilities as lu ## Exports the checkerboard approximation for representing an exponentiated hopping matrix. import Checkerboard as cb ## Package for performing Fast Fourier Transforms (FFTs). using FFTW # The next incantations are included for annoying technical reasons. # Without going into too much detail, the default multithreading behavior used by BLAS/LAPACK in Julia is somewhat sub-optimal. # As a result, it is typically a good idea to include these commands in Julia DQMC codes, as they ensure # that BLAS/LAPACK (and FFTW) run in a single-threaded fashion. For more information on this issue, # I refer readers to [this discussion](https://carstenbauer.github.io/ThreadPinning.jl/stable/explanations/blas/), # which is found in the documentation for the [`ThreadPinning.jl`](https://github.com/carstenbauer/ThreadPinning.jl.git) package. ## Set number of threads used by BLAS/LAPACK to one. BLAS.set_num_threads(1) ## Set number of threads used by FFTW to one. FFTW.set_num_threads(1) # Now we define the relevant Hamiltonian parameter values that we want to simulate. # In this example we will stick to a relatively small system size ``(4 \times 4)`` and # inverse temperature ``(\beta = 4)`` to ensure that this tutorial # can be run quickly on a personal computer. # Also, in this tutorial I will include many print statements so that when # the tutorial is run users can keep track of what is going on. That said, for a DQMC code # that will be used in actual research you will want to replace the print statements with code # that writes relevant information and measurement results to file. ## Nearest-neighbor hopping amplitude. t = 1.0 println("Nearest-neighbor hopping amplitude, t = ", t) ## Hubbard interaction. U = 6.0 println("Hubbard interaction, U = ", U) ## Chemical potential. ΞΌ = 2.0 println("Chemical potential, mu = ", ΞΌ) ## Inverse temperature. Ξ² = 4.0 println("Inverse temperature, beta = ", Ξ²) ## Lattice size. L = 4 println("Linear lattice size, L = ", L) #jl println() # Next we define the relevant DQMC simulation parameters. ## Discretization in imaginary time. Δτ = 0.05 println("Disretization in imaginary time, dtau = ", Δτ) ## Length of imaginary time axis. LΟ„ = round(Int, Ξ²/Δτ) println("Length of imaginary time axis, Ltau = ", LΟ„) ## Whether or not to use a symmetric or asymmetric definition for the propagator matrices. symmetric = false println("Whether symmetric or asymmetric propagator matrices are used, symmetric = ", symmetric) ## Whether or not to use the checkerboard approximation to represent the ## exponentiated electron kinetic energy matrix exp(-Δτ⋅K). checkerboard = false println("Whether the checkerboard approximation is used, checkerboard = ", checkerboard) ## Period with which numerical stabilization is performed i.e. ## how many imaginary time slices separate more expensive recomputations ## of the Green's function matrix using numerically stable routines. n_stab = 10 println("Numerical stabilization period, n_stab = ", n_stab) ## The number of burnin sweeps through the lattice performing local updates that ## are performed to thermalize the system. N_burnin = 2_500 println("Number of burnin sweeps, N_burnin = ", N_burnin) ## The number of measurements made once the system is thermalized. N_measurements = 10_000 println("Number of measurements, N_measurements = ", N_measurements) ## Number of local update sweeps separating sequential measurements. N_sweeps = 1 println("Number of local update sweeps seperating measurements, n_sweeps = ", N_sweeps) ## Number of bins used to performing a binning analysis when calculating final error bars ## for measured observables. N_bins = 50 println("Number of measurement bins, N_bins = ", N_bins) ## Number of measurements averaged over per measurement bin. N_binsize = N_measurements Γ· N_bins println("Number of measurements per bin, N_binsize = ", N_binsize) #jl println() # Now we initialize the random number generator (RNG) that will be used in the rest of the simulation. ## Initialize random number generator. seed = abs(rand(Int)) rng = Xoshiro(seed) println("Random seed used to initialize RNG, seed = ", seed) #jl println() # Next, we define our square lattice geometry using the [`LatticeUtilities.jl`](https://github.com/SmoQySuite/LatticeUtilities.jl.git) package. ## Define the square lattice unit cell. unit_cell = lu.UnitCell( lattice_vecs = [[1.0, 0.0], [0.0, 1.0]], basis_vecs = [[0.0, 0.0]] ) ## Define the size of the periodic square lattice. lattice = lu.Lattice( L = [L, L], periodic = [true, true] ) ## Define nearest-neighbor bond in +x direction bond_px = lu.Bond( orbitals = (1,1), displacement = [1,0] ) ## Define nearest-neighbor bond in +y direction bond_py = lu.Bond( orbitals = (1,1), displacement = [0,1] ) ## Build the neighbor table corresponding to all nearest-neighbor bonds. neighbor_table = lu.build_neighbor_table([bond_px, bond_py], unit_cell, lattice) println("The neighbor table, neighbor_table =") show(stdout, "text/plain", neighbor_table) println("\n") ## The total number of sites/orbitals in the lattice. N = lu.nsites(unit_cell, lattice) # For square lattice this is simply N = L^2 #md println("Total number of sites in lattice, N = ", N) #nb println("Total number of sites in lattice, N = ", N) ## Total number of bonds in lattice. N_bonds = size(neighbor_table, 2) #md println("Total number of bonds in lattice, N_bonds = ", N_bonds) #nb println("Total number of bonds in lattice, N_bonds = ", N_bonds) # Now we define a few other bonds that are needed to measure # the local s-wave, extended s-wave and d-wave pair susceptibilities. ## Define a "trivial" bond that maps a site back onto itself. bond_trivial = lu.Bond( orbitals = (1,1), displacement = [0,0] ) ## Define bond in -x direction. bond_nx = lu.Bond( orbitals = (1,1), displacement = [-1,0] ) ## Define bond in -y direction. bond_ny = lu.Bond( orbitals = (1,1), displacement = [0,-1] ) # Now let us calculated the exponentiated electron kinetic energy matrix ``e^{-\Delta\tau^\prime K}``, # where # ```math # \hat{K} = -t \sum_{\sigma,\langle i,j\rangle} (\hat{c}^{\dagger}_{\sigma,i} \hat{c}^{\phantom \dagger}_{\sigma,j} + {\rm h.c.}) # = \sum_\sigma \hat{\mathbf{c}}^\dagger_\sigma K \hat{\mathbf{c}}^{\phantom\dagger}_\sigma # ``` # and ``\hat{\mathbf{c}}^{\dagger}_{\sigma,i} = \left[ \hat{c}^{\dagger}_{\sigma,1} \ , \ \dots \ , \ \hat{c}^{\dagger}_{\sigma,N} \right]`` # is a row vector of electron creation operators. # Note that if `symmetric = true`, i.e. the symmetric definition for the propagator matrices # ```math # B_{\sigma,l} = e^{-\Delta\tau^\prime K} \cdot e^{-\Delta\tau V_{\sigma,l}} \cdot e^{-\Delta\tau^\prime K} # ``` # is being used, then ``\Delta\tau^\prime = \tfrac{1}{2} \Delta\tau``. # If the asymmetric definition # ```math # B_{\sigma,l} = e^{-\Delta\tau V_{\sigma,l}} \cdot e^{-\Delta\tau^\prime K} # ``` # is used (`symmetric = false`), then ``\Delta\tau^\prime = \Delta\tau.`` # # Note the branching logic below associated with whether or not the # matrix ``e^{-\Delta\tau^\prime K}`` is calculated exactly, or represented by the sparse checkerboard approximation # using the package [`Checkerboard.jl`](https://github.com/SmoQySuite/Checkerboard.jl.git). ## Define Δτ′=Δτ/2 if symmetric = true, otherwise Δτ′=Δτ Δτ′ = symmetric ? Δτ/2 : Δτ ## If the matrix exp(Δτ′⋅K) is represented by the checkerboard approximation. if checkerboard ## Construct the checkerboard approximation to the matrix exp(-Δτ′⋅K). expnΔτ′K = cb.CheckerboardMatrix(neighbor_table, fill(t, N_bonds), Δτ′) ## If the matrix exp(Δτ′⋅K) is NOT represented by the checkerboard approximation. else ## Construct the electron kinetic energy matrix. K = zeros(typeof(t), N, N) for bond in 1:N_bonds i, j = neighbor_table[1, bond], neighbor_table[2, bond] K[i,j] = -t K[j,i] = -t end ## Calculate the exponentiated kinetic energy matrix, exp(-Δτ⋅K). ## Note that behind the scenes Julia is diagonalizing the matrix K in order to exponentiate it. expnΔτ′K = exp(-Δτ′*K) ## Calculate the inverse of the exponentiated kinetic energy matrix, exp(+Δτ⋅K). exppΔτ′K = exp(+Δτ′*K) #md end; #nb end; #jl end # In this example we are going to introduce an Ising Hubbard-Stratonovich (HS) field to decouple # the Hubbard interaction. The Ising HS transformation # ```math # e^{-\Delta\tau U (\hat{n}_{\uparrow,i,l}-\tfrac{1}{2})(\hat{n}_{\downarrow,i,l}-\tfrac{1}{2})} = # \frac{1}{2} e^{-\tfrac{1}{4} \Delta\tau U} \sum_{s_{i,l} = \pm 1} e^{\alpha s_{i,l}(\hat{n}_{\uparrow,i,l}-\hat{n}_{\downarrow,i,l})} # ``` # is introduced for all imaginary time slices ``l \in [1, L_\tau]`` and sites ``i \in [1, N]`` in the lattice, where # ```math # \alpha = \cosh^{-1}\left( e^{\tfrac{1}{2}\Delta\tau U} \right) # ``` # is a constant. We start the simulation from a random ``s_{i,l}`` Ising HS field configuration. ## Define constant associated Ising Hubbard-Stratonovich (HS) transformation. Ξ± = acosh(exp(Δτ*U/2)) ## Initialize a random Ising HS configuration. s = rand(rng, -1:2:1, N, LΟ„) #md println("Random initial Ising HS configuration, s =") #md show(stdout, "text/plain", s) #nb println("Random initial Ising HS configuration, s =") #nb show(stdout, "text/plain", s) # Next we initialize a propagator matrix ``B_{\sigma,l}`` for each imaginary time slice ``l \in [1,L_\tau]``. # We first initialize a pair of vectors `Bup` and `Bdn` that will contain the ``L_\tau`` propagators associated with each time slice. # The branching logic below enforces the correct propagator matrix definition is used based on the boolean flags # `symmetric` and `checkerboard` defined above. ## Matrix element type for exponentiated electron kinetic energy matrix exp{-Δτ′⋅K} T_expnΔτK = eltype(t) ## Matrix element type for diagonal exponentiated electron potential energy matrix exp{-Δτ⋅V[Οƒ,l]} T_expnΔτV = typeof(Ξ±) ## Initialize empty vector to contain propagator matrices for each imaginary time slice. if checkerboard && symmetric ## Propagator defined as B[Οƒ,l] = exp{-Δτ⋅K/2}β‹…exp{-Δτ⋅V[Οƒ,l]}β‹…exp{-Δτ⋅K/2}, ## where the dense matrix exp{-Δτ⋅K/2} is approximated by the sparse checkerboard matrix. Bup = jdqmcf.SymChkbrdPropagator{T_expnΔτK, T_expnΔτV}[] Bdn = jdqmcf.SymChkbrdPropagator{T_expnΔτK, T_expnΔτV}[] elseif checkerboard && !symmetric ## Propagator defined as B[Οƒ,l] = exp{-Δτ⋅V[Οƒ,l]}β‹…exp{-Δτ⋅K}, ## where the dense matrix exp{-Δτ⋅K} is approximated by the sparse checkerboard matrix. Bup = jdqmcf.AbstractChkbrdPropagator{T_expnΔτK, T_expnΔτV}[] Bdn = jdqmcf.AbstractChkbrdPropagator{T_expnΔτK, T_expnΔτV}[] elseif !checkerboard && symmetric ## Propagator defined as B[Οƒ,l] = exp{-Δτ⋅K/2}β‹…exp{-Δτ⋅V[Οƒ,l]}β‹…exp{-Δτ⋅K/2}, ## where the dense matrix exp{-Δτ⋅K/2} is exactly calculated. Bup = jdqmcf.SymExactPropagator{T_expnΔτK, T_expnΔτV}[] Bdn = jdqmcf.SymExactPropagator{T_expnΔτK, T_expnΔτV}[] elseif !checkerboard && !symmetric ## Propagator defined as B[Οƒ,l] = exp{-Δτ⋅V[Οƒ,l]}β‹…exp{-Δτ⋅K}, ## where the dense matrix exp{-Δτ⋅K} is exactly calculated. Bup = jdqmcf.AsymExactPropagator{T_expnΔτK, T_expnΔτV}[] Bdn = jdqmcf.AsymExactPropagator{T_expnΔτK, T_expnΔτV}[] #md end; #nb end; #jl end # Having an initialized the vector `Bup` and `Bdn` that will contain the propagator matrices, we now construct the # propagator matrices for each time-slice based on the initial HS field configuration `s`. ## Iterate over time-slices. for l in 1:LΟ„ ## Get the HS fields associated with the current time-slice l. s_l = @view s[:,l] ## Calculate the spin-up diagonal exponentiated potential energy ## matrix exp{-Δτ⋅V[↑,l]} = exp{-Δτ⋅(-Ξ±/Δτ⋅s[i,l]-ΞΌ)} = exp{+Ξ±β‹…s[i,l] + Δτ⋅μ}. expnΔτVup = zeros(T_expnΔτV, N) @. expnΔτVup = exp(+Ξ± * s_l + Δτ*ΞΌ) ## Calculate the spin-down diagonal exponentiated potential energy ## matrix exp{-Δτ⋅V[↓,l]} = exp{-Δτ⋅(+Ξ±/Δτ⋅s[i,l]-ΞΌ)} = exp{-Ξ±β‹…s[i,l] + Δτ⋅μ}. expnΔτVdn = zeros(T_expnΔτV, N) @. expnΔτVdn = exp(-Ξ± * s_l + Δτ*ΞΌ) ## Initialize spin-up and spin-down propagator matrix for the current time-slice l. if checkerboard && symmetric push!(Bup, jdqmcf.SymChkbrdPropagator(expnΔτVup, expnΔτ′K)) push!(Bdn, jdqmcf.SymChkbrdPropagator(expnΔτVdn, expnΔτ′K)) elseif checkerboard && !symmetric push!(Bup, jdqmcf.AsymChkbrdPropagator(expnΔτVup, expnΔτ′K)) push!(Bdn, jdqmcf.AsymChkbrdPropagator(expnΔτVdn, expnΔτ′K)) elseif !checkerboard && symmetric push!(Bup, jdqmcf.SymExactPropagator(expnΔτVup, expnΔτ′K, exppΔτ′K)) push!(Bdn, jdqmcf.SymExactPropagator(expnΔτVdn, expnΔτ′K, exppΔτ′K)) elseif !checkerboard && !symmetric push!(Bup, jdqmcf.AsymExactPropagator(expnΔτVup, expnΔτ′K, exppΔτ′K)) push!(Bdn, jdqmcf.AsymExactPropagator(expnΔτVdn, expnΔτ′K, exppΔτ′K)) end end # Now we instantiate two instances for the [`FermionGreensCalculator`](@ref) type, one for each spin # species, spin up and spin down. This object enables the efficient and numerically stable calculation # of the Green's functions behind-the-scenes, so that we do not need to concern ourselves with # implementing numerical stablization routines ourselves. ## Initialize a FermionGreensCalculator for both spin up and down electrons. fermion_greens_calc_up = jdqmcf.FermionGreensCalculator(Bup, Ξ², Δτ, n_stab) #md fermion_greens_calc_dn = jdqmcf.FermionGreensCalculator(Bdn, Ξ², Δτ, n_stab); #nb fermion_greens_calc_dn = jdqmcf.FermionGreensCalculator(Bdn, Ξ², Δτ, n_stab); #jl fermion_greens_calc_dn = jdqmcf.FermionGreensCalculator(Bdn, Ξ², Δτ, n_stab) # Next we calculate the equal-time Green's function matrices # ```math # G_\sigma(0,0) = [1 + B_\sigma(\beta,0)]^{-1} = [1 + B_{\sigma,L_\tau} \dots B_{\sigma,1}]^{-1} # ``` # for both electron spin species, ``\sigma = (\uparrow, \downarrow).`` ## Calculate spin-up equal-time Green's function matrix. Gup = zeros(typeof(t), N, N) logdetGup, sgndetGup = jdqmcf.calculate_equaltime_greens!(Gup, fermion_greens_calc_up) ## Calculate spin-down equal-time Green's function matrix. Gdn = zeros(typeof(t), N, N) #md logdetGdn, sgndetGdn = jdqmcf.calculate_equaltime_greens!(Gdn, fermion_greens_calc_dn); #nb logdetGdn, sgndetGdn = jdqmcf.calculate_equaltime_greens!(Gdn, fermion_greens_calc_dn); #jl logdetGdn, sgndetGdn = jdqmcf.calculate_equaltime_greens!(Gdn, fermion_greens_calc_dn) # In order to perform the DQMC simulation all we need are the equal-time Green's function matrices # ``G_\sigma(0,0)`` calculated above. However, in order to make time-displaced correlation function # measurements we also need to initialize six more matrices, which correspond to ``G_\sigma(\tau,\tau),`` # ``G_\sigma(\tau,0)`` and ``G_\sigma(0,\tau).`` ## Allcoate time-displaced Green's functions. Gup_Ο„0 = zero(Gup) # Gup(Ο„,0) Gup_0Ο„ = zero(Gup) # Gup(0,Ο„) Gup_ττ = zero(Gup) # Gup(Ο„,Ο„) Gdn_Ο„0 = zero(Gdn) # Gdn(Ο„,0) Gdn_0Ο„ = zero(Gdn) # Gdn(0,Ο„) #md Gdn_ττ = zero(Gdn); # Gdn(Ο„,Ο„) #nb Gdn_ττ = zero(Gdn); # Gdn(Ο„,Ο„) #jl Gdn_ττ = zero(Gdn) # Gdn(Ο„,Ο„) # Now we will allocate arrays to contain the various measurements we will make during the simulation, # including various correlation functions. Note that the definition for each measurement will be # supplied later in the tutorial when we begin processing the data to calculate the final statistics # for each measured observable. ## Vector to contain binned average sign measurement. avg_sign = zeros(eltype(Gup), N_bins) ## Vector to contain binned density measurement. density = zeros(eltype(Gup), N_bins) ## Vector to contain binned double occupancy measurement. double_occ = zeros(eltype(Gup), N_bins) ## Array to contain binned position-space time-displaced Green's function measurements. C_greens = zeros(Complex{Float64}, N_bins, L, L, LΟ„+1) ## Array to contain binned position-space time-displaced Spin-Z correlation function measurements. C_spinz = zeros(Complex{Float64}, N_bins, L, L, LΟ„+1) ## Array to contain binned position-space time-displaced density correlation function measurements. C_density = zeros(Complex{Float64}, N_bins, L, L, LΟ„+1) ## Array to contain binned position-space local s-wave pair correlation function. C_loc_swave = zeros(Complex{Float64}, N_bins, L, L, LΟ„+1) ## Array to contain binned position-space extended s-wave pair correlation function. C_ext_swave = zeros(Complex{Float64}, N_bins, L, L, LΟ„+1) ## Array to contain binned position-space d-wave pair correlation function. C_dwave = zeros(Complex{Float64}, N_bins, L, L, LΟ„+1) ## Array to contain binned momentum-space d-wave pair susceptibility. #md P_d_q = zeros(Complex{Float64}, N_bins, L, L); #nb P_d_q = zeros(Complex{Float64}, N_bins, L, L); #jl P_d_q = zeros(Complex{Float64}, N_bins, L, L) # Below we implement a function that sweeps through all time-slices and sites in the lattice, # attempting an update to each Ising HS field ``s_{i,l}``. ## Function to perform local updates to all Ising HS fields. function local_update!( Gup::Matrix{T}, logdetGup, sgndetGup, Bup, fermion_greens_calc_up, Gdn::Matrix{T}, logdetGdn, sgndetGdn, Bdn, fermion_greens_calc_dn, s, ΞΌ, Ξ±, Δτ, Ξ΄G, rng ) where {T<:Number} ## Length of imaginary time axis. LΟ„ = length(Bup) ## Number of sites in lattice. N = size(Gup,1) ## Allocate temporary arrays that will be used to avoid dynamic memory allocation. A = zeros(T, N, N) u = zeros(T, N) v = zeros(T, N) ## Allocate vector of integers to contain random permutation specifying the order in which ## sites are iterated over at each imaginary time slice when performing local updates. perm = collect(1:size(Gup,1)) ## Variable to keep track of the acceptance rate. acceptance_rate = 0.0 ## Iterate over imaginary time slices. for l in fermion_greens_calc_up ## Propagate equal-time Green's function matrix to current imaginary time ## G(τ±Δτ,τ±Δτ) ==> G(Ο„,Ο„) depending on whether iterating over imaginary ## time in the forward or reverse direction jdqmcf.propagate_equaltime_greens!(Gup, fermion_greens_calc_up, Bup) jdqmcf.propagate_equaltime_greens!(Gdn, fermion_greens_calc_dn, Bdn) ## If using symmetric propagator definition (symmetric = true), then apply ## the transformation G ==> GΜƒ = exp{+Δτ⋅K/2}β‹…Gβ‹…exp{-Δτ⋅K/2}. ## If asymmetric propagator definition is used (symmetric = false), ## then this does nothing. jdqmcf.partially_wrap_greens_forward!(Gup, Bup[l], A) jdqmcf.partially_wrap_greens_forward!(Gdn, Bdn[l], A) ## Get the HS fields associated with the current imaginary time-slice. s_l = @view s[:,l] ## Perform local updates HS fields associated with the current imaginary time slice. (logdetGup, sgndetGup, logdetGdn, sgndetGdn, acceptance_rate_l) = _local_update!( Gup, logdetGup, sgndetGup, Bup[l], Gdn, logdetGdn, sgndetGdn, Bdn[l], s_l, ΞΌ, Ξ±, Δτ, rng, perm, u, v ) ## Record the acceptance rate acceptance_rate += acceptance_rate_l / LΟ„ ## If using symmetric propagator definition (symmetric = true), then apply ## the transformation GΜƒ ==> G = exp{-Δτ⋅K/2}β‹…GΜƒβ‹…exp{+Δτ⋅K/2}. ## If asymmetric propagator definition is used (symmetric = false), ## then this does nothing. jdqmcf.partially_wrap_greens_reverse!(Gup, Bup[l], A) jdqmcf.partially_wrap_greens_reverse!(Gdn, Bdn[l], A) ## Periodically re-calculate the Green's function matrix for numerical stability. logdetGup, sgndetGup, Ξ΄Gup, δθup = jdqmcf.stabilize_equaltime_greens!( Gup, logdetGup, sgndetGup, fermion_greens_calc_up, Bup, update_BΜ„ = true ) logdetGdn, sgndetGdn, Ξ΄Gdn, δθdn = jdqmcf.stabilize_equaltime_greens!( Gdn, logdetGdn, sgndetGdn, fermion_greens_calc_dn, Bdn, update_BΜ„ = true ) ## Record largest numerical error corrected by numerical stabilization. Ξ΄G = max(Ξ΄G, Ξ΄Gup, Ξ΄Gdn) ## Keep up and down spin Green's functions synchronized as iterating over imaginary time. iterate(fermion_greens_calc_dn, fermion_greens_calc_up.forward) end return logdetGup, sgndetGup, logdetGdn, sgndetGdn, Ξ΄G, acceptance_rate end ## Iterate over all sites for single imaginary time-slice, attempting a local ## update to each corresponding Ising HS field. function _local_update!( Gup, logdetGup, sgndetGup, Bup, Gdn, logdetGdn, sgndetGdn, Bdn, s, ΞΌ, Ξ±, Δτ, rng, perm, u, v ) ## Randomize the order in which the sites are iterated over. shuffle!(rng, perm) ## Counter for number of accepted updates. accepted = 0 ## Iterate over sites in lattice. for i in perm ## Calculate the new value of the diagonal potential energy matrix element ## assuming the sign of the Ising HS field is changed. Vupβ€² = -Ξ±/Δτ * (-s[i]) - ΞΌ Vdnβ€² = +Ξ±/Δτ * (-s[i]) - ΞΌ ## Calculate the determinant ratio associated with the proposed update. Rup, Ξ”up = jdqmcf.local_update_det_ratio(Gup, Bup, Vupβ€², i, Δτ) Rdn, Ξ”dn = jdqmcf.local_update_det_ratio(Gdn, Bdn, Vdnβ€², i, Δτ) ## Calculate the acceptance probability based on the Metropolis accept/reject criteria. P = min(1.0, abs(Rup * Rdn)) ## Randomly Accept or reject the proposed update with the specified probability. if rand(rng) < P ## Increment the accepted update counter. accepted += 1 ## Flip the appropriate Ising HS field. s[i] = -s[i] ## Update the Green's function matrices. logdetGup, sgndetGup = jdqmcf.local_update_greens!( Gup, logdetGup, sgndetGup, Bup, Rup, Ξ”up, i, u, v ) logdetGdn, sgndetGdn = jdqmcf.local_update_greens!( Gdn, logdetGdn, sgndetGdn, Bdn, Rdn, Ξ”dn, i, u, v ) end end ## Calculate the acceptance rate. acceptance_rate = accepted / N return logdetGup, sgndetGup, logdetGdn, sgndetGdn, acceptance_rate #md end; #nb end; #jl end # Next we implement a function to make measurements during the simulation, including time-displaced measurements. # Note that if we want to calculate the expectation value for some observable ``\langle \mathcal{O} \rangle``, # then during the simulation we actually measure ``\langle \mathcal{S O} \rangle_{\mathcal{W}}``, where # ``\langle \bullet \rangle_{\mathcal{W}}`` denotes an average with respect to states sampled according # to the DQMC weights # ```math # \mathcal{W} = | \det G_\uparrow^{-1} \det G_\downarrow^{-1} |, # ``` # such that # ```math # \mathcal{S} = \text{sign}(\det G_\uparrow^{-1} \det G_\downarrow^{-1}) # ``` # is the sign associated with each state. The reweighting method is then used at the end of a simulation # to recover the correct expectation value according to # ```math # \langle \mathcal{O} \rangle = \frac{ \langle \mathcal{SO} \rangle_{\mathcal{W}} }{ \langle \mathcal{S} \rangle_{\mathcal{W}} }, # ``` # where ``\langle \mathcal{S} \rangle_{\mathcal{W}}`` is the average sign measured over the course of the simulation. ## Make measurements. function make_measurements!( Gup, logdetGup, sgndetGup, Gup_ττ, Gup_Ο„0, Gup_0Ο„, Bup, fermion_greens_calc_up, Gdn, logdetGdn, sgndetGdn, Gdn_ττ, Gdn_Ο„0, Gdn_0Ο„, Bdn, fermion_greens_calc_dn, unit_cell, lattice, bond_trivial, bond_px, bond_nx, bond_py, bond_ny, bin, avg_sign, density, double_occ, C_greens, C_spinz, C_density, C_loc_swave, C_ext_swave, C_dwave ) ## Initialize time-displaced Green's function matrices for both spin species: ## G(Ο„=0,Ο„=0) = G(0,0) ## G(Ο„=0,0) = G(0,0) ## G(0,Ο„=0) = -(I-G(0,0)) jdqmcf.initialize_unequaltime_greens!(Gup_Ο„0, Gup_0Ο„, Gup_ττ, Gup) jdqmcf.initialize_unequaltime_greens!(Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, Gdn) ## Calculate the current sign. sgn = sign(sgndetGup * sgndetGdn) ## Measure the average sign. avg_sign[bin] += sgn ## Measure the density. nup = jdqmcm.measure_n(Gup) ndn = jdqmcm.measure_n(Gdn) density[bin] += sgn * (nup + ndn) ## Measure the double occupancy. double_occ[bin] += sgn * jdqmcm.measure_double_occ(Gup, Gdn) ## Measure equal-time correlation functions. make_correlation_measurements!( Gup, Gup_ττ, Gup_Ο„0, Gup_0Ο„, Gdn, Gdn_ττ, Gdn_Ο„0, Gdn_0Ο„, unit_cell, lattice, bond_trivial, bond_px, bond_nx, bond_py, bond_ny, bin, 0, sgn, C_greens, C_spinz, C_density, C_loc_swave, C_ext_swave, C_dwave ) ## Iterate over imaginary time slices. for l in fermion_greens_calc_up ## Propagate equal-time Green's function matrix to current imaginary time ## G(τ±Δτ,τ±Δτ) ==> G(Ο„,Ο„) depending on whether iterating over imaginary ## time in the forward or reverse direction jdqmcf.propagate_unequaltime_greens!(Gup_Ο„0, Gup_0Ο„, Gup_ττ, fermion_greens_calc_up, Bup) jdqmcf.propagate_unequaltime_greens!(Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, fermion_greens_calc_dn, Bdn) ## Measure time-displaced correlation function measurements for Ο„ = l⋅Δτ. make_correlation_measurements!( Gup, Gup_ττ, Gup_Ο„0, Gup_0Ο„, Gdn, Gdn_ττ, Gdn_Ο„0, Gdn_0Ο„, unit_cell, lattice, bond_trivial, bond_px, bond_nx, bond_py, bond_ny, bin, l, sgn, C_greens, C_spinz, C_density, C_loc_swave, C_ext_swave, C_dwave, ) ## Periodically re-calculate the Green's function matrix for numerical stability. logdetGup, sgndetGup, Ξ΄Gup, δθup = jdqmcf.stabilize_unequaltime_greens!( Gup_Ο„0, Gup_0Ο„, Gup_ττ, logdetGup, sgndetGup, fermion_greens_calc_up, Bup, update_BΜ„=false ) logdetGdn, sgndetGdn, Ξ΄Gdn, δθdn = jdqmcf.stabilize_unequaltime_greens!( Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, logdetGdn, sgndetGdn, fermion_greens_calc_dn, Bdn, update_BΜ„=false ) ## Keep up and down spin Green's functions synchronized as iterating over imaginary time. iterate(fermion_greens_calc_dn, fermion_greens_calc_up.forward) end return nothing end ## Make time-displaced measurements. function make_correlation_measurements!( Gup, Gup_ττ, Gup_Ο„0, Gup_0Ο„, Gdn, Gdn_ττ, Gdn_Ο„0, Gdn_0Ο„, unit_cell, lattice, bond_trivial, bond_px, bond_nx, bond_py, bond_ny, bin, l, sgn, C_greens, C_spinz, C_density, C_loc_swave, C_ext_swave, C_dwave, tmp = zeros(eltype(C_greens), lattice.L...) ) ## Get a view into the arrays accumulating the correlation measurements ## for the current imaginary time-slice and bin. C_greens_bin_l = @view C_greens[bin,:,:,l+1] C_spinz_bin_l = @view C_spinz[bin,:,:,l+1] C_density_bin_l = @view C_density[bin,:,:,l+1] C_loc_swave_bin_l = @view C_loc_swave[bin,:,:,l+1] C_ext_swave_bin_l = @view C_ext_swave[bin,:,:,l+1] C_dwave_bin_l = @view C_dwave[bin,:,:,l+1] ## Measure Green's function for both spin-up and spin-down. jdqmcm.greens!(C_greens_bin_l, 1, 1, unit_cell, lattice, Gup_Ο„0, sgn) jdqmcm.greens!(C_greens_bin_l, 1, 1, unit_cell, lattice, Gdn_Ο„0, sgn) ## Measure spin-z spin-spin correlation. jdqmcm.spin_z_correlation!( C_spinz_bin_l, 1, 1, unit_cell, lattice, Gup_Ο„0, Gup_0Ο„, Gup_ττ, Gup, Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, Gdn, sgn ) ## Measure density-density correlation. jdqmcm.density_correlation!( C_density_bin_l, 1, 1, unit_cell, lattice, Gup_Ο„0, Gup_0Ο„, Gup_ττ, Gup, Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, Gdn, sgn ) ## Measure local s-wave correlation measurement. jdqmcm.pair_correlation!( C_loc_swave_bin_l, bond_trivial, bond_trivial, unit_cell, lattice, Gup_Ο„0, Gdn_Ο„0, sgn ) ## Group the nearest-neighbor bonds together. bonds = (bond_px, bond_nx, bond_py, bond_ny) ## d-wave correlation phases. dwave_phases = (+1, +1, -1, -1) ## Iterate over all pairs of nearest-neigbbor bonds. for i in eachindex(bonds) for j in eachindex(bonds) ## Measure pair correlation associated with bond pair. fill!(tmp, 0) jdqmcm.pair_correlation!( tmp, bonds[i], bonds[j], unit_cell, lattice, Gup_Ο„0, Gdn_Ο„0, sgn ) ## Add contribution to extended s-wave and d-wave pair correlation. @. C_ext_swave_bin_l += tmp / 4 @. C_dwave_bin_l += dwave_phases[i] * dwave_phases[j] * tmp / 4 end end return nothing #md end; #nb end; #jl end # Now we will write a top-level function to run the simulation, including both the thermalization # and measurement portions of the simulation. ## High-level function to run the DQMC simulation. function run_simulation!( s, ΞΌ, Ξ±, Δτ, rng, N_burnin, N_bins, N_binsize, N_sweeps, Gup, logdetGup, sgndetGup, Gup_ττ, Gup_Ο„0, Gup_0Ο„, Bup, fermion_greens_calc_up, Gdn, logdetGdn, sgndetGdn, Gdn_ττ, Gdn_Ο„0, Gdn_0Ο„, Bdn, fermion_greens_calc_dn, unit_cell, lattice, bond_trivial, bond_px, bond_nx, bond_py, bond_ny, avg_sign, density, double_occ, C_greens, C_spinz, C_density, C_loc_swave, C_ext_swave, C_dwave ) ## Initialize variable to keep track of largest corrected numerical error. Ξ΄G = 0.0 ## The acceptance rate on local updates. acceptance_rate = 0.0 #jl println("Beginning Thermalization Updates") ## Perform burnin updates to thermalize system. for n in 1:N_burnin ## Attempt local update to every Ising HS field. (logdetGup, sgndetGup, logdetGdn, sgndetGdn, Ξ΄Gβ€², ac) = local_update!( Gup, logdetGup, sgndetGup, Bup, fermion_greens_calc_up, Gdn, logdetGdn, sgndetGdn, Bdn, fermion_greens_calc_dn, s, ΞΌ, Ξ±, Δτ, Ξ΄G, rng ) ## Record max numerical error. Ξ΄G = max(Ξ΄G, Ξ΄Gβ€²) ## Update acceptance rate. acceptance_rate += ac end #jl println() #jl println("Beginning Measurements.") ## Iterate over measurement bins. for bin in 1:N_bins ## Iterate over updates and measurements in bin. for n in 1:N_binsize ## Iterate over number of local update sweeps per measurement. for sweep in 1:N_sweeps ## Attempt local update to every Ising HS field. (logdetGup, sgndetGup, logdetGdn, sgndetGdn, Ξ΄Gβ€², ac) = local_update!( Gup, logdetGup, sgndetGup, Bup, fermion_greens_calc_up, Gdn, logdetGdn, sgndetGdn, Bdn, fermion_greens_calc_dn, s, ΞΌ, Ξ±, Δτ, Ξ΄G, rng ) ## Record max numerical error. Ξ΄G = max(Ξ΄G, Ξ΄Gβ€²) ## Update acceptance rate. acceptance_rate += ac end ## Make measurements. make_measurements!( Gup, logdetGup, sgndetGup, Gup_ττ, Gup_Ο„0, Gup_0Ο„, Bup, fermion_greens_calc_up, Gdn, logdetGdn, sgndetGdn, Gdn_ττ, Gdn_Ο„0, Gdn_0Ο„, Bdn, fermion_greens_calc_dn, unit_cell, lattice, bond_trivial, bond_px, bond_nx, bond_py, bond_ny, bin, avg_sign, density, double_occ, C_greens, C_spinz, C_density, C_loc_swave, C_ext_swave, C_dwave ) end ## Normalize accumulated measurements by the bin size. avg_sign[bin] /= N_binsize density[bin] /= N_binsize double_occ[bin] /= N_binsize C_greens[bin,:,:,:] /= (2 * N_binsize) C_spinz[bin,:,:,:] /= N_binsize C_density[bin,:,:,:] /= N_binsize C_loc_swave[bin,:,:,:] /= N_binsize C_ext_swave[bin,:,:,:] /= N_binsize C_dwave[bin,:,:,:] /= N_binsize end ## Calculate the final acceptance rate for local updates. acceptance_rate /= (N_burnin + N_bins * N_binsize * N_sweeps) #jl println() #jl println("Simuilation Complete.") #jl println() return acceptance_rate, Ξ΄G #md end; #nb end; #jl end # Now let us run our DQMC simulation. ## Run the DQMC simulation. acceptance_rate, Ξ΄G = run_simulation!( s, ΞΌ, Ξ±, Δτ, rng, N_burnin, N_bins, N_binsize, N_sweeps, Gup, logdetGup, sgndetGup, Gup_ττ, Gup_Ο„0, Gup_0Ο„, Bup, fermion_greens_calc_up, Gdn, logdetGdn, sgndetGdn, Gdn_ττ, Gdn_Ο„0, Gdn_0Ο„, Bdn, fermion_greens_calc_dn, unit_cell, lattice, bond_trivial, bond_px, bond_nx, bond_py, bond_ny, avg_sign, density, double_occ, C_greens, C_spinz, C_density, C_loc_swave, C_ext_swave, C_dwave ) println("Acceptance Rate = ", acceptance_rate) println("Largest Numerical Error = ", Ξ΄G) # Having completed the DQMC simulation, the next step is the analyze the results, # calculating the mean and error for various measuremed observables. # We will first calculate the relevant global measurements, including the # average density ``\langle n \rangle = \langle n_\uparrow + n_\downarrow \rangle`` # and double occupancy ``\langle n_\uparrow n_\downarrow \rangle.`` # Note that the binning method is used to calculate the error bar for the correlated data. # The Jackknife algorithm is also used to propagate error and correct for bias when evaluating # ```math # \langle \mathcal{O} \rangle = \frac{ \langle \mathcal{S O} \rangle_\mathcal{W} }{ \langle \mathcal{S} \rangle_\mathcal{W} } # ``` # to account for the sign problem. ## Calculate the average sign for the simulation. sign_avg, sign_std = jdqmcm.jackknife(identity, avg_sign) println("Avg Sign, S = ", sign_avg, " +/- ", sign_std) ## Calculate the average density. density_avg, density_std = jdqmcm.jackknife(/, density, avg_sign) println("Density, n = ", density_avg, " +/- ", density_std) ## Calculate the average double occupancy. double_occ_avg, double_occ_std = jdqmcm.jackknife(/, double_occ, avg_sign) println("Double occupancy, nup_ndn = ", double_occ_avg, " +/- ", double_occ_std) # Now we move onto processing the measured correlation function data. # We define two functions to assist with this process. # The first function integrates the binned time-displaced correlation function data # over the imaginary time axis in order to generate binned susceptibility data. # Note that the integration over the imaginary time axis is performed using Simpson's # rule, which is accurate to order ``\mathcal{O}(\Delta\tau^4)``. ## Given the binned time-displaced correlation function/structure factor data, ## calculate and return the corresponding binned susceptibility data. function susceptibility(S::AbstractArray{T}, Δτ) where {T<:Number} ## Allocate array to contain susceptibility. Ο‡ = zeros(T, size(S)[1:3]) ## Iterate over bins. for bin in axes(S,1) ## Calculate the susceptibility for the current bin by integrating the correlation ## data over the imaginary time axis using Simpson's rule. S_bin = @view S[bin,:,:,:] Ο‡_bin = @view Ο‡[bin,:,:] jdqmcm.susceptibility!(Ο‡_bin, S_bin, Δτ, 3) end return Ο‡ end # We also define a function to calculate the average and error of a correlation function # measurement based on the input binned correlation function data. ## Calculate average correlation function values based on binned data. function correlation_stats( S::AbstractArray{Complex{T}}, avg_sign::Vector{T} ) where {T<:AbstractFloat} ## Allocate arrays to contain the mean and standard deviation of ## measured correlation function. S_avg = zeros(Complex{T}, size(S)[2:end]) S_std = zeros(T, size(S)[2:end]) ## Number of bins. N_bins = length(avg_sign) ## Preallocate arrays to make the jackknife error analysis faster. jackknife_samples = (zeros(Complex{T}, N_bins), zeros(T, N_bins)) jackknife_g = zeros(Complex{T}, N_bins) ## Iterate over correlation functions. for n in CartesianIndices(S_avg) ## Use the jackknife method to calculage average and error. vals = @view S[:,n] S_avg[n], S_std[n] = jdqmcm.jackknife( /, vals, avg_sign, jackknife_samples = jackknife_samples, jackknife_g = jackknife_g ) end return S_avg, S_std end # First, let us compute the average and error for the time-displaced electron # Green's function # ```math # G_\sigma(\mathbf{r},\tau) = \langle \hat{c}^{\phantom \dagger}_{\sigma,\mathbf{i}+\mathbf{r}}(\tau) \hat{c}^\dagger_{\sigma,\mathbf{i}}(0) \rangle # ``` # in position space, and # ```math # G_\sigma(\mathbf{k},\tau) = \langle \hat{c}^{\phantom \dagger}_{\sigma,\mathbf{k}}(\tau) \hat{c}^\dagger_{\sigma,\mathbf{k}}(0) \rangle # ``` # in momentum space, where ``\tau \in [0, \Delta\tau, \dots, \beta-\Delta\tau, \beta].`` ## Fourier transform Green's function from position to momentum space. S_greens = copy(C_greens) jdqmcm.fourier_transform!(S_greens, 1, 1, (1,4), unit_cell, lattice) ## Calculate average Green's function in position space. C_greens_avg, C_greens_std = correlation_stats(C_greens, avg_sign) ## Calculate average Green's function in momentum space. S_greens_avg, S_greens_std = correlation_stats(S_greens, avg_sign) ## Verify that the position space G(r=0,Ο„=0) measurement agrees with the ## average density measurement. agreement = (2*(1-C_greens_avg[1,1,1]) β‰ˆ density_avg) #md println("(2*[1-G(r=0,tau=0)] == <n>) = ", agreement) #nb println("(2*[1-G(r=0,tau=0)] == <n>) = ", agreement) # Now we will calculate the spin susceptibility # ```math # \chi_z(\mathbf{q}) = \int_0^\beta S_z(\mathbf{q},\tau) \ d\tau # ``` # where the time-displaced spin structure # ```math # S_z(\mathbf{q},\tau) = \sum_\mathbf{r} e^{-{\rm i} \mathbf{q}\cdot\mathbf{r}} \ C_z(\mathbf{r},\tau) # ``` # is given by the fourier transform of the spin-``z`` correlation function # ```math # C_z(\mathbf{r},\tau) = \frac{1}{N} \sum_\mathbf{i} \langle \hat{S}_{z,\mathbf{i}+\mathbf{r}}(\tau) \hat{S}_{z,\mathbf{i}}(0) \rangle # ``` # in position space. Then we report the spin-suscpetibility ``\chi_{\rm afm} = \chi_z(\pi,\pi)`` corresponding to # antiferromagnetism. ## Fourier transform the binned Cz(r,Ο„) position space spin-z correlation function ## data to get the binned Sz(q,Ο„) spin-z structure factor data. S_spinz = copy(C_spinz) jdqmcm.fourier_transform!(S_spinz, 1, 1, (1,4), unit_cell, lattice) ## Integrate the binned Sz(q,Ο„) spin-z structure factor data over the imaginary ## time axis to get the binned Ο‡z(q) spin susceptibility. Ο‡_spinz = susceptibility(S_spinz, Δτ) ## Calculate the average spin correlation functions in position space. C_spinz_avg, C_spinz_std = correlation_stats(C_spinz, avg_sign) ## Calculate the average spin structure factor in momentum space. S_spinz_avg, S_spinz_std = correlation_stats(S_spinz, avg_sign) ## Calculate the average spin susceptibility for all scattering momentum q. Ο‡_spinz_avg, Ο‡_spinz_std = correlation_stats(Ο‡_spinz, avg_sign) ## Report the spin susceptibility Ο‡afm = Ο‡z(Ο€,Ο€) corresponding to antiferromagnetism. Ο‡afm_avg = real(Ο‡_spinz_avg[LΓ·2+1, LΓ·2+1]) Ο‡afm_std = Ο‡_spinz_std[LΓ·2+1, LΓ·2+1] println("Antiferromagentic Spin Susceptibility, chi_afm = ", Ο‡afm_avg, " +/- ", Ο‡afm_std) # Given the measured time-displaced density correlation function # ```math # C_{\rho}(\mathbf{r},\tau) = \sum_{\mathbf{i}} # \langle \hat{n}_{\mathbf{i}+\mathbf{r}}(\tau) \hat{n}_{\mathbf{i}}(0) \rangle, # ``` # where ``\hat{n}_{\mathbf{i}} = (\hat{n}_{\mathbf{i}, \uparrow} + \hat{n}_{\mathbf{i}, \downarrow}),`` # we can compute the time-displaced charge structure factor # ```math # S_{\rho}(\mathbf{q},\tau) = \sum_\mathbf{r} e^{-{\rm i}\mathbf{q}\cdot\mathbf{r}} \ C_{\rho}(\mathbf{r},\tau) # ``` # and corresponding charge susceptibility # ```math # \chi_{\rho}(\mathbf{q}) \int_0^\beta S_{\rho}(\mathbf{q},\tau) \ d\tau. # ``` ## Fourier transform the binned Cρ(r,Ο„) position space density correlation ## data to get the time-dispaced charge structure factor Sρ(q,Ο„) in ## momentum space. S_density = copy(C_density) jdqmcm.fourier_transform!(S_density, 1, 1, (1,4), unit_cell, lattice) ## Integrate the binned Sρ(q,Ο„) density structure factor data over the imaginary ## time axis to get the binned χρ(q) density susceptibility. Ο‡_density = susceptibility(S_density, Δτ) ## Calculate the average charge correlation functions in position space. C_density_avg, C_density_std = correlation_stats(C_density, avg_sign) ## Calculate the average charge structure factor in momentum space. S_density_avg, S_density_std = correlation_stats(S_density, avg_sign) ## Calculate the average charge susceptibility for all scattering momentum q. #md Ο‡_density_avg, Ο‡_density_std = correlation_stats(Ο‡_spinz, avg_sign); #nb Ο‡_density_avg, Ο‡_density_std = correlation_stats(Ο‡_spinz, avg_sign); #jl Ο‡_density_avg, Ο‡_density_std = correlation_stats(Ο‡_spinz, avg_sign) # Now we calculate the local s-wave pair susceptibility # ```math # P_{s} = \frac{1}{N} \int_0^\beta \langle \hat{\Delta}_{s}(\tau) \hat{\Delta}_{s}(0) \rangle \ d\tau, # ``` # where ``\hat{\Delta}_{s} = \sum_\mathbf{i} \hat{c}_{\downarrow,\mathbf{i}} \hat{c}_{\uparrow,\mathbf{i}}.`` ## Fourier transform binned position space local s-wave correlation function data to get ## the binned momentum space local s-wave structure factor data. S_loc_swave = copy(C_loc_swave) jdqmcm.fourier_transform!(S_loc_swave, 1, 1, (1,4), unit_cell, lattice) ## Integrate the binned local s-wave structure factor data to get the ## binned local s-wave pair susceptibility data. P_loc_swave = susceptibility(S_loc_swave, Δτ) ## Calculate the average local s-wave pair susceptibility for all scattering momentum q. P_loc_swave_avg, P_loc_swave_std = correlation_stats(P_loc_swave, avg_sign) ## Report the local s-wave pair suspcetibility. Ps_avg = real(P_loc_swave_avg[1,1]) Ps_std = P_loc_swave_std[1,1] println("Local s-wave pair susceptibility, P_s = ", Ps_avg, " +/- ", Ps_std) # Next, we calculate the local s-wave pair susceptibility # ```math # P_{\textrm{ext-}s} = \frac{1}{N} \int_0^\beta \langle \hat{\Delta}_{\textrm{ext-}s}(\tau) \hat{\Delta}_{\textrm{ext-}s}(0) \rangle \ d\tau, # ``` # where # ```math # \hat{\Delta}_{\textrm{ext-}s} = \frac{1}{2} \sum_\mathbf{i} # (\hat{c}_{\downarrow,\mathbf{i}+\mathbf{x}} # +\hat{c}_{\downarrow,\mathbf{i}-\mathbf{x}} # +\hat{c}_{\downarrow,\mathbf{i}+\mathbf{y}} # +\hat{c}_{\downarrow,\mathbf{i}-\mathbf{y}}) # \hat{c}_{\uparrow,\mathbf{i}}. # ``` ## Fourier transform binned position space extended s-wave correlation function data to get ## the binned momentum space extended s-wave structure factor data. S_ext_swave = copy(C_ext_swave) jdqmcm.fourier_transform!(S_ext_swave, 1, 1, (1,4), unit_cell, lattice) ## Integrate the binned extended s-wave structure factor data to get the ## binned extended s-wave pair susceptibility data. P_ext_swave = susceptibility(S_ext_swave, Δτ) ## Calculate the average extended s-wave pair susceptibility for all scattering momentum q. P_ext_swave_avg, P_ext_swave_std = correlation_stats(P_ext_swave, avg_sign) ## Report the local s-wave pair suspcetibility. Pexts_avg = real(P_ext_swave_avg[1,1]) Pexts_std = P_ext_swave_std[1,1] println("Extended s-wave pair susceptibility, P_ext-s = ", Pexts_avg, " +/- ", Pexts_std) # Lastly, we calculate the d-wave pair susceptibility # ```math # P_{d} = \frac{1}{N} \int_0^\beta \langle \hat{\Delta}_{d}(\tau) \hat{\Delta}_{d}(0) \rangle \ d\tau, # ``` # where # ```math # \hat{\Delta}_{d} = \frac{1}{2} \sum_\mathbf{i} # (\hat{c}_{\downarrow,\mathbf{i}+\mathbf{x}} # +\hat{c}_{\downarrow,\mathbf{i}-\mathbf{x}} # -\hat{c}_{\downarrow,\mathbf{i}+\mathbf{y}} # -\hat{c}_{\downarrow,\mathbf{i}-\mathbf{y}}) # \hat{c}_{\uparrow,\mathbf{i}}. # ``` ## Fourier transform binned position space d-wave correlation function data to get ## the binned momentum space d-wave structure factor data. S_dwave = copy(C_dwave) jdqmcm.fourier_transform!(S_dwave, 1, 1, (1,4), unit_cell, lattice) ## Integrate the binned d-wave structure factor data to get the ## binned d-wave pair susceptibility data. P_dwave = susceptibility(S_dwave, Δτ) ## Calculate the average d-wave pair susceptibility for all scattering momentum q. P_dwave_avg, P_dwave_std = correlation_stats(P_dwave, avg_sign) ## Report the d-wave pair susceptibility. Pd_avg = real(P_dwave_avg[1,1]) Pd_std = P_dwave_std[1,1] println("Extended s-wave pair susceptibility, P_d = ", Pd_avg, " +/- ", Pd_std)
JDQMCFramework
https://github.com/SmoQySuite/JDQMCFramework.jl.git
[ "MIT" ]
1.0.10
d37e67cd855d38efbc41b807f45d758eaaa82923
code
15266
@doc raw""" FermionGreensCalculator{T<:Continuous, E<:AbstractFloat} A type to facilitate calculating the single-particle fermion Green's function matrix. # Fields - `forward::Bool`: If `true` then iterate over imaginary time slices from ``l=1`` to ``l=L_\tau``, if `false` then iterate over imaginary time slices from ``l=L_\tau`` to ``l=1``. - `l::Int`: The current imaginary time slice ``\tau = l \cdot \Delta\tau``. - `n_stab::Int`: Frequency with which numerical stabilization is performed, i.e. every ``n_s`` imaginary time slices the equal-time Green's function is recomputed from scratch. - `N_stab::Int`: Number of numerical stabilization intervals, ``N_s = \left\lceil L_\tau / n_s \right\rceil.`` - `N::Int`: Orbitals in system. - `Ξ²::E`: The inverse temperature ``\beta=1/T,`` where ``T`` is temperature. - `Δτ::E`: Discretization in imaginary time. - `LΟ„::Int`: Length of imaginary time axis, ``L_\tau = \beta / \Delta\tau.`` - `B_bar::Vector{Matrix{T}}`: A multidimensional array where the matrix `B_bar[:,:,n]` represents ``\bar{B}_n.`` - `F::Vector{LDR{T,E}}`: A vector of ``N_s`` LDR factorizations to represent the matrices ``B(0,\tau)`` and ``B(\tau,\beta)``. - `Gβ€²::Matrix{T}`: Matrix used for calculating the error corrected by numerical stabilization of the equal time Green's function. - `ldr_ws::LDRWorkspace{T}`: Workspace for performing LDR factorization while avoiding dynamic memory allocations. """ mutable struct FermionGreensCalculator{T<:Continuous, E<:AbstractFloat} forward::Bool l::Int n_stab::Int N_stab::Int const N::Int const Ξ²::E const Δτ::E const LΟ„::Int const B_bar::Vector{Matrix{T}} const F::Vector{LDR{T,E}} const Gβ€²::Matrix{T} const ldr_ws::LDRWorkspace{T} end @doc raw""" FermionGreensCalculator( B::AbstractVector{P}, Ξ²::E, Δτ::E, n_stab::Int ) where {T<:Number, E<:AbstractFloat, P<:AbstractPropagator{T}} Initialize and return [`FermionGreensCalculator`](@ref) struct based on the vector of propagators `B` passed to the function. """ function FermionGreensCalculator( B::AbstractVector{P}, Ξ²::E, Δτ::E, n_stab::Int ) where {T<:Number, E<:AbstractFloat, P<:AbstractPropagator{T}} # get length of imaginary time axis LΟ„ = eval_length_imaginary_axis(Ξ², Δτ) # get the number of orbitals N = size(B[1],1) # check that there is a propagator for each time slice @assert length(B) == LΟ„ # make sure that the discretization in imaginary time is valid @assert (LΟ„*Δτ) β‰ˆ Ξ² # calculate the number of numerical stabalization intervals N_stab = ceil(Int, LΟ„/n_stab) # allocate array to represent partical products of B matrices, # setting each equal to the identity matrix B_bar = Matrix{T}[] for n in 1:N_stab push!(B_bar, Matrix{T}(I, N, N)) end # calculate scratch matrix Gβ€² = Matrix{T}(I, N, N) # construct vector of LDR factorization to represent B(Ο„,0) and B(Ξ²,Ο„) matrices ldr_ws = ldr_workspace(Gβ€²) F = ldrs(Gβ€², N_stab) # current imaginary time slice l = LΟ„ # whether to iterate over imaginary time Ο„=Δτ⋅l in forward (l=1 ==> l=LΟ„) or reverse order (l=LΟ„ ==> l=1) forward = false # allocate FermionGreensCalculator struct fgc = FermionGreensCalculator(forward, l, n_stab, N_stab, N, Ξ², Δτ, LΟ„, B_bar, F, Gβ€², ldr_ws) # initialize FermionGreensCalculator struct for l in fgc update_factorizations!(fgc, B) end return fgc end @doc raw""" FermionGreensCalculator(fgc::FermionGreensCalculator{T,E}) where {T,E} Return a new [`FermionGreensCalculator`](@ref) that is a copy of `fgc`. """ function FermionGreensCalculator(fgc::FermionGreensCalculator{T,E}) where {T,E} (; forward, l, N, Ξ², Δτ, LΟ„, n_stab, N_stab, B_bar, F, Gβ€², ldr_ws) = fgc B_bar_new = [copy(B_bar[i]) for i in eachindex(B_bar)] F_new = [ldr(F[i]) for i in eachindex(F)] Gβ€²_new = copy(Gβ€²) copyto!(Gβ€²_new,I) ldr_ws_new = ldr_workspace(Gβ€²_new) return FermionGreensCalculator(forward, l, n_stab, N_stab, N, Ξ², Δτ, LΟ„, B_bar_new, F_new, Gβ€²_new, ldr_ws_new) end ######################## ## OVERLOADED METHODS ## ######################## @doc raw""" eltype(fgc::FermionGreensCalculator{T,E}) where {T,E} Return matrix element type `T` associated with an instance of [`FermionGreensCalculator`](@ref). """ function eltype(fgc::FermionGreensCalculator{T,E}) where {T,E} return T end @doc raw""" resize!( fgc::FermionGreensCalculator{T,E}, G::Matrix{T}, logdetG::E, sgndetG::T, B::Vector{P}, n_stab::Int ) where {T<:Number, E<:AbstractFloat, P<:AbstractPropagator{T}} resize!( fgc::FermionGreensCalculator{T,E}, n_stab::Int ) where {T,E} Update `fgc` to reflect a new stabilizaiton frequency `n_stab`. If `G`, `logdetG`, `sgndetG` and `B` are also passed then the equal-time Green's function `G` is re-calculated and the corresponding updated values for `(logdetG, sgndetG)` are returned. """ function resize!( fgc::FermionGreensCalculator{T,E}, G::Matrix{T}, logdetG::E, sgndetG::T, B::Vector{P}, n_stab::Int ) where {T<:Number, E<:AbstractFloat, P<:AbstractPropagator{T}} # check if stablization frequency is being updated if fgc.n_stab != n_stab # resize fgc resize!(fgc, n_stab) # calculate the equal-time Green's function logdetG, sgndetG = calculate_equaltime_greens!(G, fgc, B) end return (logdetG, sgndetG) end function resize!( fgc::FermionGreensCalculator{T,E}, n_stab::Int ) where {T,E} (; N, LΟ„) = fgc B_bar = fgc.B_bar::Vector{Matrix{T}} F = fgc.F::Vector{LDR{T,E}} # check if stablization frequency is being updated if fgc.n_stab != n_stab # calculate the new number of stabilization intervals N_stab = ceil(Int, LΟ„/n_stab) # calculate the change in stablization intervals Ξ”N_stab = N_stab - fgc.N_stab # update stabilization interval and frequency fgc.n_stab = n_stab fgc.N_stab = N_stab # if number of stabilization intervals increased if Ξ”N_stab > 0 # grow B_bar and F vectors for n in 1:Ξ”N_stab B_bar_new = Matrix{T}(I, N, N) F_new = ldr(B_bar_new) push!(B_bar, B_bar_new) push!(F, F_new) end # if number of stablization intervals decreased else # shrink B_bar and F vectors for n in 1:abs(Ξ”N_stab) B_bar_deleted = pop!(B_bar) F_deleted = pop!(F) end end end return nothing end @doc raw""" copyto!( fgc_out::FermionGreensCalculator{T,E}, fgc_in::FermionGreensCalculator{T,E} ) where {T,E} Copy the contents of `fgc_in` to `fgc_out`. If `fgc_out.n_stab != fgc_in.n_stab` is true, then `fgc_out` will be resized using [`resize!`](@ref) to match `fgc_in`. """ function copyto!( fgc_out::FermionGreensCalculator{T,E}, fgc_in::FermionGreensCalculator{T,E} ) where {T,E} # resize fgc_out to match fgc_in if necessary if fgc_out.n_stab != fgc_in.n_stab resize!(fgc_out, fgc_in.n_stab) end # copy contents of fgc_in to fgc_out fgc_out.forward = fgc_in.forward fgc_out.l = fgc_in.l for i in eachindex(fgc_in.B_bar) copyto!(fgc_out.B_bar[i]::Matrix{T}, fgc_in.B_bar[i]::Matrix{T}) copyto!(fgc_out.F[i]::LDR{T,E}, fgc_in.F[i]::LDR{T,E}) end copyto!(fgc_out.ldr_ws, fgc_in.ldr_ws) return nothing end @doc raw""" iterate(iter::FermionGreensCalculator) iterate(iter::FermionGreensCalculator, state) Iterate over imaginary time slices, alternating between iterating in the forward direction from ``l=1`` to ``l=L_\tau`` and in the reverse direction from ``l=L_\tau`` to ``l=1``. The `iter.forward` boolean field in the [`FermionGreensCalculator`](@ref) type determines whether the imaginary time slices are iterated over in forward or reverse order. The `iter.forward` field is updated as needed automatically and *should not* be adjusted manually. """ function iterate(iter::FermionGreensCalculator)::Tuple{Int,Bool} state = iter.forward # set initial time slice l if state # iterating from l=1 ==> l=LΟ„ item = 1 else # iterating from l=LΟ„ ==> l=1 item = iter.LΟ„ end return (item, state) end function iterate(iter::FermionGreensCalculator, state::Bool)::Union{Tuple{Int,Bool},Nothing} if state # iterating from l=1 ==> l=LΟ„ iter.l += 1 # terminiation criteria if iter.l == iter.LΟ„+1 iter.l = iter.LΟ„ iter.forward = false return nothing else return (iter.l, iter.forward) end else # iterating from l=LΟ„ ==> l=1 iter.l -= 1 # termination criteria if iter.l == 0 iter.l = 1 iter.forward = true return nothing else return (iter.l, iter.forward) end end return next end ###################################### ## DEVELOPER METHODS (NOT EXPORTED) ## ###################################### @doc raw""" update_factorizations!( fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P} ) where {T, E, P<:AbstractPropagator{T}} If current imaginary time slice `fgc.l` corresponds to the boundary of a stabilization interval, calculate a LDR factorization to represent ``B(0, \tau)`` or ``B(\tau-\Delta\tau, \beta)`` if iterating over imaginary time in the forward (`fgc.forward = true`) or reverse (`fgc.forward = false`) directions respectively. This method should be called *after* all changes to the current time slice propagator matrix ``B_l`` have been made This method will also recompute ``\bar{B}_n`` as needed. """ function update_factorizations!( fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P} ) where {T, E, P<:AbstractPropagator{T}} # update B_bar matrix when necessary update_BΜ„!(fgc, B) # update the factorization update_factorizations!(fgc) return nothing end @doc raw""" update_factorizations!( fgc::FermionGreensCalculator{T,E} ) where {T, E} If current imaginary time slice `fgc.l` corresponds to the boundary of a stabilization interval, calculate a LDR factorization to represent ``B(\tau, 0)`` or ``B(\beta, \tau-\Delta\tau)`` if iterating over imaginary time in the forward (`fgc.forward = true`) or reverse (`fgc.forward = false`) directions respectively. This method should be called *after* all changes to the current time slice propagator matrix ``B_l`` have been made, and any required updates to a ``\bar{B}_n`` matrix have been performed using the [`JDQMCFramework.update_BΜ„!`](@ref) routine. """ function update_factorizations!( fgc::FermionGreensCalculator{T,E} ) where {T, E} (; l, LΟ„, n_stab, N_stab, forward) = fgc F = fgc.F::Vector{LDR{T,E}} ldr_ws = fgc.ldr_ws::LDRWorkspace{T,E} B_bar = fgc.B_bar::Vector{Matrix{T}} # get stabalizaiton interval n, lβ€² = stabilization_interval(fgc) # if iterating from l=1 => l=LΟ„ if forward # if at boundary of first stabilization interval (l=n_stab) if lβ€²==n_stab && n==1 # calculate LDR factorization of B(Ο„=nₛ⋅Δτ,0) = BΜ„[1] B̄₁ = B_bar[1] B_Ο„0 = F[1]::LDR{T,E} ldr!(B_Ο„0, B̄₁, ldr_ws) # if at the end of a stabilization interval elseif lβ€²==n_stab || l==LΟ„ && N_stab > 1 # calculate LDR factorization of B(Ο„=nβ‹…nₛ⋅Δτ,0) = BΜ„[n]β‹…B(Ο„=(n-1)β‹…nₛ⋅Δτ,0) BΜ„β‚™ = B_bar[n] B_Ο„0_new = F[n]::LDR{T,E} B_Ο„0_prev = F[n-1]::LDR{T,E} mul!(B_Ο„0_new, BΜ„β‚™, B_Ο„0_prev, ldr_ws) end # if iterating from l=LΟ„ => l=1 else # if at boundary of last stabilization interval (l=LΟ„-n_stab+1) if lβ€²==1 && n==N_stab # calculate LDR factorization of B(Ξ²,Ο„=Ξ²-(n_stab+1)⋅Δτ) = BΜ„[N_stab] BΜ„_Nβ‚› = B_bar[n] B_Ξ²Ο„ = F[n]::LDR{T,E} ldr!(B_Ξ²Ο„, BΜ„_Nβ‚›, ldr_ws) # if at boundary of stabilization interval elseif lβ€²==1 && N_stab > 1 # calculate LDR factorization of B(Ξ²,Ο„=Ξ²-nβ‹…nₛ⋅Δτ-Δτ) = B(Ξ²,Ο„=Ξ²-nβ‹…nₛ⋅Δτ)β‹…BΜ„[n] BΜ„β‚™ = B_bar[n] B_Ξ²Ο„_new = F[n]::LDR{T,E} B_Ξ²Ο„_prev = F[n+1]::LDR{T,E} mul!(B_Ξ²Ο„_new, B_Ξ²Ο„_prev, BΜ„β‚™, ldr_ws) end end return nothing end @doc raw""" update_BΜ„!( fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P} ) where {T,E,P<:AbstractPropagator{T}} Recalculate ``\bar{B}_n`` if the current timeslice `fgc.l` corresponds to the boundary of a stabilization interval, accounting for whether imaginary time is being iterated over in the forward (`fgc.forward = true`) or reverse (`fgc.forward = false`) direction. """ function update_BΜ„!( fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P} ) where {T,E,P<:AbstractPropagator{T}} (; forward, n_stab, l, LΟ„) = fgc # get stabilization interval info n, lβ€² = stabilization_interval(fgc) # if iterating over imaginary time in the forward direction l=1 ==> l=LΟ„ if forward # if at boundary of stabilization interval if lβ€² == n_stab || l==LΟ„ # update B_bar[n] calculate_BΜ„!(fgc, B, n) end # if iterating over imaginary time in the reviews direction l=LΟ„ ==> l=1 else # if at boundary of stabilization interval if lβ€² == 1 # update B_bar[n] calculate_BΜ„!(fgc, B, n) end end return nothing end @doc raw""" calculate_BΜ„!( fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P}, n::Int ) where {T,E,P<:AbstractPropagator{T}} Given `B`, a vector of all the propagator matrices ``B_l``, calculate the matrix product ```math \bar{B}_{\sigma,n}=\prod_{l=(n-1)\cdot n_{s}+1}^{\min(n\cdot n_{s},L_{\tau})}B_{\sigma,l}, ``` with the result getting written to `fgc.B_bar[n]`. """ function calculate_BΜ„!( fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P}, n::Int ) where {T,E,P<:AbstractPropagator{T}} (; B_bar, n_stab, LΟ„, N_stab, ldr_ws) = fgc @assert 1 <= n <= N_stab BΜ„β‚™ = B_bar[n] copyto!(BΜ„β‚™, I) # BΜ„β‚™ := I # iterate over imaginary time slices associated with stabilization interval for l in min(n*n_stab,LΟ„):-1:(n-1)*n_stab+1 B_l = B[l]::P rmul!(BΜ„β‚™, B_l, M = ldr_ws.M) # BΜ„β‚™ := BΜ„β‚™β‹…B[l] end return nothing end @doc raw""" stabilization_interval( fgc::FermionGreensCalculator )::Tuple{Int,Int} Given the current imaginary time slice `fgc.l`, return the corresponding stabilization interval `n = ceil(Int, fgc.l/fgc.n_stab)`, and the relative location within that stabilization interval `lβ€² = mod1(fgc.l, fgc.n_stab)`, such that `lβ€²βˆˆ[1,n_stab]`. """ function stabilization_interval( fgc::FermionGreensCalculator )::Tuple{Int,Int} # calculate stabilization interval n = ceil(Int, fgc.l/fgc.n_stab) # location in stabilization interval lβ€²βˆˆ[1,n_stab] lβ€² = mod1(fgc.l, fgc.n_stab) return n, lβ€² end
JDQMCFramework
https://github.com/SmoQySuite/JDQMCFramework.jl.git
[ "MIT" ]
1.0.10
d37e67cd855d38efbc41b807f45d758eaaa82923
code
2169
module JDQMCFramework using LinearAlgebra using FastLapackInterface using Checkerboard using StableLinearAlgebra # importing function to be overloaded import Base: size, copyto!, iterate, eltype, resize! import LinearAlgebra: mul!, lmul!, rmul!, ldiv!, rdiv!, ishermitian # import functions for multiplying/dividing by diagonal matrix represented by a vector import StableLinearAlgebra: mul_D!, div_D!, lmul_D!, rmul_D!, ldiv_D!, rdiv_D! @doc raw""" Continuous = Union{AbstractFloat,Complex{<:AbstractFloat}} An abstract type to represent continuous real and complex numbers. """ Continuous = Union{AbstractFloat,Complex{<:AbstractFloat}} # various utility function include("utility_functions.jl") export eval_length_imaginary_axis # calculate length of imaginary time axis LΟ„ given Ξ² and Δτ export exp! # exponentiate matrix while avoiding dynamic memory allocations export build_hopping_matrix! # construct the hopping matrix given a neighbor table and vector or hopping amplitudes # define types to represent propagator matrices, allowing for both symmetric and asymmetric propagators, # and also the use of either the exact exponentiated hopping matrix or the checkerboard approximation include("Propagators.jl") export AbstractPropagator export AbstractExactPropagator, AbstractChkbrdPropagator export SymExactPropagator, AsymExactPropagator export SymChkbrdPropagator, AsymChkbrdPropagator export SymPropagators # defines FermionGreensCalculator type to simplify the process of calculating # single-particle fermion green's funciton matrices include("FermionGreensCalculator.jl") export FermionGreensCalculator export resize! # implements core routines that are useful in writing a DQMC code include("dqmc_routines.jl") export propagate_equaltime_greens!, stabilize_equaltime_greens!, calculate_equaltime_greens! export initialize_unequaltime_greens!, propagate_unequaltime_greens!, stabilize_unequaltime_greens! export local_update_det_ratio, local_update_greens! # Implement method for partially wrapping the Greens function matrix. include("partially_wrap_greens.jl") export partially_wrap_greens_forward!, partially_wrap_greens_reverse! end
JDQMCFramework
https://github.com/SmoQySuite/JDQMCFramework.jl.git
[ "MIT" ]
1.0.10
d37e67cd855d38efbc41b807f45d758eaaa82923
code
20214
@doc raw""" abstract type AbstractPropagator{T<:Continuous, E<:Continuous} end Abstract type to represent imaginary time propagator matrices ``B``. All specific propagators types inherit from this abstract type. In the above `T` is data type of the matrix elements of the exponentiated kintetic energy matrix ``e^{-\Delta\tau K_l}`` appearing in ``B_l``, and `E` is data type of the matrix elements appearing in the diagonal exponentiated potential energy matrix ``e^{-\Delta\tau V_l}``. """ abstract type AbstractPropagator{T<:Continuous, E<:Continuous} end @doc raw""" abstract type AbstractExactPropagator{T,E} <: AbstractPropagator{T,E} end Abstract type to represent imaginary time propagator matrices ``B`` defined with an exactly exponentiated hopping matrix ``K``. """ abstract type AbstractExactPropagator{T,E} <: AbstractPropagator{T,E} end @doc raw""" abstract type AbstractChkbrdPropagator{T,E} <: AbstractPropagator{T,E} end Abstract type to represent imaginary time propagator matrices ``B`` defined with the exponentiated hopping matrix ``K`` represented by the checkerboard approximation. """ abstract type AbstractChkbrdPropagator{T,E} <: AbstractPropagator{T,E} end @doc raw""" SymExactPropagator{T, E} <: AbstractExactPropagator{T,E} Represents imaginary time propagator matrix as using the symmetric form ```math B_l = e^{-\Delta\tau K_l/2} e^{-\Delta\tau V_l} e^{-\Delta\tau K_l/2}, ``` where ``K_l`` is the strictly off-diagonal hopping matrix and ``V_l`` is the diagonal total on-site energy matrix. # Fields - `expmΔτV::Vector{E}`: A vector representing the diagonal exponeniated on-site energy matrix ``e^{-\Delta\tau V_l}.`` - `expmΔτKo2::Matrix{T}`: The exponentiated hopping matrix ``e^{-\Delta\tau K_l/2}.`` - `exppΔτKo2::Matrix{T}`: Inverse of the exponentiated hopping matrix ``e^{+\Delta\tau K_l/2}.`` """ struct SymExactPropagator{T,E} <: AbstractExactPropagator{T,E} "A vector representing the diagonal exponeniated on-site energy matrix `exp(-Δτ⋅Vβ‚—)`." expmΔτV::Vector{E} "The exponentiated hopping matrix `exp(-Δτ⋅Kβ‚—/2)`." expmΔτKo2::Matrix{T} "Inverse of the exponentiated hopping matrix `exp(+Δτ⋅Kβ‚—/2)`." exppΔτKo2::Matrix{T} end @doc raw""" AsymExactPropagator{T, E} <: AbstractExactPropagator{T,E} Represents imaginary time propagator matrix as using the symmetric form ```math B_l = e^{-\Delta\tau V_l} e^{-\Delta\tau K_l}, ``` where ``K_l`` is the strictly off-diagonal hopping matrix and ``V_l`` is the diagonal total on-site energy matrix. # Fields - `expmΔτV::Vector{E}`: A vector representing the diagonal exponeniated on-site energy matrix ``e^{-\Delta\tau V_l}.`` - `expmΔτK::Matrix{T}`: The exponentiated hopping matrix ``e^{-\Delta\tau K_l}.`` - `exppΔτK::Matrix{T}`: Inverse of the exponentiated hopping matrix ``e^{+\Delta\tau K_l}.`` """ struct AsymExactPropagator{T,E} <: AbstractExactPropagator{T,E} "A vector representing the diagonal exponeniated on-site energy matrix `exp(-Δτ⋅Vβ‚—)`." expmΔτV::Vector{E} "The exponentiated hopping matrix `exp(-Δτ⋅Kβ‚—)`" expmΔτK::Matrix{T} "Inverse of the exponentiated hopping matrix `exp(-Δτ⋅Kβ‚—)`" exppΔτK::Matrix{T} end @doc raw""" SymChkbrdPropagator{T, E} <: AbstractChkbrdPropagator{T,E} Represents imaginary time propagator matrix as using the symmetric form ```math B_l = e^{-\Delta\tau K_l/2} e^{-\Delta\tau V_l} [e^{-\Delta\tau K_l/2}]^\dagger, ``` where ``K_l`` is the strictly off-diagonal hopping matrix and ``V_l`` is the diagonal total on-site energy matrix. The exponentiated hopping matrix ``e^{-\Delta\tau K/2}`` is represented by the checkerboard approximation. # Fields - `expmΔτV::Vector{E}`: A vector representing the diagonal exponeniated on-site energy matrix ``e^{-\Delta\tau V_l}.`` - `expmΔτKo2::CheckerboardMatrix{T}`: The exponentiated hopping matrix ``e^{-\Delta\tau K_l/2}`` represented by the checkerboard approximation. """ struct SymChkbrdPropagator{T, E} <: AbstractChkbrdPropagator{T,E} "A vector representing the diagonal exponeniated on-site energy matrix `exp(-Δτ⋅Vβ‚—)`." expmΔτV::Vector{E} "The exponentiated hopping matrix `exp(-Δτ⋅Kβ‚—/2)` represented by the checkerboard approximation." expmΔτKo2::CheckerboardMatrix{T} end @doc raw""" AsymChkbrdPropagator{T, E} <: AbstractChkbrdPropagator{T,E} Represents imaginary time propagator matrix as using the symmetric form ```math B_l = e^{-\Delta\tau V_l} e^{-\Delta\tau K_l}, ``` where ``K_l`` is the strictly off-diagonal hopping matrix and ``V_l`` is the diagonal total on-site energy matrix. The exponentiated hopping matrix ``e^{-\Delta\tau K}`` is represented by the checkerboard approximation. # Fields - `expmΔτV::Vector{E}`: The vector representing the diagonal exponeniated on-site energy matrix ``e^{-\Delta\tau V_l}.`` - `expmΔτK::CheckerboardMatrix{T}`: The exponentiated hopping matrix ``e^{-\Delta\tau K_l}`` represented by the checkerboard approximation. """ struct AsymChkbrdPropagator{T,E} <: AbstractChkbrdPropagator{T,E} "The vector representing the diagonal exponeniated on-site energy matrix `exp(-Δτ⋅Vβ‚—)`." expmΔτV::Vector{E} "The exponentiated hopping matrix `exp(-Δτ⋅Kβ‚—/2)` represented by the checkerboard approximation." expmΔτK::CheckerboardMatrix{T} end @doc raw""" SymPropagators A union of the all the symmetric propagators types to help test whether a propagator type is symmetric. Assuming `typeof{B} <: AbstractPropagator` returns `true`, if `typeof(B) <: SymPropagators` returns `true`, then `B` represents a symmetric propagator, otherwise it represents an asymmetric propagator. """ SymPropagators = Union{SymExactPropagator, SymChkbrdPropagator} @doc raw""" size(B::AbstractPropagator) size(B::AbstractPropagator, dim) Return the size of a propagator. """ size(B::AbstractPropagator) = (length(B.expmΔτV), length(B.expmΔτV)) size(B::AbstractPropagator, dim::Int) = length(B.expmΔτV) @doc raw""" ishermitian(B::AbstractPropagator) Return whether a propagator is hermitian or not. """ ishermitian(B::AbstractPropagator) = return _ishermitian(B) _ishermitian(B::SymExactPropagator) = return true _ishermitian(B::SymChkbrdPropagator) = return true _ishermitian(B::AsymExactPropagator) = return false _ishermitian(B::AsymChkbrdPropagator) = return false @doc raw""" copyto!(Bβ€²::SymExactPropagator{T,E}, B::SymExactPropagator{T,E}) where {T,E} copyto!(Bβ€²::AsymExactPropagator{T,E}, B::AsymExactPropagator{T,E}) where {T,E} copyto!(Bβ€²::SymChkbrdPropagator{T,E}, B::SymChkbrdPropagator{T,E}) where {T,E} copyto!(Bβ€²::AsymChkbrdPropagator{T,E}, B::AsymChkbrdPropagator{T,E}) where {T,E} Copy the propagator `B` to `Bβ€²`. """ function copyto!(Bβ€²::SymExactPropagator{T,E}, B::SymExactPropagator{T,E}) where {T,E} copyto!(Bβ€².expmΔτV, B.expmΔτV) copyto!(Bβ€².expmΔτKo2, B.expmΔτKo2) copyto!(Bβ€².exppΔτKo2, B.exppΔτKo2) return nothing end function copyto!(Bβ€²::AsymExactPropagator{T,E}, B::AsymExactPropagator{T,E}) where {T,E} copyto!(Bβ€².expmΔτV, B.expmΔτV) copyto!(Bβ€².expmΔτK, B.expmΔτK) copyto!(Bβ€².exppΔτK, B.exppΔτK) return nothing end function copyto!(Bβ€²::SymChkbrdPropagator{T,E}, B::SymChkbrdPropagator{T,E}) where {T,E} copyto!(Bβ€².expmΔτV, B.expmΔτV) copyto!(Bβ€².expmΔτKo2, B.expmΔτKo2) return nothing end function copyto!(Bβ€²::AsymChkbrdPropagator{T,E}, B::AsymChkbrdPropagator{T,E}) where {T,E} copyto!(Bβ€².expmΔτV, B.expmΔτV) copyto!(Bβ€².expmΔτK, B.expmΔτK) return nothing end @doc raw""" eltype(B::AbstractPropagator{T,E}) where {T,E} Return the matrix element type of the propagator `T`. """ function eltype(B::AbstractPropagator{T,E}) where {T,E} return T end @doc raw""" mul!(A::AbstractMatrix{T}, B::SymExactPropagator{T}, C::AbstractMatrix{T}; M::AbstractMatrix{T}=similar(A)) where {T} mul!(A::AbstractMatrix{T}, B::AsymExactPropagator{T}, C::AbstractMatrix{T}; M::AbstractMatrix{T}=similar(A)) where {T} mul!(A::AbstractMatrix{T}, B::AbstractChkbrdPropagator{T}, C::AbstractMatrix{T}; M=nothing) where {T} Calculate the product ``A := B \cdot C``, where ``B`` is a propagator matrix represented by an instance of a type inheriting from [`AbstractPropagator`](@ref). If `B` is asymmetric and `B.adjointed = true`, then ``A = B^\dagger \cdot C`` is evaluated instead. """ function mul!(A::AbstractMatrix{T}, B::SymExactPropagator{T}, C::AbstractMatrix{T}; M::AbstractMatrix{T}=similar(A)) where {T} mul!(M, B.expmΔτKo2, C) # exp(-Δτ⋅K/2)β‹…C lmul_D!(B.expmΔτV, M) # exp(-Δτ⋅V)β‹…exp(-Δτ⋅K/2)β‹…C mul!(A, B.expmΔτKo2, M) # A = Bβ‹…C = exp(-Δτ⋅K/2)β‹…exp(-Δτ⋅V)β‹…exp(-Δτ⋅K/2)β‹…C return nothing end function mul!(A::AbstractMatrix{T}, B::AsymExactPropagator{T}, C::AbstractMatrix{T}; M::AbstractMatrix{T}=similar(A)) where {T} mul!(A, B.expmΔτK, C) # exp(-Δτ⋅K)β‹…C lmul_D!(B.expmΔτV, A) # A = Bβ‹…C = exp(-Δτ⋅V)β‹…[exp(-Δτ⋅K)β‹…C] return nothing end function mul!(A::AbstractMatrix{T}, B::AbstractChkbrdPropagator{T}, C::AbstractMatrix{T}; M=nothing) where {T} copyto!(A, C) lmul!(B, A) return nothing end @doc raw""" mul!(A::AbstractMatrix{T}, C::AbstractMatrix{T}, B::SymExactPropagator{T}; M::AbstractMatrix{T} = similar(A)) where {T} mul!(A::AbstractMatrix{T}, C::AbstractMatrix{T}, B::AsymExactPropagator{T}; M::AbstractMatrix{T} = similar(A)) where {T} mul!(A::AbstractMatrix{T}, C::AbstractMatrix{T}, B::AbstractChkbrdPropagator{T}; M=nothing) where {T} Calculate the matrix product ``A := C \cdot B``, where ``B`` is a propagator matrix represented by an instance of a type inheriting from [`AbstractPropagator`](@ref). If `B` is asymmetric and `B.adjointed = true`, then ``A = C \cdot B^\dagger`` is evaluated instead. """ function mul!(A::AbstractMatrix{T}, C::AbstractMatrix{T}, B::SymExactPropagator{T}; M::AbstractMatrix{T} = similar(A)) where {T} mul!(M, C, B.expmΔτKo2) # Cβ‹…exp(-Δτ⋅K/2) rmul_D!(M, B.expmΔτV) # Cβ‹…exp(-Δτ⋅K/2)β‹…exp(-Δτ⋅V) mul!(A, M, B.expmΔτKo2) # A := Bβ‹…C = Cβ‹…exp(-Δτ⋅K/2)β‹…exp(-Δτ⋅V)β‹…exp(-Δτ⋅K/2) return nothing end function mul!(A::AbstractMatrix{T}, C::AbstractMatrix{T}, B::AsymExactPropagator{T}; M::AbstractMatrix{T} = similar(A)) where {T} mul_D!(M, C, B.expmΔτV) # Cβ‹…exp(-Δτ⋅V) mul!(A, M, B.expmΔτK) # A := Cβ‹…B = [Cβ‹…exp(-Δτ⋅V)]β‹…exp(-Δτ⋅K) return nothing end function mul!(A::AbstractMatrix{T}, C::AbstractMatrix{T}, B::AbstractChkbrdPropagator{T}; M = nothing) where {T} copyto!(A, C) rmul!(A, B) return nothing end @doc raw""" lmul!(B::SymExactPropagator{T}, A::AbstractMatrix{T}; M::AbstractMatrix{T} = similar(A)) where {T} lmul!(B::AsymExactPropagator{T}, A::AbstractMatrix{T}; M::AbstractMatrix{T} = similar(A)) where {T} lmul!(B::AsymExactPropagator{T}, A::AbstractMatrix{T}; M::AbstractMatrix{T} = similar(A)) where {T} lmul!(B::AsymChkbrdPropagator{T}, A::AbstractMatrix{T}; M = nothing) where {T} Calculate the matrix product ``A := B \cdot A``, where ``B`` is a propagator matrix represented by an instance of a type inheriting from [`AbstractPropagator`](@ref). If `B` is asymmetric and `B.adjointed = true`, when ``A := B^\dagger \cdot A`` is evaluated instead. """ function lmul!(B::SymExactPropagator{T}, A::AbstractMatrix{T}; M::AbstractMatrix{T} = similar(A)) where {T} mul!(M, B.expmΔτKo2, A) # exp(-Δτ⋅K/2)β‹…A lmul_D!(B.expmΔτV, M) # exp(-Δτ⋅V)β‹…exp(-Δτ⋅K/2)β‹…A mul!(A, B.expmΔτKo2, M) # A := Bβ‹…A = exp(-Δτ⋅K/2)β‹…exp(-Δτ⋅V)β‹…exp(-Δτ⋅K/2)β‹…A return nothing end function lmul!(B::AsymExactPropagator{T}, A::AbstractMatrix{T}; M::AbstractMatrix{T} = similar(A)) where {T} mul!(M, B.expmΔτK, A) # exp(-Δτ⋅K)β‹…A mul_D!(A, B.expmΔτV, M) # A := Bβ‹…A = exp(-Δτ⋅V)β‹…[exp(-Δτ⋅K)β‹…A] return nothing end function lmul!(B::SymChkbrdPropagator{T}, A::AbstractMatrix{T}; M = nothing) where {T} expmΔτKo2α΅€ = adjoint(B.expmΔτKo2) lmul!(expmΔτKo2α΅€, A) # exp(-Δτ⋅K/2)α΅€β‹…A lmul_D!(B.expmΔτV, A) # exp(-Δτ⋅V)β‹…exp(-Δτ⋅K/2)α΅€β‹…A lmul!(B.expmΔτKo2, A) # A := Bβ‹…A = exp(-Δτ⋅K/2)β‹…exp(-Δτ⋅V)β‹…exp(-Δτ⋅K/2)α΅€β‹…A return nothing end function lmul!(B::AsymChkbrdPropagator{T}, A::AbstractMatrix{T}; M = nothing) where {T} lmul!(B.expmΔτK, A) # exp(-Δτ⋅K)β‹…A lmul_D!(B.expmΔτV, A) # A := Bβ‹…A = exp(-Δτ⋅V)β‹…[exp(-Δτ⋅K)β‹…A] return nothing end @doc raw""" rmul!(A::AbstractMatrix{T}, B::SymExactPropagator{T}; M::AbstractMatrix{T} = similar(A)) where {T} rmul!(A::AbstractMatrix{T}, B::AsymExactPropagator{T}; M::AbstractMatrix{T} = similar(A)) where {T} rmul!(A::AbstractMatrix{T}, B::SymChkbrdPropagator{T}; M = nothing) where {T} rmul!(A::AbstractMatrix{T}, B::AsymChkbrdPropagator{T}; M = nothing) where {T} Calculate the matrix product ``A := A \cdot B``, where ``B`` is a propagator matrix represented by an instance of a type inheriting from [`AbstractPropagator`](@ref). If `B` is asymmetric and `B.adjointed = true`, then ``A := A \cdot B^\dagger`` is evaluated instead. """ function rmul!(A::AbstractMatrix{T}, B::SymExactPropagator{T}; M::AbstractMatrix{T} = similar(A)) where {T} mul!(M, A, B.expmΔτKo2) # Aβ‹…exp(-Δτ⋅K/2) rmul_D!(M, B.expmΔτV) # Aβ‹…exp(-Δτ⋅K/2)β‹…exp(-Δτ⋅V) mul!(A, M, B.expmΔτKo2) # A := Aβ‹…B = Aβ‹…exp(-Δτ⋅K/2)β‹…exp(-Δτ⋅V)β‹…exp(-Δτ⋅K/2) return nothing end function rmul!(A::AbstractMatrix{T}, B::AsymExactPropagator{T}; M::AbstractMatrix{T} = similar(A)) where {T} mul_D!(M, A, B.expmΔτV) # Aβ‹…exp(-Δτ⋅V) mul!(A, M, B.expmΔτK) # A := Aβ‹…B = [Aβ‹…exp(-Δτ⋅V)]β‹…exp(-Δτ⋅K) return nothing end function rmul!(A::AbstractMatrix{T}, B::SymChkbrdPropagator{T}; M = nothing) where {T} expmΔτKo2α΅€ = adjoint(B.expmΔτKo2) rmul!(A, B.expmΔτKo2) # Aβ‹…exp(-Δτ⋅K/2) rmul_D!(A, B.expmΔτV) # Aβ‹…exp(-Δτ⋅K/2)β‹…exp(-Δτ⋅V) rmul!(A, expmΔτKo2α΅€) # A := Aβ‹…B = Aβ‹…exp(-Δτ⋅K/2)α΅€β‹…exp(-Δτ⋅V)β‹…exp(-Δτ⋅K/2)α΅€ return nothing end function rmul!(A::AbstractMatrix{T}, B::AsymChkbrdPropagator{T}; M = nothing) where {T} rmul_D!(A, B.expmΔτV) # Aβ‹…exp(-Δτ⋅V) rmul!(A, B.expmΔτK) # A := Aβ‹…B = [Aβ‹…exp(-Δτ⋅V)]β‹…exp(-Δτ⋅K) return nothing end @doc raw""" ldiv!(A::AbstractMatrix{T}, B::AbstractExactPropagator{T}, C::AbstractMatrix{T}; M::AbstractMatrix{T} = similar(A)) where {T} ldiv!(A::AbstractMatrix{T}, B::AbstractChkbrdPropagator{T}, C::AbstractMatrix{T}; M = nothing) where {T} Calculate the matrix product ``A := B^{-1} \cdot C``, where ``B`` is a propagator matrix represented by an instance of a type inheriting from [`AbstractPropagator`](@ref). If `B` is asymmetric and `B.adjointed = true`, then ``A = [B^\dagger]^{-1} \cdot C`` is evaluated instead. """ function ldiv!(A::AbstractMatrix{T}, B::AbstractExactPropagator{T}, C::AbstractMatrix{T}; M::AbstractMatrix{T} = similar(A)) where {T} copyto!(A, C) ldiv!(B, A, M=M) return nothing end function ldiv!(A::AbstractMatrix{T}, B::AbstractChkbrdPropagator{T}, C::AbstractMatrix{T}; M = nothing) where {T} copyto!(A, C) ldiv!(B, A) return nothing end @doc raw""" ldiv!(B::SymExactPropagator{T}, A::AbstractMatrix{T}; M::AbstractMatrix{T} = similar(A)) where {T} ldiv!(B::AsymExactPropagator{T}, A::AbstractMatrix{T}; M::AbstractMatrix{T} = similar(A)) where {T} ldiv!(B::SymChkbrdPropagator{T}, A::AbstractMatrix{T}; M = nothing) where {T} ldiv!(B::AsymChkbrdPropagator{T}, A::AbstractMatrix{T}; M = nothing) where {T} Calculate the matrix product ``A := B^{-1} \cdot A``, where ``B`` is a propagator matrix represented by an instance of a type inheriting from [`AbstractPropagator`](@ref). If `B` is asymmetric and `B.adjointed = true`, then ``A := [B^\dagger]^{-1} \cdot A`` is evaluated instead. """ function ldiv!(B::SymExactPropagator{T}, A::AbstractMatrix{T}; M::AbstractMatrix{T} = similar(A)) where {T} mul!(M, B.exppΔτKo2, A) # exp(+Δτ⋅K/2)β‹…A ldiv_D!(B.expmΔτV, M) # exp(+Δτ⋅V)β‹…exp(+Δτ⋅K/2)β‹…A mul!(A, B.exppΔτKo2, M) # A := B⁻¹⋅A = exp(+Δτ⋅K/2)β‹…exp(+Δτ⋅V)β‹…exp(+Δτ⋅K/2)β‹…A return nothing end function ldiv!(B::AsymExactPropagator{T}, A::AbstractMatrix{T}; M::AbstractMatrix{T} = similar(A)) where {T} div_D!(M, B.expmΔτV, A) # exp(+Δτ⋅V)β‹…A mul!(A, B.exppΔτK, M) # A := B⁻¹⋅A = exp(+Δτ⋅K)β‹…[exp(+Δτ⋅V)β‹…A] return nothing end function ldiv!(B::SymChkbrdPropagator{T}, A::AbstractMatrix{T}; M = nothing) where {T} expmΔτKo2α΅€ = transpose(B.expmΔτKo2) ldiv!(B.expmΔτKo2, A) # exp(+Δτ⋅K/2)β‹…A ldiv_D!(B.expmΔτV, A) # exp(+Δτ⋅V)β‹…exp(+Δτ⋅K/2)β‹…A ldiv!(expmΔτKo2α΅€, A) # A := B⁻¹⋅A = [exp(+Δτ⋅K/2)]α΅€β‹…exp(+Δτ⋅V)β‹…exp(+Δτ⋅K/2)β‹…A return nothing end function ldiv!(B::AsymChkbrdPropagator{T}, A::AbstractMatrix{T}; M = nothing) where {T} ldiv_D!(B.expmΔτV, A) # exp(+Δτ⋅V)β‹…A ldiv!(B.expmΔτK, A) # A := B⁻¹⋅A = exp(+Δτ⋅K)β‹…[exp(+Δτ⋅V)β‹…A] return nothing end @doc raw""" rldiv!(A::AbstractMatrix{T}, C::AbstractMatrix{T}, B::AbstractExactPropagator{T}; M::AbstractMatrix{T} = similar(A)) where {T} rdiv!(A::AbstractMatrix{T}, C::AbstractMatrix{T}, B::AbstractChkbrdPropagator{T}; M = nothing) where {T} Calculate the matrix product ``A := C \cdot B^{-1}``, where ``B`` is a propagator matrix represented by an instance of a type inheriting from [`AbstractPropagator`](@ref). If `B` is asymmetric and `B` is asymmetric and `B.adjointed = true`, then ``A = C \cdot [B^\dagger]^{-1}`` is evaluated instead. """ function rdiv!(A::AbstractMatrix{T}, C::AbstractMatrix{T}, B::AbstractExactPropagator{T}; M::AbstractMatrix{T} = similar(A)) where {T} copyto!(A, C) rdiv!(A, B, M=M) return nothing end function rdiv!(A::AbstractMatrix{T}, C::AbstractMatrix{T}, B::AbstractChkbrdPropagator{T}; M = nothing) where {T} copyto!(A, C) rdiv!(A, B) return nothing end @doc raw""" rdiv!(A::AbstractMatrix{T}, B::SymExactPropagator{T}; M::AbstractMatrix{T} = similar(A)) where {T} rdiv!(A::AbstractMatrix{T}, B::AsymExactPropagator{T}; M::AbstractMatrix{T} = similar(A)) where {T} rdiv!(A::AbstractMatrix{T}, B::SymChkbrdPropagator{T}; M = nothing) where {T} rdiv!(A::AbstractMatrix{T}, B::AsymChkbrdPropagator{T}; M = nothing) where {T} Calculate the matrix product ``A := A \cdot B^{-1}``, where ``B`` is a propagator matrix represented by an instance of a type inheriting from [`AbstractPropagator`](@ref). If `B` is asymmetric and `B.adjointed = true`, then ``A := A \cdot [B^\dagger]^{-1}`` is evaluated instead. """ function rdiv!(A::AbstractMatrix{T}, B::SymExactPropagator{T}; M::AbstractMatrix{T} = similar(A)) where {T} mul!(M, A, B.exppΔτKo2) # Aβ‹…exp(+Δτ⋅K/2) rdiv_D!(M, B.expmΔτV) # Aβ‹…exp(+Δτ⋅K/2)β‹…exp(+Δτ⋅V) mul!(A, M, B.exppΔτKo2) # A := Aβ‹…B⁻¹ = Aβ‹…exp(+Δτ⋅K/2)β‹…exp(+Δτ⋅V)β‹…exp(+Δτ⋅K/2) return nothing end function rdiv!(A::AbstractMatrix{T}, B::AsymExactPropagator{T}; M::AbstractMatrix{T} = similar(A)) where {T} mul!(M, A, B.exppΔτK) # Aβ‹…exp(+Δτ⋅K) div_D!(A, M, B.expmΔτV) # A := Aβ‹…B⁻¹ = [Aβ‹…exp(+Δτ⋅K)]β‹…exp(+Δτ⋅V) return nothing end function rdiv!(A::AbstractMatrix{T}, B::SymChkbrdPropagator{T}; M = nothing) where {T} expmΔτKo2α΅€ = adjoint(B.expmΔτKo2) rdiv!(A, expmΔτKo2α΅€) # Aβ‹…[exp(+Δτ⋅K/2)]α΅€ rdiv_D!(A, B.expmΔτV) # Aβ‹…[exp(+Δτ⋅K/2)]α΅€β‹…exp(+Δτ⋅V) rdiv!(A, B.expmΔτKo2) # A := Aβ‹…B⁻¹ = Aβ‹…[exp(+Δτ⋅K/2)]α΅€β‹…exp(+Δτ⋅V)β‹…exp(+Δτ⋅K/2) return nothing end function rdiv!(A::AbstractMatrix{T}, B::AsymChkbrdPropagator{T}; M = nothing) where {T} rdiv!(A, B.expmΔτK) # Aβ‹…exp(+ΔτK) rdiv_D!(A, B.expmΔτV) # A := Aβ‹…B⁻¹ = [Aβ‹…exp(+ΔτK)]β‹…exp(+Δτ⋅V) return nothing end
JDQMCFramework
https://github.com/SmoQySuite/JDQMCFramework.jl.git
[ "MIT" ]
1.0.10
d37e67cd855d38efbc41b807f45d758eaaa82923
code
25701
@doc raw""" calculate_equaltime_greens!( G::AbstractMatrix{T}, fgc::FermionGreensCalculator{T,E} )::Tuple{E,T} where {T,E} Calculate the equal-time Greens function ``G(0,0) = G(\beta,\beta) = [I + B(\beta,0)]^{-1}`` using a numerically stable procedure. This method also returns ``\log(\vert \det G \vert)`` and ``\textrm{sign}(\det G).`` Note that this routine requires `fgc.l == 1` or `fgc.l == fgc.LΟ„`. """ function calculate_equaltime_greens!( G::AbstractMatrix{T}, fgc::FermionGreensCalculator{T,E} )::Tuple{E,T} where {T,E} (; forward, l, LΟ„, N_stab, ldr_ws) = fgc @assert l == 1 || l == LΟ„ # get B(0,Ξ²) if forward B_Ξ²0 = fgc.F[1]::LDR{T,E} else B_Ξ²0 = fgc.F[N_stab]::LDR{T,E} end # calculate G(0,0) = [I + B(Ξ²,0)]⁻¹ logdetG, sgndetG = inv_IpA!(G, B_Ξ²0, ldr_ws) return logdetG, sgndetG end @doc raw""" calculate_equaltime_greens!( G::AbstractMatrix{T}, fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P} )::Tuple{E,T} where {T, E, P<:AbstractPropagator{T}} Calculate the equal-time Greens function ``G(0,0) = G(\beta,\beta) = [I + B(\beta,0)]^{-1}`` using a numerically stable procedure. Also re-calculate the ``\bar{B}_n`` matrices and the LDR matrix factorizations representing either ``B(\tau,0)`` or ``B(\beta,\tau)`` stored in `fgc.F`. This routine is useful for implementing global updates where every propagator matrix ``B_l`` has been modified, and the equal-time Green's function needs to be re-calculated from scratch. This method also returns ``\log(\vert \det G \vert)`` and ``\textrm{sign}(\det G).`` Note that this routine requires `fgc.l == 1` or `fgc.l == fgc.LΟ„`. """ function calculate_equaltime_greens!( G::AbstractMatrix{T}, fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P} )::Tuple{E,T} where {T, E, P<:AbstractPropagator{T}} # iterate over imaginary time for l in fgc # re-calculate B_bar matrices and matrix factorizations B(Ο„,0) or B(Ξ²,Ο„) as needed update_factorizations!(fgc, B) end # calculate equal-time Greens funciton matrix G(0,0) = G(Ξ²,Ξ²) logdetG, sgndetG = calculate_equaltime_greens!(G, fgc) return logdetG, sgndetG end @doc raw""" propagate_equaltime_greens!( G::AbstractMatrix{T}, fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P} ) where {T, E, P<:AbstractPropagator{T}} Propagate the equal-time Green's function matrix `G` from the previous imaginary time slice to the current imaginary time slice `fgc.l`. If iterating over imaginary time in the forward direction (`fgc.forward = true`) the relationship ```math G(\tau+\Delta\tau,\tau+\Delta\tau) = B_{l+1} \cdot G(\tau,\tau) \cdot B_{l+1}^{-1} ``` is used, and if iterating over imaginary time in the reverse direction (`fgc.forward = false`) the relationship ```math G(\tau-\Delta\tau,\tau-\Delta\tau)= B_{l}^{-1} \cdot G(\tau,\tau) \cdot B_{l} ``` is used instead, where the ``B_l`` propagator is given by `B[l]`. """ function propagate_equaltime_greens!( G::AbstractMatrix{T}, fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P} ) where {T, E, P<:AbstractPropagator{T}} (; n_stab, l, LΟ„, forward) = fgc ldr_ws = fgc.ldr_ws::LDRWorkspace{T,E} M = ldr_ws.M::Matrix{T} # get stabilization interval info n, lβ€² = stabilization_interval(fgc) # if iterating from l=1 => l=LΟ„ if forward # G(l,l) = B[l]β‹…G(l-1,l-1)β‹…B⁻¹[l] B_l = B[l]::P lmul!(B_l, G, M = M) rdiv!(G, B_l, M = M) # if iterating from l=LΟ„ => l=1. # Note: if `fgc.l` corresponds to the "end" of a stabilization interval (lβ€²=n_stab or l=LΟ„), then # when the equal-time Green's function was previously re-computed at `fgc.l+1` in the stabilize_equatime_greens!() # routine, it already calculated G(l,l), so we don't need to propagate to G(l,l) here. elseif !(lβ€² == n_stab || l==LΟ„) # G(l,l) = B⁻¹[l+1]β‹…G(l+1,l+1)β‹…B[l+1] B_lp1 = B[l+1]::P ldiv!(B_lp1, G, M = M) rmul!(G, B_lp1, M = M) end return nothing end @doc raw""" stabilize_equaltime_greens!( G::AbstractMatrix{T}, logdetG::E, sgndetG::T, fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P}; # KEYWORD ARGUMENTS update_BΜ„::Bool=true )::Tuple{E,T,E,E} where {T, E, P<:AbstractPropagator{T}} Stabilize the equal-time Green's function as iterating through imaginary time ``\tau = \Delta\tau \cdot l.`` For a given imaginary time slice `fgc.l`, this routine should be called *after* all changes to the ``B_l`` propagator have been made. When iterating through imaginary time in the forwards direction (`fgc.forward = true`), this function re-computes ```math G(\tau,\tau) = [I + B(\tau,0)B(\beta,\tau)]^{-1} ``` when at imaginary time slice `fgc.l` every `fgc.n_stab` imaginary time slice. When iterating through imaginary time in the reverse direction (`fgc.forward = false`), this function instead re-computes ```math G(\tau-\Delta\tau,\tau-\Delta\tau) = [I + B(\tau-\Delta\tau,0)B(\beta,\tau-\Delta\tau)]^{-1} ``` for `fgc.l`. This method returns four values. The first two values returned are ``\log(\vert \det G(\tau,\tau) \vert)`` and ``\textrm{sign}(\det G(\tau,\tau))``. The latter two are the maximum error in a Green's function corrected by numerical stabilization ``\vert \delta G \vert``, and the error in the phase of the determinant corrected by numerical stabilization ``\delta\theta,`` relative to naive propagation of the Green's function matrix in imaginary time occuring instead. If no stabilization was performed, than ``\vert \delta G \vert = 0`` and ``\delta \theta = 0.`` This method also computes the LDR matrix factorizations representing ``B(\tau, 0)`` or ``B(\beta, \tau-\Delta\tau)`` when iterating through imaginary time ``\tau = \Delta\tau \cdot l`` in the forward and reverse directions respectively. If `update_BΜ„ = true`, then the ``\bar{B}_n`` matrices are re-calculated as needed, but if `update_BΜ„ = false,` then they are left unchanged. """ function stabilize_equaltime_greens!( G::AbstractMatrix{T}, logdetG::E, sgndetG::T, fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P}; # KEYWORD ARGUMENTS update_BΜ„::Bool=true )::Tuple{E,T,E,E} where {T, E, P<:AbstractPropagator{T}} (; l, LΟ„, forward, n_stab, N_stab, Gβ€²) = fgc F = fgc.F::Vector{LDR{T,E}} ldr_ws = fgc.ldr_ws::LDRWorkspace{T,E} # get stabilization interval info n, lβ€² = stabilization_interval(fgc) # initialize error corrected by stabilization in green's function # and error in phase of determinant Ξ΄G = zero(E) δθ = zero(E) # boolean specifying whether or not stabilization was performed stabilized = false # record initial sign of determinant sgndetGβ€² = sgndetG # update B(Ο„,0) if iterating forward or B(Ξ²,Ο„-Δτ) if iterating backwards if update_BΜ„ # also re-calculate B_bar matrices update_factorizations!(fgc, B) else # do not update B_bar matrices update_factorizations!(fgc) end # if iterating from l=1 => l=LΟ„ if forward # if at last time slice calculate G(Ξ²,Ξ²) if l == LΟ„ # record initial Gβ€²(Ξ²,Ξ²) = G(Ξ²,Ξ²) before stabilization copyto!(Gβ€², G) # G(Ξ²,Ξ²) = [I + B(Ξ²,0)]⁻¹ B_Ξ²0 = F[N_stab]::LDR{T,E} logdetG, sgndetG = inv_IpA!(G, B_Ξ²0, ldr_ws) # record that stabilization was performed stabilized = true # if at boundary of stablization interval calculate G(Ο„,Ο„) elseif lβ€² == n_stab && N_stab > 1 # record initial Gβ€²(Ο„,Ο„) = G(Ο„,Ο„) before stabilization copyto!(Gβ€², G) # calculate G(Ο„,Ο„) = [I + B(Ο„,0)β‹…B(Ξ²,Ο„)]⁻¹ B_Ξ²Ο„ = F[n+1]::LDR{T,E} B_Ο„0 = F[n]::LDR{T,E} logdetG, sgndetG = inv_IpUV!(G, B_Ο„0, B_Ξ²Ο„, ldr_ws) # record that stabilization was performed stabilized = true end # if iterating from l=LΟ„ => l=1 else # if at first time slice calculate G(0,0) = G(Ξ²,Ξ²) if l == 1 # perform naive propagation Gβ€²(Ο„-Δτ,Ο„-Δτ) = B⁻¹[l]β‹…G(Ο„,Ο„)β‹…B[l] B_l = B[l]::P mul!(Gβ€², G, B_l, M = ldr_ws.M) # G(Ο„,Ο„)β‹…B[l] ldiv!(B_l, Gβ€², M = ldr_ws.M) # B⁻¹[l]β‹…G(Ο„,Ο„)β‹…B[l] # G(0,0) = [I + B(Ξ²,0)]⁻¹ B_Ξ²0 = F[1]::LDR{T,E} logdetG, sgndetG = inv_IpA!(G, B_Ξ²0, ldr_ws) # record that stabilization was performed stabilized = true # if at boundary of stabilization interval calculate G(Ο„-Δτ,Ο„-Δτ) elseif lβ€² == 1 && N_stab > 1 # perform naive propagation Gβ€²(Ο„-Δτ,Ο„-Δτ) = B⁻¹[l]β‹…G(Ο„,Ο„)β‹…B[l] B_l = B[l]::P mul!(Gβ€², G, B_l, M = ldr_ws.M) # G(Ο„,Ο„)β‹…B[l] ldiv!(B_l, Gβ€², M = ldr_ws.M) # B⁻¹[l]β‹…G(Ο„,Ο„)β‹…B[l] # calucate G(Ο„-Δτ,Ο„-Δτ) = [I + B(Ο„-Δτ,0)β‹…B(Ξ²,Ο„-Δτ)]⁻¹ B_Ξ²_Ο„mΔτ = F[n]::LDR{T,E} B_Ο„mΔτ_0 = F[n-1]::LDR{T,E} logdetG, sgndetG = inv_IpUV!(G, B_Ο„mΔτ_0, B_Ξ²_Ο„mΔτ, ldr_ws) # record that stabilization was performed stabilized = true end end # calculate error corrected by stabilization if stabilized Ξ”G = Gβ€² @. Ξ”G = abs(Gβ€²-G) Ξ΄G = maximum(real, Ξ”G) δθ = angle(sgndetGβ€²/sgndetG) end return (logdetG, sgndetG, Ξ΄G, δθ) end @doc raw""" initialize_unequaltime_greens!( GΟ„0::AbstractMatrix{T}, G0Ο„::AbstractMatrix{T}, Gττ::AbstractMatrix{T}, G00::AbstractMatrix{T} ) where {T<:Number} Initialize the Green's function matrices ``G(\tau,0),`` ``G(0,\tau),`` and ``G(\tau,\tau)`` for ``\tau = 0`` based on the matrix ``G(0,0).`` """ function initialize_unequaltime_greens!( GΟ„0::AbstractMatrix{T}, G0Ο„::AbstractMatrix{T}, Gττ::AbstractMatrix{T}, G00::AbstractMatrix{T} ) where {T<:Number} # G(Ο„=0,Ο„=0) = G(0,0) copyto!(Gττ, G00) # G(Ο„=0,0) = G(0,0) copyto!(GΟ„0, G00) # G(0,Ο„=0) = -(I-G(0,0)) copyto!(G0Ο„, I) @. G0Ο„ = -(G0Ο„ - G00) return nothing end @doc raw""" propagate_unequaltime_greens!( GΟ„0::AbstractMatrix{T}, G0Ο„::AbstractMatrix{T}, Gττ::AbstractMatrix{T}, fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P} ) where {T, E, P<:AbstractPropagator{T}} Propagate the Green's function matrices ``G(\tau,0)``, ``G(0,\tau)`` and ``G(\tau,\tau)`` from the previous imaginary time slice to the current imaginary time slice `fgc.l`. If iterating over imaginary time in the forward direction (`fgc.forward = true`) the relationships ```math \begin{align} G(\tau,0) = & B_{l} \cdot G(\tau-\Delta\tau, 0) \\ G(0,\tau) = & G(0, \tau-\Delta\tau) \cdot B^{-1}_{l} \\ G(\tau,\tau) = & B_{l} \cdot G(\tau-\Delta\tau, \tau-\Delta\tau) \cdot B_{l}^{-1} \end{align} ``` are used, and if iterating over imaginary time in the reverse direction (`fgc.forward = false`) the relationships ```math \begin{align} G(\tau,0) = & B_{l+1}^{-1} \cdot G(\tau+\Delta\tau, 0) \\ G(0,\tau) = & G(0, \tau + \Delta\tau) \cdot B_{l+1} \\ G(\tau,\tau) = & B_{l+1}^{-1} \cdot G(\tau+\Delta\tau, \tau+\Delta\tau) \cdot B_{l+1} \end{align} ``` are used instead, where the ``B_l`` propagator is given by `B[l]`. """ function propagate_unequaltime_greens!( GΟ„0::AbstractMatrix{T}, G0Ο„::AbstractMatrix{T}, Gττ::AbstractMatrix{T}, fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P} ) where {T, E, P<:AbstractPropagator{T}} (; n_stab, l, LΟ„, forward) = fgc ldr_ws = fgc.ldr_ws::LDRWorkspace{T,E} M = ldr_ws.M::Matrix{T} # get stabilization interval info n, lβ€² = stabilization_interval(fgc) # if iterating from l=1 => l=LΟ„ if forward # G(l,l) = B[l]β‹…G(l-1,l-1)β‹…B⁻¹[l] B_l = B[l]::P lmul!(B_l, Gττ, M = M) rdiv!(Gττ, B_l, M = M) # G(l,0) = B[l]β‹…G(l-1,0) lmul!(B_l, GΟ„0, M = M) # G(0,l) = G(0,l-1)β‹…B⁻¹[l] rdiv!(G0Ο„, B_l, M = M) # if beginning iteration from l=LΟ„ => l=1, initialize uneqaul-time green's function matrices elseif l == LΟ„ # G(Ο„=Ξ²,0) = (I - G(0,0)) copyto!(GΟ„0, I) @. GΟ„0 = (GΟ„0 - Gττ) # G(0,Ο„=Ξ²) = -G(0,0) @. G0Ο„ = -Gττ # if iterating from l=LΟ„ => l=1. # Note: if `fgc.l` corresponds to the "end" of a stabilization interval (lβ€²=n_stab), then # when the equal-time Green's function was previously re-computed at `fgc.l+1` in the stabilize_equatime_greens!() # routine, it already calculated G(l,l), so we don't need to propagate to G(l,l) here. elseif !(lβ€² == n_stab) # G(l,l) = B⁻¹[l+1]β‹…G(l+1,l+1)β‹…B[l+1] B_lp1 = B[l+1]::P ldiv!(B_lp1, Gττ, M = M) rmul!(Gττ, B_lp1, M = M) # G(l, 0) = B⁻¹[l+1]β‹…G(l+1,0) ldiv!(B_lp1, GΟ„0, M = M) # G(0, l) = G(0,l+1)β‹…B[l+1] rmul!(G0Ο„, B_lp1, M = M) end return nothing end @doc raw""" stabilize_unequaltime_greens!( GΟ„0::AbstractMatrix{T}, G0Ο„::AbstractMatrix{T}, Gττ::AbstractMatrix{T}, logdetG::E, sgndetG::T, fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P}; # KEYWORD ARGUMENTS update_BΜ„::Bool=true )::Tuple{E,T,E,E} where {T, E, P<:AbstractPropagator{T}} Stabilize the Green's function matrice ``G(\tau,0)``, ``G(0,\tau)`` and ``G(\tau,\tau)`` as iterating through imaginary time ``\tau = \Delta\tau \cdot l.`` For a given imaginary time slice `fgc.l`, this routine should be called *after* all changes to the ``B_l`` propagator have been made. When iterating through imaginary time in the forwards direction (`fgc.forward = true`), this function re-computes ```math \begin{align} G(\tau,0) = & [B^{-1}(\tau,0) + B(\beta,\tau)]^{-1} \\ G(0, \tau) = & [B^{-1}(\beta,\tau) + B(\tau,0)]^{-1} \\ G(\tau,\tau) = & [I + B(\tau,0)B(\beta,\tau)]^{-1} \end{align} ``` when at imaginary time slice `fgc.l` every `fgc.n_stab` imaginary time slice. When iterating through imaginary time in the reverse direction (`fgc.forward = false`), this function instead re-computes ```math \begin{align*} G(\tau-\Delta\tau,0) = & [B^{-1}(\tau-\Delta\tau,0) + B(\beta,\tau-\Delta\tau)]^{-1} \\ G(0,\tau-\Delta\tau) = & [B^{-1}(\beta,\tau-\Delta\tau) + B(\tau-\Delta\tau,0)]^{-1} \\ G(\tau-\Delta\tau,\tau-\Delta\tau) = & [I + B(\tau-\Delta\tau,0)B(\beta,\tau-\Delta\tau)]^{-1} \begin{align*} ``` for `fgc.l`. This method returns four values. The first two values returned are ``\log(\vert \det G(\tau,\tau) \vert)`` and ``\textrm{sign}(\det G(\tau,\tau))``. The latter two are the maximum error in a Green's function corrected by numerical stabilization ``\vert \delta G \vert``, and the error in the phase of the determinant corrected by numerical stabilization ``\delta\theta,`` relative to naive propagation of the Green's function matrix in imaginary time occuring instead. If no stabilization was performed, than ``\vert \delta G \vert = 0`` and ``\delta \theta = 0.`` This method also computes the LDR matrix factorizations representing ``B(\tau, 0)`` or ``B(\beta, \tau-\Delta\tau)`` when iterating through imaginary time ``\tau = \Delta\tau \cdot l`` in the forward and reverse directions respectively. If `update_BΜ„ = true`, then the ``\bar{B}_n`` matrices are re-calculated as needed, but if `update_BΜ„ = false,` then they are left unchanged. """ function stabilize_unequaltime_greens!( GΟ„0::AbstractMatrix{T}, G0Ο„::AbstractMatrix{T}, Gττ::AbstractMatrix{T}, logdetG::E, sgndetG::T, fgc::FermionGreensCalculator{T,E}, B::AbstractVector{P}; # KEYWORD ARGUMENTS update_BΜ„::Bool=true )::Tuple{E,T,E,E} where {T, E, P<:AbstractPropagator{T}} (; l, LΟ„, forward, n_stab, N_stab, Gβ€²) = fgc F = fgc.F::Vector{LDR{T,E}} ldr_ws = fgc.ldr_ws::LDRWorkspace{T,E} # get stabilization interval info n, lβ€² = stabilization_interval(fgc) # initialize error corrected by stabilization in green's function # and error in phase of determinant Ξ΄G = zero(E) δθ = zero(E) # boolean specifying whether or not stabilization was performed stabilized = false # record initial sign of determinant sgndetGβ€² = sgndetG # update B(Ο„,0) if iterating forward or B(Ξ²,Ο„-Δτ) if iterating backwards if update_BΜ„ # also re-calculate B_bar matrices update_factorizations!(fgc, B) else # do not update B_bar matrices update_factorizations!(fgc) end # if iterating from l=1 => l=LΟ„ if forward # if at last time slice calculate G(Ξ²,Ξ²) if l == LΟ„ # record initial Gβ€²(Ξ²,Ξ²) = G(Ξ²,Ξ²) before stabilization copyto!(Gβ€², Gττ) # G(0,0) = G(Ξ²,Ξ²) = [I + B(Ξ²,0)]⁻¹ B_Ξ²0 = F[N_stab]::LDR{T,E} logdetG, sgndetG = inv_IpA!(Gττ, B_Ξ²0, ldr_ws) # G(Ξ², 0) = I - G(0,0) copyto!(GΟ„0, I) @. GΟ„0 = GΟ„0 - Gττ # G(0, Ξ²) = -G(0,0) @. G0Ο„ = -Gττ # record that stabilization was performed stabilized = true # if at boundary of stablization interval calculate G(Ο„,Ο„) elseif lβ€² == n_stab && N_stab > 1 # record initial Gβ€²(Ο„,Ο„) = G(Ο„,Ο„) before stabilization copyto!(Gβ€², Gττ) # calculate G(Ο„,Ο„) = [I + B(Ο„,0)β‹…B(Ξ²,Ο„)]⁻¹ B_Ξ²Ο„ = F[n+1]::LDR{T,E} B_Ο„0 = F[n]::LDR{T,E} logdetG, sgndetG = inv_IpUV!(Gττ, B_Ο„0, B_Ξ²Ο„, ldr_ws) # calculate G(Ο„,0) = [B⁻¹(Ο„,0) + B(Ξ²,Ο„)]⁻¹ inv_invUpV!(GΟ„0, B_Ο„0, B_Ξ²Ο„, ldr_ws) # calculate G(0,Ο„) = -[B⁻¹(Ξ²,Ο„) + B(Ο„,0)]⁻¹ inv_invUpV!(G0Ο„, B_Ξ²Ο„, B_Ο„0, ldr_ws) @. G0Ο„ = -G0Ο„ # record that stabilization was performed stabilized = true end # if iterating from l=LΟ„ => l=1 else # if at first time slice calculate G(0,0) = G(Ξ²,Ξ²) if l == 1 # perform naive propagation Gβ€²(Ο„-Δτ,Ο„-Δτ) = B⁻¹[l]β‹…G(Ο„,Ο„)β‹…B[l] B_l = B[l]::P mul!(Gβ€², Gττ, B_l, M = ldr_ws.M) # G(Ο„,Ο„)β‹…B[l] ldiv!(B_l, Gβ€², M = ldr_ws.M) # B⁻¹[l]β‹…G(Ο„,Ο„)β‹…B[l] # G(0,0) = [I + B(Ξ²,0)]⁻¹ B_Ξ²0 = F[1]::LDR{T,E} logdetG, sgndetG = inv_IpA!(Gττ, B_Ξ²0, ldr_ws) # G(Ξ², 0) = I - G(0,0) copyto!(GΟ„0, I) @. GΟ„0 = GΟ„0 - Gττ # G(0, Ξ²) = -G(0,0) @. G0Ο„ = -Gττ # record that stabilization was performed stabilized = true # if at boundary of stabilization interval calculate G(Ο„-Δτ,Ο„-Δτ) elseif lβ€² == 1 && N_stab > 1 # perform naive propagation Gβ€²(Ο„-Δτ,Ο„-Δτ) = B⁻¹[l]β‹…G(Ο„,Ο„)β‹…B[l] B_l = B[l]::P mul!(Gβ€², Gττ, B_l, M = ldr_ws.M) # G(Ο„,Ο„)β‹…B[l] ldiv!(B_l, Gβ€², M = ldr_ws.M) # B⁻¹[l]β‹…G(Ο„,Ο„)β‹…B[l] # calucate G(Ο„-Δτ,Ο„-Δτ) = [I + B(Ο„-Δτ,0)β‹…B(Ξ²,Ο„-Δτ)]⁻¹ B_Ξ²_Ο„mΔτ = F[n]::LDR{T,E} B_Ο„mΔτ_0 = F[n-1]::LDR{T,E} logdetG, sgndetG = inv_IpUV!(Gττ, B_Ο„mΔτ_0, B_Ξ²_Ο„mΔτ, ldr_ws) # calculate G(Ο„-Δτ,0) = [B⁻¹(Ο„-Δτ,0) + B(Ξ²,Ο„-Δτ)]⁻¹ inv_invUpV!(GΟ„0, B_Ο„mΔτ_0, B_Ξ²_Ο„mΔτ, ldr_ws) # calculate G(0,Ο„-Δτ) = -[B⁻¹(Ξ²,Ο„-Δτ) + B(Ο„-Δτ,0)]⁻¹ inv_invUpV!(G0Ο„, B_Ξ²_Ο„mΔτ, B_Ο„mΔτ_0, ldr_ws) @. G0Ο„ = -G0Ο„ # record that stabilization was performed stabilized = true end end # calculate error corrected by stabilization if stabilized Ξ”G = Gβ€² @. Ξ”G = abs(Gβ€²-Gττ) Ξ΄G = maximum(real, Ξ”G) δθ = angle(sgndetGβ€²/sgndetG) end return (logdetG, sgndetG, Ξ΄G, δθ) end @doc raw""" local_update_det_ratio( G::AbstractMatrix{T}, B::AbstractPropagator{T}, Vβ€²::T, i::Int, Δτ::E )::Tuple{T,T} where {T,E} Calculate the determinant ratio ``R_{l,i}`` associated with a local update to the equal-time Green's function ``G(\tau,\tau).`` Also returns ``\Delta_{l,i},`` which is defined below. # Arguments - `G::AbstractMatrix{T}`: Equal-time Green's function matrix ``G(\tau,\tau).`` - `B::AbstractPropagator{T,E}`: Represents the propagator matrix ``B_l,`` where ``\tau = \Delta\tau \cdot l.`` - `Vβ€²::T`: The new value for the ``V^{\prime}_{l,i,i}`` matrix element in the diagonal on-site energy matrix ``V_l.`` - `i::Int`: Diagonal matrix element index in ``V_l`` being updated. - `Δτ::E`: Discretization in imaginary time ``\Delta\tau.`` # Algorithm The propagator matrix ``B_l`` above is given by ```math B_l = \Lambda_l \cdot \Gamma_l(\Delta\tau), ``` where, assuming the we are working in the orbital basis, ``\Gamma_l(\Delta\tau) = e^{-\Delta\tau K_l}`` represents the exponentiated hopping matrix ``K_l``, and ``\Lambda_l = e^{-\Delta\tau V_l}`` represents the exponentiated diagonal on-site energy matrix ``V_l.`` Given a proposed update to the ``(i,i)`` matrix element of the diagonal on-site energy matrix ``V_l``, (``V_{l,i,i} \rightarrow V^\prime_{l,i,i}),`` the corresponding determinant ratio associated with this proposed udpate is given by ```math R_{l,i} = \frac{\det G(\tau,\tau)}{\det G^\prime(\tau,\tau)} = 1+\Delta_{i,i}(\tau,i)\left(1-G_{i,i}(\tau,\tau)\right), ``` where ```math \Delta_{l,i} = \frac{\Lambda^\prime_{l,i,i}}{\Lambda_{l,i,i}} - 1 = e^{-\Delta\tau (V^\prime_{l,i,i} - V_{l,i,i})} - 1. ``` This routine returns the scalar quantities ``R_{l,i}`` and ``\Delta_{l,i}.`` Note that if the propagator matrix is instead represented using the symmetric form ```math B_l = \Gamma_l(\Delta\tau/2) \cdot \Lambda_l \cdot \Gamma^\dagger_l(\Delta\tau/2), ``` then the matrix `G` needs to instead represent the transformed equal-time Green's function matrix ```math \tilde{G}(\tau,\tau) = \Gamma_l^{-1}(\Delta\tau/2) \cdot G(\tau,\tau) \cdot \Gamma_l(\Delta\tau/2). ``` """ function local_update_det_ratio( G::AbstractMatrix{T}, B::AbstractPropagator{T}, Vβ€²::T, i::Int, Δτ::E )::Tuple{T,T} where {T,E} Ξ› = B.expmΔτV::Vector{E} Ξ” = exp(-Δτ*Vβ€²)/Ξ›[i] - 1 R = 1 + Ξ”*(1 - G[i,i]) return (R, Ξ”) end @doc raw""" local_update_greens!( G::AbstractMatrix{T}, logdetG::E, sgndetG::T, B::AbstractPropagator{T}, R::T, Ξ”::T, i::Int, u::AbstractVector{T}, v::AbstractVector{T} )::Tuple{E,T} where {T, E<:AbstractFloat} Update the equal-time Green's function matrix `G` resulting from a local update in-place. # Arguments - `G::AbstractMatrix{T}`: Equal-time Green's function matrix ``G(\tau,\tau)`` that will be updated in-place. - `logdetG::E`: The log of the absolute value of the initial Green's function matrix, ``\log( \vert \det G(\tau,\tau) \vert ).`` - `sgndetG::T`: The sign/phase of the determinant of the initial Green's function matrix, ``\textrm{sign}( \det G(\tau,\tau) ).`` - `B::AbstractPropagator{T,E}`: Propagator that needs to be updated to reflect accepted local update. - `R::T`: The determinant ratio ``R_{l,i} = \frac{\det G(\tau,\tau)}{\det G^\prime(\tau,\tau)}.`` - `Ξ”::T`: Change in the exponentiated on-site energy matrix, ``\Delta_{l,i} = e^{-\Delta\tau (V^\prime_{l,(i,i)} - V_{l,(i,i)})} - 1.`` - `i::Int`: Matrix element of diagonal on-site energy matrix ``V_l`` that is being updated. - `u::AbstractVector{T}`: Vector of length `size(G,1)` that is used to avoid dynamic memory allocations. - `v::AbstractVector{T}`: Vector of length `size(G,2)` that is used to avoid dynamic memory allocations. # Algorithm The equal-time Green's function matrix is updated using the relationship ```math G_{j,k}^{\prime}\left(\tau,\tau\right)=G_{j,k}\left(\tau,\tau\right)-\frac{1}{R_{l,i}}G_{j,i}\left(\tau,\tau\right)\Delta_{l,i}\left(\delta_{i,k}-G_{i,k}\left(\tau,\tau\right)\right). ``` The ``B_l`` progpagator `B` is also udpated. Additionally, this method returns ``\log( \vert \det G^\prime(\tau,\tau) \vert )`` and ``\textrm{sign}( \det G^\prime(\tau,\tau) ).`` An important note is that if the propagator matrices are represented in a symmetric form, then `Gβ€²` and `G` need to correspond to the transformed eqaul-time Green's function matrices ``\tilde{G}^\prime(\tau,\tau)`` and ``\tilde{G}(\tau,\tau).`` Refer to the [`local_update_det_ratio`](@ref) docstring for more information. """ function local_update_greens!( G::AbstractMatrix{T}, logdetG::E, sgndetG::T, B::AbstractPropagator{T}, R::T, Ξ”::T, i::Int, u::AbstractVector{T}, v::AbstractVector{T} )::Tuple{E,T} where {T, E<:AbstractFloat} expmΔτV = B.expmΔτV::Vector{E} # u = G[:,i] <== column vector G0i = @view G[:,i] copyto!(u, G0i) # v = G[i,:] - I[i,:] <== row vector Gi0 = @view G[i,:] copyto!(v, Gi0) # v = G[i,:] v[i] = v[i] - 1 # v = G[i,:] - I[i,:] # Gβ€² = G + (Ξ”/R)β‹…[u⨂v] = G + (Ξ”/R)β‹…G[:,i]⨂(G[i,:] - I[i,:]) # where ⨂ denotes an outer product BLAS.ger!(Ξ”/R, u, v, G) # R = det(Mβ€²)/det(M) = det(G)/det(Gβ€²) # ==> log(|R|) = log(|det(Mβ€²)|) - log(|det(M)|) = log(|det(G)|) - log(|det(Gβ€²)|) # ==> log(|det(Gβ€²)|) = log(|det(G)|) - log(|R|) logdetGβ€² = logdetG - log(abs(R)) sgndetGβ€² = sign(R) * sgndetG # update the diagonal exponentiated on-site energy matrix appearing in propagator # (1 + Ξ”[i,l]) Γ— exp(-Δτ⋅V[i,l]) = (1 + [exp(-Δτ⋅Vβ€²[i,l])/exp(-Δτ⋅V[i,l])-1]) Γ— exp(-Δτ⋅V[i,l]) # = exp(-Δτ⋅Vβ€²[i,l])/exp(-Δτ⋅V[i,l]) Γ— exp(-Δτ⋅V[i,l]) # = exp(-Δτ⋅Vβ€²[i,l]) expmΔτV[i] = (1+Ξ”) * expmΔτV[i] return (logdetGβ€², sgndetGβ€²) end
JDQMCFramework
https://github.com/SmoQySuite/JDQMCFramework.jl.git
[ "MIT" ]
1.0.10
d37e67cd855d38efbc41b807f45d758eaaa82923
code
4222
@doc raw""" partially_wrap_greens_forward!( G::Matrix{T}, B::P, M::Matrix{T} = similar(G) ) where {T, E, P<:AbstractPropagator{T,E}} If the propagator `B` is represented in the symmetric form ```math B_l = \Gamma_l(\Delta\tau/2) \cdot \Lambda_l(\Delta\tau) \cdot \Gamma_l^\dagger(\Delta\tau/2) ``` with ``\tau = l \cdot \Delta\tau,`` where ``\Gamma(\Delta\tau/2) = e^{-\Delta\tau K_l/2}`` and ``\Lambda(\Delta\tau) = e^{-\Delta\tau V_l}``, then apply the transformation ```math \tilde{G}(\tau,\tau) = \Gamma^{-1}_l(\Delta\tau/2) \cdot G(\tau,\tau) \cdot \Gamma_l(\Delta\tau/2) ``` to the equal-time Green's function matrix `G` in-place. """ function partially_wrap_greens_forward!( G::Matrix{T}, B::P, M::Matrix{T} = similar(G) ) where {T, E, P<:AbstractPropagator{T,E}} # only apply transformation if symmetric/hermitian definition for propagator is being used _partially_wrap_greens_forward!(G, B, M) return nothing end # perform the GΜƒ(Ο„,Ο„) = Γ⁻¹[l]β‹…G(Ο„,Ο„)β‹…Ξ“[l] transformation in the case the Ξ“[l]=exp(-Δτ⋅K[l]/2) is the exactly exponentiated hopping matrix function _partially_wrap_greens_forward!(G::Matrix{T}, B::SymExactPropagator{T,E}, M::Matrix{T}) where {T,E} (; expmΔτKo2, exppΔτKo2) = B mul!(M, G, expmΔτKo2) # G(Ο„,Ο„)β‹…Ξ“[l] mul!(G, exppΔτKo2, M) # GΜƒ(Ο„,Ο„) = Γ⁻¹[l]β‹…G(Ο„,Ο„)β‹…Ξ“[l] return nothing end # perform the GΜƒ(Ο„,Ο„) = Γ⁻¹[l]β‹…G(Ο„,Ο„)β‹…Ξ“[l] transformation in the case the Ξ“[l] is the checkerboard approximation of exp(-Δτ⋅K[l]/2) function _partially_wrap_greens_forward!(G::Matrix{T}, B::SymChkbrdPropagator{T,E}, ignore...) where {T,E} (; expmΔτKo2) = B rmul!(G, expmΔτKo2) # G(Ο„,Ο„)β‹…Ξ“[l] ldiv!(expmΔτKo2, G) # GΜƒ(Ο„,Ο„) = Γ⁻¹[l]β‹…G(Ο„,Ο„)β‹…Ξ“[l] return nothing end # do nothing for asymmetric propagator function _partially_wrap_greens_forward!(G::Matrix{T}, B::AsymExactPropagator{T,E}, ignore...) where {T,E} return nothing end # do nothing for asymmetric propagator function _partially_wrap_greens_forward!(G::Matrix{T}, B::AsymChkbrdPropagator{T,E}, ignore...) where {T,E} return nothing end @doc raw""" partially_wrap_greens_reverse!( G::Matrix{T}, B::P, M::Matrix{T} = similar(G) ) where {T, E, P<:AbstractPropagator{T,E}} If the propagator `B` is represented in the symmetric form ```math B_l = \Gamma_l(\Delta\tau/2) \cdot \Lambda_l(\Delta\tau) \cdot \Gamma_l^\dagger(\Delta\tau/2) ``` with ``\tau = l \cdot \Delta\tau,`` where ``\Gamma(\Delta\tau/2) = e^{-\Delta\tau K_l/2}`` and ``\Lambda(\Delta\tau) = e^{-\Delta\tau V_l}``, then apply the transformation ```math G(\tau,\tau) = \Gamma_l(\Delta\tau/2) \cdot \tilde{G}(\tau,\tau) \cdot \Gamma_l^{-1}(\Delta\tau/2) ``` to the equal-time Green's function matrix `G` in-place. """ function partially_wrap_greens_reverse!( G::Matrix{T}, B::P, M::Matrix{T} = similar(G) ) where {T, E, P<:AbstractPropagator{T,E}} # only apply transformation if symmetric/hermitian definition for propagator is being used _partially_wrap_greens_reverse!(G, B, M) return nothing end # perform the G(Ο„,Ο„) = Ξ“[l]β‹…GΜƒ(Ο„,Ο„)⋅Γ⁻¹[l] transformation in the case the Ξ“[l]=exp(-Δτ⋅K[l]/2) is the exactly exponentiated hopping matrix function _partially_wrap_greens_reverse!(G::Matrix{T}, B::SymExactPropagator{T,E}, M::Matrix{T}) where {T,E} (; expmΔτKo2, exppΔτKo2) = B mul!(M, G, exppΔτKo2) # GΜƒ(Ο„,Ο„)⋅Γ⁻¹[l] mul!(G, expmΔτKo2, M) # G(Ο„,Ο„) = Ξ“[l]β‹…GΜƒ(Ο„,Ο„)⋅Γ⁻¹[l] return nothing end # perform the G(Ο„,Ο„) = Ξ“[l]β‹…GΜƒ(Ο„,Ο„)⋅Γ⁻¹[l] transformation in the case the Ξ“[l] is the checkerboard approximation of exp(-Δτ⋅K[l]/2) function _partially_wrap_greens_reverse!(G::Matrix{T}, B::SymChkbrdPropagator{T,E}, ignore...) where {T,E} (; expmΔτKo2) = B rdiv!(G, expmΔτKo2) # GΜƒ(Ο„,Ο„)⋅Γ⁻¹[l] lmul!(expmΔτKo2, G) # G(Ο„,Ο„) = Ξ“[l]β‹…GΜƒ(Ο„,Ο„)⋅Γ⁻¹[l] return nothing end # do nothing for asymmetric propagator function _partially_wrap_greens_reverse!(G::Matrix{T}, B::AsymExactPropagator{T,E}, ignore...) where {T,E} return nothing end # do nothing for asymmetric propagator function _partially_wrap_greens_reverse!(G::Matrix{T}, B::AsymChkbrdPropagator{T,E}, ignore...) where {T,E} return nothing end
JDQMCFramework
https://github.com/SmoQySuite/JDQMCFramework.jl.git
[ "MIT" ]
1.0.10
d37e67cd855d38efbc41b807f45d758eaaa82923
code
4042
@doc raw""" eval_length_imaginary_axis( Ξ²::T, Δτ::T )::Int where {T<:AbstractFloat} Given an inverse temperature `Ξ²` and discretization in imaginary time `Δτ`, return the length of the imaginary time axis `LΟ„`. """ function eval_length_imaginary_axis( Ξ²::T, Δτ::T )::Int where {T<:AbstractFloat} LΟ„ = round(Int, Ξ²/Δτ) @assert (LΟ„*Δτ)β‰ˆΞ² return LΟ„ end @doc raw""" exp!( expΞ±H::AbstractMatrix{T}, H::AbstractMatrix{T}, Ξ±::E; # KEYWORD ARGUMENTS workspace::HermitianEigenWs{T,Matrix{T},R} = HermitianEigenWs(H), tol::R = 1e-6 ) where {T<:Number, E<:Number, R<:AbstractFloat} Given a Hermitian matrix `H`, calculate the matrix exponentials ``e^{\alpha H}.`` Note that `H` is left modified by this method. The `workspace` field is of type [`HermitianEigenWs`](https://dynarejulia.github.io/FastLapackInterface.jl/dev/workspaces/#FastLapackInterface.HermitianEigenWs), which is exported from the [`FastLapackInterface.jl`](https://github.com/DynareJulia/FastLapackInterface.jl) package, is used to avoid dynamic memory allocations. """ function exp!( expΞ±H::AbstractMatrix{T}, H::AbstractMatrix{T}, Ξ±::E; # KEYWORD ARGUMENTS workspace::HermitianEigenWs{T,Matrix{T},R} = HermitianEigenWs(H), tol::R = 1e-6 ) where {T<:Number, E<:Number, R<:AbstractFloat} # diagonalize the matrix such that H = Uβ‹…Ο΅β‹…Uα΅€ LAPACK.syevr!(workspace, 'V', 'A', 'U', H, 0.0, 0.0, 0, 0, tol) U = workspace.Z Ο΅ = workspace.w Uα΅€ = adjoint(U) # calculate the matrix product exp(Ξ±β‹…H) = Uβ‹…exp(Ξ±β‹…Ο΅)β‹…Uα΅€ @. Ο΅ = exp(Ξ±*Ο΅) mul_D!(H, Ο΅, Uα΅€) mul!(expΞ±H, U, H) return nothing end @doc raw""" exp!( exppΞ±H::AbstractMatrix{T}, expmΞ±H::AbstractMatrix{T}, H::AbstractMatrix{T}, Ξ±::E; # KEYWORD ARGUMENTS workspace::HermitianEigenWs{T,Matrix{T},R} = HermitianEigenWs(H), tol::R = 1e-6 ) where {T<:Number, E<:Number, R<:AbstractFloat} Given a Hermitian matrix `H`, calculate the matrix exponentials ``e^{+\alpha H}`` and ``e^{-\alpha H}``, which are written to `exppΞ±H` and `expmΞ±H` respectively. Note that `H` is left modified by this method. The `workspace` field is of type [`HermitianEigenWs`](https://dynarejulia.github.io/FastLapackInterface.jl/dev/workspaces/#FastLapackInterface.HermitianEigenWs), which is exported from the [`FastLapackInterface.jl`](https://github.com/DynareJulia/FastLapackInterface.jl) package, is used to avoid dynamic memory allocations. """ function exp!( exppΞ±H::AbstractMatrix{T}, expmΞ±H::AbstractMatrix{T}, H::AbstractMatrix{T}, Ξ±::E; # KEYWORD ARGUMENTS workspace::HermitianEigenWs{T,Matrix{T},R} = HermitianEigenWs(H), tol::R = 1e-6 ) where {T<:Number, E<:Number, R<:AbstractFloat} # diagonalize the matrix such that H = Uβ‹…Ο΅β‹…Uα΅€ LAPACK.syevr!(workspace, 'V', 'A', 'U', H, 0.0, 0.0, 0, 0, tol) U = workspace.Z Ο΅ = workspace.w Uα΅€ = adjoint(U) # calculate the matrix product exp(Ξ±β‹…H) = Uβ‹…exp(Ξ±β‹…Ο΅)β‹…Uα΅€ @. Ο΅ = exp(Ξ±*Ο΅) mul_D!(H, Ο΅, Uα΅€) mul!(exppΞ±H, U, H) # calculate the matrix product exp(-Ξ±β‹…H) = Uβ‹…exp(-Ξ±β‹…Ο΅)β‹…Uα΅€ div_D!(H, Ο΅, Uα΅€) mul!(expmΞ±H, U, H) return nothing end @doc raw""" build_hopping_matrix!( K::AbstractMatrix{T}, neighbor_table::Matrix{Int}, t::AbstractVector{T} ) where {T<:Continuous} Construct a hopping matrix `K` using `neighbor_table` along with the corresponding hopping amplitudes `t`. Each column of `neighbor_table` stores a pair of neighboring orbitals in the lattice, such that `size(neighbor_table,1) = 2`. """ function build_hopping_matrix!( K::AbstractMatrix{T}, neighbor_table::Matrix{Int}, t::AbstractVector{T} ) where {T<:Continuous} fill!(K, 0) @fastmath @inbounds for n in axes(neighbor_table,2) i = neighbor_table[1,n] j = neighbor_table[2,n] K[j,i] = -t[n] K[i,j] = conj(-t[n]) end return nothing end
JDQMCFramework
https://github.com/SmoQySuite/JDQMCFramework.jl.git
[ "MIT" ]
1.0.10
d37e67cd855d38efbc41b807f45d758eaaa82923
code
10254
using JDQMCFramework using Test using LinearAlgebra using LatticeUtilities # fermi function function fermi(Ο΅, Ξ²) return (1-tanh(Ξ²/2*Ο΅))/2 end # calculate exact analytic value for the retarded imaginary Green's function function retarded_greens(Ο„,Ξ²,Ο΅,U) gΟ„ = similar(Ο΅) @. gΟ„ = inv(exp(Ο„*Ο΅) + exp((Ο„-Ξ²)*Ο΅)) GΟ„ = U * Diagonal(gΟ„) * adjoint(U) logdetGΟ„, sgndetGΟ„ = logabsdet(Diagonal(gΟ„)) return GΟ„, logdetGΟ„, sgndetGΟ„ end # calculate exact analytic value for the advanced imaginary Green's function function advanced_greens(Ο„,Ξ²,Ο΅,U) gΟ„ = similar(Ο΅) @. gΟ„ = -inv(exp(-Ο„*Ο΅) + exp(-(Ο„-Ξ²)*Ο΅)) GΟ„ = U * Diagonal(gΟ„) * adjoint(U) logdetGΟ„, sgndetGΟ„ = logabsdet(Diagonal(gΟ„)) return GΟ„, logdetGΟ„, sgndetGΟ„ end @testset "JDQMCFramework.jl" begin # model parameters t = 1.0 # hopping amplitude ΞΌ = 0.0 # chemical potential L = 4 # lattice size Ξ² = 3.7 # inverse temperature Δτ = 0.1 # discretization in imaginary time n_stab = 10 # frequency of numerical stabilization # calculate length of imagninary time axis LΟ„ = eval_length_imaginary_axis(Ξ²,Δτ) # construct neighbor table for square lattice unit_cell = UnitCell(lattice_vecs = [[1.,0.],[0.,1.]], basis_vecs = [[0.,0.]]) lattice = Lattice(L = [L,L], periodic = [true,true]) bond_x = Bond(orbitals = (1,1), displacement = [1,0]) bond_y = Bond(orbitals = (1,1), displacement = [0,1]) neighbor_table = build_neighbor_table([bond_x, bond_y], unit_cell, lattice) # calculate number of sites in lattice N = nsites(unit_cell, lattice) # calculate number of bonds in lattice Nbonds = size(neighbor_table, 2) # build hopping matrix K = zeros(typeof(t), N, N) build_hopping_matrix!(K, neighbor_table, fill(t, Nbonds)) # build diagonal on-site energy matrix V = fill(-ΞΌ, N) # construct Hamiltonian matrix H = K + Diagonal(V) Ο΅, U = eigen(H) # calculate exact unequal time Green's function G_ret = zeros(typeof(t), N, N, LΟ„+1) G_adv = zeros(typeof(t), N, N, LΟ„+1) for l in 0:LΟ„ G_ret[:,:,l+1] = retarded_greens(Δτ*l, Ξ², Ο΅, U)[1] G_adv[:,:,l+1] = advanced_greens(Δτ*l, Ξ², Ο΅, U)[1] end # calculate equal-time Green's function matrix G, logdetG, sgndetG = retarded_greens(0, Ξ², Ο΅, U) # define vector of propagators expmΔτV = exp.(-Δτ*V) expmΔτK = exp(-Δτ*K) exppΔτK = exp(+Δτ*K) Bup = AsymExactPropagator{eltype(expmΔτK),eltype(expmΔτV)}[]; # spin up propagators Bdn = AsymExactPropagator{eltype(expmΔτK),eltype(expmΔτV)}[]; # spin down propagators for l in 1:LΟ„ B_l = AsymExactPropagator(expmΔτV, expmΔτK, exppΔτK) push!(Bup, B_l) push!(Bdn, B_l) end @test eltype(Bup[1]) == eltype(expmΔτK) # initiate FermionGreensCalculator struct fgc_up = FermionGreensCalculator(Bup, Ξ², Δτ, n_stab+1) fgc_dn = FermionGreensCalculator(Bdn, Ξ², Δτ, n_stab+1) # calculate equal-time Green's function Gup = zeros(typeof(t), N, N) Gdn = zeros(typeof(t), N, N) logdetGup, sgndetGup = calculate_equaltime_greens!(Gup, fgc_up) logdetGdn, sgndetGdn = calculate_equaltime_greens!(Gdn, fgc_dn) # test that spin up equal-time Green's function is correct @test G β‰ˆ Gup @test logdetG β‰ˆ logdetGup @test sgndetG β‰ˆ sgndetGup # test that spin down equal-time Green's function is correct @test G β‰ˆ Gdn @test logdetG β‰ˆ logdetGdn @test sgndetG β‰ˆ sgndetGdn # initialize copy FermionGreensCalculator fgc = FermionGreensCalculator(fgc_up) @test typeof(fgc) <: FermionGreensCalculator # copy FermionGreensCalculator copyto!(fgc, fgc_dn) @test typeof(fgc) <: FermionGreensCalculator # resize FermionGreensCalculator struct logdetGup, sgndetGup = resize!(fgc_up, Gup, logdetGup, sgndetGup, Bup, n_stab) logdetGdn, sgnderGdn = resize!(fgc_dn, Gdn, logdetGdn, sgndetGdn, Bdn, n_stab) @test fgc_up.n_stab == n_stab @test fgc_dn.n_stab == n_stab @test logdetG β‰ˆ logdetGup @test sgndetG β‰ˆ sgndetGup @test logdetG β‰ˆ logdetGdn @test sgndetG β‰ˆ sgndetGdn # copy FermionGreensCalculator with resizing copyto!(fgc, fgc_up) @test fgc.n_stab == n_stab # Iterate over imaginary time Ο„=Δτ⋅l. @testset for l in fgc_up # Propagate Green's function matrix to current imaginary time G(l,l). propagate_equaltime_greens!(Gup, fgc_up, Bup) propagate_equaltime_greens!(Gdn, fgc_dn, Bdn) # LOCAL UPDATES OR EVALUATION OF DERIVATIVE OF FERMIONIC ACTION WOULD GO HERE # test that spin up equal-time Green's function is correct @test G β‰ˆ Gup @test logdetG β‰ˆ logdetGup @test sgndetG β‰ˆ sgndetGup # test that spin down equal-time Green's function is correct @test G β‰ˆ Gdn @test logdetG β‰ˆ logdetGdn @test sgndetG β‰ˆ sgndetGdn # Periodically re-calculate the Green's function matrix for numerical stability. # If not performing updates, but just evaluating the derivative of the action, then # set update_BΜ„=false to avoid wasting cpu time re-computing B_barβ‚™ matrices. logdetGup, sgndetGup, Ξ΄Gup, δθup = stabilize_equaltime_greens!(Gup, logdetGup, sgndetGup, fgc_up, Bup, update_BΜ„=true) logdetGdn, sgndetGdn, Ξ΄Gdn, δθdn = stabilize_equaltime_greens!(Gdn, logdetGdn, sgndetGdn, fgc_dn, Bdn, update_BΜ„=true) # Keep up and down spin Green's functions synchronized as iterating over imaginary time. iterate(fgc_dn, fgc_up.forward) end # Iterate over imaginary time Ο„=Δτ⋅l. @testset for l in fgc_up # Propagate Green's function matrix to current imaginary time G(l,l). propagate_equaltime_greens!(Gup, fgc_up, Bup) propagate_equaltime_greens!(Gdn, fgc_dn, Bdn) # LOCAL UPDATES OR EVALUATION OF DERIVATIVE OF FERMIONIC ACTION WOULD GO HERE # test that spin up equal-time Green's function is correct @test G β‰ˆ Gup @test logdetG β‰ˆ logdetGup @test sgndetG β‰ˆ sgndetGup # test that spin down equal-time Green's function is correct @test G β‰ˆ Gdn @test logdetG β‰ˆ logdetGdn @test sgndetG β‰ˆ sgndetGdn # Periodically re-calculate the Green's function matrix for numerical stability. # If not performing updates, but just evaluating the derivative of the action, then # set update_BΜ„=false to avoid wasting cpu time re-computing B_barβ‚™ matrices. logdetGup, sgndetGup, Ξ΄Gup, δθup = stabilize_equaltime_greens!(Gup, logdetGup, sgndetGup, fgc_up, Bup, update_BΜ„=false) logdetGdn, sgndetGdn, Ξ΄Gdn, δθdn = stabilize_equaltime_greens!(Gdn, logdetGdn, sgndetGdn, fgc_dn, Bdn, update_BΜ„=false) # Keep up and down spin Green's functions synchronized as iterating over imaginary time. iterate(fgc_dn, fgc_up.forward) end # initialize unequal-time Green's functions Gup_Ο„0 = similar(Gdn) Gup_0Ο„ = similar(Gdn) Gup_ττ = similar(Gdn) Gdn_Ο„0 = similar(Gdn) Gdn_0Ο„ = similar(Gdn) Gdn_ττ = similar(Gdn) initialize_unequaltime_greens!(Gup_Ο„0, Gup_0Ο„, Gup_ττ, Gup) initialize_unequaltime_greens!(Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, Gdn) # Iterate over imaginary time Ο„=Δτ⋅l. @testset for l in fgc_up # Propagate Green's function matrix to current imaginary time G(l,l). propagate_unequaltime_greens!(Gup_Ο„0, Gup_0Ο„, Gup_ττ, fgc_up, Bup) propagate_unequaltime_greens!(Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, fgc_dn, Bdn) # LOCAL UPDATES OR EVALUATION OF DERIVATIVE OF FERMIONIC ACTION WOULD GO HERE # test that spin up unequal-time Green's function is correct G_Ο„0 = @view G_ret[:,:,l+1] G_0Ο„ = @view G_adv[:,:,l+1] @test G β‰ˆ Gup_ττ @test G_Ο„0 β‰ˆ Gup_Ο„0 @test G_0Ο„ β‰ˆ Gup_0Ο„ @test G β‰ˆ Gdn_ττ @test G_Ο„0 β‰ˆ Gdn_Ο„0 @test G_0Ο„ β‰ˆ Gdn_0Ο„ # Periodically re-calculate the Green's function matrix for numerical stability. # If not performing updates, but just evaluating the derivative of the action, then # set update_BΜ„=false to avoid wasting cpu time re-computing B_barβ‚™ matrices. logdetGup, sgndetGup, Ξ΄Gup, δθup = stabilize_unequaltime_greens!(Gup_Ο„0, Gup_0Ο„, Gup_ττ, logdetGup, sgndetGup, fgc_up, Bup, update_BΜ„=false) logdetGdn, sgndetGdn, Ξ΄Gdn, δθdn = stabilize_unequaltime_greens!(Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, logdetGdn, sgndetGdn, fgc_dn, Bdn, update_BΜ„=false) # Keep up and down spin Green's functions synchronized as iterating over imaginary time. iterate(fgc_dn, fgc_up.forward) end # initialize unequal-time Green's functions initialize_unequaltime_greens!(Gup_Ο„0, Gup_0Ο„, Gup_ττ, Gup) initialize_unequaltime_greens!(Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, Gdn) # Iterate over imaginary time Ο„=Δτ⋅l. @testset for l in fgc_up # Propagate Green's function matrix to current imaginary time G(l,l). propagate_unequaltime_greens!(Gup_Ο„0, Gup_0Ο„, Gup_ττ, fgc_up, Bup) propagate_unequaltime_greens!(Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, fgc_dn, Bdn) # LOCAL UPDATES OR EVALUATION OF DERIVATIVE OF FERMIONIC ACTION WOULD GO HERE # test that spin up unequal-time Green's function is correct G_Ο„0 = @view G_ret[:,:,l+1] G_0Ο„ = @view G_adv[:,:,l+1] @test G β‰ˆ Gup_ττ @test G_Ο„0 β‰ˆ Gup_Ο„0 @test G_0Ο„ β‰ˆ Gup_0Ο„ @test G β‰ˆ Gdn_ττ @test G_Ο„0 β‰ˆ Gdn_Ο„0 @test G_0Ο„ β‰ˆ Gdn_0Ο„ # Periodically re-calculate the Green's function matrix for numerical stability. # If not performing updates, but just evaluating the derivative of the action, then # set update_BΜ„=false to avoid wasting cpu time re-computing B_barβ‚™ matrices. logdetGup, sgndetGup, Ξ΄Gup, δθup = stabilize_unequaltime_greens!(Gup_Ο„0, Gup_0Ο„, Gup_ττ, logdetGup, sgndetGup, fgc_up, Bup, update_BΜ„=true) logdetGdn, sgndetGdn, Ξ΄Gdn, δθdn = stabilize_unequaltime_greens!(Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, logdetGdn, sgndetGdn, fgc_dn, Bdn, update_BΜ„=true) # Keep up and down spin Green's functions synchronized as iterating over imaginary time. iterate(fgc_dn, fgc_up.forward) end end
JDQMCFramework
https://github.com/SmoQySuite/JDQMCFramework.jl.git
[ "MIT" ]
1.0.10
d37e67cd855d38efbc41b807f45d758eaaa82923
docs
2178
# JDQMCFramework.jl [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://SmoQySuite.github.io/JDQMCFramework.jl/stable/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://SmoQySuite.github.io/JDQMCFramework.jl/dev/) [![Build Status](https://github.com/SmoQySuite/JDQMCFramework.jl/actions/workflows/CI.yml/badge.svg?branch=master)](https://github.com/SmoQySuite/JDQMCFramework.jl/actions/workflows/CI.yml?query=branch%3Amaster) [![Coverage](https://codecov.io/gh/SmoQySuite/JDQMCFramework.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/SmoQySuite/JDQMCFramework.jl) This package exports a suite of types and routines that significantly simplify the process of writing a determinant quantum Monte Carlo (DQMC) code. ## Funding The development of this code was supported by the U.S. Department of Energy, Office of Science, Basic Energy Sciences, under Award Number DE-SC0022311. ## Installation To install [`JDQMCFramework.jl`](https://github.com/SmoQySuite/JDQMCFramework.jl.git), simply open the Julia REPL and run the commands ```julia julia> ] pkg> add JDQMCFramework ``` or equivalently via `Pkg` do ```julia julia> using Pkg; Pkg.add("JDQMCFramework") ``` ## Documentation - [STABLE](https://SmoQySuite.github.io/JDQMCFramework.jl/stable/): Documentation for the latest version of the code published to the Julia [`General`](https://github.com/JuliaRegistries/General.git) registry. - [DEV](https://SmoQySuite.github.io/JDQMCFramework.jl/dev/): Documentation for the latest commit to the `master` branch. ## Citation If you found this library to be useful in the course of academic work, please consider citing us: ```bibtex @misc{SmoQyDQMC, title={SmoQyDQMC.jl: A flexible implementation of determinant quantum Monte Carlo for Hubbard and electron-phonon interactions}, author={Benjamin Cohen-Stead and Sohan Malkaruge Costa and James Neuhaus and Andy Tanjaroon Ly and Yutan Zhang and Richard Scalettar and Kipton Barros and Steven Johnston}, year={2023}, eprint={2311.09395}, archivePrefix={arXiv}, primaryClass={cond-mat.str-el}, url={https://arxiv.org/abs/2311.09395} } ```
JDQMCFramework
https://github.com/SmoQySuite/JDQMCFramework.jl.git
[ "MIT" ]
1.0.10
d37e67cd855d38efbc41b807f45d758eaaa82923
docs
2516
# API ## Propagator Types - [`AbstractPropagator`](@ref) - [`AbstractExactPropagator`](@ref) - [`AbstractChkbrdPropagator`](@ref) - [`SymExactPropagator`](@ref) - [`AsymExactPropagator`](@ref) - [`SymChkbrdPropagator`](@ref) - [`AsymChkbrdPropagator`](@ref) - [`SymPropagators`](@ref) ```@docs AbstractPropagator AbstractExactPropagator AbstractChkbrdPropagator SymExactPropagator AsymExactPropagator SymChkbrdPropagator AsymChkbrdPropagator SymPropagators ``` ## FermionGreensCalculator Type - [`FermionGreensCalculator`](@ref) ```@docs FermionGreensCalculator FermionGreensCalculator(::AbstractVector{P}, ::E, ::E, ::Int) where {T<:Number, E<:AbstractFloat, P<:AbstractPropagator{T}} FermionGreensCalculator(::FermionGreensCalculator{T,E}) where {T,E} ``` ## DQMC Building Block Routines - [`calculate_equaltime_greens!`](@ref) - [`propagate_equaltime_greens!`](@ref) - [`stabilize_equaltime_greens!`](@ref) - [`initialize_unequaltime_greens!`](@ref) - [`propagate_unequaltime_greens!`](@ref) - [`stabilize_unequaltime_greens!`](@ref) - [`local_update_det_ratio`](@ref) - [`local_update_greens!`](@ref) - [`partially_wrap_greens_forward!`](@ref) - [`partially_wrap_greens_reverse!`](@ref) ```@docs calculate_equaltime_greens! propagate_equaltime_greens! stabilize_equaltime_greens! initialize_unequaltime_greens! propagate_unequaltime_greens! stabilize_unequaltime_greens! local_update_det_ratio local_update_greens! partially_wrap_greens_forward! partially_wrap_greens_reverse! ``` ## Overloaded Functions - [`iterate`](@ref) - [`eltype`](@ref) - [`resize!`](@ref) - [`size`](@ref) - [`copyto!`](@ref) - [`ishermitian`](@ref) - [`mul!`](@ref) - [`lmul!`](@ref) - [`rmul!`](@ref) - [`ldiv!`](@ref) - [`rdiv!`](@ref) ```@docs Base.iterate Base.eltype Base.resize! Base.size Base.copyto! LinearAlgebra.ishermitian LinearAlgebra.mul! LinearAlgebra.lmul! LinearAlgebra.rmul! LinearAlgebra.ldiv! LinearAlgebra.rdiv! ``` ## Utility Functions - [`eval_length_imaginary_axis`](@ref) - [`exp!`](@ref) - [`build_hopping_matrix!`](@ref) ```@docs eval_length_imaginary_axis exp! build_hopping_matrix! ``` ## Developer API - [`JDQMCFramework.Continuous`](@ref) - [`JDQMCFramework.update_factorizations!`](@ref) - [`JDQMCFramework.update_BΜ„!`](@ref) - [`JDQMCFramework.calculate_BΜ„!`](@ref) - [`JDQMCFramework.stabilization_interval`](@ref) ```@docs JDQMCFramework.Continuous JDQMCFramework.update_factorizations! JDQMCFramework.update_BΜ„! JDQMCFramework.calculate_BΜ„! JDQMCFramework.stabilization_interval ```
JDQMCFramework
https://github.com/SmoQySuite/JDQMCFramework.jl.git
[ "MIT" ]
1.0.10
d37e67cd855d38efbc41b807f45d758eaaa82923
docs
14640
```@meta CurrentModule = JDQMCFramework ``` # JDQMCFramework.jl Documentation for [JDQMCFramework](https://github.com/cohensbw/JDQMCFramework.jl). This is a utility package that exports a suite of types and routines to simplify the process of writing a DQMC code. Matrix stabilization routines are supplied by the [`StableLinearAlgebra.jl`](https://github.com/cohensbw/StableLinearAlgebra.jl.git) package. The checkerboard decomposition functionality supported here is provided by the [`Checkerboard.jl`](https://github.com/cohensbw/Checkerboard.jl.git) package. ## Funding The development of this code was supported by the U.S. Department of Energy, Office of Science, Basic Energy Sciences, under Award Number DE-SC0022311. ## Installation To install [`JDQMCFramework.jl`](https://github.com/SmoQySuite/JDQMCFramework.jl.git), simply open the Julia REPL and run the commands ```julia julia> ] pkg> add JDQMCFramework ``` or equivalently via `Pkg` do ```julia julia> using Pkg; Pkg.add("JDQMCFramework") ``` ## Citation If you found this library to be useful in the course of academic work, please consider citing us: ```bibtex @misc{SmoQyDQMC, title={SmoQyDQMC.jl: A flexible implementation of determinant quantum Monte Carlo for Hubbard and electron-phonon interactions}, author={Benjamin Cohen-Stead and Sohan Malkaruge Costa and James Neuhaus and Andy Tanjaroon Ly and Yutan Zhang and Richard Scalettar and Kipton Barros and Steven Johnston}, year={2023}, eprint={2311.09395}, archivePrefix={arXiv}, primaryClass={cond-mat.str-el}, url={https://arxiv.org/abs/2311.09395} } ``` ## Formalism and Definitions This section describes the formalism and definitions adopted by the JDQMCFramework package. The following discussion assumes an existing familiarity with the determinant quantum Monte Carlo (DQMC) algorithm, a method for simulating systems of itinerant fermions on a lattice at finite temperature in the grand canonical ensemble. The DQMC formalism starts by representing the partition funciton as a path integral ```math \begin{align*} Z= & \textrm{Tr}\,e^{-\beta\hat{H}}=\textrm{Tr}\left[\prod_{l=1}^{L_{\tau}}e^{-\Delta\tau\hat{H}}\right] \end{align*} ``` in imaginary time ``\tau=l\cdot\Delta\tau``, at inverse temperature ``\beta=L_{\tau}\cdot\Delta\tau``. Next, the Suzuki-Trotter approximation is applied, and Hubbard-Stratonivich transformations are used as needed to render the Hamiltonian quadratic in fermion creation and annihilation operators. Lastly, the fermionic degrees of freedom are integrated out. The resulting approximate expression for the partition function allows for the definition of Monte Carlo weights of the form ```math W(\mathbf{x})=e^{-S_{B}}\prod_{\sigma}\det M_{\sigma}, ``` where ``\mathbf{x}`` signifies all the relevant degrees of freedom that need to be sampled. While not written explicitly, the bosonic action ``S_{B}`` and each fermion determinant matrix ``M_{\sigma}`` depend on ``\mathbf{x}``. In the absence of a mean field pairing term or some similarly exotic interaction, the index ``\sigma`` typically corresponds to the fermion spin species. In the case of electrons this means ``\sigma=\{\uparrow,\downarrow\}``. Each fermion determinant matrix is of the form ```math \begin{align*} M_{\sigma}(\tau)= & I+B_{\sigma}(\tau,0)B_{\sigma}(\beta,\tau)\\ = & I+B_{\sigma,l}B_{\sigma,l-1}\dots B_{\sigma,1}B_{\sigma,L_{\tau}}\dots B_{\sigma,l+2}B_{\sigma,l+1} \end{align*} ``` where ```math B_{\sigma}(\tau,\tau')=B_{\sigma,l}B_{\sigma,l-1}\dots B_{\sigma,l'+1} ``` such that ``\det M_{\sigma}(\tau)=\det M_{\sigma}(\tau')`` for any pair ``(l,l')\in[1,L_{\tau}]``. Each propagator matrix ``B_{\sigma,l}=B_{\sigma}(\tau,\tau-\Delta\tau)`` may be represented in either the symmetric form ```math B_{\sigma,l}=e^{-\tfrac{\Delta\tau}{2}K_{l}} e^{-\Delta\tau V_{l}} e^{-\tfrac{\Delta\tau}{2}K_{l}} ``` or the asymmetric form ```math B_{\sigma,l} = e^{-\Delta\tau V_{l}} e^{-\Delta\tau K_{l}}, ``` where ``V_{l}`` is a diagonal matrix corresponding to the on-site energy for each site in the lattice, and ``K_{l}`` is the strictly off-diagonal hopping matrix. The single-particle fermion Green's function is given by ```math G_{\sigma,i,j}(\tau,\tau')=\langle\hat{\mathcal{T}}\hat{c}_{\sigma,i}(\tau)\hat{c}_{\sigma,j}^{\dagger}(\tau')\rangle=\begin{cases} \langle\hat{c}_{\sigma,i}(\tau)\hat{c}_{\sigma,j}^{\dagger}(\tau')\rangle & \tau\ge\tau'\\ -\langle\hat{c}_{\sigma,j}^{\dagger}(\tau')\hat{c}_{\sigma,i}(\tau)\rangle & \tau<\tau', \end{cases} ``` where ``\hat{c}_{\sigma,i}^{\dagger}\,(\hat{c}_{\sigma,i})`` is the fermion creation (annihilation) operator for a fermion with spin ``\sigma`` on site ``i`` on the lattice, and ``\hat{\mathcal{T}}`` is the time-ordering operator. The equal-time Green's function is related to the fermion determinant matrix by ```math G_{\sigma,i,j}(\tau,\tau)=M_{\sigma,i,j}^{-1}(\tau), ``` where again ``\tau=l\cdot\Delta\tau``. The equal-time Green's function matrix can be advanced to the next imaginary time slice using the relationship ```math G_{\sigma}(\tau+\Delta\tau,\tau+\Delta\tau)=B_{\sigma,l+1}G_{\sigma}(\tau,\tau)B_{\sigma,l+1}^{-1} ``` and ```math G_{\sigma}(\tau-\Delta\tau,\tau-\Delta\tau)=B_{\sigma,l}^{-1}G_{\sigma}(\tau,\tau)B_{\sigma,l}. ``` The unequal-time Green's function is accessible using the relations ```math \begin{align*} G_{\sigma}(\tau,0) = & B_{\sigma}(\tau,0)G_{\sigma}(0,0)\\ = & [B_{\sigma}^{-1}(\tau,0) + B_{\sigma}(\beta,\tau)]^{-1}, \end{align*} ``` and ```math \begin{align*} G_{\sigma}(0,\tau) = & -[I-G_{\sigma}(0,0)] B_{\sigma}^{-1}(\tau,0) \\ = & -[B_{\sigma}^{-1}(\beta,\tau) + B_{\sigma}(\tau,0)]^{-1}, \end{align*} ``` where the second relationship may be shown by applying the Woodbury matrix identity. These relationships also imply ```math G_{\sigma}(\tau,0) = B_{\sigma}^{-1}(\tau',\tau)G_{\sigma}(\tau',0) ``` and ```math G_{\sigma}(0,\tau) = G_{\sigma}(0,\tau') B_{\sigma}(\tau',\tau), ``` for ``\tau\in[0,\beta-\Delta\tau]`` and ``\tau<\tau'<\beta``. By applying the anti-periodic boundary conditions of the single-particle Green's function in imaginary time it immediately follows that ```math G_{\sigma}(\beta,0) = I-G_{\sigma}(0,0) ``` and ```math G_\sigma(0,\beta) = -G_{\sigma}(0,0), ``` where ```math G_{\sigma}(0,0)=[I+B_{\sigma}(\beta,0)]^{-1}=[I+B_{\sigma,L_{\tau}}\dots B_{\sigma,1}]^{-1}, ``` subject to the boundary condition ``G_{\sigma}(0,0)=G_{\sigma}(\beta,\beta)``. The DQMC method also requires periodic re-calculation of the fermion Green's function matrix as ``G_{\sigma}(\tau,\tau)`` is propagated to later or ealier imaginary times to maintain numerical stability. Therefore, we introduce a parameter ``n_{s},`` which describes the frequency with which numerical stabilization needs to occur. The number of "stabilization intervals" in imaginary time is then given by ``N_{s}=\left\lceil L_{\tau}/n_{s}\right \rceil``, and we introduce the notation ```math \bar{B}_{\sigma,n}=\prod_{l=(n-1)\cdot n_{s}+1}^{\min(n\cdot n_{s},N_{s})}B_{\sigma,l}, ``` where ``n\in[1,N_{s}]``, to represent the product of propagator matrices over a single stabilization interval. Using this definition we may express ``G_{\sigma}(0,0)`` as ```math G_{\sigma}(0,0) = (I + B_{\sigma,L_\tau} B_{\sigma,L_\tau-1} \dots B_{\sigma, 2} B_{\sigma,1})^{-1} = (I + \bar{B}_{\sigma,N_s} \bar{B}_{\sigma,N_s-1} \dots \bar{B}_{\sigma, 2} \bar{B}_{\sigma,1})^{-1}. ``` ## Basic Usage In this section we introduce some of the basics of using this package by setting up the framework for a DQMC simulations in the case of a simple non-interacting square lattice tight binding model, assuming two electron spin species, spin up and spin down. While this is a "tivial" example, it is instructive. ```@example square using LinearAlgebra using LatticeUtilities using JDQMCFramework ``` First let us define the relevant model parameters. ```@example square # hopping amplitude t = 1.0 # chemical potential ΞΌ = 0.0 # lattice size L = 4 # inverse temperature Ξ² = 3.7 # discretization in imaginary time Δτ = 0.1 # frequency of numerical stabilization n_stab = 10 nothing; # hide ``` Next we calculate the length of the imaginary time axis ``L_\tau`` using the [`eval_length_imaginary_axis`](@ref) method. ```@example square LΟ„ = eval_length_imaginary_axis(Ξ², Δτ) ``` Using functionality imported from the [`LatticeUtilities.jl`](https://github.com/cohensbw/LatticeUtilities.jl.git) package, we construct the neighbor table for a square lattice. ```@example square # define unit cell unit_cell = UnitCell(lattice_vecs = [[1.,0.],[0.,1.]], basis_vecs = [[0.,0.]]) # define size of lattice lattice = Lattice(L = [L,L], periodic = [true,true]) # define bonds/hoppings in x and y directions bond_x = Bond(orbitals = (1,1), displacement = [1,0]) bond_y = Bond(orbitals = (1,1), displacement = [0,1]) # construct neighbor table neighbor_table = build_neighbor_table([bond_x, bond_y], unit_cell, lattice) # calculate number of sites in lattice N = nsites(unit_cell, lattice) # calculate number of bonds in lattice Nbonds = size(neighbor_table, 2) (N, Nbonds) ``` Next we construct the strictly off-diagonal hopping matrix ``K,`` and a vector to represent the diagonal on-site energy matrix ``V.`` ```julia # build hopping matrix K = zeros(typeof(t), N, N) build_hopping_matrix!(K, neighbor_table, fill(t, Nbonds)) # build vector representing diagonal on-site energy matrix V = fill(-ΞΌ, N) ``` Now we define a the propagator ``B_{\sigma,l}`` for each spin species ``\sigma`` and imaginary time slice ``\tau = \Delta\tau \cdot l.`` Of course, in the non-interacting limit considered here all the propagators matrices are identical. This will no longer be the case if interactions are introduced, in which case each ``B_{\sigma,l}`` matrix will in general be unique. ```julia expmΔτV = exp.(-Δτ*V) expmΔτK = exp(-Δτ*K) exppΔτK = exp(+Δτ*K) # null vector spin up propagators to fill Bup = AsymExactPropagator{eltype(expmΔτK),eltype(expmΔτV)}[] # null vecotr of spin down propagators to fill Bdn = AsymExactPropagator{eltype(expmΔτK),eltype(expmΔτV)}[] # construct propagator for each spin species and append to appropriate vector for l in 1:LΟ„ B_l = AsymExactPropagator(expmΔτV, expmΔτK, exppΔτK) push!(Bup, B_l) push!(Bdn, B_l) end ``` In the above we chose to represent the propagator matrices using the [`AsymExactPropagator`](@ref) type, which assumes the ``B_l = e^{-\Delta\tau K_l} e^{-\Delta\tau V_l}`` definition, where the ``K_l`` hopping matrix is exactly exponentiated. This package includes the other possible definitions [`AsymChkbrdPropagator`](@ref), [`SymExactPropagator`](@ref) and [`SymChkbrdPropagator`](@ref). Next we instantiate two instances of the [`FermionGreensCalculator`](@ref) type, one for each of the two electron spin species, spin up and spin down. ```julia fgc_up = FermionGreensCalculator(Bup, Ξ², Δτ, n_stab) fgc_dn = FermionGreensCalculator(Bdn, Ξ², Δτ, n_stab) ``` Now we initialize the spin up and spin down equal time Green's function matrices ``G_\uparrow(0,0)`` and ``G_\downarrow(0,0).`` ```julia Gup = zeros(N,N) logdetGup, sgndetGup = calculate_equaltime_greens!(Gup, fgc_up) Gdn = zeros(N,N) logdetGdn, sgndetGdn = calculate_equaltime_greens!(Gdn, fgc_dn) ``` Now we will demonstrate how to synchronously iterate over the imaginary time slices for both the spin up and spin down sectors. ```julia # Iterate over imaginary time Ο„=Δτ⋅l. for l in fgc_up # Propagate equal-time Green's function matrix to current imaginary time G(τ±Δτ,τ±Δτ) ==> G(Ο„,Ο„) # depending on whether iterating over imaginary time in the forward or reverse direction propagate_equaltime_greens!(Gup, fgc_up, Bup) propagate_equaltime_greens!(Gdn, fgc_dn, Bdn) # LOCAL UPDATES OR EVALUATION OF DERIVATIVE OF FERMIONIC ACTION FOR THE CURRENT # IMAGINARY TIME SLICE WOULD GO HERE # Periodically re-calculate the Green's function matrix for numerical stability. # Comment: if not performing updates, but just evaluating the derivative of the action, then # set update_BΜ„=false to avoid wasting cpu time re-computing B_barβ‚™ matrices. logdetGup, sgndetGup, Ξ΄Gup, δθup = stabilize_equaltime_greens!(Gup, logdetGup, sgndetGup, fgc_up, Bup, update_BΜ„=true) logdetGdn, sgndetGdn, Ξ΄Gdn, δθdn = stabilize_equaltime_greens!(Gdn, logdetGdn, sgndetGdn, fgc_dn, Bdn, update_BΜ„=true) # Keep up and down spin Green's functions synchronized as iterating over imaginary time. iterate(fgc_dn, fgc_up.forward) end ``` Note that if we iterate over imaginary time again, it will iterate in the opposite direction. This is expected behavior. Each time you iterate over imaginary time the direction of iteration reverses. While not immediately obvious, this allows for a reduction in the number of required matrix factorizations. This package also exports two routines, [`local_update_det_ratio`](@ref) and [`local_update_greens!`](@ref), that are useful for implementing local updates in a DQMC simulation. Lastly, we will will calculate the unequal-time Green's functions ``G_{\sigma}(\tau,0)`` and ``G_{\sigma}(0,\tau)``, and the equal-time Green's function ``G_{\sigma}(\tau,\tau)`` for all imaginary time slices. This functionality is important ```julia # initialize unequal-time Green's functions Gup_Ο„0 = similar(Gdn) # Gβ‚Š(Ο„,0) Gup_0Ο„ = similar(Gdn) # Gβ‚Š(0,Ο„) Gup_ττ = similar(Gdn) # Gβ‚Š(Ο„,Ο„) Gdn_Ο„0 = similar(Gdn) # Gβ‚‹(Ο„,0) Gdn_0Ο„ = similar(Gdn) # Gβ‚‹(0,Ο„) Gdn_ττ = similar(Gdn) # Gβ‚‹(Ο„,Ο„) initialize_unequaltime_greens!(Gup_Ο„0, Gup_0Ο„, Gup_ττ, Gup) initialize_unequaltime_greens!(Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, Gdn) # EQUAL-TIME CORRELATION MEASUREMENTS WOULD GO HERE # Iterate over imaginary time Ο„=Δτ⋅l. for l in fgc_up # Propagate Green's function matrices to current imaginary time slice propagate_unequaltime_greens!(Gup_Ο„0, Gup_0Ο„, Gup_ττ, fgc_up, Bup) propagate_unequaltime_greens!(Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, fgc_dn, Bdn) # UNEQUAL-TIME CORRELATION FUNCTION MEASUREMENTS WOULD GO HERE # Periodically re-calculate the Green's function matrix for numerical stability. logdetGup, sgndetGup, Ξ΄Gup, δθup = stabilize_unequaltime_greens!(Gup_Ο„0, Gup_0Ο„, Gup_ττ, logdetGup, sgndetGup, fgc_up, Bup, update_BΜ„=false) logdetGdn, sgndetGdn, Ξ΄Gdn, δθdn = stabilize_unequaltime_greens!(Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, logdetGdn, sgndetGdn, fgc_dn, Bdn, update_BΜ„=false) # Keep up and down spin Green's functions synchronized as iterating over imaginary time. iterate(fgc_dn, fgc_up.forward) end ```
JDQMCFramework
https://github.com/SmoQySuite/JDQMCFramework.jl.git
[ "MIT" ]
1.0.10
d37e67cd855d38efbc41b807f45d758eaaa82923
docs
47887
```@meta EditURL = "../../../examples/square_hubbard.jl" ``` Download this example as [Jupyter notebook](../assets/notebooks/square_hubbard.ipynb) or [Julia script](../assets/scripts/square_hubbard.jl). # Tutorial 1: Square Lattice Hubbard Model DQMC Simulation This tutorial implements a determinant quantum Monte Carlo (DQMC) simulation from "scratch" using the [`JDQMCFramework.jl`](https://github.com/SmoQySuite/JDQMCFramework.jl.git) package, along with several others. The purpose of this tutorial is to empower researchers to write their own lightweight DQMC codes in order to address specific research needs that fall outside the scope of existing high-level DQMC packages like [`SmoQyDQMC.jl`](https://github.com/SmoQySuite/SmoQyDQMC.jl.git), and to enable rapid prototyping of algorithmic improvements to existing DQMC methods. This tutorial is relatively long as a lot goes into writing a full DQMC code. However, in spite of the length, each step is relatively straightforward. This is made possible by leveraging the functionality exported by [`JDQMCFramework.jl`](https://github.com/SmoQySuite/JDQMCFramework.jl.git) and other packages. For instance, the [`JDQMCFramework.jl`](https://github.com/SmoQySuite/JDQMCFramework.jl.git) package takes care of all the numerical stabilization nonsense that is one of the most challenging parts of writing a DQMC code. Also, implementing various correlation measurements in a DQMC simulation is typically very time consuming and challening, as it requires working through arduous Wick's contractions, and then implementing each term. Once again, this hurdle is largely avoided by leveraging the functionality exported by the [`JDQMCMeasurements.jl`](https://github.com/SmoQySuite/JDQMCMeasurements.jl.git) package, which implements a variety of standard correlation function measurements for arbitary lattice geometries. The repulsive Hubbard model Hamiltonian on a square lattice considered in this tutorial is given by ```math \hat{H} = -t \sum_{\sigma,\langle i,j\rangle} (\hat{c}^{\dagger}_{\sigma,i} \hat{c}^{\phantom \dagger}_{\sigma,j} + {\rm h.c.}) + U \sum_i (\hat{n}_{\uparrow,i}-\tfrac{1}{2})(\hat{n}_{\downarrow,i}-\tfrac{1}{2}) - \mu \sum_{\sigma,i} \hat{n}_{\sigma,i}, ``` where ``\hat{c}^\dagger_{\sigma,i} (\hat{c}^{\phantom \dagger}_{\sigma,i})`` creates (annihilates) a spin ``\sigma`` electron on site ``i`` in the lattice, and ``\hat{n}_{\sigma,i} = \hat{c}^\dagger_{\sigma,i} \hat{c}^{\phantom \dagger}_{\sigma,i}`` is the spin-``\sigma`` electron number operator for site ``i``. In the above Hamiltonian, ``t`` is the nearest neighbor hopping integral, ``\mu`` is the chemical potential, and ``U > 0`` controls the strength of the on-site Hubbard repulsion. Lastly, if ``\mu = 0.0,`` then the Hamiltonian is particle-hole symmetric, ensuring the system is half-filled ``(\langle n_\sigma \rangle = \tfrac{1}{2})`` and that there is no sign problem. In the case of ``\mu \ne 0`` there will be a sign problem. The script version of this tutorial, which can be downloaded using the link found at the top of this page, can be run with the command ``` julia square_hubbard.jl ``` in a terminal. This tutorial can also be downloaded as a notebook at the top of this page. We begin by importing the relevant packages we will need to use in this example. Note that to run this tutorial you will need to install all the required Julia packages. However, this is straightforward as all the packages used in this tutorial are registered with the Julia [General](https://github.com/JuliaRegistries/General.git) package registry. This means they can all be easily installed with the Julia package manager using the `add` command in the same way that the [`JDQMCFramework.jl`](https://github.com/SmoQySuite/JDQMCFramework.jl.git) package is installed. ````@example square_hubbard # Import relevant standard template libraries. using Random using LinearAlgebra # Provides framework for implementing DQMC code. import JDQMCFramework as jdqmcf # Exports methods for measuring various correlation functions in a DQMC simulation. import JDQMCMeasurements as jdqmcm # Exports types and methods for representing lattice geometries. import LatticeUtilities as lu # Exports the checkerboard approximation for representing an exponentiated hopping matrix. import Checkerboard as cb # Package for performing Fast Fourier Transforms (FFTs). using FFTW ```` The next incantations are included for annoying technical reasons. Without going into too much detail, the default multithreading behavior used by BLAS/LAPACK in Julia is somewhat sub-optimal. As a result, it is typically a good idea to include these commands in Julia DQMC codes, as they ensure that BLAS/LAPACK (and FFTW) run in a single-threaded fashion. For more information on this issue, I refer readers to [this discussion](https://carstenbauer.github.io/ThreadPinning.jl/stable/explanations/blas/), which is found in the documentation for the [`ThreadPinning.jl`](https://github.com/carstenbauer/ThreadPinning.jl.git) package. ````@example square_hubbard # Set number of threads used by BLAS/LAPACK to one. BLAS.set_num_threads(1) # Set number of threads used by FFTW to one. FFTW.set_num_threads(1) ```` Now we define the relevant Hamiltonian parameter values that we want to simulate. In this example we will stick to a relatively small system size ``(4 \times 4)`` and inverse temperature ``(\beta = 4)`` to ensure that this tutorial can be run quickly on a personal computer. Also, in this tutorial I will include many print statements so that when the tutorial is run users can keep track of what is going on. That said, for a DQMC code that will be used in actual research you will want to replace the print statements with code that writes relevant information and measurement results to file. ````@example square_hubbard # Nearest-neighbor hopping amplitude. t = 1.0 println("Nearest-neighbor hopping amplitude, t = ", t) # Hubbard interaction. U = 6.0 println("Hubbard interaction, U = ", U) # Chemical potential. ΞΌ = 2.0 println("Chemical potential, mu = ", ΞΌ) # Inverse temperature. Ξ² = 4.0 println("Inverse temperature, beta = ", Ξ²) # Lattice size. L = 4 println("Linear lattice size, L = ", L) ```` Next we define the relevant DQMC simulation parameters. ````@example square_hubbard # Discretization in imaginary time. Δτ = 0.05 println("Disretization in imaginary time, dtau = ", Δτ) # Length of imaginary time axis. LΟ„ = round(Int, Ξ²/Δτ) println("Length of imaginary time axis, Ltau = ", LΟ„) # Whether or not to use a symmetric or asymmetric definition for the propagator matrices. symmetric = false println("Whether symmetric or asymmetric propagator matrices are used, symmetric = ", symmetric) # Whether or not to use the checkerboard approximation to represent the # exponentiated electron kinetic energy matrix exp(-Δτ⋅K). checkerboard = false println("Whether the checkerboard approximation is used, checkerboard = ", checkerboard) # Period with which numerical stabilization is performed i.e. # how many imaginary time slices separate more expensive recomputations # of the Green's function matrix using numerically stable routines. n_stab = 10 println("Numerical stabilization period, n_stab = ", n_stab) # The number of burnin sweeps through the lattice performing local updates that # are performed to thermalize the system. N_burnin = 2_500 println("Number of burnin sweeps, N_burnin = ", N_burnin) # The number of measurements made once the system is thermalized. N_measurements = 10_000 println("Number of measurements, N_measurements = ", N_measurements) # Number of local update sweeps separating sequential measurements. N_sweeps = 1 println("Number of local update sweeps seperating measurements, n_sweeps = ", N_sweeps) # Number of bins used to performing a binning analysis when calculating final error bars # for measured observables. N_bins = 50 println("Number of measurement bins, N_bins = ", N_bins) # Number of measurements averaged over per measurement bin. N_binsize = N_measurements Γ· N_bins println("Number of measurements per bin, N_binsize = ", N_binsize) ```` Now we initialize the random number generator (RNG) that will be used in the rest of the simulation. ````@example square_hubbard # Initialize random number generator. seed = abs(rand(Int)) rng = Xoshiro(seed) println("Random seed used to initialize RNG, seed = ", seed) ```` Next, we define our square lattice geometry using the [`LatticeUtilities.jl`](https://github.com/SmoQySuite/LatticeUtilities.jl.git) package. ````@example square_hubbard # Define the square lattice unit cell. unit_cell = lu.UnitCell( lattice_vecs = [[1.0, 0.0], [0.0, 1.0]], basis_vecs = [[0.0, 0.0]] ) # Define the size of the periodic square lattice. lattice = lu.Lattice( L = [L, L], periodic = [true, true] ) # Define nearest-neighbor bond in +x direction bond_px = lu.Bond( orbitals = (1,1), displacement = [1,0] ) # Define nearest-neighbor bond in +y direction bond_py = lu.Bond( orbitals = (1,1), displacement = [0,1] ) # Build the neighbor table corresponding to all nearest-neighbor bonds. neighbor_table = lu.build_neighbor_table([bond_px, bond_py], unit_cell, lattice) println("The neighbor table, neighbor_table =") show(stdout, "text/plain", neighbor_table) println("\n") # The total number of sites/orbitals in the lattice. N = lu.nsites(unit_cell, lattice) # For square lattice this is simply N = L^2 println("Total number of sites in lattice, N = ", N) # Total number of bonds in lattice. N_bonds = size(neighbor_table, 2) println("Total number of bonds in lattice, N_bonds = ", N_bonds) ```` Now we define a few other bonds that are needed to measure the local s-wave, extended s-wave and d-wave pair susceptibilities. ````@example square_hubbard # Define a "trivial" bond that maps a site back onto itself. bond_trivial = lu.Bond( orbitals = (1,1), displacement = [0,0] ) # Define bond in -x direction. bond_nx = lu.Bond( orbitals = (1,1), displacement = [-1,0] ) # Define bond in -y direction. bond_ny = lu.Bond( orbitals = (1,1), displacement = [0,-1] ) ```` Now let us calculated the exponentiated electron kinetic energy matrix ``e^{-\Delta\tau^\prime K}``, where ```math \hat{K} = -t \sum_{\sigma,\langle i,j\rangle} (\hat{c}^{\dagger}_{\sigma,i} \hat{c}^{\phantom \dagger}_{\sigma,j} + {\rm h.c.}) = \sum_\sigma \hat{\mathbf{c}}^\dagger_\sigma K \hat{\mathbf{c}}^{\phantom\dagger}_\sigma ``` and ``\hat{\mathbf{c}}^{\dagger}_{\sigma,i} = \left[ \hat{c}^{\dagger}_{\sigma,1} \ , \ \dots \ , \ \hat{c}^{\dagger}_{\sigma,N} \right]`` is a row vector of electron creation operators. Note that if `symmetric = true`, i.e. the symmetric definition for the propagator matrices ```math B_{\sigma,l} = e^{-\Delta\tau^\prime K} \cdot e^{-\Delta\tau V_{\sigma,l}} \cdot e^{-\Delta\tau^\prime K} ``` is being used, then ``\Delta\tau^\prime = \tfrac{1}{2} \Delta\tau``. If the asymmetric definition ```math B_{\sigma,l} = e^{-\Delta\tau V_{\sigma,l}} \cdot e^{-\Delta\tau^\prime K} ``` is used (`symmetric = false`), then ``\Delta\tau^\prime = \Delta\tau.`` Note the branching logic below associated with whether or not the matrix ``e^{-\Delta\tau^\prime K}`` is calculated exactly, or represented by the sparse checkerboard approximation using the package [`Checkerboard.jl`](https://github.com/SmoQySuite/Checkerboard.jl.git). ````@example square_hubbard # Define Δτ′=Δτ/2 if symmetric = true, otherwise Δτ′=Δτ Δτ′ = symmetric ? Δτ/2 : Δτ # If the matrix exp(Δτ′⋅K) is represented by the checkerboard approximation. if checkerboard # Construct the checkerboard approximation to the matrix exp(-Δτ′⋅K). expnΔτ′K = cb.CheckerboardMatrix(neighbor_table, fill(t, N_bonds), Δτ′) # If the matrix exp(Δτ′⋅K) is NOT represented by the checkerboard approximation. else # Construct the electron kinetic energy matrix. K = zeros(typeof(t), N, N) for bond in 1:N_bonds i, j = neighbor_table[1, bond], neighbor_table[2, bond] K[i,j] = -t K[j,i] = -t end # Calculate the exponentiated kinetic energy matrix, exp(-Δτ⋅K). # Note that behind the scenes Julia is diagonalizing the matrix K in order to exponentiate it. expnΔτ′K = exp(-Δτ′*K) # Calculate the inverse of the exponentiated kinetic energy matrix, exp(+Δτ⋅K). exppΔτ′K = exp(+Δτ′*K) end; nothing #hide ```` In this example we are going to introduce an Ising Hubbard-Stratonovich (HS) field to decouple the Hubbard interaction. The Ising HS transformation ```math e^{-\Delta\tau U (\hat{n}_{\uparrow,i,l}-\tfrac{1}{2})(\hat{n}_{\downarrow,i,l}-\tfrac{1}{2})} = \frac{1}{2} e^{-\tfrac{1}{4} \Delta\tau U} \sum_{s_{i,l} = \pm 1} e^{\alpha s_{i,l}(\hat{n}_{\uparrow,i,l}-\hat{n}_{\downarrow,i,l})} ``` is introduced for all imaginary time slices ``l \in [1, L_\tau]`` and sites ``i \in [1, N]`` in the lattice, where ```math \alpha = \cosh^{-1}\left( e^{\tfrac{1}{2}\Delta\tau U} \right) ``` is a constant. We start the simulation from a random ``s_{i,l}`` Ising HS field configuration. ````@example square_hubbard # Define constant associated Ising Hubbard-Stratonovich (HS) transformation. Ξ± = acosh(exp(Δτ*U/2)) # Initialize a random Ising HS configuration. s = rand(rng, -1:2:1, N, LΟ„) println("Random initial Ising HS configuration, s =") show(stdout, "text/plain", s) ```` Next we initialize a propagator matrix ``B_{\sigma,l}`` for each imaginary time slice ``l \in [1,L_\tau]``. We first initialize a pair of vectors `Bup` and `Bdn` that will contain the ``L_\tau`` propagators associated with each time slice. The branching logic below enforces the correct propagator matrix definition is used based on the boolean flags `symmetric` and `checkerboard` defined above. ````@example square_hubbard # Matrix element type for exponentiated electron kinetic energy matrix exp{-Δτ′⋅K} T_expnΔτK = eltype(t) # Matrix element type for diagonal exponentiated electron potential energy matrix exp{-Δτ⋅V[Οƒ,l]} T_expnΔτV = typeof(Ξ±) # Initialize empty vector to contain propagator matrices for each imaginary time slice. if checkerboard && symmetric # Propagator defined as B[Οƒ,l] = exp{-Δτ⋅K/2}β‹…exp{-Δτ⋅V[Οƒ,l]}β‹…exp{-Δτ⋅K/2}, # where the dense matrix exp{-Δτ⋅K/2} is approximated by the sparse checkerboard matrix. Bup = jdqmcf.SymChkbrdPropagator{T_expnΔτK, T_expnΔτV}[] Bdn = jdqmcf.SymChkbrdPropagator{T_expnΔτK, T_expnΔτV}[] elseif checkerboard && !symmetric # Propagator defined as B[Οƒ,l] = exp{-Δτ⋅V[Οƒ,l]}β‹…exp{-Δτ⋅K}, # where the dense matrix exp{-Δτ⋅K} is approximated by the sparse checkerboard matrix. Bup = jdqmcf.AbstractChkbrdPropagator{T_expnΔτK, T_expnΔτV}[] Bdn = jdqmcf.AbstractChkbrdPropagator{T_expnΔτK, T_expnΔτV}[] elseif !checkerboard && symmetric # Propagator defined as B[Οƒ,l] = exp{-Δτ⋅K/2}β‹…exp{-Δτ⋅V[Οƒ,l]}β‹…exp{-Δτ⋅K/2}, # where the dense matrix exp{-Δτ⋅K/2} is exactly calculated. Bup = jdqmcf.SymExactPropagator{T_expnΔτK, T_expnΔτV}[] Bdn = jdqmcf.SymExactPropagator{T_expnΔτK, T_expnΔτV}[] elseif !checkerboard && !symmetric # Propagator defined as B[Οƒ,l] = exp{-Δτ⋅V[Οƒ,l]}β‹…exp{-Δτ⋅K}, # where the dense matrix exp{-Δτ⋅K} is exactly calculated. Bup = jdqmcf.AsymExactPropagator{T_expnΔτK, T_expnΔτV}[] Bdn = jdqmcf.AsymExactPropagator{T_expnΔτK, T_expnΔτV}[] end; nothing #hide ```` Having an initialized the vector `Bup` and `Bdn` that will contain the propagator matrices, we now construct the propagator matrices for each time-slice based on the initial HS field configuration `s`. ````@example square_hubbard # Iterate over time-slices. for l in 1:LΟ„ # Get the HS fields associated with the current time-slice l. s_l = @view s[:,l] # Calculate the spin-up diagonal exponentiated potential energy # matrix exp{-Δτ⋅V[↑,l]} = exp{-Δτ⋅(-Ξ±/Δτ⋅s[i,l]-ΞΌ)} = exp{+Ξ±β‹…s[i,l] + Δτ⋅μ}. expnΔτVup = zeros(T_expnΔτV, N) @. expnΔτVup = exp(+Ξ± * s_l + Δτ*ΞΌ) # Calculate the spin-down diagonal exponentiated potential energy # matrix exp{-Δτ⋅V[↓,l]} = exp{-Δτ⋅(+Ξ±/Δτ⋅s[i,l]-ΞΌ)} = exp{-Ξ±β‹…s[i,l] + Δτ⋅μ}. expnΔτVdn = zeros(T_expnΔτV, N) @. expnΔτVdn = exp(-Ξ± * s_l + Δτ*ΞΌ) # Initialize spin-up and spin-down propagator matrix for the current time-slice l. if checkerboard && symmetric push!(Bup, jdqmcf.SymChkbrdPropagator(expnΔτVup, expnΔτ′K)) push!(Bdn, jdqmcf.SymChkbrdPropagator(expnΔτVdn, expnΔτ′K)) elseif checkerboard && !symmetric push!(Bup, jdqmcf.AsymChkbrdPropagator(expnΔτVup, expnΔτ′K)) push!(Bdn, jdqmcf.AsymChkbrdPropagator(expnΔτVdn, expnΔτ′K)) elseif !checkerboard && symmetric push!(Bup, jdqmcf.SymExactPropagator(expnΔτVup, expnΔτ′K, exppΔτ′K)) push!(Bdn, jdqmcf.SymExactPropagator(expnΔτVdn, expnΔτ′K, exppΔτ′K)) elseif !checkerboard && !symmetric push!(Bup, jdqmcf.AsymExactPropagator(expnΔτVup, expnΔτ′K, exppΔτ′K)) push!(Bdn, jdqmcf.AsymExactPropagator(expnΔτVdn, expnΔτ′K, exppΔτ′K)) end end ```` Now we instantiate two instances for the [`FermionGreensCalculator`](@ref) type, one for each spin species, spin up and spin down. This object enables the efficient and numerically stable calculation of the Green's functions behind-the-scenes, so that we do not need to concern ourselves with implementing numerical stablization routines ourselves. ````@example square_hubbard # Initialize a FermionGreensCalculator for both spin up and down electrons. fermion_greens_calc_up = jdqmcf.FermionGreensCalculator(Bup, Ξ², Δτ, n_stab) fermion_greens_calc_dn = jdqmcf.FermionGreensCalculator(Bdn, Ξ², Δτ, n_stab); nothing #hide ```` Next we calculate the equal-time Green's function matrices ```math G_\sigma(0,0) = [1 + B_\sigma(\beta,0)]^{-1} = [1 + B_{\sigma,L_\tau} \dots B_{\sigma,1}]^{-1} ``` for both electron spin species, ``\sigma = (\uparrow, \downarrow).`` ````@example square_hubbard # Calculate spin-up equal-time Green's function matrix. Gup = zeros(typeof(t), N, N) logdetGup, sgndetGup = jdqmcf.calculate_equaltime_greens!(Gup, fermion_greens_calc_up) # Calculate spin-down equal-time Green's function matrix. Gdn = zeros(typeof(t), N, N) logdetGdn, sgndetGdn = jdqmcf.calculate_equaltime_greens!(Gdn, fermion_greens_calc_dn); nothing #hide ```` In order to perform the DQMC simulation all we need are the equal-time Green's function matrices ``G_\sigma(0,0)`` calculated above. However, in order to make time-displaced correlation function measurements we also need to initialize six more matrices, which correspond to ``G_\sigma(\tau,\tau),`` ``G_\sigma(\tau,0)`` and ``G_\sigma(0,\tau).`` ````@example square_hubbard # Allcoate time-displaced Green's functions. Gup_Ο„0 = zero(Gup) # Gup(Ο„,0) Gup_0Ο„ = zero(Gup) # Gup(0,Ο„) Gup_ττ = zero(Gup) # Gup(Ο„,Ο„) Gdn_Ο„0 = zero(Gdn) # Gdn(Ο„,0) Gdn_0Ο„ = zero(Gdn) # Gdn(0,Ο„) Gdn_ττ = zero(Gdn); # Gdn(Ο„,Ο„) nothing #hide ```` Now we will allocate arrays to contain the various measurements we will make during the simulation, including various correlation functions. Note that the definition for each measurement will be supplied later in the tutorial when we begin processing the data to calculate the final statistics for each measured observable. ````@example square_hubbard # Vector to contain binned average sign measurement. avg_sign = zeros(eltype(Gup), N_bins) # Vector to contain binned density measurement. density = zeros(eltype(Gup), N_bins) # Vector to contain binned double occupancy measurement. double_occ = zeros(eltype(Gup), N_bins) # Array to contain binned position-space time-displaced Green's function measurements. C_greens = zeros(Complex{Float64}, N_bins, L, L, LΟ„+1) # Array to contain binned position-space time-displaced Spin-Z correlation function measurements. C_spinz = zeros(Complex{Float64}, N_bins, L, L, LΟ„+1) # Array to contain binned position-space time-displaced density correlation function measurements. C_density = zeros(Complex{Float64}, N_bins, L, L, LΟ„+1) # Array to contain binned position-space local s-wave pair correlation function. C_loc_swave = zeros(Complex{Float64}, N_bins, L, L, LΟ„+1) # Array to contain binned position-space extended s-wave pair correlation function. C_ext_swave = zeros(Complex{Float64}, N_bins, L, L, LΟ„+1) # Array to contain binned position-space d-wave pair correlation function. C_dwave = zeros(Complex{Float64}, N_bins, L, L, LΟ„+1) # Array to contain binned momentum-space d-wave pair susceptibility. P_d_q = zeros(Complex{Float64}, N_bins, L, L); nothing #hide ```` Below we implement a function that sweeps through all time-slices and sites in the lattice, attempting an update to each Ising HS field ``s_{i,l}``. ````@example square_hubbard # Function to perform local updates to all Ising HS fields. function local_update!( Gup::Matrix{T}, logdetGup, sgndetGup, Bup, fermion_greens_calc_up, Gdn::Matrix{T}, logdetGdn, sgndetGdn, Bdn, fermion_greens_calc_dn, s, ΞΌ, Ξ±, Δτ, Ξ΄G, rng ) where {T<:Number} # Length of imaginary time axis. LΟ„ = length(Bup) # Number of sites in lattice. N = size(Gup,1) # Allocate temporary arrays that will be used to avoid dynamic memory allocation. A = zeros(T, N, N) u = zeros(T, N) v = zeros(T, N) # Allocate vector of integers to contain random permutation specifying the order in which # sites are iterated over at each imaginary time slice when performing local updates. perm = collect(1:size(Gup,1)) # Variable to keep track of the acceptance rate. acceptance_rate = 0.0 # Iterate over imaginary time slices. for l in fermion_greens_calc_up # Propagate equal-time Green's function matrix to current imaginary time # G(τ±Δτ,τ±Δτ) ==> G(Ο„,Ο„) depending on whether iterating over imaginary # time in the forward or reverse direction jdqmcf.propagate_equaltime_greens!(Gup, fermion_greens_calc_up, Bup) jdqmcf.propagate_equaltime_greens!(Gdn, fermion_greens_calc_dn, Bdn) # If using symmetric propagator definition (symmetric = true), then apply # the transformation G ==> GΜƒ = exp{+Δτ⋅K/2}β‹…Gβ‹…exp{-Δτ⋅K/2}. # If asymmetric propagator definition is used (symmetric = false), # then this does nothing. jdqmcf.partially_wrap_greens_forward!(Gup, Bup[l], A) jdqmcf.partially_wrap_greens_forward!(Gdn, Bdn[l], A) # Get the HS fields associated with the current imaginary time-slice. s_l = @view s[:,l] # Perform local updates HS fields associated with the current imaginary time slice. (logdetGup, sgndetGup, logdetGdn, sgndetGdn, acceptance_rate_l) = _local_update!( Gup, logdetGup, sgndetGup, Bup[l], Gdn, logdetGdn, sgndetGdn, Bdn[l], s_l, ΞΌ, Ξ±, Δτ, rng, perm, u, v ) # Record the acceptance rate acceptance_rate += acceptance_rate_l / LΟ„ # If using symmetric propagator definition (symmetric = true), then apply # the transformation GΜƒ ==> G = exp{-Δτ⋅K/2}β‹…GΜƒβ‹…exp{+Δτ⋅K/2}. # If asymmetric propagator definition is used (symmetric = false), # then this does nothing. jdqmcf.partially_wrap_greens_reverse!(Gup, Bup[l], A) jdqmcf.partially_wrap_greens_reverse!(Gdn, Bdn[l], A) # Periodically re-calculate the Green's function matrix for numerical stability. logdetGup, sgndetGup, Ξ΄Gup, δθup = jdqmcf.stabilize_equaltime_greens!( Gup, logdetGup, sgndetGup, fermion_greens_calc_up, Bup, update_BΜ„ = true ) logdetGdn, sgndetGdn, Ξ΄Gdn, δθdn = jdqmcf.stabilize_equaltime_greens!( Gdn, logdetGdn, sgndetGdn, fermion_greens_calc_dn, Bdn, update_BΜ„ = true ) # Record largest numerical error corrected by numerical stabilization. Ξ΄G = max(Ξ΄G, Ξ΄Gup, Ξ΄Gdn) # Keep up and down spin Green's functions synchronized as iterating over imaginary time. iterate(fermion_greens_calc_dn, fermion_greens_calc_up.forward) end return logdetGup, sgndetGup, logdetGdn, sgndetGdn, Ξ΄G, acceptance_rate end # Iterate over all sites for single imaginary time-slice, attempting a local # update to each corresponding Ising HS field. function _local_update!( Gup, logdetGup, sgndetGup, Bup, Gdn, logdetGdn, sgndetGdn, Bdn, s, ΞΌ, Ξ±, Δτ, rng, perm, u, v ) # Randomize the order in which the sites are iterated over. shuffle!(rng, perm) # Counter for number of accepted updates. accepted = 0 # Iterate over sites in lattice. for i in perm # Calculate the new value of the diagonal potential energy matrix element # assuming the sign of the Ising HS field is changed. Vupβ€² = -Ξ±/Δτ * (-s[i]) - ΞΌ Vdnβ€² = +Ξ±/Δτ * (-s[i]) - ΞΌ # Calculate the determinant ratio associated with the proposed update. Rup, Ξ”up = jdqmcf.local_update_det_ratio(Gup, Bup, Vupβ€², i, Δτ) Rdn, Ξ”dn = jdqmcf.local_update_det_ratio(Gdn, Bdn, Vdnβ€², i, Δτ) # Calculate the acceptance probability based on the Metropolis accept/reject criteria. P = min(1.0, abs(Rup * Rdn)) # Randomly Accept or reject the proposed update with the specified probability. if rand(rng) < P # Increment the accepted update counter. accepted += 1 # Flip the appropriate Ising HS field. s[i] = -s[i] # Update the Green's function matrices. logdetGup, sgndetGup = jdqmcf.local_update_greens!( Gup, logdetGup, sgndetGup, Bup, Rup, Ξ”up, i, u, v ) logdetGdn, sgndetGdn = jdqmcf.local_update_greens!( Gdn, logdetGdn, sgndetGdn, Bdn, Rdn, Ξ”dn, i, u, v ) end end # Calculate the acceptance rate. acceptance_rate = accepted / N return logdetGup, sgndetGup, logdetGdn, sgndetGdn, acceptance_rate end; nothing #hide ```` Next we implement a function to make measurements during the simulation, including time-displaced measurements. Note that if we want to calculate the expectation value for some observable ``\langle \mathcal{O} \rangle``, then during the simulation we actually measure ``\langle \mathcal{S O} \rangle_{\mathcal{W}}``, where ``\langle \bullet \rangle_{\mathcal{W}}`` denotes an average with respect to states sampled according to the DQMC weights ```math \mathcal{W} = | \det G_\uparrow^{-1} \det G_\downarrow^{-1} |, ``` such that ```math \mathcal{S} = \text{sign}(\det G_\uparrow^{-1} \det G_\downarrow^{-1}) ``` is the sign associated with each state. The reweighting method is then used at the end of a simulation to recover the correct expectation value according to ```math \langle \mathcal{O} \rangle = \frac{ \langle \mathcal{SO} \rangle_{\mathcal{W}} }{ \langle \mathcal{S} \rangle_{\mathcal{W}} }, ``` where ``\langle \mathcal{S} \rangle_{\mathcal{W}}`` is the average sign measured over the course of the simulation. ````@example square_hubbard # Make measurements. function make_measurements!( Gup, logdetGup, sgndetGup, Gup_ττ, Gup_Ο„0, Gup_0Ο„, Bup, fermion_greens_calc_up, Gdn, logdetGdn, sgndetGdn, Gdn_ττ, Gdn_Ο„0, Gdn_0Ο„, Bdn, fermion_greens_calc_dn, unit_cell, lattice, bond_trivial, bond_px, bond_nx, bond_py, bond_ny, bin, avg_sign, density, double_occ, C_greens, C_spinz, C_density, C_loc_swave, C_ext_swave, C_dwave ) # Initialize time-displaced Green's function matrices for both spin species: # G(Ο„=0,Ο„=0) = G(0,0) # G(Ο„=0,0) = G(0,0) # G(0,Ο„=0) = -(I-G(0,0)) jdqmcf.initialize_unequaltime_greens!(Gup_Ο„0, Gup_0Ο„, Gup_ττ, Gup) jdqmcf.initialize_unequaltime_greens!(Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, Gdn) # Calculate the current sign. sgn = sign(sgndetGup * sgndetGdn) # Measure the average sign. avg_sign[bin] += sgn # Measure the density. nup = jdqmcm.measure_n(Gup) ndn = jdqmcm.measure_n(Gdn) density[bin] += sgn * (nup + ndn) # Measure the double occupancy. double_occ[bin] += sgn * jdqmcm.measure_double_occ(Gup, Gdn) # Measure equal-time correlation functions. make_correlation_measurements!( Gup, Gup_ττ, Gup_Ο„0, Gup_0Ο„, Gdn, Gdn_ττ, Gdn_Ο„0, Gdn_0Ο„, unit_cell, lattice, bond_trivial, bond_px, bond_nx, bond_py, bond_ny, bin, 0, sgn, C_greens, C_spinz, C_density, C_loc_swave, C_ext_swave, C_dwave ) # Iterate over imaginary time slices. for l in fermion_greens_calc_up # Propagate equal-time Green's function matrix to current imaginary time # G(τ±Δτ,τ±Δτ) ==> G(Ο„,Ο„) depending on whether iterating over imaginary # time in the forward or reverse direction jdqmcf.propagate_unequaltime_greens!(Gup_Ο„0, Gup_0Ο„, Gup_ττ, fermion_greens_calc_up, Bup) jdqmcf.propagate_unequaltime_greens!(Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, fermion_greens_calc_dn, Bdn) # Measure time-displaced correlation function measurements for Ο„ = l⋅Δτ. make_correlation_measurements!( Gup, Gup_ττ, Gup_Ο„0, Gup_0Ο„, Gdn, Gdn_ττ, Gdn_Ο„0, Gdn_0Ο„, unit_cell, lattice, bond_trivial, bond_px, bond_nx, bond_py, bond_ny, bin, l, sgn, C_greens, C_spinz, C_density, C_loc_swave, C_ext_swave, C_dwave, ) # Periodically re-calculate the Green's function matrix for numerical stability. logdetGup, sgndetGup, Ξ΄Gup, δθup = jdqmcf.stabilize_unequaltime_greens!( Gup_Ο„0, Gup_0Ο„, Gup_ττ, logdetGup, sgndetGup, fermion_greens_calc_up, Bup, update_BΜ„=false ) logdetGdn, sgndetGdn, Ξ΄Gdn, δθdn = jdqmcf.stabilize_unequaltime_greens!( Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, logdetGdn, sgndetGdn, fermion_greens_calc_dn, Bdn, update_BΜ„=false ) # Keep up and down spin Green's functions synchronized as iterating over imaginary time. iterate(fermion_greens_calc_dn, fermion_greens_calc_up.forward) end return nothing end # Make time-displaced measurements. function make_correlation_measurements!( Gup, Gup_ττ, Gup_Ο„0, Gup_0Ο„, Gdn, Gdn_ττ, Gdn_Ο„0, Gdn_0Ο„, unit_cell, lattice, bond_trivial, bond_px, bond_nx, bond_py, bond_ny, bin, l, sgn, C_greens, C_spinz, C_density, C_loc_swave, C_ext_swave, C_dwave, tmp = zeros(eltype(C_greens), lattice.L...) ) # Get a view into the arrays accumulating the correlation measurements # for the current imaginary time-slice and bin. C_greens_bin_l = @view C_greens[bin,:,:,l+1] C_spinz_bin_l = @view C_spinz[bin,:,:,l+1] C_density_bin_l = @view C_density[bin,:,:,l+1] C_loc_swave_bin_l = @view C_loc_swave[bin,:,:,l+1] C_ext_swave_bin_l = @view C_ext_swave[bin,:,:,l+1] C_dwave_bin_l = @view C_dwave[bin,:,:,l+1] # Measure Green's function for both spin-up and spin-down. jdqmcm.greens!(C_greens_bin_l, 1, 1, unit_cell, lattice, Gup_Ο„0, sgn) jdqmcm.greens!(C_greens_bin_l, 1, 1, unit_cell, lattice, Gdn_Ο„0, sgn) # Measure spin-z spin-spin correlation. jdqmcm.spin_z_correlation!( C_spinz_bin_l, 1, 1, unit_cell, lattice, Gup_Ο„0, Gup_0Ο„, Gup_ττ, Gup, Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, Gdn, sgn ) # Measure density-density correlation. jdqmcm.density_correlation!( C_density_bin_l, 1, 1, unit_cell, lattice, Gup_Ο„0, Gup_0Ο„, Gup_ττ, Gup, Gdn_Ο„0, Gdn_0Ο„, Gdn_ττ, Gdn, sgn ) # Measure local s-wave correlation measurement. jdqmcm.pair_correlation!( C_loc_swave_bin_l, bond_trivial, bond_trivial, unit_cell, lattice, Gup_Ο„0, Gdn_Ο„0, sgn ) # Group the nearest-neighbor bonds together. bonds = (bond_px, bond_nx, bond_py, bond_ny) # d-wave correlation phases. dwave_phases = (+1, +1, -1, -1) # Iterate over all pairs of nearest-neigbbor bonds. for i in eachindex(bonds) for j in eachindex(bonds) # Measure pair correlation associated with bond pair. fill!(tmp, 0) jdqmcm.pair_correlation!( tmp, bonds[i], bonds[j], unit_cell, lattice, Gup_Ο„0, Gdn_Ο„0, sgn ) # Add contribution to extended s-wave and d-wave pair correlation. @. C_ext_swave_bin_l += tmp / 4 @. C_dwave_bin_l += dwave_phases[i] * dwave_phases[j] * tmp / 4 end end return nothing end; nothing #hide ```` Now we will write a top-level function to run the simulation, including both the thermalization and measurement portions of the simulation. ````@example square_hubbard # High-level function to run the DQMC simulation. function run_simulation!( s, ΞΌ, Ξ±, Δτ, rng, N_burnin, N_bins, N_binsize, N_sweeps, Gup, logdetGup, sgndetGup, Gup_ττ, Gup_Ο„0, Gup_0Ο„, Bup, fermion_greens_calc_up, Gdn, logdetGdn, sgndetGdn, Gdn_ττ, Gdn_Ο„0, Gdn_0Ο„, Bdn, fermion_greens_calc_dn, unit_cell, lattice, bond_trivial, bond_px, bond_nx, bond_py, bond_ny, avg_sign, density, double_occ, C_greens, C_spinz, C_density, C_loc_swave, C_ext_swave, C_dwave ) # Initialize variable to keep track of largest corrected numerical error. Ξ΄G = 0.0 # The acceptance rate on local updates. acceptance_rate = 0.0 # Perform burnin updates to thermalize system. for n in 1:N_burnin # Attempt local update to every Ising HS field. (logdetGup, sgndetGup, logdetGdn, sgndetGdn, Ξ΄Gβ€², ac) = local_update!( Gup, logdetGup, sgndetGup, Bup, fermion_greens_calc_up, Gdn, logdetGdn, sgndetGdn, Bdn, fermion_greens_calc_dn, s, ΞΌ, Ξ±, Δτ, Ξ΄G, rng ) # Record max numerical error. Ξ΄G = max(Ξ΄G, Ξ΄Gβ€²) # Update acceptance rate. acceptance_rate += ac end # Iterate over measurement bins. for bin in 1:N_bins # Iterate over updates and measurements in bin. for n in 1:N_binsize # Iterate over number of local update sweeps per measurement. for sweep in 1:N_sweeps # Attempt local update to every Ising HS field. (logdetGup, sgndetGup, logdetGdn, sgndetGdn, Ξ΄Gβ€², ac) = local_update!( Gup, logdetGup, sgndetGup, Bup, fermion_greens_calc_up, Gdn, logdetGdn, sgndetGdn, Bdn, fermion_greens_calc_dn, s, ΞΌ, Ξ±, Δτ, Ξ΄G, rng ) # Record max numerical error. Ξ΄G = max(Ξ΄G, Ξ΄Gβ€²) # Update acceptance rate. acceptance_rate += ac end # Make measurements. make_measurements!( Gup, logdetGup, sgndetGup, Gup_ττ, Gup_Ο„0, Gup_0Ο„, Bup, fermion_greens_calc_up, Gdn, logdetGdn, sgndetGdn, Gdn_ττ, Gdn_Ο„0, Gdn_0Ο„, Bdn, fermion_greens_calc_dn, unit_cell, lattice, bond_trivial, bond_px, bond_nx, bond_py, bond_ny, bin, avg_sign, density, double_occ, C_greens, C_spinz, C_density, C_loc_swave, C_ext_swave, C_dwave ) end # Normalize accumulated measurements by the bin size. avg_sign[bin] /= N_binsize density[bin] /= N_binsize double_occ[bin] /= N_binsize C_greens[bin,:,:,:] /= (2 * N_binsize) C_spinz[bin,:,:,:] /= N_binsize C_density[bin,:,:,:] /= N_binsize C_loc_swave[bin,:,:,:] /= N_binsize C_ext_swave[bin,:,:,:] /= N_binsize C_dwave[bin,:,:,:] /= N_binsize end # Calculate the final acceptance rate for local updates. acceptance_rate /= (N_burnin + N_bins * N_binsize * N_sweeps) return acceptance_rate, Ξ΄G end; nothing #hide ```` Now let us run our DQMC simulation. ````@example square_hubbard # Run the DQMC simulation. acceptance_rate, Ξ΄G = run_simulation!( s, ΞΌ, Ξ±, Δτ, rng, N_burnin, N_bins, N_binsize, N_sweeps, Gup, logdetGup, sgndetGup, Gup_ττ, Gup_Ο„0, Gup_0Ο„, Bup, fermion_greens_calc_up, Gdn, logdetGdn, sgndetGdn, Gdn_ττ, Gdn_Ο„0, Gdn_0Ο„, Bdn, fermion_greens_calc_dn, unit_cell, lattice, bond_trivial, bond_px, bond_nx, bond_py, bond_ny, avg_sign, density, double_occ, C_greens, C_spinz, C_density, C_loc_swave, C_ext_swave, C_dwave ) println("Acceptance Rate = ", acceptance_rate) println("Largest Numerical Error = ", Ξ΄G) ```` Having completed the DQMC simulation, the next step is the analyze the results, calculating the mean and error for various measuremed observables. We will first calculate the relevant global measurements, including the average density ``\langle n \rangle = \langle n_\uparrow + n_\downarrow \rangle`` and double occupancy ``\langle n_\uparrow n_\downarrow \rangle.`` Note that the binning method is used to calculate the error bar for the correlated data. The Jackknife algorithm is also used to propagate error and correct for bias when evaluating ```math \langle \mathcal{O} \rangle = \frac{ \langle \mathcal{S O} \rangle_\mathcal{W} }{ \langle \mathcal{S} \rangle_\mathcal{W} } ``` to account for the sign problem. ````@example square_hubbard # Calculate the average sign for the simulation. sign_avg, sign_std = jdqmcm.jackknife(identity, avg_sign) println("Avg Sign, S = ", sign_avg, " +/- ", sign_std) # Calculate the average density. density_avg, density_std = jdqmcm.jackknife(/, density, avg_sign) println("Density, n = ", density_avg, " +/- ", density_std) # Calculate the average double occupancy. double_occ_avg, double_occ_std = jdqmcm.jackknife(/, double_occ, avg_sign) println("Double occupancy, nup_ndn = ", double_occ_avg, " +/- ", double_occ_std) ```` Now we move onto processing the measured correlation function data. We define two functions to assist with this process. The first function integrates the binned time-displaced correlation function data over the imaginary time axis in order to generate binned susceptibility data. Note that the integration over the imaginary time axis is performed using Simpson's rule, which is accurate to order ``\mathcal{O}(\Delta\tau^4)``. ````@example square_hubbard # Given the binned time-displaced correlation function/structure factor data, # calculate and return the corresponding binned susceptibility data. function susceptibility(S::AbstractArray{T}, Δτ) where {T<:Number} # Allocate array to contain susceptibility. Ο‡ = zeros(T, size(S)[1:3]) # Iterate over bins. for bin in axes(S,1) # Calculate the susceptibility for the current bin by integrating the correlation # data over the imaginary time axis using Simpson's rule. S_bin = @view S[bin,:,:,:] Ο‡_bin = @view Ο‡[bin,:,:] jdqmcm.susceptibility!(Ο‡_bin, S_bin, Δτ, 3) end return Ο‡ end ```` We also define a function to calculate the average and error of a correlation function measurement based on the input binned correlation function data. ````@example square_hubbard # Calculate average correlation function values based on binned data. function correlation_stats( S::AbstractArray{Complex{T}}, avg_sign::Vector{T} ) where {T<:AbstractFloat} # Allocate arrays to contain the mean and standard deviation of # measured correlation function. S_avg = zeros(Complex{T}, size(S)[2:end]) S_std = zeros(T, size(S)[2:end]) # Number of bins. N_bins = length(avg_sign) # Preallocate arrays to make the jackknife error analysis faster. jackknife_samples = (zeros(Complex{T}, N_bins), zeros(T, N_bins)) jackknife_g = zeros(Complex{T}, N_bins) # Iterate over correlation functions. for n in CartesianIndices(S_avg) # Use the jackknife method to calculage average and error. vals = @view S[:,n] S_avg[n], S_std[n] = jdqmcm.jackknife( /, vals, avg_sign, jackknife_samples = jackknife_samples, jackknife_g = jackknife_g ) end return S_avg, S_std end ```` First, let us compute the average and error for the time-displaced electron Green's function ```math G_\sigma(\mathbf{r},\tau) = \langle \hat{c}^{\phantom \dagger}_{\sigma,\mathbf{i}+\mathbf{r}}(\tau) \hat{c}^\dagger_{\sigma,\mathbf{i}}(0) \rangle ``` in position space, and ```math G_\sigma(\mathbf{k},\tau) = \langle \hat{c}^{\phantom \dagger}_{\sigma,\mathbf{k}}(\tau) \hat{c}^\dagger_{\sigma,\mathbf{k}}(0) \rangle ``` in momentum space, where ``\tau \in [0, \Delta\tau, \dots, \beta-\Delta\tau, \beta].`` ````@example square_hubbard # Fourier transform Green's function from position to momentum space. S_greens = copy(C_greens) jdqmcm.fourier_transform!(S_greens, 1, 1, (1,4), unit_cell, lattice) # Calculate average Green's function in position space. C_greens_avg, C_greens_std = correlation_stats(C_greens, avg_sign) # Calculate average Green's function in momentum space. S_greens_avg, S_greens_std = correlation_stats(S_greens, avg_sign) # Verify that the position space G(r=0,Ο„=0) measurement agrees with the # average density measurement. agreement = (2*(1-C_greens_avg[1,1,1]) β‰ˆ density_avg) println("(2*[1-G(r=0,tau=0)] == <n>) = ", agreement) ```` Now we will calculate the spin susceptibility ```math \chi_z(\mathbf{q}) = \int_0^\beta S_z(\mathbf{q},\tau) \ d\tau ``` where the time-displaced spin structure ```math S_z(\mathbf{q},\tau) = \sum_\mathbf{r} e^{-{\rm i} \mathbf{q}\cdot\mathbf{r}} \ C_z(\mathbf{r},\tau) ``` is given by the fourier transform of the spin-``z`` correlation function ```math C_z(\mathbf{r},\tau) = \frac{1}{N} \sum_\mathbf{i} \langle \hat{S}_{z,\mathbf{i}+\mathbf{r}}(\tau) \hat{S}_{z,\mathbf{i}}(0) \rangle ``` in position space. Then we report the spin-suscpetibility ``\chi_{\rm afm} = \chi_z(\pi,\pi)`` corresponding to antiferromagnetism. ````@example square_hubbard # Fourier transform the binned Cz(r,Ο„) position space spin-z correlation function # data to get the binned Sz(q,Ο„) spin-z structure factor data. S_spinz = copy(C_spinz) jdqmcm.fourier_transform!(S_spinz, 1, 1, (1,4), unit_cell, lattice) # Integrate the binned Sz(q,Ο„) spin-z structure factor data over the imaginary # time axis to get the binned Ο‡z(q) spin susceptibility. Ο‡_spinz = susceptibility(S_spinz, Δτ) # Calculate the average spin correlation functions in position space. C_spinz_avg, C_spinz_std = correlation_stats(C_spinz, avg_sign) # Calculate the average spin structure factor in momentum space. S_spinz_avg, S_spinz_std = correlation_stats(S_spinz, avg_sign) # Calculate the average spin susceptibility for all scattering momentum q. Ο‡_spinz_avg, Ο‡_spinz_std = correlation_stats(Ο‡_spinz, avg_sign) # Report the spin susceptibility Ο‡afm = Ο‡z(Ο€,Ο€) corresponding to antiferromagnetism. Ο‡afm_avg = real(Ο‡_spinz_avg[LΓ·2+1, LΓ·2+1]) Ο‡afm_std = Ο‡_spinz_std[LΓ·2+1, LΓ·2+1] println("Antiferromagentic Spin Susceptibility, chi_afm = ", Ο‡afm_avg, " +/- ", Ο‡afm_std) ```` Given the measured time-displaced density correlation function ```math C_{\rho}(\mathbf{r},\tau) = \sum_{\mathbf{i}} \langle \hat{n}_{\mathbf{i}+\mathbf{r}}(\tau) \hat{n}_{\mathbf{i}}(0) \rangle, ``` where ``\hat{n}_{\mathbf{i}} = (\hat{n}_{\mathbf{i}, \uparrow} + \hat{n}_{\mathbf{i}, \downarrow}),`` we can compute the time-displaced charge structure factor ```math S_{\rho}(\mathbf{q},\tau) = \sum_\mathbf{r} e^{-{\rm i}\mathbf{q}\cdot\mathbf{r}} \ C_{\rho}(\mathbf{r},\tau) ``` and corresponding charge susceptibility ```math \chi_{\rho}(\mathbf{q}) \int_0^\beta S_{\rho}(\mathbf{q},\tau) \ d\tau. ``` ````@example square_hubbard # Fourier transform the binned Cρ(r,Ο„) position space density correlation # data to get the time-dispaced charge structure factor Sρ(q,Ο„) in # momentum space. S_density = copy(C_density) jdqmcm.fourier_transform!(S_density, 1, 1, (1,4), unit_cell, lattice) # Integrate the binned Sρ(q,Ο„) density structure factor data over the imaginary # time axis to get the binned χρ(q) density susceptibility. Ο‡_density = susceptibility(S_density, Δτ) # Calculate the average charge correlation functions in position space. C_density_avg, C_density_std = correlation_stats(C_density, avg_sign) # Calculate the average charge structure factor in momentum space. S_density_avg, S_density_std = correlation_stats(S_density, avg_sign) # Calculate the average charge susceptibility for all scattering momentum q. Ο‡_density_avg, Ο‡_density_std = correlation_stats(Ο‡_spinz, avg_sign); nothing #hide ```` Now we calculate the local s-wave pair susceptibility ```math P_{s} = \frac{1}{N} \int_0^\beta \langle \hat{\Delta}_{s}(\tau) \hat{\Delta}_{s}(0) \rangle \ d\tau, ``` where ``\hat{\Delta}_{s} = \sum_\mathbf{i} \hat{c}_{\downarrow,\mathbf{i}} \hat{c}_{\uparrow,\mathbf{i}}.`` ````@example square_hubbard # Fourier transform binned position space local s-wave correlation function data to get # the binned momentum space local s-wave structure factor data. S_loc_swave = copy(C_loc_swave) jdqmcm.fourier_transform!(S_loc_swave, 1, 1, (1,4), unit_cell, lattice) # Integrate the binned local s-wave structure factor data to get the # binned local s-wave pair susceptibility data. P_loc_swave = susceptibility(S_loc_swave, Δτ) # Calculate the average local s-wave pair susceptibility for all scattering momentum q. P_loc_swave_avg, P_loc_swave_std = correlation_stats(P_loc_swave, avg_sign) # Report the local s-wave pair suspcetibility. Ps_avg = real(P_loc_swave_avg[1,1]) Ps_std = P_loc_swave_std[1,1] println("Local s-wave pair susceptibility, P_s = ", Ps_avg, " +/- ", Ps_std) ```` Next, we calculate the local s-wave pair susceptibility ```math P_{\textrm{ext-}s} = \frac{1}{N} \int_0^\beta \langle \hat{\Delta}_{\textrm{ext-}s}(\tau) \hat{\Delta}_{\textrm{ext-}s}(0) \rangle \ d\tau, ``` where ```math \hat{\Delta}_{\textrm{ext-}s} = \frac{1}{2} \sum_\mathbf{i} (\hat{c}_{\downarrow,\mathbf{i}+\mathbf{x}} +\hat{c}_{\downarrow,\mathbf{i}-\mathbf{x}} +\hat{c}_{\downarrow,\mathbf{i}+\mathbf{y}} +\hat{c}_{\downarrow,\mathbf{i}-\mathbf{y}}) \hat{c}_{\uparrow,\mathbf{i}}. ``` ````@example square_hubbard # Fourier transform binned position space extended s-wave correlation function data to get # the binned momentum space extended s-wave structure factor data. S_ext_swave = copy(C_ext_swave) jdqmcm.fourier_transform!(S_ext_swave, 1, 1, (1,4), unit_cell, lattice) # Integrate the binned extended s-wave structure factor data to get the # binned extended s-wave pair susceptibility data. P_ext_swave = susceptibility(S_ext_swave, Δτ) # Calculate the average extended s-wave pair susceptibility for all scattering momentum q. P_ext_swave_avg, P_ext_swave_std = correlation_stats(P_ext_swave, avg_sign) # Report the local s-wave pair suspcetibility. Pexts_avg = real(P_ext_swave_avg[1,1]) Pexts_std = P_ext_swave_std[1,1] println("Extended s-wave pair susceptibility, P_ext-s = ", Pexts_avg, " +/- ", Pexts_std) ```` Lastly, we calculate the d-wave pair susceptibility ```math P_{d} = \frac{1}{N} \int_0^\beta \langle \hat{\Delta}_{d}(\tau) \hat{\Delta}_{d}(0) \rangle \ d\tau, ``` where ```math \hat{\Delta}_{d} = \frac{1}{2} \sum_\mathbf{i} (\hat{c}_{\downarrow,\mathbf{i}+\mathbf{x}} +\hat{c}_{\downarrow,\mathbf{i}-\mathbf{x}} -\hat{c}_{\downarrow,\mathbf{i}+\mathbf{y}} -\hat{c}_{\downarrow,\mathbf{i}-\mathbf{y}}) \hat{c}_{\uparrow,\mathbf{i}}. ``` ````@example square_hubbard # Fourier transform binned position space d-wave correlation function data to get # the binned momentum space d-wave structure factor data. S_dwave = copy(C_dwave) jdqmcm.fourier_transform!(S_dwave, 1, 1, (1,4), unit_cell, lattice) # Integrate the binned d-wave structure factor data to get the # binned d-wave pair susceptibility data. P_dwave = susceptibility(S_dwave, Δτ) # Calculate the average d-wave pair susceptibility for all scattering momentum q. P_dwave_avg, P_dwave_std = correlation_stats(P_dwave, avg_sign) # Report the d-wave pair susceptibility. Pd_avg = real(P_dwave_avg[1,1]) Pd_std = P_dwave_std[1,1] println("Extended s-wave pair susceptibility, P_d = ", Pd_avg, " +/- ", Pd_std) ````
JDQMCFramework
https://github.com/SmoQySuite/JDQMCFramework.jl.git
[ "MIT" ]
0.1.0
d1b075ae5b66bb819d88d00fcde2354423d84392
code
102
using ResourceManagers @with open_file("/tmp/file.txt", "w"):f begin write(f, "Hello, world!") end
ResourceManagers
https://github.com/complyue/ResourceManagers.jl.git
[ "MIT" ]
0.1.0
d1b075ae5b66bb819d88d00fcde2354423d84392
code
4145
module ResourceManagers export @with, ResourceManager, __enter__, __exit__ export OpenFile """ abstract type ResourceManager end An abstract type representing a resource that can be managed. """ abstract type ResourceManager end """ __enter__(r::ResourceManager) Enter a context for resource management. Override this function to define what happens when the resource is acquired. """ function __enter__(r::ResourceManager) @warn "No __enter__ method defined for $(typeof(r))" return r end """ __exit__(r::ResourceManager, exc::Union{Nothing,E}) where {E<:Exception} Exit a context for resource management. Override this function to define what happens when the resource is released. """ function __exit__(r::ResourceManager, exc::Union{Nothing,E}) where {E<:Exception} @warn "No __exit__ method defined for $(typeof(r))" end """ @with pairs block A macro for simplified resource management. # Examples ```julia @with open_file("file.txt", "w") : f begin write(f, "Hello, world!") end ``` """ macro with(pairs, block) resource_pairs = [] if pairs.head == :block # Multiple resources sizehint!(resource_pairs, length(pairs.args)) for pair in filter(x -> isa(x, Expr), pairs.args) if pair.head == :call && pair.args[1] == :(:) push!(resource_pairs, (pair.args[2], pair.args[3])) elseif pair.head == :symbol || pair.head == :call || pair.head == :macrocall push!(resource_pairs, (pair, nothing)) else throw(ArgumentError("Invalid syntax. Expected assignments (resource : variable)")) end end else # Single resource if pairs.head == :call && pairs.args[1] == :(:) push!(resource_pairs, (pairs.args[2], pairs.args[3])) elseif pairs.head == :symbol || pairs.head == :call || pairs.head == :macrocall push!(resource_pairs, (pairs, nothing)) else throw(ArgumentError("Invalid syntax. Expected assignments (resource : variable)")) end end final_block = generate_with_block(resource_pairs, block) esc(final_block) end """ generate_with_block(resource_pairs, block) Generates a code block for resource management. This function is internal and used by the `@with` macro. """ function generate_with_block(resource_pairs, block) if isempty(resource_pairs) return block end (resource, as_var) = resource_pairs[1] resource_var = gensym() # Generate a unique symbol for the resource inner_block = generate_with_block((@view resource_pairs[2:end]), block) if as_var === nothing return quote local exc = nothing local $resource_var = $resource local entered_resource = __enter__($resource_var) try $inner_block catch e exc = e finally __exit__($resource_var, exc) if exc !== nothing throw(exc) end end end else return quote local exc = nothing local $resource_var = $resource local $as_var = __enter__($resource_var) try $inner_block catch e exc = e finally __exit__($resource_var, exc) if exc !== nothing throw(exc) end end end end end """ struct OpenFile <: ResourceManager A type representing a managed file, conforming to the `ResourceManager` interface. """ struct OpenFile <: ResourceManager filename::AbstractString mode::AbstractString lock::Bool file::Ref{IO} """ OpenFile(filename::AbstractString, [mode::AbstractString]; lock = true) Wrap a (to be opened) file in an `OpenFile` object for resource management. """ OpenFile( filename::AbstractString, mode::AbstractString="r"; lock=true ) = new( filename, mode, lock, Ref{IO}() ) end """ __enter__(m::OpenFile) Do open a file, as acquired resource. """ function __enter__(m::OpenFile) m.file[] = open(m.filename, m.mode; lock=m.lock) return m.file[] end """ __exit__(m::OpenFile, exc::Union{Nothing,Exception}) Release a file resource by closing it. """ function __exit__(m::OpenFile, exc::Union{Nothing,Exception}) close(m.file[]) end end # module ResourceManagers
ResourceManagers
https://github.com/complyue/ResourceManagers.jl.git
[ "MIT" ]
0.1.0
d1b075ae5b66bb819d88d00fcde2354423d84392
code
2512
using Test using ResourceManagers # Define mock resource types for testing struct DummyResource1 name::String end struct DummyResource2 name::String end # Define the __enter__ and __exit__ methods for these resources function __enter__(resource::DummyResource1) println("Entering resource: ", resource.name) return "Resource 1" end function __exit__(resource::DummyResource1, exc::Union{Nothing,Exception}) println("Exiting resource: ", resource.name) end function __enter__(resource::DummyResource2) println("Entering resource: ", resource.name) return "Resource 2" end function __exit__(resource::DummyResource2, exc::Union{Nothing,Exception}) println("Exiting resource: ", resource.name) end # Tests # Single resource, no naming @testset "Single resource without naming" begin output = @with DummyResource1("Test1") begin println("Inside block") end @test output === nothing end # Single resource with naming @testset "Single resource with naming" begin output = @with DummyResource1("Test1"):r1 begin @test r1 == "Resource 1" end end # Multiple resources without naming @testset "Multiple resources without naming" begin output = @with begin DummyResource1("Test1") DummyResource2("Test2") end begin println("Inside block") end @test output === nothing end # Multiple resources with naming @testset "Multiple resources with naming" begin output = @with begin DummyResource1("Test1"):r1 DummyResource2("Test2"):r2 end begin @test r1 == "Resource 1" @test r2 == "Resource 2" end end # Mixed resources with and without naming @testset "Mixed named and unnamed resources" begin output = @with begin DummyResource1("Test1"):r1 DummyResource2("Test2") end begin @test r1 == "Resource 1" end end @testset "Resource acquisition/release order" begin resource_order = [] struct DummyResource <: ResourceManager name::String end function __enter__(r::DummyResource) push!(resource_order, "Acquired: $(r.name)") return r end function __exit__(r::DummyResource, exc::Union{Nothing,Exception}) push!(resource_order, "Released: $(r.name)") end r1 = DummyResource("Resource 1") r2 = DummyResource("Resource 2") @with begin r1:r1_handle r2:r2_handle end begin # Perform operations with resources if needed end @test resource_order == [ "Acquired: Resource 1", "Acquired: Resource 2", "Released: Resource 2", "Released: Resource 1", ] end
ResourceManagers
https://github.com/complyue/ResourceManagers.jl.git
[ "MIT" ]
0.1.0
d1b075ae5b66bb819d88d00fcde2354423d84392
docs
3543
# ResourceManagers.jl Resource management in Julia, inspired by Python's `with` statement for resource acquisition and release. ## Authors - Compl Yue ([@complyue](https://github.com/complyue)), the designer. - ChatGPT by OpenAI, contributed to the coding and documentation. ## Table of Contents - [Authors](#authors) - [Table of Contents](#table-of-contents) - [Background](#background) - [Unique Features Compared to Julia's `do` Syntax](#unique-features-compared-to-julias-do-syntax) - [Installation](#installation) - [Usage](#usage) - [More Examples](#more-examples) - [Implementing Your Own `ResourceManager`](#implementing-your-own-resourcemanager) - [Tests](#tests) - [License](#license) ## Background The `@with` macro in this package is influenced by Python's `with` statement, which simplifies the management of resources such as file handlers, network connections, and other custom resources. While Julia has native resource management through the `do` syntax, the `@with` macro offers unique features: ### Unique Features Compared to Julia's `do` Syntax 1. **Multiple Resources**: One of the key features is the ability to manage multiple resources in a single block, which can be cumbersome with the native `do` syntax. ```julia # Using @with for multiple resources @with begin OpenFile("file1.txt", "w") : f1 OpenFile("file2.txt", "w") : f2 end begin write(f1, "Writing to file 1") write(f2, "Writing to file 2") end ``` 2. **Optional Naming**: The `@with` macro provides flexibility with optional naming of resources, enabling you to either use or omit names for the resources you are managing. ```julia # Without naming @with OpenFile("file.txt") begin # Do something end ``` By introducing these features, the `@with` macro aims to make code more readable, maintainable, and less error-prone. ## Installation To install ResourceManagers.jl, run the following command in your Julia REPL: ```julia ] add ResourceManagers ``` ## Usage Here is a quick example using `OpenFile` from this package: ```julia using ResourceManagers @with OpenFile("file.txt", "w") : f begin write(f, "Hello, world!") end ``` This ensures that `file.txt` is closed automatically after the block of code is executed. ### More Examples For managing multiple resources: ```julia @with begin OpenFile("file1.txt", "w") : f1 OpenFile("file2.txt", "w") : f2 end begin write(f1, "Writing to file 1") write(f2, "Writing to file 2") end ``` ### Implementing Your Own `ResourceManager` Implementing your own `ResourceManager` is straightforward: 1. Define your custom type. 2. Add methods for `__enter__` and `__exit__` that describe how to acquire and release the resource. This is exactly how the `OpenFile` is implemented by this package: ```julia struct OpenFile <: ResourceManager filename::AbstractString mode::AbstractString lock::Bool file::Ref{IO} OpenFile( filename::AbstractString, mode::AbstractString="r"; lock=true ) = new( filename, mode, lock, Ref{IO}() ) end function __enter__(m::OpenFile) m.file[] = open(m.filename, m.mode; lock=m.lock) return m.file[] end function __exit__(m::OpenFile, exc::Union{Nothing,Exception}) close(m.file[]) end ``` ## Tests To run tests for ResourceManagers.jl, execute the following command in your Julia REPL: ```julia ] test ResourceManagers ``` ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
ResourceManagers
https://github.com/complyue/ResourceManagers.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
code
2152
# Random variable defined by its distribution and an ID # Same id indicates same random variable # Different ids are treated as stochastic independent variables """ RandomVariable::DataType Supertype for random variables. Subtypes are [`RV`](@ref) and `[RVtransformed]`(@ref). """ abstract type RandomVariable end """ RV(distr::UnivariateDistribution, id::Int64) RV(distr::UnivariateDistribution) Characterization of a univariate random variable. It is specified by a distibution `distr` and an `id`. If only a distribution is provided, a global variable `RandomVariableCurrId` is created that keeps track of the already assigned ids. For each creation of a new random variable, a new id is assigned and the global variable increased by one. """ struct RV <: RandomVariable distr::UnivariateDistribution id::Int64 end # Function to create random variable # A global variable is used to keep track of which ids have alread been # assigned. If the global variable is not yet defined, the function does so. # Otherwise, the current id is increased by one function RV(distr::T1)::RV where {T1 <: UnivariateDistribution} try RandomVariableCurrId catch y if isa(y, UndefVarError) global RandomVariableCurrId = 1 end end id = RandomVariableCurrId global RandomVariableCurrId += 1 return RV(distr, id) end function copy(x::RV) return RV(x.distr, x.id) end # Transformed random variable """ RVtransformed(distr::UnivariateDistribution, id::Int64, fInv::Function) Characterization of a transformed univariate random variable. It is specified by a distibution `distr`, an `id` and a function `fInv`. Let `X` be a random variable and `Y = f(X)` a transformed random variable. For a union of intervals `B` associated with `Y`, the function `fInv` should return the corresponding intervals `A` associated with `X`, i.e. A = `fInv(B)` such that P(X ∈ A) = P(Y ∈ B) for an arbitrary `B`. """ struct RVtransformed <: RandomVariable distr::UnivariateDistribution id::Int64 f::Function fInv::Function end
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
code
1242
module RandomVariables using Distributions, QuadGK import Base.\, Base.diff, Base.intersect, Base.length, Base.iterate import Base.copy, Base.ndims, Base.reduce, Base.issubset, Base.union, Base.xor import Base.<, Base.>, Base.<=, Base.>=, Base.==, Base.!=, Base.in import Base.!, Base.|, Base.&, Base.⊻ import Base.+, Base.-, Base.*, Base./, Base.inv, Base.exp, Base.log, Base.sqrt import Base.abs, Base.^, Base.adjoint import Distributions.mean, Distributions.var, Distributions.skewness import Distributions.kurtosis, Distributions.std include("interval.jl") include("subset.jl") include("union.jl") include("intersect.jl") include("complement.jl") include("diffs.jl") include("RandomVariable.jl") include("events.jl") include("setAlgebra2.jl") include("probability.jl") include("operators.jl") include("transformation.jl") include("moments.jl") export not, diff, \, xor, event, eventConditional, intersect, Interval export emptyset, βˆ…, cc, oo, co, oc, length, iterate, copy, Box export box, rect, ndims, <, <= , >, >=, ==, !=, in, !, &, |, ∨, ⊻ export P, RandomVariable, RV, RVtransformed, unionDisjoint, reduce export union, issubset, +, -, *, /, inv, exp, log, sqrt, abs, adjoint, ^ export mean, var, E, skewness, kurtosis, std end
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
code
1315
# Set complement """ not(x::Interval) The complement of an interval with respect to the real numbers. The output is always a vector of intervals. """ function not(x::cc)::Vector{Interval} return union(oo(-Inf, x.l), oo(x.u, Inf)) end function not(x::oo)::Vector{Interval} return union(oc(-Inf, x.l), co(x.u, Inf)) end function not(x::co)::Vector{Interval} return union(oo(-Inf, x.l), co(x.u, Inf)) end function not(x::oc)::Vector{Interval} return union(oc(-Inf, x.l), oo(x.u, Inf)) end function not(x::emptyset)::Vector{Interval} return [oo(-Inf, Inf)] end # Vector of sets is treated as union of intervals """ not(x::Vector{Interval}) The complement of a vector of intervals with respect to the real numbers. The input vector is treated as union such that `not([co(1, 2), cc(3, 4)])` returns the intervals (-∞, 1), [2, 3) and (4, ∞). """ function not(x::Vector{T})::Vector{Interval} where {T <: Interval} if length(x) == 1 return not(x[1]) end nots = vcat(not.(x)...) outMat = Matrix{Interval}(fill(emptyset(), (length(nots), length(nots)))) for i = 1:length(nots)-1 for j = i+1:length(nots) outMat[i, j] = intersect(nots[i], nots[j]) end end return union(vec(outMat)) end
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
code
1201
""" diff(x::Interval, y::Interval) diff(x::Box, y::Box, merge::Bool) diff(x::Vector{Box}, y::Vector{Box}, merge::Bool) diff(x::Vector{Box}, y::Box, merge::Bool) diff(x::Box, y::Vector{Box}, merge::Bool) x \\ y Difference operator for two intervals or two (vectors of) boxes. Returns the subset of `x` that is not in `y`. If `merge` is true, the resulting boxes are checked if they can be merged. """ function diff(x::T1, y::T2)::Vector{Interval} where {T1, T2 <: Interval} union([x] .∩ not(y)) end (\)(x::T1, y::T2) where {T1, T2 <: Interval} = begin diff(x, y) end """ xor(x::Interval, y::Interval) xor(x::Box, y::Box) xor(x::Vector{Box}, y::Vector{Box}, merge::Bool) xor(x::Vector{Box}, y::Box, merge::Bool) xor(x::Box, y::Vector{Box}, merge::Bool) x ⊻ y Symmetric difference operator for two intervals or (vectors of) boxes. Returns a vector of intervals or boxes that are in `x` but not in `y` or in `y` but not in `x`. If `merge` is true, the resulting boxes are checked if they can be merged. """ function xor(x::T1, y::T2)::Vector{Interval} where {T1, T2 <: Interval} union([(x\y); (y\x)]) end
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
code
4529
# X: Vector of independent random variables # intevals: Vector of events such that each element in "intervals" contains as # many intervals as there are RVs in "X". The length of "intervals" might # be different from the length of "X" """ event(X::Vector{RandomVariable}, boxes::Vector{Box}) An event characterized by a vector of distinct random variables `X` and a vector of boxes. The dimension of each box must match the number of elements in `X`. The boxes must be disjoint. See also: [`Box`](@ref), [`box`](@ref), [`RandomVariable`](@ref), [`RV`](@ref), [`RVtransformed`](@ref) """ struct event X::Vector{RandomVariable} boxes::Vector{Box} function event(X::Vector{T1}, boxes::Vector{T2}) where {T1 <: RandomVariable, T2 <: Box} for i = 1:length(boxes) if boxes[i].ndims != length(X) error("Invalid dimensions") end end return new(X, boxes) end end # This function should not exist # function event(X::T1, boxes::T2){T1 <: RandomVariable, T2 <: Box} # return event([X], [boxes]) # end function event(X::T1, intervals::Vector{T2}) where {T1 <: RandomVariable, T2 <: Interval} boxes = Vector{Box}(undef, length(intervals)) for i = 1:length(intervals) boxes[i] = box([intervals[i]]) end return event([X], boxes) end function event(X::RandomVariable, interval::Interval) return event([X], [box(interval)]) end # eventConditional is a combination of two events, one for which the probability # if of interest ("of") and one event that is conditioned on ("given") # The inner constructor function checks for the IDs of random variables involved # If two events are put in that contain different vectors of random variables, # the two events are extended to contain the same random variables # Missing intervals are imputed as sure event (-Inf, Inf) """ eventConditional(of::event, given::event) A conditional event if interested in the probability of `of` given `given`. The two events must not necessarily contain the same set of random variables. The constructor function checks for overlaps and extends the two events to have matching random variables. See also: [`event`](@ref) """ struct eventConditional of::event given::event function eventConditional(of::event, given::event) if of.X == given.X return new(of, given) else id1 = (xx -> xx.id).(of.X) id2 = (xx -> xx.id).(given.X) if of.X[sortperm(id1)] == given.X[sortperm(id2)] X = of.X[sortperm(id2)] boxes1 = copy(of.boxes) for i = 1:length(boxes1) boxes1[i] = box(boxes1[i].lims[sortperm(id1)]) end boxes2 = copy(given.boxes) for i = 1:length(boxes2) boxes2[i] = box(boxes2[i].lims[sortperm(id2)]) end return new(event(X, boxes1), event(X, boxes2)) end end # Expand the events # fill in sure events id = sort(unique([id1; id2])) nRV = length(id) boxesOf = Vector{Box}(undef, length(of.boxes)) Xout = Vector{RandomVariable}(undef, nRV) boxesGiven = Vector{Box}(undef, length(given.boxes)) for i = 1:nRV if id[i] in id1 Xout[i] = of.X[findall(id1 .== id[i])[1]] else Xout[i] = given.X[findall(id2 .== id[i])[1]] end end for i = 1:length(boxesOf) temp = box(Vector{Interval}(undef, nRV)) for j = 1:length(id) if id[j] in id1 temp.lims[j] = of.boxes[i].lims[findall(id1 .== id[j])[1]] else temp.lims[j] = oo(-Inf, Inf) end end boxesOf[i] = copy(temp) end for i = 1:length(boxesGiven) temp = box(Vector{Interval}(undef, nRV)) for j = 1:length(id) if id[j] in id2 temp.lims[j] = given.boxes[i].lims[findall(id2 .== id[j])[1]] else temp.lims[j] = oo(-Inf, Inf) end end boxesGiven[i] = copy(temp) end return new(event(Xout, boxesOf), event(Xout, boxesGiven)) end end
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
code
6083
# Intersection of intervals # For two intervals x and y, returns a sinlge interval as output """ intersect(x::Interval, y::Interval) x ∩ y Intersection of two objects of type [`Interval`](@ref). The output is a single interval. """ function intersect(x::cc, y::cc)::Interval if (x.u < y.l) | (y.u < x.l) return βˆ… end if (y.l <= x.l <= y.u) & (y.l <= x.u <= y.u) return x end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return y end if x.l < y.l return cc(y.l, x.u) else return cc(x.l, y.u) end end function intersect(x::oo, y::oo)::Interval if (x.u <= y.l) | (y.u <= x.l) return βˆ… end if (y.l <= x.l <= y.u) & (y.l <= x.u <= y.u) return x end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return y end if x.l < y.l return oo(y.l, x.u) else return oo(x.l, y.u) end end function intersect(x::co, y::co)::Interval if (x.u <= y.l) | (y.u <= x.l) return βˆ… end if (y.l <= x.l <= y.u) & (y.l <= x.u <= y.u) return x end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return y end if x.l <= y.l return co(y.l, x.u) else return co(x.l, y.u) end end function intersect(x::oc, y::oc)::Interval if (x.u <= y.l) | (y.u <= x.l) return βˆ… end if (y.l <= x.l <= y.u) & (y.l <= x.u <= y.u) return x end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return y end if x.l <= y.l return oc(y.l, x.u) else return oc(x.l, y.u) end end function intersect(x::cc, y::oo)::Interval if (x.u <= y.l) | (y.u <= x.l) return βˆ… end if (y.l < x.l <= y.u) & (y.l <= x.u < y.u) return x end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return y end if x.l <= y.l return oc(y.l, x.u) else return co(x.l, y.u) end end function intersect(x::oo, y::cc)::Interval return intersect(y, x) end function intersect(x::cc, y::co)::Interval if (x.u < y.l) | (y.u <= x.l) return βˆ… end if (y.l <= x.l <= y.u) & (y.l <= x.u < y.u) return x end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return y end if x.l <= y.l return cc(y.l, x.u) else return co(x.l, y.u) end end function intersect(x::co, y::cc)::Interval return intersect(y, x) end function intersect(x::cc, y::oc)::Interval if (x.u <= y.l) | (y.u < x.l) return βˆ… end if (y.l < x.l <= y.u) & (y.l <= x.u <= y.u) return x end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return y end if x.l <= y.l return oc(y.l, x.u) else return cc(x.l, y.u) end end function intersect(x::oc, y::cc)::Interval return intersect(y, x) end function intersect(x::oo, y::co)::Interval if (x.u <= y.l) | (y.u <= x.l) return βˆ… end if (y.l < x.l <= y.u) & (y.l <= x.u <= y.u) return x end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return y end if x.l <= y.l return co(y.l, x.u) else return oo(x.l, y.u) end end function intersect(x::co, y::oo)::Interval return intersect(y, x) end function intersect(x::oo, y::oc)::Interval if (x.u <= y.l) | (y.u <= x.l) return βˆ… end if (y.l <= x.l <= y.u) & (y.l <= x.u < y.u) return x end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return y end if x.l <= y.l return oo(y.l, x.u) else return oc(x.l, y.u) end end function intersect(x::oc, y::oo)::Interval return intersect(y, x) end function intersect(x::co, y::oc)::Interval if (x.u <= y.l) | (y.u < x.l) return βˆ… end if (y.l < x.l <= y.u) & (y.l <= x.u <= y.u) return x end if (x.l <= y.l <= x.u) & (x.l <= y.u < x.u) return y end if x.l <= y.l return oo(y.l, x.u) else return cc(x.l, y.u) end end function intersect(x::oc, y::co)::Interval return intersect(y, x) end # Special treatment for empty sets function intersect(x::T, y::emptyset)::Interval where {T <: Interval} return emptyset() end function intersect(x::emptyset, y::T)::Interval where {T <: Interval} return emptyset() end function intersect(x::emptyset, y::emptyset)::Interval return emptyset() end # Intersection of a vector of intervals """ intersect(x::Vector{Interval}) ∩(x) Intersection of a vector of type [`Interval`](@ref). The intervals are intersected successively. See also: [`intersect(x::Interval, y::Interval)`](@ref) """ function intersect(x::Vector{T})::Interval where {T <: Interval} out = copy(x[1]) for i = 2:length(x) out = intersect(out, x[i]) end return out end # Intersection of two boxes, x and y """ intersect(x::Box, y::Box) x ∩ y Intersection of two boxes. The dimensions of `x` and `y` must match. A single box is returned. See also: [`Box`](@ref) """ function intersect(x::T1, y::T2)::Box where {T1, T2 <: Box} if x.ndims != y.ndims error("Invalid dimensions") end # Number of random variables nRV = x.ndims ints = Vector{Interval}(undef, nRV) for i = 1:nRV ints[i] = intersect(x.lims[i], y.lims[i]) if ints[i] == emptyset() return box(fill(emptyset(), nRV)) end end return box(ints) end function intersect(x::rect, y::rect)::rect out = Vector{Interval}(undef, 2) for i = 1:2 out[i] = intersect(x.lims[i], y.lims[i]) if out[i] == emptyset() return rect([emptyset(), emptyset()]) end end return rect(out) end
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
code
5703
# Define intervals """ Interval::DataType Abstract type for univaritate, real-valued intervals. Subtypes are intervals with lower bound `l` and upper bound `u`, i.e. the closed interval [`cc`](@ref): `[l, u]`, the open interval [`oo`](@ref): `(l, u)` and the two semi-closed intervals [`oc`](@ref): `(l, u]` and [`co`](@ref): `[l, u)` and the empty set [`βˆ…`](@ref) """ abstract type Interval end # The empty set """ emptyset() <: Interval βˆ… <: Interval The empty set, where `βˆ…` is a shortcut for emptyset() """ struct emptyset <: Interval end # Shortcut const βˆ… = emptyset() # In case the lower bound is larger than the upper bound, return empty set # closed interval [l, u] """ cc(l, u) <: Interval Closed interval of the form `[l, u]`, with lower bound `l` and upper bound `u`. Convention: If lower bound `l` exceeds upper bound `u`, return `[u, l]`. """ struct cc <: Interval l::Float64 u::Float64 function cc(l::T1, u::T2) where {T1, T2 <: Real} if l > u return cc(u, l) end if !isfinite(l) & !isfinite(u) & (sign(u) == sign(l)) return emptyset() end if isfinite(l) if isfinite(u) return new(l, u) else return co(l, u) end else if isfinite(u) return oc(-Inf, u) else return oo(-Inf, Inf) end end return new(float(l), float(u)) end end # Open interval (l, u) """ oo(l, u) <: Interval Open interval of the form `(l, u)`, with lower bound `l` and upper bound `u`. Convention: If lower bound `l` exceeds upper bound `u`, return `(u, l)`. """ struct oo <: Interval l::Float64 u::Float64 function oo(l::T1, u::T2) where {T1, T2 <: Real} if l == u return emptyset() end if l > u return oo(u, l) end if !isfinite(l) & !isfinite(u) & (sign(u) == sign(l)) return emptyset() end return new(float(l), float(u)) end end # Semi-closed interval [l, u) """ co(l, u) <: Interval Semi-closed interval of the form `[l, u)`, with lower bound `l` and upper bound `u`. Convention: If lower bound `l` exceeds upper bound `u`, return `(u, l]`. """ struct co <: Interval l::Float64 u::Float64 function co(l::T1, u::T2) where {T1, T2 <: Real} if l > u return oc(u, l) elseif l == u return cc(l, u) end if !isfinite(l) & !isfinite(u) & (sign(u) == sign(l)) return emptyset() end if isfinite(l) return new(float(l), float(u)) else return oo(l, u) end end end # Semi-closed interval (l, u] """ oc(l, u) <: Interval Semi-closed interval of the form `(l, u]`, with lower bound `l` and upper bound `u`. Convention: If lower bound `l` exceeds upper bound `u`, return `[u, l)`. """ struct oc <: Interval l::Float64 u::Float64 function oc(l::T1, u::T2) where {T1, T2 <: Real} if l > u return co(u, l) elseif l == u return cc(l, u) end if !isfinite(l) & !isfinite(u) & (sign(u) == sign(l)) return emptyset() end if isfinite(u) return new(float(l), float(u)) else return oo(l, u) end end end # For vector-wise evaluations function length(x::T) where {T <: Interval} return 1 end function iterate(x::T) where {T <: Interval} (1.00, nothing) end function iterate(x::T, nothing) where {T <: Interval} end function copy(x::T) where {T <: Interval} if x == emptyset() return emptyset() else return typeof(x)(x.l, x.u) end end """ Box::DataType Abstract supertype for [`box`}(@ref) and [`rect`](@ref). """ abstract type Box end """ box(lims::Vector{Interval}, ndims::Int64) <: Box box(lims::Vector{Interval}) <: Box A box, subset of the `ndims`-dimensional real numbers. `lims` is a vector of length `ndims` that contains the boundries in the dimensions, each being an [`Interval`](@ref). To initialize it, only the boundries can be provided. """ struct box <: Box lims::Vector{Interval} function box(lims::Vector{T}, ndims = 0) where {T <: Interval} return new(lims, ifelse(ndims == 0, length(lims), ndims)) end ndims::Int64 end function box(x::Interval) box([x], 1) end """ rect(lims::Vector{Interval}, ndims::Int64) <: Box rect(lims::Vector{Interval}) <: Box A two dimensional rectange. `lims` is a vector of length two that contains the boundries in the dimensions, each being an [`Interval`](@ref). To initialize it, only the boundries can be provided. """ struct rect <: Box lims::Vector{Interval} ndims::Int64 function rect(lims::Vector{T}, ndims::Int64 = 2) where {T <: Interval} if length(lims) != 2 error("Invalid dimensions") end return new(lims, ndims) end end function length(x::T) where {T <: Box} return 1 end function iterate(x::T) where {T <: Box} (1.00, nothing) end function iterate(x::T, nothing) where {T <: Box} end """ ndims(x <: Box)::Int64 Function to obtains the number of dimensions of a [`Box`](@ref). """ function ndims(x::T)::Int64 where {T <: Box} return x.ndims end function copy(x::T) where {T <: Box} return typeof(x)(x.lims, x.ndims) end
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
code
1055
function mean(x::RV) return Distributions.mean(x.distr) end function E(x::RV) Distributions.mean(x.distr) end function var(x::RV) return Distributions.var(x.distr) end function std(x::RV) return Distributions.std(x.distr) end function skewness(x::RV) return Distributions.skewness(x.distr) end function kurtosis(x::RV) return Distributions.kurtosis(x.distr) end # There seems to be a problem with Distributions.expectation for discrete RVs?! # function myexp(f, d::DiscreteDistribution) # sup = collect(quantile(d, 1e-10):quantile(d, 1 - 1e-10)) # return sum(pdf.(d, sup).*f.(sup)) # end function myexp(f::Function, d::DiscreteDistribution) sup = collect(quantile(d, 1e-10):quantile(d, 1 - 1e-10)) return sum(pdf.(d, sup).*f.(sup)) end function myexp(f::Function, d::ContinuousDistribution) quadgk(x -> f(x)*pdf(d, x), minimum(d), maximum(d))[1] end function mean(x::RVtransformed) myexp(x.f, x.distr) end function E(x::RVtransformed) mean(x) end
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
code
9771
# Operators that create events """ <(X::RV, y::Real) <(y::Real, X::RV) <(X::RVtransformed, y::Real) <(y::Real, X::RVtransformed) X < y y < X Operator, that takes a random variable (transformed or not) and a real number and creates an event. Instead of putting a random variable in, a distribution can be provided and a new random variable is created. """ (<)(X::RV, y::T) where {T <: Real} = begin event(X, oo(-Inf, y)) end """ <=(X::RV, y::Real) <=(y::Real, X::RV) <=(X::RVtransformed, y::Real) <=(y::Real, X::RVtransformed) X <= y y <= X Operator, that takes a random variable (transformed or not) and a real number and creates an event. Instead of putting a random variable in, a distribution can be provided and a new random variable is created. Also works with the operator ≀. """ (<=)(X::RV, y::T) where {T <: Real} = begin event(X, oc(-Inf, y)) end """ >(X::RV, y::Real) >(y::Real, X::RV) >(X::RVtransformed, y::Real) >(y::Real, X::RVtransformed) X > y y > X Operator, that takes a random variable (transformed or not) and a real number and creates an event. Instead of putting a random variable in, a distribution can be provided and a new random variable is created. """ (>)(X::RV, y::T) where {T <: Real} = begin event(X, oo(y, Inf)) end """ >=(X::RV, y::Real) >=(y::Real, X::RV) >=(X::RVtransformed, y::Real) >=(y::Real, X::RVtransformed) X >= y y >= X Operator, that takes a random variable (transformed or not) and a real number and creates an event. Instead of putting a random variable in, a distribution can be provided and a new random variable is created. Also works with the operator β‰₯. """ (>=)(X::RV, y::T) where {T <: Real} = begin event(X, co(y, Inf)) end """ ==(X::RV, y::Real) ==(y::Real, X::RV) ==(X::RVtransformed, y::Real) ==(y::Real, X::RVtransformed) X == y y == X Operator, that takes a random variable (transformed or not) and a real number and creates an event. Instead of putting a random variable in, a distribution can be provided and a new random variable is created. """ (==)(X::RV, y::T) where {T <: Real} = begin event(X, cc(y, y)) end """ !=(X::RV, y::Real) !=(y::Real, X::RV) !=(X::RVtransformed, y::Real) !=(y::Real, X::RVtransformed) X != y y != X Operator, that takes a random variable (transformed or not) and a real number and creates an event. Instead of putting a random variable in, a distribution can be provided and a new random variable is created. """ (!=)(X::RV, y::T) where {T <: Real} = begin event(X, not(cc(y, y))) end """ in(X::RV, y) in(X::RVtransformed, y) X ∈ y X βˆ‰ y Operator, that takes a random variable (transformed or not) and a vector or sequence and creates an event. Instead of putting a random variable in, a distribution can be provided and a new random variable is created. The counterevent X βˆ‰ y is also defined. """ (in)(X::RV, y::Vector{T}) where {T <: Real} = begin event(X, (z -> cc(z, z)).(y)) end (in)(X::RV, y::UnitRange) = begin event(X, (z -> cc(z, z)).(collect(y))) end (in)(X::RV, y::StepRange) = begin event(X, (z -> cc(z, z)).(collect(y))) end (in)(X::RV, y::StepRangeLen) = begin event(X, (z -> cc(z, z)).(collect(y))) end (in)(X::RV, y::Interval) = begin event([X], [y]) end # Random variable on the right hand side (<)(y::T, X::RV) where {T <: Real} = begin X > y end (<=)(y::T, X::RV) where {T <: Real} = begin X >= y end (>)(y::T, X::RV) where {T <: Real} = begin X < y end (>=)(y::T, X::RV) where {T <: Real} = begin X <= y end (==)(y::T, X::RV) where {T <: Real} = begin X == y end (!=)(y::T, X::RV) where {T <: Real} = begin X != y end # If a random variable is not defined, but only a distribution given # create a new random variable # Random variable on the left hand side # (<)(X::T1, y::T2) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # event(RV(X), oo(-Inf, y)) # end # # (<=)(X::T1, y::T2) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # event(RV(X), oc(-Inf, y)) # end # # (>)(X::T1, y::T2) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # event(RV(X), oo(y, Inf)) # end # # (>=)(X::T1, y::T2) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # event(RV(X), co(y, Inf)) # end # # (==)(X::T1, y::T2) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # event(RV(X), cc(y, y)) # end # # (!=)(X::T1, y::T2) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # event(RV(X), not(cc(y, y))) # end # # (in)(X::T1, y::Vector{T2}) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # event(RV(X), (z -> cc(z, z)).(y)) # end # # (in)(X::T, y::UnitRange) where {T <: UnivariateDistribution} = begin # event(RV(X), (z -> cc(z, z)).(collect(y))) # end # # (in)(X::T, y::StepRange) where {T <: UnivariateDistribution} = begin # event(RV(X), (z -> cc(z, z)).(collect(y))) # end # # (in)(X::T, y::StepRangeLen) where {T <: UnivariateDistribution} = begin # event(RV(X), (z -> cc(z, z)).(collect(y))) # end # # (in)(X::T, y::Interval) where {T <: UnivariateDistribution} = begin # event(RV(X), [y]) # end # Random variable on the right hand side # (<)(y::T2, X::T1) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # X > y # end # # (<=)(y::T2, X::T1) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # X >= y # end # # (>)(y::T2, X::T1) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # X < y # end # # (>=)(y::T2, X::T1) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # X <= y # end # # (==)(y::T2, X::T1) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # X == y # end # # (!=)(y::T2, X::T1) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # X != y # end # Operators involving one event """ !(A::event) !(A::eventConditional) Takes an event as input and return the counterevent. """ function !(A::event) not(A) end function !(A::eventConditional) not(A.of) | A.given end # Operators involving two events """ &(A::event, B::event) &(A::eventConditional, B::eventConditional) &(A::event, B::eventConditional) &(A::eventConditional, B::event) A & B Combination of two events. Returns the event that `A` and `B` occur. In case of conditional events, say A1|A2 and B1|B2, the resulting event ist A1 ∩ B1 | A2 ∩ B2. """ (&)(A::event, B::event) = begin A ∩ B end (&)(A::eventConditional, B::eventConditional) = begin (A.of βˆͺ B.of) | (A.given ∩ B.given) end (&)(A::event, B::eventConditional) = begin (A βˆͺ B.of) | B.given end (&)(A::eventConditional, B::event) = begin (A.of βˆͺ B) | A.given end """ |(A::event, B::event) |(A::eventConditional, B::event) A | B Combination of two events. Returns the event that `A` given that `B` occurs. Caution, this operator is not the "or" operator. If A is a conditional event, B is added as condition. See also: [`∨`](@ref) """ (|)(A::event, B::event) = begin eventConditional(A, B) end (|)(A::eventConditional, B::event) = begin eventConditional(A.of, A.given ∩ B) end """ ∨(A::event, B::event) ∨(A::eventConditional, B::eventConditional) ∨(A::event, B::eventConditional) ∨(A::eventConditional, B::event) A ∨ B Combination of two events. Returns the event that `A` or `B` occurs. In case of conditional events, say A1|A2 and B1|B2, the resulting event ist A1 βˆͺ B1 | A2 ∩ B2. """ (∨)(A::event, B::event) = begin union(A, B) end (∨)(A::eventConditional, B::eventConditional) = begin union(A.of, B.of) | intersect(A.given, B.given) end (∨)(A::event, B::eventConditional) = begin union(A, B.of) | B.given end (∨)(A::eventConditional, B::event) = begin union(A.of, B) | A.given end """ diff(A::event, B::event) diff(A::eventConditional, B::eventConditional) diff(A::event, B::eventConditional) diff(A::eventConditional, B::event) A \\ B Combination of two events. Returns the event that `A` occurs and `B` does not. Combination of two events. Returns the event that `A` or `B` occurs. In case of conditional events, say A1|A2 and B1|B2, the resulting event ist A1 \\ B1 | A2 ∩ B2. """ (\)(A::event, B::event) = begin intersect(A, not(B)) end (\)(A::eventConditional, B::eventConditional) = begin intersect(A.of, not(B.of)) | intersect(A.given, B.given) end (\)(A::event, B::eventConditional) = begin intersect(A, not(B.of)) | B.given end (\)(A::eventConditional, B::event) = begin intersect(A.of, not(B)) | A.given end """ xor(A::event, B::event) ⊻(A::event, B::event) ⊻(A::eventConditional, B::eventConditional) ⊻(A::event, B::eventConditional) ⊻(A::eventConditional, B::event) A ⊻ B Combination of two events. Returns the event that `A` occurs and `B` does not or `B` occurs and `A` does not. In case of conditional events, say A1|A2 and B1|B2, the resulting event ist A1 ⊻ B1 | A2 ∩ B2. """ function xor(A::event, B::event) A1, B1 = unifyEvents(A, B) return event(A1.X, xor(A1.boxes, B1.boxes)) end function xor(A::eventConditional, B::eventConditional) xor(A.of, B.of) | intersect(A.given, B.given) end function xor(A::event, B::eventConditional) xor(A, B.of) | B.given end function xor(A::eventConditional, B::event) xor(A.of, B) | A.given end
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
code
2072
# Probabilities of single events # Caution for discrete distributions function P(X::T1, y::cc) where {T1 <: DiscreteDistribution} cdf(X, y.u) - cdf(X, y.l) + pdf(X, y.l) end function P(X::T1, y::oo) where {T1 <: DiscreteDistribution} if y.u >= maximum(X) if !isfinite(y.u) Fu = 1 else Fu = cdf(X, y.u) - pdf(X, y.u) end else Fu = cdf(X, y.u) - pdf(X, y.u) end if y.l <= minimum(X) Fl = 0 else Fl = cdf(X, y.l) end return Fu - Fl end function P(X::T1, y::co) where {T1 <: DiscreteDistribution} if y.u >= maximum(X) if !isfinite(y.u) Fu = 1 else Fu = cdf(X, y.u) - pdf(X, y.u) end else Fu = cdf(X, y.u) - pdf(X, y.u) end if y.l < minimum(X) Fl = 0 else Fl = cdf(X, y.l) - pdf(X, y.l) end return Fu - Fl end function P(X::T1, y::oc) where {T1 <: DiscreteDistribution} if y.u >= maximum(X) Fu = 1 else Fu = cdf(X, y.u) end if y.l <= minimum(X) Fl = 0 else Fl = cdf(X, y.l) end return Fu - Fl end function P(X::T1, y::emptyset) where {T1<:DiscreteDistribution} 0.0 end function P(X::T1, y::emptyset) where {T1<:ContinuousDistribution} 0.0 end function P(X::T1, y::T2) where {T1 <: ContinuousDistribution, T2 <: Interval} cdf(X, y.u) - cdf(X, y.l) end function P(X::RV, y::T) where {T <: Interval} P(X.distr, y) end """ P(A::event) P(A::eventConditional) Computes the probability of event `A`. If A is a conditional event, i.e. A = B|C, it is computed as P(B ∩ C)/P(C). """ function P(A::event) out = 0.0 for i = 1:length(A.boxes) temp = 1.0 for j = 1:length(A.boxes[i].lims) temp *= P(A.X[j], A.boxes[i].lims[j]) end out += temp end return out end function P(A::eventConditional) P(A.of ∩ A.given)/P(A.given) end
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
code
19546
# Goal: Function to create union of two interval sets (boxes) such that # the output is a vector of disjoint boxes # Some prep functions needed # Given an interval, give out disjoint intervals whose union gives the real line # and one of the intervals is the input interval """ unionDisjoint(x::Interval) A function that splits the real numbers into disjoint intervals such that the interval `x` is one on them. """ function unionDisjoint(x::T1)::Vector{Interval} where {T1 <: Interval} # special cases if x == emptyset() return [oo(-Inf, Inf)] end if !isfinite(x.l) & !isfinite(x.u) return [oo(-Inf, Inf)] end if !isfinite(x.l) if typeof(x) in [oc, cc] return [x, oo(x.u, Inf)] else return [x, co(x.u, Inf)] end end if !isfinite(x.u) if typeof(x) in [co, cc] return [oo(-Inf, x.l), x] else return [oc(-Inf, x.l), x] end end if typeof(x) == cc return [oo(-Inf, x.l), x, oo(x.u, Inf)] elseif typeof(x) == oo return [oc(-Inf, x.l), x, co(x.u, Inf)] elseif typeof(x) == co return [oo(-Inf, x.l), x, co(x.u, Inf)] else return [oc(-Inf, x.l), x, oo(x.u, Inf)] end end # Same function as above, but for two intervals # Gives out disjoint intervals whose union forms the real line and both # input intervals are element of the output vector """ unionDisjoint(x::Vector{Interval}) A function that splits the real numbers into disjoint intervals such that each interval in `x` has a representation as union of a subset of them. """ function unionDisjoint(x::T1, y::T2)::Vector{Interval} where {T1, T2 <: Interval} out = unique([x ∩ y; xor(x, y); not(x βˆͺ y)]) keep = out .!= [emptyset()] return out[keep] end function unionDisjoint(x::Vector{T1})::Vector{Interval} where {T1 <: Interval} if length(x) == 1 return unionDisjoint(x[1]) end out = unique([x[1] ∩ x[2]; xor(x[1], x[2]); not(x[1] βˆͺ x[2])]) # Adding intervals successively for i = 3:length(x) keep = fill(true, length(out)) add = Vector{Interval}([]) for j = 1:length(out) inter = out[j] ∩ x[i] if inter != emptyset() add = [add; inter; out[j]\x[i]] # push!(add, inter, out[j] \ x[i]) keep[j] = false end end out = [out[keep]; add] end keep = out .!= [emptyset()] return out[keep] end """ increase(current::Vector{Int64}, n::Vector{Int64}) Helper function to iterate over indices. `current` gives a vector of current indices and `n` is a vector of the same length with the maximum indices. Helps when looping over an arbitrary number of indices with potentially different maximum indices. """ function increase(current::Vector{Int64}, n::Vector{Int64})::Vector{Int64} if current == n error("Reached end") end if all(current .>= n) error("Invalid current index") end # Increase last index and then check for index restrictions current[end] += 1 while any(current .> n) ind = findall(current .> n) current[ind[end] - 1] += 1 if ind[end] <= length(current) current[ind[end]:end] .= 1 end end return current end # Helper function function mergeBox(x::T1, y::T2)::Vector{Box} where {T1, T2 <: Box} if x.ndims != y.ndims error("Invalid dimensions") end if x βŠ† y return [y] end if y βŠ† x return [x] end # Create flag to indicate if two single intervals # do not overlap --> 0 # are the same --> 1 # overlap --> 2 flag = zeros(x.ndims) for i = 1:x.ndims if x.lims[i] == y.lims[i] flag[i] = 1 elseif length(union(x.lims[i], y.lims[i])) == 1 flag[i] = 2 end end # Two boxes can only be merged if they have the same single intervals # in all dimensions except for one, where they must be "mergable" if (sum(flag .!= 1) == 1) & (sum(flag .== 2) == 1) out = copy(x.lims) ind = findall(flag .== 2)[1] out[ind] = union(x.lims[ind], y.lims[ind])[1] return [box(out, x.ndims)] end return [x, y] end # another helper function, needed? function mergeOne(x::Vector{T1}) where {T1 <: Box} if length(x) == 1 return x end for i = 1:length(x) - 1 for j = i+1:length(x) temp = mergeBox(x[i], x[j]) if length(temp) == 1 return [x[setdiff(1:length(x), [i, j])]; temp[1]] end end end return x end # Function to remove empty sets and intervals that contain other intervals # Only important for the unionDisjoint # If merge = true, then the resulting boxes are checked whether they can be # unioned to one box """ reduce(x::Vector{Box}, merge::Bool) A function that takes a vector of [`Box`][@ref]s and removes - Empty boxes (where at least one boundry is the empty set) - Doubles - Boxes that contain an other box If `merge` is true, the reduced vector of boxes is checked for pairs of boxes that can be merged to one. See also: [`union(x::Box, y::Box)`](@ref) """ function reduce(x::Vector{T1}, merge::Bool = false)::Vector{Box} where {T1 <: Box} out = copy(x) # Step 1: Remove empty sets keep = fill(true, length(out)) for i = 1:length(out) if any(out[i].lims .== [emptyset()]) keep[i] = false end end out = out[keep] # Step 2: Remove doubles out = unique(out) # Step3: Remove boxes that contain other boxes keep = fill(true, length(out)) for i = 1:length(out)-1 for j = i+1:length(out) if out[i] βŠ† out[j] keep[j] = false end if out[j] βŠ† out[i] keep[i] = false end end end out = out[keep] if !merge return out end while true if length(out) == 1 return out end oneChanged = false for i = 1:length(out) - 1 for j = i+1:length(out) if !oneChanged temp = mergeBox(out[i], out[j]) if length(temp) == 1 out = [out[setdiff(1:length(out), [i, j])]; temp] oneChanged = true end end end end if !oneChanged return out end end end # Function for the same partitioning as above for two boxes """ union(x::Box, y::Box, merge::Bool)::Vector{Box} Function to union two boxes of arbitrary dimensions. It returns a vector of disjoint boxes such that their union is the union of `x`and `y`. If `merge` is true, the disjoint boxes are checked if they can be merged. """ function union(x::T1, y::T2, merge::Bool = true)::Vector{Box} where {T1, T2 <: Box} if x.ndims != y.ndims error("Invalid dimensions") end # Number of random variables nRV = x.ndims # For each dimension, divide the real line into disjoint intervals # with the two intervals being element of the partitioning allInts = Vector{Vector{Interval}}(undef, nRV) for i = 1:nRV allInts[i] = unionDisjoint(x.lims[i], y.lims[i]) end nInts = length.(allInts) out = Vector{Box}(undef, prod(nInts)) # Take one interval of each dimensions partition and build a box from them ind = ones(Int64, nRV) ind[end] = 0 for counter = 1:prod(nInts) ind = increase(ind, nInts) temp = Vector{Interval}(undef, nRV) for j = 1:nRV temp[j] = allInts[j][ind[j]] end out[counter] = box(temp) end # Then check which boxes are inside either x or y keep = fill(true, length(out)) for i = 1:length(out) if any(out[i].lims .== [emptyset()]) keep[i] = false elseif issubset(out[i], x) | issubset(out[i], y) keep[i] = true else keep[i] = false end end return reduce(out[keep], merge) end # Idea: # Provide a list of boxes, if there is an overlap, use unionDisjoint # to create non-overlapping boxes and directly return it # Repeat steps until there is no overlap anymore # Helper function # needed? function resolveOverlap(x::Vector{T1})::Vector{Box} where {T1 <: Box} n = length(x) if length(unique((z -> z.ndims).(x))) != 1 error("Invalid dimensions") end if n == 1 return x end add = Vector{Box}(undef, 0) remove = fill(false, n) for i = 1:n-1 for j = i+1:n if !remove[i] & !remove[j] temp = intersect(x[i], x[j]) if !any(temp.lims .== [emptyset()]) remove[i] = true remove[j] = true add = [add; union(x[i], x[j], false)] end end end end [x[setdiff(1:n, findall(remove))]; add] end """ union(x::Vector{Box}, y::Vector{Box}, merge::Bool)::Vector{Box} union(x::Vector{Box}, y::Box, merge::Bool)::Vector{Box} union(x::Box, y::Vector{Box}, merge::Bool)::Vector{Box} For two collections of disjoint boxes `x` and `y`, gives a vector of disjoint boxes, such that their union equals the union of `x`and `y`. If `merge` is `true`, the elements of the resulting vector are checked if they can be merged. """ # function union(x::Vector{T1}, y::Vector{T2}, merge::Bool = true)::Vector{Box} where {T1, T2 <: Box} # out = [x; y] # while true # nOld = length(out) # out = resolveOverlap(out) # if length(out) == nOld # break # end # end # return reduce(out, merge) # end # New version function union(x::Vector{T1}, merge::Bool = true)::Vector{Box} where {T1 <: Box} if length(unique((z -> z.ndims).(x))) != 1 error("Invalid dimensions") end # Number of random variables nRV = x[1].ndims nBox = length(x) if nBox == 1 return x end # For each dimension, divide the real line into disjoint intervals # with the two intervals being element of the partitioning allInts = Vector{Vector{Interval}}(undef, nRV) for i = 1:nRV intTemp = (j -> x[j].lims[i]).(1:length(x)) allInts[i] = unionDisjoint(intTemp) end nInts = length.(allInts) out = Vector{Box}(undef, prod(nInts)) # Take one interval of each dimensions partition and build a box from them ind = ones(Int64, nRV) ind[end] = 0 for counter = 1:prod(nInts) ind = increase(ind, nInts) temp = Vector{Interval}(undef, nRV) for j = 1:nRV temp[j] = allInts[j][ind[j]] end out[counter] = box(temp) end # Then check which boxes are inside one of the boxes in x keep = fill(false, length(out)) for i = 1:length(out) if !any(out[i].lims .== [emptyset()]) for j = 1:nBox if issubset(out[i], x[j]) keep[i] = true end end end end return reduce(out[keep], merge) end function union(x::Vector{T1}, y::Vector{T2}, merge::Bool = true)::Vector{Box} where {T1, T2 <: Box} return union([x; y], merge) end function union(x::Vector{T1}, y::T2, merge::Bool = true)::Vector{Box} where {T1, T2 <: Box} return union([x; y], merge) end function union(x::T1, y::Vector{T2}, merge::Bool = true)::Vector{Box} where {T1, T2 <: Box} return union([x; y], merge) end """ intersect(x::Vector{Box}, y::Vector{Box})::Vector{Box} intersect(x::Vector{Box}, y::Box)::Vector{Box} intersect(x::Box, y::Vector{Box})::Vector{Box} For two collections of disjoint boxes `x` and `y`, gives a vector of disjoint boxes, such that their union equals the union of `x`and `y`. If `merge` is `true`, the elements of the resulting vector are checked if they can be merged. """ function intersect(x::Vector{T1}, y::Vector{T2})::Vector{Box} where {T1, T2 <: Box} if length(unique([(z -> z.ndims).(x); (z -> z.ndims).(y)])) != 1 error("Invalid dimensions") end # Number of random variables nRV = x[1].ndims ints = Vector{Box}(undef, length(x)*length(y)) counter = 1 for i = 1:length(x), j = 1:length(y) ints[counter] = intersect(x[i], y[j]) counter += 1 end return reduce(ints, false) end function intersect(x::T1, y::Vector{T2})::Vector{Box} where {T1, T2 <: Box} return intersect([x], y) end function intersect(x::Vector{T1}, y::T2)::Vector{Box} where {T1, T2 <: Box} return intersect(x, [y]) end function diff(x::T1, y::T2, merge::Bool = true)::Vector{Box} where {T1, T2 <: Box} temp = union(x, y, false) keep = fill(false, length(temp)) for i = 1:length(temp) if !(temp[i] βŠ† y) & (temp[i] βŠ† x) keep[i] = true end end if any(keep) return reduce(temp[keep], merge) else return [box(fill(emptyset(), x.ndims))] end end function diff(x::Vector{T1}, y::Vector{T2}, merge::Bool = true)::Vector{Box} where {T1, T2 <: Box} temp = union(x, y, false) keep = fill(false, length(temp)) for i = 1:length(temp) if !(temp[i] βŠ† y) & (temp[i] βŠ† x) keep[i] = true end end if any(keep) return reduce(temp[keep], merge) else return [box(fill(emptyset(), x[1].ndims))] end end function diff(x::T1, y::Vector{T2}, merge::Bool = true)::Vector{Box} where {T1, T2 <: Box} return diff([x], y, merge) end function diff(x::Vector{T1}, y::T2, merge::Bool = true)::Vector{Box} where {T1, T2 <: Box} return diff(x, [y], merge) end (\)(x::T1, y::T2) where {T1, T2 <: Box} = begin diff(x, y) end (\)(x::Vector{T1}, y::T2) where {T1, T2 <: Box} = begin diff(x, y) end (\)(x::T1, y::Vector{T2}) where {T1, T2 <: Box} = begin diff(x, y) end (\)(x::Vector{T1}, y::Vector{T2}) where {T1, T2 <: Box} = begin diff(x, y) end function xor(x::T1, y::T2, merge::Bool = true)::Vector{Box} where {T1, T2 <: Box} out = union(x, y, false) keep = fill(false, length(out)) for i = 1:length(out) if (out[i] βŠ† y) & !(out[i] βŠ† x) keep[i] = true end if (out[i] βŠ† x) & !(out[i] βŠ† y) keep[i] = true end end if any(keep) return reduce(out[keep], merge) else return [box(fill(emptyset(), x.ndims))] end end function xor(x::Vector{T1}, y::Vector{T2}, merge::Bool = true)::Vector{Box} where {T1, T2 <: Box} out = union(x, y, false) keep = fill(false, length(out)) for i = 1:length(out) if (out[i] βŠ† y) & !(out[i] βŠ† x) keep[i] = true end if (out[i] βŠ† x) & !(out[i] βŠ† y) keep[i] = true end end if any(keep) return reduce(out[keep], merge) else return [box(fill(emptyset(), x.ndims))] end end function xor(x::Vector{T1}, y::T2, merge::Bool = true)::Vector{Box} where {T1, T2 <: Box} return xor(x, [y], merge) end function xor(x::T1, y::Vector{T2}, merge::Bool = true)::Vector{Box} where {T1, T2 <: Box} return xor([x], y, merge) end """ not(x::Box, merge::Bool)::Vector{Box} not(x::Vector{Box}, merge::Bool)::Vector{Box} Computes the complement of a box or the complement of a union of boxes. If `merge` is `true`, the elements of the resulting vector are checked if they can be merged. """ function not(x::T1, merge::Bool = true)::Vector{Box} where {T1 <: Box} n = x.ndims y = box(fill(oo(-Inf, Inf), n)) out = union(x, y, false) keep = fill(true, length(out)) for i = 1:length(out) if out[i] βŠ† x keep[i] = false end end if any(keep) return reduce(out[keep], merge) else return return [box(fill(emptyset(), n))] end end function not(x::Vector{T1}, merge::Bool = true)::Vector{Box} where {T1 <: Box} if length(unique((z -> z.ndims).(x))) != 1 error("Invalid dimensions") end n = x[1].ndims y = box(fill(oo(-Inf, Inf), n)) out = union(x, y, false) keep = fill(true, length(out)) for i = 1:length(out) for j = 1:length(x) if out[i] βŠ† x[j] keep[i] = false end end end if any(keep) return reduce(out[keep], merge) else return return [box(fill(emptyset(), n))] end end # Now above functions can be applied to events # Step 1: Extend the vectors of random variables to be equal # (Use ordering for boxes, fill in with sure event (-Inf, Inf)) # Step 2: Apply above function to the boxes function unifyEvents(A::event, B::event)::Tuple{event, event} X1 = copy(A.X) X2 = copy(B.X) boxes1 = copy(A.boxes) boxes2 = copy(B.boxes) id1 = (xx-> xx.id).(A.X) id2 = (xx-> xx.id).(B.X) # Step 1: Extend the events to have matching RVs for i = 1:length(id2) if !(id2[i] in id1) id1 = [id1; id2[i]] X1 = [X1; X2[i]] for j = 1:length(boxes1) boxes1[j] = box([boxes1[j].lims; oo(-Inf, Inf)], boxes1[j].ndims + 1) end end end for i = 1:length(id1) if !(id1[i] in id2) id2 = [id2; id1[i]] X2 = [X2; X1[i]] for j = 1:length(boxes2) boxes2[j] = box([boxes2[j].lims; oo(-Inf, Inf)], boxes2[j].ndims + 1) end end end # Step 2: Sort the events by RV id o = sortperm(id1) id1 = id1[o] X1 = X1[o] for i = 1:length(boxes1) boxes1[i] = box(boxes1[i].lims[o]) end o = sortperm(id2) id2 = id2[o] X2 = X2[o] for i = 1:length(boxes2) boxes2[i] = box(boxes2[i].lims[o]) end return event(X1, boxes1), event(X2, boxes2) end # Union of two events, potentially involving different random variables """ union(A::event, B::event, merge::Bool)::event A βˆͺ B Union of two events `A` and `B`. Returns the event that `A` occurs or `B` or both. If `merge` is true, the vector of boxes in the resulting event are unioned if possible. """ function union(A::event, B::event, merge::Bool = true)::event A1, B1 = unifyEvents(A, B) return event(A1.X, union(A1.boxes, B1.boxes, merge)) end # Same for intersections """ intersect(A::event, B::event)::event A ∩ B Intersection of two events `A` and `B`. Returns the event that events `A` and `B` occur. """ function intersect(A::event, B::event)::event A1, B1 = unifyEvents(A, B) return event(A1.X, intersect(A1.boxes, B1.boxes)) end """ not(A::event)::event The complementary event of an event `A`. """ function not(A::event)::event return event(A.X, not(A.boxes)) end
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
code
3101
# Input: two intervals x and y # Output: true if x βŠ† y and false otherwise # For two intervals of the same type """ issubset(x, y)::Bool x βŠ† y y βŠ‡ x Function to check if `x` is a subset of `y`. The inputs can either both be of type [`Interval`](@ref) or of type [`Box`](@ref). It can also be used as operators `βŠ†` and `βŠ‡`. """ function issubset(x::T, y::T)::Bool where {T <: Interval} if (y.l <= x.l <= y.u) & (y.l <= x.u <= y.u) return true end return false end # Special treatment for empty sets function issubset(x::T1, y::emptyset)::Bool where {T1 <: Interval} return false end function issubset(x::emptyset, y::T1)::Bool where {T1 <: Interval} return true end function issubset(x::emptyset, y::emptyset)::Bool return true end # For two different types of intervals function issubset(x::cc, y::oo)::Bool if (y.l < x.l < y.u) & (y.l < x.u < y.u) return true end return false end function issubset(x::cc, y::co)::Bool if (y.l <= x.l <= y.u) & (y.l <= x.u < y.u) return true end return false end function issubset(x::cc, y::oc)::Bool if (y.l < x.l <= y.u) & (y.l <= x.u <= y.u) return true end return false end function issubset(x::oo, y::cc)::Bool if (y.l <= x.l <= y.u) & (y.l <= x.u <= y.u) return true end return false end function issubset(x::oo, y::co)::Bool if (y.l <= x.l <= y.u) & (y.l <= x.u <= y.u) return true end return false end function issubset(x::oo, y::oc)::Bool if (y.l <= x.l <= y.u) & (y.l <= x.u <= y.u) return true end return false end function issubset(x::co, y::cc)::Bool if (y.l <= x.l <= y.u) & (y.l <= x.u <= y.u) return true end return false end function issubset(x::co, y::oo)::Bool if (y.l < x.l <= y.u) & (y.l <= x.u <= y.u) return true end return false end function issubset(x::co, y::oc)::Bool if (y.l < x.l <= y.u) & (y.l <= x.u <= y.u) return true end return false end function issubset(x::oc, y::cc)::Bool if (y.l <= x.l <= y.u) & (y.l <= x.u <= y.u) return true end return false end function issubset(x::oc, y::oo)::Bool if (y.l <= x.l <= y.u) & (y.l <= x.u < y.u) return true end return false end function issubset(x::oc, y::co)::Bool if (y.l <= x.l <= y.u) & (y.l <= x.u < y.u) return true end return false end # For boxes function issubset(x::T1, y::T2)::Bool where {T1, T2 <: Box} if x.ndims != y.ndims return false end for i = 1:x.ndims if !(x.lims[i] βŠ† y.lims[i]) return false end end return true end function issubset(x::T1, y::Vector{T2})::Bool where {T1, T2 <: Box} if !all(x.ndims .== (z -> z.ndims).(y)) return false end for i = 1:length(y) if (x βŠ† y[i]) return true end end return false end
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
code
18170
""" +(X::RandomVariable, y::Real) +(y::Real, X::RandomVariable) X + y y + X Transformation of the random variable `X`. Returns a tranformed random variable Z = X + y. Instead of a random variable, a distribution can be provided and a new random variable is created. """ (+)(X::T1, y::T2) where {T1 <: RandomVariable, T2 <: Real} = begin f = function(z::T3) where {T3 <: Real}; z + y end fInv = function(z::Vector{T3}) where {T3 <: Interval}; out = Vector{Interval}(undef, length(z)) for i = 1:length(z) if z[i] != emptyset() out[i] = typeof(z[i])(z[i].l - y, z[i].u - y) else out[i] = emptyset() end end return union(out) end if typeof(X) == RV return RVtransformed(X.distr, X.id, f, fInv) else return RVtransformed(X.distr, X.id, f ∘ X.f, X.fInv ∘ fInv) end end (+)(y::T2, X::T1) where {T1 <: RandomVariable, T2 <: Real} = begin X + y end """ *(X::RandomVariable, y::Real) *(y::Real, X::RandomVariable) X * y y * X Transformation of the random variable `X`. Returns a tranformed random variable Z = X * y. Instead of a random variable, a distribution can be provided and a new random variable is created. """ (*)(X::T1, y::T2) where {T1 <: RandomVariable, T2 <: Real} = begin f = function(z::T3) where {T3 <: Real}; z * y end if y != 0 fInv = function(z::Vector{T3}) where {T3 <: Interval} out = Vector{Interval}(undef, length(z)) for i = 1:length(z) if z[i] != emptyset() out[i] = typeof(z[i])(z[i].l/y, z[i].u/y) else out[i] = emptyset() end end return union(out) end else fInv = function(z::Vector{T3}) where {T3 <: Interval} for i = 1:length(z) if z[i] != emptyset() if z[i].l <= 0 <= z[i].u return [oo(-Inf, Inf)] end end end return [emptyset()] end end if typeof(X) == RV return RVtransformed(X.distr, X.id, f, fInv) else return RVtransformed(X.distr, X.id, f ∘ X.f, X.fInv ∘ fInv) end end (*)(y::T2, X::T1) where {T1 <: RandomVariable, T2 <: Real} = begin X*y end """ -(X::RandomVariable, y::Real) -(y::Real, X::RandomVariable) X - y y - X Transformation of the random variable `X`. Returns a tranformed random variable Z = X - y or Z = y - X. Instead of a random variable, a distribution can be provided and a new random variable is created. """ (-)(X::T1, y::T2) where {T1 <: RandomVariable, T2 <: Real} = begin X + (-y) end (-)(y::T2, X::T1) where {T1 <: RandomVariable, T2 <: Real} = begin y + X*(-1) end (-)(X::T1) where {T1 <: RandomVariable} = begin X*(-1) end """ inv(X::RandomVariable) Transformation of the random variable `X`. Returns a tranformed random variable Z = X^{-1}. Instead of a random variable, a distribution can be provided and a new random variable is created. """ function inv(X::T) where {T <: RandomVariable} f = function(z::T3) where {T3 <: Real}; 1/z end if typeof(X) == RV if typeof(X.distr) <: DiscreteDistribution if pdf(X.distr, 0) > 0 error("Invalid distribution, division by zero") end end else if sum(P.(X.distr, X.fInv([cc(0, 0)]))) != 0 error("Invalid distribution, division by zero") end end fInv = function(z::Vector{T2}) where {T2 <: Interval} out = Matrix{Interval}(fill(emptyset(), length(z), 2)) for i = 1:length(z) if (z[i] != emptyset()) & (z[i] != cc(0, 0)) if (z[i].l) <= 0 & (z[i].u >= 0) if typeof(z[i]) in [cc, co] out[i, 1] = oc(-Inf, 1/z[i].l) else out[i, 1] = oo(-Inf, 1/z[i].l) end if typeof(z[i]) in [cc, oc] out[i, 2] = co(1/z[i].u, Inf) else out[i, 2] = oo(1/z[i].u, Inf) end else out[i, 1] = typeof(z[i])(1/z[i].l, 1/z[i].u) end end end return union(vec(out)) end if typeof(X) == RV return RVtransformed(X.distr, X.id, f, fInv) else return RVtransformed(X.distr, X.id, f ∘ X.f, X.fInv ∘ fInv) end end """ /(X::RandomVariable, y::Real) /(y::Real, X::RandomVariable) X / y y / X Transformation of the random variable `X`. Returns a tranformed random variable Z = X / y or Z = y / X. Also works with the left division y\\X and X\\y. Instead of a random variable, a distribution can be provided and a new random variable is created. """ (/)(X::T1, y::T2) where {T1 <: RandomVariable, T2 <: Real} = begin if y == 0 error("Division by zero") end X * (1/y) end (/)(y::T2, X::T1) where {T1 <: RandomVariable, T2 <: Real} = begin inv(X)*y end # To include the left division operator function adjoint(x::RandomVariable) return x end """ exp(X::RandomVariable) Transformation of the random variable `X`. Returns a tranformed random variable Z = exp(X). Instead of a random variable, a distribution can be provided and a new random variable is created. """ function exp(X::T) where {T <: RandomVariable} f = function(z::T3) where {T3 <: Real}; exp(z) end fInv = function(z::Vector{T2}) where {T2 <: Interval} out = Vector{Interval}(undef, length(z)) for i = 1:length(z) if z[i] != emptyset() if z[i].l > 0 out[i] = typeof(z[i])(log(z[i].l), log(z[i].u)) else if z[i].u > 0 out[i] = ifelse(typeof(z[i]) in [cc, oc], oc, oo)(-Inf, log(z[i].u)) else out[i] = emptyset() end end else out[i] = emptyset() end end return union(out) end if typeof(X) == RV return RVtransformed(X.distr, X.id, f, fInv) else return RVtransformed(X.distr, X.id, f ∘ X.f, X.fInv ∘ fInv) end end """ log(X::RandomVariable) Transformation of the random variable `X`. Returns a tranformed random variable Z = log(X). Instead of a random variable, a distribution can be provided and a new random variable is created. """ function log(X::T) where {T <: RandomVariable} f = function(z::T3) where {T3 <: Real}; log(z) end if typeof(X) == RV if minimum(X.distr) < 0 error("Invalid distribution") end else if sum(P.(X.distr, X.fInv([oo(-Inf, 0)]))) > 0 error("Invalid distribution") end end fInv = function(z::Vector{T2}) where {T2 <: Interval} out = Vector{Interval}(undef, length(z)) for i = 1:length(z) if z[i] != emptyset() out[i] = typeof(z[i])(exp(z[i].l), exp(z[i].u)) else out[i] = emptyset() end end return union(out) end if typeof(X) == RV return RVtransformed(X.distr, X.id, f, fInv) else return RVtransformed(X.distr, X.id, f ∘ X.f, X.fInv ∘ fInv) end end """ sqrt(X::RandomVariable) Transformation of the random variable `X`. Returns a tranformed random variable Z = sqrt(X). Also works as √X. Instead of a random variable, a distribution can be provided and a new random variable is created. """ function sqrt(X::T) where {T <: RandomVariable} f = function(z::T3) where {T3 <: Real}; sqrt(z) end if typeof(X) == RV if minimum(X.distr) < 0 error("Invalid distribution") end else if sum(P.(X.distr, X.fInv([oo(-Inf, 0)]))) > 0 error("Invalid distribution") end end fInv = function(z::Vector{T2}) where {T2 <: Interval} out = Vector{Interval}(undef, length(z)) for i = 1:length(z) if z[i] != emptyset() if z[i].l > 0 out[i] = typeof(z[i])(z[i].l^2, z[i].u^2) else if z[i].u > 0 out[i] = ifelse(typeof(z[i]) in [cc, oc], cc, co)(0, z[i].u^2) else out[i] = emptyset() end end else out[i] = emptyset() end end return union(out) end if typeof(X) == RV return RVtransformed(X.distr, X.id, f, fInv) else return RVtransformed(X.distr, X.id, f ∘ X.f, X.fInv ∘ fInv) end end """ abs(X::RandomVariable) Transformation of the random variable `X`. Returns a tranformed random variable Z = |X|. Instead of a random variable, a distribution can be provided and a new random variable is created. """ function abs(X::T) where {T <: RandomVariable} f = function(z::T3) where {T3 <: Real}; abs(z) end fInv = function(z::Vector{T2}) where {T2 <: Interval} out = Matrix{Interval}(fill(emptyset(), length(z), 2)) for i = 1:length(z) if z[i] != emptyset() if z[i].u >= 0 if z[i].l >= 0 out[i, 1] = z[i] out[i, 2] = typeof(z[i])(-z[i].l, -z[i].u) else if typeof(z[i]) in [cc, oc] out[i, 1] = cc(-z[i].u, z[i].u) else out[i, 1] = oo(-z[i].u, z[i].u) end end end end end return union(vec(out)) end if typeof(X) == RV return RVtransformed(X.distr, X.id, f, fInv) else return RVtransformed(X.distr, X.id, f ∘ X.f, X.fInv ∘ fInv) end end # Internal function powI(X::T, y::Integer) where {T <: RandomVariable} f = function(z::T3) where {T3 <: Real}; z^y end if iseven(y) fInv = function(z::Vector{T2}) where {T2 <: Interval} out = Matrix{Interval}(fill(emptyset(), length(z), 2)) for i = 1:length(z) if z[i] != emptyset() if z[i].u >= 0 if z[i].l >= 0 out[i, 1] = typeof(z[i])(z[i].l^(1/y), z[i].u^(1/y)) out[i, 2] = typeof(z[i])(-(z[i].l^(1/y)), -(z[i].u^(1/y))) else if typeof(z[i]) in [cc, oc] out[i, 1] = cc(-(z[i].u^(1/y)), z[i].u^(1/y)) else out[i, 1] = oo(-(z[i].u^(1/y)), z[i].u^(1/y)) end end end end end return union(vec(out)) end else fInv = function(z::Vector{T2}) where {T2 <: Interval} out = Vector{Interval}(undef, length(z)) for i = 1:length(z) if z[i] != emptyset() out[i] = typeof(z[i])(sign(z[i].l)*abs(z[i].l)^(1/y), sign(z[i].u)*abs(z[i].u)^(1/y)) else out[i] = emptyset() end end return union(out) end end if typeof(X) == RV return RVtransformed(X.distr, X.id, f, fInv) else return RVtransformed(X.distr, X.id, f ∘ X.f, X.fInv ∘ fInv) end end function powF(X::T, y::Float64) where {T <: RandomVariable} f = function(z::T3) where {T3 <: Real}; z^y end if typeof(X) == RV if minimum(X.distr) < 0 error("Invalid distribution") end else if sum(P.(X.distr, X.fInv([oo(-Inf, 0)]))) > 0 error("Invalid distribution") end end fInv = function(z::Vector{T2}) where {T2 <: Interval} out = Vector{Interval}(undef, length(z)) for i = 1:length(z) if z[i] != emptyset() if z[i].l > 0 out[i] = typeof(z[i])(z[i].l^(1/y), z[i].u^(1/y)) else if z[i].u > 0 out[i] = ifelse(typeof(z[i]) in [cc, oc], cc, co)(0, z[i].u^(1/y)) else out[i] = emptyset() end end else out[i] = emptyset() end end return union(out) end if typeof(X) == RV return RVtransformed(X.distr, X.id, f, fInv) else return RVtransformed(X.distr, X.id, f ∘ X.f, X.fInv ∘ fInv) end end """ ^(X::RandomVariable, y::Real) X^y Transformation of the random variable `X`. Returns a tranformed random variable Z = X^y. Instead of a random variable, a distribution can be provided and a new random variable is created. """ (^)(X::T1, y::T2) where {T1 <: RandomVariable, T2 <: Real} = begin if y == floor(y) if y == 0 error("Zero not allowed as exponent") end if y < 0 return powI(inv(X), Int64(y)) else return powI(X, Int64(y)) end else if y < 0 return powF(inv(X), Float64(y)) else return powF(X, Float64(y)) end end end # Now operators to create events # Operators that create events # Random variable on the left hand side (<)(X::RVtransformed, y::T) where {T <: Real} = begin event(RV(X.distr, X.id), X.fInv([oo(-Inf, y)])) end (<=)(X::RVtransformed, y::T) where {T <: Real} = begin event(RV(X.distr, X.id), X.fInv([oc(-Inf, y)])) end (>)(X::RVtransformed, y::T) where {T <: Real} = begin event(RV(X.distr, X.id), X.fInv([oo(y, Inf)])) end (>=)(X::RVtransformed, y::T) where {T <: Real} = begin event(RV(X.distr, X.id), X.fInv([co(y, Inf)])) end (==)(X::RVtransformed, y::T) where {T <: Real} = begin event(RV(X.distr, X.id), X.fInv([cc(y, y)])) end (!=)(X::RVtransformed, y::T) where {T <: Real} = begin event(RV(X.distr, X.id), X.fInv(not(cc(y, y)))) end (in)(X::RVtransformed, y::Vector{T}) where {T <: Real} = begin event(RV(X.distr, X.id), X.fInv((z -> cc(z, z)).(y))) end (in)(X::RVtransformed, y::UnitRange) = begin event(RV(X.distr, X.id), X.fInv((z -> cc(z, z)).(collect(y)))) end (in)(X::RVtransformed, y::StepRange) = begin event(RV(X.distr, X.id), X.fInv((z -> cc(z, z)).(collect(y)))) end (in)(X::RVtransformed, y::StepRangeLen) = begin event(RV(X.distr, X.id), X.fInv((z -> cc(z, z)).(collect(y)))) end (in)(X::RVtransformed, y::Interval) = begin event(RV(X.distr, X.id), X.fInv([y])) end # Random variable on the right hand side (<)(y::T, X::RVtransformed) where {T <: Real} = begin X > y end (<=)(y::T, X::RVtransformed) where {T <: Real} = begin X >= y end (>)(y::T, X::RVtransformed) where {T <: Real} = begin X < y end (>=)(y::T, X::RVtransformed) where {T <: Real} = begin X <= y end (==)(y::T, X::RVtransformed) where {T <: Real} = begin X == y end (!=)(y::T, X::RVtransformed) where {T <: Real} = begin X != y end # And agin the lazy way where random variables are created on the fly # (+)(X::T1, y::T2) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # RV(X) + y # end # (+)(y::T2, X::T1) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # RV(X) + y # end # # (-)(X::T1, y::T2) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # RV(X) - y # end # (-)(y::T2, X::T1) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # RV(X) - y # end # (-)(X::T1) where {T1 <: UnivariateDistribution} = begin # RV(X)*(-1) # end # (-)(X::T1) where {T1 <: RandomVariable} = begin # X*(-1) # end # # (*)(X::T1, y::T2) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # RV(X) * y # end # (*)(y::T2, X::T1) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # RV(X) + y # end # # (/)(X::T1, y::T2) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # if y == 0 # error("Division by zero") # end # RV(X)/y # end # # (/)(y::T2, X::T1) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # y/RV(X) # end # # function inv(X::T) where {T <: UnivariateDistribution} # inv(RV(X)) # end # # function exp(X::T) where {T <: UnivariateDistribution} # exp(RV(X)) # end # # function log(X::T) where {T <: UnivariateDistribution} # log(RV(X)) # end # # function sqrt(X::T) where {T <: UnivariateDistribution} # sqrt(RV(X)) # end # # function abs(X::T) where {T <: UnivariateDistribution} # abs(RV(X)) # end # # (^)(X::T1, y::T2) where {T1 <: UnivariateDistribution, T2 <: Real} = begin # RV(X)^y # end
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
code
6652
# Union of intervals # Input: Two intervals x and y # Output: always vector of intervals # If x and y do not overlap, it returns a vector of two # If x and y overlap, it returns a vetor of length one """ union(x::Interval, y::Interval) x βˆͺ y Union of two objects of type [`Interval`](@ref). The output is always a vector of intervals. If `x` and `y` overlap, the output has one element and two elements if not. """ function union(x::cc, y::cc)::Vector{Interval} if (x.u < y.l) | (x.l > y.u) return [x, y] end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return [x] end if (y.l <= x.l <= y.u) & (y.l <= x.u <= y.u) return [y] end return [cc(minimum([x.l, y.l]), maximum([x.u, y.u]))] end function union(x::oo, y::oo)::Vector{Interval} if (x.u <= y.l) | (x.l >= y.u) return [x, y] end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return [x] end if (y.l <= x.l <= y.u) & (y.l <= x.u <= y.u) return [y] end return [oo(minimum([x.l, y.l]), maximum([x.u, y.u]))] end function union(x::oc, y::oc)::Vector{Interval} if (x.u < y.l) | (x.l > y.u) return [x, y] end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return [x] end if (y.l <= x.l <= y.u) & (y.l <= x.u <= y.u) return [y] end return [oc(minimum([x.l, y.l]), maximum([x.u, y.u]))] end function union(x::co, y::co)::Vector{Interval} if (x.u < y.l) | (x.l > y.u) return [x, y] end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return [x] end if (y.l <= x.l <= y.u) & (y.l <= x.u <= y.u) return [y] end return [co(minimum([x.l, y.l]), maximum([x.u, y.u]))] end function union(x::cc, y::oo)::Vector{Interval} if (x.u < y.l) | (x.l > y.u) return [x, y] end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return [x] end if (y.l < x.l < y.u) & (y.l < x.u < y.u) return [y] end if x.l <= y.l return [co(x.l, y.u)] else return [oc(y.l, x.u)] end end function union(x::oo, y::cc)::Vector{Interval} return union(y, x) end function union(x::cc, y::co)::Vector{Interval} if (x.u < y.l) | (x.l > y.u) return [x, y] end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return [x] end if (y.l <= x.l <= y.u) & (y.l <= x.u < y.u) return [y] end if x.l < y.l return [co(x.l, y.u)] else return [cc(y.l, x.u)] end end function union(x::co, y::cc)::Vector{Interval} return union(y, x) end function union(x::cc, y::oc)::Vector{Interval} if (x.u < y.l) | (x.l > y.u) return [x, y] end if (x.l <= y.l <= x.u) & (x.l <= y.u <= x.u) return [x] end if (y.l < x.l <= y.u) & (y.l <= x.u <= y.u) return [y] end if x.l <= y.l return [cc(x.l, y.u)] else return [oc(y.l, x.u)] end end function union(x::oc, y::cc)::Vector{Interval} return union(y, x) end function union(x::oo, y::co)::Vector{Interval} if (x.u < y.l) | (x.l >= y.u) return [x, y] end if (x.l < y.l <= x.u) & (x.l <= y.u <= x.u) return [x] end if (y.l <= x.l < y.u) & (y.l <= x.u <= y.u) return [y] end if x.l < y.l return [oo(x.l, y.u)] else return [co(y.l, x.u)] end end function union(x::co, y::oo)::Vector{Interval} return union(y, x) end function union(x::oo, y::oc)::Vector{Interval} if (x.u <= y.l) | (x.l > y.u) return [x, y] end if (x.l <= y.l <= x.u) & (x.l <= y.u < x.u) return [x] end if (y.l <= x.l <= y.u) & (y.l <= x.u <= y.u) return [y] end if x.l < y.l return [oc(x.l, y.u)] else return [oo(y.l, x.u)] end end function union(x::oc, y::oo)::Vector{Interval} return union(y, x) end function union(x::co, y::oc)::Vector{Interval} if (x.u <= y.l) | (x.l > y.u) return [x, y] end if (x.l <= y.l <= x.u) & (x.l <= y.u < x.u) return [x] end if (y.l < x.l <= y.u) & (y.l <= x.u <= y.u) return [y] end if x.l <= y.l return [cc(x.l, y.u)] else return [oo(y.l, x.u)] end end function union(x::oc, y::co)::Vector{Interval} return union(y, x) end function union(x::T1, y::emptyset)::Vector{Interval} where {T1 <: Interval} return [x] end function union(x::emptyset, y::T1)::Vector{Interval} where {T1 <: Interval} return [y] end function union(x::emptyset, y::emptyset)::Vector{Interval} return [emptyset()] end # Vector wise operation # For a collection if intervals, find the union """ union(x::Vector{Interval}) βˆͺ(x) Union of a vector of type [`Interval`](@ref). The intervals are unioned pairwise until there is no overlap in the single intervals. See also: [`union(x::Interval, y::Interval)`](@ref) """ function union(x::Vector{T})::Vector{Interval} where {T <: Interval} out = Vector{Interval}(x) n = length(out) if n == 1 return out end # Go through all combinations and find overlaps # In an overlap is found, replace one interval by the union and remove # the other isempty = fill(false, n) for i = 1:n if out[i] == emptyset() isempty[i] = true end end while true changedOne = false for i = 1:n-1 for j = i+1:n if !isempty[i] & !isempty[j] setTemp = union(out[i], out[j]) if length(setTemp) == 1 if setTemp[1] == out[i] out[j] = emptyset() isempty[j] = true elseif setTemp[1] == out[j] out[i] = emptyset() isempty[i] = true else out[i] = setTemp[1] out[j] = emptyset() isempty[j] = true end changedOne = true end end end end if !changedOne if any(.!isempty) return out[.!isempty] else return [emptyset()] end end end end
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
code
4315
using RandomVariables using Test using Distributions @testset "RandomVariables.jl" begin X1 = RV(Poisson(4.2)) X2 = RV(Normal()) X3 = RV(Normal(1, 2)) A = (X1 in 1:5) & (X2 < 3) & (X2 > 0) B = (X1 != 2) & (log(abs(X3) + 1) < 2) P(A) P(B) P(A|B) P(A & B) P(A ∨ B) A \ B P(A ⊻ B) P(!(A)) not(cc(1, 2)) not(oo(1, 2)) not(co(1, 2)) not(oc(1, 2)) not(emptyset()) not(not(cc(1, 2))) d = RV(Poisson(1)) d in 1:10 d in 1:1:10 d in 1:0.5:10 d in [1, 2] 1 < d 1 <= d 1 > d 1 >= d 1 == d 1 != d (X1 < 10) \ (X1 <= 3) 1 + X1 2*X1 X1 - 1 -X1 inv(inv(X1 + 1)) 2/(X1 + 1) (X1 + 1)\2 exp(X1) X4 = sqrt(X1^1.4) 1 < X4 1 <= X4 1 > X4 1 >= X4 1 == X4 1 != X4 X4 in 1:10 X4 in 1:1:10 X4 in 1:0.5:10 X4 in [1, 2] inv(RV(Exponential(2))) exp(d) sqrt(RV(Exponential(2))) abs(d) d^3 [cc(1, 2), cc(3, 4)] .∩ cc(2, 3) copy(cc(1, 2)) C = rect([cc(1, 2), cc(1, 2)]) D = rect([oo(1, 2), oo(1, 2)]) union(C, D) E(X1) mean(X1) var(X1) skewness(X1) kurtosis(X1) X1 >= 1 X1 == 1 X1 in [1, 2] X1 in 1:2:10 X1 in 1:2.0:10 1 < X1 1 <= X1 1 > X1 1 >= X1 1 == X1 1 != X1 A1 = X1 > 4 A2 = X1 > 3 A3 = X1 >= 3.5 B1 = X2 >= 10 B2 = X2 >= 9 A = A1 | A2 B = B1 | B2 !((X1 > 4) | (X1 > 3)) A & B A1 & B A & B1 A | A3 A ∨ B A1 ∨ B A ∨ B1 A \ B A1 \ B A \ B1 A1 ⊻ B1 A ⊻ B A ⊻ B1 A1 ⊻ B for t1 = [cc, co, oc, oo], t2 = [cc, co, oc, oo] for i1 = 1:4, i2 = 1:4, i3 = 1:4, i4 = 1:4 t1(i1, i2) ∩ t2(i3, i4) t1(i1, i2) βˆͺ t2(i3, i4) t1(i1, i2) \ t2(i3, i4) t1(i1, i2) ⊻ t2(i3, i4) end end intersect([cc(1, 5), cc(3, 4)]) intersect(rect([cc(1, 5), cc(1, 5)]), rect([cc(2, 7), cc(2, 7)])) unionDisjoint(βˆ…) unionDisjoint(oo(-Inf, Inf)) unionDisjoint(oc(-Inf, 3)) unionDisjoint(oo(2, Inf)) unionDisjoint(cc(1, 2)) unionDisjoint(co(1, 2)) unionDisjoint(oc(1, 2)) unionDisjoint(oo(1, 2)) C1 = box([cc(1, 2), cc(1, 2)]) C2 = box([cc(1, 2), cc(2, 3)]) C3 = box([cc(1, 2), cc(2.5, 4)]) RandomVariables.mergeOne([C1, C2]) RandomVariables.mergeOne([C1, C3]) diff(C1, C3) C1 \ C1 xor(C1, C3) not(C1) X = RV(Poisson(5)) Y = RV(Normal()) E(log(X+1)) E(Y^2) X*0 1 - X X/2 exp(X+1) log(RV(Exponential(1))) P(X^2 > 1) log(X)^2 abs(X)^1.2 exp(X) ∈ cc(1, 2) cc(1, Inf) cc(-Inf, 1) cc(-Inf, Inf) oo(Inf, Inf) co(Inf, Inf) co(-Inf, 1) oc(Inf, Inf) oc(1, Inf) copy(emptyset()) b = box([cc(1, 2), cc(1, 2)]) b2 = box([cc(1, 2), cc(1, 2), cc(1, 2)]) length(b) iterate(b) iterate(b, nothing) ndims(b) cc(1, 2) βŠ† emptyset() emptyset() βŠ† cc(1, 2) emptyset() βŠ† emptyset() cc(1, 2) βŠ† co(1, 2) cc(1, 2) βŠ† co(1, 3) oo(1, 2) βŠ† co(0, 3) co(1, 2) βŠ† cc(1, 2) co(0, 3) βŠ† cc(1, 2) co(1, 2) βŠ† oc(0, 3) oc(1, 2) βŠ† cc(0, 3) oc(1, 2) βŠ† co(0, 3) b βŠ† b2 b βŠ† [b2] P(Poisson(1), co(1, 2)) P(Poisson(1), co(-1, 2)) P(Binomial(5, 0.4), co(1, 7)) P(Binomial(5, 0.4), co(1, Inf)) P(Poisson(1), oc(0, Inf)) std(RV(Poisson(1))) copy(RV(Poisson(1))) X = RV(Poisson(1)) Y = RV(Poisson(1)) A = (X > 2) & (Y > 1) B = (Y > 0) & (X > 1) B = event(B.X[[2, 1]], B.boxes) A | B RandomVariables.unionDisjoint(oo(-Inf, 1)) RandomVariables.unionDisjoint(co(1, Inf)) RandomVariables.unionDisjoint([co(1, Inf)]) RandomVariables.mergeBox(b, b) RandomVariables.mergeBox(box(cc(1, 3)), box(cc(1, 2))) RandomVariables.mergeOne([box(cc(1, 2))]) RandomVariables.resolveOverlap([box(cc(1, 2))]) RandomVariables.resolveOverlap([box(cc(1, 2)), box(cc(1, 2))]) b1 = box(cc(1, 2)) b2 = box(cc(3, 4)) b3 = box(cc(5, 6)) union(b1, [b2, b3]) intersect(b1, [b2, b3]) intersect([b2, b3], b1) b1 \ [b2, b3] [b2, b3] \ b1 [b2, b3] \ [b1] xor(b1, [b2, b3]) xor([b2, b3], b1) end
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.1.3
1fade0beee898fb8872ac858b78c7f4b669fbd61
docs
3906
# RandomVariables [![Build status](https://ci.appveyor.com/api/projects/status/oxrt0pwdypo42ees?svg=true)](https://ci.appveyor.com/project/ManuelStapper/randomvariables-jl) [![Coverage](https://codecov.io/gh/ManuelStapper/RandomVariables.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/ManuelStapper/RandomVariables.jl) [![DOI](https://zenodo.org/badge/508331635.svg)](https://zenodo.org/badge/latestdoi/508331635) A Julia package for random variables and probabilities as an add-on to the Distributions.jl package. Scope of the package: * Defining a random variable ``X = RV(Normal(0, 1)); Y = RV(Poisson(4))`` * Transformation of random variables: ``Z = log(Y + 1)`` * Convenient probability computation: ``P(X < 2)`` * Combination of events: ``A = (X < 2) & (Y β‰₯ 2); B = (X ≀ 5) & (Y > 0)`` * Defining conditional events: ``P(A|B)`` #### Installation Distributions.jl package must be installed and loaded to use RandomVariables.jl ``` julia> import Pkg julia> Pkg.add("Distributions") julia> Pkg.add("RandomVariables") julia> using RandomVariables, Distributions ``` ### Random variables To define a random variable, the function ``RV()`` takes any univariate distribution from the Distributions.jl package and equips it with an ID. ``` X = RV(Normal()) Y = RV(Poisson(4)) ``` #### Transformation of random variables Random variables can be transformed. Say you transform a random variable X by a function h(x), i.e. Z = f(X). The object ``RVtransformed`` stores the distribution of the original random variable X, its ID, the function h and the inverse of the transformation function. Implemented transformations for a real valued ``y`` are: ``X + y``, ``X - y``, ``X * y``, ``X / y``, ``inv(X)``, ``abs(X)``, ``exp(X)``, ``log(X)``, ``sqrt(X)`` and ``X^y``. ### Events To compute probabilities, events can be defined as a combination of independent random variables and bounding intervals. For example ``X > 1`` creates an event with random variable X and the interval (1, ∞). The bounding intervals can be closed [a, b], open (a, b) or semi-closed [a, b) or (a, b]. Two events can be combined with operators * ``&`` : both events occur * ``∨`` : Either one event occurs or both * ``\`` : Left event occurs but not the right event * ``⊻`` : One event occurs but not the other * ``!`` : The complementary event Examples for events: ``` A = X > 1 B = X ≀ 3 C = X ≀ 0 ``` * A & B : (1, 3] * A ∨ C : (-∞, 0] βˆͺ (1, ∞) * A \ B : (3, ∞) * A ⊻ B : (-∞, 1] βˆͺ (3, ∞) * !(A) : (-∞, 1] Events can include multiple independent random variables. For n variables, the bounding intervals will then be n dimensional rectangles (boxes). For example ``(X < 1) & (X β‰₯ 0) & (Y ≀ 1) & (Y > 0)`` creates an event with random variables X and Y with bounding rectangle [0, 1) Γ— (0, 1]. #### Conditional Events With two events, conditional events can be defined. A|B gives the event that event A occurs given that B occurs. The random variables in A do not necessarily need to match the random variables in B. Example: ``` A = (X > 1) & (log(Y + 1) ≀ 1) B = (X < 5) P(A|B) ``` ### Moments Mean, variance, skewness and kurtosis functions from the Distributions.jl package can also be applied to random variables. Further, a short notation for the mean ``E(X)`` is added. The mean of a transformed random variable is computed by numerical integration / summation. Example ``` P((X - E(X))^2 < 3) E(log(Y + 1)) ``` ### Outlook #### Short term * A more detailed documentation * Conditional moments, i.e. ``E(X | X > 1)`` * Shift to Intervals.jl (?) * Minimum and maximum, i.e. ``Z = minimum(X, Y)`` * Transfer more functionalities of Distributions.jl to random variables? * Plotting functions? #### Long term * More arithmetic on random variables: ``X + Y``, ... * Inclusion of dependent random variables in general ### References [Distributions.jl package](https://doi.org/10.5281/zenodo.2647458)
RandomVariables
https://github.com/ManuelStapper/RandomVariables.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
1971
using MLStyle using MacroTools function doBenchMarking(expr, f) expr = MacroTools.striplines(expr) println("Benchmarking $expr") write(f, string(expr) * "\n") write(f, "```\n\n") write(f, "```bash\n") show(f, "text/plain", eval(quote $expr end)) write(f, "\n```\n\n") end function bench(file::String) file_name = split(file, ".")[1] println("Benching $file_name.jl\n") file_name_output = joinpath("bench", file_name * ".md") open(file_name_output, write = true, append = false) do f write(f, "# Benchmarks for $file_name.jl\n\n") write(f, "```julia\n") end has_displayed = false function mapexpr(expr) #println("Nouvelle expr : ", expr) #Base.remove_linenums!(expr) #println("Suppression line number : ", expr) expr = MacroTools.striplines(expr) #println("MacroTools line number : ", expr, "\n") println("Expr : ", expr) #dump(expr) open(file_name_output, write = true, append = true) do f if has_displayed write(f, "```julia\n") has_displayed = false end if hasproperty(expr, :head) && expr.head == :macrocall && expr.args[1] == Symbol("@benchmark") has_displayed = true doBenchMarking(expr, f) expr = :() else MLStyle.@match expr begin :(display($benchname)) => begin has_displayed = true doBenchMarking(quote $benchname end, f) expr = :() end _ => begin write(f, string(expr) * "\n") end end end end return expr end include(mapexpr, file) end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
15829
using BenchmarkTools using CTBase using MLStyle using StaticArrays rg(i::Integer, j::Integer) = i == j ? i : i:j ocp = Model(); time!(ocp, 0, 1); state!(ocp, 2); control!(ocp, 2); constraint!(ocp, :initial, Index(2), 10, :ci) constraint!(ocp, :final, Index(1), 1, :cf) constraint!(ocp, :control, [0, 0], [1, 1], :cu) constraint!(ocp, :state, [0, 1], [1, 2], :cs) constraint!(ocp, :boundary, (x0, xf) -> x0[2] + xf[2], 0, 1, :cb) constraint!(ocp, :control, u -> u, [0, 0], [1, 1], :cuu) constraint!(ocp, :state, x -> x, [0, 1], [1, 2], :css) constraint!(ocp, :mixed, (x, u) -> x[1] + u[1], 1, 1, :cm) # -------------------------------------------------------------------- # -------------------------------------------------------------------- function nlp_constraints_original(ocp::OptimalControlModel) # we check if the dimensions and times have been set CTBase.__check_all_set(ocp) # constraints = ocp.constraints ΞΎf = Vector{ControlConstraint}() ΞΎl = Vector{ctNumber}() ΞΎu = Vector{ctNumber}() Ξ·f = Vector{StateConstraint}() Ξ·l = Vector{ctNumber}() Ξ·u = Vector{ctNumber}() ψf = Vector{MixedConstraint}() ψl = Vector{ctNumber}() ψu = Vector{ctNumber}() Ο•f = Vector{BoundaryConstraint}() Ο•l = Vector{ctNumber}() Ο•u = Vector{ctNumber}() ΞΈf = Vector{VariableConstraint}() ΞΈl = Vector{ctNumber}() ΞΈu = Vector{ctNumber}() uind = Vector{Int}() ul = Vector{ctNumber}() uu = Vector{ctNumber}() xind = Vector{Int}() xl = Vector{ctNumber}() xu = Vector{ctNumber}() vind = Vector{Int}() vl = Vector{ctNumber}() vu = Vector{ctNumber}() for (_, c) ∈ constraints MLStyle.@match c begin (:initial, f::BoundaryConstraint, lb, ub) => begin push!(Ο•f, f) append!(Ο•l, lb) append!(Ο•u, ub) end (:final, f::BoundaryConstraint, lb, ub) => begin push!(Ο•f, f) append!(Ο•l, lb) append!(Ο•u, ub) end (:boundary, f::BoundaryConstraint, lb, ub) => begin push!(Ο•f, f) append!(Ο•l, lb) append!(Ο•u, ub) end (:control, f::ControlConstraint, lb, ub) => begin push!(ΞΎf, f) append!(ΞΎl, lb) append!(ΞΎu, ub) end (:control, rg, lb, ub) => begin append!(uind, rg) append!(ul, lb) append!(uu, ub) end (:state, f::StateConstraint, lb, ub) => begin push!(Ξ·f, f) append!(Ξ·l, lb) append!(Ξ·u, ub) end (:state, rg, lb, ub) => begin append!(xind, rg) append!(xl, lb) append!(xu, ub) end (:mixed, f::MixedConstraint, lb, ub) => begin push!(ψf, f) append!(ψl, lb) append!(ψu, ub) end (:variable, f::VariableConstraint, lb, ub) => begin push!(ΞΈf, f) append!(ΞΈl, lb) append!(ΞΈu, ub) end (:variable, rg, lb, ub) => begin append!(vind, rg) append!(vl, lb) append!(vu, ub) end _ => error("Internal error") end end function ΞΎ(t, u, v) val = Vector{ctNumber}() for i ∈ 1:length(ΞΎf) append!(val, ΞΎf[i](t, u, v)) end return val end function Ξ·(t, x, v) val = Vector{ctNumber}() for i ∈ 1:length(Ξ·f) append!(val, Ξ·f[i](t, x, v)) end return val end function ψ(t, x, u, v) val = Vector{ctNumber}() for i ∈ 1:length(ψf) append!(val, ψf[i](t, x, u, v)) end return val end function Ο•(x0, xf, v) val = Vector{ctNumber}() for i ∈ 1:length(Ο•f) append!(val, Ο•f[i](x0, xf, v)) end return val end function ΞΈ(v) val = Vector{ctNumber}() for i ∈ 1:length(ΞΈf) append!(val, ΞΈf[i](v)) end return val end return (ΞΎl, ΞΎ, ΞΎu), (Ξ·l, Ξ·, Ξ·u), (ψl, ψ, ψu), (Ο•l, Ο•, Ο•u), (ΞΈl, ΞΈ, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu) end function test_alloc_bad(ocp, N) println(" getters and setters") begin function get_state(XU, i, n, m) return XU[rg((i - 1) * (n + m) + 1, (i - 1) * (n + m) + n)] end function get_control(XU, i, n, m) return XU[rg((i - 1) * (n + m) + n + 1, (i - 1) * (n + m) + n + m)] end function set_control_constraint!(C, i, ΞΎ, nΞΎ, nc) C[((i - 1) * nc + 1):((i - 1) * nc + nΞΎ)] = ΞΎ end function set_state_constraint!(C, i, Ξ·, nΞ·, nΞΎ, nc) C[((i - 1) * nc + nΞΎ + 1):((i - 1) * nc + nΞΎ + nΞ·)] = Ξ· end function set_mixed_constraint!(C, i, ψ, nψ, nΞΎ, nΞ·, nc) C[((i - 1) * nc + nΞΎ + nΞ· + 1):((i - 1) * nc + nΞΎ + nΞ· + nψ)] = ψ end end println(" call nlp_constraints_original") (ΞΎl, ΞΎ, ΞΎu), (Ξ·l, Ξ·, Ξ·u), (ψl, ψ, ψu), (Ο•l, Ο•, Ο•u), (ΞΈl, ΞΈ, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu) = nlp_constraints_original(ocp) println(" declare variables") begin v = Real[] n = state_dimension(ocp) m = control_dimension(ocp) times = LinRange(0, 1, N) XU = ones(N * (n + m)) nΞΎ = length(ΞΎl) nΞ· = length(Ξ·l) nψ = length(ψl) nc = nΞΎ + nΞ· + nψ C = zeros(N * nc) end println(" start for loop") begin for i ∈ 1:N t = times[i] x = get_state(XU, i, n, m) u = get_control(XU, i, n, m) set_control_constraint!(C, i, ΞΎ(t, u, v), nΞΎ, nc) set_state_constraint!(C, i, Ξ·(t, x, v), nΞ·, nΞΎ, nc) set_mixed_constraint!(C, i, ψ(t, x, u, v), nψ, nΞΎ, nΞ·, nc) end end println(" end for loop") nothing end # -------------------------------------------------------------------- # -------------------------------------------------------------------- function nlp_constraints_optimized(ocp::OptimalControlModel) # we check if the dimensions and times have been set CTBase.__check_all_set(ocp) # constraints = ocp.constraints ΞΎf = Vector{ControlConstraint}() ΞΎl = Vector{ctNumber}() ΞΎu = Vector{ctNumber}() ΞΎn = Vector{Int}() Ξ·f = Vector{StateConstraint}() Ξ·l = Vector{ctNumber}() Ξ·u = Vector{ctNumber}() Ξ·n = Vector{Int}() ψf = Vector{MixedConstraint}() ψl = Vector{ctNumber}() ψu = Vector{ctNumber}() ψn = Vector{Int}() Ο•f = Vector{BoundaryConstraint}() Ο•l = Vector{ctNumber}() Ο•u = Vector{ctNumber}() Ο•n = Vector{Int}() ΞΈf = Vector{VariableConstraint}() ΞΈl = Vector{ctNumber}() ΞΈu = Vector{ctNumber}() ΞΈn = Vector{Int}() uind = Vector{Int}() ul = Vector{ctNumber}() uu = Vector{ctNumber}() xind = Vector{Int}() xl = Vector{ctNumber}() xu = Vector{ctNumber}() vind = Vector{Int}() vl = Vector{ctNumber}() vu = Vector{ctNumber}() for (_, c) ∈ constraints MLStyle.@match c begin (:initial, f::BoundaryConstraint, lb, ub) => begin append!(Ο•n, length(lb)) push!(Ο•f, f) append!(Ο•l, lb) append!(Ο•u, ub) end (:final, f::BoundaryConstraint, lb, ub) => begin append!(Ο•n, length(lb)) push!(Ο•f, f) append!(Ο•l, lb) append!(Ο•u, ub) end (:boundary, f::BoundaryConstraint, lb, ub) => begin append!(Ο•n, length(lb)) push!(Ο•f, f) append!(Ο•l, lb) append!(Ο•u, ub) end (:control, f::ControlConstraint, lb, ub) => begin append!(ΞΎn, length(lb)) push!(ΞΎf, f) append!(ΞΎl, lb) append!(ΞΎu, ub) end (:control, rg, lb, ub) => begin append!(uind, rg) append!(ul, lb) append!(uu, ub) end (:state, f::StateConstraint, lb, ub) => begin append!(Ξ·n, length(lb)) push!(Ξ·f, f) append!(Ξ·l, lb) append!(Ξ·u, ub) end (:state, rg, lb, ub) => begin append!(xind, rg) append!(xl, lb) append!(xu, ub) end (:mixed, f::MixedConstraint, lb, ub) => begin append!(ψn, length(lb)) push!(ψf, f) append!(ψl, lb) append!(ψu, ub) end (:variable, f::VariableConstraint, lb, ub) => begin append!(ΞΈn, length(lb)) push!(ΞΈf, f) append!(ΞΈl, lb) append!(ΞΈu, ub) end (:variable, rg, lb, ub) => begin append!(vind, rg) append!(vl, lb) append!(vu, ub) end _ => error("Internal error") end end ΞΎfn = length(ΞΎf) Ξ·fn = length(Ξ·f) ψfn = length(ψf) Ο•fn = length(Ο•f) ΞΈfn = length(ΞΈf) function ΞΎ!(val, t, u, v, N = ΞΎfn) offset = 0 for i ∈ 1:N #val[rg(1+offset,ΞΎn[i]+offset)] = z = ΞΎf[i](t, u, v)[:] val[rg(1 + offset, ΞΎn[i] + offset)] = z offset += ΞΎn[i] end #for i ∈ eachindex(val) # val[i] = u[1]+t #end nothing end function Ξ·!(val, t, x, v, N = Ξ·fn) offset = 0 for i ∈ 1:N val[rg(1 + offset, Ξ·n[i] + offset)] = Ξ·f[i](t, x, v) offset += Ξ·n[i] end #for i ∈ eachindex(val) # val[i] = x[1]+t #end nothing end function ψ!(val, t, x, u, v, N = ψfn) offset = 0 for i ∈ 1:N val[rg(1 + offset, ψn[i] + offset)] = ψf[i](t, x, u, v) offset += ψn[i] end #for i ∈ eachindex(val) # val[i] = x[1]+t+u[1] #end nothing end function Ο•!(val, x0, xf, v, N = Ο•fn) offset = 0 for i ∈ 1:N val[rg(1 + offset, Ο•n[i] + offset)] = Ο•f[i](x0, xf, v) offset += Ο•n[i] end #for i ∈ eachindex(val) # val[i] = x0[1]+xf[1] #end nothing end function ΞΈ!(val, v, N = ΞΈfn) offset = 0 for i ∈ 1:N val[rg(1 + offset, ΞΈn[i] + offset)] = ΞΈf[i](v) offset += ΞΈn[i] end #for i ∈ eachindex(val) # val[i] = 0 #end nothing end return (ΞΎl, ΞΎ!, ΞΎu), (Ξ·l, Ξ·!, Ξ·u), (ψl, ψ!, ψu), (Ο•l, Ο•!, Ο•u), (ΞΈl, ΞΈ!, ΞΈu), (uind, ul, uu), (xind, xl, xu), (vind, vl, vu) end function test_alloc_good(ocp, N) begin println(" getters and setters") begin function get_state(XU, i, n, m) if n == 1 return XU[(i - 1) * (n + m) + 1] else return @view XU[((i - 1) * (n + m) + 1):((i - 1) * (n + m) + n)] end end function get_control(XU, i, n, m) if m == 1 return XU[(i - 1) * (n + m) + n + 1] else return @view XU[((i - 1) * (n + m) + n + 1):((i - 1) * (n + m) + n + m)] end end function set_control_constraint!(C, i, valΞΎ, nΞΎ, nc) C[((i - 1) * nc + 1):((i - 1) * nc + nΞΎ)] = valΞΎ end function set_state_constraint!(C, i, valΞ·, nΞ·, nΞΎ, nc) C[((i - 1) * nc + nΞΎ + 1):((i - 1) * nc + nΞΎ + nΞ·)] = valΞ· end function set_mixed_constraint!(C, i, valψ, nψ, nΞΎ, nΞ·, nc) C[((i - 1) * nc + nΞΎ + nΞ· + 1):((i - 1) * nc + nΞΎ + nΞ· + nψ)] = valψ end end println(" call nlp_constraints_optimized") begin (ΞΎl, ΞΎ!, ΞΎu), (Ξ·l, Ξ·!, Ξ·u), (ψl, ψ!, ψu), (Ο•l, Ο•!, Ο•u), (ΞΈl, ΞΈ!, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu) = nlp_constraints_optimized(ocp) end println(" declare variables") begin v = Real[] n = state_dimension(ocp) m = control_dimension(ocp) times = LinRange(0, 1, N) XU = zeros(N * (n + m)) nΞΎ = length(ΞΎl) nΞ· = length(Ξ·l) nψ = length(ψl) nc = nΞΎ + nΞ· + nψ C = zeros(N * nc) valΞΎ = SizedVector{nΞΎ}(zeros(nΞΎ)) valΞ· = SizedVector{nΞ·}(zeros(nΞ·)) valψ = SizedVector{nψ}(zeros(nψ)) x = SizedVector{n}(zeros(n)) u = SizedVector{m}(zeros(m)) end t = 0 println(" start for loop") for i ∈ 1:N #= if i==-1 #|| i==2 println(" i = ", i) print("time") @time t = times[i] print("x") @time x[:] = @view XU[(i-1)*(n+m)+1:(i-1)*(n+m)+n] print("u") @time u[:] = @view XU[(i-1)*(n+m)+n+1:(i-1)*(n+m)+n+m] print("ΞΎ!") @time ΞΎ!(valΞΎ, t, u, v) print("Ξ·!") @time Ξ·!(valΞ·, t, x, v) print("ψ!") @time ψ!(valψ, t, x, u, v) print("set_control_constraint!") @time set_control_constraint!(C, i, valΞΎ, nΞΎ, nc) print("set_state_constraint!") @time set_state_constraint!(C, i, valΞ·, nΞ·, nΞΎ, nc) print("set_mixed_constraint!") @time set_mixed_constraint!(C, i, valψ, nψ, nΞΎ, nΞ·, nc) else nothing =# t = times[i] x[:] = XU[((i - 1) * (n + m) + 1):((i - 1) * (n + m) + n)] u[:] = @view XU[((i - 1) * (n + m) + n + 1):((i - 1) * (n + m) + n + m)] ΞΎ!(valΞΎ, t, u, v) Ξ·!(valΞ·, t, x, v) ψ!(valψ, t, x, u, v) #set_control_constraint!(C, i, valΞΎ, nΞΎ, nc) C[((i - 1) * nc + 1):((i - 1) * nc + nΞΎ)] = valΞΎ #set_state_constraint!(C, i, valΞ·, nΞ·, nΞΎ, nc) C[((i - 1) * nc + nΞΎ + 1):((i - 1) * nc + nΞΎ + nΞ·)] = valΞ· #set_mixed_constraint!(C, i, valψ, nψ, nΞΎ, nΞ·, nc) C[((i - 1) * nc + nΞΎ + nΞ· + 1):((i - 1) * nc + nΞΎ + nΞ· + nψ)] = valψ #end end println(" end for loop") nothing end end N = 10000 test_alloc_good(ocp, N); test_alloc_bad(ocp, N); println("----------------------------------------") println("good code") @time test_alloc_good(ocp, N) println() println("bad code") @time test_alloc_bad(ocp, N) #= # -------------------------------------------------------------------- # -------------------------------------------------------------------- println("Allocations and times for good and bad code") println() N = 200 println("good code") t_good = @benchmark test_alloc_good(ocp, N) display(t_good) println() println("bad code") t_bad = @benchmark test_alloc_bad(ocp, N) display(t_bad) println() # print the ratio of the times println("ratio of times: ", mean(t_bad.times)/mean(t_good.times)) println("ratio of allocations: ", mean(t_bad.memory)/mean(t_good.memory)) nothing =#
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
1033
using BenchmarkTools function tt() function bench_scalar(y) x = 0 for i = 1:y x += 1.0 end x end function bench_scalar_2() x = 0 for i = 1:z x += 1.0 end x end function bench_scalar_3(z) x = 0 for i = 1:z x += w end x end w = 1.0 z = 1000 display(@benchmark bench_scalar(z)) display(@benchmark bench_scalar_2()) display(@benchmark bench_scalar_3(z)) function bench_scalar_4() x = 0 for i = 1:zz x += 1.0 end x end function bench_scalar_5(z) x = 0 for i = 1:z x += ww end x end ww = 1.0 zz = 1000 display(@benchmark bench_scalar_4()) display(@benchmark bench_scalar_5(zz)) function bench_scalar_6(z = z) x = 0 for i = 1:z x += 1.0 end x end @benchmark bench_scalar_6() end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
1501
using BenchmarkTools # fun with dimension usage handled at each call struct Fun_dim_usage_each_call f::Function end function (F::Fun_dim_usage_each_call)( t::Real, x::Vector{<:Real}, u::Vector{<:Real}, args...; kwargs..., ) x_ = length(x) == 1 ? (x[1],) : (x,) u_ = length(u) == 1 ? (u[1],) : (u,) y = F.f(t, x_..., u_..., args...; kwargs...) return y isa Real ? [y] : y end # t = 1 x = [10] u = [100] # bench fun with dimension usage handled at each call # x, u scalar F = Fun_dim_usage_each_call((t, x, u) -> x + u) @benchmark F(t, x, u) # x scalar, u vector F = Fun_dim_usage_each_call((t, x, u) -> x + u[1]) @benchmark F(t, x, u) # fun with dimension usage handled by parameterization struct Fun_dim_usage_parametrization{dim_x, dim_u} f::Function end function (F::Fun_dim_usage_parametrization{1, 1})( t::Real, x::Vector{<:Real}, u::Vector{<:Real}, args...; kwargs..., ) return [F.f(t, x[1], u[1], args...; kwargs...)] end # bench fun with dimension usage handled by parameterization # x, u scalar F = Fun_dim_usage_parametrization{1, 1}((t, x, u) -> x + u) @benchmark F(t, x, u) # x scalar, u vector F = Fun_dim_usage_parametrization{1, 1}((t, x, u) -> x + u[1]) @benchmark F(t, x, u) # direct call to the function Ο•(t, x, u) = x[1] + u[1] @benchmark Ο•(t, x, u) ψ(t, x, u) = x + u @benchmark ψ(t, x[1], u[1]) ΞΈ(t, x, u) = x + u @benchmark ΞΈ(t, x, u)[1] ΞΎ(t, x, u) = x + u a = x[1] b = u[1] @benchmark ΞΎ(t, a, b)
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
85
# include("Bench.jl") # #bench("bench_usage.jl") bench("bench_nlp_constraints.jl")
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
649
using Documenter using CTBase using DocumenterMermaid makedocs(; warnonly = [:cross_references, :autodocs_block], sitename = "CTBase.jl", format = Documenter.HTML( prettyurls = false, size_threshold_ignore = ["api.md", "dev.md"], assets = [ asset("https://control-toolbox.org/assets/css/documentation.css"), asset("https://control-toolbox.org/assets/js/documentation.js"), ], ), pages = ["Introduction" => "index.md", "API" => "api.md", "Developers" => "dev.md"], checkdocs = :none, ) deploydocs(repo = "github.com/control-toolbox/CTBase.jl.git", devbranch = "main")
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
281
module CTBasePlots # using DocStringExtensions using MLStyle # pattern matching # using CTBase using Plots using LinearAlgebra import Plots: plot, plot! # -------------------------------------------------------------------------------------------------- include("plot.jl") end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
18822
""" $(TYPEDEF) Abstract node for plot. """ abstract type AbstractPlotTreeElement end """ $(TYPEDEF) A leaf of a plot tree. """ struct PlotLeaf <: AbstractPlotTreeElement value::Tuple{Symbol, Integer} PlotLeaf(value::Tuple{Symbol, Integer}) = new(value) end """ $(TYPEDEF) A node of a plot tree. """ struct PlotNode <: AbstractPlotTreeElement layout::Union{Symbol, Matrix{Any}} children::Vector{<:AbstractPlotTreeElement} PlotNode(layout::Union{Symbol, Matrix{Any}}, children::Vector{<:AbstractPlotTreeElement}) = new(layout, children) end # -------------------------------------------------------------------------------------------------- # internal plots """ $(TYPEDSIGNATURES) Update the plot `p` with the i-th component of a vectorial function of time `f(t) ∈ Rᡈ` where `f` is given by the symbol `s`. - The argument `s` can be `:state`, `:control` or `:costate`. - `time` can be `:default` or `:normalized`. """ function __plot_time!( p::Union{Plots.Plot, Plots.Subplot}, sol::OptimalControlSolution, s::Symbol, i::Integer, time::Symbol; t_label, label::String, kwargs..., ) # t_label depends if time is normalized or not t_label = @match time begin :default => t_label :normalized => "normalized " * t_label _ => error("Internal error, no such choice for time: $time. Use :default or :normalized") end # reset ylims: ylims=:auto Plots.plot!( p, sol, :time, (s, i), time; ylims = :auto, xlabel = t_label, label = label, kwargs..., ) # use simple plot # change ylims if the gap between min and max is less than a tol tol = 1e-3 ymin = Inf ymax = -Inf for s ∈ p.series_list y = s[:y] ymin = min(minimum(y), ymin) ymax = max(maximum(y), ymax) end if (ymin != Inf) && (ymax != -Inf) && (abs(ymax - ymin) ≀ abs(ymin) * tol) ymiddle = (ymin + ymax) / 2.0 if (abs(ymiddle) < 1e-12) ylims!(p, (-0.1, 0.1)) else ymiddle > 0 ? ylims!(p, (0.9 * ymiddle, 1.1 * ymiddle)) : ylims!(p, (1.1 * ymiddle, 0.9 * ymiddle)) end end return p end """ $(TYPEDSIGNATURES) Plot the i-th component of a vectorial function of time `f(t) ∈ Rᡈ` where `f` is given by the symbol `s`. - The argument `s` can be `:state`, `:control` or `:costate`. - `time` can be `:default` or `:normalized`. """ function __plot_time( sol::OptimalControlSolution, s::Symbol, i::Integer, time::Symbol; t_label, label::String, kwargs..., ) return __plot_time!(Plots.plot(), sol, s, i, time; t_label = t_label, label = label, kwargs...) end """ $(TYPEDSIGNATURES) Update the plot `p` with a vectorial function of time `f(t) ∈ Rᡈ` where `f` is given by the symbol `s`. - The argument `s` can be `:state`, `:control` or `:costate`. - `time` can be `:default` or `:normalized`. """ function __plot_time!( p::Union{Plots.Plot, Plots.Subplot}, sol::OptimalControlSolution, d::Dimension, s::Symbol, time::Symbol; t_label, labels::Vector{String}, title::String, kwargs..., ) # Plots.plot!(p; xlabel = "time", title = title, kwargs...) # for i in range(1, d) __plot_time!(p, sol, s, i, time; t_label = t_label, label = labels[i], kwargs...) end return p end """ $(TYPEDSIGNATURES) Plot a vectorial function of time `f(t) ∈ Rᡈ` where `f` is given by the symbol `s`. The argument `s` can be `:state`, `:control` or `:costate`. """ function __plot_time( sol::OptimalControlSolution, d::Dimension, s::Symbol, time::Symbol; t_label, labels::Vector{String}, title::String, kwargs..., ) return __plot_time!( Plots.plot(), sol, d, s, time; t_label = t_label, labels = labels, title = title, kwargs..., ) end """ $(TYPEDSIGNATURES) Generate a{r*h} where `r` is a real number and `h` is the height of the plot. """ function __width(r::Real)::Expr i = Expr(:call, :*, r, :h) a = Expr(:curly, :a, i) return a end """ $(TYPEDSIGNATURES) Plot a leaf. """ function __plot_tree(leaf::PlotLeaf, depth::Integer; kwargs...) return Plots.plot() end """ $(TYPEDSIGNATURES) Plot a node. """ function __plot_tree(node::PlotNode, depth::Integer = 0; kwargs...) # subplots = () # for c ∈ node.children pc = __plot_tree(c, depth + 1) subplots = (subplots..., pc) end # kwargs_plot = depth == 0 ? kwargs : () ps = @match node.layout begin :row => plot(subplots...; layout = (1, size(subplots, 1)), kwargs_plot...) :column => plot(subplots...; layout = (size(subplots, 1), 1), kwargs_plot...) _ => plot(subplots...; layout = node.layout, kwargs_plot...) end return ps end """ $(TYPEDSIGNATURES) Initial plot. """ function __initial_plot( sol::OptimalControlSolution; layout::Symbol = :split, control::Symbol = :components, kwargs..., ) # parameters n = state_dimension(sol) m = control_dimension(sol) if layout == :group @match control begin :components => begin px = Plots.plot() # state pp = Plots.plot() # costate pu = Plots.plot() # control return Plots.plot(px, pp, pu, layout = (1, 3); kwargs...) end :norm => begin px = Plots.plot() # state pp = Plots.plot() # costate pn = Plots.plot() # control norm return Plots.plot(px, pp, pn, layout = (1, 3); kwargs...) end :all => begin px = Plots.plot() # state pp = Plots.plot() # costate pu = Plots.plot() # control pn = Plots.plot() # control norm return Plots.plot(px, pp, pu, pn, layout = (2, 2); kwargs...) end _ => throw( IncorrectArgument("No such choice for control. Use :components, :norm or :all"), ) end elseif layout == :split # create tree plot state_plots = Vector{PlotLeaf}() costate_plots = Vector{PlotLeaf}() control_plots = Vector{PlotLeaf}() for i ∈ 1:n push!(state_plots, PlotLeaf((:state, i))) push!(costate_plots, PlotLeaf((:costate, i))) end l = m @match control begin :components => begin for i ∈ 1:m push!(control_plots, PlotLeaf((:control, i))) end end :norm => begin push!(control_plots, PlotLeaf((:control_norm, -1))) l = 1 end :all => begin for i ∈ 1:m push!(control_plots, PlotLeaf((:control, i))) end push!(control_plots, PlotLeaf((:control_norm, -1))) l = m + 1 end _ => throw( IncorrectArgument("No such choice for control. Use :components, :norm or :all"), ) end # node_x = PlotNode(:column, state_plots) node_p = PlotNode(:column, costate_plots) node_u = PlotNode(:column, control_plots) node_xp = PlotNode(:row, [node_x, node_p]) # r = round(n / (n + l), digits = 2) a = __width(r) @eval lay = @layout [ $a b ] root = PlotNode(lay, [node_xp, node_u]) # plot return __plot_tree(root; kwargs...) else throw(IncorrectArgument("No such choice for layout. Use :group or :split")) end end function __keep_series_attributes(; kwargs...) series_attributes = Plots.attributes(:Series) out = [] for kw ∈ kwargs kw[1] ∈ series_attributes && push!(out, kw) end return out end """ $(TYPEDSIGNATURES) Plot the optimal control solution `sol` using the layout `layout`. **Notes.** - The argument `layout` can be `:group` or `:split` (default). - `control` can be `:components`, `:norm` or `:all`. - `time` can be `:default` or `:normalized`. - The keyword arguments `state_style`, `control_style` and `costate_style` are passed to the `plot` function of the `Plots` package. The `state_style` is passed to the plot of the state, the `control_style` is passed to the plot of the control and the `costate_style` is passed to the plot of the costate. """ function Plots.plot!( p::Plots.Plot, sol::OptimalControlSolution; layout::Symbol = :split, control::Symbol = :components, time::Symbol = :default, solution_label::String = "", state_style = (), control_style = (), costate_style = (), kwargs..., ) if solution_label != "" solution_label = " " * solution_label end # n = state_dimension(sol) m = control_dimension(sol) x_labels = state_components_names(sol) u_labels = control_components_names(sol) u_label = control_name(sol) t_label = time_name(sol) # split series attributes series_attr = __keep_series_attributes(; kwargs...) if layout == :group __plot_time!( p[1], sol, n, :state, time; t_label = t_label, labels = x_labels .* solution_label, title = "state", lims = :auto, series_attr..., state_style..., ) __plot_time!( p[2], sol, n, :costate, time; t_label = t_label, labels = "p" .* x_labels .* solution_label, title = "costate", lims = :auto, series_attr..., costate_style..., ) @match control begin :components => begin __plot_time!( p[3], sol, m, :control, time; t_label = t_label, labels = u_labels .* solution_label, title = "control", lims = :auto, series_attr..., control_style..., ) end :norm => begin __plot_time!( p[3], sol, :control_norm, -1, time; t_label = t_label, label = "β€–" * u_label * "β€–" .* solution_label, title = "control norm", lims = :auto, series_attr..., control_style..., ) end :all => begin __plot_time!( p[3], sol, m, :control, time; t_label = t_label, labels = u_labels .* solution_label, title = "control", lims = :auto, series_attr..., control_style..., ) __plot_time!( p[4], sol, :control_norm, -1, time; t_label = t_label, label = "β€–" * u_label * "β€–" .* solution_label, title = "control norm", lims = :auto, series_attr..., control_style..., ) end _ => throw( IncorrectArgument("No such choice for control. Use :components, :norm or :all"), ) end elseif layout == :split for i ∈ 1:n __plot_time!( p[i], sol, :state, i, time; t_label = t_label, label = x_labels[i] * solution_label, series_attr..., state_style..., ) __plot_time!( p[i + n], sol, :costate, i, time; t_label = t_label, label = "p" * x_labels[i] * solution_label, series_attr..., costate_style..., ) end @match control begin :components => begin for i ∈ 1:m __plot_time!( p[i + 2 * n], sol, :control, i, time; t_label = t_label, label = u_labels[i] * solution_label, series_attr..., control_style..., ) end end :norm => begin __plot_time!( p[2 * n + 1], sol, :control_norm, -1, time; t_label = t_label, label = "β€–" * u_label * "β€–" * solution_label, series_attr..., control_style..., ) end :all => begin for i ∈ 1:m __plot_time!( p[i + 2 * n], sol, :control, i, time; t_label = t_label, label = u_labels[i] * solution_label, series_attr..., control_style..., ) end __plot_time!( p[2 * n + m + 1], sol, :control_norm, -1, time; t_label = t_label, label = "β€–" * u_label * "β€–" * solution_label, series_attr..., control_style..., ) end _ => throw( IncorrectArgument("No such choice for control. Use :components, :norm or :all"), ) end else throw(IncorrectArgument("No such choice for layout. Use :group or :split")) end return p end function __size_plot(sol::OptimalControlSolution, control::Symbol) n = state_dimension(sol) #m = control_dimension(sol) m = @match control begin :components => control_dimension(sol) :norm => 1 :all => control_dimension(sol) + 1 _ => throw(IncorrectArgument("No such choice for control. Use :components, :norm or :all")) end return (600, 140 * (n + m)) end """ $(TYPEDSIGNATURES) Plot the optimal control solution `sol` using the layout `layout`. **Notes.** - The argument `layout` can be `:group` or `:split` (default). - The keyword arguments `state_style`, `control_style` and `costate_style` are passed to the `plot` function of the `Plots` package. The `state_style` is passed to the plot of the state, the `control_style` is passed to the plot of the control and the `costate_style` is passed to the plot of the costate. """ function Plots.plot( sol::OptimalControlSolution; layout::Symbol = :split, control::Symbol = :components, time::Symbol = :default, size = __size_plot(sol, control), solution_label::String = "", state_style = (), control_style = (), costate_style = (), kwargs..., ) # p = __initial_plot(sol; layout = layout, control = control, size = size, kwargs...) # return Plots.plot!( p, sol; layout = layout, control = control, time = time, solution_label = solution_label, state_style = state_style, control_style = control_style, costate_style = costate_style, kwargs..., ) end """ $(TYPEDSIGNATURES) Return `x` and `y` for the plot of the optimal control solution `sol` corresponding respectively to the argument `xx` and the argument `yy`. **Notes.** - The argument `xx` can be `:time`, `:state`, `:control` or `:costate`. - If `xx` is `:time`, then, a label is added to the plot. - The argument `yy` can be `:state`, `:control` or `:costate`. """ @recipe function f( sol::OptimalControlSolution, xx::Union{Symbol, Tuple{Symbol, Integer}}, yy::Union{Symbol, Tuple{Symbol, Integer}}, time::Symbol = :default, ) # x = __get_data_plot(sol, xx, time = time) y = __get_data_plot(sol, yy, time = time) # label = recipe_label(sol, xx, yy) return x, y end function recipe_label( sol::OptimalControlSolution, xx::Union{Symbol, Tuple{Symbol, Integer}}, yy::Union{Symbol, Tuple{Symbol, Integer}}, ) # label = false # if xx isa Symbol && xx == :time s, i = @match yy begin ::Symbol => (yy, 1) _ => yy end label = @match s begin :state => state_components_names(sol)[i] :control => control_components_names(sol)[i] :costate => "p" * state_components_names(sol)[i] :control_norm => "β€–" * control_name(sol) * "β€–" _ => error("Internal error, no such choice for label") end end # return label end """ $(TYPEDSIGNATURES) Get the data for plotting. """ function __get_data_plot( sol::OptimalControlSolution, xx::Union{Symbol, Tuple{Symbol, Integer}}; time::Symbol = :default, ) T = time_grid(sol) X = state(sol).(T) U = control(sol).(T) P = costate(sol).(T) vv, ii = @match xx begin ::Symbol => (xx, 1) _ => xx end m = size(T, 1) return @match vv begin :time => begin @match time begin :default => T :normalized => (T .- T[1]) ./ (T[end] - T[1]) :normalised => (T .- T[1]) ./ (T[end] - T[1]) _ => error( "Internal error, no such choice for time: $time. Use :default, :normalized or :normalised", ) end end :state => [X[i][ii] for i = 1:m] :control => [U[i][ii] for i = 1:m] :costate => [P[i][ii] for i = 1:m] :control_norm => [norm(U[i]) for i = 1:m] _ => error("Internal error, no such choice for xx") end end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
8609
""" [`CTBase`](@ref) module. Lists all the imported modules and packages: $(IMPORTS) List of all the exported names: $(EXPORTS) """ module CTBase import Base using DocStringExtensions using DifferentiationInterface: AutoForwardDiff, derivative, gradient, jacobian, prepare_derivative, prepare_gradient, prepare_jacobian import ForwardDiff using Interpolations: linear_interpolation, Line, Interpolations # For default interpolation using MLStyle # Pattern matching using Parameters # @with_kw: to have default values in struct using Printf # To print an OptimalControlModel using DataStructures # OrderedDict for aliases using Unicode # Unicode primitives using PrettyTables # To print a table using ReplMaker using MacroTools: @capture, postwalk, striplines using LinearAlgebra # To suppress ambiguities using SparseArrays, StaticArrays # -------------------------------------------------------------------------------------------------- # Aliases for types # const AbstractVector{T} = AbstractArray{T,1}. """ Type alias for a real number. ```@example julia> const ctNumber = Real ``` """ const ctNumber = Real """ Type alias for a vector of real numbers. ```@example julia> const ctVector = Union{ctNumber, AbstractVector{<:ctNumber}} ``` See also: [`ctNumber`](@ref), [`State`](@ref), [`Costate`](@ref), [`Control`](@ref), [`Variable`](@ref). """ const ctVector = Union{ctNumber, AbstractVector{<:ctNumber}} # [] must be defined as Vector{Real}() """ Type alias for a time. ```@example julia> const Time = ctNumber ``` See also: [`ctNumber`](@ref), [`Times`](@ref), [`TimesDisc`](@ref). """ const Time = ctNumber """ Type alias for a vector of times. ```@example julia> const Times = AbstractVector{<:Time} ``` See also: [`Time`](@ref), [`TimesDisc`](@ref). """ const Times = AbstractVector{<:Time} """ Type alias for a grid of times. This is used to define a discretization of time interval given to solvers. ```@example julia> const TimesDisc = Union{Times, StepRangeLen} ``` See also: [`Time`](@ref), [`Times`](@ref). """ const TimesDisc = Union{Times, StepRangeLen} """ Type alias for a state in Rⁿ. ```@example julia> const State = ctVector ``` See also: [`ctVector`](@ref), [`Costate`](@ref), [`Control`](@ref), [`Variable`](@ref). """ const State = ctVector """ Type alias for a costate in Rⁿ. ```@example julia> const Costate = ctVector ``` See also: [`ctVector`](@ref), [`State`](@ref), [`Control`](@ref), [`Variable`](@ref). """ const Costate = ctVector # todo: add adjoint to write p*f(x, u) instead of p'*f(x,u) """ Type alias for a control in Rᡐ. ```@example julia> const Control = ctVector ``` See also: [`ctVector`](@ref), [`State`](@ref), [`Costate`](@ref), [`Variable`](@ref). """ const Control = ctVector """ Type alias for a variable in Rᡏ. ```@example julia> const Variable = ctVector ``` See also: [`ctVector`](@ref), [`State`](@ref), [`Costate`](@ref), [`Control`](@ref). """ const Variable = ctVector """ Type alias for a vector of states. ```@example julia> const States = AbstractVector{<:State} ``` See also: [`State`](@ref), [`Costates`](@ref), [`Controls`](@ref). """ const States = AbstractVector{<:State} """ Type alias for a vector of costates. ```@example julia> const Costates = AbstractVector{<:Costate} ``` See also: [`Costate`](@ref), [`States`](@ref), [`Controls`](@ref). """ const Costates = AbstractVector{<:Costate} """ Type alias for a vector of controls. ```@example julia> const Controls = AbstractVector{<:Control} ``` See also: [`Control`](@ref), [`States`](@ref), [`Costates`](@ref). """ const Controls = AbstractVector{<:Control} """ Type alias for a dimension. This is used to define the dimension of the state space, the costate space, the control space, etc. ```@example julia> const Dimension = Integer ``` """ const Dimension = Integer # """ Type alias for a tangent vector to the state space. ```@example julia> const DState = ctVector ``` See also: [`ctVector`](@ref), [`DCostate`](@ref). """ const DState = ctVector """ Type alias for a tangent vector to the costate space. ```@example julia> const DCostate = ctVector ``` See also: [`ctVector`](@ref), [`DState`](@ref). """ const DCostate = ctVector # include("exception.jl") include("description.jl") include("default.jl") include("types.jl") include("functions.jl") include("utils.jl") # Optimal Control Model include("optimal_control_model-type.jl") include("optimal_control_model-getters.jl") include("optimal_control_model-setters.jl") # Optimal Control Solution include("optimal_control_solution-type.jl") include("optimal_control_solution-getters.jl") include("optimal_control_solution-setters.jl") # include("differential_geometry.jl") include("ctparser_utils.jl") include("onepass.jl") include("repl.jl") include("init.jl") include("print.jl") # Numeric types export ctNumber, ctVector, Time, Times, TimesDisc export States, Costates, Controls, State, Costate, Control, Variable, Dimension, Index export DState, DCostate export TimeDependence, Autonomous, NonAutonomous export VariableDependence, NonFixed, Fixed # Description export Description, add, getFullDescription, remove # Exceptions export CTException, ParsingError, AmbiguousDescription, IncorrectMethod export IncorrectArgument, IncorrectOutput, NotImplemented, UnauthorizedCall export ExtensionError # AD export set_AD_backend # Functions export Hamiltonian, HamiltonianVectorField, VectorField export Mayer, Lagrange, Dynamics, ControlLaw, FeedbackControl, Multiplier export Mayer!, Lagrange!, Dynamics! export BoundaryConstraint, StateConstraint, ControlConstraint, MixedConstraint, VariableConstraint export BoundaryConstraint!, StateConstraint!, ControlConstraint!, MixedConstraint!, VariableConstraint! # Model export OptimalControlModel export Model export __OCPModel # todo: to be updated, redirection to Model to avoid confusion with other Model functions from other packages. Due to @def macro export variable!, time!, constraint!, dynamics!, objective!, state!, control!, remove_constraint!, model_expression! export is_autonomous, is_fixed export is_time_independent, is_time_dependent export is_min, is_max export is_variable_dependent, is_variable_independent export is_in_place export nlp_constraints!, constraints, constraints_labels, constraint export has_free_final_time, has_free_initial_time, has_lagrange_cost, has_mayer_cost export dim_control_constraints, dim_state_constraints, dim_mixed_constraints, dim_path_constraints export dim_boundary_constraints, dim_variable_constraints, dim_control_range export dim_state_range, dim_variable_range export model_expression, initial_time, initial_time_name, final_time, final_time_name, time_name export control_dimension, control_components_names, control_name export state_dimension, state_components_names, state_name export variable_dimension, variable_components_names, variable_name export lagrange, mayer, criterion, dynamics export __constraint, __lagrange, __mayer, __dynamics # todo: remove after in place tests # Solution export OptimalControlSolution export time_grid, control, state, variable, costate, objective export state_discretized, control_discretized, costate_discretized export iterations, stopping, message, success, infos export boundary_constraints, mult_boundary_constraints export variable_constraints, mult_variable_constraints, mult_variable_box_lower, mult_variable_box_upper export control_constraints, mult_control_constraints export state_constraints, mult_state_constraints export mixed_constraints, mult_mixed_constraints export mult_state_box_lower, mult_state_box_upper export mult_control_box_lower, mult_control_box_upper export time_grid!, costate!, iterations!, stopping!, message!, success!, infos! export boundary_constraints!, mult_boundary_constraints! export variable_constraints!, mult_variable_constraints!, mult_variable_box_lower!, mult_variable_box_upper! export control_constraints!, mult_control_constraints!, mult_control_box_lower!, mult_control_box_upper! export state_constraints!, mult_state_constraints!, mult_state_box_lower!, mult_state_box_upper! export mixed_constraints!, mult_mixed_constraints! # Initialization export OptimalControlInit # Utils export ctgradient, ctjacobian, ctinterpolate, ctindices, ctupperscripts # Differential geometry export Lie, @Lie, Poisson, HamiltonianLift, AbstractHamiltonian, Lift, β‹…, βˆ‚β‚œ # ctparser_utils export replace_call, constraint_type # onepass export @def # repl export ct_repl, ct_repl_update_model isdefined(Base, :active_repl) && ct_repl() end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
10690
# ctparser_utils """ $(TYPEDSIGNATURES) Expr iterator: apply `_Expr` to nodes and `f` to leaves of the AST. # Example ```@example julia> id(e) = expr_it(e, Expr, x -> x) ``` """ expr_it(e, _Expr, f) = if e isa Expr args = e.args n = length(args) newargs = [expr_it(e.args[i], _Expr, f) for i ∈ 1:n] return _Expr(e.head, newargs...) else return f(e) end """ $(TYPEDSIGNATURES) Substitute expression `e1` by expression `e2` in expression `e`. # Examples ```@example julia> e = :( ∫( r(t)^2 + 2u₁(t)) β†’ min ) :(∫(r(t) ^ 2 + 2 * u₁(t)) β†’ min) julia> subs(e, :r, :( x[1] )) :(∫((x[1])(t) ^ 2 + 2 * u₁(t)) β†’ min) julia> e = :( ∫( u₁(t)^2 + 2uβ‚‚(t)) β†’ min ) :(∫(u₁(t) ^ 2 + 2 * uβ‚‚(t)) β†’ min) julia> for i ∈ 1:2 e = subs(e, Symbol(:u, Char(8320+i)), :( u[\$i] )) end; e :(∫((u[1])(t) ^ 2 + 2 * (u[2])(t)) β†’ min) julia> t = :t; t0 = 0; tf = :tf; x = :x; u = :u; julia> e = :( x[1](0) * 2x(tf) - x[2](tf) * 2x(0) ) :((x[1])(0) * (2 * x(tf)) - (x[2])(tf) * (2 * x(0))) julia> x0 = Symbol(x, 0); subs(e, :( \$x[1](\$(t0)) ), :( \$x0[1] )) :(x0[1] * (2 * x(tf)) - (x[2])(tf) * (2 * x(0))) ``` """ subs(e, e1::Union{Symbol, Real}, e2) = expr_it(e, Expr, x -> x == e1 ? e2 : x) # optimised for some litterals (including symbols) subs(e, e1, e2) = begin foo(e1, e2) = (h, args...) -> begin f = Expr(h, args...) f == e1 ? e2 : f end expr_it(e, foo(e1, e2), f -> f == e1 ? e2 : f) end """ $(TYPEDSIGNATURES) Replace calls in e of the form `(...x...)(t)` by `(...y...)`. # Example ```@example julia> t = :t; t0 = 0; tf = :tf; x = :x; u = :u; julia> e = :( x[1](0) * 2x(tf) - x[2](tf) * 2x(0) ) :((x[1])(0) * (2 * x(tf)) - (x[2])(tf) * (2 * x(0))) julia> x0 = Symbol(x, 0); e = replace_call(e, x, t0, x0) :(x0[1] * (2 * x(tf)) - (x[2])(tf) * (2x0)) julia> xf = Symbol(x, "f"); replace_call(ans, x, tf, xf) :(x0[1] * (2xf) - xf[2] * (2x0)) julia> e = :( A*x(t) + B*u(t) ); replace_call(replace_call(e, x, t, x), u, t, u) :(A * x + B * u) julia> e = :( F0(x(t)) + u(t)*F1(x(t)) ); replace_call(replace_call(e, x, t, x), u, t, u) :(F0(x) + u * F1(x)) julia> e = :( 0.5u(t)^2 ); replace_call(e, u, t, u) :(0.5 * u ^ 2) ``` """ replace_call(e, x::Symbol, t, y) = replace_call(e, [x], t, [y]) """ $(TYPEDSIGNATURES) Replace calls in e of the form `(...x1...x2...)(t)` by `(...y1...y2...)` for all symbols `x1`, `x2`... in the vector `x`. # Example ```@example julia> t = :t; t0 = 0; tf = :tf; x = :x; u = :u; julia> e = :( (x^2 + u[1])(t) ); replace_call(e, [ x, u ], t , [ :xx, :uu ]) :(xx ^ 2 + uu[1]) julia> e = :( ((x^2)(t) + u[1])(t) ); replace_call(e, [ x, u ], t , [ :xx, :uu ]) :(xx ^ 2 + uu[1]) julia> e = :( ((x^2)(t0) + u[1])(t) ); replace_call(e, [ x, u ], t , [ :xx, :uu ]) :((xx ^ 2)(t0) + uu[1]) ``` """ replace_call(e, x::Vector{Symbol}, t, y) = begin @assert length(x) == length(y) foo(x, t, y) = (h, args...) -> begin ee = Expr(h, args...) @match ee begin :($eee($tt)) && if tt == t end => let ch = false for i ∈ 1:length(x) if has(eee, x[i]) eee = subs(eee, x[i], y[i]) ch = true # todo: unnecessary (as subs can be idempotent)? end end ch ? eee : ee end _ => ee end end expr_it(e, foo(x, t, y), x -> x) end """ $(TYPEDSIGNATURES) Return true if e contains e1. # Example ```@example julia> e = :( ∫( x[1](t)^2 + 2*u(t) ) β†’ min ) :(∫((x[1])(t) ^ 2 + 2 * u(t)) β†’ min) julia> has(e, 2) true julia> has(e, :x) true julia> has(e, :min) true julia> has(e, :( x[1](t)^2 )) true julia> !has(e, :( x[1](t)^3 )) true julia> !has(e, 3) true julia> !has(e, :max) true julia> has(:x, :x) true julia> !has(:x, 2) true julia> !has(:x, :y) true ``` """ has(e, e1) = begin foo(e1) = (h, args...) -> begin ee = Expr(h, args...) if :yes ∈ args :yes else ee == e1 ? :yes : ee end end expr_it(e, foo(e1), x -> x == e1 ? :yes : x) == :yes end """ $(TYPEDSIGNATURES) Return true if e contains a `(...x...)(t)` call. # Example ```@example julia> e = :( ∫( x[1](t)^2 + 2*u(t) ) β†’ min ) :(∫((x[1])(t) ^ 2 + 2 * u(t)) β†’ min) julia> has(e, :x, :t) true julia> has(e, :u, :t) true ``` """ has(e, x, t) = begin foo(x, t) = (h, args...) -> begin ee = Expr(h, args...) if :yes ∈ args :yes else @match ee begin :($eee($tt)) => (tt == t && has(eee, x)) ? :yes : ee _ => ee end end end expr_it(e, foo(x, t), x -> x) == :yes end """ $(TYPEDSIGNATURES) Return the type constraint among `:initial`, `:final`, `:boundary`, `:control_range`, `:control_fun`, `:state_range`, `:state_fun`, `:mixed`, `:variable_range`, `:variable_fun` (`:other` otherwise), together with the appropriate value (range, updated expression...) Expressions like `u(t0)` where `u` is the control and `t0` the initial time return `:other`. # Example ```@example julia> t = :t; t0 = 0; tf = :tf; x = :x; u = :u; v = :v julia> constraint_type(:( yΜ‡(t) ), t, t0, tf, x, u, v) :other julia> constraint_type(:( xΜ‡(s) ), t, t0, tf, x, u, v) :other julia> constraint_type(:( x(0)' ), t, t0, tf, x, u, v) :boundary julia> constraint_type(:( x(t)' ), t, t0, tf, x, u, v) :state_fun julia> constraint_type(:( x(0) ), t, t0, tf, x, u, v) (:initial, nothing) julia> constraint_type(:( x[1:2:5](0) ), t, t0, tf, x, u, v) (:initial, 1:2:5) julia> constraint_type(:( x[1:2](0) ), t, t0, tf, x, u, v) (:initial, 1:2) julia> constraint_type(:( x[1](0) ), t, t0, tf, x, u, v) (:initial, 1) julia> constraint_type(:( 2x[1](0)^2 ), t, t0, tf, x, u, v) :boundary julia> constraint_type(:( x(tf) ), t, t0, tf, x, u, v) (:final, nothing) j julia> constraint_type(:( x[1:2:5](tf) ), t, t0, tf, x, u, v) (:final, 1:2:5) julia> constraint_type(:( x[1:2](tf) ), t, t0, tf, x, u, v) (:final, 1:2) julia> constraint_type(:( x[1](tf) ), t, t0, tf, x, u, v) (:final, 1) julia> constraint_type(:( 2x[1](tf)^2 ), t, t0, tf, x, u, v) :boundary julia> constraint_type(:( x[1](tf) - x[2](0) ), t, t0, tf, x, u, v) :boundary julia> constraint_type(:( u[1:2:5](t) ), t, t0, tf, x, u, v) (:control_range, 1:2:5) julia> constraint_type(:( u[1:2](t) ), t, t0, tf, x, u, v) (:control_range, 1:2) julia> constraint_type(:( u[1](t) ), t, t0, tf, x, u, v) (:control_range, 1) julia> constraint_type(:( u(t) ), t, t0, tf, x, u, v) (:control_range, nothing) julia> constraint_type(:( 2u[1](t)^2 ), t, t0, tf, x, u, v) :control_fun julia> constraint_type(:( x[1:2:5](t) ), t, t0, tf, x, u, v) (:state_range, 1:2:5) julia> constraint_type(:( x[1:2](t) ), t, t0, tf, x, u, v) (:state_range, 1:2) julia> constraint_type(:( x[1](t) ), t, t0, tf, x, u, v) (:state_range, 1) julia> constraint_type(:( x(t) ), t, t0, tf, x, u, v) (:state_range, nothing) julia> constraint_type(:( 2x[1](t)^2 ), t, t0, tf, x, u, v) :state_fun julia> constraint_type(:( 2u[1](t)^2 * x(t) ), t, t0, tf, x, u, v) :mixed julia> constraint_type(:( 2u[1](0)^2 * x(t) ), t, t0, tf, x, u, v) :other julia> constraint_type(:( 2u[1](0)^2 * x(t) ), t, t0, tf, x, u, v) :other julia> constraint_type(:( 2u[1](t)^2 * x(t) + v ), t, t0, tf, x, u, v) :mixed julia> constraint_type(:( v[1:2:10] ), t, t0, tf, x, u, v) (:variable_range, 1:2:9) julia> constraint_type(:( v[1:10] ), t, t0, tf, x, u, v) (:variable_range, 1:10) julia> constraint_type(:( v[2] ), t, t0, tf, x, u, v) (:variable_range, 2) julia> constraint_type(:( v ), t, t0, tf, x, u, v) (:variable_range, nothing) julia> constraint_type(:( v^2 + 1 ), t, t0, tf, x, u, v) :variable_fun julia> constraint_type(:( v[2]^2 + 1 ), t, t0, tf, x, u, v) :variable_fun ``` """ constraint_type(e, t, t0, tf, x, u, v) = begin @match [ has(e, x, t0), has(e, x, tf), has(e, u, t), has(e, x, t), has(e, u, t0), has(e, u, tf), has(e, v), ] begin [true, false, false, false, false, false, _] => @match e begin :($y[($i):($p):($j)]($s)) && if (y == x && s == t0) end => (:initial, i:p:j) :($y[($i):($j)]($s)) && if (y == x && s == t0) end => (:initial, i:j) :($y[$i]($s)) && if (y == x && s == t0) end => (:initial, i) :($y($s)) && if (y == x && s == t0) end => (:initial, nothing) _ => :boundary end [false, true, false, false, false, false, _] => @match e begin :($y[($i):($p):($j)]($s)) && if (y == x && s == tf) end => (:final, i:p:j) :($y[($i):($j)]($s)) && if (y == x && s == tf) end => (:final, i:j) :($y[$i]($s)) && if (y == x && s == tf) end => (:final, i) :($y($s)) && if (y == x && s == tf) end => (:final, nothing) _ => :boundary end [true, true, false, false, false, false, _] => :boundary [false, false, true, false, false, false, _] => @match e begin :($c[($i):($p):($j)]($s)) && if (c == u && s == t) end => (:control_range, i:p:j) :($c[($i):($j)]($s)) && if (c == u && s == t) end => (:control_range, i:j) :($c[$i]($s)) && if (c == u && s == t) end => (:control_range, i) :($c($s)) && if (c == u && s == t) end => (:control_range, nothing) _ => :control_fun end [false, false, false, true, false, false, _] => @match e begin :($y[($i):($p):($j)]($s)) && if (y == x && s == t) end => (:state_range, i:p:j) :($y[($i):($j)]($s)) && if (y == x && s == t) end => (:state_range, i:j) :($y[$i]($s)) && if (y == x && s == t) end => (:state_range, i) :($y($s)) && if (y == x && s == t) end => (:state_range, nothing) _ => :state_fun end [false, false, true, true, false, false, _] => :mixed [false, false, false, false, false, false, true] => @match e begin :($w[($i):($p):($j)]) && if (w == v) end => (:variable_range, i:p:j) :($w[($i):($j)]) && if (w == v) end => (:variable_range, i:j) :($w[$i]) && if (w == v) end => (:variable_range, i) _ && if (e == v) end => (:variable_range, nothing) _ => :variable_fun end _ => :other end end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
4945
# const __default_AD_backend = Ref(AutoForwardDiff()) function set_AD_backend(AD) global __default_AD_backend[] = AD nothing end """ $(TYPEDSIGNATURES) Used to set the default value of Automatic Differentiation backend. The default value is `AutoForwardDiff()`, that is the `ForwardDiff` package is used by default. """ __get_AD_backend() = __default_AD_backend[] # default AD backend """ $(TYPEDSIGNATURES) Used to set the default value of the time dependence of the functions. The default value is `Autonomous`, which means that the functions are considered time independent. The other possible time dependence is `NonAutonomous`, which means that the functions are considered time dependent. """ __fun_time_dependence() = Autonomous """ $(TYPEDSIGNATURES) Used to set the default value of the variable dependence of the functions. The default value is `Fixed`, which means that the functions are considered variable independent. The other possible variable dependence is `NonFixed`, which means that the functions are considered variable dependent. """ __fun_variable_dependence() = Fixed """ $(TYPEDSIGNATURES) Used to set the default value of the time dependence of the Optimal Control Problem. The default value is `Autonomous`, which means that the Optimal Control Problem is considered time independent. The other possible time dependence is `NonAutonomous`, which means that all the functions used to define the Optimal Control Problem are considered time dependent. """ __ocp_time_dependence() = Autonomous """ $(TYPEDSIGNATURES) Used to set the default value of the variable dependence of the Optimal Control Problem. The default value is `Fixed`, which means that the Optimal Control Problem is considered variable independent. The other possible variable dependence is `NonFixed`, which means that all the functions used to define the Optimal Control Problem are considered variable dependent. """ __ocp_variable_dependence() = Fixed """ $(TYPEDSIGNATURES) Used to set the default value of the names of the variables. The default value is `"v"`. """ __variable_name() = "v" """ $(TYPEDSIGNATURES) Used to set the default value of the names of the variables. The default value is `["v"]` for a one dimensional variable, and `["v₁", "vβ‚‚", ...]` for a multi dimensional variable. """ __variable_components_names(q::Dimension, name::String) = q > 1 ? [name * ctindices(i) for i ∈ range(1, q)] : [name] """ $(TYPEDSIGNATURES) Used to set the default value of the name of the state. The default value is `"x"`. """ __state_name() = "x" """ $(TYPEDSIGNATURES) Used to set the default value of the names of the states. The default value is `["x"]` for a one dimensional state, and `["x₁", "xβ‚‚", ...]` for a multi dimensional state. """ __state_components_names(n::Dimension, name::String) = n > 1 ? [name * ctindices(i) for i ∈ range(1, n)] : [name] """ $(TYPEDSIGNATURES) Used to set the default value of the names of the control. The default value is `"u"`. """ __control_name() = "u" """ $(TYPEDSIGNATURES) Used to set the default value of the names of the controls. The default value is `["u"]` for a one dimensional control, and `["u₁", "uβ‚‚", ...]` for a multi dimensional control. """ __control_components_names(m::Dimension, name::String) = m > 1 ? [name * ctindices(i) for i ∈ range(1, m)] : [name] """ $(TYPEDSIGNATURES) Used to set the default value of the name of the time. The default value is `t`. """ __time_name() = "t" """ $(TYPEDSIGNATURES) Used to set the default value of the type of criterion. Either :min or :max. The default value is `:min`. The other possible criterion type is `:max`. """ __criterion_type() = :min """ $(TYPEDSIGNATURES) Used to set the default value of the label of a constraint. A unique value is given to each constraint using the `gensym` function and prefixing by `:unamed`. """ __constraint_label() = gensym(:unamed) """ $(TYPEDSIGNATURES) Used to set the default value of the stockage of elements in a matrix. The default value is `1`. """ __matrix_dimension_stock() = 1 """ $(TYPEDSIGNATURES) Used to set the default value of the display argument. The default value is `true`, which means that the output is printed during resolution. """ __display() = true """ $(TYPEDSIGNATURES) Used to set the default value of the callbacks argument. The default value is `()`, which means that no additional callback is given. """ __callbacks() = () """ $(TYPEDSIGNATURES) Used to set the default interpolation function used for initialisation. The default value is `Interpolations.linear_interpolation`, which means that the initial guess is linearly interpolated. """ function __init_interpolation() return (T, U) -> Interpolations.linear_interpolation(T, U, extrapolation_bc = Interpolations.Line()) end """ $(TYPEDSIGNATURES) Used to set the default initial guess. The default value is `nothing`. """ __ocp_init() = nothing
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
3237
""" DescVarArg is a Vararg of symbols. `DescVarArg` is a type alias for a Vararg of symbols. ```@example julia> const DescVarArg = Vararg{Symbol} ``` See also: [`Description`](@ref). """ const DescVarArg = Vararg{Symbol} """ A description is a tuple of symbols. `Description` is a type alias for a tuple of symbols. ```@example julia> const Description = Tuple{DescVarArg} ``` See also: [`DescVarArg`](@ref). # Example [`Base.show`](@ref) is overloaded for descriptions, that is tuple of descriptions are printed as follows: ```@example julia> display( ( (:a, :b), (:b, :c) ) ) (:a, :b) (:b, :c) ``` """ const Description = Tuple{DescVarArg} """ $(TYPEDSIGNATURES) Print a tuple of descriptions. # Example ```@example julia> display( ( (:a, :b), (:b, :c) ) ) (:a, :b) (:b, :c) ``` """ function Base.show(io::IO, ::MIME"text/plain", descriptions::Tuple{Vararg{Description}}) N = size(descriptions, 1) for i in range(1, N) description = descriptions[i] i < N ? print(io, "$description\n") : print(io, "$description") end end """ $(TYPEDSIGNATURES) Return a tuple containing only the description `y`. # Example ```@example julia> descriptions = () julia> descriptions = add(descriptions, (:a,)) (:a,) julia> print(descriptions) ((:a,),) julia> descriptions[1] (:a,) ``` """ add(x::Tuple{}, y::Description)::Tuple{Vararg{Description}} = (y,) """ $(TYPEDSIGNATURES) Concatenate the description `y` to the tuple of descriptions `x` if `x` does not contain `y` and return the new tuple of descriptions. Throw an error if the description `y` is already contained in `x`. # Example ```@example julia> descriptions = () julia> descriptions = add(descriptions, (:a,)) (:a,) julia> descriptions = add(descriptions, (:b,)) (:a,) (:b,) julia> descriptions = add(descriptions, (:b,)) ERROR: IncorrectArgument: the description (:b,) is already in ((:a,), (:b,)) ``` """ function add(x::Tuple{Vararg{Description}}, y::Description)::Tuple{Vararg{Description}} y ∈ x ? throw(IncorrectArgument("the description $y is already in $x")) : return (x..., y) end """ $(TYPEDSIGNATURES) Return a complete description from an incomplete description `desc` and a list of complete descriptions `desc_list`. If several complete descriptions are possible, then the first one is returned. # Example ```@example julia> desc_list = ((:a, :b), (:b, :c), (:a, :c)) (:a, :b) (:b, :c) (:a, :c) julia> getFullDescription((:a,), desc_list) (:a, :b) ``` """ function getFullDescription(desc::Description, desc_list::Tuple{Vararg{Description}})::Description n = size(desc_list, 1) table = zeros(Int8, n, 2) for i in range(1, n) table[i, 1] = size(desc ∩ desc_list[i], 1) table[i, 2] = desc βŠ† desc_list[i] ? 1 : 0 end if maximum(table[:, 2]) == 0 throw(AmbiguousDescription(desc)) end # argmax : Return the index or key of the maximal element in a collection. return desc_list[argmax(table[:, 1])] end """ $(TYPEDSIGNATURES) Return the difference between the description `x` and the description `y`. # Example ```@example julia> remove((:a, :b), (:a,)) (:b,) ``` """ function remove(x::Description, y::Description)::Description return Tuple(setdiff(x, y)) end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
22324
""" $(TYPEDSIGNATURES) Return the HamiltonianLift of a VectorField. # Example ```@example julia> HL = Lift(VectorField(x -> [x[1]^2,x[2]^2], autonomous=true, variable=false)) julia> HL([1, 0], [0, 1]) 0 julia> HL = Lift(VectorField((t, x, v) -> [t+x[1]^2,x[2]^2+v], autonomous=false, variable=true)) julia> HL(1, [1, 0], [0, 1], 1) 1 julia> H = Lift(x -> 2x) julia> H(1, 1) 2 julia> H = Lift((t, x, v) -> 2x + t - v, autonomous=false, variable=true) julia> H(1, 1, 1, 1) 2 julia> H = Lift((t, x, v) -> 2x + t - v, NonAutonomous, NonFixed) julia> H(1, 1, 1, 1) 2 ``` """ function Lift(X::VectorField)::HamiltonianLift return HamiltonianLift(X) end """ $(TYPEDSIGNATURES) Return the Lift of a function. Dependencies are specified with boolean : autonomous and variable. # Example ```@example julia> H = Lift(x -> 2x) julia> H(1, 1) 2 julia> H = Lift((t, x, v) -> 2x + t - v, autonomous=false, variable=true) julia> H(1, 1, 1, 1) 2 ``` """ function Lift(X::Function; autonomous::Bool = true, variable::Bool = false)::Function return @match (autonomous, variable) begin (true, false) => (x, p) -> p' * X(x) (true, true) => (x, p, v) -> p' * X(x, v) (false, false) => (t, x, p) -> p' * X(t, x) _ => (t, x, p, v) -> p' * X(t, x, v) end end """ $(TYPEDSIGNATURES) Return the Lift of a function. Dependencies are specified with DataType : Autonomous, NonAutonomous and Fixed, NonFixed. # Example ```@example julia> H = Lift(x -> 2x) julia> H(1, 1) 2 julia> H = Lift((t, x, v) -> 2x + t - v, NonAutonomous, NonFixed) julia> H(1, 1, 1, 1) 2 ``` """ function Lift(X::Function, dependences::DataType...)::Function __check_dependencies(dependences) autonomous = NonAutonomous ∈ dependences ? false : true variable = NonFixed ∈ dependences ? true : false return Lift(X; autonomous = autonomous, variable = variable) end # --------------------------------------------------------------------------- # Lie derivative of a scalar function along a vector field or a function: L_X(f) = Xβ‹…f # (postulate) # (Xβ‹…f)(x) = f'(x)β‹…X(x) # (Xβ‹…f)(t, x) = βˆ‚β‚“f(t, x)β‹…X(t, x) # (gβ‹…f)(x) = f'(x)β‹…G(x) with G the vector of g """ $(TYPEDSIGNATURES) Lie derivative of a scalar function along a vector field : L_X(f) = Xβ‹…f, in autonomous case # Example ```@example julia> Ο† = x -> [x[2], -x[1]] julia> X = VectorField(Ο†) julia> f = x -> x[1]^2 + x[2]^2 julia> (Xβ‹…f)([1, 2]) 0 ``` """ function β‹…(X::VectorField{Autonomous, <:VariableDependence}, f::Function)::Function return (x, args...) -> ctgradient(y -> f(y, args...), x)' * X(x, args...) end """ $(TYPEDSIGNATURES) Lie derivative of a scalar function along a vector field : L_X(f) = Xβ‹…f, in nonautonomous case # Example ```@example julia> Ο† = (t, x, v) -> [t + x[2] + v[1], -x[1] + v[2]] julia> X = VectorField(Ο†, NonAutonomous, NonFixed) julia> f = (t, x, v) -> t + x[1]^2 + x[2]^2 julia> (Xβ‹…f)(1, [1, 2], [2, 1]) 10 ``` """ function β‹…(X::VectorField{NonAutonomous, <:VariableDependence}, f::Function)::Function return (t, x, args...) -> ctgradient(y -> f(t, y, args...), x)' * X(t, x, args...) end """ $(TYPEDSIGNATURES) Lie derivative of a scalar function along a function. In this case both functions will be considered autonomous and non-variable. # Example ```@example julia> Ο† = x -> [x[2], -x[1]] julia> f = x -> x[1]^2 + x[2]^2 julia> (Ο†β‹…f)([1, 2]) 0 julia> Ο† = (t, x, v) -> [t + x[2] + v[1], -x[1] + v[2]] julia> f = (t, x, v) -> t + x[1]^2 + x[2]^2 julia> (Ο†β‹…f)(1, [1, 2], [2, 1]) MethodError ``` """ function β‹…(X::Function, f::Function)::Function return β‹…(VectorField(X, Autonomous, Fixed), f) end """ $(TYPEDSIGNATURES) Lie derivative of a scalar function along a vector field. # Example ```@example julia> Ο† = x -> [x[2], -x[1]] julia> X = VectorField(Ο†) julia> f = x -> x[1]^2 + x[2]^2 julia> Lie(X,f)([1, 2]) 0 julia> Ο† = (t, x, v) -> [t + x[2] + v[1], -x[1] + v[2]] julia> X = VectorField(Ο†, NonAutonomous, NonFixed) julia> f = (t, x, v) -> t + x[1]^2 + x[2]^2 julia> Lie(X, f)(1, [1, 2], [2, 1]) 10 ``` """ Lie(X::VectorField, f::Function)::Function = X β‹… f """ $(TYPEDSIGNATURES) Lie derivative of a scalar function along a function. Dependencies are specified with boolean : autonomous and variable. # Example ```@example julia> Ο† = x -> [x[2], -x[1]] julia> f = x -> x[1]^2 + x[2]^2 julia> Lie(Ο†,f)([1, 2]) 0 julia> Ο† = (t, x, v) -> [t + x[2] + v[1], -x[1] + v[2]] julia> f = (t, x, v) -> t + x[1]^2 + x[2]^2 julia> Lie(Ο†, f, autonomous=false, variable=true)(1, [1, 2], [2, 1]) 10 ``` """ function Lie(X::Function, f::Function; autonomous::Bool = true, variable::Bool = false)::Function time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return Lie(VectorField(X, time_dependence, variable_dependence), f) end """ $(TYPEDSIGNATURES) Lie derivative of a scalar function along a vector field or a function. Dependencies are specified with DataType : Autonomous, NonAutonomous and Fixed, NonFixed. # Example ```@example julia> Ο† = x -> [x[2], -x[1]] julia> f = x -> x[1]^2 + x[2]^2 julia> Lie(Ο†,f)([1, 2]) 0 julia> Ο† = (t, x, v) -> [t + x[2] + v[1], -x[1] + v[2]] julia> f = (t, x, v) -> t + x[1]^2 + x[2]^2 julia> Lie(Ο†, f, NonAutonomous, NonFixed)(1, [1, 2], [2, 1]) 10 ``` """ function Lie(X::Function, f::Function, dependences::DataType...)::Function __check_dependencies(dependences) time_dependence = NonAutonomous ∈ dependences ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependences ? NonFixed : Fixed return Lie(VectorField(X, time_dependence, variable_dependence), f) end # --------------------------------------------------------------------------- # partial derivative wrt time """ $(TYPEDSIGNATURES) Partial derivative wrt time of a function. # Example ```@example julia> βˆ‚β‚œ((t,x) -> t*x)(0,8) 8 ``` """ βˆ‚β‚œ(f) = (t, args...) -> ctgradient(y -> f(y, args...), t) # --------------------------------------------------------------------------- # "Directional derivative" of a vector field: internal and only used to compute # efficiently the Lie bracket of two vector fields """ $(TYPEDSIGNATURES) "Directional derivative" of a vector field: internal and only used to compute efficiently the Lie bracket of two vector fields, autonomous case # Example ```@example julia> X = VectorField(x -> [x[2], -x[1]]) julia> Y = VectorField(x -> [x[1], x[2]]) julia> CTBase.:(β…‹)(X, Y)([1, 2]) [2, -1] ``` """ function β…‹( X::VectorField{Autonomous, V}, Y::VectorField{Autonomous, V}, )::VectorField{Autonomous, V} where {V <: VariableDependence} return VectorField( (x, args...) -> x isa ctNumber ? ctgradient(y -> Y(y, args...), x) * X(x, args...) : ctjacobian(y -> Y(y, args...), x) * X(x, args...), Autonomous, V, ) end """ $(TYPEDSIGNATURES) "Directional derivative" of a vector field: internal and only used to compute efficiently the Lie bracket of two vector fields, nonautonomous case # Example ```@example julia> X = VectorField((t, x, v) -> [t + v[1] + v[2] + x[2], -x[1]], NonFixed, NonAutonomous) julia> Y = VectorField((t, x, v) -> [v[1] + v[2] + x[1], x[2]], NonFixed, NonAutonomous) julia> CTBase.:(β…‹)(X, Y)(1, [1, 2], [2, 3]) [8, -1] ``` """ function β…‹( X::VectorField{NonAutonomous, V}, Y::VectorField{NonAutonomous, V}, )::VectorField{NonAutonomous, V} where {V <: VariableDependence} return VectorField( (t, x, args...) -> x isa ctNumber ? ctgradient(y -> Y(t, y, args...), x) * X(t, x, args...) : ctjacobian(y -> Y(t, y, args...), x) * X(t, x, args...), NonAutonomous, V, ) end # --------------------------------------------------------------------------- # Lie bracket of two vector fields: [X, Y] = Lie(X, Y) # [X, Y]β‹…f = (X∘Y - Y∘X)β‹…f = (Xβ…‹Y - Yβ…‹X)β‹…f """ $(TYPEDSIGNATURES) Lie bracket of two vector fields: [X, Y] = Lie(X, Y), autonomous case # Example ```@example julia> f = x -> [x[2], 2x[1]] julia> g = x -> [3x[2], -x[1]] julia> X = VectorField(f) julia> Y = VectorField(g) julia> Lie(X, Y)([1, 2]) [7, -14] ``` """ function Lie( X::VectorField{Autonomous, V}, Y::VectorField{Autonomous, V}, )::VectorField{Autonomous, V} where {V <: VariableDependence} return VectorField((x, args...) -> (X β…‹ Y)(x, args...) - (Y β…‹ X)(x, args...), Autonomous, V) end """ $(TYPEDSIGNATURES) Lie bracket of two vector fields: [X, Y] = Lie(X, Y), nonautonomous case # Example ```@example julia> f = (t, x, v) -> [t + x[2] + v, -2x[1] - v] julia> g = (t, x, v) -> [t + 3x[2] + v, -x[1] - v] julia> X = VectorField(f, NonAutonomous, NonFixed) julia> Y = VectorField(g, NonAutonomous, NonFixed) julia> Lie(X, Y)(1, [1, 2], 1) [-7,12] ``` """ function Lie( X::VectorField{NonAutonomous, V}, Y::VectorField{NonAutonomous, V}, )::VectorField{NonAutonomous, V} where {V <: VariableDependence} return VectorField( (t, x, args...) -> (X β…‹ Y)(t, x, args...) - (Y β…‹ X)(t, x, args...), NonAutonomous, V, ) end # --------------------------------------------------------------------------- # Poisson bracket of two Hamiltonian functions: {f, g} = Poisson(f, g) # f(z) = pβ‹…X(x), g(z) = pβ‹…Y(x), z = (x, p) => {f,g}(z) = pβ‹…[X,Y](x) # {f, g}(z) = g'(z)β‹…F(z), where F is the Hamiltonian vector field of f # actually, z = (x, p) """ $(TYPEDSIGNATURES) Poisson bracket of two Hamiltonian functions (subtype of AbstractHamiltonian) : {f, g} = Poisson(f, g), autonomous case # Example ```@example julia> f = (x, p) -> x[2]^2 + 2x[1]^2 + p[1]^2 julia> g = (x, p) -> 3x[2]^2 + -x[1]^2 + p[2]^2 + p[1] julia> F = Hamiltonian(f) julia> G = Hamiltonian(g) julia> Poisson(f, g)([1, 2], [2, 1]) -20 julia> Poisson(f, G)([1, 2], [2, 1]) -20 julia> Poisson(F, g)([1, 2], [2, 1]) -20 ``` """ function Poisson( f::AbstractHamiltonian{Autonomous, V}, g::AbstractHamiltonian{Autonomous, V}, )::Hamiltonian{Autonomous, V} where {V <: VariableDependence} function fg(x, p, args...) n = size(x, 1) ff, gg = @match n begin 1 => (z -> f(z[1], z[2], args...), z -> g(z[1], z[2], args...)) _ => ( z -> f(z[1:n], z[(n + 1):(2n)], args...), z -> g(z[1:n], z[(n + 1):(2n)], args...), ) end df = ctgradient(ff, [x; p]) dg = ctgradient(gg, [x; p]) return df[(n + 1):(2n)]' * dg[1:n] - df[1:n]' * dg[(n + 1):(2n)] end return Hamiltonian(fg, Autonomous, V) end # f(t, z) = pβ‹…X(x), g(t, z) = pβ‹…Y(x), z = (x, p) => {f, g}(t, z) = pβ‹…[X,Y](t, x) # {f, g}(t, z) = βˆ‚β‚‚g(t, z)β‹…F(t, z) # actually, z = (x, p) """ $(TYPEDSIGNATURES) Poisson bracket of two Hamiltonian functions (subtype of AbstractHamiltonian) : {f, g} = Poisson(f, g), non autonomous case # Example ```@example julia> f = (t, x, p, v) -> t*v[1]*x[2]^2 + 2x[1]^2 + p[1]^2 + v[2] julia> g = (t, x, p, v) -> 3x[2]^2 + -x[1]^2 + p[2]^2 + p[1] + t - v[2] julia> F = Hamiltonian(f, autonomous=false, variable=true) julia> G = Hamiltonian(g, autonomous=false, variable=true) julia> Poisson(F, G)(2, [1, 2], [2, 1], [4, 4]) -76 julia> Poisson(f, g, NonAutonomous, NonFixed)(2, [1, 2], [2, 1], [4, 4]) -76 ``` """ function Poisson( f::AbstractHamiltonian{NonAutonomous, V}, g::AbstractHamiltonian{NonAutonomous, V}, )::Hamiltonian{NonAutonomous, V} where {V <: VariableDependence} function fg(t, x, p, args...) n = size(x, 1) ff, gg = @match n begin 1 => (z -> f(t, z[1], z[2], args...), z -> g(t, z[1], z[2], args...)) _ => ( z -> f(t, z[1:n], z[(n + 1):(2n)], args...), z -> g(t, z[1:n], z[(n + 1):(2n)], args...), ) end df = ctgradient(ff, [x; p]) dg = ctgradient(gg, [x; p]) return df[(n + 1):(2n)]' * dg[1:n] - df[1:n]' * dg[(n + 1):(2n)] end return Hamiltonian(fg, NonAutonomous, V) end """ $(TYPEDSIGNATURES) Poisson bracket of two HamiltonianLift functions : {f, g} = Poisson(f, g) # Example ```@example julia> f = x -> [x[1]^2+x[2]^2, 2x[1]^2] julia> g = x -> [3x[2]^2, x[2]-x[1]^2] julia> F = Lift(f) julia> G = Lift(g) julia> Poisson(F, G)([1, 2], [2, 1]) -64 julia> f = (t, x, v) -> [t*v[1]*x[2]^2, 2x[1]^2 + + v[2]] julia> g = (t, x, v) -> [3x[2]^2 + -x[1]^2, t - v[2]] julia> F = Lift(f, NonAutonomous, NonFixed) julia> G = Lift(g, NonAutonomous, NonFixed) julia> Poisson(F, G)(2, [1, 2], [2, 1], [4, 4]) 100 ``` """ function Poisson( f::HamiltonianLift{T, V}, g::HamiltonianLift{T, V}, )::HamiltonianLift{T, V} where {T <: TimeDependence, V <: VariableDependence} return HamiltonianLift(Lie(f.X, g.X)) end """ $(TYPEDSIGNATURES) Poisson bracket of two functions : {f, g} = Poisson(f, g) Dependencies are specified with boolean : autonomous and variable. # Example ```@example julia> f = (x, p) -> x[2]^2 + 2x[1]^2 + p[1]^2 julia> g = (x, p) -> 3x[2]^2 + -x[1]^2 + p[2]^2 + p[1] julia> Poisson(f, g)([1, 2], [2, 1]) -20 julia> f = (t, x, p, v) -> t*v[1]*x[2]^2 + 2x[1]^2 + p[1]^2 + v[2] julia> g = (t, x, p, v) -> 3x[2]^2 + -x[1]^2 + p[2]^2 + p[1] + t - v[2] julia> Poisson(f, g, autonomous=false, variable=true)(2, [1, 2], [2, 1], [4, 4]) -76 ``` """ function Poisson( f::Function, g::Function; autonomous::Bool = true, variable::Bool = false, )::Hamiltonian time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return Poisson( Hamiltonian(f, time_dependence, variable_dependence), Hamiltonian(g, time_dependence, variable_dependence), ) end """ $(TYPEDSIGNATURES) Poisson bracket of two functions : {f, g} = Poisson(f, g) Dependencies are specified with DataType : Autonomous, NonAutonomous and Fixed, NonFixed. # Example ```@example julia> f = (x, p) -> x[2]^2 + 2x[1]^2 + p[1]^2 julia> g = (x, p) -> 3x[2]^2 + -x[1]^2 + p[2]^2 + p[1] julia> Poisson(f, g)([1, 2], [2, 1]) -20 julia> f = (t, x, p, v) -> t*v[1]*x[2]^2 + 2x[1]^2 + p[1]^2 + v[2] julia> g = (t, x, p, v) -> 3x[2]^2 + -x[1]^2 + p[2]^2 + p[1] + t - v[2] julia> Poisson(f, g, NonAutonomous, NonFixed)(2, [1, 2], [2, 1], [4, 4]) -76 ``` """ function Poisson(f::Function, g::Function, dependences::DataType...)::Hamiltonian __check_dependencies(dependences) time_dependence = NonAutonomous ∈ dependences ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependences ? NonFixed : Fixed return Poisson( Hamiltonian(f, time_dependence, variable_dependence), Hamiltonian(g, time_dependence, variable_dependence), ) end """ $(TYPEDSIGNATURES) Poisson bracket of a function and an Hamiltonian function (subtype of AbstractHamiltonian) : {f, g} = Poisson(f, g) # Example ```@example julia> f = (x, p) -> x[2]^2 + 2x[1]^2 + p[1]^2 julia> g = (x, p) -> 3x[2]^2 + -x[1]^2 + p[2]^2 + p[1] julia> G = Hamiltonian(g) julia> Poisson(f, G)([1, 2], [2, 1]) -20 julia> f = (t, x, p, v) -> t*v[1]*x[2]^2 + 2x[1]^2 + p[1]^2 + v[2] julia> g = (t, x, p, v) -> 3x[2]^2 + -x[1]^2 + p[2]^2 + p[1] + t - v[2] julia> G = Hamiltonian(g, autonomous=false, variable=true) julia> Poisson(f, G)(2, [1, 2], [2, 1], [4, 4]) -76 ``` """ function Poisson( f::Function, g::AbstractHamiltonian{T, V}, )::Hamiltonian where {T <: TimeDependence, V <: VariableDependence} return Poisson(Hamiltonian(f, T, V), g) end """ $(TYPEDSIGNATURES) Poisson bracket of an Hamiltonian function (subtype of AbstractHamiltonian) and a function : {f, g} = Poisson(f, g), autonomous case # Example ```@example julia> f = (x, p) -> x[2]^2 + 2x[1]^2 + p[1]^2 julia> g = (x, p) -> 3x[2]^2 + -x[1]^2 + p[2]^2 + p[1] julia> F = Hamiltonian(f) julia> Poisson(F, g)([1, 2], [2, 1]) -20 julia> f = (t, x, p, v) -> t*v[1]*x[2]^2 + 2x[1]^2 + p[1]^2 + v[2] julia> g = (t, x, p, v) -> 3x[2]^2 + -x[1]^2 + p[2]^2 + p[1] + t - v[2] julia> F = Hamiltonian(f, autonomous=false, variable=true) julia> Poisson(F, g)(2, [1, 2], [2, 1], [4, 4]) -76 ``` """ function Poisson( f::AbstractHamiltonian{T, V}, g::Function, )::Hamiltonian where {T <: TimeDependence, V <: VariableDependence} return Poisson(f, Hamiltonian(g, T, V)) end # --------------------------------------------------------------------------- # Macros # @Lie [X, Y], for Lie brackets # @Lie {X, Y}, for Poisson brackets """ $(TYPEDSIGNATURES) Macros for Lie and Poisson brackets # Example ```@example julia> F0 = VectorField(x -> [x[1], x[2], (1-x[3])]) julia> F1 = VectorField(x -> [0, -x[3], x[2]]) julia> @Lie [F0, F1]([1, 2, 3]) [0, 5, 4] # julia> F0 = VectorField((t, x) -> [t+x[1], x[2], (1-x[3])], autonomous=false) julia> F1 = VectorField((t, x) -> [t, -x[3], x[2]], autonomous=false) julia> @Lie [F0, F1](1, [1, 2, 3]) # julia> F0 = VectorField((x, v) -> [x[1]+v, x[2], (1-x[3])], variable=true) julia> F1 = VectorField((x, v) -> [0, -x[3]-v, x[2]], variable=true) julia> @Lie [F0, F1]([1, 2, 3], 2) # julia> F0 = VectorField((t, x, v) -> [t+x[1]+v, x[2], (1-x[3])], autonomous=false, variable=true) julia> F1 = VectorField((t, x, v) -> [t, -x[3]-v, x[2]], autonomous=false, variable=true) julia> @Lie [F0, F1](1, [1, 2, 3], 2) # julia> H0 = Hamiltonian((x, p) -> 0.5*(2x[1]^2+x[2]^2+p[1]^2)) julia> H1 = Hamiltonian((x, p) -> 0.5*(3x[1]^2+x[2]^2+p[2]^2)) julia> @Lie {H0, H1}([1, 2, 3], [1, 0, 7]) 3.0 # julia> H0 = Hamiltonian((t, x, p) -> 0.5*(x[1]^2+x[2]^2+p[1]^2), autonomous=false) julia> H1 = Hamiltonian((t, x, p) -> 0.5*(x[1]^2+x[2]^2+p[2]^2), autonomous=false) julia> @Lie {H0, H1}(1, [1, 2, 3], [1, 0, 7]) # julia> H0 = Hamiltonian((x, p, v) -> 0.5*(x[1]^2+x[2]^2+p[1]^2+v), variable=true) julia> H1 = Hamiltonian((x, p, v) -> 0.5*(x[1]^2+x[2]^2+p[2]^2+v), variable=true) julia> @Lie {H0, H1}([1, 2, 3], [1, 0, 7], 2) # julia> H0 = Hamiltonian((t, x, p, v) -> 0.5*(x[1]^2+x[2]^2+p[1]^2+v), autonomous=false, variable=true) julia> H1 = Hamiltonian((t, x, p, v) -> 0.5*(x[1]^2+x[2]^2+p[2]^2+v), autonomous=false, variable=true) julia> @Lie {H0, H1}(1, [1, 2, 3], [1, 0, 7], 2) # ``` """ macro Lie(expr::Expr) fun(x) = @match (@capture(x, [a_, b_]), @capture(x, {c_, d_})) begin (true, false) => :(Lie($a, $b)) (false, true) => :(Poisson($c, $d)) (false, false) => x _ => error("internal error") end return esc(postwalk(fun, expr)) end """ $(TYPEDSIGNATURES) Macros for Poisson brackets # Example ```@example julia> H0 = (x, p) -> 0.5*(x[1]^2+x[2]^2+p[1]^2) julia> H1 = (x, p) -> 0.5*(x[1]^2+x[2]^2+p[2]^2) julia> @Lie {H0, H1}([1, 2, 3], [1, 0, 7]) autonomous=true variable=false # julia> H0 = (t, x, p) -> 0.5*(x[1]^2+x[2]^2+p[1]^2) julia> H1 = (t, x, p) -> 0.5*(x[1]^2+x[2]^2+p[2]^2) julia> @Lie {H0, H1}(1, [1, 2, 3], [1, 0, 7]) autonomous=false variable=false # julia> H0 = (x, p, v) -> 0.5*(x[1]^2+x[2]^2+p[1]^2+v) julia> H1 = (x, p, v) -> 0.5*(x[1]^2+x[2]^2+p[2]^2+v) julia> @Lie {H0, H1}([1, 2, 3], [1, 0, 7], 2) autonomous=true variable=true # julia> H0 = (t, x, p, v) -> 0.5*(x[1]^2+x[2]^2+p[1]^2+v) julia> H1 = (t, x, p, v) -> 0.5*(x[1]^2+x[2]^2+p[2]^2+v) julia> @Lie {H0, H1}(1, [1, 2, 3], [1, 0, 7], 2) autonomous=false variable=true ``` """ macro Lie(expr::Expr, arg1, arg2) local autonomous = true local variable = false @match arg1 begin :(Autonomous) => begin autonomous = true end :(NonAutonomous) => begin autonomous = false end :(autonomous = $a) => begin autonomous = a end :(NonFixed) => begin variable = true end :(Fixed) => begin variable = false end :(variable = $a) => begin variable = a end _ => throw(IncorrectArgument("Invalid argument: " * string(arg1))) end @match arg2 begin :(Autonomous) => begin autonomous = true end :(NonAutonomous) => begin autonomous = false end :(autonomous = $a) => begin autonomous = a end :(NonFixed) => begin variable = true end :(Fixed) => begin variable = false end :(variable = $a) => begin variable = a end _ => throw(IncorrectArgument("Invalid argument: " * string(arg2))) end fun(x) = @match (@capture(x, [a_, b_]), @capture(x, {c_, d_})) begin #(true, false) => :( Lie($a, $b; autonomous=$autonomous, variable=$variable)) (false, true) => quote ($c isa Function && $d isa Function) ? Poisson($c, $d; autonomous = $autonomous, variable = $variable) : Poisson($c, $d) end (false, false) => x _ => error("internal error") end return esc(postwalk(fun, expr)) end """ $(TYPEDSIGNATURES) Macros for Lie and Poisson brackets # Example ```@example julia> H0 = (t, x, p) -> 0.5*(x[1]^2+x[2]^2+p[1]^2) julia> H1 = (t, x, p) -> 0.5*(x[1]^2+x[2]^2+p[2]^2) julia> @Lie {H0, H1}(1, [1, 2, 3], [1, 0, 7]) autonomous=false # julia> H0 = (x, p, v) -> 0.5*(x[1]^2+x[2]^2+p[1]^2+v) julia> H1 = (x, p, v) -> 0.5*(x[1]^2+x[2]^2+p[2]^2+v) julia> @Lie {H0, H1}([1, 2, 3], [1, 0, 7], 2) variable=true # ``` """ macro Lie(expr::Expr, arg) local autonomous = true local variable = false @match arg begin :(Autonomous) => begin autonomous = true end :(NonAutonomous) => begin autonomous = false end :(autonomous = $a) => begin autonomous = a end :(NonFixed) => begin variable = true end :(Fixed) => begin variable = false end :(variable = $a) => begin variable = a end _ => throw(IncorrectArgument("Invalid argument: " * string(arg))) end fun(x) = @match (@capture(x, [a_, b_]), @capture(x, {c_, d_})) begin #(true, false) => :( Lie($a, $b; autonomous=$autonomous, variable=$variable)) (false, true) => quote ($c isa Function && $d isa Function) ? Poisson($c, $d; autonomous = $autonomous, variable = $variable) : Poisson($c, $d) end (false, false) => x _ => error("internal error") end return esc(postwalk(fun, expr)) end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
3180
""" $(TYPEDEF) Abstract type for exceptions. """ abstract type CTException <: Exception end """ $(TYPEDEF) Exception thrown when the description is ambiguous / incorrect. **Fields** $(TYPEDFIELDS) """ struct AmbiguousDescription <: CTException var::Tuple{Vararg{Symbol}} end """ $(TYPEDSIGNATURES) Print the exception. """ Base.showerror(io::IO, e::AmbiguousDescription) = print(io, "AmbiguousDescription: the description ", e.var, " is ambiguous / incorrect") """ $(TYPEDEF) Exception thrown when an argument is inconsistent. **Fields** $(TYPEDFIELDS) """ struct IncorrectArgument <: CTException var::String end """ $(TYPEDSIGNATURES) Print the exception. """ Base.showerror(io::IO, e::IncorrectArgument) = print(io, "IncorrectArgument: ", e.var) """ $(TYPEDEF) Exception thrown when a method is incorrect. **Fields** $(TYPEDFIELDS) """ struct IncorrectMethod <: CTException var::Symbol end """ $(TYPEDSIGNATURES) Print the exception. """ Base.showerror(io::IO, e::IncorrectMethod) = print(io, "IncorrectMethod: ", e.var, " is not an existing method") """ $(TYPEDEF) Exception thrown when the output is incorrect. **Fields** $(TYPEDFIELDS) """ struct IncorrectOutput <: CTException var::String end """ $(TYPEDSIGNATURES) Print the exception. """ Base.showerror(io::IO, e::IncorrectOutput) = print(io, "IncorrectOutput: ", e.var) """ $(TYPEDEF) Exception thrown when a method is not implemented. **Fields** $(TYPEDFIELDS) """ struct NotImplemented <: CTException var::String end """ $(TYPEDSIGNATURES) Print the exception. """ Base.showerror(io::IO, e::NotImplemented) = print(io, "NotImplemented: ", e.var) """ $(TYPEDEF) Exception thrown when a call to a function is not authorized. **Fields** $(TYPEDFIELDS) """ struct UnauthorizedCall <: CTException var::String end """ $(TYPEDSIGNATURES) Print the exception. """ Base.showerror(io::IO, e::UnauthorizedCall) = print(io, "UnauthorizedCall: ", e.var) """ $(TYPEDEF) Exception thrown for syntax error during abstract parsing. **Fields** $(TYPEDFIELDS) """ struct ParsingError <: CTException var::String end """ $(TYPEDSIGNATURES) Print the exception. """ Base.showerror(io::IO, e::ParsingError) = print(io, "ParsingError: ", e.var) """ $(TYPEDEF) Exception thrown when an extension is not loaded but the user tries to call a function of it. **Fields** $(TYPEDFIELDS) """ mutable struct ExtensionError <: CTException weakdeps::Tuple{Vararg{Symbol}} function ExtensionError(weakdeps::Symbol...) isempty(weakdeps) && throw( UnauthorizedCall("Please provide at least one weak dependence for the extension."), ) e = new() e.weakdeps = weakdeps return e end end """ $(TYPEDSIGNATURES) Print the exception. """ function Base.showerror(io::IO, e::ExtensionError) print(io, "ExtensionError. Please make: ") printstyled(io, "julia>", color = :green, bold = true) printstyled(io, " using ", color = :magenta) N = size(e.weakdeps, 1) for i ∈ range(1, N) wd = e.weakdeps[i] i < N ? print(io, string(wd), ", ") : print(io, string(wd)) end nothing end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
57620
# -------------------------------------------------------------------------------------------------- """ $(TYPEDSIGNATURES) Return a ```BoundaryConstraint``` of a function. Dependencies are specified with a boolean, variable, false by default. ```@example julia> B = BoundaryConstraint((x0, xf) -> [xf[2]-x0[1], 2xf[1]+x0[2]^2]) julia> B = BoundaryConstraint((x0, xf, v) -> [v[3]+xf[2]-x0[1], v[1]-v[2]+2xf[1]+x0[2]^2], variable=true) ``` """ function BoundaryConstraint(f::Function; variable::Bool = false) variable_dependence = variable ? NonFixed : Fixed return BoundaryConstraint{variable_dependence}(f) end function BoundaryConstraint!(f!::Function; variable::Bool = false) variable_dependence = variable ? NonFixed : Fixed return BoundaryConstraint!{variable_dependence}(f!) end """ $(TYPEDSIGNATURES) Return a ```BoundaryConstraint``` of a function. Dependencies are specified with a DataType, NonFixed/Fixed, Fixed by default. ```@example julia> B = BoundaryConstraint((x0, xf) -> [xf[2]-x0[1], 2xf[1]+x0[2]^2]) julia> B = BoundaryConstraint((x0, xf, v) -> [v[3]+xf[2]-x0[1], v[1]-v[2]+2xf[1]+x0[2]^2], NonFixed) ``` """ function BoundaryConstraint(f::Function, dependencies::DataType...) __check_dependencies(dependencies) variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return BoundaryConstraint{variable_dependence}(f) end function BoundaryConstraint!(f!::Function, dependencies::DataType...) __check_dependencies(dependencies) variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return BoundaryConstraint!{variable_dependence}(f!) end """ $(TYPEDSIGNATURES) Return the evaluation of the BoundaryConstraint. ```@example julia> B = BoundaryConstraint((x0, xf) -> [xf[2]-x0[1], 2xf[1]+x0[2]^2]) julia> B([0, 0], [1, 1]) [1, 2] julia> B = BoundaryConstraint((x0, xf) -> [xf[2]-x0[1], 2xf[1]+x0[2]^2]) julia> B([0, 0], [1, 1],Real[]) [1, 2] julia> B = BoundaryConstraint((x0, xf, v) -> [v[3]+xf[2]-x0[1], v[1]-v[2]+2xf[1]+x0[2]^2], variable=true) julia> B([0, 0], [1, 1], [1, 2, 3]) [4, 1] ``` """ function (F::BoundaryConstraint{Fixed})(x0::State, xf::State)::ctVector return F.f(x0, xf) end function (F::BoundaryConstraint{Fixed})(x0::State, xf::State, v::Variable)::ctVector return F.f(x0, xf) end function (F::BoundaryConstraint{NonFixed})(x0::State, xf::State, v::Variable)::ctVector return F.f(x0, xf, v) end function (F::BoundaryConstraint!{Fixed})(r::ctVector, x0::State, xf::State)::Nothing return F.f!(r, x0, xf) end function (F::BoundaryConstraint!{Fixed})(r::ctVector, x0::State, xf::State, v::Variable)::Nothing return F.f!(r, x0, xf) end function (F::BoundaryConstraint!{NonFixed})(r::ctVector, x0::State, xf::State, v::Variable)::Nothing return F.f!(r, x0, xf, v) end # -------------------------------------------------------------------------------------------------- """ $(TYPEDSIGNATURES) Return a ```Mayer``` cost of a function. Dependencies are specified with a boolean, variable, false by default. ```@example julia> G = Mayer((x0, xf) -> xf[2]-x0[1]) julia> G = Mayer((x0, xf, v) -> v[3]+xf[2]-x0[1], variable=true) ``` """ function Mayer(f::Function; variable::Bool = false) variable_dependence = variable ? NonFixed : Fixed return Mayer{variable_dependence}(f) end function Mayer!(f!::Function; variable::Bool = false) variable_dependence = variable ? NonFixed : Fixed return Mayer!{variable_dependence}(f!) end """ $(TYPEDSIGNATURES) Return a ```Mayer``` cost of a function. Dependencies are specified with a DataType, NonFixed/Fixed, Fixed by default. ```@example julia> G = Mayer((x0, xf) -> xf[2]-x0[1]) julia> G = Mayer((x0, xf, v) -> v[3]+xf[2]-x0[1], NonFixed) ``` """ function Mayer(f::Function, dependencies::DataType...) __check_dependencies(dependencies) variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return Mayer{variable_dependence}(f) end function Mayer!(f!::Function, dependencies::DataType...) __check_dependencies(dependencies) variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return Mayer!{variable_dependence}(f!) end """ $(TYPEDSIGNATURES) Return the evaluation of the Mayer cost. ```@example julia> G = Mayer((x0, xf) -> xf[2]-x0[1]) julia> G([0, 0], [1, 1]) 1 julia> G = Mayer((x0, xf) -> xf[2]-x0[1]) julia> G([0, 0], [1, 1], Real[]) 1 julia> G = Mayer((x0, xf, v) -> v[3]+xf[2]-x0[1], variable=true) julia> G([0, 0], [1, 1], [1, 2, 3]) 4 ``` """ function (F::Mayer{Fixed})(x0::State, xf::State)::ctNumber return F.f(x0, xf) end function (F::Mayer{Fixed})(x0::State, xf::State, v::Variable)::ctNumber return F.f(x0, xf) end function (F::Mayer{NonFixed})(x0::State, xf::State, v::Variable)::ctNumber return F.f(x0, xf, v) end function (F::Mayer!{Fixed})(r::ctVector, x0::State, xf::State)::Nothing return F.f!(r, x0, xf) end function (F::Mayer!{Fixed})(r::ctVector, x0::State, xf::State, v::Variable)::Nothing return F.f!(r, x0, xf) end function (F::Mayer!{NonFixed})(r::ctVector, x0::State, xf::State, v::Variable)::Nothing return F.f!(r, x0, xf, v) end # -------------------------------------------------------------------------------------------------- # Hamiltonian """ $(TYPEDSIGNATURES) Return an ```Hamiltonian``` of a function. Dependencies are specified with a boolean, variable, false by default, autonomous, true by default. ```@example julia> H = Hamiltonian((x, p) -> x[1]^2+2p[2]) julia> H = Hamiltonian((t, x, p, v) -> [t+x[1]^2+2p[2]+v[3]], autonomous=false, variable=true) ``` """ function Hamiltonian(f::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return Hamiltonian{time_dependence, variable_dependence}(f) end """ $(TYPEDSIGNATURES) Return an ```Hamiltonian``` of a function. Dependencies are specified with DataType, Autonomous, NonAutonomous and Fixed, NonFixed. ```@example julia> H = Hamiltonian((x, p) -> x[1]^2+2p[2]) julia> H = Hamiltonian((t, x, p, v) -> [t+x[1]^2+2p[2]+v[3]], NonAutonomous, NonFixed) ``` """ function Hamiltonian(f::Function, dependencies::DataType...) __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return Hamiltonian{time_dependence, variable_dependence}(f) end """ $(TYPEDSIGNATURES) Return the value of the Hamiltonian. ```@example julia> Hamiltonian((x, p) -> x + p, Int64) IncorrectArgument julia> Hamiltonian((x, p) -> x + p, Int64) IncorrectArgument julia> H = Hamiltonian((x, p) -> [x[1]^2+2p[2]]) # autonomous=true, variable=false julia> H([1, 0], [0, 1]) MethodError # H must return a scalar julia> H = Hamiltonian((x, p) -> x[1]^2+2p[2]) julia> H([1, 0], [0, 1]) 3 julia> t = 1 julia> v = Real[] julia> H(t, [1, 0], [0, 1]) MethodError julia> H([1, 0], [0, 1], v) MethodError julia> H(t, [1, 0], [0, 1], v) 3 julia> H = Hamiltonian((x, p, v) -> x[1]^2+2p[2]+v[3], variable=true) julia> H([1, 0], [0, 1], [1, 2, 3]) 6 julia> H(t, [1, 0], [0, 1], [1, 2, 3]) 6 julia> H = Hamiltonian((t, x, p) -> t+x[1]^2+2p[2], autonomous=false) julia> H(1, [1, 0], [0, 1]) 4 julia> H(1, [1, 0], [0, 1], v) 4 julia> H = Hamiltonian((t, x, p, v) -> t+x[1]^2+2p[2]+v[3], autonomous=false, variable=true) julia> H(1, [1, 0], [0, 1], [1, 2, 3]) 7 ``` """ function (F::Hamiltonian{Autonomous, Fixed})(x::State, p::Costate)::ctNumber return F.f(x, p) end function (F::Hamiltonian{Autonomous, Fixed})(t::Time, x::State, p::Costate, v::Variable)::ctNumber return F.f(x, p) end function (F::Hamiltonian{Autonomous, NonFixed})(x::State, p::Costate, v::Variable)::ctNumber return F.f(x, p, v) end function (F::Hamiltonian{Autonomous, NonFixed})( t::Time, x::State, p::Costate, v::Variable, )::ctNumber return F.f(x, p, v) end function (F::Hamiltonian{NonAutonomous, Fixed})(t::Time, x::State, p::Costate)::ctNumber return F.f(t, x, p) end function (F::Hamiltonian{NonAutonomous, Fixed})( t::Time, x::State, p::Costate, v::Variable, )::ctNumber return F.f(t, x, p) end function (F::Hamiltonian{NonAutonomous, NonFixed})( t::Time, x::State, p::Costate, v::Variable, )::ctNumber return F.f(t, x, p, v) end # --------------------------------------------------------------------------- # HamiltonianLift """ $(TYPEDSIGNATURES) Return an ```HamiltonianLift``` of a function. Dependencies are specified with a boolean, variable, false by default, autonomous, true by default. ```@example julia> HL = HamiltonianLift(x -> [x[1]^2,x[2]^2], autonomous=true, variable=false) julia> HL = HamiltonianLift((x, v) -> [x[1]^2,x[2]^2+v], autonomous=true, variable=true) julia> HL = HamiltonianLift((t, x) -> [t+x[1]^2,x[2]^2], autonomous=false, variable=false) julia> HL = HamiltonianLift((t, x, v) -> [t+x[1]^2,x[2]^2+v], autonomous=false, variable=true) ``` """ function HamiltonianLift(f::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return HamiltonianLift(VectorField(f, time_dependence, variable_dependence)) end """ $(TYPEDSIGNATURES) Return an ```HamiltonianLift``` of a function. Dependencies are specified with DataType, Autonomous, NonAutonomous and Fixed, NonFixed. ```@example julia> HamiltonianLift(HamiltonianLift(VectorField(x -> [x[1]^2, 2x[2]], Int64)) IncorrectArgument julia> HL = HamiltonianLift(x -> [x[1]^2,x[2]^2], Autonomous, Fixed) julia> HL = HamiltonianLift((x, v) -> [x[1]^2,x[2]^2+v], Autonomous, NonFixed) julia> HL = HamiltonianLift((t, x) -> [t+x[1]^2,x[2]^2], NonAutonomous, Fixed) julia> HL = HamiltonianLift((t, x, v) -> [t+x[1]^2,x[2]^2+v], NonAutonomous, NonFixed) ``` """ function HamiltonianLift(f::Function, dependences::DataType...) __check_dependencies(dependences) time_dependence = NonAutonomous ∈ dependences ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependences ? NonFixed : Fixed return HamiltonianLift(VectorField(f, time_dependence, variable_dependence)) end """ $(TYPEDSIGNATURES) Return the value of the HamiltonianLift. ## Examples ```@example julia> HamiltonianLift(HamiltonianLift(VectorField(x -> [x[1]^2, 2x[2]], Int64)) IncorrectArgument julia> H = HamiltonianLift(VectorField(x -> [x[1]^2, 2x[2]])) julia> H([1, 2], [1, 1]) 5 julia> t = 1 julia> v = Real[] julia> H(t, [1, 0], [0, 1]) MethodError julia> H([1, 0], [0, 1], v) MethodError julia> H(t, [1, 0], [0, 1], v) 5 julia> H = HamiltonianLift(VectorField((x, v) -> [x[1]^2, 2x[2]+v[3]], variable=true)) julia> H([1, 0], [0, 1], [1, 2, 3]) 3 julia> H(t, [1, 0], [0, 1], [1, 2, 3]) 3 julia> H = HamiltonianLift(VectorField((t, x) -> [t+x[1]^2, 2x[2]], autonomous=false)) julia> H(1, [1, 2], [1, 1]) 6 julia> H(1, [1, 0], [0, 1], v) 6 julia> H = HamiltonianLift(VectorField((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], autonomous=false, variable=true)) julia> H(1, [1, 0], [0, 1], [1, 2, 3]) 3 ``` """ function (H::HamiltonianLift{Autonomous, Fixed})(x::State, p::Costate)::ctNumber return p' * H.X(x) end function (H::HamiltonianLift{Autonomous, Fixed})( t::Time, x::State, p::Costate, v::Variable, )::ctNumber return p' * H.X(x) end function (H::HamiltonianLift{Autonomous, NonFixed})(x::State, p::Costate, v::Variable)::ctNumber return p' * H.X(x, v) end function (H::HamiltonianLift{Autonomous, NonFixed})( t::Time, x::State, p::Costate, v::Variable, )::ctNumber return p' * H.X(x, v) end function (H::HamiltonianLift{NonAutonomous, Fixed})(t::Time, x::State, p::Costate)::ctNumber return p' * H.X(t, x) end function (H::HamiltonianLift{NonAutonomous, Fixed})( t::Time, x::State, p::Costate, v::Variable, )::ctNumber return p' * H.X(t, x) end function (H::HamiltonianLift{NonAutonomous, NonFixed})( t::Time, x::State, p::Costate, v::Variable, )::ctNumber return p' * H.X(t, x, v) end # -------------------------------------------------------------------------------------------------- """ $(TYPEDSIGNATURES) Return an ```HamiltonianVectorField``` of a function. Dependencies are specified with a boolean, variable, false by default, autonomous, true by default. ```@example julia> Hv = HamiltonianVectorField((x, p) -> [x[1]^2+2p[2], x[2]-3p[2]^2]) # autonomous=true, variable=false julia> Hv = HamiltonianVectorField((x, p, v) -> [x[1]^2+2p[2]+v[3], x[2]-3p[2]^2+v[4]], variable=true) julia> Hv = HamiltonianVectorField((t, x, p) -> [t+x[1]^2+2p[2], x[2]-3p[2]^2], autonomous=false) julia> Hv = HamiltonianVectorField((t, x, p, v) -> [t+x[1]^2+2p[2]+v[3], x[2]-3p[2]^2+v[4]], autonomous=false, variable=true) ``` """ function HamiltonianVectorField(f::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return HamiltonianVectorField{time_dependence, variable_dependence}(f) end """ $(TYPEDSIGNATURES) Return an ```HamiltonianVectorField``` of a function. Dependencies are specified with DataType, Autonomous, NonAutonomous and Fixed, NonFixed. ```@example julia> HamiltonianVectorField((x, p) -> [x[1]^2+2p[2], x[2]-3p[2]^2], Int64) IncorrectArgument julia> HamiltonianVectorField((x, p) -> [x[1]^2+2p[2], x[2]-3p[2]^2], Int64) IncorrectArgument julia> Hv = HamiltonianVectorField((x, p) -> [x[1]^2+2p[2], x[2]-3p[2]^2]) # autonomous=true, variable=false julia> Hv = HamiltonianVectorField((x, p, v) -> [x[1]^2+2p[2]+v[3], x[2]-3p[2]^2+v[4]], NonFixed) julia> Hv = HamiltonianVectorField((t, x, p) -> [t+x[1]^2+2p[2], x[2]-3p[2]^2], NonAutonomous) julia> Hv = HamiltonianVectorField((t, x, p, v) -> [t+x[1]^2+2p[2]+v[3], x[2]-3p[2]^2+v[4]], NonAutonomous, NonFixed) ``` """ function HamiltonianVectorField(f::Function, dependencies::DataType...) __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return HamiltonianVectorField{time_dependence, variable_dependence}(f) end """ $(TYPEDSIGNATURES) Return the value of the HamiltonianVectorField. ## Examples ```@example julia> HamiltonianVectorField((x, p) -> [x[1]^2+2p[2], x[2]-3p[2]^2], Int64) IncorrectArgument julia> HamiltonianVectorField((x, p) -> [x[1]^2+2p[2], x[2]-3p[2]^2], Int64) IncorrectArgument julia> Hv = HamiltonianVectorField((x, p) -> [x[1]^2+2p[2], x[2]-3p[2]^2]) # autonomous=true, variable=false julia> Hv([1, 0], [0, 1]) [3, -3] julia> t = 1 julia> v = Real[] julia> Hv(t, [1, 0], [0, 1]) MethodError julia> Hv([1, 0], [0, 1], v) MethodError julia> Hv(t, [1, 0], [0, 1], v) [3, -3] julia> Hv = HamiltonianVectorField((x, p, v) -> [x[1]^2+2p[2]+v[3], x[2]-3p[2]^2+v[4]], variable=true) julia> Hv([1, 0], [0, 1], [1, 2, 3, 4]) [6, -3] julia> Hv(t, [1, 0], [0, 1], [1, 2, 3, 4]) [6, -3] julia> Hv = HamiltonianVectorField((t, x, p) -> [t+x[1]^2+2p[2], x[2]-3p[2]^2], autonomous=false) julia> Hv(1, [1, 0], [0, 1]) [4, -3] julia> Hv(1, [1, 0], [0, 1], v) [4, -3] julia> Hv = HamiltonianVectorField((t, x, p, v) -> [t+x[1]^2+2p[2]+v[3], x[2]-3p[2]^2+v[4]], autonomous=false, variable=true) julia> Hv(1, [1, 0], [0, 1], [1, 2, 3, 4]) [7, -3] ``` """ function (F::HamiltonianVectorField{Autonomous, Fixed})( x::State, p::Costate, )::Tuple{DState, DCostate} return F.f(x, p) end function (F::HamiltonianVectorField{Autonomous, Fixed})( t::Time, x::State, p::Costate, v::Variable, )::Tuple{DState, DCostate} return F.f(x, p) end function (F::HamiltonianVectorField{Autonomous, NonFixed})( x::State, p::Costate, v::Variable, )::Tuple{DState, DCostate} return F.f(x, p, v) end function (F::HamiltonianVectorField{Autonomous, NonFixed})( t::Time, x::State, p::Costate, v::Variable, )::Tuple{DState, DCostate} return F.f(x, p, v) end function (F::HamiltonianVectorField{NonAutonomous, Fixed})( t::Time, x::State, p::Costate, )::Tuple{DState, DCostate} return F.f(t, x, p) end function (F::HamiltonianVectorField{NonAutonomous, Fixed})( t::Time, x::State, p::Costate, v::Variable, )::Tuple{DState, DCostate} return F.f(t, x, p) end function (F::HamiltonianVectorField{NonAutonomous, NonFixed})( t::Time, x::State, p::Costate, v::Variable, )::Tuple{DState, DCostate} return F.f(t, x, p, v) end # -------------------------------------------------------------------------------------------------- """ $(TYPEDSIGNATURES) Return a ```VectorField``` of a function. Dependencies are specified with a boolean, variable, false by default, autonomous, true by default. ```@example julia> V = VectorField(x -> [x[1]^2, 2x[2]]) # autonomous=true, variable=false julia> V = VectorField((x, v) -> [x[1]^2, 2x[2]+v[3]], variable=true) julia> V = VectorField((t, x) -> [t+x[1]^2, 2x[2]], autonomous=false) julia> V = VectorField((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], autonomous=false, variable=true) ``` """ function VectorField(f::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return VectorField{time_dependence, variable_dependence}(f) end """ $(TYPEDSIGNATURES) Return a ```VectorField``` of a function. Dependencies are specified with DataType, Autonomous, NonAutonomous and Fixed, NonFixed. ```@example julia> VectorField(x -> [x[1]^2, 2x[2]], Int64) IncorrectArgument julia> VectorField(x -> [x[1]^2, 2x[2]], Int64) IncorrectArgument julia> V = VectorField(x -> [x[1]^2, 2x[2]]) # autonomous=true, variable=false julia> V = VectorField((x, v) -> [x[1]^2, 2x[2]+v[3]], NonFixed) julia> V = VectorField((t, x) -> [t+x[1]^2, 2x[2]], NonAutonomous) julia> V = VectorField((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], NonAutonomous, NonFixed) ``` """ function VectorField(f::Function, dependencies::DataType...) __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return VectorField{time_dependence, variable_dependence}(f) end """ $(TYPEDSIGNATURES) Return the value of the VectorField. ## Examples ```@example julia> VectorField(x -> [x[1]^2, 2x[2]], Int64) IncorrectArgument julia> VectorField(x -> [x[1]^2, 2x[2]], Int64) IncorrectArgument julia> V = VectorField(x -> [x[1]^2, 2x[2]]) # autonomous=true, variable=false julia> V([1, -1]) [1, -2] julia> t = 1 julia> v = Real[] julia> V(t, [1, -1]) MethodError julia> V([1, -1], v) MethodError julia> V(t, [1, -1], v) [1, -2] julia> V = VectorField((x, v) -> [x[1]^2, 2x[2]+v[3]], variable=true) julia> V([1, -1], [1, 2, 3]) [1, 1] julia> V(t, [1, -1], [1, 2, 3]) [1, 1] julia> V = VectorField((t, x) -> [t+x[1]^2, 2x[2]], autonomous=false) julia> V(1, [1, -1]) [2, -2] julia> V(1, [1, -1], v) [2, -2] julia> V = VectorField((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], autonomous=false, variable=true) julia> V(1, [1, -1], [1, 2, 3]) [2, 1] ``` """ function (F::VectorField{Autonomous, Fixed})(x::State)::ctVector return F.f(x) end function (F::VectorField{Autonomous, Fixed})(t::Time, x::State, v::Variable)::ctVector return F.f(x) end function (F::VectorField{Autonomous, NonFixed})(x::State, v::Variable)::ctVector return F.f(x, v) end function (F::VectorField{Autonomous, NonFixed})(t::Time, x::State, v::Variable)::ctVector return F.f(x, v) end function (F::VectorField{NonAutonomous, Fixed})(t::Time, x::State)::ctVector return F.f(t, x) end function (F::VectorField{NonAutonomous, Fixed})(t::Time, x::State, v::Variable)::ctVector return F.f(t, x) end function (F::VectorField{NonAutonomous, NonFixed})(t::Time, x::State, v::Variable)::ctVector return F.f(t, x, v) end # -------------------------------------------------------------------------------------------------- """ $(TYPEDSIGNATURES) Return a ```Lagrange``` cost of a function. Dependencies are specified with a boolean, variable, false by default, autonomous, true by default. ```@example julia> L = Lagrange((x, u) -> [2x[2]-u[1]^2], autonomous=true, variable=false) julia> L = Lagrange((x, u) -> 2x[2]-u[1]^2, autonomous=true, variable=false) julia> L = Lagrange((x, u, v) -> 2x[2]-u[1]^2+v[3], autonomous=true, variable=true) julia> L = Lagrange((t, x, u) -> t+2x[2]-u[1]^2, autonomous=false, variable=false) julia> L = Lagrange((t, x, u, v) -> t+2x[2]-u[1]^2+v[3], autonomous=false, variable=true) ``` """ function Lagrange(f::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return Lagrange{time_dependence, variable_dependence}(f) end function Lagrange!(f!::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return Lagrange!{time_dependence, variable_dependence}(f!) end """ $(TYPEDSIGNATURES) Return a ```Lagrange``` cost of a function. Dependencies are specified with DataType, Autonomous, NonAutonomous and Fixed, NonFixed. ```@example julia> Lagrange((x, u) -> 2x[2]-u[1]^2, Int64) IncorrectArgument julia> Lagrange((x, u) -> 2x[2]-u[1]^2, Int64) IncorrectArgument julia> L = Lagrange((x, u) -> [2x[2]-u[1]^2], autonomous=true, variable=false) julia> L = Lagrange((x, u) -> 2x[2]-u[1]^2, autonomous=true, variable=false) julia> L = Lagrange((x, u, v) -> 2x[2]-u[1]^2+v[3], autonomous=true, variable=true) julia> L = Lagrange((t, x, u) -> t+2x[2]-u[1]^2, autonomous=false, variable=false) julia> L = Lagrange((t, x, u, v) -> t+2x[2]-u[1]^2+v[3], autonomous=false, variable=true) ``` """ function Lagrange(f::Function, dependencies::DataType...) __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return Lagrange{time_dependence, variable_dependence}(f) end function Lagrange!(f!::Function, dependencies::DataType...) __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return Lagrange!{time_dependence, variable_dependence}(f!) end """ $(TYPEDSIGNATURES) Return the value of the Lagrange function. ## Examples ```@example julia> Lagrange((x, u) -> 2x[2]-u[1]^2, Int64) IncorrectArgument julia> Lagrange((x, u) -> 2x[2]-u[1]^2, Int64) IncorrectArgument julia> L = Lagrange((x, u) -> [2x[2]-u[1]^2], autonomous=true, variable=false) julia> L([1, 0], [1]) MethodError julia> L = Lagrange((x, u) -> 2x[2]-u[1]^2, autonomous=true, variable=false) julia> L([1, 0], [1]) -1 julia> t = 1 julia> v = Real[] julia> L(t, [1, 0], [1]) MethodError julia> L([1, 0], [1], v) MethodError julia> L(t, [1, 0], [1], v) -1 julia> L = Lagrange((x, u, v) -> 2x[2]-u[1]^2+v[3], autonomous=true, variable=true) julia> L([1, 0], [1], [1, 2, 3]) 2 julia> L(t, [1, 0], [1], [1, 2, 3]) 2 julia> L = Lagrange((t, x, u) -> t+2x[2]-u[1]^2, autonomous=false, variable=false) julia> L(1, [1, 0], [1]) 0 julia> L(1, [1, 0], [1], v) 0 julia> L = Lagrange((t, x, u, v) -> t+2x[2]-u[1]^2+v[3], autonomous=false, variable=true) julia> L(1, [1, 0], [1], [1, 2, 3]) 3 ``` """ function (F::Lagrange{Autonomous, Fixed})(x::State, u::Control)::ctNumber return F.f(x, u) end function (F::Lagrange{Autonomous, Fixed})(t::Time, x::State, u::Control, v::Variable)::ctNumber return F.f(x, u) end function (F::Lagrange{Autonomous, NonFixed})(x::State, u::Control, v::Variable)::ctNumber return F.f(x, u, v) end function (F::Lagrange{Autonomous, NonFixed})(t::Time, x::State, u::Control, v::Variable)::ctNumber return F.f(x, u, v) end function (F::Lagrange{NonAutonomous, Fixed})(t::Time, x::State, u::Control)::ctNumber return F.f(t, x, u) end function (F::Lagrange{NonAutonomous, Fixed})(t::Time, x::State, u::Control, v::Variable)::ctNumber return F.f(t, x, u) end function (F::Lagrange{NonAutonomous, NonFixed})( t::Time, x::State, u::Control, v::Variable, )::ctNumber return F.f(t, x, u, v) end function (F::Lagrange!{Autonomous, Fixed})(r::ctVector, x::State, u::Control)::Nothing return F.f!(r, x, u) end function (F::Lagrange!{Autonomous, Fixed})(r::ctVector, t::Time, x::State, u::Control, v::Variable)::Nothing return F.f!(r, x, u) end function (F::Lagrange!{Autonomous, NonFixed})(r::ctVector, x::State, u::Control, v::Variable)::Nothing return F.f!(r, x, u, v) end function (F::Lagrange!{Autonomous, NonFixed})(r::ctVector, t::Time, x::State, u::Control, v::Variable)::Nothing return F.f!(r, x, u, v) end function (F::Lagrange!{NonAutonomous, Fixed})(r::ctVector, t::Time, x::State, u::Control)::Nothing return F.f!(r, t, x, u) end function (F::Lagrange!{NonAutonomous, Fixed})(r::ctVector, t::Time, x::State, u::Control, v::Variable)::Nothing return F.f!(r, t, x, u) end function (F::Lagrange!{NonAutonomous, NonFixed})( r::ctVector, t::Time, x::State, u::Control, v::Variable, )::Nothing return F.f!(r, t, x, u, v) end # -------------------------------------------------------------------------------------------------- """ $(TYPEDSIGNATURES) Return the ```Dynamics``` of a function. Dependencies are specified with a boolean, variable, false by default, autonomous, true by default. ```@example julia> D = Dynamics((x, u) -> [2x[2]-u^2, x[1]], autonomous=true, variable=false) julia> D = Dynamics((x, u, v) -> [2x[2]-u^2+v[3], x[1]], autonomous=true, variable=true) julia> D = Dynamics((t, x, u) -> [t+2x[2]-u^2, x[1]], autonomous=false, variable=false) julia> D = Dynamics((t, x, u, v) -> [t+2x[2]-u^2+v[3], x[1]], autonomous=false, variable=true) ``` """ function Dynamics(f::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return Dynamics{time_dependence, variable_dependence}(f) end function Dynamics!(f!::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return Dynamics!{time_dependence, variable_dependence}(f!) end """ $(TYPEDSIGNATURES) Return the ```Dynamics``` of a function. Dependencies are specified with DataType, Autonomous, NonAutonomous and Fixed, NonFixed. ```@example julia> Dynamics((x, u) -> [2x[2]-u^2, x[1]], Int64) IncorrectArgument julia> Dynamics((x, u) -> [2x[2]-u^2, x[1]], Int64) IncorrectArgument julia> D = Dynamics((x, u) -> [2x[2]-u^2, x[1]], Autonomous, Fixed) julia> D = Dynamics((x, u, v) -> [2x[2]-u^2+v[3], x[1]], Autonomous, NonFixed) julia> D = Dynamics((t, x, u) -> [t+2x[2]-u^2, x[1]], NonAutonomous, Fixed) julia> D = Dynamics((t, x, u, v) -> [t+2x[2]-u^2+v[3], x[1]], NonAutonomous, NonFixed) ``` """ function Dynamics(f::Function, dependencies::DataType...) __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return Dynamics{time_dependence, variable_dependence}(f) end function Dynamics!(f!::Function, dependencies::DataType...) __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return Dynamics!{time_dependence, variable_dependence}(f!) end """ $(TYPEDSIGNATURES) Return the value of the Dynamics function. ```@example julia> D = Dynamics((x, u) -> [2x[2]-u^2, x[1]], autonomous=true, variable=false) julia> D([1, 0], 1) [-1, 1] julia> t = 1 julia> v = Real[] julia> D(t, [1, 0], 1, v) [-1, 1] julia> D = Dynamics((x, u, v) -> [2x[2]-u^2+v[3], x[1]], autonomous=true, variable=true) julia> D([1, 0], 1, [1, 2, 3]) [2, 1] julia> D(t, [1, 0], 1, [1, 2, 3]) [2, 1] julia> D = Dynamics((t, x, u) -> [t+2x[2]-u^2, x[1]], autonomous=false, variable=false) julia> D(1, [1, 0], 1) [0, 1] julia> D(1, [1, 0], 1, v) [0, 1] julia> D = Dynamics((t, x, u, v) -> [t+2x[2]-u^2+v[3], x[1]], autonomous=false, variable=true) julia> D(1, [1, 0], 1, [1, 2, 3]) [3, 1] ``` """ function (F::Dynamics{Autonomous, Fixed})(x::State, u::Control)::ctVector return F.f(x, u) end function (F::Dynamics{Autonomous, Fixed})(t::Time, x::State, u::Control, v::Variable)::ctVector return F.f(x, u) end function (F::Dynamics{Autonomous, NonFixed})(x::State, u::Control, v::Variable)::ctVector return F.f(x, u, v) end function (F::Dynamics{Autonomous, NonFixed})(t::Time, x::State, u::Control, v::Variable)::ctVector return F.f(x, u, v) end function (F::Dynamics{NonAutonomous, Fixed})(t::Time, x::State, u::Control)::ctVector return F.f(t, x, u) end function (F::Dynamics{NonAutonomous, Fixed})(t::Time, x::State, u::Control, v::Variable)::ctVector return F.f(t, x, u) end function (F::Dynamics{NonAutonomous, NonFixed})( t::Time, x::State, u::Control, v::Variable, )::ctVector return F.f(t, x, u, v) end function (F::Dynamics!{Autonomous, Fixed})(r::ctVector, x::State, u::Control)::Nothing return F.f!(r, x, u) end function (F::Dynamics!{Autonomous, Fixed})(r::ctVector, t::Time, x::State, u::Control, v::Variable)::Nothing return F.f!(r, x, u) end function (F::Dynamics!{Autonomous, NonFixed})(r::ctVector, x::State, u::Control, v::Variable)::Nothing return F.f!(r, x, u, v) end function (F::Dynamics!{Autonomous, NonFixed})(r::ctVector, t::Time, x::State, u::Control, v::Variable)::Nothing return F.f!(r, x, u, v) end function (F::Dynamics!{NonAutonomous, Fixed})(r::ctVector, t::Time, x::State, u::Control)::Nothing return F.f!(r, t, x, u) end function (F::Dynamics!{NonAutonomous, Fixed})(r::ctVector, t::Time, x::State, u::Control, v::Variable)::Nothing return F.f!(r, t, x, u) end function (F::Dynamics!{NonAutonomous, NonFixed})( r::ctVector, t::Time, x::State, u::Control, v::Variable, )::Nothing return F.f!(r, t, x, u, v) end # -------------------------------------------------------------------------------------------------- """ $(TYPEDSIGNATURES) Return the ```StateConstraint``` of a function. Dependencies are specified with a boolean, variable, false by default, autonomous, true by default. ```@example julia> S = StateConstraint(x -> [x[1]^2, 2x[2]], autonomous=true, variable=false) julia> S = StateConstraint((x, v) -> [x[1]^2, 2x[2]+v[3]], autonomous=true, variable=true) julia> S = StateConstraint((t, x) -> [t+x[1]^2, 2x[2]], autonomous=false, variable=false) julia> S = StateConstraint((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], autonomous=false, variable=true) ``` """ function StateConstraint(f::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return StateConstraint{time_dependence, variable_dependence}(f) end function StateConstraint!(f!::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return StateConstraint!{time_dependence, variable_dependence}(f!) end """ $(TYPEDSIGNATURES) Return the ```StateConstraint``` of a function. Dependencies are specified with DataType, Autonomous, NonAutonomous and Fixed, NonFixed. ```@example julia> StateConstraint(x -> [x[1]^2, 2x[2]], Int64) IncorrectArgument julia> StateConstraint(x -> [x[1]^2, 2x[2]], Int64) IncorrectArgument julia> S = StateConstraint(x -> [x[1]^2, 2x[2]], Autonomous, Fixed) julia> S = StateConstraint((x, v) -> [x[1]^2, 2x[2]+v[3]], Autonomous, NonFixed) julia> S = StateConstraint((t, x) -> [t+x[1]^2, 2x[2]], NonAutonomous, Fixed) julia> S = StateConstraint((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], NonAutonomous, NonFixed) ``` """ function StateConstraint(f::Function, dependencies::DataType...) __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return StateConstraint{time_dependence, variable_dependence}(f) end function StateConstraint!(f!::Function, dependencies::DataType...) __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return StateConstraint!{time_dependence, variable_dependence}(f!) end """ $(TYPEDSIGNATURES) Return the value of the StateConstraint function. ```@example julia> StateConstraint(x -> [x[1]^2, 2x[2]], Int64) IncorrectArgument julia> StateConstraint(x -> [x[1]^2, 2x[2]], Int64) IncorrectArgument julia> S = StateConstraint(x -> [x[1]^2, 2x[2]], autonomous=true, variable=false) julia> S([1, -1]) [1, -2] julia> t = 1 julia> v = Real[] julia> S(t, [1, -1], v) [1, -2] julia> S = StateConstraint((x, v) -> [x[1]^2, 2x[2]+v[3]], autonomous=true, variable=true) julia> S([1, -1], [1, 2, 3]) [1, 1] julia> S(t, [1, -1], [1, 2, 3]) [1, 1] julia> S = StateConstraint((t, x) -> [t+x[1]^2, 2x[2]], autonomous=false, variable=false) julia> S(1, [1, -1]) [2, -2] julia> S(1, [1, -1], v) [2, -2] julia> S = StateConstraint((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], autonomous=false, variable=true) julia> S(1, [1, -1], [1, 2, 3]) [2, 1] ``` """ function (F::StateConstraint{Autonomous, Fixed})(x::State)::ctVector return F.f(x) end function (F::StateConstraint{Autonomous, Fixed})(t::Time, x::State, v::Variable)::ctVector return F.f(x) end function (F::StateConstraint{Autonomous, NonFixed})(x::State, v::Variable)::ctVector return F.f(x, v) end function (F::StateConstraint{Autonomous, NonFixed})(t::Time, x::State, v::Variable)::ctVector return F.f(x, v) end function (F::StateConstraint{NonAutonomous, Fixed})(t::Time, x::State)::ctVector return F.f(t, x) end function (F::StateConstraint{NonAutonomous, Fixed})(t::Time, x::State, v::Variable)::ctVector return F.f(t, x) end function (F::StateConstraint{NonAutonomous, NonFixed})(t::Time, x::State, v::Variable)::ctVector return F.f(t, x, v) end function (F::StateConstraint!{Autonomous, Fixed})(r::ctVector, x::State)::Nothing return F.f!(r, x) end function (F::StateConstraint!{Autonomous, Fixed})(r::ctVector, t::Time, x::State, v::Variable)::Nothing return F.f!(r, x) end function (F::StateConstraint!{Autonomous, NonFixed})(r::ctVector, x::State, v::Variable)::Nothing return F.f!(r, x, v) end function (F::StateConstraint!{Autonomous, NonFixed})(r::ctVector, t::Time, x::State, v::Variable)::Nothing return F.f!(r, x, v) end function (F::StateConstraint!{NonAutonomous, Fixed})(r::ctVector, t::Time, x::State)::Nothing return F.f!(r, t, x) end function (F::StateConstraint!{NonAutonomous, Fixed})(r::ctVector, t::Time, x::State, v::Variable)::Nothing return F.f!(r, t, x) end function (F::StateConstraint!{NonAutonomous, NonFixed})(r::ctVector, t::Time, x::State, v::Variable)::Nothing return F.f!(r, t, x, v) end # -------------------------------------------------------------------------------------------------- """ $(TYPEDSIGNATURES) Return the ```ControlConstraint``` of a function. Dependencies are specified with a boolean, variable, false by default, autonomous, true by default. ```@example julia> C = ControlConstraint(u -> [u[1]^2, 2u[2]], autonomous=true, variable=false) julia> C = ControlConstraint((u, v) -> [u[1]^2, 2u[2]+v[3]], autonomous=true, variable=true) julia> C = ControlConstraint((t, u) -> [t+u[1]^2, 2u[2]], autonomous=false, variable=false) julia> C = ControlConstraint((t, u, v) -> [t+u[1]^2, 2u[2]+v[3]], autonomous=false, variable=true) ``` """ function ControlConstraint(f::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return ControlConstraint{time_dependence, variable_dependence}(f) end function ControlConstraint!(f!::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return ControlConstraint!{time_dependence, variable_dependence}(f!) end """ $(TYPEDSIGNATURES) Return the ```StateConstraint``` of a function. Dependencies are specified with DataType, Autonomous, NonAutonomous and Fixed, NonFixed. ```@example julia> IncorrectArgument ControlConstraint(u -> [u[1]^2, 2u[2]], Int64) julia> IncorrectArgument ControlConstraint(u -> [u[1]^2, 2u[2]], Int64) julia> C = ControlConstraint(u -> [u[1]^2, 2u[2]], Autonomous, Fixed) julia> C = ControlConstraint((u, v) -> [u[1]^2, 2u[2]+v[3]], Autonomous, NonFixed) julia> C = ControlConstraint((t, u) -> [t+u[1]^2, 2u[2]], NonAutonomous, Fixed) julia> C = ControlConstraint((t, u, v) -> [t+u[1]^2, 2u[2]+v[3]], NonAutonomous, NonFixed) ``` """ function ControlConstraint(f::Function, dependencies::DataType...) __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return ControlConstraint{time_dependence, variable_dependence}(f) end function ControlConstraint!(f!::Function, dependencies::DataType...) # todo: useless? only use version above? __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return ControlConstraint!{time_dependence, variable_dependence}(f!) end """ $(TYPEDSIGNATURES) Return the value of the ControlConstraint function. ```@example julia> IncorrectArgument ControlConstraint(u -> [u[1]^2, 2u[2]], Int64) julia> IncorrectArgument ControlConstraint(u -> [u[1]^2, 2u[2]], Int64) julia> C = ControlConstraint(u -> [u[1]^2, 2u[2]], autonomous=true, variable=false) julia> C([1, -1]) [1, -2] julia> t = 1 julia> v = Real[] julia> C(t, [1, -1], v) [1, -2] julia> C = ControlConstraint((u, v) -> [u[1]^2, 2u[2]+v[3]], autonomous=true, variable=true) julia> C([1, -1], [1, 2, 3]) [1, 1] julia> C(t, [1, -1], [1, 2, 3]) [1, 1] julia> C = ControlConstraint((t, u) -> [t+u[1]^2, 2u[2]], autonomous=false, variable=false) julia> C(1, [1, -1]) [2, -2] julia> C(1, [1, -1], v) [2, -2] julia> C = ControlConstraint((t, u, v) -> [t+u[1]^2, 2u[2]+v[3]], autonomous=false, variable=true) julia> C(1, [1, -1], [1, 2, 3]) [2, 1] ``` """ function (F::ControlConstraint{Autonomous, Fixed})(u::Control)::ctVector return F.f(u) end function (F::ControlConstraint{Autonomous, Fixed})(t::Time, u::Control, v::Variable)::ctVector return F.f(u) end function (F::ControlConstraint{Autonomous, NonFixed})(u::Control, v::Variable)::ctVector return F.f(u, v) end function (F::ControlConstraint{Autonomous, NonFixed})(t::Time, u::Control, v::Variable)::ctVector return F.f(u, v) end function (F::ControlConstraint{NonAutonomous, Fixed})(t::Time, u::Control)::ctVector return F.f(t, u) end function (F::ControlConstraint{NonAutonomous, Fixed})(t::Time, u::Control, v::Variable)::ctVector return F.f(t, u) end function (F::ControlConstraint{NonAutonomous, NonFixed})(t::Time, u::Control, v::Variable)::ctVector return F.f(t, u, v) end function (F::ControlConstraint!{Autonomous, Fixed})(r::ctVector, u::Control)::Nothing return F.f!(r, u) end function (F::ControlConstraint!{Autonomous, Fixed})(r::ctVector, t::Time, u::Control, v::Variable)::Nothing return F.f!(r, u) end function (F::ControlConstraint!{Autonomous, NonFixed})(r::ctVector, u::Control, v::Variable)::Nothing return F.f!(r, u, v) end function (F::ControlConstraint!{Autonomous, NonFixed})(r::ctVector, t::Time, u::Control, v::Variable)::Nothing return F.f!(r, u, v) end function (F::ControlConstraint!{NonAutonomous, Fixed})(r::ctVector, t::Time, u::Control)::Nothing return F.f!(r, t, u) end function (F::ControlConstraint!{NonAutonomous, Fixed})(r::ctVector, t::Time, u::Control, v::Variable)::Nothing return F.f!(r, t, u) end function (F::ControlConstraint!{NonAutonomous, NonFixed})(r::ctVector, t::Time, u::Control, v::Variable)::Nothing return F.f!(r, t, u, v) end # -------------------------------------------------------------------------------------------------- """ $(TYPEDSIGNATURES) Return the ```MixedConstraint``` of a function. Dependencies are specified with a boolean, variable, false by default, autonomous, true by default. ```@example julia> M = MixedConstraint((x, u) -> [2x[2]-u^2, x[1]], autonomous=true, variable=false) julia> M = MixedConstraint((x, u, v) -> [2x[2]-u^2+v[3], x[1]], autonomous=true, variable=true) julia> M = MixedConstraint((t, x, u) -> [t+2x[2]-u^2, x[1]], autonomous=false, variable=false) julia> M = MixedConstraint((t, x, u, v) -> [t+2x[2]-u^2+v[3], x[1]], autonomous=false, variable=true) ``` """ function MixedConstraint(f::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return MixedConstraint{time_dependence, variable_dependence}(f) end function MixedConstraint!(f!::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return MixedConstraint!{time_dependence, variable_dependence}(f!) end """ $(TYPEDSIGNATURES) Return the ```MixedConstraint``` of a function. Dependencies are specified with DataType, Autonomous, NonAutonomous and Fixed, NonFixed. ```@example julia> MixedConstraint((x, u) -> [2x[2]-u^2, x[1]], Int64) IncorrectArgument julia> MixedConstraint((x, u) -> [2x[2]-u^2, x[1]], Int64) IncorrectArgument julia> M = MixedConstraint((x, u) -> [2x[2]-u^2, x[1]], Autonomous, Fixed) julia> M = MixedConstraint((x, u, v) -> [2x[2]-u^2+v[3], x[1]], Autonomous, NonFixed) julia> M = MixedConstraint((t, x, u) -> [t+2x[2]-u^2, x[1]], NonAutonomous, Fixed) julia> M = MixedConstraint((t, x, u, v) -> [t+2x[2]-u^2+v[3], x[1]], NonAutonomous, NonFixed) ``` """ function MixedConstraint(f::Function, dependencies::DataType...) __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return MixedConstraint{time_dependence, variable_dependence}(f) end function MixedConstraint!(f!::Function, dependencies::DataType...) __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return MixedConstraint!{time_dependence, variable_dependence}(f!) end """ $(TYPEDSIGNATURES) Return the value of the MixedConstraint function. ```@example julia> MixedConstraint((x, u) -> [2x[2]-u^2, x[1]], Int64) IncorrectArgument julia> MixedConstraint((x, u) -> [2x[2]-u^2, x[1]], Int64) IncorrectArgument julia> M = MixedConstraint((x, u) -> [2x[2]-u^2, x[1]], autonomous=true, variable=false) julia> M([1, 0], 1) [-1, 1] julia> t = 1 julia> v = Real[] julia> MethodError M(t, [1, 0], 1) julia> MethodError M([1, 0], 1, v) julia> M(t, [1, 0], 1, v) [-1, 1] julia> M = MixedConstraint((x, u, v) -> [2x[2]-u^2+v[3], x[1]], autonomous=true, variable=true) julia> M([1, 0], 1, [1, 2, 3]) [2, 1] julia> M(t, [1, 0], 1, [1, 2, 3]) [2, 1] julia> M = MixedConstraint((t, x, u) -> [t+2x[2]-u^2, x[1]], autonomous=false, variable=false) julia> M(1, [1, 0], 1) [0, 1] julia> M(1, [1, 0], 1, v) [0, 1] julia> M = MixedConstraint((t, x, u, v) -> [t+2x[2]-u^2+v[3], x[1]], autonomous=false, variable=true) julia> M(1, [1, 0], 1, [1, 2, 3]) [3, 1] ``` """ function (F::MixedConstraint{Autonomous, Fixed})(x::State, u::Control)::ctVector return F.f(x, u) end function (F::MixedConstraint{Autonomous, Fixed})( t::Time, x::State, u::Control, v::Variable, )::ctVector return F.f(x, u) end function (F::MixedConstraint{Autonomous, NonFixed})(x::State, u::Control, v::Variable)::ctVector return F.f(x, u, v) end function (F::MixedConstraint{Autonomous, NonFixed})( t::Time, x::State, u::Control, v::Variable, )::ctVector return F.f(x, u, v) end function (F::MixedConstraint{NonAutonomous, Fixed})(t::Time, x::State, u::Control)::ctVector return F.f(t, x, u) end function (F::MixedConstraint{NonAutonomous, Fixed})( t::Time, x::State, u::Control, v::Variable, )::ctVector return F.f(t, x, u) end function (F::MixedConstraint{NonAutonomous, NonFixed})( t::Time, x::State, u::Control, v::Variable, )::ctVector return F.f(t, x, u, v) end function (F::MixedConstraint!{Autonomous, Fixed})(r::ctVector, x::State, u::Control)::Nothing return F.f!(r, x, u) end function (F::MixedConstraint!{Autonomous, Fixed})( r::ctVector, t::Time, x::State, u::Control, v::Variable, )::Nothing return F.f!(r, x, u) end function (F::MixedConstraint!{Autonomous, NonFixed})(r::ctVector, x::State, u::Control, v::Variable)::Nothing return F.f!(r, x, u, v) end function (F::MixedConstraint!{Autonomous, NonFixed})( r::ctVector, t::Time, x::State, u::Control, v::Variable, )::Nothing return F.f!(r, x, u, v) end function (F::MixedConstraint!{NonAutonomous, Fixed})(r::ctVector, t::Time, x::State, u::Control)::Nothing return F.f!(r, t, x, u) end function (F::MixedConstraint!{NonAutonomous, Fixed})( r::ctVector, t::Time, x::State, u::Control, v::Variable, )::Nothing return F.f!(r, t, x, u) end function (F::MixedConstraint!{NonAutonomous, NonFixed})( r::ctVector, t::Time, x::State, u::Control, v::Variable, )::Nothing return F.f!(r, t, x, u, v) end # -------------------------------------------------------------------------------------------------- """ $(TYPEDSIGNATURES) Return the value of the VariableConstraint function. ```@example julia> V = VariableConstraint(v -> [v[1]^2, 2v[2]]) julia> V([1, -1]) [1, -2] ``` """ function (F::VariableConstraint)(v::Variable)::ctVector return F.f(v) end function (F::VariableConstraint!)(r::ctVector, v::Variable)::Nothing return F.f!(r, v) end # -------------------------------------------------------------------------------------------------- """ $(TYPEDSIGNATURES) Return the ```FeedbackControl``` of a function. Dependencies are specified with a boolean, variable, false by default, autonomous, true by default. ```@example julia> u = FeedbackControl(x -> x[1]^2+2x[2], autonomous=true, variable=false) julia> u = FeedbackControl((x, v) -> x[1]^2+2x[2]+v[3], autonomous=true, variable=true) julia> u = FeedbackControl((t, x) -> t+x[1]^2+2x[2], autonomous=false, variable=false) julia> u = FeedbackControl((t, x, v) -> t+x[1]^2+2x[2]+v[3], autonomous=false, variable=true) ``` """ function FeedbackControl(f::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return FeedbackControl{time_dependence, variable_dependence}(f) end """ $(TYPEDSIGNATURES) Return the ```FeedbackControl``` of a function. Dependencies are specified with DataType, Autonomous, NonAutonomous and Fixed, NonFixed. ```@example julia> FeedbackControl(x -> x[1]^2+2x[2], Int64) IncorrectArgument julia> FeedbackControl(x -> x[1]^2+2x[2], Int64) IncorrectArgument julia> u = FeedbackControl(x -> x[1]^2+2x[2], Autonomous, Fixed) julia> u = FeedbackControl((x, v) -> x[1]^2+2x[2]+v[3], Autonomous, NonFixed) julia> u = FeedbackControl((t, x) -> t+x[1]^2+2x[2], NonAutonomous, Fixed) julia> u = FeedbackControl((t, x, v) -> t+x[1]^2+2x[2]+v[3], NonAutonomous, NonFixed) ``` """ function FeedbackControl(f::Function, dependencies::DataType...) __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return FeedbackControl{time_dependence, variable_dependence}(f) end """ $(TYPEDSIGNATURES) Return the value of the FeedbackControl function. ```@example julia> FeedbackControl(x -> x[1]^2+2x[2], Int64) IncorrectArgument julia> FeedbackControl(x -> x[1]^2+2x[2], Int64) IncorrectArgument julia> u = FeedbackControl(x -> x[1]^2+2x[2], autonomous=true, variable=false) julia> u([1, 0]) 1 julia> t = 1 julia> v = Real[] julia> u(t, [1, 0]) MethodError julia> u([1, 0], v) MethodError julia> u(t, [1, 0], v) 1 julia> u = FeedbackControl((x, v) -> x[1]^2+2x[2]+v[3], autonomous=true, variable=true) julia> u([1, 0], [1, 2, 3]) 4 julia> u(t, [1, 0], [1, 2, 3]) 4 julia> u = FeedbackControl((t, x) -> t+x[1]^2+2x[2], autonomous=false, variable=false) julia> u(1, [1, 0]) 2 julia> u(1, [1, 0], v) 2 julia> u = FeedbackControl((t, x, v) -> t+x[1]^2+2x[2]+v[3], autonomous=false, variable=true) julia> u(1, [1, 0], [1, 2, 3]) 5 ``` """ function (F::FeedbackControl{Autonomous, Fixed})(x::State)::ctVector return F.f(x) end function (F::FeedbackControl{Autonomous, Fixed})(t::Time, x::State, v::Variable)::ctVector return F.f(x) end function (F::FeedbackControl{Autonomous, NonFixed})(x::State, v::Variable)::ctVector return F.f(x, v) end function (F::FeedbackControl{Autonomous, NonFixed})(t::Time, x::State, v::Variable)::ctVector return F.f(x, v) end function (F::FeedbackControl{NonAutonomous, Fixed})(t::Time, x::State)::ctVector return F.f(t, x) end function (F::FeedbackControl{NonAutonomous, Fixed})(t::Time, x::State, v::Variable)::ctVector return F.f(t, x) end function (F::FeedbackControl{NonAutonomous, NonFixed})(t::Time, x::State, v::Variable)::ctVector return F.f(t, x, v) end # -------------------------------------------------------------------------------------------------- """ $(TYPEDSIGNATURES) Return the ```ControlLaw``` of a function. Dependencies are specified with a boolean, variable, false by default, autonomous, true by default. ```@example julia> u = ControlLaw((x, p) -> x[1]^2+2p[2], autonomous=true, variable=false) julia> u = ControlLaw((x, p, v) -> x[1]^2+2p[2]+v[3], autonomous=true, variable=true) julia> u = ControlLaw((t, x, p) -> t+x[1]^2+2p[2], autonomous=false, variable=false) julia> u = ControlLaw((t, x, p, v) -> t+x[1]^2+2p[2]+v[3], autonomous=false, variable=true) ``` """ function ControlLaw(f::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return ControlLaw{time_dependence, variable_dependence}(f) end """ $(TYPEDSIGNATURES) Return the ```ControlLaw``` of a function. Dependencies are specified with DataType, Autonomous, NonAutonomous and Fixed, NonFixed. ```@example julia> ControlLaw((x, p) -> x[1]^2+2p[2], Int64) IncorrectArgument julia> ControlLaw((x, p) -> x[1]^2+2p[2], Int64) IncorrectArgument julia> u = ControlLaw((x, p) -> x[1]^2+2p[2], Autonomous, Fixed) julia> u = ControlLaw((x, p, v) -> x[1]^2+2p[2]+v[3], Autonomous, NonFixed) julia> u = ControlLaw((t, x, p) -> t+x[1]^2+2p[2], NonAutonomous, Fixed) julia> u = ControlLaw((t, x, p, v) -> t+x[1]^2+2p[2]+v[3], NonAutonomous, NonFixed) ``` """ function ControlLaw(f::Function, dependencies::DataType...) __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return ControlLaw{time_dependence, variable_dependence}(f) end """ $(TYPEDSIGNATURES) Return the value of the ControlLaw function. ```@example julia> ControlLaw((x, p) -> x[1]^2+2p[2], Int64) IncorrectArgument julia> ControlLaw((x, p) -> x[1]^2+2p[2], Int64) IncorrectArgument julia> u = ControlLaw((x, p) -> x[1]^2+2p[2], autonomous=true, variable=false) julia> u([1, 0], [0, 1]) 3 julia> t = 1 julia> v = Real[] julia> u(t, [1, 0], [0, 1]) MethodError julia> u([1, 0], [0, 1], v) MethodError julia> u(t, [1, 0], [0, 1], v) 3 julia> u = ControlLaw((x, p, v) -> x[1]^2+2p[2]+v[3], autonomous=true, variable=true) julia> u([1, 0], [0, 1], [1, 2, 3]) 6 julia> u(t, [1, 0], [0, 1], [1, 2, 3]) 6 julia> u = ControlLaw((t, x, p) -> t+x[1]^2+2p[2], autonomous=false, variable=false) julia> u(1, [1, 0], [0, 1]) 4 julia> u(1, [1, 0], [0, 1], v) 4 julia> u = ControlLaw((t, x, p, v) -> t+x[1]^2+2p[2]+v[3], autonomous=false, variable=true) julia> u(1, [1, 0], [0, 1], [1, 2, 3]) 7 ``` """ function (F::ControlLaw{Autonomous, Fixed})(x::State, p::Costate)::ctVector return F.f(x, p) end function (F::ControlLaw{Autonomous, Fixed})(t::Time, x::State, p::Costate, v::Variable)::ctVector return F.f(x, p) end function (F::ControlLaw{Autonomous, NonFixed})(x::State, p::Costate, v::Variable)::ctVector return F.f(x, p, v) end function (F::ControlLaw{Autonomous, NonFixed})(t::Time, x::State, p::Costate, v::Variable)::ctVector return F.f(x, p, v) end function (F::ControlLaw{NonAutonomous, Fixed})(t::Time, x::State, p::Costate)::ctVector return F.f(t, x, p) end function (F::ControlLaw{NonAutonomous, Fixed})(t::Time, x::State, p::Costate, v::Variable)::ctVector return F.f(t, x, p) end function (F::ControlLaw{NonAutonomous, NonFixed})( t::Time, x::State, p::Costate, v::Variable, )::ctVector return F.f(t, x, p, v) end # -------------------------------------------------------------------------------------------------- """ $(TYPEDSIGNATURES) Return the ```Multiplier``` of a function. Dependencies are specified with a boolean, variable, false by default, autonomous, true by default. ```@example julia> μ = Multiplier((x, p) -> x[1]^2+2p[2], autonomous=true, variable=false) julia> μ = Multiplier((x, p, v) -> x[1]^2+2p[2]+v[3], autonomous=true, variable=true) julia> μ = Multiplier((t, x, p) -> t+x[1]^2+2p[2], autonomous=false, variable=false) julia> μ = Multiplier((t, x, p, v) -> t+x[1]^2+2p[2]+v[3], autonomous=false, variable=true) ``` """ function Multiplier(f::Function; autonomous::Bool = true, variable::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed return Multiplier{time_dependence, variable_dependence}(f) end """ $(TYPEDSIGNATURES) Return the ```Multiplier``` of a function. Dependencies are specified with DataType, Autonomous, NonAutonomous and Fixed, NonFixed. ```@example julia> Multiplier((x, p) -> x[1]^2+2p[2], Int64) IncorrectArgument julia> Multiplier((x, p) -> x[1]^2+2p[2], Int64) IncorrectArgument julia> μ = Multiplier((x, p) -> x[1]^2+2p[2], Autonomous, Fixed) julia> μ = Multiplier((x, p, v) -> x[1]^2+2p[2]+v[3], Autonomous, NonFixed) julia> μ = Multiplier((t, x, p) -> t+x[1]^2+2p[2], NonAutonomous, Fixed) julia> μ = Multiplier((t, x, p, v) -> t+x[1]^2+2p[2]+v[3], NonAutonomous, NonFixed) ``` """ function Multiplier(f::Function, dependencies::DataType...) __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return Multiplier{time_dependence, variable_dependence}(f) end """ $(TYPEDSIGNATURES) Return the value of the Multiplier function. ```@example julia> Multiplier((x, p) -> x[1]^2+2p[2], Int64) IncorrectArgument julia> Multiplier((x, p) -> x[1]^2+2p[2], Int64) IncorrectArgument julia> μ = Multiplier((x, p) -> x[1]^2+2p[2], autonomous=true, variable=false) julia> μ([1, 0], [0, 1]) 3 julia> t = 1 julia> v = Real[] julia> μ(t, [1, 0], [0, 1]) MethodError julia> μ([1, 0], [0, 1], v) MethodError julia> μ(t, [1, 0], [0, 1], v) 3 julia> μ = Multiplier((x, p, v) -> x[1]^2+2p[2]+v[3], autonomous=true, variable=true) julia> μ([1, 0], [0, 1], [1, 2, 3]) 6 julia> μ(t, [1, 0], [0, 1], [1, 2, 3]) 6 julia> μ = Multiplier((t, x, p) -> t+x[1]^2+2p[2], autonomous=false, variable=false) julia> μ(1, [1, 0], [0, 1]) 4 julia> μ(1, [1, 0], [0, 1], v) 4 julia> μ = Multiplier((t, x, p, v) -> t+x[1]^2+2p[2]+v[3], autonomous=false, variable=true) julia> μ(1, [1, 0], [0, 1], [1, 2, 3]) 7 ``` """ function (F::Multiplier{Autonomous, Fixed})(x::State, p::Costate)::ctVector return F.f(x, p) end function (F::Multiplier{Autonomous, Fixed})(t::Time, x::State, p::Costate, v::Variable)::ctVector return F.f(x, p) end function (F::Multiplier{Autonomous, NonFixed})(x::State, p::Costate, v::Variable)::ctVector return F.f(x, p, v) end function (F::Multiplier{Autonomous, NonFixed})(t::Time, x::State, p::Costate, v::Variable)::ctVector return F.f(x, p, v) end function (F::Multiplier{NonAutonomous, Fixed})(t::Time, x::State, p::Costate)::ctVector return F.f(t, x, p) end function (F::Multiplier{NonAutonomous, Fixed})(t::Time, x::State, p::Costate, v::Variable)::ctVector return F.f(t, x, p) end function (F::Multiplier{NonAutonomous, NonFixed})( t::Time, x::State, p::Costate, v::Variable, )::ctVector return F.f(t, x, p, v) end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
6460
""" $(TYPEDSIGNATURES) Check if actual dimension is equal to target dimension, error otherwise """ function checkDim(actual_dim, target_dim) if !isnothing(target_dim) && actual_dim != target_dim error("Init dimension mismatch: got ", actual_dim, " instead of ", target_dim) end end """ $(TYPEDSIGNATURES) Return true if argument is a vector of vectors """ function isaVectVect(data) return (data isa Vector) && (data[1] isa ctVector) end """ $(TYPEDSIGNATURES) Convert matrix to vector of vectors (could be expanded) """ function formatData(data) if data isa Matrix return matrix2vec(data, 1) else return data end end """ $(TYPEDSIGNATURES) Convert matrix time-grid to vector """ function formatTimeGrid(time) if isnothing(time) return nothing elseif time isa ctVector return time else return vec(time) end end """ $(TYPEDSIGNATURES) Build functional initialization: default case """ function buildFunctionalInit(data::Nothing, time, dim) # fallback to method-dependent default initialization return t -> nothing end """ $(TYPEDSIGNATURES) Build functional initialization: function case """ function buildFunctionalInit(data::Function, time, dim) # functional initialization checkDim(length(data(0)), dim) return t -> data(t) end """ $(TYPEDSIGNATURES) Build functional initialization: constant / 1D interpolation """ function buildFunctionalInit(data::ctVector, time, dim) if !isnothing(time) && (length(data) == length(time)) # interpolation vs time, dim 1 case itp = ctinterpolate(time, data) return t -> itp(t) else # constant initialization checkDim(length(data), dim) return t -> data end end """ $(TYPEDSIGNATURES) Build functional initialization: general interpolation case """ function buildFunctionalInit(data, time, dim) if isaVectVect(data) # interpolation vs time, general case itp = ctinterpolate(time, data) checkDim(length(itp(0)), dim) return t -> itp(t) else error("Unrecognized initialization argument: ", typeof(data)) end end """ $(TYPEDSIGNATURES) Build vector initialization: default / vector case """ function buildVectorInit(data, dim) if isnothing(data) return data else checkDim(length(data), dim) return data end end """ $(TYPEDSIGNATURES) Initial guess for OCP, contains - functions of time for the state and control variables - vector for optimization variables Initialization data for each field can be left to default or: - vector for optimization variables - constant / vector / function for state and control - existing solution ('warm start') for all fields # Constructors: - `OptimalControlInit()`: default initialization - `OptimalControlInit(state, control, variable, time)`: constant vector, function handles and / or matrices / vectors interpolated along given time grid - `OptimalControlInit(sol)`: from existing solution # Examples ```julia-repl julia> init = OptimalControlInit() julia> init = OptimalControlInit(state=[0.1, 0.2], control=0.3) julia> init = OptimalControlInit(state=[0.1, 0.2], control=0.3, variable=0.5) julia> init = OptimalControlInit(state=[0.1, 0.2], controlt=t->sin(t), variable=0.5) julia> init = OptimalControlInit(state=[[0, 0], [1, 2], [5, -1]], time=[0, .3, 1.], controlt=t->sin(t)) julia> init = OptimalControlInit(sol) ``` """ mutable struct OptimalControlInit state_init::Function control_init::Function variable_init::Union{Nothing, ctVector} #costate_init::Function #multipliers_init::Union{Nothing, ctVector} """ $(TYPEDSIGNATURES) OptimalControlInit base constructor with separate explicit arguments """ function OptimalControlInit(; state = nothing, control = nothing, variable = nothing, time = nothing, state_dim = nothing, control_dim = nothing, variable_dim = nothing, ) init = new() # some matrix / vector conversions time = formatTimeGrid(time) state = formatData(state) control = formatData(control) # set initialization for x, u, v init.state_init = buildFunctionalInit(state, time, state_dim) init.control_init = buildFunctionalInit(control, time, control_dim) init.variable_init = buildVectorInit(variable, variable_dim) return init end """ $(TYPEDSIGNATURES) OptimalControlInit constructor with arguments grouped as named tuple or dict """ function OptimalControlInit( init_data; state_dim = nothing, control_dim = nothing, variable_dim = nothing, ) # trivial case: default init x_init = nothing u_init = nothing v_init = nothing t_init = nothing # parse arguments if !isnothing(init_data) for key in keys(init_data) if key == :state x_init = init_data[:state] elseif key == :control u_init = init_data[:control] elseif key == :variable v_init = init_data[:variable] elseif key == :time t_init = init_data[:time] else error( "Unknown key in initialization data (allowed: state, control, variable, time, state_dim, control_dim, variable_dim): ", key, ) end end end # call base constructor return OptimalControlInit( state = x_init, control = u_init, variable = v_init, time = t_init, state_dim = state_dim, control_dim = control_dim, variable_dim = variable_dim, ) end """ $(TYPEDSIGNATURES) OptimalControlInit constructor with solution as argument (warm start) """ function OptimalControlInit(sol::OptimalControlSolution; unused_kwargs...) return OptimalControlInit( state = state(sol), control = control(sol), variable = variable(sol), state_dim = state_dimension(sol), control_dim = control_dimension(sol), variable_dim = variable_dimension(sol), ) end end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
24331
# onepass # todo: # - cannot call solve if problem not fully defined (dynamics not defined...) # - doc: explain projections wrt to t0, tf, t; (...x1...x2...)(t) -> ...gensym1...gensym2... (most internal first) # - test non autonomous cases # - robustify repl # - additional checks: when generating functions (constraints, dynamics, costs), there should not be any x or u left # (but the user might indeed do so); meaning that has(ee, x/u/t) must be false (postcondition) # - tests exceptions (parsing and semantics/runtime) # - add assert for pre/post conditions and invariants # - add tests on ParsingError + run time errors (wrapped in try ... catch's - use string to be precise) # - currently "t ∈ [ 0+0, 1 ], time" is allowed, and compels to declare "x(0+0) == ..." """ $(TYPEDEF) **Fields** """ @with_kw mutable struct ParsingInfo v::Union{Symbol, Nothing} = nothing t::Union{Symbol, Nothing} = nothing t0::Union{Real, Symbol, Expr, Nothing} = nothing tf::Union{Real, Symbol, Expr, Nothing} = nothing x::Union{Symbol, Nothing} = nothing u::Union{Symbol, Nothing} = nothing aliases::OrderedDict{Symbol, Union{Real, Symbol, Expr}} = __init_aliases() lnum::Integer = 0 line::String = "" t_dep::Bool = false end __init_aliases(; max_dim = 20) = begin al = OrderedDict{Symbol, Union{Real, Symbol, Expr}}() for i ∈ 1:max_dim al[Symbol(:R, ctupperscripts(i))] = :(R^$i) end al[:<=] = :≀ al[:>=] = :β‰₯ al[:derivative] = :βˆ‚ al[:integral] = :∫ al[:(=>)] = :β†’ al[:in] = :∈ al end __throw(ex, n, line) = quote local info info = string("\nLine ", $n, ": ", $line) throw(ParsingError(info * "\n" * $ex)) end __wrap(e, n, line) = quote local ex try $e catch ex println("Line ", $n, ": ", $line) throw(ex) end end __t_dep(p) = p.t_dep __v_dep(p) = !isnothing(p.v) """ $(TYPEDSIGNATURES) Parse the expression `e` and update the `ParsingInfo` structure `p`. # Example ```@example parse!(p, :ocp, :(v ∈ R, variable)) ``` """ parse!(p, ocp, e; log = false) = begin # p.lnum = p.lnum + 1 p.line = string(e) for a ∈ keys(p.aliases) e = subs(e, a, p.aliases[a]) end # @match e begin # aliases :($a = $e1) => @match e1 begin :(($names) ∈ R^$q, variable) => p_variable!(p, ocp, a, q; components_names = names, log) :([$names] ∈ R^$q, variable) => p_variable!(p, ocp, a, q; components_names = names, log) :(($names) ∈ R^$n, state) => p_state!(p, ocp, a, n; components_names = names, log) :([$names] ∈ R^$n, state) => p_state!(p, ocp, a, n; components_names = names, log) :(($names) ∈ R^$m, control) => p_control!(p, ocp, a, m; components_names = names, log) :([$names] ∈ R^$m, control) => p_control!(p, ocp, a, m; components_names = names, log) _ => p_alias!(p, ocp, a, e1; log) # alias end # variable :($v ∈ R^$q, variable) => p_variable!(p, ocp, v, q; log) :($v ∈ R, variable) => p_variable!(p, ocp, v, 1; log) # time :($t ∈ [$t0, $tf], time) => p_time!(p, ocp, t, t0, tf; log) # state :($x ∈ R^$n, state) => p_state!(p, ocp, x, n; log) :($x ∈ R, state) => p_state!(p, ocp, x, 1; log) # control :($u ∈ R^$m, control) => p_control!(p, ocp, u, m; log) :($u ∈ R, control) => p_control!(p, ocp, u, 1; log) # dynamics :(βˆ‚($x)($t) == $e1) => p_dynamics!(p, ocp, x, t, e1; log) :(βˆ‚($x)($t) == $e1, $label) => p_dynamics!(p, ocp, x, t, e1, label; log) # constraints :($e1 == $e2) => p_constraint!(p, ocp, e2, e1, e2; log) :($e1 == $e2, $label) => p_constraint!(p, ocp, e2, e1, e2, label; log) :($e1 ≀ $e2 ≀ $e3) => p_constraint!(p, ocp, e1, e2, e3; log) :($e1 ≀ $e2 ≀ $e3, $label) => p_constraint!(p, ocp, e1, e2, e3, label; log) :($e2 ≀ $e3) => p_constraint!(p, ocp, nothing, e2, e3; log) :($e2 ≀ $e3, $label) => p_constraint!(p, ocp, nothing, e2, e3, label; log) :($e3 β‰₯ $e2 β‰₯ $e1) => p_constraint!(p, ocp, e1, e2, e3; log) :($e3 β‰₯ $e2 β‰₯ $e1, $label) => p_constraint!(p, ocp, e1, e2, e3, label; log) :($e2 β‰₯ $e1) => p_constraint!(p, ocp, e1, e2, nothing; log) :($e2 β‰₯ $e1, $label) => p_constraint!(p, ocp, e1, e2, nothing, label; log) # lagrange cost :(∫($e1) β†’ min) => p_lagrange!(p, ocp, e1, :min; log) :(-∫($e1) β†’ min) => p_lagrange!(p, ocp, :(-$e1), :min; log) :($e1 * ∫($e2) β†’ min) => has(e1, p.t) ? (return __throw("time $(p.t) must not appear in $e1", p.lnum, p.line)) : p_lagrange!(p, ocp, :($e1 * $e2), :min; log) :(∫($e1) β†’ max) => p_lagrange!(p, ocp, e1, :max; log) :(-∫($e1) β†’ max) => p_lagrange!(p, ocp, :(-$e1), :max; log) :($e1 * ∫($e2) β†’ max) => has(e1, p.t) ? (return __throw("time $(p.t) must not appear in $e1", p.lnum, p.line)) : p_lagrange!(p, ocp, :($e1 * $e2), :max; log) # bolza cost :($e1 + ∫($e2) β†’ min) => p_bolza!(p, ocp, e1, e2, :min; log) :($e1 + $e2 * ∫($e3) β†’ min) => has(e2, p.t) ? (return __throw("time $(p.t) must not appear in $e2", p.lnum, p.line)) : p_bolza!(p, ocp, e1, :($e2 * $e3), :min; log) :($e1 - ∫($e2) β†’ min) => p_bolza!(p, ocp, e1, :(-$e2), :min; log) :($e1 - $e2 * ∫($e3) β†’ min) => has(e2, p.t) ? (return __throw("time $(p.t) must not appear in $e2", p.lnum, p.line)) : p_bolza!(p, ocp, e1, :(-$e2 * $e3), :min; log) :($e1 + ∫($e2) β†’ max) => p_bolza!(p, ocp, e1, e2, :max; log) :($e1 + $e2 * ∫($e3) β†’ max) => has(e2, p.t) ? (return __throw("time $(p.t) must not appear in $e2", p.lnum, p.line)) : p_bolza!(p, ocp, e1, :($e2 * $e3), :max; log) :($e1 - ∫($e2) β†’ max) => p_bolza!(p, ocp, e1, :(-$e2), :max; log) :($e1 - $e2 * ∫($e3) β†’ max) => has(e2, p.t) ? (return __throw("time $(p.t) must not appear in $e2", p.lnum, p.line)) : p_bolza!(p, ocp, e1, :(-$e2 * $e3), :max; log) :(∫($e2) + $e1 β†’ min) => p_bolza!(p, ocp, e1, e2, :min; log) :($e2 * ∫($e3) + $e1 β†’ min) => has(e2, p.t) ? (return __throw("time $(p.t) must not appear in $e2", p.lnum, p.line)) : p_bolza!(p, ocp, e1, :($e2 * $e3), :min; log) :(∫($e2) - $e1 β†’ min) => p_bolza!(p, ocp, :(-$e1), e2, :min; log) :($e2 * ∫($e3) - $e1 β†’ min) => has(e2, p.t) ? (return __throw("time $(p.t) must not appear in $e2", p.lnum, p.line)) : p_bolza!(p, ocp, :(-$e1), :($e2 * $e3), :min; log) :(∫($e2) + $e1 β†’ max) => p_bolza!(p, ocp, e1, e2, :max; log) :($e2 * ∫($e3) + $e1 β†’ max) => has(e2, p.t) ? (return __throw("time $(p.t) must not appear in $e2", p.lnum, p.line)) : p_bolza!(p, ocp, e1, :($e2 * $e3), :max; log) :(∫($e2) - $e1 β†’ max) => p_bolza!(p, ocp, :(-$e1), e2, :max; log) :($e2 * ∫($e3) - $e1 β†’ max) => has(e2, p.t) ? (return __throw("time $(p.t) must not appear in $e2", p.lnum, p.line)) : p_bolza!(p, ocp, :(-$e1), :($e2 * $e3), :max; log) # mayer cost :($e1 β†’ min) => p_mayer!(p, ocp, e1, :min; log) :($e1 β†’ max) => p_mayer!(p, ocp, e1, :max; log) # _ => begin if e isa LineNumberNode p.lnum = p.lnum - 1 e elseif e isa Expr && e.head == :block p.lnum = p.lnum - 1 Expr(:block, map(e -> parse!(p, ocp, e; log), e.args)...) # !!! assumes that map is done sequentially for side effects on p else return __throw("unknown syntax", p.lnum, p.line) end end end end p_variable!(p, ocp, v, q; components_names = nothing, log = false) = begin log && println("variable: $v, dim: $q") v isa Symbol || return __throw("forbidden variable name: $v", p.lnum, p.line) p.v = v vv = QuoteNode(v) qq = q isa Integer ? q : 9 for i ∈ 1:qq p.aliases[Symbol(v, ctindices(i))] = :($v[$i]) end # make: v₁, vβ‚‚... if the variable is named v for i ∈ 1:qq p.aliases[Symbol(v, i)] = :($v[$i]) end # make: v1, v2... if the variable is named v for i ∈ 1:9 p.aliases[Symbol(v, ctupperscripts(i))] = :($v^$i) end # make: vΒΉ, vΒ²... if the variable is named v if (isnothing(components_names)) code = :( variable!($ocp, $q, $vv) ) else qq == length(components_names.args) || return __throw("the number of variable components must be $qq", p.lnum, p.line) for i ∈ 1:qq p.aliases[components_names.args[i]] = :($v[$i]) end # aliases from names given by the user ss = QuoteNode(string.(components_names.args)) code = :( variable!($ocp, $q, $vv, $ss) ) end return __wrap(code, p.lnum, p.line) end p_alias!(p, ocp, a, e; log = false) = begin log && println("alias: $a = $e") a isa Symbol || return __throw("forbidden alias name: $a", p.lnum, p.line) aa = QuoteNode(a) ee = QuoteNode(e) for i ∈ 1:9 p.aliases[Symbol(a, ctupperscripts(i))] = :($a^$i) end p.aliases[a] = e code = :( LineNumberNode(0, "alias: " * string($aa) * " = " * string($ee)) ) return __wrap(code, p.lnum, p.line) end p_time!(p, ocp, t, t0, tf; log = false) = begin log && println("time: $t, initial time: $t0, final time: $tf") t isa Symbol || return __throw("forbidden time name: $t", p.lnum, p.line) p.t = t p.t0 = t0 p.tf = tf tt = QuoteNode(t) code = @match (has(t0, p.v), has(tf, p.v)) begin (false, false) => :(time!($ocp; t0 = $t0, tf = $tf, name = $tt)) (true, false) => @match t0 begin :($v1[$i]) && if (v1 == p.v) end => :(time!($ocp; ind0 = $i, tf = $tf, name = $tt)) :($v1) && if (v1 == p.v) end => quote ($ocp.variable_dimension β‰  1) && throw( IncorrectArgument("variable must be of dimension one for a time"), ) time!($ocp; ind0 = 1, tf = $tf, name = $tt) end _ => return __throw("bad time declaration", p.lnum, p.line) end (false, true) => @match tf begin :($v1[$i]) && if (v1 == p.v) end => :(time!($ocp; t0 = $t0, indf = $i, name = $tt)) :($v1) && if (v1 == p.v) end => quote ($ocp.variable_dimension β‰  1) && throw( IncorrectArgument("variable must be of dimension one for a time"), ) time!($ocp; t0 = $t0, indf = 1, name = $tt) end _ => return __throw("bad time declaration", p.lnum, p.line) end _ => @match (t0, tf) begin (:($v1[$i]), :($v2[$j])) && if (v1 == v2 == p.v) end => :(time!($ocp; ind0 = $i, indf = $j, name = $tt)) _ => return __throw("bad time declaration", p.lnum, p.line) end end return __wrap(code, p.lnum, p.line) end p_state!(p, ocp, x, n; components_names = nothing, log = false) = begin log && println("state: $x, dim: $n") x isa Symbol || return __throw("forbidden state name: $x", p.lnum, p.line) p.x = x xx = QuoteNode(x) nn = n isa Integer ? n : 9 for i ∈ 1:nn p.aliases[Symbol(x, ctindices(i))] = :($x[$i]) end # Make x₁, xβ‚‚... if the state is named x for i ∈ 1:nn p.aliases[Symbol(x, i)] = :($x[$i]) end # Make x1, x2... if the state is named x for i ∈ 1:9 p.aliases[Symbol(x, ctupperscripts(i))] = :($x^$i) end # Make xΒΉ, xΒ²... if the state is named x p.aliases[Symbol(Unicode.normalize(string(x, "Μ‡")))] = :(βˆ‚($x)) if (isnothing(components_names)) code = :( state!($ocp, $n, $xx) ) else nn == length(components_names.args) || return __throw("the number of state components must be $nn", p.lnum, p.line) for i ∈ 1:nn p.aliases[components_names.args[i]] = :($x[$i]) # todo: add aliases for state components (scalar) derivatives end # Aliases from names given by the user ss = QuoteNode(string.(components_names.args)) code = :( state!($ocp, $n, $xx, $ss) ) end return __wrap(code, p.lnum, p.line) end p_control!(p, ocp, u, m; components_names = nothing, log = false) = begin log && println("control: $u, dim: $m") u isa Symbol || return __throw("forbidden control name: $u", p.lnum, p.line) p.u = u uu = QuoteNode(u) mm = m isa Integer ? m : 9 for i ∈ 1:mm p.aliases[Symbol(u, ctindices(i))] = :($u[$i]) end # make: u₁, uβ‚‚... if the control is named u for i ∈ 1:mm p.aliases[Symbol(u, i)] = :($u[$i]) end # make: u1, u2... if the control is named u for i ∈ 1:9 p.aliases[Symbol(u, ctupperscripts(i))] = :($u^$i) end # make: uΒΉ, uΒ²... if the control is named u if (isnothing(components_names)) code = :( control!($ocp, $m, $uu) ) else mm == length(components_names.args) || return __throw("the number of control components must be $mm", p.lnum, p.line) for i ∈ 1:mm p.aliases[components_names.args[i]] = :($u[$i]) end # aliases from names given by the user ss = QuoteNode(string.(components_names.args)) code = :( control!($ocp, $m, $uu, $ss) ) end return __wrap(code, p.lnum, p.line) end p_constraint!(p, ocp, e1, e2, e3, label = gensym(); log = false) = begin c_type = constraint_type(e2, p.t, p.t0, p.tf, p.x, p.u, p.v) log && println("constraint ($c_type): $e1 ≀ $e2 ≀ $e3, ($label)") label isa Integer && (label = Symbol(:eq, label)) label isa Symbol || return __throw("forbidden label: $label", p.lnum, p.line) llabel = QuoteNode(label) code = @match c_type begin (:initial, rg) => :(constraint!($ocp, :initial; rg = $rg, lb = $e1, ub = $e3, label = $llabel)) (:final, rg) => :(constraint!($ocp, :final; rg = $rg, lb = $e1, ub = $e3, label = $llabel)) :boundary => begin gs = gensym() x0 = gensym() xf = gensym() r = gensym() ee2 = replace_call(e2, p.x, p.t0, x0) ee2 = replace_call(ee2, p.x, p.tf, xf) args = [r, x0, xf] __v_dep(p) && push!(args, p.v) quote function $gs($(args...)) @views $r[:] .= $ee2 return nothing end constraint!($ocp, :boundary; f = $gs, lb = $e1, ub = $e3, label = $llabel) end end (:control_range, rg) => :(constraint!($ocp, :control; rg = $rg, lb = $e1, ub = $e3, label = $llabel)) :control_fun => begin gs = gensym() ut = gensym() r = gensym() ee2 = replace_call(e2, p.u, p.t, ut) p.t_dep = p.t_dep || has(ee2, p.t) args = [r] __t_dep(p) && push!(args, p.t) push!(args, ut) __v_dep(p) && push!(args, p.v) quote function $gs($(args...)) @views $r[:] .= $ee2 return nothing end constraint!($ocp, :control; f = $gs, lb = $e1, ub = $e3, label = $llabel) end end (:state_range, rg) => :(constraint!($ocp, :state; rg = $rg, lb = $e1, ub = $e3, label = $llabel)) :state_fun => begin gs = gensym() xt = gensym() r = gensym() ee2 = replace_call(e2, p.x, p.t, xt) p.t_dep = p.t_dep || has(ee2, p.t) args = [r] __t_dep(p) && push!(args, p.t) push!(args, xt) __v_dep(p) && push!(args, p.v) quote function $gs($(args...)) @views $r[:] .= $ee2 return nothing end constraint!($ocp, :state; f = $gs, lb = $e1, ub = $e3, label = $llabel) end end (:variable_range, rg) => :(constraint!($ocp, :variable; rg = $rg, lb = $e1, ub = $e3, label = $llabel)) :variable_fun => begin gs = gensym() r = gensym() args = [r, p.v] quote function $gs($(args...)) @views $r[:] .= $e2 return nothing end constraint!($ocp, :variable; f = $gs, lb = $e1, ub = $e3, label = $llabel) end end :mixed => begin gs = gensym() xt = gensym() ut = gensym() r = gensym() ee2 = replace_call(e2, [p.x, p.u], p.t, [xt, ut]) p.t_dep = p.t_dep || has(ee2, p.t) args = [r] __t_dep(p) && push!(args, p.t) push!(args, xt, ut) __v_dep(p) && push!(args, p.v) quote function $gs($(args...)) @views $r[:] .= $ee2 return nothing end constraint!($ocp, :mixed; f = $gs, lb = $e1, ub = $e3, label = $llabel) end end _ => return __throw("bad constraint declaration", p.lnum, p.line) end return __wrap(code, p.lnum, p.line) end p_dynamics!(p, ocp, x, t, e, label = nothing; log = false) = begin xΜ‡ = Symbol(x, "Μ‡") log && println("dynamics: $xΜ‡($t) == $e") isnothing(label) || return __throw("dynamics cannot be labelled", p.lnum, p.line) isnothing(p.x) && return __throw("state not yet declared", p.lnum, p.line) isnothing(p.u) && return __throw("control not yet declared", p.lnum, p.line) isnothing(p.t) && return __throw("time not yet declared", p.lnum, p.line) x β‰  p.x && return __throw("wrong state for dynamics", p.lnum, p.line) t β‰  p.t && return __throw("wrong time for dynamics", p.lnum, p.line) xt = gensym() ut = gensym() e = replace_call(e, [p.x, p.u], p.t, [xt, ut]) p.t_dep = p.t_dep || has(e, t) gs = gensym() r = gensym() args = [r]; __t_dep(p) && push!(args, p.t); push!(args, xt, ut); __v_dep(p) && push!(args, p.v) code = quote function $gs($(args...)) @views $r[:] .= $e return nothing end dynamics!($ocp, $gs) end return __wrap(code, p.lnum, p.line) end p_lagrange!(p, ocp, e, type; log = false) = begin log && println("objective (Lagrange): ∫($e) β†’ $type") isnothing(p.x) && return __throw("state not yet declared", p.lnum, p.line) isnothing(p.u) && return __throw("control not yet declared", p.lnum, p.line) isnothing(p.t) && return __throw("time not yet declared", p.lnum, p.line) xt = gensym() ut = gensym() e = replace_call(e, [p.x, p.u], p.t, [xt, ut]) p.t_dep = p.t_dep || has(e, p.t) ttype = QuoteNode(type) gs = gensym() r = gensym() args = [r]; __t_dep(p) && push!(args, p.t); push!(args, xt, ut); __v_dep(p) && push!(args, p.v) code = quote function $gs($(args...)) @views $r[:] .= $e return nothing end objective!($ocp, :lagrange, $gs, $ttype) end return __wrap(code, p.lnum, p.line) end p_mayer!(p, ocp, e, type; log = false) = begin log && println("objective (Mayer): $e β†’ $type") isnothing(p.x) && return __throw("state not yet declared", p.lnum, p.line) isnothing(p.t0) && return __throw("time not yet declared", p.lnum, p.line) isnothing(p.tf) && return __throw("time not yet declared", p.lnum, p.line) has(e, :∫) && return __throw( "bad objective declaration resulting in a Mayer term with trailing ∫", p.lnum, p.line, ) gs = gensym() x0 = gensym() xf = gensym() r = gensym() e = replace_call(e, p.x, p.t0, x0) e = replace_call(e, p.x, p.tf, xf) ttype = QuoteNode(type) args = [r, x0, xf]; __v_dep(p) && push!(args, p.v) code = quote function $gs($(args...)) @views $r[:] .= $e return nothing end objective!($ocp, :mayer, $gs, $ttype) end return __wrap(code, p.lnum, p.line) end p_bolza!(p, ocp, e1, e2, type; log = false) = begin log && println("objective (Bolza): $e1 + ∫($e2) β†’ $type") isnothing(p.x) && return __throw("state not yet declared", p.lnum, p.line) isnothing(p.t0) && return __throw("time not yet declared", p.lnum, p.line) isnothing(p.tf) && return __throw("time not yet declared", p.lnum, p.line) isnothing(p.u) && return __throw("control not yet declared", p.lnum, p.line) isnothing(p.t) && return __throw("time not yet declared", p.lnum, p.line) gs1 = gensym() x0 = gensym() xf = gensym() r1 = gensym() e1 = replace_call(e1, p.x, p.t0, x0) e1 = replace_call(e1, p.x, p.tf, xf) args1 = [r1, x0, xf] __v_dep(p) && push!(args1, p.v) gs2 = gensym() xt = gensym() ut = gensym() r2 = gensym() e2 = replace_call(e2, [p.x, p.u], p.t, [xt, ut]) p.t_dep = p.t_dep || has(e2, p.t) args2 = [r2] __t_dep(p) && push!(args2, p.t) push!(args2, xt, ut) __v_dep(p) && push!(args2, p.v) ttype = QuoteNode(type) code = quote function $gs1($(args1...)) $r1[:] .= $e1 return nothing end function $gs2($(args2...)) $r2[:] .= $e2 return nothing end objective!($ocp, :bolza, $gs1, $gs2, $ttype) end return __wrap(code, p.lnum, p.line) end """ $(TYPEDSIGNATURES) Redirection to [`Model`](@ref) to avoid confusion with other functions Model from other packages if imported. This function is used by [`@def`](@ref). """ function __OCPModel(args...; kwargs...) return CTBase.Model(args...; kwargs...) end """ $(TYPEDSIGNATURES) Define an optimal control problem. One pass parsing of the definition. Can be used writing either `ocp = @def begin ... end` or `@def ocp begin ... end`. In the second case, setting `log` to `true` will display the parsing steps. # Example ```@example ocp = @def begin tf ∈ R, variable t ∈ [ 0, tf ], time x ∈ RΒ², state u ∈ R, control tf β‰₯ 0 -1 ≀ u(t) ≀ 1 q = x₁ v = xβ‚‚ q(0) == 1 v(0) == 2 q(tf) == 0 v(tf) == 0 0 ≀ q(t) ≀ 5, (1) -2 ≀ v(t) ≀ 3, (2) xΜ‡(t) == [ v(t), u(t) ] tf β†’ min end @def ocp begin tf ∈ R, variable t ∈ [ 0, tf ], time x ∈ RΒ², state u ∈ R, control tf β‰₯ 0 -1 ≀ u(t) ≀ 1 q = x₁ v = xβ‚‚ q(0) == 1 v(0) == 2 q(tf) == 0 v(tf) == 0 0 ≀ q(t) ≀ 5, (1) -2 ≀ v(t) ≀ 3, (2) xΜ‡(t) == [ v(t), u(t) ] tf β†’ min end true # final boolean to show parsing log ``` """ macro def(e) ocp = gensym() code = quote @def $ocp $e $ocp end esc(code) end macro def(ocp, e, log = false) try p0 = ParsingInfo() parse!(p0, ocp, e; log = false) # initial pass to get the dependencies (time and variable) p = ParsingInfo() p.t_dep = p0.t_dep p.v = p0.v code = parse!(p, ocp, e; log = log) in_place = true # todo: remove? init = @match (__t_dep(p), __v_dep(p)) begin (false, false) => :($ocp = __OCPModel(; in_place = $in_place)) (true, false) => :($ocp = __OCPModel(autonomous = false; in_place = $in_place)) (false, true) => :($ocp = __OCPModel(variable = true; in_place = $in_place)) _ => :($ocp = __OCPModel(autonomous = false, variable = true; in_place = $in_place)) end ee = QuoteNode(e) code = Expr(:block, init, code, :($ocp.model_expression = $ee; $ocp)) esc(code) catch ex :(throw($ex)) # can be caught by user end end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
20657
# ---------------------------------------------------------------------- # # Model getters. # """ $(TYPEDSIGNATURES) Return a 6-tuple of tuples: - `(ΞΎl, ΞΎ, ΞΎu)` are control constraints - `(Ξ·l, Ξ·, Ξ·u)` are state constraints - `(ψl, ψ, ψu)` are mixed constraints - `(Ο•l, Ο•, Ο•u)` are boundary constraints - `(ΞΈl, ΞΈ, ΞΈu)` are variable constraints - `(ul, uind, uu)` are control linear constraints of a subset of indices - `(xl, xind, xu)` are state linear constraints of a subset of indices - `(vl, vind, vu)` are variable linear constraints of a subset of indices and update information about constraints dimensions of `ocp`. Functions `ΞΎ`, `Ξ·`, `ψ`, `Ο•`, `ΞΈ` are used to evaluate the constraints at given time and state, control, or variable values. These functions are in place when the problem is defined as in place, that is when `is_in_place(ocp)`. !!! note - The dimensions of the state and control must be set before calling `nlp_constraints!`. - For a `Fixed` problem, dimensions associated with constraints on the variable are set to zero. # Example ```@example julia> (ΞΎl, ΞΎ, ΞΎu), (Ξ·l, Ξ·, Ξ·u), (ψl, ψ, ψu), (Ο•l, Ο•, Ο•u), (ΞΈl, ΞΈ, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu) = nlp_constraints!(ocp) ``` """ function nlp_constraints!(ocp::OptimalControlModel) # we check if the dimensions and times have been set __check_all_set(ocp) ControlConstraint_ = is_in_place(ocp) ? ControlConstraint! : ControlConstraint StateConstraint_ = is_in_place(ocp) ? StateConstraint! : StateConstraint MixedConstraint_ = is_in_place(ocp) ? MixedConstraint! : MixedConstraint BoundaryConstraint_ = is_in_place(ocp) ? BoundaryConstraint! : BoundaryConstraint VariableConstraint_ = is_in_place(ocp) ? VariableConstraint! : VariableConstraint ΞΎf = Vector{ControlConstraint_}() ΞΎs = Vector{Int64}() ΞΎl = Vector{ctNumber}() ΞΎu = Vector{ctNumber}() Ξ·f = Vector{StateConstraint_}() Ξ·s = Vector{Int64}() Ξ·l = Vector{ctNumber}() Ξ·u = Vector{ctNumber}() ψf = Vector{MixedConstraint_}() ψs = Vector{Int64}() ψl = Vector{ctNumber}() ψu = Vector{ctNumber}() Ο•f = Vector{BoundaryConstraint_}() Ο•s = Vector{Int64}() Ο•l = Vector{ctNumber}() Ο•u = Vector{ctNumber}() ΞΈf = Vector{VariableConstraint_}() ΞΈs = Vector{Int64}() ΞΈl = Vector{ctNumber}() ΞΈu = Vector{ctNumber}() uind = Vector{Int}() ul = Vector{ctNumber}() uu = Vector{ctNumber}() xind = Vector{Int}() xl = Vector{ctNumber}() xu = Vector{ctNumber}() vind = Vector{Int}() vl = Vector{ctNumber}() vu = Vector{ctNumber}() for (_, c) ∈ constraints(ocp) @match c begin (type, f::BoundaryConstraint_, lb, ub) && if type ∈ [:initial, :final, :boundary] end => begin push!(Ο•f, f) push!(Ο•s, length(lb)) append!(Ο•l, lb) append!(Ο•u, ub) end (:control, f::ControlConstraint_, lb, ub) => begin push!(ΞΎf, f) push!(ΞΎs, length(lb)) append!(ΞΎl, lb) append!(ΞΎu, ub) end (:control, rg, lb, ub) => begin append!(uind, rg) append!(ul, lb) append!(uu, ub) end (:state, f::StateConstraint_, lb, ub) => begin push!(Ξ·f, f) push!(Ξ·s, length(lb)) append!(Ξ·l, lb) append!(Ξ·u, ub) end (:state, rg, lb, ub) => begin append!(xind, rg) append!(xl, lb) append!(xu, ub) end (:mixed, f::MixedConstraint_, lb, ub) => begin push!(ψf, f) push!(ψs, length(lb)) append!(ψl, lb) append!(ψu, ub) end (:variable, f::VariableConstraint_, lb, ub) => begin push!(ΞΈf, f) push!(ΞΈs, length(lb)) append!(ΞΈl, lb) append!(ΞΈu, ub) end (:variable, rg, lb, ub) => begin append!(vind, rg) append!(vl, lb) append!(vu, ub) end _ => error("Internal error") end end @assert length(ΞΎl) == length(ΞΎu) @assert length(ΞΎf) == length(ΞΎs) @assert length(Ξ·l) == length(Ξ·u) @assert length(Ξ·f) == length(Ξ·s) @assert length(ψl) == length(ψu) @assert length(ψf) == length(ψs) @assert length(Ο•l) == length(Ο•u) @assert length(Ο•f) == length(Ο•s) @assert length(ΞΈl) == length(ΞΈu) @assert length(ΞΈf) == length(ΞΈs) @assert length(ul) == length(uu) @assert length(xl) == length(xu) @assert length(vl) == length(vu) function ΞΎ(t, u, v) # nonlinear control constraints dim = length(ΞΎl) val = zeros(ctNumber, dim) j = 1 for i ∈ 1:length(ΞΎf) li = ΞΎs[i] vali = ΞΎf[i](t, u, v) val[j:(j + li - 1)] .= vali # .= also allows scalar value for vali j = j + li end return val end function ΞΎ!(val, t, u, v) # nonlinear control constraints (in place) j = 1 for i ∈ 1:length(ΞΎf) li = ΞΎs[i] ΞΎf[i](@view(val[j:(j + li - 1)]), t, u, v) j = j + li end return nothing end function Ξ·(t, x, v) # nonlinear state constraints dim = length(Ξ·l) val = zeros(ctNumber, dim) j = 1 for i ∈ 1:length(Ξ·f) li = Ξ·s[i] vali = Ξ·f[i](t, x, v) val[j:(j + li - 1)] .= vali # .= also allows scalar value for vali j = j + li end return val end function Ξ·!(val, t, x, v) # nonlinear state constraints (in place) j = 1 for i ∈ 1:length(Ξ·f) li = Ξ·s[i] Ξ·f[i](@view(val[j:(j + li - 1)]), t, x, v) j = j + li end return nothing end function ψ(t, x, u, v) # nonlinear mixed constraints dim = length(ψl) val = zeros(ctNumber, dim) j = 1 for i ∈ 1:length(ψf) li = ψs[i] vali = ψf[i](t, x, u, v) val[j:(j + li - 1)] .= vali # .= also allows scalar value for vali j = j + li end return val end function ψ!(val, t, x, u, v) # nonlinear mixed constraints (in place) j = 1 for i ∈ 1:length(ψf) li = ψs[i] ψf[i](@view(val[j:(j + li - 1)]), t, x, u, v) j = j + li end return nothing end function Ο•(x0, xf, v) # nonlinear boundary constraints dim = length(Ο•l) val = zeros(ctNumber, dim) j = 1 for i ∈ 1:length(Ο•f) li = Ο•s[i] vali = Ο•f[i](x0, xf, v) val[j:(j + li - 1)] .= vali # .= also allows scalar value for vali j = j + li end return val end function Ο•!(val, x0, xf, v) # nonlinear boundary constraints j = 1 for i ∈ 1:length(Ο•f) li = Ο•s[i] Ο•f[i](@view(val[j:(j + li - 1)]), x0, xf, v) j = j + li end return nothing end function ΞΈ(v) # nonlinear variable constraints dim = length(ΞΈl) val = zeros(ctNumber, dim) j = 1 for i ∈ 1:length(ΞΈf) li = ΞΈs[i] vali = ΞΈf[i](v) val[j:(j + li - 1)] .= vali # .= also allows scalar value for vali j = j + li end return val end function ΞΈ!(val, v) # nonlinear variable constraints j = 1 for i ∈ 1:length(ΞΈf) li = ΞΈs[i] ΞΈf[i](@view(val[j:(j + li - 1)]), v) j = j + li end return nothing end ocp.dim_control_constraints = length(ΞΎl) ocp.dim_state_constraints = length(Ξ·l) ocp.dim_mixed_constraints = length(ψl) ocp.dim_boundary_constraints = length(Ο•l) ocp.dim_variable_constraints = length(ΞΈl) ocp.dim_control_range = length(ul) ocp.dim_state_range = length(xl) ocp.dim_variable_range = length(vl) ΞΎ_ = is_in_place(ocp) ? ΞΎ! : ΞΎ Ξ·_ = is_in_place(ocp) ? Ξ·! : Ξ· ψ_ = is_in_place(ocp) ? ψ! : ψ Ο•_ = is_in_place(ocp) ? Ο•! : Ο• ΞΈ_ = is_in_place(ocp) ? ΞΈ! : ΞΈ return (ΞΎl, ΞΎ_, ΞΎu), (Ξ·l, Ξ·_, Ξ·u), (ψl, ψ_, ψu), (Ο•l, Ο•_, Ο•u), (ΞΈl, ΞΈ_, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu) end """ $(TYPEDSIGNATURES) Return the constraints of the ocp or nothing. """ function constraints(ocp::OptimalControlModel) return ocp.constraints end """ $(TYPEDSIGNATURES) Return the labels of the constraints as a `Base.keys`. """ function constraints_labels(ocp::OptimalControlModel) return keys(ocp.constraints) end """ $(TYPEDSIGNATURES) Retrieve a labeled constraint. The result is a function associated with the constraint computation (not taking into account provided value / bounds). # Example ```@example julia> constraint!(ocp, :initial, 0, :c0) julia> c = constraint(ocp, :c0) julia> c(1) 1 ``` """ function constraint( ocp::OptimalControlModel{T, V}, label::Symbol, ) where {T <: TimeDependence, V <: VariableDependence} con = ocp.constraints[label] BoundaryConstraint_ = is_in_place(ocp) ? BoundaryConstraint! : BoundaryConstraint ControlConstraint_ = is_in_place(ocp) ? ControlConstraint! : ControlConstraint StateConstraint_ = is_in_place(ocp) ? StateConstraint! : StateConstraint MixedConstraint_ = is_in_place(ocp) ? MixedConstraint! : MixedConstraint VariableConstraint_ = is_in_place(ocp) ? VariableConstraint! : VariableConstraint @match con begin (:initial, f::BoundaryConstraint_, _, _) => return f (:final, f::BoundaryConstraint_, _, _) => return f (:boundary, f::BoundaryConstraint_, _, _) => return f (:control, f::ControlConstraint_, _, _) => return f (:control, rg, _, _) => begin C = @match ocp begin ::OptimalControlModel{Autonomous, Fixed} => is_in_place(ocp) ? ControlConstraint!((r, u) -> (@views r[:] .= u[rg]; nothing), T, V) : # todo: CC!{T, V}(fun) syntax? ControlConstraint(u -> u[rg], T, V) ::OptimalControlModel{Autonomous, NonFixed} => is_in_place(ocp) ? ControlConstraint!((r, u, v) -> (@views r[:] .= u[rg]; nothing), T, V) : ControlConstraint((u, v) -> u[rg], T, V) ::OptimalControlModel{NonAutonomous, Fixed} => is_in_place(ocp) ? ControlConstraint!((r, t, u) -> (@views r[:] .= u[rg]; nothing), T, V) : ControlConstraint((t, u) -> u[rg], T, V) ::OptimalControlModel{NonAutonomous, NonFixed} => is_in_place(ocp) ? ControlConstraint!((r, t, u, v) -> (@views r[:] .= u[rg]; nothing), T, V) : ControlConstraint((t, u, v) -> u[rg], T, V) _ => nothing end return C end (:state, f::StateConstraint_, _, _) => return f (:state, rg, _, _) => begin S = @match ocp begin ::OptimalControlModel{Autonomous, Fixed} => is_in_place(ocp) ? StateConstraint!((r, x) -> (@views r[:] .= x[rg]; nothing), T, V) : StateConstraint(x -> x[rg], T, V) ::OptimalControlModel{Autonomous, NonFixed} => is_in_place(ocp) ? StateConstraint!((r, x, v) -> (@views r[:] .= x[rg]; nothing), T, V) : StateConstraint((x, v) -> x[rg], T, V) ::OptimalControlModel{NonAutonomous, Fixed} => is_in_place(ocp) ? StateConstraint!((r, t, x) -> (@views r[:] .= x[rg]; nothing), T, V) : StateConstraint((t, x) -> x[rg], T, V) ::OptimalControlModel{NonAutonomous, NonFixed} => is_in_place(ocp) ? StateConstraint!((r, t, x, v) -> (@views r[:] .= x[rg]; nothing), T, V) : StateConstraint((t, x, v) -> x[rg], T, V) _ => nothing end return S end (:mixed, f::MixedConstraint_, _, _) => return f (:variable, f::VariableConstraint_, _, _) => return f (:variable, rg, _, _) => return ( is_in_place(ocp) ? VariableConstraint!((r, v) -> (@views r[:] .= v[rg]; nothing)) : VariableConstraint(v -> v[rg]) ) _ => error("Internal error") end end """ $(TYPEDSIGNATURES) Return the dimension of nonlinear state constraints (`nothing` if not knonw). Information is updated after `nlp_constraints!` is called. """ dim_state_constraints(ocp::OptimalControlModel) = ocp.dim_state_constraints """ $(TYPEDSIGNATURES) Return the dimension of nonlinear control constraints (`nothing` if not knonw). Information is updated after `nlp_constraints!` is called. """ dim_control_constraints(ocp::OptimalControlModel) = ocp.dim_control_constraints """ $(TYPEDSIGNATURES) Return the dimension of nonlinear mixed constraints (`nothing` if not knonw). Information is updated after `nlp_constraints!` is called. """ dim_mixed_constraints(ocp::OptimalControlModel) = ocp.dim_mixed_constraints """ $(TYPEDSIGNATURES) Return the dimension of nonlinear path (state + control + mixed) constraints (`nothing` if one of them is not knonw). Information is updated after `nlp_constraints!` is called. """ function dim_path_constraints(ocp::OptimalControlModel) isnothing(ocp.dim_control_constraints) && return nothing isnothing(ocp.dim_state_constraints) && return nothing isnothing(ocp.dim_mixed_constraints) && return nothing return ocp.dim_state_constraints + ocp.dim_control_constraints + ocp.dim_mixed_constraints end """ $(TYPEDSIGNATURES) Return the dimension of the boundary constraints (`nothing` if not knonw). Information is updated after `nlp_constraints!` is called. """ dim_boundary_constraints(ocp::OptimalControlModel) = ocp.dim_boundary_constraints """ $(TYPEDSIGNATURES) Return the dimension of nonlinear variable constraints (`nothing` if not knonw). Information is updated after `nlp_constraints!` is called. """ dim_variable_constraints(ocp::OptimalControlModel) = ocp.dim_variable_constraints """ $(TYPEDSIGNATURES) Return the dimension of range constraints on state (`nothing` if not knonw). Information is updated after `nlp_constraints!` is called. """ dim_state_range(ocp::OptimalControlModel) = ocp.dim_state_range """ $(TYPEDSIGNATURES) Return the dimension of range constraints on control (`nothing` if not knonw). Information is updated after `nlp_constraints!` is called. """ dim_control_range(ocp::OptimalControlModel) = ocp.dim_control_range """ $(TYPEDSIGNATURES) Return the dimension of range constraints on variable (`nothing` if not knonw). Information is updated after `nlp_constraints!` is called. """ dim_variable_range(ocp::OptimalControlModel) = ocp.dim_variable_range """ $(TYPEDSIGNATURES) Return the model expression of the optimal control problem or `nothing`. """ model_expression(ocp::OptimalControlModel) = ocp.model_expression """ $(TYPEDSIGNATURES) Return the initial time of the optimal control problem or `nothing`. """ initial_time(ocp::OptimalControlModel) = ocp.initial_time """ $(TYPEDSIGNATURES) Return the name of the initial time of the optimal control problem or `nothing`. """ initial_time_name(ocp::OptimalControlModel) = ocp.initial_time_name """ $(TYPEDSIGNATURES) Return the final time of the optimal control problem or `nothing`. """ final_time(ocp::OptimalControlModel) = ocp.final_time """ $(TYPEDSIGNATURES) Return the name of the final time of the optimal control problem or `nothing`. """ final_time_name(ocp::OptimalControlModel) = ocp.final_time_name """ $(TYPEDSIGNATURES) Return the name of the time component of the optimal control problem or `nothing`. """ time_name(ocp::OptimalControlModel) = ocp.time_name """ $(TYPEDSIGNATURES) Return the dimention of the control of the optimal control problem or `nothing`. """ control_dimension(ocp::OptimalControlModel) = ocp.control_dimension """ $(TYPEDSIGNATURES) Return the names of the components of the control of the optimal control problem or `nothing`. """ control_components_names(ocp::OptimalControlModel) = ocp.control_components_names """ $(TYPEDSIGNATURES) Return the name of the control of the optimal control problem or `nothing`. """ control_name(ocp::OptimalControlModel) = ocp.control_name """ $(TYPEDSIGNATURES) Return the dimension of the state of the optimal control problem or `nothing`. """ state_dimension(ocp::OptimalControlModel) = ocp.state_dimension """ $(TYPEDSIGNATURES) Return the names of the components of the state of the optimal control problem or `nothing`. """ state_components_names(ocp::OptimalControlModel) = ocp.state_components_names """ $(TYPEDSIGNATURES) Return the name of the state of the optimal control problem or `nothing`. """ state_name(ocp::OptimalControlModel) = ocp.state_name """ $(TYPEDSIGNATURES) Return the dimension of the variable of the optimal control problem or `nothing`. """ variable_dimension(ocp::OptimalControlModel) = ocp.variable_dimension """ $(TYPEDSIGNATURES) Return the names of the components of the variable of the optimal control problem or `nothing`. """ variable_components_names(ocp::OptimalControlModel) = ocp.variable_components_names """ $(TYPEDSIGNATURES) Return the name of the variable of the optimal control problem or `nothing`. """ variable_name(ocp::OptimalControlModel) = ocp.variable_name """ $(TYPEDSIGNATURES) Return the Lagrange part of the cost of the optimal control problem or `nothing`. """ lagrange(ocp::OptimalControlModel) = ocp.lagrange """ $(TYPEDSIGNATURES) Return the Mayer part of the cost of the optimal control problem or `nothing`. """ mayer(ocp::OptimalControlModel) = ocp.mayer """ $(TYPEDSIGNATURES) Return the criterion (`:min` or `:max`) of the optimal control problem or `nothing`. """ criterion(ocp::OptimalControlModel) = ocp.criterion """ $(TYPEDSIGNATURES) Return the dynamics of the optimal control problem or `nothing`. """ dynamics(ocp::OptimalControlModel) = ocp.dynamics """ $(TYPEDSIGNATURES) Return `true` if the model is autonomous. """ is_autonomous(ocp::OptimalControlModel{Autonomous, <:VariableDependence}) = true is_autonomous(ocp::OptimalControlModel{NonAutonomous, <:VariableDependence}) = false """ $(TYPEDSIGNATURES) Return `true` if the model has been defined as time dependent. """ is_time_dependent(ocp::OptimalControlModel) = !is_autonomous(ocp) """ $(TYPEDSIGNATURES) Return `true` if the model has been defined as time independent. """ is_time_independent(ocp::OptimalControlModel) = !is_time_dependent(ocp) """ $(TYPEDSIGNATURES) Return `true` if the criterion type of `ocp` is `:min`. """ is_min(ocp::OptimalControlModel) = criterion(ocp) == :min """ $(TYPEDSIGNATURES) Return `true` if the criterion type of `ocp` is `:max`. """ is_max(ocp::OptimalControlModel) = !is_min(ocp) """ $(TYPEDSIGNATURES) Return `true` if the model is fixed (= has no variable). """ is_fixed(ocp::OptimalControlModel{<:TimeDependence, Fixed}) = true is_fixed(ocp::OptimalControlModel{<:TimeDependence, NonFixed}) = false """ $(TYPEDSIGNATURES) Return `true` if the model has been defined as variable dependent. """ is_variable_dependent(ocp::OptimalControlModel) = !is_fixed(ocp) """ $(TYPEDSIGNATURES) Return `true` if the model has been defined as variable independent. """ is_variable_independent(ocp::OptimalControlModel) = !is_variable_dependent(ocp) """ $(TYPEDSIGNATURES) Return `true` if functions defining the ocp are in-place. Return nothing if this information has not yet been set. """ is_in_place(ocp::OptimalControlModel) = ocp.in_place """ $(TYPEDSIGNATURES) Return `true` if the model has been defined with free initial time. """ has_free_initial_time(ocp::OptimalControlModel) = (typeof(initial_time(ocp)) == Index) """ $(TYPEDSIGNATURES) Return `true` if the model has been defined with free final time. """ has_free_final_time(ocp::OptimalControlModel) = (typeof(final_time(ocp)) == Index) """ $(TYPEDSIGNATURES) Return `true` if the model has been defined with lagrange cost. """ has_lagrange_cost(ocp::OptimalControlModel) = !isnothing(lagrange(ocp)) """ $(TYPEDSIGNATURES) Return `true` if the model has been defined with mayer cost. """ has_mayer_cost(ocp::OptimalControlModel) = !isnothing(mayer(ocp))
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
29444
# ---------------------------------------------------------------------- # # Interaction with the Model that affect it. Setters / Constructors. # """ $(TYPEDSIGNATURES) Set the model expression of the optimal control problem or `nothing`. """ model_expression!(ocp::OptimalControlModel, model_expression::Expr) = (ocp.model_expression = model_expression; nothing) """ $(TYPEDSIGNATURES) Return a new `OptimalControlModel` instance, that is a model of an optimal control problem. The model is defined by the following optional keyword argument: - `autonomous`: either `true` or `false`. Default is `true`. - `variable`: either `true` or `false`. Default is `false`. # Examples ```@example julia> ocp = Model() julia> ocp = Model(autonomous=false) julia> ocp = Model(autonomous=false, variable=true) ``` !!! note - If the time dependence of the model is defined as nonautonomous, then, the dynamics function, the lagrange cost and the path constraints must be defined as functions of time and state, and possibly control. If the model is defined as autonomous, then, the dynamics function, the lagrange cost and the path constraints must be defined as functions of state, and possibly control. """ function Model(; autonomous::Bool = true, variable::Bool = false, in_place::Bool = false) time_dependence = autonomous ? Autonomous : NonAutonomous variable_dependence = variable ? NonFixed : Fixed ocp = OptimalControlModel{time_dependence, variable_dependence}() ocp.in_place = in_place return ocp end """ $(TYPEDSIGNATURES) Return a new `OptimalControlModel` instance, that is a model of an optimal control problem. The model is defined by the following argument: - `dependencies`: either `Autonomous` or `NonAutonomous`. Default is `Autonomous`. And either `NonFixed` or `Fixed`. Default is `Fixed`. # Examples ```@example julia> ocp = Model() julia> ocp = Model(NonAutonomous) julia> ocp = Model(Autonomous, NonFixed) ``` !!! note - If the time dependence of the model is defined as nonautonomous, then, the dynamics function, the lagrange cost and the path constraints must be defined as functions of time and state, and possibly control. If the model is defined as autonomous, then, the dynamics function, the lagrange cost and the path constraints must be defined as functions of state, and possibly control. """ function Model( dependencies::DataType...; in_place::Bool = false, )::OptimalControlModel{<:TimeDependence, <:VariableDependence} # some checkings: __check_dependencies(dependencies) time_dependence = NonAutonomous ∈ dependencies ? NonAutonomous : Autonomous variable_dependence = NonFixed ∈ dependencies ? NonFixed : Fixed return OptimalControlModel{time_dependence, variable_dependence}(; in_place = in_place) end """ $(TYPEDSIGNATURES) Define the variable dimension and possibly the names of each component. !!! note You can use variable! once to set the variable dimension when the model is `NonFixed`. # Examples ```@example julia> variable!(ocp, 1, "v") julia> variable!(ocp, 2, "v", [ "v₁", "vβ‚‚" ]) ``` """ function variable!( ocp::OptimalControlModel, q::Dimension, name::String = __variable_name(), components_names::Vector{String} = __variable_components_names(q, name), ) # checkings is_fixed(ocp) && throw(UnauthorizedCall("the ocp has no variable, you cannot use variable! function.")) __is_variable_set(ocp) && throw(UnauthorizedCall("the variable has already been set.")) (q > 1) && (size(components_names, 1) β‰  q) && throw( IncorrectArgument( "the number of variable names must be equal to the variable dimension", ), ) ocp.variable_dimension = q ocp.variable_components_names = components_names ocp.variable_name = name return nothing end function variable!( ocp::OptimalControlModel, q::Dimension, name::Symbol, components_names::Vector{Symbol}, ) variable!(ocp, q, string(name), string.(components_names)) end function variable!( ocp::OptimalControlModel, q::Dimension, name::Symbol, components_names::Vector{String}, ) variable!(ocp, q, string(name), components_names) end function variable!(ocp::OptimalControlModel, q::Dimension, name::Symbol) variable!(ocp, q, string(name)) end """ $(TYPEDSIGNATURES) Define the state dimension and possibly the names of each component. !!! note You must use state! only once to set the state dimension. # Examples ```@example julia> state!(ocp, 1) julia> state_dimension(ocp) 1 julia> state_components_names(ocp) ["x"] julia> state!(ocp, 1, "y") julia> state_dimension(ocp) 1 julia> state_components_names(ocp) ["y"] julia> state!(ocp, 2) julia> state_dimension(ocp) 2 julia> state_components_names(ocp) ["x₁", "xβ‚‚"] julia> state!(ocp, 2, :y) julia> state_dimension(ocp) 2 julia> state_components_names(ocp) ["y₁", "yβ‚‚"] julia> state!(ocp, 2, "y") julia> state_dimension(ocp) 2 julia> state_components_names(ocp) ["y₁", "yβ‚‚"] ``` """ function state!( ocp::OptimalControlModel, n::Dimension, name::String = __state_name(), components_names::Vector{String} = __state_components_names(n, name), ) # checkings __is_state_set(ocp) && throw(UnauthorizedCall("the state has already been set.")) (n > 1) && (size(components_names, 1) β‰  n) && throw(IncorrectArgument("the number of state names must be equal to the state dimension")) ocp.state_dimension = n ocp.state_components_names = components_names ocp.state_name = name return nothing end function state!( ocp::OptimalControlModel, n::Dimension, name::Symbol, components_names::Vector{Symbol}, ) state!(ocp, n, string(name), string.(components_names)) end function state!( ocp::OptimalControlModel, n::Dimension, name::Symbol, components_names::Vector{String}, ) state!(ocp, n, string(name), components_names) end function state!(ocp::OptimalControlModel, n::Dimension, name::Symbol) state!(ocp, n, string(name)) end """ $(TYPEDSIGNATURES) Define the control dimension and possibly the names of each coordinate. !!! note You must use control! only once to set the control dimension. # Examples ```@example julia> control!(ocp, 1) julia> control_dimension(ocp) 1 julia> control_components_names(ocp) ["u"] julia> control!(ocp, 1, "v") julia> control_dimension(ocp) 1 julia> control_components_names(ocp) ["v"] julia> control!(ocp, 2) julia> control_dimension(ocp) 2 julia> control_components_names(ocp) ["u₁", "uβ‚‚"] julia> control!(ocp, 2, :v) julia> control_dimension(ocp) 2 julia> control_components_names(ocp) ["v₁", "vβ‚‚"] julia> control!(ocp, 2, "v") julia> control_dimension(ocp) 2 julia> control_components_names(ocp) ["v₁", "vβ‚‚"] ``` """ function control!( ocp::OptimalControlModel, m::Dimension, name::String = __control_name(), components_names::Vector{String} = __control_components_names(m, name), ) # checkings __is_control_set(ocp) && throw(UnauthorizedCall("the control has already been set.")) (m > 1) && (size(components_names, 1) β‰  m) && throw( IncorrectArgument("the number of control names must be equal to the control dimension"), ) ocp.control_dimension = m ocp.control_components_names = components_names ocp.control_name = name return nothing end function control!( ocp::OptimalControlModel, m::Dimension, name::Symbol, components_names::Vector{Symbol}, ) control!(ocp, m, string(name), string.(components_names)) end function control!( ocp::OptimalControlModel, m::Dimension, name::Symbol, components_names::Vector{String}, ) control!(ocp, m, string(name), components_names) end function control!(ocp::OptimalControlModel, m::Dimension, name::Symbol) control!(ocp, m, string(name)) end """ $(TYPEDSIGNATURES) Set the initial and final times. We denote by t0 the initial time and tf the final time. The optimal control problem is denoted ocp. When a time is free, then one must provide the corresponding index of the ocp variable. !!! note You must use time! only once to set either the initial or the final time, or both. # Examples ```@example julia> time!(ocp, t0=0, tf=1 ) # Fixed t0 and fixed tf julia> time!(ocp, t0=0, indf=2) # Fixed t0 and free tf julia> time!(ocp, ind0=2, tf=1 ) # Free t0 and fixed tf julia> time!(ocp, ind0=2, indf=3) # Free t0 and free tf ``` When you plot a solution of an optimal control problem, the name of the time variable appears. By default, the name is "t". Consider you want to set the name of the time variable to "s". ```@example julia> time!(ocp, t0=0, tf=1, name="s") # name is a String # or julia> time!(ocp, t0=0, tf=1, name=:s ) # name is a Symbol ``` """ function time!( ocp::OptimalControlModel{<:TimeDependence, VT}; t0::Union{Time, Nothing} = nothing, tf::Union{Time, Nothing} = nothing, ind0::Union{Integer, Nothing} = nothing, indf::Union{Integer, Nothing} = nothing, name::Union{String, Symbol} = __time_name(), ) where {VT} # check if the problem has been set to Variable or NonVariable (VT == NonFixed) && (!isnothing(ind0) || !isnothing(indf)) && __check_variable_set(ocp) # check if indices are in 1:q q = variable_dimension(ocp) !isnothing(ind0) && !(1 ≀ ind0 ≀ q) && throw(IncorrectArgument("the index of t0 variable must be contained in 1:$q")) !isnothing(indf) && !(1 ≀ indf ≀ q) && throw(IncorrectArgument("the index of tf variable must be contained in 1:$q")) # check if the function has been already called __is_time_set(ocp) && throw(UnauthorizedCall("the time has already been set.")) # check consistency !isnothing(t0) && !isnothing(ind0) && throw( IncorrectArgument( "Providing t0 and ind0 has no sense. The initial time cannot be fixed and free.", ), ) isnothing(t0) && isnothing(ind0) && throw( IncorrectArgument( "Please either provide the value of the initial time t0 (if fixed) or its index in the variable of ocp (if free).", ), ) !isnothing(tf) && !isnothing(indf) && throw( IncorrectArgument( "Providing tf and indf has no sense. The final time cannot be fixed and free.", ), ) isnothing(tf) && isnothing(indf) && throw( IncorrectArgument( "Please either provide the value of the final time tf (if fixed) or its index in the variable of ocp (if free).", ), ) VT == Fixed && !isnothing(ind0) && throw( IncorrectArgument( "You cannot have the initial time free (ind0 is provided) and the ocp non variable.", ), ) VT == Fixed && !isnothing(indf) && throw( IncorrectArgument( "You cannot have the final time free (indf is provided) and the ocp non variable.", ), ) # name = name isa String ? name : string(name) # core @match (t0, ind0, tf, indf) begin (::Time, ::Nothing, ::Time, ::Nothing) => begin # (t0, tf) ocp.initial_time = t0 ocp.final_time = tf ocp.time_name = name ocp.initial_time_name = t0 isa Integer ? string(t0) : string(round(t0, digits = 2)) ocp.final_time_name = tf isa Integer ? string(tf) : string(round(tf, digits = 2)) end (::Nothing, ::Integer, ::Time, ::Nothing) => begin # (ind0, tf) ocp.initial_time = Index(ind0) ocp.final_time = tf ocp.time_name = name ocp.initial_time_name = variable_components_names(ocp)[ind0] ocp.final_time_name = tf isa Integer ? string(tf) : string(round(tf, digits = 2)) end (::Time, ::Nothing, ::Nothing, ::Integer) => begin # (t0, indf) ocp.initial_time = t0 ocp.final_time = Index(indf) ocp.time_name = name ocp.initial_time_name = t0 isa Integer ? string(t0) : string(round(t0, digits = 2)) ocp.final_time_name = variable_components_names(ocp)[indf] end (::Nothing, ::Integer, ::Nothing, ::Integer) => begin # (ind0, indf) ocp.initial_time = Index(ind0) ocp.final_time = Index(indf) ocp.time_name = name ocp.initial_time_name = variable_components_names(ocp)[ind0] ocp.final_time_name = variable_components_names(ocp)[indf] end _ => throw(IncorrectArgument("Provided arguments are inconsistent.")) end return nothing end """ $(TYPEDSIGNATURES) Add a constraint to an optimal control problem, denoted `ocp`. !!! note - The state, control and variable dimensions must be set before. Use state!, control! and variable!. - The initial and final times must be set before. Use time!. - When an element is of dimension 1, consider it as a scalar. You can add an `:initial`, `:final`, `:control`, `:state` or `:variable` box constraint (whole range). # Range constraint on the state, control or variable You can add an `:initial`, `:final`, `:control`, `:state` or `:variable` box constraint on a range of it, that is only on some components. If not range is specified, then the constraint is on the whole range. We denote by `x`, `u` and `v` respectively the state, control and variable. We denote by `n`, `m` and `q` respectively the dimension of the state, control and variable. The range of the constraint must be contained in 1:n if the constraint is on the state, or 1:m if the constraint is on the control, or 1:q if the constraint is on the variable. ## Examples ```@example julia> constraint!(ocp, :initial; rg=1:2:5, lb=[ 0, 0, 0 ], ub=[ 1, 2, 1 ]) julia> constraint!(ocp, :initial; rg=2:3, lb=[ 0, 0 ], ub=[ 1, 2 ]) julia> constraint!(ocp, :final; rg=1, lb=0, ub=2) julia> constraint!(ocp, :control; rg=1, lb=0, ub=2) julia> constraint!(ocp, :state; rg=2:3, lb=[ 0, 0 ], ub=[ 1, 2 ]) julia> constraint!(ocp, :variable; rg=1:2, lb=[ 0, 0 ], ub=[ 1, 2 ]) julia> constraint!(ocp, :initial; lb=[ 0, 0, 0 ]) # [ 0, 0, 0 ] ≀ x(t0), dim(x) = 3 julia> constraint!(ocp, :initial; lb=[ 0, 0, 0 ], ub=[ 1, 2, 1 ]) # [ 0, 0, 0 ] ≀ x(t0) ≀ [ 1, 2, 1 ], dim(x) = 3 julia> constraint!(ocp, :final; lb=-1, ub=1) # -1 ≀ x(tf) ≀ 1, dim(x) = 1 julia> constraint!(ocp, :control; lb=0, ub=2) # 0 ≀ u(t) ≀ 2, t ∈ [t0, tf], dim(u) = 1 julia> constraint!(ocp, :state; lb=[ 0, 0 ], ub=[ 1, 2 ]) # [ 0, 0 ] ≀ x(t) ≀ [ 1, 2 ], t ∈ [t0, tf], dim(x) = 2 julia> constraint!(ocp, :variable; lb=[ 0, 0 ], ub=[ 1, 2 ]) # [ 0, 0 ] ≀ v ≀ [ 1, 2 ], dim(v) = 2 ``` # Functional constraint You can add a `:boundary`, `:control`, `:state`, `:mixed` or `:variable` box functional constraint. ## Examples ```@example # variable independent ocp julia> constraint!(ocp, :boundary; f = (x0, xf) -> x0[3]+xf[2], lb=0, ub=1) # variable dependent ocp julia> constraint!(ocp, :boundary; f = (x0, xf, v) -> x0[3]+xf[2]*v[1], lb=0, ub=1) # time independent and variable independent ocp julia> constraint!(ocp, :control; f = u -> 2u, lb=0, ub=1) julia> constraint!(ocp, :state; f = x -> x-1, lb=[ 0, 0, 0 ], ub=[ 1, 2, 1 ]) julia> constraint!(ocp, :mixed; f = (x, u) -> x[1]-u, lb=0, ub=1) # time dependent and variable independent ocp julia> constraint!(ocp, :control; f = (t, u) -> 2u, lb=0, ub=1) julia> constraint!(ocp, :state; f = (t, x) -> t * x, lb=[ 0, 0, 0 ], ub=[ 1, 2, 1 ]) julia> constraint!(ocp, :mixed; f = (t, x, u) -> x[1]-u, lb=0, ub=1) # time independent and variable dependent ocp julia> constraint!(ocp, :control; f = (u, v) -> 2u * v[1], lb=0, ub=1) julia> constraint!(ocp, :state; f = (x, v) -> x * v[1], lb=[ 0, 0, 0 ], ub=[ 1, 2, 1 ]) julia> constraint!(ocp, :mixed; f = (x, u, v) -> x[1]-v[2]*u, lb=0, ub=1) # time dependent and variable dependent ocp julia> constraint!(ocp, :control; f = (t, u, v) -> 2u+v[2], lb=0, ub=1) julia> constraint!(ocp, :state; f = (t, x, v) -> x-t*v[1], lb=[ 0, 0, 0 ], ub=[ 1, 2, 1 ]) julia> constraint!(ocp, :mixed; f = (t, x, u, v) -> x[1]*v[2]-u, lb=0, ub=1) ``` """ function constraint!( ocp::OptimalControlModel{T, V}, type::Symbol; rg::Union{OrdinalRange{<:Integer}, Index, Integer, Nothing} = nothing, f::Union{Function, Nothing} = nothing, lb::Union{ctVector, Nothing} = nothing, ub::Union{ctVector, Nothing} = nothing, val::Union{ctVector, Nothing} = nothing, label::Symbol = __constraint_label(), ) where {T <: TimeDependence, V <: VariableDependence} __check_all_set(ocp) type == :variable && is_fixed(ocp) && throw( UnauthorizedCall( "the ocp has no variable" * ", you cannot use constraint! function with type=:variable.", ), ) label ∈ constraints_labels(ocp) && throw(UnauthorizedCall("the constraint named " * String(label) * " already exists.")) isnothing(val) && isnothing(lb) && isnothing(ub) && throw( UnauthorizedCall( "Calling the constraint! function without any bounds is not authorized.", ), ) # value for equality constraint # if val is not nothing then lb and ub should be nothing !isnothing(val) && (!isnothing(lb) || !isnothing(ub)) && throw(UnauthorizedCall("If val is provided then lb and ub must not be given.")) if !isnothing(val) lb = val ub = val end # bounds isnothing(lb) && (lb = -Inf * (size(ub, 1) == 1 ? 1 : ones(eltype(ub), size(ub, 1)))) isnothing(ub) && (ub = Inf * (size(lb, 1) == 1 ? 1 : ones(eltype(lb), size(lb, 1)))) # dimensions n = state_dimension(ocp) m = control_dimension(ocp) q = variable_dimension(ocp) # range (typeof(rg) <: Int) && (rg = Index(rg)) # todo: scalar range # core BoundaryConstraint_ = is_in_place(ocp) ? BoundaryConstraint! : BoundaryConstraint ControlConstraint_ = is_in_place(ocp) ? ControlConstraint! : ControlConstraint StateConstraint_ = is_in_place(ocp) ? StateConstraint! : StateConstraint MixedConstraint_ = is_in_place(ocp) ? MixedConstraint! : MixedConstraint VariableConstraint_ = is_in_place(ocp) ? VariableConstraint! : VariableConstraint @match (rg, f, lb, ub) begin (::Nothing, ::Nothing, ::ctVector, ::ctVector) => begin if type ∈ [:initial, :final, :state] rg = n == 1 ? Index(1) : 1:n # todo: scalar range txt = "the lower bound `lb`, the upper bound `ub` and the value `val` must be of dimension $n" elseif type == :control rg = m == 1 ? Index(1) : 1:m txt = "the lower bound `lb`, the upper bound `ub` and the value `val` must be of dimension $m" elseif type == :variable rg = q == 1 ? Index(1) : 1:q txt = "the lower bound `lb`, the upper bound `ub` and the value `val` must be of dimension $q" else throw( IncorrectArgument( "the following type of constraint is not valid: " * String(type) * ". Please choose in [ :initial, :final, :control, :state, :variable ] or check the arguments of the constraint! method.", ), ) end (length(rg) != length(lb)) && throw(IncorrectArgument(txt)) (length(rg) != length(ub)) && throw(IncorrectArgument(txt)) constraint!(ocp, type; rg = rg, lb = lb, ub = ub, label = label) end (::RangeConstraint, ::Nothing, ::ctVector, ::ctVector) => begin txt = "the range `rg`, the lower bound `lb`, the upper bound `ub` and the value `val` must have the same dimension" (length(rg) != length(lb)) && throw(IncorrectArgument(txt)) (length(rg) != length(ub)) && throw(IncorrectArgument(txt)) # check if the range is valid if type == :initial !all(1 .≀ rg .≀ n) && throw( IncorrectArgument( "the range of the initial state constraint must be contained in 1:$n", ), ) elseif type == :final !all(1 .≀ rg .≀ n) && throw( IncorrectArgument( "the range of the final state constraint must be contained in 1:$n", ), ) elseif type == :control !all(1 .≀ rg .≀ m) && throw( IncorrectArgument( "the range of the control constraint must be contained in 1:$m", ), ) elseif type == :state !all(1 .≀ rg .≀ n) && throw( IncorrectArgument( "the range of the state constraint must be contained in 1:$n", ), ) elseif type == :variable !all(1 .≀ rg .≀ q) && throw( IncorrectArgument( "the range of the variable constraint must be contained in 1:$q", ), ) end # set the constraint fun_rg = @match type begin :initial => if is_in_place(ocp) V == Fixed ? BoundaryConstraint!((r, x0, xf) -> (@views r[:] .= x0[rg]; nothing), V) : BoundaryConstraint!((r, x0, xf, v) -> (@views r[:] .= x0[rg]; nothing), V) else V == Fixed ? BoundaryConstraint((x0, xf) -> x0[rg], V) : BoundaryConstraint((x0, xf, v) -> x0[rg], V) end :final => if is_in_place(ocp) V == Fixed ? BoundaryConstraint!((r, x0, xf) -> (@views r[:] .= xf[rg]; nothing), V) : BoundaryConstraint!((r, x0, xf, v) -> (@views r[:] .= xf[rg]; nothing), V) else V == Fixed ? BoundaryConstraint((x0, xf) -> xf[rg], V) : BoundaryConstraint((x0, xf, v) -> xf[rg], V) end :control || :state || :variable => rg _ => throw( IncorrectArgument( "the following type of constraint is not valid: " * String(type) * ". Please choose in [ :initial, :final, :control, :state, :variable ] or check the arguments of the constraint! method.", ), ) end ocp.constraints[label] = (type, fun_rg, lb, ub) end (::Nothing, ::Function, ::ctVector, ::ctVector) => begin # set the constraint if type == :boundary ocp.constraints[label] = (type, BoundaryConstraint_(f, V), lb, ub) elseif type == :control ocp.constraints[label] = (type, ControlConstraint_(f, T, V), lb, ub) elseif type == :state ocp.constraints[label] = (type, StateConstraint_(f, T, V), lb, ub) elseif type == :mixed ocp.constraints[label] = (type, MixedConstraint_(f, T, V), lb, ub) elseif type == :variable ocp.constraints[label] = (type, VariableConstraint_(f), lb, ub) else throw( IncorrectArgument( "the following type of constraint is not valid: " * String(type) * ". Please choose in [ :boundary, :control, :state, :mixed ] or check the arguments of the constraint! method.", ), ) end end _ => throw(IncorrectArgument("Provided arguments are inconsistent.")) end return nothing end """ $(TYPEDSIGNATURES) Set the dynamics. !!! note You can use dynamics! only once to define the dynamics. - The state, control and variable dimensions must be set before. Use state!, control! and variable!. - The times must be set before. Use time!. - When an element is of dimension 1, consider it as a scalar. # Example ```@example julia> dynamics!(ocp, f) ``` """ function dynamics!( ocp::OptimalControlModel{T, V}, f::Function, ) where {T <: TimeDependence, V <: VariableDependence} # we check if the dimensions and times have been set __check_all_set(ocp) __is_dynamics_set(ocp) && throw(UnauthorizedCall("the dynamics has already been set.")) Dynamics_ = is_in_place(ocp) ? Dynamics! : Dynamics ocp.dynamics = Dynamics_(f, T, V) return nothing end """ $(TYPEDSIGNATURES) Set the criterion to the function `f`. Type can be `:mayer` or `:lagrange`. Criterion is `:min` or `:max`. !!! note You can use objective! only once to define the objective. - The state, control and variable dimensions must be set before. Use state!, control! and variable!. - The times must be set before. Use time!. - When an element is of dimension 1, consider it as a scalar. # Examples ```@example julia> objective!(ocp, :mayer, (x0, xf) -> x0[1] + xf[2]) julia> objective!(ocp, :lagrange, (x, u) -> x[1]^2 + u^2) # the control is of dimension 1 ``` !!! warning If you set twice the objective, only the last one will be taken into account. """ function objective!( ocp::OptimalControlModel{T, V}, type::Symbol, f::Function, criterion::Symbol = __criterion_type(), ) where {T <: TimeDependence, V <: VariableDependence} # we check if the dimensions and times have been set __check_all_set(ocp) __is_objective_set(ocp) && throw(UnauthorizedCall("the objective has already been set.")) # check the validity of the criterion !__is_criterion_valid(criterion) && throw( IncorrectArgument( "the following criterion is not valid: " * String(criterion) * ". Please choose in [ :min, :max ].", ), ) ocp.criterion = criterion # set the objective Mayer_ = is_in_place(ocp) ? Mayer! : Mayer Lagrange_ = is_in_place(ocp) ? Lagrange! : Lagrange if type == :mayer ocp.mayer = Mayer_(f, V) elseif type == :lagrange ocp.lagrange = Lagrange_(f, T, V) else throw( IncorrectArgument( "the following objective is not valid: " * String(objective) * ". Please choose in [ :mayer, :lagrange ].", ), ) end return nothing end """ $(TYPEDSIGNATURES) Set the criterion to the function `g` and `f⁰`. Type can be `:bolza`. Criterion is `:min` or `:max`. !!! note You can use objective! only once to define the objective. - The state, control and variable dimensions must be set before. Use state!, control! and variable!. - The times must be set before. Use time!. - When an element is of dimension 1, consider it as a scalar. # Example ```@example julia> objective!(ocp, :bolza, (x0, xf) -> x0[1] + xf[2], (x, u) -> x[1]^2 + u^2) # the control is of dimension 1 ``` """ function objective!( ocp::OptimalControlModel{T, V}, type::Symbol, g::Function, f⁰::Function, criterion::Symbol = __criterion_type(), ) where {T <: TimeDependence, V <: VariableDependence} # we check if the dimensions and times have been set __check_all_set(ocp) __is_objective_set(ocp) && throw(UnauthorizedCall("the objective has already been set.")) # check the validity of the criterion !__is_criterion_valid(criterion) && throw( IncorrectArgument( "the following criterion is not valid: " * String(criterion) * ". Please choose in [ :min, :max ].", ), ) ocp.criterion = criterion # set the objective Mayer_ = is_in_place(ocp) ? Mayer! : Mayer Lagrange_ = is_in_place(ocp) ? Lagrange! : Lagrange if type == :bolza ocp.mayer = Mayer_(g, V) ocp.lagrange = Lagrange_(f⁰, T, V) else throw( IncorrectArgument( "the following objective is not valid: " * String(objective) * ". Please choose :bolza.", ), ) end return nothing end """ $(TYPEDSIGNATURES) Remove a labeled constraint. # Example ```@example julia> remove_constraint!(ocp, :con) ``` """ function remove_constraint!(ocp::OptimalControlModel, label::Symbol) if !haskey(ocp.constraints, label) throw( IncorrectArgument( "the following constraint does not exist: " * String(label) * ". Please check the list of constraints: ocp.constraints.", ), ) end delete!(ocp.constraints, label) return nothing end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
8690
# ---------------------------------------------------------------------- # # Definition of an optimal control model # """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) """ @with_kw mutable struct OptimalControlModel{ time_dependence <: TimeDependence, variable_dependence <: VariableDependence, } <: AbstractOptimalControlModel model_expression::Union{Nothing, Expr} = nothing initial_time::Union{Time, Index, Nothing} = nothing initial_time_name::Union{String, Nothing} = nothing final_time::Union{Time, Index, Nothing} = nothing final_time_name::Union{String, Nothing} = nothing time_name::Union{String, Nothing} = nothing control_dimension::Union{Dimension, Nothing} = nothing control_components_names::Union{Vector{String}, Nothing} = nothing control_name::Union{String, Nothing} = nothing state_dimension::Union{Dimension, Nothing} = nothing state_components_names::Union{Vector{String}, Nothing} = nothing state_name::Union{String, Nothing} = nothing variable_dimension::Union{Dimension, Nothing} = nothing variable_components_names::Union{Vector{String}, Nothing} = nothing variable_name::Union{String, Nothing} = nothing lagrange::Union{Lagrange, Lagrange!, Nothing} = nothing mayer::Union{Mayer, Mayer!, Nothing} = nothing criterion::Union{Symbol, Nothing} = nothing dynamics::Union{Dynamics, Dynamics!, Nothing} = nothing constraints::Dict{Symbol, Tuple{Vararg{Any}}} = Dict{Symbol, Tuple{Vararg{Any}}}() dim_control_constraints::Union{Dimension, Nothing} = nothing dim_state_constraints::Union{Dimension, Nothing} = nothing dim_mixed_constraints::Union{Dimension, Nothing} = nothing dim_boundary_constraints::Union{Dimension, Nothing} = nothing dim_variable_constraints::Union{Dimension, Nothing} = nothing dim_control_range::Union{Dimension, Nothing} = nothing dim_state_range::Union{Dimension, Nothing} = nothing dim_variable_range::Union{Dimension, Nothing} = nothing in_place::Union{Bool, Nothing} = nothing end # ---------------------------------------------------------------------- # # checkings: internal functions # """ $(TYPEDSIGNATURES) """ function __is_variable_not_set(ocp::OptimalControlModel) conditions = [ isnothing(ocp.variable_dimension), isnothing(ocp.variable_name), isnothing(ocp.variable_components_names), ] @assert all(conditions) || !any(conditions) # either all or none return isnothing(ocp.variable_dimension) end """ $(TYPEDSIGNATURES) """ __is_variable_set(ocp::OptimalControlModel) = !__is_variable_not_set(ocp) """ $(TYPEDSIGNATURES) """ function __is_time_not_set(ocp::OptimalControlModel) conditions = [ isnothing(ocp.initial_time), isnothing(ocp.initial_time_name), isnothing(ocp.final_time), isnothing(ocp.final_time_name), isnothing(ocp.time_name), ] @assert all(conditions) || !any(conditions) # either all or none return isnothing(ocp.initial_time) end """ $(TYPEDSIGNATURES) """ __is_time_set(ocp::OptimalControlModel) = !__is_time_not_set(ocp) """ $(TYPEDSIGNATURES) """ function __is_state_not_set(ocp::OptimalControlModel) conditions = [ isnothing(ocp.state_dimension), isnothing(ocp.state_name), isnothing(ocp.state_components_names), ] @assert all(conditions) || !any(conditions) # either all or none return isnothing(ocp.state_dimension) end """ $(TYPEDSIGNATURES) """ __is_state_set(ocp::OptimalControlModel) = !__is_state_not_set(ocp) """ $(TYPEDSIGNATURES) """ function __is_control_not_set(ocp::OptimalControlModel) conditions = [ isnothing(ocp.control_dimension), isnothing(ocp.control_name), isnothing(ocp.control_components_names), ] @assert all(conditions) || !any(conditions) # either all or none return isnothing(ocp.control_dimension) end """ $(TYPEDSIGNATURES) """ __is_control_set(ocp::OptimalControlModel) = !__is_control_not_set(ocp) """ $(TYPEDSIGNATURES) """ __is_dynamics_not_set(ocp::OptimalControlModel) = isnothing(ocp.dynamics) """ $(TYPEDSIGNATURES) """ __is_dynamics_set(ocp::OptimalControlModel) = !__is_dynamics_not_set(ocp) """ $(TYPEDSIGNATURES) """ function __is_objective_not_set(ocp::OptimalControlModel) conditions = [isnothing(ocp.lagrange) && isnothing(ocp.mayer), isnothing(ocp.criterion)] @assert all(conditions) || !any(conditions) # either all or none return isnothing(ocp.criterion) end """ $(TYPEDSIGNATURES) """ __is_objective_set(ocp::OptimalControlModel) = !__is_objective_not_set(ocp) """ $(TYPEDSIGNATURES) """ __is_empty(ocp::OptimalControlModel) = begin isnothing(ocp.initial_time) && isnothing(ocp.initial_time_name) && isnothing(ocp.final_time) && isnothing(ocp.final_time_name) && isnothing(ocp.time_name) && isnothing(ocp.lagrange) && isnothing(ocp.mayer) && isnothing(ocp.criterion) && isnothing(ocp.dynamics) && isnothing(ocp.state_dimension) && isnothing(ocp.state_name) && isnothing(ocp.state_components_names) && isnothing(ocp.control_dimension) && isnothing(ocp.control_name) && isnothing(ocp.control_components_names) && isnothing(ocp.variable_dimension) && isnothing(ocp.variable_name) && isnothing(ocp.variable_components_names) && isempty(ocp.constraints) end """ $(TYPEDSIGNATURES) """ __is_initial_time_free(ocp) = ocp.initial_time isa Index """ $(TYPEDSIGNATURES) """ __is_final_time_free(ocp) = ocp.final_time isa Index """ $(TYPEDSIGNATURES) """ __is_incomplete(ocp) = begin __is_time_not_set(ocp) || __is_state_not_set(ocp) || __is_control_not_set(ocp) || __is_dynamics_not_set(ocp) || __is_objective_not_set(ocp) || (__is_variable_not_set(ocp) && is_variable_dependent(ocp)) end """ $(TYPEDSIGNATURES) """ __is_complete(ocp) = !__is_incomplete(ocp) """ $(TYPEDSIGNATURES) """ __is_criterion_valid(criterion::Symbol) = criterion ∈ [:min, :max] # ---------------------------------------------------------------------- # # checkings: internal functions, return exceptions # """ $(TYPEDSIGNATURES) Throw ```IncorrectArgument``` exception if dependencies arguments are incorrect. """ function __check_dependencies(dependencies::Tuple{Vararg{DataType}}) size(filter(p -> p <: VariableDependence, dependencies), 1) > 1 && throw( IncorrectArgument( "the number of arguments about variable dependence must be equal at most to 1", ), ) size(filter(p -> p <: TimeDependence, dependencies), 1) > 1 && throw( IncorrectArgument( "the number of arguments about time dependence must be equal at most to 1", ), ) size(dependencies, 1) > 2 && throw( IncorrectArgument("the number of arguments about dependencies must be equal at most to 2"), ) size(filter(p -> !(p <: Union{TimeDependence, VariableDependence}), dependencies), 1) > 0 && throw( IncorrectArgument( "wrong type arguments, possible arguments are: NonAutonomous, Autonomous, Fixed, NonFixed", ), ) end """ $(TYPEDSIGNATURES) Throw ```UnauthorizedCall``` exception if the state of an ocp is not set. """ function __check_state_set(ocp::OptimalControlModel) __is_state_not_set(ocp) && throw(UnauthorizedCall("the state dimension has to be set before.")) end """ $(TYPEDSIGNATURES) Throw ```UnauthorizedCall``` exception if the control of an ocp is not set. """ function __check_control_set(ocp::OptimalControlModel) __is_control_not_set(ocp) && throw(UnauthorizedCall("the control dimension has to be set before.")) end """ $(TYPEDSIGNATURES) Throw ```UnauthorizedCall``` exception if the time of an ocp is not set. """ function __check_is_time_set(ocp::OptimalControlModel) __is_time_not_set(ocp) && throw(UnauthorizedCall("the time dimension has to be set before.")) end """ $(TYPEDSIGNATURES) Throw ```UnauthorizedCall``` exception if the variable of an ocp is not set. """ function __check_variable_set(ocp::OptimalControlModel{<:TimeDependence, NonFixed}) __is_variable_not_set(ocp) && throw(UnauthorizedCall("the variable dimension has to be set before.")) end """ $(TYPEDSIGNATURES) Do nothing, no variable for fixed ocp. """ function __check_variable_set(ocp::OptimalControlModel{<:TimeDependence, Fixed}) return nothing end """ $(TYPEDSIGNATURES) Check if the parameters of an ocp are set. """ function __check_all_set(ocp::OptimalControlModel) __check_state_set(ocp) __check_control_set(ocp) __check_is_time_set(ocp) __check_variable_set(ocp) end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
8495
""" $(TYPEDSIGNATURES) Return the time grid of the optimal control solution or `nothing`. """ time_grid(sol::OptimalControlSolution) = sol.time_grid """ $(TYPEDSIGNATURES) Return the name of the initial time of the optimal control solution or `nothing`. """ initial_time_name(sol::OptimalControlSolution) = sol.initial_time_name """ $(TYPEDSIGNATURES) Return the name of final time of the optimal control solution or `nothing`. """ final_time_name(sol::OptimalControlSolution) = sol.final_time_name """ $(TYPEDSIGNATURES) Return the name of the time component of the optimal control solution or `nothing`. """ time_name(sol::OptimalControlSolution) = sol.time_name """ $(TYPEDSIGNATURES) Return the dimension of the control of the optimal control solution or `nothing`. """ control_dimension(sol::OptimalControlSolution) = sol.control_dimension """ $(TYPEDSIGNATURES) Return the names of the components of the control of the optimal control solution or `nothing`. """ control_components_names(sol::OptimalControlSolution) = sol.control_components_names """ $(TYPEDSIGNATURES) Return the name of the control of the optimal control solution or `nothing`. """ control_name(sol::OptimalControlSolution) = sol.control_name """ $(TYPEDSIGNATURES) Return the control (function of time) of the optimal control solution or `nothing`. ```@example julia> t0 = time_grid(sol)[1] julia> u = control(sol) julia> u0 = u(t0) # control at initial time ``` """ control(sol::OptimalControlSolution) = sol.control """ $(TYPEDSIGNATURES) Return the control values at times `time_grid(sol)` of the optimal control solution or `nothing`. ```@example julia> u = control_discretized(sol) julia> u0 = u[1] # control at initial time ``` """ control_discretized(sol::OptimalControlSolution) = control(sol).(sol.time_grid) """ $(TYPEDSIGNATURES) Return the dimension of the state of the optimal control solution or `nothing`. """ state_dimension(sol::OptimalControlSolution) = sol.state_dimension """ $(TYPEDSIGNATURES) Return the names of the components of the state of the optimal control solution or `nothing`. """ state_components_names(sol::OptimalControlSolution) = sol.state_components_names """ $(TYPEDSIGNATURES) Return the name of the state of the optimal control solution or `nothing`. """ state_name(sol::OptimalControlSolution) = sol.state_name """ $(TYPEDSIGNATURES) Return the state (function of time) of the optimal control solution or `nothing`. ```@example julia> t0 = time_grid(sol)[1] julia> x = state(sol) julia> x0 = x(t0) ``` """ state(sol::OptimalControlSolution) = sol.state """ $(TYPEDSIGNATURES) Return the state values at times `time_grid(sol)` of the optimal control solution or `nothing`. ```@example julia> x = state_discretized(sol) julia> x0 = x[1] # state at initial time ``` """ state_discretized(sol::OptimalControlSolution) = state(sol).(sol.time_grid) """ $(TYPEDSIGNATURES) Return the dimension of the variable of the optimal control solution or `nothing`. """ variable_dimension(sol::OptimalControlSolution) = sol.variable_dimension """ $(TYPEDSIGNATURES) Return the names of the components of the variable of the optimal control solution or `nothing`. """ variable_components_names(sol::OptimalControlSolution) = sol.variable_components_names """ $(TYPEDSIGNATURES) Return the name of the variable of the optimal control solution or `nothing`. """ variable_name(sol::OptimalControlSolution) = sol.variable_name """ $(TYPEDSIGNATURES) Return the variable of the optimal control solution or `nothing`. ```@example julia> v = variable(sol) ``` """ variable(sol::OptimalControlSolution) = sol.variable """ $(TYPEDSIGNATURES) Return the costate of the optimal control solution or `nothing`. ```@example julia> t0 = time_grid(sol)[1] julia> p = costate(sol) julia> p0 = p(t0) ``` """ costate(sol::OptimalControlSolution) = sol.costate """ $(TYPEDSIGNATURES) Return the costate values at times `time_grid(sol)` of the optimal control solution or `nothing`. ```@example julia> p = costate_discretized(sol) julia> p0 = p[1] # costate at initial time ``` """ costate_discretized(sol::OptimalControlSolution) = costate(sol).(sol.time_grid) """ $(TYPEDSIGNATURES) Return the objective value of the optimal control solution or `nothing`. """ objective(sol::OptimalControlSolution) = sol.objective """ $(TYPEDSIGNATURES) Return the number of iterations (if solved by an iterative method) of the optimal control solution or `nothing`. """ iterations(sol::OptimalControlSolution) = sol.iterations """ $(TYPEDSIGNATURES) Return the stopping criterion (a Symbol) of the optimal control solution or `nothing`. """ stopping(sol::OptimalControlSolution) = sol.stopping """ $(TYPEDSIGNATURES) Return the message associated to the stopping criterion of the optimal control solution or `nothing`. """ message(sol::OptimalControlSolution) = sol.message """ $(TYPEDSIGNATURES) Return the true if the solver has finished successfully of false if not, or `nothing`. """ success(sol::OptimalControlSolution) = sol.success """ $(TYPEDSIGNATURES) Return a dictionary of additional infos depending on the solver or `nothing`. """ infos(sol::OptimalControlSolution) = sol.infos # constraints and multipliers """ $(TYPEDSIGNATURES) Return the boundary constraints of the optimal control solution or `nothing`. """ boundary_constraints(sol::OptimalControlSolution) = sol.boundary_constraints """ $(TYPEDSIGNATURES) Return the multipliers to the boundary constraints of the optimal control solution or `nothing`. """ mult_boundary_constraints(sol::OptimalControlSolution) = sol.mult_boundary_constraints """ $(TYPEDSIGNATURES) Return the variable constraints of the optimal control solution or `nothing`. """ variable_constraints(sol::OptimalControlSolution) = sol.variable_constraints """ $(TYPEDSIGNATURES) Return the multipliers to the variable constraints of the optimal control solution or `nothing`. """ mult_variable_constraints(sol::OptimalControlSolution) = sol.mult_variable_constraints """ $(TYPEDSIGNATURES) Return the multipliers to the variable lower bounds of the optimal control solution or `nothing`. """ mult_variable_box_lower(sol::OptimalControlSolution) = sol.mult_variable_box_lower """ $(TYPEDSIGNATURES) Return the multipliers to the variable upper bounds of the optimal control solution or `nothing`. """ mult_variable_box_upper(sol::OptimalControlSolution) = sol.mult_variable_box_upper """ $(TYPEDSIGNATURES) Return the control constraints of the optimal control solution or `nothing`. """ control_constraints(sol::OptimalControlSolution) = sol.control_constraints """ $(TYPEDSIGNATURES) Return the multipliers to the control constraints of the optimal control solution or `nothing`. """ mult_control_constraints(sol::OptimalControlSolution) = sol.mult_control_constraints """ $(TYPEDSIGNATURES) Return the state constraints of the optimal control solution or `nothing`. """ state_constraints(sol::OptimalControlSolution) = sol.state_constraints """ $(TYPEDSIGNATURES) Return the multipliers to the state constraints of the optimal control solution or `nothing`. """ mult_state_constraints(sol::OptimalControlSolution) = sol.mult_state_constraints """ $(TYPEDSIGNATURES) Return the mixed state-control constraints of the optimal control solution or `nothing`. """ mixed_constraints(sol::OptimalControlSolution) = sol.mixed_constraints """ $(TYPEDSIGNATURES) Return the multipliers to the mixed state-control constraints of the optimal control solution or `nothing`. """ mult_mixed_constraints(sol::OptimalControlSolution) = sol.mult_mixed_constraints """ $(TYPEDSIGNATURES) Return the multipliers to the state lower bounds of the optimal control solution or `nothing`. """ mult_state_box_lower(sol::OptimalControlSolution) = sol.mult_state_box_lower """ $(TYPEDSIGNATURES) Return the multipliers to the state upper bounds of the optimal control solution or `nothing`. """ mult_state_box_upper(sol::OptimalControlSolution) = sol.mult_state_box_upper """ $(TYPEDSIGNATURES) Return the multipliers to the control lower bounds of the optimal control solution or `nothing`. """ mult_control_box_lower(sol::OptimalControlSolution) = sol.mult_control_box_lower """ $(TYPEDSIGNATURES) Return the multipliers to the control upper bounds of the optimal control solution or `nothing`. """ mult_control_box_upper(sol::OptimalControlSolution) = sol.mult_control_box_upper
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
14677
# ---------------------------------------------------------------------- # # Interaction with an optimal control solution that affect it. Setters / Constructors. # """ $(TYPEDSIGNATURES) Constructor from an optimal control problem. Internal. """ function __OptimalControlSolution( ocp::OptimalControlModel; state::Union{Nothing, Function} = nothing, control::Union{Nothing, Function} = nothing, objective::Union{Nothing, ctNumber} = nothing, costate::Union{Nothing, Function} = nothing, time_grid::Union{Nothing, TimesDisc} = nothing, variable::Union{Nothing, Variable} = nothing, iterations::Union{Nothing, Integer} = nothing, stopping::Union{Nothing, Symbol} = nothing, message::Union{Nothing, String} = nothing, success::Union{Nothing, Bool} = nothing, infos::Dict{Symbol, Any} = Dict{Symbol, Any}(), boundary_constraints::Union{Nothing, ctVector} = nothing, mult_boundary_constraints::Union{Nothing, ctVector} = nothing, variable_constraints::Union{Nothing, ctVector} = nothing, mult_variable_constraints::Union{Nothing, ctVector} = nothing, mult_variable_box_lower::Union{Nothing, ctVector} = nothing, mult_variable_box_upper::Union{Nothing, ctVector} = nothing, control_constraints::Union{Nothing, Function} = nothing, mult_control_constraints::Union{Nothing, Function} = nothing, state_constraints::Union{Nothing, Function} = nothing, mult_state_constraints::Union{Nothing, Function} = nothing, mixed_constraints::Union{Nothing, Function} = nothing, mult_mixed_constraints::Union{Nothing, Function} = nothing, mult_state_box_lower::Union{Nothing, Function} = nothing, mult_state_box_upper::Union{Nothing, Function} = nothing, mult_control_box_lower::Union{Nothing, Function} = nothing, mult_control_box_upper::Union{Nothing, Function} = nothing, )::OptimalControlSolution # sol = OptimalControlSolution() # data from ocp sol.initial_time_name = initial_time_name(ocp) sol.final_time_name = final_time_name(ocp) sol.time_name = time_name(ocp) sol.control_dimension = control_dimension(ocp) sol.control_components_names = control_components_names(ocp) sol.control_name = control_name(ocp) sol.state_dimension = state_dimension(ocp) sol.state_components_names = state_components_names(ocp) sol.state_name = state_name(ocp) sol.variable_dimension = variable_dimension(ocp) sol.variable_components_names = variable_components_names(ocp) sol.variable_name = variable_name(ocp) # data from args sol.state = state sol.control = control sol.objective = objective sol.costate = costate sol.time_grid = time_grid sol.variable = variable sol.iterations = iterations sol.stopping = stopping sol.message = message sol.success = success sol.infos = infos sol.boundary_constraints = boundary_constraints sol.mult_boundary_constraints = mult_boundary_constraints sol.variable_constraints = variable_constraints sol.mult_variable_constraints = mult_variable_constraints sol.mult_variable_box_lower = mult_variable_box_lower sol.mult_variable_box_upper = mult_variable_box_upper sol.control_constraints = control_constraints sol.mult_control_constraints = mult_control_constraints sol.state_constraints = state_constraints sol.mult_state_constraints = mult_state_constraints sol.mixed_constraints = mixed_constraints sol.mult_mixed_constraints = mult_mixed_constraints sol.mult_state_box_lower = mult_state_box_lower sol.mult_state_box_upper = mult_state_box_upper sol.mult_control_box_lower = mult_control_box_lower sol.mult_control_box_upper = mult_control_box_upper return sol end """ $(TYPEDSIGNATURES) Constructor from an optimal control problem for a Fixed ocp. """ function OptimalControlSolution( ocp::OptimalControlModel{<:TimeDependence, Fixed}; state::Function, control::Function, objective::ctNumber, variable::Union{Nothing, Variable} = nothing, costate::Union{Nothing, Function} = nothing, time_grid::Union{Nothing, TimesDisc} = nothing, iterations::Union{Nothing, Integer} = nothing, stopping::Union{Nothing, Symbol} = nothing, message::Union{Nothing, String} = nothing, success::Union{Nothing, Bool} = nothing, infos::Dict{Symbol, Any} = Dict{Symbol, Any}(), boundary_constraints::Union{Nothing, ctVector} = nothing, mult_boundary_constraints::Union{Nothing, ctVector} = nothing, variable_constraints::Union{Nothing, ctVector} = nothing, mult_variable_constraints::Union{Nothing, ctVector} = nothing, mult_variable_box_lower::Union{Nothing, ctVector} = nothing, mult_variable_box_upper::Union{Nothing, ctVector} = nothing, control_constraints::Union{Nothing, Function} = nothing, mult_control_constraints::Union{Nothing, Function} = nothing, state_constraints::Union{Nothing, Function} = nothing, mult_state_constraints::Union{Nothing, Function} = nothing, mixed_constraints::Union{Nothing, Function} = nothing, mult_mixed_constraints::Union{Nothing, Function} = nothing, mult_state_box_lower::Union{Nothing, Function} = nothing, mult_state_box_upper::Union{Nothing, Function} = nothing, mult_control_box_lower::Union{Nothing, Function} = nothing, mult_control_box_upper::Union{Nothing, Function} = nothing, )::OptimalControlSolution return __OptimalControlSolution( ocp; state = state, control = control, objective = objective, costate = costate, time_grid = time_grid, variable = variable, iterations = iterations, stopping = stopping, message = message, success = success, infos = infos, boundary_constraints = boundary_constraints, mult_boundary_constraints = mult_boundary_constraints, variable_constraints = variable_constraints, mult_variable_constraints = mult_variable_constraints, mult_variable_box_lower = mult_variable_box_lower, mult_variable_box_upper = mult_variable_box_upper, control_constraints = control_constraints, mult_control_constraints = mult_control_constraints, state_constraints = state_constraints, mult_state_constraints = mult_state_constraints, mixed_constraints = mixed_constraints, mult_mixed_constraints = mult_mixed_constraints, mult_state_box_lower = mult_state_box_lower, mult_state_box_upper = mult_state_box_upper, mult_control_box_lower = mult_control_box_lower, mult_control_box_upper = mult_control_box_upper, ) end """ $(TYPEDSIGNATURES) Constructor from an optimal control problem for a NonFixed ocp. """ function OptimalControlSolution( ocp::OptimalControlModel{<:TimeDependence, NonFixed}; state::Function, control::Function, objective::ctNumber, variable::Variable, costate::Union{Nothing, Function} = nothing, time_grid::Union{Nothing, TimesDisc} = nothing, iterations::Union{Nothing, Integer} = nothing, stopping::Union{Nothing, Symbol} = nothing, message::Union{Nothing, String} = nothing, success::Union{Nothing, Bool} = nothing, infos::Dict{Symbol, Any} = Dict{Symbol, Any}(), boundary_constraints::Union{Nothing, ctVector} = nothing, mult_boundary_constraints::Union{Nothing, ctVector} = nothing, variable_constraints::Union{Nothing, ctVector} = nothing, mult_variable_constraints::Union{Nothing, ctVector} = nothing, mult_variable_box_lower::Union{Nothing, ctVector} = nothing, mult_variable_box_upper::Union{Nothing, ctVector} = nothing, control_constraints::Union{Nothing, Function} = nothing, mult_control_constraints::Union{Nothing, Function} = nothing, state_constraints::Union{Nothing, Function} = nothing, mult_state_constraints::Union{Nothing, Function} = nothing, mixed_constraints::Union{Nothing, Function} = nothing, mult_mixed_constraints::Union{Nothing, Function} = nothing, mult_state_box_lower::Union{Nothing, Function} = nothing, mult_state_box_upper::Union{Nothing, Function} = nothing, mult_control_box_lower::Union{Nothing, Function} = nothing, mult_control_box_upper::Union{Nothing, Function} = nothing, )::OptimalControlSolution return __OptimalControlSolution( ocp; state = state, control = control, objective = objective, costate = costate, time_grid = time_grid, variable = variable, iterations = iterations, stopping = stopping, message = message, success = success, infos = infos, boundary_constraints = boundary_constraints, mult_boundary_constraints = mult_boundary_constraints, variable_constraints = variable_constraints, mult_variable_constraints = mult_variable_constraints, mult_variable_box_lower = mult_variable_box_lower, mult_variable_box_upper = mult_variable_box_upper, control_constraints = control_constraints, mult_control_constraints = mult_control_constraints, state_constraints = state_constraints, mult_state_constraints = mult_state_constraints, mixed_constraints = mixed_constraints, mult_mixed_constraints = mult_mixed_constraints, mult_state_box_lower = mult_state_box_lower, mult_state_box_upper = mult_state_box_upper, mult_control_box_lower = mult_control_box_lower, mult_control_box_upper = mult_control_box_upper, ) end # setters #state!(sol::OptimalControlSolution, state::Function) = (sol.state = state; nothing) #control!(sol::OptimalControlSolution, control::Function) = (sol.control = control; nothing) #objective!(sol::OptimalControlSolution, objective::ctNumber) = (sol.objective = objective; nothing) #variable!(sol::OptimalControlSolution, variable::Variable) = (sol.variable = variable; nothing) """ $(TYPEDSIGNATURES) Set the time grid. """ time_grid!(sol::OptimalControlSolution, time_grid::TimesDisc) = (sol.time_grid = time_grid; nothing) """ $(TYPEDSIGNATURES) Set the costate. """ costate!(sol::OptimalControlSolution, costate::Function) = (sol.costate = costate; nothing) """ $(TYPEDSIGNATURES) Set the number of iterations. """ iterations!(sol::OptimalControlSolution, iterations::Int) = (sol.iterations = iterations; nothing) """ $(TYPEDSIGNATURES) Set the stopping criterion. """ stopping!(sol::OptimalControlSolution, stopping::Symbol) = (sol.stopping = stopping; nothing) """ $(TYPEDSIGNATURES) Set the message of stopping. """ message!(sol::OptimalControlSolution, message::String) = (sol.message = message; nothing) """ $(TYPEDSIGNATURES) Set the success. """ success!(sol::OptimalControlSolution, success::Bool) = (sol.success = success; nothing) """ $(TYPEDSIGNATURES) Set the additional infos. """ infos!(sol::OptimalControlSolution, infos::Dict{Symbol, Any}) = (sol.infos = infos; nothing) """ $(TYPEDSIGNATURES) Set the boundary constraints. """ boundary_constraints!(sol::OptimalControlSolution, boundary_constraints::ctVector) = (sol.boundary_constraints = boundary_constraints; nothing) """ $(TYPEDSIGNATURES) Set the multipliers to the boundary constraints. """ mult_boundary_constraints!(sol::OptimalControlSolution, mult_boundary_constraints::ctVector) = (sol.mult_boundary_constraints = mult_boundary_constraints; nothing) """ $(TYPEDSIGNATURES) Set the variable constraints. """ variable_constraints!(sol::OptimalControlSolution, variable_constraints::ctVector) = (sol.variable_constraints = variable_constraints; nothing) """ $(TYPEDSIGNATURES) Set the multipliers to the variable constraints. """ mult_variable_constraints!(sol::OptimalControlSolution, mult_variable_constraints::ctVector) = (sol.mult_variable_constraints = mult_variable_constraints; nothing) """ $(TYPEDSIGNATURES) Set the multipliers to the variable lower bounds. """ mult_variable_box_lower!(sol::OptimalControlSolution, mult_variable_box_lower::ctVector) = (sol.mult_variable_box_lower = mult_variable_box_lower; nothing) """ $(TYPEDSIGNATURES) Set the multipliers to the variable upper bounds. """ mult_variable_box_upper!(sol::OptimalControlSolution, mult_variable_box_upper::ctVector) = (sol.mult_variable_box_upper = mult_variable_box_upper; nothing) """ $(TYPEDSIGNATURES) Set the control constraints. """ control_constraints!(sol::OptimalControlSolution, control_constraints::Function) = (sol.control_constraints = control_constraints; nothing) """ $(TYPEDSIGNATURES) Set the multipliers to the control constraints. """ mult_control_constraints!(sol::OptimalControlSolution, mult_control_constraints::Function) = (sol.mult_control_constraints = mult_control_constraints; nothing) """ $(TYPEDSIGNATURES) Set the state constraints. """ state_constraints!(sol::OptimalControlSolution, state_constraints::Function) = (sol.state_constraints = state_constraints; nothing) """ $(TYPEDSIGNATURES) Set the multipliers to the state constraints. """ mult_state_constraints!(sol::OptimalControlSolution, mult_state_constraints::Function) = (sol.mult_state_constraints = mult_state_constraints; nothing) """ $(TYPEDSIGNATURES) Set the mixed state/control constraints. """ mixed_constraints!(sol::OptimalControlSolution, mixed_constraints::Function) = (sol.mixed_constraints = mixed_constraints; nothing) """ $(TYPEDSIGNATURES) Set the multipliers to the mixed state/control constraints. """ mult_mixed_constraints!(sol::OptimalControlSolution, mult_mixed_constraints::Function) = (sol.mult_mixed_constraints = mult_mixed_constraints; nothing) """ $(TYPEDSIGNATURES) Set the multipliers to the state lower bounds. """ mult_state_box_lower!(sol::OptimalControlSolution, mult_state_box_lower::Function) = (sol.mult_state_box_lower = mult_state_box_lower; nothing) """ $(TYPEDSIGNATURES) Set the multipliers to the state upper bounds. """ mult_state_box_upper!(sol::OptimalControlSolution, mult_state_box_upper::Function) = (sol.mult_state_box_upper = mult_state_box_upper; nothing) """ $(TYPEDSIGNATURES) Set the multipliers to the control lower bounds. """ mult_control_box_lower!(sol::OptimalControlSolution, mult_control_box_lower::Function) = (sol.mult_control_box_lower = mult_control_box_lower; nothing) """ $(TYPEDSIGNATURES) Set the multipliers to the control upper bounds. """ mult_control_box_upper!(sol::OptimalControlSolution, mult_control_box_upper::Function) = (sol.mult_control_box_upper = mult_control_box_upper; nothing)
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
3237
# -------------------------------------------------------------------------------------------------- # Definition of an Optimal Control Solution # """ $(TYPEDEF) Abstract type for optimal control solutions. """ abstract type AbstractOptimalControlSolution end """ $(TYPEDEF) Type of an optimal control solution. # Fields $(TYPEDFIELDS) """ @with_kw mutable struct OptimalControlSolution <: AbstractOptimalControlSolution # time_grid = [t0, t1, ...] time_grid::Union{Nothing, TimesDisc} = nothing # name of t, t0 and tf time_name::Union{Nothing, String} = nothing initial_time_name::Union{Nothing, String} = nothing final_time_name::Union{Nothing, String} = nothing # control: dimension, name of u = (u₁, uβ‚‚, ...) and u(t) control_dimension::Union{Nothing, Dimension} = nothing control_components_names::Union{Nothing, Vector{String}} = nothing control_name::Union{Nothing, String} = nothing control::Union{Nothing, Function} = nothing # state: dimension, name of x = (x₁, xβ‚‚, ...) and x(t) state_dimension::Union{Nothing, Dimension} = nothing state_components_names::Union{Nothing, Vector{String}} = nothing state_name::Union{Nothing, String} = nothing state::Union{Nothing, Function} = nothing # variable: dimension, name of v = (v₁, vβ‚‚, ...) and value of v variable_dimension::Union{Nothing, Dimension} = nothing variable_components_names::Union{Nothing, Vector{String}} = nothing variable_name::Union{Nothing, String} = nothing variable::Union{Nothing, Variable} = nothing # costate: p(t) costate::Union{Nothing, Function} = nothing # objective value objective::Union{Nothing, ctNumber} = nothing # solver infos iterations::Union{Nothing, Int} = nothing # number of iterations stopping::Union{Nothing, Symbol} = nothing # the stopping criterion message::Union{Nothing, String} = nothing # the message corresponding to the stopping criterion success::Union{Nothing, Bool} = nothing # whether or not the method has finished successfully: CN1, stagnation vs iterations max # dictionary to save additional infos infos::Dict{Symbol, Any} = Dict{Symbol, Any}() # constraints and multipliers boundary_constraints::Union{Nothing, ctVector} = nothing mult_boundary_constraints::Union{Nothing, ctVector} = nothing variable_constraints::Union{Nothing, ctVector} = nothing mult_variable_constraints::Union{Nothing, ctVector} = nothing mult_variable_box_lower::Union{Nothing, ctVector} = nothing mult_variable_box_upper::Union{Nothing, ctVector} = nothing control_constraints::Union{Nothing, Function} = nothing mult_control_constraints::Union{Nothing, Function} = nothing state_constraints::Union{Nothing, Function} = nothing mult_state_constraints::Union{Nothing, Function} = nothing mixed_constraints::Union{Nothing, Function} = nothing mult_mixed_constraints::Union{Nothing, Function} = nothing mult_state_box_lower::Union{Nothing, Function} = nothing mult_state_box_upper::Union{Nothing, Function} = nothing mult_control_box_lower::Union{Nothing, Function} = nothing mult_control_box_upper::Union{Nothing, Function} = nothing end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
9697
# -------------------------------------------------------------------------------------------------- # model # # Display: text/html ? # Base.show, Base.print # pretty print : https://docs.julialang.org/en/v1/manual/types/#man-custom-pretty-printing __print(e::Expr, io::IO, l::Int) = begin @match e begin :(($a, $b)) => println(io, " "^l, a, ", ", b) _ => println(io, " "^l, e) end end """ $(TYPEDSIGNATURES) Print the optimal control problem. """ function Base.show( io::IO, ::MIME"text/plain", ocp::OptimalControlModel{<:TimeDependence, <:VariableDependence}, ) # check if the problem is empty __is_empty(ocp) && return # some_printing = false # print the code of the model if model_expression(ocp) is not nothing if !isnothing(model_expression(ocp)) # some checks @assert hasproperty(model_expression(ocp), :head) # #println(io) if __is_complete(ocp) printstyled(io, "The ", bold = true) is_time_dependent(ocp) ? printstyled(io, "(non autonomous) ", bold = true) : printstyled(io, "(autonomous) ", bold = true) printstyled(io, "optimal control problem is given by:\n", bold = true) else printstyled( io, "The optimal control problem is not complete but made of:\n", bold = true, ) end println(io) # print the code tab = 4 code = striplines(model_expression(ocp)) @match code.head begin :block => [__print(code.args[i], io, tab) for i ∈ eachindex(code.args)] _ => __print(code, io, tab) end some_printing = true end if __is_complete(ocp) # print the model if is is complete # dimensions x_dim = state_dimension(ocp) u_dim = control_dimension(ocp) v_dim = is_variable_dependent(ocp) ? variable_dimension(ocp) : -1 # names t_name = time_name(ocp) t0_name = initial_time_name(ocp) tf_name = final_time_name(ocp) x_name = state_name(ocp) u_name = control_name(ocp) v_name = is_variable_dependent(ocp) ? variable_name(ocp) : "" xi_names = state_components_names(ocp) ui_names = control_components_names(ocp) vi_names = is_variable_dependent(ocp) ? variable_components_names(ocp) : [] # dependencies t_ = is_time_dependent(ocp) ? t_name * ", " : "" _v = is_variable_dependent(ocp) ? ", " * v_name : "" # other names bounds_args_names = x_name * "(" * t0_name * "), " * x_name * "(" * tf_name * ")" * _v mixed_args_names = t_ * x_name * "(" * t_name * "), " * u_name * "(" * t_name * ")" * _v state_args_names = t_ * x_name * "(" * t_name * ")" * _v control_args_names = t_ * u_name * "(" * t_name * ")" * _v # some_printing && println(io) printstyled(io, "The ", bold = true) is_time_dependent(ocp) ? printstyled(io, "(non autonomous) ", bold = true) : printstyled(io, "(autonomous) ", bold = true) printstyled(io, "optimal control problem is of the form:\n", bold = true) println(io) # J printstyled(io, " minimize ", color = :blue) print(io, "J(" * x_name * ", " * u_name * _v * ") = ") # Mayer !isnothing(mayer(ocp)) && print(io, "g(" * bounds_args_names * ")") (!isnothing(mayer(ocp)) && !isnothing(lagrange(ocp))) && print(io, " + ") # Lagrange if !isnothing(lagrange(ocp)) println( io, '\u222B', " f⁰(" * mixed_args_names * ") d" * t_name * ", over [" * t0_name * ", " * tf_name * "]", ) else println(io, "") end # constraints println(io, "") printstyled(io, " subject to\n", color = :blue) println(io, "") # dynamics println( io, " " * x_name, '\u0307', "(" * t_name * ") = f(" * mixed_args_names * "), " * t_name * " in [" * t0_name * ", " * tf_name * "] a.e.,", ) println(io, "") # other constraints: control, state, mixed, boundary, bounds on u, bounds on x (ΞΎl, ΞΎ, ΞΎu), (Ξ·l, Ξ·, Ξ·u), (ψl, ψ, ψu), (Ο•l, Ο•, Ο•u), (ulb, uind, uub), (xlb, xind, xub) = nlp_constraints!(ocp) has_constraints = false if !isempty(ΞΎl) || !isempty(ulb) has_constraints = true println(io, " ΞΎl ≀ ΞΎ(" * control_args_names * ") ≀ ΞΎu, ") end if !isempty(Ξ·l) || !isempty(xlb) has_constraints = true println(io, " Ξ·l ≀ Ξ·(" * state_args_names * ") ≀ Ξ·u, ") end if !isempty(ψl) has_constraints = true println(io, " ψl ≀ ψ(" * mixed_args_names * ") ≀ ψu, ") end if !isempty(Ο•l) has_constraints = true println(io, " Ο•l ≀ Ο•(" * bounds_args_names * ") ≀ Ο•u, ") end has_constraints ? println(io, "") : nothing # spaces x_space = "R" * (x_dim == 1 ? "" : ctupperscripts(x_dim)) u_space = "R" * (u_dim == 1 ? "" : ctupperscripts(u_dim)) # state name and space if x_dim == 1 x_name_space = x_name * "(" * t_name * ")" else x_name_space = x_name * "(" * t_name * ")" if xi_names != [x_name * ctindices(i) for i ∈ range(1, x_dim)] x_name_space *= " = (" for i ∈ 1:x_dim x_name_space *= xi_names[i] * "(" * t_name * ")" i < x_dim && (x_name_space *= ", ") end x_name_space *= ")" end end x_name_space *= " ∈ " * x_space # control name and space if u_dim == 1 u_name_space = u_name * "(" * t_name * ")" else u_name_space = u_name * "(" * t_name * ")" if ui_names != [u_name * ctindices(i) for i ∈ range(1, u_dim)] u_name_space *= " = (" for i ∈ 1:u_dim u_name_space *= ui_names[i] * "(" * t_name * ")" i < u_dim && (u_name_space *= ", ") end u_name_space *= ")" end end u_name_space *= " ∈ " * u_space if is_variable_dependent(ocp) # space v_space = "R" * (v_dim == 1 ? "" : ctupperscripts(v_dim)) # variable name and space if v_dim == 1 v_name_space = v_name else v_name_space = v_name if vi_names != [v_name * ctindices(i) for i ∈ range(1, v_dim)] v_name_space *= " = (" for i ∈ 1:v_dim v_name_space *= vi_names[i] i < v_dim && (v_name_space *= ", ") end v_name_space *= ")" end end v_name_space *= " ∈ " * v_space # print print(io, " where ", x_name_space, ", ", u_name_space, " and ", v_name_space, ".\n") else # print print(io, " where ", x_name_space, " and ", u_name_space, ".\n") end some_printing = true end # some_printing && println(io) printstyled(io, "Declarations ", bold = true) printstyled(io, "(* required):\n", bold = false) #println(io) # print table of settings header = ["times*", "state*", "control*"] #is_variable_dependent(ocp) && push!(header, "variable") push!(header, "variable") push!(header, "dynamics*", "objective*", "constraints") data = hcat( __is_time_not_set(ocp) ? "X" : "V", __is_state_not_set(ocp) ? "X" : "V", __is_control_not_set(ocp) ? "X" : "V", ) #is_variable_dependent(ocp) && begin (data = hcat(data, __is_variable_not_set(ocp) ? "X" : "V")) end data = hcat( data, __is_dynamics_not_set(ocp) ? "X" : "V", __is_objective_not_set(ocp) ? "X" : "V", isempty(constraints(ocp)) ? "X" : "V", ) println("") h1 = Highlighter((data, i, j) -> data[i, j] == "X", bold = true, foreground = :red) h2 = Highlighter((data, i, j) -> data[i, j] == "V", bold = true, foreground = :green) pretty_table( io, data; tf = tf_unicode_rounded, header = header, header_crayon = crayon"yellow", crop = :none, highlighters = (h1, h2), alignment = :c, compact_printing = true, ) nothing end function Base.show_default(io::IO, ocp::OptimalControlModel) print(io, typeof(ocp)) #show(io, MIME("text/plain"), ocp) end # -------------------------------------------------------------------------------------------------- # solution # # we get an error when a solution is printed so I add this function # which has to be put in the package CTBase and has to be completed """ $(TYPEDSIGNATURES) Prints the solution. """ function Base.show(io::IO, ::MIME"text/plain", sol::OptimalControlSolution) print(io, typeof(sol)) end function Base.show_default(io::IO, sol::OptimalControlSolution) print(io, typeof(sol)) #show(io, MIME("text/plain"), sol) end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
14900
const ModelRepl = Vector{Expr} @with_kw mutable struct CTRepl model::ModelRepl = ModelRepl() ocp_name::Symbol = gensym(:ocp) sol_name::Symbol = gensym(:sol) debug::Bool = false end @with_kw mutable struct HistoryRepl index::Int = 0 ct_repl_datas_data::Vector{CTRepl} = Vector{CTRepl}() end # ct_repl_is_set::Bool = false ct_repl_data::CTRepl = CTRepl() ct_repl_history::HistoryRepl = HistoryRepl(0, Vector{ModelRepl}()) """ $(TYPEDSIGNATURES) Update the model adding the expression e. It must be public since in the ct repl, this function is quoted each time an expression is parsed and is valid. """ function ct_repl_update_model(e::Expr) ct_repl_data.debug && (println("debug> expression to add: ", e)) # update model __update!(ct_repl_data.model, e) ct_repl_data.debug && (println("debug> expression valid, model updated.")) # add ct_repl_data to ct_repl_history __add!(ct_repl_history, ct_repl_data) # return nothing end """ $(TYPEDSIGNATURES) Create a ct REPL. """ function ct_repl(; debug = false, verbose = false) global ct_repl_is_set global ct_repl_data global ct_repl_history if !ct_repl_is_set # ct_repl_is_set = true # ct_repl_data.debug = debug # # advice to start by setting the name of the ocp and the solution # println("\nType > to enter into ct repl.\n") # println("For a start, you can set the names of the optimal control problem and its solution.") # println("In ct repl, type:\n") # println(" ct> NAME=(ocp, sol)") # add initial ct_repl_data to ct_repl_history __add!(ct_repl_history, ct_repl_data) # text invalid txt_invalid = "\nInvalid expression.\n\nType HELP to see the list of commands or enter a " * "valid expression to update the model." function parse_to_expr(s::AbstractString) # remove spaces from s at the beginning and at the end s = strip(s) # check if it is a comment startswith(s, "#") && return nothing # parse string e = Meta.parse(s) # ct_repl_data.debug && println("\ndebug> parsing string: ", s) ct_repl_data.debug && println("debug> expression parsed: ", e) ct_repl_data.debug && println("debug> expression type: ", typeof(e)) ct_repl_data.debug && println("debug> dump of expression: ", dump(e)) # test if e is a command @match e begin :($c = $a) => begin command = __transform_to_command(c) ct_repl_data.debug && println("debug> command: ", command, " and argument: ", a) command ∈ keys(COMMANDS_ACTIONS) && (return COMMANDS_ACTIONS[command](ct_repl_data, a, ct_repl_history)) end :($c) => begin command = __transform_to_command(c) ct_repl_data.debug && println("debug> command: ", command) command ∈ keys(COMMANDS_ACTIONS) && (return COMMANDS_ACTIONS[command](ct_repl_data, ct_repl_history)) end _ => nothing end # check if s finishes with a ";". If yes then remove it and return nothing at the end return_nothing = endswith(s, ";") ? true : false return_nothing && (s = s[1:(end - 1)]) e = Meta.parse(s) # return_nothing && ct_repl_data.debug && println("\ndebug> new parsing string: ", s) return_nothing && ct_repl_data.debug && println("debug> new expression parsed: ", e) if e isa Expr # ocp_q_for_test = __quote_anonym_ocp(ct_repl_data, e) # test if code is valid: if not, an exception is thrown ocp_q = __quote_ocp(ct_repl_data, e) # to update the model if needed ee = QuoteNode(e) # ct_repl_data.debug && (println("debug> try to add expression: ", e)) q = quote try $ocp_q_for_test # test if the expression is valid catch ex $(ct_repl_data.debug) && (println("debug> exception thrown: ", ex)) println($txt_invalid) return end # test is ok $(ct_repl_data.debug) && (println("debug> eval ocp quote ok ")) $(ct_repl_data.debug) && (println("debug> expr to add ", $ee)) # ---------------------------------------------------------------- # keep coherence between model and ocp variable $ocp_q # define the ocp ct_repl_update_model($ee) # add the expression in the model # ---------------------------------------------------------------- $return_nothing ? nothing : begin println("\n", string($ct_repl_data.ocp_name)) $(ct_repl_data.ocp_name) end end return q else println(txt_invalid) return nothing end end # parse_to_expr # makerepl command initrepl( parse_to_expr, prompt_text = "ct> ", prompt_color = :magenta, start_key = '>', mode_name = "ct_mode", valid_input_checker = complete_julia, startup_text = false, ) return nothing else if verbose println("ct repl is already set.") end end end # ---------------------------------------------------------------- # utils functions # ---------------------------------------------------------------- function NAME_ACTION_FUNCTION(ct_repl_data::CTRepl, ct_repl_history::HistoryRepl) println("") println("Optimal control problem name: ", ct_repl_data.ocp_name) println("Solution name: ", ct_repl_data.sol_name) end function NAME_ACTION_FUNCTION( ct_repl_data::CTRepl, name::Union{Symbol, Expr}, ct_repl_history::HistoryRepl, ) ocp_name = ct_repl_data.ocp_name sol_name = ct_repl_data.sol_name if isa(name, Symbol) name = (name, Symbol(string(name, "_sol"))) elseif isa(name, Expr) name = (name.args[1], name.args[2]) else println( "\nname error\n\nType HELP to see the list of commands or enter a valid expression to update the model.", ) return nothing end ct_repl_data.ocp_name = name[1] ct_repl_data.sol_name = name[2] ct_repl_data.debug && println("debug> ocp name: ", ct_repl_data.ocp_name) ct_repl_data.debug && println("debug> sol name: ", ct_repl_data.sol_name) __add!(ct_repl_history, ct_repl_data) # update ct_repl_history qo1 = ct_repl_data.ocp_name β‰  ocp_name ? :($(ct_repl_data.ocp_name) = "no optimal control") : :() qs1 = ct_repl_data.sol_name β‰  sol_name ? :($(ct_repl_data.sol_name) = "no solution") : :() qo2 = ct_repl_data.ocp_name β‰  ocp_name ? :($(ct_repl_data.ocp_name) = $(ocp_name)) : :() qs2 = ct_repl_data.sol_name β‰  sol_name ? :($(ct_repl_data.sol_name) = $(sol_name)) : :() name_q = ( quote $(qo1) $(qs1) try $(qo2) $(qs2) nothing catch e nothing end end ) ct_repl_data.debug && println("debug> new name quote: ", name_q) return name_q end # dict of actions associated to ct repl commands COMMANDS_ACTIONS = Dict{Symbol, Function}( :SHOW => (ct_repl_data::CTRepl, ct_repl_history::HistoryRepl) -> begin q = quote println("\n", string($ct_repl_data.ocp_name)) $(ct_repl_data.ocp_name) end return q end, :SOLVE => (ct_repl_data::CTRepl, ct_repl_history::HistoryRepl) -> begin return __quote_solve(ct_repl_data) end, :PLOT => (ct_repl_data::CTRepl, ct_repl_history::HistoryRepl) -> begin return __quote_plot(ct_repl_data) end, :DEBUG => (ct_repl_data::CTRepl, ct_repl_history::HistoryRepl) -> begin ct_repl_data.debug = !ct_repl_data.debug println("\n debug mode: " * (ct_repl_data.debug ? "on" : "off")) __add!(ct_repl_history, ct_repl_data) # update ct_repl_history return nothing end, :NAME => NAME_ACTION_FUNCTION, :UNDO => (ct_repl_data::CTRepl, ct_repl_history::HistoryRepl) -> begin ct_repl_data_ = __undo!(ct_repl_history) __copy!(ct_repl_data, ct_repl_data_) ocp_q = __quote_ocp(ct_repl_data) q = quote $ocp_q nothing end return q end, :REDO => (ct_repl_data::CTRepl, ct_repl_history::HistoryRepl) -> begin ct_repl_data_ = __redo!(ct_repl_history) __copy!(ct_repl_data, ct_repl_data_) ocp_q = __quote_ocp(ct_repl_data) q = quote $ocp_q nothing end return q end, :HELP => (ct_repl_data::CTRepl, ct_repl_history::HistoryRepl) -> begin l = 8 # 22 n = 6 println("\nSpecial commands to interact with the ct repl:\n") dict = sort(collect(COMMANDS_HELPS), by = x -> x[1]) for (k, v) ∈ dict m = length(string(k)) s = " " s *= string(k) * " "^(n - m) r = length(s) s *= " "^(l - r) printstyled(s, color = :magenta) printstyled(": ", v, "\n") end return nothing end, :REPL => (ct_repl_data::CTRepl, ct_repl_history::HistoryRepl) -> begin return :($ct_repl_data) end, :CLEAR => (ct_repl_data::CTRepl, ct_repl_history::HistoryRepl) -> begin ct_repl_data.model = ModelRepl() __add!(ct_repl_history, ct_repl_data) # update ct_repl_history ocp_q = __quote_ocp(ct_repl_data) q = quote $ocp_q nothing end return q end, ) # dict of help messages associated to ct repl commands COMMANDS_HELPS = Dict{Symbol, String}( :SOLVE => "solve the optimal control problem", :PLOT => "plot the solution", #:DEBUG => "toggle debug mode", :NAME => "print the name of the optimal control problem and the solution. To set them: \n\n" * " ct> NAME=ocp\n" * " ct> NAME=(ocp, sol)\n", :UNDO => "undo last command", :REDO => "redo last command", :HELP => "help", #:REPL => "return the current ct REPL", :SHOW => "show the optimal control problem", :CLEAR => "clear the optimal control problem", ) # non existing command __non_existing_command() = :non_existing_command # transform to a command __transform_to_command(c::Symbol)::Symbol = c __transform_to_command(e::Expr)::Symbol = __non_existing_command() # get code from model function __code(model::ModelRepl)::Expr return Expr(:block, model...) end # get code from model and an extra expression function __code(model::ModelRepl, e::Expr) model_ = deepcopy(model) # copy model __update!(model_, e) # update model_ return __code(model_) # get code end function __update!(model::ModelRepl, e::Expr) push!(model, e) end # make @def ocp quote function __quote_ocp(ct_repl_data::CTRepl) code = __code(ct_repl_data.model) ocp_q = quote @def $(ct_repl_data.ocp_name) $(code) end ct_repl_data.debug && println("debug> code: ", code) ct_repl_data.debug && println("debug> quote code: ", ocp_q) return ocp_q end function __quote_ocp(ct_repl_data::CTRepl, e::Expr) code = __code(ct_repl_data.model, e) ocp_q = quote @def $(ct_repl_data.ocp_name) $(code) end ct_repl_data.debug && println("debug> code: ", code) ct_repl_data.debug && println("debug> quote code: ", ocp_q) return ocp_q end # get ocp quote function __quote_anonym_ocp(ct_repl_data::CTRepl, e::Expr) code = __code(ct_repl_data.model, e) ocp = gensym() ocp_q = quote @def $ocp $code end ct_repl_data.debug && println("debug> code: ", code) ct_repl_data.debug && println("debug> quote code: ", ocp_q) return ocp_q end # quote solve: todo: update when using real solver function __quote_solve(ct_repl_data::CTRepl) solve_q = ( quote $(ct_repl_data.sol_name) = solve($(ct_repl_data.ocp_name)) end ) ct_repl_data.debug && println("debug> quote solve: ", solve_q) return solve_q end # quote plot: todo: update when handle correctly solution function __quote_plot(ct_repl_data::CTRepl) plot_q = quote if @isdefined($(ct_repl_data.sol_name)) plot($(ct_repl_data.sol_name), size = (600, 500)) else println("\nNo solution available.") end end ct_repl_data.debug && println("debug> quote plot: ", plot_q) return plot_q end # add model to ct_repl_history function __add!(ct_repl_history::HistoryRepl, ct_repl_data::CTRepl) push!(ct_repl_history.ct_repl_datas_data, deepcopy(ct_repl_data)) ct_repl_history.index += 1 end # go to previous model in ct_repl_history function __undo!(ct_repl_history::HistoryRepl) ct_repl_history.index > 1 && (ct_repl_history.index -= 1) return ct_repl_history.ct_repl_datas_data[ct_repl_history.index] end # go to next model in ct_repl_history function __redo!(ct_repl_history::HistoryRepl) ct_repl_history.index < length(ct_repl_history.ct_repl_datas_data) && (ct_repl_history.index += 1) return ct_repl_history.ct_repl_datas_data[ct_repl_history.index] end # copy a ct_repl_data function __copy!(ct_repl_data::CTRepl, ct_repl_data_to_copy::CTRepl) ct_repl_data.model = deepcopy(ct_repl_data_to_copy.model) ct_repl_data.ocp_name = ct_repl_data_to_copy.ocp_name ct_repl_data.sol_name = ct_repl_data_to_copy.sol_name ct_repl_data.debug = ct_repl_data_to_copy.debug end function Base.show(io::IO, ::MIME"text/plain", ct_repl_data::CTRepl) print(io, "\n") println(io, "ct> ") println(io, "model: ", ct_repl_data.model) println(io, "ocp_name: ", ct_repl_data.ocp_name) println(io, "sol_name: ", ct_repl_data.sol_name) println(io, "debug: ", ct_repl_data.debug) end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
36584
# -------------------------------------------------------------------------------------------------- # functions # """ $(TYPEDEF) Abstract type for functions. """ abstract type AbstractCTFunction <: Function end """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) The default value for `variable_dependence` is `Fixed`. ## Constructor The constructor ```BoundaryConstraint``` returns a ```BoundaryConstraint``` of a function. The function must take 2 or 3 arguments `(x0, xf)` or `(x0, xf, v)`, if the function is variable, it must be specified. Dependencies are specified with a boolean, `variable`, `false` by default or with a `DataType`, `NonFixed/Fixed`, `Fixed` by default. ## *Examples* ```@example julia> B = BoundaryConstraint((x0, xf) -> [xf[2]-x0[1], 2xf[1]+x0[2]^2]) julia> B = BoundaryConstraint((x0, xf, v) -> [v[3]+xf[2]-x0[1], v[1]-v[2]+2xf[1]+x0[2]^2], variable=true) julia> B = BoundaryConstraint((x0, xf, v) -> [v[3]+xf[2]-x0[1], v[1]-v[2]+2xf[1]+x0[2]^2], NonFixed) ``` !!! warning When the state is of dimension 1, consider `x0` and `xf` as a scalar. When the constraint is dimension 1, return a scalar. ## Call The call returns the evaluation of the `BoundaryConstraint` for given values. If a variable is given for a non variable dependent boundary constraint, it will be ignored. ## *Examples* ```@example julia> B = BoundaryConstraint((x0, xf) -> [xf[2]-x0[1], 2xf[1]+x0[2]^2]) julia> B([0, 0], [1, 1]) [1, 2] julia> B = BoundaryConstraint((x0, xf) -> [xf[2]-x0[1], 2xf[1]+x0[2]^2]) julia> B([0, 0], [1, 1],Real[]) [1, 2] julia> B = BoundaryConstraint((x0, xf, v) -> [v[3]+xf[2]-x0[1], v[1]-v[2]+2xf[1]+x0[2]^2], variable=true) julia> B([0, 0], [1, 1], [1, 2, 3]) [4, 1] ``` """ struct BoundaryConstraint{variable_dependence} f::Function end struct BoundaryConstraint!{variable_dependence} f!::Function end """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) The default value for `variable_dependence` is `Fixed`. ## Constructor The constructor ```Mayer``` returns a ```Mayer``` cost of a function. The function must take 2 or 3 arguments `(x0, xf)` or `(x0, xf, v)`, if the function is variable, it must be specified. Dependencies are specified with a boolean, `variable`, `false` by default or with a `DataType`, `NonFixed/Fixed`, `Fixed` by default. ## *Examples* ```@example julia> G = Mayer((x0, xf) -> xf[2]-x0[1]) julia> G = Mayer((x0, xf, v) -> v[3]+xf[2]-x0[1], variable=true) julia> G = Mayer((x0, xf, v) -> v[3]+xf[2]-x0[1], NonFixed) ``` !!! warning When the state is of dimension 1, consider `x0` and `xf` as a scalar. ## Call The call returns the evaluation of the `Mayer` cost for given values. If a variable is given for a non variable dependent Mayer cost, it will be ignored. ## *Examples* ```@example julia> G = Mayer((x0, xf) -> xf[2]-x0[1]) julia> G([0, 0], [1, 1]) 1 julia> G = Mayer((x0, xf) -> xf[2]-x0[1]) julia> G([0, 0], [1, 1],Real[]) 1 julia> G = Mayer((x0, xf, v) -> v[3]+xf[2]-x0[1], variable=true) julia> G([0, 0], [1, 1], [1, 2, 3]) 4 ``` """ struct Mayer{variable_dependence} f::Function end struct Mayer!{variable_dependence} f!::Function end """ $(TYPEDEF) Abstract type for hamiltonians. """ abstract type AbstractHamiltonian{time_dependence, variable_dependence} end """ $(TYPEDEF) Abstract type for vector fields. """ abstract type AbstractVectorField{time_dependence, variable_dependence} end """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) The default values for `time_dependence` and `variable_dependence` are `Autonomous` and `Fixed` respectively. ## Constructor The constructor ```Hamiltonian``` returns a ```Hamiltonian``` of a function. The function must take 2 to 4 arguments, `(x, p)` to `(t, x, p, v)`, if the function is variable or non autonomous, it must be specified. Dependencies are specified either with : - booleans, `autonomous` and `variable`, respectively `true` and `false` by default - `DataType`, `Autonomous`/`NonAutonomous` and `NonFixed`/`Fixed`, respectively `Autonomous` and `Fixed` by default. ## *Examples* ```@example julia> Hamiltonian((x, p) -> x + p, Int64) IncorrectArgument julia> Hamiltonian((x, p) -> x + p, Int64) IncorrectArgument julia> H = Hamiltonian((x, p) -> x[1]^2+2p[2]) julia> H = Hamiltonian((t, x, p, v) -> [t+x[1]^2+2p[2]+v[3]], autonomous=false, variable=true) julia> H = Hamiltonian((t, x, p, v) -> [t+x[1]^2+2p[2]+v[3]], NonAutonomous, NonFixed) ``` !!! warning When the state and costate are of dimension 1, consider `x` and `p` as scalars. ## Call The call returns the evaluation of the `Hamiltonian` for given values. ## *Examples* ```@example julia> H = Hamiltonian((x, p) -> [x[1]^2+2p[2]]) # autonomous=true, variable=false julia> H([1, 0], [0, 1]) MethodError # H must return a scalar julia> H = Hamiltonian((x, p) -> x[1]^2+2p[2]) julia> H([1, 0], [0, 1]) 3 julia> t = 1 julia> v = Real[] julia> H(t, [1, 0], [0, 1]) MethodError julia> H([1, 0], [0, 1], v) MethodError julia> H(t, [1, 0], [0, 1], v) 3 julia> H = Hamiltonian((x, p, v) -> x[1]^2+2p[2]+v[3], variable=true) julia> H([1, 0], [0, 1], [1, 2, 3]) 6 julia> H(t, [1, 0], [0, 1], [1, 2, 3]) 6 julia> H = Hamiltonian((t, x, p) -> t+x[1]^2+2p[2], autonomous=false) julia> H(1, [1, 0], [0, 1]) 4 julia> H(1, [1, 0], [0, 1], v) 4 julia> H = Hamiltonian((t, x, p, v) -> t+x[1]^2+2p[2]+v[3], autonomous=false, variable=true) julia> H(1, [1, 0], [0, 1], [1, 2, 3]) 7 ``` """ struct Hamiltonian{time_dependence, variable_dependence} <: AbstractHamiltonian{time_dependence, variable_dependence} f::Function end """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) The default values for `time_dependence` and `variable_dependence` are `Autonomous` and `Fixed` respectively. ## Constructor The constructor ```VectorField``` returns a ```VectorField``` of a function. The function must take 1 to 3 arguments, `x` to `(t, x, v)`, if the function is variable or non autonomous, it must be specified. Dependencies are specified either with : - booleans, `autonomous` and `variable`, respectively `true` and `false` by default - `DataType`, `Autonomous`/`NonAutonomous` and `NonFixed`/`Fixed`, respectively `Autonomous` and `Fixed` by default. ## *Examples* ```@example julia> VectorField(x -> [x[1]^2, 2x[2]], Int64) IncorrectArgument julia> VectorField(x -> [x[1]^2, 2x[2]], Int64) IncorrectArgument julia> V = VectorField(x -> [x[1]^2, 2x[2]]) # autonomous=true, variable=false julia> V = VectorField((x, v) -> [x[1]^2, 2x[2]+v[3]], variable=true) julia> V = VectorField((t, x) -> [t+x[1]^2, 2x[2]], autonomous=false) julia> V = VectorField((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], autonomous=false, variable=true) julia> V = VectorField((x, v) -> [x[1]^2, 2x[2]+v[3]], NonFixed) julia> V = VectorField((t, x) -> [t+x[1]^2, 2x[2]], NonAutonomous) julia> V = VectorField((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], NonAutonomous, NonFixed) ``` !!! warning When the state is of dimension 1, consider `x` as a scalar. ## Call The call returns the evaluation of the `VectorField` for given values. ## *Examples* ```@example julia> V = VectorField(x -> [x[1]^2, 2x[2]]) # autonomous=true, variable=false julia> V([1, -1]) [1, -2] julia> t = 1 julia> v = Real[] julia> V(t, [1, -1]) MethodError julia> V([1, -1], v) MethodError julia> V(t, [1, -1], v) [1, -2] julia> V = VectorField((x, v) -> [x[1]^2, 2x[2]+v[3]], variable=true) julia> V([1, -1], [1, 2, 3]) [1, 1] julia> V(t, [1, -1], [1, 2, 3]) [1, 1] julia> V = VectorField((t, x) -> [t+x[1]^2, 2x[2]], autonomous=false) julia> V(1, [1, -1]) [2, -2] julia> V(1, [1, -1], v) [2, -2] julia> V = VectorField((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], autonomous=false, variable=true) julia> V(1, [1, -1], [1, 2, 3]) [2, 1] ``` """ struct VectorField{time_dependence, variable_dependence} <: AbstractVectorField{time_dependence, variable_dependence} f::Function end """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) The default values for `time_dependence` and `variable_dependence` are `Autonomous` and `Fixed` respectively. ## Constructor The constructor ```HamiltonianVectorField``` returns a ```HamiltonianVectorField``` of a function. The function must take 2 to 4 arguments, `(x, p)` to `(t, x, p, v)`, if the function is variable or non autonomous, it must be specified. Dependencies are specified either with : - booleans, `autonomous` and `variable`, respectively `true` and `false` by default - `DataType`, `Autonomous`/`NonAutonomous` and `NonFixed`/`Fixed`, respectively `Autonomous` and `Fixed` by default. ## *Examples* ```@example julia> HamiltonianVectorField((x, p) -> [x[1]^2+2p[2], x[2]-3p[2]^2], Int64) IncorrectArgument julia> HamiltonianVectorField((x, p) -> [x[1]^2+2p[2], x[2]-3p[2]^2], Int64) IncorrectArgument julia> Hv = HamiltonianVectorField((x, p) -> [x[1]^2+2p[2], x[2]-3p[2]^2]) # autonomous=true, variable=false julia> Hv = HamiltonianVectorField((x, p, v) -> [x[1]^2+2p[2]+v[3], x[2]-3p[2]^2+v[4]], variable=true) julia> Hv = HamiltonianVectorField((t, x, p) -> [t+x[1]^2+2p[2], x[2]-3p[2]^2], autonomous=false) julia> Hv = HamiltonianVectorField((t, x, p, v) -> [t+x[1]^2+2p[2]+v[3], x[2]-3p[2]^2+v[4]], autonomous=false, variable=true) julia> Hv = HamiltonianVectorField((x, p, v) -> [x[1]^2+2p[2]+v[3], x[2]-3p[2]^2+v[4]], NonFixed) julia> Hv = HamiltonianVectorField((t, x, p) -> [t+x[1]^2+2p[2], x[2]-3p[2]^2], NonAutonomous) julia> Hv = HamiltonianVectorField((t, x, p, v) -> [t+x[1]^2+2p[2]+v[3], x[2]-3p[2]^2+v[4]], NonAutonomous, NonFixed) ``` !!! warning When the state and costate are of dimension 1, consider `x` and `p` as scalars. ## Call The call returns the evaluation of the `HamiltonianVectorField` for given values. ## *Examples* ```@example julia> Hv = HamiltonianVectorField((x, p) -> [x[1]^2+2p[2], x[2]-3p[2]^2]) # autonomous=true, variable=false julia> Hv([1, 0], [0, 1]) [3, -3] julia> t = 1 julia> v = Real[] julia> Hv(t, [1, 0], [0, 1]) MethodError julia> Hv([1, 0], [0, 1], v) MethodError julia> Hv(t, [1, 0], [0, 1], v) [3, -3] julia> Hv = HamiltonianVectorField((x, p, v) -> [x[1]^2+2p[2]+v[3], x[2]-3p[2]^2+v[4]], variable=true) julia> Hv([1, 0], [0, 1], [1, 2, 3, 4]) [6, -3] julia> Hv(t, [1, 0], [0, 1], [1, 2, 3, 4]) [6, -3] julia> Hv = HamiltonianVectorField((t, x, p) -> [t+x[1]^2+2p[2], x[2]-3p[2]^2], autonomous=false) julia> Hv(1, [1, 0], [0, 1]) [4, -3] julia> Hv(1, [1, 0], [0, 1], v) [4, -3] julia> Hv = HamiltonianVectorField((t, x, p, v) -> [t+x[1]^2+2p[2]+v[3], x[2]-3p[2]^2+v[4]], autonomous=false, variable=true) julia> Hv(1, [1, 0], [0, 1], [1, 2, 3, 4]) [7, -3] ``` """ struct HamiltonianVectorField{time_dependence, variable_dependence} <: AbstractVectorField{time_dependence, variable_dependence} f::Function end """ $(TYPEDEF) **Lifts** $(TYPEDFIELDS) The values for `time_dependence` and `variable_dependence` are deternimed by the values of those for the VectorField. ## Constructor The constructor ```HamiltonianLift``` returns a ```HamiltonianLift``` of a `VectorField`. ## *Examples* ```@example julia> H = HamiltonianLift(VectorField(x -> [x[1]^2, 2x[2]])) julia> H = HamiltonianLift(VectorField((x, v) -> [x[1]^2, 2x[2]+v[3]], variable=true)) julia> H = HamiltonianLift(VectorField((t, x) -> [t+x[1]^2, 2x[2]], autonomous=false)) julia> H = HamiltonianLift(VectorField((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], autonomous=false, variable=true)) julia> H = HamiltonianLift(VectorField(x -> [x[1]^2, 2x[2]])) julia> H = HamiltonianLift(VectorField((x, v) -> [x[1]^2, 2x[2]+v[3]], NonFixed)) julia> H = HamiltonianLift(VectorField((t, x) -> [t+x[1]^2, 2x[2]], NonAutonomous)) julia> H = HamiltonianLift(VectorField((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], NonAutonomous, NonFixed)) ``` !!! warning When the state and costate are of dimension 1, consider `x` and `p` as scalars. ## Call The call returns the evaluation of the `HamiltonianLift` for given values. ## *Examples* ```@example julia> H = HamiltonianLift(VectorField(x -> [x[1]^2, 2x[2]])) julia> H([1, 2], [1, 1]) 5 julia> t = 1 julia> v = Real[] julia> H(t, [1, 0], [0, 1]) MethodError julia> H([1, 0], [0, 1], v) MethodError julia> H(t, [1, 0], [0, 1], v) 5 julia> H = HamiltonianLift(VectorField((x, v) -> [x[1]^2, 2x[2]+v[3]], variable=true)) julia> H([1, 0], [0, 1], [1, 2, 3]) 3 julia> H(t, [1, 0], [0, 1], [1, 2, 3]) 3 julia> H = HamiltonianLift(VectorField((t, x) -> [t+x[1]^2, 2x[2]], autonomous=false)) julia> H(1, [1, 2], [1, 1]) 6 julia> H(1, [1, 0], [0, 1], v) 6 julia> H = HamiltonianLift(VectorField((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], autonomous=false, variable=true)) julia> H(1, [1, 0], [0, 1], [1, 2, 3]) 3 ``` Alternatively, it is possible to construct the `HamiltonianLift` from a `Function` being the `VectorField`. ```@example julia> HL1 = HamiltonianLift((x, v) -> [x[1]^2,x[2]^2+v], autonomous=true, variable=true) julia> HL2 = HamiltonianLift(VectorField((x, v) -> [x[1]^2,x[2]^2+v], autonomous=true, variable=true)) julia> HL1([1, 0], [0, 1], 1) == HL2([1, 0], [0, 1], 1) true ``` """ struct HamiltonianLift{time_dependence, variable_dependence} <: AbstractHamiltonian{time_dependence, variable_dependence} X::VectorField function HamiltonianLift( X::VectorField{time_dependence, variable_dependence}, ) where {time_dependence, variable_dependence} new{time_dependence, variable_dependence}(X) end end """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) The default value for `time_dependence` and `variable_dependence` are `Autonomous` and `Fixed` respectively. ## Constructor The constructor ```Lagrange``` returns a ```Lagrange``` cost of a function. The function must take 2 to 4 arguments, `(x, u)` to `(t, x, u, v)`, if the function is variable or non autonomous, it must be specified. Dependencies are specified either with : - booleans, `autonomous` and `variable`, respectively `true` and `false` by default - `DataType`, `Autonomous`/`NonAutonomous` and `NonFixed`/`Fixed`, respectively `Autonomous` and `Fixed` by default. ## *Examples* ```@example julia> Lagrange((x, u) -> 2x[2]-u[1]^2, Int64) IncorrectArgument julia> Lagrange((x, u) -> 2x[2]-u[1]^2, Int64) IncorrectArgument julia> L = Lagrange((x, u) -> [2x[2]-u[1]^2], autonomous=true, variable=false) julia> L = Lagrange((x, u) -> 2x[2]-u[1]^2, autonomous=true, variable=false) julia> L = Lagrange((x, u, v) -> 2x[2]-u[1]^2+v[3], autonomous=true, variable=true) julia> L = Lagrange((t, x, u) -> t+2x[2]-u[1]^2, autonomous=false, variable=false) julia> L = Lagrange((t, x, u, v) -> t+2x[2]-u[1]^2+v[3], autonomous=false, variable=true) julia> L = Lagrange((x, u) -> [2x[2]-u[1]^2], Autonomous, Fixed) julia> L = Lagrange((x, u) -> 2x[2]-u[1]^2, Autonomous, Fixed) julia> L = Lagrange((x, u, v) -> 2x[2]-u[1]^2+v[3], Autonomous, NonFixed) julia> L = Lagrange((t, x, u) -> t+2x[2]-u[1]^2, autonomous=false, Fixed) julia> L = Lagrange((t, x, u, v) -> t+2x[2]-u[1]^2+v[3], autonomous=false, NonFixed) ``` !!! warning When the state is of dimension 1, consider `x` as a scalar. Same for the control. ## Call The call returns the evaluation of the `Lagrange` cost for given values. ## *Examples* ```@example julia> L = Lagrange((x, u) -> [2x[2]-u[1]^2], autonomous=true, variable=false) julia> L([1, 0], [1]) MethodError julia> L = Lagrange((x, u) -> 2x[2]-u[1]^2, autonomous=true, variable=false) julia> L([1, 0], [1]) -1 julia> t = 1 julia> v = Real[] julia> L(t, [1, 0], [1]) MethodError julia> L([1, 0], [1], v) MethodError julia> L(t, [1, 0], [1], v) -1 julia> L = Lagrange((x, u, v) -> 2x[2]-u[1]^2+v[3], autonomous=true, variable=true) julia> L([1, 0], [1], [1, 2, 3]) 2 julia> L(t, [1, 0], [1], [1, 2, 3]) 2 julia> L = Lagrange((t, x, u) -> t+2x[2]-u[1]^2, autonomous=false, variable=false) julia> L(1, [1, 0], [1]) 0 julia> L(1, [1, 0], [1], v) 0 julia> L = Lagrange((t, x, u, v) -> t+2x[2]-u[1]^2+v[3], autonomous=false, variable=true) julia> L(1, [1, 0], [1], [1, 2, 3]) 3 ``` """ struct Lagrange{time_dependence, variable_dependence} f::Function end struct Lagrange!{time_dependence, variable_dependence} f!::Function end """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) The default value for `time_dependence` and `variable_dependence` are `Autonomous` and `Fixed` respectively. ## Constructor The constructor ```Dynamics``` returns a ```Dynamics``` of a function. The function must take 2 to 4 arguments, `(x, u)` to `(t, x, u, v)`, if the function is variable or non autonomous, it must be specified. Dependencies are specified either with : - booleans, `autonomous` and `variable`, respectively `true` and `false` by default - `DataType`, `Autonomous`/`NonAutonomous` and `NonFixed`/`Fixed`, respectively `Autonomous` and `Fixed` by default. ## *Examples* ```@example julia> Dynamics((x, u) -> [2x[2]-u^2, x[1]], Int64) IncorrectArgument julia> Dynamics((x, u) -> [2x[2]-u^2, x[1]], Int64) IncorrectArgument julia> D = Dynamics((x, u) -> [2x[2]-u^2, x[1]], Autonomous, Fixed) julia> D = Dynamics((x, u, v) -> [2x[2]-u^2+v[3], x[1]], Autonomous, NonFixed) julia> D = Dynamics((t, x, u) -> [t+2x[2]-u^2, x[1]], NonAutonomous, Fixed) julia> D = Dynamics((t, x, u, v) -> [t+2x[2]-u^2+v[3], x[1]], NonAutonomous, NonFixed) julia> D = Dynamics((x, u) -> [2x[2]-u^2, x[1]], autonomous=true, variable=false) julia> D = Dynamics((x, u, v) -> [2x[2]-u^2+v[3], x[1]], autonomous=true, variable=true) julia> D = Dynamics((t, x, u) -> [t+2x[2]-u^2, x[1]], autonomous=false, variable=false) julia> D = Dynamics((t, x, u, v) -> [t+2x[2]-u^2+v[3], x[1]], autonomous=false, variable=true) ``` !!! warning When the state is of dimension 1, consider `x` as a scalar. Same for the control. ## Call The call returns the evaluation of the `Dynamics` for given values. ## *Examples* ```@example julia> D = Dynamics((x, u) -> [2x[2]-u^2, x[1]], autonomous=true, variable=false) julia> D([1, 0], 1) [-1, 1] julia> t = 1 julia> v = Real[] julia> D(t, [1, 0], 1, v) [-1, 1] julia> D = Dynamics((x, u, v) -> [2x[2]-u^2+v[3], x[1]], autonomous=true, variable=true) julia> D([1, 0], 1, [1, 2, 3]) [2, 1] julia> D(t, [1, 0], 1, [1, 2, 3]) [2, 1] julia> D = Dynamics((t, x, u) -> [t+2x[2]-u^2, x[1]], autonomous=false, variable=false) julia> D(1, [1, 0], 1) [0, 1] julia> D(1, [1, 0], 1, v) [0, 1] julia> D = Dynamics((t, x, u, v) -> [t+2x[2]-u^2+v[3], x[1]], autonomous=false, variable=true) julia> D(1, [1, 0], 1, [1, 2, 3]) [3, 1] ``` """ struct Dynamics{time_dependence, variable_dependence} f::Function end struct Dynamics!{time_dependence, variable_dependence} f!::Function end """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) Similar to `VectorField` in the usage, but the dimension of the output of the function `f` is arbitrary. The default values for `time_dependence` and `variable_dependence` are `Autonomous` and `Fixed` respectively. ## Constructor The constructor ```StateConstraint``` returns a ```StateConstraint``` of a function. The function must take 1 to 3 arguments, `x` to `(t, x, v)`, if the function is variable or non autonomous, it must be specified. Dependencies are specified either with : - booleans, `autonomous` and `variable`, respectively `true` and `false` by default - `DataType`, `Autonomous`/`NonAutonomous` and `NonFixed`/`Fixed`, respectively `Autonomous` and `Fixed` by default. ## *Examples* ```@example julia> StateConstraint(x -> [x[1]^2, 2x[2]], Int64) IncorrectArgument julia> StateConstraint(x -> [x[1]^2, 2x[2]], Int64) IncorrectArgument julia> S = StateConstraint(x -> [x[1]^2, 2x[2]], Autonomous, Fixed) julia> S = StateConstraint((x, v) -> [x[1]^2, 2x[2]+v[3]], Autonomous, NonFixed) julia> S = StateConstraint((t, x) -> [t+x[1]^2, 2x[2]], NonAutonomous, Fixed) julia> S = StateConstraint((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], NonAutonomous, NonFixed) julia> S = StateConstraint(x -> [x[1]^2, 2x[2]], autonomous=true, variable=false) julia> S = StateConstraint((x, v) -> [x[1]^2, 2x[2]+v[3]], autonomous=true, variable=true) julia> S = StateConstraint((t, x) -> [t+x[1]^2, 2x[2]], autonomous=false, variable=false) julia> S = StateConstraint((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], autonomous=false, variable=true) ``` !!! warning When the state is of dimension 1, consider `x` as a scalar. ## Call The call returns the evaluation of the `StateConstraint` for given values. ## *Examples* ```@example julia> StateConstraint(x -> [x[1]^2, 2x[2]], Int64) IncorrectArgument julia> StateConstraint(x -> [x[1]^2, 2x[2]], Int64) IncorrectArgument julia> S = StateConstraint(x -> [x[1]^2, 2x[2]], autonomous=true, variable=false) julia> S([1, -1]) [1, -2] julia> t = 1 julia> v = Real[] julia> S(t, [1, -1], v) [1, -2] julia> S = StateConstraint((x, v) -> [x[1]^2, 2x[2]+v[3]], autonomous=true, variable=true) julia> S([1, -1], [1, 2, 3]) [1, 1] julia> S(t, [1, -1], [1, 2, 3]) [1, 1] julia> S = StateConstraint((t, x) -> [t+x[1]^2, 2x[2]], autonomous=false, variable=false) julia> S(1, [1, -1]) [2, -2] julia> S(1, [1, -1], v) [2, -2] julia> S = StateConstraint((t, x, v) -> [t+x[1]^2, 2x[2]+v[3]], autonomous=false, variable=true) julia> S(1, [1, -1], [1, 2, 3]) [2, 1] ``` """ struct StateConstraint{time_dependence, variable_dependence} f::Function end struct StateConstraint!{time_dependence, variable_dependence} f!::Function end """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) Similar to `VectorField` in the usage, but the dimension of the output of the function `f` is arbitrary. The default values for `time_dependence` and `variable_dependence` are `Autonomous` and `Fixed` respectively. ## Constructor The constructor ```ControlConstraint``` returns a ```ControlConstraint``` of a function. The function must take 1 to 3 arguments, `u` to `(t, u, v)`, if the function is variable or non autonomous, it must be specified. Dependencies are specified either with : - booleans, `autonomous` and `variable`, respectively `true` and `false` by default - `DataType`, `Autonomous`/`NonAutonomous` and `NonFixed`/`Fixed`, respectively `Autonomous` and `Fixed` by default. ## *Examples* ```@example julia> IncorrectArgument ControlConstraint(u -> [u[1]^2, 2u[2]], Int64) julia> IncorrectArgument ControlConstraint(u -> [u[1]^2, 2u[2]], Int64) julia> C = ControlConstraint(u -> [u[1]^2, 2u[2]], Autonomous, Fixed) julia> C = ControlConstraint((u, v) -> [u[1]^2, 2u[2]+v[3]], Autonomous, NonFixed) julia> C = ControlConstraint((t, u) -> [t+u[1]^2, 2u[2]], NonAutonomous, Fixed) julia> C = ControlConstraint((t, u, v) -> [t+u[1]^2, 2u[2]+v[3]], NonAutonomous, NonFixed) julia> C = ControlConstraint(u -> [u[1]^2, 2u[2]], autonomous=true, variable=false) julia> C = ControlConstraint((u, v) -> [u[1]^2, 2u[2]+v[3]], autonomous=true, variable=true) julia> C = ControlConstraint((t, u) -> [t+u[1]^2, 2u[2]], autonomous=false, variable=false) julia> C = ControlConstraint((t, u, v) -> [t+u[1]^2, 2u[2]+v[3]], autonomous=false, variable=true) ``` !!! warning When the control is of dimension 1, consider `u` as a scalar. ## Call The call returns the evaluation of the `ControlConstraint` for given values. ## *Examples* ```@example julia> C = ControlConstraint(u -> [u[1]^2, 2u[2]], autonomous=true, variable=false) julia> C([1, -1]) [1, -2] julia> t = 1 julia> v = Real[] julia> C(t, [1, -1], v) [1, -2] julia> C = ControlConstraint((u, v) -> [u[1]^2, 2u[2]+v[3]], autonomous=true, variable=true) julia> C([1, -1], [1, 2, 3]) [1, 1] julia> C(t, [1, -1], [1, 2, 3]) [1, 1] julia> C = ControlConstraint((t, u) -> [t+u[1]^2, 2u[2]], autonomous=false, variable=false) julia> C(1, [1, -1]) [2, -2] julia> C(1, [1, -1], v) [2, -2] julia> C = ControlConstraint((t, u, v) -> [t+u[1]^2, 2u[2]+v[3]], autonomous=false, variable=true) julia> C(1, [1, -1], [1, 2, 3]) [2, 1] ``` """ struct ControlConstraint{time_dependence, variable_dependence} f::Function end struct ControlConstraint!{time_dependence, variable_dependence} f!::Function end """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) Similar to `Lagrange` in the usage, but the dimension of the output of the function `f` is arbitrary. The default value for `time_dependence` and `variable_dependence` are `Autonomous` and `Fixed` respectively. ## Constructor The constructor ```MixedConstraint``` returns a ```MixedConstraint``` of a function. The function must take 2 to 4 arguments, `(x, u)` to `(t, x, u, v)`, if the function is variable or non autonomous, it must be specified. Dependencies are specified either with : - booleans, `autonomous` and `variable`, respectively `true` and `false` by default - `DataType`, `Autonomous`/`NonAutonomous` and `NonFixed`/`Fixed`, respectively `Autonomous` and `Fixed` by default. ## *Examples* ```@example julia> MixedConstraint((x, u) -> [2x[2]-u^2, x[1]], Int64) IncorrectArgument julia> MixedConstraint((x, u) -> [2x[2]-u^2, x[1]], Int64) IncorrectArgument julia> M = MixedConstraint((x, u) -> [2x[2]-u^2, x[1]], Autonomous, Fixed) julia> M = MixedConstraint((x, u, v) -> [2x[2]-u^2+v[3], x[1]], Autonomous, NonFixed) julia> M = MixedConstraint((t, x, u) -> [t+2x[2]-u^2, x[1]], NonAutonomous, Fixed) julia> M = MixedConstraint((t, x, u, v) -> [t+2x[2]-u^2+v[3], x[1]], NonAutonomous, NonFixed) julia> M = MixedConstraint((x, u) -> [2x[2]-u^2, x[1]], autonomous=true, variable=false) julia> M = MixedConstraint((x, u, v) -> [2x[2]-u^2+v[3], x[1]], autonomous=true, variable=true) julia> M = MixedConstraint((t, x, u) -> [t+2x[2]-u^2, x[1]], autonomous=false, variable=false) julia> M = MixedConstraint((t, x, u, v) -> [t+2x[2]-u^2+v[3], x[1]], autonomous=false, variable=true) ``` !!! warning When the state is of dimension 1, consider `x` as a scalar. Same for the control. ## Call The call returns the evaluation of the `MixedConstraint` for given values. ## *Examples* ```@example julia> MixedConstraint((x, u) -> [2x[2]-u^2, x[1]], Int64) IncorrectArgument julia> MixedConstraint((x, u) -> [2x[2]-u^2, x[1]], Int64) IncorrectArgument julia> M = MixedConstraint((x, u) -> [2x[2]-u^2, x[1]], autonomous=true, variable=false) julia> M([1, 0], 1) [-1, 1] julia> t = 1 julia> v = Real[] julia> MethodError M(t, [1, 0], 1) julia> MethodError M([1, 0], 1, v) julia> M(t, [1, 0], 1, v) [-1, 1] julia> M = MixedConstraint((x, u, v) -> [2x[2]-u^2+v[3], x[1]], autonomous=true, variable=true) julia> M([1, 0], 1, [1, 2, 3]) [2, 1] julia> M(t, [1, 0], 1, [1, 2, 3]) [2, 1] julia> M = MixedConstraint((t, x, u) -> [t+2x[2]-u^2, x[1]], autonomous=false, variable=false) julia> M(1, [1, 0], 1) [0, 1] julia> M(1, [1, 0], 1, v) [0, 1] julia> M = MixedConstraint((t, x, u, v) -> [t+2x[2]-u^2+v[3], x[1]], autonomous=false, variable=true) julia> M(1, [1, 0], 1, [1, 2, 3]) [3, 1] ``` """ struct MixedConstraint{time_dependence, variable_dependence} f::Function end struct MixedConstraint!{time_dependence, variable_dependence} f!::Function end """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) The default values for `time_dependence` and `variable_dependence` are `Autonomous` and `Fixed` respectively. ## Constructor The constructor ```VariableConstraint``` returns a ```VariableConstraint``` of a function. The function must take 1 argument, `v`. ## *Examples* ```@example julia> V = VariableConstraint(v -> [v[1]^2, 2v[2]]) ``` !!! warning When the variable is of dimension 1, consider `v` as a scalar. ## Call The call returns the evaluation of the `VariableConstraint` for given values. ## *Examples* ```@example julia> V = VariableConstraint(v -> [v[1]^2, 2v[2]]) julia> V([1, -1]) [1, -2] ``` """ struct VariableConstraint f::Function end struct VariableConstraint! f!::Function end """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) Similar to `VectorField` in the usage, but the dimension of the output of the function `f` is arbitrary. The default values for `time_dependence` and `variable_dependence` are `Autonomous` and `Fixed` respectively. ## Constructor The constructor ```FeedbackControl``` returns a ```FeedbackControl``` of a function. The function must take 1 to 3 arguments, `x` to `(t, x, v)`, if the function is variable or non autonomous, it must be specified. Dependencies are specified either with : - booleans, `autonomous` and `variable`, respectively `true` and `false` by default - `DataType`, `Autonomous`/`NonAutonomous` and `NonFixed`/`Fixed`, respectively `Autonomous` and `Fixed` by default. ## *Examples* ```@example julia> FeedbackControl(x -> x[1]^2+2x[2], Int64) IncorrectArgument julia> FeedbackControl(x -> x[1]^2+2x[2], Int64) IncorrectArgument julia> u = FeedbackControl(x -> x[1]^2+2x[2], Autonomous, Fixed) julia> u = FeedbackControl((x, v) -> x[1]^2+2x[2]+v[3], Autonomous, NonFixed) julia> u = FeedbackControl((t, x) -> t+x[1]^2+2x[2], NonAutonomous, Fixed) julia> u = FeedbackControl((t, x, v) -> t+x[1]^2+2x[2]+v[3], NonAutonomous, NonFixed) julia> u = FeedbackControl(x -> x[1]^2+2x[2], autonomous=true, variable=false) julia> u = FeedbackControl((x, v) -> x[1]^2+2x[2]+v[3], autonomous=true, variable=true) julia> u = FeedbackControl((t, x) -> t+x[1]^2+2x[2], autonomous=false, variable=false) julia> u = FeedbackControl((t, x, v) -> t+x[1]^2+2x[2]+v[3], autonomous=false, variable=true) ``` !!! warning When the state is of dimension 1, consider `x` as a scalar. ## Call The call returns the evaluation of the `FeedbackControl` for given values. ## *Examples* ```@example julia> u = FeedbackControl(x -> x[1]^2+2x[2], autonomous=true, variable=false) julia> u([1, 0]) 1 julia> t = 1 julia> v = Real[] julia> u(t, [1, 0]) MethodError julia> u([1, 0], v) MethodError julia> u(t, [1, 0], v) 1 julia> u = FeedbackControl((x, v) -> x[1]^2+2x[2]+v[3], autonomous=true, variable=true) julia> u([1, 0], [1, 2, 3]) 4 julia> u(t, [1, 0], [1, 2, 3]) 4 julia> u = FeedbackControl((t, x) -> t+x[1]^2+2x[2], autonomous=false, variable=false) julia> u(1, [1, 0]) 2 julia> u(1, [1, 0], v) 2 julia> u = FeedbackControl((t, x, v) -> t+x[1]^2+2x[2]+v[3], autonomous=false, variable=true) julia> u(1, [1, 0], [1, 2, 3]) 5 ``` """ struct FeedbackControl{time_dependence, variable_dependence} f::Function end """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) Similar to `Hamiltonian` in the usage, but the dimension of the output of the function `f` is arbitrary. The default values for `time_dependence` and `variable_dependence` are `Autonomous` and `Fixed` respectively. ## Constructor The constructor ```ControlLaw``` returns a ```ControlLaw``` of a function. The function must take 2 to 4 arguments, `(x, p)` to `(t, x, p, v)`, if the function is variable or non autonomous, it must be specified. Dependencies are specified either with : - booleans, `autonomous` and `variable`, respectively `true` and `false` by default - `DataType`, `Autonomous`/`NonAutonomous` and `NonFixed`/`Fixed`, respectively `Autonomous` and `Fixed` by default. ## *Examples* ```@example julia> ControlLaw((x, p) -> x[1]^2+2p[2], Int64) IncorrectArgument julia> ControlLaw((x, p) -> x[1]^2+2p[2], Int64) IncorrectArgument julia> u = ControlLaw((x, p) -> x[1]^2+2p[2], Autonomous, Fixed) julia> u = ControlLaw((x, p, v) -> x[1]^2+2p[2]+v[3], Autonomous, NonFixed) julia> u = ControlLaw((t, x, p) -> t+x[1]^2+2p[2], NonAutonomous, Fixed) julia> u = ControlLaw((t, x, p, v) -> t+x[1]^2+2p[2]+v[3], NonAutonomous, NonFixed) julia> u = ControlLaw((x, p) -> x[1]^2+2p[2], autonomous=true, variable=false) julia> u = ControlLaw((x, p, v) -> x[1]^2+2p[2]+v[3], autonomous=true, variable=true) julia> u = ControlLaw((t, x, p) -> t+x[1]^2+2p[2], autonomous=false, variable=false) julia> u = ControlLaw((t, x, p, v) -> t+x[1]^2+2p[2]+v[3], autonomous=false, variable=true) ``` !!! warning When the state and costate are of dimension 1, consider `x` and `p` as scalars. ## Call The call returns the evaluation of the `ControlLaw` for given values. ## *Examples* ```@example julia> u = ControlLaw((x, p) -> x[1]^2+2p[2], autonomous=true, variable=false) julia> u([1, 0], [0, 1]) 3 julia> t = 1 julia> v = Real[] julia> u(t, [1, 0], [0, 1]) MethodError julia> u([1, 0], [0, 1], v) MethodError julia> u(t, [1, 0], [0, 1], v) 3 julia> u = ControlLaw((x, p, v) -> x[1]^2+2p[2]+v[3], autonomous=true, variable=true) julia> u([1, 0], [0, 1], [1, 2, 3]) 6 julia> u(t, [1, 0], [0, 1], [1, 2, 3]) 6 julia> u = ControlLaw((t, x, p) -> t+x[1]^2+2p[2], autonomous=false, variable=false) julia> u(1, [1, 0], [0, 1]) 4 julia> u(1, [1, 0], [0, 1], v) 4 julia> u = ControlLaw((t, x, p, v) -> t+x[1]^2+2p[2]+v[3], autonomous=false, variable=true) julia> u(1, [1, 0], [0, 1], [1, 2, 3]) 7 ``` """ struct ControlLaw{time_dependence, variable_dependence} f::Function end """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) Similar to `ControlLaw` in the usage. The default values for `time_dependence` and `variable_dependence` are `Autonomous` and `Fixed` respectively. ## Constructor The constructor ```Multiplier``` returns a ```Multiplier``` of a function. The function must take 2 to 4 arguments, `(x, p)` to `(t, x, p, v)`, if the function is variable or non autonomous, it must be specified. Dependencies are specified either with : - booleans, `autonomous` and `variable`, respectively `true` and `false` by default - `DataType`, `Autonomous`/`NonAutonomous` and `NonFixed`/`Fixed`, respectively `Autonomous` and `Fixed` by default. ## *Examples* ```@example julia> Multiplier((x, p) -> x[1]^2+2p[2], Int64) IncorrectArgument julia> Multiplier((x, p) -> x[1]^2+2p[2], Int64) IncorrectArgument julia> ΞΌ = Multiplier((x, p) -> x[1]^2+2p[2], Autonomous, Fixed) julia> ΞΌ = Multiplier((x, p, v) -> x[1]^2+2p[2]+v[3], Autonomous, NonFixed) julia> ΞΌ = Multiplier((t, x, p) -> t+x[1]^2+2p[2], NonAutonomous, Fixed) julia> ΞΌ = Multiplier((t, x, p, v) -> t+x[1]^2+2p[2]+v[3], NonAutonomous, NonFixed) julia> ΞΌ = Multiplier((x, p) -> x[1]^2+2p[2], autonomous=true, variable=false) julia> ΞΌ = Multiplier((x, p, v) -> x[1]^2+2p[2]+v[3], autonomous=true, variable=true) julia> ΞΌ = Multiplier((t, x, p) -> t+x[1]^2+2p[2], autonomous=false, variable=false) julia> ΞΌ = Multiplier((t, x, p, v) -> t+x[1]^2+2p[2]+v[3], autonomous=false, variable=true) ``` !!! warning When the state and costate are of dimension 1, consider `x` and `p` as scalars. ## Call The call returns the evaluation of the `Multiplier` for given values. ## *Examples* ```@example julia> ΞΌ = Multiplier((x, p) -> x[1]^2+2p[2], autonomous=true, variable=false) julia> ΞΌ([1, 0], [0, 1]) 3 julia> t = 1 julia> v = Real[] julia> ΞΌ(t, [1, 0], [0, 1]) MethodError julia> ΞΌ([1, 0], [0, 1], v) MethodError julia> ΞΌ(t, [1, 0], [0, 1], v) 3 julia> ΞΌ = Multiplier((x, p, v) -> x[1]^2+2p[2]+v[3], autonomous=true, variable=true) julia> ΞΌ([1, 0], [0, 1], [1, 2, 3]) 6 julia> ΞΌ(t, [1, 0], [0, 1], [1, 2, 3]) 6 julia> ΞΌ = Multiplier((t, x, p) -> t+x[1]^2+2p[2], autonomous=false, variable=false) julia> ΞΌ(1, [1, 0], [0, 1]) 4 julia> ΞΌ(1, [1, 0], [0, 1], v) 4 julia> ΞΌ = Multiplier((t, x, p, v) -> t+x[1]^2+2p[2]+v[3], autonomous=false, variable=true) julia> ΞΌ(1, [1, 0], [0, 1], [1, 2, 3]) 7 ``` """ struct Multiplier{time_dependence, variable_dependence} f::Function end # -------------------------------------------------------------------------------------------------- # model # """ $(TYPEDEF) **Fields** $(TYPEDFIELDS) """ mutable struct Index val::Int Index(v::Int) = v β‰₯ 1 ? new(v) : error("index must be at least 1") end Base.:(==)(i::Index, j::Index) = i.val == j.val # needed, as this is not the default behaviour for composite types Base.to_index(i::Index) = i.val Base.isless(i::Index, j::Index) = i.val ≀ j.val Base.isless(i::Index, j::Real) = i.val ≀ j Base.isless(i::Real, j::Index) = i ≀ j.val Base.length(i::Index) = 1 Base.iterate(i::Index, state = 0) = state == 0 ? (i, 1) : nothing Base.IteratorSize(::Type{Index}) = Base.HasLength() Base.append!(v::Vector, i::Index) = Base.append!(v, i.val) Base.getindex(x::AbstractArray, i::Index) = Base.getindex(x, i.val) Base.getindex(x::Real, i::Index) = x[i.val] # to suppress ambiguities Base.getindex(x::SparseArrays.ReadOnly, i::CTBase.Index) = Base.getindex(x, i.val) Base.getindex(x::StaticArrays.TrivialView, i::CTBase.Index) = Base.getindex(x, i.val) """ Type alias for an index or range. """ const RangeConstraint = Union{Index, OrdinalRange{<:Int}} """ $(TYPEDEF) """ abstract type AbstractOptimalControlModel end """ $(TYPEDEF) """ abstract type TimeDependence end """ $(TYPEDEF) """ abstract type Autonomous <: TimeDependence end """ $(TYPEDEF) """ abstract type NonAutonomous <: TimeDependence end """ $(TYPEDEF) """ abstract type VariableDependence end """ $(TYPEDEF) """ abstract type NonFixed <: VariableDependence end """ $(TYPEDEF) """ abstract type Fixed <: VariableDependence end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
5541
""" $(TYPEDSIGNATURES) Return `i` ∈ [0, 9] as a subscript. """ function ctindice(i::Integer)::Char if i < 0 || i > 9 throw(IncorrectArgument("the indice must be between 0 and 9")) end return '\u2080' + i end """ $(TYPEDSIGNATURES) Return `i` > 0 as a subscript. """ function ctindices(i::Integer)::String if i < 0 throw(IncorrectArgument("the indice must be positive")) end s = "" for d ∈ digits(i) s = ctindice(d) * s end return s end """ $(TYPEDSIGNATURES) Return `i` ∈ [0, 9] as an upperscript. """ function ctupperscript(i::Integer)::Char if i < 0 || i > 9 throw(IncorrectArgument("the upperscript must be between 0 and 9")) end if i == 0 return '\u2070' end if i == 1 return '\u00B9' end if i == 2 return '\u00B2' end if i == 3 return '\u00B3' end if i β‰₯ 4 return '\u2074' + i - 4 end end """ $(TYPEDSIGNATURES) Return `i` > 0 as an upperscript. """ function ctupperscripts(i::Integer)::String if i < 0 throw(IncorrectArgument("the upperscript must be positive")) end s = "" for d ∈ digits(i) s = ctupperscript(d) * s end return s end """ $(TYPEDSIGNATURES) Return the gradient of `f` at `x`. """ function ctgradient(f::Function, x::ctNumber; backend = __get_AD_backend()) extras = prepare_derivative(f, backend, x) return derivative(f, backend, x, extras) end function __ctgradient(f::Function, x::ctNumber) return ForwardDiff.derivative(x -> f(x), x) end """ $(TYPEDSIGNATURES) Return the gradient of `f` at `x`. """ function ctgradient(f::Function, x; backend = __get_AD_backend()) extras = prepare_gradient(f, backend, x) return gradient(f, backend, x, extras) end function __ctgradient(f::Function, x) return ForwardDiff.gradient(f, x) end """ $(TYPEDSIGNATURES) Return the gradient of `X` at `x`. """ ctgradient(X::VectorField, x) = ctgradient(X.f, x) __ctgradient(X::VectorField, x) = __ctgradient(X.f, x) """ $(TYPEDSIGNATURES) Return the Jacobian of `f` at `x`. """ function ctjacobian(f::Function, x::ctNumber; backend = __get_AD_backend()) f_number_to_number = only ∘ f ∘ only extras = prepare_derivative(f_number_to_number, backend, x) der = derivative(f_number_to_number, backend, x, extras) return [der;;] end function __ctjacobian(f::Function, x::ctNumber) return ForwardDiff.jacobian(x -> f(x[1]), [x]) end """ $(TYPEDSIGNATURES) Return the Jacobian of `f` at `x`. """ function ctjacobian(f::Function, x; backend = __get_AD_backend()) extras = prepare_jacobian(f, backend, x) return jacobian(f, backend, x, extras) end __ctjacobian(f::Function, x) = ForwardDiff.jacobian(f, x) """ $(TYPEDSIGNATURES) Return the Jacobian of `X` at `x`. """ ctjacobian(X::VectorField, x) = ctjacobian(X.f, x) __ctjacobian(X::VectorField, x) = __ctjacobian(X.f, x) """ $(TYPEDSIGNATURES) Return the interpolation of `f` at `x`. """ function ctinterpolate(x, f) # default for interpolation of the initialization return Interpolations.linear_interpolation(x, f, extrapolation_bc = Interpolations.Line()) end """ $(TYPEDSIGNATURES) Transforms `x` to a Vector{<:ctNumber}. """ function vec2vec(x::Vector{<:Vector{<:ctNumber}})::Vector{<:ctNumber} y = x[1] for i in range(2, length(x)) y = vcat(y, x[i]) end return y end """ $(TYPEDSIGNATURES) Transforms `x` to a Vector{<:Vector{<:ctNumber}}. """ function vec2vec(x::Vector{<:ctNumber}, n::Integer)::Vector{<:Vector{<:ctNumber}} y = [x[1:n]] for i = (n + 1):n:(length(x) - n + 1) y = vcat(y, [x[i:(i + n - 1)]]) end return y end """ $(TYPEDSIGNATURES) Equivalent to `vec2vec(x)` """ expand(x::Vector{<:Vector{<:ctNumber}}) = vec2vec(x) """ $(TYPEDSIGNATURES) Return `x`. """ expand(x::Vector{<:ctNumber}) = x """ $(TYPEDSIGNATURES) Return `expand(matrix2vec(x, 1))` """ expand(x::Matrix{<:ctNumber}) = expand(matrix2vec(x, 1)) """ $(TYPEDSIGNATURES) Transforms `x` to a Vector{<:Vector{<:ctNumber}}. **Note.** `dim` ∈ {1, 2} is the dimension along which the matrix is transformed. """ function matrix2vec( x::Matrix{<:ctNumber}, dim::Integer = __matrix_dimension_stock(), )::Vector{<:Vector{<:ctNumber}} m, n = size(x) y = nothing if dim == 1 y = [x[1, :]] for i = 2:m y = vcat(y, [x[i, :]]) end else y = [x[:, 1]] for j = 2:n y = vcat(y, [x[:, j]]) end end return y end """ $(TYPEDSIGNATURES) Tranform in place function to out of place. Pass the result size and type (default = `Float64`). Return a scalar when the result has size one. If `f!` is `nothing`, return `nothing`. """ function to_out_of_place(f!, n; T = Float64) function f(args...; kwargs...) r = zeros(T, n) f!(r, args...; kwargs...) return n == 1 ? r[1] : r end return isnothing(f!) ? nothing : f end # Adapt getters to test in place function __constraint(ocp, label) if is_in_place(ocp) n = length(constraints(ocp)[label][3]) # Size of lb return to_out_of_place(constraint(ocp, label), n) else return constraint(ocp, label) end end __dynamics(ocp) = is_in_place(ocp) ? to_out_of_place(dynamics(ocp), state_dimension(ocp)) : dynamics(ocp) __lagrange(ocp) = is_in_place(ocp) ? to_out_of_place(lagrange(ocp), 1) : lagrange(ocp) __mayer(ocp) = is_in_place(ocp) ? to_out_of_place(mayer(ocp), 1) : mayer(ocp)
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
881
# using Aqua # using CTBase using DifferentiationInterface: AutoForwardDiff using Plots using Test # functions and types that are not exported const vec2vec = CTBase.vec2vec const subs = CTBase.subs const has = CTBase.has const replace_call = CTBase.replace_call const constraint_type = CTBase.constraint_type # @testset verbose = true showtiming = true "Base" begin for name ∈ ( :aqua, :ctparser_utils, :default, :description, :differential_geometry, :exception, :function, :goddard, :model, :plot, :print, :solution, :utils, :onepass, ) @testset "$(name)" begin test_name = Symbol(:test_, name) println("testing: ", string(name)) include("$(test_name).jl") @eval $test_name() end end end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
387
function test_aqua() @testset "Aqua.jl" begin Aqua.test_all( CTBase; ambiguities = false, #stale_deps=(ignore=[:SomePackage],), deps_compat = (ignore = [:LinearAlgebra, :Unicode],), piracies = true, ) # do not warn about ambiguities in dependencies Aqua.test_ambiguities(CTBase) end end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
4777
# test utils function test_ctparser_utils() e = :(∫(r(t)^2 + 2u₁(t)) β†’ min) @test subs(e, :r, :(x[1])) == :(∫((x[1])(t)^2 + 2 * u₁(t)) β†’ min) e = :(∫(u₁(t)^2 + 2uβ‚‚(t)) β†’ min) for i ∈ 1:2 e = subs(e, Symbol(:u, Char(8320 + i)), :(u[$i])) end @test e == :(∫((u[1])(t)^2 + 2 * (u[2])(t)) β†’ min) t = :t t0 = 0 tf = :tf x = :x u = :u e = :(x[1](0) * 2x(tf) - x[2](tf) * 2x(0)) x0 = Symbol(x, 0) @test subs(e, :($x[1]($(t0))), :($x0[1])) == :(x0[1] * (2 * x(tf)) - (x[2])(tf) * (2 * x(0))) e = :(x[1](0) * 2x(tf) - x[2](tf) * 2x(0)) x0 = Symbol(x, "#0") xf = Symbol(x, "#f") e = replace_call(e, x, t0, x0) @test replace_call(e, x, tf, xf) == :(var"x#0"[1] * (2var"x#f") - var"x#f"[2] * (2var"x#0")) e = :(A * x(t) + B * u(t)) @test replace_call(replace_call(e, x, t, x), u, t, u) == :(A * x + B * u) e = :(F0(x(t)) + u(t) * F1(x(t))) @test replace_call(replace_call(e, x, t, x), u, t, u) == :(F0(x) + u * F1(x)) e = :(0.5u(t)^2) @test replace_call(e, u, t, u) == :(0.5 * u^2) t = :t t0 = 0 tf = :tf x = :x u = :u e = :((x^2 + u[1])(t)) @test replace_call(e, [x, u], t, [:xx, :uu]) == :(xx^2 + uu[1]) e = :(((x^2)(t) + u[1])(t)) @test replace_call(e, [x, u], t, [:xx, :uu]) == :(xx^2 + uu[1]) e = :(((x^2)(t0) + u[1])(t)) @test replace_call(e, [x, u], t, [:xx, :uu]) == :((xx^2)(t0) + uu[1]) e = :(∫(x[1](t)^2 + 2 * u(t)) β†’ min) @test has(e, :x, :t) @test has(e, :u, :t) @test !has(e, :v, :t) @test has(e, 2) @test has(e, :x) @test has(e, :min) @test has(e, :(x[1](t)^2)) @test !has(e, :(x[1](t)^3)) @test !has(e, 3) @test !has(e, :max) @test has(:x, :x) @test !has(:x, 2) @test !has(:x, :y) t = :t t0 = 0 tf = :tf x = :x u = :u v = :v @test constraint_type(:(yΜ‡(t)), t, t0, tf, x, u, v) == :other @test constraint_type(:(xΜ‡(s)), t, t0, tf, x, u, v) == :other @test constraint_type(:(x(0)'), t, t0, tf, x, u, v) == :boundary @test constraint_type(:(x'(0)), t, t0, tf, x, u, v) == :boundary @test constraint_type(:(x(t)'), t, t0, tf, x, u, v) == :state_fun @test constraint_type(:(x(0)), t, t0, tf, x, u, v) == (:initial, nothing) @test constraint_type(:(x[1:2:5](0)), t, t0, tf, x, u, v) == (:initial, 1:2:5) @test constraint_type(:(x[1:2](0)), t, t0, tf, x, u, v) == (:initial, 1:2) @test constraint_type(:(x[1](0)), t, t0, tf, x, u, v) == (:initial, 1) @test constraint_type(:(x[1:2](0)), t, t0, tf, x, u, v) == (:initial, 1:2) @test constraint_type(:(2x[1](0)^2), t, t0, tf, x, u, v) == :boundary @test constraint_type(:(x(tf)), t, t0, tf, x, u, v) == (:final, nothing) @test constraint_type(:(x[1:2:5](tf)), t, t0, tf, x, u, v) == (:final, 1:2:5) @test constraint_type(:(x[1:2](tf)), t, t0, tf, x, u, v) == (:final, 1:2) @test constraint_type(:(x[1](tf)), t, t0, tf, x, u, v) == (:final, 1) @test constraint_type(:(x[1:2](tf)), t, t0, tf, x, u, v) == (:final, 1:2) @test constraint_type(:(x[1](tf) - x[2](0)), t, t0, tf, x, u, v) == :boundary @test constraint_type(:(2x[1](tf)^2), t, t0, tf, x, u, v) == :boundary @test constraint_type(:(u[1:2:5](t)), t, t0, tf, x, u, v) == (:control_range, 1:2:5) @test constraint_type(:(u[1:2](t)), t, t0, tf, x, u, v) == (:control_range, 1:2) @test constraint_type(:(u[1](t)), t, t0, tf, x, u, v) == (:control_range, 1) @test constraint_type(:(u(t)), t, t0, tf, x, u, v) == (:control_range, nothing) @test constraint_type(:(2u[1](t)^2), t, t0, tf, x, u, v) == :control_fun @test constraint_type(:(x[1:2:5](t)), t, t0, tf, x, u, v) == (:state_range, 1:2:5) @test constraint_type(:(x[1:2](t)), t, t0, tf, x, u, v) == (:state_range, 1:2) @test constraint_type(:(x[1](t)), t, t0, tf, x, u, v) == (:state_range, 1) @test constraint_type(:(x(t)), t, t0, tf, x, u, v) == (:state_range, nothing) @test constraint_type(:(2x[1](t)^2), t, t0, tf, x, u, v) == :state_fun @test constraint_type(:(2u[1](t)^2 * x(t)), t, t0, tf, x, u, v) == :mixed @test constraint_type(:(2u[1](0)^2 * x(t)), t, t0, tf, x, u, v) == :other @test constraint_type(:(2u[1](t)^2 * x(t) + v), t, t0, tf, x, u, v) == :mixed @test constraint_type(:(v[1:2:10]), t, t0, tf, x, u, v) == (:variable_range, 1:2:9) @test constraint_type(:(v[1:10]), t, t0, tf, x, u, v) == (:variable_range, 1:10) @test constraint_type(:(v[2]), t, t0, tf, x, u, v) == (:variable_range, 2) @test constraint_type(:(v), t, t0, tf, x, u, v) == (:variable_range, nothing) @test constraint_type(:(v^2 + 1), t, t0, tf, x, u, v) == :variable_fun @test constraint_type(:(v[2]^2 + 1), t, t0, tf, x, u, v) == :variable_fun end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
2511
function test_default() @testset "Audo diff" begin set_AD_backend(AutoForwardDiff()) @test CTBase.__get_AD_backend() == AutoForwardDiff() end @testset "Default value of the time dependence of the functions" begin @test CTBase.__fun_time_dependence() == Autonomous end @testset "Default value of the time dependence of the Optimal Control Problem" begin @test CTBase.__ocp_time_dependence() == Autonomous end @testset "Default value of the variable dependence of the functions" begin @test CTBase.__fun_variable_dependence() == Fixed end @testset "Default value of the variable dependence of the Optimal Control Problem" begin @test CTBase.__ocp_variable_dependence() == Fixed end @testset "Default value of the state names of the Optimal Control Problem" begin @test CTBase.__state_name() == "x" @test CTBase.__state_components_names(2, CTBase.__state_name()) == ["x₁", "xβ‚‚"] end @testset "Default value of the control names of the Optimal Control Problem" begin @test CTBase.__control_name() == "u" @test CTBase.__control_components_names(2, CTBase.__control_name()) == ["u₁", "uβ‚‚"] end @testset "Default value of the variable names of the Optimal Control Problem" begin @test CTBase.__variable_name() == "v" @test CTBase.__variable_components_names(2, CTBase.__variable_name()) == ["v₁", "vβ‚‚"] end @testset "Default value of the time name of the Optimal Control Problem" begin @test CTBase.__time_name() == "t" end @testset "Default value of the criterion type of the Optimal Control Problem" begin @test CTBase.__criterion_type() == :min end @testset "Default value of the constraint label" begin @test CTBase.__constraint_label() isa Symbol end @testset "Default value of the stockage of elements in a matrix" begin @test CTBase.__matrix_dimension_stock() == 1 end @testset "Default value of the display during resolution" begin @test CTBase.__display() isa Bool end @testset "Default value of the additional callback function" begin @test isempty(CTBase.__callbacks()) end @testset "Default value of the interpolation function for initialisation" begin @test CTBase.__init_interpolation() isa Function end @testset "Default value of the initial guess" begin @test isnothing(CTBase.__ocp_init()) end end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
2478
function test_description() # descriptions = () descriptions = add(descriptions, (:a,)) descriptions = add(descriptions, (:b,)) @test descriptions[1] == (:a,) @test descriptions[2] == (:b,) # get the complete description of the chosen method algorithmes = () algorithmes = add(algorithmes, (:descent, :bfgs, :bissection)) algorithmes = add(algorithmes, (:descent, :bfgs, :backtracking)) algorithmes = add(algorithmes, (:descent, :bfgs, :fixedstep)) algorithmes = add(algorithmes, (:descent, :gradient, :bissection)) algorithmes = add(algorithmes, (:descent, :gradient, :backtracking)) algorithmes = add(algorithmes, (:descent, :gradient, :fixedstep)) @test getFullDescription((:descent,), algorithmes) == (:descent, :bfgs, :bissection) @test getFullDescription((:bfgs,), algorithmes) == (:descent, :bfgs, :bissection) @test getFullDescription((:bissection,), algorithmes) == (:descent, :bfgs, :bissection) @test getFullDescription((:backtracking,), algorithmes) == (:descent, :bfgs, :backtracking) @test getFullDescription((:fixedstep,), algorithmes) == (:descent, :bfgs, :fixedstep) @test getFullDescription((:fixedstep, :gradient), algorithmes) == (:descent, :gradient, :fixedstep) # incorrect description @test_throws AmbiguousDescription getFullDescription((:ttt,), algorithmes) @test_throws AmbiguousDescription getFullDescription((:descent, :ttt), algorithmes) # diff x = (:a, :b, :c) y = (:b,) @test remove(x, y) == (:a, :c) @test typeof(remove(x, y)) <: Description # inclusion and different sizes algorithmes = () algorithmes = add(algorithmes, (:a, :b, :c)) algorithmes = add(algorithmes, (:a, :b, :c, :d)) @test getFullDescription((:a, :b), algorithmes) == (:a, :b, :c) @test getFullDescription((:a, :b, :c, :d), algorithmes) == (:a, :b, :c, :d) # inclusion and different sizes - switch ordering # priority to the first with max shared elements algorithmes = () algorithmes = add(algorithmes, (:a, :b, :c, :d)) algorithmes = add(algorithmes, (:a, :b, :c)) @test getFullDescription((:a, :b), algorithmes) == (:a, :b, :c, :d) @test getFullDescription((:a, :b, :c, :d), algorithmes) == (:a, :b, :c, :d) # add a description already in the list algorithmes = () algorithmes = add(algorithmes, (:a, :b, :c)) @test_throws IncorrectArgument add(algorithmes, (:a, :b, :c)) end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
32648
function test_differential_geometry() βˆ… = Vector{Real}() dummy_function() = nothing @testset "Lifts" begin @testset "HamiltonianLift from VectorField" begin HL = HamiltonianLift( VectorField(x -> [x[1]^2, x[2]^2], autonomous = true, variable = false), ) @test HL([1, 0], [0, 1]) == 0 @test HL(1, [1, 0], [0, 1], 1) == 0 HL = HamiltonianLift( VectorField((x, v) -> [x[1]^2, x[2]^2 + v], autonomous = true, variable = true), ) @test HL([1, 0], [0, 1], 1) == 1 @test HL(1, [1, 0], [0, 1], 1) == 1 HL = HamiltonianLift( VectorField((t, x) -> [t + x[1]^2, x[2]^2], autonomous = false, variable = false), ) @test HL(1, [1, 0], [0, 1]) == 0 @test HL(1, [1, 0], [0, 1], 1) == 0 HL = HamiltonianLift( VectorField( (t, x, v) -> [t + x[1]^2, x[2]^2 + v], autonomous = false, variable = true, ), ) @test HL(1, [1, 0], [0, 1], 1) == 1 end @testset "HamiltonianLift from Function" begin HL = HamiltonianLift(x -> [x[1]^2, x[2]^2], autonomous = true, variable = false) @test HL([1, 0], [0, 1]) == 0 @test HL(1, [1, 0], [0, 1], 1) == 0 HL = HamiltonianLift((x, v) -> [x[1]^2, x[2]^2 + v], autonomous = true, variable = true) @test HL([1, 0], [0, 1], 1) == 1 @test HL(1, [1, 0], [0, 1], 1) == 1 HL = HamiltonianLift( (t, x) -> [t + x[1]^2, x[2]^2], autonomous = false, variable = false, ) @test HL(1, [1, 0], [0, 1]) == 0 @test HL(1, [1, 0], [0, 1], 1) == 0 HL = HamiltonianLift( (t, x, v) -> [t + x[1]^2, x[2]^2 + v], autonomous = false, variable = true, ) @test HL(1, [1, 0], [0, 1], 1) == 1 HL = HamiltonianLift(x -> [x[1]^2, x[2]^2], Autonomous, Fixed) @test HL([1, 0], [0, 1]) == 0 @test HL(1, [1, 0], [0, 1], 1) == 0 HL = HamiltonianLift((x, v) -> [x[1]^2, x[2]^2 + v], Autonomous, NonFixed) @test HL([1, 0], [0, 1], 1) == 1 @test HL(1, [1, 0], [0, 1], 1) == 1 HL = HamiltonianLift((t, x) -> [t + x[1]^2, x[2]^2], NonAutonomous, Fixed) @test HL(1, [1, 0], [0, 1]) == 0 @test HL(1, [1, 0], [0, 1], 1) == 0 HL = HamiltonianLift((t, x, v) -> [t + x[1]^2, x[2]^2 + v], NonAutonomous, NonFixed) @test HL(1, [1, 0], [0, 1], 1) == 1 end @testset "from VectorFields" begin # autonomous case X = VectorField(x -> 2x) H = Lift(X) Test.@test H(1, 1) == 2 Test.@test H([1, 2], [3, 4]) == 22 Test.@test_throws MethodError H([1, 2], 1) Test.@test_throws MethodError H(1, [1, 2]) # nonautonomous case X = VectorField((t, x) -> 2x, NonAutonomous) H = Lift(X) Test.@test H(1, 1, 1) == 2 Test.@test H(1, [1, 2], [3, 4]) == 22 # autonomous nonfixed case X = VectorField((x, v) -> 2x, NonFixed) H = Lift(X) Test.@test H(1, 1, 1) == 2 Test.@test H([1, 2], [3, 4], 1) == 22 Test.@test_throws MethodError H([1, 2], 1) Test.@test_throws MethodError H(1, [1, 2]) # nonautonomous nonfixed case X = VectorField((t, x, v) -> 2x, NonAutonomous, NonFixed) H = Lift(X) Test.@test H(1, 1, 1, 1) == 2 Test.@test H(1, [1, 2], [3, 4], 1) == 22 end @testset "from Function" begin # autonomous case X::Function = x -> 2x H = Lift(X) Test.@test H(1, 1) == 2 Test.@test H([1, 2], [3, 4]) == 22 # nonautonomous case Xt::Function = (t, x) -> 2x H = Lift(Xt, autonomous = false) Test.@test H(1, 1, 1) == 2 Test.@test H(1, [1, 2], [3, 4]) == 22 # autonomous nonfixed case Xv::Function = (x, v) -> 2x H = Lift(Xv, variable = true) Test.@test H(1, 1, 1) == 2 Test.@test H([1, 2], [3, 4], 1) == 22 # nonautonomous nonfixed case Xtv::Function = (t, x, v) -> 2x H = Lift(Xtv, autonomous = false, variable = true) Test.@test H(1, 1, 1, 1) == 2 Test.@test H(1, [1, 2], [3, 4], 1) == 22 # overload F::Function = x -> 2x H_F(x, p) = Lift(F)(x, p) H_F(y) = H_F(y, y) Test.@test H_F(1) == 2 # exceptions Test.@test_throws IncorrectArgument Lift(X, Int64) end end # tests for Lift @testset "Directional derivative of a scalar function" begin # autonomous, dim 2 Ο† = x -> [x[2], -x[1]] X = VectorField(Ο†) f = x -> x[1]^2 + x[2]^2 Test.@test (X β‹… f)([1, 2]) == 0 Test.@test (X β‹… f)([1, 2]) == Lie(X, f)([1, 2]) Test.@test Lie(Ο†, f)([1, 2]) == 0 # autonomous, dim 1 Ο† = x -> 2x X = VectorField(Ο†) f = x -> x^2 Test.@test (X β‹… f)(1) == 4 Test.@test (Ο† β‹… f)(1) == 4 Test.@test Lie(Ο†, f)(1) == 4 # nonautonomous, dim 2 Ο† = (t, x) -> [t + x[2], -x[1]] X = VectorField(Ο†, NonAutonomous) f = (t, x) -> t + x[1]^2 + x[2]^2 Test.@test (X β‹… f)(1, [1, 2]) == 2 Test.@test Lie(Ο†, f, NonAutonomous)(1, [1, 2]) == 2 # nonautonomous, dim 1 Ο† = (t, x) -> 2x + t X = VectorField(Ο†, NonAutonomous) f = (t, x) -> t + x^2 Test.@test (X β‹… f)(1, 1) == 6 Test.@test Lie(Ο†, f, NonAutonomous)(1, 1) == 6 # autonomous, nonfixed, dim 2 Ο† = (x, v) -> [x[2] + v[1], -x[1] + v[2]] X = VectorField(Ο†, NonFixed) f = (x, v) -> x[1]^2 + x[2]^2 Test.@test (X β‹… f)([1, 2], [2, 1]) == 8 Test.@test Lie(Ο†, f, NonFixed)([1, 2], [2, 1]) == 8 # autonomous, nonfixed, dim 1 Ο† = (x, v) -> 2x + v X = VectorField(Ο†, NonFixed) f = (x, v) -> x^2 Test.@test (X β‹… f)(1, 1) == 6 Test.@test Lie(Ο†, f, NonFixed)(1, 1) == 6 # nonautonomous, nonfixed, dim 2 Ο† = (t, x, v) -> [t + x[2] + v[1], -x[1] + v[2]] X = VectorField(Ο†, NonAutonomous, NonFixed) f = (t, x, v) -> t + x[1]^2 + x[2]^2 Test.@test (X β‹… f)(1, [1, 2], [2, 1]) == 10 Test.@test Lie(Ο†, f, NonAutonomous, NonFixed)(1, [1, 2], [2, 1]) == 10 # nonautonomous, nonfixed, dim 1 Ο† = (t, x, v) -> 2x + t + v X = VectorField(Ο†, NonAutonomous, NonFixed) f = (t, x, v) -> t + x^2 Test.@test (X β‹… f)(1, 1, 1) == 8 Test.@test Lie(Ο†, f, NonAutonomous, NonFixed)(1, 1, 1) == 8 end @testset "Directional derivative of a vector field" begin # autonomous, dim 2 X = VectorField(x -> [x[2], -x[1]]) Y = VectorField(x -> [x[1], x[2]]) Test.@test CTBase.:(β…‹)(X, Y)([1, 2]) == [2, -1] # autonomous, dim 1 X = VectorField(x -> 2x) Y = VectorField(x -> 3x) Test.@test CTBase.:(β…‹)(X, Y)(1) == 6 # nonautonomous, dim 2 X = VectorField((t, x) -> [t + x[2], -x[1]], NonAutonomous) Y = VectorField((t, x) -> [t + x[1], x[2]], NonAutonomous) Test.@test CTBase.:(β…‹)(X, Y)(1, [1, 2]) == [3, -1] # nonautonomous, dim 1 X = VectorField((t, x) -> 2x + t, NonAutonomous) Y = VectorField((t, x) -> 3x + t, NonAutonomous) Test.@test CTBase.:(β…‹)(X, Y)(1, 1) == 9 # autonomous, nonfixed, dim 1 X = VectorField((x, v) -> 2x + v, NonFixed) Y = VectorField((x, v) -> 3x + v, NonFixed) Test.@test CTBase.:(β…‹)(X, Y)(1, 1) == 9 # nonautonomous, nonfixed, dim 1 X = VectorField((t, x, v) -> t + 2x + v, NonAutonomous, NonFixed) Y = VectorField((t, x, v) -> t + 3x + v, NonAutonomous, NonFixed) Test.@test CTBase.:(β…‹)(X, Y)(1, 1, 1) == 12 # autonomous, nonfixed, dim 2 X = VectorField((x, v) -> [v[1] + v[2] + x[2], -x[1]], NonFixed) Y = VectorField((x, v) -> [v[1] + v[2] + x[1], x[2]], NonFixed) Test.@test CTBase.:(β…‹)(X, Y)([1, 2], [2, 3]) == [7, -1] # nonautonomous, nonfixed, dim 2 X = VectorField((t, x, v) -> [t + v[1] + v[2] + x[2], -x[1]], NonFixed, NonAutonomous) Y = VectorField((t, x, v) -> [v[1] + v[2] + x[1], x[2]], NonFixed, NonAutonomous) Test.@test CTBase.:(β…‹)(X, Y)(1, [1, 2], [2, 3]) == [8, -1] end @testset "Lie bracket - length 2" begin @testset "autonomous case" begin f = x -> [x[2], 2x[1]] g = x -> [3x[2], -x[1]] X = VectorField(f) Y = VectorField(g) Test.@test Lie(X, Y)([1, 2]) == [7, -14] end @testset "nonautonomous case" begin f = (t, x) -> [t + x[2], -2x[1]] g = (t, x) -> [t + 3x[2], -x[1]] X = VectorField(f, NonAutonomous) Y = VectorField(g, NonAutonomous) Test.@test Lie(X, Y)(1, [1, 2]) == [-5, 11] end @testset "autonomous nonfixed case" begin f = (x, v) -> [x[2] + v, 2x[1]] g = (x, v) -> [3x[2], v - x[1]] X = VectorField(f, NonFixed) Y = VectorField(g, variable = true) Test.@test Lie(X, Y)([1, 2], 1) == [6, -15] end @testset "nonautonomous nonfixed case" begin f = (t, x, v) -> [t + x[2] + v, -2x[1] - v] g = (t, x, v) -> [t + 3x[2] + v, -x[1] - v] X = VectorField(f, NonAutonomous, NonFixed) Y = VectorField(g, NonAutonomous, NonFixed) Test.@test Lie(X, Y)(1, [1, 2], 1) == [-7, 12] end @testset "mri example" begin Ξ“ = 2 Ξ³ = 1 Ξ΄ = Ξ³ - Ξ“ F0 = VectorField(x -> [-Ξ“ * x[1], -Ξ“ * x[2], Ξ³ * (1 - x[3])]) F1 = VectorField(x -> [0, -x[3], x[2]]) F2 = VectorField(x -> [x[3], 0, -x[1]]) F01 = Lie(F0, F1) F02 = Lie(F0, F2) F12 = Lie(F1, F2) x = [1, 2, 3] Test.@test F01(x) β‰ˆ -[0, Ξ³ - Ξ΄ * x[3], -Ξ΄ * x[2]] atol = 1e-6 Test.@test F02(x) β‰ˆ -[-Ξ³ + Ξ΄ * x[3], 0, Ξ΄ * x[1]] atol = 1e-6 Test.@test F12(x) β‰ˆ -[-x[2], x[1], 0] atol = 1e-6 end @testset "intrinsic definition" begin X = VectorField(x -> [x[2]^2, -2x[1] * x[2]]) Y = VectorField(x -> [x[1] * (1 + x[2]), 3x[2]^3]) f = x -> x[1]^4 + 2x[2]^3 x = [1, 2] # check real intrinsic order 2 definition of Lie bracket Test.@test ((@Lie [X, Y]) β‹… f)(x) == ((X β‹… (Y β‹… f))(x) - (Y β‹… (X β‹… f))(x)) end end @testset "Poisson bracket" begin @testset "autonomous case" begin f = (x, p) -> x[2]^2 + 2x[1]^2 + p[1]^2 g = (x, p) -> 3x[2]^2 + -x[1]^2 + p[2]^2 + p[1] h = (x, p) -> x[2]^2 + -2x[1]^2 + p[1]^2 - 2p[2]^2 fβ‚Šg = (x, p) -> f(x, p) + g(x, p) fg = (x, p) -> f(x, p) * g(x, p) # F = Hamiltonian(f) G = Hamiltonian(g) H = Hamiltonian(h) Fβ‚ŠG = Hamiltonian(fβ‚Šg) FG = Hamiltonian(fg) # Test.@test Poisson(f, g)([1, 2], [2, 1]) == -20 Test.@test Poisson(f, G)([1, 2], [2, 1]) == -20 Test.@test Poisson(F, g)([1, 2], [2, 1]) == -20 # Test.@test Poisson(F, Hamiltonian((x, p) -> 42))([1, 2], [2, 1]) == 0 Test.@test Poisson(F, G)([1, 2], [2, 1]) == -20 Test.@test Poisson(F, G)([1, 2], [2, 1]) == -Poisson(G, F)([1, 2], [2, 1]) # anticommutativity Test.@test Poisson(Fβ‚ŠG, H)([1, 2], [2, 1]) == Poisson(F, H)([1, 2], [2, 1]) + Poisson(G, H)([1, 2], [2, 1]) # bilinearity 1 Test.@test Poisson(H, Fβ‚ŠG)([1, 2], [2, 1]) == Poisson(H, F)([1, 2], [2, 1]) + Poisson(H, G)([1, 2], [2, 1]) # bilinearity 2 Test.@test Poisson(FG, H)([1, 2], [2, 1]) == Poisson(F, H)([1, 2], [2, 1]) * G([1, 2], [2, 1]) + F([1, 2], [2, 1]) * Poisson(G, H)([1, 2], [2, 1]) # Liebniz's rule Test.@test Poisson(F, Poisson(G, H))([1, 2], [2, 1]) + Poisson(G, Poisson(H, F))([1, 2], [2, 1]) + Poisson(H, Poisson(F, G))([1, 2], [2, 1]) == 0 # Jacobi identity end @testset "nonautonomous case" begin f = (t, x, p) -> t * x[2]^2 + 2x[1]^2 + p[1]^2 + t g = (t, x, p) -> 3x[2]^2 + -x[1]^2 + p[2]^2 + p[1] - t h = (t, x, p) -> x[2]^2 + -2x[1]^2 + p[1]^2 - 2p[2]^2 + t fβ‚Šg = (t, x, p) -> f(t, x, p) + g(t, x, p) fg = (t, x, p) -> f(t, x, p) * g(t, x, p) F = Hamiltonian(f, autonomous = false) G = Hamiltonian(g, autonomous = false) H = Hamiltonian(h, autonomous = false) Fβ‚ŠG = Hamiltonian(fβ‚Šg, autonomous = false) FG = Hamiltonian(fg, autonomous = false) # Test.@test Poisson(f, g, autonomous = false)(2, [1, 2], [2, 1]) == -28 Test.@test Poisson(f, G)(2, [1, 2], [2, 1]) == -28 Test.@test Poisson(F, g)(2, [1, 2], [2, 1]) == -28 # Test.@test Poisson(F, Hamiltonian((t, x, p) -> 42, autonomous = false))( 2, [1, 2], [2, 1], ) == 0 Test.@test Poisson(F, G)(2, [1, 2], [2, 1]) == -28 Test.@test Poisson(F, G)(2, [1, 2], [2, 1]) == -Poisson(G, F)(2, [1, 2], [2, 1]) # anticommutativity Test.@test Poisson(Fβ‚ŠG, H)(2, [1, 2], [2, 1]) == Poisson(F, H)(2, [1, 2], [2, 1]) + Poisson(G, H)(2, [1, 2], [2, 1]) # bilinearity 1 Test.@test Poisson(H, Fβ‚ŠG)(2, [1, 2], [2, 1]) == Poisson(H, F)(2, [1, 2], [2, 1]) + Poisson(H, G)(2, [1, 2], [2, 1]) # bilinearity 2 Test.@test Poisson(FG, H)(2, [1, 2], [2, 1]) == Poisson(F, H)(2, [1, 2], [2, 1]) * G(2, [1, 2], [2, 1]) + F(2, [1, 2], [2, 1]) * Poisson(G, H)(2, [1, 2], [2, 1]) # Liebniz's rule Test.@test Poisson(F, Poisson(G, H))(2, [1, 2], [2, 1]) + Poisson(G, Poisson(H, F))(2, [1, 2], [2, 1]) + Poisson(H, Poisson(F, G))(2, [1, 2], [2, 1]) == 0 # Jacobi identity end @testset "autonomous nonfixed case" begin f = (x, p, v) -> v[1] * x[2]^2 + 2x[1]^2 + p[1]^2 + v[2] g = (x, p, v) -> 3x[2]^2 + -x[1]^2 + p[2]^2 + p[1] - v[2] h = (x, p, v) -> x[2]^2 + -2x[1]^2 + p[1]^2 - 2p[2]^2 + v[2] fβ‚Šg = (x, p, v) -> f(x, p, v) + g(x, p, v) fg = (x, p, v) -> f(x, p, v) * g(x, p, v) F = Hamiltonian(f, variable = true) G = Hamiltonian(g, variable = true) H = Hamiltonian(h, variable = true) Fβ‚ŠG = Hamiltonian(fβ‚Šg, variable = true) FG = Hamiltonian(fg, variable = true) Test.@test Poisson(F, Hamiltonian((x, p, v) -> 42, variable = true))( [1, 2], [2, 1], [4, 4], ) == 0 Test.@test Poisson(F, G)([1, 2], [2, 1], [4, 4]) == -44 Test.@test Poisson(F, G)([1, 2], [2, 1], [4, 4]) == -Poisson(G, F)([1, 2], [2, 1], [4, 4]) # anticommutativity Test.@test Poisson(Fβ‚ŠG, H)([1, 2], [2, 1], [4, 4]) == Poisson(F, H)([1, 2], [2, 1], [4, 4]) + Poisson(G, H)([1, 2], [2, 1], [4, 4]) # bilinearity 1 Test.@test Poisson(H, Fβ‚ŠG)([1, 2], [2, 1], [4, 4]) == Poisson(H, F)([1, 2], [2, 1], [4, 4]) + Poisson(H, G)([1, 2], [2, 1], [4, 4]) # bilinearity 2 Test.@test Poisson(FG, H)([1, 2], [2, 1], [4, 4]) == Poisson(F, H)([1, 2], [2, 1], [4, 4]) * G([1, 2], [2, 1], [4, 4]) + F([1, 2], [2, 1], [4, 4]) * Poisson(G, H)([1, 2], [2, 1], [4, 4]) # Liebniz's rule Test.@test Poisson(F, Poisson(G, H))([1, 2], [2, 1], [4, 4]) + Poisson(G, Poisson(H, F))([1, 2], [2, 1], [4, 4]) + Poisson(H, Poisson(F, G))([1, 2], [2, 1], [4, 4]) == 0 # Jacobi identity end @testset "nonautonomous nonfixed case" begin f = (t, x, p, v) -> t * v[1] * x[2]^2 + 2x[1]^2 + p[1]^2 + v[2] g = (t, x, p, v) -> 3x[2]^2 + -x[1]^2 + p[2]^2 + p[1] + t - v[2] h = (t, x, p, v) -> x[2]^2 + -2x[1]^2 + p[1]^2 - 2p[2]^2 + t + v[2] fβ‚Šg = (t, x, p, v) -> f(t, x, p, v) + g(t, x, p, v) fg = (t, x, p, v) -> f(t, x, p, v) * g(t, x, p, v) F = Hamiltonian(f, autonomous = false, variable = true) G = Hamiltonian(g, autonomous = false, variable = true) H = Hamiltonian(h, autonomous = false, variable = true) Fβ‚ŠG = Hamiltonian(fβ‚Šg, autonomous = false, variable = true) FG = Hamiltonian(fg, autonomous = false, variable = true) Test.@test Poisson( F, Hamiltonian((t, x, p, v) -> 42, autonomous = false, variable = true), )( 2, [1, 2], [2, 1], [4, 4], ) == 0 Test.@test Poisson(F, G)(2, [1, 2], [2, 1], [4, 4]) == -76 Test.@test Poisson(F, G)(2, [1, 2], [2, 1], [4, 4]) == -Poisson(G, F)(2, [1, 2], [2, 1], [4, 4]) # anticommutativity Test.@test Poisson(Fβ‚ŠG, H)(2, [1, 2], [2, 1], [4, 4]) == Poisson(F, H)(2, [1, 2], [2, 1], [4, 4]) + Poisson(G, H)(2, [1, 2], [2, 1], [4, 4]) # bilinearity 1 Test.@test Poisson(H, Fβ‚ŠG)(2, [1, 2], [2, 1], [4, 4]) == Poisson(H, F)(2, [1, 2], [2, 1], [4, 4]) + Poisson(H, G)(2, [1, 2], [2, 1], [4, 4]) # bilinearity 2 Test.@test Poisson(FG, H)(2, [1, 2], [2, 1], [4, 4]) == Poisson(F, H)(2, [1, 2], [2, 1], [4, 4]) * G(2, [1, 2], [2, 1], [4, 4]) + F(2, [1, 2], [2, 1], [4, 4]) * Poisson(G, H)(2, [1, 2], [2, 1], [4, 4]) # Liebniz's rule Test.@test Poisson(F, Poisson(G, H))(2, [1, 2], [2, 1], [4, 4]) + Poisson(G, Poisson(H, F))(2, [1, 2], [2, 1], [4, 4]) + Poisson(H, Poisson(F, G))(2, [1, 2], [2, 1], [4, 4]) == 0 # Jacobi identity end end @testset "poisson bracket of Lifts" begin @testset "autonomous case" begin f = x -> [x[1] + x[2]^2, x[1], 0] g = x -> [0, x[2], x[1]^2 + 4 * x[2]] F = Lift(f) G = Lift(g) F_ = (x, p) -> p' * f(x) G_ = (x, p) -> p' * g(x) Test.@test Poisson(F, G)([1, 2, 3], [4, 0, 4]) β‰ˆ Poisson(F_, G_)([1, 2, 3], [4, 0, 4]) atol = 1e-6 Test.@test Poisson(F, G_)([1, 2, 3], [4, 0, 4]) β‰ˆ Poisson(F_, G)([1, 2, 3], [4, 0, 4]) atol = 1e-6 end @testset "nonautonomous case" begin f = (t, x) -> [t * x[1] + x[2]^2, x[1], 0] g = (t, x) -> [0, x[2], t * x[1]^2 + 4 * x[2]] F = Lift(f, NonAutonomous) G = Lift(g, NonAutonomous) F_ = (t, x, p) -> p' * f(t, x) G_ = (t, x, p) -> p' * g(t, x) Test.@test Poisson(F, G, NonAutonomous)(2, [1, 2, 3], [4, 0, 4]) β‰ˆ Poisson(F_, G_, NonAutonomous)(2, [1, 2, 3], [4, 0, 4]) atol = 1e-6 Test.@test Poisson(F, G_, NonAutonomous)(2, [1, 2, 3], [4, 0, 4]) β‰ˆ Poisson(F_, G, NonAutonomous)(2, [1, 2, 3], [4, 0, 4]) atol = 1e-6 end @testset "autonomous nonfixed case" begin f = (x, v) -> [x[1] + v * x[2]^2, x[1], 0] g = (x, v) -> [0, x[2], x[1]^2 + v * 4 * x[2]] F = Lift(f, NonFixed) G = Lift(g, NonFixed) F_ = (x, p, v) -> p' * f(x, v) G_ = (x, p, v) -> p' * g(x, v) Test.@test Poisson(F, G, NonFixed)([1, 2, 3], [4, 0, 4], 1) β‰ˆ Poisson(F_, G_, NonFixed)([1, 2, 3], [4, 0, 4], 1) atol = 1e-6 Test.@test Poisson(F, G_, NonFixed)([1, 2, 3], [4, 0, 4], 1) β‰ˆ Poisson(F_, G, NonFixed)([1, 2, 3], [4, 0, 4], 1) atol = 1e-6 end @testset "nonautonomous nonfixed case" begin f = (t, x, v) -> [t * x[1] + v * x[2]^2, x[1], 0] g = (t, x, v) -> [0, x[2], t * x[1]^2 + v * 4 * x[2]] F = Lift(f, NonAutonomous, NonFixed) G = Lift(g, NonAutonomous, NonFixed) F_ = (t, x, p, v) -> p' * f(t, x, v) G_ = (t, x, p, v) -> p' * g(t, x, v) Test.@test Poisson(F, G, NonAutonomous, NonFixed)(2, [1, 2, 3], [4, 0, 4], 1) β‰ˆ Poisson(F_, G_, NonAutonomous, NonFixed)(2, [1, 2, 3], [4, 0, 4], 1) atol = 1e-6 Test.@test Poisson(F, G_, NonAutonomous, NonFixed)(2, [1, 2, 3], [4, 0, 4], 1) β‰ˆ Poisson(F_, G, NonAutonomous, NonFixed)(2, [1, 2, 3], [4, 0, 4], 1) atol = 1e-6 end end # macros @testset "lie macro" begin # parameters t = 1 x = [1, 2, 3] Ξ“ = 2 Ξ³ = 1 Ξ΄ = Ξ³ - Ξ“ v = 1 # autonomous F0 = VectorField(x -> [-Ξ“ * x[1], -Ξ“ * x[2], Ξ³ * (1 - x[3])]) F1 = VectorField(x -> [0, -x[3], x[2]]) F2 = VectorField(x -> [x[3], 0, -x[1]]) F01_ = Lie(F0, F1) F011_ = Lie(F01_, F1) F01__ = @Lie [F0, F1] F011__ = @Lie [[F0, F1], F1] Test.@test F01_(x) β‰ˆ F01__(x) atol = 1e-6 Test.@test F011_(x) β‰ˆ F011__(x) atol = 1e-6 # get_F0 = () -> F0 F011___ = @Lie [[get_F0(), F1], F1] Test.@test F011_(x) β‰ˆ F011___(x) atol = 1e-6 # nonautonomous F0 = VectorField((t, x) -> [-Ξ“ * x[1], -Ξ“ * x[2], Ξ³ * (1 - x[3])], NonAutonomous) F1 = VectorField((t, x) -> [0, -x[3], x[2]], NonAutonomous) F2 = VectorField((t, x) -> [x[3], 0, -x[1]], NonAutonomous) F01_ = Lie(F0, F1) F011_ = Lie(F01_, F1) F01__ = @Lie [F0, F1] F011__ = @Lie [[F0, F1], F1] Test.@test F01_(t, x) β‰ˆ F01__(t, x) atol = 1e-6 Test.@test F011_(t, x) β‰ˆ F011__(t, x) atol = 1e-6 # get_F0 = () -> F0 F011___ = @Lie [[get_F0(), F1], F1] Test.@test F011_(t, x) β‰ˆ F011___(t, x) atol = 1e-6 # autonomous nonfixed F0 = VectorField((x, v) -> [-Ξ“ * x[1], -Ξ“ * x[2], Ξ³ * (1 - x[3])], NonFixed) F1 = VectorField((x, v) -> [0, -x[3], x[2]], NonFixed) F2 = VectorField((x, v) -> [x[3], 0, -x[1]], NonFixed) F01_ = Lie(F0, F1) F011_ = Lie(F01_, F1) F01__ = @Lie [F0, F1] F011__ = @Lie [[F0, F1], F1] Test.@test F01_(x, v) β‰ˆ F01__(x, v) atol = 1e-6 Test.@test F011_(x, v) β‰ˆ F011__(x, v) atol = 1e-6 # get_F0 = () -> F0 F011___ = @Lie [[get_F0(), F1], F1] Test.@test F011_(x, v) β‰ˆ F011___(x, v) atol = 1e-6 # nonautonomous nonfixed F0 = VectorField( (t, x, v) -> [-Ξ“ * x[1], -Ξ“ * x[2], Ξ³ * (1 - x[3])], NonAutonomous, NonFixed, ) F1 = VectorField((t, x, v) -> [0, -x[3], x[2]], NonAutonomous, NonFixed) F2 = VectorField((t, x, v) -> [x[3], 0, -x[1]], NonAutonomous, NonFixed) F01_ = Lie(F0, F1) F011_ = Lie(F01_, F1) F01__ = @Lie [F0, F1] F011__ = @Lie [[F0, F1], F1] Test.@test F01_(t, x, v) β‰ˆ F01__(t, x, v) atol = 1e-6 Test.@test F011_(t, x, v) β‰ˆ F011__(t, x, v) atol = 1e-6 # get_F0 = () -> F0 F011___ = @Lie [[get_F0(), F1], F1] Test.@test F011_(t, x, v) β‰ˆ F011___(t, x, v) atol = 1e-6 end @testset "poisson macro" begin # parameters t = 1 x = [1, 2, 3] p = [1, 0, 7] Ξ“ = 2 Ξ³ = 1 Ξ΄ = Ξ³ - Ξ“ v = 2 # autonomous H0 = Hamiltonian((x, p) -> 0.5 * (x[1]^2 + x[2]^2 + p[1]^2)) H1 = Hamiltonian((x, p) -> 0.5 * (x[1]^2 + x[2]^2 + p[2]^2)) P01 = Poisson(H0, H1) P011 = Poisson(P01, H1) P01_ = @Lie {H0, H1} P011_ = @Lie {{H0, H1}, H1} Test.@test P01(x, p) β‰ˆ P01_(x, p) atol = 1e-6 Test.@test P011(x, p) β‰ˆ P011_(x, p) atol = 1e-6 get_H0 = () -> H0 P011__ = @Lie {{get_H0(), H1}, H1} Test.@test P011_(x, p) β‰ˆ P011__(x, p) atol = 1e-6 # nonautonomous H0 = Hamiltonian((t, x, p) -> 0.5 * (x[1]^2 + x[2]^2 + p[1]^2), autonomous = false) H1 = Hamiltonian((t, x, p) -> 0.5 * (x[1]^2 + x[2]^2 + p[2]^2), NonAutonomous) P01 = Poisson(H0, H1) P011 = Poisson(P01, H1) P01_ = @Lie {H0, H1} P011_ = @Lie {{H0, H1}, H1} Test.@test P01(t, x, p) β‰ˆ P01_(t, x, p) atol = 1e-6 Test.@test P011(t, x, p) β‰ˆ P011_(t, x, p) atol = 1e-6 get_H0 = () -> H0 P011__ = @Lie {{get_H0(), H1}, H1} Test.@test P011_(t, x, p) β‰ˆ P011__(t, x, p) atol = 1e-6 # autonomous nonfixed H0 = Hamiltonian((x, p, v) -> 0.5 * (x[1]^2 + x[2]^2 + p[1]^2 + v), variable = true) H1 = Hamiltonian((x, p, v) -> 0.5 * (x[1]^2 + x[2]^2 + p[2]^2 + v), variable = true) P01 = Poisson(H0, H1) P011 = Poisson(P01, H1) P01_ = @Lie {H0, H1} P011_ = @Lie {{H0, H1}, H1} Test.@test P01(x, p, v) β‰ˆ P01_(x, p, v) atol = 1e-6 Test.@test P011(x, p, v) β‰ˆ P011_(x, p, v) atol = 1e-6 get_H0 = () -> H0 P011__ = @Lie {{get_H0(), H1}, H1} Test.@test P011_(x, p, v) β‰ˆ P011__(x, p, v) atol = 1e-6 # nonautonomous nonfixed H0 = Hamiltonian( (t, x, p, v) -> 0.5 * (x[1]^2 + x[2]^2 + p[1]^2 + v), autonomous = false, variable = true, ) H1 = Hamiltonian( (t, x, p, v) -> 0.5 * (x[1]^2 + x[2]^2 + p[2]^2 + v), NonAutonomous, NonFixed, ) P01 = Poisson(H0, H1) P011 = Poisson(P01, H1) P01_ = @Lie {H0, H1} P011_ = @Lie {{H0, H1}, H1} Test.@test P01(t, x, p, v) β‰ˆ P01_(t, x, p, v) atol = 1e-6 Test.@test P011(t, x, p, v) β‰ˆ P011_(t, x, p, v) atol = 1e-6 get_H0 = () -> H0 P011__ = @Lie {{get_H0(), H1}, H1} Test.@test P011_(t, x, p, v) β‰ˆ P011__(t, x, p, v) atol = 1e-6 end @testset "poisson macro with functions" begin # parameters t = 1 x = [1, 2, 3] p = [1, 0, 7] Ξ“ = 2 Ξ³ = 1 Ξ΄ = Ξ³ - Ξ“ v = 2 # autonomous H0 = (x, p) -> 0.5 * (x[1]^2 + x[2]^2 + p[1]^2) H1 = (x, p) -> 0.5 * (x[1]^2 + x[2]^2 + p[2]^2) P01 = Poisson(H0, H1) P011 = Poisson(P01, H1) P01_ = @Lie {H0, H1} P011_ = @Lie {{H0, H1}, H1} Test.@test P01(x, p) β‰ˆ P01_(x, p) atol = 1e-6 Test.@test P011(x, p) β‰ˆ P011_(x, p) atol = 1e-6 get_H0 = () -> H0 P011__ = @Lie {{get_H0(), H1}, H1} Test.@test P011_(x, p) β‰ˆ P011__(x, p) atol = 1e-6 # nonautonomous H0 = (t, x, p) -> 0.5 * (x[1]^2 + x[2]^2 + p[1]^2) H1 = (t, x, p) -> 0.5 * (x[1]^2 + x[2]^2 + p[2]^2) P01 = Poisson(H0, H1; autonomous = false) P011 = Poisson(P01, H1) P01_val = @Lie {H0, H1}(t, x, p) autonomous = false P01_ = @Lie {H0, H1} autonomous = false P011_ = @Lie {{H0, H1}, H1} autonomous = false Test.@test P01(t, x, p) β‰ˆ P01_(t, x, p) atol = 1e-6 Test.@test P01_val β‰ˆ P01_(t, x, p) atol = 1e-6 Test.@test P011(t, x, p) β‰ˆ P011_(t, x, p) atol = 1e-6 get_H0 = () -> H0 P011__ = @Lie {{get_H0(), H1}, H1} NonAutonomous Test.@test P011_(t, x, p) β‰ˆ P011__(t, x, p) atol = 1e-6 # autonomous nonfixed H0 = (x, p, v) -> 0.5 * (x[1]^2 + x[2]^2 + p[1]^2 + v) H1 = (x, p, v) -> 0.5 * (x[1]^2 + x[2]^2 + p[2]^2 + v) P01 = Poisson(H0, H1; variable = true) P011 = Poisson(P01, H1) P01_ = @Lie {H0, H1} variable = true P011_ = @Lie {{H0, H1}, H1} variable = true Test.@test P01(x, p, v) β‰ˆ P01_(x, p, v) atol = 1e-6 Test.@test P011(x, p, v) β‰ˆ P011_(x, p, v) atol = 1e-6 get_H0 = () -> H0 P011__ = @Lie {{get_H0(), H1}, H1} NonFixed Test.@test P011_(x, p, v) β‰ˆ P011__(x, p, v) atol = 1e-6 # nonautonomous nonfixed H0 = (t, x, p, v) -> 0.5 * (x[1]^2 + x[2]^2 + p[1]^2 + v) H1 = (t, x, p, v) -> 0.5 * (x[1]^2 + x[2]^2 + p[2]^2 + v) P01 = Poisson(H0, H1; autonomous = false, variable = true) P011 = Poisson(P01, H1) P01_ = @Lie {H0, H1} autonomous = false variable = true P011_ = @Lie {{H0, H1}, H1} NonAutonomous NonFixed Test.@test P01(t, x, p, v) β‰ˆ P01_(t, x, p, v) atol = 1e-6 Test.@test P011(t, x, p, v) β‰ˆ P011_(t, x, p, v) atol = 1e-6 get_H0 = () -> H0 P011__ = @Lie {{get_H0(), H1}, H1} NonAutonomous NonFixed Test.@test P011_(t, x, p, v) β‰ˆ P011__(t, x, p, v) atol = 1e-6 end @testset "lie and poisson macros operation (sum,diff,...)" begin # parameters t = 1 x = [1, 2, 3] p = [1, 0, 7] Ξ“ = 2 Ξ³ = 1 Ξ΄ = Ξ³ - Ξ“ v = 1 # lie # autonomous F0 = VectorField(x -> [-Ξ“ * x[1], -Ξ“ * x[2], Ξ³ * (1 - x[3])]) F1 = VectorField(x -> [0, -x[3], x[2]]) F2 = VectorField(x -> [x[3], 0, -x[1]]) Test.@test @Lie [F0, F1](x) + 4 * [F1, F2](x) == [8, -8, -2] Test.@test @Lie [F0, F1](x) - [F1, F2](x) == [-2, -3, -2] Test.@test @Lie [F0, F1](x) .* [F1, F2](x) == [0, 4, 0] Test.@test @Lie [1, 1, 1] + ([[F0, F1], F1](x) + [F1, F2](x) + [1, 1, 1]) == [4, 5, -5] # nonautonomous nonfixed F0 = VectorField( (t, x, v) -> [-Ξ“ * x[1], -Ξ“ * x[2], Ξ³ * (1 - x[3])], NonAutonomous, NonFixed, ) F1 = VectorField((t, x, v) -> [0, -x[3], x[2]], NonAutonomous, NonFixed) F2 = VectorField((t, x, v) -> [x[3], 0, -x[1]], NonAutonomous, NonFixed) Test.@test @Lie [F0, F1](t, x, v) + 4 * [F1, F2](t, x, v) == [8, -8, -2] Test.@test @Lie [F0, F1](t, x, v) - [F1, F2](t, x, v) == [-2, -3, -2] Test.@test @Lie [F0, F1](t, x, v) .* [F1, F2](t, x, v) == [0, 4, 0] Test.@test @Lie [1, 1, 1] + ([[F0, F1], F1](t, x, v) + [F1, F2](t, x, v) + [1, 1, 1]) == [4, 5, -5] # poisson # autonomous H0 = Hamiltonian((x, p) -> 0.5 * (2x[1]^2 + x[2]^2 + p[1]^2)) H1 = Hamiltonian((x, p) -> 0.5 * (3x[1]^2 + x[2]^2 + p[2]^2)) H2 = Hamiltonian((x, p) -> 0.5 * (4x[1]^2 + x[2]^2 + p[1]^3 + p[2]^2)) Test.@test @Lie {H0, H1}(x, p) + 4 * {H1, H2}(x, p) == -15 Test.@test @Lie {H0, H1}(x, p) - {H1, H2}(x, p) == 7.5 Test.@test @Lie {H0, H1}(x, p) * {H1, H2}(x, p) == -13.5 Test.@test @Lie 4 + ({{H0, H1}, H1}(x, p) + -2 * {H1, H2}(x, p) + 21) == 39 # nonautonomous nonfixed H0 = Hamiltonian( (t, x, p, v) -> 0.5 * (2x[1]^2 + x[2]^2 + p[1]^2), autonomous = false, variable = true, ) H1 = Hamiltonian( (t, x, p, v) -> 0.5 * (3x[1]^2 + x[2]^2 + p[2]^2), autonomous = false, variable = true, ) H2 = Hamiltonian( (t, x, p, v) -> 0.5 * (4x[1]^2 + x[2]^2 + p[1]^3 + p[2]^2), autonomous = false, variable = true, ) Test.@test @Lie {H0, H1}(t, x, p, v) + 4 * {H1, H2}(t, x, p, v) == -15 Test.@test @Lie {H0, H1}(t, x, p, v) - {H1, H2}(t, x, p, v) == 7.5 Test.@test @Lie {H0, H1}(t, x, p, v) * {H1, H2}(t, x, p, v) == -13.5 Test.@test @Lie 4 + ({{H0, H1}, H1}(t, x, p, v) + -2 * {H1, H2}(t, x, p, v) + 21) == 39 end end # test_differential_geometry
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
767
function test_exception() e = AmbiguousDescription((:e,)) @test_throws ErrorException error(e) @test typeof(sprint(showerror, e)) == String e = IncorrectArgument("e") @test_throws ErrorException error(e) @test typeof(sprint(showerror, e)) == String e = IncorrectMethod(:e) @test_throws ErrorException error(e) @test typeof(sprint(showerror, e)) == String e = IncorrectOutput("blabla") @test_throws ErrorException error(e) @test typeof(sprint(showerror, e)) == String e = NotImplemented("blabla") @test_throws ErrorException error(e) @test typeof(sprint(showerror, e)) == String e = ExtensionError(:tata) @test_throws ErrorException error(e) @test typeof(sprint(showerror, e)) == String end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
22145
function test_function() βˆ… = Vector{Real}() dummy_function() = nothing @testset "BoundaryConstraint" begin @test BoundaryConstraint(dummy_function, Fixed) == BoundaryConstraint(dummy_function, variable = false) @test BoundaryConstraint(dummy_function, NonFixed) == BoundaryConstraint(dummy_function, variable = true) @test_throws IncorrectArgument BoundaryConstraint( (x0, xf) -> [xf[2] - x0[1], 2xf[1] + x0[2]^2], Int64, ) B = BoundaryConstraint((x0, xf) -> [xf[2] - x0[1], 2xf[1] + x0[2]^2], variable = false) @test B([0, 0], [1, 1]) == [1, 2] @test B([0, 0], [1, 1], βˆ…) == [1, 2] B = BoundaryConstraint( (x0, xf, v) -> [v[3] + xf[2] - x0[1], v[1] - v[2] + 2xf[1] + x0[2]^2], variable = true, ) @test B([0, 0], [1, 1], [1, 2, 3]) == [4, 1] end @testset "Mayer" begin @test Mayer(dummy_function, Fixed) == Mayer(dummy_function, variable = false) @test Mayer(dummy_function, NonFixed) == Mayer(dummy_function, variable = true) @test_throws IncorrectArgument Mayer((x0, xf) -> [xf[2] - x0[1], 2xf[1] + x0[2]^2], Int64) G = Mayer((x0, xf) -> [xf[2] - x0[1]], variable = false) @test_throws MethodError G([0, 0], [1, 1]) G = Mayer((x0, xf) -> xf[2] - x0[1], variable = false) @test G([0, 0], [1, 1]) == 1 @test G([0, 0], [1, 1], βˆ…) == 1 G = Mayer((x0, xf, v) -> v[3] + xf[2] - x0[1], variable = true) @test G([0, 0], [1, 1], [1, 2, 3]) == 4 end @testset "Hamiltonian" begin @test Hamiltonian(dummy_function, Autonomous, Fixed) == Hamiltonian(dummy_function, autonomous = true, variable = false) @test Hamiltonian(dummy_function, NonAutonomous, Fixed) == Hamiltonian(dummy_function, autonomous = false, variable = false) @test Hamiltonian(dummy_function, Autonomous, NonFixed) == Hamiltonian(dummy_function, autonomous = true, variable = true) @test Hamiltonian(dummy_function, NonAutonomous, NonFixed) == Hamiltonian(dummy_function, autonomous = false, variable = true) @test_throws IncorrectArgument Hamiltonian((x, p) -> x + p, Int64) @test_throws IncorrectArgument Hamiltonian((x, p) -> x + p, Int64) H = Hamiltonian((x, p) -> [x[1]^2 + 2p[2]], autonomous = true, variable = false) @test_throws MethodError H([1, 0], [0, 1]) H = Hamiltonian((x, p) -> x[1]^2 + 2p[2], autonomous = true, variable = false) @test H([1, 0], [0, 1]) == 3 t = 1 v = Real[] @test_throws MethodError H(t, [1, 0], [0, 1]) @test_throws MethodError H([1, 0], [0, 1], v) @test H(t, [1, 0], [0, 1], v) == 3 H = Hamiltonian((x, p, v) -> x[1]^2 + 2p[2] + v[3], autonomous = true, variable = true) @test H([1, 0], [0, 1], [1, 2, 3]) == 6 @test H(t, [1, 0], [0, 1], [1, 2, 3]) == 6 H = Hamiltonian((t, x, p) -> t + x[1]^2 + 2p[2], autonomous = false, variable = false) @test H(1, [1, 0], [0, 1]) == 4 @test H(1, [1, 0], [0, 1], v) == 4 H = Hamiltonian( (t, x, p, v) -> t + x[1]^2 + 2p[2] + v[3], autonomous = false, variable = true, ) @test H(1, [1, 0], [0, 1], [1, 2, 3]) == 7 end @testset "HamiltonianVectorField" begin @test HamiltonianVectorField(dummy_function, Autonomous, Fixed) == HamiltonianVectorField(dummy_function, autonomous = true, variable = false) @test HamiltonianVectorField(dummy_function, NonAutonomous, Fixed) == HamiltonianVectorField(dummy_function, autonomous = false, variable = false) @test HamiltonianVectorField(dummy_function, Autonomous, NonFixed) == HamiltonianVectorField(dummy_function, autonomous = true, variable = true) @test HamiltonianVectorField(dummy_function, NonAutonomous, NonFixed) == HamiltonianVectorField(dummy_function, autonomous = false, variable = true) @test_throws IncorrectArgument HamiltonianVectorField( (x, p) -> ([x[1]^2 + 2p[2]], [x[2] - 3p[2]^2]), Int64, ) @test_throws IncorrectArgument HamiltonianVectorField( (x, p) -> ([x[1]^2 + 2p[2]], [x[2] - 3p[2]^2]), Int64, ) Hv = HamiltonianVectorField( (x, p) -> ([x[1]^2 + 2p[2]], [x[2] - 3p[2]^2]), autonomous = true, variable = false, ) @test Hv([1, 0], [0, 1]) == ([3], [-3]) t = 1 v = Real[] @test_throws MethodError Hv(t, [1, 0], [0, 1]) @test_throws MethodError Hv([1, 0], [0, 1], v) @test Hv(t, [1, 0], [0, 1], v) == ([3], [-3]) Hv = HamiltonianVectorField( (x, p, v) -> ([x[1]^2 + 2p[2] + v[3]], [x[2] - 3p[2]^2]), autonomous = true, variable = true, ) @test Hv([1, 0], [0, 1], [1, 2, 3]) == ([6], [-3]) @test Hv(t, [1, 0], [0, 1], [1, 2, 3]) == ([6], [-3]) Hv = HamiltonianVectorField( (t, x, p) -> ([t + x[1]^2 + 2p[2]], [x[2] - 3p[2]^2]), autonomous = false, variable = false, ) @test Hv(1, [1, 0], [0, 1]) == ([4], [-3]) @test Hv(1, [1, 0], [0, 1], v) == ([4], [-3]) Hv = HamiltonianVectorField( (t, x, p, v) -> ([t + x[1]^2 + 2p[2] + v[3]], [x[2] - 3p[2]^2]), autonomous = false, variable = true, ) @test Hv(1, [1, 0], [0, 1], [1, 2, 3]) == ([7], [-3]) end @testset "VectorField" begin @test VectorField(dummy_function, Autonomous, Fixed) == VectorField(dummy_function, autonomous = true, variable = false) @test VectorField(dummy_function, NonAutonomous, Fixed) == VectorField(dummy_function, autonomous = false, variable = false) @test VectorField(dummy_function, Autonomous, NonFixed) == VectorField(dummy_function, autonomous = true, variable = true) @test VectorField(dummy_function, NonAutonomous, NonFixed) == VectorField(dummy_function, autonomous = false, variable = true) @test_throws IncorrectArgument VectorField(x -> [x[1]^2, 2x[2]], Int64) @test_throws IncorrectArgument VectorField(x -> [x[1]^2, 2x[2]], Int64) V = VectorField(x -> [x[1]^2, 2x[2]], autonomous = true, variable = false) @test V([1, -1]) == [1, -2] t = 1 v = Real[] @test_throws MethodError V(t, [1, -1]) @test_throws MethodError V([1, -1], v) @test V(t, [1, -1], v) == [1, -2] V = VectorField((x, v) -> [x[1]^2, 2x[2] + v[3]], autonomous = true, variable = true) @test V([1, -1], [1, 2, 3]) == [1, 1] @test V(t, [1, -1], [1, 2, 3]) == [1, 1] V = VectorField((t, x) -> [t + x[1]^2, 2x[2]], autonomous = false, variable = false) @test V(1, [1, -1]) == [2, -2] @test V(1, [1, -1], v) == [2, -2] V = VectorField( (t, x, v) -> [t + x[1]^2, 2x[2] + v[3]], autonomous = false, variable = true, ) @test V(1, [1, -1], [1, 2, 3]) == [2, 1] end @testset "Lagrange" begin @test Lagrange(dummy_function, Autonomous, Fixed) == Lagrange(dummy_function, autonomous = true, variable = false) @test Lagrange(dummy_function, NonAutonomous, Fixed) == Lagrange(dummy_function, autonomous = false, variable = false) @test Lagrange(dummy_function, Autonomous, NonFixed) == Lagrange(dummy_function, autonomous = true, variable = true) @test Lagrange(dummy_function, NonAutonomous, NonFixed) == Lagrange(dummy_function, autonomous = false, variable = true) @test_throws IncorrectArgument Lagrange((x, u) -> 2x[2] - u[1]^2, Int64) @test_throws IncorrectArgument Lagrange((x, u) -> 2x[2] - u[1]^2, Int64) L = Lagrange((x, u) -> [2x[2] - u[1]^2], autonomous = true, variable = false) @test_throws MethodError L([1, 0], [1]) L = Lagrange((x, u) -> 2x[2] - u[1]^2, autonomous = true, variable = false) @test L([1, 0], [1]) == -1 t = 1 v = Real[] @test_throws MethodError L(t, [1, 0], [1]) @test_throws MethodError L([1, 0], [1], v) @test L(t, [1, 0], [1], v) == -1 L = Lagrange((x, u, v) -> 2x[2] - u[1]^2 + v[3], autonomous = true, variable = true) @test L([1, 0], [1], [1, 2, 3]) == 2 @test L(t, [1, 0], [1], [1, 2, 3]) == 2 L = Lagrange((t, x, u) -> t + 2x[2] - u[1]^2, autonomous = false, variable = false) @test L(1, [1, 0], [1]) == 0 @test L(1, [1, 0], [1], v) == 0 L = Lagrange((t, x, u, v) -> t + 2x[2] - u[1]^2 + v[3], autonomous = false, variable = true) @test L(1, [1, 0], [1], [1, 2, 3]) == 3 end @testset "Dynamics" begin @test Dynamics(dummy_function, Autonomous, Fixed) == Dynamics(dummy_function, autonomous = true, variable = false) @test Dynamics(dummy_function, NonAutonomous, Fixed) == Dynamics(dummy_function, autonomous = false, variable = false) @test Dynamics(dummy_function, Autonomous, NonFixed) == Dynamics(dummy_function, autonomous = true, variable = true) @test Dynamics(dummy_function, NonAutonomous, NonFixed) == Dynamics(dummy_function, autonomous = false, variable = true) # Similar to Lagrange, but the function Dynamics is assumed to return a vector of the same dimension as the state x. # dim x = 2, dim u = 1 # when a dim is 1, consider the element as a scalar @test_throws IncorrectArgument Dynamics((x, u) -> [2x[2] - u^2, x[1]], Int64) @test_throws IncorrectArgument Dynamics((x, u) -> [2x[2] - u^2, x[1]], Int64) D = Dynamics((x, u) -> [2x[2] - u^2, x[1]], autonomous = true, variable = false) @test D([1, 0], 1) == [-1, 1] t = 1 v = Real[] @test_throws MethodError D(t, [1, 0], 1) @test_throws MethodError D([1, 0], 1, v) @test D(t, [1, 0], 1, v) == [-1, 1] D = Dynamics((x, u, v) -> [2x[2] - u^2 + v[3], x[1]], autonomous = true, variable = true) @test D([1, 0], 1, [1, 2, 3]) == [2, 1] @test D(t, [1, 0], 1, [1, 2, 3]) == [2, 1] D = Dynamics((t, x, u) -> [t + 2x[2] - u^2, x[1]], autonomous = false, variable = false) @test D(1, [1, 0], 1) == [0, 1] @test D(1, [1, 0], 1, v) == [0, 1] D = Dynamics( (t, x, u, v) -> [t + 2x[2] - u^2 + v[3], x[1]], autonomous = false, variable = true, ) @test D(1, [1, 0], 1, [1, 2, 3]) == [3, 1] end @testset "StateConstraint" begin @test StateConstraint(dummy_function, Autonomous, Fixed) == StateConstraint(dummy_function, autonomous = true, variable = false) @test StateConstraint(dummy_function, NonAutonomous, Fixed) == StateConstraint(dummy_function, autonomous = false, variable = false) @test StateConstraint(dummy_function, Autonomous, NonFixed) == StateConstraint(dummy_function, autonomous = true, variable = true) @test StateConstraint(dummy_function, NonAutonomous, NonFixed) == StateConstraint(dummy_function, autonomous = false, variable = true) # Similar to `VectorField` in the usage, but the dimension of the output of the function StateConstraint is arbitrary. # dim x = 2 @test_throws IncorrectArgument StateConstraint(x -> [x[1]^2, 2x[2]], Int64) @test_throws IncorrectArgument StateConstraint(x -> [x[1]^2, 2x[2]], Int64) S = StateConstraint(x -> [x[1]^2, 2x[2]], autonomous = true, variable = false) @test S([1, -1]) == [1, -2] t = 1 v = Real[] @test_throws MethodError S(t, [1, -1]) @test_throws MethodError S([1, -1], v) @test S(t, [1, -1], v) == [1, -2] S = StateConstraint((x, v) -> [x[1]^2, 2x[2] + v[3]], autonomous = true, variable = true) @test S([1, -1], [1, 2, 3]) == [1, 1] @test S(t, [1, -1], [1, 2, 3]) == [1, 1] S = StateConstraint((t, x) -> [t + x[1]^2, 2x[2]], autonomous = false, variable = false) @test S(1, [1, -1]) == [2, -2] @test S(1, [1, -1], v) == [2, -2] S = StateConstraint( (t, x, v) -> [t + x[1]^2, 2x[2] + v[3]], autonomous = false, variable = true, ) @test S(1, [1, -1], [1, 2, 3]) == [2, 1] end @testset "ControlConstraint" begin @test ControlConstraint(dummy_function, Autonomous, Fixed) == ControlConstraint(dummy_function, autonomous = true, variable = false) @test ControlConstraint(dummy_function, NonAutonomous, Fixed) == ControlConstraint(dummy_function, autonomous = false, variable = false) @test ControlConstraint(dummy_function, Autonomous, NonFixed) == ControlConstraint(dummy_function, autonomous = true, variable = true) @test ControlConstraint(dummy_function, NonAutonomous, NonFixed) == ControlConstraint(dummy_function, autonomous = false, variable = true) # Similar to `VectorField` in the usage, but the dimension of the output of the function ControlConstraint is arbitrary. # dim u = 2 @test_throws IncorrectArgument ControlConstraint(u -> [u[1]^2, 2u[2]], Int64) @test_throws IncorrectArgument ControlConstraint(u -> [u[1]^2, 2u[2]], Int64) C = ControlConstraint(u -> [u[1]^2, 2u[2]], autonomous = true, variable = false) @test C([1, -1]) == [1, -2] t = 1 v = Real[] @test_throws MethodError C(t, [1, -1]) @test_throws MethodError C([1, -1], v) @test C(t, [1, -1], v) == [1, -2] C = ControlConstraint((u, v) -> [u[1]^2, 2u[2] + v[3]], autonomous = true, variable = true) @test C([1, -1], [1, 2, 3]) == [1, 1] @test C(t, [1, -1], [1, 2, 3]) == [1, 1] C = ControlConstraint((t, u) -> [t + u[1]^2, 2u[2]], autonomous = false, variable = false) @test C(1, [1, -1]) == [2, -2] @test C(1, [1, -1], v) == [2, -2] C = ControlConstraint( (t, u, v) -> [t + u[1]^2, 2u[2] + v[3]], autonomous = false, variable = true, ) @test C(1, [1, -1], [1, 2, 3]) == [2, 1] end @testset "MixedConstraint" begin @test MixedConstraint(dummy_function, Autonomous, Fixed) == MixedConstraint(dummy_function, autonomous = true, variable = false) @test MixedConstraint(dummy_function, NonAutonomous, Fixed) == MixedConstraint(dummy_function, autonomous = false, variable = false) @test MixedConstraint(dummy_function, Autonomous, NonFixed) == MixedConstraint(dummy_function, autonomous = true, variable = true) @test MixedConstraint(dummy_function, NonAutonomous, NonFixed) == MixedConstraint(dummy_function, autonomous = false, variable = true) # Similar to `Lagrange` in the usage, but the dimension of the output of the function MixedConstraint is arbitrary. # dim x = 2, dim u = 1, dim output = 2 @test_throws IncorrectArgument MixedConstraint((x, u) -> [2x[2] - u^2, x[1]], Int64) @test_throws IncorrectArgument MixedConstraint((x, u) -> [2x[2] - u^2, x[1]], Int64) M = MixedConstraint((x, u) -> [2x[2] - u^2, x[1]], autonomous = true, variable = false) @test M([1, 0], 1) == [-1, 1] t = 1 v = Real[] @test_throws MethodError M(t, [1, 0], 1) @test_throws MethodError M([1, 0], 1, v) @test M(t, [1, 0], 1, v) == [-1, 1] M = MixedConstraint( (x, u, v) -> [2x[2] - u^2 + v[3], x[1]], autonomous = true, variable = true, ) @test M([1, 0], 1, [1, 2, 3]) == [2, 1] @test M(t, [1, 0], 1, [1, 2, 3]) == [2, 1] M = MixedConstraint( (t, x, u) -> [t + 2x[2] - u^2, x[1]], autonomous = false, variable = false, ) @test M(1, [1, 0], 1) == [0, 1] @test M(1, [1, 0], 1, v) == [0, 1] M = MixedConstraint( (t, x, u, v) -> [t + 2x[2] - u^2 + v[3], x[1]], autonomous = false, variable = true, ) @test M(1, [1, 0], 1, [1, 2, 3]) == [3, 1] end @testset "VariableConstraint" begin V = VariableConstraint(v -> [v[1]^2, 2v[2]]) @test V([1, -1]) == [1, -2] end @testset "FeedbackControl" begin @test FeedbackControl(dummy_function, Autonomous, Fixed) == FeedbackControl(dummy_function, autonomous = true, variable = false) @test FeedbackControl(dummy_function, NonAutonomous, Fixed) == FeedbackControl(dummy_function, autonomous = false, variable = false) @test FeedbackControl(dummy_function, Autonomous, NonFixed) == FeedbackControl(dummy_function, autonomous = true, variable = true) @test FeedbackControl(dummy_function, NonAutonomous, NonFixed) == FeedbackControl(dummy_function, autonomous = false, variable = true) # Similar to `VectorField` in the usage, but the dimension of the output of the function `f` is arbitrary. # dim x = 2, dim output = 1 @test_throws IncorrectArgument FeedbackControl(x -> x[1]^2 + 2x[2], Int64) @test_throws IncorrectArgument FeedbackControl(x -> x[1]^2 + 2x[2], Int64) u = FeedbackControl(x -> x[1]^2 + 2x[2], autonomous = true, variable = false) @test u([1, 0]) == 1 t = 1 v = Real[] @test_throws MethodError u(t, [1, 0]) @test_throws MethodError u([1, 0], v) @test u(t, [1, 0], v) == 1 u = FeedbackControl((x, v) -> x[1]^2 + 2x[2] + v[3], autonomous = true, variable = true) @test u([1, 0], [1, 2, 3]) == 4 @test u(t, [1, 0], [1, 2, 3]) == 4 u = FeedbackControl((t, x) -> t + x[1]^2 + 2x[2], autonomous = false, variable = false) @test u(1, [1, 0]) == 2 @test u(1, [1, 0], v) == 2 u = FeedbackControl( (t, x, v) -> t + x[1]^2 + 2x[2] + v[3], autonomous = false, variable = true, ) @test u(1, [1, 0], [1, 2, 3]) == 5 end @testset "ControlLaw" begin @test ControlLaw(dummy_function, Autonomous, Fixed) == ControlLaw(dummy_function, autonomous = true, variable = false) @test ControlLaw(dummy_function, NonAutonomous, Fixed) == ControlLaw(dummy_function, autonomous = false, variable = false) @test ControlLaw(dummy_function, Autonomous, NonFixed) == ControlLaw(dummy_function, autonomous = true, variable = true) @test ControlLaw(dummy_function, NonAutonomous, NonFixed) == ControlLaw(dummy_function, autonomous = false, variable = true) # Similar to `Hamiltonian` in the usage, but the dimension of the output of the function `ControlLaw` is arbitrary. # dim x = 2, dim p =2, dim output = 1 @test_throws IncorrectArgument ControlLaw((x, p) -> x[1]^2 + 2p[2], Int64) @test_throws IncorrectArgument ControlLaw((x, p) -> x[1]^2 + 2p[2], Int64) u = ControlLaw((x, p) -> x[1]^2 + 2p[2], autonomous = true, variable = false) @test u([1, 0], [0, 1]) == 3 t = 1 v = Real[] @test_throws MethodError u(t, [1, 0], [0, 1]) @test_throws MethodError u([1, 0], [0, 1], v) @test u(t, [1, 0], [0, 1], v) == 3 u = ControlLaw((x, p, v) -> x[1]^2 + 2p[2] + v[3], autonomous = true, variable = true) @test u([1, 0], [0, 1], [1, 2, 3]) == 6 @test u(t, [1, 0], [0, 1], [1, 2, 3]) == 6 u = ControlLaw((t, x, p) -> t + x[1]^2 + 2p[2], autonomous = false, variable = false) @test u(1, [1, 0], [0, 1]) == 4 @test u(1, [1, 0], [0, 1], v) == 4 u = ControlLaw( (t, x, p, v) -> t + x[1]^2 + 2p[2] + v[3], autonomous = false, variable = true, ) @test u(1, [1, 0], [0, 1], [1, 2, 3]) == 7 end @testset "Multiplier" begin @test Multiplier(dummy_function, Autonomous, Fixed) == Multiplier(dummy_function, autonomous = true, variable = false) @test Multiplier(dummy_function, NonAutonomous, Fixed) == Multiplier(dummy_function, autonomous = false, variable = false) @test Multiplier(dummy_function, Autonomous, NonFixed) == Multiplier(dummy_function, autonomous = true, variable = true) @test Multiplier(dummy_function, NonAutonomous, NonFixed) == Multiplier(dummy_function, autonomous = false, variable = true) # Similar to `ControlLaw` in the usage. # dim x = 2, dim p =2, dim output = 1 @test_throws IncorrectArgument Multiplier((x, p) -> x[1]^2 + 2p[2], Int64) @test_throws IncorrectArgument Multiplier((x, p) -> x[1]^2 + 2p[2], Int64) ΞΌ = Multiplier((x, p) -> x[1]^2 + 2p[2], autonomous = true, variable = false) @test ΞΌ([1, 0], [0, 1]) == 3 t = 1 v = Real[] @test_throws MethodError ΞΌ(t, [1, 0], [0, 1]) @test_throws MethodError ΞΌ([1, 0], [0, 1], v) @test ΞΌ(t, [1, 0], [0, 1], v) == 3 ΞΌ = Multiplier((x, p, v) -> x[1]^2 + 2p[2] + v[3], autonomous = true, variable = true) @test ΞΌ([1, 0], [0, 1], [1, 2, 3]) == 6 @test ΞΌ(t, [1, 0], [0, 1], [1, 2, 3]) == 6 ΞΌ = Multiplier((t, x, p) -> t + x[1]^2 + 2p[2], autonomous = false, variable = false) @test ΞΌ(1, [1, 0], [0, 1]) == 4 @test ΞΌ(1, [1, 0], [0, 1], v) == 4 ΞΌ = Multiplier( (t, x, p, v) -> t + x[1]^2 + 2p[2] + v[3], autonomous = false, variable = true, ) @test ΞΌ(1, [1, 0], [0, 1], [1, 2, 3]) == 7 end end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
998
test_goddard() = begin # Parameters Cd = 310 Tmax = 3.5 Ξ² = 500 b = 2 t0 = 0 r0 = 1 v0 = 0 vmax = 0.1 m0 = 1 mf = 0.6 x0 = [r0, v0, m0] # Abstract model @def ocp begin tf ∈ R, variable t ∈ [t0, tf], time x ∈ RΒ³, state u ∈ R, control r = x₁ v = xβ‚‚ m = x₃ x(t0) == [r0, v0, m0] 0 ≀ u(t) ≀ 1 r(t) β‰₯ 0, (1) 0 ≀ v(t) ≀ vmax, (2) mf ≀ m(t) ≀ m0, (3) D = Cd * vΒ² * exp(-Ξ² * (r - 1)) xΜ‡(t) == [v(t), -D(t) / m(t) - 1 / rΒ²(t), 0] + u(t) * [0, Tmax / m(t), -b * Tmax] r(tf) β†’ max end F0(x) = begin r, v, m = x D = Cd * v^2 * exp(-Ξ² * (r - 1)) F = [v, -D / m - 1 / r^2, 0] return F end F1(x) = begin r, v, m = x F = [0, Tmax / m, -b * Tmax] return F end x = x0 u = 2 tf = 1 @test __dynamics(ocp)(x, u, tf) == F0(x) + u * F1(x) end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
82474
function test_model() # 30 55 185 βˆ… = Vector{Real}() @testset "is_in_place" begin ocp = Model() @test !is_in_place(ocp) ocp = Model(; in_place = false) @test !is_in_place(ocp) ocp = Model(; in_place = true) @test is_in_place(ocp) ocp = Model(; autonomous = true, variable = true) @test !is_in_place(ocp) ocp = Model(; autonomous = true, variable = true, in_place = false) @test !is_in_place(ocp) ocp = Model(; autonomous = true, variable = true, in_place = true) @test is_in_place(ocp) ocp = Model(; autonomous = false, variable = true) @test !is_in_place(ocp) ocp = Model(; autonomous = false, variable = true, in_place = false) @test !is_in_place(ocp) ocp = Model(; autonomous = false, variable = true, in_place = true) @test is_in_place(ocp) ocp = Model(; autonomous = true, variable = false) @test !is_in_place(ocp) ocp = Model(; autonomous = true, variable = false, in_place = false) @test !is_in_place(ocp) ocp = Model(; autonomous = true, variable = false, in_place = true) @test is_in_place(ocp) ocp = Model(; autonomous = false, variable = false) @test !is_in_place(ocp) ocp = Model(; autonomous = false, variable = false, in_place = false) @test !is_in_place(ocp) ocp = Model(; autonomous = false, variable = false, in_place = true) @test is_in_place(ocp) end @testset "variable!" begin ocp = Model(variable = false) @test_throws UnauthorizedCall variable!(ocp, 1) @test_throws UnauthorizedCall constraint!( ocp, :variable, rg = 2:3, lb = [0, 3], ub = [0, 3], ) @test_throws UnauthorizedCall constraint!(ocp, :variable, lb = 0, ub = 1) # the variable here is of dimension 1 @test_throws UnauthorizedCall constraint!( ocp, :variable, rg = 1:2, lb = [0, 0], ub = [1, 2], ) @test_throws UnauthorizedCall constraint!(ocp, :variable, lb = [3, 0, 1], ub = [3, 0, 1]) ocp = Model(variable = true) variable!(ocp, 1) @test variable_dimension(ocp) == 1 ocp = Model(variable = true) variable!(ocp, 1, "vv") @test is_variable_dependent(ocp) @test variable_dimension(ocp) == 1 @test variable_components_names(ocp) == ["vv"] ocp = Model(variable = true) variable!(ocp, 1, :vv) @test variable_dimension(ocp) == 1 @test variable_components_names(ocp) == ["vv"] ocp = Model(variable = true) variable!(ocp, 2) @test variable_dimension(ocp) == 2 ocp = Model(variable = true) variable!(ocp, 2, "vv") @test variable_dimension(ocp) == 2 @test variable_components_names(ocp) == ["vv₁", "vvβ‚‚"] ocp = Model(variable = true) variable!(ocp, 2, "uu", ["vv₁", "vvβ‚‚"]) @test variable_dimension(ocp) == 2 @test variable_components_names(ocp) == ["vv₁", "vvβ‚‚"] ocp = Model(variable = true) @test_throws MethodError variable!(ocp, 2, ["vv1", "vv2"]) ocp = Model(variable = true) variable!(ocp, 2, :vv) @test variable_dimension(ocp) == 2 @test variable_components_names(ocp) == ["vv₁", "vvβ‚‚"] end @testset "time, state and control set or not" begin for i ∈ 1:7 ocp = Model() i == 2 && begin time!(ocp; t0 = 0, tf = 1) end i == 3 && begin state!(ocp, 2) end i == 4 && begin control!(ocp, 1) end i == 5 && begin time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) end i == 6 && begin time!(ocp; t0 = 0, tf = 1) control!(ocp, 1) end i == 7 && begin state!(ocp, 2) control!(ocp, 1) end # constraint! 1 @test_throws UnauthorizedCall constraint!( ocp, :initial, rg = 1:2:5, lb = [0, 0, 0], ub = [0, 0, 0], ) @test_throws UnauthorizedCall constraint!( ocp, :initial, rg = 2:3, lb = [0, 0], ub = [0, 0], ) @test_throws UnauthorizedCall constraint!(ocp, :final, rg = 2, lb = 0, ub = 0) # constraint! 2 @test_throws UnauthorizedCall constraint!(ocp, :initial, lb = [0, 0], ub = [0, 0]) @test_throws UnauthorizedCall constraint!(ocp, :final, lb = 2, ub = 2) # if the state is of dimension 1 # constraint! 3 @test_throws UnauthorizedCall constraint!( ocp, :initial, rg = 2:3, lb = [0, 0], ub = [1, 2], ) @test_throws UnauthorizedCall constraint!(ocp, :final, rg = 1, lb = 0, ub = 2) @test_throws UnauthorizedCall constraint!(ocp, :control, rg = 1, lb = 0, ub = 2) @test_throws UnauthorizedCall constraint!( ocp, :state, rg = 2:3, lb = [0, 0], ub = [1, 2], ) @test_throws UnauthorizedCall constraint!( ocp, :initial, rg = 1:2:5, lb = [0, 0, 0], ub = [1, 2, 1], ) # constraint! 4 @test_throws UnauthorizedCall constraint!(ocp, :initial, lb = [0, 0, 0], ub = [1, 2, 1]) @test_throws UnauthorizedCall constraint!(ocp, :final, lb = [0, 0, 0], ub = [1, 2, 1]) @test_throws UnauthorizedCall constraint!(ocp, :control, lb = [0, 0], ub = [2, 3]) @test_throws UnauthorizedCall constraint!(ocp, :state, lb = [0, 0, 0], ub = [1, 2, 1]) # constraint! 5 # variable independent ocp @test_throws UnauthorizedCall constraint!( ocp, :boundary, f = (x0, xf) -> x0[3] + xf[2], lb = 0, ub = 1, ) # variable dependent ocp @test_throws UnauthorizedCall constraint!( ocp, :boundary, f = (x0, xf, v) -> x0[3] + xf[2] * v[1], lb = 0, ub = 1, ) # time independent and variable independent ocp @test_throws UnauthorizedCall constraint!(ocp, :control, f = u -> 2u, lb = 0, ub = 1) @test_throws UnauthorizedCall constraint!( ocp, :state, f = x -> x - 1, lb = [0, 0, 0], ub = [1, 2, 1], ) @test_throws UnauthorizedCall constraint!( ocp, :mixed, f = (x, u) -> x[1] - u, lb = 0, ub = 1, ) # time dependent and variable independent ocp @test_throws UnauthorizedCall constraint!( ocp, :control, f = (t, u) -> 2u, lb = 0, ub = 1, ) @test_throws UnauthorizedCall constraint!( ocp, :state, f = (t, x) -> x - t, lb = [0, 0, 0], ub = [1, 2, 1], ) @test_throws UnauthorizedCall constraint!( ocp, :mixed, f = (t, x, u) -> x[1] - u, lb = 0, ub = 1, ) # time independent and variable dependent ocp @test_throws UnauthorizedCall constraint!( ocp, :control, f = (u, v) -> 2u * v[1], lb = 0, ub = 1, ) @test_throws UnauthorizedCall constraint!( ocp, :state, f = (x, v) -> x - v[1], lb = [0, 0, 0], ub = [1, 2, 1], ) @test_throws UnauthorizedCall constraint!( ocp, :mixed, f = (x, u, v) -> x[1] - v[2] * u, lb = 0, ub = 1, ) # time dependent and variable dependent ocp @test_throws UnauthorizedCall constraint!( ocp, :control, f = (t, u, v) -> 2u + v[2], lb = 0, ub = 1, ) @test_throws UnauthorizedCall constraint!( ocp, :state, f = (t, x, v) -> x - t * v[1], lb = [0, 0, 0], ub = [1, 2, 1], ) @test_throws UnauthorizedCall constraint!( ocp, :mixed, f = (t, x, u, v) -> x[1] * v[2] - u, lb = 0, ub = 1, ) # constraint! 6 # variable independent ocp @test_throws UnauthorizedCall constraint!( ocp, :boundary, f = (x0, xf) -> x0[3] + xf[2], lb = 0, ub = 0, ) # variable dependent ocp @test_throws UnauthorizedCall constraint!( ocp, :boundary, f = (x0, xf, v) -> x0[3] + xf[2] * v[1], lb = 0, ub = 0, ) # time independent and variable independent ocp @test_throws UnauthorizedCall constraint!(ocp, :control, f = u -> 2u, lb = 1, ub = 1) @test_throws UnauthorizedCall constraint!( ocp, :state, f = x -> x - 1, lb = [0, 0, 0], ub = [0, 0, 0], ) @test_throws UnauthorizedCall constraint!( ocp, :mixed, f = (x, u) -> x[1] - u, lb = 0, ub = 0, ) # time dependent and variable independent ocp @test_throws UnauthorizedCall constraint!( ocp, :control, f = (t, u) -> 2u, lb = 1, ub = 1, ) @test_throws UnauthorizedCall constraint!( ocp, :state, f = (t, x) -> x - t, lb = [0, 0, 0], ub = [0, 0, 0], ) @test_throws UnauthorizedCall constraint!( ocp, :mixed, f = (t, x, u) -> x[1] - u, lb = 0, ub = 0, ) # time independent and variable dependent ocp @test_throws UnauthorizedCall constraint!( ocp, :control, f = (u, v) -> 2u * v[1], lb = 1, ub = 1, ) @test_throws UnauthorizedCall constraint!( ocp, :state, f = (x, v) -> x - v[2], lb = [0, 0, 0], ub = [0, 0, 0], ) @test_throws UnauthorizedCall constraint!( ocp, :mixed, f = (x, u) -> x[1] - u + v[1], lb = 0, ub = 0, ) # time dependent and variable dependent ocp @test_throws UnauthorizedCall constraint!( ocp, :control, f = (t, u, v) -> 2u - t * v[2], lb = 1, ub = 1, ) @test_throws UnauthorizedCall constraint!( ocp, :state, f = (t, x, v) -> x - t + v[1], lb = [0, 0, 0], ub = [0, 0, 0], ) @test_throws UnauthorizedCall constraint!( ocp, :mixed, f = (t, x, u, v) -> x[1] - u * v[1], lb = 0, ub = 0, ) end end @testset "initial and / or final time already set" begin ocp = Model(variable = true) @test !CTBase.__is_time_set(ocp) variable!(ocp, 1) time!(ocp; t0 = 0, indf = 1) @test CTBase.__is_time_set(ocp) ocp = Model(variable = true) variable!(ocp, 1) time!(ocp; ind0 = 1, tf = 1) @test CTBase.__is_time_set(ocp) ocp = Model() time!(ocp; t0 = 0, tf = 1) @test CTBase.__is_time_set(ocp) ocp = Model() @test_throws MethodError time!(ocp; t0 = 0, indf = 1) @test_throws MethodError time!(ocp; ind0 = 1, tf = 1) ocp = Model(variable = true) @test_throws UnauthorizedCall time!(ocp; t0 = 0, indf = 1) @test_throws UnauthorizedCall time!(ocp; ind0 = 1, tf = 1) ocp = Model(variable = true) variable!(ocp, 1) time!(ocp; t0 = 0, indf = 1) @test_throws UnauthorizedCall time!(ocp; t0 = 0, indf = 1) @test_throws UnauthorizedCall time!(ocp; ind0 = 1, tf = 1) @test_throws UnauthorizedCall time!(ocp; t0 = 0, tf = 1) ocp = Model(variable = true) variable!(ocp, 1) time!(ocp; ind0 = 1, tf = 1) @test_throws UnauthorizedCall time!(ocp; t0 = 0, indf = 1) @test_throws UnauthorizedCall time!(ocp; ind0 = 1, tf = 1) @test_throws UnauthorizedCall time!(ocp; t0 = 0, tf = 1) ocp = Model(variable = true) @test_throws UnauthorizedCall time!(ocp; t0 = 0, indf = 1) @test_throws UnauthorizedCall time!(ocp; ind0 = 1, tf = 1) ocp = Model(variable = true) time!(ocp; t0 = 0, tf = 1) @test_throws UnauthorizedCall time!(ocp; t0 = 0, indf = 1) @test_throws UnauthorizedCall time!(ocp; ind0 = 1, tf = 1) end @testset "Index" begin @test Index(1) == Index(1) @test Index(1) ≀ Index(2) @test Index(1) < Index(2) v = [10, 20] @test v[Index(1)] == v[1] @test_throws MethodError v[Index(1):Index(2)] x = 1 @test x[Index(1)] == x end @testset "time and variable dependence" begin ocp = Model() @test is_autonomous(ocp) @test is_fixed(ocp) @test is_time_independent(ocp) @test !is_time_dependent(ocp) @test is_variable_independent(ocp) @test !is_variable_dependent(ocp) ocp = Model(autonomous = false) @test !is_autonomous(ocp) @test is_fixed(ocp) @test is_time_dependent(ocp) @test !is_time_independent(ocp) @test is_variable_independent(ocp) @test !is_variable_dependent(ocp) ocp = Model(variable = true) @test is_autonomous(ocp) @test !is_fixed(ocp) @test is_time_independent(ocp) @test !is_time_dependent(ocp) @test is_variable_dependent(ocp) @test !is_variable_independent(ocp) ocp = Model(autonomous = false, variable = true) @test !is_autonomous(ocp) @test !is_fixed(ocp) @test is_time_dependent(ocp) @test !is_time_independent(ocp) @test is_variable_dependent(ocp) @test !is_variable_independent(ocp) end @testset "time and variable dependence bis" begin ocp = Model() @test is_autonomous(ocp) @test is_fixed(ocp) @test is_time_independent(ocp) @test !is_time_dependent(ocp) @test is_variable_independent(ocp) @test !is_variable_dependent(ocp) ocp = Model(NonAutonomous) @test !is_autonomous(ocp) @test is_fixed(ocp) @test is_time_dependent(ocp) @test !is_time_independent(ocp) @test is_variable_independent(ocp) @test !is_variable_dependent(ocp) ocp = Model(NonFixed) @test is_autonomous(ocp) @test !is_fixed(ocp) @test is_time_independent(ocp) @test !is_time_dependent(ocp) @test is_variable_dependent(ocp) @test !is_variable_independent(ocp) ocp = Model(NonAutonomous, NonFixed) @test !is_autonomous(ocp) @test !is_fixed(ocp) @test is_time_dependent(ocp) @test !is_time_independent(ocp) @test is_variable_dependent(ocp) @test !is_variable_independent(ocp) ocp = Model(NonFixed, NonAutonomous) @test !is_autonomous(ocp) @test !is_fixed(ocp) @test is_time_dependent(ocp) @test !is_time_independent(ocp) @test is_variable_dependent(ocp) @test !is_variable_independent(ocp) @test_throws IncorrectArgument Model(NonFixed, NonAutonomous, Autonomous) @test_throws IncorrectArgument Model(NonFixed, NonAutonomous, Autonomous) @test_throws IncorrectArgument Model(NonAutonomous, Autonomous) @test_throws IncorrectArgument Model(NonFixed, Int64) @test_throws IncorrectArgument Model(NonFixed, Int64) end @testset "time and variable dependence Bool" begin ocp = Model() @test is_autonomous(ocp) @test is_fixed(ocp) @test is_time_independent(ocp) @test !is_time_dependent(ocp) @test is_variable_independent(ocp) @test !is_variable_dependent(ocp) ocp = Model(NonAutonomous) @test !is_autonomous(ocp) @test is_fixed(ocp) @test is_time_dependent(ocp) @test !is_time_independent(ocp) @test is_variable_independent(ocp) @test !is_variable_dependent(ocp) ocp = Model(NonFixed) @test is_autonomous(ocp) @test !is_fixed(ocp) @test is_time_independent(ocp) @test !is_time_dependent(ocp) @test is_variable_dependent(ocp) @test !is_variable_independent(ocp) ocp = Model(NonAutonomous, NonFixed) @test !is_autonomous(ocp) @test !is_fixed(ocp) @test is_time_dependent(ocp) @test !is_time_independent(ocp) @test is_variable_dependent(ocp) @test !is_variable_independent(ocp) ocp = Model(NonFixed, NonAutonomous) @test !is_autonomous(ocp) @test !is_fixed(ocp) @test is_time_dependent(ocp) @test !is_time_independent(ocp) @test is_variable_dependent(ocp) @test !is_variable_independent(ocp) @test_throws IncorrectArgument Model(NonFixed, NonAutonomous, Autonomous) @test_throws IncorrectArgument Model(NonFixed, NonAutonomous, Autonomous) @test_throws IncorrectArgument Model(NonAutonomous, Autonomous) @test_throws IncorrectArgument Model(NonFixed, Int64) @test_throws IncorrectArgument Model(NonFixed, Int64) end @testset "state!" begin ocp = Model() state!(ocp, 1) @test state_dimension(ocp) == 1 @test state_components_names(ocp) == ["x"] ocp = Model() state!(ocp, 1, "y") @test state_dimension(ocp) == 1 @test state_components_names(ocp) == ["y"] ocp = Model() state!(ocp, 2) @test state_dimension(ocp) == 2 @test state_components_names(ocp) == ["x₁", "xβ‚‚"] ocp = Model() @test_throws MethodError state!(ocp, 2, ["y₁", "yβ‚‚"]) ocp = Model() state!(ocp, 2, :y) @test state_dimension(ocp) == 2 @test state_components_names(ocp) == ["y₁", "yβ‚‚"] ocp = Model() state!(ocp, 2, "y") @test state_dimension(ocp) == 2 @test state_components_names(ocp) == ["y₁", "yβ‚‚"] ocp = Model() state!(ocp, 2, "y", ["z₁", "zβ‚‚"]) @test state_dimension(ocp) == 2 @test state_components_names(ocp) == ["z₁", "zβ‚‚"] end @testset "control!" begin ocp = Model() control!(ocp, 1) @test control_dimension(ocp) == 1 @test control_components_names(ocp) == ["u"] ocp = Model() control!(ocp, 1, "v") @test control_dimension(ocp) == 1 @test control_components_names(ocp) == ["v"] ocp = Model() control!(ocp, 2) @test control_dimension(ocp) == 2 @test control_components_names(ocp) == ["u₁", "uβ‚‚"] ocp = Model() @test_throws MethodError control!(ocp, 2, ["v₁", "vβ‚‚"]) ocp = Model() control!(ocp, 2, :v) @test control_dimension(ocp) == 2 @test control_components_names(ocp) == ["v₁", "vβ‚‚"] ocp = Model() control!(ocp, 2, "v") @test control_dimension(ocp) == 2 @test control_components_names(ocp) == ["v₁", "vβ‚‚"] ocp = Model() control!(ocp, 2, "u", ["v₁", "vβ‚‚"]) @test control_dimension(ocp) == 2 @test control_components_names(ocp) == ["v₁", "vβ‚‚"] end @testset "time!" begin # initial and final times ocp = Model() time!(ocp; t0 = 0, tf = 1) @test !CTBase.__is_initial_time_free(ocp) @test !CTBase.__is_final_time_free(ocp) @test initial_time(ocp) == 0 @test final_time(ocp) == 1 @test time_name(ocp) == "t" ocp = Model() time!(ocp; t0 = 0, tf = 1, name = "s") @test initial_time(ocp) == 0 @test final_time(ocp) == 1 @test time_name(ocp) == "s" ocp = Model() time!(ocp; t0 = 0, tf = 1, name = :s) @test initial_time(ocp) == 0 @test final_time(ocp) == 1 @test time_name(ocp) == "s" # initial time ocp = Model(variable = true) variable!(ocp, 1) time!(ocp; t0 = 0, indf = 1) @test !CTBase.__is_initial_time_free(ocp) @test CTBase.__is_final_time_free(ocp) @test initial_time(ocp) == 0 @test final_time(ocp) == Index(1) @test time_name(ocp) == "t" ocp = Model(variable = true) variable!(ocp, 1) time!(ocp; t0 = 0, indf = 1, name = "s") @test initial_time(ocp) == 0 @test final_time(ocp) == Index(1) @test time_name(ocp) == "s" ocp = Model(variable = true) variable!(ocp, 1) time!(ocp; t0 = 0, indf = 1, name = :s) @test initial_time(ocp) == 0 @test final_time(ocp) == Index(1) @test time_name(ocp) == "s" # final time ocp = Model(variable = true) variable!(ocp, 1) time!(ocp; ind0 = 1, tf = 1) @test CTBase.__is_initial_time_free(ocp) @test !CTBase.__is_final_time_free(ocp) @test initial_time(ocp) == Index(1) @test final_time(ocp) == 1 @test time_name(ocp) == "t" ocp = Model(variable = true) variable!(ocp, 1) time!(ocp; ind0 = 1, tf = 1, name = "s") @test initial_time(ocp) == Index(1) @test final_time(ocp) == 1 @test time_name(ocp) == "s" ocp = Model(variable = true) variable!(ocp, 1) time!(ocp; ind0 = 1, tf = 1, name = :s) @test initial_time(ocp) == Index(1) @test final_time(ocp) == 1 @test time_name(ocp) == "s" end @testset "is_min vs is_max" begin ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) objective!(ocp, :mayer, (x0, xf) -> x0[1] + xf[2]) @test is_min(ocp) @test !is_max(ocp) ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) objective!(ocp, :mayer, (x0, xf) -> x0[1] + xf[2], :max) @test is_max(ocp) @test !is_min(ocp) ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) objective!(ocp, :lagrange, (x, u) -> 0.5u^2) @test is_min(ocp) @test !is_max(ocp) ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) objective!(ocp, :lagrange, (x, u) -> 0.5u^2, :max) @test is_max(ocp) @test !is_min(ocp) ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) objective!(ocp, :bolza, (x0, xf) -> x0[1] + xf[2], (x, u) -> x[1]^2 + u^2) # the control is of dimension 1 @test is_min(ocp) @test !is_max(ocp) ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) objective!(ocp, :bolza, (x0, xf) -> x0[1] + xf[2], (x, u) -> x[1]^2 + u^2, :max) # the control is of dimension 1 @test is_max(ocp) @test !is_min(ocp) end @testset "constraint! 1" begin ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) @test_throws IncorrectArgument constraint!( ocp, :initial, lb = [0, 1], ub = [0, 1], label = :c0, ) constraint!(ocp, :initial, lb = 0, ub = 0, label = :c0) constraint!(ocp, :final, lb = 1, ub = 1, label = :cf) @test constraint(ocp, :c0)(12, βˆ…) == 12 @test constraint(ocp, :cf)(βˆ…, 12) == 12 ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) constraint!(ocp, :initial, lb = [0, 1], ub = [0, 1], label = :c0) constraint!(ocp, :final, lb = [1, 2], ub = [1, 2], label = :cf) @test constraint(ocp, :c0)([12, 13], βˆ…) == [12, 13] @test constraint(ocp, :cf)(βˆ…, [12, 13]) == [12, 13] # constraint already exists ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) constraint!(ocp, :initial, lb = 0, ub = 0, label = :c) @test_throws UnauthorizedCall constraint!(ocp, :final, lb = 0, ub = 0, label = :c) end @testset "constraint! 2" begin ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) x = 12 x0 = 0 xf = 1 constraint!(ocp, :initial, rg = 1, lb = x0, ub = x0, label = :c0) constraint!(ocp, :final, rg = 1, lb = xf, ub = xf, label = :cf) @test constraint(ocp, :c0)(x, βˆ…) == x @test constraint(ocp, :cf)(βˆ…, x) == x constraint!(ocp, :initial, rg = 1, lb = x0, ub = x0, label = :c00) constraint!(ocp, :final, rg = 1, lb = xf, ub = xf, label = :cff) @test constraint(ocp, :c00)(x, βˆ…) == x @test constraint(ocp, :cff)(βˆ…, x) == x ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) x = [12, 13] x0 = [0, 1] xf = [1, 2] @test_throws IncorrectArgument constraint!( ocp, :initial, rg = 2, lb = x0, ub = x0, label = :c0, ) @test_throws IncorrectArgument constraint!( ocp, :final, rg = 2, lb = xf, ub = xf, label = :cf, ) ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) x = [12, 13] x0 = [0, 1] xf = [1, 2] constraint!(ocp, :initial, rg = 1:2, lb = x0, ub = x0, label = :c0) constraint!(ocp, :final, rg = 1:2, lb = xf, ub = xf, label = :cf) @test constraint(ocp, :c0)(x, βˆ…) == x[1:2] @test constraint(ocp, :cf)(βˆ…, x) == x[1:2] # constraint already exists ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) constraint!(ocp, :initial, rg = 1, lb = 0, ub = 0, label = :c) @test_throws UnauthorizedCall constraint!(ocp, :final, rg = 1, lb = 0, ub = 0, label = :c) end @testset "constraint! 3" begin ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) constraint!(ocp, :initial, lb = 0, ub = 1, label = :c0) constraint!(ocp, :final, lb = 1, ub = 2, label = :cf) constraint!(ocp, :control, lb = 0, ub = 1, label = :cu) constraint!(ocp, :state, lb = 0, ub = 1, label = :cs) @test constraint(ocp, :c0)(12, βˆ…) == 12 @test constraint(ocp, :cf)(βˆ…, 12) == 12 @test constraint(ocp, :cu)(12) == 12 @test constraint(ocp, :cs)(12) == 12 ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 2) constraint!(ocp, :initial, lb = [0, 1], ub = [1, 2], label = :c0) constraint!(ocp, :final, lb = [1, 2], ub = [2, 3], label = :cf) constraint!(ocp, :control, lb = [0, 1], ub = [1, 2], label = :cu) constraint!(ocp, :state, lb = [0, 1], ub = [1, 2], label = :cs) @test constraint(ocp, :c0)([12, 13], βˆ…) == [12, 13] @test constraint(ocp, :cf)(βˆ…, [12, 13]) == [12, 13] @test constraint(ocp, :cu)([12, 13]) == [12, 13] @test constraint(ocp, :cs)([12, 13]) == [12, 13] # constraint already exists ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) constraint!(ocp, :initial, lb = 0, ub = 1, label = :c) @test_throws UnauthorizedCall constraint!(ocp, :final, lb = 0, ub = 1, label = :c) end @testset "constraint! 4" begin ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) constraint!(ocp, :initial, rg = 1, lb = 0, ub = 1, label = :c0) constraint!(ocp, :final, rg = 1, lb = 1, ub = 2, label = :cf) constraint!(ocp, :control, rg = 1, lb = 0, ub = 1, label = :cu) constraint!(ocp, :state, rg = 1, lb = 0, ub = 1, label = :cs) @test constraint(ocp, :c0)(12, βˆ…) == 12 @test constraint(ocp, :cf)(βˆ…, 12) == 12 @test constraint(ocp, :cu)(12) == 12 @test constraint(ocp, :cs)(12) == 12 ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 2) @test_throws IncorrectArgument constraint!( ocp, :initial, rg = 2, lb = [0, 1], ub = [1, 2], label = :c0, ) @test_throws IncorrectArgument constraint!( ocp, :final, rg = 2, lb = [1, 2], ub = [2, 3], label = :cf, ) @test_throws IncorrectArgument constraint!( ocp, :control, rg = 2, lb = [0, 1], ub = [1, 2], label = :cu, ) @test_throws IncorrectArgument constraint!( ocp, :state, rg = 2, lb = [0, 1], ub = [1, 2], label = :cs, ) ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 2) constraint!(ocp, :initial, rg = 1:2, lb = [0, 1], ub = [1, 2], label = :c0) constraint!(ocp, :final, rg = 1:2, lb = [1, 2], ub = [2, 3], label = :cf) constraint!(ocp, :control, rg = 1:2, lb = [0, 1], ub = [1, 2], label = :cu) constraint!(ocp, :state, rg = 1:2, lb = [0, 1], ub = [1, 2], label = :cs) @test constraint(ocp, :c0)([12, 13], βˆ…) == [12, 13] @test constraint(ocp, :cf)(βˆ…, [12, 13]) == [12, 13] @test constraint(ocp, :cu)([12, 13]) == [12, 13] @test constraint(ocp, :cs)([12, 13]) == [12, 13] # constraint already exists ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) constraint!(ocp, :initial, rg = 1, lb = 0, ub = 1, label = :c) @test_throws UnauthorizedCall constraint!(ocp, :final, rg = 1, lb = 0, ub = 1, label = :c) end @testset "constraint! 5" begin ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) constraint!(ocp, :boundary, f = (x0, xf) -> x0 + xf, lb = 0, ub = 0, label = :cb) constraint!(ocp, :control, f = u -> u, lb = 0, ub = 0, label = :cu) constraint!(ocp, :state, f = x -> x, lb = 0, ub = 0, label = :cs) constraint!(ocp, :mixed, f = (x, u) -> x + u, lb = 1, ub = 1, label = :cm) @test constraint(ocp, :cb)(12, 13) == 12 + 13 @test constraint(ocp, :cu)(12) == 12 @test constraint(ocp, :cs)(12) == 12 @test constraint(ocp, :cm)(12, 13) == 12 + 13 ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 2) constraint!(ocp, :boundary, f = (x0, xf) -> x0[1] + xf[1], lb = 0, ub = 0, label = :cb) constraint!(ocp, :control, f = u -> u[1], lb = 0, ub = 0, label = :cu) constraint!(ocp, :state, f = x -> x[1], lb = 0, ub = 0, label = :cs) constraint!(ocp, :mixed, f = (x, u) -> x[1] + u[1], lb = 1, ub = 1, label = :cm) @test constraint(ocp, :cb)([13, 14], [16, 17]) == 13 + 16 @test constraint(ocp, :cu)([12, 13]) == 12 @test constraint(ocp, :cs)([12, 13]) == 12 @test constraint(ocp, :cm)([12, 13], [14, 15]) == 12 + 14 ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 3) control!(ocp, 3) constraint!( ocp, :boundary, f = (x0, xf) -> [x0[1] + xf[1], x0[2] + xf[2]], lb = [0, 0], ub = [0, 0], label = :cb, ) constraint!(ocp, :control, f = u -> u[1:2], lb = [0, 0], ub = [0, 0], label = :cu) constraint!(ocp, :state, f = x -> x[1:2], lb = [0, 0], ub = [0, 0], label = :cs) constraint!( ocp, :mixed, f = (x, u) -> [x[1] + u[1], x[2] + u[2]], lb = [0, 0], ub = [0, 0], label = :cm, ) @test constraint(ocp, :cb)([13, 14, 15], [17, 18, 19]) == [13 + 17, 14 + 18] @test constraint(ocp, :cu)([12, 13, 14]) == [12, 13] @test constraint(ocp, :cs)([12, 13, 14]) == [12, 13] @test constraint(ocp, :cm)([12, 13, 14], [15, 16, 17]) == [12 + 15, 13 + 16] # constraint already exists ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) constraint!(ocp, :control, f = u -> u, lb = 0, ub = 1, label = :c) @test_throws UnauthorizedCall constraint!( ocp, :control, f = u -> u, lb = 0, ub = 1, label = :c, ) end @testset "constraint! 6" begin ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) constraint!(ocp, :boundary, f = (x0, xf) -> x0 + xf, lb = 0, ub = 1, label = :cb) constraint!(ocp, :control, f = u -> u, lb = 0, ub = 1, label = :cu) constraint!(ocp, :state, f = x -> x, lb = 0, ub = 1, label = :cs) constraint!(ocp, :mixed, f = (x, u) -> x + u, lb = 1, ub = 1, label = :cm) @test constraint(ocp, :cb)(12, 13) == 12 + 13 @test constraint(ocp, :cu)(12) == 12 @test constraint(ocp, :cs)(12) == 12 @test constraint(ocp, :cm)(12, 13) == 12 + 13 ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 2) constraint!(ocp, :boundary, f = (x0, xf) -> x0[1] + xf[1], lb = 0, ub = 1, label = :cb) constraint!(ocp, :control, f = u -> u[1], lb = 0, ub = 1, label = :cu) constraint!(ocp, :state, f = x -> x[1], lb = 0, ub = 1, label = :cs) constraint!(ocp, :mixed, f = (x, u) -> x[1] + u[1], lb = 1, ub = 1, label = :cm) @test constraint(ocp, :cb)([13, 14], [16, 17]) == 13 + 16 @test constraint(ocp, :cu)([12, 13]) == 12 @test constraint(ocp, :cs)([12, 13]) == 12 @test constraint(ocp, :cm)([12, 13], [14, 15]) == 12 + 14 ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) constraint!( ocp, :boundary, f = (x0, xf) -> [x0[1] + xf[1], x0[2] + xf[2]], lb = [0, 0], ub = [1, 1], label = :cb, ) constraint!(ocp, :control, f = u -> u[1:2], lb = [0, 0], ub = [1, 1], label = :cu) constraint!(ocp, :state, f = x -> x[1:2], lb = [0, 0], ub = [1, 1], label = :cs) constraint!( ocp, :mixed, f = (x, u) -> [x[1] + u[1], x[2] + u[2]], lb = [0, 0], ub = [1, 1], label = :cm, ) @test constraint(ocp, :cb)([13, 14, 15], [17, 18, 19]) == [13 + 17, 14 + 18] @test constraint(ocp, :cu)([12, 13, 14]) == [12, 13] @test constraint(ocp, :cs)([12, 13, 14]) == [12, 13] @test constraint(ocp, :cm)([12, 13, 14], [15, 16, 17]) == [12 + 15, 13 + 16] end @testset "constraint! 7" begin x = 1 u = 2 v = [3, 4, 5, 6] x0 = 7 xf = 8 ocp = Model(variable = true) time!(ocp; t0 = 0, tf = 1) variable!(ocp, 4) state!(ocp, 1) control!(ocp, 1) constraint!(ocp, :variable, lb = [0, 0, 0, 0], ub = [1, 1, 1, 1], label = :eq1) constraint!(ocp, :variable, rg = 1, lb = 0, ub = 1, label = :eq2) constraint!(ocp, :variable, rg = 1:2, lb = [0, 0], ub = [1, 2], label = :eq3) constraint!(ocp, :variable, rg = 1:2:4, lb = [0, 0], ub = [-1, 1], label = :eq4) constraint!( ocp, :variable, f = v -> v .^ 2, lb = [0, 0, 0, 0], ub = [1, 0, 1, 0], label = :eq5, ) @test constraint(ocp, :eq1)(v) == v @test constraint(ocp, :eq2)(v) == v[1] @test constraint(ocp, :eq3)(v) == v[1:2] @test constraint(ocp, :eq4)(v) == v[1:2:4] @test constraint(ocp, :eq5)(v) == v .^ 2 end @testset "constraint! 8" begin x = 1 u = 2 v = [3, 4, 5, 6] x0 = 7 xf = 8 ocp = Model(variable = true) time!(ocp; t0 = 0, tf = 1) variable!(ocp, 4) state!(ocp, 1) control!(ocp, 1) constraint!(ocp, :boundary, f = (x0, xf, v) -> x0 + xf + v[1], lb = 0, ub = 1, label = :cb) constraint!(ocp, :control, f = (u, v) -> u + v[1], lb = 0, ub = 1, label = :cu) constraint!(ocp, :state, f = (x, v) -> x + v[1], lb = 0, ub = 1, label = :cs) constraint!(ocp, :mixed, f = (x, u, v) -> x + u + v[1], lb = 1, ub = 1, label = :cm) constraint!(ocp, :variable, lb = [0, 0, 0, 0], ub = [0, 0, 0, 0], label = :eq1) constraint!(ocp, :variable, rg = 1, lb = 0, ub = 0, label = :eq2) constraint!(ocp, :variable, rg = 1:2, lb = [0, 0], ub = [0, 0], label = :eq3) constraint!(ocp, :variable, rg = 1:2:4, lb = [0, 0], ub = [0, 0], label = :eq4) constraint!( ocp, :variable, f = v -> v .^ 2, lb = [0, 0, 0, 0], ub = [0, 0, 0, 0], label = :eq5, ) @test constraint(ocp, :cb)(x0, xf, v) == x0 + xf + v[1] @test constraint(ocp, :cu)(u, v) == u + v[1] @test constraint(ocp, :cs)(x, v) == x + v[1] @test constraint(ocp, :cm)(x, u, v) == x + u + v[1] @test constraint(ocp, :eq1)(v) == v @test constraint(ocp, :eq2)(v) == v[1] @test constraint(ocp, :eq3)(v) == v[1:2] @test constraint(ocp, :eq4)(v) == v[1:2:4] @test constraint(ocp, :eq5)(v) == v .^ 2 end @testset "constraint! 9" begin ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) dynamics!(ocp, (x, u) -> x + u) @test dynamics(ocp)(1, 2) == 3 ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 2) dynamics!(ocp, (x, u) -> x[1] + u[1]) @test dynamics(ocp)([1, 2], [3, 4]) == 4 ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 2) dynamics!(ocp, (x, u) -> [x[1] + u[1], x[2] + u[2]]) @test dynamics(ocp)([1, 2], [3, 4]) == [4, 6] ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) dynamics!(ocp, (x, u) -> [x[1] + u, x[2] + u]) @test dynamics(ocp)([1, 2], 3) == [4, 5] end @testset "constraint! 10" begin ocp = Model(autonomous = false) time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) constraint!(ocp, :initial, lb = 0, ub = 1, label = :c0) constraint!(ocp, :final, lb = 1, ub = 2, label = :cf) @test constraint(ocp, :c0)(12, βˆ…) == 12 @test constraint(ocp, :cf)(βˆ…, 12) == 12 end @testset "constraint! 11" begin dummy(u) = u^2 + u ocp = Model(variable = true) time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) variable!(ocp, 3) constraint!(ocp, :state, lb = 0, ub = 1, label = :c0) constraint!(ocp, :control, f = dummy, lb = 1, ub = 1, label = :c1) constraint!(ocp, :variable, rg = 1:2:3, lb = [-Inf, -Inf], ub = [0, 0], label = :c2) ocp_bis = Model(variable = true) time!(ocp_bis; t0 = 0, tf = 1) state!(ocp_bis, 1) control!(ocp_bis, 1) variable!(ocp_bis, 3) constraint!(ocp_bis, :state, lb = 0, ub = 1, label = :c0) constraint!(ocp_bis, :control, f = dummy, ub = 1, lb = 1, label = :c1) constraint!(ocp_bis, :variable, rg = 1:2:3, ub = [0, 0], label = :c2) @test constraints(ocp) == constraints(ocp_bis) ocp_ter = Model(variable = true) time!(ocp_ter; t0 = 0, tf = 1) state!(ocp_ter, 3) control!(ocp_ter, 1) variable!(ocp_ter, 1) constraint!(ocp_ter, :variable, lb = 1, ub = 1, label = :c0) constraint!(ocp_ter, :control, f = dummy, lb = 1, ub = Inf, label = :c1) constraint!(ocp_ter, :state, rg = 1:2:3, lb = [0, 0], ub = [0, 0], label = :c2) ocp_quad = Model(variable = true) time!(ocp_quad; t0 = 0, tf = 1) state!(ocp_quad, 3) control!(ocp_quad, 1) variable!(ocp_quad, 1) constraint!(ocp_quad, :variable, lb = 1, ub = 1, label = :c0) constraint!(ocp_quad, :control, f = dummy, lb = 1, label = :c1) constraint!(ocp_quad, :state, rg = 1:2:3, lb = [0, 0], ub = [0, 0], label = :c2) @test constraints(ocp_ter) == constraints(ocp_quad) ocp_error = ocp_error = Model(variable = true) time!(ocp_error; t0 = 0, tf = 1) state!(ocp_error, 3) control!(ocp_error, 1) variable!(ocp_error, 1) @test_throws UnauthorizedCall constraint!(ocp_error, :variable) @test_throws UnauthorizedCall constraint!(ocp_error, :control, f = dummy, label = :c1) @test_throws UnauthorizedCall constraint!(ocp_error, :state, rg = 1:2:3, label = :c2) @test_throws IncorrectArgument constraint!( ocp_error, :state, rg = 1:2:3, f = dummy, lb = [0, 0], ub = [0, 0], label = :c3, ) @test_throws IncorrectArgument constraint!( ocp_error, :state, f = dummy, rg = 1:2:3, lb = [0, 0], ub = [0, 0], label = :c4, ) @test_throws IncorrectArgument constraint!( ocp_error, :foo, lb = [0, 0], ub = [0, 0], label = :c5, ) end @testset "remove_constraint! and constraints_labels" begin ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) constraint!(ocp, :boundary, f = (x0, xf) -> x0 + xf, lb = 0, ub = 1, label = :cb) constraint!(ocp, :control, f = u -> u, lb = 0, ub = 1, label = :cu) k = constraints_labels(ocp) @test :cb ∈ k @test :cu ∈ k remove_constraint!(ocp, :cb) k = constraints_labels(ocp) @test :cb βˆ‰ k @test_throws IncorrectArgument remove_constraint!(ocp, :dummy_con) end @testset "nlp_constraints! without variable" begin ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) constraint!(ocp, :initial, rg = 2, lb = 10, ub = 10, label = :ci) constraint!(ocp, :final, rg = 1, lb = 1, ub = 1, label = :cf) constraint!(ocp, :control, lb = 0, ub = 1, label = :cu) constraint!(ocp, :state, lb = [0, 1], ub = [1, 2], label = :cs) constraint!(ocp, :boundary, f = (x0, xf) -> x0[2] + xf[2], lb = 0, ub = 1, label = :cb) constraint!(ocp, :control, f = u -> u, lb = 0, ub = 1, label = :cuu) constraint!(ocp, :state, f = x -> x, lb = [0, 1], ub = [1, 2], label = :css) constraint!(ocp, :mixed, f = (x, u) -> x[1] + u, lb = 1, ub = 1, label = :cm) # dimensions (not set yet) @test dim_control_constraints(ocp) === nothing @test dim_state_constraints(ocp) === nothing @test dim_mixed_constraints(ocp) === nothing @test dim_path_constraints(ocp) === nothing @test dim_boundary_constraints(ocp) === nothing @test dim_variable_constraints(ocp) === nothing @test dim_control_range(ocp) === nothing @test dim_state_range(ocp) === nothing @test dim_variable_range(ocp) === nothing (ΞΎl, ΞΎ, ΞΎu), (Ξ·l, Ξ·, Ξ·u), (ψl, ψ, ψu), (Ο•l, Ο•, Ο•u), (ΞΈl, ΞΈ, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu) = nlp_constraints!(ocp) v = Real[] # control @test sort(ΞΎl) == sort([0]) @test sort(ΞΎu) == sort([1]) @test sort(ΞΎ(-1, 1, v)) == sort([1]) # state @test sort(Ξ·l) == sort([0, 1]) @test sort(Ξ·u) == sort([1, 2]) @test sort(Ξ·(-1, [1, 1], v)) == sort([1, 1]) # mixed @test sort(ψl) == sort([1]) @test sort(ψu) == sort([1]) @test sort(ψ(-1, [1, 1], 2, v)) == sort([3]) # boundary @test sort(Ο•l) == sort([10, 1, 0]) @test sort(Ο•u) == sort([10, 1, 1]) @test sort(Ο•([1, 3], [4, 100], v)) == sort([3, 4, 103]) # box constraint @test sort(ul) == sort([0]) @test sort(uind) == sort([1]) @test sort(uu) == sort([1]) @test sort(xl) == sort([0, 1]) @test sort(xind) == sort([1, 2]) @test sort(xu) == sort([1, 2]) # variable @test sort(vl) == sort([]) @test sort(vind) == sort([]) @test sort(vu) == sort([]) @test sort(ΞΈl) == sort([]) @test sort(ΞΈu) == sort([]) @test sort(ΞΈ(v)) == sort([]) # dimensions (set) @test dim_control_constraints(ocp) == 1 @test dim_state_constraints(ocp) == 2 @test dim_mixed_constraints(ocp) == 1 @test dim_path_constraints(ocp) == 4 @test dim_boundary_constraints(ocp) == 3 @test dim_variable_constraints(ocp) == 0 @test dim_control_range(ocp) == 1 @test dim_state_range(ocp) == 2 @test dim_variable_range(ocp) == 0 end @testset "nlp_constraints! with variable" begin ocp = Model(variable = true) time!(ocp; t0 = 0, tf = 1) variable!(ocp, 4) state!(ocp, 2) control!(ocp, 1) constraint!(ocp, :initial, rg = 2, lb = 10, ub = 10, label = :ci) constraint!(ocp, :final, rg = 1, lb = 1, ub = 1, label = :cf) constraint!(ocp, :control, lb = 0, ub = 1, label = :cu) constraint!(ocp, :state, lb = [0, 1], ub = [1, 2], label = :cs) constraint!( ocp, :boundary, f = (x0, xf, v) -> x0[2] + xf[2] + v[1], lb = 0, ub = 1, label = :cb, ) constraint!(ocp, :control, f = (u, v) -> u + v[2], lb = 0, ub = 1, label = :cuu) constraint!(ocp, :state, f = (x, v) -> x + v[1:2], lb = [0, 1], ub = [1, 2], label = :css) constraint!(ocp, :mixed, f = (x, u, v) -> x[1] + u + v[2], lb = 1, ub = 1, label = :cm) constraint!(ocp, :variable, lb = [0, 0, 0, 0], ub = [5, 5, 5, 5], label = :cv1) constraint!(ocp, :variable, rg = 1:2, lb = [1, 2], ub = [3, 4], label = :cv2) constraint!(ocp, :variable, rg = 3, lb = 2, ub = 3, label = :cv3) constraint!(ocp, :variable, f = v -> v[3]^2, lb = 0, ub = 1, label = :cv4) # dimensions (not set yet) @test dim_control_constraints(ocp) === nothing @test dim_state_constraints(ocp) === nothing @test dim_mixed_constraints(ocp) === nothing @test dim_path_constraints(ocp) === nothing @test dim_boundary_constraints(ocp) === nothing @test dim_variable_constraints(ocp) === nothing @test dim_control_range(ocp) === nothing @test dim_state_range(ocp) === nothing @test dim_variable_range(ocp) === nothing (ΞΎl, ΞΎ, ΞΎu), (Ξ·l, Ξ·, Ξ·u), (ψl, ψ, ψu), (Ο•l, Ο•, Ο•u), (ΞΈl, ΞΈ, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu) = nlp_constraints!(ocp) v = [1, 2, 3, 4] # control @test sort(ΞΎl) == sort([0]) @test sort(ΞΎu) == sort([1]) @test sort(ΞΎ(-1, 1, v)) == sort([1 + v[2]]) # state @test sort(Ξ·l) == sort([0, 1]) @test sort(Ξ·u) == sort([1, 2]) @test sort(Ξ·(-1, [1, 1], v)) == sort([1, 1] + v[1:2]) # mixed @test sort(ψl) == sort([1]) @test sort(ψu) == sort([1]) @test sort(ψ(-1, [1, 1], 2, v)) == sort([3 + v[2]]) # boundary @test sort(Ο•l) == sort([10, 1, 0]) @test sort(Ο•u) == sort([10, 1, 1]) @test sort(Ο•([1, 3], [4, 100], v)) == sort([3, 4, 103 + v[1]]) # variable @test sort(ΞΈl) == sort([0]) @test sort(ΞΈu) == sort([1]) @test sort(ΞΈ(v)) == sort([v[3]^2]) # box constraint @test sort(ul) == sort([0]) @test sort(uind) == sort([1]) @test sort(uu) == sort([1]) @test sort(xl) == sort([0, 1]) @test sort(xind) == sort([1, 2]) @test sort(xu) == sort([1, 2]) @test sort(vl) == sort([0, 0, 0, 0, 1, 2, 2]) @test sort(vind) == sort([1, 2, 3, 4, 1, 2, 3]) @test sort(vu) == sort([5, 5, 5, 5, 3, 4, 3]) # dimensions @test dim_control_constraints(ocp) == 1 @test dim_state_constraints(ocp) == 2 @test dim_mixed_constraints(ocp) == 1 @test dim_path_constraints(ocp) == 4 @test dim_boundary_constraints(ocp) == 3 @test dim_variable_constraints(ocp) == 1 @test dim_control_range(ocp) == 1 @test dim_state_range(ocp) == 2 @test dim_variable_range(ocp) == 7 end @testset "nlp_constraints! without variable (in place)" begin ocp = Model(; in_place = true) time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 1) constraint!(ocp, :initial, rg = 2, lb = 10, ub = 10, label = :ci) constraint!(ocp, :final, rg = 1, lb = 1, ub = 1, label = :cf) constraint!(ocp, :control, lb = 0, ub = 1, label = :cu) constraint!(ocp, :state, lb = [0, 1], ub = [1, 2], label = :cs) constraint!(ocp, :boundary, f = (r, x0, xf) -> (r[:] .= x0[2] + xf[2]; nothing), lb = 0, ub = 1, label = :cb) constraint!(ocp, :control, f = (r, u) -> (r[:] .= u; nothing), lb = 0, ub = 1, label = :cuu) constraint!(ocp, :state, f = (r, x) -> (r[:] .= x; nothing), lb = [0, 1], ub = [1, 2], label = :css) constraint!(ocp, :mixed, f = (r, x, u) -> (r[:] .= x[1] + u; nothing), lb = 1, ub = 1, label = :cm) # dimensions (not set yet) @test dim_control_constraints(ocp) === nothing @test dim_state_constraints(ocp) === nothing @test dim_mixed_constraints(ocp) === nothing @test dim_path_constraints(ocp) === nothing @test dim_boundary_constraints(ocp) === nothing @test dim_variable_constraints(ocp) === nothing @test dim_control_range(ocp) === nothing @test dim_state_range(ocp) === nothing @test dim_variable_range(ocp) === nothing (ΞΎl, ΞΎ!, ΞΎu), (Ξ·l, Ξ·!, Ξ·u), (ψl, ψ!, ψu), (Ο•l, Ο•!, Ο•u), (ΞΈl, ΞΈ!, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu) = nlp_constraints!(ocp) v = Real[] # control @test sort(ΞΎl) == sort([0]) @test sort(ΞΎu) == sort([1]) r = [0.] ΞΎ!(r, -1, 1, v) @test sort(r) == sort([1]) # state @test sort(Ξ·l) == sort([0, 1]) @test sort(Ξ·u) == sort([1, 2]) r = [0., 0.] Ξ·!(r, -1, [1, 1], v) @test sort(r) == sort([1, 1]) # mixed @test sort(ψl) == sort([1]) @test sort(ψu) == sort([1]) r = [0.] ψ!(r, -1, [1, 1], 2, v) @test sort(r) == sort([3]) # boundary @test sort(Ο•l) == sort([10, 1, 0]) @test sort(Ο•u) == sort([10, 1, 1]) r = [0., 0., 0.] Ο•!(r, [1, 3], [4, 100], v) @test sort(r) == sort([3, 4, 103]) # box constraint @test sort(ul) == sort([0]) @test sort(uind) == sort([1]) @test sort(uu) == sort([1]) @test sort(xl) == sort([0, 1]) @test sort(xind) == sort([1, 2]) @test sort(xu) == sort([1, 2]) # variable @test sort(vl) == sort([]) @test sort(vind) == sort([]) @test sort(vu) == sort([]) @test sort(ΞΈl) == sort([]) @test sort(ΞΈu) == sort([]) r = Real[] ΞΈ!(r, v) @test sort(r) == sort([]) # dimensions (set) @test dim_control_constraints(ocp) == 1 @test dim_state_constraints(ocp) == 2 @test dim_mixed_constraints(ocp) == 1 @test dim_path_constraints(ocp) == 4 @test dim_boundary_constraints(ocp) == 3 @test dim_variable_constraints(ocp) == 0 @test dim_control_range(ocp) == 1 @test dim_state_range(ocp) == 2 @test dim_variable_range(ocp) == 0 end @testset "nlp_constraints! with variable (in place)" begin ocp = Model(; variable = true, in_place = true) time!(ocp; t0 = 0, tf = 1) variable!(ocp, 4) state!(ocp, 2) control!(ocp, 1) constraint!(ocp, :initial, rg = 2, lb = 10, ub = 10, label = :ci) constraint!(ocp, :final, rg = 1, lb = 1, ub = 1, label = :cf) constraint!(ocp, :control, lb = 0, ub = 1, label = :cu) constraint!(ocp, :state, lb = [0, 1], ub = [1, 2], label = :cs) constraint!( ocp, :boundary, f = (r, x0, xf, v) -> (r[:] .= x0[2] + xf[2] + v[1]; nothing), lb = 0, ub = 1, label = :cb, ) constraint!(ocp, :control, f = (r, u, v) -> (r[:] .= u + v[2]; nothing), lb = 0, ub = 1, label = :cuu) constraint!(ocp, :state, f = (r, x, v) -> (r[:] .= x + v[1:2]; nothing), lb = [0, 1], ub = [1, 2], label = :css) constraint!(ocp, :mixed, f = (r, x, u, v) -> (r[:] .= x[1] + u + v[2]; nothing), lb = 1, ub = 1, label = :cm) constraint!(ocp, :variable, lb = [0, 0, 0, 0], ub = [5, 5, 5, 5], label = :cv1) constraint!(ocp, :variable, rg = 1:2, lb = [1, 2], ub = [3, 4], label = :cv2) constraint!(ocp, :variable, rg = 3, lb = 2, ub = 3, label = :cv3) constraint!(ocp, :variable, f = (r, v) -> (r[:] .= v[3]^2; nothing), lb = 0, ub = 1, label = :cv4) # dimensions (not set yet) @test dim_control_constraints(ocp) === nothing @test dim_state_constraints(ocp) === nothing @test dim_mixed_constraints(ocp) === nothing @test dim_path_constraints(ocp) === nothing @test dim_boundary_constraints(ocp) === nothing @test dim_variable_constraints(ocp) === nothing @test dim_control_range(ocp) === nothing @test dim_state_range(ocp) === nothing @test dim_variable_range(ocp) === nothing (ΞΎl, ΞΎ!, ΞΎu), (Ξ·l, Ξ·!, Ξ·u), (ψl, ψ!, ψu), (Ο•l, Ο•!, Ο•u), (ΞΈl, ΞΈ!, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu) = nlp_constraints!(ocp) v = [1, 2, 3, 4] # control @test sort(ΞΎl) == sort([0]) @test sort(ΞΎu) == sort([1]) r = [0.] ΞΎ!(r, -1, 1, v) @test sort(r) == sort([1 + v[2]]) # state @test sort(Ξ·l) == sort([0, 1]) @test sort(Ξ·u) == sort([1, 2]) r = [0., 0.] Ξ·!(r, -1, [1, 1], v) @test sort(r) == sort([1, 1] + v[1:2]) # mixed @test sort(ψl) == sort([1]) @test sort(ψu) == sort([1]) r = [0.] ψ!(r, -1, [1, 1], 2, v) @test sort(r) == sort([3 + v[2]]) # boundary @test sort(Ο•l) == sort([10, 1, 0]) @test sort(Ο•u) == sort([10, 1, 1]) r = [0., 0., 0.] Ο•!(r, [1, 3], [4, 100], v) @test sort(r) == sort([3, 4, 103 + v[1]]) # variable @test sort(ΞΈl) == sort([0]) @test sort(ΞΈu) == sort([1]) r = [0.] ΞΈ!(r, v) @test sort(r) == sort([v[3]^2]) # box constraint @test sort(ul) == sort([0]) @test sort(uind) == sort([1]) @test sort(uu) == sort([1]) @test sort(xl) == sort([0, 1]) @test sort(xind) == sort([1, 2]) @test sort(xu) == sort([1, 2]) @test sort(vl) == sort([0, 0, 0, 0, 1, 2, 2]) @test sort(vind) == sort([1, 2, 3, 4, 1, 2, 3]) @test sort(vu) == sort([5, 5, 5, 5, 3, 4, 3]) # dimensions @test dim_control_constraints(ocp) == 1 @test dim_state_constraints(ocp) == 2 @test dim_mixed_constraints(ocp) == 1 @test dim_path_constraints(ocp) == 4 @test dim_boundary_constraints(ocp) == 3 @test dim_variable_constraints(ocp) == 1 @test dim_control_range(ocp) == 1 @test dim_state_range(ocp) == 2 @test dim_variable_range(ocp) == 7 end @testset "val vs lb and ub, errors" begin ocp = Model(variable = true) time!(ocp; t0 = 0, tf = 1) variable!(ocp, 4) state!(ocp, 2) control!(ocp, 1) # error val with ub @test_throws UnauthorizedCall constraint!( ocp, :initial; rg = Index(2), val = 10, ub = 10, label = :ci, ) @test_throws UnauthorizedCall constraint!( ocp, :final; rg = Index(1), val = 1, ub = 1, label = :cf, ) @test_throws UnauthorizedCall constraint!(ocp, :control; val = 0, ub = 0, label = :cu) @test_throws UnauthorizedCall constraint!( ocp, :state; val = [0, 1], ub = [0, 1], label = :cs, ) @test_throws UnauthorizedCall constraint!( ocp, :boundary; f = (x0, xf, v) -> x0[2] + xf[2] + v[1], val = 2, ub = 2, label = :cb, ) @test_throws UnauthorizedCall constraint!( ocp, :control; f = (u, v) -> u + v[2], val = 20, ub = 20, label = :cuu, ) @test_throws UnauthorizedCall constraint!( ocp, :state; f = (x, v) -> x + v[1:2], val = [100, 101], ub = [100, 101], label = :css, ) @test_throws UnauthorizedCall constraint!( ocp, :mixed; f = (x, u, v) -> x[1] + u + v[2], val = -1, ub = -1, label = :cm, ) @test_throws UnauthorizedCall constraint!( ocp, :variable; val = [5, 5, 5, 5], ub = [5, 5, 5, 5], label = :cv1, ) @test_throws UnauthorizedCall constraint!( ocp, :variable; rg = 1:2, val = [10, 20], ub = [10, 20], label = :cv2, ) @test_throws UnauthorizedCall constraint!( ocp, :variable; rg = Index(3), val = 1000, ub = 1000, label = :cv3, ) @test_throws UnauthorizedCall constraint!( ocp, :variable; f = v -> v[3]^2, val = -10, ub = -10, label = :cv4, ) ocp = Model(variable = true) time!(ocp; t0 = 0, tf = 1) variable!(ocp, 4) state!(ocp, 2) control!(ocp, 1) # error val with lb @test_throws UnauthorizedCall constraint!( ocp, :initial; rg = Index(2), val = 10, lb = 10, label = :ci, ) @test_throws UnauthorizedCall constraint!( ocp, :final; rg = Index(1), val = 1, lb = 1, label = :cf, ) @test_throws UnauthorizedCall constraint!(ocp, :control; val = 0, lb = 0, label = :cu) @test_throws UnauthorizedCall constraint!( ocp, :state; val = [0, 1], lb = [0, 1], label = :cs, ) @test_throws UnauthorizedCall constraint!( ocp, :boundary; f = (x0, xf, v) -> x0[2] + xf[2] + v[1], val = 2, lb = 2, label = :cb, ) @test_throws UnauthorizedCall constraint!( ocp, :control; f = (u, v) -> u + v[2], val = 20, lb = 20, label = :cuu, ) @test_throws UnauthorizedCall constraint!( ocp, :state; f = (x, v) -> x + v[1:2], val = [100, 101], lb = [100, 101], label = :css, ) @test_throws UnauthorizedCall constraint!( ocp, :mixed; f = (x, u, v) -> x[1] + u + v[2], val = -1, lb = -1, label = :cm, ) @test_throws UnauthorizedCall constraint!( ocp, :variable; val = [5, 5, 5, 5], lb = [5, 5, 5, 5], label = :cv1, ) @test_throws UnauthorizedCall constraint!( ocp, :variable; rg = 1:2, val = [10, 20], lb = [10, 20], label = :cv2, ) @test_throws UnauthorizedCall constraint!( ocp, :variable; rg = Index(3), val = 1000, lb = 1000, label = :cv3, ) @test_throws UnauthorizedCall constraint!( ocp, :variable; f = v -> v[3]^2, val = -10, lb = -10, label = :cv4, ) end @testset "val vs lb and ub, 1/2" begin ocp = Model(variable = true) time!(ocp; t0 = 0, tf = 1) variable!(ocp, 4) state!(ocp, 2) control!(ocp, 1) constraint!(ocp, :initial; rg = Index(2), lb = 10, ub = 10, label = :ci) constraint!(ocp, :final; rg = Index(1), lb = 1, ub = 1, label = :cf) constraint!(ocp, :control; lb = 0, ub = 0, label = :cu) constraint!(ocp, :state; lb = [0, 1], ub = [0, 1], label = :cs) constraint!( ocp, :boundary; f = (x0, xf, v) -> x0[2] + xf[2] + v[1], lb = 2, ub = 2, label = :cb, ) constraint!(ocp, :control; f = (u, v) -> u + v[2], lb = 20, ub = 20, label = :cuu) constraint!( ocp, :state; f = (x, v) -> x + v[1:2], lb = [100, 101], ub = [100, 101], label = :css, ) constraint!(ocp, :mixed; f = (x, u, v) -> x[1] + u + v[2], lb = -1, ub = -1, label = :cm) constraint!(ocp, :variable; lb = [5, 5, 5, 5], ub = [5, 5, 5, 5], label = :cv1) constraint!(ocp, :variable; rg = 1:2, lb = [10, 20], ub = [10, 20], label = :cv2) constraint!(ocp, :variable; rg = Index(3), lb = 1000, ub = 1000, label = :cv3) constraint!(ocp, :variable; f = v -> v[3]^2, lb = -10, ub = -10, label = :cv4) # dimensions (not set yet) @test dim_control_constraints(ocp) === nothing @test dim_state_constraints(ocp) === nothing @test dim_mixed_constraints(ocp) === nothing @test dim_path_constraints(ocp) === nothing @test dim_boundary_constraints(ocp) === nothing @test dim_variable_constraints(ocp) === nothing @test dim_control_range(ocp) === nothing @test dim_state_range(ocp) === nothing @test dim_variable_range(ocp) === nothing (ΞΎl, ΞΎ, ΞΎu), (Ξ·l, Ξ·, Ξ·u), (ψl, ψ, ψu), (Ο•l, Ο•, Ο•u), (ΞΈl, ΞΈ, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu) = nlp_constraints!(ocp) v = [1, 2, 3, 4] # control @test sort(ΞΎl) == sort([20]) @test sort(ΞΎu) == sort([20]) @test sort(ΞΎ(-1, 1, v)) == sort([1 + v[2]]) # state @test sort(Ξ·l) == sort([100, 101]) @test sort(Ξ·u) == sort([100, 101]) @test sort(Ξ·(-1, [1, 1], v)) == sort([1, 1] + v[1:2]) # mixed @test sort(ψl) == sort([-1]) @test sort(ψu) == sort([-1]) @test sort(ψ(-1, [1, 1], 2, v)) == sort([3 + v[2]]) # boundary @test sort(Ο•l) == sort([10, 1, 2]) @test sort(Ο•u) == sort([10, 1, 2]) @test sort(Ο•([1, 3], [4, 100], v)) == sort([3, 4, 103 + v[1]]) # variable @test sort(ΞΈl) == sort([-10]) @test sort(ΞΈu) == sort([-10]) @test sort(ΞΈ(v)) == sort([v[3]^2]) # box constraint @test sort(ul) == sort([0]) @test sort(uind) == sort([1]) @test sort(uu) == sort([0]) @test sort(xl) == sort([0, 1]) @test sort(xind) == sort([1, 2]) @test sort(xu) == sort([0, 1]) @test sort(vl) == sort([5, 5, 5, 5, 10, 20, 1000]) @test sort(vind) == sort([1, 2, 3, 4, 1, 2, 3]) @test sort(vu) == sort([5, 5, 5, 5, 10, 20, 1000]) # dimensions @test dim_control_constraints(ocp) == 1 @test dim_state_constraints(ocp) == 2 @test dim_mixed_constraints(ocp) == 1 @test dim_path_constraints(ocp) == 4 @test dim_boundary_constraints(ocp) == 3 @test dim_variable_constraints(ocp) == 1 @test dim_control_range(ocp) == 1 @test dim_state_range(ocp) == 2 @test dim_variable_range(ocp) == 7 end @testset "val vs lb and ub, 2/2" begin ocp = Model(variable = true) time!(ocp; t0 = 0, tf = 1) variable!(ocp, 4) state!(ocp, 2) control!(ocp, 1) constraint!(ocp, :initial; rg = Index(2), val = 10, label = :ci) constraint!(ocp, :final; rg = Index(1), val = 1, label = :cf) constraint!(ocp, :control; val = 0, label = :cu) constraint!(ocp, :state; val = [0, 1], label = :cs) constraint!(ocp, :boundary; f = (x0, xf, v) -> x0[2] + xf[2] + v[1], val = 2, label = :cb) constraint!(ocp, :control; f = (u, v) -> u + v[2], val = 20, label = :cuu) constraint!(ocp, :state; f = (x, v) -> x + v[1:2], val = [100, 101], label = :css) constraint!(ocp, :mixed; f = (x, u, v) -> x[1] + u + v[2], val = -1, label = :cm) constraint!(ocp, :variable; val = [5, 5, 5, 5], label = :cv1) constraint!(ocp, :variable; rg = 1:2, val = [10, 20], label = :cv2) constraint!(ocp, :variable; rg = Index(3), val = 1000, label = :cv3) constraint!(ocp, :variable; f = v -> v[3]^2, val = -10, label = :cv4) # dimensions (not set yet) @test dim_control_constraints(ocp) === nothing @test dim_state_constraints(ocp) === nothing @test dim_mixed_constraints(ocp) === nothing @test dim_path_constraints(ocp) === nothing @test dim_boundary_constraints(ocp) === nothing @test dim_variable_constraints(ocp) === nothing @test dim_control_range(ocp) === nothing @test dim_state_range(ocp) === nothing @test dim_variable_range(ocp) === nothing (ΞΎl, ΞΎ, ΞΎu), (Ξ·l, Ξ·, Ξ·u), (ψl, ψ, ψu), (Ο•l, Ο•, Ο•u), (ΞΈl, ΞΈ, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu) = nlp_constraints!(ocp) v = [1, 2, 3, 4] # control @test sort(ΞΎl) == sort([20]) @test sort(ΞΎu) == sort([20]) @test sort(ΞΎ(-1, 1, v)) == sort([1 + v[2]]) # state @test sort(Ξ·l) == sort([100, 101]) @test sort(Ξ·u) == sort([100, 101]) @test sort(Ξ·(-1, [1, 1], v)) == sort([1, 1] + v[1:2]) # mixed @test sort(ψl) == sort([-1]) @test sort(ψu) == sort([-1]) @test sort(ψ(-1, [1, 1], 2, v)) == sort([3 + v[2]]) # boundary @test sort(Ο•l) == sort([10, 1, 2]) @test sort(Ο•u) == sort([10, 1, 2]) @test sort(Ο•([1, 3], [4, 100], v)) == sort([3, 4, 103 + v[1]]) # variable @test sort(ΞΈl) == sort([-10]) @test sort(ΞΈu) == sort([-10]) @test sort(ΞΈ(v)) == sort([v[3]^2]) # box constraint @test sort(ul) == sort([0]) @test sort(uind) == sort([1]) @test sort(uu) == sort([0]) @test sort(xl) == sort([0, 1]) @test sort(xind) == sort([1, 2]) @test sort(xu) == sort([0, 1]) @test sort(vl) == sort([5, 5, 5, 5, 10, 20, 1000]) @test sort(vind) == sort([1, 2, 3, 4, 1, 2, 3]) @test sort(vu) == sort([5, 5, 5, 5, 10, 20, 1000]) # dimensions @test dim_control_constraints(ocp) == 1 @test dim_state_constraints(ocp) == 2 @test dim_mixed_constraints(ocp) == 1 @test dim_path_constraints(ocp) == 4 @test dim_boundary_constraints(ocp) == 3 @test dim_variable_constraints(ocp) == 1 @test dim_control_range(ocp) == 1 @test dim_state_range(ocp) == 2 @test dim_variable_range(ocp) == 7 end @testset "val vs lb and ub, 1/2 (in place)" begin ocp = Model(variable = true, in_place = true) time!(ocp; t0 = 0, tf = 1) variable!(ocp, 4) state!(ocp, 2) control!(ocp, 1) constraint!(ocp, :initial; rg = Index(2), lb = 10, ub = 10, label = :ci) constraint!(ocp, :final; rg = Index(1), lb = 1, ub = 1, label = :cf) constraint!(ocp, :control; lb = 0, ub = 0, label = :cu) constraint!(ocp, :state; lb = [0, 1], ub = [0, 1], label = :cs) constraint!( ocp, :boundary; f = (r, x0, xf, v) -> (r[:] .= x0[2] + xf[2] + v[1]; nothing), lb = 2, ub = 2, label = :cb, ) constraint!(ocp, :control; f = (r, u, v) -> (r[:] .= u + v[2]; nothing), lb = 20, ub = 20, label = :cuu) constraint!( ocp, :state; f = (r, x, v) -> (r[:] .= x + v[1:2]; nothing), lb = [100, 101], ub = [100, 101], label = :css, ) constraint!(ocp, :mixed; f = (r, x, u, v) -> (r[:] .= x[1] + u + v[2]; nothing), lb = -1, ub = -1, label = :cm) constraint!(ocp, :variable; lb = [5, 5, 5, 5], ub = [5, 5, 5, 5], label = :cv1) constraint!(ocp, :variable; rg = 1:2, lb = [10, 20], ub = [10, 20], label = :cv2) constraint!(ocp, :variable; rg = Index(3), lb = 1000, ub = 1000, label = :cv3) constraint!(ocp, :variable; f = (r, v) -> (r[:] .= v[3]^2; nothing), lb = -10, ub = -10, label = :cv4) # dimensions (not set yet) @test dim_control_constraints(ocp) === nothing @test dim_state_constraints(ocp) === nothing @test dim_mixed_constraints(ocp) === nothing @test dim_path_constraints(ocp) === nothing @test dim_boundary_constraints(ocp) === nothing @test dim_variable_constraints(ocp) === nothing @test dim_control_range(ocp) === nothing @test dim_state_range(ocp) === nothing @test dim_variable_range(ocp) === nothing (ΞΎl, ΞΎ!, ΞΎu), (Ξ·l, Ξ·!, Ξ·u), (ψl, ψ!, ψu), (Ο•l, Ο•!, Ο•u), (ΞΈl, ΞΈ!, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu) = nlp_constraints!(ocp) v = [1, 2, 3, 4] # control @test sort(ΞΎl) == sort([20]) @test sort(ΞΎu) == sort([20]) r = [0.] ΞΎ!(r, -1, 1, v) @test sort(r) == sort([1 + v[2]]) # state @test sort(Ξ·l) == sort([100, 101]) @test sort(Ξ·u) == sort([100, 101]) r = [0., 0.] Ξ·!(r, -1, [1, 1], v) @test sort(r) == sort([1, 1] + v[1:2]) # mixed @test sort(ψl) == sort([-1]) @test sort(ψu) == sort([-1]) r = [0.] ψ!(r, -1, [1, 1], 2, v) @test sort(r) == sort([3 + v[2]]) # boundary @test sort(Ο•l) == sort([10, 1, 2]) @test sort(Ο•u) == sort([10, 1, 2]) r = [0., 0., 0.] Ο•!(r, [1, 3], [4, 100], v) @test sort(r) == sort([3, 4, 103 + v[1]]) # variable @test sort(ΞΈl) == sort([-10]) @test sort(ΞΈu) == sort([-10]) r = [0.] ΞΈ!(r, v) @test sort(r) == sort([v[3]^2]) # box constraint @test sort(ul) == sort([0]) @test sort(uind) == sort([1]) @test sort(uu) == sort([0]) @test sort(xl) == sort([0, 1]) @test sort(xind) == sort([1, 2]) @test sort(xu) == sort([0, 1]) @test sort(vl) == sort([5, 5, 5, 5, 10, 20, 1000]) @test sort(vind) == sort([1, 2, 3, 4, 1, 2, 3]) @test sort(vu) == sort([5, 5, 5, 5, 10, 20, 1000]) # dimensions @test dim_control_constraints(ocp) == 1 @test dim_state_constraints(ocp) == 2 @test dim_mixed_constraints(ocp) == 1 @test dim_path_constraints(ocp) == 4 @test dim_boundary_constraints(ocp) == 3 @test dim_variable_constraints(ocp) == 1 @test dim_control_range(ocp) == 1 @test dim_state_range(ocp) == 2 @test dim_variable_range(ocp) == 7 end @testset "val vs lb and ub, 2/2 (in place)" begin ocp = Model(variable = true, in_place = true) time!(ocp; t0 = 0, tf = 1) variable!(ocp, 4) state!(ocp, 2) control!(ocp, 1) constraint!(ocp, :initial; rg = Index(2), val = 10, label = :ci) constraint!(ocp, :final; rg = Index(1), val = 1, label = :cf) constraint!(ocp, :control; val = 0, label = :cu) constraint!(ocp, :state; val = [0, 1], label = :cs) constraint!(ocp, :boundary; f = (r, x0, xf, v) -> (r[:] .= x0[2] + xf[2] + v[1]; nothing), val = 2, label = :cb) constraint!(ocp, :control; f = (r, u, v) -> (r[:] .= u + v[2]; nothing), val = 20, label = :cuu) constraint!(ocp, :state; f = (r, x, v) -> (r[:] .= x + v[1:2]; nothing), val = [100, 101], label = :css) constraint!(ocp, :mixed; f = (r, x, u, v) -> (r[:] .= x[1] + u + v[2]; nothing), val = -1, label = :cm) constraint!(ocp, :variable; val = [5, 5, 5, 5], label = :cv1) constraint!(ocp, :variable; rg = 1:2, val = [10, 20], label = :cv2) constraint!(ocp, :variable; rg = Index(3), val = 1000, label = :cv3) constraint!(ocp, :variable; f = (r, v) -> (r[:] .= v[3]^2; nothing), val = -10, label = :cv4) # dimensions (not set yet) @test dim_control_constraints(ocp) === nothing @test dim_state_constraints(ocp) === nothing @test dim_mixed_constraints(ocp) === nothing @test dim_path_constraints(ocp) === nothing @test dim_boundary_constraints(ocp) === nothing @test dim_variable_constraints(ocp) === nothing @test dim_control_range(ocp) === nothing @test dim_state_range(ocp) === nothing @test dim_variable_range(ocp) === nothing (ΞΎl, ΞΎ!, ΞΎu), (Ξ·l, Ξ·!, Ξ·u), (ψl, ψ!, ψu), (Ο•l, Ο•!, Ο•u), (ΞΈl, ΞΈ!, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu) = nlp_constraints!(ocp) v = [1, 2, 3, 4] # control @test sort(ΞΎl) == sort([20]) @test sort(ΞΎu) == sort([20]) r = [0.] ΞΎ!(r, -1, 1, v) @test sort(r) == sort([1 + v[2]]) # state @test sort(Ξ·l) == sort([100, 101]) @test sort(Ξ·u) == sort([100, 101]) r = [0., 0.] Ξ·!(r, -1, [1, 1], v) @test sort(r) == sort([1, 1] + v[1:2]) # mixed @test sort(ψl) == sort([-1]) @test sort(ψu) == sort([-1]) r = [0.] ψ!(r, -1, [1, 1], 2, v) @test sort(r) == sort([3 + v[2]]) # boundary @test sort(Ο•l) == sort([10, 1, 2]) @test sort(Ο•u) == sort([10, 1, 2]) r = [0., 0., 0.] Ο•!(r, [1, 3], [4, 100], v) @test sort(r) == sort([3, 4, 103 + v[1]]) # variable @test sort(ΞΈl) == sort([-10]) @test sort(ΞΈu) == sort([-10]) r = [0.] ΞΈ!(r, v) @test sort(r) == sort([v[3]^2]) # box constraint @test sort(ul) == sort([0]) @test sort(uind) == sort([1]) @test sort(uu) == sort([0]) @test sort(xl) == sort([0, 1]) @test sort(xind) == sort([1, 2]) @test sort(xu) == sort([0, 1]) @test sort(vl) == sort([5, 5, 5, 5, 10, 20, 1000]) @test sort(vind) == sort([1, 2, 3, 4, 1, 2, 3]) @test sort(vu) == sort([5, 5, 5, 5, 10, 20, 1000]) # dimensions @test dim_control_constraints(ocp) == 1 @test dim_state_constraints(ocp) == 2 @test dim_mixed_constraints(ocp) == 1 @test dim_path_constraints(ocp) == 4 @test dim_boundary_constraints(ocp) == 3 @test dim_variable_constraints(ocp) == 1 @test dim_control_range(ocp) == 1 @test dim_state_range(ocp) == 2 @test dim_variable_range(ocp) == 7 end @testset "objective!" begin ocp = Model() @test_throws UnauthorizedCall objective!(ocp, :lagrange, (x, u) -> 0.5u^2) @test_throws UnauthorizedCall objective!(ocp, :mayer, (t0, x0, tf, xf) -> 0.5x0^2) @test_throws UnauthorizedCall objective!( ocp, :bolza, (t0, x0, tf, xf) -> 0.5x0^2, (x, u) -> 0.5u^2, ) ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) objective!(ocp, :lagrange, (x, u) -> 0.5u^2) @test lagrange(ocp)(1, 2) == 2 ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 2) objective!(ocp, :lagrange, (x, u) -> 0.5u[1]^2) @test lagrange(ocp)([1, 2], [3, 4]) == 4.5 ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) objective!(ocp, :mayer, (x0, xf) -> 0.5x0^2) @test mayer(ocp)(2, 3) == 2 ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 2) objective!(ocp, :mayer, (x0, xf) -> 0.5x0[1]^2) @test mayer(ocp)([2, 3], [5, 6]) == 2 ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) objective!(ocp, :bolza, (x0, xf) -> 0.5x0^2, (x, u) -> 0.5u^2) @test mayer(ocp)(2, 3) == 2 @test lagrange(ocp)(1, 2) == 2 ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 2) objective!(ocp, :bolza, (x0, xf) -> 0.5x0[1]^2, (x, u) -> 0.5u[1]^2) @test mayer(ocp)([2, 3], [5, 6]) == 2 @test lagrange(ocp)([1, 2], [3, 4]) == 4.5 ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 2) objective!(ocp, :lagrange, (x, u) -> 0.5u[1]^2) @test lagrange(ocp)([1, 2], [3, 4]) == 4.5 @test isnothing(mayer(ocp)) ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 2) control!(ocp, 2) objective!(ocp, :mayer, (x0, xf) -> 0.5x0[1]^2) @test mayer(ocp)([2, 3], [5, 6]) == 2 @test isnothing(lagrange(ocp)) end @testset "redeclarations" begin ocp = Model(variable = true) variable!(ocp, 1) @test_throws UnauthorizedCall variable!(ocp, 1) ocp = Model() time!(ocp; t0 = 0, tf = 1) @test_throws UnauthorizedCall time!(ocp; t0 = 0, tf = 1) ocp = Model() state!(ocp, 1) @test_throws UnauthorizedCall state!(ocp, 1) ocp = Model() control!(ocp, 1) @test_throws UnauthorizedCall control!(ocp, 1) ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) dynamics!(ocp, (x, u) -> x + u) @test_throws UnauthorizedCall dynamics!(ocp, (x, u) -> x + u) ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) objective!(ocp, :mayer, (x0, xf) -> x0 + xf) @test_throws UnauthorizedCall objective!(ocp, :mayer, (x0, xf) -> x0 + xf) ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) objective!(ocp, :lagrange, (x, u) -> x + u) @test_throws UnauthorizedCall objective!(ocp, :lagrange, (x, u) -> x + u) ocp = Model() time!(ocp; t0 = 0, tf = 1) state!(ocp, 1) control!(ocp, 1) objective!(ocp, :bolza, (x0, xf) -> x0 + xf, (x, u) -> x + u) @test_throws UnauthorizedCall objective!(ocp, :bolza, (x0, xf) -> x0 + xf, (x, u) -> x + u) end end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
73919
# test onepass function test_onepass() # --------------------------------------------------------------- # --------------------------------------------------------------- @testset "@def o syntax" begin println("@def o syntax testset...") oo = @def begin Ξ» ∈ R^2, variable tf = Ξ»β‚‚ t ∈ [0, tf], time end @test initial_time(oo) == 0 @test final_time(oo) == Index(2) a = 1 f(b) = begin # closure of a, local c, and @def in function c = 3 ocp = @def begin t ∈ [a, b], time x ∈ R, state u ∈ R, control αΊ‹(t) == x(t) + u(t) + b + c + d end return ocp end b = 2 o = f(b) d = 4 x = 10 u = 20 @test __dynamics(o)(x, u) == x + u + b + 3 + d end @testset "log" begin println("log testset...") @def o begin Ξ» ∈ R^2, variable tf = Ξ»β‚‚ t ∈ [0, tf], time end true @test initial_time(o) == 0 @test final_time(o) == Index(2) end # --------------------------------------------------------------- # --------------------------------------------------------------- @testset "aliases" begin println("aliases testset...") @def o begin x = (y, z) in RΒ², state u = (uu1, uu2, uu3) in RΒ³, control v = (vv1, vv2) in RΒ², variable end @test state_components_names(o) == ["y", "z"] @test control_components_names(o) == ["uu1", "uu2", "uu3"] @test variable_components_names(o) == ["vv1", "vv2"] @def o begin x = (y, z) ∈ RΒ², state u = (uu1, uu2, uu3) ∈ RΒ³, control v = (vv1, vv2) ∈ RΒ², variable end @test state_components_names(o) == ["y", "z"] @test control_components_names(o) == ["uu1", "uu2", "uu3"] @test variable_components_names(o) == ["vv1", "vv2"] @def o begin x = [y, z] ∈ RΒ², state u = [uu1, uu2, uu3] ∈ RΒ³, control v = [vv1, vv2] ∈ RΒ², variable end @test state_components_names(o) == ["y", "z"] @test control_components_names(o) == ["uu1", "uu2", "uu3"] @test variable_components_names(o) == ["vv1", "vv2"] @test_throws ParsingError @def o begin # a name must be provided (y, z) ∈ RΒ², state end @test_throws ParsingError @def o begin # a name must be provided (uu1, uu2, uu3) ∈ RΒ³, control end @test_throws ParsingError @def o begin # a name must be provided (vv1, vv2) ∈ RΒ², variable end @test_throws ParsingError @def o begin # a name must be provided [y, z] ∈ RΒ², state end @test_throws ParsingError @def o begin # a name must be provided [uu1, uu2, uu3] ∈ RΒ³, control end @test_throws ParsingError @def o begin # a name must be provided [vv1, vv2] ∈ RΒ², variable end @def o begin t ∈ [0, 1], time x = (r, v) ∈ RΒ², state u ∈ R, control w = r + 2v r(0) == 0, (1) v(0) == 1, (β™‘) xΜ‡(t) == [v(t), w(t)^2] ∫(u(t)^2 + x₁(t)) β†’ min end x = [1, 2] x0 = 2 * x xf = 3 * x u = 3 @test __constraint(o, :eq1)(x0, xf) == x0[1] @test __constraint(o, Symbol("β™‘"))(x0, xf) == x0[2] @test __dynamics(o)(x, u) == [x[2], (x[1] + 2x[2])^2] @test __lagrange(o)(x, u) == u^2 + x[1] @def o begin t ∈ [0, 1], time x = [r, v] ∈ RΒ², state u ∈ R, control w = r + 2v r(0) == 0, (1) v(0) == 1, (β™‘) xΜ‡(t) == [v(t), w(t)^2] ∫(u(t)^2 + x₁(t)) β†’ min end x = [1, 2] x0 = 2 * x xf = 3 * x u = 3 @test __constraint(o, :eq1)(x0, xf) == x0[1] @test __constraint(o, Symbol("β™‘"))(x0, xf) == x0[2] @test __dynamics(o)(x, u) == [x[2], (x[1] + 2x[2])^2] @test __lagrange(o)(x, u) == u^2 + x[1] @def o begin t ∈ [0, 1], time x = [r, v] ∈ RΒ², state c = [u, b] ∈ RΒ², control w = r + 2v b(t) == 0 r(0) == 0, (1) v(0) == 1, (β™‘) xΜ‡(t) == [v(t), w(t)^2] ∫(u(t)^2 + b(t)^2 + x₁(t)) β†’ min end x = [1, 2] x0 = 2 * x xf = 3 * x u = 3 c = [u, 0] @test __constraint(o, :eq1)(x0, xf) == x0[1] @test __constraint(o, Symbol("β™‘"))(x0, xf) == x0[2] @test __dynamics(o)(x, c) == [x[2], (x[1] + 2x[2])^2] @test __lagrange(o)(x, c) == u^2 + x[1] @def o begin t ∈ [0, 1], time x ∈ R^3, state u = (u₁, v) ∈ R^2, control xΜ‡(t) == [x[1](t) + 2v(t), 2x[3](t), x[1](t) + v(t)] end @test state_dimension(o) == 3 @test control_dimension(o) == 2 x = [1, 2, 3] u = [-1, 2] @test __dynamics(o)(x, u) == [x[1] + 2u[2], 2x[3], x[1] + u[2]] t0 = 0.0 tf = 0.1 @def ocp begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control r = x[1] v = xβ‚‚ a = x₃ end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test control_name(ocp) == "u" @test control_dimension(ocp) == 3 @test state_name(ocp) == "x" @test state_dimension(ocp) == 3 end # --------------------------------------------------------------- # --------------------------------------------------------------- @testset "variable" begin println("variable testset...") @def o begin Ξ» ∈ R^2, variable tf = Ξ»β‚‚ t ∈ [0, tf], time end @test initial_time(o) == 0 @test final_time(o) == Index(2) @def o begin Ξ» = (λ₁, tf) ∈ R^2, variable t ∈ [0, tf], time end @test initial_time(o) == 0 @test final_time(o) == Index(2) @def o begin t0 ∈ R, variable t ∈ [t0, 1], time end @test initial_time(o) == Index(1) @test final_time(o) == 1 @def o begin tf ∈ R, variable t ∈ [0, tf], time end @test initial_time(o) == 0 @test final_time(o) == Index(1) @def o begin v ∈ RΒ², variable s ∈ [v[1], v[2]], time end @test initial_time(o) == Index(1) @test final_time(o) == Index(2) @def o begin v ∈ RΒ², variable s0 = v₁ sf = vβ‚‚ s ∈ [s0, sf], time end @test initial_time(o) == Index(1) @test final_time(o) == Index(2) @test_throws IncorrectArgument @def o begin t0 ∈ RΒ², variable t ∈ [t0, 1], time end @test_throws IncorrectArgument @def o begin tf ∈ RΒ², variable t ∈ [0, tf], time end @test_throws ParsingError @def o begin v, variable t ∈ [0, tf[v]], time end @test_throws ParsingError @def o begin v, variable t ∈ [t0[v], 1], time end @test_throws ParsingError @def o begin v, variable t ∈ [t0[v], tf[v + 1]], time end t0 = 0.0 tf = 0.1 @def ocp begin t ∈ [t0, tf], time a ∈ R, variable end @test ocp isa OptimalControlModel @test variable_dimension(ocp) == 1 @test variable_name(ocp) == "a" t0 = 0.0 tf = 0.1 @def ocp begin t ∈ [t0, tf], time a ∈ RΒ³, variable end @test ocp isa OptimalControlModel @test variable_dimension(ocp) == 3 @test variable_name(ocp) == "a" end # --------------------------------------------------------------- # --------------------------------------------------------------- @testset "time" begin println("time testset...") t0 = 0 @def o t ∈ [t0, t0 + 4], time @test initial_time(o) == t0 @test final_time(o) == t0 + 4 @test_throws ParsingError @def o t ∈ 1 @def ocp t ∈ [0.0, 1.0], time @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == 0.0 @test final_time(ocp) == 1.0 t0 = 3.0 @def ocp begin tf ∈ R, variable t ∈ [t0, tf], time end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == Index(1) tf = 3.14 @def ocp begin t0 ∈ R, variable t ∈ [t0, tf], time end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == Index(1) @test final_time(ocp) == tf end # --------------------------------------------------------------- # --------------------------------------------------------------- @testset "state / control" begin println("state / control testset...") @def o begin x ∈ R, state u ∈ R, control end @test state_dimension(o) == 1 @test control_dimension(o) == 1 # state t0 = 1.0 tf = 1.1 @def ocp begin t ∈ [t0, tf], time u ∈ R, state end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test state_dimension(ocp) == 1 @test state_name(ocp) == "u" t0 = 2.0 tf = 2.1 @def ocp begin t ∈ [t0, tf], time v ∈ R^4, state end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test state_dimension(ocp) == 4 @test state_name(ocp) == "v" t0 = 3.0 tf = 3.1 @def ocp begin t ∈ [t0, tf], time w ∈ R^3, state end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test state_dimension(ocp) == 3 @test state_name(ocp) == "w" t0 = 4.0 tf = 4.1 @def ocp begin t ∈ [t0, tf], time a ∈ R, state end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test state_dimension(ocp) == 1 @test state_name(ocp) == "a" t0 = 5.0 tf = 5.1 @def ocp begin t ∈ [t0, tf], time b ∈ RΒΉ, state end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test state_dimension(ocp) == 1 @test state_name(ocp) == "b" t0 = 6.0 tf = 6.1 @def ocp begin t ∈ [t0, tf], time u ∈ R⁹, state end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test state_dimension(ocp) == 9 @test state_name(ocp) == "u" n = 3 t0 = 7.0 tf = 7.1 @def ocp begin t ∈ [t0, tf], time u ∈ R^n, state end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test state_dimension(ocp) == n @test state_name(ocp) == "u" # control t0 = 1.0 tf = 1.1 @def ocp begin t ∈ [t0, tf], time u ∈ R, control end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test control_dimension(ocp) == 1 @test control_name(ocp) == "u" t0 = 2.0 tf = 2.1 @def ocp begin t ∈ [t0, tf], time v ∈ R^4, control end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test control_dimension(ocp) == 4 @test control_name(ocp) == "v" t0 = 3.0 tf = 3.1 @def ocp begin t ∈ [t0, tf], time w ∈ R^3, control end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test control_dimension(ocp) == 3 @test control_name(ocp) == "w" t0 = 4.0 tf = 4.1 @def ocp begin t ∈ [t0, tf], time a ∈ R, control end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test control_dimension(ocp) == 1 @test control_name(ocp) == "a" t0 = 5.0 tf = 5.1 @def ocp begin t ∈ [t0, tf], time b ∈ RΒΉ, control end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test control_dimension(ocp) == 1 @test control_name(ocp) == "b" t0 = 6.0 tf = 6.1 @def ocp begin t ∈ [t0, tf], time u ∈ R⁹, control end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test control_dimension(ocp) == 9 @test control_name(ocp) == "u" n = 3 t0 = 7.0 tf = 7.1 @def ocp begin t ∈ [t0, tf], time u ∈ R^n, control end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test control_dimension(ocp) == n @test control_name(ocp) == "u" end # --------------------------------------------------------------- # --------------------------------------------------------------- @testset "dynamics" begin println("dynamics testset...") @def o begin t ∈ [0, 1], time x ∈ R^3, state u ∈ R^2, control xΜ‡(t) == [x[1](t) + 2u[2](t), 2x[3](t), x[1](t) + u[2](t)] end @test state_dimension(o) == 3 @test control_dimension(o) == 2 x = [1, 2, 3] u = [-1, 2] @test __dynamics(o)(x, u) == [x[1] + 2u[2], 2x[3], x[1] + u[2]] @def o begin z ∈ RΒ², variable s ∈ [0, z₁], time y ∈ R⁴, state w ∈ R, control r = y₃ v = yβ‚„ aa = y₁ yΜ‡(s) == [aa(s), rΒ²(s) + w(s) + z₁, 0, 0] end z = [5, 6] y = [1, 2, 3, 4] w = 9 @test __dynamics(o)(y, w, z) == [y[1], y[3]^2 + w + z[1], 0, 0] @def o begin z ∈ RΒ², variable __s ∈ [0, z₁], time y ∈ R⁴, state w ∈ R, control r = y₃ v = yβ‚„ aa = y₁(__s) yΜ‡(__s) == [aa(__s), rΒ²(__s) + w(__s) + z₁, 0, 0] end z = [5, 6] y = [1, 2, 3, 4] w = 9 @test_throws MethodError __dynamics(o)(y, w, z) @def o begin z ∈ RΒ², variable s ∈ [0, z₁], time y ∈ R⁴, state w ∈ R, control r = y₃ v = yβ‚„ aa = y₁(s) + vΒ³ + zβ‚‚ yΜ‡(s) == [aa(s) + w(s)^2, rΒ²(s), 0, 0] end z = [5, 6] y = [1, 2, 3, 4] y0 = y yf = 3y0 ww = 19 @test __dynamics(o)(y, ww, z) == [y[1] + ww^2 + y[4]^3 + z[2], y[3]^2, 0, 0] @def o begin z ∈ RΒ², variable __t ∈ [0, z₁], time y ∈ R⁴, state w ∈ R, control r = y₃ v = yβ‚„ aa = y₁(0) + vΒ³ + zβ‚‚ yΜ‡(__t) == [aa(__t) + (w^2)(__t), rΒ²(__t), 0, 0] aa(0) + yβ‚‚(z₁) β†’ min end z = [5, 6] y = [1, 2, 3, 4] y0 = y yf = 3y0 w = 11 @test_throws MethodError __dynamics(o)(y, w, z) @test __mayer(o)(y0, yf, z) == y0[1] + y0[4]^3 + z[2] + yf[2] end # --------------------------------------------------------------- # --------------------------------------------------------------- @testset "constraints" begin println("constraints testset...") @def o begin tf ∈ R, variable t ∈ [0, tf], time x ∈ RΒ², state u ∈ R, control r = x₁ v = xβ‚‚ w = rΒΉ + 2vΒ³ r(0) + w(tf) - tfΒ² == 0, (1) end tf = 2 x0 = [1, 2] xf = [3, 4] @test __constraint(o, :eq1)(x0, xf, tf) == x0[1] + (xf[1] + 2xf[2]^3) - tf^2 n = 11 m = 6 @def o begin t ∈ [0, 1], time x ∈ R^n, state u ∈ R^m, control r = x₁ v = xβ‚‚ 0 ≀ r(t) ≀ 1, (1) zeros(n) ≀ x(t) ≀ ones(n), (2) [0, 0] ≀ x[1:2](t) ≀ [1, 1], (3) [0, 0] ≀ x[1:2:4](t) ≀ [1, 1], (4) 0 ≀ v(t)^2 ≀ 1, (5) zeros(m) ≀ u(t) ≀ ones(m), (6) [0, 0] ≀ u[1:2](t) ≀ [1, 1], (7) [0, 0] ≀ u[1:2:4](t) ≀ [1, 1], (8) 0 ≀ uβ‚‚(t)^2 ≀ 1, (9) u₁(t) * x[1:2](t) == [1, 1], (10) [0, 0] ≀ u₁(t) * x[1:2](t) .^ 3 ≀ [1, 1], (11) end x = Vector{Float64}(1:n) u = 2 * Vector{Float64}(1:m) @test __constraint(o, :eq1)(x) == x[1] @test __constraint(o, :eq2)(x) == x @test __constraint(o, :eq3)(x) == x[1:2] @test __constraint(o, :eq4)(x) == x[1:2:4] @test __constraint(o, :eq5)(x) == x[2]^2 @test __constraint(o, :eq6)(u) == u @test __constraint(o, :eq7)(u) == u[1:2] @test __constraint(o, :eq8)(u) == u[1:2:4] @test __constraint(o, :eq9)(u) == u[2]^2 @test __constraint(o, :eq10)(x, u) == u[1] * x[1:2] @test __constraint(o, :eq11)(x, u) == u[1] * x[1:2] .^ 3 n = 11 m = 6 @def o begin z ∈ R^2, variable t ∈ [0, 1], time x ∈ R^n, state u ∈ R^m, control r = x₁ v = xβ‚‚ 0 ≀ r(t) ≀ 1, (1) zeros(n) ≀ x(t) ≀ ones(n), (2) [0, 0] ≀ x[1:2](t) - [z₁, 1] ≀ [1, 1], (3) [0, 0] ≀ x[1:2:4](t) ≀ [1, 1], (4) 0 ≀ v(t)^2 ≀ 1, (5) zeros(m) ≀ u(t) ≀ ones(m), (6) [0, 0] ≀ u[1:2](t) ≀ [1, 1], (7) [0, 0] ≀ u[1:2:4](t) ≀ [1, 1], (8) 0 ≀ uβ‚‚(t)^2 ≀ 1, (9) u₁(t) * x[1:2](t) + z + f() == [1, 1], (10) [0, 0] ≀ u₁(t) * x[1:2](t) .^ 3 + z ≀ [1, 1], (11) end f() = [1, 1] z = 3 * Vector{Float64}(1:2) x = Vector{Float64}(1:n) u = 2 * Vector{Float64}(1:m) @test __constraint(o, :eq1)(x, z) == x[1] @test __constraint(o, :eq2)(x, z) == x @test __constraint(o, :eq3)(x, z) == x[1:2] - [z[1], 1] @test __constraint(o, :eq4)(x, z) == x[1:2:4] @test __constraint(o, :eq5)(x, z) == x[2]^2 @test __constraint(o, :eq6)(u, z) == u @test __constraint(o, :eq7)(u, z) == u[1:2] @test __constraint(o, :eq8)(u, z) == u[1:2:4] @test __constraint(o, :eq9)(u, z) == u[2]^2 @test __constraint(o, :eq10)(x, u, z) == u[1] * x[1:2] + z + f() @test __constraint(o, :eq11)(x, u, z) == u[1] * x[1:2] .^ 3 + z @def o begin t ∈ [0, 1], time x ∈ RΒ², state u ∈ R, control begin r = x₁ v = xβ‚‚ w = r + 2v r(0) == 0, (1) end v(0) == 1, (β™‘) xΜ‡(t) == [v(t), w(t)^2] ∫(u(t)^2 + x₁(t)) β†’ min end x = [1, 2] x0 = 2 * x xf = 3 * x u = 3 @test __constraint(o, :eq1)(x0, xf) == x0[1] @test __constraint(o, Symbol("β™‘"))(x0, xf) == x0[2] @test __dynamics(o)(x, u) == [x[2], (x[1] + 2x[2])^2] @test __lagrange(o)(x, u) == u^2 + x[1] @def o begin t ∈ [0, 1], time x ∈ RΒ², state u ∈ R, control r = x₁ v = xβ‚‚ w = r + 2v r(0) == 0, (1) v(0) == 1, (β™‘) xΜ‡(t) == [v(t), w(t)^2] ∫(u(t)^2 + x₁(t)) β†’ min end x = [1, 2] x0 = 2 * x xf = 3 * x u = 3 @test __constraint(o, :eq1)(x0, xf) == x0[1] @test __constraint(o, Symbol("β™‘"))(x0, xf) == x0[2] @test __dynamics(o)(x, u) == [x[2], (x[1] + 2x[2])^2] @test __lagrange(o)(x, u) == u^2 + x[1] @def o begin z ∈ RΒ², variable t ∈ [0, 1], time x ∈ RΒ², state u ∈ R, control r = x₁ v = xβ‚‚ w = r + 2v r(0) == 0, (1) v(0) == 1, (β™‘) xΜ‡(t) == [v(t), w(t)^2 + z₁] ∫(u(t)^2 + zβ‚‚ * x₁(t)) β†’ min end x = [1, 2] x0 = 2 * [1, 2] xf = 3 * [1, 2] u = 3 z = [4, 5] @test __constraint(o, :eq1)(x0, xf, z) == x0[1] @test __constraint(o, Symbol("β™‘"))(x0, xf, z) == x0[2] @test __dynamics(o)(x, u, z) == [x[2], (x[1] + 2x[2])^2 + z[1]] @test __lagrange(o)(x, u, z) == u^2 + z[2] * x[1] @def o begin t ∈ [0, 1], time x ∈ RΒ², state u ∈ R, control r = x₁ v = xβ‚‚ r(0)^2 + v(1) == 0, (1) v(0) == 1, (β™‘) xΜ‡(t) == [v(t), r(t)^2] ∫(u(t)^2 + x₁(t)) β†’ min end x0 = [2, 3] xf = [4, 5] x = [1, 2] u = 3 @test __constraint(o, :eq1)(x0, xf) == x0[1]^2 + xf[2] @test __constraint(o, Symbol("β™‘"))(x0, xf) == x0[2] @test __dynamics(o)(x, u) == [x[2], x[1]^2] @test __lagrange(o)(x, u) == u^2 + x[1] @def o begin z ∈ R, variable t ∈ [0, 1], time x ∈ RΒ², state u ∈ R, control r = x₁ v = xβ‚‚ r(0) - z == 0, (1) v(0) == 1, (β™‘) xΜ‡(t) == [v(t), r(t)^2 + z] ∫(u(t)^2 + z * x₁(t)) β†’ min end x0 = [2, 3] xf = [4, 5] x = [1, 2] u = 3 z = 4 @test __constraint(o, :eq1)(x0, xf, z) == x0[1] - z @test __constraint(o, Symbol("β™‘"))(x0, xf, z) == x0[2] @test __dynamics(o)(x, u, z) == [x[2], x[1]^2 + z] @test __lagrange(o)(x, u, z) == u^2 + z * x[1] @def o begin z ∈ R, variable t ∈ [0, 1], time x ∈ RΒ², state u ∈ R, control r = x₁ v = xβ‚‚ 0 ≀ r(0) - z ≀ 1, (1) 0 ≀ v(1)^2 ≀ 1, (2) [0, 0] ≀ x(0) ≀ [1, 1], (β™‘) xΜ‡(t) == [v(t), r(t)^2 + z] ∫(u(t)^2 + z * x₁(t)) β†’ min end x0 = [2, 3] xf = [4, 5] x = [1, 2] u = 3 z = 4 @test __constraint(o, :eq1)(x0, xf, z) == x0[1] - z @test __constraint(o, :eq2)(x0, xf, z) == xf[2]^2 @test __constraint(o, Symbol("β™‘"))(x0, xf, z) == x0 @test __dynamics(o)(x, u, z) == [x[2], x[1]^2 + z] @test __lagrange(o)(x, u, z) == u^2 + z * x[1] @def o begin z ∈ R, variable t ∈ [0, 1], time x ∈ RΒ², state u ∈ R, control r = x₁ v = xβ‚‚ 1 β‰₯ r(0) - z β‰₯ 0, (1) 1 β‰₯ v(1)^2 β‰₯ 0, (2) [1, 1] β‰₯ x(0) β‰₯ [0, 0], (3) xΜ‡(t) == [v(t), r(t)^2 + z] ∫(u(t)^2 + z * x₁(t)) β†’ min end x0 = [2, 3] xf = [4, 5] x = [1, 2] u = 3 z = 4 @test __constraint(o, :eq1)(x0, xf, z) == x0[1] - z @test __constraint(o, :eq2)(x0, xf, z) == xf[2]^2 @test __constraint(o, :eq3)(x0, xf, z) == x0 @test __dynamics(o)(x, u, z) == [x[2], x[1]^2 + z] @test __lagrange(o)(x, u, z) == u^2 + z * x[1] @test constraints(o)[:eq1][3] == 0 @test constraints(o)[:eq1][4] == 1 @test constraints(o)[:eq2][3] == 0 @test constraints(o)[:eq2][4] == 1 @test constraints(o)[:eq3][3] == [0, 0] @test constraints(o)[:eq3][4] == [1, 1] @def o begin v ∈ RΒ², variable t ∈ [0, 1], time x ∈ R, state u ∈ R, control x(0) - v₁ == 0, (1) x(1) - v₁ == 0, (2) 0 ≀ x(0) - v₁ ≀ 1, (3) 0 ≀ x(1) - v₁ ≀ 1, (4) x(0) + x(1) - vβ‚‚ == 0, (5) 0 ≀ x(0) + x(1) - vβ‚‚ ≀ 1, (6) x(t) - v₁ == 0, (7) u(t) - v₁ == 0, (8) z = v₁ + 2vβ‚‚ 0 ≀ x(t) - z ≀ 1, (9) 0 ≀ u(t) - z ≀ 1, (10) 0 ≀ x(t) + u(t) - z ≀ 1, (11) xΜ‡(t) == z * x(t) + 2u(t) v₁ == 1, (12) 0 ≀ v₁ ≀ 1, (13) z == 1, (14) 0 ≀ z ≀ 1, (15) z * x(1) β†’ min end x = 1 x0 = 2 xf = 3 u = 4 v = [5, 6] z = v[1] + 2v[2] @test __constraint(o, :eq1)(x0, xf, v) == x0 - v[1] @test __constraint(o, :eq2)(x0, xf, v) == xf - v[1] @test __constraint(o, :eq3)(x0, xf, v) == x0 - v[1] @test __constraint(o, :eq4)(x0, xf, v) == xf - v[1] @test __constraint(o, :eq5)(x0, xf, v) == x0 + xf - v[2] @test __constraint(o, :eq6)(x0, xf, v) == x0 + xf - v[2] @test __constraint(o, :eq7)(x, v) == x - v[1] @test __constraint(o, :eq9)(x, v) == x - z @test __constraint(o, :eq10)(u, v) == u - z @test __constraint(o, :eq11)(x, u, v) == x + u - z @test __constraint(o, :eq12)(v) == v[1] @test __constraint(o, :eq13)(v) == v[1] @test __constraint(o, :eq14)(v) == v[1] + 2v[2] @test __constraint(o, :eq15)(v) == v[1] + 2v[2] @def o begin v ∈ R, variable t ∈ [0, 1], time x ∈ R, state u ∈ RΒ², control x(0) ≀ 0 x(0) ≀ 0, (1) x(1) ≀ 0 x(1) ≀ 0, (2) xΒ³(0) ≀ 0 xΒ³(0) ≀ 0, (3) xΒ³(1) ≀ 0 xΒ³(1) ≀ 0, (4) x(t) ≀ 0 x(t) ≀ 0, (5) x(t) ≀ 0 x(t) ≀ 0, (6) u₁(t) ≀ 0 u₁(t) ≀ 0, (7) u₁(t) ≀ 0 u₁(t) ≀ 0, (8) xΒ³(t) ≀ 0 xΒ³(t) ≀ 0, (9) xΒ³(t) ≀ 0 xΒ³(t) ≀ 0, (10) (u₁^3)(t) ≀ 0 (u₁^3)(t) ≀ 0, (11) (u₁^3)(t) ≀ 0 (u₁^3)(t) ≀ 0, (12) x(t) + (u₁^3)(t) ≀ 0 x(t) + (u₁^3)(t) ≀ 0, (13) x(t) + (u₁^3)(t) ≀ 0 x(t) + (u₁^3)(t) ≀ 0, (14) v ≀ 0 v ≀ 0, (15) end @test constraints(o)[:eq1][3] == -Inf @test constraints(o)[:eq2][3] == -Inf @test constraints(o)[:eq3][3] == -Inf @test constraints(o)[:eq4][3] == -Inf @test constraints(o)[:eq5][3] == -Inf @test constraints(o)[:eq6][3] == -Inf @test constraints(o)[:eq7][3] == -Inf @test constraints(o)[:eq8][3] == -Inf @test constraints(o)[:eq9][3] == -Inf @test constraints(o)[:eq10][3] == -Inf @test constraints(o)[:eq11][3] == -Inf @test constraints(o)[:eq12][3] == -Inf @test constraints(o)[:eq13][3] == -Inf @test constraints(o)[:eq14][3] == -Inf @test constraints(o)[:eq15][3] == -Inf @test constraints(o)[:eq1][4] == 0 @test constraints(o)[:eq2][4] == 0 @test constraints(o)[:eq3][4] == 0 @test constraints(o)[:eq4][4] == 0 @test constraints(o)[:eq5][4] == 0 @test constraints(o)[:eq6][4] == 0 @test constraints(o)[:eq7][4] == 0 @test constraints(o)[:eq8][4] == 0 @test constraints(o)[:eq9][4] == 0 @test constraints(o)[:eq10][4] == 0 @test constraints(o)[:eq11][4] == 0 @test constraints(o)[:eq12][4] == 0 @test constraints(o)[:eq13][4] == 0 @test constraints(o)[:eq14][4] == 0 @test constraints(o)[:eq15][4] == 0 @def o begin v ∈ R, variable t ∈ [0, 1], time x ∈ R, state u ∈ RΒ², control x(0) β‰₯ 0 x(0) β‰₯ 0, (1) x(1) β‰₯ 0 x(1) β‰₯ 0, (2) xΒ³(0) β‰₯ 0 xΒ³(0) β‰₯ 0, (3) xΒ³(1) β‰₯ 0 xΒ³(1) β‰₯ 0, (4) x(t) β‰₯ 0 x(t) β‰₯ 0, (5) x(t) β‰₯ 0 x(t) β‰₯ 0, (6) u₁(t) β‰₯ 0 u₁(t) β‰₯ 0, (7) u₁(t) β‰₯ 0 u₁(t) β‰₯ 0, (8) xΒ³(t) β‰₯ 0 xΒ³(t) β‰₯ 0, (9) xΒ³(t) β‰₯ 0 xΒ³(t) β‰₯ 0, (10) (u₁^3)(t) β‰₯ 0 (u₁^3)(t) β‰₯ 0, (11) (u₁^3)(t) β‰₯ 0 (u₁^3)(t) β‰₯ 0, (12) x(t) + (u₁^3)(t) β‰₯ 0 x(t) + (u₁^3)(t) β‰₯ 0, (13) x(t) + (u₁^3)(t) β‰₯ 0 x(t) + (u₁^3)(t) β‰₯ 0, (14) v β‰₯ 0 v β‰₯ 0, (15) end @test constraints(o)[:eq1][3] == 0 @test constraints(o)[:eq2][3] == 0 @test constraints(o)[:eq3][3] == 0 @test constraints(o)[:eq4][3] == 0 @test constraints(o)[:eq5][3] == 0 @test constraints(o)[:eq6][3] == 0 @test constraints(o)[:eq7][3] == 0 @test constraints(o)[:eq8][3] == 0 @test constraints(o)[:eq9][3] == 0 @test constraints(o)[:eq10][3] == 0 @test constraints(o)[:eq11][3] == 0 @test constraints(o)[:eq12][3] == 0 @test constraints(o)[:eq13][3] == 0 @test constraints(o)[:eq14][3] == 0 @test constraints(o)[:eq15][3] == 0 @test constraints(o)[:eq1][4] == Inf @test constraints(o)[:eq2][4] == Inf @test constraints(o)[:eq3][4] == Inf @test constraints(o)[:eq4][4] == Inf @test constraints(o)[:eq5][4] == Inf @test constraints(o)[:eq6][4] == Inf @test constraints(o)[:eq7][4] == Inf @test constraints(o)[:eq8][4] == Inf @test constraints(o)[:eq9][4] == Inf @test constraints(o)[:eq10][4] == Inf @test constraints(o)[:eq11][4] == Inf @test constraints(o)[:eq12][4] == Inf @test constraints(o)[:eq13][4] == Inf @test constraints(o)[:eq14][4] == Inf @test constraints(o)[:eq15][4] == Inf @def o begin v ∈ R^2, variable t ∈ [0, 1], time x ∈ RΒ², state u ∈ RΒ², control x(0) ≀ [0, 0] x(0) ≀ [0, 0], (1) x(1) ≀ [0, 0] x(1) ≀ [0, 0], (2) [x₁(0)^3, 0] ≀ [0, 0] [x₁(0)^3, 0] ≀ [0, 0], (3) x(t) ≀ [0, 0] x(t) ≀ [0, 0], (4) u(t) ≀ [0, 0] u(t) ≀ [0, 0], (5) [x₁(t)^3, 0] ≀ [0, 0] [x₁(t)^3, 0] ≀ [0, 0], (6) [u₁(t)^3, 0] ≀ [0, 0] [u₁(t)^3, 0] ≀ [0, 0], (7) [u₁(t)^3, x₁(t)] ≀ [0, 0] [u₁(t)^3, x₁(t)] ≀ [0, 0], (8) v ≀ [0, 0] v ≀ [0, 0], (9) [v₁^2, 0] ≀ [0, 0] [v₁^2, 0] ≀ [0, 0], (10) end @test constraints(o)[:eq1][3] == -[Inf, Inf] @test constraints(o)[:eq2][3] == -[Inf, Inf] @test constraints(o)[:eq3][3] == -[Inf, Inf] @test constraints(o)[:eq4][3] == -[Inf, Inf] @test constraints(o)[:eq5][3] == -[Inf, Inf] @test constraints(o)[:eq6][3] == -[Inf, Inf] @test constraints(o)[:eq7][3] == -[Inf, Inf] @test constraints(o)[:eq8][3] == -[Inf, Inf] @test constraints(o)[:eq9][3] == -[Inf, Inf] @test constraints(o)[:eq10][3] == -[Inf, Inf] @test constraints(o)[:eq1][4] == [0, 0] @test constraints(o)[:eq2][4] == [0, 0] @test constraints(o)[:eq3][4] == [0, 0] @test constraints(o)[:eq4][4] == [0, 0] @test constraints(o)[:eq5][4] == [0, 0] @test constraints(o)[:eq6][4] == [0, 0] @test constraints(o)[:eq7][4] == [0, 0] @test constraints(o)[:eq8][4] == [0, 0] @test constraints(o)[:eq9][4] == [0, 0] @test constraints(o)[:eq10][4] == [0, 0] @def o begin v ∈ R^2, variable t ∈ [0, 1], time x ∈ RΒ², state u ∈ RΒ², control x(0) β‰₯ [0, 0] x(0) β‰₯ [0, 0], (1) x(1) β‰₯ [0, 0] x(1) β‰₯ [0, 0], (2) [x₁(0)^3, 0] β‰₯ [0, 0] [x₁(0)^3, 0] β‰₯ [0, 0], (3) x(t) β‰₯ [0, 0] x(t) β‰₯ [0, 0], (4) u(t) β‰₯ [0, 0] u(t) β‰₯ [0, 0], (5) [x₁(t)^3, 0] β‰₯ [0, 0] [x₁(t)^3, 0] β‰₯ [0, 0], (6) [u₁(t)^3, 0] β‰₯ [0, 0] [u₁(t)^3, 0] β‰₯ [0, 0], (7) [u₁(t)^3, x₁(t)] β‰₯ [0, 0] [u₁(t)^3, x₁(t)] β‰₯ [0, 0], (8) v β‰₯ [0, 0] v β‰₯ [0, 0], (9) [v₁^2, 0] β‰₯ [0, 0] [v₁^2, 0] β‰₯ [0, 0], (10) end @test constraints(o)[:eq1][4] == [Inf, Inf] @test constraints(o)[:eq2][4] == [Inf, Inf] @test constraints(o)[:eq3][4] == [Inf, Inf] @test constraints(o)[:eq4][4] == [Inf, Inf] @test constraints(o)[:eq5][4] == [Inf, Inf] @test constraints(o)[:eq6][4] == [Inf, Inf] @test constraints(o)[:eq7][4] == [Inf, Inf] @test constraints(o)[:eq8][4] == [Inf, Inf] @test constraints(o)[:eq9][4] == [Inf, Inf] @test constraints(o)[:eq10][4] == [Inf, Inf] @test constraints(o)[:eq1][3] == [0, 0] @test constraints(o)[:eq2][3] == [0, 0] @test constraints(o)[:eq3][3] == [0, 0] @test constraints(o)[:eq4][3] == [0, 0] @test constraints(o)[:eq5][3] == [0, 0] @test constraints(o)[:eq6][3] == [0, 0] @test constraints(o)[:eq7][3] == [0, 0] @test constraints(o)[:eq8][3] == [0, 0] @test constraints(o)[:eq9][3] == [0, 0] @test constraints(o)[:eq10][3] == [0, 0] t0 = 9.0 tf = 9.1 r0 = 1.0 r1 = 2.0 v0 = 2.0 vmax = sqrt(2) m0 = 3.0 mf = 1.1 @def ocp begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^2, control m = xβ‚‚ x(t0) == [r0, v0, m0], (1) 0 ≀ u[1](t) ≀ 1, (deux) r0 ≀ x(t)[1] ≀ r1, (trois) 0 ≀ xβ‚‚(t) ≀ vmax, (quatre) mf ≀ m(t) ≀ m0, (5) end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test control_name(ocp) == "u" @test control_dimension(ocp) == 2 @test state_name(ocp) == "x" @test state_dimension(ocp) == 3 @def ocp begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^2, control m = xβ‚‚ x(t0) == [r0, v0, m0] 0 ≀ u(t)[2] ≀ 1 r0 ≀ x(t)[1] ≀ r1 0 ≀ xβ‚‚(t) ≀ vmax mf ≀ m(t) ≀ m0 end @test ocp isa OptimalControlModel @test time_name(ocp) == "t" @test initial_time(ocp) == t0 @test final_time(ocp) == tf @test control_name(ocp) == "u" @test control_dimension(ocp) == 2 @test state_name(ocp) == "x" @test state_dimension(ocp) == 3 # dyslexic definition: t -> u -> x -> t u0 = 9.0 uf = 9.1 z0 = 1.0 z1 = 2.0 k0 = 2.0 kmax = sqrt(2) b0 = 3.0 bf = 1.1 @def ocp begin u ∈ [u0, uf], time t ∈ R^3, state x ∈ R^2, control b = tβ‚‚ t(u0) == [z0, k0, b0] 0 ≀ x[2](u) ≀ 1 z0 ≀ t(u)[1] ≀ z1 0 ≀ tβ‚‚(u) ≀ kmax bf ≀ b(u) ≀ b0 end @test ocp isa OptimalControlModel @test time_name(ocp) == "u" @test initial_time(ocp) == u0 @test final_time(ocp) == uf @test control_name(ocp) == "x" @test control_dimension(ocp) == 2 @test state_name(ocp) == "t" @test state_dimension(ocp) == 3 # # test all constraints on @def macro # # ref: https://github.com/control-toolbox/CTBase.jl/issues/9 # #function test_ctparser_constraints() # all used variables must be definedbefore each test x0 = [1, 2, 11.11] x02 = 11.111 x0_b = 11.1111 x0_u = 11.11111 y0 = [1, 2.22] y0_b = [1, 2.222] y0_u = [2, 2.2222] # === initial t0 = 0.0 tf = 1.0 n = 3 @def ocp1 begin t ∈ [t0, tf], time x ∈ R^n, state u ∈ R^n, control x(t0) == x0 x[2](t0) == x02 x[2:3](t0) == y0 x0_b ≀ xβ‚‚(t0) ≀ x0_u y0_b ≀ x[2:3](t0) ≀ y0_u end @test ocp1 isa OptimalControlModel @test state_dimension(ocp1) == n @test control_dimension(ocp1) == n @test initial_time(ocp1) == t0 @test final_time(ocp1) == tf t0 = 0.1 tf = 1.1 x0 = ones(4) n = 4 @def ocp2 begin t ∈ [t0, tf], time x ∈ R^n, state u ∈ R^n, control x(t0) == x0, initial_1 x[2](t0) == 1, initial_2 x[2:3](t0) == [1, 2], initial_3 x0 ≀ x(t0) ≀ x0 .+ 1, initial_4 [1, 2] ≀ x[2:3](t0) ≀ [3, 4], initial_5 end @test ocp2 isa OptimalControlModel @test state_dimension(ocp2) == n @test control_dimension(ocp2) == n @test initial_time(ocp2) == t0 @test final_time(ocp2) == tf # all used variables must be defined before each test xf = 11.11 * ones(4) xf2 = 11.111 xf_b = 11.1111 * ones(4) xf_u = 11.11111 * ones(4) yf = 2.22 * ones(2) yf_b = 2.222 * ones(2) yf_u = 2.2222 * ones(2) # === final t0 = 0.2 tf = 1.2 n = 4 @def ocp3 begin t ∈ [t0, tf], time x ∈ R^n, state u ∈ R^n, control x(tf) == xf xf_b ≀ x(tf) ≀ xf_u x[2](tf) == xf2 x[2:3](tf) == yf yf_b ≀ x[2:3](tf) ≀ yf_u end @test ocp3 isa OptimalControlModel @test state_dimension(ocp3) == n @test control_dimension(ocp3) == n @test initial_time(ocp3) == t0 @test final_time(ocp3) == tf t0 = 0.3 tf = 1.3 n = 6 xf = 11.11 * ones(n) xf2 = 11.111 xf_b = 11.1111 * ones(n) xf_u = 11.11111 * ones(n) yf = 2.22 * ones(2) yf_b = 2.222 * ones(2) yf_u = 2.2222 * ones(2) @def ocp4 begin t ∈ [t0, tf], time x ∈ R^n, state u ∈ R^n, control x(tf) == xf, final_1 xf_b ≀ x(tf) ≀ xf_u, final_2 x[2](tf) == xf2, final_3 x[2:3](tf) == yf, final_4 yf_b ≀ x[2:3](tf) ≀ yf_u, final_5 end @test ocp4 isa OptimalControlModel @test state_dimension(ocp4) == n @test control_dimension(ocp4) == n @test initial_time(ocp4) == t0 @test final_time(ocp4) == tf # === boundary t0 = 0.4 tf = 1.4 n = 2 @def ocp5 begin t ∈ [t0, tf], time x ∈ R^n, state u ∈ R^n, control x(tf) - tf * x(t0) == [0, 1] [0, 1] ≀ x(tf) - tf * x(t0) ≀ [1, 3] x[2](t0)^2 == 1 1 ≀ x[2](t0)^2 ≀ 2 x[2](tf)^2 == 1 1 ≀ x[2](tf)^2 ≀ 2 end @test ocp5 isa OptimalControlModel @test state_dimension(ocp5) == n @test control_dimension(ocp5) == n @test initial_time(ocp5) == t0 @test final_time(ocp5) == tf t0 = 0.5 tf = 1.5 n = 2 @def ocp6 begin t ∈ [t0, tf], time x ∈ R^n, state u ∈ R^n, control x(tf) - tf * x(t0) == [0, 1], boundary_1 [0, 1] ≀ x(tf) - tf * x(t0) ≀ [1, 3], boundary_2 x[2](t0)^2 == 1, boundary_3 1 ≀ x[2](t0)^2 ≀ 2, boundary_4 x[2](tf)^2 == 1, boundary_5 1 ≀ x[2](tf)^2 ≀ 2, boundary_6 end @test ocp6 isa OptimalControlModel @test state_dimension(ocp6) == n @test control_dimension(ocp6) == n @test initial_time(ocp6) == t0 @test final_time(ocp6) == tf # define more variables u_b = 1.0 u_u = 2.0 u2_b = 3.0 u2_u = 4.0 v_b = 5.0 v_u = 6.0 t0 = 0.6 tf = 1.6 n = 2 @def ocp7 begin t ∈ [t0, tf], time x ∈ R^n, state u ∈ R^n, control u_b ≀ u[1](t) ≀ u_u u2_b ≀ u[1](t) ≀ u2_u v_b ≀ u[2](t) ≀ v_u #u[2:3](t) == v_u u[1](t)^2 + u[2](t)^2 == 1 1 ≀ u[1](t)^2 + u[2](t)^2 ≀ 2 end @test ocp7 isa OptimalControlModel @test state_dimension(ocp7) == n @test control_dimension(ocp7) == n @test initial_time(ocp7) == t0 @test final_time(ocp7) == tf t0 = 0.7 tf = 1.7 n = 2 u_b = 1.0 u_u = 2.0 u2_b = 3.0 u2_u = 4.0 v_b = 5.0 v_u = 6.0 @def ocp8 begin t ∈ [t0, tf], time x ∈ R^n, state u ∈ R^n, control u_b ≀ u[2](t) ≀ u_u, control_1 u2_b ≀ u[1](t) ≀ u2_u, control_3 [1, v_b] ≀ u[1:2](t) ≀ [2, v_u], control_5 u[1](t)^2 + u[2](t)^2 == 1, control_7 1 ≀ u[1](t)^2 + u[2](t)^2 ≀ 2, control_8 end @test ocp8 isa OptimalControlModel @test state_dimension(ocp8) == n @test control_dimension(ocp8) == n @test initial_time(ocp8) == t0 @test final_time(ocp8) == tf # more vars x_b = 10.0 x_u = 11.0 x2_b = 13.0 x2_u = 14.0 x_u = 15.0 y_u = 16.0 # === state t0 = 0.8 tf = 1.8 n = 10 @def ocp9 begin t ∈ [t0, tf], time x ∈ R^n, state u ∈ R^n, control x_b ≀ x[3](t) ≀ x_u #x(t) == x_u x2_b ≀ x[2](t) ≀ x2_u #x[2](t) == x2_u #x[2:3](t) == y_u x_u ≀ x[10](t) ≀ y_u x[1:2](t) + x[3:4](t) == [-1, 1] [-1, 1] ≀ x[1:2](t) + x[3:4](t) ≀ [0, 2] end @test ocp9 isa OptimalControlModel @test state_dimension(ocp9) == n @test control_dimension(ocp9) == n @test initial_time(ocp9) == t0 @test final_time(ocp9) == tf t0 = 0.9 tf = 1.9 n = 11 @def ocp10 begin t ∈ [t0, tf], time x ∈ R^n, state u ∈ R^n, control x_b ≀ x[3](t) ≀ x_u, state_1 #x(t) == x_u , state_2 x2_b ≀ x[2](t) ≀ x2_u, state_3 #x[2](t) == x2_u , state_4 #x[2:3](t) == y_u , state_5 x_u ≀ x[3](t) ≀ y_u, state_6 x[1:2](t) + x[3:4](t) == [-1, 1], state_7 [-1, 1] ≀ x[1:2](t) + x[3:4](t) ≀ [0, 2], state_8 end @test ocp10 isa OptimalControlModel @test state_dimension(ocp10) == n @test control_dimension(ocp10) == n @test initial_time(ocp10) == t0 @test final_time(ocp10) == tf # === mixed t0 = 0.111 tf = 1.111 n = 12 @def ocp11 begin t ∈ [t0, tf], time x ∈ R^n, state u ∈ R^n, control u[2](t) * x[1:2](t) == [-1, 1] [-1, 1] ≀ u[2](t) * x[1:2](t) ≀ [0, 2] end @test ocp11 isa OptimalControlModel @test state_dimension(ocp11) == n @test control_dimension(ocp11) == n @test initial_time(ocp11) == t0 @test final_time(ocp11) == tf @def ocp12 begin t ∈ [t0, tf], time x ∈ R^n, state u ∈ R^n, control u[2](t) * x[1:2](t) == [-1, 1], mixed_1 [-1, 1] ≀ u[2](t) * x[1:2](t) ≀ [0, 2], mixed_2 end @test ocp12 isa OptimalControlModel @test state_dimension(ocp12) == n @test control_dimension(ocp12) == n @test initial_time(ocp12) == t0 @test final_time(ocp12) == tf # === dynamics t0 = 0.112 tf = 1.112 @def ocp13 begin t ∈ [t0, tf], time x ∈ R, state u ∈ R, control xΜ‡(t) == 2x(t) + u(t)^2 end @test ocp13 isa OptimalControlModel @test state_dimension(ocp13) == 1 @test control_dimension(ocp13) == 1 @test initial_time(ocp13) == t0 @test final_time(ocp13) == tf # some syntax (even parseable) are not allowed # this is the actual exhaustive list # note: equality constraints on ranges for state and control # are now allowed to ensure a uniform treatment of equalities # as particular inequalities @test_throws ParsingError @def o begin t ∈ [t0, tf], time x ∈ R, state u ∈ R, control xΜ‡(t) == f(x(t), u(t)), named_dynamics_not_allowed # but allowed if unnamed ! end end # --------------------------------------------------------------- # --------------------------------------------------------------- @testset "Lagrange cost" begin println("lagrange testset...") # -------------------------------- # min t0 = 0 tf = 1 @def o begin t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] xΜ‡(t) == A * x(t) + B * u(t) ∫(0.5u(t)^2) β†’ min end x = [1, 2] x0 = 2 * x xf = 3 * x u = -1 A = [ 0 1 0 0 ] B = [ 0 1 ] @test __constraint(o, :eq1)(x0, xf) == x0 @test __dynamics(o)(x, u) == A * x + B * u @test __lagrange(o)(x, u) == 0.5u^2 @test criterion(o) == :min t0 = 0 tf = 1 @def o begin t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] xΜ‡(t) == A * x(t) + B * u(t) -∫(0.5u(t)^2) β†’ min end x = [1, 2] x0 = 2 * x xf = 3 * x u = -1 A = [ 0 1 0 0 ] B = [ 0 1 ] @test __constraint(o, :eq1)(x0, xf) == x0 @test __dynamics(o)(x, u) == A * x + B * u @test __lagrange(o)(x, u) == -0.5u^2 @test criterion(o) == :min t0 = 0 tf = 1 @def o begin t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] xΜ‡(t) == A * x(t) + B * u(t) 0.5 * ∫(u(t)^2) β†’ min end x = [1, 2] x0 = 2 * x xf = 3 * x u = -1 A = [ 0 1 0 0 ] B = [ 0 1 ] @test __constraint(o, :eq1)(x0, xf) == x0 @test __dynamics(o)(x, u) == A * x + B * u @test __lagrange(o)(x, u) == 0.5u^2 @test criterion(o) == :min t0 = 0 tf = 1 @def o begin t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] xΜ‡(t) == A * x(t) + B * u(t) 0.5∫(u(t)^2) β†’ min end x = [1, 2] x0 = 2 * x xf = 3 * x u = -1 A = [ 0 1 0 0 ] B = [ 0 1 ] @test __constraint(o, :eq1)(x0, xf) == x0 @test __dynamics(o)(x, u) == A * x + B * u @test __lagrange(o)(x, u) == 0.5u^2 @test criterion(o) == :min t0 = 0 tf = 1 @def o begin t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] xΜ‡(t) == A * x(t) + B * u(t) -0.5 * ∫(u(t)^2) β†’ min end x = [1, 2] x0 = 2 * x xf = 3 * x u = -1 A = [ 0 1 0 0 ] B = [ 0 1 ] @test __constraint(o, :eq1)(x0, xf) == x0 @test __dynamics(o)(x, u) == A * x + B * u @test __lagrange(o)(x, u) == -0.5u^2 @test criterion(o) == :min t0 = 0 tf = 1 @def o begin t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] xΜ‡(t) == A * x(t) + B * u(t) (-0.5 + tf) * ∫(u(t)^2) β†’ min end x = [1, 2] x0 = 2 * x xf = 3 * x u = -1 A = [ 0 1 0 0 ] B = [ 0 1 ] @test __constraint(o, :eq1)(x0, xf) == x0 @test __dynamics(o)(x, u) == A * x + B * u @test __lagrange(o)(x, u) == (-0.5 + tf) * u^2 @test criterion(o) == :min t0 = 0 tf = 1 @test_throws ParsingError @def o begin # a call to the time (t, here) must not appear before the integral t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] xΜ‡(t) == A * x(t) + B * u(t) (-0.5 + t) * ∫(u(t)^2) β†’ min end t0 = 0 tf = 1 @test_throws ParsingError @def o begin # a call to the time (t, here) must not appear before the integral t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] xΜ‡(t) == A * x(t) + B * u(t) (-0.5 + x(t)) * ∫(u(t)^2) β†’ min end # ----------------------------------- # max t0 = 0 tf = 1 @def o begin t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] xΜ‡(t) == A * x(t) + B * u(t) ∫(0.5u(t)^2) β†’ max end x = [1, 2] x0 = 2 * x xf = 3 * x u = -1 A = [ 0 1 0 0 ] B = [ 0 1 ] @test __constraint(o, :eq1)(x0, xf) == x0 @test __dynamics(o)(x, u) == A * x + B * u @test __lagrange(o)(x, u) == 0.5u^2 @test criterion(o) == :max t0 = 0 tf = 1 @def o begin t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] xΜ‡(t) == A * x(t) + B * u(t) -∫(0.5u(t)^2) β†’ max end x = [1, 2] x0 = 2 * x xf = 3 * x u = -1 A = [ 0 1 0 0 ] B = [ 0 1 ] @test __constraint(o, :eq1)(x0, xf) == x0 @test __dynamics(o)(x, u) == A * x + B * u @test __lagrange(o)(x, u) == -0.5u^2 @test criterion(o) == :max t0 = 0 tf = 1 @def o begin t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] xΜ‡(t) == A * x(t) + B * u(t) 0.5 * ∫(u(t)^2) β†’ max end x = [1, 2] x0 = 2 * x xf = 3 * x u = -1 A = [ 0 1 0 0 ] B = [ 0 1 ] @test __constraint(o, :eq1)(x0, xf) == x0 @test __dynamics(o)(x, u) == A * x + B * u @test __lagrange(o)(x, u) == 0.5u^2 @test criterion(o) == :max t0 = 0 tf = 1 @def o begin t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] xΜ‡(t) == A * x(t) + B * u(t) 0.5∫(u(t)^2) β†’ max end x = [1, 2] x0 = 2 * x xf = 3 * x u = -1 A = [ 0 1 0 0 ] B = [ 0 1 ] @test __constraint(o, :eq1)(x0, xf) == x0 @test __dynamics(o)(x, u) == A * x + B * u @test __lagrange(o)(x, u) == 0.5u^2 @test criterion(o) == :max t0 = 0 tf = 1 @def o begin t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] xΜ‡(t) == A * x(t) + B * u(t) -0.5 * ∫(u(t)^2) β†’ max end x = [1, 2] x0 = 2 * x xf = 3 * x u = -1 A = [ 0 1 0 0 ] B = [ 0 1 ] @test __constraint(o, :eq1)(x0, xf) == x0 @test __dynamics(o)(x, u) == A * x + B * u @test __lagrange(o)(x, u) == -0.5u^2 @test criterion(o) == :max # ----------------------------------- t0 = 0.0 tf = 0.1 @def ocp begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control ∫(0.5u(t)^2) β†’ min end @test ocp isa OptimalControlModel t0 = 0.0 tf = 0.1 @def ocp begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control ∫(0.5u(t)^2) β†’ max end @test ocp isa OptimalControlModel end t0 = 0 tf = 1 @test_throws ParsingError @def o begin # a call to the time (t, here) must not appear before the integral t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] xΜ‡(t) == A * x(t) + B * u(t) (-0.5 + t) * ∫(u(t)^2) β†’ max end t0 = 0 tf = 1 @test_throws ParsingError @def o begin # a call to the time (t, here) must not appear before the integral t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] xΜ‡(t) == A * x(t) + B * u(t) (-0.5 + x(t)) * ∫(u(t)^2) β†’ max end # --------------------------------------------------------------- # --------------------------------------------------------------- @testset "Bolza cost" begin println("Bolza testset...") # ------------------------------- # min # Mayer Β± Lagrange @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control (x(0) + 3x(1)) + ∫(x(t) + u(t)) β†’ min end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == x0 + 3xf @test __lagrange(o)(x, u) == x + u @test criterion(o) == :min @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control (x(0) + 2x(1)) + ∫(x(t) + u(t)) β†’ min end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == x0 + 2xf @test __lagrange(o)(x, u) == x + u @test criterion(o) == :min @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control (x(0) + 2x(1)) + 2 * ∫(x(t) + u(t)) β†’ min end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == x0 + 2xf @test __lagrange(o)(x, u) == 2(x + u) @test criterion(o) == :min @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control (x(0) + 2x(1)) - ∫(x(t) + u(t)) β†’ min end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == x0 + 2xf @test __lagrange(o)(x, u) == -(x + u) @test criterion(o) == :min @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control (x(0) + 2x(1)) - 2 * ∫(x(t) + u(t)) β†’ min end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == x0 + 2xf @test __lagrange(o)(x, u) == -2(x + u) @test criterion(o) == :min @test_throws ParsingError @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control (x(0) + 2x(1)) + t * ∫(x(t) + u(t)) β†’ min end @test_throws ParsingError @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control (x(0) + 2x(1)) - t * ∫(x(t) + u(t)) β†’ min end # ------------------------------- # max # Mayer Β± Lagrange @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control (x(0) + 5x(1)) + ∫(x(t) + u(t)) β†’ max end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == x0 + 5xf @test __lagrange(o)(x, u) == x + u @test criterion(o) == :max @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control (x(0) + 2x(1)) + 2 * ∫(x(t) + u(t)) β†’ max end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == x0 + 2xf @test __lagrange(o)(x, u) == 2(x + u) @test criterion(o) == :max @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control (x(0) + 2x(1)) - ∫(x(t) + u(t)) β†’ max end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == x0 + 2xf @test __lagrange(o)(x, u) == -(x + u) @test criterion(o) == :max @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control (x(0) + 2x(1)) - 2 * ∫(x(t) + u(t)) β†’ max end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == x0 + 2xf @test __lagrange(o)(x, u) == -2(x + u) @test criterion(o) == :max @test_throws ParsingError @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control (x(0) + 2x(1)) + t * ∫(x(t) + u(t)) β†’ max end @test_throws ParsingError @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control (x(0) + 2x(1)) - t * ∫(x(t) + u(t)) β†’ max end # ------------------------------- # min # Lagrange Β± Mayer @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control ∫(x(t) + u(t)) + (x(0) + 2x(1)) β†’ min end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == x0 + 2xf @test __lagrange(o)(x, u) == x + u @test criterion(o) == :min @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control 2 * ∫(x(t) + u(t)) + (x(0) + 2x(1)) β†’ min end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == x0 + 2xf @test __lagrange(o)(x, u) == 2(x + u) @test criterion(o) == :min @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control ∫(x(t) + u(t)) - (x(0) + 2x(1)) β†’ min end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == -(x0 + 2xf) @test __lagrange(o)(x, u) == x + u @test criterion(o) == :min @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control 2 * ∫(x(t) + u(t)) - (x(0) + 2x(1)) β†’ min end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == -(x0 + 2xf) @test __lagrange(o)(x, u) == 2(x + u) @test criterion(o) == :min @test_throws ParsingError @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control t * ∫(x(t) + u(t)) + 1 β†’ min end @test_throws ParsingError @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control t * ∫(x(t) + u(t)) - 1 β†’ min end # ------------------------------- # max # Lagrange Β± Mayer @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control ∫(x(t) + u(t)) + (x(0) + 2x(1)) β†’ max end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == x0 + 2xf @test __lagrange(o)(x, u) == x + u @test criterion(o) == :max @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control 2 * ∫(x(t) + u(t)) + (x(0) + 2x(1)) β†’ max end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == x0 + 2xf @test __lagrange(o)(x, u) == 2(x + u) @test criterion(o) == :max @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control ∫(x(t) + u(t)) - (x(0) + 2x(1)) β†’ max end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == -(x0 + 2xf) @test __lagrange(o)(x, u) == x + u @test criterion(o) == :max @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control 2 * ∫(x(t) + u(t)) - (x(0) + 2x(1)) β†’ max end x = 1 u = 2 x0 = 3 xf = 4 @test __mayer(o)(x0, xf) == -(x0 + 2xf) @test __lagrange(o)(x, u) == 2(x + u) @test criterion(o) == :max @test_throws ParsingError @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control t * ∫(x(t) + u(t)) + 1 β†’ max end @test_throws ParsingError @def o begin t ∈ [0, 1], time x ∈ R, state u ∈ R, control t * ∫(x(t) + u(t)) - 1 β†’ max end end # --------------------------------------------------------------- # --------------------------------------------------------------- @testset "Mayer cost" begin println("Mayer testset...") @def o begin s ∈ [0, 1], time y ∈ R^4, state w ∈ R, control r = y₃ v = yβ‚„ r(0) + v(1) β†’ min end y0 = [1, 2, 3, 4] yf = 2 * [1, 2, 3, 4] @test is_min(o) @test __mayer(o)(y0, yf) == y0[3] + yf[4] @def o begin s ∈ [0, 1], time y ∈ R^4, state w ∈ R, control r = y₃ v = yβ‚„ r(0) + v(1) β†’ max end y0 = [1, 2, 3, 4] yf = 2 * [1, 2, 3, 4] @test is_max(o) @test __mayer(o)(y0, yf) == y0[3] + yf[4] @def o begin z ∈ R^2, variable s ∈ [0, z₁], time y ∈ R^4, state w ∈ R, control r = y₃ v = yβ‚„ r(0) + v(z₁) + zβ‚‚ β†’ min end z = [5, 6] y0 = [1, 2, 3, 4] yf = 2 * [1, 2, 3, 4] @test is_min(o) @test __mayer(o)(y0, yf, z) == y0[3] + yf[4] + z[2] @def o begin z ∈ RΒ², variable s ∈ [0, z₁], time y ∈ R⁴, state w ∈ R, control r = y₃ v = yβ‚„ aa = y₁ + wΒ² + vΒ³ + zβ‚‚ yΜ‡(s) == [aa(s), rΒ²(s), 0, 0] r(0) + v(z₁) + zβ‚‚ β†’ min end z = [5, 6] y = [1, 2, 3, 4] y0 = y yf = 3y0 w = 7 @test __dynamics(o)(y, w, z) == [y[1] + w^2 + y[4]^3 + z[2], y[3]^2, 0, 0] @test __mayer(o)(y0, yf, z) == y0[3] + yf[4] + z[2] @def o begin z ∈ RΒ², variable s ∈ [0, z₁], time y ∈ R⁴, state w ∈ R, control r = y₃ v = yβ‚„ aa = y₁(s) + vΒ³ + zβ‚‚ yΜ‡(s) == [aa(s) + (w^2)(s), rΒ²(s), 0, 0] r(0) + v(z₁) + zβ‚‚ β†’ min end z = [5, 6] y = [1, 2, 3, 4] y0 = y yf = 3y0 w = 7 @test __dynamics(o)(y, w, z) == [y[1] + w^2 + y[4]^3 + z[2], y[3]^2, 0, 0] @test __mayer(o)(y0, yf, z) == y0[3] + yf[4] + z[2] @def o begin z ∈ RΒ², variable s ∈ [0, z₁], time y ∈ R⁴, state w ∈ R, control r = y₃ v = yβ‚„ aa = y₁ + vΒ³ + zβ‚‚ aa(0) + yβ‚‚(z₁) β†’ min end z = [5, 6] y0 = y yf = 3y0 @test __mayer(o)(y0, yf, z) == y0[1] + y0[4]^3 + z[2] + yf[2] @def o begin z ∈ RΒ², variable __t ∈ [0, z₁], time y ∈ R⁴, state w ∈ R, control r = y₃ v = yβ‚„ aa = y₁(__t) + vΒ³ + zβ‚‚ yΜ‡(__t) == [aa(__t) + (w^2)(__t), rΒ²(__t), 0, 0] aa(0) + yβ‚‚(z₁) β†’ min end z = [5, 6] y = [1, 2, 3, 4] y0 = y yf = 3y0 w = 11 @test __dynamics(o)(y, w, z) == [y[1] + w^2 + y[4]^3 + z[2], y[3]^2, 0, 0] @test_throws UndefVarError __mayer(o)(y0, yf, z) end # --------------------------------------------------------------- # --------------------------------------------------------------- @testset "closure" begin println("closure testset...") a = 1 f(b) = begin # closure of a, local c, and @def in function c = 3 @def ocp begin t ∈ [a, b], time x ∈ R, state u ∈ R, control xΜ‡(t) == x(t) + u(t) + b + c + d end return ocp end b = 2 o = f(b) d = 4 x = 10 u = 20 @test __dynamics(o)(x, u) == x + u + b + 3 + d end # --------------------------------------------------------------- # --------------------------------------------------------------- @testset "error detection" begin # error detections (this can be tricky -> need more work) # this one is detected by the generated code (and not the parser) t0 = 9.0 tf = 9.1 @test_throws CTException @def o begin t ∈ [t0, tf], time t ∈ [t0, tf], time end # illegal constraint name (1bis), detected by the parser t0 = 9.0 tf = 9.1 r0 = 1.0 v0 = 2.0 m0 = 3.0 @test_throws ParsingError @def o begin t ∈ [t0, tf], time x ∈ R^2, state u ∈ R^2, control 0 ≀ u(t) ≀ 1, (1bis) end # t0 is unknown in the x(t0) constraint, detected by the parser r0 = 1.0 v0 = 2.0 m0 = 3.0 @test_throws ParsingError @def o begin t ∈ [0, 1], time x ∈ R^2, state u ∈ R^2, control x(t0) == [r0, v0, m0], (1) 0 ≀ u(t) ≀ 1, (1bis) end # bad syntax for Bolza cost interpreted as a Mayer term with trailing ∫ @test_throws ParsingError @def o begin t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] αΊ‹(t) == A * x(t) + B * u(t) 1 + 2 + ∫(u(t)^2) β†’ min # should be ( 1 + 2 ) + ∫(...) end @test_throws ParsingError @def o begin t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] αΊ‹(t) == A * x(t) + B * u(t) ∫(u(t)^2) + 1 + 2 β†’ min # should be ∫(...) + ( 1 + 2 ) end @test_throws ParsingError @def o begin t ∈ [t0, tf], time x ∈ R^2, state u ∈ R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] αΊ‹(t) == A * x(t) + B * u(t) ∫(u(t)^2) / 2 β†’ min # forbidden end end # --------------------------------------------------------------- # --------------------------------------------------------------- @testset "non unicode keywords" begin println("non unicode keywords testset...") # -------------------------------- # min t0 = 0 tf = 1 @def o begin t in [t0, tf], time x in R^2, state u in R, control x(t0) == [-1, 0], (1) x(tf) == [0, 0] derivative(x)(t) == A * x(t) + B * u(t) integral(0.5u(t)^2) => min end x = [1, 2] x0 = 2 * x xf = 3 * x u = -1 A = [ 0 1 0 0 ] B = [ 0 1 ] @test __constraint(o, :eq1)(x0, xf) == x0 @test __dynamics(o)(x, u) == A * x + B * u @test __lagrange(o)(x, u) == 0.5u^2 @test criterion(o) == :min @def o begin z in R, variable t in [0, 1], time x in R^2, state u in R, control r = x[1] v = x[2] 0 <= r(0) - z <= 1, (1) 0 <= v(1)^2 <= 1, (2) [0, 0] <= x(0) <= [1, 1], (β™‘) z >= 0, (3) derivative(x)(t) == [v(t), r(t)^2 + z] integral(u(t)^2 + z * x[1](t)) => min end x0 = [2, 3] xf = [4, 5] x = [1, 2] u = 3 z = 4 @test __constraint(o, :eq1)(x0, xf, z) == x0[1] - z @test __constraint(o, :eq2)(x0, xf, z) == xf[2]^2 @test __constraint(o, Symbol("β™‘"))(x0, xf, z) == x0 @test __constraint(o, :eq3)(z) == z @test __dynamics(o)(x, u, z) == [x[2], x[1]^2 + z] @test __lagrange(o)(x, u, z) == u^2 + z * x[1] @def o begin z in R, variable t in [0, 1], time x in R^2, state u in R, control r = x[1] v = x[2] 0 <= r(0) - z <= 1, (1) 0 <= v(1)^2 <= 1, (2) [0, 0] <= x(0) <= [1, 1], (β™‘) z >= 0, (3) derivative(x)(t) == [v(t), r(t)^2 + z] integral(u(t)^2 + z * x[1](t)) => min end x0 = [2, 3] xf = [4, 5] x = [1, 2] u = 3 z = 4 @test __constraint(o, :eq1)(x0, xf, z) == x0[1] - z @test __constraint(o, :eq2)(x0, xf, z) == xf[2]^2 @test __constraint(o, Symbol("β™‘"))(x0, xf, z) == x0 @test __constraint(o, :eq3)(z) == z @test __dynamics(o)(x, u, z) == [x[2], x[1]^2 + z] @test __lagrange(o)(x, u, z) == u^2 + z * x[1] @def o begin z in R^2, variable t in [0, 1], time x in R^2, state u in R^2, control r = x1 v = x2 0 <= r(0) - z1 <= 1, (1) 0 <= v(1)^2 <= 1, (2) [0, 0] <= x(0) <= [1, 1], (β™‘) z1 >= 0, (3) z2 == 1 u2(t) == 0 derivative(x)(t) == [v(t), r(t)^2 + z1] integral(u1(t)^2 + z1 * x1(t)) => min end x0 = [2, 3] xf = [4, 5] x = [1, 2] u = [3, 0] z = [4, 1] @test __constraint(o, :eq1)(x0, xf, z) == x0[1] - z[1] @test __constraint(o, :eq2)(x0, xf, z) == xf[2]^2 @test __constraint(o, Symbol("β™‘"))(x0, xf, z) == x0 @test __constraint(o, :eq3)(z) == z[1] @test __dynamics(o)(x, u, z) == [x[2], x[1]^2 + z[1]] @test __lagrange(o)(x, u, z) == u[1]^2 + z[1] * x[1] end end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
1323
function test_plot() # create a solution n = 2 m = 1 t0 = 0.0 tf = 1.0 x0 = [-1.0, 0.0] xf = [0.0, 0.0] a = x0[1] b = x0[2] C = [ -(tf - t0)^3/6.0 (tf - t0)^2/2.0 -(tf - t0)^2/2.0 (tf-t0) ] D = [-a - b * (tf - t0), -b] + xf p0 = C \ D α = p0[1] β = p0[2] x(t) = [ a + b * (t - t0) + β * (t - t0)^2 / 2.0 - α * (t - t0)^3 / 6.0, b + β * (t - t0) - α * (t - t0)^2 / 2.0, ] p(t) = [α, -α * (t - t0) + β] u(t) = [p(t)[2]] objective = 0.5 * (α^2 * (tf - t0)^3 / 3 + β^2 * (tf - t0) - α * β * (tf - t0)^2) # N = 201 times = range(t0, tf, N) # sol = OptimalControlSolution() sol.state_dimension = n sol.control_dimension = m sol.time_grid = times sol.time_name = "t" sol.state = x sol.state_name = "x" sol.state_components_names = ["x" * ctindices(i) for i ∈ range(1, n)] sol.costate = p sol.control = u sol.control_name = "u" sol.control_components_names = ["u"] sol.objective = objective sol.iterations = 0 sol.stopping = :dummy sol.message = "ceci est un test" sol.success = true # @test plot(sol, layout = :split) isa Plots.Plot @test plot(sol, layout = :group) isa Plots.Plot @test display(sol) isa Nothing end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
628
using Plots function keep_series_attributes(; kwargs...) series_attributes = Plots.attributes(:Series) out = [] for kw ∈ kwargs kw[1] ∈ series_attributes && push!(out, kw) end return out end function print_kwargs(; kwargs...) for kw ∈ kwargs println(kw) end end attributes = (size = (900, 600), linewidth = 2, flip = true, colorbar = :best, bins = :auto) println("\nBefore keeping series attributes\n") print_kwargs(; attributes...) series_attributes = keep_series_attributes(; attributes...) println("\nAfter keeping series attributes\n") print_kwargs(; series_attributes...)
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
2625
function test_print() # @test display(Model()) isa Nothing @def ocp begin t ∈ [0, 1], time x ∈ RΒ², state u ∈ R, control x(0) == [-1, 0] x(1) == [0, 0] xΜ‡(t) == [xβ‚‚(t), u(t)] ∫(0.5u(t)^2) β†’ min end @test display(ocp) isa Nothing # ocp = Model(autonomous = false) state!(ocp, 2, "state", ["r", "v"]) # dimension of the state with the names of the components control!(ocp, 1) # dimension of the control time!(ocp; t0 = 0, tf = 1, name = "s") # initial and final time, with the name of the variable time constraint!(ocp, :initial, lb = [-1, 0], ub = [-1, 0]) constraint!(ocp, :final, lb = [0, 0], ub = [0, 0]) A = [ 0 1 0 0 ] B = [ 0 1 ] dynamics!(ocp, (t, x, u) -> A * x + B * u) constraint!(ocp, :state, f = (t, x) -> x[2], lb = 0, ub = 1) constraint!(ocp, :control, f = (t, u) -> u, lb = -1, ub = 1) constraint!(ocp, :mixed, f = (t, x, u) -> x[1] + u, lb = 2, ub = 3) constraint!(ocp, :state, rg = 1, lb = -10, ub = 10) constraint!(ocp, :control, lb = -2, ub = 2) objective!(ocp, :bolza, (t0, x0, tf, xf) -> tf, (t, x, u) -> 0.5u^2) @test display(ocp) isa Nothing # ocp = Model(autonomous = false) state!(ocp, 1, "y") # dimension of the state with the names of the components control!(ocp, 1, "v") # dimension of the control time!(ocp; t0 = 0, tf = 1, name = "s") # initial and final time, with the name of the variable time constraint!(ocp, :initial, lb = -1, ub = -1) constraint!(ocp, :final, lb = 0, ub = 0) dynamics!(ocp, (t, x, u) -> x + u) constraint!(ocp, :state, f = (t, x) -> x, lb = 0, ub = 1) constraint!(ocp, :control, f = (t, u) -> u, lb = -1, ub = 1) constraint!(ocp, :mixed, f = (t, x, u) -> x + u, lb = 2, ub = 3) constraint!(ocp, :state, lb = -10, ub = 10) constraint!(ocp, :control, lb = -2, ub = 2) objective!(ocp, :mayer, (t0, x0, tf, xf) -> tf) @test display(ocp) isa Nothing # ocp = Model(autonomous = false, variable = true) variable!(ocp, 1) state!(ocp, 1, "y") # dimension of the state with the names of the components control!(ocp, 2) # dimension of the control time!(ocp; t0 = 0, indf = 1, name = "s") # initial and final time, with the name of the variable time constraint!(ocp, :initial, lb = -1, ub = -1) constraint!(ocp, :final, lb = 0, ub = 0) dynamics!(ocp, (t, x, u) -> x + u) objective!(ocp, :mayer, (t0, x0, tf, xf) -> tf) @test display(ocp) isa Nothing end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
1302
function test_solution() # Fixed ocp @def ocp begin t ∈ [0, 1], time x ∈ RΒ², state u ∈ R, control x(0) == [-1, 0] x(1) == [0, 0] xΜ‡(t) == [xβ‚‚(t), u(t)] ∫(0.5u(t)^2) β†’ min end times = range(0, 1, 10) x = t -> t u = t -> 2t p = t -> t obj = 1 sol = OptimalControlSolution( ocp; state = x, control = u, costate = p, objective = obj, time_grid = times, ) @test objective(sol) == obj @test typeof(sol) == OptimalControlSolution # getters @test all(state_discretized(sol) .== x.(times)) @test all(control_discretized(sol) .== u.(times)) @test all(costate_discretized(sol) .== p.(times)) # NonFixed ocp @def ocp begin v ∈ R, variable t ∈ [0, 1], time x ∈ RΒ², state u ∈ R, control x(0) == [-1, 0] x(1) == [0, 0] xΜ‡(t) == [xβ‚‚(t), u(t)] ∫(0.5u(t)^2) β†’ min end x = t -> t u = t -> 2t obj = 1 v = 1 sol = OptimalControlSolution(ocp; state = x, control = u, objective = obj, variable = v) @test variable(sol) == v @test typeof(sol) == OptimalControlSolution @test_throws UndefKeywordError OptimalControlSolution(ocp; x, u, obj) end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
3486
function test_utils() @testset "AD" begin x0 = 1.0 f = x -> cos(x) @test CTBase.ctgradient(f, x0) β‰ˆ -sin(x0) atol = 1e-10 @test CTBase.__ctgradient(f, x0) β‰ˆ -sin(x0) atol = 1e-10 @test CTBase.ctgradient(VectorField(f), x0) β‰ˆ -sin(x0) atol = 1e-10 @test CTBase.__ctgradient(VectorField(f), x0) β‰ˆ -sin(x0) atol = 1e-10 f = x -> [cos(x)] @test CTBase.ctjacobian(f, x0) β‰ˆ [-sin(x0);;] atol = 1e-10 @test CTBase.__ctjacobian(f, x0) β‰ˆ [-sin(x0);;] atol = 1e-10 @test CTBase.ctjacobian(VectorField(f), x0) β‰ˆ [-sin(x0);;] atol = 1e-10 @test CTBase.__ctjacobian(VectorField(f), x0) β‰ˆ [-sin(x0);;] atol = 1e-10 g = x -> cos(x[1]) + sin(x[2]) @test CTBase.ctgradient(g, [x0, x0]) β‰ˆ [-sin(x0), cos(x0)] atol = 1e-10 @test CTBase.__ctgradient(g, [x0, x0]) β‰ˆ [-sin(x0), cos(x0)] atol = 1e-10 g = x -> [cos(x[1]) + sin(x[2])] @test CTBase.ctjacobian(g, [x0, x0]) β‰ˆ [-sin(x0) cos(x0)] atol = 1e-10 @test CTBase.__ctjacobian(g, [x0, x0]) β‰ˆ [-sin(x0) cos(x0)] atol = 1e-10 end @testset "Other" begin v = [1.0; 2.0; 3.0; 4.0; 5.0; 6.0] n = 2 u = vec2vec(v, n) w = vec2vec(u) @test v == w A = [ 0 1 2 3 ] V = CTBase.matrix2vec(A) @test V[1] == [0, 1] @test V[2] == [2, 3] W = CTBase.matrix2vec(A, 2) @test W[1] == [0, 2] @test W[2] == [1, 3] @test_throws IncorrectArgument CTBase.ctindice(-1) @test_throws IncorrectArgument CTBase.ctindice(10) @test CTBase.ctindice(0) == 'β‚€' @test CTBase.ctindice(1) == '₁' @test CTBase.ctindice(2) == 'β‚‚' @test CTBase.ctindice(3) == '₃' @test CTBase.ctindice(4) == 'β‚„' @test CTBase.ctindice(5) == 'β‚…' @test CTBase.ctindice(6) == '₆' @test CTBase.ctindice(7) == '₇' @test CTBase.ctindice(8) == 'β‚ˆ' @test CTBase.ctindice(9) == '₉' @test_throws IncorrectArgument CTBase.ctindices(-1) @test CTBase.ctindices(019) == "₁₉" @test CTBase.ctindices(314) == "₃₁₄" @test_throws IncorrectArgument CTBase.ctupperscript(-1) @test_throws IncorrectArgument CTBase.ctupperscript(10) @test CTBase.ctupperscript(0) == '⁰' @test CTBase.ctupperscript(1) == 'ΒΉ' @test CTBase.ctupperscript(2) == 'Β²' @test CTBase.ctupperscript(3) == 'Β³' @test CTBase.ctupperscript(4) == '⁴' @test CTBase.ctupperscript(5) == '⁡' @test CTBase.ctupperscript(6) == '⁢' @test CTBase.ctupperscript(7) == '⁷' @test CTBase.ctupperscript(8) == '⁸' @test CTBase.ctupperscript(9) == '⁹' @test_throws IncorrectArgument CTBase.ctupperscripts(-1) @test CTBase.ctupperscripts(019) == "¹⁹" @test CTBase.ctupperscripts(109) == "¹⁰⁹" end @testset "to_out_of_place" begin function f1!(r, x) r[1] = x r[2] = x + 1 return nothing end @test CTBase.to_out_of_place(f1!, 2)(1.0) == [1.0, 2.0] function f2!(r, x, y) r[:] .= x + y return nothing end @test CTBase.to_out_of_place(f2!, 1; T = Int32)(1, 2) == 3 function f3!(r, x; y = 1) r[:] .= x + y return nothing end @test CTBase.to_out_of_place(f3!, 1; T = Int32)(1; y = 2) == 3 @test isnothing( CTBase.to_out_of_place(nothing, 1) ) end end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
605
#!/usr/bin/env julia # # basic problem using macros # # find local CTBase basename = '/' * joinpath(split(Base.source_path(), '/')[1:(end - 3)]) println(basename) using Pkg; Pkg.activate(basename); using CTBase tf = 1.0 @def verbose_threshold = 80 debug = true begin t0, variable t ∈ [t0, tf], time x ∈ R⁹, state a = x₁ b = xβ‚‚ c = x₃ d = xβ‚„ e = xβ‚… f = x₆ g = x₇ h = xβ‚ˆ i = x₉ 0 ≀ a(t) ≀ 1 0 ≀ b(t) ≀ 1 0 ≀ c(t) ≀ 1 0 ≀ d(t) ≀ 1 0 ≀ e(t) ≀ 1 0 ≀ f(t) ≀ 1 0 ≀ g(t) ≀ 1 0 ≀ h(t) ≀ 1 0 ≀ i(t) ≀ 1 v(tf) -> min end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
4393
#!/usr/bin/env julia # # test all constraints # # ref: https://github.com/control-toolbox/CTBase.jl/issues/9 # # find local CTBase basename = '/' * joinpath(split(Base.source_path(), '/')[1:(end - 3)]) using Pkg; Pkg.activate(basename); using CTBase # all used variables must be definedbefore each test t0 = 0.0 tf = 1.0 x0 = 11.11 x02 = 11.111 x0_b = 11.1111 x0_u = 11.11111 y0 = 2.22 y0_b = 2.222 y0_u = 2.2222 # === initial @def begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control x(t0) == x0 x[2](t0) == x02 x[2:3](t0) == y0 x0_b ≀ x(t0) ≀ x0_u y0_b ≀ x[2:3](t0) ≀ y0_u end @def begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control x(t0) == x0 => initial_1 x[2](t0) == x02 => initial_2 x[2:3](t0) == y0 => initial_3 x0_b ≀ x(t0) ≀ x0_u => initial_4 y0_b ≀ x[2:3](t0) ≀ y0_u => initial_5 end # all used variables must be definedbefore each test xf = 11.11 xf2 = 11.111 xf_b = 11.1111 xf_u = 11.11111 yf = 2.22 yf_b = 2.222 yf_u = 2.2222 # === final @def begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control x(tf) == xf xf_b ≀ x(tf) ≀ xf_u x[2](tf) == xf2 x[2:3](tf) == yf yf_b ≀ x[2:3](tf) ≀ yf_u end @def begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control x(tf) == xf => final_1 xf_b ≀ x(tf) ≀ xf_u => final_2 x[2](tf) == xf2 => final_3 x[2:3](tf) == yf => final_4 yf_b ≀ x[2:3](tf) ≀ yf_u => final_5 end # === boundary @def begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control x(tf) - tf * x(t0) == [0, 1] [0, 1] ≀ x(tf) - tf * x(t0) ≀ [1, 3] x[2](t0)^2 == 1 1 ≀ x[2](t0)^2 ≀ 2 x[2](tf)^2 == 1 1 ≀ x[2](tf)^2 ≀ 2 end @def begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control x(tf) - tf * x(t0) == [0, 1] => boundary_1 [0, 1] ≀ x(tf) - tf * x(t0) ≀ [1, 3] => boundary_2 x[2](t0)^2 == 1 => boundary_3 1 ≀ x[2](t0)^2 ≀ 2 => boundary_4 x[2](tf)^2 == 1 => boundary_5 1 ≀ x[2](tf)^2 ≀ 2 => boundary_6 end # define more variables u_b = 1.0 u_u = 2.0 u2_b = 3.0 u2_u = 4.0 v_b = 5.0 v_u = 6.0 @def begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control u_b ≀ u(t) ≀ u_u #u(t) == u_u u2_b ≀ u[2](t) ≀ u2_u #u[2](t) == u2_u v_b ≀ u[2:3](t) ≀ v_u #u[2:3](t) == v_u u[1](t)^2 + u[2](t)^2 == 1 1 ≀ u[1](t)^2 + u[2](t)^2 ≀ 2 end @def begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control u_b ≀ u(t) ≀ u_u => control_1 #u(t) == u_u => control_2 u2_b ≀ u[2](t) ≀ u2_u => control_3 #u[2](t) == u2_u => control_4 v_b ≀ u[2:3](t) ≀ v_u => control_5 #u[2:3](t) == v_u => control_6 u[1](t)^2 + u[2](t)^2 == 1 => control_7 1 ≀ u[1](t)^2 + u[2](t)^2 ≀ 2 => control_8 end # more vars x_b = 10.0 x_u = 11.0 x2_b = 13.0 x2_u = 14.0 x_u = 15.0 y_u = 16.0 # === state @def begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control x_b ≀ x(t) ≀ x_u #x(t) == x_u x2_b ≀ x[2](t) ≀ x2_u #x[2](t) == x2_u #x[2:3](t) == y_u x_u ≀ x[2:3](t) ≀ y_u x[1:2](t) + x[3:4](t) == [-1, 1] [-1, 1] ≀ x[1:2](t) + x[3:4](t) ≀ [0, 2] end @def begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control x_b ≀ x(t) ≀ x_u => state_1 #x(t) == x_u => state_2 x2_b ≀ x[2](t) ≀ x2_u => state_3 #x[2](t) == x2_u => state_4 #x[2:3](t) == y_u => state_5 x_u ≀ x[2:3](t) ≀ y_u => state_6 x[1:2](t) + x[3:4](t) == [-1, 1] => state_7 [-1, 1] ≀ x[1:2](t) + x[3:4](t) ≀ [0, 2] => state_8 end # === mixed @def begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control u[2](t) * x[1:2](t) == [-1, 1] [-1, 1] ≀ u[2](t) * x[1:2](t) ≀ [0, 2] end @def begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control u[2](t) * x[1:2](t) == [-1, 1] => mixed_1 [-1, 1] ≀ u[2](t) * x[1:2](t) ≀ [0, 2] => mixed_2 end # === dynamics @def begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control x'(t) == 2x(t) + u(t)^2 x'(t) == f(x(t), u(t)) end @def begin t ∈ [t0, tf], time x ∈ R^3, state u ∈ R^3, control # x'(t) == 2x(t) + u(t)^2 => dynamics_1 # x'(t) == f(x(t), u(t)) => dynamics_2 end
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
661
#!/usr/bin/env julia # # basic problem using macros # # find local CTBase basename = '/' * joinpath(split(Base.source_path(), '/')[1:(end - 3)]) println(basename) using Pkg; Pkg.activate(basename); using CTBase t0 = 0.0 tf = 1.0 x0 = [-1, 0] xf = [0, 0] A = [ 0 1 0 0 ] B = [ 0 1 ] n = 2 ocp = @def verbose_threshold = 50 debug = true begin t ∈ [t0, tf], time x ∈ R^n, state u ∈ R, control x(t0) == x0 => (1) x(tf) == xf, (deux) x'(t) == A * x(t) + B * u(t) ∫(0.5u(t)^2) β†’ min end # print problem definition println("== Basic problem:") display(ocp) println("== Generated code:") print_generated_code(ocp)
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
996
#!/usr/bin/env julia # # Goddard # # find local CTBase basename = '/' * joinpath(split(Base.source_path(), '/')[1:(end - 3)]) println(basename) using Pkg; Pkg.activate(basename); using CTBase Cd = 310 Tmax = 3.5 Ξ² = 500 b = 2 N = 100 t0 = 0 r0 = 1 v0 = 0 vmax = 0.1 m0 = 1 mf = 0.6 # Problem definition ocp = @def verbose_threshold = 100 begin tf, variable t ∈ [t0, tf], time x ∈ R^3, state u ∈ R, control r = x₁ v = xβ‚‚ m = x₃ x(t0) == [r0, v0, m0] 0 ≀ u(t) ≀ 1 0 ≀ r(t) ≀ 1, (1) 0 ≀ v(t) ≀ vmax, (2bis) mf ≀ m(t) ≀ m0, (trois) x'(t) == F0(x(t)) + u(t) * F1(x(t)) r(tf) -> max end function F0(x) r, v, m = x D = Cd * v^2 * exp(-Ξ² * (r - 1)) F = [v, -D / m - 1 / r^2, 0] return F end function F1(x) r, v, m = x F = [0, Tmax / m, -b * Tmax] return F end # print problem definition println("== Goddard problem:") display(ocp) # println("== Generated code:") print_generated_code(ocp) #code_debug_info()
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
code
676
using OptimalControl: solve using CTBase tf = 2.0 @def ocp begin t ∈ [0, tf], time x ∈ RΒ², state u ∈ R, control x(0) == [-1, 0] x(tf) == [0, 0] xΜ‡(t) == [xβ‚‚(t), u(t)] ∫(0.5u(t)^2) β†’ min end sol = solve(ocp, display = false) @def ocp begin t ∈ [0, tf], time x ∈ RΒ², state u ∈ R, control x(0) == [-0.5, -0.5] x(tf) == [0, 0] xΜ‡(t) == [xβ‚‚(t), u(t)] ∫(0.5u(t)^2) β†’ min end sol2 = solve(ocp, display = false) # first plot plt = plot(sol, size = (700, 450), time = :default) # second plot style = (linestyle = :dash,) plot!(plt, sol2, time = :default, state_style = style, costate_style = style, control_style = style)
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
docs
5229
# Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [email protected]. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
docs
1139
# Contributing [issue-url]: https://github.com/control-toolbox/CTBase.jl/issues [first-good-issue-url]: https://github.com/control-toolbox/CTBase.jl/contribute If you think you found a bug or if you have a feature request / suggestion, feel free to open an [issue][issue-url]. Before opening a pull request, please start an issue or a discussion on the topic. Contributions are welcomed, check out [how to contribute to a Github project](https://docs.github.com/en/get-started/exploring-projects-on-github/contributing-to-a-project). If it is your first contribution, you can also check [this first contribution tutorial](https://github.com/firstcontributions/first-contributions). You can find first good issues (if any πŸ™‚) [here][first-good-issue-url]. You may find other packages to contribute to at the [control-toolbox organization](https://github.com/control-toolbox). If you want to ask a question, feel free to start a discussion [here](https://github.com/orgs/control-toolbox/discussions). This forum is for general discussion about this repository and the [control-toolbox organization](https://github.com/control-toolbox).
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
docs
4129
# CTBase.jl [ci-img]: https://github.com/control-toolbox/CTBase.jl/actions/workflows/CI.yml/badge.svg?branch=main [ci-url]: https://github.com/control-toolbox/CTBase.jl/actions/workflows/CI.yml?query=branch%3Amain [co-img]: https://codecov.io/gh/control-toolbox/CTBase.jl/branch/main/graph/badge.svg?token=YM5YQQUSO3 [co-url]: https://codecov.io/gh/control-toolbox/CTBase.jl [doc-dev-img]: https://img.shields.io/badge/docs-dev-8A2BE2.svg [doc-dev-url]: https://control-toolbox.org/CTBase.jl/dev/ [doc-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [doc-stable-url]: https://control-toolbox.org/CTBase.jl/stable/ [release-img]: https://juliahub.com/docs/General/CTBase/stable/version.svg [release-url]: https://github.com/control-toolbox/CTBase.jl/releases [pkg-eval-img]: https://juliahub.com/docs/General/CTBase/stable/pkgeval.svg [pkg-eval-url]: https://juliahub.com/ui/Packages/General/CTBase [deps-img]: https://juliahub.com/docs/General/CTBase/stable/deps.svg [deps-url]: https://juliahub.com/ui/Packages/General/CTBase?t=2 [licence-img]: https://img.shields.io/badge/License-MIT-yellow.svg [licence-url]: https://github.com/control-toolbox/CTBase.jl/blob/master/LICENSE [aqua-img]: https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg [aqua-url]: https://github.com/JuliaTesting/Aqua.jl The CTBase.jl package is part of the [control-toolbox ecosystem](https://github.com/control-toolbox). The control-toolbox ecosystem gathers Julia packages for mathematical control and applications. The root package is [OptimalControl.jl](https://github.com/control-toolbox/OptimalControl.jl) which aims to provide tools to modelise and solve optimal control problems with ordinary differential equations by direct and indirect methods. [![doc OptimalControl.jl](https://img.shields.io/badge/Documentation-OptimalControl.jl-blue)](http://control-toolbox.org/OptimalControl.jl) | **Name** | **Badge** | :-------------------|:------------------| | Documentation | [![Documentation][doc-stable-img]][doc-stable-url] [![Documentation][doc-dev-img]][doc-dev-url] | | Code Status | [![Build Status][ci-img]][ci-url] [![Covering Status][co-img]][co-url] [![pkgeval][pkg-eval-img]][pkg-eval-url] [![Aqua.jl][aqua-img]][aqua-url] | | Dependencies | [![deps][deps-img]][deps-url] | | Licence | [![License: MIT][licence-img]][licence-url] | | Release | [![Release][release-img]][release-url] | ## Installation To install CTBase.jl please <a href="https://docs.julialang.org/en/v1/manual/getting-started/">open Julia's interactive session (known as REPL)</a> and press <kbd>]</kbd> key in the REPL to use the package mode, then add the package: ```julia julia> ] pkg> add CTBase ``` ## Contributing [issue-url]: https://github.com/control-toolbox/CTBase.jl/issues [first-good-issue-url]: https://github.com/control-toolbox/CTBase.jl/contribute If you think you found a bug or if you have a feature request / suggestion, feel free to open an [issue][issue-url]. Before opening a pull request, please start an issue or a discussion on the topic. Contributions are welcomed, check out [how to contribute to a Github project](https://docs.github.com/en/get-started/exploring-projects-on-github/contributing-to-a-project). If it is your first contribution, you can also check [this first contribution tutorial](https://github.com/firstcontributions/first-contributions). You can find first good issues (if any πŸ™‚) [here][first-good-issue-url]. You may find other packages to contribute to at the [control-toolbox organization](https://github.com/control-toolbox). If you want to ask a question, feel free to start a discussion [here](https://github.com/orgs/control-toolbox/discussions). This forum is for general discussion about this repository and the [control-toolbox organization](https://github.com/control-toolbox). >[!NOTE] > If you want to add an application or a package to the control-toolbox ecosystem, please follow this [set up tutorial](https://github.com/control-toolbox/CTApp.jl/discussions/9).
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
docs
122
--- name: Blank issue about: Blank template for general issue title: "[General] title" labels: '' assignees: ocots ---
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
docs
617
--- name: Bug report about: Create a bug report to help us improve title: "[Bug] title" labels: bug assignees: ocots --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Give if possible the code to reproduce the error: ```julia julia> f(x)=1 f (generic function with 1 method) julia> f() ERROR: MethodError: no method matching f() ``` **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Additional context** Add any other context about the problem here.
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
docs
128
--- name: 'Developers ' about: Suggest internal modifications title: "[Dev] title" labels: internal dev assignees: ocots ---
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
docs
198
--- name: Documentation suggestion about: Suggest improvements or additions to the documentation title: "[Doc] title" labels: documentation assignees: ocots --- **Please detail your suggestion.**
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
docs
622
--- name: Feature request about: Suggest an idea for this project title: "[Feature] title" labels: enhancement assignees: ocots --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here.
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
docs
14127
# Benchmarks for bench_nlp_constraints.jl ```julia using BenchmarkTools using CTBase using MLStyle using StaticArrays rg(i::Integer, j::Integer) = begin if i == j i else i:j end end $(Expr(:toplevel, :(ocp = Model()), :(time!(ocp, 0, 1)), :(state!(ocp, 2)), :(control!(ocp, 2)))) constraint!(ocp, :initial, Index(2), 10, :ci) constraint!(ocp, :final, Index(1), 1, :cf) constraint!(ocp, :control, [0, 0], [1, 1], :cu) constraint!(ocp, :state, [0, 1], [1, 2], :cs) constraint!(ocp, :boundary, ((x0, xf)->begin x0[2] + xf[2] end), 0, 1, :cb) constraint!(ocp, :control, (u->begin u end), [0, 0], [1, 1], :cuu) constraint!(ocp, :state, (x->begin x end), [0, 1], [1, 2], :css) constraint!(ocp, :mixed, ((x, u)->begin x[1] + u[1] end), 1, 1, :cm) function nlp_constraints_original(ocp::OptimalControlModel) CTBase.__check_all_set(ocp) constraints = ocp.constraints ΞΎf = Vector{ControlConstraint}() ΞΎl = Vector{ctNumber}() ΞΎu = Vector{ctNumber}() Ξ·f = Vector{StateConstraint}() Ξ·l = Vector{ctNumber}() Ξ·u = Vector{ctNumber}() ψf = Vector{MixedConstraint}() ψl = Vector{ctNumber}() ψu = Vector{ctNumber}() Ο•f = Vector{BoundaryConstraint}() Ο•l = Vector{ctNumber}() Ο•u = Vector{ctNumber}() ΞΈf = Vector{VariableConstraint}() ΞΈl = Vector{ctNumber}() ΞΈu = Vector{ctNumber}() uind = Vector{Int}() ul = Vector{ctNumber}() uu = Vector{ctNumber}() xind = Vector{Int}() xl = Vector{ctNumber}() xu = Vector{ctNumber}() vind = Vector{Int}() vl = Vector{ctNumber}() vu = Vector{ctNumber}() for (_, c) = constraints MLStyle.@match c begin (:initial, f::BoundaryConstraint, lb, ub) => begin push!(Ο•f, f) append!(Ο•l, lb) append!(Ο•u, ub) end (:final, f::BoundaryConstraint, lb, ub) => begin push!(Ο•f, f) append!(Ο•l, lb) append!(Ο•u, ub) end (:boundary, f::BoundaryConstraint, lb, ub) => begin push!(Ο•f, f) append!(Ο•l, lb) append!(Ο•u, ub) end (:control, f::ControlConstraint, lb, ub) => begin push!(ΞΎf, f) append!(ΞΎl, lb) append!(ΞΎu, ub) end (:control, rg, lb, ub) => begin append!(uind, rg) append!(ul, lb) append!(uu, ub) end (:state, f::StateConstraint, lb, ub) => begin push!(Ξ·f, f) append!(Ξ·l, lb) append!(Ξ·u, ub) end (:state, rg, lb, ub) => begin append!(xind, rg) append!(xl, lb) append!(xu, ub) end (:mixed, f::MixedConstraint, lb, ub) => begin push!(ψf, f) append!(ψl, lb) append!(ψu, ub) end (:variable, f::VariableConstraint, lb, ub) => begin push!(ΞΈf, f) append!(ΞΈl, lb) append!(ΞΈu, ub) end (:variable, rg, lb, ub) => begin append!(vind, rg) append!(vl, lb) append!(vu, ub) end _ => error("Internal error") end end function ΞΎ(t, u, v) val = Vector{ctNumber}() for i = 1:length(ΞΎf) append!(val, (ΞΎf[i])(t, u, v)) end return val end function Ξ·(t, x, v) val = Vector{ctNumber}() for i = 1:length(Ξ·f) append!(val, (Ξ·f[i])(t, x, v)) end return val end function ψ(t, x, u, v) val = Vector{ctNumber}() for i = 1:length(ψf) append!(val, (ψf[i])(t, x, u, v)) end return val end function Ο•(x0, xf, v) val = Vector{ctNumber}() for i = 1:length(Ο•f) append!(val, (Ο•f[i])(x0, xf, v)) end return val end function ΞΈ(v) val = Vector{ctNumber}() for i = 1:length(ΞΈf) append!(val, (ΞΈf[i])(v)) end return val end return ((ΞΎl, ΞΎ, ΞΎu), (Ξ·l, Ξ·, Ξ·u), (ψl, ψ, ψu), (Ο•l, Ο•, Ο•u), (ΞΈl, ΞΈ, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu)) end function test_alloc_bad(ocp, N) println(" getters and setters") begin function get_state(XU, i, n, m) return XU[rg((i - 1) * (n + m) + 1, (i - 1) * (n + m) + n)] end function get_control(XU, i, n, m) return XU[rg((i - 1) * (n + m) + n + 1, (i - 1) * (n + m) + n + m)] end function set_control_constraint!(C, i, ΞΎ, nΞΎ, nc) C[(i - 1) * nc + 1:(i - 1) * nc + nΞΎ] = ΞΎ end function set_state_constraint!(C, i, Ξ·, nΞ·, nΞΎ, nc) C[(i - 1) * nc + nΞΎ + 1:(i - 1) * nc + nΞΎ + nΞ·] = Ξ· end function set_mixed_constraint!(C, i, ψ, nψ, nΞΎ, nΞ·, nc) C[(i - 1) * nc + nΞΎ + nΞ· + 1:(i - 1) * nc + nΞΎ + nΞ· + nψ] = ψ end end println(" call nlp_constraints_original") ((ΞΎl, ΞΎ, ΞΎu), (Ξ·l, Ξ·, Ξ·u), (ψl, ψ, ψu), (Ο•l, Ο•, Ο•u), (ΞΈl, ΞΈ, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu)) = nlp_constraints_original(ocp) println(" declare variables") begin v = Real[] n = state_dimension(ocp) m = control_dimension(ocp) times = LinRange(0, 1, N) XU = ones(N * (n + m)) nΞΎ = length(ΞΎl) nΞ· = length(Ξ·l) nψ = length(ψl) nc = nΞΎ + nΞ· + nψ C = zeros(N * nc) end println(" start for loop") begin for i = 1:N t = times[i] x = get_state(XU, i, n, m) u = get_control(XU, i, n, m) set_control_constraint!(C, i, ΞΎ(t, u, v), nΞΎ, nc) set_state_constraint!(C, i, Ξ·(t, x, v), nΞ·, nΞΎ, nc) set_mixed_constraint!(C, i, ψ(t, x, u, v), nψ, nΞΎ, nΞ·, nc) end end println(" end for loop") nothing end function nlp_constraints_optimized(ocp::OptimalControlModel) CTBase.__check_all_set(ocp) constraints = ocp.constraints ΞΎf = Vector{ControlConstraint}() ΞΎl = Vector{ctNumber}() ΞΎu = Vector{ctNumber}() ΞΎn = Vector{Int}() Ξ·f = Vector{StateConstraint}() Ξ·l = Vector{ctNumber}() Ξ·u = Vector{ctNumber}() Ξ·n = Vector{Int}() ψf = Vector{MixedConstraint}() ψl = Vector{ctNumber}() ψu = Vector{ctNumber}() ψn = Vector{Int}() Ο•f = Vector{BoundaryConstraint}() Ο•l = Vector{ctNumber}() Ο•u = Vector{ctNumber}() Ο•n = Vector{Int}() ΞΈf = Vector{VariableConstraint}() ΞΈl = Vector{ctNumber}() ΞΈu = Vector{ctNumber}() ΞΈn = Vector{Int}() uind = Vector{Int}() ul = Vector{ctNumber}() uu = Vector{ctNumber}() xind = Vector{Int}() xl = Vector{ctNumber}() xu = Vector{ctNumber}() vind = Vector{Int}() vl = Vector{ctNumber}() vu = Vector{ctNumber}() for (_, c) = constraints MLStyle.@match c begin (:initial, f::BoundaryConstraint, lb, ub) => begin append!(Ο•n, length(lb)) push!(Ο•f, f) append!(Ο•l, lb) append!(Ο•u, ub) end (:final, f::BoundaryConstraint, lb, ub) => begin append!(Ο•n, length(lb)) push!(Ο•f, f) append!(Ο•l, lb) append!(Ο•u, ub) end (:boundary, f::BoundaryConstraint, lb, ub) => begin append!(Ο•n, length(lb)) push!(Ο•f, f) append!(Ο•l, lb) append!(Ο•u, ub) end (:control, f::ControlConstraint, lb, ub) => begin append!(ΞΎn, length(lb)) push!(ΞΎf, f) append!(ΞΎl, lb) append!(ΞΎu, ub) end (:control, rg, lb, ub) => begin append!(uind, rg) append!(ul, lb) append!(uu, ub) end (:state, f::StateConstraint, lb, ub) => begin append!(Ξ·n, length(lb)) push!(Ξ·f, f) append!(Ξ·l, lb) append!(Ξ·u, ub) end (:state, rg, lb, ub) => begin append!(xind, rg) append!(xl, lb) append!(xu, ub) end (:mixed, f::MixedConstraint, lb, ub) => begin append!(ψn, length(lb)) push!(ψf, f) append!(ψl, lb) append!(ψu, ub) end (:variable, f::VariableConstraint, lb, ub) => begin append!(ΞΈn, length(lb)) push!(ΞΈf, f) append!(ΞΈl, lb) append!(ΞΈu, ub) end (:variable, rg, lb, ub) => begin append!(vind, rg) append!(vl, lb) append!(vu, ub) end _ => error("Internal error") end end ΞΎfn = length(ΞΎf) Ξ·fn = length(Ξ·f) ψfn = length(ψf) Ο•fn = length(Ο•f) ΞΈfn = length(ΞΈf) function ΞΎ!(val, t, u, v, N = ΞΎfn) offset = 0 for i = 1:N z = ((ΞΎf[i])(t, u, v))[:] val[rg(1 + offset, ΞΎn[i] + offset)] = z offset += ΞΎn[i] end nothing end function Ξ·!(val, t, x, v, N = Ξ·fn) offset = 0 for i = 1:N val[rg(1 + offset, Ξ·n[i] + offset)] = (Ξ·f[i])(t, x, v) offset += Ξ·n[i] end nothing end function ψ!(val, t, x, u, v, N = ψfn) offset = 0 for i = 1:N val[rg(1 + offset, ψn[i] + offset)] = (ψf[i])(t, x, u, v) offset += ψn[i] end nothing end function Ο•!(val, x0, xf, v, N = Ο•fn) offset = 0 for i = 1:N val[rg(1 + offset, Ο•n[i] + offset)] = (Ο•f[i])(x0, xf, v) offset += Ο•n[i] end nothing end function ΞΈ!(val, v, N = ΞΈfn) offset = 0 for i = 1:N val[rg(1 + offset, ΞΈn[i] + offset)] = (ΞΈf[i])(v) offset += ΞΈn[i] end nothing end return ((ΞΎl, ΞΎ!, ΞΎu), (Ξ·l, Ξ·!, Ξ·u), (ψl, ψ!, ψu), (Ο•l, Ο•!, Ο•u), (ΞΈl, ΞΈ!, ΞΈu), (uind, ul, uu), (xind, xl, xu), (vind, vl, vu)) end function test_alloc_good(ocp, N) begin println(" getters and setters") begin function get_state(XU, i, n, m) if n == 1 return XU[(i - 1) * (n + m) + 1] else return @view(XU[(i - 1) * (n + m) + 1:(i - 1) * (n + m) + n]) end end function get_control(XU, i, n, m) if m == 1 return XU[(i - 1) * (n + m) + n + 1] else return @view(XU[(i - 1) * (n + m) + n + 1:(i - 1) * (n + m) + n + m]) end end function set_control_constraint!(C, i, valΞΎ, nΞΎ, nc) C[(i - 1) * nc + 1:(i - 1) * nc + nΞΎ] = valΞΎ end function set_state_constraint!(C, i, valΞ·, nΞ·, nΞΎ, nc) C[(i - 1) * nc + nΞΎ + 1:(i - 1) * nc + nΞΎ + nΞ·] = valΞ· end function set_mixed_constraint!(C, i, valψ, nψ, nΞΎ, nΞ·, nc) C[(i - 1) * nc + nΞΎ + nΞ· + 1:(i - 1) * nc + nΞΎ + nΞ· + nψ] = valψ end end println(" call nlp_constraints_optimized") begin ((ΞΎl, ΞΎ!, ΞΎu), (Ξ·l, Ξ·!, Ξ·u), (ψl, ψ!, ψu), (Ο•l, Ο•!, Ο•u), (ΞΈl, ΞΈ!, ΞΈu), (ul, uind, uu), (xl, xind, xu), (vl, vind, vu)) = nlp_constraints_optimized(ocp) end println(" declare variables") begin v = Real[] n = state_dimension(ocp) m = control_dimension(ocp) times = LinRange(0, 1, N) XU = zeros(N * (n + m)) nΞΎ = length(ΞΎl) nΞ· = length(Ξ·l) nψ = length(ψl) nc = nΞΎ + nΞ· + nψ C = zeros(N * nc) valΞΎ = SizedVector{nΞΎ}(zeros(nΞΎ)) valΞ· = SizedVector{nΞ·}(zeros(nΞ·)) valψ = SizedVector{nψ}(zeros(nψ)) x = SizedVector{n}(zeros(n)) u = SizedVector{m}(zeros(m)) end t = 0 println(" start for loop") for i = 1:N t = times[i] x[:] = XU[(i - 1) * (n + m) + 1:(i - 1) * (n + m) + n] u[:] = @view(XU[(i - 1) * (n + m) + n + 1:(i - 1) * (n + m) + n + m]) ΞΎ!(valΞΎ, t, u, v) Ξ·!(valΞ·, t, x, v) ψ!(valψ, t, x, u, v) C[(i - 1) * nc + 1:(i - 1) * nc + nΞΎ] = valΞΎ C[(i - 1) * nc + nΞΎ + 1:(i - 1) * nc + nΞΎ + nΞ·] = valΞ· C[(i - 1) * nc + nΞΎ + nΞ· + 1:(i - 1) * nc + nΞΎ + nΞ· + nψ] = valψ end println(" end for loop") nothing end end N = 10000 $(Expr(:toplevel, :(test_alloc_good(ocp, N)))) $(Expr(:toplevel, :(test_alloc_bad(ocp, N)))) println("----------------------------------------") println("good code") @time test_alloc_good(ocp, N) println() println("bad code") @time test_alloc_bad(ocp, N)
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
docs
5992
# Benchmarks for bench_usage.jl ```julia using BenchmarkTools struct Fun_dim_usage_each_call f::Function end function (F::Fun_dim_usage_each_call)(t::Real, x::Vector{<:Real}, u::Vector{<:Real}, args...; kwargs...) x_ = if length(x) == 1 (x[1],) else (x,) end u_ = if length(u) == 1 (u[1],) else (u,) end y = F.f(t, x_..., u_..., args...; kwargs...) return if y isa Real [y] else y end end t = 1 x = [10] u = [100] F = Fun_dim_usage_each_call(((t, x, u)->begin x + u end)) @benchmark F(t, x, u) ``` ```bash BenchmarkTools.Trial: 10000 samples with 492 evaluations. Range (min … max): 221.518 ns … 11.205 ΞΌs β”Š GC (min … max): 0.00% … 0.00% Time (median): 235.602 ns β”Š GC (median): 0.00% Time (mean Β± Οƒ): 287.003 ns Β± 268.401 ns β”Š GC (mean Β± Οƒ): 2.30% Β± 3.26% β–ˆβ–†β–…β–†β–…β–ƒβ–β–β–β– ▁▁ ▁ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‡β–‡β–‡β–‡β–‡β–‡β–ˆβ–‡β–‡β–‡β–‡β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‡β–‡β–†β–†β–†β–†β–†β–†β–†β–…β–†β–†β–…β–†β–…β–†β–…β–…β–„β–„β–…β–ƒβ–ƒβ–„β–ƒβ–ƒ β–ˆ 222 ns Histogram: log(frequency) by time 780 ns < Memory estimate: 112 bytes, allocs estimate: 4. ``` ```julia F = Fun_dim_usage_each_call(((t, x, u)->begin x + u[1] end)) @benchmark F(t, x, u) ``` ```bash BenchmarkTools.Trial: 10000 samples with 487 evaluations. Range (min … max): 219.608 ns … 13.100 ΞΌs β”Š GC (min … max): 0.00% … 96.18% Time (median): 243.357 ns β”Š GC (median): 0.00% Time (mean Β± Οƒ): 282.687 ns Β± 268.154 ns β”Š GC (mean Β± Οƒ): 2.82% Β± 3.28% β–ˆβ–‡β–…β–†β–†β–†β–„β–ƒβ–‚β–‚β–‚β–β–β–β–β– ▁▁ β–‚ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‡β–‡β–‡β–‡β–‡β–‡β–†β–‡β–‡β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‡β–‡β–‡β–‡β–†β–‡β–†β–…β–†β–…β–…β–…β–†β–…β–†β–…β–†β–†β–…β–… β–ˆ 220 ns Histogram: log(frequency) by time 664 ns < Memory estimate: 112 bytes, allocs estimate: 4. ``` ```julia struct Fun_dim_usage_parametrization{dim_x, dim_u} f::Function end function (F::Fun_dim_usage_parametrization{1, 1})(t::Real, x::Vector{<:Real}, u::Vector{<:Real}, args...; kwargs...) return [F.f(t, x[1], u[1], args...; kwargs...)] end F = Fun_dim_usage_parametrization{1, 1}(((t, x, u)->begin x + u end)) @benchmark F(t, x, u) ``` ```bash BenchmarkTools.Trial: 10000 samples with 943 evaluations. Range (min … max): 100.929 ns … 7.845 ΞΌs β”Š GC (min … max): 0.00% … 0.00% Time (median): 113.607 ns β”Š GC (median): 0.00% Time (mean Β± Οƒ): 154.201 ns Β± 217.625 ns β”Š GC (mean Β± Οƒ): 2.17% Β± 3.39% β–ˆβ–‡β–†β–…β–ƒβ–ƒβ–‚β–‚β–‚β–‚β–β–β–β–β–β–‚β–‚β–ƒβ–‚β–‚β–β– β–‚ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‡β–†β–ˆβ–‡β–‡β–†β–‡β–†β–‡β–†β–†β–…β–…β–†β–…β–„β–„β–…β–…β–…β–…β–…β–„β–„β–„β–ƒβ–„β–ƒβ–ƒβ–…β–…β–…β–β–ƒβ–ƒ β–ˆ 101 ns Histogram: log(frequency) by time 590 ns < Memory estimate: 64 bytes, allocs estimate: 1. ``` ```julia F = Fun_dim_usage_parametrization{1, 1}(((t, x, u)->begin x + u[1] end)) @benchmark F(t, x, u) ``` ```bash BenchmarkTools.Trial: 10000 samples with 932 evaluations. Range (min … max): 108.153 ns … 9.895 ΞΌs β”Š GC (min … max): 0.00% … 97.64% Time (median): 121.779 ns β”Š GC (median): 0.00% Time (mean Β± Οƒ): 163.448 ns Β± 209.973 ns β”Š GC (mean Β± Οƒ): 2.82% Β± 3.41% β–ˆβ–‡β–†β–„β–ƒβ–ƒβ–ƒβ–‚β–‚β–‚β–‚β–‚β–‚β–‚β–ƒβ–ƒβ–ƒβ–‚β–‚β– β–‚ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‡β–ˆβ–‡β–†β–†β–†β–†β–‡β–…β–†β–†β–„β–…β–†β–…β–†β–†β–…β–…β–„β–…β–…β–„β–…β–…β–…β–„β–„β–„β–ƒβ–ƒβ–„β–β–β–„ β–ˆ 108 ns Histogram: log(frequency) by time 637 ns < Memory estimate: 64 bytes, allocs estimate: 1. ``` ```julia Ο•(t, x, u) = begin x[1] + u[1] end @benchmark Ο•(t, x, u) ``` ```bash BenchmarkTools.Trial: 10000 samples with 996 evaluations. Range (min … max): 23.104 ns … 331.326 ns β”Š GC (min … max): 0.00% … 0.00% Time (median): 23.441 ns β”Š GC (median): 0.00% Time (mean Β± Οƒ): 25.784 ns Β± 8.268 ns β”Š GC (mean Β± Οƒ): 0.00% Β± 0.00% β–ˆ β–‡ ▁ ▁ β–ˆβ–‡β–†β–ˆβ–†β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–…β–…β–…β–„β–…β–„β–„β–†β–‡β–†β–†β–‡β–‡β–†β–…β–†β–†β–…β–†β–†β–†β–†β–†β–†β–‡β–‡β–‡β–‡β–‡β–‡β–‡β–†β–…β–ƒβ–ƒβ–‚β–‚β–…β–…β–„β–ƒβ–ƒβ–…β–…β–…β–„β–…β–„β–ƒβ–ƒ β–ˆ 23.1 ns Histogram: log(frequency) by time 52.7 ns < Memory estimate: 0 bytes, allocs estimate: 0. ``` ```julia ψ(t, x, u) = begin x + u end @benchmark ψ(t, x[1], u[1]) ``` ```bash BenchmarkTools.Trial: 10000 samples with 983 evaluations. Range (min … max): 56.845 ns … 624.227 ns β”Š GC (min … max): 0.00% … 0.00% Time (median): 57.128 ns β”Š GC (median): 0.00% Time (mean Β± Οƒ): 65.067 ns Β± 20.266 ns β”Š GC (mean Β± Οƒ): 0.00% Β± 0.00% β–ˆβ– ▆▂▁ β–‚ ▁ β–ˆβ–ˆβ–ˆβ–‡β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‡β–†β–†β–†β–†β–†β–†β–†β–†β–†β–†β–†β–†β–†β–†β–‡β–‡β–‡β–‡β–†β–‡β–ˆβ–‡β–‡β–‡β–ˆβ–ˆβ–‡β–‡β–‡β–ˆβ–‡β–†β–‡β–†β–†β–…β–†β–†β–…β–…β–…β–…β–…β–…β–†β–„ β–ˆ 56.8 ns Histogram: log(frequency) by time 130 ns < Memory estimate: 0 bytes, allocs estimate: 0. ``` ```julia ΞΈ(t, x, u) = begin x + u end @benchmark (ΞΈ(t, x, u))[1] ``` ```bash BenchmarkTools.Trial: 10000 samples with 965 evaluations. Range (min … max): 83.120 ns … 5.867 ΞΌs β”Š GC (min … max): 0.00% … 97.83% Time (median): 94.203 ns β”Š GC (median): 0.00% Time (mean Β± Οƒ): 123.157 ns Β± 151.340 ns β”Š GC (mean Β± Οƒ): 3.19% Β± 3.29% β–ˆβ–‡β–‡β–…β–„β–ƒβ–ƒβ–‚β–‚β–‚β–‚β–β–β– ▁▁▁▁▂▂▂▃▂▂▂▁▁ β–‚ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‡β–‡β–‡β–‡β–‡β–†β–‡β–†β–‡β–†β–†β–†β–†β–…β–†β–…β–…β–†β–…β–…β–…β–†β–†β–…β–β–„β–…β–…β–…β–ƒβ–ƒβ–… β–ˆ 83.1 ns Histogram: log(frequency) by time 408 ns < Memory estimate: 64 bytes, allocs estimate: 1. ``` ```julia ΞΎ(t, x, u) = begin x + u end a = x[1] b = u[1] @benchmark ΞΎ(t, a, b) ``` ```bash BenchmarkTools.Trial: 10000 samples with 996 evaluations. Range (min … max): 22.802 ns … 3.982 ΞΌs β”Š GC (min … max): 0.00% … 0.00% Time (median): 25.470 ns β”Š GC (median): 0.00% Time (mean Β± Οƒ): 36.790 ns Β± 90.791 ns β”Š GC (mean Β± Οƒ): 0.00% Β± 0.00% β–ˆβ–†β–‚β–ƒβ–„β–„β–ƒβ–‚β–‚β–β–β– ▁ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‡β–‡β–‡β–†β–‡β–†β–†β–†β–…β–…β–…β–…β–…β–…β–„β–…β–„β–…β–…β–„β–„β–ƒβ–„β–…β–„β–„β–„β–…β–β–„β–„β–„β–β–ƒβ–β–β–β–„β–ƒβ–„β–„ β–ˆ 22.8 ns Histogram: log(frequency) by time 182 ns < Memory estimate: 0 bytes, allocs estimate: 0. ```
CTBase
https://github.com/control-toolbox/CTBase.jl.git