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" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
3393
using Revise using StatsBase using Statistics using OnlineStats using BenchmarkTools using WeightedOnlineStats x = (collect(reverse((1:10_000_000)*0.0000001))) w = (collect((1:10_000_000)*0.0000001)) x1 = x[1:5_000_000] x2 = (x[5_000_001:end]) w1 = w[1:5_000_000] w2 = (w[5_000_001:end]) vw = WeightedVariance() vw1 = WeightedVariance() vw2 = WeightedVariance() fit!(vw, x, w) fit!(vw1, x1, w1) fit!(vw2, x2, w2) @code_warntype merge!(vw1, vw2) @benchmark merge($vw1, $vw2) #= BenchmarkTools.Trial.1.1: ll. 133-145 (w/o 135-138) memory estimate: 544 bytes allocs estimate: 7 -------------- minimum time: 3.140 μs (0.00% GC) median time: 3.257 μs (0.00% GC) mean time: 3.476 μs (1.52% GC) maximum time: 272.601 μs (97.37% GC) -------------- samples: 10000 evals/sample: 8 BenchmarkTools.Trial.1.2: ll. 133-145 (w/o 139-141) memory estimate: 544 bytes allocs estimate: 7 -------------- minimum time: 3.141 μs (0.00% GC) median time: 3.206 μs (0.00% GC) mean time: 3.380 μs (1.54% GC) maximum time: 268.521 μs (97.16% GC) -------------- samples: 10000 evals/sample: 8 BenchmarkTools.Trial.2: ll. 151-161 memory estimate: 544 bytes allocs estimate: 7 -------------- minimum time: 3.136 μs (0.00% GC) median time: 3.229 μs (0.00% GC) mean time: 3.347 μs (1.53% GC) maximum time: 262.741 μs (97.26% GC) -------------- samples: 10000 evals/sample: 8 =# x = (collect(reverse((1:10_000_000)*0.0000001))) w = (collect((1:10_000_000)*0.0000001)) x1 = x[1:5_000_000] x2 = BigFloat.(x[5_000_001:end]) w1 = w[1:5_000_000] w2 = BigFloat.(w[5_000_001:end]) vw = WeightedVariance() vw1 = WeightedVariance() vw2 = WeightedVariance(BigFloat) fit!(vw, x, w) fit!(vw1, x1, w1) fit!(vw2, x2, w2) @code_warntype merge(vw1, vw2) merge(vw1, vw2) merge(vw2, vw1) @benchmark merge($vw1, $vw2) @benchmark merge($vw2, $vw1) #= BenchmarkTools.Trial.1.1: ll. 133-145 (w/o 135-138) memory estimate: 2.28 KiB allocs estimate: 39 -------------- minimum time: 4.955 μs (0.00% GC) median time: 5.060 μs (0.00% GC) mean time: 5.603 μs (3.95% GC) maximum time: 346.025 μs (94.78% GC) -------------- samples: 10000 evals/sample: 7 BenchmarkTools.Trial.1.2: ll. 133-145 (w/o 139-141) memory estimate: 2.06 KiB allocs estimate: 35 -------------- minimum time: 4.779 μs (0.00% GC) median time: 4.861 μs (0.00% GC) mean time: 5.366 μs (3.63% GC) maximum time: 348.297 μs (96.43% GC) -------------- samples: 10000 evals/sample: 7 BenchmarkTools.Trial.2: ll. 151-161 memory estimate: 2.50 KiB allocs estimate: 43 -------------- minimum time: 5.398 μs (0.00% GC) median time: 5.515 μs (0.00% GC) mean time: 6.042 μs (3.80% GC) maximum time: 426.032 μs (96.56% GC) -------------- samples: 10000 evals/sample: 6 =# using Traceur x = rand(100) x2 = rand(100, 2) w = rand(100) @trace fit!(WeightedSum(), x, w) @trace fit!(WeightedSum(Float32), x, w) @trace fit!(WeightedMean(), x, w) @trace fit!(WeightedMean(Float32), x, w) @trace fit!(WeightedVariance(), x, w) @trace fit!(WeightedVariance(Float32), x, w) @trace fit!(WeightedCovMatrix(), x2, w) @trace fit!(WeightedCovMatrix(Float32), x2, w)
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
1085
module WeightedOnlineStats export WeightedSum, WeightedMean, WeightedVariance, WeightedCovMatrix, WeightedHist, WeightedAdaptiveHist, WeightedAdaptiveBins, fit!, merge!, weightsum, value, mean, std, cov, cor, median, quantile import OnlineStats import OnlineStats: Tup, VectorOb, TwoThings, Algorithm, Extrema, smooth, smooth!, smooth_syr! import OnlineStatsBase import OnlineStatsBase: OnlineStat, name, fit!, merge!, _fit!, _merge!, eachrow, eachcol, nobs, value import Statistics import Statistics: mean, var, std, cov, cor, median, quantile import LinearAlgebra import LinearAlgebra: Hermitian, lmul!, rmul!, Diagonal, diag import StatsBase: midpoints include("interface.jl") include("sum.jl") include("mean.jl") include("var.jl") include("covmatrix.jl") export pca """ `pca` creates a PCA object from a `WeightedCovMatrix` object. Requires MultivariateStats to be loaded! """ function pca end if !isdefined(Base, :get_extension) include("../ext/PcaExt.jl") end include("histogram.jl") end # module WeightedOnlineStats
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
4470
""" WeightedCovMatrix(T = Float64) Weighted covariance matrix, tracked as a matrix of type `T`. *After* a call to `cov` the covariance matrix is stored in `o.C`. # Example: o = fit!(WeightedCovMatrix(), rand(100, 4) |> eachrow, rand(100)) o = fit!(WeightedCovMatrix(), rand(4, 100) |> eachcol, rand(100)) sum(o) mean(o) var(o) std(o) cov(o) cor(o) """ mutable struct WeightedCovMatrix{T} <: WeightedOnlineStat{VectorOb} C::Matrix{T} A::Matrix{T} b::Vector{T} W::T W2::T n::Int function WeightedCovMatrix{T}( C = zeros(T, 0, 0), A = zeros(T, 0, 0), b = zeros(T, 0), W = T(0), W2 = T(0), n = 0 ) where {T} new{T}(C, A, b, W, W2, n) end end function WeightedCovMatrix( C::Matrix{T}, A::Matrix{T}, b::Vector{T}, W::T, W2::T, n::Int ) where {T} WeightedCovMatrix{T}(C, A, b, W, W2, n) end WeightedCovMatrix(::Type{T}, p::Int = 0) where {T} = WeightedCovMatrix(zeros(T, p, p), zeros(T, p, p), zeros(T, p), T(0), T(0), 0) WeightedCovMatrix() = WeightedCovMatrix(Float64) function _fit!(o::WeightedCovMatrix{T}, x, w) where {T} if eltype(x) != T xx = convert(Array{T}, x) else xx = x end ww = convert(T, w) o.n += 1 γ1 = T(1) / o.n o.W = smooth(o.W, ww, γ1) o.W2 = smooth(o.W2, ww * ww, γ1) γ2 = ww / (o.W * o.n) if isempty(o.A) p = length(xx) o.b = zeros(T, p) o.A = zeros(T, p, p) o.C = zeros(T, p, p) end smooth!(o.b, xx, γ2) smooth_syr!(o.A, xx, γ2) end function _fit!(o::WeightedCovMatrix{T1}, x::AbstractVector{Union{T2,Missing}}, w) where {T1,T2} if !mapreduce(ismissing, |, x) xx = convert(Vector{T1}, x) _fit!(o, xx, w) end return o end _fit!(o::WeightedCovMatrix, x, w::Missing) = o function _merge!(o::WeightedCovMatrix{T}, o2::WeightedCovMatrix) where {T} o2_A = convert(Matrix{T}, o2.A) o2_b = convert(Vector{T}, o2.b) o2_W = convert(T, o2.W) o2_W2 = convert(T, o2.W2) if isempty(o.A) o.C = convert(Matrix{T}, o2.C) o.A = o2_A o.b = o2_b o.W = o2_W o.W2 = o2_W2 o.n = o2.n else n = o.n + o2.n W = smooth(o.W, o2_W, o2.n / n) γ = (o2_W * o2.n) / (W * n) smooth!(o.A, o2_A, γ) smooth!(o.b, o2_b, γ) o.n = n o.W = W o.W2 = smooth(o.W2, o2_W2, o2.n / o.n) end return o end nvars(o::WeightedCovMatrix) = size(o.A, 1) function OnlineStatsBase.value(o::WeightedCovMatrix) # o.A is only the upper triangle: # o.C .= o.A .- o.b .* o.b' @inbounds for i in 1:size(o.A, 1) for j in 1:i o.C[j, i] = o.A[j, i] - o.b[i] * o.b[j] end end LinearAlgebra.copytri!(o.C, 'U') o.C end function Statistics.cov(o::WeightedCovMatrix; corrected = true, weight_type = :analytic) if corrected if weight_type == :analytic LinearAlgebra.rmul!( value(o), 1 / (1 - (o.W2 * nobs(o)) / (weightsum(o)^2)) ) elseif weight_type == :frequency LinearAlgebra.rmul!( value(o), 1 / (weightsum(o) - 1) * weightsum(o) ) elseif weight_type == :probability error("If you need this, please make a PR or open an issue") else throw(ArgumentError("weight type $weight_type not implemented")) end else value(o) end end function Statistics.cor(o::WeightedCovMatrix; kw...) cov(o; kw...) v = diag(o.C) v .= 1 ./ sqrt.(v) return o.C .* v .* v' end Base.sum(o::WeightedCovMatrix) = o.b .* (meanweight(o) * nobs(o)) Statistics.mean(o::WeightedCovMatrix) = copy(o.b) Statistics.var(o::WeightedCovMatrix; kw...) = diag(cov(o; kw...)) Statistics.std(o::WeightedCovMatrix; kw...) = sqrt.(var(o; kw...)) Base.eltype(o::WeightedCovMatrix{T}) where {T} = T Base.copy(o::WeightedCovMatrix) = WeightedCovMatrix(copy(o.C), copy(o.A), copy(o.b), o.W, o.W2, o.n) Base.size(x::WeightedCovMatrix, i) = size(x.C, i) Base.size(x::WeightedCovMatrix) = size(x.C) function Base.convert(::Type{WeightedCovMatrix{T}}, o::WeightedCovMatrix) where {T} WeightedCovMatrix{T}( convert(Matrix{T}, o.C), convert(Matrix{T}, o.A), convert(Vector{T}, o.b), convert(T, o.W), convert(T, o.W2), o.n ) end
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
11888
############################################################## # Using the code from OnlineStats.jl/src/stats/hist.jl # Modifying it to work with WeightedOnlineStats ############################################################## import LinearAlgebra abstract type WeightedHistogramStat{T} <: WeightedOnlineStat{T} end abstract type WeightedHist{T} <: WeightedHistogramStat{T} end split_candidates(o::WeightedHistogramStat) = midpoints(o) Statistics.mean(o::WeightedHistogramStat) = mean(midpoints(o), fweights(counts(o))) Statistics.var(o::WeightedHistogramStat) = var(midpoints(o), fweights(counts(o)); corrected=true) Statistics.std(o::WeightedHistogramStat) = sqrt.(var(o)) Statistics.median(o::WeightedHistogramStat) = quantile(o, .5) function Base.show(io::IO, o::WeightedHistogramStat) print(io, name(o, false, false), ": ") print(io, "∑wᵢ=", nobs(o)) print(io, " | value=") show(IOContext(io, :compact => true), value(o)) end #-----------------------------------------------------------------------# WeightedHist """ WeightedHist(edges; left = true, closed = true) Create a histogram with bin partition defined by `edges`. - If `left`, the bins will be left-closed. - If `closed`, the bin on the end will be closed. - E.g. for a two bin histogram ``[a, b), [b, c)`` vs. ``[a, b), [b, c]`` If `edges` is a tuple instead of an array, a multidimensional histogram will be generated that behaves like a `WeightedOnlineStat{VectorOb}`. # Examples o = fit!(WeightedHist(-5:.1:5), randn(10^6)) # approximate statistics using Statistics mean(o) var(o) std(o) quantile(o) median(o) extrema(o) area(o) pdf(o) ## 2d Histogram hist2d = fit!(WeightedHist((-5:1:5, -5:1:5) ), randn(10000,2), rand(10000)) value(hist2d).y """ struct WeightedHist1D{R} <: WeightedHist{Float64} edges::R counts::Vector{Int} meanw::Vector{Float64} outcount::Vector{Int} meanwout::Vector{Float64} left::Bool closed::Bool end struct WeightedHistND{R, N} <: WeightedHist{OnlineStats.VectorOb} edges::R counts::Array{Int,N} meanw::Array{Float64,N} outcount::Array{Int,N} meanwout::Array{Float64,N} left::Bool closed::Bool end function WeightedHist(edges; left::Bool=true, closed::Bool = true) edges = isa(edges,Tuple) ? edges : (edges,) counts = zeros(Int, map(i->length(i)-1, edges)) meanw = zeros(Float64, map(i->length(i)-1, edges)) outcount = zeros(Int,ntuple(_->3,length(edges))) meanwout = zeros(Float64,ntuple(_->3,length(edges))) if length(edges) == 1 WeightedHist1D(edges[1],counts,meanw,outcount,meanwout,left,closed) else WeightedHistND{typeof(edges),length(edges)}(edges, counts, meanw,outcount,meanwout, left, closed) end end # Special case for 1D Histogram nobs(o::WeightedHist) = sum(o.counts) + sum(o.outcount) weightsum(o::WeightedHist) = LinearAlgebra.dot(o.counts, o.meanw) + LinearAlgebra.dot(o.outcount,o.meanwout) value(o::WeightedHist) = (x=edges(o), y=o.counts .* o.meanw) binindices(o::WeightedHistND{<:Any,N}, x::AbstractVector) where N = binindices(o, ntuple(i->x[i],N)) binindices(o::WeightedHist1D,x) = OnlineStats.binindex(o.edges, x, o.left, o.closed) binindices(o::WeightedHistND,x) = CartesianIndex(map((e,ix)->OnlineStats.binindex(e, ix, o.left, o.closed), o.edges, x)) midpoints(o::WeightedHistND) = Iterators.product(map(midpoints,o.edges)...) midpoints(o::WeightedHist1D) = midpoints(edges(o)) counts(o::WeightedHist) = o.counts edges(o::WeightedHist) = o.edges function Statistics.mean(o::WeightedHist) weights = value(o).y N = ndims(o.counts) r = ntuple(N) do idim a = map(i->i[idim],midpoints(o)) mean(a,fweights(weights)) end N==1 ? r[1] : r end function Statistics.var(o::WeightedHist) weights = value(o).y N = ndims(o.counts) r = ntuple(N) do idim a = map(i->i[idim],midpoints(o)) var(a,fweights(weights),corrected=true) end N==1 ? r[1] : r end Statistics.std(o::WeightedHist) = sqrt.(var(o)) Statistics.median(o::WeightedHist) = quantile(o, .5) function Base.extrema(o::WeightedHist1D) x, y = midpoints(o), counts(o) x[findfirst(!iszero,y)],x[findlast(!iszero,y)] end function Base.extrema(o::WeightedHistND{<:Any,N}) where N x, y = midpoints(o), counts(o) ntuple(N) do idim avalue = any(!iszero, y, dims = setdiff(1:N,idim))[:] x.iterators[idim][findfirst(avalue)],x.iterators[idim][findlast(avalue)] end end function Statistics.quantile(o::WeightedHist, p = [0, .25, .5, .75, 1]) x, y = midpoints(o), counts(o) N = ndims(y) inds = findall(!iszero, y) yweights = fweights(y[inds]) subset = collect(x)[inds] r = ntuple(N) do idim data = map(i->i[idim],subset) quantile(data, fweights(y[inds]), p) end if N==1 return r[1] else return r end end function area(o::WeightedHist) c = o.counts e = o.edges return mapreduce(+, CartesianIndices(c)) do I ar = prod(map((ed,i)->ed[i+1]-ed[i],e,I.I)) c[I]*ar end end outindex(o, ci::CartesianIndex) = CartesianIndex(map((i,l)->i < 1 ? 1 : i > l ? 3 : 2, ci.I, size(o.counts))) outindex(o, ci::Int) = CartesianIndex(ci < 1 ? 1 : ci > length(o.counts) ? 3 : 2) function pdf(o::WeightedHist, y) ci = binindices(o, y) if all(isequal(2),outindex(o,ci).I) return o.counts[ci]*o.meanw[ci] / area(o) / weightsum(o) else return 0.0 end end function _fit!(o::WeightedHist, x, wt) #length(x) == N || error("You must provide $(N) values for the histogram") ci = binindices(o, x) oi = outindex(o,ci) if all(isequal(2),oi.I) o.counts[ci] += 1 o.meanw[ci] = smooth(o.meanw[ci], wt, 1.0 / o.counts[ci]) else o.outcount[oi] += 1 o.meanwout[oi] = smooth(o.meanwout[oi], wt, 1.0 / o.outcount[oi]) end end function _merge!(o::WeightedHist, o2::WeightedHist) if o.edges == o2.edges for j in eachindex(o.counts) newcount = o.counts[j] + o2.counts[j] if newcount > 0 o.meanw[j] = (o.meanw[j]*o.counts[j] + o2.meanw[j]*o2.counts[j])/newcount end o.counts[j] = newcount end for j in eachindex(o.outcount) newcount = o.outcount[j] + o2.outcount[j] if newcount > 0 o.meanwout[j] = (o.meanwout[j]*o.outcount[j] + o2.meanwout[j]*o2.outcount[j])/newcount end o.outcount[j] = newcount end else @warn("WeightedHistogram edges do not align. Merging is approximate.") for (yi, wi) in zip(midpoints(o2.edges), o2.counts) for k in 1:wi _fit!(o, yi) end end end end #-----------------------------------------------------------------------# Adaptive Hist abstract type WeightedHistAlgorithm{N} <: Algorithm end Base.show(io::IO, o::WeightedHistAlgorithm) = print(io, name(o, false, false)) make_alg(o::WeightedHistAlgorithm) = o """ Weighted Histogram Calculate a histogram of weighted data. # Example # A weighted histogram with 4 bins: o = fit!(WeightedAdaptiveHist(4), rand(1000), rand(1000)) mean(o) var(o) std(o) median(o) quantile(o, [0, 0.25, 0.5, 0.25, 1.0]) extrema(o) """ struct WeightedAdaptiveHist{N, H <: WeightedHistAlgorithm{N}} <: WeightedHistogramStat{N} alg::H WeightedAdaptiveHist{H}(alg::H) where {N, H<:WeightedHistAlgorithm{N}} = new{N, H}(alg) end WeightedAdaptiveHist(args...; kw...) = (alg = make_alg(args...; kw...); WeightedAdaptiveHist{typeof(alg)}(alg)) for f in [:nobs, :counts, :midpoints, :edges, :area] @eval $f(o::WeightedAdaptiveHist) = $f(o.alg) end for f in [:(_fit!), :pdf, :cdf, :(Base.getindex)] @eval $f(o::WeightedAdaptiveHist, y, w) = $f(o.alg, y, w) end Base.copy(o::WeightedAdaptiveHist) = WeightedAdaptiveHist(copy(o.alg)) # Base.show(io::IO, o::Hist) = print(io, "Hist: ", o.alg) OnlineStatsBase._merge!(o::WeightedAdaptiveHist, o2::WeightedAdaptiveHist) = _merge!(o.alg, o2.alg) function OnlineStatsBase.value(o::WeightedAdaptiveHist) (midpoints(o), counts(o)) end function Base.extrema(o::WeightedAdaptiveHist) mids, counts = value(o) inds = findall(x->x!=0, counts) # filter out zero weights mids[inds[1]], mids[inds[end]] end function Statistics.quantile(o::WeightedAdaptiveHist, p = [0, .25, .5, .75, 1]) mids, counts = value(o) inds = findall(x->x!=0, counts) # filter out zero weights quantile(mids[inds], fweights(counts[inds]), p) end function weightsum(o::WeightedAdaptiveHist) nobs(o) end #-----------------------------------------------------------------------# WeightedAdaptiveBins struct WeightedAdaptiveBins{T} <: WeightedHistAlgorithm{T} value::Vector{Pair{T, T}} b::Int ex::Extrema{T} function WeightedAdaptiveBins{T}(value = Pair{T, T}[], b = 10, ex = Extrema(T)) where T new{T}(value, b, ex) end end Base.copy(o::T) where T <: WeightedAdaptiveBins = T(copy(o.value), copy(o.b), copy(o.ex)) make_alg(T::Type, b::Int) = WeightedAdaptiveBins{T}(Pair{T, T}[], b, Extrema(T)) make_alg(b::Int) = WeightedAdaptiveBins{Float64}(Pair{Float64, Float64}[], b, Extrema(Float64)) midpoints(o::WeightedAdaptiveBins) = first.(o.value) counts(o::WeightedAdaptiveBins) = last.(o.value) OnlineStatsBase.nobs(o::WeightedAdaptiveBins) = isempty(o.value) ? 0 : sum(last, o.value) function Base.:(==)(a::T, b::T) where {T<:WeightedAdaptiveBins} (a.value == b.value) && (a.b == b.b) && (a.ex == b.ex) end Base.extrema(o::WeightedAdaptiveHist{<:Any, <:WeightedAdaptiveBins}) = extrema(o.alg.ex) # Doesn't happen with weighted stats OnlineStatsBase._fit!(o::WeightedAdaptiveBins, y::Number, w::Number) = _fit!(o, Pair(y, w)) function OnlineStatsBase._fit!(o::WeightedAdaptiveBins{T}, y::Pair) where T y2 = convert(Pair{T, T}, y) fit!(o.ex, first(y2)) v = o.value i = searchsortedfirst(v, y2) insert!(v, i, y2) if length(v) > o.b # find minimum difference i = 0 mindiff = T(Inf) for k in 1:(length(v) - 1) @inbounds diff = first(v[k + 1]) - first(v[k]) if diff < mindiff mindiff = diff i = k end end # merge bins i, i+1 q2, k2 = v[i + 1] if k2 > 0 q1, k1 = v[i] k3 = k1 + k2 v[i] = Pair(smooth(q1, q2, k2 / k3), k3) end deleteat!(o.value, i + 1) end end function OnlineStatsBase._merge!(o::T, o2::T) where {T <: WeightedAdaptiveBins} for v in o2.value _fit!(o, v) end fit!(o.ex, extrema(o2.ex)) end function Base.getindex(o::WeightedAdaptiveBins, i) if i == 0 return Pair(minimum(o.ex), 0) elseif i == (length(o.value) + 1) return Pair(maximum(o.ex), 0) else return o.value[i] end end # based on linear interpolation function pdf(o::WeightedAdaptiveBins, x::Number) v = o.value if x ≤ minimum(o.ex) return 0.0 elseif x ≥ maximum(o.ex) return 0.0 else i = searchsortedfirst(v, Pair(x, 0.0)) x1, y1 = o[i - 1] x2, y2 = o[i] return smooth(y1, y2, (x - x1) / (x2 - x1)) / area(o) end end function cdf(o::WeightedAdaptiveBins, x::Number) if x ≤ minimum(o.ex) return 0.0 elseif x ≥ maximum(o.ex) return 1.0 else i = searchsortedfirst(o.value, Pair(x, 0.0)) x1, y1 = o[i - 1] x2, y2 = o[i] w = x - x1 h = smooth(y1, y2, (x2 - x) / (x2 - x1)) return (area(o, i-2) + w * h) / area(o) end end function area(o::WeightedAdaptiveBins, ind = length(o.value)) out = 0.0 for i in 1:ind w = first(o[i+1]) - first(o[i]) h = (last(o[i+1]) + last(o[i])) / 2 out += h * w end out end
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
1714
abstract type WeightedOnlineStat{T} <: OnlineStat{T} end using OnlineStats: fweights meanweight(o::WeightedOnlineStat) = o.W weightsum(o::WeightedOnlineStat) = meanweight(o) * nobs(o) Base.eltype(o::WeightedOnlineStat{T}) where T = T ############################################################## # Define our own interface so that it accepts two inputs. ############################################################## function OnlineStatsBase.fit!(o::WeightedOnlineStat, xi::Number, wi::Number) _fit!(o, xi, wi) return o end OnlineStatsBase.fit!(o::WeightedOnlineStat, xi::Missing, wi::Number) = o OnlineStatsBase.fit!(o::WeightedOnlineStat, xi::Number, wi::Missing) = o # The missing cases in x are dealt with in the dispatch of _fit! function OnlineStatsBase.fit!(o::WeightedOnlineStat{VectorOb}, x::VectorOb, w::Number) _fit!(o, x, w) return o end OnlineStatsBase.fit!(o::WeightedOnlineStat{VectorOb}, xi::VectorOb, wi::Missing) = o function OnlineStatsBase.fit!(o::WeightedOnlineStat, y, w::AbstractVector) for (yy, ww) in zip(y, w) fit!(o, yy, ww) end o end OnlineStatsBase.fit!(o::WeightedOnlineStat, x::TwoThings) = fit!(o, x[1], x[2]) OnlineStatsBase.fit!(o::WeightedOnlineStat{VectorOb}, x::AbstractMatrix, w::AbstractVector) = fit!(o, eachrow(x), w) function OnlineStatsBase.merge!(o::WeightedOnlineStat, o2::WeightedOnlineStat) (weightsum(o) > 0 || weightsum(o2) > 0) && _merge!(o, o2) o end function Base.show(io::IO, o::WeightedOnlineStat) print(io, name(o, false, false), ": ") print(io, "∑wᵢ=") show(IOContext(io, :compact => true), weightsum(o)) print(io, " | value=") show(IOContext(io, :compact => true), value(o)) end
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
1212
""" WeightedMean(T = Float64) Simple weighted mean, tracked as type `T`. # Example: o = fit!(WeightedMean(), rand(100), rand(100)) sum(o) mean(o) """ mutable struct WeightedMean{T} <: WeightedOnlineStat{T} μ::T W::T n::Int function WeightedMean{T}(μ = T(0), W = T(0), n = 0) where T new{T}(T(μ), T(W), Int(n)) end end WeightedMean(μ::T, W::T, n::Int) where T = WeightedMean{T}(μ, W, n) WeightedMean(::Type{T}) where T = WeightedMean(T(0), T(0), 0) WeightedMean() = WeightedMean(Float64) function OnlineStatsBase._fit!(o::WeightedMean{T}, x, w) where T xx = convert(T, x) ww = convert(T, w) o.n += 1 o.W = smooth(o.W, ww, T(1) / o.n) o.μ = smooth(o.μ, xx, ww / (o.W * o.n)) o end function OnlineStatsBase._merge!(o::WeightedMean{T}, o2::WeightedMean) where T o2_W = convert(T, o2.W) o2_μ = convert(T, o2.μ) o.n += o2.n o.W = smooth(o.W, o2_W, o2.n / o.n) o.μ = smooth(o.μ, o2_μ, (o2_W * o2.n) / (o.W * o.n)) o end OnlineStatsBase.value(o::WeightedMean) = o.μ Statistics.mean(o::WeightedMean) = value(o) Base.sum(o::WeightedMean) = mean(o) * weightsum(o) Base.copy(o::WeightedMean) = WeightedMean(o.μ, o.W, o.n)
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
1044
""" WeightedSum(T = Float64) Simple weighted sum, tracked as type `T`. # Example: o = fit!(WeightedSum(), rand(100), rand(100)) sum(o) """ mutable struct WeightedSum{T} <: WeightedOnlineStat{T} ∑::T W::T n::Int function WeightedSum{T}(∑ = T(0), W = T(0), n = 0) where T new{T}(T(∑), T(W), Int(n)) end end WeightedSum(∑::T, W::T, n::Int) where T = WeightedSum{T}(∑, W, n) WeightedSum(::Type{T}) where T = WeightedSum(T(0), T(0), 0) WeightedSum() = WeightedSum(Float64) function WeightedOnlineStats._fit!(o::WeightedSum{T}, x, w) where T ww = convert(T, w) xx = convert(T, x) o.n += 1 o.W += smooth(o.W, ww, T(1) / o.n) o.∑ += xx * ww o end function WeightedOnlineStats._merge!(o::WeightedSum{T}, o2::WeightedSum) where T o.n += o2.n o.W = smooth(o.W, convert(T, o2.W), convert(T, o2.n / o.n)) o.∑ += convert(T, o2.∑) o end OnlineStatsBase.value(o::WeightedSum) = o.∑ Base.sum(o::WeightedSum) = value(o) Base.copy(o::WeightedSum) = WeightedSum(o.∑, o.W, o.n)
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
2975
""" WeightedVariance(T = Float64) Simple weighted variance, tracked as type `T`. # Example: o = fit!(WeightedVariance(), rand(100), rand(100)) sum(o) mean(o) var(o) std(o) """ mutable struct WeightedVariance{T} <: WeightedOnlineStat{T} μ::T σ2::T W::T W2::T n::Int function WeightedVariance{T}( μ = T(0), σ2 = T(0), W = T(0), W2 = T(0), n = 0 ) where T new{T}(T(μ), T(σ2), T(W), T(W2), Int(n)) end end WeightedVariance(μ::T, σ2::T, W::T, W2::T, n::Int) where T = WeightedVariance{T}(μ, σ2, W, W2, n) WeightedVariance(::Type{T}) where T = WeightedVariance(T(0), T(0), T(0), T(0), 0) WeightedVariance() = WeightedVariance(Float64) function OnlineStatsBase._fit!(o::WeightedVariance{T}, x, w) where T xx = convert(T, x) ww = convert(T, w) o.n += 1 γ1 = T(1) / o.n o.W = smooth(o.W, ww, γ1) o.W2 = smooth(o.W2, ww * ww, γ1) γ = ww / (o.W * o.n) μ = o.μ o.μ = smooth(o.μ, xx, γ) o.σ2 = smooth(o.σ2, (xx - o.μ) * (xx - μ), γ) return o end function OnlineStatsBase._merge!( o::WeightedVariance{T}, o2::WeightedVariance ) where T o2_μ = convert(T, o2.μ) o2_σ2 = convert(T, o2.σ2) o2_W = convert(T, o2.W) o2_W2 = convert(T, o2.W2) n = o.n + o2.n W = smooth(o.W, o2_W, o2.n / n) γ1 = (o.W * o.n) / (W * n) γ2 = (o2_W * o2.n) / (W * n) μ = smooth(o.μ, o2_μ, γ2) # o.σ2 = # γ1 * ( o.σ2 + o.μ ^ 2) + # γ2 * (o2_σ2 + o2_μ ^ 2) - # μ ^ 2 o.σ2 = γ1 * ( o.σ2 + (o.μ - μ) ^ 2) + γ2 * (o2_σ2 + (o2_μ - μ) ^ 2) o.n = n o.μ = μ o.W = W o.W2 = OnlineStats.smooth(o.W2, o2_W2, o2.n / o.n) ########################################### # μ = o.μ # # γ = o2_W / (o2_W + o.W) # δ = o2_μ - o.μ # # o.σ2 = OnlineStats.smooth(o.σ2, o2_σ2, γ) + (δ ^ 2) * γ * (1.0 - γ) # o.μ = OnlineStats.smooth(o.μ, o2_μ, γ) # # o.σ2 = o.σ2 + (o.W + o2_W) * (μ) # # o.W += o2_W # o.W2 += o2_W2 return o end OnlineStatsBase.value(o::WeightedVariance) = o.σ2 Base.sum(o::WeightedVariance) = mean(o) * meanweight(o) * nobs(o) Statistics.mean(o::WeightedVariance) = o.μ function Statistics.var( o::WeightedVariance; corrected = true, weight_type = :analytic ) if corrected if weight_type == :analytic value(o) / (1 - (o.W2 * nobs(o)) / (weightsum(o) ^ 2)) elseif weight_type == :frequency value(o) / (weightsum(o) - 1) * weightsum(o) elseif weight_type == :probability error("If you need this, please make a PR or open an issue") else throw(ArgumentError("weight type $weight_type not implemented")) end else value(o) end end Statistics.std(o::WeightedVariance; kw...) = sqrt.(var(o; kw...)) Base.copy(o::WeightedVariance) = WeightedVariance(o.μ, o.σ2, o.W, o.W2, o.n)
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
1225
# using Revise # using Pkg # cd("..") # Pkg.activate(".") using Test using WeightedOnlineStats import OnlineStatsBase: eachcol, eachrow using StatsBase import OnlineStats: Extrema using Statistics using Random using MultivariateStats Random.seed!(124) l = 1000 x = rand(l); xmis = convert(Array{Union{Float64,Missing}}, x); x2 = rand(l, 5) x2mis = convert(Array{Union{Float64,Missing}}, x2) x2mis[end, 1] = missing x2mis[end-1, 1] = missing w = rand(l); wmis = convert(Array{Union{Float64,Missing}}, w); wmis[end] = missing wmis[end-2] = missing Base.isapprox(x::Tuple, y::Tuple) = reduce(&, map((a, b) -> a ≈ b, x, y)) missing_to_nan(x::Array{Union{Missing,T}}) where {T} = map(y -> y === missing ? T(NaN) : y, x) function test_fit( T::Type{<:WeightedOnlineStats.WeightedOnlineStat{S}}, data, weights, unpack_fun, jfun ) where {S} l = length(data) @assert l == length(weights) o = T() for (xi, wi) in zip(data, weights) fit!(o, xi, wi) end @test unpack_fun(o) ≈ jfun(data, weights) @test eltype(unpack_fun(o)) == eltype(o) end include("test_hist.jl") include("test_sum.jl") include("test_mean.jl") include("test_var.jl") include("test_cov.jl") include("test_pca.jl")
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
4801
@testset "WeightedCovMatrix fit!" begin s, m, c = (map(x -> sum(x .* w), eachcol(x2)), map(x -> mean(x, weights(w)), eachcol(x2)), cov(x2, aweights(w), corrected = true)) ma, ca = map(x -> mean(x, weights(w)), eachcol(x2)), cov(x2, aweights(w), corrected = true) mf, cf = map(x -> mean(x, weights(w)), eachcol(x2)), cov(x2, fweights(w), corrected = true) mp, cp = map(x -> mean(x, weights(w)), eachcol(x2)), cov(x2, pweights(w), corrected = true) o = WeightedCovMatrix() for i in 1:l fit!(o, x2[i, :], w[i]) end o sfor, mfor, cfor = sum(o), mean(o), cov(o) o_32 = WeightedCovMatrix(Float32) for i in 1:l fit!(o_32, x2[i, :], w[i]) end o_32 sfor_32, mfor_32, cfor_32 = sum(o_32), mean(o_32), cov(o_32) sval, mval, cval = fit!(WeightedCovMatrix(), x2, w) |> x -> (sum(x), mean(x), cov(x)) svalt, mvalt, cvalt = fit!(WeightedCovMatrix(), eachcol(permutedims(x2)), w) |> x -> (sum(x), mean(x), cov(x)) szip, mzip, czip = fit!(WeightedCovMatrix(), zip(eachrow(x2), w)) |> x -> (sum(x), mean(x), cov(x)) mvala, cvala = fit!(WeightedCovMatrix(), x2, w) |> x -> (mean(x), cov(x, corrected = true, weight_type = :analytic)) mvalf, cvalf = fit!(WeightedCovMatrix(), x2, w) |> x -> (mean(x), cov(x, corrected = true, weight_type = :frequency)) @test_throws ArgumentError fit!(WeightedCovMatrix(), x2, w) |> x -> (mean(x), cov(x, corrected = true, weight_type = :something)) @test c ≈ czip @test c ≈ cfor @test c ≈ cfor_32 @test c ≈ cval @test c ≈ cvalt @test m ≈ mzip @test m ≈ mfor @test m ≈ mfor_32 @test m ≈ mval @test m ≈ mvalt @test ca ≈ cvala @test cf ≈ cvalf @test ma ≈ mvala @test mf ≈ mvalf @test s ≈ sfor @test s ≈ sfor_32 @test s ≈ sval @test s ≈ svalt @test s ≈ szip # After implementing :probability, these should pass/not throw any more: @test_throws ErrorException mvalp, vvalp = fit!(WeightedCovMatrix(), x2, w) |> x -> (mean(x), cov(x, corrected = true, weight_type = :probability)) @test_broken vp ≈ vvalp @test_broken mp ≈ mvalp @test eltype(o) == Float64 @test eltype(o_32) == Float32 oold = copy(o) fit!(o, [missing, 1, 2, 3, 4], 1) @test o == oold fit!(o, [1, 2, 3, 4, 5], missing) @test o == oold # issue #29 fit!(o, eachrow([missing 1 2 3 4 missing 2 3 4 5]), [1.0, 1.0]) @test o == oold end @testset "WeightedCovMatrix merge!" begin c = cov(x2, aweights(w), corrected = true) wc = fit!(WeightedCovMatrix(), x2, w) oc = map(eachrow(x2), w) do xi, wi fit!(WeightedCovMatrix(), xi, wi) end rc = reduce(merge!, deepcopy(oc)) rc2 = merge!( fit!(WeightedCovMatrix(), x2[1:end÷2, :], w[1:end÷2]), fit!(WeightedCovMatrix(), x2[end÷2+1:end, :], w[end÷2+1:end])) rc_32 = reduce(merge!, deepcopy(oc), init = WeightedCovMatrix(Float32)) rc2_32 = merge!( fit!(WeightedCovMatrix(Float32), x2[1:end÷2, :], w[1:end÷2]), fit!(WeightedCovMatrix(), x2[end÷2+1:end, :], w[end÷2+1:end])) @test rc.b ≈ wc.b @test rc.C ≈ wc.C @test rc.W ≈ wc.W @test rc.W2 ≈ wc.W2 @test rc2.b ≈ wc.b @test rc2.C ≈ wc.C @test rc2.W ≈ wc.W @test rc2.W2 ≈ wc.W2 @test cov(rc) ≈ c @test cov(rc2) ≈ c @test rc_32.b ≈ wc.b @test rc_32.C ≈ wc.C @test rc_32.W ≈ wc.W @test rc_32.W2 ≈ wc.W2 @test rc2_32.b ≈ wc.b @test rc2_32.C ≈ wc.C @test rc2_32.W ≈ wc.W @test rc2_32.W2 ≈ wc.W2 @test cov(rc_32) ≈ c @test cov(rc2_32) ≈ c @test eltype(rc) == Float64 @test eltype(rc2) == Float64 @test eltype(rc_32) == Float32 @test eltype(rc2_32) == Float32 end @testset "WeightedCovMatrix copy" begin o = fit!(WeightedCovMatrix(), x2, w) o2 = copy(o) @test o !== o2 @test o.C !== o2.C @test o.A !== o2.A @test o.b !== o2.b # @test o.W !== o2.W # @test o.W2 !== o2.W2 # @test o.n !== o2.n @test o.C == o2.C @test o.A == o2.A @test o.b == o2.b @test o.W == o2.W @test o.W2 == o2.W2 @test o.n == o2.n end @testset "WeightedCovMatrix constructor" begin @test WeightedCovMatrix{Float64}() == WeightedCovMatrix() @test WeightedCovMatrix{Float32}() == WeightedCovMatrix(Float32) @test WeightedCovMatrix() == WeightedCovMatrix(zeros(Float64, 0, 0), zeros(Float64, 0, 0), zeros(Float64, 0), 0.0, 0.0, 0) @test convert(WeightedCovMatrix{Float32}, WeightedCovMatrix()) == WeightedCovMatrix{Float32}() end
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
4936
using Statistics import OnlineStats d1, w1 = fill(1, 40), fill(4, 40) d2, w2 = fill(2, 30), fill(3, 30) d3, w3 = fill(3, 20), fill(2, 20) d4, w4 = fill(4, 10), fill(1, 10) d, wh = vcat(d1, d2, d3, d4), vcat(w1, w2, w3, w4) @testset "WeightedAdaptiveHist fit!" begin h = (unique(d), map(*, sort(collect(keys(countmap(wh))), rev = true), sort(collect(values(countmap(wh))), rev = true) ) ) ws = sum(wh) o = WeightedAdaptiveHist(4) for i in 1:length(d) fit!(o, d[i], wh[i]) end hfor, vsfor = value(o), weightsum(o) hval, vsval = value(fit!(WeightedAdaptiveHist(4), d, wh)), weightsum(fit!(WeightedAdaptiveHist(4), d, wh)) hzip, vszip = value(fit!(WeightedAdaptiveHist(4), zip(d, wh))), weightsum(fit!(WeightedAdaptiveHist(4), zip(d, wh))) @test (h, ws) == (hfor, vsfor) @test (h, ws) == (hval, vsval) @test (h, ws) == (hzip, vszip) end @testset "WeightedAdaptiveHist merge" begin h = (unique(d), map(*, sort(collect(keys(countmap(wh))), rev = true), sort(collect(values(countmap(wh))), rev = true) ) ) ws = sum(wh) oh = map(d, wh) do di, whi fit!(WeightedAdaptiveHist(4), di, whi) end; r = reduce(merge!, oh) r2 = merge!( fit!(WeightedAdaptiveHist(4), d[1:end ÷ 2], wh[1:end ÷ 2]), fit!(WeightedAdaptiveHist(4), d[end ÷ 2 + 1:end], wh[end ÷ 2 + 1:end]) ) rh, rws = value(r), weightsum(r) rh2, rws2 = value(r2), weightsum(r2) @test (h, ws) == (rh, rws) @test (h, ws) == (rh2, rws2) end @testset "WeightedAdaptiveHist copy" begin o1 = WeightedAdaptiveHist(20) o2 = copy(o1) @test o1 !== o2 @test o2.alg.value !== o1.alg.value # @test o2.alg.b !== o1.alg.b @test o2.alg.ex !== o1.alg.ex end @testset "WeightedAdaptiveHist constructor" begin @test WeightedAdaptiveHist{WeightedAdaptiveBins{Float64}}( WeightedAdaptiveBins{Float64}( Pair{Float64, Float64}[], 20, Extrema(Float64) ) ) == WeightedAdaptiveHist(20) @test WeightedAdaptiveHist{WeightedAdaptiveBins{Float32}}( WeightedAdaptiveBins{Float32}( Pair{Float32, Float32}[], 20, Extrema(Float32) ) ) == WeightedAdaptiveHist(Float32, 20) @test WeightedAdaptiveHist(20) == WeightedAdaptiveHist(Float64, 20) end @testset "WeightedHist" begin @testset "fit!" begin h = WeightedHist(-3:1:1) fit!(h, -2.5,1.3) @test h.counts == [1,0,0,0] @test h.meanw == [1.3,0,0,0] fit!(h, (-2.1, 1.0)) @test value(h).y == [2.3, 0,0,0] @test h.counts == [2,0,0,0] @test h.meanw == [1.15,0,0,0] fit!(h, (-20, 2.0)) @test value(h).y == [2.3, 0,0,0] @test h.outcount == [1, 0, 0] @test h.meanwout == [2.0,0,0] fit!(h, 20, 1.7) @test value(h).y == [2.3, 0,0,0] @test h.meanwout == [2.0, 0.0, 1.7] @test h.outcount == [1, 0, 1] fit!(h, -0.1, 1.1) @test value(h).y == [2.3, 0,1.1,0] @test h.edges === -3:1:1 end @testset "merge!" begin h1 = WeightedHist(-2:2:2) fit!(h1, (-1, 5)) fit!(h1, (1, 10)) h1_copy = deepcopy(h1) @test merge!(h1, WeightedHist([-2,0,2])) == h1_copy @test value(merge!(h1_copy, h1)).y == [10, 20.] end @testset "stats" begin h = WeightedHist(-2:2:2) ho = OnlineStats.Hist(-2.:2:2) for _ in 1:rand(1:20) x = randn() fit!(h, x, 1.0) fit!(ho, x) end @test mean(h) ≈ mean(ho) @test std(h) ≈ std(ho) @test median(h) ≈ median(ho) @test nobs(h) ≈ nobs(ho) @test var(h) ≈ var(ho) @test all(extrema(h) .≈ extrema(ho)) end @testset "N-dimensional Hist" begin h = WeightedHist((-2:2:2,0:3:6)) fit!(h,(-1.5,1.5),1.5) @test h.counts == [1 0; 0 0] @test h.meanw == [1.5 0; 0 0] fit!(h,(-0.5,0.2),1.1) @test h.counts == [2 0; 0 0] @test h.meanw == [1.3 0;0 0] fit!(h,(-3.0,0.0),1.5) @test h.counts == [2 0; 0 0] @test h.meanw == [1.3 0;0 0] @test h.outcount == [0 1 0; 0 0 0; 0 0 0] fit!(h,(-10,-10),1.1) @test h.counts == [2 0; 0 0] @test h.meanw == [1.3 0;0 0] @test h.outcount == [1 1 0; 0 0 0; 0 0 0] fit!(h,(1.5,4.5),2.6) @test h.counts == [2 0; 0 1] @test h.meanw == [1.3 0; 0 2.6] @test value(h) == (x=(-2:2:2, 0:3:6),y=[2.6 0;0 2.6]) @test mean(h) == (0.0,3.0) @test var(h) == (1.2380952380952381, 2.785714285714286) @test std(h) == (1.1126972805283737, 1.6690459207925605) @test median(h) == (-1.0, 1.5) @test nobs(h) == 5 @test extrema(h) == ((-1,1),(1.5,4.5)) end end
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
1961
@testset "WeighedMean fit!" begin test_fit(WeightedMean{Float64}, x, w, mean, (x, w) -> mean(x, weights(w))) test_fit(WeightedMean{Float32}, x, w, mean, (x, w) -> mean(x, weights(w))) test_fit(WeightedMean{Float64}, xmis, wmis, mean, (x, w) -> sum(skipmissing(x .* w)) / sum(skipmissing(w))) m = mean(x, weights(w)) s = sum(broadcast(*, w, x)) mval = mean(fit!(WeightedMean(), x, w)) mzip = mean(fit!(WeightedMean(), zip(x, w))) sval = sum(fit!(WeightedMean(), x, w)) szip = sum(fit!(WeightedMean(), zip(x, w))) @test m ≈ mzip @test m ≈ mval @test s ≈ szip @test s ≈ sval m2val = mean(fit!(WeightedMean(Float32), x, w)) m2zip = mean(fit!(WeightedMean(Float32), zip(x, w))) @test m ≈ m2zip @test m ≈ m2val @test typeof(m2val) == Float32 @test typeof(m2zip) == Float32 end @testset "WeighedMean merge!" begin m = mean(x, weights(w)) wm = fit!(WeightedMean(), x, w) |> mean om = map(x, w) do xi, wi fit!(WeightedMean(), xi, wi) end rm = reduce(merge!, om) |> mean rm_32 = reduce(merge!, om, init = WeightedMean(Float32)) |> mean rm2 = merge!( fit!(WeightedMean(), x[1:end÷2], w[1:end÷2]), fit!(WeightedMean(), x[end÷2+1:end], w[end÷2+1:end]) ) |> mean rm2_32 = merge!( fit!(WeightedMean(Float32), x[1:end÷2], w[1:end÷2]), fit!(WeightedMean(), x[end÷2+1:end], w[end÷2+1:end]) ) |> mean @test wm ≈ m @test rm ≈ m @test rm2 ≈ m @test rm_32 ≈ m @test rm2_32 ≈ m @test typeof(rm) == Float64 @test typeof(rm2) == Float64 @test typeof(rm_32) == Float32 @test typeof(rm2_32) == Float32 end @testset "WeightedMean constructor" begin @test WeightedMean{Float64}() == WeightedMean() @test WeightedMean{Float32}() == WeightedMean(Float32) @test WeightedMean() == WeightedMean(0.0, 0.0, 0) @test WeightedMean() == WeightedMean{Float64}(0, 0, 0) end
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
2126
using StatsBase """ the eigenvectors have arbitrary directions. """ function test_proj(v1, v2; atol = 0.0) all(isapprox(v1[:, i], v2[:, i], atol = atol) || isapprox(v1[:, i], -v2[:, i], atol = atol) for i in 1:size(v1, 2)) end @testset "PCA" begin x = rand(4, 100) w = ones(100) zsm = fit(ZScoreTransform, x, dims = 2) zm = fit(ZScoreTransform, x, scale = false, dims = 2) c = fit!(WeightedCovMatrix(), x', w) t, p = pca(c, cov_pca = true) p6 = fit( PCA, StatsBase.transform(zm, x), method = :cov, maxoutdim = 4, pratio = 1.0, mean = nothing ) @test t.mean ≈ zm.mean @test t.scale ≈ zm.scale @test isapprox(p.prinvars, p6.prinvars, atol = 1.0e-2) @test isapprox(p.tprinvar, p6.tprinvar, atol = 1.0e-2) @test isapprox(p.tvar, p6.tvar, atol = 1.0e-2) @test test_proj(p.proj, p6.proj) # @test x === StatsBase.transform((), x) # @test x === StatsBase.reconstruct((), x) # @test x === StatsBase.transform([], x) # @test x === StatsBase.reconstruct([], x) y = StatsBase.transform(t, x) x2 = StatsBase.reconstruct(t, y) @test isapprox(x2, x) x2 = StatsBase.transform(t, x) y = StatsBase.predict(p, x2) x3 = MultivariateStats.reconstruct(p, y) x4 = StatsBase.reconstruct(t, x3) @test isapprox(x4, x) t, p = pca(c, cov_pca = false) p4 = fit( PCA, StatsBase.transform(zsm, x), method = :cov, maxoutdim = 4, pratio = 1.0, mean = 0 ) @test t.mean ≈ zsm.mean @test isapprox(t.scale, zsm.scale, atol = 1.0e-2) @test isapprox(p.prinvars, p4.prinvars, atol = 1.0e-2) @test isapprox(p.tprinvar, p4.tprinvar, atol = 1.0e-2) @test isapprox(p.tvar, p4.tvar, atol = 1.0e-2) @test test_proj(p.proj, p4.proj) y = StatsBase.transform(t, x) x2 = StatsBase.reconstruct(t, y) @test isapprox(x2, x) x2 = StatsBase.transform(t, x) y = StatsBase.predict(p, x2) x3 = MultivariateStats.reconstruct(p, y) x4 = StatsBase.reconstruct(t, x3) @test isapprox(x4, x) end
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
1737
@testset "WeightedSum fit!" begin test_fit(WeightedSum{Float64}, x, w, sum, (x, w) -> sum(x .* w)) test_fit(WeightedSum{Float32}, x, w, sum, (x, w) -> sum(x .* w)) test_fit(WeightedSum{Float64}, xmis, wmis, sum, (x, w) -> sum(skipmissing(x .* w))) s = sum(broadcast(*, x, w)) szip = sum(fit!(WeightedSum(), zip(x, w))) sval = sum(fit!(WeightedSum(), x, w)) s2val = sum(fit!(WeightedSum(Float32), x, w)) s2zip = sum(fit!(WeightedSum(Float32), zip(x, w))) @test s ≈ szip @test s ≈ sval @test s ≈ s2zip @test s ≈ s2val @test typeof(s2val) == Float32 @test typeof(s2zip) == Float32 end @testset "WeightedSum merge!" begin s = sum(broadcast(*, x, w)) smap = map(x, w) do xi, wi fit!(WeightedSum(), xi, wi) end; rs = reduce(merge!, smap) |> sum rs2 = merge!( fit!(WeightedSum(), x[1:end ÷ 2], w[1:end ÷ 2]), fit!(WeightedSum(), x[end ÷ 2 + 1:end], w[end ÷ 2 + 1:end]) ) |> sum # Float32 smap2 = map(x, w) do xi, wi fit!(WeightedSum(), xi, wi) end; rs_32 = reduce(merge!, smap2, init = WeightedSum(Float32)) |> sum rs2_32 = merge!( fit!(WeightedSum(Float32), x[1:end ÷ 2], w[1:end ÷ 2]), fit!(WeightedSum(), x[end ÷ 2 + 1:end], w[end ÷ 2 + 1:end]) ) |> sum @test rs ≈ s @test rs2 ≈ s @test rs_32 ≈ s @test rs2_32 ≈ s @test typeof(rs) == Float64 @test typeof(rs2) == Float64 @test typeof(rs_32) == Float32 @test typeof(rs2_32) == Float32 end @testset "WeightedSum constructor" begin @test WeightedSum{Float64}() == WeightedSum() @test WeightedSum{Float32}() == WeightedSum(Float32) @test WeightedSum() == WeightedSum(0.0, 0.0, 0) end
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
4246
@testset "WeightedVariance fit!" begin test_fit(WeightedVariance{Float64}, x, w, x -> (var(x), mean(x)), (x, w) -> (var(x, aweights(w), corrected = true), mean(x, weights(w)))) test_fit(WeightedVariance{Float32}, x, w, x -> (var(x), mean(x)), (x, w) -> (var(x, aweights(w), corrected = true), mean(x, weights(w)))) test_fit(WeightedVariance{Float64}, xmis, wmis, x -> (var(x), mean(x)), (x, w) -> begin ## doesn't work: # idx = findall((x) -> !ismissing(x[1]) & !ismissing(x[2]), zip(x, w)) idx = findall(.!ismissing(x) .& .!ismissing.(w)) xx = Float64.(x[idx]) ww = Float64.(w[idx]) (var(xx, aweights(ww), corrected = true), mean(xx, aweights(ww))) end ) s, m, v = sum(x .* w), mean(x, weights(w)), var(x, aweights(w), corrected = true) sa, ma, va = sum(x .* w), mean(x, weights(w)), var(x, aweights(w), corrected = true) sf, mf, vf = sum(x .* w), mean(x, weights(w)), var(x, fweights(w), corrected = true) sp, mp, vp = sum(x .* w), mean(x, weights(w)), var(x, pweights(w), corrected = true) sval, mval, vval = fit!(WeightedVariance(), x, w) |> x -> (sum(x), mean(x), var(x)) szip, mzip, vzip = fit!(WeightedVariance(), zip(x, w)) |> x -> (sum(x), mean(x), var(x)) svala, mvala, vvala = fit!(WeightedVariance(), x, w) |> x -> (sum(x), mean(x), var(x, corrected = true, weight_type = :analytic)) svalf, mvalf, vvalf = fit!(WeightedVariance(), x, w) |> x -> (sum(x), mean(x), var(x, corrected = true, weight_type = :frequency)) @test_throws ArgumentError fit!(WeightedVariance(), x, w) |> x -> (sum(x), mean(x), var(x, corrected = true, weight_type = :something)) @test v ≈ vzip @test v ≈ vval @test m ≈ mzip @test m ≈ mval @test va ≈ vvala @test vf ≈ vvalf @test ma ≈ mvala @test mf ≈ mvalf @test s ≈ sval @test s ≈ szip @test s ≈ svala @test s ≈ svalf # After implementing :probability, these should pass/not throw any more: @test_throws ErrorException mvalp, vvalp = fit!(WeightedVariance(), x, w) |> x -> (mean(x), var(x, corrected = true, weight_type = :probability)) @test_broken vp ≈ vvalp @test_broken mp ≈ mvalp end @testset "WeighedVariance merge!" begin v = var(x, aweights(w), corrected = true) wv = fit!(WeightedVariance(), x, w) ov = map(x, w) do xi, wi fit!(WeightedVariance(), xi, wi) end; rv = reduce(merge!, deepcopy(ov)) rv2 = merge!( fit!(WeightedVariance(), x[1:end ÷ 2], w[1:end ÷ 2]), fit!(WeightedVariance(), x[end ÷ 2 + 1:end], w[end ÷ 2 + 1:end])) rv_32 = reduce(merge!, deepcopy(ov), init = WeightedVariance(Float32)) rv2_32 = merge!( fit!(WeightedVariance(Float32), x[1:end ÷ 2], w[1:end ÷ 2]), fit!(WeightedVariance(), x[end ÷ 2 + 1:end], w[end ÷ 2 + 1:end])) @test rv.μ ≈ wv.μ @test rv.σ2 ≈ wv.σ2 @test rv.W ≈ wv.W @test rv.W2 ≈ wv.W2 @test rv2.μ ≈ wv.μ @test rv2.σ2 ≈ wv.σ2 @test rv2.W ≈ wv.W @test rv2.W2 ≈ wv.W2 @test var(rv) ≈ v @test var(rv2) ≈ v @test var(rv_32) ≈ v @test var(rv2_32) ≈ v @test mean(rv_32) ≈ wv.μ @test mean(rv2_32) ≈ wv.μ @test eltype(rv) == Float64 @test eltype(rv2) == Float64 @test eltype(rv_32) == Float32 @test eltype(rv2_32) == Float32 end @testset "WeightedVariance copy" begin o = fit!(WeightedVariance(), x2, w) o2 = copy(o) @test o !== o2 # @test o.μ !== o.μ # @test o.σ2 !== o.σ2 # @test o.W !== o2.W # @test o.W2 !== o2.W2 # @test o.n !== o2.n @test o.μ == o2.μ @test o.σ2 == o2.σ2 @test o.W == o2.W @test o.W2 == o2.W2 @test o.n == o2.n end @testset "WeightedVariance constructor" begin @test WeightedVariance{Float64}() == WeightedVariance() @test WeightedVariance{Float32}() == WeightedVariance(Float32) @test WeightedVariance() == WeightedVariance(0.0, 0.0, 0.0, 0.0, 0) @test WeightedVariance() == WeightedVariance{Float64}(0, 0, 0, 0, 0) end
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
code
266
# only push coverage from one bot get(ENV, "TRAVIS_OS_NAME", nothing) == "linux" || exit(0) get(ENV, "TRAVIS_JULIA_VERSION", nothing) == "1.3" || exit(0) using Coverage cd(joinpath(@__DIR__, "..", "..")) do Codecov.submit(Codecov.process_folder()) end
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
docs
199
# WeightedOnlineStats.jl v0.3.0 * Renamed `WeightedHist` to `WeightedAdaptiveHist` and added `WeightedHist` similar to `OnlineStats.Hist` (Thanks Jan Weidner!) * Removed support for `Julia 0.7`.
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
docs
1190
# `WeightedOnlineStats.jl` [![DOI](https://zenodo.org/badge/156201284.svg)](https://zenodo.org/badge/latestdoi/156201284) [![CI](https://github.com/gdkrmr/WeightedOnlineStats.jl/actions/workflows/CI.yml/badge.svg)](https://github.com/gdkrmr/WeightedOnlineStats.jl/actions/workflows/CI.yml) [![codecov.io](http://codecov.io/github/gdkrmr/WeightedOnlineStats.jl/coverage.svg?branch=master)](http://codecov.io/github/gdkrmr/WeightedOnlineStats.jl?branch=master) An extension of `OnlineStatsBase.jl` that supports proper statistical weighting and arbitrary numerical precision. # Usage ```julia using WeightedOnlineStats values = rand(100) weights = rand(100) # fit using arrays: o1 = fit!(WeightedMean(), values, weights) # fit using an iterator that returns a tuple (value, weight): o2 = fit!(WeightedMean(), zip(values, weights)) # fit single values at a time: o3 = WeightedMean() for i in 1:length(values) fit!(o3, values[i], weights[i]) end mean(o1) mean(o2) mean(o3) ``` # Statistics `WeightedOnlineStats.jl` currently implements the following Statistics: - `WeightedSum` - `WeightedMean` - `WeightedVariance` - `WeightedCovMatrix` - `WeightedHist` - `WeightedAdaptiveHist`
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
docs
71
# API ```@index ``` ```@autodocs Modules = [WeightedOnlineStats] ```
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.6.3
97af6ba86935292d5ed4a76cfee6e47d7ce02366
docs
387
# WeightedOnlineStats.jl A version onf OnlineStats.jl allowing observations with custom weights. ## Basics ### Creating ```@repl index using WeightedOnlineStats m = WeightedMean() x = randn(100); w = randn(100); ``` ### Updating ```@repl index fit!(m, x, w) ``` ### Merging ```@repl index m2 = WeightedMean() x2 = rand(100); w2 = rand(100); fit!(m2, x2, w2) merge!(m, m2) ```
WeightedOnlineStats
https://github.com/gdkrmr/WeightedOnlineStats.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
598
import Pkg Pkg.activate(@__DIR__) using LiveServer servedocs(; literate_dir = joinpath("docs", "src", "literate"), skip_dirs = [ joinpath("docs", "src", "notebooks"), joinpath("docs", "src", "tutorials"), joinpath("docs", "src", "applications"), ], skip_files = [ joinpath("docs", "src", "api", "logical.md"), joinpath("docs", "src", "api", "memberships.md"), joinpath("docs", "src", "assets", "indigo.css"), ], launch_browser = true, verbose = true)
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
5208
ENV["GKSwstype"] = "100" const IS_CI = get(ENV, "CI", "false") == "true" import Pkg Pkg.activate(@__DIR__) using Documenter using DocThemeIndigo using InteractiveUtils using FuzzyLogic using Literate ############################### # GENERATE LITERATE NOTEBOOKS # ############################### const jldir = joinpath(@__DIR__, "src", "literate") # input directory for literate scripts. const mddir = joinpath(@__DIR__, "src") # output directory for markdown files. const nbdir = joinpath(@__DIR__, "src", "notebooks") # output directory for notebooks. # fix edit links (only locally) function fix_edit_link(content) replace(content, "EditURL = \"<unknown>" => "EditURL = \"https://github.com/lucaferranti/FuzzyLogic.jl/blob/main") end # Adds link from markdown to notebook. # Points to local path locally and to nbviewer when deployed. notebook_link(file) = content -> notebook_link(file, content) function notebook_link(file, content) root = IS_CI ? "@__NBVIEWER_ROOT_URL__" : "https://nbviewer.org/github/lucaferranti/FuzzyLogic.jl/blob/gh-pages/dev" path = joinpath(root, "notebooks", replace(file, ".jl" => ".ipynb")) note = """!!! tip "Try it yourself!"\n Read this as Jupyter notebook [here]($path)""" replace(content, "DOWNLOAD_NOTE" => note) end for (root, _, files) in walkdir(jldir), file in files endswith(file, ".jl") || continue ipath = joinpath(root, file) opath = splitdir(replace(ipath, jldir => mddir))[1] Literate.markdown(ipath, opath; preprocess = notebook_link(file), postprocess = IS_CI ? identity : fix_edit_link, credit = false) Literate.notebook(ipath, nbdir; execute = IS_CI, credit = false) end ################### # CREATE API DOCS # ################### function generate_memberships() mfs = subtypes(FuzzyLogic.AbstractMembershipFunction) open(joinpath(@__DIR__, "src", "api", "memberships.md"), "w") do f write(f, """```@setup memberships using FuzzyLogic using Plots ``` # Membership functions """) for mf in mfs sec = string(mf)[1:(end - 2)] * " membership function" write(f, """## $sec ```@docs $mf ``` """) docstring = match(r"```julia\nmf = (.+)\n```", string(Docs.doc(mf))) if !isnothing(docstring) mfex = only(docstring.captures) write(f, """ ```@example memberships plot($mfex, 0, 10) # hide ``` """) end end end end function generate_norms() connectives = [ subtypes(FuzzyLogic.AbstractAnd), subtypes(FuzzyLogic.AbstractOr), subtypes(FuzzyLogic.AbstractImplication), ] titles = ["Conjuction", "Disjunction", "Implication"] open(joinpath(@__DIR__, "src", "api", "logical.md"), "w") do f write(f, """```@setup logicals using FuzzyLogic using Plots ``` # Logical connectives """) for (t, c) in zip(titles, connectives) write(f, """ ## $t methods """) for ci in c write(f, """ ### $(nameof(ci)) ```@docs $ci ``` ```@example logicals x = y = 0:0.01:1 # hide contourf(x, y, (x, y) -> $ci()(x, y)) # hide ``` """) end end end end # Logical connectives generate_memberships() generate_norms() ############### # CREATE HTML # ############### makedocs(; modules = [FuzzyLogic], authors = "Luca Ferranti", sitename = "FuzzyLogic.jl", doctest = false, checkdocs = :exports, format = Documenter.HTML(; assets = [ DocThemeIndigo.install(FuzzyLogic), "assets/favicon.ico", ], prettyurls = IS_CI, collapselevel = 1, canonical = "https://lucaferranti.github.io/FuzzyLogic.jl"), pages = [ "Home" => "index.md", "Tutorials" => [ "Build a Mamdani inference system" => "tutorials/mamdani.md", "Build a Sugeno inference system" => "tutorials/sugeno.md", "Build a type-2 inference system" => "tutorials/type2.md", ], "Applications" => [ "Edge detection" => "applications/edge_detector.md", ], "API" => [ "Inference system API" => [ "Types" => "api/fis.md", "Logical connectives" => "api/logical.md", "Aggregation methods" => "api/aggregation.md", "Defuzzification methods" => "api/defuzzification.md", ], "Membership functions" => "api/memberships.md", "Reading/Writing" => "api/readwrite.md", "Learning fuzzy models" => "api/genfis.md", "Plotting" => "api/plotting.md", ], "Contributor's Guide" => "contributing.md", "Release notes" => "changelog.md", ]) ########## # DEPLOY # ########## IS_CI && deploydocs(; repo = "github.com/lucaferranti/FuzzyLogic.jl", push_preview = true)
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
115
import Pkg Pkg.activate(@__DIR__) Pkg.develop(Pkg.PackageSpec(path = joinpath(@__DIR__, ".."))) Pkg.instantiate()
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
3962
#= # Fuzzy edge detector This tutorial shows how fuzzy logic can be applied to image processing. It showcases how `FuzzyLogic.jl` seamlessly composes with common Julia image processing libraries and works out-of-the box. This tutorial builds a fuzzy edge detector and it is inspired from the matlab tutorial available [here](https://www.mathworks.com/help/fuzzy/fuzzy-logic-image-processing.html). DOWNLOAD_NOTE ## Introduction We want to design an edge detector. That is, a function that takes an image as input and finds the edges in the image. Our function should produce a new image, with edges highlighted in black and flat areas in white. First, let's load the image processing tools we need in this tutorial. =# using TestImages, ImageFiltering, ImageShow, ImageCore img = Gray.(testimage("house")) #= Next, we need to model our problem. When we cross an edge, we have a transition from a clearly delimited area to another. Hence, a pixel is on an edge if moving in its neighborhood we see some change in intensity. If, on the other hand, in the pixel neighborhood there is no change, then it belongs to a flat area. Hence, to detect edges we need to compute the gradient of the image at each pixel. This can be done using `imgradients` from [ImageFiltering](https://github.com/JuliaImages/ImageFiltering.jl). This function will return two images, one containg the gradient x-component at each pixel, and one containing the y-component at each pixel. For better visualization, these gradient images are renormalized so that their maximum in absolute value is ``1``. =# img_y, img_x = imgradients(img, KernelFactors.sobel) img_y /= Float64(maximum(abs.(img_y))) img_x /= Float64(maximum(abs.(img_x))) img_y #- img_x #= ## Fuzzy system design Now we want to design a fuzzy system that takes as input the gradient x- and y- components and produces as output the intensity of the new image. Particularly, in the output image we want to plot flat areas in white (intensity close to ``1``) and edges in black (intensity close to ``0``). Based on our previous discussion, a pixel belongs to a flat area if it has zero gradient (i.e. both x- and y-components are zero). If the gradient is non-zero (either x- or y-component is non-zero) then it belongs to an edge. Hence for our fuzzy edge detector we can use the following rules - If the gradient x-component is zero and the gradient y-component is zero, then the output intensity is white. - If the gradient x-component is nonzero or the gradient y-compnent is non-zero, then the output intensity is black. Hence, for the input, we will use a single membership function `zero`, which is a sharp Gaussian centered at zero. For the outupt, we have two membership functions, `black` and `white`. Recalling that a black pixel means intensity zero and a white pixel intensity one, we will use for `black` a linear membership function, that decreases from ``1`` to ``0`` as the intensity increases. Similarly, for `white` we can use a linear membership function that increases as the intensity increases. We can now implement and visualize our inference system. =# using FuzzyLogic, Plots fis = @mamfis function edge_detector(dx, dy)::Iout dx := begin domain = -1:1 zero = GaussianMF(0.0, 0.1) end dy := begin domain = -1:1 zero = GaussianMF(0.0, 0.1) end Iout := begin domain = 0:1 black = LinearMF(0.7, 0.0) white = LinearMF(0.1, 1.0) end dx == zero && dy == zero --> Iout == white dx != zero || dy != zero --> Iout == black end plot(fis) #- plot(plot(fis, :dx), plot(fis, :Iout), layout = (1, 2)) #= We are now ready to apply our fuzzy edge detector to the input image. We will create a new image `Iout` and assign to each pixel the intensity value computed with our fuzzy system. =# Iout = copy(img) for idx in eachindex(Iout) Iout[idx] = fis(dx = img_x[idx], dy = img_y[idx])[:Iout] end Iout
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
7272
#= # Build a Mamdani inference system This tutorial gives a general overiew of FuzzyLogic.jl basic functionalities by showing how to implement and use a type-1 Mamdani inference system. DOWNLOAD_NOTE ## Setup To follow the tutorial, you should have [installed Julia](https://julialang.org/downloads/). Next, you can install `FuzzyLogic.jl` with ```julia using Pkg; Pkg.add("FuzzyLogic") ``` ## Building the inference system First, we need to load the library. =# using FuzzyLogic # The Mamdani inference system can be constructed with the [`@mamfis`](@ref) macro. # We will first give a full example and then explain every step. fis = @mamfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = TriangularMF(0, 5, 10) average = TriangularMF(10, 15, 20) generous = TriangularMF(20, 25, 30) end and = ProdAnd or = ProbSumOr implication = ProdImplication service == poor || food == rancid --> tip == cheap service == good --> tip == average service == excellent || food == delicious --> tip == generous aggregator = ProbSumAggregator defuzzifier = CentroidDefuzzifier end #= As you can see, defining a fuzzy inference system with `@mamfis` looks a lot like writing Julia code. Let us now take a closer look at the components. The first line ```julia function tipper(service, food)::tip ``` specifies the basic properties of the system, particularly - the function name `tipper` will be the name of the system - the input arguments `service, food` represent the input variables of the system - the output type annotation `::tip` represents the output variable of the system. If the system has multiple outputs, they should be enclosed in braces, i.e. `::{tip1, tip2}` The next block is the variable specifications block, identified by the `:=` operator. This block is used to specify the domain and membership functions of a variable, for example ```julia service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end ``` The order of the statements inside the `begin ... end` block is irrelevant. - The line `domain = 0:10` sets the domain of the variable to the interval ``[0, 10]``. Note that setting the domain is required - The other lines specify the membership functions of the variable. For example, `poor = GaussianMF(0.0, 1.5)` means that the variable has a Gaussian membership function called `poor` with mean ``0.0`` and stanrdard devisation ``1.5``. A complete list of supported dmembership functions and their parameters can be found in the [Membership functions](@ref) section of the API documentation. Next, we describe rule blocks. A fuzzy relation such as `service is poor` is described with the `==` operator, for example `service == poor`. The *premise* i.e. left-hand side, of the rule can be any logical proposition connecting fuzzy relations with the `&&` (AND) and `||` (OR) operators. The *consequence* i.e. right-hand side, of the rule is a fuzzy relation for the output variable. Premise and consequence are connected with the `-->` operator. For example, the rule ```julia service == poor || food == rancid --> tip == cheap ``` reads *If the service is poor or the food is rancid, then the tip is cheap*. Note that in the premise can be any logical proposition, you can have both `&&` and `||` connectives and you can also have nested propositions. For example, the following is a valid rule ```julia service == poor || food = rancid && service == good ``` The connectives follow Julia precedence rules, so `&&` binds stronger than `||`. If you have multiple outputs, then the consequence should be a tuple, for example ```julia service == poor || food == rancid --> (tip1 == cheap, tip2 == cheap) ``` Finally, assignment lines like ```julia and = ProdAnd ``` are used to set the settings of the inference system. For a Mamdani inference system, the following settings are available - `and`: algorithm to evaluate `&&`. Must be one of the available [Conjuction methods](@ref). Default [`MinAnd`](@ref). - `or`: algorithm to evaluate `||`. Must be one of the available [Disjunction methods](@ref). Default [`MaxOr`](@ref) - `implication`: algorithm to evalute `-->`. Must be one of the available [Implication methods](@ref). Default [`MinImplication`](@ref). - `aggregato`: algorithm to perform outputs aggregation. Must be one of the available [Aggregation methods](@ref). Default [`MaxAggregator`](@ref). - `defuzzifier`: algorithm to perform defuzzification. Must be one of the available [Defuzzification methods](@ref). Default [`CentroidDefuzzifier`](@ref). If one of the above settings is not specified, the corresponding default value is used. Some of the above settings may have internal parameters. For example, [`CentroidDefuzzifier`](@ref) has an integer parameter `N`, the number of points used to perform numerical integration. If the parameter is not specified, as in `defuzzifier = CentroidDefuzzifier`, then the default value for `N` can be used. This parameter can be overwritten with custom values, for example ```julia defuzzifier = CentroidDefuzzifier(50) ``` will use ``50`` as value of `N` instead of the default one (``100`` in this case). ## Visualization The library offers tools to visualize your fuzzy inference system. This requires installing and importing the `Plots.jl` library. =# using Plots #= The membership functions of a given variable can be plotted by calling `plot(fis, varname)`, where `fis` is the inference system you created and `varname` is the name of the variable you want to visualize, given as a symbol. For example, =# plot(fis, :service) # Giving only the inference system object to `plot` will plot the inference rules, one per line. plot(fis) # If the FIS has at most 2 inputs, we can plot the generating surface of the system using the function [`gensurf`](@ref). # This is a surface visualizing how the output changes as a function of the input. gensurf(fis) #= ## Inference To perform inference, you can call the above constructed inference system as a function, passing th input values as parameters. Note that the system does not accept positional arguments, but inputs should be passed as name-value pairs. For example =# res = fis(service = 2, food = 3) # The result is a Dictionary containing the output value corresponding to each output variable. # The value of a specific output variable can be extracted using the variable name as key. res[:tip] #= ## Code generation The model can be compiled to native Julia code using the [`compilefis`](@ref) function. This produces optimized Julia code independent of the library, that can be executed as stand-alone function. =# fis_ex = compilefis(fis) # The new expression can now be evaluated as normal Julia code. Notice that the generated # function uses positional arguments. eval(fis_ex) tipper(2, 3)
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
2853
#= # Build a Sugeno inference system This tutorial describes how to construct a type-1 Sugeno inference system. The reader is assumed to be familiar with the basic syntax to build a fuzzy system, which is described in the [Build a Mamdani inference system](@ref) tutorial. DOWNLOAD_NOTE A Sugeno inference system can be built using the [`@sugfis`](@ref) macro. The following example shows the macro in action =# using FuzzyLogic, Plots fis = @sugfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = 5.002 average = 15 generous = 2service, 0.5food, 5.0 end service == poor || food == rancid --> tip == cheap service == good --> tip == average service == excellent || food == delicious --> tip == generous end #= The result is an object of type [`SugenoFuzzySystem`](@ref). This is similar to a Mamdani, with the main difference being in the output definition. In a Sugeno system, the output "membership functions" can be: - A [`ConstantSugenoOutput`](@ref), e.g. `average = 15`. This means that if the tip is average, then it has constant value ``15``, - A [`LinearSugenoOutput`](@ref), e.g. `generous = 2service, 0.5food, 5.0`. This means that if the tip is generous, then its value will be ``2service+0.5food + 5.0``. It is good to highlight that these functions return the value of the output variable and not a membership degree, like in a Mamdani system. The second difference from a Mandani system is in the settings that can be tuned. A Sugeno system only has the following options: - `and`: algorithm to evaluate `&&`. Must be one of the available [Conjuction methods](@ref). Default [`ProdAnd`](@ref). - `or`: algorithm to evaluate `||`. Must be one of the available [Disjunction methods](@ref). Default [`ProbSumOr`](@ref) The created model can be evaluated the same way of a Mamdani system. =# fis(service = 2, food = 3) # Let's see the plotting of output variables, as it differs from the Mamdani system plot(fis, :tip) #= As you can see - If the membership function is constant, then the plot simply shows a horizontal line at the output value level. - For `LinearSugenoOutput`, the plot is a bar plot, showing for each input variable the corresponding coefficient. This gives a visual indication of how much each input contributes to the output. Like the Mamdani case, we can plot the whole system. =# plot(fis) # Similarly to Mamdani, we can also generate stand-alone Julia code fis_ex = compilefis(fis) # eval(fis_ex) tipper(2, 3)
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
2428
#= # Build a type-2 inference system This tutorial explains how to build a type-2 inference system. The reader is assumed to be familiar with the basic syntax to build a fuzzy system, which is described in the [Build a Mamdani inference system](@ref) tutorial. DOWNLOAD_NOTE ## Interval membership function While a normal membership function associates each element of a fuzzy set ot a membership degree $\mu \in [0, 1]$, an interval membership function associates each element to an *interval membership degeee* $\overline{\mu}\subseteq[0, 1]$. The following example shows how to contruct an interval membership function in the library and displays the result. =# using FuzzyLogic, Plots mf = 0.7 * TriangularMF(1, 2, 3) .. TriangularMF(0, 2, 4) plot(mf, -1, 5) #= An interval membership function can be constructed using the `..` operator. The left input is the lower bound and the right input is the upper bound. The expression `0.5 * TriangularMF(1, 2, 3)` constructs a scaled membership. ## Type-2 inference systems A type-2 Mamdani system can be built with the [`@mamfis`](@ref) macro, just like type-1, with two differences - membership functions can be interval membership funcions - the defuzzifier should be one of the [Type-2 defuzzifiers](@ref) The following code shows an example of building a type-2 system and performing inference with it. =# fis = @mamfis function tipper(service, food)::tip service := begin domain = 0:10 poor = 0.8 * GaussianMF(0.0, 1.2) .. GaussianMF(0.0, 1.5) good = 0.8 * GaussianMF(5.0, 1.2) .. GaussianMF(5.0, 1.5) excellent = 0.8 * GaussianMF(10.0, 1.2) .. GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = 0.9 * TrapezoidalMF(-1.8, 0.0, 1.0, 2.8) .. TrapezoidalMF(-2, 0, 1, 3) delicious = 0.9 * TrapezoidalMF(8, 9, 10, 12) .. TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = 0.8 * TriangularMF(1, 5, 9) .. TriangularMF(0, 5, 10) average = 0.8 * TriangularMF(11, 15, 19) .. TriangularMF(10, 15, 20) generous = 0.8 * TriangularMF(22, 25, 29) .. TriangularMF(20, 25, 30) end service == poor || food == rancid --> tip == cheap service == good --> tip == average service == excellent || food == delicious --> tip == generous defuzzifier = KarnikMendelDefuzzifier() end plot(fis) #- fis(service = 2, food = 3)
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
1444
module FuzzyLogic using Dictionaries, Reexport include("docstrings.jl") include("intervals.jl") include("membership_functions.jl") include("variables.jl") include("rules.jl") include("options.jl") include("InferenceSystem.jl") include("parser.jl") include("evaluation.jl") include("plotting.jl") include("genfis.jl") include("tojulia.jl") include("readwrite.jl") export DifferenceSigmoidMF, LinearMF, GeneralizedBellMF, GaussianMF, ProductSigmoidMF, SigmoidMF, SingletonMF, TrapezoidalMF, TriangularMF, SShapeMF, ZShapeMF, PiShapeMF, SemiEllipticMF, PiecewiseLinearMF, WeightedMF, Type2MF, .., ProdAnd, MinAnd, LukasiewiczAnd, DrasticAnd, NilpotentAnd, HamacherAnd, EinsteinAnd, ProbSumOr, MaxOr, BoundedSumOr, DrasticOr, NilpotentOr, EinsteinOr, HamacherOr, MinImplication, ProdImplication, MaxAggregator, ProbSumAggregator, CentroidDefuzzifier, BisectorDefuzzifier, LeftMaximumDefuzzifier, RightMaximumDefuzzifier, MeanOfMaximaDefuzzifier, KarnikMendelDefuzzifier, EKMDefuzzifier, IASCDefuzzifier, EIASCDefuzzifier, @mamfis, MamdaniFuzzySystem, @sugfis, SugenoFuzzySystem, set, LinearSugenoOutput, ConstantSugenoOutput, fuzzy_cmeans, compilefis, readfis ## parsers include("parsers/fcl.jl") include("parsers/matlab_fis.jl") include("parsers/fml.jl") @reexport using .FCLParser @reexport using .MatlabParser @reexport using .FMLParser end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
7168
# Fuzzy Inference System abstract type AbstractFuzzySystem end """ Create a copy of the given fuzzy systems, but with the new settings as specified in the keyword arguments. ### Inputs - `fis::AbstractFuzzySystem` -- input fuzzy system ### Keyword arguments - `kwargs...` -- new settings of the inference system to be tuned """ function set(fis::AbstractFuzzySystem; kwargs...) typeof(fis).name.wrapper(NamedTuple(f => get(kwargs, f, getproperty(fis, f)) for f in fieldnames(typeof(fis)))...) end ########### # Mamdani # ########### """ Data structure representing a type-1 Mamdani fuzzy inference system. It can be created using the [`@mamfis`](@ref) macro. It can be called as a function to evaluate the system at a given input. The inputs should be given as keyword arguments. $(TYPEDFIELDS) # Extended help ### Example ```jldoctest; filter=r"Dictionaries\\." fis = @mamfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = TriangularMF(0, 5, 10) average = TriangularMF(10, 15, 20) generous = TriangularMF(20, 25, 30) end service == poor || food == rancid --> tip == cheap service == good --> tip == average service == excellent || food == delicious --> tip == generous end fis(service=1, food=2) # output 1-element Dictionaries.Dictionary{Symbol, Float64} :tip │ 5.558585929783786 ``` """ Base.@kwdef struct MamdaniFuzzySystem{And <: AbstractAnd, Or <: AbstractOr, Impl <: AbstractImplication, Aggr <: AbstractAggregator, Defuzz <: AbstractDefuzzifier, R <: AbstractRule} <: AbstractFuzzySystem "name of the system." name::Symbol "input variables and corresponding domain." inputs::Dictionary{Symbol, Variable} = Dictionary{Symbol, Variable}() "output variables and corresponding domain." outputs::Dictionary{Symbol, Variable} = Dictionary{Symbol, Variable}() "inference rules." rules::Vector{R} = FuzzyRule[] "method used to compute conjuction in rules, default [`MinAnd`](@ref)." and::And = MinAnd() "method used to compute disjunction in rules, default [`MaxOr`](@ref)." or::Or = MaxOr() "method used to compute implication in rules, default [`MinImplication`](@ref)" implication::Impl = MinImplication() "method used to aggregate fuzzy outputs, default [`MaxAggregator`](@ref)." aggregator::Aggr = MaxAggregator() "method used to defuzzify the result, default [`CentroidDefuzzifier`](@ref)." defuzzifier::Defuzz = CentroidDefuzzifier() end implication(fis::MamdaniFuzzySystem) = fis.implication print_title(io::IO, s::String) = println(io, "\n$s\n", repeat('-', length(s))) function Base.show(io::IO, fis::AbstractFuzzySystem) print(io, fis.name, "\n") if !isempty(fis.inputs) print_title(io, "Inputs:") for (name, var) in pairs(fis.inputs) println(io, name, " ∈ ", domain(var), " with membership functions:") for (name, mf) in pairs(memberships(var)) println(io, " ", name, " = ", mf) end println(io) end end if !isempty(fis.outputs) print_title(io, "Outputs:") for (name, var) in pairs(fis.outputs) println(io, name, " ∈ ", domain(var), " with membership functions:") for (name, mf) in pairs(memberships(var)) println(io, " ", name, " = ", mf) end println(io) end end if !isempty(fis.rules) print_title(io, "Inference rules:") for rule in fis.rules println(io, rule) end println(io) end settings = setdiff(fieldnames(typeof(fis)), (:name, :inputs, :outputs, :rules)) if !isempty(settings) print_title(io, "Settings:") for setting in settings println(io, "- ", getproperty(fis, setting)) end end end ########## # SUGENO # ########## """ Data structure representing a type-1 Sugeno fuzzy inference system. It can be created using the [`@sugfis`](@ref) macro. It can be called as a function to evaluate the system at a given input. The inputs should be given as keyword arguments. $(TYPEDFIELDS) """ Base.@kwdef struct SugenoFuzzySystem{And <: AbstractAnd, Or <: AbstractOr, R <: AbstractRule} <: AbstractFuzzySystem "name of the system." name::Symbol "input variables and corresponding domain." inputs::Dictionary{Symbol, Variable} = Dictionary{Symbol, Variable}() "output variables and corresponding domain." outputs::Dictionary{Symbol, Variable} = Dictionary{Symbol, Variable}() "inference rules." rules::Vector{R} = FuzzyRule[] "method used to compute conjuction in rules, default [`MinAnd`](@ref)." and::And = ProdAnd() "method used to compute disjunction in rules, default [`MaxOr`](@ref)." or::Or = ProbSumOr() end const SETTINGS = (MamdaniFuzzySystem = (:and, :or, :implication, :aggregator, :defuzzifier), SugenoFuzzySystem = (:and, :or)) # sugeno output functions abstract type AbstractSugenoOutputFunction <: AbstractPredicate end """ Represents constant output in Sugeno inference systems. $(TYPEDFIELDS) """ struct ConstantSugenoOutput{T <: Real} <: AbstractSugenoOutputFunction "value of the constant output." c::T end (csmf::ConstantSugenoOutput)(inputs) = csmf.c (csmf::ConstantSugenoOutput)(; inputs...) = csmf.c Base.show(io::IO, csmf::ConstantSugenoOutput) = print(io, csmf.c) """ Represents an output variable that has a first-order polynomial relation on the inputs. Used for Sugeno inference systems. $(TYPEDFIELDS) """ struct LinearSugenoOutput{T} <: AbstractSugenoOutputFunction "coefficients associated with each input variable." coeffs::Dictionary{Symbol, T} "offset of the output." offset::T end function Base.:(==)(m1::LinearSugenoOutput, m2::LinearSugenoOutput) m1.offset == m2.offset && m1.coeffs == m2.coeffs end function (fsmf::LinearSugenoOutput)(inputs) sum(val * fsmf.coeffs[name] for (name, val) in pairs(inputs)) + fsmf.offset end (fsmf::LinearSugenoOutput)(; inputs...) = fsmf(inputs) function Base.show(io::IO, lsmf::LinearSugenoOutput) started = false for (var, c) in pairs(lsmf.coeffs) iszero(c) && continue if started print(io, c < 0 ? " - " : " + ", isone(abs(c)) ? "" : abs(c), var) else print(io, isone(c) ? "" : c, var) end started = true end if started iszero(lsmf.offset) || print(io, lsmf.offset < 0 ? " - " : " + ", abs(lsmf.offset)) else print(io, lsmf.offset) end end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
356
## Docstring Templates using DocStringExtensions @template (FUNCTIONS, METHODS, MACROS) = """ $(TYPEDSIGNATURES) $(DOCSTRING) """ @template TYPES = """ $(TYPEDEF) $(DOCSTRING) """
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
2835
# utilities to evaluate a fuzzy inference system function (fr::FuzzyRelation)(fis::AbstractFuzzySystem, inputs::T) where {T <: NamedTuple} memberships(fis.inputs[fr.subj])[fr.prop](inputs[fr.subj]) end function (fr::FuzzyNegation)(fis::AbstractFuzzySystem, inputs::T)::float(eltype(T)) where {T <: NamedTuple} 1 - memberships(fis.inputs[fr.subj])[fr.prop](inputs[fr.subj]) end function (fa::FuzzyAnd)(fis::AbstractFuzzySystem, inputs) fis.and(fa.left(fis, inputs), fa.right(fis, inputs)) end function (fo::FuzzyOr)(fis::AbstractFuzzySystem, inputs) fis.or(fo.left(fis, inputs), fo.right(fis, inputs)) end function (fis::MamdaniFuzzySystem)(inputs::T) where {T <: NamedTuple} Npoints = fis.defuzzifier.N + 1 S = outputtype(typeof(fis.defuzzifier), T) res = Dictionary{Symbol, Vector{S}}(keys(fis.outputs), [zeros(S, Npoints) for _ in 1:length(fis.outputs)]) @inbounds for rule in fis.rules w = rule.antecedent(fis, inputs) for con in rule.consequent var = fis.outputs[con.subj] l, h = low(var.domain), high(var.domain) mf = map(var.mfs[con.prop], LinRange(l, h, Npoints)) ruleres = scale(map(Base.Fix1(implication(fis), w), mf), rule) res[con.subj] = broadcast(fis.aggregator, res[con.subj], ruleres) end end Dictionary{Symbol, float(S)}(keys(fis.outputs), map(zip(res, fis.outputs)) do (y, var) fis.defuzzifier(y, var.domain) end) end (fis::MamdaniFuzzySystem)(; inputs...) = fis(values(inputs)) @inline function (fis::MamdaniFuzzySystem)(inputs::Union{AbstractVector, Tuple}) fis((; zip(collect(keys(fis.inputs)), inputs)...)) end function (fis::SugenoFuzzySystem)(inputs::T) where {T <: NamedTuple} S = float(eltype(T)) res = Dictionary{Symbol, Union{S, Interval{S}}}(keys(fis.outputs), zeros(float(eltype(T)), length(fis.outputs))) weights_sum = zero(S) for rule in fis.rules w = scale(rule.antecedent(fis, inputs), rule) weights_sum += w for con in rule.consequent res[con.subj] += w * memberships(fis.outputs[con.subj])[con.prop](inputs) end end map(Base.Fix2(/, weights_sum), res) end (fis::SugenoFuzzySystem)(; inputs...) = fis(values(inputs)) @inline function (fis::SugenoFuzzySystem)(inputs::Union{AbstractVector, Tuple}) fis((; zip(collect(keys(fis.inputs)), inputs)...)) end outputtype(::Type{T}, S) where {T <: AbstractDefuzzifier} = float(eltype(S)) outputtype(::Type{T}, S) where {T <: Type2Defuzzifier} = Interval{float(eltype(S))}
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
1869
""" Performs fuzzy clustering on th data `X` using `N` clusters. ### Input - `X` -- ``d × M`` matrix of data, each column is a data point - `N` -- number of clusters used. ### Keyword argumes - `m` -- exponent of the fuzzy membership function, default `2.0` - `maxiter` -- maximum number of iterations, default `100` - `tol` -- absolute error for stopping condition. Stop if ``|Eₖ - Eₖ₊₁|≤tol``, where ``Eₖ`` is the cost function value at the ``k``:th iteration. ### Output - `C` -- ``d × N``matrix of centers, each column is the center of a cluster. - `U` -- ``M × N`` matrix of membership degrees, `Uᵢⱼ`` tells has the membership degree of the ``j``th point to the ``i``th cluster. """ function fuzzy_cmeans(X::Matrix{T}, N::Int; m = 2.0, maxiter = 100, tol = 1e-5) where {T <: Real} m > 1 || throw(ArgumentError("m must be greater than 1")) e = 1 / (m - 1) M = size(X, 2) U = rand(float(T), M, N) C = X * U .^ m ./ sum(U .^ m; dims = 1) J = zero(float(T)) @inbounds for (j, cj) in enumerate(eachcol(C)) for (i, xi) in enumerate(eachcol(X)) J += U[i, j]^m * sum(abs2(k) for k in xi - cj) end end @inbounds for i in 1:maxiter for (j, cj) in enumerate(eachcol(C)) for (i, xi) in enumerate(eachcol(X)) U[i, j] = 1 / sum(sum(abs2.(xi - cj)) / sum(abs2.(xi - ck)) for ck in eachcol(C))^e end end C .= X * U .^ m ./ sum(U .^ m; dims = 1) Jnew = zero(float(T)) for (j, cj) in enumerate(eachcol(C)) for (i, xi) in enumerate(eachcol(X)) Jnew += U[i, j]^m * sum(abs2(k) for k in xi - cj) end end abs(J - Jnew) <= tol && break J = Jnew end return C, U end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
1382
struct Interval{T <: Real} lo::T hi::T end inf(a::Interval) = a.lo sup(a::Interval) = a.hi inf(a::Real) = a sup(a::Real) = a mid(a::Interval) = (a.lo + a.hi) / 2 mid(a::Real) = a diam(a::Interval) = a.hi - a.lo diam(x::Real) = zero(x) Base.convert(::Type{Interval{T}}, x::Real) where {T <: Real} = Interval(T(x), T(x)) Base.float(::Type{Interval{T}}) where {T <: Real} = T Base.:+(a::Interval) = a Base.:-(a::Interval) = Interval(-a.hi, -a.lo) Base.:+(a::Interval, b::Interval) = Interval(a.lo + b.lo, a.hi + b.hi) Base.:-(a::Interval, b::Interval) = Interval(a.lo - b.hi, a.hi - b.lo) function Base.:*(a::Interval, b::Interval) Interval(extrema((a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi))...) end function Base.:/(a::Interval, b::Interval) Interval(extrema((a.lo / b.lo, a.lo / b.hi, a.hi / b.lo, a.hi / b.hi))...) end Base.min(a::Interval, b::Interval) = Interval(min(a.lo, b.lo), min(a.hi, b.hi)) Base.max(a::Interval, b::Interval) = Interval(max(a.lo, b.lo), max(a.hi, b.hi)) Base.zero(::Type{Interval{T}}) where {T <: Real} = Interval(zero(T), zero(T)) for op in (:+, :-, :*, :/, :min, :max) @eval Base.$op(a::Interval, b::Real) = $op(a, Interval(b, b)) @eval Base.$op(a::Real, b::Interval) = $op(Interval(a, a), b) end function Base.:≈(a::Interval, b::Interval; kwargs...) ≈(a.lo, b.lo; kwargs...) && ≈(a.hi, b.hi; kwargs...) end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
8073
# Membership functions abstract type AbstractPredicate end abstract type AbstractMembershipFunction <: AbstractPredicate end """ Singleton membership function. Equal to one at a single point and zero elsewhere. ### Fields $(TYPEDFIELDS) ### Example ```julia mf = SingletonMF(4) ``` """ struct SingletonMF{T <: Real} <: AbstractMembershipFunction "Point at which the membership function has value 1." c::T end (mf::SingletonMF)(x::Real) = mf.c == x ? one(x) : zero(x) """ Generalized Bell membership function ``\\frac{1}{1+\\vert\\frac{x-c}{a}\\vert^{2b}}``. ### Fields $(TYPEDFIELDS) ### Example ```julia mf = GeneralizedBellMF(2, 4, 5) ``` """ struct GeneralizedBellMF{T <: Real, S <: Real} <: AbstractMembershipFunction "Width of the curve, the bigger the wider." a::T "Slope of the curve, the bigger the steeper." b::S "Center of the curve." c::T end (mf::GeneralizedBellMF)(x) = 1 / (1 + abs((x - mf.c) / mf.a)^(2mf.b)) """ Gaussian membership function ``e^{-\\frac{(x-μ)²}{2σ²}}``. ### Fields $(TYPEDFIELDS) ### Example ```julia mf = GaussianMF(5.0, 1.5) ``` """ struct GaussianMF{T <: Real} <: AbstractMembershipFunction "mean ``μ``." mu::T "standard deviation ``σ``." sig::T end (mf::GaussianMF)(x) = exp(-(x - mf.mu)^2 / (2mf.sig^2)) """ Triangular membership function. ### Fields $(TYPEDFIELDS) ### Example ```julia mf = TriangularMF(3, 5, 7) ``` """ struct TriangularMF{T <: Real} <: AbstractMembershipFunction "left foot." a::T "peak." b::T "right foot." c::T end (mf::TriangularMF)(x) = max(min((x - mf.a) / (mf.b - mf.a), (mf.c - x) / (mf.c - mf.b)), 0) """ Trapezoidal membership function. ### Fields $(TYPEDFIELDS) ### Example ```julia mf = TrapezoidalMF(1, 3, 7, 9) ``` """ struct TrapezoidalMF{T <: Real} <: AbstractMembershipFunction "left foot." a::T "left shoulder." b::T "right shoulder." c::T "right foot." d::T end function (mf::TrapezoidalMF)(x) return max(min((x - mf.a) / (mf.b - mf.a), 1, (mf.d - x) / (mf.d - mf.c)), 0) end """ Linear membership function. If ``a < b``, it is increasing (S-shaped), otherwise it is decreasing (Z-shaped). ### Fields $(TYPEDFIELDS) ### Example ```julia mf = LinearMF(2, 8) ``` """ struct LinearMF{T <: Real} <: AbstractMembershipFunction "foot." a::T "shoulder." b::T end (mf::LinearMF)(x) = max(min((x - mf.a) / (mf.b - mf.a), 1), 0) """ Sigmoid membership function ``\\frac{1}{1+e^{-a(x-c)}}``. ### Fields $(TYPEDFIELDS) ### Example ```julia mf = SigmoidMF(2, 5) ``` """ struct SigmoidMF{T <: Real} <: AbstractMembershipFunction "parameter controlling the slope of the curve." a::T "center of the slope." c::T end (mf::SigmoidMF)(x) = 1 / (1 + exp(-mf.a * (x - mf.c))) """ Difference of two sigmoids. See also [`SigmoidMF`](@ref). ### Fields $(TYPEDFIELDS) ### Example ```julia mf = DifferenceSigmoidMF(5, 2, 5, 7) ``` """ struct DifferenceSigmoidMF{T <: Real} <: AbstractMembershipFunction "slope of the first sigmoid." a1::T "center of the first sigmoid." c1::T "slope of the second sigmoid." a2::T "center of the second sigmoid." c2::T end function (mf::DifferenceSigmoidMF)(x) return max(min(1 / (1 + exp(-mf.a1 * (x - mf.c1))) - 1 / (1 + exp(-mf.a2 * (x - mf.c2))), 1), 0) end """ Product of two sigmoids. See also [`SigmoidMF`](@ref). ### Fields $(TYPEDFIELDS) ### Example ```julia mf = ProductSigmoidMF(2, 3, -5, 8) ``` """ struct ProductSigmoidMF{T <: Real} <: AbstractMembershipFunction "slope of the first sigmoid." a1::T "center of the first sigmoid." c1::T "slope of the second sigmoid." a2::T "center of the second sigmoid." c2::T end function (mf::ProductSigmoidMF)(x) return 1 / ((1 + exp(-mf.a1 * (x - mf.c1))) * (1 + exp(-mf.a2 * (x - mf.c2)))) end """ S-shaped membership function. ### Fields $(TYPEDFIELDS) ### Example ```julia mf = SShapeMF(1, 8) ``` """ struct SShapeMF{T <: Real} <: AbstractMembershipFunction "foot." a::T "shoulder." b::T end function (s::SShapeMF)(x::T) where {T <: Real} x <= s.a && return zero(float(T)) x >= s.b && return one(float(T)) x >= (s.a + s.b) / 2 && return 1 - 2 * ((x - s.b) / (s.b - s.a))^2 return 2 * ((x - s.a) / (s.b - s.a))^2 end """ Z-shaped membership function. ### Fields $(TYPEDFIELDS) ### Example ```julia mf = ZShapeMF(3, 7) ``` """ struct ZShapeMF{T <: Real} <: AbstractMembershipFunction "shoulder." a::T "foot." b::T end function (z::ZShapeMF)(x::T) where {T <: Real} x <= z.a && return one(float(T)) x >= z.b && return zero(float(T)) x >= (z.a + z.b) / 2 && return 2 * ((x - z.b) / (z.b - z.a))^2 return 1 - 2 * ((x - z.a) / (z.b - z.a))^2 end """ Π-shaped membership function. ### Fields $(TYPEDFIELDS) ### Example ```julia mf = PiShapeMF(1, 4, 5, 10) ``` """ struct PiShapeMF{T <: Real} <: AbstractMembershipFunction "left foot." a::T "left shoulder." b::T "right shoulder." c::T "right foot." d::T end function (p::PiShapeMF)(x::T) where {T <: Real} (x <= p.a || x >= p.d) && return zero(float(T)) p.b <= x <= p.c && return one(float(T)) x <= (p.a + p.b) / 2 && return 2 * ((x - p.a) / (p.b - p.a))^2 x <= p.b && return 1 - 2 * ((x - p.b) / (p.b - p.a))^2 x <= (p.c + p.d) / 2 && return 1 - 2 * ((x - p.c) / (p.d - p.c))^2 return 2 * ((x - p.d) / (p.d - p.c))^2 end """ Semi-elliptic membership function. ### Fields $(TYPEDFIELDS) ### Example ```julia mf = SemiEllipticMF(5.0, 4.0) ``` """ struct SemiEllipticMF{T <: Real} <: AbstractMembershipFunction "center." cd::T "semi-axis." rd::T end function (semf::SemiEllipticMF)(x::Real) cd, rd = semf.cd, semf.rd cd - rd <= x <= cd + rd || return zero(x) sqrt(1 - (cd - x)^2 / rd^2) end """ Piecewise linear membership function. ### Fields $(TYPEDFIELDS) ### Notes If the input is between two points, its membership degree is computed by linear interpolation. If the input is before the first point, it has the same membership degree of the first point. If the input is after the last point, it has the same membership degree of the first point. ### Example ```julia mf = PiecewiseLinearMF([(1, 0), (2, 1), (3, 0), (4, 0.5), (5, 0), (6, 1)]) ``` """ struct PiecewiseLinearMF{T <: Real, S <: Real} <: AbstractMembershipFunction points::Vector{Tuple{T, S}} end function (plmf::PiecewiseLinearMF)(x::Real) x <= plmf.points[1][1] && return float(plmf.points[1][2]) x >= plmf.points[end][1] && return float(plmf.points[end][2]) idx = findlast(p -> x >= p[1], plmf.points) x1, y1 = plmf.points[idx] x2, y2 = plmf.points[idx + 1] (y2 - y1) / (x2 - x1) * (x - x1) + y1 end # TODO: more robust soultion for all mfs Base.:(==)(mf1::PiecewiseLinearMF, mf2::PiecewiseLinearMF) = mf1.points == mf2.points """ A membership function scaled by a parameter ``0 ≤ w ≤ 1``. $(TYPEDFIELDS) ### Example ```julia mf = 0.5 * TriangularMF(1, 2, 3) ``` """ struct WeightedMF{MF <: AbstractMembershipFunction, T <: Real} <: AbstractMembershipFunction "membership function." mf::MF "scaling factor." w::T end (wmf::WeightedMF)(x) = wmf.w * wmf.mf(x) Base.show(io::IO, wmf::WeightedMF) = print(io, wmf.w, wmf.mf) Base.:*(w::Real, mf::AbstractMembershipFunction) = WeightedMF(mf, w) Base.:*(mf::AbstractMembershipFunction, w::Real) = WeightedMF(mf, w) """ A type-2 membership function. $(TYPEDFIELDS) ### Example ```julia mf = 0.7 * TriangularMF(3, 5, 7) .. TriangularMF(1, 5, 9) ``` """ struct Type2MF{MF1 <: AbstractMembershipFunction, MF2 <: AbstractMembershipFunction} <: AbstractMembershipFunction "lower membership function." lo::MF1 "upper membership function." hi::MF2 end (mf2::Type2MF)(x) = Interval(mf2.lo(x), mf2.hi(x)) ..(mf1::AbstractMembershipFunction, mf2::AbstractMembershipFunction) = Type2MF(mf1, mf2) Base.show(io::IO, mf2::Type2MF) = print(io, mf2.lo, " .. ", mf2.hi)
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
14623
# Fuzzy inference system options abstract type AbstractFISSetting end ## T-Norms abstract type AbstractAnd <: AbstractFISSetting end """ Minimum T-norm defining conjuction as ``A ∧ B = \\min(A, B)``. """ struct MinAnd <: AbstractAnd end (ma::MinAnd)(x, y) = min(x, y) """ Product T-norm defining conjuction as ``A ∧ B = AB``. """ struct ProdAnd <: AbstractAnd end (pa::ProdAnd)(x, y) = x * y """ Lukasiewicz T-norm defining conjuction as ``A ∧ B = \\max(0, A + B - 1)``. """ struct LukasiewiczAnd <: AbstractAnd end (la::LukasiewiczAnd)(x, y) = max(0, x + y - 1) """ Drastic T-norm defining conjuction as ``A ∧ B = \\min(A, B)`` is ``A = 1`` or ``B = 1`` and ``A ∧ B = 0`` otherwise. """ struct DrasticAnd <: AbstractAnd end function (da::DrasticAnd)(x::T, y::S) where {T <: Real, S <: Real} TS = promote_type(T, S) isone(x) && return TS(y) isone(y) && return TS(x) zero(TS) end """ Nilpotent T-norm defining conjuction as ``A ∧ B = \\min(A, B)`` when ``A + B > 1`` and ``A ∧ B = 0`` otherwise. """ struct NilpotentAnd <: AbstractAnd end function (na::NilpotentAnd)(x::T, y::S) where {T <: Real, S <: Real} m = min(x, y) x + y > 1 && return m return zero(m) end """ Hamacher T-norm defining conjuction as ``A ∧ B = \\frac{AB}{A + B - AB}`` if ``A \\neq 0 \\neq B`` and ``A ∧ B = 0`` otherwise. """ struct HamacherAnd <: AbstractAnd end function (ha::HamacherAnd)(x::T, y::S) where {T <: Real, S <: Real} iszero(x) && iszero(y) && return zero(float(promote_type(T, S))) (x * y) / (x + y - x * y) end """ Einstein T-norm defining conjuction as ``A ∧ B = \\frac{AB}{2 - A - B + AB}``. """ struct EinsteinAnd <: AbstractAnd end (ha::EinsteinAnd)(x::Real, y::Real) = (x * y) / (2 - x - y + x * y) ## S-Norms abstract type AbstractOr <: AbstractFISSetting end """ Maximum S-norm defining disjunction as ``A ∨ B = \\max(A, B)``. """ struct MaxOr <: AbstractOr end (mo::MaxOr)(x, y) = max(x, y) """ Probabilistic sum S-norm defining disjunction as ``A ∨ B = A + B - AB``. """ struct ProbSumOr <: AbstractOr end (pso::ProbSumOr)(x, y) = x + y - x * y """ Bounded sum S-norm defining disjunction as ``A ∨ B = \\min(1, A + B)``. """ struct BoundedSumOr <: AbstractOr end (la::BoundedSumOr)(x, y) = min(1, x + y) """ Drastic S-norm defining disjunction as ``A ∨ B = \\min(1, A + B)``. """ struct DrasticOr <: AbstractOr end function (da::DrasticOr)(x::T, y::S) where {T <: Real, S <: Real} TS = promote_type(T, S) iszero(x) && return TS(y) iszero(y) && return TS(x) one(TS) end """ Nilpotent S-norm defining disjunction as ``A ∨ B = \\max(A, B)`` when ``A + B < 1`` and ``A ∧ B = 1`` otherwise. """ struct NilpotentOr <: AbstractOr end function (na::NilpotentOr)(x::T, y::S) where {T <: Real, S <: Real} m = max(x, y) x + y < 1 && return m return one(m) end """ Einstein S-norm defining disjunction as ``A ∨ B = \\frac{A + B}{1 + AB}``. """ struct EinsteinOr <: AbstractOr end (ha::EinsteinOr)(x, y) = (x + y) / (1 + x * y) """ Hamacher S-norm defining conjuction as ``A ∨ B = \\frac{A + B - AB}{1 - AB}`` if ``A \\neq 1 \\neq B`` and ``A ∨ B = 1`` otherwise. """ struct HamacherOr <: AbstractOr end function (ha::HamacherOr)(x::T, y::S) where {T <: Real, S <: Real} isone(x) && isone(y) && return one(float(promote_type(T, S))) (x + y - 2 * x * y) / (1 - x * y) end ## Implication abstract type AbstractImplication <: AbstractFISSetting end """ Minimum implication defined as ``A → B = \\min(A, B)``. """ struct MinImplication <: AbstractImplication end (mini::MinImplication)(x, y) = min(x, y) """ Product implication defined as ``A → B = AB``. """ struct ProdImplication <: AbstractImplication end (pim::ProdImplication)(x, y) = x * y ## Aggregation abstract type AbstractAggregator <: AbstractFISSetting end """ Aggregator that combines fuzzy rules output by taking their maximum. """ struct MaxAggregator <: AbstractAggregator end (ma::MaxAggregator)(x, y) = max(x, y) """ Aggregator that combines fuzzy rules output by taking their probabilistic sum. See also [`ProbSumOr`](@ref). """ struct ProbSumAggregator <: AbstractAggregator end (psa::ProbSumAggregator)(x, y) = x + y - x * y ## Defuzzification abstract type AbstractDefuzzifier <: AbstractFISSetting end """ Centroid defuzzifier. Given the aggregated output function ``f`` and the output variable domain ``[a, b]`` the defuzzified output is the centroid computed as ```math \\frac{∫_a^bxf(x)\\textrm{d}x}{∫_a^bf(x)\\textrm{d}x}. ``` ### Parameters $(TYPEDFIELDS) ## Algorithm The integrals are computed numerically using the trapezoidal rule. """ struct CentroidDefuzzifier <: AbstractDefuzzifier "number of subintervals for integration, default 100." N::Int end CentroidDefuzzifier() = CentroidDefuzzifier(100) function (cd::CentroidDefuzzifier)(y, dom::Domain{T})::float(T) where {T} dx = (high(dom) - low(dom)) / cd.N _trapz(dx, LinRange(low(dom), high(dom), cd.N + 1) .* y) / _trapz(dx, y) end """ Bisector defuzzifier. Given the aggregated output function ``f`` and the output variable domain ``[a, b]`` the defuzzified output is the value ``t ∈ [a, b]`` that divides the area under ``f`` into two equal parts. That is ```math ∫_a^tf(x)\\textrm{d}x = ∫_t^af(x)\\textrm{d}x. ``` ### Parameters $(TYPEDFIELDS) ## Algorithm The domain is partitioned into N equal subintervals. For each subinterval endpoint, the left and right area are approximated using the trapezoidal rule. The end point leading to the best approximation is the final result. """ struct BisectorDefuzzifier <: AbstractDefuzzifier "number of subintervals for integration, default 100." N::Int end BisectorDefuzzifier() = BisectorDefuzzifier(100) function (bd::BisectorDefuzzifier)(y, dom::Domain{T})::float(T) where {T} area_left = zero(T) h = (high(dom) - low(dom)) / bd.N area_right = _trapz(h, y) cand = LinRange(low(dom), high(dom), bd.N + 1) i = firstindex(y) while area_left < area_right trap = (y[i] + y[i + 1]) * h / 2 area_left += trap area_right -= trap i += 1 end (y[i - 1] + y[i]) * h / 2 >= area_left - area_right ? cand[i] : cand[i - 1] end """ Left maximum defuzzifier. Returns the smallest value in the domain for which the membership function reaches its maximum. ### Parameters $(TYPEDFIELDS) """ Base.@kwdef struct LeftMaximumDefuzzifier <: AbstractDefuzzifier "number of subintervals, default 100." N::Int = 100 "absolute tolerance to determine if a value is maximum, default `eps(Float64)`." tol::Float64 = eps(Float64) end function (lmd::LeftMaximumDefuzzifier)(y, dom::Domain{T}) where {T} res = float(low(dom)) maxval = first(y) for (xi, yi) in zip(LinRange(low(dom), high(dom), lmd.N + 1), y) if yi > maxval + lmd.tol res = xi maxval = yi end end res end """ Right maximum defuzzifier. Returns the largest value in the domain for which the membership function reaches its maximum. ### Parameters $(TYPEDFIELDS) """ Base.@kwdef struct RightMaximumDefuzzifier <: AbstractDefuzzifier "number of subintervals, default 100." N::Int = 100 "absolute tolerance to determine if a value is maximum, default `eps(Float64)`." tol::Float64 = eps(Float64) end function (lmd::RightMaximumDefuzzifier)(y, dom::Domain{T}) where {T} res = float(low(dom)) maxval = first(y) for (xi, yi) in zip(LinRange(low(dom), high(dom), lmd.N + 1), y) if yi >= maxval - lmd.tol res = xi maxval = yi end end res end """ Mean of maxima defuzzifier. Returns the mean of the values in the domain for which the membership function reaches its maximum. ### Parameters $(TYPEDFIELDS) """ Base.@kwdef struct MeanOfMaximaDefuzzifier <: AbstractDefuzzifier "number of subintervals, default 100." N::Int = 100 "absolute tolerance to determine if a value is maximum, default `eps(Float64)`." tol::Float64 = eps(Float64) end function (lmd::MeanOfMaximaDefuzzifier)(y, dom::Domain{T}) where {T} res = zero(float(T)) maxcnt = 0 maxval = first(y) for (xi, yi) in zip(LinRange(low(dom), high(dom), lmd.N + 1), y) if yi - maxval > lmd.tol # reset mean calculation res = xi maxval = yi maxcnt = 1 elseif abs(yi - maxval) <= lmd.tol res += xi maxcnt += 1 end end return res / maxcnt end _trapz(dx, y) = (2sum(y) - first(y) - last(y)) * dx / 2 abstract type Type2Defuzzifier <: AbstractDefuzzifier end """ Karnik-Mendel type-reduction/defuzzification algorithm for Type-2 fuzzy systems. ### Parameters $(TYPEDFIELDS) # Extended help The algorithm was introduced in - Karnik, Nilesh N., and Jerry M. Mendel. ‘Centroid of a Type-2 Fuzzy Set’. Information Sciences 132, no. 1–4 (February 2001): 195–220 """ Base.@kwdef struct KarnikMendelDefuzzifier <: Type2Defuzzifier "number of subintervals for integration, default 100." N::Int = 100 "maximum number of iterations, default 100." maxiter::Int = 100 "absolute tolerance for stopping iterations" atol::Float64 = 1e-6 end function (kmd::KarnikMendelDefuzzifier)(w, dom::Domain{T})::float(T) where {T} x = LinRange(low(dom), high(dom), length(w)) m = map(mid, w) x0 = sum(xi * mi for (xi, mi) in zip(x, m)) / sum(m) xl = x0 xr = x0 idx = searchsortedlast(x, x0) @inbounds for _ in 1:(kmd.maxiter) num = zero(eltype(m)) den = zero(eltype(m)) for i in firstindex(x):idx den += sup(w[i]) num += sup(w[i]) * x[i] end for i in (idx + 1):length(x) den += inf(w[i]) num += inf(w[i]) * x[i] end cand = num / den if abs(cand - xl) <= kmd.atol xl = cand break end xl = cand idx = searchsortedlast(x, xl) end @inbounds for _ in 1:(kmd.maxiter) num = zero(eltype(m)) den = zero(eltype(m)) for i in firstindex(x):idx den += inf(w[i]) num += inf(w[i]) * x[i] end for i in (idx + 1):length(x) den += sup(w[i]) num += sup(w[i]) * x[i] end cand = num / den if abs(cand - xr) <= kmd.atol xr = cand break end xr = cand idx = searchsortedlast(x, xr) end return (xl + xr) / 2 end """ Enhanced Karnik-Mendel type-reduction/defuzzification algorithm for Type-2 fuzzy systems. ### Parameters $(TYPEDFIELDS) # Extended help The algorithm was introduced in - Wu, D. and J.M. Mendel, "Enhanced Karnik-Mendel algorithms," IEEE Transactions on Fuzzy Systems, vol. 17, pp. 923-934. (2009) """ Base.@kwdef struct EKMDefuzzifier <: Type2Defuzzifier "number of subintervals for integration, default 100." N::Int = 100 "maximum number of iterations, default 100." maxiter::Int = 100 end function (ekmd::EKMDefuzzifier)(w, dom::Domain{T})::float(T) where {T} Np = length(w) x = LinRange(low(dom), high(dom), Np) k = round(Int, Np / 2.4) a = sum(x[i] * sup(w[i]) for i in 1:k) + sum(x[i] * inf(w[i]) for i in (k + 1):Np) b = sum(sup(w[i]) for i in 1:k) + sum(inf(w[i]) for i in (k + 1):Np) yl = a / b @inbounds for _ in 1:(ekmd.maxiter) knew = searchsortedlast(x, yl) k == knew && break s = sign(knew - k) a += s * sum(x[i] * diam(w[i]) for i in (min(k, knew) + 1):max(k, knew)) b += s * sum(diam(w[i]) for i in (min(k, knew) + 1):max(k, knew)) yl = a / b k = knew end k = round(Int, Np / 1.7) a = sum(x[i] * inf(w[i]) for i in 1:k) + sum(x[i] * sup(w[i]) for i in (k + 1):Np) b = sum(inf(w[i]) for i in 1:k) + sum(sup(w[i]) for i in (k + 1):Np) yr = a / b @inbounds for _ in 1:(ekmd.maxiter) knew = searchsortedlast(x, yr) k == knew && break s = sign(knew - k) a -= s * sum(x[i] * diam(w[i]) for i in (min(k, knew) + 1):max(k, knew)) b -= s * sum(diam(w[i]) for i in (min(k, knew) + 1):max(k, knew)) yr = a / b k = knew end return (yl + yr) / 2 end """ Defuzzifier for type-2 inference systems using Iterative Algorithm with Stopping Condition (IASC). ### PARAMETERS $(TYPEDFIELDS) # Extended help The algorithm was introduced in - Duran, K., H. Bernal, and M. Melgarejo, "Improved iterative algorithm for computing the generalized centroid of an interval type-2 fuzzy set," Annual Meeting of the North American Fuzzy Information Processing Society, pp. 190-194. (2008) """ Base.@kwdef struct IASCDefuzzifier <: Type2Defuzzifier "number of subintervals for integration, default 100." N::Int = 100 end function (iasc::IASCDefuzzifier)(w, dom::Domain{T})::float(T) where {T} Np = length(w) x = LinRange(low(dom), high(dom), Np) a = sum(xi * inf(wi) for (xi, wi) in zip(x, w)) b = sum(inf, w) yl = last(x) @inbounds for (xi, wi) in zip(x, w) a += xi * diam(wi) b += diam(wi) c = a / b c > yl && break yl = c end a = sum(xi * sup(wi) for (xi, wi) in zip(x, w)) b = sum(sup, w) yr = first(x) @inbounds for (xi, wi) in zip(x, w) a -= xi * diam(wi) b -= diam(wi) c = a / b c < yr && break yr = c end return (yl + yr) / 2 end """ Defuzzifier for type-2 inference systems using Iterative Algorithm with Stopping Condition (IASC). ### PARAMETERS $(TYPEDFIELDS) # Extended help The algorithm was introduced in - Wu, D. and M. Nie, "Comparison and practical implementations of type-reduction algorithms for type-2 fuzzy sets and systems," Proceedings of FUZZ-IEEE, pp. 2131-2138 (2011) """ Base.@kwdef struct EIASCDefuzzifier <: Type2Defuzzifier "number of subintervals for integration, default 100." N::Int = 100 end function (eiasc::EIASCDefuzzifier)(w, dom::Domain{T})::float(T) where {T} Np = length(w) x = LinRange(low(dom), high(dom), Np) a = sum(xi * inf(wi) for (xi, wi) in zip(x, w)) b = sum(inf, w) yl = last(x) @inbounds for (xi, wi) in zip(x, w) a += xi * diam(wi) b += diam(wi) c = a / b c > yl && break yl = c end a = sum(xi * inf(wi) for (xi, wi) in zip(x, w)) b = sum(inf, w) yr = first(x) @inbounds for i in reverse(eachindex(x)) a += x[i] * diam(w[i]) b += diam(w[i]) c = a / b c < yr && break yr = c end return (yl + yr) / 2 end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
10116
using MacroTools """ $(TYPEDSIGNATURES) Parse julia code into a [`MamdaniFuzzySystem`](@ref). See extended help for an example. # Extended help ### Example ```jldoctest fis = @mamfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = TriangularMF(0, 5, 10) average = TriangularMF(10, 15, 20) generous = TriangularMF(20, 25, 30) end and = ProdAnd or = ProbSumOr implication = ProdImplication service == poor || food == rancid --> tip == cheap service == good --> tip == average service == excellent || food == delicious --> tip == generous aggregator = ProbSumAggregator defuzzifier = BisectorDefuzzifier end # output tipper Inputs: ------- service ∈ [0, 10] with membership functions: poor = GaussianMF{Float64}(0.0, 1.5) good = GaussianMF{Float64}(5.0, 1.5) excellent = GaussianMF{Float64}(10.0, 1.5) food ∈ [0, 10] with membership functions: rancid = TrapezoidalMF{Int64}(-2, 0, 1, 3) delicious = TrapezoidalMF{Int64}(7, 9, 10, 12) Outputs: -------- tip ∈ [0, 30] with membership functions: cheap = TriangularMF{Int64}(0, 5, 10) average = TriangularMF{Int64}(10, 15, 20) generous = TriangularMF{Int64}(20, 25, 30) Inference rules: ---------------- (service is poor ∨ food is rancid) --> tip is cheap service is good --> tip is average (service is excellent ∨ food is delicious) --> tip is generous Settings: --------- - ProdAnd() - ProbSumOr() - ProdImplication() - ProbSumAggregator() - BisectorDefuzzifier(100) ``` """ macro mamfis(ex::Expr) return _fis(ex, :MamdaniFuzzySystem) end """ $(TYPEDSIGNATURES) Parse julia code into a [`SugenoFuzzySystem`](@ref). See extended help for an example. # Extended help ### Example ```jldoctest fis = @sugfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = 0 average = food generous = 2service, food, -2 end service == poor && food == rancid --> tip == cheap service == good --> tip == average service == excellent || food == delicious --> tip == generous end # output tipper Inputs: ------- service ∈ [0, 10] with membership functions: poor = GaussianMF{Float64}(0.0, 1.5) good = GaussianMF{Float64}(5.0, 1.5) excellent = GaussianMF{Float64}(10.0, 1.5) food ∈ [0, 10] with membership functions: rancid = TrapezoidalMF{Int64}(-2, 0, 1, 3) delicious = TrapezoidalMF{Int64}(7, 9, 10, 12) Outputs: -------- tip ∈ [0, 30] with membership functions: cheap = 0 average = food generous = 2service + food - 2 Inference rules: ---------------- (service is poor ∧ food is rancid) --> tip is cheap service is good --> tip is average (service is excellent ∨ food is delicious) --> tip is generous Settings: --------- - ProdAnd() - ProbSumOr() ``` """ macro sugfis(ex::Expr) return _fis(ex, :SugenoFuzzySystem) end function _fis(ex::Expr, type) @capture ex function name_(argsin__)::({argsout__} | argsout__) body_ end argsin, argsout = process_args(argsin), process_args(argsout) inputs, outputs, opts, rules = parse_body(body, argsin, argsout, type) fis = :($type(; name = $(QuoteNode(name)), inputs = $inputs, outputs = $outputs, rules = $rules)) append!(fis.args[2].args, opts) return fis end process_args(x::Symbol) = [x] function process_args(ex::Expr) if @capture(ex, x_[start_:stop_]) [Symbol(x, i) for i in start:stop] else throw(ArgumentError("invalid expression $ex")) end end process_args(v::Vector) = mapreduce(process_args, vcat, v) """ convert a symbol or expression to variable name. A symbol is returned as such. An expression in the form `:(x[i])` is converted to a symbol `:xi`. """ to_var_name(ex::Symbol) = ex function to_var_name(ex::Expr) if @capture(ex, x_[i_]) return Symbol(x, eval(i)) else throw(ArgumentError("Invalid variable name $ex")) end end function parse_variable(var, args) mfs = :(dictionary([])) ex = :(Variable()) for arg in args if @capture(arg, domain=low_:high_) push!(ex.args, :(Domain($low, $high))) elseif @capture(arg, mfname_=mfex_) push!(mfs.args[2].args, :($(QuoteNode(mfname)) => $mfex)) else throw(ArgumentError("Invalid expression $arg")) end end push!(ex.args, mfs) return :($(QuoteNode(var)) => $ex) end function parse_body(body, argsin, argsout, type) opts = Expr[] rules = Expr(:vect) inputs = :(dictionary([])) outputs = :(dictionary([])) for line in body.args line isa LineNumberNode && continue parse_line!(inputs, outputs, rules, opts, line, argsin, argsout, type) end return inputs, outputs, opts, rules end function parse_line!(inputs, outputs, rules, opts, line, argsin, argsout, type) if @capture(line, var_:=begin args__ end) var = to_var_name(var) if var in argsin push!(inputs.args[2].args, parse_variable(var, args)) elseif var in argsout # TODO: makes this more scalable push!(outputs.args[2].args, type == :SugenoFuzzySystem ? parse_sugeno_output(var, args, argsin) : parse_variable(var, args)) else throw(ArgumentError("Undefined variable $var")) end elseif @capture(line, for i_ in start_:stop_ sts__ end) for j in start:stop for st in sts ex = MacroTools.postwalk(x -> x == i ? j : x, st) parse_line!(inputs, outputs, rules, opts, ex, argsin, argsout, type) end end elseif @capture(line, var_=value_) var in SETTINGS[type] || throw(ArgumentError("Invalid keyword $var in line $line")) push!(opts, Expr(:kw, var, value isa Symbol ? :($value()) : value)) elseif @capture(line, ant_-->(cons__,) * w_Number) push!(rules.args, parse_rule(ant, cons, w)) elseif @capture(line, ant_-->p_ == q_ * w_Number) push!(rules.args, parse_rule(ant, [:($p == $q)], w)) elseif @capture(line, ant_-->(cons__,) | cons__) push!(rules.args, parse_rule(ant, cons)) else throw(ArgumentError("Invalid expression $line")) end end ################# # RULES PARSING # ################# function parse_rule(ant, cons, w) Expr(:call, :WeightedFuzzyRule, parse_antecedent(ant), parse_consequents(cons), w) end function parse_rule(ant, cons) Expr(:call, :FuzzyRule, parse_antecedent(ant), parse_consequents(cons)) end function parse_antecedent(ant) if @capture(ant, left_&&right_) return Expr(:call, :FuzzyAnd, parse_antecedent(left), parse_antecedent(right)) elseif @capture(ant, left_||right_) return Expr(:call, :FuzzyOr, parse_antecedent(left), parse_antecedent(right)) elseif @capture(ant, subj_==prop_) return Expr(:call, :FuzzyRelation, QuoteNode(to_var_name(subj)), QuoteNode(to_var_name(prop))) elseif @capture(ant, subj_!=prop_) return Expr(:call, :FuzzyNegation, QuoteNode(to_var_name(subj)), QuoteNode(to_var_name(prop))) else throw(ArgumentError("Invalid premise $ant")) end end function parse_consequents(cons) newcons = map(cons) do c @capture(c, subj_==prop_) || throw(ArgumentError("Invalid consequence $c")) Expr(:call, :FuzzyRelation, QuoteNode(to_var_name(subj)), QuoteNode(to_var_name(prop))) end return Expr(:vect, newcons...) end ############################ # PARSE SUGENO EXPRESSIONS # ############################ function parse_sugeno_coeffs(exs::Vector, argsin::Vector, mfname::Symbol) coeffs = :([$([0 for _ in 1:length(argsin)]...)]) offsets = [] for ex in exs if @capture(ex, c_Number*var_Symbol) idx = findfirst(==(var), argsin) isnothing(idx) && throw(ArgumentError("Unkonwn variable $var in $mfname definition")) coeffs.args[idx] = c elseif ex isa Number push!(offsets, ex) elseif ex isa Symbol idx = findfirst(==(ex), argsin) isnothing(idx) && throw(ArgumentError("Unkonwn variable $ex in $mfname definition")) coeffs.args[idx] = 1 else throw(ArgumentError("Invalid expression $ex in $mfname definition")) end end length(offsets) < 2 || throw(ArgumentError("multiple constants in $(Expr(:tuple, exs...))")) coeffs, isempty(offsets) ? 0 : only(offsets) end function parse_sugeno_output(var, args, argsin) mfs = :(dictionary([])) ex = :(Variable()) inputs = Expr(:vect, map(QuoteNode, argsin)...) for arg in args if @capture(arg, domain=low_:high_) push!(ex.args, :(Domain($low, $high))) elseif @capture(arg, mfname_=c_Number) push!(mfs.args[2].args, :($(QuoteNode(mfname)) => $(ConstantSugenoOutput(c)))) elseif @capture(arg, mfname_=(mfex__,) | mfex__) coeffs, offset = parse_sugeno_coeffs(mfex, argsin, mfname) mf = :(LinearSugenoOutput(Dictionary($inputs, $coeffs), $offset)) push!(mfs.args[2].args, :($(QuoteNode(mfname)) => $mf)) else throw(ArgumentError("Invalid expression $arg")) end end push!(ex.args, mfs) return :($(QuoteNode(var)) => $ex) end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
5618
using RecipesBase # plot membership function @recipe function f(mf::AbstractMembershipFunction, low::Real, high::Real) legend --> nothing x -> mf(x), low, high end # special case: singleton mf @recipe function f(mf::SingletonMF, low::Real, high::Real) legend --> nothing line --> :stem marker --> :circle markersize --> 10 xlims --> (low, high) [mf.c], [1] end @recipe function f(mf::Type2MF, low::Real, high::Real) legend --> nothing @series begin fillrange := x -> mf.hi(x) fillalpha --> 0.5 linealpha --> 1 linewidth --> 2 x -> mf.lo(x), low, high end @series begin primary := false linewidth --> 2 x -> mf.hi(x), low, high end end @recipe f(mf::AbstractPredicate, dom::Domain) = mf, low(dom), high(dom) # plot sugeno membership functions @recipe function f(mf::ConstantSugenoOutput, low::Real, high::Real) legend --> nothing ylims --> (low, high) yticks --> [low, mf.c, high] xticks --> nothing x -> mf(x), low, high end @recipe function f(mf::LinearSugenoOutput, low::Real, high::Real) legend --> nothing line --> :stem framestyle --> :origin x = 1:2:(2 * length(mf.coeffs) + 2) xticks --> (x, push!(collect(keys(mf.coeffs)), :offset)) xlims --> (0, x[end] + 1) x, push!(collect(mf.coeffs), mf.offset) end # plot variables @recipe function f(var::Variable, varname::Union{Symbol, Nothing} = nothing) issugeno = first(var.mfs) isa AbstractSugenoOutputFunction if !isnothing(varname) plot_title --> string(varname) end dom = domain(var) mfs = memberships(var) if issugeno legend --> false layout --> (1, length(var.mfs)) else legend --> true end for (name, mf) in pairs(mfs) @series begin if issugeno title --> string(name) else label --> string(name) end mf, dom end end nothing end @recipe function f(fis::AbstractFuzzySystem, varname::Symbol) if haskey(fis.inputs, varname) fis.inputs[varname], varname elseif haskey(fis.outputs, varname) fis.outputs[varname], varname end end # plot fis @recipe function f(fis::AbstractFuzzySystem) plot_title := string(fis.name) nout = length(fis.outputs) nin = length(fis.inputs) nrules = length(fis.rules) layout := (nrules, nin + nout) size --> (300 * (nin + nout), 200 * nrules) for (i, rule) in enumerate(fis.rules) ants = leaves(rule.antecedent) for (j, (varname, var)) in enumerate(pairs(fis.inputs)) idx = findall(x -> subject(x) == varname, ants) length(idx) > 1 && throw(ArgumentError("Cannot plot repeated variables in rules")) @series if length(idx) == 1 rel = ants[first(idx)] title := string(rel) subplot := (i - 1) * (nin + nout) + j # TODO: use own recipes for negation and relation if rel isa FuzzyNegation legend --> false x -> 1 - var.mfs[predicate(rel)](x), low(var.domain), high(var.domain) else var.mfs[predicate(rel)], var.domain end else subplot := (i - 1) * (nin + nout) + j grid --> false axis --> false legend --> false () end end for (j, (varname, var)) in enumerate(pairs(fis.outputs)) idx = findall(x -> subject(x) == varname, rule.consequent) length(idx) > 1 && throw(ArgumentError("Cannot plot repeated variables in rules")) @series if length(idx) == 1 subplot := (i - 1) * (nin + nout) + nin + j rel = rule.consequent[first(idx)] title := string(rel) var.mfs[predicate(rel)], var.domain else subplot := (i - 1) * (nin + nout) + nin + j grid --> false axis --> false legend --> false () end end end end @userplot GenSurf @recipe function f(plt::GenSurf; Npoints = 100) fis = first(plt.args) if length(fis.inputs) > 2 throw(ArgumentError("Cannot plot generating surface for a system with more than 2 inputs")) end if length(fis.outputs) > 1 throw(ArgumentError("Cannot plot generating surface for a system with more than one output.")) end o = first(keys(fis.outputs)) if length(fis.inputs) == 2 x, y = fis.inputs seriestype := :surface xlabel --> first(keys(fis.inputs)) ylabel --> last(keys(fis.inputs)) zlabel --> o range(x.domain.low, x.domain.high, Npoints), range(x.domain.low, x.domain.high, Npoints), (x, y) -> fis((x, y))[o] else x = first(fis.inputs) xlabel --> first(keys(fis.inputs)) ylabel --> o legend --> nothing range(x.domain.low, x.domain.high, Npoints), x -> fis((x,))[o] end end """ gensurf(fis::AbstractFuzzySystem; Npoints=100) Plots the generating surface of the given fuzzy inference system. The given FIS must have exactly one output and at most two inputs. ### Inputs - `fis::AbstractFuzzySystem` -- fuzzy inference system to plot - `Npoints::Int64 (default 100)` -- number of sample points used for each input to plot the generating surface. """ gensurf
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
1096
""" Read a fuzzy system from a file using a specified format. ### Inputs - `file::String` -- path to the file to read. - `fmt::Union{Symbol,Nothing}` -- input format of the file. If `nothing`, it is inferred from the file extension. Supported formats are - `:fcl` -- Fuzzy Control Language (corresponding file extension `.fcl`) - `:fml` -- Fuzzy Markup Language (corresponding file extension `.xml`) - `:matlab` -- Matlab fis (corresponding file extension `.fis`) """ function readfis(file::String, fmt::Union{Symbol, Nothing} = nothing)::AbstractFuzzySystem if isnothing(fmt) ex = split(file, ".")[end] fmt = if ex == "fcl" :fcl elseif ex == "fis" :matlab elseif ex == "xml" :fml else throw(ArgumentError("Unrecognized extension $ex.")) end end s = read(file, String) if fmt === :fcl parse_fcl(s) elseif fmt === :matlab parse_matlabfis(s) elseif fmt === :fml parse_fml(s) else throw(ArgumentError("Unknown format $fmt.")) end end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
3285
# Data structure to describe fuzzy rules. abstract type AbstractFuzzyProposition end """ Describes a fuzzy relation like "food is good". """ struct FuzzyRelation <: AbstractFuzzyProposition "subject of the relation." subj::Symbol "property of the relation." prop::Symbol end Base.show(io::IO, fr::FuzzyRelation) = print(io, fr.subj, " is ", fr.prop) subject(fr::FuzzyRelation) = fr.subj predicate(fr::FuzzyRelation) = fr.prop """ Describes a fuzzy relation like "food is good". """ struct FuzzyNegation <: AbstractFuzzyProposition "subject of the relation." subj::Symbol "property of the relation." prop::Symbol end Base.show(io::IO, fr::FuzzyNegation) = print(io, fr.subj, " is not ", fr.prop) subject(fr::FuzzyNegation) = fr.subj predicate(fr::FuzzyNegation) = fr.prop """ Describes the conjuction of two propositions. """ struct FuzzyAnd{T <: AbstractFuzzyProposition, S <: AbstractFuzzyProposition} <: AbstractFuzzyProposition left::T right::S end Base.show(io::IO, fa::FuzzyAnd) = print(io, '(', fa.left, " ∧ ", fa.right, ')') """ Describe disjunction of two propositions. """ struct FuzzyOr{T <: AbstractFuzzyProposition, S <: AbstractFuzzyProposition} <: AbstractFuzzyProposition left::T right::S end Base.show(io::IO, fo::FuzzyOr) = print(io, '(', fo.left, " ∨ ", fo.right, ')') abstract type AbstractRule end """ Describes a fuzzy implication rule IF antecedent THEN consequent. """ struct FuzzyRule{T <: AbstractFuzzyProposition} <: AbstractRule "premise of the inference rule." antecedent::T "consequences of the inference rule." consequent::Vector{FuzzyRelation} end Base.show(io::IO, r::FuzzyRule) = print(io, r.antecedent, " --> ", join(r.consequent, ", ")) """ Weighted fuzzy rule. In Mamdani systems, the result of implication is scaled by the weight. In Sugeno systems, the result of the antecedent is scaled by the weight. """ struct WeightedFuzzyRule{T <: AbstractFuzzyProposition, S <: Real} <: AbstractRule "premise of the inference rule." antecedent::T "consequences of the inference rule." consequent::Vector{FuzzyRelation} "weight of the rule." weight::S end function Base.show(io::IO, r::WeightedFuzzyRule) print(io, r.antecedent, " --> ", join(r.consequent, ", "), " (", r.weight, ")") end @inline scale(w, ::FuzzyRule) = w @inline scale(w, r::WeightedFuzzyRule) = w * r.weight # comparisons (for testing) Base.:(==)(r1::FuzzyRelation, r2::FuzzyRelation) = r1.subj == r2.subj && r1.prop == r2.prop Base.:(==)(r1::FuzzyNegation, r2::FuzzyNegation) = r1.subj == r2.subj && r1.prop == r2.prop function Base.:(==)(p1::T, p2::T) where {T <: AbstractFuzzyProposition} p1.left == p2.left && p1.right == p2.right end Base.:(==)(p1::AbstractFuzzyProposition, p2::AbstractFuzzyProposition) = false function Base.:(==)(r1::FuzzyRule, r2::FuzzyRule) r1.antecedent == r2.antecedent && r1.consequent == r1.consequent end function Base.:(==)(r1::WeightedFuzzyRule, r2::WeightedFuzzyRule) r1.antecedent == r2.antecedent && r1.consequent == r1.consequent && r1.weight == r2.weight end # utilities leaves(fr::Union{FuzzyNegation, FuzzyRelation}) = (fr,) leaves(fp::AbstractFuzzyProposition) = [leaves(fp.left)..., leaves(fp.right)...]
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
13092
""" Compile the fuzzy inference system into stand-alone Julia code. If the first argument is a string, it write the code in the given file, otherwise it returns the Julia expression of the code. ### Inputs - `fname::AbstractString` -- file where to write - `fis::AbstractFuzzySystem` -- fuzzy system to compile - `name::Symbol` -- name of the generated function, default `fis.name` ### Notes Only type-1 inference systems are supported """ function compilefis(fname::AbstractString, fis::AbstractFuzzySystem, name::Symbol = fis.name) open(fname, "w") do io write(io, string(to_expr(fis, name))) end end @inline compilefis(fis::AbstractFuzzySystem, name::Symbol = fis.name) = to_expr(fis, name) function to_expr(fis::MamdaniFuzzySystem, name::Symbol = fis.name) body = quote end for (varname, var) in pairs(fis.inputs) for (mfname, mf) in pairs(var.mfs) push!(body.args, :($mfname = $(to_expr(mf, varname)))) end end # parse rules. Antecedents are stored in local variables, which can be useful if one has # multiple outputs. Each rule is converted to a dictionary indexed by output variable. rules = Vector{Dict{Symbol, Expr}}(undef, length(fis.rules)) for (i, rule) in enumerate(fis.rules) ant_name = Symbol(:ant, i) ant_body = to_expr(fis, rule.antecedent) push!(body.args, :($ant_name = $ant_body)) rules[i] = to_expr(fis, rule; antidx = i) end # construct expression that computes each output for (varname, var) in pairs(fis.outputs) varagg = Symbol(varname, :_agg) out_dom = LinRange(low(var.domain), high(var.domain), fis.defuzzifier.N + 1) push!(body.args, :($varagg = collect($out_dom))) # vector for aggregated output # evaluate output membership functions. rule_eval = quote end for (mfname, mf) in pairs(var.mfs) push!(rule_eval.args, :($mfname = $(to_expr(mf)))) end # construct expression that performs implication and aggregation of all rules agg = :() for rule in rules if haskey(rule, varname) if agg == :() agg = rule[varname] else agg = to_expr(fis.aggregator, agg, rule[varname]) end end end defuzz = to_expr(fis.defuzzifier, Symbol(varname, :_agg), var.domain) # defuzzifier ex = quote @inbounds for (i, x) in enumerate($varagg) $rule_eval $varagg[i] = $agg end $varname = $defuzz end push!(body.args, ex) end prettify(:(function $name($(collect(keys(fis.inputs))...)) $body return $(keys(fis.outputs)...) end)) end function to_expr(fis::SugenoFuzzySystem, name::Symbol = fis.name) body = quote end for (varname, var) in pairs(fis.inputs) for (mfname, mf) in pairs(var.mfs) push!(body.args, :($mfname = $(to_expr(mf, varname)))) end end rules = Vector{Dict{Symbol, Expr}}(undef, length(fis.rules)) tot_weight = Expr(:call, :+) for (i, rule) in enumerate(fis.rules) ant, res = to_expr(fis, rule, i) push!(body.args, ant) push!(tot_weight.args, Symbol(:ant, i)) rules[i] = res end push!(body.args, :(tot_weight = $tot_weight)) for (varname, var) in pairs(fis.outputs) num = Expr(:call, :+) for (mfname, mf) in pairs(var.mfs) push!(body.args, :($mfname = $(to_expr(mf)))) end for rule in rules if haskey(rule, varname) push!(num.args, rule[varname]) end end ex = :($varname = $num / tot_weight) push!(body.args, ex) end prettify(:(function $name($(collect(keys(fis.inputs))...)) $body return $(keys(fis.outputs)...) end)) end ######################################## # MEMBERSHIP FUNCTIONS CODE GENERATION # ######################################## to_expr(mf::SingletonMF, x = :x) = :($x == $(mf.c) ? one($x) : zero($x)) to_expr(mf::GaussianMF, x = :x) = :(exp(-($x - $(mf.mu))^2 / $(2 * mf.sig^2))) function to_expr(mf::TriangularMF, x = :x) :(max(min(($x - $(mf.a)) / $(mf.b - mf.a), ($(mf.c) - $x) / $(mf.c - mf.b)), 0)) end function to_expr(mf::TrapezoidalMF, x = :x) :(max(min(($x - $(mf.a)) / $(mf.b - mf.a), 1, ($(mf.d) - $x) / $(mf.d - mf.c)), 0)) end function to_expr(mf::LinearMF, x = :x) :(max(min(($x - $(mf.a)) / ($(mf.b) - $(mf.a)), 1), 0)) end function to_expr(mf::SigmoidMF, x = :x) :(1 / (1 + exp(-$(mf.a) * ($x - $(mf.c))))) end function to_expr(mf::DifferenceSigmoidMF, x = :x) :(max(min(1 / (1 + exp(-$(mf.a1) * ($x - $(mf.c1)))) - 1 / (1 + exp(-$(mf.a2) * ($x - $(mf.c2)))), 1), 0)) end function to_expr(mf::ProductSigmoidMF, x = :x) :(1 / ((1 + exp(-$(mf.a1) * ($x - $(mf.c1)))) * (1 + exp(-$(mf.a2) * ($x - $(mf.c2)))))) end function to_expr(mf::GeneralizedBellMF, x = :x) :(1 / (1 + abs(($x - $(mf.c)) / $(mf.a))^$(2mf.b))) end function to_expr(s::SShapeMF, x = :x) :(if $x <= $(s.a) zero(float(typeof($x))) elseif $x >= $(s.b) one(float(typeof($x))) elseif $x >= $((s.a + s.b) / 2) 1 - $(2 / (s.b - s.a)^2) * ($x - $(s.b))^2 else $(2 / (s.b - s.a)^2) * ($x - $(s.a))^2 end) end function to_expr(mf::ZShapeMF, x = :x) :(if $x <= $(mf.a) one(float(typeof($x))) elseif $x >= $(mf.b) zero(float(typeof($x))) elseif $x >= $((mf.a + mf.b) / 2) $(2 / (mf.b - mf.a)^2) * ($x - $(mf.b))^2 else 1 - $(2 / (mf.b - mf.a)^2) * ($x - $(mf.a))^2 end) end function to_expr(p::PiShapeMF, x = :x) :(if $x <= $(p.a) || $x >= $(p.d) zero(float(typeof($x))) elseif $(p.b) <= $x <= $(p.c) one(float(typeof($x))) elseif $x <= $((p.a + p.b) / 2) $(2 / (p.b - p.a)^2) * ($x - $(p.a))^2 elseif $x <= $(p.b) 1 - $(2 / (p.b - p.a)^2) * ($x - $(p.b))^2 elseif $x <= $((p.c + p.d) / 2) 1 - $(2 / (p.d - p.c)^2) * ($x - $(p.c))^2 else $(2 / (p.d - p.c)^2) * ($x - $(p.d))^2 end) end function to_expr(se::SemiEllipticMF, x = :x) :(if $(se.cd - se.rd) <= $x <= $(se.cd + se.rd) sqrt(1 - ($(se.cd) - $x)^2 / $(se.rd)^2) else zero($x) end) end function to_expr(plmf::PiecewiseLinearMF, x = :x) :(if $x <= $(plmf.points[1][1]) $(float(plmf.points[1][2])) elseif $x >= $(plmf.points[end][1]) $(float(plmf.points[end][2])) else pnts = $(plmf.points) idx = findlast(p -> $x >= p[1], pnts) x1, y1 = pnts[idx] x2, y2 = pnts[idx + 1] (y2 - y1) / (x2 - x1) * ($x - x1) + y1 end) end function to_expr(mf::WeightedMF, x = :x) :($(mf.w) * $(to_expr(mf.mf, x))) end to_expr(mf::ConstantSugenoOutput) = mf.c function to_expr(mf::LinearSugenoOutput) ex = Expr(:call, :+, mf.offset) for (varname, coeff) in pairs(mf.coeffs) push!(ex.args, :($coeff * $varname)) end return ex end ##################################### # LOGICAL OPERATORS CODE GENERATION # ##################################### to_expr(::MinAnd, x = :y, y = :y) = :(min($x, $y)) to_expr(::ProdAnd, x = :x, y = :y) = :($x * $y) to_expr(::LukasiewiczAnd, x = :x, y = :y) = :(max(0, $x + $y - 1)) function to_expr(::DrasticAnd, x = :x, y = :y) :(isone($x) || isone($y) ? min($x, $y) : zero(promote_type(typeof($x), typeof($y)))) end function to_expr(::NilpotentAnd, x = :x, y = :y) :($x + $y > 1 ? min($x, $y) : zero(promote_type(typeof($x), typeof($y)))) end function to_expr(::HamacherAnd, x = :x, y = :y) :(let z = ($x * $y) / ($x + $y - $x * $y) isfinite(z) ? z : zero(z) end) end to_expr(::EinsteinAnd, x = :x, y = :y) = :(($x * $y) / (2 - $x - $y + $x * $y)) to_expr(::MaxOr, x = :x, y = :y) = :(max($x, $y)) to_expr(::ProbSumOr, x = :x, y = :y) = :($x + $y - $x * $y) to_expr(::BoundedSumOr, x = :x, y = :y) = :(min(1, $x + $y)) function to_expr(::DrasticOr, x = :x, y = :y) :(iszero($x) || iszero($y) ? max($x, $y) : one(promote_type(typeof($x), typeof($y)))) end function to_expr(::NilpotentOr, x = :x, y = :y) :($x + $y < 1 ? max($x, $y) : one(promote_type(typeof($x), typeof($y)))) end function to_expr(::HamacherOr, x = :x, y = :y) :(let z = ($x + $y - 2 * $x * $y) / (1 - $x * $y) isfinite(z) ? z : one(z) end) end to_expr(::EinsteinOr, x = :x, y = :y) = :(($x + $y) / (1 + $x * $y)) to_expr(::MinImplication, x = :x, y = :y) = :(min($x, $y)) to_expr(::ProdImplication, x = :x, y = :y) = :($x * $y) to_expr(::MaxAggregator, x = :x, y = :y) = :(max($x, $y)) to_expr(::ProbSumAggregator, x = :x, y = :y) = :($x + $y - $x * $y) ######################### # RULES CODE GENERATION # ######################### function to_expr(fis::MamdaniFuzzySystem, rule::FuzzyRule; antidx = nothing) res = Dict{Symbol, Expr}() for cons in rule.consequent ant = isnothing(antidx) ? to_expr(fis, rule.antecedent) : Symbol(:ant, antidx) res[cons.subj] = to_expr(fis.implication, ant, to_expr(fis, cons)) end res end function to_expr(fis::MamdaniFuzzySystem, rule::WeightedFuzzyRule; antidx = nothing) res = to_expr(fis, FuzzyRule(rule.antecedent, rule.consequent); antidx) for (var, ex) in res res[var] = :($(rule.weight) * $ex) end res end to_expr(::AbstractFuzzySystem, r::FuzzyRelation) = r.prop to_expr(::AbstractFuzzySystem, r::FuzzyNegation) = :(1 - $(r.prop)) function to_expr(fis::AbstractFuzzySystem, r::FuzzyAnd) to_expr(fis.and, to_expr(fis, r.left), to_expr(fis, r.right)) end function to_expr(fis::AbstractFuzzySystem, r::FuzzyOr) to_expr(fis.or, to_expr(fis, r.left), to_expr(fis, r.right)) end function to_expr(fis::SugenoFuzzySystem, rule::AbstractRule, antidx) antbody = to_expr(fis, rule.antecedent) if rule isa WeightedFuzzyRule antbody = :($(rule.weight) * $antbody) end antname = Symbol(:ant, antidx) ant = Expr(:(=), antname, antbody) res = Dict{Symbol, Expr}() for cons in rule.consequent res[cons.subj] = Expr(:call, :*, antname, to_expr(fis, cons)) end return ant, res end ################################ # DEFUZZIFIERS CODE GENERATION # ################################ function to_expr(defuzz::CentroidDefuzzifier, mf, dom::Domain) :((2sum(mfi * xi for (mfi, xi) in zip($mf, $(LinRange(low(dom), high(dom), defuzz.N + 1)))) - first($mf) * $(low(dom)) - last($mf) * $(high(dom))) / (2sum($mf) - first($mf) - last($mf))) end function to_expr(defuzz::BisectorDefuzzifier, mf, dom::Domain{T}) where {T <: Real} area_left = zero(T) h = (high(dom) - low(dom)) / defuzz.N area_right = :((2sum($mf) - first(mf) - last(mf)) * $(h / 2)) cand = LinRange(low(dom), high(dom), defuzz.N + 1) :(let mf = $mf area_left = $area_left h = $h area_right = (2sum(mf) - first(mf) - last(mf)) * $(h / 2) cand = $cand i = firstindex(mf) while area_left < area_right trap = (mf[i] + mf[i + 1]) * $(h / 2) area_left += trap area_right -= trap i += 1 end (mf[i - 1] + mf[i]) * $(h / 2) >= area_left - area_right ? cand[i] : cand[i - 1] end) end function to_expr(defuzz::LeftMaximumDefuzzifier, mf, dom::Domain{T}) where {T <: Real} :(let res = $(float(low(dom))) y = $mf maxval = first(y) for (xi, yi) in zip($(LinRange(low(dom), high(dom), defuzz.N + 1)), y) if yi > maxval + $(defuzz.tol) res = xi maxval = yi end end res end) end function to_expr(defuzz::RightMaximumDefuzzifier, mf, dom::Domain{T}) where {T <: Real} :(let res = $(float(low(dom))) y = $mf maxval = first(y) for (xi, yi) in zip($(LinRange(low(dom), high(dom), defuzz.N + 1)), y) if yi >= maxval - $(defuzz.tol) res = xi maxval = yi end end res end) end function to_expr(defuzz::MeanOfMaximaDefuzzifier, mf, dom::Domain{T}) where {T <: Real} :(let res = $(zero(float(T))) y = $mf maxval = first(y) maxcnt = 0 for (xi, yi) in zip($(LinRange(low(dom), high(dom), defuzz.N + 1)), y) if yi - maxval > $(defuzz.tol) # reset mean calculation res = xi maxval = yi maxcnt = 1 elseif abs(yi - maxval) <= $(defuzz.tol) res += xi maxcnt += 1 end end res / maxcnt end) end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
514
""" An interval representing the domain of a given variable. """ struct Domain{T <: Real} "lower bound." low::T "upper bound." high::T end Base.show(io::IO, d::Domain) = print(io, '[', low(d), ", ", high(d), ']') low(d::Domain) = d.low high(d::Domain) = d.high struct Variable domain::Domain mfs::Dictionary{Symbol, AbstractPredicate} end Base.:(==)(x::Variable, y::Variable) = x.domain == y.domain && x.mfs == y.mfs domain(var::Variable) = var.domain memberships(var::Variable) = var.mfs
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
7019
module FCLParser using PEG, Dictionaries using ..FuzzyLogic using ..FuzzyLogic: Variable, Domain export parse_fcl, @fcl_str const FCL_JULIA = Dict("COG" => CentroidDefuzzifier(), "COGS" => "COGS", # dummy since hardcoded for sugeno "COA" => BisectorDefuzzifier(), "LM" => LeftMaximumDefuzzifier(), "RM" => RightMaximumDefuzzifier(), "MOM" => MeanOfMaximaDefuzzifier(), "ANDMIN" => MinAnd(), "ANDPROD" => ProdAnd(), "ANDBDIF" => LukasiewiczAnd(), "ORMAX" => MaxOr(), "ORASUM" => ProbSumOr(), "ORBSUM" => BoundedSumOr(), "ACTPROD" => ProdImplication(), "ACTMIN" => MinImplication()) function fcl_julia(s::AbstractString) haskey(FCL_JULIA, s) ? FCL_JULIA[s] : throw(ArgumentError("Option $s not supported.")) end function parse_rule(x) if isempty(x[5]) FuzzyLogic.FuzzyRule(x[2], x[4]) else FuzzyLogic.WeightedFuzzyRule(x[2], x[4], x[5][1][2]) end end @rule id = r"[a-zA-Z_]+[a-zA-z0-9_]*"p |> Symbol @rule function_block = r"FUNCTION_BLOCK"p & id & var_input_block & var_output_block & fuzzify_block[1:end] & defuzzify_block[1:end] & rule_block & r"END_FUNCTION_BLOCK"p |> x -> x[2:7] @rule var_input_block = r"VAR_INPUT"p & var_def[1:end] & r"END_VAR"p |> x -> Vector{Symbol}(x[2]) @rule var_output_block = r"VAR_OUTPUT"p & var_def[1:end] & r"END_VAR"p |> x -> Vector{Symbol}(x[2]) @rule var_def = id & r":"p & r"REAL"p & r";"p |> first @rule fuzzify_block = r"FUZZIFY"p & id & linguistic_term[1:end] & range_term & r"END_FUZZIFY"p |> x -> x[2] => Variable(x[4], dictionary(x[3])) @rule range_term = r"RANGE\s*:=\s*\("p & numeral & r".."p & numeral & r"\)\s*;"p |> x -> Domain(x[2], x[4]) @rule linguistic_term = r"TERM"p & id & r":="p & membership_function & r";"p |> x -> x[2] => x[4] @rule membership_function = singleton, points @rule singleton = r"[+-]?\d+\.?\d*([eE][+-]?\d+)?"p |> ConstantSugenoOutput ∘ Base.Fix1(parse, Float64) @rule numeral = r"[+-]?\d+(\.\d+)?([eE][+-]?\d+)?"p |> Base.Fix1(parse, Float64) @rule point = r"\("p & numeral & r","p & numeral & r"\)"p |> x -> tuple(x[2], x[4]) @rule points = point[2:end] |> PiecewiseLinearMF ∘ Vector{Tuple{Float64, Float64}} @rule defuzzify_block = r"DEFUZZIFY"p & id & linguistic_term[1:end] & defuzzify_method & range_term & r"END_DEFUZZIFY"p |> (x -> (x[2] => Variable(x[5], dictionary(x[3])), x[4])) @rule defuzzify_method = r"METHOD\s*:"p & (r"COGS"p, r"COG"p, r"COA"p, r"LM"p, r"RM"p) & r";"p |> x -> fcl_julia(x[2]) @rule rule_block = r"RULEBLOCK"p & id & operator_definition & activation_method[:?] & rule[1:end] & r"END_RULEBLOCK"p |> x -> (x[3], x[4], identity.(x[5])) @rule or_definition = r"OR"p & r":"p & (r"MAX"p, r"ASUM"p, r"BSUM"p) & r";"p @rule and_definition = r"AND"p & r":"p & (r"MIN"p, r"PROD"p, r"BDIF"p) & r";"p @rule operator_definition = (and_definition, or_definition) |> x -> fcl_julia(join([x[1], x[3]])) @rule activation_method = r"ACT"p & r":"p & (r"MIN"p, r"PROD"p) & r";"p |> x -> fcl_julia(join([x[1], x[3]])) @rule rule = r"RULE\s+\d+\s*:\s*IF"p & condition & r"THEN"p & conclusion & (r"WITH"p & numeral)[:?] & r";"p |> parse_rule @rule relation = negrel, posrel @rule posrel = id & r"IS"p & id |> x -> FuzzyLogic.FuzzyRelation(x[1], x[3]) @rule negrel = (id & r"IS\s+NOT"p & id |> x -> FuzzyLogic.FuzzyNegation(x[1], x[3])), r"NOT\s*\("p & id & r"IS"p & id & r"\)"p |> x -> FuzzyLogic.FuzzyNegation(x[2], x[4]) @rule conclusion = posrel & (r","p & posrel)[*] |> x -> append!([x[1]], map(last, x[2])) @rule condition = orcondition @rule orcondition = andcondition & (r"OR"p & andcondition)[*] |> x -> reduce(FuzzyLogic.FuzzyOr, vcat(x[1], map(last, x[2]))) @rule andcondition = term & (r"AND"p & term)[*] |> x -> reduce(FuzzyLogic.FuzzyAnd, vcat(x[1], map(last, x[2]))) @rule term = relation, r"\("p & condition & r"\)"p |> x -> x[2] """ parse_fcl(s::String)::AbstractFuzzySystem Parse a fuzzy inference system from a string representation in Fuzzy Control Language (FCL). ### Inputs - `s::String` -- string describing a fuzzy system in FCL conformant to the IEC 1131-7 standard. ### Notes The parsers can read FCL comformant to IEC 1131-7, with the following remarks: - Sugeno (system with singleton outputs) shall use COGS as defuzzifier. - the `RANGE` keyword is required for both fuzzification and defuzzification blocks. - Only the required `MAX` accumulator is supported. - Default value for defuzzification not supported. - Optional local variables are not supported. With the exceptions above, the parser supports all required and optional features of the standard (tables 6.1-1 and 6.1-2). In addition, it also supports the following features: - Piecewise linear functions can have any number of points. - Membership degrees in piecewise linear functions points can be any number between ``0`` and ``1``. """ function parse_fcl(s::String)::FuzzyLogic.AbstractFuzzySystem name, inputs, outputs, inputsmfs, outputsmf, (op, imp, rules) = parse_whole(function_block, s) varsin = dictionary(inputsmfs) @assert sort(collect(keys(varsin)))==sort(inputs) "Mismatch between declared and fuzzified input variables." varsout = dictionary(first.(outputsmf)) @assert sort(collect(keys(varsout)))==sort(outputs) "Mismatch between declared and defuzzified output variables." @assert all(==(outputsmf[1][2]), last.(outputsmf)) "All output variables should use the same defuzzification method." defuzzifier = outputsmf[1][2] and, or = ops_pairs(op) if defuzzifier == "COGS" # sugeno SugenoFuzzySystem(name, varsin, varsout, rules, and, or) else # mamdani imp = isempty(imp) ? MinImplication() : first(imp) MamdaniFuzzySystem(name, varsin, varsout, rules, and, or, imp, MaxAggregator(), defuzzifier) end end ops_pairs(::MinAnd) = MinAnd(), MaxOr() ops_pairs(::ProdAnd) = ProdAnd(), ProbSumOr() ops_pairs(::LukasiewiczAnd) = LukasiewiczAnd(), BoundedSumOr() ops_pairs(::MaxOr) = MinAnd(), MaxOr() ops_pairs(::ProbSumOr) = ProdAnd(), ProbSumOr() ops_pairs(::BoundedSumOr) = LukasiewiczAnd(), BoundedSumOr() """ String macro to parse Fuzzy Control Language (FCL). See [`parse_fcl`](@ref) for more details. """ macro fcl_str(s::AbstractString) parse_fcl(s) end end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
8255
module FMLParser using Dictionaries, LightXML using ..FuzzyLogic using ..FuzzyLogic: FuzzyAnd, FuzzyOr, FuzzyRule, FuzzyRelation, FuzzyNegation, Domain, WeightedFuzzyRule, Variable, memberships, AbstractMembershipFunction, AbstractSugenoOutputFunction export parse_fml, @fml_str XML_JULIA = Dict("mamdaniRuleBase" => MamdaniFuzzySystem, "tskRuleBase" => SugenoFuzzySystem, "triangularShape" => TriangularMF, "trapezoidShape" => TrapezoidalMF, "piShape" => PiShapeMF, "sShape" => SShapeMF, "zShape" => ZShapeMF, "gaussianShape" => GaussianMF, "rightGaussianShape" => GaussianMF, "leftGaussianShape" => GaussianMF, "rightLinearShape" => LinearMF, "leftLinearShape" => LinearMF, "rightLinearShape" => LinearMF, "COG" => CentroidDefuzzifier(), "COA" => BisectorDefuzzifier(), "MOM" => MeanOfMaximaDefuzzifier(), "LM" => LeftMaximumDefuzzifier(), "RM" => RightMaximumDefuzzifier(), "ACCMAX" => MaxAggregator(), "andMIN" => MinAnd(), "andPROD" => ProdAnd(), "andBDIF" => LukasiewiczAnd(), "andDRP" => DrasticAnd(), "andHPROD" => HamacherAnd(), "andEPROD" => EinsteinAnd(), "andNILMIN" => DrasticAnd(), "orMAX" => MaxOr(), "orPROBOR" => ProbSumOr(), "orBSUM" => BoundedSumOr(), "orDRS" => DrasticOr(), "orNILMAX" => NilpotentOr(), "orESUM" => EinsteinOr(), "orHSUM" => HamacherOr(), "impMIN" => MinImplication(), "and" => FuzzyAnd, "or" => FuzzyOr) get_attribute(x, s, d) = has_attribute(x, s) ? attribute(x, s) : d to_key(s, pre) = isempty(pre) ? s : pre * uppercasefirst(s) function process_params(mf, params) if mf == "rightLinearShape" reverse(params) else params end end # Parse variable from xml. FML does not have negated relations, but negated mfs, # so we store in the set `negated` what relations will have to be `FuzzyNegation`. function parse_variable!(var, negated::Set) varname = Symbol(attribute(var, "name")) dom = Domain(parse(Float64, attribute(var, "domainleft")), parse(Float64, attribute(var, "domainright"))) mfs = AbstractMembershipFunction[] mfnames = Symbol[] for term in get_elements_by_tagname(var, "fuzzyTerm") mfname = Symbol(attribute(term, "name")) push!(mfnames, mfname) if has_attribute(term, "complement") && lowercase(attribute(term, "complement")) == "true" push!(negated, (varname, mfname)) end mf = only(child_elements(term)) params = process_params(name(mf), parse.(Float64, value.(collect(attributes(mf))))) push!(mfs, XML_JULIA[name(mf)](params...)) end return varname => Variable(dom, Dictionary(mfnames, identity.(mfs))) end function parse_sugeno_output(var, input_names) varname = Symbol(attribute(var, "name")) dom = Domain(parse(Float64, get_attribute(var, "domainleft", "-Inf")), parse(Float64, get_attribute(var, "domainright", "Inf"))) mfs = AbstractSugenoOutputFunction[] mfnames = Symbol[] for term in get_elements_by_tagname(var, "tskTerm") push!(mfnames, Symbol(attribute(term, "name"))) mf = if attribute(term, "order") == "0" ConstantSugenoOutput(parse(Float64, content(find_element(term, "tskValue")))) elseif attribute(term, "order") == "1" coeffs = map(get_elements_by_tagname(term, "tskValue")) do t parse(Float64, content(t)) end LinearSugenoOutput(Dictionary(input_names, coeffs[1:(end - 1)]), coeffs[end]) end push!(mfs, mf) end return varname => Variable(dom, Dictionary(mfnames, identity.(mfs))) end function parse_knowledgebase(kb, settings) negated = Set{Tuple{Symbol, Symbol}}() inputs = Pair{Symbol, Variable}[] outputs = Pair{Symbol, Variable}[] for var in get_elements_by_tagname(kb, "fuzzyVariable") if attribute(var, "type") == "input" push!(inputs, parse_variable!(var, negated)) elseif attribute(var, "type") == "output" settings[:defuzzifier] = XML_JULIA[get_attribute(var, "defuzzifier", "COG")] settings[:aggregator] = XML_JULIA["ACC" * get_attribute(var, "accumulation", "MAX")] push!(outputs, parse_variable!(var, negated)) end end for var in get_elements_by_tagname(kb, "tskVariable") push!(outputs, parse_sugeno_output(var, first.(inputs))) end settings[:inputs] = dictionary(identity.(inputs)) settings[:outputs] = dictionary(identity.(outputs)) return negated end function parse_rules!(settings, rulebase, negated) pre = name(rulebase) == "tskRuleBase" ? "tsk" : "" settings[:and] = XML_JULIA["and" * get_attribute(rulebase, "andMethod", "MIN")] settings[:or] = XML_JULIA["or" * get_attribute(rulebase, "orMethod", "MAX")] if isempty(pre) settings[:implication] = XML_JULIA["imp" * get_attribute(rulebase, "activationMethod", "MIN")] end settings[:rules] = identity.([parse_rule(rule, negated, pre) for rule in get_elements_by_tagname(rulebase, to_key("rule", pre))]) end function parse_rule(rule, negated, pre = "") op = XML_JULIA[lowercase(get_attribute(rule, "connector", "and"))] ant = find_element(rule, "antecedent") ant = mapreduce(op, get_elements_by_tagname(ant, "clause")) do clause var = Symbol(content(find_element(clause, "variable"))) t = Symbol(content(find_element(clause, "term"))) (var, t) in negated ? FuzzyNegation(var, t) : FuzzyRelation(var, t) end cons = find_element(find_element(rule, to_key("consequent", pre)), to_key("then", pre)) cons = map(get_elements_by_tagname(cons, to_key("clause", pre))) do clause var = Symbol(content(find_element(clause, "variable"))) t = Symbol(content(find_element(clause, "term"))) (var, t) in negated ? FuzzyNegation(var, t) : FuzzyRelation(var, t) end w = parse(Float64, get_attribute(rule, "weight", "1.0")) if isone(w) FuzzyRule(ant, cons) else WeightedFuzzyRule(ant, cons, w) end end function get_rulebase(f) rules = find_element(f, "mamdaniRuleBase") isnothing(rules) || return rules rules = find_element(f, "tskRuleBase") isnothing(rules) || return rules end """ parse_fml(s::String)::AbstractFuzzySystem Parse a fuzzy inference system from a string representation in Fuzzy Markup Language (FML). ### Inputs - `s::String` -- string describing a fuzzy system in FML conformant to the IEEE 1855-2016 standard. ### Notes The parsers can read FML comformant to IEEE 1855-2016, with the following remarks: - only Mamdani and Sugeno are supported. - Operators `and` and `or` definitions should be set in the rule base block. Definitions at individual rules are ignored. - Modifiers are not supported. """ function parse_fml(s::String) parse_fml(root(parse_string(s))) end function parse_fml(f::XMLElement) settings = Dict() kb = only(get_elements_by_tagname(f, "knowledgeBase")) settings[:name] = Symbol(attribute(f, "name")) negated = parse_knowledgebase(kb, settings) rulebase = get_rulebase(f) parse_rules!(settings, rulebase, negated) settings XML_JULIA[name(rulebase)](; settings...) end """ String macro to parse Fuzzy Markup Language (FML). See [`parse_fml`](@ref) for more details. """ macro fml_str(s) parse_fml(s) end end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
5916
module MatlabParser using Dictionaries using ..FuzzyLogic using ..FuzzyLogic: FuzzyAnd, FuzzyOr, FuzzyRule, FuzzyRelation, FuzzyNegation, Domain, WeightedFuzzyRule, Variable, memberships, AbstractMembershipFunction export parse_matlabfis, @matlabfis_str const MATLAB_JULIA = Dict("'mamdani'" => MamdaniFuzzySystem, "'sugeno'" => SugenoFuzzySystem, "and'min'" => MinAnd(), "and'prod'" => ProdAnd(), "or'max'" => MaxOr(), "or'probor'" => ProbSumOr(), "imp'min'" => MinImplication(), "imp'prod'" => ProdImplication(), "agg'max'" => MaxAggregator(), "agg'probor'" => ProbSumAggregator(), "'centroid'" => CentroidDefuzzifier(), "'bisector'" => BisectorDefuzzifier(), "'mom'" => MeanOfMaximaDefuzzifier(), "'lom'" => RightMaximumDefuzzifier(), "'som'" => LeftMaximumDefuzzifier(), "'trapmf'" => TrapezoidalMF, "'trimf'" => TriangularMF, "'gaussmf'" => GaussianMF, "'gbellmf'" => GeneralizedBellMF, "'sigmf'" => SigmoidMF, "'dsigmf'" => DifferenceSigmoidMF, "'psigmf'" => ProductSigmoidMF, "'zmf'" => ZShapeMF, "'smf'" => SShapeMF, "'pimf'" => PiShapeMF, "'linzmf'" => LinearMF, "'linsmf'" => LinearMF, "'constant'" => ConstantSugenoOutput, "'linear'" => LinearSugenoOutput) # Handle special cases where FuzzyLogic.jl and matlab dont store parameters the same way. function preprocess_params(mftype, mfparams; inputs = nothing) mftype in ("'gaussmf'", "'linzmf'") && return reverse(mfparams) mftype == "'linear'" && return [Dictionary(inputs, mfparams[1:(end - 1)]), mfparams[end]] mfparams end function parse_mf(line::AbstractString; inputs = nothing) mfname, mftype, mfparams = split(line, r"[:,]") mfname = Symbol(mfname[2:(end - 1)]) mfparams = parse.(Float64, split(mfparams[2:(end - 1)])) mfparams = preprocess_params(mftype, mfparams; inputs) mfname, MATLAB_JULIA[mftype](mfparams...) end function parse_var(var; inputs = nothing) dom = Domain(parse.(Float64, split(var["Range"][2:(end - 1)]))...) name = Symbol(var["Name"][2:(end - 1)]) mfs = map(1:parse(Int, var["NumMFs"])) do i mfname, mf = parse_mf(var["MF$i"]; inputs) mfname => mf end |> dictionary name, Variable(dom, mfs) end function parse_rule(line, inputnames, outputnames, inputmfs, outputmfs) ants, consw, op = split(line, r"[,:] ") consw = split(consw) considx = parse.(Int, consw[1:length(outputnames)]) w = parse(Float64, consw[end][2:(end - 1)]) antsidx = filter!(!iszero, parse.(Int, split(ants))) filter!(!iszero, considx) op = op == "1" ? FuzzyAnd : FuzzyOr length(antsidx) == 1 && (op = identity) ant = mapreduce(op, enumerate(antsidx)) do (var, mf) if mf > 0 FuzzyRelation(inputnames[var], inputmfs[var][mf]) else FuzzyNegation(inputnames[var], inputmfs[var][-mf]) end end con = map(enumerate(considx)) do (var, mf) FuzzyRelation(outputnames[var], outputmfs[var][mf]) end if isone(w) FuzzyRule(ant, con) else WeightedFuzzyRule(ant, con, w) end end function parse_rules(lines, inputs, outputs) inputnames = collect(keys(inputs)) outputnames = collect(keys(outputs)) inputmfs = collect.(keys.(memberships.(collect(inputs)))) outputmfs = collect.(keys.(memberships.(collect(outputs)))) identity.([parse_rule(line, inputnames, outputnames, inputmfs, outputmfs) for line in lines]) end """ parse_matlabfis(s::AbstractString) Parse a fuzzy inference system from a string in Matlab FIS format. """ function parse_matlabfis(s::AbstractString) lines = strip.(split(s, "\n")) key = "" fis = Dict() for line in lines if occursin(r"\[[a-zA-Z0-9_]+\]", line) key = line fis[key] = ifelse(key == "[Rules]", [], Dict()) elseif !isempty(line) if key != "[Rules]" k, v = split(line, "=") fis[key][k] = v else push!(fis[key], line) end end end sysinfo = fis["[System]"] inputs = Dictionary{Symbol, Variable}() for i in 1:parse(Int, sysinfo["NumInputs"]) varname, var = parse_var(fis["[Input$i]"]) insert!(inputs, varname, var) end outputs = Dictionary{Symbol, Variable}() for i in 1:parse(Int, sysinfo["NumOutputs"]) varname, var = parse_var(fis["[Output$i]"]; inputs = collect(keys(inputs))) insert!(outputs, varname, var) end rules = parse_rules(fis["[Rules]"], inputs, outputs) opts = (; name = Symbol(sysinfo["Name"][2:(end - 1)]), inputs = inputs, outputs = outputs, rules = rules, and = MATLAB_JULIA["and" * sysinfo["AndMethod"]], or = MATLAB_JULIA["or" * sysinfo["OrMethod"]]) if sysinfo["Type"] == "'mamdani'" opts = (; opts..., implication = MATLAB_JULIA["imp" * sysinfo["ImpMethod"]], aggregator = MATLAB_JULIA["agg" * sysinfo["AggMethod"]], defuzzifier = MATLAB_JULIA[sysinfo["DefuzzMethod"]]) end MATLAB_JULIA[sysinfo["Type"]](; opts...) end """ String macro to parse Matlab fis formats. See [`parse_matlabfis`](@ref) for more details. """ macro matlabfis_str(s::AbstractString) parse_matlabfis(s) end end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
478
using SafeTestsets, Test testfiles = [ "test_intervals.jl", "test_membership_functions.jl", "test_settings.jl", "test_parser.jl", "test_evaluation.jl", "test_plotting.jl", "test_genfis.jl", "test_compilation.jl", "test_parsers/test_fcl.jl", "test_parsers/test_matlab.jl", "test_parsers/test_fml.jl", "test_aqua.jl", "test_doctests.jl", ] for file in testfiles @eval @time @safetestset $file begin include($file) end end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
105
using FuzzyLogic, Aqua Aqua.test_all(FuzzyLogic; ambiguities = false) Aqua.test_ambiguities(FuzzyLogic)
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
4965
using FuzzyLogic, MacroTools, Test @testset "compile Mamdani fuzzy system" begin fis = @mamfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = TriangularMF(0, 5, 10) average = TriangularMF(10, 15, 20) generous = TriangularMF(20, 25, 30) end service == poor || food == rancid --> tip == cheap * 0.5 service == good && food != rancid --> tip == average service == excellent || food == delicious --> tip == generous end fis_ex = compilefis(fis) # construct output range outside, since LinRange repr changed between 1.6 and 1.8 out_dom = LinRange(0.0, 30.0, 101) ref_ex = prettify(:(function tipper(service, food) poor = exp(-((service - 0.0)^2) / 4.5) good = exp(-((service - 5.0)^2) / 4.5) excellent = exp(-((service - 10.0)^2) / 4.5) rancid = max(min((food - -2) / 2, 1, (3 - food) / 2), 0) delicious = max(min((food - 7) / 2, 1, (12 - food) / 2), 0) ant1 = max(poor, rancid) ant2 = min(good, 1 - rancid) ant3 = max(excellent, delicious) tip_agg = collect($out_dom) @inbounds for (i, x) in enumerate(tip_agg) cheap = max(min((x - 0) / 5, (10 - x) / 5), 0) average = max(min((x - 10) / 5, (20 - x) / 5), 0) generous = max(min((x - 20) / 5, (30 - x) / 5), 0) tip_agg[i] = max(max(0.5 * min(ant1, cheap), min(ant2, average)), min(ant3, generous)) end tip = ((2 * sum((mfi * xi for (mfi, xi) in zip(tip_agg, $out_dom))) - first(tip_agg) * 0) - last(tip_agg) * 30) / ((2 * sum(tip_agg) - first(tip_agg)) - last(tip_agg)) return tip end)) @test string(fis_ex) == string(ref_ex) fname = joinpath(tempdir(), "tmp.jl") compilefis(fname, fis, :tipper2) include(fname) @test fis((2, 7))[:tip] ≈ tipper2(2, 7) rm(fname) end @testset "compile sugeno system" begin fis = @sugfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = 5.002 average = 15 generous = 2service, 0.5food, 5.0 end service == poor || food == rancid --> tip == cheap * 0.5 service == good --> tip == average service == excellent || food == delicious --> tip == generous end fis_ex = compilefis(fis) ref_ex = prettify(:(function tipper(service, food) poor = exp(-((service - 0.0)^2) / 4.5) good = exp(-((service - 5.0)^2) / 4.5) excellent = exp(-((service - 10.0)^2) / 4.5) rancid = max(min((food - -2) / 2, 1, (3 - food) / 2), 0) delicious = max(min((food - 7) / 2, 1, (12 - food) / 2), 0) ant1 = 0.5 * ((poor + rancid) - poor * rancid) ant2 = good ant3 = (excellent + delicious) - excellent * delicious tot_weight = ant1 + ant2 + ant3 cheap = 5.002 average = 15 generous = 5.0 + 2.0service + 0.5 * food tip = (ant1 * cheap + ant2 * average + ant3 * generous) / tot_weight return tip end)) @test string(fis_ex) == string(ref_ex) fname = joinpath(tempdir(), "tmp.jl") compilefis(fname, fis, :tipper2) include(fname) @test fis((2, 7))[:tip] ≈ tipper2(2, 7) rm(fname) end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
179
using Documenter, FuzzyLogic, Test DocMeta.setdocmeta!(FuzzyLogic, :DocTestSetup, :(using FuzzyLogic); recursive = true) doctest(FuzzyLogic; manual = false)
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
6120
using FuzzyLogic, Test @testset "test Mamdani evaluation" begin fis = @mamfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = TriangularMF(0, 5, 10) average = TriangularMF(10, 15, 20) generous = TriangularMF(20, 25, 30) end service == poor || food == rancid --> tip == cheap service == good --> tip == average service == excellent || food == delicious --> tip == generous end @test fis(service = 1, food = 2)[:tip]≈5.55 atol=1e-2 @test fis(service = 3, food = 5)[:tip]≈12.21 atol=1e-2 @test fis(service = 2, food = 7)[:tip]≈7.79 atol=1e-2 @test fis(service = 3, food = 1)[:tip]≈8.95 atol=1e-2 # with weighted rules and negation fis = @mamfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = TriangularMF(0, 5, 10) average = TriangularMF(10, 15, 20) generous = TriangularMF(20, 25, 30) end service == poor || food == rancid --> tip == cheap * 0.5 service == good && food != rancid --> tip == average service == excellent || food == delicious --> tip == generous end @test fis(service = 2, food = 7)[:tip]≈9.36 atol=1e-2 @test fis([2, 7])[:tip]≈9.36 atol=1e-2 end @testset "test Sugeno evaluation" begin fis = @sugfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = 5.002 average = 15 generous = 24.998 end service == poor || food == rancid --> tip == cheap * 0.5 service == good --> tip == average service == excellent || food == delicious --> tip == generous end @test fis(service = 2, food = 3)[:tip]≈8.97 atol=5e-3 fis2 = @sugfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = 5.002 average = 15 generous = 2service, 0.5food, 5.0 end service == poor || food == rancid --> tip == cheap service == good --> tip == average service == excellent || food == delicious --> tip == generous end @test fis2(service = 7, food = 8)[:tip]≈19.639 atol=1e-3 @test fis2((7, 8))[:tip]≈19.639 atol=1e-3 end @testset "Type-2 Mamdani" begin fis = @mamfis function tipper(service, food)::tip service := begin domain = 0:10 poor = 0.9 * GaussianMF(0.0, 1.2) .. GaussianMF(0.0, 1.5) good = 0.9 * GaussianMF(5.0, 1.2) .. GaussianMF(5.0, 1.5) excellent = 0.9 * GaussianMF(10.0, 1.2) .. GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = 0.9 * TrapezoidalMF(-1.8, 0.0, 1.0, 2.8) .. TrapezoidalMF(-2, 0, 1, 3) delicious = 0.9 * TrapezoidalMF(8, 9, 10, 12) .. TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = 0.9 * TriangularMF(1, 5, 9) .. TriangularMF(0, 5, 10) average = 0.9 * TriangularMF(11, 15, 19) .. TriangularMF(10, 15, 20) generous = 0.9 * TriangularMF(22, 25, 29) .. TriangularMF(20, 25, 30) end service == poor || food == rancid --> tip == cheap service == good --> tip == average service == excellent || food == delicious --> tip == generous defuzzifier = KarnikMendelDefuzzifier() end for defuzzifier in (KarnikMendelDefuzzifier(), EKMDefuzzifier(), IASCDefuzzifier(), EIASCDefuzzifier()) fis = set(fis; defuzzifier) @test fis(service = 2, food = 3)[:tip]≈7.439 atol=1e-3 end end @testset "Type-2 Sugeno" begin fis = @sugfis function tipper(service, food)::tip service := begin domain = 0:10 poor = 0.6 * GaussianMF(0.0, 1.5) .. GaussianMF(0.0, 1.5) good = 0.6 * GaussianMF(5.0, 1.5) .. GaussianMF(5.0, 1.5) excellent = 0.9 * GaussianMF(10.0, 1.5) .. GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = 0.8 * TrapezoidalMF(-2, 0, 1, 3) .. TrapezoidalMF(-2, 0, 1, 4) delicious = 0.8 * TrapezoidalMF(8, 9, 10, 12) .. TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = 5.002 average = 15 generous = 24.998 end service == poor || food == rancid --> tip == cheap * 0.5 service == good --> tip == average service == excellent || food == delicious --> tip == generous end @test fis(service = 2, food = 3)[:tip]≈FuzzyLogic.Interval(2.94, 28.613) atol=1e-3 end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
312
using FuzzyLogic, Test @testset "fuzzy c-means" begin X = [-3 -3 -3 -2 -2 -2 -1 0 1 2 2 2 3 3 3; -2 0 2 -1 0 1 0 0 0 -1 0 1 -2 0 2] C, U = fuzzy_cmeans(X, 2; m = 3) @test sortslices(C; dims = 2)≈[-2.02767 2.02767; 0 0] atol=1e-3 @test_throws ArgumentError fuzzy_cmeans(X, 3; m = 1) end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
874
using FuzzyLogic, Test using FuzzyLogic: Interval, inf, sup, mid, diam @testset "interval operations" begin a = Interval(0.1, 1.0) b = Interval(0.2, 0.8) @test inf(a) == 0.1 @test sup(a) == 1.0 @test mid(a) ≈ 0.55 @test inf(0.1) == sup(0.1) == mid(0.1) == 0.1 @test diam(a) ≈ 0.9 @test diam(0.1) == 0.0 @test Interval(1.0, 2.0) ≈ Interval(nextfloat(1.0), prevfloat(2.0)) @test +a == a @test -a == Interval(-1.0, -0.1) @test a + b ≈ Interval(0.3, 1.8) @test a - b ≈ Interval(-0.7, 0.8) @test a * b ≈ Interval(0.02, 0.8) @test a / b ≈ Interval(0.125, 5.0) @test min(a, b) == Interval(0.1, 0.8) @test max(a, b) == Interval(0.2, 1.0) @test zero(Interval{Float64}) == Interval(0.0, 0.0) @test convert(Interval{Float64}, 1.0) == Interval(1.0, 1.0) @test float(Interval{BigFloat}) == BigFloat end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
5618
using FuzzyLogic, Test using FuzzyLogic: Interval, to_expr @testset "Difference of sigmoids MF" begin f = DifferenceSigmoidMF(5, 2, 5, 7) @test f(5)≈1 atol=1e-3 @test f(4)≈1 atol=1e-3 @test f(10)≈0 atol=1e-3 @test eval(to_expr(f, 5))≈1 atol=1e-3 @test eval(to_expr(f, 4))≈1 atol=1e-3 @test eval(to_expr(f, 10))≈0 atol=1e-3 end @testset "Linear MF" begin f = LinearMF(4, 6) @test f(3) == eval(to_expr(f, 3)) == 0 @test f(4) == eval(to_expr(f, 4)) == 0 @test f(5) == eval(to_expr(f, 5)) == 0.5 @test f(6) == eval(to_expr(f, 6)) == 1 @test f(7) == eval(to_expr(f, 7)) == 1 g = LinearMF(6, 4) @test g(3) == eval(to_expr(g, 3)) == 1 @test g(4) == eval(to_expr(g, 4)) == 1 @test g(5) == eval(to_expr(g, 5)) == 0.5 @test g(6) == eval(to_expr(g, 6)) == 0 @test g(7) == eval(to_expr(g, 7)) == 0 end @testset "Generalized Bell MF" begin f = GeneralizedBellMF(2, 4, 6) @test f(0) ≈ eval(to_expr(f, 0)) ≈ 0.00015239256324291374 @test f(4) == eval(to_expr(f, 4)) == 0.5 @test f(6) == eval(to_expr(f, 6)) == 1 @test f(8) == eval(to_expr(f, 8)) == 0.5 end @testset "Gaussian MF" begin f = GaussianMF(5, 2) @test f(3) == eval(to_expr(f, 3)) == 1 / √ℯ @test f(5) == eval(to_expr(f, 5)) == 1 @test f(7) == eval(to_expr(f, 7)) == 1 / √ℯ end @testset "Product of sigmoids MF" begin f = ProductSigmoidMF(2, 3, -5, 8) f1 = SigmoidMF(2, 3) f2 = SigmoidMF(-5, 8) for val in 2:2:8 @test f(val) ≈ eval(to_expr(f, val)) ≈ f1(val) * f2(val) end end @testset "Sigmoid MF" begin f = SigmoidMF(2, 4) @test f(4) == eval(to_expr(f, 4)) == 0.5 @test f(9) == eval(to_expr(f, 9)) == 1 / (1 + exp(-10)) @test f(0) == eval(to_expr(f, 0)) == 1 / (1 + exp(8)) @test f(2) == eval(to_expr(f, 2)) == 1 / (1 + exp(4)) end @testset "Singleton MF" begin f = SingletonMF(4) @test f(4) === eval(to_expr(f, 4)) === 1 @test f(4.0) === eval(to_expr(f, 4.0)) === 1.0 @test iszero(f(3)) @test iszero(eval(to_expr(f, 3))) @test iszero(f(5)) end @testset "Trapezoidal MF" begin f = TrapezoidalMF(1, 5, 7, 8) @test f(0) == eval(to_expr(f, 0)) == 0 @test f(1) == eval(to_expr(f, 1)) == 0 @test f(3) == eval(to_expr(f, 3)) == 0.5 @test f(5) == eval(to_expr(f, 5)) == 1 @test f(6) == eval(to_expr(f, 6)) == 1 @test f(7) == eval(to_expr(f, 7)) == 1 @test f(8) == eval(to_expr(f, 8)) == 0 @test f(9) == eval(to_expr(f, 9)) == 0 end @testset "Triangular MF" begin f = TriangularMF(3, 6, 8) @test f(2) == eval(to_expr(f, 2)) == 0 @test f(3) == eval(to_expr(f, 3)) == 0 @test f(4.5) == eval(to_expr(f, 4.5)) == 0.5 @test f(6) == eval(to_expr(f, 6)) == 1 @test f(7) == eval(to_expr(f, 7)) == 0.5 @test f(8) == eval(to_expr(f, 8)) == 0 @test f(9) == eval(to_expr(f, 9)) == 0 end @testset "S-shaped MF" begin mf = SShapeMF(1, 8) @test mf(0) == eval(to_expr(mf, 0)) == 0 @test mf(1) == eval(to_expr(mf, 1)) == 0 @test mf(2.75) ≈ eval(to_expr(mf, 2.75)) ≈ 0.125 @test mf(4.5) ≈ eval(to_expr(mf, 4.5)) ≈ 0.5 @test mf(6.25) ≈ eval(to_expr(mf, 6.25)) ≈ 0.875 @test mf(8) == eval(to_expr(mf, 8)) == 1 @test mf(9) == eval(to_expr(mf, 9)) == 1 end @testset "Z-shaped MF" begin mf = ZShapeMF(3, 7) @test mf(2) == eval(to_expr(mf, 2)) == 1 @test mf(3) == eval(to_expr(mf, 3)) == 1 @test mf(4) ≈ eval(to_expr(mf, 4)) ≈ 0.875 @test mf(5) ≈ eval(to_expr(mf, 5)) ≈ 0.5 @test mf(6) ≈ eval(to_expr(mf, 6)) ≈ 0.125 @test mf(7) == eval(to_expr(mf, 7)) == 0 @test mf(9) == eval(to_expr(mf, 9)) == 0 end @testset "Pi-shaped MF" begin mf = PiShapeMF(1, 4, 5, 10) @test mf(1) == eval(to_expr(mf, 1)) == 0 @test mf(2.5) == eval(to_expr(mf, 2.5)) == 0.5 @test mf(4) == eval(to_expr(mf, 4)) == 1 @test mf(4.5) == eval(to_expr(mf, 4.5)) == 1 @test mf(5) == eval(to_expr(mf, 5)) == 1 @test mf(7.5) == eval(to_expr(mf, 7.5)) == 0.5 @test mf(8.75) == eval(to_expr(mf, 8.75)) == 0.125 @test mf(10) == eval(to_expr(mf, 10)) == 0 end @testset "Semi-Elliptic MF" begin mf = SemiEllipticMF(5.0, 4.0) @test mf(0) == eval(to_expr(mf, 0)) == 0 @test mf(1) == eval(to_expr(mf, 1)) == 0 @test mf(5) == eval(to_expr(mf, 5)) == 1 @test mf(9) == eval(to_expr(mf, 9)) == 0 @test mf(10) == eval(to_expr(mf, 10)) == 0 end @testset "Piecewise linear Membership function" begin mf = PiecewiseLinearMF([(1, 0), (2, 1), (3, 0), (4, 0.5), (5, 0), (6, 1)]) @test mf(0.0) == eval(to_expr(mf, 0.0)) == 0 @test mf(1.0) == eval(to_expr(mf, 1.0)) == 0 @test mf(1.5) == eval(to_expr(mf, 1.5)) == 0.5 @test mf(2) == eval(to_expr(mf, 2)) == 1 @test mf(3.5) == eval(to_expr(mf, 3.5)) == 0.25 @test mf(7) == eval(to_expr(mf, 7)) == 1 end @testset "Weighted Membership function" begin mf = TriangularMF(1, 2, 3) mf1 = 0.5 * mf mf2 = mf * 0.5 @test mf1(1) == mf2(1) == eval(to_expr(mf1, 1)) == 0 @test mf1(3) == mf2(3) == eval(to_expr(mf1, 3)) == 0 @test mf1(2) == mf2(2) == eval(to_expr(mf1, 2)) == 0.5 @test mf1(0.3) == mf2(0.3) == eval(to_expr(mf1, 0.3)) == 0.5 * mf(0.3) end @testset "Type-2 membership function" begin mf = 0.5 * TriangularMF(1, 2, 3) .. TriangularMF(0, 2, 4) @test mf(-1) == Interval(0.0, 0.0) @test mf(0) == Interval(0.0, 0.0) @test mf(1) == Interval(0.0, 0.5) @test mf(1.5) == Interval(0.25, 0.75) @test mf(2) == Interval(0.5, 1.0) @test mf(3) == Interval(0.0, 0.5) @test mf(4) == Interval(0.0, 0.0) @test mf(5) == Interval(0.0, 0.0) end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
5981
using Dictionaries, FuzzyLogic, Test using FuzzyLogic: FuzzyRelation, FuzzyAnd, FuzzyOr, FuzzyRule, WeightedFuzzyRule, Domain, Variable # TODO: write more low level tests @testset "test Mamdani parser" begin fis = @mamfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = TriangularMF(0, 5, 10) average = TriangularMF(10, 15, 20) generous = TriangularMF(20, 25, 30) end and = ProdAnd or = ProbSumOr implication = ProdImplication service == poor && food == rancid --> tip == cheap * 0.2 service == good --> (tip == average, tip == average) * 0.3 service == excellent || food == delicious --> tip == generous service == excellent || food == delicious --> (tip == generous, tip == generous) aggregator = ProbSumAggregator defuzzifier = BisectorDefuzzifier end @test fis isa MamdaniFuzzySystem{ProdAnd, ProbSumOr, ProdImplication, ProbSumAggregator, BisectorDefuzzifier} @test fis.name == :tipper service = Variable(Domain(0, 10), Dictionary([:poor, :good, :excellent], [GaussianMF(0.0, 1.5), GaussianMF(5.0, 1.5), GaussianMF(10.0, 1.5)])) food = Variable(Domain(0, 10), Dictionary([:rancid, :delicious], [TrapezoidalMF(-2, 0, 1, 3), TrapezoidalMF(7, 9, 10, 12)])) tip = Variable(Domain(0, 30), Dictionary([:cheap, :average, :generous], [ TriangularMF(0, 5, 10), TriangularMF(10, 15, 20), TriangularMF(20, 25, 30), ])) @test fis.inputs == Dictionary([:service, :food], [service, food]) @test fis.outputs == Dictionary([:tip], [tip]) @test fis.rules == [ WeightedFuzzyRule(FuzzyAnd(FuzzyRelation(:service, :poor), FuzzyRelation(:food, :rancid)), [FuzzyRelation(:tip, :cheap)], 0.2), WeightedFuzzyRule(FuzzyRelation(:service, :good), [FuzzyRelation(:tip, :average), FuzzyRelation(:tip, :average)], 0.3), FuzzyRule(FuzzyOr(FuzzyRelation(:service, :excellent), FuzzyRelation(:food, :delicious)), [FuzzyRelation(:tip, :generous)]), FuzzyRule(FuzzyOr(FuzzyRelation(:service, :excellent), FuzzyRelation(:food, :delicious)), [FuzzyRelation(:tip, :generous), FuzzyRelation(:tip, :generous)]), ] end @testset "test Sugeno parser" begin fis = @sugfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = 0 average = food generous = 2service, food, -2 end service == poor && food == rancid --> tip == cheap service == good --> tip == average service == excellent || food == delicious --> tip == generous end @test fis isa SugenoFuzzySystem{ProdAnd, ProbSumOr} @test fis.name == :tipper mfs = Dictionary([:cheap, :average, :generous], [ ConstantSugenoOutput(0), LinearSugenoOutput(Dictionary([:service, :food], [0, 1]), 0), LinearSugenoOutput(Dictionary([:service, :food], [2, 1]), -2), ]) @test fis.outputs[:tip].mfs == mfs end @testset "parse vector-like notation" begin fis = @mamfis function denoise(x[1:3])::y[1:2] for i in 1:3 x[i] := begin domain = -1000:1000 POS = TriangularMF(-255.0, 255.0, 765.0) NEG = TriangularMF(-765.0, -255.0, 255.0) end end y1 := begin domain = -1000:1000 POS = TriangularMF(-255.0, 255.0, 765.0) NEG = TriangularMF(-765.0, -255.0, 255.0) end y2 := begin domain = -1000:1000 POS = TriangularMF(-255.0, 255.0, 765.0) NEG = TriangularMF(-765.0, -255.0, 255.0) end for i in 1:2 x[i] == POS && x[i + 1] == NEG --> (y[i] == POS, y[i % 2 + 1] == NEG) end end var = Variable(Domain(-1000, 1000), Dictionary([:POS, :NEG], [ TriangularMF(-255.0, 255.0, 765.0), TriangularMF(-765.0, -255.0, 255.0), ])) for x in (:x1, :x2, :x3) @test fis.inputs[x] == var end for y in (:y1, :y2) @test fis.outputs[y] == var end @test fis.rules == [ FuzzyRule(FuzzyAnd(FuzzyRelation(:x1, :POS), FuzzyRelation(:x2, :NEG)), [FuzzyRelation(:y1, :POS), FuzzyRelation(:y2, :NEG)]), FuzzyRule(FuzzyAnd(FuzzyRelation(:x2, :POS), FuzzyRelation(:x3, :NEG)), [FuzzyRelation(:y2, :POS), FuzzyRelation(:y1, :NEG)]), ] end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
6254
using FuzzyLogic using FuzzyLogic: Domain, Variable, GenSurf using RecipesBase using Dictionaries using Test @testset "Plotting variables" begin mf1 = TriangularMF(1, 2, 3) mf2 = TrapezoidalMF(1, 2, 3, 4) dom = Domain(0, 5) rec = RecipesBase.apply_recipe(Dict{Symbol, Any}(), mf1, dom) @test isempty(only(rec).plotattributes) @test only(rec).args == (mf1, 0, 5) rec = RecipesBase.apply_recipe(Dict{Symbol, Any}(), mf1, 0, 5) @test only(rec).plotattributes == Dict(:legend => nothing) @test only(rec).args[2:3] == (0, 5) @test only(rec).args[1](0) == mf1(0) mfnames = [:mf1, :mf2] mfs = [mf1, mf2] var = Variable(dom, Dictionary(mfnames, mfs)) rec = RecipesBase.apply_recipe(Dict{Symbol, Any}(), var, :var) @test length(rec) == 2 for i in 1:2 @test rec[i].plotattributes == Dict(:legend => true, :label => string(mfnames[i]), :plot_title => "var") @test rec[i].args == (mfs[i], dom) end end @testset "Plotting Mamdani inference system" begin fis = @mamfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = TriangularMF(0, 5, 10) average = TriangularMF(10, 15, 20) generous = TriangularMF(20, 25, 30) end service == poor || food == rancid --> tip == cheap service == good --> tip == average service == excellent || food == delicious --> tip == generous end rec = RecipesBase.apply_recipe(Dict{Symbol, Any}(), fis) dom_in = Domain(0, 10) dom_out = Domain(0, 30) data = [ (GaussianMF(0.0, 1.5), dom_in), (TrapezoidalMF(-2, 0, 1, 3), dom_in), (TriangularMF(0, 5, 10), dom_out), (GaussianMF(5.0, 1.5), dom_in), (), (TriangularMF(10, 15, 20), dom_out), (GaussianMF(10.0, 1.5), dom_in), (TrapezoidalMF(7, 9, 10, 12), dom_in), (TriangularMF(20, 25, 30), dom_out) ] titles = [ "service is poor", "food is rancid", "tip is cheap", "service is good", "", "tip is average", "service is excellent", "food is delicious", "tip is generous" ] for (i, (p, d, t)) in enumerate(zip(rec, data, titles)) @test p.args == d if isempty(d) @test p.plotattributes == Dict(:plot_title => "tipper", :grid => false, :legend => false, :axis => false, :layout => (3, 3), :size => (900, 600), :subplot => i) else @test p.plotattributes == Dict(:plot_title => "tipper", :size => (900, 600), :title => t, :layout => (3, 3), :subplot => i) end end end @testset "Plotting sugeno output variables" begin mfnames = [:average, :generous] mfs = [ ConstantSugenoOutput(15), LinearSugenoOutput(Dictionary([:service, :food], [2.0, 0.5]), 5.0) ] var = Variable(Domain(0, 30), Dictionary(mfnames, mfs)) plts = RecipesBase.apply_recipe(Dict{Symbol, Any}(), var, :tip) for (plt, mfname, mf) in zip(plts, mfnames, mfs) @test plt.args == (mf, Domain(0, 30)) @test plt.plotattributes == Dict(:plot_title => "tip", :legend => false, :title => string(mfname), :layout => (1, 2)) end end @testset "Plotting type-2 membership functions" begin mf = 0.5 * TriangularMF(1, 2, 3) .. TriangularMF(0, 2, 4) plt = RecipesBase.apply_recipe(Dict{Symbol, Any}(), mf, 0, 4) @test plt[1].args[1](0.0) == mf.lo(0.0) @test keys(plt[1].plotattributes) == Set([:fillrange, :legend, :fillalpha, :linewidth, :linealpha]) @test plt[1].plotattributes[:fillrange](0.0) == mf.hi(0.0) @test plt[2].args[1](2) == 1.0 end # @testset "Plotting generating surface" begin # fis = @mamfis function tipper(service, food)::tip # service := begin # domain = 0:10 # poor = GaussianMF(0.0, 1.5) # good = GaussianMF(5.0, 1.5) # excellent = GaussianMF(10.0, 1.5) # end # food := begin # domain = 0:10 # rancid = TrapezoidalMF(-2, 0, 1, 3) # delicious = TrapezoidalMF(7, 9, 10, 12) # end # tip := begin # domain = 0:30 # cheap = TriangularMF(0, 5, 10) # average = TriangularMF(10, 15, 20) # generous = TriangularMF(20, 25, 30) # end # service == poor || food == rancid --> tip == cheap # service == good --> tip == average # service == excellent || food == delicious --> tip == generous # end # plt = RecipesBase.apply_recipe(Dict{Symbol, Any}(), GenSurf((fis,)))[1] # @test plt.args[1] == range(0, 10, 100) # @test plt.args[2] == range(0, 10, 100) # @test plt.args[3](1, 2) == fis((1, 2))[:tip] # @test plt.plotattributes[:seriestype] == :surface # @test plt.plotattributes[:xlabel] == :service # @test plt.plotattributes[:ylabel] == :food # @test plt.plotattributes[:zlabel] == :tip # fis1 = @mamfis function fis1(x)::y # x := begin # domain = 0:10 # low = TriangularMF(0, 2, 4) # med = TriangularMF(4, 6, 8) # high = TriangularMF(8, 9, 10) # end # y := begin # domain = 0:10 # low = TriangularMF(0, 2, 4) # med = TriangularMF(4, 6, 8) # high = TriangularMF(8, 9, 10) # end # x == low --> y == low # x == med --> y == med # x == high --> y == high # end # plt = RecipesBase.apply_recipe(Dict{Symbol, Any}(), FuzzyLogic.GenSurf((fis1,)))[1] # @test plt.args[1] == range(0, 10, 100) # @test plt.args[2](2.5) == 2.0 # @test plt.plotattributes == # Dict{Symbol, Any}(:ylabel => :y, :legend => nothing, :xlabel => :x) # end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
5655
using FuzzyLogic using FuzzyLogic: to_expr using Test @testset "update fuzzy systems" begin fis = @mamfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = TriangularMF(0, 5, 10) average = TriangularMF(10, 15, 20) generous = TriangularMF(20, 25, 30) end and = ProdAnd or = ProbSumOr implication = ProdImplication service == poor && food == rancid --> tip == cheap * 0.2 service == good --> (tip == average, tip == average) * 0.3 service == excellent || food == delicious --> tip == generous service == excellent || food == delicious --> (tip == generous, tip == generous) aggregator = ProbSumAggregator defuzzifier = BisectorDefuzzifier end fis2 = set(fis; name = :tipper2, defuzzifier = CentroidDefuzzifier()) @test fis2.name == :tipper2 @test fis2 isa MamdaniFuzzySystem{ProdAnd, ProbSumOr, ProdImplication, ProbSumAggregator, CentroidDefuzzifier} end @testset "test T--norms" begin @test MinAnd()(0.4, 0.2) == eval(to_expr(MinAnd(), 0.4, 0.2)) == 0.2 @test MinAnd()(1.0, 1.0) == eval(to_expr(MinAnd(), 1.0, 1.0)) == 1.0 @test MinAnd()(0.0, 0.0) == eval(to_expr(MinAnd(), 0.0, 0.0)) == 0.0 @test ProdAnd()(0.4, 0.2) ≈ eval(to_expr(ProdAnd(), 0.4, 0.2)) ≈ 0.08 @test ProdAnd()(1.0, 1.0) == eval(to_expr(ProdAnd(), 1.0, 1.0)) == 1.0 @test ProdAnd()(0.0, 0.0) == eval(to_expr(ProdAnd(), 0.0, 0.0)) == 0.0 @test DrasticAnd()(1.0, 0.2) == eval(to_expr(DrasticAnd(), 1.0, 0.2)) == 0.2 @test DrasticAnd()(0.3, 1.0) == eval(to_expr(DrasticAnd(), 0.3, 1.0)) == 0.3 @test DrasticAnd()(0.9, 0.9) == eval(to_expr(DrasticAnd(), 0.9, 0.9)) == 0.0 @test LukasiewiczAnd()(0.4, 0.2) == eval(to_expr(LukasiewiczAnd(), 0.4, 0.2)) == 0 @test LukasiewiczAnd()(0.7, 0.5) ≈ eval(to_expr(LukasiewiczAnd(), 0.7, 0.5)) ≈ 0.2 @test LukasiewiczAnd()(0.5, 0.5) ≈ eval(to_expr(LukasiewiczAnd(), 0.5, 0.5)) ≈ 0 @test NilpotentAnd()(0.4, 0.2) == eval(to_expr(NilpotentAnd(), 0.4, 0.2)) == 0.0 @test NilpotentAnd()(0.5, 0.7) == eval(to_expr(NilpotentAnd(), 0.5, 0.7)) == 0.5 @test NilpotentAnd()(0.5, 0.5) == eval(to_expr(NilpotentAnd(), 0.5, 0.5)) == 0.0 @test HamacherAnd()(0.0, 0.0) == eval(to_expr(HamacherAnd(), 0.0, 0.0)) == 0.0 @test HamacherAnd()(0.4, 0.2) ≈ eval(to_expr(HamacherAnd(), 0.4, 0.2)) ≈ 0.15384615384615388 @test HamacherAnd()(1.0, 1.0) == eval(to_expr(HamacherAnd(), 1.0, 1.0)) == 1.0 @test EinsteinAnd()(0.0, 0.0) == eval(to_expr(EinsteinAnd(), 0.0, 0.0)) == 0.0 @test EinsteinAnd()(1.0, 0.0) == eval(to_expr(EinsteinAnd(), 1.0, 0.0)) == 0.0 @test EinsteinAnd()(0.5, 0.5) ≈ eval(to_expr(EinsteinAnd(), 0.5, 0.5)) ≈ 0.2 end @testset "test S-norms" begin @test MaxOr()(0.4, 0.2) == eval(to_expr(MaxOr(), 0.4, 0.2)) == 0.4 @test MaxOr()(1.0, 1.0) == eval(to_expr(MaxOr(), 1.0, 1.0)) == 1.0 @test MaxOr()(0.0, 0.0) == eval(to_expr(MaxOr(), 0.0, 0.0)) == 0.0 @test ProbSumOr()(0.5, 0.5) == eval(to_expr(ProbSumOr(), 0.5, 0.5)) == 0.75 @test ProbSumOr()(1.0, 0.2) == eval(to_expr(ProbSumOr(), 1.0, 0.2)) == 1.0 @test ProbSumOr()(1.0, 0.0) == eval(to_expr(ProbSumOr(), 1.0, 0.0)) == 1.0 @test BoundedSumOr()(0.2, 0.3) == eval(to_expr(BoundedSumOr(), 0.2, 0.3)) == 0.5 @test BoundedSumOr()(0.6, 0.6) == eval(to_expr(BoundedSumOr(), 0.6, 0.6)) == 1.0 @test BoundedSumOr()(0.0, 0.0) == eval(to_expr(BoundedSumOr(), 0.0, 0.0)) == 0.0 @test DrasticOr()(0.2, 0.0) == eval(to_expr(DrasticOr(), 0.2, 0.0)) == 0.2 @test DrasticOr()(0.0, 0.2) == eval(to_expr(DrasticOr(), 0.0, 0.2)) == 0.2 @test DrasticOr()(0.01, 0.01) == eval(to_expr(DrasticOr(), 0.01, 0.01)) == 1.0 @test NilpotentOr()(0.2, 0.3) == eval(to_expr(NilpotentOr(), 0.2, 0.3)) == 0.3 @test NilpotentOr()(0.5, 0.6) == eval(to_expr(NilpotentOr(), 0.5, 0.6)) == 1.0 @test NilpotentOr()(0.7, 0.1) == eval(to_expr(NilpotentOr(), 0.7, 0.1)) == 0.7 @test EinsteinOr()(0.0, 0.0) == eval(to_expr(EinsteinOr(), 0.0, 0.0)) == 0.0 @test EinsteinOr()(0.5, 0.5) == eval(to_expr(EinsteinOr(), 0.5, 0.5)) == 0.8 @test EinsteinOr()(1.0, 1.0) == eval(to_expr(EinsteinOr(), 1.0, 1.0)) == 1.0 @test HamacherOr()(0.0, 0.0) == eval(to_expr(HamacherOr(), 0.0, 0.0)) == 0.0 @test HamacherOr()(0.5, 0.5) ≈ eval(to_expr(HamacherOr(), 0.5, 0.5)) ≈ 2 / 3 @test HamacherOr()(1.0, 1.0) == eval(to_expr(HamacherOr(), 1.0, 1.0)) == 1.0 end @testset "test type-1 defuzzifiers" begin N = 800 mf = TrapezoidalMF(1, 2, 5, 7) x = LinRange(0, 8, N + 1) y = mf.(x) dom = FuzzyLogic.Domain(0, 8) @test BisectorDefuzzifier(N)(y, dom) ≈ eval(to_expr(BisectorDefuzzifier(N), y, dom)) ≈ 3.75 @test CentroidDefuzzifier(N)(y, dom) ≈ eval(to_expr(CentroidDefuzzifier(N), y, dom)) ≈ 3.7777777777777772 @test LeftMaximumDefuzzifier(; N)(y, dom) ≈ eval(to_expr(LeftMaximumDefuzzifier(; N), y, dom)) ≈ 2 @test RightMaximumDefuzzifier(; N)(y, dom) ≈ eval(to_expr(RightMaximumDefuzzifier(; N), y, dom)) ≈ 5 @test MeanOfMaximaDefuzzifier(; N)(y, dom) ≈ eval(to_expr(MeanOfMaximaDefuzzifier(; N), y, dom)) ≈ 3.5 end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
6191
using Dictionaries, FuzzyLogic, PEG, Test using FuzzyLogic: Variable, Domain, FuzzyRelation, FuzzyAnd, FuzzyOr, FuzzyNegation, FuzzyRule, WeightedFuzzyRule @testset "parse propositions" begin s = [ "a IS b OR Ix IS black AND th IS NOT red", "(a IS b OR Ix IS black) AND th IS NOT red", "a IS ai AND (b IS bi OR NOT (c IS ci))", ] r = [ FuzzyOr(FuzzyRelation(:a, :b), FuzzyAnd(FuzzyRelation(:Ix, :black), FuzzyNegation(:th, :red))), FuzzyAnd(FuzzyOr(FuzzyRelation(:a, :b), FuzzyRelation(:Ix, :black)), FuzzyNegation(:th, :red)), FuzzyAnd(FuzzyRelation(:a, :ai), FuzzyOr(FuzzyRelation(:b, :bi), FuzzyNegation(:c, :ci))), ] for (si, ri) in zip(s, r) @test parse_whole(FuzzyLogic.FCLParser.condition, si) == ri end end @testset "Parse Sugeno FIS from FCL" begin fis1 = fcl""" FUNCTION_BLOCK container_crane VAR_INPUT distance: REAL; angle: REAL; END_VAR VAR_OUTPUT power: REAL; END_VAR FUZZIFY distance TERM too_far:= (-5, 1) ( 0, 0); TERM zero := (-5, 0) ( 0, 1) ( 5,0); TERM close := ( 0, 0) ( 5, 1) (10,0); TERM medium := ( 5, 0) (10, 1) (22,0); TERM far := (10, 0) (22,1); RANGE := (-7 .. 23); END_FUZZIFY FUZZIFY angle TERM neg_big := (-50, 1) (-5, 0); TERM neg_small := (-50, 0) (-5, 1) ( 0,0); TERM zero := ( -5, 0) ( 0, 1) ( 5,0); TERM pos_small := ( 0, 0) ( 5, 1) (50,0); TERM pos_big := ( 5, 0) (50, 1); RANGE := (-50..50); END_FUZZIFY DEFUZZIFY power TERM neg_high := -27; TERM neg_medium := -12; TERM zero := 0; TERM pos_medium := 12; TERM pos_high := 27; METHOD : COGS; RANGE := (-27..27); END_DEFUZZIFY RULEBLOCK No1 AND: MIN; RULE 1: IF distance IS far AND angle IS zero THEN power IS pos_medium; RULE 2: IF distance IS far AND angle IS neg_small THEN power IS pos_big; RULE 3: IF distance IS far AND angle IS neg_big THEN power IS pos_medium; RULE 4: IF distance IS medium AND angle IS neg_small THEN power IS neg_medium; RULE 5: IF distance IS close AND angle IS pos_small THEN power IS pos_medium; RULE 6: IF distance IS zero AND angle IS zero THEN power IS zero; END_RULEBLOCK END_FUNCTION_BLOCK """ fis2 = readfis(joinpath(@__DIR__, "data", "container_crane.fcl")) for fis in (fis1, fis2) @test fis isa SugenoFuzzySystem{MinAnd, MaxOr} mfs_dist = Dictionary([:too_far, :zero, :close, :medium, :far], [ PiecewiseLinearMF([(-5.0, 1.0), (0.0, 0.0)]), PiecewiseLinearMF([(-5.0, 0.0), (0.0, 1.0), (5.0, 0.0)]), PiecewiseLinearMF([(0.0, 0.0), (5.0, 1.0), (10.0, 0.0)]), PiecewiseLinearMF([(5.0, 0.0), (10.0, 1.0), (22.0, 0.0)]), PiecewiseLinearMF([(10.0, 0.0), (22.0, 1.0)]), ]) @test fis.inputs[:distance] == Variable(Domain(-7.0, 23.0), mfs_dist) mfs_power = Dictionary([:neg_high, :neg_medium, :zero, :pos_medium, :pos_high], [ ConstantSugenoOutput(-27.0), ConstantSugenoOutput(-12.0), ConstantSugenoOutput(0.0), ConstantSugenoOutput(12.0), ConstantSugenoOutput(27.0)]) @test fis.outputs[:power] == Variable(Domain(-27.0, 27.0), mfs_power) _parse_rule(exs::Tuple) = eval(FuzzyLogic.parse_rule(exs...)) rules = [(:(distance == far && angle == zero), [:(power == pos_medium)]), (:(distance == far && angle == neg_small), [:(power == pos_big)]), (:(distance == far && angle == neg_big), [:(power == pos_medium)]), (:(distance == medium && angle == neg_small), [:(power == neg_medium)]), (:(distance == close && angle == pos_small), [:(power == pos_medium)]), (:(distance == zero && angle == zero), [:(power == zero)]), ] @test fis.rules == map(_parse_rule, rules) end end @testset "parse Mamdani system" begin fis = fcl""" FUNCTION_BLOCK edge_detector VAR_INPUT Ix: REAL; Iy: REAL; END_VAR VAR_OUTPUT Iout: REAL; END_VAR FUZZIFY Ix TERM zero := (-0.3, 0.0) (0.0, 1.0) (0.3, 0.0); RANGE := (-1..1); END_FUZZIFY FUZZIFY Iy TERM zero := (-0.3, 0.0) (0.0, 1.0) (0.3, 0.0); RANGE := (-1..1); END_FUZZIFY DEFUZZIFY Iout TERM black := (0.0, 1.0) (0.7, 0.0); TERM white := (0.1, 0.0) (1.0, 1.0); METHOD: COA; RANGE := (0.0..1.0); END_DEFUZZIFY RULEBLOCK rules OR: ASUM; ACT: PROD; RULE 1: IF Ix IS zero AND Iy IS zero THEN Iout IS white WITH 0.5; RULE 2: IF Ix IS NOT zero OR Iy IS NOT zero THEN Iout IS black; END_RULEBLOCK END_FUNCTION_BLOCK """ @test fis isa MamdaniFuzzySystem{ProdAnd, ProbSumOr, ProdImplication, MaxAggregator, BisectorDefuzzifier} @test fis.inputs[:Ix] == fis.inputs[:Iy] == Variable(Domain(-1.0, 1.0), Dictionary([:zero], [PiecewiseLinearMF([(-0.3, 0.0), (0.0, 1.0), (0.3, 0.0)])])) @test fis.outputs[:Iout] == Variable(Domain(0.0, 1.0), Dictionary([:black, :white], [ PiecewiseLinearMF([(0.0, 1.0), (0.7, 0.0)]), PiecewiseLinearMF([(0.1, 0.0), (1.0, 1.0)]), ])) @test fis.rules == [ WeightedFuzzyRule(FuzzyAnd(FuzzyRelation(:Ix, :zero), FuzzyRelation(:Iy, :zero)), [FuzzyRelation(:Iout, :white)], 0.5), FuzzyRule(FuzzyOr(FuzzyNegation(:Ix, :zero), FuzzyNegation(:Iy, :zero)), [FuzzyRelation(:Iout, :black)]), ] end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
7545
using Dictionaries, FuzzyLogic, PEG, Test using FuzzyLogic: Variable, Domain, FuzzyRelation, FuzzyAnd, FuzzyOr, FuzzyNegation, WeightedFuzzyRule, FuzzyRule @testset "parse Mamdani infernce system" begin fis = readfis(joinpath(@__DIR__, "data", "tipper.xml")) @test fis isa MamdaniFuzzySystem{MinAnd, MaxOr, MinImplication, MaxAggregator, CentroidDefuzzifier} @test fis.name == :tipper service = Variable(Domain(0.0, 10.0), Dictionary([:poor, :good, :excellent], [GaussianMF(0.0, 2.0), GaussianMF(5.0, 2.0), GaussianMF(10.0, 2.0)])) food = Variable(Domain(0.0, 10.0), Dictionary([:rancid, :delicious], [ LinearMF(5.5, 0.0), LinearMF(5.5, 10.0), ])) tip = Variable(Domain(0.0, 20.0), Dictionary([:cheap, :average, :generous], [ TriangularMF(0.0, 5.0, 10.0), TriangularMF(5.0, 10.0, 15.0), TriangularMF(10.0, 15.0, 20.0), ])) @test fis.inputs == Dictionary([:food, :service], [food, service]) @test fis.outputs == Dictionary([:tip], [tip]) @test fis.rules == [ FuzzyRule(FuzzyOr(FuzzyRelation(:food, :rancid), FuzzyRelation(:service, :poor)), [FuzzyRelation(:tip, :cheap)]), FuzzyRule(FuzzyRelation(:service, :good), [FuzzyRelation(:tip, :average)]), FuzzyRule(FuzzyOr(FuzzyRelation(:service, :excellent), FuzzyRelation(:food, :delicious)), [FuzzyRelation(:tip, :generous)]), ] end @testset "Test Sugeno inference system" begin fis = fml""" <?xml version="1.0" encoding="UTF-8"?> <fuzzySystem name="tipper" networkAddress="127.0.0.1"> <knowledgeBase> <fuzzyVariable name="food" domainleft="0.0" domainright="10.0" scale="" type="input"> <fuzzyTerm name="rancid" complement="false"> <rightLinearShape param1="0.0" param2="5.5" /> </fuzzyTerm> <fuzzyTerm name="rancid2" complement="true"> <rightLinearShape param1="0.0" param2="5.5" /> </fuzzyTerm> <fuzzyTerm name="delicious" complement="false"> <leftLinearShape param1="5.5" param2="10.0" /> </fuzzyTerm> </fuzzyVariable> <fuzzyVariable name="service" domainleft="0.0" domainright="10.0" scale="" type="input"> <fuzzyTerm name="poor" complement="false"> <rightGaussianShape param1="0.0" param2="2.0" /> </fuzzyTerm> <fuzzyTerm name="good" complement="false"> <gaussianShape param1="5.0" param2="2.0" /> </fuzzyTerm> <fuzzyTerm name="excellent" complement="false"> <leftGaussianShape param1="10.0" param2="2.0" /> </fuzzyTerm> </fuzzyVariable> <tskVariable name="tip" scale="null" combination="WA" type="output"> <tskTerm name="average" order="0"> <tskValue>1.6</tskValue> </tskTerm> <tskTerm name="cheap" order="1"> <tskValue>1.9</tskValue> <tskValue>5.6</tskValue> <tskValue>6.0</tskValue> </tskTerm> <tskTerm name="generous" order="1"> <tskValue>0.6</tskValue> <tskValue>1.3</tskValue> <tskValue>1.0</tskValue> </tskTerm> </tskVariable> </knowledgeBase> <tskRuleBase name="No1" andMethod="PROD" orMethod="PROBOR"> <tskRule name="reg1" connector="or" orMethod="MAX" weight="1.0"> <antecedent> <clause> <variable>food</variable> <term>rancid</term> </clause> <clause> <variable>service</variable> <term>poor</term> </clause> </antecedent> <tskConsequent> <tskThen> <tskClause> <variable>tip</variable> <term>cheap</term> </tskClause> </tskThen> </tskConsequent> </tskRule> <tskRule name="reg2" connector="and" weight="0.75"> <antecedent> <clause> <variable>service</variable> <term>good</term> </clause> <clause> <variable>food</variable> <term>rancid2</term> </clause> </antecedent> <tskConsequent> <tskThen> <tskClause> <variable>tip</variable> <term>average</term> </tskClause> </tskThen> </tskConsequent> </tskRule> <tskRule name="reg3" connector="or" orMethod="MAX" weight="1.0"> <antecedent> <clause> <variable>food</variable> <term>delicious</term> </clause> <clause> <variable>service</variable> <term>excellent</term> </clause> </antecedent> <tskConsequent> <tskThen> <tskClause> <variable>tip</variable> <term>generous</term> </tskClause> </tskThen> </tskConsequent> </tskRule> </tskRuleBase> </fuzzySystem> """ @test fis isa SugenoFuzzySystem{ProdAnd, ProbSumOr} @test fis.outputs[:tip] == Variable(Domain(-Inf, Inf), Dictionary([:average, :cheap, :generous], [ ConstantSugenoOutput(1.6), LinearSugenoOutput(Dictionary([:food, :service], [1.9, 5.6]), 6.0), LinearSugenoOutput(Dictionary([:food, :service], [0.6, 1.3]), 1.0), ])) @test fis.rules == [ FuzzyRule(FuzzyOr(FuzzyRelation(:food, :rancid), FuzzyRelation(:service, :poor)), [FuzzyRelation(:tip, :cheap)]), WeightedFuzzyRule(FuzzyAnd(FuzzyRelation(:service, :good), FuzzyNegation(:food, :rancid2)), [FuzzyRelation(:tip, :average)], 0.75), FuzzyRule(FuzzyOr(FuzzyRelation(:food, :delicious), FuzzyRelation(:service, :excellent)), [FuzzyRelation(:tip, :generous)]), ] end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
code
4172
using Dictionaries, FuzzyLogic, PEG, Test using FuzzyLogic: Variable, Domain, FuzzyRelation, FuzzyAnd, FuzzyOr, FuzzyNegation, WeightedFuzzyRule, FuzzyRule @testset "parse Mamdani infernce system" begin fis = readfis(joinpath(@__DIR__, "data", "tipper.fis")) @test fis isa MamdaniFuzzySystem{MinAnd, MaxOr, MinImplication, MaxAggregator, CentroidDefuzzifier} @test fis.name == :tipper service = Variable(Domain(0.0, 10.0), Dictionary([:poor, :good, :excellent], [GaussianMF(0.0, 1.5), GaussianMF(5.0, 1.5), GaussianMF(10.0, 1.5)])) food = Variable(Domain(0.0, 10.0), Dictionary([:rancid, :delicious], [ TrapezoidalMF(-2.0, 0.0, 1.0, 3.0), TrapezoidalMF(7.0, 9.0, 10.0, 12.0), ])) tip = Variable(Domain(0.0, 30.0), Dictionary([:cheap, :average, :generous], [ TriangularMF(0.0, 5.0, 10.0), TriangularMF(10.0, 15.0, 20.0), TriangularMF(20.0, 25.0, 30.0), ])) @test fis.inputs == Dictionary([:service, :food], [service, food]) @test fis.outputs == Dictionary([:tip], [tip]) @test fis.rules == [ FuzzyRule(FuzzyOr(FuzzyRelation(:service, :poor), FuzzyRelation(:food, :rancid)), [FuzzyRelation(:tip, :cheap)]), FuzzyRule(FuzzyRelation(:service, :good), [FuzzyRelation(:tip, :average)]), FuzzyRule(FuzzyOr(FuzzyRelation(:service, :excellent), FuzzyRelation(:food, :delicious)), [FuzzyRelation(:tip, :generous)]), ] fis = matlabfis""" [System] Name='edgefis' Type='mamdani' Version=2.0 NumInputs=2 NumOutputs=1 NumRules=2 AndMethod='min' OrMethod='max' ImpMethod='min' AggMethod='max' DefuzzMethod='bisector' [Input1] Name='Ix' Range=[-1 1] NumMFs=1 MF1='zero':'gaussmf',[0.1 0] [Input2] Name='Iy' Range=[-1 1] NumMFs=1 MF1='zero':'gaussmf',[0.1 0] [Output1] Name='Iout' Range=[0 1] NumMFs=2 MF1='white':'linsmf',[0.1 1] MF2='black':'linzmf',[0 0.7] [Rules] 1 1, 1 (1) : 1 -1 -1, 2 (1) : 2 """ @test fis isa MamdaniFuzzySystem{MinAnd, MaxOr, MinImplication, MaxAggregator, BisectorDefuzzifier} @test fis.outputs[:Iout].mfs == Dictionary([:white, :black], [LinearMF(0.1, 1.0), LinearMF(0.7, 0.0)]) @test fis.rules[2] == FuzzyRule(FuzzyOr(FuzzyNegation(:Ix, :zero), FuzzyNegation(:Iy, :zero)), [FuzzyRelation(:Iout, :black)]) end @testset "Test Sugeno inference system" begin fis = matlabfis""" [System] Name='sugfis' Type='sugeno' Version=2.0 NumInputs=1 NumOutputs=1 NumRules=2 AndMethod='prod' OrMethod='probor' ImpMethod='prod' AggMethod='sum' DefuzzMethod='wtaver' [Input1] Name='input' Range=[-5 5] NumMFs=2 MF1='low':'gaussmf',[4 -5] MF2='high':'gaussmf',[4 5] [Output1] Name='output' Range=[0 1] NumMFs=2 MF1='line1':'linear',[-1 -1] MF2='line2':'constant',[0.5] [Rules] 1, 1 (0.5) : 1 2, 2 (0.5) : 1 """ @test fis isa SugenoFuzzySystem{ProdAnd, ProbSumOr} @test fis.outputs[:output].mfs == Dictionary([:line1, :line2], [ LinearSugenoOutput(Dictionary([:input], [-1.0]), -1.0), ConstantSugenoOutput(0.5), ]) @test fis.rules == [ WeightedFuzzyRule(FuzzyRelation(:input, :low), [FuzzyRelation(:output, :line1)], 0.5), WeightedFuzzyRule(FuzzyRelation(:input, :high), [FuzzyRelation(:output, :line2)], 0.5), ] end
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
docs
6871
# FuzzyLogic.jl |**Info**|**Build status**|**Documentation**|**Contributing**|**Citation**| |:------:|:--------------:|:---------------:|:--------------:|:----------:| |[![version][ver-img]][ver-url]|[![CI Status][ci-img]][ci-url]|[![Stable docs][stable-img]][stable-url]|[![contributing guidelines][contrib-img]][contrib-url]|[![bibtex][bibtex-img]][bibtex-url] |[![Licese: MIT][license-img]][license-url]|[![Coverage][cov-img]][cov-url]|[![Dev docs][dev-img]][dev-url]|[![SciML Code Style][style-img]][style-url]|[![paper][paper-img]][paper-url]| |[![downloads][download-img]][download-url]|[![pkgeval-img]][pkgeval-url]|[![JuliaCon video][video-img]][video-url]|[![gitter-chat][chat-img]][chat-url]|[![zenodo][zenodo-img]][zenodo-url] <p align="center"> <img src="./docs/src/assets/logo.svg"/> </p> A Julia library for fuzzy logic and applications. If you use this in your research, please cite it as ```bibtex @INPROCEEDINGS{ferranti2023fuzzylogicjl, author={Ferranti, Luca and Boutellier, Jani}, booktitle={2023 IEEE International Conference on Fuzzy Systems (FUZZ)}, title={FuzzyLogic.jl: A Flexible Library for Efficient and Productive Fuzzy Inference}, year={2023}, pages={1-5}, doi={10.1109/FUZZ52849.2023.10309777}} ``` ## Features - **Rich!** Mamdani and Sugeno inference systems, both Type-1 and Type-2, several [membership functions](https://lucaferranti.github.io/FuzzyLogic.jl/stable/api/memberships) and [algoritms options](https://lucaferranti.github.io/FuzzyLogic.jl/stable/api/fis) available. - **Compatible!** Read your models from [IEC 61131-7 Fuzzy Control Language](https://ffll.sourceforge.net/fcl.htm), [IEEE 1855-2016 Fuzzy Markup Language](https://en.wikipedia.org/wiki/Fuzzy_markup_language) and Matlab Fuzzy toolbox `.fis` files. - **Expressive!** Clear Domain Specific Language to write your model as human readable Julia code - **Productive!** Several visualization tools to help debug and tune your model. - **Portable!** Compile your final model to Julia code. ## Installation 1. If you haven't already, install Julia. The easiest way is to install [Juliaup](https://github.com/JuliaLang/juliaup#installation). This allows to easily manage julia versions. 2. Open the terminal and start a julia session by simply typing `julia` 3. Install the library by typing ```julia using Pkg; Pkg.add("FuzzyLogic") ``` 4. The package can now be loaded (in the interactive REPL or in a script file) with the command ```julia using FuzzyLogic ``` 5. That's it, have fun! ## Quickstart example ```julia fis = @mamfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = TriangularMF(0, 5, 10) average = TriangularMF(10, 15, 20) generous = TriangularMF(20, 25, 30) end service == poor || food == rancid --> tip == cheap service == good --> tip == average service == excellent || food == delicious --> tip == generous end fis(service=1, food=2) ``` ## Documentation - [**STABLE**][stable-url]: Documentation of the latest release - [**DEV**][dev-url]: Documentation of the version on main [![JuliaCon video](https://img.youtube.com/vi/6WfX3e-aOBc/0.jpg)](https://youtu.be/6WfX3e-aOBc) ## Contributing Contributions are welcome! Here is a small decision tree with useful links. - To chat withe the core dev(s), you can use the [element chat][chat-url]. This is a good entry point for less structured queries. - If you find a bug or want to request a feature, [open an issue](https://github.com/lucaferranti/FuzzyLogic.jl/issues). - There is a [discussion section](https://github.com/lucaferranti/FuzzyLogic.jl/discussions) on GitHub. You can use the [helpdesk](https://github.com/lucaferranti/FuzzyLogic.jl/discussions/categories/helpdesk) for asking for help on how to use the software or the [show and tell](https://github.com/lucaferranti/FuzzyLogic.jl/discussions/categories/show-and-tell) to share with the world your work using FuzzyLogic.jl. - You are also encouraged to send pull requests (PRs). For small changes, it is ok to open a PR directly. For bigger changes, it is advisable to discuss it in an issue first. Before opening a PR, make sure to check the [contributing guidelines](https://lucaferranti.github.io/FuzzyLogic.jl/dev/contributing). ## Copyright - Copyright (c) 2022 [Luca Ferranti](https://github.com/lucaferranti), released under MIT license. [ver-img]: https://juliahub.com/docs/FuzzyLogic/version.svg [ver-url]: https://github.com/lucaferranti/FuzzyLogic.jl/releases/latest [license-img]: https://img.shields.io/badge/license-MIT-yellow.svg [license-url]: https://github.com/lucaferranti/FuzzyLogic.jl/blob/main/LICENSE [download-img]: https://shields.io/endpoint?url=https://pkgs.genieframework.com/api/v1/badge/FuzzyLogic&label=downloads [download-url]: https://pkgs.genieframework.com/?packages=FuzzyLogic [stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [stable-url]:https://lucaferranti.github.io/FuzzyLogic.jl/stable/ [dev-img]: https://img.shields.io/badge/docs-dev-blue.svg [dev-url]: https://lucaferranti.github.io/FuzzyLogic.jl/dev/ [video-img]: https://img.shields.io/badge/JuliaCon-video-red.svg [video-url]: https://www.youtube.com/watch?v=6WfX3e-aOBc [ci-img]: https://github.com/lucaferranti/FuzzyLogic.jl/actions/workflows/CI.yml/badge.svg?branch=main [ci-url]: https://github.com/lucaferranti/FuzzyLogic.jl/actions/workflows/CI.yml?query=branch%3Amain [cov-img]: https://codecov.io/gh/lucaferranti/FuzzyLogic.jl/branch/main/graph/badge.svg [cov-url]: https://codecov.io/gh/lucaferranti/FuzzyLogic.jl [pkgeval-img]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/F/FuzzyLogic.svg [pkgeval-url]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/F/FuzzyLogic.html [contrib-img]: https://img.shields.io/badge/Contributor-Guide-blueviolet [contrib-url]: https://lucaferranti.github.io/FuzzyLogic.jl/dev/contributing [style-img]: https://img.shields.io/static/v1?label=code%20style&message=SciML&color=9558b2&labelColor=389826 [style-url]: https://github.com/SciML/SciMLStyle [chat-img]: https://badges.gitter.im/badge.svg [chat-url]: https://app.gitter.im/#/room/#FuzzyLogic-jl:gitter.im [bibtex-img]: https://img.shields.io/badge/BibTeX-citation-orange [bibtex-url]: https://github.com/lucaferranti/FuzzyLogic.jl/blob/main/CITATION.bib [paper-img]: https://img.shields.io/badge/FUZZIEEE-paper-blue [paper-url]: https://arxiv.org/abs/2306.10316 [zenodo-img]: https://img.shields.io/badge/Zenodo-archive-blue [zenodo-url]: https://doi.org/10.5281/zenodo.7570243
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
docs
3187
# Code of Conduct Interactions with people in the community must always follow the [Julia community standards](https://julialang.org/community/standards/), including in pull requests, issues, and discussions. > ## Julia Community Standards > > The Julia community is committed to maintaining a welcoming, civil and constructive environment. We expect the following standards to be observed and upheld by all participants in any community forum (mailing lists, GitHub, IRC, etc.). > > ### Be respectful and inclusive > > Please do not use overtly sexual language or imagery. Do not attack anyone based on any aspect of personal identity, including gender, sexuality, politics, religion, ethnicity, race, age, or ability. Keep in mind that what you write or say in public forums is read or heard by many people who don't know you personally, so please refrain from making prejudiced or sexual jokes and comments – even ones that you might consider acceptable in private. Ask yourself if a comment or statement might make someone feel unwelcomed or like an outsider. > > In particular, do not sexualize the term "Julia" or any other aspects of the project. While "Julia" is a female name in many parts of the world, the programming language is not a person and does not have a gender. > > ### Give credit > > All participants in the Julia community are expected to respect copyright laws and ethical attribution standards. This applies to both code and written materials, such as documentation or blog posts. Materials that violate the law, are plagiaristic, or ethically dubious in some way will be removed from officially-maintained lists of resources. > > ### Be concise > > Constructive criticism and suggestions are welcome, but high-traffic forums do not generally have the bandwidth for extensive discourse. Consider writing a blog post if you feel that you have enough to say on a particular subject. > > ### For Researchers > > We welcome the participation of researchers of all kinds in the Julia community. However, please remember that open source development is a social process and that the participants on the other side of any interaction are (obviously) humans. If you are doing research *on the community or its processes*, you are likely performing Human Subjects Research (HSR) and are expected to abide by the highest standards of ethics and professional practice. Meeting this expectation is your responsibility. In particular, please be aware that Institutional Review Boards (IRBs) or other review committees may not have sufficient context or experience to understand the social processes of an open source community. We consider engaging in unethical research (human subject or otherwise) to be a cause for bans or other sanctions from the community. > > ### Get involved > > The Julia community is built on a foundation of reciprocity and collaboration. Be aware that most community members contribute on a voluntary basis, so ideas and bug reports are ok, but demands are not. Pull requests are always welcomed – see the [guidelines for contributing](https://lucaferranti.github.io/FuzzyLogic.jl/dev/contributing) to read about how to get started.
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
docs
469
## Contributing Contributions are welcome! If you find a bug or want to request a feature, [open an issue](https://github.com/lucaferranti/FuzzyLogic.jl/issues). You are also encouraged to send pull requests (PRs). For small changes, it is ok to open a PR directly. For bigger changes, it is advisable to discuss it in an issue first. Before opening a PR, make sure to check the [contributing guidelines](https://lucaferranti.github.io/FuzzyLogic.jl/dev/contributing).
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
docs
803
## PR description <!-- A short description of what is done in this PR. --> ## Before <!-- Small example showing the functionality before this PR. Needed only if you are changing existing source code (e.g. bug fix) --> ## After <!-- Small example showing the functionality added/changed in this PR. Needed only if you change the source code. --> ## Related issues <!-- List the issues related to this PR. E.g. - #01 - #02 If you are closing some issues add "fixes" before the issue number, e.g. - fixes #01 - #02 --> ## Checklist <!-- Needed only if you change the source code. You don't need to get everything done before opening the PR :) --> - [ ] Updated/added tests - [ ] Updated/added docstring (needed only for exported functions) ## Other <!-- Add here any other relevant information. -->
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
docs
949
--- name: Bug report about: Report a bug for this project title: "[bug]" labels: bug assignees: '' --- ## Bug description <!-- A clear and concise description of what the bug is. --> ## Minimum (non-)working example <!-- A short code snippet demonstrating the bug, e.g. a snapshot from the REPL (make sure to include the whole error stracktrace) or a link to a notebook/script to reproduce the bug --> ## Expected behavior <!-- A clear and concise description of what you expected to happen. --> ## Version info <!-- you can get the package version with `]st FuzzyLogic` from the REPL. For the system information, enter `versioninfo()` in the Julia REPL and copy-paste the output. --> - FuzzyLogic.jl version: - System information: ## Related issues <!-- if you already know or suspect some existing issues are related to this, please mention those here, otherwise leave blank --> ## Additional information Add any other useful information
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
docs
521
--- name: Feature request about: Suggest an idea for this project title: "[enhancement]: " labels: enhancement assignees: '' --- ## Feature description <!-- A clear and concise description of the feature you would like to be added. Try to also give motivation why it would be a nice addition. --> ## Minimum working example <!-- If you already have in mind what the code for your feature could look like, paste an example code snippet here --> ## Additional information <!-- Add any other useful information here -->
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
docs
3680
# Release Notes The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## Unreleased - ![](https://img.shields.io/badge/bugfix-purple.svg) fix bug in Julia code generation of ZShape and SShape mf - ![](https://img.shields.io/badge/bugfix-purple.svg) disallow implicit conversion from interval to float - ![](https://img.shields.io/badge/new%20feature-green.svg) added semi-elliptic and singleton membership functions - ![](https://img.shields.io/badge/new%20feature-green.svg) added `gensurf` to plot generating surface - ![](https://img.shields.io/badge/bugfix-purple.svg) fix plotting of systems with several rules and membership functions. - ![](https://img.shields.io/badge/bugfix-purple.svg) fix plotting of Type-2 systems ## v0.1.2 -- 2023-03-12 [view release on GitHub](https://github.com/lucaferranti/FuzzyLogic.jl/releases/tag/v0.1.2) - ![](https://img.shields.io/badge/new%20feature-green.svg) support for weighted rules. - ![](https://img.shields.io/badge/new%20feature-green.svg) allow to specify input and output variables as vectors (e.g. `x[1:10]`) and support for loops to avoid repetitive code. - ![](https://img.shields.io/badge/new%20feature-green.svg) added support for type-2 membership functions and type-2 systems. - ![](https://img.shields.io/badge/new%20feature-green.svg) added parser for Fuzzy Markup Language. - ![](https://img.shields.io/badge/new%20feature-green.svg) added generation of native Julia code. - ![](https://img.shields.io/badge/enhancement-blue.svg) added left maximum, right maximum and mean of maxima defuzzifiers. ## v0.1.1 -- 2023-02-25 [view release on GitHub](https://github.com/lucaferranti/FuzzyLogic.jl/releases/tag/v0.1.1) - ![](https://img.shields.io/badge/new%20feature-green.svg) Added fuzzy c-means - ![](https://img.shields.io/badge/enhancement-blue.svg) added Lukasiewicz, drastic, nilpotent and Hamacher T-norms and corresponding S-norms. - ![](https://img.shields.io/badge/enhancement-blue.svg) dont build anonymous functions during mamdani inference, but evaluate output directly. Now defuzzifiers don't take a function as input, but an array. - ![](https://img.shields.io/badge/enhancement-blue.svg) added piecewise linear membership function - ![](https://img.shields.io/badge/new%20feature-green.svg) added parser for Fuzzy Control Language and matlab fis. ## v0.1.0 -- 2023-01-10 **initial public release** - initial domain specific language design and parser - initial membership functions: triangular, trapezoidal, gaussian, bell, linear, sigmoid, sum of sigmoids, product of sigmoids, s-shaped, z-shaped, pi-shaped. - initial implementation of Mamdani and Sugeno inference systems (type 1) - min and prod t-norms with corresponding conorms - min and prod implication - max and probabilistic sum aggregation method - centroid and bisector defuzzifier - linear and constant output for Sugeno - initial plotting functionalities - plotting variables and membership functions - plotting rules of fuzzy inference system [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/new%20feature-green.svg [badge-enhancement]: https://img.shields.io/badge/enhancement-blue.svg [badge-bugfix]: https://img.shields.io/badge/bugfix-purple.svg [badge-security]: https://img.shields.io/badge/security-black.svg [badge-experimental]: https://img.shields.io/badge/experimental-lightgrey.svg [badge-maintenance]: https://img.shields.io/badge/maintenance-gray.svg
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
docs
5777
# Contributor's guide First of all, huge thanks for your interest in the package! ✨ This page has some tips and guidelines on how to contribute. For more unstructured discussions, you can chat with the developers in the [element chat](https://app.gitter.im/#/room/#FuzzyLogic-jl:gitter.im). ## Discussions If you are using FuzzyLogic.jl in your work and get stuck, you can use the [helpdesk](https://github.com/lucaferranti/FuzzyLogic.jl/discussions/categories/helpdesk) to ask for help. This is preferable over issues, which are meant for bugs and feature requests, because discussions do not get closed once fixed and remain browsable for others. There is also a [show and tell](https://github.com/lucaferranti/FuzzyLogic.jl/discussions/categories/show-and-tell) section to share with the world your work using FuzzyLogic.jl. If your work involves a new application of FuzzyLogic.jl and you also want it featured in the Applications section in the documentation, let us know (in the element chat or in an issue). You will get help with the workflow and setup, but you are expected to do the writing 😃 . ## Opening issues If you spot something strange in the software (something doesn't work or doesn't behave as expected) do not hesitate to open a [bug issue](https://github.com/lucaferranti/FuzzyLogic.jl/issues/new?assignees=&labels=bug&template=bug_report.md&title=%5Bbug%5D). If have an idea of how to make the package better (a new feature, a new piece of documentation, an idea to improve some existing feature), you can open an [enhancement issue](https://github.com/lucaferranti/FuzzyLogic.jl/issues/new?assignees=&labels=enhancement&template=feature_request.md&title=%5Benhancement%5D%3A+). In both cases, try to follow the template, but do not worry if you don't know how to fill something. If you feel like your issue does not fit any of the above mentioned templates (e.g. you just want to ask something), you can also open a [blank issue](https://github.com/lucaferranti/FuzzyLogic.jl/issues/new). ## Collaborative Practices We follow the [ColPrac guide for collaborative practices](https://github.com/SciML/ColPrac). New contributors should make sure to read that guide. Below are some additional practices we follow. ## Git workflow All contributions should go through git branches. If you are not familiar with git practices, you will find some references at the end of this file. Here is a short cheat-sheet. ### Setup **1.** Clone the repository ``` git clone https://github.com/lucaferranti/FuzzyLogic.jl.git ``` and enter it with ``` cd FuzzyLogic.jl ``` !!! warning "Warning" From now on, these instructions assume you are in the `FuzzyLogic.jl` folder **2.** [Fork the repository](https://github.com/lucaferranti/FuzzyLogic.jl). **3.** Add your fork as remote with ``` git remote add $new_remote_name $your_fork_link ``` for example ``` git remote add johndoe https://github.com/johndoe/FuzzyLogic.jl.git ``` after this running `git remote -v` should produce ``` lucaferranti https://github.com/lucaferranti/FuzzyLogic.jl.git (fetch) lucaferranti https://github.com/lucaferranti/FuzzyLogic.jl.git (push) johndoe https://github.com/johndoe/FuzzyLogic.jl.git (fetch) johndoe https://github.com/johndoe/FuzzyLogic.jl.git (push) ``` ### Working with branches **0.** Run `git branch` and check you are on `main`. If you are not, switch to `main` via ``` git switch main ``` Next, make sure your local version is up to date by running ``` git fetch origin git merge origin/main ``` **1.** Create a new branch with ``` git switch -c $new-branch-name ``` **3.** Now let the fun begin! Fix bugs, add the new features, modify the docs, whatever you do, it's gonna be awesome! **4.** When you are ready, go to the [package main repository](https://github.com/lucaferranti/FuzzyLogic.jl) (not your fork!) and open a pull request. **5.** If nothing happens within 7 working days feel free to ping Luca Ferranti (@lucaferranti) every 1-2 days until you get his attention. ## Coding guideline * The package follows [SciMLStyle](https://github.com/sciml/SciMLStyle). * You can run the tests locally from the Julia REPL with ```julia include("test/runtests.jl") ``` * Each test file is stand-alone, hence you can also run individual files, e.g. `include("test/test_parser.jl")` * To make finding tests easier, the test folder structure should (roughly) reflect the structure of the `src` folder. ## Working on the documentation ### Local setup The first time you start working on the documentation locally, you will need to install all needed dependencies. To do so, run ``` julia docs/setup.jl ``` This needs to be done only the fist time (if you don't have `docs/Manifest.toml`) or any time the Manifest becomes outdated. Next, you can build the documentation locally by running ``` julia docs/liveserver.jl ``` This will open a preview of the documentation in your browser and watch the documentation source files, meaning the preview will automatically update on every documentation change. ### Working with literate. * Tutorials and applications are written using [Literate.jl](https://github.com/fredrikekre/Literate.jl). Hence, do not directly edit the markdown files under `docs/src/tutorials` and `docs/src/applications`, edit instead the corresponding julia files under `docs/src/literate`. ## Further reading Here is a list of useful resources for contributors. * [Making a first Julia pull request](https://kshyatt.github.io/post/firstjuliapr/) <-- read this if you are not familiar with the git workflow! * [JuliaReach developers docs](https://github.com/JuliaReach/JuliaReachDevDocs) * [Julia contributing guideline](https://github.com/JuliaLang/julia/blob/master/CONTRIBUTING.md)
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
docs
4783
# FuzzyLogic.jl |**Info**|**Build status**|**Documentation**|**Contributing**|**Citation**| |:------:|:--------------:|:---------------:|:--------------:|:----------:| |[![version](https://juliahub.com/docs/FuzzyLogic/version.svg)](https://github.com/lucaferranti/FuzzyLogic.jl/releases/latest)|[![CI Status](https://github.com/lucaferranti/FuzzyLogic.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/lucaferranti/FuzzyLogic.jl/actions/workflows/CI.yml?query=branch%3Amain)|[![Stable docs](https://img.shields.io/badge/docs-stable-blue.svg)](https://lucaferranti.github.io/FuzzyLogic.jl/stable/)|[![contributing guidelines](https://img.shields.io/badge/Contributor-Guide-blueviolet)](https://lucaferranti.github.io/FuzzyLogic.jl/dev/contributing)|[![bibtex](https://img.shields.io/badge/BibTeX-citation-orange)](https://github.com/lucaferranti/FuzzyLogic.jl/blob/main/CITATION.bib) |[![Licese: MIT](https://img.shields.io/badge/license-MIT-yellow.svg)](https://github.com/lucaferranti/FuzzyLogic.jl/blob/main/LICENSE)|[![Coverage](https://codecov.io/gh/lucaferranti/FuzzyLogic.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/lucaferranti/FuzzyLogic.jl)|[![Dev docs](https://img.shields.io/badge/docs-dev-blue.svg)](https://lucaferranti.github.io/FuzzyLogic.jl/dev/)|[![SciML Code Style](https://img.shields.io/static/v1?label=code%20style&message=SciML&color=9558b2&labelColor=389826)](https://github.com/SciML/SciMLStyle)|[![paper](https://img.shields.io/badge/FUZZIEEE-paper-blue)](https://arxiv.org/abs/2306.10316) |[![downloads](https://shields.io/endpoint?url=https://pkgs.genieframework.com/api/v1/badge/FuzzyLogic&label=downloads)](https://pkgs.genieframework.com/?packages=FuzzyLogic)|[![PkgEval](https://juliaci.github.io/NanosoldierReports/pkgeval_badges/F/FuzzyLogic.svg)](https://juliaci.github.io/NanosoldierReports/pkgeval_badges/F/FuzzyLogic.html)|[![JuliaCon video](https://img.shields.io/badge/JuliaCon-video-red.svg)](https://www.youtube.com/watch?v=6WfX3e-aOBc)|[![gitter-chat](https://badges.gitter.im/badge.svg)](https://app.gitter.im/#/room/#FuzzyLogic-jl:gitter.im)|[![zenodo](https://img.shields.io/badge/Zenodo-archive-blue)](https://doi.org/10.5281/zenodo.7570243) A Julia library for fuzzy logic and applications. If you use this in your research, please cite it as ```bibtex @INPROCEEDINGS{ferranti2023fuzzylogicjl, author={Ferranti, Luca and Boutellier, Jani}, booktitle={2023 IEEE International Conference on Fuzzy Systems (FUZZ)}, title={FuzzyLogic.jl: A Flexible Library for Efficient and Productive Fuzzy Inference}, year={2023}, pages={1-5}, doi={10.1109/FUZZ52849.2023.10309777}} ``` ## Features - **Rich!** Mamdani and Sugeno inference systems, both Type-1 and Type-2, several [membership functions](https://lucaferranti.github.io/FuzzyLogic.jl/stable/api/memberships) and [algoritms options](https://lucaferranti.github.io/FuzzyLogic.jl/stable/api/fis) available. - **Compatible!** Read your models from [IEC 61131-7 Fuzzy Control Language](https://ffll.sourceforge.net/fcl.htm), [IEEE 1855-2016 Fuzzy Markup Language](https://en.wikipedia.org/wiki/Fuzzy_markup_language) and Matlab Fuzzy toolbox `.fis` files. - **Expressive!** Clear Domain Specific Language to write your model as human readable Julia code - **Productive!** Several visualization tools to help debug and tune your model. - **Portable!** Compile your final model to Julia code. ## Installation 1. If you haven't already, install Julia. The easiest way is to install [Juliaup](https://github.com/JuliaLang/juliaup#installation). This allows to easily manage julia versions. 2. Open the terminal and start a julia session by simply typing `julia` 3. Install the library by typing ```julia using Pkg; Pkg.add("FuzzyLogic") ``` 4. The package can now be loaded (in the interactive REPL or in a script file) with the command ```julia using FuzzyLogic ``` 5. That's it, have fun! ## Quickstart example ```julia fis = @mamfis function tipper(service, food)::tip service := begin domain = 0:10 poor = GaussianMF(0.0, 1.5) good = GaussianMF(5.0, 1.5) excellent = GaussianMF(10.0, 1.5) end food := begin domain = 0:10 rancid = TrapezoidalMF(-2, 0, 1, 3) delicious = TrapezoidalMF(7, 9, 10, 12) end tip := begin domain = 0:30 cheap = TriangularMF(0, 5, 10) average = TriangularMF(10, 15, 20) generous = TriangularMF(20, 25, 30) end service == poor || food == rancid --> tip == cheap service == good --> tip == average service == excellent || food == delicious --> tip == generous end fis(service=1, food=2) ``` ## Copyright - Copyright (c) 2022 [Luca Ferranti](https://github.com/lucaferranti), released under MIT license.
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
docs
137
# Aggregation methods ```@autodocs Modules = [FuzzyLogic] Filter = t -> typeof(t) === DataType && t <: FuzzyLogic.AbstractAggregator ```
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
docs
343
# Defuzzification methods ## Type-1 defuzzifiers ```@autodocs Modules = [FuzzyLogic] Filter = t -> typeof(t) === DataType && t <: FuzzyLogic.AbstractDefuzzifier && !(t <: FuzzyLogic.Type2Defuzzifier) ``` ## Type-2 defuzzifiers ```@autodocs Modules = [FuzzyLogic] Filter = t -> typeof(t) === DataType && t <: FuzzyLogic.Type2Defuzzifier ```
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
docs
221
# Inference Systems ## Mamdani inference system ```@docs MamdaniFuzzySystem ``` ## Sugeno inference system ```@docs SugenoFuzzySystem ConstantSugenoOutput LinearSugenoOutput ``` ## General functions ```@docs set ```
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
docs
50
# Learning fuzzy models ```@docs fuzzy_cmeans ```
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
docs
49
# Plotting functionalities ```@docs gensurf ```
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.1.3
a115d9472101bda97aa1c48b304ed8d8626d5bd7
docs
333
# Reading / writing functionalities ## Parse Julia code ```@docs @mamfis @sugfis ``` ## Generate Julia code ```@docs compilefis ``` ## Read from file ```@docs readfis ``` ## Parse FCL ```@docs parse_fcl @fcl_str ``` ## Parse FML ```@docs parse_fml @fml_str ``` ## Parse Matlab ```@docs parse_matlabfis @matlabfis_str ```
FuzzyLogic
https://github.com/lucaferranti/FuzzyLogic.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
601
# Retrieve name of example and output directory if length(ARGS) != 2 error("please specify the name of the example and the output directory") end const EXAMPLE = ARGS[1] const OUTDIR = ARGS[2] # Activate environment # Note that each example's Project.toml must include Literate as a dependency using Pkg: Pkg const EXAMPLEPATH = joinpath(@__DIR__, "..", "examples", EXAMPLE) Pkg.activate(EXAMPLEPATH) Pkg.instantiate() using Literate: Literate # Convert to markdown and notebook const SCRIPTJL = joinpath(EXAMPLEPATH, "script.jl") Literate.markdown(SCRIPTJL, OUTDIR; name=EXAMPLE, execute=true)
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
2479
# # With minor changes from https://github.com/JuliaGaussianProcesses/AbstractGPs.jl/docs # ### Process examples # Always rerun examples const EXAMPLES_OUT = joinpath(@__DIR__, "src", "examples") ispath(EXAMPLES_OUT) && rm(EXAMPLES_OUT; recursive=true) mkpath(EXAMPLES_OUT) # Install and precompile all packages # Workaround for https://github.com/JuliaLang/Pkg.jl/issues/2219 examples = filter!(isdir, readdir(joinpath(@__DIR__, "..", "examples"); join=true)) above = joinpath(@__DIR__, "..") let script = "using Pkg; Pkg.activate(ARGS[1]); Pkg.instantiate(); Pkg.develop(path=\"$(above)\");" for example in examples if !success(`$(Base.julia_cmd()) -e $script $example`) error( "project environment of example ", basename(example), " could not be instantiated", ) end end end # Run examples asynchronously processes = let literatejl = joinpath(@__DIR__, "literate.jl") map(examples) do example return run( pipeline( `$(Base.julia_cmd()) $literatejl $(basename(example)) $EXAMPLES_OUT`; stdin=devnull, stdout=devnull, stderr=stderr, ); wait=false, )::Base.Process end end # Check that all examples were run successfully isempty(processes) || success(processes) || error("some examples were not run successfully") # Building Documenter using Documenter using AdvancedPS DocMeta.setdocmeta!(AdvancedPS, :DocTestSetup, :(using AdvancedPS); recursive=true) makedocs(; sitename="AdvancedPS", format=Documenter.HTML(), modules=[AdvancedPS], pages=[ "Home" => "index.md", "api.md", "Examples" => [ "example.md", map( (x) -> joinpath("examples", x), filter!(filename -> endswith(filename, ".md"), readdir(EXAMPLES_OUT)), )..., ], ], #strict=true, checkdocs=:exports, doctestfilters=[ # Older versions will show "0 element Array" instead of "Type[]". r"(Any\[\]|0-element Array{.+,[0-9]+})", # Older versions will show "Array{...,1}" instead of "Vector{...}". r"(Array{.+,\s?1}|Vector{.+})", # Older versions will show "Array{...,2}" instead of "Matrix{...}". r"(Array{.+,\s?2}|Matrix{.+})", ], ) deploydocs(; repo="github.com/TuringLang/AdvancedPS.jl.git", push_preview=true)
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
2222
# # Gaussian Process State-Space Model (GP-SSM) using LinearAlgebra using Random using AdvancedPS using AbstractGPs using Plots using Distributions using Libtask using SSMProblems Parameters = @NamedTuple begin a::Float64 q::Float64 kernel end mutable struct GPSSM <: SSMProblems.AbstractStateSpaceModel X::Vector{Float64} observations::Vector{Float64} θ::Parameters GPSSM(params::Parameters) = new(Vector{Float64}(), params) GPSSM(y::Vector{Float64}, params::Parameters) = new(Vector{Float64}(), y, params) end seed = 1 T = 100 Nₚ = 20 Nₛ = 250 a = 0.9 q = 0.5 params = Parameters((a, q, SqExponentialKernel())) f(θ::Parameters, x, t) = Normal(θ.a * x, θ.q) h(θ::Parameters) = Normal(0, θ.q) g(θ::Parameters, x, t) = Normal(0, exp(0.5 * x)^2) rng = Random.MersenneTwister(seed) x = zeros(T) y = similar(x) x[1] = rand(rng, h(params)) for t in 1:T if t < T x[t + 1] = rand(rng, f(params, x[t], t)) end y[t] = rand(rng, g(params, x[t], t)) end function gp_update(model::GPSSM, state, step) gp = GP(model.θ.kernel) prior = gp(1:(step - 1)) post = posterior(prior, model.X[1:(step - 1)]) μ, σ = mean_and_cov(post, [step]) return Normal(μ[1], σ[1]) end SSMProblems.transition!!(rng::AbstractRNG, model::GPSSM) = rand(rng, h(model.θ)) function SSMProblems.transition!!(rng::AbstractRNG, model::GPSSM, state, step) return rand(rng, gp_update(model, state, step)) end function SSMProblems.emission_logdensity(model::GPSSM, state, step) return logpdf(g(model.θ, state, step), model.observations[step]) end function SSMProblems.transition_logdensity(model::GPSSM, prev_state, current_state, step) return logpdf(gp_update(model, prev_state, step), current_state) end AdvancedPS.isdone(::GPSSM, step) = step > T model = GPSSM(y, params) pg = AdvancedPS.PGAS(Nₚ) chains = sample(rng, model, pg, Nₛ) particles = hcat([chain.trajectory.model.X for chain in chains]...) mean_trajectory = mean(particles; dims=2); scatter(particles; label=false, opacity=0.01, color=:black, xlabel="t", ylabel="state") plot!(x; color=:darkorange, label="Original Trajectory") plot!(mean_trajectory; color=:dodgerblue, label="Mean trajectory", opacity=0.9)
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
4750
# # Particle Gibbs for Gaussian state-space model using AdvancedPS using Random using Distributions using Plots using SSMProblems # We consider the following linear state-space model with Gaussian innovations. The latent state is a simple gaussian random walk # and the observation is linear in the latent states, namely: # # ```math # x_{t+1} = a x_{t} + \epsilon_t \quad \epsilon_t \sim \mathcal{N}(0,q^2) # ``` # ```math # y_{t} = x_{t} + \nu_{t} \quad \nu_{t} \sim \mathcal{N}(0, r^2) # ``` # # Here we assume the static parameters $\theta = (a, q^2, r^2)$ are known and we are only interested in sampling from the latent states $x_t$. # To use particle gibbs with the ancestor sampling update step we need to provide both the transition and observation densities. # # From the definition above we get: # ```math # x_{t+1} \sim f_{\theta}(x_{t+1}|x_t) = \mathcal{N}(a x_t, q^2) # ``` # ```math # y_t \sim g_{\theta}(y_t|x_t) = \mathcal{N}(x_t, q^2) # ``` # as well as the initial distribution $f_0(x) = \mathcal{N}(0, q^2/(1-a^2))$. # To use `AdvancedPS` we first need to define a model type that subtypes `AdvancedPS.AbstractStateSpaceModel`. Parameters = @NamedTuple begin a::Float64 q::Float64 r::Float64 end mutable struct LinearSSM <: SSMProblems.AbstractStateSpaceModel X::Vector{Float64} observations::Vector{Float64} θ::Parameters LinearSSM(θ::Parameters) = new(Vector{Float64}(), θ) LinearSSM(y::Vector, θ::Parameters) = new(Vector{Float64}(), y, θ) end # and the densities defined above. f(θ::Parameters, state, t) = Normal(θ.a * state, θ.q) # Transition density g(θ::Parameters, state, t) = Normal(state, θ.r) # Observation density f₀(θ::Parameters) = Normal(0, θ.q^2 / (1 - θ.a^2)) # Initial state density #md nothing #hide # We also need to specify the dynamics of the system through the transition equations: # - `AdvancedPS.initialization`: the initial state density # - `AdvancedPS.transition`: the state transition density # - `AdvancedPS.observation`: the observation score given the observed data # - `AdvancedPS.isdone`: signals the end of the execution for the model SSMProblems.transition!!(rng::AbstractRNG, model::LinearSSM) = rand(rng, f₀(model.θ)) function SSMProblems.transition!!( rng::AbstractRNG, model::LinearSSM, state::Float64, step::Int ) return rand(rng, f(model.θ, state, step)) end function SSMProblems.emission_logdensity(modeL::LinearSSM, state::Float64, step::Int) return logpdf(g(model.θ, state, step), model.observations[step]) end function SSMProblems.transition_logdensity( model::LinearSSM, prev_state, current_state, step ) return logpdf(f(model.θ, prev_state, step), current_state) end # We need to think seriously about how the data is handled AdvancedPS.isdone(::LinearSSM, step) = step > Tₘ # Everything is now ready to simulate some data. a = 0.9 # Scale q = 0.32 # State variance r = 1 # Observation variance Tₘ = 200 # Number of observation Nₚ = 20 # Number of particles Nₛ = 500 # Number of samples seed = 1 # Reproduce everything θ₀ = Parameters((a, q, r)) rng = Random.MersenneTwister(seed) x = zeros(Tₘ) y = zeros(Tₘ) x[1] = rand(rng, f₀(θ₀)) for t in 1:Tₘ if t < Tₘ x[t + 1] = rand(rng, f(θ₀, x[t], t)) end y[t] = rand(rng, g(θ₀, x[t], t)) end # Here are the latent and obseravation timeseries plot(x; label="x", xlabel="t") plot!(y; seriestype=:scatter, label="y", xlabel="t", mc=:red, ms=2, ma=0.5) # `AdvancedPS` subscribes to the `AbstractMCMC` API. To sample we just need to define a Particle Gibbs kernel # and a model interface. model = LinearSSM(y, θ₀) pgas = AdvancedPS.PGAS(Nₚ) chains = sample(rng, model, pgas, Nₛ; progress=false); #md nothing #hide # particles = hcat([chain.trajectory.model.X for chain in chains]...) mean_trajectory = mean(particles; dims=2); #md nothing #hide # This toy model is small enough to inspect all the generated traces: scatter(particles; label=false, opacity=0.01, color=:black, xlabel="t", ylabel="state") plot!(x; color=:darkorange, label="Original Trajectory") plot!(mean_trajectory; color=:dodgerblue, label="Mean trajectory", opacity=0.9) # We used a particle gibbs kernel with the ancestor updating step which should help with the particle # degeneracy problem and improve the mixing. # We can compute the update rate of $x_t$ vs $t$ defined as the proportion of times $t$ where $x_t$ gets updated: update_rate = sum(abs.(diff(particles; dims=2)) .> 0; dims=2) / Nₛ #md nothing #hide # and compare it to the theoretical value of $1 - 1/Nₚ$. plot( update_rate; label=false, ylim=[0, 1], legend=:bottomleft, xlabel="Iteration", ylabel="Update rate", ) hline!([1 - 1 / Nₚ]; label="N: $(Nₚ)")
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
6413
# # Levy-SSM latent state inference using AdvancedPS: SSMProblems using AdvancedPS using Random using Plots using Distributions using AdvancedPS using LinearAlgebra using SSMProblems struct GammaProcess C::Float64 β::Float64 tol::Float64 end struct GammaPath{T} jumps::Vector{T} times::Vector{T} end struct LangevinDynamics{T} A::Matrix{T} L::Vector{T} θ::T H::Vector{T} σe::T end struct NormalMeanVariance{T} μ::T σ::T end function simulate( rng::AbstractRNG, process::GammaProcess, rate::Float64, start::Float64, finish::Float64, t0::Float64=0.0, ) let β = process.β, C = process.C, tolerance = process.tol jumps = Float64[] last_jump = Inf t = t0 truncated = last_jump < tolerance while !truncated t += rand(rng, Exponential(1.0 / rate)) xi = 1.0 / (β * (exp(t / C) - 1)) prob = (1.0 + β * xi) * exp(-β * xi) if rand(rng) < prob push!(jumps, xi) last_jump = xi end truncated = last_jump < tolerance end times = rand(rng, Uniform(start, finish), length(jumps)) return GammaPath(jumps, times) end end function integral(times::Array{Float64}, path::GammaPath) let jumps = path.jumps, jump_times = path.times return [sum(jumps[jump_times .<= t]) for t in times] end end # Gamma Process C = 1.0 β = 1.0 ϵ = 1e-10 process = GammaProcess(C, β, ϵ) # Normal Mean-Variance representation μw = 0.0 σw = 1.0 nvm = NormalMeanVariance(μw, σw) # Levy SSM with Langevin dynamics # dx(t) = A x(t) dt + L dW(t) # y(t) = H x(t) + ϵ(t) θ = -0.5 A = [ 0.0 1.0 0.0 θ ] L = [0.0; 1.0] σe = 1.0 H = [1.0, 0] dyn = LangevinDynamics(A, L, θ, H, σe) # Simulation parameters start, finish = 0, 100 N = 200 ts = range(start, finish; length=N) seed = 4 rng = Random.MersenneTwister(seed) Np = 50 Ns = 100 f(dt, θ) = exp(θ * dt) function Base.exp(dyn::LangevinDynamics, dt::Real) let θ = dyn.θ f_val = f(dt, θ) return [1.0 (f_val - 1)/θ; 0 f_val] end end function meancov( t::T, dyn::LangevinDynamics, path::GammaPath, nvm::NormalMeanVariance ) where {T<:Real} μ = zeros(T, 2) Σ = zeros(T, (2, 2)) let times = path.times, jumps = path.jumps, μw = nvm.μ, σw = nvm.σ for (v, z) in zip(times, jumps) ft = exp(dyn, (t - v)) * dyn.L μ += ft .* μw .* z Σ += ft * transpose(ft) .* σw^2 .* z end return μ, Σ end end X = zeros(Float64, (N, 2)) Y = zeros(Float64, N) for (i, t) in enumerate(ts) if i > 1 s = ts[i - 1] dt = t - s path = simulate(rng, process, dt, s, t, ϵ) μ, Σ = meancov(t, dyn, path, nvm) X[i, :] .= rand(rng, MultivariateNormal(exp(dyn, dt) * X[i - 1, :] + μ, Σ)) end let H = dyn.H, σe = dyn.σe Y[i] = transpose(H) * X[i, :] + rand(rng, Normal(0, σe)) end end # AdvancedPS Parameters = @NamedTuple begin dyn::LangevinDynamics process::GammaProcess nvm::NormalMeanVariance times::Vector{Float64} end struct MixedState{T} x::Vector{T} path::GammaPath{T} end mutable struct LevyLangevin <: SSMProblems.AbstractStateSpaceModel X::Vector{MixedState{Float64}} observations::Vector{Float64} θ::Parameters LevyLangevin(θ::Parameters) = new(Vector{MixedState{Float64}}(), θ) function LevyLangevin(y::Vector{Float64}, θ::Parameters) return new(Vector{MixedState{Float64}}(), y, θ) end end function SSMProblems.transition!!(rng::AbstractRNG, model::LevyLangevin) return MixedState( rand(rng, MultivariateNormal([0, 0], I)), GammaPath(Float64[], Float64[]) ) end function SSMProblems.transition!!( rng::AbstractRNG, model::LevyLangevin, state::MixedState, step ) times = model.θ.times s = times[step - 1] t = times[step] dt = t - s path = simulate(rng, model.θ.process, dt, s, t) μ, Σ = meancov(t, model.θ.dyn, path, model.θ.nvm) Σ += 1e-6 * I return MixedState(rand(rng, MultivariateNormal(exp(dyn, dt) * state.x + μ, Σ)), path) end function SSMProblems.transition_logdensity( model::LevyLangevin, prev_state::MixedState, current_state::MixedState, step ) times = model.θ.times s = times[step - 1] t = times[step] dt = t - s path = simulate(rng, model.θ.process, dt, s, t) μ, Σ = meancov(t, model.θ.dyn, path, model.θ.nvm) Σ += 1e-6 * I return logpdf(MultivariateNormal(exp(dyn, dt) * prev_state.x + μ, Σ), current_state.x) end function SSMProblems.emission_logdensity(model::LevyLangevin, state::MixedState, step) return logpdf(Normal(transpose(H) * state.x, σe), model.observations[step]) end AdvancedPS.isdone(model::LevyLangevin, step) = step > length(model.θ.times) θ₀ = Parameters((dyn, process, nvm, ts)) model = LevyLangevin(Y, θ₀) pg = AdvancedPS.PGAS(Np) chains = sample(rng, model, pg, Ns; progress=false); # Concat all sampled states particles = hcat([chain.trajectory.model.X for chain in chains]...) marginal_states = map(s -> s.x, particles); jump_times = map(s -> s.path.times, particles); jump_intensities = map(s -> s.path.jumps, particles); # Plot marginal state and jump intensities for one trajectory p1 = plot( ts, [state[1] for state in marginal_states[:, end]]; color=:darkorange, label="Marginal State (x1)", ) plot!( ts, [state[2] for state in marginal_states[:, end]]; color=:dodgerblue, label="Marginal State (x2)", ) p2 = scatter( vcat([t for t in jump_times[:, end]]...), vcat([j for j in jump_intensities[:, end]]...); color=:darkorange, label="Jumps", ) plot( p1, p2; plot_title="Marginal State and Jump Intensities", layout=(2, 1), size=(600, 600) ) # Plot mean trajectory with standard deviation mean_trajectory = transpose(hcat(mean(marginal_states; dims=2)...)) std_trajectory = dropdims(std(stack(marginal_states); dims=3); dims=3) ps = [] for d in 1:2 p = plot( ts, mean_trajectory[:, d]; ribbon=2 * std_trajectory[:, d]', color=:darkorange, label="Mean Trajectory (±2σ)", fillalpha=0.2, title="Marginal State Trajectories (X$d)", ) plot!(p, ts, X[:, d]; color=:dodgerblue, label="True Trajectory") push!(ps, p) end plot(ps...; layout=(2, 1), size=(600, 600))
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
5481
# # Particle Gibbs for non-linear models using AdvancedPS using Random using Distributions using Plots using AbstractMCMC using Random123 using SSMProblems """ plot_update_rate(update_rate, N) Plot empirical update rate against theoretical value """ function plot_update_rate(update_rate::AbstractVector{Float64}, Nₚ::Int) plt = plot( update_rate; label=false, ylim=[0, 1], legend=:bottomleft, xlabel="Iteration", ylabel="Update rate", ) return hline!(plt, [1 - 1 / Nₚ]; label="N: $(Nₚ)") end """ update_rate(trajectories, N) Compute latent state update rate """ function update_rate(particles::AbstractMatrix{Float64}, Nₛ) return sum(abs.(diff(particles; dims=2)) .> 0; dims=2) / Nₛ end #md nothing #hide # We consider the following stochastic volatility model: # # ```math # x_{t+1} = a x_t + v_t \quad v_{t} \sim \mathcal{N}(0, r^2) # ``` # ```math # y_{t} = e_t \exp(\frac{1}{2}x_t) \quad e_t \sim \mathcal{N}(0, 1) # ``` # # We can reformulate the above in terms of transition and observation densities: # ```math # x_{t+1} \sim f_{\theta}(x_{t+1}|x_t) = \mathcal{N}(a x_t, r^2) # ``` # ```math # y_t \sim g_{\theta}(y_t|x_t) = \mathcal{N}(0, \exp(\frac{1}{2}x_t)^2) # ``` # with the initial distribution $f_0(x) = \mathcal{N}(0, q^2)$. # Here we assume the static parameters $\theta = (q^2, r^2)$ are known and we are only interested in sampling from the latent state $x_t$. Parameters = @NamedTuple begin a::Float64 q::Float64 T::Int end f(θ::Parameters, state, t) = Normal(θ.a * state, θ.q) g(θ::Parameters, state, t) = Normal(0, exp(0.5 * state)) f₀(θ::Parameters) = Normal(0, θ.q) #md nothing #hide # Let's simulate some data a = 0.9 # State Variance q = 0.5 # Observation variance Tₘ = 200 # Number of observation Nₚ = 20 # Number of particles Nₛ = 200 # Number of samples seed = 1 # Reproduce everything θ₀ = Parameters((a, q, Tₘ)) rng = Random.MersenneTwister(seed) x = zeros(Tₘ) y = zeros(Tₘ) x[1] = 0 for t in 1:Tₘ if t < Tₘ x[t + 1] = rand(rng, f(θ₀, x[t], t)) end y[t] = rand(rng, g(θ₀, x[t], t)) end # Here are the latent and observation series: plot(x; label="x", xlabel="t") # plot(y; label="y", xlabel="t") # Each model takes an `AbstractRNG` as input and generates the logpdf of the current transition: mutable struct NonLinearTimeSeries <: SSMProblems.AbstractStateSpaceModel X::Vector{Float64} observations::Vector{Float64} θ::Parameters NonLinearTimeSeries(θ::Parameters) = new(Float64[], θ) NonLinearTimeSeries(y::Vector{Float64}, θ::Parameters) = new(Float64[], y, θ) end # The dynamics of the model is defined through the `AbstractStateSpaceModel` interface: function SSMProblems.transition!!(rng::AbstractRNG, model::NonLinearTimeSeries) return rand(rng, f₀(model.θ)) end function SSMProblems.transition!!( rng::AbstractRNG, model::NonLinearTimeSeries, state::Float64, step::Int ) return rand(rng, f(model.θ, state, step)) end function SSMProblems.emission_logdensity( modeL::NonLinearTimeSeries, state::Float64, step::Int ) return logpdf(g(model.θ, state, step), model.observations[step]) end function SSMProblems.transition_logdensity( model::NonLinearTimeSeries, prev_state, current_state, step ) return logpdf(f(model.θ, prev_state, step), current_state) end # We need to tell AdvancedPS when to stop the execution of the model # TODO AdvancedPS.isdone(::NonLinearTimeSeries, step) = step > Tₘ # Here we use the particle gibbs kernel without adaptive resampling. model = NonLinearTimeSeries(y, θ₀) pg = AdvancedPS.PG(Nₚ, 1.0) chains = sample(rng, model, pg, Nₛ; progress=false); #md nothing #hide particles = hcat([chain.trajectory.model.X for chain in chains]...) # Concat all sampled states mean_trajectory = mean(particles; dims=2); #md nothing #hide # We can now plot all the generated traces. # Beyond the last few timesteps all the trajectories collapse into one. Using the ancestor updating step can help with the degeneracy problem, as we show below. scatter( particles[:, 1:50]; label=false, opacity=0.5, color=:black, xlabel="t", ylabel="state" ) plot!(x; color=:darkorange, label="Original Trajectory") plot!(mean_trajectory; color=:dodgerblue, label="Mean trajectory", opacity=0.9) # We can also check the mixing as defined in the Gaussian State Space model example. As seen on the # scatter plot above, we are mostly left with a single trajectory before timestep 150. The orange # bar is the optimal mixing rate for the number of particles we use. plot_update_rate(update_rate(particles, Nₛ)[:, 1], Nₚ) # Let's see if ancestor sampling can help with the degeneracy problem. We use the same number of particles, but replace the sampler with PGAS. pgas = AdvancedPS.PGAS(Nₚ) chains = sample(rng, model, pgas, Nₛ; progress=false); particles = hcat([chain.trajectory.model.X for chain in chains]...); mean_trajectory = mean(particles; dims=2); # The ancestor sampling has helped with the degeneracy problem and we now have a much more diverse set of trajectories, also at earlier time periods. scatter( particles[:, 1:50]; label=false, opacity=0.5, color=:black, xlabel="t", ylabel="state" ) plot!(x; color=:darkorange, label="Original Trajectory") plot!(mean_trajectory; color=:dodgerblue, label="Mean trajectory", opacity=0.9) # The update rate is now much higher throughout time. plot_update_rate(update_rate(particles, Nₛ)[:, 1], Nₚ)
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
6889
module AdvancedPSLibtaskExt if isdefined(Base, :get_extension) using AdvancedPS: AdvancedPS using AdvancedPS: Random123 using AdvancedPS: AbstractMCMC using AdvancedPS: Random using AdvancedPS: Distributions using Libtask: Libtask else using ..AdvancedPS: AdvancedPS using ..AdvancedPS: Random123 using ..AdvancedPS: AbstractMCMC using ..AdvancedPS: Random using ..AdvancedPS: Distributions using ..Libtask: Libtask end """ LibtaskModel{F} State wrapper to hold `Libtask.CTask` model initiated from `f`. """ function AdvancedPS.LibtaskModel( f::AdvancedPS.AbstractGenericModel, rng::Random.AbstractRNG, args... ) # Changed the API, need to take care of the RNG properly return AdvancedPS.LibtaskModel( f, Libtask.TapedTask( f, rng, args...; deepcopy_types=Union{AdvancedPS.TracedRNG,typeof(f)} ), ) end """ copy(model::AdvancedPS.LibtaskModel) The task is copied (forked) and the inner model is deepcopied. """ function Base.copy(model::AdvancedPS.LibtaskModel) return AdvancedPS.LibtaskModel(deepcopy(model.f), copy(model.ctask)) end const LibtaskTrace{R} = AdvancedPS.Trace{<:AdvancedPS.LibtaskModel,R} function AdvancedPS.Trace( model::AdvancedPS.AbstractGenericModel, rng::Random.AbstractRNG, args... ) return AdvancedPS.Trace(AdvancedPS.LibtaskModel(model, rng, args...), rng) end # step to the next observe statement and # return the log probability of the transition (or nothing if done) function AdvancedPS.advance!(t::LibtaskTrace, isref::Bool=false) isref ? AdvancedPS.load_state!(t.rng) : AdvancedPS.save_state!(t.rng) AdvancedPS.inc_counter!(t.rng) # Move to next step return Libtask.consume(t.model.ctask) end # create a backward reference in task_local_storage function AdvancedPS.addreference!(task::Task, trace::LibtaskTrace) if task.storage === nothing task.storage = IdDict() end task.storage[:__trace] = trace return task end function AdvancedPS.update_rng!(trace::LibtaskTrace) rng, = trace.model.ctask.args trace.rng = rng return trace end # Task copying version of fork for Trace. function AdvancedPS.fork(trace::LibtaskTrace, isref::Bool=false) newtrace = copy(trace) AdvancedPS.update_rng!(newtrace) isref && AdvancedPS.delete_retained!(newtrace.model.f) isref && delete_seeds!(newtrace) # add backward reference AdvancedPS.addreference!(newtrace.model.ctask.task, newtrace) return newtrace end # PG requires keeping all randomness for the reference particle # Create new task and copy randomness function AdvancedPS.forkr(trace::LibtaskTrace) newf = AdvancedPS.reset_model(trace.model.f) Random123.set_counter!(trace.rng, 1) ctask = Libtask.TapedTask( newf, trace.rng; deepcopy_types=Union{AdvancedPS.TracedRNG,typeof(trace.model.f)} ) new_tapedmodel = AdvancedPS.LibtaskModel(newf, ctask) # add backward reference newtrace = AdvancedPS.Trace(new_tapedmodel, trace.rng) AdvancedPS.addreference!(ctask.task, newtrace) AdvancedPS.gen_refseed!(newtrace) return newtrace end AdvancedPS.update_ref!(::LibtaskTrace) = nothing """ observe(dist::Distribution, x) Observe sample `x` from distribution `dist` and yield its log-likelihood value. """ function AdvancedPS.observe(dist::Distributions.Distribution, x) return Libtask.produce(Distributions.loglikelihood(dist, x)) end """ AbstractMCMC interface. We need libtask to sample from arbitrary callable AbstractModel """ function AbstractMCMC.step( rng::Random.AbstractRNG, model::AdvancedPS.AbstractGenericModel, sampler::AdvancedPS.PG, state::Union{AdvancedPS.PGState,Nothing}=nothing; kwargs..., ) # Create a new set of particles. nparticles = sampler.nparticles isref = !isnothing(state) traces = map(1:nparticles) do i if i == nparticles && isref # Create reference trajectory. AdvancedPS.forkr(copy(state.trajectory)) else trng = AdvancedPS.TracedRNG() trace = AdvancedPS.Trace(deepcopy(model), trng) AdvancedPS.addreference!(trace.model.ctask.task, trace) # TODO: Do we need it here ? trace end end particles = AdvancedPS.ParticleContainer(traces, AdvancedPS.TracedRNG(), rng) # Perform a particle sweep. reference = isref ? particles.vals[nparticles] : nothing logevidence = AdvancedPS.sweep!(rng, particles, sampler.resampler, sampler, reference) # Pick a particle to be retained. newtrajectory = rand(rng, particles) replayed = AdvancedPS.replay(newtrajectory) return AdvancedPS.PGSample(replayed.model.f, logevidence), AdvancedPS.PGState(newtrajectory) end function AbstractMCMC.sample( model::AdvancedPS.AbstractGenericModel, sampler::AdvancedPS.SMC; kwargs... ) return AbstractMCMC.sample(Random.GLOBAL_RNG, model, sampler; kwargs...) end function AbstractMCMC.sample( rng::Random.AbstractRNG, model::AdvancedPS.AbstractGenericModel, sampler::AdvancedPS.SMC; kwargs..., ) if !isempty(kwargs) @warn "keyword arguments $(keys(kwargs)) are not supported by `SMC`" end traces = map(1:(sampler.nparticles)) do i trng = AdvancedPS.TracedRNG() trace = AdvancedPS.Trace(deepcopy(model), trng) AdvancedPS.addreference!(trace.model.ctask.task, trace) # Do we need it here ? trace end # Create a set of particles. particles = AdvancedPS.ParticleContainer(traces, AdvancedPS.TracedRNG(), rng) # Perform particle sweep. logevidence = AdvancedPS.sweep!(rng, particles, sampler.resampler, sampler) replayed = map(particle -> AdvancedPS.replay(particle).model.f, particles.vals) return AdvancedPS.SMCSample( collect(replayed), AdvancedPS.getweights(particles), logevidence ) end """ replay(particle::AdvancedPS.Particle) Rewind the particle and regenerate all sampled values. This ensures that the returned trajectory has the correct values. """ function AdvancedPS.replay(particle::AdvancedPS.Particle) trng = deepcopy(particle.rng) Random123.set_counter!(trng.rng, 0) trng.count = 1 trace = AdvancedPS.Trace( AdvancedPS.LibtaskModel(deepcopy(particle.model.f), trng), trng ) score = AdvancedPS.advance!(trace, true) while !isnothing(score) score = AdvancedPS.advance!(trace, true) end return trace end """ delete_seeds!(particle::Particle) Truncate the seed history from the `particle` rng. When forking the reference Particle we need to keep the seeds up to the current model iteration but generate new seeds and random values afterward. """ function delete_seeds!(particle::AdvancedPS.Particle) return particle.rng.keys = particle.rng.keys[1:(particle.rng.count - 1)] end end
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
951
module AdvancedPS using AbstractMCMC: AbstractMCMC using Distributions: Distributions using Random: Random using StatsFuns: StatsFuns using Random123: Random123 using SSMProblems: SSMProblems abstract type AbstractParticleModel <: AbstractMCMC.AbstractModel end abstract type AbstractParticleSampler <: AbstractMCMC.AbstractSampler end """ Abstract type for an abstract model formulated in the state space form """ abstract type AbstractStateSpaceModel <: AbstractParticleModel end abstract type AbstractGenericModel <: AbstractParticleModel end include("resampling.jl") include("rng.jl") include("model.jl") include("container.jl") include("smc.jl") include("pgas.jl") if !isdefined(Base, :get_extension) using Requires end @static if !isdefined(Base, :get_extension) function __init__() @require Libtask = "6f1fad26-d15e-5dc8-ae53-837a1d7b8c9f" include( "../ext/AdvancedPSLibtaskExt.jl" ) end end end
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
10806
""" Data structure for particle filters - `effectiveSampleSize(pc :: ParticleContainer)`: Return the effective sample size of the particles in `pc` """ mutable struct ParticleContainer{T<:Particle,R<:TracedRNG} "Particles." vals::Vector{T} "Unnormalized logarithmic weights." logWs::Vector{Float64} "Traced RNG to replay the resampling step" rng::R end function ParticleContainer(particles::Vector{<:Particle}) return ParticleContainer(particles, zeros(length(particles)), TracedRNG()) end function ParticleContainer(particles::Vector{<:Particle}, rng::TracedRNG) return ParticleContainer(particles, zeros(length(particles)), rng) end function ParticleContainer( particles::Vector{<:Particle}, trng::TracedRNG, rng::Random.AbstractRNG ) pc = ParticleContainer(particles, trng) return seed_from_rng!(pc, rng) end Base.collect(pc::ParticleContainer) = pc.vals Base.length(pc::ParticleContainer) = length(pc.vals) Base.@propagate_inbounds Base.getindex(pc::ParticleContainer, i::Int) = pc.vals[i] function Base.rand(rng::Random.AbstractRNG, pc::ParticleContainer) index = randcat(rng, getweights(pc)) return pc[index] end # registers a new x-particle in the container function Base.push!(pc::ParticleContainer, p::Particle) push!(pc.vals, p) push!(pc.logWs, 0.0) return pc end # clones a theta-particle function Base.copy(pc::ParticleContainer) # fork particles vals = eltype(pc.vals)[fork(p) for p in pc.vals] # copy weights logWs = copy(pc.logWs) # Copy rng and states rng = copy(pc.rng) return ParticleContainer(vals, logWs, rng) end """ update_ref!(particle::Trace, pc::ParticleContainer) Update reference trajectory. Defaults to `nothing` """ function update_ref!( particle::Trace, pc::ParticleContainer, sampler::T ) where {T<:AbstractMCMC.AbstractSampler} return nothing end """ reset_logweights!(pc::ParticleContainer) Reset all unnormalized logarithmic weights to zero. """ function reset_logweights!(pc::ParticleContainer) fill!(pc.logWs, 0.0) return pc end """ increase_logweight!(pc::ParticleContainer, i::Int, x) Increase the unnormalized logarithmic weight of the `i`th particle with `x`. """ function increase_logweight!(pc::ParticleContainer, i, logw) pc.logWs[i] += logw return pc end """ getweights(pc::ParticleContainer) Compute the normalized weights of the particles. """ getweights(pc::ParticleContainer) = StatsFuns.softmax(pc.logWs) """ getweight(pc::ParticleContainer, i) Compute the normalized weight of the `i`th particle. """ getweight(pc::ParticleContainer, i) = exp(pc.logWs[i] - logZ(pc)) """ logZ(pc::ParticleContainer) Return the logarithm of the normalizing constant of the unnormalized logarithmic weights. """ logZ(pc::ParticleContainer) = StatsFuns.logsumexp(pc.logWs) """ effectiveSampleSize(pc::ParticleContainer) Compute the effective sample size ``1 / ∑ wᵢ²``, where ``wᵢ```are the normalized weights. """ function effectiveSampleSize(pc::ParticleContainer) Ws = getweights(pc) return inv(sum(abs2, Ws)) end """ update_keys!(pc::ParticleContainer) Create new unique keys for the particles in the ParticleContainer """ function update_keys!(pc::ParticleContainer, ref::Union{Particle,Nothing}=nothing) # Update keys to new particle ids nparticles = length(pc) n = ref === nothing ? nparticles : nparticles - 1 for i in 1:n pi = pc.vals[i] k = split(state(pi.rng.rng)) Random.seed!(pi.rng, k[1]) end return nothing end """ seed_from_rng!(pc::ParticleContainer, rng::Random.AbstractRNG, ref::Union{Particle,Nothing}=nothing) Set seeds of particle rng from user-provided `rng` """ function seed_from_rng!( pc::ParticleContainer{T,<:TracedRNG{R,N,<:Random123.AbstractR123{I}}}, rng::Random.AbstractRNG, ref::Union{Particle,Nothing}=nothing, ) where {T,R,N,I} n = length(pc.vals) nseeds = isnothing(ref) ? n : n - 1 sampler = Random.Sampler(rng, I) for i in 1:nseeds subrng = pc.vals[i].rng Random.seed!(subrng, gen_seed(rng, subrng, sampler)) end Random.seed!(pc.rng, gen_seed(rng, pc.rng, sampler)) return pc end """ resample_propagate!(rng, pc::ParticleContainer[, randcat = resample_systematic, ref = nothing; weights = getweights(pc)]) Resample and propagate the particles in `pc`. Function `randcat` is used for sampling ancestor indices from the categorical distribution of the particle `weights`. For Particle Gibbs sampling, one can provide a reference particle `ref` that is ensured to survive the resampling step. """ function resample_propagate!( ::Random.AbstractRNG, pc::ParticleContainer, sampler::T, randcat=DEFAULT_RESAMPLER, ref::Union{Particle,Nothing}=nothing; weights=getweights(pc), ) where {T<:AbstractMCMC.AbstractSampler} # sample ancestor indices n = length(pc) nresamples = ref === nothing ? n : n - 1 indx = randcat(pc.rng, weights, nresamples) # count number of children for each particle num_children = zeros(Int, n) @inbounds for i in indx num_children[i] += 1 end # fork particles particles = collect(pc) children = similar(particles) j = 0 @inbounds for i in 1:n ni = num_children[i] if ni > 0 # fork first child pi = particles[i] isref = pi === ref p = isref ? fork(pi, isref) : pi key = isref ? safe_get_refseed(ref.rng) : state(p.rng.rng) # Pick up the alternative rng stream if using the reference particle nsplits = isref ? ni + 1 : ni # We need one more seed to refresh the alternative rng stream seeds = split(key, nsplits) isref && safe_set_refseed!(ref.rng, seeds[end]) # Refresh the alternative rng stream Random.seed!(p.rng, seeds[1]) children[j += 1] = p # fork additional children for k in 2:ni part = fork(p, isref) Random.seed!(part.rng, seeds[k]) children[j += 1] = part end end end if ref !== nothing # Insert the retained particle. This is based on the replaying trick for efficiency # reasons. If we implement PG using task copying, we need to store Nx * T particles! update_ref!(ref, pc, sampler) @inbounds children[n] = ref end # replace particles and log weights in the container with new particles and weights pc.vals = children reset_logweights!(pc) return pc end function resample_propagate!( rng::Random.AbstractRNG, pc::ParticleContainer, sampler::T, resampler::ResampleWithESSThreshold, ref::Union{Particle,Nothing}=nothing; weights=getweights(pc), ) where {T<:AbstractMCMC.AbstractSampler} # Compute the effective sample size ``1 / ∑ wᵢ²`` with normalized weights ``wᵢ`` ess = inv(sum(abs2, weights)) if ess ≤ resampler.threshold * length(pc) resample_propagate!(rng, pc, sampler, resampler.resampler, ref; weights=weights) else update_keys!(pc, ref) end return pc end """ reweight!(pc::ParticleContainer) Check if the final time step is reached, and otherwise reweight the particles by considering the next observation. """ function reweight!(pc::ParticleContainer, ref::Union{Particle,Nothing}=nothing) n = length(pc) particles = collect(pc) numdone = 0 for i in 1:n p = particles[i] # Obtain ``\\log p(yₜ | y₁, …, yₜ₋₁, x₁, …, xₜ, θ₁, …, θₜ)``, or `nothing` if the # the execution of the model is finished. # Here ``yᵢ`` are observations, ``xᵢ`` variables of the particle filter, and # ``θᵢ`` are variables of other samplers. isref = p === ref score = advance!(p, isref) # SSMProblems.transition!! if score === nothing numdone += 1 else # Increase the unnormalized logarithmic weights. increase_logweight!(pc, i, score) # Reset the accumulator of the log probability in the model so that we can # accumulate log probabilities of variables of other samplers until the next # observation. reset_logprob!(p) end end # Check if all particles are propagated to the final time point. numdone == n && return true # The posterior for models with random number of observations is not well-defined. if numdone != 0 error( "mis-aligned execution traces: # particles = ", n, " # completed trajectories = ", numdone, ". Please make sure the number of observations is NOT random.", ) end return false end """ sweep!(rng, pc::ParticleContainer, resampler) Perform a particle sweep and return an unbiased estimate of the log evidence. The resampling steps use the given `resampler`. # Reference Del Moral, P., Doucet, A., & Jasra, A. (2006). Sequential monte carlo samplers. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 68(3), 411-436. """ function sweep!( rng::Random.AbstractRNG, pc::ParticleContainer, resampler, sampler::AbstractMCMC.AbstractSampler, ref::Union{Particle,Nothing}=nothing, ) # Initial step: # Resample and propagate particles. resample_propagate!(rng, pc, sampler, resampler, ref) # Compute the current normalizing constant ``Z₀`` of the unnormalized logarithmic # weights. # Usually it is equal to the number of particles in the beginning but this # implementation covers also the unlikely case of a particle container that is # initialized with non-zero logarithmic weights. logZ0 = logZ(pc) # Reweight the particles by including the first observation ``y₁``. isdone = reweight!(pc, ref) # Compute the normalizing constant ``Z₁`` after reweighting. logZ1 = logZ(pc) # Compute the estimate of the log evidence ``\\log p(y₁)``. logevidence = logZ1 - logZ0 # For observations ``y₂, …, yₜ``: while !isdone # Resample and propagate particles. resample_propagate!(rng, pc, sampler, resampler, ref) # Compute the current normalizing constant ``Z₀`` of the unnormalized logarithmic # weights. logZ0 = logZ(pc) # Reweight the particles by including the next observation ``yₜ``. isdone = reweight!(pc, ref) # Compute the normalizing constant ``Z₁`` after reweighting. logZ1 = logZ(pc) # Compute the estimate of the log evidence ``\\log p(y₁, …, yₜ)``. logevidence += logZ1 - logZ0 end return logevidence end
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
1365
""" Trace{F,R} """ mutable struct Trace{F,R} model::F rng::R end const Particle = Trace const SSMTrace{R} = Trace{<:SSMProblems.AbstractStateSpaceModel,R} const GenericTrace{R} = Trace{<:AbstractGenericModel,R} reset_logprob!(::AdvancedPS.Particle) = nothing reset_model(f) = deepcopy(f) delete_retained!(f) = nothing """ isdone(model::SSMProblems.AbstractStateSpaceModel, step) Returns `true` if we reached the end of the model execution """ function isdone end """ copy(trace::Trace) Copy a trace. The `TracedRNG` is deep-copied. The inner model is shallow-copied. """ Base.copy(trace::Trace) = Trace(copy(trace.model), deepcopy(trace.rng)) """ gen_refseed!(particle::Particle) Generate a new seed for the reference particle. """ function gen_refseed!(particle::Particle) seed = split(state(particle.rng.rng), 1) return safe_set_refseed!(particle.rng, seed[1]) end # A few internal functions used in the Libtask extension. Since it is not possible to access objects defined # in an extension, we just define dummy in the main module and implement them in the extension. function observe end function replay end function addreference! end current_trace() = current_task().storage[:__trace] # We need this one to be visible outside of the extension for dispatching (Turing.jl). struct LibtaskModel{F,T} f::F ctask::T end
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
3577
""" previous_state(trace::SSMTrace) Return `Xₜ₋₁` or `nothing` from `model` """ function previous_state(trace::SSMTrace) return trace.model.X[current_step(trace) - 1] end function past_idx(trace::SSMTrace) return 1:(current_step(trace) - 1) end """ current_step(model::AbstractStateSpaceModel) Return current model step """ current_step(trace::SSMTrace) = trace.rng.count """ transition_logweight(model::AbstractStateSpaceModel, x) Get the log weight of the transition from previous state of `model` to `x` """ function transition_logweight(particle::SSMTrace, x) score = SSMProblems.transition_logdensity( particle.model, particle.model.X[current_step(particle) - 2], x, current_step(particle) - 1, ) return score end """ get_ancestor_logweights(pc::ParticleContainer{F,R}, x) where {F<:SSMTrace,R} Get the ancestor log weights for each particle in `pc` """ function get_ancestor_logweights(pc::ParticleContainer{<:SSMTrace}, x, weights) nparticles = length(pc.vals) logweights = map(1:nparticles) do i transition_logweight(pc.vals[i], x) + weights[i] end return logweights end """ advance!(particle::SSMTrace, isref::Bool=false) Return the log-probability of the transition nothing if done """ function advance!(particle::SSMTrace, isref::Bool=false) isref ? load_state!(particle.rng) : save_state!(particle.rng) model = particle.model running_step = current_step(particle) isdone(model, running_step) && return nothing if !isref if running_step == 1 new_state = SSMProblems.transition!!(particle.rng, model) else current_state = model.X[running_step - 1] new_state = SSMProblems.transition!!( particle.rng, model, current_state, running_step ) end else new_state = model.X[running_step] # We need the current state from the reference particle end score = SSMProblems.emission_logdensity(model, new_state, running_step) # accept transition !isref && push!(model.X, new_state) inc_counter!(particle.rng) # Increase rng counter, we use it as the model `time` index instead of handling two distinct counters return score end function truncate!(particle::SSMTrace) model = particle.model idx = past_idx(particle) model.X = model.X[idx] particle.rng.keys = particle.rng.keys[idx] return model end function fork(particle::SSMTrace, isref::Bool) model = deepcopy(particle.model) new_particle = Trace(model, deepcopy(particle.rng)) isref && truncate!(new_particle) # Forget the rest of the reference trajectory return new_particle end function forkr(particle::SSMTrace) Random123.set_counter!(particle.rng, 1) newtrace = Trace(deepcopy(particle.model), deepcopy(particle.rng)) gen_refseed!(newtrace) return newtrace end function update_ref!(ref::SSMTrace, pc::ParticleContainer{<:SSMTrace}, sampler::PGAS) current_step(ref) <= 2 && return nothing # At the beginning of step + 1 since we start at 1 isdone(ref.model, current_step(ref)) && return nothing ancestor_weights = get_ancestor_logweights( pc, ref.model.X[current_step(ref) - 1], pc.logWs ) norm_weights = StatsFuns.softmax(ancestor_weights) ancestor_index = rand(pc.rng, Distributions.Categorical(norm_weights)) ancestor = pc.vals[ancestor_index] idx = past_idx(ref) ref.model.X[idx] = ancestor.model.X[idx] return ref.rng.keys[idx] = ancestor.rng.keys[idx] end
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
5914
#### #### Resampling schemes for particle filters #### # Some references # - http://arxiv.org/pdf/1301.4019.pdf # - http://people.isy.liu.se/rt/schon/Publications/HolSG2006.pdf # Code adapted from: http://uk.mathworks.com/matlabcentral/fileexchange/24968-resampling-methods-for-particle-filtering # More stable, faster version of rand(Categorical) function randcat(rng::Random.AbstractRNG, p::AbstractVector{<:Real}) T = eltype(p) r = rand(rng, T) cp = p[1] s = 1 n = length(p) while cp <= r && s < n @inbounds cp += p[s += 1] end return s end """ resample_multinomial(rng, weights, n) Return a vector of `n` samples `x₁`, ..., `xₙ` from the numbers 1, ..., `length(weights)`, generated by multinomial resampling. The new indices are sampled from the multinomial distribution with probabilities equal to `weights` """ function resample_multinomial( rng::Random.AbstractRNG, w::AbstractVector{<:Real}, num_particles::Integer=length(w) ) return rand(rng, Distributions.sampler(Distributions.Categorical(w)), num_particles) end """ resample_residual(rng, weights, n) Return a vector of `n` samples `x₁`, ..., `xₙ` from the numbers 1, ..., `length(weights)`, generated by residual resampling. In residual resampling we start by duplicating all the particles whose weight is bigger than `1/n`. We copy each of these particles ``N_i`` times where ``N_i = \\left\\lfloor n w_i \\right\\rfloor`` We then duplicate the ``R_t = n - \\sum_i N_i`` missing particles using multinomial resampling with the residual weights given by: ``\\tilde{w} = w_i - \\frac{N_i}{N}`` """ function resample_residual( rng::Random.AbstractRNG, w::AbstractVector{<:Real}, num_particles::Integer=length(weights), ) # Pre-allocate array for resampled particles indices = Vector{Int}(undef, num_particles) # deterministic assignment residuals = similar(w) i = 1 @inbounds for j in 1:length(w) x = num_particles * w[j] floor_x = floor(Int, x) for k in 1:floor_x indices[i] = j i += 1 end residuals[j] = x - floor_x end # sampling from residuals if i <= num_particles residuals ./= sum(residuals) rand!(rng, Distributions.Categorical(residuals), view(indices, i:num_particles)) end return indices end """ resample_stratified(rng, weights, n) Return a vector of `n` samples `x₁`, ..., `xₙ` from the numbers 1, ..., `length(weights)`, generated by stratified resampling. In stratified resampling `n` ordered random numbers `u₁`, ..., `uₙ` are generated, where ``uₖ \\sim U[(k - 1) / n, k / n)``. Based on these numbers the samples `x₁`, ..., `xₙ` are selected according to the multinomial distribution defined by the normalized `weights`, i.e., `xᵢ = j` if and only if ``uᵢ \\in \\left[\\sum_{s=1}^{j-1} weights_{s}, \\sum_{s=1}^{j} weights_{s}\\right)``. """ function resample_stratified( rng::Random.AbstractRNG, weights::AbstractVector{<:Real}, n::Integer=length(weights) ) # check input m = length(weights) m > 0 || error("weight vector is empty") # pre-calculations @inbounds v = n * weights[1] # generate all samples samples = Array{Int}(undef, n) sample = 1 @inbounds for i in 1:n # sample next `u` (scaled by `n`) u = oftype(v, i - 1 + rand(rng)) # as long as we have not found the next sample while v < u # increase and check the sample sample += 1 sample > m && error("sample could not be selected (are the weights normalized?)") # update the cumulative sum of weights (scaled by `n`) v += n * weights[sample] end # save the next sample samples[i] = sample end return samples end """ resample_systematic(rng, weights, n) Return a vector of `n` samples `x₁`, ..., `xₙ` from the numbers 1, ..., `length(weights)`, generated by systematic resampling. In systematic resampling a random number ``u \\sim U[0, 1)`` is used to generate `n` ordered numbers `u₁`, ..., `uₙ` where ``uₖ = (u + k − 1) / n``. Based on these numbers the samples `x₁`, ..., `xₙ` are selected according to the multinomial distribution defined by the normalized `weights`, i.e., `xᵢ = j` if and only if ``uᵢ \\in \\left[\\sum_{s=1}^{j-1} weights_{s}, \\sum_{s=1}^{j} weights_{s}\\right)`` """ function resample_systematic( rng::Random.AbstractRNG, weights::AbstractVector{<:Real}, n::Integer=length(weights) ) # check input m = length(weights) m > 0 || error("weight vector is empty") # pre-calculations @inbounds v = n * weights[1] u = oftype(v, rand(rng)) # find all samples samples = Array{Int}(undef, n) sample = 1 @inbounds for i in 1:n # as long as we have not found the next sample while v < u # increase and check the sample sample += 1 sample > m && error("sample could not be selected (are the weights normalized?)") # update the cumulative sum of weights (scaled by `n`) v += n * weights[sample] end # save the next sample samples[i] = sample # update `u` u += one(u) end return samples end const DEFAULT_RESAMPLER = resample_systematic """ ResampleWithESSThreshold{R,T<:Real} Perform resampling using `R` if the effective sample size is below `T`. By default we use `resample_systematic` with a threshold of 0.5 """ struct ResampleWithESSThreshold{R,T<:Real} resampler::R threshold::T end function ResampleWithESSThreshold(resampler=DEFAULT_RESAMPLER) return ResampleWithESSThreshold(resampler, 0.5) end function ResampleWithESSThreshold(threshold::T) where {T<:Real} return ResampleWithESSThreshold(DEFAULT_RESAMPLER, threshold) end
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
3691
# Default RNG type for when nothing is specified const _BASE_RNG = Random123.Philox2x # Rng with state bigger than 1 are broken because of Split """ TracedRNG{R,N,T} Wrapped random number generator from Random123 to keep track of random streams during model evaluation """ mutable struct TracedRNG{R,N,T<:Random123.AbstractR123} <: Random.AbstractRNG "Model step counter" count::Int "Inner RNG" rng::T "Array of keys" keys::Array{R,N} "Reference particle alternative seed" refseed::Union{R,Nothing} end """ TracedRNG(r::Random123.AbstractR123=AdvancedPS._BASE_RNG()) Create a `TracedRNG` with `r` as the inner RNG. """ function TracedRNG(r::Random123.AbstractR123=_BASE_RNG()) Random123.set_counter!(r, 0) return TracedRNG(1, r, Random123.seed_type(r)[], nothing) end # Connect to the Random API Random.rng_native_52(rng::TracedRNG) = Random.rng_native_52(rng.rng) Base.rand(rng::TracedRNG, ::Type{T}) where {T} = Base.rand(rng.rng, T) """ split(key::Integer, n::Integer=1) Split `key` into `n` new keys """ function split(key::Integer, n::Integer=1) T = typeof(key) # Make sure the type of `key` is consistent on W32 and W64 systems. return T[hash(key, i) for i in UInt(1):UInt(n)] end """ load_state!(r::TracedRNG) Load state from current model iteration. Random streams are now replayed """ function load_state!(rng::TracedRNG) key = rng.keys[rng.count] Random.seed!(rng.rng, key) return Random123.set_counter!(rng.rng, 0) end """ Random.seed!(rng::TracedRNG, key) Set key and counter of inner rng in `rng` to `key` and the running model step to 0 """ function Random.seed!(rng::TracedRNG, key) Random.seed!(rng.rng, key) return Random123.set_counter!(rng.rng, 0) end """ gen_seed(rng::Random.AbstractRNG, subrng::TracedRNG, sampler::Random.Sampler) Generate a `seed` for the subrng based on top-level `rng` and `sampler` """ function gen_seed(rng::Random.AbstractRNG, ::TracedRNG{<:Integer}, sampler::Random.Sampler) return rand(rng, sampler) end function gen_seed( rng::Random.AbstractRNG, ::TracedRNG{<:NTuple{N}}, sampler::Random.Sampler ) where {N} return Tuple(rand(rng, sampler, N)) end """ save_state!(r::TracedRNG) Add current key of the inner rng in `r` to `keys`. """ function save_state!(r::TracedRNG) return push!(r.keys, state(r.rng)) end state(rng::Random123.Philox2x) = rng.key state(rng::Random123.Philox4x) = (rng.key1, rng.key2) function Base.copy(rng::TracedRNG) return TracedRNG(rng.count, copy(rng.rng), deepcopy(rng.keys), rng.refseed) end # Add an extra seed to the reference particle keys array to use as an alternative stream # (we don't need to tack this one) # # We have to be careful when spliting the reference particle. # Since we don't know the seed tree from the previous SMC run we cannot reuse any of the intermediate seed # in the TracedRNG container. We might collide with a previous seed and the children particle would collapse # to the reference particle. A solution to solve this is to have an extra stream attached to the reference particle # that we only use to seed the children of the reference particle. # safe_set_refseed!(rng::TracedRNG{R}, seed::R) where {R} = rng.refseed = seed safe_get_refseed(rng::TracedRNG) = rng.refseed """ set_counter!(r::TracedRNG, n::Integer) Set the counter of the inner rng in `r`, used to keep track of the current model step """ Random123.set_counter!(r::TracedRNG, n::Integer) = r.count = n """ inc_counter!(r::TracedRNG, n::Integer=1) Increase the model step counter by `n` """ inc_counter!(r::TracedRNG, n::Integer=1) = r.count += n function update_rng! end
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
3780
struct SMC{R} <: AbstractParticleSampler nparticles::Int resampler::R end """ SMC(n[, resampler = ResampleWithESSThreshold()]) SMC(n, [resampler = resample_systematic, ]threshold) Create a sequential Monte Carlo (SMC) sampler with `n` particles. If the algorithm for the resampling step is not specified explicitly, systematic resampling is performed if the estimated effective sample size per particle drops below 0.5. """ SMC(nparticles::Int) = SMC(nparticles, ResampleWithESSThreshold()) # Convenient constructors with ESS threshold function SMC(nparticles::Int, resampler, threshold::Real) return SMC(nparticles, ResampleWithESSThreshold(resampler, threshold)) end SMC(nparticles::Int, threshold::Real) = SMC(nparticles, DEFAULT_RESAMPLER, threshold) struct SMCSample{P,W,L} trajectories::P weights::W logevidence::L end function AbstractMCMC.sample( model::SSMProblems.AbstractStateSpaceModel, sampler::SMC; kwargs... ) return AbstractMCMC.sample(Random.GLOBAL_RNG, model, sampler; kwargs...) end function AbstractMCMC.sample( rng::Random.AbstractRNG, model::SSMProblems.AbstractStateSpaceModel, sampler::SMC; kwargs..., ) if !isempty(kwargs) @warn "keyword arguments $(keys(kwargs)) are not supported by `SMC`" end traces = map(1:(sampler.nparticles)) do i trng = TracedRNG() Trace(deepcopy(model), trng) end # Create a set of particles. particles = ParticleContainer(traces, TracedRNG(), rng) # Perform particle sweep. logevidence = sweep!(rng, particles, sampler.resampler, sampler) return SMCSample(collect(particles), getweights(particles), logevidence) end struct PG{R} <: AbstractParticleSampler """Number of particles.""" nparticles::Int """Resampling algorithm.""" resampler::R end """ PG(n, [resampler = ResampleWithESSThreshold()]) PG(n, [resampler = resample_systematic, ]threshold) Create a Particle Gibbs sampler with `n` particles. If the algorithm for the resampling step is not specified explicitly, systematic resampling is performed if the estimated effective sample size per particle drops below 0.5. """ PG(nparticles::Int) = PG(nparticles, ResampleWithESSThreshold()) # Convenient constructors with ESS threshold function PG(nparticles::Int, resampler, threshold::Real) return PG(nparticles, ResampleWithESSThreshold(resampler, threshold)) end PG(nparticles::Int, threshold::Real) = PG(nparticles, DEFAULT_RESAMPLER, threshold) struct PGState{T} trajectory::T end struct PGSample{T,L} trajectory::T logevidence::L end struct PGAS{R} <: AbstractParticleSampler """Number of particles.""" nparticles::Int """Resampling algorithm.""" resampler::R end PGAS(nparticles::Int) = PGAS(nparticles, ResampleWithESSThreshold(1.0)) function AbstractMCMC.step( rng::Random.AbstractRNG, model::SSMProblems.AbstractStateSpaceModel, sampler::Union{PGAS,PG}, state::Union{PGState,Nothing}=nothing; kwargs..., ) # Create a new set of particles. nparticles = sampler.nparticles isref = !isnothing(state) traces = map(1:nparticles) do i if i == nparticles && isref # Create reference trajectory. forkr(deepcopy(state.trajectory)) else Trace(deepcopy(model), TracedRNG()) end end particles = ParticleContainer(traces, TracedRNG(), rng) # Perform a particle sweep. reference = isref ? particles.vals[nparticles] : nothing logevidence = sweep!(rng, particles, sampler.resampler, sampler, reference) # Pick a particle to be retained. newtrajectory = rand(particles.rng, particles) return PGSample(newtrajectory, logevidence), PGState(newtrajectory) end
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
7238
@testset "container.jl" begin # Since the extension would hide the low level function call API mutable struct LogPModel{T} <: SSMProblems.AbstractStateSpaceModel logp::T X::Array{T} end SSMProblems.transition!!(rng::AbstractRNG, model::LogPModel) = rand(rng, Uniform()) function SSMProblems.transition!!(rng::AbstractRNG, model::LogPModel, state, step) return rand(rng, Uniform()) end SSMProblems.emission_logdensity(model::LogPModel, state, step) = model.logp AdvancedPS.isdone(model::LogPModel, step) = false @testset "copy particle container" begin pc = AdvancedPS.ParticleContainer(AdvancedPS.Trace[]) newpc = copy(pc) @test newpc.logWs == pc.logWs @test typeof(pc) === typeof(newpc) end @testset "particle container" begin # Create particle container. logps = [0.0, -1.0, -2.0] particles = map(logps) do logp trng = AdvancedPS.TracedRNG() AdvancedPS.Trace(LogPModel(logp, []), trng) end pc = AdvancedPS.ParticleContainer(particles) # Push! pc2 = deepcopy(pc) particle = AdvancedPS.Trace(LogPModel(0, []), AdvancedPS.TracedRNG()) push!(pc2, particle) @test length(pc2.vals) == 4 @test pc2.logWs ≈ zeros(4) # Initial state. @test pc.logWs == zeros(3) @test AdvancedPS.getweights(pc) == fill(1 / 3, 3) @test all(AdvancedPS.getweight(pc, i) == 1 / 3 for i in 1:3) @test AdvancedPS.logZ(pc) ≈ log(3) @test AdvancedPS.effectiveSampleSize(pc) == 3 # Reweight particles. AdvancedPS.reweight!(pc) @test pc.logWs == logps @test AdvancedPS.getweights(pc) ≈ exp.(logps) ./ sum(exp, logps) @test all( AdvancedPS.getweight(pc, i) ≈ exp(logps[i]) / sum(exp, logps) for i in 1:3 ) @test AdvancedPS.logZ(pc) ≈ log(sum(exp, logps)) # Reweight particles. AdvancedPS.reweight!(pc) @test pc.logWs == 2 .* logps @test AdvancedPS.getweights(pc) == exp.(2 .* logps) ./ sum(exp, 2 .* logps) @test all( AdvancedPS.getweight(pc, i) ≈ exp(2 * logps[i]) / sum(exp, 2 .* logps) for i in 1:3 ) @test AdvancedPS.logZ(pc) ≈ log(sum(exp, 2 .* logps)) # Resample and propagate particles with reference particle particles_ref = map(logps) do logp trng = AdvancedPS.TracedRNG() AdvancedPS.Trace(LogPModel(logp, []), trng) end pc_ref = AdvancedPS.ParticleContainer(particles_ref) selected = particles_ref[end] # Replicate life cycle of the reference particle AdvancedPS.advance!(selected) ref = AdvancedPS.forkr(selected) pc_ref.vals[end] = ref sampler = AdvancedPS.PG(length(logps)) AdvancedPS.resample_propagate!( Random.GLOBAL_RNG, pc_ref, sampler, AdvancedPS.resample_systematic, ref ) @test pc_ref.logWs == zeros(3) @test AdvancedPS.getweights(pc_ref) == fill(1 / 3, 3) @test all(AdvancedPS.getweight(pc_ref, i) == 1 / 3 for i in 1:3) @test AdvancedPS.logZ(pc_ref) ≈ log(3) @test AdvancedPS.effectiveSampleSize(pc_ref) == 3 @test pc_ref.vals[end] === particles_ref[end] # Resample and propagate particles. AdvancedPS.resample_propagate!(Random.GLOBAL_RNG, pc, sampler) @test pc.logWs == zeros(3) @test AdvancedPS.getweights(pc) == fill(1 / 3, 3) @test all(AdvancedPS.getweight(pc, i) == 1 / 3 for i in 1:3) @test AdvancedPS.logZ(pc) ≈ log(3) @test AdvancedPS.effectiveSampleSize(pc) == 3 # Reweight particles. AdvancedPS.reweight!(pc) @test pc.logWs ⊆ logps @test AdvancedPS.getweights(pc) == exp.(pc.logWs) ./ sum(exp, pc.logWs) @test all( AdvancedPS.getweight(pc, i) ≈ exp(pc.logWs[i]) / sum(exp, pc.logWs) for i in 1:3 ) @test AdvancedPS.logZ(pc) ≈ log(sum(exp, pc.logWs)) # Increase unnormalized logarithmic weights. logws = copy(pc.logWs) AdvancedPS.increase_logweight!(pc, 2, 1.41) @test pc.logWs == logws + [0, 1.41, 0] # Reset unnormalized logarithmic weights. logws = pc.logWs AdvancedPS.reset_logweights!(pc) @test pc.logWs === logws @test all(iszero, pc.logWs) end @testset "trace" begin struct Model <: AdvancedPS.AbstractGenericModel val::Ref{Int} end function (model::Model)(rng::Random.AbstractRNG) t = [0] while true model.val[] += 1 produce(t[1]) model.val[] += 1 t[1] += 1 end end # Test task copy version of trace trng = AdvancedPS.TracedRNG() tr = AdvancedPS.Trace(Model(Ref(0)), trng) consume(tr.model.ctask) consume(tr.model.ctask) a = AdvancedPS.fork(tr) consume(a.model.ctask) consume(a.model.ctask) @test consume(tr.model.ctask) == 2 @test consume(a.model.ctask) == 4 end @testset "current trace" begin struct TaskIdModel <: AdvancedPS.AbstractGenericModel end function (model::TaskIdModel)(rng::Random.AbstractRNG) # Just print the task it's running in id = objectid(AdvancedPS.current_trace()) return Libtask.produce(id) end trace = AdvancedPS.Trace(TaskIdModel(), AdvancedPS.TracedRNG()) AdvancedPS.addreference!(trace.model.ctask.task, trace) @test AdvancedPS.advance!(trace, false) === objectid(trace) end @testset "seed container" begin seed = 1 n = 3 rng = Random.MersenneTwister(seed) particles = map(1:n) do _ trng = AdvancedPS.TracedRNG() AdvancedPS.Trace(LogPModel(1.0, []), trng) end pc = AdvancedPS.ParticleContainer(particles, AdvancedPS.TracedRNG()) AdvancedPS.seed_from_rng!(pc, rng) old_seeds = vcat([part.rng.rng.key for part in pc.vals], [pc.rng.rng.key]) Random.seed!(rng, seed) AdvancedPS.seed_from_rng!(pc, rng) new_seeds = vcat([part.rng.rng.key for part in pc.vals], [pc.rng.rng.key]) # Check if we reset the seeds properly @test old_seeds ≈ new_seeds Random.seed!(rng, 2) AdvancedPS.seed_from_rng!(pc, rng, pc.vals[n]) ref_seeds = vcat([part.rng.rng.key for part in pc.vals], [pc.rng.rng.key]) # Dont reset reference particle @test ref_seeds[n] ≈ new_seeds[n] end @testset "seed history" begin # Test task copy version of trace trng = AdvancedPS.TracedRNG() tr = AdvancedPS.Trace(LogPModel(1.0, []), trng) AdvancedPS.advance!(tr) AdvancedPS.advance!(tr) AdvancedPS.advance!(tr) ref = AdvancedPS.forkr(tr) # Ref particle new_tr = AdvancedPS.fork(ref, true) @test length(new_tr.rng.keys) == 0 AdvancedPS.advance!(ref) child = AdvancedPS.fork(ref, true) @test length(child.rng.keys) == 1 end end
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
3418
""" Unit tests for the validity of the SMC algorithms included in this package. We test each SMC algorithm on a one-dimensional linear Gaussian state space model for which an analytic filtering distribution can be computed using the Kalman filter provided by the `Kalman.jl` package. The validity of the algorithm is tested by comparing the final estimated filtering distribution ground truth using a one-sided Kolmogorov-Smirnov test. """ using DynamicIterators using GaussianDistributions using HypothesisTests using Kalman function test_algorithm(rng, algorithm, model, N_SAMPLES, Xf) chains = sample(rng, model, algorithm, N_SAMPLES; progress=false) particles = hcat([chain.trajectory.model.X for chain in chains]...) final_particles = particles[:, end] test = ExactOneSampleKSTest(final_particles, Normal(Xf.x[end].μ, sqrt(Xf.x[end].Σ))) return pvalue(test) end @testset "linear-gaussian.jl" begin T = 3 N_PARTICLES = 100 N_SAMPLES = 50 # Model dynamics a = 0.5 b = 0.2 q = 0.1 E = LinearEvolution(a, Gaussian(b, q)) H = 1.0 R = 0.1 Obs = LinearObservationModel(H, R) x0 = 0.0 P0 = 1.0 G0 = Gaussian(x0, P0) M = LinearStateSpaceModel(E, Obs) O = LinearObservation(E, H, R) # Simulate from model rng = StableRNG(1234) initial = rand(rng, StateObs(G0, M.obs)) trajectory = trace(DynamicIterators.Sampled(M, rng), 1 => initial, endtime(T)) y_pairs = collect(t => y for (t, (x, y)) in pairs(trajectory)) ys = [y for (t, (x, y)) in pairs(trajectory)] # Ground truth smoothing Xf, ll = kalmanfilter(M, 1 => G0, y_pairs) # Define AdvancedPS model mutable struct LinearGaussianParams a::Float64 b::Float64 q::Float64 h::Float64 r::Float64 x0::Float64 p0::Float64 end mutable struct LinearGaussianModel <: SSMProblems.AbstractStateSpaceModel X::Vector{Float64} observations::Vector{Float64} θ::LinearGaussianParams function LinearGaussianModel(y::Vector{Float64}, θ::LinearGaussianParams) return new(Vector{Float64}(), y, θ) end end function SSMProblems.transition!!(rng::AbstractRNG, model::LinearGaussianModel) return rand(rng, Normal(model.θ.x0, model.θ.p0)) end function SSMProblems.transition!!( rng::AbstractRNG, model::LinearGaussianModel, state, step ) return rand(rng, Normal(model.θ.a * state + model.θ.b, model.θ.q)) end function SSMProblems.transition_logdensity( model::LinearGaussianModel, prev_state, current_state, step ) return logpdf(Normal(model.θ.a * prev_state + model.θ.b, model.θ.q), current_state) end function SSMProblems.emission_logdensity(model::LinearGaussianModel, state, step) return logpdf(Normal(model.θ.h * state, model.θ.r), model.observations[step]) end AdvancedPS.isdone(::LinearGaussianModel, step) = step > T params = LinearGaussianParams(a, b, q, H, R, x0, P0) model = LinearGaussianModel(ys, params) @testset "PGAS" begin pgas = AdvancedPS.PGAS(N_PARTICLES) p = test_algorithm(rng, pgas, model, N_SAMPLES, Xf) @test p > 0.05 end @testset "PG" begin pg = AdvancedPS.PG(N_PARTICLES) p = test_algorithm(rng, pg, model, N_SAMPLES, Xf) @test p > 0.05 end end
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
4324
@testset "pgas.jl" begin mutable struct Params a::Float64 q::Float64 r::Float64 end mutable struct BaseModel <: SSMProblems.AbstractStateSpaceModel X::Vector{Float64} θ::Params BaseModel(params::Params) = new(Vector{Float64}(), params) end function SSMProblems.transition!!(rng::AbstractRNG, model::BaseModel) return rand(rng, Normal(0, model.θ.q)) end function SSMProblems.transition!!(rng::AbstractRNG, model::BaseModel, state, step) return rand(rng, Normal(model.θ.a * state, model.θ.q)) end function SSMProblems.emission_logdensity(model::BaseModel, state, step) return logpdf(Distributions.Normal(state, model.θ.r), 0) end function SSMProblems.transition_logdensity( model::BaseModel, prev_state, current_state, step ) return logpdf(Normal(model.θ.a * prev_state, model.θ.q), current_state) end AdvancedPS.isdone(::BaseModel, step) = step > 3 @testset "fork reference" begin model = BaseModel(Params(0.9, 0.32, 1)) part = AdvancedPS.Trace(model, AdvancedPS.TracedRNG()) AdvancedPS.advance!(part) AdvancedPS.advance!(part) AdvancedPS.advance!(part) @test length(part.model.X) == 3 trajectory = deepcopy(part.model.X) ref = AdvancedPS.forkr(part) @test all(trajectory .≈ ref.model.X) AdvancedPS.advance!(ref) new_part = AdvancedPS.fork(ref, true) @test length(new_part.model.X) == 1 @test new_part.model.X[1] ≈ ref.model.X[1] end @testset "update reference" begin base_rng = Random.MersenneTwister(31) particles = [ AdvancedPS.Trace(BaseModel(Params(0.9, 0.31, 1)), AdvancedPS.TracedRNG()) for _ in 1:3 ] sampler = AdvancedPS.PGAS(3) resampler = AdvancedPS.ResampleWithESSThreshold(1.0) part = particles[3] AdvancedPS.advance!(part) AdvancedPS.advance!(part) AdvancedPS.advance!(part) ref = AdvancedPS.forkr(part) particles[3] = ref pc = AdvancedPS.ParticleContainer(particles, AdvancedPS.TracedRNG(), base_rng) AdvancedPS.reweight!(pc, ref) AdvancedPS.resample_propagate!(base_rng, pc, sampler, resampler, ref) AdvancedPS.reweight!(pc, ref) pc.logWs = [-Inf, 0, -Inf] # Force ancestor update to second particle AdvancedPS.resample_propagate!(base_rng, pc, sampler, resampler, ref) AdvancedPS.reweight!(pc, ref) @test all(pc.vals[2].model.X[1:2] .≈ ref.model.X[1:2]) terminal_values = [part.model.X[3] for part in pc.vals] @test length(Set(terminal_values)) == 3 # All distinct end @testset "constructor" begin sampler = AdvancedPS.PGAS(10) @test sampler.nparticles == 10 @test sampler.resampler === AdvancedPS.ResampleWithESSThreshold(1.0) # adaptive PG-AS ? end @testset "rng stability" begin model = BaseModel(Params(0.9, 0.32, 1)) seed = 10 rng = Random.MersenneTwister(seed) for sampler in [AdvancedPS.PGAS(10), AdvancedPS.PG(10)] Random.seed!(rng, seed) chain1 = sample(rng, model, sampler, 10) vals1 = hcat([chain.trajectory.model.X for chain in chain1]...) Random.seed!(rng, seed) chain2 = sample(rng, model, sampler, 10) vals2 = hcat([chain.trajectory.model.X for chain in chain2]...) # TODO: Create proper chains @test vals1 ≈ vals2 end # Test stability for SMC sampler = AdvancedPS.SMC(10) Random.seed!(rng, seed) chain1 = sample(rng, model, sampler) vals1 = hcat([trace.model.X for trace in chain1.trajectories]...) Random.seed!(rng, seed) chain2 = sample(rng, model, sampler) vals2 = hcat([trace.model.X for trace in chain2.trajectories]...) @test vals1 ≈ vals2 end # Smoke test mostly @testset "smc sampler" begin model = BaseModel(Params(0.9, 0.32, 1)) npart = 10 sampler = AdvancedPS.SMC(npart) chains = sample(model, sampler) @test length(chains.trajectories) == npart @test length(chains.trajectories[1].model.X) == 3 end end
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
776
@testset "resampling.jl" begin D = [0.3, 0.4, 0.3] num_samples = Int(1e6) rng = Random.GLOBAL_RNG resSystematic = AdvancedPS.resample_systematic(rng, D, num_samples) resStratified = AdvancedPS.resample_stratified(rng, D, num_samples) resMultinomial = AdvancedPS.resample_multinomial(rng, D, num_samples) resResidual = AdvancedPS.resample_residual(rng, D, num_samples) AdvancedPS.resample_systematic(rng, D) @test sum(resSystematic .== 2) ≈ (num_samples * 0.4) atol = 1e-3 * num_samples @test sum(resStratified .== 2) ≈ (num_samples * 0.4) atol = 1e-3 * num_samples @test sum(resMultinomial .== 2) ≈ (num_samples * 0.4) atol = 1e-2 * num_samples @test sum(resResidual .== 2) ≈ (num_samples * 0.4) atol = 1e-2 * num_samples end
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
604
@testset "rng.jl" begin @testset "sample distribution" begin rng = AdvancedPS.TracedRNG() vns = rand(rng, Distributions.Normal()) AdvancedPS.save_state!(rng) rand(rng, Distributions.Normal()) AdvancedPS.load_state!(rng) new_vns = rand(rng, Distributions.Normal()) @test new_vns ≈ vns end @testset "split" begin rng = AdvancedPS.TracedRNG() key = rng.rng.key new_key, = AdvancedPS.split(key, 1) @test key ≠ new_key Random.seed!(rng, new_key) @test rng.rng.key === new_key end end
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
613
using AdvancedPS using AbstractMCMC using Distributions using Libtask using Random using StableRNGs using Test using SSMProblems @testset "AdvancedPS.jl" begin @testset "Resampling tests" begin include("resampling.jl") end @testset "Container tests" begin include("container.jl") end @testset "SMC and PG tests" begin include("smc.jl") end @testset "RNG tests" begin include("rng.jl") end @testset "PG-AS" begin include("pgas.jl") end @testset "Linear Gaussian SSM tests" begin include("linear-gaussian.jl") end end
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
code
5569
@testset "smc.jl" begin @testset "SMC constructor" begin sampler = AdvancedPS.SMC(10) @test sampler.nparticles == 10 @test sampler.resampler == AdvancedPS.ResampleWithESSThreshold() sampler = AdvancedPS.SMC(15, 0.6) @test sampler.nparticles == 15 @test sampler.resampler === AdvancedPS.ResampleWithESSThreshold(AdvancedPS.resample_systematic, 0.6) sampler = AdvancedPS.SMC(20, AdvancedPS.resample_multinomial, 0.6) @test sampler.nparticles == 20 @test sampler.resampler === AdvancedPS.ResampleWithESSThreshold(AdvancedPS.resample_multinomial, 0.6) sampler = AdvancedPS.SMC(25, AdvancedPS.resample_systematic) @test sampler.nparticles == 25 @test sampler.resampler === AdvancedPS.resample_systematic end # Smoke tests @testset "models" begin mutable struct NormalModel <: AdvancedPS.AbstractGenericModel a::Float64 b::Float64 NormalModel() = new() end function (m::NormalModel)(rng::Random.AbstractRNG) # First latent variable. m.a = a = rand(rng, Normal(4, 5)) # First observation. AdvancedPS.observe(Normal(a, 2), 3) # Second latent variable. m.b = b = rand(rng, Normal(a, 1)) # Second observation. return AdvancedPS.observe(Normal(b, 2), 1.5) end sample(NormalModel(), AdvancedPS.SMC(100)) # failing test mutable struct FailSMCModel <: AdvancedPS.AbstractGenericModel a::Float64 b::Float64 FailSMCModel() = new() end function (m::FailSMCModel)(rng::Random.AbstractRNG) m.a = a = rand(rng, Normal(4, 5)) m.b = b = rand(rng, Normal(a, 1)) if a >= 4 AdvancedPS.observe(Normal(b, 2), 1.5) end end @test_throws ErrorException sample(FailSMCModel(), AdvancedPS.SMC(100)) end @testset "logevidence" begin Random.seed!(100) mutable struct TestModel <: AdvancedPS.AbstractGenericModel a::Float64 x::Bool b::Float64 c::Float64 TestModel() = new() end function (m::TestModel)(rng::Random.AbstractRNG) # First hidden variables. m.a = rand(rng, Normal(0, 1)) m.x = x = rand(rng, Bernoulli(1)) m.b = rand(rng, Gamma(2, 3)) # First observation. AdvancedPS.observe(Bernoulli(x / 2), 1) # Second hidden variable. m.c = rand(rng, Beta()) # Second observation. return AdvancedPS.observe(Bernoulli(x / 2), 0) end chains_smc = sample(TestModel(), AdvancedPS.SMC(100)) @test all(isone(particle.x) for particle in chains_smc.trajectories) @test chains_smc.logevidence ≈ -2 * log(2) end @testset "PG constructor" begin sampler = AdvancedPS.PG(10) @test sampler.nparticles == 10 @test sampler.resampler == AdvancedPS.ResampleWithESSThreshold() sampler = AdvancedPS.PG(60, 0.6) @test sampler.nparticles == 60 @test sampler.resampler === AdvancedPS.ResampleWithESSThreshold(AdvancedPS.resample_systematic, 0.6) sampler = AdvancedPS.PG(80, AdvancedPS.resample_multinomial, 0.6) @test sampler.nparticles == 80 @test sampler.resampler === AdvancedPS.ResampleWithESSThreshold(AdvancedPS.resample_multinomial, 0.6) sampler = AdvancedPS.PG(100, AdvancedPS.resample_systematic) @test sampler.nparticles == 100 @test sampler.resampler === AdvancedPS.resample_systematic end @testset "logevidence" begin Random.seed!(100) mutable struct TestModel <: AdvancedPS.AbstractGenericModel a::Float64 x::Bool b::Float64 c::Float64 TestModel() = new() end function (m::TestModel)(rng::Random.AbstractRNG) # First hidden variables. m.a = rand(rng, Normal(0, 1)) m.x = x = rand(rng, Bernoulli(1)) m.b = rand(rng, Gamma(2, 3)) # First observation. AdvancedPS.observe(Bernoulli(x / 2), 1) # Second hidden variable. m.c = rand(rng, Beta()) # Second observation. return AdvancedPS.observe(Bernoulli(x / 2), 0) end chains_pg = sample(TestModel(), AdvancedPS.PG(10), 100) @test all(isone(p.trajectory.x) for p in chains_pg) @test mean(x.logevidence for x in chains_pg) ≈ -2 * log(2) atol = 0.01 end @testset "Replay reference" begin mutable struct DummyModel <: AdvancedPS.AbstractGenericModel a::Float64 b::Float64 DummyModel() = new() end function (m::DummyModel)(rng) m.a = rand(rng, Normal()) AdvancedPS.observe(Normal(), m.a) m.b = rand(rng, Normal()) return AdvancedPS.observe(Normal(), m.b) end pg = AdvancedPS.PG(1) first, second = sample(DummyModel(), pg, 2) first_model = first.trajectory second_model = second.trajectory # Single Particle - must be replaying @test first_model.a ≈ second_model.a @test first_model.b ≈ second_model.b @test first.logevidence ≈ second.logevidence end end
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
docs
2390
# AdvancedPS [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://turinglang.github.io/AdvancedPS.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://turinglang.github.io/AdvancedPS.jl/dev) [![Build Status](https://github.com/TuringLang/AdvancedPS.jl/workflows/CI/badge.svg?branch=master)](https://github.com/TuringLang/AdvancedPS.jl/actions?query=workflow%3ACI%20branch%3Amaster) [![Coverage](https://codecov.io/gh/TuringLang/AdvancedPS.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/TuringLang/AdvancedPS.jl) [![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle) AdvancedPS provides an efficient implementation of common particle-based Monte Carlo samplers using the [AbstractMCMC](https://github.com/TuringLang/AbstractMCMC.jl) interface. The package also relies on [Libtask](https://github.com/TuringLang/Libtask.jl) for task manipulation. AdvancedPS is part of the [Turing](https://turinglang.org/stable/) ecosystem. Detailed examples are available in the [documentation](https://turinglang.github.io/AdvancedPS.jl/dev/) ### Reference 1. Doucet, Arnaud, and Adam M. Johansen. "A tutorial on particle filtering and smoothing: Fifteen years later." Handbook of nonlinear filtering 12, no. 656-704 (2009): 3. 2. Andrieu, Christophe, Arnaud Doucet, and Roman Holenstein. "Particle Markov chain Monte Carlo methods." Journal of the Royal Statistical Society: Series B (Statistical Methodology) 72, no. 3 (2010): 269-342. 3. Tripuraneni, Nilesh, Shixiang Shane Gu, Hong Ge, and Zoubin Ghahramani. "Particle Gibbs for infinite hidden Markov models." In Advances in Neural Information Processing Systems, pp. 2395-2403. 2015. 4. Lindsten, Fredrik, Michael I. Jordan, and Thomas B. Schön. "Particle Gibbs with ancestor sampling." The Journal of Machine Learning Research 15, no. 1 (2014): 2145-2184. 5. Pitt, Michael K., and Neil Shephard. "Filtering via simulation: Auxiliary particle filters." Journal of the American Statistical Association 94, no. 446 (1999): 590-599. 6. Doucet, Arnaud, Nando de Freitas, and Neil Gordon. "Sequential Monte Carlo Methods in Practice." 7. Del Moral, Pierre, Arnaud Doucet, and Ajay Jasra. "Sequential Monte Carlo samplers." Journal of the Royal Statistical Society: Series B (Statistical Methodology) 68, no. 3 (2006): 411-436.
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
docs
3333
# API ## Samplers AdvancedPS introduces a few samplers extending [AbstractMCMC](https://github.com/TuringLang/AbstractMCMC.jl). The `sample` method expects a custom type that subtypes `AbstractMCMC.AbstractModel`. The available samplers are listed below: ### SMC ```@docs AdvancedPS.SMC ``` The SMC sampler populates a set of particles in a [`AdvancedPS.ParticleContainer`](@ref) and performs a [`AdvancedPS.sweep!`](@ref) which propagates the particles and provides an estimation of the log-evidence ```julia sampler = SMC(nparticles) chains = sample(model, sampler) ``` ### Particle Gibbs ```@docs AdvancedPS.PG ``` The Particle Gibbs introduced in [^2] runs a sequence of conditional SMC steps where a pre-selected particle, the reference particle, is replayed and propagated through the SMC step. ```julia sampler = PG(nparticles) chains = sample(model, sampler, nchains) ``` For more detailed examples please refer to the [Examples](@ref) page. ## Resampling AdvancedPS implements adaptive resampling for both [`AdvancedPS.PG`](@ref) and [`AdvancedPS.SMC`](@ref). The following resampling schemes are implemented: ```@docs AdvancedPS.resample_multinomial AdvancedPS.resample_residual AdvancedPS.resample_stratified AdvancedPS.resample_systematic ``` Each of these schemes is wrapped in a [`AdvancedPS.ResampleWithESSThreshold`](@ref) struct to trigger a resampling step whenever the ESS is below a certain threshold. ```@docs AdvancedPS.ResampleWithESSThreshold ``` ## RNG AdvancedPS replays the individual trajectories instead of storing the intermediate values. This way we can build efficient samplers. However in order to replay the trajectories we need to reproduce most of the random numbers generated during the execution of the program while also generating diverging traces after each resampling step. To solve these two issues AdvancedPS uses counter-based RNG introduced in [^1] and widely used in large parallel systems see [StochasticDifferentialEquations](https://github.com/SciML/StochasticDiffEq.jl) or [JAX](https://jax.readthedocs.io/en/latest/jax-101/05-random-numbers.html?highlight=random) for other implementations. Under the hood AdvancedPS is using [Random123](https://github.com/JuliaRandom/Random123.jl) for the generators. Using counter-based RNG allows us to split generators thus creating new independent random streams. These generators are also wrapped in a [`AdvancedPS.TracedRNG`](@ref) type. The `TracedRNG` keeps track of the keys generated at every `split` and can be reset to replay random streams. ```@docs AdvancedPS.TracedRNG AdvancedPS.split AdvancedPS.load_state! AdvancedPS.save_state! ``` ## Internals ### Particle Sweep ```@docs AdvancedPS.ParticleContainer AdvancedPS.sweep! ``` [^1]: John K. Salmon, Mark A. Moraes, Ron O. Dror, and David E. Shaw. 2011. Parallel random numbers: as easy as 1, 2, 3. In Proceedings of 2011 International Conference for High Performance Computing, Networking, Storage and Analysis (SC '11). Association for Computing Machinery, New York, NY, USA, Article 16, 1–12. DOI:https://doi.org/10.1145/2063384.2063405 [^2]: Andrieu, Christophe, Arnaud Doucet, and Roman Holenstein. "Particle Markov chain Monte Carlo methods." Journal of the Royal Statistical Society: Series B (Statistical Methodology) 72, no. 3 (2010): 269-342.
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
docs
106
# Examples The following pages walk you through some examples using AdvancedPS and the Turing ecosystem.
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
docs
398
# AdvancedPS: Particle Samplers for Julia This is a lightweight package that implements particle based Monte Carlo algorithms for the [Turing](https://turing.ml/stable/) ecosystem. ### Installing from Julia To install the package, use the following command inside the Julia REPL: ```julia using Pkg Pkg.add("AdvancedPS") ``` To load the package, use the command: ```julia using AdvancedPS ```
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
docs
77
# Examples The examples in this directory are stored in Literate.jl format.
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git
[ "MIT" ]
0.6.0
5dcd3de7e7346f48739256e71a86d0f96690b8c8
docs
448
### Guidelines Extensions allow you to take advantage of any structure your models might have. API: - `AdvancedPS.Trace`: Trace container for your custom model type - `AdvancedPS.advance!`: Emits logdensity - `AdvancedPS.fork`: Fork particle and create independent child - `AdvancedPS.forkr`: Fork particle while keeping generated randomness, used for the reference particle in particle MCMC - `AdvancedPS.update_ref!`: Update reference particle
AdvancedPS
https://github.com/TuringLang/AdvancedPS.jl.git