licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
docs
296
# API ```@meta CollapsedDocStrings = true ``` ## Index ```@index Pages = ["api.md"] Modules = [CTBase] Order = [:module, :constant, :type, :function, :macro] ``` ## Documentation ```@autodocs Modules = [CTBase] Order = [:module, :constant, :type, :function, :macro] Private = false ```
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
docs
310
# Private functions ```@meta CollapsedDocStrings = true ``` ## Index ```@index Pages = ["dev.md"] Modules = [CTBase] Order = [:module, :constant, :type, :function, :macro] ``` ## Documentation ```@autodocs Modules = [CTBase] Order = [:module, :constant, :type, :function, :macro] Public = false ```
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.14.0
68e9ab3053e0b38e8e574f2809dd280c9dafa338
docs
608
# CTBase.jl ```@meta CurrentModule = CTBase ``` The `CTBase.jl` package is part of the [control-toolbox ecosystem](https://github.com/control-toolbox). ```mermaid flowchart TD O(<a href='https://control-toolbox.org/OptimalControl.jl/stable/'>OptimalControl</a>) --> B(<a href='https://control-toolbox.org/OptimalControl.jl/stable/api-ctbase.html'>CTBase</a>) O --> D(<a href='https://control-toolbox.org/OptimalControl.jl/stable/api-ctdirect.html'>CTDirect</a>) O --> F(<a href='https://control-toolbox.org/OptimalControl.jl/stable/api-ctflows.html'>CTFlows</a>) F --> B D --> B style B fill:#FBF275 ```
CTBase
https://github.com/control-toolbox/CTBase.jl.git
[ "MIT" ]
0.1.2
decb6ccca24c54748e740cc42076b13fcccf384a
code
134
module ApproxLogFunction export Approxlog export toclang include("./core.jl") include("./clang.jl") end # module ApproxLogFunction
ApproxLogFunction
https://github.com/sonosole/ApproxLogFunction.jl.git
[ "MIT" ]
0.1.2
decb6ccca24c54748e740cc42076b13fcccf384a
code
2249
function hcsrc(filename::String, funcname::String, f::Approxlog{I,F}) where {I,F} four = " " fmax = floatmax(F) ftype = nothing itype = nothing logᵦ = f.logtable N = length(logᵦ) dotc = """ #include <stdint.h> #include "$(filename).h"\n """ if I <: Int32 ftype = "float" itype = "int32_t" dotc *= "static float table[$N] = \n{\n" end if I <: Int64 ftype = "double" itype = "int64_t" dotc *= "static double table[$N] = \n{\n" end for i = 1 : N - 1 dotc *= "$four$(logᵦ[i]),\n" end;dotc *= "$four$(logᵦ[N])\n};\n\n" fracbits = f.fracbits expobias = f.expobias fracmask = f.fracmask shiftbits = f.shiftbits logbase2 = f.logbase2 dotc *= """ $ftype $funcname($ftype x) { if(x <= 0){ return -$fmax; } $itype z = *( ($itype*) (&x) ); $itype e = (z >> $fracbits) - $expobias; $itype i = (z & $fracmask) >> $shiftbits; return $logbase2 * e + table[i]; } """ FILENAME = uppercase(filename) doth = """ #ifndef $(FILENAME)_H #define $(FILENAME)_H $ftype $funcname($ftype x); #endif """ return doth, dotc end """ toclang(dstdir::String, filename::String, funcname::String, f::Approxlog) generate C language `.h` and `.c` files for an `Approxlog` functor `f`. + `dstdir` is the directory to save the C language files (`dir` would be made if it doesn't exist before) + `filename` is the name of the generated `.c` and `.h` files + `funcname` is the name of the generated approximate function # Example ```julia alog₂ = Approxlog(2, abserror=0.12, dtype=Float32); toclang("./cfolder/", "approxlog", "alog", alog₂); ``` """ function toclang(dstdir::String, filename::String, funcname::String, f::Approxlog{I,F}) where {I,F} if !isdir(dstdir) mkdir(dstdir) end nowdir = pwd() cd(dstdir) doth, dotc = hcsrc(filename, funcname, f) hdst = touch(filename * ".h") cdst = touch(filename * ".c") open(hdst, "w") do io write(io, doth) end open(cdst, "w") do io write(io, dotc) end cd(nowdir) return nothing end
ApproxLogFunction
https://github.com/sonosole/ApproxLogFunction.jl.git
[ "MIT" ]
0.1.2
decb6ccca24c54748e740cc42076b13fcccf384a
code
4367
@inline function f2i(::Type{F}) where F <: AbstractFloat (F <: Float16) && return Int16 (F <: Float32) && return Int32 (F <: Float64) && return Int64 end struct Approxlog{XInt, XFloat} expobits :: XInt fracbits :: XInt expobias :: XInt fracmask :: XInt shiftbits :: XInt logbase :: Real logbase2 :: XFloat maxerror :: XFloat logtable :: Vector{XFloat} function Approxlog{XInt,XFloat}(expobits :: XInt, fracbits :: XInt, expobias :: XInt, fracmask :: XInt, shiftbits :: XInt, logbase :: Real, logbase2 :: XFloat, maxerror :: XFloat, logtable :: Vector{XFloat}) where {XInt <: Integer, XFloat <: AbstractFloat} new{XInt,XFloat}(expobits, fracbits, expobias, fracmask, shiftbits, logbase, logbase2, maxerror, logtable) end end function Base.show(io::IO, ::MIME"text/plain", a::Approxlog{I,F}) where {I,F} logbase = a.logbase maxerror = a.maxerror expobits = a.expobits fracbits = a.fracbits expobias = a.expobias fracmask = a.fracmask shiftbits = a.shiftbits println("Approxlog{$logbase, $F}:") println(" maxerror = $maxerror") println(" signbits = 1") println(" expobits = $expobits") println(" fracbits = $fracbits") println(" expobias = $expobias") println(" fracmask = $fracmask") print(" shiftbits = $shiftbits") end function table(f::Approxlog) return f.logtable end function maxerror(f::Approxlog) return f.maxerror end """ Approxlog(base::Real; dtype::Type{<:AbstractFloat}, abserror::Real) A lookup table based method to calculate `y` = log(base, `x`) with controllable error + `base` is the radix of logarithm operation + `dtype` is the data type of input `x` and output `y` + `abserror` is the required absolute error of the output `y` # Example ```julia alog₂ = Approxlog(2, abserror=0.1, dtype=Float32); input = 5.20f2; output = alog₂(input); ``` """ function Approxlog(base::Real; dtype::Type{F}, abserror::Real) where F <: AbstractFloat @assert base > 0 "base > 0 shall be met, but got $base" @assert base ≠ 1 "base ≠ 1 shall be met, but got $base" if abs(1-base) < 1e-2 @warn("the base of log is too much closing to 1") end I = f2i(F) # the right integer type corresponding to float type F l = one(I) # alias for integer 1 inputerror = abserror * abs(log(base)) usedfracbits = floor(I, log2(nextpow(2, 1 / inputerror))) tablelength = l << usedfracbits if usedfracbits > 14 kbs = 2^usedfracbits * sizeof(F) / 1024 @warn("the table buffer would occupy $kbs KiB") end Δx = F(1 / tablelength) # the actual input error Δy = F(Δx / abs(log(base))) # the actual output error expobits = nothing fracbits = nothing if F <: Float16 expobits = I(5) fracbits = I(10) end if F <: Float32 expobits = I(8) fracbits = I(23) end if F <: Float64 expobits = I(11) fracbits = I(52) end expobias = ( (l << (expobits-1)) - l ) # exponent part's bias number for float type F fracmask = ( (l << (fracbits )) - l ) # to set non-fracbits 0 shiftbits = fracbits - usedfracbits @assert fracbits > usedfracbits "using too much bits for fraction, we only have $fracbits for $F, but you want $usedfracbits" table = Vector{F}(undef, tablelength) for i = 1 : tablelength table[i] = log(base, 1 + (i-1) * Δx) end return Approxlog{I,F}(expobits, fracbits, expobias, fracmask, shiftbits, base, F(log(base,2)), Δy, table) end function (f::Approxlog{I,F})(x::F) where {I,F} x < 0 && error("input shall be greater than 0") x == 0 && return -floatmax(F) xint = reinterpret(I, x) e = (xint >> f.fracbits) - f.expobias i = (xint & f.fracmask) >> f.shiftbits return @inbounds e * f.logbase2 + f.logtable[i+1] end
ApproxLogFunction
https://github.com/sonosole/ApproxLogFunction.jl.git
[ "MIT" ]
0.1.2
decb6ccca24c54748e740cc42076b13fcccf384a
code
410
using Test using ApproxLogFunction @testset "checking error requirement" begin N = 32; for type in [Float16, Float32, Float64], base in [1.997, π, 10], Δout in [0.2, 0.1, 0.05] alog = Approxlog(base, abserror=Δout, dtype=type); k = type(17) x = rand(type, N) .* k; y = alog.(x) z = log.(base, x) @test sum(y - z)/N ≤ Δout end end
ApproxLogFunction
https://github.com/sonosole/ApproxLogFunction.jl.git
[ "MIT" ]
0.1.2
decb6ccca24c54748e740cc42076b13fcccf384a
docs
4257
# ApproxLogFunction A lookup table based method to calculate $y = {\rm log}_b(x)$ with a controllable error, where $b > 0$, $b ≠ 1$, $x > 0$, and $x$ shall be the **IEEE754** floating-point **normal** numbers. ## 💽 Installation ```julia julia> import Pkg; julia> Pkg.add("ApproxLogFunction"); ``` ## 👨‍🏫 Usage ### 🔌 Exposed Functor The exposed constructor : ```julia Approxlog(base::Real; abserror::Real, dtype::Type{<:AbstractFloat}) ``` where `base` is the radix of logarithm operation, `abserror` is the maximum absolute error of the output and `dtype` is the data type of input and output value, for example : ```julia alog₂ = Approxlog(2, abserror=0.1, dtype=Float32); input = 5.20f2; output = alog₂(input); ``` ### 📈 Error Visualization ```julia using Plots, ApproxLogFunction figs = [] base = 2 t = -2f-0 : 1f-4 : 5f0; x = 2 .^ t; y₁ = log.(base, x) for Δout in [0.6, 0.3] alog = Approxlog(base, abserror=Δout, dtype=Float32) y₂ = alog.(x) fg = plot(x, y₁, linewidth=1.1, xscale=:log10); plot!(x, y₂, linewidth=1.1, titlefontsize=10) title!("abserror=$Δout") push!(figs, fg) end plot(figs..., layout=(1,2), leg=nothing, size=(999,666)) ``` ![error](./doc/abserr.jpg) ## 🥇 Benchmark Some unimportant information was omitted when benchmarking. ### 💃🏻 Scalar Input ```julia julia> using ApproxLogFunction, BenchmarkTools; julia> begin type = Float32; base = type(2.0); Δout = 0.1; alog = Approxlog(base, abserror=Δout, dtype=type); end; julia> x = 1.23456f0; julia> @benchmark y₁ = log($base, $x) Time (median): 21.643 ns julia> @benchmark y₁ = log2($x) Time (median): 14.800 ns julia> @benchmark y₂ = alog($x) Time (median): 74.129 ns ``` ### 👨‍👨‍👧‍👧 Array Input ```julia julia> using ApproxLogFunction, BenchmarkTools; julia> begin type = Float32; base = type(2.0); Δout = 0.1; alog = Approxlog(base, abserror=Δout, dtype=type); end; julia> x = rand(type, 1024, 1024); julia> @benchmark y₁ = log.($base, $x) Time (median): 21.422 ms julia> @benchmark y₁ = log2.($x) Time (median): 11.626 ms julia> @benchmark y₂ = alog.($x) Time (median): 5.207 ms ``` Calculating scaler input is slower, but why calculating array input is faster ? 😂😂😂 ## ⚠️ Attention ### About The Input Range Error is well controlled when using IEEE754 floating-point positive **normal** numbers, which is represented as : $$ x = 2^{E-B} \ (1 + F × 2^{-|F|}) $$ where $0 < E < (2^{|E|} - 1)$ is the value of exponent part, $|E|$ is the bit width of $E$, $F$ is the value of fraction part, $|F|$ is the bit width of $F$, and $B=(2 ^ {|E| - 1} - 1)$ is the bias for $E$. So the range for an `Approxlog` object's input is $[X_{\rm min}, X_{\rm max}]$, where $$ \begin{aligned} X_{\rm min} &= 2^{1-B} \ (1 + 0 × 2^{-|F|}) &&= 2^{1-B} \\ X_{\rm max} &= 2^{(2^{|E|}-2)-B} \ \big(1 + (2^{|F|}-1) × 2^{-|F|}\big) &&= 2^{B} \ \big(1 + (2^{|F|}-1) × 2^{-|F|}\big) \end{aligned} $$ In short, for `Float16` input, its range is : $$ 2^{1-15} \le X_{\rm Float16} \le 2^{15} \ \left( 1 + (2^{10} -1) × 2^{-10} \right) $$ for `Float32` input : $$ 2^{1-127} \le X_{\rm Float32} \le 2^{127} \ \left(1 + (2^{23} -1) × 2^{-23}\right) $$ and for `Float64` input : $$ 2^{1-1023} \le X_{\rm Float64} \le 2^{1023} \ \left(1 + (2^{52} -1) × 2^{-52}\right) $$ As to positive **subnormal** numbers, the result is not reliable. ### About The Base Range We have mentioned $b ≠ 1$, but base value closing to $1$ is not recommended, e.g. $1.0001$, $0.9999$. ## 📁 C-Lang Files Interface function : ```julia toclang(dir::String, filename::String, funcname::String, f::Approxlog) ``` `dir` is the directory to save the C language files (`dir` would be made if it doesn't exist before), `filename` is the name of the generated `.c` and `.h` files, `funcname` is the name of the generated approximate function and `f` is the approximate log functor, for example : ```julia alog₂ = Approxlog(2, abserror=0.12, dtype=Float32) toclang("./cfolder/", "approxlog", "alog", alog₂) ``` this would generate `approxlog.c` and `approxlog.h` files in `./cfolder/`, the function is named as `alog` .
ApproxLogFunction
https://github.com/sonosole/ApproxLogFunction.jl.git
[ "MIT" ]
0.0.1
4fe353b814d2306e297db626a1669e6b6aa9f2af
code
2452
module DefaultFields using Parameters export @with_fields """ Add `fields` to a type definition. Fields format: `:(fieldname::Type)`. """ function add_field!(typedef, fields...) @assert typedef.head == :struct fdef = typedef.args[3] dupl = intersect(_fieldnames.(fields), _fieldnames(fdef)) length(dupl) == 0 || error("syntax: duplicate field name: $(dupl...)") push!(fdef.args, fields...) typedef end """ ```julia @with_fields atypename fields... ``` Macro to define an abstract type `atypename` that automatically adds `fields` to its subtypes. The subtypes are declared using the macro `@atypename`. # Examples: ```julia julia> @with_fields abs_type a::Int b julia> @abs_type struct mystruct c::Float64 end julia> fieldnames(mystruct) (:c, :a, :b) julia> fieldtypes(mystruct) (Float64, Int64, Any) julia> mystruct <: abs_type true julia> abstract type supertype end julia> @with_fields abs_type <: supertype field_a field_b julia> abs_type <: supertype true ``` """ macro with_fields(namedef, fields...) allunique(_fieldnames.(fields)) || error("syntax: duplicate field name: $(_duplicates(_fieldnames.(fields))...)") macroname = namedef isa Expr ? (namedef.head == :<: ? namedef.args[1] : error("Invalid abstract type declaration")) : namedef absdef = Expr(:abstract, namedef) macrodef = quote macro $(macroname)(typedef) typedef.args[2] = :($(typedef.args[2]) <: $$macroname) total_def = $add_field!(typedef, $fields...) if $_has_kwdefs(typedef) # evaluate the with_kw function (not macro), interpolating from this module esc($Parameters.with_kw(total_def, @__MODULE__)) else esc(total_def) end end end esc(:($absdef, $macrodef)) end """ Return the names of fields defined in `fdef`. """ function _fieldnames(fdef::Expr) fdef.head == :block && return Symbol.(filter(!isnothing, (_fieldnames.(fdef.args)))) fdef.head == :(::) && return fdef.args[1] fdef.head == :(=) && return _fieldnames(fdef.args[1]) nothing end _fieldnames(s::Symbol) = s _fieldnames(arb) = nothing """ Return the list of elements in array which occur more than once. """ _duplicates(a) = filter( el -> length(findall(==(el), a)) > 1, unique(a) ) _has_kwdefs(typedef::Expr) = any( (f isa Expr && f.head == :(=) for f in typedef.args[3].args) ) end
DefaultFields
https://github.com/jkosata/DefaultFields.jl.git
[ "MIT" ]
0.0.1
4fe353b814d2306e297db626a1669e6b6aa9f2af
code
1801
using DefaultFields, Test, Parameters abstract type supertype end @with_fields abs_type <: supertype custom_float::Float64 custom_int::Int @abs_type struct new_type orig_field::Dict end @test fieldtype(new_type, :orig_field) == Dict @test fieldtype(new_type, :custom_float) == Float64 @test fieldtype(new_type, :custom_int) == Int @test new_type <: abs_type && new_type <: supertype new_inst = new_type(Dict(), 1.0, 2) @test new_inst isa abs_type @test_throws "syntax: duplicate" @macroexpand @abs_type struct invalid_type; custom_int::Int end @with_fields abs_type_weak custom_float custom_int @abs_type_weak struct new_type_weak orig_field::Dict end @test fieldtype(new_type_weak, :custom_float) == Any @test fieldtype(new_type_weak, :custom_int) == Any @test_throws "syntax: duplicate" @macroexpand @abs_type_weak struct invalid_type; custom_int end @test_throws "syntax: duplicate" @macroexpand @with_fields invalid_type custom_field custom_field ### # Parameters.jl compatibility # to replace Base.@kwdef with @with_kw requires a modification of Parameters.jl to unwrap macrocalls ### @abs_type struct kw_struct new_field new_field_def=1 end @test Set([:new_field, :new_field_def, :custom_int, :custom_float]) == Set(fieldnames(kw_struct)) kw_inst = kw_struct(custom_float=1, custom_int=2, new_field=[]) @test kw_inst.new_field_def == 1 @with_fields abs_def custom_float=1.0 custom_int::Int=4 @abs_def struct struct_with_defs particular end @test Set(fieldnames(struct_with_defs)) == Set([:custom_float, :custom_int, :particular]) @test struct_with_defs(particular=1).custom_int == 4 @test struct_with_defs(particular=1).custom_float == 1.0 @test struct_with_defs(particular=1, custom_int=2, custom_float=0).custom_int == 2 @test struct_with_defs <: abs_def
DefaultFields
https://github.com/jkosata/DefaultFields.jl.git
[ "MIT" ]
0.0.1
4fe353b814d2306e297db626a1669e6b6aa9f2af
docs
1640
![tests](https://github.com/jkosata/DefaultFields.jl/workflows/tests/badge.svg?branch=master) ### DefaultFields.jl This is a simple package to declare abstract types with default fields and their values in Julia. The idea of having this as base functionality is [somewhat disputed](https://github.com/JuliaLang/julia/issues/4935) in the Julia community. I just find it handy sometimes to have a family of types without copypasting blocks of field declarations around. The macro `@with_fields` defines an abstract type and its default fields. It then creates another macro to declare subtypes of this abstract type. The default fields are appended to type-particular field definitions. ```julia julia> using DefaultFields julia> @with_fields abs_type a_def::Int b_def julia> @abs_type struct mystruct c::Float64 end julia> fieldnames(mystruct) (:c, :a_def, :b_def) julia> mystruct(1, 2, []) mystruct(1.0, 2, Any[]) julia> mystruct <: abs_type true ``` ### Default values Default field values can be entered in both the abstract and concrete declarations (see [`Parameters.jl`](https://github.com/mauro3/Parameters.jl) for syntax). With ```julia julia> @with_fields abs_type a_def::Int=5 b_def ``` calling ```julia julia> @abs_type struct mystruct c::Float64=6.0 end ``` Is equivalent to ```julia using Parameters abstract type abs_type end @with_kw struct mystruct <: abs_type c::Float64 = 6.0 a_def::Int = 5 b_def end ``` ### Supertyping ```julia julia> abstract type supertype end julia> @with_fields abs_type <: supertype a_def b_def julia> abs_type <: supertype true ```
DefaultFields
https://github.com/jkosata/DefaultFields.jl.git
[ "MIT" ]
0.2.0
8fe5d02b92242d50f2507d7d3f045a4cdde8a6c2
code
759
using ItPropFit using Documenter DocMeta.setdocmeta!(ItPropFit, :DocTestSetup, :(using ItPropFit); recursive=true) makedocs(; modules=[ItPropFit], authors="Erik-Jan van Kesteren", repo="https://github.com/vankesteren/ItPropFit.jl/blob/{commit}{path}#{line}", sitename="ItPropFit.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://vankesteren.github.io/ItPropFit.jl", edit_link="main", assets=String[], ), pages=[ "Home" => "index.md", "Examples" => "examples.md", "Benchmarks" => "benchmarks.md", "Reference" => "reference.md" ], ) deploydocs(; repo="github.com/vankesteren/ItPropFit.jl", devbranch="dev", )
ItPropFit
https://github.com/vankesteren/ProportionalFitting.jl.git
[ "MIT" ]
0.2.0
8fe5d02b92242d50f2507d7d3f045a4cdde8a6c2
code
3179
""" ArrayFactors(af::Vector{<:AbstractArray}, di::DimIndices) ArrayFactors(af::Vector{<:AbstractArray}, di::Vector) ArrayFactors(af::Vector{<:AbstractArray}) Array factors are defined such that the array's elements are their products: `M[i, j, ..., l] = af[1][i] * af[2][j] * ... * af[3][l]`. The array factors can be vectors or multidimensional arrays themselves. The main use of ArrayFactors is as a memory-efficient representation of a multidimensional array, which can be constructed using the `Array()` method. see also: [`ipf`](@ref), [`ArrayMargins`](@ref), [`DimIndices`](@ref) # Fields - `af::Vector{<:AbstractArray}`: Vector of (multidimensional) array factors - `di::DimIndices`: Dimension indices to which the array factors belong. # Examples ```julia-repl julia> AF = ArrayFactors([[1,2,3], [4,5]]) Factors for array of size (3, 2): [1]: [1, 2, 3] [2]: [4, 5] julia> eltype(AF) Int64 julia> Array(AF) 3×2 Matrix{Int64}: 4 5 8 10 12 15 julia> AF = ArrayFactors([[1,2,3], [4 5; 6 7]], DimIndices([2, [1, 3]])) Factors for 3D array: [2]: [1, 2, 3] [1, 3]: [4 5; 6 7] julia> Array(AF) 2×3×2 Array{Int64, 3}: [:, :, 1] = 4 8 12 6 12 18 [:, :, 2] = 5 10 15 7 14 21 ``` """ struct ArrayFactors{T} af::Vector{<:AbstractArray{T}} di::DimIndices end # Constructor for mixed-type arrayfactors needs promotion before construction function ArrayFactors(af::Vector{<:AbstractArray}, di::DimIndices) AT = eltype(af) PT = promote_type(eltype.(af)...) ArrayFactors(Vector{AT{PT}}(af), di) end # Constructor promoting vector to dimindices ArrayFactors(af::Vector{<:AbstractArray}, di::Vector) = ArrayMargins(af, DimIndices(di)) # Constructor based on factors without dimindices ArrayFactors(af::Vector{<:AbstractArray}) = ArrayFactors(af, default_dimindices(af)) # Overloading base methods function Base.eltype(::Type{ArrayFactors{T}}) where {T} return T end function Base.show(io::IO, AF::ArrayFactors) print(io, "Factors for $(ndims(AF.di))D array:") for i in 1:length(AF.af) print(io, "\n $(AF.di.idx[i]): ") show(io, AF.af[i]) end end Base.size(AF::ArrayFactors) = flatten(size.(AF.af)...)[sortperm(vcat(AF.di.idx...))] Base.length(AF::ArrayFactors) = length(AF.af) """ Array(AF::ArrayFactors{T}) Create an array out of an ArrayFactors object. # Arguments - `A::ArrayFactors{T}`: Array factors # Examples ```julia-repl julia> fac = ArrayFactors([[1,2,3], [4,5], [6,7]]) Factors for array of size (3, 2, 2): 1: [1, 2, 3] 2: [4, 5] 3: [6, 7] julia> Array(fac) 3×2×2 Array{Int64, 3}: [:, :, 1] = 24 30 48 60 72 90 [:, :, 2] = 28 35 56 70 84 105 ``` """ function Base.Array(AF::ArrayFactors{T}) where {T} D = length(AF.di) asize = size(AF) M = ones(T, asize) for d in 1:D idx = AF.di.idx[d] af = AF.af[d] if !issorted(idx) sp = sortperm(idx) idx = idx[sp] af = permutedims(af, sp) end dims = [idx...] shp = ntuple(i -> i ∉ dims ? 1 : asize[popfirst!(dims)], ndims(AF.di)) M .*= reshape(af, shp) end return M end
ItPropFit
https://github.com/vankesteren/ProportionalFitting.jl.git
[ "MIT" ]
0.2.0
8fe5d02b92242d50f2507d7d3f045a4cdde8a6c2
code
3367
""" ArrayMargins(am::Vector{<:AbstractArray}, di::DimIndices) ArrayMargins(am::Vector{<:AbstractArray}, di::Vector) ArrayMargins(am::Vector{<:AbstractArray}) ArrayMargins(X::AbstractArray, di::DimIndices) ArrayMargins(X::AbstractArray) ArrayMargins are marginal sums of an array, combined with the indices of the dimensions these sums belong to. The marginal sums can be multidimensional arrays themselves. There are various constructors for ArrayMargins, based on either raw margins or an actual array from which the margins are then computed. see also: [`DimIndices`](@ref), [`ArrayFactors`](@ref), [`ipf`](@ref) # Fields - `am::Vector{AbstractArray}`: Vector of marginal sums. - `di::DimIndices`: Dimension indices to which the elements of `am` belong. # Examples ```julia-repl julia> X = reshape(1:12, 2, 3, 2) 2×3×2 reshape(::UnitRange{Int64}, 2, 3, 2) with eltype Int64: [:, :, 1] = 1 3 5 2 4 6 [:, :, 2] = 7 9 11 8 10 12 julia> ArrayMargins(X) Margins from 3D array: [1]: [36, 42] [2]: [18, 26, 34] [3]: [21, 57] julia> ArrayMargins(X, [1, [2, 3]]) Margins from 3D array: [1]: [36, 42] [2, 3]: [3 15; 7 19; 11 23] julia> ArrayMargins(X, [2, [3, 1]]) Margins of 3D array: [2]: [18, 26, 34] [3, 1]: [9 12; 27 30] ``` """ struct ArrayMargins{T} am::Vector{<:AbstractArray{T}} di::DimIndices end # Constructor for mixed-type arraymargins needs promotion before construction function ArrayMargins(am::Vector{<:AbstractArray}, di::DimIndices) AT = eltype(am) PT = promote_type(eltype.(am)...) ArrayFactors(Vector{AT{PT}}(am), di) end # Constructor promoting vector to dimindices ArrayMargins(am::Vector{<:AbstractArray}, di::Vector) = ArrayMargins(am, DimIndices(di)) # Constructor based on margins without indices ArrayMargins(am::Vector{<:AbstractArray}) = ArrayMargins(am, default_dimindices(am)) # Constructor based on array function ArrayMargins(X::AbstractArray, di::DimIndices) D = ndims(X) if D != ndims(di) throw(DimensionMismatch("Dimensions of X ($(ndims(X))) mismatch DI ($(ndims(di))).")) end # create the margins am = Vector{AbstractArray{eltype(X)}}() for dim in di.idx notd = Tuple(setdiff(1:D, dim)) mar = dropdims(sum(X; dims = notd); dims = notd) if !issorted(dim) mar = permutedims(mar, sortperm(sortperm(dim))) end push!(am, mar) end return ArrayMargins(am, di) end ArrayMargins(X::AbstractArray) = ArrayMargins(X, DimIndices([1:ndims(X)...])) ArrayMargins(X::AbstractArray, DI::Vector) = ArrayMargins(X, DimIndices(DI)) # Base methods function Base.show(io::IO, AM::ArrayMargins) print(io, "Margins of $(ndims(AM.di))D array:") for i in 1:length(AM.am) print(io, "\n $(AM.di.idx[i]): ") show(io, AM.am[i]) end end Base.size(AM::ArrayMargins) = flatten(size.(AM.am)...)[sortperm(vcat(AM.di.idx...))] Base.length(AM::ArrayMargins) = length(AM.am) Base.ndims(AM::ArrayMargins) = sum(ndims.(AM.am)) # methods for consistency of margins function isconsistent(AM::ArrayMargins; tol::Float64 = eps(Float64)) marsums = sum.(AM.am) return (maximum(marsums) - minimum(marsums)) < tol end function proportion_transform(AM::ArrayMargins) mar = convert.(Vector{Float64}, AM.am) ./ sum.(AM.am) return ArrayMargins(mar, AM.di) end
ItPropFit
https://github.com/vankesteren/ProportionalFitting.jl.git
[ "MIT" ]
0.2.0
8fe5d02b92242d50f2507d7d3f045a4cdde8a6c2
code
2569
""" DimIndices(idx::Vector{Vector{Int}}) DimIndices represent an exhaustive list of indices for the dimensions of an array. It is an object containing a single element, `idx`, which is a nested vector of integers; e.g., `[[2], [1, 3], [4]]`. DimIndices objects are checked for uniqueness and completeness, i.e., all indices up to the largest index are used exactly once. # Fields - `idx::Vector{Vector{Int}}`: nested vector of dimension indices. # Examples ```julia-repl julia> DimIndices([2, [1, 3], 4]) Indices for 4D array: [[2], [1, 3], [4]] ``` """ struct DimIndices idx::Vector{Vector{Int}} # inner constructor checking uniqueness & completeness function DimIndices(idx::Vector{Vector{Int}}) # uniqueness if !allunique(vcat(idx...)) error("Some dimensions were duplicated.") end # completeness D = maximum(maximum.(idx)) dmissing = setdiff(1:D, vcat(idx...)) if length(dmissing) > 0 error("Missing array dimensions: $dmissing.") end return new(idx) end end # convenient constructor DimIndices(X::Vector) = DimIndices(Vector{Union{Int, Vector{Int}}}(X)) function DimIndices(X::Vector{Union{Int, Vector{Int}}}) DimIndices(broadcast((x) -> [x...], X)) end """ default_dimindices(m::Vector{<:AbstractArray}) Create default dimensions from a vector of arrays. These dimensions are assumed to be ordered. For example, for the dimensions will be [[1], [2], [3]]. For [[1, 2], [2 1 ; 3 4]], it will be [[1], [2, 3]]. See also: [`DimIndices`](@ref) # Arguments - `m::Vector{<:AbstractArray}`: Array margins or factors. # Examples ```julia-repl julia> default_dimindices([[1, 2], [2, 1], [3, 4]]) Indices for 3D array: [[1], [2], [3]] julia> default_dimindices([[1, 2], [2 1 ; 3 4]]) Indices for 3D array: [[1], [2, 3]] ``` """ function default_dimindices(m::Vector{<:AbstractArray}) nd = ndims.(m) j = 0 dd = [] for i in nd push!(dd, collect((j+1):(j+i))) j += i end return DimIndices(dd) end # Base methods Base.ndims(DI::DimIndices) = maximum(maximum.(DI.idx)) Base.length(DI::DimIndices) = length(DI.idx) Base.issorted(DI::DimIndices) = issorted(vcat(maximum.(DI.idx)...)) Base.getindex(DI::DimIndices, varargs...) = getindex(DI.idx, varargs...) function Base.show(io::IO, DI::DimIndices) println(io, "Indices for $(ndims(DI))D array:") print("[") for i in 1:length(DI) show(io, DI.idx[i]) if i != length(DI) print(", ") end end print("]") end
ItPropFit
https://github.com/vankesteren/ProportionalFitting.jl.git
[ "MIT" ]
0.2.0
8fe5d02b92242d50f2507d7d3f045a4cdde8a6c2
code
254
module ItPropFit export DimIndices, ArrayMargins, isconsistent, proportion_transform, ArrayFactors, ipf include("DimIndices.jl") include("ArrayMargins.jl") include("ArrayFactors.jl") include("utils.jl") include("ipf.jl") end # module
ItPropFit
https://github.com/vankesteren/ProportionalFitting.jl.git
[ "MIT" ]
0.2.0
8fe5d02b92242d50f2507d7d3f045a4cdde8a6c2
code
5415
""" ipf(X::AbstractArray{<:Real}, mar::ArrayMargins; maxiter::Int = 1000, tol::Float64 = 1e-10) ipf(X::AbstractArray{<:Real}, mar::Vector{<:Vector{<:Real}}) ipf(mar::ArrayMargins) ipf(mar::Vector{<:Vector{<:Real}}) Perform iterative proportional fitting (factor method). The array (X) can be any number of dimensions, and the margins can be multidimensional as well. If only the margins are given, then the seed matrix `X` is assumed to be an array filled with ones of the correct size and element type. If the margins are not an ArrayMargins object, they will be coerced to this type. This function returns the update matrix as an ArrayFactors object. To compute the updated matrix, use `Array(result) .* X` (see examples). see also: [`ArrayFactors`](@ref), [`ArrayMargins`](@ref) # Arguments - `X::AbstractArray{<:Real}`: Array to be adjusted - `mar::ArrayMargins`: Target margins as an ArrayMargins object - `maxiter::Int=1000`: Maximum number of iterations - `tol::Float64=1e-10`: Factor change tolerance for convergence # Examples ```julia-repl julia> X = [40 30 20 10; 35 50 100 75; 30 80 70 120; 20 30 40 50] julia> u = [150, 300, 400, 150] julia> v = [200, 300, 400, 100] julia> AF = ipf(X, [u, v]) Factors for 2D array: [1]: [0.9986403503185242, 0.8833622306385376, 1.1698911437112522, 0.8895042701910321] [2]: [1.616160156063788, 1.5431801747375655, 1.771623700829941, 0.38299396265192226] julia> Z = Array(AF) .* X 4×4 Matrix{Float64}: 64.5585 46.2325 35.3843 3.82473 49.9679 68.1594 156.499 25.3742 56.7219 144.428 145.082 53.7673 28.7516 41.18 63.0347 17.0337 julia> ArrayMargins(Z) Margins of 2D array: [1]: [150.0000000009452, 299.99999999962523, 399.99999999949796, 149.99999999993148] [2]: [200.0, 299.99999999999994, 399.99999999999994, 99.99999999999997] ``` """ function ipf(X::AbstractArray{<:Real}, mar::ArrayMargins; maxiter::Int = 1000, tol::Float64 = 1e-10) # dimension check if ndims(X) != ndims(mar) throw(DimensionMismatch("The number of margins ($(ndims(mar))) needs to equal ndims(X) = $(ndims(X)).")) end array_size = size(X) if array_size != size(mar) throw(DimensionMismatch("The size of the margins $(size(mar)) needs to equal size(X) = $array_size.")) end # margin consistency check if !isconsistent(mar; tol = tol) # transform to proportions @info "Inconsistent target margins, converting `X` and `mar` to proportions. Margin totals: $(sum.(mar.am))" X /= sum(X) mar = proportion_transform(mar) end # initialization (simplified first iteration) J = length(mar) di = mar.di mar_seed = ArrayMargins(X, di) fac = [mar.am[i] ./ mar_seed.am[i] for i in 1:J] X_prod = copy(X) # start iteration iter = 0 crit = 0. for i in 1:maxiter iter += 1 oldfac = deepcopy(fac) for j in 1:J # loop over margin elements # get complement dimensions notj = setdiff(1:J, j) notd = di[notj] # create X multiplied by complement factors for k in 1:(J-1) # loop over complement dimensions # get current dimindex & current factor cur_idx = di[notj[k]] cur_fac = fac[notj[k]] # reorder if necessary for elementwise multiplication if !issorted(cur_idx) sp = sortperm(cur_idx) cur_idx = cur_idx[sp] cur_fac = permutedims(cur_fac, sp) end # create correct shape for elementwise multiplication dims = copy(cur_idx) shp = ntuple(i -> i ∉ dims ? 1 : array_size[popfirst!(dims)], ndims(di)) # perform elementwise multiplication if k == 1 X_prod = X .* reshape(cur_fac, shp) else X_prod .*= reshape(cur_fac, shp) end end # then we compute the margin by summing over all complement dimensions complement_dims = Tuple(vcat(notd...)) cur_sum = dropdims(sum(X_prod; dims = complement_dims), dims = complement_dims) if !issorted(di[j]) # reorder if necessary for elementwise division cur_sum = permutedims(cur_sum, sortperm(sortperm(di[j]))) end # update this factor fac[j] = mar.am[j] ./ cur_sum end # convergence check crit = maximum(broadcast(x -> maximum(abs.(x)), fac - oldfac)) if crit < tol break end end if iter == maxiter @warn "Did not converge. Try increasing the number of iterations. Maximum absolute difference between subsequent iterations: $crit" else @info "Converged in $iter iterations." end return ArrayFactors(fac, di) end function ipf(X::AbstractArray{<:Real}, mar::Vector{<:Vector{<:Real}}; maxiter::Int = 1000, tol::Float64 = 1e-10) ipf(X, ArrayMargins(mar); maxiter = maxiter, tol = tol) end function ipf(mar::ArrayMargins{T}; maxiter::Int = 1000, tol::Float64 = 1e-10) where T ipf(ones(T, size(mar)), mar; maxiter = maxiter, tol = tol) end function ipf(mar::Vector{<:Vector{<:Real}}; maxiter::Int = 1000, tol::Float64 = 1e-10) ipf(ArrayMargins(mar); maxiter = maxiter, tol = tol) end
ItPropFit
https://github.com/vankesteren/ProportionalFitting.jl.git
[ "MIT" ]
0.2.0
8fe5d02b92242d50f2507d7d3f045a4cdde8a6c2
code
446
# flatten nested tuples into single tuple # https://discourse.julialang.org/t/efficient-tuple-concatenation/5398/10 flatten(x::Tuple) = x flatten(x::Tuple, y::Tuple) = (x..., y...) flatten(x::Tuple, y::Tuple, z::Tuple...) = (x..., flatten(y, z...)...) # dict methods for future reference Base.Dict(AM::ArrayMargins) = Dict(AM.di[i] => AM.am[i] for i in 1:length(AM)) Base.Dict(AF::ArrayFactors) = Dict(AF.di[i] => AF.af[i] for i in 1:length(AF))
ItPropFit
https://github.com/vankesteren/ProportionalFitting.jl.git
[ "MIT" ]
0.2.0
8fe5d02b92242d50f2507d7d3f045a4cdde8a6c2
code
4342
using Test, ItPropFit @testset "DimIndices" begin # Basic object & method di = DimIndices([1, [2, 3], [4, 5, 6]]) @test typeof(di) == DimIndices @test length(di) == 3 @test ndims(di) == 6 # test completeness @test_throws ErrorException DimIndices([2, 1, [5, 4, 6]]) # test uniqueness @test_throws ErrorException DimIndices([[2, 3, 2], 1, [5, 4, 6]]) end @testset "ArrayMargins" begin # Basic object & methods di = DimIndices([1, 2]) mar = ArrayMargins([[22, 26, 30], [6, 15, 24, 33]], di) @test typeof(mar) == ArrayMargins{Int} @test length(mar) == 2 @test size(mar) == (3, 4) # Consistency check @test isconsistent(mar) mar_p = proportion_transform(mar) @test sum.(mar_p.am) == [1., 1.] # Constructors mar2 = ArrayMargins([[22, 26, 30], [6, 15, 24, 33]]) @test mar.am == mar2.am && mar.di.idx == mar2.di.idx X = [1 4 7 10 2 5 8 11 3 6 9 12] mar3 = ArrayMargins(X) @test mar.am == mar3.am && mar.di.idx == mar3.di.idx mar4 = ArrayMargins(X, DimIndices([2, 1])) @test mar.am == reverse(mar4.am) && mar.di.idx == reverse(mar4.di.idx) mar5 = ArrayMargins(X, DimIndices([[2, 1]])) @test mar5.am[1] == X' end @testset "ArrayFactors" begin # Basic object & methods di = DimIndices([1, 2]) fac = ArrayFactors([[1,2,3], [4,5]], di) @test size(fac) == (3, 2) @test eltype(fac) == Int64 @test Array(fac) == [4 5 ; 8 10 ; 12 15] # constructors fac2 = ArrayFactors([[1,2,3], [4, 5]]) @test fac.af == fac2.af && fac.di.idx == fac2.di.idx fac3 = ArrayFactors([[4, 5], [1, 2, 3]], DimIndices([2, 1])) @test Array(fac) == Array(fac3) # multidimensional madness di = DimIndices([1, [2, 3], 4, [5, 6, 7]]) f1 = [.1, .6] f2 = [3. 2. 1. ; 6. 5. 4.] f3 = [.5, .1, .9] f4 = reshape(1.0:12.0, 2, 3, 2) fac4 = ArrayFactors([f1, f2, f3, f4], di) @test length(Array(fac4)) == prod(size(fac4)) di = DimIndices([1, [3, 2], 4, [5, 6, 7]]) fac5 = ArrayFactors([f1, f2', f3, f4], di) @test Array(fac4) ≈ Array(fac5) # nb: approx because floating point errors di = DimIndices([4, [3, 2], 1, [5, 6, 7]]) fac6 = ArrayFactors([f3, f2', f1, f4], di) @test Array(fac4) ≈ Array(fac6) di = DimIndices([4, [3, 2], 1, [7, 5, 6]]) fac7 = ArrayFactors([f3, f2', f1, permutedims(f4, [3, 1, 2])], di) @test Array(fac4) ≈ Array(fac7) end @testset "Two-dimensional ipf" begin # Basic example with convenient interface X = [40 30 20 10; 35 50 100 75; 30 80 70 120; 20 30 40 50] u = [150, 300, 400, 150] v = [200, 300, 400, 100] AF = ipf(X, [u, v]) X_prime = Array(AF) .* X AM = ArrayMargins(X_prime) @test AM.am ≈ [u, v] # Margins only AF = ipf([u, v]) AM = ArrayMargins(Array(AF)) @test AM.am ≈ [u, v] # Inconsistent margins w = [15, 30, 40, 15] AF = ipf(X, [w, v]) AM = ArrayMargins(X ./ sum(X) .* Array(AF)) @test AM.am ≈ [w ./ sum(w), v ./ sum(v)] # Large 100 x 100 matrix X = reshape(repeat(1:16, 625), 100, 100) Y = reshape(repeat(1:5, 2000), 100, 100) + X m = ArrayMargins(Y) AF = ipf(X, m) X_prime = Array(AF) .* X AM = ArrayMargins(X_prime) @test AM.am ≈ m.am end @testset "Multidimensional ipf" begin # Small three-dimensional case X = reshape(1:12, 2, 3, 2) m = ArrayMargins([[48, 60], [28, 36, 44], [34, 74]]) AF = ipf(X, m) X_prime = Array(AF) .* X AM = ArrayMargins(X_prime) @test AM.am ≈ m.am # large five-dimensional case X = reshape(repeat(1:12, 100), 6, 4, 2, 5, 5) Y = reshape(repeat(1:5, 240), 6, 4, 2, 5, 5) + X m = ArrayMargins(Y) AF = ipf(X, m) X_prime = Array(AF) .* X AM = ArrayMargins(X_prime) @test AM.am ≈ m.am # large five-dimensional case with multidimensional margins di = DimIndices([[1, 2], [3, 4, 5]]) m = ArrayMargins(Y, di) AF = ipf(X, m) X_prime = Array(AF) .* X AM = ArrayMargins(X_prime, di) @test AM.am ≈ m.am # large five-dimensional case with unordered multidimensional margins di = DimIndices([[1, 4], [5, 2, 3]]) m = ArrayMargins(Y, di) AF = ipf(X, m) X_prime = Array(AF) .* X AM = ArrayMargins(X_prime, di) @test AM.am ≈ m.am end
ItPropFit
https://github.com/vankesteren/ProportionalFitting.jl.git
[ "MIT" ]
0.2.0
8fe5d02b92242d50f2507d7d3f045a4cdde8a6c2
docs
1657
# ItPropFit.jl [![CI](https://github.com/vankesteren/ItPropFit.jl/actions/workflows/CI.yml/badge.svg)](https://github.com/vankesteren/ItPropFit.jl/actions/workflows/CI.yml) Multidimensional iterative proportional fitting in Julia. [ItPropFit](https://github.com/vankesteren/ItPropFit.jl) implements a multidimensional version of the [factor estimation method](https://en.wikipedia.org/wiki/Iterative_proportional_fitting#Algorithm_2_(factor_estimation)) for performing iterative proportional fitting (also called RAS algorithm, raking, matrix scaling) ## Showcase See the full documentation and getting started [here](https://vankesteren.github.io/ItPropFit.jl/). ```julia using ItPropFit # matrix to be adjusted X = [40 30 20 10; 35 50 100 75; 30 80 70 120; 20 30 40 50] # target margins u = [150, 300, 400, 150] v = [200, 300, 400, 100] # Perform iterative proportional fitting fac = ipf(X, [u, v]) ``` ``` [ Info: Converged in 8 iterations. Factors for 2D array: [1]: [0.9986403503185242, 0.8833622306385376, 1.1698911437112522, 0.8895042701910321] [2]: [1.616160156063788, 1.5431801747375655, 1.771623700829941, 0.38299396265192226] ``` ```julia # compute adjusted matrix Z = Array(fac) .* X ``` ``` 4×4 Matrix{Float64}: 64.5585 46.2325 35.3843 3.82473 49.9679 68.1594 156.499 25.3742 56.7219 144.428 145.082 53.7673 28.7516 41.18 63.0347 17.0337 ``` ```julia # check that the margins are indeed [u, v] ArrayMargins(Z) ``` ``` Margins of 2D array: [1]: [150.0000000009452, 299.99999999962523, 399.99999999949796, 149.99999999993148] [2]: [200.0, 299.99999999999994, 399.99999999999994, 99.99999999999997] ```
ItPropFit
https://github.com/vankesteren/ProportionalFitting.jl.git
[ "MIT" ]
0.2.0
8fe5d02b92242d50f2507d7d3f045a4cdde8a6c2
docs
711
# Benchmarks ```@setup bench using BenchmarkTools, ItPropFit, Logging Logging.disable_logging(Logging.Info) ``` The benchmarks below were run on Julia 1.7.2. ### Default example ```@example bench X = [40 30 20 10; 35 50 100 75; 30 80 70 120; 20 30 40 50] u = [150, 300, 400, 150] v = [200, 300, 400, 100] @benchmark ipf(X, [u, v]) ``` ### Large contingency table ```@example bench X = reshape(repeat(1:16, 625), 100, 100) Y = reshape(repeat(1:5, 2000), 100, 100) + X m = ArrayMargins(Y) @benchmark ipf(X, m) ``` ### Six-dimensional contingency table ```@example bench X = reshape(repeat(1:12, 100), 6, 4, 2, 5, 5) Y = reshape(repeat(1:5, 240), 6, 4, 2, 5, 5) + X m = ArrayMargins(Y) @benchmark ipf(X, m) ```
ItPropFit
https://github.com/vankesteren/ProportionalFitting.jl.git
[ "MIT" ]
0.2.0
8fe5d02b92242d50f2507d7d3f045a4cdde8a6c2
docs
1823
# Examples ## Regression poststratification ```@example pstrat using StatsKit, FreqTables, ItPropFit ``` First, we generate some fake data with demographic characteristics. ```@example pstrat N = 100 p_sex = Categorical([0.49, 0.51]) p_edu = Categorical([0.1, 0.3, 0.4, 0.2]) p_age = Categorical([0.1, 0.3, 0.3, 0.2, 0.1]) p_inc = LogNormal(5, 3) p_opn = Normal(0, 3) df = DataFrame( :sex => CategoricalArray(["m", "f"][rand(p_sex, N)]), :edu => CategoricalArray(["no", "lo", "med", "hi"][rand(p_edu, N)], ordered = true), :age => CategoricalArray(["<10", "11<25", "26<50", "51<70", ">70"][rand(p_age, N)], ordered = true), :inc => rand(p_inc, N) ) df.opn = 1.5 .+ log.(df.inc) .* .1 + rand(p_opn, N) df ``` Then, we create post-stratification weights based on population-level margins using the background characteristics through ItPropFit. ```@example pstrat # Create a cross-table of background characteristics tab = freqtable(df, :sex, :edu, :age) # Create margins from the population (aggregates obtained from statistical agency) pop_margins = ArrayMargins([[0.49, 0.51], [0.05, 0.2, 0.5, 0.25], [0.1, 0.2, 0.4, 0.15, 0.15]]) # Compute array factors fac = ipf(Array(tab), pop_margins) # Compute adjusted table tab_adj = Array(fac) .* tab ``` Create weights by looking up the adjusted counts and then performing normalization. ```@example pstrat # Create a poststratification weight variable by lookup from the table df.w = [tab_adj[row...] for row in eachrow(df[:, [:sex, :edu, :age]])] df.w = df.w ./ sum(df.w) .* N # normalize the weights ``` Let's take a look at how our regression estimates change! ```@example pstrat # perform unweighted regression frm = @formula(opn ~ log(inc)) res = lm(frm, df) ``` ```@example pstrat # perform weighted regression res_w = lm(frm, df, wts = df.w) ```
ItPropFit
https://github.com/vankesteren/ProportionalFitting.jl.git
[ "MIT" ]
0.2.0
8fe5d02b92242d50f2507d7d3f045a4cdde8a6c2
docs
3486
# ItPropFit Multidimensional iterative proportional fitting in Julia. [ItPropFit](https://github.com/vankesteren/ItPropFit.jl) implements a multidimensional version of the [factor estimation method](https://en.wikipedia.org/wiki/Iterative_proportional_fitting#Algorithm_2_(factor_estimation)) for performing iterative proportional fitting (also called RAS algorithm, raking, matrix scaling). In the two-dimensional case, iterative proportional fitting means changing a matrix $X$ to have marginal sum totals $u, v$. One prime use is in survey data analysis, where $X$ could be your data's cross-tabulation of demographic characteristics, and $u, v$ the known population proportions of those characteristics. ## Getting started ```@setup ex using ItPropFit ``` Assume you have a matrix `X`: ```@example ex X = [40 30 20 10; 35 50 100 75; 30 80 70 120; 20 30 40 50] ``` And the row and column margins of another matrix `Y` (`u` and `v`, respectively) but not the full matrix: ```@example ex u = [150, 300, 400, 150] v = [200, 300, 400, 100] ``` Then the `ipf` function from ItPropFit will find the array factors which adjust matrix `X` to have the margins `u` and `v`: ```@example ex fac = ipf(X, [u, v]) ``` Array factors (`ArrayFactors`) are a specific type exported by ItPropFit with a few methods, for example `Array()`: ```@example ex Array(fac) ``` To create the adjusted matrix `Z` with the margins `u` and `v`, we perform elementwise multiplication of this matrix with `X`: ```@example ex Z = Array(fac) .* X ``` We can then check that the marginal sum totals are correct: ```@example ex ArrayMargins(Z) ``` ## Inconsistent margins If the margins are inconsistent (i.e., the margins do not sum to the same amounts) then both `X` and the margins will be transformed to proportions. ```@example ex m = ArrayMargins([[12, 23, 14, 35], [17, 44, 12, 33]]) af = ipf(X, m) ``` Then, `Z` needs to be computed in a different way as well: ```@example ex X_prop = X ./ sum(X) Z = X_prop .* Array(af) ``` ## Multidimensional arrays ItPropFit can also deal with multidimensional arrays of arbitrary shape. For example, consider the following `(3, 2, 3)` array and target margins: ```@example ex X = reshape(1:12, 2, 3, 2) m = [[48, 60], [28, 36, 44], [34, 74]] ``` Now we can run `ipf` to compute the adjustment: ```@example ex fac = ipf(X, m) ``` And we can create the adjusted array `Z`: ```@example ex Array(fac) .* X ``` ## Multidimensional margins ItPropFit can also deal with multidimensional margins of arbitrary shape. For example, consider the same `(3, 2, 3)` array as before: ```@example ex X = reshape(1:12, 2, 3, 2) ``` We have multidimensional target margins (a 1D vector and a 2D matrix): ```@example ex m1 = [48, 60] m2 = [9 11 14; 19 25 30] mar = [m1, m2] ``` Here, `m1` belongs to the first dimension of target matrix, and `m2` belongs to the third and second dimension (in that order). This can be encoded in a `DimIndices` object as follows: ```@example ex dimid = DimIndices([1, [3, 2]]) ``` Together, the margins and dimension indices they belong to constitute an `ArrayMargins` object: ```@example ex m = ArrayMargins(mar, dimid) ``` Now we can run `ipf` to compute the adjustment: ```@example ex fac = ipf(X, m) ``` And we can create the adjusted array `Z`: ```@example ex Z = Array(fac) .* X ``` We then also use `ArrayMargins` to check whether the margins of this array are indeed as expected! ```@example ex ArrayMargins(Z, dimid) ```
ItPropFit
https://github.com/vankesteren/ProportionalFitting.jl.git
[ "MIT" ]
0.2.0
8fe5d02b92242d50f2507d7d3f045a4cdde8a6c2
docs
107
```@meta CurrentModule = ItPropFit ``` # Reference ```@index ``` ```@autodocs Modules = [ItPropFit] ```
ItPropFit
https://github.com/vankesteren/ProportionalFitting.jl.git
[ "MIT" ]
1.0.0
793203c510c8c1c6f496c75c75588c4c94d082f2
code
1744
module Smoothing export binomial """ binomial(data::Vector{any}, Nₚ::Int) Takes a 1d data array and smooths the data with a 2Nₚ+1 binomial filter. This is computed using the method outlined in :<br> *Binomial smoothing filter: A way to avoid some pitfalls of least‐squares polynomial smoothing* in Review of Scientific Instruments 54, 1034 (1983); https://doi.org/10.1063/1.1137498 <br> or see <br> https://aip.scitation.org/doi/abs/10.1063/1.1137498 The method implements a 2Nₚ+1 binomial filter by Nₚ passes of the three point binomial filter; and this is computationally implemented by two passess of the {1,1}/2 smoothing implemented below. The filter preserves the values starting and ending values of the initial data set. # Examples (you can easily manually verify data1's smoothing is correct.) ```julia-repl julia> data1 = [1.0, 2.0, 3.0, 4.0, 5.0] julia> data2 = [3.0, 6.0, 1.0, 4.0, 0.0] julia> binomial(data1, 1) 5-element Vector{Float64}: 1.0 2.0 3.0 4.0 5.0 julia> binomial(data2, 20) 5-element Vector{Float64}: 3.0 2.3162835515104234 1.5937387603335083 0.8162830746732652 0.0 ``` """ function binomial(data::Vector, Nₚ::Int) y = data for pass in 1:Nₚ x = zeros(length(data)) for i in 1:length(y) if i==1 x[i] = (y[i] + y[i+1])/2.0 elseif i>1 && i<length(y) x[i] = (y[i] + y[i+1])/2.0 end end y = zeros(length(data)) for j in 1:length(x) if j==1 y[j] = data[j] elseif j>1 && j<length(x) y[j] = (x[j-1] + x[j])/2.0 else y[j] = data[j] end end end return y end end # module
Smoothing
https://github.com/paulnakroshis/Smoothing.jl.git
[ "MIT" ]
1.0.0
793203c510c8c1c6f496c75c75588c4c94d082f2
code
442
using Smoothing using Test @test Smoothing.binomial([1.0,2.0,3.0,4.0,5.0], 1) == [1.0,2.0,3.0,4.0,5.0] @test Smoothing.binomial([1.0,2.0,3.0,4.0,5.0], 3) == [1.0,2.0,3.0,4.0,5.0] println("Passed Smoothing of counting numbers tests (1 and 3 pass)") @test Smoothing.binomial([0.0,2.0,4.0,6.0,4.0, 2.0, 0.0], 1) == [0.0, 2.0, 4.0, 5.0, 4.0, 2.0, 0.0] println("Passed Smoothing of manually created triangle pulse") println("3 Tests passed!")
Smoothing
https://github.com/paulnakroshis/Smoothing.jl.git
[ "MIT" ]
1.0.0
793203c510c8c1c6f496c75c75588c4c94d082f2
docs
784
# Smoothing.jl A package to smooth time series data in Julia. <br> Currently v1.0 only includes binomial smoothing. Takes a 1d data array and smooths the data with a 2Nₚ+1 binomial filter. This is computed using the method outlined in :<br> *Binomial smoothing filter: A way to avoid some pitfalls of least‐squares polynomial smoothing* <br> in Review of Scientific Instruments 54, 1034 (1983); https://doi.org/10.1063/1.1137498 <br> The filter preserves the values starting and ending values of the initial data set. ### Example (you can easily manually verify my_data's smoothing is correct.) Usage: ```julia-repl julia> using Smoothing julia> my_data = [1.0, 2.0, 3.0, 4.0, 5.0] julia> Smoothing.binomial(my_data, 1) 5-element Vector{Float64}: 1.0 2.0 3.0 4.0 5.0 ```
Smoothing
https://github.com/paulnakroshis/Smoothing.jl.git
[ "MIT" ]
0.2.0
ebe090fc0a0f83685b5bfd7d1eb3fd870bbd1773
code
401
using Documenter using SolverLogging makedocs( sitename = "SolverLogging.jl", format = Documenter.HTML( prettyurls = !("local" in ARGS), ansicolor=true ), pages = [ "Introduction" => "index.md", "API" => "api.md", "Examples" => "examples.md" ] ) deploydocs( repo = "github.com/bjack205/SolverLogging.jl.git", devbranch = "master" )
SolverLogging
https://github.com/bjack205/SolverLogging.jl.git
[ "MIT" ]
0.2.0
ebe090fc0a0f83685b5bfd7d1eb3fd870bbd1773
code
1585
module SolverLogging using Printf using Formatting using Crayons using Logging include("utils.jl") include("conditional_crayon.jl") include("logger.jl") # include("default_logger.jl") include("setentry.jl") # Set entries in default logger """ @log [logger] args... Logs the data with `logger`, which is the default logger if not provided. Can be any of the following forms: @log "name" 1.0 # literal value @log "name" 2a # an expression @log "name" name # a variable @log name # shortcut for previous If the specified entry is active at the current verbosity level, """ macro log(args...) return log_expr(args...) end # Use the symbol as the string name # e.g. `@log α`` logs the value of α in the "α" field function log_expr(logger, ex::Symbol) name = string(ex) _log_expr(logger, name, ex) end # Pass-through to actual function log_expr(logger, name::String, ex) = _log_expr(logger, name, ex) log_expr(logger, name::String, ex, op::QuoteNode) = _log_expr(logger, name, ex, op) function _log_expr(logger, name::String, expr, op::QuoteNode=QuoteNode(:replace)) quote let lg = $(esc(logger)) # @debug "Calling @log on $name" if isenabled(lg) # espec = lg.fmt[$name] # if lg.opts.curlevel <= espec.level _log!(lg, $name, $(esc(expr)), $op) # end end end end end export setentry, Logger, @log, printheader, printrow, printlog, setlevel!, ConditionalCrayon end # module
SolverLogging
https://github.com/bjack205/SolverLogging.jl.git
[ "MIT" ]
0.2.0
ebe090fc0a0f83685b5bfd7d1eb3fd870bbd1773
code
2433
""" ConditionalCrayon Sets conditional formatting for printing to the terminal. Each `ConditionalCrayon` specifies a function `bad(x)` that returns `true` if the argument `x` is not acceptable, printing with color `cbad`, and a function `good(x)` that returns `true` if `x` is acceptable, printing with color `cgood`. If neither are true then `cdefault` is the color. The `bad` function will be checked before `good`, so takes precedence if both happen to return `true`. This is not checked. All colors must be specified as a Crayon type from Crayons.jl # Constructors Usage will generally be through the following constructor: ConditionalCrayon(badfun::Function, goodfun::Function; [goodcolor, badcolor, defaultcolor]) The colors default to green for good, red for bad, and default color (`Crayon(reset=true)`) for the default. For convenience when working with ranges, the following constructor is also provided: ConditionalCrayon(lo, hi; [reverse, goodcolor, badcolor, defaultcolor]) Which will be good if the value is less than `lo` and bad if it's higher than `hi`. This is reversed if `reverse=true`. A default constructor ConditionalCrayon() Is also provided, which always returns the default color. # Usage The `ConditionalCrayon` is a functor object that accepts a single argument of any type, and returns the `Crayon` according to the output of the `good` and `bad` functions on that input. It's the user's responsibility to make sure the input type is appropriate for the functions (since these are all user-specified). """ struct ConditionalCrayon cgood::Crayon cdefault::Crayon cbad::Crayon bad::Function good::Function end ConditionalCrayon() = ConditionalCrayon(x->false, x->false) function ConditionalCrayon(badfun::Function, goodfun::Function; goodcolor=crayon"green", badcolor=crayon"red", defaultcolor=Crayon(reset=true) ) ConditionalCrayon(goodcolor, defaultcolor, badcolor, badfun, goodfun) end function ConditionalCrayon(lo, hi; reverse::Bool=false, kwargs...) @assert lo <= hi if reverse badfun = x->x < lo goodfun = x->x >= hi else badfun = x->x > hi goodfun = x->x <= lo end ConditionalCrayon(badfun, goodfun; kwargs...) end function (c::ConditionalCrayon)(v) if c.bad(v) return c.cbad elseif c.good(v) return c.cgood else return c.cdefault end end
SolverLogging
https://github.com/bjack205/SolverLogging.jl.git
[ "MIT" ]
0.2.0
ebe090fc0a0f83685b5bfd7d1eb3fd870bbd1773
code
11749
const DEFAULT_LEVEL = 1 const DEFAULT_WIDTH = 10 struct EntrySpec type::DataType fmt::String # C-style format string uid::UInt16 # unique ID, corresponds to the order the entry was added level::UInt8 # verbosity level. 0 always prints. Higher number -> lower priority width::UInt8 # column width in characters ccrayon::ConditionalCrayon end EntrySpec(T::DataType, fmt::String, eid, level=DEFAULT_LEVEL, width=DEFAULT_WIDTH; ccrayon=ConditionalCrayon()) = EntrySpec(T, fmt, UInt16(eid), UInt8(level), UInt8(width), ccrayon) Base.@kwdef mutable struct LoggerOpts curlevel::UInt8 = DEFAULT_LEVEL freq::UInt16 = 10 # how often header prints _count::UInt16 = 0 # internal counter headerstyle::Crayon = crayon"bold blue" linechar::Char = '—' enable::Bool = true autosize::Bool = true # automatically expand columns end """ SolverLogger.Logger A logger designed to print tabulated data that can be updated at any point. It supports varying verbosity levels, each including all of the information from previous levels. # Constructor SolverLogger.Logger(io=stdout; opts...) SolverLogger.Logger(filename; opts...) The constructor can take either an `IO` object or a filename, in which case it will be opened with write permissions, replacing any existing contents. The keyword arguments `opts` are one of the following: * `curlevel` Current verbosity level of the solver. A non-negative integer. * `freq` A non-negative integer specifying how often the header row should be printed. * `headerstyle` A `Crayon` specifying the style of the header. * `linechar` A `Char` that is used for the deliminating row underneath the header. Set to `\0` to not print a row below the header. * `enable` Enabled/disabled state of the logger at construction. # Typical Usage The fields to be printed are specified before use via [`setentry`](@ref). Here the user can specify properties of the field such as the width of the column, format specifications (such as number of decimal places, numeric format, alignment, etc.), column index, and even conditional formatting via a [`ConditionalCrayon`](@ref). Each field is assigned a fixed verbosity level, and is only printed if the current verbosity level of the logger, set via [`setlevel!`](@ref) is greater than or equal to the level of the field. Once all the fields for the logger have been specified, typical usage is via the [`@log`](@ref) macro: @log logger "iter" 1 @log logger "cost" cost * 10 # supports expressions @log logger "alpha" alpha @log logger alpha # shortcut for the previous All calls to `@log` overwrite any previous data. Data is only stored in the logger if the field is active at the current verbosity. To print the log, the easiest is via the [`printlog`](@ref) function, which will automatically print the header rows for you, at the frequency specified by `logger.opts.freq`. The period can be reset (printing a header at the next call to `printlog`) via [`resetcount!`](@ref). For more control, the header and rows can be printed directly via [`printheader`](@ref) and [`printrow`](@ref). The logger can be completely reset via [`resetlogger!`](@ref). # Enabling / Disabling The logger can be enable/disabled via `SolverLogging.enable` and `SolverLogging.disable`. This overwrites the verbosity level. """ struct Logger io::IO fmt::Dict{String,EntrySpec} # Collection of entry specifications. UID for each entry is automatically assigned fmtfun::Dict{String,Function} idx::Vector{Int16} # determines column order. idx[id] gives the column for entry with id. data::Vector{String} crayons::Vector{Crayon} defaults::Dict{DataType,String} opts::LoggerOpts end function Logger(io::IO=Base.stdout; opts...) fmt = Dict{String,EntrySpec}() fmtfun = Dict{String,Function}() idx = UInt16[] data = String[] crayons = Crayon[] defaults = _default_formats() Logger(io, fmt, fmtfun, idx, data, crayons, defaults, LoggerOpts(; opts...)) end Logger(filename::AbstractString; kwargs...) = Logger(open(filename, "w"); kwargs...) isenabled(log::Logger) = log.opts.enable enable(log::Logger) = log.opts.enable = true disable(log::Logger) = log.opts.enable = false function _default_formats() Dict( AbstractFloat => "%.2e", AbstractString => "%s", Integer => "%d", Any => "%s" # default to string printing ) end """ empty!(log::Logger) Clears out all data from logger and restores it to the default configuration. Users should prefer to use [`resetlogger!`](@ref) which calls this function. """ function Base.empty!(log::Logger) empty!(log.fmt) empty!(log.fmtfun) empty!(log.idx) empty!(log.data) empty!(log.defaults) merge!(log.defaults, _default_formats()) return log end function clear!(log::Logger) level = getlevel(log) for (k,v) in pairs(log.fmt) idx = log.idx[v.uid] if v.level > level log.data[idx] = "" else log.data[idx] = " "^v.width end end end """ resetcount!(logger) Resets the row counter such that the subsequent call to [`printlog`](@ref) will print a header row, and start the count from that point. """ resetcount!(log::Logger) = log.opts._count = 0 """ resetlogger!(logger) Resets the logger to the default configuration. All current data will be lost, including all fields and default formats. """ resetlogger!(log::Logger) = begin empty!(log); resetcount!(log) end """ _log!(logger, name, val) Internal method for logging a value with the logger. Users should prefer to use the [`@log`](@ref) macro. If `name` is a registered field, `val` will be stored in the logger. Internally, this method converts `val` to a string using the format specifications and calculates the color using the [`ConditionalCrayon`](@ref) for the entry. """ function _log!(log::Logger, name::String, val, op::Symbol=:replace) if haskey(log.fmt, name) espec = log.fmt[name] if espec.level <= log.opts.curlevel idx = log.idx[espec.uid] fun = log.fmtfun[espec.fmt] crayon = espec.ccrayon(val) if op == :replace log.data[idx] = rpad(log.fmtfun[espec.fmt](val), espec.width) elseif op == :append if espec.type <: AbstractString data0 = rstrip(log.data[idx]) newdata = log.fmtfun[espec.fmt](string(val)) if all(isspace, data0) data = newdata elseif data0[end] == '.' data = data0 * " " * newdata else data = data0 * ". " * newdata end log.data[idx] = rpad( data, espec.width) else @warn "Cannot append to a non-string entry." end elseif op == :add if espec.type <: Number data0 = parse(espec.type, rstrip(log.data[idx])) log.data[idx] = rpad(log.fmtfun[espec.fmt](val + data0), espec.width) else @warn "Cannot add to a non-numeric field. Use :append for strings." end end log.crayons[idx] = crayon @debug "Logging $name with value $val at index $idx" if length(log.data[idx]) > espec.width if log.opts.autosize newwidth = round(Int, length(log.data[idx])*1.5) setentry(log, name, width = newwidth) log.opts._count = 0 log.data[idx] = rpad(log.data[idx], newwidth) else @warn "Entry for $name ($(log.data[idx])) is longer than field width ($(espec.width)). Alignment may be affected. Try increasing the field width." end end else @debug "Not logging $name, level not high enough" end return nothing else @debug "Rejecting log for $name with value $val" end end """ getlevel(logger) Gets the current verbosity level for the logger. """ getlevel(logger::Logger) = logger.opts.curlevel """ setlevel!(logger, level) Set the verbosity level for the logger. High levels prints more information. Returns the previous verbosity level. """ function setlevel!(log::Logger, level) prevlvl = log.opts.curlevel log.opts.curlevel = level # Reset all levels that are no longer active for (k,v) in pairs(log.fmt) idx = log.idx[v.uid] if v.level > level log.data[idx] = "" else log.data[idx] = rpad(log.data[idx], v.width) end end return prevlvl end """ printheader(logger) Prints the header row(s) for the logger, including only the entries that are active at the current verbosity level. The style of the header can be changed via `logger.opts.headerstyle`, which is a Crayon that applies to the entire header. The repeated character under the header can be specified via `logger.opts.linechar`. This value can be set to the null character `\0` if this line should be excluded. """ function printheader(log::Logger) isenabled(log) || return _printheader(log.io, log) return nothing end function _printheader(io::IOStream, log::Logger) header = formheader(log) println(io, header) if log.opts.linechar != '\0' println(io, repeat(log.opts.linechar, length(header))) end end function _printheader(io::IO, log::Logger) header = formheader(log) println(log.opts.headerstyle(header)) if log.opts.linechar != '\0' println(log.opts.headerstyle(repeat(log.opts.linechar, length(header)))) end end """ formheader(logger) Outputs the header as a string """ function formheader(log::Logger) names = fill("", length(log.idx)) for (k,v) in pairs(log.fmt) idx = log.idx[v.uid] if v.level <= log.opts.curlevel names[idx] = rpad(k, v.width) end end header = "" for name in names header *= name end return header end """ printrow(logger) Prints the data currently stored in the logger. Any entries with a [`ConditionalCrayon`](@ref) will be printed in the specified color. Only prints the data for the current verbosity level. """ function printrow(log::Logger) isenabled(log) || return _printrow(log.io, log) log.opts._count += 1 return nothing end function _printrow(io::IOStream, log::Logger) for v in log.data print(io,v) end println(io) flush(io) end function _printrow(io::IO, log::Logger) for (c,v) in zip(log.crayons, log.data) print(c,v) end println() flush(stdout) end """ formrow(logger) Outputs the data for the current verbosity level as a string. """ function formrow(log::Logger) row = "" for v in log.data row *= v end return row end """ printlog(logger) Prints the data currently in the logger, automatically printing the header at the frequency specified by `logger.opts.freq`. The period of the header can be reset using [`resetcount!`](@ref). """ function printlog(log::Logger) cnt, freq = log.opts._count, log.opts.freq if cnt % freq == 0 printheader(log) resetcount!(log) end printrow(log) end # Gets the index of the field `name` @inline getidx(log::Logger, name::String) = log.idx[log.fmt[name].uid] _getdata(log::Logger, name::String) = log.data[getidx(log, name)]
SolverLogging
https://github.com/bjack205/SolverLogging.jl.git
[ "MIT" ]
0.2.0
ebe090fc0a0f83685b5bfd7d1eb3fd870bbd1773
code
5229
""" setentry(logger, name::String, type; kwargs...) Used to add a new entry/field or modify an existing entry/field in the `logger`. # Adding a new entry Specify a unique `name` to add a new entry to the logger. The `type` is used to provide reasonable formatting defaults and must be included. The keyword arguments control the behavior/formatting of the field: * `fmt` A C-style format string used to control the format of the field * `index` Column for the entry in the output. Negative numbers insert from the end. * `level` Verbosity level for the entry. A higher level will be printed less often. Level 0 will always be printed, unless the logger is disabled. Prefer to use a minimum level of 1. * `width` Width of the column. Data is left-aligned to this width. * `ccrayon` A [`ConditionalCrayon`](@ref) for conditional formatting. # Modified an existing entry This method can also modify an existing entry, if `name` is already a field int the logger. The `type` can be omitted in this case. Simply specify any of the keyword arguments with the new setting. """ function setentry(log::Logger, name::String, type::Type{T}=Float64; fmt::String=default_format(log, name, T), index::Integer=default_index(log, name), level=default_level(log, name), width::Integer=default_width(log, name, fmt), ccrayon=nothing ) where T @assert width > 0 "Field width must be positive" # Check if index is valid newentry = !haskey(log.fmt, name) index == 0 && error("Index can't be zero. Must be positive or negative") if length(log.data) == 0 && abs(index) == 1 index = 1 elseif index < 0 if index >= -length(log.data) index = length(log.data) + index + 1 + newentry # add one to the end else error("Invalid index. Negative indices must be greater than $(-length(log.data))") end elseif index > length(log.data) error("Invalid index. Must be less than $(length(log.data))") end # Check if the field already exists if haskey(log.fmt, name) espec = log.fmt[name] fid = espec.uid oldindex = log.idx[fid] # Shift data if oldindex != index shiftswap!(log.data, index, oldindex) shiftswap!(log.crayons, index, oldindex) shiftidx!(log.idx, fid, index) end if isnothing(ccrayon) ccrayon = espec.ccrayon end if fmt != espec.fmt || level != espec.level || width != espec.width || ccrayon != espec.ccrayon log.fmt[name] = EntrySpec(espec.type, fmt, fid, level, width, ccrayon) end else @assert type != Nothing "Must specify type for a new field" # Insert new field fid = length(log.idx) + 1 insert!(log.data, index, " "^width) insert!(log.crayons, index, Crayon(reset=true)) push!(log.idx, fid) shiftidx!(log.idx, fid, index) if isnothing(ccrayon) ccrayon = ConditionalCrayon() end # Set field format and index log.fmt[name] = EntrySpec(T, fmt, fid, level, width, ccrayon) end # Add formatter if it doesn't exist if !haskey(log.fmtfun, fmt) log.fmtfun[fmt] = generate_formatter(fmt) end return end function default_index(log::Logger, name::String) if haskey(log.fmt, name) uid = log.fmt[name].uid return log.idx[uid]::Int16 end Int16(-1) end function default_level(log::Logger, name::String) if haskey(log.fmt, name) return log.fmt[name].level::UInt8 end UInt8(DEFAULT_LEVEL) end function default_width(log::Logger, name::String, fmt::String)::UInt8 if haskey(log.fmt, name) width = log.fmt[name].width::UInt8 else width = getwidth(fmt) if width <= 0 width = DEFAULT_WIDTH else width += 1 end end return UInt8(max(length(name) + 1, width)) end # Default Formatting function default_format(log::Logger, name::String, ::Type{T}) where T if haskey(log.fmt, name) return log.fmt[name].fmt end _getformat(log.defaults, T) end default_format(log::Logger, ::Type{T}) where T = _getformat(log.defaults, T) """ set_default_format(logger, type, fmt) Set the default format for entries type type is a sub-type of `type`. For example: set_default_format(logger, AbstractFloat, "%0.2d") Will print all floating point fields with 2 decimal places. The most format for the type closest to the default is always chosen, such that if we specified set_default_format(logger, Float64, "%0.1d") This would override the previous behavior for `Float64`s. """ function set_default_format(log::Logger, ::Type{T}, fmt::String) where T log.defaults[T] = fmt end function _getformat(fmt::Dict, ::Type{T}) where T if haskey(fmt, T) return fmt[T] else return _newdefault(fmt, T) end end function _newdefault(fmt::Dict, ::Type{T}) where T Tsuper = Any for (k,v) in pairs(fmt) if (T <: k) && (k <: Tsuper) Tsuper = k end end fmt[T] = fmt[Tsuper] end
SolverLogging
https://github.com/bjack205/SolverLogging.jl.git
[ "MIT" ]
0.2.0
ebe090fc0a0f83685b5bfd7d1eb3fd870bbd1773
code
1581
""" shiftswap!(a, inew, iold) Move an entry in vector `iold` to `inew`, shifting the other arguments. """ function shiftswap!(a::AbstractVector, inew, iold) if inew != iold v = a[iold] deleteat!(a, iold) insert!(a, inew, v) end return a end """ shiftidx!(idx, fid, inew) For a vector of unique, consecutive indices `idx`, set the index of entry `fid` to the new index `inew`. Update the other entries, maintaining relative ordering, such that `idx` is still a vector of unique, consecutive integers. Runs in O(n). """ function shiftidx!(idx::AbstractVector{<:Integer}, fid::Integer, inew::Integer) iold = idx[fid] ilo = min(iold,inew) ihi = max(iold,inew) s = -sign(inew - iold) for j = 1:length(idx) if ilo <= idx[j] <= ihi idx[j] += s end end idx[fid] = inew return idx end """ getwidth(fmt::String) Get the width field from a C-style printf format string. It looks for a set of numbers followed by a decimal or letter, but not preceded by a decimal or digit. Returns -1 if no width is found. """ function getwidth(fmt::String)::Int period = findlast(".", fmt) # search for a set of characters followed by a decimal or letter, but not # preceded by a decimal or digit regex = r"(?<![0-9|.])[0-9]+(?=[a-zA-Z|.])" inds = findfirst(regex, fmt) if !isnothing(inds) width = parse(Int, fmt[inds]) if width == 0 return -1 else return width end else return -1 end end
SolverLogging
https://github.com/bjack205/SolverLogging.jl.git
[ "MIT" ]
0.2.0
ebe090fc0a0f83685b5bfd7d1eb3fd870bbd1773
code
7801
using SolverLogging using Test using Crayons using SolverLogging: EntrySpec # using BenchmarkTools # using Formatting ## Formatting defaults lg = SolverLogging.Logger() def = SolverLogging._default_formats() @test !haskey(def, Float64) # Add a new entry @test SolverLogging.default_format(lg, Float64) == def[AbstractFloat] @test haskey(lg.defaults, Float64) # Set default @test !haskey(lg.defaults, Int) SolverLogging.set_default_format(lg, Int, "%3d") @test haskey(lg.defaults, Int) @test SolverLogging.default_format(lg, Int) !== SolverLogging.default_format(lg, Int32) @test haskey(lg.defaults, Int32) # Insert fields @test length(lg.data) == 0 SolverLogging.setentry(lg, "alpha", Float64) @test length(lg.data) == 1 @test lg.fmt["alpha"] == EntrySpec(Float64, def[AbstractFloat],1, 1, SolverLogging.DEFAULT_WIDTH) @test lg.idx[1] == 1 @test SolverLogging.getidx(lg, "alpha") == 1 lg.data[1] = "alpha" # Add an integer entry SolverLogging.setentry(lg, "iter", Int, fmt="%10d") @test lg.fmt["iter"] == EntrySpec(Int,"%10d",2,1,11) @test length(lg.data) == 2 @test SolverLogging.getidx(lg, "iter") == 2 lg.data[2] = "iter" # Insert twice SolverLogging.setentry(lg, "iter", Int, fmt="%3d", index=2) @test length(lg.data) == 2 @test lg.data[2] == "iter" @test length(keys(lg.fmt)) == 2 @test lg.data == ["alpha","iter"] @test SolverLogging.getidx(lg, "iter") == 2 # New string field SolverLogging.setentry(lg, "info", String, index=1, width=20) @test lg.fmt["info"] == EntrySpec(String,"%s",3,1,20) @test SolverLogging.getidx(lg, "info") == 1 @test SolverLogging.getidx(lg, "alpha") == 2 @test SolverLogging.getidx(lg, "iter") == 3 lg.data[1] = "info" @test lg.data == ["info", "alpha","iter"] # Move an existing field (1 to 3) SolverLogging.setentry(lg, "info", String, index=-1) @test lg.fmt["info"] == EntrySpec(String,"%s",3,1,20) @test lg.data == ["alpha","iter","info"] @test lg.idx == [1,2,3] # Change the width (not specifying type) @test lg.fmt["alpha"].width == SolverLogging.DEFAULT_WIDTH SolverLogging.setentry(lg, "alpha", width=12) @test lg.fmt["alpha"].width == 12 # Change the ccrayon and test SolverLogging.setentry(lg, "alpha", ccrayon=ConditionalCrayon(1, 10)) entry = lg.fmt["alpha"] @test entry.ccrayon(5) == Crayon(reset=true) @test entry.ccrayon(0) == crayon"green" @test entry.ccrayon(11) == crayon"red" # Make sure it doesn't erase the previous crayon if another field is modified SolverLogging.setentry(lg, "alpha", width=9) entry = lg.fmt["alpha"] @test entry.ccrayon(5) == Crayon(reset=true) @test entry.ccrayon(0) == crayon"green" @test entry.ccrayon(11) == crayon"red" # # Try adding new field without the type # @test_throws AssertionError SolverLogging.setentry(lg, "ϕ") # Add to 2nd to last field SolverLogging.setentry(lg, "ϕ", Int32, index=-2) @test lg.fmt["ϕ"] == EntrySpec(Int32,def[Integer],4,1, 10) lg.data[3] = "phi" @test lg.data == ["alpha","iter","phi","info"] @test lg.idx == [1,2,4,3] # move and use new format (3 to 2) SolverLogging.setentry(lg, "ϕ", Int32, index=-3, fmt="%5d") @test lg.fmt["ϕ"] == EntrySpec(Int32,"%5d", 4, 1, 10) @test lg.data == ["alpha","phi","iter","info"] @test lg.idx == [1,3,4,2] # Change level SolverLogging.setentry(lg, "ϕ", Int32, level=2) @test lg.fmt["ϕ"] == EntrySpec(Int32,"%5d", 4, 2, 10) # Change Width SolverLogging.setentry(lg, "ϕ", Int32, width=12) @test lg.fmt["ϕ"] == EntrySpec(Int32,"%5d", 4, 2, 12) # Test clear SolverLogging.clear!(lg) for i in (1,3,4) @test all(isspace, lg.data[1]) end @test isempty(lg.data[2]) ############################################# ## Log values ############################################# SolverLogging._log!(lg, "iter", 1) @test lg.data[3] == " 1 " @test parse(Int,lg.data[3]) == 1 SolverLogging._log!(lg, "iter", 200) @test parse(Int,lg.data[3]) == 200 SolverLogging._log!(lg, "info", "hi there") @test lg.data[4] == rpad("hi there", 20) SolverLogging.setentry(lg, "alpha", Float64, width=6) lg.opts.autosize = false @test_logs (:warn,) SolverLogging._log!(lg, "alpha", 1.234567e-3) @test lg.data[1] == "1.23e-03" SolverLogging.setentry(lg, "alpha", Float64, width=10) SolverLogging._log!(lg, "alpha", 1e-3) @test lg.data[1] == "1.00e-03 " @test lg.crayons[1] == crayon"green" # Move alpha and make sure the crayon moves too SolverLogging.setentry(lg, "alpha", index=2) @test lg.data[2] == "1.00e-03 " @test lg.crayons[2] == crayon"green" SolverLogging.setentry(lg, "alpha", index=1) # Test append operation lg.opts.autosize = false SolverLogging._log!(lg, "info", "hi there") info = SolverLogging._getdata(lg, "info") length(info) == 20 SolverLogging._log!(lg, "info", "Something", :append) newinfo = SolverLogging._getdata(lg, "info") @test newinfo == rpad("hi there. Something", 20) @test_logs (:warn,) SolverLogging._log!(lg, "info", "new", :append) info = SolverLogging._getdata(lg, "info") @test length(info) > 20 lg.opts.autosize = true SolverLogging._log!(lg, "info", "hi there") info = SolverLogging._getdata(lg, "info") length(info) == 20 SolverLogging._log!(lg, "info", "Something", :append) newinfo = SolverLogging._getdata(lg, "info") @test newinfo == rpad("hi there. Something", 20) @test_nowarn SolverLogging._log!(lg, "info", "new", :append) info = SolverLogging._getdata(lg, "info") @test length(info) > 20 @test Int(lg.fmt["info"].width) == length(info) @test_logs (:warn,) SolverLogging._log!(lg, "iter", 1, :append) SolverLogging._log!(lg, "iter", "new", :append) newinfo = SolverLogging._getdata(lg, "info") # Test add operation SolverLogging._log!(lg, "iter", 11) iter = parse(Int,SolverLogging._getdata(lg, "iter")) SolverLogging._log!(lg, "iter", 2, :add) newiter = parse(Int,SolverLogging._getdata(lg, "iter")) @test newiter == iter + 2 SolverLogging._log!(lg, "info", "hi there") @test_logs (:warn,r"Cannot add*") SolverLogging._log!(lg, "info", "a", :add) ## Test printing and verbosity setentry(lg, "info", width=20) SolverLogging._log!(lg, "info", "") SolverLogging.setlevel!(lg, 1) @test lg.data[2] == "" SolverLogging._log!(lg, "ϕ", 3) @test lg.data[2] == "" @test !occursin("ϕ", SolverLogging.formheader(lg)) @test length(SolverLogging.formrow(lg)) == 41 setentry(lg, "info", index=2) setentry(lg, "info", width=20) SolverLogging._log!(lg, "info", "hi there") SolverLogging.printheader(lg) for i = 1:10 SolverLogging._log!(lg, "alpha", 2i-5) SolverLogging.printrow(lg) end # Try expanding column setentry(lg, "info", width=20) SolverLogging._log!(lg, "info", "hi there") lg.opts.freq = 10 SolverLogging.resetcount!(lg) for i = 1:10 SolverLogging._log!(lg, "alpha", 2i-5) SolverLogging._log!(lg, "info", "$i", :append) SolverLogging.printlog(lg) end @test SolverLogging.setlevel!(lg, 2) == 1 SolverLogging._log!(lg, "ϕ", 3) @test lg.data[3] == rpad(" 3", 12) @test occursin("ϕ", SolverLogging.formheader(lg)) @test length(SolverLogging.formrow(lg)) == 85 begin SolverLogging.printheader(lg) for i = 1:3 SolverLogging._log!(lg, "iter", i) SolverLogging.printrow(lg) end end # Try append operation for strings setentry(lg, "info", width=25) SolverLogging._log!(lg, "info", "more info", :append) @test occursin("more info", lg.data[SolverLogging.getidx(lg, "info")]) && occursin("hi there.", lg.data[SolverLogging.getidx(lg, "info")]) printlog(lg) # Print a lower verbosity level and make sure there # aren't any extra entries @test SolverLogging.setlevel!(lg, 1) == 2 begin SolverLogging.printheader(lg) for i = 1:3 SolverLogging._log!(lg, "alpha", 10(i-1)-5) SolverLogging._log!(lg, "iter", i) SolverLogging.printrow(lg) end end SolverLogging._log!(lg, "ϕ", 21.2) header = SolverLogging.formheader(lg) @test !occursin("ϕ", header) row = SolverLogging.formrow(lg) @test !occursin("21.5", row)
SolverLogging
https://github.com/bjack205/SolverLogging.jl.git
[ "MIT" ]
0.2.0
ebe090fc0a0f83685b5bfd7d1eb3fd870bbd1773
code
3178
using SolverLogging using Crayons using Test ## lg = SolverLogging.Logger() SolverLogging.resetlogger!(lg) setentry(lg, "iter", Int64, width=5) setentry(lg, "cost") setentry(lg, "ΔJ") setentry(lg, "α", fmt="%6.4f") setentry(lg, "info", String) a = 1+2 itr = 1 @log lg "iter" itr @log lg "cost" 10a @log lg "ΔJ" 1e-3 cost = 12.0 @log lg cost printheader(lg) SolverLogging.formrow(lg) printrow(lg) @test lg.opts._count == 1 printrow(lg) @test lg.opts._count == 2 iter = 2 @log lg iter lg.data printlog(lg) # Test the add operation @log lg "iter" 1 :add @test parse(Int,lg.data[1]) == 3 setentry(lg, "info", String, width=25) @log lg "info" "Some info" SolverLogging.resetcount!(lg) for iter = 1:12 @log lg iter iter == 12 && @log lg "info" "last iter" :append printlog(lg) end @test occursin("Some info. last iter", SolverLogging.formrow(lg)) @test SolverLogging.isenabled(lg) println("\nNothing should print between this line...") SolverLogging.disable(lg) SolverLogging.resetcount!(lg) for iter = 1:12 @log lg iter printlog(lg) end println("...and this line") SolverLogging.enable(lg) @test lg.opts.enable == true SolverLogging.resetlogger!(lg) @test length(lg.data) == 0 ## Test Info field setentry(lg, "info", String, width=20) @log lg "info" "Cost Increase" occursin("Cost Increase", lg.data[1]) # Should insert a period @log lg "info" "Max Iters." :append occursin("Cost Increase. Max Iters", lg.data[1]) # Try inserting spaces @log lg "info" " " @log lg "info" "New message" @test lg.data[1][1:3] == "New" ENV["JULIA_DEBUG"] = "SolverLogging" @test_logs (:debug,r"Rejecting") @log lg "new" 1.0 ## Test output to a file filename = joinpath(@__DIR__, "log.out") lg = SolverLogging.Logger(filename) setentry(lg, "iter", Int) setentry(lg, "cost", Float64) setentry(lg, "tol", Float64, level=2) lg.opts.freq = 5 lg.opts.linechar = 0 iter = 1 for i = 1:10 local iter = i @log lg iter @log lg "cost" log(10*i) @log lg "tol" exp(-i) printlog(lg) end SolverLogging.resetcount!(lg) lg.opts.linechar = '*' for i = 1:10 local iter = i @log lg iter @log lg "cost" log(10*i) @log lg "tol" exp(-i) printlog(lg) end @test lg.io isa IOStream lines = readlines(filename) @test length(lines) == 26 for i in (1,7) @test occursin("iter", lines[i]) @test occursin("cost", lines[i]) @test !occursin("tol", lines[i]) end for i = 2:6 @test occursin("$(i-1)", lines[i]) end @test length(filter(x->occursin("***", x), lines)) == 2 rm(filename) ## Test Condition formatting ccrayon_tol = ConditionalCrayon(1e-6,Inf, reverse=false) goodctrl = x->abs(x) < 1 badctrl = x->abs(x) > 10 defcolor = crayon"208" # the ANSI color for a dark orange. ccrayon_control = ConditionalCrayon(badctrl, goodctrl, defaultcolor=defcolor) logger = SolverLogging.Logger() setentry(logger, "iter", Int, width=5) setentry(logger, "tol", Float64, ccrayon=ccrayon_tol) setentry(logger, "ctrl", Float64, fmt="%.1f", ccrayon=ccrayon_control) logger.fmt["iter"].ccrayon(10) for iter = 1:10 tol = exp10(-iter) ctrl = 0.1*(iter-1)*iter^2 @log logger iter @log logger tol @log logger ctrl printlog(logger) end
SolverLogging
https://github.com/bjack205/SolverLogging.jl.git
[ "MIT" ]
0.2.0
ebe090fc0a0f83685b5bfd7d1eb3fd870bbd1773
code
161
using SolverLogging using Test @testset "Basics" begin include("basic.jl") include("utils.jl") end @testset "Macros" begin include("macros.jl") end
SolverLogging
https://github.com/bjack205/SolverLogging.jl.git
[ "MIT" ]
0.2.0
ebe090fc0a0f83685b5bfd7d1eb3fd870bbd1773
code
452
@test SolverLogging.getwidth("%0.24e") == -1 @test SolverLogging.getwidth("%01.24e") == 1 @test SolverLogging.getwidth("%0112.24e") == 112 @test SolverLogging.getwidth("%-1.24e") == 1 @test SolverLogging.getwidth("012%-13.24e") == 13 @test SolverLogging.getwidth("%.24e") == -1 @test SolverLogging.getwidth("%e") == -1 @test SolverLogging.getwidth("%5d") == 5 @test SolverLogging.getwidth("%512d") == 512 @test SolverLogging.getwidth("%0512d") == 512
SolverLogging
https://github.com/bjack205/SolverLogging.jl.git
[ "MIT" ]
0.2.0
ebe090fc0a0f83685b5bfd7d1eb3fd870bbd1773
docs
2635
[![CI](https://github.com/bjack205/SolverLogging.jl/actions/workflows/CI.yml/badge.svg)](https://github.com/bjack205/SolverLogging.jl/actions/workflows/CI.yml) [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://bjack205.github.io/SolverLogging.jl/) # SolverLogging.jl This package provides a logger that is designed for use in iterative solvers. The logger presents data in a tabulated format, with each line representing the data from an iteration of the solver. The key features of this package are: * The ability to handle different verbosity levels. Assumes each verbosity level contains all information from previous levels. Allows the user to scale the information based on current needs. * Precise control over output formatting. The location, column width, and entry formatting for each field can be controlled. * Color printing to the terminal thanks to [Crayons.jl](https://github.com/KristofferC/Crayons.jl) * Conditional formatting that allows values to be automatically formatted based on a the current value. ## Quickstart To use the default logger provided by the package, start by specifying the fields you want to log: ```@example quickstart; continued=true using SolverLogging SolverLogging.resetlogger!() # good idea to always reset the global logger setentry("iter", Int, width=5) setentry("cost") setentry("info", String, width=25) setentry("α", fmt="%6.4f") # sets the numeric formatting setentry("ΔJ", index=-2) # sets it to penultimate column setentry("tol", level=2) # sets it to verbosity level 2 (prints less often) ``` After specifying the data we want to log, we log the data using the [`@log`](@ref) macro: ```@example quickstart; continued=true @log "iter" 1 @log "cost" 10.2 ``` Note this macro allows expressions: ```@example quickstart; continued=true dJ = 1e-3 str = "Some Error Code: " @log "ΔJ" dJ @log "info" str * string(10) ``` As a convenient shortcut, we if the local variable name matches the name of the field we can just pass the local variable and the name will be automatically extracted: ```@example quickstart; continued=true iter = 2 @log iter ``` To print the output use [`printlog`](@ref): ```@example quickstart; continued=true iter = 2 @log iter ``` which will automatically handle printing the header lines. Here we call it in a loop, updating the iteration field each time: ```@example quickstart; continued=false for iter = 1:15 @log iter printlog() end ``` ## Sample Output A simple output with conditional formatting looks like this: ![](https://github.com/bjack205/SolverLogging.jl/blob/master/docs/src/sample_output.png)
SolverLogging
https://github.com/bjack205/SolverLogging.jl.git
[ "MIT" ]
0.2.0
ebe090fc0a0f83685b5bfd7d1eb3fd870bbd1773
docs
383
# [API](@id api_section) ```@meta CurrentModule = SolverLogging ``` ## The Logger ```@docs Logger ``` ### Main Methods ```@docs printlog printheader printrow formheader formrow getlevel setlevel! resetcount! resetlogger! ``` ## Defining Entries ```@docs setentry set_default_format ``` ## Logging ```@docs @log _log! ``` ## Conditional Formatting ```@docs ConditionalCrayon ```
SolverLogging
https://github.com/bjack205/SolverLogging.jl.git
[ "MIT" ]
0.2.0
ebe090fc0a0f83685b5bfd7d1eb3fd870bbd1773
docs
4797
# [Examples](@id examples_section) ```@meta CurrentModule = SolverLogging ``` ## Setting up a Logger The [Quickstart](@ref) used the default logger provided by this package. It's usually a better idea to have your own local logger you can use, to avoid possible conflicts. ```@example ex1; continue=true using SolverLogging logger = SolverLogging.Logger() setentry(logger, "iter", Int, width=5) setentry(logger, "cost") setentry(logger, "dJ", level=2) setentry(logger, "info", String, width=25) ``` We can change a few things about the behavior of our logger by accessing the logger options. Here we change the header print frequency to print every 5 iterations instead of the default 10, eliminate the line under the header, and set the header to print in bold yellow: ```@example ex1; continue=true using Crayons logger.opts.freq = 5 logger.opts.linechar = '\0' logger.opts.headerstyle = crayon"bold yellow"; ``` If we set the verbosity to 1 and print, we'll see that it doesn't print the `dJ` field: ```@example ex1; continue=true setlevel!(logger, 1) Jprev = 100 for iter = 1:3 global Jprev J = 100/iter @log logger iter @log logger "cost" J @log logger "dJ" Jprev - J # note this is disregarded Jprev = J if iter == 5 @log logger "info" "Last Iteration" end printlog(logger) end ``` If we change the verbosity to 2, we now see `dJ` printed out: ```@example ex1; continue=true setlevel!(logger, 2) # note the change to 2 Jprev = 100 for iter = 1:5 global Jprev J = 100/iter @log logger iter @log logger "cost" J @log logger "dJ" Jprev - J Jprev = J if iter == 5 @log logger "info" "Last Iteration" end printlog(logger) end ``` Note how the new output doesn't start with a header, since it's continuing the count from before. We can change this by resetting the count with [`resetcount!`](@ref): ```@example ex1; continue=false setlevel!(logger, 1) # note the change back to 1 SolverLogging.resetcount!(logger) # this resets the print count Jprev = 100 for iter = 1:5 global Jprev J = 100/iter @log logger iter @log logger "cost" J @log logger "dJ" Jprev - J Jprev = J if iter == 5 @log logger "info" "Last Iteration" end printlog(logger) end ``` So that, as you can see, we now get a nice output with the header at the top. By changing the verbosity level back to 1, you see that it got rid of the `dJ` column again. ## Conditional Formatting In this example we cover how to use the conditional formatting. Lets say we have a field `tol` that we want below `1e-6`. We also have another field `control` that we want to be "good" if it's absolute value is less than 1, and "bad" if it's greater than 10. We create 2 [`ConditionalCrayon`](@ref) types to encode this behavior. Our first one can be covered using the constructor that takes a `lo` and `hi` value: ```@example ex2; continue=true using SolverLogging ccrayon_tol = ConditionalCrayon(1e-6,Inf, reverse=false) nothing # hide ``` Which by default will consider any values less than `lo` good and any values greater than `hi` bad. We can reverse this with the optional `reverse` keyword. For our control formatting, let's say we want it to print orange if it's absolute value is in between 1 and 10 and cyan if it's less than 1: ```@example ex2; continue=true using Crayons goodctrl = x->abs(x) < 1 badctrl = x->abs(x) > 10 lowcolor = crayon"blue" defcolor = crayon"208" # the ANSI color for a dark orange. ccrayon_control = ConditionalCrayon(badctrl, goodctrl, defaultcolor=defcolor, goodcolor=crayon"cyan") nothing # hide ``` !!! tip Use `Crayons.test_256_colors()` to generate a sample of all the ANSI color codes. We can now specify these when we set up our fields: ```@example ex2; continue=true logger = SolverLogging.Logger() setentry(logger, "iter", Int, width=5) setentry(logger, "tol", Float64, ccrayon=ccrayon_tol) setentry(logger, "ctrl", Float64, fmt="%.1f", ccrayon=ccrayon_control) ``` We should see the desired behavior when we print out some test values: ```@example ex2; continue=false for iter = 1:10 tol = exp10(-iter) ctrl = 0.1*(iter-1)*iter^2 @log logger iter @log logger tol @log logger ctrl printlog(logger) end ``` ## Saving to a File Instead of writing to `stdout`, we can write a to a file. This interface is exactly the same, but we pass a filename or an `IOStream` to the logger when we create it: ``` using SolverLogging filename = "log.out" logger = SolverLogging.Logger(filename) ``` Note that this will automatically open the file with read privileges, overwritting any contents in the file. The stream is flushed after every write so it should populate the contents of the file in real time.
SolverLogging
https://github.com/bjack205/SolverLogging.jl.git
[ "MIT" ]
0.2.0
ebe090fc0a0f83685b5bfd7d1eb3fd870bbd1773
docs
2404
# SolverLogging.jl ## Overview This package provides a logger that is designed for use in iterative solvers. The logger presents data in a tabulated format, with each line representing the data from an iteration of the solver. The key features of this package are: * The ability to handle different verbosity levels. Assumes each verbosity level contains all information from previous levels. Allows the user to scale the information based on current needs. * Precise control over output formatting. The location, column width, and entry formatting for each field can be controlled. * Color printing to the terminal thanks to [Crayons.jl](https://github.com/KristofferC/Crayons.jl) * Conditional formatting that allows values to be automatically formatted based on a the current value. ## Quickstart To use the logger provided by the package, start by specifying the fields you want to log: ```@example quickstart; continue=true using SolverLogging lg = SolverLogging.Logger() SolverLogging.resetlogger!(lg) # good idea to always reset the global logger setentry(lg, "iter", Int, width=5) setentry(lg, "cost") setentry(lg, "info", String, width=25) setentry(lg, "α", fmt="%6.4f") # sets the numeric formatting setentry(lg, "ΔJ", index=-2) # sets it to penultimate column setentry(lg, "tol", level=2) # sets it to verbosity level 2 (prints less often) ``` After specifying the data we want to log, we log the data using the [`@log`](@ref) macro: ```@example quickstart; continue=true @log lg "iter" 1 @log lg "cost" 10.2 ``` Note this macro allows expressions: ```@example quickstart; continue=true dJ = 1e-3 str = "Some Error Code: " @log lg "ΔJ" dJ @log lg "info" str * string(10) ``` As a convenient shortcut, we if the local variable name matches the name of the field we can just pass the local variable and the name will be automatically extracted: ```@example quickstart; continue=true iter = 2 @log lg iter ``` To print the output use [`printlog`](@ref), which will automatically handle printing the header lines. Here we call it in a loop, updating the iteration field each time: ```@example quickstart; continue=false for iter = 1:15 @log lg iter printlog(lg) end ``` ## API See the [API](@ref api_section) page for details on how to use the logger in your application. ## Examples See the [Examples](@ref) page for a few example to help you get started.
SolverLogging
https://github.com/bjack205/SolverLogging.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
code
539
push!(LOAD_PATH,"../src/") using Documenter, RDates makedocs( modules = [RDates], clean = false, format = Documenter.HTML(), sitename = "RDates.jl", authors = "Iain Skett", pages = [ "Introduction" => "index.md", "Primitives" => "primitives.md", "Months and Years" => "months_and_years.md", "Combinations" => "combinations.md", "Business Days" => "business_days.md", "Ranges" => "ranges.md" ], ) deploydocs( repo = "github.com/InfiniteChai/RDates.jl.git" )
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
code
679
module RDates include("abstracts.jl") # Rounding and Compounds defined upfront as we need them for the grammar include("rounding.jl") include("compounds.jl") include("grammar.jl") include("monthinc.jl") include("invalidday.jl") # The various basic implementations (along with shows and grammar registrations) include("primitives.jl") include("ranges.jl") include("calendars.jl") # include("io.jl") # Export the macro and non-macro parsers. export @rd_str export rdate export is_holiday, holidays, holidaycount, bizdaycount export calendar export apply export SimpleCalendarManager, setcalendar!, setcachedcalendar! export WeekendCalendar, CachedCalendar end # module RDates
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
code
5687
import Dates using Compat @compat abstract type RDate end # Calendars @compat abstract type CalendarManager end @compat abstract type Calendar end """ HolidayRoundingConvention The convention used in conjunction with holiday calendars to determine what to do if an adjustments falls on a holiday. """ @compat abstract type HolidayRoundingConvention end """ InvalidDayConvention The convention used for handling month or year increments which fall on a day which is not valid. """ @compat abstract type InvalidDayConvention end """ MonthIncrementConvention The convention used for handling month or year increments and how they should be applied. Should handle invalid days explicitly, as these wil be handled separately by the InvalidDayConvention """ @compat abstract type MonthIncrementConvention end """ NullCalendarManager() The most primitive calendar manager, that will return an error for any request to get a calendar. The default calendar manager that is available when applying rdates using the + operator, without an explicit calendar manager. """ struct NullCalendarManager <: CalendarManager end """ is_holiday(calendar::Calendar, date::Dates.Date)::Bool Determine whether the date requested is a holiday for this calendar or not. """ is_holiday(x::Calendar, ::Dates.Date) = error("$(typeof(x)) does not support is_holiday") """ holidays(calendar::Calendar, from::Dates.Date, to::Dates.Date)::Vector{Bool} Get the vector of each day and whether its a holiday or not, inclusive of from and to. """ holidays(::C, ::Dates.Date, ::Dates.Date) where {C<:Calendar} = error("holidays not implemented by $C") """ holidaycount(calendar::Calendar, from::Dates.Date, to::Dates.Date)::Int Get the number of holidays in the calendar between two dates (inclusive) """ holidaycount(cal::Calendar, from::Dates.Date, to::Dates.Date) = Base.sum(holidays(cal, from, to)) """ bizdaycount(calendar::Calendar, from::Dates.Date, to::Dates.Date)::Int Get the number of business days in the calendar between two dates (inclusive) """ bizdaycount(cal::Calendar, from::Dates.Date, to::Dates.Date) = 1 + (to-from).value - holidaycount(cal, from, to) """ calendar(calendarmgr::CalendarManager, names::Vector)::Calendar Given a set of calendar names, request the calendar manager to retrieve the associated calendar that supports the union of them. """ calendar(x::CalendarManager, names::Vector)::Calendar = error("$(typeof(x)) does not support calendar") calendar(x::CalendarManager, name::String)::Calendar = calendar(x, split(name, "|")) """ apply(rdate::RDate, date::Dates.Date, calendarmgr::CalendarManager)::Dates.Date The application of an rdate to a specific date, given an explicit calendar manager. ### Examples ```jula-repl julia> cal_mgr = SimpleCalendarManager() julia> setcalendar!(cal_mgr, "WEEKEND", WeekendCalendar()) julia> apply(rd"1b@WEEKEND", Date(2021,7,9), cal_mgr) 2021-07-12 ``` """ apply(rd::RDate, ::Dates.Date, ::CalendarManager)::Dates.Date = error("$(typeof(rd)) does not support date apply") """ multiply(rdate::RDate, count::Integer)::RDate An internalised multiplication of an rdate which is generated without reapplication of a relative date multiple times. To apply an rdate multiple times, then use a `Repeat`. For example "6m" + "6m" != "12m" for all dates, due to the fact that there are different days in each month and invalid day conventions will kick in. """ multiply(rd::R, count::Integer) where {R<:RDate} = error("multiply not implemented by $R") Base.:*(rdate::RDate, count::Integer) = multiply(rdate, count) Base.:*(count::Integer, rdate::RDate) = multiply(rdate, count) """ apply(rdate::RDate, date::Dates.Date)::Dates.Date The application of an rdate to a specific date, without an explicit calendar manager. This will use the `NullCalendarManager()`. """ apply(rd::RDate, date::Dates.Date) = apply(rd, date, NullCalendarManager()) Base.:+(rd::RDate, date::Dates.Date) = apply(rd, date) Base.:+(date::Dates.Date, rd::RDate) = apply(rd, date) Base.:-(date::Dates.Date, rd::RDate) = apply(-rd, date) Base.:-(x::RDate)::RDate = error("$(typeof(x)) does not support negation") """ apply(rounding::HolidayRoundingConvention, date::Dates.Date, calendar::Calendar)::Dates.Date Apply the holiday rounding to a given date. There is no strict requirement that the resolved date will not be a holiday for the given date. """ apply(x::HolidayRoundingConvention, date::Dates.Date, calendar::Calendar) = error("$(typeof(x)) does not support apply") """ apply(rounding::InvalidDayConvention, day::Integer, month::Integer, year::Integer)::Dates.Date Given a day, month and year which do not generate a valid date, adjust them in some form to a valid date. """ adjust(x::InvalidDayConvention, day, month, year) = error("$(typeof(x)) does not support adjust") """ apply(rounding::MonthIncrementConvention, from::Dates.Date, new_month::Integer, new_year::Integer, calendar_mgr::CalendarManager)::Tuple{Integer, Integer, Integer} Given the initial day, month and year that we're moving from and a generated new month and new year, determine the new day, month and year that should be used. Generally used to handle specific features around preservation of month ends or days of week, if required. Note that the generated (day, month, year) do not need to be able to produce a valid date. The invalid day convention should be applied, if required, after this calculation. May use a calendar manager if required as well """ adjust(x::MonthIncrementConvention, from::Dates.Date, new_month, new_year, calendar_mgr::CalendarManager) = error("$(typeof(x)) does not support adjust")
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
code
8384
import Dates """ NullCalendar() A holiday calendar for which there is never a holiday. *sigh* """ struct NullCalendar <: Calendar end is_holiday(::NullCalendar, ::Dates.Date) = false holidays(::NullCalendar, from::Dates.Date, to::Dates.Date) = Base.repeat([false], (to - from).value + 1) """ WeekendCalendar() A calendar which will mark every Saturday and Sunday as a holiday """ struct WeekendCalendar <: Calendar end function is_holiday(::WeekendCalendar, date::Dates.Date) signbit(5 - Dates.dayofweek(date)) end function holidays(::WeekendCalendar, from::Dates.Date, to::Dates.Date) dow = Dates.dayofweek(from) days = (to - from).value + 1 hols = Base.repeat([false], days) satstart = dow == 7 ? 7 : 7 - dow sunstart = 8 - dow for i in Iterators.flatten([satstart:7:days, sunstart:7:days]) @inbounds hols[i] = true end hols end mutable struct CalendarCache bdays::Vector{Bool} bdayscounter::Vector{UInt32} dtmin::Dates.Date dtmax::Dates.Date initialised::Bool CalendarCache() = new([], [], Dates.Date(1900,1,1), Dates.Date(1900,1,1), false) end function needsupdate(cache::CalendarCache, d0::Dates.Date, d1::Dates.Date) !cache.initialised || d0 < cache.dtmin || d1 > cache.dtmax end """ CachedCalendar(cal::Calendar) Creating a wrapping calendar that will cache the holidays lazily as retrieved for a given year, rather than loading them in one go. """ struct CachedCalendar <: Calendar calendar::Calendar cache::CalendarCache period::UInt8 CachedCalendar(cal::Calendar) = new(cal, CalendarCache(), 10) end Base.show(io::IO, mgr::CachedCalendar) = (print(io, "CachedCalendar("); show(io, mgr.calendar); print(io, ")")) function updatecache!(cal::CachedCalendar, d0::Dates.Date, d1::Dates.Date) needsupdate(cal.cache, d0, d1) || return if cal.cache.initialised if d0 < cal.cache.dtmin days = (cal.cache.dtmin-d0).value bdays = holidays(cal.calendar, d0, cal.cache.dtmin-Dates.Day(1)) cal.cache.bdays = vcat(bdays, cal.cache.bdays) counters = Base.sum(bdays) .+ cal.cache.bdayscounter lcounters = Vector{UInt32}(undef, days) lcounters[1] = UInt32(bdays[1]) for i in 2:days @inbounds lcounters[i] = lcounters[i-1] + bdays[i] end cal.cache.bdayscounter = vcat(lcounters, counters) cal.cache.dtmin = d0 end if d1 > cal.cache.dtmax days = (d1-cal.cache.dtmax).value bdays = holidays(cal.calendar, cal.cache.dtmax+Dates.Day(1), d1) cal.cache.bdays = vcat(cal.cache.bdays, bdays) rcounters = Vector{UInt32}(undef, days) rcounters[1] = cal.cache.bdayscounter[end] + UInt32(bdays[1]) for i in 2:days @inbounds rcounters[i] = rcounters[i-1] + bdays[i] end cal.cache.bdayscounter = vcat(cal.cache.bdayscounter, rcounters) cal.cache.dtmax = d1 end else days = (d1-d0).value + 1 cal.cache.bdays = holidays(cal.calendar, d0, d1) cal.cache.bdayscounter = Vector{UInt32}(undef, days) cal.cache.bdayscounter[1] = UInt32(cal.cache.bdays[1]) for i in 2:days @inbounds cal.cache.bdayscounter[i] = cal.cache.bdayscounter[i-1] + cal.cache.bdays[i] end cal.cache.dtmin = d0 cal.cache.dtmax = d1 cal.cache.initialised = true end end function is_holiday(cal::CachedCalendar, date::Dates.Date) if needsupdate(cal.cache, date, date) d0 = Dates.Date(cal.period*div(Dates.year(date), cal.period), 1, 1) d1 = Dates.Date(cal.period*(1+div(Dates.year(date), cal.period)), 12, 31) updatecache!(cal, d0, d1) end t0 = (date-cal.cache.dtmin).value + 1 cal.cache.bdays[t0] end function holidaycount(cal::CachedCalendar, from::Dates.Date, to::Dates.Date) if needsupdate(cal.cache, from, to) d0 = Dates.Date(cal.period*div(Dates.year(from), cal.period), 1, 1) d1 = Dates.Date(cal.period*(1+div(Dates.year(to), cal.period)), 12, 31) updatecache!(cal, d0, d1) end t0 = (from-cal.cache.dtmin).value + 1 t1 = (to-from).value Int(cal.cache.bdayscounter[t1+t0] - cal.cache.bdayscounter[t0] + cal.cache.bdays[t0]) end function holidays(cal::CachedCalendar, from::Dates.Date, to::Dates.Date) if needsupdate(cal.cache, from, to) d0 = Dates.Date(cal.period*div(Dates.year(from), cal.period), 1, 1) d1 = Dates.Date(cal.period*(1+div(Dates.year(to), cal.period)), 12, 31) updatecache!(cal, d0, d1) end t0 = (from-cal.cache.dtmin).value + 1 t1 = (to-from).value cal.cache.bdays[t0:t0+t1] end """ JointCalendar(calendars::Vector{Calendar}) <: Calendar A grouping of calendars, for which it is a holiday if it's marked as a holiday for any of the underlying calendars. By default addition of calendars will generate a joint calendar for you. """ struct JointCalendar <: Calendar calendars::Vector{Calendar} end function is_holiday(cal::JointCalendar, date::Dates.Date) foldl( (acc, val) -> acc || is_holiday(val, date), cal.calendars; init = false, ) end function holidays(cal::JointCalendar, from::Dates.Date, to::Dates.Date) hols = Base.repeat([false], (to-from).value+1) for subcal in cal.calendars hols = hols .| holidays(subcal, from, to) end hols end Base.:+(cal1::Calendar, cal2::Calendar) = JointCalendar([cal1, cal2]) Base.:+(cal1::Calendar, cal2::JointCalendar) = JointCalendar(vcat(cal1, cal2.calendars)) Base.:+(cal1::JointCalendar, cal2::Calendar) = JointCalendar(vcat(cal1.calendars, cal2)) Base.:+(cal1::JointCalendar, cal2::JointCalendar) = JointCalendar(vcat(cal1.calendars, cal2.calendars)) """ SimpleCalendarManager() SimpleCalendarManager(calendars::Dict{String, Calendar}) A basic calendar manager which just holds a reference to each underlying calendar, by name, and will generate a joint calendar if multiple names are requested. To set a calendar on this manager then use `setcalendar!` ```julia-repl julia> mgr = SimpleCalendarManager() julia> setcalendar!(mgr, "WEEKEND", WeekendCalendar()) WeekendCalendar() ``` If you want to set a cached wrapping of a calendar then use `setcachedcalendar!` ```julia-repl julia> mgr = SimpleCalendarManager() julia> setcachedcalendar!(mgr, "WEEKEND", WeekendCalendar()) CachedCalendar(WeekendCalendar()) ``` ### Examples ```julia-repl julia> mgr = SimpleCalendarManager() julia> setcalendar!(mgr, "WEEKEND", WeekendCalendar()) julia> is_holiday(calendar(mgr, ["WEEKEND"]), Date(2019,9,28)) true ``` """ struct SimpleCalendarManager <: CalendarManager calendars::Dict{String,Calendar} SimpleCalendarManager(calendars) = new(calendars) SimpleCalendarManager() = new(Dict()) end Base.show(io::IO, mgr::SimpleCalendarManager) = (print(io, "SimpleCalendarManager($(length(mgr.calendars)) calendars)")) setcalendar!(mgr::SimpleCalendarManager, name::String, cal::Calendar) = (mgr.calendars[name] = cal;) setcachedcalendar!(mgr::SimpleCalendarManager, name::String, cal::Calendar) = (mgr.calendars[name] = CachedCalendar(cal);) setcachedcalendar!(mgr::SimpleCalendarManager, name::String, cal::CachedCalendar) = setcalendar!(mgr, name, cal) function calendar(cal_mgr::SimpleCalendarManager, names::Vector)::Calendar if length(names) == 0 NullCalendar() elseif length(names) == 1 cal_mgr.calendars[names[1]] else foldl( (acc, val) -> acc + cal_mgr.calendars[val], names[2:end], cal_mgr.calendars[names[1]], ) end end """ get_calendar_names(rdate::RDate)::Vector{String} A helper method to get all of the calendar names that could potentially be requested by this rdate. This mechanism can be used to mark the minimal set of calendars on which adjustments depend. """ get_calendar_names(::RDate) = Vector{String}() get_calendar_names(rdate::Union{BizDays,CalendarAdj}) = rdate.calendar_names get_calendar_names(rdate::Compound) = Base.foldl((val, acc) -> vcat( acc, get_calendar_names(val), rdate.parts, init = Vector{String}(), )) get_calendar_names(rdate::Repeat) = get_calendar_names(rdate.part)
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
code
8131
using AutoHashEquals """ Compound <: RDate Apply a list of rdates in order """ @auto_hash_equals struct Compound <: RDate parts::Vector{RDate} end apply(rdate::Compound, date::Dates.Date, cal_mgr::CalendarManager) = Base.foldl((x,y) -> apply(y, x, cal_mgr), rdate.parts, init=date) multiply(rdate::Compound, count::Integer) = Compound(map(x -> multiply(x, count), rdate.parts)) combine(left::RDate, right::RDate) = Compound([left,right]) Base.:+(left::RDate, right::RDate) = combine(left, right) Base.:-(left::RDate, right::RDate) = combine(left, -right) Base.:-(rdate::Compound) = Compound(map(-, rdate.parts)) Base.:+(x::Compound, y::RDate) = Compound(vcat(x.parts, y)) Base.:+(x::RDate, y::Compound) = Compound(vcat(x, y.parts)) function Base.show(io::IO, rdate::Compound) for (i,part) in enumerate(rdate.parts) if i > 1 print(io, "+") end show(io, part) end end """ Repeat <: RDate Repeat the application of an rdate n times. """ @auto_hash_equals struct Repeat <: RDate count::Int64 part::RDate function Repeat(count::Int64, part::RDate) count > 0 || error("Repeat must use a positive count, not $count") new(count, part) end Repeat(part::RDate) = new(1, part) end function apply(rdate::Repeat, date::Dates.Date, cal_mgr::CalendarManager) for _ in 1:rdate.count date = apply(rdate.part, date, cal_mgr) end date end multiply(rdate::Repeat, count::Integer) = Repeat(count*rdate.count, rdate.part) Base.:-(rdate::Repeat) = Repeat(rdate.count, -rdate.part) Base.show(io::IO, rdate::Repeat) = (print(io, "$(rdate.count)*Repeat("), show(io, rdate.part), print(io,")")) """ CalendarAdj(calendars, rdate::RDate, rounding::HolidayRoundingConvention) Apply a calendar adjustment to an underlying rdate, applying an appropriate convention if our final date falls on a holiday. The calendars can only use alphanumeric characters, plus `/`, `-` and ` `. In the string-form, you can apply a calendar adjustment using the `@` character and provide `|` separated calendar names to apply it on. The convention is finally provided in square brackets using its string-form name. ### Examples ```julia-repl julia> cal_mgr = SimpleCalendarManager() julia> setcalendar!(cal_mgr, "WEEKEND", WeekendCalendar()) julia> apply(rd"1d", Date(2019,9,27), cal_mgr) 2019-09-28 julia> apply(rd"1d@WEEKEND[NBD]", Date(2019,9,27), cal_mgr) 2019-09-30 julia> apply(rd"2m - 1d", Date(2019,7,23), cal_mgr) 2019-09-22 julia> apply(rd"(2m - 1d)@WEEKEND[PBD]", Date(2019,7,23), cal_mgr) 2019-09-20 ``` """ @auto_hash_equals struct CalendarAdj{R <: RDate, S <: HolidayRoundingConvention} <: RDate calendar_names::Vector{String} part::R rounding::S CalendarAdj(calendar_names, part::R, rounding::S) where {R <: RDate, S <: HolidayRoundingConvention} = new{R, S}(calendar_names, part, rounding) CalendarAdj(calendar_names::String, part::R, rounding::S) where {R<:RDate, S <: HolidayRoundingConvention} = new{R,S}(split(calendar_names, "|"), part, rounding) end function apply(rdate::CalendarAdj, date::Dates.Date, cal_mgr::CalendarManager) base_date = apply(rdate.part, date, cal_mgr) cal = calendar(cal_mgr, rdate.calendar_names) apply(rdate.rounding, base_date, cal) end multiply(rdate::CalendarAdj, count::Integer) = CalendarAdj(rdate.calendar_names, multiply(rdate.part, count), rdate.rounding) Base.:-(x::CalendarAdj) = CalendarAdj(x.calendar_names, -x.part, x.rounding) Base.show(io::IO, rdate::CalendarAdj) = print(io, "($(rdate.part))@$(join(rdate.calendar_names, "|"))[$(rdate.rounding)]") """ Next(parts, inclusive::Bool = false) Next is a mechanism through which we can find the next closest date in the future, given a list of rdates to apply. We can choose whether today is also deemed a valid date. This is commonly used in conjunction with rdates which don't necessarily always give a date in the future, such as asking for the next Easter from today. ### Examples ```julia-repl julia> RDates.Next([RDates.Easter(0), RDates.Easter(1)]) + Date(2019,1,1) 2019-04-21 julia> rd"Next(0E,1E)" + Date(2019,1,1) 2019-04-21 julia> RDates.Next([RDates.Easter(0), RDates.Easter(1)]) + Date(2019,4,21) 2020-04-12 julia> RDates.Next([RDates.Easter(0), RDates.Easter(1)], true) + Date(2019,4,21) 2019-04-21 julia> rd"Next!(0E,1E)" + Date(2019,4,21) 2019-04-21 ``` !!! note The negation of `Next` will actually produce a `Previous`. ```julia-repl julia> -rd"Next(1d,2d)" Previous(-1d, -2d) julia> -3 * rd"Next(1d,2d)" Previous(-3d, -6d) ``` !!! warning While `Next` is a powerful operator, it does require application of every rdate every time, so can be expensive. When combining with ranges, it can often be useful to use an appropriate pivot point to start from instead. """ @auto_hash_equals struct Next <: RDate parts::Vector{RDate} inclusive::Bool Next(parts, inclusive::Bool = false) = new(parts, inclusive) end """ Previous(parts, inclusive::Bool = false) Previous is a mechanism through which we can find the next closest date in the past, given a list of rdates to apply. We can choose whether today is also deemed a valid date. This is commonly used in conjunction with rdates which don't necessarily always give a date in the future, such as asking for the previous Easter from today. ### Examples ```julia-repl julia> RDates.Previous([RDates.Easter(0), RDates.Easter(-1)]) + Date(2019,12,31) 2019-04-21 julia> rd"Previous(0E,-1E)" + Date(2019,12,31) 2019-04-21 julia> RDates.Previous([RDates.Easter(0), RDates.Easter(-1)]) + Date(2019,4,21) 2018-04-01 julia> RDates.Previous([RDates.Easter(0), RDates.Easter(-1)], true) + Date(2019,4,21) 2019-04-21 julia> rd"Previous!(0E,-1E)" + Date(2019,4,21) 2019-04-21 ``` !!! note The negation of `Previous` will actually produce a `Next`. ```julia-repl julia> -rd"Previous(-1d,-2d)" Next(1d, 2d) julia> -3 * rd"Previous(-1d,-2d)" Next(3d, 6d) ``` !!! warning While `Previous` is a powerful operator, it does require application of every rdate every time, so can be expensive. When combining with ranges, it can often be useful to use an appropriate pivot point to start from instead. """ @auto_hash_equals struct Previous <: RDate parts::Vector{RDate} inclusive::Bool Previous(parts, inclusive::Bool = false) = new(parts, inclusive) end function apply(rdate::Next, date::Dates.Date, cal_mgr::CalendarManager) dates = map(part -> apply(part, date, cal_mgr), rdate.parts) op = rdate.inclusive ? Base.:>= : Base.:> dates = [d for d in dates if op(d, date)] length(dates) > 0 || error("$rdate failed to apply to $date") min(dates...) end function apply(rdate::Previous, date::Dates.Date, cal_mgr::CalendarManager) dates = map(part -> apply(part, date, cal_mgr), rdate.parts) op = rdate.inclusive ? Base.:<= : Base.:< dates = [d for d in dates if op(d, date)] length(dates) > 0 || error("$rdate failed to apply to $date") max(dates...) end function multiply(rdate::Next, count::Integer) method = count >= 0 ? Next : Previous method(map(x -> multiply(x, count), rdate.parts), rdate.inclusive) end function multiply(rdate::Previous, count::Integer) method = count >= 0 ? Previous : Next method(map(x -> multiply(x, count), rdate.parts), rdate.inclusive) end Base.:-(rdate::Next) = Previous(map(-, rdate.parts), rdate.inclusive) Base.:-(rdate::Previous) = Next(map(-, rdate.parts), rdate.inclusive) function Base.show(io::IO, rdate::Next) incsign = rdate.inclusive ? "!" : "" print(io, "Next$incsign(") for (i,part) in enumerate(rdate.parts) show(io, part) if i < length(rdate.parts) print(io, ", ") end end print(io, ")") end function Base.show(io::IO, rdate::Previous) incsign = rdate.inclusive ? "!" : "" print(io, "Previous$incsign(") for (i,part) in enumerate(rdate.parts) show(io, part) if i < length(rdate.parts) print(io, ", ") end end print(io, ")") end
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
code
2359
import ParserCombinator: PInt64, Eos, set_fix, Drop, Star, Space, @with_pre, Parse, @p_str, Pattern, Alt, Delayed, parse_one, @E_str import Dates space = Drop(Star(Space())) PNonZeroInt64() = Parse(p"-?[1-9][0-9]*", Int64) PPosInt64() = Parse(p"[1-9][0-9]*", Int64) PPosZeroInt64() = Parse(p"[0-9][0-9]*", Int64) PCalendarNames() = p"[a-zA-Z0-9-\/\s|]+" @with_pre space begin sum = Delayed() weekday_short = Alt(map(x -> Pattern(uppercase(x)), Dates.ENGLISH.days_of_week_abbr)...) month_short = Alt(map(x -> Pattern(uppercase(x)), Dates.ENGLISH.months_abbr)...) brackets = E"(" + space + sum + space + E")" repeat = E"Repeat(" + space + sum + space + E")" > rd -> Repeat(rd) rdate_term = Alt() next = E"Next(" + (space + sum) + (E"," + space + sum)[0:end] + space + E")" |> parts -> Next(parts) next_inc = E"Next!(" + (space + sum) + (E"," + space + sum)[0:end] + space + E")" |> parts -> Next(parts, true) previous = E"Previous(" + (space + sum) + (E"," + space + sum)[0:end] + space + E")" |> parts -> Previous(parts) previous_inc = E"Previous!(" + (space + sum) + (E"," + space + sum)[0:end] + space + E")" |> parts -> Previous(parts, true) rdate_expr = rdate_term | brackets | repeat | next | next_inc | previous | previous_inc neg = Delayed() neg.matcher = rdate_expr | (E"-" + neg > -) cal_adj = neg + (E"@" + PCalendarNames() + E"[" + Alt(map(Pattern, collect(keys(HOLIDAY_ROUNDING_MAPPINGS)))...) + E"]")[0:1] |> xs -> length(xs) == 1 ? xs[1] : CalendarAdj(map(String, split(xs[2], "|")), xs[1], HOLIDAY_ROUNDING_MAPPINGS[xs[3]]) mult = Delayed() mult = cal_adj | ((PPosInt64() + space + E"*" + space + cal_adj) > (c,rd) -> multiply(rd, c)) | ((cal_adj + space + E"*" + space + PPosInt64()) > (rd,c) -> multiply(rd, c)) add = E"+" + mult sub = E"-" + mult > - sum.matcher = (sub | mult) + (add | mult)[0:end] |> Base.sum entry = sum + Eos() end function register_grammar!(term) # Handle the spacing correctly push!(rdate_term.matchers[2].matchers, term) end macro rd_str(arg::String) val = parse_one(arg, entry)[1] isa(val, RDate) || error("Unable to parse $(arg) as RDate") return val end function rdate(arg::String) val = parse_one(arg, entry)[1] isa(val, RDate) || error("Unable to parse $(arg) as RDate") return val end
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
code
1352
import Dates """ InvalidDayLDOM() When the day calculated is invalid, move to the last day of the month. Will use the "LDOM" short hand. """ struct InvalidDayLDOM <: InvalidDayConvention end adjust(::InvalidDayLDOM, day, month, year) = Dates.Date(year, month, Dates.daysinmonth(year, month)) Base.show(io::IO, ::InvalidDayLDOM) = print(io, "LDOM") """ InvalidDayFDONM() When the day calculated is invalid, move to the first day of the next month. Uses the "FDONM" short hand. """ struct InvalidDayFDONM <: InvalidDayConvention end adjust(::InvalidDayFDONM, day, month, year) = month == 12 ? Dates.Date(year+1, 1, 1) : Dates.Date(year, month+1, 1) Base.show(io::IO, ::InvalidDayFDONM) = print(io, "FDONM") """ InvalidDayNDONM() When the day calculated is invalid, move to the nth day of the next month where n is the number of days past the last day of the month. Uses the "NDONM" short hand. """ struct InvalidDayNDONM <: InvalidDayConvention end function adjust(::InvalidDayNDONM, day, month, year) dayδ = day - Dates.daysinmonth(year, month) return month == 12 ? Dates.Date(year+1, 1, dayδ) : Dates.Date(year, month+1, dayδ) end Base.show(io::IO, ::InvalidDayNDONM) = print(io, "NDONM") const INVALID_DAY_MAPPINGS = Dict( "LDOM" => InvalidDayLDOM(), "FDONM" => InvalidDayFDONM(), "NDONM" => InvalidDayNDONM() )
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
code
1768
import Dates using AutoHashEquals """ MonthIncrementPDOM() When incrementing by months (or years) then preserve the day of month from originally requested. Uses the "PDOM" shorthand """ struct MonthIncrementPDOM <: MonthIncrementConvention end adjust(::MonthIncrementPDOM, date::Dates.Date, new_month, new_year, cal_mgr::CalendarManager) = (new_year, new_month, Dates.day(date)) Base.show(io::IO, ::MonthIncrementPDOM) = print(io, "PDOM") """ MonthIncrementPDOMEOM() MonthIncrementPDOMEOM(calendars) When incrementing by months (or years) then preserve the day of month from originally requested, unless it's the last day of the month then maintain that. Uses the "PDOMEOM" short hand. To preserve the last business day of the month, then you can pass calendars as well. """ @auto_hash_equals struct MonthIncrementPDOMEOM <: MonthIncrementConvention calendars::Union{Vector{String}, Nothing} MonthIncrementPDOMEOM() = new(nothing) MonthIncrementPDOMEOM(calendars) = new(calendars) MonthIncrementPDOMEOM(calendars::String) = new(split(calendars, "|")) end function adjust(mic::MonthIncrementPDOMEOM, date::Dates.Date, new_month, new_year, cal_mgr::CalendarManager) ldom_rdate = LDOM(mic.calendars) ldom = apply(ldom_rdate, date, cal_mgr) if ldom == date new_ldom = apply(ldom_rdate, Dates.Date(new_year, new_month), cal_mgr) return Dates.yearmonthday(new_ldom) else return (new_year, new_month, Dates.day(date)) end end Base.show(io::IO, mic::MonthIncrementPDOMEOM) = mic.calendars === nothing ? print(io, "PDOMEOM") : print(io, "PDOMEOM@$(join(mic.calendars, "|"))") const MONTH_INCREMENT_MAPPINGS = Dict( "PDOM" => MonthIncrementPDOM(), "PDOMEOM" => MonthIncrementPDOMEOM() )
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
code
22348
import Dates using AutoHashEquals const WEEKDAYS = Dict(map(reverse,enumerate(map(Symbol ∘ uppercase, Dates.ENGLISH.days_of_week_abbr)))) const NTH_PERIODS = ["1st", "2nd", "3rd", "4th", "5th"] const NTH_LAST_PERIODS = ["Last", "2nd Last", "3rd Last", "4th Last", "5th Last"] const PERIODS = merge(Dict(map(reverse,enumerate(NTH_PERIODS))), Dict(map(reverse,enumerate(NTH_LAST_PERIODS)))) const MONTHS = Dict(zip(map(Symbol ∘ uppercase, Dates.ENGLISH.months_abbr),range(1,stop=12))) """ FDOM() FDOM(calendars) Calculate the first day of the month. Optionally can also take calendar names to determine the first business day of the month. ### Examples ```julia-repl julia> RDates.FDOM() + Date(2019,1,13) 2019-01-01 julia> rd"FDOM" + Date(2019,1,13) 2019-01-01 julia> cals = SimpleCalendarManager() julia> setcalendar!(cals, "WEEKEND", WeekendCalendar()) julia> apply(RDates.FDOM("WEEKEND"), Date(2017,1,13), cals) 2017-01-02 julia> apply(rd"FDOM@WEEKEND", Date(2017,1,13), cals) 2017-01-02 ``` """ struct FDOM <: RDate FDOM() = new() FDOM(calendars::Nothing) = new() FDOM(calendars) = CalendarAdj(calendars, new(), HolidayRoundingNBD()) end apply(::FDOM, d::Dates.Date, ::CalendarManager) = Dates.firstdayofmonth(d) multiply(x::FDOM, ::Integer) = x Base.:-(x::FDOM) = x Base.show(io::IO, ::FDOM) = print(io, "FDOM") register_grammar!(E"FDOM" > FDOM) register_grammar!(E"FDOM@" + PCalendarNames() > calendar_name -> FDOM(map(String, split(calendar_name, "|")))) """ LDOM() LDOM(calendars) Calculate the last day of the month. Optionally can also take calendar names to determine the last business day of the month. ### Examples ```julia-repl julia> RDates.LDOM() + Date(2019,1,13) 2019-01-31 julia> rd"LDOM" + Date(2019,1,13) 2019-01-31 julia> cals = SimpleCalendarManager() julia> setcalendar!(cals, "WEEKEND", WeekendCalendar()) julia> apply(RDates.LDOM("WEEKEND"), Date(2021,1,13), cals) 2021-01-29 julia> apply(rd"LDOM@WEEKEND", Date(2021,1,13), cals) 2021-01-29 ``` """ struct LDOM <: RDate LDOM() = new() LDOM(calendars::Nothing) = new() LDOM(calendars) = CalendarAdj(calendars, new(), HolidayRoundingPBD()) end apply(::LDOM, d::Dates.Date, ::CalendarManager) = Dates.lastdayofmonth(d) multiply(x::LDOM, ::Integer) = x Base.:-(x::LDOM) = x Base.show(io::IO, ::LDOM) = print(io, "LDOM") register_grammar!(E"LDOM" > LDOM) register_grammar!(E"LDOM@" + PCalendarNames() > calendar_name -> LDOM(map(String, split(calendar_name, "|")))) """ Easter(yearδ::Int64) A date that is well known from hunting eggs and pictures of bunnies, it's a rather tricky calculation to perform. We provide a simple method to allow you to get the Easter for the given year (plus some delta). !!! note `0E` will get the Easter of the current year, so it could be before or after the date you've provided. ### Examples ```julia-repl julia> RDates.Easter(0) + Date(2019,1,1) 2019-04-21 julia> rd"0E" + Date(2019,1,1) 2019-04-21 julia> RDates.Easter(0) + Date(2019,8,1) 2019-04-21 julia> RDates.Easter(10) + Date(2019,8,1) 2029-04-01 ``` """ struct Easter <: RDate yearδ::Int64 end function apply(rdate::Easter, date::Dates.Date, cal_mgr::CalendarManager) y = Dates.year(date) + rdate.yearδ a = rem(y, 19) b = div(y, 100) c = rem(y, 100) d = div(b, 4) e = rem(b, 4) f = div(b + 8, 25) g = div(b - f + 1, 3) h = rem(19*a + b - d - g + 15, 30) i = div(c, 4) k = rem(c, 4) l = rem(32 + 2*e + 2*i - h - k, 7) m = div(a + 11*h + 22*l, 451) n = div(h + l - 7*m + 114, 31) p = rem(h + l - 7*m + 114, 31) return Dates.Date(y, n, p + 1) end multiply(x::Easter, count::Integer) = Easter(x.yearδ*count) Base.:-(rdate::Easter) = Easter(-rdate.yearδ) Base.show(io::IO, rdate::Easter) = print(io, "$(rdate.yearδ)E") register_grammar!(PInt64() + E"E" > Easter) """ Day(days::Int64) Provides us with the ability to add or subtract days from a date. This is equivalent to the `Dates.Day` struct. ### Examples ```julia-repl julia> RDates.Day(3) + Date(2019,1,1) 2019-01-04 julia> rd"3d" + Date(2019,1,1) 2019-01-04 julia> RDates.Day(-2) + Date(2019,1,1) 2018-12-30 ``` """ struct Day <: RDate days::Int64 end apply(x::Day, y::Dates.Date, cal_mgr::CalendarManager) = y + Dates.Day(x.days) multiply(x::Day, count::Integer) = Day(x.days*count) Base.:-(x::Day) = Day(-x.days) Base.:+(x::Day, y::Day) = Day(x.days + y.days) Base.show(io::IO, rdate::Day) = print(io, "$(rdate.days)d") register_grammar!(PInt64() + E"d" > Day) """ Week(weeks::Int64) Provides us with the ability to add or subtract weeks from a date. This is equivalent to the `Dates.Week` struct. ### Examples ```julia-repl julia> RDates.Week(3) + Date(2019,1,1) 2019-01-22 julia> rd"3w" + Date(2019,1,1) 2019-01-22 julia> RDates.Week(-2) + Date(2019,1,1) 2018-12-18 ``` """ struct Week <: RDate weeks::Int64 end apply(x::Week, y::Dates.Date, cal_mgr::CalendarManager) = y + Dates.Week(x.weeks) multiply(x::Week, count::Integer) = Week(x.weeks*count) Base.:-(x::Week) = Week(-x.weeks) Base.:+(x::Week, y::Week) = Week(x.weeks + y.weeks) Base.:+(x::Day, y::Week) = Day(x.days + 7*y.weeks) Base.:+(x::Week, y::Day) = Day(7*x.weeks + y.days) Base.show(io::IO, rdate::Week) = print(io, "$(rdate.weeks)w") register_grammar!(PInt64() + E"w" > Week) """ Month(months::Int64) Month(months::Int64, idc::InvalidDayConvention, mic::MonthIncrementConvention) Provides us with the ability to move a specified number of months, with conventions to handle how we should increment and what to do if we fall on an invalid day. ### Examples ```julia-repl julia> RDates.Month(1) + Date(2019,1,31) 2019-02-28 julia> rd"1m" + Date(2019,1,31) 2019-02-28 julia> RDates.Month(1, RDates.InvalidDayFDONM(), RDates.MonthIncrementPDOM()) + Date(2019,1,31) 2019-03-01 julia> rd"1m[FDONM;PDOM]" + Date(2019,1,31) 2019-03-01 julia> RDates.Month(1, RDates.InvalidDayNDONM(), RDates.MonthIncrementPDOM()) + Date(2019,1,31) 2019-03-03 julia> rd"1m[NDONM;PDOM]" + Date(2019,1,31) 2019-03-03 julia> RDates.Month(1, RDates.InvalidDayNDONM(), RDates.MonthIncrementPDOMEOM()) + Date(2019,1,31) 2019-02-28 julia> rd"1m[NDONM;PDOMEOM]" + Date(2019,1,31) 2019-02-28 julia> RDates.Month(-1, RDates.InvalidDayNDONM(), RDates.MonthIncrementPDOMEOM()) + Date(2019,2,28) 2019-01-31 julia> rd"-1m[NDONM;PDOMEOM]" + Date(2019,2,28) 2019-01-31 ``` """ struct Month <: RDate months::Int64 idc::InvalidDayConvention mic::MonthIncrementConvention Month(months::Int64) = new(months, InvalidDayLDOM(), MonthIncrementPDOM()) Month(months::Int64, idc::InvalidDayConvention, mic::MonthIncrementConvention) = new(months, idc, mic) end function apply(rdate::Month, date::Dates.Date, cal_mgr::CalendarManager) y, m = Dates.yearmonth(date) ny = Dates.yearwrap(y, m, rdate.months) nm = Dates.monthwrap(m, rdate.months) ay, am, ad = adjust(rdate.mic, date, nm, ny, cal_mgr) ld = Dates.daysinmonth(ay, am) return ad <= ld ? Dates.Date(ay, am, ad) : adjust(rdate.idc, ad, am, ay) end multiply(x::Month, count::Integer) = Month(x.months*count, x.idc, x.mic) Base.:-(x::Month) = Month(-x.months) Base.show(io::IO, rdate::Month) = (print(io, "$(rdate.months)m["), show(io, rdate.idc), print(io, ";"), show(io, rdate.mic), print(io,"]")) register_grammar!(PInt64() + E"m" > Month) register_grammar!(PInt64() + E"m[" + Alt(map(Pattern, collect(keys(INVALID_DAY_MAPPINGS)))...) + E";" + Alt(map(Pattern, collect(keys(MONTH_INCREMENT_MAPPINGS)))...) + E"]" > (d,idc,mic) -> Month(d, INVALID_DAY_MAPPINGS[idc], MONTH_INCREMENT_MAPPINGS[mic])) # We also have the more complex PDOMEOM month increment which we handle separately. register_grammar!(PInt64() + E"m[" + Alt(map(Pattern, collect(keys(INVALID_DAY_MAPPINGS)))...) + E";PDOMEOM@" + PCalendarNames() + E"]" > (d,idc,calendar_name) -> Month(d, INVALID_DAY_MAPPINGS[idc], MonthIncrementPDOMEOM(map(String, split(calendar_name, "|"))))) """ Year(years::Int64) Year(years::Int64, idc::InvalidDayConvention, mic::MonthIncrementConvention) Provides us with the ability to move a specified number of months, with conventions to handle how we should increment and what to do if we fall on an invalid day. !!! note While these conventions are necessary, it's only around the handling of leap years and when we're on the last day of the February that it actually matters. ### Examples ```julia-repl julia> RDates.Year(1) + Date(2019,2,28) 2020-02-28 julia> rd"1y" + Date(2019,2,28) 2020-02-28 julia> RDates.Year(1, RDates.InvalidDayFDONM(), RDates.MonthIncrementPDOMEOM()) + Date(2019,2,28) 2020-02-29 julia> rd"1y[FDONM;PDOMEOM]" + Date(2019,2,28) 2020-02-29 julia> RDates.Year(1, RDates.InvalidDayLDOM(), RDates.MonthIncrementPDOM()) + Date(2020,2,29) 2021-02-28 julia> rd"1y[LDOM;PDOM]" + Date(2020,2,29) 2021-02-28 julia> RDates.Year(1, RDates.InvalidDayFDONM(), RDates.MonthIncrementPDOM()) + Date(2020,2,29) 2021-03-01 julia> rd"1y[FDONM;PDOM]" + Date(2020,2,29) 2021-03-01 ``` """ struct Year <: RDate years::Int64 idc::InvalidDayConvention mic::MonthIncrementConvention Year(years::Int64) = new(years, InvalidDayLDOM(), MonthIncrementPDOM()) Year(years::Int64, idc::InvalidDayConvention, mic::MonthIncrementConvention) = new(years, idc, mic) end function apply(rdate::Year, date::Dates.Date, cal_mgr::CalendarManager) oy, m = Dates.yearmonth(date) ny = oy + rdate.years (ay, am, ad) = adjust(rdate.mic, date, m, ny, cal_mgr) ld = Dates.daysinmonth(ay, am) return ad <= ld ? Dates.Date(ay, am, ad) : adjust(rdate.idc, ad, am, ay) end multiply(x::Year, count::Integer) = Year(x.years*count, x.idc, x.mic) Base.:-(x::Year) = Year(-x.years) Base.show(io::IO, rdate::Year) = (print(io, "$(rdate.years)y["), show(io, rdate.idc), print(io, ";"), show(io, rdate.mic), print(io,"]")) register_grammar!(PInt64() + E"y" > Year) register_grammar!(PInt64() + E"y[" + Alt(map(Pattern, collect(keys(INVALID_DAY_MAPPINGS)))...) + E";" + Alt(map(Pattern, collect(keys(MONTH_INCREMENT_MAPPINGS)))...) + E"]" > (d,idc,mic) -> Year(d, INVALID_DAY_MAPPINGS[idc], MONTH_INCREMENT_MAPPINGS[mic])) # We also have the more complex PDOMEOM month increment which we handle separately. register_grammar!(PInt64() + E"y[" + Alt(map(Pattern, collect(keys(INVALID_DAY_MAPPINGS)))...) + E";PDOMEOM@" + PCalendarNames() + E"]" > (d,idc,calendar_name) -> Year(d, INVALID_DAY_MAPPINGS[idc], MonthIncrementPDOMEOM(map(String, split(calendar_name, "|"))))) """ DayMonth(day::Int64, month::Int64) DayMonth(day::Int64, month::Symbol) Provides us with the ability to move to a specific day and month in the provided year. !!! note `1MAR` will get the 1st of March of the current year, so it could be before or after the date you've provided. ### Examples ```julia-repl julia> RDates.DayMonth(23, 10) + Date(2019,1,1) 2019-10-23 julia> RDates.DayMonth(23, :OCT) + Date(2019,1,1) 2019-10-23 julia> rd"23OCT" + Date(2019,1,1) 2019-10-23 ``` """ struct DayMonth <: RDate day::Int64 month::Int64 DayMonth(day::Int64, month::Int64) = new(day, month) DayMonth(day::Int64, month::Symbol) = new(day, RDates.MONTHS[month]) end apply(rdate::DayMonth, date::Dates.Date, cal_mgr::CalendarManager) = Dates.Date(Dates.year(date), rdate.month, rdate.day) multiply(x::DayMonth, ::Integer) = x Base.:-(x::DayMonth) = x Base.show(io::IO, rdate::DayMonth) = print(io, "$(rdate.day)$(uppercase(Dates.ENGLISH.months_abbr[rdate.month]))") register_grammar!(PPosInt64() + month_short > (d,m) -> DayMonth(d,MONTHS[Symbol(m)])) """ Date(date::Dates.Date) Date(year::Int64, month::Int64, day::Int64) Provides us with the ability to move to a specific date, irrespective of the date passed in. This is primarily used when you want to provide a pivot point for ranges which doesn't relate to the start or end. ### Examples ```julia-repl julia> RDates.Date(Dates.Date(2017,10,23)) + Date(2019,1,1) 2017-10-23 julia> RDates.Date(2017,10,23) + Date(2019,1,1) 2017-10-23 julia> rd"23OCT2017" + Date(2019,1,1) 2017-10-23 ``` """ struct Date <: RDate date::Dates.Date Date(date::Dates.Date) = new(date) Date(y::Int64, m::Int64, d::Int64) = new(Dates.Date(y, m, d)) end multiply(x::Date, ::Integer) = x Base.:-(x::Date) = x apply(rdate::Date, date::Dates.Date, cal_mgr::CalendarManager) = rdate.date Base.show(io::IO, rdate::Date) = print(io, "$(Dates.day(rdate.date))$(uppercase(Dates.ENGLISH.months_abbr[Dates.month(rdate.date)]))$(Dates.year(rdate.date))") register_grammar!(PPosInt64() + month_short + PPosInt64() > (d,m,y) -> Date(Dates.Date(y, MONTHS[Symbol(m)], d))) """ NthWeekdays(dayofweek::Int64, period::Int64) NthWeekdays(dayofweek::Symbol, period::Int64) Move to the nth weekday in the given month and year. This is commonly used for holiday calendars, such as [Thanksgiving](https://en.wikipedia.org/wiki/Thanksgiving) which in the U.S. falls on the 4th Thursday in November. !!! note It's possible that a given period (such as the 5th weekday) may exist for only a subsection of dates. While it's a valid RDate it may not produce valid results when applied (and will throw an exception) ### Examples ```julia-repl julia> RDates.NthWeekdays(:MON, 2) + Date(2019,1,1) 2019-01-14 julia> RDates.NthWeekdays(1, 2) + Date(2019,1,1) 2019-01-14 julia> rd"2nd MON" + Date(2019,1,1) 2019-01-14 julia> RDates.NthWeekdays(:MON, 5) + Date(2019,1,1) ERROR: ArgumentError: Day: 35 out of range (1:31) ``` """ struct NthWeekdays <: RDate dayofweek::Int64 period::Int64 NthWeekdays(dayofweek::Int64, period::Int64) = new(dayofweek, period) NthWeekdays(dayofweek::Symbol, period::Int64) = new(RDates.WEEKDAYS[dayofweek], period) end function apply(rdate::NthWeekdays, date::Dates.Date, cal_mgr::CalendarManager) wd = Dates.dayofweek(date) wd1st = mod(wd - mod(Dates.day(date), 7), 7) + 1 wd1stdiff = wd1st - rdate.dayofweek period = wd1stdiff > 0 ? rdate.period : rdate.period - 1 days = 7*period - wd1stdiff + 1 return Dates.Date(Dates.year(date), Dates.month(date), days) end multiply(x::NthWeekdays, ::Integer) = x Base.:-(x::NthWeekdays) = x Base.show(io::IO, rdate::NthWeekdays) = print(io, "$(NTH_PERIODS[rdate.period]) $(uppercase(Dates.ENGLISH.days_of_week_abbr[rdate.dayofweek]))") register_grammar!(Alt(map(Pattern, NTH_PERIODS)...) + space + weekday_short > (p,wd) -> NthWeekdays(WEEKDAYS[Symbol(wd)], PERIODS[p])) """ NthLastWeekdays(dayofweek::Int64, period::Int64) NthLastWeekdays(dayofweek::Symbol, period::Int64) Move to the nth last weekday in the given month and year. This is commonly used for holiday calendars, such as the Spring Bank Holiday in the UK, which is the last Monday in May. !!! note It's possible that a given period (such as the 5th Last weekday) may exist for only a subsection of dates. While it's a valid RDate it may not produce valid results when applied (and will throw an exception) ### Examples ```julia-repl julia> RDates.NthLastWeekdays(:MON, 2) + Date(2019,1,1) 2019-01-21 julia> RDates.NthLastWeekdays(1, 2) + Date(2019,1,1) 2019-01-21 julia> rd"2nd Last MON" + Date(2019,1,1) 2019-01-21 julia> RDates.NthLastWeekdays(:MON, 5) + Date(2019,1,1) ERROR: ArgumentError: Day: 0 out of range (1:31) ``` """ struct NthLastWeekdays <: RDate dayofweek::Int64 period::Int64 NthLastWeekdays(dayofweek::Int64, period::Int64) = new(dayofweek, period) NthLastWeekdays(dayofweek::Symbol, period::Int64) = new(RDates.WEEKDAYS[dayofweek], period) end function apply(rdate::NthLastWeekdays, date::Dates.Date, cal_mgr::CalendarManager) ldom = LDOM() + date ldom_dow = Dates.dayofweek(ldom) ldom_dow_diff = ldom_dow - rdate.dayofweek period = ldom_dow_diff >= 0 ? rdate.period - 1 : rdate.period days_to_sub = 7*period + ldom_dow_diff days = Dates.day(ldom) - days_to_sub return Dates.Date(Dates.year(date), Dates.month(date), days) end multiply(x::NthLastWeekdays, ::Integer) = x Base.:-(x::NthLastWeekdays) = x Base.show(io::IO, rdate::NthLastWeekdays) = print(io, "$(NTH_LAST_PERIODS[rdate.period]) $(uppercase(Dates.ENGLISH.days_of_week_abbr[rdate.dayofweek]))") register_grammar!(Alt(map(Pattern, NTH_LAST_PERIODS)...) + space + weekday_short > (p,wd) -> NthLastWeekdays(WEEKDAYS[Symbol(wd)], PERIODS[p])) """ Weekdays(dayofweek::Int64, count::Int64, inclusive::Bool = false) Weekdays(dayofweek::Symbol, count::Int64, inclusive::Bool = false) Provides a mechanism to ask for the next Saturday or the last Tuesday. The count specifies what we're looking for. `Weekdays(:MON, 1)` will ask for the next Monday, exclusive of the date started from. You can make it inclusive by passing the inclusive parameter with `Weekdays(:MON, 1, true)`. !!! note A count of `0` is not supported as it doesn't specify what you're actually looking for! Incrementing the count will then be additional weeks (forward or backwards) from the single count point. ### Examples ```julia-repl julia> RDates.Weekdays(:WED, 1) + Date(2019,9,24) # Tuesday 2019-09-25 julia> RDates.Weekdays(3, 1) + Date(2019,9,24) 2019-09-25 julia> rd"1WED" + Date(2019,9,24) 2019-09-25 julia> RDates.Weekdays(:WED, 1) + Date(2019,9,25) 2019-10-02 julia> RDates.Weekdays(:WED, 1, true) + Date(2019,9,25) 2019-09-25 julia> rd"1WED!" + Date(2019,9,25) 2019-09-25 julia> RDates.Weekdays(:WED, -1) + Date(2019,9,24) 2019-09-18 ``` """ struct Weekdays <: RDate dayofweek::Int64 count::Int64 inclusive::Bool function Weekdays(dayofweek::Int64, count::Int64, inclusive::Bool = false) count != 0 || error("Cannot create 0 Weekdays") new(dayofweek, count, inclusive) end function Weekdays(dayofweek::Symbol, count::Int64, inclusive::Bool = false) count != 0 || error("Cannot create 0 Weekdays") new(WEEKDAYS[dayofweek], count, inclusive) end end function apply(rdate::Weekdays, date::Dates.Date, cal_mgr::CalendarManager) dayδ = Dates.dayofweek(date) - rdate.dayofweek weekδ = rdate.count if rdate.count < 0 && (dayδ > 0 || (rdate.inclusive && dayδ == 0)) weekδ += 1 elseif rdate.count > 0 && (dayδ < 0 || (rdate.inclusive && dayδ == 0)) weekδ -= 1 end return date + Dates.Day(weekδ*7 - dayδ) end multiply(x::Weekdays, count::Integer) = Weekdays(x.dayofweek, x.count * count, x.inclusive) Base.:-(rdate::Weekdays) = Weekdays(rdate.dayofweek, -rdate.count) function Base.show(io::IO, rdate::Weekdays) weekday = uppercase(Dates.ENGLISH.days_of_week_abbr[rdate.dayofweek]) inclusive = rdate.inclusive ? "!" : "" print(io, "$(rdate.count)$weekday$inclusive") end register_grammar!(PNonZeroInt64() + weekday_short > (i,wd) -> Weekdays(WEEKDAYS[Symbol(wd)], i)) register_grammar!(PNonZeroInt64() + weekday_short + E"!" > (i,wd) -> Weekdays(WEEKDAYS[Symbol(wd)], i, true)) """ BizDayZero Wrapper for a zero day count in business days, which holds the direction. Direction can either be :next or :prev """ struct BizDayZero direction::Symbol function BizDayZero(direction::Symbol) direction in (:next, :prev) || error("unknown direction $direction for BizDayZero") new(direction) end end function Base.:-(x::BizDayZero) BizDayZero(x.direction == :next ? :prev : :next) end """ BizDays(days::Int64, calendars) BizDays(days::BizDayZero) It can be handy to work in business days at times, rather than calendar days. This allows us to move forwards or backwards `n` days. ```julia-repl julia> cal_mgr = SimpleCalendarManager() julia> setcalendar!(cal_mgr, "WEEKEND", WeekendCalendar()) julia> apply(RDates.BizDays(1, "WEEKEND"), Date(2021,7,9), cal_mgr) 2021-07-12 julia> apply(rd"1b@WEEKEND", Date(2021,7,9), cal_mgr) 2021-07-12 julia> apply(RDates.BizDays(-10, "WEEKEND"), Date(2021,7,9), cal_mgr) 2021-06-25 ``` If the date falls on a holiday, then it is first moved forward (or backwards) to a valid business day. ```julia-repl julia> apply(RDates.BizDays(1, "WEEKEND"), Date(2021,7,10), cal_mgr) 2021-07-13 ``` For zero business days, we could either want to move forwards or backwards. As such we provide `BizDayZero` which can be used to provide each. By default, `0b` will move forward ```julia-repl julia> apply(RDates.BizDays(RDates.BizDayZero(:next), "WEEKEND"), Date(2021,7,10), cal_mgr) 2021-07-12 julia> apply(RDates.BizDays(RDates.BizDayZero(:prev), "WEEKEND"), Date(2021,7,10), cal_mgr) 2021-07-09 julia> apply(rd"0b@WEEKEND", Date(2021,7,10), cal_mgr) 2021-07-12 julia> apply(rd"-0b@WEEKEND", Date(2021,7,10), cal_mgr) 2021-07-09 ``` """ @auto_hash_equals struct BizDays <: RDate days::Union{Int64, BizDayZero} calendar_names::Vector{String} function BizDays(days::Int64, calendar_names) days = days != 0 ? days : BizDayZero(:next) new(days, calendar_names) end BizDays(days::Int64, calendar_names::String) = BizDays(days, split(calendar_names, "|")) BizDays(days::BizDayZero, calendar_names) = new(days, calendar_names) BizDays(days::BizDayZero, calendar_names::String) = new(days, split(calendar_names, "|")) end function apply(rdate::BizDays, date::Dates.Date, cal_mgr::CalendarManager) cal = calendar(cal_mgr, rdate.calendar_names) if isa(rdate.days, BizDayZero) rounding = rdate.days.direction == :next ? HolidayRoundingNBD() : HolidayRoundingPBD() apply(rounding, date, cal) else rounding = rdate.days > 0 ? HolidayRoundingNBD() : HolidayRoundingPBD() date = apply(rounding, date, cal) count = rdate.days if rdate.days > 0 while count > 0 date = apply(rounding, date + Dates.Day(1), cal) count -= 1 end elseif rdate.days < 0 while count < 0 date = apply(rounding, date - Dates.Day(1), cal) count += 1 end end date end end function multiply(x::BizDays, count::Integer) x = count < 0 ? -x : x days = isa(x.days, BizDayZero) ? x.days : x.days * abs(count) return BizDays(days, x.calendar_names) end Base.:-(x::BizDays) = BizDays(-x.days, x.calendar_names) register_grammar!(PPosZeroInt64() + E"b@" + PCalendarNames() > (days,calendar_name) -> BizDays(days, map(String, split(calendar_name, "|"))))
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
code
3051
""" range(from::Date, rdate::RDate; inc_from=true, cal_mgr=nothing) range(from::Date, to::Date, rdate::RDate; inc_from=true, inc_to=true, cal_mgr=nothing) The range provides a mechanism for iterating over a range of dates given a period. This can provide a mechanism for getting an infinite range (from a given date) or appropriately clipped. ```julia-repl julia> collect(Iterators.take(range(Date(2017,1,25), rd"1d"), 3)) 3-element Vector{Date}: 2017-01-25 2017-01-26 2017-01-27 julia> collect(Iterators.take(range(Date(2017,1,25), rd"1d"; inc_from=false), 3)) 3-element Vector{Date}: 2017-01-26 2017-01-27 2017-01-28 julia> collect(range(Date(2019,4,17), Date(2019,4,22), rd"2d")) 3-element Vector{Date}: 2019-04-17 2019-04-19 2019-04-21 ``` Under the hoods, the range will `multiply` the period. Since non-periodic RDates will always give back self when you multiply it allows us to set a reference point. ```julia-repl julia> rd"1JAN2001+3m+3rd WED" 1JAN2001+3m[LDOM;PDOM]+3rd WED julia> 3*rd"1JAN2001+3m+3rd WED" 1JAN2001+9m[LDOM;PDOM]+3rd WED ``` This provides the basic building blocks to come up with more complex functionality. For example to get the next four [IMM dates](https://en.wikipedia.org/wiki/IMM_dates) ```julia-repl julia> d = Date(2017,1,1) julia> collect(Iterators.take(range(d, rd"1MAR+3m+3rd WED"), 4)) 4-element Vector{Date}: 2017-03-15 2017-06-21 2017-09-20 2017-12-20 ``` """ struct RDateRange from::Dates.Date to::Union{Dates.Date, Nothing} period::RDate inc_from::Bool inc_to::Bool calendar_mgr::CalendarManager end function Base.iterate(iter::RDateRange, state=nothing) if state === nothing count = 0 elem = apply(multiply(iter.period, count), iter.from, iter.calendar_mgr) while elem > iter.from count -= 1 elem = apply(multiply(iter.period, count), iter.from, iter.calendar_mgr) end from_op = iter.inc_from ? Base.:< : Base.:<= while from_op(elem, iter.from) count += 1 elem = apply(multiply(iter.period, count), iter.from, iter.calendar_mgr) end state = (elem, count) end elem, count = state op = iter.inc_to ? Base.:> : Base.:>= if iter.to !== nothing && op(elem,iter.to) return nothing end return (elem, (apply(multiply(iter.period, count+1), iter.from, iter.calendar_mgr), count+1)) end Base.IteratorSize(::Type{RDateRange}) = Base.SizeUnknown() Base.eltype(::Type{RDateRange}) = Dates.Date function Base.range(from::Dates.Date, period::RDate; inc_from::Bool=true, cal_mgr::Union{CalendarManager,Nothing}=nothing) return RDateRange(from, nothing, period, inc_from, false, cal_mgr !== nothing ? cal_mgr : NullCalendarManager()) end function Base.range(from::Dates.Date, to::Dates.Date, period::RDate; inc_from::Bool=true, inc_to::Bool=true, cal_mgr::Union{CalendarManager,Nothing}=nothing) return RDateRange(from, to, period, inc_from, inc_to, cal_mgr !== nothing ? cal_mgr : NullCalendarManager()) end
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
code
5810
import Dates """ HolidayRoundingNBD() Move to the next business day when a date falls on a holiday. #### Examples ```julia-repl julia> cal_mgr = SimpleCalendarManager() julia> setcalendar!(cal_mgr, "WEEKEND", WeekendCalendar()) julia> apply(RDates.CalendarAdj("WEEKEND", rd"0d", RDates.HolidayRoundingNBD()), Date(2021,7,10), cal_mgr) 2021-07-12 julia> apply(rd"0d@WEEKEND[NBD]", Date(2021,7,10), cal_mgr) 2021-07-12 ``` """ struct HolidayRoundingNBD <: HolidayRoundingConvention end function apply(::HolidayRoundingNBD, date::Dates.Date, calendar::Calendar)::Dates.Date while is_holiday(calendar, date) date += Dates.Day(1) end date end Base.show(io::IO, ::HolidayRoundingNBD) = print(io, "NBD") """ HolidayRoundingPBD() Move to the previous business day when a date falls on a holiday. #### Examples ```julia-repl julia> cal_mgr = SimpleCalendarManager() julia> setcalendar!(cal_mgr, "WEEKEND", WeekendCalendar()) julia> apply(RDates.CalendarAdj("WEEKEND", rd"0d", RDates.HolidayRoundingPBD()), Date(2021,7,10), cal_mgr) 2021-07-09 julia> apply(rd"0d@WEEKEND[PBD]", Date(2021,7,10), cal_mgr) 2021-07-09 ``` """ struct HolidayRoundingPBD <: HolidayRoundingConvention end function apply(::HolidayRoundingPBD, date::Dates.Date, calendar::Calendar)::Dates.Date while is_holiday(calendar, date) date -= Dates.Day(1) end date end Base.show(io::IO, ::HolidayRoundingPBD) = print(io, "PBD") """ HolidayRoundingNBDSM() Move to the next business day when a date falls on a holiday, unless the adjusted date would be in the next month, then go the previous business date instead. #### Examples ```julia-repl julia> cal_mgr = SimpleCalendarManager() julia> setcalendar!(cal_mgr, "WEEKEND", WeekendCalendar()) julia> apply(RDates.CalendarAdj("WEEKEND", rd"0d", RDates.HolidayRoundingNBDSM()), Date(2021,7,10), cal_mgr) 2021-07-12 julia> apply(rd"0d@WEEKEND[NBDSM]", Date(2021,7,10), cal_mgr) 2021-07-12 julia> apply(rd"0d@WEEKEND[NBDSM]", Date(2021,7,31), cal_mgr) 2021-07-30 ``` """ struct HolidayRoundingNBDSM <: HolidayRoundingConvention end function apply(::HolidayRoundingNBDSM, date::Dates.Date, calendar::Calendar)::Dates.Date new_date = date while is_holiday(calendar, new_date) new_date += Dates.Day(1) end if Dates.month(new_date) != Dates.month(date) new_date = date while is_holiday(calendar, new_date) new_date -= Dates.Day(1) end end new_date end Base.show(io::IO, ::HolidayRoundingNBDSM) = print(io, "NBDSM") """ HolidayRoundingPBDSM() Move to the previous business day when a date falls on a holiday, unless the adjusted date would be in the previous month, then go the next business date instead. #### Examples ```julia-repl julia> cal_mgr = SimpleCalendarManager() julia> setcalendar!(cal_mgr, "WEEKEND", WeekendCalendar()) julia> apply(RDates.CalendarAdj("WEEKEND", rd"0d", RDates.HolidayRoundingPBDSM()), Date(2021,7,10), cal_mgr) 2021-07-09 julia> apply(rd"0d@WEEKEND[PBDSM]", Date(2021,7,10), cal_mgr) 2021-07-09 julia> apply(rd"0d@WEEKEND[NBDSM]", Date(2021,8,1), cal_mgr) 2021-08-02 ``` """ struct HolidayRoundingPBDSM <: HolidayRoundingConvention end function apply(::HolidayRoundingPBDSM, date::Dates.Date, calendar::Calendar)::Dates.Date new_date = date while is_holiday(calendar, new_date) new_date -= Dates.Day(1) end if Dates.month(new_date) != Dates.month(date) new_date = date while is_holiday(calendar, new_date) new_date += Dates.Day(1) end end new_date end Base.show(io::IO, ::HolidayRoundingPBDSM) = print(io, "PBDSM") """ HolidayRoundingNR() No rounding, so just give back the same date even though it's a holiday. Uses "NR" for short hand. #### Examples ```julia-repl julia> cal_mgr = SimpleCalendarManager() julia> setcalendar!(cal_mgr, "WEEKEND", WeekendCalendar()) julia> apply(RDates.CalendarAdj("WEEKEND", rd"0d", RDates.HolidayRoundingNR()), Date(2021,7,10), cal_mgr) 2021-07-10 julia> apply(rd"0d@WEEKEND[NR]", Date(2021,7,10), cal_mgr) 2021-07-10 ``` """ struct HolidayRoundingNR <: HolidayRoundingConvention end apply(::HolidayRoundingNR, date::Dates.Date, ::Calendar) = date Base.show(io::IO, ::HolidayRoundingNR) = print(io, "NR") """ HolidayRoundingNearest() Move to the nearest business day, with the next one taking precedence in a tie. This is commonly used for U.S. calendars which will adjust Sat to Fri and Sun to Mon for their fixed date holidays. #### Examples ```julia-repl julia> cal_mgr = SimpleCalendarManager() julia> setcalendar!(cal_mgr, "WEEKEND", WeekendCalendar()) julia> apply(RDates.CalendarAdj("WEEKEND", rd"0d", RDates.HolidayRoundingNearest()), Date(2021,7,10), cal_mgr) 2021-07-09 julia> apply(rd"0d@WEEKEND[NEAR]", Date(2021,7,10), cal_mgr) 2021-07-09 julia> apply(rd"0d@WEEKEND[NEAR]", Date(2021,7,11), cal_mgr) 2021-07-12 ``` """ struct HolidayRoundingNearest <: HolidayRoundingConvention end function apply(::HolidayRoundingNearest, date::Dates.Date, cal::Calendar) is_holiday(cal, date) || return date count = 0 result = nothing while result === nothing up_date = date + Dates.Day(count) if !is_holiday(cal, up_date) result = up_date else down_date = date - Dates.Day(count) if !is_holiday(cal, down_date) result = down_date end end count += 1 end result end Base.show(io::IO, ::HolidayRoundingNearest) = print(io, "NEAR") const HOLIDAY_ROUNDING_MAPPINGS = Dict( "NR" => HolidayRoundingNR(), "NBD" => HolidayRoundingNBD(), "PBD" => HolidayRoundingPBD(), "NBDSM" => HolidayRoundingNBDSM(), "PBDSM" => HolidayRoundingPBDSM(), "NEAR" => HolidayRoundingNearest() )
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
code
15158
using Test using RDates using Dates using ParserCombinator cal_mgr = SimpleCalendarManager() setcalendar!(cal_mgr, "WEEKEND", WeekendCalendar()) setcalendar!(cal_mgr, "WEEK/END", calendar(cal_mgr, "WEEKEND")) setcalendar!(cal_mgr, "WEEK-END", calendar(cal_mgr, "WEEKEND")) setcalendar!(cal_mgr, "WEEK END", calendar(cal_mgr, "WEEKEND")) setcachedcalendar!(cal_mgr, "CACHED WEEKEND", calendar(cal_mgr, "WEEKEND")) @testset "RDates" verbose=true begin @testset "Calendar Holidays" begin @test holidays(calendar(cal_mgr, "WEEKEND"), Date(2021,7,8), Date(2021,7,11)) == Bool[0, 0, 1, 1] @test holidays(calendar(cal_mgr, "WEEKEND"), Date(2021,7,8), Date(2021,7,9)) == Bool[0, 0] @test holidaycount(calendar(cal_mgr, "WEEKEND"), Date(2021,7,4), Date(2021,7,20)) == 5 @test bizdaycount(calendar(cal_mgr, "WEEKEND"), Date(2021,7,4), Date(2021,7,20)) == 12 @test holidays(calendar(cal_mgr, "CACHED WEEKEND"), Date(2021,7,8), Date(2021,7,11)) == Bool[0, 0, 1, 1] @test holidays(calendar(cal_mgr, "CACHED WEEKEND"), Date(2021,7,8), Date(2021,7,9)) == Bool[0, 0] @test holidaycount(calendar(cal_mgr, "CACHED WEEKEND"), Date(2021,7,4), Date(2021,7,20)) == 5 @test bizdaycount(calendar(cal_mgr, "CACHED WEEKEND"), Date(2021,7,4), Date(2021,7,20)) == 12 @test holidays(calendar(cal_mgr, "CACHED WEEKEND"), Date(2031,1,30), Date(2031,2,3)) == Bool[0, 0, 1, 1, 0] @test holidays(calendar(cal_mgr, "CACHED WEEKEND"), Date(2011,2,3), Date(2011,2,6)) == Bool[0, 0, 1, 1] end @testset "Next and Previous" begin @test rd"Next(0E, 1E)" + Date(2021,1,1) == Date(2021,4,4) @test rd"Next(0E, 1E)" + Date(2021,4,3) == Date(2021,4,4) @test rd"Next(0E, 1E)" + Date(2021,4,4) == Date(2022,4,17) @test rd"Next!(0E, 1E)" + Date(2021,4,4) == Date(2021,4,4) @test rd"Next!(0E, 1E)" + Date(2021,4,5) == Date(2022,4,17) @test rd"Next(0E, -1E)" + Date(2021,1,1) == Date(2021,4,4) @test_throws ErrorException rd"Next(0E, -1E)" + Date(2021,12,31) @test rd"Previous(0E, -1E)" + Date(2021,1,1) == Date(2020,4,12) @test rd"Previous(0E, -1E)" + Date(2020,4,13) == Date(2020,4,12) @test rd"Previous(0E, -1E)" + Date(2020,4,12) == Date(2019,4,21) @test rd"Previous!(0E, -1E)" + Date(2020,4,12) == Date(2020,4,12) @test rd"Previous!(0E, -1E)" + Date(2020,4,11) == Date(2019,4,21) @test rd"Previous(0E, 1E)" + Date(2021,12,31) == Date(2021,4,4) @test_throws ErrorException rd"Previous(0E, 1E)" + Date(2021,1,1) @test -rd"Next(1d)" == rd"Previous(-1d)" @test rd"-Next(1d)" == rd"Previous(-1d)" @test -2*rd"Next(1d)" == rd"Previous(-2d)" @test rd"-2*Next(1d)" == rd"Previous(-2d)" @test -rd"Previous(-1d)" == rd"Next(1d)" @test rd"-Previous(-1d)" == rd"Next(1d)" @test -2*rd"Previous(-1d)" == rd"Next(2d)" @test rd"-2*Previous(-1d)" == rd"Next(2d)" end @testset "Rounding Conventions" begin @test apply(rd"0d@WEEKEND[NBD]", Date(2021,7,10), cal_mgr) == Date(2021,7,12) @test apply(rd"0d@WEEKEND[NBD]", Date(2021,7,11), cal_mgr) == Date(2021,7,12) @test apply(rd"0d@WEEKEND[NBDSM]", Date(2021,7,10), cal_mgr) == Date(2021,7,12) @test apply(rd"0d@WEEKEND[NBDSM]", Date(2021,7,11), cal_mgr) == Date(2021,7,12) @test apply(rd"0d@WEEKEND[PBD]", Date(2021,7,10), cal_mgr) == Date(2021,7,9) @test apply(rd"0d@WEEKEND[PBD]", Date(2021,7,11), cal_mgr) == Date(2021,7,9) @test apply(rd"0d@WEEKEND[PBDSM]", Date(2021,7,10), cal_mgr) == Date(2021,7,9) @test apply(rd"0d@WEEKEND[PBDSM]", Date(2021,7,11), cal_mgr) == Date(2021,7,9) @test apply(rd"0d@WEEKEND[NR]", Date(2021,7,10), cal_mgr) == Date(2021,7,10) @test apply(rd"0d@WEEKEND[NR]", Date(2021,7,11), cal_mgr) == Date(2021,7,11) @test apply(rd"0d@WEEKEND[NEAR]", Date(2021,7,10), cal_mgr) == Date(2021,7,9) @test apply(rd"0d@WEEKEND[NEAR]", Date(2021,7,11), cal_mgr) == Date(2021,7,12) # same month special casing @test apply(rd"0d@WEEKEND[NBDSM]", Date(2021,7,31), cal_mgr) == Date(2021,7,30) @test apply(rd"0d@WEEKEND[NBDSM]", Date(2021,8,1), cal_mgr) == Date(2021,8,2) @test apply(rd"0d@WEEKEND[PBDSM]", Date(2021,7,31), cal_mgr) == Date(2021,7,30) @test apply(rd"0d@WEEKEND[PBDSM]", Date(2021,8,1), cal_mgr) == Date(2021,8,2) end @testset "Calendar Formats" begin @test apply(rd"0d@WEEKEND[NBD]", Date(2021,7,10), cal_mgr) == Date(2021,7,12) @test apply(rd"0d@WEEK/END[NBD]", Date(2021,7,10), cal_mgr) == Date(2021,7,12) @test apply(rd"0d@WEEK END[NBD]", Date(2021,7,10), cal_mgr) == Date(2021,7,12) @test apply(rd"0d@WEEK-END[NBD]", Date(2021,7,10), cal_mgr) == Date(2021,7,12) @test apply(rd"0b@WEEKEND", Date(2021,7,10), cal_mgr) == Date(2021,7,12) @test apply(rd"0b@WEEK/END", Date(2021,7,10), cal_mgr) == Date(2021,7,12) @test apply(rd"0b@WEEK END", Date(2021,7,10), cal_mgr) == Date(2021,7,12) @test apply(rd"0b@WEEK-END", Date(2021,7,10), cal_mgr) == Date(2021,7,12) end @testset "Calendar Adjustments" begin cal_mgr = RDates.SimpleCalendarManager(Dict("WEEKEND" => RDates.WeekendCalendar())) @test apply(RDates.CalendarAdj(["WEEKEND"], rd"1d", RDates.HolidayRoundingNBD()), Date(2019,4,16), cal_mgr) == Date(2019,4,17) @test apply(RDates.CalendarAdj(["WEEKEND"], rd"1d", RDates.HolidayRoundingNBD()), Date(2019,9,27), cal_mgr) == Date(2019,9,30) @test apply(RDates.CalendarAdj(["WEEKEND"], rd"1d", RDates.HolidayRoundingNBD()), Date(2019,11,29), cal_mgr) == Date(2019,12,2) @test apply(RDates.CalendarAdj(["WEEKEND"], rd"1d", RDates.HolidayRoundingNBDSM()), Date(2019,11,29), cal_mgr) == Date(2019,11,29) end @testset "Business Days" begin @test apply(rd"0b@WEEKEND", Date(2019,9,28), cal_mgr) == Date(2019,9,30) @test apply(rd"-0b@WEEKEND", Date(2019,9,28), cal_mgr) == Date(2019,9,27) @test apply(rd"1b@WEEKEND", Date(2019,9,28), cal_mgr) == Date(2019,10,1) @test apply(rd"-1b@WEEKEND", Date(2019,9,28), cal_mgr) == Date(2019,9,26) @test apply(rd"2b@WEEKEND", Date(2019,9,28), cal_mgr) == Date(2019,10,2) end @testset "Add Ordering" begin @test rd"1d" + Date(2019,4,16) == Date(2019,4,17) @test Date(2019,4,16) + rd"1d" == Date(2019,4,17) @test rd"1d+2d" == rd"1d" + rd"2d" @test rd"3*1d" == rd"3d" end @testset "Month and Year Conventions" begin @test RDates.Year(1) + Date(2016,2,29) == Date(2017,2,28) @test Dates.Year(1) + Date(2016,2,29) == Date(2017,2,28) @test rd"1y" + Date(2016,2,29) == Date(2017,2,28) @test RDates.Year(1, RDates.InvalidDayLDOM(), RDates.MonthIncrementPDOM()) + Date(2016,2,29) == Date(2017,2,28) @test rd"1y[LDOM;PDOM]" + Date(2016,2,29) == Date(2017,2,28) @test RDates.Year(1, RDates.InvalidDayFDONM(), RDates.MonthIncrementPDOM()) + Date(2016,2,29) == Date(2017,3,1) @test rd"1y[FDONM;PDOM]" + Date(2016,2,29) == Date(2017,3,1) @test RDates.Month(1) + Date(2019,1,31) == Date(2019,2,28) @test Dates.Month(1) + Date(2019,1,31) == Date(2019,2,28) @test rd"1m" + Date(2019,1,31) == Date(2019,2,28) @test RDates.Month(1, RDates.InvalidDayNDONM(), RDates.MonthIncrementPDOM()) + Date(2019,1,31) == Date(2019,3,3) @test rd"1m[NDONM;PDOM]" + Date(2019,1,31) == Date(2019,3,3) @test RDates.Month(1, RDates.InvalidDayFDONM(), RDates.MonthIncrementPDOM()) + Date(2019,1,31) == Date(2019,3,1) @test rd"1m[FDONM;PDOM]" + Date(2019,1,31) == Date(2019,3,1) @test RDates.Month(1, RDates.InvalidDayNDONM(), RDates.MonthIncrementPDOMEOM()) + Date(2019,1,31) == Date(2019,2,28) @test rd"1m[NDONM;PDOMEOM]" + Date(2019,1,31) == Date(2019,2,28) @test RDates.Month(1, RDates.InvalidDayNDONM(), RDates.MonthIncrementPDOMEOM()) + Date(2019,1,30) == Date(2019,3,2) @test rd"1m[NDONM;PDOMEOM]" + Date(2019,1,30) == Date(2019,3,2) # PDOMEOM can also support calendars to work off the last business day of the month @test apply(rd"3m[LDOM;PDOMEOM@WEEKEND]", Date(2019,8,30), cal_mgr) == Date(2019,11,29) end @testset "Parsing Whitespace" begin @test rd" 1d" == rd"1d" @test rd"1d + 3d" == rd"1d+3d" @test rd"--1d" == rd"1d" end @testset "Days" begin @test rd"1d" + Date(2019,4,16) == Date(2019,4,17) @test rd"1d" + Date(2019,4,30) == Date(2019,5,1) @test rd"0d" + Date(2015,3,23) == Date(2015,3,23) @test rd"7d" + Date(2017,10,25) == Date(2017,11,1) @test rd"-1d" + Date(2014,1,1) == Date(2013,12,31) end @testset "Weeks" begin @test rd"1w" + Date(2019,4,16) == Date(2019,4,23) @test rd"1w" + Date(2019,4,30) == Date(2019,5,7) @test rd"0w" + Date(2015,3,23) == Date(2015,3,23) @test rd"7w" + Date(2017,10,25) == Date(2017,12,13) @test rd"-1w" + Date(2014,1,1) == Date(2013,12,25) end @testset "Months" begin @test rd"1m" + Date(2019,4,16) == Date(2019,5,16) @test rd"1m" + Date(2019,4,30) == Date(2019,5,30) @test rd"0m" + Date(2015,3,23) == Date(2015,3,23) @test rd"12m" + Date(2017,10,25) == Date(2018,10,25) @test rd"-1m" + Date(2014,1,1) == Date(2013,12,1) end @testset "Years" begin @test rd"1y" + Date(2019,4,16) == Date(2020,4,16) @test rd"1y" + Date(2019,4,30) == Date(2020,4,30) @test rd"0m" + Date(2015,3,23) == Date(2015,3,23) @test rd"12y" + Date(2017,10,25) == Date(2029,10,25) @test rd"-1y" + Date(2014,1,1) == Date(2013,1,1) end @testset "Day Months" begin @test rd"12MAR" + Date(2018,3,3) == Date(2018,3,12) @test rd"1JAN" + Date(2019,12,31) == Date(2019,1,1) @test rd"1JAN" + Date(2020,1,1) == Date(2020,1,1) end @testset "Easters" begin @test rd"0E" + Date(2018,3,3) == Date(2018,4,1) @test rd"0E" + Date(2018,12,3) == Date(2018,4,1) @test rd"1E" + Date(2018,3,3) == Date(2019,4,21) @test rd"-1E" + Date(2018,3,3) == Date(2017,4,16) end @testset "Weekdays" begin @test rd"1MON" + Date(2017,10,25) == Date(2017,10,30) @test rd"10SAT" + Date(2017,10,25) == Date(2017,12,30) @test rd"-1WED" + Date(2017,10,25) == Date(2017,10,18) @test rd"-10FRI" + Date(2017,10,25) == Date(2017,8,18) @test rd"-1TUE" + Date(2017,10,25) == Date(2017,10,24) end @testset "Dates" begin @test rd"1JAN2019" + Date(2017,10,25) == Date(2019,1,1) @test RDates.Date(Date(2019,1,1)) + Date(2017,10,25) == Date(2019,1,1) end @testset "Non Supported Negations" begin @test rd"1d" - rd"1st MON" == rd"1d" + rd"1st MON" end @testset "Nth Weekdays" begin @test rd"1st MON" + Date(2017,10,25) == Date(2017,10,2) @test rd"2nd FRI" + Date(2017,10,25) == Date(2017,10,13) @test rd"4th SAT" + Date(2017,11,25) == Date(2017,11,25) @test rd"5th SUN" + Date(2017,12,25) == Date(2017,12,31) end @testset "Nth Last Weekdays" begin @test rd"Last MON" + Date(2017,10,24) == Date(2017,10,30) @test rd"2nd Last FRI" + Date(2017,10,24) == Date(2017,10,20) @test rd"5th Last SUN" + Date(2017,12,24) == Date(2017,12,3) end @testset "Bad Nth Weekdays" begin @test_throws ArgumentError rd"5th WED" + Date(2017,10,25) @test_throws ArgumentError rd"5th MON" + Date(2017,6,1) end @testset "First/Last Day of Month" begin @test rd"FDOM" + Date(2017,10,25) == Date(2017,10,1) @test rd"LDOM" + Date(2017,10,25) == Date(2017,10,31) # FDOM and LDOM can support calendars as well. @test apply(rd"FDOM@WEEKEND", Date(2019,9,25), cal_mgr) == Date(2019,9,2) @test apply(rd"LDOM@WEEKEND", Date(2019,8,25), cal_mgr) == Date(2019,8,30) end @testset "Basic Compounds" begin @test rd"1d+1d" + Date(2017,10,26) == Date(2017,10,28) @test rd"2*1d" + Date(2017,10,26) == Date(2017,10,28) @test rd"1d+1d+1d+1d" + Date(2017,10,26) == Date(2017,10,30) @test rd"4*1d" + Date(2017,10,26) == Date(2017,10,30) @test rd"2*2d" + Date(2017,10,26) == Date(2017,10,30) @test rd"1d-1d+1d-1d" + Date(2017,10,26) == Date(2017,10,26) @test rd"2*3d+1d" + Date(2019,4,16) == Date(2019,4,23) @test rd"2*(3d+1d)" + Date(2019,4,16) == Date(2019,4,24) @test rd"2d-1E" + Date(2019,4,16) == Date(2018,4,1) @test rd"1d" - rd"2*1d" + Date(2019,5,1) == Date(2019,4,30) @test RDates.multiply(rd"1d", 3) + Date(2017,4,14) == Date(2017,4,17) end @testset "Roll vs No-Roll Multiplication" begin # If we apply each 1m addition individually, then invalid days in Feb kicks in. @test rd"1m+1m" + Date(2019,1,31) == Date(2019,3,28) @test rd"2*Repeat(1m)" + Date(2019,1,31) == Date(2019,3,28) # Normal multiplication will embed this in the period instead. @test rd"2m" + Date(2019,1,31) == Date(2019,3,31) @test rd"2*1m" + Date(2019,1,31) == Date(2019,3,31) end @testset "Ranges" begin @test collect(range(Date(2017,1,1), Date(2017,1,3), rd"1d")) == [Date(2017,1,1), Date(2017,1,2), Date(2017,1,3)] @test collect(range(Date(2017,1,1), Date(2017,1,3), rd"2d")) == [Date(2017,1,1), Date(2017,1,3)] @test collect(range(Date(2017,1,1), Date(2017,1,18), rd"1d+1w")) == [Date(2017,1,1), Date(2017,1,9), Date(2017,1,17)] @test collect(range(Date(2017,1,1), Date(2017,1,3), rd"1d", inc_from=false)) == [Date(2017,1,2), Date(2017,1,3)] @test collect(range(Date(2017,1,1), Date(2017,1,3), rd"1d", inc_to=false)) == [Date(2017,1,1), Date(2017,1,2)] @test collect(range(Date(2017,1,1), Date(2017,1,3), rd"1d", inc_from=false, inc_to=false)) == [Date(2017,1,2)] @test collect(range(Date(2017,1,1), Date(2018,1,1), rd"1DEC2017 + 3m + 3rd WED")) == [Date(2017,3,15), Date(2017,6,21), Date(2017,9,20), Date(2017,12,20)] end @testset "Parsing Methods" begin @test rdate("1d") == rd"1d" @test rdate("3*2d") == rd"3*2d" @test rd"3*2d" == 3*rd"2d" end @testset "Failed Parsing" begin @test_throws ParserCombinator.ParserException rdate("1*2") @test_throws ParserCombinator.ParserException rdate("1dw") @test_throws ParserCombinator.ParserException rdate("+2d") @test_throws ParserCombinator.ParserException rdate("2d+") @test_throws ParserCombinator.ParserException rdate("d") end @testset "String Forms" begin @test string(rd"1d") == "1d" @test string(rd"3d + 2w") == "17d" @test string(rd"2*(1m + 1y)") == "2m[LDOM;PDOM]+2y[LDOM;PDOM]" @test string(rd"2*Repeat(1m)") == "2*Repeat(1m[LDOM;PDOM])" @test string(rd"1m[LDOM;PDOMEOM@A]@B[NBD]") == "(1m[LDOM;PDOMEOM@A])@B[NBD]" @test string(rd"(1m+2d)@A[PBD]") == "(1m[LDOM;PDOM]+2d)@A[PBD]" end end
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
docs
2050
# RDates *A relative date library for Julia* | **Documentation** | **Build Status** | |:-------------------------------------------------------------------------:|:-------------------------------------------------------------:| | [![][docs-stable-img]][docs-stable-url] [![][docs-latest-img]][docs-latest-url] | [![][travis-img]][travis-url] [![][codecov-img]][codecov-url] | This is a project that builds around the [Dates](https://docs.julialang.org/en/v1/stdlib/Dates/) module to allow complex date operations. The aim is to provide a standard toolset to allow you to answer questions such as *when is the next Easter* or *what is the 3rd Wednesday of March next year?* ## Package Features ## - A generic, extendable algebra for date operations with a rich set of primitives. - A composable design to allow complex combinations of relative date operations. - An extendable parsing library to provide a language to describe relative dates. - An interface for integrating holiday calendar systems. ## Installation RDates can be installed using the Julia package manager. From the Julia REPL, type `]` to enter the Pkg REPL mode and run ```julia-repl pkg> add RDates ``` At this point you can now start using RDates in your current Julia session using the following command ```julia-repl julia> using RDates ``` [docs-latest-img]: https://img.shields.io/badge/docs-latest-blue.svg [docs-latest-url]: https://infinitechai.github.io/RDates.jl/latest [docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [docs-stable-url]: https://infinitechai.github.io/RDates.jl/stable [travis-img]: https://travis-ci.com/InfiniteChai/RDates.jl.svg?branch=master [travis-url]: https://travis-ci.com/InfiniteChai/RDates.jl [codecov-img]: https://codecov.io/gh/InfiniteChai/RDates.jl/branch/master/graph/badge.svg [codecov-url]: https://codecov.io/gh/InfiniteChai/RDates.jl [issues-url]: https://github.com/JuliaDocs/Documenter.jl/issues
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
docs
2772
# Business Days Up to now we have dealt with date operations that do not take into consideration one of the key features, holidays. Whether its working around weekends or the UK's bank holidays, operations involving holidays (or equivalently *business days*) is essential. As such the RDate package provides the construct to allow you to work with holiday calendars, without tying you to a specific implementation. !!! note `RDates` will never provide an explicit implementation of the calendar system, but do check out [HolidayCalendars](https://github.com/InfiniteChai/HolidayCalendars.jl) which will get released soon which builds rule-based calendar systems. Before we walk through how this is integrated into the RDate language, we'll look at how calendars are modelled. ## Calendars A calendar defines whether a given day is a holiday. To implement a calendar you need to inherit from `RDates.Calendar` and define the following methods. ```@docs RDates.is_holiday RDates.holidays ``` Calendars also come with a number of helpful wrapper methods ```@docs RDates.holidaycount RDates.bizdaycount ``` RDate provides some primitive calendar implementations to get started with ```@docs RDates.NullCalendar RDates.WeekendCalendar RDates.JointCalendar RDates.CachedCalendar ``` ## Calendar Manager To access calendars within the relative date library, we use a calendar manager. It provides the interface to access calendars based on their name, a string identifier. A calendar manager must inherit from `RDates.CalendarManager` and implement the following ```@docs calendar(::RDates.CalendarManager, ::Vector) ``` RDates provides some primitive calendar manager implementations to get started with ```@docs RDates.NullCalendarManager RDates.SimpleCalendarManager ``` When you just add a `Date` and an `RDate` then we'll use the `NullCalendarManager()` by default. To pass a calendar manager to the rdate when it's been applied, use the `apply` function. ```@docs RDates.apply ``` ## Calendar Adjustments Now that we have a way for checking whether a given day is a holiday and can use your calendar manager, let's introduce calendar adjustments. These allow us to apply a holiday calendar adjustment, after a base rdate has been applied. To support this we need to introduce the concept of *Holiday Rounding*. ### Holiday Rounding Convention The holiday rounding convention provides the details on what to do if we fall on a holiday. ```@docs RDates.HolidayRoundingNBD RDates.HolidayRoundingPBD RDates.HolidayRoundingNBDSM RDates.HolidayRoundingPBDSM RDates.HolidayRoundingNR RDates.HolidayRoundingNearest ``` Now we have everything we need to define calendar adjustments and business days ```@docs RDates.CalendarAdj RDates.BizDays ```
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
docs
2811
# Combinations One of the key features of RDates is to allow us to combine primitive operations to provide a generalised method to describe date adjustments. ## Negation All our primitive operations provide a negative operation, which is achieved by applying the `-` operator to the `RDate`. ```julia-repl julia> Date(2019,1,1) - RDates.Day(1) 2018-12-31 julia> -RDates.Week(3) + Date(2019,1,1) 2018-12-11 ``` !!! note While all our RDates support negation, they may not have an effect and will just return itself. ```julia-repl julia> -rd"1st WED" == rd"1st WED" true ``` ## Addition All RDates can be combined together via addition. The components are applied from left to right. ```julia-repl julia> rd"1d + 1y" + Date(2019,1,1) 2020-01-02 julia> rd"1MAR + 3rd WED" + Date(2019,1,1) 2019-03-20 ``` !!! note Where possible, addition operations may be optimised to reduce down to simpler state. This will always be done in a way in which we maintain the expected behaviour. ```julia-repl julia> rd"1d + 1d" == rd"2d" true ``` !!! warning The alegbra of month addition is not always straight forward. Make sure you're clear on exactly what you want to achieve. ```julia-repl julia> rd"2m" + Date(2019,1,31) 2019-03-31 julia> rd"1m + 1m" + Date(2019,1,31) 2019-03-28 ``` ## Multiplication and Repeats Every RDate supports multiplication and this will usually multiply it's underlying count. For most primitives this is completely understandable due to the inherent link between addition and multiplication. ```julia-repl julia> RDates.Day(2) * 5 10d julia> RDates.Week(2) * -5 -10w ``` For RDates which do not have a natural count then the multiplication will just return itself ```julia-repl julia> 10 * RDates.NthWeekdays(:MON, 1) 1st MON ``` However when we come to handling months (and by extension years, though in rarer cases) we need to be more careful. We set a convention that multiplication is equivalent to multiplication of the internal count and so we won't get the same result as adding it n times. ```julia-repl julia> 2 * RDates.Month(1) 2m[LDOM;PDOM] julia> rd"2 * 1m" 2m[LDOM;PDOM] julia> 2 * RDates.Month(1) + Date(2019,1,31) 2019-03-31 julia> RDates.Month(1) + RDates.Month(1) + Date(2019,1,31) 2019-03-28 ``` It may be though that you want that handling and so we introduce the `Repeat` operator to support that. This operator will repeat the application of the internalised rdate, rather than passing the multiplier through. ```julia-repl julia> 2 * RDates.Repeat(RDates.Month(1)) 2*Repeat(1m[PDOM;LDOM]) julia> 2 * RDates.Repeat(RDates.Month(1)) + Date(2019,1,31) 2019-03-28 julia> rd"2*Repeat(1m)" + Date(2019,1,31) 2019-03-28 ``` ## Other Operators ```@docs RDates.Next RDates.Previous ```
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
docs
1518
# Introduction *A relative date library for Julia* This is a project that builds around the [Dates](https://docs.julialang.org/en/v1/stdlib/Dates/) module to allow complex date arithmetic. The aim is to provide a standard toolset to allow you to answer questions such as *when is the next Easter* or *what are the next 4 [IMM](https://en.wikipedia.org/wiki/IMM_dates) dates from today?* ## Package Features ## - A generic, extendable algebra for date operations with a rich set of primitives. - A composable design to allow complex combinations of relative date operations. - An extendable parsing library to provide a language to describe relative dates. - An interface for integrating holiday calendar systems. ## Installation RDates can be installed using the Julia package manager. From the Julia REPL, type `]` to enter the Pkg REPL mode and run ```julia-repl pkg> add RDates ``` At this point you can now start using RDates in your current Julia session using the following command ```julia-repl julia> using RDates ``` ## Answering Those Questions So while the documentation will provide the details, let's see a quick start on how it works - When is the next Easter? ```julia-repl julia> rd"Next(0E,1E)" + Date(2021,7,12) 2022-04-17 ``` - What are the next 4 [IMM](https://en.wikipedia.org/wiki/IMM_dates) dates? ```julia-repl julia> d = Date(2021,7,12) julia> collect(Iterators.take(range(d, rd"1MAR+3m+3rd WED"), 4)) 4-element Vector{Date}: 2021-09-15 2021-12-15 2022-03-16 2022-06-15 ```
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
docs
1208
# Months and Years Adding months to a date is a surprisingly complex operation and so we've created a dedicated page to go through the details. For example - What should happen if I add one month to the 31st January? - Should adding one month to the 30th April maintain the end of month? Years are less complex, but still suffer from the same edge case due to leap years and the 29th February. As such, we incorporate the same conventions. To give us the level of flexibility, we need to introduce two conventions to support us. ## Month Increment Convention When we add a month to a date, we need to determine what we should do with the day. Most of the time we'll maintain the same day, but sometimes we may want to maintain the last day of the month, which is a common feature in financial contracts. ```@docs RDates.MonthIncrementPDOM RDates.MonthIncrementPDOMEOM ``` ## Invalid Day Convention The next convention we need is what to do if our increment leaves us on an invalid day of the month. ```@docs RDates.InvalidDayLDOM RDates.InvalidDayFDONM RDates.InvalidDayNDONM ``` We now have all the conventions we need to handle month and year adjustments ```@docs RDates.Month RDates.Year ```
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
docs
607
# Primitives RDates is designed to allow complex date operations to be completed using basic primitive types. Each of these primitive types and operations are explained in more detail in subsequent sections. We now go through each of the primitive types, from which we can combine together using compounding operations. Also take note of the examples and the associated short-hand that we can use to define them with the `rd""` macro. ```@docs RDates.Day RDates.Week RDates.FDOM RDates.LDOM RDates.Easter RDates.DayMonth RDates.Date RDates.NthWeekdays RDates.NthLastWeekdays RDates.Weekdays ```
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.5.1
62bf589fb964a59f52cca21acb9562a5fc587fdb
docs
41
# Ranges ```@docs RDates.RDateRange ```
RDates
https://github.com/InfiniteChai/RDates.jl.git
[ "MIT" ]
0.2.0
fe65c9d5b0c46c99cffd64c30ad332440c8b8c42
code
11965
module SimplePolynomialRing using SparseArrays import Primes: isprime, factor import Base: (+), (-), (*), (^), (÷), (%), (/) include("tools.jl") """ Pℤ{P, X} Polynomial of ℤₚ[X]. # Examples ```jldoctest julia> a = Pℤ{3, :x}(:(1 + x + 2x^2)) 1 + x + 2x^2 julia> b = Pℤ{3, :x}("1 + x + 2x^2") 1 + x + 2x^2 julia> c = Pℤ{3}(2) 2 julia> d = Pℤ{3}(5) 2 julia> e = Pℤ₂([1,0,0,1,1,0,1]) 1 + x^3 + x^4 + x^6 ``` """ struct Pℤ{P,X} coeffs::SparseVector{Int,Int} function Pℤ{P,X}(coeffs::SparseVector{Int,Int}) where {P,X} (typeof(P) != Int || P < 2) && throw("`P` must be natural number") typeof(X) != Symbol && throw("`X` must be Symbol") for d in coeffs.nzind if coeffs[d] < 0 while coeffs[d] < 0 coeffs[d] += P end else coeffs[d] %= P end end dropzeros!(coeffs) # coeffs = sparsevec(coeffs.nzind, coeffs.nzval) # coeffs = length(coeffs.nzind)==0 ? sparsevec([0]) : coeffs new{P,X}(coeffs) end function Pℤ{P,X}(coeffs::Vector{Int}) where {P,X} coeffs = sparsevec(coeffs) Pℤ{P,X}(coeffs) end function Pℤ{P,X}(poly::Int) where {P,X} Pℤ{P,X}(sparsevec([(poly + P) % P])) end function Pℤ{P,X}(poly::Symbol) where {P,X} Pℤ{P,poly}(sparsevec([0, 1])) end function Pℤ{P,X}(poly::Expr) where {P,X} (typeof(P) != Int || P < 2) && throw("`P` must be natural number") typeof(X) != Symbol && throw("`X` must be Symbol") coeffs = Dict{Int,Int}() if length(poly.args) == 0 coeffs[1] = 0 elseif poly.args[1] == :+ for arg in poly.args[2:end] if typeof(arg) == Int coeffs[1] = arg elseif typeof(arg) == Symbol coeffs[2] = 1 elseif typeof(arg) == Expr inner = arg.args[2:end] if typeof.(inner) == [Symbol, Int] coeffs[inner[2]+1] = 1 elseif typeof.(inner) == [Int, Expr] coeffs[inner[2].args[3]+1] = inner[1] elseif typeof.(inner) == [Int, Symbol] coeffs[2] = inner[1] end end end elseif poly.args[1] == :^ coeffs[poly.args[end]+1] = 1 elseif poly.args[1] == :* if typeof(poly.args[end]) == Expr coeffs[poly.args[end].args[3]+1] = poly.args[2] elseif typeof(poly.args[end]) == Symbol coeffs[2] = poly.args[2] end end Pℤ{P,X}(coeffs |> sparsevec) end function Pℤ{P,X}(poly::String) where {P,X} Pℤ{P,X}(poly |> Meta.parse) end Pℤ{P}(poly::Union{Expr,String,Int,Symbol,Vector{Int}}) where {P} = Pℤ{P,:x}(poly) end Base.one(::Pℤ{P,X}) where {P,X} = Pℤ{P,X}(1) Base.zero(::Pℤ{P,X}) where {P,X} = Pℤ{P,X}(0) Base.one(::Type{Pℤ{P,X}}) where {P,X} = Pℤ{P,X}(1) Base.zero(::Type{Pℤ{P,X}}) where {P,X} = Pℤ{P,X}(0) function Base.getproperty(p::Pℤ{P,X}, name::Symbol) where {P,X} if name == :P return P elseif name == :X return X else return getfield(p, name) end end Base.copy(p::Pℤ{P,X}) where {P,X} = Pℤ{P,X}(p.coeffs) Base.hash(p::Pℤ{P,X}, h::UInt) where {P,X} = hash((p.coeffs, p.P, p.X), h) """ degree(p::Pℤ) Return the degree of the polynomial `p`. """ degree(p::Pℤ{P,X}) where {P,X} = length(p.coeffs.nzind) == 0 ? 0 : (p.coeffs.nzind |> maximum) - 1 import Base: (==), (!=) Base.isequal(left::Pℤ{P,X}, right::Pℤ{P,X}) where {P,X} = left.coeffs.nzind == right.coeffs.nzind && left.coeffs.nzval == right.coeffs.nzval (==)(left::Pℤ{P,X}, right::Pℤ{P,X}) where {P,X} = isequal(left, right) (==)(v::Vector{Pℤ{P,X}}, p::Pℤ{P,X}) where {P,X} = broadcast(==, v, p) (==)(p::Pℤ{P,X}, v::Vector{Pℤ{P,X}}) where {P,X} = broadcast(==, p, v) Base.Vector(p::Pℤ{P,X}) where {P,X} = length(p.coeffs.nzind) == 0 ? [0] : let v = zeros(Int, maximum(p.coeffs.nzind[p.coeffs.nzval.!=0])) v[p.coeffs.nzind[p.coeffs.nzval.!=0]] .= p.coeffs.nzval[p.coeffs.nzval.!=0] return v end function Base.unique(v::Vector{Pℤ{P,X}}) where {P,X} uv = [] while length(v) > 0 push!(uv, v[1]) v = v[.!(v == v[1])] end sort!(uv, by=x -> degree(x)) end Base.Symbol(p::Pℤ) = Symbol(string(p)) Base.size(::Pℤ) = () Base.getindex(p::Pℤ, i) = p Base.Broadcast.broadcastable(p::Pℤ) = Ref(p) function Base.show(io::IO, p::Pℤ{P,X}) where {P,X} degrees = p.coeffs.nzind if length(degrees) == 0 return print(io, "0") end p_str = "" for i in 1:length(degrees)-1 if degrees[i] == 1 # x ^ 0 p_str *= "$(p.coeffs[1])" elseif degrees[i] == 2 # x ^ 1 if p.coeffs[2] != 1 p_str *= "$(p.coeffs[2])" end p_str *= String(X) else if p.coeffs[degrees[i]] != 1 p_str *= "$(p.coeffs[degrees[i]])" end p_str *= String(X) * "^$(degrees[i]-1)" end p_str *= " + " end if degrees[end] == 1 p_str *= "$(p.coeffs[1])" elseif degrees[end] == 2 # x ^ 1 if p.coeffs[2] != 1 p_str *= "$(p.coeffs[2])" end p_str *= String(X) else if p.coeffs[degrees[end]] != 1 p_str *= "$(p.coeffs[degrees[end]])" end p_str *= String(X) * "^$(degrees[end]-1)" end print(io, p_str) end function +(left::Pℤ{P,X}, right::Pℤ{P,X})::Pℤ{P,X} where {P,X} left_length = left.coeffs |> length right_length = right.coeffs |> length ans_length = max(left_length, right_length) Pℤ{P,X}( [left.coeffs; spzeros(Int, ans_length - left_length)] + [right.coeffs; spzeros(Int, ans_length - right_length)] ) end function -(left::Pℤ{P,X}, right::Pℤ{P,X})::Pℤ{P,X} where {P,X} left_length = left.coeffs |> length right_length = right.coeffs |> length ans_length = max(left_length, right_length) Pℤ{P,X}( [left.coeffs; spzeros(Int, ans_length - left_length)] - [right.coeffs; spzeros(Int, ans_length - right_length)] ) end (*)(left::Pℤ{P,X}, right::Int) where {P,X} = degree(left) == 0 ? left : Pℤ{P,X}(left.coeffs .* right) (*)(left::Int, right::Pℤ{P,X}) where {P,X} = right * left function *(left::Pℤ{P,X}, right::Pℤ{P,X}) where {P,X} left_degrees = left.coeffs.nzind right_degrees = right.coeffs.nzind coeffs = spzeros(Int, degree(left) + degree(right) + 1) for ld in left_degrees for rd in right_degrees coeffs[ld+rd-1] += left.coeffs[ld] * right.coeffs[rd] end end Pℤ{P,X}(coeffs) end (^)(left::Pℤ{P,X}, right::Int) where {P,X} = Base.power_by_squaring(left, right) function ÷(left::Pℤ{P,X}, right::Pℤ{P,X}) where {P,X} div = Pℤ{P,X}(:()) rc = right.coeffs[degree(right)+1] while degree(left) >= degree(right) && left != Pℤ{P,X}(:()) c = 1 while c * rc % P != left.coeffs[degree(left)+1] c += 1 end div += Pℤ{P,X}("$(c)$(X)^$(degree(left)-degree(right))") left -= right * Pℤ{P,X}("$(c)$(X)^$(degree(left)-degree(right))") end (div, left) end function /(left::Pℤ{P,X}, right::Pℤ{P,X}) where {P,X} return ÷(left, right)[1] end function %(left::Pℤ{P,X}, right::Pℤ{P,X}) where {P,X} return ÷(left, right)[2] end +(v::Vector{Pℤ{P,X}}, p::Pℤ{P,X}) where {P,X} = broadcast(+, v, p) +(p::Pℤ{P,X}, v::Vector{Pℤ{P,X}}) where {P,X} = broadcast(+, p, v) -(v::Vector{Pℤ{P,X}}, p::Pℤ{P,X}) where {P,X} = broadcast(-, v, p) -(p::Pℤ{P,X}, v::Vector{Pℤ{P,X}}) where {P,X} = broadcast(-, p, v) *(v::Vector{Pℤ{P,X}}, p::Pℤ{P,X}) where {P,X} = broadcast(*, v, p) *(p::Pℤ{P,X}, v::Vector{Pℤ{P,X}}) where {P,X} = broadcast(*, p, v) *(v::Vector{Pℤ{P,X}}, n::Int) where {P,X} = broadcast(*, v, n) ^(v::Vector{Pℤ{P,X}}, n::Int) where {P,X} = broadcast(^, v, n) %(v::Vector{Pℤ{P,X}}, p::Pℤ{P,X}) where {P,X} = broadcast(%, v, p) %(p::Pℤ{P,X}, v::Vector{Pℤ{P,X}}) where {P,X} = broadcast(%, p, v) /(v::Vector{Pℤ{P,X}}, p::Pℤ{P,X}) where {P,X} = broadcast(/, v, p) /(p::Pℤ{P,X}, v::Vector{Pℤ{P,X}}) where {P,X} = broadcast(/, p, v) """ gcdx(a::Pℤ{P,X}, b::Pℤ{P,X}) Computes the greatest common divisor of `a` and `b` and their Bézout coefficients, i.e. the polynomials `u` and `v` that satisfy `ua+vb = d = gcd(a, b)`. `gcdx(a, b) returns `(d, u, v)`. """ function Base.gcdx(a::Pℤ{P,X}, b::Pℤ{P,X}) where {P,X} if a == Pℤ{P,X}(0) return b, Pℤ{P,X}(0), Pℤ{P,X}(1) end d, x₁, y₁ = gcdx(b % a, a) return d, y₁ - (b / a) * x₁, x₁ end # Factorization struct PℤGenerator{P,X} a::UnitRange t::Int function PℤGenerator{P,X}(n::Int) where {P,X} (typeof(P) != Int || P < 2) && throw("`P` must be natural number") typeof(X) != Symbol && throw("`X` must be Symbol") n < 0 && throw("`n` (degree of polynomial) must be non negative number") new{P,X}(0:(P-1), n + 1) end end Base.eltype(::Type{PℤGenerator{P,X}}) where {P,X} = Pℤ{P,X} Base.length(p::PℤGenerator) = p.t == 1 ? length(p.a) : length(p.a)^(p.t) - length(p.a)^(p.t - 1) function Base.iterate(p::PℤGenerator{P,X}, s=[ones(Int, p.t - 1); [1, 2][Int(p.t != 1)+1]]) where {P,X} (!isempty(s) && s[end] > length(p.a) || p.t < 0) && return perm = p.a[s] s[1] += 1 i = 1 while i < length(s) && s[i] > length(p.a) s[i] = 1 s[i+1] += 1 i += 1 end (Pℤ{P,X}(perm), s) end """ generate(n::Int, p::Int; x::Symbol=:x) Generates all the polynomials over ℤₚ up to degree `n`. """ function generate(n::Int, p::Int; x::Symbol=:x) n < 0 && throw("`n` (degree of polynomial) must be non negative number") p < 1 && throw("`p` must be natural number") n == 0 ? Pℤ{p,x}.(0:(p-1)) : Pℤ{p,x}.(Permutations(0:(p-1), n + 1)) end """ primes(n::Int, p::Int; x::Symbol=:x) Returns a collection of the prime polynomials over ℤₚ up to degree `n`. """ function primes(n::Int, p::Int; x::Symbol=:x) !isprime(p) && throw("`p` must be prime number") ZERO = Pℤ{p,x}(0) primes_list = generate(1, p, x=x) |> collect for i in 2:n gen_list = generate(i, p, x=x) |> collect append!(primes_list, gen_list[sum([ gen_list % primes_list[j] == ZERO for j in 1:round(Int, length(primes_list) / 2) ]).==0]) end primes_list end """ factor(p::Pℤ) Compute the prime factorization of a polynomial `p`. """ function factor(p::Pℤ{P,X}) where {P,X} (p == Pℤ{P,X}(1) || p == Pℤ{P,X}(0)) && return Dict(p => 1) !isprime(P) && throw("`P` must be prime number") ZERO = Pℤ{P,X}(0) rainbow = primes(round(Int, degree(p) / 2), P; x=X) factorization = Dict{Pℤ{P,X},Int}() for r in rainbow if p % r == ZERO factorization[r] = 0 while p % r == ZERO factorization[r] += 1 p = p / r end end end if p != Pℤ{P,X}(1) factorization[p] = 1 end factorization end """ isprime(p::Pℤ) -> Bool Returns `true` if polynomial `p` is prime, and `false` otherwise. """ isprime(p::Pℤ) = length(factor(p)) == 1 """ irreducible(n::Int, p::Int; x::Symbol=:x) Generates irreducible polynomials over ℤₚ of degree `n`. """ function irreducible(n::Int, p::Int; x::Symbol=:x) n < 1 && throw("`n` (degree of polynomial) must be natural number") p < 1 && throw("`p` must be natural number") !isprime(p) && throw("`p` must be prime number") filter( p -> degree(p) == n, primes(n, p; x=x) ) end """ Pℤ₂ Alias for Pℤ{2, :x} """ Pℤ₂ = Pℤ{2} export Pℤ, Pℤ₂, degree, generate, irreducible, primes, factor, isprime end # module PolynomialRing
SimplePolynomialRing
https://github.com/Scurrra/SimplePolynomialRing.jl.git
[ "MIT" ]
0.2.0
fe65c9d5b0c46c99cffd64c30ad332440c8b8c42
code
554
# Combinatorics """ Permutations{T}(a, t) Returns permutations except that has first element of `a` at the end """ struct Permutations{T} a::T t::Int end Base.eltype(::Type{Permutations{T}}) where {T} = Vector{eltype(T)} Base.length(p::Permutations) = length(p.a)^(p.t) - length(p.a)^(p.t-1) function Base.iterate(p::Permutations, s=[ones(Int, p.t-1); 2]) (!isempty(s) && s[end] > length(p.a) || p.t < 0) && return perm = p.a[s] s[1] += 1 i = 1 while i < length(s) && s[i] > length(p.a) s[i] = 1 s[i+1] += 1 i += 1 end (perm, s) end
SimplePolynomialRing
https://github.com/Scurrra/SimplePolynomialRing.jl.git
[ "MIT" ]
0.2.0
fe65c9d5b0c46c99cffd64c30ad332440c8b8c42
docs
3045
# Simple Polynomial Ring [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://juliahub.com/docs/SimplePolynomialRing/uWGaY) Polynomial ring realization. ## Installation ```julia (v1.8) pkg> add SimplePolynomialRing ``` This package supports Julia 1.8 and later. ## Usage ```julia julia> using SimplePolynomialRing ``` ## Construction Polynomial could be constructed from Julia Expr or String. ```julia julia> a = Pℤ{3, :x}(:(1 + x + 2x^2)) 1 + x + 2x^2 julia> b = Pℤ{3, :x}("1 + x + 2x^2") 1 + x + 2x^2 ``` As polynom's coefficients are modulo `P`, then the following polynomials are the same. ```julia julia> c = Pℤ{3}(2) 2 julia> d = Pℤ{3}(5) 2 julia> c == d true ``` ```julia julia> e = Pℤ₂([1,0,0,1,1,0,1]) # alias for `Pℤ{2, :x}` 1 + x^3 + x^4 + x^6 ``` ## Arithmetic Operaions with two polynomials. ```julia julia> p = Pℤ{3, :x}(:(1 + 2x + x^3 + 2x^5)) 1 + 2x + x^3 + 2x^5 julia> q = Pℤ{3, :x}(:(1 + x + 2x^2)) 1 + x + 2x^2 julia> p + q 2 + 2x^2 + x^3 + 2x^5 julia> p - q x + x^2 + x^3 + 2x^5 julia> p * q 1 + x^2 + 2x^3 + x^4 + x^5 + 2x^6 + x^7 julia> p ÷ q (2 + x + x^2 + x^3, 2 + 2x) julia> p / q 2 + x + x^2 + x^3 julia> p % q 2 + 2x ``` Operations with a polynomial and a number. ```julia julia> p = Pℤ{3, :x}(:(1 + 2x + x^3 + 2x^5)) 1 + 2x + x^3 + 2x^5 julia> p * 5 2 + x + 2x^3 + x^5 julia> p ^ 5 1 + x + x^2 + x^3 + x^6 + 2x^7 + x^9 + 2x^10 + 2x^12 + x^14 + 2x^15 + 2x^16 + x^18 + 2x^20 + 2x^23 + 2x^25 ``` ## Some useful functions on polynomials Extended GCD. ```julia julia> p = Pℤ{3, :x}(:(1 + 2x + x^3 + 2x^5)) 1 + 2x + x^3 + 2x^5 julia> q = Pℤ{3, :x}(:(1 + x + 2x^2)) 1 + x + 2x^2 julia> gcdx(p, q) (2, 2 + 2x, 2x^2 + 2x^3 + x^4) ``` Factorization and primality test. ```julia julia> p = Pℤ{3, :x}(:(1 + 2x + x^3 + 2x^5)) 1 + 2x + x^3 + 2x^5 julia> isprime(p) false julia> factor(p) Dict{Pℤ{3, :x}, Int64} with 2 entries: 2 + x => 2 1 + x + x^2 + 2x^3 => 1 ``` Polynomial generation: all possible and prime. ```julia julia> generate(3, 3) 54-element Vector{Pℤ{3, :x}}: x^3 1 + x^3 2 + x^3 x + x^3 1 + x + x^3 2 + x + x^3 2x + x^3 1 + 2x + x^3 2 + 2x + x^3 x^2 + x^3 1 + x^2 + x^3 ⋮ 2 + 2x + x^2 + 2x^3 2x^2 + 2x^3 1 + 2x^2 + 2x^3 2 + 2x^2 + 2x^3 x + 2x^2 + 2x^3 1 + x + 2x^2 + 2x^3 2 + x + 2x^2 + 2x^3 2x + 2x^2 + 2x^3 1 + 2x + 2x^2 + 2x^3 2 + 2x + 2x^2 + 2x^3 julia> primes(3, 3) 28-element Vector{Pℤ{3, :x}}: x 1 + x 2 + x 2x 1 + 2x 2 + 2x 1 + x^2 2 + x + x^2 2 + 2x + x^2 2 + 2x^2 1 + x + 2x^2 ⋮ 1 + x + 2x^2 + x^3 2 + 2x + 2x^2 + x^3 1 + x + 2x^3 2 + x + 2x^3 2 + x^2 + 2x^3 1 + x + x^2 + 2x^3 2 + 2x + x^2 + 2x^3 1 + 2x^2 + 2x^3 2 + x + 2x^2 + 2x^3 1 + 2x + 2x^2 + 2x^3 julia> irreducible(3, 3) 16-element Vector{Pℤ{3, :x}}: 1 + 2x + x^3 2 + 2x + x^3 2 + x^2 + x^3 2 + x + x^2 + x^3 1 + 2x + x^2 + x^3 1 + 2x^2 + x^3 1 + x + 2x^2 + x^3 2 + 2x + 2x^2 + x^3 1 + x + 2x^3 2 + x + 2x^3 2 + x^2 + 2x^3 1 + x + x^2 + 2x^3 2 + 2x + x^2 + 2x^3 1 + 2x^2 + 2x^3 2 + x + 2x^2 + 2x^3 1 + 2x + 2x^2 + 2x^3 ```
SimplePolynomialRing
https://github.com/Scurrra/SimplePolynomialRing.jl.git
[ "MIT" ]
0.1.1
067aabe9bb023e12ccac4e52574891de7bfde242
code
590
using Documenter, Literate, Recombinase @info "makedocs" for filename in ["tutorial.jl", "digging_deeper.jl"] Literate.markdown( joinpath(@__DIR__, "src", filename), joinpath(@__DIR__, "src", "generated") ) end makedocs( format = Documenter.HTML(prettyurls = get(ENV, "CI", nothing) == "true"), sitename = "Recombinase.jl", pages = [ "index.md", "generated/tutorial.md", "interactive_interface.md", "generated/digging_deeper.md", ] ) @info "deploydocs" deploydocs( repo = "github.com/piever/Recombinase.jl.git", )
Recombinase
https://github.com/piever/Recombinase.jl.git
[ "MIT" ]
0.1.1
067aabe9bb023e12ccac4e52574891de7bfde242
code
2779
# # Digging deeper # The core functioning of Recombinase is based on a set of preimplemented analysis # functions and on the [OnlineStats](https://github.com/joshday/OnlineStats.jl) package # to compute summary statistics efficiently. # ## Analysis functions # Under the hood, the actual computations are implemented in some built-in `Analysis` # objects. Each `Analysis` takes some vectors (a varying number, one for `density` # and two for `prediction` for example), an optional `axis` argument to specify # the `x` axis argument and returns an iterator of `(x, y)` values, representing # the `y` value corresponding to each point of the `x` axis. using Recombinase: density, hazard, cumulative, prediction x = randn(100) res = density(x) collect(Iterators.take(res, 5)) # let's see the first few elements # We can collect the iterator in a table container to see # that we recover the `x` and `y` axis, ready for plotting using JuliaDB s = table(res) # `prediction` is similar but requrires two arguments: xs = 10 .* rand(100) ys = sin.(xs) .+ 0.5 .* rand(100) res = prediction(xs, ys) table(res) # The function `discrete` can turn any analysis into its discrete counter-part # (analyses are continuous for numerical axes and discrete otherwise by default). # It also automatically comutes the error of the prediction (s.e.m). using Recombinase: discrete x = rand(1:3, 1000) y = rand(1000) .+ 0.1 .* x res = discrete(prediction)(x, y) table(res) # ## OnlineStats integration # Summary statistics are computed using the excellent [OnlineStats](https://github.com/joshday/OnlineStats.jl) # package. First the data is split by the splitting variable (in this case `School`), # then the analysis is computed on each split chunk on the selected column(s). # Finally the results from different schools are put together in summary statistics # (default is `mean` and `s.e.m`): using Recombinase: datafolder, compute_summary data = loadtable(joinpath(datafolder, "school.csv")) compute_summary(density, data, :School; select = :MAch) # Any summary statistic can be used. If we only want the mean we can use using OnlineStats compute_summary(density, data, :School; select = :MAch, stats = Mean()) # We can also pass a `Tuple` of statistics to compute many at the same time: using OnlineStats compute_summary(density, data, :School; select = :MAch, stats = Series(Mean(), Variance())) # One can optionally pass pairs of `OnlineStat` and function to apply the function to the # `OnlineStat` before plotting (default is just taking the `value`). # To compute a different error bar (for example just the standard deviation) you can simply do: stats = (Mean(), Variance() => t -> sqrt(value(t))) compute_summary(density, data, :School; select = :MAch, stats = stats)
Recombinase
https://github.com/piever/Recombinase.jl.git
[ "MIT" ]
0.1.1
067aabe9bb023e12ccac4e52574891de7bfde242
code
4849
# # Tutorial # # First, let us load the relevant packages and an example dataset: # using Statistics, StatsBase, StatsPlots, JuliaDB using OnlineStats: Mean, Variance using Recombinase using Recombinase: cumulative, density, hazard, prediction data = loadtable(joinpath(Recombinase.datafolder, "school.csv")) # # ### Simple scatter plots # # Then we can compute a simple scatter plot of one variable against an other. This is done in two steps: first the positional and named arguments of the plot call are computed, then they are passed to a plotting function: # args, kwargs = series2D( data, Group(:Sx), select = (:MAch, :SSS), ) scatter(args...; kwargs...) # This creates an overcrowded plot. We could instead compute the average value of our columns of interest for each school and then plot just one point per school (with error bars representing variability within the school): # args, kwargs = series2D( data, Group(:Sx), error = :School, select = (:MAch, :SSS), ) scatter(args...; kwargs...) # By default, this computes the mean and standard error, we can pass `stats = Mean()` to only compute the mean. # # ### Splitting by many variables # # We can use different attributes to split the data as follows: # args, kwargs = series2D( data, Group(color = :Sx, markershape = :Sector), error = :School, select = (:MAch, :SSS), stats = Mean(), ) scatter(args...; kwargs...) # ### Styling the plot # # There are two ways in which we can style the plot: first, we can pass a custom set of colors instead of the default palette: # args, kwargs = series2D( data, Group(:Sx), error = :School, select = (:MAch, :SSS), stats = Mean(), color = [:red, :blue] ) scatter(args...; kwargs...) # Second, we can style plat attributes as we would normally do: # args, kwargs = series2D( data, Group(:Sx), error = :School, select = (:MAch, :SSS), stats = Mean(), ) scatter(args...; legend = :topleft, markersize = 10, kwargs...) # ### Computing summaries # # It is also possible to get average value and variability of a given analysis (density, cumulative, hazard rate and local regression are supported so far, but one can also add their own function) across groups. # # For example (here we use `ribbon` to signal we want a shaded ribbon to denote the error estimate): # args, kwargs = series2D( cumulative, data, Group(:Sx), error = :School, select = :MAch, ribbon = true ) plot(args...; kwargs..., legend = :topleft) # Note that extra keyword arguments can be passed to the analysis: # args, kwargs = series2D( density(bandwidth = 1), data, Group(color=:Sx, linestyle=:Sector), error = :School, select = :MAch, ribbon = true ) plot(args...; kwargs..., legend = :bottom) # If we do not specify `error`, it defaults to the "analyses specific error". For discrete prediction it is the standard error of the mean across observations. # args, kwargs = series2D( prediction, data, Group(color = :Minrty), select = (:Sx, :MAch), ) groupedbar(args...; kwargs...) # ### Axis style selection # # Analyses try to infer the axis type (continuous if the variable is numeric, categorical otherwise). If that is not appropriate for your data you can use `discrete(prediction)` or `continuous(prediction)` (works for `hazard`, `density` and `cumulative` as well). # A special type of axis type is vectorial: the `x` and `y` axes can be contain `AbstractArray` elements, in which case # we take views of elements of `y` corresponding to elements of `x`. This can be useful to compute averages of time varying signals. using Recombinase: offsetrange signal = sin.(range(0, 10π, length = 1000)) .+ 0.1 .* rand.() events = range(50, 950, step = 100) z = repeat([true, false], outer = 5) x = [offsetrange(signal, ev) for ev in events] y = fill(signal, length(x)) t = table(x, y, z, names = [:offsets, :signals, :peak]) args, kwargs = series2D( prediction(axis = -60:60), t, Group(:peak), select = (:offsets, :signals), ribbon = true, ) plot(args...; kwargs...) # ### Post processing # # Finally, for some analyses it can be useful to postprocess the result. For example, in the case # of the "signal plot" above, we may wish to rescale the `x` axis. This is done by passing a named # tuple of functions as a `postprocess` keyword argument, which will be applied element-wise to the relative column of the output. For example, if our signal was sampled at `60 Hz`, we may wish to divide the `:offsets` column by `60` to show the result in seconds: args, kwargs = series2D( prediction(axis = -60:60), t, Group(:peak), select = (:offsets, :signals), ribbon = true, postprocess = (; offsets = t -> t/60), ) plot(args...; kwargs...)
Recombinase
https://github.com/piever/Recombinase.jl.git
[ "MIT" ]
0.1.1
067aabe9bb023e12ccac4e52574891de7bfde242
code
1017
module Recombinase using IterTools using Statistics using StatsBase: countmap, ecdf, sem using Loess: loess, predict using KernelDensity: pdf, kde, InterpKDE using StructArrays: StructVector, StructArray, finduniquesorted, uniquesorted, fieldarrays, GroupPerm, StructArrays using IndexedTables: collect_columns, collect_columns_flattened, rows, columns, IndexedTable, colnames, pushcol, table, dropmissing import IndexedTables: sortpermby, lowerselection using ColorTypes: RGB import Widgets using Observables: AbstractObservable, Observable, @map, @map! using Widgets: Widget, dropdown, toggle, button using OrderedCollections: OrderedDict using OnlineStatsBase: Mean, Variance, FTSeries, fit!, OnlineStat, nobs, value import Tables, TableOperations export Group, compute_summary, series2D export discrete datafolder = joinpath(@__DIR__, "..", "data") include("analysisfunctions.jl") include("timeseries.jl") include("compute_summary.jl") include("styles.jl") include("plots.jl") include("gui.jl") end # module
Recombinase
https://github.com/piever/Recombinase.jl.git
[ "MIT" ]
0.1.1
067aabe9bb023e12ccac4e52574891de7bfde242
code
5154
struct Analysis{S, F, NT<:NamedTuple} f::F kwargs::NT Analysis{S}(f::F, kwargs::NT) where {S, F, NT<:NamedTuple} = new{S, F, NT}(f, kwargs) end Analysis{S}(f; kwargs...) where {S} = Analysis{S}(f, values(kwargs)) Analysis{S}(a::Analysis; kwargs...) where {S} = Analysis{S}(a.f, merge(a.kwargs, values(kwargs))) Analysis(args...; kwargs...) = Analysis{:automatic}(args...; kwargs...) getfunction(funcs, S) = funcs getfunction(funcs::NamedTuple, S::Symbol) = getfield(funcs, S) getfunction(a::Analysis{S}) where {S} = getfunction(a.f, S) (a::Analysis{S})(; kwargs...) where {S} = Analysis{S}(a; kwargs...) (a::Analysis{:automatic})(; kwargs...) = Analysis{:automatic}(a; kwargs...) (a::Analysis{S})(args...) where {S} = getfunction(a)(args...; a.kwargs...) (a::Analysis{:automatic})(args...) = (infer_axis(args...)(a))(args...) discrete(a::Analysis) = Analysis{:discrete}(a.f, a.kwargs) continuous(a::Analysis) = Analysis{:continuous}(a.f, a.kwargs) vectorial(a::Analysis) = Analysis{:vectorial}(a.f, a.kwargs) discrete(::Nothing) = nothing continuous(::Nothing) = nothing vectorial(::Nothing) = nothing Base.get(a::Analysis, s::Symbol, def) = get(a.kwargs, s, def) Base.get(f::Function, a::Analysis, s::Symbol) = get(f, a.kwargs, s) function set(f::Function, a::Analysis, s::Symbol) val = get(f, a, s) nt = NamedTuple{(s,)}((val,)) a(; nt...) end const FunctionOrAnalysis = Union{Function, Analysis} # TODO compute axis if called standalone! compute_axis(f::Function, args...) = compute_axis(Analysis(f), args...) infer_axis(x::AbstractVector{T}, args...) where {T<:Union{Missing, Number}} = Analysis{:continuous} infer_axis(x::AbstractVector{T}, args...) where {T<:Union{Missing, AbstractArray}} = Analysis{:vectorial} infer_axis(x::AbstractVector{Missing}, args...) = error("All data is missing") infer_axis(x, args...) = Analysis{:discrete} get_axis(s::Analysis) = s.kwargs.axis function compute_axis(a::Analysis, args...) a_inf = infer_axis(args...)(a) compute_axis(a_inf, args...) end continuous_axis(x, args...; npoints = 100) = range(extrema(x)...; length = npoints) function compute_axis(a::Analysis{:continuous}, args...) set(a, :axis) do npoints = get(a, :npoints, 100) continuous_axis(args..., npoints = npoints) end end discrete_axis(x, args...) = unique(sort(x)) function compute_axis(a::Analysis{:discrete}, args...) set(a, :axis) do discrete_axis(args...) end end vectorial_axis(x, args...) = axes(x[1], 1) function compute_axis(a::Analysis{:vectorial}, args...) set(a, :axis) do vectorial_axis(args...) end end has_error(a::Analysis) = has_error(getfunction(a)) has_error(a::Analysis, args...) = has_error(infer_axis(args...)(a)) has_error(args...) = false _expectedvalue(x, y; axis = nothing, kwargs...) = lazy_summary(x, y; kwargs...) has_error(::typeof(_expectedvalue)) = true function _localregression(x, y; npoints = 100, axis = continuous_axis(x, y; npoints = npoints), kwargs...) min, max = extrema(x) model = loess(convert(Vector{Float64}, x), convert(Vector{Float64}, y); kwargs...) return ((val, predict(model, val)) for (ind, val) in enumerate(axis) if min < val < max) end function _alignedsummary(xs, ys; axis = vectorial_axis(xs, ys), min_nobs = 2, stats = summary, kwargs...) stat, func = initstat(stats; kwargs...) iter = (view(y, x) for (x, y) in zip(xs, ys)) stats = OffsetArray([copy(stat) for _ in axis], axis) fitvecmany!(stats, iter) ((val, func(st)) for (val, st) in zip(axis, stats) if nobs(st) >= min_nobs) end has_error(::typeof(_alignedsummary)) = true const prediction = Analysis((continuous = _localregression, discrete = _expectedvalue, vectorial = _alignedsummary)) function _density(x; npoints = 100, axis = continuous_axis(x, npoints = npoints), kwargs...) d = InterpKDE(kde(x; kwargs...)) return ((val, pdf(d, val)) for val in axis) end function _frequency(x; axis = discrete_axis(x), npoints = 100) c = countmap(x) s = sum(values(c)) return ((val, get(c, val, 0)/s) for val in axis) end const density = Analysis((continuous = _density, discrete = _frequency)) function _cumulative(x; npoints = 100, axis = continuous_axis(x, npoints = npoints), kwargs...) func = ecdf(x) return ((val, func(val)) for val in axis) end function _cumulative_frequency(x; axis = discrete_axis(x, npoints = npoints), kwargs...) func = ecdf(x) return ((val, func(val)) for val in axis) end const cumulative = Analysis((continuous = _cumulative, discrete = _cumulative_frequency)) function _hazard(t; npoints = 100, axis = continuous_axis(t, npoints = npoints), kwargs...) pdf_iter = _density(t; axis = axis, kwargs...) cdf_func = ecdf(t) ((val, pdf / (1 + step(axis) * pdf - cdf_func(val))) for (val, pdf) in pdf_iter) end function _hazard_frequency(t; axis = discrete_axis(t), kwargs...) pdf_iter = _frequency(t; axis = axis, kwargs...) cdf_func = ecdf(t) ((val, pdf / (1 + pdf - cdf_func(val))) for (val, pdf) in pdf_iter) end const hazard = Analysis((continuous = _hazard, discrete = _hazard_frequency))
Recombinase
https://github.com/piever/Recombinase.jl.git
[ "MIT" ]
0.1.1
067aabe9bb023e12ccac4e52574891de7bfde242
code
4507
const Tup = Union{Tuple, NamedTuple} struct Automatic; end const automatic = Automatic() Base.string(::Automatic) = "automatic" apply(f::Function, a::Automatic) = a apply(f::Function, val) = f(val) apply(f::Tup, val::Tup) = map(apply, f, val) apply(f::Function, val::Tup) = map(f, val) _all(f::Function, tup::Tup) = all(f, tup) _all(f::Function, t) = f(t) isfinitevalue(::Missing) = false isfinitevalue(x::Number) = isfinite(x) statpost(m::OnlineStat) = m => value statpost(sp::Pair{<:OnlineStat}) = sp initstat(m::OnlineStat; kwargs...) = initstat(m => value; kwargs...) function initstat(sp::Pair{<:OnlineStat}; filter = isfinitevalue, transform = identity) stat, func = sp FTSeries(stat; filter = filter, transform = transform) => t -> func(first(t.stats)) end function initstat(stats::Tuple; filter = isfinitevalue, transform = identity) statsfuncs = map(statpost, stats) stats = map(first, statsfuncs) funcs = map(last, statsfuncs) FTSeries(stats...; filter = filter, transform = transform) => t -> apply(funcs, t.stats) end const summary = (Mean(), Variance() => t -> sqrt(value(t)/nobs(t))) function lazy_summary(keys::AbstractVector, cols; perm = sortperm(keys), min_nobs = 2, stats = summary, kwargs...) stat, func = initstat(stats; kwargs...) function process(idxs) apply(cols) do col init = copy(stat) for i in idxs val = col[perm[i]] fit!(init, val) end return init end end iter = (keys[perm[first(idxs)]] => process(idxs) for idxs in GroupPerm(keys, perm)) return (key => apply(func, vals) for (key, vals) in iter if _all(t -> nobs(t) >= min_nobs, vals)) end compute_summary(keys::AbstractVector, cols::AbstractVector; kwargs...) = compute_summary(keys, (cols,); kwargs...) function compute_summary(keys::AbstractVector, cols::Tup; kwargs...) collect_columns(val for (_, val) in lazy_summary(keys, cols; kwargs...)) end function compute_summary(f::FunctionOrAnalysis, keys::AbstractVector, cols::AbstractVector; kwargs...) compute_summary(f, keys, (cols,); kwargs...) end function compute_summary(f::FunctionOrAnalysis, keys::AbstractVector, cols::Tup; min_nobs = 2, perm = sortperm(keys), stats = summary, kwargs...) stat, func = initstat(stats; kwargs...) analysis = compute_axis(f, cols...) axis = get_axis(analysis) summaries = [copy(stat) for _ in axis] data = StructVector(cols) _compute_summary!(axis, summaries, analysis, keys, perm, data) return collect_columns((ax, func(s)) for (ax, s) in zip(axis, summaries) if nobs(s) >= min_nobs) end _first(t) = t _first(t::Union{Tuple, NamedTuple}) = first(t) function fititer!(axis, summaries, iter) lo, hi = extrema(axes(axis, 1)) for (key, val) in iter ind = searchsortedfirst(axis, key, lo, hi, Base.Order.Forward) lo = ind + 1 ind > hi && break fit!(summaries[ind], _first(val)) end end function _compute_summary!(axis, summaries, analysis, keys, perm, data) for (_, idxs) in finduniquesorted(keys, perm) res = analysis(tupleofarrays(view(data, idxs))...) fititer!(axis, summaries, res) end end compute_summary(::Nothing, args...; kwargs...) = compute_summary(args...; kwargs...) compute_summary(t::IndexedTable, ::Automatic; select, kwargs...) = compute_summary(t; select = select, kwargs...) function compute_summary(t::IndexedTable; select, kwargs...) rows(t, select) end function compute_summary(t::IndexedTable, keys; select, kwargs...) perm, keys = sortpermby(t, keys, return_keys=true) compute_summary(keys, columntuple(t, select); perm=perm, kwargs...) end function compute_summary(f::FunctionOrAnalysis, t::IndexedTable, keys; select, kwargs...) perm, keys = sortpermby(t, keys, return_keys=true) compute_summary(f, keys, columntuple(t, select); perm=perm, kwargs...) end function compute_summary(f::FunctionOrAnalysis, t::IndexedTable; select, kwargs...) args = columntuple(t, select) has_error(f, args...) && (f = f(; kwargs...)) collect_columns(f(args...)) end compute_summary(f::FunctionOrAnalysis, t::IndexedTable, ::Automatic; select, kwargs...) = compute_summary(f, t; select=select, kwargs...) tupleofarrays(s::Tup) = Tuple(s) tupleofarrays(s::StructVector) = Tuple(fieldarrays(s)) to_tuple(s::Tup) = s to_tuple(v) = (v,) columntuple(t, cols) = to_tuple(columns(t, cols)) columntuple(t) = to_tuple(columns(t))
Recombinase
https://github.com/piever/Recombinase.jl.git
[ "MIT" ]
0.1.1
067aabe9bb023e12ccac4e52574891de7bfde242
code
4202
_hbox(args...) = Widgets.div(args...; style = Dict("display" => "flex", "flex-direction"=>"row")) _vbox(args...) = Widgets.div(args...; style = Dict("display" => "flex", "flex-direction"=>"column")) get_kwargs(; kwargs...) = kwargs string2kwargs(s::AbstractString) = eval(Meta.parse("get_kwargs($s)")) const analysis_options = OrderedDict( "" => nothing, "Cumulative" => Recombinase.cumulative, "Density" => Recombinase.density, "Hazard" => Recombinase.hazard, "Prediction" => Recombinase.prediction, ) function is_small(col, n = 100) for (ind, _) in enumerate(IterTools.distinct(col)) ind > n && return false end return true end function take_small(t, vec::AbstractVector{Symbol}, n = 100) filter(vec) do sym col = get(columns(t), sym, ()) return is_small(col, n) end end """ `gui(data, plotters; postprocess = NamedTuple())` Create a gui around `data::IndexedTable` given a list of plotting functions plotters. ## Examples ```julia using StatsPlots, Recombinase, JuliaDB, Interact school = loadtable(joinpath(Recombinase.datafolder, "school.csv")) plotters = [plot, scatter, groupedbar] Recombinase.gui(school, plotters) ``` """ function gui(data′, plotters; postprocess = NamedTuple()) (data′ isa AbstractObservable) || (data′ = Observable{Any}(data′)) data = @map table(&data′, copy = false, presorted = true) ns = @map collect(colnames(&data)) maybens = @map vcat(Symbol(), &ns) xaxis = dropdown(ns,label = "X") yaxis = dropdown(maybens,label = "Y") an_opt = dropdown(analysis_options, label = "Analysis") axis_type = dropdown([:automatic, :continuous, :discrete, :vectorial], label = "Axis type") error = dropdown(@map(vcat(automatic, &ns)), label="Error") styles = collect(keys(style_dict)) sort!(styles) smallns = map(take_small, data, maybens) splitters = [dropdown(smallns, label = string(style)) for style in styles] plotter = dropdown(plotters, label = "Plotter") ribbon = toggle("Ribbon", value = false) btn = button("Plot") output = Observable{Any}("Set the dropdown menus and press plot to get started.") plot_kwargs = Widgets.textbox("Insert optional plot attributes") @map! output begin &btn select = yaxis[] == Symbol() ? xaxis[] : (xaxis[], yaxis[]) grps = Dict(key => val[] for (key, val) in zip(styles, splitters) if val[] != Symbol()) an = an_opt[] an_inf = isnothing(an) ? nothing : Analysis{axis_type[]}(an) args, kwargs = series2D( an_inf, &data, Group(; grps...); postprocess = postprocess, select = select, error = error[], ribbon = ribbon[] ) plotter[](args...; kwargs..., string2kwargs(plot_kwargs[])...) end ui = Widget( OrderedDict( :xaxis => xaxis, :yaxis => yaxis, :analysis => an_opt, :axis_type => axis_type, :error => error, :plotter => plotter, :plot_button => btn, :plot_kwargs => plot_kwargs, :ribbon => ribbon, :splitters => splitters, ), output = output ) Widgets.@layout! ui Widgets.div( _hbox( :xaxis, :yaxis, :analysis, :axis_type, :error, :plotter ), :ribbon, :plot_button, _hbox( _vbox(:splitters...), _vbox(output, :plot_kwargs) ) ) end
Recombinase
https://github.com/piever/Recombinase.jl.git
[ "MIT" ]
0.1.1
067aabe9bb023e12ccac4e52574891de7bfde242
code
4276
struct Group{NT} kwargs::NT function Group(; kwargs...) nt = values(kwargs) NT = typeof(nt) return new{NT}(nt) end end Group(s) = Group(color = s) apply(f::Function, g::Group) = Group(; map(t -> apply(f, t), g.kwargs)...) to_string(t::Tuple) = join(t, ", ") to_string(t::Any) = string(t) to_string(nt::NamedTuple) = join(("$a = $b" for (a, b) in pairs(nt)), ", ") struct Observations; end const observations = Observations() Base.string(::Observations) = "observations" function sortpermby(t::IndexedTable, ::Observations; return_keys = false) perm = Base.OneTo(length(t)) return return_keys ? (perm, perm) : perm end function apply_postprocess(t::IndexedTable, res; select, postprocess) cols = Tuple(fieldarrays(res)) colinds = to_tuple(lowerselection(t, select)) N = length(colinds) cols_trimmed = cols[1:N] res = map(cols_trimmed, colinds) do col, ind isa(ind, Integer) && ind > 0 || return col name = colnames(t)[ind] haskey(postprocess, name) || return col f = postprocess[name] return collect_columns(apply(f, el) for el in col) end StructArray((res..., cols[N+1:end]...)) end function series2D(s::StructVector; ribbon = false) kwargs = Dict{Symbol, Any}() xcols, ycols = map(columntuple, fieldarrays(s)) x, y = xcols[1], ycols[1] yerr = ifelse(ribbon, :ribbon, :yerr) length(xcols) == 2 && (kwargs[:xerr] = xcols[2]) length(ycols) == 2 && (kwargs[yerr] = ycols[2]) return (x, y), kwargs end series2D(t, g = Group(); kwargs...) = series2D(nothing, t, g; kwargs...) function series2D(f::Union{Nothing, FunctionOrAnalysis}, t, g = Group(); select, error = automatic, kwargs...) isa(g, Group) || (g = Group(g)) by = _flatten(g.kwargs) err_cols = error === automatic ? () : to_tuple(error) sel_cols = (to_tuple(by)..., to_tuple(select)..., err_cols...) coltable = Tables.columntable(TableOperations.select(t, sel_cols...)) coldict = Dict(zip(sel_cols, keys(coltable))) to_symbol = i -> coldict[i] t = table(coltable, copy=false) return series2D(f, t, apply(to_symbol, g); select = apply(to_symbol, select), error = apply(to_symbol, error), kwargs...) end function series2D(f::Union{Nothing, FunctionOrAnalysis}, t′::IndexedTable, g = Group(); select, postprocess = NamedTuple(), error = automatic, ribbon=false, stats=summary, filter=isfinitevalue, transform=identity, min_nobs=2, kwargs...) t = dropmissing(t′, select) isa(g, Group) || (g = Group(g)) group = g.kwargs if isempty(group) itr = ("" => :,) else by = _flatten(group) perm, group_rows = sortpermby(t, by, return_keys = true) itr = finduniquesorted(group_rows, perm) end keys = similar(group_rows, 0) vals = collect_columns_flattened( Base.Generator(itr) do (key, idxs) v = compute_summary( f, view(t, idxs), error; min_nobs=min_nobs, select=select, stats=stats, filter=filter, transform=transform, ) append!(keys, fill(key, length(v))) return v end ) res = apply_postprocess(t, vals; select = select, postprocess = postprocess) plot_args, plot_kwargs = series2D(res; ribbon = ribbon) plot_kwargs[:group] = columns(keys) grpd = collect_columns(key for (key, _) in itr) style_kwargs = Dict(kwargs) for (key, val) in pairs(group) col = rows(grpd, val) s = unique(sort(col)) d = Dict(zip(s, 1:length(s))) style = get(style_kwargs, key) do style_dict[key] end plot_kwargs[key] = permutedims(access_style(style, getindex.(Ref(d), col))) end get!(plot_kwargs, :color, "black") plot_args, plot_kwargs end function access_style(st, n::AbstractArray) [access_style(st, i) for i in n] end function access_style(st, n::Integer) v = vec(st) m = ((n-1) % length(v))+1 v[m] end _flatten(t) = IterTools.imap(to_tuple, t) |> Iterators.flatten |> IterTools.distinct |> Tuple
Recombinase
https://github.com/piever/Recombinase.jl.git
[ "MIT" ]
0.1.1
067aabe9bb023e12ccac4e52574891de7bfde242
code
937
#= Conservative 7-color palette from Points of view: Color blindness, Bang Wong - Nature Methods https://www.nature.com/articles/nmeth.1618?WT.ec_id=NMETH-201106 =# const wong_colors = [ RGB(230/255, 159/255, 0/255), RGB(86/255, 180/255, 233/255), RGB(0/255, 158/255, 115/255), RGB(240/255, 228/255, 66/255), RGB(0/255, 114/255, 178/255), RGB(213/255, 94/255, 0/255), RGB(204/255, 121/255, 167/255), ] const default_style_dict = Dict{Symbol, Any}( :color => wong_colors, :markershape => [:circle, :diamond, :utriangle, :star5, :cross], :linestyle => [:solid, :dash, :dot, :dashdot], :linewidth => [1,4,2,3], :markersize => [3,9,5,7] ) const style_dict = copy(default_style_dict) function set_theme!(; kwargs...) empty!(style_dict) for (key, val) in default_style_dict style_dict[key] = val end for (key, val) in kwargs style_dict[key] = val end end
Recombinase
https://github.com/piever/Recombinase.jl.git
[ "MIT" ]
0.1.1
067aabe9bb023e12ccac4e52574891de7bfde242
code
1909
using OffsetArrays: OffsetArray # replace first entries in a by b merge_tups(a::Tuple, b) = merge_tups(a, to_tuple(b)::Tuple) merge_tups(a::Tuple, ::Tuple{}) = a merge_tups(a::Tuple, b::Tuple) = (first(b), merge_tups(Base.tail(a), Base.tail(b))...) # only take first few entries of a so that result is as long as b cut_tup(a::Tuple, b) = cut_tup(a, to_tuple(b)::Tuple) cut_tup(a::Tuple, ::Tuple{}) = () cut_tup(a::Tuple, b::Tuple) = (first(a), cut_tup(Base.tail(a), Base.tail(b))...) to_indexarray(t::Tuple{AbstractArray}) = t[1] to_indexarray(t::Tuple{AbstractArray, Vararg{AbstractArray}}) = CartesianIndices(t) _view(a::AbstractArray{<:Any, M}, b::AbstractArray{<:Any, N}) where {M, N} = view(a, b, ntuple(_ -> :, M-N)...) _view(a::AbstractArray{<:Any, N}, b::AbstractArray{<:Any, N}) where {N} = view(a, b) offsetrange(v, offset, range=()) = offsetrange(v, to_tuple(offset)::Tuple, to_tuple(range)::Tuple) function offsetrange(v, offset::Tuple, range::Tuple=()) short_axes = cut_tup(axes(v), offset) padded_range = merge_tups(short_axes, range) rel_offset = map(short_axes, offset, padded_range) do ax, off, r - off + first(r) - first(ax) end OffsetArray(to_indexarray(padded_range), rel_offset) end aroundindex(v, args...) = _view(v, offsetrange(v, args...)) function initstats(stat, ranges) ranges = to_tuple(ranges) itr = Iterators.product(ranges...) vec = [copy(stat) for _ in itr] return OffsetArray(vec, ranges) end # TODO combine fititer! and fitvec! function fitvec!(m, val, shared_indices = eachindex(m, val)) for cart in shared_indices @inbounds fit!(m[cart], val[cart]) end return m end function fitvecmany!(m, iter) for el in iter am, ael = axes(m), axes(el) shared = (am == ael) ? eachindex(m, el) : CartesianIndices(map(intersect, am, ael)) fitvec!(m, el, shared) end return m end
Recombinase
https://github.com/piever/Recombinase.jl.git
[ "MIT" ]
0.1.1
067aabe9bb023e12ccac4e52574891de7bfde242
code
2310
using Statistics, StatsBase using StructArrays using Recombinase using Recombinase: compute_summary, aroundindex, discrete, prediction, density using Test using IndexedTables using OnlineStatsBase @testset "discrete" begin x = [1, 2, 3, 1, 2, 3] y = [0.3, 0.1, 0.3, 0.4, 0.2, 0.1] across = [1, 1, 1, 2, 2, 2] res = compute_summary( discrete(prediction)(min_nobs = 1), across, (x, y), stats = Mean() ) xcol, ycol = fieldarrays(res) @test xcol == [1, 2, 3] @test map(Recombinase._first, ycol) ≈ [0.35, 0.15, 0.2] res = compute_summary( discrete(density), across, (x,), stats = Mean() ) xcol, ycol = fieldarrays(res) @test xcol == [1, 2, 3] @test map(Recombinase._first, ycol) ≈ [1, 1, 1]./3 end # example function to test initstats and fitvecmany! function fitvec(stats, iter, ranges) start = iterate(iter) start === nothing && error("Nothing to fit!") val, state = start init = Recombinase.initstats(stats, Recombinase.merge_tups(axes(val), ranges)) Recombinase.fitvecmany!(init, Iterators.rest(iter, state)) StructArray(((nobs = nobs(el), value = value(el)) for el in init); unwrap = t -> t <: Union{Tuple, NamedTuple}) end @testset "timeseries" begin v1 = rand(1000) # day 1 v2 = rand(50) # day 2 traces = [v1, v1, v1, v2, v2, v2] ts = [10, 501, 733, 1, 20, 30] trims = [7:13, 498:504, 730:736, 1:4, 17:23, 27:33] stats = Series(mean = Mean(), variance = Variance()) s = fitvec(stats, (aroundindex(trace, t) for (trace, t) in zip(traces, ts)), -5:5); @test axes(s) == (-5:5,) @test s[-3].nobs == 4 @test s[-3].value isa NamedTuple{(:mean, :variance)} s = fitvec(stats, (aroundindex(trace, t, trim) for (trace, t, trim) in zip(traces, ts, trims)), -5:5); @test axes(s) == (-5:5,) @test s[-3].nobs == 4 @test s[-3].value isa NamedTuple{(:mean, :variance)} @test s[-4].nobs == 0 stats = Mean() s = fitvec(stats, (aroundindex(trace, t) for (trace, t) in zip(traces, ts)), -5:5); @test axes(s) == (-5:5,) @test s[-3].nobs == 4 @test s[-3].value isa Float64 g() = aroundindex(rand(4, 4, 4), (2, 2), (1:3, 1:3)) @inferred g() @test axes(g()) == (-1:1, -1:1, 1:4) end
Recombinase
https://github.com/piever/Recombinase.jl.git
[ "MIT" ]
0.1.1
067aabe9bb023e12ccac4e52574891de7bfde242
docs
530
# Recombinase [![Build Status](https://travis-ci.org/piever/Recombinase.jl.svg?branch=master)](https://travis-ci.org/piever/Recombinase.jl) [![](https://img.shields.io/badge/docs-latest-blue.svg)](https://piever.github.io/Recombinase.jl/latest/index.html) A simple package to do data analyses and visualizations. See the [docs](https://piever.github.io/Recombinase.jl/latest/index.html) to learn how to use it. ![interactgui](https://user-images.githubusercontent.com/6333339/55816219-b3af4a00-5ae9-11e9-94f5-d3cc4e5d722d.png)
Recombinase
https://github.com/piever/Recombinase.jl.git
[ "MIT" ]
0.1.1
067aabe9bb023e12ccac4e52574891de7bfde242
docs
432
# Index Recombinase allows to do simple data analyses and visualizations in Julia, especially in the case of grouped data. ## Getting started To install Recombinase, simply activate the package REPL with `]` in the Julia console and then add the package using the repository URL: ```julia julia> ] pkg> add https://github.com/piever/Recombinase.jl.git ``` See the [Tutorial](@ref) for a quick guide on how to use this package.
Recombinase
https://github.com/piever/Recombinase.jl.git
[ "MIT" ]
0.1.1
067aabe9bb023e12ccac4e52574891de7bfde242
docs
502
# Interactive interface Most of the available analyses can be selected from a simple [Interact](http://juliagizmos.github.io/Interact.jl/latest/)-based UI. To launch the UI simply do: ```julia using Recombinase, Interact, StatsPlots, Blink # here we give the functions we want to use for plotting ui = Recombinase.gui(data, [plot, scatter, groupedbar]); w = Window() body!(w, ui) ``` ![interactgui](https://user-images.githubusercontent.com/6333339/55816219-b3af4a00-5ae9-11e9-94f5-d3cc4e5d722d.png)
Recombinase
https://github.com/piever/Recombinase.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
5593
module QuantizedSystemSolver const global VERBOSE=false const global DEBUG=false const global DEBUG2=false #using ResumableFunctions using RuntimeGeneratedFunctions using StaticArrays using SymEngine using PolynomialRoots #using Reexport #@reexport using StaticArrays #@reexport using ResumableFunctions #using SymEngine##########might not need using ExprTools #combineddef using MacroTools: postwalk,prewalk, @capture#, isexpr, #= import Base.:- import Base.:+ import Base.:* =# using Plots: plot!,plot,savefig using Dates: now,year,month,day,hour,minute,second #fortimestamp #using TimerOutputs########################################################temporary #using Profile################################################################temporary RuntimeGeneratedFunctions.init(@__MODULE__) #this section belongs to taylorseries subcomponent import Base: ==, +, -, *, /, ^ #import Plots:plot! #import Base: Base.gc_enable import Base: iterate, size, eachindex, firstindex, lastindex, eltype, length, getindex, setindex!, axes, copyto! import Base: sqrt, exp, log, sin, cos, sincos, tan, asin, acos, atan, sinh, cosh, tanh, atanh, asinh, acosh, zero, one, zeros, ones, isinf, isnan, iszero, convert, promote_rule, promote, show,abs #= real, imag, conj, adjoint, rem, mod, mod2pi, abs2, =# #= power_by_squaring, rtoldefault, isfinite, isapprox, rad2deg, deg2rad =# #end of taylorseries section of imports # list of public (API) to the user, not between files as those are linked as if in one file export qss1,qss2,qss3,liqss1,liqss2,liqss3,mliqss1,mliqss2,mliqss3,light,heavy,sparse,dense,saveat,nliqss1,nliqss2,nliqss3,nmliqss1,nmliqss2,nmliqss3 export save_Sol,save_SolDer,save_SimulSol#,stacksave_Sol,plotSol,stackplotSol,plot_save_Sol,stackplot_save_Sol,plot_save_SolVars,plotSol_Der1,evaluateSol,save_SolVar,save_SolZoomed export save_SolSum,plotRelativeError#,stackplotRelativeError,plot_save_RelativeError,stackplot_save_RelativeError,saveRelativeError,stacksaveRelativeError export plotAbsoluteError#,stackplotAbsoluteError,plot_save_AbsoluteError,stackplot_save_AbsoluteError,saveAbsoluteError,stacksaveAbsoluteError export getError,getPlot,getPlot!#,plotCumulativeSquaredRelativeError,plotMSE,getIntervalError,plotElapsed export NLODEProblem export NLodeProblem#= , @NLodeProblem,@saveNLodeProblem =#,solve,save_prob_to_model,QSS_Solve_from_model,solInterpolated export Sol,getErrorByRodas,getAllErrorsByRefs,getAverageErrorByRefs export Taylor0,mulT,mulTT,createT,addsub,negateT,subsub,subadd,subT,addT,muladdT,mulsub,divT # in case to save into a file, otherwise remove export savedNLODEContProblem,savedNLODEDiscProblem,EventDependencyStruct export testfunc """testfunc(expression) creates a problem from the user code """ testfunc(x) = 2x + 1 #include section of ts subcomponent # include("ownTaylor/parameters.jl") include("ownTaylor/constructors.jl") # include("ownTaylor/conversion.jl") include("ownTaylor/arithmetic.jl") include("ownTaylor/arithmeticT.jl") include("ownTaylor/functions.jl") include("ownTaylor/functionsT.jl") include("ownTaylor/power.jl") include("ownTaylor/powerT.jl") include("ownTaylor/auxiliary.jl") include("ownTaylor/calculus.jl") include("ownTaylor/other_functions.jl") include("ownTaylor/evaluate.jl") #Utils include("Utils/rootfinders/SimUtils.jl") # include("Utils/rootfinders/intervalNewton.jl") include("Utils/rootfinders/inter9-var.jl") include("Utils/rootfinders/compare_cubics_smallPos.jl") #Common include("Common/TaylorEquationConstruction.jl") include("Common/QSSNL_AbstractTypes.jl") include("Common/Solution.jl") include("Common/SolutionPlot.jl") include("Common/SolutionDerPlot.jl") include("Common/SolutionError.jl") include("Common/Helper_QSSNLProblem.jl") include("Common/Helper_QSSNLDiscreteProblem.jl") include("Common/QSSNLContinousProblem.jl") include("Common/QSSNLdiscrProblem.jl") include("Common/QSS_Algorithm.jl") include("Common/QSS_data.jl") include("Common/Scheduler.jl") # integrator # include("dense/NL_integrators/NL_QSS_Integrator.jl") # include("dense/NL_integrators/NL_QSS_discreteIntegrator.jl") # implicit integrator when large entries on the main diagonal of the jacobian # include("dense/NL_integrators/NL_LiQSS_Integrator.jl") # include("dense/NL_integrators/NL_LiQSS_discreteIntegrator.jl") # implicit integrator when large entries NOT on the main diagonal of the jacobian include("dense/NL_integrators/NL_nmLiQSS_Integrator.jl") include("dense/NL_integrators/NL_nmLiQSS_discreteIntegrator.jl") #implicit intgrators used to show improvement of modifications # include("dense/NL_integrators/NL_mLiQSS_Integrator.jl") # include("dense/NL_integrators/NL_nLiQSS_Integrator.jl") include("dense/Quantizers/Quantizer_Common.jl") include("dense/Quantizers/QSS_quantizer.jl") include("dense/Quantizers/LiQSS_quantizer1.jl") include("dense/Quantizers/LiQSS_quantizer2.jl") include("dense/Quantizers/LiQSS_quantizer3.jl") include("dense/Quantizers/mLiQSS_quantizer1.jl") include("dense/Quantizers/mLiQSS_quantizer2.jl") include("dense/Quantizers/mLiQSS_quantizer3.jl") #main entrance/ Interface include("Interface/indexMacro.jl") include("Interface/QSS_Solve.jl") end # module
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
8219
struct EventDependencyStruct id::Int evCont::Vector{Int} #index tracking used for HD & HZ. Also it is used to update q,quantum,recomputeNext when x is modified in an event evDisc::Vector{Int} #index tracking used for HD & HZ. evContRHS::Vector{Int} #index tracking used to update other Qs before executing the event end # the following functions handle discrete problems # to extract jac & dD....SD can be extracted from jac later function extractJacDepNormal(varNum::Int,rhs::Union{Symbol,Int,Expr},jac :: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}},exacteJacExpr :: Dict{Expr,Union{Float64,Int,Symbol,Expr}},symDict::Dict{Symbol,Expr},dD :: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}}) jacSet=Set{Union{Int,Symbol,Expr}}() #jacDiscrSet=Set{Union{Int,Symbol,Expr}}() m=postwalk(rhs) do a # if a isa Expr && a.head == :ref && a.args[1]==:q# q[2] push!(jacSet, (a.args[2])) # du[varNum=1]=rhs=u[5]+u[2] : 2 and 5 are stored in jacset one at a time a=eliminateRef(a)#q[i] -> qi elseif a isa Expr && a.head == :ref && a.args[1]==:d# d[3] # push!(jacDiscrSet, (a.args[2])) # dDset=Set{Union{Int,Symbol,Expr}}() if haskey(dD, (a.args[2])) # dict dD already contains key a.args[2] (in this case var 3) dDset=get(dD,(a.args[2]),dDset) # if var d3 first time to influence some var, dDset is empty, otherwise get its set of influences end push!(dDset, varNum) # d3 also influences varNum dD[(a.args[2])]=dDset #update the dict a=eliminateRef(a)#d[i] -> di end return a end # extract the jac basi = convert(Basic, m) # m ready: all refs are symbols for i in jacSet # jacset contains vars in RHS symarg=symbolFromRef(i) # specific to elements in jacSet: get q1 from 1 for exple coef = diff(basi, symarg) # symbolic differentiation: returns type Basic coefstr=string(coef);coefExpr=Meta.parse(coefstr)#convert from basic to expression jacEntry=restoreRef(coefExpr,symDict)# get back ref: qi->q[i][0] ...0 because later in exactJac fun cache[1]::Float64=jacEntry exacteJacExpr[:(($varNum,$i))]=jacEntry # entry (varNum,i) is jacEntry end if length(jacSet)>0 jac[varNum]=jacSet end #if length(jacDiscrSet)>0 jacDiscr[varNum]=jacDiscrSet end end # like above except (b,niter) instead of varNum function extractJacDepLoop(b::Int,niter::Int,rhs::Union{Symbol,Int,Expr},jac :: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}},exacteJacExpr :: Dict{Expr,Union{Float64,Int,Symbol,Expr}},symDict::Dict{Symbol,Expr},dD :: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}}) #dD is for the saving-function case jacSet=Set{Union{Int,Symbol,Expr}}() # jacDiscrSet=Set{Union{Int,Symbol,Expr}}() #sdSet=Set{Union{Int,Symbol,Expr}}() # when the index is a symbol or expr SD will be filled like Jac and later (the caller outside) will extract SDFunction. SDset uppercase is for numbers #dDSet=Set{Union{Int,Symbol,Expr}}() # feature not implemented: I will restrict d[---] to integers ie --- == intger m=postwalk(rhs) do a if a isa Expr && a.head == :ref && a.args[1]==:q# push!(jacSet, (a.args[2])) # a=eliminateRef(a)#q[i] -> qi elseif a isa Expr && a.head == :ref && a.args[1]==:d # push!(jacDiscrSet, (a.args[2])) if a.args[2] isa Int #for now allow only d[integer] dDset=Set{Union{Int,Symbol,Expr}}() if haskey(dD, (a.args[2])) dDset=get(dD,(a.args[2]),dDset) end push!(dDset, :(($b,$niter))) dD[(a.args[2])]=dDset #= elseif a.args[2] isa Symbol push!(dDSet, (a.args[2])) elseif a.args[2] isa Expr temp=deepcopy(a.args[2]) if a.args[2].args[1]== :+ temp.args[1]= :- elseif a.args[2].args[1]== :- temp.args[1]= :+ elseif a.args[2].args[1]== :* temp.args[1]= :/ elseif a.args[2].args[1]== :/ temp.args[1]= :* end push!(dDSet, temp) =# end a=eliminateRef(a)#q[i] -> qi end return a end basi = convert(Basic, m) for i in jacSet symarg=symbolFromRef(i); coef = diff(basi, symarg) coefstr=string(coef); coefExpr=Meta.parse(coefstr) jacEntry=restoreRef(coefExpr,symDict) exacteJacExpr[:((($b,$niter),$i))]=jacEntry end jac[:(($b,$niter))]=jacSet # jacDiscr[:(($b,$niter))]=jacDiscrSet # SD[:(($b,$niter))]=sdSet #symbol and expressions stored like jac end function extractZCJacDepNormal(counter::Int,zcf::Expr,zcjac :: Vector{Vector{Int}},SZ ::Dict{Int,Set{Int}},dZ :: Dict{Int,Set{Int}}) zcjacSet=Set{Int}() #zcjacDiscrSet=Set{Int}() postwalk(zcf) do a # if a isa Expr && a.head == :ref && a.args[1]==:q# push!(zcjacSet, (a.args[2])) # SZset=Set{Int}() if haskey(SZ, (a.args[2])) SZset=get(SZ,(a.args[2]),SZset) end push!(SZset, counter) SZ[(a.args[2])]=SZset elseif a isa Expr && a.head == :ref && a.args[1]==:d# # push!(zcjacDiscrSet, (a.args[2])) # dZset=Set{Int}() if haskey(dZ, (a.args[2])) dZset=get(dZ,(a.args[2]),dZset) end push!(dZset, counter) dZ[(a.args[2])]=dZset end return a end push!(zcjac,collect(zcjacSet))#convert set to vector #push!(zcjacDiscr,collect(zcjacDiscrSet)) end function createDependencyToEventsDiscr(dD::Vector{Vector{Int}},dZ::Dict{Int64, Set{Int64}},eventDep::Vector{EventDependencyStruct}) Y=length(eventDep) lendD=length(dD) HD2 = Vector{Vector{Int}}(undef, Y) HZ2 = Vector{Vector{Int}}(undef, Y) for ii=1:Y HD2[ii] =Vector{Int}()# define it so i can push elements as i find them below HZ2[ii] =Vector{Int}()# define it so i can push elements as i find them below end for j=1:Y hdSet=Set{Int}() hzSet=Set{Int}() evdiscrete=eventDep[j].evDisc for i in evdiscrete if i<=lendD for k in dD[i] push!(hdSet,k) end end tempSet=Set{Int}() if haskey(dZ, i) tempSet=get(dZ,i,tempSet) end for kk in tempSet push!(hzSet,kk) end end HD2[j] =collect(hdSet)# define it so i can push elements as i find them below HZ2[j] =collect(hzSet) end #end for j (events) return (HZ2,HD2) end function createDependencyToEventsCont(SD::Vector{Vector{Int}},sZ::Dict{Int64, Set{Int64}},eventDep::Vector{EventDependencyStruct}) Y=length(eventDep) HD2 = Vector{Vector{Int}}(undef, Y) HZ2 = Vector{Vector{Int}}(undef, Y) for ii=1:Y HD2[ii] =Vector{Int}()# define it so i can push elements as i find them below HZ2[ii] =Vector{Int}()# define it so i can push elements as i find them below end for j=1:Y hdSet=Set{Int}() hzSet=Set{Int}() evContin=eventDep[j].evCont for i in evContin for k in SD[i] push!(hdSet,k) end tempSet=Set{Int}() if haskey(sZ, i) tempSet=get(sZ,i,tempSet) end for kk in tempSet push!(hzSet,kk) end end HD2[j] =collect(hdSet)# define it so i can push elements as i find them below HZ2[j] =collect(hzSet) end #end for j (events) return (HZ2,HD2) end #function unionDependency(HZ1::SVector{Y,SVector{Z,Int}},HZ2::SVector{Y,SVector{Z,Int}})where{Z,Y} function unionDependency(HZ1::Vector{Vector{Int}},HZ2::Vector{Vector{Int}}) Y=length(HZ1) HZ = Vector{Vector{Int}}(undef, Y) for ii=1:Y HZ[ii] =Vector{Int}()# define it so i can push elements as i find them below end for j=1:Y hzSet=Set{Int}() for kk in HZ1[j] push!(hzSet,kk) end for kk in HZ2[j] push!(hzSet,kk) end HZ[j]=collect(hzSet) end HZ end
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
6504
function changeExprToFirstValue(ex::Expr)## newEx=postwalk(ex) do a # change u[1] to u[1][0] if a isa Expr && a.head == :ref && a.args[1]==:q # change q[1] to q[1][0] outerRef=Expr(:ref) push!(outerRef.args,a) push!(outerRef.args,:(0)) a=outerRef end return a end newEx end function eliminateRef(a)#q[i] -> qi if a.args[2] isa Expr if a.args[2].args[1]==:+ a=Symbol((a.args[1]),(a.args[2].args[2]), "plus",(a.args[2].args[3])) elseif a.args[2].args[1]==:- a=Symbol((a.args[1]),(a.args[2].args[2]), "minus",(a.args[2].args[3])) elseif a.args[2].args[1]==:* a=Symbol((a.args[1]),(a.args[2].args[2]), "times",(a.args[2].args[3])) elseif a.args[2].args[1]==:/ a=Symbol((a.args[1]),(a.args[2].args[2]), "over",(a.args[2].args[3])) end else a=Symbol((a.args[1]),(a.args[2])) end return a end function symbolFromRef(refEx)#refEx is i+1 in q[i+1] for example if refEx isa Expr # if refEx.args[1]==:+ refEx=Symbol("q",(refEx.args[2]), "plus",(refEx.args[3])) elseif refEx.args[1]==:- refEx=Symbol("q",(refEx.args[2]), "minus",(refEx.args[3])) elseif refEx.args[1]==:* refEx=Symbol("q",(refEx.args[2]), "times",(refEx.args[3])) elseif refEx.args[1]==:/ refEx=Symbol("q",(refEx.args[2]), "over",(refEx.args[3])) end else refEx=Symbol("q",(refEx)) end return refEx end function symbolFromRefd(refEx)#refEx is i+1 in q[i+1] for example if refEx isa Expr # if refEx.args[1]==:+ refEx=Symbol("d",(refEx.args[2]), "plus",(refEx.args[3])) elseif refEx.args[1]==:- refEx=Symbol("d",(refEx.args[2]), "minus",(refEx.args[3])) elseif refEx.args[1]==:* refEx=Symbol("d",(refEx.args[2]), "times",(refEx.args[3])) elseif refEx.args[1]==:/ refEx=Symbol("d",(refEx.args[2]), "over",(refEx.args[3])) end else refEx=Symbol("d",(refEx)) end return refEx end function restoreRef(coefExpr,symDict) newEx=postwalk(coefExpr) do element# if element isa Symbol && !(element in (:+,:-,:*,:/)) && haskey(symDict, element) && element != :d element=symDict[element] element=changeExprToFirstValue(element)# change u[1] to u[1][0] elseif element== :d element=symDict[element] end return element end#end postwalk newEx end function changeVarNames_params(ex::Expr,stateVarName::Symbol,muteVar::Symbol,param::Dict{Symbol,Union{Float64,Expr}},symDict::Dict{Symbol,Expr})# newEx=postwalk(ex) do element#postwalk to change var names and parameters if element isa Symbol if haskey(param, element)#symbol is a parameter element=copy(param[element]) # copy needed in the case symbol id=expression substitued in equations...do not want all eqs reference same expression...ie if 1 eq changes, other eqs change elseif element==stateVarName #symbol is a var element=:q elseif element==:discrete #symbol is a discr var element=:d elseif element==muteVar #symbol is a mute var element=:i #= else # + - * / =# end elseif element isa Expr && element.head == :ref && element.args[1]==:q# symarg=symbolFromRef(element.args[2]) #q[i] -> qi symDict[symarg]=element #store this translation q[i] <-> qi for later use elseif element isa Expr && element.head == :ref && element.args[1]==:d# symarg=symbolFromRefd(element.args[2]) #d[i] -> di symDict[symarg]=element #store this translation d[i] <-> di end return element end#end postwalk newEx end function changeVarNames_params(ex::Expr,stateVarName::Symbol,muteVar::Symbol,param::Dict{Symbol,Union{Float64,Expr}})######special for if statements and events newEx=postwalk(ex) do element#postwalk to change var names and parameters if element isa Symbol if haskey(param, element)#symbol is a parameter element=copy(param[element]) elseif element==stateVarName #symbol is a var element=:q elseif element==:discrete #symbol is a discr var element=:d elseif element==muteVar #symbol is a mute var element=:i #= else # + - * / =# end end return element end#end postwalk newEx end # these 2 function handle continuous problems only function extractJacDepNormal(varNum::Int,rhs::Union{Int,Expr},jac :: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}}, exacteJacExpr :: Dict{Expr,Union{Float64,Int,Symbol,Expr}},symDict::Dict{Symbol,Expr}) jacSet=Set{Union{Int,Symbol,Expr}}() m=postwalk(rhs) do a # if a isa Expr && a.head == :ref # push!(jacSet, (a.args[2])) # du[varNum=1]=rhs=u[5]+u[2] : 2 and 5 are stored in jacset a=eliminateRef(a)#q[i] -> qi end return a end basi = convert(Basic, m) for i in jacSet symarg=symbolFromRef(i) # specific to elements in jacSet: get q1 from 1 for exple coef = diff(basi, symarg) # symbolic differentiation: returns type Basic coefstr=string(coef);coefExpr=Meta.parse(coefstr)#convert from basic to expression jacEntry=restoreRef(coefExpr,symDict)# get back ref: qi->q[i][0] ...0 because later in exactJac fun cache[1]::Float64=jacEntry exacteJacExpr[:(($varNum,$i))]=jacEntry # entry (varNum,i) is jacEntry end if length(jacSet)>0 jac[varNum]=jacSet end # jac={1->(2,5)} #@show jac end function extractJacDepLoop(b::Int,niter::Int,rhs::Union{Int,Expr},jac :: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}} ,exacteJacExpr :: Dict{Expr,Union{Float64,Int,Symbol,Expr}},symDict::Dict{Symbol,Expr}) jacSet=Set{Union{Int,Symbol,Expr}}() m=postwalk(rhs) do a if a isa Expr && a.head == :ref # push!(jacSet, (a.args[2])) # a=eliminateRef(a) end return a end basi = convert(Basic, m) for i in jacSet symarg=symbolFromRef(i); coef = diff(basi, symarg) coefstr=string(coef); #= coef1 = diff(basi, symarg)#df coef2 = diff(coef1, symarg)#ddf coefstr=string(coef1,-,"(",coef2,")*",symarg,*,0.5) =# # coefstr=string("(",basi,")/",symarg) coefExpr=Meta.parse(coefstr) jacEntry=restoreRef(coefExpr,symDict) exacteJacExpr[:((($b,$niter),$i))]=jacEntry end if length(jacSet)>0 jac[:(($b,$niter))]=jacSet end end
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
14448
struct NLODEContProblem{PRTYPE,T,Z,Y,CS}<: NLODEProblem{PRTYPE,T,Z,Y,CS} prname::Symbol # problem name used to distinguish printed results prtype::Val{PRTYPE} # problem type: not used but created in case in the future we want to handle problems differently a::Val{T} #problem size based on number of vars: T is used not a: 'a' is a mute var b::Val{Z} #number of Zero crossing functions (ZCF) based on number of 'if statements': Z is used not b: 'b' is a mute var c::Val{Y} #number of discrete events=2*ZCF: Z is used not c: 'c' is a mute var cacheSize::Val{CS}# CS= cache size is used : 'cacheSize' is a mute var initConditions::Vector{Float64} # eqs::Function#function that holds all ODEs jac::Vector{Vector{Int}}#Jacobian dependency..I have a der and I want to know which vars affect it...opposite of SD...is a vect for direct method (later @resumable..closure..for saved method) SD::Vector{Vector{Int}}# I have a var and I want the der that are affected by it exactJac::Function # used only in the implicit intgration #map::Function # if sparsity to be exploited: it maps a[i][j] to a[i][γ] where γ usually=1,2,3...(a small int) jacDim::Function # if sparsity to be exploited: gives length of each row end # to create NLODEContProblem above function NLodeProblemFunc(odeExprs::Expr,::Val{T},::Val{0},::Val{0}, initConditions::Vector{Float64} ,du::Symbol,symDict::Dict{Symbol,Expr})where {T} if VERBOSE println("nlodeprobfun T= $T") end equs=Dict{Union{Int,Expr},Expr}() #du[int] or du[i]==du[a<i<b]==du[(a:b)] jac = Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}}()# datastrucutre 'Set' used because we do not want to insert an existing varNum exacteJacExpr = Dict{Expr,Union{Float64,Int,Symbol,Expr}}() # NO need to constrcut SD...SDVect will be extracted from Jac num_cache_equs=1#initial cachesize::will hold the number of caches (vectors) of the longest equation for argI in odeExprs.args #only diff eqs: du[]= number || ref || call if argI isa Expr && argI.head == :(=) && argI.args[1] isa Expr && argI.args[1].head == :ref && argI.args[1].args[1]==du#expr LHS=RHS and LHS is du y=argI.args[1];rhs=argI.args[2] varNum=y.args[2] # order/index of variable if rhs isa Number # rhs of equ =number equs[varNum]=:($((transformFSimplecase(:($(rhs)))))) #change rhs from N to cache=taylor0=[[N,0,0],2] for order 2 for exple elseif rhs isa Symbol # case du=t #equs[varNum ]=quote $rhs end equs[varNum ]=:($((transformFSimplecase(:($(rhs))))))# elseif rhs.head==:ref #rhs is only one var extractJacDepNormal(varNum,rhs,jac,exacteJacExpr ,symDict ) #extract jacobian and exactJac approx form from normal equation equs[varNum ]=:($((transformFSimplecase(:($(rhs))))))#change rhs from q[i] to cache=q[i] ...just put taylor var in cache else #rhs head==call...to be tested later for math functions and other possible scenarios or user erros extractJacDepNormal(varNum,rhs,jac,exacteJacExpr,symDict ) temp=(transformF(:($(rhs),1))).args[2] #temp=number of caches distibuted...rhs already changed inside if num_cache_equs<temp num_cache_equs=temp end equs[varNum]=rhs end elseif @capture(argI, for counter_ in b_:niter_ loopbody__ end) #case where diff equation is an expr in for loop specRHS=loopbody[1].args[2] extractJacDepLoop(b,niter,specRHS,jac,exacteJacExpr,symDict ) #extract jacobian and SD dependencies from loop temp=(transformF(:($(specRHS),1))).args[2] if num_cache_equs<temp num_cache_equs=temp end equs[:(($b,$niter))]=specRHS else#end of equations and user enter something weird...handle later # error("expression $x: top level contains only expressions 'A=B' or 'if a b' or for loop... ")# end #end for x in end #end for args ######################################################################################################### fname= :f #default problem name #path="./temp.jl" #default path if odeExprs.args[1] isa Expr && odeExprs.args[1].args[2] isa Expr && odeExprs.args[1].args[2].head == :tuple#user has to enter problem info in a tuple fname= odeExprs.args[1].args[2].args[1] #path=odeExprs.args[1].args[2].args[2] end exacteJacfunction=createExactJacFun(exacteJacExpr,fname) #= open("./temp.jl", "a") do io println(io,string(exacteJacfunction)) end =# exactJacfunctionF=@RuntimeGeneratedFunction(exacteJacfunction) diffEqfunction=createContEqFun(equs,fname)# diff equations before this are stored in a dict:: now we have a giant function that holds all diff equations jacVect=createJacVect(jac,Val(T)) #jacobian dependency SDVect=createSDVect(jac,Val(T)) # state derivative dependency # mapFun=createMapFun(jac,fname) # for sparsity jacDimFunction=createJacDimensionFun(jac,fname) #for sparsity diffEqfunctionF=@RuntimeGeneratedFunction(diffEqfunction) # @RuntimeGeneratedFunction changes a fun expression to actual fun without running into world age problems # mapFunF=@RuntimeGeneratedFunction(mapFun) jacDimFunctionF=@RuntimeGeneratedFunction(jacDimFunction) prob=NLODEContProblem(fname,Val(1),Val(T),Val(0),Val(0),Val(num_cache_equs),initConditions,diffEqfunctionF,jacVect,SDVect,exactJacfunctionF,jacDimFunctionF)# prtype type 1...prob not saved and struct contains vects end function createContEqFun(equs::Dict{Union{Int,Expr},Expr},funName::Symbol) s="if i==0 return nothing\n" # :i is the mute var for elmt in equs Base.remove_linenums!(elmt[1]) Base.remove_linenums!(elmt[2]) if elmt[1] isa Int s*="elseif i==$(elmt[1]) $(elmt[2]) ;return nothing\n" end if elmt[1] isa Expr s*="elseif $(elmt[1].args[1])<=i<=$(elmt[1].args[2]) $(elmt[2]) ;return nothing\n" end end s*=" end " myex1=Meta.parse(s) Base.remove_linenums!(myex1) def=Dict{Symbol,Any}() def[:head] = :function def[:name] = funName def[:args] = [:(i::Int),:(q::Vector{Taylor0}),:(t::Taylor0),:(cache::Vector{Taylor0})] def[:body] = myex1 functioncode=combinedef(def) # @show functioncode;functioncode end function createJacDimensionFun(jac:: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}},funName::Symbol) ss="if i==0 return 0\n" for dictElement in jac #= Base.remove_linenums!(dictElement[1]) Base.remove_linenums!(dictElement[2]) =# # counterJac=1 if dictElement[1] isa Int ss*="elseif i==$(dictElement[1]) \n" ss*="return $(length(dictElement[2])) \n" # ss*=" return nothing \n" elseif dictElement[1] isa Expr ss*="elseif $(dictElement[1].args[1])<=i<=$(dictElement[1].args[2]) \n" ss*="return $(length(dictElement[2])) \n" end end ss*=" end \n" myex1=Meta.parse(ss) Base.remove_linenums!(myex1) def1=Dict{Symbol,Any}() #any changeto Union{expr,Symbol} ???? def1[:head] = :function def1[:name] = Symbol(:jacDimension,funName) def1[:args] = [:(i::Int)] def1[:body] = myex1 functioncode1=combinedef(def1) end function createMapFun(jac:: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}},funName::Symbol) ss="if i==0 return nothing\n" for dictElement in jac #= Base.remove_linenums!(dictElement[1]) Base.remove_linenums!(dictElement[2]) =# # counterJac=1 if dictElement[1] isa Int ss*="elseif i==$(dictElement[1]) \n" ns=sort!(collect(dictElement[2])) ss*="if j==0 return nothing\n" iter=1 for k in ns ss*="elseif j==$k \n" ss*="cache[1]=$iter \n" ss*=" return nothing \n" iter+=1 end ss*=" end \n" elseif dictElement[1] isa Expr ss*="elseif $(dictElement[1].args[1])<=i<=$(dictElement[1].args[2]) \n" @show dictElement[2] ns=sort!(collect(dictElement[2])) ss*="if j==0 return nothing\n" iter=1 for k in ns ss*="elseif j==$k \n" ss*="cache[1]=$iter \n" ss*=" return nothing \n" iter+=1 end ss*=" end \n" end end ss*=" end \n" myex1=Meta.parse(ss) Base.remove_linenums!(myex1) def1=Dict{Symbol,Any}() #any changeto Union{expr,Symbol} ???? def1[:head] = :function def1[:name] = Symbol(:map,funName) def1[:args] = [:(cache::MVector{1,Int}),:(i::Int),:(j::Int)] def1[:body] = myex1 functioncode1=combinedef(def1) end function createExactJacFun(jac:: Dict{Expr,Union{Float64,Int,Symbol,Expr}},funName::Symbol) ss="if i==0 return nothing\n" for dictElement in jac if dictElement[1].args[1] isa Int ss*="elseif i==$(dictElement[1].args[1]) && j==$(dictElement[1].args[2]) \n" ss*="cache[1]=$(dictElement[2]) \n" ss*=" return nothing \n" elseif dictElement[1].args[1] isa Expr ss*="elseif $(dictElement[1].args[1].args[1])<=i<=$(dictElement[1].args[1].args[2]) && j==$(dictElement[1].args[2]) \n" ss*="cache[1]=$(dictElement[2]) \n" ss*=" return nothing \n" end end ss*=" end \n" myex1=Meta.parse(ss) Base.remove_linenums!(myex1) def1=Dict{Symbol,Any}() #any changeto Union{expr,Symbol} ???? def1[:head] = :function def1[:name] = Symbol(:exactJac,funName) def1[:args] = [:(q::Vector{Taylor0}),:(d::Vector{Float64}),:(cache::MVector{1,Float64}),:(i::Int),:(j::Int),:(t::Float64)] def1[:body] = myex1 functioncode1=combinedef(def1) end function createExactJacDiscreteFun(jac:: Dict{Expr,Union{Float64,Int,Symbol,Expr}},funName::Symbol) ss="if i==0 return nothing\n" for dictElement in jac if dictElement[1].args[1] isa Int ss*="elseif i==$(dictElement[1].args[1]) && j==$(dictElement[1].args[2]) \n" ss*="cache[1]=$(dictElement[2]) \n" ss*=" return nothing \n" elseif dictElement[1].args[1] isa Expr ss*="elseif $(dictElement[1].args[1].args[1])<=i<=$(dictElement[1].args[1].args[2]) && j==$(dictElement[1].args[2]) \n" ss*="cache[1]=$(dictElement[2]) \n" ss*=" return nothing \n" end end ss*=" end \n" myex1=Meta.parse(ss) Base.remove_linenums!(myex1) def1=Dict{Symbol,Any}() #any changeto Union{expr,Symbol} ???? def1[:head] = :function def1[:name] = Symbol(:exactJac,funName) def1[:args] = [:(q::Vector{Taylor0}),:(d::Vector{Float64}),:(cache::MVector{1,Float64}),:(i::Int),:(j::Int),:(t::Float64)] # in jac t does not need to be a taylor def1[:body] = myex1 functioncode1=combinedef(def1) end function createJacVect(jac:: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}},::Val{T}) where{T}# jacVect = Vector{Vector{Int}}(undef, T) for i=1:T jacVect[i]=Vector{Int}()# define it so i can push elements as i find them below end for dictElement in jac if dictElement[1] isa Int #jac[varNum]=jacSet jacVect[dictElement[1]]=collect(dictElement[2]) elseif dictElement[1] isa Expr #jac[:(($b,$niter))]=jacSet for j_=(dictElement[1].args[1]):(dictElement[1].args[2]) temp=Vector{Int}() for element in dictElement[2] if element isa Expr || element isa Symbol#can split symbol alone since no need to postwalk fa= postwalk(a -> a isa Symbol && a==:i ? j_ : a, element) # change each symbol i to exact number push!(temp,eval(fa)) else #element is int push!(temp,element) end end jacVect[j_]=temp end end end jacVect end function createSDVect(jac:: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}},::Val{T}) where{T} sdVect = Vector{Vector{Int}}(undef, T) for ii=1:T sdVect[ii]=Vector{Int}()# define it so i can push elements as i find them below end #SD = Dict{Union{Int64, Expr}, Set{Union{Int64, Expr, Symbol}}}(2 => Set([1]), 10 => Set([10]), :((2, 9)) => Set([:k, :(k - 1), :(k + 1)]), 9 => Set([10]), 1 => Set([1])) for dictElement in jac if dictElement[1] isa Int # key is an int for k in dictElement[2] #elments values push!(sdVect[k],dictElement[1]) end elseif dictElement[1] isa Expr # key is an expression for j_=(dictElement[1].args[1]):(dictElement[1].args[2]) # j_=b:N this can be expensive when N is large::this is why it is recommended to use a function createsd (save) for large prob for element in dictElement[2] if element isa Expr || element isa Symbol#element= fa= postwalk(a -> a isa Symbol && a==:i ? j_ : a, element) push!(sdVect[eval(fa)],j_) else#element is int push!(sdVect[element],j_) end end end end end sdVect end #helper funs used in lines 136 and 150 function Base.isless(ex1::Expr, ex2::Expr)#:i is the mute var that prob is now using fa= postwalk(a -> a isa Symbol && a==:i ? 1 : a, ex1)# check isa symbol not needed fb=postwalk(a -> a isa Symbol && a==:i ? 1 : a, ex2) eval(fa)<eval(fb) end function Base.isless(ex1::Expr, ex2::Symbol) fa= postwalk(a -> a isa Symbol && a==:i ? 1 : a, ex1) eval(fa)<1 end function Base.isless(ex1::Symbol, ex2::Expr) fa= postwalk(a -> a isa Symbol && a==:i ? 1 : a, ex2) 1<eval(fa) end
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
201
abstract type NLODEProblem{PRTYPE,T,Z,Y,CS} end abstract type ALGORITHM{N,O} end abstract type Sol{T,O} end abstract type SpecialQSS_data{O1,Lightness} end abstract type SpecialLiqssQSS_data end
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
18118
#helper struct that holds dependency metadata of an event (which vars exist on which side lhs=rhs #= struct EventDependencyStruct id::Int evCont::Vector{Int} evDisc::Vector{Int} evContRHS::Vector{Int} end =# #struct that holds prob data struct NLODEDiscProblem{PRTYPE,T,Z,D,CS}<: NLODEProblem{PRTYPE,T,Z,D,CS} prname::Symbol prtype::Val{PRTYPE} a::Val{T} b::Val{Z} c::Val{D} cacheSize::Val{CS} initConditions::Vector{Float64} discreteVars::Vector{Float64} jac::Vector{Vector{Int}}#Jacobian dependency..I have a der and I want to know which vars affect it...opposite of SD ZCjac::Vector{Vector{Int}} # to update other Qs before checking ZCfunction eqs::Function#function that holds all ODEs eventDependencies::Vector{EventDependencyStruct}# SD::Vector{Vector{Int}}# I have a var and I want the der that are affected by it HZ::Vector{Vector{Int}}# an ev occured and I want the ZC that are affected by it HD::Vector{Vector{Int}}# an ev occured and I want the der that are affected by it SZ::Vector{Vector{Int}}# I have a var and I want the ZC that are affected by it exactJac::Function #used only in the implicit integration: linear approximation end function getInitCond(prob::NLODEDiscProblem,i::Int) return prob.initConditions[i] end #= function getInitCond(prob::savedNLODEDiscProblem,i::Int) return prob.initConditions(i) end =# # receives user code and creates the problem struct function NLodeProblemFunc(odeExprs::Expr,::Val{T},::Val{D},::Val{Z},initCond::Vector{Float64},du::Symbol,symDict::Dict{Symbol,Expr})where {T,D,Z} if VERBOSE println("discrete nlodeprobfun T D Z= $T $D $Z") end # @show odeExprs discrVars=Vector{Float64}() equs=Dict{Union{Int,Expr},Union{Int,Symbol,Expr}}() jac = Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}}()# set used because do not want to insert an existing varNum #SD = Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}}() # NO need to constrcut SD...SDVect will be extracted from Jac (needed for func-save case) #jacDiscrete = Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}}()# for now is similar to continous jac...if feature of d[i] not to be added then jacDiscr=Dict{Union{Int,Expr},Set{Int}}()...later dD = Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}}() # similarly if feature not given then dD=Dict{Int,Set{Union{Int,Symbol,Expr}}}() exacteJacExpr = Dict{Expr,Union{Float64,Int,Symbol,Expr}}() zcequs=Vector{Expr}()#vect to collect if-statements eventequs=Vector{Expr}()#vect to collect events ZCjac=Vector{Vector{Int}}()#zeros(SVector{Z,SVector{T,Int}}) # bad when T is large...it is a good idea to use Vector{Vector{Int}}(undef, Z) ZCFCounter=0 #SZ=Vector{Vector{Int}}()#zeros(SVector{T,SVector{Z,Int}}) # bad when T is large...(opposite of ZCjac)...many vars dont influence zcf so it is better to use dict # dZ=Vector{Vector{Int}}()#zeros(SVector{D,SVector{Z,Int}})# usually D (num of disc vars) and Z (num of zcfunctions) are small even for real problems SZ= Dict{Int,Set{Int}}() dZ= Dict{Int,Set{Int}}() #since D is not large ...i can use zeros(SVector{D,SVector{Z,Int}}) evsArr = EventDependencyStruct[] num_cache_equs=1#cachesize for argI in odeExprs.args if argI isa Expr && argI.head == :(=) && argI.args[1]== :discrete discrVars = Vector{Float64}(argI.args[2].args) #only diff eqs: du[]= number/one ref/call elseif argI isa Expr && argI.head == :(=) && argI.args[1] isa Expr && argI.args[1].head == :ref && argI.args[1].args[1]==du#&& ((argI.args[2] isa Expr && (argI.args[2].head ==:ref || argI.args[2].head ==:call ))||argI.args[2] isa Number) y=argI.args[1];rhs=argI.args[2] varNum=y.args[2] # order of variable if rhs isa Number || rhs isa Symbol # rhs of equ =number or symbol equs[varNum]=:($((transformFSimplecase(:($(rhs)))))) elseif rhs isa Expr && rhs.head==:ref && rhs.args[1]==:q #rhs is only one var...# rhs.args[1]==:q # check not needed? extractJacDepNormal(varNum,rhs,jac,exacteJacExpr ,symDict,dD ) # end equs[varNum ]=:($((transformFSimplecase(:($(rhs)))))) #elseif rhs isa Symbol #time t else #rhs head==call...to be tested later for math functions and other possible scenarios or user erros extractJacDepNormal(varNum,rhs,jac,exacteJacExpr ,symDict,dD ) temp=(transformF(:($(rhs),1))).args[2] #number of caches distibuted ...no need interpolation and wrap in expr?....before was cuz quote.... if num_cache_equs<temp num_cache_equs=temp end equs[varNum]=rhs end elseif @capture(argI, for counter_ in b_:niter_ loopbody__ end) specRHS=loopbody[1].args[2] # extractJacDepLoop(b,niter,specRHS,jac ,jacDiscrete ,SD,dD ) extractJacDepLoop(b,niter,specRHS,jac,exacteJacExpr,symDict ,dD ) temp=(transformF(:($(specRHS),1))).args[2] if num_cache_equs<temp num_cache_equs=temp end equs[:(($b,$niter))]=specRHS elseif argI isa Expr && argI.head==:if #@capture if did not work zcf=argI.args[1].args[2] ZCFCounter+=1 extractZCJacDepNormal(ZCFCounter,zcf,ZCjac ,SZ ,dZ ) if zcf.head==:ref #if one_Var push!(zcequs,(transformFSimplecase(:($(zcf))))) ########################push!(zcequs,:($((transformFSimplecase(:($(zcf))))))) # push!(num_cache_zcequs,1) #to be deleted later else # if whole expre ops with many vars temp=:($((transformF(:($(zcf),1))).args[2])) #number of caches distibuted, given 1 place holder for ex.args[2] to be filled inside and returned if num_cache_equs<temp num_cache_equs=temp end push!(zcequs,(zcf)) end ################################################################################################################## # events ################################################################################################################## # each 'if-statmets' has 2 events (arg[2]=posEv and arg[3]=NegEv) each pos or neg event has a function...later i can try one event for zc if length(argI.args)==2 #if user only wrote the positive evnt, here I added the negative event wich does nothing nothingexpr = quote nothing end # neg dummy event push!(argI.args, nothingexpr) Base.remove_linenums!(argI.args[3]) end # end#end temporary if # end#end temporay for argI #pos event newPosEventExprToFunc=changeExprToFirstValue(argI.args[2]) #change u[1] to u[1][0] # pos ev can't be a symbol ...later maybe add check anyway push!(eventequs,newPosEventExprToFunc) #neg eve if argI.args[3].args[1] isa Expr # argI.args[3] isa expr and is either an equation or :block symbol end ...so lets check .args[1] newNegEventExprToFunc=changeExprToFirstValue(argI.args[3]) push!(eventequs,newNegEventExprToFunc) else push!(eventequs,argI.args[3]) #symbol nothing end #after constructing the equations we move to dependencies: we need to change A[n] to An so that they become symbols posEvExp = argI.args[2] negEvExp = argI.args[3] #dump(negEvExp) indexPosEv = 2 * length(zcequs) - 1 # store events in order indexNegEv = 2 * length(zcequs) #------------------pos Event--------------------# posEv_disArrLHS= Vector{Int}()#@SVector fill(NaN, D) #...better than @SVector zeros(D), I can use NaN posEv_conArrLHS= Vector{Int}()#@SVector fill(NaN, T) posEv_conArrRHS=Vector{Int}()#@SVector zeros(T) #to be used inside intgrator to updateOtherQs (intgrateState) before executing the event there is no discArrRHS because d is not changing overtime to be updated for j = 1:length(posEvExp.args) # j coressponds the number of statements under one posEvent # !(posEvExp.args[j] isa Expr && posEvExp.args[j].head == :(=)) && error("event should be A=B") if (posEvExp.args[j] isa Expr && posEvExp.args[j].head == :(=)) poslhs=posEvExp.args[j].args[1];posrhs=posEvExp.args[j].args[2] # !(poslhs isa Expr && poslhs.head == :ref && (poslhs.args[1]==:q || poslhs.args[1]==:d)) && error("lhs of events must be a continuous or a discrete variable") if (poslhs isa Expr && poslhs.head == :ref && (poslhs.args[1]==:q || poslhs.args[1]==:d)) if poslhs.args[1]==:q push!(posEv_conArrLHS,poslhs.args[2]) else # lhs is a disc var push!(posEv_disArrLHS,poslhs.args[2]) end #@show poslhs,posrhs postwalk(posrhs) do a # if a isa Expr && a.head == :ref && a.args[1]==:q# push!(posEv_conArrRHS, (a.args[2])) # end return a end end end end #------------------neg Event--------------------# negEv_disArrLHS= Vector{Int}()#@SVector fill(NaN, D) #...better than @SVector zeros(D), I can use NaN negEv_conArrLHS= Vector{Int}()#@SVector fill(NaN, T) negEv_conArrRHS=Vector{Int}()#@SVector zeros(T) #to be used inside intgrator to updateOtherQs (intgrateState) before executing the event there is no discArrRHS because d is not changing overtime to be updated if negEvExp.args[1] != :nothing for j = 1:length(negEvExp.args) # j coressponds the number of statements under one negEvent # !(negEvExp.args[j] isa Expr && negEvExp.args[j].head == :(=)) && error("event should be A=B") neglhs=negEvExp.args[j].args[1];negrhs=negEvExp.args[j].args[1] # !(neglhs isa Expr && neglhs.head == :ref && (neglhs.args[1]==:q || neglhs.args[1]==:d)) && error("lhs of events must be a continuous or a discrete variable") if (neglhs isa Expr && neglhs.head == :ref && (neglhs.args[1]==:q || neglhs.args[1]==:d)) if neglhs.args[1]==:q push!(negEv_conArrLHS,neglhs.args[2]) else # lhs is a disc var push!(negEv_disArrLHS,neglhs.args[2]) end postwalk(negrhs) do a # if a isa Expr && a.head == :ref && a.args[1]==:q# push!(negEv_conArrRHS, (a.args[2])) # end return a end end end end structposEvent = EventDependencyStruct(indexPosEv, posEv_conArrLHS, posEv_disArrLHS,posEv_conArrRHS) # right now posEv_conArr is vect of ... push!(evsArr, structposEvent) structnegEvent = EventDependencyStruct(indexNegEv, negEv_conArrLHS, negEv_disArrLHS,negEv_conArrRHS) push!(evsArr, structnegEvent) end #end cases end #end for ######################################################################################################### ############@show evsArr #println("end of useless convesrion to svector") allEpxpr=Expr(:block) ##############diffEqua###################### #= io = IOBuffer() # i guess this is a sys of diff equ solver so I am not optimizing for case 1 equ write(io, "if j==1 $(equs[1]) ;return nothing") =# s="if i==0 return nothing\n" # :i is the mute var for elmt in equs Base.remove_linenums!(elmt[1]) Base.remove_linenums!(elmt[2]) if elmt[1] isa Int s*="elseif i==$(elmt[1]) $(elmt[2]) ;return nothing\n" end if elmt[1] isa Expr s*="elseif $(elmt[1].args[1])<=i<=$(elmt[1].args[2]) $(elmt[2]) ;return nothing\n" end end s*=" end " myex1=Meta.parse(s) push!(allEpxpr.args,myex1) ##############ZCF###################### if length(zcequs)>0 #= io = IOBuffer() write(io, "if zc==1 $(zcequs[1]) ;return nothing") =# s="if zc==1 $(zcequs[1]) ;return nothing" for i=2:length(zcequs) s*= " elseif zc==$i $(zcequs[i]) ;return nothing" end # write(io, " else $(zcequs[length(zcequs)]) ;return nothing end ") s*= " end " myex2=Meta.parse(s) push!(allEpxpr.args,myex2) end ##############events###################### if length(eventequs)>0 s= "if ev==1 $(eventequs[1]) ;return nothing" for i=2:length(eventequs) s*= " elseif ev==$i $(eventequs[i]) ;return nothing" end # write(io, " else $(zcequs[length(zcequs)]) ;return nothing end ") s*= " end " myex3=Meta.parse(s) push!(allEpxpr.args,myex3) end fname= :f #default problem name #path="./temp.jl" #default path if odeExprs.args[1] isa Expr && odeExprs.args[1].args[2] isa Expr && odeExprs.args[1].args[2].head == :tuple#user has to enter problem info in a tuple fname= odeExprs.args[1].args[2].args[1] #path=odeExprs.args[1].args[2].args[2] end Base.remove_linenums!(allEpxpr) def=Dict{Symbol,Any}() def[:head] = :function def[:name] = fname def[:args] = [:(i::Int),:(zc::Int),:(ev::Int),:(q::Vector{Taylor0}),:(d::Vector{Float64}), :(t::Taylor0),:(cache::Vector{Taylor0})] def[:body] = allEpxpr #def[:rtype]=:nothing# test if cache1 always holds sol functioncode=combinedef(def) functioncodeF=@RuntimeGeneratedFunction(functioncode) #= jac = Dict{Union{Int64, Expr}, Set{Union{Int64, Expr, Symbol}}}(1 => Set([2])) SD = Dict{Union{Int64, Expr}, Set{Union{Int64, Expr, Symbol}}}(2 => Set([1])) jacDiscrete = Dict{Union{Int64, Expr}, Set{Union{Int64, Expr, Symbol}}}(1 => Set()) dD = Dict{Union{Int64, Expr}, Set{Union{Int64, Expr, Symbol}}}() ZCjac = [[1], [2]] ZCFCounter = 2 SZ = Dict{Int64, Set{Int64}}(2 => Set([2]), 1 => Set([1])) dZ = Dict{Int64, Set{Int64}}(1 => Set([1])) =# jacVect=createJacVect(jac,Val(T)) SDVect=createSDVect(jac,Val(T)) #@show dD dDVect =createdDvect(dD,Val(D)) #jacDiscreteVect=createJacVect(jacDiscrete,Val(T)) # SZvect=createSZvect(SZ,Val(T)) #@show evsArr #@show jacVect,SDVect,dDVect,SZvect #= SDVect = [Int64[], [2, 1], [3], [4], Int64[]] jacVect = [[2], [2], [3], [4], Int64[]] jacDiscreteVect = [[2, 1], [1], [1], [1], [2, 1]] dDVect = [[5, 2, 3, 4, 1], [5, 1]] =# # temporary dependencies to be used to determine HD and HZ...determine HD: event-->Derivative && determine HZ:Event-->ZCfunction....influence of events on derivatives and zcfunctions: #an event is a discrteVar change or a cont Var change. So HD=HD1 UNION HD2 (same for HZ=HZ1 UNION HZ2) # (1) through a discrete Var: # ============================ # HD1=Hd-->dD where Hd comes from the eventDependecies Struct. # HZ1=Hd-->dZ where Hd comes from the eventDependecies Struct. HZ1HD1=createDependencyToEventsDiscr(dDVect,dZ,evsArr) # @show HZ1HD1 # (2) through a continous Var: # ============================== # HD2=Hs-->sD where Hs comes from the eventDependecies Struct.(sd already created) # HZ2=Hs-->sZ where Hs comes from the eventDependecies Struct.(sZ already created) HZ2HD2=createDependencyToEventsCont(SDVect,SZ,evsArr) # @show HZ2HD2 ##########UNION############## HZ=unionDependency(HZ1HD1[1],HZ2HD2[1]) # @show HZ HD=unionDependency(HZ1HD1[2],HZ2HD2[2]) # @show HD # mapFun=createMapFun(jac,fname) # mapFunF=@RuntimeGeneratedFunction(mapFun) exacteJacfunction=createExactJacDiscreteFun(exacteJacExpr,fname) exacteJacfunctionF=@RuntimeGeneratedFunction(exacteJacfunction) if VERBOSE println("discrete problem created") end myodeProblem = NLODEDiscProblem(fname,Val(1),Val(T),Val(Z),Val(D),Val(num_cache_equs),initCond, discrVars, jacVect ,ZCjac ,functioncodeF, evsArr,SDVect,HZ,HD,SZvect,exacteJacfunctionF) end function createdDvect(dD::Dict{Union{Int64, Expr}, Set{Union{Int64, Expr, Symbol}}},::Val{D})where{D} dDVect = Vector{Vector{Int}}(undef, D) for ii=1:D dDVect[ii]=Vector{Int}()# define it so i can push elements as i find them below end for dictElement in dD temp=Vector{Int}() for k in dictElement[2] if k isa Int push!(temp,k) elseif k isa Expr #tuple for j_=(k.args[1]):(k.args[2]) push!(temp,j_) end end end dDVect[dictElement[1]]=temp end dDVect end function createSZvect(SZ :: Dict{Int64, Set{Int64}},::Val{T})where{T} szVect = Vector{Vector{Int}}(undef, T) for ii=1:T szVect[ii]=Vector{Int}()# define it so i can push elements as i find them below end for ele in SZ szVect[ele[1]]=collect(ele[2]) end szVect end
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
790
# struct QSSAlgorithm{N,O}#<:QSSAlgorithm{N,O} name::Val{N} order::Val{O} end qss1()=QSSAlgorithm(Val(:qss),Val(1)) qss2()=QSSAlgorithm(Val(:qss),Val(2)) qss3()=QSSAlgorithm(Val(:qss),Val(3)) nmliqss1()=QSSAlgorithm(Val(:nmliqss),Val(1)) nmliqss2()=QSSAlgorithm(Val(:nmliqss),Val(2)) nmliqss3()=QSSAlgorithm(Val(:nmliqss),Val(3)) nliqss1()=QSSAlgorithm(Val(:nliqss),Val(1)) nliqss2()=QSSAlgorithm(Val(:nliqss),Val(2)) nliqss3()=QSSAlgorithm(Val(:nliqss),Val(3)) mliqss1()=QSSAlgorithm(Val(:mliqss),Val(1)) mliqss2()=QSSAlgorithm(Val(:mliqss),Val(2)) mliqss3()=QSSAlgorithm(Val(:mliqss),Val(3)) liqss1()=QSSAlgorithm(Val(:liqss),Val(1)) liqss2()=QSSAlgorithm(Val(:liqss),Val(2)) liqss3()=QSSAlgorithm(Val(:liqss),Val(3)) sparse()=Val(true) dense()=Val(false)
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
2128
#= """ hold helper datastructures needed for simulation, can be seen as the model in the qss architecture (model-integrator-quantizer)""" =# struct CommonQSS_data{Z} quantum :: Vector{Float64} x :: Vector{Taylor0} #MVector cannot hold non-isbits q :: Vector{Taylor0} tx :: Vector{Float64} tq :: Vector{Float64} d::Vector{Float64} nextStateTime :: Vector{Float64} nextInputTime :: Vector{Float64} # nextEventTime :: MVector{Z,Float64} t::Taylor0# mute taylor var to be used with math functions to represent time integratorCache::Taylor0 taylorOpsCache::Vector{Taylor0} finalTime:: Float64 savetimeincrement::Float64 initialTime :: Float64 dQmin ::Float64 dQrel ::Float64 maxErr ::Float64 savedTimes :: Vector{Vector{Float64}} savedVars:: Vector{Vector{Float64}} end #= ``` data needed only for implicit case ``` =# struct LiQSS_data{O,Sparsity} vs::Val{Sparsity} a::Vector{Vector{Float64}} # u:: Vector{Vector{MVector{O,Float64}}} qaux::Vector{MVector{O,Float64}} olddx::Vector{MVector{O,Float64}} dxaux::Vector{MVector{O,Float64}} olddxSpec::Vector{MVector{O,Float64}} end struct LightSpecialQSS_data{O1,Lightness}<:SpecialQSS_data{O1,Lightness} ls::Val{Lightness} p::Val{O1} savedVars :: Vector{Vector{Float64}} #has to be vector (not SA) cuz to be resized in integrator end #= struct HeavySpecialQSS_data{T,O1,Lightness}<:SpecialQSS_data{T,O1,Lightness} ls::Val{Lightness} savedVars :: Vector{Array{Taylor0}} #has to be vector (not SA) cuz to be resized in integrator prevStepVal ::MVector{T,MVector{O1,Float64}} #use end =# struct SpecialLiQSS_data<:SpecialLiqssQSS_data cacheA::MVector{1,Float64} direction::Vector{Float64} qminus::Vector{Float64} buddySimul::MVector{2,Int} prevStepVal ::Vector{Float64} end #= function createSpecialQSS_data(savedVars :: Vector{Array{Taylor0}}, prevStepVal::MVector{T,MVector{O1,Float64}},cacheA::MVector{1,Int}) where {T,O1} hv=HeavySpecialQSS_data(savedVars,prevStepVal,cacheA) end =#
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
1456
function updateScheduler(::Val{T},nextStateTime::Vector{Float64},nextEventTime :: MVector{Z,Float64},nextInputTime :: Vector{Float64})where{T,Z} #later MVect for nextInput minStateTime=Inf minState_index=0 # what if all nextstateTime= Inf ...especially at begining????? min_index stays 0!!! minEventTime=Inf minEvent_index=0 minInputTime=Inf minInput_index=0 returnedVar=() # used to print something if something is bad for i=1:T if nextStateTime[i]<minStateTime minStateTime=nextStateTime[i] minState_index=i end if nextInputTime[i] < minInputTime minInputTime=nextInputTime[i] minInput_index=i end end for i=1:Z if nextEventTime[i] < minEventTime minEventTime=nextEventTime[i] minEvent_index=i end end if minEventTime<minStateTime if minInputTime<minEventTime returnedVar=(minInput_index,minInputTime,:ST_INPUT) else returnedVar=(minEvent_index,minEventTime,:ST_EVENT) end else if minInputTime<minStateTime returnedVar=(minInput_index,minInputTime,:ST_INPUT) else returnedVar=(minState_index,minStateTime,:ST_STATE) end end if returnedVar[1]==0 returnedVar=(1,Inf,:ST_STATE) println("null step made state step") end return returnedVar end
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
6348
struct LightSol{T,O}<:Sol{T,O} size::Val{T} order::Val{O} savedTimes::Vector{Vector{Float64}} savedVars::Vector{Vector{Float64}} #savedVarsQ::Vector{Vector{Float64}} algName::String sysName::String absQ::Float64 totalSteps::Int simulStepCount::Int evCount::Int numSteps ::Vector{Int} ft::Float64 end struct HeavySol{T,O}<:Sol{T,O} size::Val{T} order::Val{O} savedTimes::Vector{Vector{Float64}} savedVars::Vector{Vector{Float64}} savedDers::Vector{Vector{Float64}} #savedVarsQ::Vector{Vector{Float64}} algName::String sysName::String absQ::Float64 totalSteps::Int simulStepCount::Int evCount::Int numSteps ::Vector{Int} ft::Float64 end @inline function createSol(::Val{T},::Val{O}, savedTimes:: Vector{Vector{Float64}},savedVars :: Vector{Vector{Float64}},solver::String,nameof_F::String,absQ::Float64,totalSteps::Int#= ,stepsaftersimul::Int =#,simulStepCount::Int,evCount::Int,numSteps ::Vector{Int},ft::Float64#= ,simulStepsVals :: Vector{Vector{Float64}}, simulStepsDers :: Vector{Vector{Float64}} ,simulStepsTimes :: Vector{Vector{Float64}} =#)where {T,O} # println("light") sol=LightSol(Val(T),Val(O),savedTimes, savedVars,solver,nameof_F,absQ,totalSteps#= ,stepsaftersimul =#,simulStepCount,evCount,numSteps,ft#= ,simulStepsVals,simulStepsDers,simulStepsTimes =#) end @inline function createSol(::Val{T},::Val{O}, savedTimes:: Vector{Vector{Float64}},savedVars :: Vector{Vector{Float64}},savedDers :: Vector{Vector{Float64}},solver::String,nameof_F::String,absQ::Float64,totalSteps::Int#= ,stepsaftersimul::Int =#,simulStepCount::Int,evCount::Int,numSteps ::Vector{Int},ft::Float64#= ,simulStepsVals :: Vector{Vector{Float64}}, simulStepsDers :: Vector{Vector{Float64}} ,simulStepsTimes :: Vector{Vector{Float64}} =#)where {T,O} # println("light") sol=HeavySol(Val(T),Val(O),savedTimes, savedVars,savedDers,solver,nameof_F,absQ,totalSteps#= ,stepsaftersimul =#,simulStepCount,evCount,numSteps,ft#= ,simulStepsVals,simulStepsDers,simulStepsTimes =#) end function getindex(s::Sol, i::Int64) if i==1 return s.savedTimes elseif i==2 return s.savedVars else error("sol has 2 attributes: time and states") end end @inline function evaluateSol(sol::LightSol{T,O},index::Int,t::Float64)where {T,O} (t>sol.ft) && error("given point is outside the sol range") x=sol[2][index][end] #integratorCache=Taylor0(zeros(O+1),O) for i=2:length(sol[1][index])#savedTimes after the init time...init time is at index i=1 if sol[1][index][i]>t # i-1 is closest lower point f1=sol[2][index][i-1];f2=sol[2][index][i];t1=sol[1][index][i-1] ;t2=sol[1][index][i]# find x=f(t)=at+b...linear interpolation a=(f2-f1)/(t2-t1) b=(f1*t2-f2*t1)/(t2-t1) x=a*t+b # println("1st case") return x#taylor evaluation after small elapsed with the point before (i-1) elseif sol[1][index][i]==t # i-1 is closest lower point x=sol[2][index][i] # println("2nd case") return x end end # println("3rd case") return x #if var never changed then return init cond or if t>lastSavedTime for this var then return last value end function solInterpolated(sol::Sol{T,O},step::Float64)where {T,O} #(sol.ft>sol[1][end]) && error("given point is outside the sol range") #numPoints=length(sol.savedTimes) interpTimes=Float64[] allInterpTimes=Vector{Vector{Float64}}(undef, T) t=0.0 #later can change to init_time which could be diff than zero push!(interpTimes,t) while t+step<sol.ft t=t+step push!(interpTimes,t) end push!(interpTimes,sol.ft) numInterpPoints=length(interpTimes) #display(interpTimes) interpValues=nothing if sol isa LightSol interpValues=Vector{Vector{Float64}}(undef, T) #= elseif sol isa HeavySol interpValues=Vector{Array{Taylor0}}(undef, T) =# end for index=1:T interpValues[index]=[] push!(interpValues[index],sol[2][index][1]) #1st element is the init cond (true value) # end for i=2:numInterpPoints-1 # for index=1:T # push!(interpValues[index],evaluateSol(sol,index,interpTimes[i])) # end end # for index=1:T push!(interpValues[index],sol[2][index][end]) #last pt @ft allInterpTimes[index]=interpTimes end #(interpTimes,interpValues) createSol(Val(T),Val(O),allInterpTimes,interpValues,sol.algName,sol.sysName,sol.absQ,sol.totalSteps#= ,sol.stepsaftersimul =#,sol.simulStepCount,sol.evCount,sol.numSteps,sol.ft#= ,sol.simulStepsVals,sol.simulStepsDers,sol.simulStepsVals =#) end function evaluateSimpleSol(sol::Sol,index::Int,t::Float64) for i=2:length(sol[1])#savedTimes after the init time...init time is at index i=1 if sol[1][i]>=t # i-1 is closest lower point return sol[2][index][i-1](t-sol[1][i-1])#taylor evaluation after small elapsed with the point before (i-1) end end end function simpleSolInterpolated(sol::Sol,index::Int,step::Float64,ft::Float64) numPoints=length(sol.savedTimes) interpTimes=[] t=0.0 #later can change to init_time which could be diff than zero push!(interpTimes,t) while t+step<ft t=t+step push!(interpTimes,t) end push!(interpTimes,ft) numInterpPoints=length(interpTimes) #display(interpTimes) interpValues=[] push!(interpValues,sol[2][index][1][0]) #1st element is the init cond (true value) for i=2:numInterpPoints-1 push!(interpValues,evaluateSol(sol,index,interpTimes[i])) end push!(interpValues,sol[2][index][numPoints][0]) #last pt @ft (interpTimes,interpValues) end (sol::Sol)(index::Int,t::Float64) = evaluateSol(sol,index,t) #################################################################################################### function plotElapsed(sol::Sol) numVars=length(sol.savedVars) p1=plot() for k=1:numVars#T p1=plot!(p1,sol.et[k], sol.hv[k],marker=(:xcross),markersize=3,label="x$(k)_hqThrow"#= ,xlims=(877.5,877.8),ylims=(-0.01,0.03) =#) p1=plot!(p1,sol.ets[k], sol.hvs[k],marker=(:star8),markersize=3,title="$(sol.algName)_$(sol.absQ)",label="x$(k)_SimulhqThrow"#= ,xlims=(877.5,877.8),ylims=(-0.01,0.03) =#) p1=plot!(legend=:topleft,xlims=(16.0,20.0),ylims=(0.0,0.5)) end savefig(p1, "trackELAPSED_$(sol.sysName)_$(sol.algName)_$(sol.absQ).png") end
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
6577
#if you want to put a note and lims in the graph function plot_SolDer(sol::Sol{T,O},xvars::Int...;note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64},legend=:true::Bool) where{T,O} p1=plot() #= if sol.algName=="nmliqss1" mycolor=:green stle=:dash else mycolor=:blue end =# if xvars!=() for k in xvars if k==1 stle=:dash sze=2 elseif k==2 stle=:solid sze=4 elseif k==3 stle=:dot sze=3 elseif k==4 stle=:dashdot sze=2 elseif k==5 stle=:dashdotdot sze=2 else sze=1 stle=:solid end # p1=plot!(p1,sol.savedTimes[k], sol.savedVarsQ[k],line=(1,mycolor,:dash),marker=(:star),label="q$k $(sol.algName)") # p1=plot!(p1,sol.savedTimes[k], sol.savedDers[k]#= ,marker=(:circle) =#,markersize=2,label="x$k ",legend=:bottomright) p1=plot!(p1,sol.savedTimes[k], sol.savedDers[k],line=(sze,stle),marker=(:circle),label="dx$k $(sol.numSteps[k])"#= ,legend=:right =#) end else for k=1:T if k==1 mycolor=:red else mycolor=:purple end # p1=plot!(p1,sol.savedTimes[k], sol.savedVarsQ[k],line=(1,mycolor,:dash),marker=(:star),label="q$k $(sol.algName)") p1=plot!(p1,sol.savedTimes[k], sol.savedDers[k],marker=(:circle),markersize=2,label="dx$k $(sol.numSteps[k])"#= ,legend=:false =#) end end if xlims!=(0.0,0.0) && ylims!=(0.0,0.0) p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note", xlims=xlims ,ylims=ylims) elseif xlims!=(0.0,0.0) && ylims==(0.0,0.0) p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note", xlims=xlims #= ,ylims=ylims =#) elseif xlims==(0.0,0.0) && ylims!=(0.0,0.0) p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note"#= , xlims=xlims =#,ylims=ylims) else p1=plot!(p1, title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note",legend=legend) end p1 #savefig(p1, "plot_$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(note)_ft_$(sol.ft)_$(timestamp).png") end function save_SolDer(sol::Sol{T,O},xvars::Int...;note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64},legend=:true::Bool) where{T,O} p1= plot_SolDer(sol,xvars...;note=note,xlims=xlims,ylims=ylims,legend=legend) mydate=now() timestamp=(string(year(mydate),"_",month(mydate),"_",day(mydate),"_",hour(mydate),"_",minute(mydate),"_",second(mydate))) savefig(p1, "plot_$(sol.sysName)_$(sol.algName)_$(xvars)_$(sol.absQ)_$(note)_ftt_$(sol.ft)_$(timestamp).png") end #= #for debug to be deleted later: simultaneous steps plot function save_SimulSol(sol::Sol{T,O},xvars::Int...;note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64}) where{T,O} p1=plot() mydate=now() timestamp=(string(year(mydate),"_",month(mydate),"_",day(mydate),"_",hour(mydate),"_",minute(mydate),"_",second(mydate))) if xvars[1]!=() for k in xvars p1=plot!(p1,sol.savedTimes[k], sol.savedDers[k],marker=(:circle),markersize=2,label="x$k $(sol.numSteps[k])") p1=plot!(p1,sol.simulStepsTimes[k], sol.simulStepsVals[k],marker=(:circle),markersize=4,label="x$k ") end else for k=1:T p1=plot!(p1,sol.savedTimes[k], sol.savedDers[k],marker=(:circle),markersize=2,label="x$k $(sol.numSteps[k])") p1=plot!(p1,sol.simulStepsTimes[k], sol.simulStepsVals[k],marker=(:circle),markersize=4,label="x$k ") end end if xlims!=(0.0,0.0) && ylims!=(0.0,0.0) p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount) \n $note", xlims=xlims ,ylims=ylims) elseif xlims!=(0.0,0.0) && ylims==(0.0,0.0) p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount) \n $note", xlims=xlims #= ,ylims=ylims =#) elseif xlims==(0.0,0.0) && ylims!=(0.0,0.0) p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount) \n $note"#= , xlims=xlims =#,ylims=ylims) else p1=plot!(p1, title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount) \n $note") end savefig(p1, "plot_$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(note)_ft_$(sol.ft)_$(timestamp).png") end function getPlot(sol::Sol{T,O}) where{T,O} p1=plot(title="$(sol.sysName)")#;p2=nothing for k=1:T p1=plot!(p1,sol.savedTimes[k], sol.savedDers[k],marker=(:circle),markersize=2,label="x$k $(sol.numSteps[k]) ") end p1 end function getPlot(sol::Sol{T,O},k::Int) where{T,O} p1=plot!(sol.savedTimes[k], sol.savedDers[k],marker=(:circle),markersize=2,#= title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.simulStepCount) ", =#label="x$index ") end function getPlot!(sol::Sol{T,O}) where{T,O} p1=plot!(title="$(sol.sysName)") if sol.algName=="nmliqss1" mycolor=:red else mycolor=:blue end for k=1:T #p1=plot!(p1,sol.savedTimes[k], sol.savedVarsQ[k],line=(1,mycolor,:dash),label="q$k $(sol.algName)") p1=plot!(p1,sol.savedTimes[k], sol.savedDers[k],line=(1,mycolor),marker=(:circle),markersize=2,label="x$k $(sol.numSteps[k])$(sol.algName)_$(sol.totalSteps)_$(sol.stepsaftersimul)_$(sol.simulStepCount)") end p1 end function getPlot!(sol::Sol{T,O},k::Int) where{T,O} p1=plot!(title="$(sol.sysName)") if sol.algName=="nmliqss1" mycolor=:red;linsty=:dash else mycolor=:blue;linsty=:dot end # p1=plot!(p1,sol.savedTimes[k], sol.savedVarsQ[k],line=(1,mycolor,:dash),marker=(:star),label="q$k $(sol.algName)") p1=plot!(p1,sol.savedTimes[k], sol.savedDers[k],line=(1,mycolor),marker=(:circle),markersize=2,label="x$k $(sol.numSteps[k])$(sol.algName)_$(sol.totalSteps)_$(sol.simulStepCount)") end =# #= function plotSol(sol::Sol{T,O}) where{T,O} numPoints=length(sol.savedTimes) #numVars=length(sol.savedDers) p1=plot() for k=1:T temp = [] for i = 1:numPoints #each point is a taylor push!(temp, sol.savedDers[k][i].coeffs[1]) end display(plot!(p1,sol.savedTimes, temp,marker=(:circle),markersize=3,title="$(sol.algName) _$(sol.absQ)_$(sol.simulStepCount)",label="x$k"#= ,xlims=(877.5,877.8),ylims=(-0.01,0.03) =#)) end println("press enter to exit") readline() end =#
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
7245
function getError(sol::Sol{T,O},index::Int,f::Function)where{T,O} index>T && error("the system contains only $T variables!") numPoints=length(sol.savedTimes[index]) sumTrueSqr=0.0 sumDiffSqr=0.0 relerror=0.0 for i = 1:numPoints-1 #each point is a taylor ts=f(sol.savedTimes[index][i]) sumDiffSqr+=(sol.savedVars[index][i]-ts)*(sol.savedVars[index][i]-ts) sumTrueSqr+=ts*ts end relerror=sqrt(sumDiffSqr/sumTrueSqr) return relerror end function getErrorByRefs(solRef::Vector{Any},solmliqss::Sol{T,O},index::Int)where{T,O} #numVars=length(solmliqss.savedVars) index>T && error("the system contains only $T variables!") numPoints=length(solmliqss.savedTimes[index]) sumTrueSqr=0.0 sumDiffSqr=0.0 relerror=0.0 for i = 1:numPoints-1 #-1 because savedtimes holds init cond at begining ts=solRef[i][index] sumDiffSqr+=(solmliqss.savedVars[index][i]-ts)*(solmliqss.savedVars[index][i]-ts) sumTrueSqr+=ts*ts end relerror=sqrt(sumDiffSqr/sumTrueSqr) return relerror end function getAllErrorsByRefs(solRef::Vector{Any},solmliqss::Sol{T,O})where{T,O} numPoints=length(solmliqss.savedTimes[1]) allErrors=Array{Float64}(undef, T) for index=1:T sumTrueSqr=0.0 sumDiffSqr=0.0 relerror=0.0 for i = 1:numPoints-1 #each point is a taylor ts=solRef[i][index] Ns=getX_fromSavedVars(solmliqss.savedVars,index,i) sumDiffSqr+=(Ns-ts)*(Ns-ts) sumTrueSqr+=ts*ts end relerror=sqrt(sumDiffSqr/sumTrueSqr) allErrors[index]= relerror end return allErrors end @inline function getX_fromSavedVars(savedVars :: Vector{Array{Taylor0}},index::Int,i::Int) return savedVars[index][i].coeffs[1] end @inline function getX_fromSavedVars(savedVars :: Vector{Vector{Float64}},index::Int,i::Int) return savedVars[index][i] end function getAverageErrorByRefs(solRef::Vector{Any},solmliqss::Sol{T,O})where{T,O} numPoints=length(solmliqss.savedTimes[1]) allErrors=0.0 for index=1:T sumTrueSqr=0.0 sumDiffSqr=0.0 relerror=0.0 for i = 1:numPoints-1 #each point is a taylor ts=solRef[i][index] Ns=getX_fromSavedVars(solmliqss.savedVars,index,i) sumDiffSqr+=(Ns-ts)*(Ns-ts) sumTrueSqr+=ts*ts end if abs(sumTrueSqr)>1e-12 relerror=sqrt(sumDiffSqr/sumTrueSqr) else relerror=0.0 end allErrors+= relerror end return allErrors/T end function plotRelativeError(sol::Sol,index::Int,f::Function) numPoints=length(sol.savedTimes) numVars=length(sol.savedVars) if index<=numVars temp = [] tempt = [] for i = 1:numPoints #each point is a taylor ft=f(sol.savedTimes[i]) if ft>1e-12 || ft < -1e-12 push!(temp, abs((sol.savedVars[index][i].coeffs[1]-ft)/ft)) push!(tempt,sol.savedTimes[i]) end end display(plot(tempt, temp,title="RelError:(S-T)/T for x$(index)_$(sol.absQ)",label="$(sol.algName)"#= ,xlims=(80,200),ylims=(0.0,0.0002) =#) ) println("press enter to exit") readline() else error("the system contains only $numVars variables!") end end function saveRelativeError(sol::Sol,index::Int,f::Function) numPoints=length(sol.savedTimes) numVars=length(sol.savedVars) mydate=now() timestamp=(string(year(mydate),"_",month(mydate),"_",day(mydate),"_",hour(mydate),"_",minute(mydate),"_",second(mydate))) if index<=numVars temp = [] tempt = [] for i = 1:numPoints #each point is a taylor ft=f(sol.savedTimes[i]) if ft>1e-12 || ft < -1e-12 push!(temp, abs((sol.savedVars[index][i].coeffs[1]-ft)/ft)) push!(tempt,sol.savedTimes[i]) end end # display(plot!(tempt, temp,title="RelError:(S-T)/T for x$index",label="$(sol.algName)")) p1=plot(tempt, temp,title="RelError:(S-T)/T for x$(index)_$(sol.absQ)",label="$(sol.algName)"#= ,xlims=(80,200),ylims=(0.0,0.0002) =#) savefig(p1, "relError_$(sol.sysName)_$(sol.algName)_$(sol.absQ)_x$(index)_$(timestamp).png") else error("the system contains only $numVars variables!") end end function plotAbsoluteError(sol::Sol,index::Int,f::Function) numPoints=length(sol.savedTimes) numVars=length(sol.savedVars) if index<=numVars temp = [] # tempt = [] for i = 1:numPoints #each point is a taylor ft=f(sol.savedTimes[i]) #if ft>1e-2 || ft < -1e-2 push!(temp, abs((sol.savedVars[index][i].coeffs[1]-ft))) # push!(tempt,sol.savedTimes[i]) # end end #display(plot!(sol.savedTimes, temp,title="AbsError:(S-T) for x$index",label="$(sol.algName)")) display(plot(sol.savedTimes, temp,title="AbsError:(S-T) for x$(index)_$(sol.absQ)",label="$(sol.algName)"#= ,xlims=(80,200),ylims=(0.0,0.0002) =#)) println("press enter to exit") readline() else error("the system contains only $numVars variables!") end end function saveAbsoluteError(sol::Sol,index::Int,f::Function) numPoints=length(sol.savedTimes) numVars=length(sol.savedVars) mydate=now() timestamp=(string(year(mydate),"_",month(mydate),"_",day(mydate),"_",hour(mydate),"_",minute(mydate),"_",second(mydate))) if index<=numVars temp = [] # tempt = [] for i = 1:numPoints #each point is a taylor ft=f(sol.savedTimes[i]) #if ft>1e-2 || ft < -1e-2 push!(temp, abs((sol.savedVars[index][i].coeffs[1]-ft))) # push!(tempt,sol.savedTimes[i]) # end end #display(plot!(sol.savedTimes, temp,title="AbsError:(S-T) for x$index",label="$(sol.algName)")) p1=plot(sol.savedTimes, temp,title="AbsError:(S-T) for x$(index)_$(sol.absQ)",label="$(sol.algName)"#= ,xlims=(80,200),ylims=(0.0,0.0002) =#) savefig(p1, "absError_$(sol.sysName)_$(sol.algName)_$(sol.absQ)_x$(index)_$(timestamp).png") else error("the system contains only $numVars variables!") end end function plotCumulativeSquaredRelativeError(sol::Sol,index::Int,f::Function) numPoints=length(sol.savedTimes) numVars=length(sol.savedVars) sumTrueSqr=0.0 sumDiffSqr=0.0 if index<=numVars temp = [] for i = 1:numPoints #each point is a taylor ft=f(sol.savedTimes[i]) sumDiffSqr+=(sol.savedVars[index][i].coeffs[1]-ft)*(sol.savedVars[index][i].coeffs[1]-ft) sumTrueSqr+=ft*ft push!(temp, sqrt(sumDiffSqr/sumTrueSqr)) end display(plot!(sol.savedTimes, temp,title="Error:sqrt(∑(S-T)^2/∑T^2) for x$index",label="$(sol.algName)")) else error("the system contains only $numVars variables!") end println("press enter to exit") readline() end function plotMSE(sol::Sol,index::Int,f::Function) numPoints=length(sol.savedTimes) numVars=length(sol.savedVars) # sumTrueSqr=0.0 sumDiffSqr=0.0 if index<=numVars temp = [] for i = 1:numPoints #each point is a taylor ft=f(sol.savedTimes[i]) sumDiffSqr+=(sol.savedVars[index][i].coeffs[1]-ft)*(sol.savedVars[index][i].coeffs[1]-ft) # sumTrueSqr+=ft*ft push!(temp, (sumDiffSqr/i)) end display(plot!(sol.savedTimes, temp,title="Error:(∑(S-T)^2/i) for x$index",label="$(sol.algName)")) else error("the system contains only $numVars variables!") end println("press enter to exit") readline() end
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
8967
#plot the sum of variables function plot_SolSum(sol::Sol{T,O},xvars::Int...;interp=0.0001,note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64},legend=:true::Bool) where{T,O} p1=plot() #= if sol.algName=="nmliqss1" mycolor=:green stle=:dash else mycolor=:blue end =# if xvars!=() solInterp=solInterpolated(sol,interp) # for now interpl all sumV=solInterp.savedVars[xvars[1]] sumT=solInterp.savedTimes[xvars[1]]# numPoints=length(sumT) for i=1:numPoints for k=2: length(xvars) sumV[i]+=solInterp.savedVars[xvars[k]][i] end end # p1=plot!(p1,sol.savedTimes[k], sol.savedVarsQ[k],line=(1,mycolor,:dash),marker=(:star),label="q$k $(sol.algName)") # p1=plot!(p1,sol.savedTimes[k], sol.savedVars[k]#= ,marker=(:circle) =#,markersize=2,label="x$k ",legend=:bottomright) p1=plot!(p1,sumT, sumV,marker=(:circle),#= ,legend=:right =#) else println("pick vars to plot their sum") end if xlims!=(0.0,0.0) && ylims!=(0.0,0.0) p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note", xlims=xlims ,ylims=ylims) elseif xlims!=(0.0,0.0) && ylims==(0.0,0.0) p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note", xlims=xlims #= ,ylims=ylims =#) elseif xlims==(0.0,0.0) && ylims!=(0.0,0.0) p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note"#= , xlims=xlims =#,ylims=ylims) else p1=plot!(p1, title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note",legend=legend) end p1 #savefig(p1, "plot_$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(note)_ft_$(sol.ft)_$(timestamp).png") end function plot_Sol(sol::Sol{T,O},xvars::Int...;note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64},legend=:true::Bool) where{T,O} p1=plot() #= if sol.algName=="nmliqss1" mycolor=:green stle=:dash else mycolor=:blue end =# if xvars!=() for k in xvars if k==1 stle=:dash sze=2 elseif k==2 stle=:solid sze=4 elseif k==3 stle=:dot sze=3 elseif k==4 stle=:dashdot sze=2 elseif k==5 stle=:dashdotdot sze=2 else sze=1 stle=:solid end # p1=plot!(p1,sol.savedTimes[k], sol.savedVarsQ[k],line=(1,mycolor,:dash),marker=(:star),label="q$k $(sol.algName)") # p1=plot!(p1,sol.savedTimes[k], sol.savedVars[k]#= ,marker=(:circle) =#,markersize=2,label="x$k ",legend=:bottomright) p1=plot!(p1,sol.savedTimes[k], sol.savedVars[k],line=(sze,stle),marker=(:circle),label="x$k $(sol.numSteps[k])"#= ,legend=:right =#) end else for k=1:T if k==1 mycolor=:red else mycolor=:purple end # p1=plot!(p1,sol.savedTimes[k], sol.savedVarsQ[k],line=(1,mycolor,:dash),marker=(:star),label="q$k $(sol.algName)") p1=plot!(p1,sol.savedTimes[k], sol.savedVars[k],marker=(:circle),markersize=2,label="x$k $(sol.numSteps[k])"#= ,legend=:false =#) end end if xlims!=(0.0,0.0) && ylims!=(0.0,0.0) p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note", xlims=xlims ,ylims=ylims) elseif xlims!=(0.0,0.0) && ylims==(0.0,0.0) p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note", xlims=xlims #= ,ylims=ylims =#) elseif xlims==(0.0,0.0) && ylims!=(0.0,0.0) p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note"#= , xlims=xlims =#,ylims=ylims) else p1=plot!(p1, title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note",legend=legend) end p1 #savefig(p1, "plot_$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(note)_ft_$(sol.ft)_$(timestamp).png") end function save_Sol(sol::Sol{T,O},xvars::Int...;note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64},legend=:true::Bool) where{T,O} p1= plot_Sol(sol,xvars...;note=note,xlims=xlims,ylims=ylims,legend=legend) mydate=now() timestamp=(string(year(mydate),"_",month(mydate),"_",day(mydate),"_",hour(mydate),"_",minute(mydate),"_",second(mydate))) savefig(p1, "plot_$(sol.sysName)_$(sol.algName)_$(xvars)_$(sol.absQ)_$(note)_ft_$(sol.ft)_$(timestamp).png") end function save_SolSum(sol::Sol{T,O},xvars::Int...;interp=0.0001,note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64},legend=:true::Bool) where{T,O} p1= plot_SolSum(sol,xvars...;interp=interp,note=note,xlims=xlims,ylims=ylims,legend=legend) mydate=now() timestamp=(string(year(mydate),"_",month(mydate),"_",day(mydate),"_",hour(mydate),"_",minute(mydate),"_",second(mydate))) savefig(p1, "plot_$(sol.sysName)_$(sol.algName)_$(xvars)_$(sol.absQ)_$(note)_ft_$(sol.ft)_$(timestamp).png") end #for debug to be deleted later: simultaneous steps plot function save_SimulSol(sol::Sol{T,O},xvars::Int...;note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64}) where{T,O} p1=plot() mydate=now() timestamp=(string(year(mydate),"_",month(mydate),"_",day(mydate),"_",hour(mydate),"_",minute(mydate),"_",second(mydate))) if xvars[1]!=() for k in xvars p1=plot!(p1,sol.savedTimes[k], sol.savedVars[k],marker=(:circle),markersize=2,label="x$k $(sol.numSteps[k])") p1=plot!(p1,sol.simulStepsTimes[k], sol.simulStepsVals[k],marker=(:circle),markersize=4,label="x$k ") end else for k=1:T p1=plot!(p1,sol.savedTimes[k], sol.savedVars[k],marker=(:circle),markersize=2,label="x$k $(sol.numSteps[k])") p1=plot!(p1,sol.simulStepsTimes[k], sol.simulStepsVals[k],marker=(:circle),markersize=4,label="x$k ") end end if xlims!=(0.0,0.0) && ylims!=(0.0,0.0) p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount) \n $note", xlims=xlims ,ylims=ylims) elseif xlims!=(0.0,0.0) && ylims==(0.0,0.0) p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount) \n $note", xlims=xlims #= ,ylims=ylims =#) elseif xlims==(0.0,0.0) && ylims!=(0.0,0.0) p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount) \n $note"#= , xlims=xlims =#,ylims=ylims) else p1=plot!(p1, title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount) \n $note") end savefig(p1, "plot_$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(note)_ft_$(sol.ft)_$(timestamp).png") end function getPlot(sol::Sol{T,O}) where{T,O} p1=plot(title="$(sol.sysName)")#;p2=nothing for k=1:T p1=plot!(p1,sol.savedTimes[k], sol.savedVars[k],marker=(:circle),markersize=2,label="x$k $(sol.numSteps[k]) ") end p1 end function getPlot(sol::Sol{T,O},k::Int) where{T,O} p1=plot!(sol.savedTimes[k], sol.savedVars[k],marker=(:circle),markersize=2,#= title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.simulStepCount) ", =#label="x$k ") end function getPlot!(sol::Sol{T,O}) where{T,O} p1=plot!(title="$(sol.sysName)") if sol.algName=="nmliqss1" mycolor=:red else mycolor=:blue end for k=1:T #p1=plot!(p1,sol.savedTimes[k], sol.savedVarsQ[k],line=(1,mycolor,:dash),label="q$k $(sol.algName)") p1=plot!(p1,sol.savedTimes[k], sol.savedVars[k],line=(1,mycolor),marker=(:circle),markersize=2,label="x$k $(sol.numSteps[k])$(sol.algName)_$(sol.totalSteps)_$(sol.stepsaftersimul)_$(sol.simulStepCount)") end p1 end function getPlot!(sol::Sol{T,O},k::Int) where{T,O} p1=plot!(title="$(sol.sysName)") if sol.algName=="nmliqss1" mycolor=:red;linsty=:dash else mycolor=:blue;linsty=:dot end # p1=plot!(p1,sol.savedTimes[k], sol.savedVarsQ[k],line=(1,mycolor,:dash),marker=(:star),label="q$k $(sol.algName)") p1=plot!(p1,sol.savedTimes[k], sol.savedVars[k],line=(1,mycolor),marker=(:circle),markersize=2,label="x$k $(sol.numSteps[k])$(sol.algName)_$(sol.totalSteps)_$(sol.simulStepCount)") end #= function plotSol(sol::Sol{T,O}) where{T,O} numPoints=length(sol.savedTimes) #numVars=length(sol.savedVars) p1=plot() for k=1:T temp = [] for i = 1:numPoints #each point is a taylor push!(temp, sol.savedVars[k][i].coeffs[1]) end display(plot!(p1,sol.savedTimes, temp,marker=(:circle),markersize=3,title="$(sol.algName) _$(sol.absQ)_$(sol.simulStepCount)",label="x$k"#= ,xlims=(877.5,877.8),ylims=(-0.01,0.03) =#)) end println("press enter to exit") readline() end =#
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
10586
function transformFSimplecase(ex)# it s easier and healthier to leave the big case alone in one prewalk (below) when returning the size of the distributed cahce ex=Expr(:call, :createT,ex)# case where rhs of eq is a number needed to change to taylor (in cache) to be used for qss || #case where rhs is q[i]...reutrn cache that contains it cachexpr = Expr(:ref, :cache) # add cache[1] to createT(ex,....) push!(cachexpr.args,1) push!( ex.args, cachexpr) return ex end function transformF(ex)# name to be changed later....i call this funciton in the docs the function that does the transformation cachexpr_lengthtracker = Expr(:mongi)# an expr to track the number of distributed caches prewalk(ex) do x #############################minus sign############################################# if x isa Expr && x.head == :call && x.args[1] == :- && length(x.args) == 3 && !(x.args[2] isa Int) && !(x.args[3] isa Int) #last 2 to avoid changing u[i-1] #MacroTools.isexpr(x, :call) replaces the begining if x.args[2] isa Expr && x.args[2].head == :call && x.args[2].args[1] == :- && length(x.args[2].args) == 3 push!(x.args, x.args[3])# args[4]=c x.args[3] = x.args[2].args[3]# args[3]=b x.args[2] = x.args[2].args[2]# args[2]=a x.args[1] = :subsub push!(cachexpr_lengthtracker.args,:b) #b is anything ...not needed, just to fill vector tracker cachexpr = Expr(:ref, :cache) #prepare cache push!(cachexpr.args,length(cachexpr_lengthtracker.args))#constrcut cache with index cache[1] push!(x.args, cachexpr) elseif x.args[2] isa Expr && x.args[2].head == :call && x.args[2].args[1] == :+ && length(x.args[2].args) == 3 push!(x.args, x.args[3])# args[4]=c x.args[3] = x.args[2].args[3]# args[3]=b x.args[2] = x.args[2].args[2]# args[2]=a x.args[1] = :addsub # £ µ § ~.... push!(cachexpr_lengthtracker.args,:b) cachexpr = Expr(:ref, :cache) push!(cachexpr.args,length(cachexpr_lengthtracker.args)) #cachexpr.args[2] = index[i] push!(x.args, cachexpr) elseif x.args[2] isa Expr && x.args[2].head == :call && x.args[2].args[1] == :* && length(x.args[2].args) == 3 push!(x.args, x.args[3])# args[4]=c x.args[3] = x.args[2].args[3]# args[3]=b x.args[2] = x.args[2].args[2]# args[2]=a x.args[1] = :mulsub # £ µ § ~.... push!(cachexpr_lengthtracker.args,:b) cachexpr1 = Expr(:ref, :cache) push!(cachexpr1.args,length(cachexpr_lengthtracker.args)) push!(x.args, cachexpr1) else x.args[1] = :subT # symbol changed cuz avoid type taylor piracy push!(cachexpr_lengthtracker.args,:b) cachexpr = Expr(:ref, :cache) push!(cachexpr.args,length(cachexpr_lengthtracker.args)) push!(x.args, cachexpr) end elseif x isa Expr && x.head == :call && x.args[1] == :- && length(x.args) == 2 && !(x.args[2] isa Number)#negate x.args[1] = :negateT # symbol changed cuz avoid type taylor piracy push!(cachexpr_lengthtracker.args,:b) cachexpr = Expr(:ref, :cache) push!(cachexpr.args,length(cachexpr_lengthtracker.args)) push!(x.args, cachexpr) ############################### plus sign####################################### elseif x isa Expr && x.head == :call && x.args[1] == :+ && length(x.args) == 3 && typeof(x.args[2])!=Int && typeof(x.args[3])!=Int #last 2 to avoid changing u[i+1] if x.args[2] isa Expr && x.args[2].head == :call && x.args[2].args[1] == :- && length(x.args[2].args) == 3 push!(x.args, x.args[3])# args[4]=c x.args[3] = x.args[2].args[3]# args[3]=b x.args[2] = x.args[2].args[2]# args[2]=a x.args[1] = :subadd#:µ # £ § .... push!(cachexpr_lengthtracker.args,:b) cachexpr = Expr(:ref, :cache) push!(cachexpr.args,length(cachexpr_lengthtracker.args)) #cachexpr.args[2] = index[i] push!(x.args, cachexpr) elseif x.args[2] isa Expr && x.args[2].head == :call && x.args[2].args[1] == :* && length(x.args[2].args) == 3 push!(x.args, x.args[3])# args[4]=c x.args[3] = x.args[2].args[3]# args[3]=b x.args[2] = x.args[2].args[2]# args[2]=a x.args[1] = :muladdT#:µ # £ § .... push!(cachexpr_lengthtracker.args,:b) cachexpr1 = Expr(:ref, :cache) push!(cachexpr1.args,length(cachexpr_lengthtracker.args)) push!(x.args, cachexpr1) else x.args[1] = :addT push!(cachexpr_lengthtracker.args,:b) cachexpr = Expr(:ref, :cache) push!(cachexpr.args,length(cachexpr_lengthtracker.args)) push!(x.args, cachexpr) end elseif x isa Expr && x.head == :call && x.args[1] == :+ && (4 <= length(x.args) <= 9) # special add :i stopped at 9 cuz by testing it was allocating anyway after 9 x.args[1] = :addT push!(cachexpr_lengthtracker.args,:b) cachexpr = Expr(:ref, :cache) push!(cachexpr.args,length(cachexpr_lengthtracker.args)) push!(x.args, cachexpr) ############################### multiply sign####################################### #never happens :# elseif x isa Expr && x.head == :call && x.args[1]==:* && length(x.args)==3 to get addmul or submul elseif x isa Expr && x.head == :call && (x.args[1] == :*) && (3 == length(x.args)) && typeof(x.args[2])!=Int && typeof(x.args[3])!=Int #last 2 to avoid changing u[i*1] x.args[1] = :mulT push!(cachexpr_lengthtracker.args,:b) cachexpr1 = Expr(:ref, :cache) push!(cachexpr1.args,length(cachexpr_lengthtracker.args)) push!(x.args, cachexpr1) elseif x isa Expr && x.head == :call && (x.args[1] == :*) && (4 <= length(x.args) <= 7)# i stopped at 7 cuz by testing it was allocating anyway after 7 x.args[1] = :mulTT push!(cachexpr_lengthtracker.args,:b) cachexpr1 = Expr(:ref, :cache) push!(cachexpr1.args,length(cachexpr_lengthtracker.args)) push!(x.args, cachexpr1) push!(cachexpr_lengthtracker.args,:b) cachexpr2 = Expr(:ref, :cache) #multiply needs two caches push!(cachexpr2.args,length(cachexpr_lengthtracker.args)) push!(x.args, cachexpr2) elseif x isa Expr && x.head == :call && (x.args[1] == :/) && typeof(x.args[2])!=Int && typeof(x.args[3])!=Int #last 2 to avoid changing u[i/1] x.args[1] = :divT push!(cachexpr_lengthtracker.args,:b) cachexpr = Expr(:ref, :cache) push!(cachexpr.args,length(cachexpr_lengthtracker.args)) push!(x.args, cachexpr) elseif x isa Expr && x.head == :call && (x.args[1] == :exp ||x.args[1] == :log ||x.args[1] == :sqrt ||x.args[1] == :abs ) push!(cachexpr_lengthtracker.args,:b) cachexpr = Expr(:ref, :cache) push!(cachexpr.args,length(cachexpr_lengthtracker.args)) push!(x.args, cachexpr) elseif x isa Expr && x.head == :call && (x.args[1] == :^ ) x.args[1] = :powerT # should be like above but for lets keep it now...in test qss.^ caused a problem...fix later push!(cachexpr_lengthtracker.args,:b) cachexpr = Expr(:ref, :cache) push!(cachexpr.args,length(cachexpr_lengthtracker.args)) push!(x.args, cachexpr) elseif x isa Expr && x.head == :call && (x.args[1] == :cos ||x.args[1] == :sin ||x.args[1] == :tan||x.args[1] == :atan ) push!(cachexpr_lengthtracker.args,:b) cachexpr = Expr(:ref, :cache) push!(cachexpr.args,length(cachexpr_lengthtracker.args)) push!(x.args, cachexpr) #second cache push!(cachexpr_lengthtracker.args,:b)#index2 cachexpr2 = Expr(:ref, :cache) push!(cachexpr2.args,length(cachexpr_lengthtracker.args))#construct cache[2] push!(x.args, cachexpr2) elseif x isa Expr && x.head == :call && (x.args[1] == :acos ||x.args[1] == :asin) #did not change symbol here push!(cachexpr_lengthtracker.args,:b) cachexpr = Expr(:ref, :cache) push!(cachexpr.args,length(cachexpr_lengthtracker.args)) push!(x.args, cachexpr) #second cache push!(cachexpr_lengthtracker.args,:b)#index2 cachexpr2 = Expr(:ref, :cache) push!(cachexpr2.args,length(cachexpr_lengthtracker.args))#construct cache[2] push!(x.args, cachexpr2) #third cache push!(cachexpr_lengthtracker.args,:b)#index3 cachexpr2 = Expr(:ref, :cache) push!(cachexpr2.args,length(cachexpr_lengthtracker.args))#construct cache[2] push!(x.args, cachexpr2) elseif false #holder for "myviewing" for next symbol for other functions... end return x # this is the line that actually enables modification of the original expression (prewalk only) end#end prewalk #return ex ########################################************************ ex.args[2]=length(cachexpr_lengthtracker.args)# return the number of caches distributed...later clean the max of all these return ex # end #end if number else prewalk end#end function #this macro is to be deleted : created for testing #= macro changeAST(ex) Base.remove_linenums!(ex) # dump(ex; maxdepth=18) transformF(ex) # dump( ex.args[1]) #= @show ex.args[1]# return return nothing =# esc(ex.args[1])# return end =#
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
7947
# user does not provide solver. default mliqss2 """solve(prob::NLODEProblem{PRTYPE,T,Z,D,CS},tspan::Tuple{Float64, Float64};sparsity::Val{Sparsity}=Val(false)::Float64,saveat=1e-9::Float64::Float64,abstol=1e-4::Float64,reltol=1e-3::Float64,maxErr=Inf::Float64) where {PRTYPE,T,Z,D,CS,Sparsity} dispatches on a specific integrator based on the algorithm provided. After the simulation, the solution is returned as a Solution object. """ function solve(prob::NLODEProblem{PRTYPE,T,Z,D,CS},tspan::Tuple{Float64, Float64};sparsity::Val{Sparsity}=Val(false)::Float64,saveat=1e-9::Float64::Float64,abstol=1e-4::Float64,reltol=1e-3::Float64,maxErr=Inf::Float64) where {PRTYPE,T,Z,D,CS,Sparsity} solve(prob,QSSAlgorithm(Val(:nmliqss),Val(2)),tspan;sparsity=sparsity,saveat=saveat,abstol=abstol,reltol=reltol,maxErr=maxErr) end #main solve interface function solve(prob::NLODEProblem{PRTYPE,T,Z,D,CS},al::QSSAlgorithm{SolverType, OrderType},tspan::Tuple{Float64, Float64};sparsity::Val{Sparsity}=Val(false),saveat=1e-9::Float64,abstol=1e-4::Float64,reltol=1e-3::Float64,maxErr=Inf::Float64) where{PRTYPE,T,Z,D,CS,SolverType,OrderType,Sparsity} custom_Solve(prob,al,Val(Sparsity),tspan[2],saveat,tspan[1],abstol,reltol,maxErr) end #default solve method: this is not to be touched...extension or modification is done through creating another custom_solve with different PRTYPE function custom_Solve(prob::NLODEProblem{PRTYPE,T,Z,D,CS},al::QSSAlgorithm{Solver, Order},::Val{Sparsity},finalTime::Float64,saveat::Float64,initialTime::Float64,abstol::Float64,reltol::Float64,maxErr::Float64) where{PRTYPE,T,Z,D,CS,Solver,Order,Sparsity} # sizehint=floor(Int64, 1.0+(finalTime/saveat)*0.6) commonQSSdata=createCommonData(prob,Val(Order),finalTime,saveat, initialTime,abstol,reltol,maxErr) jac=getClosure(prob.jac)::Function #if in future jac and SD are different datastructures SD=getClosure(prob.SD)::Function if Solver==:qss integrate(al,commonQSSdata,prob,prob.eqs,jac,SD) else liqssdata=createLiqssData(prob,Val(Sparsity),Val(T),Val(Order)) specialLiqssData=createSpecialLiqssData(Val(T)) if VERBOSE println("begin dispatch on liqss algorithm") end #integrate() integrate(al,commonQSSdata,liqssdata,specialLiqssData,prob) integrate(al,commonQSSdata,liqssdata,specialLiqssData,prob,prob.eqs,jac,SD,prob.exactJac) #= if Solver==:nmliqss nmLiQSS_integrate(commonQSSdata,liqssdata,specialLiqssData,prob,prob.eqs,jac,SD,prob.exactJac) elseif Solver==:nliqss nLiQSS_integrate(commonQSSdata,liqssdata,specialLiqssData,prob,prob.eqs,jac,SD,prob.exactJac) elseif Solver==:mliqss mLiQSS_integrate(commonQSSdata,liqssdata,specialLiqssData,prob,prob.eqs,jac,SD,prob.exactJac) elseif Solver==:liqss LiQSS_integrate(commonQSSdata,liqssdata,specialLiqssData,prob,prob.eqs,jac,SD,prob.exactJac) end =# end end function getClosure(jacSD::Function)::Function # function closureJacSD(i::Int) jacSD(i) end return closureJacSD end function getClosure(jacSD::Vector{Vector{Int}})::Function function closureJacSD(i::Int) jacSD[i] end return closureJacSD end #helper methods...not to be touched...extension can be done through creating others via specializing on one PRTYPE or more of the symbols (PRTYPE,T,Z,D,Order) if in the future... ################################################################################################################################################################################# function createCommonData(prob::NLODEProblem{PRTYPE,T,Z,D,CS},::Val{Order},finalTime::Float64,saveat::Float64,initialTime::Float64,abstol::Float64,reltol::Float64,maxErr::Float64)where{PRTYPE,T,Z,D,CS,Order} if VERBOSE println("begin create common data") end quantum = zeros(T) x = Vector{Taylor0}(undef, T) q = Vector{Taylor0}(undef, T) savedTimes=Vector{Vector{Float64}}(undef, T) savedVars = Vector{Vector{Float64}}(undef, T) nextStateTime = zeros(T) nextInputTime = zeros(T) tx = zeros(T) tq = zeros(T) nextEventTime=@MVector zeros(Z)# only Z number of zcf is usually under 100...so use of SA is ok t = Taylor0(zeros(Order + 1), Order) t[1]=1.0 t[0]=initialTime integratorCache=Taylor0(zeros(Order+1),Order) #for integratestate only d=zeros(D) for i=1:D d[i]=prob.discreteVars[i] end for i = 1:T nextInputTime[i]=Inf x[i]=Taylor0(zeros(Order + 1), Order) x[i][0]= getInitCond(prob,i) # x[i][0]= prob.initConditions[i] if to remove saving as func q[i]=Taylor0(zeros(Order+1), Order)#q normally 1order lower than x but since we want f(q) to be a taylor that holds all info (1,2,3), lets have q of same Order and not update last coeff tx[i] = initialTime tq[i] = initialTime savedTimes[i]=Vector{Float64}() savedVars[i]=Vector{Float64}() end taylorOpsCache=Array{Taylor0,1}()# cache= vector of taylor0s of size CS for i=1:CS push!(taylorOpsCache,Taylor0(zeros(Order+1),Order)) end if VERBOSE println("END create common data") end commonQSSdata= CommonQSS_data(quantum,x,q,tx,tq,d,nextStateTime,nextInputTime ,nextEventTime , t, integratorCache,taylorOpsCache,finalTime,saveat, initialTime,abstol,reltol,maxErr,savedTimes,savedVars) end #no sparsity function createLiqssData(prob::NLODEProblem{PRTYPE,T,Z,D,CS},::Val{false},::Val{T},::Val{Order})where{PRTYPE,T,Z,D,CS,Order} if VERBOSE println("begin create Liqss data") end a = Vector{Vector{Float64}}(undef, T) # u=Vector{Vector{MVector{Order,Float64}}}(undef, T) qaux = Vector{MVector{Order,Float64}}(undef, T) dxaux=Vector{MVector{Order,Float64}}(undef, T) olddx = Vector{MVector{Order,Float64}}(undef, T) olddxSpec = Vector{MVector{Order,Float64}}(undef, T) for i=1:T #= temparr=Vector{MVector{Order,Float64}}(undef, T) for j=1:T temparr[j]=zeros(MVector{Order,Float64}) end u[i]=temparr =# a[i]=zeros(T) qaux[i]=zeros(MVector{Order,Float64}) olddx[i]=zeros(MVector{Order,Float64}) dxaux[i]=zeros(MVector{Order,Float64}) olddxSpec[i]=zeros(MVector{Order,Float64}) end if VERBOSE println("END create Liqss data") end liqssdata= LiQSS_data(Val(false),a#= ,u =#,qaux,olddx,dxaux,olddxSpec) end #to be removed if sparsity did not help function createLiqssData(prob::NLODEProblem{PRTYPE,T,Z,D,CS},::Val{true},::Val{T},::Val{Order})where{PRTYPE,T,Z,D,CS,Order} a = Vector{Vector{Float64}}(undef, T) u=Vector{Vector{MVector{Order,Float64}}}(undef, T) qaux = Vector{MVector{Order,Float64}}(undef, T) olddx = Vector{MVector{Order,Float64}}(undef, T) olddxSpec = Vector{MVector{Order,Float64}}(undef, T) jacDim=prob.jacDim #= @timeit "liqsssparse" =# for i=1:T temparr=Vector{MVector{Order,Float64}}(undef, T) for j=1:T temparr[j]=zeros(MVector{Order,Float64}) end u[i]=temparr a[i]=zeros(jacDim(i)) qaux[i]=zeros(MVector{Order,Float64}) olddx[i]=zeros(MVector{Order,Float64}) olddxSpec[i]=zeros(MVector{Order,Float64}) end liqssdata= LiQSS_data(Val(true),a,u,qaux,olddx,olddxSpec) end function createSpecialLiqssData(::Val{T})where{T} cacheA=zeros(MVector{1,Float64}) direction= zeros(T) qminus= zeros(T) buddySimul=zeros(MVector{2,Int}) prevStepVal = zeros(T) specialLiqssData=SpecialLiQSS_data(cacheA,direction,qminus,buddySimul,prevStepVal) end # get init conds for normal vect...getinitcond for fun can be found with qssnlsavedprob file function getInitCond(prob::NLODEContProblem,i::Int) return prob.initConditions[i] end
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
5632
#macro NLodeProblem(odeExprs) function NLodeProblem(odeExprs) Base.remove_linenums!(odeExprs) if VERBOSE println("starting prob parsing...") end probHelper=arrangeProb(odeExprs)# replace symbols and params , extract info about size,symbols,initconds probSize=probHelper.problemSize discSize=probHelper.discreteSize zcSize=probHelper.numZC initConds=probHelper.initConditions # vector symDict=probHelper.symDict du=probHelper.du if length(initConds)==0 #user chose shortcuts...initcond saved in a dict initConds=zeros(probSize)# vector of init conds to be created savedinitConds=probHelper.savedInitCond #init conds already created in a dict for i in savedinitConds if i[1] isa Int #if key (i[1]) is an integer initConds[i[1]]=i[2] else # key is an expression for j=(i[1].args[1]):(i[1].args[2]) initConds[j]=i[2] end end end end # @show odeExprs NLodeProblemFunc(odeExprs,Val(probSize),Val(discSize),Val(zcSize),initConds,du,symDict) #returns prob end struct probHelper #helper struct to return stuff from arrangeProb problemSize::Int discreteSize::Int numZC::Int savedInitCond::Dict{Union{Int,Expr},Float64} initConditions::Vector{Float64} du::Symbol symDict::Dict{Symbol,Expr} end function arrangeProb(x::Expr) # replace symbols and params , extract info about sizes,symbols,initconds param=Dict{Symbol,Union{Float64,Expr}}() symDict=Dict{Symbol,Expr}() stateVarName=:q du=:nothing #default anything problemSize=0 discreteSize=0 numZC=0 savedInitCond=Dict{Union{Int,Expr},Float64}() initConditions=Vector{Float64}() for argI in x.args if argI isa Expr && argI.head == :(=) #&& @capture(argI, y_ = rhs_) y=argI.args[1];rhs=argI.args[2] if y isa Symbol && rhs isa Number #params: fill dict of param param[y]=rhs elseif y isa Symbol && rhs isa Expr && (rhs.head==:call || rhs.head==:ref) #params=epression fill dict of param argI.args[2]=changeVarNames_params(rhs,stateVarName,:nothing,param,symDict) param[y]=argI.args[2] elseif y isa Expr && y.head == :ref && rhs isa Number #initial conds "1st way" u[a]=N or u[a:b]=N... if string(y.args[1])[1] !='d' #prevent the case diffEq du[]=Number stateVarName=y.args[1] #extract var name if du==:nothing du=Symbol(:d,stateVarName) end # construct symbol du if y.args[2] isa Expr && y.args[2].args[1]== :(:) #u[a:b]=N length(y.args[2].args)==3 || error(" use syntax u[a:b]") # not needed savedInitCond[:(($(y.args[2].args[2]),$(y.args[2].args[3])))]=rhs# dict {expr->float} if problemSize < y.args[2].args[3] problemSize=y.args[2].args[3] #largest b determines probSize end elseif y.args[2] isa Int #u[a]=N problemSize+=1 savedInitCond[y.args[2]]=rhs#.args[1] end end elseif y isa Symbol && rhs isa Expr && rhs.head==:vect # cont vars u=[] "2nd way" or discrete vars d=[] if y!=:discrete stateVarName=y du=Symbol(:d,stateVarName) initConditions= convert(Array{Float64,1}, rhs.args) problemSize=length(rhs.args) else discreteSize = length(rhs.args) end elseif y isa Expr && y.head == :ref && (rhs isa Expr && rhs.head !=:vect)#&& rhs.head==:call or ref # a diff equa not in a loop argI.args[2]=changeVarNames_params(rhs,stateVarName,:nothing,param,symDict) elseif y isa Expr && y.head == :ref && rhs isa Symbol if haskey(param, rhs)#symbol is a parameter argI.args[2]=copy(param[rhs]) end end elseif @capture(argI, for var_ in b_:niter_ loopbody__ end) argI.args[2]=changeVarNames_params(loopbody[1],stateVarName,var,param,symDict) elseif argI isa Expr && argI.head==:if numZC+=1 (length(argI.args)!=3 && length(argI.args)!=2) && error("use format if A>0 B else C or if A>0 B") !(argI.args[1] isa Expr && argI.args[1].head==:call && argI.args[1].args[1]==:> && (argI.args[1].args[3]==0||argI.args[1].args[3]==0.0)) && error("use the format 'if a>0: change if a>b to if a-b>0") # !(argI.args[1].args[2] isa Expr) && error("LHS of > must be be an expression!") argI.args[1].args[2]=changeVarNames_params(argI.args[1].args[2],stateVarName,:nothing,param)#zcf # name changes have to be per block if length(argI.args)==2 #user used if a b argI.args[2]=changeVarNames_params(argI.args[2],stateVarName,:nothing,param) #posEv elseif length(argI.args)==3 #user used if a b else c argI.args[2]=changeVarNames_params(argI.args[2],stateVarName,:nothing,param)#posEv argI.args[3]=changeVarNames_params(argI.args[3],stateVarName,:nothing,param)#negEv end end#end cases of argI end#end for argI in args p=probHelper(problemSize,discreteSize,numZC,savedInitCond,initConditions,du,symDict) end#end function
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
17705
#using StaticArrays function minPosRoot(coeff::SVector{2,Float64}, ::Val{1}) # coming from val(1) means coef has x and derx only...size 2 mpr=-1 if coeff[2] == 0 mpr = Inf else mpr = -coeff[1] / coeff[2]; end if mpr < 0 mpr = Inf end # println("mpr inside minPosRoot in utils= ",mpr) return mpr end function minPosRoot(coeff::Taylor0, ::Val{1}) # coming from val(1) means coef has x and derx only...size 2 mpr=-1 if coeff[1] == 0 mpr = Inf else mpr = -coeff[0] / coeff[1]; end if mpr < 0 mpr = Inf end # println("mpr inside minPosRoot in utils= ",mpr) return mpr end function minPosRootv1(coeff::NTuple{3,Float64}) # a=coeff[1];b=coeff[2];c=coeff[3] mpr=-1 #coef1=c, coef2=b, coef3=a if a== 0 || 10000 * abs(a) < abs(b)# coef3 is the coef of t^2 if b == 0 # julia allows to divide by zero and result is Inf ...so no need to check mpr = Inf else mpr = -c / b end if mpr < 0 mpr = Inf end else #double disc; disc = b* b - 4 * a * c#b^2-4ac if disc < 0 # no real roots mpr = Inf else #double sd, r1; sd = sqrt(disc); r1 = (-b + sd) / (2 * a); if r1 > 0 mpr = r1; else mpr = Inf; end r1 = (-b - sd) / (2 * a); if ((r1 > 0) && (r1 < mpr)) mpr = r1; end end end return mpr end function minPosRoot(coeff::SVector{3,Float64}, ::Val{2}) # credit goes to github.com/CIFASIS/qss-solver mpr=-1 a=coeff[3];b=coeff[2];c=coeff[1]; # a is coeff 3 because in taylor representation 1 is var 2 is der 3 is derder if a == 0 || (10000 * abs(a)) < abs(b)# coef3 is the coef of t^2 if b == 0 mpr = Inf else mpr = -c / b #@show mpr end if mpr < 0 mpr = Inf end else #double disc; disc = b * b - 4 * a * c#b^2-4ac if disc < 0 # no real roots mpr = Inf else #double sd, r1; sd = sqrt(disc); r1 = (-b + sd) / (2 * a); if r1 > 0 mpr = r1; else mpr = Inf; end r1 = (-b - sd) / (2 * a); if ((r1 > 0) && (r1 < mpr)) mpr = r1; end end end if DEBUG2 && mpr!=Inf sl=c+mpr*b+a*mpr*mpr @show sl end return mpr end function minPosRoot(coeff::Taylor0, ::Val{2}) # credit goes to github.com/CIFASIS/qss-solver mpr=-1 a=coeff[2];b=coeff[1];c=coeff[0]; # a is coeff 3 because in taylor representation 1 is var 2 is der 3 is derder if a == 0 || (100000 * abs(a)) < abs(b)# coef3 is the coef of t^2 if b == 0 mpr = Inf else mpr = -c / b #@show mpr end if mpr < 0 mpr = Inf end else #double disc; disc = b * b - 4 * a * c#b^2-4ac if disc < 0 # no real roots mpr = Inf else #double sd, r1; sd = sqrt(disc); r1 = (-b + sd) / (2 * a); if r1 > 0 mpr = r1; else mpr = Inf; end r1 = (-b - sd) / (2 * a); if ((r1 > 0) && (r1 < mpr)) mpr = r1; end end end if DEBUG2 && mpr!=Inf sl=c+mpr*b+a*mpr*mpr @show sl end return mpr end function minPosRoot2(coeff::SVector{3,Float64}, ::Val{2}) # ben lauwens mpr=-1 #coef1=c, coef2=b, coef3=a a=coeff[3];b=coeff[2];c=coeff[1] if a == 0 #|| (10000 * abs(coeff[3])) < abs(coeff[2])# coef3 is the coef of t^2 if b == 0 mpr = Inf else mpr = -c / b end if mpr <= 0 mpr = Inf end else #double disc; Δ = 1.0 - 4c*a / (b*b) if Δ < 0.0 mpr=Inf else sq=sqrt(Δ) mpr = -0.5*(1.0+sq)*b/a if mpr<=0 mpr=Inf end mpr2=-0.5*(1.0-sq)*b/a if mpr2>0 && mpr2<mpr mpr=mpr2 end end end return mpr end #= @inline function minPosRoot(coeffs::SVector{4,Float64}, ::Val{3})#where F <: AbstractFloat if coeffs[4] == 0.0 coeffs2=@SVector[coeffs[1],coeffs[2],coeffs[3]] return minPosRoot(coeffs2, Val(2)) end _a = 1.0 / coeffs[4] b, c, d = coeffs[3] * _a, coeffs[2] * _a, coeffs[1] * _a m = b < c ? b : c m = d < m ? d : m m > eps(Float64) && return Inf#typemax(Float64) # Cauchy bound _3 = 1.0 / 3 _9 = 1.0 / 9 SQ3 = sqrt(3.0) xₙ = -b * _3 b²_9 = b * b * _9 yₙ = muladd(muladd(-2, b²_9, c), xₙ, d) #eq to 2R δ² = muladd(-_3, c, b²_9) #eq to Q h² = 4δ² * δ² * δ² Δ = muladd(yₙ, yₙ, -h²) if Δ > 4eps(Float64) # one real root and two complex roots p = yₙ < 0 ? cbrt(0.5 * (-yₙ + √Δ)) : cbrt(0.5 * (-yₙ - √Δ)) q = δ² / p z = xₙ + p + q z > -eps(Float64) ? z : Inf#typemax(Float64) elseif Δ < -4eps(Float64) # three real roots θ = abs(yₙ) < eps(Float64) ? 0.5π * _3 : atan(√abs(Δ) / abs(yₙ)) * _3 # acos(-yₙ / √h²) δ = yₙ < 0 ? √abs(δ²) : -√abs(δ²) z₁ = 2δ * cos(θ) z₂ = muladd(-0.5, z₁, xₙ) z₃ = SQ3 * δ * sin(θ) x₁ = xₙ + z₁ x₂ = z₂ + z₃ x₃ = z₂ - z₃ x = x₁ > -eps(Float64) ? x₁ : Inf# typemax(F) x = x₂ > -eps(Float64) && x₂ < x ? x₂ : x x₃ > -eps(Float64) && x₃ < x ? x₃ : x else # double or triple real roots δ = cbrt(0.5yₙ) x₁ = xₙ + δ x₂ = xₙ - 2δ x = x₁ > -eps(Float64) ? x₁ : Inf#typemax(F) x₂ > -eps(Float64) && x₂ < x ? x₂ : x end end =# function minPosRoot(ZCFun::Taylor0, ::Val{3}) coeffs=@SVector [ZCFun[0],ZCFun[1],ZCFun[2],ZCFun[3]] minPosRoot(coeffs,Val(3)) end @inline function minPosRoot(coeffs::SVector{4,Float64}, ::Val{3})#where F <: AbstractFloat if coeffs[4] == 0.0 coeffs2=@SVector[coeffs[1],coeffs[2],coeffs[3]] return minPosRoot(coeffs2, Val(2)) end _a = 1.0 / coeffs[4] b, c, d = coeffs[3] * _a, coeffs[2] * _a, coeffs[1] * _a m = b < c ? b : c m = d < m ? d : m m > 0.0 && return Inf#typemax(Float64) # Cauchy bound _3 = 1.0 / 3 _9 = 1.0 / 9 SQ3 = sqrt(3.0) xₙ = -b * _3 b²_9 = b * b * _9 yₙ = muladd(muladd(-2, b²_9, c), xₙ, d) #eq to 2R δ² = muladd(-_3, c, b²_9) #eq to Q h² = 4δ² * δ² * δ² Δ = muladd(yₙ, yₙ, -h²) if Δ > 0.0 # one real root and two complex roots p = yₙ < 0 ? cbrt(0.5 * (-yₙ + √Δ)) : cbrt(0.5 * (-yₙ - √Δ)) q = δ² / p z = xₙ + p + q z > 0.0 ? z : Inf#typemax(Float64) elseif Δ < 0.0 # three real roots θ = abs(yₙ) < 0.0 ? 0.5π * _3 : atan(√abs(Δ) / abs(yₙ)) * _3 # acos(-yₙ / √h²) δ = yₙ < 0 ? √abs(δ²) : -√abs(δ²) z₁ = 2δ * cos(θ) z₂ = muladd(-0.5, z₁, xₙ) z₃ = SQ3 * δ * sin(θ) x₁ = xₙ + z₁ x₂ = z₂ + z₃ x₃ = z₂ - z₃ x = x₁ > 0.0 ? x₁ : Inf# typemax(F) x = x₂ > 0.0 && x₂ < x ? x₂ : x x₃ > 0.0 && x₃ < x ? x₃ : x else # double or triple real roots δ = cbrt(0.5yₙ) x₁ = xₙ + δ x₂ = xₙ - 2δ x = x₁ > 0.0 ? x₁ : Inf#typemax(F) x₂ > 0.0 && x₂ < x ? x₂ : x end end ###########later optimize #= @inline function minPosRoot(coeffs::NTuple{3,Float64}, ::Val{2}) _a = 1.0 / coeffs[1] b, c = -0.5coeffs[2] * _a, coeffs[3] * _a Δ = muladd(b, b, -c) # b * b - c if Δ < -4eps() # Complex roots Inf elseif Δ > 4eps() # Real roots if b > eps() c > eps() ? c / (b + sqrt(Δ)) : b + sqrt(Δ) elseif b < -eps() c < eps() ? c / (b - sqrt(Δ)) : Inf else sqrt(-c) end else # Double real root b > -eps() ? b : Inf end end =# #coef=@SVector [-5.144241008311048e7, -8938.3815305787700, -0.2906652780025, 1e-6] #coef=@SVector [17, -239999.2196676244, -2.5768276401549883e-12] #= coef=@SVector [-2.5768276401549883e-12, 23999.2196676244, 0.7] x=minPosRoot(coef, Val(2)) @show x #x=7.23046371232382538e9 sl=coef[1]+x*coef[2]+coef[3]*x*x @show sl =# #coef=@SVector [-5.144241008311048e7, -8938.3815305787700, -0.2906652780025, 1e-6] #= coef=@SVector [1e-6, -0.040323840000000166, -3914.116824448214, 1.021243315770821e8] x=minPosRoot(coef, Val(3)) @show x =# #= function PosRoot(coeff::SVector{3,Float64}, ::Val{2}) # credit goes to github.com/CIFASIS/qss-solver mpr=() #coef1=c, coef2=b, coef3=a if coeff[3] == 0 #|| (10000 * abs(coeff[3])) < abs(coeff[2])# coef3 is the coef of t^2 if coeff[2] != 0 if -coeff[1] / coeff[2]>0 mpr = (-coeff[1] / coeff[2],) end end else #double disc; disc = coeff[2] * coeff[2] - 4 * coeff[3] * coeff[1]#b^2-4ac if disc >0 #double sd, r1; sd = sqrt(disc); r1 = (-coeff[2] + sd) / (2 * coeff[3]); r2 = (-coeff[2] - sd) / (2 * coeff[3]); if ((r1 > 0) && (r2 >0)) mpr = (r1,r2) elseif ((r1 > 0) && (r2 <0)) mpr = (r1,) elseif ((r1 < 0) && (r2 >0)) mpr = (r2,) end end end return mpr end =# #= function PosRoot(coeff::NTuple{3,Float64}) # mpr=() #coef1=c, coef2=b, coef3=a a=coeff[3];b=coeff[2];c=coeff[1] if a == 0 #|| (10000 * abs(coeff[3])) < abs(coeff[2])# coef3 is the coef of t^2 if b != 0 if -c / b>0 mpr = (-c / b,) end end else #double disc; Δ = 1.0 - 4c*a / (b*b) if Δ >0 q = -0.5*(1.0+sign(b)*sqrt(Δ))*b r1 = q / a r2=c / q #@show r1,r2 if ((r1 > 0) && (r2 >0)) mpr = (r1,r2) elseif ((r1 > 0) && (r2 <=0)) mpr = (r1,) elseif ((r1 < 0) && (r2 >0)) mpr = (r2,) end end end return mpr end =# function constructIntrval2(cache::Vector{Vector{Float64}},t1::Float64,t2::Float64) h1=min(t1,t2) h4=max(t1,t2) # res=((0.0,h1),(h4,Inf)) cache[1][1]=0.0;cache[1][2]=h1; cache[2][1]=h4;cache[2][2]=Inf; return nothing end #constructIntrval(tup2::Tuple{},tup::NTuple{2, Float64})=constructIntrval(tup,tup2) #merge has 3 elements function constructIntrval3(cache::Vector{Vector{Float64}},t1::Float64,t2::Float64,t3::Float64) #t1=tup[1];t2=tup[2];t3=tup2[1] t12=min(t1,t2);t21=max(t1,t2) #= if t1<t2 t12=t1;t21=t2 else t12=t2;t21=t1 end =# if t3<t12 # res=((0.0,t3),(t12,t21)) cache[1][1]=0.0;cache[1][2]=t3; cache[2][1]=t12;cache[2][2]=t21; else if t3<t21 # res=((0.0,t12),(t3,t21)) cache[1][1]=0.0;cache[1][2]=t12; cache[2][1]=t3;cache[2][2]=t21; else #res=((0.0,t12),(t21,t3)) cache[1][1]=0.0;cache[1][2]=t12; cache[2][1]=t21;cache[2][2]=t3; end end return nothing end #merge has 4 elements function constructIntrval4(cache::Vector{Vector{Float64}},t1::Float64,t2::Float64,t3::Float64,t4::Float64,) # t1=tup[1];t2=tup[2];t3=tup2[1];t4=tup2[2] h1=min(t1,t2,t3,t4);h4=max(t1,t2,t3,t4) if t1==h1 if t2==h4 # res=((0,t1),(min(t3,t4),max(t3,t4)),(t2,Inf)) cache[1][1]=0.0;cache[1][2]=t1; cache[2][1]=min(t3,t4);cache[2][2]=max(t3,t4); cache[3][1]=t2;cache[3][2]=Inf; elseif t3==h4 #res=((0,t1),(min(t2,t4),max(t2,t4)),(t3,Inf)) cache[1][1]=0.0;cache[1][2]=t1; cache[2][1]=min(t2,t4);cache[2][2]=max(t2,t4); cache[3][1]=t3;cache[3][2]=Inf; else # res=((0,t1),(min(t2,t3),max(t2,t3)),(t4,Inf)) cache[1][1]=0.0;cache[1][2]=t1; cache[2][1]=min(t3,t2);cache[2][2]=max(t3,t2); cache[3][1]=t4;cache[3][2]=Inf; end elseif t2==h1 if t1==h4 #res=((0,t2),(min(t3,t4),max(t3,t4)),(t1,Inf)) cache[1][1]=0.0;cache[1][2]=t2; cache[2][1]=min(t3,t4);cache[2][2]=max(t3,t4); cache[3][1]=t1;cache[3][2]=Inf; elseif t3==h4 #res=((0,t2),(min(t1,t4),max(t1,t4)),(t3,Inf)) cache[1][1]=0.0;cache[1][2]=t2; cache[2][1]=min(t1,t4);cache[2][2]=max(t1,t4); cache[3][1]=t3;cache[3][2]=Inf; else # res=((0,t2),(min(t1,t3),max(t1,t3)),(t4,Inf)) cache[1][1]=0.0;cache[1][2]=t2; cache[2][1]=min(t3,t1);cache[2][2]=max(t3,t1); cache[3][1]=t4;cache[3][2]=Inf; end elseif t3==h1 if t1==h4 #res=((0,t3),(min(t2,t4),max(t2,t4)),(t1,Inf)) cache[1][1]=0.0;cache[1][2]=t3; cache[2][1]=min(t2,t4);cache[2][2]=max(t2,t4); cache[3][1]=t1;cache[3][2]=Inf; elseif t2==h4 #res=((0,t3),(min(t1,t4),max(t1,t4)),(t2,Inf)) cache[1][1]=0.0;cache[1][2]=t3; cache[2][1]=min(t1,t4);cache[2][2]=max(t1,t4); cache[3][1]=t2;cache[3][2]=Inf; else #res=((0,t3),(min(t1,t2),max(t1,t2)),(t4,Inf)) cache[1][1]=0.0;cache[1][2]=t3; cache[2][1]=min(t1,t2);cache[2][2]=max(t1,t2); cache[3][1]=t4;cache[3][2]=Inf; end else if t1==h4 #res=((0,t4),(min(t2,t3),max(t2,t3)),(t1,Inf)) cache[1][1]=0.0;cache[1][2]=t4; cache[2][1]=min(t3,t2);cache[2][2]=max(t3,t2); cache[3][1]=t1;cache[3][2]=Inf; elseif t2==h4 # res=((0,t4),(min(t1,t3),max(t1,t3)),(t2,Inf)) cache[1][1]=0.0;cache[1][2]=t4; cache[2][1]=min(t3,t1);cache[2][2]=max(t3,t1); cache[3][1]=t2;cache[3][2]=Inf; else #res=((0,t4),(min(t1,t2),max(t1,t2)),(t3,Inf)) cache[1][1]=0.0;cache[1][2]=t4; cache[2][1]=min(t1,t2);cache[2][2]=max(t1,t2); cache[3][1]=t3;cache[3][2]=Inf; end end return nothing end #order1 @inline function constructIntrval(cache::Vector{Vector{Float64}},res1::Float64,res2::Float64,res3::Float64,res4::Float64) #= vec1=(1.2,3.3) vec2=() =# if res1<=0.0 && res2<=0.0 && res3<=0.0 && res4<=0.0 #res=((0.0,Inf),) cache[1][1]=0.0;cache[1][2]=Inf; elseif res1>0.0 && res2<=0.0 && res3<=0.0 && res4<=0.0 cache[1][1]=0.0;cache[1][2]=res1; elseif res2>0.0 && res1<=0.0 && res3<=0.0 && res4<=0.0 cache[1][1]=0.0;cache[1][2]=res2; elseif res3>0.0 && res2<=0.0 && res1<=0.0 && res4<=0.0 cache[1][1]=0.0;cache[1][2]=res3; elseif res4>0.0 && res2<=0.0 && res3<=0.0 && res1<=0.0 cache[1][1]=0.0;cache[1][2]=res4; elseif res1>0.0 && res2>0.0 && res3<=0.0 && res4<=0.0 constructIntrval2(cache,res1,res2) elseif res1>0.0 && res3>0.0 && res2<=0.0 && res4<=0.0 constructIntrval2(cache,res1,res3) elseif res1>0.0 && res4>0.0 && res2<=0.0 && res4<=0.0 constructIntrval2(cache,res1,res4) elseif res2>0.0 && res3>0.0 && res1<=0.0 && res4<=0.0 constructIntrval2(cache,res2,res3) elseif res2>0.0 && res4>0.0 && res1<=0.0 && res3<=0.0 constructIntrval2(cache,res2,res4) elseif res3>0.0 && res4>0.0 && res1<=0.0 && res2<=0.0 constructIntrval2(cache,res3,res4) elseif res1>0.0 && res2>0.0 && res3>0.0 && res4<=0.0 constructIntrval3(cache,res1,res2,res3) elseif res1>0.0 && res2>0.0 && res4>0.0 && res3<=0.0 constructIntrval3(cache,res1,res2,res4) elseif res1>0.0 && res3>0.0 && res4>0.0 && res2<=0.0 constructIntrval3(cache,res1,res3,res4) elseif res1<=0.0 && res3>0.0 && res4>0.0 && res2>0.0 constructIntrval3(cache,res2,res3,res4) else constructIntrval4(cache,res1,res2,res3,res4) end return nothing end #order2 bigfloat function constructIntrval(accepted::Vector{Vector{BigFloat}},cacheRoots::Vector{BigFloat}) enterFlag=true foundStart=false #nonzero entry found? acceptedCounter=1 len=length(cacheRoots) for i=1:len if !foundStart && cacheRoots[i]!=0.0 foundStart=true#never execute this code again accepted[acceptedCounter][1]=0.0;accepted[acceptedCounter][2]=cacheRoots[i]; acceptedCounter+=1 continue #use next i end if foundStart if enterFlag if i!=len #not last enterFlag=false #prevent next elemt from constructing cuz already covered with elements accepted[acceptedCounter][1]=cacheRoots[i];accepted[acceptedCounter][2]=cacheRoots[i+1]; acceptedCounter+=1 else #i=len=(12 order2) ..last accepted[acceptedCounter][1]=cacheRoots[i];accepted[acceptedCounter][2]=Inf; acceptedCounter+=1 end else# root where function is exiting enterFlag=true #next root makes function enters acceptable range end end end if !foundStart #never found non zero....ie zero roots accepted[acceptedCounter][1]=0.0;accepted[acceptedCounter][2]=Inf; #acceptedCounter+=1 end end function constructIntrval(accepted::Vector{Vector{Float64}},cacheRoots::Vector{Float64}) enterFlag=true foundStart=false acceptedCounter=1 len=length(cacheRoots) for i=1:len if !foundStart && cacheRoots[i]!=0.0 foundStart=true#never execute this code again accepted[acceptedCounter][1]=0.0;accepted[acceptedCounter][2]=cacheRoots[i]; acceptedCounter+=1 continue end if foundStart if enterFlag if i!=len #not last enterFlag=false #prevent next elemt from constructing cuz already covered with elements accepted[acceptedCounter][1]=cacheRoots[i];accepted[acceptedCounter][2]=cacheRoots[i+1]; acceptedCounter+=1 else #i=len=(12 order2) ..last accepted[acceptedCounter][1]=cacheRoots[i];accepted[acceptedCounter][2]=Inf; acceptedCounter+=1 end else# root where function is exiting enterFlag=true #next root makes function enters acceptable range end end end if !foundStart #never found non zero....ie zero roots accepted[acceptedCounter][1]=0.0;accepted[acceptedCounter][2]=Inf; acceptedCounter+=1 end end
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
11232
#= using StaticArrays function linear(a::Float64, b::Float64) if a == 0.0 res = Inf else res = -b / a if res<=0 res=Inf end end return res end function quadratic(a::Float64, b::Float64, c::Float64) if a == 0.0 res = linear(b,c) else if c == 0.0 res = linear(a,b) else if b == 0.0 r = -c / a if r <= 0.0 res=Inf else res = sqrt(r) end else Δ = 1.0 - 4c*a / (b*b) if Δ < 0.0 res=Inf else q = -0.5*(1.0+sign(b)*sqrt(Δ))*b res = q / a if res<=0 res=Inf end res2=c / q if res2>0 && res2<res res=res2 end end end end end return res end =# #= function cubic1(a::Float64, b::Float64, c::Float64, d::Float64) if isnan(a) @show b,c,d end if a == 0.0 res = quadratic(b,c,d) else if d == 0.0 res = quadratic(a,b,c) else A = b/a B = c/a C = d/a Q = (A^2-3B)/9 R = (2*A^3-9A*B+27C)/54 S = -A/3 if R^2 < Q^3 P = -2*sqrt(Q) ϕ = acos(R/sqrt(Q^3)) res = P*cos(ϕ/3)+S #@show res if res<=0 res=Inf end res2 = P*cos((ϕ+2π)/3)+S #@show res2 if res2>0 && res2 <res res=res2 end res3 = P*cos((ϕ-2π)/3)+S #@show res3 if res3>0 && res3 <res res=res3 end if isnan(res) @show P,R,Q,ϕ,S @show a end else T = -sign(R)*cbrt(abs(R)+sqrt(R^2-Q^3)) U = 0.0 if T != 0.0 U = Q/T end res= 0.5*(T+U) if isnan(res) @show T,R,Q,U @show a end #println("1root= ",res) if res<=0 res=Inf end end end end return res end function cubic2(a::Float64, b::Float64, c::Float64, d::Float64) if a == 0.0 res = quadratic(b,c,d) else if d == 0.0 res = quadratic(a,b,c) else A = b/a B = c/a C = d/a Q = (A^2-3B)/9 R = (2*A^3-9A*B+27C)/54 p=-3*Q q=2*R S = -A/3 if 4p*p*p+27q*q>0 m=sqrt((q*q/4)+p*p*p/27) c=cbrt(-q/2+m) res=c-p/(3c)+S #if <0 Inf else res=Inf end end end return res end function cubic3(a::Float64, b::Float64, c::Float64, d::Float64) if a == 0.0 res = quadratic(b,c,d) else if d == 0.0 res = quadratic(a,b,c) else A = b/a B = c/a C = d/a Q = (A^2-3B)/9 R = (2*A^3-9A*B+27C)/54 p=-3*Q q=2*R S = -A/3 if 4p*p*p+27q*q>0 m=sqrt((q*q/4)+p*p*p/27) res=cbrt(-q/2+m)+cbrt(-q/2-m)+S else res=Inf end end end return res end function cubic4(a::Float64, b::Float64, c::Float64, d::Float64) #Cardano’s method: if a == 0.0 res = quadratic(b,c,d) else if d == 0.0 res = quadratic(a,b,c) else A = b/a B = c/a C = d/a Q = (A^2-3B)/9 R = (2*A^3-9A*B+27C)/54 p=-3*Q q=2*R S = -A/3 if 4p*p*p+27q*q>0 resVect = allrealquadratic(1.0,q,-(p^3)/27) z=resVect[1] # @show resVect α=cbrt(resVect[1]) β=-p/(3α) res=α+β+S if res<=0 res=Inf end α=cbrt(resVect[2]) β=-p/(3α) res2=α+β+S if res2 < res && res2 >0 res=res2 end else res=Inf end end end return res#,res2#,res3 end =# function cubic5(a::Float64, b::Float64, c::Float64, d::Float64) # _a = 1.0 / a b, c, d = b * _a, c * _a, d * _a m = b < c ? b : c m = d < m ? d : m m > 0.0 && return Inf#typemax(Float64) # Cauchy bound _3 = 1.0 / 3 _9 = 1.0 / 9 SQ3 = sqrt(3.0) xₙ = -b * _3 b²_9 = b * b * _9 yₙ = muladd(muladd(-2, b²_9, c), xₙ, d) #eq to 2R δ² = muladd(-_3, c, b²_9) #eq to Q h² = 4δ² * δ² * δ² Δ = muladd(yₙ, yₙ, -h²) if Δ > 0.0 # one real root and two complex roots p = yₙ < 0 ? cbrt(0.5 * (-yₙ + √Δ)) : cbrt(0.5 * (-yₙ - √Δ)) q = δ² / p z = xₙ + p + q z > 0.0 ? z : Inf#typemax(Float64) elseif Δ < 0.0 # three real roots θ = abs(yₙ) < 0.0 ? 0.5π * _3 : atan(√abs(Δ) / abs(yₙ)) * _3 # acos(-yₙ / √h²) δ = yₙ < 0 ? √abs(δ²) : -√abs(δ²) z₁ = 2δ * cos(θ) z₂ = muladd(-0.5, z₁, xₙ) z₃ = SQ3 * δ * sin(θ) x₁ = xₙ + z₁ x₂ = z₂ + z₃ x₃ = z₂ - z₃ x = x₁ > 0.0 ? x₁ : Inf# typemax(Float64) x = x₂ > 0.0 && x₂ < x ? x₂ : x x₃ > 0.0 && x₃ < x ? x₃ : x else # double or triple real roots δ = cbrt(0.5yₙ) x₁ = xₙ + δ x₂ = xₙ - 2δ x = x₁ > 0.0 ? x₁ : Inf#typemax(Float64) x₂ > 0.0 && x₂ < x ? x₂ : x end end #= function cubic55(a::Float64, b::Float64, c::Float64, d::Float64) # _a = 1.0 / a b, c, d = b * _a, c * _a, d * _a m = b < c ? b : c m = d < m ? d : m m > eps(Float64) && return Inf#typemax(Float64) # Cauchy bound _3 = 1.0 / 3 _9 = 1.0 / 9 SQ3 = sqrt(3.0) xₙ = -b * _3 b²_9 = b * b * _9 yₙ = muladd(muladd(-2, b²_9, c), xₙ, d) #eq to 2R δ² = muladd(-_3, c, b²_9) #eq to Q h² = 4δ² * δ² * δ² Δ = muladd(yₙ, yₙ, -h²) if Δ > 4eps(Float64) # one real root and two complex roots p = yₙ < 0 ? cbrt(0.5 * (-yₙ + √Δ)) : cbrt(0.5 * (-yₙ - √Δ)) q = δ² / p z = xₙ + p + q z > -eps(Float64) ? z : Inf#typemax(Float64) elseif Δ < -4eps(Float64) # three real roots θ = abs(yₙ) < eps(Float64) ? 0.5π * _3 : atan(√abs(Δ) / abs(yₙ)) * _3 # acos(-yₙ / √h²) δ = yₙ < 0 ? √abs(δ²) : -√abs(δ²) z₁ = 2δ * cos(θ) z₂ = muladd(-0.5, z₁, xₙ) z₃ = SQ3 * δ * sin(θ) x₁ = xₙ + z₁ x₂ = z₂ + z₃ x₃ = z₂ - z₃ x = x₁ > -eps(Float64) ? x₁ : Inf# typemax(Float64) x = x₂ > -eps(Float64) && x₂ < x ? x₂ : x x₃ > -eps(Float64) && x₃ < x ? x₃ : x else # double or triple real roots δ = cbrt(0.5yₙ) x₁ = xₙ + δ x₂ = xₙ - 2δ x = x₁ > -eps(Float64) ? x₁ : Inf#typemax(Float64) x₂ > -eps(Float64) && x₂ < x ? x₂ : x end end =# #= function cubic6(coeffs::NTuple{4,Float64})# _a = 1.0 / coeffs[4] b, c, d = coeffs[3] * _a, coeffs[2] * _a, coeffs[1] * _a m = b < c ? b : c m = d < m ? d : m m > eps(Float64) && return Inf#typemax(Float64) # Cauchy bound _3 = 1.0 / 3 _9 = 1.0 / 9 SQ3 = sqrt(3.0) xₙ = -b * _3 b²_9 = b * b * _9 yₙ = muladd(muladd(-2, b²_9, c), xₙ, d) #eq to 2R δ² = muladd(-_3, c, b²_9) #eq to Q h² = 4δ² * δ² * δ² Δ = muladd(yₙ, yₙ, -h²) if Δ > 4eps(Float64) # one real root and two complex roots p = yₙ < 0 ? cbrt(0.5 * (-yₙ + √Δ)) : cbrt(0.5 * (-yₙ - √Δ)) q = δ² / p z = xₙ + p + q z > -eps(Float64) ? z : Inf#typemax(Float64) elseif Δ < -4eps(Float64) # three real roots θ = abs(yₙ) < eps(Float64) ? 0.5π * _3 : atan(√abs(Δ) / abs(yₙ)) * _3 # acos(-yₙ / √h²) δ = yₙ < 0 ? √abs(δ²) : -√abs(δ²) z₁ = 2δ * cos(θ) z₂ = muladd(-0.5, z₁, xₙ) z₃ = SQ3 * δ * sin(θ) x₁ = xₙ + z₁ x₂ = z₂ + z₃ x₃ = z₂ - z₃ x = x₁ > -eps(Float64) ? x₁ : Inf# typemax(Float64) x = x₂ > -eps(Float64) && x₂ < x ? x₂ : x x₃ > -eps(Float64) && x₃ < x ? x₃ : x else # double or triple real roots δ = cbrt(0.5yₙ) x₁ = xₙ + δ x₂ = xₙ - 2δ x = x₁ > -eps(Float64) ? x₁ : Inf#typemax(Float64) x₂ > -eps(Float64) && x₂ < x ? x₂ : x end end =# #= function cubic7(coeffs::SVector{4,Float64})# _a = 1.0 / coeffs[4] b, c, d = coeffs[3] * _a, coeffs[2] * _a, coeffs[1] * _a m = b < c ? b : c m = d < m ? d : m m > 0.0 && return Inf#typemax(Float64) # Cauchy bound _3 = 1.0 / 3 _9 = 1.0 / 9 SQ3 = sqrt(3.0) xₙ = -b * _3 b²_9 = b * b * _9 yₙ = muladd(muladd(-2, b²_9, c), xₙ, d) #eq to 2R δ² = muladd(-_3, c, b²_9) #eq to Q h² = 4δ² * δ² * δ² Δ = muladd(yₙ, yₙ, -h²) if Δ > 0.0 # one real root and two complex roots p = yₙ < 0 ? cbrt(0.5 * (-yₙ + √Δ)) : cbrt(0.5 * (-yₙ - √Δ)) q = δ² / p z = xₙ + p + q z > 0.0 ? z : Inf#typemax(Float64) elseif Δ < 0.0 # three real roots θ = abs(yₙ) < 0.0 ? 0.5π * _3 : atan(√abs(Δ) / abs(yₙ)) * _3 # acos(-yₙ / √h²) δ = yₙ < 0 ? √abs(δ²) : -√abs(δ²) z₁ = 2δ * cos(θ) z₂ = muladd(-0.5, z₁, xₙ) z₃ = SQ3 * δ * sin(θ) x₁ = xₙ + z₁ x₂ = z₂ + z₃ x₃ = z₂ - z₃ x = x₁ > 0.0 ? x₁ : Inf# typemax(Float64) x = x₂ > 0.0 && x₂ < x ? x₂ : x x₃ > 0.0 && x₃ < x ? x₃ : x else # double or triple real roots δ = cbrt(0.5yₙ) x₁ = xₙ + δ x₂ = xₙ - 2δ x = x₁ > 0.0 ? x₁ : Inf#typemax(Float64) x₂ > 0.0 && x₂ < x ? x₂ : x end end =# #= d=1e-6 #= a=-5.144241008311048e7 b=-8938.381530578772 c=-0.2906652780025244 =# c=-0.040323840000000166 b=-3914.116824448214 a=1.021243315770821e8 @show cubic1(a,b,c,d)#-0.8186606842427812 @show cubic2(a,b,c,d) #Inf @show cubic3(a,b,c,d) #2.515556238254017 @show cubic4(a,b,c,d) # 2.5155562382540193 @show cubic5(a,b,c,d)#2.515556238254016 coeffs2=NTuple{4,Float64}((d,c,b,a)) coeffs3=@SVector [d,c,b,a] @show cubic7(coeffs3) @show cubic6(coeffs2) =#
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
8513
@inline function smallest(args::NTuple{N,F}) where {N, F <: Float64} @inbounds m = args[1] for i in 2:N @inbounds arg = args[i] m = arg < m ? arg : m end m end @inline function horner(x::F, coeffs::NTuple{N,F}) where {N, F <: Float64} @inbounds v = coeffs[1] for i in 2:N @inbounds coeff = coeffs[i] v = muladd(x, v, coeff) end v end @inline function horner2(x::F, y::F, coeffs::NTuple{N,F}) where {N, F <: Float64} @inbounds v = coeffs[1] w = v for i in 2:N @inbounds coeff = coeffs[i] v = muladd(x, v, coeff) w = muladd(y, w, coeff) end v, w end @inline function hornerd(x::F, coeffs::NTuple{N,F}) where {N, F <: Float64} @inbounds v = coeffs[1] d = zero(F) for i in 2:N @inbounds coeff = coeffs[i] d = muladd(x, d, v) v = muladd(x, v, coeff) end v, d end @inline function intervalhorner(low::F, high::F, coeffs::NTuple{N,F}) where {N, F <: Float64} @inbounds colow = coeffs[1] cohigh = colow if low < zero(F) for i in 2:N @inbounds coeff = coeffs[i] colow, cohigh = if colow > zero(F) muladd(low, cohigh, coeff), muladd(high, colow, coeff) elseif cohigh < zero(F) muladd(high, cohigh, coeff), muladd(low, colow, coeff) else muladd(low, cohigh, coeff), muladd(low, colow, coeff) end end else for i in 2:N @inbounds coeff = coeffs[i] colow, cohigh = if colow > zero(F) muladd(low, colow, coeff), muladd(high, cohigh, coeff) elseif cohigh < zero(F) muladd(high, colow, coeff), muladd(low, cohigh, coeff) else muladd(high, colow, coeff), muladd(high, cohigh, coeff) end end end colow, cohigh end @inline function posintervalhorner(low::F, high::F, coeffs::NTuple{N,F}) where {N, F <: Float64} @inbounds colow = coeffs[1] cohigh = colow for i in 2:N @inbounds coeff = coeffs[i] colow, cohigh = if colow > zero(F) muladd(low, colow, coeff), muladd(high, cohigh, coeff) elseif cohigh < zero(F) muladd(high, colow, coeff), muladd(low, cohigh, coeff) else muladd(high, colow, coeff), muladd(high, cohigh, coeff) end end colow, cohigh end #function allrealrootintervalnewtonregulafalsi(coeffs::NTuple{N,F}, res::Ptr{F}, doms::Ptr{NTuple{2,F}}) where {N, F <: Float64} function allrealrootintervalnewtonregulafalsi(coeffs::NTuple{N,F}, res::Ptr{F}, doms::Ptr{NTuple{2,F}}) where {N, F <: Float64} if N == 1 return 0 elseif N == 2 #println("fix setIndex Ptr error") @inbounds res[1] = -coeffs[2] / coeffs[1] return 1 end @inbounds _coeff1 = inv(coeffs[1]) poly = ntuple(N) do i @inbounds _coeff1 * coeffs[i] end poly′ = ntuple(N - 1) do i @inbounds (N-i) * poly[i] end mm = zero(F) MM = zero(F) s = -one(F) for i in 2:N @inbounds coeff = poly[i] if coeff < MM; MM = coeff end _coeff = s * coeff if _coeff < mm; mm = _coeff end s = -s end if mm == zero(F) && MM == zero(F) return 0 end index = 0 domlow, domhigh = if mm < zero(F) if MM < zero(F) index = 1 unsafe_store!(doms, (zero(F), one(F) - MM), 1) end mm - one(F), zero(F) else zero(F), one(F) - MM end counter = 0 while true #@show domlow domhigh mid = 0.5(domlow + domhigh) comid = horner(mid, poly) codom′low, codom′high = intervalhorner(domlow, domhigh, poly′) #@show mid comid codom′low codom′high if codom′low < zero(F) < codom′high leftlow, lefthigh, rightlow, righthigh = if comid < zero(F) domlow, mid - comid / codom′low, mid - comid / codom′high, domhigh else domlow, mid - comid / codom′high, mid - comid / codom′low, domhigh end #@show leftlow lefthigh rightlow righthigh if leftlow < lefthigh if rightlow < righthigh index += 1 unsafe_store!(doms, (rightlow, righthigh), index) end domlow, domhigh = leftlow, lefthigh continue elseif rightlow < righthigh domlow, domhigh = rightlow, righthigh continue end else codomlow, codomhigh = horner2(domlow, domhigh, poly) #@show domlow domhigh codomlow codomhigh if codomlow * codomhigh < zero(F) while true comid, comid′ = hornerd(mid, poly) delta = comid / comid′ #@show mid comid comid′ newmid = mid - delta if abs(delta) < 1.0e-15abs(mid) counter += 1 unsafe_store!(res, newmid, counter) break elseif domlow < newmid < domhigh mid = newmid else if comid * codomlow < zero(F) domhigh, codomhigh = mid, comid else domlow, codomlow = mid, comid end mid = (domlow*codomhigh - domhigh*codomlow) / (codomhigh - codomlow) # regula falsi end end end end if index == 0 || counter == N-1 break end domlow, domhigh = unsafe_load(doms, index) index -= 1 end return counter end function smallestpositiverootintervalnewtonregulafalsi(coeffs::NTuple{N,F}, doms::Ptr{NTuple{2,F}}) where {N, F <: AbstractFloat} if N == 1 return typemax(F) elseif N == 2 @inbounds ret = -coeffs[2] / coeffs[1] if ret < zero(F) return typemax(F) else return ret end end @inbounds _coeff1 = inv(coeffs[1]) poly = ntuple(N) do i @inbounds _coeff1 * coeffs[i] end poly′ = ntuple(N - 1) do i @inbounds (N-i) * poly[i] end MM = smallest(poly) if MM > zero(F) return typemax(F) end domlow, domhigh = zero(F), one(F) - MM index = 0 while true #@show domlow domhigh mid = 0.5(domlow + domhigh) comid = horner(mid, poly) codom′low, codom′high = posintervalhorner(domlow, domhigh, poly′) #@show comid codom′low codom′high if codom′low < zero(F) < codom′high leftlow, lefthigh, rightlow, righthigh = if comid < zero(F) domlow, mid - comid / codom′low, mid - comid / codom′high, domhigh else domlow, mid - comid / codom′high, mid - comid / codom′low, domhigh end #@show leftlow lefthigh rightlow righthigh if leftlow < lefthigh if rightlow < righthigh index += 1 unsafe_store!(doms, (rightlow, righthigh), index) end domlow, domhigh = leftlow, lefthigh continue elseif rightlow < righthigh domlow, domhigh = rightlow, righthigh continue end else codomlow, codomhigh = horner2(domlow, domhigh, poly) #@show domlow domhigh codomlow codomhigh if codomlow * codomhigh < zero(F) while true comid, comid′ = hornerd(mid, poly) delta = comid / comid′ newmid = mid - delta if abs(delta) < 1.0e-8mid return newmid elseif domlow < newmid < domhigh mid = newmid else if comid * codomlow < zero(F) domhigh, codomhigh = mid, comid else domlow, codomlow = mid, comid end mid = (domlow*codomhigh - domhigh*codomlow) / (codomhigh - codomlow) # regula falsi end end end end if index == 0 break end domlow, domhigh = unsafe_load(doms, index) index -= 1 end return typemax(F) end a,b,c,d,e,f,g=2.4794107580075693e12, 1.228418015847665e15, -6.091596024738817e15, -1.5165486073419932e18, -4.545138347948389e12, -6.054155392961131e6, -3.024053636764291 coefi=NTuple{7,Float64}((2.4794107580075693e12, 1.228418015847665e15, -6.091596024738817e15, -1.5165486073419932e18, -4.545138347948389e12, -6.054155392961131e6, -3.024053636764291)) #coefi=NTuple{7,Float64}((Float64(a), Float64(b), Float64(c), Float64(d), Float64(e), Float64(f), Float64(g))) #coefi=NTuple{7,Float64}((Float64(2.4855534831418154e12), Float64(1.2375936757103965e15), Float64(-1.1620693333574219e9), Float64(-1.21270658290325e12), Float64(-4.129153524641228e7), Float64(-80.08000016083042), Float64(-4.0000000000000105e-5))) #pp=pointer(Vector{NTuple{2,Float64}}(undef, 7)) #respp = pointer(Vector{Float64}(undef, 6)) pp=pointer(Vector{NTuple{2,Float64}}(undef, 7)) respp = pointer(Vector{Float64}(undef, 6)) unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6) #= allrealrootintervalnewtonregulafalsi(coefi,respp,pp) resi1,resi2,resi3,resi4,resi5,resi6=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6) for h in(resi1,resi2,resi3,resi4,resi5,resi6) ff(x)=coefi[1]*x^6+coefi[2]*x^5+coefi[3]*x^4+coefi[4]*x^3+coefi[5]*x^2+coefi[6]*x+coefi[7] @show h @show ff(h) end =# h=smallestpositiverootintervalnewtonregulafalsi(coefi,pp) ff(x)=coefi[1]*x^6+coefi[2]*x^5+coefi[3]*x^4+coefi[4]*x^3+coefi[5]*x^2+coefi[6]*x+coefi[7] @show h @show ff(h)
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
14450
#using BenchmarkTools @inline function smallest(args::NTuple{N,F}) where {N, F <: AbstractFloat} @inbounds m = args[1] for i in 2:N @inbounds arg = args[i] m = arg < m ? arg : m end m end @inline function horner(x::F, coeffs::NTuple{N,F}) where {N, F <: AbstractFloat} @inbounds v = coeffs[1] for i in 2:N @inbounds coeff = coeffs[i] v = muladd(x, v, coeff) end v end @inline function horner2(x::F, y::F, coeffs::NTuple{N,F}) where {N, F <: AbstractFloat} @inbounds v = coeffs[1] w = v for i in 2:N @inbounds coeff = coeffs[i] v = muladd(x, v, coeff) w = muladd(y, w, coeff) end v, w end @inline function hornerd(x::F, coeffs::NTuple{N,F}) where {N, F <: AbstractFloat} @inbounds v = coeffs[1] d = zero(F) for i in 2:N @inbounds coeff = coeffs[i] d = muladd(x, d, v) v = muladd(x, v, coeff) end v, d end @inline function intervalhorner(low::F, high::F, coeffs::NTuple{N,F}) where {N, F <: AbstractFloat} @inbounds colow = coeffs[1] cohigh = colow if low < zero(F) for i in 2:N @inbounds coeff = coeffs[i] colow, cohigh = if colow > zero(F) muladd(low, cohigh, coeff), muladd(high, colow, coeff) elseif cohigh < zero(F) muladd(high, cohigh, coeff), muladd(low, colow, coeff) else muladd(low, cohigh, coeff), muladd(low, colow, coeff) end end else for i in 2:N @inbounds coeff = coeffs[i] colow, cohigh = if colow > zero(F) muladd(low, colow, coeff), muladd(high, cohigh, coeff) elseif cohigh < zero(F) muladd(high, colow, coeff), muladd(low, cohigh, coeff) else muladd(high, colow, coeff), muladd(high, cohigh, coeff) end end end colow, cohigh end @inline function posintervalhorner(low::F, high::F, coeffs::NTuple{N,F}) where {N, F <: AbstractFloat} @inbounds colow = coeffs[1] cohigh = colow for i in 2:N @inbounds coeff = coeffs[i] colow, cohigh = if colow > zero(F) muladd(low, colow, coeff), muladd(high, cohigh, coeff) elseif cohigh < zero(F) muladd(high, colow, coeff), muladd(low, cohigh, coeff) else muladd(high, colow, coeff), muladd(high, cohigh, coeff) end end colow, cohigh end function smallestpositiverootintervalnewtonregulafalsi(coeffs::NTuple{N,F}, doms::Ptr{NTuple{2,F}}) where {N, F <: AbstractFloat} if N == 1 return typemax(F) elseif N == 2 @inbounds ret = -coeffs[2] / coeffs[1] if ret < zero(F) return typemax(F) else return ret end end @inbounds _coeff1 = inv(coeffs[1]) poly = ntuple(N) do i @inbounds _coeff1 * coeffs[i] end poly′ = ntuple(N - 1) do i @inbounds (N-i) * poly[i] end MM = smallest(poly) if MM > zero(F) return typemax(F) end domlow, domhigh = zero(F), one(F) - MM index = 0 while true #@show domlow domhigh mid = 0.5(domlow + domhigh) comid = horner(mid, poly) codom′low, codom′high = posintervalhorner(domlow, domhigh, poly′) #@show comid codom′low codom′high if codom′low < zero(F) < codom′high leftlow, lefthigh, rightlow, righthigh = if comid < zero(F) domlow, mid - comid / codom′low, mid - comid / codom′high, domhigh else domlow, mid - comid / codom′high, mid - comid / codom′low, domhigh end #@show leftlow lefthigh rightlow righthigh if leftlow < lefthigh if rightlow < righthigh index += 1 unsafe_store!(doms, (rightlow, righthigh), index) end domlow, domhigh = leftlow, lefthigh continue elseif rightlow < righthigh domlow, domhigh = rightlow, righthigh continue end else codomlow, codomhigh = horner2(domlow, domhigh, poly) #@show domlow domhigh codomlow codomhigh if codomlow * codomhigh < zero(F) while true comid, comid′ = hornerd(mid, poly) delta = comid / comid′ newmid = mid - delta if abs(delta) < 1.0e-8mid return newmid elseif domlow < newmid < domhigh mid = newmid else if comid * codomlow < zero(F) domhigh, codomhigh = mid, comid else domlow, codomlow = mid, comid end mid = (domlow*codomhigh - domhigh*codomlow) / (codomhigh - codomlow) # regula falsi end end end end if index == 0 break end domlow, domhigh = unsafe_load(doms, index) index -= 1 end return typemax(F) end function allrealrootintervalnewtonregulafalsi(coeffs::NTuple{N,F}, res::Ptr{F}, doms::Ptr{NTuple{2,F}}) where {N, F <: AbstractFloat} if N == 1 unsafe_store!(res, typemax(F), 1) return 1#typemax(F) elseif N == 2 if coeffs[1]!=zero(F) @inbounds ret = -coeffs[2] / coeffs[1] unsafe_store!(res, ret, 1) return 1#ret else unsafe_store!(res, typemax(F), 1) return 1#typemax(F) end end if coeffs[1]==0.0 #abs(coeffs[1])<1e-25 nCoef=coeffs[2:end] #Base.GC.enable(false) ret=allrealrootintervalnewtonregulafalsi(nCoef, res, doms) #Base.GC.enable(true) return ret end @inbounds _coeff1 = inv(coeffs[1]) poly = ntuple(N) do i @inbounds _coeff1 * coeffs[i] end poly′ = ntuple(N - 1) do i @inbounds (N-i) * poly[i] end mm = zero(F) MM = zero(F) s = -one(F) for i in 2:N @inbounds coeff = poly[i] if coeff < MM; MM = coeff end _coeff = s * coeff if _coeff < mm; mm = _coeff end s = -s end if mm == zero(F) && MM == zero(F) return 0 end index = 0 domlow, domhigh = if mm < zero(F) if MM < zero(F) index = 1 unsafe_store!(doms, (zero(F), one(F) - MM), 1) end mm - one(F), zero(F) else zero(F), one(F) - MM end counter = 0 while true #@show domlow domhigh mid = 0.5(domlow + domhigh) comid = horner(mid, poly) codom′low, codom′high = intervalhorner(domlow, domhigh, poly′) #@show mid comid codom′low codom′high if codom′low < zero(F) < codom′high leftlow, lefthigh, rightlow, righthigh = if comid < zero(F) domlow, mid - comid / codom′low, mid - comid / codom′high, domhigh else domlow, mid - comid / codom′high, mid - comid / codom′low, domhigh end #@show leftlow lefthigh rightlow righthigh if leftlow < lefthigh if rightlow < righthigh index += 1 unsafe_store!(doms, (rightlow, righthigh), index) end domlow, domhigh = leftlow, lefthigh continue elseif rightlow < righthigh domlow, domhigh = rightlow, righthigh continue end else codomlow, codomhigh = horner2(domlow, domhigh, poly) #@show domlow domhigh codomlow codomhigh if codomlow * codomhigh < zero(F) while true comid, comid′ = hornerd(mid, poly) delta = comid / comid′ #@show mid comid comid′ newmid = mid - delta if abs(delta) < 1.0e-14abs(mid) counter += 1 unsafe_store!(res, newmid, counter) break elseif domlow < newmid < domhigh mid = newmid else if comid * codomlow < zero(F) domhigh, codomhigh = mid, comid else domlow, codomlow = mid, comid end mid = (domlow*codomhigh - domhigh*codomlow) / (codomhigh - codomlow) # regula falsi end end end end if index == 0 || counter == N-1 break end domlow, domhigh = unsafe_load(doms, index) index -= 1 end return counter end function classicRoot(coeff::NTuple{3,Float64}) # credit goes to github.com/CIFASIS/qss-solver mpr=(-1.0,-1.0) # a=coeff[1];b=coeff[2];c=coeff[3] if a == 0.0 #|| (10000 * abs(a)) < abs(b)# coef3 is the coef of t^2 if b != 0.0 if -c / b>0.0 mpr = (-c / b,-1.0) end end else #double disc; disc = b * b - 4.0 * a * c#b^2-4ac if disc > 0.0 # no real roots #double sd, r1; sd = sqrt(disc); r1 = (-b + sd) / (2.0 * a); r2 = (-b - sd) / (2.0 * a); mpr = (r1,r2) elseif disc == 0.0 r1 = (-b ) / (2.0 * a); mpr = (r1,-1.0) end end return mpr end function quadRootv2(coeff::NTuple{3,Float64}) # mpr=(-1.0,-1.0) #size 2 to use mpr[2] in quantizer a=coeff[1];b=coeff[2];c=coeff[3] if a == 0.0 || (1e7 * abs(a)) < abs(b)# coef3 is the coef of t^2 if b != 0.0 if 0<-c / b<1e7 # neglecting a small 'a' then having a large h would cause an error 'a*h*h' because large mpr = (-c / b,-1.0) end end elseif b==0.0 if -c/a>0 mpr = (sqrt(-c / a),-1.0) end elseif c==0.0 mpr=(-1.0,-b/a) else #double disc; Δ = 1.0 - 4.0*c*a / (b*b) if Δ >0.0 #= q = -0.5*(1.0+sign(b)*sqrt(Δ))*b r1 = q / a r2=c / q =# sq=sqrt(Δ) #@show sq r1=-0.5*(1.0+sq)*b/a r2=-0.5*(1.0-sq)*b/a mpr = (r1,r2) #@show mpr elseif Δ ==0.0 r1=-0.5*b/a mpr = (r1,r1-1e-12) end end return mpr end function mprv2(coeff::NTuple{3,Float64}) # mpr=Inf a=coeff[1];b=coeff[2];c=coeff[3] if a == 0.0 #|| (10000 * abs(a)) < abs(b)# coef3 is the coef of t^2 if b != 0.0 if -c / b>0.0 mpr = -c / b end end elseif b==0.0 if -c/a>0 mpr = sqrt(-c / a) end elseif c==0.0 if -b/a>0.0 mpr = -b/a end else #double disc; Δ = 1.0 - 4.0*c*a / (b*b) if Δ >0.0 #= q = -0.5*(1.0+sign(b)*sqrt(Δ))*b r1 = q / a r2=c / q =# sq=sqrt(Δ) r1=-0.5*(1.0+sq)*b/a if r1 > 0 mpr = r1; end r1=-0.5*(1.0-sq)*b/a if ((r1 > 0) && (r1 < mpr)) mpr = r1; end elseif Δ ==0.0 r1=-0.5*b/a if r1 > 0 mpr = r1; end end end return mpr end #= coef=NTuple{3,Float64}( (-54.5, 676862.94717592, 0.015584725741558765)) x=quadRootv2(coef) @show x =# #= sl=coef[3]+x*coef[2]+coef[1]*x*x @show sl =# #= coef=NTuple{3,Float64}((-2.5768276401549883e-12, -239999.2196676244,1735305783508325)) x=quadRootv2(coef) @show x sl=coef[3]+x*coef[2]+coef[1]*x*x @show sl =# # 1735305783508325, -239999.2196676244, -2.5768276401549883 #= coeffs2=NTuple{3,Float64}((0.7,23999.2196676244,-2.5768276401549883e-12)) #coeffs2=NTuple{3,Float64}((-2.5768276401549883e-12,-239999.2196676244,17)) #coeffs2=NTuple{3,Float64}((14.691504647354595,-747452.6968034876,1.0e-6)) function iter(res1::Ptr{Float64}, pp::Ptr{NTuple{2,Float64}},coeffs2::NTuple{3,Float64}) #coeffs2=NTuple{3,Float64}((1.0, -2.0, -1.06)) pp=pointer(Vector{NTuple{2,Float64}}(undef, 7)) res1 = pointer(Vector{Float64}(undef, 2)) unsafe_store!(res1, -1.0, 1);unsafe_store!(res1, -1.0, 2) allrealrootintervalnewtonregulafalsi(coeffs2,res1,pp) resTup=(unsafe_load(res1,1),unsafe_load(res1,2)) #@show resTup resfilterd=filter((x) -> x >0.0 , resTup) # display(resfilterd) end function anal1(coeffs2::NTuple{3,Float64}) #coeffs2=NTuple{3,Float64}((1.0, -2.0, -1.06)) classicRoot(coeffs2) end function anal2(coeffs2::NTuple{3,Float64}) #coeffs2=NTuple{3,Float64}((1.0, -2.0, -1.06)) quadRootv2(coeffs2) end pp=pointer(Vector{NTuple{2,Float64}}(undef, 7)) res1 = pointer(Vector{Float64}(undef, 2)) @show iter(res1,pp,coeffs2) @show anal1(coeffs2) @show anal2(coeffs2) x= smallestpositiverootintervalnewtonregulafalsi(coeffs2,pp) @show x sl=coeffs2[3]+x*coeffs2[2]+coeffs2[1]*x*x @show sl =# #= @btime iter(res1,pp) @btime anal1() @btime anal2() =# #= coeffs=NTuple{3,Float64}((29160.956861496, 67.56376290717117, 0.014452560693316113)) #coeffs2=NTuple{3,Float64}((201011.0777843986, 106.4755863000737, 0.014452560693316113)) coeffs2=NTuple{4,Float64}((1.021243315770821e8, -3914.116824448214, -0.040323840000000166,1e-6)) pp=pointer(Vector{NTuple{2,Float64}}(undef, 11)) res1 = pointer(Vector{Float64}(undef, 3)) res2 = pointer(Vector{Float64}(undef, 3)) =# #= count=allrealrootintervalnewtonregulafalsi(coeffs2,res2,pp) @show count resTup2=(unsafe_load(res2,1),unsafe_load(res2,2),unsafe_load(res2,3)) @show resTup2 resfilterd2=filter((x) -> x >0.0 , resTup2) display(resfilterd2) =# #coefi=NTuple{7,Float64}((2.4855534831418154e12, 1.2375936757103965e15, -1.1620693333574219e9, -1.21270658290325e12, -4.129153524641228e7, -80.08000016083042, -4.0000000000000105e-5)) #coefi=NTuple{7,Float64}((2.4794107580075693e12, 1.228418015847665e15, -6.091596024738817e15, -1.5165486073419932e18, -4.545138347948389e12, -6.054155392961131e6, -3.024053636764291)) #= coefi=NTuple{7,Float64}((-2.5668078295588949092296481e+16, 1.0474193043858423245087585e+18,1.7114669426922051413515583e+13, -2.8508122708869649897226691e+14, -8.5524376124873223589469262e+08, -1140.3250641304001419575054, -0.00057016254603761695740615778)) pp=pointer(Vector{NTuple{2,Float64}}(undef, 7)) respp = pointer(Vector{Float64}(undef, 6)) unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6) allrealrootintervalnewtonregulafalsi(coefi,respp,pp) resi1,resi2,resi3,resi4,resi5,resi6=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6) for h in(resi1,resi2,resi3,resi4,resi5,resi6) #@show h if h>0 f(x)=coefi[1]*x^6+coefi[2]*x^5+coefi[3]*x^4+coefi[4]*x^3+coefi[5]*x^2+coefi[6]*x+coefi[7] g(x)=coefi[7]+coefi[6]*x+coefi[5]*x^2+coefi[4]*x^3+coefi[3]*x^4+coefi[2]*x^5+coefi[1]*x^6 @show h @show f(h),g(h) end end =# #= coefi=NTuple{7,Float64}((-2.5668078295588949092296481e+16, 1.0474193043858423245087585e+18,1.7114669426922051413515583e+13, -2.8508122708869649897226691e+14, -8.5524376124873223589469262e+08, -1140.3250641304001419575054, -0.00057016254603761695740615778)) pp=pointer(Vector{NTuple{2,Float64}}(undef, 7)) respp = pointer(Vector{Float64}(undef, 6)) Base.GC.enable(false) unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6) allrealrootintervalnewtonregulafalsi(coefi,respp,pp) resi1,resi2,resi3,resi4,resi5,resi6=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6) Base.GC.enable(true) for h in(resi1,resi2,resi3,resi4,resi5,resi6) #@show h if h>0 f(x)=coefi[1]*x^6+coefi[2]*x^5+coefi[3]*x^4+coefi[4]*x^3+coefi[5]*x^2+coefi[6]*x+coefi[7] g(x)=coefi[7]+coefi[6]*x+coefi[5]*x^2+coefi[4]*x^3+coefi[3]*x^4+coefi[2]*x^5+coefi[1]*x^6 @show h @show f(h),g(h) end end =#
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
9043
#using TimerOutputs #using InteractiveUtils function LiQSS_integrate(Al::QSSAlgorithm{:nmliqss,O},CommonqssData::CommonQSS_data{0},liqssdata::LiQSS_data{O,false},specialLiqssData::SpecialLiqssQSS_data, odep::NLODEProblem{PRTYPE,T,0,0,CS},f::Function,jac::Function,SD::Function,exacteA::Function ) where {PRTYPE,CS,O,T} cacheA=specialLiqssData.cacheA ft = CommonqssData.finalTime;initTime = CommonqssData.initialTime;relQ = CommonqssData.dQrel;absQ = CommonqssData.dQmin;maxErr=CommonqssData.maxErr; savetimeincrement=CommonqssData.savetimeincrement;savetime = savetimeincrement quantum = CommonqssData.quantum;nextStateTime = CommonqssData.nextStateTime;nextEventTime = CommonqssData.nextEventTime;nextInputTime = CommonqssData.nextInputTime tx = CommonqssData.tx;tq = CommonqssData.tq;x = CommonqssData.x;q = CommonqssData.q;t=CommonqssData.t savedVars=CommonqssData.savedVars; savedTimes=CommonqssData.savedTimes;integratorCache=CommonqssData.integratorCache;taylorOpsCache=CommonqssData.taylorOpsCache;#Val(CS)=odep.Val(CS) #a=liqssdata.a #u=liqssdata.u; #*************************************************************** qaux=liqssdata.qaux;olddx=liqssdata.olddx;dxaux=liqssdata.dxaux;olddxSpec=liqssdata.olddxSpec numSteps = Vector{Int}(undef, T) simulStepsVals = Vector{Vector{Float64}}(undef, T) simulStepsDers = Vector{Vector{Float64}}(undef, T) simulStepsTimes = Vector{Vector{Float64}}(undef, T) exacteA(q,cacheA,1,1) #######################################compute initial values################################################## n=1 for k = 1:O # compute initial derivatives for x and q (similar to a recursive way ) n=n*k for i = 1:T q[i].coeffs[k] = x[i].coeffs[k] # q computed from x and it is going to be used in the next x end for i = 1:T clearCache(taylorOpsCache,Val(CS),Val(O));f(i,q,t ,taylorOpsCache) ndifferentiate!(integratorCache,taylorOpsCache[1] , k - 1) x[i].coeffs[k+1] = (integratorCache.coeffs[1]) / n # /fact cuz i will store der/fac like the convention...to extract the derivatives (at endof sim) multiply by fac derderx=coef[3]*fac(2) end end for i = 1:T #= p=1 for k=1:O p=p*k m=p/k for j=1:T if j!=i u[i][j][k]=p*x[i][k]-a[i][i]*m*q[i][k-1]-a[i][j]*m*q[j][k-1] else u[i][j][k]=p*x[i][k]-a[i][i]*m*q[i][k-1] end end end =# numSteps[i]=0 simulStepsTimes[i]=Vector{Float64}() simulStepsVals[i]=Vector{Float64}() simulStepsDers[i]=Vector{Float64}() push!(savedVars[i],x[i][0]) push!(savedTimes[i],0.0) quantum[i] = relQ * abs(x[i].coeffs[1]) ;quantum[i]=quantum[i] < absQ ? absQ : quantum[i];quantum[i]=quantum[i] > maxErr ? maxErr : quantum[i] # exacteA(q,cacheA,i,i) updateQ(Val(O),i,x,q,quantum,exacteA,cacheA,dxaux,qaux,tx,tq,initTime,ft,nextStateTime) #display(@code_warntype updateQ(Val(O),i,x,q,quantum,exacteA,cacheA,dxaux,qaux,olddx,tx,tq,initTime,ft,nextStateTime)) end for i = 1:T clearCache(taylorOpsCache,Val(CS),Val(O));f(i,q,t,taylorOpsCache); computeDerivative(Val(O), x[i], taylorOpsCache[1]#= ,0.0 =#)#0.0 used to be elapsed...even down below not neeeded anymore Liqss_reComputeNextTime(Val(O), i, initTime, nextStateTime, x, q, quantum) computeNextInputTime(Val(O), i, initTime, 0.1,taylorOpsCache[1] , nextInputTime, x, quantum)# not complete, currently elapsed=0.1 is temp until fixed end ################################################################################################################################################################### #################################################################################################################################################################### #---------------------------------------------------------------------------------while loop------------------------------------------------------------------------- ################################################################################################################################################################### #################################################################################################################################################################### simt = initTime ;simulStepCount=0;totalSteps=0;prevStepTime=initTime simul=false while simt < ft && totalSteps < 200000000 sch = updateScheduler(Val(T),nextStateTime,nextEventTime, nextInputTime) simt = sch[2];index = sch[1] if simt>ft #simt=ft break end numSteps[index]+=1;totalSteps+=1 t[0]=simt ##########################################state######################################## if sch[3] == :ST_STATE elapsed = simt - tx[index]; integrateState(Val(O),x[index],elapsed) tx[index] = simt quantum[index] = relQ * abs(x[index].coeffs[1]) ;quantum[index]=quantum[index] < absQ ? absQ : quantum[index];quantum[index]=quantum[index] > maxErr ? maxErr : quantum[index] #= elapsedq = simt - tq[index] integrateState(Val(O-1),q[index],elapsedq) =# #= @timeit "exacteA" =# #exacteA(q,cacheA,index,index) # a=cacheA[1] updateQ(Val(O),index,x,q,quantum, exacteA,cacheA,dxaux,qaux,tx,tq,simt,ft,nextStateTime) ;tq[index] = simt for j in SD(index) elapsedx = simt - tx[j] if elapsedx > 0 x[j].coeffs[1] = x[j](elapsedx);tx[j] = simt elapsedq = simt - tq[j] if elapsedq > 0 integrateState(Val(O-1),q[j],elapsedq);tq[j] = simt end end for b in jac(j) elapsedq = simt - tq[b] if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end end clearCache(taylorOpsCache,Val(CS),Val(O)); f(j,q,t,taylorOpsCache);computeDerivative(Val(O), x[j], taylorOpsCache[1]) Liqss_reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum) end#end for SD ###exacteA no need: updateLinearApprox(index,x,q,a,qaux,olddx)# ##################################input######################################## elseif sch[3] == :ST_INPUT # time of change has come to a state var that does not depend on anything...no one will give you a chance to change but yourself @show 55 elapsed = simt - tx[index];integrateState(Val(O),x[index],elapsed);tx[index] = simt quantum[index] = relQ * abs(x[index].coeffs[1]) ;quantum[index]=quantum[index] < absQ ? absQ : quantum[index];quantum[index]=quantum[index] > maxErr ? maxErr : quantum[index] if abs(x[index].coeffs[2])>1e7 quantum[index]=10*quantum[index] end for k = 1:O q[index].coeffs[k] = x[index].coeffs[k] end; tq[index] = simt for b in jac(index) elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end end clearCache(taylorOpsCache,Val(CS),Val(O));f(index,q,t,taylorOpsCache) computeNextInputTime(Val(O), index, simt, elapsed,taylorOpsCache[1] , nextInputTime, x, quantum) computeDerivative(Val(O), x[index], taylorOpsCache[1]#= ,elapsed =#) # reComputeNextTime(Val(O), index, simt, nextStateTime, x, q, quantum) for j in (SD(index)) elapsedx = simt - tx[j]; if elapsedx > 0 x[j].coeffs[1] = x[j](elapsedx);tx[j] = simt # quantum[j] = relQ * abs(x[j].coeffs[1]) ;quantum[j]=quantum[j] < absQ ? absQ : quantum[j];quantum[j]=quantum[j] > maxErr ? maxErr : quantum[j] end elapsedq = simt - tq[j];if elapsedq > 0 integrateState(Val(O-1),q[j],elapsedq);tq[j] = simt end#q needs to be updated here for recomputeNext for b in jac(j) elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end end clearCache(taylorOpsCache,Val(CS),Val(O));f(j,q,t,taylorOpsCache);computeDerivative(Val(O), x[j], taylorOpsCache[1]#= ,elapsed =#) reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum) end#end for end#end state/input/event push!(savedVars[index],x[index][0]) push!(savedTimes[index],simt) end#end while # createSol(Val(T),Val(O),savedTimes,savedVars, "liqss$O",string(odep.prname),absQ,totalSteps,simulStepCount,numSteps,ft,simulStepsVals,simulStepsDers,simulStepsTimes) createSol(Val(T),Val(O),savedTimes,savedVars, "Liqss$O",string(odep.prname),absQ,totalSteps,simulStepCount,0,numSteps,ft) end#end integrate #= function exacteA(q, cache, i, j) if i == 0 return nothing elseif i == 1 && j == 1 cache[1] = -20.0 return nothing elseif i == 2 && j == 2 cache[1] = -0.01 return nothing elseif i == 1 && j == 2 cache[1] = -80.0 return nothing elseif i == 2 && j == 1 cache[1] = 1.24 return nothing end end =#
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
8561
#using TimerOutputs function integrate(Al::QSSAlgorithm{:qss,O},CommonqssData::CommonQSS_data{0}, odep::NLODEProblem{PRTYPE,T,0,0,CS},f::Function,jac::Function,SD::Function) where {PRTYPE,O,T,CS} ft = CommonqssData.finalTime;initTime = CommonqssData.initialTime;relQ = CommonqssData.dQrel;absQ = CommonqssData.dQmin;maxErr=CommonqssData.maxErr; #= savetimeincrement=CommonqssData.savetimeincrement;savetime = savetimeincrement =# quantum = CommonqssData.quantum;nextStateTime = CommonqssData.nextStateTime;nextEventTime = CommonqssData.nextEventTime;nextInputTime = CommonqssData.nextInputTime tx = CommonqssData.tx;tq = CommonqssData.tq;x = CommonqssData.x;q = CommonqssData.q;t=CommonqssData.t savedVars=CommonqssData.savedVars; savedTimes=CommonqssData.savedTimes;integratorCache=CommonqssData.integratorCache;taylorOpsCache=CommonqssData.taylorOpsCache; #a=deepcopy(odep.initJac); #********************************helper values******************************* # qaux=CommonqssData.qaux;olddx=CommonqssData.olddx;olddxSpec = zeros(MVector{T,MVector{O,Float64}}) # later can only care about 1st der numSteps = Vector{Int}(undef, T) savedVarsQ = Vector{Vector{Float64}}(undef, T) for i=1:T savedVarsQ[i]=Vector{Float64}() end #######################################compute initial values################################################## n=1 for k = 1:O # compute initial derivatives for x and q (similar to a recursive way ) n=n*k for i = 1:T q[i].coeffs[k] = x[i].coeffs[k] end # q computed from x and it is going to be used in the next x for i = 1:T clearCache(taylorOpsCache,Val(CS),Val(O));f(i,q, t ,taylorOpsCache) ndifferentiate!(integratorCache,taylorOpsCache[1] , k - 1) x[i].coeffs[k+1] = (integratorCache.coeffs[1]) / n # /fact cuz i will store der/fac like the convention...to extract the derivatives (at endof sim) multiply by fac derderx=coef[3]*fac(2) end end for i = 1:T numSteps[i]=0 push!(savedVarsQ[i],q[i][0]) push!(savedVars[i],x[i][0]) push!(savedTimes[i],0.0) quantum[i] = relQ * abs(x[i].coeffs[1]) ;quantum[i]=quantum[i] < absQ ? absQ : quantum[i];quantum[i]=quantum[i] > maxErr ? maxErr : quantum[i] computeNextTime(Val(O), i, initTime, nextStateTime, x, quantum) initSmallAdvance=0.1 #t[0]=initTime#initSmallAdvance # clearCache(taylorOpsCache,Val(CS),Val(O)); #@timeit "f" f(i,q,t,taylorOpsCache);#@show taylorOpsCache computeNextInputTime(Val(O), i, initTime, initSmallAdvance,taylorOpsCache[1] , nextInputTime, x, quantum) #= assignXPrevStepVals(Val(O),prevStepVal,x,i) =# end ################################################################################################################################################################### #################################################################################################################################################################### #---------------------------------------------------------------------------------while loop------------------------------------------------------------------------- ################################################################################################################################################################### #################################################################################################################################################################### simt = initTime ;totalSteps=0;prevStepTime=initTime # breakloop= zeros(MVector{1,Float64}) #@timeit "qssintgrateWhile" while simt < ft && totalSteps < 200000000 #= if breakloop[1]>5.0 break end =# sch = updateScheduler(Val(T),nextStateTime,nextEventTime, nextInputTime) simt = sch[2] # @timeit "saveLast" #= if simt>ft saveLast!(Val(T),Val(O),savedVars, savedTimes,saveVarsHelper,ft,prevStepTime,integratorCache, x) break ###################################################break########################################## end =# index = sch[1] totalSteps+=1 t[0]=simt ##########################################state######################################## if sch[3] == :ST_STATE numSteps[index]+=1; elapsed = simt - tx[index];integrateState(Val(O),x[index],elapsed);tx[index] = simt quantum[index] = relQ * abs(x[index].coeffs[1]) ;quantum[index]=quantum[index] < absQ ? absQ : quantum[index];quantum[index]=quantum[index] > maxErr ? maxErr : quantum[index] if abs(x[index].coeffs[2])>1e7 quantum[index]=10*quantum[index] end for k = 1:O q[index].coeffs[k] = x[index].coeffs[k] end; tq[index] = simt computeNextTime(Val(O), index, simt, nextStateTime, x, quantum) # for j in (SD(index)) elapsedx = simt - tx[j];if elapsedx > 0 x[j].coeffs[1] = x[j](elapsedx);tx[j] = simt end # quantum[j] = relQ * abs(x[j].coeffs[1]) ;quantum[j]=quantum[j] < absQ ? absQ : quantum[j];quantum[j]=quantum[j] > maxErr ? maxErr : quantum[j] elapsedq = simt - tq[j];if elapsedq > 0 integrateState(Val(O-1),q[j],elapsedq);tq[j] = simt end#q needs to be updated here for recomputeNext for b in (jac(j) ) elapsedq = simt - tq[b] if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end end clearCache(taylorOpsCache,Val(CS),Val(O));f(j,q,t,taylorOpsCache);computeDerivative(Val(O), x[j], taylorOpsCache[1]) reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum) end#end for SD ##################################input######################################## elseif sch[3] == :ST_INPUT # time of change has come to a state var that does not depend on anything...no one will give you a chance to change but yourself @show index elapsed = simt - tx[index];integrateState(Val(O),x[index],elapsed);tx[index] = simt quantum[index] = relQ * abs(x[index].coeffs[1]) ;quantum[index]=quantum[index] < absQ ? absQ : quantum[index];quantum[index]=quantum[index] > maxErr ? maxErr : quantum[index] for k = 1:O q[index].coeffs[k] = x[index].coeffs[k] end; tq[index] = simt for b in jac(index) elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end end clearCache(taylorOpsCache,Val(CS),Val(O));f(index,q,t,taylorOpsCache) computeNextInputTime(Val(O), index, simt, elapsed,taylorOpsCache[1] , nextInputTime, x, quantum) computeDerivative(Val(O), x[index], taylorOpsCache[1]) for j in(SD(index)) elapsedx = simt - tx[j]; if elapsedx > 0 x[j].coeffs[1] = x[j](elapsedx);tx[j] = simt quantum[j] = relQ * abs(x[j].coeffs[1]) ;quantum[j]=quantum[j] < absQ ? absQ : quantum[j];quantum[j]=quantum[j] > maxErr ? maxErr : quantum[j] end elapsedq = simt - tq[j];if elapsedq > 0 integrateState(Val(O-1),q[j],elapsedq);tq[j] = simt end#q needs to be updated here for recomputeNext # elapsed update all other vars that this derj depends upon. for b in jac(j) elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end end clearCache(taylorOpsCache,Val(CS),Val(O));f(j,q,t,taylorOpsCache);computeDerivative(Val(O), x[j], taylorOpsCache[1]) reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum) end#end for end#end state/input/event #= if simt > savetime #|| sch[3] ==:ST_EVENT save!(Val(O),savedVars , savedTimes , saveVarsHelper,prevStepTime ,simt,tx ,tq , integratorCache,x , q,prevStepVal) savetime += savetimeincrement #next savetime else#end if save for k = 1:T elapsed = simt - tx[k];integrateState(Val(O),x[k],elapsed);tx[k] = simt #in case this point did not get updated. elapsedq = simt - tq[k];integrateState(Val(O-1),q[k],elapsedq);tq[k]=simt assignXPrevStepVals(Val(O),prevStepVal,x,k) end end prevStepTime=simt =# push!(savedVars[index],x[index][0]) push!(savedTimes[index],simt) # push!(savedVarsQ[index],q[index][0]) #= for i=1:T push!(savedVars[i],x[i][0]) push!(savedTimes[i],simt) push!(savedVarsQ[i],q[i][0]) end =# end#end while #= for i=1:T# throw away empty points resize!(savedVars[i],saveVarsHelper[1]) end resize!(savedTimes,saveVarsHelper[1]) =# createSol(Val(T),Val(O),savedTimes,savedVars, "qss$O",string(odep.prname),absQ,totalSteps,0,0,numSteps,ft) end#end integrate
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
code
12722
#using TimerOutputs function integrate(Al::QSSAlgorithm{:qss,O},CommonqssData::CommonQSS_data{Z}, odep::NLODEProblem{PRTYPE,T,Z,Y,CS},f::Function,jac::Function,SD::Function) where {PRTYPE,O,T,Z,Y,CS} ft = CommonqssData.finalTime;initTime = CommonqssData.initialTime;relQ = CommonqssData.dQrel;absQ = CommonqssData.dQmin;maxErr=CommonqssData.maxErr; #savetimeincrement=CommonqssData.savetimeincrement;savetime = savetimeincrement quantum = CommonqssData.quantum;nextStateTime = CommonqssData.nextStateTime;nextEventTime = CommonqssData.nextEventTime;nextInputTime = CommonqssData.nextInputTime tx = CommonqssData.tx;tq = CommonqssData.tq;x = CommonqssData.x;q = CommonqssData.q;t=CommonqssData.t savedVars=CommonqssData.savedVars; savedTimes=CommonqssData.savedTimes;integratorCache=CommonqssData.integratorCache;taylorOpsCache=CommonqssData.taylorOpsCache;#cacheSize=odep.cacheSize #prevStepVal = specialLiqssData.prevStepVal #*********************************problem info***************************************** d = odep.discreteVars zc_SimpleJac=odep.ZCjac HZ=odep.HZ HD=odep.HD SZ=odep.SZ evDep = odep.eventDependencies if DEBUG2 @show HD,HZ,SZ,zc_SimpleJac,d end if DEBUG2 @show evDep end if DEBUG2 @show f end #********************************helper values******************************* oldsignValue = MMatrix{Z,2}(zeros(Z*2)) #usedto track if zc changed sign; each zc has a value and a sign numSteps = Vector{Int}(undef, T) #######################################compute initial values################################################## n=1 for k = 1:O # compute initial derivatives for x and q (similar to a recursive way ) n=n*k for i = 1:T q[i].coeffs[k] = x[i].coeffs[k] end # q computed from x and it is going to be used in the next x for i = 1:T clearCache(taylorOpsCache,Val(CS),Val(O));f(i,-1,-1,q,d, t ,taylorOpsCache) ndifferentiate!(integratorCache,taylorOpsCache[1] , k - 1) x[i].coeffs[k+1] = (integratorCache.coeffs[1]) / n # /fact cuz i will store der/fac like the convention...to extract the derivatives (at endof sim) multiply by fac derderx=coef[3]*fac(2) end end for i = 1:T numSteps[i]=0 push!(savedVars[i],x[i][0]) push!(savedTimes[i],0.0) quantum[i] = relQ * abs(x[i].coeffs[1]) ;quantum[i]=quantum[i] < absQ ? absQ : quantum[i];quantum[i]=quantum[i] > maxErr ? maxErr : quantum[i] computeNextTime(Val(O), i, initTime, nextStateTime, x, quantum) #updateQ(Val(O),i,x,q,quantum,exacteA,cacheA,dxaux,qaux,tx,tq,initTime,ft,nextStateTime) end for i=1:Z clearCache(taylorOpsCache,Val(CS),Val(O));f(-1,i,-1,x,d,t,taylorOpsCache) oldsignValue[i,2]=taylorOpsCache[1][0] #value oldsignValue[i,1]=sign(taylorOpsCache[1][0]) #sign modify computeNextEventTime(Val(O),i,taylorOpsCache[1],oldsignValue,initTime, nextEventTime, quantum,absQ) end ################################################################################################################################################################### #################################################################################################################################################################### #---------------------------------------------------------------------------------while loop------------------------------------------------------------------------- ################################################################################################################################################################### #################################################################################################################################################################### simt = initTime ;totalSteps=0;prevStepTime=initTime;modifiedIndex=0;statestep=0; countEvents=0;#needSaveEvent=false while simt<ft && totalSteps < 50000000 sch = updateScheduler(Val(T),nextStateTime,nextEventTime, nextInputTime) simt = sch[2];index = sch[1];stepType=sch[3] if simt>ft #saveLast!(Val(T),Val(O),savedVars, savedTimes,saveVarsHelper,ft,prevStepTime, x) break ###################################################break########################################## end totalSteps+=1 t[0]=simt DEBUG_time=DEBUG && 0.0<=simt<=ft ##########################################state######################################## if stepType == :ST_STATE statestep+=1 numSteps[index]+=1; elapsed = simt - tx[index];integrateState(Val(O),x[index],elapsed);tx[index] = simt quantum[index] = relQ * abs(x[index].coeffs[1]) ;quantum[index]=quantum[index] < absQ ? absQ : quantum[index];quantum[index]=quantum[index] > maxErr ? maxErr : quantum[index] if abs(x[index].coeffs[2])>1e7 quantum[index]=10*quantum[index] end for k = 1:O q[index].coeffs[k] = x[index].coeffs[k] end; tq[index] = simt computeNextTime(Val(O), index, simt, nextStateTime, x, quantum) # for j in (SD(index)) elapsedx = simt - tx[j];if elapsedx > 0 x[j].coeffs[1] = x[j](elapsedx);tx[j] = simt end elapsedq = simt - tq[j];if elapsedq > 0 integrateState(Val(O-1),q[j],elapsedq);tq[j] = simt end#q needs to be updated here for recomputeNext for b in (jac(j) ) elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end end clearCache(taylorOpsCache,Val(CS),Val(O));f(j,-1,-1,q,d,t,taylorOpsCache);computeDerivative(Val(O), x[j], taylorOpsCache[1]) reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum) end#end for SD for j in (SZ[index]) for b in zc_SimpleJac[j] # elapsed update all other vars that this derj depends upon. elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end end clearCache(taylorOpsCache,Val(CS),Val(O));f(-1,j,-1,q,d,t,taylorOpsCache) # run ZCF-------- computeNextEventTime(Val(O),j,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum,absQ) end#end for SZ ##################################input######################################## elseif stepType == :ST_INPUT # time of change has come to a state var that does not depend on anything...no one will give you a chance to change but yourself #################################################################event######################################## else if DEBUG println("at start of event simt=$simt index=$index") end for b in zc_SimpleJac[index] # elapsed update all other vars that this zc depends upon. elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end end clearCache(taylorOpsCache,Val(CS),Val(O));f(-1,index,-1,q,d,t,taylorOpsCache) # run ZCF-------- if DEBUG @show oldsignValue[index,2],taylorOpsCache[1][0] end #= if oldsignValue[index,2]*taylorOpsCache[1][0]>=0 && abs(taylorOpsCache[1][0])>1e-9*absQ # if both have same sign and zcf is not very small computeNextEventTime(Val(O),index,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum,absQ) if DEBUG println("wrong estimation of event at $simt") end continue end # needSaveEvent=true countEvents+=1 if taylorOpsCache[1][0]>oldsignValue[index,2] # rise modifiedIndex=2*index-1 elseif taylorOpsCache[1][0]<oldsignValue[index,2] # drop modifiedIndex=2*index else # == ( zcf==oldZCF) if DEBUG println("ZCF==oldZCF at $simt") end continue end oldsignValue[index,2]=taylorOpsCache[1][0] oldsignValue[index,1]=sign(taylorOpsCache[1][0]) =# if oldsignValue[index,2]*taylorOpsCache[1][0]>=0 if abs(taylorOpsCache[1][0])>1e-9*absQ # if both have same sign and zcf is not very small: zc=1e-9*absQ is allowed as an event computeNextEventTime(Val(O),index,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum,absQ) # @show index,countEvents # @show oldsignValue[index,2],taylorOpsCache[1][0] if DEBUG_time println("wrong estimation of event at $simt") end continue end end if abs(oldsignValue[index,2]) <=1e-9*absQ #earlier zc=1e-9*absQ was considered event , so now it should be prevented from passing nextEventTime[index]=Inf # at this instant next zc will be triggered now, and this will lead to infinite events, so cannot computenextevent here continue end # needSaveEvent=true if taylorOpsCache[1][0]>oldsignValue[index,2] #scheduled rise modifiedIndex=2*index-1 elseif taylorOpsCache[1][0]<oldsignValue[index,2] #scheduled drop modifiedIndex=2*index else # == ( zcf==oldZCF) if DEBUG_time println("this should never be reached ZCF==oldZCF at $simt cuz small old not allowed and large zc not allowed!!") end computeNextEventTime(Val(O),index,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum,absQ) continue end countEvents+=1 oldsignValue[index,2]=taylorOpsCache[1][0] oldsignValue[index,1]=sign(taylorOpsCache[1][0]) #= if DEBUG @show modifiedIndex,x @show q end =# for b in evDep[modifiedIndex].evContRHS elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end end f(-1,-1,modifiedIndex,x,d,t,taylorOpsCache)# execute event-------- for i in evDep[modifiedIndex].evCont #------------event influences a Continete var: x already updated in event...here update quantum and q and computenext quantum[i] = relQ * abs(x[i].coeffs[1]) ;quantum[i]=quantum[i] < absQ ? absQ : quantum[i];quantum[i]=quantum[i] > maxErr ? maxErr : quantum[i] for k = 0:O-1 q[i][k]=x[i][k] end;tx[i] = simt;tq[i] = simt # for liqss updateQ? # firstguess=updateQ(Val(O),i,x,q,quantum,exacteA,cacheA,dxaux,qaux,tx,tq,simt,ft,nextStateTime) ;tq[i] = simt computeNextTime(Val(O), i, simt, nextStateTime, x, quantum) end # nextEventTime[index]=Inf #investigate more computeNextEventTime(Val(O),index,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum,absQ) # it could happen zcf=0.0 then infinite event for j in (HD[modifiedIndex]) # care about dependency to this event only elapsedx = simt - tx[j];if elapsedx > 0 x[j].coeffs[1] = x[j](elapsedx);tx[j] = simt;#= @show j,x[j] =# end elapsedq = simt - tq[j];if elapsedq > 0 integrateState(Val(O-1),q[j],elapsedq);tq[j] = simt;#= @show q[j] =# end#q needs to be updated here for recomputeNext for b = 1:T # elapsed update all other vars that this derj depends upon. if b in jac(j) elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt;#= @show q[b] =# end end end clearCache(taylorOpsCache,Val(CS),Val(O));f(j,-1,-1,q,d,t,taylorOpsCache);computeDerivative(Val(O), x[j], taylorOpsCache[1]) reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum) # @show simt,j,x end for j in (HZ[modifiedIndex]) for b in zc_SimpleJac[j] # elapsed update all other vars that this derj depends upon. elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end end clearCache(taylorOpsCache,Val(CS),Val(O));f(-1,j,-1,q,d,t,taylorOpsCache) # run ZCF-------- if VERBOSE @show j,oldsignValue[j,2],taylorOpsCache[1][0] end computeNextEventTime(Val(O),j,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum,absQ) end if DEBUG println("x at end of event simt=$simt x=$x") println("q at end of event simt=$simt q=$q") @show countEvents,totalSteps,statestep @show nextStateTime,quantum end end#end state/input/event if stepType != :ST_EVENT push!(savedVars[index],x[index][0]) push!(savedTimes[index],simt) #= for i =1:T push!(savedVars[i],x[i][0]) push!(savedTimes[i],simt) end =# else #if needSaveEvent for j in (HD[modifiedIndex]) push!(savedVars[j],x[j][0]) push!(savedTimes[j],simt) end # end end prevStepTime=simt end#end while #@show countEvents,totalSteps createSol(Val(T),Val(O),savedTimes,savedVars, "qss$O",string(odep.prname),absQ,totalSteps,0,countEvents,numSteps,ft) end#end integrate
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git