licenses
listlengths
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
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
2292
#RSDeltaSigma: Array manipulations #------------------------------------------------------------------------------- #==Converters to make input data uniform ===============================================================================# """`conv2seriesmatrix2D(x)` Ensure we have a 2D matrix representing series data (Vector->2×N Array) """ conv2seriesmatrix2D(x::T) where T = throw(ErrorException("Cannot convert $T to a \"series data matrix\"")) conv2seriesmatrix2D(x::AbstractVector) = collect(x') conv2seriesmatrix2D(x::Array{T, 2}) where T<:Number = x #Assume format is ok. #==Array/Vector padding ===============================================================================# """`y = padl(x, n, val)` Pad a matrix x on the left to length n with value val(0) The empty matrix is assumed to be have 1 empty row """ padl(x, n::Int, val=0) = [ val*ones(eltype(x), max(1,size(x,1)), n-size(x,2)) x ] padl(x::Vector, n::Int, val=0) = vcat(val*ones(eltype(x), n-length(x)), x) """`y = padr(x, n, val)` Pad a matrix x on the right to length n with value val(0) The empty matrix is assumed to be have 1 empty row """ padr(x, n::Int, val=0) = [ x val*ones(eltype(x), max(1,size(x,1)), n-size(x,2)) ] padr(x::Vector, n::Int, val=0) = vcat(x, val*ones(eltype(x), n-length(x))) """`y = padt(x, n, val)` Pad a matrix x on the top to length n with value val(0) The empty matrix is assumed to be have 1 empty column """ padt(x, n::Int, val=0) = [ val*ones(eltype(x), n-size(x,1), max(1,size(x,2))); x ] padt(x::Vector, n::Int, val=0) = padl(x,n,val) """`y = padb(x, n, val)` Pad a matrix x on the bottom to length n with value val(0) The empty matrix is assumed to be have 1 empty column """ padb(x, n::Int, val=0) = [ x ; val*ones(eltype(x), n-size(x,1), max(1,size(x,2))) ] padb(x::Vector, n::Int, val=0) = padr(x,n,val) #==Quadrature <--> real ===============================================================================# """`A = mapQtoR(Z)` Convert a quadrature matrix into its real equivalent. Each element in `Z` is represented by a 2x2 matrix in `A`: - `z -> [x -y; y x]` """ function mapQtoR(Z) A = zeros(2*size(Z)) A[1:2:end,1:2:end] = real(Z) A[2:2:end,2:2:end] = real(Z) A[1:2:end,2:2:end] = -imag(Z) A[2:2:end,1:2:end] = imag(Z) return A end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
4871
#RSDeltaSigma: Base functionnality and types #------------------------------------------------------------------------------- #=Info - Circumvent using ControlSystems.jl for now by specifying custom zpk() functions & data structures. =# #==Type definitions ===============================================================================# const IndexRange = UnitRange{Int64} const MISSINGARG = ArgumentError("Missing Argument") #Type used to dispatch on a symbol & minimize namespace pollution: struct DS{Symbol}; end; #Dispatchable symbol DS(v::Symbol) = DS{v}() """`ZPKData` Custom structure to store zpk data. """ mutable struct ZPKData z p k Ts::Real end function _zpk(z, p, k, Ts::Number=0) ZPKData(z, p, k, Ts) end function _zpkdata(d::ZPKData, idx=0) accesspz(v::Array, idx) = v[idx] accesspz(v::Array{T}, idx) where T<:Number = (if idx != 1; throw("no data at given index"); end; return v) accessk(v::Array, idx) = v[idx] accessk(v::Number, idx) = (if idx != 1; throw("no data at given index"); end; return v) (z, p, k) = (d.z, d.p, d.k) if idx > 0 z = accesspz(z, idx) p = accesspz(p, idx) k = accessk(k, idx) end return (z, p, k) end abstract type AbstractDSM; end """`RealDSM(;order=3, OSR=16, M=1, f0=0, form=:CRFB, Hinf=1.5, opt=1)` Describe a real-valued (not quadrature) ΔΣ modulator. # Inputs - `order`: order of the modulator - `OSR`: oversampling ratio - `M`: Number of quantizer steps (`M=nlev-1`) - `f0`: center frequency (1->fs) - `form`: - `H_inf`: maximum NTF gain - `opt`: flag for optimized zeros - `--> opt=0` -> not optimized, - `--> opt=1` -> optimized, - `--> opt=2` -> optimized with at least one zero at band-center, - `--> opt=3` -> optimized zeros (Requires MATLAB6 and Optimization Toolbox), - `--> opt=[z]` -> zero locations in complex form (TODO?) """ struct RealDSM <: AbstractDSM order::Int OSR::Int M::Int #Num steps f0::Float64 form::Symbol Hinf::Float64 opt::Int end RealDSM(;order=3, OSR=16, M=1, f0=0, form=:CRFB, Hinf=1.5, opt=1) = RealDSM(order, OSR, M, f0, form, Hinf, opt) struct QuadratureDSM <: AbstractDSM order::Int OSR::Int M::Int #Num steps f0::Float64 form::Symbol NG::Int ING::Int end QuadratureDSM(;order=4, OSR=32, M=1, f0=1/16, form=:PFB, NG=-50, ING=-10) = QuadratureDSM(order, OSR, M, f0, form, NG, ING) """`CTDTPrefilters` The mixed CT/DT prefilters which form the samples. """ mutable struct CTDTPrefilters Hs #TODO Type should be transfer function Hz #TODO Type should be transfer function end #==Accessors ===============================================================================# isquadrature(::RealDSM) = false isquadrature(::QuadratureDSM) = true #==Helper functions ===============================================================================# function orderinfo(order::Int) order2 = div(order, 2) Δodd = mod(order, 2) isodd = order > 2*order2 return (order2, isodd, Δodd) end orderinfo(dsm::AbstractDSM) = orderinfo(dsm.order) #Sort roots such that real values show up first function realfirst(a) epstol = 100 #Index of real roots: Δmin = epstol*eps.(abs.(a)) #Threshold for numerical error ireal = abs.(imag.(a)) .< Δmin areal = real.(a[ireal]) #Clean up real roots acplx = a[.!ireal] #complex pairs return vcat(sort(areal), acplx) #Sort roots end #==Basic frequency calculations/defaults ===============================================================================# """`(f1, f2) = ds_f1f2(;OSR=64, f0=0, iscomplex=0)` Deprecated. Use `default_fband()` instead. # See also: [`default_fband`](@ref), [`default_ftest`](@ref) """ function ds_f1f2(;OSR::Int=64, f0::Float64=0, iscomplex::Bool=false) local f1, f2 if iscomplex f1 = f0-0.5/OSR f2 = f0+0.5/OSR else if f0>0.25/OSR f1 = f0-0.25/OSR f2 = f0+0.25/OSR else f1 = 0 f2 = 0.5/OSR end end return (f1, f2) end """`[f1, f2] = default_fband(dsm)` Compute a default application band (normalized frequency limits) for the given ΔΣ modulator. # See also: [`default_ftest`](@ref) """ default_fband default_fband(OSR::Int; f0::Float64=0.0, quadrature::Bool=false) = collect(ds_f1f2(OSR=OSR, f0=f0, iscomplex=quadrature)) #Vector form default_fband(dsm::RealDSM) = default_fband(dsm.OSR, f0=dsm.f0, quadrature=false) default_fband(dsm::QuadratureDSM) = default_fband(dsm.OSR, f0=dsm.f0, quadrature=false) """`default_ftest(dsm)` Compute a default test (normalized) frequency for the given ΔΣ modulator. # See also: [`default_fband`](@ref) """ default_ftest function default_ftest(OSR::Int; f0::Float64=0, quadrature::Bool=false) if quadrature return ftest = 0.15/OSR else return (0==f0) ? 0.15/OSR : f0 + 0.08/OSR end end default_ftest(dsm::RealDSM) = default_ftest(dsm.OSR, f0=dsm.f0, quadrature=false) default_ftest(dsm::QuadratureDSM) = default_ftest(dsm.OSR, f0=dsm.f0, quadrature=true) #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
1846
#RSDeltaSigmaPort: Calculate frequency spectrum information #------------------------------------------------------------------------------- #==calcSpecInfo ===============================================================================# """ Calculate spectrum information # Inputs - sig: Signal to analyze - NTF: Noise transfer function to compute theoretical noise spectrum - fband: Specifies (𝑓min, 𝑓max) band limits of the modulator (normalized 𝑓) - ftest: test frequency (normalized 𝑓) - M: Number of quantizer steps (nlev = M+1) - quadrature: """ function calcSpecInfo(sig, NTF, fband, ftest::Float64; M::Int=1, quadrature::Bool=false) sig = conv2seriesmatrix2D(sig) R, N = size(sig) if R!=1 throw("FIXME: replicate hann window rows for R>0") end iband = round(Int, minimum(fband)*N):round(Int, maximum(fband)*N) itest = round(Int, ftest*N) Δ = 2 NBW = 1.5/N spec0 = fft(applywnd(sig, ds_hann(N)))/(M*N/4) local 𝑓, specdB, SNR, ePSD if !quadrature 𝑓pts = div(N,2)+1 #Only need half the spectrum for display purposes 𝑓 = range(0, stop=0.5, length=𝑓pts) specdB = dbv.(spec0[1:𝑓pts]) # @show iband .+ 1, itest-minimum(iband) SNR = calculateSNR(spec0[iband .+ 1], itest-minimum(iband)) #Compute Expected power spetral density: # Sqq = 4 * evalTF(NTF ,exp.(2π*j*𝑓)).^2 / (3*M^2) Snn = abs.(evalTF(NTF, exp.(2π*j*𝑓))).^2 * 2*2/12 * (Δ/M)^2 ePSD = dbp.(Snn*NBW) else throw("Not implemented") end return (freq=𝑓, spec0=spec0, specdB=specdB, ePSD=ePSD, SNR=SNR, NBW=NBW, NTF=NTF, M=M, iband=iband, itest=itest ) end function calcSpecInfo(sig, dsm::RealDSM, fband=nothing, ftest=nothing) if isnothing(fband); fband = default_fband(dsm); end if isnothing(ftest); ftest = default_ftest(dsm); end NTF = synthesizeNTF(dsm) return calcSpecInfo(sig, NTF, fband, ftest, M=dsm.M, false) end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
655
#RSDeltaSigmaPort: Dataset manipulations #------------------------------------------------------------------------------- #Validate x, y pair simple vectors function validatexy_vec(x, y) sz = size(x); sz_y = size(y) if sz != sz_y throw("x & y sizes do not match") elseif length(sz) > 1 throw("Dimension of data too large (Simple vector expected).") end return end #Validate x, y pair for 1 parameter sweep (2D array) function validatexy_1param(x, y) sz = size(x); sz_y = size(y) if sz != sz_y throw("x & y sizes do not match") elseif length(sz) > 2 throw("Dimension of data too large (2D arrays expected).") end return end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
11593
#RSDeltaSigma: designHBF() algorithm #------------------------------------------------------------------------------- #=IMPORTANT designHBF6() (a version that doesn't need firpm()) no longer exists in the source code used in this port. It actually just copies designHBF7(). =# #==Helper functions ===============================================================================# """`F1 = evalF1(f1, z, phi)` Calculate the values of the F1 filter (tranformed prototype filter) of a Saramaki HBF at the given points. """ function evalF1(f1, z) F1 = 0.5 for i = 1:length(f1) F1 = F1 .+ f1[i] * z .^ (2*i-1) end return F1 end evalF1(f1, z, phi::Float64) = evalF1(f1, z/phi) """`F0 = evalF0(f1, z, phi)` Calculate the values of the F0 (prototype) filter of a Saramaki HBF at the given points. """ evalF0(f1, z, phi::Float64) = evalF1( f1, 0.5*(z + 1 ./ z), phi ) #==frespHBF() ===============================================================================# function _frespHBF(f, f1, f2, fp, calcripples::Bool) Npts = length(f) w = 2*pi*f z = exp.(j*w) cos_w = real.(z) n2 = length(f2) F2 = zeros(size(w)) for i = 1:n2 F2 = F2 + f2[i]*cos.(w*(2*i-1)) end F2 = F2*2 mag = evalF1(f1, F2) pbr = sbr = nothing if calcripples passband = 1:floor(Int, 2*fp*(Npts-1)+1) stopband = (Npts + 1) .- passband pbr = maximum( abs.(abs.(mag[passband]) .- 1) ) sbr = maximum( abs.(mag[stopband]) ) end return (z, mag, F2, pbr, sbr) end """`(mag, pbr, sbr) = frespHBF(f,f1,f2,phi=1.0,fp=0.2,msg="")` Compute the frequency response, the passband ripple and the stopband ripple of a Saramaki HBF. If msg is non-null, a plot is made. - `fp` is the passband edge. - `phi` is used by designHBF. """ function frespHBF(f,f1,f2; phi=1.0, fp=0.2, msg="", calcripples=true) if isa(f, Number) && isnan(f) f = range(0, stop=.5, length=1024) end if isa(f1, Vector{CoeffCSD}) f1 = values(f1) end if isa(f2, Vector{CoeffCSD}) f2 = values(f2) end calcripples = calcripples || isempty(msg) (z, mag, F2, pbr, sbr) = _frespHBF(f, f1, f2, fp, calcripples) if !isempty(msg) F1 = evalF0(f1, z, phi) plot = cons(:plot, linlin, nstrips=2, title="Frequency Response", legend=true, xaxis=set(label="Normalized Frequency", min=0, max=0.5), ystrip1=set(axislabel="Mag", min=0, max=1.1), ystrip2=set(axislabel="Mag [dB]", min=-150, max=10), ) plot.title = msg w1 = waveform(f, abs.(F1)) w2 = waveform(f, phi*abs.(F2)) w3 = waveform(f, abs.(mag)) w4 = waveform(f, dbv.(mag)) pbr_str = @sprintf("pbr = %.1e", pbr) #orig. coords: (0.0,-10) sbr_str = @sprintf("sbr = %.0fdB", dbv(sbr)) #orig. coords: (0.0,dbv(sbr)) push!(plot, cons(:wfrm, w1, line=set(style=:dash, color=:blue, width=2), label="F1"), cons(:wfrm, w2, line=set(style=:dot, color=:red, width=2), label="F2"), cons(:wfrm, w3, line=set(style=:solid, color=:green, width=2), label="HBF"), cons(:wfrm, w4, line=set(style=:solid, color=:green, width=2), label="HBF", strip=2), cons(:atext, pbr_str, y=-10, reloffset=set(x=0.05), align=:tl, strip=2), cons(:atext, sbr_str, y=dbv(sbr), reloffset=set(x=.95), align=:br, strip=2), ) displaygui(plot) end return (mag,pbr,sbr) end #==designF1() ===============================================================================# """`(f1, zetap, phi) = designF1(delta, fp1)` Design the F1 sub-filter of a Saramaki halfband filter. This function is called by designHBF() - `f1`: A structure array containing the F1 filter coefficents and Their CSD representation. - `phi`: The scaling factor for the F2 filter (imbedded in the f1 coeffs.) """ function designF1(delta, fp1) passband = exp.(4π*j*range(0, stop=fp1, length=10)) ok = false n1_found = 7 local h for n1 in 1:2:7 #Odd values only if n1 == 1 h = [0.5, 0.5] else h = remez(2*n1, [(0,4*fp1)=>1, (1,1)=>0], Hz=2) if !(abs(sum(h)-1) < 1e-3) #remez bug! Use firls instead throw("Remez bug! workaround not yet implemented") #h = firls(2*n1-1,[0 4*fp1 1-1e-6 1],[1 1 0 0]) #workaround end end fresp = abs.( polyval(h,passband) ) if maximum( abs.(fresp .- 1) ) <= delta n1_found = n1 ok = true break end end n1 = n1_found if !ok zetap = 1 #Use this as an indication that the function failed. return ([], zetap, 0) end #Transform h(n) to a chebyshev polynomial f1(n) #Sum(f1(i)*cos(w)^n)|i=1:n1 + Sum(h(n1+i))*cos(n*w))|i=1:n1, n = 2*i-1; w = π*rand(1,n1) cos_w = cos.(w) A = zeros(n1,length(w)) B = zeros(1,n1) for i in 1:n1 n = 2*i-1 A[i,:] = cos_w .^ n B = B .+ h[n1+i] * cos.(n*w) end f1 = B/A f1 = f1[:] #Vectorize phivecb = [] #Optimize the quantized version of f1 to maximize the stopband width #( = acos(zetap) ) zetap = 1 phi = 0 f1_saved = nothing testPoints = vcat(0, 10 .^ range(-2, stop=0, length=128)) .- 1 for nsd in 3:8 f1a = f1; f1b = f1 #First try the unperturbed filter. for phia in 1 ./ vcat(1, f1) phia = phia / 2^nextpow(2, abs(phia)) #keep phi in (0.5,1] #Try a bunch of coefficients in the current neighborhood, #shrinking the neighborhood once 10 successive trial values show no #improvement. If 2 successive shrinkages do no good, try a higher nsd. count = 0 nohelp = 0 neighborhood = .05 while neighborhood > 1e-5 phivec = phia .^ collect(1:2:2*n1-1) #Matlab Ver. 5 change: if isempty(phivecb); phivecb = phivec; end f1q = bquantize( f1a .* phivec, nsd ) f1qval = values(f1q) F1 = evalF1( f1qval, testPoints, phia ) fi = findall( abs.(F1) .> delta ) zeta = -testPoints[ max(fi[1]-1, 1) ] #fprintf(2,'nsd=%d, nbhd= %f, count=%d, zeta = %f, phia=%f\n', ... # nsd, neighborhood, count, zeta, phia ) if zeta < zetap count = 0 nohelp = 0 zetap = zeta f1b = f1qval f1_saved = f1q phi = phia phivecb = phivec else count = count + 1 end if count > 10 count = 0 neighborhood = neighborhood/2 nohelp = nohelp + 1 if nohelp > 2 break end end f1a = f1b ./ phivecb + neighborhood*(rand(size(f1b)...) .- 0.5) phia = phia .+ neighborhood*(rand()-0.5) end #while neighborhood ... if zetap < 1 #Found a filter with adequate attn. break end end #for phia ... if zetap < 1 #Found a filter with adequate attn. break end end #for nsd ... return (f1_saved, zetap, phi) end #==designF2() ===============================================================================# """`f2 = designF2(fp,zetap,phi)` Design the F2 sub-filter of a Saramaki halfband filter. This function is called by designHBF(). # subfilter design: `1 - delta2' < |F2/phi| < 1` for `f` in `[0 fp]` `-1 < |F2/phi| < -1 + delta2` for `f` in `[0.5-fp, 0.5]` `1-delta2 = (1-delta2)/(1+delta2)` """ function designF2(fp, zetap, phi) delta2 = (1-zetap)/(1+zetap) #delta2p = 1 - (1-delta2)/(1+delta2) #determine the minimum order required by the filter passband = exp.(j*range(0, stop=4π*fp, length=10)) nsub_found = 17 for nsub in 3:2:17 h2 = remez(nsub+1, [(0,4*fp)=>1, (1,1)=>0], Hz=2) mag = abs.( polyval(h2, passband) ) if maximum(abs.(mag .- 1)) < delta2 nsub_found = nsub break end end n2min = (nsub_found+1)/2 #Search all n2,nsd pairs, in order of the product n2*(nsd+1) #allowing fp to be a variable? success = false nsdmin = 3; nsdmax = 6 for product in (nsdmin+1)*n2min:(nsdmax+1)*n2min for nsd in nsdmin:nsdmax n2 = product/(nsd+1) if floor(n2) != n2 #Only take integer n2,nsd pairs break end n2 = floor(Int, n2) nsub = 2*n2-1 #Could try a bunch of fp values #fprintf(2,'designF2: Trying (n2,nsd2,fp)=(%2d,%2d,%6.4f)\n',n2,nsd,fp); h2 = remez(nsub+1, [(0,4*fp)=>1, (1,1)=>0], Hz=2) h2 = h2/(phi*(1+delta2)) #Adjust the coefficients. f2 = bquantize( h2[n2+1:nsub+1], nsd ) f2val = values(f2) h2 = (1+delta2)*phi*vcat(f2val[n2:-1:1], f2val) mag = abs.( polyval(h2, passband) ) if maximum(abs.(mag .- 1)) < delta2 success = true break end end if success break end end if !success f2 = [] q2 = [] end return f2 end #==designHBF() ===============================================================================# """`(f1,f2,info)=designHBF(fp(=0.2),delta=1e-5,debug=false)` Design a half-band filter which can be realized without general multipliers. The filter is a composition of a prototype and sub- filter. # Input - `fp`: The normalized cutoff frequency of the filter. Due to the symmetry imposed by a HBF, the stopband begins at `0.5-fp`. - `delta`: The absolute value of the deviation of the frequency response from the ideal values of 1 in the passband and 0 in the stopband. # Output - `f1`,`f2`: The coefficients of the prototype and sub-filters and their canonical-signed digit (csd) representation. - `info`: A vector containing the following data (only set when debug=1): - -->`complexity`: The number of additions per output sample. - -->`n1,n2`: The length of the f1 and f2 vectors. - -->`sbr`: The achieved stob-band attenuation (dB). - -->`phi`: The scaling factor for the F2 filter. """ function designHBF(fp::Float64=0.2; delta::Float64=1e-5, debug::Bool=false) f1_saved = f2_saved = nothing #Declare variables phi_saved = 0.0 #=To Do: Clean up the code a bit more, esp. wrt the use of the struct. arrays. Use the phi variable to cut down on the number of adders in F2. Apply a simulated annealing/genetic optimization alg instead of the ad hoc one I have now. =# #Try several different values for the fp1 parameter. #The best values are usually around .04 #Surrender if 3 successive attempts yield progressively greater complexity. lowest_complexity = Inf; prev_complexity = Inf; local worse for fp1 in [.03, .035, .025, .040, .020, .045, .015, .05] failed = false (f1, zetap, phi) = designF1(delta, fp1) if zetap == 1 #designF1 failed failed = true if debug @warn("designF1 failed at fp1=$fp1\n") end end if !failed f2 = designF2(fp, zetap, phi) n1 = length(f1); n2 = length(f2) if n2 == 0 #designF2 failed failed = true if debug @warn("designF2 failed when zetap=$zetap, phi=$phi\n") end end end if !failed #complexity(+ performance) = the number of two-input adders (+ sbr) complexity = sum(csdsize2(f1)) + (2*n1-1)*(n2+sum(csdsize2(f2))-1) #VERIFYME msg = "" if debug msg = @sprintf("%d adders: n1=%d, n2=%d, (fp1=%.2f, zetap=%.3f, phi=%4.2f)", complexity, n1, n2, fp1, zetap, phi ) end (fresp, pbr, sbr) = frespHBF(NaN, f1, f2, phi=phi, fp=fp, msg=msg) if pbr <= delta && sbr <= delta complexity = complexity + sbr if complexity < prev_complexity worse = 0 if complexity < lowest_complexity lowest_complexity = complexity f1_saved = f1; f2_saved = f2 phi_saved = phi if debug; println(msg); end end else worse = worse + 1 if worse > 2; break; end end prev_complexity = complexity end #if pbr <= delta end #!failed end #for fp1 info=nothing if isinf(lowest_complexity) @warn("designHBF: Unable to meet the design requirements.") else complexity = floor(lowest_complexity) msg = "Final Design: $complexity adders" (junk, pbr, sbr) = frespHBF(NaN, f1_saved, f2_saved, phi=phi_saved, fp=fp, msg=msg) n1 = length(f1_saved); n2 = length(f2_saved) if debug msg *= @sprintf(" (%d,%d,%.0fdB)", n1, n2, dbv(sbr)) println(msg) end info = (complexity=complexity, n1=n1, n2=n2, sbr=dbv(sbr), phi=phi_saved) end return (f1_saved, f2_saved, info) end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
13003
#RSDeltaSigma: designLCBP() algorithm #------------------------------------------------------------------------------- #==Types ===============================================================================# """`LCBPParameters` A struct containing the (`n`, `OSR`, `Hinf`, `f0`, `t` and `form`) arguments for the LCBP filter, plus the following fields: - `t`: A two-element vector containing the start and end times of the feedback waveform. Default `= [0 1]`. - `l`: The inductances in each tank. - `c`: The capacitances in each tank. - `gu`: The transconductance from the u input to each of the tanks. The final term is the voltage gain from u to the comparator input. Default `= [1 0 .. ]`. (1 by n+1) - `gv`: The transconductance from the v output to each of the tanks. (1 by n+1) - `gw`: The inter-stage transconductances. Default `= [1 1 .. ]`. (1 by n-1) - `gx`: The gains from the top of each tank resistor to the comparator. Default `= [0 0 .. 1]`. (1 by n) - `rx`: The resistances inserted between the output of each interstage transconductance and top of each tank. Default `= [0 ..]`. (1 by n) Note that rx[1] is not used. - `rl`: The series resistance of each inductor. Default `= [0 ..]`. (1 by n) - `gc`: The parallel conductances of each tank. Default `= [0 ..]`. (1 by n) """ mutable struct LCBPParameters n::Int OSR::Int Hinf::Float64 f0::Float64 t form::Symbol l::Array{Float64}; c::Array{Float64} gu::Array{Float64}; gv::Array{Float64}; gw::Array{Float64}; gx::Array{Float64} rx::Array{Float64}; rl::Array{Float64}; gc::Array{Float64} end LCBPParameters(n=3; OSR=64, Hinf=1.6, f0=0.25, t=[0 1], form::Symbol=:FB) = LCBPParameters(n, OSR, Hinf, f0, t, form, [], [], [], [], [], [], [], [], []) #== ===============================================================================# """`(H,L0,ABCD,k)=LCparam2tf(param,k=1)` Compute the transfer functions (and the Q. gain, k) of an LC modulator. # Arguments - `param`: A LCBPParameters struct. - `k`: The value to assume for the quantizer gain. # Note: - If `k` is omitted or if `k` is defaulted, `k` is taken to be 1. - If `k` is `0`, a value is computed by the formula `k = mean(abs(y))/mean(y.^2)`, where y is the quantizer input sequence when the modulator is fed with a small input at f0. # Output - `H`: The closed-loop noise transfer function (in z). - `L0`: The open-loop tf (in s) from u to v. G may be evaluated using `evalContSTF(L0,H,f)`. - `k`: The value of the quantizer gain used to compute the above tfs. - `ABCD`: The state-space description of the discrete-time system For the conversion from continuous to discrete time, corrections to the standard MATLAB formulae need to be applied in order for the sampled-data value to be taken at the END of the time interval. This effectively makes t1>0 and requires corrections if t2>=1 and gv(n+1)~=0. More complex formulae are needed for t2>=1, so for the moment this code requires t2<1. """ function LCparam2tf(param::LCBPParameters, k::Float64=1.0) l = param.l; c = param.c f0 = mean(1 ./ sqrt.(l .* c)) ./ (2π *pi) n = length(l) gu = param.gu isempty(gu) && (gu = vcat(1, zeros(n))) #Defaults, if needed gu = padr(gu, n+1, 0) #Pad out with zeros, if needed. gv = padr(param.gv, n+1, 0) #Pad out with zeros, if needed. gw = param.gw isempty(gw) && (gw = ones(n-1)) #Defaults, if needed gx = param.gx isempty(gx) && (gx = vcat(zeros(n-1), 1)) #Defaults, if needed rx = param.rx if isempty(rx) rx = zeros(n) elseif 1==length(rx) throw("Not sure: Original code did not seem to make sense.") rx = ones(n) end t = param.t isempty(t) && (t = [0 1]) #Defaults, if needed rl = param.rl if isempty(rl) rl = zeros(n) elseif 1==length(rl) throw("Not sure: Original code did not seem to make sense.") rl = ones(n) end gc = param.gc if isempty(gc) gc = zeros(n) elseif 1==length(gc) throw("Not sure: Original code did not seem to make sense.") gc = ones(n) end #Form the state-space description of the modulator #The states are ordered v1, i1, v2, i2 ... n2 = 2*n local y ABc = zeros(n2,n2+2); CDc = zeros(1,n2+2) for i = 1:n i2 = 2*i-1 #y represents the voltage at the top of the resistor stacked on the tank. if i == 1 y = vcat(1, zeros(n2+1)) else ABc[i2,:] = gw[i-1]*y y = rx[i]*gw[i-1]*y; y[i2] = 1 end ABc[i2,n2+1:n2+2] = [gu[i] -gv[i]] ABc[i2:i2+1,i2:i2+1] = [-gc[i] -1; 1 -rl[i]] ABc[i2,:] = ABc[i2,:]/c[i] ABc[i2+1,:] = ABc[i2+1,:]/l[i] CDc = CDc + (gx[i]*y)' end CDc = CDc + [zeros(1,n2) gu[n+1] -gv[n+1]] #THIS IS THE NEW CODE !! (Ac,Bc,Cc,Dc) = partitionABCD([ABc;CDc], 2) sys_c = _ss( Ac, Bc[:,2], Cc, Dc[2] ) (sys,) = mapCtoD(sys_c, t=t, f0=f0) #Augment the input matrix. A=sys.A B=[padb(Bc[:,1],size(sys.B,1)) sys.B] C=sys.C D=[Dc[1] sys.D] #Compute L0; use the LC parameters to compute the poles and thereby #ensure exact agreement with the zeros in H. #!! THIS IS GOING TO NEED FIXING s_poles = zeros(2*n) .+ 0j #Make complex for i in 1:n _v = [l[i]*c[i], rl[i]*c[i] + gc[i]*l[i], 1+rl[i]*gc[i]] s_poles[2*i-1:2*i] = _roots(_v) end LF0 = _ss(Ac, Bc[:,1], Cc, Dc[1]) L0 = _zpk( LF0 ) L0.p = s_poles #Compute H. Use the poles in L0 to compute the zeros in H. ABCD =[A B; C D] if k==0 #Estimate k by simulatiing the modulator with a small input w0 = mean(1/sqrt.(l .* c)) H = calculateTF(ABCD) H.z = exp.(s_poles) stf0 = abs(evalTFP(L0, H, w0/(2π))) u = 0.1/stf0*sin.(w0*(0:10000)) y = simulateDSM(u, [A B; C D]).y k = mean(abs.(y))/mean(y .^ 2) end (H, STF) = calculateTF(ABCD, [k]) H.z = exp.(s_poles) #Correct L0k to include the quantizer gain L0.k = L0.k*k return (H,L0,ABCD,k) end #Dead code??? function XLCoptparam2tf(x, param) n = param.n #Uncomment the following line to take into account the quantizer gain #before returning results and doing the plots #(H, L0, ABCD, k) = LCparam2tf(param, 0) #Uncomment the following lines to yield parameters corresponding to k=1 #param.gu = k*param.gu; param.gv = k*param.gv #ABCD[2*n+1, :] = ABCD[2*n+1, :] / k #ABCD[:, 2*n+[1 2]] = ABCD[:, 2*n+[1 2]] * k #Now fix up the inputs for 0dB gain at f0. gain_f0 = abs(evalTFP(L0, H, f0)) param.gu = param.gu/gain_f0; L0.k = L0.k/gain_f0 ABCD[:,2*n+1] = ABCD[:,2*n+1]/gain_f0 if (:FF==form) || (:FFR==form) param.gu[n+1] = 1 #For the flattest STF end if dbg @warn("LCplotTF: not yet implemented") #LCplotTF(H,L0,param) end return (H, L0, ABCD, param) end """`LCoptparam2tf(...)` Convert optimization parameters to transfer functions. """ function LCoptparam2tf(x,param) n = param.n param.gw = ones(n-1) if :FB == param.form param.gu = vcat(1, zeros(n)) param.gv = vcat(x) param.gx = vcat(zeros(n-1), 1) param.rx = zeros(n) elseif :FF == param.form param.gu = vcat(1, zeros(n-1), 1) param.gv = vcat(1, zeros(n)) param.gx = vcat(x) param.rx = zeros(n) elseif :FFR == param.form param.gu = vcat(1, zeros(n-1), 1) param.gv = vcat(x[1], zeros(n)) param.gx = vcat(zeros(n-1), 1) param.rx = vcat(0, x[2:n]) elseif :GEN == param.form param.gv = x[1:n] param.rx = vcat(0, x[n+1:2*n-1]) else form = param.form throw("form=:$form is not supported.") end (H, L0, ABCD) = LCparam2tf(param) return (H,L0,ABCD,param) end """`f = LCObj1a(x, param, max_radius, dbg)` The objective function for the initial optimization process used to put the roots of the denominator of the LCBP NTF inside the unit circle. """ function LCObj1a(x, param, max_radius, dbg) return f=1 #No actual objective end """`(C, Ceq) = LCObj1b(x, param, max_radius, dbg)` The constraints function for the initial optimization process used to put the roots of the denominator of the LCBP NTF inside the unit circle. """ function LCObj1b(x, param, max_radius, dbg) (H,) = LCoptparam2tf(x,param) objective = 1 #No actual objective rmax = maximum(abs.(H.p[:])) C = rmax - max_radius Ceq = [] if dbg @show(x) @show(rmax) end return (C, Ceq) end #The objective function function LCObj2a(x, param, rmax, dbg) if dbg @show(x) end (H, L0, ABCD) = LCoptparam2tf(x, param) #The objective is the in-band noise, in dB f1 = param.f0 - 0.25/param.OSR f2 = param.f0 + 0.25/param.OSR objective = dbv(rmsGain(H,f1,f2)/sqrt(3*param.OSR)) println(@sprintf("N0^2 = %.1fdB", objective)) return objective end """`(C, Ceq) = LCObj2b(x,param,rmax,dbg)` % The constraints: r-rmax, Hinf-Hinfdesired, quantizer input, % and for the FB form, |stf|-1.1. """ function LCObj2b(x, param, rmax, dbg) (H, L0, ABCD) = LCoptparam2tf(x, param) Ceq = [] local C #The constraints are on the maximum radius of the poles of the NTF #the infinity-norm of the NTF, the peaking of the STF (for the 'FB' form), #and the maximum input to the quantizer. max_radius = maximum(abs(H.p[:])) H_inf = infnorm(H) stf0 = abs( evalTFP(L0, H, param.f0) ) y = simulateDSM(0.5/stf0*sin(2π*param.f0*(0:1000)), ABCD).y ymax = maximum(abs.(y)) if :FB == param.form f1 = param.f0 - 0.25/param.OSR f2 = param.f0 + 0.25/param.OSR stf1 = abs( evalTFP(L0, H, f1) )/stf0 stf2 = abs( evalTFP(L0, H, f2) )/stf0 C = vcat(100*(max_radius .- rmax), H_inf-param.Hinf, stf1-1.01, stf2-1.01, (ymax-5)/10) #C = vcat(100*(max_radius .- rmax), H_inf-param.Hinf, stf1-1.01, stf2-1.01, log(ymax/5)) else C = vcat(100*(max_radius .- rmax), H_inf-param.Hinf, (ymax-5)/10) end if dbg println(@sprintf("constraints = %8.5f", C)) println(@sprintf("rmax = %5.3f, Hinf = %4.2f, ymax = %5.3f\n", max_radius, H_inf, ymax) ) end return (C, Ceq) end #==Main algorithm ===============================================================================# """`(param,H,L0,ABCD,x)=designLCBP(n=3,OSR=64,opt=2,Hinf=1.6,f0=1/4,t=[0 1],form='FB',x0,dbg=0)` Design an LC modulator of order `2*n` with center frequency `f0`. The feedback waveform is a rectangular pulse from `t[1]` to `t[2]`. # Arguments - `n`: The number of LC tanks. - `OSR`: The oversampling ratio. - `opt`: A flag for NTF zero optimization. See synthesizeNTF. - `Hinf`: The target out-of-band gain of the NTF. - `f0`: The center frequency of the modulator, normalized to fs. - `t`: A 2-element vector containing the (normalized) feedback pulse edge times. - `form`: The modulator topology. One of `:FB`, `:FF`, `:FFR` or `:GEN`. - `x0`: An initial guess at the parameter vector for the optimizer. - `dbg`: A flag for enabling debugging/progress report output. # Output - `param`: A LCBPParameters struct. - `H`: The noise transfer function of the modulator, taking into account the post-design quantizer gain. - `L0`: A description of the open-loop TF from u to v, for use with evalTFP(). - `ABCD`: The state-space representation of the discrete-time equivalent. """ function designLCBP(n=3; OSR=64, opt=2, Hinf=1.6, f0=0.25, t=[0 1], form::Symbol=:FB, x0=NaN, dbg::Bool=false) param = LCBPParameters(n, OSR=OSR, Hinf=Hinf, f0=f0, t=t, form=form) #Compute the resonant frequencies for the LC tanks #and the L and C values. local w if opt>0 w = 2π*(f0 .+ 0.25/OSR*ds_optzeros(n,opt)) else w = 2π*f0*ones(n) end param.l = (1 ./ w); param.c = (1 ./ w) #Impedance scaling is possible. #Find values for the parameters that yield a stable system. #?? Could some control theory help here ?? x = x0 if isnan(x0) x = collect(2:n+1)*1.0 #Needs to be Float64 elseif length(x0) != n throw("Initial guess (x0) has the wrong number of parameters.") end if dbg println("Iterations for initial pole placement:") end max_radius = 0.97 opt = Optim.Options(x_tol=0.001, f_tol=1, iterations=1000) lx = Float64[0,0,0]; ux = Float64[10,10,10] lc = [-Inf]; uc = [max_radius^2] fun1!(x) = LCObj1a(x, param, max_radius, dbg) con_c1!(c, x) = ((C, Ceq)=LCObj1b(x, param, max_radius, dbg); C) # dfc = TwiceDifferentiableConstraints(con_c!, con_jacobian!, con_h!,lx,ux,lc,uc) dfc = TwiceDifferentiableConstraints(con_c1!,lx,ux,lc,uc)#,:forward) # x = optimize(fun1!, dfc, x, IPNewton()).minimum x = optimize(fun1!, con_c1!, x, LBFGS()).minimum #x = fmincon(@LCObj1a,x,[],[],[],[],[],[],@LCObj1b,options,param,0.97,dbg); (H,) = LCoptparam2tf(x,param) rmax = maximum(abs.(H.p[:])) if rmax>max_radius #Failure to converge! throw("Unable to find parameter values which stabilize the system.") end #Do the main optimization for the feedback parameters. if dbg println("\nParameter Optimization:") end max_radius = 0.97 opt = Optim.Options(x_tol=0.001, f_tol=1, iterations=1000, show_trace=dbg, #Extra debugging info g_tol=0.01 #Solver-specific ) lx = Float64[]; ux = Float64[] lc = [-Inf]; uc = [max_radius^2] fun2!(x) = LCObj2a(x, param, max_radius, dbg) con_c2!(c, x) = ((C, Ceq)=LCObj2b(x, param, max_radius, dbg); C) dfc = TwiceDifferentiableConstraints(con_c2!,lx,ux,lc,uc,:forward) x = optimize(fun2!, dfc, x, IPNewton()).minimum #x = fmincon(@LCObj2a,x,[],[],[],[],[],[],@LCObj2b,options,param,0.97,dbg); return (param,H,L0,ABCD,x) end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
3582
#RSDeltaSigmaPort display facilities #------------------------------------------------------------------------------- const PlotOrColl = Union{EasyPlot.Plot, EasyPlot.PlotCollection} struct ImageRepr{T} obj::T #Object to display as image width::Float64 #Width of resultant image AR::Float64 #Aspect ratio end """`ImageRepr{T}(obj::T; width=640, AR=1)` Wrapper object requesting an image representation of something using a specific width and aspect ratio. """ ImageRepr(obj; width=640, AR=1) = ImageRepr(obj, Float64(width), Float64(AR)) #==helper functions ===============================================================================# #Convert EasyPlot.Plot -> EasyPlot.PlotCollection _plt2coll(plot::EasyPlot.Plot) = push!(cons(:plot_collection), plot) #=="show" interface ===============================================================================# function _show(io::IO, mime::MIME, r::ImageRepr{EasyPlot.PlotCollection}) w=round(Int, r.width); h = round(Int, w/r.AR) set = EasyPlot.set opt = EasyPlot.ShowOptions(dim=set(w=w, h=h)) b = EasyPlot.getbuilder(:image, :InspectDR) nativeplot = EasyPlot.build(b, r.obj) EasyPlot._show(io, mime, opt, nativeplot) return nothing end function _show(io::IO, mime::MIME, r::ImageRepr{EasyPlot.Plot}) pcoll = _plt2coll(r.obj) return _show(io, mime, ImageRepr(pcoll, width=r.width, AR=r.AR)) end #Only publicly provide Base.show() for MIME"image/png": Base.show(io::IO, mime::MIME"image/png", r::ImageRepr{T}) where T<:PlotOrColl = _show(io, mime, r) function Base.show(io::IO, mime::MIME"text/plain", r::ImageRepr{EasyPlot.PlotCollection}) #Do not warn. Jupyter calls function even if it doesn't use the results. #Might it be generating text for a hover-pop-up or something? # @warn("Trying to display inline plot on simple text display.") println(io, "[INLINE PLOT]: ", r.obj.title) return nothing end function Base.show(io::IO, mime::MIME"text/plain", r::ImageRepr{EasyPlot.Plot}) println(io, "[INLINE PLOT]: ", r.obj.title) return nothing end #=="showable" interface ===============================================================================# #Base.showable(mime::MIME"image/png", p::ImageRepr) = true #==User-facing interface ===============================================================================# """`inlinedisp(plot; AR=1, scalew=1, maxw=900)` Display plot as inline image. # Arguments - `AR`: Aspect ratio (w/h) of generated image. - `maxw`: Reference width of image (typ. max width of display). - `scalew`: Amount by which to scale image before rendering it (`imagew=maxw*scalew`) """ inlinedisp(plot; AR=1, scalew=1, maxw=900) = display(ImageRepr(plot; AR=AR, width=maxw*scalew)) _write(mime::Symbol, filepath::String, nativeplot; opt_kwargs...) = _write(mime, filepath, ShowOptions(; opt_kwargs...), nativeplot) """`saveimage(mime::Symbol, filepath::String, plot; AR=1, width=900)` Saves plot as an image. # Arguments - `AR`: Aspect ratio (w/h) of generated image. - `maxw`: Reference width of image (typ. max width of display). - `scalew`: Amount by which to scale image before rendering it (`imagew=maxw*scalew`) """ function saveimage(mime::Symbol, filepath::String, plot::PlotOrColl; AR=1, width=900) ir = ImageRepr(plot; AR=AR, width=width) open(filepath, "w") do io _show(io, EasyPlot._getmime(mime), ir) end end function displaygui(plot::PlotOrColl) result = EasyPlot.displaygui(:InspectDR, plot) sleep(0.1) #Get GUI to refresh (Ideally: `doevents()`, or something) #NOTE: Appears sleep needs to be > 0 to refresh. return result end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
2155
#RSDeltaSigma: exampleHBF() function #------------------------------------------------------------------------------- function HBFex1() q1 = [ 0 -4 -5; 1 1 1; 0 -4 -5; -1 -1 -1; -1 -3 -5; 1 1 1; -3 -5 0; -1 -1 0; ] q2 = [ -1 -3 -7; 1 1 1; -2 -5 -7; -1 1 1; -3 -8 0; 1 -1 0; -4 -6 -8; -1 -1 -1; -4 -8 0; 1 -1 0; -5 -7 -8; -1 -1 -1; -5 0 0; 1 0 0; -6 -7 0; -1 -1 0; -7 -8 0; -1 -1 0; -6 0 0; 1 0 0; ] return (q1,q2) end """`HBFex2()` Coefficients from toolbox v2.0 documentation. """ function HBFex2() q1 = [ 0 -4 -7; 1 -1 1; -1 -3 -6; -1 -1 -1; -2 -4 -7; 1 -1 1; ] q2 = [ -1 -3 -8; 1 1 -1; -2 -4 -9; -1 1 -1; -3 -5 -9; 1 -1 1; -4 -7 -8; -1 1 1; -5 -8 -11; 1 -1 -1; -6 -9 -11; -1 1 -1; ] return (q1,q2) end """`Saramaki88()` Coefficients from "Efficient VLSI-Realizable Decimators for Sigma-Delta Analog-to-Digital Converters," T. Saramaki and H. Tenhunen, ISCAS 1988, pp 1525-2528. """ function Saramaki88() q1 = [ 0 -2; 1 -1; -2 -9; -1 1; ] q2 = [ -1 -3 0; 1 1 0; -3 -5 -6; -1 -1 -1; -4 -6 0; 1 1 0; ] return (q1,q2) end """`Saramaki90()` Coefficients from "Multiplier-Free Decimation Algorithms for Superresolution Oversampled Converters," T. Saramaki, T. Karema, T. Ritoniemi, and H. Tenhunen ISCAS 1990, vol. 4. pp 1525-2528. """ function Saramaki90() q1 = [ 0 -4 -5; 1 1 1; 0 -4 -5; -1 -1 -1; -1 -3 -5; 1 1 1; -3 -5 -20; -1 -1 1; ] q2 = [ -1 -3 -7; 1 1 1; -2 -5 -7; -1 1 1; -3 -8 0; 1 -1 0; -4 -6 -8; -1 -1 -1; -4 -8 0; 1 -1 0; -5 -7 -8; -1 -1 -1; -5 0 0; 1 0 0; -6 -7 0; -1 -1 0; -6 0 0; 1 0 0; -7 -8 0; -1 -1 0; -6 0 0; 1 0 0; ] return (q1,q2) end function exampleHBF(n::Int = 0) fnlist = [HBFex1, HBFex2, Saramaki88, Saramaki90] if !in(n, keys(fnlist)) throw("exampleHBF: No code for example $n.") end fn = fnlist[n] (q1, q2) = fn() F1 = convertForm(bunquantize(q1),q1) F2 = convertForm(bunquantize(q2),q2) return (F1, F2) end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
2389
#RSDeltaSigma: Base functions to assist with filtering operations #------------------------------------------------------------------------------- #==Types ===============================================================================# """`CoeffCSD` A structure containing filter coefficents and their canonical-signed digit (CSD) representation. """ struct CoeffCSD val csd end #==Accessors ===============================================================================# csdsize2(f::Vector{CoeffCSD}) = [size(fi.csd,2) for fi in f] #VERIFYME Base.values(f::Vector{CoeffCSD}) = [fi.val for fi in f] #==Functions ===============================================================================# """`bquantize(x, nsd=3, abstol=eps, reltol=10*eps)` Bidirectionally quantize a n by 1 vector x to nsd signed digits. Terminate early if the error is less than the specified tolerances. # Output y is a CoeffCSD[] with the following fields: - `y[i].val` is the quantized value in floating-point form - `y[i].csd` is a 2-by-nsd (or less) matrix containing the powers of two (first row) and their signs (second row). # See also: [`bunquantize`](@ref) """ function bquantize(x, nsd::Int=3, abstol::Float64=eps(1.0), reltol::Float64=10*eps(1.0)) n = length(x) q = zeros(2*n,nsd) y = Array{CoeffCSD}(undef, n) offset = -log2(0.75) for i in 1:n xp = x[i] val = 0 csd = zeros(2,nsd) for j in 1:nsd error = abs(val-x[i]) if error <= abstol || error <= abs(x[i])*reltol break end p = floor( log2(abs(xp)) + offset ) p2 = 2^p sx = sign(xp) xp = xp - sx*p2 val = val + sx*p2 csd[1:2, j] = [p; sx] end y[i] = CoeffCSD(val, csd) end return y end """`bunquantize(q)` Calculate the value corresponding to a bidirectionally quantized quantity. q is a 2n by m matrix containing the powers of 2 and their signs for each quantized value. # See also: [`bquantize`](@ref) """ function bunquantize(q) q = 1.0*q #Ensure we have floating point values n = size(q,1)/2 y = zeros(array_round(n),1) signs = 2:2:array_round(2*n) powers = signs .- 1 for i in 1:size(q,2) y = y + 2 .^ q[powers,i] .* q[signs,i] end return y end function convertForm(f,q) n = length(f) F = CoeffCSD[] for i in 1:n val = f[i] csdrep = q[2*i-1:2*i,:] csd = csdrep[:,findall(csdrep[1,:] .!=0)] push!(F, CoeffCSD(val, csd)) end return F end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
6388
#RSDeltaSigma: mapCtoD (State space utility) #------------------------------------------------------------------------------- #==Helper functions ===============================================================================# function B2formula(Ac, t1, t2, B2) local term=0 local term1=0 if t1==0 && t2==0 term = B2 return term end n = size(Ac, 1) tmp = eye(n) - exp(-Ac) if cond(tmp) < 1e6 term = ( (exp(-Ac*t1) - exp(-Ac*t2)) * inv(tmp)) * B2 return term end #Numerical trouble. Perturb slightly and check the result ntry = 0 k = sqrt(eps(1.0)) Ac0 = Ac #Make this operation repeatable #rng_state = rng; rng('default') #Original code Random.seed!(0) while ntry <2 Ac = Ac0 + k*rand(n,n) tmp = eye(n) - exp(-Ac) if cond(tmp) < 1/sqrt(eps(1.0)) ntry = ntry+1 if ntry == 1 term = ( (exp(-Ac*t1) - exp(-Ac*t2)) * inv(tmp)) * B2 else term1 = ( (exp(-Ac*t1) - exp(-Ac*t2)) * inv(tmp)) * B2 end end k = k*sqrt(2) end Random.seed!() #original code restores state: rng(rng_state) if norm(term1-term) > 1e-3 @warn("Inaccurate calculation in mapCtoD.") end return term end """`(sys, Gp) = mapCtoD(sys_c, t=[0 1], f0=0, calcGp=false)` Map a MIMO continuous-time system to a SIMO discrete-time equivalent. The criterion for equivalence is that the sampled pulse response of the CT system must be identical to the impulse response of the DT system. i.e. If yc is the output of the CT system with an input vc taken from a set of DACs fed with a single DT input v, then y, the output of the equivalent DT system with input v satisfies y(n) = yc(n-) for integer n. The DACs are characterized by rectangular impulse responses with edge times specified in the t matrix. # Input - `sys_c`: The LTI description of the CT system. - `t`: The edge times of the DAC pulse used to make CT waveforms from DT inputs. Each row corresponds to one of the system inputs; `[-1 -1]` denotes a CT input. The default is `[0 1]`, for all inputs except the first. - `f0`: The (normalized) frequency at which the Gp filters' gains are to be set to unity. Default 0 (DC). # Output - `sys`: The LTI description for the DT equivalent - `Gp`: The mixed CT/DT prefilters which form the samples fed to each state for the CT inputs. # Reference - R. Schreier and B. Zhang, "Delta-sigma modulators employing continuous-time circuitry," IEEE Transactions on Circuits and Systems I, vol. 43, no. 4, pp. 324-332, April 1996. """ function mapCtoD(sys_c; t=[0 1], f0::Float64=0.0, calcGp::Bool = false) ni = size(sys_c.B, 2) if size(t) == (1,2) && (ni > 1) #VERIFYME t = [-1 -1; ones(ni-1,1)*t] end if size(t) != (ni, 2) #VERIFYME error("The t argument has the wrong dimensions.") end di = ones(ni) for i in 1:ni if t[[i],:]==[-1 -1] di[i] = 0 end end di = (di .!= 0) #Convert to logical array. i!di = findall(.!di); idi = findall(di) #c2d assumes t1=0, t2=1. #Also c2d often complains about poor scaling and can even produce #incorrect results. NEEDS_DELAY = false #VERSIONSWITCH if NEEDS_DELAY #set(sys_c,'InputDelay',0) end sys = _c2d(sys_c, 1, :zoh) Ac = sys_c.A Bc1 = sys_c.B[:, i!di] A = sys.A; B = sys.B; C = sys.C; D = sys.D B1 = B[:, i!di]; D1 = D[:, i!di] #Examine the discrete-time inputs to see how big the #augmented matrices need to be. n = size(A,1) t2 = ceil.(Int, t[idi,2]) esn = (t2 .== t[idi,2]) .& (D[[1],idi] .!= 0)' #extra states needed? np = n + maximum(t2 .- 1 + esn) #Augment A to np x np, B to np x 1, C to 1 x np. Ap = padb( padr(A,np), np ) for i in n+2:np Ap[i, i-1] = 1 end Bp = zeros(np, 1) if np>n Bp[n+1] = 1 end Cp = padr(C, np) Dp = 0 #Add in the contributions from each DAC for i in findall(di) t1 = t[i,1] t2 = t[i,2] B2 = B[:,i] D2 = D[:,i] if t1==0 && t2==1 && all(D2 .== 0) #No fancy stuff necessary Bp = Bp + padb(B2,np) else n1 = floor(Int, t1); n2 = ceil(Int, t2)-n1-1 t1 = t1-n1; t2 = t2-n2-n1 if t2==1 && all(D2 .!= 0) n2 = n2+1 extraStateNeeded = true else extraStateNeeded = false end nt = n+n1+n2 if n2>0 && t2!=1 Ap[1:n,nt] = Ap[1:n,nt] + B2formula(Ac, 0, t2, B2) end local Btmp if n2>0 #pulse extends to the next period Btmp = B2formula(Ac,t1,1,B2) else #pulse ends in this period Btmp = B2formula(Ac,t1,t2,B2) end if n1>0 Ap[1:n,n+n1] = Ap[1:n,n+n1] + Btmp else Bp = Bp + padb(Btmp,np) end if n2>0 Cp = Cp + padr([zeros(size(D2,1),n+n1) D2*ones(1,n2)], np) end end end sys = _ss(Ap, Bp, Cp, Dp, 1) Gp = nothing if any(di .== 0) if calcGp #Compute the prefilters and add in the CT feed-ins. #Gp = inv(sI-Ac) * (zI-A)/z *Bc1 (n, m) = size(Bc1) Gp = fill(CTDTPrefilters[], n,m) ztf = Array{Any}(nothing, size(Bc1)) #!!Make this like stf: an array of zpk objects #Compute the z-domain portions of the filters ABc1 = A*Bc1 for h in 1:m for i in 1:n if Bc1[i,h]==0 ztf[i,h] = _zpk([],0,-ABc1[i,h],1) else ztf[i,h] = _zpk(ABc1[i,h]/Bc1[i,h],0,Bc1[i,h],1) end end end #Compute the s-domain portions of each of the filters stf = _zpk(_ss(Ac,eye(n),eye(n),zeros(n,n))) #Doesn't do pole-zero cancelation for h in 1:m for i in 1:n for j=1:n if stf.k[i,j]!=0 && ztf[j].k!=0 #A non-zero term push!(Gp[i,h], CTDTPrefilters(stf(i,j), ztf[j,h])) end end end end if f0 != 0 #Need to correct the gain terms calculated by c2d #B1 = gains of Gp @f0; for h in 1:m for i in 1:n B1[i,h] = evalMixedTF(Gp[i,h],f0) #abs() used because ss() whines if B has complex entries... #This is clearly incorrect. #I've fudged the complex stuff by including a sign.... B1[i,h] = abs(B1[i,h]) * sign(real(B1[i,h])) if abs(B1[i,h]) < 1e-9 B1[i,h] = 1e-9 #This prevents NaN in line 174 end end end end #Adjust the gains of the pre-filters for h in 1:m for i in 1:n for j in 1:length(Gp[i,h]) Gp[i,h][j].Hs.k = Gp[i,h][j].Hs.k/B1[i,h] #This is line 174 end end end newB = [padb(B1,np) sys.B]; newD = [D1 sys.D] sys = _ss(sys.A, newB, sys.C, newD) else #Cheat and just dublicate the B1 terms newB = [padb(Bc1,np) sys.B]; newD = [D1 sys.D] sys = _ss(sys.A, newB, sys.C, newD) end end return (sys, Gp) end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
3978
#RSDeltaSigmaPort: Implement missing core functionality #------------------------------------------------------------------------------- """Emulates rounding of array indices""" array_round(i) = round(Int, i) #VERIFYME function rat(v::Real, tol::Float64) r=rationalize(Float64(v), tol=tol) return (r.num, r.den) end function squeeze(a) sz = collect(size(a)) for i in reverse(keys(sz)) if sz[i]<2 a = dropdims(a, dims=i) end end return a end #Sort complex poles function _cplxpair(a) epstol = 100 #Sorts real first, then imaginary: function isrealless(a,b) Δmin = epstol*eps(abs(a)) if abs(real(a) - real(b)) < Δmin return imag(a) < imag(b) else return real(a) < real(b) end end a = sort(a, lt=isrealless) i = 1 while i < length(a) v = a[i] Δmin = epstol*eps(abs(v)) if abs(imag(v)) < Δmin #Really a real number a[i] = real(v) i+=1 break elseif i < length(a) if abs(v-conj(a[i+1])) < Δmin i+=2 #Skip both cplx conj pairs. break else throw(ErrorException("cplxpair failed.")) end else throw(ErrorException("cplxpair failed.")) end end return a end """`cplxpair(a)` Sort roots in array a such that complex pairs are in ascending order of their real parts, then by their imaginary part. In the output, the real roots re-positionned after the complex roots. """ function cplxpair(a) epstol = 100 #Index of real roots: Δmin = epstol*eps.(abs.(a)) #Threshold for numerical error ireal = abs.(imag.(a)) .< Δmin areal = real.(a[ireal]) #Clean up real roots acplx = a[.!ireal] #complex pairs return vcat(_cplxpair(acplx), sort(areal)) #Sort roots end #Custom function to ensure complex conjugate pairs match exactly. function cleancplxpair(l) epstol = 100 if length(l) < 2 return l end l = cplxpair(l) #Sort to group complex conjugates together result = similar(l) if length(l)>0 #Copy last value in case not part of conjugate pair #(ignored by following algorithm) result[end] = l[end] end i = 1 while i < length(l) a, b = l[i], l[i+1] ΔRmin = epstol*eps(real(a)) ΔXmin = epstol*eps(imag(a)) result[i] = a if abs(real(a) - real(b)) < ΔRmin && abs(imag(a) + imag(b)) < ΔXmin a = (a+conj(b))/2 #Take mean & re-write result[i] = a result[i+1] = conj(a) i+=1 end i+=1 end return result end #TODO: Will algorithms work without collect (possibly faster?): eye(n::Int) = collect(LinearAlgebra.I(n)) #It sounds like this should be implementation of orth: #orth(A) = LinearAlgebra.qr(A).Q #But scipy seems to do it this way: orth(A) = LinearAlgebra.svd(A).U #Convert array of roots into polynomial: function poly(rA) result = [1] for r in rA result = conv(result, [1, -r]) end return result end eig(a) = eigen(a).values #Implement interp1 using linear interpolation: function interp1_lin(xA, yA, xv) ILib = Interpolations itp = ILib.interpolate((x,), y, ILib.Gridded(ILib.Linear())) return itp(xv) end #Implement interp1 using cubic interpolation: function interp1_cubic(xA, yA, xv) ILib = Interpolations itp = ILib.interpolate(yA, ILib.BSpline(ILib.Cubic(ILib.Natural())), ILib.OnGrid()) intf = ILib.scale(itp, xA) return intf(xv) end #FIXME/VERIFYME #Algoritm assembled together by MALaforge, hoping it will be sufficient. #Probably a good idea to have an expert implement proper function. function interp(v, OSR::Int) thresh = .01 Δs = OSR*ceil(Int, 1/(thresh*π)) x = -Δs:1:Δs v_0 = zeros(length(v)*OSR) for i in 0:length(v)-1 v_0[1+OSR*i] = v[1+i] end _filt = sinc.(x/OSR) result = conv(_filt, v_0) result = result[Δs .+ (1:length(v_0))] return result end #Evaluate polynomial p at value x function polyval(p, x) #NOTE: [1, 2, 3] => 1 + 2x¹ + 3x² polyfn = Polynomial(p) return polyfn.(x) #Evaluates polynomial end #_roots so as to not confuse it with Polynomials.roots #NOTE: Polynomial expects the coefficients in opposite order: _roots(p) = Polynomials.roots(Polynomial(reverse(p))) #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
1622
#RSDeltaSigmaPort: Implement missing core functionality using ControlSystems.jl #------------------------------------------------------------------------------- #=TODO (Goal) Want to not depend on ControlSystems.jl (slows down compile time significantly). UPDATE: Much better in Julia 1.6 - especially using Revise.jl. Maybe ok to depend on ControlSystems.jl. =# _c2d(sys, Ts, method=:zoh) = ControlSystems.c2d(sys, Ts, method) _ss(A,B,C,D) = ControlSystems.ss(A,B,C,D) #Ts=0.0 default: continuous-time system _ss(A,B,C,D,Ts) = ControlSystems.ss(A,B,C,D,Ts) function _zpk(sys::ControlSystems.StateSpace) H=ControlSystems.zpk(sys) z, p, k = ControlSystems.zpkdata(H) #Cannot access sys.Ts for continuous time: #(use sys because Ts does not get ported over in zpk() for some reason) Ts = isdiscrete(sys) ? sys.Ts : 0.0 return _zpk(z, p, k, Ts) end function _zp2ss(z, p, k) H = ControlSystems.zpk(z, p, k) return ControlSystems.ss(H) end function _zp2tf(z, p, k) H = ControlSystems.zpk(z, p, k) _num = ControlSystems.num(H) _den = ControlSystems.den(H) return (_num, _den) end function _freqz(num, den, w) H = ControlSystems.tf(num, den, 1) return ControlSystems.freqresp(H, w) end _tf(num, den, ts) = ControlSystems.tf(num, den, ts) _minreal(sys, tol) = ControlSystems.minreal(sys, tol) function _impulse(sys, t) y, t, x = ControlSystems.impulse(sys, t) return (y, t, x) end function _lsim(sys, u) if !isdiscrete(sys) throw("_lsim: must specify t-vector") end Ts = sys.Ts t = range(0, step=Ts, length=length(u)) y, t, x = ControlSystems.lsim(sys, u, t) return (y, t, x) end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
2517
#RSDeltaSigmaPort: Optimization functions #------------------------------------------------------------------------------- "values for optimal zeros when opt==1" const _VALUES_OPTZEROS_OPT1 = [ #Currently not type stable [0.0], # n = 1 [sqrt(1/3)], [sqrt(3/5), 0], sqrt.([3/7+sqrt(9/49-3/35), 3/7-sqrt(9/49-3/35)]), sqrt.([5/9+sqrt(25/81-5/21), 5/9-sqrt(25/81-5/21), 0]), # n = 5 [0.23862059, 0.66120988, 0.9324696], [0, 0.40584371, 0.74153078, 0.94910785], [0.18343709, 0.52553345, 0.79666684, 0.96028993], [0, 0.32425101, 0.61337056, 0.83603082, 0.9681602], [0.1834370913, 0.5255334458, 0.7966668433, 0.9602899327], # n = 10 [0, 0.26953955, 0.51909468, 0.73015137, 0.88706238, 0.97822864], [0.12523875, 0.36783403, 0.58731921, 0.7699033, 0.90411753, 0.9815607], [0, 0.23045331, 0.44849063, 0.64234828, 0.8015776, 0.91759824, 0.98418306], [0.10806212, 0.31911586, 0.51525046, 0.68729392, 0.82720185, 0.92843513, 0.98628389], # n = 14 ] "values for optimal zeros when opt==2" #or other?; is it called in other cases? const _VALUES_OPTZEROS_OPT2 = [ _VALUES_OPTZEROS_OPT1[1], # n = 1 [0.0], _VALUES_OPTZEROS_OPT1[3], [0, sqrt(5/7)], _VALUES_OPTZEROS_OPT1[5], # n = 5 sqrt.([0, 7/11+sqrt(56)/33, 7/11-sqrt(56)/33]), _VALUES_OPTZEROS_OPT1[7], [0, 0.50563161, 0.79017286, 0.95914731], _VALUES_OPTZEROS_OPT1[9], [0, 0.41572267, 0.67208682, 0.86238894, 0.97342121], # n = 10 _VALUES_OPTZEROS_OPT1[11], [0, 0.35222363, 0.58006251, 0.76647993, 0.90281326, 0.98132047], _VALUES_OPTZEROS_OPT1[13], [0, 0.30524384, 0.50836649, 0.6836066, 0.82537239, 0.92772336, 0.98615167], # n = 14 ] @assert(length(_VALUES_OPTZEROS_OPT1) == length(_VALUES_OPTZEROS_OPT2)) """`optZeros = ds_optzeros( n, opt=1 )` A helper function for the synthesizeNTF function of the Delta-Sigma Toolbox. Returns the zeros which minimize the in-band noise power of a delta-sigma modulator's NTF. """ function ds_optzeros(n, opt=1) norig = n; n = array_round(n) #VERIFYME local optZeros if opt==0 optZeros = zeros(ceil(Int, norig/2)) elseif n > length(_VALUES_OPTZEROS_OPT1) throw(ErrorException("Optimized zeros for n>14 are not available.")) elseif opt==1 optZeros = _VALUES_OPTZEROS_OPT1[n] else optZeros = _VALUES_OPTZEROS_OPT2[n] end # Sort the zeros and replicate them. z = sort(optZeros) optZeros = zeros(n) m=1 if mod(n,2)==1 optZeros[1] = z[1] z = z[2:length(z)] m=m+1 end for i=1:length(z) optZeros[m] = z[i] optZeros[m+1] = -z[i] m = m+2 end return optZeros end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
7346
#RSDeltaSigmaPort: Generate plots for noise transfer functions #------------------------------------------------------------------------------- #==Vector generators ===============================================================================# """`𝑓 = ds_freq(OSR=64, f0=0, quadrature=false)` Frequency vector suitable for plotting the frequency response of an NTF. """ function ds_freq(;OSR::Int=64, f0::Float64=0, quadrature::Bool=false) local f_left, f_special if quadrature f_left = -0.5 f_special = [f0 -f0] else f_left = 0 f_special = f0 end 𝑓 = collect(range(f_left, stop=0.5, length=100)) #Use finer spacing in the vicinity of the passband for fx = f_special f1 = max(f_left, fx-1/OSR) f2 = min(0.5,fx+2/OSR) deleteat!(𝑓, (𝑓 .<= f2) .& (𝑓 .>= f1)) 𝑓 = sort( vcat(𝑓, range(f1, stop=f2, length=100)) ) end return 𝑓 end #==NTF plots ===============================================================================# function plotNTF(isbandpass) dBmin = -100 #Limit dB window to finite value 𝑓min_log = 10^-2 #Limit min 𝑓 for log(𝑓-norm) plots nogrid = set(vmajor = false, vminor = false, hmajor=false, hminor=false) vgridonly = set(vmajor = true, vminor = true, hmajor=false, hminor=false) plot_PZ = plotPZ() plot_PZ.title = "NTF Poles and Zeros" plot_NTFlin = cons(:plot, legend=false, title = "NTF Magnitude Response", xyaxes=set(xscale=:lin, yscale=:lin, ymin=dBmin), labels=set(xaxis="Normalized frequency (1→f_s)", yaxis="dB"), ) plot_NTFlog = cons(:plot, legend=false, grid = vgridonly, # title = "NTF Magnitude Response", xyaxes=set(xscale=:log, yscale=:lin, xmin=𝑓min_log, ymin=dBmin), labels=set(xaxis="Normalized frequency (1→f_B)", yaxis="dB"), ) plot_NTFzoom = cons(:plot, legend=false, grid = vgridonly, # title = "NTF Magnitude Response", xyaxes=set(xscale=:lin, yscale=:lin, xmin=-0.6, ymax=0.6, ymin=dBmin), labels=set(xaxis="Normalized frequency offset", yaxis="dB"), ) if !isbandpass; plot_NTFzoom = plot_NTFlog; end pcoll = push!(cons(:plot_collection, title="Sample Plot"), plot_PZ, plot_NTFlin, plot_NTFzoom ) pcoll.bblist = [ BoundingBox(0, 0.5, 0, 1), #Pole-zero BoundingBox(0.5, 1, 0, 0.5), #NTF linf BoundingBox(0.5, 1, 0.5, 1), #NTF zoom ] return pcoll end function plotNTF!(pcoll, NTF::ZPKData, OSR::Int; color=:blue, f0::Real=0, STF=nothing) dfltline = cons(:a, line=set(style=:solid, color=color, width=2)) gainline = cons(:a, line=set(style=:solid, color=:red, width=2)) markerline = cons(:a, line=set(style=:dash, width=2.5)) plot_PZ, plot_NTFlin, plot_NTFzoom = pcoll.plotlist isbandpass = f0!=0 #Plot poles and zeros plotPZ!(plot_PZ, NTF, color=color) #Plot full-range NTF 𝑓 = vcat(range(0, stop=0.75/OSR, length=100), range(0.75/OSR, stop=0.5, length=100)) if isbandpass f1 = f0-1/(2*OSR); f2 = f0+1/(2*OSR) 𝑓 = vcat(range(0, stop=f1, length=50), range(f1, stop=f2, length=100), range(f2, stop=0.5, length=50)) end z = exp.(2j*π*𝑓) magNTF = dbv(evalTF(NTF, z)) push!(plot_NTFlin, cons(:wfrm, DataF1(𝑓, magNTF), dfltline, label="|NTF|") ) if STF != nothing plot_NTFlin.title = "NTF/STF Magnitude Response" magSTF = dbv(evalTF(STF,z)) push!(plot_NTFlin, cons(:wfrm, DataF1(𝑓, magSTF), gainline, label="|STF|") ) end #Plot "zoomed-in" NTF 𝑓start = 0.01 𝑓 = collect(range(𝑓start, stop=1.2, length=200)/(2*OSR)) ∫rng = [0, 0.5/OSR] if isbandpass f1 = f0-0.3/OSR; f2 = f0+0.3/OSR 𝑓 = collect(range(f1, stop=f2, length=100)) ∫rng = f0 .+ [-.25, .25]/OSR end z = exp.(2j*π*𝑓) 𝑓norm = (𝑓 .- f0)*(2*OSR) magNTF = dbv(evalTF(NTF, z)) σ_NTF = dbv(rmsGain(NTF, ∫rng[1], ∫rng[2])) rmsgain_str = @sprintf("RMS Gain = %5.0fdB", σ_NTF) push!(plot_NTFzoom, cons(:wfrm, DataF1(𝑓norm, magNTF), dfltline, label="|NTF|"), cons(:atext, rmsgain_str, y=σ_NTF, offset=set(y=3), reloffset=set(x=0.5), align=:bc), cons(:hmarker, σ_NTF, markerline, strip=2), ) return pcoll end plotNTF(NTF::ZPKData, args...; f0=0, kwargs...) = plotNTF!(plotNTF(f0!=0), NTF::ZPKData, args...; f0=f0, kwargs...) #==documentNTF ===============================================================================# """`plot = documentNTF(NTF|ABCD|mod_struct; OSR=64, f0=0, quadrature=false, frespOnly=false, sizes=nothing)` The first argument is either the NTF, ABCD matrix or a struct containing NTF, OSR=64, f0=0, quadrature=0 and optionally stf. If the first argument is a struct, then no other arguments should be supplied. If the first argument is ABCD, the stf is also plotted. """ function documentNTF(arg1; OSR::Int=64, f0::Float64=0.0, quadrature::Bool=false, frespOnly::Bool=false, sizes=nothing) STF=nothing local NTF if isa(arg1, ZPKData) NTF = arg1 else #if isa(arg1, Array) #Assume ABCD matrix ABCD = arg1 NTF, STF = calculateTF(ABCD) end logplot = f0==0 if quadrature f_left = -0.5 elseif logplot f_left = 1e-3 else f_left = 0.0 end pcoll = cons(:plot_collection, ncolumns=2, title="") if !frespOnly #Plot poles and zeros plot = plotPZ(NTF, color=:blue) push!(pcoll, plot) pcoll.bblist = [ #Format plot locations BoundingBox(0, 0.5, 0, 1), #Pole-zero plot BoundingBox(0.5, 1, 0, 1), #Frequency spectrum ] end #Frequency response 𝑓 = ds_freq(OSR=OSR, f0=f0, quadrature=quadrature) z = exp.(2π*j*𝑓) H = dbv.(evalTF(NTF, z)) axes = logplot ? loglin : linlin plot = cons(:plot, axes, title="Frequency Response", legend=false, labels=set(xaxis="Normalized Frequency", yaxis=""), xyaxes=set(xmin=f_left, xmax=0.5, ymin=-100, ymax=15), ) push!(pcoll, plot) H = waveform(𝑓, H) push!(plot, cons(:wfrm, H, line=set(style=:solid, color=:blue, width=2), label=""), ) if !isnothing(STF) # plot.title = "NTF and STF" G = dbv.(evalTF(STF,z)) G = waveform(𝑓, G) push!(plot, cons(:wfrm, G, line=set(style=:solid, color=:magenta, width=2), label=""), ) end f1, f2 = ds_f1f2(OSR=OSR, f0=f0, iscomplex=quadrature) NG0 = dbv.(rmsGain(NTF, f1, f2)) NG0w = waveform([max(f1,f_left), f2], NG0*[1,1]) push!(plot, cons(:wfrm, NG0w, line=set(style=:dash, color=:black, width=2), label=""), ) tstr = @sprintf(" %.0fdB", NG0) if f0==0 && logplot a = cons(:atext, tstr, x=sqrt(f_left*0.5/OSR), y=NG0+2, align=:bc) else a = cons(:atext, tstr, x=f2, y=NG0-1, align=:cl) end push!(plot, a) #set(h, 'FontSize',sizes.fs, 'FontWeight',sizes.fw); msg = @sprintf(" Inf-norm of H = %.2f\n 2-norm of H = %.2f", infnorm(NTF)[1], rmsGain(NTF,0,1)); if f0<0.25 a = cons(:atext, msg, x=0.48, y=0.0, align=:tr) else a = cons(:atext, msg, x=f_left, y=0.0, align=:tl) end push!(plot, a) #set(h, 'FontSize',sizes.fs, 'FontWeight',sizes.fw); if quadrature ING0 = dbv(rmsGain(ntf,-f1,-f2)) ING0w = waveform(-1*[f1, f2], ING0*[1, 1]) tstr = @sprintf("%.0fdB", ING0) push!(plot, cons(:wfrm, NG0w, line=set(style=:solid, color=:black, width=2), label=""), cons(:atext, tstr, x=-f0, y=ING0+1, align=:bc), ) end #set(h, 'FontSize',sizes.fs, 'FontWeight',sizes.fw); return pcoll end """`documentNTF(dsm, SYS=nothing; frespOnly=false, sizes=nothing)` """ function documentNTF(dsm::AbstractDSM, SYS=nothing; frespOnly::Bool=false, sizes=nothing) isnothing(SYS) && (SYS = synthesizeNTF(SYS)) return documentNTF(SYS; OSR=dsm.OSR, f0=dsm.f0, quadrature=false, frespOnly=frespOnly, sizes=sizes) end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
1586
#RSDeltaSigmaPort: Generate plots of the Signal-to-Noise Ratio #------------------------------------------------------------------------------- #==SNR plot ===============================================================================# #TODO: Rename `plotSQNR`? function plotSNR() plot = cons(:plot, linlin, title="SQNR vs. Input Level", legend=true, #xyaxes=set(xmin=-120, xmax=0, ymin=0, ymax=120), xyaxes=set(ymax=120), #Clip infinite gains only labels=set(xaxis="Input Level (dBFS)", yaxis="SQNR (dB)"), ) return plot end function plotSNR!(plot, snrinfo, dsm::RealDSM; id::String="simulation", color=:green) simglyph = cons(:a, glyph=set(shape=:o, size=1, color=color, fillcolor=color)) #Access data: (amp, SNR) = snrinfo.vs_amp_sim (pk_amp, pk_SNR) = snrinfo.peak #Convert to waveforms: SNR = waveform(amp, SNR) infostr = @sprintf("peak SNR = %4.1fdB\n@ A = %4.1f dBFS (OSR = %d)", pk_SNR, pk_amp, dsm.OSR #orig. coords: (-25, 85) ) push!(plot, cons(:wfrm, SNR, simglyph, line=set(style=:dashdot, color=color, width=2), label="simulation"), cons(:atext, infostr, x=-25, y=85, align=:cr), ) if !isnothing(snrinfo.vs_amp_predicted) (amp_pred, SNR_pred) = snrinfo.vs_amp_predicted SNR_pred = waveform(amp_pred, SNR_pred) #Convert to waveform push!(plot, cons(:wfrm, SNR_pred, line=set(style=:solid, color=:red, width=2), label="theory"), ) end return plot end function plotSNR(snrinfo, dsm::RealDSM; id::String="simulation", color=:green) plot = plotSNR() plotSNR!(plot, snrinfo, dsm, id=id, color=color) return plot end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
4225
#RSDeltaSigmaPort: Base plot generation tools #------------------------------------------------------------------------------- #==Useful constants ===============================================================================# const linlin = cons(:a, xyaxes=set(xscale=:lin, yscale=:lin)) const linlog = cons(:a, xyaxes=set(xscale=:lin, yscale=:log)) const loglin = cons(:a, xyaxes=set(xscale=:log, yscale=:lin)) const loglog = cons(:a, xyaxes=set(xscale=:log, yscale=:log)) const dfltline = cons(:a, line=set(style=:solid, color=:blue, width=2)) #==Waveform builders ===============================================================================# function _wfrm__(x::Vector, y::Vector, sweepid::String) validatexy_vec(x, y) return DataF1(x,y) end _wfrm__(x::AbstractVector, y::Vector, sweepid::String) = _wfrm__(collect(x), y, sweepid) function _wfrm__(x::Array{Float64,2}, y::Array{Float64,2}, sweepid::String) validatexy_1param(x, y) N = size(x, 1) wfrm = fill(DataRS{DataF1}, PSweep(sweepid, collect(1:N))) do i return DataF1(x[i,:], y[i,:]) #Returns from implicit "do" function end return wfrm end """`waveform(x, y; sweepid="i")` Create a waveform object with a given string to identify the sweep. """ waveform(x, y; sweepid::String="i") = _wfrm__(x, y, sweepid) #==logsmooth ===============================================================================# """`(f, p) = logsmooth(X,inBin,nbin=8,n=3)` Smooth the fft, X, and convert it to dB. - Use nbin bins from 0 to 3*inBin, thereafter increase bin sizes by a factor of 1.1, staying less than 2^10. - For the n sets of bins inBin+[0:2], 2*inBin+[0:2], ... n*inBin+[0:2], don't do averaging. This way, the noise BW and the scaling of the tone and its harmonics are unchanged. Unfortunately, harmonics above the nth appear smaller than they really are because their energy is averaged over many bins. """ function logsmooth(X, inBin; nbin::Int=8, n::Int=3) #= Comment (MALaforge): VERIFYME - Goes infinite @inBin because startbin[] values jump back on 1st iteration of `for i in 1:n`. - Was this ententional to help user locate inBin? =# N=length(X); N2=div(N,2) f1 = mod(inBin-1, nbin) + 1 startbin = vcat(f1:nbin:inBin-1, inBin:inBin+2) for i in 1:n startbin = vcat(startbin, startbin[end]+1:nbin:i*inBin-1, i*inBin .+ (0:2)) end m = startbin[length(startbin)]+nbin while m < N2 startbin = vcat(startbin, m) nbin = min(nbin*1.1, 2^10) m = round(Int, m+nbin) end stopbin = vcat(startbin[2:length(startbin)] .- 1, N2) f = ((startbin .+ stopbin)/2 .- 1)/N p = zeros(size(f)) for i in 1:length(f) p[i] = dbp(norm(X[startbin[i]:stopbin[i]])^2 / (stopbin[i]-startbin[i]+1)) end return (f, p) end #==plotUsage() ===============================================================================# """`plotUsage(sv,colors=[:blue, :green, :red, :yellow])` Plot the element usage for a multi-elemet DAC. The colors are for sv = 1,-1,i,-i. """ function plotUsage(sv,colors=[:blue, :green, :red, :yellow]) (M, T) = size(sv) T2 = ceil(Int, (T+1)/2) plot = cons(:plot, linlin, title = "", legend=false, xyaxes=set(xmin=0, xmax=T, ymin=0, ymax=M), labels=set(xaxis="Time", yaxis="Element Number"), ) #Plot the grid x = [(0:T)'; (0:T)'] x = x[:] y = [zeros(1,T2); M*ones(2,T2); zeros(1,T2)] y = y[1:2*(T+1)] yw = waveform(x, y) #Convert to waveform push!(plot, cons(:wfrm, yw, line=set(style=:solid, color=:black, width=2), label=""), ) M2 = ceil(Int, (M+1)/2) x = [zeros(1,M2); T*ones(2,M2); zeros(1,M2)] x = x[1:2*(M+1)] y = [0:M; 0:M] y = y[:] yw = waveform(x, y) #Convert to waveform push!(plot, cons(:wfrm, yw, line=set(style=:solid, color=:black, width=2), label=""), ) @warn("TODO (plotUsage): draw polygons.") #=Create polygons #Not yet supported by EasyPlot (would have to manipulate InspectDR manually) for t in 1:T for i in 1:M if sv[i,t] == 1 fill([t-1 t-1 t t],[i-1 i i i-1],colors(1)); elseif sv(i,t) == -1 fill([t-1 t-1 t t],[i-1 i i i-1],colors(2)); elseif sv(i,t) == 1i fill([t-1 t-1 t t],[i-1 i i i-1],colors(3)); elseif sv(i,t) == -1i fill([t-1 t-1 t t],[i-1 i i i-1],colors(4)); end end end =# return plot end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
7146
#RSDeltaSigmaPort: Generate frequency spectrum plots #------------------------------------------------------------------------------- #==Frequency-spectrum plots ===============================================================================# function plotSpec() plot = cons(:plot, linlin, title = "Signal Spectrum", legend=true, xyaxes=set(xmin=0, xmax=0.5, ymin=-120, ymax=0), labels=set(xaxis="Normalized Frequency", yaxis="dBFS"), ) return plot end function plotSpec!(plot, sig; M::Int=1, id::String="signal", color=:blue) sig = conv2seriesmatrix2D(sig) M, N = size(sig) 𝑓pts = div(N,2)+1 #Only need half the spectrum 𝑓 = range(0, stop=0.5, length=𝑓pts) 𝑓 = ones(M)*𝑓' #2D frequency matrix for downstream algorithms spec = fft(sig)/(M*N/4) specdB = dbv.(spec[:,1:𝑓pts]) #Convert to waveforms: specdB = waveform(𝑓, specdB) push!(plot, cons(:wfrm, specdB, line=set(style=:solid, color=color, width=2), label=id), ) return plot end function plotSpec(sig; M::Int=1, id::String="signal", color=:blue) plot = plotSpec() return plotSpec!(plot, sig, id=id, color=color, M=M) end #==Modulator output spectrum ===============================================================================# function plotModSpectrum() plot = plotSpec() plot.title = "Modulator Output Spectrum" return plot end function plotModSpectrum!(plot, specinfo; id::String="Simulation", color=:blue) 𝑓 = specinfo.freq #Convert to waveforms: ePSD = waveform(𝑓, specinfo.ePSD) specdB = waveform(𝑓, specinfo.specdB) snr_str = @sprintf("SNR = %4.1fdB", specinfo.SNR) #orig. coords: (0.05,-10) nbw_str = @sprintf("NBW = %4.1E × 𝑓s", specinfo.NBW) #orig. coords: (0.5, -90) ann_str = string(snr_str, "\n", nbw_str) push!(plot, cons(:wfrm, specdB, line=set(style=:solid, color=color, width=2), label=id), cons(:wfrm, ePSD, line=set(style=:solid, color=:red, width=2), label="Expected PSD"), cons(:atext, ann_str, y=-90, reloffset=set(x=0.5), align=:cc), ) return plot end """`plotModSpectrum(sig, NTF, iband, f; M=1, title, id)` Generate plot of modulator output spectrum: - `sig`: Time domain ΔΣ signal. - `NTF`: - `f`: Bin location of input signal. - `M`: Number of modulator steps (= nlev-1). """ function plotModSpectrum(specinfo; id::String="Simulation", color=:blue) plot = plotModSpectrum() plotModSpectrum!(plot, specinfo, id=id, color=color) return plot end #==plotSpectrum() ===============================================================================# function plotSpectrum() plot = cons(:plot, loglin, title = "Smoothed Spectrum", legend=true, xyaxes=set(xmin=1e-3, xmax=0.5, ymin=-120, ymax=0), labels=set(xaxis="Normalized Frequency", yaxis=""), ) return plot end function plotSpectrum!(plot, X, fin; nbin::Int=8, n::Int=3, lw=1, color=:blue, id="") (f, p) = logsmooth(X, fin, nbin=nbin, n=n) pw = waveform(f, p) push!(plot, cons(:wfrm, pw, line=set(style=:solid, color=color, width=lw), label=id), ) return plot end """`plotSpectrum(X, fin, nbin=8, n=3, lw=1)` Plot a smoothed spectrum. """ function plotSpectrum(X, fin; nbin::Int=8, n::Int=3, lw=1, color=:blue, id="") plot = plotSpectrum() plotSpectrum!(plot, X, fin, nbin=nbin, n=n, lw=lw, color=color, id=id) return plot end #==plotExampleSpectrum ===============================================================================# """`plotExampleSpectrum(NTF, OSR=64, M=1, f0=0, quadrature=false, ampdB=-3, ftest=nothing, N=2^12, sizes=nothing)` #Inputs - `M`: Number of modulator steps (= nlev-1). - `ampdB`: Test tone amplitude, relative to full-scale. """ function plotExampleSpectrum(NTF; OSR::Int=64, M::Int=1, f0::Float64=0, quadrature::Bool=false, ampdB::Float64=-3.0, ftest=nothing, N::Int=2^12, sizes=nothing) #Computed defaults if isnothing(ftest) ftest = default_ftest(OSR, f0=f0, quadrature=quadrature) end fband = default_fband(OSR, f0=f0, quadrature=quadrature) delta = 2 usrsizes = sizes sizes = Dict{Symbol, Any}( #Defaults :lw => 1, #LineWidth :ms => 5, #MarkerSize :fs => 12, #FontSize :fw => "normal", #FontWeight ) if isa(usrsizes, Dict) #Overwrite with user supplied values push!(sizes, usrsizes...) end #Plot an example spectrum # fin = round(Int, ftest*N) local u, simresult if !quadrature phi0=π/2 #Switch from sin to cos (u, iftest) = genTestTone_sin(ampdB, ftest, M=M, phi0=phi0, N=N) simresult = simulateDSM(u, NTF, nlev=M+1) else (u, iftest) = genTestTone_quad(ampdB, ftest, M=M, N=N) simresult = simulateQDSM(u, NTF, nlev=M+1) end plot = cons(:plot, linlin, title = "Modulator Output Spectrum", legend=true, labels=set(xaxis="Normalized Frequency", yaxis="PSD [dBFS/NBW]"), xyaxes=set(ymin=-140, ymax=0), ) specinfo = calcSpecInfo(simresult.v, NTF, fband, ftest, M=M, quadrature=quadrature) if !quadrature if 0==f0 # set(plot, loglin, xyaxes=set(xmin=.001)) end #circular smoothing; not re-scaled spec_smoothed = circ_smooth(abs.(specinfo.spec0).^2, 16) A = dbv(specinfo.spec0[specinfo.itest+1]) #Convert to waveforms & add to plot: 𝑓 = specinfo.freq; 𝑓pts = length(𝑓) specw = waveform(𝑓, specinfo.specdB) spec_sw = waveform(𝑓, dbp.(spec_smoothed[1:𝑓pts])) ePSDw = waveform(𝑓, specinfo.ePSD) push!(plot, cons(:wfrm, specw, line=set(style=:solid, color=:cyan, width=2), label=""), cons(:wfrm, spec_sw, line=set(style=:solid, color=:blue, width=2), label=""), cons(:wfrm, ePSDw, line=set(style=:solid, color=:magenta, width=1), label=""), ) alignleft = f0<0.25 align = alignleft ? :tl : :tr annx = alignleft ? f0+0.5/OSR : f0-0.5/OSR tstr = @sprintf(" SQNR = %.1fdB\n @ A = %.1fdBFS\n & OSR = %.0f\n", specinfo.SNR, A, OSR ) nbwstr = @sprintf("NBW=%.1e ", specinfo.NBW) #TODO: use `sizes` atext: push!(plot, cons(:atext, tstr, x=annx, y=-5, align=align), cons(:atext, nbwstr, x=0.5, y=-135, align=:cr), ) else error("plotExampleSpectrum not implemented for quadrature modulators.") #= spec0 = fftshift(spec0/2) freq = range(-0.5, stop=0.5, length=N+1) freq = deleteat!(collect(freq), N+1) plot(freq,dbv(spec0),'c','Linewidth',1); spec_smoothed = circ_smooth(abs(spec0).^2, 16); plot(freq, dbp(spec_smoothed), 'b', 'Linewidth', 3); Snn = abs(evalTF(NTF,exp(2i*pi*freq))).^2 * 2/12 * (delta/M)^2; plot(freq, dbp(Snn*NBW), 'm', 'Linewidth', 1); SNR = calculateSNR(spec0(N/2+1+[f1_bin:f2_bin]),fin-f1_bin); msg = sprintf('SQNR = %.1fdB\n @ A=%.1fdBFS & OSR=%.0f\n', ... SNR, dbv(spec0(N/2+fin+1)), OSR ); if f0>=0 text(f0-0.05, -15, msg,'Hor','Right'); else text(f0+0.05, -15, msg,'Hor','Left'); end text(-0.5,-135,sprintf(' NBW=%.1e',NBW),'hor','left'); figureMagic([-0.5 0.5],0.125,2, [-140 0],10,2); =# end return plot end """`plotExampleSpectrum(dsm, NTF=nothing; ampdB=-3, ftest=nothing, N=2^12, sizes=sizes)` """ function plotExampleSpectrum(dsm::AbstractDSM, NTF=nothing; ampdB=-3.0, ftest=nothing, N=2^12, sizes=nothing) isnothing(NTF) && (NTF = synthesizeNTF(dsm)) return plotExampleSpectrum(NTF, OSR=dsm.OSR, M=dsm.M, f0=dsm.f0, quadrature=isquadrature(dsm), ampdB=ampdB, ftest=ftest, N=N, sizes=sizes ) end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
1557
#RSDeltaSigmaPort: Generate plots of internal state #------------------------------------------------------------------------------- #==Plot state maxima ===============================================================================# """`plotStateMaxima(u, ABCD, test_sig=nothing; nlev::Int=2, N::Int=10^5)` # Inputs - `N`: Number of points used to generate a test signal (only used if `test_sig=nothing`). """ function plotStateMaxima(u, ABCD, test_sig=nothing; nlev::Int=2, N::Int=10^5) title = "Simulated State Maxima"; color = :blue u = collect(u) if isnothing(test_sig) test_sig = ones(1,N) end nu, nq, order = get_nu_nq_order(test_sig, ABCD, nlev) maxima = zeros(order,length(u)) for i = 1:length(u) ui = u[i] simresult = simulateDSM(ui*test_sig, ABCD, nlev=nlev, trackmax=true) maxima[:,i] = simresult.xmax[:] if any(simresult.xmax .> 1e2) @warn("plotStateMaxima(): umax was too high.") umax = ui u = u[1:i] maxima = maxima[:,1:i] break end end plot = cons(:plot, linlog, title = title, legend=true, # xyaxes=set(xmin=0, xmax=0.6, ymin=1e-4, ymax=10), xyaxes=set(ymin=1e-4, ymax=10), labels=set(xaxis="DC input", yaxis="Peak value"), ) colors = range(HSV(0,1,1), stop=HSV(-360,1,1), length=order) for i in 1:order id = "state $i"; c = colors[i] simglyph = cons(:a, glyph=set(shape=:o, size=1, color=c, fillcolor=c)) _maxima = waveform(u, maxima[i,:]) push!(plot, cons(:wfrm, _maxima, simglyph, line=set(style=:dash, color=c, width=2), label=id), ) end return plot end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
3852
#RSDeltaSigmaPort: Generate time-domain plots of ΔΣ signals #------------------------------------------------------------------------------- #==Waveform builders ===============================================================================# function _stairs__(x::Vector, y::Vector, sweepid::String) validatexy_vec(x, y) if length(x) < 1 throw("Does not support zero-length arrays") end xs = similar(x, 2*length(x)) ys = similar(y, 2*length(y)) ii = io = 1 while ii < length(x) xs[io] = x[ii] xs[io+1] = x[ii+1] ii += 1; io +=2 end if ii <= length(x) #last point Δx = 1 #Step size (if x has a single point) if length(x) > 1; Δx = x[end]-x[end-1]; end xs[io] = x[ii] xs[io+1] = x[ii]+Δx #Use final step size end ii = io = 1 while ii <= length(y) _y = y[ii] ys[io] = _y ys[io+1] = _y ii += 1; io +=2 end return DataF1(xs, ys) end function _stairs__(x::Array{Float64,2}, y::Array{Float64,2}, sweepid::String) validatexy_1param(x, y) N = size(x, 1) wfrm = fill(DataRS{DataF1}, PSweep(sweepid, collect(1:N))) do i return _stairs__(x[i,:], y[i,:], "") #Returns from implicit "do" function end return wfrm end """`wfrm_stairs(x, y; sweepid="i")` Create a staircase-waveform object with a given string to identify the sweep. """ wfrm_stairs(x, y; sweepid::String="i") = _stairs__(x, y, sweepid) """`(values, sticks) = lollipop(x, y; ybot=0.0)` Generate waveforms suitable for "lollipop" plots (o's and sticks) """ function lollipop(x, y; ybot::Float64=0.0) #Make sure we have column vectors of Float64 (Required by InspectDR): x = Float64.(x[:]); y = Float64.(abs.(y[:])) len = length(x) if length(y) != len error("x & y array lengths must match.") end #Generate sticks xsticks = [x'; x'; fill(NaN, (1,len))] ysticks = [y'; fill(ybot, (1,len)); fill(NaN, (1,len))] xsticks = xsticks[:]; ysticks = ysticks[:] #Need to re-sort as vectors #Generate waveforms: values = waveform(x, y) sticks = waveform(xsticks, ysticks) return (values, sticks) end #==Time domain plots of modulator ===============================================================================# function plotModTransient(; legend::Bool=true) plot = cons(:plot, linlin, title = "Modulator Input & Output", legend=legend, labels=set(xaxis="Sample Number", yaxis="Amplitude [V]"), ) return plot end function plotModTransient!(plot, sig; color=:blue, label::String="") #Ensure we have a 2D-`Array`, not a `Vector`: sig = conv2seriesmatrix2D(sig) #Generate matrix of sample numbers: M = size(sig,1) #Number of rows (ex: quantizers) N = size(sig,2) #Number of samples n = 1:N sn = ones(Float64, M)*n' #Matrix of "sample number" (Use Float64s for downstream functions) #Generate staircase waveform of signal: sig = wfrm_stairs(sn, sig) push!(plot, cons(:wfrm, sig, line=set(style=:solid, color=color, width=2), label=label), ) return plot end function plotModTransient(inputSig, outputSig; legend::Bool=true, color=:blue) plot = plotModTransient(legend=legend) plotModTransient!(plot, outputSig, color=color, label="output") plotModTransient!(plot, inputSig, color=:red, label="input") return plot end """`plotLollipop(x, y; color=:blue, lw=2.0, ybot=0.0, label="", legend=false)` Generate "lollipop" plot (o's and sticks). """ function plotLollipop(x, y; color=:blue, lw::Float64=2.0, ybot::Float64=0.0, label="", legend=false) plot = cons(:plot, linlin, title = "Time-domain", legend=legend, labels=set(xaxis="Time", yaxis="Amplitude"), ) (values, sticks) = lollipop(x, y, ybot=ybot) simglyph = cons(:a, glyph=set(shape=:o, size=1.5, color=color, fillcolor=color)) push!(plot, cons(:wfrm, sticks, line=set(style=:solid, color=color, width=lw), label=label), cons(:wfrm, values, simglyph, line=set(style=:none, color=color, width=lw), label=label), ) return plot end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
2822
#RSDeltaSigmaPort: Generate plots of the complex Z-plane #------------------------------------------------------------------------------- #==Waveform builders ===============================================================================# function plot_unitcircle!(plot; color=:black, width=2, nseg::Int=360) Θ = range(0, stop=2π, length=nseg+1) cplxcircle = exp.((2π*j)*Θ) circle = DataF1(real(cplxcircle), imag(cplxcircle)) push!(plot, cons(:wfrm, circle, line=set(style=:solid, color=color, width=width)) ) return plot end #==Pole-zero plots ===============================================================================# #Create empty pole-zero plot function plotPZ() plot = cons(:plot, title = "Pole-Zero Plot", legend=false, xyaxes=set(xscale=:lin, yscale=:lin, xmin=-1.1, xmax=1.1, ymin=-1.1, ymax=1.1), labels=set(xaxis="Real", yaxis="Imag"), ) plot_unitcircle!(plot) return plot end """`function plotPZ!(H,color=:black,markersize=5,list=false)` Plot the poles and zeros of a transfer function. If list=true, a list of the poles and zeros is superimposed on the plot. """ function plotPZ!(plot, H::ZPKData; color=:blue, markersize=2, list::Bool=false) isVector = isa(color, Vector) color_pole = isVector ? color[1] : color color_zero = isVector ? color[end] : color attrib_poles = cons(:a, glyph=set(shape=:x, color=color_pole, size=markersize), line=set(style=:none, width=2) ) attrib_zeros = cons(:a, glyph=set(shape=:o, color=color_zero, size=markersize), line=set(style=:none, width=2) ) z, p, k = _zpkdata(H) # Plot x and o for poles and zeros, respectively: push!(plot, cons(:wfrm, DataF1(real(p), imag(p)), attrib_poles)) if !isempty(z) #Add zeros push!(plot, cons(:wfrm, DataF1(real(z), imag(z)), attrib_zeros)) end #= if list # List the poles and zeros p = cplxpair(p); y = 0.05*(ceil(length(p)/2)+1); str = 'Poles: '; text( 0, y, str, 'Hor', 'Right', 'Ver', 'Mid'); y = y - 0.1; for i = 1:2:length(p); if abs(imag(p(i))) < 1e-6 str = sprintf('%+.4f ', real(p(i)) ); else str = sprintf( '%+.4f+/-j%.4f ', real(p(i)), abs(imag(p(i))) ); end text( 0, y, str, 'Hor', 'Right', 'Ver', 'Mid'); y = y - 0.1; end if !isempty(z) z = z( !isnan(z) && !isinf(z) ); z = cplxpair(z); y = 0.05*(ceil(length(z)/2)+1); str = ' Zeros:'; text( 0, y, str, 'Hor', 'Left', 'Ver', 'Mid'); y = y - 0.1; for i = 1:2:length(z); if abs(imag(z(i))) < 1e-6 str = sprintf('%+.4f ', real(z(i)) ); else str = sprintf( ' %+.4f+/-j%.4f', real(z(i)), abs(imag(z(i))) ); end text( 0, y, str, 'Hor', 'Left', 'Ver', 'Mid'); y = y - 0.1; end end end =# return plot end plotPZ(H::ZPKData, args...; kwargs...) = plotPZ!(plotPZ(), H::ZPKData, args...; kwargs...) #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
913
#RSDeltaSigmaPort: Compute power values. #------------------------------------------------------------------------------- """`dbm(v,R=50) = 10*log10(v^2/R*1000)` The equivalent in dBm of an RMS voltage v """ dbm(v; R::Float64=50.0) = 10*log10.(abs.(v .^ 2)/R) .+ 30; """`dbp(x) = 10*log10(x)` The dB equivalent of the power x """ dbp(x) = 10*log10.(abs.(x)) """`dbv(x) = 20*log10(abs(x))` The dB equivalent of the voltage x """ dbv(x) = 20*log10.(abs.(x)) "`y = rms(x; no_dc=false)`" function rms(x; no_dc::Bool=false) if no_dc x = x - mean(x) end return norm(x)/sqrt(length(x)) end """`v = undbm(p, z=50) = sqrt(z*10^(p/10-3))` RMS voltage equivalent to a power p in dBm """ undbm(p; z::Float64=50.0) = sqrt.(z*10 .^ (p/10 .- 3)) """`y = undbp(x)` Convert x from dB to a power """ undbp(x) = 10 .^ (x/10) """`y = undbv(x)` Convert x from dB to a voltage """ undbv(x) = 10 .^ (x/20) #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
1917
#RSDeltaSigma: Quantizer functionnality #------------------------------------------------------------------------------- #Version from simulateDSM.m #------------------------------------------------------------------------------- #VERIFYME: Did this one actually get called? Was the other version the one being called?? """`ds_quantize_DSM(y,n)` Quantize y to: - an odd integer in [-n+1, n-1], if n is even, or - an even integer in [-n, n], if n is odd. This definition gives the same step height for both mid-rise and mid-tread quantizers. """ function ds_quantize_DSM(y, n::Int) if mod(n,2)==0 #mid-rise quantizer v = 2*floor.(0.5*y) .+ 1 else #mid-tread quantizer v = 2*floor.(0.5*(y .+ 1)) end #Limit the output for qi in 1:length(n) #Loop for multiple quantizers L = n[qi]-1 i = v[qi,:] .> L if any(i) v[qi,i] .= L end i = v[qi,:] .< -L if any(i) v[qi,i] .= -L end end return v end #Pretty sure mod(n,2) code needs to be adapted for Vector: ds_quantize_DSM(y, n::Vector{Int}) = throw(ErrorException("ds_quantizer: does not support n::Vector")) #Version from ds_quantize.m: #------------------------------------------------------------------------------- #= function v = ds_quantize(y,n) %v = ds_quantize(y,n=2) %Quantize y to % an odd integer in [-n+1, n-1], if n is even, or % an even integer in [-n+1, n-1], if n is odd. %This definition gives the same step height for both mid-rise %and mid-tread quantizers. %n can be a column vector which specifies how to quantize the rows of y if nargin<2 n=2; end if length(n)==1 n = n*ones(size(y)); elseif size(n,1)==size(y,1) n = n*ones(1,size(y,2)); end i = rem(n,2)==0; v = zeros(size(y)); v(i) = 2*floor(0.5*y(i))+1; % mid-rise quantizer v(~i) = 2*floor(0.5*(y(~i)+1)); % mid-tread quantizer % Limit the output L = n-1; for m=[-1 1] i = m*v>L; if any(i(:)) v(i) = m*L(i); end end =# #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
12761
#RSDeltaSigma: realize transfer functions #------------------------------------------------------------------------------- #==Calcualtions for realizeNTF ===============================================================================# function _calc_agb!(::DS{:CRFB}, a::Array{Float64}, g::Array{Float64}, b::Array{Float64}, order::Int, ntf_z, ntf_p, zSet, T, hasSTF::Bool) (order2, isodd, Δodd) = orderinfo(order) #Find g #Assume the roots are ordered, real first, then cx conj. pairs for i in 1:order2 g[i] = 2*(1-real(ntf_z[2*i-1+Δodd])) end L1 = zeros(ComplexF64, 1, order*2) #Form the linear matrix equation a*T*=L1 for i in 1:order*2 z = zSet[i] #L1(z) = 1-1/H(z) L1[i] = 1 - evalRPoly(ntf_p,z) ./ evalRPoly(ntf_z,z) Dfactor = (z-1)/z product=1 for j in order:-2:(1+Δodd) product = z ./ evalRPoly(ntf_z[(j-1):j],z) .* product T[j,i] = product*Dfactor T[j-1,i] = product end if isodd T[1,i]=product/(z-1) end end a[:] = -real.(L1/T) if !hasSTF b[keys(a)] = a[:] b[order+1] = 1 end return end function _calc_agb!(::DS{:CRFF}, a::Array{Float64}, g::Array{Float64}, b::Array{Float64}, order::Int, ntf_z, ntf_p, zSet, T) (order2, isodd, Δodd) = orderinfo(order) #Find g #Assume the roots are ordered, real first, then cx conj. pairs for i in 1:order2 g[i] = 2*(1-real(ntf_z[2*i-1+odd])) end L1 = zeros(ComplexF64, 1, order*2) #Form the linear matrix equation a*T*=L1 for i in 1:order*2 z = zSet[i] #L1(z) = 1-1/H(z) L1[i] = 1 - evalRPoly(ntf_p,z) ./ evalRPoly(ntf_z,z) if isodd Dfactor = z-1 product = 1/Dfactor T[1,i] = product else Dfactor = (z-1)/z product=1 end for j in 1+odd:2:order product = z ./ evalRPoly(ntf_z[j:j+1],z) .* product T[j,i] = product*Dfactor T[j+1,i] = product end end a[:] = -real.(L1/T) if !hasSTF b[:] = [1 zeros(1,order-1) 1] end return end #= case 'CIFB' %Assume the roots are ordered, real first, then cx conj. pairs %Note ones which are moved significantly. if any( abs(real(ntf_z)-1) > 1e-3) fprintf(stderr,'%s Warning: The ntf''s zeros have had their real parts set to one.\n', mfilename); end ntf_z = 1 + 1i*imag(ntf_z); for i=1:order2 g(i) = imag(ntf_z(2*i-1+odd))^2; end L1 = zeros(1,order); %Form the linear matrix equation a*T*=L1 for i=1:order*2 z = zSet(i); %L1(z) = 1-1/H(z) L1(i) = 1-evalRPoly(ntf_p,z)/evalRPoly(ntf_z,z); Dfactor = (z-1); product = 1; for j=order:-2:(1+odd) product = product/evalRPoly(ntf_z((j-1):j),z); T(j,i) = product*Dfactor; T(j-1,i) = product; end if( odd ) T(1,i) = product/(z-1); end end a = -real(L1/T); if isempty(stf) b = a; b(order+1) = 1; end case 'CIFF' %Assume the roots are ordered, real first, then cx conj. pairs %Note ones which are moved significantly. if any( abs(real(ntf_z)-1) > 1e-3 ) fprintf(stderr,'%s Warning: The ntf''s zeros have had their real parts set to one.\n', mfilename); end ntf_z = 1 + 1i*imag(ntf_z); for i=1:order2 g(i) = imag(ntf_z(2*i-1+odd))^2; end L1 = zeros(1,order); %Form the linear matrix equation a*T*=L1 for i=1:order*2 z = zSet(i); %L1(z) = 1-1/H(z) L1(i) = 1-evalRPoly(ntf_p,z)/evalRPoly(ntf_z,z); Dfactor = (z-1); if( odd ) product = 1/(z-1); T(1,i) = product; else product = 1; end for j=odd+1:2:order-1 product = product/evalRPoly(ntf_z(j:j+1),z); T(j,i) = product*Dfactor; T(j+1,i) = product; end end a = -real(L1/T); if isempty(stf) b = [ 1 zeros(1,order-1) 1]; end case 'CRFBD' %Find g %Assume the roots are ordered, real first, then cx conj. pairs for i=1:order2 g(i) = 2*(1-real(ntf_z(2*i-1+odd))); end L1 = zeros(1,order); %Form the linear matrix equation a*T*=L1 for i=1:order*2 z = zSet(i); %L1(z) = 1-1/H(z) L1(i) = 1-evalRPoly(ntf_p,z)/evalRPoly(ntf_z,z); Dfactor = (z-1); product=1/z; for j=order:-2:(1+odd) product = z/evalRPoly(ntf_z((j-1):j),z)*product; T(j,i) = product*Dfactor; T(j-1,i) = product; end if( odd ) T(1,i)=product*z/(z-1); end end a = -real(L1/T); if isempty(stf) b = a; b(order+1) = 1; end case 'CRFFD' %Find g %Assume the roots are ordered, real first, then cx conj. pairs for i=1:order2 g(i) = 2*(1-real(ntf_z(2*i-1+odd))); end %zL1 = z*(1-1/H(z)) zL1 = zSet .* (1-1./evalTF(ntf,zSet)); %Form the linear matrix equation a*T*=zL1 for i=1:order*2 z = zSet(i); if( odd ) Dfactor = (z-1)/z; product = 1/Dfactor; T(1,i) = product; else Dfactor = z-1; product=1; end for j=1+odd:2:order product = z/evalRPoly(ntf_z(j:j+1),z)*product; T(j,i) = product*Dfactor; T(j+1,i) = product; end end a = -real(zL1/T); if isempty(stf) b = [ 1 zeros(1,order-1) 1]; end case 'PFF' %Find g %Assume the roots are ordered, real first, then cx conj. pairs % with the secondary zeros after the primary zeros for i=1:order2 g(i) = 2*(1-real(ntf_z(2*i-1+odd))); end % Find the dividing line between the zeros theta0 = abs(angle(ntf_z(1))); % !! 0.5 radians is an arbitrary separation !! i = find( abs(abs(angle(ntf_z)) - theta0) > 0.5 ); order_1 = i(1)-1; order_2 = order-order_1; if length(i) ~= order_2 keyboard error('For the PFF form, the NTF zeros must be sorted into primary and secondary zeros'); end odd_1 = mod(order_1,2); odd_2 = mod(order_2,2); L1 = zeros(1,order); %Form the linear matrix equation a*T*=L1 for i=1:order*2 z = zSet(i); %L1(z) = 1-1/H(z) L1(i) = 1-evalRPoly(ntf_p,z)/evalRPoly(ntf_z,z); if( odd_1 ) Dfactor = z-1; product = 1/Dfactor; T(1,i) = product; else Dfactor = (z-1)/z; product=1; end for j=1+odd_1:2:order_1 product = z/evalRPoly(ntf_z(j:j+1),z)*product; T(j,i) = product*Dfactor; T(j+1,i) = product; end if( odd_2 ) Dfactor = z-1; product = 1/Dfactor; T(order_1+1,i) = product; else Dfactor = (z-1)/z; product=1; end for j=order_1+1+odd_2:2:order product = z/evalRPoly(ntf_z(j:j+1),z)*product; T(j,i) = product*Dfactor; T(j+1,i) = product; end end a = -real(L1/T); if isempty(stf) b = [ 1 zeros(1,order_1-1) 1 zeros(1,order_2-1) 1]; end case 'Stratos' % code copied from case 'CRFF': %Find g %Assume the roots are ordered, real first, then cx conj. pairs for i=1:order2 g(i) = 2*(1-real(ntf_z(2*i-1+odd))); end % code copied from case 'CIFF': L1 = zeros(1,order); %Form the linear matrix equation a*T*=L1 for i=1:order*2 z = zSet(i); %L1(z) = 1-1/H(z) L1(i) = 1-evalRPoly(ntf_p,z)/evalRPoly(ntf_z,z); Dfactor = (z-1); if( odd ) product = 1/(z-1); T(1,i) = product; else product = 1; end for j=odd+1:2:order-1 product = product/evalRPoly(ntf_z(j:j+1),z); T(j,i) = product*Dfactor; T(j+1,i) = product; end end a = -real(L1/T); if isempty(stf) b = [ 1 zeros(1,order-1) 1]; end case 'DSFB' %Find g %Assume the roots are ordered, real first, then cx conj. pairs for i=1:(order+odd)/2 -1 g(i) = tan( angle( ntf_z(2*i-1+odd) ) /2 ) ^ 2; end if ~odd g(order/2) = 2*(1 - cos( angle( ntf_z(order) ) )); end L1 = zeros(1,order); % Form the linear matrix equation a*T = L1 for i=1:order*2 z = zSet(i); %L1(z) = 1-1/H(z) L1(i) = 1-evalRPoly(ntf_p,z)/evalRPoly(ntf_z,z); if odd product = 1/(z-1); T(order,i) = product; else Dfactor = (z-1)^2 + g(order/2)*z; T(order,i) = (z-1)/Dfactor; product = (z+1)/Dfactor; T(order-1,i) = product; end for j=order+odd-2:-2:1 Dfactor = (z-1)^2 + g(j/2)*(z+1)^2; product = product/Dfactor; T(j,i) = product*(z^2-1); product = product*(z+1)^2; T(j-1,i) = product; end end a = -real(L1/T); if isempty(stf) b = a; b(order+1) = 1; end otherwise error( 'Unsupported form %s', form ); end =# #==realizeNTF ===============================================================================# """`[a,g,b,c] = realizeNTF(ntf,form='CRFB',stf=nothing)` Convert a noise transfer function into coefficients for the desired structure. Supported structures are: - CRFB: Cascade of resonators, feedback form. - CRFF: Cascade of resonators, feedforward form. - CIFB: Cascade of integrators, feedback form. - CIFF: Cascade of integrators, feedforward form. - CRFBD: CRFB with delaying quantizer. - CRFFD: CRFF with delaying quantizer. - PFF: Parallel feed-forward. - Stratos: A CIFF-like structure with non-delaying resonator feedbacks, (contributed in 2007 by Jeff Gealow) - DSFB: Cascade of double-sampled integrators, feedback form. See the accompanying documentation for block diagrams of each structure The order of the NTF zeros must be (real, complex conj. pairs). The order of the zeros is used when mapping the NTF onto the chosen topology. stf is a zpk transfer function The basic idea is to equate the loop filter at a set of points in the z-plane to L1 = 1-1/ntf at those points. """ function realizeNTF(ntf, form::Symbol=:CRFB, stf=nothing) #Code common to all functions: (ntf_z, ntf_p) = _zpkdata(ntf) order = length(ntf_p) (order2, isodd, Δodd) = orderinfo(order) strform = string(form) isFF = length(strform) >= 4 && ("FF" == strform[3:4]) ntf_z = realfirst(ntf_z); ntf_p = realfirst(ntf_p) a = zeros(1, order) g = zeros(1, order2) b = zeros(1, order+1) c = ones(1, order) #Choose a set of points in the z-plane at which to try to make L1 = 1-1/H #I don't know how to do this properly, but the code below seems to work #for order <= 11 N = 200 min_distance = 0.09 C = zeros(N) j = 1 for i=1:N z = 1.1*exp(2i*pi*i/N) if all( abs.(ntf_z .- z) .> min_distance ) C[j] = z j = j+1 end end deleteat!(C, j:length(C)) zSet = C T = zeros(ComplexF64, order,2*order) _calc_agb!(DS(form), a, g, b, order, ntf_z, ntf_p, zSet, T, stf != nothing) if stf != nothing #Compute the TF from each feed-in to the output #and solve for coefficients which yield the best match #THIS CODE IS NOT OPTIMAL, in terms of computational efficiency. stfList = Array{Any}(undef, (1,order+1)) for i in 1:order+1 bi = zeros(1,order+1); bi[i]=1 ABCD = stuffABCD(a,g,bi,c,form) if isFF ABCD[1,order+2] = -1 #b1 is used to set the feedback end (junk, stfList[i]) = calculateTF(ABCD) end #Build the matrix equation b A = x and solve it. A = zeros(order+1,length(zSet)) for i = 1:order+1 A[i,:] = evalTF(stfList[i],zSet) end x = evalTF(stf,zSet) b[:] = real.(x'/A) end return (a, g, b, c) end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
6839
#RSDeltaSigma: realize continuous-time NTF #------------------------------------------------------------------------------- #==Helper functions ===============================================================================# #==realizeNTF_ct ===============================================================================# """`(ABCDc, tdac2) = realizeNTF_ct(NTF, form='FB', tdac, ordering=[1:n], bp=zeros(...), ABCDc)` Realize a NTF with a continuous-time loop filter. # Output - `ABCDc`: A state-space description of the CT loop filter - `tdac2`: A matrix with the DAC timings, including ones that were automatically added. # Input Arguments - `NTF`: A noise transfer function in pole-zero form. - `form`: `= {:FB, :FF}` Specifies the topology of the loop filter. - `-->` For the `:FB` structure, the elements of `Bc` are calculated so that the sampled pulse response matches the `L1` impulse respnse. - `-->` For the `:FF` structure, `Cc` is calculated. - `tdac`: The timing for the feedback DAC(s). - `-->` If `tdac[1]>=1`, direct feedback terms are added to the quantizer. - `-->` Multiple timings (1 or more per integrator) for the `:FB` topology can be specified by making `tdac` a cell array, e.g. `tdac = { [1,2]; [1 2]; {[0.5 1],[1 1.5]}; []}`. - `-->` In above example, the first two integrators have dacs with `[1,2]` timing, the third has a pair of dacs, one with `[0.5 1]` timing and the other with `[1 1.5]` timing, and there is no direct feedback DAC to the quantizer - `ordering`: A vector specifying which NTF zero-pair to use in each resonator. Default is for the zero-pairs to be used in the order specified in the NTF. - `bp`: A vector specifying which resonator sections are bandpass. The default (zeros(...)) is for all sections to be lowpass. - `ABCDc`: The loop filter structure, in state-space form. If this argument is omitted, ABCDc is constructed according to `form`. """ function realizeNTF_ct(ntf, form=:FB, tdac=[0 1], ordering=1:0, bp=Int[], ABCDc=Float64[]) (ntf_z, ntf_p) = _zpkdata(ntf, 1) ntf_z = deepcopy(ntf_z); ntf_p = deepcopy(ntf_p) #Don't modify original ntf_z = realfirst(ntf_z); ntf_p = realfirst(ntf_p) #VERIFYME: Expected by realizeNTF... here too? ntf_z_orig = deepcopy(ntf_z) #VERIFYME: Doesn't get modified to match legacy code. Intentional or omission?? order = length(ntf_p) (order2, isodd, Δodd) = orderinfo(order) if isempty(ordering); ordering = 1:order2; end if isempty(bp); bp = zeros(Int, order2); end #compensate for limited accuracy of zero calculation ntf_z[findall( abs.(ntf_z .- 1) .< eps(1.0)^(1/(1+order)) )] .= 1.0 #ntf_z_orig=ntf_z #??? multi_tmg = (eltype(tdac)<:Array) if multi_tmg if size(tdac) != (order+1,) error("For multi-array tdac, tdac be a vector of length `order+1`") end if form != :FB error("Currently only supporting form=:FB for multi-array tdac") end else if size(tdac) != (1, 2) #TODO: Update message error("For non cell array tdac, size(tdac) must be (1, 2)") end end n_direct = 0 n_extra = 0 tdac2 = Float64[-1 -1] if !multi_tmg #Need direct terms for every interval of memory in the DAC n_direct = ceil(Int, tdac[2]) - 1 if ceil(Int, tdac[2]) - floor(Int, tdac[1]) > 1 n_extra = n_direct-1 #tdac pulse spans a sample point else n_extra = n_direct end tdac2 = Float64[ -1 -1; tdac; 0.5*ones(n_extra,1)*[-1 1] .+ cumsum(ones(n_extra,2), dims=1) ] end if isempty(ABCDc) ABCDc = zeros(order+1, order+2); #Stuff the A portion if isodd ABCDc[1,1] = real( log( ntf_z[1] ) ) ABCDc[2,1] = 1 end for i = 1:order2 n = bp[i] i1 = 2*i + Δodd - 1 zi = 2*ordering[i] + Δodd - 1 w = abs( angle( ntf_z[zi] ) ) ABCDc[i1 .+ [0 1 2], i1 .+ [0 1]] = [ 0 -w^2; 1 0; n 1-n; ] end ABCDc[1,order+1] = 1 ABCDc[1,order+2] = -1 #2006.10.02 Changed to -1 to make FF STF have +ve gain at DC end Ac = ABCDc[1:order, 1:order] local Bc, Cc, Dc, tp if :FB == form Cc = ABCDc[[order+1],1:order] if !multi_tmg Bc = [eye(order) zeros(order,1)] Dc = [zeros(1,order) 1] tp = repeat(tdac,order+1,1) else #Assemble tdac2, Bc and Dc tdac2 = Float64[-1 -1] Bc = ones(order, 0) #0-column Bci = [eye(order) zeros(order,1)] Dc = ones(1, 0) Dci = [zeros(1,order) 1] for i in 1:length(tdac) tdi = tdac[i] if (eltype(tdi)<:Array) for j in 1:length(tdi) tdj = tdi[j] tdac2 = [tdac2; tdj] Bc = [Bc Bci[:,i]] Dc = [Dc Dci[:,i]] end elseif !isempty(tdi) tdac2 = [tdac2; tdi] Bc = [Bc Bci[:,i]] Dc = [Dc Dci[:,i]] end end tp = tdac2[2:end,:] end elseif :FF == form Cc = [eye(order); zeros(1,order)] Bc = [-1; zeros(order-1,1)] Dc = [zeros(order,1); 1] tp = tdac #2008-03-24 fix from Ayman Shabra else error("Sorry, no code for form ", form) end #Sample the L1 impulse response n_imp = ceil(Int, 2*order + maximum(tdac2[:,2]) + 1) y = impL1(ntf,n_imp) sys_c = _ss( Ac, Bc, Cc, Dc ) yy = pulse(sys_c, tp, 1.0, 1.0*n_imp, true) yy = squeeze(yy) #Endow yy with n_extra extra impulses. #These will need to be implemented with n_extra extra DACs. #!! Note: if t1=int, matlab says pulse(sys) @t1 ~=0 #!! This code corrects this problem. if n_extra>0 y_right = padb([zeros(1,n_extra+1); eye(n_extra+1)], n_imp+1) #Replace the last column in yy with an ordered set of impulses yy = [yy[:,1:end-1] y_right[:,end:-1:1]] end #Solve for the coefficients: x = yy\y if norm(yy*x - y) > 1e-4 @warn("Pulse response fit is poor.") end local Bc2, Dc2 if :FB == form if !multi_tmg Bc2 = [ x[1:order] zeros(order,n_extra) ] Dc2 = x[order+1:end]' else BcDc = [Bc; Dc] i = findall(BcDc .!= 0) BcDc[i] = x Bc2 = BcDc[1:end-1,:] Dc2 = BcDc[[end],:] end elseif :FF == form Bc2 = [Bc zeros(order,n_extra)] Cc = x[1:order]' Dc2 = x[order+1:end]' else error("No code for form \"$form\"") end Dc1 = 0 Dc = [Dc1 Dc2] Bc1 = [1; zeros(order-1,1)] Bc = [Bc1 Bc2] #Scale Bc1 for unity STF magnitude at f0 fz = angle.(ntf_z_orig)/(2π) f1 = fz[1] ibz = findall(abs.(fz .- f1) .<= abs.(fz .+ f1)) fz = fz[ibz] f0 = mean(fz) if minimum(abs.(fz)) < 3*minimum(abs.(fz .- f0)) f0 = 0 end #MALaforge: FIXME: ss->zpk conversion appears not to be numerically stable L0c = _zpk(_ss(Ac,Bc1,Cc,Dc1)) #Hard-coded approximation of L0c's poly-ratio representation: msg = "FIXME: Using hard-coded system to get realizeNTF_ct to work." msg *= "\nThis is NOT ok; results are probably not useful." @warn(msg) L0c = ControlSystems.tf([1], [1, 0, 0.0057829713287632966, 0]) (_z, _p, _k) = ControlSystems.zpkdata(L0c) L0c = _zpk(_z, _p, _k) G0 = evalTFP(L0c, ntf, f0) Bc[:,1] = Bc[:,1]/abs.(G0) ABCDc = [Ac Bc; Cc Dc] return (ABCDc, tdac2) end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
4758
#RSDeltaSigma: time-domain signal generators #------------------------------------------------------------------------------- #==Input signal generators ===============================================================================# """`genTestTone_sin()` Limiation: If N is small relative to ftest (you don't generate a whole period), iftest gets rounded to nothing. Typical ampdB: -3dB """ function genTestTone_sin(ampdB::Float64, ftest::Float64; M::Int=1, phi0::Float64=0.0, N::Int=2^12) amp = undbv(ampdB) #Test tone amplitude, relative to full-scale. iftest = round(Int, ftest*N) u = amp*M*sin.((2π/N)*iftest * (0:N-1) .+ phi0) return (u, iftest) end function genTestTone_quad(ampdB::Float64, ftest::Float64; M::Int=1, phi0::Float64=0.0, N::Int=2^12) amp = undbv(ampdB) #Test tone amplitude, relative to full-scale. iftest = round(Int, ftest*N) u = amp*M*exp.((2π*j/N)*iftest * (0:N-1) .+ phi0) return (u, iftest) end genTestTone(dsm::RealDSM, ampdB::Float64, ftest::Float64; phi0::Float64=0.0, N::Int=2^12) = genTestTone_sin(ampdB, ftest, M=dsm.M, phi0=phi0, N=N) genTestTone(dsm::QuadratureDSM, ampdB::Float64, ftest::Float64; phi0::Float64=0.0, N::Int=2^12) = genTestTone_quad(ampdB, ftest, M=dsm.M, phi0=phi0, N=N) #==impL1 ===============================================================================# """`y=impL1(ntf, n=10)` Compute the impulse response from the comparator output to the comparator input for the given NTF. n is the (optional) number of points (10). This function is useful when verifying the realization of a NTF with a specified topology. """ function impL1(ntf::ZPKData, n::Int=10) (z, p) = _zpkdata(ntf) lf_den = padr(poly(z), length(p)+1) lf_num = lf_den .- poly(p) if any(imag.(vcat(lf_num, lf_den)) .!= 0) #Complex loop filter lfr_den = real.( conv(lf_den, conj.(lf_den)) ) lfr_num = conv(lf_num, conj.(lf_den)) lf_i = _tf(real.(lfr_num), lfr_den, 1) lf_q = _tf(imag.(lfr_num), lfr_den, 1) (yi,) = _impulse(lf_i, n) (yq,) = _impulse(lf_q, n) y = yi .+ j*yq else lf_num = real.(lf_num); lf_den = real(lf_den) (y,) = _impulse(_tf(lf_num, lf_den, 1), n) end return y end #==pulse ===============================================================================# """`y = pulse(S, tp=[0 1], dt=1, tfinal=10, nosum=true)` Calculate the sampled pulse response of a ct system. `tp` may be an array of pulse timings, one for each input. # Outputs - `y` The pulse response. # Inputs - `S`: An LTI object specifying the system. - `tp`: An nx2 array of pulse timings. - `dt`: The time increment. - `tfinal`: The time of the last desired sample. - `nosum`: A flag indicating that the responses are not to be summed. """ function pulse(S, tp=[0 1], dt::Float64=1.0, tfinal::Float64=10.0, nosum::Bool=false) #Check the arguments if isdiscrete(S) error("S must be a cts-time system.") end #Compute the time increment dd = 1 for i in 1:prod(size(tp)) (x, di) = rat(tp[i],1e-3) dd = lcm(di,dd); end (x, ddt) = rat(dt,1e-3) (x, df) = rat(tfinal,1e-3) delta_t = 1 / lcm( dd, lcm(ddt,df) ) delta_t = max(1e-3, delta_t) #Put a lower limit on delta_t (y1, ty1, xy1) = step(S, 0:delta_t:tfinal) #= #DEBUG p=cons(:plot, title="") for i in 1:size(y1, 3) push!(p, cons(:wfrm, waveform(collect(ty1[:]), y1[:,1,i]))) end displaygui(p) =# nd = round(Int, dt/delta_t) nf = round(Int, tfinal/delta_t) ndac = size(tp,1) ni = size(S.B,2) if mod(ni,ndac) != 0 error("The number of inputs must be divisible by the number of dac timings.") #This requirement comes from the complex case, where the number of inputs #is 2 times the number of dac timings. I think this could be tidied up. end nis = div(ni,ndac) #Number of inputs grouped together with a common DAC timing # (2 for the complex case) if !nosum #Sum the responses due to each input set y = zeros(array_round(tfinal/dt+1),size(S.C,1),nis) else y = zeros(array_round(tfinal/dt+1),size(S.C,1),ni) end for i = 1:ndac n1 = round(Int, tp[i,1]/delta_t) n2 = round(Int, tp[i,2]/delta_t) z1 = (n1, size(y1,2), nis) z2 = (n2, size(y1,2), nis) yy = [zeros(z1); y1[1:nf-n1+1,:,(i-1)*nis+1:i*nis]] .- [zeros(z2); y1[1:nf-n2+1,:,(i-1)*nis+1:i*nis]] yy = yy[1:nd:end,:,:] if !nosum #Sum the responses due to each input set y = y .+ yy else y[:,:,i] = yy end end return y end #==pulse ===============================================================================# """`sv = ds_therm(v,M)` `sv` is an `M` by `length(v)` matrix of `+/-1`s where `sum(sv)=v` and the `-1`s are located in the bottom rows """ function ds_therm(v, M::Int) sv = -ones(M, length(v)) for i in 1:length(v) iend = array_round((M+v[i])/2) sv[1:iend, i] .= 1 end return sv end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
3111
#RSDeltaSigma: simulateDSM() algorithm #------------------------------------------------------------------------------- #==simulateDSM() ===============================================================================# #Main algorithm for simulateDSM function _simulateDSM(u, nq, nlev, x0, order, A, B, C, D1, savestate::Bool, trackmax::Bool) if isnan(x0) x0 = zeros(order,1) end N = length(u) v = zeros(nq,N) y = zeros(nq,N) xn = nothing; xmax = nothing if savestate #Need to store the state information xn = zeros(order,N) end if trackmax #Need to keep track of the state maxima xmax = abs.(x0) end for i=1:N y[:,i] = C*x0 .+ D1 .* u[:,i] v[:,i] = ds_quantize_DSM(y[:,i], nlev) x0 = A * x0 .+ B * [u[:,i]; v[:,i]] if savestate #Save the next state xn[:,i] = x0 end if trackmax #Keep track of the state maxima xmax = max.(abs.(x0), xmax) end end result = (v=v, y=y) if savestate result = merge(result, (xn=xn,)) end if trackmax result = merge(result, (xmax=xmax,)) end return result end function simulateDSM(u, ntf::ZPKData; nlev=2, x0=NaN, savestate::Bool=false, trackmax::Bool=false) u = conv2seriesmatrix2D(u) nq = length(nlev) #Number of quantizers order = length(ntf.z) _ss = _zp2ss(ntf.p,ntf.z,-1) #realization of 1/H A, B2, C, D2 = _ss.A, _ss.B, _ss.C, _ss.D #Transform the realization so that C = [1 0 0 ...] Sinv = orth([C' eye(order)])/norm(C); S = inv(Sinv) C = C*Sinv if C[1]<0 S = -S Sinv = -Sinv end A = S*A*Sinv; B2 = S*B2; C = [1 zeros(1,order-1)]; #C=C*Sinv D2 = 0 #!!!! Assume stf=1 B1 = -B2 D1 = 1 B = [B1 B2] return _simulateDSM(u, nq, nlev, x0, order, A, B, C, D1, savestate, trackmax) end function simulateDSM(u, ABCD::Array; nlev=2, x0=NaN, savestate::Bool=false, trackmax::Bool=false) u = conv2seriesmatrix2D(u) nu, nq, order = get_nu_nq_order(u, ABCD, nlev) A = ABCD[1:order, 1:order] B = ABCD[1:order, order+1:order+nu+nq] C = ABCD[order+1:order+nq, 1:order] D1= ABCD[order+1:order+nq, order+1:order+nu] return _simulateDSM(u, nq, nlev, x0, order, A, B, C, D1, savestate, trackmax) end """`simresult = simulateDSM(u, [NTF|ABCD]; nlev=2, x0=NaN, savestate=false, trackmax=false))` Compute the output of a general ΔΣ modulator. # Inputs - `u[]`: Input signal (Multiple inputs are implied by the number of rows in `u`) - `[NTF|ABCD]`: NTF or ABCD (state-space) - `nlev`: Quantizer levels (Multiple quantizers are implied by making `nlev` an array) - `x0[]`: Initial state x0 (default zero). The NTF is zpk object. (The STF is assumed to be 1.) The structure that is simulated is the block-diagional structure used by zp2ss.m. # Returns `simresult::NamedTuple`: - .v: Output signal of ΔΣ modulator. - .xn: Internal state of ΔΣ modulator. - .xmax: Maximum internal state of ΔΣ modulator. - .y: """ simulateDSM @warn("Implements .m version of simulateDSM(). C code might be more efficient/validated.") #==simulateQDSM ===============================================================================# simulateQDSM(args...; kwargs...) = throw("simulateQDSM() not implemented") #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
2258
#RSDeltaSigma: simulateHBF() algorithm #------------------------------------------------------------------------------- """`y = simulateHBF(x, f1, f2, mode=0)` Simulate a Saramaki half-band filter. The `f1` and `f2` vectors contain coefficients for the structure. (`f1` and `f2` can also be struct arrays like those returned from designHBF.m i.e. struct arrays whose .val fields contain the coeffiecients.) The `mode` flag determines whether the input is filtered, interpolated, or decimated according to the following table: - `mode = 0`: Plain filtering, no interpolation or decimation. - `mode = 1`: The input is interpolated. - `mode = 2`: The output is decimated, even samples are taken. - `mode = 3`: The output is decimated, odd samples are taken. """ function simulateHBF(x, f1, f2, mode::Int=0) if isa(f1, Number) && isnan(f1) (f1, f2) = exampleHBF(4) end if isa(f1, Vector{CoeffCSD}) f1 = values(f1) end if isa(f2, Vector{CoeffCSD}) f2 = values(f2) end x = (x[:])' #Row matrix f1 = f1[:]; f2 = f2[:] #Redundant unless `val`s are not always simple numbers n1 = length(f1); n2 = length(f2) f2imp = vcat(f2[end:-1:1], f2) if 0 == mode #Insert zeros f2imp = vcat(f2imp, zeros(2*n2)) f2imp = f2imp[1:4*n2-1] end F2 = _tf(f2imp, vcat(1, zeros(length(f2imp)-1)), 1) if 0 == mode #Plain (up,) = _lsim(F2,x) y = 0.5*delay(x,2*n2-1) + f1[1]*up for i in 2:n1 (up,) = _lsim(F2,up) (up,) = _lsim(F2,up) y = f1[i]*up + delay(y, 4*n2-2) end elseif 1 == mode #Interpolating up = zeros(size(x)) nz = 2*n2-1 for i in n1:-1:1 if i==1 (up,) = _lsim(F2,up+f1[i]*x) nz = n2-1 else (up,) = _lsim(F2,up+f1[i]*x) (up,) = _lsim(F2,up) end x = delay(x,nz) end y = [2*up'; x']; y = y[:] #Interleave the upper and lower streams elseif mode in [2, 3] #Decimating x = x[1:2*div(end,2)] if 3 == mode y = 0.5*x[1:2:end] up = x[2:2:end] nz = n2-1 else y = 0.5*x[2:2:end] up = x[1:2:end] nz = n2 end for i in 1:n1 if i==1 (up,) = _lsim(F2,up) else (up,) = _lsim(F2,up) (up,) = _lsim(F2,up) end y = f1[i]*up + delay(y,nz) nz = 2*n2-1 end else throw("$mode is not a valid value for the mode variable.") end return y end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
2868
#RSDeltaSigma: simulateMS() algorithm #------------------------------------------------------------------------------- #==simulateMS() ===============================================================================# """`simulateMS(v, M=16, mtf=zpk(1,0,1,1), d=0, dw=[1..], sx0=[0..])` Simulate the vector-based Mismatch-Shaping for a multi-element DAC: - simresult = (sv, sx, sigma_se, max_sx, max_sy) # Inputs: - `v`: A vector of the digital input values. v is in (-M:2:M) if dw=[1..] otherwise v is in [-sum(dw),sum(dw)]. - `M`: The number of elements. - `mtf`: The mismatch-shaping transfer function, given in zero-pole form. - `d`: Dither uniformly distributed in [-d,d] is added to sy. - `dw`: A vector of dac element weights - `sx0`: A matrix whose columns are the initial states of the ESL. # Outputs: - `sv`: An MxN matrix whose columns are the selection vectors. - `sx`: An orderxM matrix containing the final state of the ESL. - `sigma_se`: The rms value of the selection error. - `max_sx`: The maximum absolute value of the state for all modulators. - `max_sy`: The maximum absolute value of the input to the VQ. # Notes: For a brief description of the theory of mismatch-shaping DACs, see R. Schreier and B. Zhang "Noise-shaped multibit D/A convertor employing unit elements", Electronics Letters, vol. 31, no. 20, pp. 1712-1713, Sept. 28 1995. """ function simulateMS(v; M::Int=16, mtf=[], d::Float64=0.0, dw::Vector=[], sx0=[]) local mtf_z; local mtf_p; local mtf_k if isa(mtf, Array) && isempty(mtf) mtf_z = [1]; mtf_p = [0] elseif isa(mtf, ZPKData) (mtf_z, mtf_p, mtf_k) = _zpkdata(mtf) else _type = typeof(mtf) throw("mtf type not supported: $_type.") end order = length(mtf_p) if isempty(sx0) sx0 = zeros(order,M) end if isempty(dw) dw = ones(M) end #B/A = MTF-1 num = poly(mtf_z) den = poly(mtf_p) A = real.(-den[2:order+1]) B = real.(num[2:order+1]+A) A = A'; B = B' #Need row vectors N = length(v) sv = zeros(M,N) sx = sx0 max_sx = maximum(maximum(abs.(sx))) max_sy = 0 sum_se2 = 0 for i in 1:N #Compute the sy vector. sy = B*sx #Normalize sy for a minimum value of zero. sy = sy .- minimum(sy) syd = (sy + d*(2*rand(1,M) .- 1))[:] #Pick the elements that have the largest desired_usage (sy) values. sv[:,i] = selectElement(v[i], syd, dw) #Compute the selection error. se = sv[:,[i]]' - sy #Compute the new sx matrix sxn = A*sx + se sx = [ sxn; sx[1:order-1,:]] #Keep track of some statistics. sum_se2 = sum_se2 + sum((se .- mean(se)) .^ 2) max_sx = maximum([max_sx abs.(sxn)]) max_sy = maximum([max_sy abs.(sy)]) end sigma_se = sqrt(sum_se2/(M*N)) simresult = (sv=sv, sx=sx, sigma_se=sigma_se, max_sx=max_sx, max_sy=max_sy) return simresult end @warn("Implements .m version of simulateMS(). C code might be more efficient/validated.") #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
2187
#RSDeltaSigma: Tools used to aid with simulations #------------------------------------------------------------------------------- #==selectElement() ===============================================================================# """`sv = selectElement(v, sy, dw=[], tri=false)` Select elements of a multi-element DAC to minimize the selection error, subject to the constraint that the nominal DAC output is v, i.e. v = sv'*dw. Assume that the preferred usage order is that given by dw. # Input - `v`: DSM output in `-M:2:M` - `sy`: Mx1 desired usage vector - `dw`: Mx1 vector of element weights - `tri`: Flag indicating the elements are tri-level, i.e. `sv=0` is allowed. NOT SUPPORTED YET. # Output - `sv`: Mx1 selection vector. `+/-1` if `tri==false`, `{0,+-1}` if `tri==true`. """ function selectElement(v, sy::Vector, dw::Vector=[], tri=false) %#ok<INUSD> M = length(sy) sdw = M dw_is_one = (isempty(dw) || all(dw .== 1)) if !dw_is_one sdw = sum(dw) end if abs(v) > sdw throw("|v| is too large.") elseif v == sdw return ones(M,1) elseif v == -sdw return -ones(M,1) end sv = -ones(M,1) possibilities = sortperm(-sy) #Determine the element priority #Speed up selection in the usual case where all element weights are one. #Suggested 1997-03-05 by J. A. Cherry. if dw_is_one sv[possibilities[1:array_round((M+v)/2)]] .= 1 return sv end #Go through sv possibilities one by one, until one which meets the #v = sv'*dw constraint is found. i = 1 #Selection level pointer = ones(1,M) #Array of pointers to selected elements selected = zeros(1,M) #Selected elements dw0 = [0; dw] while true while pointer[i]>M #backtrack i = i-1 if i==0 break #failure! end pointer[i] = pointer[i] + 1 selected[i+1:end] = 0 end selected[i] = possibilities[pointer[i]] dv = 2*sum(dw0[selected+1]) - sdw if dv==v break #success! elseif dv<v #Proceed to the next level of selection pointer[i+1] = pointer[i] + 1 i = i+1 else #Try the next element at the current level. pointer[i] = pointer[i] + 1 end end selected = selected[findall(selected .!= 0)] sv[selected] = 1 return sv end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
11575
#RSDeltaSigmaPort SNR calculations #------------------------------------------------------------------------------- """`snr = calculateSNR(hwfft,f,nsig=1)` Estimate the signal-to-noise ratio, given the in-band bins of a (Hann-windowed) fft and the location of the input signal (f>0). - For nsig=1, the input tone is contained in `hwfft(f:f+2)`; this range is appropriate for a Hann-windowed fft. - Each increment in `nsig` adds a bin to either side. - The SNR is expressed in dB. """ function calculateSNR(hwfft, f::Int, nsig::Int = 1) signalBins = f-nsig+1:f+nsig+1 signalBins = signalBins[signalBins .> 0] signalBins = signalBins[signalBins .<= length(hwfft)] s = norm(hwfft[signalBins]) #*4/(N*sqrt(3)) for true rms value noiseBins = collect(1:length(hwfft)) deleteat!(noiseBins, signalBins) n = norm(hwfft[noiseBins]) snr = (n!=0) ? dbv(s/n) : Inf return snr end """`(peak_snr,peak_amp) = peakSNR(snr,amp)` Estimate the snr peak by threading a line of slope 1 through the (amp,snr) data. Both amp and snr are expressed in dB. """ function peakSNR(snr, amp) snr = deepcopy(snr); amp = deepcopy(amp) #Delete garbage data i = abs.(snr) .== Inf; deleteat!(snr, i); deleteat!(amp, i) i = isnan.(snr); deleteat!(snr, i); deleteat!(amp, i) i = snr .< 3; deleteat!(snr, i); deleteat!(amp, i) n = length(amp) #Sort by amplitude i = sortperm(amp) amp = amp[i]; snr = snr[i] i = [true] local m = 0.0 while any(i) && n > 3 #Draw a 45-degree median line through the data tmp = sort(snr .- amp) if mod(n,2) == 0 m = mean( tmp[div(n,2) .+ [1, 0]] ) else m = tmp[div(n+1,2)] end #Discard data that is more than 6dB off i = abs.(amp .- snr .+ m) .> 6 deleteat!(snr, i); deleteat!(amp, i) n = length(amp) end peak_amp = maximum(amp) peak_snr = peak_amp + m return (peak_snr, peak_amp) end """`(snr,amp,k0,k1,sigma_e2) = predictSNR(ntf,R=64,amp=...,f0=0)` Predict the SNR curve of a binary delta-sigma modulator by using the describing function method of Ardalan and Paulos. The modulator is specified by a noise transfer function (ntf). The band of interest is defined by the oversampling ratio (R) and the center frequency (f0). The input signal is characterized by the amp vector. amp defaults to [-120 -110...-20 -15 -10 -9 -8 ... 0]dB, where 0 dB means a full-scale (peak value = 1) sine wave. The algorithm assumes that the amp vector is sorted in increasing order; once instability is detected, the remaining SNR values are set to -Inf. # Output: - snr: a vector of SNR values (in dB) - amp: a vector of amplitudes (in dB) - k0: the quantizer signal gain - k1: the quantizer noise gain - sigma_e2: the power of the quantizer noise (not in dB) The describing function method of A&P assumes that the quantizer processes signal and noise components separately. The quantizer is modelled as two (not necessarily equal) linear gains, k0 and k1, and an additive white gaussian noise source of power sigma_e2. k0, k1 and sigma_e2 are calculated as functions of the input. The modulator's loop filter is assumed to have nearly infinite gain at the test frequency. Future versions may accommodate STFs. """ function predictSNR(ntf, R=64, amp=vcat(-120:10:-20, -15, -10:0); f0::Float64=0.0) Nb = 100 XTAB = range(-2, stop=0, length=21) #The following code was used to create the YTAB matrix #YTAB = []; #for xi=XTAB # YTAB = [YTAB; hypergeo(0.5,1,xi) hypergeo(0.5,2,xi)]; #end YTAB = [0.46575960516930 0.67366999387741; 0.47904652357101 0.68426650762558; 0.49316295981407 0.69527947902679; 0.50817364454269 0.70673173666000; 0.52414894104004 0.71864765882492; 0.54116523265839 0.73105299472809; 0.55930554866791 0.74397552013397; 0.57866013050079 0.75744456052780; 0.59932720661163 0.77149158716202; 0.62141352891922 0.78615015745163; 0.64503526687622 0.80145609378815; 0.67031890153885 0.81744754314423; 0.69740217924118 0.83416539430618; 0.72643494606018 0.85165339708328; 0.75758063793182 0.86995816230774; 0.79101717472076 0.88912981748581; 0.82693856954575 0.90922164916992; 0.86555624008179 0.93029111623764; 0.90710091590881 0.95239937305450; 0.95182400941849 0.97561222314835; 1.00000000000000 1.00000000000000; ] if f0==0 band_of_interest = range(0, stop=pi/R, length=Nb) else band_of_interest = range(2*pi*(f0-0.25/R), stop=2*pi*(f0+0.25/R), length=Nb) end num, den = _zp2tf(ntf.z, ntf.p, 1) num1 = num - den N = length(amp) snr = zeros(1,N) .- Inf k0 = zeros(1,N) k1 = zeros(1,N) sigma_e2 = zeros(1,N) u = 10 .^ (amp/20) Nimp = 100 unstable = false f_prev = 0.0; fprime = 0.0 m0 = 0.0; rho = 0.0; erfinvu = 0.0 for n=1:N #Calculate sigma_e2 if f0==0 erfinvu = erfinv(u[n]) sigma_e2[n] = 1 - u[n]^2 - 2/pi*exp(-2*erfinvu^2) else #Sinusoidal input. #Solve sqrt(pi)*u/2 = rho * hypergeo(0.5,2,-rho^2); #Formulate as solve f(rho)=0, f = rho*M(0.5,2,-rho^2)-K #and use the secant method. K = 0.5 * sqrt(pi) * u[n] if n==1 rho = u[n]^2 #Initial guess; otherwise use previous value. fprime = 1.0 end drho = 1.0 for itn = 1:20 m0 = interp1_cubic(XTAB,YTAB[:,2],-rho^2) f = rho*m0 - K if( itn >1 ) fprime = max((f-f_prev)/drho,0.5) #Secant approx. end if abs(f) < 1e-8; break; end #!Converged drho = -f/fprime if abs(drho) > 0.2; drho = sign(drho)*0.2; end if abs(drho) < 1e-6; break; end #!Converged rho = rho + drho f_prev = f end m1 = interp1_cubic(XTAB,YTAB[:,1], -rho^2) sigma_e2[n] = 1 - u[n]^2/2 - 2/pi*m1^2 end #Sinusoidal input #Iterate to solve for k1 and sigma_1. #Using one of MATLAB's nonlinear equation solvers would be more efficient, #but this function code would then require the optimization toolbox. #!Future work: put in 2-D BFGS code. k1[n] = (n>1) ? k1[n-1] : 1.2 #Use the previous value of k1 as the initial guess. k1_prev = 0 itn = 0 k1sigma1 = (f0==0) ? sqrt(2/pi)*exp(-erfinvu^2) : sqrt(2/pi)*m1 local sigma_1 = 0.0 while abs(k1[n]-k1_prev) > 1e-6*(1+k1[n]) && itn < 100 #Create the function: H_hat = L1/(1-k1*L1)=(H-1)/(H*(1-k1)+k1). den1 = (1-k1[n])*num + den*k1[n] #Calculate pGain, the square of the 2-norm of H_hat. pGain, Nimp = powerGain(num1, den1, Nimp) if isinf(pGain) unstable = true break end sigma_1 = sqrt(pGain*sigma_e2[n]) k1_prev = k1[n] k1[n] = k1sigma1/sigma_1 itn = itn+1 end if unstable break end if f0==0 y0 = sqrt(2)*erfinvu*sigma_1 k0[n] = u[n]/y0 else k0[n] = sqrt(2/pi)*m0/sigma_1 end h = _freqz(num, (1-k1[n])*num + k1[n]*den, band_of_interest) #For both DC and sine wave inputs, use u^2/2 as the signal #power since true DC measurements are usually impossible. snr[n] = dbp( 0.5*u[n]^2 / (sum(h.^2)/(R*Nb)*sigma_e2[n]) ) end return (snr, amp, k0, k1, sigma_e2) end """`(snr,amp) = simulateSNR(ΔΣmodel,osr,amp; f0=0,nlev=2,f=1/(4*osr),k=13,quadrature=false)` Determine the SNR for a delta-sigma modulator by using simulations. `ΔΣmodel` describes the modulator by a noise transfer function (ntf) and the number of quantizer levels (`nlev`). Alternatively, `ΔΣmodel` may be a function taking the input signal as its sole argument: - `ΔΣmodel::ZPKData`: z, p, k transfer function - `ΔΣmodel::Array` ABCD matrix - `ΔΣmodel::Function` funΔΣ(u) generating ΔΣ output. The band of interest is defined by the oversampling ratio (`osr`) and the center frequency (`f0`). The input signal is characterized by the `amp` vector and the `f` variable. - `amp` defaults to [-120 -110...-20 -15 -10 -9 -8 ... 0]dB, where 0 dB means a full-scale (peak value = nlev-1) sine wave. - `f` is the input frequency, normalized such that 1 -> fs; - `f` is rounded to an FFT bin. Using sine waves located in FFT bins, the SNR is calculated as the ratio of the sine wave power to the power in all in-band bins other than those associated with the input tone. Due to spectral smearing, the input tone is not allowed to lie in bins 0 or 1. The length of the FFT is 2^k. - If ntf is complex, simulateQDSM (which is slow) is called. - If ABCD is complex, simulateDSM is used with the real equivalent of ABCD in order to speed up simulations. Future versions may accommodate STFs. """ function simulateSNR(arg1, osr::Int=64, amp=vcat(-120:10:-20, -15, -10:0); f0::Float64=0.0, nlev::Int=2, f::Float64=NaN, k::Int=13, quadrature::Bool=false ) is_function = isa(arg1, Function) #Look at arg1 and decide if the system is quadrature quadrature_ntf = false if !is_function if isa(arg1, ZPKData) pz = [arg1.p, arg1.z] for i=1:2 if any( abs.(imag.(poly(pz[i]))) .> 1e-4 ) quadrature = true quadrature_ntf = true end end else #ABCD matrix if !all(all(imag.(arg1) .== 0)) quadrature = true end end end osr_mult = 2 if f0!=0 && !quadrature osr_mult = 2*osr_mult end if isnan(f) f = f0 + 0.5/(osr*osr_mult) #Halfway across the band end M = nlev-1 if quadrature && !quadrature_ntf #Modify arg1 (ABCD) and nlev so that simulateDSM can be used nlev = [nlev; nlev] arg1 = mapQtoR(arg1) end if abs(f-f0) > 1/(osr*osr_mult) @warn("The input tone is out-of-band.") end N = 2^k if N < 8*2*osr #Require at least 8 bins to be "in-band" @warn("Increasing k to accommodate a large oversampling ratio.") k = ceil(Int, log2(8*2*osr)) N = 2^k end F = round(Int, f*N) if abs(F)<=1 @warn("Increasing k to accommodate a low input frequency.") #Want f*N >= 1 k = ceil(Int, log2(1/f)) N = 2^k F = 2 end Ntransient = 100 soft_start = 0.5*(1 .- cos.(2π/Ntransient * (0:div(Ntransient,2)-1))) if !quadrature tone = M * sin.(2π*F/N * (0:(N+Ntransient-1))) tone[1:div(Ntransient,2)] = tone[1:div(Ntransient,2)] .* soft_start else tone = M * exp.(2π*j*F/N * (0:(N+Ntransient-1)) ) tone[1:div(Ntransient,2)] = tone[1:div(Ntransient,2)] .* soft_start if !quadrature_ntf tone = [real(tone); imag(tone)] end end window = .5*(1 .- cos.(2π*(0:N-1)/N) ) #Hann window if f0==0 #Exclude DC and its adjacent bin inBandBins = div(N,2) .+ (3:round(Int, N/(osr_mult*osr))) F = F-2 else f1 = round(Int, N*(f0-1/(osr_mult*osr))) f2 = round(Int, N*(f0+1/(osr_mult*osr))) inBandBins = div(N,2) .+ (f1:f2) #Should exclude DC F = F-f1+1 end snr = zeros(size(amp)) i=1 for A = 10 .^ (amp/20) if is_function v = arg1(A*tone) elseif quadrature_ntf v = simulateQDSM(A*tone, arg1, nlev=nlev).v else v = simulateDSM(A*tone, arg1, nlev=nlev).v if quadrature v = v[1,:] + im*v[2,:] end end hwfft = fftshift(fft(applywnd(v[1+Ntransient:N+Ntransient], window))) snr[i] = calculateSNR(hwfft[inBandBins], F) i=i+1 end return (snr,amp) end #Not meant to be called externally: function _calcSNRInfo(NTF, OSR::Int, M::Int, f0::Float64) nlev=M+1 SNR, amp = simulateSNR(NTF, OSR, f0=f0, nlev=nlev) pk_snr, pk_amp = peakSNR(SNR, amp) #Single values vs_amp_predicted = nothing if nlev == 2 #predictSNR() only supports 2 levels SNR_pred, amp_pred = predictSNR(NTF, OSR, f0=f0) amp_pred = conv2seriesmatrix2D(amp_pred*1.0) #Ensure amplitudes are Float64 vs_amp_predicted=(amp_pred, SNR_pred) end return (vs_amp_sim=(amp, SNR), peak=(pk_amp, pk_snr), vs_amp_predicted=vs_amp_predicted, OSR=OSR ) end """`calcSNRInfo(sig, dsm::RealDSM; NTF=nothing)` """ function calcSNRInfo(dsm::RealDSM; NTF=nothing) isnothing(NTF) && (NTF = synthesizeNTF(dsm)) return _calcSNRInfo(NTF, dsm.OSR, dsm.M, dsm.f0) end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
16355
#RSDeltaSigma: State space utilities #------------------------------------------------------------------------------- #SEARCH: even, odd #==getorder ===============================================================================# #Figure out nu, nq, and order of the system & ensure dimensions are ok function get_nu_nq_order(u, ABCD, nlev) u = conv2seriesmatrix2D(u) nu = size(u,1) nq = length(nlev) if !(size(ABCD,2) > 2 && size(ABCD,2)==nu+size(ABCD,1)) msg = "The ABCD argument does not have proper dimensions." throw(ArgumentError(msg)) end order = size(ABCD,1)-nq return (nu, nq, order) end #==partitionABCD ===============================================================================# """`[A B C D] = partitionABCD(ABCD, m)` Partition ABCD into A, B, C, D for an m-input state-space system. """ function partitionABCD(ABCD, m=nothing) n = 0 if m!= nothing n = size(ABCD,2) - m else n = minimum(size(ABCD)) - 1 m = size(ABCD,2) - n end r = size(ABCD,1) - n A = ABCD[1:n, 1:n] B = ABCD[1:n, n+1:n+m] C = ABCD[n+1:n+r, 1:n] D = ABCD[n+1:n+r, n+1:n+m] return (A, B, C, D) end #==stuffABCD ===============================================================================# function _stuffABCD(::DS{:CRFB}, a,g,b,c) order = length(a) ABCD = zeros(order+1,order+2) (order2, isodd, Δodd) = orderinfo(order) Δeven = 1-Δodd #C=(0 0...c_n) #This is done as part of the construction of A, below #B1 = (b_1 b_2... b_n), D=(b_(n+1) 0) ABCD[:,order+1] = b' #B2 = -(a_1 a_2... a_n) ABCD[1:order,order+2] = -a' diagonal = 1:(order+2):order*(order+1) ABCD[diagonal] = ones(1,order) subdiag = diagonal[(1+Δeven):2:order] .+ 1 ABCD[subdiag] = c[1+Δeven:2:order] supdiag = subdiag[(1+Δodd):length(subdiag)] .- 2 ABCD[supdiag] = -g dly = (2+Δodd):2:order #row numbers of delaying integrators ABCD[dly,:] = ABCD[dly,:] .+ diagm(c[dly .- 1]) * ABCD[dly .- 1,:] return ABCD end #= switch form case 'CRFF' %B1 = (b_1 b_2... b_n), D=(b_(n+1) 0) ABCD(:,order+1) = b'; %B2 = -(c_1 0... 0) ABCD(1,order+2) = -c(1); diagonal = 1:(order+2):order*(order+1); % # of elements = order ABCD(diagonal) = ones(1,order); subdiag = diagonal(1:2:order-1)+1; ABCD(subdiag)= c(2:2:order); if even multg = 1:2:order; % rows to have g*(following row) subtracted. ABCD(multg,:) = ABCD(multg,:) - diagm(g)*ABCD(multg+1,:); elseif order >= 3 supdiag = diagonal(3:2:order)-1; ABCD(supdiag) = -g; end multc = 3:2:order; % rows to have c*(preceding row) added. ABCD(multc,:) = ABCD(multc,:) + diagm(c(multc))*ABCD(multc-1,:); ABCD(order+1,1:2:order) = a(1:2:order); for i = 2:2:order ABCD(order+1,:) = ABCD(order+1,:) + a(i)*ABCD(i,:); end case 'CIFB' %C=(0 0...c_n) % This is done as part of the construction of A, below %B1 = (b_1 b_2... b_n), D=(b_(n+1) 0) ABCD(:,order+1) = b'; %B2 = -(a_1 a_2... a_n) ABCD(1:order,order+2) = -a'; diagonal = 1:(order+2):order*(order+1); ABCD(diagonal) = ones(1,order); subdiag = diagonal(1:order)+1; ABCD(subdiag)= c; supdiag = diagonal((2+odd):2:order)-1; ABCD(supdiag) = -g; case 'CIFF' %B1 = (b_1 b_2... b_n), D=(b_(n+1) 0) ABCD(:,order+1) = b'; %B2 = -(c_1 0... 0) ABCD(1,order+2) = -c(1); diagonal = 1:(order+2):order*(order+1); ABCD(diagonal) = ones(1,order); subdiag = diagonal(1:order-1)+1; ABCD(subdiag)= c(2:end); %C = (a_1 a_2... a_n) ABCD(order+1,1:order) = a(1:order); supdiag = diagonal((2+odd):2:order)-1; ABCD(supdiag) = -g; case 'CRFBD' %C=(0 0...c_n) ABCD(order+1,order) = c(order); %B1 = (b_1 b_2... b_n), D=(b_n+1 0) ABCD(:,order+1) = b'; %B2 = -(a_1 a_2... a_n) ABCD(1:order,order+2) = -a'; diagonal = 1:(order+2):order*(order+1); ABCD(diagonal) = ones(1,order); dly = (1+odd):2:order; % row numbers of delaying integrators subdiag = diagonal(dly)+1; ABCD(subdiag)= c(dly); supdiag = subdiag((1+odd):length(subdiag))-2; ABCD(dly,:) = ABCD(dly,:) - diagm(g)*ABCD(dly+1,:); if order>2 coupl = 2+even:2:order; ABCD(coupl,:) = ABCD(coupl,:) + diagm(c(coupl-1))*ABCD(coupl-1,:); end case 'CRFFD' diagonal = 1:(order+2):order*(order+1); subdiag = diagonal(1:order-1)+1; supdiag = diagonal(2:order)-1; %B1 = (b_1 b_2... b_n), D=(b_(n+1) 0) ABCD(:,order+1) = b'; %B2 = -(c_1 0... 0) ABCD(1,order+2) = -c(1); ABCD(diagonal) = ones(1,order); multc = 2:2:order; % rows to have c*(preceding row) added. if order>2 ABCD(subdiag(2:2:end)) = c(3:2:end); end if even ABCD(supdiag(1:2:end)) = -g; else % subtract g*(following row) from the multc rows ABCD(multc,:) = ABCD(multc,:) - diagm(g)*ABCD(multc+1,:); end ABCD(multc,:) = ABCD(multc,:) + diagm(c(multc))*ABCD(multc-1,:); % C ABCD(order+1,2:2:order) = a(2:2:order); for i = 1:2:order ABCD(order+1,:) = ABCD(order+1,:) + a(i)*ABCD(i,:); end % The above gives y(n+1); need to add a delay to get y(n). % Do this by augmenting the states. Note: this means that % the apparent order of the NTF is one higher than it acually is. [A B C D] = partitionABCD(ABCD,2); A = [A zeros(order,1); C 0]; B = [B; D]; C = [zeros(1,order) 1]; D = [0 0]; ABCD = [A B; C D]; case 'PFF' %B1 = (b_1 b_2... b_n), D=(b_(n+1) 0) ABCD(:,order+1) = b'; odd_1 = odd; % !! Bold assumption !! odd_2 = 0; % !! Bold assumption !! gc = g.* c(1+odd_1:2:end); theta = acos(1-gc/2); if odd_1 theta0 = 0; else theta0 = theta(1); end order_2 = 2*length(find(abs(theta-theta0)>0.5)); order_1 = order - order_2; %B2 = -(c_1 0...0 c_n 0...0) ABCD(1,order+2) = -c(1); ABCD(order_1+1,order+2) = -c(order_1+1); diagonal = 1:(order+2):order*(order+1); % # of elements = order ABCD(diagonal) = ones(1,order); i = [1:2:order_1-1 order-order_2+1:2:order] subdiag = diagonal(i)+1; ABCD(subdiag)= c(i+1); if odd_1 if order_1 >= 3 supdiag = diagonal(3:2:order_1)-1; ABCD(supdiag) = -g(1:(order_1-1)/2); end else multg = 1:2:order_1; % rows to have g*(following row) subtracted. ABCD(multg,:) = ABCD(multg,:) - diagm(g(1:order_1/2))*ABCD(multg+1,:); end if odd_2 if order_2 >= 3 supdiag = diagonal(order_1+2:2:order)-1; ABCD(supdiag) = -g(1:(order_1-1)/2); end else multg = order_1+1:2:order; % rows to have g*(following row) subtracted. gg = g((order_1-odd_1)/2+1:end); ABCD(multg,:) = ABCD(multg,:) - diagm(gg)*ABCD(multg+1,:); end % Rows to have c*(preceding row) added. multc = [3:2:order_1 order_1+3:2:order]; ABCD(multc,:) = ABCD(multc,:) + diagm(c(multc))*ABCD(multc-1,:); % C portion of ABCD i = [1:2:order_1 order_1+1:2:order]; ABCD(order+1,i) = a(i); for i = [2:2:order_1 order_1+2:2:order] ABCD(order+1,:) = ABCD(order+1,:) + a(i)*ABCD(i,:); end case 'Stratos' % code copied from case 'CIFF': %B1 = (b_1 b_2... b_n), D=(b_(n+1) 0) ABCD(:,order+1) = b'; %B2 = -(c_1 0... 0) ABCD(1,order+2) = -c(1); diagonal = 1:(order+2):order*(order+1); ABCD(diagonal) = ones(1,order); subdiag = diagonal(1:order-1)+1; ABCD(subdiag)= c(2:end); % code based on case 'CRFF': multg = 1+odd:2:order-1; % rows to have g*(following row) subtracted. ABCD(multg,:) = ABCD(multg,:) - diagm(g)*ABCD(multg+1,:); % code copied from case 'CIFF': %C = (a_1 a_2... a_n) ABCD(order+1,1:order) = a(1:order); case 'DSFB' I = eye(order); A0 = I; A1 = zeros(order,order); indices = 2:order+1:(order-1)*order; % subdiagonal A1(indices) = c(1:order-1); indices = order+1 : 2*(order+1) : order*order-1; %supdiagonal A1(indices) = -g; C0 = I; C1 = I; D0 = zeros(order,2); if odd C1(order,order) = 0; else A1(order-1:order,order-1:order) = [ 0 -g(end)/2; c(end-1) 0]; C0(order,order) = 0; D0(order-1,2) = g(end)/2; end M = inv(I - A1*C1); A = M * (A0 + A1*C0 ); B = M * ( [b(1:order)' -a'] + A1*D0 ); C = [zeros(1,order-1) c(order)]; D = [b(order+1) 0]; ABCD = [A B; C D]; otherwise fprintf(1,'%s error: Form %s is not yet supported.\n',mfilename,form) end =# """`ABCD = stuffABCD(a,g,b,c,form='CRFB')` Compute the ABCD matrix for the specified structure. See realizeNTF.m for a list of supported structures. `mapABCD` is the inverse function. """ function stuffABCD(a,g,b,c, form::Symbol=:CRFB) order = length(a) if length(b)==1 b = [b zeros(1,order)] end return _stuffABCD(DS(form), a, g, b, c) end #==mapABCD ===============================================================================# #Common implementation for CRFB, CIFB, & CRFBD: function _mapABCD_CRFB_CIFB_CRFBD(ABCD, subdiag, supdiag, order::Int, form::Symbol) order2, isodd, Δodd = orderinfo(order) Δeven = 1 - Δodd c = ABCD[subdiag] g = -ABCD[supdiag] if :CRFB == form dly = (2+Δodd):2:order #row numbers of delaying integrators. ABCD[dly,:] = ABCD[dly,:] .- diagm(c[dly .- 1])*ABCD[dly .- 1,:] elseif :CRFBD == form dly = (1+Δodd):2:order #row numbers of delaying integrators. ABCD[dly,:] = ABCD[dly,:] .+ diagm(g)*ABCD[dly .+ 1,:] if order>2 coupl = 2+Δeven:2:order ABCD[coupl,:] = ABCD[coupl,:] .- diagm(c[coupl .- 1])*ABCD[coupl .- 1,:] end end a = -ABCD[1:order,order+2]' b = ABCD[:,order+1]' return (a,g,b,c) end _mapABCD(::DS{:CRFB}, ABCD, diagonal, subdiag, supdiag, order::Int) = _mapABCD_CRFB_CIFB_CRFBD(ABCD, subdiag, supdiag, order, :CRFB) _mapABCD(::DS{:CIFB}, ABCD, diagonal, subdiag, supdiag, order::Int) = _mapABCD_CRFB_CIFB_CRFBD(ABCD, subdiag, supdiag, order, :CIFB) _mapABCD(::DS{:CRFBD}, ABCD, diagonal, subdiag, supdiag, order::Int) = _mapABCD_CRFB_CIFB_CRFBD(ABCD, subdiag, supdiag, order, :CRFBD) #= case 'CRFF' c = [-ABCD(1,order+2) ABCD(subdiag(1:end-1))]; g = -ABCD(supdiag); if even multg = 1:2:order; %Rows to have g*(following row) added. ABCD(multg,:) = ABCD(multg,:)+diag(g)*ABCD(multg+1,:); end multc=3:2:order; %Rows to have c*(preceding row) subtracted. ABCD(multc,:)=ABCD(multc,:)-diag(c(multc))*ABCD(multc-1,:); a(2:2:order)=ABCD(order+1,2:2:order); for i=2:2:order %Recover a coeff. ABCD(order+1,:)=ABCD(order+1,:)-a(i)*ABCD(i,:); end a(1:2:order)=ABCD(order+1,1:2:order); b = ABCD(:,order+1)'; case 'CRFFD' % CRFFD has an extra order. Correct the common variables order = order-1; order2, isodd, Δodd = orderinfo(order) odd = rem(order,2); even = ~odd; diagonal = diagonal(1:order); subdiag = diagonal(1:order-1)+1; supdiag = diagonal(2+Δodd:2:order)-1; g = -ABCD(supdiag); c = [-ABCD(1,order+3) ABCD(subdiag)]; a = zeros(1,order); for i=1:2:order %Recover the a coefficients a(i) = ABCD(order+1,i); ABCD(order+1,:) = ABCD(order+1,:) - a(i)*ABCD(i,:); end a(2:2:order) = ABCD(order+1,2:2:order); b = ABCD(1:order+1,order+2)'; for i=2:2:order %Recover the b coefficients b(i) = b(i) - c(i) *b(i-1); if isodd b(i) = b(i) + g(i/2) *b(i+1); end end yscale = ABCD(order+2,order+1); a = a*yscale; b(end) = b(end)*yscale; case {'CIFF','Stratos'} a = ABCD(order+1,1:order); c = [-ABCD(1,order+2) ABCD(subdiag(1:end-1))]; g = -ABCD(supdiag); b = ABCD(:,order+1)'; otherwise fprintf(1,'%s error: Form %s is not yet supported.\n',mfilename,form) end =# """`(a,g,b,c) = mapABCD(ABCD, form=:CRFB)` Compute the coefficients for the specified structure. See `realizeNTF` for a list of supported structures. `stuffABCD` is the inverse function. """ function mapABCD(ABCD, form::Symbol=:CRFB) order=size(ABCD,1)-1 order2, isodd, Δodd = orderinfo(order) diagonal = 1:(order+2):order*(order+1) subdiag = diagonal[1:order] .+ 1 supdiag = diagonal[2+Δodd:2:order] .- 1 #Algorithm below modifies ABCDs copy so as not to modify original: ABCD = deepcopy(ABCD) #Do the mapping. return _mapABCD(DS(form), ABCD, diagonal, subdiag, supdiag, order) end #==scaleABCD ===============================================================================# """`(ABCDs,umax,S)=scaleABCD(ABCD; nlev=2,f=0,xlim=1,ymax=nlev+5,umax,N=10^5,N0=10)` Scale the loop filter of a general delta-sigma modulator for dynamic range. - ABCD: The state-space description of the loop filter. - nlev: The number of levels in the quantizer. - xlim: A vector or scalar specifying the limit for each state variable. - ymax: The stability threshold. Inputs that yield quantizer inputs above ymax are considered to be beyond the stable range of the modulator. - umax: The maximum allowable input amplitude. umax is calculated if it is not supplied. - ABCDs: The state-space description of the scaled loop filter. - S: The diagonal scaling matrix, ABCDs = [S*A*Sinv S*B; C*Sinv D]; xs = S*x; """ function scaleABCD(ABCD; nlev::Int=2, f=0, xlim=1, ymax=NaN, umax=NaN, N::Int=10^5, N0=10) N_sim=N order = size(ABCD,1)-1 if isnan(ymax) ymax=nlev+5 end if length(xlim)==1 xlim = xlim * ones(1,order) #Convert scalar xlim to a vector end quadrature = !isreal(ABCD) #Make this function repeatable #rng_state = rng; rng('default') #Original code Random.seed!(0) #Envelope for smooth start-up raised_cosine = 0.5*(1 .- cos.(pi/N0 * (0:N0-1)))' if isnan(umax) #Simulate the modulator with DC or sine wave inputs to detect its stable #input range. #First get a rough estimate of umax. ulist =(0.1:0.1:1.0) * (nlev-1) umax = nlev-1 N = 10^3 u0 = [ exp.(2π*j*f*(-N0:-1))' .* raised_cosine exp.(2π*j*f*(0:N-1))' ] .+ 0.01*[1 j]*randn(2, N+N0) if !quadrature; u0 = real.(u0); end local simresult for u in ulist if !quadrature simresult = simulateDSM(u*u0,ABCD, nlev=nlev, trackmax=true) else simresult = simulateQDSM(u*u0,ABCD, nlev=nlev, trackmax=true) end if maximum(abs.(simresult.y)) > ymax umax = u #umax is the smallest input found which causes 'instability' break end end if umax == ulist[1] umaxstr = @sprintf("%.1f", umax) msg = "Modulator is unstable even with an input amplitude of $umaxstr." throw(msg) end end #More detailed simulation N = N_sim u0 = [ exp.(2π*j*f*(-N0:-1))' .* raised_cosine exp.(2π*j*f*(0:N-1))' ] + 0.01*[1 j]*randn(2, N+N0) if !quadrature; u0 = real.(u0); end maxima = zeros(1,order) .- 1 ulist = range(0.7*umax, stop=umax, length=10) local simresult for u in ulist if !quadrature simresult = simulateDSM(u*u0,ABCD, nlev=nlev, trackmax=true) else simresult = simulateQDSM(u*u0,ABCD, nlev=nlev, trackmax=true) end if maximum(abs.(simresult.y)) > ymax break end #We need to do this at least once. umax = u #umax is the largest input which keeps |y| < ymax #maxima = maximum([maxima; simresult.xmax'], dims=1) maxima = max.(maxima, simresult.xmax') end #Scale the modulator so that all states are at most xlim. scale = maxima ./ xlim scale = scale[:] #Convert to simple vector S = diagm(1 ./ scale); Sinv = diagm(scale) #xs = S * x (A, B, C, D) = partitionABCD(ABCD) ABCDs = [S*A*Sinv S*B; C*Sinv D] Random.seed!() #original code restores state: rng(rng_state) return (ABCDs, umax, S) end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
10869
#RSDeltaSigmaPort: Synthesize NTFs #------------------------------------------------------------------------------- #==Warnings ===============================================================================# function _synthesizeNTF_warn_Hinf() msg = string(@__FILE__, ": Unable to achieve specified Hinf.\n", "Setting all NTF poles to zero." ) @warn(msg) end function _synthesizeNTF_warn_iter() msg = string(@__FILE__, ": Danger! Iteration limit exceeded.") @error(msg) end function _synthesizeNTF_warn_Hinf_iter() msg = string(@__FILE__, ": Danger! Hinf iteration limit exceeded.") @error(msg) end #==synthesizeNTF_setup() ===============================================================================# function synthesizeNTF_setup(order::Int, OSR::Int, opt, f0::Float64, isNTF1::Bool) local z order = Float64(order) #Type stability dw = π/OSR if f0!=0 #Bandpass design-- halve the order temporarily. order = order/2 dw = π/(2*OSR) end order_i = array_round(order) #Determine the zeros. if length(opt)==1 if opt==0 z = zeros(order_i) else opt_for_zeros = isNTF1 ? (1+mod(opt-1,2)) : opt z = dw*ds_optzeros(order, opt_for_zeros) if isempty(z) throw_unreachable() return; end end if f0!=0 # Bandpass design-- shift and replicate the zeros. order = order*2 z = z .+ 2π*f0 z = conj.(z) z = vcat(z, -z) end z = exp.(j*z) else z = opt[:] * complex(1.0) #Ensure is Vector{Complex{Float64}} end #Order might possibly be a N.5 value (float) here. Not sure if this is actually the intent. return (order, z) #Order potentially gets modified. Not sure this is actually the intent. end #==synthesizeNTF0() ===============================================================================# function _synthesizeNTF0_z(order::Float64, OSR::Int, z::Vector{Complex{Float64}}, H_inf::Float64, f0::Float64) order_i = array_round(order) Ts = 1.0 ntf = _zpk(z,zeros(order_i),1,Ts) itn_limit = 100 #ntf_z, ntf_p, ntf_k, = zpkdata(ntf) # Iteratively determine the poles by finding the value of the x-parameter # which results in the desired H_inf. if f0 == 0 # Lowpass design HinfLimit = 2^order # !!! The limit is actually lower for opt=1 and low OSR if H_inf >= HinfLimit _synthesizeNTF_warn_Hinf() ntf.p = zeros(order_i) else x=0.3^(order-1) # starting guess converged = 0 local fprev = 0 #Initialize local delta_x = 0 #Initialize for itn=1:itn_limit me2 = -0.5*(x^(2/order)) w = (2*collect(1:order_i) .- 1)*π/order #VERIFYME mb2 = 1 .+ me2*exp.(j*w) p = mb2 - sqrt.(mb2 .^ 2 .- 1) out = findall(abs.(p) .> 1) p[out] = 1 ./ p[out] # reflect poles to be inside the unit circle. ntf.z = z; ntf.p = cplxpair(p) f = real(evalTF(ntf,-1))-H_inf # [ x f ] if itn==1 delta_x = -f/100 else delta_x = -f*delta_x/(f-fprev) end xplus = x+delta_x if xplus>0 x = xplus else x = x*0.1 end fprev = f; if abs(f)<1e-10 || abs(delta_x)<1e-10 converged = 1 break end if x>1e6 _synthesizeNTF_warn_Hinf() ntf.z = z; ntf.p = zeros(order_i) break; end if itn == itn_limit _synthesizeNTF_warn_iter() end end end else # Bandpass design. x = 0.3^(order/2-1) # starting guess (not very good for f0~0) if f0>0.25 z_inf=1 else z_inf=-1 end c2pif0 = cos(2π*f0) local fprev = 0 #Initialize local delta_x = 0 #Initialize for itn=1:itn_limit e2 = 0.5*x^(2/order) w = (2*collect(1:order_i) .- 1)*π/order #VERIFYME mb2 = c2pif0 .+ e2*exp.(j*w) p = mb2 .- sqrt.(mb2.^2 .- 1) # reflect poles to be inside the unit circle. out = findall(abs.(p) .> 1) p[out] = 1 ./ p[out] ntf.z = z; ntf.p = cplxpair(p) f = real(evalTF(ntf,z_inf))-H_inf # [x f] if itn==1 delta_x = -f/100 else delta_x = -f*delta_x/(f-fprev) end xplus = x+delta_x if xplus > 0 x = xplus else x = x*0.1 end fprev = f if abs(f)<1e-10 || abs(delta_x)<1e-10 break end if x>1e6 _synthesizeNTF_warn_Hinf() ntf.p = zeros(order_i) break end if itn == itn_limit _synthesizeNTF_warn_iter() end end end ntf.z = cleancplxpair(ntf.z) ntf.p = cleancplxpair(ntf.p) return ntf end function synthesizeNTF0(order::Int, OSR::Int, opt, H_inf::Float64, f0::Float64) (order, z) = synthesizeNTF_setup(order, OSR, opt, f0, false) _synthesizeNTF0_z(order, OSR, z, H_inf, f0) end #==synthesizeNTF1() ===============================================================================# function _synthesizeNTF1_z(order::Float64, osr::Int, opt, z::Vector{Complex{Float64}}, H_inf::Float64, f0::Float64) order_i = array_round(order) zp = z[findall(angle.(z) .> 0)] x0 = (angle.(zp) .- 2π*f0) * osr / π if opt==4 && f0 != 0 #Do not optimize the zeros at f0 deleteat!(x0, abs.(x0) .< 1e-10) end Ts = 1.0 ntf = _zpk(z,zeros(order_i),1,Ts) Hinf_itn_limit = 100 opt_iteration = 5 #Max number of zero-optimizing/Hinf iterations while opt_iteration > 0 #Iteratively determine the poles by finding the value of the x-parameter #which results in the desired H_inf. ftol = 1e-10 z_inf = f0>0.25 ? 1 : -1 if f0 == 0 #Lowpass design HinfLimit = 2^order #!!! The limit is actually lower for opt=1 and low osr if H_inf >= HinfLimit _synthesizeNTF_warn_Hinf() ntf.p = zeros(order_i,1) else x=0.3^(order-1) #starting guess converged = false local delta_x local fprev for itn in 1:Hinf_itn_limit me2 = -0.5*(x^(2/order)) w = (2*collect(1:order_i) .- 1)*π/order #VERIFYME mb2 = 1 .+ me2*exp.(j*w) p = mb2 .- sqrt.(mb2 .^ 2 .- 1) out = findall(abs.(p) .> 1) p[out] = 1 ./ p[out] #reflect poles to be inside the unit circle. p = cplxpair(p) ntf.z = z; ntf.p = p f = real(evalTF(ntf, z_inf))-H_inf #[ x f ] if itn==1 delta_x = -f/100 else delta_x = -f*delta_x/(f-fprev) end xplus = x+delta_x x = (xplus>0) ? xplus : x*0.1 fprev = f if abs(f)<ftol || abs(delta_x)<1e-10 converged = true break end if x>1e6 _synthesizeNTF_warn_Hinf() ntf.z = z; ntf.p = zeros(order_i,1) break end if itn == Hinf_itn_limit _synthesizeNTF_warn_iter() end end end else #Bandpass design. x = 0.3^(order/2-1) #starting guess (not very good for f0~0) c2pif0 = cos(2π*f0) local delta_x local fprev for itn=1:Hinf_itn_limit e2 = 0.5*x^(2/order) w = (2*collect(1:order_i) .- 1)*π/order mb2 = c2pif0 .+ e2*exp.(j*w) p = mb2 .- sqrt.(mb2 .^ 2 .- 1) #reflect poles to be inside the unit circle. out = findall(abs.(p) .> 1) p[out] = 1 ./ p[out] p = cplxpair(p) ntf.z = z; ntf.p = p f = real(evalTF(ntf, z_inf)) - H_inf #[x f] if itn==1 delta_x = -f/100 else delta_x = -f*delta_x/(f-fprev) end xplus = x+delta_x x = (xplus>0) ? xplus : x*0.1 fprev = f if abs(f)<ftol || abs(delta_x)<1e-10 break end if x>1e6 _synthesizeNTF_warn_Hinf() p = zeros(order_i,1) ntf.p = p break end if itn == Hinf_itn_limit _synthesizeNTF_warn_Hinf_iter() end end end ######################################################## if opt < 3 #Do not optimize the zeros opt_iteration = 0 else if f0 == 0 ub = ones(size(x0)) lb = zeros(size(x0)) else ub = 0.5*ones(size(x0)) lb = -ub end opt = Optim.Options(x_tol=0.001, f_tol=0.01, iterations=100) f2min(x) = ds_synNTFobj1(x,p,osr,f0) #Function to minimize (optimum point) x = optimize(f2min, x0, lb, ub, Fminbox(GradientDescent())).minimum x0 = x z = exp.(2π*j*(f0 .+ 0.5/osr*x)) if f0>0 z = padt(z, array_round(length(p)/2), val=exp(2π*j*f0)) end z = vcat(z, conj.(z)) if f0==0 z = padt(z, length(p), val=1.0) end ntf.z = z; ntf.p = p if abs( real(evalTF(ntf, z_inf)) - H_inf ) < ftol opt_iteration = 0 else opt_iteration = opt_iteration - 1 end end end ntf.z = cleancplxpair(ntf.z) ntf.p = cleancplxpair(ntf.p) return ntf end function synthesizeNTF1(order::Int, OSR::Int, opt, H_inf::Float64, f0::Float64) (order, z) = synthesizeNTF_setup(order, OSR, opt, f0, true) _synthesizeNTF1_z(order, OSR, opt, z, H_inf, f0) end #==synthesizeNTF() ===============================================================================# """`NTF = synthesizeNTF(order=3, OSR=64, opt=0, H_inf=1.5, f0=0)` Synthesize a noise transfer function for a delta-sigma modulator. # Inputs - `order`: order of the modulator - `OSR`: oversampling ratio - `opt`: flag for optimized zeros\r - `--> opt=0` -> not optimized, - `--> opt=1` -> optimized, - `--> opt=2` -> optimized with at least one zero at band-center, - `--> opt=3` -> optimized zeros (Requires MATLAB6 and Optimization Toolbox), - `--> opt=[z]` -> zero locations in complex form (TODO?) - `H_inf`: maximum NTF gain - `f0`: center frequency (1->fs) # Output `NTF` is a `_zpk` object containing the zeros and poles of the NTF (See [`_zpk`](@ref)). # Note This is actually a wrapper function which calls either the appropriate version of `synthesizeNTF` based on the availability of the `fmincon` function from the Optimization Toolbox """ function synthesizeNTF(order::Int=3, osr::Int=64; opt=0, H_inf::Float64=1.5, f0::Float64=0.0) if f0 > 0.5 throw(ErrorException("f0 must be less than 0.5.")) end if f0 != 0 && f0 < 0.25/osr @warn(string("(", @__FILE__, ") Creating a lowpass ntf.")) f0 = 0 end if f0 != 0 && mod(order,2) != 0 throw(ErrorException("order must be even for a bandpass modulator.")) end if length(opt)>1 && length(opt)!=order throw(ErrorException("The opt vector must be of length $order(=order).")) end if true #Use version that applies optimization #throw_notimplemented() return synthesizeNTF1(order,osr,opt,H_inf,f0) else return synthesizeNTF0(order,osr,opt,H_inf,f0) end end """`NTF = synthesizeNTF(dsm)` Synthesize a noise transfer function for a ΔΣ modulator. # Output `NTF` is a `_zpk` object containing the zeros and poles of the NTF (See [`_zpk`](@ref)). # See also: - `dsm` types: [`RealDSM`](@ref), [`QuadratureDSM`](@ref) - [`clans()`](@ref): "Closed-loop analysis of noise-shaper." An alternative method for selecting NTFs based on the 1-norm of the impulse response of the NTF. - [`synthesizeChebyshevNTF`](@ref): Select a type-2 highpass Chebyshev NTF. This function does a better job than `synthesizeNTF` if `OSR` or `H_inf` is low. - [`_zpk`](@ref) """ synthesizeNTF synthesizeNTF(dsm::RealDSM) = synthesizeNTF(dsm.order, dsm.OSR, opt=dsm.opt, H_inf=dsm.Hinf, f0=dsm.f0) #synthesizeNTF(dsm::QuadratureDSM) = # synthesizeQNTF(dsm.order, dsm.OSR, dsm.f0, dsm.NG, dsm.ING) #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
711
#RSDeltaSigma: Text generation #------------------------------------------------------------------------------- const ORDINAL_STRING = [ "Zeroth", "First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Nineth", "Tenth", "Twelfth", "Thirteenth", ] function ds_orderString(n::Int, capitalize::Bool=false) idx = n+1 if idx in keys(ORDINAL_STRING) s = ORDINAL_STRING[idx] capitalize || (s = lowercase(s)) else s = "$(n)th" end return s end function str_modulatortype(dsm::AbstractDSM) typestr = (0==dsm.f0) ? "Lowpass" : "Bandpass" if isquadrature(dsm) typestr = "Quadrature " * typestr end return ds_orderString(dsm.order, true) * "-Order " * typestr end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
1465
#RSDeltaSigmaPort: Time domain operations/utilities #------------------------------------------------------------------------------- """`y = delay(x, n=1)` Delay signal x by n samples """ function delay(x, n::Int=1) local y nx = length(x) if nx <= n y = zeros(size(x)) else if 1 == length(size(x)) y = vcat(zeros(n), x[1:nx-n]) elseif 1 == size(x, 2) #Still a row vector, but 2D+ now y = vcat(zeros(n,1), x[1:nx-n,[1]]) else #Assume a single row vector: y = hcat(zeros(1,n), x[[1],1:nx-n]) end end return y end """`y = sinc_decimate(x, m, r)` Decimate x by m-th order sinc of length r. """ function sinc_decimate(x, m::Int, r::Int) x = x[:] #Vector form for i in 1:m x = cumsum(x) x = vcat(x[1:r], x[r+1:end] .- x[1:end-r])/r end y = x[r:r:end] return y end """`applywnd(v, wnd)` Safely apply window `wnd`. Avoids calling `fft()` on an accidentally large matrix. """ function applywnd(v, wnd) szv = size(v); szw = size(wnd) if length(szv) < 1 || length(szw) < 1 throw("applywnd: Does not support 0-length arrays") elseif length(szv) > 2 || length(szw) > 2 throw("applywnd: Does not yet support 3D+ arrays") elseif szv == szw return v .* wnd elseif 1 == length(szw) #Wnd is 1D (column) matrix if szv[2] == szw[1] return v .* wnd' end elseif 1 == szw[1] #Wnd is a row matrix if szv[2] == szw[2] return v .* wnd end end throw(ArgumentError("Unexpected input sizes: $szv & $szw")) end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
8661
#RSDeltaSigmaPort: utilities for transfer functions #------------------------------------------------------------------------------- """`y = evalRPoly(roots,x,k=1)` Compute the value of a polynomial which is given in terms of its roots. """ function evalRPoly(roots,x::AbstractArray,k=1) y = k * ones(size(x)) finiteroots = findall(isfinite.(roots)) roots = roots[finiteroots] for i in 1:length(roots) y = y.*(x .- roots[i]) end return y end evalRPoly(roots,x,k=1) = evalRPoly(roots, [x], k)[1] """`h = evalTF(tf,z)` Evaluates the rational function described by the struct tf at the point(s) given in the z vector. TF must be either a zpk object or a struct containing - form: 'zp' or 'coeff' - zeros,poles,k: if form=='zp' - num,den: if form=='coeff' In Matlab 5, the ss/freqresp() function does nearly the same thing. """ function evalTF(tf::ZPKData,z) h = tf.k * evalRPoly(tf.z,z) ./ evalRPoly(tf.p,z) return h end function evalTF(tf,z) throw(ErrorException("Transfer function of this type not currently supported.")) #elseif any(strcmp(fieldnames(tf),'form')) # if strcmp(tf.form,'zp') # h = tf.k * evalRPoly(tf.zeros,z) ./ evalRPoly(tf.poles,z); # elseif strcmp(tf.form,'coeff') # h = polyval(tf.num,z) ./ polyval(tf.den,z); # else # fprintf(1,'%s: Unknown form: %s\n', mfilename, tf.form); # end #else % Assume zp form # h = tf.k * evalRPoly(tf.zeros,z) ./ evalRPoly(tf.poles,z); #end end """`H=evalTFP(Hs, Hz, f)` Compute the value of a transfer function product Hs*Hz at a frequency f, where Hs is a cts-time TF and Hz is a discrete-time TF. Both Hs and Hz are SISO zpk objects. This function attempts to cancel poles in Hs with zeros in Hz. """ function evalTFP(Hs,Hz,f::AbstractArray) (szeros, spoles, sk) = _zpkdata(Hs, 1) (zzeros, zpoles, zk) = _zpkdata(Hz, 1) slim = min(1e-3, max(1e-5, eps(1.0)^(1/(1+length(spoles))))) zlim = min(1e-3, max(1e-5, eps(1.0)^(1/(1+length(zzeros))))) H = zeros(size(f)) w = 2*pi*f; s = j*w; z=exp.(s) for i in 1:length(f) wi = w[i]; si = s[i]; zi = z[i] cancel = false if !isempty(spoles) cancel = abs.(si .- spoles) .< slim end if !any(cancel) #wi is far from a pole, so just use the product Hs*Hz #H[i] = evalTF(Hs,si) * evalTF(Hz,zi); #use evalRPoly directly with z/p/k data, much faster. (David Alldred, Feb 4 2013) H[i] = sk * evalRPoly(szeros,si) / evalRPoly(spoles,si) * zk * evalRPoly(zzeros,zi) / evalRPoly(zpoles,zi) else #cancel pole(s) of Hs with corresponding zero(s) of Hz cancelz = abs.(zi .- zzeros) .< zlim sumcancel = sum(1*cancel); sumcancelz = sum(1*cancelz) if sumcancelz > sumcancel H[i] = 0.0 elseif sumcancelz < sumcancel H[i] = Inf else H[i] = evalRPoly(szeros,si,sk) * zi^sumcancel * evalRPoly(zzeros[.!cancelz],zi,zk) / (evalRPoly(spoles[.!cancel],si,1)*evalRPoly(zpoles,zi,1)) end end end return H end evalTFP(Hs,Hz,f) = evalTFP(Hs,Hz,[f])[1] #Single value """`evalMixedTF(tf,f, df=1e-5)` Compute the mixed transfer function tf at a frequency f. tf is a struct array with fields Hs and Hz wich represent a continuous-time/discrete-time tfs which must be multiplied together and then added up. """ function evalMixedTF(tf::CTDTPrefilters, f; df=1e-5) H = zeros(size(f)) for i = 1:length(tf) H = H + evalTFP(tf[i].Hs, tf[i].Hz, f) end err = findall(isnan.(H) .| isinf.(H)) if !isempty(err) #Need to fill in the holes. !! Use a "nearby" frequency point for i in err H[i] = evalMixedTF(tf, f[i] .+ df, df=df*10) end end return H end #==Calculators ===============================================================================# """`g = rmsGain(H,f1,f2,N=100)` Compute the root mean-square gain of the discrete-time tf H in the frequency band (f1,f2) """ function rmsGain(H,f1,f2,N::Int=100) w = collect(range(2*pi*f1, stop=2*pi*f2, length=N)) g = norm( evalTF(H, exp.(j*w)) ) / sqrt(N) return g end """`(pGain, Nimp) = powerGain(num,den,Nimp0=100)` Calculate the power gain of a TF given in coefficient form. - `Nimp` is the recommended number of impulse response samples for use in future calls and `Nimp0` is the suggested number to use. """ function powerGain(num, den, Nimp0::Int=100) Nimp = Nimp0 unstable = false sys = _tf(num,den,1) (imp,) = _impulse(sys, Nimp) if sum(abs.(imp[Nimp-10:Nimp])) < 1e-8 && Nimp > 50 #Use fewer samples. Nimp = round(Int, Nimp/1.3) else while sum(abs.(imp[Nimp-10:Nimp])) > 1e-6 Nimp = Nimp*2 (imp,) = _impulse(sys, Nimp) if sum(abs.(imp[Nimp-10:Nimp])) >= 50 || Nimp >= 1e4 #H is close to being unstable unstable = true break end end end pGain = unstable ? Inf : sum(imp .^ 2) return (pGain, Nimp) end """`zpk2 = cancelPZ(zpk1, tol=1e-6)` Cancel zeros/poles in a zpk system """ function cancelPZ(zpk1, tol::Float64=1e-6) (z, p) = _zpkdata(zpk1, 1) zpk2 = deepcopy(zpk1) #Captures k, and whether tf is in s or z #Need to go in reverse order because z gets smaller with each cancellation for i = length(z):-1:1 d = z[i] .- p cancel = findall(abs.(d) .< tol) if !isempty(cancel) deleteat!(p, cancel[1]) deleteat!(z, i) end end zpk2.z = z zpk2.p = p return zpk2 end #==infnorm ===============================================================================# """`nabsH(w, H)` Computes the negative of the absolute value of H at the specified frequency on the unit circle. This function is used by infnorm(). """ function nabsH(w, H) z = exp.(j*w) return -abs.(evalTF(H, z)) end """`(Hinf,fmax) = infnorm(H)` Find the infinity norm of a z-domain transfer function. Get a rough idea of the location of the maximum. """ function infnorm(H) N = 129 w = range(0, stop=2π, length=N); dw = 2π/(N-1) Hval = abs.(evalTF(H, exp.(j*w))) wi = argmax(abs.(Hval))[1] Hinf = Hval[wi] local wmax if true #NEEDS_OPTIMIZATION opt = Optim.Options(x_tol=1e-8, f_tol=1e-6) f2min(w) = nabsH(w, H) #Function to minimize (optimum point) lower = w[wi]-dw; upper = w[wi]+dw wmax = optimize(f2min, lower, upper, GoldenSection()).minimum else msg = "Hinf: Warning. Optimization toolbox functions not found.\n" * " The result returned may not be very accurate." @warn(msg) wmax = w[wi] end Hinf = -nabsH(wmax, H) fmax = wmax/(2*pi) return (Hinf, wmax) end #==calculateTF ===============================================================================# #Use a loophole to set complex poles and zeros in zpk objects #MALaforge: I think this tries to implement minreal() function setPolesAndZeros(z,p,k) tol = 3e-5 #tolerance for pole-zero cancellation z = deepcopy(z) #Don't change original Z = _zpk(ComplexF64[0.0],ComplexF64[],1.0,1.0) ztf = _zpk(ComplexF64[],ComplexF64[],k,1.0) for i in 1:length(p) match = abs.(p[i] .- z) .< tol if any(match) f = findall(match) deleteat!(z, f[1]) else #ztf = ztf/(Z-p[i]) #Original code push!(ztf.p, p[i]) #VERIFYME: Think this is intent of original code end end for i in 1:length(z) #ztf = ztf*(Z-z[i]) #Original code push!(ztf.z, z[i]) #VERIFYME: Think this is intent of original code end return ztf end """`(NTF,STF) = calculateTF(ABCD, k=1, wantSTF=true)` Calculate the NTF and STF of a delta-sigma modulator whose loop filter is described by the ABCD matrix, assuming a quantizer gain of k. The NTF and STF are zpk objects. """ function calculateTF(ABCD, k::Vector=[1], wantSTF::Bool=true) nq = length(k) n = size(ABCD,1) - nq nu = size(ABCD,2) - size(ABCD,1) A,B,C,D = partitionABCD(ABCD, nu+nq) B1 = B[:,1:nu] B2 = B[:,nu+1:end] D1 = D[:,1:nu] if any(any( D[:,nu+1:end] .!= 0 )) throw("D2 must be zero") end K = diagm(k) #Find the noise transfer function by forming the closed-loop #system (sys_cl) in state-space form. Acl = A + B2*K*C Bcl = hcat(B1 + B2*K*D1, B2) Ccl = K*C Dcl = [K*D1 eye(nq)] #map(display, [Acl, Bcl, Ccl, Dcl]) local NTF, STF tol = min(1e-3, max(1e-6, eps(1.0)^(1/(size(ABCD,1))))) if false # true || all(imag.(ABCD) .== 0) #real modulator #REQUESTHELP sys_cl = _ss(Acl,Bcl,Ccl,Dcl,1) sys_tf = ControlSystems.tf(sys_cl) mtfs = _minreal(sys_tf, tol) display(mtfs) @show (mtfs.nu, mtfs.ny), (nu, nq) #MALaforge: Can't make sense of the following; not sure what structure should be: STF = mtfs[:,1:nu] NTF = mtfs[:,nu+1:nu+nq] else #quadrature modulator and less advanced language features p = eig(Acl) NTFz = eig(A) NTF = setPolesAndZeros(NTFz, p, 1) if wantSTF @warn("Sorry. calculateTF cannot compute the STF for a complex modulator with this version of the code.") end STF=nothing end return (NTF, STF) end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
778
#RSDeltaSigmaPort: Windowing functions #------------------------------------------------------------------------------- """`w = ds_hann(n)` A Hann window of length n. Does not smear tones located exactly in a bin. """ function ds_hann(n::Int) w = .5*(1 .- cos.(2*pi*collect(0:n-1)/n) ) return w end """`circ_smooth(x,n)` """ function circ_smooth(x::Array{T, 2}, n::Int) where T <: Number szx = size(x) if szx[1] != 1 throw("Arrays with nrows!=1 are not yet supported") end nx = szx[2] w = ds_hann(n)'/(n/2) xw = conv(x, w) y = circshift(hcat(xw[:, n:nx], xw[:, 1:n-1] .+ xw[:, nx+1:end]), (0, div(n,2)-1)) return y end function circ_smooth(x::Vector, n::Int) x = conv2seriesmatrix2D(x) return circ_smooth(x, n)[:] #Keep things in vector form end #Last line
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
562
@testset "Array-related tests" begin show_testset_section() #Scope for test data @testset "pad*()" begin show_testset_description() v = [4,5,6,10] @test padt(v, 7) == [0,0,0, 4,5,6,10] @test padl(v, 7) == [0,0,0, 4,5,6,10] @test padb(v, 7) == [4,5,6,10, 0,0,0] @test padr(v, 7) == [4,5,6,10, 0,0,0] v = [4 5 6; 8 10 11] @test padt(v, 5) == [0 0 0; 0 0 0; 0 0 0; 4 5 6; 8 10 11] @test padb(v, 5) == [4 5 6; 8 10 11; 0 0 0; 0 0 0; 0 0 0] @test padl(v, 7) == [0 0 0 0 4 5 6; 0 0 0 0 8 10 11] @test padr(v, 7) == [4 5 6 0 0 0 0; 8 10 11 0 0 0 0] end end
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
1284
@testset "Ml function tests" begin show_testset_section() #Scope for test data p = exp.((2*pi*im/7) .* collect(0:6)) #= 1.0 + 0.0im 0.6234898018587336 + 0.7818314824680298im -0.22252093395631434 + 0.9749279121818236im -0.900968867902419 + 0.43388373911755823im -0.9009688679024191 - 0.433883739117558im -0.2225209339563146 - 0.9749279121818236im 0.6234898018587334 - 0.7818314824680299im =# @testset "cplxpair()" begin show_testset_description() rtol = 1e-12 pA = exp.((2*pi*im/7) .* collect(0:6)) pA = RSDeltaSigmaPort.cplxpair(pA) p = -0.900968867902419 + 0.43388373911755823im @test pA[1] ≈ conj(p) rtol = rtol @test pA[2] ≈ p rtol = rtol p = -0.22252093395631434 + 0.9749279121818236im @test pA[3] ≈ conj(p) rtol = rtol @test pA[4] ≈ p rtol = rtol p = 0.6234898018587336 + 0.7818314824680298im @test pA[5] ≈ conj(p) rtol = rtol @test pA[6] ≈ p rtol = rtol p = 1.0 + 0.0im @test pA[7] ≈ p rtol = rtol end @testset "poly()" begin show_testset_description() @test RSDeltaSigmaPort.poly([3,4,5]) == [1, -12, 47, -60] end @testset "interp()" begin show_testset_description() abstol = 1e-15 v = sin.(0:.1:2π) OSR = 32 @test all(abs.(RSDeltaSigmaPort.interp(v, OSR)[1:OSR:end] .- v[:]) .< abstol) end end
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
code
432
using Test, RSDeltaSigmaPort function printheader(title) println("\n", title, "\n", repeat("=", 80)) end function show_testset_section() println() @info "SECTION: " * Test.get_testset().description * "\n" * repeat("=", 80) end function show_testset_description() @info "Testing: " * Test.get_testset().description end testfiles = ["mlfunc.jl", "arrays.jl"] for testfile in testfiles include(testfile) end :Test_Complete
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
docs
6570
<!-- Reference-style links to make tables & lists more readable --> [Gallery]: <https://github.com/ma-laforge/FileRepo/blob/master/RSDeltaSigmaPort/notebook> [CMDimDataJL]: <https://github.com/ma-laforge/CMDimData.jl> [InspectDRJL]: <https://github.com/ma-laforge/InspectDR.jl> # RSDeltaSigmaPort.jl: Port of Richard Schreier's Delta Sigma Toolbox&sup1; **Galleries:** [:art: Sample notebooks (w/outputs)][Gallery] &sup1;Richard Schreier (2021). Delta Sigma Toolbox (<https://www.mathworks.com/matlabcentral/fileexchange/19-delta-sigma-toolbox>), MATLAB Central File Exchange. Retrieved March 20, 2021. [![Build Status](https://github.com/ma-laforge/RSDeltaSigmaPort.jl/workflows/CI/badge.svg)](https://github.com/ma-laforge/RSDeltaSigmaPort.jl/actions?query=workflow%3ACI) ### :warning: Progress report ***INTERMEDIATE STAGE OF PORT***: A significant portion of the Delta Sigma toolbox has been ported. The following high-level functionnality has (at least partially) been ported: - `simulateDSM`, `simulateMS`, `simulateSNR`, `simulateHBF` - `synthesizeNTF`, `realizeNTF`, `realizeNTF_ct` - `calculateSNR`, `peakSNR`, `predictSNR` - `calculateTF`, `evalTF`, `evalTFP` - `stuffABCD`, `scaleABCD`, `mapABCD`, `partitionABCD` - `mapCtoD`, `mapQtoR` - `exampleHBF` - `pulse`, `impL1` - `lollipop`, `logsmooth` - `documentNTF`, `plotExampleSpectrum` And demos: - `dsdemo1`, ..., `dsdemo6`, `dsexample1`, `dsexample2`, `demoLPandBP` ## Table of contents 1. [Description](#Description) 1. Sample usage 1. [IJupyter notebooks (`notebook/`)](notebook/) 1. [IJupyter notebooks (with output) &#x21AA;][Gallery] 1. [Sample directory w/plain `.jl` files (`sample/`)](sample/) 1. [Plotting](#Plotting) 1. [Installation](#Installation) 1. [Running sample scripts](#SampleScripts) 1. [Function (API) help](#APIHelp) 1. [Julia tips](doc/juliatips.md) 1. [Useful functions](doc/juliatips.md#FunctionLibraries) 1. [`linspace()` & `logspace()`](doc/juliatips.md#LinLogSpace) 1. [Known limitations](#KnownLimitations) 1. [TODO](doc/todo.md) <a name="Description"></a> ## Description As its name suggests, `RSDeltaSigmaPort.jl` is a Julia port of Richard Schreier's Delta Sigma Toolbox. ### Module name Note that this module is not named something like `DeltaSigmaModulators.jl`, thus allowing someone else to appropriate the package name later on. Hopefully, `RSDeltaSigmaPort` will eventually be superseded by a more generically named package that is better integrated with Julia's ecosystem than this simple port. ### Design decisions This module tries to remain true to the original Delta Sigma Toolbox while conforming to some Julia patterns, including: - Multiple dispatch (make function calls simpler to write). - ***Not*** writing each function definition in its own, separate file. - Using keyword arguments when deemed appropriate. - Returning `NamedTuple`s instead of simple arrays when multiple values are returned. - ... Progressively replacing modulator parameters in function calls with `RealDSM` and `QuadratureDSM` objects: - Simplifies function interface for user. - Centralizes defaults for parameter values on construction of `RealDSM` and `QuadratureDSM`. - Looking to keep "original" function interface (with individual modulator parameters) available for accustomed users. - Looking to remove default values from said interface to avoid unexpected bugs from inconsistent defaults. - Might change with time (not sure if certain parameters, like `opt`, should migrate to a NTF structure or something). <a name="Plotting"></a> ## Plotting `RSDeltaSigmaPort.jl` uses [CMDimData.jl/EasyPlot][CMDimDataJL] to handle plotting. For examples on how to generate ***new/customized*** plots, see the built-in functions found in `plot_*.jl` files in the source directory: - [`src/`](src/) <a name="Installation"></a> ## Installation The `RSDeltaSigmaPort.jl` toolbox is written using the Julia programming language. Unless you already have Julia installed, you will need to first install the base language. Simply download \& install the most recent version of Julia from Julia's official "downloads" page. **Julia's official "downloads" page:** - <https://julialang.org/downloads/> Step 2 is to install the `RSDeltaSigmaPort.jl` package itself. Since `RSDeltaSigmaPort.jl` is registered with Julia's **General** registry, you can automatically download & install it from Julia's built-in package manager. Simply launch Julia, and run the following from the command prompt: ```julia-repl julia> ] pkg> add RSDeltaSigmaPort ``` <a name="SampleScripts"></a> ## Running sample scripts Sample scripts in the `sample/` subdirectory can be run using `include()`. For convenience, the `@runsample` macro automatically locates the script path and executes `include()` for you: ```julia-repl julia> using RSDeltaSigmaPort #Will take a while to load, compile, etc... julia> import RSDeltaSigmaPort: @runsample julia> @runsample("dsdemo1.jl") julia> @runsample("dsdemo2.jl") julia> @runsample("dsdemo3.jl") julia> @runsample("dsdemo4_audio.jl") julia> @runsample("dsdemo5.jl") julia> @runsample("dsdemo6.jl") julia> @runsample("dsexample1.jl") julia> @runsample("dsexample2.jl") julia> @runsample("demoLPandBP.jl") ``` <a name="APIHelp"></a> ## Function (API) help Typing `?RSDeltaSigmaPort` in Julia's command line gives you a list of available functions: ```julia-repl julia> ? help?> RSDeltaSigmaPort ``` Information on individual functions can be obtained in a similar fashion. Example: ```julia-repl julia> ? help?> simulateDSM ``` ### Original documentation Richard Schreier's original documentation is available here: - [`original_source/delsig/OnePageStory.pdf`](original_source/delsig/OnePageStory.pdf) - [`original_source/delsig/DSToolbox.pdf`](original_source/delsig/DSToolbox.pdf) <a name="KnownLimitations"></a> ## Known limitations Functions that are not supported: - `printmif()` ### [TODO](doc/todo.md) ### Compatibility Extensive compatibility testing of `RSDeltaSigmaPort.jl` has not been performed. The module has been tested using the following environment(s): - Linux / Julia-1.6.0 ## :warning: Disclaimer - ***INTERMEDIATE STAGE OF PORT***: A significant portion of the Delta Sigma toolbox has been ported. - Jupyter [notebooks](notebook/) might be slightly broken/out of date. If so, see their counterparts in the [`sample/`](sample/) directory for a more regularly maintained example. - The `RSDeltaSigmaPort.jl` module is not yet mature. Expect significant changes.
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
docs
1392
# RSDeltaSigma: Julia tips 1. [Useful functions](#FunctionLibraries) 1. [`linspace()` & `logspace()`](#LinLogSpace) <a name="FunctionLibraries"></a> ## Useful functions Not all functions you might want to use are directly available in julia. In many cases, you need to make functions available by importing them from different libraries: ```julia import Random import Statistics: mean import LinearAlgebra import LinearAlgebra: norm, diagm, eigen import SpecialFunctions: erfinv import FFTW: fft, fftshift import DSP: conv import Polynomials: roots, Polynomial import Printf: @sprintf ``` `RSDeltaSigma` does not automatically export these symbols/functions (make the functions available to the user). This choice was deliberatly made to avoid symbol collisions in cases where the user needs to manually import said symbols to get other portions of their code working. <a name="LinLogSpace"></a> ## `linspace()` & `logspace()` Functions `linspace()` & `logspace()` don't exist in Julia 1.0+. Instead, you should use `range()`: 1. `range(start, stop=stop, length=n)`: Constructs a `StepRangeLen` object. - `collect(range(0, stop=100, length=101))`: Generates a `Vector{Float64}` (not `Vector{Int}`). 1. `10 .^ range(start, stop=stop, length=n)`: Generates a `Vector{Float64}` object. - `10 .^ range(-10, stop=10, length=101)`: Log-spaced values &isin; [1.0e-10, 1.0e10].
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
docs
615
# RSDeltaSigma: TODO ## Migrate to use ControlSystems.jl directly? Deprecate legacy functions/names to use slightly altered API from ControlSystems.jl? ```julia #See: export _ss, _zpk, _zpkdata export _zp2ss, _zp2tf, _freqz, _tf, _minreal, _impulse #etc. ``` ## Deprecate `array_round()` - Figure out if orignial code rounded indicies to nearest integer, or implicitly applied `floor()`, etc. - Start using `div(num, den)` more if possible (should be faster than `round`/`floor`/`ceil`). ## Add regression tests. Very little code is tested at the moment. ## List other known elements needing attention HERE.
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "BSD-3-Clause", "MIT" ]
0.4.2
286a0cf04d4e951697988474d818613ec4632282
docs
638
<!-- Reference-style links to make tables & lists more readable --> [Gallery]: <https://github.com/ma-laforge/FileRepo/blob/master/RSDeltaSigmaPort/notebook> # RSDeltaSigmaPort: Sample notebooks ## :warning: Environment stack Jupyter notebooks seems to have a built-in mechanism that recursively adds ***all*** `Project.toml` files appearing in the active `.ipynb` notebook's ("real path") parent directories to the environment stack. ## Blank notebooks The notebooks in this folder should all be clear of data to avoid repository bloat. ## Notebooks that include outputs Notebooks that include outputs can be found [here][Gallery].
RSDeltaSigmaPort
https://github.com/ma-laforge/RSDeltaSigmaPort.jl.git
[ "MIT" ]
0.1.0
69f74150a58a45cce84e62ad44460df0fd29ce34
code
290
# A very complicated example to use `BEE.jl` # # We will *prove* the following fact using BEE @beeint x 0 5 @beeint y -4 9 @beeint z -5 10 x + y == z @beeint w 0 10 xl = [beebool("x$i") for i=1:4] xl[1] == -xl[2] xl[2] == true sum([-xl[1], xl[2], -xl[3], xl[4]]) == w BEE.render()
BeeEncoder
https://github.com/newptcai/BeeEncoder.jl.git
[ "MIT" ]
0.1.0
69f74150a58a45cce84e62ad44460df0fd29ce34
code
295
# A simple example to use `BeeEncoder.jl` using BeeEncoder @beeint x 0 5 @beeint y -4 9 @beeint z -5 10 @constrain x + y == z @beeint w 0 10 xl = @beebool x[1:4] @constrain xl[1] == -xl[2] @constrain xl[2] == true @constrain sum([-xl[1], xl[2], -xl[3], xl[4]]) == w BeeEncoder.render()
BeeEncoder
https://github.com/newptcai/BeeEncoder.jl.git
[ "MIT" ]
0.1.0
69f74150a58a45cce84e62ad44460df0fd29ce34
code
22434
module BeeEncoder import Base: -, +, *, /, mod, max, min, ==, <, <=, !=, >, >=, sum, show, convert, isequal, in using Suppressor export BeeInt, BeeBool, BeeModel, BeeSolution, @beeint, @beebool, beeint, beebool, render, reset, and, or, iff, alldiff, constrain, @constrain, solve, hasvar, hasbool, hasint, fetchbool, getbool, getint, GBL_MODEL, capture_render # ------------------------------------------------------------- # abstract types # ------------------------------------------------------------- "An object that can be rendered to BEE syntax" abstract type BeeObject end "A symbol in BEE sytanx. Can be either a variable or a value." abstract type BeeSymbol <: BeeObject end abstract type BeeBoolean <: BeeSymbol end abstract type BeeInteger <: BeeSymbol end BB = Union{BeeBoolean, Bool} ZZ = Union{BeeInteger, Int} "Reload `isequal` to allow using `BeeSymbol` comparing them for `Dict`." isequal(v1::BeeSymbol, v2::BeeSymbol) = v1 === v2 "Reload `in` to allow checking if a `BeeSymbol` is in an array" function in(v::T, vs::Array{T,1}) where T <: BeeSymbol for s in vs if v === s return true end end false end # ------------------------------------------------------------- # BEE integer variable # ------------------------------------------------------------- "An integer variable in BEE syntax" struct BeeInt <: BeeInteger name::String lo::Int hi::Int function BeeInt(model, name, lo, hi) if lo > hi error("$lo > $hi") end if hasvar(model, name) error("Variable $name has already been defined in $model") end var = new(name, lo, hi) model.intdict[name] = var end end BeeInt(name::String, lo::Int, hi::Int) = BeeInt(GBL_MODEL, name, lo, hi) BeeInt(name::Symbol, lo, hi) = BeeInt(string(name), lo, hi) macro beeint(name, lo, hi) q = Expr(:block) if isa(name, Symbol) ex = :($(esc(name)) = beeint($(string(name)), $lo, $hi)) push!(q.args, ex) push!(q.args, escvar(name)) # return all of the variables we created elseif isa(name, Expr) && name.head == :ref vhead = name.args[1] vlist = [] for i in eval(name.args[2]) vhead = name.args[1] vstr = "$vhead$i" vsym = Symbol(vstr) ex = :($(esc(vsym)) = beeint($(vstr), $lo, $hi)) push!(vlist, vsym) push!(q.args, ex) end push!(q.args, escvar(vlist)) end q end "Create an integer varaible called `name` in `GBL_MODEL`" beeint(name, lo, hi) = beeint(GBL_MODEL, name, lo, hi) "Create an integer varaible called `name` in `GBL_MODEL`" beeint(model, name, lo, hi) = BeeInt(model, name, lo, hi) render(io::IO, var::BeeInt) = print(io, "new_int($var, $(var.lo), $(var.hi))\n") # ------------------------------------------------------------- # BEE boolean variable # ------------------------------------------------------------- "A boolean variable in BEE syntax" struct BeeBool <: BeeBoolean name::String function BeeBool(model, name) if hasvar(model, name) error("Variable $name has already been defined in $model") end var = new(name) model.booldict[name] = var end end BeeBool(name::String) = BeeBool(GBL_MODEL, name) BeeBool(name::Symbol) = BeeBool(string(name)) function escvar(var) if isa(var, Symbol) vs = esc(var) else vs = Expr(:vect, [esc(v) for v in var]...) end vs end macro beebool(namelist...) q = Expr(:block) varlist = [] # list of boolean variables to create for name in namelist if isa(name, Symbol) push!(varlist, name) ex = :($(esc(name)) = beebool($(string(name)))) push!(q.args, ex) elseif isa(name, Expr) && name.head == :ref vhead = name.args[1] vlist = [] for i in eval(name.args[2]) vhead = name.args[1] vstr = "$vhead$i" vsym = Symbol(vstr) ex = :($(esc(vsym)) = beebool($(vstr))) push!(vlist, vsym) push!(q.args, ex) end push!(varlist, vlist) end end if length(varlist) > 1 ret = Expr(:tuple, map(escvar, varlist)...) else ret = escvar(varlist[1]) end push!(q.args, ret) # return all of the variables we created q end "Create a boolean varaible called `name` in `GBL_MODEL`" beebool(name) = beebool(GBL_MODEL, name) "Create a boolean varaible called `name` in `model`" beebool(model, name) = BeeBool(model, name) render(io::IO, var::BeeBool) = print(io, "new_bool($var)\n") "The negate of a boolean variable in BEE syntax" struct BeeNegateBool <:BeeBoolean boolvar::BeeBool end show(io::IO, v::BeeNegateBool) = print(io, "-", v.boolvar) (-)(var::BeeBool) = BeeNegateBool(var) (-)(var::BeeNegateBool) = var.boolvar # ------------------------------------------------------------- # BEE literals # ------------------------------------------------------------- "An integer value like `1`" struct BeeIntLiteral <: BeeInteger val::Int end show(io::IO, v::BeeIntLiteral) = print(io, v.val) convert(::Type{BeeInteger}, v::Int) = BeeIntLiteral(v) convert(::Type{BeeSymbol}, v::Int) = BeeIntLiteral(v) "A boolean value, i.e., `true` or `false`" struct BeeBoolLiteral <: BeeBoolean val::Bool end show(io::IO, v::BeeBoolLiteral) = print(io, v.val) convert(::Type{BeeBoolean}, v::Bool) = BeeBoolLiteral(v) convert(::Type{BeeSymbol}, v::Bool) = BeeBoolLiteral(v) """ render(obj::BeeObject) Render `obj` to BEE syntax and print it to `stdout`. """ render(obj::BeeObject) = render(Base.stdout, obj) render(arr::Array{T, 1}) where T <: Any = render(Base.stdout, arr) render(io::IO, arr::Array{T, 1}) where T <: BeeObject = show(io, arr) show(io::IO, v::BeeSymbol) = print(io, v.name) function show(io::IO, arr::Array{T, 1}) where T <: BeeObject print(io, "[", join(arr, ", "), "]") end # ------------------------------------------------------------- # BEE expressions # ------------------------------------------------------------- """ An expression can be made part of a `BeeObject`, but they themselves cannot be rendered. """ abstract type BeeExpression end function show(io::IO, tuple::NTuple{N, T} where {N, T <: BeeSymbol}) print(io, join(tuple, ", ")) end # ------------------------------------------------------------- # BEE Constrains # ------------------------------------------------------------- struct BeeConstraint <: BeeObject name::String # Don't check the type of the array varlist::Array{T, 1} where T end """ render(io, cons) Render `cons` to BEE syntax. For constraints, there's is no difference between how they are rendered and printed. """ render(io::IO, constraint::BeeConstraint) = print(io, constraint, "\n") function show(io::IO, constraint::BeeConstraint) varstr = join(constraint.varlist, ", ") print(io, constraint.name, "(", varstr, ")") end # ------------------------------------------------------------- # BEE model # ------------------------------------------------------------- struct BeeModel <: BeeObject name::String intdict::Dict{String, BeeInt} booldict::Dict{String, BeeBool} conslist::Array{BeeConstraint, 1} end BeeModel(name::String) = BeeModel(name, Dict{String, BeeInt}(), Dict{String, BeeBool}(), Array{BeeConstraint,1}()) show(io::IO, m::BeeModel) = print(io, "BEE model [$(m.name)]") show(io::IO, ::MIME"text/plain", m::BeeModel) = print(io, """BEE model [$(m.name)]: * Integer variables: $(collect(values(m.intdict))) * Boolean variables: $(collect(values(m.booldict))) * Constraint: $(m.conslist)""") "Check if the model has a variable called `name`" hasvar(model::BeeModel, name::String) = haskey(model.intdict, name) || haskey(model.booldict, name) "Check if the model has a bollean variable called `name` in `model`" hasbool(model::BeeModel, name) = haskey(model.booldict, name) "Check if the model has a bollean variable called `name` in `GBL_MODEL`" hasbool(name) = hasbool(GBL_MODEL, name) "Check if the model has a integer variable called `name` in `model`" hasint(model::BeeModel, name) = haskey(model.intdict, name) "Check if the model has a integer variable called `name` in `GBL_MODEL`" hasint(name) = hasint(GBL_MODEL, name) "Retrive an existing integer variable called `name` in `GBL_MODEL`" getint(model, name) = model.intdict[name] "Retrive an existing integer variable called `name` in `GBL_MODEL`" getint(name) = getint(GBL_MODEL, name) "Either create or retrive an existing boolean variable called `name` in `model`" function fetchbool(model::BeeModel, name) if hasbool(model, name) model.booldict[name] else beebool(model, name) end end "Either create or retrive an existing boolean variable called `name` in `GBL_MODEL`" fetchbool(name) = fetchbool(GBL_MODEL, name) "Retrive an existing boolean variable called `name` in `GBL_MODEL`" getbool(model, name) = model.booldict[name] "Retrive an existing boolean variable called `name` in `GBL_MODEL`" getbool(name) = getbool(GBL_MODEL, name) """ constrain(model, cons) Add the `cons` to `model`. Note that unlike a variable, a constraint is not automatically added to any model when it is created. """ function constrain(model::BeeModel, cons::BeeConstraint) push!(model.conslist, cons) cons end constrain(cons) = constrain(GBL_MODEL, cons) macro constrain(cons) :(constrain($(esc(cons)))) end "Render the global model `GBL_MODEL` to BEE syntax and print it to `stdout`." render() = render(Base.stdout, GBL_MODEL) "Render the global model `GBL_MODEL` to BEE syntax and print it to `io`." render(io::IO) = render(io, GBL_MODEL) function render(io::IO, model::BeeModel) for intv in values(model.intdict) render(io, intv) end for boolv in values(model.booldict) render(io, boolv) end for cons in model.conslist render(io, cons) end print(io, "solve satisfy\n") end "Delete all variables and constraints from the default model." function reset() global GBL_MODEL = BeeModel("defaul model") end # ------------------------------------------------------------- # Call BumbleBEE directly from Julia # ------------------------------------------------------------- struct BeeSolution sat::Bool intdict::Dict{String, Int} booldict::Dict{String, Bool} end "Call `BumbleBEE` to solve the `model` and print the output into `io`" function solve(model::BeeModel, io::IO, deletefile=true) # Find where is BumbleBEE beepath = Sys.which("BumbleBEE") beedir = dirname(beepath) # Render solution to the file tempf = tempname() * ".bee" open(tempf, "w") do io render(io) end tempout = tempname() * ".sol" # Solve with BumbleBEE curdir = pwd() cd(beedir) println(tempout) run(pipeline(`./BumbleBEE $tempf`, stdout=tempout)) output = readlines(tempout) cd(curdir) if deletefile rm(tempf) rm(tempout) end # filter comments rc = r"^%" ri = r"^\s*(\w+)\s*=\s*(-?+\d+)" rb = r"^\s*(\w+)\s*=\s*(true|false)" runsat = r"=====UNSATISFIABLE=====" sat = true intdict = Dict{String, Int}() booldict = Dict{String, Bool}() for line in output println(io, line) if match(runsat, line) !== nothing sat = false end if match(rc, line) !== nothing continue elseif (m = match(ri, line)) !== nothing name, val = m.captures intdict[name] = parse(Int, val) elseif (m = match(rb, line)) !== nothing name, val = m.captures booldict[name] = parse(Bool, val) end end BeeSolution(sat, intdict, booldict) end " Solve the default model and print the solution to `stdout`." solve() = solve(GBL_MODEL, Base.stdout) solve(deletefile::Bool) = solve(GBL_MODEL, Base.stdout, deletefile) show(io::IO, ::MIME"text/plain", sol::BeeSolution) = print(io, """ BEE solution: * Satisfiable: $(sol.sat) * Integer variables: $(sol.intdict) * Boolean variables: $(sol.booldict)""") # ------------------------------------------------------------- # BEE operator for both integer and boolean # ------------------------------------------------------------- # Create BEE summation expression, which applies to list of symbols struct BeeSum{T <: BeeSymbol} <: BeeExpression varlist::Array{BeeSymbol, 1} end sum(varlist::Array{T, 1}) where T <: BeeBoolean = BeeSum{T}(varlist) sum(varlist::Array{T, 1}) where T <: BeeInteger = BeeSum{T}(varlist) # Create BEE operator on summation. for (VT, VF) in [(:BeeBoolean, :bool), (:BeeInteger, :int)], (OP, EF) in [(:(<=), :leq), (:(>=), :geq), (:(==), :eq), (:(<), :lt), (:(>), :gt), (:(!=), :neq)] @eval BeeEncoder begin # Some of these are not symmetirc. Let's don't switch order # $OP(lhs::ZZ, rhs::BeeSum{T} where T <: $VT) = $OP(rhs, lhs) $OP(lhs::BeeSum{T} where T <: $VT, rhs::ZZ) = $(Symbol(VF, :_array_sum_, EF))(lhs.varlist, rhs) end end # ------------------------------------------------------------- # BEE operator for integers # ------------------------------------------------------------- # Boolean operator on two integers intBOP = [(:BeeLeq, :leq, :(<=)), (:BeeGeq, :geq, :(>=)), (:BeeEq, :eq, :(==)), (:BeeLt, :lt, :(<)), (:BeeGt, :gt, :(>)), (:BeeNeq, :neq, :(!=))] # Arithmetic operator on two integers intAOP = [(:BeePlus, :plus, :+), (:BeeTimes, :times, :*), (:BeeMax, :max, :max), (:BeeMin, :min, :min), (:BeeDiv, :div, :/), (:BeeMod, :mod, :mod)] # Define function for integer $OP integer. Avoid matching `Int` $OP `Int` for (ET, EF, OP) in [intBOP; intAOP] @eval BeeEncoder begin $OP(lhs::Int, rhs::BeeInteger) = $ET(BeeIntLiteral(lhs), rhs) $OP(lhs::BeeInteger, rhs::Int) = $ET(lhs, BeeIntLiteral(rhs)) $OP(lhs::BeeInteger, rhs::BeeInteger) = $ET(lhs, rhs) end end # Create BEE boolean expression for two integers, which applies to two `BeeInteger`. for (ET, EF, OP) in intBOP @eval BeeEncoder begin struct $ET <: BeeExpression lhs::BeeInteger rhs::BeeInteger end # `lhs` is true `iff` rhs is true (==)(lhs::BeeBoolean, rhs::$ET) = rhs == lhs function (==)(lhs::$ET, rhs::BeeBoolean) $(Symbol(:int_, EF, :_reif))(lhs.lhs, lhs.rhs, rhs) end # `lhs` is true `iff` rhs is true (==)(lhs::Bool, rhs::$ET) = rhs == lhs function (==)(lhs::$ET, rhs::Bool) if rhs $(Symbol(:int_, EF))(lhs.lhs, lhs.rhs) else $(Symbol(:int_, EF, :_reif))(lhs.lhs, lhs.rhs, rhs) end end end end # Create BEE arithmetic expression for two integers, which applies to two `BeeInteger`. for (ET, EF, OP) in intAOP @eval BeeEncoder begin struct $ET <: BeeExpression lhs::BeeInteger rhs::BeeInteger end # `lhs` == `rhs` is true (==)(lhs::ZZ, rhs::$ET) = rhs == lhs function (==)(lhs::$ET, rhs::ZZ) $(Symbol(:int_, EF))(lhs.lhs, lhs.rhs, rhs) end end end # Create BEE allDiff operations on one integer array intarrayOP = [(:BeeArrayAllDiff, :allDiff, :alldiff, :_reif)] for (ET, EF, OP, TAIL) in intarrayOP @eval BeeEncoder begin struct $ET <: BeeExpression varlist::Array{BeeInteger, 1} end # No need to check type here $OP(varlist::Array{T, 1} where T <: ZZ) = $ET(varlist) (==)(lhs::BeeInteger, rhs::$ET) = rhs == lhs function (==)(lhs::$ET, rhs::BeeInteger) $(Symbol(:int_array_, EF, TAIL))(lhs.varlist, rhs) end (==)(lhs::Bool, rhs::$ET) = rhs == lhs function (==)(lhs::$ET, rhs::Bool) if rhs $(Symbol(:int_array_, EF))(lhs.varlist) else $(Symbol(:int_array_, EF, TAIL))(lhs.varlist, rhs) end end end end # Create BEE operations on one integer array intarrayOP = [(:BeeArrayPlus, :plus, :plus), (:BeeArrayTimes, :times, :times), (:BeeArrayMax, :max, :max), (:BeeArrayMin, :min, :min)] for (ET, EF, OP) in intarrayOP @eval BeeEncoder begin struct $ET <: BeeExpression varlist::Array{BeeInteger, 1} end # No need to check type here $OP(varlist::Array{T, 1} where T <: ZZ) = $ET(varlist) (==)(lhs::BeeInteger, rhs::$ET) = rhs == lhs function (==)(lhs::$ET, rhs::BeeInteger) $(Symbol(:int_array_, EF))(lhs.varlist, rhs) end end end # ------------------------------------------------------------- # BEE operator for boolean # ------------------------------------------------------------- # hard code this bit since it's just one function (==)(lhs::Bool, rhs::BeeBoolean) = bool_eq(lhs, rhs) (==)(lhs::BeeBoolean, rhs::Bool) = bool_eq(lhs, rhs) (==)(lhs::BeeBoolean, rhs::BeeBoolean) = bool_eq(lhs, rhs) # Logic Expressions on two boolean. boolOP = [(:BeeAnd, :and, :and), (:BeeOr, :or, :or), (:BeeXor, :xor, :xor), (:BeeIff, :iff, :iff)] for (ET, EF, OP) in boolOP @eval BeeEncoder begin struct $ET <: BeeExpression lhs::BeeSymbol rhs::BeeSymbol end # No need to check type here $OP(lhs, rhs) = $ET(lhs, rhs) (==)(lhs::BeeBoolean, rhs::$ET) = rhs == lhs function (==)(lhs::$ET, rhs::BeeBoolean) $(Symbol(:bool_, EF, :_reif))(lhs.lhs, lhs.rhs, rhs) end (==)(lhs::Bool, rhs::$ET) = rhs == lhs function (==)(lhs::$ET, rhs::Bool) if rhs $(Symbol(:bool_, EF))(lhs.lhs, lhs.rhs) else $(Symbol(:bool_, EF, :_reif))(lhs.lhs, lhs.rhs, rhs) end end end end # Create BEE operators on boolean arrays. Note that boolarrayOP = [(:BeeArrayAnd, :and, :and), (:BeeArrayOr, :or, :or), (:BeeArrayXor, :xor, :xor), (:BeeArrayIff, :iff, :iff)] for (ET, EF, OP) in boolarrayOP @eval BeeEncoder begin struct $ET <: BeeExpression varlist::Array{BeeBoolean, 1} end # No need to check type here $OP(varlist) = $ET(varlist) (==)(lhs::BeeBoolean, rhs::$ET) = rhs == lhs function (==)(lhs::$ET, rhs::BeeBoolean) $(Symbol(:bool_array_, EF, :_reif))(lhs.varlist, rhs) end (==)(lhs::Bool, rhs::$ET) = rhs == lhs function (==)(lhs::$ET, rhs::Bool) if rhs $(Symbol(:bool_array_, EF))(lhs.varlist) else $(Symbol(:bool_array_, EF, :_reif))(lhs.varlist, rhs) end end end end # Create BEE operators on two boolean arrays bool2arrayOP = [(:BeeArrayEq, :eq, :(==)), (:BeeArrayNeq, :neq, :(!=)), (:BeeLex, :lex, :(<=)), (:BeelexLt, :lexLt, :(<))] for (ET, EF, OP) in bool2arrayOP @eval BeeEncoder begin struct $ET <: BeeExpression lhs::Array{BeeBoolean, 1} rhs::Array{BeeBoolean, 1} end $OP(lhs::Array{T, 1} where T <: BB, rhs::Array{T, 1} where T <: BB) = $ET(lhs, rhs) (==)(lhs::BeeBoolean, rhs::$ET) = rhs == lhs function (==)(lhs::$ET, rhs::BeeBoolean) $(Symbol(:bool_arrays_, EF, :_reif))(lhs.lhs, lhs.rhs, rhs) end (==)(lhs::Bool, rhs::$ET) = rhs == lhs function (==)(lhs::$ET, rhs::Bool) if rhs $(Symbol(:bool_arrays_, EF))(lhs.lhs, lhs.rhs) else $(Symbol(:bool_arrays_, EF, :_reif))(lhs.lhs, lhs.rhs, rhs) end end end end # ------------------------------------------------------------- # BEE functions # ------------------------------------------------------------- # Adding constraint function. Do not do any check. Let BEE to report errors. for F in (:int_order2bool_array, :bool2int, :bool_eq, :bool_array_eq_reif, :bool_array_or, :bool_array_and, :bool_array_xor, :bool_array_iff, :bool_array_or_reif, :bool_array_and_reif, :bool_array_xor_reif, :bool_array_iff_reif, :bool_or_reif, :bool_and_reif, :bool_xor_reif, :bool_iff_reif, :bool_ite, :bool_ite_reif, :int_leq, :int_geq, :int_eq, :int_lt, :int_gt, :int_neq, :int_leq_reif, :int_geq_reif, :int_eq_reif, :int_lt_reif, :int_gt_reif, :int_neq_reif, :int_array_allDiff, :int_array_allDiff_reif, :int_array_allDiffCond, :int_abs, :int_plus, :int_times, :int_div, :int_mod, :int_max, :int_min, :int_array_plus, :int_array_times, :int_array_max, :int_array_min, :bool_array_sum_leq, :bool_array_sum_geq, :bool_array_sum_eq, :bool_array_sum_lt, :bool_array_sum_gt, :bool_array_pb_leq, :bool_array_pb_geq, :bool_array_pb_eq, :bool_array_pb_lt, :bool_array_pb_gt, :int_array_sum_leq, :int_array_sum_geq, :int_array_sum_eq, :int_array_sum_lt, :int_array_sum_gt, :int_array_lin_leq, :int_array_lin_geq, :int_array_lin_eq, :int_array_lin_lt, :int_array_lin_gt, :int_array_sumCond_leq, :int_array_sumCond_geq, :int_array_sumCond_eq, :int_array_sumCond_lt, :int_array_sumCond_gt, :bool_array_sum_modK, :bool_array_sum_divK, :bool_array_sum_divModK, :int_array_sum_modK, :int_array_sum_divK, :int_array_sum_divModK, :bool_arrays_eq, :bool_arrays_neq, :bool_arrays_eq_reif, :bool_arrays_neq_reif, :bool_arrays_lex, :bool_arrays_lexLt, :bool_arrays_lex_reif, :bool_arrays_lexLt_reif, :int_arrays_eq, :int_arrays_neq, :int_arrays_eq_reif, :int_arrays_neq_reif, :int_arrays_lex, :int_arrays_lexLt, :int_arrays_lex_implied, :int_arrays_lexLt_implied, :int_arrays_lex_reif, :int_arrays_lexLt_reif) SF = String(F) @eval BeeEncoder $F(var...) = BeeConstraint($SF, [var...]) end # ------------------------------------------------------------- # Initialize module # ------------------------------------------------------------- reset() # ------------------------------------------------------------- # For testing # ------------------------------------------------------------- function capture_render(c) @capture_out render(c) end function capture_render() @capture_out render() end end
BeeEncoder
https://github.com/newptcai/BeeEncoder.jl.git
[ "MIT" ]
0.1.0
69f74150a58a45cce84e62ad44460df0fd29ce34
code
6251
using BeeEncoder using Suppressor using Test @testset "BeeEncoder.jl" begin @testset "simple" begin BeeEncoder.reset() example="""new_int(w, 0, 10) new_int(x, 0, 5) new_int(z, -5, 10) new_int(y, -4, 9) new_bool(x1) new_bool(x4) new_bool(x2) new_bool(x3) int_plus(x, y, z) bool_eq(x1, -x2) bool_eq(x2, true) bool_array_sum_eq([-x1, x2, -x3, x4], w) solve satisfy """ ret = @capture_out include("../example/simple-example.jl") @test ret == example @test "new_int(w, 0, 10)\n" == capture_render(w) c = x+y == z @test "int_plus(x, y, z)\n" == capture_render(c) c = xl[1] == -xl[2] @test "bool_eq(x1, -x2)\n" == capture_render(c) BeeEncoder.reset() @constrain xl[1] == -xl[2] @test "bool_eq(x1, -x2)\nsolve satisfy\n" == capture_render() BeeEncoder.reset() constrain(xl[1] == -xl[2]) @test "bool_eq(x1, -x2)\nsolve satisfy\n" == capture_render() end @testset "Declaring Variable" begin BeeEncoder.reset() @beebool x1 @test "new_bool(x1)\n" == capture_render(x1) x2 = beebool("x2") @test "new_bool(x2)\n" == capture_render(x2) x3 = beebool("x3") @test "new_bool(x3)\n" == capture_render(x3) @test hasbool("x3") @test !hasbool("x4") x5 = fetchbool("x5") @test isa(x5, BeeBool) @test x5.name == "x5" @test x5 === fetchbool("x5") @test x5 === getbool("x5") @test_throws KeyError getbool("x6") xx1 = fetchbool("xx") xx2 = fetchbool("xx") @test isequal(xx1, xx2) yl = @beebool y1 y2 y3 for i in 1:3 @test "new_bool(y$i)\n" == capture_render(yl[i]) end zl = @beebool z[1:10] for i in 1:10 @test "new_bool(z$i)\n" == capture_render(zl[i]) end z1 = fetchbool("z1") @test z1 in zl (a, b, cl, d) = @beebool a b c[1:10] d for i in 1:10 @test "new_bool(c$i)\n" == capture_render(cl[i]) end BeeEncoder.reset() @beeint xx 3 55 @test isequal(xx, xx) @test "new_int(xx, 3, 55)\n" == capture_render(xx) il = @beeint i[1:10] 3 7 for i in 1:10 @test "new_int(i$i, 3, 7)\n" == capture_render(il[i]) end @test "[i1, i2, i3]" == capture_render(il[1:3]) i1 = getint("i1") @test i1 in il @test hasint("i4") @test !hasint("i12") @test xx === getint("xx") @test_throws KeyError getint("x6") end @testset "Boolean statements" begin BeeEncoder.reset() @beebool x1 @beebool x2 x3 = BeeBool("x3") c = x1 == x2 @test "bool_eq(x1, x2)\n" == capture_render(c) c = -x1 == x2 @test "bool_eq(-x1, x2)\n" == capture_render(c) c = true == and([x1, -x2, x3]) @test "bool_array_and([x1, -x2, x3])\n" == capture_render(c) c = and([x1, x2]) == -x3 @test "bool_array_and_reif([x1, x2], -x3)\n" == capture_render(c) c = -x3 == BeeEncoder.xor(-x1, x2) @test "bool_xor_reif(-x1, x2, -x3)\n" == capture_render(c) end @testset "Integer statements" begin BeeEncoder.reset() @beeint x1 3 7 @beeint x2 4 6 x3 = beeint("x3", 10, 15) c = (x1 < x2) == true @test "int_lt(x1, x2)\n" == capture_render(c) c = true == (x1 < x2) @test "int_lt(x1, x2)\n" == capture_render(c) c = false == (x1 < x2) @test "int_lt_reif(x1, x2, false)\n" == capture_render(c) c = (x1 < x2) == false @test "int_lt_reif(x1, x2, false)\n" == capture_render(c) c = alldiff([x1, x2, x3]) == true @test "int_array_allDiff([x1, x2, x3])\n" == capture_render(c) c = true == alldiff([x1, x2, x3]) @test "int_array_allDiff([x1, x2, x3])\n" == capture_render(c) c = alldiff([x1, x2]) == x3 @test "int_array_allDiff_reif([x1, x2], x3)\n" == capture_render(c) c = x3 == alldiff([x1, x2]) @test "int_array_allDiff_reif([x1, x2], x3)\n" == capture_render(c) c = x1 * x2 == x3 @test "int_times(x1, x2, x3)\n" == capture_render(c) c = x3 == x1 * x2 @test "int_times(x1, x2, x3)\n" == capture_render(c) c = x1 + x2 == 33 @test "int_plus(x1, x2, 33)\n" == capture_render(c) c = 33 == x1 + x2 @test "int_plus(x1, x2, 33)\n" == capture_render(c) c = max([x1, x2]) == x3 @test "int_array_max([x1, x2], x3)\n" == capture_render(c) c = x3 == max([x1, x2]) @test "int_array_max([x1, x2], x3)\n" == capture_render(c) end @testset "Cardinality" begin BeeEncoder.reset() xl = [beebool("x$i") for i in 1:3] il = [beeint("i$i", 3, 5) for i in 1:3] c = sum(il) == il[1] @test "int_array_sum_eq([i1, i2, i3], i1)\n" == capture_render(c) c = sum(xl) >= il[1] @test "bool_array_sum_geq([x1, x2, x3], i1)\n" == capture_render(c) c = sum(xl) > il[1] @test "bool_array_sum_gt([x1, x2, x3], i1)\n" == capture_render(c) end @testset "Boolean arrays relation" begin BeeEncoder.reset() xl = [beebool("x$i") for i in 1:3] il = [beebool("i$i") for i in 1:3] @beebool b c = (xl == il) == true @test "bool_arrays_eq([x1, x2, x3], [i1, i2, i3])\n" == capture_render(c) c = (xl != il) == true @test "bool_arrays_neq([x1, x2, x3], [i1, i2, i3])\n" == capture_render(c) c = (xl <= il) == true @test "bool_arrays_lex([x1, x2, x3], [i1, i2, i3])\n" == capture_render(c) c = (xl < il) == true @test "bool_arrays_lexLt([x1, x2, x3], [i1, i2, i3])\n" == capture_render(c) c = (xl <= il) == b @test "bool_arrays_lex_reif([x1, x2, x3], [i1, i2, i3], b)\n" == capture_render(c) c = (xl < il) == b @test "bool_arrays_lexLt_reif([x1, x2, x3], [i1, i2, i3], b)\n" == capture_render(c) end end
BeeEncoder
https://github.com/newptcai/BeeEncoder.jl.git
[ "MIT" ]
0.1.0
69f74150a58a45cce84e62ad44460df0fd29ce34
docs
14214
# Using `BEE` and `BeeEncoder.jl` 🐝️ to solve SAT problems [![Build Status](https://travis-ci.org/newptcai/BeeEncoder.jl.svg?branch=master)](https://travis-ci.org/newptcai/BeeEncoder.jl) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) *This package was originally named [`BEE.jl`](https://github.com/newptcai/BEE.jl). The name was changed so it can be registered in Julia's package repository.* ## The beauty of brute force 🤜️ <p align="center"> <img src="images/egg-power.jpg" alt="Brute force" width="450" /> </p> Modern [SAT](https://en.wikipedia.org/wiki/Boolean_satisfiability_problem) solver are often capable of handling problems with *HUGE* size. They have been successfully applied to many combinatorics problems. Communications ACM has an article titled [The Science of Brute Force](https://cacm.acm.org/magazines/2017/8/219606-the-science-of-brute-force/fulltext) on how the [Boolean Pythagorean Triples problem](https://www.cs.utexas.edu/~marijn/publications/ptn.pdf) was solved with an SAT solver. Another well-known example is [Paul Erdős Discrepancy Conjecture](https://www.quantamagazine.org/terence-taos-answer-to-the-erdos-discrepancy-problem-20151001/), which was [initially attacked with the help of computer](https://arxiv.org/pdf/1402.2184.pdf). Thus it is perhaps beneficial 🥦️ for anyone who is interested in combinatorics 🀄️ to learn how to harness the beautiful brute force 🔨 of SAT solvers. Doing experiments with SAT solver can search much bigger space than pencil and paper. New patterns can be spotted 👁️. Conjectures can be proved or disapproved 🎉️. However, combinatorial problems are often difficult to encode into CNF formulas, which can only contain boolean variables. So integers must be represented by such boolean variables with some encoding scheme. Doing so manually can be very tedious 😑️. Of course you can use solvers which go beyond CNF. For example Microsoft has a [`Z3`](https://github.com/Z3Prover/z3) theorem proved. You can solve many more types of problems with it. But if the size of your problem matters, pure CNF solver is still way much faster 🚀️. ## What is `BEE` 🐝️ One project that tries to ease using SAT solvers is [`BEE` (Ben-Gurion University Equi-propagation Encoder)](http://amit.metodi.me/research/bee/), which > ... is a > compiler which enables to encode finite domain constraint problems to CNF. During compilation, `BEE` > applies optimizations which include equi-propagation (see paper), partial-evaluation, and a careful > selection of encoding techniques per constraint, depending on various parameters of the constraint. From my experiments, `BEE` has a good balance of expressive power and performance. ## Many ways to use `BEE` 🤔️ `BEE` is written in [`Prolog`](https://en.wikipedia.org/wiki/Prolog). So you either have to learn `Prolog`, or you can 1. encode your problem in a syntax defined by `BEE`, 2. use a program `BumbleBEE` that comes with the package to solve it directly with `BEE` 3. or use `BumbleBEE` to compile your problem to a [DIMACS CNF file](https://people.sc.fsu.edu/~jburkardt/data/cnf/cnf.html), which can be solved by the numerous SAT solvers out there. My choice is to use [Julia](https://julialang.org/) to convert combinatorics problems into `BumbleBEE` code and this is why I wrote the package [`BeeEncoder.jl`](https://github.com/newptcai/BeeEncoder.jl). Here's my workflow for smaller problems ```shell Julia code --(BeeEncoder.jl)--> BEE code --(BumbleBEE)--> solution/unsatisfiable ``` When the problem is getting bigger, I try ```shell Julia code --(BeeEncoder.jl)--> BEE code -- (BumbleBEE)--> CNF --(SAT Solver) | +-------------------------+--------------------------------+ | | v v unsatisfiable CNF solution --(BumbleSol)--> BEE solution ``` In the rest of this article, I will mostly describe how to use `BEE` 😀️. You do not need to know any Julia to understand this part. I will only briefly mention what `BeeEncoder.jl` does by the end. ## `BEE` and SAT solver for beginners ### Docker image The easiest way to try `BEE` and `BeeEncoder.jl` is to use this [docker image](https://hub.docker.com/r/newptcai/beeencoder) with everything you need. If you have [docker](https://www.docker.com/) install, simply type in a terminal ```shell docker pull newptcai/beeencoder docker run -it newptcai/beeencoder ``` This will download and start a bash shell within the image. You will find `BEE` install in the folder `/bee`. To check it works, run ```shell cd bee && ./BumbleBEE beeSolver/bExamples/ex_sat.bee ``` `BeeEncoder.jl` is also included in this image. You can start Julia REPL and use it immediately. The drawback of this method is that the image is quite large (about 600MB). This is unavoidable if we use docker. Julia itself needs about 400MB, and Prolog costs another 100MB. 😑️ ### Compiling and running `BEE` I ran into some difficulties when I tried to compile [2017 version of `BEE`](http://amit.metodi.me/research/bee/bee20170615.zip). Here is how to do it correctly on Ubuntu. Other Linux system should work in similar ways. First install [SWI-Prolog](https://www.swi-prolog.org/build/PPA.txt). You can do this in a terminal by typing ```shell sudo apt-add-repository ppa:swi-prolog/stable sudo apt-get update sudo apt-get install swi-prolog-nox ``` Download `BEE` using the link above and unzip it somewhere on your computer. In a terminal, change directory to ```shell cd /path-to-downloaded-file/bee20170615/satsolver_src ``` Compile sat solvers coming with `BEE` by ```shell env CPATH="/usr/lib/swi-prolog/include/" make satSolvers ``` If compilation is successful, you should be able to excute ```shell cd ../satsolver && ls ``` and see the following output ```shell pl-glucose4.so pl-glucose.so pl-minisat.so satsolver.pl ``` Next we compile `BumbleBEE` by ```shell cd ../beeSolver/ && make ``` If you succeed, you will be able to find `BumbleBEE` and `BumbleSol` one directory above by ```shell cd .. && ls ``` And you should see these files ```shell bApplications beeSolver BumbleSol pl-satsolver.so satsolver beeCompiler BumbleBEE Constraints.pdf README.txt satsolver_src ``` ### Using `BumbleBEE` We can now give `BEE` a try 😁️. You can find examples of `BumbleBEE` problems in the folder `beeSolver/bExamples`. A very simple one is the following `ex_sat.bee`. ```shell new_int(x,0,5) new_int(y,-4,9) new_int(z,-5,10) int_plus(x,y,z) new_int(w,0,10) new_bool(x1) new_bool(x2) new_bool(x3) new_bool(x4) bool_eq(x1,-x2) bool_eq(x2,true) bool_array_sum_eq([-x1,x2,-x3,x4],w) solve satisfy ``` It defines 4 integer variables `x, y, z, w` in various range and 4 boolean variables `x1, x2, x3, x4`. Then it adds various constraints on these variables, for example, `x+y==z` and `x1==x2`. For the syntax, check the [document](http://amit.metodi.me/research/bee/Constraints.pdf). ### Solving problem directly We can solve problem directly with `BumbleBEE` by ```shell ./BumbleBEE beeSolver/bExamples/ex_sat.bee ``` And the solution should be ```shell (base) xing@MAT-WL-xinca341:bee20170615$ ./BumbleBEE beeSolver/bExamples/ex_sat.bee % \'''/ // BumbleBEE / \_/ \_/ \ % -(|||)(') (15/06/2017) \_/ \_/ \_/ % ^^^ by Amit Metodi / \_/ \_/ \ % % reading BEE file ... done % load pl-satSolver ... % SWI-Prolog interface to Glucose v4.0 ... OK % encoding BEE model ... done % solving CNF (satisfy) ... x = 0 y = -4 z = -4 w = 3 x1 = false x2 = true x3 = false x4 = false ---------- ``` You can check that all the constraints are satisfied. <font size="+2">⚠️ </font> But here is a caveat -- you must run `BumbleBEE` with the current directory `PWD` set to be where the file `BumbleBEE` is. You cannot use any other directory 🤦. For example if you try ```shell cd .. && bee20170615/BumbleBEE bee20170615/beeSolver/bExamples/ex_sat.bee ``` You will only get error messages. ### Convert the problem to CNF As I mentioned earlier, you can also compile your problem into CNF DIMACS format. For example ```shell ./BumbleBEE beeSolver/bExamples/ex_sat.bee -dimacs ./ex_sat.cnf ./ex_sat.map ``` will create two files `ex_sat.cnf` and `ex_sat.map`. The top few lines of `ex_sat.cnf` looks like this ```shell c DIMACS File generated by BumbleBEE p cnf 37 189 1 0 -6 5 0 -5 4 0 -4 3 0 -3 2 0 -19 18 0 -18 17 0 -17 16 0 ``` A little bit explanation for the first 4 lines 1. A line with `c` at the beginning is a comment. 2. The line with `p` says that this is a CNF formula with `37` variables and `189` clauses. 3. `1 0` is a clause which says that variable `1` must be true. `0` is symbol to end a clause. 4. `-6 5` means either the negate of variable `6` is true or variable `5` is true ... As you can see, with integers are needed, even a toy problem needs a large numbers of boolean variables. This is why efficient coding of integers are critical. And this is where `BEE` helps. Now you can try your favourite SAT solver on the problem. I often use [`CryptoMiniSat`](https://www.msoos.org/cryptominisat5/). Assuming that you have it on your `PATH`, you can now use ```shell cryptominisat5 ex_sat.cnf > ex_sat.sol ``` to solve the problem and save the solution into a file `ex_sat.sol`. Most of `ex_sat.sol` are comments except the last 3 lines ```shell s SATISFIABLE v 1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 v -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 34 -35 -36 -37 0 ``` It says the problem is satisfiable and one solution is given. A number in the line starting with an `v` means a variables. Without a `-` sign in front of it, a variable is assigned the value `true` otherwise it is assigned `false`. <font size="+2">⚠️ </font> To get back to a solution to `BEE` variables, we use `BumbleSol`, which is at the same folder as `BumbleBEE`. But `BumbleSol` needs bit help 😑️. Remove the starting `s` and `v` in the `ex_sat.sol` to make it like this ```shell SATISFIABLE 1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 34 -35 -36 -37 0 ``` Then we can run ```shell ./BumbleSol ex_sat.map ex_sat.sol ``` and get ```shell % \'''/ // BumbleBEE Solution Reader / \_/ \_/ \ % -(|||)(') (04/06/2016) \_/ \_/ \_/ % ^^^ by Amit Metodi / \_/ \_/ \ % % reading Dimacs solution file ... done % reading and decoding BEE map file ... x = 0 y = -4 z = -4 w = 2 x1 = false x2 = true x3 = false x4 = false ---------- ========== ``` That's it! Now you know how to use `BEE` 🐝️! Have fan with your problem 🤣️. ### Choice of SAT solver Some top-level SAT solvers are * [CaDical](https://github.com/arminbiere/cadical) -- Winner of [2019 SAT Race](http://sat-race-2019.ciirc.cvut.cz/). Tends to be fastest in dealing with solvable problems. * [Lingeling, Plingeling and Treengeling](http://fmv.jku.at/lingeling/) -- Good at parallelization. * [Painless](https://www.lrde.epita.fr/wiki/Painless) -- Uses a divide and conquer strategy for parallelization. * MapleLCMDiscChronoBT-DL -- Winner of 2019 SAT Race for unsatisfiable problem. But I have not found any documents of it. My experience is that all these SAT solvers have similar performance. It is always more important to try to encode your problem better. ## How to use `BeeEncoder.jl` When your problems becomes bigger, you don't want to write all `BEE` code manually. Here's what `BeeEncoder.jl` may help. You can write your problem in Julia, and `BeeEncoder.jl` will convert it to `BEE` syntax. Here's how to do the example above with `BeeEncoder.jl` First install `BeeEncoder.jl` by typing this in `Julia REPL`. ```Julia using Pkg; Pkg.add("BeeEncoder") ``` Then run the following code in Julia REPL ```Julia using BeeEncoder @beeint x 0 5 @beeint y -4 9 @beeint z -5 10 @constrain x + y == z @beeint w 0 10 xl = @beebool x[1:4] @constrain xl[1] == -xl[2] @constrain xl[2] == true @constrain sum([-xl[1], xl[2], -xl[3], xl[4]]) == w BEE.render() ``` You will get output like this ```Julia new_int(w, 0, 10) new_int(x, 0, 5) new_int(z, -5, 10) new_int(y, -4, 9) new_bool(x1) new_bool(x4) new_bool(x2) new_bool(x3) int_plus(x, y, z) bool_eq(x1, -x2) bool_eq(x2, true) bool_array_sum_eq(([-x1, x2, -x3, x4], w)) solve satisfy ``` Exactly as above. You can solve this into a file and solve it with `BumbleBEE` as I described before. If you have `BEE` installed and `BumbleBEE` can be found through your `PATH` environment variable, then you can run `BEE.solve()` directly in Julia and get the solution, like this. ```Julia julia> output = solve(); % SWI-Prolog interface to Glucose v4.0 ... OK % \'''/ // BumbleBEE / \_/ \_/ \ % -(|||)(') (15/06/2017) \_/ \_/ \_/ % ^^^ by Amit Metodi / \_/ \_/ \ % % reading BEE file ... done % load pl-satSolver ... % encoding BEE model ... done % solving CNF (satisfy) ... w = 2 x = 0 z = -4 y = -4 x1 = false x4 = false x2 = true x3 = true ---------- ========== ``` And if you check `output`, you will it is a dictionary containing the solution. ```Julia julia> out BEE solution: * Satisfiable: true * Integer variables: Dict("w" => 2,"x" => 0,"z" => -4,"y" => -4) * Boolean variables: Dict{String,Bool}("x1" => 0,"x4" => 0,"x2" => 1,"x3" => 1) ``` To reset the model, use `reset()`. ## Acknowledgement 🙏️ I want to thank all the generous ❤️ people who have spend their time to create these amazing SAT solvers and made them freely available to everyone. By writing this module, I have learn quite a great deal of Julia and its convenient meta-programming features. I want to thank everyone 💁 on GitHub and [Julia Slack channel](https://slackinvite.julialang.org/) who has helped me, in particular Alex Arslan, [David Sanders](https://github.com/dpsanders), Syx Pek, and [Jeffrey Sarnoff](https://github.com/JeffreySarnoff). I also want to thank my dear friend [Yelena Yuditsky](https://sites.google.com/view/yuditsky/home) for giving me a problem to solve so that I have the motivation to do all this.
BeeEncoder
https://github.com/newptcai/BeeEncoder.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
10968
# (-1)^k B_{2k}/(2k)! where B_{2k} are the even Bernoulli numbers # B(k) = 2*(-1)^(2*k + 1)*SpecialFunctions.zeta(2*k)/(2*pi)^(2*k) const B = ( -8.3333333333333333e-002,-1.3888888888888889e-003,-3.3068783068783069e-005,-8.2671957671957672e-007, -2.0876756987868099e-008,-5.2841901386874932e-010,-1.3382536530684679e-011,-3.3896802963225829e-013, -8.5860620562778446e-015,-2.1748686985580619e-016,-5.5090028283602295e-018,-1.3954464685812523e-019, -3.5347070396294675e-021,-8.9535174270375469e-023,-2.2679524523376831e-024,-5.7447906688722024e-026, -1.4551724756148649e-027,-3.6859949406653102e-029,-9.3367342570950447e-031,-2.3650224157006299e-032, -5.9906717624821343e-034,-1.5174548844682903e-035,-3.8437581254541882e-037,-9.7363530726466910e-039, -2.4662470442006810e-040,-6.2470767418207437e-042,-1.5824030244644914e-043,-4.0082736859489360e-045, -1.0153075855569556e-046,-2.5718041582418717e-048,-6.5144560352338149e-050,-1.6501309906896525e-051, -4.1798306285394759e-053,-1.0587634667702909e-054,-2.6818791912607707e-056,-6.7932793511074212e-058, -1.7207577616681405e-059,-4.3587303293488938e-061,-1.1040792903684667e-062,-2.7966655133781345e-064, -7.0840365016794702e-066,-1.7944074082892241e-067,-4.5452870636110961e-069,-1.1513346631982052e-070, -2.9163647710923614e-072,-7.3872382634973376e-074,-1.8712093117637953e-075,-4.7398285577617994e-077, -1.2006125993354507e-078,-3.0411872415142924e-080,-7.7034172747051063e-082,-1.9512983909098831e-083, -4.9426965651594615e-085,-1.2519996659171848e-086,-3.1713522017635155e-088,-8.0331289707353345e-090, -2.0348153391661466e-091,-5.1542474664474739e-093,-1.3055861352149467e-094,-3.3070883141750912e-096, -8.3769525600490913e-098,-2.1219068717497138e-099,-5.3748528956122803e-101,-1.3614661432172069e-102, -3.4486340279933990e-104,-8.7354920416383551e-106,-2.2127259833925497e-107,-5.6049003928372242e-109, -1.4197378549991788e-110,-3.5962379982587627e-112,-9.1093772660782319e-114,-2.3074322171091233e-115, -5.8447940852990020e-117,-1.4805036371705745e-118,-3.7501595226227197e-120,-9.4992650419929583e-122, -2.4061919444675199e-123,-6.0949553971026848e-125,-1.5438702377042471e-126,-3.9106689968592923e-128, -9.9058402898794298e-130,-2.5091786578563553e-131,-6.3558237896024598e-133,-1.6099489734616250e-134, -4.0780483898724622e-136,-1.0329817245315190e-137,-2.6165732752609202e-139,-6.6278575334086228e-141, -1.6788559257443673e-142,-4.2525917390343006e-144,-1.0771940713664573e-145,-2.7285644580839580e-147, -6.9115345134370137e-149,-1.7507121442157682e-150,-4.4346056667239196e-152,-1.1232987378487150e-153, -2.8453489425693971e-155,-7.2073530684151368e-157,-1.8256438595501418e-158,-4.6244099189746555e-160, -1.1713767165946985e-161,-2.9671318854112523e-163,-7.5158328663197353e-165,-1.9037827051837494e-166, -4.8223379271757316e-168,-1.2215124667619569e-169,-3.0941272241548313e-171,-7.8375158172837117e-173, -1.9852659485568249e-174,-5.0287373938151486e-176,-1.2737940624195893e-177,-3.2265580530233667e-179, -8.1729670255761088e-181,-2.0702367322529201e-182,-5.2439709032927841e-184,-1.3283133472690102e-185, -3.3646570148302941e-187,-8.5227757823275058e-189,-2.1588443254591854e-190,-5.4684165588767235e-192, -1.3851660959868732e-193,-3.5086667096656512e-195,-8.8875566007447618e-197,-2.2512443861893281e-198, -5.7024686469217722e-200,-1.4444521824735857e-201,-3.6588401210745441e-203,-9.2679502956336812e-205, -2.3475992347298971e-206,-5.9465383295169881e-208,-1.5062757553029781e-209,-3.8154410604763518e-211, -9.6646251091260105e-213,-2.4480781387902631e-214,-6.2010543667790175e-216,-1.5707454206813435e-217, -3.9787446306053875e-219,-1.0078277884588346e-220,-2.5528576108572180e-222,-6.4664638700600961e-224, -1.6379744332372530e-225,-4.1490377087871461e-227,-1.0509635290775169e-228,-2.6621217182765621e-230, -6.7432330873938832e-232,-1.7080808949773099e-233,-4.3266194508991167e-235,-1.0959455098376500e-236, -2.7760624066064009e-238,-7.0318482225589324e-240,-1.7811879627573501e-241,-4.5118018169014740e-243, -1.1428527511202687e-244,-2.8948798368101921e-246,-7.3328162891986569e-248,-1.8574240646335573e-249, -4.7049101188608530e-251,-1.1917676554344843e-252,-3.0187827368818927e-254,-7.6466660014982318e-256, -1.9369231254735576e-257,-4.9062835924299293e-259,-1.2427761521749539e-260,-3.1479887685209103e-262, -7.9739487029830971e-264,-2.0198248022238287e-265,-5.1162759927867278e-267,-1.2959678485750701e-268, -3.2827249095010017e-270,-8.3152393350706909e-272,-2.1062747292467202e-273,-5.3352562160805552e-275, -1.3514361871210552e-276,-3.4232278524048296e-278,-8.6711374470768819e-280,-2.1964247741580717e-281, -5.5636089474762561e-283,-1.4092786097034883e-284,-3.5697444204246398e-286,-9.0422682494513886e-288, -2.2904333046148606e-289,-5.8017353369352214e-291,-1.4695967287946349e-292,-3.7225320009595016e-294, -9.4292837120924187e-296,-2.3884654665215509e-297,-6.0500537039203004e-299,-1.5324965059522865e-300, -3.8818589977708149e-302,-9.8328637096699497e-304,-2.4906934741438690e-305,-6.3090002722625804e-307, -1.5980884379636898e-308,-4.0480053024903931e-310,-1.0253717215969654e-311,-2.5972969126396544e-313, -6.5790299364809836e-315,-1.6664877509565689e-316,-4.2212627863094242e-318,-1.0692583549355590e-319, -2.7084630535382438e-321,-6.8606170609008831e-323 ) # Binomial coefficents, [ binomial(n,k) for n=0:7, k=0:7 ] const binomial_coeffs = ( (1, 0, 0, 0, 0, 0, 0, 0), (1, 1, 0, 0, 0, 0, 0, 0), (1, 2, 1, 0, 0, 0, 0, 0), (1, 3, 3, 1, 0, 0, 0, 0), (1, 4, 6, 4, 1, 0, 0, 0), (1, 5, 10, 10, 5, 1, 0, 0), (1, 6, 15, 20, 15, 6, 1, 0), (1, 7, 21, 35, 35, 21, 7, 1) ) # 1/n! for integer n = 0, 1, 2, ... const inverse_factorials = ( 1.0, 1.0, 1/2, 1/6, 1/24, 1/120, 1/720, 1/5040, 1/40320 ) # zeta(n) for n = 2,...,9 const zetas = ( 1.6449340668482264, 1.2020569031595943, 1.0823232337111382, 1.0369277551433699, 1.0173430619844491, 1.0083492773819228, 1.0040773561979443, 1.0020083928260822 ) # returns binomial(n,k) using pre-computed table function binomial_coeff(n::Integer, k::Integer) binomial_coeffs[n + 1][k + 1] end # returns 1/n! function inverse_factorial(n::Integer) inverse_factorials[n + 1] end # returns zeta(n) function zeta(n::Integer) zetas[n - 1] end # returns P_n(x) function pcal(n::Integer, x::Float64) sum = zero(x) x2 = x*x fl = (n - 1)÷2 for i in 3:2:n sgn = iseven(fl + (i - 1)÷2) ? 1.0 : -1.0 sum = x2*sum + sgn*zeta(i)*inverse_factorial(n - i) end if iseven(n) sum *= x end sum end # returns N_n(x) from Eq.(2.11) function ncal(n::Integer, x::Float64) sum = zero(x) xn1 = x^(n + 1) x2 = x*x xn = xn1*x2 # x^(n + 3) for k in one(n):length(B) old_sum = sum sum += B[k]*xn/(2*k + n + 1) sum == old_sum && break xn *= x2 end (xn1/(n + 1) + sum)/(n + 1) end # returns sum in Eq.(2.13), n > 1 function nsum(n::Integer, x::Float64) sum = zero(x) xn = one(x) for i in zero(n):(n - 3) sum += binomial_coeff(n - 2, i)*xn*ncal(n - 2 - i, x) xn *= -x end sum + xn*ncal(0, x) end # returns Cl(n,x) using the naive series expansion function cl_series(n::Integer, x::Float64) if iseven(n) si_series(n, x) else co_series(n, x) end end """ cl(n, z) Returns the value of the Clausen function ``\\operatorname{Cl}_n(z)`` for all integers ``n\\in\\mathbb{Z}`` and arguments ``z`` of type `Real` or `Complex`. For complex ``z\\in\\mathbb{C}`` this function is defined as ```math \\begin{aligned} \\operatorname{Cl}_n(z) &= \\frac{i}{2}\\left[\\operatorname{Li}_n(e^{-iz}) - \\operatorname{Li}_n(e^{iz})\\right], \\qquad \\text{for}~n~\\text{even}, \\\\ \\operatorname{Cl}_n(z) &= \\frac{1}{2}\\left[\\operatorname{Li}_n(e^{-iz}) + \\operatorname{Li}_n(e^{iz})\\right], \\qquad \\text{for}~n~\\text{odd}. \\end{aligned} ``` For real ``z\\in\\mathbb{R}`` the function simplifies to ```math \\begin{aligned} \\operatorname{Cl}_n(z) &= \\Im[\\operatorname{Li}_n(e^{iz})] = \\sum_{k=1}^\\infty \\frac{\\sin(kz)}{k^n}, \\qquad \\text{for even}~n>0, \\\\ \\operatorname{Cl}_n(z) &= \\Re[\\operatorname{Li}_n(e^{iz})] = \\sum_{k=1}^\\infty \\frac{\\cos(kz)}{k^n}, \\qquad \\text{for odd}~n>0. \\end{aligned} ``` Note: ``\\operatorname{Cl}_1(z)`` is not defined for ``z=2k\\pi`` with ``k\\in\\mathbb{Z}``. For ``z`` of type `Float16`, `Float32` or `Float64` the implementation follows the approach presented in [Jiming Wu, Xiaoping Zhang, Dongjie Liu, "An efficient calculation of the Clausen functions Cl_n(θ)(n >= 2)", Bit Numer Math 50, 193-206 (2010) [https://doi.org/10.1007/s10543-009-0246-8](https://doi.org/10.1007/s10543-009-0246-8)]. Author: Alexander Voigt License: MIT # Example ```jldoctest; setup = :(using ClausenFunctions), output = false julia> cl(10, 1.0) 0.8423605391686301 julia> cl(10, big"1") 0.8423605391686302305168624869816554653186479602725762955247227248477087749849797 julia> cl(10, 1.0 + 1.0im) 1.301796548970136 + 0.6333106255561783im julia> cl(10, big"1" + 1im) 1.301796548970136401486390838171927382622047488046695826621336318796926878116022 + 0.6333106255561785282041229828047700199791464296534659278461150656661132141323808im ``` """ cl cl(n::Integer, x::Real) = _cl(n, float(x)) _cl(n::Integer, x::Float16) = oftype(x, _cl(n, Float32(x))) _cl(n::Integer, x::Float32) = oftype(x, _cl(n, Float64(x))) function _cl(n::Integer, x::Float64)::Float64 n < 1 && return invoke(_cl, Tuple{Integer, Real}, n, x) n == 1 && return cl1(x) n == 2 && return cl2(x) n == 3 && return cl3(x) n == 4 && return cl4(x) n == 5 && return cl5(x) n == 6 && return cl6(x) (x, sgn) = range_reduce(n, x) if iseven(n) && iszero(x) x elseif iseven(n) && x == convert(Float64, pi) zero(x) elseif n < 10 sign1 = iseven((n + 1)÷2) ? 1.0 : -1.0; # first line in Eq.(2.13) term1 = iszero(x) ? zero(x) : sign1*x^(n - 1)*inverse_factorial(n - 1)*log(2*sin(x/2)) sign2 = iseven(n÷2) ? 1.0 : -1.0 # second line in Eq.(2.13) term2 = pcal(n, x) - sign2*inverse_factorial(n - 2)*nsum(n, x) # Eq.(2.13) sgn*(term1 + term2) else # n >= 10 sgn*cl_series(n, x) end end function _cl(n::Integer, x::Real) if iseven(n) imag(PolyLog.li(n, cis(x))) else real(PolyLog.li(n, cis(x))) end end function cl(n::Integer, z::Complex) eiz = cis(z) if iseven(n) if iszero(z) z else (PolyLog.li(n, inv(eiz)) - PolyLog.li(n, eiz))*im/2 end else (PolyLog.li(n, inv(eiz)) + PolyLog.li(n, eiz))/2 end end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
1294
""" cl1(z) Returns the value of the Clausen function ``\\operatorname{Cl}_1(z)`` for an argument ``z`` of type `Real` or `Complex`. This function is defined as ```math \\operatorname{Cl}_1(z) = -\\frac{1}{2}\\left[\\log(1 - e^{iz}) + \\log(1 - e^{-iz})\\right] ``` Note: ``\\operatorname{Cl}_1(z)`` is not defined for ``z=2k\\pi`` with ``k\\in\\mathbb{Z}``. Author: Alexander Voigt License: MIT # Example ```jldoctest; setup = :(using ClausenFunctions), output = false julia> cl1(1.0) 0.04201950582536895 julia> cl1(big"1") 0.04201950582536896172579838403790203712453892055703441769956888996856898991572203 julia> cl1(1.0 + 1.0im) -0.3479608285425303 - 0.7021088550913619im julia> cl1(big"1" + 1im) -0.3479608285425304681676697311626225254052481291939705626677618712960309352197459 - 0.7021088550913618982002640571209884840333848751442483836897991093694470903764252im ``` """ cl1 cl1(x::Float16) = oftype(x, cl1(Float32(x))) cl1(x::Float32) = oftype(x, cl1(Float64(x))) function cl1(x::Float64)::Float64 x = range_reduce_odd(x) if iszero(x) return Inf end -log(2*sin(one(x)/2*x)) end function cl1(x::Real) -log(hypot(one(x) - cos(x), sin(x))) end function cl1(z::Complex) eiz = cis(z) -(log(one(z) - eiz) + log(one(z) - inv(eiz)))/2 end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
1729
""" cl2(x::Real)::Real Returns the value of the Clausen function ``\\operatorname{Cl}_2(x)`` for a real angle ``x`` of type `Real`. The Clausen function is defined as ```math \\operatorname{Cl}_2(x) = -\\int_0^x \\log|2\\sin(t/2)| dt ``` Author: Alexander Voigt License: MIT # Example ```jldoctest; setup = :(using ClausenFunctions), output = false julia> cl2(1.0) 1.0139591323607684 ``` """ cl2(x::Real) = _cl2(float(x)) _cl2(x::Float16) = oftype(x, _cl2(Float32(x))) _cl2(x::Float32) = oftype(x, _cl2(Float64(x))) function _cl2(x::Float64)::Float64 (x, sgn) = range_reduce_even(x) if iszero(x) x elseif x < pi/2 P = (1.3888888888888889e-02, -4.3286930203743071e-04, 3.2779814789973427e-06, -3.6001540369575084e-09) Q = (1.0000000000000000e+00, -3.6166589746694121e-02, 3.6015827281202639e-04, -8.3646182842184428e-07) y = x*x y2 = y*y p = P[1] + y * P[2] + y2 * (P[3] + y * P[4]) q = Q[1] + y * Q[2] + y2 * (Q[3] + y * Q[4]) sgn*x*(1.0 - log(x) + y*p/q) elseif x < pi P = (6.4005702446195512e-01, -2.0641655351338783e-01, 2.4175305223497718e-02, -1.2355955287855728e-03, 2.5649833551291124e-05, -1.4783829128773320e-07) Q = (1.0000000000000000e+00, -2.5299102015666356e-01, 2.2148751048467057e-02, -7.8183920462457496e-04, 9.5432542196310670e-06, -1.8184302880448247e-08) y = pi - x z = y*y - pi*pi/8 z2 = z*z z4 = z2*z2 p = P[1] + z * P[2] + z2 * (P[3] + z * P[4]) + z4 * (P[5] + z * P[6]) q = Q[1] + z * Q[2] + z2 * (Q[3] + z * Q[4]) + z4 * (Q[5] + z * Q[6]) sgn*y*p/q end end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
1785
""" cl3(x::Real)::Real Returns the value of the Clausen function ``\\operatorname{Cl}_3(x)`` for a real angle ``x`` of type `Real`. This function is defined as ```math \\operatorname{Cl}_3(x) = \\Re[\\operatorname{Li}_3(e^{ix})] = \\sum_{k=1}^\\infty \\frac{\\cos(kx)}{k^3} ``` Author: Alexander Voigt License: MIT # Example ```jldoctest; setup = :(using ClausenFunctions), output = false julia> cl3(1.0) 0.44857300728001737 ``` """ cl3(x::Real) = _cl3(float(x)) _cl3(x::Float16) = oftype(x, _cl3(Float32(x))) _cl3(x::Float32) = oftype(x, _cl3(Float64(x))) function _cl3(x::Float64)::Float64 zeta3 = 1.2020569031595943 x = range_reduce_odd(x) if iszero(x) zeta3 elseif x < pi/2 P = (-7.5000000000000001e-01, 1.5707637881835541e-02, -3.5426736843494423e-05, -2.4408931585123682e-07) Q = (1.0000000000000000e+00, -2.5573146805410089e-02, 1.5019774853075050e-04, -1.0648552418111624e-07) y = x*x y2 = y*y p = P[1] + y * P[2] + y2 * (P[3] + y * P[4]) q = Q[1] + y * Q[2] + y2 * (Q[3] + y * Q[4]) zeta3 + y*(p/q + 0.5*log(x)) else P = (-4.9017024647634973e-01, 4.1559155224660940e-01, -7.9425531417806701e-02, 5.9420152260602943e-03, -1.8302227163540190e-04, 1.8027408929418533e-06) Q = (1.0000000000000000e+00, -1.9495887541644712e-01, 1.2059410236484074e-02, -2.5235889467301620e-04, 1.0199322763377861e-06, 1.9612106499469264e-09) y = pi - x z = y*y - pi*pi/8 z2 = z*z z4 = z2*z2 p = P[1] + z * P[2] + z2 * (P[3] + z * P[4]) + z4 * (P[5] + z * P[6]) q = Q[1] + z * Q[2] + z2 * (Q[3] + z * Q[4]) + z4 * (Q[5] + z * Q[6]) p/q end end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
1805
""" cl4(x::Real)::Real Returns the value of the Clausen function ``\\operatorname{Cl}_4(x)`` for a real angle ``x`` of type `Real`. This function is defined as ```math \\operatorname{Cl}_4(x) = \\Im[\\operatorname{Li}_4(e^{ix})] = \\sum_{k=1}^\\infty \\frac{\\sin(kx)}{k^4} ``` Author: Alexander Voigt License: MIT # Example ```jldoctest; setup = :(using ClausenFunctions), output = false julia> cl4(1.0) 0.8958052386793799 ``` """ cl4(x::Real) = _cl4(float(x)) _cl4(x::Float16) = oftype(x, _cl4(Float32(x))) _cl4(x::Float32) = oftype(x, _cl4(Float64(x))) function _cl4(x::Float64)::Float64 (x, sgn) = range_reduce_even(x) if iszero(x) x elseif x < pi/2 zeta3 = 1.2020569031595943 P = (-3.0555555555555556e-01, 6.0521392328447206e-03, -1.9587493942041528e-05, -3.1137343767030358e-08) Q = (1.0000000000000000e+00, -2.2079728398400851e-02, 1.0887447112236682e-04, -6.1847621370547954e-08) y = x*x y2 = y*y p = P[1] + y * P[2] + y2 * (P[3] + y * P[4]) q = Q[1] + y * Q[2] + y2 * (Q[3] + y * Q[4]) sgn*x*(zeta3 + y*(p/q + 1/6*log(x))) else P = (7.6223911686491336e-01, -2.4339587368267260e-01, 2.8715364937979943e-02, -1.5368612510964667e-03, 3.6261044225761673e-05, -2.8557977333851308e-07) Q = (1.0000000000000000e+00, -1.7465715261403233e-01, 9.5439417991615653e-03, -1.7325070821666274e-04, 5.9283675098376635e-07, 9.4127575773361230e-10) y = pi - x z = y*y - pi*pi/8 z2 = z*z z4 = z2*z2 p = P[1] + z * P[2] + z2 * (P[3] + z * P[4]) + z4 * (P[5] + z * P[6]) q = Q[1] + z * Q[2] + z2 * (Q[3] + z * Q[4]) + z4 * (Q[5] + z * Q[6]) sgn*y*p/q end end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
1817
""" cl5(x::Real)::Real Returns the value of the Clausen function ``\\operatorname{Cl}_5(x)`` for a real angle ``x`` of type `Real`. This function is defined as ```math \\operatorname{Cl}_5(x) = \\Re[\\operatorname{Li}_5(e^{ix})] = \\sum_{k=1}^\\infty \\frac{\\cos(kx)}{k^5} ``` Author: Alexander Voigt License: MIT # Example ```jldoctest; setup = :(using ClausenFunctions), output = false julia> cl5(1.0) 0.5228208076420943 ``` """ cl5(x::Real) = _cl5(float(x)) _cl5(x::Float16) = oftype(x, _cl5(Float32(x))) _cl5(x::Float32) = oftype(x, _cl5(Float64(x))) function _cl5(x::Float64)::Float64 x = range_reduce_odd(x) if iszero(x) 1.0369277551433699 # zeta(5) elseif x < pi/2 P = (1.0369277551433699e+00, -6.1354800479984468e-01, 9.4076401395712763e-02, -9.4056155866704436e-04) Q = (1.0000000000000000e+00, -1.2073698633244778e-02, 1.3703409625482991e-05, -1.9701280330628469e-09, 2.1944550184416500e-11) y = x*x y2 = y*y p = P[1] + y * P[2] + y2 * (P[3] + y * P[4]) q = Q[1] + y * Q[2] + y2 * (Q[3] + y * Q[4] + y2 * Q[5]) p/q - 1/24*y2*log(x) else P = (-4.5930112735784898e-01, 4.3720705508867954e-01, -7.5895226486465095e-02, 5.2244176912488065e-03, -1.5677716622013956e-04, 1.6641624171748576e-06) Q = ( 1.0000000000000000e+00, -1.2211486825401188e-01, 3.8940070749313620e-03, -2.2674805547074318e-05, -7.4383354448335299e-08, -3.4131758392216437e-10) y = pi - x z = y*y - pi*pi/8 z2 = z*z z4 = z2*z2 p = P[1] + z * P[2] + z2 * (P[3] + z * P[4]) + z4 * (P[5] + z * P[6]) q = Q[1] + z * Q[2] + z2 * (Q[3] + z * Q[4]) + z4 * (Q[5] + z * Q[6]) p/q end end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
1720
""" cl6(x::Real)::Real Returns the value of the Clausen function ``\\operatorname{Cl}_6(x)`` for a real angle ``x`` of type `Real`. This function is defined as ```math \\operatorname{Cl}_6(x) = \\Im[\\operatorname{Li}_6(e^{ix})] = \\sum_{k=1}^\\infty \\frac{\\sin(kx)}{k^6} ``` Author: Alexander Voigt License: MIT # Example ```jldoctest; setup = :(using ClausenFunctions), output = false julia> cl6(1.0) 0.855629273183937 ``` """ cl6(x::Real) = _cl6(float(x)) _cl6(x::Float16) = oftype(x, _cl6(Float32(x))) _cl6(x::Float32) = oftype(x, _cl6(Float64(x))) function _cl6(x::Float64)::Float64 (x, sgn) = range_reduce_even(x) if iszero(x) x elseif x < pi/2 P = (1.0369277551433699e+00, -2.087195444107175e-01, 2.0652251045312954e-02, -1.383438138256840e-04) Q = (1.0000000000000000e+00, -8.0784096827362542e-03, 5.8074568862993102e-06, -5.1960620033050114e-10) y = x*x y2 = y*y p = P[1] + y * P[2] + y2 * (P[3] + y * P[4]) q = Q[1] + y * Q[2] + y2 * (Q[3] + y * Q[4]) sgn*x*(p/q - 1/120*y2*log(x)) else P = (7.9544504578027050e-01, -1.9255025309738589e-01, 1.5805208288846591e-02, -5.4175380521534706e-04, 6.7577493541009068e-06) Q = (1.0000000000000000e+00, -7.0798422394109274e-02, 7.1744189715634762e-04, 3.9098747334347093e-06, 3.5669441618295266e-08, 2.5315391843409925e-10) y = pi - x z = y*y - pi*pi/8 z2 = z*z z4 = z2*z2 p = P[1] + z * P[2] + z2 * (P[3] + z * P[4]) + z4 * P[5] q = Q[1] + z * Q[2] + z2 * (Q[3] + z * Q[4]) + z4 * (Q[5] + z * Q[6]) sgn*y*p/q end end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
326
module ClausenFunctions import PolyLog include("range_reduction.jl") include("Cl1.jl") include("Cl2.jl") include("Cl3.jl") include("Cl4.jl") include("Cl5.jl") include("Cl6.jl") include("Cl.jl") include("Series.jl") include("Sl.jl") export cl1 export cl2 export cl3 export cl4 export cl5 export cl6 export cl export sl end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
874
# returns sum(k=1:inf, cos(k*x)/k^n) function co_series(n::Integer, x::Number) kmax = max_terms(n, typeof(x)) co = cos(x) co2 = one(x) # cos((k-2)*x) co1 = co # cos((k-1)*x) sum = co for k in 2:kmax con = 2*co*co1 - co2 # cos(k*x) co2 = co1 co1 = con sum += con/oftype(x, k)^n end sum end # returns sum(k=1:inf, sin(k*x)/k^n) function si_series(n::Integer, x::Number) kmax = max_terms(n, typeof(x)) si, co = sincos(x) si2 = zero(x) # sin((k-2)*x) si1 = si # sin((k-1)*x) sum = si for k in 2:kmax si = 2*co*si1 - si2 # sin(k*x) si2 = si1 si1 = si sum += si/oftype(x, k)^n end sum end # returns maximum number of terms in co_series or si_series function max_terms(n::Integer, ::Type{T}) where T ceil(typeof(n), eps(T)^(-inv(n))) end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
8816
# returns Sl(n,x) using the naive series expansion function sl_series(n::Integer, x::Number) if iseven(n) co_series(n, x) else si_series(n, x) end end """ sl(n, z) Returns the value of the Glaisher-Clausen function ``\\operatorname{Sl}_n(z)`` for all integers ``n\\in\\mathbb{Z}`` and arguments ``z`` of type `Real` or `Complex`. For complex ``z\\in\\mathbb{C}`` this function is defined as ```math \\begin{aligned} \\operatorname{Sl}_n(z) &= \\frac{1}{2}\\left[\\operatorname{Li}_n(e^{-iz}) + \\operatorname{Li}_n(e^{iz})\\right], \\qquad \\text{for}~n~\\text{even}, \\\\ \\operatorname{Sl}_n(z) &= \\frac{i}{2}\\left[\\operatorname{Li}_n(e^{-iz}) - \\operatorname{Li}_n(e^{iz})\\right], \\qquad \\text{for}~n~\\text{odd}. \\end{aligned} ``` For real ``z\\in\\mathbb{R}`` the function simplifies to ```math \\begin{aligned} \\operatorname{Sl}_n(z) &= \\Re[\\operatorname{Li}_n(e^{iz})] = \\sum_{k=1}^\\infty \\frac{\\cos(kz)}{k^n}, \\qquad \\text{for even}~n>0, \\\\ \\operatorname{Sl}_n(z) &= \\Im[\\operatorname{Li}_n(e^{iz})] = \\sum_{k=1}^\\infty \\frac{\\sin(kz)}{k^n}, \\qquad \\text{for odd}~n>0. \\end{aligned} ``` Note: We set ``\\operatorname{Sl}_1(0) = 0`` for consistency with the series expansion. Author: Alexander Voigt License: MIT # Example ```jldoctest; setup = :(using ClausenFunctions), output = false julia> sl(10, 1.0) 0.5398785706335891 julia> sl(10, big"1") 0.5398785706335893473201701431352733846690266746377581980285682505050227015352517 julia> sl(10, 1.0 + 1.0im) 0.832020890646937 - 0.9921163924162678im julia> sl(10, big"1" + 1im) 0.832020890646937194384242195240640660735825609698824394209500978844042810286907 - 0.9921163924162683284596904585334878021171116435958891901780686447162617670776108im ``` """ sl(n::Integer, x::Real) = _sl(n, float(x)) _sl(n::Integer, x::Float16) = oftype(x, _sl(n, Float32(x))) _sl(n::Integer, x::Float32) = oftype(x, _sl(n, Float64(x))) function _sl(n::Integer, x::Float64)::Float64 n < 0 && return zero(x) n == 0 && return -1/2 (x, sgn) = range_reduce(n + 1, x) isodd(n) && iszero(x) && return x n == 1 && return sgn*(pi/2 - 1/2*x) n == 2 && return sgn*(pi^2/6 + (-1/2*pi + 1/4*x)*x) n == 3 && return sgn*(x*(pi^2/6 + (-1/4*pi + 1/12*x)*x)) x2 = x*x n == 4 && return sgn*(pi^4/90 + x2*(-1/12*pi^2 + (pi/12 - 1/48*x)*x)) n == 5 && return sgn*(x*(pi^4/90 + x2*(-1/36*pi^2 + (pi/48 - 1/240*x)*x))) n == 6 && return sgn*(pi^6/945 + x2*(-1/180*pi^4 + x2*(pi^2/144 + (-1/240*pi + 1/1440*x)*x))) n == 7 && return sgn*(x*(pi^6/945 + x2*(-1/540*pi^4 + x2*(pi^2/720 + (-1/1440*pi + 1/10080*x)*x)))) n == 8 && return sgn*(pi^8/9450 + x2*(-1/1890*pi^6 + x2*(pi^4/2160 + x2*(-1/4320*pi^2 + (pi/10080 - 1/80640*x)*x)))) n == 9 && return sgn*(x*(pi^8/9450 + x2*(-1/5670*pi^6 + x2*(pi^4/10800 + x2*(-1/30240*pi^2 + (pi/80640 - 1/725760*x)*x))))) n == 10 && return sgn*(pi^10/93555 + x2*(-1/18900*pi^8 + x2*(pi^6/22680 + x2*(-1/64800*pi^4 + x2*(pi^2/241920 + (-1/725760*pi + 1/7257600*x)*x))))) n == 11 && return sgn*(x*(pi^10/93555 + x2*(-1/56700*pi^8 + x2*(pi^6/113400 + x2*(-1/453600*pi^4 + x2*(pi^2/2177280 + (-1/7257600*pi + 1/79833600*x)*x)))))) n == 12 && return sgn*((691*pi^12)/638512875 + x2*(-1/187110*pi^10 + x2*(pi^8/226800 + x2*(-1/680400*pi^6 + x2*(pi^4/3628800 + x2*(-1/21772800*pi^2 + (pi/79833600 - 1/958003200*x)*x)))))) n == 13 && return sgn*(x*((691*pi^12)/638512875 + x2*(-1/561330*pi^10 + x2*(pi^8/1134000 + x2*(-1/4762800*pi^6 + x2*(pi^4/32659200 + x2*(-1/239500800*pi^2 + (pi/958003200 - 1/12454041600*x)*x))))))) n == 14 && return sgn*((2*pi^14)/18243225 + x2*((-691*pi^12)/1277025750 + x2*(pi^10/2245320 + x2*(-1/6804000*pi^8 + x2*(pi^6/38102400 + x2*(-1/326592000*pi^4 + x2*(pi^2/2874009600 + (-1/12454041600*pi + 1/174356582400*x)*x))))))) n == 15 && return sgn*(x*((2*pi^14)/18243225 + x2*((-691*pi^12)/3831077250 + x2*(pi^10/11226600 + x2*(-1/47628000*pi^8 + x2*(pi^6/342921600 + x2*(-1/3592512000*pi^4 + x2*(pi^2/37362124800 + (-1/174356582400*pi + 1/2615348736000*x)*x)))))))) n == 16 && return sgn*((3617*pi^16)/325641566250 + x2*(-1/18243225*pi^14 + x2*((691*pi^12)/15324309000 + x2*(-1/67359600*pi^10 + x2*(pi^8/381024000 + x2*(-1/3429216000*pi^6 + x2*(pi^4/43110144000 + x2*(-1/523069747200*pi^2 + (pi/2615348736000 - 1/41845579776000*x)*x)))))))) n == 17 && return sgn*(x*((3617*pi^16)/325641566250 + x2*(-1/54729675*pi^14 + x2*((691*pi^12)/76621545000 + x2*(-1/471517200*pi^10 + x2*(pi^8/3429216000 + x2*(-1/37721376000*pi^6 + x2*(pi^4/560431872000 + x2*(-1/7846046208000*pi^2 + (pi/41845579776000 - 1/711374856192000*x)*x))))))))) n == 18 && return sgn*((43867*pi^18)/38979295480125 + x2*((-3617*pi^16)/651283132500 + x2*(pi^14/218918700 + x2*((-691*pi^12)/459729270000 + x2*(pi^10/3772137600 + x2*(-1/34292160000*pi^8 + x2*(pi^6/452656512000 + x2*(-1/7846046208000*pi^4 + x2*(pi^2/125536739328000 + (-1/711374856192000*pi + 1/12804747411456000*x)*x))))))))) n == 19 && return sgn*(x*((43867*pi^18)/38979295480125 + x2*((-3617*pi^16)/1953849397500 + x2*(pi^14/1094593500 + x2*((-691*pi^12)/3218104890000 + x2*(pi^10/33949238400 + x2*(-1/377213760000*pi^8 + x2*(pi^6/5884534656000 + x2*(-1/117690693120000*pi^4 + x2*(pi^2/2134124568576000 + (-1/12804747411456000*pi + 1/243290200817664000*x)*x)))))))))) n == 20 && return sgn*((174611*pi^20)/1531329465290625 + x2*((-43867*pi^18)/77958590960250 + x2*((3617*pi^16)/7815397590000 + x2*(-1/6567561000*pi^14 + x2*((691*pi^12)/25744839120000 + x2*(-1/339492384000*pi^10 + x2*(pi^8/4526565120000 + x2*(-1/82383485184000*pi^6 + x2*(pi^4/1883051089920000 + x2*(-1/38414242234368000*pi^2 + (pi/243290200817664000 - 1/4865804016353280000*x)*x)))))))))) n == 21 && return sgn*(x*((174611*pi^20)/1531329465290625 + x2*((-43867*pi^18)/233875772880750 + x2*((3617*pi^16)/39076987950000 + x2*(-1/45972927000*pi^14 + x2*((691*pi^12)/231703552080000 + x2*(-1/3734416224000*pi^10 + x2*(pi^8/58845346560000 + x2*(-1/1235752277760000*pi^6 + x2*(pi^4/32011868528640000 + x2*(-1/729870602452992000*pi^2 + (pi/4865804016353280000 - 1/102181884343418880000*x)*x))))))))))) n == 22 && return sgn*((155366*pi^22)/13447856940643125 + x2*((-174611*pi^20)/3062658930581250 + x2*((43867*pi^18)/935503091523000 + x2*((-3617*pi^16)/234461927700000 + x2*(pi^14/367783416000 + x2*((-691*pi^12)/2317035520800000 + x2*(pi^10/44812994688000 + x2*(-1/823834851840000*pi^8 + x2*(pi^6/19772036444160000 + x2*(-1/576213633515520000*pi^4 + x2*(pi^2/14597412049059840000 + (-1/102181884343418880000*pi + 1/2248001455555215360000*x)*x))))))))))) n == 23 && return sgn*(x*((155366*pi^22)/13447856940643125 + x2*((-174611*pi^20)/9187976791743750 + x2*((43867*pi^18)/4677515457615000 + x2*((-3617*pi^16)/1641233493900000 + x2*(pi^14/3310050744000 + x2*((-691*pi^12)/25487390728800000 + x2*(pi^10/582568930944000 + x2*(-1/12357522777600000*pi^8 + x2*(pi^6/336124619550720000 + x2*(-1/10948059036794880000*pi^4 + x2*(pi^2/306545653030256640000 + (-1/2248001455555215360000*pi + 1/51704033477769953280000*x)*x)))))))))))) n == 24 && return sgn*((236364091*pi^24)/201919571963756521875 + x2*((-77683*pi^22)/13447856940643125 + x2*((174611*pi^20)/36751907166975000 + x2*((-43867*pi^18)/28065092745690000 + x2*((3617*pi^16)/13129867951200000 + x2*(-1/33100507440000*pi^14 + x2*((691*pi^12)/305848688745600000 + x2*(-1/8155965033216000*pi^10 + x2*(pi^8/197720364441600000 + x2*(-1/6050243151912960000*pi^6 + x2*(pi^4/218961180735897600000 + x2*(-1/6744004366665646080000*pi^2 + (pi/51704033477769953280000 - 1/1240896803466478878720000*x)*x)))))))))))) n == 25 && return sgn*(x*((236364091*pi^24)/201919571963756521875 + x2*((-77683*pi^22)/40343570821929375 + x2*((174611*pi^20)/183759535834875000 + x2*((-43867*pi^18)/196455649219830000 + x2*((3617*pi^16)/118168811560800000 + x2*(-1/364105581840000*pi^14 + x2*((691*pi^12)/3976032953692800000 + x2*(-1/122339475498240000*pi^10 + x2*(pi^8/3361246195507200000 + x2*(-1/114954619886346240000*pi^6 + x2*(pi^4/4598184795453849600000 + x2*(-1/155112100433309859840000*pi^2 + (pi/1240896803466478878720000 - 1/31022420086661971968000000*x)*x))))))))))))) sgn*sl_series(n, x) end function _sl(n::Integer, x::Real) if n < 0 zero(x) elseif iszero(n) -one(x)/2 elseif n == one(n) && iszero(x) x elseif iseven(n) real(PolyLog.li(n, cis(x))) else imag(PolyLog.li(n, cis(x))) end end function sl(n::Integer, z::Complex) if n < 0 zero(z) elseif iszero(n) -one(z)/2 elseif isodd(n) && iszero(z) z else eiz = cis(z) if iseven(n) (PolyLog.li(n, inv(eiz)) + PolyLog.li(n, eiz))/2 else (PolyLog.li(n, inv(eiz)) - PolyLog.li(n, eiz))*im/2 end end end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
1148
# returns 2pi - x, avoiding a catastrophic cancellation function two_pi_minus(x::Float16)::Float16 2pi - x end # returns 2pi - x, avoiding a catastrophic cancellation function two_pi_minus(x::Float32)::Float32 2pi - x end # returns 2pi - x, avoiding a catastrophic cancellation function two_pi_minus(x::Float64) p0 = 6.28125 p1 = 0.0019353071795864769253 (p0 - x) + p1 end # returns range-reduced x in [0,pi] for odd n function range_reduce_odd(x::Real) if x < zero(x) x = -x end if x >= 2pi x = mod(x, 2pi) end if x > pi x = two_pi_minus(x) end x end # returns (x, sign) with range-reduced x in [0,pi] for even n function range_reduce_even(x::Real) sgn = one(x) if x < zero(x) x = -x sgn = -one(x) end if x >= 2pi x = mod(x, 2pi) end if x > pi x = two_pi_minus(x) sgn = -sgn end (x, sgn) end # returns (x, sign) with range-reduced x in [0,pi] function range_reduce(n::Integer, x::Real) if iseven(n) range_reduce_even(x) else (range_reduce_odd(x), one(x)) end end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
2655
import ClausenFunctions n = 10_000_000 x_min = 0.0 x_max = pi data = (x_max - x_min)*rand(Float64, n) + x_min*ones(n) cdata = (x_max - x_min)*rand(ComplexF64, n) + x_min*ones(n) println("Benchmarking cl1::Float64") time_cl1(data) = @time map(ClausenFunctions.cl1, data) map(ClausenFunctions.cl1, data) # trigger compilation time_cl1(data) # trigger compilation time_cl1(data) time_cl1(data) println("Benchmarking cl1::ComplexF64") map(ClausenFunctions.cl1, cdata) # trigger compilation time_cl1(cdata) # trigger compilation time_cl1(cdata) time_cl1(cdata) println("Benchmarking cl2::Float64") time_cl2(data) = @time map(ClausenFunctions.cl2, data) map(ClausenFunctions.cl2, data) # trigger compilation time_cl2(data) # trigger compilation time_cl2(data) time_cl2(data) println("Benchmarking cl3::Float64") time_cl3(data) = @time map(ClausenFunctions.cl3, data) map(ClausenFunctions.cl3, data) # trigger compilation time_cl3(data) # trigger compilation time_cl3(data) time_cl3(data) println("Benchmarking cl4::Float64") time_cl4(data) = @time map(ClausenFunctions.cl4, data) map(ClausenFunctions.cl4, data) # trigger compilation time_cl4(data) # trigger compilation time_cl4(data) time_cl4(data) println("Benchmarking cl5::Float64") time_cl5(data) = @time map(ClausenFunctions.cl5, data) map(ClausenFunctions.cl5, data) # trigger compilation time_cl5(data) # trigger compilation time_cl5(data) time_cl5(data) println("Benchmarking cl6::Float64") time_cl6(data) = @time map(ClausenFunctions.cl6, data) map(ClausenFunctions.cl6, data) # trigger compilation time_cl6(data) # trigger compilation time_cl6(data) time_cl6(data) println("Benchmarking cl::Float64") time_cl(k, data) = @time map(x -> ClausenFunctions.cl(k, x), data) n = 1_000_000 data = (x_max - x_min)*rand(Float64, n) + x_min*ones(n) for k in vcat(collect(1:16), [1000, 1001, 1_000_000]) println("Benchmarking cl($(k),x)::Float64") map(x -> ClausenFunctions.cl(k, x), data) # trigger compilation time_cl(k, data) # trigger compilation time_cl(k, data) time_cl(k, data) end println("Benchmarking sl::Float64") time_sl(k, data) = @time map(x -> ClausenFunctions.sl(k, x), data) n = 1_000_000 data = (x_max - x_min)*rand(Float64, n) + x_min*ones(n) for k in vcat(collect(1:31), [1000, 1001, 1_000_000]) println("Benchmarking sl($(k),x)::Float64") map(x -> ClausenFunctions.sl(k, x), data) # trigger compilation time_sl(k, data) # trigger compilation time_sl(k, data) time_sl(k, data) end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
5718
@testset "cl" for TN in (Int8, Int16, Int32, Int64, Int128) for n in vcat(collect(1:16), [1000, 1001, 1_000_000, 0, -1, -2, -3]) (n > typemax(TN) || n < typemin(TN)) && continue data = open(readdlm, joinpath(@__DIR__, "data", "Cl$(n).txt")) for r in 1:size(data, 1) row = data[r, :] x = row[1] expected = row[2] sgn = -(-1)^n cl = ClausenFunctions.cl(TN(n), x) clm = sgn*ClausenFunctions.cl(TN(n), -x) ccl = ClausenFunctions.cl(TN(n), Complex(x)) @test cl == clm @test cl ≈ expected rtol=1e-14 atol=1e-14 @test ccl ≈ expected rtol=1e-14 atol=1e-14 (n > typemax(TN) || n < typemin(TN)) && continue if n > 0 @test ClausenFunctions.cl(TN(n), Float16(x)) ≈ Float16(expected) atol=30*eps(Float16) rtol=30*eps(Float16) @test ClausenFunctions.cl(TN(n), Float32(x)) ≈ Float32(expected) atol=30*eps(Float32) rtol=30*eps(Float32) @test ClausenFunctions.cl(TN(n), Complex(Float16(x))) ≈ Float16(expected) atol=30*eps(Float16) rtol=30*eps(Float16) @test ClausenFunctions.cl(TN(n), Complex(Float32(x))) ≈ Float32(expected) atol=30*eps(Float32) rtol=30*eps(Float32) end end end # test zeros at pi for n in 2:2:20 @test iszero(ClausenFunctions.cl(TN(n), pi)) end @test ClausenFunctions.cl(TN(1), 1//2) ≈ 0.70358563513784466 rtol=1e-14 @test ClausenFunctions.cl(TN(2), 1//2) ≈ 0.84831187770367927 rtol=1e-14 @test ClausenFunctions.cl(TN(3), 1//2) ≈ 0.92769631047023043 rtol=1e-14 @test ClausenFunctions.cl(TN(4), 1//2) ≈ 0.54837172654589549 rtol=1e-14 @test ClausenFunctions.cl(TN(5), 1//2) ≈ 0.89390286951083851 rtol=1e-14 @test ClausenFunctions.cl(TN(6), 1//2) ≈ 0.49419627977618802 rtol=1e-14 @test ClausenFunctions.cl(TN(1), Complex(1//2)) ≈ 0.70358563513784466 rtol=1e-14 @test ClausenFunctions.cl(TN(2), Complex(1//2)) ≈ 0.84831187770367927 rtol=1e-14 @test ClausenFunctions.cl(TN(3), Complex(1//2)) ≈ 0.92769631047023043 rtol=1e-14 @test ClausenFunctions.cl(TN(4), Complex(1//2)) ≈ 0.54837172654589549 rtol=1e-14 @test ClausenFunctions.cl(TN(5), Complex(1//2)) ≈ 0.89390286951083851 rtol=1e-14 @test ClausenFunctions.cl(TN(6), Complex(1//2)) ≈ 0.49419627977618802 rtol=1e-14 @test ClausenFunctions.cl(TN(-2), 1.0 + 1.0im) ≈ 0.50688457710655124 + 0.50950616274374456im rtol=1e-14 @test ClausenFunctions.cl(TN(-2), 1.0 - 1.0im) ≈ 0.50688457710655124 - 0.50950616274374456im rtol=1e-14 @test ClausenFunctions.cl(TN(-1), 1.0 + 1.0im) ≈ -0.08267495282794197 + 0.49171277760817954im rtol=1e-14 @test ClausenFunctions.cl(TN(-1), 1.0 - 1.0im) ≈ -0.08267495282794197 - 0.49171277760817954im rtol=1e-14 @test ClausenFunctions.cl(TN( 0), 1.0 + 1.0im) ≈ cot(1/2 + im/2)/2 rtol=1e-14 @test ClausenFunctions.cl(TN( 0), 1.0 - 1.0im) ≈ coth(1/2 + im/2)*im/2 rtol=1e-14 @test ClausenFunctions.cl(TN( 1), 0.0 + 1.0im) ≈ -0.0413248546129181 - 1.5707963267948966im rtol=1e-14 @test ClausenFunctions.cl(TN( 1), 0.0 - 1.0im) ≈ -0.0413248546129181 - 1.5707963267948966im rtol=1e-14 @test ClausenFunctions.cl(TN( 2), 0.0 + 1.0im) ≈ 1.5707963267948966 + 0.9861797794993302im rtol=1e-14 @test ClausenFunctions.cl(TN( 2), 0.0 - 1.0im) ≈ -1.5707963267948966 - 0.9861797794993302im rtol=1e-14 @test ClausenFunctions.cl(TN( 2), 1.0 + 1.0im) ≈ 1.4107754938116412 - 0.1044778629291566im rtol=1e-14 @test ClausenFunctions.cl(TN( 2), 1.0 - 1.0im) ≈ 1.4107754938116412 + 0.1044778629291566im rtol=1e-14 @test ClausenFunctions.cl(TN(-2), big(1)) ≈ 1im*(1 + exp(big(1)*im))*exp(big(1)*im)/(exp(big(1)*im) - 1)^3 rtol=1e-40 @test ClausenFunctions.cl(TN(-2), big(1) + 0im) ≈ 1im*(1 + exp(big(1)*im))*exp(big(1)*im)/(exp(big(1)*im) - 1)^3 rtol=1e-40 @test ClausenFunctions.cl(TN(-1), big(1)) ≈ exp(big(1)*im)/(exp(big(1)*im) - 1)^2 rtol=1e-40 @test ClausenFunctions.cl(TN(-1), big(1) + 0im) ≈ exp(big(1)*im)/(exp(big(1)*im) - 1)^2 rtol=1e-40 @test ClausenFunctions.cl(TN( 0), big(1)) ≈ cot(BigFloat("0.5"))/2 rtol=1e-40 @test ClausenFunctions.cl(TN( 0), big(1) + 0im) ≈ cot(BigFloat("0.5"))/2 rtol=1e-40 @test ClausenFunctions.cl(TN( 1), big(1)) ≈ BigFloat("0.04201950582536896172579838403790203712454") rtol=1e-40 @test ClausenFunctions.cl(TN( 1), big(1) + 0im) ≈ BigFloat("0.04201950582536896172579838403790203712454") rtol=1e-40 @test ClausenFunctions.cl(TN( 2), big(1)) ≈ BigFloat("1.0139591323607685042945743388859146875612") rtol=1e-40 @test ClausenFunctions.cl(TN( 2), big(1) + 0im) ≈ BigFloat("1.0139591323607685042945743388859146875612") rtol=1e-40 # test handling of negative zero for n in -100:2:100 @test !signbit(ClausenFunctions.cl(TN(n), 0.0)) @test signbit(ClausenFunctions.cl(TN(n), -0.0)) @test !signbit(ClausenFunctions.cl(TN(n), BigFloat("0.0"))) @test signbit(ClausenFunctions.cl(TN(n), BigFloat("-0.0"))) @test !signbit(real(ClausenFunctions.cl(TN(n), Complex(0.0, 0.0)))) @test !signbit(imag(ClausenFunctions.cl(TN(n), Complex(0.0, 0.0)))) @test !signbit(real(ClausenFunctions.cl(TN(n), Complex(0.0, -0.0)))) @test signbit(imag(ClausenFunctions.cl(TN(n), Complex(0.0, -0.0)))) @test signbit(real(ClausenFunctions.cl(TN(n), Complex(-0.0, 0.0)))) @test !signbit(imag(ClausenFunctions.cl(TN(n), Complex(-0.0, 0.0)))) @test signbit(real(ClausenFunctions.cl(TN(n), Complex(-0.0, -0.0)))) @test signbit(imag(ClausenFunctions.cl(TN(n), Complex(-0.0, -0.0)))) end end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
3183
@testset "cl1" begin data = open(readdlm, joinpath(@__DIR__, "data", "Cl1.txt")) for r in 1:size(data, 1) row = data[r, :] x = row[1] expected = row[2] @test ClausenFunctions.cl1(x) ≈ expected rtol=1e-13 @test ClausenFunctions.cl1(-x) ≈ expected rtol=1e-13 @test ClausenFunctions.cl1(x - 2pi) ≈ expected rtol=1e-12 @test ClausenFunctions.cl1(x + 2pi) ≈ expected rtol=1e-13 @test ClausenFunctions.cl1(Float16(x)) ≈ Float16(expected) atol=10*eps(Float16) rtol=30*eps(Float16) @test ClausenFunctions.cl1(Float32(x)) ≈ Float32(expected) atol=10*eps(Float32) rtol=30*eps(Float32) @test ClausenFunctions.cl1(x) ≈ real(ClausenFunctions.cl1(Complex(x))) rtol=1e-13 end @test ClausenFunctions.cl1(1//2) ≈ 0.70358563513784466 rtol=1e-14 @test ClausenFunctions.cl1(1) ≈ ClausenFunctions.cl1(1.0) rtol=1e-14 @test ClausenFunctions.cl1(0.0) == Inf # test complex Clausen function cl1 @test ClausenFunctions.cl1(Complex(1/2)) ≈ 0.70358563513784466 rtol=1e-14 @test ClausenFunctions.cl1(Complex(1/2, 1)) ≈ -0.14296382186432422 - 1.06599896593689653im rtol=1e-14 @test ClausenFunctions.cl1(Complex(1/2, -1)) ≈ -0.14296382186432422 + 1.06599896593689653im rtol=1e-14 @test ClausenFunctions.cl1(Complex(1, 0)) ≈ 0.042019505825368962 rtol=1e-14 @test ClausenFunctions.cl1(Complex(1, 1)) ≈ -0.34796082854253047 - 0.70210885509136190im rtol=1e-14 @test ClausenFunctions.cl1(Complex(2, 0)) ≈ -0.52054343429085363 rtol=1e-14 @test ClausenFunctions.cl1(Complex(1.0, 0.0)) ≈ 0.042019505825368962 rtol=1e-14 @test ClausenFunctions.cl1(Complex(1.0, 1.0)) ≈ -0.34796082854253047 - 0.70210885509136190im rtol=1e-14 @test ClausenFunctions.cl1(Complex(2.0, 0.0)) ≈ -0.52054343429085363 rtol=1e-14 @test ClausenFunctions.cl1(Complex(2.0, 1.0)) ≈ -0.68284871442091651 - 0.28844676165196074im rtol=1e-14 @test ClausenFunctions.cl1(Complex(2.0, -1.0)) ≈ -0.68284871442091651 + 0.28844676165196074im rtol=1e-14 @test imag(ClausenFunctions.cl1(Complex(2.0, eps(Float64)))) < 0.0 @test imag(ClausenFunctions.cl1(Complex(2.0, -eps(Float64)))) > 0.0 @test ClausenFunctions.cl1(Complex(2.0, -eps(Float64))) ≈ -0.52054343429085363 rtol=1e-14 @test ClausenFunctions.cl1(Complex(0)) == Inf @test ClausenFunctions.cl1(Complex(0.0)) == Inf # test BigFloat setprecision(BigFloat, 100) do @test isapprox(ClausenFunctions.cl1(BigFloat("1")), BigFloat("0.042019505825368961725798384037902037124538920557034"); rtol=10*eps(BigFloat)) @test isapprox(ClausenFunctions.cl1(BigFloat("0.5") + BigFloat("1")*im), BigFloat("-0.14296382186432422499606514633517958638642188617714") + BigFloat("-1.0659989659368965336455070335833947446477603110289")*im; rtol=10*eps(BigFloat)) @test isapprox(ClausenFunctions.cl1(BigFloat("2") + BigFloat("-1")*im), BigFloat("-0.68284871442091650950302220327572227276874425568964") + BigFloat("0.28844676165196073566657598635590990207739789086077")*im; rtol=10*eps(BigFloat)) @test isapprox(ClausenFunctions.cl1(BigFloat("0")), BigFloat("Inf"); rtol=10*eps(BigFloat)) end end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
1102
@testset "cl2" begin data = open(readdlm, joinpath(@__DIR__, "data", "Cl2.txt")) for r in 1:size(data, 1) row = data[r, :] x = row[1] expected = row[2] @test ClausenFunctions.cl2(x) ≈ expected rtol=1e-14 atol=1e-14 @test ClausenFunctions.cl2(-x) ≈ -expected rtol=1e-14 atol=1e-14 @test ClausenFunctions.cl2(x - 2pi) ≈ expected rtol=1e-13 atol=1e-13 @test ClausenFunctions.cl2(x + 2pi) ≈ expected rtol=1e-13 atol=1e-13 @test ClausenFunctions.cl2(Float16(x)) ≈ Float16(expected) atol=30*eps(Float16) rtol=30*eps(Float16) @test ClausenFunctions.cl2(Float32(x)) ≈ Float32(expected) atol=30*eps(Float32) rtol=30*eps(Float32) end @test ClausenFunctions.cl2(0.0) == 0.0 @test ClausenFunctions.cl2(pi) == 0.0 @test ClausenFunctions.cl2(pi/2) ≈ 0.915965594177219015054603514932384110 rtol=1e-14 @test ClausenFunctions.cl2(1//2) ≈ 0.84831187770367927 rtol=1e-14 # test handling of negative zero @test !signbit(ClausenFunctions.cl2(0.0)) @test signbit(ClausenFunctions.cl2(-0.0)) end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
797
@testset "cl3" begin data = open(readdlm, joinpath(@__DIR__, "data", "Cl3.txt")) for r in 1:size(data, 1) row = data[r, :] x = row[1] expected = row[2] @test ClausenFunctions.cl3(x) ≈ expected rtol=1e-14 atol=1e-14 @test ClausenFunctions.cl3(-x) ≈ expected rtol=1e-14 atol=1e-14 @test ClausenFunctions.cl3(x - 2pi) ≈ expected rtol=1e-14 atol=1e-13 @test ClausenFunctions.cl3(x + 2pi) ≈ expected rtol=1e-14 atol=1e-13 @test ClausenFunctions.cl3(Float16(x)) ≈ Float16(expected) atol=30*eps(Float16) rtol=30*eps(Float16) @test ClausenFunctions.cl3(Float32(x)) ≈ Float32(expected) atol=30*eps(Float32) rtol=30*eps(Float32) end @test ClausenFunctions.cl3(1//2) ≈ 0.92769631047023043 rtol=1e-14 end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
1013
@testset "cl4" begin data = open(readdlm, joinpath(@__DIR__, "data", "Cl4.txt")) for r in 1:size(data, 1) row = data[r, :] x = row[1] expected = row[2] @test ClausenFunctions.cl4(x) ≈ expected rtol=1e-14 atol=1e-14 @test ClausenFunctions.cl4(-x) ≈ -expected rtol=1e-14 atol=1e-14 @test ClausenFunctions.cl4(x - 2pi) ≈ expected rtol=1e-14 atol=1e-13 @test ClausenFunctions.cl4(x + 2pi) ≈ expected rtol=1e-14 atol=1e-13 @test ClausenFunctions.cl4(Float16(x)) ≈ Float16(expected) atol=30*eps(Float16) rtol=30*eps(Float16) @test ClausenFunctions.cl4(Float32(x)) ≈ Float32(expected) atol=30*eps(Float32) rtol=30*eps(Float32) end @test ClausenFunctions.cl4(0.0) == 0.0 @test ClausenFunctions.cl4(pi) == 0.0 @test ClausenFunctions.cl4(1//2) ≈ 0.54837172654589549 rtol=1e-14 # test handling of negative zero @test !signbit(ClausenFunctions.cl4(0.0)) @test signbit(ClausenFunctions.cl4(-0.0)) end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
797
@testset "cl5" begin data = open(readdlm, joinpath(@__DIR__, "data", "Cl5.txt")) for r in 1:size(data, 1) row = data[r, :] x = row[1] expected = row[2] @test ClausenFunctions.cl5(x) ≈ expected rtol=1e-14 atol=1e-14 @test ClausenFunctions.cl5(-x) ≈ expected rtol=1e-14 atol=1e-14 @test ClausenFunctions.cl5(x - 2pi) ≈ expected rtol=1e-14 atol=1e-13 @test ClausenFunctions.cl5(x + 2pi) ≈ expected rtol=1e-14 atol=1e-13 @test ClausenFunctions.cl5(Float16(x)) ≈ Float16(expected) atol=30*eps(Float16) rtol=30*eps(Float16) @test ClausenFunctions.cl5(Float32(x)) ≈ Float32(expected) atol=30*eps(Float32) rtol=30*eps(Float32) end @test ClausenFunctions.cl5(1//2) ≈ 0.89390286951083851 rtol=1e-14 end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
1013
@testset "cl6" begin data = open(readdlm, joinpath(@__DIR__, "data", "Cl6.txt")) for r in 1:size(data, 1) row = data[r, :] x = row[1] expected = row[2] @test ClausenFunctions.cl6(x) ≈ expected rtol=1e-14 atol=1e-14 @test ClausenFunctions.cl6(-x) ≈ -expected rtol=1e-14 atol=1e-14 @test ClausenFunctions.cl6(x - 2pi) ≈ expected rtol=1e-14 atol=1e-13 @test ClausenFunctions.cl6(x + 2pi) ≈ expected rtol=1e-14 atol=1e-13 @test ClausenFunctions.cl6(Float16(x)) ≈ Float16(expected) atol=30*eps(Float16) rtol=30*eps(Float16) @test ClausenFunctions.cl6(Float32(x)) ≈ Float32(expected) atol=30*eps(Float32) rtol=30*eps(Float32) end @test ClausenFunctions.cl6(0.0) == 0.0 @test ClausenFunctions.cl6(pi) == 0.0 @test ClausenFunctions.cl6(1//2) ≈ 0.49419627977618802 rtol=1e-14 # test handling of negative zero @test !signbit(ClausenFunctions.cl6(0.0)) @test signbit(ClausenFunctions.cl6(-0.0)) end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
5439
@testset "sl" for TN in (Int8, Int16, Int32, Int64, Int128) Sl1(x) = 0.5*(pi - x) Sl2(x) = pi^2/6 - pi/2*x + x^2/4 Sl3(x) = pi^2/6*x - pi/4*x^2 + x^3/12 Sl4(x) = pi^4/90 - pi^2/12*x^2 + pi/12*x^3 - x^4/48 n = 10 x_min = 0.0 x_max = 2pi data = (x_max - x_min)*rand(Float64, n) + x_min*ones(n) for x in data @test ClausenFunctions.sl(TN(1), x) ≈ Sl1(x) rtol=1e-14 atol=1e-14 @test ClausenFunctions.sl(TN(2), x) ≈ Sl2(x) rtol=1e-14 atol=1e-14 @test ClausenFunctions.sl(TN(3), x) ≈ Sl3(x) rtol=1e-14 atol=1e-14 @test ClausenFunctions.sl(TN(4), x) ≈ Sl4(x) rtol=1e-14 atol=1e-13 end for n in vcat(collect(-2:31), [1000, 1001]) (n > typemax(TN) || n < typemin(TN)) && continue data = open(readdlm, joinpath(@__DIR__, "data", "Sl$(n).txt")) for r in 1:size(data, 1) row = data[r, :] x = row[1] expected = row[2] @test ClausenFunctions.sl(TN(n), x) == (-1)^TN(n)*ClausenFunctions.sl(TN(n), -x) @test ClausenFunctions.sl(TN(n), x) ≈ expected rtol=1e-14 atol=1e-14 @test ClausenFunctions.sl(TN(n), Float16(x)) ≈ Float16(expected) atol=30*eps(Float16) rtol=30*eps(Float16) @test ClausenFunctions.sl(TN(n), Float32(x)) ≈ Float32(expected) atol=30*eps(Float32) rtol=30*eps(Float32) @test ClausenFunctions.sl(TN(n), Complex(x)) ≈ expected rtol=1e-14 atol=1e-14 @test ClausenFunctions.sl(TN(n), Complex(Float16(x))) ≈ Float16(expected) atol=30*eps(Float16) rtol=30*eps(Float16) @test ClausenFunctions.sl(TN(n), Complex(Float32(x))) ≈ Float32(expected) atol=30*eps(Float32) rtol=30*eps(Float32) end end @test ClausenFunctions.sl(TN(1), 1//2) ≈ 1.3207963267948966 rtol=1e-14 @test ClausenFunctions.sl(TN(2), 1//2) ≈ 0.92203590345077813 rtol=1e-14 @test ClausenFunctions.sl(TN(3), 1//2) ≈ 0.63653415924141781 rtol=1e-14 @test ClausenFunctions.sl(TN(4), 1//2) ≈ 0.90812931549667023 rtol=1e-14 @test ClausenFunctions.sl(TN(5), 1//2) ≈ 0.51085256423059275 rtol=1e-14 @test ClausenFunctions.sl(TN(6), 1//2) ≈ 0.88593812938731573 rtol=1e-14 @test ClausenFunctions.sl(TN(1), Complex(1//2)) ≈ 1.3207963267948966 rtol=1e-14 @test ClausenFunctions.sl(TN(2), Complex(1//2)) ≈ 0.92203590345077813 rtol=1e-14 @test ClausenFunctions.sl(TN(3), Complex(1//2)) ≈ 0.63653415924141781 rtol=1e-14 @test ClausenFunctions.sl(TN(4), Complex(1//2)) ≈ 0.90812931549667023 rtol=1e-14 @test ClausenFunctions.sl(TN(5), Complex(1//2)) ≈ 0.51085256423059275 rtol=1e-14 @test ClausenFunctions.sl(TN(6), Complex(1//2)) ≈ 0.88593812938731573 rtol=1e-14 @test ClausenFunctions.sl(TN(1), 0.0 + 1.0im) ≈ 1.5707963267948966 - 0.5im rtol=1e-14 @test ClausenFunctions.sl(TN(1), 0.0 - 1.0im) ≈ -1.5707963267948966 + 0.5im rtol=1e-14 # @todo check @test ClausenFunctions.sl(TN(2), 0.0 + 1.0im) ≈ 1.3949340668482264 - 1.5707963267948966im rtol=1e-14 @test ClausenFunctions.sl(TN(2), 0.0 - 1.0im) ≈ 1.3949340668482264 - 1.5707963267948966im rtol=1e-14 # @todo check @test ClausenFunctions.sl(TN(2), 1.0 + 1.0im) ≈ 0.07413774005332982 - 1.07079632679489662im rtol=1e-14 @test ClausenFunctions.sl(TN(2), 1.0 - 1.0im) ≈ 0.07413774005332982 + 1.07079632679489662im rtol=1e-14 @test ClausenFunctions.sl(TN(3), 0.0 + 1.0im) ≈ 0.7853981633974483 + 1.5616007335148931im rtol=1e-14 @test ClausenFunctions.sl(TN(3), 0.0 - 1.0im) ≈ -0.7853981633974483 - 1.5616007335148931im rtol=1e-14 # @todo check @test ClausenFunctions.sl(TN(-2), big(1)) == 0 @test ClausenFunctions.sl(TN(-2), big(1) + 0im) == 0 @test ClausenFunctions.sl(TN(-1), big(1)) == 0 @test ClausenFunctions.sl(TN(-1), big(1) + 0im) == 0 @test ClausenFunctions.sl(TN( 0), big(1)) ≈ -BigFloat("0.5") rtol=1e-40 @test ClausenFunctions.sl(TN( 0), big(1) + 0im) ≈ -BigFloat("0.5") rtol=1e-40 @test ClausenFunctions.sl(TN( 1), big(0)) == BigFloat(0) @test ClausenFunctions.sl(TN( 1), big(1)) ≈ BigFloat("1.07079632679489661923132169163975144209858") rtol=1e-40 @test ClausenFunctions.sl(TN( 1), big(1) + 0im) ≈ BigFloat("1.07079632679489661923132169163975144209858") rtol=1e-40 @test ClausenFunctions.sl(TN( 2), big(1)) ≈ BigFloat("0.324137740053329817241093475006273747120365") rtol=1e-40 @test ClausenFunctions.sl(TN( 2), big(1) + 0im) ≈ BigFloat("0.324137740053329817241093475006273747120365") rtol=1e-40 # test handling of negative zero for n in 1:2:101 @test !signbit(ClausenFunctions.sl(TN(n), 0.0)) @test signbit(ClausenFunctions.sl(TN(n), -0.0)) @test !signbit(ClausenFunctions.sl(TN(n), BigFloat("0.0"))) @test signbit(ClausenFunctions.sl(TN(n), BigFloat("-0.0"))) @test !signbit(real(ClausenFunctions.sl(TN(n), Complex(0.0, 0.0)))) @test !signbit(imag(ClausenFunctions.sl(TN(n), Complex(0.0, 0.0)))) @test !signbit(real(ClausenFunctions.sl(TN(n), Complex(0.0, -0.0)))) @test signbit(imag(ClausenFunctions.sl(TN(n), Complex(0.0, -0.0)))) @test signbit(real(ClausenFunctions.sl(TN(n), Complex(-0.0, 0.0)))) @test !signbit(imag(ClausenFunctions.sl(TN(n), Complex(-0.0, 0.0)))) @test signbit(real(ClausenFunctions.sl(TN(n), Complex(-0.0, -0.0)))) @test signbit(imag(ClausenFunctions.sl(TN(n), Complex(-0.0, -0.0)))) end end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
2714
@testset "range_reduction (n = $n)" for n in 1:2 rr(x) = ClausenFunctions.range_reduce(n, x)[1] # cases with catastrophic cancellation (therefore not tested with rtol) @test rr(2pi) ≈ zero(Float64) atol=eps(Float64) @test rr(2pi + 1e-15) ≈ 1e-15 atol=eps(Float64) @test rr(2pi + 1e-14) ≈ 1e-14 atol=2*eps(Float64) @test rr(2pi + 1e-13) ≈ 1e-13 atol=2*eps(Float64) @test rr(2pi + 1e-12) ≈ 1e-12 atol=2*eps(Float64) # cases with catastrophic cancellation (therefore not tested with rtol) @test rr(prevfloat(2pi)) ≈ 1.4769252867665590e-15 atol=10*eps(Float64) @test rr(2pi - 1e-15) ≈ 1e-15 atol=eps(Float64) @test rr(2pi - 1e-14) ≈ 1e-14 atol=2*eps(Float64) @test rr(2pi - 1e-13) ≈ 1e-13 atol=4*eps(Float64) @test rr(2pi - 1e-12) ≈ 1e-12 atol=2*eps(Float64) # cases w/o catastrophic cancellation @test rr(3pi) ≈ pi rtol=eps(Float64) @test rr(nextfloat(3pi)) ≈ 3.1415926535897920 rtol=eps(Float64) @test rr(3pi + 1e-15) ≈ pi - 1e-15 rtol=eps(Float64) @test rr(3pi + 1e-14) ≈ pi - 1e-14 rtol=eps(Float64) @test rr(3pi + 1e-13) ≈ pi - 1e-13 rtol=2*eps(Float64) @test rr(3pi + 1e-12) ≈ pi - 1e-12 rtol=eps(Float64) end @testset "two_pi_minus" begin f(x) = ClausenFunctions.two_pi_minus(x) # Float16 @test f(Float16(2pi)) ≈ zero(Float16) atol=2*eps(Float16) @test f(nextfloat(Float16(2pi))) ≈ -eps(Float16(2pi)) atol=2*eps(Float16) @test f(nextfloat(Float16(2pi), 2)) ≈ -2*eps(Float16(2pi)) atol=2*eps(Float16) @test f(prevfloat(Float16(2pi))) ≈ eps(Float16(2pi)) atol=2*eps(Float16) @test f(prevfloat(Float16(2pi), 2)) ≈ 2*eps(Float16(2pi)) atol=2*eps(Float16) # Float32 @test f(Float32(2pi)) ≈ zero(Float32) atol=2*eps(Float32) @test f(nextfloat(Float32(2pi))) ≈ -eps(Float32(2pi)) atol=2*eps(Float32) @test f(nextfloat(Float32(2pi), 2)) ≈ -2*eps(Float32(2pi)) atol=2*eps(Float32) @test f(prevfloat(Float32(2pi))) ≈ eps(Float32(2pi)) atol=2*eps(Float32) @test f(prevfloat(Float32(2pi), 2)) ≈ 2*eps(Float32(2pi)) atol=2*eps(Float32) # Float64 @test f(2pi) ≈ zero(Float64) atol=2*eps(Float64) @test f(nextfloat(2pi)) ≈ -eps(2pi) atol=2*eps(Float64) @test f(nextfloat(2pi, 2)) ≈ -2*eps(2pi) atol=2*eps(Float64) @test f(prevfloat(2pi)) ≈ eps(2pi) atol=2*eps(Float64) @test f(prevfloat(2pi, 2)) ≈ 2*eps(2pi) atol=2*eps(Float64) end
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
code
229
using Test using DelimitedFiles import ClausenFunctions include("Cl1.jl") include("Cl2.jl") include("Cl3.jl") include("Cl4.jl") include("Cl5.jl") include("Cl6.jl") include("Cl.jl") include("Sl.jl") include("range_reduction.jl")
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
1.16.0
29b6b51b22e92c7815878573834576744c1119d2
docs
1993
ClausenFunctions.jl =================== [![test](https://github.com/Expander/ClausenFunctions.jl/actions/workflows/build.yml/badge.svg)](https://github.com/Expander/ClausenFunctions.jl/actions/workflows/build.yml) [![coverage](https://coveralls.io/repos/github/Expander/ClausenFunctions.jl/badge.svg)](https://coveralls.io/github/Expander/ClausenFunctions.jl) The ClausenFunctions.jl package provides Julia implementations of the Standard Clausen functions and Glaisher-Clausen functions of integer order for real or complex arguments. Example ------- ```.jl using ClausenFunctions # real arguments cl1(1.0) # Standard Clausen function Cl_1(x) cl2(1.0) # Standard Clausen function Cl_2(x) cl3(1.0) # Standard Clausen function Cl_3(x) cl4(1.0) # Standard Clausen function Cl_4(x) cl5(1.0) # Standard Clausen function Cl_5(x) cl6(1.0) # Standard Clausen function Cl_6(x) cl(10, 1.0) # Standard Clausen function Cl_n(x) cl(10, big"1") # Standard Clausen function Cl_n(x) sl(10, 1.0) # Glaisher-Clausen function Sl_n(x) sl(10, big"1") # Glaisher-Clausen function Sl_n(x) # complex arguments cl1(1.0 + 1.0im) # Standard Clausen function Cl_1(x) cl(10, 1.0 + 1.0im) # Standard Clausen function Cl_n(x) cl(10, big"1" + 1im) # Standard Clausen function Cl_n(x) sl(10, 1.0 + 1.0im) # Glaisher-Clausen function Sl_n(x) sl(10, big"1" + 1im) # Glaisher-Clausen function Sl_n(x) ``` Documentation ------------- [https://docs.juliahub.com/ClausenFunctions/](https://docs.juliahub.com/ClausenFunctions/) Notes ----- The implementation of the Standard Clausen function `cl(n,x)` for real `x` follows the approach presented in [Jiming Wu, Xiaoping Zhang, Dongjie Liu, "An efficient calculation of the Clausen functions Cl_n(θ)(n >= 2)", Bit Numer Math 50, 193-206 (2010) [https://doi.org/10.1007/s10543-009-0246-8](https://doi.org/10.1007/s10543-009-0246-8)]. Copying ------- ClausenFunctions.jl is licenced under the MIT License.
ClausenFunctions
https://github.com/Expander/ClausenFunctions.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
3086
using Distributed nprocs() == 1 && addprocs() @everywhere begin using AutoOfflineRL using AutoMLPipeline using Parquet using DataFrames end @everywhere begin # load preprocessing elements #### Scaler rb = SKPreprocessor("RobustScaler"); pt = SKPreprocessor("PowerTransformer"); norm = SKPreprocessor("Normalizer"); mx = SKPreprocessor("MinMaxScaler"); std = SKPreprocessor("StandardScaler") ##### Column selector catf = CatFeatureSelector(); numf = NumFeatureSelector(); ## load filters ##### Decomposition #apca = SKPreprocessor("PCA",Dict(:autocomponent=>true,:name=>"autoPCA")); #afa = SKPreprocessor("FactorAnalysis",Dict(:autocomponent=>true,:name=>"autoFA")); #aica = SKPreprocessor("FastICA",Dict(:autocomponent=>true,:name=>"autoICA")); pca = SKPreprocessor("PCA"); fa = SKPreprocessor("FactorAnalysis"); ica = SKPreprocessor("FastICA"); noop = Identity(Dict(:name => "Noop")); end # load dataset path = pkgdir(AutoOfflineRL) dataset = "$path/data/smalldata.parquet" df = Parquet.read_parquet(dataset) |> DataFrame |> dropmissing #df = df[:,["day", "hour", "minute", "dow"]] #df.sensor1 = rand(1:500,srow) #df.sensor2 = rand(1:200,srow) #df.sensor3 = rand(1:100,srow) #df.action = rand([10,50,100],srow) #df.reward = rand(srow) srow,_ = size(df) observation = df[:, ["day", "hour", "minute", "dow", "sensor1", "sensor2", "sensor3"]] reward = df[:,["reward"]] |> deepcopy |> DataFrame action = df[:,["action"]] |> deepcopy |> DataFrame _terminals = zeros(Int,srow) _terminals[collect(100:1000:9000)] .= 1 _terminals[end] = 1 dterminal = DataFrame(terminal=_terminals) action_reward_terminal = DataFrame[action, reward, dterminal] agent = DiscreteRLOffline("NFQ") pipe = (numf |> mx |> pca) |> agent crossvalidateRL(pipe,observation,action_reward_terminal) function pipelinesearch() agentnames = ["DiscreteCQL","NFQ","DoubleDQN","DiscreteSAC","DiscreteBCQ","DiscreteBC","DQN"] scalers = [rb,pt,norm,std,mx,noop] extractors = [pca,ica,fa,noop] dfresults = @sync @distributed (vcat) for agentname in agentnames @distributed (vcat) for sc in scalers @distributed (vcat) for xt in extractors try rlagent = DiscreteRLOffline(agentname,Dict(:runtime_args=>Dict(:n_epochs=>1))) rlpipeline = ((numf |> sc |> xt)) |> rlagent res = crossvalidateRL(rlpipeline,observation,action_reward_terminal) scn = sc.name[1:end - 4]; xtn = xt.name[1:end - 4]; lrn = rlagent.name[1:end - 4] pname = "$scn |> $xtn |> $lrn" if !isnan(res) DataFrame(pipeline=pname,td_error=res) else DataFrame() end catch e println("error in $agentname") DataFrame() end end end end #sort!(dfresults,:percent_action_matches,rev=true) return dfresults end dftable= pipelinesearch() sort!(dftable,:td_error,rev=false) show(dftable,allcols=true,allrows=true,truncate=0)
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
3086
using Distributed nprocs() == 1 && addprocs() @everywhere begin using AutoOfflineRL using AutoMLPipeline using Parquet using DataFrames end @everywhere begin # load preprocessing elements #### Scaler rb = SKPreprocessor("RobustScaler"); pt = SKPreprocessor("PowerTransformer"); norm = SKPreprocessor("Normalizer"); mx = SKPreprocessor("MinMaxScaler"); std = SKPreprocessor("StandardScaler") ##### Column selector catf = CatFeatureSelector(); numf = NumFeatureSelector(); ## load filters ##### Decomposition #apca = SKPreprocessor("PCA",Dict(:autocomponent=>true,:name=>"autoPCA")); #afa = SKPreprocessor("FactorAnalysis",Dict(:autocomponent=>true,:name=>"autoFA")); #aica = SKPreprocessor("FastICA",Dict(:autocomponent=>true,:name=>"autoICA")); pca = SKPreprocessor("PCA"); fa = SKPreprocessor("FactorAnalysis"); ica = SKPreprocessor("FastICA"); noop = Identity(Dict(:name => "Noop")); end # load dataset path = pkgdir(AutoOfflineRL) dataset = "$path/data/smalldata.parquet" df = Parquet.read_parquet(dataset) |> DataFrame |> dropmissing #df = df[:,["day", "hour", "minute", "dow"]] #df.sensor1 = rand(1:500,srow) #df.sensor2 = rand(1:200,srow) #df.sensor3 = rand(1:100,srow) #df.action = rand([10,50,100],srow) #df.reward = rand(srow) srow,_ = size(df) observation = df[:, ["day", "hour", "minute", "dow", "sensor1", "sensor2", "sensor3"]] reward = df[:,["reward"]] |> deepcopy |> DataFrame action = df[:,["action"]] |> deepcopy |> DataFrame _terminals = zeros(Int,srow) _terminals[collect(100:1000:9000)] .= 1 _terminals[end] = 1 dterminal = DataFrame(terminal=_terminals) action_reward_terminal = DataFrame[action, reward, dterminal] agent = DiscreteRLOffline("NFQ") pipe = (numf |> mx |> pca) |> agent crossvalidateRL(pipe,observation,action_reward_terminal) function pipelinesearch() agentnames = ["DiscreteCQL","NFQ","DoubleDQN","DiscreteSAC","DiscreteBCQ","DiscreteBC","DQN"] scalers = [rb,pt,norm,std,mx,noop] extractors = [pca,ica,fa,noop] dfresults = @sync @distributed (vcat) for agentname in agentnames @distributed (vcat) for sc in scalers @distributed (vcat) for xt in extractors try rlagent = DiscreteRLOffline(agentname,Dict(:runtime_args=>Dict(:n_epochs=>1))) rlpipeline = ((numf |> sc |> xt)) |> rlagent res = crossvalidateRL(rlpipeline,observation,action_reward_terminal) scn = sc.name[1:end - 4]; xtn = xt.name[1:end - 4]; lrn = rlagent.name[1:end - 4] pname = "$scn |> $xtn |> $lrn" if !isnan(res) DataFrame(pipeline=pname,td_error=res) else DataFrame() end catch e println("error in $agentname") DataFrame() end end end end #sort!(dfresults,:percent_action_matches,rev=true) return dfresults end dftable= pipelinesearch() sort!(dftable,:td_error,rev=false) show(dftable,allcols=true,allrows=true,truncate=0)
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
1414
module AutoOfflineRL using DataFrames using CSV export fit, fit!, transform, transform!,fit_transform, fit_transform! import AMLPipelineBase.AbsTypes: fit, fit!, transform, transform! using AMLPipelineBase using AMLPipelineBase: AbsTypes, Utils, BaselineModels, Pipelines using AMLPipelineBase: BaseFilters, FeatureSelectors, DecisionTreeLearners using AMLPipelineBase: EnsembleMethods, CrossValidators using AMLPipelineBase: NARemovers export Machine, Learner, Transformer, Workflow, Computer export holdout, kfold, score, infer_eltype, nested_dict_to_tuples, nested_dict_set!, nested_dict_merge, create_transformer, mergedict, getiris,getprofb, skipmean,skipmedian,skipstd, aggregatorclskipmissing export Baseline, Identity export Imputer,OneHotEncoder,Wrapper export PrunedTree,RandomForest,Adaboost export VoteEnsemble, StackEnsemble, BestLearner export FeatureSelector, CatFeatureSelector, NumFeatureSelector, CatNumDiscriminator export crossvalidate export NARemover export @pipeline export @pipelinex export @pipelinez export +, |>, *, |, >> export Pipeline, ComboPipeline #export RLMachine, RLOffline, WeeklyEpisodes #Base.@kwdef struct WeeklyEpisodes <: RLMachine # _params::Dict = Dict() # _model::Dict = Dict() #end include("offlinerls.jl") using .OfflineRLs export DiscreteRLOffline, fit! export driver, listdiscreateagents export crossvalidateRL end # module
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
9687
module OfflineRLs using AutoOfflineRL using PythonCall import Statistics using Parquet using Distributed using DataFrames: DataFrame, dropmissing using Random using CSV using Dates using ..AbsTypes using ..Utils import ..AbsTypes: fit, fit!, transform, transform! import PythonCall const PYC = PythonCall using ..Utils: nested_dict_merge export DiscreteRLOffline, fit!, transform!, fit, transform export listdiscreateagents, driver export crossvalidateRL const rl_dict = Dict{String, PYC.Py}() const metric_dict = Dict{String, PYC.Py}() const PYRL = PYC.pynew() const PYPD = PYC.pynew() const PYNP = PYC.pynew() const PYDT = PYC.pynew() const PYMT = PYC.pynew() const PYSK = PYC.pynew() function __init__() PYC.pycopy!(PYRL, PYC.pyimport("d3rlpy.algos")) PYC.pycopy!(PYDT, PYC.pyimport("d3rlpy.datasets")) PYC.pycopy!(PYSK, PYC.pyimport("sklearn.model_selection")) PYC.pycopy!(PYMT, PYC.pyimport("d3rlpy.metrics")) PYC.pycopy!(PYPD, PYC.pyimport("pandas")) PYC.pycopy!(PYNP, PYC.pyimport("numpy")) # OfflineRLs metric_dict["cross_validate"] = PYSK.cross_validate metric_dict["train_test_split"] = PYSK.train_test_split metric_dict["td_error_scorer"] = PYMT.td_error_scorer metric_dict["discrete_action_match_scorer"] = PYMT.discrete_action_match_scorer metric_dict["average_value_estimation_scorer"] = PYMT.average_value_estimation_scorer metric_dict["get_cartpole"] = PYDT.get_cartpole rl_dict["DiscreteBC"] = PYRL rl_dict["DQN"] = PYRL rl_dict["NFQ"] = PYRL rl_dict["DoubleDQN"] = PYRL rl_dict["DiscreteBCQ"] = PYRL rl_dict["DiscreteCQL"] = PYRL rl_dict["DiscreteSAC"] = PYRL #rl_dict["DiscreteRandomPolicy"] = PYRL end mutable struct DiscreteRLOffline <: Learner name::String model::Dict{Symbol,Any} function DiscreteRLOffline(args=Dict{Symbol,Any}()) default_args = Dict{Symbol,Any}( :name => "DQN", :tag => "RLOffline", :rlagent => "DQN", :iterations => 100, :save_metrics => false, :rlobjtrained => PYC.PyNULL, :o_header => ["day", "hour", "minute", "dow", "metric1", "metric2", "metric3", "metric4"], :a_header => ["action"], :r_header => ["reward"], :save_model => false, :runtime_args => Dict{Symbol, Any}( :n_epochs => 3, ), :impl_args => Dict{Symbol,Any}( :scaler => "min_max", :use_gpu => false, ) ) cargs = nested_dict_merge(default_args,args) #datestring = Dates.format(now(), "yyyy-mm-dd-HH-MM") cargs[:name] = cargs[:name]*"_"*randstring(3) rlagent = cargs[:rlagent] if !(rlagent in keys(rl_dict)) println("error: $rlagent is not supported.") println() discreteagents() error("Argument keyword error") end new(cargs[:name],cargs) end end function DiscreteRLOffline(rlagent::String, args::Dict) DiscreteRLOffline(Dict(:rlagent => rlagent, :name => rlagent, args...)) end function DiscreteRLOffline(rlagent::String; args...) DiscreteRLOffline(Dict( :rlagent => rlagent, :name => rlagent, args... )) end function listdiscreateagents() println() println("RL Discrete Agents:") agents = keys(rl_dict) |> collect [println(" ",agent," ") for agent in agents] println("See d3rlpy python package for details about the agent arguments.") nothing end function discreteagents() println() println("syntax: DiscreteRLOffline(name::String, args::Dict)") println("and 'args' are the agent's parameters") println("See d3rlpy python package for details about the agent arguments.") println("use: listdiscreateagents() to get the available RL agents") end function createmdpdata!(agent::DiscreteRLOffline, df::DataFrame, action_reward_term::Vector) _observations = df |> Array .|> PYC.float |> x -> PYNP.array(x, dtype = "float32") _actions = action_reward_term[1] |> Array .|> PYC.float |> x -> PYNP.array(x, dtype = "float32") _rewards = action_reward_term[2] |> Array .|> PYC.float |> x -> PYNP.array(x, dtype = "float32") _terminals = action_reward_term[3] |> Array .|> PYC.float |> x -> PYNP.array(x, dtype = "float32") ## create dataset for RLOffline mdp_dataset = PYDT.MDPDataset( observations = _observations, actions = _actions, rewards = _rewards, terminals = _terminals, ) ## save params agent.model[:mdp_dataset] = mdp_dataset agent.model[:np_observations] = _observations agent.model[:np_actions] = _actions agent.model[:np_rewards] = _rewards return mdp_dataset end function checkheaders(agent::DiscreteRLOffline, df) o_header = agent.model[:o_header] a_header = agent.model[:a_header] r_header = agent.model[:r_header] dfnames = names(df) [@assert header in dfnames "\"$header\" is not in data header" for header in vcat(o_header, a_header, r_header)] end function fit!(agent::DiscreteRLOffline, df::DataFrame, action_reward_term::Vector)::Nothing # check if headers exist #checkheaders(agent::DiscreteRLOffline, df) # create mdp data nrow, ncol = size(df) mdp_dataset = createmdpdata!(agent, df,action_reward_term) ## prepare algorithm runtime_args = agent.model[:runtime_args] logging = agent.model[:save_metrics] impl_args = copy(agent.model[:impl_args]) rlagent = agent.model[:rlagent] py_rlagent = getproperty(rl_dict[rlagent],rlagent) pyrlobj = py_rlagent(;impl_args...) pyrlobj.fit(mdp_dataset; save_metrics = logging, runtime_args... ) ## save rl to model dictionary agent.model[:rlobjtrained] = pyrlobj agent.model[:nrow] = nrow agent.model[:ncol] = ncol ## save model to file if agent.model[:save_model] == true path = pkgdir(AutoOfflineRL) agentname = agent.model[:name] tag = agent.model[:tag] fnmodel = "$path/model/$(agentname)_$(tag)_model.pt" fnpolicy = "$path/model/$(agentname)_$(tag)_policy.pt" pyrlobj.save_model(fnmodel) pyrlobj.save_policy(fnpolicy) end return nothing end function transform!(agent::DiscreteRLOffline,df::DataFrame=DataFrame())::Vector pyrlobj = agent.model[:rlobjtrained] #o_header = agent.model[:o_header] observations = df |> Array .|> PYC.float |> x -> PYNP.array(x, dtype = "float32") res = map(observations) do obs action = pyrlobj.predict(obs) value = pyrlobj.predict_value([obs],action) action = PYC.pyconvert.(Float64,action) value = PYC.pyconvert.(Float64,value) obs = PYC.pyconvert.(Float64,obs) (;obs,action,value) end return res end function prp_fit_transform(pipe::Machine, instances::DataFrame,actrewterm::Vector) machines = pipe.model[:machines] machine_args = pipe.model[:machine_args] current_instances = instances trlength = length(machines) for t_index in 1:(trlength - 1) machine = createmachine(machines[t_index], machine_args) fit!(machine, current_instances, actrewterm) current_instances = transform!(machine, current_instances) end return current_instances end function driver() path = pkgdir(AutoOfflineRL) dataset = "$path/data/smalldata.parquet" df = Parquet.read_parquet(dataset) |> DataFrame |> dropmissing df_input = df[:, ["day", "hour", "minute", "dow", "metric1", "metric2", "metric3", "metric4"]] reward = df[:,["reward"]] |> deepcopy |> DataFrame action = df[:,["action"]] |> deepcopy |> DataFrame action_reward = DataFrame[action, reward] agentname="NFQ" agent = DiscreteRLOffline(agentname) #fit_transform!(agent,df_input,action_reward) end function traintesteval(agent::DiscreteRLOffline,mdp_dataset::Py) runtime_args = agent.model[:runtime_args] logging = agent.model[:save_metrics] impl_args = copy(agent.model[:impl_args]) rlagent = agent.model[:rlagent] py_rlagent = getproperty(rl_dict[rlagent],rlagent) pyrlobj = py_rlagent(;impl_args...) py_train_test_split = metric_dict["train_test_split"] trainepisodes,testepisodes = py_train_test_split(mdp_dataset) td_error_scorer = PYMT.td_error_scorer discrete_action_match_scorer = PYMT.discrete_action_match_scorer runconfig = Dict(:scorers=>Dict("td_error"=>td_error_scorer)) #runconfig = Dict(:scorers=>Dict("metric"=>discrete_action_match_scorer)) score=pyrlobj.fit(trainepisodes; eval_episodes=testepisodes, runtime_args...,runconfig...) vals = pyconvert(Array,score) mvals = [v[2]["td_error"] for v in vals] |> Statistics.mean #mvals = [v[2]["metric"] for v in vals] |> Statistics.mean return mvals end function crossvalidateRL(pp::Machine, dfobs::DataFrame, actrewterm::Vector; cv=3) pipe = deepcopy(pp) features = deepcopy(dfobs) machines = pipe.model[:machines] agent = machines[end] df_input = prp_fit_transform(pipe,features,actrewterm) mdp_dataset = createmdpdata!(agent,df_input,actrewterm) scores= [traintesteval(agent,mdp_dataset) for i in 1:cv] return Statistics.mean(scores) #pyskcrossvalidate = metric_dict["cross_validate"] #td_error_scorer = metric_dict["td_error_scorer"] #average_value_estimation_scorer = metric_dict["average_value_estimation_scorer"] #runconfig = Dict(:scoring=>Dict("td_error"=>td_error_scorer, # "value_scale"=>average_value_estimation_scorer), # :fit_params=>Dict("n_epochs"=>1)) #scores = pyskcrossvalidate(pyrlobj,mdp_dataset; runconfig...) #return scores end end
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
2098
module TestOfflineRL using AutoOfflineRL using Test using DataFrames using PythonCall using Parquet const PYC=PythonCall @testset "Load Agents with Default Params" begin for agentid in keys(AutoOfflineRL.OfflineRLs.rl_dict) @info "loading $agentid default params" rlagent = DiscreteRLOffline(agentid) @test typeof(rlagent) <: AutoOfflineRL.Learner end end @testset "Load Agents with Param Args" begin println() for agentid in keys(AutoOfflineRL.OfflineRLs.rl_dict) @info "loading $agentid with customized params" rlagent = DiscreteRLOffline(agentid, Dict(:name=>agentid, :iterations=>10000, :epochs=>100) ) @test typeof(rlagent) <: AutoOfflineRL.Learner end end @testset "Test Exceptions" begin @test_throws ErrorException DiscreteRLOffline("dummy") end @testset "Test Agent fit!/transform Runs" begin println() path = pkgdir(AutoOfflineRL) dataset = "$path/data/smalldata.parquet" df = Parquet.read_parquet(dataset) |> DataFrame |> dropmissing srow,_ = size(df) df_input = df[:, ["day", "hour", "minute", "dow", "sensor1", "sensor2", "sensor3"]] reward = df[:,["reward"]] |> deepcopy |> DataFrame action = df[:,["action"]] |> deepcopy |> DataFrame _terminals = zeros(Int,srow) _terminals[collect(100:1000:9000)] .= 1 _terminals[end] = 1 dterminal = DataFrame(terminal=_terminals) action_reward_terminal = DataFrame[action, reward, dterminal] for agentid in keys(AutoOfflineRL.OfflineRLs.rl_dict) @info "training $agentid" agent = DiscreteRLOffline(agentid; save_model=false,runtime_args=Dict(:n_epochs=>1,:verbose=>false, :show_progress=>true)) o_header = agent.model[:o_header] fit!(agent,df_input,action_reward_terminal) @test agent.model[:rlobjtrained] !== PYC.PyNULL @info "transform $agentid" adf = df_input[1:2,:] if agentid != "DiscreteBC" res = AutoOfflineRL.transform!(agent,adf) @test typeof(res[1]) .== NamedTuple{(:obs,:action, :value), Tuple{Vector{Float64},Vector{Float64}, Vector{Float64}}} end end end end
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
837
using Documenter, AutoMLPipeline makedocs( source = "src", build = "build", modules = [AutoMLPipeline], clean = true, sitename = "AutoMLPipeline Documentation", doctest = false, pages = Any[ "HOME" => "index.md", "Tutorial" => Any[ "tutorial/pipeline.md", "tutorial/preprocessing.md", "tutorial/learning.md", "tutorial/extending.md" ], "Manual" => Any[ "Pipeline" => "man/pipeline.md", "Preprocessors" => "man/preprocessors.md", "Learners" => "man/learners.md", "Meta-Ensembles" => "man/metaensembles.md" ], "Library" => Any[ "Types and Functions" => "lib/typesfunctions.md" ] ], format = Documenter.HTML( prettyurls = get(ENV, "CI", nothing) == "true" ) ) deploydocs( repo = "github.com/IBM/AutoMLPipeline.jl.git", )
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
177
import AMLPipelineBase include(joinpath(pkgdir(AMLPipelineBase), "test", "runtests.jl")) import AutoMLPipeline include(joinpath(pkgdir(AutoMLPipeline), "test", "runtests.jl"))
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
395
using PackageCompiler create_sysimage(["AMLPipelineBase","DataFrames","StatsBase", "ArgParse","AutoMLPipeline","CSV","Dates","Distributed", "Random","ArgParse","Test","Distributed","PythonCall", "Statistics","Serialization","StatsBase","Test"], sysimage_path="automl.so", precompile_execution_file="automl_precompile.jl")
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
3316
# make sure local environment is activated using Pkg Pkg.activate(".") # Symbolic Pipeline Composition # For parallel search using AutoMLPipeline using Distributed using DataFrames # Add workers nprocs() ==1 && addprocs(exeflags=["--project=$(Base.active_project())"]) workers() # disable warnings @everywhere import PythonCall @everywhere const PYC=PythonCall @everywhere warnings = PYC.pyimport("warnings") @everywhere warnings.filterwarnings("ignore") @sync @everywhere using AutoMLPipeline @sync @everywhere using DataFrames # get data begin data = getprofb() X = data[:,2:end] Y = data[:,1] |> Vector end #### feature selectors catf = CatFeatureSelector(); numf = NumFeatureSelector(); # hot-bit encoder ohe = OneHotEncoder(); #### feature scalers rb = SKPreprocessor("RobustScaler"); pt = SKPreprocessor("PowerTransformer"); mx = SKPreprocessor("MinMaxScaler"); std = SKPreprocessor("StandardScaler"); norm = SKPreprocessor("Normalizer"); #### feature extractors pca = SKPreprocessor("PCA", Dict(:autocomponent => true)); ica = SKPreprocessor("FastICA", Dict(:autocomponent => true)); fa = SKPreprocessor("FactorAnalysis", Dict(:autocomponent => true)); #### Learners rf = SKLearner("RandomForestClassifier", Dict(:impl_args => Dict(:n_estimators => 10))); gb = SKLearner("GradientBoostingClassifier"); lsvc = SKLearner("LinearSVC"); mlp = SKLearner("MLPClassifier"); stack = StackEnsemble(); rbfsvc = SKLearner("SVC"); ada = SKLearner("AdaBoostClassifier"); vote = VoteEnsemble(); best = BestLearner(); tree = PrunedTree(); sgd = SKLearner("SGDClassifier"); noop = Identity(Dict(:name => "Noop")); pipe = @pipeline catf; pred = fit_transform!(pipe, X, Y) pipe = @pipeline catf |> ohe; pred = fit_transform!(pipe, X, Y) pipe = @pipeline numf; pred = fit_transform!(pipe, X, Y) pipe = @pipeline numf |> norm; pred = fit_transform!(pipe, X, Y) pipe = @pipeline (numf |> norm) + (catf |> ohe); pred = fit_transform!(pipe, X, Y) pipe = @pipeline (numf |> norm) + (catf |> ohe) |> rf; pred = fit_transform!(pipe, X, Y) crossvalidate(pipe,X,Y) pipe = @pipeline (numf |> norm) + (catf |> ohe) |> sgd; crossvalidate(pipe,X,Y) pipe = @pipeline (numf |> norm |> pca) + (numf |> rb |> pca) + (catf |> ohe) |> tree; crossvalidate(pipe,X,Y) # Parallel Search for Datamining Optimal Pipelines function prpsearch() learners = [rf,ada,sgd,tree,rbfsvc,lsvc,gb]; scalers = [rb,pt,norm,std,mx,noop]; extractors = [pca,ica,fa,noop]; dftable = @sync @distributed (vcat) for lr in learners @distributed (vcat) for sc in scalers @distributed (vcat) for xt in extractors pipe = @pipeline (catf |> ohe) + (numf |> sc |> xt) |> lr scn = sc.name[1:end - 4]; xtn = xt.name[1:end - 4]; lrn = lr.name[1:end - 4] pname = "$scn |> $xtn |> $lrn" ptime = @elapsed begin mean, sd, kfold, _ = crossvalidate(pipe, X, Y, "accuracy_score", 3) end DataFrame(pipeline=pname, mean=mean, sd=sd, time=ptime, folds=kfold) end end end sort!(dftable, :mean, rev=true); dftable end runtime = @elapsed begin df = prpsearch() end; serialtime = df.time |> sum; (serialtime = "$(round(serialtime / 60.0)) minutes", paralleltime = "$(round(runtime)) seconds") # pipeline performances @show df
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
1114
using PrecompileTools: @setup_workload, @compile_workload using Distributed using DataFrames using AutoMLPipeline using CSV using K8sClusterManagers addprocs(K8sClusterManagers.K8sClusterManager(2; cpu=1, namespace="argo",memory="10000Mi", pending_timeout=300); exeflags=["--project=$(Base.active_project())"]) #workers=5 #nprocs() == 1 && addprocs(workers; exeflags=["--project=$(Base.active_project())"]) #addprocs(K8sClusterManager(10, cpu=1, memory="300Mi", pending_timeout=300); exeflags="--project") #nprocs() == 1 && addprocs(; exeflags = "--project") @setup_workload begin @compile_workload begin include("twoblocks.jl") end end @everywhere include("twoblocks.jl") @everywhere using Main.TwoBlocksPipeline dataset = getiris() X = dataset[:,1:4] Y = dataset[:,5] |> collect X = dataset[:,2:end-1] #dataset=CSV.read("environment_data.csv",DataFrame) #X = select(dataset, Not([:state,:time])) #Y = dataset.state results=TwoBlocksPipeline.twoblockspipelinesearch(X,Y) # println(results) println("best pipeline is: ", results[1,1],", with mean ± sd: ",results[1,2], " ± ",results[1,3])
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
926
using PrecompileTools: @setup_workload, @compile_workload using Distributed using DataFrames using AutoMLPipeline using CSV workers=5 nprocs() == 1 && addprocs(workers; exeflags=["--project=$(Base.active_project())"]) #addprocs(K8sClusterManager(10, cpu=1, memory="300Mi", pending_timeout=300); exeflags="--project") #nprocs() == 1 && addprocs(; exeflags = "--project") @setup_workload begin @compile_workload begin include("twoblocks.jl") end end @everywhere include("twoblocks.jl") @everywhere using Main.TwoBlocksPipeline dataset = getiris() X = dataset[:,1:4] Y = dataset[:,5] |> collect X = dataset[:,2:end-1] #dataset=CSV.read("environment_data.csv",DataFrame) #X = select(dataset, Not([:state,:time])) #Y = dataset.state results=TwoBlocksPipeline.twoblockspipelinesearch(X,Y) # println(results) println("best pipeline is: ", results[1,1],", with mean ± sd: ",results[1,2], " ± ",results[1,3])
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
925
using PrecompileTools: @setup_workload, @compile_workload using Distributed using DataFrames using AutoMLPipeline using CSV workers=5 nprocs() == 1 && addprocs(workers; exeflags=["--project=$(Base.active_project())"]) #addprocs(K8sClusterManager(10, cpu=1, memory="300Mi", pending_timeout=300); exeflags="--project") #nprocs() == 1 && addprocs(; exeflags = "--project") @setup_workload begin @compile_workload begin include("twoblocks.jl") end end @everywhere include("twoblocks.jl") @everywhere using Main.TwoBlocksPipeline dataset = getiris() X = dataset[:,1:4] Y = dataset[:,5] |> collect X = dataset[:,2:end-1] #dataset=CSV.read("environment_data.csv",DataFrame) #X = select(dataset, Not([:state,:time])) #Y = dataset.state results=TwoBlocksPipeline.twoblockspipelinesearch(X,Y) # println(results) println("best pipeline is: ", results[1,1],", with mean ± sd: ",results[1,2], " ± ",results[1,3])
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
2947
using Distributed using ArgParse using CSV using DataFrames using AutoMLPipeline function parse_commandline() s = ArgParseSettings() @add_arg_table! s begin "--pipeline_complexity", "-c" help = "pipeline complexity" arg_type = String default = "low" "--prediction_type", "-t" help = "classification or regression" arg_type = String default = "classification" "--output_file", "-o" help = "output location" arg_type = String default = "NONE" "--nfolds", "-f" help = "number of crossvalidation folds" arg_type = Int64 default = 3 "--workers", "-w" help = "number of workers" arg_type = Int64 default = 5 "--no_save" help = "save model" action = :store_true "csvfile" help = "input csv file" required = true #default="iris.csv" end return parse_args(s;as_symbols=true) end #function extract_args() # parsed_args = parse_commandline() # println("Parsed args:") # for (arg,val) in parsed_args # println(" $arg => $val") # end # fname = parsed_args[:input_csvfile] # data = CSV.read(fname,DataFrame) # X = data[:,1:(end-1)] # Y = data[:,end] |> collect # #return(workers,X,Y) # return (;parsed_args...) #end # #const (csv,X,Y)=extract_args() const _cliargs = (;parse_commandline()...) const _workers = _cliargs[:workers] nprocs() == 1 && addprocs(_workers;exeflags=["--project=$(Base.active_project())"]) if _cliargs[:prediction_type] == "classification" @everywhere include("pipelineblocksclassification.jl") @everywhere using .PipelineBlocksClassification:twoblockspipelinesearch @everywhere using .PipelineBlocksClassification:oneblockpipelinesearch elseif _cliargs[:prediction_type] == "regression" @everywhere include("pipelineblocksregression.jl") @everywhere using .PipelineBlocksRegression:twoblockspipelinesearch @everywhere using .PipelineBlocksRegression:oneblockpipelinesearch else error("cli argument error for prediction type") end function mymain() fname = _cliargs[:csvfile] data = CSV.read(fname,DataFrame) X = data[:,1:(end-1)] Y = data[:,end] |> collect best = if _cliargs[:pipeline_complexity] == "low" oneblockpipelinesearch(X,Y;nfolds=_cliargs[:nfolds]) else twoblockspipelinesearch(X,Y;nfolds=_cliargs[:nfolds]) end r(x)=round(x,digits=2) println("best model: $(best[1])") println(" mean ± sd: $(r(best[2])) ± $(r(best[3]))") ofile = _cliargs[:output_file] if ofile != "NONE" stfile = open(ofile,"w") println(stfile,"best model: $(best[1])") println(stfile," mean ± sd: $(r(best[2])) ± $(r(best[3]))") close(stfile) end return best end mymain()
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
6264
module PipelineBlocksClassification export twoblockspipelinesearch, oneblockpipelinesearch using Distributed using AutoMLPipeline using DataFrames using DataFrames:DataFrame using AutoMLPipeline: score using Random # disable truncation of dataframes columns import Base.show show(df::AbstractDataFrame) = show(df,truncate=0) show(io::IO,df::AbstractDataFrame) = show(io,df;truncate=0) # define scalers const rb = SKPreprocessor("RobustScaler",Dict(:name=>"rb")) const pt = SKPreprocessor("PowerTransformer",Dict(:name=>"pt")) const norm = SKPreprocessor("Normalizer",Dict(:name=>"norm")) const mx = SKPreprocessor("MinMaxScaler",Dict(:name=>"mx")) const std = SKPreprocessor("StandardScaler",Dict(:name=>"std")) # define extractors const pca = SKPreprocessor("PCA",Dict(:name=>"pca")) const fa = SKPreprocessor("FactorAnalysis",Dict(:name=>"fa")) const ica = SKPreprocessor("FastICA",Dict(:name=>"ica")) # define learners const rf = SKLearner("RandomForestClassifier",Dict(:name => "rf")) const ada = SKLearner("AdaBoostClassifier",Dict(:name => "ada")) const gb = SKLearner("GradientBoostingClassifier",Dict(:name => "gb")) const lsvc = SKLearner("LinearSVC",Dict(:name => "lsvc")) const rbfsvc = SKLearner("SVC",Dict(:name => "rbfsvc")) const dt = SKLearner("DecisionTreeClassifier",Dict(:name =>"dt")) const et = SKLearner("ExtraTreesClassifier",Dict(:name =>"et")) const ridge = SKLearner("RidgeClassifier",Dict(:name =>"ridge")) const sgd = SKLearner("SGDClassifier",Dict(:name =>"sgd")) #const gp = SKLearner("GaussianProcessClassifier",Dict(:name =>"gp")) const bg = SKLearner("BaggingClassifier",Dict(:name =>"bg")) const pa = SKLearner("PassiveAggressiveClassifier",Dict(:name =>"pa")) # preprocessing const noop = Identity(Dict(:name =>"noop")) const ohe = OneHotEncoder(Dict(:name=>"ohe")) const catf = CatFeatureSelector(Dict(:name=>"catf")) const numf = NumFeatureSelector(Dict(:name=>"numf")) const vscalers = [rb,pt,norm,mx,std,noop] const vextractors = [pca,fa,ica,noop] const vlearners = [rf,gb,lsvc,rbfsvc,ada,dt,et,ridge,sgd,bg,pa] const learnerdict = Dict("rf"=>rf,"gb"=>gb,"lsvc"=>lsvc,"rbfsvc"=>rbfsvc,"ada"=>ada, "dt"=>dt,"et"=>et,"ridge"=>ridge, "sgd"=>sgd,"bg"=>bg,"pa"=>pa ) function oneblock_pipeline_factory(scalers,extractors,learners) results = @distributed (vcat) for lr in learners @distributed (vcat) for xt in extractors @distributed (vcat) for sc in scalers # baseline preprocessing prep = @pipeline ((catf |> ohe) + numf) # one-block prp expx = @pipeline prep |> (sc |> xt) |> lr scn = sc.name[1:end - 4];xtn = xt.name[1:end - 4]; lrn = lr.name[1:end - 4] pname = "($scn |> $xtn) |> $lrn" DataFrame(Description=pname,Pipeline=expx) end end end return results end function evaluate_pipeline(dfpipelines,X,Y;folds=3) res=@distributed (vcat) for prow in eachrow(dfpipelines) perf = crossvalidate(prow.Pipeline,X,Y,"balanced_accuracy_score";nfolds=folds) DataFrame(;Description=prow.Description,mean=perf.mean,sd=perf.std,prow.Pipeline) end return res end function twoblock_pipeline_factory(scalers,extractors,learners) results = @distributed (vcat) for lr in learners @distributed (vcat) for xt1 in extractors @distributed (vcat) for xt2 in extractors @distributed (vcat) for sc1 in scalers @distributed (vcat) for sc2 in scalers prep = @pipeline ((catf |> ohe) + numf) expx = @pipeline prep |> ((sc1 |> xt1) + (sc2 |> xt2)) |> lr scn1 = sc1.name[1:end - 4];xtn1 = xt1.name[1:end - 4]; scn2 = sc2.name[1:end - 4];xtn2 = xt2.name[1:end - 4]; lrn = lr.name[1:end - 4] pname = "($scn1 |> $xtn1) + ($scn2 |> $xtn2) |> $lrn" DataFrame(Description=pname,Pipeline=expx) end end end end end return results end function model_selection_pipeline(learners) results = @distributed (vcat) for lr in learners prep = @pipeline ((catf |> ohe) + numf) expx = @pipeline prep |> (rb |> pca) |> lr pname = "(rb |> pca) |> $(lr.name[1:end-4])" DataFrame(Description=pname,Pipeline=expx) end return results end function lname(n::Learner) n.name[1:end-4] end function twoblockspipelinesearch(X::DataFrame,Y::Vector;scalers=vscalers,extractors=vextractors,learners=vlearners,nfolds=3) dfpipes = model_selection_pipeline(vlearners) # find the best model by evaluating the models modelsperf = evaluate_pipeline(dfpipes,X,Y;folds=nfolds) sort!(modelsperf,:mean, rev = true) # get the string name of the top model bestm = filter(x->occursin(x,modelsperf.Description[1]),lname.(vlearners))[1] # get corresponding model object bestmodel = learnerdict[bestm] # use the best model to generate pipeline search dfp = twoblock_pipeline_factory(vscalers,vextractors,[bestmodel]) # evaluate the pipeline bestp=evaluate_pipeline(dfp,X,Y;folds=nfolds) sort!(bestp,:mean, rev = true) show(bestp;allrows=false,truncate=1,allcols=false) println() optmodel = bestp[1,:] return optmodel end function oneblockpipelinesearch(X::DataFrame,Y::Vector;scalers=vscalers,extractors=vextractors,learners=vlearners,nfolds=3) dfpipes = model_selection_pipeline(vlearners) # find the best model by evaluating the models modelsperf = evaluate_pipeline(dfpipes,X,Y;folds=nfolds) sort!(modelsperf,:mean, rev = true) # get the string name of the top model bestm = filter(x->occursin(x,modelsperf.Description[1]),lname.(vlearners))[1] # get corresponding model object bestmodel = learnerdict[bestm] # use the best model to generate pipeline search dfp = oneblock_pipeline_factory(vscalers,vextractors,[bestmodel]) # evaluate the pipeline bestp=evaluate_pipeline(dfp,X,Y;folds=nfolds) sort!(bestp,:mean, rev = true) show(bestp;allrows=false,truncate=1,allcols=false) println() optmodel = bestp[1,:] return optmodel end end
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
6229
module PipelineBlocksRegression export twoblockspipelinesearch, oneblockpipelinesearch using Distributed using AutoMLPipeline using DataFrames using DataFrames:DataFrame using AutoMLPipeline: score using Random # disable truncation of dataframes columns import Base.show show(df::AbstractDataFrame) = show(df,truncate=0) show(io::IO,df::AbstractDataFrame) = show(io,df;truncate=0) # define scalers const rb = SKPreprocessor("RobustScaler",Dict(:name=>"rb")) const pt = SKPreprocessor("PowerTransformer",Dict(:name=>"pt")) const norm = SKPreprocessor("Normalizer",Dict(:name=>"norm")) const mx = SKPreprocessor("MinMaxScaler",Dict(:name=>"mx")) const std = SKPreprocessor("StandardScaler",Dict(:name=>"std")) # define extractors const pca = SKPreprocessor("PCA",Dict(:name=>"pca")) const fa = SKPreprocessor("FactorAnalysis",Dict(:name=>"fa")) const ica = SKPreprocessor("FastICA",Dict(:name=>"ica")) # define learners const rf = SKLearner("RandomForestRegressor",Dict(:name => "rf")) const ada = SKLearner("AdaBoostRegressor",Dict(:name => "ada")) const gb = SKLearner("GradientBoostingRegressor",Dict(:name => "gb")) const ridge = SKLearner("Ridge",Dict(:name => "ridge")) const svr = SKLearner("SVR",Dict(:name => "svr")) const dt = SKLearner("DecisionTreeRegressor",Dict(:name =>"dt")) const lasso = SKLearner("Lasso",Dict(:name =>"lasso")) const enet = SKLearner("ElasticNet",Dict(:name =>"enet")) const ard = SKLearner("ARDRegression",Dict(:name =>"ard")) const lars = SKLearner("Lars",Dict(:name =>"lars")) const sgd = SKLearner("SGDRegressor",Dict(:name =>"sgd")) const kridge = SKLearner("KernelRidge",Dict(:name =>"kridge")) # preprocessing const noop = Identity(Dict(:name =>"noop")) const ohe = OneHotEncoder(Dict(:name=>"ohe")) const catf = CatFeatureSelector(Dict(:name=>"catf")) const numf = NumFeatureSelector(Dict(:name=>"numf")) const vscalers = [rb,pt,norm,mx,std,noop] const vextractors = [pca,fa,ica,noop] const vlearners = [rf,gb,ridge,svr,ada,dt,lasso,enet,ard,lars,sgd,kridge] const learnerdict = Dict("rf"=>rf,"gb"=>gb,"ridge"=>ridge,"svr"=>svr, "ada"=>ada,"dt"=>dt,"lasso"=>lasso,"enet"=>enet,"ard"=>ard, "lars"=>lars,"sgd"=>sgd,"kridge"=>kridge ) function oneblock_pipeline_factory(scalers,extractors,learners) results = @distributed (vcat) for lr in learners @distributed (vcat) for xt in extractors @distributed (vcat) for sc in scalers # baseline preprocessing prep = @pipeline ((catf |> ohe) + numf) # one-block prp expx = @pipeline prep |> (sc |> xt) |> lr scn = sc.name[1:end - 4];xtn = xt.name[1:end - 4]; lrn = lr.name[1:end - 4] pname = "($scn |> $xtn) |> $lrn" DataFrame(Description=pname,Pipeline=expx) end end end return results end function evaluate_pipeline(dfpipelines,X,Y;folds=3) res=@distributed (vcat) for prow in eachrow(dfpipelines) perf = crossvalidate(prow.Pipeline,X,Y,"mean_squared_error";nfolds=folds) DataFrame(;Description=prow.Description,mean=perf.mean,sd=perf.std,prow.Pipeline) end return res end function twoblock_pipeline_factory(scalers,extractors,learners) results = @distributed (vcat) for lr in learners @distributed (vcat) for xt1 in extractors @distributed (vcat) for xt2 in extractors @distributed (vcat) for sc1 in scalers @distributed (vcat) for sc2 in scalers prep = @pipeline ((catf |> ohe) + numf) expx = @pipeline prep |> ((sc1 |> xt1) + (sc2 |> xt2)) |> lr scn1 = sc1.name[1:end - 4];xtn1 = xt1.name[1:end - 4]; scn2 = sc2.name[1:end - 4];xtn2 = xt2.name[1:end - 4]; lrn = lr.name[1:end - 4] pname = "($scn1 |> $xtn1) + ($scn2 |> $xtn2) |> $lrn" DataFrame(Description=pname,Pipeline=expx) end end end end end return results end function model_selection_pipeline(learners) results = @distributed (vcat) for lr in learners prep = @pipeline ((catf |> ohe) + numf) expx = @pipeline prep |> (rb |> pca) |> lr pname = "(rb |> pca) |> $(lr.name[1:end-4])" DataFrame(Description=pname,Pipeline=expx) end return results end function lname(n::Learner) n.name[1:end-4] end function twoblockspipelinesearch(X::DataFrame,Y::Vector;scalers=vscalers,extractors=vextractors,learners=vlearners,nfolds=3) dfpipes = model_selection_pipeline(vlearners) # find the best model by evaluating the models modelsperf = evaluate_pipeline(dfpipes,X,Y;folds=nfolds) sort!(modelsperf,:mean, rev = false) # get the string name of the top model bestm = filter(x->occursin(x,modelsperf.Description[1]),lname.(vlearners))[1] # get corresponding model object bestmodel = learnerdict[bestm] # use the best model to generate pipeline search dfp = twoblock_pipeline_factory(vscalers,vextractors,[bestmodel]) # evaluate the pipeline bestp=evaluate_pipeline(dfp,X,Y;folds=nfolds) sort!(bestp,:mean, rev = false) show(bestp;allrows=false,truncate=1,allcols=false) println() optmodel = bestp[1,:] return optmodel end function oneblockpipelinesearch(X::DataFrame,Y::Vector;scalers=vscalers,extractors=vextractors,learners=vlearners,nfolds=3) dfpipes = model_selection_pipeline(vlearners) # find the best model by evaluating the models modelsperf = evaluate_pipeline(dfpipes,X,Y;folds=nfolds) sort!(modelsperf,:mean, rev = false) # get the string name of the top model bestm = filter(x->occursin(x,modelsperf.Description[1]),lname.(vlearners))[1] # get corresponding model object bestmodel = learnerdict[bestm] # use the best model to generate pipeline search dfp = oneblock_pipeline_factory(vscalers,vextractors,[bestmodel]) # evaluate the pipeline bestp=evaluate_pipeline(dfp,X,Y;folds=nfolds) sort!(bestp,:mean, rev = false) show(bestp;allrows=false,truncate=1,allcols=false) println() optmodel = bestp[1,:] return optmodel end end
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
157
import AMLPipelineBase include(joinpath(pkgdir(AMLPipelineBase), "test", "runtests.jl")) import TSML include(joinpath(pkgdir(TSML), "test", "runtests.jl"))
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
378
import SimpleContainerGenerator pkgs = ["ArgParse","AutoMLPipeline","CSV","DataFrames","Distributed","Random"] julia_version = "1.10.2" SimpleContainerGenerator.create_dockerfile(pkgs; output_directory=pwd(), julia_version = julia_version) run(`nerdctl build -t ppalmes/automlpipeline .`)
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
320
using PackageCompiler create_sysimage(["AMLPipelineBase","DataFrames","StatsBase", "CSV","Dates","Distributed","TSML", "Random","ArgParse","Test", "Statistics","Serialization"], sysimage_path="amlp.so", precompile_execution_file="precompile.jl")
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
4886
module TwoBlocksPipeline export twoblockspipelinesearch using Distributed #nprocs() == 1 && addprocs(; exeflags = "--project") #nprocs() == 1 && addprocs() using AutoMLPipeline using DataFrames using DataFrames:DataFrame using AutoMLPipeline: score using Random # disable truncation of dataframes columns import Base.show show(df::AbstractDataFrame) = show(df,truncate=0) show(io::IO,df::AbstractDataFrame) = show(io,df;truncate=0) # define scalers const rb = SKPreprocessor("RobustScaler",Dict(:name=>"rb")) const pt = SKPreprocessor("PowerTransformer",Dict(:name=>"pt")) const norm = SKPreprocessor("Normalizer",Dict(:name=>"norm")) const mx = SKPreprocessor("MinMaxScaler",Dict(:name=>"mx")) const std = SKPreprocessor("StandardScaler",Dict(:name=>"std")) # define extractors const pca = SKPreprocessor("PCA",Dict(:name=>"pca")) const fa = SKPreprocessor("FactorAnalysis",Dict(:name=>"fa")) const ica = SKPreprocessor("FastICA",Dict(:name=>"ica")) # define learners const rf = SKLearner("RandomForestClassifier",Dict(:name => "rf")) const ada = SKLearner("AdaBoostClassifier",Dict(:name => "ada")) const gb = SKLearner("GradientBoostingClassifier",Dict(:name => "gb")) const lsvc = SKLearner("LinearSVC",Dict(:name => "lsvc")) const rbfsvc = SKLearner("SVC",Dict(:name => "rbfsvc")) const dt = SKLearner("DecisionTreeClassifier",Dict(:name =>"dt")) # preprocessing const noop = Identity(Dict(:name =>"noop")) const ohe = OneHotEncoder(Dict(:name=>"ohe")) const catf = CatFeatureSelector(Dict(:name=>"catf")) const numf = NumFeatureSelector(Dict(:name=>"numf")) const vscalers = [rb,pt,norm,mx,std,noop] const vextractors = [pca,fa,ica,noop] const vlearners = [rf,gb,lsvc,rbfsvc,ada,dt] const learnerdict = Dict("rf"=>rf,"gb"=>gb,"lsvc"=>lsvc,"rbfsvc"=>rbfsvc,"ada"=>ada,"dt"=>dt) function oneblock_pipeline_factory(scalers,extractors,learners) results = @distributed (vcat) for lr in learners @distributed (vcat) for xt in extractors @distributed (vcat) for sc in scalers # baseline preprocessing prep = @pipeline ((catf |> ohe) + numf) # one-block prp expx = @pipeline prep |> (sc |> xt) |> lr scn = sc.name[1:end - 4];xtn = xt.name[1:end - 4]; lrn = lr.name[1:end - 4] pname = "($scn |> $xtn) |> $lrn" DataFrame(Description=pname,Pipeline=expx) end end end return results end function evaluate_pipeline(dfpipelines,X,Y;folds=3) res=@distributed (vcat) for prow in eachrow(dfpipelines) perf = crossvalidate(prow.Pipeline,X,Y,"balanced_accuracy_score";nfolds=folds) DataFrame(;Description=prow.Description,mean=perf.mean,sd=perf.std,prow.Pipeline) end return res end function twoblock_pipeline_factory(scalers,extractors,learners) results = @distributed (vcat) for lr in learners @distributed (vcat) for xt1 in extractors @distributed (vcat) for xt2 in extractors @distributed (vcat) for sc1 in scalers @distributed (vcat) for sc2 in scalers prep = @pipeline ((catf |> ohe) + numf) expx = @pipeline prep |> ((sc1 |> xt1) + (sc2 |> xt2)) |> lr scn1 = sc1.name[1:end - 4];xtn1 = xt1.name[1:end - 4]; scn2 = sc2.name[1:end - 4];xtn2 = xt2.name[1:end - 4]; lrn = lr.name[1:end - 4] pname = "($scn1 |> $xtn1) + ($scn2 |> $xtn2) |> $lrn" DataFrame(Description=pname,Pipeline=expx) end end end end end return results end function model_selection_pipeline(learners) results = @distributed (vcat) for lr in learners prep = @pipeline ((catf |> ohe) + numf) expx = @pipeline prep |> (rb |> pca) |> lr pname = "(rb |> pca) |> $(lr.name[1:end-4])" DataFrame(Description=pname,Pipeline=expx) end return results end function lname(n::Learner) n.name[1:end-4] end function twoblockspipelinesearch(X::DataFrame,Y::Vector;scalers=vscalers,extractors=vextractors,learners=vlearners,nfolds=3) dfpipes = model_selection_pipeline(vlearners) # find the best model by evaluating the models modelsperf = evaluate_pipeline(dfpipes,X,Y;folds=nfolds) sort!(modelsperf,:mean, rev = true) # get the string name of the top model bestm = filter(x->occursin(x,modelsperf.Description[1]),lname.(vlearners))[1] # get corresponding model object bestmodel = learnerdict[bestm] # use the best model to generate pipeline search dfp = twoblock_pipeline_factory(vscalers,vextractors,[bestmodel]) # evaluate the pipeline bestp=evaluate_pipeline(dfp,X,Y;folds=nfolds) sort!(bestp,:mean, rev = true) show(bestp;allrows=false,truncate=1,allcols=false) println() optmodel = bestp[1,:] return bestp end end
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
1267
module End2EndAI __precompile__(false) using DataFrames using CSV using ArgParse using Distributed export automlmain workers=5 nprocs() == 1 && addprocs(workers; exeflags=["--project=$(Base.active_project())"]) include("twoblocks.jl") @everywhere include("twoblocks.jl") @everywhere using .TwoBlocksPipeline function parse_commandline() s = ArgParseSettings() @add_arg_table! s begin "--pipeline_level" help = "small, medium, large" arg_type = String default = "small" "--model" help = "small, medium, large" arg_type = String default = "small" "--save" help = "save results" action = :store_true "csvfilename" help = "csv file to process" default = "iris.csv" #required = true end return parse_args(s,as_symbols=true) end function automlmain() parsed_args = parse_commandline() createrunpipeline(parsed_args) end function createrunpipeline(args::Dict) fname = args[:csvfilename] df = CSV.read(fname,DataFrame) X = df[:,1:(end-1)] Y = df[:,end] |> collect results = TwoBlocksPipeline.twoblockspipelinesearch(X,Y) println(results[1:1,:]) end end
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
2834
module ArgumentParsers using Dates using DataFrames using CSV using ArgParse using AutoMLPipeline export automlmain function parse_commandline() s = ArgParseSettings() @add_arg_table! s begin "--aggregate" help = "aggregate interval such as: minutely, hourly, weekly, monthly, Dates.Minute(30),Dates.Hour(2)" arg_type = String default = "hourly" "--dateformat" help = "date and time format" arg_type = String default = "dd/mm/yyyy HH:MM" "--impute" help = "impute with NN" action = :store_true "--mono" help = "normalize monotonic" action = :store_true "--clean" help = "remove outliers" action = :store_true "--stat" help = "get statistics" action = :store_true "--save" help = "save results" action = :store_true "csvfilename" help = "csv file to process" required = true end return parse_args(s,as_symbols=true) end function automlmain() parsed_args = parse_commandline() createrunpipeline(parsed_args) end function createrunpipeline(args::Dict) dateformat = args[:dateformat] fname = args[:csvfilename] csvreader = CSVDateValReader(Dict(:filename=>fname,:dateformat=>dateformat)) csvwriter = CSVDateValWriter() fnameoutput = "" if args[:save] == true name = split(fname,".csv")[1] fnameoutput = name*"_output"*".csv" csvwriter.args[:filename] = fnameoutput end # extract date interval dateintervalstring = args[:aggregate] dateinterval = Dates.Hour(1) if dateintervalstring in keys(DATEINTERVAL) dateinterval = DATEINTERVAL[dateintervalstring] else # parse the string into expression and evaluate # example: "Dates.Hour(1)" or "Dates.Minute(30)" dateinterval = eval(Meta.parse(dateintervalstring)) end commonarg = Dict(:dateformat=>dateformat,:dateinterval=>dateinterval) valgator = DateValgator(commonarg) imputer = DateValNNer(commonarg) mono = Monotonicer() outliernicer = Outliernicer(commonarg) statifier = Statifier(Dict(:processmissing=>true)) transformers = [csvreader,valgator] if args[:impute] == true transformers = [transformers;imputer] end if args[:mono] == true transformers = [transformers;mono] end if args[:clean] == true transformers = [transformers;outliernicer] end if args[:stat] == true transformers = [transformers;statifier] end if args[:save] == true transformers = [transformers;csvwriter] end pipeline = Pipeline(transformers) fit_transform!(pipeline) end end
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
3316
# make sure local environment is activated using Pkg Pkg.activate(".") # Symbolic Pipeline Composition # For parallel search using AutoMLPipeline using Distributed using DataFrames # Add workers nprocs() ==1 && addprocs(exeflags=["--project=$(Base.active_project())"]) workers() # disable warnings @everywhere import PythonCall @everywhere const PYC=PythonCall @everywhere warnings = PYC.pyimport("warnings") @everywhere warnings.filterwarnings("ignore") @sync @everywhere using AutoMLPipeline @sync @everywhere using DataFrames # get data begin data = getprofb() X = data[:,2:end] Y = data[:,1] |> Vector end #### feature selectors catf = CatFeatureSelector(); numf = NumFeatureSelector(); # hot-bit encoder ohe = OneHotEncoder(); #### feature scalers rb = SKPreprocessor("RobustScaler"); pt = SKPreprocessor("PowerTransformer"); mx = SKPreprocessor("MinMaxScaler"); std = SKPreprocessor("StandardScaler"); norm = SKPreprocessor("Normalizer"); #### feature extractors pca = SKPreprocessor("PCA", Dict(:autocomponent => true)); ica = SKPreprocessor("FastICA", Dict(:autocomponent => true)); fa = SKPreprocessor("FactorAnalysis", Dict(:autocomponent => true)); #### Learners rf = SKLearner("RandomForestClassifier", Dict(:impl_args => Dict(:n_estimators => 10))); gb = SKLearner("GradientBoostingClassifier"); lsvc = SKLearner("LinearSVC"); mlp = SKLearner("MLPClassifier"); stack = StackEnsemble(); rbfsvc = SKLearner("SVC"); ada = SKLearner("AdaBoostClassifier"); vote = VoteEnsemble(); best = BestLearner(); tree = PrunedTree(); sgd = SKLearner("SGDClassifier"); noop = Identity(Dict(:name => "Noop")); pipe = @pipeline catf; pred = fit_transform!(pipe, X, Y) pipe = @pipeline catf |> ohe; pred = fit_transform!(pipe, X, Y) pipe = @pipeline numf; pred = fit_transform!(pipe, X, Y) pipe = @pipeline numf |> norm; pred = fit_transform!(pipe, X, Y) pipe = @pipeline (numf |> norm) + (catf |> ohe); pred = fit_transform!(pipe, X, Y) pipe = @pipeline (numf |> norm) + (catf |> ohe) |> rf; pred = fit_transform!(pipe, X, Y) crossvalidate(pipe,X,Y) pipe = @pipeline (numf |> norm) + (catf |> ohe) |> sgd; crossvalidate(pipe,X,Y) pipe = @pipeline (numf |> norm |> pca) + (numf |> rb |> pca) + (catf |> ohe) |> tree; crossvalidate(pipe,X,Y) # Parallel Search for Datamining Optimal Pipelines function prpsearch() learners = [rf,ada,sgd,tree,rbfsvc,lsvc,gb]; scalers = [rb,pt,norm,std,mx,noop]; extractors = [pca,ica,fa,noop]; dftable = @sync @distributed (vcat) for lr in learners @distributed (vcat) for sc in scalers @distributed (vcat) for xt in extractors pipe = @pipeline (catf |> ohe) + (numf |> sc |> xt) |> lr scn = sc.name[1:end - 4]; xtn = xt.name[1:end - 4]; lrn = lr.name[1:end - 4] pname = "$scn |> $xtn |> $lrn" ptime = @elapsed begin mean, sd, kfold, _ = crossvalidate(pipe, X, Y, "accuracy_score", 3) end DataFrame(pipeline=pname, mean=mean, sd=sd, time=ptime, folds=kfold) end end end sort!(dftable, :mean, rev=true); dftable end runtime = @elapsed begin df = prpsearch() end; serialtime = df.time |> sum; (serialtime = "$(round(serialtime / 60.0)) minutes", paralleltime = "$(round(runtime)) seconds") # pipeline performances @show df
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
815
module MyMain using Distributed using DataFrames using AutoMLPipeline using CSV workers=5 nprocs() == 1 && addprocs(workers; exeflags=["--project=$(Base.active_project())"]) #addprocs(K8sClusterManager(10, cpu=1, memory="300Mi", pending_timeout=300); exeflags="--project") #nprocs() == 1 && addprocs(; exeflags = "--project") include("twoblocks.jl") @everywhere include("twoblocks.jl") @everywhere using Main.TwoBlocksPipeline dataset = getiris() X = dataset[:,1:4] Y = dataset[:,5] |> collect X = dataset[:,2:end-1] #dataset=CSV.read("environment_data.csv",DataFrame) #X = select(dataset, Not([:state,:time])) #Y = dataset.state results=TwoBlocksPipeline.twoblockspipelinesearch(X,Y) # println(results) println("best pipeline is: ", results[1,1],", with mean ± sd: ",results[1,2], " ± ",results[1,3]) end
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
4804
module TwoBlocksPipeline export twoblockspipelinesearch using Distributed using AutoMLPipeline using DataFrames using DataFrames:DataFrame using AutoMLPipeline: score using Random # disable truncation of dataframes columns import Base.show show(df::AbstractDataFrame) = show(df,truncate=0) show(io::IO,df::AbstractDataFrame) = show(io,df;truncate=0) # define scalers const rb = SKPreprocessor("RobustScaler",Dict(:name=>"rb")) const pt = SKPreprocessor("PowerTransformer",Dict(:name=>"pt")) const norm = SKPreprocessor("Normalizer",Dict(:name=>"norm")) const mx = SKPreprocessor("MinMaxScaler",Dict(:name=>"mx")) const std = SKPreprocessor("StandardScaler",Dict(:name=>"std")) # define extractors const pca = SKPreprocessor("PCA",Dict(:name=>"pca")) const fa = SKPreprocessor("FactorAnalysis",Dict(:name=>"fa")) const ica = SKPreprocessor("FastICA",Dict(:name=>"ica")) # define learners const rf = SKLearner("RandomForestClassifier",Dict(:name => "rf")) const ada = SKLearner("AdaBoostClassifier",Dict(:name => "ada")) const gb = SKLearner("GradientBoostingClassifier",Dict(:name => "gb")) const lsvc = SKLearner("LinearSVC",Dict(:name => "lsvc")) const rbfsvc = SKLearner("SVC",Dict(:name => "rbfsvc")) const dt = SKLearner("DecisionTreeClassifier",Dict(:name =>"dt")) # preprocessing const noop = Identity(Dict(:name =>"noop")) const ohe = OneHotEncoder(Dict(:name=>"ohe")) const catf = CatFeatureSelector(Dict(:name=>"catf")) const numf = NumFeatureSelector(Dict(:name=>"numf")) const vscalers = [rb,pt,norm,mx,std,noop] const vextractors = [pca,fa,ica,noop] const vlearners = [rf,gb,lsvc,rbfsvc,ada,dt] const learnerdict = Dict("rf"=>rf,"gb"=>gb,"lsvc"=>lsvc,"rbfsvc"=>rbfsvc,"ada"=>ada,"dt"=>dt) function oneblock_pipeline_factory(scalers,extractors,learners) results = @distributed (vcat) for lr in learners @distributed (vcat) for xt in extractors @distributed (vcat) for sc in scalers # baseline preprocessing prep = @pipeline ((catf |> ohe) + numf) # one-block prp expx = @pipeline prep |> (sc |> xt) |> lr scn = sc.name[1:end - 4];xtn = xt.name[1:end - 4]; lrn = lr.name[1:end - 4] pname = "($scn |> $xtn) |> $lrn" DataFrame(Description=pname,Pipeline=expx) end end end return results end function evaluate_pipeline(dfpipelines,X,Y;folds=3) res=@distributed (vcat) for prow in eachrow(dfpipelines) perf = crossvalidate(prow.Pipeline,X,Y,"balanced_accuracy_score";nfolds=folds) DataFrame(;Description=prow.Description,mean=perf.mean,sd=perf.std,prow.Pipeline) end return res end function twoblock_pipeline_factory(scalers,extractors,learners) results = @distributed (vcat) for lr in learners @distributed (vcat) for xt1 in extractors @distributed (vcat) for xt2 in extractors @distributed (vcat) for sc1 in scalers @distributed (vcat) for sc2 in scalers prep = @pipeline ((catf |> ohe) + numf) expx = @pipeline prep |> ((sc1 |> xt1) + (sc2 |> xt2)) |> lr scn1 = sc1.name[1:end - 4];xtn1 = xt1.name[1:end - 4]; scn2 = sc2.name[1:end - 4];xtn2 = xt2.name[1:end - 4]; lrn = lr.name[1:end - 4] pname = "($scn1 |> $xtn1) + ($scn2 |> $xtn2) |> $lrn" DataFrame(Description=pname,Pipeline=expx) end end end end end return results end function model_selection_pipeline(learners) results = @distributed (vcat) for lr in learners prep = @pipeline ((catf |> ohe) + numf) expx = @pipeline prep |> (rb |> pca) |> lr pname = "(rb |> pca) |> $(lr.name[1:end-4])" DataFrame(Description=pname,Pipeline=expx) end return results end function lname(n::Learner) n.name[1:end-4] end function twoblockspipelinesearch(X::DataFrame,Y::Vector;scalers=vscalers,extractors=vextractors,learners=vlearners,nfolds=3) dfpipes = model_selection_pipeline(vlearners) # find the best model by evaluating the models modelsperf = evaluate_pipeline(dfpipes,X,Y;folds=nfolds) sort!(modelsperf,:mean, rev = true) # get the string name of the top model bestm = filter(x->occursin(x,modelsperf.Description[1]),lname.(vlearners))[1] # get corresponding model object bestmodel = learnerdict[bestm] # use the best model to generate pipeline search dfp = twoblock_pipeline_factory(vscalers,vextractors,[bestmodel]) # evaluate the pipeline bestp=evaluate_pipeline(dfp,X,Y;folds=nfolds) sort!(bestp,:mean, rev = true) show(bestp;allrows=false,truncate=1,allcols=false) println() optmodel = bestp[1,:] return bestp end end
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
1931
# from discourse discussion with zevelev # make sure local environment is activated using Pkg Pkg.activate(".") using Distributed using AutoMLPipeline using DataFrames # add workers nprocs() ==1 && addprocs(exeflags=["--project=$(Base.active_project())"]) workers() # disable warnings @everywhere import PythonCall @everywhere const PYC=PythonCall @everywhere warnings = PYC.pyimport("warnings") @everywhere warnings.filterwarnings("ignore") @everywhere using AutoMLPipeline @everywhere using DataFrames #Get models. sk= AutoMLPipeline.SKLearners.learner_dict |> keys |> collect; sk= sk |> x-> sort(x,lt=(x,y)->lowercase(x)<lowercase(y)); m_cl= sk[occursin.("Classifier", sk)]; m_cl= m_cl ∪ sk[occursin.("NB", sk)]; m_cl= m_cl ∪ sk[occursin.("SVC", sk)]; m_cl= m_cl ∪ ["LDA", "QDA"]; iris = AutoMLPipeline.Utils.getiris(); X = iris[:,1:4]; Y = iris[:,end] |> Vector; # find optimal learners learners = @distributed (vcat) for m in m_cl learner = skoperator(m) pcmc = AutoMLPipeline.@pipeline learner println(learner.name) mean,sd,folds,err = crossvalidate(pcmc,X,Y,"accuracy_score",5) if !isnan(mean) DataFrame(name=learner.name,mean=mean,sd=sd,folds=folds,errors=err) else DataFrame() end end; sort!(learners,:mean,rev=true) @show learners; # optimized C results=@distributed (vcat) for C in 1:5 @distributed (vcat) for gamma = 1:5 svcmodel = SKLearner("SVC",Dict(:impl_args=>Dict(:kernel=>"rbf",:C=>C,:gamma=>gamma) )) mn,sd,fld,err = crossvalidate(svcmodel,X,Y) DataFrame(name=svcmodel.name,mean=mn,sd=sd,C=C,gamma=gamma,folds=fld,errors=err) end end sort!(results,:mean,rev=true) @show results # search best learner by crossvalidation and use it for prediction learners = SKLearner.(["AdaBoostClassifier","BaggingClassifier","SGDClassifier","SVC","LinearSVC"]) blearner = BestLearner(learners) crossvalidate(blearner,X,Y,"accuracy_score") fit!(blearner,X,Y)
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
3316
# make sure local environment is activated using Pkg Pkg.activate(".") # Symbolic Pipeline Composition # For parallel search using AutoMLPipeline using Distributed using DataFrames # Add workers nprocs() ==1 && addprocs(exeflags=["--project=$(Base.active_project())"]) workers() # disable warnings @everywhere import PythonCall @everywhere const PYC=PythonCall @everywhere warnings = PYC.pyimport("warnings") @everywhere warnings.filterwarnings("ignore") @sync @everywhere using AutoMLPipeline @sync @everywhere using DataFrames # get data begin data = getprofb() X = data[:,2:end] Y = data[:,1] |> Vector end #### feature selectors catf = CatFeatureSelector(); numf = NumFeatureSelector(); # hot-bit encoder ohe = OneHotEncoder(); #### feature scalers rb = SKPreprocessor("RobustScaler"); pt = SKPreprocessor("PowerTransformer"); mx = SKPreprocessor("MinMaxScaler"); std = SKPreprocessor("StandardScaler"); norm = SKPreprocessor("Normalizer"); #### feature extractors pca = SKPreprocessor("PCA", Dict(:autocomponent => true)); ica = SKPreprocessor("FastICA", Dict(:autocomponent => true)); fa = SKPreprocessor("FactorAnalysis", Dict(:autocomponent => true)); #### Learners rf = SKLearner("RandomForestClassifier", Dict(:impl_args => Dict(:n_estimators => 10))); gb = SKLearner("GradientBoostingClassifier"); lsvc = SKLearner("LinearSVC"); mlp = SKLearner("MLPClassifier"); stack = StackEnsemble(); rbfsvc = SKLearner("SVC"); ada = SKLearner("AdaBoostClassifier"); vote = VoteEnsemble(); best = BestLearner(); tree = PrunedTree(); sgd = SKLearner("SGDClassifier"); noop = Identity(Dict(:name => "Noop")); pipe = @pipeline catf; pred = fit_transform!(pipe, X, Y) pipe = @pipeline catf |> ohe; pred = fit_transform!(pipe, X, Y) pipe = @pipeline numf; pred = fit_transform!(pipe, X, Y) pipe = @pipeline numf |> norm; pred = fit_transform!(pipe, X, Y) pipe = @pipeline (numf |> norm) + (catf |> ohe); pred = fit_transform!(pipe, X, Y) pipe = @pipeline (numf |> norm) + (catf |> ohe) |> rf; pred = fit_transform!(pipe, X, Y) crossvalidate(pipe,X,Y) pipe = @pipeline (numf |> norm) + (catf |> ohe) |> sgd; crossvalidate(pipe,X,Y) pipe = @pipeline (numf |> norm |> pca) + (numf |> rb |> pca) + (catf |> ohe) |> tree; crossvalidate(pipe,X,Y) # Parallel Search for Datamining Optimal Pipelines function prpsearch() learners = [rf,ada,sgd,tree,rbfsvc,lsvc,gb]; scalers = [rb,pt,norm,std,mx,noop]; extractors = [pca,ica,fa,noop]; dftable = @sync @distributed (vcat) for lr in learners @distributed (vcat) for sc in scalers @distributed (vcat) for xt in extractors pipe = @pipeline (catf |> ohe) + (numf |> sc |> xt) |> lr scn = sc.name[1:end - 4]; xtn = xt.name[1:end - 4]; lrn = lr.name[1:end - 4] pname = "$scn |> $xtn |> $lrn" ptime = @elapsed begin mean, sd, kfold, _ = crossvalidate(pipe, X, Y, "accuracy_score", 3) end DataFrame(pipeline=pname, mean=mean, sd=sd, time=ptime, folds=kfold) end end end sort!(dftable, :mean, rev=true); dftable end runtime = @elapsed begin df = prpsearch() end; serialtime = df.time |> sum; (serialtime = "$(round(serialtime / 60.0)) minutes", paralleltime = "$(round(runtime)) seconds") # pipeline performances @show df
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
5204
# Brief Intro # - Paulito Palmes, PhD # - IBM Research Scientist # - IBM Dublin Research Lab # # Acknowledgement # # Problem Overview # - given a set of pipeline elements (prp): # - feature selectors (fsl) : catf, numf # - scalers (fsc) : norm, minmax, std, rb # - feature extractors (fxt) : pca, ica, fa # - learners (lr) : rf, xgb, svm # # - Find optimal U{fsl |> fsc |> fxt} |> lr # - Note: x |> f => f(x); x + y => U{x,y} # - Assume one-block prp: fsl |> fsc |> fxt # - Optimize: prp1 + prp2 + ... + prpn |> lr # - Optimize: matching between {prps} x {lrs} s.t. # chosen prp |> lr is optimal # - Complexity: n(prps) x n(lrs) # - exponential/combinatorial complexity # # - Two-stage strategy (avoid simultaneous search prps and lrs) # - Pick a surrogate pipeline and search best lr in {lrs} # - Use lr to search for best prp in {prps} # - Reduce complexity from n(prps) x n(lrs) to n(prps) + n(lrs) # - limitations: # - only pipeline structure optimization # - no hyper-parameter optimization # - for classification tasks # # - Current Toolkits # sklearn: Pipeline, FeatureUnion, Hyperparam-Optim # caret: No pipeline, Hyperparam-Optim # lale: sklearn + AutoML (CASH) # - bayesian optimization, tree search, random, stochastic, evolutionary # # AutoMLPipeline: A package that makes it trivial to create and evaluate machine # learning pipeline architectures. It can be used as building block # for developing AutoML algorithms similar to lale but in Julia # ecosystem. # # ------------------------------- # Sample Workflow # ------------------------------- # make sure local environment is activated using Pkg Pkg.activate(".") # Symbolic Pipeline Composition # For parallel search using AutoMLPipeline using Distributed using DataFrames # disable truncation of dataframes columns import Base.show show(df::AbstractDataFrame) = show(df,truncate=0) show(io::IO,df::AbstractDataFrame) = show(io,df;truncate=0) # add workers nprocs() ==1 && addprocs(exeflags=["--project=$(Base.active_project())"]) workers() # disable warnings @everywhere import PythonCall @everywhere const PYC=PythonCall @everywhere warnings = PYC.pyimport("warnings") @everywhere warnings.filterwarnings("ignore") @sync @everywhere using AutoMLPipeline @sync @everywhere using DataFrames # get data begin data = getprofb() X = data[:,2:end] Y = data[:,1] |> Vector end #### feature selectors catf = CatFeatureSelector(); numf = NumFeatureSelector(); # hot-bit encoder ohe = OneHotEncoder(); #### feature scalers rb = SKPreprocessor("RobustScaler"); pt = SKPreprocessor("PowerTransformer"); mx = SKPreprocessor("MinMaxScaler"); std = SKPreprocessor("StandardScaler"); norm = SKPreprocessor("Normalizer"); #### feature extractors pca = SKPreprocessor("PCA", Dict(:autocomponent => true)); ica = SKPreprocessor("FastICA", Dict(:autocomponent => true)); fa = SKPreprocessor("FactorAnalysis", Dict(:autocomponent => true)); #### Learners rf = SKLearner("RandomForestClassifier", Dict(:impl_args => Dict(:n_estimators => 10))); gb = SKLearner("GradientBoostingClassifier"); lsvc = SKLearner("LinearSVC"); mlp = SKLearner("MLPClassifier"); stack = StackEnsemble(); rbfsvc = SKLearner("SVC"); ada = SKLearner("AdaBoostClassifier"); vote = VoteEnsemble(); best = BestLearner(); tree = PrunedTree(); sgd = SKLearner("SGDClassifier"); noop = Identity(Dict(:name => "Noop")); pipe = @pipeline catf; pred = fit_transform!(pipe, X, Y) pipe = @pipeline catf |> ohe; pred = fit_transform!(pipe, X, Y) pipe = @pipeline numf; pred = fit_transform!(pipe, X, Y) pipe = @pipeline numf |> norm; pred = fit_transform!(pipe, X, Y) pipe = @pipeline (numf |> norm) + (catf |> ohe); pred = fit_transform!(pipe, X, Y) pipe = @pipeline (numf |> norm) + (catf |> ohe) |> rf; pred = fit_transform!(pipe, X, Y); crossvalidate(pipe,X,Y) pipe = @pipeline (numf |> norm) + (catf |> ohe) |> sgd; crossvalidate(pipe,X,Y) pipe = @pipeline (numf |> norm |> pca) + (numf |> rb |> pca) + (catf |> ohe) |> tree; crossvalidate(pipe,X,Y) # Parallel Search for Datamining Optimal Pipelines function prpsearch() learners = [rf,ada,sgd,tree,rbfsvc,lsvc,gb]; scalers = [rb,pt,norm,std,mx,noop]; extractors = [pca,ica,fa,noop]; dftable = @sync @distributed (vcat) for lr in learners @distributed (vcat) for sc in scalers @distributed (vcat) for xt in extractors pipe = @pipeline (catf |> ohe) + (numf |> sc |> xt) |> lr scn = sc.name[1:end - 4]; xtn = xt.name[1:end - 4]; lrn = lr.name[1:end - 4] pname = "$scn |> $xtn |> $lrn" ptime = @elapsed begin mean, sd, kfold, _ = crossvalidate(pipe, X, Y, "accuracy_score", 3) end DataFrame(pipeline=pname, mean=mean, sd=sd, time=ptime, folds=kfold) end end end sort!(dftable, :mean, rev=true); dftable end runtime = @elapsed begin df = prpsearch() end; serialtime = df.time |> sum; (serialtime = "$(round(serialtime / 60.0)) minutes", paralleltime = "$(round(runtime)) seconds") # pipeline performances sort!(df,:mean,rev=true)
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
5858
# ---------------------------------- # Implementation # ---------------------------------- # make sure local environment is activated using Pkg Pkg.activate(".") using Distributed # add workers nprocs() ==1 && addprocs(exeflags=["--project=$(Base.active_project())"]) workers() # disable warnings @everywhere import PythonCall @everywhere const PYC=PythonCall @everywhere warnings = PYC.pyimport("warnings") @everywhere warnings.filterwarnings("ignore") @everywhere using AutoMLPipeline @everywhere using DataFrames @everywhere using AutoMLPipeline: score @everywhere using Random ENV["COLUMNS"]=1000 ENV["LINES"]=100; # disable truncation of dataframes columns import Base.show show(df::AbstractDataFrame) = show(df,truncate=0) show(io::IO,df::AbstractDataFrame) = show(io,df;truncate=0) # brief overview of AutoMLPipeline package # more details is in my Juliacon2020 presentation about this package # we use AutoMLPipeline to develop the pipeline optimizer # define scalers rb = SKPreprocessor("RobustScaler",Dict(:name=>"rb")) pt = SKPreprocessor("PowerTransformer",Dict(:name=>"pt")) norm = SKPreprocessor("Normalizer",Dict(:name=>"norm")) mx = SKPreprocessor("MinMaxScaler",Dict(:name=>"mx")) std = SKPreprocessor("StandardScaler",Dict(:name=>"std")) # define extractors pca = SKPreprocessor("PCA",Dict(:name=>"pca")) fa = SKPreprocessor("FactorAnalysis",Dict(:name=>"fa")) ica = SKPreprocessor("FastICA",Dict(:name=>"ica")) # define learners rf = SKLearner("RandomForestClassifier",Dict(:name => "rf")) ada = SKLearner("AdaBoostClassifier",Dict(:name => "ada")) gb = SKLearner("GradientBoostingClassifier",Dict(:name => "gb")) lsvc = SKLearner("LinearSVC",Dict(:name => "lsvc")) rbfsvc = SKLearner("SVC",Dict(:name => "rbfsvc")) dt = SKLearner("DecisionTreeClassifier",Dict(:name =>"dt")) # preprocessing noop = Identity(Dict(:name =>"noop")) ohe = OneHotEncoder(Dict(:name=>"ohe")) catf = CatFeatureSelector(Dict(:name=>"catf")) numf = NumFeatureSelector(Dict(:name=>"numf")) vscalers = [rb,pt,norm,mx,std,noop] vextractors = [pca,fa,ica,noop] vlearners = [rf,gb,lsvc,rbfsvc,ada,dt] dataset = getiris() X = dataset[:,1:4] Y = dataset[:,5] |> collect # one-block pipeline prep = @pipeline (catf |> ohe) + numf ppl1 = @pipeline prep |> (mx |> pca) |> rf crossvalidate(ppl1,X,Y) # two-block pipeline ppl2 = @pipeline prep |> ((norm |> ica) + (pt |> pca)) |> lsvc crossvalidate(ppl2,X,Y) function oneblock_pipeline_factory(scalers,extractors,learners) results = @distributed (vcat) for lr in learners @distributed (vcat) for xt in extractors @distributed (vcat) for sc in scalers # baseline preprocessing prep = @pipeline ((catf |> ohe) + numf) # one-block prp expx = @pipeline prep |> (sc |> xt) |> lr scn = sc.name[1:end - 4];xtn = xt.name[1:end - 4]; lrn = lr.name[1:end - 4] pname = "($scn |> $xtn) |> $lrn" DataFrame(Description=pname,Pipeline=expx) end end end return results end res_oneblock = oneblock_pipeline_factory(vscalers,vextractors,vlearners) crossvalidate(res_oneblock.Pipeline[1],X,Y) function evaluate_pipeline(dfpipelines,X,Y;folds=3) res=@distributed (vcat) for prow in eachrow(dfpipelines) perf = crossvalidate(prow.Pipeline,X,Y;nfolds=folds) DataFrame(Description=prow.Description,mean=perf.mean,sd=perf.std,Pipeline=prow.Pipeline,) end return res end cross_res_oneblock = evaluate_pipeline(res_oneblock,X,Y) sort!(cross_res_oneblock,:mean, rev = true) show(cross_res_oneblock;allrows=true,allcols=true,truncate=0) function twoblock_pipeline_factory(scalers,extractors,learners) results = @distributed (vcat) for lr in learners @distributed (vcat) for xt1 in extractors @distributed (vcat) for xt2 in extractors @distributed (vcat) for sc1 in scalers @distributed (vcat) for sc2 in scalers prep = @pipeline ((catf |> ohe) + numf) expx = @pipeline prep |> ((sc1 |> xt1) + (sc2 |> xt2)) |> lr scn1 = sc1.name[1:end - 4];xtn1 = xt1.name[1:end - 4]; scn2 = sc2.name[1:end - 4];xtn2 = xt2.name[1:end - 4]; lrn = lr.name[1:end - 4] pname = "($scn1 |> $xtn1) + ($scn2 |> $xtn2) |> $lrn" DataFrame(Description=pname,Pipeline=expx) end end end end end return results end res_twoblock = twoblock_pipeline_factory(vscalers,vextractors,vlearners) function model_selection_pipeline(learners) results = @distributed (vcat) for lr in learners prep = @pipeline ((catf |> ohe) + numf) expx = @pipeline prep |> (rb |> pca) |> lr pname = "(rb |> pca) |> $(lr.name[1:end-4])" DataFrame(Description=pname,Pipeline=expx) end return results end dfpipes = model_selection_pipeline(vlearners) # find the best model @everywhere Random.seed!(10) res = evaluate_pipeline(dfpipes,X,Y;folds=10) sort!(res,:mean, rev = true) # use the best model to generate pipeline search dfp = twoblock_pipeline_factory(vscalers,vextractors,[rbfsvc]) # evaluate the pipeline @everywhere Random.seed!(10) bestp=evaluate_pipeline(dfp,X,Y;folds=3) sort!(bestp,:mean, rev = true) show(bestp;allrows=false,truncate=0,allcols=false) # create pipeline factory # - create oneblock factory # - create twoblocks factory # # evaluate pipeline factory # Model selection should be given more priority than pipeline and hyperparam search # Algo: # - start with an arbitrary pipeline and search for the best model # using their default parameters # - with the best model selected, refine the solution # by searching for the best pipeline # - refine the model more by hyperparm search if needed
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git
[ "MIT" ]
0.4.6
02a92d379ef775b7e3bf07414a4459ec72cca73d
code
2232
# activate local env using Pkg Pkg.activate(".") # load packages/modules using DataFrames using AutoMLPipeline using AbstractTrees # disable warnings import PythonCall const PYC=PythonCall warnings = PYC.pyimport("warnings") warnings.filterwarnings("ignore") ## get data profbdata = getprofb() X = profbdata[:,2:end]; Y = profbdata[:,1] |> Vector; topdf(x)=first(x,5) topdf(profbdata) ## # load filters #### Decomposition pca = SKPreprocessor("PCA"); fa = SKPreprocessor("FactorAnalysis"); ica = SKPreprocessor("FastICA"); #### Scaler rb = SKPreprocessor("RobustScaler"); pt = SKPreprocessor("PowerTransformer"); norm = SKPreprocessor("Normalizer"); mx = SKPreprocessor("MinMaxScaler"); #### categorical preprocessing ohe = OneHotEncoder() #### Column selector catf = CatFeatureSelector(); numf = NumFeatureSelector(); #### Learners rf = SKLearner("RandomForestClassifier",Dict(:impl_args=>Dict(:n_estimators => 100))); gb = SKLearner("GradientBoostingClassifier"); lsvc = SKLearner("LinearSVC"); mlp = SKLearner("MLPClassifier"); jrf = RandomForest(); stack = StackEnsemble(); svc = SKLearner("SVC"); ada = SKLearner("AdaBoostClassifier"); vote = VoteEnsemble(); best = BestLearner(); # filter categories and hotbit encode pohe = @pipeline catf |> ohe; tr = fit_transform!(pohe,X,Y) pohe = @pipeline numf |> pca; tr = fit_transform!(pohe,X,Y) # filter numeric and apply pca and ica pdec = @pipeline (numf |> pca) + (numf |> ica); tr = fit_transform!(pdec,X,Y) # filter numeric, apply rb/pt transforms and ica/pca extractions ppt = @pipeline (numf |> rb |> ica) + (numf |> pt |> pca) tr = fit_transform!(ppt,X,Y) # rf learn baseline rfp1 = @pipeline ( (catf |> ohe) + (catf |> ohe) + (numf) ) |> rf; crossvalidate(rfp1, X,Y) # rf learn: bigrams, 2-blocks rfp2 = @pipeline ((catf |> ohe) + numf |> rb |> ica) + (numf |> pt |> pca) |> ada; crossvalidate(rfp2, X,Y) # lsvc learn: bigrams, 3-blocks plsvc = @pipeline ((numf |> rb |> pca)+(numf |> rb |> fa)+(numf |> rb |> ica)+(catf |> ohe )) |> lsvc; pred = fit_transform!(plsvc,X,Y) crossvalidate(plsvc,X,Y) expressiontree = @pipelinex ((numf |> rb |> pca)+(numf |> rb |> fa)+(numf |> rb |> ica)+(catf |> ohe )) |> lsvc print_tree(expressiontree)
AutoMLPipeline
https://github.com/IBM/AutoMLPipeline.jl.git