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.0.3 | 5ff0e4fee0b4144ad3393177f449108cd07556d1 | code | 766 | module SatelliteToolboxLegendre
############################################################################################
# Includes #
############################################################################################
include("./misc.jl")
include("./dlegendre/fully_normalized_dlegendre.jl")
include("./dlegendre/schmidt_quasi_normalized_dlegendre.jl")
include("./dlegendre/unnormalized_dlegendre.jl")
include("./dlegendre/dlegendre.jl")
include("./legendre/fully_normalized_legendre.jl")
include("./legendre/schmidt_quasi_normalized_legendre.jl")
include("./legendre/unnormalized_legendre.jl")
include("./legendre/legendre.jl")
end # module SatelliteToolboxLegendre
| SatelliteToolboxLegendre | https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl.git |
|
[
"MIT"
] | 1.0.3 | 5ff0e4fee0b4144ad3393177f449108cd07556d1 | code | 1825 | ## Description #############################################################################
#
# Miscellaneous functions.
#
############################################################################################
# Return the maximum degree and order to compute the Legendre associated functions given the
# matrix `P` and the configuration values `n_max` and `m_max`.
function _get_degree_and_order(P::AbstractMatrix, n_max::Integer, m_max::Integer)
# Get the size of the matrix.
rows, cols = size(P)
# If the order or degree is less than 0, then the user wants to use all the available
# memory.
if n_max < 0
n_max = rows - 1
end
if m_max < 0
m_max = (cols <= rows) ? cols - 1 : n_max
end
# Make sure that the degree and order fits the matrix.
if n_max > rows - 1
n_max = rows - 1
end
if (m_max > cols - 1) || (m_max > n_max)
m_max = min(cols - 1, n_max)
end
return n_max, m_max
end
# Return the maximum degree and order to compute the Legendre associated functions given the
# matrices `dP`, `P`, and the configuration values `n_max` and `m_max`.
function _get_degree_and_order(dP, P, n_max, m_max)
# Get the size of the matrices.
Prows, Pcols = size(P)
dProws, dPcols = size(dP)
rows = min(Prows, dProws)
cols = min(Pcols, dPcols)
# If the order or degree is less than 0, then the user wants to use all the available
# memory.
if n_max < 0
n_max = rows - 1
end
if m_max < 0
m_max = (cols <= rows) ? cols - 1 : n_max
end
# Make sure that the degree and order fits the matrix.
if n_max > rows - 1
n_max = rows - 1
end
if (m_max > cols - 1) || (m_max > n_max)
m_max = min(cols - 1, n_max)
end
return n_max, m_max
end
| SatelliteToolboxLegendre | https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl.git |
|
[
"MIT"
] | 1.0.3 | 5ff0e4fee0b4144ad3393177f449108cd07556d1 | code | 4853 | ## Description #############################################################################
#
# Functions related to the first-order derivative of associated Legendre functions.
#
## References ##############################################################################
#
# [1] Du, J., Chen, C., Lesur, V., and Wang, L (2015). Non-singular spherical harmonic
# expressions of geomagnetic vector and gradient tensor fields in the local
# north-oriented reference frame. Geoscientific Model Development, 8, pp. 1979-1990.
#
# [2] Ilk, K. H.: Ein Beitrag zur Dynamik ausgedehnter Körper-Gravitationswechselwirkung,
# Deutsche Geodätische Kommission. Reihe C, Heft Nr. 288, München, 1983.
#
############################################################################################
export dlegendre!, dlegendre
"""
dlegendre!(dP::AbstractMatrix, ϕ::Number, P::AbstractMatrix, n_max::Integer = -1, m_max::Integer = -1; kwargs...) -> Nothing
Compute the first-order derivative of the associated Legendre function `P_n,m[cos(ϕ)]` with
respect to `ϕ` [rad]:
∂P_n,m[cos(ϕ)]
──────────────
∂ϕ
The maximum degree and order that will be computed are given by the parameters `n_max` and
`m_max`. If they are negative (default), the dimensions of matrix `dP` will be used:
maximum degree -> number of rows - 1
maximum order -> number of columns - 1
The derivatives will be stored in the matrix `dP`.
The parameter `N` selects the normalization. The following values are valid:
- `Val(:full)`: Compute the fully normalized associated Legendre function.
- `Val(:schmidt)`: Compute the Schmidt quasi-normalized associated Legendre function.
- `Val(:unnormalized)`: Compute the unnormalized associated Legendre function.
This algorithm needs the matrix `P` with the values of the associated Legendre function
using the same normalization `N`, which can be computed using the function
[`legendre`](@ref).
!!! warning
The user is responsible to pass a matrix `P` with the correct values. For example, if
`ph_term` is `true`, `P` must also be computed with `ph_term` set to `true`.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
"""
function dlegendre!(
::Val{:full},
dP::AbstractMatrix,
ϕ::Number,
P::AbstractMatrix,
n_max::Integer = -1,
m_max::Integer = -1;
ph_term::Bool = false
)
return fully_normalized_dlegendre!(dP, ϕ, P, n_max, m_max; ph_term = ph_term)
end
function dlegendre!(
::Val{:schmidt},
dP::AbstractMatrix,
ϕ::Number,
P::AbstractMatrix,
n_max::Integer = -1,
m_max::Integer = -1;
ph_term::Bool = false
)
return schmidt_quasi_normalized_dlegendre!(dP, ϕ, P, n_max, m_max; ph_term = ph_term)
end
function dlegendre!(
::Val{:unnormalized},
dP::AbstractMatrix,
ϕ::Number,
P::AbstractMatrix,
n_max::Integer = -1,
m_max::Integer = -1;
ph_term::Bool = false
)
return unnormalized_dlegendre!(dP, ϕ, P, n_max, m_max; ph_term = ph_term)
end
"""
dlegendre(N, ϕ::T, n_max::Integer, m_max::Integer = -1; kwargs...) where T<:Number -> Matrix{float(T)}, Matrix{float(T)}
Compute the first-order derivative of the associated Legendre function `P_n,m[cos(ϕ)]` with
respect to `ϕ` [rad]:
∂P_n,m[cos(ϕ)]
──────────────
∂ϕ
The maximum degree that will be computed is `n_max` and the maximum order is `m_max`. Notice
that if `m_max` is higher than `n_max` or negative (default), it is set to `n_max`.
The parameter `N` selects the normalization. The following values are valid:
- `Val(:full)`: Compute the fully normalized associated Legendre function.
- `Val(:schmidt)`: Compute the Schmidt quasi-normalized associated Legendre function.
- `Val(:unnormalized)`: Compute the unnormalized associated Legendre function.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
# Returns
- `Matrix{float(T)}`: A matrix with the first-order derivative of the Legendre associated
functions `P_n,m[cos(ϕ)]`.
- `Matrix{float(T)}`: A matrix with the Legendre associated functions `P_n,m[cos(ϕ)]`.
"""
function dlegendre(
::Val{:full},
ϕ::Number,
n_max::Integer,
m_max::Integer = -1;
ph_term::Bool = false
)
return fully_normalized_dlegendre(ϕ, n_max, m_max; ph_term = ph_term)
end
function dlegendre(
::Val{:schmidt},
ϕ::Number,
n_max::Integer,
m_max::Integer = -1;
ph_term::Bool = false
)
return schmidt_quasi_normalized_dlegendre(ϕ, n_max, m_max; ph_term = ph_term)
end
function dlegendre(
::Val{:unnormalized},
ϕ::Number,
n_max::Integer,
m_max::Integer = -1;
ph_term::Bool = false
)
return unnormalized_dlegendre(ϕ, n_max, m_max; ph_term = ph_term)
end
| SatelliteToolboxLegendre | https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl.git |
|
[
"MIT"
] | 1.0.3 | 5ff0e4fee0b4144ad3393177f449108cd07556d1 | code | 7229 | ## Description #############################################################################
#
# Compute the first-order derivative of associated Legendre functions with full
# normalization.
#
## References ##############################################################################
#
# [1] Du, J., Chen, C., Lesur, V., and Wang, L (2015). Non-singular spherical harmonic
# expressions of geomagnetic vector and gradient tensor fields in the local
# north-oriented reference frame. Geoscientific Model Development, 8, pp. 1979-1990.
#
# [2] Ilk, K. H.: Ein Beitrag zur Dynamik ausgedehnter Körper-Gravitationswechselwirkung,
# Deutsche Geodätische Kommission. Reihe C, Heft Nr. 288, München, 1983.
#
############################################################################################
"""
fully_normalized_dlegendre!(dP::AbstractMatrix{T}, ϕ::Number, P::AbstractMatrix, n_max::Integer = -1, m_max::Integer = -1; kwargs...) where T<:Number -> Nothing
Compute the first-order derivative of the fully normalized associated Legendre function
`P_n,m[cos(ϕ)]` with respect to `ϕ` [rad]:
∂P_n,m[cos(ϕ)]
──────────────
∂ϕ
The maximum degree and order that will be computed are given by the parameters `n_max` and
`m_max`. If they are negative (default), the dimensions of matrix `dP` will be used:
maximum degree -> number of rows - 1
maximum order -> number of columns - 1
The derivatives will be stored in the matrix `dP`.
This algorithm needs the matrix `P` with the values of the fully normalized associated
Legendre function. This can be computed using the function
[`fully_normalized_legendre!`](@ref).
!!! warning
The user is responsible to pass a matrix `P` with the correct values. For example, if
`ph_term` is `true`, `P` must also be computed with `ph_term` set to `true`.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
"""
function fully_normalized_dlegendre!(
dP::AbstractMatrix{T},
ϕ::Number,
P::AbstractMatrix,
n_max::Integer = -1,
m_max::Integer = -1;
ph_term::Bool = false
) where T<:Number
# Obtain the maximum degree and order that must be computed.
n_max, m_max = _get_degree_and_order(dP, P, n_max, m_max)
# The derivative is compute using the following equation [1, p. 1981]:
#
# ∂P(n, m)
# ──────── = a_nm . P(n,m-1) + b_nm . P(n,m+1),
# ∂ϕ
#
# a_nm = ¹/₂ . √(n + m) . √(n - m + 1) . √(C_{m} / C_{m-1})
#
# b_nm = -¹/₂ . √(n + m + 1) . √(n - m) . √(C_{m} / C_{m+1})
#
# ┌
# │ 1, m = 0
# C_{m} = │
# │ 2, m != 0
# └
#
# NOTE: The conversion of the coefficients between the full normalization and the
# Schmidt quasi-normalization is performed using:
#
# √(2n + 1),
#
# which depends only on `n`. Since the derivative equation only has terms related to the
# order `n`, the same algorithm will work for both full normalization and Schmidt
# quasi-normalization.
#
# TODO: This algorithm is based on eq. Z.1.44 of [2]. However, it was verified that it
# does not provide the correct sign when ϕ ∈ [π, 2π]. This makes sense because the
# algorithm uses only the values of the coefficients, which are equal for ϕ and -ϕ.
# However, the derivative with respect to ϕ does change. This hack was used so that the
# values are correct, but further verification is needed.
#
# In fact, in [2, p. 119], it is mentioned that `0 <= ϕ <= π`. However, further
# clarification is required.
ϕ = mod(ϕ, T(2π))
fact = ϕ > π ? -1 : 1
if ph_term
fact *= -1
end
# Get the first indices in `P` to take into account offset arrays.
i₀, j₀ = first.(axes(P))
# Get the first indices in `dP` to take into account offset arrays.
di₀, dj₀ = first.(axes(dP))
dP[di₀, dj₀] = 0
m_max < 0 && return nothing
@inbounds for n in 1:n_max
for m in 0:n
if m == 0
aux = √(T(n) * T(n + 1) / 2)
a_nm = aux / 2
b_nm = -a_nm
# Notice that [1, p. 1985]:
#
# m
# P_(n, -m) = (-1) . P_(n, m),
#
dP[di₀+n, dj₀] = -a_nm * P[i₀+n, j₀+1] + b_nm * P[i₀+n, j₀+1]
# We should consider the case `m == 1` separately from `n == m` because of the
# coefficient `C_{m}`.
elseif m == 1
a_nm = √(T(2n) * T(n + 1)) / 2
dP[di₀+n, dj₀+1] = a_nm * P[i₀+n, j₀]
# Only compute `b_nm` if `n > 1`. Otherwise, we could access an invalid
# memory region if `P` is 2 × 2.
if n > 1
b_nm = -√(T(n + 2) * T(n - 1)) / 2
dP[di₀+n, dj₀+1] += b_nm * P[i₀+n, j₀+2]
end
elseif n != m
a_nm = +√(T(n + m) * T(n - m + 1)) / 2
b_nm = -√(T(n + m + 1) * T(n - m)) / 2
dP[di₀+n, dj₀+m] = a_nm * P[i₀+n, j₀+m-1] + b_nm * P[i₀+n, j₀+m+1]
else
a_nm = +√(T(n + m) * T(n - m + 1)) / 2
dP[di₀+n, dj₀+m] = a_nm * P[i₀+n, j₀+m-1]
end
dP[di₀+n, dj₀+m] *= fact
# Check if the maximum desired order has been reached.
m >= m_max && break
end
end
return nothing
end
"""
dlegendre_fully_normalized(ϕ::T, n_max::Integer, m_max::Integer = -1, ph_term::Bool = false) where T<:Number -> Matrix{float(T)}, Matrix{float(T)}
Compute the first-order derivative of the fully normalized associated Legendre function
`P_n,m[cos(ϕ)]` with respect to `ϕ` [rad]:
∂P_n,m[cos(ϕ)]
──────────────
∂ϕ
The maximum degree that will be computed is `n_max` and the maximum order is `m_max`. Notice
that if `m_max` is higher than `n_max` or negative (default), it is set to `n_max`.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
# Returns
- `Matrix{float(T)}`: A matrix with the first-order derivative of the Legendre associated
functions `P_n,m[cos(ϕ)]`.
- `Matrix{float(T)}`: A matrix with the Legendre associated functions `P_n,m[cos(ϕ)]`.
"""
function fully_normalized_dlegendre(
ϕ::T,
n_max::Integer,
m_max::Integer = -1;
ph_term::Bool = false
) where T<:Number
if (m_max < 0) || (m_max > n_max)
m_max = n_max
end
# Check if we need to compute and additional degree in `P` to provide the desire order
# in `dP`.
if n_max == m_max
n_max_P = m_max_P = n_max
else
n_max_P = n_max
m_max_P = m_max + 1
end
# First, compute the matrix with the associated Legendre functions.
P = fully_normalized_legendre(ϕ, n_max_P, m_max_P; ph_term = ph_term)
# Now, compute and return the derivative of the associated Legendre functions.
dP = zeros(float(T), n_max + 1, m_max + 1)
fully_normalized_dlegendre!(dP, ϕ, P; ph_term = ph_term)
return dP, P
end
| SatelliteToolboxLegendre | https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl.git |
|
[
"MIT"
] | 1.0.3 | 5ff0e4fee0b4144ad3393177f449108cd07556d1 | code | 3673 | ## Description #############################################################################
#
# Compute the first-order derivative of associated Legendre functions with the Schmidt
# quasi-normalization.
#
############################################################################################
"""
schmidt_quasi_normalized_dlegendre!(dP::AbstractMatrix, ϕ::Number, P::AbstractMatrix, n_max::Integer = -1, m_max::Integer = -1; kwargs...) -> Nothing
Compute the first-order derivative of the Schmidt quasi-normalized associated Legendre
function `P_n,m[cos(ϕ)]` with respect to `ϕ` [rad]:
∂P_n,m[cos(ϕ)]
──────────────
∂ϕ
The maximum degree and order that will be computed are given by the parameters `n_max` and
`m_max`. If they are negative (default), the dimensions of matrix `dP` will be used:
maximum degree -> number of rows - 1
maximum order -> number of columns - 1
The derivatives will be stored in the matrix `dP`.
This algorithm needs the matrix `P` with the values of the Schmidt quasi-normalized
associated Legendre function. This can be computed using the function
[`schmidt_quase_normalized_legendre!`](@ref).
!!! warning
The user is responsible to pass a matrix `P` with the correct values. For example, if
`ph_term` is `true`, `P` must also be computed with `ph_term` set to `true`.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
"""
function schmidt_quasi_normalized_dlegendre!(
dP::AbstractMatrix,
ϕ::Number,
P::AbstractMatrix,
n_max::Integer = -1,
m_max::Integer = -1;
ph_term::Bool = false
)
# The algorithm to compute the first-order derivative using Schmidt normalization is
# precisely the same as the one that computes using full normalization, given that `P`
# has the correct coefficients.
return fully_normalized_dlegendre!(dP, ϕ, P, n_max, m_max; ph_term = ph_term)
end
"""
schmidt_quasi_normalized_dlegendre(ϕ::T, n_max::Integer, m_max::Integer = -1; kwargs...) where T<:Number -> Matrix{float(T)}, Matrix{float(T)}
Compute the first-order derivative of the Schmidt quasi-normalized associated Legendre
function `P_n,m[cos(ϕ)]` with respect to `ϕ` [rad]:
∂P_n,m[cos(ϕ)]
──────────────
∂ϕ
The maximum degree that will be computed is `n_max` and the maximum order is `m_max`. Notice
that if `m_max` is higher than `n_max` or negative (default), it is set to `n_max`.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
# Returns
- `Matrix{float(T)}`: A matrix with the first-order derivative of the Legendre associated
functions `P_n,m[cos(ϕ)]`.
- `Matrix{float(T)}`: A matrix with the Legendre associated functions `P_n,m[cos(ϕ)]`.
"""
function schmidt_quasi_normalized_dlegendre(
ϕ::T,
n_max::Integer,
m_max::Integer = -1;
ph_term::Bool = false
) where T<:Number
if (m_max < 0) || (m_max > n_max)
m_max = n_max
end
# Check if we need to compute and additional degree in `P` to provide the desire order
# in `dP`.
if n_max == m_max
n_max_P = m_max_P = n_max
else
n_max_P = n_max
m_max_P = m_max + 1
end
# First, compute the matrix with the associated Legendre functions.
P = schmidt_quasi_normalized_legendre(ϕ, n_max_P, m_max_P; ph_term = ph_term)
# Now, compute and return the derivative of the associated Legendre
# functions.
dP = zeros(float(T), n_max + 1, m_max + 1)
schmidt_quasi_normalized_dlegendre!(dP, ϕ, P; ph_term = ph_term)
return dP, P
end
| SatelliteToolboxLegendre | https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl.git |
|
[
"MIT"
] | 1.0.3 | 5ff0e4fee0b4144ad3393177f449108cd07556d1 | code | 5585 | ## Description #############################################################################
#
# Compute the first-order derivative of associated Legendre functions without
# normalization.
#
## References ##############################################################################
#
# [1] Du, J., Chen, C., Lesur, V., and Wang, L (2015). Non-singular spherical harmonic
# expressions of geomagnetic vector and gradient tensor fields in the local
# north-oriented reference frame. Geoscientific Model Development, 8, pp. 1979-1990.
#
# [2] Ilk, K. H.: Ein Beitrag zur Dynamik ausgedehnter Körper-Gravitationswechselwirkung,
# Deutsche Geodätische Kommission. Reihe C, Heft Nr. 288, München, 1983.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
"""
unnormalized_dlegendre!(dP::AbstractMatrix{T}, ϕ::Number, P::AbstractMatrix, n_max::Integer = -1, m_max::Integer = -1; kwargs...) where T<:Number -> Nothing
Compute the first-order derivative of the unnormalized (or conventional) associated Legendre
function `P_n,m[cos(ϕ)]` with respect to `ϕ` [rad]:
∂P_n,m[cos(ϕ)]
──────────────
∂ϕ
The maximum degree and order that will be computed are given by the parameters `n_max` and
`m_max`. If they are negative (default), the dimensions of matrix `dP` will be used:
maximum degree -> number of rows - 1
maximum order -> number of columns - 1
The derivatives will be stored in the matrix `dP`.
This algorithm needs the matrix `P` with the values of the unnormalized associated Legendre
function. This can be computed using the function [`unnormalized_legendre!`](@ref).
!!! warning
The user is responsible to pass a matrix `P` with the correct values. For example, if
`ph_term` is `true`, `P` must also be computed with `ph_term` set to `true`.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
"""
function unnormalized_dlegendre!(
dP::AbstractMatrix{T},
ϕ::Number,
P::AbstractMatrix,
n_max::Integer = -1,
m_max::Integer = -1;
ph_term::Bool = false
) where T<:Number
# Obtain the maximum degree and order that must be computed.
n_max, m_max = _get_degree_and_order(dP, P, n_max, m_max)
# The derivative is computed using the following equation [1, p. 1981]:
#
# ∂P(n, m)
# ──────── = ¹/₂ . ((n + m) . (n - m + 1) . P(n, m-1) - P(n, m+1)),
# ∂θ
#
# TODO: This algorithm is based on eq. Z.1.44 of [2]. However, it was verified that it
# does not provide the correct sign when ϕ ∈ [π, 2π]. This makes sense because the
# algorithm uses only the values of the coefficients, which are equal for ϕ and -ϕ.
# However, the derivative w.r.t. ϕ does change. This hack was used so that the values
# are correct, but further verification is needed.
#
# In fact, in [2, p. 119], it is mentioned that `0 <= ϕ <= π`. However, further
# clarification is required.
ϕ = mod(ϕ, T(2π))
fact = ϕ > π ? -1 : 1
if ph_term
fact *= -1
end
# Get the first indices in `P` to take into account offset arrays.
i₀, j₀ = first.(axes(P))
# Get the first indices in `dP` to take into account offset arrays.
di₀, dj₀ = first.(axes(dP))
dP[di₀, dj₀] = 0
m_max < 0 && return nothing
@inbounds for n in 1:n_max
for m in 0:n
if m == 0
dP[di₀+n, dj₀+m] = -P[i₀+n, j₀+1]
elseif n != m
dP[di₀+n, dj₀+m] = ((n + m) * (n - m + 1) * P[i₀+n, j₀+m-1] - P[i₀+n, j₀+m+1]) / 2
else
dP[di₀+n, dj₀+m] = ((n + m) * (n - m + 1) * P[i₀+n, j₀+m-1]) / 2
end
dP[di₀+n, dj₀+m] *= fact
# Check if the maximum desired order has been reached.
m >= m_max && break
end
end
nothing
end
"""
unnormalized_dlegendre(ϕ::T, n_max::Integer, m_max::Integer = -1; ph_term::Bool = false) where T<:Number -> Matrix{float(T)}, Matrix{float(T)}
Compute the first-order derivative of the unnormalized (or conventional) associated Legendre
function `P_n,m[cos(ϕ)]` with respect to `ϕ` [rad]:
∂P_n,m[cos(ϕ)]
──────────────
∂ϕ
The maximum degree that will be computed is `n_max` and the maximum order is `m_max`. Notice
that if `m_max` is higher than `n_max` or negative, it is set to `n_max`.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
# Returns
- `Matrix{float(T)}`: A matrix with the first-order derivative of the Legendre associated
functions `P_n,m[cos(ϕ)]`.
- `Matrix{float(T)}`: A matrix with the Legendre associated functions `P_n,m[cos(ϕ)]`.
"""
function unnormalized_dlegendre(
ϕ::T,
n_max::Integer,
m_max::Integer = -1;
ph_term::Bool = false
) where T<:Number
if (m_max < 0) || (m_max > n_max)
m_max = n_max
end
# Check if we need to compute and additional degree in `P` to provide the desire order
# in `dP`.
if n_max == m_max
n_max_P = m_max_P = n_max
else
n_max_P = n_max
m_max_P = m_max + 1
end
# First, compute the matrix with the associated Legendre functions.
P = unnormalized_legendre(ϕ, n_max_P, m_max_P; ph_term = ph_term)
# Now, compute and return the derivative of the associated Legendre functions.
dP = zeros(float(T), n_max + 1, m_max + 1)
unnormalized_dlegendre!(dP, ϕ, P; ph_term = ph_term)
return dP, P
end
| SatelliteToolboxLegendre | https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl.git |
|
[
"MIT"
] | 1.0.3 | 5ff0e4fee0b4144ad3393177f449108cd07556d1 | code | 6325 | ## Description #############################################################################
#
# Compute the associated Legendre functions with full normalization.
#
## References ##############################################################################
#
# [1] Holmes, S. A. and W. E. Featherstone, 2002. A unified approach to the Clenshaw
# summation and the recursive computation of very high degree and order normalised
# associated Legendre functions. Journal of Geodesy, 76(5), pp. 279-299.
#
# For more info.: http://mitgcm.org/~mlosch/geoidcookbook/node11.html
#
# [2] Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications. Microcosm Press,
# Hawthorn, CA, USA.
#
############################################################################################
"""
fully_normalized_legendre!(P::AbstractMatrix{T}, ϕ::Number, n_max::Integer = -1, m_max::Integer = -1; kwargs...) where T<:Number -> Nothing
Compute the fully normalized associated Legendre function `P_n,m[cos(ϕ)]`. The maximum
degree and order that will be computed are given by the arguments `n_max` and `m_max`. If
they are negative (default), the dimensions of matrix `P` will be used:
maximum degree -> number of rows - 1
maximum order -> number of columns - 1
The result will be stored in the matrix `P`.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
# Remarks
This algorithm was based on **[1]**. Our definition of fully normalized associated Legendre
function can be seen in **[2, p. 546]**. The conversion is obtained by:
┌ ┐
│ (n-m)! . k . (2n+1) │
K_n,m = √│ ───────────────────── │, k = (m = 0) ? 1 : 2.
│ (n+m)! │
└ ┘
P̄_n,m = P_n,m * K_n,m,
where `P̄_n,m` is the fully normalized Legendre associated function.
# References
- **[1]** Holmes, S. A. and W. E. Featherstone, 2002. A unified approach to the Clenshaw
summation and the recursive computation of very high degree and order normalised
associated Legendre functions. Journal of Geodesy, 76(5), pp. 279-299. For more info.:
http://mitgcm.org/~mlosch/geoidcookbook/node11.html
- **[2]** Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications. Microcosm
Press, Hawthorn, CA, USA.
"""
function fully_normalized_legendre!(
P::AbstractMatrix{T},
ϕ::Number,
n_max::Integer = -1,
m_max::Integer = -1;
ph_term::Bool = false
) where T<:Number
# Obtain the maximum degree and order that must be computed.
n_max, m_max = _get_degree_and_order(P, n_max, m_max)
# Auxiliary variables to improve code performance.
s, c = sincos(T(ϕ))
# The sine must be always positive. In fact, `s` was previously computed using
# `√(1 - c^2)`. However, we had numerical problems for very small angles that lead to
# `cos(ϕ) = 1`.
if s < 0
s = -s
end
s_fact = !ph_term ? +s : -s
# Get the first indices in `P` to take into account offset arrays.
i₀, j₀ = first.(axes(P))
sq3 = √T(3)
@inbounds for n in 0:n_max
# Starting values.
if n == 0
P[i₀, j₀] = 1
continue
elseif n == 1
P[i₀+1, j₀] = +sq3 * c
if m_max > 0
P[i₀+1, j₀+1] = +sq3 * s_fact
end
continue
end
aux_an = T(2n - 1) * T(2n + 1)
aux_bn = T(2n + 1) / T(2n - 3)
for m in 0:n
if n == m
P[i₀+n, j₀+n] = s_fact * √(T(2n + 1) / T(2n)) * P[i₀+n-1, j₀+n-1]
else
aux_nm = T(n - m) * T(n + m)
a_nm = √(aux_an / aux_nm) * c
b_nm = √(T(n + m - 1) * T(n - m - 1) * aux_bn / aux_nm)
# We assume that the matrix is not initialized. Hence, we must not access
# elements on the upper triangle.
if m != n - 1
P[i₀+n, j₀+m] = a_nm * P[i₀+n-1, j₀+m] - b_nm * P[i₀+n-2, j₀+m]
else
P[i₀+n, j₀+m] = a_nm * P[i₀+n-1, j₀+m]
end
end
# Check if the maximum desired order has been reached.
m == m_max && break
end
end
return nothing
end
"""
fully_normalized_legendre!(ϕ::T, n_max::Integer, m_max::Integer = -1; kwargs...) where T<:Number -> Matrix{float(T)}
Compute the fully normalized associated Legendre function `P_n,m[cos(ϕ)]`. The maximum
degree that will be computed is `n_max` and the maximum order is `m_max`. Notice that if
`m_max` is higher than `n_max` or negative, it is set to `n_max`.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
# Returns
- `Matrix{float(T)}`: A matrix with the Legendre associated functions `P_n,m[cos(ϕ)]`.
# Remarks
This algorithm was based on **[1]**. Our definition of fully normalized associated Legendre
function can be seen in **[2, p. 546]**. The conversion is obtained by:
┌ ┐
│ (n-m)! . k . (2n+1) │
K_n,m = √│ ───────────────────── │, k = (m = 0) ? 1 : 2.
│ (n+m)! │
└ ┘
P̄_n,m = P_n,m * K_n,m,
where `P̄_n,m` is the fully normalized Legendre associated function.
# References
- **[1]** Holmes, S. A. and W. E. Featherstone, 2002. A unified approach to the Clenshaw
summation and the recursive computation of very high degree and order normalised
associated Legendre functions. Journal of Geodesy, 76(5), pp. 279-299. For more info.:
http://mitgcm.org/~mlosch/geoidcookbook/node11.html
- **[2]** Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications. Microcosm
Press, Hawthorn, CA, USA.
"""
function fully_normalized_legendre(
ϕ::T,
n_max::Integer,
m_max::Integer = -1;
ph_term::Bool = false
) where T<:Number
n_max < 0 && throw(ArgumentError("n_max must be positive."))
if (m_max < 0) || (m_max > n_max)
m_max = n_max
end
P = zeros(float(T), n_max + 1, m_max + 1)
fully_normalized_legendre!(P, ϕ; ph_term = ph_term)
return P
end
| SatelliteToolboxLegendre | https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl.git |
|
[
"MIT"
] | 1.0.3 | 5ff0e4fee0b4144ad3393177f449108cd07556d1 | code | 7518 | ## Description #############################################################################
#
# Functions related to the associated Legendre functions.
#
## References ##############################################################################
#
# [1] Holmes, S. A. and W. E. Featherstone, 2002. A unified approach to the Clenshaw
# summation and the recursive computation of very high degree and order normalised
# associated Legendre functions. Journal of Geodesy, 76(5), pp. 279-299.
#
# For more info.: http://mitgcm.org/~mlosch/geoidcookbook/node11.html
#
# [2] Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications. Microcosm Press,
# Hawthorn, CA, USA.
#
# [3] Schmidt, A (1917). Erdmagnetismus, Enzykl. Math. Wiss., 6, pp. 265–396.
#
# [4] Winch, D. E., Ivers, D. J., Turner, J. P. R., Stening R. J (2005). Geomagnetism and
# Schmidt quasi-normalization. Geophysical Journal International, 160(2), pp. 487-504.
#
############################################################################################
export legendre!, legendre
"""
legendre!(N, P::AbstractMatrix, ϕ::Number, n_max::Integer = -1, m_max::Integer = -1; kwargs...) -> Nothing
Compute the associated Legendre function `P_n,m[cos(ϕ)]`. The maximum degree and order that
will be computed are given by the parameters `n_max` and `m_max`. If they are negative
(default), the dimensions of matrix `P` will be used:
maximum degree -> number of rows - 1
maximum order -> number of columns - 1
The result will be stored at matrix `P`.
The parameter `N` selects the normalization. The following values are valid:
- `Val(:full)`: Compute the fully normalized associated Legendre function.
- `Val(:schmidt)`: Compute the Schmidt quasi-normalized associated Legendre function.
- `Val(:unnormalized)`: Compute the unnormalized associated Legendre function.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
# Remarks
## Full normalization
This algorithm was based on **[1]**. Our definition of fully normalized associated Legendre
function can be seen in **[2, p. 546]**. The conversion is obtained by:
┌ ┐
│ (n-m)! . k . (2n+1) │
K_n,m = √│ ───────────────────── │, k = (m = 0) ? 1 : 2.
│ (n+m)! │
└ ┘
P̄_n,m = P_n,m * K_n,m,
where `P̄_n,m` is the fully normalized Legendre associated function.
## Schmidt quasi-normalization
This algorithm was based on **[3, 4]**. The conversion is obtained by:
┌ ┐
│ (n-m)! │
K_n,m = √│ k . ──────── │, k = (m = 0) ? 1 : 2.
│ (n+m)! │
└ ┘
P̂_n,m = P_n,m * K_n,m,
where `P̂_n,m` is the Schmidt quasi-normalized Legendre associated function.
# References
- **[1]** Holmes, S. A. and W. E. Featherstone, 2002. A unified approach to the Clenshaw
summation and the recursive computation of very high degree and order normalised
associated Legendre functions. Journal of Geodesy, 76(5), pp. 279-299. For more info.:
http://mitgcm.org/~mlosch/geoidcookbook/node11.html
- **[2]** Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications. Microcosm
Press, Hawthorn, CA, USA.
- **[3]** Schmidt, A (1917). Erdmagnetismus, Enzykl. Math. Wiss., 6, pp. 265–396.
- **[4]** Winch, D. E., Ivers, D. J., Turner, J. P. R., Stening R. J (2005). Geomagnetism
and Schmidt quasi-normalization. Geophysical Journal International, 160(2), pp. 487-504.
"""
function legendre!(
::Val{:full},
P::AbstractMatrix,
ϕ::Number,
n_max::Integer = -1,
m_max::Integer = -1;
ph_term::Bool = false
)
return fully_normalized_legendre!(P, ϕ, n_max, m_max; ph_term = ph_term)
end
function legendre!(
::Val{:schmidt},
P::AbstractMatrix,
ϕ::Number,
n_max::Integer = -1,
m_max::Integer = -1;
ph_term::Bool = false
)
return schmidt_quasi_normalized_legendre!(P, ϕ, n_max, m_max; ph_term = ph_term)
end
function legendre!(
::Val{:unnormalized},
P::AbstractMatrix,
ϕ::Number,
n_max::Integer = -1,
m_max::Integer = -1;
ph_term::Bool = false
)
return unnormalized_legendre!(P, ϕ, n_max, m_max; ph_term = ph_term)
end
"""
legendre(N, ϕ::T, n_max::Integer, m_max::Integer = -1; ph_term::Bool = false) where T<:Number -> Matrix{float(T)}
Compute the associated Legendre function `P_n,m[cos(ϕ)]`. The maximum degree that will be
computed is `n_max` and the maximum order is `m_max`. Notice that if `m_max` is higher than
`n_max` or negative (default), it is set to `n_max`.
The parameter `N` selects the normalization. The following values are valid:
- `Val(:full)`: Compute the fully normalized associated Legendre function.
- `Val(:schmidt)`: Compute the Schmidt quasi-normalized associated Legendre function.
- `Val(:unnormalized)`: Compute the unnormalized associated Legendre function.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
# Returns
- `Matrix{float(T)}`: A matrix with the Legendre associated functions `P_n,m[cos(ϕ)]`.
# Remarks
## Full normalization
This algorithm was based on **[1]**. Our definition of fully normalized associated Legendre
function can be seen in **[2, p. 546]**. The conversion is obtained by:
┌ ┐
│ (n-m)! . k . (2n+1) │
K_n,m = √│ ───────────────────── │, k = (m = 0) ? 1 : 2.
│ (n+m)! │
└ ┘
P̄_n,m = P_n,m * K_n,m,
where `P̄_n,m` is the fully normalized Legendre associated function.
## Schmidt quasi-normalization
This algorithm was based on **[3, 4]**. The conversion is obtained by:
┌ ┐
│ (n-m)! │
K_n,m = √│ k . ──────── │, k = (m = 0) ? 1 : 2.
│ (n+m)! │
└ ┘
P̂_n,m = P_n,m * K_n,m,
where `P̂_n,m` is the Schmidt quasi-normalized Legendre associated function.
# References
- **[1]** Holmes, S. A. and W. E. Featherstone, 2002. A unified approach to the Clenshaw
summation and the recursive computation of very high degree and order normalised
associated Legendre functions. Journal of Geodesy, 76(5), pp. 279-299. For more info.:
http://mitgcm.org/~mlosch/geoidcookbook/node11.html
- **[2]** Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications. Microcosm
Press, Hawthorn, CA, USA.
- **[3]** Schmidt, A (1917). Erdmagnetismus, Enzykl. Math. Wiss., 6, pp. 265–396.
- **[4]** Winch, D. E., Ivers, D. J., Turner, J. P. R., Stening R. J (2005). Geomagnetism
and Schmidt quasi-normalization. Geophysical Journal International, 160(2), pp. 487-504.
"""
function legendre(
::Val{:full},
ϕ::Number,
n_max::Integer,
m_max::Integer = -1;
ph_term::Bool = false
)
return fully_normalized_legendre(ϕ, n_max, m_max; ph_term = ph_term)
end
function legendre(
::Val{:schmidt},
ϕ::Number,
n_max::Integer,
m_max::Integer = -1;
ph_term::Bool = false
)
return schmidt_quasi_normalized_legendre(ϕ, n_max, m_max; ph_term = ph_term)
end
function legendre(
::Val{:unnormalized},
ϕ::Number,
n_max::Integer,
m_max::Integer = -1;
ph_term::Bool = false
)
return unnormalized_legendre(ϕ, n_max, m_max; ph_term = ph_term)
end
| SatelliteToolboxLegendre | https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl.git |
|
[
"MIT"
] | 1.0.3 | 5ff0e4fee0b4144ad3393177f449108cd07556d1 | code | 5589 | ## Description #############################################################################
#
# Compute the associated Legendre functions with the Schmidt quasi-normalization.
#
## References ##############################################################################
#
# [1] Schmidt, A (1917). Erdmagnetismus, Enzykl. Math. Wiss., 6, pp. 265–396.
#
# [2] Winch, D. E., Ivers, D. J., Turner, J. P. R., Stening R. J (2005). Geomagnetism and
# Schmidt quasi-normalization. Geophysical Journal International, 160(2), pp. 487-504.
#
############################################################################################
"""
schmidt_quasi_normalized_legendre!(P::AbstractMatrix{T}, ϕ::Number, n_max::Integer = -1, m_max::Integer = -1; kwargs...) where T<:Number -> Nothing
Compute the Schmidt quasi-normalized associated Legendre function `P_n,m[cos(ϕ)]`
**[1, 2]**. The maximum degree and order that will be computed are given by the parameters
`n_max` and `m_max`. If they are negative (default), the dimensions of matrix `P` will be
used:
maximum degree -> number of rows - 1
maximum order -> number of columns - 1
The result will be stored at matrix `P`.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
# Remarks
This algorithm was based on **[1, 2]**. The conversion is obtained by:
┌ ┐
│ (n-m)! │
K_n,m = √│ k . ──────── │, k = (m = 0) ? 1 : 2.
│ (n+m)! │
└ ┘
P̂_n,m = P_n,m * K_n,m,
where `P̂_n,m` is the Schmidt quasi-normalized Legendre associated function.
# References
- **[1]** Schmidt, A (1917). Erdmagnetismus, Enzykl. Math. Wiss., 6, pp. 265–396.
- **[2]** Winch, D. E., Ivers, D. J., Turner, J. P. R., Stening R. J (2005). Geomagnetism
and Schmidt quasi-normalization. Geophysical Journal International, 160(2), pp. 487-504.
"""
function schmidt_quasi_normalized_legendre!(
P::AbstractMatrix{T},
ϕ::Number,
n_max::Integer = -1,
m_max::Integer = -1;
ph_term::Bool = false
) where T<:Number
# Obtain the maximum degree and order that must be computed.
n_max, m_max = _get_degree_and_order(P, n_max, m_max)
# Auxiliary variables to improve code performance.
s, c = sincos(T(ϕ))
# The sine must be always positive. In fact, `s` was previously computed using
# `√(1 - c^2)`. However, we had numerical problems for very small angles that lead to
# `cos(ϕ) = 1`.
if (s < 0)
s = -s
end
s_fact = !ph_term ? +s : -s
# Get the first indices in `P` to take into account offset arrays.
i₀, j₀ = first.(axes(P))
@inbounds for n in 0:n_max
# Starting values.
if n == 0
P[i₀, j₀] = 1
continue
elseif n == 1
P[i₀+1, j₀] = +c
if m_max > 0
P[i₀+1, j₀+1] = +s_fact
end
continue
end
aux_n = T(2n - 1) # ......................................... √((2n - 1) * (2n - 1))
for m in 0:n
if m == n
P[i₀+n, j₀+n] = s_fact * √(aux_n / T(2n)) * P[i₀+n-1, j₀+n-1]
else
aux_nm = √(T(n - m) * T(n + m))
a_nm = aux_n / aux_nm * c
b_nm = √(T(n + m - 1) * T(n - m - 1)) / aux_nm
# We assume that the matrix is not initialized. Hence, we must not access
# elements on the upper triangle.
if m != n - 1
P[i₀+n, j₀+m] = a_nm * P[i₀+n-1, j₀+m] - b_nm * P[i₀+n-2, j₀+m]
else
P[i₀+n, j₀+m] = a_nm * P[i₀+n-1, j₀+m]
end
end
# Check if the maximum desired order has been reached.
m == m_max && break
end
end
return nothing
end
"""
schmidt_quasi_normalized_legendre(ϕ::T, n_max::Integer = -1, m_max::Integer = -1; kwargs...) where T<:Number -> Matrix{float(T)}
Compute the Schmidt quasi-normalized associated Legendre function `P_n,m[cos(ϕ)]`. The
maximum degree that will be computed is `n_max` and the maximum order is `m_max`. Notice
that if `m_max` is higher than `n_max` or negative, it is set to `n_max`.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
# Returns
- `Matrix{float(T)}`: A matrix with the Legendre associated functions `P_n,m[cos(ϕ)]`.
# Remarks
This algorithm was based on **[1, 2]**. The conversion is obtained by:
┌ ┐
│ (n-m)! │
K_n,m = √│ k . ──────── │, k = (m = 0) ? 1 : 2.
│ (n+m)! │
└ ┘
P̂_n,m = P_n,m * K_n,m,
where `P̂_n,m` is the Schmidt quasi-normalized Legendre associated function.
# References
- **[1]** Schmidt, A (1917). Erdmagnetismus, Enzykl. Math. Wiss., 6, pp. 265–396.
- **[2]** Winch, D. E., Ivers, D. J., Turner, J. P. R., Stening R. J (2005). Geomagnetism
and Schmidt quasi-normalization. Geophysical Journal International, 160(2), pp. 487-504.
"""
function schmidt_quasi_normalized_legendre(
ϕ::T,
n_max::Integer = -1,
m_max::Integer = -1;
ph_term::Bool = false
) where T<:Number
n_max < 0 && throw(ArgumentError("n_max must be positive."))
if (m_max < 0) || (m_max > n_max)
m_max = n_max
end
P = zeros(float(T), n_max + 1, m_max + 1)
schmidt_quasi_normalized_legendre!(P, ϕ; ph_term = ph_term)
return P
end
| SatelliteToolboxLegendre | https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl.git |
|
[
"MIT"
] | 1.0.3 | 5ff0e4fee0b4144ad3393177f449108cd07556d1 | code | 4454 | ## Description #############################################################################
#
# Compute the associated Legendre functions without normalization.
#
## References ##############################################################################
#
# [1] Holmes, S. A. and W. E. Featherstone, 2002. A unified approach to the Clenshaw
# summation and the recursive computation of very high degree and order normalised
# associated Legendre functions. Journal of Geodesy, 76(5), pp. 279-299.
#
# For more info.: http://mitgcm.org/~mlosch/geoidcookbook/node11.html
#
# [2] Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications. Microcosm Press,
# Hawthorn, CA, USA.
#
############################################################################################
"""
unnormalized_legendre!(P::AbstractMatrix{T}, ϕ::Number, n_max::Integer = -1, m_max::Integer = -1; kwargs...) where T<:Number -> Nothing
Compute the unnormalized (or conventional) associated Legendre function `P_n,m[cos(ϕ)]`. The
maximum degree and order that will be computed are given by the parameters `n_max` and
`m_max`. If they are negative (default), the dimensions of matrix `P` will be used:
maximum degree -> number of rows - 1
maximum order -> number of columns - 1
The result will be stored at matrix `P`.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
"""
function unnormalized_legendre!(
P::AbstractMatrix{T},
ϕ::Number,
n_max::Integer = -1,
m_max::Integer = -1;
ph_term::Bool = false
) where T<:Number
# Obtain the maximum degree and order that must be computed.
n_max, m_max = _get_degree_and_order(P, n_max, m_max)
# Auxiliary variables to improve code performance.
s, c = sincos(T(ϕ))
# The sine must be always positive. In fact, `s` was previously computed using
# `√(1 - c^2)`. However, we had numerical problems for very small angles that lead to
# `cos(ϕ) = 1`.
if s < 0
s = -s
end
s_fact = !ph_term ? +s : -s
# Get the first indices in `P` to take into account offset arrays.
i₀, j₀ = first.(axes(P))
@inbounds for n in 0:n_max
# Starting values.
if n == 0
P[i₀, j₀] = 1
continue
elseif n == 1
P[i₀+1, j₀] = +c
if m_max > 0
P[i₀+1, j₀+1] = +s_fact
end
continue
end
aux_n = T(2n - 1) # ......................................... √((2n - 1) * (2n - 1))
for m in 0:n
if n == m
P[i₀+n, j₀+n] = s_fact * aux_n * P[i₀+n-1, j₀+n-1]
else
aux_nm = T(n - m) # ...................... √((n - m) * (n - m))
a_nm = aux_n / aux_nm * c
b_nm = T(n + m - 1) / aux_nm # ..... √((n + m - 1) * (n + m - 1)) / aux_nm
# We assume that the matrix is not initialized. Hence, we must
# not access elements on the upper triangle.
if m != n-1
P[i₀+n, j₀+m] = a_nm * P[i₀+n-1, j₀+m] - b_nm * P[i₀+n-2, j₀+m]
else
P[i₀+n, j₀+m] = a_nm * P[i₀+n-1, j₀+m]
end
end
# Check if the maximum desired order has been reached.
m == m_max && break
end
end
return nothing
end
"""
unnormalized_legendre(ϕ::T, n_max::Integer, m_max::Integer = -1; kwargs...) where T<:Number -> Matrix{float(T)}
Compute the unnormalized (or conventional) associated Legendre function `P_n,m[cos(ϕ)]`. The
maximum degree that will be computed is `n_max` and the maximum order is `m_max`. Notice
that if `m_max` is higher than `n_max` or negative, it is set to `n_max`.
# Keywords
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term `(-1)^m` will be included.
(**Default** = `false`)
# Returns
- `Matrix{float(T)}`: A matrix with the Legendre associated functions `P_n,m[cos(ϕ)]`.
"""
function unnormalized_legendre(
ϕ::T,
n_max::Integer,
m_max::Integer = -1;
ph_term::Bool = false
) where T<:Number
n_max < 0 && throw(ArgumentError("n_max must be positive."))
if (m_max < 0) || (m_max > n_max)
m_max = n_max
end
P = zeros(float(T), n_max + 1, m_max + 1)
unnormalized_legendre!(P, ϕ; ph_term = ph_term)
return P
end
| SatelliteToolboxLegendre | https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl.git |
|
[
"MIT"
] | 1.0.3 | 5ff0e4fee0b4144ad3393177f449108cd07556d1 | code | 13478 | ## Description #############################################################################
#
# Tests related to the functions to create the matrices with the values of the Legendre
# associated function derivatives.
#
############################################################################################
# == File: ./src/dlegendre.jl ==============================================================
# -- Functions: dlegendre and dlegendre! ---------------------------------------------------
@testset "Unnormalized" begin
# == Float64 ===========================================================================
# -- Default ---------------------------------------------------------------------------
expected = [
0.0 0.0 0.0 0.0
-0.12269009002431533 0.9924450321351935 0.0 0.0
-0.36528951101055424 2.909682850858952 0.7305790220211085 0.0
-0.7222892661973235 5.618539670379986 3.5975950570380495 0.6722610448623454
]
result, ~ = dlegendre(Val(:unnormalized), 0.123, 3)
@test result ≈ expected
@test eltype(result) == Float64
# -- Order Higher than Degree ----------------------------------------------------------
result, ~ = dlegendre(Val(:unnormalized), 0.123, 3, 5)
@test result ≈ expected
@test eltype(result) == Float64
# -- Order Lower than Degree -----------------------------------------------------------
expected_dP = [
0.0 0.0
-0.12269009002431533 0.9924450321351935
-0.36528951101055424 2.909682850858952
-0.7222892661973235 5.618539670379986
]
expected_P = [
1.0 0.0 0.0
0.9924450321351935 0.12269009002431533 0.0
0.9774207127147378 0.36528951101055424 0.0451585745705238
0.9550971963095074 0.7222892661973235 0.22408701495411515
]
result_dP, result_P = dlegendre(Val(:unnormalized), 0.123, 3, 1)
@test result_dP ≈ expected_dP
@test result_P ≈ expected_P
@test eltype(result_dP) == Float64
@test eltype(result_P) == Float64
# -- Angle with Negative Sine ----------------------------------------------------------
expected = [
0.0 0.0 0.0 0.0
0.9589242746631385 -0.28366218546322625 0.0 0.0
0.8160316663340547 2.517214587229357 -1.6320633326681093 0.0
-0.8596930972959173 4.166871190282159 10.911704231754335 -11.737688606123031
]
result, ~ = dlegendre(Val(:unnormalized), 5, 3)
@test result ≈ expected
@test eltype(result) == Float64
# -- Phase Term ------------------------------------------------------------------------
expected = [
0.0 0.0 0.0 0.0
-0.12269009002431533 -0.9924450321351935 0.0 0.0
-0.36528951101055424 -2.909682850858952 0.7305790220211085 0.0
-0.7222892661973235 -5.618539670379986 3.5975950570380495 -0.6722610448623454
]
result, ~ = dlegendre(Val(:unnormalized), 0.123, 3; ph_term = true)
@test result ≈ expected
@test eltype(result) == Float64
# -- In-Place --------------------------------------------------------------------------
expected = [
0.0 0.0 0.0 0.0
-0.12269009002431533 0.9924450321351935 0.0 0.0
-0.36528951101055424 2.909682850858952 0.0 0.0
-0.7222892661973235 5.618539670379986 0.0 0.0
]
P = legendre(Val(:unnormalized), 0.123, 3, 2)
result = zeros(Float64, 4, 4)
dlegendre!(Val(:unnormalized), result, 0.123, P, 3, 1)
@test result ≈ expected
@test eltype(result) == Float64
expected = [
0.0 0.0 0.0 0.0
-0.12269009002431533 0.9924450321351935 0.0 0.0
-0.36528951101055424 2.909682850858952 0.7305790220211085 0.0
-0.7222892661973235 5.618539670379986 3.5975950570380495 0.6722610448623454
]
P = legendre(Val(:unnormalized), 0.123, 4, 4)
result = zeros(Float64, 4, 4)
dlegendre!(Val(:unnormalized), result, 0.123, P, 10, 20)
@test result ≈ expected
@test eltype(result) == Float64
# == Float32 ===========================================================================
expected = Float32[
0.0 0.0 0.0 0.0
-0.1226901 0.99244505 0.0 0.0
-0.36528954 2.9096832 0.7305791 0.0
-0.7222893 5.618541 3.5975955 0.6722612
]
result, ~ = dlegendre(Val(:unnormalized), 0.123f0, 3)
@test result ≈ expected
@test eltype(result) == Float32
end
@testset "Schmidt Quasi-Normalization" begin
# == Float64 ===========================================================================
# -- Default ---------------------------------------------------------------------------
expected = [
0.0 0.0 0.0 0.0
-0.12269009002431533 0.9924450321351935 0.0 0.0
-0.36528951101055424 1.6799061771998531 0.21089999751409028 0.0
-0.7222892661973236 2.293759215336026 0.46444752474354967 0.03543126806616079
]
result, ~ = dlegendre(Val(:schmidt), 0.123, 3)
@test result ≈ expected
@test eltype(result) == Float64
# -- Order Higher than Degree ----------------------------------------------------------
result, ~ = dlegendre(Val(:schmidt), 0.123, 3, 5)
@test result ≈ expected
@test eltype(result) == Float64
# -- Order Lower than Degree -----------------------------------------------------------
expected_dP = [
0.0 0.0
-0.12269009002431533 0.9924450321351935
-0.36528951101055424 1.6799061771998531
-0.7222892661973236 2.293759215336026
]
expected_P = [
1.0 0.0 0.0
0.9924450321351935 0.12269009002431533 0.0
0.9774207127147378 0.21089999751409028 0.013036157592255852
0.9550971963095074 0.29487335814545546 0.028929509233954008
]
result_dP, result_P = dlegendre(Val(:schmidt), 0.123, 3, 1)
@test result_dP ≈ expected_dP
@test result_P ≈ expected_P
@test eltype(result_dP) == Float64
@test eltype(result_P) == Float64
# -- Angle with Negative Sine ----------------------------------------------------------
expected = [
0.0 0.0 0.0 0.0
0.9589242746631385 -0.28366218546322625 0.0 0.0
0.8160316663340547 1.453314519544922 -0.47113610222522534 0.0
-0.8596930972959171 1.7011180400158135 1.4086949589441842 -0.6186305076859298
]
result, ~ = dlegendre(Val(:schmidt), 5, 3)
@test result ≈ expected
@test eltype(result) == Float64
# -- Phase Term ------------------------------------------------------------------------
expected = [
0.0 0.0 0.0 0.0
-0.12269009002431533 -0.9924450321351935 0.0 0.0
-0.36528951101055424 -1.6799061771998531 0.21089999751409028 0.0
-0.7222892661973236 -2.293759215336026 0.46444752474354967 -0.03543126806616079
]
result, ~ = dlegendre(Val(:schmidt), 0.123, 3; ph_term = true)
@test result ≈ expected
@test eltype(result) == Float64
# -- In-Place --------------------------------------------------------------------------
expected = [
0.0 0.0 0.0 0.0
-0.12269009002431533 0.9924450321351935 0.0 0.0
-0.36528951101055424 1.6799061771998531 0.0 0.0
-0.7222892661973236 2.293759215336026 0.0 0.0
]
P = legendre(Val(:schmidt), 0.123, 3, 2)
result = zeros(Float64, 4, 4)
dlegendre!(Val(:schmidt), result, 0.123, P, 3, 1)
@test result ≈ expected
@test eltype(result) == Float64
expected = [
0.0 0.0 0.0 0.0
-0.12269009002431533 0.9924450321351935 0.0 0.0
-0.36528951101055424 1.6799061771998531 0.21089999751409028 0.0
-0.7222892661973236 2.293759215336026 0.46444752474354967 0.03543126806616079
]
P = legendre(Val(:schmidt), 0.123, 4, 4)
result = zeros(Float64, 4, 4)
dlegendre!(Val(:schmidt), result, 0.123, P, 10, 20)
@test result ≈ expected
@test eltype(result) == Float64
# == Float32 ===========================================================================
expected = Float32[
0.0 0.0 0.0 0.0
-0.1226901 0.99244505 0.0 0.0
-0.36528954 1.6799064 0.21090002 0.0
-0.7222894 2.2937596 0.46444756 0.035431273
]
result, ~ = dlegendre(Val(:schmidt), 0.123f0, 3)
@test result ≈ expected
@test eltype(result) == Float32
end
@testset "Full Normalization" begin
# == Float64 ===========================================================================
# -- Default ---------------------------------------------------------------------------
expected = [
0.0 0.0 0.0 0.0
-0.2125054695073136 1.7189652193774823 0.0 0.0
-0.816812178087257 3.7563844080406796 0.4715867308960424 0.0
-1.9109977730094496 6.068716451241777 1.2288126475109502 0.09374232393872588
]
result, ~ = dlegendre(Val(:full), 0.123, 3)
@test result ≈ expected
@test eltype(result) == Float64
# -- Order Higher than Degree ----------------------------------------------------------
result, ~ = dlegendre(Val(:full), 0.123, 3, 5)
@test result ≈ expected
@test eltype(result) == Float64
# -- Order Lower than Degree -----------------------------------------------------------
expected_dP = [
0.0 0.0
-0.2125054695073136 1.7189652193774823
-0.816812178087257 3.7563844080406796
-1.9109977730094496 6.068716451241777
]
expected_P = [
1.0 0.0 0.0
1.7189652193774823 0.2125054695073136 0.0
2.185579156246447 0.4715867308960424 0.029149734541684073
2.526949659329994 0.7801615739113572 0.07654028698418901
]
result_dP, result_P = dlegendre(Val(:full), 0.123, 3, 1)
@test result_dP ≈ expected_dP
@test result_P ≈ expected_P
@test eltype(result_dP) == Float64
@test eltype(result_P) == Float64
# -- Angle with Negative Sine ----------------------------------------------------------
expected = [
0.0 0.0 0.0 0.0
1.6609055643276887 -0.4913173174083336 0.0 0.0
1.8247022777153725 3.2497100583898924 -1.0534923512298937 0.0
-2.2745341392838507 4.500735284647465 3.727056534516655 -1.6367424767746024
]
result, ~ = dlegendre(Val(:full), 5, 3)
@test result ≈ expected
@test eltype(result) == Float64
# -- Phase Term ------------------------------------------------------------------------
expected = [
0.0 0.0 0.0 0.0
-0.2125054695073136 -1.7189652193774823 0.0 0.0
-0.816812178087257 -3.7563844080406796 0.4715867308960424 0.0
-1.9109977730094496 -6.068716451241777 1.2288126475109502 -0.09374232393872588
]
result, ~ = dlegendre(Val(:full), 0.123, 3; ph_term = true)
@test result ≈ expected
@test eltype(result) == Float64
# -- In-Place --------------------------------------------------------------------------
expected = [
0.0 0.0 0.0 0.0
-0.2125054695073136 1.7189652193774823 0.0 0.0
-0.816812178087257 3.7563844080406796 0.0 0.0
-1.9109977730094496 6.068716451241777 0.0 0.0
]
P = legendre(Val(:full), 0.123, 3, 2)
result = zeros(Float64, 4, 4)
dlegendre!(Val(:full), result, 0.123, P, 3, 1)
@test result ≈ expected
@test eltype(result) == Float64
expected = [
0.0 0.0 0.0 0.0
-0.2125054695073136 1.7189652193774823 0.0 0.0
-0.816812178087257 3.7563844080406796 0.4715867308960424 0.0
-1.9109977730094496 6.068716451241777 1.2288126475109502 0.09374232393872588
]
P = legendre(Val(:full), 0.123, 4, 4)
result = zeros(Float64, 4, 4)
dlegendre!(Val(:full), result, 0.123, P, 10, 20)
@test result ≈ expected
@test eltype(result) == Float64
# == Float32 ===========================================================================
expected = Float32[
0.0 0.0 0.0 0.0
-0.21250547 1.7189652 0.0 0.0
-0.8168122 3.7563846 0.47158676 0.0
-1.910998 6.0687184 1.2288128 0.09374233
]
result, ~ = dlegendre(Val(:full), 0.123f0, 3)
@test result ≈ expected
@test eltype(result) == Float32
end
@testset "Errors" begin
@test_throws ArgumentError dlegendre(Val(:unnormalized), 0.123, -2)
@test_throws ArgumentError dlegendre(Val(:schmidt), 0.123, -2)
@test_throws ArgumentError dlegendre(Val(:full), 0.123, -2)
end
| SatelliteToolboxLegendre | https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl.git |
|
[
"MIT"
] | 1.0.3 | 5ff0e4fee0b4144ad3393177f449108cd07556d1 | code | 11799 | ## Description #############################################################################
#
# Tests related to the functions to create the matrices with the values of the Legendre
# associated functions.
#
############################################################################################
# == File: ./src/legendre.jl ===============================================================
# -- Functions: legendre and legendre! -----------------------------------------------------
@testset "Unnormalized" begin
# == Float64 ===========================================================================
# -- Default ---------------------------------------------------------------------------
expected = [
1.0 0.0 0.0 0.0
0.9924450321351935 0.12269009002431533 0.0 0.0
0.9774207127147378 0.36528951101055424 0.0451585745705238 0.0
0.9550971963095074 0.7222892661973235 0.22408701495411515 0.02770254789713661
]
result = legendre(Val(:unnormalized), 0.123, 3)
@test result ≈ expected
@test eltype(result) == Float64
# -- Order Higher than Degree ----------------------------------------------------------
result = legendre(Val(:unnormalized), 0.123, 3, 5)
@test result ≈ expected
@test eltype(result) == Float64
# -- Order Lower than Degree -----------------------------------------------------------
expected = [
1.0 0.0
0.9924450321351935 0.12269009002431533
0.9774207127147378 0.36528951101055424
0.9550971963095074 0.7222892661973235
]
result = legendre(Val(:unnormalized), 0.123, 3, 1)
@test result ≈ expected
@test eltype(result) == Float64
# -- Angle with Negative Sine ----------------------------------------------------------
expected = [
1.0 0.0 0.0 0.0
0.28366218546322625 0.9589242746631385 0.0 0.0
-0.37930364680733936 0.8160316663340547 2.7586072936146784 0.0
-0.36843162598805346 -0.8596930972959173 3.912562868707677 13.226477490549495
]
result = legendre(Val(:unnormalized), 5, 3)
@test result ≈ expected
@test eltype(result) == Float64
# -- Phase Term ------------------------------------------------------------------------
expected = [
1.0 0.0 0.0 0.0
0.9924450321351935 -0.12269009002431533 0.0 0.0
0.9774207127147378 -0.36528951101055424 0.0451585745705238 0.0
0.9550971963095074 -0.7222892661973235 0.22408701495411515 -0.02770254789713661
]
result = legendre(Val(:unnormalized), 0.123, 3; ph_term = true)
@test result ≈ expected
@test eltype(result) == Float64
# -- In-Place --------------------------------------------------------------------------
expected = [
1.0 0.0 0.0 0.0
0.9924450321351935 0.12269009002431533 0.0 0.0
0.9774207127147378 0.36528951101055424 0.0 0.0
0.9550971963095074 0.7222892661973235 0.0 0.0
]
result = zeros(Float64, 4, 4)
legendre!(Val(:unnormalized), result, 0.123, 3, 1)
@test result ≈ expected
expected = [
1.0 0.0 0.0 0.0
0.9924450321351935 0.12269009002431533 0.0 0.0
0.9774207127147378 0.36528951101055424 0.0451585745705238 0.0
0.9550971963095074 0.7222892661973235 0.22408701495411515 0.02770254789713661
]
result = zeros(Float64, 4, 4)
legendre!(Val(:unnormalized), result, 0.123, 10, 20)
@test result ≈ expected
# == Float32 ===========================================================================
expected = Float32[
1.0 0.0 0.0 0.0
0.99244505 0.1226901 0.0 0.0
0.9774208 0.36528954 0.04515858 0.0
0.9550973 0.7222893 0.22408706 0.027702551
]
result = legendre(Val(:unnormalized), 0.123f0, 3)
@test result ≈ expected
@test eltype(result) == Float32
end
@testset "Schmidt Quasi-Normalization" begin
# == Float64 ===========================================================================
# -- Default ---------------------------------------------------------------------------
expected = [
1.0 0.0 0.0 0.0
0.9924450321351935 0.12269009002431533 0.0 0.0
0.9774207127147378 0.21089999751409028 0.013036157592255852 0.0
0.9550971963095074 0.29487335814545546 0.028929509233954008 0.001460052472414327
]
result = legendre(Val(:schmidt), 0.123, 3)
@test result ≈ expected
@test eltype(result) == Float64
# -- Order Higher than Degree ----------------------------------------------------------
result = legendre(Val(:schmidt), 0.123, 3, 5)
@test result ≈ expected
@test eltype(result) == Float64
# -- Order Lower than Degree -----------------------------------------------------------
expected = [
1.0 0.0
0.9924450321351935 0.12269009002431533
0.9774207127147378 0.21089999751409028
0.9550971963095074 0.29487335814545546
]
result = legendre(Val(:schmidt), 0.123, 3, 1)
@test result ≈ expected
@test eltype(result) == Float64
# -- Angle with Negative Sine ----------------------------------------------------------
expected = [
1.0 0.0 0.0 0.0
0.28366218546322625 0.9589242746631385 0.0 0.0
-0.37930364680733936 0.47113610222522534 0.7963413317784498 0.0
-0.36843162598805346 -0.35096823729464166 0.505109694383145 0.6970965715180766
]
result = legendre(Val(:schmidt), 5, 3)
@test result ≈ expected
@test eltype(result) == Float64
# -- Phase Term ------------------------------------------------------------------------
expected = [
1.0 0.0 0.0 0.0
0.9924450321351935 -0.12269009002431533 0.0 0.0
0.9774207127147378 -0.21089999751409028 0.013036157592255852 0.0
0.9550971963095074 -0.29487335814545546 0.028929509233954008 -0.001460052472414327
]
result = legendre(Val(:schmidt), 0.123, 3; ph_term = true)
@test result ≈ expected
@test eltype(result) == Float64
# -- In-Place --------------------------------------------------------------------------
expected = [
1.0 0.0 0.0 0.0
0.9924450321351935 0.12269009002431533 0.0 0.0
0.9774207127147378 0.21089999751409028 0.0 0.0
0.9550971963095074 0.29487335814545546 0.0 0.0
]
result = zeros(Float64, 4, 4)
legendre!(Val(:schmidt), result, 0.123, 3, 1)
@test result ≈ expected
expected = [
1.0 0.0 0.0 0.0
0.9924450321351935 0.12269009002431533 0.0 0.0
0.9774207127147378 0.21089999751409028 0.013036157592255852 0.0
0.9550971963095074 0.29487335814545546 0.028929509233954008 0.001460052472414327
]
result = zeros(Float64, 4, 4)
legendre!(Val(:schmidt), result, 0.123, 10, 20)
@test result ≈ expected
# == Float32 ===========================================================================
expected = Float32[
1.0 0.0 0.0 0.0
0.99244505 0.1226901 0.0 0.0
0.9774208 0.21090002 0.013036159 0.0
0.9550973 0.2948734 0.028929513 0.0014600528
]
result = legendre(Val(:schmidt), 0.123f0, 3)
@test result ≈ expected
@test eltype(result) == Float32
end
@testset "Full Normalization" begin
# == Float64 ===========================================================================
# -- Default ---------------------------------------------------------------------------
expected = [
1.0 0.0 0.0 0.0
1.7189652193774823 0.2125054695073136 0.0 0.0
2.185579156246447 0.4715867308960424 0.029149734541684073 0.0
2.526949659329994 0.7801615739113572 0.07654028698418901 0.003862935743113303
]
result = legendre(Val(:full), 0.123, 3)
@test result ≈ expected
@test eltype(result) == Float64
# -- Order Higher than Degree ----------------------------------------------------------
result = legendre(Val(:full), 0.123, 3, 5)
@test result ≈ expected
@test eltype(result) == Float64
# -- Order Lower than Degree -----------------------------------------------------------
expected = [
1.0 0.0
1.7189652193774823 0.2125054695073136
2.185579156246447 0.4715867308960424
2.526949659329994 0.7801615739113572
]
result = legendre(Val(:full), 0.123, 3, 1)
@test result ≈ expected
@test eltype(result) == Float64
# -- Angle with Negative Sine ----------------------------------------------------------
expected = [
1.0 0.0 0.0 0.0
0.4913173174083336 1.6609055643276887 0.0 0.0
-0.8481487383747819 1.0534923512298937 1.7806733511493273 0.0
-0.9747784574955511 -0.9285746739643262 1.336394636145641 1.8443441680325823
]
result = legendre(Val(:full), 5, 3)
@test result ≈ expected
@test eltype(result) == Float64
# -- Phase Term ------------------------------------------------------------------------
expected = [
1.0 0.0 0.0 0.0
1.7189652193774823 -0.2125054695073136 0.0 0.0
2.185579156246447 -0.4715867308960424 0.029149734541684073 0.0
2.526949659329994 -0.7801615739113572 0.07654028698418901 -0.003862935743113303
]
result = legendre(Val(:full), 0.123, 3; ph_term = true)
@test result ≈ expected
@test eltype(result) == Float64
# -- In-Place --------------------------------------------------------------------------
expected = [
1.0 0.0 0.0 0.0
1.7189652193774823 0.2125054695073136 0.0 0.0
2.185579156246447 0.4715867308960424 0.0 0.0
2.526949659329994 0.7801615739113572 0.0 0.0
]
result = zeros(Float64, 4, 4)
legendre!(Val(:full), result, 0.123, 3, 1)
@test result ≈ expected
expected = [
1.0 0.0 0.0 0.0
1.7189652193774823 0.2125054695073136 0.0 0.0
2.185579156246447 0.4715867308960424 0.029149734541684073 0.0
2.526949659329994 0.7801615739113572 0.07654028698418901 0.003862935743113303
]
result = zeros(Float64, 4, 4)
legendre!(Val(:full), result, 0.123, 10, 20)
@test result ≈ expected
# == Float32 ===========================================================================
expected = Float32[
1.0 0.0 0.0 0.0
1.7189652 0.21250547 0.0 0.0
2.1855793 0.47158676 0.029149737 0.0
2.5269504 0.7801616 0.07654029 0.0038629363
]
result = legendre(Val(:full), 0.123f0, 3)
@test result ≈ expected
@test eltype(result) == Float32
end
@testset "Errors" begin
@test_throws ArgumentError legendre(Val(:unnormalized), 0.123, -2)
@test_throws ArgumentError legendre(Val(:schmidt), 0.123, -2)
@test_throws ArgumentError legendre(Val(:full), 0.123, -2)
end
| SatelliteToolboxLegendre | https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl.git |
|
[
"MIT"
] | 1.0.3 | 5ff0e4fee0b4144ad3393177f449108cd07556d1 | code | 254 | using Test
using SatelliteToolboxLegendre
@testset "Legendre Associated Functions" verbose = true begin
include("./legendre.jl")
end
@testset "Derivative of the Legendre Associated Functions" verbose = true begin
include("./dlegendre.jl")
end
| SatelliteToolboxLegendre | https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl.git |
|
[
"MIT"
] | 1.0.3 | 5ff0e4fee0b4144ad3393177f449108cd07556d1 | docs | 1347 | SatelliteToolboxLegendre.jl Changelog
=====================================
Version 1.0.3
-------------
- ![Enhancement][badge-enhancement] Minor source-code updates.
Version 1.0.2
-------------
- ![Enhancement][badge-enhancement] Documentation update.
Version 1.0.1
-------------
- ![Bugfix][badge-bugfix] Fix keyword argument when computing Legendre associated functions
with full normalization using the API.
Version 1.0.0
-------------
- ![Enhancement][badge-enhancement] The documentation received some minor improvements.
- ![Info][badge-info] This algorithm has been stable in **SatelliteToolbox.jl** for over six
years. Hence, we are setting the current version as 1.0.0. The API modifications from the
current version in **SatelliteToolbox.jl** are breaking but subtle. Therefore, we do not
expect any problems.
Version 0.1.0
-------------
- Initial version.
- This version was based on the code in **SatelliteToolbox.jl**.
[badge-breaking]: https://img.shields.io/badge/BREAKING-red.svg
[badge-deprecation]: https://img.shields.io/badge/Deprecation-orange.svg
[badge-feature]: https://img.shields.io/badge/Feature-green.svg
[badge-enhancement]: https://img.shields.io/badge/Enhancement-blue.svg
[badge-bugfix]: https://img.shields.io/badge/Bugfix-purple.svg
[badge-info]: https://img.shields.io/badge/Info-gray.svg
| SatelliteToolboxLegendre | https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl.git |
|
[
"MIT"
] | 1.0.3 | 5ff0e4fee0b4144ad3393177f449108cd07556d1 | docs | 10070 | <p align="center">
<img src="./docs/src/assets/logo.png" width="150" title="SatelliteToolboxTransformations.jl"><br>
<small><i>This package is part of the <a href="https://github.com/JuliaSpace/SatelliteToolbox.jl">SatelliteToolbox.jl</a> ecosystem.</i></small>
</p>
# SatelliteToolboxLegendre.jl
[](https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl/actions/workflows/ci.yml)
[](https://codecov.io/gh/JuliaSpace/SatelliteToolboxLegendre.jl)
[](https://github.com/invenia/BlueStyle)
[](https://zenodo.org/doi/10.5281/zenodo.11246481)
This package contains function to compute the Legendre associated functions and its
derivatives for the models in the **SatelliteToolbox.jl** ecosystem.
## Installation
```julia
julia> using Pkg
julia> Pkg.add("SatelliteToolboxLegendre")
```
## Usage
### Legendre Associated Functions
This package exports two methods to compute the Legendre associated functions: `legendre`
and `legendre!`.
---
```julia
legendre(N, ϕ::T, n_max::Integer, m_max::Integer = -1; ph_term::Bool = false) where T<:Number -> Matrix{float(T)}
```
Compute the associated Legendre function $P_{n,m}\left[\cos(\phi)\right]$. The maximum
degree that will be computed is `n_max` and the maximum order is `m_max`. Notice that if
`m_max` is higher than `n_max` or negative (default), it is set to `n_max`.
The parameter `N` selects the normalization. The following values are valid:
- `Val(:full)`: Compute the fully normalized associated Legendre function.
- `Val(:schmidt)`: Compute the Schmidt quasi-normalized associated Legendre function.
- `Val(:unnormalized)`: Compute the unnormalized associated Legendre function.
This function has the following keywords:
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term $(-1)^m$ will be included.
(**Default** = `false`)
It returns a `Matrix{float(T)}` with the Legendre associated functions
$P_{n,m}\left[\cos(\phi)\right]$.
```julia
julia> legendre(Val(:unnormalized), 0.45, 4)
5×5 Matrix{Float64}:
1.0 0.0 0.0 0.0 0.0
0.900447 0.434966 0.0 0.0 0.0
0.716207 1.17499 0.567585 0.0 0.0
0.474547 1.99259 2.5554 1.2344 0.0
0.210627 2.61987 6.63455 7.78058 3.75845
julia> legendre(Val(:schmidt), 0.45, 4, 3; ph_term = true)
5×4 Matrix{Float64}:
1.0 0.0 0.0 0.0
0.900447 -0.434966 0.0 0.0
0.716207 -0.678381 0.163848 0.0
0.474547 -0.813473 0.329901 -0.0650586
0.210627 -0.828476 0.49451 -0.154993
julia> legendre(Val(:full), 0.45, 4, 1)
5×2 Matrix{Float64}:
1.0 0.0
1.55962 0.753382
1.60149 1.51691
1.25553 2.15225
0.631881 2.48543
```
---
```julia
legendre!(N, P::AbstractMatrix, ϕ::Number, n_max::Integer = -1, m_max::Integer = -1; kwargs...) -> Nothing
```
Compute the associated Legendre function $P_{n,m}\left[\cos(\phi)\right]$. The maximum
degree and order that will be computed are given by the parameters `n_max` and `m_max`. If
they are negative (default), the dimensions of matrix `P` will be used:
maximum degree -> number of rows - 1
maximum order -> number of columns - 1
The result will be stored at matrix `P`. Hence, this function can be used to reduce
allocations.
The parameter `N` selects the normalization. The following values are valid:
- `Val(:full)`: Compute the fully normalized associated Legendre function.
- `Val(:schmidt)`: Compute the Schmidt quasi-normalized associated Legendre function.
- `Val(:unnormalized)`: Compute the unnormalized associated Legendre function.
This function has the following keywords:
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term $(-1)^m$ will be included.
(**Default** = `false`)
### Derivative of the Legendre Associated Functions
This package exports two methods to compute the derivative of the Legendre associated
functions: `dlegendre` and `dlegendre!`.
---
```julia
dlegendre(N, ϕ::T, n_max::Integer, m_max::Integer = -1; kwargs...) where T<:Number -> Matrix{float(T)}, Matrix{float(T)}
```
Compute the first-order derivative of the associated Legendre function
$P_{n,m}\left[\cos(\phi)\right]$ with respect to $\phi$ [rad]:
$$\frac{\partial P_{n,m} \left[\cos(\phi)\right]}{\partial\phi}$$
The maximum degree that will be computed is `n_max` and the maximum order is `m_max`. Notice
that if `m_max` is higher than `n_max` or negative (default), it is set to `n_max`.
The parameter `N` selects the normalization. The following values are valid:
- `Val(:full)`: Compute the fully normalized associated Legendre function.
- `Val(:schmidt)`: Compute the Schmidt quasi-normalized associated Legendre function.
- `Val(:unnormalized)`: Compute the unnormalized associated Legendre function.
This function has the following keywords:
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term $(-1)^m$ will be included.
(**Default** = `false`)
It returns the following objects:
- `Matrix{float(T)}`: A matrix with the first-order derivative of the Legendre associated
functions $P_{n,m}\left[\cos(\phi)\right]$.
- `Matrix{float(T)}`: A matrix with the Legendre associated functions
$P_{n,m}\left[\cos(\phi)\right]$`.
```julia
julia> dP, P = dlegendre(Val(:unnormalized), 0.45, 4)
julia> dP
5×5 Matrix{Float64}:
0.0 0.0 0.0 0.0 0.0
-0.434966 0.900447 0.0 0.0 0.0
-1.17499 1.86483 2.34998 0.0 0.0
-1.99259 1.56958 9.34577 7.6662 0.0
-2.61987 -1.21101 19.6885 44.5626 31.1223
julia> P
5×5 Matrix{Float64}:
1.0 0.0 0.0 0.0 0.0
0.900447 0.434966 0.0 0.0 0.0
0.716207 1.17499 0.567585 0.0 0.0
0.474547 1.99259 2.5554 1.2344 0.0
0.210627 2.61987 6.63455 7.78058 3.75845
julia> dP, P = dlegendre(Val(:schmidt), 0.45, 4, 3; ph_term = true)
julia> dP
5×4 Matrix{Float64}:
0.0 0.0 0.0 0.0
-0.434966 -0.900447 0.0 0.0
-1.17499 -1.07666 0.678381 0.0
-1.99259 -0.640778 1.20653 -0.404044
-2.61987 0.382954 1.4675 -0.887709
julia> P
5×5 Matrix{Float64}:
1.0 0.0 0.0 0.0 0.0
0.900447 -0.434966 0.0 0.0 0.0
0.716207 -0.678381 0.163848 0.0 0.0
0.474547 -0.813473 0.329901 -0.0650586 0.0
0.210627 -0.828476 0.49451 -0.154993 0.0264706
julia> dP, P = dlegendre(Val(:full), 0.45, 4, 1)
julia> dP
5×2 Matrix{Float64}:
0.0 0.0
-0.753382 1.55962
-2.62736 2.40749
-5.27191 1.69534
-7.85961 -1.14886
julia> P
5×3 Matrix{Float64}:
1.0 0.0 0.0
1.55962 0.753382 0.0
1.60149 1.51691 0.366375
1.25553 2.15225 0.872836
0.631881 2.48543 1.48353
```
---
```julia
dlegendre!(dP::AbstractMatrix, ϕ::Number, P::AbstractMatrix, n_max::Integer = -1, m_max::Integer = -1; kwargs...) -> Nothing
```
Compute the first-order derivative of the associated Legendre function
$P_{n,m}\left[\cos(\phi)\right]$ with respect to $\phi$ [rad]:
$$\frac{\partial P_{n,m} \left[\cos(\phi)\right]}{\partial\phi}$$
The maximum degree and order that will be computed are given by the parameters `n_max` and
`m_max`. If they are negative (default), the dimensions of matrix `dP` will be used:
maximum degree -> number of rows - 1
maximum order -> number of columns - 1
The derivatives will be stored in the matrix `dP`. Hence, this function can be used to reduce
allocations.
The parameter `N` selects the normalization. The following values are valid:
- `Val(:full)`: Compute the fully normalized associated Legendre function.
- `Val(:schmidt)`: Compute the Schmidt quasi-normalized associated Legendre function.
- `Val(:unnormalized)`: Compute the unnormalized associated Legendre function.
This algorithm needs the matrix `P` with the values of the associated Legendre function
using the same normalization `N`, which can be computed using the function `legendre`.
> **Warning**
> The user is responsible to pass a matrix `P` with the correct values. For example, if
> `ph_term` is `true`, `P` must also be computed with `ph_term` set to `true`.
This function has the following keywords:
- `ph_term::Bool`: If `true`, the Condon-Shortley phase term $(-1)^m$ will be included.
(**Default** = `false`)
## Normalizations
### Full normalization
This algorithm was based on **[1]**. Our definition of fully normalized associated Legendre
function can be seen in **[2, p. 546]**. The conversion is obtained by:
$$K_{n,m} = \sqrt{k \cdot \frac{(n - m)! \cdot (2n + 1)}{(n + m)!}}~,$$
where $k = 1$ if $m = 0$ or $k = 2$ otherwise. Hence:
$$P^f_{n,m} = P_{n,m} \cdot K_{n,m}$$
where $P^f_{n,m}$ is the fully normalized Legendre associated function.
### Schmidt quasi-normalization
This algorithm was based on **[3, 4]**. The conversion is obtained by:
$$K_{n,m} = \sqrt{k \cdot \frac{(n - m)!}{(n + m)!}}~,$$
where $k = 1$ if $m = 0$ or $k = 2$ otherwise. Hence:
$$P^s_{n,m} = P_{n,m} \cdot K_{n,m}$$
where $P^s_{n,m}$ is the Schmidt quasi-normalized Legendre associated function.
## References
- **[1]** Holmes, S. A. and W. E. Featherstone, 2002. A unified approach to the Clenshaw
summation and the recursive computation of very high degree and order normalised
associated Legendre functions. Journal of Geodesy, 76(5), pp. 279-299. For more info.:
http://mitgcm.org/~mlosch/geoidcookbook/node11.html
- **[2]** Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications. Microcosm
Press, Hawthorn, CA, USA.
- **[3]** Schmidt, A (1917). Erdmagnetismus, Enzykl. Math. Wiss., 6, pp. 265–396.
- **[4]** Winch, D. E., Ivers, D. J., Turner, J. P. R., Stening R. J (2005). Geomagnetism
and Schmidt quasi-normalization. Geophysical Journal International, 160(2), pp. 487-504.
| SatelliteToolboxLegendre | https://github.com/JuliaSpace/SatelliteToolboxLegendre.jl.git |
|
[
"MIT"
] | 0.4.0 | a8e887c6a810ce59f68e7640bb12732d5c32f092 | code | 474 | ENV["PLOTS_TEST"] = "true"
ENV["GKSwstype"] = "100"
using SymPyPythonCall
using Documenter
makedocs(
sitename = "SymPyPythonCall",
format = Documenter.HTML(),
modules = [SymPyPythonCall],
warnonly = [:missing_docs],
)
# Documenter can also automatically deploy documentation to gh-pages.
# See "Hosting Documentation" and deploydocs() in the Documenter manual
# for more information.
deploydocs(
repo = "github.com/jverzani/SymPyPythonCall.jl.git"
)
| SymPyPythonCall | https://github.com/jverzani/SymPyPythonCall.jl.git |
|
[
"MIT"
] | 0.4.0 | a8e887c6a810ce59f68e7640bb12732d5c32f092 | code | 4506 | module SymPyPythonCallSymbolicsExt
# from https://github.com/JuliaSymbolics/Symbolics.jl/pull/957/
# by @jClugstor
import SymPyPythonCall
sp = SymPyPythonCall._sympy_
const PythonCall = SymPyPythonCall.PythonCall
import PythonCall: pyconvert, pyimport, pyisinstance
import Symbolics
import Symbolics: @variables
PythonCall.pyconvert(::Type{T}, x::SymPyPythonCall.Sym) where {T} = pyconvert(T, x.o)
# rule functions
function pyconvert_rule_sympy_symbol(::Type{Symbolics.Num}, x)
if !pyisinstance(x,sp.Symbol)
return PythonCall.pyconvert_unconverted()
end
name = PythonCall.pyconvert(Symbol,x.name)
return PythonCall.pyconvert_return(Symbolics.variable(name))
end
function pyconvert_rule_sympy_pow(::Type{Symbolics.Num}, x)
if !pyisinstance(x,sp.Pow)
return PythonCall.pyconvert_unconverted()
end
expbase = pyconvert(Symbolics.Num,x.base)
exp = pyconvert(Symbolics.Num,x.exp)
return PythonCall.pyconvert_return(expbase^exp)
end
function pyconvert_rule_sympy_mul(::Type{Symbolics.Num}, x)
if !pyisinstance(x,sp.Mul)
return PythonCall.pyconvert_unconverted()
end
mult = reduce(*,PythonCall.pyconvert.(Symbolics.Num,x.args))
return PythonCall.pyconvert_return(mult)
end
function pyconvert_rule_sympy_add(::Type{Symbolics.Num}, x)
if !pyisinstance(x,sp.Add)
return PythonCall.pyconvert_unconverted()
end
sum = reduce(+, PythonCall.pyconvert.(Symbolics.Num,x.args))
return PythonCall.pyconvert_return(sum)
end
function pyconvert_rule_sympy_derivative(::Type{Symbolics.Num}, x)
if !pyisinstance(x,sp.Derivative)
return PythonCall.pyconvert_unconverted()
end
variables = pyconvert.(Symbolics.Num,x.variables)
derivatives = prod(var -> Differential(var), variables)
expr = pyconvert(Symbolics.Num, x.expr)
return PythonCall.pyconvert_return(derivatives(expr))
end
function pyconvert_rule_sympy_function(::Type{Symbolics.Num}, x)
if !pyisinstance(x,sp.Function)
return PythonCall.pyconvert_unconverted()
end
nm = PythonCall.pygetattr(x, "func", nothing)
isnothing(nm) && return PythonCall.pyconvert_unconverted() # XXX
name = pyconvert(Symbol, nm)
args = pyconvert.(Symbolics.Num, x.args)
func = @variables $name(..)
return PythonCall.pyconvert_return(first(func)(args...))
end
function pyconvert_rule_sympy_equality(::Type{Symbolics.Equation}, x)
if !pyisinstance(x,sp.Equality)
return PythonCall.pyconvert_unconverted()
end
rhs = pyconvert(Symbolics.Num,x.rhs)
lhs = pyconvert(Symbolics.Num,x.lhs)
return PythonCall.pyconvert_return(rhs ~ lhs)
end
function __init__()
# added rules
# T = Symbolics.Num
PythonCall.pyconvert_add_rule("sympy.core.symbol:Symbol", Symbolics.Num, pyconvert_rule_sympy_symbol)
PythonCall.pyconvert_add_rule("sympy.core.power:Pow", Symbolics.Num, pyconvert_rule_sympy_pow)
PythonCall.pyconvert_add_rule("sympy.core.mul:Mul", Symbolics.Num, pyconvert_rule_sympy_mul)
PythonCall.pyconvert_add_rule("sympy.core.add:Add", Symbolics.Num, pyconvert_rule_sympy_add)
PythonCall.pyconvert_add_rule("sympy.core.function:Derivative", Symbolics.Num, pyconvert_rule_sympy_derivative)
PythonCall.pyconvert_add_rule("sympy.core.function:Function", Symbolics.Num, pyconvert_rule_sympy_function)
# T = Symbolics.Equation
PythonCall.pyconvert_add_rule("sympy.core.relational:Equality", Symbolics.Equation, pyconvert_rule_sympy_equality)
# core numbers
add_pyconvert_rule(f, cls, T=Symbolics.Num) = PythonCall.pyconvert_add_rule(cls, T, f)
add_pyconvert_rule("sympy.core.numbers:Pi") do T::Type{Symbolics.Num}, x
PythonCall.pyconvert_return(Symbolics.Num(pi))
end
add_pyconvert_rule("sympy.core.numbers:Exp1") do T::Type{Symbolics.Num}, x
PythonCall.pyconvert_return(Symbolics.Num(ℯ))
end
add_pyconvert_rule("sympy.core.numbers:Infinity") do T::Type{Symbolics.Num}, x
PythonCall.pyconvert_return(Symbolics.Num(Inf))
end
# Complex{Num}
add_pyconvert_rule("sympy.core.numbers:ImaginaryUnit", Complex{Symbolics.Num}) do T::Type{Complex{Symbolics.Num}}, x
PythonCall.pyconvert_return(Complex(Symbolics.Num(0), Symbolics.Num{1}))
end
add_pyconvert_rule("sympy.core.numbers:ComplexInfinity", Complex{Symbolics.Num}) do T::Type{Complex{Symbolics.Num}}, x
PythonCall.pyconvert_return(Complex(Symbolics.Num(0), Symbolics.Num(Inf)) )
end
end
end
| SymPyPythonCall | https://github.com/jverzani/SymPyPythonCall.jl.git |
|
[
"MIT"
] | 0.4.0 | a8e887c6a810ce59f68e7640bb12732d5c32f092 | code | 647 | """
SymPyPythonCall
Module to call Python's SymPy package from Julia using PythonCall
"""
module SymPyPythonCall
using SymPyCore
using PythonCall
const _PyType = PythonCall.Py
_pynull() = PythonCall.pynew()
_copy!(a, b) = PythonCall.pycopy!(a,b)
_pyimport(a) = PythonCall.pyimport(a)
_pyimport_conda(a,b) = PythonCall.pyimport(a) # XXX lose things
_pyobject(x) = PythonCall.pyconvert(Py, x)
_pytype_mapping(typ,a) = nothing
const _pybuiltin = PythonCall.pybuiltins
core_src_path = joinpath(pathof(SymPyCore), "../../src/SymPy")
include(joinpath(core_src_path, "sympy.jl"))
include("python_connection.jl")
include("deprecated.jl")
end
| SymPyPythonCall | https://github.com/jverzani/SymPyPythonCall.jl.git |
|
[
"MIT"
] | 0.4.0 | a8e887c6a810ce59f68e7640bb12732d5c32f092 | code | 1388 | # deprecations
# exported in 1.0.3
# [Symbol("@syms"), :Differential, :E, :Eq, :FALSE, :Ge, :Gt, :IM, :Le, :Lt, :N, :Ne, :PI, :Sym, :SymPyPythonCall, :TRUE, :VectorField, :Wild, :apart, :ask, :cancel, :degree, :doit, :dsolve, :elements, :expand, :expand_trig, :factor, :free_symbols, :hessian, :integrate, :lambdify, :lhs, :limit, :linsolve, :nonlinsolve, :nroots, :nsolve, :oo, :plot_implicit, :plot_parametric_surface, :real_roots, :refine, :rewrite, :rhs, :roots, :series, :simplify, :solve, :solveset, :subs, :summation, :symbols, :sympy, :sympy_plotting, :together, :zoo, :¬, :∧, :∨, :≦, :≧, :≪, :≫, :≶, :≷, :⩵, :𝑄]
Base.@deprecate expand_trig(x) x.expand_trig() true
Base.@deprecate_binding Q 𝑄
function unSym(x)
Base.depwarn("`unSym` is deprecated. Use `↓(x)`.", :unSym)
↓(x)
end
function asSymbolic(x)
Base.depwarn("`asSymbolic` is deprecated. Use `↑(x)`.", :asSymbolic)
↑(x)
end
function VectorField(args...; kwargs...)
Base.depwarn("`VectorField` has been removed", :VectorField)
nothing
end
function plot_implicit(args...; kwargs...)
Base.depwarn("`plot_implicit` has been removed. See `sympy.plotting.plot_implicit`", :VectorField)
nothing
end
function plot_parametric_surface(args...; kwargs...)
Base.depwarn("`VectorField` has been removed. See `sympy.plotting.plot3d_parametric_surface`", :plot_parametric_surface)
nothing
end
| SymPyPythonCall | https://github.com/jverzani/SymPyPythonCall.jl.git |
|
[
"MIT"
] | 0.4.0 | a8e887c6a810ce59f68e7640bb12732d5c32f092 | code | 3304 | ## PythonCall specific usage
Base.convert(::Type{S}, x::Sym{T}) where {T <: PythonCall.Py, S<:Sym} = x
Base.convert(::Type{S}, x::Sym{T}) where {T <: PythonCall.Py,
S<:Sym{PythonCall.Py}} = x
Base.convert(::Type{S}, x::T) where {T<:PythonCall.Py, S <: SymbolicObject} = Sym(x)
SymPyCore._convert(::Type{T}, x) where {T} = pyconvert(T, x)
function SymPyCore._convert(::Type{Bool}, x::Py)
pyisinstance(x, _sympy_.logic.boolalg.BooleanTrue) && return true
pyisinstance(x, _sympy_.logic.boolalg.BooleanFalse) && return false
pyconvert(Bool, pybool(x))
end
function SymPyCore.Bool3(x::Sym{T}) where {T <: PythonCall.Py}
y = ↓(x)
isnothing(y) && return nothing
if hasproperty(y, "is_Boolean")
if pyconvert(Bool, y.is_Boolean)
return SymPyCore._convert(Bool, y)
end
elseif hasproperty(y, "__bool__")
if pyconvert(Bool, y.__bool__ != ↓(Sym(nothing)))
return pyconvert(Bool, y.__bool__())
end
end
return nothing
end
## Modifications for ↓, ↑
Sym(x::Nothing) = Sym(pybuiltins.None)
SymPyCore.:↓(x::PythonCall.Py) = x
SymPyCore.:↓(d::Dict) = pydict((↓(k) => ↓(v) for (k,v) ∈ pairs(d)))
SymPyCore.:↓(x::Set) = _sympy_.sympify(pyset(↓(sᵢ) for sᵢ ∈ x))
SymPyCore.:↑(::Type{<:AbstractString}, x) = Sym(Py(x))
function SymPyCore.:↑(::Type{PythonCall.Py}, x)
# this lower level approach shouldn't allocate
pyisinstance(x, pybuiltins.set) && return Set(Sym.(collect(x))) #Set(↑(xᵢ) for xᵢ ∈ x)
pyisinstance(x, pybuiltins.tuple) && return Tuple(↑(xᵢ) for xᵢ ∈ x)
pyisinstance(x, pybuiltins.list) && return [↑(xᵢ) for xᵢ ∈ x]
pyisinstance(x, pybuiltins.dict) && return Dict(↑(k) => ↑(x[k]) for k ∈ x)
# add more sympy containers in sympy.jl and here
pyisinstance(x, _FiniteSet_) && return Set(Sym.(collect(x)))
pyisinstance(x, _MutableDenseMatrix_) && return _up_matrix(x) #map(↑, x.tolist())
# fallback
Sym(x)
end
function _up_matrix(m) # ↑ for matrices
sh = m.shape
r, c = SymPyCore._convert(Int, sh.__getitem__(0)), SymPyCore._convert(Int, sh.__getitem__(1))
out = [↑(m.__getitem__(i*c + j)) for i ∈ 0:(r-1), j ∈ 0:(c-1)]
out
end
function Base.hash(x::SymbolicObject{T}, h::UInt) where {T <: PythonCall.Py}
o = ↓(x)
hash(o, h)
end
# should we also have different code path for a::String like PyCall?
function Base.getproperty(x::SymbolicObject{T}, a::Symbol) where {T <: PythonCall.Py}
a == :o && return getfield(x, a)
if a == :py
Base.depwarn("The field `.py` has been renamed `.o`", :getproperty)
return getfield(x,:o)
end
val = ↓(x)
𝑎 = string(a)
hasproperty(val, 𝑎) || return nothing # not a property
meth = getproperty(val, 𝑎)
pyis(meth, pybuiltins.None) && return nothing
## __call__
if pycallable(meth) # "__call__") #hasproperty(meth, "__call__")
return SymPyCore.SymbolicCallable(meth)
end
# __class__ dispatch
if pyisinstance(meth, _bool_)
return pyconvert(Bool, meth)
end
if pyisinstance(meth, _ModuleType_)
return Sym(meth)
end
# just convert
return ↑(convert(PythonCall.Py, meth))
end
# do we need this conversion?
#Base.convert(::Type{T}, o::Py) where {T <: Sym} = T(o)
| SymPyPythonCall | https://github.com/jverzani/SymPyPythonCall.jl.git |
|
[
"MIT"
] | 0.4.0 | a8e887c6a810ce59f68e7640bb12732d5c32f092 | code | 194 | using SymPyPythonCall
path = joinpath(pathof(SymPyPythonCall.SymPyCore), "../../test")
include(joinpath(path, "runtests-sympycore.jl"))
## VERSION >= v"1.9.0" && include("test-extensions.jl")
| SymPyPythonCall | https://github.com/jverzani/SymPyPythonCall.jl.git |
|
[
"MIT"
] | 0.4.0 | a8e887c6a810ce59f68e7640bb12732d5c32f092 | code | 190 | using SymPyPythonCall
import Symbolics
using Test
@testset "Symbolics" begin
@syms x
𝑥 = SymPyPythonCall.PythonCall.pyconvert(Symbolics.Num, x)
@test isa(𝑥, Symbolics.Num)
end
| SymPyPythonCall | https://github.com/jverzani/SymPyPythonCall.jl.git |
|
[
"MIT"
] | 0.4.0 | a8e887c6a810ce59f68e7640bb12732d5c32f092 | docs | 1237 | # SymPyPythonCall
[](https://jverzani.github.io/SymPyCore.jl/dev)
[](https://github.com/jverzani/SymPyPythonCall.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/jverzani/SymPyPythonCall.jl)
[SymPyCore](https://github.com/jverzani/SymPyCore.jl) provides a `Julia`n interface to the [SymPy](https://www.sympy.org/) library of Python.
[SymPyPythonCall](https://github.com/jverzani/SymPyPythonCall.jl) utilizes `SymPyCore` and the `PythonCall` package (to provide the interop between `Julia` and `Python`) to enable access to Python's SymPy library using the practices and idioms of `Julia`.
The package [SymPyPyCall](https://github.com/jverzani/SymPyPyCall.jl) does a similar thing with the `PyCall` package providing the interop.
## Installation
Installing this package should install the `SymPyCore` package and the `PythonCall` package. The `PythonCall` package installs a `CondaPkg` package that installs the underlying SymPy library for Python.
| SymPyPythonCall | https://github.com/jverzani/SymPyPythonCall.jl.git |
|
[
"MIT"
] | 0.4.0 | a8e887c6a810ce59f68e7640bb12732d5c32f092 | docs | 1134 | ---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Wait**
Most all issues are actually issues with [SymPyCore](https://github.com/jverzani/SymPyCore.jl/issues). If so please report them there.
`SymPyPythonCall` contains very little code. Basically only that necessary to support the "glue" package `PythonCall` to interop `Julia` with `Python`.
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.
| SymPyPythonCall | https://github.com/jverzani/SymPyPythonCall.jl.git |
|
[
"MIT"
] | 0.4.0 | a8e887c6a810ce59f68e7640bb12732d5c32f092 | docs | 595 | ---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**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.
| SymPyPythonCall | https://github.com/jverzani/SymPyPythonCall.jl.git |
|
[
"MIT"
] | 0.4.0 | a8e887c6a810ce59f68e7640bb12732d5c32f092 | docs | 185 | ---
name: Question about SymPyCore
about: An issue or question about using the SymPyPythonCall.jl package
title: ''
labels: ''
assignees: ''
---
(*Please be as specific as possible*)
| SymPyPythonCall | https://github.com/jverzani/SymPyPythonCall.jl.git |
|
[
"MIT"
] | 0.4.0 | a8e887c6a810ce59f68e7640bb12732d5c32f092 | docs | 289 | ```@meta
CurrentModule = SymPyPythonCall
```
# SymPyPythonCall
This is a package providing access to the SymPy library of `Python` from within `Julia` utilizing `PythonCall` as the glue package between the two systems.
See docs at [SymPyCore](https://github.com/jverzani/SymPyCore.jl).
| SymPyPythonCall | https://github.com/jverzani/SymPyPythonCall.jl.git |
|
[
"MIT"
] | 1.6.1 | b3cc6698599b10e652832c2f23db3cab99d51b59 | code | 2067 | module SerializationExt
using LRUCache
using Serialization
function Serialization.serialize(s::AbstractSerializer, lru::LRU{K, V}) where {K, V}
Serialization.writetag(s.io, Serialization.OBJECT_TAG)
serialize(s, typeof(lru))
@assert lru.currentsize == length(lru)
serialize(s, lru.currentsize)
serialize(s, lru.maxsize)
serialize(s, lru.hits)
serialize(s, lru.misses)
serialize(s, lru.lock)
serialize(s, lru.by)
serialize(s, lru.finalizer)
for (k, val) in lru
serialize(s, k)
serialize(s, val)
sz = lru.dict[k][3]
serialize(s, sz)
end
end
function Serialization.deserialize(s::AbstractSerializer, ::Type{LRU{K, V}}) where {K, V}
currentsize = Serialization.deserialize(s)
maxsize = Serialization.deserialize(s)
hits = Serialization.deserialize(s)
misses = Serialization.deserialize(s)
lock = Serialization.deserialize(s)
by = Serialization.deserialize(s)
finalizer = Serialization.deserialize(s)
dict = Dict{K, Tuple{V, LRUCache.LinkedNode{K}, Int}}()
sizehint!(dict, currentsize)
# Create node chain
first = nothing
node = nothing
for i in 1:currentsize
prev = node
k = deserialize(s)
node = LRUCache.LinkedNode{K}(k)
val = deserialize(s)
sz = deserialize(s)
dict[k] = (val, node, sz)
if i == 1
first = node
continue
else
prev.next = node
node.prev = prev
end
end
# close the chain if any node exists
if node !== nothing
node.next = first
first.prev = node
end
# Createa cyclic ordered set from the node chain
keyset = LRUCache.CyclicOrderedSet{K}()
keyset.first = first
keyset.length = currentsize
# Create the LRU
lru = LRU{K,V}(maxsize=maxsize)
lru.dict = dict
lru.keyset = keyset
lru.currentsize = currentsize
lru.hits = hits
lru.misses = misses
lru.lock = lock
lru.by = by
lru.finalizer = finalizer
lru
end
end
| LRUCache | https://github.com/JuliaCollections/LRUCache.jl.git |
|
[
"MIT"
] | 1.6.1 | b3cc6698599b10e652832c2f23db3cab99d51b59 | code | 8560 | module LRUCache
include("cyclicorderedset.jl")
export LRU, cache_info
using Base.Threads
using Base: Callable
_constone(x) = 1
# Default cache size
mutable struct LRU{K,V} <: AbstractDict{K,V}
dict::Dict{K, Tuple{V, LinkedNode{K}, Int}}
keyset::CyclicOrderedSet{K}
currentsize::Int
maxsize::Int
hits::Int
misses::Int
lock::SpinLock
by::Any
finalizer::Any
function LRU{K, V}(; maxsize::Int, by = _constone, finalizer = nothing) where {K, V}
dict = Dict{K, V}()
keyset = CyclicOrderedSet{K}()
new{K, V}(dict, keyset , 0, maxsize, 0, 0, SpinLock(), by, finalizer)
end
end
Base.@kwdef struct CacheInfo
hits::Int
misses::Int
currentsize::Int
maxsize::Int
end
function Base.show(io::IO, c::CacheInfo)
return print(io, "CacheInfo(; hits=$(c.hits), misses=$(c.misses), currentsize=$(c.currentsize), maxsize=$(c.maxsize))")
end
"""
cache_info(lru::LRU) -> CacheInfo
Returns a `CacheInfo` object holding a snapshot of information about the cache hits, misses, current size, and maximum size, current as of when the function was called. To access the values programmatically, use property access, e.g. `info.hits`.
Note that only `get!` and `get` contribute to hits and misses, and `empty!` resets the counts of hits and misses to 0.
## Example
```jldoctest
lru = LRU{Int, Float64}(maxsize=10)
get!(lru, 1, 1.0) # miss
get!(lru, 1, 1.0) # hit
get(lru, 2, 2) # miss
get(lru, 2, 2) # miss
info = cache_info(lru)
# output
CacheInfo(; hits=1, misses=3, currentsize=1, maxsize=10)
```
"""
function cache_info(lru::LRU)
lock(lru.lock) do
return CacheInfo(; hits=lru.hits, misses=lru.misses, currentsize=lru.currentsize, maxsize=lru.maxsize)
end
end
LRU(; maxsize::Int, by = _constone, finalizer = nothing) =
LRU{Any,Any}(maxsize = maxsize, by = by, finalizer = finalizer)
Base.show(io::IO, lru::LRU{K, V}) where {K, V} =
print(io, "LRU{$K, $V}(; maxsize = $(lru.maxsize))")
function Base.iterate(lru::LRU, state...)
next = iterate(lru.keyset, state...)
if next === nothing
return nothing
else
k, state = next
v, = lru.dict[k]
return k=>v, state
end
end
function Base.iterate(lru::Iterators.Reverse{<:LRU}, state...)
next = iterate(Iterators.Reverse(lru.itr.keyset), state...)
if next === nothing
return nothing
else
k, state = next
v, = lru.itr.dict[k]
return k=>v, state
end
end
Base.length(lru::LRU) = length(lru.keyset)
Base.isempty(lru::LRU) = isempty(lru.keyset)
function Base.sizehint!(lru::LRU, n::Integer)
lock(lru.lock) do
sizehint!(lru.dict, n)
end
return lru
end
_unsafe_haskey(lru::LRU, key) = haskey(lru.dict, key)
function Base.haskey(lru::LRU, key)
lock(lru.lock) do
return _unsafe_haskey(lru, key)
end
end
function Base.get(lru::LRU, key, default)
lock(lru.lock) do
if _unsafe_haskey(lru, key)
v = _unsafe_getindex(lru, key)
lru.hits += 1
return v
else
lru.misses += 1
return default
end
end
end
function Base.get(default::Callable, lru::LRU, key)
lock(lru.lock)
try
if _unsafe_haskey(lru, key)
lru.hits += 1
return _unsafe_getindex(lru, key)
end
lru.misses += 1
finally
unlock(lru.lock)
end
return default()
end
function Base.get!(lru::LRU{K, V}, key, default) where {K, V}
evictions = Tuple{K, V}[]
v = lock(lru.lock) do
if _unsafe_haskey(lru, key)
lru.hits += 1
v = _unsafe_getindex(lru, key)
return v
end
v = default
_unsafe_addindex!(lru, v, key)
_unsafe_resize!(lru, evictions)
lru.misses += 1
return v
end
_finalize_evictions!(lru.finalizer, evictions)
return v
end
function Base.get!(default::Callable, lru::LRU{K, V}, key) where {K, V}
evictions = Tuple{K, V}[]
lock(lru.lock)
try
if _unsafe_haskey(lru, key)
lru.hits += 1
return _unsafe_getindex(lru, key)
end
finally
unlock(lru.lock)
end
v = default()
lock(lru.lock)
try
if _unsafe_haskey(lru, key)
lru.hits += 1
# should we test that this yields the same result as default()
v = _unsafe_getindex(lru, key)
else
_unsafe_addindex!(lru, v, key)
_unsafe_resize!(lru, evictions)
lru.misses += 1
end
finally
unlock(lru.lock)
end
_finalize_evictions!(lru.finalizer, evictions)
return v
end
function _unsafe_getindex(lru::LRU, key)
v, n, s = lru.dict[key]
_move_to_front!(lru.keyset, n)
return v
end
function Base.getindex(lru::LRU, key)
lock(lru.lock) do
if _unsafe_haskey(lru, key)
v = _unsafe_getindex(lru, key)
return v
else
throw(KeyError(key))
end
end
end
function _unsafe_addindex!(lru::LRU{K}, v, key) where K
s = lru.by(v)::Int
# If entry is larger than entire cache, don't add it
s > lru.maxsize && return
n = LinkedNode{K}(key)
rotate!(_push!(lru.keyset, n))
lru.currentsize += s
lru.dict[key] = (v, n, s)
return
end
function Base.setindex!(lru::LRU{K, V}, v, key) where {K, V}
evictions = Tuple{K, V}[]
lock(lru.lock) do
if _unsafe_haskey(lru, key)
old_v, n, s = lru.dict[key]
if lru.finalizer !== nothing
push!(evictions, (key, old_v))
end
lru.currentsize -= s
s = lru.by(v)::Int
# If new entry is larger than entire cache, don't add it
# (but still evict the old entry!)
if s > lru.maxsize
# We are inside the lock still, so we will remove it manually rather than
# `delete!(lru, key)` which would need the lock again.
delete!(lru.dict, key)
_delete!(lru.keyset, n)
else # add the new entry
lru.currentsize += s
lru.dict[key] = (v, n, s)
_move_to_front!(lru.keyset, n)
end
else
_unsafe_addindex!(lru, v, key)
end
_unsafe_resize!(lru, evictions)
end
_finalize_evictions!(lru.finalizer, evictions)
return lru
end
function _unsafe_resize!(lru::LRU{K, V}, evictions::Vector{Tuple{K, V}},
maxsize::Integer = lru.maxsize) where {K, V}
lru.maxsize = maxsize
while lru.currentsize > lru.maxsize
key = pop!(lru.keyset)
v, n, s = pop!(lru.dict, key)
if lru.finalizer !== nothing
push!(evictions, (key, v))
end
lru.currentsize -= s
end
return
end
function Base.resize!(lru::LRU{K, V}; maxsize::Integer = lru.maxsize) where {K, V}
@assert 0 <= maxsize
evictions = Tuple{K, V}[]
lock(lru.lock) do
_unsafe_resize!(lru, evictions, maxsize)
end
_finalize_evictions!(lru.finalizer, evictions)
return lru
end
function Base.delete!(lru::LRU{K, V}, key) where {K, V}
v = lock(lru.lock) do
v, n, s = pop!(lru.dict, key)
lru.currentsize -= s
_delete!(lru.keyset, n)
return v
end
if lru.finalizer !== nothing
lru.finalizer(key, v)
end
return lru
end
function Base.pop!(lru::LRU{K, V}, key) where {K, V}
(key, v) = lock(lru.lock) do
v, n, s = pop!(lru.dict, key)
lru.currentsize -= s
_delete!(lru.keyset, n)
return (key, v)
end
if lru.finalizer !== nothing
lru.finalizer(key, v)
end
return v
end
function Base.empty!(lru::LRU{K, V}) where {K, V}
evictions = Tuple{K, V}[]
lock(lru.lock) do
if lru.finalizer === nothing
lru.currentsize = 0
empty!(lru.dict)
empty!(lru.keyset)
else
sizehint!(evictions, length(lru))
maxsize = lru.maxsize
_unsafe_resize!(lru, evictions, 0)
lru.maxsize = maxsize # restore `maxsize`
end
lru.hits = 0
lru.misses = 0
end
_finalize_evictions!(lru.finalizer, evictions)
return lru
end
function _finalize_evictions!(finalizer, evictions)
for (key, value) in evictions
finalizer(key, value)
end
return
end
if !isdefined(Base, :get_extension)
include("../ext/SerializationExt.jl")
end
end # module
| LRUCache | https://github.com/JuliaCollections/LRUCache.jl.git |
|
[
"MIT"
] | 1.6.1 | b3cc6698599b10e652832c2f23db3cab99d51b59 | code | 4485 | using Base: IteratorEltype, HasEltype, HasLength, EltypeUnknown
mutable struct LinkedNode{T}
val::T
next::LinkedNode{T}
prev::LinkedNode{T}
# All new created nodes are self referential only
function LinkedNode{T}(k::T) where {T}
x = new{T}(k)
x.next = x
x.prev = x
return x
end
end
mutable struct CyclicOrderedSet{T} <: AbstractSet{T}
first::Union{LinkedNode{T}, Nothing}
length::Int
CyclicOrderedSet{T}() where {T} = new{T}(nothing, 0)
end
CyclicOrderedSet(itr) = _CyclicOrderedSet(itr, IteratorEltype(itr))
_CyclicOrderedSet(itr, ::HasEltype) = CyclicOrderedSet{eltype(itr)}(itr)
function _CyclicOrderedSet(itr, ::EltypeUnknown)
T = Base.@default_eltype(itr)
(isconcretetype(T) || T === Union{}) || return grow_to!(CyclicOrderedSet{T}(), itr)
return CyclicOrderedSet{T}(itr)
end
CyclicOrderedSet{T}(itr) where {T} = union!(CyclicOrderedSet{T}(), itr)
Base.IteratorSize(::Type{<:CyclicOrderedSet}) = HasLength()
Base.IteratorEltype(::Type{<:CyclicOrderedSet}) = HasEltype()
Base.length(s::CyclicOrderedSet) = s.length
Base.isempty(s::CyclicOrderedSet) = length(s) == 0
Base.empty(s::CyclicOrderedSet{T}, ::Type{U}=T) where {T,U} = CyclicOrderedSet{U}()
function Base.iterate(s::CyclicOrderedSet, state = s.first)
if state === nothing
return nothing
else
return state.val, state.next == s.first ? nothing : state.next
end
end
function Base.iterate(s::Iterators.Reverse{<:LRUCache.CyclicOrderedSet},
state = (s.itr.first isa Nothing) ? nothing : s.itr.first.prev)
if state === nothing
return nothing
else
return state.val, state.prev == s.itr.first.prev ? nothing : state.prev
end
end
function Base.last(s::CyclicOrderedSet)
isempty(s) && throw(ArgumentError("collection must be non-empty"))
return s.first.prev.val
end
function Base.show(io::IO, s::CyclicOrderedSet)
print(io, typeof(s))
print(io, "([")
if s.first !== nothing
f = s.first
show(io, f.val)
n = f.next
while n !== f
print(io, ", ")
show(io, n.val)
n = n.next
end
end
print(io, "])")
end
function _findnode(s::CyclicOrderedSet, x)
isempty(s) && return nothing
n = s.first
while !isequal(n.val, x)
n = n.next
n == s.first && return nothing
end
return n
end
# adding items
function _push!(s::CyclicOrderedSet{T}, n::LinkedNode{T}) where {T}
if isempty(s)
s.first = n
else
list = s.first
n.next = list
n.prev = list.prev
list.prev.next = n
list.prev = n
end
s.length += 1
return s
end
function Base.push!(s::CyclicOrderedSet{T}, x) where T
n = _findnode(s, x)
if n === nothing
_push!(s, LinkedNode{T}(x))
else
_delete!(s, n)
_push!(s, n)
end
return s
end
Base.pushfirst!(s::CyclicOrderedSet, x) = rotate!(push!(s, x))
# removing items
function _delete!(s::CyclicOrderedSet{T}, n::LinkedNode{T}) where {T}
n.next.prev = n.prev
n.prev.next = n.next
s.length -= 1
if n == s.first
s.first = s.length == 0 ? nothing : n.next
end
return s
end
function Base.pop!(s::CyclicOrderedSet)
isempty(s) && throw(ArgumentError("collection must be non-empty"))
n = s.first.prev
_delete!(s, n)
return n.val
end
function Base.pop!(s::CyclicOrderedSet, x)
n = _findnode(s, x)
if n === nothing
throw(KeyError(x))
else
_delete!(s, n)
return x
end
end
function Base.pop!(s::CyclicOrderedSet, x, default)
n = _findnode(s, x)
if n === nothing
return default
else
_delete!(s, n)
return x
end
end
function Base.delete!(s::CyclicOrderedSet, x)
n = _findnode(s, x)
if n !== nothing
_delete!(s, n)
end
return s
end
function Base.empty!(s::CyclicOrderedSet)
s.first = nothing
s.length = 0
return s
end
# Rotate one step forward, so last element is now first
function rotate!(s::CyclicOrderedSet)
if length(s) > 1
s.first = s.first.prev
end
return s
end
function _move_to_front!(s::CyclicOrderedSet{T}, n::LinkedNode{T}) where {T}
if s.first !== n
n.next.prev = n.prev
n.prev.next = n.next
n.next = s.first
n.prev = s.first.prev
s.first.prev.next = n
s.first.prev = n
s.first = n
end
return s
end
| LRUCache | https://github.com/JuliaCollections/LRUCache.jl.git |
|
[
"MIT"
] | 1.6.1 | b3cc6698599b10e652832c2f23db3cab99d51b59 | code | 2372 | module Benchmark
using LRUCache
# This benchmark is a simple recursive Fibonnaci calculation. While not
# comparable to most real world problems, the simplicity of the underlying
# calculation means that most of the time is spent in the cacheing operations,
# rather than on the function itself. Which is optimal for comparing
# improvements to the cache speed.
const FIBCACHE = LRU{Int, Int}(; maxsize = 10)
function fib(a::Int)
get!(FIBCACHE, a) do
if a < 2
a
else
fib(a - 1) + fib(a - 2)
end
end
end
function fib_benchmark(cachesize)
resize!(FIBCACHE; maxsize = cachesize)
empty!(FIBCACHE)
println("Cache Size = $cachesize")
@time fib(50)
end
println("========== BENCHMARKS ==========")
println()
println("Toss this timing, things are still compiling")
fib_benchmark(5)
println()
println("Fibonnaci Benchmarks")
println("--------------------")
for n in (10, 50, 100)
fib_benchmark(n)
end
println()
# Now we benchmark individual operations
function setup_cache(cachesize, items)
resize!(FIBCACHE; maxsize = cachesize)
empty!(FIBCACHE)
for i in items
FIBCACHE[i] = i
end
end
function benchmark_get(n)
@time FIBCACHE[n]
end
function benchmark_set(k, v)
@time FIBCACHE[k] = v
end
println("Access Benchmarks")
println("-----------------")
# Cache is [10, 9, 8, ...., 1] in order of use, and is full
setup_cache(10, 1:10)
println("Access for elements at head of cache")
for i in 1:5
benchmark_get(10)
end
println()
# Cache is [10, 9, 8, ...., 1] in order of use, and is full
println("Access for elements not at head of cache")
for i in 1:5
benchmark_get(i)
end
println()
println("Insertion Benchmarks")
println("--------------------")
# Cache is empty, with size 5
resize!(FIBCACHE; maxsize = 5)
empty!(FIBCACHE)
println("Insertion when cache is not full, element not in cache")
for i in 1:5
benchmark_set(i, i)
end
println()
# Cache is [5, 4, 3, 2, 1]
println("Insertion when element already in cache, not at head")
for i in 1:5
benchmark_set(i, i)
end
println()
# Cache is [5, 4, 3, 2, 1]
println("Insertion when element already in cache, at head")
for i in 1:5
benchmark_set(5, 5)
end
println()
# Cache is [5, 4, 3, 2, 1]
println("Insertion when cache is full, element not in cache")
for i in 6:10
benchmark_set(i, i)
end
end
| LRUCache | https://github.com/JuliaCollections/LRUCache.jl.git |
|
[
"MIT"
] | 1.6.1 | b3cc6698599b10e652832c2f23db3cab99d51b59 | code | 1538 | @testset "Original tests" begin
function test_order(lru, keys, vals)
for (i, (k,v)) = enumerate(lru)
@test k == keys[i]
@test v == vals[i]
end
end
CACHE = LRU{Int, Int}(; maxsize = 20)
# Test insertion ordering
kvs = 1:10
for i in reverse(kvs)
CACHE[i] = i
end
test_order(CACHE, 1:10, 1:10)
# Test reinsertion ordering
kvs = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
for i in reverse(kvs)
CACHE[i] = i
end
test_order(CACHE, kvs, kvs)
# Test least recently used items are evicted
resize!(CACHE; maxsize = 5)
test_order(CACHE, kvs[1:5], kvs[1:5])
resize!(CACHE; maxsize = 10)
test_order(CACHE, kvs[1:5], kvs[1:5])
kvs = 1:11
for i in reverse(kvs)
CACHE[i] = i
end
test_order(CACHE, kvs[1:end-1], kvs[1:end-1])
# Test lookups, and that lookups reorder
kvs = 1:10
for i in reverse(kvs)
CACHE[i] = 2*i
end
for i in kvs
@test CACHE[i] == 2*i
end
test_order(CACHE, reverse(kvs), reverse(2*kvs))
# Test empty!
empty!(CACHE)
@test length(CACHE) == 0
# Test get! with default parameter
@test get!(CACHE, 1, 2) == 2 # not in cache
@test get!(CACHE, 1, 2) == 2 # in cache
# Test get! with function call
val = get!(CACHE, 2) do
3
end
@test val == 3
get!(CACHE, 2) do
error("this shouldn't have been called!")
end
# Test Abstract typed cache. All we're checking for here is that the container
# is able to hold abstract types without issue. Insertion order is already
# tested above.
CACHE2 = LRU{String, Integer}(; maxsize = 5)
CACHE2["test"] = 4
@test CACHE2["test"] == 4
end
| LRUCache | https://github.com/JuliaCollections/LRUCache.jl.git |
|
[
"MIT"
] | 1.6.1 | b3cc6698599b10e652832c2f23db3cab99d51b59 | code | 9063 | using LRUCache
using LRUCache: CacheInfo
using Test
using Random
using Base.Threads
# Test insertion and reinsertion ordering
@testset "Single-threaded insertion and reinsertion" begin
for cache in [LRU(; maxsize = 100), LRU{Int, Int}(; maxsize = 100)]
r = 1:100
for i in reverse(r)
cache[i] = i
end
@test collect(cache) == collect(i=>i for i in r)
for i = 1:10:100
@test haskey(cache, i)
@test !haskey(cache, 100+i)
end
# reinsert in random order
p = randperm(100)
for i in reverse(p)
cache[i] = i
end
@test collect(cache) == collect(i=>i for i in p)
end
end
@testset "Multi-threaded insertion and reinsertion" begin
cache = LRU{Int, Int}(; maxsize = 100)
r = 1:100
@threads for i in reverse(r)
cache[i] = i
end
@threads for i = 1:10:100
@test haskey(cache, i)
@test !haskey(cache, 100+i)
end
@test Set(cache) == Set(i=>i for i=1:100)
@threads for i in 100:-1:1
cache[i] = 2*i
end
@test Set(cache) == Set(i=>2*i for i=1:100)
end
@testset "Single-threaded getting and setting" begin
cache = LRU{Int, Int}(; maxsize = 50*sizeof(Int), by = sizeof)
for i in 100:-1:1
@test 2*i == get(cache, i, 2*i)
@test 2*i == get(()->2*i, cache, i)
@test i == (iseven(i) ? get!(cache, i, i) : get!(()->i, cache, i))
@test i == get!(cache, i, 2*i)
@test i == get!(()->error("this should not happen"), cache, i)
@test i == get(cache, i, 2*i)
@test i == get(()->2*i, cache, i)
end
for i in 1:50
@test haskey(cache, i)
@test !haskey(cache, i+50)
@test_throws KeyError getindex(cache, i+50)
end
@test collect(cache) == collect(i=>i for i in 1:50)
p = randperm(50)
for i in reverse(p)
cache[i] = i
end
@test collect(cache) == collect(i=>i for i in p)
p10 = p[1:10]
resize!(cache; maxsize = 10*sizeof(Int))
@test collect(cache) == collect(i=>i for i in p10)
resize!(cache; maxsize = 50*sizeof(Int))
@test collect(cache) == collect(i=>i for i in p10)
for i in 50:-1:1
@test get!(cache, i, 2*i) == (i in p10 ? i : 2*i)
end
for i in reverse(p10)
@test cache[i] == i
end
resize!(cache; maxsize = 10*sizeof(Int))
@test collect(cache) == collect(i=>i for i in p10)
delete!(cache, p10[1])
@test !haskey(cache, p10[1])
@test p10[10] == pop!(cache, p10[10])
@test !haskey(cache, p10[10])
@test length(empty!(cache)) == 0
@test isempty(cache)
for i in p10
@test !haskey(cache, p10)
end
end
@testset "Multi-threaded getting and setting" begin
cache = LRU{Int, Int}(; maxsize = 50*sizeof(Int), by = sizeof)
@threads for i in 50:-1:1
@test 2*i == get(cache, i, 2*i)
@test 2*i == get(()->2*i, cache, i)
@test i == (iseven(i) ? get!(cache, i, i) : get!(()->i, cache, i))
@test i == get!(cache, i, 2*i)
@test i == get!(()->error("this should not happen"), cache, i)
@test i == get(cache, i, 2*i)
@test i == get(()->2*i, cache, i)
end
p = randperm(50)
p10 = p[1:10]
@threads for i in p10
@test cache[i] == i
end
resize!(cache; maxsize = 10*sizeof(Int))
@test Set(cache) == Set(i=>i for i in p10)
resize!(cache; maxsize = 50*sizeof(Int))
@test Set(cache) == Set(i=>i for i in p10)
delete!(cache, p10[1])
@test !haskey(cache, p10[1])
@test_throws KeyError getindex(cache, p10[1])
@test p10[10] == pop!(cache, p10[10])
@test !haskey(cache, p10[10])
@test_throws KeyError getindex(cache, p10[1])
end
@testset "Recursive lock in get(!)" begin
cache = LRU{Int,Int}(; maxsize = 100)
p = randperm(100)
cache[1] = 1
f!(cache, i) = get!(()->(f!(cache, i-1) + 1), cache, i)
@threads for i = 1:100
f!(cache, p[i])
end
@threads for i = 1:100
@test haskey(cache, i)
@test cache[i] == i
end
end
@testset "Eviction callback" begin
# Julia 1.0 and 1.1 crash with multiple threads on this
# combination of @threads and Channel.
if VERSION >= v"1.2" || Threads.nthreads() == 1
resources = Channel{Matrix{Float64}}(11)
for _ = 1:11
put!(resources, zeros(5, 5))
end
callback = (key, value) -> put!(resources, value)
cache = LRU{Int,Matrix{Float64}}(; maxsize = 10, finalizer = callback)
@threads for i = 1:100
cache[i ÷ gcd(i, 60)] = take!(resources)
end
# Note: It's not ideal to rely on the Channel internals but there
# doesn't seem to be a public way to check how much is occupied.
@test length(resources.data) == 1
cache[101] = take!(resources)
@test length(resources.data) == 1
pop!(cache, 101)
@test length(resources.data) == 2
cache[101] = take!(resources)
@test length(resources.data) == 1
delete!(cache, 101)
@test length(resources.data) == 2
get!(cache, 101, take!(resources))
@test length(resources.data) == 1
get!(() -> take!(resources), cache, 102)
@test length(resources.data) == 1
get!(() -> take!(resources), cache, 102)
@test length(resources.data) == 1
resize!(cache, maxsize = 5)
@test length(resources.data) == 6
empty!(cache)
@test length(resources.data) == 11
@test cache.maxsize == 5
end
end
@testset "Reverse iterator" begin
lru = LRU(;maxsize = 4)
# Instantiate lazy reverse iterator
rlru = Iterators.reverse(lru)
# Did we handle the empty cache?
@test [k => v for (k,v) in lru] == []
@test [k => v for (k,v) in rlru] == []
# Fill in some data
lru["first"] = 1
# Does a single element cache work
@test [k => v for (k,v) in lru] == ["first" => 1]
@test [k => v for (k,v) in rlru] == ["first" => 1]
lru["second"] = 2
# Does a partially filled cache work
@test [k => v for (k,v) in lru] == ["second" => 2, "first" => 1]
@test [k => v for (k,v) in rlru] == ["first" => 1, "second" => 2]
lru["third"] = 3
lru["fourth"] = 4
# Does forward iteration give us the expected result?
@test [k => v for (k,v) in lru] == ["fourth" => 4, "third" => 3, "second" => 2, "first" => 1]
@test [k => v for (k,v) in rlru] == ["first" => 1, "second" => 2, "third" => 3, "fourth" => 4]
# Evict first by inserting fifth
lru["fifth"] = 5
@test [k => v for (k,v) in lru] == ["fifth" => 5, "fourth" => 4, "third" => 3, "second" => 2]
@test [k => v for (k,v) in rlru] == ["second" => 2, "third" => 3, "fourth" => 4, "fifth" => 5]
end
# https://github.com/JuliaCollections/LRUCache.jl/issues/37
@testset "Large entries" begin
lru = LRU{Int, Vector{Int}}(; maxsize=10, by=length)
get!(lru, 1, 1:9)
@test !isempty(lru)
@test lru[1] == 1:9
# Add too-big entry
get!(lru, 2, 1:11)
# did not add entry 2, it is too big
@test !haskey(lru, 2)
# Still have old entries
@test !isempty(lru)
@test lru[1] == 1:9
# Same with `setindex!`
lru[2] = 1:11
@test !haskey(lru, 2)
@test !isempty(lru)
@test lru[1] == 1:9
# Add a second small entry
lru[2] = 1:1
@test haskey(lru, 2)
@test lru[1] == 1:9
@test lru[2] == 1:1
# Re-assign it to a too-big entry
lru[2] = 1:11
@test !haskey(lru, 2) # don't keep the old entry!
@test lru[1] == 1:9
end
@testset "cache_info" begin
lru = LRU{Int, Float64}(; maxsize=10)
get!(lru, 1, 1.0) # miss
@test cache_info(lru) == CacheInfo(; hits=0, misses=1, currentsize=1, maxsize=10)
get!(lru, 1, 1.0) # hit
@test cache_info(lru) == CacheInfo(; hits=1, misses=1, currentsize=1, maxsize=10)
get(lru, 1, 1.0) # hit
@test cache_info(lru) == CacheInfo(; hits=2, misses=1, currentsize=1, maxsize=10)
get(lru, 2, 1.0) # miss
info = CacheInfo(; hits=2, misses=2, currentsize=1, maxsize=10)
@test cache_info(lru) == info
@test sprint(show, info) == "CacheInfo(; hits=2, misses=2, currentsize=1, maxsize=10)"
# These don't change the hits and misses
@test haskey(lru, 1)
@test cache_info(lru) == info
@test lru[1] == 1.0
@test cache_info(lru) == info
@test !haskey(lru, 2)
@test cache_info(lru) == info
# This affects `currentsize` but not hits or misses
delete!(lru, 1)
@test cache_info(lru) == CacheInfo(; hits=2, misses=2, currentsize=0, maxsize=10)
# Likewise setindex! does not affect hits or misses, just `currentsize`
lru[1] = 1.0
@test cache_info(lru) == info
# Only affects size
pop!(lru, 1)
@test cache_info(lru) == CacheInfo(; hits=2, misses=2, currentsize=0, maxsize=10)
# Resets counts
empty!(lru)
@test cache_info(lru) == CacheInfo(; hits=0, misses=0, currentsize=0, maxsize=10)
end
include("originaltests.jl")
include("serializationtests.jl")
| LRUCache | https://github.com/JuliaCollections/LRUCache.jl.git |
|
[
"MIT"
] | 1.6.1 | b3cc6698599b10e652832c2f23db3cab99d51b59 | code | 1920 | using Serialization
@testset "Large Serialize and Deserialize" begin
cache = LRU{Int, Int}(maxsize=100_000)
# Populate the cache with dummy data
num_entries_to_test = [0, 1, 2, 3, 4, 5, 100_000, 1_000_000]
for i in 0:maximum(num_entries_to_test)
# Add dummy data on all but the first iteration,
# to test an empty cache
i > 0 && (cache[i] = i+1)
i ∈ num_entries_to_test || continue
io = IOBuffer()
serialize(io, cache)
seekstart(io)
deserialized_cache = deserialize(io)
# Check that the cache is the same
@test cache.maxsize == deserialized_cache.maxsize
@test cache.currentsize == deserialized_cache.currentsize
@test cache.hits == deserialized_cache.hits
@test cache.misses == deserialized_cache.misses
@test cache.by == deserialized_cache.by
@test cache.finalizer == deserialized_cache.finalizer
@test cache.keyset.length == deserialized_cache.keyset.length
@test issetequal(collect(cache), collect(deserialized_cache))
# Check that the cache has the same keyset
@test length(cache.keyset) == length(deserialized_cache.keyset)
@test all(((c_val, d_val),) -> c_val == d_val, zip(cache.keyset, deserialized_cache.keyset))
# Check that the cache keys, values, and sizes are the same
for (key, (c_value, c_node, c_s)) in cache.dict
d_value, d_node, d_s = deserialized_cache.dict[key]
c_value == d_value || @test false
c_node.val == d_node.val || @test false
c_s == d_s || @test false
end
end
end
@testset "Serialize mutable references" begin
lru = LRU(; maxsize=5)
a = b = [1]
lru[1] = a
lru[2] = b
@test lru[1] === lru[2]
io = IOBuffer()
serialize(io, lru)
seekstart(io)
lru2 = deserialize(io)
@test lru2[1] === lru2[2]
end
| LRUCache | https://github.com/JuliaCollections/LRUCache.jl.git |
|
[
"MIT"
] | 1.6.1 | b3cc6698599b10e652832c2f23db3cab99d51b59 | docs | 4957 | # LRUCache.jl
[](https://github.com/JuliaCollections/LRUCache.jl/actions/workflows/ci.yml)
[](https://github.com/JuliaCollections/LRUCache.jl/actions/workflows/ci-julia-nightly.yml)
[](LICENSE.md)
[](http://codecov.io/github/JuliaCollections/LRUCache.jl?branch=master)
Provides a thread-safe implementation of a Least Recently Used (LRU) Cache for Julia.
An LRU Cache is a useful associative data structure (`AbstractDict` in Julia) that has a
set maximum size (as measured by number of elements or a custom size measure for items).
Once that size is reached, the least recently used items are removed first. A lock ensures
that data access does not lead to race conditions.
A particular use case of this package is to implement function memoization for functions
that can simultaneously be called from different threads.
## Installation
Install with the package manager via `]add LRUCache` or
```julia
using Pkg
Pkg.add("LRUCache")
```
## Interface
`LRU` supports the standard `AbstractDict` interface. Some examples of common
operations are shown below:
**Creation**
```julia
lru = LRU{K, V}(, maxsize = size [, by = ...] [,finalizer = ...])
```
Create an LRU Cache with a maximum size (number of items) specified by the *required*
keyword argument `maxsize`. Here, the size can be the number of elements (default), or the
maximal total size of the values in the dictionary, as counted by an arbitrary user
function (which should return a single value of type `Int`) specified with the keyword
argument `by`. Sensible choices would for example be `by = sizeof` for e.g. values which
are `Array`s of bitstypes, or `by = Base.summarysize` for values of some arbitrary user
type.
If `finalizer` is set, it is called for each entry that leaves the cache, with `key` and
`value` as arguments. This is useful if the cached values contain some resource that you
want to recover.
**Add an item to the cache**
```julia
setindex!(lru, value, key)
lru[key] = value
```
**Lookup an item in the cache**
```julia
getindex(lru, key)
lru[key]
```
**Change the maxsize**
```julia
resize!(lru; maxsize = size)
```
Here, the maximal size is specified via a required keyword argument. Remember that the
maximal size is not necessarily the same as the maximal length, if a custom function was
specified using the keyword argument `by` in the construction of the LRU cache.
**Empty the cache**
```julia
empty!(lru)
```
### Caching Use
To effectively use `LRU` as a cache, several functions from the `AbstractDict` interface
can be used for easy checking if an item is present, and if not quickly calculating a
default.
#### get!(lru::LRU, key, default)
Returns the value stored in `lru` for `key` if present. If not, stores `key =>
default`, and returns `default`.
#### get!(default::Callable, lru::LRU, key)
Like above, except if `key` is not present, stores `key => default()`, and
returns the result. This is intended to be used in `do` block syntax:
```julia
get!(lru, key) do
...
end
```
#### get(lru::LRU, key, default)
Returns the value stored in `lru` for `key` if present. If not, returns default without
storing this value in `lru`. Also comes in the following form:
#### get(default::Callable, lru::LRU, key)
#### cache_info(lru::LRU)
Returns an object holding a snapshot of information about hits, misses, current size, and total size in its properties.
The caching functions `get` and `get!` each contribute a cache hit or miss on every function call (depending on whether or not the key was found). `empty!` resets the counts of hits and misses to 0.
The other functions, e.g. `getindex` `iterate`, `haskey`, `setindex!`, `delete!`, and `pop!` do not contribute cache hits or misses, regardless of whether or not a key is retrieved. This is because it is not possible to use these functions for caching.
## Example
Commonly, you may have some long running function that sometimes gets called with the same
parameters more than once. As such, it may benefit from caching the results.
Here's our example, long running calculation:
```julia
function foo(a::Float64, b::Float64)
sleep(100)
result = a * b
end
```
As this function requires more than one parameter, we need a cache from
`(Float64, Float64)` to `Float64`. A cached version is then:
```julia
const lru = LRU{Tuple{Float64, Float64}, Float64}(maxsize=10)
function cached_foo(a::Float64, b::Float64)
get!(lru, (a, b)) do
foo(a,b)
end
end
```
If we want to see how our cache is performing, we can call `cache_info` to see the number of cache hits and misses.
| LRUCache | https://github.com/JuliaCollections/LRUCache.jl.git |
|
[
"MIT"
] | 0.3.5 | 91018794af6e76d2d42b96b25f5479bca52598f5 | code | 402 | using CodeInfoTools
using Documenter
makedocs(; modules=[CodeInfoTools], sitename="CodeInfoTools",
authors="McCoy R. Becker, Xiu-Zhe (Roger) Luo, and Valentin Churavy",
pages=["API Documentation" => "index.md"],
format = Documenter.HTML(prettyurls = true),
clean = true)
deploydocs(; repo="github.com/JuliaCompilerPlugins/CodeInfoTools.jl.git", push_preview=true)
| CodeInfoTools | https://github.com/JuliaCompilerPlugins/CodeInfoTools.jl.git |
|
[
"MIT"
] | 0.3.5 | 91018794af6e76d2d42b96b25f5479bca52598f5 | code | 289 | using JuliaFormatter
function main()
perfect = format(joinpath(@__DIR__, ".."); verbose=true)
if perfect
@info "Linting complete - no files altered"
else
@info "Linting complete - files altered"
run(`git status`)
end
return nothing
end
main()
| CodeInfoTools | https://github.com/JuliaCompilerPlugins/CodeInfoTools.jl.git |
|
[
"MIT"
] | 0.3.5 | 91018794af6e76d2d42b96b25f5479bca52598f5 | code | 20699 | module CodeInfoTools
using Core: CodeInfo
import Base: iterate,
push!,
pushfirst!,
insert!,
delete!,
getindex,
lastindex,
setindex!,
display,
+,
length,
identity,
isempty,
show
import Core.Compiler: AbstractInterpreter,
OptimizationState,
OptimizationParams
#####
##### Exports
#####
export code_info,
code_inferred,
walk,
var,
Variable,
slot,
get_slot,
Statement,
stmt,
Canvas,
Builder,
slot!,
return!,
renumber,
verify,
finish,
unwrap,
lambda,
λ
#####
##### Utilities
#####
const Variable = Core.SSAValue
var(id::Int) = Variable(id)
@doc(
"""
const Variable = Core.SSAValue
var(id::Int) = Variable(id)
Alias for `Core.SSAValue` -- represents a primitive register in lowered code. See the section of Julia's documentation on [lowered forms](https://docs.julialang.org/en/v1/devdocs/ast/#Lowered-form) for more information.
""", Variable)
Base.:(+)(v::Variable, id::Int) = Variable(v.id + id)
Base.:(+)(id::Int, v::Variable) = Variable(v.id + id)
function code_info(f, tt::Type{T}; generated=true, debuginfo=:default) where T <: Tuple
ir = code_lowered(f, tt; generated = generated, debuginfo = :default)
isempty(ir) && return nothing
return ir[1]
end
function code_info(f, t::Type...; generated = true, debuginfo = :default)
return code_info(f, Tuple{t...}; generated = generated, debuginfo = debuginfo)
end
@doc(
"""
code_info(f::Function, tt::Type{T}; generated = true, debuginfo = :default) where T <: Tuple
code_info(f::Function, t::Type...; generated = true, debuginfo = :default)
Return lowered code for function `f` with tuple type `tt`. Equivalent to `InteractiveUtils.@code_lowered` -- but a function call and requires a tuple type `tt` as input.
""", code_info)
slot(ind::Int) = Core.SlotNumber(ind)
function get_slot(ci::CodeInfo, s::Symbol)
ind = findfirst(el -> el == s, ci.slotnames)
ind === nothing && return
return slot(ind)
end
@doc(
"""
get_slot(ci::CodeInfo, s::Symbol)
Get the `Core.Compiler.SlotNumber` associated with the `s::Symbol` in `ci::CodeInfo`. If there is no associated `Core.Compiler.SlotNumber`, returns `nothing`.
""", get_slot)
walk(fn, x, guard) = fn(x)
walk(fn, x::Variable, guard) = fn(x)
walk(fn, x::Core.SlotNumber, guard) = fn(x)
walk(fn, x::Core.NewvarNode, guard) = Core.NewvarNode(walk(fn, x.slot, guard))
walk(fn, x::Core.ReturnNode, guard) = Core.ReturnNode(walk(fn, x.val, guard))
walk(fn, x::Core.GotoNode, guard) = Core.GotoNode(walk(fn, x.label, guard))
walk(fn, x::Core.GotoIfNot, guard) = Core.GotoIfNot(walk(fn, x.cond, guard), walk(fn, x.dest, guard))
walk(fn, x::Expr, guard) = Expr(x.head, map(a -> walk(fn, a, guard), x.args)...)
function walk(fn, x::Vector, guard)
map(x) do el
walk(fn, el, guard)
end
end
walk(fn, x) = walk(fn, x, Val(:no_catch))
@doc(
"""
walk(fn::Function, x)
A generic dispatch-based tree-walker which applies `fn::Function` to `x`, specialized to `Code` node types (like `Core.ReturnNode`, `Core.GotoNode`, `Core.GotoIfNot`, etc). Applies `fn::Function` to sub-fields of nodes, and then zips the result back up into the node.
""", walk)
resolve(x) = x
resolve(gr::GlobalRef) = getproperty(gr.mod, gr.name)
#####
##### Canvas
#####
struct Statement{T}
node::T
type::Any
end
Statement(node::T) where T = Statement(node, Union{})
unwrap(stmt::Statement) = stmt.node
walk(fn, stmt::Statement{T}, guard) where T = Statement(walk(fn, stmt.node, guard), stmt.type)
const stmt = Statement
@doc(
"""
struct Statement{T}
node::T
type::Any
end
A wrapper around `Core` nodes with an optional `type` field to allow for user-based local propagation and other forms of analysis. Usage of [`Builder`](@ref) or [`Canvas`](@ref) will automatically wrap or unwrap nodes when inserting or calling [`finish`](@ref) -- so the user should never see `Statement` instances directly unless they are working on type propagation.
For more information on `Core` nodes, please see Julia's documentation on [lowered forms](https://docs.julialang.org/en/v1/devdocs/ast/#Lowered-form).
""", Statement)
struct Canvas
defs::Vector{Tuple{Int, Int}}
code::Vector{Any}
codelocs::Vector{Int32}
end
Canvas() = Canvas(Tuple{Int, Int}[], [], Int32[])
Base.isempty(canv::Canvas) = Base.isempty(canv.defs)
@doc(
"""
```julia
struct Canvas
defs::Vector{Tuple{Int, Int}}
code::Vector{Any}
codelocs::Vector{Int32}
end
Canvas() = Canvas(Tuple{Int, Int}[], [], Int32[])
```
A `Vector`-like abstraction for `Core` code nodes.
Properties to keep in mind:
1. Insertion anywhere is slow.
2. Pushing to beginning is slow.
2. Pushing to end is fast.
3. Deletion is fast.
4. Accessing elements is fast.
5. Setting elements is fast.
Thus, if you build up a `Canvas` instance incrementally, everything should be fast.
""", Canvas)
length(c::Canvas) = length(filter(x -> x[2] > 0, c.defs))
function getindex(c::Canvas, idx::Int)
r, ind = c.defs[idx]
@assert ind > 0
getindex(c.code, r)
end
getindex(c::Canvas, v::Variable) = getindex(c, v.id)
function push!(c::Canvas, stmt::Statement)
push!(c.code, stmt)
push!(c.codelocs, Int32(1))
l = length(c.defs) + 1
push!(c.defs, (l, l))
return Variable(length(c.defs))
end
function push!(c::Canvas, node)
push!(c.code, Statement(node))
push!(c.codelocs, Int32(1))
l = length(c.defs) + 1
push!(c.defs, (l, l))
return Variable(length(c.defs))
end
function insert!(c::Canvas, idx::Int, x::Statement)
r, ind = c.defs[idx]
@assert(ind > 0)
push!(c.code, x)
push!(c.codelocs, Int32(1))
for i in 1 : length(c.defs)
r, k = c.defs[i]
if k > 0 && k >= ind
c.defs[i] = (r, k + 1)
end
end
push!(c.defs, (length(c.defs) + 1, ind))
return Variable(length(c.defs))
end
function insert!(c::Canvas, idx::Int, x)
r, ind = c.defs[idx]
@assert(ind > 0)
push!(c.code, Statement(x))
push!(c.codelocs, Int32(1))
for i in 1 : length(c.defs)
r, k = c.defs[i]
if k > 0 && k >= ind
c.defs[i] = (r, k + 1)
end
end
push!(c.defs, (length(c.defs) + 1, ind))
return Variable(length(c.defs))
end
insert!(c::Canvas, v::Variable, x) = insert!(c, v.id, x)
pushfirst!(c::Canvas, x) = isempty(c.defs) ? push!(c, x) : insert!(c, 1, x)
setindex!(c::Canvas, x::Statement, v::Int) = setindex!(c.code, x, v)
setindex!(c::Canvas, x, v::Int) = setindex!(c, Statement(x), v)
setindex!(c::Canvas, x, v::Variable) = setindex!(c, x, v.id)
function delete!(c::Canvas, idx::Int)
c.code[idx] = nothing
c.defs[idx] = (idx, -1)
return nothing
end
delete!(c::Canvas, v::Variable) = delete!(c, v.id)
_get(d::Dict, c, k) = c
_get(d::Dict, c::Variable, k) = haskey(d, c.id) ? Variable(getindex(d, c.id)) : nothing
function _get(d::Dict, c::Core.GotoIfNot, k)
v = c.dest
if haskey(d, v)
nv = getindex(d, v)
else
nv = findfirst(l -> l > v, d)
if nv === nothing
nv = maximum(d)[1]
end
nv = getindex(d, nv)
end
c = _get(d, c.cond, c.cond)
return Core.GotoIfNot(c, nv)
end
function _get(d::Dict, c::Core.GotoNode, k)
v = c.label
if haskey(d, v)
nv = getindex(d, v)
else
nv = findfirst(l -> l > v, d)
if nv === nothing
nv = maximum(d)[1]
end
nv = getindex(d, nv)
end
return Core.GotoNode(nv)
end
# Override for renumber.
walk(fn, c::Core.GotoIfNot, ::Val{:catch_jumps}) = fn(c)
walk(fn, c::Core.GotoNode, ::Val{:catch_jumps}) = fn(c)
function renumber(c::Canvas)
s = sort(filter(v -> v[2] > 0, c.defs); by = x -> x[2])
d = Dict((s[i][1], i) for i in 1 : length(s))
ind = first.(s)
swap = walk(k -> _get(d, k, k), c.code, Val(:catch_jumps))
return Canvas(Tuple{Int, Int}[(i, i) for i in 1 : length(s)],
getindex(swap, ind), getindex(c.codelocs, ind))
end
#####
##### Pretty printing
#####
print_stmt(io::IO, ex) = print(io, ex)
print_stmt(io::IO, ex::Expr) = print_stmt(io::IO, Val(ex.head), ex)
const tab = " "
function show(io::IO, c::Canvas)
indent = get(io, :indent, 0)
bs = get(io, :bindings, Dict())
for (r, ind) in sort(c.defs; by = x -> x[2])
ind > 0 || continue
println(io)
print(io, tab^indent, " ")
print(io, string("%", r), " = ")
ex = get(c.code, r, nothing)
ex == nothing ? print(io, "nothing") : print_stmt(io, unwrap(ex))
if unwrap(ex) isa Expr
ex.type !== Union{} && print(io, "::$(ex.type)")
end
end
end
print_stmt(io::IO, ::Val, ex) = print(io, ex)
function print_stmt(io::IO, ::Val{:enter}, ex)
print(io, "try (outer %$(ex.args[1]))")
end
function print_stmt(io::IO, ::Val{:leave}, ex)
print(io, "end try (start %$(ex.args[1]))")
end
function print_stmt(io::IO, ::Val{:pop_exception}, ex)
print(io, "pop exception $(ex.args[1])")
end
#####
##### Builder
#####
struct NewVariable
id::Int
end
mutable struct Builder
from::CodeInfo
to::Canvas
map::Dict{Any, Any}
slots::Vector{Symbol}
var::Int
end
function Builder(ci::CodeInfo)
canv = Canvas()
p = Builder(ci, canv, Dict(), Symbol[], 0)
return p
end
function Builder(fn::Function, t::Type...)
src = code_info(fn, t...)
return Builder(src)
end
function Builder()
dummy = () -> return
return Builder(dummy)
end
@doc(
"""
Builder(ci::Core.CodeInfo)
Builder(fn::Function, t::Type...)
Builder()
A wrapper around a [`Canvas`](@ref) instance. Call [`finish`](@ref) when done to produce a new `CodeInfo` instance.
""", Builder)
function get_slot(b::Builder, s::Symbol)
s = get_slot(b.from, s)
s === nothing || return s
ind = findfirst(k -> k == s, b.slots)
return ind === nothing ? s : slot(ind)
end
# This is used to handle NewVariable instances.
substitute!(b::Builder, x, y) = (b.map[x] = y; x)
substitute(b::Builder, x) = get(b.map, x, x)
substitute(b::Builder, x::Expr) = Expr(x.head, substitute.((b, ), x.args)...)
substitute(b::Builder, x::Core.GotoNode) = Core.GotoNode(substitute(b, x.label))
substitute(b::Builder, x::Core.GotoIfNot) = Core.GotoIfNot(substitute(b, x.cond), substitute(b, x.dest))
substitute(b::Builder, x::Core.ReturnNode) = Core.ReturnNode(substitute(b, x.val))
length(b::Builder) = length(b.to)
getindex(b::Builder, v) = getindex(b.to, v)
function getindex(b::Builder, v::Union{Variable, NewVariable})
tg = substitute(b, v)
return getindex(b.to, tg)
end
lastindex(b::Builder) = length(b.to)
function pipestate(ci::CodeInfo)
ks = sort([Variable(i) => v for (i, v) in enumerate(ci.code)], by = x -> x[1].id)
return first.(ks)
end
function iterate(b::Builder, (ks, i) = (pipestate(b.from), 1))
i > length(ks) && return
v = ks[i]
st = walk(resolve, b.from.code[v.id])
substitute!(b, v, push!(b.to, substitute(b, st)))
return ((v, st), (ks, i + 1))
end
@doc(
"""
iterate(b::Builder, (ks, i) = (pipestate(p.from), 1))
Iterate over the original `CodeInfo` and add statements to a target [`Canvas`](@ref) held by `b::Builder`. `iterate` builds the [`Canvas`](@ref) in place -- it also resolves local `GlobalRef` instances to their global values in-place at the function argument (the 1st argument) of `Expr(:call, ...)` instances. `iterate` is the key to expressing idioms like:
```julia
for (v, st) in b
b[v] = swap(st)
end
```
At each step of the iteration, a new node is copied from the original `CodeInfo` to the target [`Canvas`](@ref) -- and the user is allowed to `setindex!`, `push!`, or otherwise change the target [`Canvas`](@ref) before the next iteration. The naming of `Core.SSAValues` is taken care of to allow this.
""", iterate)
var!(b::Builder) = NewVariable(b.var += 1)
function Base.push!(b::Builder, x)
tmp = var!(b)
v = push!(b.to, substitute(b, x))
substitute!(b, tmp, v)
return tmp
end
function Base.pushfirst!(b::Builder, x)
tmp = var!(b)
v = pushfirst!(b.to, substitute(b, x))
substitute!(b, tmp, v)
return tmp
end
function setindex!(b::Builder, x, v::Union{Variable, NewVariable})
k = substitute(b, v)
setindex!(b.to, substitute(b, x), k)
end
function insert!(b::Builder, v::Union{Variable, NewVariable}, x; after = false)
v′ = substitute(b, v).id
x = substitute(b, x)
tmp = var!(b)
substitute!(b, tmp, insert!(b.to, v′ + after, x))
return tmp
end
function Base.delete!(b::Builder, v::Union{Variable, NewVariable})
v′ = substitute(b, v)
substitute!(b, v′, delete!(b.to, v′))
end
function slot!(b::Builder, name::Symbol; arg = false)
@assert(get_slot(b, name) === nothing)
push!(b.slots, name)
ind = length(b.from.slotnames) + length(b.slots)
s = slot(ind)
arg || pushfirst!(b, Core.NewvarNode(s))
return s
end
@doc(
"""
slot!(b::Builder, name::Symbol; arg = false)::Core.SlotNumber
Add a new `Core.SlotNumber` with associated `name::Symbol` to the in-progress `Core.CodeInfo` on the `c::Canvas` inside `b::Builder`. If `arg == false`, also performs a `pushfirst!` with a `Core.NewvarNode` for consistency in the in-progress `Core.CodeInfo`. (`arg` controls whether or not we interpreter the new slot as an argument)
`name::Symbol` must not already be associated with a `Core.SlotNumber`.
""", slot!)
return!(b::Builder, v) = push!(b, Core.ReturnNode(v))
return!(b::Builder, v::Variable) = push!(b, Core.ReturnNode(v))
return!(b::Builder, v::NewVariable) = push!(b, Core.ReturnNode(v))
@doc(
"""
return!(b::Builder, v::Variable)
return!(b::Builder, v::NewVariable)
Push a `Core.ReturnNode` to the current end of `b.to::Canvas`. Requires that the user pass in a `v::Variable` or `v::NewVariable` instance -- so perform the correct unpack/tupling before creating a `Core.ReturnNode`.
""", return!)
function verify(src::Core.CodeInfo)
Core.Compiler.validate_code(src)
@assert(!isempty(src.linetable))
end
@doc(
"""
verify(src::Core.CodeInfo)
Validate `Core.CodeInfo` instances using `Core.Compiler.verify`. Also explicitly checks that the linetable in `src::Core.CodeInfo` is not empty.
""", verify)
function check_empty_canvas(b::Builder)
isempty(b.to) && error("Builder has empty `c::Canvas` instance. This means you haven't added anything, or you've accidentally wiped the :defs subfield of `c::Canvas`.")
end
function finish(b::Builder; validate = true)
check_empty_canvas(b)
new_ci = copy(b.from)
c = renumber(b.to)
new_ci.code = map(unwrap, c.code)
new_ci.codelocs = c.codelocs
new_ci.slotnames = copy(b.from.slotnames)
append!(new_ci.slotnames, b.slots)
new_ci.slotflags = copy(b.from.slotflags)
append!(new_ci.slotflags, [0x18 for _ in b.slots])
new_ci.inferred = false
new_ci.inlineable = b.from.inlineable
new_ci.ssavaluetypes = length(b.to)
validate && verify(new_ci)
return new_ci
end
@doc(
"""
finish(b::Builder)
Create a new `CodeInfo` instance from a [`Builder`](@ref). Renumbers the wrapped [`Canvas`](@ref) in-place -- then copies information from the original `CodeInfo` instance and inserts modifications from the wrapped [`Canvas`](@ref)
""", finish)
function Base.show(io::IO, b::Builder)
print("1: $((b.from.slotnames..., b.slots...))")
Base.show(io, b.to)
end
function Base.identity(b::Builder)
for (v, st) in b
end
return b
end
#####
##### Inference
#####
# Experimental interfaces which exposes several **stateful** parts of Core.Compiler.
# If you're using this stuff, you should really know what you're doing.
function code_inferred(mi::Core.Compiler.MethodInstance;
world=Base.get_world_counter(),
interp=Core.Compiler.NativeInterpreter(world))
ccall(:jl_typeinf_begin, Cvoid, ())
result = Core.Compiler.InferenceResult(mi)
src = Core.Compiler.retrieve_code_info(mi)
src === nothing && return nothing
src.inferred && return src
Core.Compiler.validate_code_in_debug_mode(result.linfo,
src, "lowered")
frame = @static if VERSION < v"1.8.0-DEV.472"
Core.Compiler.InferenceState(result, src, false, interp)
else
Core.Compiler.InferenceState(result, src, :no, interp)
end
frame === nothing && return nothing
if Core.Compiler.typeinf(interp, frame)
opt_params = Core.Compiler.OptimizationParams(interp)
opt = Core.Compiler.OptimizationState(frame, opt_params, interp)
Core.Compiler.optimize(interp, opt, opt_params, result)
end
ccall(:jl_typeinf_end, Cvoid, ())
frame.inferred || return nothing
return src
end
function code_inferred(@nospecialize(f), types::Type{T};
world=Base.get_world_counter(),
interp=Core.Compiler.NativeInterpreter(world)) where T <: Tuple
return pop!([code_inferred(mi; world=world, interp=interp)
for mi in Base.method_instances(f, types, world)])
end
function code_inferred(@nospecialize(f), t::Type...;
world = Base.get_world_counter(),
interp = Core.Compiler.NativeInterpreter(world))
return code_inferred(f, Tuple{t...};
world = world, interp = interp)
end
@doc(
"""
code_inferred(@nospecialize(f), t::Type...;
world = Base.get_world_counter(),
interp = Core.Compiler.NativeInterpreter(world))
Derives a `Core.MethodInstance` specialization for signature `Tuple{typeof(f), t::Type...}` and infers it with `interp`. Can be used to derive inferred lowered code with custom interpreters, either as parts of custom compilation pipelines or for debugging purposes.
`code_inferred` includes explicit checks which prevent the user from inadvertedly running inference multiple times on the same cached `Core.CodeInfo` associated with the specialization.
!!! warning
Inference and optimization are stateful -- if you try to do "dumb" things like grab the inferred `Core.CodeInfo`, wipe it, and shove it through [`lambda`](@ref) ... it is highly unlikely to work and very likely to explode in your face.
Inference also caches the inferred `Core.CodeInfo` associated with the `Core.MethodInstance` specialization _irrespective of the interpreter_. That means (at least as far as I know at this time) you can't quickly infer with multiple interpreters without forcing a cache invalidation in between inference runs.
""", code_inferred)
#####
##### Evaluation
#####
function lambda(m::Module, src::Core.CodeInfo)
ci = copy(src)
verify(ci)
inds = findall(==(0x00), src.slotflags)
@assert(inds !== nothing)
args = getindex(src.slotnames, inds)[2 : end]
@eval m @generated function $(gensym())($(args...))
return $ci
end
end
function lambda(m::Module, src::Core.CodeInfo, nargs::Int)
ci = copy(src)
verify(ci)
@debug "Warning: using explicit `nargs` to construct the generated function. If this number does not match the correct number of arguments in the :slotflags field of `src::Core.CodeInfo`, this can lead to segfaults and other bad behavior."
args = src.slotnames[2 : 1 + nargs]
@eval m @generated function $(gensym())($(args...))
return $ci
end
end
lambda(src::Core.CodeInfo) = lambda(Main, src)
lambda(src::Core.CodeInfo, nargs::Int) = lambda(Main, src, nargs)
const λ = lambda
@doc(
"""
!!! warning
It is relatively difficult to prevent the user from shooting themselves in the foot with this sort of functionality. Please be aware of this. Segfaults should be cautiously expected.
```julia
lambda(m::Module, src::Core.CodeInfo)
lambda(m::Module, src::Core.CodeInfo, nargs::Int)
const λ = lambda
```
Create an anonymous `@generated` function from a piece of `src::Core.CodeInfo`. The `src::Core.CodeInfo` is checked for consistency by [`verify`](@ref).
`lambda` has a 2 different forms. The first form, given by signature:
```julia
lambda(m::Module, src::Core.CodeInfo)
```
tries to detect the correct number of arguments automatically. This may fail (for any number of internal reasons). Expecting this, the second form, given by signature:
```julia
lambda(m::Module, src::Core.CodeInfo, nargs::Int)
```
allows the user to specify the number of arguments via `nargs`.
`lambda` also has the shorthand `λ` for those lovers of Unicode.
""", lambda)
end # module
| CodeInfoTools | https://github.com/JuliaCompilerPlugins/CodeInfoTools.jl.git |
|
[
"MIT"
] | 0.3.5 | 91018794af6e76d2d42b96b25f5479bca52598f5 | code | 3418 | #####
##### Builder
#####
f(x) = begin
y = 10 + x
z = 20 + y
q = 20 + z
return q + 50
end
function g(x)
try
if x > 1
x + g(x - 1)
else
return 1
end
while true
println("Nice!")
end
return
catch e
return 0
end
end
function fn(x, y)
z = 10
if z > 10
n = 10
return x + y
else
return x + y + z
end
end
@testset "Builder -- iterate" begin
ir = code_info(f, Tuple{Int})
p = CodeInfoTools.Builder(ir)
local c = 1
for (v, st) in p
@test v == var(c)
println(getindex(p, v))
c += 1
end
ir = code_info(g, Tuple{Int})
p = CodeInfoTools.Builder(ir)
c = 1
for (v, st) in p
@test v == var(c)
c += 1
end
end
@testset "Builder -- setindex!" begin
ir = code_info(f, Tuple{Int})
p = CodeInfoTools.Builder(ir)
len = length(p.from.code)
for (v, st) in p
p[v] = st
end
ir = finish(p)
@test length(p.to.code) == len
for (v, st) in CodeInfoTools.Builder(ir)
st isa Expr && st.head == :call || continue
@test st.args[1] == Base.:(+)
end
ir = code_info(g, Tuple{Int})
p = CodeInfoTools.Builder(ir)
len = length(p.from.code)
for (v, st) in p
p[v] = st
end
ir = finish(p)
@test length(p.to.code) == len
for (v, st) in CodeInfoTools.Builder(ir)
st isa Expr && st.head == :call || continue
@test (st.args[1] in (g, Base.:(+), Base.:(-), Base.:(>), Base.println))
end
end
@testset "Builder -- push!" begin
ir = code_info(f, Tuple{Int})
p = CodeInfoTools.Builder(ir)
c = deepcopy(p.from.code)
for (v, st) in p
end
push!(p, Expr(:call, rand))
@test length(p.to.code) == length(c) + 1
push!(p, Expr(:call, rand))
@test length(p.to.code) == length(c) + 2
push!(p, Expr(:call, rand))
@test length(p.to.code) == length(c) + 3
@test unwrap(p[end - 3]) isa Core.ReturnNode
ir = code_info(g, Tuple{Int})
p = CodeInfoTools.Builder(ir)
c = deepcopy(p.from.code)
for (v, st) in p
end
push!(p, Expr(:call, rand))
@test length(p.to.code) == length(c) + 1
push!(p, Expr(:call, rand))
@test length(p.to.code) == length(c) + 2
push!(p, Expr(:call, rand))
@test length(p.to.code) == length(c) + 3
@test unwrap(p[end - 3]) isa Core.ReturnNode
end
@testset "Builder -- pushfirst!" begin
ir = code_info(f, Tuple{Int})
p = CodeInfoTools.Builder(ir)
push!(p, Expr(:call, rand))
@test length(p.to.code) == 1
pushfirst!(p, Expr(:call, rand))
@test length(p.to.code) == 2
pushfirst!(p, Expr(:call, rand))
@test length(p.to.code) == 3
ir = code_info(g, Tuple{Int})
p = CodeInfoTools.Builder(ir)
push!(p, Expr(:call, rand))
@test length(p.to.code) == 1
pushfirst!(p, Expr(:call, rand))
@test length(p.to.code) == 2
pushfirst!(p, Expr(:call, rand))
@test length(p.to.code) == 3
end
@testset "Builder -- delete!" begin
ir = code_info(f, Tuple{Int})
p = CodeInfoTools.Builder(ir)
for (v, st) in p
end
display(p)
println()
delete!(p, var(1))
display(p)
println()
insert!(p, var(2), Expr(:call, rand))
display(p)
println()
display(renumber(p.to))
println()
display(finish(p))
println()
end
| CodeInfoTools | https://github.com/JuliaCompilerPlugins/CodeInfoTools.jl.git |
|
[
"MIT"
] | 0.3.5 | 91018794af6e76d2d42b96b25f5479bca52598f5 | code | 3879 | #####
##### Canvas
#####
@testset "Canvas -- push!" begin
c = Canvas()
@test Variable(1) == push!(c, Statement(Expr(:call, rand)))
@test Variable(2) == push!(c, Expr(:call, rand))
@test Variable(3) == push!(c, Expr(:call, rand))
@test Variable(4) == push!(c, Expr(:call, rand))
@test Variable(5) == push!(c, Expr(:call, rand))
@test length(c) == 5
for i in 1 : 5
@test c.defs[i] == (i, i)
@test c.codelocs[i] == Int32(1)
@test unwrap(getindex(c, i)) == Expr(:call, rand)
end
end
@testset "Canvas -- insert!" begin
c = Canvas()
@test Variable(1) == push!(c, Expr(:call, rand))
@test Variable(2) == insert!(c, 1, Statement(Expr(:call, rand)))
@test Variable(3) == insert!(c, 1, Expr(:call, rand))
@test Variable(4) == insert!(c, 1, Expr(:call, rand))
@test Variable(5) == insert!(c, 1, Expr(:call, rand))
@test length(c) == 5
v = [5, 1, 2, 3, 4]
for i in 1 : 5
@test c.defs[i][2] == v[i]
end
c = Canvas()
@test Variable(1) == push!(c, Expr(:call, rand))
@test Variable(2) == pushfirst!(c, Expr(:call, rand))
@test Variable(3) == pushfirst!(c, Expr(:call, rand))
@test Variable(4) == pushfirst!(c, Expr(:call, rand))
@test Variable(5) == pushfirst!(c, Expr(:call, rand))
@test length(c) == 5
for i in 1 : 5
@test c.defs[i][1] == i
end
end
@testset "Canvas -- delete!" begin
c = Canvas()
push!(c, Expr(:call, +, 5, 5))
push!(c, Expr(:call, +, 10, 10))
push!(c, Expr(:call, +, 15, 15))
push!(c, Expr(:call, +, 20, 20))
push!(c, Expr(:call, +, 25, 25))
delete!(c, 4)
@test c.defs == [(1,1), (2,2), (3,3), (4, -1), (5, 5)]
@test unwrap(c[1]) == Expr(:call, +, 5, 5)
@test unwrap(c[2]) == Expr(:call, +, 10, 10)
@test unwrap(c[3]) == Expr(:call, +, 15, 15)
@test unwrap(c[5]) == Expr(:call, +, 25, 25)
push!(c, Expr(:call, +, 10, 10))
delete!(c, 4)
@test c.defs == [(1,1), (2,2), (3,3), (4, -1), (5, 5), (6, 6)]
@test unwrap(c[1]) == Expr(:call, +, 5, 5)
@test unwrap(c[2]) == Expr(:call, +, 10, 10)
@test unwrap(c[3]) == Expr(:call, +, 15, 15)
@test unwrap(c[6]) == Expr(:call, +, 10, 10)
end
@testset "Canvas -- setindex!" begin
c = Canvas()
push!(c, Expr(:call, +, 5, 5))
pushfirst!(c, Expr(:call, +, 10, 10))
pushfirst!(c, Expr(:call, +, 15, 15))
pushfirst!(c, Expr(:call, +, 20, 20))
pushfirst!(c, Expr(:call, +, 25, 25))
@test unwrap(getindex(c, 1)) == Expr(:call, +, 5, 5)
setindex!(c, Expr(:call, *, 10, 10), 1)
@test unwrap(getindex(c, 1)) == Expr(:call, *, 10, 10)
@test unwrap(getindex(c, 2)) == Expr(:call, +, 10, 10)
setindex!(c, Expr(:call, *, 5, 5), 2)
@test unwrap(getindex(c, 2)) == Expr(:call, *, 5, 5)
@test unwrap(getindex(c, 3)) == Expr(:call, +, 15, 15)
setindex!(c, Expr(:call, *, 10, 10), 3)
@test unwrap(getindex(c, 3)) == Expr(:call, *, 10, 10)
end
@testset "Canvas -- renumber" begin
c = Canvas()
push!(c, Expr(:call, +, 5, 5))
pushfirst!(c, Expr(:call, +, 10, 10))
pushfirst!(c, Expr(:call, +, 15, 15))
pushfirst!(c, Expr(:call, +, 20, 20))
pushfirst!(c, Expr(:call, +, 25, 25))
delete!(c, 4)
display(c)
println()
c = renumber(c)
display(c)
println()
@test c.defs == [(1, 1), (2, 2), (3, 3), (4, 4)]
@test unwrap(c[1]) == Expr(:call, +, 10, 10)
@test unwrap(c[2]) == Expr(:call, +, 15, 15)
@test unwrap(c[3]) == Expr(:call, +, 25, 25)
@test unwrap(c[4]) == Expr(:call, +, 5, 5)
end
@testset "Canvas -- misc." begin
c = Canvas()
push!(c, Expr(:call, +, 5, 5))
pushfirst!(c, Expr(:call, +, 10, 10))
pushfirst!(c, Expr(:call, +, 15, 15))
pushfirst!(c, Expr(:call, +, 20, 20))
pushfirst!(c, Expr(:call, +, 25, 25))
insert!(c, var(1), Expr(:call, rand))
end
| CodeInfoTools | https://github.com/JuliaCompilerPlugins/CodeInfoTools.jl.git |
|
[
"MIT"
] | 0.3.5 | 91018794af6e76d2d42b96b25f5479bca52598f5 | code | 1723 | #####
##### Evaluation
#####
function thunk()
return 120
end
@testset "Evaluation - slots = (#self)" begin
b = Builder(code_info(thunk))
identity(b)
fn = λ(finish(b))
@test thunk() == fn()
end
function foo(x::Int)
y = 0
while x > 10
y += 1
x -= 1
end
return y
end
@testset "Evaluation - slots = (#self, :x)" begin
b = Builder(code_info(foo, Int))
identity(b)
fn = λ(finish(b))
@test foo(5) == fn(5)
end
@testset "Evaluation with nargs - slots = (#self, :x)" begin
b = Builder(code_info(foo, Int))
identity(b)
fn = λ(finish(b), 1)
@test foo(5) == fn(5)
end
foo(x::Int64, y, z) = x <= 1 ? 1 : x * foo(x - 1, y, z)
@testset "Evaluation with nargs - slots = (#self, :x, :y, :z)" begin
b = Builder(code_info(foo, Int, Any, Any))
identity(b)
fn = λ(finish(b), 3)
@test foo(5, nothing, nothing) == fn(5, nothing, nothing)
end
rosenbrock(x, y, a, b) = (a - x)^2 + b * (y - x^2)^2
@testset "Evaluation with nargs - slots = (#self, :x, :y, :a, :b)" begin
b = Builder(code_info(rosenbrock, Float64, Float64,
Float64, Float64))
identity(b)
fn = λ(finish(b), 4)
@test rosenbrock(1.0, 1.0, 1.0, 1.0) == fn(1.0, 1.0, 1.0, 1.0)
end
@testset "Evaluation with nargs -- from lambda" begin
l = (x, y) -> x + y
b = Builder(l, Int, Int)
identity(b)
fn = λ(finish(b), 2)
@test l(5, 5) == fn(5, 5)
end
@testset "Evaluation with nargs -- blank build" begin
b = Builder()
x = slot!(b, :x; arg = true)
y = slot!(b, :y; arg = true)
v = push!(b, Expr(:call, Base.:(+), x, y))
return!(b, v)
src = finish(b)
fn = λ(src, 2)
@test fn(5, 5) == 10
end
| CodeInfoTools | https://github.com/JuliaCompilerPlugins/CodeInfoTools.jl.git |
|
[
"MIT"
] | 0.3.5 | 91018794af6e76d2d42b96b25f5479bca52598f5 | code | 1964 | #####
##### Misc (usually for coverage)
#####
@testset "Base.:(+) -- SSAValues" begin
@test (+)(Core.SSAValue(1), 1) == Core.SSAValue(2)
@test (+)(1, Core.SSAValue(1)) == Core.SSAValue(2)
end
@testset "`walk` -- misc." begin
v = Core.NewvarNode(Core.SlotNumber(5))
walk(x -> x isa Core.SlotNumber ?
Core.SlotNumber(x.id + 1) : x, v)
end
@testset "Builder -- misc." begin
ir = code_info(g, Int)
p = CodeInfoTools.Builder(ir)
for (v, st) in p
end
display(p)
p = CodeInfoTools.Builder(ir)
p = identity(p)
get_slot(p, :x)
println()
println(length(p))
println()
slot!(p, :m)
get_slot(p, :m)
end
@testset "code_info on constructor -- misc." begin
struct T
i::Int
end
ir = code_info(T, Int)
@test Meta.isexpr(ir.code[1], :new)
end
@testset "code_inferred -- misc." begin
b = CodeInfoTools.Builder(g, Int)
identity(b)
l = λ(finish(b), 1)
src = code_inferred(l, Int)
display(src)
end
@testset "Coverage removal -- misc." begin
b = CodeInfoTools.Builder()
push!(b, Expr(:code_coverage_effect))
push!(b, Expr(:code_coverage_effect))
push!(b, Expr(:code_coverage_effect))
push!(b, Expr(:code_coverage_effect))
push!(b, Expr(:call, :foo, 2))
v = push!(b, Expr(:call, :measure, 2))
push!(b, Expr(:code_coverage_effect))
push!(b, Expr(:code_coverage_effect))
k = push!(b, Expr(:call, :measure_cmp, v, 1))
push!(b, Core.GotoIfNot(k, 14))
push!(b, Expr(:code_coverage_effect))
push!(b, Expr(:code_coverage_effect))
push!(b, Expr(:call, :foo, 2))
push!(b, Expr(:code_coverage_effect))
push!(b, Core.GotoNode(14))
return!(b, nothing)
start = finish(b)
display(start)
new = CodeInfoTools.Builder(start)
for (v, st) in new
if st isa Expr && st.head == :code_coverage_effect
delete!(new, v)
end
end
src = finish(new)
display(src)
end
| CodeInfoTools | https://github.com/JuliaCompilerPlugins/CodeInfoTools.jl.git |
|
[
"MIT"
] | 0.3.5 | 91018794af6e76d2d42b96b25f5479bca52598f5 | code | 159 | module TestCodeInfoTools
using CodeInfoTools
using Test
include("canvas.jl")
include("builder.jl")
include("evaluation.jl")
include("misc.jl")
end # module
| CodeInfoTools | https://github.com/JuliaCompilerPlugins/CodeInfoTools.jl.git |
|
[
"MIT"
] | 0.3.5 | 91018794af6e76d2d42b96b25f5479bca52598f5 | docs | 4009 | # CodeInfoTools.jl
| **Build Status** | **Coverage** | **Documentation** |
|:------------------------------------------------------:|:-------------------------------:|:-----------------:|
| [![][gha-ci-img]][gha-url] [![][gha-nightly-img]][gha-url] | [![][codecov-img]][codecov-url] | [![][dev-docs-img]][dev-docs-url] |
[gha-ci-img]: https://github.com/JuliaCompilerPlugins/CodeInfoTools.jl/workflows/CI/badge.svg?branch=master
[gha-nightly-img]: https://github.com/JuliaCompilerPlugins/CodeInfoTools.jl/workflows/JuliaNightly/badge.svg?branch=master
[gha-url]: https://github.com/JuliaCompilerPlugins/CodeInfoTools.jl/actions
[codecov-img]: https://codecov.io/github/JuliaCompilerPlugins/CodeInfoTools.jl/badge.svg?branch=master
[codecov-url]: https://codecov.io/github/JuliaCompilerPlugins/CodeInfoTools.jl?branch=master
[dev-docs-img]: https://img.shields.io/badge/docs-dev-blue.svg
[dev-docs-url]: https://JuliaCompilerPlugins.github.io/CodeInfoTools.jl/dev
```
] add CodeInfoTools
```
> **Note**: A curated collection of tools for the discerning `Core.CodeInfo` connoisseur.
>
> The architecture of this package is based closely on the [Pipe construct in IRTools.jl](https://github.com/FluxML/IRTools.jl/blob/1f3f43be654a41d0db154fd16b31fdf40f30748c/src/ir/ir.jl#L814-L973). Many (if not all) of the same idioms apply.
## Motivation
Working with `Core.CodeInfo` is often not fun. E.g. when examining the untyped lowered form of the [Rosenbrock function](https://en.wikipedia.org/wiki/Rosenbrock_function)
```
CodeInfo(
@ /Users/mccoybecker/dev/CodeInfoTools.jl/examples/simple.jl:7 within `rosenbrock'
1 ─ a = 1.0
│ b = 100.0
│ result = 0.0
│ %4 = (length)(x)
│ %5 = (-)(%4, 1)
│ %6 = (Colon())(1, %5)
│ @_3 = (iterate)(%6)
│ %8 = (===)(@_3, nothing)
│ %9 = (Core.Intrinsics.not_int)(%8)
└── goto #4 if not %9
2 ┄ %11 = @_3
│ i = (getfield)(%11, 1)
│ %13 = (getfield)(%11, 2)
│ .
│ .
│ .
│
│ %36 = (===)(@_3, nothing)
│ %37 = (Core.Intrinsics.not_int)(%36)
└── goto #4 if not %37
3 ─ goto #2
4 ┄ return result
)
```
Do you ever wonder -- is there another (perhaps, any) way to work with this object? A `Builder` perhaps? Where I might load my `CodeInfo` into -- iterate, make local changes, and produce a new copy?
## Contribution
`CodeInfoTools.jl` provides a `Builder` abstraction which allows you to safely iterate over and manipulate `Core.CodeInfo`. It also provides more advanced functionality for creating and evaluating `Core.CodeInfo` -- [which is a bit on the experimental side.](https://juliacompilerplugins.github.io/CodeInfoTools.jl/dev/#Evaluation)
How might you use this in practice?
```julia
using CodeInfoTools
function f(x, y)
z = 10
if z > 10
n = 10
return x + y
else
return x + y + z
end
end
src = code_info(f, Int, Int)
function transform(src)
b = CodeInfoTools.Builder(src)
for (v, st) in b
st isa Expr || continue
st.head == :call || continue
st.args[1] == Base.:(+) || continue
b[v] = Expr(:call, Base.:(*), st.args[2:end]...)
end
return finish(b)
end
display(src)
display(transform(src))
```
Here, we've lowered a function directly to a `Core.CodeInfo` instance and created a `Builder` instance `b`. You can now safely iterate over this object, perform local changes, press `finish` and - _(la di da!)_ - out comes a new `Core.CodeInfo` with your changes fresh.
```
# Before:
CodeInfo(
1 ─ Core.NewvarNode(:(n))
│ z = 10
│ %3 = z > 10
└── goto #3 if not %3
2 ─ n = 10
│ %6 = x + y
└── return %6
3 ─ %8 = x + y + z
└── return %8
)
# After:
CodeInfo(
1 ─ Core.NewvarNode(:(n))
│ z = 10
│ %3 = (>)(z, 10)
└── goto #3 if not %3
2 ─ n = 10
│ %6 = (*)(x, y)
└── return %6
3 ─ %8 = (*)(x, y, z)
└── return %8
)
```
| CodeInfoTools | https://github.com/JuliaCompilerPlugins/CodeInfoTools.jl.git |
|
[
"MIT"
] | 0.3.5 | 91018794af6e76d2d42b96b25f5479bca52598f5 | docs | 396 | # API Documentation
Below is the API documentation for [CodeInfoTools.jl](https://github.com/JuliaCompilerPlugins/CodeInfoTools.jl)
```@meta
CurrentModule = CodeInfoTools
```
## Utilities
```@docs
code_info
walk
get_slot
code_inferred
```
## Working with `Core.CodeInfo`
```@docs
Variable
Statement
Canvas
Builder
slot!
return!
iterate
verify
finish
```
## Evaluation
```@docs
lambda
```
| CodeInfoTools | https://github.com/JuliaCompilerPlugins/CodeInfoTools.jl.git |
|
[
"MIT"
] | 1.0.0 | 6e4e531a8ba163d95a38ab1de41c655812dc9e7d | code | 1964 | module ResistanceDistance
using Graphs: laplacian_matrix,nv
using LinearAlgebra: pinv,det
export resistance_distance_matrix,resistance_distance
"""
resistance_distance_matrix(g)
Calculate the resistance distance matrix for a graph.
# Arguments
- `g`: The graph for which the resistance distance matrix is to be calculated.
# Returns
- A matrix where the element at the i-th row and j-th column represents the resistance distance between nodes `i` and `j`.
# Notes
- The resistance distance matrix is calculated using the formula for resistance distance in terms of the Laplacian matrix of the graph.
- The Laplacian matrix of the graph is calculated using the `laplacian_matrix` function.
- The pseudoinverse of the Laplacian matrix is calculated using the `pinv` function from the LinearAlgebra module.
"""
function resistance_distance_matrix(g)
il=pinv(Matrix(laplacian_matrix(g)))
out=zeros(Float64,(nv(g),nv(g)))
for i in axes(out,1)
for j in axes(out,2)
if j>=i
break
end
out[i,j]=il[i,i]+il[j,j]-2il[i,j]
out[j,i]=out[i,j]
end
end
return out
end
"""
resistance_distance(g, i::Int64, j::Int64)
Calculate the resistance distance between two nodes in a graph.
# Arguments
- `g`: The graph in which the resistance distance is to be calculated.
- `i`: The first node.
- `j`: The second node.
# Returns
- The resistance distance between nodes `i` and `j`.
# Notes
- Implements:
Bapat, Ravindra B., Gutmana, Ivan and Xiao, Wenjun. "A Simple Method for Computing Resistance Distance" Zeitschrift für Naturforschung A, vol. 58, no. 9-10, 2003, pp. 494-498. https://doi.org/10.1515/zna-2003-9-1003
"""
function resistance_distance(g,i::Int64,j::Int64)
if i==j
return 0
end
lg=laplacian_matrix(g)
return det(@view lg[setdiff(1:end, [i,j]), setdiff(1:end, [i,j])])/det(@view lg[setdiff(1:end, i), setdiff(1:end, i)])
end
end | ResistanceDistance | https://github.com/jeanfdp/ResistanceDistance.jl.git |
|
[
"MIT"
] | 1.0.0 | 6e4e531a8ba163d95a38ab1de41c655812dc9e7d | code | 1060 | using ResistanceDistance,Graphs
using Test
# Define a custom tolerance
tolerance = 1e-6
@testset "ResistanceDistance.jl" begin
@testset "resistance_distance_matrix function" begin
# Create a test graph
g = ladder_graph(2)
# Calculate the resistance distance matrix
matrix = resistance_distance_matrix(g)
# Define the expected result
expected = [0.0 0.75 0.75 1.0
0.75 0.0 1.0 0.75
0.75 1.0 0.0 0.75
1.0 0.75 0.75 0.0]
# Test that the function returns the expected result
@test isapprox(matrix, expected, atol=tolerance)
end
@testset "resistance_distance function" begin
# Create a test graph
g = ladder_graph(2)
# Calculate the resistance distance between nodes 1 and 2
distance = resistance_distance(g,1,2)
# Define the expected result
expected = 0.75
# Test that the function returns the expected result
@test isapprox(distance, expected, atol=tolerance)
end
end
| ResistanceDistance | https://github.com/jeanfdp/ResistanceDistance.jl.git |
|
[
"MIT"
] | 1.0.0 | 6e4e531a8ba163d95a38ab1de41c655812dc9e7d | docs | 2264 | # ResistanceDistance.jl
This is a Julia package for calculating the resistance distance matrix of a graph.
## Installation
To install the package, use the following command in the Julia package manager:
```julia
using Pkg
Pkg.add(url="https://github.com/jeanfdp/ResistanceDistance.jl")
```
## Usage
This package provides functions to calculate resistance distances in a graph. You can use the following functions in your Julia code:
### `resistance_distance_matrix(g)`
This function calculates the resistance distance matrix for a given graph, which represents the resistance distances between all pairs of nodes in the graph.
#### Arguments
- `g`: The graph for which the resistance distance matrix is to be calculated.
#### Returns
- A matrix where the element at the i-th row and j-th column represents the resistance distance between nodes `i` and `j`.
#### Example
```julia
using Graphs,ResistanceDistance
# Create a graph (replace with your own graph creation code)
g = ladder_graph(4)
# Calculate the resistance distance matrix
matrix = resistance_distance_matrix(g)
println(matrix)
```
### `resistance_distance(g, i::Int64, j::Int64)`
This function calculates the resistance distance between two nodes in a graph.
#### Arguments
- `g`: The graph in which the resistance distance is to be calculated.
- `i`: The first node.
- `j`: The second node.
#### Returns
- The resistance distance between nodes `i` and `j`.
#### Example
```julia
using Graphs,ResistanceDistance
# Create a graph (replace with your own graph creation code)
g = ladder_graph(4)
# Calculate the resistance distance between nodes 1 and 5
distance = resistance_distance(g, 1, 5)
println("Resistance Distance between Node 1 and Node 5: $distance")
```
### References
- The package implements the resistance distance calculation method described in the paper: "A Simple Method for Computing Resistance Distance" by Bapat, Ravindra B., Gutman, Ivan, and Xiao, Wenjun. You can find the paper at [this link](https://doi.org/10.1515/zna-2003-9-1003).
[](https://github.com/jeanfdp/ResistanceDistance.jl/actions/workflows/CI.yml?query=branch%3Amaster)
| ResistanceDistance | https://github.com/jeanfdp/ResistanceDistance.jl.git |
|
[
"MIT"
] | 0.2.0 | d1a06655265b3ca5a4af73ecdd1a3d60e04711f6 | code | 958 | using Documenter
using PiGPIO
using Literate
Literate.markdown(joinpath(@__DIR__, "..", "examples", "01_blink.jl"), joinpath(@__DIR__, "src", "examples"))
Literate.markdown(joinpath(@__DIR__, "..", "examples", "02_blink_twice.jl"),joinpath(@__DIR__, "src", "examples"))
Literate.markdown(joinpath(@__DIR__, "..", "examples", "03_rgb.jl"), joinpath(@__DIR__, "src", "examples"))
makedocs(
sitename = "PiGPIO",
format = Documenter.HTML(),
modules = [PiGPIO],
pages = [
"index.md",
"API Docs" => "api.md",
"Examples" => [
"Blink Once" => "examples/01_blink.md",
"Blink Twice" => "examples/02_blink_twice.md",
"Red-Green-Blue" => "examples/03_rgb.md"
]
]
)
# Documenter can also automatically deploy documentation to gh-pages.
# See "Hosting Documentation" and deploydocs() in the Documenter manual
# for more information.
#=deploydocs(
repo = "<repository url>"
)=#
| PiGPIO | https://github.com/JuliaBerry/PiGPIO.jl.git |
|
[
"MIT"
] | 0.2.0 | d1a06655265b3ca5a4af73ecdd1a3d60e04711f6 | code | 364 |
using PiGPIO
red_pin = 18 #change this accordingly with your GPIO pin number
p=Pi()
set_mode(p, red_pin, PiGPIO.OUTPUT)
try
for i in 1:10
PiGPIO.write(p, red_pin, PiGPIO.HIGH)
sleep(0.5)
PiGPIO.write(p, red_pin, PiGPIO.LOW)
sleep(0.5)
end
finally
println("Cleaning up!")
set_mode(p, red_pin, PiGPIO.INPUT)
end
| PiGPIO | https://github.com/JuliaBerry/PiGPIO.jl.git |
|
[
"MIT"
] | 0.2.0 | d1a06655265b3ca5a4af73ecdd1a3d60e04711f6 | code | 556 |
using PiGPIO
red_pin1 = 18 #change these numbers accordingly with your GPIO pins
red_pin2 = 23
p=Pi()
set_mode(p, red_pin1, PiGPIO.OUTPUT)
set_mode(p, red_pin2, PiGPIO.OUTPUT)
try
for i in 1:10
PiGPIO.write(p, red_pin1, PiGPIO.HIGH)
PiGPIO.write(p, red_pin2, PiGPIO.LOW)
sleep(0.5)
PiGPIO.write(p, red_pin1, PiGPIO.LOW)
PiGPIO.write(p, red_pin2, PiGPIO.HIGH)
sleep(0.5)
end
finally
println("Cleaning up!")
set_mode(p, red_pin1, PiGPIO.INPUT)
set_mode(p, red_pin2, PiGPIO.INPUT)
end
| PiGPIO | https://github.com/JuliaBerry/PiGPIO.jl.git |
|
[
"MIT"
] | 0.2.0 | d1a06655265b3ca5a4af73ecdd1a3d60e04711f6 | code | 1204 |
using PiGPIO
red_pin = 23
green_pin = 24
blue_pin = 25
p=Pi()
using Colors
dc = distinguishable_colors(10)
for r in dc
set_PWM_dutycycle(p, red_pin, round(Int, r.r*255))
set_PWM_dutycycle(p, green_pin, round(Int,r.g*255))
set_PWM_dutycycle(p, blue_pin, round(Int,r.b*255))
sleep(0.5)
end
set_PWM_dutycycle(p, red_pin, 0)
set_PWM_dutycycle(p, green_pin, 0)
set_PWM_dutycycle(p, blue_pin, 0)
using SIUnits
using SIUnits.ShortUnits
function normalize0(c::XYZ)
d=convert(xyY, c)
xyY(d.x, d.y, 1.0)
end
const hc_k = 0.0143877696*K*m
const twohc²= 1.19104287e-16*Watt*m^2
planck{S1<:Real, S2<:Real}(λ::quantity(S1,Meter); T::quantity(S2,Kelvin)=5778.0K) =
λ≤0m ? zero(λ)*Watt*m^-4 : twohc²*λ^-5.0/(exp(hc_k/(λ*T))-1)
Base.convert{S<:Real}(::Type{xyY}, T::quantity(S, K)) =
mapreduce(λ->planck(λ*nm,T=T)*m^3/Watt*colormatch(λ), +, 380:780) |>
normalize0
blackbodies = xyY[convert(xyY, T) for T in 100K:200K:10000K]
for b in blackbodies
r=convert(RGB, b)
set_PWM_dutycycle(p, red_pin, round(Int, r.r*255))
set_PWM_dutycycle(p, green_pin, round(Int,r.g*255))
set_PWM_dutycycle(p, blue_pin, round(Int,r.b*255))
sleep(0.5)
end
| PiGPIO | https://github.com/JuliaBerry/PiGPIO.jl.git |
|
[
"MIT"
] | 0.2.0 | d1a06655265b3ca5a4af73ecdd1a3d60e04711f6 | code | 207 | # https://github.com/joan2937/pigpio/blob/master/pigpio.py
module PiGPIO
export Pi
using Sockets
include("constants.jl")
include("pi.jl")
include("wave.jl")
include("i2c.jl")
include("spiSerial.jl")
end
| PiGPIO | https://github.com/JuliaBerry/PiGPIO.jl.git |
|
[
"MIT"
] | 0.2.0 | d1a06655265b3ca5a4af73ecdd1a3d60e04711f6 | code | 12620 | # GPIO levels
OFF = 0
LOW = 0
CLEAR = 0
ON = 1
HIGH = 1
SET = 1
TIMEOUT = 2
# GPIO edges
RISING_EDGE = 0
FALLING_EDGE = 1
EITHER_EDGE = 2
# GPIO modes
INPUT = 0
OUTPUT = 1
ALT0 = 4
ALT1 = 5
ALT2 = 6
ALT3 = 7
ALT4 = 3
ALT5 = 2
# GPIO Pull Up Down
PUD_OFF = 0
PUD_DOWN = 1
PUD_UP = 2
# script run status
PI_SCRIPT_INITING=0
PI_SCRIPT_HALTED =1
PI_SCRIPT_RUNNING=2
PI_SCRIPT_WAITING=3
PI_SCRIPT_FAILED =4
# notification flags
NTFY_FLAGS_ALIVE = (1 << 6)
NTFY_FLAGS_WDOG = (1 << 5)
NTFY_FLAGS_GPIO = 31
# wave modes
WAVE_MODE_ONE_SHOT =0
WAVE_MODE_REPEAT =1
WAVE_MODE_ONE_SHOT_SYNC=2
WAVE_MODE_REPEAT_SYNC =3
WAVE_NOT_FOUND = 9998 # Transmitted wave not found.
NO_TX_WAVE = 9999 # No wave being transmitted.
# pigpio command numbers
_PI_CMD_MODES= 0
_PI_CMD_MODEG= 1
_PI_CMD_PUD= 2
_PI_CMD_READ= 3
_PI_CMD_WRITE= 4
_PI_CMD_PWM= 5
_PI_CMD_PRS= 6
_PI_CMD_PFS= 7
_PI_CMD_SERVO= 8
_PI_CMD_WDOG= 9
_PI_CMD_BR1= 10
_PI_CMD_BR2= 11
_PI_CMD_BC1= 12
_PI_CMD_BC2= 13
_PI_CMD_BS1= 14
_PI_CMD_BS2= 15
_PI_CMD_TICK= 16
_PI_CMD_HWVER=17
_PI_CMD_NO= 18
_PI_CMD_NB= 19
_PI_CMD_NP= 20
_PI_CMD_NC= 21
_PI_CMD_PRG= 22
_PI_CMD_PFG= 23
_PI_CMD_PRRG= 24
_PI_CMD_HELP= 25
_PI_CMD_PIGPV=26
_PI_CMD_WVCLR=27
_PI_CMD_WVAG= 28
_PI_CMD_WVAS= 29
_PI_CMD_WVGO= 30
_PI_CMD_WVGOR=31
_PI_CMD_WVBSY=32
_PI_CMD_WVHLT=33
_PI_CMD_WVSM= 34
_PI_CMD_WVSP= 35
_PI_CMD_WVSC= 36
_PI_CMD_TRIG= 37
_PI_CMD_PROC= 38
_PI_CMD_PROCD=39
_PI_CMD_PROCR=40
_PI_CMD_PROCS=41
_PI_CMD_SLRO= 42
_PI_CMD_SLR= 43
_PI_CMD_SLRC= 44
_PI_CMD_PROCP=45
_PI_CMD_MICRO=46
_PI_CMD_MILLI=47
_PI_CMD_PARSE=48
_PI_CMD_WVCRE=49
_PI_CMD_WVDEL=50
_PI_CMD_WVTX =51
_PI_CMD_WVTXR=52
_PI_CMD_WVNEW=53
_PI_CMD_I2CO =54
_PI_CMD_I2CC =55
_PI_CMD_I2CRD=56
_PI_CMD_I2CWD=57
_PI_CMD_I2CWQ=58
_PI_CMD_I2CRS=59
_PI_CMD_I2CWS=60
_PI_CMD_I2CRB=61
_PI_CMD_I2CWB=62
_PI_CMD_I2CRW=63
_PI_CMD_I2CWW=64
_PI_CMD_I2CRK=65
_PI_CMD_I2CWK=66
_PI_CMD_I2CRI=67
_PI_CMD_I2CWI=68
_PI_CMD_I2CPC=69
_PI_CMD_I2CPK=70
_PI_CMD_SPIO =71
_PI_CMD_SPIC =72
_PI_CMD_SPIR =73
_PI_CMD_SPIW =74
_PI_CMD_SPIX =75
_PI_CMD_SERO =76
_PI_CMD_SERC =77
_PI_CMD_SERRB=78
_PI_CMD_SERWB=79
_PI_CMD_SERR =80
_PI_CMD_SERW =81
_PI_CMD_SERDA=82
_PI_CMD_GDC =83
_PI_CMD_GPW =84
_PI_CMD_HC =85
_PI_CMD_HP =86
_PI_CMD_CF1 =87
_PI_CMD_CF2 =88
_PI_CMD_NOIB =99
_PI_CMD_BI2CC=89
_PI_CMD_BI2CO=90
_PI_CMD_BI2CZ=91
_PI_CMD_I2CZ =92
_PI_CMD_WVCHA=93
_PI_CMD_SLRI =94
_PI_CMD_CGI =95
_PI_CMD_CSI =96
_PI_CMD_FG =97
_PI_CMD_FN =98
_PI_CMD_WVTXM=100
_PI_CMD_WVTAT=101
# pigpio error numbers
_PI_INIT_FAILED =-1
PI_BAD_USER_GPIO =-2
PI_BAD_GPIO =-3
PI_BAD_MODE =-4
PI_BAD_LEVEL =-5
PI_BAD_PUD =-6
PI_BAD_PULSEWIDTH =-7
PI_BAD_DUTYCYCLE =-8
_PI_BAD_TIMER =-9
_PI_BAD_MS =-10
_PI_BAD_TIMETYPE =-11
_PI_BAD_SECONDS =-12
_PI_BAD_MICROS =-13
_PI_TIMER_FAILED =-14
PI_BAD_WDOG_TIMEOUT =-15
_PI_NO_ALERT_FUNC =-16
_PI_BAD_CLK_PERIPH =-17
_PI_BAD_CLK_SOURCE =-18
_PI_BAD_CLK_MICROS =-19
_PI_BAD_BUF_MILLIS =-20
PI_BAD_DUTYRANGE =-21
_PI_BAD_SIGNUM =-22
_PI_BAD_PATHNAME =-23
PI_NO_HANDLE =-24
PI_BAD_HANDLE =-25
_PI_BAD_IF_FLAGS =-26
_PI_BAD_CHANNEL =-27
_PI_BAD_PRIM_CHANNEL=-27
_PI_BAD_SOCKET_PORT =-28
_PI_BAD_FIFO_COMMAND=-29
_PI_BAD_SECO_CHANNEL=-30
_PI_NOT_INITIALISED =-31
_PI_INITIALISED =-32
_PI_BAD_WAVE_MODE =-33
_PI_BAD_CFG_INTERNAL=-34
PI_BAD_WAVE_BAUD =-35
PI_TOO_MANY_PULSES =-36
PI_TOO_MANY_CHARS =-37
PI_NOT_SERIAL_GPIO =-38
_PI_BAD_SERIAL_STRUC=-39
_PI_BAD_SERIAL_BUF =-40
PI_NOT_PERMITTED =-41
PI_SOME_PERMITTED =-42
PI_BAD_WVSC_COMMND =-43
PI_BAD_WVSM_COMMND =-44
PI_BAD_WVSP_COMMND =-45
PI_BAD_PULSELEN =-46
PI_BAD_SCRIPT =-47
PI_BAD_SCRIPT_ID =-48
PI_BAD_SER_OFFSET =-49
PI_GPIO_IN_USE =-50
PI_BAD_SERIAL_COUNT =-51
PI_BAD_PARAM_NUM =-52
PI_DUP_TAG =-53
PI_TOO_MANY_TAGS =-54
PI_BAD_SCRIPT_CMD =-55
PI_BAD_VAR_NUM =-56
PI_NO_SCRIPT_ROOM =-57
PI_NO_MEMORY =-58
PI_SOCK_READ_FAILED =-59
PI_SOCK_WRIT_FAILED =-60
PI_TOO_MANY_PARAM =-61
PI_SCRIPT_NOT_READY =-62
PI_BAD_TAG =-63
PI_BAD_MICS_DELAY =-64
PI_BAD_MILS_DELAY =-65
PI_BAD_WAVE_ID =-66
PI_TOO_MANY_CBS =-67
PI_TOO_MANY_OOL =-68
PI_EMPTY_WAVEFORM =-69
PI_NO_WAVEFORM_ID =-70
PI_I2C_OPEN_FAILED =-71
PI_SER_OPEN_FAILED =-72
PI_SPI_OPEN_FAILED =-73
PI_BAD_I2C_BUS =-74
PI_BAD_I2C_ADDR =-75
PI_BAD_SPI_CHANNEL =-76
PI_BAD_FLAGS =-77
PI_BAD_SPI_SPEED =-78
PI_BAD_SER_DEVICE =-79
PI_BAD_SER_SPEED =-80
PI_BAD_PARAM =-81
PI_I2C_WRITE_FAILED =-82
PI_I2C_READ_FAILED =-83
PI_BAD_SPI_COUNT =-84
PI_SER_WRITE_FAILED =-85
PI_SER_READ_FAILED =-86
PI_SER_READ_NO_DATA =-87
PI_UNKNOWN_COMMAND =-88
PI_SPI_XFER_FAILED =-89
_PI_BAD_POINTER =-90
PI_NO_AUX_SPI =-91
PI_NOT_PWM_GPIO =-92
PI_NOT_SERVO_GPIO =-93
PI_NOT_HCLK_GPIO =-94
PI_NOT_HPWM_GPIO =-95
PI_BAD_HPWM_FREQ =-96
PI_BAD_HPWM_DUTY =-97
PI_BAD_HCLK_FREQ =-98
PI_BAD_HCLK_PASS =-99
PI_HPWM_ILLEGAL =-100
PI_BAD_DATABITS =-101
PI_BAD_STOPBITS =-102
PI_MSG_TOOBIG =-103
PI_BAD_MALLOC_MODE =-104
_PI_TOO_MANY_SEGS =-105
_PI_BAD_I2C_SEG =-106
PI_BAD_SMBUS_CMD =-107
PI_NOT_I2C_GPIO =-108
PI_BAD_I2C_WLEN =-109
PI_BAD_I2C_RLEN =-110
PI_BAD_I2C_CMD =-111
PI_BAD_I2C_BAUD =-112
PI_CHAIN_LOOP_CNT =-113
PI_BAD_CHAIN_LOOP =-114
PI_CHAIN_COUNTER =-115
PI_BAD_CHAIN_CMD =-116
PI_BAD_CHAIN_DELAY =-117
PI_CHAIN_NESTING =-118
PI_CHAIN_TOO_BIG =-119
PI_DEPRECATED =-120
PI_BAD_SER_INVERT =-121
_PI_BAD_EDGE =-122
_PI_BAD_ISR_INIT =-123
PI_BAD_FOREVER =-124
PI_BAD_FILTER =-125
# pigpio error text
_errors=[
[_PI_INIT_FAILED , "pigpio initialisation failed"],
[PI_BAD_USER_GPIO , "GPIO not 0-31"],
[PI_BAD_GPIO , "GPIO not 0-53"],
[PI_BAD_MODE , "mode not 0-7"],
[PI_BAD_LEVEL , "level not 0-1"],
[PI_BAD_PUD , "pud not 0-2"],
[PI_BAD_PULSEWIDTH , "pulsewidth not 0 or 500-2500"],
[PI_BAD_DUTYCYCLE , "dutycycle not 0-range (default 255)"],
[_PI_BAD_TIMER , "timer not 0-9"],
[_PI_BAD_MS , "ms not 10-60000"],
[_PI_BAD_TIMETYPE , "timetype not 0-1"],
[_PI_BAD_SECONDS , "seconds < 0"],
[_PI_BAD_MICROS , "micros not 0-999999"],
[_PI_TIMER_FAILED , "gpioSetTimerFunc failed"],
[PI_BAD_WDOG_TIMEOUT , "timeout not 0-60000"],
[_PI_NO_ALERT_FUNC , "DEPRECATED"],
[_PI_BAD_CLK_PERIPH , "clock peripheral not 0-1"],
[_PI_BAD_CLK_SOURCE , "DEPRECATED"],
[_PI_BAD_CLK_MICROS , "clock micros not 1, 2, 4, 5, 8, or 10"],
[_PI_BAD_BUF_MILLIS , "buf millis not 100-10000"],
[PI_BAD_DUTYRANGE , "dutycycle range not 25-40000"],
[_PI_BAD_SIGNUM , "signum not 0-63"],
[_PI_BAD_PATHNAME , "can't open pathname"],
[PI_NO_HANDLE , "no handle available"],
[PI_BAD_HANDLE , "unknown handle"],
[_PI_BAD_IF_FLAGS , "ifFlags > 3"],
[_PI_BAD_CHANNEL , "DMA channel not 0-14"],
[_PI_BAD_SOCKET_PORT , "socket port not 1024-30000"],
[_PI_BAD_FIFO_COMMAND , "unknown fifo command"],
[_PI_BAD_SECO_CHANNEL , "DMA secondary channel not 0-14"],
[_PI_NOT_INITIALISED , "function called before gpioInitialise"],
[_PI_INITIALISED , "function called after gpioInitialise"],
[_PI_BAD_WAVE_MODE , "waveform mode not 0-1"],
[_PI_BAD_CFG_INTERNAL , "bad parameter in gpioCfgInternals call"],
[PI_BAD_WAVE_BAUD , "baud rate not 50-250000(RX)/1000000(TX)"],
[PI_TOO_MANY_PULSES , "waveform has too many pulses"],
[PI_TOO_MANY_CHARS , "waveform has too many chars"],
[PI_NOT_SERIAL_GPIO , "no bit bang serial read in progress on GPIO"],
[PI_NOT_PERMITTED , "no permission to update GPIO"],
[PI_SOME_PERMITTED , "no permission to update one or more GPIO"],
[PI_BAD_WVSC_COMMND , "bad WVSC subcommand"],
[PI_BAD_WVSM_COMMND , "bad WVSM subcommand"],
[PI_BAD_WVSP_COMMND , "bad WVSP subcommand"],
[PI_BAD_PULSELEN , "trigger pulse length not 1-100"],
[PI_BAD_SCRIPT , "invalid script"],
[PI_BAD_SCRIPT_ID , "unknown script id"],
[PI_BAD_SER_OFFSET , "add serial data offset > 30 minute"],
[PI_GPIO_IN_USE , "GPIO already in use"],
[PI_BAD_SERIAL_COUNT , "must read at least a byte at a time"],
[PI_BAD_PARAM_NUM , "script parameter id not 0-9"],
[PI_DUP_TAG , "script has duplicate tag"],
[PI_TOO_MANY_TAGS , "script has too many tags"],
[PI_BAD_SCRIPT_CMD , "illegal script command"],
[PI_BAD_VAR_NUM , "script variable id not 0-149"],
[PI_NO_SCRIPT_ROOM , "no more room for scripts"],
[PI_NO_MEMORY , "can't allocate temporary memory"],
[PI_SOCK_READ_FAILED , "socket read failed"],
[PI_SOCK_WRIT_FAILED , "socket write failed"],
[PI_TOO_MANY_PARAM , "too many script parameters (> 10)"],
[PI_SCRIPT_NOT_READY , "script initialising"],
[PI_BAD_TAG , "script has unresolved tag"],
[PI_BAD_MICS_DELAY , "bad MICS delay (too large)"],
[PI_BAD_MILS_DELAY , "bad MILS delay (too large)"],
[PI_BAD_WAVE_ID , "non existent wave id"],
[PI_TOO_MANY_CBS , "No more CBs for waveform"],
[PI_TOO_MANY_OOL , "No more OOL for waveform"],
[PI_EMPTY_WAVEFORM , "attempt to create an empty waveform"],
[PI_NO_WAVEFORM_ID , "No more waveform ids"],
[PI_I2C_OPEN_FAILED , "can't open I2C device"],
[PI_SER_OPEN_FAILED , "can't open serial device"],
[PI_SPI_OPEN_FAILED , "can't open SPI device"],
[PI_BAD_I2C_BUS , "bad I2C bus"],
[PI_BAD_I2C_ADDR , "bad I2C address"],
[PI_BAD_SPI_CHANNEL , "bad SPI channel"],
[PI_BAD_FLAGS , "bad i2c/spi/ser open flags"],
[PI_BAD_SPI_SPEED , "bad SPI speed"],
[PI_BAD_SER_DEVICE , "bad serial device name"],
[PI_BAD_SER_SPEED , "bad serial baud rate"],
[PI_BAD_PARAM , "bad i2c/spi/ser parameter"],
[PI_I2C_WRITE_FAILED , "I2C write failed"],
[PI_I2C_READ_FAILED , "I2C read failed"],
[PI_BAD_SPI_COUNT , "bad SPI count"],
[PI_SER_WRITE_FAILED , "ser write failed"],
[PI_SER_READ_FAILED , "ser read failed"],
[PI_SER_READ_NO_DATA , "ser read no data available"],
[PI_UNKNOWN_COMMAND , "unknown command"],
[PI_SPI_XFER_FAILED , "SPI xfer/read/write failed"],
[_PI_BAD_POINTER , "bad (NULL) pointer"],
[PI_NO_AUX_SPI , "no auxiliary SPI on Pi A or B"],
[PI_NOT_PWM_GPIO , "GPIO is not in use for PWM"],
[PI_NOT_SERVO_GPIO , "GPIO is not in use for servo pulses"],
[PI_NOT_HCLK_GPIO , "GPIO has no hardware clock"],
[PI_NOT_HPWM_GPIO , "GPIO has no hardware PWM"],
[PI_BAD_HPWM_FREQ , "hardware PWM frequency not 1-125M"],
[PI_BAD_HPWM_DUTY , "hardware PWM dutycycle not 0-1M"],
[PI_BAD_HCLK_FREQ , "hardware clock frequency not 4689-250M"],
[PI_BAD_HCLK_PASS , "need password to use hardware clock 1"],
[PI_HPWM_ILLEGAL , "illegal, PWM in use for main clock"],
[PI_BAD_DATABITS , "serial data bits not 1-32"],
[PI_BAD_STOPBITS , "serial (half) stop bits not 2-8"],
[PI_MSG_TOOBIG , "socket/pipe message too big"],
[PI_BAD_MALLOC_MODE , "bad memory allocation mode"],
[_PI_TOO_MANY_SEGS , "too many I2C transaction segments"],
[_PI_BAD_I2C_SEG , "an I2C transaction segment failed"],
[PI_BAD_SMBUS_CMD , "SMBus command not supported"],
[PI_NOT_I2C_GPIO , "no bit bang I2C in progress on GPIO"],
[PI_BAD_I2C_WLEN , "bad I2C write length"],
[PI_BAD_I2C_RLEN , "bad I2C read length"],
[PI_BAD_I2C_CMD , "bad I2C command"],
[PI_BAD_I2C_BAUD , "bad I2C baud rate, not 50-500k"],
[PI_CHAIN_LOOP_CNT , "bad chain loop count"],
[PI_BAD_CHAIN_LOOP , "empty chain loop"],
[PI_CHAIN_COUNTER , "too many chain counters"],
[PI_BAD_CHAIN_CMD , "bad chain command"],
[PI_BAD_CHAIN_DELAY , "bad chain delay micros"],
[PI_CHAIN_NESTING , "chain counters nested too deeply"],
[PI_CHAIN_TOO_BIG , "chain is too long"],
[PI_DEPRECATED , "deprecated function removed"],
[PI_BAD_SER_INVERT , "bit bang serial invert not 0 or 1"],
[_PI_BAD_EDGE , "bad ISR edge value, not 0-2"],
[_PI_BAD_ISR_INIT , "bad ISR initialisation"],
[PI_BAD_FOREVER , "loop forever must be last chain command"],
[PI_BAD_FILTER , "bad filter parameter"],
]
| PiGPIO | https://github.com/JuliaBerry/PiGPIO.jl.git |
|
[
"MIT"
] | 0.2.0 | d1a06655265b3ca5a4af73ecdd1a3d60e04711f6 | code | 19533 | """
Returns a handle (>=0) for the device at the I2C bus address.
i2c_bus:= >=0.
i2c_address:= 0-0x7F.
i2c_flags:= 0, no flags are currently defined.
Normally you would only use the [*i2c_**] functions if
you are or will be connecting to the Pi over a network. If
you will always run on the local Pi use the standard SMBus
module instead.
Physically buses 0 and 1 are available on the Pi. Higher
numbered buses will be available if a kernel supported bus
multiplexor is being used.
For the SMBus commands the low level transactions are shown
at the end of the function description. The following
abbreviations are used.
. .
S (1 bit) : Start bit
P (1 bit) : Stop bit
Rd/Wr (1 bit) : Read/Write bit. Rd equals 1, Wr equals 0.
A, NA (1 bit) : Accept and not accept bit.
Addr (7 bits): I2C 7 bit address.
reg (8 bits): Command byte, which often selects a register.
Data (8 bits): A data byte.
Count (8 bits): A byte defining the length of a block operation.
[..]: Data sent by the device.
. .
...
h = i2c_open(pi, 1, 0x53) # open device at address 0x53 on bus 1
...
"""
function i2c_open(self::Pi, i2c_bus, i2c_address, i2c_flags=0)
# I p1 i2c_bus
# I p2 i2c_addr
# I p3 4
## extension ##
# I i2c_flags
extents = [pack("I", i2c_flags)]
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_I2CO, i2c_bus, i2c_address, 4, extents))
end
"""
Closes the I2C device associated with handle.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
...
i2c_close(pi, h)
...
"""
function i2c_close(self::Pi, handle)
return _u2i(_pigpio_command(self.sl, _PI_CMD_I2CC, handle, 0))
end
"""
Sends a single bit to the device associated with handle.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
bit:= 0 or 1, the value to write.
SMBus 2.0 5.5.1 - Quick command.
. .
S Addr bit [A] P
. .
...
i2c_write_quick(pi, 0, 1) # send 1 to device 0
i2c_write_quick(pi, 3, 0) # send 0 to device 3
...
"""
function i2c_write_quick(self::Pi, handle, bit)
return _u2i(_pigpio_command(self.sl, _PI_CMD_I2CWQ, handle, bit))
end
"""
Sends a single byte to the device associated with handle.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
byte_val:= 0-255, the value to write.
SMBus 2.0 5.5.2 - Send byte.
. .
S Addr Wr [A] byte_val [A] P
. .
...
i2c_write_byte(pi, 1, 17) # send byte 17 to device 1
i2c_write_byte(pi, 2, 0x23) # send byte 0x23 to device 2
...
"""
function i2c_write_byte(self::Pi, handle, byte_val)
return _u2i(
_pigpio_command(self.sl, _PI_CMD_I2CWS, handle, byte_val))
end
"""
Reads a single byte from the device associated with handle.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
SMBus 2.0 5.5.3 - Receive byte.
. .
S Addr Rd [A] [Data] NA P
. .
...
b = i2c_read_byte(pi, 2) # read a byte from device 2
...
"""
function i2c_read_byte(self::Pi, handle)
return _u2i(_pigpio_command(self.sl, _PI_CMD_I2CRS, handle, 0))
end
"""
Writes a single byte to the specified register of the device
associated with handle.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
reg:= >=0, the device register.
byte_val:= 0-255, the value to write.
SMBus 2.0 5.5.4 - Write byte.
. .
S Addr Wr [A] reg [A] byte_val [A] P
. .
...
# send byte 0xC5 to reg 2 of device 1
i2c_write_byte_data(pi, 1, 2, 0xC5)
# send byte 9 to reg 4 of device 2
i2c_write_byte_data(pi, 2, 4, 9)
...
"""
function i2c_write_byte_data(self::Pi, handle, reg, byte_val)
# I p1 handle
# I p2 reg
# I p3 4
## extension ##
# I byte_val
extents = IOBuffer
write(extents, byte_val)
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_I2CWB, handle, reg, 4, extents))
end
"""
Writes a single 16 bit word to the specified register of the
device associated with handle.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
reg:= >=0, the device register.
word_val:= 0-65535, the value to write.
SMBus 2.0 5.5.4 - Write word.
. .
S Addr Wr [A] reg [A] word_val_Low [A] word_val_High [A] P
. .
...
# send word 0xA0C5 to reg 5 of device 4
i2c_write_word_data(pi, 4, 5, 0xA0C5)
# send word 2 to reg 2 of device 5
i2c_write_word_data(pi, 5, 2, 23)
...
"""
function i2c_write_word_data(self::Pi, handle, reg, word_val)
# I p1 handle
# I p2 reg
# I p3 4
## extension ##
# I word_val
extents = IOBuffer
write(extents, word_val)
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_I2CWW, handle, reg, 4, extents))
end
"""
Reads a single byte from the specified register of the device
associated with handle.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
reg:= >=0, the device register.
SMBus 2.0 5.5.5 - Read byte.
. .
S Addr Wr [A] reg [A] S Addr Rd [A] [Data] NA P
. .
...
# read byte from reg 17 of device 2
b = i2c_read_byte_data(pi, 2, 17)
# read byte from reg 1 of device 0
b = i2c_read_byte_data(pi, 0, 1)
...
"""
function i2c_read_byte_data(self, handle, reg)
return _u2i(_pigpio_command(self.sl, _PI_CMD_I2CRB, handle, reg))
end
"""
Reads a single 16 bit word from the specified register of the
device associated with handle.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
reg:= >=0, the device register.
SMBus 2.0 5.5.5 - Read word.
. .
S Addr Wr [A] reg [A] S Addr Rd [A] [DataLow] A [DataHigh] NA P
. .
...
# read word from reg 2 of device 3
w = i2c_read_word_data(pi, 3, 2)
# read word from reg 7 of device 2
w = i2c_read_word_data(pi, 2, 7)
...
"""
function i2c_read_word_data(self, handle, reg)
return _u2i(_pigpio_command(self.sl, _PI_CMD_I2CRW, handle, reg))
end
"""
Writes 16 bits of data to the specified register of the device
associated with handle and reads 16 bits of data in return.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
reg:= >=0, the device register.
word_val:= 0-65535, the value to write.
SMBus 2.0 5.5.6 - Process call.
. .
S Addr Wr [A] reg [A] word_val_Low [A] word_val_High [A]
S Addr Rd [A] [DataLow] A [DataHigh] NA P
. .
...
r = i2c_process_call(pi, h, 4, 0x1231)
r = i2c_process_call(pi, h, 6, 0)
...
"""
function i2c_process_call(self, handle, reg, word_val)
# I p1 handle
# I p2 reg
# I p3 4
## extension ##
# I word_val
extents = IOBuffer
write(extents, word_val)
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_I2CPC, handle, reg, 4, extents))
end
"""
Writes up to 32 bytes to the specified register of the device
associated with handle.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
reg:= >=0, the device register.
data:= the bytes to write.
SMBus 2.0 5.5.7 - Block write.
. .
S Addr Wr [A] reg [A] length(data) [A] data0 [A] data1 [A] ... [A]
datan [A] P
. .
...
i2c_write_block_data(pi, 4, 5, b'hello')
i2c_write_block_data(pi, 4, 5, "data bytes")
i2c_write_block_data(pi, 5, 0, b'\\x00\\x01\\x22')
i2c_write_block_data(pi, 6, 2, [0, 1, 0x22])
...
"""
function i2c_write_block_data(self, handle, reg, data)
# I p1 handle
# I p2 reg
# I p3 len
## extension ##
# s len data bytes
if length(data)
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_I2CWK, handle, reg, length(data), data))
else
return 0
end
end
"""
Reads a block of up to 32 bytes from the specified register of
the device associated with handle.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
reg:= >=0, the device register.
SMBus 2.0 5.5.7 - Block read.
. .
S Addr Wr [A] reg [A]
S Addr Rd [A] [Count] A [Data] A [Data] A ... A [Data] NA P
. .
The amount of returned data is set by the device.
The returned value is a tuple of the number of bytes read and a
bytearray containing the bytes. If there was an error the
number of bytes read will be less than zero (and will contain
the error code).
...
(b, d) = i2c_read_block_data(pi, h, 10)
if b >= 0
# process data
else
# process read failure
...
"""
function i2c_read_block_data(self::Pi, handle, reg)
# Don't raise exception. Must release lock.
bytes = u2i(_pigpio_command(self.sl, _PI_CMD_I2CRK, handle, reg, false))
if bytes > 0
data = rxbuf(bytes)
else
data = ""
end
unlock(self.sl.l)
return bytes, data
end
"""
Writes data bytes to the specified register of the device
associated with handle and reads a device specified number
of bytes of data in return.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
reg:= >=0, the device register.
data:= the bytes to write.
The SMBus 2.0 documentation states that a minimum of 1 byte may
be sent and a minimum of 1 byte may be received. The total
number of bytes sent/received must be 32 or less.
SMBus 2.0 5.5.8 - Block write-block read.
. .
S Addr Wr [A] reg [A] length(data) [A] data0 [A] ... datan [A]
S Addr Rd [A] [Count] A [Data] ... A P
. .
The returned value is a tuple of the number of bytes read and a
bytearray containing the bytes. If there was an error the
number of bytes read will be less than zero (and will contain
the error code).
...
(b, d) = i2c_block_process_call(pi, h, 10, b'\\x02\\x05\\x00')
(b, d) = i2c_block_process_call(pi, h, 10, b'abcdr')
(b, d) = i2c_block_process_call(pi, h, 10, "abracad")
(b, d) = i2c_block_process_call(pi, h, 10, [2, 5, 16])
...
"""
function i2c_block_process_call(self::Pi, handle, reg, data)
# I p1 handle
# I p2 reg
# I p3 len
## extension ##
# s len data bytes
# Don't raise exception. Must release lock.
bytes = u2i(_pigpio_command_ext(
self.sl, _PI_CMD_I2CPK, handle, reg, length(data), data, false))
if bytes > 0
data = rxbuf(self, bytes)
else
data = ""
end
unlock(self.sl.l)
return bytes, data
end
"""
Writes data bytes to the specified register of the device
associated with handle . 1-32 bytes may be written.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
reg:= >=0, the device register.
data:= the bytes to write.
. .
S Addr Wr [A] reg [A] data0 [A] data1 [A] ... [A] datan [NA] P
. .
...
i2c_write_i2c_block_data(pi, 4, 5, 'hello')
i2c_write_i2c_block_data(pi, 4, 5, b'hello')
i2c_write_i2c_block_data(pi, 5, 0, b'\\x00\\x01\\x22')
i2c_write_i2c_block_data(pi, 6, 2, [0, 1, 0x22])
...
"""
function i2c_write_i2c_block_data(self::Pi, handle, reg, data)
# I p1 handle
# I p2 reg
# I p3 len
## extension ##
# s len data bytes
if length(data) > 0
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_I2CWI, handle, reg, length(data), [data]))
else
return 0
end
end
"""
Reads count bytes from the specified register of the device
associated with handle . The count may be 1-32.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
reg:= >=0, the device register.
count:= >0, the number of bytes to read.
. .
S Addr Wr [A] reg [A]
S Addr Rd [A] [Data] A [Data] A ... A [Data] NA P
. .
The returned value is a tuple of the number of bytes read and a
bytearray containing the bytes. If there was an error the
number of bytes read will be less than zero (and will contain
the error code).
...
(b, d) = i2c_read_i2c_block_data(pi, h, 4, 32)
if b >= 0
# process data
else
# process read failure
...
"""
function i2c_read_i2c_block_data(self::Pi, handle, reg, count)
# I p1 handle
# I p2 reg
# I p3 4
## extension ##
# I count
extents = IOBuffer()
write(extents, count)
# Don't raise exception. Must release lock.
bytes = u2i(_pigpio_command_ext(
self.sl, _PI_CMD_I2CRI, handle, reg, 4, extents, false))
if bytes > 0
data = rxbuf(self, bytes)
else
data = ""
end
unlock(self.sl.l)
return bytes, data
end
"""
Returns count bytes read from the raw device associated
with handle.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
count:= >0, the number of bytes to read.
. .
S Addr Rd [A] [Data] A [Data] A ... A [Data] NA P
. .
The returned value is a tuple of the number of bytes read and a
bytearray containing the bytes. If there was an error the
number of bytes read will be less than zero (and will contain
the error code).
...
(count, data) = i2c_read_device(pi, h, 12)
...
"""
function i2c_read_device(self::Pi, handle, count)
# Don't raise exception. Must release lock.
bytes = u2i(
_pigpio_command(self.sl, _PI_CMD_I2CRD, handle, count, false))
if bytes > 0
data = rxbuf(self, bytes)
else
data = ""
end
unlock(self.sl.l)
return bytes, data
end
"""
Writes the data bytes to the raw device associated with handle.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
data:= the bytes to write.
. .
S Addr Wr [A] data0 [A] data1 [A] ... [A] datan [A] P
. .
...
i2c_write_device(pi, h, b"\\x12\\x34\\xA8")
i2c_write_device(pi, h, b"help")
i2c_write_device(pi, h, 'help')
i2c_write_device(pi, h, [23, 56, 231])
...
"""
function i2c_write_device(self::Pi, handle, data)
# I p1 handle
# I p2 0
# I p3 len
## extension ##
# s len data bytes
if length(data)
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_I2CWD, handle, 0, length(data), data))
else
return 0
end
end
"""
This function executes a sequence of I2C operations. The
operations to be performed are specified by the contents of data
which contains the concatenated command codes and associated data.
handle:= >=0 (as returned by a prior call to [*i2c_open*]).
data:= the concatenated I2C commands, see below
The returned value is a tuple of the number of bytes read and a
bytearray containing the bytes. If there was an error the
number of bytes read will be less than zero (and will contain
the error code).
...
(count, data) = i2c_zip(pi, h, [4, 0x53, 7, 1, 0x32, 6, 6, 0])
...
The following command codes are supported
Name @ Cmd & Data @ Meaning
End @ 0 @ No more commands
Escape @ 1 @ Next P is two bytes
On @ 2 @ Switch combined flag on
Off @ 3 @ Switch combined flag off
Address @ 4 P @ Set I2C address to P
Flags @ 5 lsb msb @ Set I2C flags to lsb + (msb << 8)
Read @ 6 P @ Read P bytes of data
Write @ 7 P ... @ Write P bytes of data
The address, read, and write commands take a parameter P.
Normally P is one byte (0-255). If the command is preceded by
the Escape command then P is two bytes (0-65535, least significant
byte first).
The address defaults to that associated with the handle.
The flags default to 0. The address and flags maintain their
previous value until updated.
Any read I2C data is concatenated in the returned bytearray.
...
Set address 0x53, write 0x32, read 6 bytes
Set address 0x1E, write 0x03, read 6 bytes
Set address 0x68, write 0x1B, read 8 bytes
End
0x04 0x53 0x07 0x01 0x32 0x06 0x06
0x04 0x1E 0x07 0x01 0x03 0x06 0x06
0x04 0x68 0x07 0x01 0x1B 0x06 0x08
0x00
...
"""
function i2c_zip(self::Pi, handle, data)
# I p1 handle
# I p2 0
# I p3 len
## extension ##
# s len data bytes
# Don't raise exception. Must release lock.
bytes = u2i(_pigpio_command_ext(
self.sl, _PI_CMD_I2CZ, handle, 0, length(data), data, false))
if bytes > 0
data = self._rxbuf(bytes)
else
data = ""
end
unlock(self.sl.l)
return bytes, data
end
"""
This function selects a pair of GPIO for bit banging I2C at a
specified baud rate.
Bit banging I2C allows for certain operations which are not possible
with the standard I2C driver.
o baud rates as low as 50
o repeated starts
o clock stretching
o I2C on any pair of spare GPIO
SDA:= 0-31
SCL:= 0-31
baud:= 50-500000
Returns 0 if OK, otherwise PI_BAD_USER_GPIO, PI_BAD_I2C_BAUD, or
PI_GPIO_IN_USE.
NOTE
The GPIO used for SDA and SCL must have pull-ups to 3V3 connected.
As a guide the hardware pull-ups on pins 3 and 5 are 1k8 in value.
...
h = bb_i2c_open(pi, 4, 5, 50000) # bit bang on GPIO 4/5 at 50kbps
...
"""
function bb_i2c_open(self::Pi, SDA, SCL, baud=100000)
# I p1 SDA
# I p2 SCL
# I p3 4
## extension ##
# I baud
extents = IOBuffer()
write(extents, baud)
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_BI2CO, SDA, SCL, 4, extents))
end
"""
This function stops bit banging I2C on a pair of GPIO
previously opened with [*bb_i2c_open*].
SDA:= 0-31, the SDA GPIO used in a prior call to [*bb_i2c_open*]
Returns 0 if OK, otherwise PI_BAD_USER_GPIO, or PI_NOT_I2C_GPIO.
...
bb_i2c_close(pi, SDA)
...
"""
function bb_i2c_close(self::Pi, SDA)
return _u2i(_pigpio_command(self.sl, _PI_CMD_BI2CC, SDA, 0))
end
"""
This function executes a sequence of bit banged I2C operations.
The operations to be performed are specified by the contents
of data which contains the concatenated command codes and
associated data.
SDA:= 0-31 (as used in a prior call to [*bb_i2c_open*])
data:= the concatenated I2C commands, see below
The returned value is a tuple of the number of bytes read and a
bytearray containing the bytes. If there was an error the
number of bytes read will be less than zero (and will contain
the error code).
...
(count, data) = pi.bb_i2c_zip(
h, [4, 0x53, 2, 7, 1, 0x32, 2, 6, 6, 3, 0])
...
The following command codes are supported
Name @ Cmd & Data @ Meaning
End @ 0 @ No more commands
Escape @ 1 @ Next P is two bytes
Start @ 2 @ Start condition
Stop @ 3 @ Stop condition
Address @ 4 P @ Set I2C address to P
Flags @ 5 lsb msb @ Set I2C flags to lsb + (msb << 8)
Read @ 6 P @ Read P bytes of data
Write @ 7 P ... @ Write P bytes of data
The address, read, and write commands take a parameter P.
Normally P is one byte (0-255). If the command is preceded by
the Escape command then P is two bytes (0-65535, least significant
byte first).
The address and flags default to 0. The address and flags maintain
their previous value until updated.
No flags are currently defined.
Any read I2C data is concatenated in the returned bytearray.
...
Set address 0x53
start, write 0x32, (re)start, read 6 bytes, stop
Set address 0x1E
start, write 0x03, (re)start, read 6 bytes, stop
Set address 0x68
start, write 0x1B, (re)start, read 8 bytes, stop
End
0x04 0x53
0x02 0x07 0x01 0x32 0x02 0x06 0x06 0x03
0x04 0x1E
0x02 0x07 0x01 0x03 0x02 0x06 0x06 0x03
0x04 0x68
0x02 0x07 0x01 0x1B 0x02 0x06 0x08 0x03
0x00
...
"""
function bb_i2c_zip(self::Pi, SDA, data)
# I p1 SDA
# I p2 0
# I p3 len
## extension ##
# s len data bytes
# Don't raise exception. Must release lock.
bytes = u2i(_pigpio_command_ext(
self.sl, _PI_CMD_BI2CZ, SDA, 0, length(data), [data], false))
if bytes > 0
data = self._rxbuf(bytes)
else
data = ""
end
unlock(self.sl.l)
return bytes, data
end
| PiGPIO | https://github.com/JuliaBerry/PiGPIO.jl.git |
|
[
"MIT"
] | 0.2.0 | d1a06655265b3ca5a4af73ecdd1a3d60e04711f6 | code | 32313 | export set_mode, get_mode, set_pull_up_down
exceptions = true
"""
A class to store socket and lock.
"""
mutable struct SockLock
s::TCPSocket
l::ReentrantLock
end
"""
A class to store pulse information.
gpio_on: the GPIO to switch on at the start of the pulse.
gpio_off: the GPIO to switch off at the start of the pulse.
delay: the delay in microseconds before the next pulse.
"""
mutable struct Pulse
gpio_on::Int
gpio_off::Int
delay::Int
end
"""
Returns a text description of a pigpio error.
errnum:= <0, the error number
...
print(pigpio.error_text(-5))
level not 0-1
...
"""
function error_text(errnum)
for e in _errors
if e[0] == errnum
return e[1]
end
end
return "unknown error ($ernum)"
end
"""
Returns the microsecond difference between two ticks.
t1:= the earlier tick
t2:= the later tick
...
print(pigpio.tickDiff(4294967272, 12))
36
...
"""
function tickDiff(t1, t2)
tDiff = t2 - t1
if tDiff < 0
tDiff += (1 << 32)
end
return tDiff
end
"""
Converts a 32 bit unsigned number to signed. If the number
is negative it indicates an error. On error a pigpio
exception will be raised if exceptions is true.
"""
function _u2i(x::UInt32)
v = convert(Int32, x)
if v < 0
if exceptions
error(error_text(v))
end
end
return v
end
struct InMsg
cmd::Cuint # a bits type
p1::Cuint # an array of bits types
p2::Cuint # a string with a fixed number of bytes
d::Cuint
end
struct OutMsg
dummy::Array{UInt8,1} # a bits type
res::Cuint # an array of bits types
end
"""
Runs a pigpio socket command.
sl:= command socket and lock.
cmd:= the command to be executed.
p1:= command parameter 1 (if applicable).
p2:= command parameter 2 (if applicable).
"""
function _pigpio_command(sl::SockLock, cmd::Integer, p1::Integer, p2::Integer, rl=true)
lock(sl.l)
Base.write(sl.s, UInt32.([cmd, p1, p2, 0]))
out = IOBuffer(Base.read(sl.s, 16))
msg = reinterpret(Cuint, take!(out))[4]
if rl
unlock(sl.l)
end
return msg
end
"""
Runs an extended pigpio socket command.
sl:= command socket and lock.
cmd:= the command to be executed.
p1:= command parameter 1 (if applicable).
p2:= command parameter 2 (if applicable).
p3:= total size in bytes of following extents
extents:= additional data blocks
"""
function _pigpio_command_ext(sl, cmd, p1, p2, p3, extents, rl=true)
ext = IOBuffer()
Base.write(ext, Array(reinterpret(UInt8, [cmd, p1, p2, p3])))
for x in extents
write(ext, string(x))
end
lock(sl.l)
write(sl.s, ext)
msg = reinterpret(Cuint, sl.s)[4]
if rl
unlock(sl.l)
end
return res
end
"""An ADT class to hold callback information
gpio:= Broadcom GPIO number.
edge:= EITHER_EDGE, RISING_EDGE, or FALLING_EDGE.
func:= a user function taking three arguments (GPIO, level, tick).
"""
mutable struct Callback_ADT
gpio::Int
edge::Int
func::Function
bit::Int
Callback_ADT(gpio, edge, func) = new(gpio, edge, func, 1<<gpio)
end
"""A class to encapsulate pigpio notification callbacks."""
mutable struct CallbackThread #(threading.Thread)
control::SockLock
sl::SockLock
go::Bool
daemon::Bool
monitor::Int
handle::Cuint
callbacks::Array{Any, 1}
end
"""Initialises notifications."""
function CallbackThread(control, host, port)
socket = connect(host, port)
sl = SockLock(socket, ReentrantLock())
self = CallbackThread(control, sl, false, true, 0, 0, Any[])
self.handle = _pigpio_command(sl, _PI_CMD_NOIB, 0, 0)
self.go = true
return self
#self.start() #TODO
end
"""Stops notifications."""
function stop(self::CallbackThread)
if self.go
self.go = false
Base.write(self.sl.s, _PI_CMD_NC, self.handle, 0, 0)
end
end
"""Adds a callback to the notification thread."""
function append(self::CallbackThread, callb)
push!(self.callbacks, callb)
self.monitor = self.monitor | callb.bit
_pigpio_command(self.control, _PI_CMD_NB, self.handle, self.monitor)
end
"""Removes a callback from the notification thread."""
function remove(self::CallbackThread, callb)
if callb in self.callbacks
self.callbacks.remove(callb)
newMonitor = 0
for c in self.callbacks
newMonitor |= c.bit
end
if newMonitor != self.monitor
self.monitor = newMonitor
_pigpio_command(
self.control, _PI_CMD_NB, self.handle, self.monitor)
end
end
end
struct CallbMsg
seq::Cushort
flags::Cushort
tick::Cuint
level::Cuint
end
"""Runs the notification thread."""
function run(self::CallbackThread)
lastLevel = _pigpio_command(self.control, _PI_CMD_BR1, 0, 0)
MSG_SIZ = 12
while self.go
buf = readbytes(self.sl.s, MSG_SIZ, all=true)
if self.go
msg = reinterpret(CallbMsg, buf)
seq = msg.seq
seq, flags, tick, level = (msg.seq, msg.flags, msg.tick, msg.level)
if flags == 0
changed = level ^ lastLevel
lastLevel = level
for cb in self.callbacks
if cb.bit && changed
newLevel = 0
elseif cb.bit & level
newLevel = 1
end
if (cb.edge ^ newLevel)
cb.func(cb.gpio, newLevel, tick)
end
end
else
if flags & NTFY_FLAGS_WDOG
gpio = flags & NTFY_FLAGS_GPIO
for cb in self.callbacks
if cb.gpio == gpio
cb.func(cb.gpio, TIMEOUT, tick)
end
end
end
end
end
end
close(self.sl.s)
end
"""A class to provide GPIO level change callbacks."""
mutable struct Callback
notify::Array{Callback_ADT, 1}
count::Int
reset::Bool
callb::Callback_ADT
end
function Callback(notify, user_gpio::Int, edge::Int=RISING_EDGE, func=nothing)
self = Callback(notify, 0, false, nothing)
if func == nothing
func = _tally
end
self.callb = Callback_ADT(user_gpio, edge, func)
push!(self.notify, self.callb)
end
"""Cancels a callback by removing it from the notification thread."""
function cancel(self)
filter(x->x!=self.callb, self.notify)
end
"""Increment the callback called count."""
function _tally(self::Callback, user_gpio, level, tick)
if self.reset
self.reset = false
self.count = 0
end
self.count += 1
end
"""
Provides a count of how many times the default tally
callback has triggered.
The count will be zero if the user has supplied their own
callback function.
"""
function tally(self::Callback)
return self.count
end
"""
Resets the tally count to zero.
"""
function reset_tally(self::Callback)
self._reset = true
self.count = 0
end
"""Encapsulates waiting for GPIO edges."""
mutable struct WaitForEdge
notify
callb::Function
trigger
start
end
"""Initialises a wait_for_edge."""
function WaitForEdge( notify, gpio::Int, edge, timeout)
callb = _callback_ADT(gpio, edge, self.func)
self = WaitForEdge(notify, callb, false, time())
push!(self.notify, self.callb)
while (self.trigger == false) && ((time()-self.start) < timeout)
time.sleep(0.05)
end
self._notify.remove(self.callb)
end
"""Sets wait_for_edge triggered."""
function func(self::WaitForEdge, gpio, level, tick)
self.trigger = true
end
mutable struct Pi
host::String
port::Int
connected::Bool
sl::SockLock
notify::CallbackThread
end
"""Returns count bytes from the command socket."""
function rxbuf(self::Pi, count)
ext = readbytes(self.sl.s, count, all)
return ext
end
"""
Sets the GPIO mode.
gpio:= 0-53.
mode:= INPUT, OUTPUT, ALT0, ALT1, ALT2, ALT3, ALT4, ALT5.
...
set_mode(pi, 4, pigpio.INPUT) # GPIO 4 as input
set_mode(pi, 17, pigpio.OUTPUT) # GPIO 17 as output
set_mode(pi, 24, pigpio.ALT2) # GPIO 24 as ALT2
...
"""
function set_mode(self::Pi, gpio, mode)
return _u2i(_pigpio_command(self.sl, _PI_CMD_MODES, gpio, mode))
end
"""
Returns the GPIO mode.
gpio:= 0-53.
Returns a value as follows
. .
0 = INPUT
1 = OUTPUT
2 = ALT5
3 = ALT4
4 = ALT0
5 = ALT1
6 = ALT2
7 = ALT3
. .
...
print(get_mode(pi, 0))
4
...
"""
function get_mode(self::Pi, gpio)
return _u2i(_pigpio_command(self.sl, _PI_CMD_MODEG, gpio, 0))
end
"""
Sets or clears the internal GPIO pull-up/down resistor.
gpio:= 0-53.
pud:= PUD_UP, PUD_DOWN, PUD_OFF.
...
set_pull_up_down(pi, 17, pigpio.PUD_OFF)
set_pull_up_down(pi, 23, pigpio.PUD_UP)
set_pull_up_down(pi, 24, pigpio.PUD_DOWN)
...
"""
function set_pull_up_down(self::Pi, gpio, pud)
return _u2i(_pigpio_command(self.sl, _PI_CMD_PUD, gpio, pud))
end
"""
Returns the GPIO level.
gpio:= 0-53.
...
set_mode(pi, 23, pigpio.INPUT)
set_pull_up_down(pi, 23, pigpio.PUD_DOWN)
print(read(pi, 23))
0
set_pull_up_down(pi, 23, pigpio.PUD_UP)
print(read(pi, 23))
1
...
"""
function read(self::Pi, gpio)
return _u2i(_pigpio_command(self.sl, _PI_CMD_READ, gpio, 0))
end
"""
Sets the GPIO level.
GPIO:= 0-53.
level:= 0, 1.
If PWM or servo pulses are active on the GPIO they are
switched off.
...
set_mode(pi, 17, pigpio.OUTPUT)
write(pi, 17,0)
print(read(pi, 17))
0
write(pi, 17,1)
print(read(pi, 17))
1
...
"""
function write(self::Pi, gpio, level)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WRITE, gpio, level))
end
"""
Starts (non-zero dutycycle) or stops (0) PWM pulses on the GPIO.
user_gpio:= 0-31.
dutycycle:= 0-range (range defaults to 255).
The [*set_PWM_range*] function can change the default range of 255.
...
set_PWM_dutycycle(pi, 4, 0) # PWM off
set_PWM_dutycycle(pi, 4, 64) # PWM 1/4 on
set_PWM_dutycycle(pi, 4, 128) # PWM 1/2 on
set_PWM_dutycycle(pi, 4, 192) # PWM 3/4 on
set_PWM_dutycycle(pi, 4, 255) # PWM full on
...
"""
function set_PWM_dutycycle(self::Pi, user_gpio, dutycycle)
return _u2i(_pigpio_command(
self.sl, _PI_CMD_PWM, user_gpio, Int(dutycycle)))
end
"""
Returns the PWM dutycycle being used on the GPIO.
user_gpio:= 0-31.
Returns the PWM dutycycle.
For normal PWM the dutycycle will be out of the defined range
for the GPIO (see [*get_PWM_range*]).
If a hardware clock is active on the GPIO the reported
dutycycle will be 500000 (500k) out of 1000000 (1M).
If hardware PWM is active on the GPIO the reported dutycycle
will be out of a 1000000 (1M).
...
set_PWM_dutycycle(pi, 4, 25)
print(get_PWM_dutycycle(pi, 4))
25
set_PWM_dutycycle(pi, 4, 203)
print(get_PWM_dutycycle(pi, 4))
203
...
"""
function get_PWM_dutycycle(self::Pi, user_gpio)
return _u2i(_pigpio_command(self.sl, _PI_CMD_GDC, user_gpio, 0))
end
"""
Sets the range of PWM values to be used on the GPIO.
user_gpio:= 0-31.
range_:= 25-40000.
...
set_PWM_range(pi, 9, 100) # now 25 1/4, 50 1/2, 75 3/4 on
set_PWM_range(pi, 9, 500) # now 125 1/4, 250 1/2, 375 3/4 on
set_PWM_range(pi, 9, 3000) # now 750 1/4, 1500 1/2, 2250 3/4 on
...
"""
function set_PWM_range(self::Pi, user_gpio, range_)
return _u2i(_pigpio_command(self.sl, _PI_CMD_PRS, user_gpio, range_))
end
"""
Returns the range of PWM values being used on the GPIO.
user_gpio:= 0-31.
If a hardware clock or hardware PWM is active on the GPIO
the reported range will be 1000000 (1M).
...
set_PWM_range(pi, 9, 500)
print(get_PWM_range(pi, 9))
500
...
"""
function get_PWM_range(self::Pi, user_gpio)
return _u2i(_pigpio_command(self.sl, _PI_CMD_PRG, user_gpio, 0))
end
"""
Returns the real (underlying) range of PWM values being
used on the GPIO.
user_gpio:= 0-31.
If a hardware clock is active on the GPIO the reported
real range will be 1000000 (1M).
If hardware PWM is active on the GPIO the reported real range
will be approximately 250M divided by the set PWM frequency.
...
set_PWM_frequency(pi, 4, 800)
print(get_PWM_real_range(pi, 4))
250
...
"""
function get_PWM_real_range(self::Pi, user_gpio)
return _u2i(_pigpio_command(self.sl, _PI_CMD_PRRG, user_gpio, 0))
end
"""
Sets the frequency (in Hz) of the PWM to be used on the GPIO.
user_gpio:= 0-31.
frequency:= >=0 Hz
Returns the numerically closest frequency if OK, otherwise
PI_BAD_USER_GPIO or PI_NOT_PERMITTED.
If PWM is currently active on the GPIO it will be switched
off and then back on at the new frequency.
Each GPIO can be independently set to one of 18 different
PWM frequencies.
The selectable frequencies depend upon the sample rate which
may be 1, 2, 4, 5, 8, or 10 microseconds (default 5). The
sample rate is set when the pigpio daemon is started.
The frequencies for each sample rate are
. .
Hertz
1: 40000 20000 10000 8000 5000 4000 2500 2000 1600
1250 1000 800 500 400 250 200 100 50
2: 20000 10000 5000 4000 2500 2000 1250 1000 800
625 500 400 250 200 125 100 50 25
4: 10000 5000 2500 2000 1250 1000 625 500 400
313 250 200 125 100 63 50 25 13
sample
rate
(us) 5: 8000 4000 2000 1600 1000 800 500 400 320
250 200 160 100 80 50 40 20 10
8: 5000 2500 1250 1000 625 500 313 250 200
156 125 100 63 50 31 25 13 6
10: 4000 2000 1000 800 500 400 250 200 160
125 100 80 50 40 25 20 10 5
. .
...
set_PWM_frequency(pi, 4,0)
print(get_PWM_frequency(pi, 4))
10
set_PWM_frequency(pi, 4,100000)
print(get_PWM_frequency(pi, 4))
8000
...
"""
function set_PWM_frequency(self::Pi, user_gpio, frequency)
return _u2i(
_pigpio_command(self.sl, _PI_CMD_PFS, user_gpio, frequency))
end
"""
Returns the frequency of PWM being used on the GPIO.
user_gpio:= 0-31.
Returns the frequency (in Hz) used for the GPIO.
For normal PWM the frequency will be that defined for the GPIO
by [*set_PWM_frequency*].
If a hardware clock is active on the GPIO the reported frequency
will be that set by [*hardware_clock*].
If hardware PWM is active on the GPIO the reported frequency
will be that set by [*hardware_PWM*].
...
set_PWM_frequency(pi, 4,0)
print(get_PWM_frequency(pi, 4))
10
set_PWM_frequency(pi, 4, 800)
print(get_PWM_frequency(pi, 4))
800
...
"""
function get_PWM_frequency(self::Pi, user_gpio)
return _u2i(_pigpio_command(self.sl, _PI_CMD_PFG, user_gpio, 0))
end
"""
Starts (500-2500) or stops (0) servo pulses on the GPIO.
user_gpio:= 0-31.
pulsewidth:= 0 (off),
500 (most anti-clockwise) - 2500 (most clockwise).
The selected pulsewidth will continue to be transmitted until
changed by a subsequent call to set_servo_pulsewidth.
The pulsewidths supported by servos varies and should probably
be determined by experiment. A value of 1500 should always be
safe and represents the mid-point of rotation.
You can DAMAGE a servo if you command it to move beyond its
limits.
...
set_servo_pulsewidth(pi, 17, 0) # off
set_servo_pulsewidth(pi, 17, 1000) # safe anti-clockwise
set_servo_pulsewidth(pi, 17, 1500) # centre
set_servo_pulsewidth(pi, 17, 2000) # safe clockwise
...
"""
function set_servo_pulsewidth(self::Pi, user_gpio, pulsewidth)
return _u2i(_pigpio_command(
self.sl, _PI_CMD_SERVO, user_gpio, int(pulsewidth)))
end
"""
Returns the servo pulsewidth being used on the GPIO.
user_gpio:= 0-31.
Returns the servo pulsewidth.
...
set_servo_pulsewidth(pi, 4, 525)
print(get_servo_pulsewidth(pi, 4))
525
set_servo_pulsewidth(pi, 4, 2130)
print(get_servo_pulsewidth(pi, 4))
2130
...
"""
function get_servo_pulsewidth(self::Pi, user_gpio)
return _u2i(_pigpio_command(self.sl, _PI_CMD_GPW, user_gpio, 0))
end
"""
Returns a notification handle (>=0).
A notification is a method for being notified of GPIO state
changes via a pipe.
Pipes are only accessible from the local machine so this
function serves no purpose if you are using Python from a
remote machine. The in-built (socket) notifications
provided by [*callback*] should be used instead.
Notifications for handle x will be available at the pipe
named /dev/pigpiox (where x is the handle number).
E.g. if the function returns 15 then the notifications must be
read from /dev/pigpio15.
Notifications have the following structure.
. .
I seqno
I flags
I tick
I level
. .
seqno: starts at 0 each time the handle is opened and then
increments by one for each report.
flags: two flags are defined, PI_NTFY_FLAGS_WDOG and
PI_NTFY_FLAGS_ALIVE. If bit 5 is set (PI_NTFY_FLAGS_WDOG)
then bits 0-4 of the flags indicate a GPIO which has had a
watchdog timeout; if bit 6 is set (PI_NTFY_FLAGS_ALIVE) this
indicates a keep alive signal on the pipe/socket and is sent
once a minute in the absence of other notification activity.
tick: the number of microseconds since system boot. It wraps
around after 1h12m.
level: indicates the level of each GPIO. If bit 1<<x is set
then GPIO x is high.
...
h = notify_open(pi, )
if h >= 0
notify_begin(pi, h, 1234)
...
"""
function notify_open(self::Pi)
return _u2i(_pigpio_command(self.sl, _PI_CMD_NO, 0, 0))
end
"""
Starts notifications on a handle.
handle:= >=0 (as returned by a prior call to [*notify_open*])
bits:= a 32 bit mask indicating the GPIO to be notified.
The notification sends state changes for each GPIO whose
corresponding bit in bits is set.
The following code starts notifications for GPIO 1, 4,
6, 7, and 10 (1234 = 0x04D2 = 0b0000010011010010).
...
h = notify_open(pi, )
if h >= 0
notify_begin(pi, h, 1234)
...
"""
function notify_begin(self::Pi, handle, bits)
return _u2i(_pigpio_command(self.sl, _PI_CMD_NB, handle, bits))
end
"""
Pauses notifications on a handle.
handle:= >=0 (as returned by a prior call to [*notify_open*])
Notifications for the handle are suspended until
[*notify_begin*] is called again.
...
h = notify_open(pi, )
if h >= 0
notify_begin(pi, h, 1234)
...
notify_pause(pi, h)
...
notify_begin(pi, h, 1234)
...
...
"""
function notify_pause(self::Pi, handle)
return _u2i(_pigpio_command(self.sl, _PI_CMD_NB, handle, 0))
end
"""
Stops notifications on a handle and releases the handle for reuse.
handle:= >=0 (as returned by a prior call to [*notify_open*])
...
h = notify_open(pi, )
if h >= 0
notify_begin(pi, h, 1234)
...
notify_close(pi, h)
...
...
"""
function notify_close(self::Pi, handle)
return _u2i(_pigpio_command(self.sl, _PI_CMD_NC, handle, 0))
end
"""
Sets a watchdog timeout for a GPIO.
user_gpio:= 0-31.
wdog_timeout:= 0-60000.
The watchdog is nominally in milliseconds.
Only one watchdog may be registered per GPIO.
The watchdog may be cancelled by setting timeout to 0.
If no level change has been detected for the GPIO for timeout
milliseconds any notification for the GPIO has a report written
to the fifo with the flags set to indicate a watchdog timeout.
The callback class interprets the flags and will
call registered callbacks for the GPIO with level TIMEOUT.
...
set_watchdog(pi, 23, 1000) # 1000 ms watchdog on GPIO 23
set_watchdog(pi, 23, 0) # cancel watchdog on GPIO 23
...
"""
function set_watchdog(self::Pi, user_gpio, wdog_timeout)
return _u2i(_pigpio_command(
self.sl, _PI_CMD_WDOG, user_gpio, Int(wdog_timeout)))
end
"""
Returns the levels of the bank 1 GPIO (GPIO 0-31).
The returned 32 bit integer has a bit set if the corresponding
GPIO is high. GPIO n has bit value (1<<n).
...
print(bin(read_bank_1(pi, )))
0b10010100000011100100001001111
...
"""
function read_bank_1(self::Pi)
return _pigpio_command(self.sl, _PI_CMD_BR1, 0, 0)
end
"""
Returns the levels of the bank 2 GPIO (GPIO 32-53).
The returned 32 bit integer has a bit set if the corresponding
GPIO is high. GPIO n has bit value (1<<(n-32)).
...
print(bin(read_bank_2(pi, )))
0b1111110000000000000000
...
"""
function read_bank_2(self::Pi)
return _pigpio_command(self.sl, _PI_CMD_BR2, 0, 0)
end
"""
Clears GPIO 0-31 if the corresponding bit in bits is set.
bits:= a 32 bit mask with 1 set if the corresponding GPIO is
to be cleared.
A returned status of PI_SOME_PERMITTED indicates that the user
is not allowed to write to one or more of the GPIO.
...
clear_bank_1(int(pi, "111110010000",2))
...
"""
function clear_bank_1(self::Pi, bits)
return _u2i(_pigpio_command(self.sl, _PI_CMD_BC1, bits, 0))
end
"""
Clears GPIO 32-53 if the corresponding bit (0-21) in bits is set.
bits:= a 32 bit mask with 1 set if the corresponding GPIO is
to be cleared.
A returned status of PI_SOME_PERMITTED indicates that the user
is not allowed to write to one or more of the GPIO.
...
clear_bank_2(pi, 0x1010)
...
"""
function clear_bank_2(self::Pi, bits)
return _u2i(_pigpio_command(self.sl, _PI_CMD_BC2, bits, 0))
end
"""
Sets GPIO 0-31 if the corresponding bit in bits is set.
bits:= a 32 bit mask with 1 set if the corresponding GPIO is
to be set.
A returned status of PI_SOME_PERMITTED indicates that the user
is not allowed to write to one or more of the GPIO.
...
set_bank_1(int(pi, "111110010000",2))
...
"""
function set_bank_1(self::Pi, bits)
return _u2i(_pigpio_command(self.sl, _PI_CMD_BS1, bits, 0))
end
"""
Sets GPIO 32-53 if the corresponding bit (0-21) in bits is set.
bits:= a 32 bit mask with 1 set if the corresponding GPIO is
to be set.
A returned status of PI_SOME_PERMITTED indicates that the user
is not allowed to write to one or more of the GPIO.
...
set_bank_2(pi, 0x303)
...
"""
function set_bank_2(self::Pi, bits)
return _u2i(_pigpio_command(self.sl, _PI_CMD_BS2, bits, 0))
end
"""
Starts a hardware clock on a GPIO at the specified frequency.
Frequencies above 30MHz are unlikely to work.
gpio:= see description
clkfreq:= 0 (off) or 4689-250000000 (250M)
Returns 0 if OK, otherwise PI_NOT_PERMITTED, PI_BAD_GPIO,
PI_NOT_HCLK_GPIO, PI_BAD_HCLK_FREQ,or PI_BAD_HCLK_PASS.
The same clock is available on multiple GPIO. The latest
frequency setting will be used by all GPIO which share a clock.
The GPIO must be one of the following.
. .
4 clock 0 All models
5 clock 1 All models but A and B (reserved for system use)
6 clock 2 All models but A and B
20 clock 0 All models but A and B
21 clock 1 All models but A and Rev.2 B (reserved for system use)
32 clock 0 Compute module only
34 clock 0 Compute module only
42 clock 1 Compute module only (reserved for system use)
43 clock 2 Compute module only
44 clock 1 Compute module only (reserved for system use)
. .
Access to clock 1 is protected by a password as its use will
likely crash the Pi. The password is given by or'ing 0x5A000000
with the GPIO number.
...
hardware_clock(pi, 4, 5000) # 5 KHz clock on GPIO 4
hardware_clock(pi, 4, 40000000) # 40 MHz clock on GPIO 4
...
"""
function hardware_clock(self::Pi, gpio, clkfreq)
return _u2i(_pigpio_command(self.sl, _PI_CMD_HC, gpio, clkfreq))
end
"""
Starts hardware PWM on a GPIO at the specified frequency
and dutycycle. Frequencies above 30MHz are unlikely to work.
NOTE: Any waveform started by [*wave_send_once*],
[*wave_send_repeat*], or [*wave_chain*] will be cancelled.
This function is only valid if the pigpio main clock is PCM.
The main clock defaults to PCM but may be overridden when the
pigpio daemon is started (option -t).
gpio:= see descripton
PWMfreq:= 0 (off) or 1-125000000 (125M).
PWMduty:= 0 (off) to 1000000 (1M)(fully on).
Returns 0 if OK, otherwise PI_NOT_PERMITTED, PI_BAD_GPIO,
PI_NOT_HPWM_GPIO, PI_BAD_HPWM_DUTY, PI_BAD_HPWM_FREQ.
The same PWM channel is available on multiple GPIO.
The latest frequency and dutycycle setting will be used
by all GPIO which share a PWM channel.
The GPIO must be one of the following.
. .
12 PWM channel 0 All models but A and B
13 PWM channel 1 All models but A and B
18 PWM channel 0 All models
19 PWM channel 1 All models but A and B
40 PWM channel 0 Compute module only
41 PWM channel 1 Compute module only
45 PWM channel 1 Compute module only
52 PWM channel 0 Compute module only
53 PWM channel 1 Compute module only
. .
The actual number of steps beween off and fully on is the
integral part of 250 million divided by PWMfreq.
The actual frequency set is 250 million / steps.
There will only be a million steps for a PWMfreq of 250.
Lower frequencies will have more steps and higher
frequencies will have fewer steps. PWMduty is
automatically scaled to take this into account.
...
hardware_PWM(pi, 18, 800, 250000) # 800Hz 25% dutycycle
hardware_PWM(pi, 18, 2000, 750000) # 2000Hz 75% dutycycle
...
"""
function hardware_PWM(self::Pi, gpio, PWMfreq, PWMduty)
# pigpio message format
# I p1 gpio
# I p2 PWMfreq
# I p3 4
## extension ##
# I PWMdutycycle
extents = IOBuffer()
extents =write(extents, 10)
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_HP, gpio, PWMfreq, 4, extents))
end
"""
Returns the current system tick.
Tick is the number of microseconds since system boot. As an
unsigned 32 bit quantity tick wraps around approximately
every 71.6 minutes.
...
t1 = get_current_tick(pi, )
time.sleep(1)
t2 = get_current_tick(pi, )
...
"""
function get_current_tick(self::Pi)
return _pigpio_command(self.sl, _PI_CMD_TICK, 0, 0)
end
"""
Returns the Pi's hardware revision number.
The hardware revision is the last few characters on the
Revision line of /proc/cpuinfo.
The revision number can be used to determine the assignment
of GPIO to pins (see [*gpio*]).
There are at least three types of board.
Type 1 boards have hardware revision numbers of 2 and 3.
Type 2 boards have hardware revision numbers of 4, 5, 6, and 15.
Type 3 boards have hardware revision numbers of 16 or greater.
If the hardware revision can not be found or is not a valid
hexadecimal number the function returns 0.
...
print(get_hardware_revision(pi, ))
2
...
"""
function get_hardware_revision(self::Pi)
return _pigpio_command(self.sl, _PI_CMD_HWVER, 0, 0)
end
"""
Returns the pigpio software version.
...
v = get_pigpio_version(pi, )
...
"""
function get_pigpio_version(self::Pi)
return _pigpio_command(self.sl, _PI_CMD_PIGPV, 0, 0)
end
"""
Calls a pigpio function customised by the user.
arg1:= >=0, default 0.
arg2:= >=0, default 0.
argx:= extra arguments (each 0-255), default empty.
The returned value is an integer which by convention
should be >=0 for OK and <0 for error.
...
value = custom_1(pi, )
value = custom_1(pi, 23)
value = custom_1(pi, 0, 55)
value = custom_1(pi, 23, 56, [1, 5, 7])
value = custom_1(pi, 23, 56, b"hello")
value = custom_1(pi, 23, 56, "hello")
...
"""
function custom_1(self, arg1=0, arg2=0, argx=[])
# I p1 arg1
# I p2 arg2
# I p3 len
## extension ##
# s len argx bytes
return u2i(_pigpio_command_ext(
self.sl, _PI_CMD_CF1, arg1, arg2, length(argx), [argx]))
end
"""
Calls a pigpio function customised by the user.
arg1:= >=0, default 0.
argx:= extra arguments (each 0-255), default empty.
retMax:= >=0, maximum number of bytes to return, default 8192.
The returned value is a tuple of the number of bytes
returned and a bytearray containing the bytes. If
there was an error the number of bytes read will be
less than zero (and will contain the error code).
...
(count, data) = custom_2(pi, )
(count, data) = custom_2(pi, 23)
(count, data) = custom_2(pi, 23, [1, 5, 7])
(count, data) = custom_2(pi, 23, b"hello")
(count, data) = custom_2(pi, 23, "hello", 128)
...
"""
function custom_2(self, arg1=0, argx=[], retMax=8192)
# I p1 arg1
# I p2 retMax
# I p3 len
## extension ##
# s len argx bytes
# Don't raise exception. Must release lock.
bytes = u2i(_pigpio_command_ext(
self.sl, _PI_CMD_CF2, arg1, retMax, length(argx), [argx], false))
if bytes > 0
data = rxbuf(bytes)
else
data = ""
end
unlock(self.sl.l)
return bytes, data
end
"""
Calls a user supplied function (a callback) whenever the
specified GPIO edge is detected.
user_gpio:= 0-31.
edge:= EITHER_EDGE, RISING_EDGE (default), or FALLING_EDGE.
func:= user supplied callback function.
The user supplied callback receives three parameters, the GPIO,
the level, and the tick.
If a user callback is not specified a default tally callback is
provided which simply counts edges. The count may be retrieved
by calling the tally function. The count may be reset to zero
by calling the reset_tally function.
The callback may be cancelled by calling the cancel function.
A GPIO may have multiple callbacks (although I can't think of
a reason to do so).
...
end
function cbf(gpio, level, tick)
print(gpio, level, tick)
cb1 = callback(pi, 22, pigpio.EITHER_EDGE, cbf)
cb2 = callback(pi, 4, pigpio.EITHER_EDGE)
cb3 = callback(pi, 17)
print(cb3.tally())
cb3.reset_tally()
cb1.cancel() # To cancel callback cb1.
...
"""
function callback(self::Pi, user_gpio, edge=RISING_EDGE, func=nothing)
return _callback(self._notify, user_gpio, edge, func)
end
"""
Wait for an edge event on a GPIO.
user_gpio:= 0-31.
edge:= EITHER_EDGE, RISING_EDGE (default), or
FALLING_EDGE.
wait_timeout:= >=0.0 (default 60.0).
The function returns when the edge is detected or after
the number of seconds specified by timeout has expired.
Do not use this function for precise timing purposes,
the edge is only checked 20 times a second. Whenever
you need to know the accurate time of GPIO events use
a [*callback*] function.
The function returns true if the edge is detected,
otherwise false.
...
if wait_for_edge(pi, 23)
print("Rising edge detected")
else
print("wait for edge timed out")
if wait_for_edge(pi, 23, pigpio.FALLING_EDGE, 5.0)
print("Falling edge detected")
else
print("wait for falling edge timed out")
...
"""
function wait_for_edge(self::Pi, user_gpio, edge=RISING_EDGE, wait_timeout=60.0)
a = _wait_for_edge(self.notify, user_gpio, edge, wait_timeout)
return a.trigger
end
"""
Grants access to a Pi's GPIO.
host:= the host name of the Pi on which the pigpio daemon is
running. The default is localhost unless overridden by
the PIGPIO_ADDR environment variable.
port:= the port number on which the pigpio daemon is listening.
The default is 8888 unless overridden by the PIGPIO_PORT
environment variable. The pigpio daemon must have been
started with the same port number.
This connects to the pigpio daemon and reserves resources
to be used for sending commands and receiving notifications.
An instance attribute [*connected*] may be used to check the
success of the connection. If the connection is established
successfully [*connected*] will be true, otherwise false.
...
pi = pigpio.pi() # use defaults
pi = pigpio.pi('mypi') # specify host, default port
pi = pigpio.pi('mypi', 7777) # specify host and port
pi = pigpio.pi() # exit script if no connection
if not pi.connected
exit()
...
"""
function Pi(; host = get(ENV, "PIGPIO_ADDR", ""), port = get(ENV, "PIGPIO_PORT", 8888))
port = Int(port)
if host == "" || host == nothing
host = "localhost"
end
try
sock = connect(host, port)
ccall(:uv_tcp_nodelay, Cint, (Ptr{Cvoid}, Cuint), sock, 1) # Disable Nagle's Algorithm
sl = SockLock(sock, ReentrantLock())
notify = CallbackThread(sl, host, port)
self = Pi(host, port, true, sl, notify)
@info "Successfully connected!"
return self
#atexit.register(self.stop) #TODO
catch error
println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
println("Can't connect to pigpio at $host:$port")
println("Did you start the pigpio daemon? E.g. sudo pigpiod\n")
println("Did you specify the correct Pi host/port in the environment")
println("variables PIGPIO_ADDR/PIGPIO_PORT?")
println("E.g. export PIGPIO_ADDR=soft, export PIGPIO_PORT=8888\n")
println("Did you specify the correct Pi host/port in the")
println("Pi() function? E.g. Pi('soft', 8888))")
println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
throw(error)
end
end
"""Release pigpio resources.
...
stop(pi)
...
"""
function stop(self::Pi)
self.connected = false
stop(self.notify)
close(self.sl.s)
end
| PiGPIO | https://github.com/JuliaBerry/PiGPIO.jl.git |
|
[
"MIT"
] | 0.2.0 | d1a06655265b3ca5a4af73ecdd1a3d60e04711f6 | code | 11914 | """
Returns a handle for the SPI device on channel. Data will be
transferred at baud bits per second. The flags may be used to
modify the default behaviour of 4-wire operation, mode 0,
active low chip select.
An auxiliary SPI device is available on all models but the
A and B and may be selected by setting the A bit in the
flags. The auxiliary device has 3 chip selects and a
selectable word size in bits.
spi_channel:= 0-1 (0-2 for the auxiliary SPI device).
baud:= 32K-125M (values above 30M are unlikely to work).
spi_flags:= see below.
Normally you would only use the [*spi_**] functions if
you are or will be connecting to the Pi over a network. If
you will always run on the local Pi use the standard SPI
module instead.
spi_flags consists of the least significant 22 bits.
. .
21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
b b b b b b R T n n n n W A u2 u1 u0 p2 p1 p0 m m
. .
mm defines the SPI mode.
WARNING: modes 1 and 3 do not appear to work on
the auxiliary device.
. .
Mode POL PHA
0 0 0
1 0 1
2 1 0
3 1 1
. .
px is 0 if CEx is active low (default) and 1 for active high.
ux is 0 if the CEx GPIO is reserved for SPI (default)
and 1 otherwise.
A is 0 for the standard SPI device, 1 for the auxiliary SPI.
W is 0 if the device is not 3-wire, 1 if the device is 3-wire.
Standard SPI device only.
nnnn defines the number of bytes (0-15) to write before
switching the MOSI line to MISO to read data. This field
is ignored if W is not set. Standard SPI device only.
T is 1 if the least significant bit is transmitted on MOSI
first, the default (0) shifts the most significant bit out
first. Auxiliary SPI device only.
R is 1 if the least significant bit is received on MISO
first, the default (0) receives the most significant bit
first. Auxiliary SPI device only.
bbbbbb defines the word size in bits (0-32). The default (0)
sets 8 bits per word. Auxiliary SPI device only.
The [*spi_read*], [*spi_write*], and [*spi_xfer*] functions
transfer data packed into 1, 2, or 4 bytes according to
the word size in bits.
For bits 1-8 there will be one byte per character.
For bits 9-16 there will be two bytes per character.
For bits 17-32 there will be four bytes per character.
E.g. 32 12-bit words will be transferred in 64 bytes.
The other bits in flags should be set to zero.
...
# open SPI device on channel 1 in mode 3 at 50000 bits per second
h = spi_open(pi, 1, 50000, 3)
...
"""
function spi_open(self::Pi, spi_channel, baud, spi_flags=0)
# I p1 spi_channel
# I p2 baud
# I p3 4
## extension ##
# I spi_flags
extents=IOBuffer()
write(extents, spi_flags::Cint)
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_SPIO, spi_channel, baud, 4, extents))
end
"""
Closes the SPI device associated with handle.
handle:= >=0 (as returned by a prior call to [*spi_open*]).
...
spi_close(pi, h)
...
"""
function spi_close(self, handle)
return _u2i(_pigpio_command(self.sl, _PI_CMD_SPIC, handle, 0))
end
"""
Reads count bytes from the SPI device associated with handle.
handle:= >=0 (as returned by a prior call to [*spi_open*]).
count:= >0, the number of bytes to read.
The returned value is a tuple of the number of bytes read and a
bytearray containing the bytes. If there was an error the
number of bytes read will be less than zero (and will contain
the error code).
...
(b, d) = spi_read(pi, h, 60) # read 60 bytes from device h
if b == 60
# process read data
else
# error path
...
"""
function spi_read(self::Pi, handle, count)
# Don't raise exception. Must release lock.
bytes = u2i(_pigpio_command(
self.sl, _PI_CMD_SPIR, handle, count, false))
if bytes > 0
data = rxbuf(bytes)
else
data = ""
end
unlock(self.sl.l)
return bytes, data
end
"""
Writes the data bytes to the SPI device associated with handle.
handle:= >=0 (as returned by a prior call to [*spi_open*]).
data:= the bytes to write.
...
spi_write(pi, 0, b'\\x02\\xc0\\x80') # write 3 bytes to device 0
spi_write(pi, 0, b'defgh') # write 5 bytes to device 0
spi_write(pi, 0, "def") # write 3 bytes to device 0
spi_write(pi, 1, [2, 192, 128]) # write 3 bytes to device 1
...
"""
function spi_write(self::Pi, handle, data)
# I p1 handle
# I p2 0
# I p3 len
## extension ##
# s len data bytes
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_SPIW, handle, 0, length(data), data))
end
"""
Writes the data bytes to the SPI device associated with handle,
returning the data bytes read from the device.
handle:= >=0 (as returned by a prior call to [*spi_open*]).
data:= the bytes to write.
The returned value is a tuple of the number of bytes read and a
bytearray containing the bytes. If there was an error the
number of bytes read will be less than zero (and will contain
the error code).
...
(count, rx_data) = spi_xfer(pi, h, b'\\x01\\x80\\x00')
(count, rx_data) = spi_xfer(pi, h, [1, 128, 0])
(count, rx_data) = spi_xfer(pi, h, b"hello")
(count, rx_data) = spi_xfer(pi, h, "hello")
...
"""
function spi_xfer(self::Pi, handle, data)
# I p1 handle
# I p2 0
# I p3 len
## extension ##
# s len data bytes
# Don't raise exception. Must release lock.
bytes = u2i(_pigpio_command_ext(
self.sl, _PI_CMD_SPIX, handle, 0, length(data), data, false))
if bytes > 0
data = rxbuf(bytes)
else
data = ""
end
unlock(self.sl.l)
return bytes, data
end
"""
Returns a handle for the serial tty device opened
at baud bits per second.
tty:= the serial device to open.
baud:= baud rate in bits per second, see below.
ser_flags:= 0, no flags are currently defined.
Normally you would only use the [*serial_**] functions if
you are or will be connecting to the Pi over a network. If
you will always run on the local Pi use the standard serial
module instead.
The baud rate must be one of 50, 75, 110, 134, 150,
200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200,
38400, 57600, 115200, or 230400.
...
h1 = serial_open(pi, "/dev/ttyAMA0", 300)
h2 = serial_open(pi, "/dev/ttyUSB1", 19200, 0)
...
"""
function serial_open(self::Pi, tty, baud, ser_flags=0)
# I p1 baud
# I p2 ser_flags
# I p3 len
## extension ##
# s len data bytes
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_SERO, baud, ser_flags, length(tty), [tty]))
end
"""
Closes the serial device associated with handle.
handle:= >=0 (as returned by a prior call to [*serial_open*]).
...
serial_close(pi, h1)
...
"""
function serial_close(self::Pi, handle)
return _u2i(_pigpio_command(self.sl, _PI_CMD_SERC, handle, 0))
end
"""
Returns a single byte from the device associated with handle.
handle:= >=0 (as returned by a prior call to [*serial_open*]).
...
b = serial_read_byte(pi, h1)
...
"""
function serial_read_byte(self::Pi, handle)
return _u2i(_pigpio_command(self.sl, _PI_CMD_SERRB, handle, 0))
end
"""
Writes a single byte to the device associated with handle.
handle:= >=0 (as returned by a prior call to [*serial_open*]).
byte_val:= 0-255, the value to write.
...
serial_write_byte(pi, h1, 23)
serial_write_byte(h1, ord(pi, 'Z'))
...
"""
function serial_write_byte(self::Pi, handle, byte_val)
return _u2i(
_pigpio_command(self.sl, _PI_CMD_SERWB, handle, byte_val))
end
"""
Reads up to count bytes from the device associated with handle.
handle:= >=0 (as returned by a prior call to [*serial_open*]).
count:= >0, the number of bytes to read.
The returned value is a tuple of the number of bytes read and a
bytearray containing the bytes. If there was an error the
number of bytes read will be less than zero (and will contain
the error code).
...
(b, d) = serial_read(pi, h2, 100)
if b > 0
# process read data
...
"""
function serial_read(self::Pi, handle, count)
# Don't raise exception. Must release lock.
bytes = u2i(
_pigpio_command(self.sl, _PI_CMD_SERR, handle, count, false))
if bytes > 0
data = rxbuf(bytes)
else
data = ""
end
unlock(self.sl.l)
return bytes, data
end
"""
Writes the data bytes to the device associated with handle.
handle:= >=0 (as returned by a prior call to [*serial_open*]).
data:= the bytes to write.
...
serial_write(pi, h1, b'\\x02\\x03\\x04')
serial_write(pi, h2, b'help')
serial_write(pi, h2, "hello")
serial_write(pi, h1, [2, 3, 4])
...
"""
function serial_write(self::Pi, handle, data)
# I p1 handle
# I p2 0
# I p3 len
## extension ##
# s len data bytes
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_SERW, handle, 0, length(data), [data]))
end
"""
Returns the number of bytes available to be read from the
device associated with handle.
handle:= >=0 (as returned by a prior call to [*serial_open*]).
...
rdy = serial_data_available(pi, h1)
if rdy > 0
(b, d) = serial_read(pi, h1, rdy)
...
"""
function serial_data_available(self::Pi, handle)
return _u2i(_pigpio_command(self.sl, _PI_CMD_SERDA, handle, 0))
end
"""
Opens a GPIO for bit bang reading of serial data.
user_gpio:= 0-31, the GPIO to use.
baud:= 50-250000, the baud rate.
bb_bits:= 1-32, the number of bits per word, default 8.
The serial data is held in a cyclic buffer and is read using
[*bb_serial_read*].
It is the caller's responsibility to read data from the cyclic
buffer in a timely fashion.
...
status = bb_serial_read_open(pi, 4, 19200)
status = bb_serial_read_open(pi, 17, 9600)
...
"""
function bb_serial_read_open(self, user_gpio, baud, bb_bits=8)
# pigpio message format
# I p1 user_gpio
# I p2 baud
# I p3 4
## extension ##
# I bb_bits
extents = IOBuffer()
write(extents, bb_bits::Cuint)
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_SLRO, user_gpio, baud, 4, extents))
end
"""
Returns data from the bit bang serial cyclic buffer.
user_gpio:= 0-31 (opened in a prior call to [*bb_serial_read_open*])
The returned value is a tuple of the number of bytes read and a
bytearray containing the bytes. If there was an error the
number of bytes read will be less than zero (and will contain
the error code).
The bytes returned for each character depend upon the number of
data bits [*bb_bits*] specified in the [*bb_serial_read_open*]
command.
For [*bb_bits*] 1-8 there will be one byte per character.
For [*bb_bits*] 9-16 there will be two bytes per character.
For [*bb_bits*] 17-32 there will be four bytes per character.
...
(count, data) = bb_serial_read(pi, 4)
...
"""
function bb_serial_read(self, user_gpio)
# Don't raise exception. Must release lock.
bytes = u2i(
_pigpio_command(self.sl, _PI_CMD_SLR, user_gpio, 10000, false))
if bytes > 0
data = self._rxbuf(bytes)
else
data = ""
end
unlock(self.sl.l)
return bytes, data
end
"""
Closes a GPIO for bit bang reading of serial data.
user_gpio:= 0-31 (opened in a prior call to [*bb_serial_read_open*])
...
status = bb_serial_read_close(pi, 17)
...
"""
function bb_serial_read_close(self, user_gpio)
return _u2i(_pigpio_command(self.sl, _PI_CMD_SLRC, user_gpio, 0))
end
"""
Invert serial logic.
user_gpio:= 0-31 (opened in a prior call to [*bb_serial_read_open*])
invert:= 0-1 (1 invert, 0 normal)
...
status = bb_serial_invert(pi, 17, 1)
...
"""
function bb_serial_invert(self, user_gpio, invert)
return _u2i(_pigpio_command(self.sl, _PI_CMD_SLRI, user_gpio, invert))
end
| PiGPIO | https://github.com/JuliaBerry/PiGPIO.jl.git |
|
[
"MIT"
] | 0.2.0 | d1a06655265b3ca5a4af73ecdd1a3d60e04711f6 | code | 13467 | """
Clears all waveforms and any data added by calls to the
[*wave_add_**] functions.
...
wave_clear(pi, )
...
"""
function wave_clear(self::Pi)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVCLR, 0, 0))
end
"""
Starts a new empty waveform.
You would not normally need to call this function as it is
automatically called after a waveform is created with the
[*wave_create*] function.
...
wave_add_new(pi, )
...
"""
function wave_add_new(self::Pi)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVNEW, 0, 0))
end
"""
Adds a list of pulses to the current waveform.
pulses:= list of pulses to add to the waveform.
Returns the new total number of pulses in the current waveform.
The pulses are interleaved in time order within the existing
waveform (if any).
Merging allows the waveform to be built in parts, that is the
settings for GPIO#1 can be added, and then GPIO#2 etc.
If the added waveform is intended to start after or within
the existing waveform then the first pulse should consist
solely of a delay.
...
G1=4
G2=24
set_mode(pi, G1, pigpio.OUTPUT)
set_mode(pi, G2, pigpio.OUTPUT)
flash_500=[] # flash every 500 ms
flash_100=[] # flash every 100 ms
# ON OFF DELAY
flash_500.append(pigpio.pulse(1<<G1, 1<<G2, 500000))
flash_500.append(pigpio.pulse(1<<G2, 1<<G1, 500000))
flash_100.append(pigpio.pulse(1<<G1, 1<<G2, 100000))
flash_100.append(pigpio.pulse(1<<G2, 1<<G1, 100000))
wave_clear(pi, ) # clear any existing waveforms
wave_add_generic(pi, flash_500) # 500 ms flashes
f500 = wave_create(pi, ) # create and save id
wave_add_generic(pi, flash_100) # 100 ms flashes
f100 = wave_create(pi, ) # create and save id
wave_send_repeat(pi, f500)
time.sleep(4)
wave_send_repeat(pi, f100)
time.sleep(4)
wave_send_repeat(pi, f500)
time.sleep(4)
wave_tx_stop(pi, ) # stop waveform
wave_clear(pi, ) # clear all waveforms
...
"""
function wave_add_generic(self::Pi, pulses)
# pigpio message format
# I p1 0
# I p2 0
# I p3 pulses * 12
## extension ##
# III on/off/delay * pulses
if length(pulses)
ext = bytearray()
for p in pulses
ext.extend(pack("III", p.gpio_on, p.gpio_off, p.delay))
end
extents = [ext]
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_WVAG, 0, 0, length(pulses)*12, extents))
else
return 0
end
end
"""
Adds a waveform representing serial data to the existing
waveform (if any). The serial data starts [*offset*]
microseconds from the start of the waveform.
user_gpio:= GPIO to transmit data. You must set the GPIO mode
to output.
baud:= 50-1000000 bits per second.
data:= the bytes to write.
offset:= number of microseconds from the start of the
waveform, default 0.
bb_bits:= number of data bits, default 8.
bb_stop:= number of stop half bits, default 2.
Returns the new total number of pulses in the current waveform.
The serial data is formatted as one start bit, [*bb_bits*]
data bits, and [*bb_stop*]/2 stop bits.
It is legal to add serial data streams with different baud
rates to the same waveform.
The bytes required for each character depend upon [*bb_bits*].
For [*bb_bits*] 1-8 there will be one byte per character.
For [*bb_bits*] 9-16 there will be two bytes per character.
For [*bb_bits*] 17-32 there will be four bytes per character.
...
wave_add_serial(pi, 4, 300, 'Hello world')
wave_add_serial(pi, 4, 300, b"Hello world")
wave_add_serial(pi, 4, 300, b'\\x23\\x01\\x00\\x45')
wave_add_serial(pi, 17, 38400, [23, 128, 234], 5000)
...
"""
function wave_add_serial(
self::Pi, user_gpio, baud, data, offset=0, bb_bits=8, bb_stop=2)
if length(data)
extents = [pack("III", bb_bits, bb_stop, offset), data]
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_WVAS, user_gpio, baud, length(data)+12, extents))
else
return 0
end
end
"""
Creates a waveform from the data provided by the prior calls
to the [*wave_add_**] functions.
Returns a wave id (>=0) if OK, otherwise PI_EMPTY_WAVEFORM,
PI_TOO_MANY_CBS, PI_TOO_MANY_OOL, or PI_NO_WAVEFORM_ID.
The data provided by the [*wave_add_**] functions is consumed by
this function.
As many waveforms may be created as there is space available.
The wave id is passed to [*wave_send_**] to specify the waveform
to transmit.
Normal usage would be
Step 1. [*wave_clear*] to clear all waveforms and added data.
Step 2. [*wave_add_**] calls to supply the waveform data.
Step 3. [*wave_create*] to create the waveform and get a unique id
Repeat steps 2 and 3 as needed.
Step 4. [*wave_send_**] with the id of the waveform to transmit.
A waveform comprises one or more pulses.
A pulse specifies
1) the GPIO to be switched on at the start of the pulse.
2) the GPIO to be switched off at the start of the pulse.
3) the delay in microseconds before the next pulse.
Any or all the fields can be zero. It doesn't make any sense
to set all the fields to zero (the pulse will be ignored).
When a waveform is started each pulse is executed in order with
the specified delay between the pulse and the next.
...
wid = wave_create(pi, )
...
"""
function wave_create(self::Pi)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVCRE, 0, 0))
end
"""
This function deletes the waveform with id wave_id.
wave_id:= >=0 (as returned by a prior call to [*wave_create*]).
Wave ids are allocated in order, 0, 1, 2, etc.
...
wave_delete(pi, 6) # delete waveform with id 6
wave_delete(pi, 0) # delete waveform with id 0
...
"""
function wave_delete(self::Pi, wave_id)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVDEL, wave_id, 0))
end
"""
This function is deprecated and has been removed.
Use [*wave_create*]/[*wave_send_**] instead.
"""
function wave_tx_start(self::Pi) # DEPRECATED
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVGO, 0, 0))
end
"""
This function is deprecated and has beeen removed.
Use [*wave_create*]/[*wave_send_**] instead.
"""
function wave_tx_repeat(self::Pi) # DEPRECATED
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVGOR, 0, 0))
end
"""
Transmits the waveform with id wave_id. The waveform is sent
once.
NOTE: Any hardware PWM started by [*hardware_PWM*] will
be cancelled.
wave_id:= >=0 (as returned by a prior call to [*wave_create*]).
Returns the number of DMA control blocks used in the waveform.
...
cbs = wave_send_once(pi, wid)
...
"""
function wave_send_once(self::Pi, wave_id)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVTX, wave_id, 0))
end
"""
Transmits the waveform with id wave_id. The waveform repeats
until wave_tx_stop is called or another call to [*wave_send_**]
is made.
NOTE: Any hardware PWM started by [*hardware_PWM*] will
be cancelled.
wave_id:= >=0 (as returned by a prior call to [*wave_create*]).
Returns the number of DMA control blocks used in the waveform.
...
cbs = wave_send_repeat(pi, wid)
...
"""
function wave_send_repeat(self::Pi, wave_id)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVTXR, wave_id, 0))
end
"""
Transmits the waveform with id wave_id using mode mode.
wave_id:= >=0 (as returned by a prior call to [*wave_create*]).
mode:= WAVE_MODE_ONE_SHOT, WAVE_MODE_REPEAT,
WAVE_MODE_ONE_SHOT_SYNC, or WAVE_MODE_REPEAT_SYNC.
WAVE_MODE_ONE_SHOT: same as [*wave_send_once*].
WAVE_MODE_REPEAT same as [*wave_send_repeat*].
WAVE_MODE_ONE_SHOT_SYNC same as [*wave_send_once*] but tries
to sync with the previous waveform.
WAVE_MODE_REPEAT_SYNC same as [*wave_send_repeat*] but tries
to sync with the previous waveform.
WARNING: bad things may happen if you delete the previous
waveform before it has been synced to the new waveform.
NOTE: Any hardware PWM started by [*hardware_PWM*] will
be cancelled.
wave_id:= >=0 (as returned by a prior call to [*wave_create*]).
Returns the number of DMA control blocks used in the waveform.
...
cbs = wave_send_using_mode(pi, wid, WAVE_MODE_REPEAT_SYNC)
...
"""
function wave_send_using_mode(self::Pi, wave_id, mode)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVTXM, wave_id, mode))
end
"""
Returns the id of the waveform currently being
transmitted.
Returns the waveform id or one of the following special
values
WAVE_NOT_FOUND (9998) - transmitted wave not found.
NO_TX_WAVE (9999) - no wave being transmitted.
...
wid = wave_tx_at(pi, )
...
"""
function wave_tx_at(self::Pi)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVTAT, 0, 0))
end
"""
Returns 1 if a waveform is currently being transmitted,
otherwise 0.
...
wave_send_once(pi, 0) # send first waveform
while wave_tx_busy(pi, ): # wait for waveform to be sent
time.sleep(0.1)
wave_send_once(pi, 1) # send next waveform
...
"""
function wave_tx_busy(self::Pi)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVBSY, 0, 0))
end
"""
Stops the transmission of the current waveform.
This function is intended to stop a waveform started with
wave_send_repeat.
...
wave_send_repeat(pi, 3)
time.sleep(5)
wave_tx_stop(pi, )
...
"""
function wave_tx_stop(self::Pi)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVHLT, 0, 0))
end
"""
This function transmits a chain of waveforms.
NOTE: Any hardware PWM started by [*hardware_PWM*]
will be cancelled.
The waves to be transmitted are specified by the contents
of data which contains an ordered list of [*wave_id*]s
and optional command codes and related data.
Returns 0 if OK, otherwise PI_CHAIN_NESTING,
PI_CHAIN_LOOP_CNT, PI_BAD_CHAIN_LOOP, PI_BAD_CHAIN_CMD,
PI_CHAIN_COUNTER, PI_BAD_CHAIN_DELAY, PI_CHAIN_TOO_BIG,
or PI_BAD_WAVE_ID.
Each wave is transmitted in the order specified. A wave
may occur multiple times per chain.
A blocks of waves may be transmitted multiple times by
using the loop commands. The block is bracketed by loop
start and end commands. Loops may be nested.
Delays between waves may be added with the delay command.
The following command codes are supported
Name @ Cmd & Data @ Meaning
Loop Start @ 255 0 @ Identify start of a wave block
Loop Repeat @ 255 1 x y @ loop x + y*256 times
Delay @ 255 2 x y @ delay x + y*256 microseconds
Loop Forever @ 255 3 @ loop forever
If present Loop Forever must be the last entry in the chain.
The code is currently dimensioned to support a chain with
roughly 600 entries and 20 loop counters.
...
#!/usr/bin/env python
import time
import pigpio
WAVES=5
GPIO=4
wid=[0]*WAVES
pi = pigpio.pi() # Connect to local Pi.
set_mode(pi, GPIO, pigpio.OUTPUT);
for i in range(WAVES)
pi.wave_add_generic([
pigpio.pulse(1<<GPIO, 0, 20),
pigpio.pulse(0, 1<<GPIO, (i+1)*200)]);
wid[i] = wave_create(pi, );
pi.wave_chain([
wid[4], wid[3], wid[2], # transmit waves 4+3+2
255, 0, # loop start
wid[0], wid[0], wid[0], # transmit waves 0+0+0
255, 0, # loop start
wid[0], wid[1], # transmit waves 0+1
255, 2, 0x88, 0x13, # delay 5000us
255, 1, 30, 0, # loop end (repeat 30 times)
255, 0, # loop start
wid[2], wid[3], wid[0], # transmit waves 2+3+0
wid[3], wid[1], wid[2], # transmit waves 3+1+2
255, 1, 10, 0, # loop end (repeat 10 times)
255, 1, 5, 0, # loop end (repeat 5 times)
wid[4], wid[4], wid[4], # transmit waves 4+4+4
255, 2, 0x20, 0x4E, # delay 20000us
wid[0], wid[0], wid[0], # transmit waves 0+0+0
])
while wave_tx_busy(pi, )
time.sleep(0.1);
for i in range(WAVES)
wave_delete(pi, wid[i])
stop(pi, )
...
"""
function wave_chain(self::Pi, data)
# I p1 0
# I p2 0
# I p3 len
## extension ##
# s len data bytes
return _u2i(_pigpio_command_ext(
self.sl, _PI_CMD_WVCHA, 0, 0, length(data), [data]))
end
"""
Returns the length in microseconds of the current waveform.
...
micros = wave_get_micros(pi, )
...
"""
function wave_get_micros(self::Pi)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSM, 0, 0))
end
"""
Returns the maximum possible size of a waveform in microseconds.
...
micros = wave_get_max_micros(pi, )
...
"""
function wave_get_max_micros(self::Pi)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSM, 2, 0))
end
"""
Returns the length in pulses of the current waveform.
...
pulses = wave_get_pulses(pi, )
...
"""
function wave_get_pulses(self::Pi)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSP, 0, 0))
end
"""
Returns the maximum possible size of a waveform in pulses.
...
pulses = wave_get_max_pulses(pi, )
...
"""
function wave_get_max_pulses(self::Pi)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSP, 2, 0))
end
"""
Returns the length in DMA control blocks of the current
waveform.
...
cbs = wave_get_cbs(pi, )
...
"""
function wave_get_cbs(self::Pi)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSC, 0, 0))
end
"""
Returns the maximum possible size of a waveform in DMA
control blocks.
...
cbs = wave_get_max_cbs(pi, )
...
"""
function wave_get_max_cbs(self::Pi)
return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSC, 2, 0))
end
| PiGPIO | https://github.com/JuliaBerry/PiGPIO.jl.git |
|
[
"MIT"
] | 0.2.0 | d1a06655265b3ca5a4af73ecdd1a3d60e04711f6 | code | 55 | using PiGPIO
# write your own tests here
@test 1 == 1
| PiGPIO | https://github.com/JuliaBerry/PiGPIO.jl.git |
|
[
"MIT"
] | 0.2.0 | d1a06655265b3ca5a4af73ecdd1a3d60e04711f6 | docs | 2038 | # PiGPIO.jl
#### Control GPIO pins on the Raspberry Pi from Julia
[![][docs-stable-img]][docs-stable-url]
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: https://juliahub.com/docs/PiGPIO/
[](https://www.youtube.com/watch?v=UmSQjkaATk8)
PiGPIO.jl is a Julia package for the Raspberry which communicates with the pigpio
daemon to allow control of the general purpose
input outputs (GPIO).
This package is an effective translation of the python package for the same.
Which can be found [here](http://abyz.me.uk/rpi/pigpio/python.html)
Click [here](https://medium.com/@imkimfung/using-julia-to-control-leds-on-a-raspberry-pi-b320be83e503) for an **in-depth tutorial** on how you can control GPIO pins such as LEDs from Julia on the Raspberry Pi.
### Features
* OS independent. Only Julia 1.0+ required.
* Controls one or more Pi's.
* Hardware timed pulse width modulation.
* Hardware timed servo pulse.
* Callbacks when any of GPIO change state.
* Create and transmit precise waveforms.
* Read/Write GPIO and set their modes.
* Wrappers for I2C, SPI, and serial links.
Once a pigpio daemon is launched on the pi this package can connect to
it and communicate with it to manipulate the GPIO pins of the pi. The actual
work is done by the daemon. One benefit of working this way is that you can
remotely access the pi over a network and multiple instances can be connected
to the daemon simultaneously.
## Launching the Daemon
Launching the daemon requires sudo privileges. Launch by typing `sudo pigpiod`
in the terminal.
## Installation and Usage
```julia
using Pkg
Pkg.add("PiGPIO")
using PiGPIO
pi=Pi() #connect to pigpiod daemon on localhost
```
## Example Usage
```julia
set_mode(p::Pi, pin::Int, mode)
get_mode(p::Pi, pin::Int)
# mode can be INPUT or OUTPUT
PiGPIO.read(p, pin)
PiGPIO.write(p, pin, state)
#state can be HIGH, LOW, ON, OFF
PiGPIO.set_PWM_dutycycle(p, pin, dutycyle)
#dutycyle defaults to a range 0-255
```
| PiGPIO | https://github.com/JuliaBerry/PiGPIO.jl.git |
|
[
"MIT"
] | 0.2.0 | d1a06655265b3ca5a4af73ecdd1a3d60e04711f6 | docs | 2994 | ## Overview
Via this tutorial, we shall be going over the entire process of installation and use of the Julia Programming language on a Raspberry Pi. We will be using the [PiGPIO.jl](https://github.com/JuliaBerry/PiGPIO.jl) library for controlling GPIO elements (namely LEDs). We shall be building a simple circuit of two alternately blinking LEDs.
## What you'll need
You will require a Raspberry Pi (I am using a Raspberry Pi 3 model B+), along with the standard peripherals(keyboard, mouse, display, power supply), 1 breadboard, 2 resistors, 2 LEDs and jumper wires. I am assuming that you have the Raspbian OS set up and running on the Raspberry Pi. If not, take a look at [this tutorial.](https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up)
## Setting up Julia
In your __Raspbian commmand line__, simply run:
```
sudo apt install julia
```
Next, we need to launch a __pigpio daemon__, which PiGPIO.jl can connect to and control the GPIO pins. To do this, run the following command.
```
sudo pigpiod
```
Then, run this to enter the __Julia REPL__
```
julia
```
now run the following commands to install the __PiGPIO__ library:
```
using Pkg
Pkg.add("PiGPIO")
```
You should now be ready to start with the circuit
## Building the Circuit
connect the __cathode__ of both the LEDs to the __ground rail__ of the breadboard. Connect the __anode__, via an appropriate resistor (I used 82 ohm) to __GPIO pins 2 and 3__ of the Raspberry Pi.
### circuit diagram for reference:

You are now ready to launch Julia and start coding. PiGPIO.jl should be installed by now.
## The Code
You can run this code through an __external text editor__ or in the __Julia REPL__ itself.
First we need to import the package with the __using__ keyword. Next, we need to initialize the Raspberry Pi by creating an object variable and initialising it to __Pi()__
```Julia
using PiGPIO
pi = Pi()
```
Next, we need to intitialize the GPIO pins and their state (__INPUT/OUTPUT__ --> in this case __OUTPUT__).
```Julia
pin1 = 2 # GPIO pin 2
pin2 = 3 # GPIO pin 3
set_mode(pi, pin1, PiGPIO.OUTPUT)
set_mode(pi, pin2, PiGPIO.OUTPUT)
# ^ initialization
```
Now we shall use a for loop to implement the blinking LEDs
```Julia
num_loops = 20 # The number of times you want the lights to blink.
for i = 1:num_loops
PiGPIO.write(pi, pin1, HIGH) # setting GPIO pin state
PiGPIO.write(pi, pin2, LOW)
sleep(1) # delay in seconds
PiGPIO.write(pi, pin1, LOW)
PiGPIO.write(pi, pin2, HIGH)
sleep(1)
end
```
You should be getting blinking LEDs when you run this code.
### pictures of the final working model:


This project was made by Nand Vinchhi for the purpose of __GCI 2019__.
Circuit diagrams drawn with [circuit-diagram.org](https://www.circuit-diagram.org/)
| PiGPIO | https://github.com/JuliaBerry/PiGPIO.jl.git |
|
[
"MIT"
] | 0.2.0 | d1a06655265b3ca5a4af73ecdd1a3d60e04711f6 | docs | 65 | # PiGPIO API
```@index
```
```@autodocs
Modules = [PiGPIO]
```
| PiGPIO | https://github.com/JuliaBerry/PiGPIO.jl.git |
|
[
"MIT"
] | 0.2.0 | d1a06655265b3ca5a4af73ecdd1a3d60e04711f6 | docs | 1862 | # PiGPIO.jl
Documentation for PiGPIO.jl
#### Control GPIO pins on the Raspberry Pi from Julia
[![][docs-stable-img]][docs-stable-url]
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: https://pkg.julialang.org/docs/PiGPIO/
[](https://www.youtube.com/watch?v=UmSQjkaATk8)
PiGPIO.jl is a Julia package for the Raspberry which communicates with the pigpio
daemon to allow control of the general purpose
input outputs (GPIO).
This package is an effective translation of the python package for the same.
Which can be found [here](http://abyz.me.uk/rpi/pigpio/python.html)
### Features
* OS independent. Only Julia 1.0+ required.
* Controls one or more Pi's.
* Hardware timed pulse width modulation.
* Hardware timed servo pulse.
* Callbacks when any of GPIO change state.
* Create and transmit precise waveforms.
* Read/Write GPIO and set their modes.
* Wrappers for I2C, SPI, and serial links.
Once a pigpio daemon is launched on the pi this package can connect to
it and communicate with it to manipulate the GPIO pins of the pi. The actual
work is done by the daemon. One benefit of working this way is that you can
remotely access the pi over a network and multiple instances can be connected
to the daemon simultaneously.
## Launching the Daemon
Launching the daemon requires sudo privileges. Launch by typing `sudo pigpiod`
in the terminal.
## Installation and Usage
```julia
using Pkg
Pkg.add("PiGPIO")
using PiGPIO
pi=Pi() #connect to pigpiod daemon on localhost
```
## Example Usage
```julia
set_mode(p::Pi, pin::Int, mode)
get_mode(p::Pi, pin::Int)
# mode can be INPUT or OUTPUT
PiGPIO.read(p, pin)
PiGPIO.write(p, pin, state)
#state can be HIGH, LOW, ON, OFF
PiGPIO.set_PWM_dutycycle(p, pin, dutycyle)
#dutycyle defaults to a range 0-255
```
| PiGPIO | https://github.com/JuliaBerry/PiGPIO.jl.git |
|
[
"MIT"
] | 0.2.0 | 225ff13b22f4c88aeb70ce20e89b016c1897790b | code | 2597 | module ComoniconZSHCompletion
using ComoniconTypes
const tab = " "
function emit_zshcompletion(cmd::Entry)
name = cmd.root.name
"#compdef _$name $name \n" * emit_zshcompletion("_", cmd.root, true)
end
function emit_zshcompletion(prefix::String, cmd::NodeCommand, entry::Bool)
lines = [
"# These are set by _arguments",
"local context state state_descr line",
"typeset -A opt_args",
"",
]
args = basic_arguments(entry)
hints = map(values(cmd.subcmds)) do x
str = x.name * "\\:"
str *= "'" * x.description.brief * "'"
end
hints = "((" * join(hints, " ") * "))"
push!(args, "\"1: :$hints\"")
push!(args, "\"*:: :->args\"")
push!(lines, "_arguments -C \\")
append!(lines, map(x -> tab * x * " \\", args))
push!(lines, "")
push!(lines, raw"case $state in")
push!(lines, tab * "(args)")
push!(lines, tab * tab * raw"case ${words[1]} in")
commands = []
for (_, each) in cmd.subcmds
name = each.name
push!(commands, name * ")")
push!(commands, tab * prefix * cmd.name * "_" * name)
push!(commands, ";;")
end
append!(lines, map(x -> tab^3 * x, commands))
push!(lines, tab^2 * "esac")
push!(lines, "esac")
body = join(map(x -> tab * x, lines), "\n")
script = []
push!(
script,
"""
function $prefix$(cmd.name)() {
$body
}
""",
)
for (_, each) in cmd.subcmds
push!(script, emit_zshcompletion(prefix * cmd.name * "_", each, false))
end
return join(script, "\n\n")
end
function emit_zshcompletion(prefix::String, cmd::LeafCommand, entry::Bool)
lines = ["_arguments \\"]
args = basic_arguments(entry)
for (_, option) in cmd.options
name = option.name
doc = option.description.brief
token = "--$name"
if option.short
token = "{-$(name[1]),--$name}"
end
push!(args, "$token'[$doc]'")
end
append!(lines, map(x -> tab * x * " \\", args))
body = join(map(x -> tab * x, lines), "\n")
return """
function $prefix$(cmd.name)() {
$body
}
"""
end
function basic_arguments(entry)
args = ["'(- 1 *)'{-h,--help}'[show help information]'"]
if entry
push!(args, "'(- 1 *)'{-V,--version}'[show version information]'")
end
return args
end
function actions(args)
hints = map(args) do x
str = cmd_name(x) * "\\:"
str *= "'" * cmd_doc(x).first * "'"
end
return "((" * join(hints, " ") * "))"
end
end
| ComoniconZSHCompletion | https://github.com/comonicon/ComoniconZSHCompletion.jl.git |
|
[
"MIT"
] | 0.2.0 | 225ff13b22f4c88aeb70ce20e89b016c1897790b | code | 358 | using ComoniconTestUtils
using ComoniconZSHCompletion: emit_zshcompletion
using Test
using Random
Random.seed!(42)
@testset "test completion" for _ in 1:5
cmd = rand_command()
script = emit_zshcompletion(cmd)
@test occursin("#compdef _$(cmd.root.name) $(cmd.root.name)", script)
@test occursin("function _$(cmd.root.name)() {", script)
end
| ComoniconZSHCompletion | https://github.com/comonicon/ComoniconZSHCompletion.jl.git |
|
[
"MIT"
] | 0.2.0 | 225ff13b22f4c88aeb70ce20e89b016c1897790b | docs | 1004 | # ComoniconZSHCompletion
[](https://github.com/comonicon/ComoniconZSHCompletion.jl/actions)
[](https://codecov.io/gh/comonicon/ComoniconZSHCompletion.jl)
The ZSH auto-complete support for Comonicon.
## Installation
<p>
ComoniconZSHCompletion is a
<a href="https://julialang.org">
<img src="https://raw.githubusercontent.com/JuliaLang/julia-logo-graphics/master/images/julia.ico" width="16em">
Julia Language
</a>
package. To install ComoniconZSHCompletion,
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 type the following command
</p>
```julia
pkg> add ComoniconZSHCompletion
```
## License
MIT License
| ComoniconZSHCompletion | https://github.com/comonicon/ComoniconZSHCompletion.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.6.0 | f76a7a0f10af6ce7f227b7a921bfe351f628ed45 | code | 585 | module GraphPlot
using Compose # for plotting features
using Graphs
const gadflyjs = joinpath(dirname(Base.source_path()), "gadfly.js")
export
gplot,
gplothtml,
random_layout,
circular_layout,
collapse_layout,
community_layout,
spring_layout,
spectral_layout,
shell_layout,
stressmajorize_layout,
saveplot,
mm, cm, inch
include("deprecations.jl")
# layout algorithms
include("layout.jl")
include("stress.jl")
# ploting utilities
include("shape.jl")
include("lines.jl")
include("plot.jl")
include("collapse_plot.jl")
end # module
| GraphPlot | https://github.com/JuliaGraphs/GraphPlot.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.6.0 | f76a7a0f10af6ce7f227b7a921bfe351f628ed45 | code | 2712 | using GraphPlot
function collapse_graph(g::AbstractGraph, membership::Vector{Int})
nb_comm = maximum(membership)
collapsed_edge_weights = Vector{Dict{Int,Float64}}(undef, nb_comm)
for i=1:nb_comm
collapsed_edge_weights[i] = Dict{Int,Float64}()
end
for e in edges(g)
u = src(e)
v = dst(e)
u_comm = membership[u]
v_comm = membership[v]
# for special case of undirected network
if !is_directed(g)
u_comm, v_comm = minmax(u_comm, v_comm)
end
if haskey(collapsed_edge_weights[u_comm], v_comm)
collapsed_edge_weights[u_comm][v_comm] += 1
else
collapsed_edge_weights[u_comm][v_comm] = 1
end
end
collapsed_graph = SimpleGraph(nb_comm)
collapsed_weights = Float64[]
for u=1:nb_comm
for (v,w) in collapsed_edge_weights[u]
add_edge!(collapsed_graph, u, v)
push!(collapsed_weights, w)
end
end
return collapsed_graph, collapsed_weights
end
function community_layout(g::AbstractGraph, membership::Vector{Int})
N = length(membership)
lx = zeros(N)
ly = zeros(N)
comms = Dict{Int,Vector{Int}}()
for (idx,lbl) in enumerate(membership)
if haskey(comms, lbl)
push!(comms[lbl], idx)
else
comms[lbl] = Int[idx]
end
end
h, w = collapse_graph(g, membership)
clx, cly = spring_layout(h)
for (lbl, nodes) in comms
θ = range(0, stop=2pi, length=(length(nodes) + 1))[1:end-1]
for (idx, node) in enumerate(nodes)
lx[node] = 1.8*length(nodes)/N*cos(θ[idx]) + clx[lbl]
ly[node] = 1.8*length(nodes)/N*sin(θ[idx]) + cly[lbl]
end
end
return lx, ly
end
function collapse_layout(g::AbstractGraph, membership::Vector{Int})
sg = Graphs.SimpleGraph(nv(g))
for e in edges(g)
u = src(e)
v = dst(e)
Graphs.add_edge!(sg, u, v)
end
N = length(membership)
lx = zeros(N)
ly = zeros(N)
comms = Dict{Int,Vector{Int}}()
for (idx,lbl) in enumerate(membership)
if haskey(comms, lbl)
push!(comms[lbl], idx)
else
comms[lbl] = Int[idx]
end
end
h, w = collapse_graph(g, membership)
clx, cly = spring_layout(h)
for (lbl, nodes) in comms
subg = sg[nodes]
sublx, subly = spring_layout(subg)
θ = range(0, stop=2pi, length=(length(nodes) + 1))[1:end-1]
for (idx, node) in enumerate(nodes)
lx[node] = 1.8*length(nodes)/N*sublx[idx] + clx[lbl]
ly[node] = 1.8*length(nodes)/N*subly[idx] + cly[lbl]
end
end
return lx, ly
end
| GraphPlot | https://github.com/JuliaGraphs/GraphPlot.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.6.0 | f76a7a0f10af6ce7f227b7a921bfe351f628ed45 | code | 3023 | using Base: depwarn
function _nv(g)
depwarn("`GraphPlot._nv(g)` is deprectated. Use `Graphs.nv(g)` instead.", :_nv)
return Graphs.nv(g)
end
function _ne(g)
depwarn("`GraphPlot._ne(g)` is deprectated. Use `Graphs.ne(g)` instead.", :_ne)
return Graphs.ne(g)
end
function _vertices(g)
depwarn("`GraphPlot._vertices(g)` is deprectated. Use `Graphs.vertices(g)` instead.", :_vertices)
return Graphs.vertices(g)
end
function _edges(g)
depwarn("`GraphPlot._edges(g)` is deprectated. Use `Graphs.edges(g)` instead.", :_edges)
return Graphs.edges(g)
end
function _src_index(e, g)
depwarn("`GraphPlot._src_index(g)` is deprectated. Use `Graphs.src(e)` instead.", :_src_index)
return Graphs.src(e)
end
function _dst_index(e, g)
depwarn("`GraphPlot._dst_index(g)` is deprectated. Use `Graphs.dst(e)` instead.", :_dst_index)
return Graphs.dst(e)
end
function _adjacency_matrix(g)
depwarn("`GraphPlot._adjacency_matrix(g)` is deprectated. Use `Graphs.adjacency_matrix(g)` instead.", :_adjacency_matrix)
return Graphs.adjacency_matrix(g)
end
function _is_directed(g)
depwarn("`GraphPlot._is_directed(g)` is deprectated. Use `Graphs.is_directed(g)` instead.", :_is_directed)
return Graphs.is_directed(g)
end
function _laplacian_matrix(g)
depwarn("`GraphPlot._laplacian_matrix(g)` is deprectated. Use `Graphs.laplacian_matrix(g)` instead.", :_laplacian_matrix)
return Graphs.laplacian_matrix(g)
end
"""
read some famous graphs
**Paramenters**
*graphname*
Currently, `graphname` can be one of ["karate", "football", "dolphins",
"netscience", "polbooks", "power", "cond-mat"]
**Return**
a graph
**Example**
julia> g = graphfamous("karate")
"""
function graphfamous(graphname::AbstractString)
depwarn("""
`graphfamous` has been deprecated and will be removed in the future. Consider the package `GraphIO.jl` for loading graphs.
""", :graphfamous)
file = joinpath(dirname(@__DIR__), "data", graphname*".dat")
readedgelist(file)
end
export graphfamous
using DelimitedFiles: readdlm
"""read graph from in edgelist format"""
function readedgelist(filename; is_directed::Bool=false, start_index::Int=0, delim::Char=' ')
depwarn("""
`graphfamous` has been deprecated and will be removed in the future. Consider the package `GraphIO.jl` for loading graphs.
""", :graphfamous)
es = readdlm(filename, delim, Int)
es = unique(es, dims=1)
if start_index == 0
es = es .+ 1
end
N = maximum(es)
if is_directed
g = DiGraph(N)
for i=1:size(es,1)
add_edge!(g, es[i,1], es[i,2])
end
return g
else
for i=1:size(es,1)
if es[i,1] > es[i,2]
es[i,1], es[i,2] = es[i,2], es[i,1]
end
end
es = unique(es, dims=1)
g = Graph(N)
for i=1:size(es,1)
add_edge!(g, es[i,1], es[i,2])
end
return g
end
end
export readedgelist
| GraphPlot | https://github.com/JuliaGraphs/GraphPlot.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.6.0 | f76a7a0f10af6ce7f227b7a921bfe351f628ed45 | code | 7491 | using SparseArrays: SparseMatrixCSC, sparse
using ArnoldiMethod: SR
using Base: OneTo
using LinearAlgebra: eigen
"""
Position nodes uniformly at random in the unit square.
For every node, a position is generated by choosing each of dim
coordinates uniformly at random on the interval [0.0, 1.0).
**Parameters**
*G*
graph or list of nodes,
A position will be assigned to every node in G
**Return**
*locs_x, locs_y*
Locations of the nodes. Can be any units you want,
but will be normalized and centered anyway
**Examples**
```
julia> g = simple_house_graph()
julia> loc_x, loc_y = random_layout(g)
```
"""
function random_layout(g)
rand(nv(g)), rand(nv(g))
end
"""
This function wrap from [NetworkX](https://github.com/networkx/networkx)
Position nodes on a circle.
**Parameters**
*g*
a graph
**Returns**
*locs_x, locs_y*
Locations of the nodes. Can be any units you want,
but will be normalized and centered anyway
**Examples**
```
julia> g = smallgraph(:house)
julia> locs_x, locs_y = circular_layout(g)
```
"""
function circular_layout(g)
if nv(g) == 1
return [0.0], [0.0]
else
# Discard the extra angle since it matches 0 radians.
θ = range(0, stop=2pi, length=nv(g)+1)[1:end-1]
return cos.(θ), sin.(θ)
end
end
"""
This function is copy from [IainNZ](https://github.com/IainNZ)'s [GraphLayout.jl](https://github.com/IainNZ/GraphLayout.jl)
Use a modified version of the spring/repulsion model of Fruchterman and Reingold (1991):
+ Attractive force: f_a(d) = d / k
+ Repulsive force: f_r(d) = -k^2 / d^2
where d is distance between two vertices and the optimal distance
between vertices k is defined as C * sqrt( area / num_vertices )
where C is a parameter we can adjust
**Parameters**
*g*
a graph
*C*
Constant to fiddle with density of resulting layout
*MAXITER*
Number of iterations we apply the forces
*INITTEMP*
Initial "temperature", controls movement per iteration
*seed*
Integer seed for pseudorandom generation of locations (default = 0).
**Examples**
```
julia> g = smallgraph(:karate)
julia> locs_x, locs_y = spring_layout(g)
```
"""
function spring_layout(g::AbstractGraph,
locs_x_in::AbstractVector{R1}=2*rand(nv(g)).-1.0,
locs_y_in::AbstractVector{R2}=2*rand(nv(g)).-1.0;
C=2.0,
MAXITER=100,
INITTEMP=2.0) where {R1 <: Real, R2 <: Real}
nvg = nv(g)
adj_matrix = adjacency_matrix(g)
# The optimal distance bewteen vertices
k = C * sqrt(4.0 / nvg)
k² = k * k
# Store forces and apply at end of iteration all at once
force_x = zeros(nvg)
force_y = zeros(nvg)
# Convert locs to float
locs_x = convert(Vector{Float64}, locs_x_in)
locs_y = convert(Vector{Float64}, locs_y_in)
# Iterate MAXITER times
@inbounds for iter = 1:MAXITER
# Calculate forces
for i = 1:nvg
force_vec_x = 0.0
force_vec_y = 0.0
for j = 1:nvg
i == j && continue
d_x = locs_x[j] - locs_x[i]
d_y = locs_y[j] - locs_y[i]
dist² = (d_x * d_x) + (d_y * d_y)
dist = sqrt(dist²)
if !( iszero(adj_matrix[i,j]) && iszero(adj_matrix[j,i]) )
# Attractive + repulsive force
# F_d = dist² / k - k² / dist # original FR algorithm
F_d = dist / k - k² / dist²
else
# Just repulsive
# F_d = -k² / dist # original FR algorithm
F_d = -k² / dist²
end
force_vec_x += F_d*d_x
force_vec_y += F_d*d_y
end
force_x[i] = force_vec_x
force_y[i] = force_vec_y
end
# Cool down
temp = INITTEMP / iter
# Now apply them, but limit to temperature
for i = 1:nvg
fx = force_x[i]
fy = force_y[i]
force_mag = sqrt((fx * fx) + (fy * fy))
scale = min(force_mag, temp) / force_mag
locs_x[i] += force_x[i] * scale
locs_y[i] += force_y[i] * scale
end
end
# Scale to unit square
min_x, max_x = minimum(locs_x), maximum(locs_x)
min_y, max_y = minimum(locs_y), maximum(locs_y)
function scaler(z, a, b)
2.0*((z - a)/(b - a)) - 1.0
end
map!(z -> scaler(z, min_x, max_x), locs_x, locs_x)
map!(z -> scaler(z, min_y, max_y), locs_y, locs_y)
return locs_x, locs_y
end
using Random: MersenneTwister
function spring_layout(g::AbstractGraph, seed::Integer; kws...)
rng = MersenneTwister(seed)
spring_layout(g, 2 .* rand(rng, nv(g)) .- 1.0, 2 .* rand(rng,nv(g)) .- 1.0; kws...)
end
"""
This function is copy from [IainNZ](https://github.com/IainNZ)'s [GraphLayout.jl](https://github.com/IainNZ/GraphLayout.jl)
Position nodes in concentric circles.
**Parameters**
*g*
a graph
*nlist*
Vector of Vector, Vector of node Vector for each shell.
**Examples**
```
julia> g = smallgraph(:karate)
julia> nlist = Vector{Vector{Int}}()
julia> push!(nlist, collect(1:5))
julia> push!(nlist, collect(6:nv(g)))
julia> locs_x, locs_y = shell_layout(g, nlist)
```
"""
function shell_layout(g, nlist::Union{Nothing, Vector{Vector{Int}}} = nothing)
if nv(g) == 1
return [0.0], [0.0]
end
if isnothing(nlist)
nlist = [collect(1:nv(g))]
end
radius = 0.0
if length(nlist[1]) > 1
radius = 1.0
end
locs_x = zeros(nv(g))
locs_y = zeros(nv(g))
for nodes in nlist
# Discard the extra angle since it matches 0 radians.
θ = range(0, stop=2pi, length=length(nodes)+1)[1:end-1]
locs_x[nodes] = radius*cos.(θ)
locs_y[nodes] = radius*sin.(θ)
radius += 1.0
end
return locs_x, locs_y
end
"""
This function wrap from [NetworkX](https://github.com/networkx/networkx)
Position nodes using the eigenvectors of the graph Laplacian.
**Parameters**
*g*
a graph
*weight*
array or nothing, optional (default=nothing)
The edge attribute that holds the numerical value used for
the edge weight. If None, then all edge weights are 1.
**Examples**
```
julia> g = smallgraph(:karate)
julia> weight = rand(ne(g))
julia> locs_x, locs_y = spectral_layout(g, weight)
```
"""
function spectral_layout(g::AbstractGraph, weight=nothing)
if nv(g) == 1
return [0.0], [0.0]
elseif nv(g) == 2
return [0.0, 1.0], [0.0, 0.0]
end
if weight == nothing
weight = ones(ne(g))
end
if nv(g) > 500
A = sparse(Int[src(e) for e in edges(g)],
Int[dst(e) for e in edges(g)],
weight, nv(g), nv(g))
if is_directed(g)
A = A + transpose(A)
end
return _spectral(A)
else
L = laplacian_matrix(g)
return _spectral(Matrix(L))
end
end
function _spectral(L::Matrix)
eigenvalues, eigenvectors = eigen(L)
index = sortperm(eigenvalues)[2:3]
return eigenvectors[:, index[1]], eigenvectors[:, index[2]]
end
function _spectral(A::SparseMatrixCSC)
data = vec(sum(A, dims=1))
D = sparse(Base.OneTo(length(data)), Base.OneTo(length(data)), data)
L = D - A
eigenvalues, eigenvectors = Graphs.LinAlg.eigs(L, nev=3, which=SR())
index = sortperm(real(eigenvalues))[2:3]
return real(eigenvectors[:, index[1]]), real(eigenvectors[:, index[2]])
end
| GraphPlot | https://github.com/JuliaGraphs/GraphPlot.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.6.0 | f76a7a0f10af6ce7f227b7a921bfe351f628ed45 | code | 10979 | """
Return lines and arrow heads
"""
function midpoint(pt1,pt2)
x = (pt1[1] + pt2[1]) / 2
y = (pt1[2] + pt2[2]) / 2
return x,y
end
function interpolate_bezier(x::Vector,t)
#TODO: since this is only being used for `curve` which has 4 points (n = 3), the calculation can be simplified for this case.
n = length(x)-1
x_loc = sum(binomial(n,i)*(1-t)^(n-i)*t^i*x[i+1][1] for i in 0:n)
y_loc = sum(binomial(n,i)*(1-t)^(n-i)*t^i*x[i+1][2] for i in 0:n)
return x_loc.value, y_loc.value
end
interpolate_bezier(x::Compose.CurvePrimitive,t) =
interpolate_bezier([x.anchor0, x.ctrl0, x.ctrl1, x.anchor1], t)
function interpolate_line(locs_x,locs_y,i,j,t)
x_loc = locs_x[i] + (locs_x[j]-locs_x[i])*t
y_loc = locs_y[i] + (locs_y[j]-locs_y[i])*t
return x_loc, y_loc
end
function graphline(edge_list, locs_x, locs_y, nodesize::Vector{T}, arrowlength, angleoffset) where {T<:Real}
num_edges = length(edge_list)
lines = Array{Vector{Tuple{Float64,Float64}}}(undef, num_edges)
arrows = Array{Vector{Tuple{Float64,Float64}}}(undef, num_edges)
for (e_idx, e) in enumerate(edge_list)
i = src(e)
j = dst(e)
Δx = locs_x[j] - locs_x[i]
Δy = locs_y[j] - locs_y[i]
θ = atan(Δy,Δx)
startx = locs_x[i] + nodesize[i]*cos(θ)
starty = locs_y[i] + nodesize[i]*sin(θ)
endx = locs_x[j] + nodesize[j]*cos(θ+π)
endy = locs_y[j] + nodesize[j]*sin(θ+π)
arr1, arr2 = arrowcoords(θ, endx, endy, arrowlength, angleoffset)
endx0, endy0 = midpoint(arr1, arr2)
e_idx2 = findfirst(==(Edge(j,i)), collect(edge_list)) #get index of reverse arc
if !isnothing(e_idx2) && e_idx2 < e_idx #only make changes if lines/arrows have already been defined for that arc
startx, starty = midpoint(arrows[e_idx2][[1,3]]...) #get midopint of reverse arc and use as new start point
lines[e_idx2][1] = (endx0, endy0) #update endpoint of reverse arc
end
lines[e_idx] = [(startx, starty), (endx0, endy0)]
arrows[e_idx] = [arr1, (endx, endy), arr2]
end
lines, arrows
end
function graphline(edge_list, locs_x, locs_y, nodesize::Real, arrowlength, angleoffset)
num_edges = length(edge_list)
lines = Array{Vector{Tuple{Float64,Float64}}}(undef, num_edges)
arrows = Array{Vector{Tuple{Float64,Float64}}}(undef, num_edges)
for (e_idx, e) in enumerate(edge_list)
i = src(e)
j = dst(e)
Δx = locs_x[j] - locs_x[i]
Δy = locs_y[j] - locs_y[i]
θ = atan(Δy,Δx)
startx = locs_x[i] + nodesize*cos(θ)
starty = locs_y[i] + nodesize*sin(θ)
endx = locs_x[j] + nodesize*cos(θ+π)
endy = locs_y[j] + nodesize*sin(θ+π)
arr1, arr2 = arrowcoords(θ, endx, endy, arrowlength, angleoffset)
endx0, endy0 = midpoint(arr1, arr2)
e_idx2 = findfirst(==(Edge(j,i)), collect(edge_list)) #get index of reverse arc
if !isnothing(e_idx2) && e_idx2 < e_idx #only make changes if lines/arrows have already been defined for that arc
startx, starty = midpoint(arrows[e_idx2][[1,3]]...) #get midopint of reverse arc and use as new start point
lines[e_idx2][1] = (endx0, endy0) #update endpoint of reverse arc
end
lines[e_idx] = [(startx, starty), (endx0, endy0)]
arrows[e_idx] = [arr1, (endx, endy), arr2]
end
lines, arrows
end
function graphline(edge_list, locs_x, locs_y, nodesize::Vector{T}) where {T<:Real}
num_edges = length(edge_list)
lines = Array{Vector{Tuple{Float64,Float64}}}(undef, num_edges)
for (e_idx, e) in enumerate(edge_list)
i = src(e)
j = dst(e)
Δx = locs_x[j] - locs_x[i]
Δy = locs_y[j] - locs_y[i]
θ = atan(Δy,Δx)
startx = locs_x[i] + nodesize[i]*cos(θ)
starty = locs_y[i] + nodesize[i]*sin(θ)
endx = locs_x[j] + nodesize[j]*cos(θ+π)
endy = locs_y[j] + nodesize[j]*sin(θ+π)
lines[e_idx] = [(startx, starty), (endx, endy)]
end
lines
end
function graphline(edge_list, locs_x, locs_y, nodesize::Real)
num_edges = length(edge_list)
lines = Array{Vector{Tuple{Float64,Float64}}}(undef, num_edges)
for (e_idx, e) in enumerate(edge_list)
i = src(e)
j = dst(e)
Δx = locs_x[j] - locs_x[i]
Δy = locs_y[j] - locs_y[i]
θ = atan(Δy,Δx)
startx = locs_x[i] + nodesize*cos(θ)
starty = locs_y[i] + nodesize*sin(θ)
endx = locs_x[j] + nodesize*cos(θ+π)
endy = locs_y[j] + nodesize*sin(θ+π)
lines[e_idx] = [(startx, starty), (endx, endy)]
end
return lines
end
function graphcurve(edge_list, locs_x, locs_y, nodesize::Vector{T}, arrowlength, angleoffset, outangle=pi/5) where {T<:Real}
num_edges = length(edge_list)
curves = Matrix{Tuple{Float64,Float64}}(undef, num_edges, 4)
arrows = Array{Vector{Tuple{Float64,Float64}}}(undef, num_edges)
for (e_idx, e) in enumerate(edge_list)
i = src(e)
j = dst(e)
Δx = locs_x[j] - locs_x[i]
Δy = locs_y[j] - locs_y[i]
θ = atan(Δy,Δx)
startx = locs_x[i] + nodesize[i]*cos(θ+outangle)
starty = locs_y[i] + nodesize[i]*sin(θ+outangle)
endx = locs_x[j] + nodesize[j]*cos(θ+π-outangle)
endy = locs_y[j] + nodesize[j]*sin(θ+π-outangle)
d = hypot(endx-startx, endy-starty)
if i == j
d = 2 * π * nodesize[i]
end
arr1, arr2 = arrowcoords(θ-outangle, endx, endy, arrowlength, angleoffset)
endx0 = (arr1[1] + arr2[1]) / 2
endy0 = (arr1[2] + arr2[2]) / 2
curves[e_idx, :] = curveedge(startx, starty, endx0, endy0, θ, outangle, d)
arrows[e_idx] = [arr1, (endx, endy), arr2]
end
return curves, arrows
end
function graphcurve(edge_list, locs_x, locs_y, nodesize::Real, arrowlength, angleoffset, outangle=pi/5)
num_edges = length(edge_list)
curves = Matrix{Tuple{Float64,Float64}}(undef, num_edges, 4)
arrows = Array{Vector{Tuple{Float64,Float64}}}(undef, num_edges)
for (e_idx, e) in enumerate(edge_list)
i = src(e)
j = dst(e)
Δx = locs_x[j] - locs_x[i]
Δy = locs_y[j] - locs_y[i]
θ = atan(Δy,Δx)
startx = locs_x[i] + nodesize*cos(θ+outangle)
starty = locs_y[i] + nodesize*sin(θ+outangle)
endx = locs_x[j] + nodesize*cos(θ+π-outangle)
endy = locs_y[j] + nodesize*sin(θ+π-outangle)
d = hypot(endx-startx, endy-starty)
if i == j
d = 2 * π * nodesize
end
arr1, arr2 = arrowcoords(θ-outangle, endx, endy, arrowlength, angleoffset)
endx0 = (arr1[1] + arr2[1]) / 2
endy0 = (arr1[2] + arr2[2]) / 2
curves[e_idx, :] = curveedge(startx, starty, endx0, endy0, θ, outangle, d)
arrows[e_idx] = [arr1, (endx, endy), arr2]
end
return curves, arrows
end
function graphcurve(edge_list, locs_x, locs_y, nodesize::Real, outangle)
num_edges = length(edge_list)
curves = Matrix{Tuple{Float64,Float64}}(undef, num_edges, 4)
for (e_idx, e) in enumerate(edge_list)
i = src(e)
j = dst(e)
Δx = locs_x[j] - locs_x[i]
Δy = locs_y[j] - locs_y[i]
θ = atan(Δy,Δx)
startx = locs_x[i] + nodesize*cos(θ+outangle)
starty = locs_y[i] + nodesize*sin(θ+outangle)
endx = locs_x[j] + nodesize*cos(θ+π-outangle)
endy = locs_y[j] + nodesize*sin(θ+π-outangle)
d = hypot(endx-startx, endy-starty)
if i == j
d = 2 * π * nodesize
end
curves[e_idx, :] = curveedge(startx, starty, endx, endy, θ, outangle, d)
end
return curves
end
function graphcurve(edge_list, locs_x, locs_y, nodesize::Vector{T}, outangle) where {T<:Real}
num_edges = length(edge_list)
curves = Matrix{Tuple{Float64,Float64}}(undef, num_edges, 4)
for (e_idx, e) in enumerate(edge_list)
i = src(e)
j = dst(e)
Δx = locs_x[j] - locs_x[i]
Δy = locs_y[j] - locs_y[i]
θ = atan(Δy,Δx)
startx = locs_x[i] + nodesize[i]*cos(θ+outangle)
starty = locs_y[i] + nodesize[i]*sin(θ+outangle)
endx = locs_x[j] + nodesize[j]*cos(θ+π-outangle)
endy = locs_y[j] + nodesize[j]*sin(θ+π-outangle)
d = hypot(endx-startx, endy-starty)
if i == j
d = 2 * π * nodesize[i]
end
curves[e_idx, :] = curveedge(startx, starty, endx, endy, θ, outangle, d)
end
return curves
end
# this function is copy from [IainNZ](https://github.com/IainNZ)'s [GraphLayout.jl](https://github.com/IainNZ/GraphLayout.jl)
function arrowcoords(θ, endx, endy, arrowlength, angleoffset=20.0/180.0*π)
arr1x = endx - arrowlength*cos(θ+angleoffset)
arr1y = endy - arrowlength*sin(θ+angleoffset)
arr2x = endx - arrowlength*cos(θ-angleoffset)
arr2y = endy - arrowlength*sin(θ-angleoffset)
return (arr1x, arr1y), (arr2x, arr2y)
end
function curveedge(x1, y1, x2, y2, θ, outangle, d; k=0.5)
r = d * k
# Control points for left bending curve.
xc1 = x1 + r * cos(θ + outangle)
yc1 = y1 + r * sin(θ + outangle)
xc2 = x2 + r * cos(θ + π - outangle)
yc2 = y2 + r * sin(θ + π - outangle)
return [(x1,y1) (xc1, yc1) (xc2, yc2) (x2, y2)]
end
function build_curved_edges(edge_list, locs_x, locs_y, nodesize, arrowlengthfrac, arrowangleoffset, outangle)
if arrowlengthfrac > 0.0
curves_cord, arrows_cord = graphcurve(edge_list, locs_x, locs_y, nodesize, arrowlengthfrac, arrowangleoffset, outangle)
curves = curve(curves_cord[:,1], curves_cord[:,2], curves_cord[:,3], curves_cord[:,4])
carrows = polygon(arrows_cord)
else
curves_cord = graphcurve(edge_list, locs_x, locs_y, nodesize, outangle)
curves = curve(curves_cord[:,1], curves_cord[:,2], curves_cord[:,3], curves_cord[:,4])
carrows = nothing
end
return curves, carrows
end
function build_straight_edges(edge_list, locs_x, locs_y, nodesize, arrowlengthfrac, arrowangleoffset)
if arrowlengthfrac > 0.0
lines_cord, arrows_cord = graphline(edge_list, locs_x, locs_y, nodesize, arrowlengthfrac, arrowangleoffset)
lines = line(lines_cord)
larrows = polygon(arrows_cord)
else
lines_cord = graphline(edge_list, locs_x, locs_y, nodesize)
lines = line(lines_cord)
larrows = nothing
end
return lines, larrows
end
function build_straight_curved_edges(g, locs_x, locs_y, nodesize, arrowlengthfrac, arrowangleoffset, outangle)
edge_list1 = filter(e -> src(e) != dst(e), collect(edges(g)))
edge_list2 = filter(e -> src(e) == dst(e), collect(edges(g)))
lines, larrows = build_straight_edges(edge_list1, locs_x, locs_y, nodesize, arrowlengthfrac, arrowangleoffset)
curves, carrows = build_curved_edges(edge_list2, locs_x, locs_y, nodesize, arrowlengthfrac, arrowangleoffset, outangle)
return lines, larrows, curves, carrows
end | GraphPlot | https://github.com/JuliaGraphs/GraphPlot.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.6.0 | f76a7a0f10af6ce7f227b7a921bfe351f628ed45 | code | 1012 | # to do
mutable struct PIENODE
x::Float64
y::Float64
r::Float64
prop::Vector{Float64}
colors
strokes
end
function pie(pn::PIENODE)
p = [0.0;2pi*pn.prop/sum(pn.prop)]
θ = cumsum(p)
s = Vector[]
for i=1:length(θ)-1
push!(s, sector(pn.x, pn.y, pn.r, θ[i], θ[i+1]))
end
compose(context(),path(s), fill(pn.colors), stroke(pn.strokes))
end
function sector(x, y, r, θ1, θ2)
if θ2-θ1<=pi
[:M, x+r*cos(θ1),y-r*sin(θ1), :A, r, r, 0, false, false, x+r*cos(θ2), y-r*sin(θ2), :L, x, y, :Z]
else
[
:M, x+r*cos(θ1),y-r*sin(θ1),
:A, r, r, 0, false, false, x+r*cos(θ1+pi), y-r*sin(θ1+pi),
:A, r, r, 0, false, false, x+r*cos(θ2), y-r*sin(θ2),
:L, x, y,
:Z
]
end
end
function sector(x::Vector{T}, y::Vector{T}, r::Vector{T}, θ1::Vector{T}, θ2::Vector{T}) where {T}
s = Vector[]
for i=1:length(x)
push!(s, sector(x[i],y[i],r[i],θ1[i],θ2[i]))
end
s
end
| GraphPlot | https://github.com/JuliaGraphs/GraphPlot.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.6.0 | f76a7a0f10af6ce7f227b7a921bfe351f628ed45 | code | 11072 | using Colors
# this function is copy from [GraphLayout.jl](https://github.com/IainNZ/GraphLayout.jl) and make some modifications.
"""
Given a graph and two vectors of X and Y coordinates, returns
a Compose tree of the graph layout
**Arguments**
`G`
Graph to draw
`locs_x, locs_y`
Locations of the nodes. Can be any units you want,
but will be normalized and centered anyway. If not provided, will
be obtained from `layout` kwarg.
**Keyword Arguments**
`layout`
Layout algorithm. Currently can be one of [`random_layout`,
`circular_layout`, `spring_layout`, `shell_layout`, `stressmajorize_layout`,
`spectral_layout`].
Default: `spring_layout`
`title`
Plot title. Default: `""`
`title_color`
Plot title color. Default: `colorant"black"`
`title_size`
Plot title size. Default: `4.0`
`font_family`
Font family for all text. Default: `"Helvetica"`
`NODESIZE`
Max size for the nodes. Default: `3.0/sqrt(N)`
`nodesize`
Relative size for the nodes, can be a Vector. Default: `1.0`
`nodelabel`
Labels for the vertices, a Vector or nothing. Default: `nothing`
`nodelabelc`
Color for the node labels, can be a Vector. Default: `colorant"black"`
`nodelabeldist`
Distances for the node labels from center of nodes. Default: `0.0`
`nodelabelangleoffset`
Angle offset for the node labels. Default: `π/4.0`
`NODELABELSIZE`
Largest fontsize for the vertex labels. Default: `4.0`
`nodelabelsize`
Relative fontsize for the vertex labels, can be a Vector. Default: `1.0`
`nodefillc`
Color to fill the nodes with, can be a Vector. Default: `colorant"turquoise"`
`nodestrokec`
Color for the nodes stroke, can be a Vector. Default: `nothing`
`nodestrokelw`
Line width for the nodes stroke, can be a Vector. Default: `0.0`
`edgelabel`
Labels for the edges, a Vector or nothing. Default: `[]`
`edgelabelc`
Color for the edge labels, can be a Vector. Default: `colorant"black"`
`edgelabeldistx, edgelabeldisty`
Distance for the edge label from center of edge. Default: `0.0`
`EDGELABELSIZE`
Largest fontsize for the edge labels. Default: `4.0`
`edgelabelsize`
Relative fontsize for the edge labels, can be a Vector. Default: `1.0`
`EDGELINEWIDTH`
Max line width for the edges. Default: `0.25/sqrt(N)`
`edgelinewidth`
Relative line width for the edges, can be a Vector. Default: `1.0`
`edgestrokec`
Color for the edge strokes, can be a Vector. Default: `colorant"lightgray"`
`arrowlengthfrac`
Fraction of line length to use for arrows.
Equal to 0 for undirected graphs. Default: `0.1` for the directed graphs
`arrowangleoffset`
Angular width in radians for the arrows. Default: `π/9 (20 degrees)`
`linetype`
Type of line used for edges ("straight", "curve"). Default: "straight"
`outangle`
Angular width in radians for the edges (only used if `linetype = "curve`).
Default: `π/5 (36 degrees)`
`background_color`
Color for the plot background. Default: `nothing`
`plot_size`
Tuple of measures for width x height for plot area. Default: `(10cm, 10cm)`
`leftpad, rightpad, toppad, bottompad`
Padding for the plot margins. Default: `0mm`
`pad`
Padding for plot margins (overrides individual padding if given). Default: `nothing`
"""
function gplot(g::AbstractGraph{T},
locs_x_in::AbstractVector{R1}, locs_y_in::AbstractVector{R2};
title = "",
title_color = colorant"black",
title_size = 4.0,
font_family = "Helvetica",
nodelabel = nothing,
nodelabelc = colorant"black",
nodelabelsize = 1.0,
NODELABELSIZE = 4.0,
nodelabeldist = 0.0,
nodelabelangleoffset = π / 4.0,
edgelabel = [],
edgelabelc = colorant"black",
edgelabelsize = 1.0,
EDGELABELSIZE = 4.0,
edgestrokec = colorant"lightgray",
edgelinewidth = 1.0,
EDGELINEWIDTH = 3.0 / sqrt(nv(g)),
edgelabeldistx = 0.0,
edgelabeldisty = 0.0,
nodesize = 1.0,
NODESIZE = 0.25 / sqrt(nv(g)),
nodefillc = colorant"turquoise",
nodestrokec = nothing,
nodestrokelw = 0.0,
arrowlengthfrac = is_directed(g) ? 0.1 : 0.0,
arrowangleoffset = π / 9,
linetype = "straight",
outangle = π / 5,
background_color = nothing,
plot_size = (10cm, 10cm),
leftpad = 0mm,
rightpad = 0mm,
toppad = 0mm,
bottompad = 0mm,
pad = nothing
) where {T <:Integer, R1 <: Real, R2 <: Real}
length(locs_x_in) != length(locs_y_in) && error("Vectors must be same length")
N = nv(g)
NE = ne(g)
if !isnothing(nodelabel) && length(nodelabel) != N
error("Must have one label per node (or none)")
end
if !isempty(edgelabel) && length(edgelabel) != NE
error("Must have one label per edge (or none)")
end
locs_x = convert(Vector{Float64}, locs_x_in)
locs_y = convert(Vector{Float64}, locs_y_in)
# Scale to unit square
min_x, max_x = extrema(locs_x)
min_y, max_y = extrema(locs_y)
function scaler(z, a, b)
if (a - b) == 0.0
return 0.5
else
return 2.0 * ((z - a) / (b - a)) - 1.0
end
end
map!(z -> scaler(z, min_x, max_x), locs_x, locs_x)
map!(z -> scaler(z, min_y, max_y), locs_y, locs_y)
# Determine sizes
#NODESIZE = 0.25/sqrt(N)
#LINEWIDTH = 3.0/sqrt(N)
max_nodesize = NODESIZE / maximum(nodesize)
nodesize *= max_nodesize
max_edgelinewidth = EDGELINEWIDTH / maximum(edgelinewidth)
edgelinewidth *= max_edgelinewidth
max_edgelabelsize = EDGELABELSIZE / maximum(edgelabelsize)
edgelabelsize *= max_edgelabelsize
max_nodelabelsize = NODELABELSIZE / maximum(nodelabelsize)
nodelabelsize *= max_nodelabelsize
max_nodestrokelw = maximum(nodestrokelw)
if max_nodestrokelw > 0.0
max_nodestrokelw = EDGELINEWIDTH / max_nodestrokelw
nodestrokelw *= max_nodestrokelw
end
# Create nodes
nodecircle = fill(0.4*2.4, length(locs_x)) #40% of the width of the unit box
if isa(nodesize, Real)
for i = 1:length(locs_x)
nodecircle[i] *= nodesize
end
else
for i = 1:length(locs_x)
nodecircle[i] *= nodesize[i]
end
end
nodes = circle(locs_x, locs_y, nodecircle)
# Create node labels if provided
texts = nothing
if !isnothing(nodelabel)
text_locs_x = deepcopy(locs_x)
text_locs_y = deepcopy(locs_y)
texts = text(text_locs_x .+ nodesize .* (nodelabeldist * cos(nodelabelangleoffset)),
text_locs_y .- nodesize .* (nodelabeldist * sin(nodelabelangleoffset)),
map(string, nodelabel), [hcenter], [vcenter])
end
# Create lines and arrow heads
lines, larrows = nothing, nothing
curves, carrows = nothing, nothing
if linetype == "curve"
curves, carrows = build_curved_edges(edges(g), locs_x, locs_y, nodesize, arrowlengthfrac, arrowangleoffset, outangle)
elseif has_self_loops(g)
lines, larrows, curves, carrows = build_straight_curved_edges(g, locs_x, locs_y, nodesize, arrowlengthfrac, arrowangleoffset, outangle)
else
lines, larrows = build_straight_edges(edges(g), locs_x, locs_y, nodesize, arrowlengthfrac, arrowangleoffset)
end
# Create edge labels if provided
edgetexts = nothing
if !isempty(edgelabel)
edge_locs_x = zeros(R1, NE)
edge_locs_y = zeros(R2, NE)
self_loop_idx = 1
for (e_idx, e) in enumerate(edges(g))
i, j = src(e), dst(e)
if linetype == "curve"
mid_x, mid_y = interpolate_bezier(curves.primitives[e_idx], 0.5)
elseif src(e) == dst(e)
mid_x, mid_y = interpolate_bezier(curves.primitives[self_loop_idx], 0.5)
self_loop_idx += 1
else
mid_x, mid_y = interpolate_line(locs_x,locs_y,i,j,0.5)
end
edge_locs_x[e_idx] = mid_x + edgelabeldistx * NODESIZE
edge_locs_y[e_idx] = mid_y + edgelabeldisty * NODESIZE
end
edgetexts = text(edge_locs_x, edge_locs_y, map(string, edgelabel), [hcenter], [vcenter])
end
# Set plot_size
if length(plot_size) != 2 || !isa(plot_size[1], Compose.AbsoluteLength) || !isa(plot_size[2], Compose.AbsoluteLength)
error("`plot_size` must be a Tuple of lengths")
end
Compose.set_default_graphic_size(plot_size...)
# Plot title
title_offset = isempty(title) ? 0 : 0.1*title_size/4 #Fix title offset
title = text(0, -1.2 - title_offset/2, title, hcenter, vcenter)
# Plot padding
if !isnothing(pad)
leftpad, rightpad, toppad, bottompad = pad, pad, pad, pad
end
# Plot area size
plot_area = (-1.2, -1.2 - title_offset, +2.4, +2.4 + title_offset)
# Build figure
compose(
context(units=UnitBox(plot_area...; leftpad, rightpad, toppad, bottompad)),
compose(context(), title, fill(title_color), fontsize(title_size), font(font_family)),
compose(context(), texts, fill(nodelabelc), fontsize(nodelabelsize), font(font_family)),
compose(context(), nodes, fill(nodefillc), stroke(nodestrokec), linewidth(nodestrokelw)),
compose(context(), edgetexts, fill(edgelabelc), fontsize(edgelabelsize)),
compose(context(), larrows, fill(edgestrokec)),
compose(context(), carrows, fill(edgestrokec)),
compose(context(), lines, stroke(edgestrokec), linewidth(edgelinewidth)),
compose(context(), curves, stroke(edgestrokec), linewidth(edgelinewidth)),
compose(context(units=UnitBox(plot_area...)), rectangle(plot_area...), fill(background_color))
)
end
function gplot(g; layout::Function=spring_layout, keyargs...)
gplot(g, layout(g)...; keyargs...)
end
# take from [Gadfly.jl](https://github.com/dcjones/Gadfly.jl)
function open_file(filename)
if Sys.isapple() #apple
run(`open $(filename)`)
elseif Sys.islinux() || Sys.isbsd() #linux
run(`xdg-open $(filename)`)
elseif Sys.iswindows() #windows
run(`$(ENV["COMSPEC"]) /c start $(filename)`)
else
@warn("Showing plots is not supported on OS $(string(Sys.KERNEL))")
end
end
# taken from [Gadfly.jl](https://github.com/dcjones/Gadfly.jl)
function gplothtml(args...; keyargs...)
filename = string(tempname(), ".html")
output = open(filename, "w")
plot_output = IOBuffer()
draw(SVGJS(plot_output, Compose.default_graphic_width,
Compose.default_graphic_width, false), gplot(args...; keyargs...))
plotsvg = String(take!(plot_output))
write(output,
"""
<!DOCTYPE html>
<html>
<head>
<title>GraphPlot Plot</title>
<meta charset="utf-8">
</head>
<body>
<script charset="utf-8">
$(read(Compose.snapsvgjs, String))
</script>
<script charset="utf-8">
$(read(gadflyjs, String))
</script>
$(plotsvg)
</body>
</html>
""")
close(output)
open_file(filename)
end
function saveplot(gplot::Compose.Context, filename::String)
draw(SVG(filename), gplot)
return nothing
end | GraphPlot | https://github.com/JuliaGraphs/GraphPlot.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.6.0 | f76a7a0f10af6ce7f227b7a921bfe351f628ed45 | code | 328 | # draw a regular n-gon
function ngon(x, y, r, n=3, θ=0.0)
αs = linspace(0,2pi,n+1)[1:end-1]
[(r*cos(α-θ)+x, r*sin(α-θ)+y) for α in αs]
end
function ngon(xs::Vector, ys::Vector, rs::Vector, ns::Vector=fill(3,length(xs)), θs::Vector=zeros(length(xs)))
[ngon(xs[i], ys[i], rs[i], ns[i], θs[i]) for i=1:length(xs)]
end
| GraphPlot | https://github.com/JuliaGraphs/GraphPlot.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.6.0 | f76a7a0f10af6ce7f227b7a921bfe351f628ed45 | code | 5519 | using LinearAlgebra
# This layout algorithm is copy from [IainNZ](https://github.com/IainNZ)'s [GraphLayout.jl](https://github.com/IainNZ/GraphLayout.jl)
@doc """
Compute graph layout using stress majorization
Inputs:
δ: Matrix of pairwise distances
p: Dimension of embedding (default: 2)
w: Matrix of weights. If not specified, defaults to
w[i,j] = δ[i,j]^-2 if δ[i,j] is nonzero, or 0 otherwise
X0: Initial guess for the layout. Coordinates are given in rows.
If not specified, default to random matrix of Gaussians
Additional optional keyword arguments control the convergence of the algorithm
and the additional output as requested:
maxiter: Maximum number of iterations. Default: 400size(X0, 1)^2
abstols: Absolute tolerance for convergence of stress.
The iterations terminate if the difference between two
successive stresses is less than abstol.
Default: √(eps(eltype(X0))
reltols: Relative tolerance for convergence of stress.
The iterations terminate if the difference between two
successive stresses relative to the current stress is less than
reltol. Default: √(eps(eltype(X0))
abstolx: Absolute tolerance for convergence of layout.
The iterations terminate if the Frobenius norm of two successive
layouts is less than abstolx. Default: √(eps(eltype(X0))
verbose: If true, prints convergence information at each iteration.
Default: false
returnall: If true, returns all iterates and their associated stresses.
If false (default), returns the last iterate
Output:
The final layout X, with coordinates given in rows, unless returnall=true.
Reference:
The main equation to solve is (8) of:
@incollection{
author = {Emden R Gansner and Yehuda Koren and Stephen North},
title = {Graph Drawing by Stress Majorization}
year={2005},
isbn={978-3-540-24528-5},
booktitle={Graph Drawing},
seriesvolume={3383},
series={Lecture Notes in Computer Science},
editor={Pach, J\'anos},
doi={10.1007/978-3-540-31843-9_25},
publisher={Springer Berlin Heidelberg},
pages={239--250},
}
"""
function stressmajorize_layout(g::AbstractGraph,
p::Int=2,
w=nothing,
X0=randn(nv(g), p);
maxiter = 400size(X0, 1)^2,
abstols=√(eps(eltype(X0))),
reltols=√(eps(eltype(X0))),
abstolx=√(eps(eltype(X0))),
verbose = false,
returnall = false)
@assert size(X0, 2)==p
δ = fill(1.0, nv(g), nv(g))
if w == nothing
w = δ.^-2
w[.!isfinite.(w)] .= 0
end
@assert size(X0, 1)==size(δ, 1)==size(δ, 2)==size(w, 1)==size(w, 2)
Lw = weightedlaplacian(w)
pinvLw = pinv(Lw)
newstress = stress(X0, δ, w)
Xs = Matrix[X0]
stresses = [newstress]
iter = 0
for outer iter = 1:maxiter
#TODO the faster way is to drop the first row and col from the iteration
X = pinvLw * (LZ(X0, δ, w)*X0)
@assert all(isfinite.(X))
newstress, oldstress = stress(X, δ, w), newstress
verbose && @info("""Iteration $iter
Change in coordinates: $(norm(X - X0))
Stress: $newstress (change: $(newstress-oldstress))
""")
push!(Xs, X)
push!(stresses, newstress)
abs(newstress - oldstress) < reltols * newstress && break
abs(newstress - oldstress) < abstols && break
norm(X - X0) < abstolx && break
X0 = X
end
iter == maxiter && @warn("Maximum number of iterations reached without convergence")
#returnall ? (Xs, stresses) : Xs[end]
Xs[end][:,1], Xs[end][:,2]
end
@doc """
Stress function to majorize
Input:
X: A particular layout (coordinates in rows)
d: Matrix of pairwise distances
w: Weights for each pairwise distance
See (1) of Reference
"""
function stress(X, d=fill(1.0, size(X, 1), size(X, 1)), w=nothing)
s = 0.0
n = size(X, 1)
if w==nothing
w = d.^-2
w[!isfinite.(w)] = 0
end
@assert n==size(d, 1)==size(d, 2)==size(w, 1)==size(w, 2)
for j=1:n, i=1:j-1
s += w[i, j] * (norm(X[i,:] - X[j,:]) - d[i,j])^2
end
@assert isfinite(s)
return s
end
@doc """
Compute weighted Laplacian given ideal weights w
Lʷ defined in (4) of the Reference
"""
function weightedlaplacian(w)
n = LinearAlgebra.checksquare(w)
T = eltype(w)
Lw = zeros(T, n, n)
for i=1:n
D = zero(T)
for j=1:n
i==j && continue
Lw[i, j] = -w[i, j]
D += w[i, j]
end
Lw[i, i] = D
end
return Lw
end
@doc """
Computes L^Z defined in (5) of the Reference
Input: Z: current layout (coordinates)
d: Ideal distances (default: all 1)
w: weights (default: d.^-2)
"""
function LZ(Z, d, w)
n = size(Z, 1)
L = zeros(n, n)
for i=1:n
D = 0.0
for j=1:n
i==j && continue
nrmz = norm(Z[i,:] - Z[j,:])
nrmz==0 && continue
δ = w[i, j] * d[i, j]
L[i, j] = -δ/nrmz
D -= -δ/nrmz
end
L[i, i] = D
end
@assert all(isfinite.(L))
L
end
| GraphPlot | https://github.com/JuliaGraphs/GraphPlot.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.6.0 | f76a7a0f10af6ce7f227b7a921bfe351f628ed45 | code | 5797 | @info "Importing test packages..."
# This should fix an error, see : https://github.com/JuliaIO/ImageMagick.jl/issues/133
(Sys.islinux() || Sys.iswindows()) && import ImageMagick
using GraphPlot
using GraphPlot.Graphs
using Cairo
using GraphPlot.Colors
using GraphPlot.Compose
using Random
using Test
using VisualRegressionTests
using ImageMagick
# global variables
istravis = "TRAVIS" ∈ keys(ENV)
datadir = joinpath(@__DIR__, "data")
@info "Starting tests..."
# TODO smallgraph(:karate) has already been added to Graphs
# but as there hasn't been any new version tagged, we relay on this instead
karate_edges = Edge.([
1 => 2, 1 => 3, 1 => 4, 1 => 5, 1 => 6, 1 => 7,
1 => 8, 1 => 9, 1 => 11, 1 => 12, 1 => 13, 1 => 14,
1 => 18, 1 => 20, 1 => 22, 1 => 32, 2 => 3, 2 => 4,
2 => 8, 2 => 14, 2 => 18, 2 => 20, 2 => 22, 2 => 31,
3 => 4, 3 => 8, 3 => 9, 3 => 10, 3 => 14, 3 => 28,
3 => 29, 3 => 33, 4 => 8, 4 => 13 , 4 => 14, 5 => 7,
5 => 11, 6 => 7, 6 => 11, 6 => 17 , 7 => 17, 9 => 31,
9 => 33, 9 => 34, 10 => 34, 14 => 34, 15 => 33, 15 => 34,
16 => 33, 16 => 34, 19 => 33, 19 => 34, 20 => 34, 21 => 33,
21 => 34, 23 => 33, 23 => 34, 24 => 26, 24 => 28, 24 => 30,
24 => 33, 24 => 34, 25 => 26, 25 => 28, 25 => 32, 26 => 32,
27 => 30, 27 => 34, 28 => 34, 29 => 32, 29 => 34, 30 => 33,
30 => 34, 31 => 33, 31 => 34, 32 => 33, 32 => 34, 33 => 34,
])
# graphs to test
#g = smallgraph(:karate)
g = SimpleGraph(karate_edges)
h = Graphs.wheel_graph(10)
test_layout(g::AbstractGraph; kws...) = spring_layout(g, 2017, kws...)
# plot and save function for visual regression tests
function plot_and_save(fname, g; gplot_kwargs...)
draw(PNG(fname, 8inch, 8inch), gplot(g; layout=test_layout, gplot_kwargs...))
end
function save_comparison(result::VisualTestResult)
grid = hcat(result.refImage, result.testImage)
path = joinpath(datadir, string(basename(result.refFilename)[1:end-length(".png")], "-comparison.png"))
ImageMagick.save(path, grid)
return result
end
@testset "Karate Net" begin
# auxiliary variables
nodelabel = collect(1:nv(g))
nodesize = outdegree(g) .* 1.0
# test nodesize
plot_and_save1(fname) = plot_and_save(fname, g, nodesize=nodesize.^0.3, nodelabel=nodelabel, nodelabelsize=nodesize.^0.3)
refimg1 = joinpath(datadir, "karate_different_nodesize.png")
@test test_images(VisualTest(plot_and_save1, refimg1), popup=!istravis) |> save_comparison |> success
# test directed graph
plot_and_save2(fname) = plot_and_save(fname, g, arrowlengthfrac=0.05, nodelabel=nodelabel, font_family="Sans")
refimg2 = joinpath(datadir, "karate_straight_directed.png")
@test test_images(VisualTest(plot_and_save2, refimg2), popup=!istravis) |> save_comparison |> success
# test node membership
membership = [1,1,1,1,1,1,1,1,2,1,1,1,1,1,2,2,1,1,2,1,2,1,2,2,2,2,2,2,2,2,2,2,2,2]
nodecolor = [colorant"lightseagreen", colorant"orange"]
nodefillc = nodecolor[membership]
plot_and_save3(fname) = plot_and_save(fname, g, nodelabel=nodelabel, nodefillc=nodefillc)
refimg3 = joinpath(datadir, "karate_groups.png")
@test test_images(VisualTest(plot_and_save3, refimg3), popup=!istravis) |> save_comparison |> success
# test background color
plot_and_save4(fname) = plot_and_save(fname, g, background_color=colorant"lightyellow")
refimg4 = joinpath(datadir, "karate_background_color.png")
@test test_images(VisualTest(plot_and_save4, refimg4), popup=!istravis) |> save_comparison |> success
end
@testset "WheelGraph" begin
# default options
plot_and_save1(fname) = plot_and_save(fname, h)
refimg1 = joinpath(datadir, "wheel10.png")
@test test_images(VisualTest(plot_and_save1, refimg1), popup=!istravis) |> save_comparison |> success
end
@testset "Curves" begin
g2 = DiGraph(2)
add_edge!(g2, 1,2)
add_edge!(g2, 2,1)
plot_and_save1(fname) = plot_and_save(fname, g2, linetype="curve", arrowlengthfrac=0.2, pad=5mm)
refimg1 = joinpath(datadir, "curve.png")
@test test_images(VisualTest(plot_and_save1, refimg1), popup=!istravis) |> save_comparison |> success
g3 = DiGraph(2)
add_edge!(g3, 1,1)
add_edge!(g3, 1,2)
add_edge!(g3, 2,1)
plot_and_save2(fname) = plot_and_save(fname, g3, linetype="curve", arrowlengthfrac=0.2, leftpad=20mm, toppad=3mm, bottompad=3mm)
refimg2 = joinpath(datadir, "self_directed.png")
@test test_images(VisualTest(plot_and_save2, refimg2), popup=!istravis) |> save_comparison |> success
end
@testset "Spring Layout" begin
g1 = path_digraph(3)
x1, y1 = spring_layout(g1, 0; C = 1)
@test all(isapprox.(x1, [1.0, -0.014799825222963192, -1.0]))
@test all(isapprox.(y1, [-1.0, 0.014799825222963303, 1.0]))
end
@testset "Circular Layout" begin
#single node
g1 = SimpleGraph(1)
x1,y1 = circular_layout(g1)
@test iszero(x1)
@test iszero(y1)
#2 nodes
g2 = SimpleGraph(2)
x2,y2 = circular_layout(g2)
@test all(isapprox.(x2, [1.0, -1.0]))
@test all(isapprox.(y2, [0.0, 1.2246467991473532e-16]))
end
@testset "Shell Layout" begin
#continuous nlist
g = SimpleGraph(6)
x1,y1 = shell_layout(g,[[1,2,3],[4,5,6]])
@test all(isapprox.(x1, [1.0, -0.4999999999999998, -0.5000000000000004, 2.0, -0.9999999999999996, -1.0000000000000009]))
@test all(isapprox.(y1, [0.0, 0.8660254037844387, -0.8660254037844385, 0.0, 1.7320508075688774, -1.732050807568877]))
#skipping positions
x2,y2 = shell_layout(g,[[1,3,5],[2,4,6]])
@test all(isapprox.(x2, [1.0, 2.0, -0.4999999999999998, -0.9999999999999996, -0.5000000000000004, -1.0000000000000009]))
@test all(isapprox.(y2, [0.0, 0.0, 0.8660254037844387, 1.7320508075688774, -0.8660254037844385, -1.732050807568877]))
end | GraphPlot | https://github.com/JuliaGraphs/GraphPlot.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.6.0 | f76a7a0f10af6ce7f227b7a921bfe351f628ed45 | docs | 7373 | # GraphPlot

[](https://juliahub.com/ui/Packages/GraphPlot/bUwXr)
Graph layout and visualization algorithms based on [Compose.jl](https://github.com/dcjones/Compose.jl) and inspired by [GraphLayout.jl](https://github.com/IainNZ/GraphLayout.jl).
The `spring_layout` and `stressmajorize_layout` function are copy from [IainNZ](https://github.com/IainNZ)'s [GraphLayout.jl](https://github.com/IainNZ/GraphLayout.jl).
Other layout algorithms are wrapped from [NetworkX](https://github.com/networkx/networkx).
`gadfly.js` is copied from [Gadfly.jl](https://github.com/dcjones/Gadfly.jl)
# Getting Started
From the Julia REPL the latest version can be installed with
```julia
Pkg.add("GraphPlot")
```
GraphPlot is then loaded with
```julia
using GraphPlot
```
# Usage
## karate network
```julia
using Graphs: smallgraph
g = smallgraph(:karate)
gplot(g)
```
## Add node label
```julia
using Graphs
nodelabel = 1:nv(g)
gplot(g, nodelabel=nodelabel)
```
## Adjust node labels
```julia
gplot(g, nodelabel=nodelabel, nodelabeldist=1.5, nodelabelangleoffset=π/4)
```
## Control the node size
```julia
# nodes size proportional to their degree
nodesize = [Graphs.outdegree(g, v) for v in Graphs.vertices(g)]
gplot(g, nodesize=nodesize)
```
## Control the node color
Feed the keyword argument `nodefillc` a color array, ensure each node has a color. `length(nodefillc)` must be equal `|V|`.
```julia
using Colors
# Generate n maximally distinguishable colors in LCHab space.
nodefillc = distinguishable_colors(nv(g), colorant"blue")
gplot(g, nodefillc=nodefillc, nodelabel=nodelabel, nodelabeldist=1.8, nodelabelangleoffset=π/4)
```
## Transparent
```julia
# stick out large degree nodes
alphas = nodesize/maximum(nodesize)
nodefillc = [RGBA(0.0,0.8,0.8,i) for i in alphas]
gplot(g, nodefillc=nodefillc)
```
## Control the node label size
```julia
nodelabelsize = nodesize
gplot(g, nodelabelsize=nodelabelsize, nodesize=nodesize, nodelabel=nodelabel)
```
## Draw edge labels
```julia
edgelabel = 1:Graphs.ne(g)
gplot(g, edgelabel=edgelabel, nodelabel=nodelabel)
```
## Adjust edge labels
```julia
edgelabel = 1:Graphs.ne(g)
gplot(g, edgelabel=edgelabel, nodelabel=nodelabel, edgelabeldistx=0.5, edgelabeldisty=0.5)
```
## Color the graph
```julia
# nodes membership
membership = [1,1,1,1,1,1,1,1,2,1,1,1,1,1,2,2,1,1,2,1,2,1,2,2,2,2,2,2,2,2,2,2,2,2]
nodecolor = [colorant"lightseagreen", colorant"orange"]
# membership color
nodefillc = nodecolor[membership]
gplot(g, nodefillc=nodefillc)
```
## Different layout
### spring layout (default)
This is the defaut layout and will be chosen if no layout is specified. The [default parameters to the spring layout algorithm](https://github.com/JuliaGraphs/GraphPlot.jl/blob/master/src/layout.jl#L78) can be changed by supplying an anonymous function, e.g., if nodes appear clustered too tightly together, try
```julia
layout=(args...)->spring_layout(args...; C=20)
gplot(g, layout=layout, nodelabel=nodelabel)
```
where `C` influences the desired distance between nodes.
### random layout
```julia
gplot(g, layout=random_layout, nodelabel=nodelabel)
```
### circular layout
```julia
gplot(g, layout=circular_layout, nodelabel=nodelabel)
```
### spectral layout
```julia
gplot(g, layout=spectral_layout)
```
### shell layout
```julia
nlist = Vector{Vector{Int}}(undef, 2) # two shells
nlist[1] = 1:5 # first shell
nlist[2] = 6:nv(g) # second shell
locs_x, locs_y = shell_layout(g, nlist)
gplot(g, locs_x, locs_y, nodelabel=nodelabel)
```
## Curve edge
```julia
gplot(g, linetype="curve")
```
## Show plot
When using an IDE such as VSCode, `Cairo.jl` is required to visualize the plot inside the IDE.
When using the REPL, `gplothtml` will allow displaying the plot on a browser.
## Save to figure
```julia
using Compose
# save to pdf
draw(PDF("karate.pdf", 16cm, 16cm), gplot(g))
# save to png
draw(PNG("karate.png", 16cm, 16cm), gplot(g))
# save to svg
draw(SVG("karate.svg", 16cm, 16cm), gplot(g))
# alternate way of saving to svg without loading Compose
saveplot(gplot(g, plot_size = (16cm, 16cm)), "karate.svg")
```
# Graphs.jl integration
```julia
using Graphs
h = watts_strogatz(50, 6, 0.3)
gplot(h)
```
# Arguments
+ `G` Graph to draw
+ `locs_x, locs_y` Locations of the nodes (will be normalized and centered). If not specified, will be obtained from `layout` kwarg.
# Keyword Arguments
+ `layout` Layout algorithm: `random_layout`, `circular_layout`, `spring_layout`, `shell_layout`, `stressmajorize_layout`, `spectral_layout`. Default: `spring_layout`
+ `title` Plot title. Default: `""`
+ `title_color` Plot title color. Default: `colorant"black"`
+ `title_size` Plot title size. Default: `4.0`
+ `font_family` Font family for all text. Default: `"Helvetica"`
+ `NODESIZE` Max size for the nodes. Default: `3.0/sqrt(N)`
+ `nodesize` Relative size for the nodes, can be a Vector. Default: `1.0`
+ `nodelabel` Labels for the vertices, a Vector or nothing. Default: `nothing`
+ `nodelabelc` Color for the node labels, can be a Vector. Default: `colorant"black"`
+ `nodelabeldist` Distances for the node labels from center of nodes. Default: `0.0`
+ `nodelabelangleoffset` Angle offset for the node labels. Default: `π/4.0`
+ `NODELABELSIZE` Largest fontsize for the vertice labels. Default: `4.0`
+ `nodelabelsize` Relative fontsize for the vertice labels, can be a Vector. Default: `1.0`
+ `nodefillc` Color to fill the nodes with, can be a Vector. Default: `colorant"turquoise"`
+ `nodestrokec` Color for the nodes stroke, can be a Vector. Default: `nothing`
+ `nodestrokelw` Line width for the nodes stroke, can be a Vector. Default: `0.0`
+ `edgelabel` Labels for the edges, a Vector or nothing. Default: `[]`
+ `edgelabelc` Color for the edge labels, can be a Vector. Default: `colorant"black"`
+ `edgelabeldistx, edgelabeldisty` Distance for the edge label from center of edge. Default: `0.0`
+ `EDGELABELSIZE` Largest fontsize for the edge labels. Default: `4.0`
+ `edgelabelsize` Relative fontsize for the edge labels, can be a Vector. Default: `1.0`
+ `EDGELINEWIDTH` Max line width for the edges. Default: `0.25/sqrt(N)`
+ `edgelinewidth` Relative line width for the edges, can be a Vector. Default: `1.0`
+ `edgestrokec` Color for the edge strokes, can be a Vector. Default: `colorant"lightgray"`
+ `arrowlengthfrac` Fraction of line length to use for arrows. Equal to 0 for undirected graphs. Default: `0.1` for the directed graphs
+ `arrowangleoffset` Angular width in radians for the arrows. Default: `π/9 (20 degrees)`
+ `linetype` Type of line used for edges ("straight", "curve"). Default: "straight"
+ `outangle` Angular width in radians for the edges (only used if `linetype = "curve`). Default: `π/5 (36 degrees)`
+ `background_color` Color for the plot background. Default: `nothing`
+ `plot_size` Tuple of measures for width x height of plot area. Default: `(10cm, 10cm)`
+ `leftpad, rightpad, toppad, bottompad` Padding for the plot margins. Default: `0mm`
+ `pad` Padding for plot margins (overrides individual padding if given). Default: `nothing`
# Reporting Bugs
Filing an issue to report a bug, counterintuitive behavior, or even to request a feature is extremely valuable in helping me prioritize what to work on, so don't hestitate.
| GraphPlot | https://github.com/JuliaGraphs/GraphPlot.jl.git |
|
[
"MIT"
] | 0.1.4 | 9bb6a6efd74e0f315a6e5bd73c15b58ac5a6de2c | code | 802 | push!(LOAD_PATH,"../src")
using Documenter: Documenter, makedocs, deploydocs, doctest, DocMeta
using Tries
using Test
DocMeta.setdocmeta!(Tries, :DocTestSetup, quote
using Tries
end; recursive=true)
## doctest(Tries; fix=true)
makedocs(;
modules=[Tries],
authors="Gregor Kappler",
repo="https://github.com/gkappler/Tries.jl/blob/{commit}{path}#L{line}",
sitename="Tries.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://gkappler.github.io/Tries.jl",
assets=String[],
),
pages=[
"Home" => "index.md",
"Library" => Any[
"Public" => "lib/public.md",
],
# "Developer Guide" => "developer.md"
],
)
deploydocs(;
repo="github.com/gkappler/Tries.jl",
)
| Tries | https://github.com/gkappler/Tries.jl.git |
|
[
"MIT"
] | 0.1.4 | 9bb6a6efd74e0f315a6e5bd73c15b58ac5a6de2c | code | 12067 | """
Implemented of a Trie data structure.
This is an associative data structure with keys of type `NTuple{N,K} where N` and values of type `V`.
"""
module Tries
import Base: get!, show, get, isempty, haskey, setindex!, getindex, pairs, keys, values, keytype, eltype, valtype
import AbstractTrees
import AbstractTrees: children, printnode, PreOrderDFS, print_tree
##using VectorDicts
export AbstractTrie, Trie, SubTrie, nodes, subtrie
abstract type AbstractTrie{K,T} end
"""
Base.length(x::Tries.AbstractTrie)
Cumulative count of all nodes.
"""
Base.length(x::AbstractTrie) =
1+_length(x)
_length(x::AbstractTrie) =
isempty(nodes(x)) ? 0 : (0+length(nodes(x)) + (sum)(_length.(values(nodes(x)))))::Int
"""
Base.iterate(x::Tries.AbstractTrie, a...)
`iterate(pairs(x), a...)`.
"""
Base.iterate(x::AbstractTrie, a...) =
iterate(pairs(x), a...)
struct Trie{K,T} <: AbstractTrie{K,T}
value::Union{Missing,T}
nodes::Dict{K,Trie{K,T}}
end
"""
nodes(x::AbstractTrie{K,T})
Getter for node dictionary.
"""
nodes(x::Trie) = x.nodes
"""
A Trie with a path.
"""
struct SubTrie{K,T} <: AbstractTrie{K,T}
path::NTuple{N,K} where N
value::Trie{K,T}
SubTrie(path::NTuple{N,K} where N, t::Trie{K,V}) where {K,V} =
new{K,V}(path, t)
SubTrie(path::NTuple{N,K} where N, st::SubTrie{K,V}) where {K,V} =
new{K,V}((path..., st.path...), st.value)
end
nodes(x::SubTrie) = x.value.nodes
subtrie(x::SubTrie, a...) =
SubTrie(x.path,subtrie(x.value,a...))
subtrie!(x::SubTrie, a...) =
SubTrie(x.path,subtrie!(x.value,a...))
subtrie!(f::Function, x::SubTrie, a...) =
SubTrie(x.path,subtrie!(f,x.value,a...))
"""
Trie{K,T}()
Construct an empty `Trie{K,T}` with root value `missing`.
"""
Trie{K,T}() where {K,T} = Trie{K,T}(missing, Dict{K,Trie{K,T}}())
"""
Trie{K,T}(value)
Construct an empty `Trie{K,T}` with root value is `value`.
"""
Trie{K,T}(value) where {K,T} = Trie{K,T}(value, Dict{K,Trie{K,T}}())
"""
Trie(values::Vararg{Pair{NTuple{N,K},T} where N}) where {K,T}
Trie(values::Vararg{Pair{Vector{K},T}}) where {K,T}
Trie(values::Vararg{Pair{NTuple{N,K},<:Any} where N}) where {K}
Trie(values::Base.Generator)
Construct a `Trie{K,T}` and populate it with `r[k...]=v`.
```jldoctest
julia> Trie((:a,)=>"a", (:a,:b)=>"c", (:a,:c,:d)=>"z", (:a,:b,:d)=>1)
Trie{Symbol,Any}
└─ :a => "a"
├─ :b => "c"
│ └─ :d => 1
└─ :c
└─ :d => "z"
julia> Trie((:a,)=>"a", (:a,:b)=>"c", (:a,:c,:d)=>"z", (:a,:b,:d)=>"y")
Trie{Symbol,String}
└─ :a => "a"
├─ :b => "c"
│ └─ :d => "y"
└─ :c
└─ :d => "z"
```
See also [`setindex!`](@ref).
"""
function Trie(values::Vararg{Pair{NTuple{N,K},T} where N}) where {K,T}
r = Trie{K,T}(missing, Dict{K,Trie{K,T}}())
for (k,v) in values
r[k...]=v
end
r
end
function Trie(values::Vararg{Pair{Vector{K},T}}) where {K,T}
r = Trie{K,T}(missing, Dict{K,Trie{K,T}}())
for (k,v) in values
r[k...]=v
end
r
end
function Trie(values::Vararg{Pair{NTuple{N,K},<:Any} where N}) where {K}
r = Trie{K,Any}(missing, Dict{K,Trie{K,Any}}())
for (k,v) in values
r[k...]=v
end
r
end
Trie(values::Base.Generator) = Trie(values...)
# struct ETrie{K,T,D<:AbstractDict}
# value::Union{Missing,T}
# nodes::D{K,ETrie{K,T,D}}
# end
# ETrie{K,T}() where {K,T} =
# ETrie{K,T,}(missing, @show VectorDict{K,ETrie{K,T,VectorDict}}())
"""
Base.get(x::Trie)
Base.get(x::SubTrie)
Return `value::Union{Missing,valtype(x)}` of `x`.
"""
function Base.get(x::Trie)
x.value
end
Base.get(x::SubTrie) = get(x.value)
"""
Base.show(x::Trie)
Base.show(x::SubTrie)
Display `x` with `AbstractTrees.print_tree`.
"""
function Base.show(io::IO, x::Trie)
print(io,"Trie{$(keytype(x)),$(valtype(x))}") ## error("should print key")
print_tree(io,x)
end
function Base.show(io::IO, x::SubTrie)
print(io,"SubTrie{$(keytype(x)),$(valtype(x))} @ ") ## error("should print key")
if length(x.path)>1
for p in x.path[1:end-1]
show(io,p)
print(io,", ")
end
end
print_tree(io,x)
end
AbstractTrees.children(x::Trie{K,V}) where {K,V} =
[ SubTrie(tuple(k), v) for (k,v) in pairs(x.nodes) ]
function AbstractTrees.printnode(io::IO, x::Trie)
if get(x) !== missing
print(io, " => ")
show(io, get(x))
end
end
AbstractTrees.children(x::SubTrie{K,V}) where {K,V} =
[ SubTrie(tuple(x.path..., k), v)
for (k,v) in pairs(x.value.nodes) ]
function AbstractTrees.printnode(io::IO, x::SubTrie)
!isempty(x.path) && show(io,x.path[end])
if get(x) !== missing
print(io, " => ")
show(io, get(x))
end
end
"""
Base.keytype(::Type{Trie{K,V}}) where {K,V}
Base.keytype(::Trie{K,V}) where {K,V}
Returns `K`.
!!! warning
please review: should this return `NTuple{N,K} where N`?
"""
Base.keytype(::Type{<:AbstractTrie{K,V}}) where {K,V} = K
Base.keytype(x::AbstractTrie) = keytype(typeof(x))
"""
Base.eltype(::Type{<:AbstractTrie{K,V}}) where {K,V}
Base.etype(::AbstractTrie{K,V}) where {K,V}
Returns `Pair{Tuple{Vararg{K,N} where N},Union{Missing,V}}` for `iterate` and `collect`.
"""
Base.eltype(::Type{<:AbstractTrie{K,V}}) where {K,V} = Pair{Tuple{Vararg{K,N} where N},Union{Missing,V}}
Base.eltype(x::AbstractTrie) = eltype(typeof(x))
"""
Base.valtype(::Type{AbstractTrie{K,V}}) where {K,V}
Base.valtype(::AbstractTrie{K,V}) where {K,V}
Returns `V`.
"""
Base.valtype(::Type{<:AbstractTrie{K,V}}) where {K,V} = V
Base.valtype(x::AbstractTrie) = valtype(typeof(x))
"""
Base.get!(x::Trie,k)
Returns `subtrie!(x,k).value`.
See also [`subtrie!`](@ref)
"""
Base.get!(x::Trie{K,T},k) where {K,T} =
get(subtrie!(x, k...))
"""
Base.get(x::Trie,k)
Returns `subtrie(x,k).value`.
See also [`subtrie`](@ref)
"""
Base.get(x::Trie{K,T}, k) where {K,T} =
get(subtrie(x, k...))
"""
Base.get!(x::Trie,k)
Returns `subtrie!(x,k).value`.
See also [`subtrie!`](@ref)
"""
Base.get!(f::Function, x::Trie{K,T}, k) where {K,T} =
get(subtrie!(f, x, k...))
"""
Base.isempty(x::Trie)
Returns `true` iif x has no nodes.
"""
Base.isempty(x::Trie) =
isempty(x.nodes)
"""
Base.haskey(x::Trie,path)
Returns `true` iif x has nodes along `path`.
"""
Base.haskey(x::Trie,path) =
isempty(path) || ( haskey(x.nodes,path[1]) && ( length(path)==1 || haskey(x[path[1]],path[2:end]) ) )
export subtrie!
"""
subtrie!(x::Trie,path...)
Return a subtree at `path`.
Nodes missing in `x` along path are created and populated with values `missing`.
"""
subtrie!(x::Trie{K,V},path::K...) where {K,V} =
subtrie!((_,_)->missing, x,path...)
"""
subtrie!(f::Function,x::Trie,path...)
Return a subtree at `path`.
Nodes missing in `x` along path are created and populated with values `f(path, index)`.
```jldoctest
julia> a = Trie{Int,Int}(0)
Trie{Int64,Int64} => 0
julia> subtrie!((p,i)->i, a, 4,3,2,1)
SubTrie{Int64,Int64} @ 4, 3, 2, 1 => 4
julia> a
Trie{Int64,Int64} => 0
└─ 4 => 1
└─ 3 => 2
└─ 2 => 3
└─ 1 => 4
```
"""
function subtrie!(f::Function,x::Trie{K,T},path::K...) where {K,T}
isempty(path) && return SubTrie(tuple(),x)
x_::Trie{K,T} = x
for i in 1:(lastindex(path)-1)
k = path[i]
x_ = get!(() -> Trie{K,T}(f(path,i)),
nodes(x_), k)
end
##if length(path) >= 1
x_ = get!(() -> Trie{K,T}(f(path,lastindex(path))),
nodes(x_), path[end])
##end
SubTrie(path, x_)
end
"""
subtrie(x::Trie{K,T},path...)
Return a subtree at `path`.
```jldoctest
julia> a = Trie((:a,)=>"a", (:a,:b)=>"c", (:a,:c,:d)=>"z", (:a,:b,:d)=>"y")
Trie{Symbol,String}
└─ :a => "a"
├─ :b => "c"
│ └─ :d => "y"
└─ :c
└─ :d => "z"
julia> subtrie(a, :a, :b)
SubTrie{Symbol,String} @ :a, :b => "c"
└─ :d => "y"
julia> subtrie(a, :a, :d, :b)
ERROR: KeyError: key (:d, :b) not found
Stacktrace:
[1] (::Tries.var"#41#42")(::Tuple{Symbol,Symbol,Symbol}, ::Int64) at /home/gregor/dev/julia/Tries/src/Tries.jl:334
[2] subtrie(::Tries.var"#41#42", ::Trie{Symbol,String}, ::Symbol, ::Vararg{Symbol,N} where N) at /home/gregor/dev/julia/Tries/src/Tries.jl:386
[3] subtrie(::Trie{Symbol,String}, ::Symbol, ::Symbol, ::Vararg{Symbol,N} where N) at /home/gregor/dev/julia/Tries/src/Tries.jl:334
[4] top-level scope at REPL[12]:1
```
"""
function subtrie(x::AbstractTrie,path...)
subtrie((path,i)->throw(KeyError(path[i:end])),x,path...)
end
"""
subtrie(::Nothing,x::Trie{K,T},path...)
Return a subtree at `path`, or `nothing`, if `path` does not exist in `x`.
Does not modify `x`.
```jldoctest
julia> a = Trie((:a,)=>"a", (:a,:b)=>"c", (:a,:c,:d)=>"z", (:a,:b,:d)=>"y")
Trie{Symbol,String}
└─ :a => "a"
├─ :b => "c"
│ └─ :d => "y"
└─ :c
└─ :d => "z"
julia> subtrie(nothing, a, :a, :d)
```
"""
function subtrie(::Nothing,x::AbstractTrie{K,T},path::K...) where {K,T}
subtrie((p,i)->nothing,x,path...)
end
"""
subtrie(notfound::Function,x::Trie{K,T},path...)
Return a subtree at `path`, or `notfound(path,error_index)`, if `path` does not exist in `x`
(default `(path,i)->throw(KeyError(path[i:end]))`).
Does not modify `x`.
```jldoctest
julia> a = Trie((:a,)=>"a", (:a,:b)=>"c", (:a,:c,:d)=>"z", (:a,:b,:d)=>"y")
Trie{Symbol,String}
└─ :a => "a"
├─ :b => "c"
│ └─ :d => "y"
└─ :c
└─ :d => "z"
julia> subtrie((x...) -> x, a, :a, :d)
((:a, :d), 2)
```
"""
function subtrie(f::Function,x::AbstractTrie{K,T},path::K...) where {K,T}
x_ = x
for (i,k) in enumerate(path)
!(haskey(nodes(x_),k)) && return f(path,i)
# && @warn "no key $k" collect(keys(x_.nodes)) # k haskey(x_.nodes,k) x_.nodes
x_ = nodes(x_)[k]
end
SubTrie(path, x_)
end
import Base.setindex!
"""
Base.setindex!(x::Trie{K,T}, v::T, path...) where {K,T}
Set value at `path` to `v and return previous value or missing.
!!! note
To retrieve last value you need to call `setindex!` explicitly.
```jldoctest
julia> x = Trie((:a,)=>"a", (:a,:b)=>"c", (:a,:c,:d)=>"z", (:a,:b,:d)=>"y")
Trie{Symbol,String}
└─ :a => "a"
├─ :b => "c"
│ └─ :d => "y"
└─ :c
└─ :d => "z"
julia> x[:a,:b,:z]="node added"
"node added"
julia> setindex!(x,"value set",:a,:c)
Trie{Symbol,String}
└─ :d => "z"
julia> x
Trie{Symbol,String}
└─ :a => "a"
├─ :b => "c"
│ ├─ :d => "y"
│ └─ :z => "node added"
└─ :c => "value set"
└─ :d => "z"
```
See also [`subtrie!`](@ref)
"""
function Base.setindex!(x::Trie{K,T}, v::T, path::K...) where {K,T}
x_=subtrie!(x,path[1:end-1]...)
leaf=subtrie!(x_,path[end])
x_.value.nodes[path[end]] = Trie{K,T}(v,leaf.value.nodes)
leaf.value
end
"""
Base.getindex(x::Trie{K,T}, path...) where {K,T}
Get `SubTrie` at `path`.
See also [`SubTrie`](@ref).
"""
function Base.getindex(x::Trie{K,T}, path::K...) where {K,T}
subtrie(x,path...)
end
"""
Base.getindex(x::SubTrie, path...)
Get `SubTrie` at `(x.path...,path...)`.
See also [`SubTrie`](@ref).
"""
function Base.getindex(x::SubTrie{K,V}, path::K...) where {K,V}
SubTrie(tuple(x.path...,path...),subtrie(x,path...))
end
"""
Base.pairs(x::Trie{K,V}) where {K,V}
Base.pairs(x::SubTrie)
Generator returning `path => value` pairs.
See also [`AbstractTrees.PreOrderDFS`](https://juliacollections.github.io/AbstractTrees.jl/stable/api/#AbstractTrees.PreOrderDFS)
"""
Base.pairs(x::Trie) =
pairs(SubTrie(tuple(),x))
function Base.pairs(x::SubTrie{K,V}) where {K,V}
( Pair{Tuple{Vararg{K,N} where N},Union{Missing,V}}(x.path, get(x))
for x in PreOrderDFS(x) )
end
"""
Base.keys(x::AbstractTrie)
Generator returning `path`s as `first` fields from `pairs(x)`.
See also [`pairs`](@ref)
"""
Base.keys(x::AbstractTrie) =
( kv.first for kv in pairs(x) )
"""
Base.values(x::Union{Trie,SubTrie})
Generator returning `value`s as `second` fields from `pairs(x)`.
See also [`pairs`](@ref)
"""
Base.values(x::AbstractTrie) =
( kv.second for kv in pairs(x) )
end # module
| Tries | https://github.com/gkappler/Tries.jl.git |
|
[
"MIT"
] | 0.1.4 | 9bb6a6efd74e0f315a6e5bd73c15b58ac5a6de2c | code | 3317 | using Tries
using Test
@testset "Tries.jl" begin
x=Trie((:a,)=>"a", (:a,:b)=>"c", (:a,:c,:d)=>"z", (:a,:b,:d)=>1)
x=Trie((:a,)=>"a", (:a,:b)=>"c", (:a,:c,:d)=>"z", (:a,:b,:d)=>"y")
@test length(x) == 6
@test [ n for n in x if n.second!==missing ] == [ (:a,)=>"a", (:a,:b)=>"c", (:a,:b,:d)=>"y", (:a,:c,:d)=>"z" ]
@test isempty(x) == false
@test haskey(x,(:a,)) == true
@test collect(keys(nodes(x[:a]))) == [:b,:c]
@testset "eltype, keytype" begin
@test eltype(x) == Pair{Tuple{Vararg{Symbol,N} where N},Union{Missing,String}}
@test eltype(typeof(x)) == Pair{Tuple{Vararg{Symbol,N} where N},Union{Missing,String}}
@test eltype(x[:a]) == Pair{Tuple{Vararg{Symbol,N} where N},Union{Missing,String}}
@test eltype(typeof(x[:a])) == Pair{Tuple{Vararg{Symbol,N} where N},Union{Missing,String}}
@test valtype(x) == String
@test valtype(typeof(x)) == String
@test valtype(x[:a]) == String
@test valtype(typeof(x[:a])) == String
@test keytype(x) == Symbol
@test keytype(typeof(x)) == Symbol
@test keytype(x[:a]) == Symbol
@test keytype(typeof(x[:a])) == Symbol
@test_broken keytype(x) == Vararg{Symbol}
end
@testset "getting subtries and values" begin
@test x[:a] isa SubTrie
@test x[:a].path == (:a,) ## method?
@test get(x[:a])=="a"
@test get(x[:a,:b])=="c"
@test get(x[:a,:b,:d])=="y"
@test get(x[:a][:b,:d])=="y"
end
@testset "keys as vectors" begin
x=Trie([:a]=>"a", [:a,:b]=>"c", [:a,:c,:d]=>"z", [:a,:b,:d]=>"y")
@test get(x[:a][:b,:d])=="y"
end
@testset "Generator constructor" begin
x=Trie(kv for kv in ([:a]=>"a", [:a,:b]=>"c", [:a,:c,:d]=>"z", [:a,:b,:d]=>"y"))
@test_throws KeyError subtrie(x,:z,:y)
@test subtrie((p,i)->1,x,:z,:y)==1
@test subtrie(nothing,x,:z,:y)===nothing
@test get(x[:a][:b,:d])=="y"
subtrie!(x,:z,:y)
@test get(x[:z][:y])===missing
get!(x,(:z2,:y2))
@test get(x,(:z2,:y2)) === missing
@test get!(x,(:z3,:y3)) do k,i
string(k[1:i])
end == "(:z3, :y3)"
end
@testset "setting values" begin
x[:z]="added"
@test get(x[:z])=="added"
x[:z,:n]="n"
@test get(x[:z,:n])=="n"
x[:z,:n]="m"
@test get(x[:z,:n])=="m"
@testset "changing value preserves subtrie" begin
x[:z]="changed"
@test get(x[:z,:n])=="m"
end
end
show(x[:a,:b])
@testset "populating path" begin
x=Trie{Int,Int}()
leaf = subtrie!(x, 1,2,3,4,5) do x,i
x[i]+1
end
@test get(leaf)==6
@test get(x[1])==2
@test get(x[1,2])==3
leaf2 = subtrie!(x[1,2],9,10) do x,i
x[i]-1
end
@test get(x[1,2,9,10])==9
end
show(Trie{Symbol,Int}(1))
@testset "pairs, keys, values" begin
x=Trie(tuple(:a,:b) => 1, (:a,) => 2)
@test collect(values(x))[2:3] == [2,1]
@test collect(keys(x)) == [tuple(), (:a,),(:a,:b)]
## @test collect(pairs(x))[1] == ( tuple()=>missing )
@test collect(pairs(x))[2] == ( (:a,)=>2 )
@test collect(pairs(x))[3] == ( (:a,:b)=>1 )
end
end
| Tries | https://github.com/gkappler/Tries.jl.git |
|
[
"MIT"
] | 0.1.4 | 9bb6a6efd74e0f315a6e5bd73c15b58ac5a6de2c | docs | 3470 | # Tries
<!-- [](https://gkappler.github.io/Tries.jl/stable) -->
[](https://gkappler.github.io/Tries.jl/dev)
[](https://travis-ci.com/github/gkappler/Tries.jl)
[](https://codecov.io/gh/gkappler/Tries.jl)
[Trie](https://en.wikipedia.org/wiki/Trie) is a small package providing a tree-like data structure implemented on a `Dict` backend and using [AbstractTrees](https://github.com/JuliaCollections/AbstractTrees.jl) for printing and traversal.
`Trie` generalizes [DataStructures.Trie](https://juliacollections.github.io/DataStructures.jl/latest/trie/) from `AbstractString` keys to arbitrary `NTuple{N,K} where N` key types.
Some design decisions for a `trie::Trie{K,V}` regarding `keytype` and `getindex` might change in future versions based on discussions with the community.
:
- `getindex(trie, ks::K...)` and `setindex!(trie, v, ks::K...)` consider `Trie` as sparse representation of an object with values`::Union{V,Missing}` referenced by any finite `N`-dimensional key `ks::NTuple{N,K} where N`.
- `keytype(trie)` currently is `K`, should it be `ks::NTuple{N,K} where N`?
- Future versions might switch backend to Andy Ferris [Dictionaries.jl](https://github.com/andyferris/Dictionaries.jl).
Contributions, thoughts and suggestions very welcome!
<pre><code class="language-julia-repl">
julia> using Tries
julia> x=Trie((:a,)=>"a",
(:a,:b)=>"c",
(:a,:c,:d)=>"z",
(:a,:b,:d)=>1)
Trie{Symbol,Any}
└─ :a => "a"
├─ :b => "c"
│ └─ :d => 1
└─ :c
└─ :d => "z"
julia> eltype(x)
Any
julia> x[:a,:b]
SubTrie{Symbol,Any} @ :a, :b => "c"
└─ :d => 1
julia> x[:a,:b].path
(:a, :b)
julia> get(x[:a,:b])
"c"
julia> get(x[:a][:b,:d])
1
julia> #
get(x,[:a,:b])
"c"
julia> x[:z]="added"
"added"
julia> get(x[:z])
"added"
julia> x[:z,:n]="n"
"n"
julia> x[:z]
SubTrie{Symbol,Any} @ :z => "added"
└─ :n => "n"
julia> x[:z,:n]="m"
"m"
julia> x[:z]
SubTrie{Symbol,Any} @ :z => "added"
└─ :n => "m"
julia> x
Trie{Symbol,Any}
├─ :a => "a"
│ ├─ :b => "c"
│ │ └─ :d => 1
│ └─ :c
│ └─ :d => "z"
└─ :z => "added"
└─ :n => "m"</code></pre><pre><code class="language-julia-repl">julia> using Tries
julia> x=Trie{Int,Int}(0)
Trie{Int64,Int64} => 0
julia> subtrie!(x, 1,2,3,4,5) do x
x[end]+1
end
SubTrie{Int64,Int64} @ 1, 2, 3, 4, 5 => 6
julia> x
Trie{Int64,Int64} => 0
└─ 1 => 2
└─ 2 => 3
└─ 3 => 4
└─ 4 => 5
└─ 5 => 6
⋮
julia> collect(keys(x))
6-element Array{Tuple{Vararg{Int64,N} where N},1}:
()
(1,)
(1, 2)
(1, 2, 3)
(1, 2, 3, 4)
(1, 2, 3, 4, 5)
</code></pre>
`Tries` is used in [CombinedParsers.jl](https://github.com/gkappler/CombinedParsers.jl)
for fast prefix tree matching (see [docs](https://gkappler.github.io/CombinedParsers.jl/dev/man/example-either-trie/)).
| Tries | https://github.com/gkappler/Tries.jl.git |
|
[
"MIT"
] | 0.1.4 | 9bb6a6efd74e0f315a6e5bd73c15b58ac5a6de2c | docs | 1025 | # Tries.jl Documentation
Implemented of a Trie data structure.
This is an associative data structure with keys of type `NTuple{N,K} where N` and values of type `V`.
## Package Features
- General trie data structure building on `Dict`.
- Generalizes [DataStructures Trie](https://juliacollections.github.io/DataStructures.jl/latest/trie/) from `AbstractString` to arbitrary key types.
!!! note
Future versions might switch backend to Andy Ferris [Dictionaries.jl](https://github.com/andyferris/Dictionaries.jl).
## Using Tries
```@repl
using Tries
x=Trie((:a,)=>"a",
(:a,:b)=>"c",
(:a,:c,:d)=>"z",
(:a,:b,:d)=>1)
eltype(x)
x[:a,:b]
x[:a,:b].path
get(x[:a,:b])
get(x[:a][:b,:d])
#
get(x,[:a,:b])
x[:z]="added"
get(x[:z])
x[:z,:n]="n"
x[:z]
x[:z,:n]="m"
x[:z]
x
```
```@repl
using Tries
x=Trie{Int,Int}(0)
subtrie!(x, 1,2,3,4,5) do x
x[end]+1
end
x
collect(keys(x))
```
## Library Outline
```@contents
Pages = [ "lib/public.md" ]
Depth = 5
```
```@index
Pages = ["lib/public.md"]
```
| Tries | https://github.com/gkappler/Tries.jl.git |
|
[
"MIT"
] | 0.1.4 | 9bb6a6efd74e0f315a6e5bd73c15b58ac5a6de2c | docs | 199 | # Public Interface
Documentation for `Tries.jl`'s public interface.
```@docs
Tries
Trie
SubTrie
get
get!
show
isempty
keytype
eltype
haskey
subtrie
subtrie!
getindex
setindex!
pairs
values
keys
```
| Tries | https://github.com/gkappler/Tries.jl.git |
|
[
"MIT"
] | 1.7.8 | ced77ccd05871211833ae690698488c52eb38680 | code | 1342 | # Copyright (c) 2024 Oscar Dowson, and contributors
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.
using Tar, Inflate, SHA, TOML
function get_artifact(data)
dir = "$(data.arch)-$(data.platform)"
filename = "$(dir).tar.bz2"
run(`tar -cjf $filename $dir`)
sha256 = bytes2hex(open(sha256, filename))
url = "https://github.com/chkwon/PATHSolver.jl/releases/download/v5.0.3-path-binaries/$filename"
ret = Dict(
"git-tree-sha1" => Tar.tree_hash(`gzcat $filename`),
"arch" => data.arch,
"os" => data.os,
"download" => Any[Dict("sha256" => sha256, "url" => url)],
)
return ret
end
function main()
platforms = [
(os = "linux", arch = "x86_64", platform = "linux-gnu"),
(os = "macos", arch = "x86_64", platform = "apple-darwin"),
(os = "macos", arch = "aarch64", platform = "apple-darwin"),
(os = "windows", arch = "x86_64", platform = "w64-mingw32"),
]
output = Dict("PATHSolver" => get_artifact.(platforms))
open(joinpath(dirname(@__DIR__), "Artifacts.toml"), "w") do io
return TOML.print(io, output)
end
return
end
# julia --project=scripts scripts/update_artifacts.jl
#
# Update the Artifacts.toml file.
main()
| PATHSolver | https://github.com/chkwon/PATHSolver.jl.git |
|
[
"MIT"
] | 1.7.8 | ced77ccd05871211833ae690698488c52eb38680 | code | 27985 | # Copyright (c) 2016 Changhyun Kwon, Oscar Dowson, and contributors
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.
# PATH uses the Float64 value 1e20 to represent +infinity.
const INFINITY = 1e20
###
### License.h
###
function c_api_License_SetString(license::String)
return @ccall PATH_SOLVER.License_SetString(license::Ptr{Cchar})::Cint
end
###
### Output_Interface.h
###
const c_api_Output_Log = Cint(1 << 0)
const c_api_Output_Status = Cint(1 << 1)
const c_api_Output_Listing = Cint(1 << 2)
mutable struct OutputData
io::IO
end
mutable struct OutputInterface
output_data::Ptr{Cvoid}
print::Ptr{Cvoid}
flush::Ptr{Cvoid}
end
# flush argument is optional and appears unused. I could not trigger
# a test that used it.
# function _c_flush(data::Ptr{Cvoid}, mode::Cint)
# output_data = unsafe_pointer_to_objref(data)::OutputData
# flush(output_data.io)
# return
# end
function _c_print(data::Ptr{Cvoid}, mode::Cint, msg::Ptr{Cchar})
if (
mode & c_api_Output_Log == c_api_Output_Log ||
# TODO(odow): decide whether to print the Output_Status. It has a lot of
# information...
# mode & c_api_Output_Status == c_api_Output_Status ||
mode & c_api_Output_Listing == c_api_Output_Listing
)
output_data = unsafe_pointer_to_objref(data)::OutputData
print(output_data.io, unsafe_string(msg))
end
return
end
function OutputInterface(output_data)
_C_PRINT = @cfunction(_c_print, Cvoid, (Ptr{Cvoid}, Cint, Ptr{Cchar}))
_C_FLUSH = C_NULL # flush argument is optional
# To make pointer_from_objref legal, you must ensure that output_data AND
# the Output_Interface object outlive any ccalls. We do this in solve_mcp
# using `gc_root`.
return OutputInterface(pointer_from_objref(output_data), _C_PRINT, _C_FLUSH)
end
function c_api_Output_SetInterface(o::OutputInterface)
return @ccall(
PATH_SOLVER.Output_SetInterface(o::Ref{OutputInterface})::Cvoid,
)
end
###
### Options.h
###
mutable struct Options
ptr::Ptr{Cvoid}
function Options(ptr::Ptr{Cvoid})
o = new(ptr)
finalizer(c_api_Options_Destroy, o)
return o
end
end
Base.cconvert(::Type{Ptr{Cvoid}}, x::Options) = x
Base.unsafe_convert(::Type{Ptr{Cvoid}}, x::Options) = x.ptr
function c_api_Options_Create()
return Options(@ccall PATH_SOLVER.Options_Create()::Ptr{Cvoid})
end
function c_api_Options_Destroy(o::Options)
return @ccall PATH_SOLVER.Options_Destroy(o::Ptr{Cvoid})::Cvoid
end
function c_api_Options_Default(o::Options)
return @ccall PATH_SOLVER.Options_Default(o::Ptr{Cvoid})::Cvoid
end
function c_api_Options_Display(o::Options)
return @ccall PATH_SOLVER.Options_Display(o::Ptr{Cvoid})::Cvoid
end
function c_api_Options_Read(o::Options, filename::String)
return @ccall(
PATH_SOLVER.Options_Read(o::Ptr{Cvoid}, filename::Ptr{Cchar})::Cvoid,
)
end
function c_api_Path_AddOptions(o::Options)
return @ccall PATH_SOLVER.Path_AddOptions(o::Ptr{Cvoid})::Cvoid
end
###
### Presolve_Interface.h
###
const PRESOLVE_LINEAR = 0
const PRESOLVE_NONLINEAR = 1
mutable struct PresolveData
jac_typ::Function
end
function _c_jac_typ(data_ptr::Ptr{Cvoid}, nnz::Cint, typ_ptr::Ptr{Cint})
data = unsafe_pointer_to_objref(data_ptr)::PresolveData
data.jac_typ(nnz, unsafe_wrap(Array{Cint}, typ_ptr, nnz))
return
end
mutable struct Presolve_Interface
presolve_data::Ptr{Cvoid}
start_pre::Ptr{Cvoid}
start_post::Ptr{Cvoid}
finish_pre::Ptr{Cvoid}
finish_post::Ptr{Cvoid}
jac_typ::Ptr{Cvoid}
con_typ::Ptr{Cvoid}
# To make pointer_from_objref legal, you must ensure that presolve_data AND
# the Presolve_Interface object outlive any ccalls. We do this in solve_mcp
# using `gc_root`.
function Presolve_Interface(presolve_data::PresolveData)
return new(
pointer_from_objref(presolve_data),
C_NULL,
C_NULL,
C_NULL,
C_NULL,
@cfunction(_c_jac_typ, Cvoid, (Ptr{Cvoid}, Cint, Ptr{Cint})),
C_NULL,
)
end
end
###
### MCP_Interface.h
###
mutable struct InterfaceData
n::Cint
nnz::Cint
F::Function
J::Function
lb::Vector{Cdouble}
ub::Vector{Cdouble}
z::Vector{Cdouble}
variable_names::Vector{String}
constraint_names::Vector{String}
end
function _c_problem_size(
id_ptr::Ptr{Cvoid},
n_ptr::Ptr{Cint},
nnz_ptr::Ptr{Cint},
)
id_data = unsafe_pointer_to_objref(id_ptr)::InterfaceData
unsafe_store!(n_ptr, id_data.n)
unsafe_store!(nnz_ptr, id_data.nnz)
return
end
function _c_bounds(
id_ptr::Ptr{Cvoid},
n::Cint,
z_ptr::Ptr{Cdouble},
lb_ptr::Ptr{Cdouble},
ub_ptr::Ptr{Cdouble},
)
id_data = unsafe_pointer_to_objref(id_ptr)::InterfaceData
copy!(unsafe_wrap(Array{Cdouble}, z_ptr, n), id_data.z)
copy!(unsafe_wrap(Array{Cdouble}, lb_ptr, n), id_data.lb)
copy!(unsafe_wrap(Array{Cdouble}, ub_ptr, n), id_data.ub)
return
end
function _c_function_evaluation(
id_ptr::Ptr{Cvoid},
n::Cint,
x_ptr::Ptr{Cdouble},
f_ptr::Ptr{Cdouble},
)
id_data = unsafe_pointer_to_objref(id_ptr)::InterfaceData
x = unsafe_wrap(Array{Cdouble}, x_ptr, n)
f = unsafe_wrap(Array{Cdouble}, f_ptr, n)
return id_data.F(n, x, f)
end
function _c_jacobian_evaluation(
id_ptr::Ptr{Cvoid},
n::Cint,
x_ptr::Ptr{Cdouble},
wantf::Cint,
f_ptr::Ptr{Cdouble},
nnz_ptr::Ptr{Cint},
col_ptr::Ptr{Cint},
len_ptr::Ptr{Cint},
row_ptr::Ptr{Cint},
data_ptr::Ptr{Cdouble},
)
id_data = unsafe_pointer_to_objref(id_ptr)::InterfaceData
x = unsafe_wrap(Array{Cdouble}, x_ptr, n)
err = Cint(0)
if wantf > 0
f = unsafe_wrap(Array{Cdouble}, f_ptr, n)
err += id_data.F(n, x, f)
end
nnz = unsafe_load(nnz_ptr)::Cint
col = unsafe_wrap(Array{Cint}, col_ptr, n)
len = unsafe_wrap(Array{Cint}, len_ptr, n)
row = unsafe_wrap(Array{Cint}, row_ptr, nnz)
data = unsafe_wrap(Array{Cdouble}, data_ptr, nnz)
err += id_data.J(n, nnz, x, col, len, row, data)
unsafe_store!(nnz_ptr, Cint(sum(len)))
return err
end
function _c_variable_name(
id_ptr::Ptr{Cvoid},
i::Cint,
buf_ptr::Ptr{UInt8},
buf_size::Cint,
)
id_data = unsafe_pointer_to_objref(id_ptr)::InterfaceData
data = fill(UInt8('\0'), buf_size)
units = codeunits(id_data.variable_names[i])
for j in 1:min(length(units), buf_size)-1
data[j] = units[j]
end
GC.@preserve data begin
unsafe_copyto!(buf_ptr, pointer(data), buf_size)
end
return
end
function _c_constraint_name(
id_ptr::Ptr{Cvoid},
i::Cint,
buf_ptr::Ptr{UInt8},
buf_size::Cint,
)
id_data = unsafe_pointer_to_objref(id_ptr)::InterfaceData
data = fill(UInt8('\0'), buf_size)
units = codeunits(id_data.constraint_names[i])
for j in 1:min(length(units), buf_size)-1
data[j] = units[j]
end
GC.@preserve data begin
unsafe_copyto!(buf_ptr, pointer(data), buf_size)
end
return
end
"""
MCP_Interface
A storage struct that is used to pass problem-specific functions to PATH.
"""
mutable struct MCP_Interface
interface_data::Ptr{Cvoid}
problem_size::Ptr{Cvoid}
bounds::Ptr{Cvoid}
function_evaluation::Ptr{Cvoid}
jacobian_evaluation::Ptr{Cvoid}
# TODO(odow): the .h files I have don't include the hessian evaluation in
# MCP_Interface, but Standalone_Path.c includes it. Ask M.
# Ferris to look at the source.
# Answer: there is an #ifdef to turn it on or off. In the GAMS builds it
# appears to be on, but we should be careful when updating PATH
# versions.
hessian_evaluation::Ptr{Cvoid}
start::Ptr{Cvoid}
finish::Ptr{Cvoid}
variable_name::Ptr{Cvoid}
constraint_name::Ptr{Cvoid}
basis::Ptr{Cvoid}
function MCP_Interface(interface_data::InterfaceData)
_C_PROBLEM_SIZE = @cfunction(
_c_problem_size,
Cvoid,
(Ptr{Cvoid}, Ptr{Cint}, Ptr{Cint})
)
_C_BOUNDS = @cfunction(
_c_bounds,
Cvoid,
(Ptr{Cvoid}, Cint, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble})
)
_C_FUNCTION_EVALUATION = @cfunction(
_c_function_evaluation,
Cint,
(Ptr{Cvoid}, Cint, Ptr{Cdouble}, Ptr{Cdouble})
)
_C_JACOBIAN_EVALUATION = @cfunction(
_c_jacobian_evaluation,
Cint,
(
Ptr{Cvoid},
Cint,
Ptr{Cdouble},
Cint,
Ptr{Cdouble},
Ptr{Cint},
Ptr{Cint},
Ptr{Cint},
Ptr{Cint},
Ptr{Cdouble},
)
)
if isempty(interface_data.variable_names)
_C_VARIABLE_NAME = C_NULL
else
_C_VARIABLE_NAME = @cfunction(
_c_variable_name,
Cvoid,
(Ptr{Cvoid}, Cint, Ptr{Cuchar}, Cint)
)
end
if isempty(interface_data.constraint_names)
_C_CONSTRAINT_NAME = C_NULL
else
_C_CONSTRAINT_NAME = @cfunction(
_c_constraint_name,
Cvoid,
(Ptr{Cvoid}, Cint, Ptr{Cuchar}, Cint)
)
end
# To make pointer_from_objref legal, you must ensure that interface_data
# AND the MCP_Interface object outlive any ccalls. We do this in
# solve_mcp using `gc_root`.
return new(
pointer_from_objref(interface_data),
_C_PROBLEM_SIZE,
_C_BOUNDS,
_C_FUNCTION_EVALUATION,
_C_JACOBIAN_EVALUATION,
C_NULL,
C_NULL, # See TODO note in definition of fields above.
C_NULL,
_C_VARIABLE_NAME,
_C_CONSTRAINT_NAME,
C_NULL,
)
end
end
mutable struct MCP
n::Int
ptr::Ptr{Cvoid}
function MCP(n::Int, ptr::Ptr{Cvoid})
m = new(n, ptr)
finalizer(c_api_MCP_Destroy, m)
return m
end
end
Base.cconvert(::Type{Ptr{Cvoid}}, x::MCP) = x
Base.unsafe_convert(::Type{Ptr{Cvoid}}, x::MCP) = x.ptr
function c_api_MCP_Create(n::Int, nnz::Int)
ptr = @ccall PATH_SOLVER.MCP_Create(n::Cint, nnz::Cint)::Ptr{Cvoid}
return MCP(n, ptr)
end
function c_api_MCP_Jacobian_Structure_Constant(m::MCP, flag::Bool)
@ccall PATH_SOLVER.MCP_Jacobian_Structure_Constant(
m::Ptr{Cvoid},
flag::Cint,
)::Cvoid
return
end
function c_api_MCP_Jacobian_Data_Contiguous(m::MCP, flag::Bool)
@ccall PATH_SOLVER.MCP_Jacobian_Data_Contiguous(
m::Ptr{Cvoid},
flag::Cint,
)::Cvoid
return
end
function c_api_MCP_Destroy(m::MCP)
if m.ptr === C_NULL
return
end
@ccall PATH_SOLVER.MCP_Destroy(m::Ptr{Cvoid})::Cvoid
return
end
function c_api_MCP_SetInterface(m::MCP, interface::MCP_Interface)
@ccall PATH_SOLVER.MCP_SetInterface(
m::Ptr{Cvoid},
interface::Ref{MCP_Interface},
)::Cvoid
return
end
function c_api_MCP_SetPresolveInterface(m::MCP, interface::Presolve_Interface)
@ccall PATH_SOLVER.MCP_SetPresolveInterface(
m::Ptr{Cvoid},
interface::Ref{Presolve_Interface},
)::Cvoid
return
end
function c_api_MCP_GetX(m::MCP)
ptr = @ccall PATH_SOLVER.MCP_GetX(m::Ptr{Cvoid})::Ptr{Cdouble}
return copy(unsafe_wrap(Array{Cdouble}, ptr, m.n))
end
###
### Types.h
###
@enum(
MCP_Termination,
MCP_Solved = 1,
MCP_NoProgress,
MCP_MajorIterationLimit,
MCP_MinorIterationLimit,
MCP_TimeLimit,
MCP_UserInterrupt,
MCP_BoundError,
MCP_DomainError,
MCP_Infeasible,
MCP_Error,
MCP_LicenseError,
MCP_OK
)
mutable struct Information
# Double residual; /* Value of residual at final point */
residual::Cdouble
# Double distance; /* Distance between initial and final point */
distance::Cdouble
# Double steplength; /* Steplength taken */
steplength::Cdouble
# Double total_time; /* Amount of time spent in the code */
total_time::Cdouble
# Double basis_time; /* Amount of time spent factoring */
basis_time::Cdouble
# Double maximum_distance; /* Maximum distance from init point allowed */
maximum_distance::Cdouble
# Int major_iterations; /* Major iterations taken */
major_iterations::Cint
# Int minor_iterations; /* Minor iterations taken */
minor_iterations::Cint
# Int crash_iterations; /* Crash iterations taken */
crash_iterations::Cint
# Int function_evaluations; /* Function evaluations performed */
function_evaluations::Cint
# Int jacobian_evaluations; /* Jacobian evaluations performed */
jacobian_evaluations::Cint
# Int gradient_steps; /* Gradient steps taken */
gradient_steps::Cint
# Int restarts; /* Restarts used */
restarts::Cint
# Int generate_output; /* Mask where output can be displayed. */
generate_output::Cint
# Int generated_output; /* Mask where output displayed. */
generated_output::Cint
# Boolean forward; /* Move forward? */
forward::Bool
# Boolean backtrace; /* Back track? */
backtrace::Bool
# Boolean gradient; /* Take gradient step? */
gradient::Bool
# Boolean use_start; /* Use the starting point provided? */
use_start::Bool
# Boolean use_basics; /* Use the basis provided? */
use_basics::Bool
# Boolean used_start; /* Was the starting point given used? */
used_start::Bool
# Boolean used_basics; /* Was the initial basis given used? */
used_basics::Bool
function Information(;
generate_output::Integer = 0,
use_start::Bool = true,
use_basics::Bool = false,
)
return new(
0.0, # residual
0.0, # distance
0.0, # steplength
0.0, # total_time
0.0, # basis_time
0.0, # maximum_distance
0, # major_iterations
0, # minor_iterations
0, # crash_iterations
0, # function_evaluations
0, # jacobian_evaluations
0, # gradient_steps
0, # restarts
generate_output, # generate_output
0, # generated_output
false, # forward
false, # backtrace
false, # gradient
use_start, # use_start
use_basics, # use_basics
false, # used_start
false, # used_basics
)
end
end
###
### Path.h
###
"""
c_api_Path_CheckLicense(n::Int, nnz::Int)
Check that the current license (stored in the environment variable
`PATH_LICENSE_STRING` if present) is valid for problems with `n` variables and
`nnz` non-zeros in the Jacobian.
Returns a nonzero value on successful completion, and a zero value on failure.
"""
function c_api_Path_CheckLicense(n::Int, nnz::Int)
return @ccall PATH_SOLVER.Path_CheckLicense(n::Cint, nnz::Cint)::Cint
end
"""
c_api_Path_Version()
Return a string of the PATH version.
"""
function c_api_Path_Version()
return unsafe_string(@ccall PATH_SOLVER.Path_Version()::Ptr{Cchar})
end
"""
c_api_Path_Solve(m::MCP, info::Information)
Returns a MCP_Termination status.
"""
function c_api_Path_Solve(m::MCP, info::Information)
return @ccall(
PATH_SOLVER.Path_Solve(m::Ptr{Cvoid}, info::Ref{Information})::Cint,
)
end
###
### Standalone interface
###
"""
solve_mcp(
F::Function,
J::Function
lb::Vector{Cdouble},
ub::Vector{Cdouble},
z::Vector{Cdouble};
nnz::Int = length(lb)^2,
variable_name::Vector{String}=String[],
constraint_name::Vector{String}=String[],
silent::Bool = false,
generate_output::Integer = 0,
use_start::Bool = true,
use_basics::Bool = false,
jacobian_structure_constant::Bool = false,
jacobian_data_contiguous::Bool = false,
jacobian_linear_elements::Vector{Int} = Int[],
kwargs...
)
Mathematically, the mixed complementarity problem is to find an x such that
for each i, at least one of the following hold:
1. F_i(x) = 0, lb_i <= (x)_i <= ub_i
2. F_i(x) > 0, (x)_i = lb_i
3. F_i(x) < 0, (x)_i = ub_i
where F is a given function from R^n to R^n, and lb and ub are prescribed
lower and upper bounds.
## The `F` argument
`F` is a function that calculates the value of function ``F(x)`` and stores the
result in `f`. It must have the signature:
```julia
function F(n::Cint, x::Vector{Cdouble}, f::Vector{Cdouble})
for i in 1:n
f[i] = ... do stuff ...
end
return Cint(0)
end
```
## The `J` argument
`J` is a function that calculates the Jacobiann of the function ``F(x)``. The
Jacobian is a square sparse matrix. It must have the signature:
```julia
function J(
n::Cint,
nnz::Cint,
x::Vector{Cdouble},
col::Vector{Cint},
len::Vector{Cint},
row::Vector{Cint},
data::Vector{Cdouble},
)
# ...
return Cint(0)
end
```
where:
* `n` is the number of variables (which is also the number rows and columns in
the Jacobian matrix).
* `nnz` is the maximum number of non-zero terms in the Jacobian. This value is
chosen by the user as the `nnz` argumennt to `solve_mcp`.
* `x` is the value of the decision variables at which to evaluate the Jacobian.
The remaining arguments, `col`, `len`, `row`, and `data`, specify a sparse
column representation of the Jacobian matrix. These must be filled in by your
function.
* `col` is a length `n` vector, where `col[i]` is the 1-indexed position of the
start of the non-zeros in column `i` in the `data` vector.
* `len` is a length `n` vector, where `len[i]` is the number of non-zeros in
column `i`.
Together, `col` and `len` can be used to form a range of indices in `row` and
`data` corresponding to the non-zero elements of column `i` in the Jacobian.
Thus, we can iterate over the non-zeros in the Jacobian using:
```julia
for i in 1:n
for k in (col[i]):(col[i] + len[i] - 1)
row[k] = ... the 1-indexed row of the k'th non-zero in the Jacobian
data[k] = ... the value of the k'th non-zero in the Jacobian
end
end
```
To improve performance, see the `jacobian_structure_constant` and
`jacobian_data_contiguous` keyword arguments.
## Other positional arguments
* `lb`: a vector of the variable lower bounds
* `ub`: a vector of the variable upper bounds
* `z`: an initial starting point for the search. You can disable this by
passing an empty vector and settig `use_start = false`
## Keyword arguments
* `nnz`: the maximum number of non-zeros in the Jacobian matrix. If not
specified if defaults to the dense estimate of `n^2` where `n` is the number
of variables.
* `variable_name`: a vector of variable names. This can improve the legibility
of the output printed by PATH, particularly if there are issues associated
with a particular variable.
* `constraint_name`: a vector of constraint names. This can improve the
legibility of the output printed by PATH, particularly if there are issues
associated with a particular row of the `F` function.
* `silent`: set `silent = true` to disable printing.
* `generate_output`: an integer mask passed to the C API of PATH to dictate
with output can be displayed.
* `use_start`: set `use_start = false` to disable the use of the startint point
`z`.
* `use_basics`: set `use_basics = true` to use the basis provided.
* `jacobian_structure_constant`: if `true`, the sparsity pattern of the
Jacobian matrix must be constant between evaluations. You can improve
performance by setting this to `true` and filling the `col`, `len` and `row`
on the first evaluation only.
* `jacobian_data_contiguous`: if `true`, the Jacobian data is stored
contiguously from `1..nnz` in the `row` and `data` arrays of the Jacobian
callback. In most cases, you can improve performance by settinng this to
`true`. It is `false` by default for the general case.
* `jacobian_linear_elements`: a vector of the 1-indexed indices of the Jacobian
`data` array that appear linearly in the Jacobian, that is, their value is
independent of the point `x` at which the Jacobian is evaluated. If you set
this option, you must also set `jacobian_structure_constant = true`.
* `kwargs`: other options passed to directly to PATH.
"""
function solve_mcp(
F::Function,
J::Function,
lb::Vector{Cdouble},
ub::Vector{Cdouble},
z::Vector{Cdouble};
nnz::Int = length(lb)^2,
variable_names::Vector{String} = String[],
constraint_names::Vector{String} = String[],
silent::Bool = false,
generate_output::Integer = 0,
use_start::Bool = true,
use_basics::Bool = false,
jacobian_structure_constant::Bool = false,
jacobian_data_contiguous::Bool = false,
jacobian_linear_elements::Vector{Int} = Int[],
kwargs...,
)
@assert length(z) == length(lb) == length(ub)
n = length(z)
if nnz > typemax(Cint)
return MCP_Error, nothing, nothing
elseif n == 0
return MCP_Solved, nothing, nothing
end
# gc_root is used to store various objects to prevent them from being GC'd.
gc_root = IdDict()
GC.@preserve gc_root begin
out_io = silent ? IOBuffer() : stdout
output_data = OutputData(out_io)
# We shouldn't GC output_data until we exit the GC.@preserve block.
gc_root[output_data] = true
output_interface = OutputInterface(output_data)
# We shouldn't GC output_interface until we exit the GC.@preserve block.
gc_root[output_interface] = true
c_api_Output_SetInterface(output_interface)
# We need to call `c_api_Path_CheckLicense` _after_ setting the output
# interface because CheckLicense may try to print to the screen.
if c_api_Path_CheckLicense(n, nnz) == 0
return MCP_LicenseError, nothing, nothing
end
o = c_api_Options_Create()
# Options has a finalizer. We don't want that to run until we exit the
# GC.@preserve block.
gc_root[o] = true
c_api_Path_AddOptions(o)
c_api_Options_Default(o)
m = c_api_MCP_Create(n, nnz)
if jacobian_structure_constant
c_api_MCP_Jacobian_Structure_Constant(m, true)
end
if jacobian_data_contiguous
c_api_MCP_Jacobian_Data_Contiguous(m, true)
end
id_data = InterfaceData(
Cint(n),
Cint(nnz),
F,
J,
lb,
ub,
z,
variable_names,
constraint_names,
)
# We shouldn't GC id_data until we exit the GC.@preserve block.
gc_root[id_data] = true
m_interface = MCP_Interface(id_data)
# We shouldn't GC m_interface until we exit the GC.@preserve block.
gc_root[m_interface] = true
c_api_MCP_SetInterface(m, m_interface)
if jacobian_structure_constant && !isempty(jacobian_linear_elements)
function presolve_fn(::Cint, types::Vector{Cint})
types[jacobian_linear_elements] .= PRESOLVE_LINEAR
return
end
presolve_data = PresolveData(presolve_fn)
# We shouldn't GC presolve_data until we exit the GC.@preserve block.
gc_root[presolve_data] = true
presolve_interface = Presolve_Interface(presolve_data)
# We shouldn't GC presolve_interface until we exit the GC.@preserve
# block.
gc_root[presolve_interface] = true
c_api_MCP_SetPresolveInterface(m, presolve_interface)
end
if length(kwargs) > 0
mktemp() do path, io
println(
io,
"* Automatically generated by PATH.jl. Do not edit.",
)
for (key, val) in kwargs
println(io, key, " ", val)
end
close(io)
return c_api_Options_Read(o, path)
end
end
c_api_Options_Display(o)
info = Information(;
generate_output = generate_output,
use_start = use_start,
use_basics = use_basics,
)
status = c_api_Path_Solve(m, info)
X = c_api_MCP_GetX(m)
end # GC.@preserve
# TODO(odow): I don't know why, but manually calling MCP_Destroy was
# necessary to avoid a segfault on Julia 1.0 when using LUSOL. I guess it's
# something to do with the timing of when things need to get freed on the
# PATH side? i.e., MCP_Destroy before other things?
c_api_MCP_Destroy(m)
m.ptr = C_NULL
return MCP_Termination(status), X, info
end
function _linear_function(M::AbstractMatrix, q::Vector)
if size(M, 1) != size(M, 2)
error("M not square! size = $(size(M))")
elseif size(M, 1) != length(q)
error("q is wrong shape. Expected $(size(M, 1)), got $(length(q)).")
end
return function F(n::Cint, x::Vector{Cdouble}, f::Vector{Cdouble})
f .= M * x .+ q
return Cint(0)
end
end
function _linear_jacobian(M::SparseArrays.SparseMatrixCSC{Cdouble,Cint})
# Size is checked with error message in _linear_function.
@assert size(M, 1) == size(M, 2)
return function J(
n::Cint,
nnz::Cint,
x::Vector{Cdouble},
col::Vector{Cint},
len::Vector{Cint},
row::Vector{Cint},
data::Vector{Cdouble},
)
@assert n == length(x) == length(col) == length(len) == size(M, 1)
@assert nnz == length(row) == length(data)
@assert nnz >= SparseArrays.nnz(M)
for i in 1:n
col[i] = M.colptr[i]
len[i] = M.colptr[i+1] - M.colptr[i]
end
for (i, v) in enumerate(SparseArrays.rowvals(M))
row[i] = v
end
for (i, v) in enumerate(SparseArrays.nonzeros(M))
data[i] = v
end
return Cint(0)
end
end
"""
solve_mcp(;
M::SparseArrays.SparseMatrixCSC{Cdouble, Cint},
q::Vector{Cdouble},
lb::Vector{Cdouble},
ub::Vector{Cdouble},
z::Vector{Cdouble};
kwargs...
)
Mathematically, the mixed complementarity problem is to find an x such that
for each i, at least one of the following hold:
1. F_i(x) = 0, lb_i <= (x)_i <= ub_i
2. F_i(x) > 0, (x)_i = lb_i
3. F_i(x) < 0, (x)_i = ub_i
where F is a function `F(x) = M * x + q` from R^n to R^n, and lb and ub are
prescribed lower and upper bounds.
`z` is an initial starting point for the search.
"""
function solve_mcp(
M::SparseArrays.SparseMatrixCSC{Cdouble,Cint},
q::Vector{Cdouble},
lb::Vector{Cdouble},
ub::Vector{Cdouble},
z::Vector{Cdouble};
nnz = SparseArrays.nnz(M),
kwargs...,
)
return solve_mcp(
_linear_function(M, q),
_linear_jacobian(M),
lb,
ub,
z;
nnz = nnz,
jacobian_structure_constant = true,
jacobian_data_contiguous = true,
jacobian_linear_elements = collect(1:nnz),
kwargs...,
)
end
| PATHSolver | https://github.com/chkwon/PATHSolver.jl.git |
|
[
"MIT"
] | 1.7.8 | ced77ccd05871211833ae690698488c52eb38680 | code | 15010 | # Copyright (c) 2016 Changhyun Kwon, Oscar Dowson, and contributors
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.
MOI.Utilities.@model(
Optimizer,
(), # Scalar sets
(), # Typed scalar sets
(MOI.Complements,), # Vector sets
(), # Typed vector sets
(), # Scalar functions
(), # Typed scalar functions
(MOI.VectorOfVariables, MOI.VectorNonlinearFunction), # Vector functions
(MOI.VectorAffineFunction, MOI.VectorQuadraticFunction), # Typed vector functions
true, # is_optimizer
)
function MOI.supports_constraint(
::Optimizer,
::Type{MOI.VariableIndex},
::Type{<:MOI.AbstractScalarSet},
)
return false
end
function MOI.supports_constraint(
::Optimizer,
::Type{MOI.VariableIndex},
::Type{S},
) where {
S<:Union{
MOI.LessThan{Float64},
MOI.GreaterThan{Float64},
MOI.EqualTo{Float64},
MOI.Interval{Float64},
},
}
return true
end
function MOI.supports(
::Optimizer,
::MOI.ObjectiveFunction{F},
) where {F<:MOI.AbstractFunction}
return false
end
"""
Optimizer()
Define a new PATH optimizer.
Pass options using `MOI.RawOptimizerAttribute`. Common options include:
- output => "yes"
- convergence_tolerance => 1e-6
- time_limit => 3600
A full list of options can be found at http://pages.cs.wisc.edu/~ferris/path/options.pdf.
### Example
```julia
import PATHSolver
import MathOptInterface as MOI
model = PATHSolver.Optimizer()
MOI.set(model, MOI.RawOptimizerAttribute("output"), "no")
```
"""
function Optimizer()
model = Optimizer{Float64}()
model.ext[:silent] = false
model.ext[:kwargs] = Dict{Symbol,Any}()
model.ext[:solution] = nothing
model.ext[:user_defined_functions] = Dict{MOI.UserDefinedFunction,Any}()
return model
end
# MOI.RawOptimizerAttribute
MOI.supports(::Optimizer, ::MOI.RawOptimizerAttribute) = true
function MOI.set(model::Optimizer, p::MOI.RawOptimizerAttribute, v)
model.ext[:kwargs][Symbol(p.name)] = v
return
end
function MOI.get(model::Optimizer, p::MOI.RawOptimizerAttribute)
return get(model.ext[:kwargs], Symbol(p.name), nothing)
end
# MOI.Silent
MOI.supports(model::Optimizer, ::MOI.Silent) = true
MOI.get(model::Optimizer, ::MOI.Silent) = model.ext[:silent]
function MOI.set(model::Optimizer, ::MOI.Silent, x::Bool)
model.ext[:silent] = x
return
end
# MOI.SolverName
MOI.get(model::Optimizer, ::MOI.SolverName) = c_api_Path_Version()
# MOI.VariablePrimalStart
function MOI.supports(
::Optimizer,
::MOI.VariablePrimalStart,
::Type{MOI.VariableIndex},
)
return true
end
function MOI.get(
model::Optimizer,
::MOI.VariablePrimalStart,
x::MOI.VariableIndex,
)
initial = get(model.ext, :variable_primal_start, nothing)
if initial === nothing
return nothing
end
return get(initial, x, nothing)
end
function MOI.set(
model::Optimizer,
::MOI.VariablePrimalStart,
x::MOI.VariableIndex,
value,
)
initial = get(model.ext, :variable_primal_start, nothing)
if initial === nothing
model.ext[:variable_primal_start] = Dict{MOI.VariableIndex,Float64}()
initial = model.ext[:variable_primal_start]
end
if value === nothing
delete!(initial, x)
else
initial[x] = value
end
return
end
# MOI.UserDefinedFunction
MOI.supports(::Optimizer, ::MOI.UserDefinedFunction) = true
function MOI.get(model::Optimizer, attr::MOI.UserDefinedFunction)
return model.ext[:user_defined_functions][attr]
end
function MOI.set(model::Optimizer, attr::MOI.UserDefinedFunction, value)
model.ext[:user_defined_functions][attr] = value
return
end
# Operators
function _F_linear_operator(model::Optimizer)
n = MOI.get(model, MOI.NumberOfVariables())
I, J, V = Int32[], Int32[], Float64[]
q = zeros(n)
has_term = fill(false, n)
names = fill("", n)
for index in MOI.get(
model,
MOI.ListOfConstraintIndices{
MOI.VectorAffineFunction{Float64},
MOI.Complements,
}(),
)
Fi = MOI.get(model, MOI.ConstraintFunction(), index)
Si = MOI.get(model, MOI.ConstraintSet(), index)
var_i = div(Si.dimension, 2) + 1
if Si.dimension != length(Fi.constants)
error(
"Dimension of constant vector $(length(Fi.constants)) does not match the " *
"required dimension of the complementarity set $(Si.dimension).",
)
elseif any(!iszero, Fi.constants[var_i:end])
error(
"VectorAffineFunction malformed: a constant associated with a " *
"complemented variable is not zero: $(Fi.constants[var_i:end]).",
)
end
# First pass: get rows vector and check for invalid functions.
rows = fill(0, Si.dimension)
for term in Fi.terms
if term.output_index <= div(Si.dimension, 2)
# No-op: leave for second pass.
continue
elseif term.output_index > Si.dimension
error(
"VectorAffineFunction malformed: output_index $(term.output_index) " *
"is too large.",
)
end
dimension_i = term.output_index - div(Si.dimension, 2)
row_i = term.scalar_term.variable.value
if rows[dimension_i] != 0 || has_term[row_i]
error(
"The variable $(term.scalar_term.variable) appears in more " *
"than one complementarity constraint.",
)
elseif term.scalar_term.coefficient != 1.0
error(
"VectorAffineFunction malformed: variable " *
"$(term.scalar_term.variable) has a coefficient that is not 1 " *
"in row $(term.output_index) of the VectorAffineFunction.",
)
end
rows[dimension_i] = row_i
has_term[row_i] = true
q[row_i] = Fi.constants[dimension_i]
end
# Second pass: add to sparse array
for term in Fi.terms
s_term = term.scalar_term
if term.output_index >= var_i || iszero(s_term.coefficient)
continue
end
row_i = rows[term.output_index]
if iszero(row_i)
error(
"VectorAffineFunction malformed: expected variable in row " *
"$(div(Si.dimension, 2) + term.output_index).",
)
end
push!(I, row_i)
push!(J, s_term.variable.value)
push!(V, s_term.coefficient)
end
c_name = MOI.get(model, MOI.ConstraintName(), index)
if length(rows) == 2
names[rows[1]] = c_name
else
for i in 1:div(Si.dimension, 2)
names[rows[i]] = "$(c_name)[$i]"
end
end
end
M = SparseArrays.sparse(I, J, V, n, n)
return M, q, SparseArrays.nnz(M), names
end
_to_f(f) = convert(MOI.ScalarNonlinearFunction, f)
_to_x(f::MOI.VariableIndex) = f
_to_x(f::MOI.ScalarAffineFunction) = convert(MOI.VariableIndex, f)
_to_x(f::MOI.ScalarQuadraticFunction) = convert(MOI.VariableIndex, f)
function _to_x(f::MOI.ScalarNonlinearFunction)
# Hacky way to ensure that f is a standalone variable
@assert f isa MOI.ScalarNonlinearFunction
@assert f.head == :+ && length(f.args) == 1
@assert f.args[1] isa MOI.VariableIndex
return return f.args[1]
end
function _F_nonlinear_operator(model::Optimizer)
x = MOI.get(model, MOI.ListOfVariableIndices())
f_map = Vector{MOI.ScalarNonlinearFunction}(undef, length(x))
names = fill("", length(x))
for (FType, SType) in MOI.get(model, MOI.ListOfConstraintTypesPresent())
if SType != MOI.Complements
continue
end
for ci in MOI.get(model, MOI.ListOfConstraintIndices{FType,SType}())
f = MOI.get(model, MOI.ConstraintFunction(), ci)
s = MOI.get(model, MOI.ConstraintSet(), ci)
N = div(MOI.dimension(s), 2)
scalars = MOI.Utilities.scalarize(f)
c_name = MOI.get(model, MOI.ConstraintName(), ci)
for i in 1:N
fi, xi = _to_f(scalars[i]), _to_x(scalars[i+N])
if isassigned(f_map, xi.value)
error(
"The variable $xi appears in more than one " *
"complementarity constraint.",
)
end
f_map[xi.value] = fi
if N == 1
names[xi.value] = c_name
else
names[xi.value] = "$(c_name)[$i]"
end
end
end
end
for i in 1:length(x)
if !isassigned(f_map, i)
f_map[i] = MOI.ScalarNonlinearFunction(:+, Any[0.0])
end
end
nlp = MOI.Nonlinear.Model()
for (attr, value) in model.ext[:user_defined_functions]
MOI.Nonlinear.register_operator(nlp, attr.name, attr.arity, value...)
end
for fi in f_map
MOI.Nonlinear.add_constraint(nlp, fi, MOI.EqualTo(0.0))
end
evaluator =
MOI.Nonlinear.Evaluator(nlp, MOI.Nonlinear.SparseReverseMode(), x)
MOI.initialize(evaluator, [:Jac])
J_structure = MOI.jacobian_structure(evaluator)
forward_perm = sortperm(J_structure; by = reverse)
inverse_perm = invperm(forward_perm)
jacobian_called = false
function F(::Cint, x::Vector{Cdouble}, f::Vector{Cdouble})
MOI.eval_constraint(evaluator, f, x)
return Cint(0)
end
function J(
::Cint,
nnz::Cint,
x::Vector{Cdouble},
col::Vector{Cint},
len::Vector{Cint},
row::Vector{Cint},
data::Vector{Cdouble},
)
if !jacobian_called
k = 1
last_col = 0
# We need to zero all entries up front in case some rows do not
# appear in the Jacobian.
len .= Cint(0)
for p in forward_perm
r, c = J_structure[p]
if c != last_col
col[c], last_col = k, c
end
len[c] += 1
row[k] = r
k += 1
end
jacobian_called = true
# Seems like a potential bug in PATH. If the Jacobian is empty, PATH
# still passes `nnz = 1`.
@assert (nnz == k - 1) || (nnz == k == 1)
end
MOI.eval_constraint_jacobian(evaluator, view(data, inverse_perm), x)
return Cint(0)
end
return F, J, length(J_structure), names
end
_finite(x, y) = isfinite(x) ? x : y
function _bounds_and_starting(model::Optimizer)
x = MOI.get(model, MOI.ListOfVariableIndices())
lower = fill(-INFINITY, length(x))
upper = fill(INFINITY, length(x))
initial = fill(0.0, length(x))
for (i, xi) in enumerate(x)
l, u = MOI.Utilities.get_bounds(model, Float64, xi)
z = MOI.get(model, MOI.VariablePrimalStart(), xi)
lower[i] = l
upper[i] = u
initial[i] = something(z, _finite(l, _finite(u, 0.0)))
end
names = MOI.get.(model, MOI.VariableName(), x)
return lower, upper, initial, names
end
# MOI.optimize!
struct Solution
status::MCP_Termination
x::Vector{Float64}
info::Information
end
function solution(model::Optimizer)
return get(model.ext, :solution, nothing)::Union{Nothing,Solution}
end
function MOI.optimize!(model::Optimizer)
con_types = MOI.get(model, MOI.ListOfConstraintTypesPresent())
is_nlp =
(MOI.VectorNonlinearFunction, MOI.Complements) in con_types ||
(MOI.VectorQuadraticFunction{Float64}, MOI.Complements) in con_types
F, J, nnz, c_names = if is_nlp
_F_nonlinear_operator(model)
else
_F_linear_operator(model)
end
model.ext[:solution] = nothing
lower, upper, initial, names = _bounds_and_starting(model)
status, x, info = solve_mcp(
F,
J,
lower,
upper,
initial;
nnz = nnz,
silent = model.ext[:silent],
jacobian_structure_constant = true,
jacobian_data_contiguous = true,
variable_names = names,
constraint_names = c_names,
[k => v for (k, v) in model.ext[:kwargs]]...,
)
if x === nothing
x = fill(NaN, length(initial))
end
if info === nothing
info = Information()
end
model.ext[:solution] = Solution(status, x, info)
return
end
const _MCP_TERMINATION_STATUS_MAP =
Dict{MCP_Termination,Tuple{MOI.TerminationStatusCode,String}}(
MCP_Solved => (MOI.LOCALLY_SOLVED, "The problem was solved"),
MCP_NoProgress => (MOI.SLOW_PROGRESS, "A stationary point was found"),
MCP_MajorIterationLimit =>
(MOI.ITERATION_LIMIT, "Major iteration limit met"),
MCP_MinorIterationLimit =>
(MOI.ITERATION_LIMIT, "Cumulative minor iterlim met"),
MCP_TimeLimit => (MOI.TIME_LIMIT, "Ran out of time"),
MCP_UserInterrupt => (MOI.INTERRUPTED, "Control-C, typically"),
MCP_BoundError => (MOI.INVALID_MODEL, "Problem has a bound error"),
MCP_DomainError =>
(MOI.NUMERICAL_ERROR, "Could not find a starting point"),
MCP_Infeasible => (MOI.INFEASIBLE, "Problem has no solution"),
MCP_Error => (MOI.OTHER_ERROR, "An error occured within the code"),
MCP_LicenseError => (MOI.OTHER_ERROR, "License could not be found"),
MCP_OK => (MOI.OTHER_ERROR, ""),
)
function MOI.get(model::Optimizer, ::MOI.TerminationStatus)
if solution(model) === nothing
return MOI.OPTIMIZE_NOT_CALLED
end
status, _ = _MCP_TERMINATION_STATUS_MAP[solution(model).status]
return status
end
function MOI.get(model::Optimizer, attr::MOI.PrimalStatus)
if solution(model) === nothing || attr.result_index != 1
return MOI.NO_SOLUTION
end
if MOI.get(model, MOI.TerminationStatus()) == MOI.LOCALLY_SOLVED
return MOI.FEASIBLE_POINT
end
return MOI.UNKNOWN_RESULT_STATUS
end
MOI.get(::Optimizer, ::MOI.DualStatus) = MOI.NO_SOLUTION
function MOI.get(model::Optimizer, ::MOI.RawStatusString)
if solution(model) === nothing
return "MOI.optimize! was not called yet"
end
_, reason = _MCP_TERMINATION_STATUS_MAP[solution(model).status]
return reason
end
function MOI.get(model::Optimizer, ::MOI.ResultCount)
return solution(model) !== nothing ? 1 : 0
end
function MOI.get(
model::Optimizer,
attr::MOI.VariablePrimal,
x::MOI.VariableIndex,
)
MOI.check_result_index_bounds(model, attr)
return solution(model).x[x.value]
end
function MOI.get(model::Optimizer, ::MOI.SolveTimeSec)
return solution(model).info.total_time
end
| PATHSolver | https://github.com/chkwon/PATHSolver.jl.git |
|
[
"MIT"
] | 1.7.8 | ced77ccd05871211833ae690698488c52eb38680 | code | 1175 | # Copyright (c) 2016 Changhyun Kwon, Oscar Dowson, and contributors
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.
module PATHSolver
import LazyArtifacts
import MathOptInterface as MOI
import SparseArrays
function _get_artifact_path(file)
root = LazyArtifacts.artifact"PATHSolver"
if Sys.iswindows() # There's a permission error with the artifact
chmod(root, 0o755; recursive = true)
end
triplet = join(split(Base.BUILD_TRIPLET, "-")[1:3], "-")
ext = ifelse(Sys.iswindows(), "dll", ifelse(Sys.isapple(), "dylib", "so"))
filename = joinpath(root, triplet, "$file.$ext")
if !isfile(filename)
error("Unsupported platform: $triplet")
end
return filename
end
function __init__()
if haskey(ENV, "PATH_JL_LOCATION")
global PATH_SOLVER = ENV["PATH_JL_LOCATION"]
global LUSOL_LIBRARY_PATH = ""
else
global PATH_SOLVER = _get_artifact_path("libpath")
global LUSOL_LIBRARY_PATH = _get_artifact_path("liblusol")
end
return
end
include("C_API.jl")
include("MOI_wrapper.jl")
end
| PATHSolver | https://github.com/chkwon/PATHSolver.jl.git |
|
[
"MIT"
] | 1.7.8 | ced77ccd05871211833ae690698488c52eb38680 | code | 7415 | # Copyright (c) 2016 Changhyun Kwon, Oscar Dowson, and contributors
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.
module TestCAPI
using Test
import PATHSolver
import SparseArrays
function runtests()
for name in names(@__MODULE__; all = true)
if startswith("$(name)", "test_")
@testset "$(name)" begin
getfield(@__MODULE__, name)()
end
end
end
return
end
function _check_info_sanity(info)
@test info.residual < 1e-5
@test iszero(info.restarts)
@test info.function_evaluations > 0
return
end
function test_License_SetString()
@test PATHSolver.c_api_License_SetString("bad_license") != 0
return
end
function test_CheckLicense()
out_io = IOBuffer()
output_data = PATHSolver.OutputData(out_io)
output_interface = PATHSolver.OutputInterface(output_data)
GC.@preserve output_data output_interface begin
# The output_interface needs to be set before calling CheckLicense
PATHSolver.c_api_Output_SetInterface(output_interface)
@test PATHSolver.c_api_Path_CheckLicense(1, 1) == 1
@test PATHSolver.c_api_Path_CheckLicense(1_000, 1_000) == 0
end
n = 1_000
M = zeros(n, n)
for i in 1:n
M[i, i] = 1.0
end
ret = PATHSolver.solve_mcp(
SparseArrays.SparseMatrixCSC{Float64,Int32}(M),
ones(n), # q
zeros(n), # lb
ones(n), # ub
ones(n), # z
)
@test ret == (PATHSolver.MCP_LicenseError, nothing, nothing)
return
end
function test_PathVersion()
s = PATHSolver.c_api_Path_Version()
@test match(r"Path [0-9]\.[0-9]\.[0-9][0-9]", s) !== nothing
return
end
function test_Example()
M = convert(
SparseArrays.SparseMatrixCSC{Cdouble,Cint},
SparseArrays.sparse([
0 0 -1 -1
0 0 1 -2
1 -1 2 -2
1 2 -2 4
]),
)
status, z, info = PATHSolver.solve_mcp(
M,
Float64[2, 2, -2, -6],
fill(0.0, 4),
fill(10.0, 4),
[0.0, 0.0, 0.0, 0.0];
output = "yes",
)
@test status == PATHSolver.MCP_Solved
@test isapprox(z, [2.8, 0.0, 0.8, 1.2])
_check_info_sanity(info)
return
end
function test_M_not_square()
M = convert(
SparseArrays.SparseMatrixCSC{Cdouble,Cint},
SparseArrays.sparse([
1 -1 2 -2
1 2 -2 4
]),
)
err = ErrorException("M not square! size = $(size(M))")
@test_throws err PATHSolver.solve_mcp(
M,
Float64[2, 2],
fill(0.0, 4),
fill(10.0, 4),
[0.0, 0.0, 0.0, 0.0];
output = "yes",
)
return
end
function test_q_wrong_shape()
M = convert(
SparseArrays.SparseMatrixCSC{Cdouble,Cint},
SparseArrays.sparse([
0 0 -1 -1
0 0 1 -2
1 -1 2 -2
1 2 -2 4
]),
)
q = [2.0, 2.0]
err = ErrorException(
"q is wrong shape. Expected $(size(M, 1)), got $(length(q)).",
)
@test_throws err PATHSolver.solve_mcp(
M,
q,
fill(0.0, 4),
fill(10.0, 4),
[0.0, 0.0, 0.0, 0.0];
output = "yes",
)
return
end
function test_Example_LUSOL()
M = convert(
SparseArrays.SparseMatrixCSC{Cdouble,Cint},
SparseArrays.sparse([
0 0 -1 -1
0 0 1 -2
1 -1 2 -2
1 2 -2 4
]),
)
status, z, info = PATHSolver.solve_mcp(
M,
Float64[2, 2, -2, -6],
fill(0.0, 4),
fill(10.0, 4),
[0.0, 0.0, 0.0, 0.0];
output = "yes",
# TODO(odow): when enabled, I get segfaults :(
factorization_method = "blu_lusol",
factorization_library_name = PATHSolver.LUSOL_LIBRARY_PATH,
)
@test status == PATHSolver.MCP_Solved
@test isapprox(z, [2.8, 0.0, 0.8, 1.2])
_check_info_sanity(info)
return
end
function test_Example_II()
M = [
0 0 -1 -1
0 0 1 -2
1 -1 2 -2
1 2 -2 4
]
q = [2; 2; -2; -6]
function F(n::Cint, x::Vector{Cdouble}, f::Vector{Cdouble})
@assert n == length(x) == length(f) == 4
f[1] = -x[3]^2 - x[4] + q[1]
f[2] = x[3]^3 - 2x[4]^2 + q[2]
f[3] = x[1]^5 - x[2] + 2x[3] - 2x[4] + q[3]
f[4] = x[1] + 2x[2]^3 - 2x[3] + 4x[4] + q[4]
return Cint(0)
end
function J(
n::Cint,
nnz::Cint,
x::Vector{Cdouble},
col::Vector{Cint},
len::Vector{Cint},
row::Vector{Cint},
data::Vector{Cdouble},
)
JAC = [
0 0 -2x[3] -1
0 0 3x[3]^2 -4x[4]
5x[1]^4 -1 2 -2
1 6x[2] -2 4
]
@assert n == length(x) == length(col) == length(len) == 4
@assert nnz == length(row) == length(data)
i = 1
for c in 1:n
col[c] = i
len[c] = 0
for r in 1:n
if !iszero(JAC[r, c])
data[i] = JAC[r, c]
row[i] = r
len[c] += 1
i += 1
end
end
end
@test sum(len) == nnz
return Cint(0)
end
status, z, info = PATHSolver.solve_mcp(
F,
J,
fill(0.0, 4),
fill(10.0, 4),
[1.0, 1.0, 1.0, 1.0];
output = "yes",
nnz = 12,
)
@test status == PATHSolver.MCP_Solved
@test isapprox(z, [1.28475, 0.972916, 0.909376, 1.17304], atol = 1e-4)
_check_info_sanity(info)
return
end
function test_Name()
M = convert(
SparseArrays.SparseMatrixCSC{Cdouble,Cint},
SparseArrays.sparse([
0 0 -1 -1
0 0 1 -2
1 -1 2 -2
1 2 -2 4
]),
)
z0 = [-10.0, 10.0, -5.0, 5.0]
status, z, info = PATHSolver.solve_mcp(
M,
Float64[2, 2, -2, -6],
fill(0.0, 4),
fill(10.0, 4),
z0;
variable_names = ["x1", "x2", "x3", "x4"],
constraint_names = ["F1", "F2", "F3", "F4"],
output = "yes",
)
@test status == PATHSolver.MCP_Solved
@test isapprox(z, [2.8, 0.0, 0.8, 1.2])
_check_info_sanity(info)
status, z, info = PATHSolver.solve_mcp(
M,
Float64[2, 2, -2, -6],
fill(0.0, 4),
fill(10.0, 4),
z0;
variable_names = ["x1", "x2", "x3", "x4"],
constraint_names = [
"A2345678901234567890",
"B23456789012345678901234567",
"C234567890",
"D234567890",
],
output = "yes",
)
@test status == PATHSolver.MCP_Solved
@test isapprox(z, [2.8, 0.0, 0.8, 1.2])
_check_info_sanity(info)
status, z, info = PATHSolver.solve_mcp(
M,
Float64[2, 2, -2, -6],
fill(0.0, 4),
fill(10.0, 4),
z0;
variable_names = ["x1", "x2", "x3", "x4"],
constraint_names = [
"A2345678901234567890",
"B23456789012345678901234567",
"C🤖λ⚽️⚽️⚽️⚽️🏸⚽️⚽️⚽️⚽️🏸",
"D도레미파솔",
],
output = "yes",
)
@test status == PATHSolver.MCP_Solved
@test isapprox(z, [2.8, 0.0, 0.8, 1.2])
_check_info_sanity(info)
return
end
end
TestCAPI.runtests()
| PATHSolver | https://github.com/chkwon/PATHSolver.jl.git |
|
[
"MIT"
] | 1.7.8 | ced77ccd05871211833ae690698488c52eb38680 | code | 18623 | # Copyright (c) 2016 Changhyun Kwon, Oscar Dowson, and contributors
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.
module TestMOIWrapper
using Test
import MathOptInterface as MOI
import PATHSolver
function runtests()
for name in names(@__MODULE__; all = true)
if startswith("$(name)", "test_")
@testset "$(name)" begin
getfield(@__MODULE__, name)()
end
end
end
return
end
function test_Name()
model = PATHSolver.Optimizer()
@test MOI.get(model, MOI.SolverName()) == PATHSolver.c_api_Path_Version()
return
end
function test_AbstractOptimizer()
@test PATHSolver.Optimizer() isa MOI.AbstractOptimizer
return
end
function test_DualStatus()
@test MOI.get(PATHSolver.Optimizer(), MOI.DualStatus()) == MOI.NO_SOLUTION
return
end
function test_RawOptimizerAttribute()
model = PATHSolver.Optimizer()
@test MOI.supports(model, MOI.RawOptimizerAttribute("output"))
@test MOI.get(model, MOI.RawOptimizerAttribute("output")) === nothing
MOI.set(model, MOI.RawOptimizerAttribute("output"), "no")
@test MOI.get(model, MOI.RawOptimizerAttribute("output")) == "no"
return
end
function test_infeasible()
model = PATHSolver.Optimizer()
x = MOI.add_variable(model)
MOI.add_constraint(model, x, MOI.Interval(0.0, -1.0))
MOI.optimize!(model)
@test MOI.get(model, MOI.TerminationStatus()) == MOI.INVALID_MODEL
@test MOI.get(model, MOI.RawStatusString()) == "Problem has a bound error"
@test MOI.get(model, MOI.PrimalStatus()) == MOI.UNKNOWN_RESULT_STATUS
return
end
function test_ZeroOne()
model = PATHSolver.Optimizer()
x = MOI.add_variable(model)
@test !MOI.supports_constraint(model, MOI.VariableIndex, MOI.ZeroOne)
return
end
function test_wrong_dimension()
model = PATHSolver.Optimizer()
x = MOI.add_variable(model)
MOI.add_constraint(
model,
MOI.VectorAffineFunction(MOI.VectorAffineTerm{Float64}[], [0.0]),
MOI.Complements(2),
)
@test_throws(
ErrorException(
"Dimension of constant vector 1 does not match the required dimension of " *
"the complementarity set 2.",
),
MOI.optimize!(model)
)
return
end
function test_nonzero_variable_offset()
model = PATHSolver.Optimizer()
x = MOI.add_variable(model)
MOI.add_constraint(
model,
MOI.VectorAffineFunction(
[
MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(1.0, x)),
MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(1.0, x)),
],
[0.0, 1.0],
),
MOI.Complements(2),
)
@test_throws(
ErrorException(
"VectorAffineFunction malformed: a constant associated with a " *
"complemented variable is not zero: [1.0].",
),
MOI.optimize!(model)
)
return
end
function test_output_dimension_too_large()
model = PATHSolver.Optimizer()
x = MOI.add_variable(model)
MOI.add_constraint(
model,
MOI.VectorAffineFunction(
[
MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(1.0, x)),
MOI.VectorAffineTerm(3, MOI.ScalarAffineTerm(1.0, x)),
],
[0.0, 0.0],
),
MOI.Complements(2),
)
@test_throws(
ErrorException(
"VectorAffineFunction malformed: output_index 3 is too large.",
),
MOI.optimize!(model)
)
return
end
function test_missing_complement_variable()
model = PATHSolver.Optimizer()
x = MOI.add_variable(model)
MOI.add_constraint(
model,
MOI.VectorAffineFunction(
[MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(1.0, x))],
[0.0, 0.0],
),
MOI.Complements(2),
)
@test_throws(
ErrorException(
"VectorAffineFunction malformed: expected variable in row 2.",
),
MOI.optimize!(model)
)
return
end
function test_malformed_complement_variable()
model = PATHSolver.Optimizer()
x = MOI.add_variable(model)
MOI.add_constraint(
model,
MOI.VectorAffineFunction(
[
MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(1.0, x)),
MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(2.0, x)),
],
[0.0, 0.0],
),
MOI.Complements(2),
)
@test_throws(
ErrorException(
"VectorAffineFunction malformed: variable $(x) has a coefficient that is " *
"not 1 in row 2 of the VectorAffineFunction.",
),
MOI.optimize!(model)
)
return
end
function test_variable_in_multiple_constraints()
model = PATHSolver.Optimizer()
x = MOI.add_variable(model)
MOI.add_constraint(
model,
MOI.VectorAffineFunction(
[
MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(1.0, x)),
MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(1.0, x)),
MOI.VectorAffineTerm(3, MOI.ScalarAffineTerm(1.0, x)),
MOI.VectorAffineTerm(4, MOI.ScalarAffineTerm(1.0, x)),
],
[0.0, 0.0, 0.0, 0.0],
),
MOI.Complements(4),
)
@test_throws(
ErrorException(
"The variable $(x) appears in more than one complementarity constraint.",
),
MOI.optimize!(model)
)
return
end
function test_variable_primal_start()
model = PATHSolver.Optimizer()
x = MOI.add_variable(model)
@test MOI.supports(model, MOI.VariablePrimalStart(), MOI.VariableIndex)
@test MOI.get(model, MOI.VariablePrimalStart(), x) === nothing
MOI.set(model, MOI.VariablePrimalStart(), x, 1.0)
@test MOI.get(model, MOI.VariablePrimalStart(), x) === 1.0
MOI.set(model, MOI.VariablePrimalStart(), x, nothing)
@test MOI.get(model, MOI.VariablePrimalStart(), x) === nothing
return
end
function _test_Example_I(use_primal_start::Bool)
model = PATHSolver.Optimizer()
MOI.set(model, MOI.RawOptimizerAttribute("time_limit"), 60)
@test MOI.supports(model, MOI.Silent()) == true
@test MOI.get(model, MOI.Silent()) == false
MOI.set(model, MOI.Silent(), true)
@test MOI.get(model, MOI.Silent()) == true
x = MOI.add_variables(model, 4)
@test MOI.supports(model, MOI.VariablePrimalStart(), MOI.VariableIndex)
@test MOI.get(model, MOI.VariablePrimalStart(), x[1]) === nothing
MOI.add_constraint.(model, x, MOI.Interval(0.0, 10.0))
if use_primal_start
MOI.set.(model, MOI.VariablePrimalStart(), x, 0.0)
end
M = Float64[
0 0 -1 -1
0 0 1 -2
1 -1 2 -2
1 2 -2 4
]
q = [2; 2; -2; -6]
for i in 1:4
terms = [MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(1.0, x[i]))]
for j in 1:4
iszero(M[i, j]) && continue
push!(
terms,
MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(M[i, j], x[j])),
)
end
MOI.add_constraint(
model,
MOI.VectorAffineFunction(terms, [q[i], 0.0]),
MOI.Complements(2),
)
end
@test MOI.get(model, MOI.TerminationStatus()) == MOI.OPTIMIZE_NOT_CALLED
@test MOI.get(model, MOI.PrimalStatus()) == MOI.NO_SOLUTION
@test MOI.get(model, MOI.RawStatusString()) ==
"MOI.optimize! was not called yet"
MOI.optimize!(model)
@test MOI.get(model, MOI.TerminationStatus()) == MOI.LOCALLY_SOLVED
@test MOI.get(model, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT
@test MOI.get(model, MOI.RawStatusString()) == "The problem was solved"
x_val = MOI.get.(model, MOI.VariablePrimal(), x)
@test isapprox(x_val, [2.8, 0.0, 0.8, 1.2])
@test 0 <= MOI.get(model, MOI.SolveTimeSec()) < 1
return
end
test_Example_I() = _test_Example_I(true)
test_Example_I_no_start() = _test_Example_I(false)
# An implementation of the GAMS model transmcp.gms: transporation model
# as an equilibrium problem.
#
# https://www.gams.com/latest/gamslib_ml/libhtml/gamslib_transmcp.html
#
# Transportation model as equilibrium problem (TRANSMCP,SEQ=126)
#
# Dantzig's original transportation model (TRNSPORT) is
# reformulated as a linear complementarity problem. We first
# solve the model with fixed demand and supply quantities, and
# then we incorporate price-responsiveness on both sides of the
# market.
#
# Dantzig, G B, Chapter 3.3. In Linear Programming and Extensions.
# Princeton University Press, Princeton, New Jersey, 1963.
function test_transmcp()
plants = ["seattle", "san-diego"]
P = length(plants)
capacity = Dict("seattle" => 350, "san-diego" => 600)
markets = ["new-york", "chicago", "topeka"]
M = length(markets)
demand = Dict("new-york" => 325, "chicago" => 300, "topeka" => 275)
distance = Dict(
("seattle" => "new-york") => 2.5,
("seattle" => "chicago") => 1.7,
("seattle" => "topeka") => 1.8,
("san-diego" => "new-york") => 2.5,
("san-diego" => "chicago") => 1.8,
("san-diego" => "topeka") => 1.4,
)
model = PATHSolver.Optimizer()
MOI.set(model, MOI.Silent(), true)
# w[i in plants] >= 0
w = MOI.add_variables(model, P)
MOI.add_constraint.(model, w, MOI.GreaterThan(0.0))
# p[j in markets] >= 0
p = MOI.add_variables(model, M)
MOI.add_constraint.(model, p, MOI.GreaterThan(0.0))
# x[i in plants, j in markets] >= 0
x = reshape(MOI.add_variables(model, P * M), P, M)
MOI.add_constraint.(model, x, MOI.GreaterThan(0.0))
# w[i] + 90 * distance[i => j] / 1000 - p[j] ⟂ x[i, j]
for (i, plant) in enumerate(plants), (j, market) in enumerate(markets)
MOI.add_constraint(
model,
MOI.VectorAffineFunction(
[
MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(1.0, w[i])),
MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(-1.0, p[j])),
MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(1.0, x[i, j])),
],
[90 * distance[plant=>market] / 1000, 0.0],
),
MOI.Complements(2),
)
end
# capacity[i] - sum(x[i, :]) ⟂ w[i]
terms = MOI.VectorAffineTerm{Float64}[]
for (i, plant) in enumerate(plants)
for j in 1:M
push!(
terms,
MOI.VectorAffineTerm(i, MOI.ScalarAffineTerm(-1.0, x[i, j])),
)
end
push!(
terms,
MOI.VectorAffineTerm(P + i, MOI.ScalarAffineTerm(1.0, w[i])),
)
end
q = vcat([capacity[p] for p in plants], zeros(P))
MOI.add_constraint(
model,
MOI.VectorAffineFunction(terms, q),
MOI.Complements(2 * P),
)
# sum(x[:, j]) - demand[j] ⟂ p[j]
terms = MOI.VectorAffineTerm{Float64}[]
for (j, market) in enumerate(markets)
for i in 1:P
push!(
terms,
MOI.VectorAffineTerm(j, MOI.ScalarAffineTerm(1.0, x[i, j])),
)
end
push!(
terms,
MOI.VectorAffineTerm(M + j, MOI.ScalarAffineTerm(1.0, p[j])),
)
end
q = vcat([-demand[m] for m in markets], zeros(M))
MOI.add_constraint(
model,
MOI.VectorAffineFunction(terms, q),
MOI.Complements(2 * M),
)
MOI.optimize!(model)
@test isapprox(
MOI.get.(model, MOI.VariablePrimal(), p),
[0.225, 0.153, 0.126],
atol = 1e-3,
)
return
end
function test_supports()
model = PATHSolver.Optimizer()
F = MOI.VariableIndex
@test !MOI.supports(model, MOI.ObjectiveFunction{F}())
@test MOI.supports_constraint(model, F, MOI.GreaterThan{Float64})
return
end
function test_VectorOfVariables_nonlinear_operator()
model = PATHSolver.Optimizer()
MOI.Utilities.loadfromstring!(
model,
"""
variables: x, y, z
VectorNonlinearFunction([0, z]) in Complements(2)
[y, x] in Complements(2)
x in GreaterThan(0.0)
y in GreaterThan(0.0)
""",
)
x = MOI.get(model, MOI.ListOfVariableIndices())
MOI.set.(model, MOI.VariablePrimalStart(), x, 1.0)
MOI.optimize!(model)
y = MOI.get.(model, MOI.VariablePrimal(), x)
@test abs(y[1] * y[2]) <= 1e-8
return
end
function test_VectorQuadraticFunction_VectorNonlinearFunction()
model = PATHSolver.Optimizer()
MOI.Utilities.loadfromstring!(
model,
"""
variables: v, w, x, y, z
VectorNonlinearFunction([0, v]) in Complements(2)
[-1.0 * y * y + -1.0 * z + 2, w] in Complements(2)
VectorNonlinearFunction([ScalarNonlinearFunction(y^3 - 2z^2 + 2), ScalarNonlinearFunction(w^5 - x + 2y - 2z - 2), x, y]) in Complements(4)
VectorNonlinearFunction([ScalarNonlinearFunction(w + 2x^3 - 2y + 4z - 6), z]) in Complements(2)
v in EqualTo(1.0)
w in Interval(0.0, 10.0)
x in GreaterThan(0.0)
z in Interval(1.0, 2.0)
""",
)
x = MOI.get(model, MOI.ListOfVariableIndices())
MOI.set.(model, MOI.VariablePrimalStart(), x, 1.0)
MOI.optimize!(model)
@test ≈(
MOI.get.(model, MOI.VariablePrimal(), x),
[1.0, 1.2847523, 0.9729164, 0.9093761, 1.1730350];
atol = 1e-6,
)
return
end
function test_nonlinear_duplicate_rows()
model = PATHSolver.Optimizer()
MOI.Utilities.loadfromstring!(
model,
"""
variables: x
VectorNonlinearFunction([0.0, x]) in Complements(2)
VectorNonlinearFunction([0.0, x]) in Complements(2)
""",
)
@test_throws(
ErrorException(
"The variable $(MOI.VariableIndex(1)) appears in more than one " *
"complementarity constraint.",
),
MOI.optimize!(model),
)
return
end
function test_missing_rows()
model = PATHSolver.Optimizer()
MOI.Utilities.loadfromstring!(
model,
"""
variables: x, y
VectorNonlinearFunction([0.0, x]) in Complements(2)
""",
)
MOI.optimize!(model)
@test MOI.get(model, MOI.TerminationStatus()) == MOI.LOCALLY_SOLVED
return
end
function test_user_defined_function()
f(x...) = (1 - x[1])
function ∇f(g, x...)
g[1] = -1
return
end
model = MOI.instantiate(PATHSolver.Optimizer)
MOI.set(model, MOI.Silent(), true)
x = MOI.add_variables(model, 2)
MOI.add_constraint.(model, x, MOI.GreaterThan(0.0))
@test MOI.supports(model, MOI.UserDefinedFunction(:op_f, 2))
MOI.set(model, MOI.UserDefinedFunction(:op_f, 2), (f, ∇f))
@test MOI.get(model, MOI.UserDefinedFunction(:op_f, 2)) == (f, ∇f)
MOI.add_constraint(
model,
MOI.VectorNonlinearFunction([
MOI.ScalarNonlinearFunction(:op_f, Any[x...]),
MOI.ScalarNonlinearFunction(:+, Any[x[1]]),
]),
MOI.Complements(2),
)
MOI.add_constraint(
model,
MOI.Utilities.operate(vcat, Float64, 1.0 - x[2], x[2]),
MOI.Complements(2),
)
MOI.optimize!(model)
sol = MOI.get(model, MOI.VariablePrimal(), x)
@test all(abs.(sol .* (1 .- sol)) .< 1e-4)
return
end
function test_empty_model()
model = PATHSolver.Optimizer()
MOI.optimize!(model)
@test MOI.get(model, MOI.TerminationStatus()) == MOI.LOCALLY_SOLVED
return
end
function test_solve_with_names()
model = PATHSolver.Optimizer()
MOI.set(model, MOI.RawOptimizerAttribute("output_linear_model"), "yes")
MOI.Utilities.loadfromstring!(
model,
"""
variables: v, w, x, y, z
c2: [0.0, -1.0 * y * y + -1.0 * z + 2, v, w] in Complements(4)
c3: VectorNonlinearFunction([ScalarNonlinearFunction(y^3 - 2z^2 + 2), ScalarNonlinearFunction(w^5 - x + 2y - 2z - 2), x, y]) in Complements(4)
c4: VectorNonlinearFunction([ScalarNonlinearFunction(w + 2x^3 - 2y + 4z - 6), z]) in Complements(2)
v in EqualTo(1.0)
w in Interval(0.0, 10.0)
x in GreaterThan(0.0)
z in Interval(1.0, 2.0)
""",
)
x = MOI.get(model, MOI.ListOfVariableIndices())
MOI.set.(model, MOI.VariablePrimalStart(), x, 1.0)
MOI.optimize!(model)
@test ≈(
MOI.get.(model, MOI.VariablePrimal(), x),
[1.0, 1.2847523, 0.9729164, 0.9093761, 1.1730350];
atol = 1e-6,
)
return
end
function test_solve_with_names_nonlinear()
model = PATHSolver.Optimizer()
MOI.set(model, MOI.RawOptimizerAttribute("output_linear_model"), "yes")
MOI.Utilities.loadfromstring!(
model,
"""
variables: v, w, x, y, z
cnl2: VectorNonlinearFunction([0.0, -1.0 * y * y + -1.0 * z + 2, v, w]) in Complements(4)
c3: VectorNonlinearFunction([ScalarNonlinearFunction(y^3 - 2z^2 + 2), ScalarNonlinearFunction(w^5 - x + 2y - 2z - 2), x, y]) in Complements(4)
c4: VectorNonlinearFunction([ScalarNonlinearFunction(w + 2x^3 - 2y + 4z - 6), z]) in Complements(2)
v in EqualTo(1.0)
w in Interval(0.0, 10.0)
x in GreaterThan(0.0)
z in Interval(1.0, 2.0)
""",
)
x = MOI.get(model, MOI.ListOfVariableIndices())
MOI.set.(model, MOI.VariablePrimalStart(), x, 1.0)
MOI.optimize!(model)
@test ≈(
MOI.get.(model, MOI.VariablePrimal(), x),
[1.0, 1.2847523, 0.9729164, 0.9093761, 1.1730350];
atol = 1e-6,
)
return
end
function test_nonlinear_blank_row()
model = PATHSolver.Optimizer()
MOI.Utilities.loadfromstring!(
model,
"""
variables: a, x
[1.0 * x * x + 2.0 * x + -1.0, x] in Complements(2)
a in GreaterThan(0.0)
x in GreaterThan(0.0)
""",
)
x = MOI.get(model, MOI.ListOfVariableIndices())
MOI.optimize!(model)
@test ≈(
MOI.get.(model, MOI.VariablePrimal(), x),
[0.0, -1 + sqrt(2)];
atol = 1e-6,
)
return
end
function test_linear_blank_row()
model = PATHSolver.Optimizer()
MOI.Utilities.loadfromstring!(
model,
"""
variables: a, x
c: [2.0 * x + -1.0, x] in Complements(2)
a in GreaterThan(0.0)
x in GreaterThan(0.0)
""",
)
x = MOI.get(model, MOI.ListOfVariableIndices())
MOI.optimize!(model)
@test ≈(MOI.get.(model, MOI.VariablePrimal(), x), [0.0, 0.5]; atol = 1e-6)
return
end
end
TestMOIWrapper.runtests()
| PATHSolver | https://github.com/chkwon/PATHSolver.jl.git |
|
[
"MIT"
] | 1.7.8 | ced77ccd05871211833ae690698488c52eb38680 | code | 389 | # Copyright (c) 2016 Changhyun Kwon, Oscar Dowson, and contributors
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.
using Test
@testset "PATH" begin
@testset "$(file)" for file in ["C_API.jl", "MOI_wrapper.jl"]
println("Running: $(file)")
include(file)
end
end
| PATHSolver | https://github.com/chkwon/PATHSolver.jl.git |
|
[
"MIT"
] | 1.7.8 | ced77ccd05871211833ae690698488c52eb38680 | docs | 9170 | # PATHSolver.jl
[](https://github.com/chkwon/PATHSolver.jl/actions?query=workflow%3ACI)
[](https://codecov.io/gh/chkwon/PATHSolver.jl)
[PATHSolver.jl](https://github.com/chkwon/PATHSolver.jl) is a wrapper for the
[PATH solver](http://pages.cs.wisc.edu/~ferris/path.html).
The wrapper has two components:
* a thin wrapper around the C API
* an interface to [MathOptInterface](https://github.com/jump-dev/MathOptInterface.jl)
You can solve any complementarity problem using the wrapper around the C API,
although you must manually provide the callback functions, including the
Jacobian.
The MathOptInterface wrapper is more limited, supporting only linear
complementarity problems, but it enables PATHSolver to be used with [JuMP](https://github.com/jump-dev/JuMP.jl).
## Affiliation
This wrapper is maintained by the JuMP community and is not an official wrapper
of PATH. However, we are in close contact with the PATH developers, and they
have given us permission to re-distribute the PATH binaries for automatic
installation.
## License
`PATHSolver.jl` is licensed under the [MIT License](https://github.com/chkwon/PATHSolver.jl/blob/master/LICENSE.md).
The underlying solver, [path](https://pages.cs.wisc.edu/~ferris/path.html) is
closed source and requires a license.
Without a license, the PATH Solver can solve problem instances up to with up
to 300 variables and 2000 non-zeros. For larger problems,
[this web page](http://pages.cs.wisc.edu/~ferris/path/julia/LICENSE) provides a
temporary license that is valid for a year.
You can either store the license in the `PATH_LICENSE_STRING` environment
variable, or you can use the `PATHSolver.c_api_License_SetString` function
immediately after importing the `PATHSolver` package:
```julia
import PATHSolver
PATHSolver.c_api_License_SetString("<LICENSE STRING>")
```
where `<LICENSE STRING>` is replaced by the current license string.
## Installation
Install `PATHSolver.jl` as follows:
```julia
import Pkg
Pkg.add("PATHSolver")
```
By default, `PATHSolver.jl` will download a copy of the underlying PATH solver.
To use a different version of PATH, see the Manual Installation section below.
## Use with JuMP
```julia
julia> using JuMP, PATHSolver
julia> M = [
0 0 -1 -1
0 0 1 -2
1 -1 2 -2
1 2 -2 4
]
4×4 Array{Int64,2}:
0 0 -1 -1
0 0 1 -2
1 -1 2 -2
1 2 -2 4
julia> q = [2, 2, -2, -6]
4-element Array{Int64,1}:
2
2
-2
-6
julia> model = Model(PATHSolver.Optimizer)
A JuMP Model
Feasibility problem with:
Variables: 0
Model mode: AUTOMATIC
CachingOptimizer state: EMPTY_OPTIMIZER
Solver name: Path 5.0.00
julia> set_optimizer_attribute(model, "output", "no")
julia> @variable(model, x[1:4] >= 0)
4-element Array{VariableRef,1}:
x[1]
x[2]
x[3]
x[4]
julia> @constraint(model, M * x .+ q ⟂ x)
[-x[3] - x[4] + 2, x[3] - 2 x[4] + 2, x[1] - x[2] + 2 x[3] - 2 x[4] - 2, x[1] + 2 x[2] - 2 x[3] + 4 x[4] - 6, x[1], x[2], x[3], x[4]] ∈ MOI.Complements(4)
julia> optimize!(model)
Reading options file /var/folders/bg/dzq_hhvx1dxgy6gb5510pxj80000gn/T/tmpiSsCRO
Read of options file complete.
Path 5.0.00 (Mon Aug 19 10:57:18 2019)
Written by Todd Munson, Steven Dirkse, Youngdae Kim, and Michael Ferris
julia> value.(x)
4-element Array{Float64,1}:
2.8
0.0
0.7999999999999998
1.2
julia> termination_status(model)
LOCALLY_SOLVED::TerminationStatusCode = 4
```
Note that options are set using `JuMP.set_optimizer_attribute`.
The list of options supported by PATH can be found here: https://pages.cs.wisc.edu/~ferris/path/options.pdf
## MathOptInterface API
The Path 5.0.03 optimizer supports the following constraints and attributes.
List of supported variable types:
* [`MOI.Reals`](@ref)
List of supported constraint types:
* [`MOI.VariableIndex`](@ref) in [`MOI.EqualTo{Float64}`](@ref)
* [`MOI.VariableIndex`](@ref) in [`MOI.GreaterThan{Float64}`](@ref)
* [`MOI.VariableIndex`](@ref) in [`MOI.Interval{Float64}`](@ref)
* [`MOI.VariableIndex`](@ref) in [`MOI.LessThan{Float64}`](@ref)
* [`MOI.VectorOfVariables`](@ref) in [`MOI.Complements`](@ref)
* [`MOI.VectorAffineFunction{Float64}`](@ref) in [`MOI.Complements`](@ref)
* [`MOI.VectorQuadraticFunction{Float64}`](@ref) in [`MOI.Complements`](@ref)
* [`MOI.VectorNonlinearFunction`](@ref) in [`MOI.Complements`](@ref)
List of supported model attributes:
* [`MOI.Name()`](@ref)
## Use with the C API
`PATHSolver.jl` wraps the PATH C API using `PATHSolver.c_api_XXX` for the C
method `XXX`. However, using the C API directly from Julia can be challenging,
particularly with respect to avoiding issues with Julia's garbage collector.
Instead, we recommend that you use the `PATHSolver.solve_mcp` function, which
wrappers the C API into a single call. See the docstring of `PATHSolver.solve_mcp`
for a detailed description of the arguments.
Here is the same example using `PATHSolver.solve_mcp`. Note that you must
manually construct the sparse Jacobian callback.
```julia
julia> import PATHSolver
julia> M = [
0 0 -1 -1
0 0 1 -2
1 -1 2 -2
1 2 -2 4
]
4×4 Matrix{Int64}:
0 0 -1 -1
0 0 1 -2
1 -1 2 -2
1 2 -2 4
julia> q = [2, 2, -2, -6]
4-element Vector{Int64}:
2
2
-2
-6
julia> function F(n::Cint, x::Vector{Cdouble}, f::Vector{Cdouble})
@assert n == length(x) == length(f)
f .= M * x .+ q
return Cint(0)
end
F (generic function with 1 method)
julia> function J(
n::Cint,
nnz::Cint,
x::Vector{Cdouble},
col::Vector{Cint},
len::Vector{Cint},
row::Vector{Cint},
data::Vector{Cdouble},
)
@assert n == length(x) == length(col) == length(len) == 4
@assert nnz == length(row) == length(data)
i = 1
for c in 1:n
col[c], len[c] = i, 0
for r in 1:n
if !iszero(M[r, c])
row[i], data[i] = r, M[r, c]
len[c] += 1
i += 1
end
end
end
return Cint(0)
end
J (generic function with 1 method)
julia> status, z, info = PATHSolver.solve_mcp(
F,
J,
fill(0.0, 4), # Lower bounds
fill(Inf, 4), # Upper bounds
fill(0.0, 4); # Starting point
nnz = 12, # Number of nonzeros in the Jacobian
output = "yes",
)
Reading options file /var/folders/bg/dzq_hhvx1dxgy6gb5510pxj80000gn/T/jl_iftYBS
> output yes
Read of options file complete.
Path 5.0.03 (Fri Jun 26 09:58:07 2020)
Written by Todd Munson, Steven Dirkse, Youngdae Kim, and Michael Ferris
Crash Log
major func diff size residual step prox (label)
0 0 1.2649e+01 0.0e+00 (f[ 4])
1 2 4 2 1.0535e+01 8.0e-01 0.0e+00 (f[ 1])
2 3 2 4 8.4815e-01 1.0e+00 0.0e+00 (f[ 4])
3 4 0 3 4.4409e-16 1.0e+00 0.0e+00 (f[ 3])
pn_search terminated: no basis change.
Major Iteration Log
major minor func grad residual step type prox inorm (label)
0 0 5 4 4.4409e-16 I 0.0e+00 4.4e-16 (f[ 3])
Major Iterations. . . . 0
Minor Iterations. . . . 0
Restarts. . . . . . . . 0
Crash Iterations. . . . 3
Gradient Steps. . . . . 0
Function Evaluations. . 5
Gradient Evaluations. . 4
Basis Time. . . . . . . 0.000016
Total Time. . . . . . . 0.044383
Residual. . . . . . . . 4.440892e-16
(PATHSolver.MCP_Solved, [2.8, 0.0, 0.8, 1.2], PATHSolver.Information(4.4408920985006247e-16, 0.0, 0.0, 0.044383, 1.6e-5, 0.0, 0, 0, 3, 5, 4, 0, 0, 0, 0, false, false, false, true, false, false, false))
julia> status
MCP_Solved::MCP_Termination = 1
julia> z
4-element Vector{Float64}:
2.8
0.0
0.8
1.2
```
## Thread safety
PATH is not thread-safe and there are no known work-arounds. Do not run it in
parallel using `Threads.@threads`. See
[issue #62](https://github.com/chkwon/PATHSolver.jl/issues/62) for more details.
## Factorization methods
By default, `PATHSolver.jl` will download the [LUSOL](https://web.stanford.edu/group/SOL/software/lusol/)
shared library. To use LUSOL, set the following options:
```julia
model = Model(PATHSolver.Optimizer)
set_optimizer_attribute(model, "factorization_method", "blu_lusol")
set_optimizer_attribute(model, "factorization_library_name", PATHSolver.LUSOL_LIBRARY_PATH)
```
To use `factorization_method umfpack` you will need the `umfpack` shared library that
is available directly from the [developers of that code for academic use](http://faculty.cse.tamu.edu/davis/suitesparse.html).
## Manual installation
By default `PATHSolver.jl` will download a copy of the `libpath` library. If you
already have one installed and want to use that, set the `PATH_JL_LOCATION`
environment variable to point to the `libpath50.xx` library.
| PATHSolver | https://github.com/chkwon/PATHSolver.jl.git |
|
[
"MIT"
] | 0.1.2 | 47a08b35777450039eaa8e971e1278369931b431 | code | 1250 | using LibIIO
using LibIIO.CLibIIO
using Documenter
makedocs(;
modules=[LibIIO],
authors="Oliver Kliebisch <[email protected]> and contributors",
repo="https://github.com/tachawkes/LibIIO.jl/blob/{commit}{path}#{line}",
sitename="LibIIO.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
edit_link="main",
assets=String[],
),
pages=[
"Introduction" => "index.md",
"Examples" => [
"IIO Demo" => "iio_demo.md"
],
"High-level libiio bindings" => [
"Context" => "context.md",
"Devices" => "device.md",
"Channel" => "channel.md",
"Buffer" => "buffer.md",
],
"Low-level libiio access (for advanced users)" => [
"Overview" => "cindex.md",
"Functions for scanning available contexts" => "cscan.md",
"Top-level functions" => "ctoplevel.md",
"Context" => "ccontext.md",
"Device" => "cdevice.md",
"Channel" => "cchannel.md",
"Buffer" => "cbuffer.md",
"Debug" => "cdebug.md"
]
],
)
deploydocs(;
repo="github.com/TacHawkes/LibIIO.jl.gi",
devbranch="main",
)
| LibIIO | https://github.com/TacHawkes/LibIIO.jl.git |
|
[
"MIT"
] | 0.1.2 | 47a08b35777450039eaa8e971e1278369931b431 | code | 1514 | #=
This examples assumes that the IIO Demo application is installed on a linux host.
Find details here: https://wiki.analog.com/resources/eval/user-guides/iio_demo/no-os-setup
A simple signal is sent to the virtual DAC device which is looped back into the virtual ADC.
This shows how to use buffers for high-speed data transfer.
=#
using LibIIO
# Adjust to your settings
uri = "ip:192.168.64.2"
# create context
ctx = Context(uri)
# get both device handles by their name
dac = find_device(ctx, "dac_demo")
adc = find_device(ctx, "adc_demo")
# get both channels (adc/dac)
dac_chn = find_channel(dac, "dac_out_ch0", true)
adc_chn = find_channel(adc, "adc_in_ch0")
# enable the channels
enabled!(dac_chn, true)
enabled!(adc_chn, true)
# create DAC buffer with 400 samples
dac_buf = Buffer(dac, 400)
# create the ADC buffer for reading
adc_buf = Buffer(adc, 400)
# dummy signal to feed into the DAC and read back using the ADC
y = round.(Int16, 10000*sin.(2π*1/200*(1:400)))
# write the test signal into the buffer
write(dac_buf, y)
# push the buffer to the hardware
push(dac_buf)
# Read samples from the ADC hardware into the buffer
refill(adc_buf)
# Retrieve the samples from the buffer
data = read(adc_buf)
# Reinterpret as Int16, the actual sample format
d2 = reinterpret(Int16, data)
# Verify that the read signal matches the original signal
if all(d2 .== y)
@info "Loopback successful"
else
@error "Loopback failed"
end
##
atr = attrs(adc_chn)["adc_channel_attr"]
ret, v = read(atr)
| LibIIO | https://github.com/TacHawkes/LibIIO.jl.git |
|
[
"MIT"
] | 0.1.2 | 47a08b35777450039eaa8e971e1278369931b431 | code | 661 | module LibIIO
include("clib/CLibIIO.jl")
using .CLibIIO
import Base: read, write, show
const ENOENT = -34
include("types.jl")
include("alias.jl")
include("attrs.jl")
include("channel.jl")
include("buffer.jl")
include("device.jl")
include("context.jl")
export Context,
LocalContext,
XMLContext,
NetworkContext,
Buffer,
Device,
Channel,
Trigger,
name,
id,
label,
attrs,
buffer_attrs,
debug_attrs,
description,
xml,
find_channel,
find_device,
devices,
channels,
enabled,
enabled!,
push,
refill
end
| LibIIO | https://github.com/TacHawkes/LibIIO.jl.git |
|
[
"MIT"
] | 0.1.2 | 47a08b35777450039eaa8e971e1278369931b431 | code | 4037 | #=
Aliases matching the Python bindings
=#
const _get_backends_count = iio_get_backends_count
const _get_backend = iio_get_backend
const _create_scan_context = iio_create_scan_context
const _destroy_scan_context = iio_scan_context_destroy
const _has_backend = iio_has_backend
const _get_context_info_list = iio_scan_context_get_info_list
const _context_info_list_free = iio_context_info_list_free
const _context_info_get_description = iio_context_info_get_description
const _context_info_get_uri = iio_context_info_get_uri
const _new_local = iio_create_local_context
const _new_xml = iio_create_xml_context
const _new_network = iio_create_network_context
const _new_default = iio_create_default_context
const _new_uri = iio_create_context_from_uri
const _destroy = iio_context_destroy
const _get_name = iio_context_get_name
const _get_description = iio_context_get_description
const _get_xml = iio_context_get_xml
const _get_library_version = iio_library_get_version
const _get_version = iio_context_get_version
const _get_attrs_count = iio_context_get_attrs_count
const _get_attr = iio_context_get_attr
const _devices_count = iio_context_get_devices_count
const _get_device = iio_context_get_device
const _find_device = iio_context_find_device
const _set_timeout = iio_context_set_timeout
const _clone = iio_context_clone
const _d_get_id = iio_device_get_id
const _d_get_name = iio_device_get_name
const _d_get_label = iio_device_get_label
const _d_attr_count = iio_device_get_attrs_count
const _d_get_attr = iio_device_get_attr
const _d_read_attr = iio_device_attr_read
const _d_write_attr = iio_device_attr_write
const _d_debug_attr_count = iio_device_get_debug_attrs_count
const _d_get_debug_attr = iio_device_get_debug_attr
const _d_read_debug_attr = iio_device_debug_attr_read
const _d_write_debug_attr = iio_device_debug_attr_write
const _d_buffer_attr_count = iio_device_get_buffer_attrs_count
const _d_get_buffer_attr = iio_device_get_buffer_attr
const _d_read_buffer_attr = iio_device_buffer_attr_read
const _d_write_buffer_attr = iio_device_attr_write
const _d_get_context = iio_device_get_context
const _d_find_channel = iio_device_find_channel
const _d_reg_write = iio_device_reg_write
const _d_reg_read = iio_device_reg_read
const _channels_count = iio_device_get_channels_count
const _get_channel = iio_device_get_channel
const _get_sample_size = iio_device_get_sample_size
const _d_is_trigger = iio_device_is_trigger
const _d_get_trigger = iio_device_get_trigger
const _d_set_trigger = iio_device_set_trigger
const _d_set_buffers_count = iio_device_set_kernel_buffers_count
const _c_get_id = iio_channel_get_id
const _c_get_name = iio_channel_get_name
const _c_is_output = iio_channel_is_output
const _c_is_scan_element = iio_channel_is_scan_element
const _c_attr_count = iio_channel_get_attrs_count
const _c_get_attr = iio_channel_get_attr
const _c_get_filename = iio_channel_attr_get_filename
const _c_read_attr = iio_channel_attr_read
const _c_write_attr = iio_channel_attr_write
const _c_enable = iio_channel_enable
const _c_disable = iio_channel_disable
const _c_is_enabled = iio_channel_is_enabled
const _c_read = iio_channel_read
const _c_read_raw = iio_channel_read_raw
const _c_write = iio_channel_write
const _c_write_raw = iio_channel_write_raw
const _channel_get_device = iio_channel_get_device
const _channel_get_index = iio_channel_get_index
const _channel_get_data_format = iio_channel_get_data_format
const _channel_get_modifier = iio_channel_get_modifier
const _channel_get_type = iio_channel_get_type
const _create_buffer = iio_device_create_buffer
const _buffer_destroy = iio_buffer_destroy
const _buffer_refill = iio_buffer_refill
const _buffer_push_partial = iio_buffer_push_partial
const _buffer_start = iio_buffer_start
const _buffer_end = iio_buffer_end
const _buffer_cancel = iio_buffer_cancel
const _buffer_get_device = iio_buffer_get_device
const _buffer_get_poll_fd = iio_buffer_get_poll_fd
const _buffer_step = iio_buffer_step
const _buffer_set_blocking_mode = iio_buffer_set_blocking_mode
| LibIIO | https://github.com/TacHawkes/LibIIO.jl.git |
|
[
"MIT"
] | 0.1.2 | 47a08b35777450039eaa8e971e1278369931b431 | code | 940 | """
Abstract super-type for all Attributes-like types
"""
abstract type Attr end
"""
read(::Attr)
The current value of this attribute (as string).
"""
read(a::Attr) = error(typeof(a), " does not support reading")
"""
write(::Attr, value)
Sets the value of the attribute to the passed value.
"""
write(a::Attr, value) = error(typeof(a), " does not support writing")
"""
name(:Attr)
"""
name(a::Attr) = a.name
"""
filename(:Attr)
The filename in sysfs to which this attribute is bound.
"""
filename(a::Attr) = a.filename
function show(io::IO, ::MIME"text/plain", attr::Attr, tree_depth = 0, k = -1)
ret, value = read(attr)
_name = name(attr)
print(io, "\t"^tree_depth, "attr")
k >= 0 ? print(io, " $k:") : print(io, ":")
print(io, " ", _name, " ")
if ret > 0
println(io, "value: $value")
else
err_str = iio_strerror(-ret)
println(io, "ERROR: $err_str")
end
end
| LibIIO | https://github.com/TacHawkes/LibIIO.jl.git |
|
[
"MIT"
] | 0.1.2 | 47a08b35777450039eaa8e971e1278369931b431 | code | 3544 | import Base: length
"""
This class is used for all I/O operations of buffer capable devices.
"""
mutable struct Buffer{T <: AbstractDeviceOrTrigger} <: AbstractBuffer
buffer::Ptr{iio_buffer}
length::Int
samples_count::Int
dev::T
end
"""
Buffer(device::T, samples_count, cyclic::Bool = false) where {T <: AbstractDeviceOrTrigger}
Initializes a new Buffer instance.
# Parameters
- `device::AbstractDeviceOrTrigger` : A device instance (either [`Device`](@ref) or [`Trigger`](@ref) to which the buffer belongs
- `samples_count` : The size of the buffer in samples
- `cyclic` : If set to true, the buffer is circular
"""
function Buffer(device::T, samples_count,
cyclic::Bool = false) where {T <: AbstractDeviceOrTrigger}
buf = _create_buffer(device_or_trigger(device).device, convert(Csize_t, samples_count),
cyclic)
buffer = Buffer(buf,
samples_count * sample_size(device),
samples_count,
device)
# register finalizer
finalizer(buffer) do x
_buffer_destroy(x.buffer)
end
return buffer
end
"""
length(buf::Buffer)
Size of this buffer, in bytes.
"""
length(buf::Buffer) = buf.length
"""
refill(buf::Buffer)
Fetch a new set of samples from the hardware.
"""
refill(buf::Buffer) = _buffer_refill(buf.buffer)
"""
push(buf::Buffer [, samples_count])
Submit the samples contained in this buffer to the hardware.
# Parameters
- `buf::Buffer` : The buffer struct
- `samples_count` (optional) : The number of samples to submit, default = full buffer
"""
push(buf::Buffer) = _buffer_push_partial(buf.buffer, convert(Csize_t, buf.samples_count))
function push(buf::Buffer, samples_count)
_buffer_push_partial(buf.buffer, convert(Csize_t, samples_count))
end
"""
read(buf::Buffer)
Retrieves the samples contained inside the Buffer.
# Returns
- A `Vector{Cuchar}` containing the samples
"""
function read(buf::Buffer)
_start = _buffer_start(buf.buffer)
_end = _buffer_end(buf.buffer)
len = _end - _start
src = Ptr{Cuchar}(_start)
dst = Vector{Cuchar}(undef, len)
n = len * Base.aligned_sizeof(Cuchar)
unsafe_copyto!(pointer(dst), src, n)
return dst
end
"""
write(buf::Buffer, data::Vector{T}) where {T}
Copy the given vector of samples into the buffer
# Parameters
- `data` : The data vector containing the samples to copy
# Returns
- The number of bytes written into the buffer
"""
function write(buf::Buffer, data::Vector{T}) where {T}
_data = reinterpret(Cuchar, data)
_start = _buffer_start(buf.buffer)
_end = _buffer_end(buf.buffer)
len = _end - _start
(len > length(_data)) && (len = length(_data))
n = len * Base.aligned_sizeof(Cuchar)
src = Ptr{Cuchar}(_start)
unsafe_copyto!(src, pointer(_data), n)
return len
end
"""
cancel(buf::Buffer)
Cancel the current buffer.
"""
cancel(buf::Buffer) = _buffer_cancel(buf.buffer)
"""
set_blocking_mode(buf::Buffer, blocking)
Set the buffer's blocking mode.
# Parameters:
- `blocking` : True if in blocking mode else false.
"""
set_blocking_mode(buf::Buffer, blocking) = _buffer_set_blocking_mode(buf.buffer, blocking)
"""
device(buf::Buffer)
[`Device`](@ref) for the buffer.
"""
device(buf::Buffer) = buf.dev
"""
poll_fd(buf::Buffer)
Poll_fd for the buffer.
"""
poll_fd(buf::Buffer) = _buffer_get_poll_fd(buf.buffer)
"""
step(buf::Buffer)
Step size for the buffer.
"""
step(buf::Buffer) = _buffer_step(buf.buffer)
| LibIIO | https://github.com/TacHawkes/LibIIO.jl.git |
|
[
"MIT"
] | 0.1.2 | 47a08b35777450039eaa8e971e1278369931b431 | code | 6785 | """
ChannelAttr <: Attr
Represents an attribute of a IIO channel
"""
struct ChannelAttr <: Attr
channel::Ptr{iio_channel}
name::String
filename::String
end
"""
ChannelAttr(chn::Ptr{iio_channel}, name::String)
Initializes a new instance of a ChannelAttr.
# Parameters
- `chn::Ptr{iio_channel}` : A valid pointer to an [`iio_channel`](@ref)
- `name::String` : The channel attribute's name
# Returns
- A new instance of this type
"""
function ChannelAttr(chn::Ptr{iio_channel}, name::String)
return ChannelAttr(chn,
name,
_c_get_filename(chn, name))
end
read(a::ChannelAttr) = _c_read_attr(a.channel, a.name)
write(a::ChannelAttr, value) = _c_write_attr(a.channel, a.name, value)
function show(io::IO, ::MIME"text/plain", chn::AbstractChannel, tree_depth = 0)
_chn = iio_channel(chn)
if chn.output
type_name = "output"
else
type_name = "input"
end
_name = name(chn)
_id = id(chn)
print(io, "\t"^tree_depth, "$_id: $_name ($type_name")
(type(chn) == IIO_CHAN_TYPE_UNKNOWN) &&
print(io, ", WARN::iio_channel_get_type()=UNKNOWN")
if chn.scan_element
format = _channel_get_data_format(_chn)
_sign = convert(Bool, format.is_signed) ? 's' : 'u'
_repeat = ""
convert(Bool, format.is_fully_defined) && (_sign += 'A' - 'a')
_idx = iio_channel_get_index(_chn)
_endianness = convert(Bool, format.is_be) ? 'b' : 'l'
if format.repeat > 1
_repeat = "X$(format.repeat)"
end
println(io,
", index: $_idx, format: $(_endianness)e:$(_sign)$(format.bits)/$(format.length)$_repeat>>$(format.shift))")
else
println(io, ")")
end
nb_attrs = iio_channel_get_attrs_count(_chn)
if nb_attrs > 0
println(io, "\t"^tree_depth, "$nb_attrs channel-specific attributes found:")
k = 0
for (_name, attr) in chn.attrs
show(io, MIME("text/plain"), attr, tree_depth + 1, k)
k += 1
end
end
end
iio_channel(chn::AbstractChannel) = chn.channel
"""
read(chn::AbstractChannel, buf::AbstractBuffer, raw=false)
Extract the samples corresponding to this channel from the given buffer.
# Parameters
- `chn::Channel` : The channel instance
- `buf::AbstractBuffer` : A buffer instance
- `raw::Bool`: If set to true, the samples are not converted from their
native format to their host format
# Returns
- A `Vector{Cuchar}` containing the samples for this channel
"""
function read(chn::AbstractChannel, buf::AbstractBuffer, raw = false)
dst = Vector{Cuchar}(undef, length(buf))
if raw
len = _c_read_raw(iio_channel(chn), buf.buffer, dst)
else
len = _c_read(iio_channel(chn), buf.buffer, dst)
end
return dst
end
"""
read(chn::AbstractChannel, buf::AbstractBuffer, data::Vector{T}, raw=false) where {T}
Write the specified vector of samples into the buffer the specified channel.
# Parameters
- `chn::Channel` : The channel instance
- `buf::AbstractBuffer` : A buffer instance
- `data::Vector{T}` : A data vector containing the samples to copy
- `raw::Bool`: If set to true, the samples are not converted from their
host format to their native format
# Returns
- The number of bytes written
"""
function write(chn::AbstractChannel, buf::AbstractBuffer, data::Vector{T}, raw = false) where {T}
_data = reinterpret(Cuchar, data)
if raw
return _c_write_raw(iio_channel(chn), buf.buffer, _data)
end
return _c_write(iio_channel(chn), buf.buffer, _data)
end
name(chn::AbstractChannel) = chn.name
"""
id(chn)
An identifier of this channel.
Note that it is possible that two channels have the same ID,
if one is an input channel and the other is an output channel.
"""
id(chn::AbstractChannel) = chn.id
"""
attrs(chn)
List of attributes for the given channel.
"""
attrs(chn::AbstractChannel) = chn.attrs
"""
output(chn)
Contains true if the channel is an output channel, false otherwise.
"""
output(chn::AbstractChannel) = chn.output
"""
scan_element(chn)
Contains true if the channel is a scan element, false otherwise.
"""
scan_element(chn::AbstractChannel) = chn.scan_element
"""
enabled(chn)
Returns true if the channel is enabled, false otherwise.
"""
enabled(chn::AbstractChannel) = _c_is_enabled(iio_channel(chn))
"""
enabled!(chn, state)
Sets the channel state to enabled if true, disabled otherwise.
"""
enabled!(chn::AbstractChannel, state) = state ? _c_enable(iio_channel(chn)) : _c_disable(iio_channel(chn))
"""
device(chn)
Retrieves the corresponding `AbstractDeviceOrTrigger` for this channel.
"""
device(chn::AbstractChannel) = chn.dev
"""
index(chn)
Returns the index of the channel.
"""
index(chn::AbstractChannel) = _channel_get_index(iio_channel(chn))
"""
data_format(chn)
Returns the channel data format as a C-struct. See [`iio_data_format`](@ref).
"""
data_format(chn::AbstractChannel) = _channel_get_data_format(iio_channel(chn))
"""
modifier(chn)::iio_modifier
Returns the channel modifier as an enum value.
"""
modifier(chn::AbstractChannel) = _channel_get_modifier(iio_channel(chn))
"""
type(chn)::iio_chan_type
Returns the channel type as an enum value.
"""
type(chn::AbstractChannel) = _channel_get_type(iio_channel(chn))
"""
Channel{T <: AbstractDeviceOrTrigger} <: AbstractChannel
Represents a channel of an IIO device.
"""
struct Channel{T <: AbstractDeviceOrTrigger} <: AbstractChannel
channel::Ptr{iio_channel}
dev::T
attrs::Dict{String, ChannelAttr}
id::String
name::String
output::Bool
scan_element::Bool
end
"""
Channel(dev::AbstractDeviceOrTrigger, channel::Ptr{iio_channel})
Initializes a new instance of the Channel type.
# Parameters
- `dev::AbstractDeviceOrTrigger` : The parent device handle (`Device` or `Trigger`)
- `channel::Ptr{iio_channel}` : A valid pointer to an IIO channel.
# Returns
- A new instance of this type
"""
function Channel(dev::AbstractDeviceOrTrigger, channel::Ptr{iio_channel})
attrs = Dict{String, ChannelAttr}(name => ChannelAttr(channel, name)
for name in [_c_get_attr(channel,
convert(Cuint, x - 1))
for x in 1:_c_attr_count(channel)])
id = _c_get_id(channel)
name = _c_get_name(channel)
output = _c_is_output(channel)
scan_element = _c_is_scan_element(channel)
return Channel(channel,
dev,
attrs,
id,
name,
output,
scan_element)
end
| LibIIO | https://github.com/TacHawkes/LibIIO.jl.git |
|
[
"MIT"
] | 0.1.2 | 47a08b35777450039eaa8e971e1278369931b431 | code | 7007 | # internal method, get underlying pointer to iio_context
iio_context(ctx::AbstractContext) = ctx.context
"""
set_timeout(ctx::AbstractContext, timeout)
Set a timeout for I/O operations.
# Parameters
- `value` : The timeout value, in milliseconds
"""
set_timeout(ctx::AbstractContext, timeout) = _set_timeout(iio_context(ctx), timeout)
"""
clone(ctx::T) where {T <: AbstractContext}
Clones the IIO context.
"""
clone(ctx::T) where {T <: AbstractContext} = T(_clone(iio_context(ctx)))
"""
name(ctx::AbstractContext)
Name of the IIO context.
"""
name(ctx::AbstractContext) = ctx.name
"""
description(ctx::AbstractContext)
Description of this IIO context.
"""
description(ctx::AbstractContext) = ctx.description
"""
xml(ctx::AbstractContext)
XML representation of the IIO context.
"""
xml(ctx::AbstractContext) = ctx.xml_file
"""
version(ctx::AbstractContext)
Version of the context backed, as `Tuple(UInt, UInt, String)``
"""
version(ctx::AbstractContext) = ctx.version
"""
attrs(ctx::AbstractContext)
Lost of context-specific attributes.
"""
attrs(ctx::AbstractContext) = ctx.attrs
"""
find_device(ctx::AbstractContext, name_or_id_or_label)
Find an IIO device by its name, ID or label.
"""
function find_device(ctx::AbstractContext, name_or_id_or_label)
dev = _find_device(iio_context(ctx), name_or_id_or_label)
return _d_is_trigger(dev) ? Trigger(ctx, dev) : Device(ctx, dev)
end
"""
devices(ctx::AbstractContext)
List of devices contained in this context.
"""
function devices(ctx::AbstractContext)
return [(_d_is_trigger(dev) ? Trigger(ctx, dev) : Device(ctx, dev))
for dev in [_get_device(iio_context(ctx), convert(Cuint, x - 1))
for x in 1:_devices_count(iio_context(ctx))]]
end
function show(io::IO, ::MIME"text/plain", ctx::AbstractContext)
_ctx = iio_context(ctx)
name = _get_name(_ctx)
println(io, "IIO context created with ", name, " backend.")
ret, major, minor, git_tag = _get_version(_ctx)
if ret == 0
println(io, "Backend version: $major.$minor (git tag: $git_tag)")
else
err_str = iio_strerror(-ret)
println(io, "Unable to get backend version: $err_str")
end
println(io, "Backend description string: $(_get_description(_ctx))")
nb_ctx_attrs = _get_attrs_count(_ctx)
nb_ctx_attrs > 0 && println(io, "IIO context has $nb_ctx_attrs attributes:")
for i in 0:(nb_ctx_attrs - 1)
ret, name, value = _get_attr(_ctx, convert(Cuint, i))
if ret == 0
println(io, "\t$name: $value")
else
err_str = iio_strerror(-ret)
println(io, "\tUnable to read IIO context attributes: $err_str")
end
end
nb_devices = _devices_count(_ctx)
println(io, "IIO context has $nb_devices devices:")
devs = devices(ctx)
for dev in devs
show(io, MIME("text/plain"), dev, 1)
end
end
"""
Contains the representation of an IIO context.
"""
mutable struct Context <: AbstractContext
context::Ptr{iio_context}
name::String
description::String
xml::String
version::Tuple{Int, Int, String}
attrs::Dict{String, String}
end
"""
Context(ptr_uri_or_nothing = nothing)
Initializes a new Context using the local or the network backend of the IIO library.
This function will create a network context if the IIOD_REMOTE
environment variable is set to the hostname where the IIOD server runs.
If set to an empty string, the server will be discovered using ZeroConf.
If the environment variable is not set, a local context will be created instead.
# Parameters
- `ptr_uri_or_nothing` : Either a `Ptr{iio_context}`, an URI string (recommended) or `nothing`
to construct the default context (Linux only).
"""
function Context(ptr_uri_or_nothing = nothing)
# init context
ctx = init_ctx(ptr_uri_or_nothing)
# init attributes
attrs = Dict{String, String}()
for index in 1:_get_attrs_count(ctx)
ret, name, value = _get_attr(ctx, convert(Cuint, index - 1))
push!(attrs, name => value)
end
name = _get_name(ctx)
description = _get_description(ctx)
xml = _get_xml(ctx)
ret, major, minor, git_tag = _get_version(ctx)
_context = Context(ctx,
name,
description,
xml,
(major, minor, git_tag),
attrs)
# register finalizer
finalizer(_context) do x
_destroy(x.context)
end
end
init_ctx(ctx::Ptr{iio_context}) = ctx
init_ctx(ctx::String) = _new_uri(ctx)
init_ctx(::Nothing) = _new_default()
abstract type AbstractBackendContext <: AbstractContext end
iio_context(ctx::AbstractBackendContext) = iio_context(ctx.context)
name(ctx::AbstractBackendContext) = name(ctx.context)
description(ctx::AbstractBackendContext) = description(ctx.context)
xml(ctx::AbstractBackendContext) = xml(ctx.context)
version(ctx::AbstractBackendContext) = version(ctx.context)
attrs(ctx::AbstractBackendContext) = attrs(ctx.context)
"""
Local IIO Context.
"""
struct LocalContext <: AbstractBackendContext
context::Context
end
"""
LocalContext([ctx::Ptr{iio_context}])
Initializes a new LocalContext using the local backend if the IIO library.
Can be constructed from an existing pointer to an `iio_context`.
"""
function LocalContext()
ctx = _new_local()
return LocalContext(Context(ctx))
end
LocalContext(ctx::Ptr{iio_context}) = LocalContext(Context(ctx))
"""
XML IIO Context.
"""
struct XMLContext <: AbstractBackendContext
context::Context
end
"""
XMLContext(xml_file)
Initializes a new XMLContext using the XML backend if the IIO library.
# Parameters
- `xmlfile` : Filename of the XML file to build the context from.
"""
function XMLContext(xmlfile::String)
ctx = _new_xml(xmlfile)
return XMLContext(Context(ctx))
end
XMLContext(ctx::Ptr{iio_context}) = XMLContext(Context(ctx))
"""
Network IIO context
"""
struct NetworkContext <: AbstractBackendContext
context::Context
end
"""
XMLContext(xml_file)
Initializes a new NetworkContext using the network backend if the IIO library.
# Parameters
- `hostname` : Hostname, IPv4 or IPv6 address where the IIO Daemon is running
"""
function NetworkContext(hostname::Union{String, Nothing} = nothing)
ctx = !isnothing(hostname) ? _new_network(hostname) : nothing
return NetworkContext(Context(ctx))
end
NetworkContext(ctx::Ptr{iio_context}) = NetworkContext(Context(ctx))
"""
scan_contexts()
Scan Context.
"""
function scan_contexts()
scan_ctx = Dict{String, String}()
ptr = Ptr{Ptr{iio_context_info}}(0)
ctx = _create_scan_context("")
ctx_nb = _get_context_info_list(ctx, Ref(ptr))
for i in 1:ctx_nb
info = unsafe_load(ptr[], i)
scan_ctx[_context_info_get_uri(info)] = _context_info_get_description(info)
end
_context_info_list_free(ptr)
_destroy_scan_context(ctx)
return scan_ctx
end
| LibIIO | https://github.com/TacHawkes/LibIIO.jl.git |
|
[
"MIT"
] | 0.1.2 | 47a08b35777450039eaa8e971e1278369931b431 | code | 10766 | """
DeviceAttr <: Attr
Represents an attribute of an IIO device
"""
struct DeviceAttr <: Attr
device::Ptr{iio_device}
name::String
end
filename(a::DeviceAttr) = a.name
read(a::DeviceAttr) = _d_read_attr(a.device, a.name)
write(a::DeviceAttr, value) = _d_write_attr(a.device, a.name, value)
"""
DeviceAttr <: Attr
Represents a debug attribute of an IIO device
"""
struct DeviceDebugAttr <: Attr
device::Ptr{iio_device}
name::String
end
filename(a::DeviceDebugAttr) = a.name
read(a::DeviceDebugAttr) = _d_read_debug_attr(a.device, a.name)
write(a::DeviceDebugAttr, value) = _d_write_debug_attr(a.device, a.name, value)
"""
DeviceAttr <: Attr
Represents a buffer attribute of an IIO device
"""
struct DeviceBufferAttr <: Attr
device::Ptr{iio_device}
name::String
end
filename(a::DeviceBufferAttr) = a.name
read(a::DeviceBufferAttr) = _d_read_buffer_attr(a.device, a.name)
write(a::DeviceBufferAttr, value) = _d_write_buffer_attr(a.device, a.name, value)
device_or_trigger(d::AbstractDeviceOrTrigger) = d
"""
id(d::AbstractDeviceOrTrigger)
An identifier of the device, only valid in this IIO context.
"""
id(d::AbstractDeviceOrTrigger) = device_or_trigger(d).id
"""
name(d::AbstractDeviceOrTrigger)
The name of the device.
"""
name(d::AbstractDeviceOrTrigger) = device_or_trigger(d).name
"""
label(d::AbstractDeviceOrTrigger)
The label of the device.
"""
label(d::AbstractDeviceOrTrigger) = device_or_trigger(d).label
"""
attrs(d::AbstractDeviceOrTrigger)
List of attributes for the IIO device.
"""
attrs(d::AbstractDeviceOrTrigger) = device_or_trigger(d).attrs
"""
debug_attrs(d::AbstractDeviceOrTrigger)
List of debug attributes for the IIO device.
"""
debug_attrs(d::AbstractDeviceOrTrigger) = device_or_trigger(d).debug_attrs
"""
buffer_attrs(d::AbstractDeviceOrTrigger)
List of buffer attributes for the IIO device.
"""
buffer_attrs(d::AbstractDeviceOrTrigger) = device_or_trigger(d).buffer_attrs
"""
channels(d::AbstractDeviceOrTrigger)
List of channels available with this IIO device.
"""
function channels(d::AbstractDeviceOrTrigger)
_dt = device_or_trigger(d)
chns = [Channel(_dt,
_get_channel(_dt.device, convert(Cuint, x - 1)))
for x in 1:_channels_count(_dt.device)]
sort!(chns, by = x -> id(x))
return chns
end
"""
reg_write(d::AbstractDeviceOrTrigger, reg, value)
Set a valie to one register of the device.
# Parameters
- `d` : The device instance
- `reg` : The register address
- `value` ; The value that will be used for this register
"""
function reg_write(d::AbstractDeviceOrTrigger, reg, value)
_d_reg_write(device_or_trigger(d).device, reg, value)
end
"""
reg_read(d::AbstractDeviceOrTrigger, reg)
Read the content of a register of this device.
# Parameters
- `d` : The device instance
- `reg` : The register address
# Returns
- The value of the register
"""
reg_read(d::AbstractDeviceOrTrigger, reg) = _d_reg_read(device_or_trigger(d).device, reg)
"""
find_channel(d::AbstractDeviceOrTrigger, name_or_id, is_output = false)
Find an IIO channel by its name or ID.
# Parameters
- `d` : The device instance
- `name_or_id` : The name or ID of the channel to find
- `is_output` : Set to true to search for an output channel
# Returns
- The IIO channel as `Channel`
"""
function find_channel(d::AbstractDeviceOrTrigger, name_or_id, is_output = false)
chn = _d_find_channel(device_or_trigger(d).device, name_or_id, is_output)
return chn == C_NULL ? nothing : Channel(d, chn)
end
"""
set_kernel_buffers_count(d::AbstractDeviceOrTrigger, count)
Set the number of kernel buffers to use with the specified device
# Parameters
- `d` : The device instance
- `count` : The number of kernel buffers
"""
function set_kernel_buffers_count(d::AbstractDeviceOrTrigger, count)
_d_set_buffers_count(device_or_trigger(d).device, count)
end
"""
sample_size(d::AbstractDeviceOrTrigger)
Sample size of the device.
The sample size varies each time channels get enabled or disabled.
"""
sample_size(d::AbstractDeviceOrTrigger) = _get_sample_size(device_or_trigger(d).device)
function show(io::IO, ::MIME"text/plain", dev::AbstractDeviceOrTrigger, tree_depth = 0)
d_o_t = device_or_trigger(dev)
_dev = d_o_t.device
_name = name(dev)
_label = label(dev)
_id = id(dev)
print(io, "\t"^tree_depth, "$_id:")
!isempty(_name) && print(io, " $_name")
!isempty(_label) && print(io, " (label: $_label")
dev_is_buffer_capable(_dev) && print(io, " (buffer capable)")
println(io)
tree_depth += 1
nb_channels = _channels_count(_dev)
println(io, "\t"^tree_depth, "$nb_channels channels found:")
chns = channels(dev)
for chn in chns
show(io, MIME("text/plain"), chn, tree_depth + 1)
end
nb_attrs = _d_attr_count(_dev)
if nb_attrs > 0
println(io, "\t"^tree_depth, "$nb_attrs device-specific attributes found:")
j = 0
for (_name, attr) in attrs(dev)
show(io, MIME("text/plain"), attr, tree_depth + 2, j)
j += 1
end
end
nb_attrs = _d_buffer_attr_count(_dev)
if nb_attrs > 0
println(io, "\t"^tree_depth, "$nb_attrs buffer-specific attributes found:")
j = 0
for (_name, attr) in buffer_attrs(dev)
show(io, MIME("text/plain"), attr, tree_depth + 2, j)
j += 1
end
end
nb_attrs = _d_debug_attr_count(_dev)
if nb_attrs > 0
println(io, "\t"^tree_depth, "$nb_attrs debug-specific attributes found:")
j = 0
for (_name, attr) in debug_attrs(dev)
show(io, MIME("text/plain"), attr, tree_depth + 2, j)
j += 1
end
end
ret, trig = _d_get_trigger(_dev)
if ret == 0
if trig == C_NULL
println(io, "\t"^tree_depth, "No trigger assigned to device")
else
_name = _d_get_name(trig)
_id = _d_get_id(trig)
println("\t"^tree_depth, "Current trigger: $_name($_id)")
end
elseif ret == -ENOENT
println(io, "\t"^tree_depth, "No trigger on this device")
elseif ret < 0
err_str = iio_strerror(-ret)
println("ERROR: checking for trigger : $err_str")
end
end
struct DeviceOrTrigger{T <: AbstractContext} <: AbstractDeviceOrTrigger
ctx::T
context::Ptr{iio_context}
device::Ptr{iio_device}
attrs::Dict{String, DeviceAttr}
debug_attrs::Dict{String, DeviceDebugAttr}
buffer_attrs::Dict{String, DeviceBufferAttr}
id::String
name::String
label::String
end
function DeviceOrTrigger(ctx::AbstractContext, device::Ptr{iio_device})
context = _d_get_context(device)
attrs = Dict{String, DeviceAttr}(name => DeviceAttr(device, name)
for name in [_d_get_attr(device,
convert(Cuint, x - 1))
for x in 1:_d_attr_count(device)])
debug_attrs = Dict{String, DeviceDebugAttr}(name => DeviceDebugAttr(device, name)
for name in [_d_get_debug_attr(device,
convert(Cuint,
x -
1))
for x in 1:_d_debug_attr_count(device)])
buffer_attrs = Dict{String, DeviceBufferAttr}(name => DeviceBufferAttr(device, name)
for name in [_d_get_buffer_attr(device,
convert(Cuint,
x -
1))
for x in 1:_d_buffer_attr_count(device)])
id = _d_get_id(device)
name = _d_get_name(device)
label = _d_get_label(device)
return DeviceOrTrigger(ctx,
context,
device,
attrs,
debug_attrs,
buffer_attrs,
id,
name,
label)
end
"""
Contains the representation of an IIO device that can act as a trigger.
"""
struct Trigger{T <: AbstractContext} <: AbstractDeviceOrTrigger
trigger::DeviceOrTrigger{T}
end
"""
Trigger(ctx::AbstractContext, device::Ptr{iio_device})
Initializes a new Trigger instance.
# Parameters
- `ctx` : The IIO context instance with which the device is accessed
- `device` : A pointer to an iio_device which represents this trigger
"""
function Trigger(ctx::AbstractContext, device::Ptr{iio_device})
return Trigger(DeviceOrTrigger(ctx, device))
end
device_or_trigger(t::Trigger) = t.trigger
"""
frequency(t::Trigger)
Configured frequency (in Hz) of the trigger.
"""
frequency(t::Trigger) = parse(Int, read(attrs(t)["sampling_frequency"]))
"""
frequency!(t::Trigger, value)
Set the trigger rate.
"""
frequency!(t::Trigger, value) = write(attrs(t)["sampling_frequency"], string(value))
"""
Contains the representation of an IIO device.
"""
struct Device{T <: AbstractContext} <: AbstractDeviceOrTrigger
device::DeviceOrTrigger{T}
end
"""
Device(ctx::AbstractContext, device::Ptr{iio_device})
Initializes a new Device instance.
# Parameters
- `ctx` : The IIO context instance with which the device is accessed
- `device` : A pointer to an iio_device which represents this device
"""
function Device(ctx::AbstractContext, device::Ptr{iio_device})
return Device(DeviceOrTrigger(ctx, device))
end
device_or_trigger(d::Device) = d.device
hwmon(d::Device) = error("TODO")
"""
context(d::Device)
Context for the device.
"""
iio_context(d::Device) = device_or_trigger(d).ctx
"""
trigger!(d::Device, trigger::Trigger)
Sets the configured trigger for this IIO device.
"""
function trigger!(d::Device, trigger::Trigger)
_d_set_trigger(d.device.device, trigger.device.device)
end
"""
trigger(d::Device)
Returns the configured trigger for this IIO device, if present in the current context.
"""
function trigger(d::Device)
ret, _trig = _d_get_trigger(d.device.device)
trig = Trigger(iio_context(d), _trig)
for dev in devices(iio_context(d))
if id(trig.id) == id(dev)
return dev
end
end
return nothing
end
| LibIIO | https://github.com/TacHawkes/LibIIO.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.