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.1.0
32ac213c415abaee7c6a36dd65bacf2c65b8836d
docs
1002
# ExportPublic.jl: Easily hide your implementation details This is a fork of [`ExportAll.jl`](https://github.com/JKRT/ExportAll.jl/) that helps you write modules with public and private symbols. If something starts with an underscore `_`, it will **not** be exported. ```julia module SimpleMathExample using ExportPublic _secret_pi = 22/7 # Private my_pi = _secret_pi # Public function add_squared(a::Int, b::Int) # Public _squared(a) + _squared(b) end function _squared(a::Int) # Private a ^ 2 end @exportPublic() # <--- Export our Public symbols end ``` The "*Public*" symbols are automatically exported: ```julia julia> include("SimpleMathExample.jl") julia> using .SimpleMathExample julia> add_squared(5, 5) 50 julia> my_pi 3.142857142857143 julia> _secret_pi ERROR: UndefVarError: _secret_pi not defined julia> _squared(5) ERROR: UndefVarError: _squared not defined ```
ExportPublic
https://github.com/hayesall/ExportPublic.jl.git
[ "MIT" ]
0.1.0
32ac213c415abaee7c6a36dd65bacf2c65b8836d
docs
1007
# ExportPublic.jl > *Easily hide your implementation details.* This is a fork of [`ExportAll.jl`](https://github.com/JKRT/ExportAll.jl/) that helps you write modules with public and private symbols. If something starts with an underscore `_`, it will **not** be exported. ```julia module SimpleMathExample using ExportPublic _secret_pi = 22/7 # Private my_pi = _secret_pi # Public function add_squared(a::Int, b::Int) # Public _squared(a) + _squared(b) end function _squared(a::Int) # Private a ^ 2 end @exportPublic() # <--- Export our Public symbols end ``` The "*Public*" symbols are automatically exported: ```julia julia> include("SimpleMathExample.jl") julia> using .SimpleMathExample julia> add_squared(5, 5) 50 julia> my_pi 3.142857142857143 julia> _secret_pi ERROR: UndefVarError: _secret_pi not defined julia> _squared(5) ERROR: UndefVarError: _squared not defined ```
ExportPublic
https://github.com/hayesall/ExportPublic.jl.git
[ "MIT" ]
1.0.0
42fd9023fef18b9b78c8343a4e2f3813ffbcefcb
code
210
module TestItems export @testitem, @testmodule, @testsnippet macro testitem(ex...) return nothing end macro testmodule(ex...) return nothing end macro testsnippet(ex...) return nothing end end
TestItems
https://github.com/julia-vscode/TestItems.jl.git
[ "MIT" ]
1.0.0
42fd9023fef18b9b78c8343a4e2f3813ffbcefcb
code
377
using TestItems using Test @testset "TestItems" begin x = @testitem "Name of the test item" begin println("Hello world") end @test x === nothing y = @testmodule Foo begin const x = 10 getfloat() = rand() end @test y === nothing z = @testsnippet Bar begin println("Hello world") end @test z ===nothing end
TestItems
https://github.com/julia-vscode/TestItems.jl.git
[ "MIT" ]
1.0.0
42fd9023fef18b9b78c8343a4e2f3813ffbcefcb
docs
644
# TestItems.jl [![Project Status: Active – The project has reached a stable, usable state and is being actively developed.](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active) ![](https://github.com/julia-vscode/TestItems.jl/workflows/Run%20tests/badge.svg) [![codecov](https://codecov.io/gh/julia-vscode/TestItems.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/julia-vscode/TestItems.jl) ## Overview This package provides the `@testitem` macro for the test runner feature in VS Code. Please look at https://github.com/julia-vscode/TestItemRunner.jl for the documentation for this package here.
TestItems
https://github.com/julia-vscode/TestItems.jl.git
[ "MIT" ]
1.0.0
36351b6b743f7ee469047e54ad1d4a71e9915e28
code
605
using BisectPy using Documenter DocMeta.setdocmeta!(BisectPy, :DocTestSetup, :(using BisectPy); recursive=true) makedocs(; modules=[BisectPy], authors="Qi Zhang <[email protected]>", repo="https://github.com/singularitti/BisectPy.jl/blob/{commit}{path}#{line}", sitename="BisectPy.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://singularitti.github.io/BisectPy.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/singularitti/BisectPy.jl", )
BisectPy
https://github.com/singularitti/BisectPy.jl.git
[ "MIT" ]
1.0.0
36351b6b743f7ee469047e54ad1d4a71e9915e28
code
83
module BisectPy include("bisect.jl") include("insort.jl") include("find.jl") end
BisectPy
https://github.com/singularitti/BisectPy.jl.git
[ "MIT" ]
1.0.0
36351b6b743f7ee469047e54ad1d4a71e9915e28
code
2019
export bisect_left, bisect_right, bisect """ bisect_left(a, x, lo = 1, hi = length(a) + 1) Return the index where to insert item `x` in array `a`, assuming `a` is in an non-decreasing order. The return value `i` is such that all `e` in `a[:(i - 1)]` have `e < x`, and all `e` in `a[i:]` have `e >= x`. So if `x` already appears in the array, `insert!(a, i, x)` will insert just before the leftmost `x` already there. # Arguments Optional args `lo` (default `1`) and `hi` (default `length(a) + 1`) bound the slice of `a` to be searched. # Examples ```jldoctest julia> bisect_left([1, 2, 3, 4, 5], 3.5) 4 julia> bisect_left([1, 2, 3, 4, 5], 2) 2 julia> bisect_left([1, 2, 3, 3, 3, 5], 3) 3 ``` """ function bisect_left(a, x, lo = 1, hi = nothing) if lo < 1 throw(BoundsError(a, lo)) end if hi === nothing hi = length(a) + 1 # It's not `length(a)`! end while lo < hi mid = (lo + hi) ÷ 2 a[mid] < x ? lo = mid + 1 : hi = mid end return lo end """ bisect_right(a, x, lo = 1, hi = length(a) + 1) Return the index where to insert item `x` in array `a`, assuming `a` is in an non-decreasing order. The return value `i` is such that all `e` in `a[:(i - 1)]` have `e <= x`, and all `e` in `a[i:]` have `e > x`. So if `x` already appears in the array, `insert!(a, i, x)` will insert just after the rightmost `x` already there. # Arguments Optional args `lo` (default `1`) and `hi` (default `length(a) + 1`) bound the slice of `a` to be searched. # Examples ```jldoctest julia> bisect_right([1, 2, 3, 4, 5], 3.5) 4 julia> bisect_right([1, 2, 3, 4, 5], 2) 3 julia> bisect_right([1, 2, 3, 3, 3, 5], 3) 6 ``` """ function bisect_right(a, x, lo = 1, hi = nothing) if lo < 1 throw(BoundsError(a, lo)) end if hi === nothing hi = length(a) + 1 # It's not `length(a)`! end while lo < hi mid = (lo + hi) ÷ 2 x < a[mid] ? hi = mid : lo = mid + 1 end return lo end const bisect = bisect_right
BisectPy
https://github.com/singularitti/BisectPy.jl.git
[ "MIT" ]
1.0.0
36351b6b743f7ee469047e54ad1d4a71e9915e28
code
879
""" index(a, x) Locate the leftmost value exactly equal to `x` in `a`. """ function index(a, x) i = bisect_left(a, x) return i != length(a) + 1 && a[i] == x ? i : nothing end """ find_lt(a, x) Find rightmost value less than `x` in `a`. """ function find_lt(a, x) i = bisect_left(a, x) return i > 1 ? a[i-1] : nothing end """ find_le(a, x) Find rightmost value less than or equal to `x` in `a`. """ function find_le(a, x) i = bisect_right(a, x) return i > 1 ? a[i-1] : nothing end """ find_gt(a, x) Find leftmost value greater than `x` in `a`. """ function find_gt(a, x) i = bisect_right(a, x) return i != length(a) + 1 ? a[i] : nothing end """ find_ge(a, x) Find leftmost item greater than or equal to `x` in `a`. """ function find_ge(a, x) i = bisect_left(a, x) return i != length(a) + 1 ? a[i] : nothing end
BisectPy
https://github.com/singularitti/BisectPy.jl.git
[ "MIT" ]
1.0.0
36351b6b743f7ee469047e54ad1d4a71e9915e28
code
909
export insort_left, insort_right, insort """ insort_left(a, x, lo = 1, hi = nothing) Insert item `x` in array `a`, and keep it sorted assuming `a` is sorted. If `x` is already in `a`, insert it to the left of the leftmost `x`. Optional args `lo` (default `1`) and `hi` (default `length(a)`) bound the slice of `a` to be searched. """ function insort_left(a, x, lo = 1, hi = nothing) lo = bisect_left(a, x, lo, hi) return insert!(a, lo, x) end """ insort_right(a, x, lo = 1, hi = nothing) Insert item `x` in array `a`, and keep it sorted assuming `a` is sorted. If `x` is already in `a`, insert it to the right of the rightmost `x`. Optional args `lo` (default `1`) and `hi` (default `length(a)`) bound the slice of `a` to be searched. """ function insort_right(a, x, lo = 1, hi = nothing) lo = bisect_right(a, x, lo, hi) return insert!(a, lo, x) end const insort = insort_right
BisectPy
https://github.com/singularitti/BisectPy.jl.git
[ "MIT" ]
1.0.0
36351b6b743f7ee469047e54ad1d4a71e9915e28
code
3096
using BisectPy: bisect_left, bisect_right, index, find_lt, find_le, find_gt, find_ge, insort_left, insort_right using Test @testset "BisectPy.jl" begin @test bisect_left([1, 2, 3, 4, 5], 3.5) == 4 @test bisect_right([1, 2, 3, 4, 5], 3.5) == 4 @testset "Equal tests" begin @test bisect_left([1, 2, 3, 4, 5], 2) == 2 @test bisect_left([1, 2, 3, 3, 3, 5], 3) == 3 @test bisect_right([1, 2, 3, 4, 5], 2) == 3 @test bisect_right([1, 2, 3, 3, 3, 5], 3) == 6 end @testset "Boundary tests" begin @test bisect_left([1, 2, 3, 4, 5], 0) == 1 @test bisect_left([1, 2, 3, 4, 5], 5) == 5 @test bisect_left([1, 2, 3, 4, 5], 6) == 6 @test bisect_right([1, 2, 3.0, 4, 5], 5) == 6 @test bisect_right([1, 2, 3.0, 4, 5], 6) == 6 @test bisect_right([1, 2, 3, 4, 5], 1) == 2 @test bisect_right([1, 2, 3, 4, 5], 0) == 1 end @testset "`Python example 1`" begin function grade(score, breakpoints = [60, 70, 80, 90], grades = "FDCBA") i = bisect_right(breakpoints, score) return grades[i] end @test [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]] == ['F', 'A', 'C', 'C', 'B', 'A', 'A'] end @testset "`Python example 2`" begin data = [("red", 5), ("blue", 1), ("yellow", 8), ("black", 0)] sort!(data) keys = [r[2] for r in sort(data)] @test data[bisect_left(keys, 0)] == ("black", 0) @test data[bisect_left(keys, 1)] == ("blue", 1) @test data[bisect_left(keys, 5)] == ("red", 5) @test data[bisect_left(keys, 8)] == ("yellow", 8) end @test insort_left([1, 2, 3, 4, 5], 0) == [0, 1, 2, 3, 4, 5] @test insort_left([1, 2, 3, 4, 5], 6) == [1, 2, 3, 4, 5, 6] @test insort_right([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5, 5] @test insort_right([1, 2, 3, 4, 5], 6) == [1, 2, 3, 4, 5, 6] @test index([1, 2, 3, 4, 5], 3.5) === nothing @test index([1, 2, 2, 3, 4, 5], 2) == 2 @test index([1, 2, 3, 4, 5], 5) == 5 @test index([1, 2, 3, 4, 5], 6) === nothing @test find_lt([1, 2, 3, 4, 5], 2) == 1 @test find_lt([1, 2, 2, 3, 4, 4, 5], 3) == 2 @test find_lt([1, 2, 2, 3, 3.5, 4, 4, 5], 3.5) == 3 @test find_lt([1, 2, 3, 4, 5], 0) === nothing @test find_lt([1, 2, 3, 4, 5], 6) == 5 @test find_le([1, 2, 3, 4, 5], 2) == 2 @test find_le([1, 2, 2, 3, 4, 4, 5], 3) == 3 @test find_le([1, 2, 2, 3, 4, 5, 5], 3.5) == 3 @test find_le([1, 2, 3, 4, 5], 0) === nothing @test find_le([1, 2, 3, 4, 5], 6) == 5 @test find_gt([1, 2, 3, 4, 5], 2) == 3 @test find_gt([1, 2, 2, 3, 4, 4, 5], 3) == 4 @test find_gt([1, 2, 2, 3, 4, 5, 5], 3.5) == 4 @test find_gt([1, 2, 3, 4, 5], 0) == 1 @test find_gt([1, 2, 3, 4, 5, 5], 6) === nothing @test find_ge([1, 2, 3, 4, 5], 2) == 2 @test find_ge([1, 2, 2, 3, 4, 4, 5], 3) == 3 @test find_ge([1, 2, 2, 3, 4, 5, 5], 3.5) == 4 @test find_ge([1, 2, 3, 4, 5], 0) == 1 @test find_ge([1, 2, 3, 4, 5, 5], 6) === nothing end
BisectPy
https://github.com/singularitti/BisectPy.jl.git
[ "MIT" ]
1.0.0
36351b6b743f7ee469047e54ad1d4a71e9915e28
docs
1744
# BisectPy: array bisection algorithm [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://singularitti.github.io/BisectPy.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://singularitti.github.io/BisectPy.jl/dev) [![Build Status](https://github.com/singularitti/BisectPy.jl/workflows/CI/badge.svg)](https://github.com/singularitti/BisectPy.jl/actions) [![Build Status](https://travis-ci.com/singularitti/BisectPy.jl.svg?branch=master)](https://travis-ci.com/singularitti/BisectPy.jl) [![Build Status](https://ci.appveyor.com/api/projects/status/github/singularitti/BisectPy.jl?svg=true)](https://ci.appveyor.com/project/singularitti/BisectPy-jl) [![Build Status](https://cloud.drone.io/api/badges/singularitti/BisectPy.jl/status.svg)](https://cloud.drone.io/singularitti/BisectPy.jl) [![Build Status](https://api.cirrus-ci.com/github/singularitti/BisectPy.jl.svg)](https://cirrus-ci.com/github/singularitti/BisectPy.jl) [![Coverage](https://codecov.io/gh/singularitti/BisectPy.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/singularitti/BisectPy.jl) [![Coverage](https://coveralls.io/repos/github/singularitti/BisectPy.jl/badge.svg?branch=master)](https://coveralls.io/github/singularitti/BisectPy.jl?branch=master) This is a package that migrates Python's [`bisect` module](https://docs.python.org/3.7/library/bisect.html#module-bisect) to Jula. Note that since Julia's array index starts from `1` but Python starts from `0`, the returned index of either `bisect_left` or `bisect_right` is always their Python's correspondence plus `1`! Also, the behavior of Python's `a[:i]` where `a` is an array is also different from Julia: Julia array includes the `i`th item but Python does not!
BisectPy
https://github.com/singularitti/BisectPy.jl.git
[ "MIT" ]
1.0.0
36351b6b743f7ee469047e54ad1d4a71e9915e28
docs
132
```@meta CurrentModule = BisectPy ``` # BisectPy ## [Index](@id main-index) ```@index ``` ```@autodocs Modules = [BisectPy] ```
BisectPy
https://github.com/singularitti/BisectPy.jl.git
[ "MPL-2.0" ]
1.0.0
3a94c01a1d7678f1c29b7d97216f5046f1ed1768
code
2854
module PkgExt using Pkg using StyledStrings using About: About, about, columnlist using PrecompileTools: @compile_workload function About.about_pkg(io::IO, pkg::Base.PkgId, mod::Module) isnothing(pkgversion(mod)) || print(io, styled" Version {about_module:$(pkgversion(mod))}") srcdir = pkgdir(mod) if isnothing(srcdir) print(io, styled" (builtin)") else srcdir = Base.fixup_stdlib_path(srcdir) srcdir = something(Base.find_source_file(srcdir), srcdir) srcdir = contractuser(srcdir) print(io, styled" loaded from {light,underline:$srcdir}") end println(io) isnothing(srcdir) && return manifest_file = Pkg.Types.manifestfile_path(pkgdir(mod)) project_file = Pkg.Types.projectfile_path(pkgdir(mod)) thedeps = if !isnothing(manifest_file) && isfile(manifest_file) Pkg.Types.read_manifest(manifest_file).deps else Pkg.dependencies() end directdeps = if haskey(thedeps, pkg.uuid) listdeps(thedeps, pkg.uuid) elseif !isnothing(project_file) && isfile(project_file) collect(values(Pkg.Types.read_project(project_file).deps)) else collect(keys(thedeps)) end isempty(directdeps) && return depstrs = map(directdeps) do dep indirectextras = length(alldeps(thedeps, dep, directdeps)) if indirectextras > 0 styled"$(thedeps[dep].name) {shadow:(+$indirectextras)}" else styled"$(thedeps[dep].name)" end end indirect_depcount = length(alldeps(thedeps, pkg.uuid) ∪ directdeps) - length(depstrs) indirect_info = if indirect_depcount > 0 styled" {shadow:(+$indirect_depcount indirectly)}" else styled"" end println(io, styled"\n{bold:Directly depends on {emphasis:$(length(directdeps))} \ package$(ifelse(length(directdeps) == 1, \"\", \"s\"))}$indirect_info:") columnlist(io, depstrs) end function listdeps(deps::Dict{Base.UUID, Pkg.Types.PackageEntry}, pkg::Base.UUID) if haskey(deps, pkg) collect(values(deps[pkg].deps)) else Base.UUID[] end end function listdeps(deps::Dict{Base.UUID, Pkg.API.PackageInfo}, pkg::Base.UUID) if haskey(deps, pkg) collect(values(deps[pkg].dependencies)) else Base.UUID[] end end function alldeps(deps::Dict{Base.UUID, <:Union{Pkg.Types.PackageEntry, Pkg.API.PackageInfo}}, pkg::Base.UUID, ignore::Vector{Base.UUID} = Base.UUID[]) depcheck = listdeps(deps, pkg) depcollection = Set{Base.UUID}() while !isempty(depcheck) id = popfirst!(depcheck) id in depcollection || id in ignore && continue append!(depcheck, listdeps(deps, id)) push!(depcollection, id) end collect(depcollection) end @compile_workload begin about(devnull, @__MODULE__) end end
About
https://github.com/tecosaur/About.jl.git
[ "MPL-2.0" ]
1.0.0
3a94c01a1d7678f1c29b7d97216f5046f1ed1768
code
6747
""" About Sometimes you want to know more *about* what you're working with, whether it be a function, type, value, or something else entirely. This package is a utility to help answer that question, it exports a single function `about`, which can be applied to any Julia object. # Extended Help ## Examples **Applied to a Module** ```julia-repl julia> about(About) Module About [69d22d85-9f48-4c46-bbbe-7ad8341ff72a] Version 0.1.0 loaded from ~/.julia/dev/About Directly depends on 4 packages (+9 indirectly): • PrecompileTools (+5) • InteractiveUtils (+3) • StyledStrings • JuliaSyntaxHighlighting (+1) Exports 2 names: • About • about ``` **Applied to a singleton value** ```julia-repl julia> about(ℯ) Irrational{:ℯ} (<: AbstractIrrational <: Real <: Number <: Any), occupies 0B. singelton ``` **Applied to a float** ```julia-repl julia> about(Float64(ℯ)) Float64 (<: AbstractFloat <: Real <: Number <: Any), occupies 8B. 0100000000000101101111110000101010001011000101000101011101101001 ╨└────┬────┘└────────────────────────┬─────────────────────────┘ + 2^1 × 1.359140914229522545 = 2.7182818284590451 ``` **Applied to a character** ```julia-repl julia> about('√') Char (<: AbstractChar <: Any), occupies 4B. ┌2─┐ ┌2─┐┌──1──┐┌A─┐ 11100010 10001000 10011010 00000000 └─0xe2─┘ └─0x88─┘ └─0x9a─┘ └─0x00─┘ = U+221A Unicode '√', category: Symbol, math (Sm) ``` **Applied to a struct type** ```julia-repl julia> about(Dict{Symbol, Int}) Concrete DataType defined in Base, 64B Dict{Symbol, Int64} <: AbstractDict{Symbol, Int64} <: Any Struct with 8 fields: • slots *Memory{UInt8} • keys *Memory{Symbol} • vals *Memory{Int64} • ndel Int64 • count Int64 • age UInt64 • idxfloor Int64 • maxprobe Int64 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ * * * 8B 8B 8B 8B 8B * = Pointer (8B) ``` **Applied to a function** ```julia-repl julia> about(sum, Set{Int}) sum (generic function with 10 methods) Defined in Base(8) extended in Base.MPFR(1) and Base.GMP(1). Matched 1 method :: Int64 sum(a; kw...) @ Base reduce.jl:561 Method effects ✗ consistent might not return or terminate consistently ✔ effect free guaranteed to be free from externally semantically visible side effects ✗ no throw may throw an exception ✗ terminates might not always terminate ✔ no task state guaranteed not to access task state (allowing migration between tasks) ~ inaccessible memory only may access or modify mutable memory iff pointed to by its call arguments ✗ no undefined behaviour may execute undefined behaviour ✔ non-overlayed may call methods from an overlayed method table ``` ## Faces These are the faces that `About` defines, and can be customised to change the style of the output. - `about_module` (bright red) - `about_pointer` (cyan) - `about_count` (bold) - `about_bytes` (bold) - `about_cycle1` (bright blue) - `about_cycle2` (bright green) - `about_cycle3` (bright yellow) - `about_cycle4` (bright magenta) ## Public API - `about` - `memorylayout` (extensible) - `elaboration` (extensible) """ module About using StyledStrings: @styled_str, Face, face!, addface! using JuliaSyntaxHighlighting: highlight using InteractiveUtils @static if VERSION >=v"1.11-alpha" using Base: AnnotatedString, AnnotatedIOBuffer else using StyledStrings: AnnotatedString, AnnotatedIOBuffer end using PrecompileTools: @compile_workload const var"@S_str" = var"@styled_str" export about include("utils.jl") include("functions.jl") include("types.jl") include("values.jl") """ about([io::IO], thing) Display information (to `io` if provided) on the particular nature of `thing`, whatever it may be. This is implemented for a variety of types and objects, with general implementations for: - Functions - Types - Values - Modules Not sure what to make of this? Just try it out 😉 !!! tip "Tip for package developers" See the *extended help* for information on how to implement specialised forms for your own objects. Also consider putting specialised display methods in a package extension. # Extended help While it is possible to extend `about` by implementing specialised `about(::IO, ::MyThing)` methods, it is better to specialise the two main functions called by the `about` function for values (not a `Function`, `Type`, or `Module`): - `memorylayout(::IO, ::MyThing)` - `elaboration(::IO, ::MyThing)` Either or both of these functions can be specialised to customise the display from `about(::IO, ::MyThing)`, and are involved in the output like so: ```julia-repl julia> about(mything) [name] [type hierachy] [size] [memorylayout] [elaboration (when non-compact)] ``` As can be guessed from the names, it is expected that `memorylayout` prints an informative representation of the memory layout of its argument. See `src/values.jl` within the `About` package source for some examples (just scroll past the initial generic implementation). Unlike `memorylayout`, the `elaboration` function does not print anything by default, but can be specialised to add extra pieces of useful information that don't relate to the in-memory representation of the object itself. """ function about end about(x) = about(stderr, x) function about(xs...) if first(xs) == stderr throw(MethodError(about, xs)) else about(stderr, xs...) end end """ memorylayout(io::IO, T::DataType) memorylayout(io::IO, val::T) Print to `io` the memory layout of the type `T`, or `val` a particular instance of the type. Specialised implementations should be implemented freely to enhance the utility and prettiness of the display. """ function memorylayout end """ elaboration(::IO, x::Any) Elaborate on `x` to io, providing extra information that might be of interest seperately from `about` or `memorylayout`. Specialised implementations should be implemented freely to enhance the utility and prettiness of the display. By convention, this is not invoked when displaying `x` compactly. """ elaboration(::IO, ::Any) = nothing const ABOUT_FACES = [ :about_module => Face(foreground=:bright_red), :about_pointer => Face(foreground=:cyan), :about_count => Face(weight=:bold), :about_bytes => Face(weight=:bold), :about_cycle1 => Face(inherit=:bright_blue), :about_cycle2 => Face(inherit=:bright_green), :about_cycle3 => Face(inherit=:bright_yellow), :about_cycle4 => Face(inherit=:bright_magenta), ] __init__() = foreach(addface!, ABOUT_FACES) @compile_workload begin about(devnull, FieldInfo) about(devnull, 1) about(devnull, 1.0) about(devnull, nothing) end end
About
https://github.com/tecosaur/About.jl.git
[ "MPL-2.0" ]
1.0.0
3a94c01a1d7678f1c29b7d97216f5046f1ed1768
code
7862
function about(io::IO, fn::Function) source = Main.InteractiveUtils.which(parentmodule(fn), nameof(fn)) methodmodules = getproperty.(methods(fn).ms, :module) others = setdiff(methodmodules, [source]) fn_smry = split(Base.summary(fn), ' ', limit=2) fn_name, fn_extra = if length(fn_smry) == 1 (fn_smry[1], "") else fn_smry end print(io, S"{julia_funcall:$fn_name} $fn_extra\n Defined in {about_module:$source}") if length(others) > 0 print(io, S"{shadow:({emphasis:$(sum(Ref(source) .=== methodmodules))})} extended in ") for (i, oth) in enumerate(others) print(io, S"{about_module:$oth}{shadow:({emphasis:$(sum(Ref(oth) .=== methodmodules))})}") if length(others) == 2 && i == 1 print(io, " and ") elseif length(others) > 2 && i < length(others)-1 print(io, ", ") elseif length(others) > 2 && i == length(others)-1 print(io, ", and ") end end end print(io, ".\n") if !get(io, :about_inner, false) println(io, S"\n {tip:■ Hint:} {grey:to get more information on a particular method try} {light:$(highlight(\"about($fn, argtypes...)\"))}") end end function about(io::IO, @nospecialize(cfn::ComposedFunction)) print(io, S"{bold:Composed function:} ") fnstack = Function[] function decompose!(fnstk, c::ComposedFunction) decompose!(fnstk, c.outer) decompose!(fnstk, c.inner) end decompose!(fnstk, c::Function) = push!(fnstk, c) decompose!(fnstack, cfn) join(io, map(f -> S"{julia_funcall:$f}", fnstack), S" {julia_operator:∘} ") println(io) for fn in fnstack print(io, S" {emphasis:•} ") about(IOContext(io, :about_inner => true), fn) end end function about(io::IO, method::Method) fn, sig = first(method.sig.types).instance, Tuple{map(Base.unwrap_unionall, method.sig.types[2:end])...} show(io, method) println(io) print_effects(io, fn, sig) end function about(io::IO, fn::Function, @nospecialize(argtypes::Type{<:Tuple})) iio = IOContext(io, :about_inner => true) about(iio, fn); println(io) ms = methods(fn, argtypes) if isempty(ms) fncall = highlight("$fn($(join(collect(argtypes.types), ", ")))") println(io, S" {error:!} No methods matched $fncall") return end rinfo = let rtypes = Base.return_types(fn, argtypes) # HACK: this is technically private API unique!(rtypes) for i in eachindex(rtypes), j in eachindex(rtypes) Tᵢ, Tⱼ = rtypes[i], rtypes[j] if Tᵢ <: Tⱼ rtypes[i] = Tⱼ elseif Tⱼ <: Tᵢ rtypes[j] = Tᵢ end end unique!(rtypes) sort!(rtypes, by=length ∘ supertypes) join(map(t -> S"{julia_type:$t}", rtypes), ", ") end println(io, S" Matched {emphasis:$(length(ms))} method$(ifelse(length(ms) > 1, \"s\", \"\")) {julia_type:::} $rinfo") for method in ms mcall, msrc = split(sprint(show, method), " @ ") msrcinfo = match(r"^([A-Z][A-Za-z0-9\.]+) (.+)$", msrc) msrcpretty = if isnothing(msrcinfo) S"{shadow,underline:$msrc}" else mmod, mfile = msrcinfo.captures S"{about_module:$mmod} {shadow,underline:$mfile}" end println(io, S" $(highlight(mcall)) {shadow,bold:@} $msrcpretty") end println(io) about(iio, Base.infer_effects(fn, argtypes)) end struct CompatibleCoreCompilerConstants end function Base.getproperty(::CompatibleCoreCompilerConstants, name::Symbol) if isdefined(Core.Compiler, name) getglobal(Core.Compiler, name) end end const C4 = CompatibleCoreCompilerConstants() function about(io::IO, effects::Core.Compiler.Effects) function effectinfo(io::IO, field::Symbol, name::String, labels::Pair{<:Union{UInt8, Bool, Nothing}, AnnotatedString{String}}...; prefix::AbstractString = "", suffix::AbstractString = "") hasproperty(effects, field) || return value = getproperty(effects, field) icon, accent = if value === C4.ALWAYS_TRUE || value === true '✔', :success elseif value === C4.ALWAYS_FALSE || value === false '✗', :error else '~', :warning end msg = S"{bold,italic,grey:???}" for (id, label) in labels if id == value msg = label break end end name_pad_width = 13 dispwidth = last(displaysize(io)) declr = S" {bold,$accent:$icon $(rpad(name, name_pad_width))} " get(io, :about_inner, false) === true && print(io, ' ') print(io, declr) indent = name_pad_width + 5 desc = S"{grey:$prefix$(ifelse(isempty(prefix), \"\", \" \"))$msg$(ifelse(isempty(suffix), \"\", \" \"))$suffix}" desclines = wraplines(desc, dispwidth - indent, indent) for (i, line) in enumerate(desclines) i > 1 && print(io, ' '^indent) println(io, line) end end get(io, :about_inner, false) === true && print(io, ' ') println(io, S"{bold:Method effects}") effectinfo(io, :consistent, "consistent", C4.ALWAYS_TRUE => S"guaranteed to", C4.ALWAYS_FALSE => S"{italic:might} not", C4.CONSISTENT_IF_NOTRETURNED => S"when the return value {italic:never} involves newly allocated mutable objects, will", C4.CONSISTENT_IF_INACCESSIBLEMEMONLY => S"when {code:inaccessible memory only} is also proven, will", suffix = "return or terminate consistently") effectinfo(io, :effect_free, "effect free", C4.ALWAYS_TRUE => S"guaranteed to be", C4.ALWAYS_FALSE => S"{italic:might} not be", C4.EFFECT_FREE_IF_INACCESSIBLEMEMONLY => S"when {code:inaccessible memory only} is also proven, is", suffix = "free from externally semantically visible side effects") effectinfo(io, :nothrow, "no throw", true => S"guaranteed to {italic:never}", false => S"{italic:may}", suffix = "throw an exception") effectinfo(io, :terminates, "terminates", true => S"guaranteed to", false => S"{italic:might} not", suffix = "always terminate") effectinfo(io, :notaskstate, "no task state", true => S"guaranteed not to access task state (allowing migration between tasks)", false => S"{italic:may} access task state (preventing migration between tasks)") effectinfo(io, :inaccessiblememonly, "inaccessible memory only", C4.ALWAYS_TRUE => S"guaranteed to {italic:never} access or modify externally accessible mutable memory", C4.ALWAYS_FALSE => S"{italic:may} access or modify externally accessible mutable memory", C4.INACCESSIBLEMEM_OR_ARGMEMONLY => S"{italic:may} access or modify mutable memory {italic:iff} pointed to by its call arguments") effectinfo(io, :noub, "no undefined behaviour", C4.ALWAYS_TRUE => S"guaranteed to {italic:never}", C4.ALWAYS_FALSE => S"{italic:may}", C4.NOUB_IF_NOINBOUNDS => S"so long as {code,julia_macro:@inbounds} is not used or propagated, will not", suffix = "execute undefined behaviour") effectinfo(io, :nonoverlayed, "non-overlayed", true => S"{italic:never} calls any methods from an overlayed method table", false => S"{italic:may} call methods from an overlayed method table") end about(io::IO, fn::Function, sig::NTuple{N, <:Type}) where {N} = about(io, fn, Tuple{sig...}) about(io::IO, fn::Function, sig::Type...) = about(io, fn, sig)
About
https://github.com/tecosaur/About.jl.git
[ "MPL-2.0" ]
1.0.0
3a94c01a1d7678f1c29b7d97216f5046f1ed1768
code
4360
struct FieldInfo i::Int face::Union{Symbol, Face} offset::Int size::Int contentsize::Int ispointer::Bool name::Union{Symbol, Int} type::Type end function structinfo(T::Type) map(1:fieldcount(T)) do i if hassizeof(T) offset = fieldoffset(T, i) |> Int size = Int(if i < fieldcount(T) fieldoffset(T, i+1) else sizeof(T) end - fieldoffset(T, i)) contentsize = if hassizeof(fieldtype(T, i)) sizeof(fieldtype(T, i)) else 0 end if contentsize > size # Pointer? contentsize = 0 end else offset = size = contentsize = -1 # Cannot deduce easily end FieldInfo(i, FACE_CYCLE[i % length(FACE_CYCLE) + 1], offset, size, contentsize, contentsize == 0, # ispointer fieldname(T, i), fieldtype(T, i)) end end function about(io::IO, type::Type) if isprimitivetype(type) print(io, "Primitive ") elseif isconcretetype(type) print(io, "Concrete ") if Base.datatype_haspadding(type) print(io, S"{shadow:(padded)} ") end elseif isabstracttype(type) print(io, "Abstract ") end if Base.issingletontype(type) print(io, "singleton ") end print(io, Base.summary(type)) print(io, S" defined in {about_module:$(parentmodule(type))}, ") hassizeof(type) && print(io, "$(join(humansize(sizeof(type))))") print(io, "\n ") supertypeinfo(io, type) (!isstructtype(type) || fieldcount(type) == 0) && return println(io, S"\n\nStruct with {bold:$(fieldcount(type))} fields:") fieldinfo = AnnotatedString[] if type isa DataType sinfo = structinfo(type) namepad = maximum(fi -> textwidth(string(fi.name)), sinfo) + 1 for (; face, name, type, ispointer) in sinfo push!(fieldinfo, rpad(S"{$face:$name}", namepad) * S"{about_pointer:$(ifelse(ispointer, \"*\", \" \"))}$type") end else for (; name, type) in structinfo(type) push!(fieldinfo, S"$name{shadow:::$type}") end end if length(fieldinfo) < 32 columnlist(io, fieldinfo, maxcols=1) else columnlist(io, fieldinfo, spacing=3) end if type isa DataType memorylayout(io, type) end end function supertypeinfo(io::IO, type::Type) typestr(t) = highlight(sprint(show, Base.unwrap_unionall(t))) join(io, map(typestr, supertypes(type)), S" {julia_comparator:<:} ") end function memorylayout(io::IO, type::DataType) hassizeof(type) || return si = structinfo(type) !isempty(si) || return memstep = memstep = gcd((getfield.(si, :size), getfield.(si, :contentsize)) |> Iterators.flatten |> collect) memscale = max(1, floor(Int, 70/(sizeof(type)/memstep))) bars = AnnotatedString[] descs = AnnotatedString[] for (; i, size, contentsize, ispointer) in si size <= 0 && continue color = FACE_CYCLE[i % length(FACE_CYCLE) + 1] width = max(2, memscale * size÷memstep) fsize, funits = humansize(size) desc = if ispointer cpad(S" {$color,bold:*} ", width) elseif contentsize < size csize, cunits = humansize(contentsize) psize, punits = humansize(size - contentsize) cpad(S" {$color:$csize$cunits}{shadow:+$psize$punits} ", width, ' ', RoundUp) else cpad(S" {$color:$fsize$funits} ", width) end push!(descs, desc) width = textwidth(desc) contentwidth = round(Int, width * contentsize / size) bar = S"{$color:$('■'^contentwidth)}" if contentsize < size paddwidth = width - contentwidth if ispointer bar *= S"{about_pointer,light:$('■'^paddwidth)}" else bar *= S"{shadow:$('■'^paddwidth)}" end end push!(bars, bar) end println(io) multirow_wrap(io, permutedims(hcat(bars, descs))) if any(i -> i.ispointer, si) println(io, S"\n {about_pointer,bold:*} = {about_pointer:Pointer} {light:(8B)}") end end
About
https://github.com/tecosaur/About.jl.git
[ "MPL-2.0" ]
1.0.0
3a94c01a1d7678f1c29b7d97216f5046f1ed1768
code
5146
const FACE_CYCLE = [:about_cycle1, :about_cycle2, :about_cycle3, :about_cycle4] function humansize(bytes::Integer) units = ("B", "kB", "MB", "GB") magnitude = floor(Int, log(1024, 1 + bytes)) if 10 < bytes < 10*1024^magnitude round(bytes / 1024^magnitude, digits=1) else round(Int, bytes / 1024^magnitude) end, units[1+magnitude] end function hassizeof(type::Type) !isconcretetype(type) && return false @static if VERSION >= v"1.11-alpha" type <: GenericMemory && return false end type in (Symbol, String, Core.SimpleVector) && return false true end function cpad(s, n::Integer, pad::Union{AbstractString, AbstractChar}=' ', r::RoundingMode = RoundToZero) rpad(lpad(s, div(n+textwidth(s), 2, r), pad), n, pad) end splural(n::Int) = ifelse(n == 1, "", "s") splural(c::Vector) = splural(length(c)) function struncate(str::AbstractString, maxwidth::Int, joiner::Union{AbstractString, AbstractChar} = '…', mode::Symbol = :center) textwidth(str) <= maxwidth && return str left, right = firstindex(str), lastindex(str) width = textwidth(joiner) while true if mode ∈ (:right, :center) (width += textwidth(str[left])) <= maxwidth || break left = nextind(str, left) end if mode ∈ (:left, :center) && width < maxwidth (width += textwidth(str[right])) <= maxwidth || break right = prevind(str, right) end end str[begin:prevind(str, left)] * joiner * str[nextind(str, right):end] end function columnlist(io::IO, entries::Vector{<:AbstractString}; maxcols::Int=8, maxwidth::Int=last(displaysize(io)), prefix::AbstractString = S"{emphasis:•} ", spacing::Int=2) isempty(entries) && return thecolumns = Vector{eltype(entries)}[] thecolwidths = Int[] for ncols in 1:maxcols columns = Vector{eltype(entries)}[] for col in Iterators.partition(entries, div(length(entries), ncols, RoundUp)) push!(columns, collect(col)) end widths = map.(textwidth, columns) colwidths = map(maximum, widths) layoutwidth = sum(colwidths) + ncols * textwidth(prefix) + (ncols - 1) * spacing if layoutwidth > maxwidth break else thecolumns, thecolwidths = columns, colwidths end end for rnum in 1:length(first(thecolumns)) for cnum in 1:length(thecolumns) rnum > length(thecolumns[cnum]) && continue cnum > 1 && print(io, ' '^spacing) print(io, prefix, rpad(thecolumns[cnum][rnum], thecolwidths[cnum])) end println(io) end end function multirow_wrap(io::IO, cells::Matrix{<:AbstractString}; indent::AbstractString = " ", maxwidth::Int=last(displaysize(io))) widths = map(textwidth, cells) colwidths = maximum(widths, dims=1) thiscol = textwidth(indent) segments = UnitRange{Int}[1:0] for (i, (col, width)) in enumerate(zip(eachcol(cells), colwidths)) if thiscol + width > maxwidth push!(segments, last(last(segments))+1:i-1) thiscol = textwidth(indent) + width else thiscol += width end end push!(segments, last(last(segments))+1:size(cells, 2)) filter!(!isempty, segments) for segment in segments for row in eachrow(cells[:, segment]) println(io, indent, join(row)) end end end """ wraplines(content::AnnotatedString, width::Integer = 80, column::Integer = 0) Wrap `content` into a vector of lines of at most `width` (according to `textwidth`), with the first line starting at `column`. """ function wraplines(content::Union{Annot, SubString{<:Annot}}, width::Integer = 80, column::Integer = 0) where { Annot <: AnnotatedString} s, lines = String(content), SubString{Annot}[] i, lastwrap, slen = firstindex(s), 0, ncodeunits(s) most_recent_break_opportunity = 1 while i < slen if isspace(s[i]) && s[i] != '\n' most_recent_break_opportunity = i elseif s[i] == '\n' push!(lines, content[nextind(s, lastwrap):prevind(s, i)]) lastwrap = i column = 0 elseif column >= width && most_recent_break_opportunity > 1 if lastwrap == most_recent_break_opportunity nextbreak = findfirst(isspace, @view s[nextind(s, lastwrap):end]) if isnothing(nextbreak) break else most_recent_break_opportunity = lastwrap + nextbreak end i = most_recent_break_opportunity else i = nextind(s, most_recent_break_opportunity) end push!(lines, content[nextind(s, lastwrap):prevind(s, most_recent_break_opportunity)]) lastwrap = most_recent_break_opportunity column = 0 end column += textwidth(s[i]) i = nextind(s, i) end if lastwrap < slen push!(lines, content[nextind(s, lastwrap):end]) end lines end
About
https://github.com/tecosaur/About.jl.git
[ "MPL-2.0" ]
1.0.0
3a94c01a1d7678f1c29b7d97216f5046f1ed1768
code
27519
# ------------------ # Structs, in general # ------------------ function about(io::IO, value::T) where {T} # Type information iotype = AnnotatedIOBuffer() print(iotype, Base.summary(value)) ismutable(value) && print(iotype, " (mutable)") print(iotype, S" ({julia_comparator:<:} ") supertypeinfo(iotype, supertype(T)) print(iotype, ")") infotype = read(seekstart(iotype), AnnotatedString) # Size information typesize = try sizeof(T) catch _ sizeof(value) end datasize = sizeof(value) netsize = Base.summarysize(value) infosize = if typesize == datasize == netsize S"{about_bytes:$(join(humansize(typesize)))}." elseif typesize == datasize <= netsize S"{about_bytes:$(join(humansize(typesize)))} directly \ (referencing {about_bytes:$(join(humansize(netsize)))} in total)" elseif typesize == datasize > netsize S"{about_bytes:$(join(humansize(typesize)))} directly \ ({warning:!} referencing {about_bytes:$(join(humansize(netsize)))} in total, \ {warning:strangely less than the direct, \ {underline,link={https://github.com/tecosaur/About.jl}:\ please open an issue on About.jl with this example}})" else # all different S"{about_bytes:$(join(humansize(typesize)))} directly \ (referencing {about_bytes:$(join(humansize(netsize)))} in total, \ holding {about_bytes:$(join(humansize(datasize)))} of data)" end print(io, infotype) if textwidth(infotype) < last(displaysize(io)) && textwidth(infotype) + textwidth(infosize) + 12 >= last(displaysize(io)) print(io, "\n Memory footprint: ") else print(io, ", occupies ") end println(io, infosize) # Layout + elaboration memorylayout(io, value) if get(io, :compact, false) != true elaboration(io, value) end end function memorylayout(io::IO, value::T) where {T} if isprimitivetype(T) get(io, :compact, false) || print(io, "\n ") print(io, bitstring(value)) return end if get(io, :compact, false) == true print(io, "«struct»") return end if Base.issingletontype(T) println(io, S"{italic:singelton}") return end sinfo = structinfo(T) isempty(sinfo) && return ffaces = Union{Face, Symbol}[] fnames = String[] ftypes = String[] fsizes = String[] freprs = AnnotatedString[] fshows = AnnotatedString[] for (; face, name, type, size, ispointer) in sinfo size <= 0 && continue push!(ffaces, face) push!(fnames, string(name)) push!(ftypes, string(type)) push!(fsizes, join(humansize(size))) aio = AnnotatedIOBuffer() fvalue = getfield(value, name) if Base.issingletontype(typeof(fvalue)) push!(freprs, S"{shadow:singleton}") elseif size == 0 push!(freprs, S"{error:??}") elseif ispointer try pt = pointer(fvalue) push!(freprs, S"{about_pointer:@ $(sprint(show, UInt64(pt)))}") catch push!(freprs, S"{about_pointer:Ptr?}") end else memorylayout(IOContext(aio, :compact => true), fvalue) push!(freprs, read(seekstart(aio), AnnotatedString)) end truncate(aio, 0) show(IOContext(aio, :compact => true), fvalue) push!(fshows, read(seekstart(aio), AnnotatedString)) end width = last(displaysize(io)) - 2 namewidth = maximum(textwidth, fnames, init=0) typewidth = min(maximum(textwidth, ftypes, init=0), width ÷ 4) sizewidth = maximum(textwidth, fsizes, init=0) width -= 1 + namewidth + 1 + typewidth + 2 + sizewidth reprwidth = min((2 * width) ÷ 3, maximum(textwidth, freprs, init=0)) showwidth = width - reprwidth for (face, name, type, size, brepr, shown) in zip(ffaces, fnames, ftypes, fsizes, freprs, fshows) println(io, ' ', S"{$face:$(lpad(name, namewidth)){shadow:::}$(rpad(struncate(type, typewidth, \"…\", :right), typewidth)) $(lpad(size, sizewidth))}", ' ', rpad(struncate(brepr, reprwidth, S" {shadow:…} "), reprwidth), ' ', face!(struncate(shown, showwidth, S" {shadow:…} "), face)) end memorylayout(io, T) end # ------------------ # Modules # ------------------ function about(io::IO, mod::Module) pkg = nothing for (bpkg, m) in Base.loaded_modules if m == mod pkg = bpkg break end end !isnothing(pkg) && !applicable(about_pkg, io, pkg, mod) && Base.require(Base.PkgId(Base.UUID("44cfe95a-1eb2-52ea-b672-e2afdf69b78f"), "Pkg")) print(io, S"{bold:Module {about_module:$mod}}") if !isnothing(pkg) println(io, S" {shadow:[$(something(pkg.uuid, \"no uuid\"))]}") Base.invokelatest(about_pkg, io, pkg, mod) else println(io) end function classify(m::Module, name::Symbol) val = getglobal(mod, name) order, kind, face, parent = if val isa Module 0, :module, :about_module, val elseif val isa Function && first(String(name)) == '@' 1, :macro, :julia_macro, parentmodule(val) elseif val isa Function 2, :function, :julia_funcall, parentmodule(val) elseif val isa Type 3, :type, :julia_type, if val isa UnionAll || val isa Union m else parentmodule(val) end else 4, :value, :julia_identifier, if Base.issingletontype(typeof(val)) parentmodule(typeof(m)) else m end end while parentmodule(parent) ∉ (parent, Main) parent = parentmodule(parent) end (; name, str = S"{code,$face:$name}", kind, parent, order) end classify(m::Module, names::Vector{Symbol}) = sort(map(Base.Fix1(classify, m), names), by=x->x.order) allnames = classify(mod, names(mod)) exports = similar(allnames, 0) reexports = similar(allnames, 0) publics = similar(allnames, 0) for exp in allnames if exp.parent === mod && Base.isexported(mod, exp.name) push!(exports, exp) elseif exp.parent === mod && Base.ispublic(mod, exp.name) push!(publics, exp) elseif exp.parent !== mod push!(reexports, exp) end end if !isempty(exports) println(io, S"\n{bold:Exports {emphasis:$(length(exports))} name$(splural(exports)):}") columnlist(io, map(x->x.str, exports)) end if !isempty(reexports) parents = join(sort(map(p->S"{about_module:$p}", unique(map(x->x.parent, reexports)))), ", ") println(io, S"\n{bold:Re-exports {emphasis:$(length(reexports))} name$(splural(reexports))} (from $parents){bold::}") columnlist(io, map(x->x.str, reexports)) end if !isempty(publics) println(io, S"\n{bold:Public API ({emphasis:$(length(publics))} name$(splural(publics))):}") columnlist(io, map(x->x.str, publics)) end end function about_pkg end # Implemented in `../ext/PkgExt.jl` # ------------------ # Numeric types # ------------------ const NUMBER_BIT_FACES = ( sign = :bright_blue, exponent = :bright_green, mantissa = :bright_red ) function memorylayout(io::IO, value::Bool) bits = AnnotatedString(bitstring(value)) face!(bits[1:end-1], :shadow) face!(bits[end:end], NUMBER_BIT_FACES.sign) if get(io, :compact, false) == true print(io, bits) else println(io, "\n ", bits, S" {bold:=} $value") end end function memorylayout(io::IO, value::Union{UInt8, UInt16, UInt32, UInt64, UInt128}) bits = AnnotatedString(bitstring(value)) for (; match) in eachmatch(r"0+", bits) face!(match, :shadow) end if get(io, :compact, false) == true print(io, bits) else println(io, "\n ", bits, ifelse(sizeof(value) > 4, "\n", ""), S" {bold:=} $value") end end function memorylayout(io::IO, value::Union{Int8, Int16, Int32, Int64, Int128}) bits = AnnotatedString(bitstring(value)) face!(bits[1:1], NUMBER_BIT_FACES.sign) for (; match) in eachmatch(r"0+", bits) if match.offset == 0 match = bits[2:match.ncodeunits] end face!(match, :shadow) end if get(io, :compact, false) == true print(io, bits) else signstr = ifelse(value < 0, '-', '+') println(io, "\n ", bits, ifelse(sizeof(value) > 4, "\n", ""), S" {bold:=} {$(NUMBER_BIT_FACES.sign):$signstr}$(abs(value))") end end memorylayout(io::IO, float::Float64) = floatlayout(io, float, 11) memorylayout(io::IO, float::Float32) = floatlayout(io, float, 8) memorylayout(io::IO, float::Float16) = floatlayout(io, float, 5) @static if VERSION >=v"1.11-alpha" memorylayout(io::IO, float::Core.BFloat16) = floatlayout(io, float, 8) end function floatlayout(io::IO, float::AbstractFloat, expbits::Int) fsign, fexp, fmant = NUMBER_BIT_FACES.sign, NUMBER_BIT_FACES.exponent, NUMBER_BIT_FACES.mantissa bitstr = bitstring(float) hl_bits = S"{$fsign:$(bitstr[1])}{$fexp:$(bitstr[2:expbits+1])}{$fmant:$(bitstr[expbits+2:end])}" if get(io, :compact, false) == true print(io, hl_bits) else fracbits = 8 * sizeof(float) - expbits - 1 fracdp = round(Int, log10(2 ^ (fracbits + 1))) maxexp = 2^(expbits - 1) - 1 sign = ifelse(bitstr[1] == '1', '-', '+') bits = reinterpret(UInt64, Float64(float)) exponent = Int((bits >> 52) & Base.Ryu.EXP_MASK) - 1023 fraction = reinterpret(Float64, bits & Base.Ryu.MANTISSA_MASK | 0x3ff0000000000000) expstr = cpad(if exponent == 1024 "Inf" else "2^$exponent" end, expbits - 1, ' ', RoundUp) fracstr = cpad(if exponent == 1024 ifelse(fraction == 1.0, "1", "NaN") else Base.Ryu.writefixed(fraction, fracdp + 2) end, fracbits, ' ', RoundUp) hl_info = let eleft = (expbits - 3) ÷ 2 eright = (expbits - 3) - eleft fleft = (fracbits - 3) ÷ 2 fright = (fracbits - 3) - fleft S"{$fsign:╨}{$fexp:└$('─'^eleft)┬$('─'^eright)┘}{$fmant:└$('─'^fleft)┬$('─'^fright)┘}" end hl_vals = S"{$fsign,bold:$sign}{$fexp:$expstr}{bold:×}{$fmant:$fracstr}" hl_more = S" {$fexp:exponent}$(' '^17){$fmant:mantissa / fraction}" println(io, "\n ", hl_bits, " \n ", hl_info, "\n ", hl_vals, S"\n {bold:=} ", if -8 < exponent < 8 Base.Ryu.writefixed(float, fracdp) else Base.Ryu.writeexp(float, fracdp) end) end end # ------------------ # Vector/Memory # ------------------ function vecbytes(io::IO, items::DenseVector{T}; elshowfn::Function = show, eltext = "item", topbar::NamedTuple = (lcap='┌', lbar='╴', bar='─', rbar='╶', rcap='┐', trunc='⋯'), itemfaces::Vector{Symbol} = FACE_CYCLE, byteface::Symbol = :light, bitcolour::Bool = false, bytevals::Bool = T != UInt8) where {T} nitems = length(items) bytes = reinterpret(UInt8, items) nbytes = length(bytes) if nbytes == 1 println(io, "\n ", bitstring(first(bytes)), "\n ", "└──────┘") return end itemoverbar = '┌' * '─'^(8 * sizeof(T) - 2) * '┐' margintextwidth = 4 + textwidth(eltext) + ndigits(nbytes) showbytes = if last(displaysize(io)) - 2 - margintextwidth >=8 * nbytes nbytes else (last(displaysize(io)) - 2 - ndigits(nbytes) - textwidth("⋯(×)⋯") - margintextwidth) ÷ 8 end lbytes, rbytes = showbytes ÷ 2, showbytes - showbytes ÷ 2 litems, ritems = lbytes ÷ sizeof(T), rbytes ÷ sizeof(T) print(io, "\n ") function fmtitem(val, idx) truncval = struncate(sprint(elshowfn, val), 8 * sizeof(T) - 4, topbar.trunc) padval = cpad(topbar.lbar * truncval * topbar.rbar, 8 * sizeof(T) - 2, topbar.bar) tbar = topbar.lcap * padval * topbar.rcap face = itemfaces[mod1(idx, length(itemfaces))] S"{$face:$tbar}" end for litem in 1:litems print(io, fmtitem(items[litem], litem)) end if showbytes < nbytes lbar = 8 * (lbytes - litems * sizeof(T)) - 1 facel = itemfaces[mod1(litems + 1, length(itemfaces))] lbar > 0 && print(io, S"{$facel:$(topbar.rcap)$(topbar.bar^lbar)}") print(io, S" {shadow:⋯(×$(lpad(nitems-litems-ritems, ndigits(nbytes-showbytes))))⋯} ") rbar = 8 * (rbytes - ritems * sizeof(T)) - 1 facer = itemfaces[mod1(nitems - ritems, length(itemfaces))] rbar > 0 && print(io, S"{$facer:$(topbar.bar^rbar)$(topbar.rcap)}") elseif litems + ritems < nitems face = itemfaces[mod1(litems + 1, length(itemfaces))] print(io, fmtitem(items[litems + 1], litems + 1)) end for ritem in nitems-ritems+1:nitems face = FACE_CYCLE[mod1(ritem, length(FACE_CYCLE))] print(io, fmtitem(items[ritem], ritem)) end print(io, S" {emphasis:$(lpad(nitems, ndigits(nbytes)))} $eltext$(splural(nitems))") lbstring = AnnotatedString(join(map(bitstring, bytes[1:lbytes]))) rbstring = AnnotatedString(join(map(bitstring, bytes[end-rbytes+1:end]))) if bitcolour for b in 1:lbytes face!(lbstring[8*(b-1)+1:8*b], itemfaces[mod1(b, length(itemfaces))]) end for b in 1:rbytes face!(rbstring[8*(b-1)+1:8*b], itemfaces[mod1(b + nbytes - rbytes, length(itemfaces))]) end end for bstr in (lbstring, rbstring), (; match) in eachmatch(r"0+", bstr) face!(match, :shadow) end print(io, "\n ", lbstring, if showbytes < nbytes ' '^(7 + ndigits(nbytes-showbytes)) else "" end, rbstring) if bytevals print(io, ' '^ndigits(nbytes), S" {shadow:in}\n ") function fmtbyte(b, _itemidx) S"{$byteface:└─0x$(lpad(string(b, base=16), 2, '0'))─┘}" end for b in 1:lbytes print(io, fmtbyte(bytes[b], fld1(b, sizeof(T)))) end showbytes < nbytes && print(io, S" {shadow:⋯(×$(nbytes-showbytes))⋯} ") for b in nbytes-rbytes+1:nbytes print(io, fmtbyte(bytes[b], fld1(b, sizeof(T)))) end print(io, S" {emphasis:$nbytes} byte$(splural(nbytes))") end println(io) end @static if VERSION >= v"1.11-alpha" function memorylayout(io::IO, mem::GenericMemory{kind, T, addrspace}) where {kind, T, addrspace} if mem.length == 0 println(io, S" {shadow:(empty)} {about_pointer:@ $(sprint(show, UInt64(mem.ptr)))}") return end println(io, "\n ", if kind === :atomic "Atomic memory block" else "Memory block" end, if addrspace !== Core.CPU addressor = (((::Core.AddrSpace{T}) where {T}) -> T)(addrspace) |> nameof |> String S" ({emphasis:$addressor}-addressed)" else S" ({emphasis:CPU}-addressed)" end, S" from {about_pointer:$(sprint(show, UInt64(mem.ptr)))} to {about_pointer:$(sprint(show, UInt64(mem.ptr + mem.length * sizeof(T))))}.") vecbytes(io, mem) end end # ------------------ # Char/String # ------------------ function memorylayout(io::IO, char::Char) chunks = reinterpret(NTuple{4, UInt8}, reinterpret(UInt32, char) |> hton) get(io, :compact, false) || print(io, "\n ") nchunks = something(findlast(!iszero, chunks), 1) byte0leading = [1, 3, 4, 5][nchunks] ucodepoint = if Base.isoverlong(char) Base.decode_overlong(char) else codepoint(char) end bit_spreads = [[3, 4], [3, 4, 4], [4, 4, 4, 4], [1, 4, 4, 4, 4, 4] ][nchunks] ubytes = collect(uppercase(string( ucodepoint, base=16, pad = length(bit_spreads)))) overlong_bytes = if Base.isoverlong(char) 1:min(something(findfirst(==('1'), ubytes), length(ubytes)) - 1, length(ubytes) - 2) else 1:0 end chunk_coloring = [Pair{UnitRange{Int}, Symbol}[] for _ in 1:length(chunks)] ustr = S"{bold:U+$(lpad(join(ubytes), 4, '0'))}" for (i, b, color) in zip(1:length(ubytes), collect(eachindex(ustr))[end-length(ubytes)+1:end], Iterators.cycle(Iterators.reverse(FACE_CYCLE))) if i in overlong_bytes color = :error # overlong end face!(ustr[b:b], color) end if get(io, :compact, false) == true print(io, ustr, ' ') else let current_bit = byte0leading print(io, ' '^byte0leading) for (i, ubyte, nbits, color) in zip(1:length(ubytes), ubytes, bit_spreads, Iterators.cycle(Iterators.reverse(FACE_CYCLE))) if i in overlong_bytes color = :error # overlong end does_byte_jump = current_bit ÷ 8 < (current_bit + nbits) ÷ 8 clean_jump = does_byte_jump && (current_bit + nbits) % 8 == 0 next_bit = current_bit + nbits + does_byte_jump * 2 width = nbits + 3 * (does_byte_jump && !clean_jump) byte_brace = if width <= 2 lpad(ubyte, width) else '┌' * cpad(ubyte, width-2, '─') * '┐' end print(io, S"{$color:$byte_brace}") clean_jump && print(io, " ") if does_byte_jump && !clean_jump push!(chunk_coloring[1 + current_bit ÷ 8], (1 + current_bit % 8):8 => color) push!(chunk_coloring[1 + next_bit ÷ 8], 3:mod1(next_bit, 8) => color) else push!(chunk_coloring[1 + current_bit ÷ 8], (1 + current_bit % 8):mod1(current_bit + nbits, 8) => color) end current_bit = next_bit end print(io, "\n ") end end for (i, (chunk, coloring)) in enumerate(zip(chunks, chunk_coloring)) cbits = bitstring(chunk) cstr = if i > nchunks S"{shadow:$cbits}" else leadingbits = if i == 1; byte0leading else 2 end leading = cbits[1:leadingbits] rest = AnnotatedString(cbits[leadingbits+1:end]) for (; match) in eachmatch(r"1+", rest) face!(match, :underline) end cstr = S"{shadow:$leading}$rest" for (range, color) in coloring face!(cstr, range, color) end cstr end print(io, cstr, ' ') end if get(io, :compact, false) != true println(io) for chunk in chunks byte = lpad(string(chunk, base=16), 2, '0') print(io, S" {shadow:└─0x$(byte)─┘}") end print(io, "\n = ", ustr) Base.isoverlong(char) && print(io, S" {error:[overlong]}") println(io) end end const CONTROL_CHARACTERS = ('\x00' => ("NULL", "Null character", "Originally the code of blank paper tape and used as padding to slow transmission. Now often used to indicate the end of a string in C-like languages."), '\x01' => ("SOH", "Start of Heading", ""), '\x02' => ("SOT", "Start of Text", ""), '\x03' => ("ETX", "End of Text", ""), '\x04' => ("EOT", "End of Transmission", ""), '\x05' => ("ENQ", "Enquiry", "Trigger a response at the receiving end, to see if it is still present."), '\x06' => ("ACK", "Acknowledge", "Indication of successful receipt of a message."), '\x07' => ("BEL", "Bell", "Call for attention from an operator."), '\x08' => ("HBS", "Backspace", "Move one position leftwards. Next character may overprint or replace the character that was there."), '\x09' => ("HT", "Horizontal Tab", "Move right to the next tab stop."), '\x0a' => ("LF", "Line Feed", "Move down to the same position on the next line (some devices also moved to the left column)."), '\x0b' => ("VT", "Vertical Tab", "Move down to the next vertical tab stop. "), '\x0c' => ("FF", "Form Feed", "Move down to the top of the next page. "), '\x0d' => ("CR", "Carriage Return", "Move to column zero while staying on the same line."), '\x0e' => ("SO", "Shift Out", "Switch to an alternative character set."), '\x0f' => ("SI", "Shift In", "Return to regular character set after SO."), '\x10' => ("DLE", "Data Link Escape", "Cause a limited number of contiguously following characters to be interpreted in some different way."), '\x11' => ("DC1", "Device Control One (XON)", "Used by teletype devices for the paper tape reader and tape punch. Became the de-facto standard for software flow control, now obsolete."), '\x12' => ("DC2", "Device Control Two", "Used by teletype devices for the paper tape reader and tape punch. Became the de-facto standard for software flow control, now obsolete."), '\x13' => ("DC3", "Device Control Three (XOFF)", "Used by teletype devices for the paper tape reader and tape punch. Became the de-facto standard for software flow control, now obsolete."), '\x14' => ("DC4", "Device Control Four", "Used by teletype devices for the paper tape reader and tape punch. Became the de-facto standard for software flow control, now obsolete."), '\x15' => ("NAK", "Negative Acknowledge", "Negative response to a sender, such as a detected error. "), '\x16' => ("SYN", "Synchronous Idle", "A transmission control character used by a synchronous transmission system in the absence of any other character (idle condition) to provide a signal from which synchronism may be achieved or retained between data terminal equipment."), '\x17' => ("ETB", "End of Transmission Block", "End of a transmission block of data when data are divided into such blocks for transmission purposes."), '\x18' => ("CAN", "Cancel", "A character, or the first character of a sequence, indicating that the data preceding it is in error. As a result, this data is to be ignored. The specific meaning of this character must be defined for each application and/or between sender and recipient."), '\x19' => ("EM", "End of Medium", "Indicates on paper or magnetic tapes that the end of the usable portion of the tape had been reached."), '\x1a' => ("SUB", "Substitute/Control-Z", "A control character used in the place of a character that has been found to be invalid or in error. SUB is intended to be introduced by automatic means."), '\x1b' => ("ESC", "Escape", "A control character which is used to provide additional control functions. It alters the meaning of a limited number of contiguously following bit combinations. The use of this character is specified in ISO-2022."), '\x1c' => ("FS", "File Separator", "Used to separate and qualify data logically; its specific meaning has to be specified for each application. If this character is used in hierarchical order, it delimits a data item called a file. "), '\x1d' => ("GS", "Group Separator", "Used to separate and qualify data logically; its specific meaning has to be specified for each application. If this character is used in hierarchical order, it delimits a data item called a group."), '\x1e' => ("RG", "Record Separator", "Used to separate and qualify data logically; its specific meaning has to be specified for each application. If this character is used in hierarchical order, it delimits a data item called a record."), '\x1f' => ("US", "Unit Separator", "Used to separate and qualify data logically; its specific meaning has to be specified for each application. If this character is used in hierarchical order, it delimits a data item called a unit."), '\x7f' => ("DEL", "Delete", "Originally used to delete characters on punched tape by punching out all the holes.")) function elaboration(io::IO, char::Char) c0index = findfirst(c -> first(c) == char, CONTROL_CHARACTERS) stychr = S"{julia_char:$(sprint(show, char))}" if !isnothing(c0index) cshort, cname, cinfo = last(CONTROL_CHARACTERS[c0index]) println(io, "\n Control character ", stychr, ": ", cname, " ($cshort)", ifelse(isempty(cinfo), "", "\n "), cinfo) elseif isascii(char) kind = if char in 'a':'z' "lowercase letter" elseif char in 'A':'Z' "uppercase letter" elseif char in '0':'9' "numeral" elseif char == ' ' "space" elseif char in ('(', ')', '[', ']', '{', '}', '«', '»') "parenthesis" elseif char in ('!':'/'..., ':':'@'..., '\\', '^', '_', '`', '|', '~') "punctuation" end println(io, "\n ASCII $kind ", stychr) elseif char in ('Ç':'ø'..., 'Ø', 'á':'Ñ'..., 'Á':'À', 'ã', 'Ã', 'ð':'Ï'..., 'Ó':'Ý') println(io, "\n Extended ASCII accented letter ", stychr, S" ({julia_number:0x$(string(UInt8(char), base=16))})") elseif Base.isoverlong(char) elseif codepoint(char) in 128:255 println(io, "\n Extended ASCII symbol ", stychr, S" ({shadow:0x$(string(Int(char), base=16))})") else catstr = Base.Unicode.category_string(char) catabr = Base.Unicode.category_abbrev(char) println(io, S"\n Unicode $stychr, category: $catstr ($catabr)") end end function elaboration(io::IO, str::String) charfreq = Dict{Char, Int}() for char in str charfreq[char] = get(charfreq, char, 0) + 1 end charset_index = maximum(c -> if Int(c) < 127; 2 elseif Int(c) < 255; 3 else 4 end, keys(charfreq), init = 1) charset = ["None", "ASCII", "Extended ASCII", "Unicode"][charset_index] println(io, S" {emphasis:•} Character set: {emphasis:$charset}") control_character_counts = map( c -> get(charfreq, first(c), 0), CONTROL_CHARACTERS) if !all(iszero, control_character_counts) println(io, S" {emphasis:•} Contains \ {about_count:$(sum(control_character_counts))} \ instances of {about_count:$(sum(>(0), control_character_counts))} \ control characters:") for ((char, info), count) in zip(CONTROL_CHARACTERS, control_character_counts) count > 0 && println(io, S" {emphasis:∗} {julia_char:$(sprint(show, char))} ({about_count:$count}): $(join(info, ' '))") end end if startswith(str, '\ufeff') println(io, S" {emphasis:•} Prefixed by BOM (byte-order mark)") end vecbytes(io, codeunits(str), eltext = "codepoint", elshowfn = (io, c) -> show(io, Char(c)), bitcolour = true, bytevals = false) end # TODO struct
About
https://github.com/tecosaur/About.jl.git
[ "MIT" ]
1.1.1
7560cbf6518c2891fcaa82d082a974701529d101
code
1236
### This is a validation test ### the objective is to show that KPLS can easily fit any curve using the same matrix ### If not, the regressor could be wrong ### Example extracted from a python KPLS implementation: https://github.com/jhumphry/regressions/blob/master/examples/kpls_example.py using PLSRegressor using Gadfly import Random Random.seed!(1) z(x) = 4.26 * (exp.(-x) - 4 * exp.(-2.0*x) + 3 * exp.(-3.0*x)) x_values = range(0.0,step=3.5,length=100) z_pure = z(x_values) noise = randn(100) z_noisy = z_pure + noise X = collect(x_values)[:,:] Y = z_noisy[:,:] #z_pure global min_mae = 10 global best_pred global best_w = 10 global best_g = 10 for g in [1,2], w in range(0.01,step=3,length=10) print(".") model = PLSRegressor.fit(X,Y,centralize=true,nfactors=g,kernel="rbf",width=w) Y_pred = PLSRegressor.predict(model,X) mae = mean(abs.(Y .- Y_pred)) if mae < min_mae min_mae = mae best_pred = Y_pred[:] best_g = g best_w = w end end print("[KPLS] min mae error : $(min_mae)") print("[KPLS] best factor : $(best_g)") print("[KPLS] best width : $(best_w)") plot([Y,best_pred ], x=Row.index, y=Col.value, color=Col.index, Geom.line)
PLSRegressor
https://github.com/lalvim/PLSRegressor.jl.git
[ "MIT" ]
1.1.1
7560cbf6518c2891fcaa82d082a974701529d101
code
1522
using MultivariateStats using PLSRegressor const defdir = PLSRegressor.dir("datasets") function gethousingdata(dir, filename) url = "https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data" mkpath(dir) path = download(url, "$(defdir)/$filename") end function loaddata(test=0.1) filename = "housing.data" file = "$(defdir)/$filename" isfile("$(defdir)/$filename") || gethousingdata(defdir, filename) data = readdlm(file) nfeatures = size(data)[2] - 1 target_idx = size(data)[2] x = data[:, 1:nfeatures] y = data[:, target_idx:target_idx] if test == 0 xtrn = xtst = x ytrn = ytst = y else r = randperm(size(x,1)) # trn/tst split n = round(Int, (1-test) * size(x,1)) xtrn=x[r[1:n], :] ytrn=y[r[1:n], :] xtst=x[r[n+1:end], :] ytst=y[r[n+1:end], :] end (xtrn, [ytrn...], xtst, [ytst...]) end (xtrn, ytrn, xtst, ytst) = loaddata() model = PLSRegressor.fit(xtrn, ytrn, nfactors = 3) pred = PLSRegressor.predict(model, xtst) println("[PLS] mae error :", mean(abs.(ytst .- pred))) # linear least squares from MultiVariateStats sol = llsq(xtrn, ytrn) a, b = sol[1:end-1], sol[end] yp = xtst * a + b println("[LLS] mae error :",mean(abs.(ytst .- yp))) ### if you want to save or load model use this #PLSRegressor.save(model,filename="/tmp/pls_model.jld",modelname="pls_model") #model = PLSRegressor.load(filename="/tmp/pls_model.jld",modelname="pls_model")
PLSRegressor
https://github.com/lalvim/PLSRegressor.jl.git
[ "MIT" ]
1.1.1
7560cbf6518c2891fcaa82d082a974701529d101
code
272
# Partial Least Squares (PLS1 and PLS2 NIPALS version) module PLSRegressor using JLD include("utils.jl") include("types.jl") include("pls1.jl") include("pls2.jl") include("kpls.jl") include("method.jl") dir(path...) = joinpath(dirname(dirname(@__FILE__)),path...) end
PLSRegressor
https://github.com/lalvim/PLSRegressor.jl.git
[ "MIT" ]
1.1.1
7560cbf6518c2891fcaa82d082a974701529d101
code
3833
using LinearAlgebra # A gaussian kernel function @inline function Φ(x::Vector{T}, y::Vector{T}, r::T=1.0) where T<:AbstractFloat n = 1.0 / sqrt(2π*r) s = 1.0 / (2r^2) return n*exp(-s*sum((x.-y).^2)) end # A kernel matrix function ΦΦ(X::AbstractArray{T}, r::T=1.0) where T<:AbstractFloat n = size(X,1) K = zeros(n,n) for i=1:n for j=1:i K[i, j] = Φ(X[i, :], X[j, :],r) K[j, i] = K[i, j] end K[i, i] = Φ(X[i, :], X[i, :],r) end K end # A kernel matrix for test data function ΦΦ(X::AbstractArray{T}, Z::AbstractArray{T}, r::T=1.0) where T<:AbstractFloat (nx,mx) = size(X) (nz,mz) = size(Z) K = zeros(T,nz, nx) for i=1:nz for j=1:nx K[i, j] = Φ(Z[i, :], X[j, :],r) end end K end ## the learning algorithm: KPLS2 - multiple targets function trainer(model::KPLSModel{T}, X::AbstractArray{T}, Y::AbstractArray{T}; ignore_failures = true, tol = 1e-6, max_iterations = 250 ) where T<:AbstractFloat kernel,width = model.kernel,model.width Y = Y[:,:] model.ntargetcols = size(Y,2) nfactors = model.nfactors n = size(X,1) Tj = zeros(T,n, nfactors) Q = zeros(T,model.ntargetcols, nfactors) U = zeros(T,n, nfactors) P = zeros(T,n, nfactors) K = ΦΦ(X,width) # centralize kernel c = Matrix{Float64}(I, n, n) - ones(Float64,n,n).*1.0/n K = c * K * c K_j = K[:,:] for j=1:nfactors u = Y[:,1] iteration_count = 0 iteration_change = tol * 10.0 local w,t,q,old_u while iteration_count < max_iterations && iteration_change > tol w = K * u t = w / norm(w, 2) q = Y' * t old_u = u u = Y * q u /= norm(u, 2) iteration_change = norm(u - old_u) iteration_count += 1 end if iteration_count >= max_iterations if ignore_failures nfactors = j warn("KPLS: Found with less factors. Overall factors = $(nfactors)") break else error("KPLS: failed to converge for component: $(nfactors+1)") end end Tj[:, j] = t Q[:, j] = q U[:, j] = u P[:, j] = (K_j' * w) / (w'w) deflator = Matrix{Float64}(I, n, n) .- t'*t K_j = deflator * K_j * deflator Y = Y - t * q' end # If iteration stopped early because of failed convergence, only # the actual components will be copied Tj = Tj[:, 1:nfactors] Q = Q[:, 1:nfactors] U = U[:, 1:nfactors] #P = P[:, 1:nfactors] model.nfactors = nfactors model.X = X # unfortunately it is necessary on the prediction phase model.K = K # unfortunately it is necessary on the prediction phase try model.B = U * inv(Tj' * K * U) * Q' catch error("KPLS: Not able to compute inverse. Maybe nfactors is greater than ncols of input data (X) or this matrix is not invertible. ") end return model end function predictor(model::KPLSModel{T}, Z::AbstractArray{T}) where T<:AbstractFloat X,K,B,w = model.X,model.K,model.B,model.width (nx,mx) = size(X) (nz,mz) = size(Z) Kt = ΦΦ(X,Z,w) # kernel matrix # centralize c = (1.0 / nx) .* ones(T,nz,nx) Kt = (Kt - c * K) * (Matrix{T}(I, nx, nx) - (1.0 / nx) .* ones(T,nx,nx)) Y = Kt * B return Y end
PLSRegressor
https://github.com/lalvim/PLSRegressor.jl.git
[ "MIT" ]
1.1.1
7560cbf6518c2891fcaa82d082a974701529d101
code
2413
## constants const NFACT = 10 # default number of factors if it is not informed by the user """ fit(X::Matrix{:<AbstractFloat},Y::Vector{:<AbstractFloat}; nfactors::Int=10,copydata::Bool=true,centralize::Bool=true,kernel="",width=1.0) A Partial Least Squares learning algorithm. # Arguments - `nfactors::Int = 10`: The number of latent variables to explain the data. - `copydata::Bool = true`: If you want to use the same input matrix or a copy. - `centralize::Bool = true`: If you want to z-score columns. Recommended if not z-scored yet. - `kernel::AbstractString = "gaussian"`: If you want to apply a nonlinear PLS with gaussian Kernel. - `width::AbstractFloat = 1.0`: Gaussian Kernel width (Only if kernel="gaussian"). """ function fit(X::AbstractArray{T}, Y::AbstractArray{T}; nfactors::Int = NFACT, copydata::Bool = true, centralize::Bool = true, kernel = "linear", width = 1.0) where T<:AbstractFloat X = X[:,:] check_constant_cols(X) check_constant_cols(Y) check_params(nfactors, size(X,2),kernel) check_data(X, Y) Xi = (copydata ? deepcopy(X) : X) Yi = (copydata ? deepcopy(Y) : Y) if kernel == "rbf" model = Model(Xi,Yi, nfactors, centralize, kernel, width) else model = Model(Xi,Yi, nfactors, centralize) end Xi = (centralize ? centralize_data(Xi,model.mx,model.sx) : Xi) Yi = (centralize ? centralize_data(Yi,model.my,model.sy) : Yi) model.centralize = (centralize ? true : false) trainer(model,Xi,Yi) return model end """ transform(model::PLSRegressor.Model; X::Matrix{:<AbstractFloat}; copydata::Bool=true) A Partial Least Squares predictor. # Arguments - `copydata::Bool = true`: If you want to use the same input matrix or a copy. """ function predict(model::PLSModel{T}, X::AbstractArray{T}; copydata::Bool=true) where T<:AbstractFloat X = X[:,:] check_data(X,model.nfeatures) Xi = (copydata ? deepcopy(X) : X) Xi = (model.centralize ? centralize_data(Xi,model.mx,model.sx) : Xi) Yi = predictor(model,Xi) Yi = decentralize_data(Yi,model.my,model.sy) return Yi end
PLSRegressor
https://github.com/lalvim/PLSRegressor.jl.git
[ "MIT" ]
1.1.1
7560cbf6518c2891fcaa82d082a974701529d101
code
1092
using LinearAlgebra ## the learning algorithm: PLS1 - single target function trainer(model::PLS1Model{T}, X::AbstractArray{T}, Y::Vector{T}) where T<:AbstractFloat W,b,P = model.W,model.b,model.P nfactors = model.nfactors for i = 1:nfactors W[:,i] = X'Y W[:,i] /= norm(W[:,i])#sqrt.(W[:,i]'*W[:,i]) R = X*W[:,i] Rn = R'/(R'R) # change to use function... P[:,i] = Rn*X b[i] = Rn * Y if abs(b[i]) <= 1e-3 print("PLS1 converged. No need learning with more than $(i) factors") model.nfactors = i break end X = X - R * P[:,i]' Y = Y - R * b[i] end return model end function predictor(model::PLS1Model{T}, X::AbstractArray{T}) where T<:AbstractFloat W,b,P = model.W,model.b,model.P nfactors = model.nfactors nrows = size(X,1) Y = zeros(T,nrows) for i = 1:nfactors R = X*W[:,i] Y = Y + R*b[i] X = X - R*P[:,i]' end return Y end
PLSRegressor
https://github.com/lalvim/PLSRegressor.jl.git
[ "MIT" ]
1.1.1
7560cbf6518c2891fcaa82d082a974701529d101
code
1635
using LinearAlgebra ## the learning algorithm: PLS2 - multiple targets function trainer(model::PLS2Model{T}, X::AbstractArray{T}, Y::Matrix{T}) where T<:AbstractFloat W,b,P,Q = model.W,model.b,model.P,model.Q model.ntargetcols = size(Y,2) nfactors = model.nfactors for i = 1:nfactors b[:,i] = Y[:,1] #u: arbitrary col. Thus, I set to the first. Rold = b[:,i] local R::Vector{T} while true W[:,i] = X'b[:,i] W[:,i] /= norm(W[:,i])#sqrt.(W[:,i]'*W[:,i]) R = X*W[:,i] Rold = R Q[:,i] = Y'R Q[:,i] /= norm(Q[:,i]) b[:,i] = Y*Q[:,i] if all(abs.(R - Rold) .<= 1.0e-3) break end end Rn = R'/(R'R) # change to use function... P[:,i] = Rn*X X = X - R * P[:,i]' c = Rn'b[:,i:i]'./(R'R) Yp = c*R*Q[:,i]' Y = Y - Yp if all(abs.(Y - Yp) .<= 1.0e-3) print("PLS2 converged. No need learning with more than $(i) factors") model.nfactors = i return model end end return model end function predictor(model::PLS2Model{T}, X::AbstractArray{T}) where T<:AbstractFloat W,Q,P = model.W,model.Q,model.P nfactors = model.nfactors Y = zeros(T,size(X,1),model.ntargetcols) #println("nfactors: ",nfactors) for i = 1:nfactors R = X*W[:,i] X = X - R * P[:,i]' Y = Y + R * Q[:,i]' end return Y end
PLSRegressor
https://github.com/lalvim/PLSRegressor.jl.git
[ "MIT" ]
1.1.1
7560cbf6518c2891fcaa82d082a974701529d101
code
5823
#### Libs using Statistics #### Constants const MODEL_FILENAME = "pls_model.jld" # jld filename for storing the model const MODEL_ID = "pls_model" # if od the model in the filesystem jld data #### An abstract pls model abstract type PLSModel{T} end #### PLS1 type mutable struct PLS1Model{T<:AbstractFloat} <:PLSModel{T} W::Matrix{T} # a set of vectors representing correlation weights of input data (X) with the target (Y) b::Matrix{T} # a set of scalar values representing a latent value for dependent variables or target (Y) P::Matrix{T} # a set of latent vetors for the input data (X) nfactors::Int # a scalar value representing the number of latent variables mx::Matrix{T} # mean stat after for z-scoring input data (X) my::T # mean stat after for z-scoring target data (Y) sx::Matrix{T} # standard deviation stat after z-scoring input data (X) sy::T # standard deviation stat after z-scoring target data (X) nfeatures::Int # number of input (X) features columns centralize::Bool # store information of centralization of data. if true, tehn it is passed to transform function end ## PLS1: constructor function Model(X::Matrix{T}, Y::Vector{T}, nfactors::Int, centralize::Bool) where T<:AbstractFloat (nrows,ncols) = size(X) ## Allocation return PLS1Model(zeros(T,ncols,nfactors), ## W zeros(T,1,nfactors), ## b zeros(T,ncols,nfactors), ## P nfactors, mean(X,dims=1), mean(Y), std(X,dims=1), std(Y), ncols, centralize) end ######################################################################################## #### PLS2 type mutable struct PLS2Model{T<:AbstractFloat} <:PLSModel{T} W::Matrix{T} # a set of vectors representing correlation weights of input data (X) with the target (Y) Q::Matrix{T} # b::Matrix{T} # a set of scalar values representing a latent value for dependent variables or target (Y) P::Matrix{T} # a set of latent vetors for the input data (X) nfactors::Int # a scalar value representing the number of latent variables mx::Matrix{T} # mean stat after for z-scoring input data (X) my::Matrix{T} # mean stat after for z-scoring target data (Y) sx::Matrix{T} # standard deviation stat after z-scoring input data (X) sy::Matrix{T} # standard deviation stat after z-scoring target data (X) nfeatures::Int # number of input (X) features columns ntargetcols::Int # number of target (Y) columns centralize::Bool # store information of centralization of data. if true, tehn it is passed to transform function end ## PLS2: constructor function Model(X::Matrix{T}, Y::Matrix{T}, # this is the diference from PLS1 param constructor! nfactors::Int, centralize::Bool) where T<:AbstractFloat (nrows,ncols) = size(X) (n,m) = size(Y) ## Allocation return PLS2Model(zeros(T,ncols,nfactors), ## W zeros(T,m,nfactors), ## Q zeros(T,n,nfactors), ## b zeros(T,ncols,nfactors), ## P nfactors, mean(X,dims=1), mean(Y,dims=1), std(X,dims=1), std(Y,dims=1), ncols, m, centralize) end ################################################################################ #### KPLS type mutable struct KPLSModel{T<:AbstractFloat} <:PLSModel{T} X::Matrix{T} # Training set K::Matrix{T} # Kernel matrix B::Matrix{T} # Regression matrix nfactors::Int # a scalar value representing the number of latent variables mx::Matrix{T} # mean stat after for z-scoring input data (X) my::AbstractArray{T} # mean stat after for z-scoring target data (Y) sx::Matrix{T} # standard deviation stat after z-scoring input data (X) sy::AbstractArray{T} # standard deviation stat after z-scoring target data (X) nfeatures::Int # number of input (X) features columns ntargetcols::Int # number of target (Y) columns centralize::Bool # store information of centralization of data. if true, tehn it is passed to transform function kernel::AbstractString width::Float64 end ## KPLS: constructor function Model(X::Matrix{T}, Y::AbstractArray{T}, # this is the diference from PLS1 param constructor! nfactors::Int, centralize::Bool, kernel::String, width::Float64) where T<:AbstractFloat (nrows,ncols) = size(X) (n,m) = size(Y[:,:]) ## Allocation return KPLSModel(zeros(T,nrows,ncols), ## X zeros(T,nrows,nrows), ## K zeros(T,ncols,m), ## B nfactors, mean(X,dims=1), mean(Y,dims=1), std(X,dims=1), std(Y,dims=1), ncols, m, centralize, kernel, width) end ###################################################################################################### ## Load and Store models (good for production) function load(; filename::AbstractString = MODEL_FILENAME, modelname::AbstractString = MODEL_ID) local M jldopen(filename, "r") do file M = read(file, modelname) end M end function save(M::PLSModel; filename::AbstractString = MODEL_FILENAME, modelname::AbstractString = MODEL_ID) jldopen(filename, "w") do file write(file, modelname, M) end end
PLSRegressor
https://github.com/lalvim/PLSRegressor.jl.git
[ "MIT" ]
1.1.1
7560cbf6518c2891fcaa82d082a974701529d101
code
2113
## Auxiliary functions ## checks PLS input data and params ## checks PLS input data and params function check_data(X::Matrix{T},Y::Union{Vector{T},Matrix{T}}) where T<:AbstractFloat !isempty(X) || throw(DimensionMismatch("Empty input data (X).")) !isempty(Y) || throw(DimensionMismatch("Empty target data (Y).")) size(X, 1) == size(Y, 1) || throw(DimensionMismatch("Incompatible number of rows of input data (X) and target data (Y).")) end function check_data(X::Matrix{T},nfeatures::Int) where T<:AbstractFloat !isempty(X) || throw(DimensionMismatch("Empty input data (X).")) size(X, 2) == nfeatures || throw(DimensionMismatch("Incompatible number of columns of input data (X) and original training X columns.")) end function check_params(nfactors::Int, ncols::Int, kernel::AbstractString) nfactors >= 1 || error("nfactors must be a positive integer.") nfactors <= ncols || warn("nfactors greater than ncols of input data (X) must generate numerical problems. However, can improve results if ok.") kernel == "rbf" || kernel == "linear" || error("kernel must be kernel='linear' or 'kernel=rbf'") end ## checks constant columns check_constant_cols(X::Matrix{T}) where {T<:AbstractFloat} = size(X,1)>1 && !any(all(X .== X[1,:]',dims=1)) || error("You must remove constant columns of input data (X) before train") check_constant_cols(Y::Vector{T}) where {T<:AbstractFloat} = length(Y)>1 && length(unique(Y)) > 1 || error("Your target values are constant. All values are equal to $(Y[1])") ## Preprocessing data using z-score statistics. this is due to the fact that if X and Y are z-scored, than X'Y returns for W vector a pearson correlation for each element! :) centralize_data(D::Matrix{T}, m::Matrix{T}, s::Matrix{T}) where {T<:AbstractFloat} = (D .-m)./s centralize_data(D::Vector{T}, m::T, s::T) where {T<:AbstractFloat} = (D .-m)./s decentralize_data(D::Matrix{T}, m::Matrix{T}, s::Matrix{T}) where {T<:AbstractFloat} = D .*s .+m decentralize_data(D::Vector{T}, m::T, s::T) where {T<:AbstractFloat} = D .*s .+m
PLSRegressor
https://github.com/lalvim/PLSRegressor.jl.git
[ "MIT" ]
1.1.1
7560cbf6518c2891fcaa82d082a974701529d101
code
2895
using Statistics using LinearAlgebra import Random @testset "KPLS Pediction Tests (in sample)" begin @testset "Test KPLS Single Non Linear Target" begin Random.seed!(1) z(x) = 4.26 * (exp.(-x) - 4 * exp.(-2.0*x) + 3 * exp.(-3.0*x)) x_values = Array(range(0.0,step=3.5,length=100)) z_pure = z(x_values) noise = Random.randn(100) z_noisy = z_pure + noise X = collect(x_values)[:,:] Y = z_noisy[:,:] #z_pure model = PLSRegressor.fit(X,Y,nfactors=1,kernel="rbf",width=0.01) Y_pred = PLSRegressor.predict(model,X) @test mean(abs.(Y .- Y_pred)) < 1e-2 end @testset "Test KPLS Single Target (Linear Target)" begin X = [1 2; 2 4; 4.0 6][:,:] Y = [-2; -4; -6.0][:,:] model = PLSRegressor.fit(X,Y,nfactors=1,kernel="rbf",width=0.01) Y_pred = PLSRegressor.predict(model,X) @test mean(abs.(Y .- Y_pred)) < 1e-6 X = [1 2; 2 4; 4.0 6][:,:] Y = [2; 4; 6.0][:,:] model = PLSRegressor.fit(X,Y,nfactors=1,kernel="rbf",width=0.01) Y_pred = PLSRegressor.predict(model,X) @test mean(abs.(Y .- Y_pred)) < 1e-6 end @testset "Test KPLS Multiple Target (Linear Target)" begin X = [1; 2; 3.0][:,:] Y = [1 1; 2 2; 3 3.0][:,:] model = PLSRegressor.fit(X,Y,nfactors=1,kernel="rbf",width=0.01) Y_pred = PLSRegressor.predict(model,X) @test mean(abs.(Y .- Y_pred)) < 1e-6 X = [1; 2; 3.0][:,:] Y = [1 -1; 2 -2; 3 -3.0][:,:] model = PLSRegressor.fit(X,Y,nfactors=1,kernel="rbf",width=0.01) Y_pred = PLSRegressor.predict(model,X) @test mean(abs.(Y .- Y_pred)) < 1e-6 @testset "Linear Prediction Tests " begin X = [1 2; 2 4; 4 6.0][:,:] Y = [4 2;6 4;8 6.0][:,:] model = PLSRegressor.fit(X,Y,nfactors=1,kernel="rbf",width=0.01) Y_pred = PLSRegressor.predict(model,X) @test mean(abs.(Y .- Y_pred)) < 1e-6 X = [1 -2; 2 -4; 4 -6.0][:,:] Y = [-4 -2;-6 -4;-8 -6.0][:,:] model = PLSRegressor.fit(X,Y,nfactors=1,kernel="rbf",width=0.01) Y_pred = PLSRegressor.predict(model,X) @test mean(abs.(Y .- Y_pred)) < 1e-6 end end end; ### not saving yeat. @testset "Test Saving and Loading KPLS Models" begin Xtr = [1 -2; 2 -4; 4.0 -6] Ytr = [-2; -4; -6.0][:,:] Xt = [6 -8; 8 -10; 10.0 -12] model1 = PLSRegressor.fit(Xtr,Ytr,nfactors=1,kernel="rbf",width=0.01) pred1 = PLSRegressor.predict(model1,Xt) PLSRegressor.save(model1) model2 = PLSRegressor.load() pred2 = PLSRegressor.predict(model2,Xt) rm(PLSRegressor.MODEL_FILENAME) @test all(pred1 .== pred2) end;
PLSRegressor
https://github.com/lalvim/PLSRegressor.jl.git
[ "MIT" ]
1.1.1
7560cbf6518c2891fcaa82d082a974701529d101
code
3115
@testset "Test Saving and Loading PLS1 Models" begin Xtr = [1 -2; 2 -4; 4.0 -6] Ytr = [-2; -4; -6.0] Xt = [6 -8; 8 -10; 10.0 -12] model1 = PLSRegressor.fit(Xtr,Ytr,nfactors=2) pred1 = PLSRegressor.predict(model1,Xt) PLSRegressor.save(model1) model2 = PLSRegressor.load() pred2 = PLSRegressor.predict(model2,Xt) rm(PLSRegressor.MODEL_FILENAME) @test all(pred1 .== pred2) end @testset "PLS1 Pediction Tests (in sample)" begin @testset "Single Column Prediction Test" begin X = [1; 2; 3.0][:,:] Y = [1; 2; 3.0] model = PLSRegressor.fit(X,Y,nfactors=1) pred = PLSRegressor.predict(model,X) @test isequal(round.(pred),[1; 2; 3.0]) end @testset "Constant Values Prediction Tests (Ax + b) | A=0, b=1 " begin X = [1 3;2 1;3 2.0] Y = [1; 1; 1.0] try PLSRegressor.fit(X,Y,nfactors=2) catch @test true end end @testset "Linear Prediction Tests " begin X = [1 2; 2 4; 4.0 6] Y = [2; 4; 6.0] model = PLSRegressor.fit(X,Y,nfactors=2) pred = PLSRegressor.predict(model,X) @test isequal(round.(pred),[2; 4; 6.0]) X = [1 -2; 2 -4; 4.0 -6] Y = [-2; -4; -6.0] model = PLSRegressor.fit(X,Y,nfactors=2) pred = PLSRegressor.predict(model,X) @test isequal(round.(pred),[-2; -4; -6.0]) end @testset "Linear Prediction Tests (Ax + b)" begin Xtr = [1 2; 2 4; 4.0 6] Ytr = [2; 4; 6.0] Xt = [6 8; 8 10; 10.0 12] # same sample model = PLSRegressor.fit(Xtr,Ytr,nfactors=2) pred = PLSRegressor.predict(model,Xt) @test isequal(round.(pred),[8; 10; 12.0]) Xtr = [1 2; 2 4.0; 4.0 6; 6 8] Ytr = [2; 4; 6.0; 8] Xt = [1 2; 2 4.0] # a subsample model = PLSRegressor.fit(Xtr,Ytr,nfactors=2,centralize=true) pred = PLSRegressor.predict(model,Xt) @test isequal(round.(pred),[2; 4]) end end; @testset "PLS1 Pediction Tests (out of sample)" begin @testset "Linear Prediction Tests (Ax + b) | A>0" begin Xtr = [1 2; 2 4; 4.0 6] Ytr = [2; 4; 6.0] Xt = [6 8; 8 10; 10.0 12] model = PLSRegressor.fit(Xtr,Ytr,nfactors=2) pred = PLSRegressor.predict(model,Xt) @test isequal(round.(pred),[8; 10; 12.0]) Xtr = [1 2; 2 4; 4.0 6] Ytr = [4; 6; 8.0] Xt = [6 8; 8 10; 10.0 12] model = PLSRegressor.fit(Xtr,Ytr,nfactors=2) pred = PLSRegressor.predict(model,Xt) @test isequal(round.(pred),[10; 12; 14.0]) end @testset "Linear Prediction Tests (Ax + b) | A<0" begin Xtr = [1 -2; 2 -4; 4.0 -6] Ytr = [-2; -4; -6.0] Xt = [6 -8; 8 -10; 10.0 -12] model = PLSRegressor.fit(Xtr,Ytr,nfactors=2) pred = PLSRegressor.predict(model,Xt) @test isequal(round.(pred),[-8; -10; -12.0]) Xtr = [1 -2; 2 -4; 4.0 -6] Ytr = [-4; -6; -8.0] Xt = [6 -8; 8 -10; 10.0 -12] model = PLSRegressor.fit(Xtr,Ytr,nfactors=2) pred = PLSRegressor.predict(model,Xt) @test isequal(round.(pred),[-10; -12; -14.0]) end end;
PLSRegressor
https://github.com/lalvim/PLSRegressor.jl.git
[ "MIT" ]
1.1.1
7560cbf6518c2891fcaa82d082a974701529d101
code
2658
@testset "Test Saving and Loading PLS2 Models" begin Xtr = [1 2;2 4;3 6;6 12;7 14.0] Ytr = [2 2;4 4;6 6;12 12;14 14.0] Xt = [4 8;5 10.0] model1 = PLSRegressor.fit(Xtr,Ytr,nfactors=2) pred1 = PLSRegressor.predict(model1,Xt) PLSRegressor.save(model1) model2 = PLSRegressor.load() pred2 = PLSRegressor.predict(model2,Xt) rm(PLSRegressor.MODEL_FILENAME) @test all(pred1 .== pred2) end @testset "PLS2 Prediction Tests (in sample)" begin @testset "Single Column Prediction Test" begin X = [1; 2; 3.0] Y = [1 1; 2 2; 3 3.0] model = PLSRegressor.fit(X,Y,nfactors=1) pred = PLSRegressor.predict(model,X) @test isequal(round.(pred),[1 1; 2 2; 3 3.0]) end @testset "Constant Values Prediction Tests (Ax + b) | A=0, b=1 " begin X = [1 3;2 1;3 2.0] Y = [1 1; 1 1; 1 1.0] try PLSRegressor.fit(X,Y,nfactors=2) catch @test true end end @testset "Linear Prediction Tests " begin X = [1 2; 2 4; 4 6.0] Y = [4 2;6 4;8 6.0] model = PLSRegressor.fit(X,Y,nfactors=2) pred = PLSRegressor.predict(model,X) @test isequal(round.(pred),[4 2;6 4;8 6.0]) X = [1 -2; 2 -4; 4 -6.0] Y = [-4 -2;-6 -4;-8 -6.0] model = PLSRegressor.fit(X,Y,nfactors=2) pred = PLSRegressor.predict(model,X) @test isequal(round.(pred),[-4 -2;-6 -4;-8 -6.0]) end end @testset "PLS2 Pediction Tests (out of sample)" begin @testset "Linear Prediction Tests (Ax + b) | A>0" begin Xtr = [1 2;2 4;3 6;6 12;7 14.0] Ytr = [2 2;4 4;6 6;12 12;14 14.0] Xt = [4 8;5 10.0] model = PLSRegressor.fit(Xtr,Ytr,nfactors=2) pred = PLSRegressor.predict(model,Xt) @test isequal(round.(pred),[8 8;10 10.0]) Xtr = [1 2;2 4;3 6;6 12;7 14.0] Ytr = [2 4;4 6;6 8;12 14;14 16.0] Xt = [4 8;5 10.0] model = PLSRegressor.fit(Xtr,Ytr,nfactors=2) pred = PLSRegressor.predict(model,Xt) @test isequal(round.(pred),[8 10;10 12.0]) end @testset "Linear Prediction Tests (Ax + b) | A<0" begin Xtr = [1 -2;2 -4;3 -6;6 -12;7 -14.0] Ytr = [2 -2;4 -4;6 -6;12 -12;14 -14.0] Xt = [4 -8;5 -10.0] model = PLSRegressor.fit(Xtr,Ytr,nfactors=2) pred = PLSRegressor.predict(model,Xt) @test isequal(round.(pred),[8 -8;10 -10.0]) Xtr = [1 -2;2 -4;3 -6;6 -12;7 -14.0] Ytr = [2 -4;4 -6;6 -8;12 -14;14 -16.0] Xt = [4 -8;5 -10.0] model = PLSRegressor.fit(Xtr,Ytr,nfactors=2) pred = PLSRegressor.predict(model,Xt) @test isequal(round.(pred),[8 -10;10 -12.0]) end end;
PLSRegressor
https://github.com/lalvim/PLSRegressor.jl.git
[ "MIT" ]
1.1.1
7560cbf6518c2891fcaa82d082a974701529d101
code
136
using PLSRegressor using Test include("./pls1_test.jl") include("./pls2_test.jl") include("./utils_test.jl") include("./kpls_test.jl")
PLSRegressor
https://github.com/lalvim/PLSRegressor.jl.git
[ "MIT" ]
1.1.1
7560cbf6518c2891fcaa82d082a974701529d101
code
1542
using Statistics @testset "Auxiliary Functions Test" begin @testset "check constant columns" begin try PLSRegressor.check_constant_cols([1.0 1;1 2;1 3]) catch @test true end try PLSRegressor.check_constant_cols([1.0;1;1][:,:]) catch @test true end try PLSRegressor.check_constant_cols([1.0 2 3]) catch @test true end try PLSRegressor.check_constant_cols([1.0; 1; 1][:,:]) catch @test true end @test PLSRegressor.check_constant_cols([1.0 1;2 2;3 3]) @test PLSRegressor.check_constant_cols([1.0;2;3][:,:]) end @testset "centralize" begin X = [1; 2; 3.0][:,:] X = PLSRegressor.centralize_data(X,mean(X,dims=1),std(X,dims=1)) @test all(X .== [-1;0;1.0]) end @testset "decentralize" begin Xo = [1; 2; 3.0][:,:] Xn = [-1;0;1.0][:,:] Xn = PLSRegressor.decentralize_data(Xn,mean(Xo,dims=1),std(Xo,dims=1)) @test all(Xn .== [1; 2; 3.0]) end @testset "checkdata" begin try PLSRegressor.check_params(2,1,"linear") catch @test true end try PLSRegressor.check_params(-1,2,"linear") catch @test true end try PLSRegressor.check_params(1,2,"x") catch @test true end @test PLSRegressor.check_params(1,2,"linear") end @testset "checkparams" begin try PLSRegressor.check_data(zeros(0,0), 0) catch @test true end try PLSRegressor.check_data(zeros(1,1), 10) catch @test true end @test PLSRegressor.check_data(zeros(1,1), 1) end end;
PLSRegressor
https://github.com/lalvim/PLSRegressor.jl.git
[ "MIT" ]
1.1.1
7560cbf6518c2891fcaa82d082a974701529d101
docs
4939
PLSRegressor.jl ====== A Partial Least Squares Regressor package. Contains PLS1, PLS2 and Kernel PLS2 NIPALS algorithms. Can be used mainly for regression. However, for classification task, binarizing targets and then obtaining multiple targets, you can apply KPLS. | **PackageEvaluator** | **Build Status** | |:-------------------------------:|:-----------------------------------------:| | [![][pkg-0.6-img]][pkg-0.6-url] | [![][travis-img]][travis-url] [![][codecov-img]][codecov-url] | [travis-img]: https://travis-ci.org/lalvim/PLSRegressor.jl.svg?branch=master [travis-url]: https://travis-ci.org/lalvim/PLSRegressor.jl [codecov-img]: http://codecov.io/github/lalvim/PLSRegressor.jl/coverage.svg?branch=master [codecov-url]: http://codecov.io/github/lalvim/PLSRegressor.jl?branch=master [issues-url]: https://github.com/lalvim/PLSRegressor.jl/issues [pkg-0.6-img]: http://pkg.julialang.org/badges/PLSRegressor_0.6.svg [pkg-0.6-url]: http://pkg.julialang.org/?pkg=PLSRegressor&ver=0.6 [pkg-0.7-img]: http://pkg.julialang.org/badges/PLSRegressor_0.7.svg [pkg-0.7-url]: http://pkg.julialang.org/?pkg=PLSRegressor&ver=0.7 Install ======= Pkg.add("PLSRegressor") Using ===== using PLSRegressor Examples ======== using PLSRegressor # learning a single target X_train = [1 2; 2 4; 4 6.0] Y_train = [4; 6; 8.0] X_test = [6 8; 8 10; 10 12.0] Y_test = [10; 12; 14.0] model = PLSRegressor.fit(X_train,Y_train,nfactors=2) Y_pred = PLSRegressor.predict(model,X_test) print("[PLS1] mae error : $(mean(abs.(Y_test .- Y_pred)))") # learning multiple targets X_train = [1 2; 2 4; 4 6.0] Y_train = [2 4;4 6;6 8.0] X_test = [6 8; 8 10; 10 12.0] Y_test = [8 10; 10 12; 12 14.0] model = PLSRegressor.fit(X_train,Y_train,nfactors=2) Y_pred = PLSRegressor.predict(model,X_test) print("[PLS2] mae error : $(mean(abs.(Y_test .- Y_pred)))") # nonlinear learning with multiple targets model = PLSRegressor.fit(X_train,Y_train,nfactors=2,kernel="rbf",width=0.1) Y_pred = PLSRegressor.predict(model,X_test) print("[KPLS] mae error : $(mean(abs.(Y_test .- Y_pred)))") # if you want to save your model PLSRegressor.save(model,filename=joinpath(homedir(),"pls_model.jld")) # if you want to load back your model model = PLSRegressor.load(filename=joinpath(homedir(),"pls_model.jld")) What is Implemented ====== * A fast linear algorithm for single targets (PLS1 - NIPALS) * A linear algorithm for multiple targets (PLS2 - NIPALS) * A non linear algorithm for multiple targets (Kernel PLS2 - NIPALS) What is Upcoming ======= * Bagging for Kernel PLS * An automatic validation inside fit function Method Description ======= * PLSRegressor.fit - learns from input data and its related single target * X::Matrix{:<AbstractFloat} - A matrix that columns are the features and rows are the samples * Y::Vector{:<AbstractFloat} - A vector with float values. * nfactors::Int = 10 - The number of latent variables to explain the data. * copydata::Bool = true - If you want to use the same input matrix or a copy. * centralize::Bool = true - If you want to z-score columns. Recommended if not z-scored yet. * kernel::AbstractString = "rbf" - use a non linear kernel. * width::AbstractFloat = 1.0 - If you want to z-score columns. Recommended if not z-scored yet. * PLSRegressor.transform - predicts using the learnt model extracted from fit. * model::PLSRegressor.Model - A PLS model learnt from fit. * X::Matrix{:<AbstractFloat} - A matrix that columns are the features and rows are the samples. * copydata::Bool = true - If you want to use the same input matrix or a copy. References ======= * PLS1 and PLS2 based on * Bob Collins Slides, LPAC Group. http://vision.cse.psu.edu/seminars/talks/PLSpresentation.pdf * A Kernel PLS2 based on * Kernel Partial Least Squares Regression in Reproducing Kernel Hilbert Space" by Roman Rosipal and Leonard J Trejo. Journal of Machine Learning Research 2 (2001) 97-123 http://www.jmlr.org/papers/volume2/rosipal01a/rosipal01a.pdf * NIPALS: Nonlinear Iterative Partial Least Squares * Wold, H. (1966). Estimation of principal components and related models by iterative least squares. In P.R. Krishnaiaah (Ed.). Multivariate Analysis. (pp.391-420) New York: Academic Press. * SIMPLS: more efficient, optimal result * Supports multivariate Y * De Jong, S., 1993. SIMPLS: an alternative approach to partial least squares regression. Chemometrics and Intelligent Laboratory Systems, 18: 251– 263 License ======= The PLSRegressor.jl is free software: you can redistribute it and/or modify it under the terms of the MIT "Expat" License. A copy of this license is provided in ``LICENSE.md``
PLSRegressor
https://github.com/lalvim/PLSRegressor.jl.git
[ "MIT" ]
1.0.0
bcde119253c63737005e06f453c4e0c6eab70c61
code
2031
include("bissection.jl") include("interp1.jl") @doc raw""" `r=refmin(y,X,q)` `refmin` computes the minimum value of the reflux ratio of a distillation column using the McCabe-Thiele method given a function y = y(x) that relates the liquid fraction x and the vapor fraction y, or a x-y matrix of the liquid and the vapor fractions, the vector of the fractions of the distillate and the feed, and the feed quality. If feed is a saturated liquid, feed quality q = 1, feed quality is reset to q = 1 - 1e-10. See also: `stages`, `qR2S`. Examples ========== Compute the minimum value of the reflux ratio of a distillation column given a matrix that relates the liquid fraction and the vapor fraction, the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 %: ``` data=[0. 0.; 0.1 0.212; 0.2 0.384; 0.3 0.529; 0.4 0.651; 0.5 0.752; 0.6 0.833; 0.7 0.895; 0.8 0.942; 0.9 0.974; 1. 1.]; x=[0.88 0.46]; q=0.56; r=refmin(data,x,q) ``` Compute the minimum value of the reflux ratio of a distillation column given the function that compute the vapor fraction given the liquid fraction, the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 %, the feed is saturated liquid: ``` y(x)=x.^0.9 .* (1-x).^1.2 + x; x=[0.88 0.46]; q=1; r=refmin(y,x,q) ``` """ function refmin(data, X, q) xD = X[1] xF = X[2] if xD < xF error("Inconsistent feed and/or products compositions.") end if q == 1 q = 1 - 1e-10 end if isa(data, Matrix) f(x) = interp1(data[:, 1], data[:, 2], x) else f = data end foo(x) = f(x) - (q / (q - 1) * x - xF / (q - 1)) xi = bissection(foo, 0.0, 1.0) yi = q / (q - 1) * xi - xF / (q - 1) alpha = (xD - yi) / (xD - xi) alpha / (1 - alpha) end
McCabeThiele
https://github.com/aumpierre-unb/McCabeThiele.jl.git
[ "MIT" ]
1.0.0
bcde119253c63737005e06f453c4e0c6eab70c61
code
704
@doc raw""" `McCabeThiele` provides a set of functions to compute the number of theoretical stages of a distillation column using the McCabe-Thiele method. Author: Alexandre Umpierre `[email protected]` Maintainer's repository: `https://github.com/aumpierre-unb/McCabe-Thiele.jl` Citation (any version): `DOI 10.5281/zenodo.7126164` See also: `stages`, `refmin`, `qR2S`, `qS2R`, `RS2q`. """ module McCabeThiele using Plots using Test export stages, refmin, qR2S, qS2R, RS2q include("stages.jl") include("stages_updown.jl") include("stages_downup.jl") include("refmin.jl") include("qR2S.jl") include("doplots.jl") include("bissection.jl") include("interp1.jl") end
McCabeThiele
https://github.com/aumpierre-unb/McCabeThiele.jl.git
[ "MIT" ]
1.0.0
bcde119253c63737005e06f453c4e0c6eab70c61
code
1248
@doc raw""" `RS2q(z::Vector{Float64}, R::Number, S::Number)` `RS2q` computes the feed quality of a distillation column using the McCabe-Thiele method given the compositions of the products and the feed, the reflux ratio at the bottom of the column and the reflux ratio at the top of the column. If feed is a saturated liquid, feed quality q = 1, feed quality is reset to q = 1 - 1e-10. `RS2q` is a main function of the `McCabeThiele` toolbox for Julia. See also: `stages`, `refmin`, `qR2S`, `qS2R`. Examples ========== Compute the the feed quality given the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 %, the reflux ratio at the top of the column is 2 and reflux ratio at the bottom of the column is 2.5: ``` x=[0.88;0.46;0.11]; R=2; S=2.5; q=RS2q(x,R,S) ``` """ function RS2q(z::Vector{Float64}, R::Number, S::Number) xD, xF, xB = z if xD < xF || xB > xF error("Inconsistent feed and/or products compositions.") end xi = (xB / S + xD / (R + 1)) / ((S + 1) / S - R / (R + 1)) yi = R / (R + 1) * xi + xD / (R + 1) a = (yi - xF) / (xi - xF) q = a / (a - 1) if q == 1 q = 1 - 1e-10 else q end end
McCabeThiele
https://github.com/aumpierre-unb/McCabeThiele.jl.git
[ "MIT" ]
1.0.0
bcde119253c63737005e06f453c4e0c6eab70c61
code
438
@doc raw""" `bissection` computes computes the root of a function using the method of bissection given it is found between the guess values. `bissection` is an internal function of the `McCabeThiele` toolbox for Julia. """ function bissection(f, x1, x2) while abs(f(x2)) > 1e-4 x = (x1 + x2) / 2 if f(x) * f(x1) > 0 x1 = x else x2 = x end end x2 end
McCabeThiele
https://github.com/aumpierre-unb/McCabeThiele.jl.git
[ "MIT" ]
1.0.0
bcde119253c63737005e06f453c4e0c6eab70c61
code
2093
using Plots @doc raw""" `doplot` produces a x-y diagram with a representation of the theoretical stages of equilibrium computed for a distillation column using the McCabe-Thiele method. `doplot` is an internal function of the `McCabeThiele` toolbox for Julia. """ function doplot(dots, updown, f, x, y, data, X, q, R) xD, xF, xB, xi, yi = X plot(xlabel="x", ylabel="y", xlims=(0, 1), ylims=(0, 1), legend=false, framestyle=:box, grid=:true, minorgrid=:true, size=(750, 600)) if dots X = data[:, 1] Y = data[:, 2] plot!(X, Y, seriestype=:line, color=:black, markershape=:circle, markersize=3) else X = collect(range(0, 1, length=101)) Y = f.(X) plot!(X, Y, seriestype=:line, color=:black) end X = [0; 1] Y = X plot!(X, Y, seriestype=:line, color=:black, linestyle=:dash) Y = R / (1 + R) .* X .+ xD / (1 + R) plot!(X, Y, seriestype=:line, color=:blue, linestyle=:dashdot) plot!([xD], seriestype=:vline, color=:blue, linestyle=:dash) Y = (xB - yi) / (xB - xi) .* (X .- xi) .+ yi plot!(X, Y, seriestype=:line, color=:red, linestyle=:dashdot) plot!([xB], seriestype=:vline, color=:red, linestyle=:dash) if q != 1 - 1e-10 Y = q / (q - 1) .* X .- xF / (q - 1) plot!(X, Y, seriestype=:line, color=:magenta, linestyle=:dashdot) end plot!([xF], seriestype=:vline, color=:magenta, linestyle=:dash) if updown plot!(x, y, seriestype=:steppost, color=:cyan, linestyle=:solid) else plot!(x, y, seriestype=:steppre, color=:cyan, linestyle=:solid) end display(plot!()) end
McCabeThiele
https://github.com/aumpierre-unb/McCabeThiele.jl.git
[ "MIT" ]
1.0.0
bcde119253c63737005e06f453c4e0c6eab70c61
code
335
@doc raw""" `interp1` computes the interpolation of a number. `interp1` is an internal function of the `McCabeThiele` toolbox for Julia. """ function interp1(X, Y, x) for i = 1:length(X)-1 if X[i] <= x <= X[i+1] return (Y[i+1] - Y[i]) / (X[i+1] - X[i]) * (x - X[i]) + Y[i] end end end
McCabeThiele
https://github.com/aumpierre-unb/McCabeThiele.jl.git
[ "MIT" ]
1.0.0
bcde119253c63737005e06f453c4e0c6eab70c61
code
1266
@doc raw""" `qR2S(z::Vector{Float64}, q::Number, R::Number)` `qR2S` computes the reflux ratio at the bottom of a distillation column using the McCabe-Thiele method given the compositions of the products and the feed, the feed quality and the reflux ratio at the top of the column. If feed is a saturated liquid, feed quality q = 1, feed quality is reset to q = 1 - 1e-10. `qR2S` is a main function of the `McCabeThiele` toolbox for Julia. See also: `stages`, `refmin`, `qS2R`, `RS2q`. Examples ========== Compute the reflux ratio at the bottom of the column given the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 %, the feed is saturated liquid and the reflux ratio at the top of the column is 2: ``` x=[0.88;0.46;0.11]; q=1; R=2; S=qR2S(x,q,R) ``` """ function qR2S(z::Vector{Float64}, q::Number, R::Number) xD, xF, xB = z if xD < xF || xB > xF error("Inconsistent feed and/or products compositions.") end if q == 1 q = 1 - 1e-10 end xi = (xD / (R + 1) + xF / (q - 1)) / (q / (q - 1) - R / (R + 1)) yi = q / (q - 1) * xi - xF / (q - 1) a = (yi - xB) / (xi - xB) 1 / (a - 1) end
McCabeThiele
https://github.com/aumpierre-unb/McCabeThiele.jl.git
[ "MIT" ]
1.0.0
bcde119253c63737005e06f453c4e0c6eab70c61
code
1218
@doc raw""" `qS2R(z::Vector{Float64}, q::Number, S::Number)` `qS2R` computes the reflux ratio at the top of a distillation column using the McCabe-Thiele method given the compositions of the products and the feed, the feed quality and the reflux ratio at the bottom of the column. If feed is a saturated liquid, feed quality q = 1, feed quality is reset to q = 1 - 1e-10. `qS2R` is a main function of the `McCabeThiele` toolbox for Julia. See also: `stages`, `refmin`, `qR2S`, `RS2q`. Examples ========== Compute the reflux ratio at the top of the column given the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 %, the feed is saturated liquid and the reflux ratio at the bottom of the column is 2.5: ``` x=[0.88;0.46;0.11]; q=1; S=2.5; R=qS2R(x,q,S) ``` """ function qS2R(z::Vector{Float64}, q::Number, S::Number) xD, xF, xB = z if xD < xF || xB > xF error("Inconsistent feed and/or products compositions.") end if q == 1 q = 1 - 1e-10 end xi = (xB / S - xF / (q - 1)) / ((S + 1) / S - q / (q - 1)) yi = q / (q - 1) * xi - xF / (q - 1) a = (yi - xD) / (xi - xD) a / (1 - a) end
McCabeThiele
https://github.com/aumpierre-unb/McCabeThiele.jl.git
[ "MIT" ]
1.0.0
bcde119253c63737005e06f453c4e0c6eab70c61
code
2468
include("bissection.jl") include("interp1.jl") @doc raw""" `refmin(data::Union{Matrix{Float64},Function}, z::Vector{Float64}; q::Number=1)` `refmin` computes the minimum reflux ratios at the top and the bottom of a distillation column using the McCabe-Thiele method given a function y = y(x) that relates the liquid fraction x and the vapor fraction y, or a x-y matrix of the liquid and the vapor fractions, the vector of the fractions of the distillate and the feed and the feed quality. By default, feed is a saturated liquid at the feed stage, q = 1. If feed is a saturated liquid at the feed stage, q = 1, feed quality is reset to q = 1 - 1e-10. `refmin` is a main function of the `McCabeThiele` toolbox for Julia. See also: `stages`, `qR2S`, `qS2R`, `RS2q`. Examples ========== Compute the minimum value of the reflux ratio of a distillation column given a matrix that relates the liquid fraction and the vapor fraction, the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 % and the feed is a liquid-vapor equilibrium with 44 % vapor at the feed stage: ``` data=[0. 0.; 0.1 0.212; 0.2 0.384; 0.3 0.529; 0.4 0.651; 0.5 0.752; 0.6 0.833; 0.7 0.895; 0.8 0.942; 0.9 0.974; 1. 1.]; x=[0.88;0.46;0.11]; r,s=refmin(data,x,q=1-0.44) ``` Compute the minimum value of the reflux ratio of a distillation column given the function that compute the vapor fraction given the liquid fraction, the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 % and the feed is saturated liquid at the feed stage: ``` y(x)=x.^0.9 .* (1-x).^1.2 + x; x=[0.88;0.46;0.11]; r,s=refmin(y,x,q=1) ``` """ function refmin(data::Union{Matrix{Float64},Function}, z::Vector{Float64}; q::Number=1) xD, xF, xB = z if xD < xF || xB > xF error("Inconsistent feed and/or products compositions.") end if q == 1 q = 1 - 1e-10 end if isa(data, Matrix) f(x) = interp1(data[:, 1], data[:, 2], x) else f = data end foo(x) = f(x) - (q / (q - 1) * x - xF / (q - 1)) xi = bissection(foo, 0.0, 1.0) yi = q / (q - 1) * xi - xF / (q - 1) a = (xD - yi) / (xD - xi) b = (xB - yi) / (xB - xi) a / (1 - a), 1 / (b - 1) end
McCabeThiele
https://github.com/aumpierre-unb/McCabeThiele.jl.git
[ "MIT" ]
1.0.0
bcde119253c63737005e06f453c4e0c6eab70c61
code
3959
include("xyRq2N.jl") include("doplots.jl") include("refmin.jl") include("RS2q.jl") include("qS2R.jl") @doc raw""" `stages(data::Union{Matrix{Float64},Function}, z::Vector{Float64}; q::Number=NaN, R::Number=NaN, S::Number=NaN, updown::Bool=true, fig::Bool=true)` `stages` computes the number of theoretical stages of a distillation column using the McCabe-Thiele method given a function y = y(x) that relates the liquid fraction x and the vapor fraction y or a x-y matrix of the liquid and the vapor fractions, the vector of products and feed compositions and two parameters among the feed quality, the reflux ratio at the top of the column and the reflux ratio at the bottom of the column. By default, feed is a saturated liquid at the feed stage, q = 1. If feed is a saturated liquid at the feed stage, q = 1, feed quality is reset to q = 1 - 1e-10. By default, theoretical stages are computed from the stripping section to the rectifying section, updown = true. If updown = false is given, theoretical stages are computed from the rectifying section to the stripping section. By default, `stages` plots a schematic diagram of the solution, fig = true. If fig = false is given, no plot is shown. `stages` is a main function of the `McCabeThiele` toolbox for Julia. See also: `refmin`, `qR2S`, `qS2R`, `RS2q`. Examples ========== Compute the number of theoretical stages of a distillation column from the bottom to the top of the column given a matrix that relates the liquid fraction and the vapor fraction, the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 %, the feed is a liquid-vapor equilibrium with 44 % vapor at the feed stage and the reflux ratio at the top of the column is 70 % higher than the minimum reflux ratio: ``` data=[0. 0.; 0.1 0.212; 0.2 0.384; 0.3 0.529; 0.4 0.651; 0.5 0.752; 0.6 0.833; 0.7 0.895; 0.8 0.942; 0.9 0.974; 1. 1.]; x=[0.88;0.46;0.11]; r,s=refmin(data,x,q=1-0.44) N=stages(data,x,q=1-0.44,R=1.70*r,updown=false,fig=false) ``` Compute the number of theoretical stages of a distillation column from the top to the bottom of the column given the function that compute the vapor fraction given the liquid fraction, the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 %, the feed is saturated liquid at the feed stage and the reflux ratio at the top of the column is 70 % higher than the minimum reflux ratio and plot a schematic diagram of the solution: ``` y(x)=x.^0.9 .* (1-x).^1.2 + x; x=[0.88;0.46;0.11]; r,s=refmin(y,x,q=1) N=stages(y,x,q=1,R=1.70*r) ``` """ function stages(data::Union{Matrix{Float64},Function}, z::Vector{Float64}; q::Number=NaN, R::Number=NaN, S::Number=NaN, updown::Bool=true, fig::Bool=true) xD, xF, xB = z if xD < xF || xB > xF error("Inconsistent feed and/or products compositions.") end if q == 1 q = 1 - 1e-10 end if isa(data, Matrix) f(x) = interp1(data[:, 1], data[:, 2], x) dots = true else f = data dots = false end a = isnan.([q, R, S]) .!= 1 if sum(a) != 2 error("""stages requires that two parameter among the feed quality, the reflux ratio at the top of the column and the reflux ratio at the bottom of the column be given alone.""") end if a == [1, 0, 1] R = qS2R(z, q, S) elseif a == [0, 1, 1] q = RS2q(z, R, S) end r = refmin(data, z, q=q)[1] if R <= r error("Minimum reflux ratios exceeded.") end N, z, x, y = xyRq2N(f, z, q, R, updown) if !fig return N end doplot(dots, updown, f, x, y, data, z, q, R) N end
McCabeThiele
https://github.com/aumpierre-unb/McCabeThiele.jl.git
[ "MIT" ]
1.0.0
bcde119253c63737005e06f453c4e0c6eab70c61
code
666
@doc raw""" `stages_downup` scomputes the number of theoretical stages of equilibrium of a distillation column using the McCabe-Thiele method, strating from the bottom to the top of the column. `stages_downup` is an internal function of the `McCabeThiele` toolbox for Julia. """ function stages_downup(f, X, R) xD, xF, xB, xi, yi = X y = [xB] x = [xB] while x[end] < xD y = [y; f(x[end])] if y[end] < yi x = [x; (y[end] - yi) / ((xB - yi) / (xB - xi)) + xi] else x = [x; (y[end] - xD / (R + 1)) * (R + 1) / R] end end length(x) - 1 - 1 + (xD - x[end-1]) / (x[end] - x[end-1]), x, y end
McCabeThiele
https://github.com/aumpierre-unb/McCabeThiele.jl.git
[ "MIT" ]
1.0.0
bcde119253c63737005e06f453c4e0c6eab70c61
code
733
include("bissection.jl") @doc raw""" `stages_updown` scomputes the number of theoretical stages of equilibrium of a distillation column using the McCabe-Thiele method, strating from the bottom to the top of the column. `stages_updown` is an internal function of the `McCabeThiele` toolbox for Julia. """ function stages_updown(f, X, R) xD, xF, xB, xi, yi = X x = [xD] y = [xD] while x[end] > xB foo(x) = (f(x) - y[end]) x = [x; bissection(foo, 0, 1)] if x[end] > xi y = [y; R / (R + 1) * x[end] + xD / (R + 1)] else y = [y; (xB - yi) / (xB - xi) * (x[end] - xB) + xB] end end length(x) - 1 - 1 + (x[end-1] - xB) / (x[end-1] - x[end]), x, y end
McCabeThiele
https://github.com/aumpierre-unb/McCabeThiele.jl.git
[ "MIT" ]
1.0.0
bcde119253c63737005e06f453c4e0c6eab70c61
code
1255
include("stages_updown.jl") include("stages_downup.jl") @doc raw""" `N=xyRq2N(data::Matrix{Float64}, X::Vector{Float64}, q::Number, R::Number, updown::Bool=true)` `xyRq2N` computes the number of theoretical stages of a distillation column using the McCabe-Thiele method given a function y = y(x) that relates the liquid fraction x and the vapor fraction y or a x-y matrix of the liquid and the vapor fractions, the vector of products and feed compositions, the feed quality, and the reflux ratio at the top of the column. If feed is a saturated liquid, feed quality q = 1, feed quality is reset to q = 1 - 1e-10. By default, theoretical stages are computed from the stripping section to the rectifying section, updown = true. If updown = false is given, theoretical stages are computed from the rectifying section to the stripping section. `xyRq2N` is is an internal function of the `McCabeThiele` toolbox for Julia. """ function xyRq2N(f, X, q, R, updown::Bool=true) xD, xF, xB = X xi = (xD / (R + 1) + xF / (q - 1)) / (q / (q - 1) - R / (R + 1)) yi = q / (q - 1) * xi - xF / (q - 1) X = [X; xi; yi] if updown N, x, y = stages_updown(f, X, R) else N, x, y = stages_downup(f, X, R) end N, X, x, y end
McCabeThiele
https://github.com/aumpierre-unb/McCabeThiele.jl.git
[ "MIT" ]
1.0.0
bcde119253c63737005e06f453c4e0c6eab70c61
code
282
using McCabeThiele using Test using Plots @testset "McCabeThiele.jl" begin # data(x) = x .^ 1.11 .* (1 - x) .^ 1.09 + x # x = [0.1 0.5 0.9] # q = 0.54 # R = refmin(data, x, q) # R = 1.7 * R # @test 9 > strays(data, x, q, R, true, false) > 8 end
McCabeThiele
https://github.com/aumpierre-unb/McCabeThiele.jl.git
[ "MIT" ]
1.0.0
bcde119253c63737005e06f453c4e0c6eab70c61
docs
8327
# McCabeThiele.jl [![DOI](https://zenodo.org/badge/543161141.svg)](https://doi.org/10.5281/zenodo.7126164) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![version](https://juliahub.com/docs/McCabeThiele/version.svg)](https://juliahub.com/ui/Packages/McCabeThiele/WauTj) ## Installing and Loading McCabeThiele McCabeThiele can be installed and loaded either from the JuliaHub repository (last released version) or from the [maintainer's repository](https://github.com/aumpierre-unb/McCabeThiele.jl). ### Last Released Version The last version of McCabeThiele can be installed from JuliaHub repository: ```julia using Pkg Pkg.add("McCabeThiele") using McCabeThiele ``` If McCabeThiele is already installed, it can be updated: ```julia using Pkg Pkg.update("McCabeThiele") using McCabeThiele ``` ### Pre-Release (Under Construction) Version The pre-release (under construction) version of McCabeThiele can be installed from the [maintainer's repository](https://github.com/aumpierre-unb/McCabeThiele.jl). ```julia using Pkg Pkg.add(path="https://github.com/aumpierre-unb/McCabeThiele.jl") using McCabeThiele ``` ## Citation of McCabeThiele You can cite all versions (both released and pre-released), by using [10.5281/zenodo.7126164](https://doi.org/10.5281/zenodo.7126164). This DOI represents all versions, and will always resolve to the latest one. ## The McCabeThiele Module for Julia McCabeThiele provides the following functions: - **stages** - **refmin** - **qR2S** - **qS2R** - **RS2q** ### **stages** stages computes the number of theoretical stages of a distillation column using the McCabe-Thiele method, given a function or a matrix of the liquid and the vapor fraction, the compositions of the feed and the products, the feed quality, and the reflux ratio at the top of the column. By default, feed is a saturated liquid at the feed stage, q = 1. If feed is a saturated liquid at the feed stage, q = 1, feed quality is reset to q = 1 - 1e-10. By default, theoretical stages are computed from the stripping section to the rectifying section, updown = true. If updown = false is given, theoretical stages are computed from the rectifying section to the stripping section. By default, stages plots a schematic diagram of the solution, fig = true. If fig = false is given, no plot is shown. **Syntax:** ```julia stages(data::Union{Matrix{Float64},Function},z::Vector{Float64}; q::Number=NaN,R::Number=NaN,S::Number=NaN,updown::Bool=true,fig::Bool=true) ``` **Examples:** Compute the number of theoretical stages of a distillation column from the bottom to the top of the column given a matrix that relates the liquid fraction and the vapor fraction, the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 %, the feed is a liquid-vapor equilibrium with 44 % vapor at the feed stage and the reflux ratio at the top of the column is 70 % higher than the minimum reflux ratio: ```julia data=[0. 0.; 0.1 0.212; 0.2 0.384; 0.3 0.529; 0.4 0.651; 0.5 0.752; 0.6 0.833; 0.7 0.895; 0.8 0.942; 0.9 0.974; 1. 1.]; x=[0.88;0.46;0.11]; r,s=refmin(data,x,q=1-0.44) N=stages(data,x,q=1-0.44,R=1.70*r,updown=false,fig=false) ``` Compute the number of theoretical stages of a distillation column from the top to the bottom of the column given the function that compute the vapor fraction given the liquid fraction, the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 %, the feed is saturated liquid at the feed stage and the reflux ratio at the top of the column is 70 % higher than the minimum reflux ratio and plot a schematic diagram of the solution: ```julia y(x)=x.^0.9 .* (1-x).^1.2 + x; x=[0.88;0.46;0.11]; r,s=refmin(y,x,q=1) N=stages(y,x,q=1,R=1.70*r) ``` ### **refmin** refmin computes the minimum value of the reflux ratio of a distillation column using the McCabe-Thiele method, given a function or a matrix of the liquid and the vapor fraction, the compositions of the feed and the distillate, and the feed quality. By default, feed is a saturated liquid at the feed stage, q = 1. If feed is a saturated liquid at the feed stage, q = 1, feed quality is reset to q = 1 - 1e-10. **Syntax:** ```julia refmin(data::Union{Matrix{Float64},Function},z::Vector{Float64},q::Number) ``` **Examples:** Compute the minimum value of the reflux ratio of a distillation column given a matrix that relates the liquid fraction and the vapor fraction, the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 % and the feed is a liquid-vapor equilibrium with 44 % vapor at the feed stage: ```julia data=[0. 0.; 0.1 0.212; 0.2 0.384; 0.3 0.529; 0.4 0.651; 0.5 0.752; 0.6 0.833; 0.7 0.895; 0.8 0.942; 0.9 0.974; 1. 1.]; x=[0.88;0.46;0.11]; r,s=refmin(data,x,q=1-0.44) ``` Compute the minimum value of the reflux ratio of a distillation column given the function that compute the vapor fraction given the liquid fraction, the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 % and the feed is saturated liquid at the feed stage: ```julia y(x)=x.^0.9 .* (1-x).^1.2 + x; x=[0.88;0.46;0.11]; r,s=refmin(y,x,q=1) ``` ### **qR2S** qR2S computes the reflux ratio at the bottom of the column, given the compositions of the feed and the products, the feed quality, and the reflux ratio at the top of the column. If feed is a saturated liquid, feed quality q = 1, feed quality is reset to q = 1 - 1e-10. **Syntax:** ```julia qR2S(z::Vector{Float64},q::Number,R::Number) ``` **Examples:** Compute the reflux ratio at the bottom of the column given the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 %, the feed is saturated liquid and the reflux ratio at the top of the column is 2: ```julia x=[0.88;0.46;0.11]; q=1; R=2; S=qR2S(x,q,R) ``` ### **qS2R** qS2R computes the reflux ratio at the top of a distillation column using the McCabe-Thiele method given the compositions of the products and the feed, the feed quality and the reflux ratio at the bottom of the column. If feed is a saturated liquid, feed quality q = 1, feed quality is reset to q = 1 - 1e-10. **Syntax:** ```julia qS2R(z::Vector{Float64},q::Number,S::Number) ``` **Examples:** Compute the reflux ratio at the top of the column given the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 %, the feed is saturated liquid and the reflux ratio at the bottom of the column is 2.5: ```julia x=[0.88;0.46;0.11]; q=1; S=2.5; R=qS2R(x,q,S) ``` ### **RS2q** RS2q computes the feed quality of a distillation column using the McCabe-Thiele method given the compositions of the products and the feed, the reflux ratio at the bottom of the column and the reflux ratio at the top of the column. If feed is a saturated liquid, feed quality q = 1, feed quality is reset to q = 1 - 1e-10. **Syntax:** ```julia RS2q(z::Vector{Float64}, R::Number, S::Number) ``` **Examples:** Compute the reflux ratio at the top of the column given the composition of the distillate is 88 %, the composition of the feed is 46 %, the composition of the column's bottom product is 11 %, the reflux ratio at the top of the column is 2 and reflux ratio at the bottom of the column is 2.5: ```julia x=[0.88;0.46;0.11]; R=2; S=2.5; q=RS2q(x,R,S) ``` ### See Also [PonchonSavarit.jl](https://github.com/aumpierre-unb/PonchonSavarit.jl), [Psychrometrics.jl](https://github.com/aumpierre-unb/Psychrometrics.jl), [InternalFluidFlow.jl](https://github.com/aumpierre-unb/InternalFluidFlow.jl). Copyright &copy; 2022 2023 Alexandre Umpierre email: <[email protected]>
McCabeThiele
https://github.com/aumpierre-unb/McCabeThiele.jl.git
[ "MIT" ]
0.1.6
8a609b85f354d460b65e1e07d90dde8c73b3e297
code
148
module FlexibleFunctors import ConstructionBase: constructorof export destructure, ffunctor, fieldmap include("param_functors.jl") end # module
FlexibleFunctors
https://github.com/Metalenz/FlexibleFunctors.jl.git
[ "MIT" ]
0.1.6
8a609b85f354d460b65e1e07d90dde8c73b3e297
code
3006
#= This code is adapted from Flux.jl/src/functors.jl, credit to Mike Innes, et al. A reference to the original code can be found here: https://github.com/FluxML/Flux.jl/blob/v0.10.0/src/functor.jl =# """ isleaf(x) Return true if `x` has no children according to [`parameters`](@ref). """ isleaf(x) = parameters(x) === () """ parameters(x) Returns a tuple of parameters, as marked by the user during construction """ parameters(x) = () parameters(x::Tuple) = x parameters(x::NamedTuple) = x parameters(x::AbstractArray) = x parameters(x::AbstractArray{<:Number}) = () """ parammap(f, x) Maps `f` to each parameter (as specified by [`parameters`](@ref)) to the model `x`. Evaluates calls to [`ffunctor`](@ref). """ function parammap(f, x) func, re = ffunctor(x) return re(map(f, func)) end """ ffunctor(x::T) Returns a flexible functor based on the chosen [`parameters`](@ref). """ function ffunctor(x::T) where T params = parameters(x) re = (y) -> begin all_args = map(fieldnames(T)) do fn field = fn in params ? getfield(y, fn) : getfield(x, fn) return field end return constructorof(T)(all_args...) end func = (; (p => getfield(x, p) for p in params)...) return func, re end ffunctor(x::AbstractArray) = x, y -> y ffunctor(x::AbstractArray{<:Number}) = (), _ -> x """ destructure(s) For a struct `s` which has parameters given by [`parameters`](@ref), iterates through all non-leaf nodes and collects the marked fields into a flat vector. This is particularly useful for model training or optimization, or use with `ForwardDiff`. A function which restructures `s` according to a flat vector is returned as the second argument. NOTE: The flat vector representation is a `Vector{T}`. Julia will promote all entries to a common type if possible. This means [1, 2.0] == [1.0, 2.0] and both are Vector{Float64}. """ function destructure(s) xs = [] fieldmap(s) do x x isa AbstractArray && push!(xs, x) x isa Number && push!(xs, [x]) return x end return vcat(vec.(copy(xs))...), p -> restructure(s, p) end """ restructure(s, xs) Given a struct `s` with parameters given by [`parameters`](@ref), restructures `s` according to the vector `xs`. In particular, `s == restructure(s, destructure(s)[1])`. """ function restructure(s, xs) i = 0 fieldmap(s) do x if x isa AbstractArray x = reshape(xs[i.+(1:length(x))], size(x)) i += length(x) elseif x isa Number x = xs[i+1] i += 1 end return x end end """ fieldmap(f, x; exlude = isleaf) Maps the function `f` over the fields of a `FlexibleFunctor` (equivalently, the parameter fields of a struct `s` given by [`parameters`](@ref)). """ function fieldmap(f, x; exclude = isleaf) y = exclude(x) ? f(x) : parammap(x -> fieldmap(f, x; exclude = exclude), x) return y end
FlexibleFunctors
https://github.com/Metalenz/FlexibleFunctors.jl.git
[ "MIT" ]
0.1.6
8a609b85f354d460b65e1e07d90dde8c73b3e297
code
2028
using FlexibleFunctors; const FF = FlexibleFunctors # Standard struct with constant parameters struct Foo{X,Y,PS<:Tuple} x::X y::Y ps::PS end FF.parameters(f::Foo) = f.ps @testset "Parameters" begin @test FF.parameters([1, 2]) === () A = [Ref(1), Ref(2)] @test FF.parameters(A) === A @test FF.parameters((1, 2)) == (1, 2) @test FF.parameters((a=1, b=2)) == (a=1, b=2) p0, re = ffunctor([1, 2]) @test p0 === () p0, re = ffunctor(A) @test p0 === A end @testset "FlexibleFunctors" begin # No parameters mf1 = Foo(1, 2, ()) p0, re = ffunctor(mf1) @test re(()) == mf1 # One parameters mf2 = Foo(1.0, 2, (:x, )) p0, re = ffunctor(mf2) @test re(p0) == mf2 # Reconstruct self _, re2 = destructure(mf2) @test re2([1]) == Foo(1, 2, (:x,)) # Change type on Foo.x from Float64 to Int # Both fields as parameters mf3 = Foo(22.0, 3.14, (:x, :y)) p0, re = destructure(mf3) @test re(p0) == mf3 @test re(reverse(p0)) == Foo(3.14, 22.0, (:x, :y)) # Swap the fields # Nested parameters mf4 = Foo(Foo(1, 2, (:y,)), 3, (:x, :y)) p0, re = destructure(mf4) @test re(p0) == mf4 @test re(["hello", -1]) == Foo(Foo(1, "hello", (:y,)), -1, (:x, :y)) end @testset "fieldmap" begin mf1 = Foo(3.0, 2, (:x,)) @test fieldmap((x) -> x^2, mf1) == Foo(9.0, 2, (:x,)) mf2 = Foo(-22.0, 3.14, (:x, :y)) @test fieldmap(abs, mf2) == Foo(22.0, 3.14, (:x, :y)) mf3 = Foo(Foo(1, 2, (:y,)), 3, (:x, :y)) @test fieldmap(sqrt, mf3) == Foo(Foo(1, sqrt(2), (:y,)), sqrt(3), (:x, :y)) end module MyMod import FlexibleFunctors struct Bar{A,B,PS<:Tuple} a::A b::B parameters::PS end FlexibleFunctors.parameters(b::Bar) = b.parameters end import .MyMod @testset "Reconstruction of Module-Specific Type" begin mb = MyMod.Bar(1, 2, (:a,)) p0, re = destructure(mb) @test re(p0) == mb @test re([3]) == MyMod.Bar(3, 2, (:a,)) end
FlexibleFunctors
https://github.com/Metalenz/FlexibleFunctors.jl.git
[ "MIT" ]
0.1.6
8a609b85f354d460b65e1e07d90dde8c73b3e297
code
42
using Test @time include("ffunctors.jl")
FlexibleFunctors
https://github.com/Metalenz/FlexibleFunctors.jl.git
[ "MIT" ]
0.1.6
8a609b85f354d460b65e1e07d90dde8c73b3e297
docs
3830
# FlexibleFunctors.jl `FlexibleFunctors.jl` allows you to convert struct fields to a flat vector representation, and it also provides a function to transform similar vectors back into structs. However, `FlexibleFunctors.jl` also provides a `parameters(x)` function which can be extended to dynamically determine which fields make it into the vector and which fields are fixed. ## Example ```julia using FlexibleFunctors, Zygote import FlexibleFunctors: parameters struct Model elements params end parameters(m::Model) = m.params struct Square w params end parameters(s::Square) = s.params area(s::Square) = s.w^2 s1 = Square(1.0, (:w,)) s2 = Square(2.0, ()) s3 = Square(3.0, (:w,)) m1 = Model([s1, s2, s3], (:elements,)) m2 = Model([s1, s2, s3], ()) p1, re1 = destructure(m1) p2, re2 = destructure(m2) julia> println(p1) # [1.0, 3.0] julia> println(p2) # Any[] # Replace first and third widths with vector values julia> mapreduce((s)->area(s), +, re1([3.0, 4.0]).elements) # 29 # Uses original widths since `m2` has no parameters julia> mapreduce((s)->area(s), +, re2([3.0, 4.0]).elements) # 14 # Map vector of parameters to an object for optimization grad = Zygote.gradient((x) -> mapreduce(area, +, x.elements), re1([3.0, 4.0])); julia> getfield.(grad[1].elements, :w) # [6.0, 4.0, 8.0] ``` ## Overview `FlexibleFunctors.jl` adds the ability to specify individual fields of a type as parameters. These parameters indicate fields which can be retrieved to obtain a flat vector representation of the struct parameters through `destructure`. `destructure` also returns a function, `re`, which reconstructs an instance of the original type. `re` operates as a function of the flat vector representation, but the reconstructed values of parameter fields are drawn from this vector while non-parameter fields are left unchanged. Parameters are determined recursively. If a tagged field contains a struct with parameters of its own, those parameters are also included in the resulting vector and reconstruction. `ffunctor` takes a struct instance with a `parameters` method and returns a `NamedTuple` representation of the parameters. `ffunctor` also returns a `re` function for reconstructing the `struct` from the `NamedTuple` representation. In either case, you must provide a `FlexibleFunctors.parameters(::YourType)` method which return the parameters of `YourType` in a `Tuple` of `Symbol`s. This is accomplished by `import`ing `FlexibleFunctors.jl` and adding additional methods directly to `parameters`. ## What's Flexible about FlexibleFunctors? The functionality provided by `FlexibleFunctors.jl` is similar to `Functors.jl`. Both projects annotate types with special fields to convert in between flat vector representations of structs and a `re`constructed instance. However, `Functors.jl` stores this information at the type-level for all instances of a type, forcing all instances to use identical fields as (what we call) parameters. `FlexibleFunctors.jl` can store these parameter fields at the instance-level. For example, instead of hard-coding the returned parameters, we could add a `parameters` field to a `struct`, and then specify these `parameters` at run-time as a tuple of `Symbol`s. In this way, we can use the same types but specialize which fields are actually parameterized and liable to be changed during a `re`construction. If parameter fields are stored within a struct instance, re-parameterizing the type instance is possible. For this, we recommend [Setfield.jl](https://github.com/jw3126/Setfield.jl) and the `@set` macro which can easily update nested fields. Further, note that `FlexibleFunctors.jl` can reproduce similar behavior to `Functors.jl`. If `parameters(m::M) = (:some, :fixed, :tuple)`, then all instances of `M` will have the same parameters.
FlexibleFunctors
https://github.com/Metalenz/FlexibleFunctors.jl.git
[ "MIT" ]
0.1.0
885ac78c0988377171063296a13558e21dd5d8ba
code
117
module NoiseModels import StatsAPI: fit export GaussianNoiseModel export fit include("gaussian.jl") end # module
NoiseModels
https://github.com/org-arl/NoiseModels.jl.git
[ "MIT" ]
0.1.0
885ac78c0988377171063296a13558e21dd5d8ba
code
2994
import Optimization: OptimizationFunction, OptimizationProblem, solve, SciMLBase, AutoZygote import OptimizationOptimJL: BFGS import Statistics: cov, std import Random: GLOBAL_RNG, AbstractRNG import Zygote """ Multichannel colored Gaussian noise model. """ struct GaussianNoiseModel s::Vector{Float64} # per-channel scaling factor α::Array{Float64,3} # noise mixing parameters end function Base.show(io::IO, model::GaussianNoiseModel) print(io, "GaussianNoiseModel($(size(model.α,1)) channel$(size(model.α,1)==1 ? "" : "s"))") end """ fit(GaussianNoiseModel, data::AbstractArray; maxlag=64, maxiters=100) Fit a multichannel colored Gaussian noise model to `data`. Returns a fitted model struct. `maxlag` controls the maximum time lag (in samples) to estimate noise correlation. `maxiters` controls the maximum number of iterations for optimization. """ function fit(::Type{GaussianNoiseModel}, data::AbstractMatrix; maxlag=64, maxiters=100, verbose=false) # estimate scale factor to make the problem numerically stable s = std(data; dims=1) s[s .< 1e-6] .= 0 data = data ./ s # estimate covariance matrix verbose && @info "Estimating covariance matrix..." nchannels = size(data, 2) R̄ = zeros(nchannels, nchannels, maxlag+1) Threads.@threads for i ∈ 1:nchannels for j ∈ 1:nchannels @simd for δ ∈ 0:maxlag @inbounds R̄[i,j,δ+1] = @views cov(data[1+δ:end,i], data[1:end-δ,j]) end end end # pick a good initial value for noise mixing parameters α0 = zeros(size(R̄)) for i ∈ 1:nchannels α0[i,i,1] = 1 end # estimate noise mixing parameters verbose && @info "Estimating mixing parameters..." @info "Initial loss = $(first(_gaussian_loss(vec(α0), R̄)))" optf = OptimizationFunction(_gaussian_loss, AutoZygote()) prob = OptimizationProblem(optf, vec(α0), R̄) sol = solve(prob, BFGS(); maxiters) @info "Final loss = $(first(_gaussian_loss(sol.u, R̄)))" # create noise model GaussianNoiseModel(vec(s), reshape(sol.u, size(α0))) end function fit(modeltype::Type{GaussianNoiseModel}, data::AbstractVector) fit(modeltype, Base.ReshapedArray(data, (length(data),1), ())) end """ rand(model::GaussianNoiseModel, n) rand(rng::AbstractRNG, model::GaussianNoiseModel, n) Generate `n` time samples of multichannel colored Gaussian noise as per the `model`. """ function Base.rand(rng::AbstractRNG, model::GaussianNoiseModel, n::Integer) nchannels, _, nlags = size(model.α) z = randn(nchannels, n + nlags - 1) x = zeros(n, nchannels) for i ∈ 1:nchannels, k ∈ 1:n x[k,i] += sum(model.α[i,:,:] .* z[:,k:k+nlags-1]) end x .* model.s' end Base.rand(model::GaussianNoiseModel, n::Integer) = rand(GLOBAL_RNG, model, n) ### helpers function _gaussian_loss(u, R̄) α = reshape(u, size(R̄)) s = 0.0 @inbounds for i ∈ 1:size(R̄,1), j ∈ 1:size(R̄,2), δ ∈ 0:size(R̄,3)-1 R = @views sum(α[i,:,1:end-δ] .* α[j,:,1+δ:end]) s += abs2(R̄[i,j,δ+1] - R) end s, nothing end
NoiseModels
https://github.com/org-arl/NoiseModels.jl.git
[ "MIT" ]
0.1.0
885ac78c0988377171063296a13558e21dd5d8ba
docs
747
# NoiseModels.jl **Generative noise models** ### Installation ```julia julia> # press ] for pkg mode pkg> add NoiseModels ``` ### Models Currently the only model implemented is a `GaussianNoiseModel`. This model generates multichannel colored Gaussian noise given a noise sample or a covariance tensor. ### Usage Given `training_data` as a $T \times N$ matrix of $T$ time samples and $N$ channels, we train a `GaussianNoiseModel` as follows: ```julia using NoiseModels # fit a GaussianNoiseModel to training_data model = fit(GaussianNoiseModel, training_data) ``` To generate noise samples with the same statistics as the training data: ```julia # generate 10000 time samples of N channel random noise generated = rand(model, 10000) ```
NoiseModels
https://github.com/org-arl/NoiseModels.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
406
using Documenter using FlightMechanicsUtils makedocs( sitename = "Flight Mechanics Utils Documentation", modules = [FlightMechanicsUtils], pages = ["Home" => "index.md", "API" => "api.md"], format = Documenter.HTML(prettyurls = get(ENV, "CI", nothing) == "true"), ) deploydocs( repo = "github.com:AlexS12/FlightMechanicsUtils.jl.git", push_preview=true, devbranch = "main" )
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
1332
module FlightMechanicsUtils using LinearAlgebra using StaticArrays export γ_AIR, R_AIR export gD export RAD2DEG, DEG2RAD, M2FT, FT2M, KEL2RANK, RANK2KEL, KG2LB, LB2KG, SLUG2KG, KG2SLUG export PSF2PA, PA2PSF, SLUGFT32KGM3, KGM32SLUGFT3 include("constants.jl") export atmosphere_isa include("atmosphere.jl") export rigid_body_velocity, rigid_body_acceleration export pqr_2_ψθϕ_dot, pqr_2_quat_dot, ψθϕ_dot_2_pqr export uvw_to_tasαβ, uvw_dot_to_tasαβ_dot, tasαβ_dot_to_uvw_dot export rate_of_climb_constrain_no_wind include("kinematics.jl") export coordinated_turn_bank, steiner_inertia, translate_forces_moments include("mechanics.jl") export euler_angles, quaternions, rotation_matrix_zyx export body2horizon, body2wind export wind2body, wind2horizon export horizon2body, horizon2wind export horizon2ecef, ecef2horizon include("rotations.jl") export Ellipsoid export Clarke1866, Clarke1880, International, Bessel, Everest, ModifiedEverest, AustralianNational, SouthAmerican1969, Airy, ModifiedAiry, Hough, Fischer1960SouthAsia, Fischer1960Mercury, Fischer1968, WGS60, WGS66, WGS72, WGS84 export llh2ecef, ecef2llh include("ellipsoid.jl") export qc2cas, qc2eas, qc2tas export cas2eas, cas2tas export eas2cas, eas2tas export tas2cas, tas2eas export compressible_qinf, incompressible_qinf include("anemometry.jl") end
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
4660
# Air at sea level conditions h=0 (m) const ρ0 = 1.225 # Density at sea level (kg/m3) const p0 = 101325.0 # Pressure at sea level (Pa) const a0 = 340.293990543 # Sound speed at sea level (m/s) """ qc2cas(qc) Calculate calibrated airspeed from ASI (Air Speed indicator), differential pressure between impact pressure and static pressure. ``qc = p_t - p_s`` # References 1. Ward, D. T. (1993). Introduction to flight test engineering. Elsevier Science Ltd. (page 13, formula 2.13) """ function qc2cas(qc) cas = sqrt((2*γ_AIR*p0) / ((γ_AIR - 1) * ρ0) * ((qc / p0 + 1) ^ ((γ_AIR - 1) / γ_AIR) - 1)) return cas end """ qc2tas(qc, ρ, p) Calculate true airspeed from ASI (Air Speed indicator), differential pressure between impact pressure and static pressure (qc = p_t - p_s), rho and p. # References 1. Ward, D. T. (1993). Introduction to flight test engineering. Elsevier Science Ltd. (page 12, based on formula 2.11) """ function qc2tas(qc, ρ, p) tas2 = (2*γ_AIR*p) / ((γ_AIR - 1) * ρ0) * ((qc/p + 1) ^ ((γ_AIR - 1) / γ_AIR) - 1) * ρ0/ρ tas = sqrt(tas2) return tas end """ qc2eas(qc, p) Calculate equivalent airspeed from ASI (Air Speed indicator), differential pressure between impact pressure and static pressure (qc = p_t - p_s) and p. # References 1. Ward, D. T. (1993). Introduction to flight test engineering. Elsevier Science Ltd. """ function qc2eas(qc, p) eas = sqrt((2*γ_AIR*p) / ((γ_AIR - 1) * ρ0) * ((qc/p + 1) ^ ((γ_AIR - 1) / γ_AIR) - 1)) return eas end """ tas2eas(tas, ρ) Calculate equivalent airspeed from true airspeed and density at current altitude (ρ). # References 1. Ward, D. T. (1993). Introduction to flight test engineering. Elsevier Science Ltd. (page 13, formula 2.15) """ function tas2eas(tas, ρ) eas = tas * sqrt(ρ / ρ0) return eas end """ eas2tas(qc, ρ) Calculate true airspeed from equivalent airspeed and density at current altitude (ρ). # References 1. Ward, D. T. (1993). Introduction to flight test engineering. Elsevier Science Ltd. (page 13, formula 2.15) """ function eas2tas(eas, ρ) tas = eas / sqrt(ρ / ρ0) return tas end """ cas2eas(cas, ρ, p) Calculate equivalent airspeed from calibrated airspeed, density (ρ) and pressure (p) at the current altitude. """ function cas2eas(cas, ρ, p) tas = cas2tas(cas, ρ, p) eas = tas2eas(tas, ρ) return eas end """ eas2cas(eas, ρ, p) Calculate calibrated airspeed from equivalent airspeed, density (ρ) and pressure (p) at the current altitude. """ function eas2cas(eas, ρ, p) tas = eas2tas(eas, ρ) cas = tas2cas(tas, ρ, p) return cas end """ cas2tas(cas, ρ, p) Calculate true airspeed from calibrated airspeed, density (ρ) and pressure (p) at the current altitude. """ function cas2tas(cas, ρ, p) a = sqrt(γ_AIR * p / ρ) temp = (cas*cas * (γ_AIR - 1.0)/(2.0 * a0*a0) + 1.0) ^ (γ_AIR / (γ_AIR - 1.0)) temp = (temp - 1.0) * (p0 / p) temp = (temp + 1.0) ^ ((γ_AIR - 1.0) / γ_AIR) - 1.0 tas = sqrt(2.0 * a*a / (γ_AIR - 1.0) * temp) return tas end """ tas2cas(cas, ρ, p) Calculate true airspeed from calibrated airspeed, density (ρ) and pressure (p) at the current altitude. """ function tas2cas(tas, ρ, p) a = sqrt(γ_AIR * p / ρ) temp = (tas*tas * (γ_AIR - 1.0)/(2.0 * a*a) + 1.0) ^ (γ_AIR / (γ_AIR - 1.0)) temp = (temp - 1.0) * (p / p0) temp = (temp + 1.0) ^ ((γ_AIR - 1.0) / γ_AIR) - 1.0 cas = sqrt(2.0 * a0*a0 / (γ_AIR - 1) * temp) return cas end """ incompressible_qinf(tas, ρ) Calculate incompressible dynamic pressure from true airspeed (tas) and density (ρ) at current altitude. # References 1. Ward, D. T. (1993). Introduction to flight test engineering. Elsevier Science Ltd. (page 13, formula 2.14) """ function incompressible_qinf(tas, ρ) return 0.5 * ρ * tas*tas end """ compressible_qinf(tas, p, a) Calculate compressible dynamic pressure from Mach number and static pressure (p) Two different models are used depending on the Mach number: - Subsonic case: Bernouilli's equation compressible form. - Supersonic case: to be implemented. # References 1. Ward, D. T. (1993). Introduction to flight test engineering. Elsevier Science Ltd. (page 12) 2. Fundamentals of Aerdynamics, 5th edition, J.D.Anderson Jr (page 550) """ function compressible_qinf(M, p) if M < 1 pt = p * (1 + (γ_AIR - 1) / 2 * M*M) ^ (γ_AIR / (γ_AIR - 1)) else # (M >= 1) pt = p * ((1 - γ_AIR + (2 * γ_AIR * M^2))/(γ_AIR + 1)) * (((γ_AIR + 1)^2 * M^2)/((4 * γ_AIR * M^2) - 2*(γ_AIR - 1)))^(γ_AIR / (γ_AIR - 1)) end return pt end
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
2697
""" atmosphere_isa(height) Calculate temperature, pressure, density and sound velocity for the given geopotential height according to International Standard Atmosphere 1976. # References 1.U.S. Standard Atmosphere, 1976, U.S. Government Printing Office, Washington, D.C., 1976 | Layer | h (m) | p (Pa) | T (K) | ``α`` (K/m) | | ----- | ----- | ------- | ------ | ----------- | | 0 | 0 | 101325 | 288.15 | -0.0065 | | 1 | 11000 | 22632.1 | 216.65 | 0 | | 2 | 20000 | 5474.89 | 216.65 | 0.001 | | 3 | 32000 | 868.019 | 228.65 | 0.0028 | | 4 | 47000 | 110.906 | 270.65 | 0 | | 5 | 51000 | 66.9389 | 270.65 | -0.0028 | | 6 | 71000 | 3.95642 | 214.65 | -0.002 | Source: [https://en.wikipedia.org/wiki/U.S._Standard_Atmosphere](https://en.wikipedia.org/wiki/U.S._Standard_Atmosphere) """ function atmosphere_isa(height) if 0 <= height < 11000 # Troposphere α = -0.0065 # K/m T0 = 288.15 # K p0 = 101325.0 # Pa T = T0 + α * height p = p0 * (T0 / T) ^ (gD / (R_AIR * α)) elseif 11000 <= height < 20000 # Tropopause T = 216.65 # K p0 = 22632.1 # Pa h0 = 11000 # m p = p0 * exp(-gD * (height - h0) / (R_AIR * T)) elseif 20000 <= height < 32000 # Stratosphere 1 α = 0.001 # K/m T0 = 216.65 # K p0 = 5474.89 # Pa h0 = 20000 # m T = T0 + α * (height - h0) p = p0 * (T0 / T) ^ (gD / (R_AIR * α)) elseif 32000 <= height < 47000 # Stratosphere 2 α = 0.0028 # K/m T0 = 228.65 # K p0 = 868.019 # Pa h0 = 32000 # m T = T0 + α * (height - h0) p = p0 * (T0 / T) ^ (gD / (R_AIR * α)) elseif 47000 <= height < 51000 # Stratopause T = 270.65 # K p0 = 110.906 # Pa h0 = 47000 # m h0 = 47000 # m p = p0 * exp(-gD * (height - h0) / (R_AIR * T)) elseif 51000 <= height < 71000 # Mesosphere 1 α = -0.0028 # K/m T0 = 270.65 # K p0 = 66.9389 # Pa h0 = 51000 # m T = T0 + α * (height - h0) p = p0 * (T0 / T) ^ (gD / (R_AIR * α)) elseif 71000 <= height <= 84500 # Mesosphere 2 α = -0.002 # K/m T0 = 214.65 # K p0 = 3.95642 # Pa h0 = 71000 # m T = T0 + α * (height - h0) p = p0 * (T0 / T) ^ (gD / (R_AIR * α)) else throw(DomainError(height, "height must be between 0 m and 84500 m")) end rho = p / (R_AIR * T) a = sqrt(γ_AIR * R_AIR * T) return [T, p, rho, a] end
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
1372
# ------------------------ Air ------------------------ """ γ_AIR = 1.4 Adiabatic index or ratio of specific heats (dry air at 20º C). """ const γ_AIR = 1.4 """ R_AIR = 287.05287 (J/(Kg·K)) Specific gas constant for dry air. """ const R_AIR = 287.05287 # ------------------------ Earth ------------------------ """ gD = 9.80665 (m/s²) Down component of gravity acceleration at Earth surface at 45º geodetic latitude. 1. Stevens, B. L., Lewis, F. L., & Johnson, E. N. (2015). Aircraft control and simulation: dynamics, controls design, and autonomous systems. John Wiley & Sons. Equation (page 33) """ const gD = 9.80665 # m/s² # ------------------------ UNIT CONVERSION ------------------------ # ANGLES const RAD2DEG = 57.29578 # Radians (rad) to degrees (deg) const DEG2RAD = 1 / RAD2DEG # LENGTH const FT2M = 0.3048 # Feet (ft) to meter (m) const M2FT = 1 / FT2M # TEMPERATURE const KEL2RANK = 1.8 # Kelvin to Rankine const RANK2KEL = 1 / KEL2RANK # MASS const KG2LB = 2.20462262185 # Kilogram (Kg) to pound (lb) const LB2KG = 1 / KG2LB const SLUG2KG = 14.5939029372 # Slug to Kilogram (kg) const KG2SLUG = 1 / SLUG2KG # PRESSURE const PSF2PA = LB2KG * gD / FT2M^2 # Pounds per square foot (PSF) to Pascal (Pa) const PA2PSF = 1 / PSF2PA const SLUGFT32KGM3 = SLUG2KG / FT2M^3 # slug/ft³ to Kg/m³ const KGM32SLUGFT3 = 1 / SLUGFT32KGM3
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
6051
@doc raw""" Ellipsoid(a, b, f, finv, e2, ϵ2, name) Ellipsoid(a, finv, name) Earth ellipsoid model. # Fields - `a::Real`: semi-major axis (m). - `b::Real`: semi-minor axis (m). - `f::Real`: flattening (``f``). - `finv::Real`: inverse of flattening (``f^{-1}``). - `e2::Real`: eccentricity squared. - `ϵ2::Real`: second eccentricity squared. - `name::String`: ellipsoid name. # Notes ``a`` is the semi-major axis, ``b`` is the semi-minor axis. Ellipsoids are normally defined by ``a`` and ``f^{-1}``. The rest of parameters are derived. - Flattening: ```math f = 1 - \frac{b}{a} ``` - Eccentricity (first eccentricity): ```math e^2 = \frac{a^2 - b^2}{a^2} = f (2 - f) ``` - Second eccentricity: ```math ϵ^2 = \frac{a^2 - b^2}{b^2} = \frac{f (2 - f)}{(1 - f)^2} ``` # References 1. Stevens, B. L., Lewis, F. L., (1992). Aircraft control and simulation: dynamics, controls design, and autonomous systems. John Wiley & Sons. Section 1.6 (page 23) 2. Rogers, R. M. (2007). Applied mathematics in integrated navigation systems. American Institute of Aeronautics and Astronautics. Chapter 4 (Nomenclature differs from 1). 3. Bowring, B. R. (1976). Transformation from spatial to geographical coordinates. Survey review, 23(181), 323-327. """ struct Ellipsoid "Semi-major axis (m)." a::Real "Semi-minor axis (m)." b::Real "Flattening ``f = \frac{a-b}{a} = a - \frac{b}{a}``." f::Real "Inverse of flattening." finv::Real "Eccentricity. ``e^2 = \frac{a^2 - b^2}{a^2} = f (2 - f)``" e2::Real "Second eccentricity. ``ϵ^2 = \frac{a^2 - b^2}{b^2} = \frac{f (2 - f)}{(1 - f)^2}``." ϵ2::Real "Ellipsoid name." name::String end function Ellipsoid(a, finv, name) f = 1 / finv b = a * (1 - f) e2 = f * (2 - f) ϵ2 = e2 / (1 - f)^2 return Ellipsoid(a, b, f, finv, e2, ϵ2, name) end # Rogers, R. M. (2007). Applied mathematics in integrated navigation systems. # American Institute of Aeronautics and Astronautics. (Page 76, table 4.1) const Clarke1866 = Ellipsoid(6378206.4, 294.9786982, "Clarke1866") const Clarke1880 = Ellipsoid(6378249.145, 294.465, "Clarke1880") const International = Ellipsoid(6378388.0, 297.0, "International") const Bessel = Ellipsoid(6377397.155, 299.1528128, "Bessel") const Everest = Ellipsoid(6377276.345, 300.8017, "Everest") const ModifiedEverest = Ellipsoid(6377304.063, 300.8017, "ModifiedEverest") const AustralianNational = Ellipsoid(6378160.0, 298.25, "AustralianNational") const SouthAmerican1969 = Ellipsoid(6378160.0, 298.25, "SouthAmerican1969") const Airy = Ellipsoid(6377564.396, 299.3249646, "Airy") const ModifiedAiry = Ellipsoid(6377340.189, 299.3249646, "ModifiedAiry") const Hough = Ellipsoid(6378270.0, 297.0, "Hough") const Fischer1960SouthAsia = Ellipsoid(6378155.0, 298.3, "Fischer1960SouthAsia") const Fischer1960Mercury = Ellipsoid(6378166.0, 298.3, "Fischer1960Mercury") const Fischer1968 = Ellipsoid(6378150.0, 298.3, "Fischer1968") const WGS60 = Ellipsoid(6378165.0, 298.3, "WGS60") const WGS66 = Ellipsoid(6378145.0, 298.25, "WGS66") const WGS72 = Ellipsoid(6378135.0, 298.26, "WGS72") const WGS84 = Ellipsoid(6378137.0, 298.257223563, "WGS84") """ llh2ecef(lat, lon, height; ellipsoid=WGS84) Transform geodetic latitude, longitude (rad) and ellipsoidal height (m) to ECEF for the given ellipsoid (default ellipsoid is WGS84). # References 1. Rogers, R. M. (2007). Applied mathematics in integrated navigation systems. American Institute of Aeronautics and Astronautics. (Page 75, equations 4.20, 4.21, 4.22) """ function llh2ecef(lat, lon, height; ellipsoid=WGS84) f = ellipsoid.f a = ellipsoid.a e2 = ellipsoid.e2 var = a / sqrt(1.0 - e2 * sin(lat)*sin(lat)) px = (var + height) * cos(lat)*cos(lon) py = (var + height) * cos(lat)*sin(lon) pz = (var * (1.0 - e2) + height)* sin(lat) return [px, py, pz] end """ ecef2llh(xecef, yecef, zecef; ellipsoid=WGS84) Transform ECEF coordinates to geodetic latitude, longitude (rad) and ellipsoidal height (m) for the given ellipsoid (default ellipsoid is WGS84). # Notes * The transformation is direct without iterations as [1] introduced the need to iterate for near Earth positions. * [2] is an update of increased accuracy of [1]. The former is used in this implementation although the latter implementation is commented in the code. * Model becomes unstable if latitude is close to 90º. An alternative equation can be found in [2] equation (16) but has not been implemented. # References 1. Bowring, B. R. (1976). Transformation from spatial to geographical coordinates. Survey review, 23(181), 323-327. 2. Bowring, B. R. (1985). The accuracy of geodetic latitude and height equations. Survey Review, 28(218), 202-206. """ function ecef2llh(xecef, yecef, zecef; ellipsoid=WGS84) x, y, z = xecef, yecef, zecef e = sqrt(ellipsoid.e2); e2 = ellipsoid.e2 ϵ2 = ellipsoid.ϵ2 a = ellipsoid.a b = ellipsoid.b p = sqrt(x*x + y*y) R = sqrt(p*p + z*z) θ = atan(z, p) # [1] equation (1) does not change in [2] lon = atan(y, x) # u -> geographical latitude # [1] below equation (4) and [2] equation (6) # This lead to errors in latitud with maximum value 0.0018" #u = atan(a/b * z/x) # [2] equation (17) If the latitude is also required to be very accurate # for outer-space positions then the value of u for (6) should be obtained # from: u = atan(b*z / (a*p) * (1 + ϵ2 * b / R)) # [1] equation (4) #lat = atan((z + ϵ2 * b * sin(u)^3) / (x - e2 * a * cos(u)^3)) # [2] equation (18) lat = atan((z + ϵ2 * b * sin(u)^3) / (p - e2 * a * cos(u)^3)) # [2] after equation (1) v = a / sqrt(1.0 - e2*sin(lat)^2) # [2] equation (7) # height = p*cos(lat) + z*sin(lat) - a*a / v # equivalent to [2] equation (8) height = R * cos(lat - θ) - a*a / v # which is insensitive to the error in latitude calculation (The influence # is of order 2 [2] equation (12)) return [lat, lon, height] end
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
7563
@doc raw""" rigid_body_velocity(vel_P, ω, r_PQ) Calculate rigid solid velocity field. Return velocity of a point Q of a rigid solid given the velocity of a point P (vel_P), the rotational velocity of the solid (ω) and the relative position of Q with respect to P. If the reference frame 1 is attached to the solid and the velocity is calculated with respect to reference frame 0: ``v_{10}^{Q} = v_{10}^{P} + \omega_{10} \times r^{PQ}`` being: - ``v_{10}^{Q}`` the velocity of point Q, fixed to 1, wrt 0 - ``\omega_{10}`` the angular velocity of the solid 1 wrt 0 - ``r^{PQ}`` the position of Q wrt P (``r^{Q}-r^{P}``) Every vector needs to be expressed in the same coordinate system. # References 1. Stevens, B. L., Lewis, F. L., (1992). Aircraft control and simulation: dynamics, controls design, and autonomous systems. John Wiley & Sons. (Section 1.3, page 26) """ function rigid_body_velocity(vel_P, ω, r_PQ) vel_Q = vel_P + ω × r_PQ return vel_Q end @doc raw""" rigid_body_acceleration(acc_P, ω, ω_dot, r_PQ) Calcualte rigid body acceleration field. Return the acceleration of a point Q of a rigid solid given the acceleration of a point P (acc_P), the rotational velocity of the solid (ω), the rotational acceleration of the solid (ω_dot) and the relative position of Q with respect to P. ``a_{10}^{Q} = a_{10}^{P} + \omega_{10} \times (\omega_{10} \times r^{PQ}) + \dot{\omega}_{10} \times r^{PQ}`` being: - ``a_{10}^{Q}`` the acceleration of point Q, fixed to 1, wrt 0 - ``\omega_{10}`` the angular velocity of the solid 1 wrt 0 - ``\dot{\omega}_{10}`` the angular acceleration of the solid 1 wrt 0 - ``r^{PQ}`` the position of Q wrt P (``r^{Q}-r^{P}``) # References 1. Stevens, B. L., Lewis, F. L., (1992). Aircraft control and simulation: dynamics, controls design, and autonomous systems. John Wiley & Sons. (Section 1.3, Formaula 1.3-14c, page 26) """ function rigid_body_acceleration(acc_P, ω, ω_dot, r_PQ) acc_Q = acc_P + ω × (ω × r_PQ) + ω_dot × r_PQ return acc_Q end """ pqr_2_ψθϕ_dot(p, q, r, ψ, θ, ϕ) Transform body angular velocity (p, q, r) [rad/s] to Euler angles rates (ψ_dot, θ_dot, ϕ_dot) [rad/s] given the euler angles (θ, ϕ) [rad] using kinematic angular equations. # See also [`ψθϕ_dot_2_pqr`](@ref), [`pqr_2_quat_dot`](@ref) # References 1. Stevens, B. L., Lewis, F. L., & Johnson, E. N. (2015). Aircraft control and simulation: dynamics, controls design, and autonomous systems. John Wiley & Sons. Equation (1.4-4) (page 20) """ function pqr_2_ψθϕ_dot(p, q, r, θ, ϕ) sθ, cθ = sin(θ), cos(θ) sϕ, cϕ = sin(ϕ), cos(ϕ) ψ_dot = (q * sϕ + r * cϕ) / cθ θ_dot = q * cϕ - r * sϕ # ϕ_dot = p + (q * sϕ + r * cϕ) * tan(θ) ϕ_dot = p + ψ_dot * sθ return [ψ_dot, θ_dot, ϕ_dot] end """ ψθϕ_dot_2_pqr(ψ_dot, θ_dot, ϕ_dot, ψ, θ, ϕ) Transform Euler angles rates (ψ_dot, θ_dot, ϕ_dot) [rad/s] to body angular velocity (p, q, r) [rad/s] given the euler angles (θ, ϕ) [rad] using kinematic angular equations. # See also [`pqr_2_ψθϕ_dot`](@ref) # References 1. Stevens, B. L., Lewis, F. L., & Johnson, E. N. (2015). Aircraft control and simulation: dynamics, controls design, and autonomous systems. John Wiley & Sons. Equation (1.4-3) (page 20) """ function ψθϕ_dot_2_pqr(ψ_dot, θ_dot, ϕ_dot, θ, ϕ) sθ, cθ = sin(θ), cos(θ) sϕ, cϕ = sin(ϕ), cos(ϕ) p = ϕ_dot - sθ * ψ_dot q = cϕ * θ_dot + sϕ*cθ * ψ_dot r = -sϕ * θ_dot + cϕ*cθ * ψ_dot return [p, q, r] end """ pqr_2_quat_dot(p, q, r, q0, q1, q2, q3) Transform body angular velocity (p, q, r) [rad/s] to quaternion rates [1/s]. # See also [`pqr_2_ψθϕ_dot`](@ref) # References 1. Stevens, B. L., Lewis, F. L., & Johnson, E. N. (2015). Aircraft control and simulation: dynamics, controls design, and autonomous systems. John Wiley & Sons. Equation (1.8-15) (page 51). """ function pqr_2_quat_dot(p, q, r, q0, q1, q2, q3) Ω = [ 0 -p -q -r; p 0 r -q; q -r 0 p; r q -p 0; ] q = [q0; q1; q2; q3] q_dot = 0.5 * Ω * q return q_dot end """ uvw_to_tasαβ(u, v, w) Calculate true air speed (TAS), angle of attack (α) and angle of side slip (β) from velocity expressed in body axis. # Notes This function assumes that u, v, w are the body components of the aerodynamic speed. This is not true in genreal (wind speed different from zero), as u, v, w represent velocity with respect to an inertial reference frame. # References 1. Stevens, B. L., Lewis, F. L., & Johnson, E. N. (2015). Aircraft control and simulation: dynamics, controls design, and autonomous systems. John Wiley & Sons. Equation (2.3-6b) (page 78). """ function uvw_to_tasαβ(u, v, w) tas = sqrt(u*u + v*v + w*w) α = atan(w, u) β = asin(v / tas) return [tas, α, β] end """ uvw_dot_to_tasαβ_dot(u, v, w, u_dot, v_dot, w_dot) Calculate time derivatives of velocity expressed as TAS, AOA, AOS. # Notes Note that tas here is not necessarily true air speed. Could also be inertial speed in the direction of airspeed. It will concide whith TAS for no wind. # See also [`tasαβ_dot_to_uvw_dot`](@ref) # References 1. Morelli, Eugene A., and Vladislav Klein. Aircraft system identification: Theory and practice. Williamsburg, VA: Sunflyte Enterprises, 2016. Equation 3.33 (page 44). 2. Stevens, B. L., Lewis, F. L., & Johnson, E. N. (2015). Aircraft control and simulation: dynamics, controls design, and autonomous systems. John Wiley & Sons. Equation (2.3-10) (page 81). """ function uvw_dot_to_tasαβ_dot(u, v, w, u_dot, v_dot, w_dot) # [1] 3.31 tas = sqrt(u*u + v*v + w*w) # [1] 3.33a tas_dot = (u * u_dot + v * v_dot + w * w_dot) / tas # [1] 3.33b β_dot = ((u*u + w*w) * v_dot - v * (u * u_dot + w * w_dot)) / (tas^2 * sqrt(u*u + w*w)) # [2] 2.3.10b # β_dot = (v_dot * tas - v * tas_dot) / (tas * sqrt(u*u + w*w)) # [1] 3.33c α_dot = (w_dot * u - w * u_dot) / (u*u + w*w) return [tas_dot, α_dot, β_dot] end """ tasαβ_dot_to_uvw_dot(tas, α, β, tas_dot, α_dot, β_dot) Obatain body velocity derivatives given velocity in wind axis and its derivatives. # See also [`uvw_dot_to_tasαβ_dot`](@ref) # References 1. Morelli, Eugene A., and Vladislav Klein. Aircraft system identification: Theory and practice. Williamsburg, VA: Sunflyte Enterprises, 2016. Derived from equation 3.32 (page 44). """ function tasαβ_dot_to_uvw_dot(tas, α, β, tas_dot, α_dot, β_dot) u_dot = tas_dot * cos(α) * cos(β) - tas * (α_dot * sin(α) * cos(β) + β_dot * cos(α) * sin(β)) v_dot = tas_dot * sin(β) + tas * β_dot * cos(β) w_dot = tas_dot * sin(α) * cos(β) + tas * (α_dot * cos(α) * cos(β) - β_dot * sin(α) * sin(β)) return [u_dot, v_dot, w_dot] end @doc raw""" rate_of_climb_constrain_no_wind(γ, α, β, ϕ) Calculate pitch angle (θ rad) to obtain a flight path angle (γ rad) at certain angle of attack (α rad), angle of sideslip (β rad) and roll (ϕ rad). Inertial velocity and aerodynamic velocity are equivalent in the absence of wind: `` v_{cg-e}^e = R_{eb} R_{bw} v_{cg-air}^w `` # References 1. Stevens, B. L., Lewis, F. L., (1992). Aircraft control and simulation: dynamics, controls design, and autonomous systems. John Wiley & Sons. (Section 3.6, equation 3.6-3, page 187) """ function rate_of_climb_constrain_no_wind(γ, α, β, ϕ) a = cos(α) * cos(β) b = sin(ϕ) * sin(β) + cos(ϕ) * sin(α) * cos(β) sq = sqrt(a^2 - sin(γ)^2 + b^2) θ = (a * b + sin(γ) * sq) / (a^2 - sin(γ)^2) θ = atan(θ) return θ end
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
1840
@doc raw""" translate_forces_moments(forces_1, moments_1, p1, p2) Calculate equivalent moment at point 2 (p2) given the forces (forces_1) and moments (moments_1) at point 1 (p1). `` r = p_1 - p_2 `` ``M_{2} = M_{1} + r \times F_{1}`` """ function translate_forces_moments(forces_1, moments_1, p1, p2) r21 = p1 - p2 moments_2 = moments_1 + r21 × forces_1 return moments_2 end @doc raw""" steiner_inertia(cg, inertia_g, mass, p2) Calculate the inertia tensor of a rigid solid at point 2 (p2), given the inertia tensor (inertia_g) at the center of gravity (cg) and the mass of the system. `` r = p_2 - cg `` ``I_{2} = I_{cg} + m (r^T · r I - r · r^T) `` """ function steiner_inertia(cg, inertia1, mass, p2) r = p2 - cg inertia2 = inertia1 + mass * ((r' * r) * I - r*r') return inertia2 end """ coordinated_turn_bank(ψ_dot, α, β, tas, γ[, g]) Calculate roll angle (ϕ) [rad] for a given turn rate, angle of attack, angle of sideslip, tas and flight path angle in the absence of wind for a coordinated turn bank. Imposes sum of forces along y body axis equal to zero. # Arguments - `ψ_dot`: turn rate (rad/s). - `α`: angle of attack (rad). - `β`: angle of sideslip (rad). - `tas`: true air speed (m/s). - `γ`: flight path angle (rad). - `g`: gravity (m/s²). Optional. Default value is `gD`. """ function coordinated_turn_bank(ψ_dot, α, β, tas, γ, g=gD) G = ψ_dot * tas / g if abs(γ) < 1e-8 ϕ = G * cos(β) / (cos(α) - G * sin(α) * sin(β)) ϕ = atan(ϕ) else a = 1 - G * tan(α) * sin(β) b = sin(γ) / cos(β) c = 1 + G^2 * cos(β)^2 sq = sqrt(c * (1 - b^2) + G^2 * sin(β)^2) num = (a - b^2) + b * tan(α) * sq den = a ^ 2 - b^2 * (1 + c * tan(α)^2) ϕ = atan(G * cos(β) / cos(α) * num / den) end return ϕ end
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
5236
""" rotation_matrix_zyx(α1, α2, α3) Calculate the rotation matrix ``R_{ab}`` that transforms a vector in b frame to a frame (``v_{a} = R_{ab} v_{b}``) given the rotations (α1, α2, α3) (rad). Frame b is obtained from frame a performing three intrinsic rotations of magnitude α1, α2 and α3 in ZYX order. """ function rotation_matrix_zyx(α1, α2, α3) sα1, cα1 = sin(α1), cos(α1) sα2, cα2 = sin(α2), cos(α2) sα3, cα3 = sin(α3), cos(α3) R = @SMatrix [ cα2 * cα1 (sα3 * sα2 * cα1 - cα3 * sα1) (cα3 * sα2 * cα1 + sα3 * sα1) cα2 * sα1 (sα3 * sα2 * sα1 + cα3 * cα1) (cα3 * sα2 * sα1 - sα3 * cα1) -sα2 sα3 * cα2 cα3 * cα2 ] return R end """ rotation_matrix_zyx(q0, q1, q2, q3) Calculate the rotation matrix ``R_{ab}`` that transforms a vector in b frame to a frame (``v_{a} = R_{ab} v_{b}``) given the quaternions ``q_0, q_1, q_2, q_3``. """ function rotation_matrix_zyx(q0, q1, q2, q3) q02, q12, q22, q32 = q0*q0, q1*q1, q2*q2, q3*q3 R = @SMatrix [ (q02+q12-q22-q32) 2*(q1*q2 - q0*q3) 2*(q1*q3 + q0*q2) 2*(q1*q2 + q0*q3) (q02-q12+q22-q32) 2*(q2*q3 - q0*q1) 2*(q1*q3 - q0*q2) 2*(q2*q3 + q0*q1) (q02-q12-q22+q32) ] return R end """ quaternions(ψ, θ, ϕ) Calculate quaternion representation given the Euler angles (ψ, θ, ϕ) (rad). """ function quaternions(ψ, θ, ϕ) s_ψ2, c_ψ2 = sin(ψ/2), cos(ψ/2) s_θ2, c_θ2 = sin(θ/2), cos(θ/2) s_ϕ2, c_ϕ2 = sin(ϕ/2), cos(ϕ/2) q0 = c_ψ2*c_θ2*c_ϕ2 + s_ψ2*s_θ2*s_ϕ2 q1 = c_ψ2*c_θ2*s_ϕ2 - s_ψ2*s_θ2*c_ϕ2 q2 = c_ψ2*s_θ2*c_ϕ2 + s_ψ2*c_θ2*s_ϕ2 q3 = s_ψ2*c_θ2*c_ϕ2 - c_ψ2*s_θ2*s_ϕ2 return @SVector [q0, q1, q2, q3] end """ euler_angles(q0, q1, q2, q3) Calculate Euler angles (ψ, θ, ϕ) (rad) given the quaternions ``q_0, q_1, q_2, q_3``. """ function euler_angles(q0, q1, q2, q3) ψ = atan(2 * (q1*q2 + q0*q3), q0*q0 + q1*q1 - q2*q2 - q3*q3) θ = asin(-2 * (q1*q3 - q0*q2)) ϕ = atan(2 * (q2*q3 + q0*q1), q0*q0 - q1*q1 - q2*q2 + q3*q3) return @SVector [mod2pi(ψ), θ, ϕ] end """ body2horizon(x, y, z, ψ, θ, ϕ) Transform the vector coordintes (x, y, z) given in body axis to local horizon given the Euler angles (ψ, θ, ϕ) (rad). """ function body2horizon(x, y, z, ψ, θ, ϕ) v = @SVector [x, y, z] rv = rotation_matrix_zyx(ψ, θ, ϕ) * v return rv end """ horizon2body(x, y, z, ψ, θ, ϕ) Transform the vector coordintes (x, y, z) given in local horizon axis to body given the Euler angles (ψ, θ, ϕ) (rad). """ function horizon2body(x, y, z, ψ, θ, ϕ) v = @SVector [x, y, z] rv = transpose(rotation_matrix_zyx(ψ, θ, ϕ)) * v return rv end """ body2horizon(x, y, z, q0, q1, q2, q3) Transform the vector coordintes (x, y, z) given in body axis to local horizon given the quaternions ``q_0, q_1, q_2, q_3``. """ function body2horizon(x, y, z, q0, q1, q2, q3) v = @SVector [x, y, z] rv = rotation_matrix_zyx(q0, q1, q2, q3) * v return rv end """ horizon2body(x, y, z, q0, q1, q2, q3) Transform the vector coordintes (x, y, z) given in local horizon axis to body given the quaternions ``q_0, q_1, q_2, q_3``. """ function horizon2body(x, y, z, q0, q1, q2, q3) v = @SVector [x, y, z] rv = transpose(rotation_matrix_zyx(q0, q1, q2, q3)) * v return rv end """ wind2body(x, y, z, α, β) Transform the vector coordintes (x, y, z) given in wind axis to body given the angle of attack (α) and the angle of sideslip (β) (rad). """ function wind2body(x, y, z, α, β) v = @SVector [x, y, z] rv = transpose(rotation_matrix_zyx(-β, α, 0)) * v return rv end """ body2wind(x, y, z, α, β) Transform the vector coordintes (x, y, z) given in body axis to wind given the angle of attack (α) and the angle of sideslip (β) (rad). """ function body2wind(x, y, z, α, β) v = @SVector [x, y, z] rv = rotation_matrix_zyx(-β, α, 0) * v return rv end """ wind2horizon(x, y, z, χ, γ, μ) Transform the vector coordintes (x, y, z) given in wind axis to local horizon given the velocity angles (χ, γ, μ) (rad). """ function wind2horizon(x, y, z, χ, γ, μ) v = @SVector [x, y, z] rv = rotation_matrix_zyx(χ, γ, μ) * v return rv end """ horizon2wind(x, y, z, χ, γ, μ) Transform the vector coordintes (x, y, z) given in local horizon axis to wind given the velocity angles (χ, γ, μ) (rad). """ function horizon2wind(x, y, z, χ, γ, μ) v = @SVector [x, y, z] rv = transpose(rotation_matrix_zyx(χ, γ, μ)) * v return rv end """ ecef2horizon(x, y, z, lat, lon) Transform the vector coordintes (x, y, z) given in ECEF (Earth Fixed Earth Centered) coordinates to local horizon coordinates using geodetic latitude and longitude (rad). """ function ecef2horizon(x, y, z, lat, lon) v = @SVector [x, y, z] rv = transpose(rotation_matrix_zyx(lon, -lat - π/2, 0)) * v end """ horizon2ecef(x, y, z, lat, lon) Transform the vector coordintes (x, y, z) given in local horizon axis to ECEF (Earth Fixed Earth Centered) using geodetic latitude and longitude (rad). """ function horizon2ecef(x, y, z, lat, lon) v = @SVector [x, y, z] rv = rotation_matrix_zyx(lon, -lat - π/2, 0) * v end
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
3220
using Test using FlightMechanicsUtils const KT2MS = 0.514444 # knots (kt) to meters/second (m/s) # TESTS for TAS CAS EAS based on values from # http://www.hochwarth.com/misc/AviationCalculator.html # --- height = 0 m --- h = 0.0 # m T, p, rho, a = atmosphere_isa(h) # From TAS tas = 100.0 * KT2MS # m/s expected_eas = 100.0 * KT2MS # m/s expected_cas = 100.0 * KT2MS # m/s eas = tas2eas(tas, rho) cas = tas2cas(tas, rho, p) @test isapprox(eas, expected_eas) @test isapprox(cas, expected_cas) # From CAS cas = 100.0 * KT2MS # m/s expected_eas = 100.0 * KT2MS # m/s expected_tas = 100.0 * KT2MS # m/s eas = cas2eas(cas, rho, p) tas = cas2tas(cas, rho, p) @test isapprox(eas, expected_eas) @test isapprox(tas, expected_tas) # From EAS eas = 100.0 * KT2MS # m/s expected_cas = 100.0 * KT2MS # m/s expected_tas = 100.0 * KT2MS # m/s cas = eas2cas(eas, rho, p) tas = eas2tas(eas, rho) @test isapprox(cas, expected_cas) @test isapprox(tas, expected_tas) # --- height = 5000 m --- h = 5000.0 # m T, p, rho, a = atmosphere_isa(h) # From TAS tas = 200.0 * KT2MS # m/s expected_eas = 155.03684 * KT2MS # m/s expected_cas = 155.95551 * KT2MS # m/s eas = tas2eas(tas, rho) cas = tas2cas(tas, rho, p) @test isapprox(eas, expected_eas, atol=1e-4) @test isapprox(cas, expected_cas, atol=1e-4) # From CAS cas = 200.0 * KT2MS # m/s expected_eas = 198.101308 * KT2MS # m/s expected_tas = 255.553851 * KT2MS # m/s eas = cas2eas(cas, rho, p) tas = cas2tas(cas, rho, p) @test isapprox(eas, expected_eas, atol=1e-4) @test isapprox(tas, expected_tas, atol=1e-4) # From EAS eas = 200.0 * KT2MS # m/s expected_cas = 201.95290 * KT2MS # m/s expected_tas = 258.00319 * KT2MS # m/s cas = eas2cas(eas, rho, p) tas = eas2tas(eas, rho) @test isapprox(cas, expected_cas, atol=1e-4) @test isapprox(tas, expected_tas, atol=1e-4) # --- Velocities from qc --- # Values from http://www.aerospaceweb.org/design/scripts/atmosphere/ # geometric altitude = 8010.0807 # m --> geopotential = 8000.0 # m # velocity = 100 # m/s h = 8000.0 # m T, p, rho, a = atmosphere_isa(h) tas = 100 # m/s qinf = 38295.5172 # Pa (Total Head) qc = qinf - p exp_cas = 66.0304 # m/s exp_tas = 100 # m/s exp_eas = 65.4758 # m/s eas = qc2eas(qc, p) tas_ = qc2tas(qc, rho, p) cas = qc2cas(qc) @test isapprox(cas, exp_cas, atol=1e-3) @test isapprox(eas, exp_eas, atol=1e-3) @test isapprox(tas_, exp_tas, atol=1e-3) # --- Dynamic pressure --- # Values from http://www.aerospaceweb.org/design/scripts/atmosphere/ # geometric altitude = 8010.0807 # m --> geopotential = 8000.0 # m # velocity = 100 # m/s h = 8000.0 # m T, p, rho, a = atmosphere_isa(h) tas = 100 # m/s exp_qinf_inc = 2625.8356 # Pa (True Dynamic Pressure) qinf_inc = incompressible_qinf(tas, rho) @test isapprox(qinf_inc, exp_qinf_inc, atol=0.0001) M = tas / a exp_qinf_comp = 38295.5172 # Pa (Total Head) qinf_comp = compressible_qinf(M, p) @test isapprox(qinf_comp, exp_qinf_comp, atol=0.01) M = [0.6, 1.3, 3.0] # Ref=> Aerodynamics, Anderson, page 550 p = 1 exp_qinf_comp = [1.276, 2.714, 12.06] qinf_comp = [] for i = 1:length(exp_qinf_comp) push!(qinf_comp, compressible_qinf(M[i], p)) end @test isapprox(qinf_comp, exp_qinf_comp, atol=0.01)
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
3443
using FlightMechanicsUtils using Test @testset "ISA1978" begin # Test sea level T, p, rho, a = atmosphere_isa(0.0) @test isapprox(T, 288.15) @test isapprox(p, 101325) @test isapprox(rho, 1.225) @test isapprox(a, 340.29398, rtol=1e-7) # Test 0-11 Km h = [0.0, 50.0, 550.0, 6500.0, 10000.0, 11000.0] # TODO: have a look again at unzip options # I would expect a tuple of Arrays, however an Array of tuples is returned. # https://discourse.julialang.org/t/broadcast-map-return-type-for-a-function-returning-a-tuple/574/6 rv = atmosphere_isa.(h) rv_arr = reduce(hcat, rv) T = rv_arr[1, :] p = rv_arr[2, :] rho = rv_arr[3, :] a = rv_arr[4, :] @test isapprox(T, [288.150, 287.825, 284.575, 245.900, 223.150, 216.650]) @test isapprox(rho, [1.2250, 1.2191, 1.1616, 0.62384, 0.41271, 0.36392], rtol=1e-4) @test isapprox(a, [340.29, 340.10, 338.18, 314.36, 299.46, 295.07], rtol=1e-5) # Test 11-20 Km h = [12000, 14200, 17500, 20000, ] # m rv = atmosphere_isa.(h) rv_arr = reduce(hcat, rv) T = rv_arr[1, :] p = rv_arr[2, :] rho = rv_arr[3, :] a = rv_arr[4, :] @test isapprox(T, [216.650, 216.650, 216.650, 216.650]) @test isapprox(rho, [0.31083, 0.21971, 0.13058, 0.088035], rtol=1e-4) @test isapprox(a, [295.07, 295.07, 295.07, 295.07], rtol=1e-5) # Test 20-32 Km h = [22100, 24000, 28800, 32000] # m rv = atmosphere_isa.(h) rv_arr = reduce(hcat, rv) T = rv_arr[1, :] p = rv_arr[2, :] rho = rv_arr[3, :] a = rv_arr[4, :] @test isapprox(T, [218.750, 220.650, 225.450, 228.650]) @test isapprox(rho, [0.062711, 0.046267, 0.021708, 0.013225], rtol=1e-4) @test isapprox(a, [296.50, 297.78, 301.00, 303.13], rtol=1e-5) # Test 32-47 Km h = [32200, 36000, 42000, 47000] # m rv = atmosphere_isa.(h) rv_arr = reduce(hcat, rv) T = rv_arr[1, :] p = rv_arr[2, :] rho = rv_arr[3, :] a = rv_arr[4, :] @test isapprox(T, [229.210, 239.850, 256.650, 270.650]) @test isapprox(rho, [0.012805, 0.0070344, 0.0028780, 0.0014275], rtol=1e-4) @test isapprox(a, [303.50, 310.47, 321.16, 329.80], rtol=1e-5) # Test 47-51 Km h = [47200, 49000, 51000] # m rv = atmosphere_isa.(h) rv_arr = reduce(hcat, rv) T = rv_arr[1, :] p = rv_arr[2, :] rho = rv_arr[3, :] a = rv_arr[4, :] @test isapprox(T, [270.650, 270.650, 270.650]) @test isapprox(rho, [0.0013919, 0.0011090, 0.00086160], rtol=1e-4) @test isapprox(a, [329.80, 329.80, 329.80], rtol=1e-5) # Test 51-71 Km h = [51500, 60000, 71000] # m rv = atmosphere_isa.(h) rv_arr = reduce(hcat, rv) T = rv_arr[1, :] p = rv_arr[2, :] rho = rv_arr[3, :] a = rv_arr[4, :] @test isapprox(T, [269.250, 245.450, 214.650]) @test isapprox(rho, [0.00081298, 2.8832e-4, 6.4211e-5], rtol=1e-4) @test isapprox(a, [328.94, 314.07, 293.70], rtol=1e-4) # Test 71-84 Km h = [52000, 60000, 84500] # m rv = atmosphere_isa.(h) rv_arr = reduce(hcat, rv) T = rv_arr[1, :] p = rv_arr[2, :] rho = rv_arr[3, :] a = rv_arr[4, :] @test isapprox(T, [267.850, 245.450, 187.650]) @test isapprox(rho, [7.6687e-4, 2.8832e-4, 7.3914e-6], rtol=1e-4) @test isapprox(a, [328.09, 314.07, 274.61], rtol=1e-5) @test_throws DomainError atmosphere_isa(84500.1) @test_throws DomainError atmosphere_isa(-0.1) end
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
2668
using FlightMechanicsUtils using Test @testset "Ellipsoid WGS84" begin # Rogers, R. M. (2007). Applied mathematics in integrated navigation systems. # American Institute of Aeronautics and Astronautics. (Page 77, table 4.2) @test isapprox(WGS84.a, 6378137) @test isapprox(WGS84.b, 6356752.3142) @test isapprox(WGS84.finv, 298.257223563) @test isapprox(WGS84.e2, 0.0818191908426^2) end @testset "llh <-> ECEF" begin # llh ECEF (using data from # - [1] Bowring, B. R. (1976). Transformation from spatial to geographical # coordinates. Survey review, 23(181), 323-327.) # From [1] Example 1 (page 325) x = 4114496.258 # m y = 0.0 # m z = 4870157.031 # m # Ellipsoid does not match any known standard a_bowring1976 = 6378249.145 # m b_bowring1976 = 6356514.870 # m finv_bowring1976 = a_bowring1976 / (a_bowring1976 - b_bowring1976) Bowring1976 = Ellipsoid(a_bowring1976, finv_bowring1976, "Bowring 1976") exp_llh = [deg2rad(50.0), 0, 10000.0] llh = ecef2llh(x, y, z; ellipsoid=Bowring1976) @test isapprox(llh, exp_llh) exp_xyz = [4114496.258, 0.0, 4870157.031] # m xyz = llh2ecef(deg2rad(50.0), 0, 10000.0; ellipsoid=Bowring1976) @test isapprox(xyz, exp_xyz) # http://www.sysense.com/products/ecef_lla_converter/index.html x, y, z = (4114496.258, 0.0, 4870157.031) # m exp_llh = [deg2rad(49.996908), 0.000000, 9907.31] llh = ecef2llh(x, y, z) # Longitude should be exact, latitude max error: 0.0018" according to [1] # Altitude 0.17 m # The implemented function must be better, but I don't know which one is using # this web page. The ellipsoid is assumed to be WGS84 @test isapprox(llh[:2], exp_llh[:2], atol=deg2rad(0.0018/3600.0)) @test isapprox(llh[3], exp_llh[3], atol=0.17) exp_xyz = [4114291.97, 0.00, 4870449.48] # m xyz = llh2ecef(deg2rad(50.0), 0, 10000.0) @test isapprox(xyz, exp_xyz) # non-zero longitude x, y, z = (3814496.258, 1514496.258, 4870157.031) # m exp_llh = [deg2rad(50.068095), deg2rad(21.654910), 3263.97] llh = ecef2llh(x, y, z) # Longitude should be exact, latitude max error: 0.0018" according to [1] # Altitude 0.17 m # The implemented function must be better, but I don't know which one is using # this web page. The ellipsoid is assumed to be WGS84 @test isapprox(llh[:2], exp_llh[:2], atol=deg2rad(0.0018/3600.0)) @test isapprox(llh[3], exp_llh[3], atol=0.17) exp_xyz = [3814496.258, 1514496.258, 4870157.031] # m xyz = llh2ecef(deg2rad(50.068095), deg2rad(21.654910), 3263.97) @test isapprox(xyz, exp_xyz) end
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
3816
using FlightMechanicsUtils using Test @testset "Rigid body vel and accel fields" begin # TEST rigid_body_velocity # Test without angular velocity vel_P = [10.0, 0.0, 0.0] ω = [0.0, 0.0, 0.0] r_PQ = [5.0, 5.0, 5.0] exp_vel_Q = [10.0, 0.0, 0.0] vel_Q = rigid_body_velocity(vel_P, ω, r_PQ) @test isapprox(vel_Q, exp_vel_Q) # Only angular velocity in Z axis vel_P = [0.0, 0.0, 0.0] ω = [0.0, 0.0, 1.0] r_PQ = [5.0, 5.0, 5.0] exp_vel_Q = [-sqrt(50) * sin(pi/4), sqrt(50) * cos(pi/4), 0.0] vel_Q = rigid_body_velocity(vel_P, ω, r_PQ) @test isapprox(vel_Q, exp_vel_Q) # X linear velocity and Z angular velocity vel_P = [10.0, 0.0, 0.0] ω = [0.0, 0.0, 1.0] r_PQ = [5.0, 5.0, 5.0] exp_vel_Q = [-sqrt(50) * sin(pi/4) + 10.0, sqrt(50) * cos(pi/4), 0.0] vel_Q = rigid_body_velocity(vel_P, ω, r_PQ) @test isapprox(vel_Q, exp_vel_Q) # TEST rigid_body_acceleration # Only X linear acceleration acc_P = [10.0, 0.0, 0.0] ω = [0.0, 0.0, 0.0] ω_dot = [0.0, 0.0, 0.0] r_PQ = [5.0, 5.0, 5.0] exp_accel_Q = [10.0, 0.0, 0.0] accel_Q = rigid_body_acceleration(acc_P, ω, ω_dot, r_PQ) @test isapprox(accel_Q, exp_accel_Q) # Only Z angular acceleration acc_P = [0.0, 0.0, 0.0] ω = [0.0, 0.0, 0.0] ω_dot = [0.0, 0.0, 1.0] r_PQ = [5.0, 5.0, 5.0] exp_accel_Q = [-sqrt(50) * sin(pi/4), sqrt(50) * cos(pi/4), 0.0] accel_Q = rigid_body_acceleration(acc_P, ω, ω_dot, r_PQ) @test isapprox(accel_Q, exp_accel_Q) # Only Z angular velocity acc_P = [0.0, 0.0, 0.0] ω = [0.0, 0.0, 2.0] ω_dot = [0.0, 0.0, 0.0] r_PQ = [5.0, 5.0, 5.0] exp_accel_Q = [-4.0 * sqrt(50) * sin(pi/4), -4.0 * sqrt(50) * cos(pi/4), 0.0] accel_Q = rigid_body_acceleration(acc_P, ω, ω_dot, r_PQ) @test isapprox(accel_Q, exp_accel_Q) end @testset "Angular kinematic equations" begin # Null Euler angles pqr = [0.5, 0.3, 0.7] euler_angles_rates = pqr_2_ψθϕ_dot(pqr..., 0, 0) @test isapprox(euler_angles_rates, pqr[end:-1:1]) ψθϕ_dot = [0.5, 0.3, 0.7] pqr_ = ψθϕ_dot_2_pqr(ψθϕ_dot..., 0, 0) @test isapprox(pqr_, ψθϕ_dot[end:-1:1]) # Reciprocal relationships θ = 0.15 # rad ϕ = 0.6 # rad pqr = [0.5, 0.3, 0.7] euler_angles_rates = pqr_2_ψθϕ_dot(pqr..., θ, ϕ) pqr_ = ψθϕ_dot_2_pqr(euler_angles_rates..., θ, ϕ) @test isapprox(pqr, pqr_) # TODO: test body_angular_velocity_to_quaternion_rates end @testset "Aero <--> Body velocity" begin uvw = [30, 3, 5] tas, α, β = uvw_to_tasαβ(30, 3, 5) u, v, w = wind2body(tas, 0, 0, α, β) @test isapprox([u, v, w], uvw) uvw = [100, 0, 0] # m/s rv = uvw_to_tasαβ(uvw...) @test isapprox(rv, [100, 0, 0]) uvw = 10, 0, 10 # m/s rv = uvw_to_tasαβ(uvw...) @test isapprox(rv, [sqrt(200), atan(1), 0]) uvw = [10, 10, 0] # m/s rv = uvw_to_tasαβ(uvw...) @test isapprox(rv, [sqrt(200), 0, asin(10/sqrt(200))]) uvw_dot = [5, 1, 10] tasαβ_dot = uvw_dot_to_tasαβ_dot(uvw..., uvw_dot...) uvw_dot_ = tasαβ_dot_to_uvw_dot(uvw_to_tasαβ(uvw...)..., tasαβ_dot...) @test isapprox(uvw_dot_, uvw_dot) end @testset "Rate of climb constrain" begin # wings-level, no sideslip: θ = α + γ θ = rate_of_climb_constrain_no_wind(0.1, 0.05, 0, 0) @test isapprox(θ, 0.1 + 0.05) # Check case: Stevens, B. L., Lewis, F. L., (1992). # Aircraft control and simulation: dynamics, controls design, and autonomous systems. # John Wiley & Sons. (Section 3.6, figure 3.6-2, page 192) θ =rate_of_climb_constrain_no_wind(0.0, deg2rad(13.7), deg2rad(0.0292), deg2rad(78.3)) # Take into account that this check case is a full trim not just the kinematic realtionship @test isapprox(rad2deg(θ), 2.87, rtol=0.01) end
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
2782
using FlightMechanicsUtils using Test @testset "Translate forces and moments" begin # No traslation m2 = translate_forces_moments([10, 20, 30], [50, 60, 90], [1, 1, 1], [1, 1, 1]) @test isapprox(m2, [50, 60, 90]) # Simple translation 1 m2 = translate_forces_moments([1, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 1]) @test isapprox(m2, [0, -1, 0]) # Simple translation 2 m2 = translate_forces_moments([1, 0, 0], [1, 0, 0], [0, 0, 0], [0, 0, 1]) @test isapprox(m2, [1, -1, 0]) # Simple translation 3 m2 = translate_forces_moments( [10, 20, 30], [50, 60, 90], [1, 1, 1], [1, 1, 1] + [0, 1, 0], ) @test isapprox(m2, [50, 60, 90] + [-30, 0, 10]) # Reciprocal m2 = translate_forces_moments([10, 20, 30], [50, 60, 90], [1, 1, 1], [10, 20, 30]) m1_ = translate_forces_moments([10, 20, 30], m2, [10, 20, 30], [1, 1, 1]) @test isapprox([50, 60, 90], m1_) end @testset "Steiner" begin # No point translation p1 = [0, 0, 0] p2 = p1 inertia = [ 1 0 0 0 2 0 0 0 3 ] mass = 10 @test isapprox(steiner_inertia(p1, inertia, mass, p2), inertia) # Point with no inertia p1 = [0, 0, 0] p2 = [10, 0, 0] inertia = zeros(3, 3) p2 = [10, 0, 0] inertia = zeros(3, 3) mass = 10 exp_inertia = [ 0 0 0 0 1000 0 0 0 1000 ] @test isapprox(steiner_inertia(p1, inertia, mass, p2), exp_inertia) # Point with with inertia p1 = [0, 0, 0] p2 = [10, 0, 0] inertia = [ 1 0 0 0 2 0 0 0 3 ] mass = 10 exp_inertia = [ 0 0 0 0 1000 0 0 0 1000 ] + inertia @test isapprox(steiner_inertia(p1, inertia, mass, p2), exp_inertia) end @testset "Coordinated turn bank angle constrain" begin # Check case: Stevens, B. L., Lewis, F. L., (1992). # Aircraft control and simulation: dynamics, controls design, and autonomous systems. # John Wiley & Sons. (Section 3.6, figure 3.6-2, page 192) ϕ = coordinated_turn_bank(0.3, deg2rad(13.7), deg2rad(0.0292), 502*0.3048, 0.0) # Take into account that this check case is a full trim not just the kinematic realtionship @test isapprox(rad2deg(ϕ), 78.3, atol=0.05) # Opposite turn ϕ = coordinated_turn_bank(-0.3, deg2rad(13.7), deg2rad(0.0292), 502*0.3048, 0.0) @test isapprox(rad2deg(ϕ), -78.3, atol=0.05) # Null turn rate ϕ = coordinated_turn_bank(0, deg2rad(13.7), deg2rad(0.0292), 502*0.3048, 0.0) @test isapprox(rad2deg(ϕ), 0) # For regression testing (no check values found in Stevens) ϕ = coordinated_turn_bank(0.1, deg2rad(13.7), deg2rad(0.0292), 502*0.3048, 10) @test isapprox(rad2deg(ϕ), 51.16941949883969) end
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
6859
using FlightMechanicsUtils using LinearAlgebra using Test @testset "quaternion <-> euler" begin quat = [0.8660254037844387, 0.0, 0.5, 0.0] euler_exp = [0.0, 1.04719755, 0.0] euler = euler_angles(quat...) @test isapprox(euler, euler_exp) quat_exp = [quat...] quat = quaternions(euler_exp...) @test isapprox(quat, quat_exp) quat = [0.5, 0.5, 0.0, 0.0] euler_exp = [0.0, 0.0, pi/2.0] euler = euler_angles(quat...) @test isapprox(euler, euler_exp) quat_exp = [quat...] quat = quaternions(euler_exp...) @test isapprox(quat, quat_exp / norm(quat_exp)) psi, theta, phi = pi/4.0, pi/6.0, pi/12.0 quat = quaternions(psi, theta, phi) euler = euler_angles(quat...) @test isapprox([psi, theta, phi], euler) quat = [0.5, 0.1, 0.2, 0.7] quat = quat / norm(quat) euler = euler_angles(quat...) quat3 = quaternions(euler...) @test isapprox(quat, quat3) end @testset "body <-> horizon" begin ones_ = [1.0, 1.0, 1.0] # body2horizon Euler # no rotation @test ones_ ≈ body2horizon(ones_..., 0., 0., 0.) angles1 = [0., 45*pi/180., 0.] angles2 = [0., 0., 45*pi/180] angles3 = [45*pi/180, 0., 0.] exp_b2h_1 = [2*0.70710678118654757, 1, 0] exp_b2h_2 = [1, 0, 2*0.70710678118654757] exp_b2h_3 = [0, 2*0.70710678118654757, 1] @test exp_b2h_1 ≈ body2horizon(ones_..., angles1...) @test exp_b2h_2 ≈ body2horizon(ones_..., angles2...) @test exp_b2h_3 ≈ body2horizon(ones_..., angles3...) # horizon2body Euler @test ones_ ≈ horizon2body(ones_..., 0., 0., 0.) @test ones_ ≈ horizon2body(exp_b2h_1..., angles1...) @test ones_ ≈ horizon2body(exp_b2h_2..., angles2...) @test ones_ ≈ horizon2body(exp_b2h_3..., angles3...) # body2horizon quaternion @test ones_ ≈ body2horizon(ones_..., 0., 0., 0.) quat1 = quaternions(angles1...) quat2 = quaternions(angles2...) quat3 = quaternions(angles3...) @test exp_b2h_1 ≈ body2horizon(ones_..., quat1...) @test exp_b2h_2 ≈ body2horizon(ones_..., quat2...) @test exp_b2h_3 ≈ body2horizon(ones_..., quat3...) # horizon2body quaternionr @test ones_ ≈ horizon2body(ones_..., 0., 0., 0.) @test ones_ ≈ horizon2body(exp_b2h_1..., quat1...) @test ones_ ≈ horizon2body(exp_b2h_2..., quat2...) @test ones_ ≈ horizon2body(exp_b2h_3..., quat3...) # rotation matrix body to hor (euler) r_hb1 = rotation_matrix_zyx(angles1...) @test exp_b2h_1 ≈ r_hb1 * ones_ r_hb2 = rotation_matrix_zyx(angles2...) @test exp_b2h_2 ≈ r_hb2 * ones_ r_hb3 = rotation_matrix_zyx(angles3...) @test exp_b2h_3 ≈ r_hb3 * ones_ # rotation matrix body <-> hor (quaternion) r_hb1q = rotation_matrix_zyx(quat1...) @test exp_b2h_1 ≈ r_hb1q * ones_ r_hb2q = rotation_matrix_zyx(quat2...) @test exp_b2h_2 ≈ r_hb2q * ones_ r_hb3q = rotation_matrix_zyx(quat3...) @test exp_b2h_3 ≈ r_hb3q * ones_ # r_hb equivalent with euler and quaternion @test isapprox(r_hb1, r_hb1q) @test isapprox(r_hb2, r_hb2q) @test isapprox(r_hb3, r_hb3q) # rotation matrix hor to body (euler) r_bh1 = transpose(rotation_matrix_zyx(angles1...)) @test ones_ ≈ r_bh1 * exp_b2h_1 r_bh2 = transpose(rotation_matrix_zyx(angles2...)) @test ones_ ≈ r_bh2 * exp_b2h_2 r_bh3 = transpose(rotation_matrix_zyx(angles3...)) @test ones_ ≈ r_bh3 * exp_b2h_3 # rotation matrix horizon2body (quaternion) r_bh1q = transpose(rotation_matrix_zyx(quat1...)) @test ones_ ≈ r_bh1q * exp_b2h_1 r_bh2q = transpose(rotation_matrix_zyx(quat2...)) @test ones_ ≈ r_bh2q * exp_b2h_2 r_bh3q = transpose(rotation_matrix_zyx(quat3...)) @test ones_ ≈ r_bh3q * exp_b2h_3 # r_bh equivalent with euler and quaternion @test isapprox(r_bh1, r_bh1q) @test isapprox(r_bh2, r_bh2q) @test isapprox(r_bh3, r_bh3q) # Test that quaternion and euler produce the same transformation psi, theta, phi = pi/4.0, pi/6.0, pi/12.0 quat = quaternions(psi, theta, phi) xh, yh, zh = 100.0, 10.0, -1.0 xyz_b_e = horizon2body(xh, yh, zh, psi, theta, phi) xyz_b_q = horizon2body(xh, yh, zh, quat...) @test isapprox(xyz_b_e, xyz_b_q) xyz_h_e = body2horizon(xyz_b_e..., psi, theta, phi) xyz_h_q = body2horizon(xyz_b_e..., quat...) @test isapprox(xyz_h_e, xyz_h_q) end @testset "wind <-> hor/body" begin ones_ = [1.0, 1.0, 1.0] angles1 = [0., 45*pi/180., 0.] angles2 = [0., 0., 45*pi/180] angles3 = [45*pi/180, 0., 0.] exp_b2h_1 = [2*0.70710678118654757, 1, 0] exp_b2h_2 = [1, 0, 2*0.70710678118654757] exp_b2h_3 = [0, 2*0.70710678118654757, 1] #wind2horizon @test ones_ ≈ wind2horizon(ones_..., 0., 0., 0.) @test exp_b2h_1 ≈ wind2horizon(ones_..., angles1...) @test exp_b2h_2 ≈ wind2horizon(ones_..., angles2...) @test exp_b2h_3 ≈ wind2horizon(ones_..., angles3...) #horizon2wind @test ones_ ≈ horizon2wind(ones_..., 0., 0., 0.) @test ones_ ≈ horizon2wind(exp_b2h_1..., angles1...) @test ones_ ≈ horizon2wind(exp_b2h_2..., angles2...) @test ones_ ≈ horizon2wind(exp_b2h_3..., angles3...) #wind2body @test ones_ ≈ wind2body(ones_..., 0., 0.) @test [0, 1, 2*0.70710678118654757] ≈ wind2body(ones_..., 45*pi/180., 0.) @test exp_b2h_3 ≈ wind2body(ones_..., 0., 45*pi/180.) #body2wind @test ones_ ≈ body2wind(ones_..., 0., 0.) @test ones_ ≈ body2wind(0, 1, 2*0.70710678118654757, 45*pi/180., 0.) @test ones_ ≈ body2wind(exp_b2h_3..., 0., 45*pi/180.) end @testset "hor <-> ECEF" begin xecef, yecef, zecef = 1.0, 10.0, 100.0 lat, lon = 0.0, 0.0 exp_xyz_hor = [100.0, 10.0 ,-1.0] xyz_hor = ecef2horizon(xecef, yecef, zecef, lat, lon) @test isapprox(xyz_hor, exp_xyz_hor) exp_xyz_ecef = [xecef, yecef, zecef] xyz_ecef = horizon2ecef(exp_xyz_hor..., lat, lon) @test isapprox(xyz_ecef, exp_xyz_ecef) lat, lon = pi/2.0, 0.0 exp_xyz_hor = [-1.0, 10.0 ,-100.0] xyz_hor = ecef2horizon(xecef, yecef, zecef, lat, lon) @test isapprox(xyz_hor, exp_xyz_hor) exp_xyz_ecef = [xecef, yecef, zecef] xyz_ecef = horizon2ecef(exp_xyz_hor..., lat, lon) @test isapprox(xyz_ecef, exp_xyz_ecef) lat, lon = 0.0, pi/2.0 exp_xyz_hor = [100.0, -1.0 ,-10.0] xyz_hor = ecef2horizon(xecef, yecef, zecef, lat, lon) @test isapprox(xyz_hor, exp_xyz_hor) exp_xyz_ecef = [xecef, yecef, zecef] xyz_ecef = horizon2ecef(exp_xyz_hor..., lat, lon) @test isapprox(xyz_ecef, exp_xyz_ecef) lat, lon = pi/2.0, pi/2.0 exp_xyz_hor = [-10.0, -1.0 ,-100.0] xyz_hor = ecef2horizon(xecef, yecef, zecef, lat, lon) @test isapprox(xyz_hor, exp_xyz_hor) exp_xyz_ecef = [xecef, yecef, zecef] xyz_ecef = horizon2ecef(exp_xyz_hor..., lat, lon) @test isapprox(xyz_ecef, exp_xyz_ecef) end
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
code
380
using SafeTestsets @safetestset "Rotations" begin include("rotations.jl") end @safetestset "Ellipsoid" begin include("ellipsoid.jl") end @safetestset "Atmosphere" begin include("atmosphere.jl") end @safetestset "Kinematics" begin include("kinematics.jl") end @safetestset "Mechanics" begin include("mechanics.jl") end @safetestset "Anemometry" begin include("anemometry.jl") end
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
docs
1615
# FlightMechanicsUtils [![Build Status](https://github.com/AlexS12/FlightMechanicsUtils.jl/workflows/CI/badge.svg)](https://github.com/AlexS12/FlightMechanicsUtils.jl/actions) [![Documentation](https://img.shields.io/badge/docs-latest-brightgreen.svg?style=flat-square)](https://alexs12.github.io/FlightMechanicsUtils.jl/dev) [![License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](https://github.com/AlexS12/FlightMechanicsUtils.jl/blob/main/LICENSE) This is a suite for Flight Mechanics written in Julia. The purpose of this package is to supply efficient and validated Julia implementations of common Flight Mechanics calculations. At the moment, it covers: - International Standard Atmosphere. - Transformations between common coordinate systems in Flight Mechanics problems (body, horizon, wind, ECEF) supporting Euler angles and quaternions. - Kinematics & Dynamics: - Rigid solid velocity and acceleration fields. - Angular kinematic equations. - Steiner theorem:to determine the moment of inertia of a rigid body about any axis. - Trimmer constrains for leveled flight, climbs and turns. - Anemometric functions (tas, cas, eas, dynamic pressure). - ECEF (Earth Centered Earth Fixed) <---> LLH (Latitude Longitude Height) conversions. ## Install Last release: `pkg> add FlightMechanicsUtils` Dev version: `pkg> dev FlightMechanicsUtils` Run tests: `pkg> test FlightMechanicsUtils` ## Contributing If you are using or want to use this package and have any suggestion or found a bug, open an [issue](https://github.com/AlexS12/FlightMechanicsUtils.jl/issues).
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
docs
2109
# API ## Constants ### Air ```@docs γ_AIR R_AIR ``` ### Earth ```@docs gD ``` ## Ellipsoid Available ellipsoid models: | Name | a (m) | ``f^{-1}`` | | :--------------------: | :------------ | :--------------- | | `Clarke1866` | 6378206.4 | 294.9786982 | | `Clarke1880` | 6378249.145 | 294.465 | | `International` | 6378388.0 | 297.0 | | `Bessel` | 6377397.155 | 299.1528128 | | `Everest` | 6377276.345 | 300.8017 | | `ModifiedEverest` | 6377304.063 | 300.8017 | | `AustralianNational` | 6378160.0 | 298.25 | | `SouthAmerican1969` | 6378160.0 | 298.25 | | `Airy` | 6377564.396 | 299.3249646 | | `ModifiedAiry` | 6377340.189 | 299.3249646 | | `Hough` | 6378270.0 | 297.0 | | `Fischer1960SouthAsia` | 6378155.0 | 298.3 | | `Fischer1960Mercury` | 6378166.0 | 298.3 | | `Fischer1968` | 6378150.0 | 298.3 | | `WGS60` | 6378165.0 | 298.3 | | `WGS66` | 6378145.0 | 298.25 | | `WGS72` | 6378135.0 | 298.26 | | `WGS84` | 6378137.0 | 298.257223563 | ```@autodocs Modules = [FlightMechanicsUtils] Pages = ["ellipsoid.jl"] Private = false ``` ## Rotations ### Coordinate systems - Earth - Local horizon - Body - Wind ```@autodocs Modules = [FlightMechanicsUtils] Pages = ["rotations.jl"] Private = false ``` ## Atmosphere ```@autodocs Modules = [FlightMechanicsUtils] Pages = ["atmosphere.jl"] Private = false ``` ## Kinematics ```@autodocs Modules = [FlightMechanicsUtils] Pages = ["kinematics.jl"] Private = false ``` ## Mechanics ```@autodocs Modules = [FlightMechanicsUtils] Pages = ["mechanics.jl"] Private = false ``` ## Anemometry - Calibrated - Equivalent - True ```@autodocs Modules = [FlightMechanicsUtils] Pages = ["anemometry.jl"] Private = false ```
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.1.2
de9ce8d885ae995c6309f33cb9b40b59cd187661
docs
1709
# FlightMechanicsUtils.jl *Flight Mechanics in Julia.* ## Overview This is a suite for Flight Mechanics written in Julia. The purpose of this package is to supply efficient and validated Julia implementations of common Flight Mechanics calculations. At the moment, it covers: - International Standard Atmosphere. - Transformations between common coordinate systems in Flight Mechanics problems (body, horizon, wind, ECEF) supporting Euler angles and quaternions. - Kinematics & Dynamics: - Rigid solid velocity and acceleration fields. - Angular kinematic equations. - Steiner theorem:to determine the moment of inertia of a rigid body about any axis. - Trimmer constrains for leveled flight, climbs and turns. - Anemometric functions (tas, cas, eas, dynamic pressure). - ECEF (Earth Centered Earth Fixed) <---> LLH (Latitude Longitude Height) conversions. ## Install Last release: `pkg> add FlightMechanicsUtils` Dev version: `pkg> dev FlightMechanicsUtils` Run tests: `pkg> test FlightMechanicsUtils` ## What's new ### v0.1.2 #### New - [`Ellipsoid`](@ref) type with some common ellipsoids such as `WGS84`. - Transformation ([`ecef2llh`](@ref)) from ECEF (Earth Centered Earth Fixed) to LLH (latitude, longitude, height) and viceversa ([`llh2ecef`](@ref)) given the reference ellipsoid. - Rotation ([`horizon2ecef`](@ref)) from local horizon to ECEF axis and vicecersa ([`ecef2horizon`](@ref)). #### Enhancements - [`coordinated_turn_bank(ψ_dot, α, β, tas, γ, g)`](@ref) now accepts gravity as optional argument. ### v.0.1.1 Initial [release](https://github.com/AlexS12/FlightMechanicsUtils.jl/releases/tag/v0.1.1). ## Contents ```@contents Pages = ["index.md", "api.md"] ```
FlightMechanicsUtils
https://github.com/AlexS12/FlightMechanicsUtils.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
6766
using LinearAlgebra N = 40 N_t = 300 N_f = 150 #s = tf("s"); """ `toeplitz2(vc, N = length(vc))` Create toeplitxz matrix by stacking vc as columns, to width N, keeping height at length(vc) """ function toeplitz2(vc, N = size(vc,1)) M = vc[:,:] Ncol = size(vc,2) Nrow = size(vc,1) for i = 2:N M = [M [zeros(i-1, Ncol); vc[1:Nrow-i+1, :]]] end return M end function toeplitz(vc::AbstractVector{T}, vr) where T N = length(vc) @assert N == length(vr) @assert vc[1] == vr[1] M = Array{T,2}(undef, N, N) # Subdiagonal for i = 1:N # Each column M[i:N,i] = vc[1:N-i+1] end for i = 1:N # Each row M[i, i:N] = vr[1:N-i+1] end return M end """ Compute A,b for the eqpression A*q+b corresponding to S*v=(I-PQ)v """ function Saff_t(TP,v,N) A = - T_P*toeplitz2(v,N) b = copy(v) return A, b end """ Compute A,b for the eqpression A*q+b corresponding to PS*v=P(I-PQ)v """ function PSaff_t(TP,v,N) AQ,bQ = CSaff_t(TP,v,N) A = -TP*TP*AQ b = TP*(v - TP*bQ) return A, b end """ Compute A,b for the eqpression A*q+b corresponding to CS*v=Qv """ function CSaff_t(TP,v,N) A = toeplitz2(v,N) b = zero(v) return A, b end """ Compute A,b for the eqpression A*q+b corresponding to CS*v=Qv """ function PCSaff_t(TP,v,N) A = TP*toeplitz2(v,N) b = zero(v) return A, b end function Saff_fr(P_fr, Qf) # Q_fr = G_q_fr*b # S_fr = 1 - P_fr.*Q_fr A = -P_fr.*Qf b = ones(eltype(Qf), size(P_fr,1)) return A,b end """ T_P = SysP(g) Given impulse response of system p, generate system (toeplitz) matrix TP """ function SysP(g) T_P = toeplitz(g, [g[1]; zeros(length(g)-1)]); end """ G_q_fr = Qfreq(Ω, N) Generate matrix for calculating frequency respose (Q_fr) of Q on grid Ω, such that Q_fr = G_q_fr*q where q is the impulse response or order N, and Ω∈(0,π) """ function Qfreq(Ω, N) exp.((-im.*Ω)*(0:N-1)') end using ControlSystems #P = c2d(1/(20*s + 1) * exp(-5*s), 1); z_d = tf("z", 1) P_sysd = (1/20)/(z_d-0.95)/z_d^5 P_d(z) = (1/20)/(z-0.95)/z^5 #P(z) = (1/20)/(z-0.95)*z^(-5) g = impulse(P_sysd, N_t-1)[1][:] T_P = SysP(g) Ω = 2*pi*(10 .^range(-3, log10(0.5), length=N_f)) #P_fr = freqresp(P_sysd, Ω)[:] P_fr = P_d.(exp.(im.*Ω)) G_q_fr = Qfreq(Ω, N) e1 = [1; zeros(N_t - 1)]; d1 = ones(N_t); PSA, PSb = PSaff_t(T_P, d1, N) SA_fr, Sb_fr = Saff_fr(P_fr, G_q_fr) using Convex ################# Multiple affine and cones in Convex: b = Variable(N) y_d = Variable(N_t) #Q_fr = ComplexVariable(N_f) S_fr_re = Variable(N_f) S_fr_im = Variable(N_f) t1 = Variable() t2 = Variable() t3 = Variable(N_f) t4 = Variable() #c2 = (Q_fr == G_q_fr*b) c3_re = (S_fr_re == real(SA_fr)*b + real(Sb_fr)) # Aff c3_im = (S_fr_im == imag(SA_fr)*b + imag(Sb_fr)) # Aff c4 = (t2 == t1 - 5^2) # Aff c5 = sumsquares(b) <= t1; # SOC ∋ (b,t1) c7 = (t2 <= 0) # NonPos ∋ t2 c8 = (abs2(S_fr_re) + abs2(S_fr_im) <= t3) # Many SOCs ∋ (S_fr,t3) c9 = (t3 == 1.6^2) # Affine #cost = sumsquares(y_d) c1 = (y_d == PSA*b+PSb) # Affine c10 = (sumsquares(y_d) <= t4) # SOC ∋ (y_d, t4) c11 = (t4 == 1.1207+0.01) # Affine prob = minimize(0, c1, c3_re, c3_im, c4, c5, c6, c7, c8, c9, c10, c11) ################# As one affine + cone in convex Astag1 = toeplitz2([1 0 0; zeros(N_f-1, 3)]) Astag2 = toeplitz2([0 1 0; zeros(N_f-1, 3)]) Astag3 = toeplitz2([0 0 1; zeros(N_f-1, 3)]) A1 = [ zeros(N_f,1) -real(SA_fr) zeros(N_f,1) Astag2 zeros(N_f,1) zeros(N_f, N_t) ] A2 = [ zeros(N_f,1) -imag(SA_fr) zeros(N_f,1) Astag3 zeros(N_f,1) zeros(N_f, N_t) ] A3 = [ -1 zeros(1,N) 1 zeros(1,N_f*3) zeros(1, 1) zeros(1, N_t) ] A4 = [ zeros(N_f,1) zeros(N_f,N) zeros(N_f,1) Astag1 zeros(N_f,1) zeros(N_f, N_t) ] A5 = [ zeros(N_t,1) -PSA zeros(N_t,1) zeros(N_t,N_f*3) zeros(N_t,1) I ] A6 = [ 0 zeros(1,N) 0 zeros(1,N_f*3) 1 zeros(1, N_t) ] x = [t1;b;t2; vcat(([t3[i];S_fr_re[i];S_fr_im[i];] for i in 1:N_f)...); t4; y_d] # For comparison xc = [sqrt(t1);b;t2; vcat(([sqrt(t3[i]);S_fr_re[i];S_fr_im[i];] for i in 1:N_f)...); sqrt(t4); y_d] Aall = [A1;A2;A3;A4;A5;A6] ball = [real(Sb_fr); imag(Sb_fr); -5^2; fill(1.6^2, N_f); PSb; 1.1207+0.01] Aff = (Aall*x == ball) Cone = [sumsquares(b) <= t1; t2 <= 0; vcat((abs2(S_fr_re[i]) + abs2(S_fr_im[i]) <= t3[i] for i in 1:N_f)...); sumsquares(y_d) <= t4] prob = minimize(0, Aff, Cone...) using SCS @time solve!(prob, SCSSolver()) using Plots plot(evaluate(b)) ############ Using ProximalOperators using ProximalOperators ball2 = [real(Sb_fr); imag(Sb_fr); -5; fill(1.6, N_f); PSb; sqrt(1.1207+0.01)] S1 = IndAffine(Aall, ball2) fs = (IndSOC(), IndNonpositive(), (IndSOC() for i in 1:N_f)..., IndSOC()) idxs = (1:(N+1), (N+2):(N+2), ((N+3+i-1):(N+3+i+1) for i in 1:3:(N_f*3))..., (N+2+3*N_f+1):(N+2+3*N_f+N_t+1)) S2 = SlicedSeparableSum(fs, tuple.(idxs)) y0 = randn(size(Aall,2)) x0 = randn(size(Aall,2)) using FirstOrderSolvers alg = DR() problem = FirstOrderSolvers.Feasibility(S1, S2, size(Aall,2)) sol = FirstOrderSolvers.solve!(p, solver, checki=10, eps=1e-9) using ProximalAlgorithms solver = ProximalAlgorithms.DouglasRachford(gamma=1.0,maxit=10000,verbose=true) x0, y0, it = solver(x0, f=S1, g=S2) @profiler solver(x0, f=S1, g=S2) tmp1 = similar(x0) tmp2 = similar(x0) tmp3 = similar(x0) @time for i = 1:1000 prox!(x0, S1, y0) tmp1 .= 2. *x0 .- y0 prox!(tmp2, S2, tmp1) tmp3 .= 2. *tmp2 .- tmp1 i%100 == 0 && (print("Err: "); println(norm(x0-tmp2))) i%100 == 0 && (print("Ang: "); println(acos(min(dot(y0-x0, tmp2-tmp1)/norm(x0-y0)/norm(tmp2-tmp1),1)))) # Shadow in tmp2 y0 .= (tmp3 .+ y0)./2 end bsol = tmp2[2:N+1] plot(bsol) using Convex b = Variable(N) #T_Q = toeplitz2([b; zeros(N_t-N)]) #y_d = T_P*(Matrix{Float64}(I,N_t,N_t) - T_P*T_Q)*d1 #y_d = T_P*d1 - T_P*T_P*toeplitz2(d1,N)*b y_d = PSA*b+PSb Q_fr = G_q_fr*b cost = sumsquares(y_d) const1 = abs(SA_fr*b+Sb_fr) <= 1.6 const2 = sumsquares(b) <= 5^2 prob = minimize(cost, const1, const2) using SCS solve!(prob, SCSSolver()) using Plots plot(evaluate(b)) plot(Ω./2 ./pi, abs.(1 .- P_fr.*evaluate(Q_fr)), yscale=:log10, xscale=:log10) C_fr = vec(evaluate(Q_fr) ./ (1 .- P_fr .*evaluate(Q_fr))) plot(Ω/2/pi, abs.(C_fr), yscale=:log10, xscale=:log10)
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
2670
import MathProgBase.SolverInterface: ConicModel, LinearQuadraticModel, optimize!, status, getobjval, getsolution, loadproblem!, numvar, numconstr, supportedcones ConicModel(s::FOSAlgorithm) = FOSMathProgModel(s; s.options...) LinearQuadraticModel(s::FOSAlgorithm) = ConicToLPQPBridge(ConicModel(s)) function optimize!(m::FOSMathProgModel) #TODO fix history m.history = ValueHistories.MVHistory() solution = solve!(m) #TODO Code here! m.solve_stat = solution.status m.primal_sol = solution.x m.dual_sol = solution.y m.slack = solution.s m.obj_val = dot(m.c, m.primal_sol)# * (m.orig_sense == :Max ? -1 : +1) end status(m::FOSMathProgModel) = m.solve_stat getobjval(m::FOSMathProgModel) = m.obj_val getsolution(m::FOSMathProgModel) = copy(m.primal_sol) function loadproblem!(model::FOSMathProgModel, c, A, b, constr_cones, var_cones) loadproblem!(model, c, sparse(A), b, constr_cones, var_cones) end function loadproblem!(model::FOSMathProgModel, c, A::SparseMatrixCSC, b, constr_cones, var_cones) t1 = time_ns() model.input_numconstr = size(A,1) model.input_numvar = size(A,2) # Verify only good cones for cone_vars in constr_cones cone_vars[1] in badcones && @error "Cone type $(cone_vars[1]) not supported" end for cone_vars in var_cones cone_vars[1] in badcones && @error "Cone type $(cone_vars[1]) not supported" end conesK1 = tuple([conemap[t[1]] for t in constr_cones]...) indexK1 = tuple([t[2] for t in constr_cones]...) model.K1 = ConeProduct(indexK1, conesK1) conesK2 = tuple([conemap[t[1]] for t in var_cones]...) indexK2 = tuple([t[2] for t in var_cones]...) model.K2 = ConeProduct(indexK2, conesK2) model.A = A # TODO figure out :Min/:Max model.b = b model.c = c # Calls a specific method based on the type T in model::FOSMathProgModel{T} data, status_generator = init_algorithm!(model.alg, model) model.status_generator = status_generator model.data = data t2 = time_ns() model.init_duration = t2-t1 return model end numvar(model::FOSMathProgModel) = model.input_numvar numconstr(model::FOSMathProgModel) = model.input_numconstr supportedcones(s::FOSAlgorithm) = [:Free, :Zero, :NonNeg, :NonPos, :SOC, :SDP, :ExpPrimal, :ExpDual] """ `S1, S2, n, status_generator = get_sets_and_status(alg::FOSAlgorithm, model::FOSMathProgModel)` Get the sets S1, S2 and their size n """ function get_sets_and_status(alg::FOSAlgorithm, model::FOSMathProgModel) hsde, status_generator = HSDE(model, direct=alg.direct) return hsde.indAffine, hsde.indCones, hsde.n, status_generator end
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
906
#__precompile__() module FirstOrderSolvers using ProximalOperators using SparseArrays using Printf import ValueHistories using LinearAlgebra import LinearAlgebra: mul!, Transpose, dot, norm export Feasibility include("cones.jl") include("types.jl") include("status.jl") include("utilities/conjugategradients.jl") include("utilities/affinepluslinear.jl") include("problemforms/HSDE/HSDEStatus.jl") include("problemforms/HSDE/HSDE.jl") include("problemforms/HSDE/HSDEAffine.jl") include("problemforms/Feasibility/Feasibility.jl") include("problemforms/Feasibility/FeasibilityStatus.jl") include("FOSSolverInterface.jl") # MathProgBase interface include("solverwrapper.jl") include("wrappers/longstep.jl") include("wrappers/linesearch.jl") include("solvers/defaults.jl") include("solvers/solvers.jl") #include("lapack.jl") #include("solvermethods.jl") #include("line_search_methods.jl") end # module
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
4294
import ProximalOperators: ProximableFunction, prox!, IndPSD # TODO zero cone const conemap = Dict{Symbol, ProximableFunction}( :Free => IndFree(), :Zero => IndZero(), :NonNeg => IndNonnegative(), :NonPos => IndNonpositive(), :SOC => IndSOC(), :SOCRotated => IndRotatedSOC(), :SDP => IndPSD(scaling=true), :ExpPrimal => IndExpPrimal(), :ExpDual => IndExpDual() ) const badcones = ProximableFunction[] # type DualCone{T<:ProximableFunction} <: ProximableFunction # C::T # end # dual{T<:ProximableFunction}(C::T) = DualCone{T}(C) # dual(C::DualCone) = C.C # function prox!(cone::DualCone, x, y) # prox!(cone.C, -x, y) # for i = 1:length(x) # y[i] = x[i] + y[i] # end # end mutable struct ConeProduct{N,T} <: ProximableFunction ranges::NTuple{N, UnitRange{Int64}} cones::T end # ConeProduct() = ConeProduct{0,Any}((),()) # function ConeProduct(ranges::NTuple{N, UnitRange{Int64}}, cones::T) where {N,T} # return ConeProduct{N,T}(ranges, cones) # end toRanges(rangesIn::NTuple{N, UnitRange{Int64}}) where N = rangesIn function toRanges(rangesIn::NTuple{N,Array{T,1}}) where {N, T<:Integer} ranges = Array{UnitRange{Int64},1}(undef, N) for j in 1:N range = rangesIn[j] for (i,el) in enumerate(range[1]:range[end]) if el != range[i] @error "Invalid range in input" end end ranges[j] = range[1]:range[end] end return tuple(ranges...) end #Should accept tro tuples with UnitRange{Int64} and ProximableFunction #Cant enforce types or ambigous with default constructor? function ConeProduct(rangesIn, cones) ranges = toRanges(rangesIn) N = length(cones) @assert typeof(ranges) == NTuple{N, UnitRange{Int64}} @assert length(ranges) == N @assert typeof(cones) <: Tuple #Verify that ranges covers the whole range prevRangeEnd = 0 for i = 1:N @assert ranges[i][1] == prevRangeEnd + 1 prevRangeEnd = ranges[i][end] @assert typeof(cones[i]) <: ProximableFunction end T = typeof(cones) #println("Dumping cones input") #dump(cones) ConeProduct(ranges, cones) end #Wrapper for dual prox to avoid double duals function proxDual!(y::AbstractArray, C::ProximableFunction, x::AbstractArray) prox!(y, C, -x) @simd for i = 1:length(x) y[i] = x[i] + y[i] end end # proxDual!(y, C::DualCone, x) = prox!(y, C.C, x) function prox!(y::AbstractArray, C::ConeProduct{N,T}, x::AbstractArray) where {N,T} #TODO Paralell implementation for i = 1:N prox!(view(y, C.ranges[i]), C.cones[i], view(x, C.ranges[i])) end end ## Some better dual projections const myIndFree = IndFree() proxDual!(y::AbstractArray, C::IndZero, x::AbstractArray) = prox!(y, myIndFree, x) const myIndZero = IndPoint() proxDual!(y::AbstractArray, C::IndFree, x::AbstractArray) = prox!(y, myIndZero, x) proxDual!(y::AbstractArray, C::IndNonnegative, x::AbstractArray) = prox!(y, C, x) proxDual!(y::AbstractArray, C::IndNonpositive, x::AbstractArray) = prox!(y, C, x) # TODO figure out if self dual PSD #proxDual!(y::AbstractArray, C::IndPSD, x::AbstractArray) = prox!(y, C, x) function proxDual!(y::AbstractArray, C::ConeProduct{N,T}, x::AbstractArray) where {N,T} #TODO Paralell implementation for i = 1:N proxDual!(view(y, C.ranges[i]), C.cones[i], view(x, C.ranges[i])) end end """ Indicator of K2×K1*×R+ × K2*×K1×R+ ∈ (R^n,R^m,R)^2""" mutable struct DualConeProduct{T1<:ConeProduct,T2<:ConeProduct} <: ProximableFunction K1::T1 K2::T2 m::Int64 n::Int64 end DualConeProduct(K1::T1,K2::T2) where {T1,T2} = DualConeProduct{T1,T2}(K1, K2, K1.ranges[end][end], K2.ranges[end][end]) function prox!(y::AbstractArray, K::DualConeProduct, x::AbstractArray) m, n = K.m, K.n K1, K2 = K.K1, K.K2 nu = n+m+1 xx = view(x, 1:n) xy = view(x, (n+1):(n+m)) xr = view(x, (nu+1):(nu+n)) xs = view(x, (nu+n+1):(nu+n+m)) yx = view(y, 1:n) yy = view(y, (n+1):(n+m)) yr = view(y, (nu+1):(nu+n)) ys = view(y, (nu+n+1):(nu+n+m)) prox!( yx, K2, xx) proxDual!(yy, K1, xy) y[nu] = max(x[nu], 0) proxDual!(yr, K2, xr) prox!( ys, K1, xs) y[2nu] = max(x[2nu], 0) end
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
246
function plothistory(problem, p = plot()) hist = problem.model.history h = hist[:p] nonnan = !isnan.(hist[:p].values) val = hist[:p].values[nonnan] iter = hist[:p].iterations[nonnan] plot!(p, iter, val, yscale=:log10) end
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
1389
function solve!(model::AbstractFOSModel) opts = Dict(model.options) #TODO better kwarg default handling max_iters = :max_iters ∈ keys(opts) ? opts[:max_iters] : 10000 verbose = :verbose ∈ keys(opts) ? opts[:verbose] : 1 debug = :debug ∈ keys(opts) ? opts[:debug] : 1 eps = :eps ∈ keys(opts) ? opts[:eps] : 1e-5 checki = :checki ∈ keys(opts) ? opts[:checki] : 100 x = getinitialvalue(model, model.alg, model.data) #TODO general status status = model.status_generator(model, checki, eps, verbose, debug) guess = iterate(model.alg, model.data, status, x, max_iters) sol = populate_solution(model, model.alg, model.data, guess, status) return sol end function iterate(alg::FOSAlgorithm, data::FOSSolverData, status, x, max_iters) t1 = time() printstatusheader(status) for i = 1:max_iters status.i = i step(alg, data, x, i, status) if status.status != :Continue break end end #TODO Status should maybe be more consistent with guess guess = getsol(alg, data, x) if !status.checked #If max_iters reached without check checkstatus(status, guess, override = true) #Force check independent of iteration count end if status.verbose > 0 println("Time for iterations: ") t2 = time() println("$(t2-t1) s") end return guess end
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
128
import ValueHistories: push! function checkstatus(::NoStatus, z) return false end printstatusheader(::NoStatus) = nothing
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
2129
using MathProgBase.SolverInterface #export FOSAlgorithm abstract type AbstractSolution end mutable struct Solution <: AbstractSolution x::Array{Float64, 1} y::Array{Float64, 1} s::Array{Float64, 1} status::Symbol end abstract type FOSAlgorithm <: AbstractMathProgSolver end abstract type FOSSolverData end struct FOSSolverDataPlaceholder <: FOSSolverData end abstract type FOSModel end abstract type AbstractStatus end mutable struct NoStatus <: AbstractStatus status::Symbol end # Define Solver for interface # struct FOSSolver <: AbstractMathProgSolver # options # end # FOSSolver(;kwargs...) = FOSSolver(kwargs) # mutable struct FOSMathProgModel <: AbstractConicModel input_numconstr::Int64 # Only needed for interface? input_numvar::Int64 # Only needed for interface? K1::ConeProduct K2::ConeProduct A::SparseMatrixCSC{Float64,Int} # The A matrix (equalities) b::Vector{Float64} # RHS c::Vector{Float64} # The objective coeffs (always min) alg::FOSAlgorithm #This descides which algorithm to call data::FOSSolverData # Solver specific data is stored here # orig_sense::Symbol # Original objective sense # Post-solve solve_stat::Symbol obj_val::Float64 primal_sol::Vector{Float64} dual_sol::Vector{Float64} slack::Vector{Float64} options::Dict{Symbol, Any} enditr::Int64 status_generator::Function init_duration::UInt64 # In nano-seconds history::ValueHistories.MVHistory end function FOSMathProgModel(s::FOSAlgorithm; kwargs...) FOSMathProgModel(0, 0, ConeProduct(), ConeProduct(), spzeros(0, 0), Float64[], Float64[], s, FOSSolverDataPlaceholder(), :NotSolved, 0.0, Float64[], Float64[], Float64[], Dict{Symbol,Any}(kwargs), -1, x -> (@error "No status generator defined"), UInt64(1), ValueHistories.MVHistory()) end # To handle both custom types and const AbstractFOSModel = Union{FOSMathProgModel, FOSModel}
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
2543
## Problem struct Feasibility{T1<:ProximableFunction,T2<:ProximableFunction} S1::T1 S2::T2 n::Int64 end mutable struct FeasibilitySolution <: AbstractSolution x::Array{Float64, 1} status::Symbol end # Model with all data mutable struct FeasibilityModel{T1<:ProximableFunction,T2<:ProximableFunction} <: FOSModel S1::T1 S2::T2 n::Int64 alg::FOSAlgorithm #This descides which algorithm to call data::FOSSolverData # Solver specific data is stored here solve_stat::Symbol obj_val::Float64 options::Dict{Symbol, Any} enditr::Int64 status_generator::Function init_duration::UInt64 # In nano-seconds history::ValueHistories.MVHistory end function FeasibilityModel(problem::Feasibility, alg::FOSAlgorithm, kwargs...) t1 = time_ns() model = FeasibilityModel(problem.S1, problem.S2, problem.n, alg, FOSSolverDataPlaceholder(), :NotSolved, 0.0, Dict{Symbol,Any}(kwargs), -1, x -> (@error "No status generator defined"), UInt64(1), ValueHistories.MVHistory()) data, status_generator = init_algorithm!(model.alg, model) model.status_generator = status_generator model.data = data t2 = time_ns() model.init_duration = t2-t1 return model end function solve!(problem::Feasibility, alg::FOSAlgorithm; kwargs...) model = FeasibilityModel(problem, alg, kwargs...) solution = solve!(model) end getinitialvalue(model::FeasibilityModel) = zeros(model.n) getinitialvalue(model::FeasibilityModel, alg, data) = zeros(model.n) function populate_solution(model::FeasibilityModel, alg, data, x, status) endstatus = status.status if endstatus == :Continue endstatus = :Indeterminate end solution = FeasibilitySolution(x, endstatus) end """ `S1, S2, n, status_generator = get_sets_and_status(alg::FOSAlgorithm, model::FOSMathProgModel)` Get the sets S1, S2 and their size n """ function get_sets_and_status(alg::FOSAlgorithm, model::FeasibilityModel) direct = true # alg.direct # No support in this model for setting flag here #!alg.direct && @warn "Not possible to set direct/indirect solve in algorithm, use appropriate set from ProximalOperators" status_generator = (mo, checki, eps, verbose, debug) -> FeasibilityStatus(mo.n, 0, mo, fill(NaN, mo.n), :Continue, checki, eps, verbose, false, direct, time_ns(), mo.init_duration, debug) return model.S1, model.S2, model.n, status_generator end
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
2565
mutable struct FeasibilityStatus <: AbstractStatus n::Int64 i::Int64 model::FeasibilityModel prev::Array{Float64,1} # Previous iterate to check convergence status::Symbol checki::Int64 eps::Float64 verbose::Int64 checked::Bool direct::Bool init_time::UInt64 #As reported by time_ns() init_duration::UInt64 #In nano-seconds debug::Int64 end """ checkstatus(stat::FeasibilityStatus, x) Returns `false` if no check was made If convergence check is done, returns `true` and sets stat.status to one of: :Continue, :Optimal, :Infeasible """ function checkstatus(stat::FeasibilityStatus, z; override = false) #TODO fix m, n if stat.i % stat.checki == 0 || override t = time_ns() - stat.init_time n, i, model, verbose, debug, ϵ = stat.n, stat.i, stat.model, stat.verbose, stat.debug, stat.eps prev = stat.prev # TODO Measure better err = norm(prev - z) if debug > 0 savedata(i, err, z, t, model, debug) end if verbose > 0 if !stat.direct cgiter = getcgiter(stat.model.data) push!(model.history, :cgiter, i, cgiter) printstatusiter(i, err, cgiter, t) else printstatusiter(i, err, t) end end status = :Continue if err <= ϵ if verbose > 0 println("Found solution i=$i") end status = :Optimal elseif false # TODO Be able to check better status = :Infeasible end stat.status = status stat.checked = true stat.prev .= z return stat.checked else stat.checked = false stat.prev .= z return stat.checked end end function printstatusheader(stat::FeasibilityStatus) if stat.verbose > 0 println("Time to initialize: $(stat.init_duration/1e9)s") width = 22 + (stat.direct ? 0 : 5) println("-"^width) print(" Iter | res") !stat.direct && print(" | cg ") println(" | time") println("-"^width) end end function printstatusiter(i, err, t) @printf("%6d|% 9.2e % .1es\n",i,err,t/1e9) end function printstatusiter(i, err, cgiter, t) @printf("%6d|% 9.2e % 4d % .1es\n",i,err,cgiter,t/1e9) end function savedata(i, err, z, t, model, debug) history = model.history push!(history, :err, i, err) push!(history, :t, i, t) if debug > 1 push!(history, :z, i, z) end return end
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
2059
mutable struct HSDE{T1<:ProximableFunction,T2<:DualConeProduct} indAffine::T1 indCones::T2 n::Int64 end function HSDE(model::FOSMathProgModel; direct=false) m,n = size(model.A) S1 = if direct # Uses direct solver from ProximalOperators Q = [spzeros(n,n) model.A' model.c; -model.A spzeros(m,m) model.b; -model.c' -model.b' 0 ] IndAffine([sparse(Q) -I], zeros(size(Q,1))) else Q = HSDEMatrixQ(model.A, model.b, model.c) # Q = [spzeros(n,n) model.A' model.c; # -model.A spzeros(m,m) model.b; # -model.c' -model.b' 0 ] # Using CG on KKT system AffinePlusLinear(Q, zeros(size(Q,1)), zeros(size(Q,1)), 1, decreasing_accuracy=true) end S2 = DualConeProduct(model.K1,model.K2) m,n = S2.m, S2.n status_generator = (mo, checki, eps, verbose, debug) -> HSDEStatus(m, n, 0, mo, :Continue, checki, eps, verbose, false, direct, time_ns(), model.init_duration, debug) return HSDE(S1, S2, 2*(size(model.A,1)+size(model.A,2)+1)), status_generator end # TODO Unclear why this is nessesary/differenet getinitialvalue(model::FOSMathProgModel) = HSDE_getinitialvalue(model) getinitialvalue(model::FOSMathProgModel, alg, data) = HSDE_getinitialvalue(model) populate_solution(model::FOSMathProgModel, alg, data, x, status) = HSDE_populatesolution(model, x, status) function HSDE_getinitialvalue(model::FOSMathProgModel) m, n = size(model.A) l = m+n+1 x = zeros(2*l) x[l] = 1.0 x[2l] = 1.0 return x end function HSDE_populatesolution(model::FOSMathProgModel, x, status::HSDEStatus) m, n = size(model.A) l = m+n+1 @assert length(x) == 2l τ = x[l] κ = x[2l] #TODO Eveluate status endstatus = status.status if endstatus == :Continue endstatus = :Indeterminate end solution = Solution(x[1:n]/τ, x[n+1:n+m]/τ, x[l+n+1:l+n+m]/τ, endstatus) end
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
4133
struct HSDEMatrixQ{T,M<:AbstractMatrix{T},V<:AbstractVector{T}} <: AbstractMatrix{T} A::M b::V c::V am::Int64 an::Int64 end """ HSDEMatrixQ(A::M, b::V, c::V) where {T,M<:AbstractMatrix{T},V<:AbstractVector{T}} """ function HSDEMatrixQ(A::M, b::V, c::V) where {T,M<:AbstractMatrix{T},V<:AbstractVector{T}} am, an = size(A) @assert size(b,1) == am @assert size(c,1) == an HSDEMatrixQ{T,M,V}(A, b, c, am, an) end Base.size(Q::HSDEMatrixQ) = (Q.am+Q.an+1, Q.am+Q.an+1) # Fallback, to have both defined Base.show(io::IO, mt::MIME"text/plain", Q::T) where {T<:HSDEMatrixQ} = Base.show(io, Q) function Base.show(io::IO, Q::T) where {T<:HSDEMatrixQ} m,n = size(Q) println(io, "$(m)x$(m) $T:") println(io, "[0 A' c;\n -A 0 b;\n -c' -b' 0]") println(io,"where A:") Base.show(io, Q.A) println(io,"\nb:") Base.show(io, Q.b) println(io,"\nc:") Base.show(io, Q.c) end # Q of size #(n,n) (n,m) (n,1) #(m,m) (m,m) (m,1) #(1,n) (1,m) (1,1) function mul!(Y::AbstractArray{T,1}, Q::HSDEMatrixQ{T,M,V}, B::AbstractArray{T,1}) where {T,M<:AbstractArray{T,2},V<:AbstractArray{T,1}} @assert size(Q) == (size(Y,1), size(B,1)) y1 = view(Y, 1:Q.an) y2 = view(Y, (Q.an+1):(Q.an+Q.am)) b1 = view(B, 1:Q.an) b2 = view(B, (Q.an+1):(Q.an+Q.am)) b3 = B[Q.am+Q.an+1] A = Q.A b = Q.b c = Q.c mul!(y1, transpose(A), b2) mul!( y2, A, b1) #TODO maybe switch back for readability? y1 .+= b3.*c # y1 .= y1 .+ c.*b3 y2 .-= b3.*b # y2 .= b.*b3 .- y2 y2 .= .-y2 Y[Q.am+Q.an+1] = - dot(c, b1) - dot(b,b2) return Y end function mul!(Y::AbstractArray{T,1}, Q::Transpose{T, QMat}, B::AbstractArray{T,1}) where {T, M<:AbstractArray{T,2},V<:AbstractArray{T,1}, QMat<:HSDEMatrixQ{T,M,V}} mul!(Y,Q.parent,B) Y .= .-Y return Y end struct HSDEMatrix{T,QType<:AbstractMatrix{T}} <: AbstractMatrix{T} Q::QType cgdata::CGdata{T} end """ HSDEMatrix(Q::HSDEMatrixQ) """ HSDEMatrix(Q::QType) where {T, QType<:AbstractMatrix{T}} = HSDEMatrix{T,QType}(Q, CGdata(2*size(Q)[1])) """ HSDEMatrix(A::M, b::V, c::V) where {T,M<:AbstractMatrix{T},V<:AbstractVector{T}} """ function HSDEMatrix(A::M, b::V, c::V) where {T,M<:AbstractMatrix{T},V<:AbstractVector{T}} Q = HSDEMatrixQ(A, b, c) HSDEMatrix(Q, CGdata(2*size(M.Q)[1])) end function Base.size(M::HSDEMatrix) m, n = size(M.Q) return (2m,2m) end # Try fallback Base.show(io::IO, mt::MIME"text/plain", M::T) where {T<:HSDEMatrix} = Base.show(io, M) function Base.show(io::IO, M::T) where {T<:HSDEMatrix} m,n = size(M) println(io, "$(m)x$(m) $T:") println(io, "[I Q';\n Q -I]") println(io,"where Q:") Base.show(io, M.Q) end """ solve argmin_y{||x-y||₂}, s.t. Q*u==v, where [u;v] == x """ function prox!(y::AbstractVector, A::HSDEMatrix, x::AbstractVector) tol = size(A,2)*eps() max_iters = 1000 cgdata = A.cgdata if cgdata.firstrun.x #Pointer, has this been initialized cgdata.xinit .= x #Works as guess since Q square cgdata.firstrun.x = false end #Since y is the initial guess, use previous solution y .= cgdata.xinit #solve [I Q';Q -I][u^(k+1);μ] = [u^k;v^k] conjugategradient!(y, A, x, cgdata.r, cgdata.p, cgdata.z, tol = tol, max_iters = max_iters) #Save initial guess for next prox! cgdata.xinit .= y m, n = size(A.Q) #Let v=Q*u u = view(y,1:m) v = view(y,(m+1):2m) mul!(v, A.Q, u) return 0.0 end function mul!(Y::AbstractArray{T,1}, M::HSDEMatrix{T,QType}, B::AbstractArray{T,1}) where {T,QType<:AbstractMatrix{T}} m2 = size(M)[1] mQ = size(M.Q)[1] @assert (m2,m2) == (size(Y,1), size(B,1)) y1 = view(Y, 1:mQ) y2 = view(Y, (mQ+1):(2mQ)) b1 = view(B, 1:mQ) b2 = view(B, (mQ+1):(2mQ)) mul!(y1, transpose(M.Q), b2) mul!( y2, M.Q, b1) @inbounds y1 .= y1 .+ b1 @inbounds y2 .= y2 .- b2 return Y end mul!(Y::AbstractArray{T,1}, Q::Transpose{T, QMat}, B::AbstractArray{T,1}) where {T, QType<:AbstractMatrix{T}, QMat<:HSDEMatrix{T,QType}} = mul!(Y, Q.parent, B)
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
4479
mutable struct HSDEStatus <: AbstractStatus m::Int64 n::Int64 i::Int64 model::FOSMathProgModel status::Symbol checki::Int64 eps::Float64 verbose::Int64 checked::Bool direct::Bool init_time::UInt64 #As reported by time_ns() init_duration::UInt64 #In nano-seconds debug::Int64 end """ checkstatus(stat::HSDEStatus, x) Returns `false` if no check was made If convergence check is done, returns `true` and sets stat.status to one of: :Continue, :Optimal, :Unbounded, :Infeasible """ function checkstatus(stat::HSDEStatus, z; override = false) #TODO fix m, n if stat.i % stat.checki == 0 || override t = time_ns() - stat.init_time m, n, i, model, verbose, debug, ϵ = stat.m, stat.n, stat.i, stat.model, stat.verbose, stat.debug, stat.eps x, y, s, r, τ, κ = getvalues(model, m, n, z, i, verbose, debug) ϵpri = ϵdual = ϵgap = ϵinfeas = ϵunbound = ϵ p = norm(model.A*x/τ + s/τ - model.b)/norm(1+norm(model.b)) d = norm(model.A'*y/τ + model.c - r/τ)/norm(1+norm(model.c)) ctx = (model.c'*x)[1] bty = (model.b'*y)[1] g = norm(ctx/τ + bty/τ)/(1+abs(ctx/τ)+abs(bty/τ)) if debug > 0 savedata(i, p, d, g, ctx, bty, κ, τ, x, y, s, t, model, debug) end # TODO test u^T v if verbose > 0 if !stat.direct cgiter = getcgiter(stat.model.data) push!(model.history, :cgiter, i, cgiter) printstatusiter(i, p, d, g, ctx, bty, κ/τ, cgiter, t) else printstatusiter(i, p, d, g, ctx, bty, κ/τ, t) end end status = :Continue if p <= ϵpri*(1+norm(model.b)) && d <= ϵdual*(1+norm(model.c)) && g <= ϵgap*(1+norm(ctx/τ)+norm(bty/τ)) if verbose > 0 println("Found solution i=$i") end status = :Optimal elseif norm(model.A*x + s) <= ϵunbound*(-ctx/norm(model.c)) status = :Unbounded elseif norm(model.A'*y) <= ϵinfeas*(-bty/norm(model.b)) status = :Infeasible end stat.status = status stat.checked = true return stat.checked else stat.checked = false return stat.checked end end function printstatusheader(stat::HSDEStatus) if stat.verbose > 0 println("Time to initialize: $(stat.init_duration/1e9)s") width = 76 + (stat.direct ? 0 : 5) println("-"^width) print(" Iter | pri res | dua res | rel gap | pri obj | dua obj | kap/tau") !stat.direct && print(" | cg ") println(" | time") println("-"^width) end end function printstatusiter(i, p, d, g, stx, bty, κτ, t) @printf("%6d|% 9.2e % 9.2e % 9.2e % 9.2e % 9.2e % 9.2e % .1es\n",i,p,d,g,stx,-bty,κτ,t/1e9) end function printstatusiter(i, p, d, g, stx, bty, κτ, cgiter, t) @printf("%6d|% 9.2e % 9.2e % 9.2e % 9.2e % 9.2e % 9.2e % 4d % .1es\n",i,p,d,g,stx,-bty,κτ,cgiter,t/1e9) end function getvalues(model, m, n, z, i, verbose, debug) nu = n+m+1 x = view(z, 1:n) y = view(z, (n+1):(n+m)) r = view(z, (nu+1):(nu+n)) s = view(z, (nu+n+1):(nu+n+m)) τ = z[nu] κ = z[2nu] x, y, s, r, τ, κ end # """ # Checks primal and dual feasibility assuming that x,y,s are satisfying the cone constraints # """ # function printstatus(model, x, y, s, r, τ, κ, i, verbose, debug) # p = norm(model.A*x/τ + s/τ - model.b)/norm(1+norm(model.b)) # d = norm(model.A'*y/τ + model.c - r/τ)/norm(1+norm(model.c)) # ctx = (model.c'*x)[1] # bty = (model.b'*y)[1] # g = norm(ctx/τ + bty/τ)/(1+abs(ctx/τ)+abs(bty/τ)) # if debug > 0 # savedata(i, p, d, g, ctx, bty, κ, τ, x, y, s, model, debug) # end # # TODO test u^T v # if verbose > 0 # printstatusiter(i, p, d, g, ctx, bty, κ/τ) # end # return # end @generated function savedata(i, p, d, g, ctx, bty, κ, τ, x, y, s, t, model, debug) ex = :(history = model.history) for (v,vs) in [(:p, "p"), (:d, "d"), (:g, "g"), (:ctx, "ctx"), (:bty, "bty"), (:κ, "κ"), (:τ, "τ"), (:t, "t")] ex = :($ex ; push!(history, Symbol($vs), i, $v)) end ex2 = :() for (v,vs) in [(:x, "x"), (:y,"y"), (:s,"s")] ex2 = :($ex2 ; push!(history, Symbol($vs), i, $v)) end ex = :($ex; if debug > 1; $ex2; end) ex = :($ex; return) return ex end
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
1069
support_longstep(::Any) = false projections_per_step(::Any) = (0,0) """ Line search types: Val{:False} : No line search available Val{:True} : Line search available, but at the cost of extra evaluations Should provide an nonexpansive operator `y=T(x)` as `T!(y, alg<:FOSAlgorithm, data<:FOSSolverData, x, i, status, longstep)` so the algorithm becomes `x^(k+1) = (1-αk)x^k = αk*T(x^k)` Val{:Fast} : Line search available with low extra cost Should provide two operators `y=S1(x)`, `z=S2(y)` as `S1!(y, alg<:FOSAlgorithm, data<:FOSSolverData, x, i, status, longstep)` `S2!(y, alg<:FOSAlgorithm, data<:FOSSolverData, x, i, status, longstep)` so the algorithm becomes `x^(k+1) = (1-αk)x^k = αk*S2(S1(x^k))` `S1` has to be an affine operator, i.e. S1(x+y)+S1(0)=S1(x)+S2(y). """ support_linesearch(::Any) = Val{:False} #Defaults to that data.S1 counts cg iteration function getcgiter(data::FOSSolverData) return getcgiter(data.S1) end # Fallback getcgiter(data) = throw(ArgumentError("CGdata not available for type $(typeof(data))"))
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
1228
""" Dykstra """ mutable struct Dykstra <: FOSAlgorithm direct::Bool options end Dykstra(;direct=false, kwargs...) = Dykstra(direct, kwargs) struct DykstraData{T1,T2} <: FOSSolverData p::Array{Float64,1} q::Array{Float64,1} y::Array{Float64,1} S1::T1 S2::T2 end function init_algorithm!(alg::Dykstra, model::AbstractFOSModel) S1, S2, n, status_generator = get_sets_and_status(alg, model) data = DykstraData(zeros(n), zeros(n), Array{Float64,1}(undef, n), S1, S2) return data, status_generator end function Base.step(::Dykstra, data::DykstraData, x, i, status::AbstractStatus, longstep=nothing) p,q,y,S1,S2 = data.p,data.q,data.y,data.S1,data.S2 prox!(y, S1, x .+ p) addprojeq(longstep, y, x .+ p) p .= x .+ p .- y prox!(x, S2, y .+ q) checkstatus(status, x) addprojineq(longstep, x, y .+ q) q .= y .+ q .- x return end function getsol(::Dykstra, data::DykstraData, x) y,S1,S2 = data.y,data.S1,data.S2 tmp1 = similar(x) #Ok to allocate here, could overwrite p, q, if safe warmstart? prox!(tmp1, S1, x) prox!(y, S2, tmp1) return y #We reuse y here end support_longstep(::Dykstra) = true projections_per_step(::Dykstra) = (1,1)
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
1479
""" FISTA """ mutable struct FISTA <: FOSAlgorithm α::Float64 direct::Bool options end FISTA(α=1.0; direct=false, kwargs...) = FISTA(α, direct, kwargs) struct FISTAData{T1,T2} <: FOSSolverData t::Base.RefValue{Float64} y::Array{Float64,1} xold::Array{Float64,1} tmp1::Array{Float64,1} S1::T1 S2::T2 end function init_algorithm!(alg::FISTA, model::AbstractFOSModel) S1, S2, n, status_generator = get_sets_and_status(alg, model) data = FISTAData(Ref(1.0), zeros(n), zeros(n), Array{Float64,1}(undef, n), S1, S2) return data, status_generator end function Base.step(alg::FISTA, data::FISTAData, x, i, status::AbstractStatus, longstep=nothing) α,y,xold,tmp1,S1,S2 = alg.α,data.y,data.xold,data.tmp1,data.S1,data.S2 t = data.t #Reference if i == 1 #TODO this is ugly initializing hack y .= x end # Relaxed projection onto S1 prox!(tmp1, S1, y) addprojeq(longstep, tmp1, y) tmp1 .= α.*tmp1 .+ (1-α).*y # Relaxed projection onto S2 xold .= x prox!(x, S2, tmp1) checkstatus(status, x) addprojineq(longstep, x, tmp1) told = t.x t.x = (1+sqrt(1+4*t.x^2))/2 y .= x .+ (told-1)./(t.x).*(x .- xold) return end function getsol(::FISTA, data::FISTAData, x) tmp1,S1,S2 = data.tmp1,data.S1,data.S2 tmp2 = similar(x) prox!(tmp1, S1, x) prox!(tmp2, S2, tmp1) return tmp2 end support_longstep(::FISTA) = true projections_per_step(::FISTA) = (1,1)
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
2344
""" GAP """ mutable struct GAP <: FOSAlgorithm α::Float64 α1::Float64 α2::Float64 direct::Bool options end GAP(α=0.8, α1=1.8, α2=1.8; direct=false, kwargs...) = GAP(α, α1, α2, direct, kwargs) struct GAPData{T1,T2} <: FOSSolverData tmp1::Array{Float64,1} tmp2::Array{Float64,1} constinit::Base.RefValue{Bool} # If constant term has been calculated (linesearch feature) S1::T1 S2::T2 end function init_algorithm!(alg::GAP, model::AbstractFOSModel) S1, S2, n, status_generator = get_sets_and_status(alg, model) data = GAPData(Array{Float64,1}(undef, n), Array{Float64,1}(undef, n), Ref(false), S1, S2) return data, status_generator end function S1constant!(y, alg::GAP, data::GAPData, mem, i) if !data.constinit.x y .= 0.0 #TODO high accuracy? prox!(mem, S1, y) mem .= α1.*mem# .+ (1-α1).*0.0 data.constinit.x = true end y .= mem return end function S1!(y, alg::GAP, data::GAPData, x, i, status::AbstractStatus, longstep=nothing) α1, S1 = alg.α1, data.S1 prox!(y, S1, x) addprojeq(longstep, y, x) y .= α1.*y .+ (1-α1).*x end function S2!(y, alg::GAP, data::GAPData, x, i, status::AbstractStatus, longstep=nothing) α2, S2 = alg.α2, data.S2 prox!(y, S2, x) checkstatus(status, y) addprojineq(longstep, y, x) y .= α2.*y .+ (1-α2).*x end function Base.step(alg::GAP, data::GAPData, x, i, status::AbstractStatus, longstep=nothing) α = alg.α tmp1, tmp2 = data.tmp1, data.tmp2 # Relaxed projection onto S1 S1!(tmp1, alg, data, x, i, status, longstep) # α1, S1 = alg.α1, data.S1 # prox!(tmp1, S1, x) # addprojeq(longstep, tmp1, x) # tmp1 .= α1.*tmp1 .+ (1-α1).*x #Relaxed projection onto S2 S2!(tmp2, alg, data, tmp1, i, status, longstep) # α2, S2 = alg.α2, data.S2 # prox!(tmp2, S2, tmp1) # checkstatus(status, tmp2) # addprojineq(longstep, tmp2, tmp1) # tmp2 .= α2.*tmp2 .+ (1-α2).*tmp1 # Relaxation x .= α.*tmp2 .+ (1-α).*x return end function getsol(::GAP, data::GAPData, x) tmp1,tmp2,S1,S2 = data.tmp1,data.tmp2,data.S1,data.S2 prox!(tmp1, S1, x) prox!(tmp2, S2, tmp1) return tmp2 end support_linesearch(::GAP) = Val{:Fast} support_longstep(::GAP) = true projections_per_step(::GAP) = (1,1)
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
3403
""" `GAPA(α=1.0, β=0.0; kwargs...)`` GAP Adaptive Same as GAP but with adaptive `α1,α2` set to optimal `αopt=2/(1+sinθ)` according to the estimate of the Friedrischs angle `θ`. `β` is averaging factor between `αopt` and `2`: `α1=α2= (1-β)*αopt + β*2.0`. """ mutable struct GAPA <: FOSAlgorithm α::Float64 β::Float64 direct::Bool options end GAPA(α=1.0, β=0.0; direct=false, kwargs...) = GAPA(α, β, direct, kwargs) mutable struct GAPAData{T1,T2} <: FOSSolverData α12::Float64 tmp1::Array{Float64,1} tmp2::Array{Float64,1} constinit::Base.RefValue{Bool} # If constant term has been calculated (linesearch feature) S1::T1 S2::T2 end #GAPAData{T1,T2}(α12, tmp1, tmp2, S1::T1, S2::T2) = GAPAData{T1,T2}(α12, tmp1, tmp2, S1, S2) function init_algorithm!(alg::GAPA, model::AbstractFOSModel) S1, S2, n, status_generator = get_sets_and_status(alg, model) data = GAPAData(2.0, Array{Float64,1}(undef, n), Array{Float64,1}(undef, n), Ref(false), S1, S2) return data, status_generator end """ normedScalar(x1,x2,y1,y2) Calculate |<x1-x2,y1-y2>|/(||x1-x2||*||y1-y2||)""" function normedScalar(x1,x2,y1,y2) sum, norm1, norm2 = 0.0, 0.0, 0.0 #@inbounds @simd for i in 1:length(x1) d1 = x1[i] - x2[i] d2 = y1[i] - y2[i] sum += d1*d2 norm1 += d1^2 norm2 += d2^2 end return abs(sum)/sqrt(norm1*norm2) end function S1constant!(y, alg::GAPA, data::GAPAData, mem, i) α12 = data.α12 if !data.constinit.x y .= 0.0 #TODO high accuracy? prox!(mem, S1, y) data.constinit.x = true end y .= α12.*mem# .+ (1-α1).*0.0 return end function S1!(y, alg::GAPA, data::GAPAData, x, i, status::AbstractStatus, longstep=nothing) α12, S1 = data.α12, data.S1 prox!(y, S1, x) addprojeq(longstep, y, x) y .= α12.*y .+ (1-α12).*x end function S2!(y, alg::GAPA, data::GAPAData, x, i, status::AbstractStatus, longstep=nothing) α12, S2 = data.α12, data.S2 prox!(y, S2, x) checkstatus(status, y) addprojineq(longstep, y, x) y .= α12.*y .+ (1-α12).*x end function Base.step(alg::GAPA, data::GAPAData, x, i, status::AbstractStatus, longstep=nothing) α,β = alg.α,alg.β α12,tmp1,tmp2,S1,S2 = data.α12,data.tmp1,data.tmp2,data.S1,data.S2 # Relaxed projection onto S1 S1!(tmp1, alg, data, x, i, status, longstep) # prox!(tmp1, S1, x) # addprojeq(longstep, tmp1, x) # tmp1 .= α12.*tmp1 .+ (1-α12).*x # Relaxed projection onto S2 S2!(tmp2, alg, data, tmp1, i, status, longstep) # prox!(tmp2, S2, tmp1) # checkstatus(status, tmp2) # #println("α12: $α12") # addprojineq(longstep, tmp2, tmp1) # tmp2 .= α12.*tmp2 .+ (1-α12).*tmp1 #Calculate θ_F estimate, normedScalar(x1,x2,y1,y2) = |<x1-x2,y1-y2>|/(||x1-x2||*||y1-y2||) scl = clamp(normedScalar(tmp2,tmp1,tmp1,x), 0.0, 1.0) s = sqrt(1-scl^2) #Efficient way to sin(acos(scl)) # Update α1, α2 αopt = 2/(1+s) # α1,α2 = 2/(1+sin(Θ_F)) data.α12 = (1-β)*αopt + β*2.0 #Set output x .= α.*tmp2 .+ (1-α).*x return end function getsol(::GAPA, data::GAPAData, x) tmp1,tmp2,S1,S2 = data.tmp1,data.tmp2,data.S1,data.S2 prox!(tmp1, S1, x) prox!(tmp2, S2, tmp1) return tmp2 end support_longstep(::GAPA) = true projections_per_step(::GAPA) = (1,1) support_linesearch(::GAPA) = Val{:Fast}
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
2273
""" GAPP projected GAP Defaults to direct solve of the linear system """ mutable struct GAPP <: FOSAlgorithm α::Float64 α1::Float64 α2::Float64 iproj::Int64 direct::Bool options end GAPP(α=0.8, α1=1.8, α2=1.8; direct=true, iproj=100, kwargs...) = GAPP(α, α1, α2, iproj, direct, kwargs) struct GAPPData{T1,T2} <: FOSSolverData tmp1::Array{Float64,1} tmp2::Array{Float64,1} S1::T1 S2::T2 end function init_algorithm!(alg::GAPP, model::AbstractFOSModel) S1, S2, n, status_generator = get_sets_and_status(alg, model) data = GAPPData(Array{Float64,1}(undef, n), Array{Float64,1}(undef, n), S1, S2) return data, status_generator end function Base.step(alg::GAPP, data::GAPPData, x, i, status::AbstractStatus, longstep=nothing) α,α1,α2 = alg.α, alg.α1, alg.α2 tmp1,tmp2,S1,S2 = data.tmp1, data.tmp2, data.S1, data.S2 # Relaxed projection onto S1 prox!(tmp1, S1, x) if i % alg.iproj == 0 tmp3 = similar(tmp1) tmp4 = similar(tmp1) res = similar(tmp1) # Projection onto S2 prox!(tmp2, S2, tmp1) prox!(res, S1, tmp2) res .= res - tmp1 #res = Ps1*(Ps2*Ps1-I)x normbest = Inf αbest = -1.0 for k = 0:20 αtest = 2.0.^k tmp3 .= tmp1 .+ αtest.*res prox!(tmp4, S2, tmp3) normtest = norm(tmp4 - tmp3) println("normtest: $normtest") if normtest < normbest αbest = αtest normbest = normtest end end println("αbest: $αbest") tmp1 .= tmp1 .+ αbest.*res prox!(tmp2, S2, tmp1) checkstatus(status, tmp2) tmp2 .= α2.*tmp2 .+ (1-α2).*tmp1 x .= tmp2 else tmp1 .= α1.*tmp1 .+ (1-α1).*x # Relaxed projection onto S2 prox!(tmp2, S2, tmp1) checkstatus(status, tmp2) tmp2 .= α2.*tmp2 .+ (1-α2).*tmp1 # Relaxation x .= α.*tmp2 .+ (1-α).*x end return end function getsol(::GAPP, data::GAPPData, x) tmp1,tmp2,S1,S2 = data.tmp1,data.tmp2,data.S1,data.S2 prox!(tmp1, S1, x) prox!(tmp2, S2, tmp1) return tmp2 end support_longstep(alg::GAPP) = false projections_per_step(alg::GAPP) = (0,0)
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
292
export GAP, GAPA, GAPP, DR, AP, Dykstra, FISTA include("gap.jl") include("gapa.jl") include("gapproj.jl") include("dykstra.jl") include("fista.jl") #Some shortnames for common algorithms DR(α=0.5; kwargs...) = GAP(α, 2.0, 2.0; kwargs...) AP(α=1; kwargs...) = GAP(α, 1.0, 1.0; kwargs...)
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
4429
""" Representation of the matrix [I A'; A -I] """ struct KKTMatrix{T, M<:AbstractMatrix{T}} <: AbstractMatrix{T} A::M am::Int64 an::Int64 # TODO test and remove if not better # x1::SubArray{T,1,Array{T,1},Tuple{UnitRange{Int64}},true} # x2::SubArray{T,1,Array{T,1},Tuple{UnitRange{Int64}},true} # y1::SubArray{T,1,Array{T,1},Tuple{UnitRange{Int64}},true} # y2::SubArray{T,1,Array{T,1},Tuple{UnitRange{Int64}},true} end KKTMatrix(A::M) where {T, M<:AbstractMatrix{T}} = KKTMatrix{T,M}(A, size(A)...)#, # view([1.],1:1), view([1.],1:1), view([1.],1:1), view([1.],1:1)) # Alternative implementation with "constant" views # @inbounds function Base.A_mul_B!(y::AbstractVector{T}, M::KKTMatrix, x::AbstractVector{T}) where {T} # if M.x1.parent !== x || M.y1.parent !== y # M.x1 = view(x, 1:M.an ) # M.x2 = view(x, M.an+1:M.an+M.am) # M.y1 = view(y, 1:M.an ) # M.y2 = view(y, M.an+1:M.an+M.am) # #println("Update pointers") # end # # # [I A'; # # A -I] # At_mul_B!(M.y1, M.A, M.x2) # @blas! M.y1 += M.x1 # A_mul_B!(M.y2, M.A, M.x1) # @blas! M.y2 -= M.x2 # end @inbounds function mul!(y::AbstractVector{T}, M::KKTMatrix, x::AbstractVector{T}) where T x1 = view(x, 1:M.an ) x2 = view(x, M.an+1:M.an+M.am) y1 = view(y, 1:M.an ) y2 = view(y, M.an+1:M.an+M.am) # [I A'; # A -I] mul!(y1, transpose(M.A), x2) y1 .+= x1 mul!(y2, M.A, x1) y2 .-= x2 end #Assuming we don't introduce scaling ρ mul!(y::AbstractVector{T}, M::Transpose{T, MType}, x::AbstractVector{T}) where {T, MType<:KKTMatrix} = mul!(y, M.parent, x) """ Representation of the function `f([x;z]) = q'x+i(Ax-βz==b)` where `β` is `1` or `-1`. """ mutable struct AffinePlusLinear{T,M<:AbstractMatrix{T}} <: ProximalOperators.ProximableFunction M::KKTMatrix{T,M} A::M β::Int64 b::Array{Float64,1} q::Array{Float64,1} rhs::Array{Float64,1} decreasing_accuracy::Bool i::Int64 #Count for number of calls, descides the tolerance cgiter::Int64 #How many iterarions CG did last time cgdata::CGdata{Float64} end function AffinePlusLinear(A::M, b, q, β; decreasing_accuracy=false) where {T,M<:AbstractMatrix{T}} am, an = size(A) @assert β == 1 || β == -1 #Initiate second half of rhs, maybe without view? rhs = Array{T}(undef, am+an) rhs2 = view(rhs, (1+an):(am+an)) rhs2 .= b return AffinePlusLinear{T,M}(KKTMatrix(A), A, β, b, q, rhs, decreasing_accuracy, 1, 0, CGdata(length(rhs))) end getcgiter(S::AffinePlusLinear) = S.cgiter function prox!(y::AbstractArray, S::AffinePlusLinear, x::AbstractArray) #x2 = (2π-I)v or similar #[x;z] ∈ R(n×m) an = S.M.an am = S.M.am rhs1 = view(S.rhs, 1:an) x1 = view(x, 1:an) x2 = view(x, (an+1):(an+am)) y2 = view(y, (an+1):(an+am)) #Build rhs, rhs2 already contains b β = S.β mul!(rhs1, transpose(S.A), x2) rhs1 .= β.*rhs1 .+ x1 .- S.q #Now rhs = [x-q+β*A'z; b] #Do CG to solve M*[y1;y2] = rhs #Initial guess: cgdata = S.cgdata if cgdata.firstrun.x # has this been initialized? (pointer) cgdata.xinit .= x #Works as guess since M square cgdata.firstrun.x = false end #Since y is the initial guess, use previous solution y .= cgdata.xinit #Now run CG tol = if S.decreasing_accuracy max(0.2^sqrt(S.i), size(S.A,2)*eps()) else size(S.A,2)*eps() end #println(tol) S.i += 1 max_iters = 1000 #TODO Verify that CG can solve this problem correctly iter = conjugategradient!(y, S.M, S.rhs, cgdata.r, cgdata.p, cgdata.z, tol = tol, max_iters = max_iters) iter == max_iters && @warn "CG reached max iterations, result may be inaccurate" S.cgiter = iter cgdata.xinit .= y #Save initial guess for next prox! #Now scale y2 with beta β y2 .*= β return 0.0 end # A = [Ã -b; # 0 1] # [A -I][x;xn;z;zn] = 0 # # [Ã -I][x;z] -b*xn = 0 # [Ã -I][x;z] = b #OK # xn-zn=0 # # A' = [ Ã' 0; # -b' 1] # # hn=1? # x̃n - xn -b'(z̃ - h) + 1(z̃n-hn) = 0 # [1 -b'][x̃n; z̃]=xn-b'h # b'*x̃ = b'*h #Maybe needed? # # #So: # [I Ã'][x̃;z̃] = [-q+x+Ã'h] # [b' 0][x̃;z̃] = [b'*h] # #Complete system: # [Ã -I ; = [b ; # [I Ã'; = -q+x+Ã'h; # [b' 0 ] = b'h ]
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
1589
struct CGdata{T} r::Array{T,1} p::Array{T,1} z::Array{T,1} xinit::Array{T,1}#TODO remove this firstrun::Base.RefValue{Bool} end CGdata(r::AbstractArray{T},p::AbstractArray{T},z::AbstractArray{T}) where T = CGdata{T}(r,p,z, T[], Ref(true)) CGdata(size) = CGdata{Float64}(Array{Float64,1}(undef, size), Array{Float64,1}(undef, size), Array{Float64,1}(undef, size), Array{Float64,1}(undef, size), Ref(true)) function conjugategradient!(x,A,b; useasinitial=true) cgdata = CGdata(similar(b), similar(b), similar(b)) if !useasinitial x .= 1.0 end conjugategradient!(x, A, b, cgdata.r, cgdata.p, cgdata.z) return cgdata end """ `conjugategradient!(x,A,b,r,p,Ap; tol = size(A,2)*eps(), max_iters = 10000)` Solve `A*x==b` with the conjugate gradient method. Uses `x` as warm start and stores solution in `x`. `r`,`p`,`Ap` should be same size as `x` and will be changed. Implemented as in "Matrix Compuatations" 2nd edition, Golub and Van Loan (1989) """ function conjugategradient!(x,A,b,r,p,Ap; tol = size(A,2)*eps(), max_iters = 10000) mul!(Ap, A, x) r .= b .- Ap p .= r rn = dot(r,r) iter = 1 while true mul!(Ap, A, p) α = rn/dot(Ap,p) x .+= α.*p r .-= α.*Ap if norm(r) <= tol || iter >= max_iters break end rnold = rn rn = dot(r,r) β = rn/rnold #p .= r .+ β.*p p .*= β p .+= r iter += 1 end iter == max_iters && @warn "CG reached max iterations, result may be inaccurate" return iter end
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
3090
export LineSearchWrapper mutable struct LineSearchWrapper{T<:FOSAlgorithm} <: FOSAlgorithm lsinterval::Int64 alg::T options end mutable struct LineSearchWrapperData{T<:FOSSolverData} <: FOSSolverData lsinterval::Int64 tmp1::Array{Float64,1} tmp2::Array{Float64,1} tmp3::Array{Float64,1} mem::Array{Float64,1} res::Array{Float64,1} algdata::T end function LineSearchWrapper(alg::T; lsinterval=100, kwargs...) where T if support_linesearch(alg) == Val{:False} @error "Algorithm $T does not support line search" end LineSearchWrapper{T}(lsinterval, alg, [kwargs;alg.options]) end function init_algorithm!(ls::LineSearchWrapper, model::FOSMathProgModel) alg, lsinterval = ls.alg, ls.lsinterval algdata, status = init_algorithm!(alg, model) x = getinitialvalue(model, alg, algdata) data = LineSearchWrapperData(lsinterval, similar(x), similar(x), similar(x), similar(x), similar(x), algdata) return data, status end #getmn(data::LineSearchWrapperData) = getmn(data.algdata) function Base.step(wrap::LineSearchWrapper, lsdata::LineSearchWrapperData, x, i, status::AbstractStatus, longstep=nothing) lsinterval, tmp1, tmp2, tmp3, mem, res = lsdata.lsinterval, lsdata.tmp1, lsdata.tmp2, lsdata.tmp3, lsdata.mem, lsdata.res do_linesearch = i % lsinterval == 0 if do_linesearch #Should we do ls? tmp1 .= x #step(wrap.alg, lsdata.algdata, x, i, status, nothing) #S1constant!(f0, wrap.alg, lsdata.algdata, mem, i) S1!(tmp2, wrap.alg, lsdata.algdata, x, i, status, nothing) S2!(x, wrap.alg, lsdata.algdata, tmp2, i, status, nothing) nostatus = NoStatus(:Continue) res .= x .- tmp1 normres = norm(res) println("test, $normres") k = 1 normresbest = Inf αbest = 1.0 α = 0.1 for k = 0:30 α = α*1.8 x .= tmp1 .+ α.*res #testres = get_normres!(wrap, lsdata, x, i, nostatus) S1!(tmp2, wrap.alg, lsdata.algdata, x, i, nostatus, nothing) S2!(tmp3, wrap.alg, lsdata.algdata, tmp2, i, nostatus, nothing) testres = normdiff(x,tmp3) println("α: $α, $testres") if testres < normresbest normresbest = testres αbest = α end end println("α: $αbest") x .= tmp1 .+ αbest.*res else step(wrap.alg, lsdata.algdata, x, i, status, longstep) end end function normdiff(x::T,y::T) where T<:StridedVector nx, ny = length(x), length(y) s = 0.0 @assert nx == ny for j = 1:nx s += abs2(x[j]-y[j]) end return sqrt(s) end function get_normres!(wrap::LineSearchWrapper, lsdata::LineSearchWrapperData, x, i, status::AbstractStatus) lsdata.tmp2 .= x step(wrap.alg, lsdata.algdata, x, i, status, nothing) #If time to do lsdata normres = normdiff(x,lsdata.tmp2) end function getsol(alg::LineSearchWrapper, data::LineSearchWrapperData, x) getsol(alg.alg, data.algdata, x) end
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git
[ "MIT" ]
0.2.0
b887fff9ad1cadd1e324fd0cf0ad502cd45501c0
code
3314
export LongstepWrapper include("saveplanes.jl") mutable struct LongstepWrapper{T<:FOSAlgorithm} <: FOSAlgorithm longinterval::Int64 nsave::Int64 alg::T options end mutable struct LongstepWrapperData{T<:FOSSolverData} <: FOSSolverData longinterval::Int64 nsave::Int64 saved::SavedPlanes{Float64} saveineq::Bool savepos::Int64 eqi::Int64 uneqi::Int64 tmp::Array{Float64,1} algdata::T end function LongstepWrapper(alg::T; longinterval=100, nsave=10, kwargs...) where T LongstepWrapper{T}(longinterval, nsave, alg, [kwargs...,alg.options...]) end function init_algorithm!(long::LongstepWrapper, model::FOSMathProgModel) alg, longinterval, nsave = long.alg, long.longinterval, long.nsave !support_longstep(alg) && @error "Algorithm alg does not support longstep" data, status_generator = init_algorithm!(alg, model) neq, nineq = projections_per_step(alg) #TODO x x = getinitialvalue(model) saved = SavedPlanes(x, nsave, neq, nineq) # TODO Fix case with saveineq=false data = LongstepWrapperData(longinterval, nsave, saved, true, 0, 1, 1, similar(x), data) return data, status_generator end getmn(data::LongstepWrapperData) = getmn(data.algdata) function Base.step(wrap::LongstepWrapper, longstep::LongstepWrapperData, x, i, status::AbstractStatus) nsave, longinterval = longstep.nsave, longstep.longinterval #println("At iteration $i") savepos = (i-1)%longinterval - longinterval + nsave + 2 # Index of collection to save #println("savepos: $savepos") if 0 < savepos #Should we start saving collections? longstep.savepos = savepos longstep.eqi, longstep.uneqi = 0, 0 end step(wrap.alg, longstep.algdata, x, i, status, longstep) #If time to do longstep if longstep.savepos == nsave+1 #println("Doing projection!") fail = projectonnormals!(longstep.saved, x, longstep.tmp) longstep.savepos = -1 x .= longstep.tmp end end function getsol(alg::LongstepWrapper, data::LongstepWrapperData, x) getsol(alg.alg, data.algdata, x) end getcgiter(data::LongstepWrapperData) = getcgiter(data.algdata) addprojeq(::Nothing, ::Any, ::Any) = nothing addprojineq(::Nothing, ::Any, ::Any) = nothing function addprojeq(long::T, y, x) where T<:LongstepWrapperData if long.savepos > 0 #println("adding EQ, nsave: $(long.nsave) i:$(long.i) eqi:$(long.eqi) uneqi:$(long.uneqi)") s = long.saved i = (long.savepos-1)*(s.neq + s.nineq*long.saveineq) + long.eqi + 1 s.A[i,:] .= x .- y b = 0.0 for j = 1:length(x) b += (x[j]-y[j])*y[j] end s.b[i] = b long.eqi += 1 end return end """Saves inequalities as equality for now""" function addprojineq(long::T, y, x) where T<:LongstepWrapperData if long.savepos > 0 && (long.saveineq || long.savepos == long.nsave+1) #println("adding inEQ, nsave: $(long.nsave) i:$(long.i) eqi:$(long.eqi) uneqi:$(long.uneqi)") s = long.saved i = (long.savepos-1)*(s.neq + s.nineq*long.saveineq) + long.eqi + long.uneqi + 1 s.A[i,:] .= x .- y b = 0.0 for j = 1:length(x) b += (x[j]-y[j])*y[j] end s.b[i] = b long.uneqi += 1 end end
FirstOrderSolvers
https://github.com/mfalt/FirstOrderSolvers.jl.git