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.1
10c04258080b378ecf9b81b6739206eca3f63535
code
3301
""" ``` struct InpStiffness{dim, N, TF, TI, TBool, Tch <: ConstraintHandler, GO, TInds <: AbstractVector{TI}, TMeta<:Metadata} <: StiffnessTopOptProblem{dim, TF} inp_content::InpContent{dim, TF, N, TI} geom_order::Type{Val{GO}} ch::Tch black::TBool white::TBool varind::TInds metadata::TMeta end ``` - `dim`: dimension of the problem - `TF`: number type for computations and coordinates - `N`: number of nodes in a cell of the grid - `inp_content`: an instance of [`InpContent`](@ref) which stores all the information from the ``.inp` file. - `geom_order`: a field equal to `Val{GO}` where `GO` is an integer representing the order of the finite elements. Linear elements have a `geom_order` of `Val{1}` and quadratic elements have a `geom_order` of `Val{2}`. - `metadata`: Metadata having various cell-node-dof relationships - `black`: a `BitVector` of length equal to the number of elements where `black[e]` is 1 iff the `e`^th element must be part of the final design - `white`: a `BitVector` of length equal to the number of elements where `white[e]` is 1 iff the `e`^th element must not be part of the final design - `varind`: an `AbstractVector{Int}` of length equal to the number of elements where `varind[e]` gives the index of the decision variable corresponding to element `e`. Because some elements can be fixed to be black or white, not every element has a decision variable associated. """ struct InpStiffness{dim, N, TF, TI, TBool, Tch <: ConstraintHandler, GO, TInds <: AbstractVector{TI}, TMeta<:Metadata} <: StiffnessTopOptProblem{dim, TF} inp_content::InpContent{dim, TF, N, TI} geom_order::Type{Val{GO}} ch::Tch black::TBool white::TBool varind::TInds metadata::TMeta end """ InpStiffness(filepath::AbstractString; keep_load_cells = false) Imports stiffness problem from a .inp file, e.g. `InpStiffness("example.inp")`. The `keep_load_cells` keyword argument will enforce that any cell with a load applied on it is to be part of the final optimal design generated by topology optimization algorithms. """ function InpStiffness(filepath_with_ext::AbstractString; keep_load_cells = false) problem = Parser.extract_inp(filepath_with_ext) return InpStiffness(problem; keep_load_cells = keep_load_cells) end function InpStiffness(problem::Parser.InpContent; keep_load_cells = false) ch = Parser.inp_to_ferrite(problem) black, white = find_black_and_white(ch.dh) metadata = Metadata(ch.dh) geom_order = Ferrite.getorder(ch.dh.field_interpolations[1]) if keep_load_cells for k in keys(problem.cloads) for (c, f) in metadata.node_cells[k] black[c] = 1 end end end varind = find_varind(black, white) return InpStiffness(problem, Val{geom_order}, ch, black, white, varind, metadata) end getE(p::InpStiffness) = p.inp_content.E getν(p::InpStiffness) = p.inp_content.ν nnodespercell(::InpStiffness{dim, N}) where {dim, N} = N getgeomorder(p::InpStiffness{<:Any, <:Any, <:Any, <:Any, <:Any, <:Any, GO}) where {GO} = GO getdensity(p::InpStiffness) = p.inp_content.density getpressuredict(p::InpStiffness) = p.inp_content.dloads getcloaddict(p::InpStiffness) = p.inp_content.cloads getfacesets(p::InpStiffness) = p.inp_content.facesets
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
5451
module Parser using Ferrite, SparseArrays export extract_inp, InpContent """ ``` struct InpContent{dim, TF, N, TI} node_coords::Vector{NTuple{dim,TF}} celltype::String cells::Vector{NTuple{N,TI}} nodesets::Dict{String,Vector{TI}} cellsets::Dict{String,Vector{TI}} E::TF ν::TF density::TF nodedbcs::Dict{String, Vector{Tuple{TI,TF}}} cloads::Dict{Int, Vector{TF}} facesets::Dict{String, Vector{Tuple{TI,TI}}} dloads::Dict{String, TF} end ``` - `node_coords`: a vector of node coordinates. - `celltype`: a cell type code in the INP convention - `cells`: a vector of cell connectivities - `nodesets`: a dictionary mapping a node set name to a vector of node indices - `cellsets`: a dictionary mapping a cell set name to a vector of cell indices - `E`: Young's modulus - `ν`: Poisson ratio - `density`: physical density of the material - `nodedbcs`: a dictionary mapping a node set name to a vector of tuples of type `Tuple{Int, Float64}` specifying a Dirichlet boundary condition on that node set. Each tuple in the vector specifies the local index of a constrained degree of freedom and its fixed value. A 3-dimensional field has 3 degrees of freedom per node for example. So the index can be 1, 2 or 3. - `cloads`: a dictionary mapping a node index to a load vector on that node. - `facesets`: a dictionary mapping a face set name to a vector of `Tuple{Int,Int}` tuples where each tuple is a face index. The first integer is the cell index where the face is and the second integer is the local face index in the cell according to the VTK convention. - `dloads`: a dictionary of distributed loads mapping face set names to a normal traction load value. """ struct InpContent{dim, TF, N, TI} node_coords::Vector{NTuple{dim,TF}} celltype::String cells::Vector{NTuple{N,TI}} nodesets::Dict{String,Vector{TI}} cellsets::Dict{String,Vector{TI}} E::TF ν::TF density::TF nodedbcs::Dict{String, Vector{Tuple{TI,TF}}} cloads::Dict{Int, Vector{TF}} facesets::Dict{String, Vector{Tuple{TI,TI}}} dloads::Dict{String, TF} end const stopping_pattern = r"^\*[^\*]" # Import include(joinpath("FeatureExtractors", "extract_cells.jl")) include(joinpath("FeatureExtractors", "extract_cload.jl")) include(joinpath("FeatureExtractors", "extract_dbcs.jl")) include(joinpath("FeatureExtractors", "extract_dload.jl")) include(joinpath("FeatureExtractors", "extract_material.jl")) include(joinpath("FeatureExtractors", "extract_nodes.jl")) include(joinpath("FeatureExtractors", "extract_set.jl")) include(joinpath("inp_to_ferrite.jl")) function extract_inp(filepath_with_ext) file = open(filepath_with_ext, "r") local node_coords local celltype, cells, offset nodesets = Dict{String,Vector{Int}}() cellsets = Dict{String,Vector{Int}}() local E, mu nodedbcs = Dict{String, Vector{Tuple{Int,Float64}}}() cloads = Dict{Int, Vector{Float64}}() facesets = Dict{String, Vector{Tuple{Int,Int}}}() dloads = Dict{String, Float64}() density = 0. # Should extract from the file node_heading_pattern = r"\*Node\s*,\s*NSET\s*=\s*([^,]*)" cell_heading_pattern = r"\*Element\s*,\s*TYPE\s*=\s*([^,]*)\s*,\s*ELSET\s*=\s*([^,]*)" nodeset_heading_pattern = r"\*NSET\s*,\s*NSET\s*=\s*([^,]*)" cellset_heading_pattern = r"\*ELSET\s*,\s*ELSET\s*=\s*([^,]*)" material_heading_pattern = r"\*MATERIAL\s*,\s*NAME\s*=\s*([^\s]*)" boundary_heading_pattern = r"\*BOUNDARY" cload_heading_pattern = r"\*CLOAD" dload_heading_pattern = r"\*DLOAD" line = readline(file) local dim while !eof(file) m = match(node_heading_pattern, line) if m != nothing && m[1] == "Nall" node_coords, line = extract_nodes(file) dim = length(node_coords[1]) continue end m = match(cell_heading_pattern, line) if m != nothing celltype = String(m[1]) cellsetname = String(m[2]) cells, offset, line = extract_cells(file) cellsets[cellsetname] = collect(1:length(cells)) continue end m = match(nodeset_heading_pattern, line) if m != nothing nodesetname = String(m[1]) line = extract_set!(nodesets, nodesetname, file) continue end m = match(cellset_heading_pattern, line) if m != nothing cellsetname = String(m[1]) line = extract_set!(cellsets, cellsetname, file, offset) continue end m = match(material_heading_pattern, line) if m != nothing material_name = String(m[1]) E, mu, line = extract_material(file) continue end m = match(boundary_heading_pattern, line) if m != nothing line = extract_nodedbcs!(nodedbcs, file) continue end m = match(cload_heading_pattern, line) if m != nothing line = extract_cload!(cloads, file, Val{dim}) continue end m = match(dload_heading_pattern, line) if m != nothing line = extract_dload!(dloads, facesets, file, Val{dim}, offset) continue end line = readline(file) end close(file) return InpContent(node_coords, celltype, cells, nodesets, cellsets, E, mu, density, nodedbcs, cloads, facesets, dloads) end end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
4207
function inpcelltype(::Type{CT}) where CT if CT === Triangle return "CPS3" elseif CT === QuadraticTriangle return "CPS6" elseif CT === Tetrahedron return "C3D4" elseif CT === QuadraticTetrahedron return "C3D10" elseif CT === Quadrilateral return "CPS4" elseif CT === QuadraticQuadrilateral return "CPS8" elseif CT === Hexahedron return "C3D8" elseif CT === QuadraticHexahedron return "C3D20" else return "" end end function import_inp(filepath_with_ext) problem = extract_inp(filepath_with_ext) return inp_to_ferrite(problem) end function inp_to_ferrite(problem::InpContent) _celltype = problem.celltype if _celltype == "CPS3" # Linear triangle celltype = Triangle geom_order = 1 refshape = RefTetrahedron dim = 2 elseif _celltype == "CPS6" # Quadratic triangle celltype = QuadraticTriangle geom_order = 2 refshape = RefTetrahedron dim = 2 elseif _celltype == "C3D4" # Linear tetrahedron celltype = Tetrahedron geom_order = 1 refshape = RefTetrahedron dim = 3 elseif _celltype == "C3D10" # Quadratic tetrahedron celltype = QuadraticTetrahedron geom_order = 2 refshape = RefTetrahedron dim = 3 elseif _celltype == "CPS4" # Linear quadrilateral celltype = Quadrilateral geom_order = 1 refshape = RefCube dim = 2 elseif _celltype == "CPS8" || _celltype == "CPS8R" # Quadratic quadrilateral celltype = QuadraticQuadrilateral geom_order = 2 refshape = RefCube dim = 2 elseif _celltype == "C3D8" || _celltype == "C3D8R" # Linear hexahedron celltype = Hexahedron geom_order = 1 refshape = RefCube dim = 3 elseif _celltype == "C3D20" || _celltype == "C3D20R" # Quadratic hexahedron celltype = QuadraticHexahedron geom_order = 2 refshape = RefCube dim = 3 #elseif _celltype == "C3D6" # Linear wedge #elseif _celltype == "C3D15" # Quadratic wedge else throw("Unsupported cell type $_celltype.") end cells = celltype.(problem.cells) nodes = Node.(problem.node_coords) grid = Grid(cells, nodes) for k in keys(problem.cellsets) grid.cellsets[k] = Set(problem.cellsets[k]) end for k in keys(problem.nodesets) grid.nodesets[k] = Set(problem.nodesets[k]) end for k in keys(problem.facesets) grid.facesets[k] = Set(problem.facesets[k]) end # Define boundary faces grid.boundary_matrix = extract_boundary_matrix(grid); dh = DofHandler(grid) # Isoparametric field_interpolation = Lagrange{dim, refshape, geom_order}() push!(dh, :u, dim, field_interpolation) close!(dh) ch = ConstraintHandler(dh) for k in keys(problem.nodedbcs) vec = problem.nodedbcs[k] f(x, t) = [vec[i][2] for i in 1:length(vec)] components = [vec[i][1] for i in 1:length(vec)] dbc = Dirichlet(:u, getnodeset(grid, k), f, components) add!(ch, dbc) close!(ch) update!(ch, 0.0) end return ch end function extract_boundary_matrix(grid::Grid{dim}) where dim nfaces = length(Ferrite.faces(grid.cells[1])) ncells = length(grid.cells) countedbefore = Dict{NTuple{dim,Int},Bool}() boundary_matrix = ones(Bool, nfaces, ncells) # Assume all are boundary faces for (ci, cell) in enumerate(getcells(grid)) for (fi, face) in enumerate(Ferrite.faces(cell)) sface = Ferrite.sortface(face) # TODO: faces(cell) may as well just return the sorted list token = Base.ht_keyindex2!(countedbefore, sface) if token > 0 # haskey(countedbefore, sface) boundary_matrix[fi, ci] = 0 else # distribute new dofs Base._setindex!(countedbefore, true, sface, -token)# countedbefore[sface] = true, mark the face as counted end end end sparse(boundary_matrix) end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
1445
function extract_cells(file, ::Type{TI}=Int) where TI line = readline(file) cell_idx_pattern = r"^(\d+)\s*," m = match(cell_idx_pattern, line) first_cell_idx = parse(TI, m[1]) node_idx_pattern = r",\s*(\d+)" local cells nodes = TI[] for m in eachmatch(node_idx_pattern, line) push!(nodes, parse(TI, m[1])) end cells = [Tuple(nodes)] nextline = _extract_cells!(cells, file, first_cell_idx) return cells, first_cell_idx-TI(1), nextline end function _extract_cells!(cells::AbstractVector{NTuple{nnodes, TI}}, file, prev_cell_idx::TI) where {nnodes, TI} cell_idx_pattern = r"^(\d+)\s*," node_idx_pattern = r",\s*(\d+)" nodes = zeros(TI, nnodes) line = readline(file) m = match(stopping_pattern, line) while m isa Nothing m = match(cell_idx_pattern, line) if m != nothing cell_idx = parse(TI, m[1]) cell_idx == prev_cell_idx + TI(1) || throw("Cell indices are not consecutive.") nodes .= zero(TI) for (i, m) in enumerate(eachmatch(node_idx_pattern, line)) nodes[i] = parse(TI, m[1]) end all(nodes .!= zero(TI)) || throw("Cell $cell_idx has fewer nodes than it should.") push!(cells, Tuple(nodes)) prev_cell_idx = cell_idx end line = readline(file) m = match(stopping_pattern, line) end return line end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
739
function extract_cload!(cloads::Dict{TI, Vector{TF}}, file, ::Type{Val{dim}}) where {TI, TF, dim} pattern = r"(\d+)\s*,\s*(\d)\s*,\s*(\-?\d+\.\d*E[\+\-]\d{2})" line = readline(file) m = match(stopping_pattern, line) while m isa Nothing m = match(pattern, line) if m != nothing nodeidx = parse(TI, m[1]) dof = parse(Int, m[2]) load = parse(TF, m[3]) if haskey(cloads, nodeidx) cloads[nodeidx][dof] += load else cloads[nodeidx] = zeros(TF, dim) cloads[nodeidx][dof] = load end end line = readline(file) m = match(stopping_pattern, line) end return line end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
2242
function extract_nodedbcs!(node_dbcs::Dict{String, Vector{Tuple{TI,TF}}}, file) where {TI, TF} pattern_zero = r"([^,]+)\s*,\s*(\d)" pattern_range = r"([^,]+)\s*,\s*(\d)\s*,\s*(\d)" pattern_other = r"([^,]+)\s*,\s*(\d)\s*,\s*(\d)\s*,\s*(\-?\d+\.\d*)" line = readline(file) m = match(stopping_pattern, line) while m isa Nothing m = match(pattern_other, line) if m != nothing nodesetname = m[1] dof1 = parse(TI, m[2]) dof2 = parse(TI, m[3]) val = parse(TF, m[4]) if haskey(node_dbcs, nodesetname) for dof in dof1:dof2 push!(node_dbcs[nodesetname], (dof, val)) end else node_dbcs[nodesetname] = [(dof1, val)] for dof in dof1+1:dof2 push!(node_dbcs[nodesetname], (dof, val)) end end line = readline(file) m = match(stopping_pattern, line) continue end m = match(pattern_range, line) if m != nothing nodesetname = m[1] dof1 = parse(TI, m[2]) dof2 = parse(TI, m[3]) if haskey(node_dbcs, nodesetname) for dof in dof1:dof2 push!(node_dbcs[nodesetname], (dof, zero(TF))) end else node_dbcs[nodesetname] = [(dof1, zero(TF))] for dof in dof1+1:dof2 push!(node_dbcs[nodesetname], (dof, zero(TF))) end end line = readline(file) m = match(stopping_pattern, line) continue end m = match(pattern_zero, line) if m != nothing nodesetname = m[1] dof = parse(TI, m[2]) if haskey(node_dbcs, nodesetname) push!(node_dbcs[nodesetname], (dof, zero(TF))) else node_dbcs[nodesetname] = [(dof, zero(TF))] end line = readline(file) m = match(stopping_pattern, line) continue end line = readline(file) m = match(stopping_pattern, line) end return line end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
1362
function extract_dload!(dloads::Dict{String, TF}, facesets::Dict{String, Vector{Tuple{TI,TI}}}, file, ::Type{Val{dim}}, offset::TI) where {TI, TF, dim} pattern = r"(\d+)\s*,\s*P(\d+)\s*,\s*(\-?\d+\.\d*)" dload_heading_pattern = r"\*DLOAD" faceset_name = "DLOAD_SET_$(length(dloads)+1)" facesets[faceset_name] = Tuple{TI,TI}[] first = true prevload = zero(TF) load = zero(TF) line = readline(file) m = match(stopping_pattern, line) while m isa Nothing m = match(dload_heading_pattern, line) if m != nothing dloads[faceset_name] = load first = true faceset_name = "DLOAD_SET_$(length(dloads)+1)" facesets[faceset_name] = Tuple{TI,TI}[] end m = match(pattern, line) if m != nothing cellidx = parse(TI, m[1]) - offset faceidx = parse(TI, m[2]) load = parse(TF, m[3]) if !first && prevload != load throw("Loads in the same DLOAD set are not equal.") end prevload = load if first first = false end push!(facesets[faceset_name], (cellidx, faceidx)) end line = readline(file) m = match(stopping_pattern, line) end dloads[faceset_name] = load return line end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
529
function extract_material(file, ::Type{TF}=Float64) where TF elastic_heading_pattern = r"\*ELASTIC" Emu_pattern = r"(-?\d+\.?\d*)\s*,\s*(-?\d+\.?\d*)" line = readline(file) m = match(elastic_heading_pattern, line) if m != nothing line = readline(file) m = match(Emu_pattern, line) if m != nothing E = parse(TF, m[1]) mu = parse(TF, m[2]) end else throw("Material not supported.") end line = readline(file) return E, mu, line end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
1786
function extract_nodes(file, ::Type{TF}=Float64, ::Type{TI}=Int) where {TF, TI} line = readline(file) pattern = r"(\d+)\s*,\s*(-?\d+\.?\d*(e[-\+]?\d*)?)\s*,\s*(-?\d+\.?\d*(e[-\+]?\d*)?)\s*(,\s*(-?\d+\.?\d*(e[-\+]?\d*)?))?" m = match(pattern, line) first_node_idx = parse(TI, m[1]) first_node_idx == TI(1) || throw("First node index is not 1.") if m[6] isa Nothing node_coords = [(parse(TF, m[2]), parse(TF, m[4]))] nextline = _extract_nodes!(node_coords, file, TI(1)) else node_coords = [(parse(TF, m[2]), parse(TF, m[4]), parse(TF, m[7]))] nextline = _extract_nodes!(node_coords, file, TI(1)) end return node_coords, nextline end function _extract_nodes!(node_coords::AbstractVector{NTuple{dim, TF}}, file, prev_node_idx::TI) where {dim, TF, TI} if dim === 2 pattern = r"(\d+)\s*,\s*(-?\d+\.?\d*(e[-\+]?\d*)?)\s*,\s*(-?\d+\.?\d*(e[-\+]?\d*)?)" elseif dim === 3 pattern = r"(\d+)\s*,\s*(-?\d+\.?\d*(e[-\+]?\d*)?)\s*,\s*(-?\d+\.?\d*(e[-\+]?\d*)?)\s*,\s*(-?\d+\.?\d*(e[-\+]?\d*)?)" else error("Dimension is not supported.") end line = readline(file) m = match(stopping_pattern, line) while m isa Nothing m = match(pattern, line) if m != nothing node_idx = parse(Int, m[1]) node_idx == prev_node_idx + TI(1) || throw("Node indices are not consecutive.") if dim === 2 push!(node_coords, (parse(TF, m[2]), parse(TF, m[4]))) else push!(node_coords, (parse(TF, m[2]), parse(TF, m[4]), parse(TF, m[6]))) end prev_node_idx = node_idx end line = readline(file) m = match(stopping_pattern, line) end return line end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
819
function extract_set!(sets::Dict{String, TV}, setname::AbstractString, file, offset=0) where {TI, TV<:AbstractVector{TI}} sets[setname] = Int[] vector = sets[setname] pattern_single = r"^(\d+)" pattern_subset = r"^([^,]+)" line = readline(file) m = match(stopping_pattern, line) while m isa Nothing m = match(pattern_single, line) if m != nothing push!(vector, parse(TI, m[1])-offset) else m = match(pattern_subset, line) if m != nothing subsetname = String(m[1]) if haskey(sets, subsetname) append!(vector, sets[subsetname]) end end end line = readline(file) m = match(stopping_pattern, line) end return line end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
816
module Utilities using ForwardDiff, Ferrite, IterativeSolvers, Requires export AbstractPenalty, PowerPenalty, RationalPenalty, HeavisideProjection, SigmoidProjection, ProjectedPenalty, setpenalty, TopOptTrace, RaggedArray, @debug, compliance, meandiag, density, find_black_and_white, find_varind, YoungsModulus, PoissonRatio, getpenalty, getprevpenalty, setpenalty!, getsolver, @params, @forward_property function getpenalty end function getprevpenalty end function setpenalty! end getsolver(f) = f.solver # Utilities include("utils.jl") # Trace definition include("traces.jl") # Penalty definitions include("penalties.jl") end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
1183
using ..CUDASupport using ..TopOpt: @init_cuda, CPU, GPU @init_cuda() import ..TopOpt: whichdevice using ..GPUUtils, ForwardDiff abstract type AbstractGPUPenalty{T} <: AbstractPenalty{T} end whichdevice(::AbstractCPUPenalty) = CPU() whichdevice(::AbstractGPUPenalty) = GPU() CUDAnative.pow(d::TD, p::AbstractFloat) where {T, TV, TD <: ForwardDiff.Dual{T, TV, 1}} = ForwardDiff.Dual{T}(CUDAnative.pow(d.value, p), p * d.partials[1] * CUDAnative.pow(d.value, p - 1)) struct GPUPowerPenalty{T} <: AbstractGPUPenalty{T} p::T end @inline (P::GPUPowerPenalty)(x) = CUDAnative.pow(x, P.p) struct GPURationalPenalty{T} <: AbstractGPUPenalty{T} p::T end @inline (P::GPURationalPenalty)(x) = x / (1 + R.p * (1 - x)) struct GPUSinhPenalty{T} <: AbstractGPUPenalty{T} p::T end @inline (P::GPUSinhPenalty)(x) = CUDAnative.sinh(R.p*x)/CUDAnative.sinh(R.p) for T in (:PowerPenalty, :RationalPenalty) fname = Symbol(:GPU, T) @eval @inline CuArrays.cu(p::$T) = $fname(p.p) end CuArrays.cu(p::AbstractGPUPenalty) = p @define_cu(IterativeSolvers.CGStateVariables, :u, :r, :c) whichdevice(ra::RaggedArray) = whichdevice(ra.offsets) @define_cu(RaggedArray, :offsets, :values)
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
1578
abstract type AbstractPenalty{T} end abstract type AbstractCPUPenalty{T} <: AbstractPenalty{T} end abstract type AbstractProjection end mutable struct PowerPenalty{T} <: AbstractCPUPenalty{T} p::T end @inline (P::PowerPenalty)(x) = x^(P.p) mutable struct RationalPenalty{T} <: AbstractCPUPenalty{T} p::T end @inline (R::RationalPenalty)(x) = x / (1 + R.p * (1 - x)) mutable struct SinhPenalty{T} <: AbstractCPUPenalty{T} p::T end @inline (R::SinhPenalty)(x) = sinh(R.p*x)/sinh(R.p) struct ProjectedPenalty{T, Tpen <: AbstractPenalty{T}, Tproj} <: AbstractCPUPenalty{T} penalty::Tpen proj::Tproj end function ProjectedPenalty(penalty::AbstractPenalty{T}) where {T} return ProjectedPenalty(penalty, HeavisideProjection(10*one(T))) end @inline (P::ProjectedPenalty)(x) = P.penalty(P.proj(x)) @forward_property ProjectedPenalty penalty mutable struct HeavisideProjection{T} <: AbstractProjection β::T end @inline (P::HeavisideProjection)(x) = 1 - exp(-P.β*x) + x * exp(-P.β) mutable struct SigmoidProjection{T} <: AbstractProjection β::T end @inline (P::SigmoidProjection)(x) = 1 / (1 + exp((P.β + 1) * (-x + 0.5))) import Base: copy copy(p::TP) where {TP<:AbstractPenalty} = TP(p.p) copy(p::HeavisideProjection) = HeavisideProjection(p.β) copy(p::SigmoidProjection) = SigmoidProjection(p.β) copy(p::ProjectedPenalty) = ProjectedPenalty(copy(p.penalty), copy(p.proj)) function Utilities.setpenalty!(P::AbstractPenalty, p) P.p = p return P end function Utilities.setpenalty!(P::ProjectedPenalty, p) P.penalty.p = p return P end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
1076
import Base: length, append!, sizehint! @params struct TopOptTrace{T, TI <: Integer} c_hist::AbstractVector{T} v_hist::AbstractVector{T} x_hist::AbstractVector{<:AbstractVector{T}} add_hist::AbstractVector{TI} rem_hist::AbstractVector{TI} end TopOptTrace{T, TI}() where {T, TI<:Integer} = TopOptTrace(Vector{T}(), Vector{T}(), Vector{Vector{T}}(), Vector{TI}(), Vector{TI}()) length(t::TopOptTrace) = length(t.v_hist) topopt_trace_fields = fieldnames(TopOptTrace) macro append_fields_t1_t2() return esc(Expr(:block, [Expr(:call, :append!, :(t1.$f), :(t2.$f)) for f in topopt_trace_fields]...)) end function append!(t1::TopOptTrace, t2::TopOptTrace) @append_fields_t1_t2() end macro sizehint!_fields_t() return esc(Expr(:block, [Expr(:call, :sizehint!, :(t.$f), :n) for f in topopt_trace_fields]...)) end function sizehint!(t::TopOptTrace, n) @sizehint!_fields_t() return end function append!(ts::Vector{<:TopOptTrace}) sizehint!(ts[1], sum(length.(ts))) for i in 2:length(ts) append!(ts[1], ts[i]) end return ts[1] end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
4939
""" @params struct_def A macro that changes all fields' types to type parameters while respecting the type bounds specificied by the user. For example: ``` @params struct MyType{T} f1::T f2::AbstractVector{T} f3::AbstractVector{<:Real} f4 end ``` will define: ``` struct MyType{T, T1 <: T, T2 <: AbstractVector{T}, T3 <: AbstractVector{<:Real}, T4} f1::T1 f2::T1 f3::T3 f4::T4 end ``` The default non-parameteric constructor, e.g. `MyType(f1, f2, f3, f4)`, will always work if all the type parameters used in the type header are used in the field types. Using a type parameter in the type header that is not used in the field types such as: ``` struct MyType{T} f1 f2 end ``` is not recommended. """ macro params(struct_expr) header = struct_expr.args[2] fields = @view struct_expr.args[3].args[2:2:end] params = [] for i in 1:length(fields) x = fields[i] T = gensym() if x isa Symbol push!(params, T) fields[i] = :($x::$T) elseif x.head == :(::) abstr = x.args[2] var = x.args[1] push!(params, :($T <: $abstr)) fields[i] = :($var::$T) end end if header isa Symbol && length(params) > 0 struct_expr.args[2] = :($header{$(params...)}) elseif header.head == :curly append!(struct_expr.args[2].args, params) elseif header.head == :<: if struct_expr.args[2].args[1] isa Symbol name = struct_expr.args[2].args[1] struct_expr.args[2].args[1] = :($name{$(params...)}) elseif header.head == :<: && struct_expr.args[2].args[1] isa Expr append!(struct_expr.args[2].args[1].args, params) else error("Unidentified type definition.") end else error("Unidentified type definition.") end esc(struct_expr) end struct RaggedArray{TO, TV} offsets::TO values::TV end function RaggedArray(vv::Vector{Vector{T}}) where T offsets = [1; 1 .+ accumulate(+, collect(length(v) for v in vv))] values = Vector{T}(undef, offsets[end]-1) for (i, v) in enumerate(vv) r = offsets[i]:offsets[i+1]-1 values[r] .= v end RaggedArray(offsets, values) end function Base.getindex(ra::RaggedArray, i) @assert 1 <= i < length(ra.offsets) r = ra.offsets[i]:ra.offsets[i+1]-1 @assert 1 <= r.start && r.stop <= length(ra.values) return @view ra.values[r] end function Base.getindex(ra::RaggedArray, i, j) @assert 1 <= j < length(ra.offsets) r = ra.offsets[j]:ra.offsets[j+1]-1 @assert 1 <= i <= length(r) return ra.values[r[i]] end function Base.setindex!(ra::RaggedArray, v, i, j) @assert 1 <= j < length(ra.offsets) r = ra.offsets[j]:ra.offsets[j+1]-1 @assert 1 <= i <= length(r) ra.values[r[i]] = v end function find_varind(black, white, ::Type{TI}=Int) where TI nel = length(black) nel == length(white) || throw("Black and white vectors should be of the same length") varind = zeros(TI, nel) k = 1 for i in 1:nel if !black[i] && !white[i] varind[i] = k k += 1 end end return varind end function find_black_and_white(dh) black = falses(getncells(dh.grid)) white = falses(getncells(dh.grid)) if haskey(dh.grid.cellsets, "black") for c in grid.cellsets["black"] black[c] = true end end if haskey(dh.grid.cellsets, "white") for c in grid.cellsets["white"] white[c] = true end end return black, white end YoungsModulus(p) = getE(p) PoissonRatio(p) = getν(p) function compliance(Ke, u, dofs) comp = zero(eltype(u)) for i in 1:length(dofs) for j in 1:length(dofs) comp += u[dofs[i]]*Ke[i,j]*u[dofs[j]] end end comp end function meandiag(K::AbstractMatrix) z = zero(eltype(K)) for i in 1:size(K, 1) z += abs(K[i, i]) end return z / size(K, 1) end density(var, xmin) = var*(1-xmin) + xmin macro debug(expr) return quote if DEBUG[] $(esc(expr)) end end end @generated function _getproperty(c::T, ::Val{fallback}, ::Val{f}) where {T, fallback, f} f ∈ fieldnames(T) && return :(getfield(c, $(QuoteNode(f)))) return :(getproperty(getfield(c, $(QuoteNode(fallback))), $(QuoteNode(f)))) end @generated function _setproperty!(c::T, ::Val{fallback}, ::Val{f}, val) where {T, fallback, f} f ∈ fieldnames(T) && return :(setfield!(c, $(QuoteNode(f)), val)) return :(setproperty!(getfield(c, $(QuoteNode(fallback))), $(QuoteNode(f)), val)) end macro forward_property(T, field) quote Base.getproperty(c::$(esc(T)), f::Symbol) = _getproperty(c, Val($(QuoteNode(field))), Val(f)) Base.setproperty!(c::$(esc(T)), f::Symbol, val) = _setproperty!(c, Val($(QuoteNode(field))), Val(f), val) end end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
856
@testset "Element stiffness matrix" begin # 1x1 linear quadrilateral cell # Isoparameteric # 2nd order quadrature rule E = 1 nu = 0.3 k = [1/2-nu/6, 1/8+nu/8, -1/4-nu/12, -1/8+3*nu/8, -1/4+nu/12, -1/8-nu/8, nu/6, 1/8-3*nu/8] Ke = E/(1-nu^2)*[k[1] k[2] k[3] k[4] k[5] k[6] k[7] k[8]; k[2] k[1] k[8] k[7] k[6] k[5] k[4] k[3]; k[3] k[8] k[1] k[6] k[7] k[4] k[5] k[2]; k[4] k[7] k[6] k[1] k[8] k[3] k[2] k[5]; k[5] k[6] k[7] k[8] k[1] k[2] k[3] k[4]; k[6] k[5] k[4] k[3] k[2] k[1] k[8] k[7]; k[7] k[4] k[5] k[2] k[3] k[8] k[1] k[6]; k[8] k[3] k[2] k[5] k[4] k[7] k[6] k[1]] problem = HalfMBB((2,2), (1.,1.), 1., 0.3, 1.); #@test ElementFEAInfo(problem).Kes[1] ≈ Ke end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
4201
@testset "Metadata" begin #HalfMBB - 2x2 # 7 8 9 # x--x--x x--x--x # | | | |C3|C4| # x--x--x x--x--x # 4| 5| |6 |C1|C2| # x--x--x x--x--x # 1 2 3 #Node coords: #Ferrite.Node{2,Float64}([0.0, 0.0]) #Ferrite.Node{2,Float64}([1.0, 0.0]) #Ferrite.Node{2,Float64}([2.0, 0.0]) #Ferrite.Node{2,Float64}([0.0, 1.0]) #Ferrite.Node{2,Float64}([1.0, 1.0]) #Ferrite.Node{2,Float64}([2.0, 1.0]) #Ferrite.Node{2,Float64}([0.0, 2.0]) #Ferrite.Node{2,Float64}([1.0, 2.0]) #Ferrite.Node{2,Float64}([2.0, 2.0]) #Cells #Ferrite.Cell{2,4,4}((1, 2, 5, 4)) #Ferrite.Cell{2,4,4}((2, 3, 6, 5)) #Ferrite.Cell{2,4,4}((4, 5, 8, 7)) #Ferrite.Cell{2,4,4}((5, 6, 9, 8)) # 7 8 9 # x--x--x x--x--x # | | | |C3|C4| # x--x--x x--x--x # 4| 5| |6 |C1|C2| # x--x--x x--x--x # 1 2 3 #Node dofs ##1 #2 #3 #4 #5 #6 #7 #8 #9 #1 3 9 7 5 11 15 13 17 #2 4 10 8 6 12 16 14 18 #Cell dofs # #1 #2 #3 #4 # 1 3 7 5 # 2 4 8 6 # 3 9 5 11 # 4 10 6 12 # 5 11 13 17 # 6 12 14 18 # 7 5 15 13 # 8 6 16 14 problem = HalfMBB(Val{:Linear}, (2,2), (1.,1.), 1., 0.3, 1.); coords = [(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (0.0, 1.0), (1.0, 1.0), (2.0, 1.0), (0.0, 2.0), (1.0, 2.0), (2.0, 2.0)] for (i, node) in enumerate(problem.ch.dh.grid.nodes) @test node.x.data == coords[i] end cells = [Ferrite.Cell{2,4,4}((1, 2, 5, 4)), Ferrite.Cell{2,4,4}((2, 3, 6, 5)), Ferrite.Cell{2,4,4}((4, 5, 8, 7)), Ferrite.Cell{2,4,4}((5, 6, 9, 8))] @test problem.ch.dh.grid.cells == cells node_dofs = [1 3 9 7 5 11 15 13 17; 2 4 10 8 6 12 16 14 18] @test problem.metadata.node_dofs == node_dofs cell_dofs = [1 3 7 5; 2 4 8 6; 3 9 5 11; 4 10 6 12; 5 11 13 17; 6 12 14 18; 7 5 15 13; 8 6 16 14] @test problem.metadata.cell_dofs == cell_dofs dof_cells = problem.metadata.dof_cells cell_dofs = problem.metadata.cell_dofs for i in 1:Ferrite.ndofs(problem.ch.dh) d_cells = dof_cells[i] for c in d_cells (cellid, localdof) = c @test i == cell_dofs[localdof, cellid] end end node_first_cells = [(1, 1), (1, 2), (2, 2), (1, 4), (1, 3), (2, 3), (3, 4), (3, 3), (4, 3)] # First node is the first cell's first node. @test problem.metadata.node_cells[1] == [(1, 1)] # Second node is the first cell's second node, # and the second cell's first node. @test problem.metadata.node_cells[2] == [(1, 2), (2, 1)] # Third node is the second cell's second node. @test problem.metadata.node_cells[3] == [(2, 2)] # Fourth node is the first cell's fourth node, # and the third cell's first node. @test problem.metadata.node_cells[4] == [(1, 4), (3, 1)] # Fifth node is the first cell's third node, the second cell's fourth node, # the third cell's second node and the fourth cell's first node. @test problem.metadata.node_cells[5] == [(1, 3), (2, 4), (3, 2), (4, 1)] # Sixth node is the second cell's third node, # and the fourth cell's second node. @test problem.metadata.node_cells[6] == [(2, 3), (4, 2)] # Seventh node is the third cell's fourth node. @test problem.metadata.node_cells[7] == [(3, 4)] # Eigth node is the third cell's third node, # and the fourth cell's fourth node. @test problem.metadata.node_cells[8] == [(3, 3), (4, 4)] # Ninth node is the fourth cell's third node. @test problem.metadata.node_cells[9] == [(4, 3)] end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
5656
using TopOptProblems using Test using Ferrite using TopOptProblems: boundingbox E = 1.0 ν = 0.3 force = 1.0 # Cantilever beam problem tests @testset "Point load cantilever beam" begin global E, ν, force problem = PointLoadCantilever(Val{:Linear}, (160,40), (1.0,1.0), E, ν, force); ncells = 160*40 @test problem.E == E @test problem.ν == ν @test problem.black == problem.white == falses(ncells) @test problem.force == force @test problem.force_dof == 161 * 21 * 2 @test problem.varind == 1:ncells grid = problem.ch.dh.grid @test length(grid.cells) == ncells for i in 1:2, j in 1:2 @test boundingbox(grid)[i][j] ≈ problem.rect_grid.corners[i][j] atol = 1e-8 end @test length(grid.boundary_matrix.nzval) == 2*160 + 2*40 for (c, f) in grid.facesets["bottom"] @test f == 1 for n in grid.cells[c].nodes[[1,2]] @test grid.nodes[n].x[2] == 0 end end for (c, f) in grid.facesets["right"] @test f == 2 for n in grid.cells[c].nodes[[2,3]] @test grid.nodes[n].x[1] ≈ 160 atol = 1e-8 end end for (c, f) in grid.facesets["top"] @test f == 3 for n in grid.cells[c].nodes[[3,4]] @test grid.nodes[n].x[2] ≈ 40 atol = 1e-8 end end for (c, f) in grid.facesets["left"] @test f == 4 for n in grid.cells[c].nodes[[1,4]] @test grid.nodes[n].x[1] == 0 end end @test sum(length, getindex.((grid.facesets,), ["bottom", "right", "top", "left"])) == 2*160 + 2*40 end # Half MBB beam problem @testset "Half MBB beam" begin global E, ν, force problem = HalfMBB(Val{:Linear}, (60,20), (1.,1.), E, ν, force); ncells = 60*20 @test problem.E == E @test problem.ν == ν @test problem.black == problem.white == falses(ncells) @test problem.force == force @test problem.force_dof == (61 * 20 + 2) * 2 @test problem.varind == 1:ncells grid = problem.ch.dh.grid @test length(grid.cells) == ncells for i in 1:2, j in 1:2 @test boundingbox(grid)[i][j] ≈ problem.rect_grid.corners[i][j] atol = 1e-8 end @test length(grid.boundary_matrix.nzval) == 2*60 + 2*20 for (c, f) in grid.facesets["bottom"] @test f == 1 for n in grid.cells[c].nodes[[1,2]] @test grid.nodes[n].x[2] == 0 end end for (c, f) in grid.facesets["right"] @test f == 2 for n in grid.cells[c].nodes[[2,3]] @test grid.nodes[n].x[1] ≈ 60 atol = 1e-8 end end for (c, f) in grid.facesets["top"] @test f == 3 for n in grid.cells[c].nodes[[3,4]] @test grid.nodes[n].x[2] ≈ 20 atol = 1e-8 end end for (c, f) in grid.facesets["left"] @test f == 4 for n in grid.cells[c].nodes[[1,4]] @test grid.nodes[n].x[1] == 0 end end @test sum(length, getindex.((grid.facesets,), ["bottom", "right", "top", "left"])) == 2*60 + 2*20 end # L-beam problem @testset "L-beam" begin global E, ν, force problem = LBeam(Val{:Linear}, Float64, force=force); ncells = 100*50 + 50*50 @test problem.E == E @test problem.ν == ν @test problem.black == problem.white == falses(ncells) @test problem.force == force @test problem.force_dof == (51 * 51 + 50 * 26) * 2 @test problem.varind == 1:ncells grid = problem.ch.dh.grid @test length(grid.cells) == ncells corners = [[0.0, 0.0], [100.0, 100.0]] for i in 1:2, j in 1:2 @test boundingbox(grid)[i][j] ≈ corners[i][j] atol = 1e-8 end @test length(grid.boundary_matrix.nzval) == 100 * 2 + 50 * 4 for (c, f) in grid.facesets["right"] @test f == 2 for n in grid.cells[c].nodes[[2,3]] @test grid.nodes[n].x[1] ≈ 100 atol = 1e-8 end end for (c, f) in grid.facesets["top"] @test f == 3 for n in grid.cells[c].nodes[[3,4]] @test grid.nodes[n].x[2] ≈ 100 atol = 1e-8 end end @test sum(length, getindex.((grid.facesets,), ["right", "top"])) == 2*50 end # Tie-beam problem @testset "Tie-beam" begin problem = TopOptProblems.TieBeam(Val{:Quadratic}, Float64); ncells = 100 @test problem.E == 1 @test problem.ν == 0.3 @test problem.black == problem.white == falses(ncells) @test problem.force == 1 @test problem.varind == 1:ncells grid = problem.ch.dh.grid @test length(grid.cells) == ncells corners = [[0.0, 0.0], [32.0, 7.0]] for i in 1:2, j in 1:2 @test boundingbox(grid)[i][j] ≈ corners[i][j] atol = 1e-8 end @test length(grid.boundary_matrix.nzval) == 32 * 2 + 3 * 2 + 4 * 2 for (c, f) in grid.facesets["bottomload"] @test f == 1 for n in grid.cells[c].nodes[[1,2]] @test grid.nodes[n].x[2] == 0 end end for (c, f) in grid.facesets["rightload"] @test f == 2 for n in grid.cells[c].nodes[[2,3]] @test grid.nodes[n].x[1] ≈ 32 atol = 1e-8 end end for (c, f) in grid.facesets["toproller"] @test f == 3 for n in grid.cells[c].nodes[[3,4]] @test grid.nodes[n].x[2] ≈ 7 atol = 1e-8 end end for (c, f) in grid.facesets["leftfixed"] @test f == 4 for n in grid.cells[c].nodes[[1,4]] @test grid.nodes[n].x[1] == 0 end end @test sum(length, getindex.((grid.facesets,), ["bottomload", "rightload", "toproller", "leftfixed"])) == 8 @test Ferrite.getorder(problem.ch.dh.field_interpolations[1]) == 2 @test Ferrite.nnodes(grid.cells[1]) == 9 end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
code
122
using Test, SafeTestsets @safetestset "TopOptProblems.jl" begin include("problems.jl") include("metadata.jl") end
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MIT" ]
0.1.1
10c04258080b378ecf9b81b6739206eca3f63535
docs
624
# TopOptProblems [![Actions Status](https://github.com/juliatopopt/TopOptProblems.jl/workflows/CI/badge.svg)](https://github.com/juliatopopt/TopOptProblems.jl/actions) [![codecov](https://codecov.io/gh/juliatopopt/TopOptProblems.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/juliatopopt/TopOptProblems.jl) `TopOptProblems` is a collection of standard topology optimisation problems package written in [Julia](https://github.com/JuliaLang/julia). ## Installation To install `TopOptProblems.jl`, run: ```julia using Pkg pkg"add TopOptProblems" ``` To load the package, use: ```julia using TopOptProblems ```
TopOptProblems
https://github.com/JuliaTopOpt/TopOptProblems.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
488
using Documenter, SolverBenchmark makedocs( modules = [SolverBenchmark], checkdocs = :exports, doctest = true, linkcheck = true, format = Documenter.HTML( assets = ["assets/style.css"], prettyurls = get(ENV, "CI", nothing) == "true", ), sitename = "SolverBenchmark.jl", pages = ["Home" => "index.md", "Reference" => "reference.md"], ) deploydocs( repo = "github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git", push_preview = true, devbranch = "main", )
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
580
# need to have done, e.g., # results = PkgBenchmark.benchmarkpkg("Krylov", script="benchmark/cg_bmark.jl") # optional: customize plot appearance using Plots pyplot() # recommended! using PlotThemes theme(:juno) common_plot_args = Dict{Symbol, Any}( :linewidth => 2, :alpha => 0.75, :titlefontsize => 8, :legendfontsize => 8, :xtickfontsize => 6, :ytickfontsize => 6, :guidefontsize => 8, ) Plots.default(; common_plot_args...) # process benchmark results and post gist p = profile_solvers(results) posted_gist = to_gist(results, p) println(posted_gist.html_url)
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
771
module SolverBenchmark using Logging using Printf using ColorSchemes using DataFrames using JLD2 using LaTeXStrings using PrettyTables using NLPModels using SolverCore # reexport PrettyTable table formats for convenience export unicode, ascii_dots, ascii_rounded, borderless, compact, tf_markdown, matrix, mysql, simple, unicode_rounded # Tables include("formats.jl") include("latex_formats.jl") include("highlighters.jl") include("join.jl") # Benchmark include("run_solver.jl") include("bmark_solvers.jl") include("bmark_utils.jl") # deprecated, remove in a future version include("formatting.jl") include("latex_tables.jl") include("markdown_tables.jl") # Profiles include("profiles.jl") # PkgBenchmark benchmarks include("pkgbmark.jl") end
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
730
export bmark_solvers """ bmark_solvers(solvers :: Dict{Symbol,Any}, args...; kwargs...) Run a set of solvers on a set of problems. #### Arguments * `solvers`: a dictionary of solvers to which each problem should be passed * other positional arguments accepted by `solve_problems`, except for a solver name #### Keyword arguments Any keyword argument accepted by `solve_problems` #### Return value A Dict{Symbol, AbstractExecutionStats} of statistics. """ function bmark_solvers(solvers::Dict{Symbol, <:Any}, args...; kwargs...) stats = Dict{Symbol, DataFrame}() for (name, solver) in solvers @info "running solver $name" stats[name] = solve_problems(solver, name, args...; kwargs...) end return stats end
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
4013
export save_stats, load_stats, count_unique, quick_summary """ save_stats(stats, filename; kwargs...) Write the benchmark statistics `stats` to a file named `filename`. #### Arguments * `stats::Dict{Symbol,DataFrame}`: benchmark statistics such as returned by `bmark_solvers` * `filename::AbstractString`: the output file name. #### Keyword arguments * `force::Bool=false`: whether to overwrite `filename` if it already exists * `key::String="stats"`: the key under which the data can be read from `filename` later. #### Return value This method returns an error if `filename` exists and `force==false`. On success, it returns the value of `jldopen(filename, "w")`. """ function save_stats( stats::Dict{Symbol, DataFrame}, filename::AbstractString; force::Bool = false, key::String = "stats", ) isfile(filename) && !force && error("$filename already exists; use `force=true` to overwrite") jldopen(filename, "w") do file file[key] = stats end end """ stats = load_stats(filename; kwargs...) #### Arguments * `filename::AbstractString`: the input file name. #### Keyword arguments * `key::String="stats"`: the key under which the data can be read in `filename`. The key should be the same as the one used when `save_stats` was called. #### Return value A `Dict{Symbol,DataFrame}` containing the statistics stored in file `filename`. The user should `import DataFrames` before calling `load_stats`. """ function load_stats(filename::AbstractString; key::String = "stats") jldopen(filename) do file file[key] end end @doc raw""" vals = count_unique(X) Count the number of occurrences of each value in `X`. #### Arguments * `X`: an iterable. #### Return value A `Dict{eltype(X),Int}` whose keys are the unique elements in `X` and values are their number of occurrences. Example: the snippet stats = load_stats("mystats.jld2") for solver ∈ keys(stats) @info "$solver statuses" count_unique(stats[solver].status) end displays the number of occurrences of each final status for each solver in `stats`. """ function count_unique(X) vals = Dict{eltype(X), Int}() for x ∈ X vals[x] = x ∈ keys(vals) ? (vals[x] + 1) : 1 end vals end """ statuses, avgs = quick_summary(stats; kwargs...) Call `count_unique` and compute a few average measures for each solver in `stats`. #### Arguments * `stats::Dict{Symbol,DataFrame}`: benchmark statistics such as returned by `bmark_solvers`. #### Keyword arguments * `cols::Vector{Symbol}`: symbols indicating `DataFrame` columns in solver statistics for which we compute averages. Default: `[:iter, :neval_obj, :neval_grad, :neval_hess, :neval_hprod, :elapsed_time]`. #### Return value * `statuses::Dict{Symbol,Dict{Symbol,Int}}`: a dictionary of number of occurrences of each final status for each solver in `stats`. Each value in this dictionary is returned by `count_unique` * `avgs::Dict{Symbol,Dict{Symbol,Float64}}`: a dictionary that contains averages of performance measures across all problems for each solver. Each `avgs[solver]` is a `Dict{Symbol,Float64}` where the measures are those given in the keyword argument `cols` and values are averages of those measures across all problems. Example: the snippet statuses, avgs = quick_summary(stats) for solver ∈ keys(stats) @info "statistics for" solver statuses[solver] avgs[solver] end displays quick summary and averages for each solver. """ function quick_summary( stats::Dict{Symbol, DataFrame}; cols::Vector{Symbol} = [:iter, :neval_obj, :neval_grad, :neval_hess, :neval_hprod, :elapsed_time], ) nproblems = size(stats[first(keys(stats))], 1) statuses = Dict{Symbol, Dict{Symbol, Int}}() avgs = Dict{Symbol, Dict{Symbol, Float64}}() for solver ∈ keys(stats) statuses[solver] = count_unique(stats[solver].status) avgs[solver] = Dict{Symbol, Float64}() for col ∈ cols avgs[solver][col] = sum(stats[solver][!, col]) / nproblems end end statuses, avgs end
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
3157
export pretty_stats const default_formatters = Dict(AbstractFloat => "%9.2e", Signed => "%6d", AbstractString => "%15s", Symbol => "%15s") abstract_supertype(T::DataType) = T == Symbol ? T : supertype(T) abstract_supertype(::Type{<:AbstractFloat}) = AbstractFloat abstract_supertype(::Type{<:AbstractString}) = AbstractString """ pretty_stats(df; kwargs...) Pretty-print a DataFrame using PrettyTables. ### Arguments * `io::IO`: an IO stream to which the table will be output (default: `stdout`); * `df::DataFrame`: the DataFrame to be displayed. If only certain columns of `df` should be displayed, they should be extracted explicitly, e.g., by passing `df[!, [:col1, :col2, :col3]]`. ### Keyword Arguments * `col_formatters::Dict{Symbol, String}`: a Dict of format strings to apply to selected columns of `df`. The keys of `col_formatters` should be symbols, so that specific formatting can be applied to specific columns. By default, `default_formatters` is used, based on the column type. If PrettyTables formatters are passed using the `formatters` keyword argument, they are applied before those in `col_formatters`. * `hdr_override::Dict{Symbol, String}`: a Dict of those headers that should be displayed differently than simply according to the column name (default: empty). Example: `Dict(:col1 => "column 1")`. All other keyword arguments are passed directly to `pretty_table`. In particular, * use `tf=tf_markdown` to display a Markdown table; * do not use this function for LaTeX output; use `pretty_latex_stats` instead; * any PrettyTables highlighters can be given, but see the predefined `passfail_highlighter` and `gradient_highlighter`. """ function pretty_stats( io::IO, df::DataFrame; col_formatters = default_formatters, hdr_override::Dict{Symbol, String} = Dict{Symbol, String}(), kwargs..., ) kwargs = Dict(kwargs) pt_formatters = [] # if PrettyTable formatters are given, apply those first if :formatters ∈ keys(kwargs) kw_fmts = pop!(kwargs, :formatters) if typeof(kw_fmts) <: Tuple for fmt ∈ kw_fmts push!(pt_formatters, fmt) end else push!(pt_formatters, kw_fmts) end end # merge default and user-specified column formatters df_names = propertynames(df) for col = 1:length(df_names) name = df_names[col] if name ∈ keys(col_formatters) push!(pt_formatters, ft_printf(col_formatters[name], col)) else typ = Missings.nonmissingtype(eltype(df[!, name])) used_format_type = abstract_supertype(typ) push!(pt_formatters, ft_printf(default_formatters[used_format_type], col)) end end # set header header = String[] for name ∈ df_names push!(header, name ∈ keys(hdr_override) ? hdr_override[name] : String(name)) end # set nosubheader=true to avoid printing the column data types :nosubheader ∈ keys(kwargs) && pop!(kwargs, :nosubheader) # pretty_table expects a tuple of formatters pretty_table(io, df, header = header, formatters = tuple(pt_formatters...); kwargs...) end pretty_stats(df::DataFrame; kwargs...) = pretty_stats(stdout, df; kwargs...)
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
1954
""" format_table(df, formatter, kwargs...) Format the data frame into a table using `formatter`. Used by other table functions. Inputs: - `df::DataFrame`: Dataframe of a solver. Each row is a problem. - `formatter::Function`: A function that formats its input according to its type. See `LTXformat` or `MDformat` for examples. Keyword arguments: - `cols::Array{Symbol}`: Which columns of the `df`. Defaults to using all columns; - `ignore_missing_cols::Bool`: If `true`, filters out the columns in `cols` that don't exist in the data frame. Useful when creating tables for solvers in a loop where one solver has a column the other doesn't. If `false`, throws `BoundsError` in that situation. - `fmt_override::Dict{Symbol,Function}`: Overrides format for a specific column, such as fmt_override=Dict(:name => x->@sprintf("**%-10s**", x)) - `hdr_override::Dict{Symbol,String}`: Overrides header names, such as `hdr_override=Dict(:name => "Name")`. Outputs: - `header::Array{String,1}`: header vector. - `table::Array{String,2}`: formatted table. """ function format_table( df::DataFrame, formatter::Function; cols::Array{Symbol, 1} = propertynames(df), ignore_missing_cols::Bool = false, fmt_override::Dict{Symbol, F} = Dict{Symbol, Function}(), hdr_override::Dict{Symbol, String} = Dict{Symbol, String}(), ) where {F <: Function} if ignore_missing_cols cols = filter(c -> hasproperty(df, c), cols) elseif !all(hasproperty(df, c) for c in cols) missing_cols = setdiff(cols, propertynames(df)) @error("There are no columns `" * join(missing_cols, ", ") * "` in dataframe") throw(BoundsError) end string_cols = [map(haskey(fmt_override, col) ? fmt_override[col] : formatter, df[!, col]) for col in cols] table = hcat(string_cols...) header = [haskey(hdr_override, c) ? hdr_override[c] : formatter(c) for c in cols] return header, table end Base.@deprecate format_table pretty_stats false
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
2395
export passfail_highlighter, passfail_latex_highlighter, gradient_highlighter # helper function function find_failure_ids(df::DataFrame) hasproperty(df, :status) ? df[(df.status .!= :first_order) .& (df.status .!= :unbounded), :].id : Int[] end """ hl = passfail_highlighter(df, c=crayon"bold red") A PrettyTables highlighter that colors failures in bold red by default. ### Input Arguments * `df::DataFrame` dataframe to which the highlighter will be applied. `df` must have the `id` column. If `df` has the `:status` property, the highlighter will be applied to rows for which `df.status` indicates a failure. A failure is any status different from `:first_order` or `:unbounded`. """ function passfail_highlighter(df::DataFrame, c = crayon"bold red") # extract failure ids failure_id = find_failure_ids(df) Highlighter((data, i, j) -> i ∈ failure_id, c) end """ hl = passfail_latex_highlighter(df) A PrettyTables LaTeX highlighter that colors failures in bold red by default. See the documentation of `passfail_highlighter` for more information. """ function passfail_latex_highlighter(df::DataFrame, c = "cellcolor{red}") # NB: not obvious how to also use bold as \textbf{\(1.0e-03\)} will not appear in bold failure_id = find_failure_ids(df) LatexHighlighter((data, i, j) -> i ∈ failure_id, c) end """ hl = gradient_highlighter(df, col; cmap=:coolwarm) A PrettyTables highlighter the applies a color gradient to the values in columns given by `cols`. ### Input Arguments * `df::DataFrame` dataframe to which the highlighter will be applied; * `col::Symbol` a symbol to indicate which column the highlighter will be applied to. ### Keyword Arguments * `cmap::Symbol` color scheme to use, from ColorSchemes. """ function gradient_highlighter(df::DataFrame, col::Symbol; cmap::Symbol = :coolwarm) # inspired from https://ronisbr.github.io/PrettyTables.jl/stable/man/text_examples min_data = minimum(df[!, col]) max_data = maximum(df[!, col]) colidx = findfirst(x -> x == col, names(df)) Highlighter( (data, i, j) -> true, (h, data, i, j) -> begin color = get(ColorSchemes.colorschemes[cmap], data[i, colidx], (min_data, max_data)) return Crayon( foreground = ( round(Int, color.r * 255), round(Int, color.g * 255), round(Int, color.b * 255), ), ) end, ) end
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
1942
import Base.join export join """ df = join(stats, cols; kwargs...) Join a dictionary of DataFrames given by `stats`. Column `:id` is required in all DataFrames. The resulting DataFrame will have column `id` and all columns `cols` for each solver. Inputs: - `stats::Dict{Symbol,DataFrame}`: Dictionary of DataFrames per solver. Each key is a different solver; - `cols::Array{Symbol}`: Which columns of the DataFrames. Keyword arguments: - `invariant_cols::Array{Symbol,1}`: Invariant columns to be added, i.e., columns that don't change depending on the solver (such as name of problem, number of variables, etc.); - `hdr_override::Dict{Symbol,String}`: Override header names. Output: - `df::DataFrame`: Resulting dataframe. """ function join( stats::Dict{Symbol, DataFrame}, cols::Array{Symbol, 1}; invariant_cols::Array{Symbol, 1} = Symbol[], hdr_override::Dict{Symbol, String} = Dict{Symbol, String}(), ) length(cols) == 0 && error("cols can't be empty") if !all(:id in propertynames(df) for (s, df) in stats) error("Missing column :id in some DataFrame") elseif !all(setdiff(cols, propertynames(df)) == [] for (s, df) in stats) error("Not all DataFrames have all columns given by `cols`") end if :id in cols deleteat!(cols, findall(cols .== :id)) end if :id in invariant_cols deleteat!(cols, findall(cols .== :id)) end invariant_cols = [:id; invariant_cols] cols = setdiff(cols, invariant_cols) if length(cols) == 0 error("All columns are invariant") end cols = [:id; cols] s = first(stats)[1] df = stats[s][:, invariant_cols] rename_f(c, s) = begin symbol_c = Symbol(c) symbol_c in invariant_cols && return symbol_c sc = haskey(hdr_override, symbol_c) ? hdr_override[symbol_c] : c Symbol(sc * "_$s") end for (s, dfs) in stats df = innerjoin(df, rename(c -> rename_f(c, s), dfs[!, cols]), on = :id, makeunique = true) end return df end
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
5618
export pretty_latex_stats StringOrLaTeXString = Union{String, LaTeXString} """ safe_latex_Signed_col(col::Integer) Generate a PrettyTables LaTeX formatter for signed integers. """ function safe_latex_Signed_col(col::Integer) return (s, i, j) -> begin j !== col && return s return ismissing(s) ? " "^10 : safe_latex_Signed(s) end end """ safe_latex_Signed(s::AbstractString) Format the string representation of signed integers for output in a LaTeX table. Encloses `s` in `\\(` and `\\)`. """ safe_latex_Signed(s::AbstractString) = LaTeXString("\\(" * string(s) * "\\)") """ safe_latex_AbstractString_col(col:::Integer) Generate a PrettyTables LaTeX formatter for strings. Replaces `_` with `\\_`. """ function safe_latex_AbstractString_col(col::Integer) return (s, i, j) -> begin j !== col && return s ismissing(s) ? " " : safe_latex_AbstractString(s) end end """ safe_latex_AbstractString(s::AbstractString) Format a string for output in a LaTeX table. Escapes underscores. """ function safe_latex_AbstractString(s::AbstractString) if occursin("_", s) LaTeXString(replace(s, "_" => "\\_")) else LaTeXString(s) end end """ safe_latex_Symbol_col(col::Integer) Generate a PrettyTables LaTeX formatter for symbols. """ function safe_latex_Symbol_col(col::Integer) return (s, i, j) -> begin j !== col && return s safe_latex_Symbol(s) end end """ safe_latex_Symbol(s) Format a symbol for output in a LaTeX table. Calls `safe_latex_AbstractString(string(s))`. """ safe_latex_Symbol(s) = safe_latex_AbstractString(string(s)) """ safe_latex_AbstractFloat_col(col::Integer) Generate a PrettyTables LaTeX formatter for real numbers. """ function safe_latex_AbstractFloat_col(col::Integer) # by this point, the table value should already have been converted to a string return (s, i, j) -> begin j != col && return s return ismissing(s) ? " "^17 : safe_latex_AbstractFloat(s) end end """ safe_latex_AbstractFloat(s::AbstractString) Format the string representation of floats for output in a LaTeX table. Replaces infinite values with the `\\infty` LaTeX sequence. If the float is represented in exponential notation, the mantissa and exponent are wrapped in math delimiters. Otherwise, the entire float is wrapped in math delimiters. """ function safe_latex_AbstractFloat(s::AbstractString) strip(s) == "Inf" && return LaTeXString("\\(\\infty\\)") strip(s) == "-Inf" && return LaTeXString("\\(-\\infty\\)") strip(s) == "NaN" && return s if occursin('e', s) mantissa, exponent = split(s, 'e') return LaTeXString("\\(" * string(mantissa) * "\\)e\\(" * string(exponent) * "\\)") else return LaTeXString("\\(" * string(s) * "\\)") end end safe_latex_formatters = Dict( AbstractFloat => safe_latex_AbstractFloat_col, Signed => safe_latex_Signed_col, AbstractString => safe_latex_AbstractString_col, Symbol => safe_latex_Symbol_col, ) """ pretty_latex_stats(df; kwargs...) Pretty-print a DataFrame as a LaTeX longtable using PrettyTables. See the `pretty_stats` documentation. Specific settings in this method are: * the backend is set to `:latex`; * the table type is set to `:longtable`; * highlighters, if any, should be LaTeX highlighters. See the PrettyTables documentation for more information. """ function pretty_latex_stats( io::IO, df::DataFrame; col_formatters = default_formatters, hdr_override::Dict{Symbol, String} = Dict{Symbol, String}(), kwargs..., ) kwargs = Dict(kwargs) pt_formatters = [] # if PrettyTable formatters are given, apply those first if :formatters ∈ keys(kwargs) kw_fmts = pop!(kwargs, :formatters) if typeof(kw_fmts) <: Tuple for fmt ∈ kw_fmts push!(pt_formatters, fmt) end else push!(pt_formatters, kw_fmts) end end # merge default and user-specified column formatters df_names = propertynames(df) for col = 1:length(df_names) name = df_names[col] typ = Missings.nonmissingtype(eltype(df[!, name])) styp = supertype(typ) if name ∈ keys(col_formatters) push!(pt_formatters, ft_printf(col_formatters[name], col)) else # be careful because supertype(Symbol) = Any used_format_type = abstract_supertype(typ) push!(pt_formatters, ft_printf(default_formatters[used_format_type], col)) # add LaTeX-specific formatters to make our table pretty push!(pt_formatters, safe_latex_formatters[used_format_type](col)) end end # set header header = StringOrLaTeXString[] for name ∈ df_names push!( header, (name ∈ keys(hdr_override) ? hdr_override[name] : String(name)) |> safe_latex_AbstractString, ) end # force a few options for s ∈ (:nosubheader, :backend, :table_type, :tf) s ∈ keys(kwargs) && pop!(kwargs, s) end # by default, PrettyTables wants to boldface headers # that won't work if we put any math headers tf = LatexTableFormat( top_line = "\\hline", header_line = "\\hline", mid_line = "\\hline", bottom_line = "\\hline", left_vline = "|", mid_vline = "|", right_vline = "|", header_envs = [], subheader_envs = ["texttt"], ) # pretty_table expects a tuple of formatters pretty_table( io, df, header = header, backend = Val(:latex), table_type = :longtable, tf = tf, vlines = :none, longtable_footer = "{\\bfseries Continued on next page}", formatters = tuple(pt_formatters...); kwargs..., ) end pretty_latex_stats(df::DataFrame; kwargs...) = pretty_latex_stats(stdout, df; kwargs...)
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
2109
# dependencies imports using LaTeXTabulars for (typ, fmt) in default_formatters safe = Symbol("safe_latex_$typ") @eval begin LTXformat(x::$typ) = @sprintf($fmt, x) |> $safe end end LTXformat(x::Missing) = "NA" @doc """ LTXformat(x) Format `x` according to its type. For types `Signed`, `AbstractFloat`, `AbstractString` and `Symbol`, use a predefined formatting string passed to `@sprintf` and then the corresponding `safe_latex_<type>` function. For type `Missing`, return "NA". """ LTXformat """ latex_table(io, df, kwargs...) Create a latex longtable of a DataFrame using LaTeXTabulars, and format the output for a publication-ready table. Inputs: - `io::IO`: where to send the table, e.g.: open("file.tex", "w") do io latex_table(io, df) end If left out, `io` defaults to `stdout`. - `df::DataFrame`: Dataframe of a solver. Each row is a problem. Keyword arguments: - `cols::Array{Symbol}`: Which columns of the `df`. Defaults to using all columns; - `ignore_missing_cols::Bool`: If `true`, filters out the columns in `cols` that don't exist in the data frame. Useful when creating tables for solvers in a loop where one solver has a column the other doesn't. If `false`, throws `BoundsError` in that situation. - `fmt_override::Dict{Symbol,Function}`: Overrides format for a specific column, such as fmt_override=Dict(:name => x->@sprintf("\\textbf{%s}", x) |> safe_latex_AbstractString)` - `hdr_override::Dict{Symbol,String}`: Overrides header names, such as `hdr_override=Dict(:name => "Name")`, where LaTeX escaping should be used if necessary. We recommend using the `safe_latex_foo` functions when overriding formats, unless you're sure you don't need them. """ function latex_table(io::IO, df::DataFrame; kwargs...) header, table, _ = format_table(df, LTXformat; kwargs...) # ignore highlighter latex_tabular(io, LongTable("l" * "r"^(length(header) - 1), header), [table, Rule()]) nothing end latex_table(df::DataFrame; kwargs...) = latex_table(stdout, df; kwargs...) Base.@deprecate latex_table pretty_latex_stats false
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
1341
for (typ, fmt) in default_formatters @eval begin MDformat(x::$typ) = @sprintf($fmt, x) end end MDformat(x::Missing) = "NA" @doc """ MDformat(x) Format `x` according to its type. For types `Signed`, `AbstractFloat`, `AbstractString` and `Symbol`, use a predefined formatting string passed to `@sprintf`. For type `Missing`, return "NA". """ MDformat """ markdown_table(io, df, kwargs...) Create a markdown table from a DataFrame using PrettyTables and format the output. Inputs: - `io::IO`: where to send the table, e.g.: open("file.md", "w") do io markdown_table(io, df) end If left out, `io` defaults to `stdout`. - `df::DataFrame`: Dataframe of a solver. Each row is a problem. Keyword arguments: - `hl`: a highlighter or tuple of highlighters to color individual cells (when output to screen). By default, we use a simple `passfail_highlighter`. - all other keyword arguments are passed directly to `format_table`. """ function markdown_table(io::IO, df::DataFrame; hl = passfail_highlighter(df), kwargs...) header, table = format_table(df, MDformat; kwargs...) pretty_table(io, table, header = header, tf = tf_markdown, highlighters = hl) end markdown_table(df::DataFrame; kwargs...) = markdown_table(stdout, df; kwargs...) Base.@deprecate markdown_table pretty_stats false
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
5519
import BenchmarkTools import GitHub import JSON import PkgBenchmark export bmark_results_to_dataframes, judgement_results_to_dataframes, profile_package, to_gist """ stats = bmark_results_to_dataframes(results) Convert `PkgBenchmark` results to a dictionary of `DataFrame`s. The benchmark SUITE should have been constructed in the form SUITE[solver][case] = ... where `solver` will be recorded as one of the solvers to be compared in the DataFrame and case is a test case. For example: SUITE["CG"]["BCSSTK09"] = @benchmarkable ... SUITE["LBFGS"]["ROSENBR"] = @benchmarkable ... Inputs: - `results::BenchmarkResults`: the result of `PkgBenchmark.benchmarkpkg` Output: - `stats::Dict{Symbol,DataFrame}`: a dictionary of `DataFrame`s containing the benchmark results per solver. """ function bmark_results_to_dataframes(results::PkgBenchmark.BenchmarkResults) entries = BenchmarkTools.leaves(PkgBenchmark.benchmarkgroup(results)) entries = entries[sortperm(map(x -> string(first(x)), entries))] solvers = unique(map(pair -> pair[1][1], entries)) names = [:name, :time, :memory, :gctime, :allocations] types = [String, Float64, Float64, Float64, Int] stats = Dict{Symbol, DataFrame}() for solver in solvers stats[Symbol(solver)] = DataFrame(names .=> [T[] for T in types]) end for entry in entries case, trial = entry name = case[end] solver = Symbol(case[1]) time = BenchmarkTools.time(trial) mem = BenchmarkTools.memory(trial) gctime = BenchmarkTools.gctime(trial) allocs = BenchmarkTools.allocs(trial) push!(stats[solver], [name, time, mem, gctime, allocs]) end stats end """ stats = judgement_results_to_dataframes(judgement) Convert `BenchmarkJudgement` results to a dictionary of `DataFrame`s. Inputs: - `judgement::BenchmarkJudgement`: the result of, e.g., commit = benchmarkpkg(mypkg) # benchmark a commit or pull request main = benchmarkpkg(mypkg, "main") # baseline benchmark judgement = judge(commit, main) Output: - `stats::Dict{Symbol,Dict{Symbol,DataFrame}}`: a dictionary of `Dict{Symbol,DataFrame}`s containing the target and baseline benchmark results. The elements of this dictionary are the same as those returned by `bmark_results_to_dataframes(main)` and `bmark_results_to_dataframes(commit)`. """ function judgement_results_to_dataframes(judgement::PkgBenchmark.BenchmarkJudgement) target_stats = bmark_results_to_dataframes(judgement.target_results) baseline_stats = bmark_results_to_dataframes(judgement.baseline_results) Dict{Symbol, Dict{Symbol, DataFrame}}( k => Dict{Symbol, DataFrame}(:target => target_stats[k], :baseline => baseline_stats[k]) for k ∈ keys(target_stats) ) end """ p = profile_solvers(results) Produce performance profiles based on `PkgBenchmark.benchmarkpkg` results. Inputs: - `results::BenchmarkResults`: the result of `PkgBenchmark.benchmarkpkg`. """ function profile_solvers(results::PkgBenchmark.BenchmarkResults) # guard against zero gctimes costs = [df -> df[!, :time], df -> df[!, :memory], df -> df[!, :gctime] .+ 1, df -> df[!, :allocations]] profile_solvers( bmark_results_to_dataframes(results), costs, ["time", "memory", "gctime+1", "allocations"], ) end """ p = profile_package(judgement) Produce performance profiles based on `PkgBenchmark.BenchmarkJudgement` results. Inputs: - `judgement::BenchmarkJudgement`: the result of, e.g., commit = benchmarkpkg(mypkg) # benchmark a commit or pull request main = benchmarkpkg(mypkg, "main") # baseline benchmark judgement = judge(commit, main) """ function profile_package(judgement::PkgBenchmark.BenchmarkJudgement) # guard against zero gctimes costs = [df -> df[!, :time], df -> df[!, :memory], df -> df[!, :gctime] .+ 1, df -> df[!, :allocations]] judgement_dataframes = judgement_results_to_dataframes(judgement) Dict{Symbol, Plots.Plot}( k => profile_solvers( judgement_dataframes[k], costs, ["time", "memory", "gctime+1", "allocations"], ) for k ∈ keys(judgement_dataframes) ) end """ posted_gist = to_gist(results, p) Create and post a gist with the benchmark results and performance profiles. Inputs: - `results::BenchmarkResults`: the result of `PkgBenchmark.benchmarkpkg` - `p`:: the result of `profile_solvers`. Output: - the return value of GitHub.jl's `create_gist`. """ function to_gist(results::PkgBenchmark.BenchmarkResults, p) filename = tempname() svgfilename = "$(filename).svg" savefig(p, svgfilename) svgfilecontents = escape_string(read(svgfilename, String)) gist_json = JSON.parse( """ { "description": "Benchmarks uploaded by SolverBenchmark.jl", "public": true, "files": { "bmark.md": { "content": "$(escape_string(sprint(PkgBenchmark.export_markdown, results; context=stdout)))" }, "bmark.svg": { "content": "$(svgfilecontents)" } } } """, ) # Need to add GITHUB_AUTH to your .bashrc myauth = GitHub.authenticate(ENV["GITHUB_AUTH"]) GitHub.create_gist(params = gist_json, auth = myauth) end """ posted_gist = to_gist(results) Create and post a gist with the benchmark results and performance profiles. Inputs: - `results::BenchmarkResults`: the result of `PkgBenchmark.benchmarkpkg` Output: - the return value of GitHub.jl's `create_gist`. """ to_gist(results) = to_gist(results, profile_solvers(results))
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
4479
import BenchmarkProfiles: performance_profile using BenchmarkProfiles, Plots export performance_profile, profile_solvers """ performance_profile(stats, cost, args...; b = PlotsBackend(), kwargs...) Produce a performance profile comparing solvers in `stats` using the `cost` function. Inputs: - `stats::Dict{Symbol,DataFrame}`: pairs of `:solver => df`; - `cost::Function`: cost function applyed to each `df`. Should return a vector with the cost of solving the problem at each row; - 0 cost is not allowed; - If the solver did not solve the problem, return Inf or a negative number. - `b::BenchmarkProfiles.AbstractBackend` : backend used for the plot. Examples of cost functions: - `cost(df) = df.elapsed_time`: Simple `elapsed_time` cost. Assumes the solver solved the problem. - `cost(df) = (df.status .!= :first_order) * Inf + df.elapsed_time`: Takes into consideration the status of the solver. """ function performance_profile( stats::Dict{Symbol, DataFrame}, cost::Function, args...; b::BenchmarkProfiles.AbstractBackend = PlotsBackend(), kwargs..., ) solvers = keys(stats) dfs = (stats[s] for s in solvers) P = hcat([cost(df) for df in dfs]...) performance_profile(b, P, string.(solvers), args...; kwargs...) end """ p = profile_solvers(stats, costs, costnames; width = 400, height = 400, b = PlotsBackend(), kwargs...) Produce performance profiles comparing `solvers` based on the data in `stats`. Inputs: - `stats::Dict{Symbol,DataFrame}`: a dictionary of `DataFrame`s containing the benchmark results per solver (e.g., produced by `bmark_results_to_dataframes()`) - `costs::Vector{Function}`: a vector of functions specifying the measures to use in the profiles - `costnames::Vector{String}`: names to be used as titles of the profiles. Keyword inputs: - `width::Int`: Width of each individual plot (Default: 400) - `height::Int`: Height of each individual plot (Default: 400) - `b::BenchmarkProfiles.AbstractBackend` : backend used for the plot. Additional `kwargs` are passed to the `plot` call. Output: A Plots.jl plot representing a set of performance profiles comparing the solvers. The set contains performance profiles comparing all the solvers together on the measures given in `costs`. If there are more than two solvers, additional profiles are produced comparing the solvers two by two on each cost measure. """ function profile_solvers( stats::Dict{Symbol, DataFrame}, costs::Vector{<:Function}, costnames::Vector{String}; width::Int = 400, height::Int = 400, b::BenchmarkProfiles.AbstractBackend = PlotsBackend(), kwargs..., ) solvers = collect(keys(stats)) dfs = (stats[solver] for solver in solvers) Ps = [hcat([Float64.(cost(df)) for df in dfs]...) for cost in costs] nprobs = size(stats[first(solvers)], 1) nsolvers = length(solvers) ncosts = length(costs) npairs = div(nsolvers * (nsolvers - 1), 2) colors = get_color_palette(:auto, nsolvers) # profiles with all solvers ps = [ performance_profile( b, Ps[1], string.(solvers), palette = colors, title = costnames[1], legend = :bottomright, ), ] nsolvers > 2 && xlabel!(ps[1], "") for k = 2:ncosts p = performance_profile( b, Ps[k], string.(solvers), palette = colors, title = costnames[k], legend = false, ) nsolvers > 2 && xlabel!(p, "") ylabel!(p, "") push!(ps, p) end if nsolvers > 2 ipairs = 0 # combinations of solvers 2 by 2 for i = 2:nsolvers for j = 1:(i - 1) ipairs += 1 pair = [solvers[i], solvers[j]] dfs = (stats[solver] for solver in pair) Ps = [hcat([Float64.(cost(df)) for df in dfs]...) for cost in costs] clrs = [colors[i], colors[j]] p = performance_profile(b, Ps[1], string.(pair), palette = clrs, legend = :bottomright) ipairs < npairs && xlabel!(p, "") push!(ps, p) for k = 2:length(Ps) p = performance_profile(b, Ps[k], string.(pair), palette = clrs, legend = false) ipairs < npairs && xlabel!(p, "") ylabel!(p, "") push!(ps, p) end end end p = plot( ps..., layout = (1 + ipairs, ncosts), size = (ncosts * width, (1 + ipairs) * height); kwargs..., ) else p = plot(ps..., layout = (1, ncosts), size = (ncosts * width, height); kwargs...) end p end
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
4879
export solve_problems """ solve_problems(solver, solver_name, problems; kwargs...) Apply a solver to a set of problems. #### Arguments * `solver`: the function name of a solver; * `solver_name`: name of the solver; * `problems`: the set of problems to pass to the solver, as an iterable of `AbstractNLPModel`. It is recommended to use a generator expression (necessary for CUTEst problems). #### Keyword arguments * `solver_logger::AbstractLogger`: logger wrapping the solver call (default: `NullLogger`); * `reset_problem::Bool`: reset the problem's counters before solving (default: `true`); * `skipif::Function`: function to be applied to a problem and return whether to skip it (default: `x->false`); * `colstats::Vector{Symbol}`: summary statistics for the logger to output during the benchmark (default: `[:name, :nvar, :ncon, :status, :elapsed_time, :objective, :dual_feas, :primal_feas]`); * `info_hdr_override::Dict{Symbol,String}`: header overrides for the summary statistics (default: use default headers); * `prune`: do not include skipped problems in the final statistics (default: `true`); * any other keyword argument to be passed to the solver. #### Return value * a `DataFrame` where each row is a problem, minus the skipped ones if `prune` is true. """ function solve_problems( solver, solver_name::TName, problems; solver_logger::AbstractLogger = NullLogger(), reset_problem::Bool = true, skipif::Function = x -> false, colstats::Vector{Symbol} = [ :solver_name, :name, :nvar, :ncon, :status, :iter, :elapsed_time, :objective, :dual_feas, :primal_feas, ], info_hdr_override::Dict{Symbol, String} = Dict{Symbol, String}(:solver_name => "Solver"), prune::Bool = true, kwargs..., ) where {TName} f_counters = collect(fieldnames(Counters)) fnls_counters = collect(fieldnames(NLSCounters))[2:end] # Excludes :counters ncounters = length(f_counters) + length(fnls_counters) types = [ TName Int String Int Int Int Symbol Float64 Float64 Int Float64 Float64 fill(Int, ncounters) String ] names = [ :solver_name :id :name :nvar :ncon :nequ :status :objective :elapsed_time :iter :dual_feas :primal_feas f_counters fnls_counters :extrainfo ] stats = DataFrame(names .=> [T[] for T in types]) specific = Symbol[] col_idx = indexin(colstats, names) first_problem = true for (id, problem) in enumerate(problems) if reset_problem reset!(problem) end nequ = problem isa AbstractNLSModel ? problem.nls_meta.nequ : 0 problem_info = [id; problem.meta.name; problem.meta.nvar; problem.meta.ncon; nequ] skipthis = skipif(problem) if skipthis prune || push!( stats, [ solver_name problem_info :exception Inf Inf 0 Inf Inf fill(0, ncounters) "skipped" fill(missing, length(specific)) ], ) finalize(problem) else try s = with_logger(solver_logger) do solver(problem; kwargs...) end if first_problem for (k, v) in s.solver_specific if !(typeof(v) <: AbstractVector) insertcols!(stats, ncol(stats) + 1, k => Vector{Union{typeof(v), Missing}}()) push!(specific, k) end end @info log_header(colstats, types[col_idx], hdr_override = info_hdr_override) first_problem = false end counters_list = problem isa AbstractNLSModel ? [getfield(problem.counters.counters, f) for f in f_counters] : [getfield(problem.counters, f) for f in f_counters] nls_counters_list = problem isa AbstractNLSModel ? [getfield(problem.counters, f) for f in fnls_counters] : zeros(Int, length(fnls_counters)) push!( stats, [ solver_name problem_info s.status s.objective s.elapsed_time s.iter s.dual_feas s.primal_feas counters_list nls_counters_list "" [s.solver_specific[k] for k in specific] ], ) catch e @error "caught exception" e push!( stats, [ solver_name problem_info :exception Inf Inf 0 Inf Inf fill(0, ncounters) string(e) fill(missing, length(specific)) ], ) finally finalize(problem) end end (skipthis && prune) || @info log_row(stats[end, col_idx]) end return stats end
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
312
using LinearAlgebra using BenchmarkTools # make up bogus benchmark suite SUITE = BenchmarkGroup() SUITE["lu"] = BenchmarkGroup() SUITE["qr"] = BenchmarkGroup() for _ = 1:10 A = rand(10, 10) name = string(gensym()) SUITE["lu"][name] = @benchmarkable lu($A) SUITE["qr"][name] = @benchmarkable qr($A) end
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
502
function get_stats_data() n = 10 names = [:alpha, :beta, :gamma] stats = Dict( name => DataFrame( :id => 1:n, :name => [@sprintf("prob%03d", i) for i = 1:n], :status => map(x -> mod(x, 3) == 0 ? :first_order : :failure, 1:n), :f => [exp(i / n) for i = 1:n], :t => [1e-3 .+ abs(sin(2π * i / n)) * 1000 for i = 1:n], :iter => [3 + 2 * Int(ceil(sin(2π * i / n))) for i = 1:n], :irrelevant => collect(1:n), ) for name in names ) return stats end
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
8713
alpha_md = raw"""| flag | name | f(x) | time | iter | |-------------|---------|-----------|--------|--------| | failure | prob001 | 1.11e+00 | 587.79 | 5 | | failure | prob002 | 1.22e+00 | 951.06 | 5 | | first_order | prob003 | 1.35e+00 | 951.06 | 5 | | failure | prob004 | 1.49e+00 | 587.79 | 5 | | failure | prob005 | 1.65e+00 | 0.00 | 5 | | first_order | prob006 | 1.82e+00 | 587.79 | 3 | | failure | prob007 | 2.01e+00 | 951.06 | 3 | | failure | prob008 | 2.23e+00 | 951.06 | 3 | | first_order | prob009 | 2.46e+00 | 587.79 | 3 | | failure | prob010 | 2.72e+00 | 0.00 | 3 | """ alpha_tex = raw"""\begin{longtable}{rrrrr} \hline flag & name & \(f(x)\) & time & iter \\\hline \endfirsthead \hline flag & name & \(f(x)\) & time & iter \\\hline \endhead \hline \multicolumn{5}{r}{{\bfseries Continued on next page}}\\ \hline \endfoot \endlastfoot failure & prob001 & \( 1.11\)e\(+00\) & \( 5.88\)e\(+02\) & \( 5\) \\ failure & prob002 & \( 1.22\)e\(+00\) & \( 9.51\)e\(+02\) & \( 5\) \\ first\_order & prob003 & \( 1.35\)e\(+00\) & \( 9.51\)e\(+02\) & \( 5\) \\ failure & prob004 & \( 1.49\)e\(+00\) & \( 5.88\)e\(+02\) & \( 5\) \\ failure & prob005 & \( 1.65\)e\(+00\) & \( 1.00\)e\(-03\) & \( 5\) \\ first\_order & prob006 & \( 1.82\)e\(+00\) & \( 5.88\)e\(+02\) & \( 3\) \\ failure & prob007 & \( 2.01\)e\(+00\) & \( 9.51\)e\(+02\) & \( 3\) \\ failure & prob008 & \( 2.23\)e\(+00\) & \( 9.51\)e\(+02\) & \( 3\) \\ first\_order & prob009 & \( 2.46\)e\(+00\) & \( 5.88\)e\(+02\) & \( 3\) \\ failure & prob010 & \( 2.72\)e\(+00\) & \( 1.00\)e\(-03\) & \( 3\) \\\hline \end{longtable} """ alpha_txt = raw"""┌─────────────┬─────────┬───────────┬────────┬────────┐ │ flag │ name │ f(x) │ time │ iter │ ├─────────────┼─────────┼───────────┼────────┼────────┤ │ failure │ prob001 │ 1.11e+00 │ 587.79 │ 5 │ │ failure │ prob002 │ 1.22e+00 │ 951.06 │ 5 │ │ first_order │ prob003 │ 1.35e+00 │ 951.06 │ 5 │ │ failure │ prob004 │ 1.49e+00 │ 587.79 │ 5 │ │ failure │ prob005 │ 1.65e+00 │ 0.00 │ 5 │ │ first_order │ prob006 │ 1.82e+00 │ 587.79 │ 3 │ │ failure │ prob007 │ 2.01e+00 │ 951.06 │ 3 │ │ failure │ prob008 │ 2.23e+00 │ 951.06 │ 3 │ │ first_order │ prob009 │ 2.46e+00 │ 587.79 │ 3 │ │ failure │ prob010 │ 2.72e+00 │ 0.00 │ 3 │ └─────────────┴─────────┴───────────┴────────┴────────┘ """ alpha_hi_tex = raw"""\begin{longtable}{rrrrr} \hline flag & name & \(f(x)\) & time & iter \\\hline \endfirsthead \hline flag & name & \(f(x)\) & time & iter \\\hline \endhead \hline \multicolumn{5}{r}{{\bfseries Continued on next page}}\\ \hline \endfoot \endlastfoot \cellcolor{red}{failure} & \cellcolor{red}{prob001} & \cellcolor{red}{\( 1.11\)e\(+00\)} & \cellcolor{red}{\( 5.88\)e\(+02\)} & \cellcolor{red}{\( 5\)} \\ \cellcolor{red}{failure} & \cellcolor{red}{prob002} & \cellcolor{red}{\( 1.22\)e\(+00\)} & \cellcolor{red}{\( 9.51\)e\(+02\)} & \cellcolor{red}{\( 5\)} \\ first\_order & prob003 & \( 1.35\)e\(+00\) & \( 9.51\)e\(+02\) & \( 5\) \\ \cellcolor{red}{failure} & \cellcolor{red}{prob004} & \cellcolor{red}{\( 1.49\)e\(+00\)} & \cellcolor{red}{\( 5.88\)e\(+02\)} & \cellcolor{red}{\( 5\)} \\ \cellcolor{red}{failure} & \cellcolor{red}{prob005} & \cellcolor{red}{\( 1.65\)e\(+00\)} & \cellcolor{red}{\( 1.00\)e\(-03\)} & \cellcolor{red}{\( 5\)} \\ first\_order & prob006 & \( 1.82\)e\(+00\) & \( 5.88\)e\(+02\) & \( 3\) \\ \cellcolor{red}{failure} & \cellcolor{red}{prob007} & \cellcolor{red}{\( 2.01\)e\(+00\)} & \cellcolor{red}{\( 9.51\)e\(+02\)} & \cellcolor{red}{\( 3\)} \\ \cellcolor{red}{failure} & \cellcolor{red}{prob008} & \cellcolor{red}{\( 2.23\)e\(+00\)} & \cellcolor{red}{\( 9.51\)e\(+02\)} & \cellcolor{red}{\( 3\)} \\ first\_order & prob009 & \( 2.46\)e\(+00\) & \( 5.88\)e\(+02\) & \( 3\) \\ \cellcolor{red}{failure} & \cellcolor{red}{prob010} & \cellcolor{red}{\( 2.72\)e\(+00\)} & \cellcolor{red}{\( 1.00\)e\(-03\)} & \cellcolor{red}{\( 3\)} \\\hline \end{longtable} """ joined_tex = raw"""\begin{longtable}{rrrrrrrrrrr} \hline id & name & flag\_alpha & f\_alpha & t\_alpha & flag\_beta & f\_beta & t\_beta & flag\_gamma & f\_gamma & t\_gamma \\\hline \endfirsthead \hline id & name & flag\_alpha & f\_alpha & t\_alpha & flag\_beta & f\_beta & t\_beta & flag\_gamma & f\_gamma & t\_gamma \\\hline \endhead \hline \multicolumn{11}{r}{{\bfseries Continued on next page}}\\ \hline \endfoot \endlastfoot \( 1\) & prob001 & failure & \( 1.11\)e\(+00\) & \( 5.88\)e\(+02\) & failure & \( 1.11\)e\(+00\) & \( 5.88\)e\(+02\) & failure & \( 1.11\)e\(+00\) & \( 5.88\)e\(+02\) \\ \( 2\) & prob002 & failure & \( 1.22\)e\(+00\) & \( 9.51\)e\(+02\) & failure & \( 1.22\)e\(+00\) & \( 9.51\)e\(+02\) & failure & \( 1.22\)e\(+00\) & \( 9.51\)e\(+02\) \\ \( 3\) & prob003 & first\_order & \( 1.35\)e\(+00\) & \( 9.51\)e\(+02\) & first\_order & \( 1.35\)e\(+00\) & \( 9.51\)e\(+02\) & first\_order & \( 1.35\)e\(+00\) & \( 9.51\)e\(+02\) \\ \( 4\) & prob004 & failure & \( 1.49\)e\(+00\) & \( 5.88\)e\(+02\) & failure & \( 1.49\)e\(+00\) & \( 5.88\)e\(+02\) & failure & \( 1.49\)e\(+00\) & \( 5.88\)e\(+02\) \\ \( 5\) & prob005 & failure & \( 1.65\)e\(+00\) & \( 1.00\)e\(-03\) & failure & \( 1.65\)e\(+00\) & \( 1.00\)e\(-03\) & failure & \( 1.65\)e\(+00\) & \( 1.00\)e\(-03\) \\ \( 6\) & prob006 & first\_order & \( 1.82\)e\(+00\) & \( 5.88\)e\(+02\) & first\_order & \( 1.82\)e\(+00\) & \( 5.88\)e\(+02\) & first\_order & \( 1.82\)e\(+00\) & \( 5.88\)e\(+02\) \\ \( 7\) & prob007 & failure & \( 2.01\)e\(+00\) & \( 9.51\)e\(+02\) & failure & \( 2.01\)e\(+00\) & \( 9.51\)e\(+02\) & failure & \( 2.01\)e\(+00\) & \( 9.51\)e\(+02\) \\ \( 8\) & prob008 & failure & \( 2.23\)e\(+00\) & \( 9.51\)e\(+02\) & failure & \( 2.23\)e\(+00\) & \( 9.51\)e\(+02\) & failure & \( 2.23\)e\(+00\) & \( 9.51\)e\(+02\) \\ \( 9\) & prob009 & first\_order & \( 2.46\)e\(+00\) & \( 5.88\)e\(+02\) & first\_order & \( 2.46\)e\(+00\) & \( 5.88\)e\(+02\) & first\_order & \( 2.46\)e\(+00\) & \( 5.88\)e\(+02\) \\ \( 10\) & prob010 & failure & \( 2.72\)e\(+00\) & \( 1.00\)e\(-03\) & failure & \( 2.72\)e\(+00\) & \( 1.00\)e\(-03\) & failure & \( 2.72\)e\(+00\) & \( 1.00\)e\(-03\) \\\hline \end{longtable} """ joined_md = raw"""| id | name | flag_alpha | f_alpha | t_alpha | flag_beta | f_beta | t_beta | flag_gamma | f_gamma | t_gamma | |--------|---------|-------------|-----------|-----------|-------------|-----------|-----------|-------------|-----------|-----------| | 1 | prob001 | failure | 1.11e+00 | 5.88e+02 | failure | 1.11e+00 | 5.88e+02 | failure | 1.11e+00 | 5.88e+02 | | 2 | prob002 | failure | 1.22e+00 | 9.51e+02 | failure | 1.22e+00 | 9.51e+02 | failure | 1.22e+00 | 9.51e+02 | | 3 | prob003 | first_order | 1.35e+00 | 9.51e+02 | first_order | 1.35e+00 | 9.51e+02 | first_order | 1.35e+00 | 9.51e+02 | | 4 | prob004 | failure | 1.49e+00 | 5.88e+02 | failure | 1.49e+00 | 5.88e+02 | failure | 1.49e+00 | 5.88e+02 | | 5 | prob005 | failure | 1.65e+00 | 1.00e-03 | failure | 1.65e+00 | 1.00e-03 | failure | 1.65e+00 | 1.00e-03 | | 6 | prob006 | first_order | 1.82e+00 | 5.88e+02 | first_order | 1.82e+00 | 5.88e+02 | first_order | 1.82e+00 | 5.88e+02 | | 7 | prob007 | failure | 2.01e+00 | 9.51e+02 | failure | 2.01e+00 | 9.51e+02 | failure | 2.01e+00 | 9.51e+02 | | 8 | prob008 | failure | 2.23e+00 | 9.51e+02 | failure | 2.23e+00 | 9.51e+02 | failure | 2.23e+00 | 9.51e+02 | | 9 | prob009 | first_order | 2.46e+00 | 5.88e+02 | first_order | 2.46e+00 | 5.88e+02 | first_order | 2.46e+00 | 5.88e+02 | | 10 | prob010 | failure | 2.72e+00 | 1.00e-03 | failure | 2.72e+00 | 1.00e-03 | failure | 2.72e+00 | 1.00e-03 | """ missing_md = raw"""| A | B | C | D | |-----------|---------|---------|---------| | 1.00e+00 | missing | missing | missing | | missing | 1 | a | missing | | 3.00e+00 | 3 | b | notmiss | """ missing_ltx = raw"""\begin{longtable}{rrrr} \hline A & B & C & D \\\hline \endfirsthead \hline A & B & C & D \\\hline \endhead \hline \multicolumn{4}{r}{{\bfseries Continued on next page}}\\ \hline \endfoot \endlastfoot \( 1.00\)e\(+00\) & & & missing \\ & \( 1\) & a & missing \\ \( 3.00\)e\(+00\) & \( 3\) & b & notmiss \\\hline \end{longtable} """
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
1981
using BenchmarkTools using LibGit2 using PkgBenchmark import Plots function test_pkgbmark() # When running breakage tests, don't run these tests if get(ENV, "CI", nothing) !== nothing && get(ENV, "GITHUB_REPOSITORY", "") != "JuliaSmoothOptimizers/SolverBenchmark.jl" return end results = PkgBenchmark.benchmarkpkg("SolverBenchmark", script = joinpath(@__DIR__, "bmark_suite.jl")) stats = bmark_results_to_dataframes(results) @info stats @test length(keys(stats)) == 2 @test :lu ∈ keys(stats) @test :qr ∈ keys(stats) @test size(stats[:lu]) == (10, 5) # 10 problems x (problem name + 4 PkgBenchmark measures) @test size(stats[:qr]) == (10, 5) p = profile_solvers(results) @test typeof(p) <: Plots.Plot costs = [df -> df[!, :time], df -> df[!, :memory], df -> df[!, :gctime] .+ 1, df -> df[!, :allocations]] p = profile_solvers(stats, costs, ["time", "memory", "gctime+1", "allocations"]) @test typeof(p) <: Plots.Plot repo = LibGit2.GitRepo(joinpath(@__DIR__, "..")) LibGit2.lookup_branch(repo, "main") === nothing && LibGit2.branch!(repo, "main", force = true) main = PkgBenchmark.benchmarkpkg( "SolverBenchmark", "main", script = joinpath(@__DIR__, "bmark_suite.jl"), ) judgement = PkgBenchmark.judge(results, main) stats = judgement_results_to_dataframes(judgement) @info stats @test length(keys(stats)) == 2 @test :lu ∈ keys(stats) @test :qr ∈ keys(stats) for k ∈ keys(stats) @test :target ∈ keys(stats[k]) @test :baseline ∈ keys(stats[k]) end for k ∈ keys(stats) for j ∈ keys(stats[k]) @test size(stats[k][j]) == (10, 5) end end p = profile_package(judgement) @test typeof(p) <: Dict{Symbol, Plots.Plot} costs = [df -> df[!, :time], df -> df[!, :memory], df -> df[!, :gctime] .+ 1, df -> df[!, :allocations]] p = profile_solvers(stats[:lu], costs, ["time", "memory", "gctime+1", "allocations"]) @test typeof(p) <: Plots.Plot end test_pkgbmark()
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
555
function test_profiles() stats = get_stats_data() # from data.jl @info "Generating performance profiles" @info "Cost: t" unicodeplots() p = performance_profile( stats, df -> df.t, b = SolverBenchmark.BenchmarkProfiles.UnicodePlotsBackend(), ) p = profile_solvers(stats, [df -> df.t, df -> df.iter], ["Time", "Iterations"]) if !Sys.isfreebsd() pgfplotsx() p = performance_profile( stats, df -> df.t, b = SolverBenchmark.BenchmarkProfiles.PGFPlotsXBackend(), ) end nothing end test_profiles()
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
352
# stdlib imports using LinearAlgebra using Printf using Random using Test # dependencies imports using DataFrames using LaTeXStrings # test dependencies using PGFPlotsX using UnicodePlots using Plots # this package using SolverBenchmark include("data.jl") include("tables.jl") include("profiles.jl") include("pkgbmark.jl") include("test_bmark.jl")
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
2727
# Test all table output function test_tables() example_folder = joinpath(@__DIR__, "example") stats = get_stats_data() # from data.jl include("output_results.jl") df = stats[:alpha] cols = [:status, :name, :f, :t, :iter] @testset "alpha results in latex format" begin header = Dict(:status => "flag", :f => "\\(f(x)\\)", :t => "time") io = IOBuffer() pretty_latex_stats(io, df[!, cols], hdr_override = header) @test all(chomp.(split(alpha_tex)) .== chomp.(split(String(take!(io))))) end @testset "alpha results in latex format with highlighting" begin header = Dict(:status => "flag", :f => "\\(f(x)\\)", :t => "time") hl = passfail_latex_highlighter(df) io = IOBuffer() pretty_latex_stats(io, df[!, cols], hdr_override = header, highlighters = hl) @test all(chomp.(split(alpha_hi_tex)) .== chomp.(split(String(take!(io))))) end @testset "alpha results in markdown format" begin header = Dict(:status => "flag", :f => "f(x)", :t => "time") fmts = Dict(:t => "%.2f") io = IOBuffer() pretty_stats(io, df[!, cols], col_formatters = fmts, hdr_override = header, tf = tf_markdown) @test all(chomp.(split(alpha_md)) .== chomp.(split(String(take!(io))))) end @testset "alpha results in unicode format" begin header = Dict(:status => "flag", :f => "f(x)", :t => "time") fmts = Dict(:t => "%.2f") io = IOBuffer() pretty_stats(io, df[!, cols], col_formatters = fmts, hdr_override = header) @test all(chomp.(split(alpha_txt)) .== chomp.(split(String(take!(io))))) end @testset "Show all table output for joined solver" begin df = join( stats, [:status, :f, :t], invariant_cols = [:name], hdr_override = Dict(:status => "flag"), ) println(df) end @testset "joined results in latex format" begin io = IOBuffer() pretty_latex_stats(io, df) @test all(chomp.(split(joined_tex)) .== chomp.(split(String(take!(io))))) end @testset "joined results in markdown format" begin io = IOBuffer() pretty_stats(io, df, tf = tf_markdown) @test all(chomp.(split(joined_md)) .== chomp.(split(String(take!(io))))) end @testset "missing values" begin df = DataFrame( A = [1.0, missing, 3.0], B = [missing, 1, 3], C = [missing, "a", "b"], D = [missing, missing, :notmiss], ) io = IOBuffer() pretty_stats(io, df, tf = tf_markdown) pretty_stats(stdout, df, tf = tf_markdown) println(missing_md) @test all(chomp.(split(missing_md)) .== chomp.(split(String(take!(io))))) io = IOBuffer() pretty_latex_stats(io, df) @test all(chomp.(split(missing_ltx)) .== chomp.(split(String(take!(io))))) end end test_tables()
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
code
2607
using DataFrames using Logging using NLPModels, ADNLPModels using SolverCore import SolverCore.dummy_solver mutable struct CallableSolver end function (solver::CallableSolver)(nlp::AbstractNLPModel; kwargs...) return GenericExecutionStats(nlp) end function test_bmark() @testset "Testing bmark" begin problems = [ ADNLPModel(x -> sum(x .^ 2), ones(2), name = "Quadratic"), ADNLPModel( x -> sum(x .^ 2), ones(2), x -> [sum(x) - 1], [0.0], [0.0], name = "Cons quadratic", ), ADNLPModel( x -> (x[1] - 1)^2 + 4 * (x[2] - x[1]^2)^2, ones(2), x -> [x[1]^2 + x[2]^2 - 1], [0.0], [0.0], name = "Cons Rosen", ), ] callable = CallableSolver() stats = solve_problems(dummy_solver, "dummy", problems) @test stats isa DataFrame stats = solve_problems(dummy_solver, "dummy", problems, reset_problem = false) stats = solve_problems(dummy_solver, "dummy", problems, reset_problem = true) solve_problems(callable, "callable", problems) solvers = Dict(:dummy => dummy_solver, :callable => callable) stats = bmark_solvers(solvers, problems) @test stats isa Dict{Symbol, DataFrame} for k in keys(solvers) @test haskey(stats, k) end # write stats to file filename = tempname() save_stats(stats, filename) # read stats from file stats2 = load_stats(filename) # check that they are the same for k ∈ keys(stats) @test k ∈ keys(stats2) @test stats[k] == stats2[k] end statuses, avgs = quick_summary(stats) pretty_stats(stats[:dummy]) end @testset "Testing logging" begin nlps = [ADNLPModel(x -> sum(x .^ k), ones(2k), name = "Sum of power $k") for k = 2:4] push!( nlps, ADNLPModel(x -> dot(x, x), ones(2), x -> [sum(x) - 1], [0.0], [0.0], name = "linquad"), ) with_logger(ConsoleLogger()) do @info "Testing simple logger on `solve_problems`" solve_problems(dummy_solver, "dummy", nlps) reset!.(nlps) @info "Testing logger with specific columns on `solve_problems`" solve_problems( dummy_solver, "dummy", nlps, colstats = [:name, :nvar, :elapsed_time, :objective, :dual_feas], ) reset!.(nlps) @info "Testing logger with hdr_override on `solve_problems`" hdr_override = Dict(:dual_feas => "‖∇L(x)‖", :primal_feas => "‖c(x)‖") solve_problems(dummy_solver, "dummy", nlps, info_hdr_override = hdr_override) reset!.(nlps) end end end test_bmark()
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
docs
5517
# SolverBenchmark.jl ## How to Cite If you use SolverBenchmark.jl in your work, please cite using the format given in [CITATION.cff](https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl/blob/main/CITATION.cff). [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.3948381.svg)](https://doi.org/10.5281/zenodo.3948381) ![CI](https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl/workflows/CI/badge.svg?branch=main) [![Build Status](https://api.cirrus-ci.com/github/JuliaSmoothOptimizers/SolverBenchmark.jl.svg)](https://cirrus-ci.com/github/JuliaSmoothOptimizers/SolverBenchmark.jl) [![](https://img.shields.io/badge/docs-stable-3f51b5.svg)](https://JuliaSmoothOptimizers.github.io/SolverBenchmark.jl/stable) [![](https://img.shields.io/badge/docs-dev-3f51b5.svg)](https://JuliaSmoothOptimizers.github.io/SolverBenchmark.jl/dev) [![codecov](https://codecov.io/gh/JuliaSmoothOptimizers/SolverBenchmark.jl/branch/main/graph/badge.svg?token=E0srGT31Xi)](https://codecov.io/gh/JuliaSmoothOptimizers/SolverBenchmark.jl) This package provides general tools for benchmarking solvers, focusing on the following guidelines: - The output of a solver's run on a suite of problems is a `DataFrame`, where each row is a different problem. - Since naming issues may arise (e.g., same problem with different number of variables), there must be an ID column; - The collection of two or more solver runs (`DataFrame`s), is a `Dict{Symbol,DataFrame}`, where each key is a solver; This package is developed focusing on [Krylov.jl](https://github.com/JuliaSmoothOptimizers/Krylov.jl) and [JSOSolvers.jl](https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl), but is sufficiently general to be used in other places. ## Example Obs: See the [assets](assets) folder for the complete code, or the [docs](https://JuliaSmoothOptimizers.github.io/SolverBenchmark.jl/latest) for a more detailed example. ### Example table of a single `DataFrame` `pretty_stats(df)` ``` ┌─────────────┬─────────┬───────────┬───────────┬────────┐ │ flag │ name │ f(x) │ time │ iter │ ├─────────────┼─────────┼───────────┼───────────┼────────┤ │ failure │ prob001 │ -6.89e-01 │ 6.24e+01 │ 70 │ │ failure │ prob002 │ -7.63e-01 │ 3.53e+02 │ 10 │ │ first_order │ prob003 │ 3.97e-01 │ 7.68e+02 │ 10 │ │ first_order │ prob004 │ 8.12e-01 │ 4.31e+01 │ 80 │ │ first_order │ prob005 │ -3.46e-01 │ 2.68e+02 │ 30 │ │ first_order │ prob006 │ -1.88e-01 │ 6.68e+01 │ 80 │ │ first_order │ prob007 │ -1.61e+00 │ 1.57e+02 │ 60 │ │ first_order │ prob008 │ -2.48e+00 │ 6.05e+02 │ 40 │ │ first_order │ prob009 │ 2.28e+00 │ 1.36e+02 │ 40 │ │ failure │ prob010 │ 2.20e-01 │ 8.38e+02 │ 50 │ └─────────────┴─────────┴───────────┴───────────┴────────┘ ``` `pretty_latex_stats(df)` ![](assets/alpha.svg) ### Example table of a joined `DataFrame` ``` df = join(stats, [:status, :f, :t], ...) pretty_stats(df, tf=markdown) ``` ``` | id | name | flag_alpha | f_alpha | t_alpha | flag_beta | f_beta | t_beta | flag_gamma | f_gamma | t_gamma | |--------|---------|-------------|-----------|-----------|-------------|-----------|-----------|-------------|-----------|-----------| | 1 | prob001 | failure | -6.89e-01 | 6.24e+01 | first_order | -4.83e-01 | 3.92e+02 | failure | -9.99e-01 | 6.97e+02 | | 2 | prob002 | failure | -7.63e-01 | 3.53e+02 | first_order | -1.16e+00 | 4.79e+02 | first_order | 1.03e+00 | 4.35e+02 | | 3 | prob003 | first_order | 3.97e-01 | 7.68e+02 | first_order | -2.14e-01 | 6.82e+01 | first_order | -1.16e+00 | 9.86e+02 | | 4 | prob004 | first_order | 8.12e-01 | 4.31e+01 | first_order | -1.37e+00 | 4.80e+02 | first_order | 5.34e-01 | 9.97e+02 | | 5 | prob005 | first_order | -3.46e-01 | 2.68e+02 | first_order | -1.54e+00 | 4.68e+02 | first_order | -3.08e-01 | 5.08e+02 | | 6 | prob006 | first_order | -1.88e-01 | 6.68e+01 | first_order | -1.23e+00 | 4.52e+02 | first_order | 9.86e-01 | 2.16e+02 | | 7 | prob007 | first_order | -1.61e+00 | 1.57e+02 | first_order | -1.96e+00 | 6.44e+02 | first_order | -1.19e+00 | 8.59e+02 | | 8 | prob008 | first_order | -2.48e+00 | 6.05e+02 | failure | -4.73e-01 | 6.69e+02 | first_order | 6.80e-01 | 9.05e+02 | | 9 | prob009 | first_order | 2.28e+00 | 1.36e+02 | first_order | 1.34e+00 | 9.48e+01 | failure | 2.04e-03 | 4.35e+02 | | 10 | prob010 | failure | 2.20e-01 | 8.38e+02 | first_order | 8.08e-01 | 9.49e+02 | first_order | -4.78e-01 | 6.59e+01 | ``` `pretty_latex_stats(df)` ![](assets/joined.svg) ### Example profile `p = performance_profile(stats, df->df.t)` ![](assets/profile1.svg) ### Example profile-wall `p = profile_solvers(stats, costs, titles)` ![](assets/profile2.svg) ## Bug reports and discussions If you think you found a bug, feel free to open an [issue](https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl/issues). Focused suggestions and requests can also be opened as issues. Before opening a pull request, start an issue or a discussion on the topic, please. If you want to ask a question not suited for a bug report, feel free to start a discussion [here](https://github.com/JuliaSmoothOptimizers/Organization/discussions). This forum is for general discussion about this repository and the [JuliaSmoothOptimizers](https://github.com/JuliaSmoothOptimizers) organization, so questions about any of our packages are welcome.
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
docs
1726
# [SolverBenchmark.jl documentation](@id Home) This package provides general tools for benchmarking solvers, focusing on a few guidelines: - The output of a solver's run on a suite of problems is a `DataFrame`, where each row is a different problem. - Since naming issues may arise (e.g., same problem with different number of variables), there must be an ID column; - The collection of two or more solver runs (`DataFrame`s), is a `Dict{Symbol,DataFrame}`, where each key is a solver; This package is developed focusing on [Krylov.jl](https://github.com/JuliaSmoothOptimizers/Krylov.jl) and [JSOSolvers.jl](https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl), but they should be general enough to be used in other places. ## Bug reports and discussions If you think you found a bug, feel free to open an [issue](https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl/issues). Focused suggestions and requests can also be opened as issues. Before opening a pull request, start an issue or a discussion on the topic, please. If you want to ask a question not suited for a bug report, feel free to start a discussion [here](https://github.com/JuliaSmoothOptimizers/Organization/discussions). This forum is for general discussion about this repository and the [JuliaSmoothOptimizers](https://github.com/JuliaSmoothOptimizers) organization, so questions about any of our packages are welcome. # Tutorials You can access more tutorials regarding [SolverBenchmark.jl](https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl) on the JuliaSmoothOptimizers website [jso.dev](https://jso.dev), for instance, an [Introduction to SolverBenchmark](https://jso.dev/tutorials/introduction-to-solverbenchmark/).
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MPL-2.0" ]
0.6.1
c70c1123e2ae0a7c441f7719e369d3d3ef8f90a4
docs
168
# Reference ​ ## Contents ​ ```@contents Pages = ["reference.md"] ``` ​ ## Index ​ ```@index Pages = ["reference.md"] ``` ​ ```@autodocs Modules = [SolverBenchmark] ```
SolverBenchmark
https://github.com/JuliaSmoothOptimizers/SolverBenchmark.jl.git
[ "MIT" ]
0.2.6
7a89075c252d95cd9530f937158955939c218425
code
345
module PrincipalMomentAnalysisApp export pmaapp using PrincipalMomentAnalysis using LinearAlgebra using DataFrames using CSV using Statistics using Blink using JSExpr using Colors using PlotlyJS import IterTools using SparseArrays include("Schedulers.jl") using .Schedulers include("pmaplots.jl") include("pca.jl") include("app.jl") end
PrincipalMomentAnalysisApp
https://github.com/PrincipalMomentAnalysis/PrincipalMomentAnalysisApp.jl.git
[ "MIT" ]
0.2.6
7a89075c252d95cd9530f937158955939c218425
code
17168
module Schedulers using DataStructures export Scheduler, JobStatusChange, PropagatedError, JobID, createjob!, deletejob!, add_dependency!, remove_dependency!, set_dependency!, setfunction!, setresult!, schedule!, cancel!, cancelall!, iscanceled, wantstorun, isactive, step!, status, statusstring, jobstatus, jobname const JobID = Int const Timestamp = Int const Callback = Union{Function,Nothing} struct JobStatus # TODO: rename changedAt::Threads.Atomic{Timestamp} runAt::Timestamp # i.e. the value of changedAt when the job was run end mutable struct Job changedAt::Threads.Atomic{Timestamp} # Only set by Scheduler thread. Can be read by other threads. name::String # Only used in error/log messages. Set once. f::Union{Function,Nothing} spawn::Bool edges::Dict{String,JobID} # name=>fromID edgesReverse::Set{Tuple{JobID,String}} # Set{(toID,name)} result::Any status::Symbol # one of :notstarted,:waiting,:spawned,:running,:done,:errored statusChangedTime::UInt64 # from time_ns() runAt::Timestamp waitingFor::Set{JobID} callbacks::Vector{Function} end Job(changedAt::Int, name::String, f::Union{Function,Nothing}, spawn::Bool, result, status::Symbol, runAt::Timestamp) = Job(Threads.Atomic{Int}(changedAt), name, f, spawn, Dict{String,JobID}(), Set{Tuple{JobID,String}}(), result, status, time_ns(), runAt, Set{JobID}(), []) Job(name::String, f::Function, changedAt::Int, spawn::Bool) = Job(changedAt, name, f, spawn, nothing, :notstarted, -1) Job(name::String, result::Any, changedAt::Int, spawn::Bool) = Job(changedAt, name, nothing, spawn, result, result2status(result), changedAt) struct DetachedJob jobID::JobID runAt::Timestamp end struct JobStatusChange jobID::JobID jobName::String status::Symbol time::UInt64 message::String end JobStatusChange(jobID::JobID,job::Job) = JobStatusChange(jobID, job.name, job.status, job.statusChangedTime, job.status==:errored ? sprint(showerror,job.result) : "") struct Scheduler threaded::Bool timestamp::Ref{Timestamp} jobCounter::Threads.Atomic{JobID} jobs::Dict{JobID,Job} actions::Channel{Function} slowActions::Channel{Function} dirtyJobs::Vector{JobID} activeJobs::Set{JobID} detachedJobs::Dict{DetachedJob, UInt64} # -> time_ns() when job started running hasSpawned::Ref{Bool} statusChannel::Union{Channel{JobStatusChange},Nothing} verbose::Bool end function Scheduler(;threaded=Threads.nthreads()>1, statusChannel=nothing, verbose=false) threaded && Threads.nthreads()==1 && @warn "Trying to run threaded Scheduler, but threading is not enabled, please set the environment variable JULIA_NUM_THREADS to the desired number of threads." Scheduler(threaded, Ref(0), Threads.Atomic{JobID}(1), Dict{JobID,Job}(), Channel{Function}(Inf), Channel{Function}(Inf), [], Set{JobID}(), Dict{DetachedJob,UInt64}(), Ref(false), statusChannel, verbose) end struct PropagatedError{T<:Exception} <: Exception e::T jobName::String inputName::String end errorchain(io::IO, e::Exception) = showerror(io,e) errorchain(io::IO, e::PropagatedError) = (print(io, e.inputName, '[', e.jobName, "]<--"); errorchain(io, e.e)) Base.showerror(io::IO, e::PropagatedError) = (print(io::IO, "Propagated error: "); errorchain(io,e)) # --- exported functions --- function createjob!(s::Scheduler, result::Any, args::Pair{JobID,String}...; spawn::Bool=true, name::Union{String,Nothing}=nothing) id = newjobid!(s) name = name==nothing ? "AnonymousJob#$id" : name addaction!(s->_createjob!(s,id,result,name,spawn), s) for (fromID,toName) in args add_dependency!(s, fromID=>(id,toName)) end id end createjob!(f::Function, s::Scheduler, args::Pair{JobID,String}...; name=string(f), kwargs...) = createjob!(s, f, args...; name=name, kwargs...) deletejob!(s::Scheduler, jobID::JobID) = addaction!(s->_deletejob!(s,jobID), s) add_dependency!( s::Scheduler, dep::Pair{JobID,Tuple{JobID,String}}) = addaction!(s-> add_edge!(s,dep), s) remove_dependency!(s::Scheduler, dep::Pair{JobID,Tuple{JobID,String}}) = addaction!(s->remove_edge!(s,dep), s) set_dependency!(s::Scheduler, dep::Pair{JobID,Tuple{JobID,String}}) = addaction!(s-> set_edge!(s,dep), s) setfunction!(f::Function, s::Scheduler, jobID::JobID) = addaction!(s->_setfunction!(s,jobID,f), s) setresult!(s::Scheduler, jobID::JobID, result::Any) = addaction!(s->_setresult!(s,jobID,result), s) schedule!(callback::Callback, s::Scheduler, jobID::JobID) = addaction!(s->_schedule!(s,jobID,callback), s) schedule!(s::Scheduler, jobID::JobID) = schedule!(nothing,s,jobID) cancel!(s::Scheduler, jobID::JobID) = addaction!(s->_cancel!(s,jobID),s) cancelall!(s::Scheduler) = addaction!(s) do s for jobID in keys(s.jobs) _cancel!(s, jobID) end end iscanceled(jobStatus::JobStatus) = jobStatus.changedAt[] > jobStatus.runAt wantstorun(s::Scheduler) = isready(s.actions) || isready(s.slowActions) function step!(s::Scheduler) while isready(s.actions) take!(s.actions)(s) end s.hasSpawned[] = false # TODO: revise this solution while !s.hasSpawned[] && isready(s.slowActions) # at most one slow spawning job per step take!(s.slowActions)(s) end updatetimestamps!(s) end isactive(s::Scheduler) = !isempty(s.activeJobs) function status(s::Scheduler) # Running (A[2s], B[3s], ...), Detached Running (...), Spawned (C[0.1s], D [...), Waiting (...) now = time_ns() running = Tuple{String,Float64}[] detached = Tuple{String,Float64}[] spawned = Tuple{String,Float64}[] waiting = Tuple{String,Float64}[] for jobID in s.activeJobs job = s.jobs[jobID] job.status == :running && push!(running,(job.name,(now-job.statusChangedTime)/1e9)) job.status == :spawned && push!(spawned,(job.name,(now-job.statusChangedTime)/1e9)) job.status == :waiting && push!(waiting,(job.name,(now-job.statusChangedTime)/1e9)) end for (detachedJob,jobStartTime) in s.detachedJobs jobName = "Unknown" haskey(s.jobs, detachedJob.jobID) && (jobName = s.jobs[detachedJob.jobID].name) push!(detached, (jobName,(now-jobStartTime)/1e9)) end running, detached, spawned, waiting end function statusstring(s::Scheduler; delim=", ") running, detached, spawned, waiting = status(s) strs = String[] isempty(running) || push!(strs, string("Running (", join(_durationstring.(running), ", "), ")")) isempty(detached) || push!(strs, string("Detached (", join(_durationstring.(detached), ", "), ")")) isempty(spawned) || push!(strs, string("Spawned (", join(_durationstring.(spawned), ", "), ")")) isempty(waiting) || push!(strs, string("Waiting (", join(_durationstring.(waiting), ", "), ")")) join(strs, delim) end """ jobstatus(s::Scheduler, jobID::JobID) Returns one of :doesntexist, :notstarted, :waiting, :spawned, :running, :done, :errored """ jobstatus(s::Scheduler, jobID::JobID) = haskey(s.jobs, jobID) ? s.jobs[jobID].status : :doesntexist jobname(s::Scheduler, jobID::JobID) = haskey(s.jobs, jobID) ? s.jobs[jobID].name : "Unknown" # --- internal functions --- result2status(::Any) = :done result2status(::Exception) = :errored function _setstatus!(s::Scheduler, jobID::JobID, job::Job, status::Symbol, statusChangedTime::UInt64=time_ns()) if status in (:notstarted,:doesntexist) && job.status in (:running,:spawned) job.status==:running && @warn "Detaching running job $(job.name)" s.detachedJobs[DetachedJob(jobID,job.runAt)] = job.statusChangedTime end wasActive = job.status in (:waiting,:spawned,:running) isActive = status in (:waiting,:spawned,:running) job.status = status job.statusChangedTime = statusChangedTime wasActive && !isActive && pop!(s.activeJobs, jobID) isActive && !wasActive && push!(s.activeJobs, jobID) s.statusChannel!=nothing && put!(s.statusChannel, JobStatusChange(jobID, job)) nothing end _durationstring(t::Tuple{String,Float64}, digits=1) = string(t[1], '[', round(t[2],digits=digits), "s]") newjobid!(s::Scheduler) = Threads.atomic_add!(s.jobCounter, 1) newtimestamp!(s::Scheduler) = s.timestamp[]+=1 addaction!(action::Function, s::Scheduler; slow::Bool=false) = (put!(slow ? s.slowActions : s.actions, action); nothing) function _createjob!(s::Scheduler, jobID::JobID, x, name::String, spawn::Bool) job = Job(name, x, newtimestamp!(s), spawn) s.jobs[jobID] = job _setstatus!(s, jobID, job, job.status) nothing end function _deletejob!(s::Scheduler, jobID::JobID) @assert haskey(s.jobs, jobID) "Trying to delete nonexisting job with id $(jobID)" # remove dependencies job = s.jobs[jobID] for (name,fromID) in job.edges remove_edge!(s, fromID=>(jobID,name)) end for (toID,name) in job.edgesReverse remove_edge!(s, jobID=>(toID,name)) end _setstatus!(s, jobID, job, :doesntexist) # ensures removal from active jobs and detaching if needed delete!(s.jobs, jobID) nothing end function _setfunction!(s::Scheduler, jobID::JobID, f::Function) @assert haskey(s.jobs, jobID) "Trying to update nonexisting job with id $(jobID)" job = s.jobs[jobID] job.f = f setdirty!(s, jobID) nothing end function _setresult!(s::Scheduler, jobID::JobID, result::Any) @assert haskey(s.jobs, jobID) "Trying to update nonexisting job with id $(jobID)" job = s.jobs[jobID] @assert job.f == nothing result==job.result && return nothing # Nothing to do. setdirty!(s, jobID) updatetimestamps!(s) @assert job.status == :notstarted job.result = result _setstatus!(s, jobID, job, result2status(result)) nothing end _schedule!(callback::Function, s::Scheduler, jobID::JobID, scheduledAt::Timestamp) = _schedule!(s,jobID,callback,scheduledAt) function _schedule!(s::Scheduler, jobID::JobID, callback::Callback, scheduledAt::Timestamp = s.timestamp[]) @assert haskey(s.jobs, jobID) "Trying to schedule nonexisting job with id $jobID" updatetimestamps!(s) job = s.jobs[jobID] changedAt = job.changedAt[] scheduledAt < changedAt && return # Scheduling out of date. slow = !job.spawn if job.runAt < changedAt # the job needs to run at a later timestamp than what has been run before @assert job.status == :notstarted job.runAt = changedAt _setstatus!(s, jobID, job, :waiting) empty!(job.callbacks) # figure out which jobs we are waiting for to finish waitingFor = Set{JobID}() # NB: do not reuse old set as it might be referenced from old dependency callbacks! for e in job.edges fromID = e[2] if s.jobs[fromID].result == nothing push!(waitingFor, fromID) _schedule!(s, fromID, scheduledAt) do x delete!(waitingFor,fromID) isempty(waitingFor) && addaction!(s->_spawn!(s,jobID,scheduledAt),s; slow=slow) end end end job.waitingFor = waitingFor s.verbose && @info "$(job.name) waiting for $(length(job.waitingFor)) jobs to finish." end @assert job.runAt == changedAt callback != nothing && push!(job.callbacks, callback) isempty(job.waitingFor) && addaction!(s->_spawn!(s,jobID,scheduledAt),s; slow=slow) nothing end function _setstatustorunning!(s::Scheduler, jobID::JobID, runAt::Timestamp, statusChangedTime::UInt64) haskey(s.jobs, jobID) || return # nothing to do if the job was deleted before it finished job = s.jobs[jobID] runAt < job.changedAt[] && return # nothing to do @assert job.status == :spawned _setstatus!(s, jobID, job, :running, statusChangedTime) nothing end function _spawn!(s::Scheduler, jobID::JobID, scheduledAt::Timestamp) haskey(s.jobs, jobID) || return # nothing to do if the job was deleted before it finished updatetimestamps!(s) job = s.jobs[jobID] changedAt = job.changedAt[] scheduledAt < changedAt && return # Spawned after dependency was finished, but now out of date. if job.status in (:done, :errored) job.result != nothing && _finish!(s, jobID, job.runAt, job.result, time_ns()) elseif job.status == :waiting @assert isempty(job.waitingFor) s.verbose && @info "Spawning $(job.name) ($jobID@$changedAt)" s.hasSpawned[] = true inputs = getinput(s,jobID) _setstatus!(s, jobID, job, :spawned) f = job.f if s.threaded && job.spawn Threads.@spawn runjob!(s, jobID, job.name, job.changedAt, changedAt, f, inputs) else runjob!(s, jobID, job.name, job.changedAt, changedAt, f, inputs) end end nothing end function _cancel!(s::Scheduler, jobID::JobID) @assert haskey(s.jobs, jobID) "Trying to cancel nonexisting job with id $jobID" updatetimestamps!(s) job = s.jobs[jobID] job.result == nothing && setdirty!(s, jobID) # Do not invalidate jobs that have finished! end function _finish!(s::Scheduler, jobID::JobID, runAt::Timestamp, result::Any, statusChangedTime::UInt64) if haskey(s.jobs, jobID) updatetimestamps!(s) job = s.jobs[jobID] changedAt = job.changedAt[] if changedAt == runAt # we finished the last version of the job @assert job.status in (:running,:done,:errored) job.result = result _setstatus!(s, jobID, job, result2status(result), statusChangedTime) for callback in job.callbacks callback(job.result) end empty!(job.callbacks) result isa Exception && throw(result) return end end # if we reach here, the job was either deleted or we finished running an old version of the job pop!(s.detachedJobs, DetachedJob(jobID,runAt)) # remove from list of detached jobs nothing end function getinput(s::Scheduler, jobID::JobID) job = s.jobs[jobID] Dict{String,Any}((name=>s.jobs[inputJobID].result) for (name,inputJobID) in job.edges) end function add_edge!(s::Scheduler, dep::Pair{JobID,Tuple{JobID,String}}) fromID,(toID,toName) = dep @assert haskey(s.jobs, toID) "Trying to add edge to nonexisting job with id $(toID)" @assert haskey(s.jobs, fromID) "Trying to add edge from nonexisting job with id $(fromID)" from,to = s.jobs[fromID], s.jobs[toID] @assert !haskey(to.edges, toName) "Trying to add edge \"$toName\" that already exists in job with id ($toID)" to.edges[toName] = fromID push!(from.edgesReverse, (toID,toName)) setdirty!(s, toID) nothing end function remove_edge!(s::Scheduler, dep::Pair{JobID,Tuple{JobID,String}}) fromID,(toID,toName) = dep @assert haskey(s.jobs, toID) "Trying to remove edge to nonexisting job with id $(toID)" @assert haskey(s.jobs, fromID) "Trying to remove edge from nonexisting job with id $(fromID)" from,to = s.jobs[fromID], s.jobs[toID] # we don't allow removing edges that doesn't exist @assert haskey(to.edges, toName) "Trying to remove edge \"$toName\" that doesn't exists in job with id ($toID)" @assert to.edges[toName]==fromID delete!(to.edges, toName) delete!(from.edgesReverse, (toID,toName)) setdirty!(s, toID) nothing end function set_edge!(s::Scheduler, dep::Pair{JobID,Tuple{JobID,String}}) fromID,(toID,toName) = dep @assert haskey(s.jobs, toID) "Trying to replace edge to nonexisting job with id $(toID)" @assert haskey(s.jobs, fromID) "Trying to replace (remove) edge from nonexisting job with id $(fromID)" from,to = s.jobs[fromID], s.jobs[toID] if haskey(to.edges, toName) prevFromID = to.edges[toName] prevFromID == fromID && return remove_edge!(s, prevFromID=>(toID,toName)) end add_edge!(s, dep) nothing end function setdirty!(s::Scheduler, jobID::JobID) job = s.jobs[jobID] job.changedAt[] = newtimestamp!(s) push!(s.dirtyJobs, jobID) nothing end function updatetimestamprec!(s::Scheduler, jobID::JobID) haskey(s.jobs, jobID) || return # happens if the job was deleted job = s.jobs[jobID] changedAt = job.changedAt[] _setstatus!(s, jobID, job, :notstarted) job.result = nothing for (toID,name) in job.edgesReverse toJob = s.jobs[toID] Threads.atomic_max!(toJob.changedAt,changedAt) < changedAt && updatetimestamprec!(s,toID) end end function updatetimestamps!(s::Scheduler) while !isempty(s.dirtyJobs) # go through in reverse order to minimize changes to dependency graph updatetimestamprec!(s,pop!(s.dirtyJobs)) end end function runjob!(s::Scheduler, jobID::JobID, jobName::String, changedAt::Threads.Atomic{Timestamp}, runAt::Timestamp, f::Function, input::Dict{String,Any}) jobStatus = JobStatus(changedAt, runAt) result = nothing if !iscanceled(jobStatus) # ensure the job was not changed after it was scheduled try s.verbose && @info "Running $jobName ($jobID@$runAt) with $(length(input)) parameter(s) in thread $(Threads.threadid())." jobStartTime = time_ns() addaction!(s->_setstatustorunning!(s,jobID,runAt,jobStartTime), s) # sanity check input and propagate errors for (name,v) in input @assert v != nothing "Job \"$jobName\" input \"$name\" has not been computed." v isa Exception && throw(PropagatedError(v,jobName,name)) end result = f(jobStatus, input) dur = round((time_ns()-jobStartTime)/1e9,digits=1) isCanceled = iscanceled(jobStatus) detachedStr = isCanceled ? " (detached job)" : "" s.verbose && @info "Finished running$detachedStr $jobName[$(dur)s] ($jobID@$runAt) in thread $(Threads.threadid())." isCanceled || @assert result!=nothing "Job $jobName returned nothing" catch err if !(err isa PropagatedError) @warn "Job $jobName ($jobID@$runAt) failed" showerror(stdout, err, catch_backtrace()) end result = err end end statusChangedTime = time_ns() addaction!(s->_finish!(s,jobID,runAt,result,statusChangedTime), s) result isa Exception && throw(result) nothing end end
PrincipalMomentAnalysisApp
https://github.com/PrincipalMomentAnalysis/PrincipalMomentAnalysisApp.jl.git
[ "MIT" ]
0.2.6
7a89075c252d95cd9530f937158955939c218425
code
19117
struct JobGraph scheduler::Scheduler sampleStatus::Ref{String} fileIOLock::ReentrantLock paramIDs::Dict{String,JobID} loadSampleID::JobID normalizeID::JobID setupSimplicesID::JobID dimreductionID::JobID makeplotID::JobID exportSingleID::JobID exportMultipleID::JobID end struct SampleData data::Matrix sa::DataFrame va::DataFrame end SampleData() = SampleData(zeros(0,0),DataFrame(),DataFrame(),"") struct ReducedSampleData F::Factorization sa::DataFrame va::DataFrame end guesslastsampleannot(df::DataFrame) = something(findlast(j->!(eltype(df[!,j])<:Union{Real,Missing}), 1:size(df,2)), 1) # a reasonable guess for which column to use as the last sample annotation getdelim(filepath::String) = lowercase(splitext(filepath)[2])==".csv" ? ',' : '\t' loadcsv(filepath::String; delim, transpose::Bool=false) = CSV.read(filepath, DataFrame; delim=delim, transpose=transpose, ntasks=1) # ntasks=1 might prevent crashes on some systems??? function loadsample(st, input::Dict{String,Any})::DataFrame @assert length(input)==2 filepath = input["filepath"]::String rowsAsSamples = parse(Bool,input["rowsassamples"]) filepath == :__INVALID__ && return Nothing filepath::String isempty(filepath) && return Nothing @assert isfile(filepath) "Sample file not found: \"$filepath\"" df = loadcsv(filepath; delim=getdelim(filepath), transpose=!rowsAsSamples) @assert size(df,2)>1 "Invalid data set. Must contain at least one sample annotation and one variable." @assert guesslastsampleannot(df)<size(df,2) "Invalid data set. Numerical data (variables) must come after sample annotations." df end # callback function function showsampleannotnames(df::DataFrame, toGUI) indLastSampleAnnot = guesslastsampleannot(df) put!(toGUI, :displaysampleannotnames=>(names(df)[1:min(max(indLastSampleAnnot+10,40),end)], indLastSampleAnnot)) end function normalizesample(st, input::Dict{String,Any}) @assert length(input)==5 df = input["dataframe"] method = input["method"] lastSampleAnnot = input["lastsampleannot"] logTransform = parse(Bool,input["logtransform"]) logTransformOffset = parse(Float64, input["logtransformoffset"]) @assert method in ("None", "Mean=0", "Mean=0,Std=1") nbrSampleAnnots = findfirst(x->string(x)==lastSampleAnnot, names(df)) @assert nbrSampleAnnots != nothing "Couldn't find sample annotation: \"$lastSampleAnnot\"" sa = df[:, 1:nbrSampleAnnots] va = DataFrame(VariableId=propertynames(df)[nbrSampleAnnots+1:end]) originalData = Matrix(df[!,nbrSampleAnnots+1:end])' @assert eltype(originalData) <: Union{Number,Missing} if logTransform @assert all(x->x>-logTransformOffset, skipmissing(originalData)) "Data contains negative values, cannot log-transform." originalData .= log2.(originalData.+logTransformOffset) end data = zeros(size(originalData)) if any(ismissing,originalData) # Replace missing values with mean over samples with nonmissing data @info "Reconstructing missing values (taking the mean over all nonmissing samples)" for i=1:size(data,1) m = ismissing.(originalData[i,:]) data[i,.!m] .= originalData[i,.!m] reconstructed = mean(originalData[i,.!m]) data[i,m] .= isnan(reconstructed) ? 0.0 : reconstructed end else data .= originalData # just copy end @assert all(!isnan, data) "Input data cannot contain NaNs. Use empty cells for missing values." X = data if method == "Mean=0,Std=1" X = normalizemeanstd!(X) elseif method == "Mean=0" X = normalizemean!(X) end SampleData(X,sa,va) end function setupsimplices(st, input::Dict{String,Any}) @assert length(input)==6 sampleData = input["sampledata"] method = Symbol(input["method"]) sampleAnnot = Symbol(input["sampleannot"]) timeAnnot = Symbol(input["timeannot"]) kNN = parse(Int,input["knearestneighbors"]) distNN = parse(Float64, input["distnearestneighbors"]) @assert method in (:SA,:Time,:NN,:NNSA) local G, description if method == :SA G = groupsimplices(sampleData.sa[!,sampleAnnot]) description = "GroupBy=$sampleAnnot" elseif method == :Time eltype(sampleData.sa[!,timeAnnot])<:Number || @warn "Expected time annotation to contain numbers, got $(eltype(sampleData.sa[!,timeAnnot])). Fallback to default sorting." G = timeseriessimplices(sampleData.sa[!,timeAnnot], groupby=sampleData.sa[!,sampleAnnot]) description = "Time=$timeAnnot, GroupBy=$sampleAnnot" elseif method == :NN G = neighborsimplices(sampleData.data; k=kNN, r=distNN, dim=50) description = "Nearest Neighbors k=$kNN, r=$distNN" elseif method == :NNSA G = neighborsimplices(sampleData.data; k=kNN, r=distNN, dim=50, groupby=sampleData.sa[!,sampleAnnot]) description = "Nearest Neighbors k=$kNN, r=$distNN, GroupBy=$sampleAnnot" end G, description end function dimreduction(st, input::Dict{String,Any}) @assert length(input)==3 sampleData = input["sampledata"] sampleSimplices = input["samplesimplices"][1] method = Symbol(input["method"]) X = sampleData.data::Matrix{Float64} # dim = 3 dim = min(10, size(X)...) if method==:PMA F = pma(X, sampleSimplices, nsv=dim) elseif method==:PCA F = svdbyeigen(X,nsv=dim) end ReducedSampleData(F, sampleData.sa, sampleData.va) end function makeplot(st, input::Dict{String,Any}) @assert length(input)==17 reduced = input["reduced"]::ReducedSampleData dimReductionMethod = Symbol(input["dimreductionmethod"]) sampleAnnot = Symbol(input["sampleannot"]) sampleSimplices, sampleSimplexDescription = input["samplesimplices"] xaxis = parse(Int,input["xaxis"]) yaxis = parse(Int,input["yaxis"]) zaxis = parse(Int,input["zaxis"]) plotWidth = parse(Int,input["plotwidth"]) plotHeight = parse(Int,input["plotheight"]) showPoints = parse(Bool,input["showpoints"]) showLines = parse(Bool,input["showlines"]) showTriangles = parse(Bool,input["showtriangles"]) markerSize = parse(Float64,input["markersize"]) lineWidth = parse(Float64,input["linewidth"]) triangleOpacity = parse(Float64,input["triangleopacity"]) colorByMethod = Symbol(input["colorby"]) colorAnnot = Symbol(input["colorannot"]) # shapeByMethod = Symbol(input["shapeby"]) # shapeAnnot = Symbol(input["shapeannot"]) title = "$dimReductionMethod - $sampleSimplexDescription" colorByMethod == :Auto && (colorAnnot=sampleAnnot) colorBy = colorByMethod == :None ? repeat([""],size(reduced.sa,1)) : reduced.sa[!,colorAnnot] colorDict = (eltype(colorBy) <: Real) ? nothing : colordict(colorBy) shapeBy, shapeDict = nothing, nothing # if shapeByMethod == :Custom # shapeBy = reduced.sa[!,shapeAnnot] # shapeDict = shapedict(shapeBy) # end # TODO: handle missing values in sample annotations? dims = [xaxis, yaxis, zaxis] plotArgs = plotsimplices(reduced.F.V[:,dims],sampleSimplices,colorBy,colorDict, title=title, drawPoints=showPoints, drawLines=showLines, drawTriangles=showTriangles, opacity=triangleOpacity, markerSize=markerSize, lineWidth=lineWidth, shapeBy=shapeBy, shapeDict=shapeDict, xLabel=string("PMA",xaxis), yLabel=string("PMA",yaxis), zLabel=string("PMA",zaxis)) plotArgs, plotWidth, plotHeight end showplot(data, toGUI::Channel) = put!(toGUI, :displayplot=>data) function exportsingle(st, input::Dict{String,Any}) @assert length(input)==5 reduced = input["reduced"]::ReducedSampleData mode = Symbol(input["mode"]) filepath = input["filepath"] sortMode = Symbol(input["sort"]) dim = parse(Int,input["dim"]) @assert mode in (:Variables, :Samples) @assert sortMode in (:Abs, :Descending, :Ascending, :Original) colName = Symbol("PMA",dim) if mode == :Variables df = copy(reduced.va) df[!,colName] = reduced.F.U[:,dim] else df = copy(reduced.sa[!,1:1]) df[!,colName] = reduced.F.V[:,dim] end if sortMode==:Abs sort!(df, colName, by=abs, rev=true) elseif sortMode==:Descending sort!(df, colName, rev=true) elseif sortMode==:Ascending sort!(df, colName) end CSV.write(filepath, df, delim=getdelim(filepath)) end function exportmultiple(st, input::Dict{String,Any}) @assert length(input)==4 reduced = input["reduced"]::ReducedSampleData mode = Symbol(input["mode"]) filepath = input["filepath"] dim = parse(Int,input["dim"]) @assert mode in (:Variables, :Samples) if mode == :Variables df = copy(reduced.va) PMAs = reduced.F.U else df = copy(reduced.sa[!,1:1]) PMAs = reduced.F.V end for d in 1:dim df[!,Symbol("PMA",d)] = PMAs[:,d] end CSV.write(filepath, df, delim=getdelim(filepath)) end function samplestatus(jg::JobGraph) status = jobstatus(jg.scheduler, jg.loadSampleID) status==:done && return "Sample loaded." status in (:waiting,:running) && return "Loading sample." "Please load sample." end function setsamplestatus(jg::JobGraph, toGUI::Channel) sampleStatus = samplestatus(jg) sampleStatus!=jg.sampleStatus[] && put!(toGUI, :samplestatus=>sampleStatus) jg.sampleStatus[] = sampleStatus end function JobGraph(;verbose=false) scheduler = Scheduler(verbose=verbose) # scheduler = Scheduler(threaded=false, verbose=verbose) # For DEBUG # Data Nodes (i.e. parameters chosen in the GUI) paramIDs = Dict{String,JobID}() loadSampleID = createjob!(loadsample, scheduler, getparamjobid(scheduler,paramIDs,"samplefilepath")=>"filepath", getparamjobid(scheduler,paramIDs,"loadrowsassamples")=>"rowsassamples") normalizeID = createjob!(normalizesample, scheduler, loadSampleID=>"dataframe", getparamjobid(scheduler,paramIDs,"lastsampleannot")=>"lastsampleannot", getparamjobid(scheduler,paramIDs,"normalizemethod")=>"method", getparamjobid(scheduler,paramIDs,"logtransform")=>"logtransform", getparamjobid(scheduler,paramIDs,"logtransformoffset")=>"logtransformoffset") setupSimplicesID = createjob!(setupsimplices, scheduler, normalizeID=>"sampledata", getparamjobid(scheduler,paramIDs,"samplesimplexmethod")=>"method", getparamjobid(scheduler,paramIDs,"sampleannot")=>"sampleannot", getparamjobid(scheduler,paramIDs,"timeannot")=>"timeannot", getparamjobid(scheduler,paramIDs,"knearestneighbors")=>"knearestneighbors", getparamjobid(scheduler,paramIDs,"distnearestneighbors")=>"distnearestneighbors") dimreductionID = createjob!(dimreduction, scheduler, normalizeID=>"sampledata", setupSimplicesID=>"samplesimplices", getparamjobid(scheduler,paramIDs,"dimreductionmethod")=>"method") makeplotID = createjob!(makeplot, scheduler, dimreductionID=>"reduced", getparamjobid(scheduler,paramIDs,"dimreductionmethod")=>"dimreductionmethod", getparamjobid(scheduler,paramIDs,"sampleannot")=>"sampleannot", setupSimplicesID=>"samplesimplices", getparamjobid(scheduler,paramIDs,"xaxis")=>"xaxis", getparamjobid(scheduler,paramIDs,"yaxis")=>"yaxis", getparamjobid(scheduler,paramIDs,"zaxis")=>"zaxis", getparamjobid(scheduler,paramIDs,"plotwidth")=>"plotwidth", getparamjobid(scheduler,paramIDs,"plotheight")=>"plotheight", getparamjobid(scheduler,paramIDs,"showpoints")=>"showpoints", getparamjobid(scheduler,paramIDs,"showlines")=>"showlines", getparamjobid(scheduler,paramIDs,"showtriangles")=>"showtriangles", getparamjobid(scheduler,paramIDs,"markersize")=>"markersize", getparamjobid(scheduler,paramIDs,"linewidth")=>"linewidth", getparamjobid(scheduler,paramIDs,"triangleopacity")=>"triangleopacity", getparamjobid(scheduler,paramIDs,"colorby")=>"colorby", getparamjobid(scheduler,paramIDs,"colorannot")=>"colorannot") # getparamjobid(scheduler,paramIDs,"shapeby")=>"shapeby", # getparamjobid(scheduler,paramIDs,"shapeannot")=>"shapeannot") exportSingleID = createjob!(exportsingle, scheduler, dimreductionID=>"reduced", getparamjobid(scheduler,paramIDs,"exportmode")=>"mode", getparamjobid(scheduler,paramIDs,"exportsinglepath")=>"filepath", getparamjobid(scheduler,paramIDs,"exportsingledim")=>"dim", getparamjobid(scheduler,paramIDs,"exportsinglesort")=>"sort") exportMultipleID = createjob!(exportmultiple, scheduler, dimreductionID=>"reduced", getparamjobid(scheduler,paramIDs,"exportmode")=>"mode", getparamjobid(scheduler,paramIDs,"exportmultiplepath")=>"filepath", getparamjobid(scheduler,paramIDs,"exportmultipledim")=>"dim") JobGraph(scheduler, Ref(""), ReentrantLock(), paramIDs, loadSampleID, normalizeID, setupSimplicesID, dimreductionID, makeplotID, exportSingleID, exportMultipleID) end getparamjobid(s::Scheduler, paramIDs::Dict{String,JobID}, name::String, create::Bool=true) = create ? get!(paramIDs,name,createjob!(s, :__INVALID__, name=name)) : paramIDs[name] getparamjobid(jg::JobGraph, name::String, args...) = getparamjobid(jg.scheduler, jg.paramIDs, name, args...) function setparam(jg::JobGraph, name::String, value) if haskey(jg.paramIDs, name) setresult!(jg.scheduler, getparamjobid(jg,name), value) else @warn "Unknown variable name: $name" end end function process_step(jg::JobGraph, fromGUI::Channel, toGUI::Channel, lastSchedulerTime::Ref{UInt64}; verbosityLevel) scheduler = jg.scheduler verbosityLevel>=3 && @info "[Processing] tick" timeNow = time_ns() if isready(fromGUI) try msg = take!(fromGUI) msgName = msg.first msgArgs = msg.second verbosityLevel>=2 && @info "[Processing] Got message: $msgName $msgArgs" if msgName == :exit return false elseif msgName == :cancel verbosityLevel>=2 && @info "[Processing] Cancelling all future events." cancelall!(scheduler) elseif msgName == :setvalue setparam(jg, msgArgs[1], msgArgs[2]) elseif msgName == :loadsample schedule!(x->showsampleannotnames(x,toGUI), scheduler, jg.loadSampleID) elseif msgName == :normalize schedule!(scheduler, jg.normalizeID) elseif msgName == :dimreduction schedule!(scheduler, jg.dimreductionID) elseif msgName == :showplot schedule!(x->showplot(x,toGUI), scheduler, jg.makeplotID) elseif msgName == :exportsingle schedule!(scheduler, jg.exportSingleID) elseif msgName == :exportmultiple schedule!(scheduler, jg.exportMultipleID) else @warn "Unknown message type: $(msgName)" end catch e @warn "[Processing] Error processing GUI message." showerror(stdout, e, catch_backtrace()) end setsamplestatus(jg, toGUI) elseif wantstorun(scheduler) || (isactive(scheduler) && (timeNow-lastSchedulerTime[])/1e9 > 5.0) lastSchedulerTime[] = timeNow try step!(scheduler) status = statusstring(scheduler) !isempty(status) && verbosityLevel>=2 && @info "Job status: $status" catch e @warn "[Processing] Error processing event: $e" #showerror(stdout, e, catch_backtrace()) end setsamplestatus(jg, toGUI) else sleep(0.05)#yield() end true end function process_thread(jg::JobGraph, fromGUI::Channel, toGUI::Channel; verbosityLevel) lastSchedulerTime = Ref{UInt64}(0) try while process_step(jg, fromGUI, toGUI, lastSchedulerTime; verbosityLevel=verbosityLevel) end catch e @warn "[Processing] Fatal error." showerror(stdout, e, catch_backtrace()) end verbosityLevel>=2 && @info "[Processing] Exiting thread." put!(toGUI, :exited=>nothing) end """ pmaapp() Start the Principal Moment Analysis App. """ function pmaapp(; verbosityLevel=1, return_job_graph=false) # This is the GUI thread jg = JobGraph(verbose=verbosityLevel>=2) verbosityLevel>=1 && @info "[PMAGUI] Using $(Threads.nthreads()) of $(Sys.CPU_THREADS) available threads." Threads.nthreads() == 1 && verbosityLevel>=1 && @warn "[PMAGUI] Threading not enabled, please set the environment variable JULIA_NUM_THREADS to the desired number of threads." # init fromGUI = Channel{Pair{Symbol,Vector}}(Inf) toGUI = Channel{Pair{Symbol,Any}}(Inf) # start processing thread processingThreadRunning = true Threads.@spawn process_thread(jg, fromGUI, toGUI; verbosityLevel=verbosityLevel) # setup gui w = Window(Dict(:width=>512,:height=>768)) # event listeners handle(w, "msg") do args msgName = Symbol(args[1]) msgArgs = args[2:end] verbosityLevel>=2 && @info "[GUI] sending message: $msgName $(join(msgArgs,", "))" processingThreadRunning && put!(fromGUI, msgName=>msgArgs) end doc = read(joinpath(@__DIR__,"content.html"),String) body!(w,doc,async=false) js(w, js"init()") while isopen(w.content.sock) # is there a better way to check if the window is still open? verbosityLevel>=3 && @info "[GUI] tick" if isready(toGUI) msg = take!(toGUI) msgName = msg.first msgArgs = msg.second verbosityLevel>=2 && @info "[GUI] got message: $msgName" if msgName == :samplestatus js(w, js"""setSampleStatus($msgArgs)""") elseif msgName == :displayplot plotArgs,plotWidth,plotHeight = msgArgs pl = plot(plotArgs...) relayout!(pl, Dict(:margin=>attr(l=1, r=1, b=1, t=50))) # by doing this here - we seem to avoid a bug that causes axis ticks to disappear from subsequent Volcano(!) plots. display(pl) # Slight hack to set window size properly plSize = size(pl) size(pl.window, floor(Int,plotWidth*1.05), floor(Int,plotHeight*1.05)) elseif msgName == :displaysampleannotnames js(w, js"""setSampleAnnotNames($(msgArgs[1]), $(msgArgs[2]-1))""") elseif msgName == :exited processingThreadRunning = false end end sleep(0.05)#yield() # Allow GUI to run end verbosityLevel>=2 && @info "[GUI] Waiting for scheduler thread to finish." processingThreadRunning && put!(fromGUI, :exit=>[]) # wait until all threads have exited while processingThreadRunning msg = take!(toGUI) msgName = msg.first msgArgs = msg.second verbosityLevel>=2 && @info "[GUI] got message: $msgName" msgName == :exited && (processingThreadRunning = false) sleep(0.05) end verbosityLevel>=2 && @info "[GUI] Scheduler thread finished." return_job_graph ? jg : nothing end
PrincipalMomentAnalysisApp
https://github.com/PrincipalMomentAnalysis/PrincipalMomentAnalysisApp.jl.git
[ "MIT" ]
0.2.6
7a89075c252d95cd9530f937158955939c218425
code
243
function svdbyeigen(A; nsv::Integer=3) P,N = size(A) K = Symmetric(N<=P ? A'A : A*A') M = size(K,1) F = eigen(K, M-nsv+1:M) S = sqrt.(max.(0.,reverse(F.values))) V = F.vectors[:,end:-1:1] N<=P ? SVD(A*V./S',S,V') : SVD(V,S,V'A./S) end
PrincipalMomentAnalysisApp
https://github.com/PrincipalMomentAnalysis/PrincipalMomentAnalysisApp.jl.git
[ "MIT" ]
0.2.6
7a89075c252d95cd9530f937158955939c218425
code
9310
function _scatter(V; kwargs...) size(V,2)==2 && return scatter(;x=V[:,1], y=V[:,2], kwargs...) scatter3d(;x=V[:,1], y=V[:,2], z=V[:,3], kwargs...) end function plotsimplices(V, sg, colorBy, colorDict; drawPoints=true, drawLines=true, drawTriangles=true, title="", opacity=0.3, markerSize=5, lineWidth=2, shapeBy=nothing, shapeDict=nothing, xLabel="x", yLabel="y", zLabel="z", legendTitle="", cameraAttr=attr()) @assert size(V,2) in 2:3 traces = GenericTrace[] # colorscale setup colorScale = nothing tOffs, tScale = 0.0, 1.0 if colorDict==nothing # this is the "RdBu" colorscale used by PlotlyJS colorScale = ColorScale([0, 0.35, 0.5, 0.6, 0.7, 1], [RGB(5/255,10/255,172/255), RGB(106/255,137/255,247/255), RGB(190/255,190/255,190/255), RGB(220/255,170/255,132/255), RGB(230/255,145/255,90/255), RGB(178/255,10/255,28/255)]) if !isempty(skipmissing(colorBy)) m,M = Float64.(extrema(skipmissing(colorBy))) tOffs,tScale = M>m ? (m, 1.0./(M-m)) : (m-0.5, 1.0) # if there is only one unique value, map it to the middle of the colorscale end end if drawTriangles && size(V,2)>2 # Triangles not supported in 2d plot for now TRIANGLE_LIMIT = 2_000_000 triangleInds = Int[] for c=1:size(sg.G,2) ind = findall(sg.G[:,c]) isempty(ind) && continue length(ind)<3 && continue # no triangles # slow and ugly solution for tri in IterTools.subsets(ind,3) append!(triangleInds, sort(tri)) end end triangleInds = reshape(triangleInds,3,:) triangleInds = unique(triangleInds,dims=2) # remove duplicates triangleInds .-= 1 # PlotlyJS wants zero-based indices if size(triangleInds,2)>TRIANGLE_LIMIT @warn "More than $TRIANGLE_LIMIT triangles to plot, disabling triangle plotting for performance reasons." else if colorDict==nothing vertexColor = [ ismissing(t) ? RGB(0.,0.,0.) : lookup(colorScale, (t-tOffs)*tScale) for t in colorBy ] else vertexColor = getindex.((colorDict,), colorBy) end push!(traces, mesh3d(; x=V[:,1],y=V[:,2],z=V[:,3],i=triangleInds[1,:],j=triangleInds[2,:],k=triangleInds[3,:], vertexcolor=vertexColor, opacity=opacity, lighting=attr(ambient=1.0,diffuse=0.0,specular=0.0,fresnel=0.0), showlegend=false)) end end if drawLines LINE_LIMIT = 300_000 GK = sg.G*sg.G' nbrLines = div(nnz(GK) - sum(i->GK[i,i]>0, 1:size(GK,1)), 2) # number of elements above the diagonal if nbrLines > LINE_LIMIT @warn "More than $LINE_LIMIT lines to plot, disabling line plotting for performance reasons." else # every third point is "nothing" to make lines disconnected VL = repeat(Union{Float64,Nothing}[nothing], nbrLines*3, size(V,2)) colorsRGB = repeat([RGB(0.,0.,0.)], nbrLines*3) lineInd = 1 rows = rowvals(GK) for c = 1:size(GK,2) for k in nzrange(GK, c) r = rows[k] r>=c && break # just use upper triangular part VL[lineInd, :] .= V[r,:] VL[lineInd+1, :] .= V[c,:] if colorDict==nothing t1,t2 = colorBy[r],colorBy[c] col1 = ismissing(t1) ? RGB(0.,0.,0.) : lookup(colorScale, (t1-tOffs)*tScale) col2 = ismissing(t2) ? RGB(0.,0.,0.) : lookup(colorScale, (t2-tOffs)*tScale) else col1 = colorDict[colorBy[r]] col2 = colorDict[colorBy[c]] end colorsRGB[lineInd] = col1 colorsRGB[lineInd+1] = col2 lineInd+=3 end end @assert lineInd == nbrLines*3+1 if size(V,2)==2 # PLOTLY DOESN'T HANDLE PER VERTEX COLORS FOR 2D LINES. THIS IS A STUPID WORKAROUND TO MAKE LINES BLACK IN 2D. push!(traces, _scatter(VL; mode="lines", line=attr(color=colorant"black", width=lineWidth), showlegend=false)) else push!(traces, _scatter(VL; mode="lines", line=attr(color=colorsRGB, width=lineWidth), showlegend=false)) end end end # plot each group in different colors if drawPoints # TODO: merge the two cases below? if colorDict != nothing for cb in unique(colorBy) ind = findall(colorBy.==cb ) col = colorDict[cb] extras = [] length(colorDict)==1 && push!(extras, (;showlegend=false)) shapeBy!=nothing && shapeDict!=nothing && push!(extras, (marker_symbol=[shapeDict[k] for k in shapeBy[ind]],)) isempty(extras) || (extras = pairs(extras...)) points = _scatter(V[ind,:]; mode="markers", marker_color=col, marker_size=markerSize, marker_line_width=0, name=string(cb), extras...) push!(traces, points) end else extras = [] shapeBy!=nothing && shapeDict!=nothing && push!(extras, (marker_symbol=[shapeDict[k] for k in shapeBy],)) isempty(extras) || (extras = pairs(extras...)) V2 = V c = colorBy # handle missing values by plotting them in another trace (with a different color) if any(ismissing, c) mask = ismissing.(c) pointsNA = _scatter(V2[mask,:]; mode="markers", marker=attr(color=colorant"black", size=markerSize, line_width=0), name="", showlegend=false, extras...) push!(traces, pointsNA) V2 = V2[.!mask,:] c = disallowmissing(c[.!mask]) end points = _scatter(V2; mode="markers", marker=attr(color=c, colorscale=to_list(colorScale), showscale=true, size=markerSize, line_width=0, colorbar=attr(title=legendTitle)), name="", showlegend=false, extras...) push!(traces, points) end end if size(V,2)==2 layout = Layout(title=title, xaxis=attr(title=xLabel, constrain="domain"), yaxis=attr(title=yLabel, constrain="domain", scaleanchor='x'), legend=attr(title_text=legendTitle, itemsizing="constant"), hovermode="closest") else layout = Layout(title=title, scene=attr(xaxis=attr(title=xLabel), yaxis=attr(title=yLabel), zaxis=attr(title=zLabel), camera=cameraAttr, aspectmode="data"), legend=attr(title_text=legendTitle, itemsizing="constant")) end traces, layout # return plot args rather than plot because of threading issues. end _distinguishable_colors(n) = distinguishable_colors(n+1,colorant"white")[2:end] function colordict(x::AbstractArray) k = unique(x) Dict(s=>c for (s,c) in zip(k,_distinguishable_colors(length(k)))) end struct ColorScale t::Vector{Float64} # increasing values between 0 and 1. First must be 0 and last must be 1. colors::Vector{RGB{Float64}} # must be same length as t end to_list(colorScale::ColorScale) = [ [t,c] for (t,c) in zip(colorScale.t, colorScale.colors)] function lookup(colorScale::ColorScale, t::Float64) i2 = searchsortedfirst(colorScale.t, t) i2>length(colorScale.t) && return colorScale.colors[end] i2==1 && return colorScale.colors[1] i1 = i2-1 α = (t-colorScale.t[i1]) / (colorScale.t[i2]-colorScale.t[i1]) weighted_color_mean(α, colorScale.colors[i2], colorScale.colors[i1]) # NB: order because α=1 means first color in weighted_color_mean end const SHAPES = ["circle","square","diamond","cross","x","triangle-up","triangle-down","triangle-left","triangle-right","triangle-ne","triangle-se","triangle-sw","triangle-nw","pentagon","hexagon","hexagon2","octagon","star","hexagram","star-triangle-up","star-triangle-down","star-square","star-diamond","diamond-tall","diamond-wide","hourglass","bowtie","circle-cross","circle-x","square-cross","square-x","diamond-cross","diamond-x","cross-thin","x-thin","asterisk","hash","y-up","y-down","y-left","y-right","line-ew","line-ns","line-ne","line-nw","circle-open","square-open","diamond-open","cross-open","x-open","triangle-up-open","triangle-down-open","triangle-left-open","triangle-right-open","triangle-ne-open","triangle-se-open","triangle-sw-open","triangle-nw-open","pentagon-open","hexagon-open","hexagon2-open","octagon-open","star-open","hexagram-open","star-triangle-up-open","star-triangle-down-open","star-square-open","star-diamond-open","diamond-tall-open","diamond-wide-open","hourglass-open","bowtie-open","circle-cross-open","circle-x-open","square-cross-open","square-x-open","diamond-cross-open","diamond-x-open","cross-thin-open","x-thin-open","asterisk-open","hash-open","y-up-open","y-down-open","y-left-open","y-right-open","line-ew-open","line-ns-open","line-ne-open","line-nw-open","","circle-dot","square-dot","diamond-dot","cross-dot","x-dot","triangle-up-dot","triangle-down-dot","triangle-left-dot","triangle-right-dot","triangle-ne-dot","triangle-se-dot","triangle-sw-dot","triangle-nw-dot","pentagon-dot","hexagon-dot","hexagon2-dot","octagon-dot","star-dot","hexagram-dot","star-triangle-up-dot","star-triangle-down-dot","star-square-dot","star-diamond-dot","diamond-tall-dot","diamond-wide-dot","hash-dot","circle-open-dot","square-open-dot","diamond-open-dot","cross-open-dot","x-open-dot","triangle-up-open-dot","triangle-down-open-dot","triangle-left-open-dot","triangle-right-open-dot","triangle-ne-open-dot","triangle-se-open-dot","triangle-sw-open-dot","triangle-nw-open-dot","pentagon-open-dot","hexagon-open-dot","hexagon2-open-dot","octagon-open-dot","star-open-dot","hexagram-open-dot","star-triangle-up-open-dot","star-triangle-down-open-dot","star-square-open-dot","star-diamond-open-dot","diamond-tall-open-dot","diamond-wide-open-dot","hash-open-dot"] shapedict(x::AbstractArray) = Dict(v=>SHAPES[mod(i-1,length(SHAPES))+1] for (i,v) in enumerate(unique(x)))
PrincipalMomentAnalysisApp
https://github.com/PrincipalMomentAnalysis/PrincipalMomentAnalysisApp.jl.git
[ "MIT" ]
0.2.6
7a89075c252d95cd9530f937158955939c218425
code
368
using PrincipalMomentAnalysisApp using Test using PrincipalMomentAnalysis using LinearAlgebra using DataFrames using CSV import PrincipalMomentAnalysisApp: JobGraph, process_thread, process_step using PrincipalMomentAnalysisApp.Schedulers include("utils.jl") @testset "PrincipalMomentAnalysisApp" begin include("test_content.jl") include("test_app.jl") end
PrincipalMomentAnalysisApp
https://github.com/PrincipalMomentAnalysis/PrincipalMomentAnalysisApp.jl.git
[ "MIT" ]
0.2.6
7a89075c252d95cd9530f937158955939c218425
code
18163
@testset "app" begin @testset "exit" begin app = MiniApp() put!(app.fromGUI, :exit=>[]) process_thread(app.jg, app.fromGUI, app.toGUI; verbosityLevel=2) didExit = false while true @test isready(app.toGUI) msg = take!(app.toGUI) msg.first == :exited && (didExit=true; break) end @test didExit end @testset "exit2" begin app = MiniApp() init(app) lastSchedulerTime = Ref{UInt64}(0) put!(app.fromGUI, :exit=>[]) @test !runall(app) end @testset "data.tsv" begin filepath = joinpath(@__DIR__, "data/data.tsv") varIds = [Symbol("V$i") for i=1:40] sampleIds = [string('S',lpad(i,2,'0')) for i=1:20] groupAnnot = repeat(["A","B"],inner=10) timeAnnot = vcat(0.01:0.01:0.1, 0.01:0.01:0.1) app = MiniApp() init(app) # Open file setvalue(app, Any["samplefilepath", filepath]) setvalue(app, Any["lastsampleannot", "Time"]) put!(app.fromGUI, :loadsample=>[]) @test runall(app) dfSample = app.jg.scheduler.jobs[app.jg.loadSampleID].result @test propertynames(dfSample) == vcat([:SampleId, :Group, :Time], varIds) @test dfSample.SampleId == sampleIds @test dfSample.Group == groupAnnot @test dfSample.Time == timeAnnot @test size(dfSample)==(20,3+40) X = Matrix(Matrix{Float64}(dfSample[:,4:end])') normalizemean!(X) # PMA (groups) setvalue(app, Any["samplesimplexmethod", "SA"]) setvalue(app, Any["sampleannot", "Group"]) put!(app.fromGUI, :dimreduction=>[]) @test runall(app) reduced = app.jg.scheduler.jobs[app.jg.dimreductionID].result @test reduced.sa == dfSample[!,1:3] @test reduced.va[!,1] == varIds factorizationcmp(pma(X, groupsimplices(groupAnnot); nsv=10), reduced.F) # PMA (time series) setvalue(app, Any["samplesimplexmethod", "Time"]) setvalue(app, Any["sampleannot", "Group"]) setvalue(app, Any["timeannot", "Time"]) put!(app.fromGUI, :dimreduction=>[]) @test runall(app) reduced = app.jg.scheduler.jobs[app.jg.dimreductionID].result @test reduced.sa == dfSample[!,1:3] @test reduced.va[!,1] == varIds #factorizationcmp(pma(X, timeseriessimplices(timeAnnot, groupby=groupAnnot); nsv=10), reduced.F) G = timeseriessimplices(timeAnnot, groupby=groupAnnot) factorizationcmp(pma(X, G; nsv=10), reduced.F) # PMA (NN) setvalue(app, Any["samplesimplexmethod", "NN"]) setvalue(app, Any["knearestneighbors", "2"]) setvalue(app, Any["distnearestneighbors", "0.5"]) put!(app.fromGUI, :dimreduction=>[]) @test runall(app) reduced = app.jg.scheduler.jobs[app.jg.dimreductionID].result @test reduced.sa == dfSample[!,1:3] @test reduced.va[!,1] == varIds factorizationcmp(pma(X, neighborsimplices(X,k=2,r=0.5,dim=50), nsv=10), reduced.F) # PMA (NN withing groups) setvalue(app, Any["samplesimplexmethod", "NNSA"]) setvalue(app, Any["sampleannot", "Group"]) setvalue(app, Any["knearestneighbors", "2"]) setvalue(app, Any["distnearestneighbors", "0.5"]) put!(app.fromGUI, :dimreduction=>[]) @test runall(app) reduced = app.jg.scheduler.jobs[app.jg.dimreductionID].result @test reduced.sa == dfSample[!,1:3] @test reduced.va[!,1] == varIds F = pma(X, neighborsimplices(X,k=2,r=0.5,dim=50,groupby=groupAnnot), nsv=10) factorizationcmp(F, reduced.F) # Exports mktempdir() do temppath for (dim,order,mode) in zip((1,3,7,10), ("Abs","Descending","Ascending","Original"), ("Samples","Variables","Samples","Variables")) setvalue(app, Any["exportsingledim", "$dim"]) setvalue(app, Any["exportsinglesort", order]) setvalue(app, Any["exportmode", mode]) filepath = joinpath(temppath,"PMA$(dim)_$(mode)_$order.tsv") setvalue(app, Any["exportsinglepath", filepath]) put!(app.fromGUI, :exportsingle=>[]) @test runall(app) result = CSV.read(filepath, DataFrame; delim='\t', ntasks=1) colName = Symbol(:PMA,dim) resultPMA = result[:,colName] if mode=="Samples" idCol = :SampleId ids = sampleIds PMA = reduced.F.V[:,dim] else idCol = :VariableId ids = string.(varIds) PMA = reduced.F.U[:,dim] end perm = collect(1:length(PMA)) if order=="Abs" perm = sortperm(PMA, by=abs, rev=true) elseif order=="Descending" perm = sortperm(PMA, rev=true) elseif order=="Ascending" perm = sortperm(PMA) end @test propertynames(result)==[idCol,colName] @test result[!,idCol] == ids[perm] @test resultPMA ≈ PMA[perm] end for (dim,mode) in zip((4,5), ("Samples","Variables")) setvalue(app, Any["exportmultipledim", "$dim"]) setvalue(app, Any["exportmode", mode]) filepath = joinpath(temppath,"PMA$(dim)_$(mode).csv") setvalue(app, Any["exportmultiplepath", filepath]) put!(app.fromGUI, :exportmultiple=>[]) @test runall(app) result = CSV.read(filepath, DataFrame; delim=',', ntasks=false) colNames = Symbol.(:PMA,1:dim) if mode=="Samples" @test propertynames(result)==vcat(:SampleId, colNames) @test result.SampleId == sampleIds @test Matrix(result[:,colNames]) ≈ reduced.F.V[:,1:dim] else @test propertynames(result)==vcat(:VariableId, colNames) @test result.VariableId == string.(varIds) @test Matrix(result[:,colNames]) ≈ reduced.F.U[:,1:dim] end end end # Exit put!(app.fromGUI, :exit=>[]) @test !runall(app) end @testset "MissingValueReconstruction" begin reconstructed = Float64[0.06 0.26 0.0 0.0 0.28 0.03 0.04 0.12 0.05 0.0 0.02 0.31 0.0 0.85 0.41 0.06 0.04 0.92 0.32 0.12; 0.01 0.13 0.48 0.64 0.23 0.01 0.0 0.18 0.03 0.14 0.26 0.0 0.09 0.27 0.1 0.0 0.48 0.06 0.07 0.56; 0.0 0.22 0.02 0.0 0.02 0.06 0.05 0.59 0.64 0.81 0.98 0.24 0.08 0.24 0.41 0.0 0.65 0.15 0.11 0.0; 0.01 0.01 0.31 0.23 0.02 0.0 0.01 0.15 0.03 0.64 0.21 0.16 0.0 0.02 0.12 0.84 0.06 0.0 0.0 0.2; 0.03 0.55 0.0 0.06 0.01 0.01 0.16 0.01 0.42 0.73 0.01 0.15 0.27 0.02 0.02 0.37 0.16 0.19 0.04 0.0; 0.36 0.97 0.54 0.98 0.03 0.52 0.1 0.06 0.14 0.0 0.46 0.38 0.29 0.93 0.06 0.07 0.05 0.45 0.0 0.01; 0.12 0.97 0.3 0.07 0.11 0.28 0.31 0.07 0.0 0.16 0.0 0.29 0.33 0.01 0.01 0.02 0.17 0.0 0.67 0.45; 0.0 0.08 0.49 0.34 0.07 0.01 0.03 0.1 0.05 0.16 0.05 0.36 0.0 0.38 0.41 0.0 0.09 0.67 0.61 1.0; 0.01 0.3 0.19 0.0 0.0 0.0 0.32 0.72 0.0 0.04 0.7 1.0 0.55 0.12 0.03 0.19 0.52 0.04 0.04 0.8; 0.12 0.0 0.04 0.02 0.19 0.09 0.01 0.66 0.25 0.21 0.01 0.02 0.38 0.62 0.3 0.99 0.38 0.1 0.54 0.07; 0.08 0.0 0.16 0.01 0.69 0.23 0.81 0.29 0.13 0.4 0.04 0.15 0.17 0.64 0.03 0.32 0.78 0.28 0.12 0.36; 0.89 0.02 0.0 0.02 0.26 0.06 0.01 0.01 0.48 0.58 0.25 0.29 0.51 0.31 0.22 0.0 0.27 0.01 0.04 0.05; 0.55 0.04 0.47 0.0 0.24 0.07 0.64 0.01 0.02 0.0 0.42 0.0 0.36 0.22 0.06 0.95 0.66 0.27 0.09 0.05; 0.46 0.19 0.1 0.01 0.13 0.15 0.06 0.84 0.02 0.0 0.09 0.62 0.01 0.0 0.01 0.0 0.01 0.33 0.47 0.58; 0.04 0.28 0.27 0.69 0.0 0.78 0.12 0.01 0.13 0.0 0.0 0.09 0.11 0.53 0.0 0.29 0.39 0.67 0.42 0.29; 0.01 0.09 0.0 0.49 0.18 0.0 0.64 0.67 0.32 0.37 0.08 0.0 0.04 0.17 0.0 0.06 0.01 0.0 0.43 0.22; 0.27 0.02 0.05 0.88 0.02 0.16 0.09 0.0 0.46 0.05 0.18 0.11 0.02 0.37 0.88 0.47 0.92 0.41 0.96 0.0; 0.0 0.99 0.98 0.31 0.05 0.02 0.06 0.03 0.34 0.37 0.17 0.0 0.33 0.78 0.47 0.75 0.34 0.04 0.69 0.0; 0.69 0.34 0.15 0.12 0.11 0.0 0.91 0.35 0.05 0.0 0.26 0.01 0.62 0.82 0.48 0.4 0.08 0.0 0.32 0.0; 0.08 0.01 0.85 0.82 0.0 0.0 0.99 0.0 0.12 0.05 0.04 0.53 0.0 0.89 0.26 0.01 0.17 0.39 0.05 0.0; 0.01 0.01 0.72 0.2647368421052631 0.0 0.6 0.01 0.08 0.18 0.42 0.48 0.02 0.34 0.59 0.02 0.6 0.02 0.76 0.03 0.14; 0.17555555555555552 0.13 0.47 0.01 0.08 0.26 0.25 0.17555555555555552 0.0 0.0 0.01 0.82 0.0 0.0 0.03 0.0 0.0 0.3 0.07 0.73; 0.0 0.3664705882352941 0.39 0.99 0.03 0.5 0.88 0.13 0.8 0.0 0.0 0.0 0.3664705882352941 0.3664705882352941 0.43 0.7 0.72 0.22 0.04 0.4; 0.0 0.5 0.5 0.97 0.02 0.08 0.35 0.238125 0.02 0.26 0.02 0.238125 0.1 0.0 0.0 0.92 0.0 0.238125 0.238125 0.07; 0.09 0.0 0.09733333333333334 0.09733333333333334 0.56 0.0 0.09733333333333334 0.09733333333333334 0.0 0.14 0.01 0.0 0.02 0.08 0.12 0.0 0.09733333333333334 0.09 0.1 0.25; 0.34500000000000003 0.34500000000000003 0.13 0.63 0.34500000000000003 0.03 0.0 0.06 0.56 0.55 0.15 0.34500000000000003 0.87 0.9 0.79 0.04 0.34500000000000003 0.34500000000000003 0.09 0.03; 0.85 0.79 0.32769230769230767 0.32769230769230767 0.35 0.32769230769230767 0.32769230769230767 0.21 0.03 0.01 0.36 0.44 0.52 0.01 0.32769230769230767 0.66 0.32769230769230767 0.03 0.0 0.32769230769230767; 0.86 0.24499999999999997 0.24499999999999997 0.24 0.01 0.24499999999999997 0.84 0.24499999999999997 0.24499999999999997 0.15 0.24499999999999997 0.24499999999999997 0.24499999999999997 0.1 0.13 0.3 0.03 0.04 0.24 0.0; 0.3427272727272727 0.92 0.3427272727272727 0.3427272727272727 0.09 0.3427272727272727 0.9 0.0 0.3427272727272727 0.3427272727272727 0.02 0.3427272727272727 0.63 0.05 0.19 0.09 0.0 0.88 0.3427272727272727 0.3427272727272727; 0.6 0.271 0.271 0.271 0.271 0.271 0.16 0.271 0.271 0.271 0.271 0.271 0.02 0.4 0.04 0.0 0.18 0.34 0.01 0.96; 0.0 0.1688888888888889 0.24 0.0 0.1688888888888889 0.2 0.02 0.1688888888888889 0.33 0.1688888888888889 0.1688888888888889 0.1688888888888889 0.17 0.1688888888888889 0.06 0.1688888888888889 0.1688888888888889 0.1688888888888889 0.1688888888888889 0.5; 0.26375000000000004 0.26375000000000004 0.84 0.26375000000000004 0.26375000000000004 0.42 0.26375000000000004 0.26375000000000004 0.26375000000000004 0.26375000000000004 0.54 0.26375000000000004 0.26375000000000004 0.0 0.13 0.01 0.04 0.26375000000000004 0.26375000000000004 0.13; 0.21142857142857144 0.21142857142857144 0.21142857142857144 0.21142857142857144 0.27 0.03 0.21142857142857144 0.11 0.21142857142857144 0.5 0.21142857142857144 0.21142857142857144 0.21142857142857144 0.21142857142857144 0.21142857142857144 0.21142857142857144 0.21142857142857144 0.15 0.36 0.06; 0.22833333333333336 0.22833333333333336 0.22833333333333336 0.22833333333333336 0.1 0.22833333333333336 0.22833333333333336 0.01 0.02 0.22833333333333336 0.01 0.22833333333333336 0.22833333333333336 0.22833333333333336 0.22833333333333336 0.64 0.22833333333333336 0.59 0.22833333333333336 0.22833333333333336; 0.08800000000000001 0.08800000000000001 0.08800000000000001 0.04 0.08800000000000001 0.08800000000000001 0.08 0.15 0.17 0.08800000000000001 0.08800000000000001 0.08800000000000001 0.08800000000000001 0.08800000000000001 0.08800000000000001 0.0 0.08800000000000001 0.08800000000000001 0.08800000000000001 0.08800000000000001; 0.52 0.62 0.30250000000000005 0.07 0.30250000000000005 0.30250000000000005 0.30250000000000005 0.30250000000000005 0.30250000000000005 0.30250000000000005 0.30250000000000005 0.30250000000000005 0.30250000000000005 0.30250000000000005 0.0 0.30250000000000005 0.30250000000000005 0.30250000000000005 0.30250000000000005 0.30250000000000005; 0.043333333333333335 0.08 0.043333333333333335 0.043333333333333335 0.043333333333333335 0.043333333333333335 0.0 0.043333333333333335 0.043333333333333335 0.043333333333333335 0.043333333333333335 0.043333333333333335 0.043333333333333335 0.05 0.043333333333333335 0.043333333333333335 0.043333333333333335 0.043333333333333335 0.043333333333333335 0.043333333333333335; 0.34 0.34 0.34 0.34 0.34 0.34 0.34 0.68 0.34 0.0 0.34 0.34 0.34 0.34 0.34 0.34 0.34 0.34 0.34 0.34; 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0] logReconstructed = Float64[-0.6666 -0.2688 -0.811 -0.811 -0.2345 -0.737 -0.7131 -0.5353 -0.6897 -0.811 -0.7612 -0.1844 -0.811 0.5059 -0.02915 -0.6666 -0.7131 0.5753 -0.1681 -0.5353; -0.7859 -0.5146 0.07039 0.275 -0.3219 -0.7859 -0.811 -0.415 -0.737 -0.4941 -0.2688 -0.811 -0.5995 -0.2515 -0.5778 -0.811 0.07039 -0.6666 -0.6439 0.1763; -0.811 -0.3401 -0.7612 -0.811 -0.7612 -0.6666 -0.6897 0.2141 0.275 0.4647 0.6323 -0.304 -0.6215 -0.304 -0.02915 -0.811 0.2869 -0.4739 -0.5564 -0.811; -0.7859 -0.7859 -0.1844 -0.3219 -0.7612 -0.811 -0.7859 -0.4739 -0.737 0.275 -0.3585 -0.454 -0.811 -0.7612 -0.5353 0.4957 -0.6666 -0.811 -0.811 -0.3771; -0.737 0.1635 -0.811 -0.6666 -0.7859 -0.7859 -0.454 -0.7859 -0.0145 0.3785 -0.7859 -0.4739 -0.2515 -0.7612 -0.7612 -0.08927 -0.454 -0.3959 -0.7131 -0.811; -0.1047 0.6229 0.1506 0.6323 -0.737 0.1243 -0.5778 -0.6666 -0.4941 -0.811 0.04264 -0.074 -0.2176 0.585 -0.6666 -0.6439 -0.6897 0.02857 -0.811 -0.7859; -0.5353 0.6229 -0.2009 -0.6439 -0.5564 -0.2345 -0.1844 -0.6439 -0.811 -0.454 -0.811 -0.2176 -0.152 -0.7859 -0.7859 -0.7612 -0.4344 -0.811 0.3103 0.02857; -0.811 -0.6215 0.08406 -0.1361 -0.6439 -0.7859 -0.737 -0.5778 -0.6897 -0.454 -0.6897 -0.1047 -0.811 -0.074 -0.02915 -0.811 -0.5995 0.3103 0.2388 0.6508; -0.7859 -0.2009 -0.3959 -0.811 -0.811 -0.811 -0.1681 0.3674 -0.811 -0.7131 0.3448 0.6508 0.1635 -0.5353 -0.737 -0.3959 0.1243 -0.7131 -0.7131 0.4542; -0.5353 -0.811 -0.7131 -0.7612 -0.3959 -0.5995 -0.7859 0.2987 -0.2863 -0.3585 -0.7859 -0.7612 -0.074 0.251 -0.2009 0.6415 -0.074 -0.5778 0.1506 -0.6439; -0.6215 -0.811 -0.454 -0.7859 0.3334 -0.3219 0.4647 -0.2176 -0.5146 -0.04394 -0.7131 -0.4739 -0.4344 0.275 -0.737 -0.1681 0.433 -0.2345 -0.5353 -0.1047; 0.546 -0.7612 -0.811 -0.7612 -0.2688 -0.6666 -0.7859 -0.7859 0.07039 0.2016 -0.2863 -0.2176 0.111 -0.1844 -0.3401 -0.811 -0.2515 -0.7859 -0.7131 -0.6897; 0.1635 -0.7131 0.05658 -0.811 -0.304 -0.6439 0.275 -0.7859 -0.7612 -0.811 -0.0145 -0.811 -0.1047 -0.3401 -0.6666 0.6041 0.2987 -0.2515 -0.5995 -0.6897; 0.04264 -0.3959 -0.5778 -0.7859 -0.5146 -0.4739 -0.6666 0.4957 -0.7612 -0.811 -0.5995 0.251 -0.7859 -0.811 -0.7859 -0.811 -0.7859 -0.152 0.05658 0.2016; -0.7131 -0.2345 -0.2515 0.3334 -0.811 0.433 -0.5353 -0.7859 -0.5146 -0.811 -0.811 -0.5995 -0.5564 0.1375 -0.811 -0.2176 -0.05889 0.3103 -0.0145 -0.2176; -0.7859 -0.5995 -0.811 0.08406 -0.415 -0.811 0.275 0.3103 -0.1681 -0.08927 -0.6215 -0.811 -0.7131 -0.4344 -0.811 -0.6666 -0.7859 -0.811 0.0 -0.3401; -0.2515 -0.7612 -0.6897 0.5361 -0.7612 -0.454 -0.5995 -0.811 0.04264 -0.6897 -0.415 -0.5564 -0.7612 -0.08927 0.5361 0.05658 0.5753 -0.02915 0.6135 -0.811; -0.811 0.6415 0.6323 -0.1844 -0.6897 -0.7612 -0.6666 -0.737 -0.1361 -0.08927 -0.4344 -0.811 -0.152 0.433 0.05658 0.4005 -0.1361 -0.7131 0.3334 -0.811; 0.3334 -0.1361 -0.4739 -0.5353 -0.5564 -0.811 0.5656 -0.1203 -0.6897 -0.811 -0.2688 -0.7859 0.251 0.4751 0.07039 -0.04394 -0.6215 -0.811 -0.1681 -0.811; -0.6215 -0.7859 0.5059 0.4751 -0.811 -0.811 0.6415 -0.811 -0.5353 -0.6897 -0.7131 0.1375 -0.811 0.546 -0.2688 -0.7859 -0.4344 -0.05889 -0.6897 -0.811; -0.7859 -0.7859 0.3674 -0.3344 -0.811 0.2265 -0.7859 -0.6215 -0.415 -0.0145 0.07039 -0.7612 -0.1361 0.2141 -0.7612 0.2265 -0.7612 0.4114 -0.737 -0.4941; -0.4889 -0.5146 0.05658 -0.7859 -0.6215 -0.2688 -0.2863 -0.4889 -0.811 -0.811 -0.7859 0.4751 -0.811 -0.811 -0.737 -0.811 -0.811 -0.2009 -0.6439 0.3785; -0.811 -0.1888 -0.05889 0.6415 -0.737 0.09761 0.5361 -0.5146 0.4542 -0.811 -0.811 -0.811 -0.1888 -0.1888 0.0 0.3448 0.3674 -0.3401 -0.7131 -0.04394; -0.811 0.09761 0.09761 0.6229 -0.7612 -0.6215 -0.1203 -0.3979 -0.7612 -0.2688 -0.7612 -0.3979 -0.5778 -0.811 -0.811 0.5753 -0.811 -0.3979 -0.3979 -0.6439; -0.5995 -0.811 -0.6093 -0.6093 0.1763 -0.811 -0.6093 -0.6093 -0.811 -0.4941 -0.7859 -0.811 -0.7612 -0.6215 -0.5353 -0.811 -0.6093 -0.5995 -0.5778 -0.2863; -0.2232 -0.2232 -0.5146 0.263 -0.2232 -0.737 -0.811 -0.6666 0.1763 0.1635 -0.4739 -0.2232 0.5261 0.5558 0.4436 -0.7131 -0.2232 -0.2232 -0.5995 -0.737; 0.5059 0.4436 -0.2349 -0.2349 -0.1203 -0.2349 -0.2349 -0.3585 -0.737 -0.7859 -0.1047 0.01436 0.1243 -0.7859 -0.2349 0.2987 -0.2349 -0.737 -0.811 -0.2349; 0.516 -0.3675 -0.3675 -0.304 -0.7859 -0.3675 0.4957 -0.3675 -0.3675 -0.4739 -0.3675 -0.3675 -0.3675 -0.5778 -0.5146 -0.2009 -0.737 -0.7131 -0.304 -0.811; -0.2489 0.5753 -0.2489 -0.2489 -0.5995 -0.2489 0.5558 -0.811 -0.2489 -0.2489 -0.7612 -0.2489 0.263 -0.6897 -0.3959 -0.5995 -0.811 0.5361 -0.2489 -0.2489; 0.2265 -0.328 -0.328 -0.328 -0.328 -0.328 -0.454 -0.328 -0.328 -0.328 -0.328 -0.328 -0.7612 -0.04394 -0.7131 -0.811 -0.415 -0.1361 -0.7859 0.6135; -0.811 -0.4688 -0.304 -0.811 -0.4688 -0.3771 -0.7612 -0.4688 -0.152 -0.4688 -0.4688 -0.4688 -0.4344 -0.4688 -0.6666 -0.4688 -0.4688 -0.4688 -0.4688 0.09761; -0.3384 -0.3384 0.4957 -0.3384 -0.3384 -0.0145 -0.3384 -0.3384 -0.3384 -0.3384 0.1506 -0.3384 -0.3384 -0.811 -0.5146 -0.7859 -0.7131 -0.3384 -0.3384 -0.5146; -0.3846 -0.3846 -0.3846 -0.3846 -0.2515 -0.737 -0.3846 -0.5564 -0.3846 0.09761 -0.3846 -0.3846 -0.3846 -0.3846 -0.3846 -0.3846 -0.3846 -0.4739 -0.1047 -0.6666; -0.4036 -0.4036 -0.4036 -0.4036 -0.5778 -0.4036 -0.4036 -0.7859 -0.7612 -0.4036 -0.7859 -0.4036 -0.4036 -0.4036 -0.4036 0.275 -0.4036 0.2141 -0.4036 -0.4036; -0.6108 -0.6108 -0.6108 -0.7131 -0.6108 -0.6108 -0.6215 -0.4739 -0.4344 -0.6108 -0.6108 -0.6108 -0.6108 -0.6108 -0.6108 -0.811 -0.6108 -0.6108 -0.6108 -0.6108; 0.1243 0.251 -0.2699 -0.6439 -0.2699 -0.2699 -0.2699 -0.2699 -0.2699 -0.2699 -0.2699 -0.2699 -0.2699 -0.2699 -0.811 -0.2699 -0.2699 -0.2699 -0.2699 -0.2699; -0.7074 -0.6215 -0.7074 -0.7074 -0.7074 -0.7074 -0.811 -0.7074 -0.7074 -0.7074 -0.7074 -0.7074 -0.7074 -0.6897 -0.7074 -0.7074 -0.7074 -0.7074 -0.7074 -0.7074; -0.2445 -0.2445 -0.2445 -0.2445 -0.2445 -0.2445 -0.2445 0.3219 -0.2445 -0.811 -0.2445 -0.2445 -0.2445 -0.2445 -0.2445 -0.2445 -0.2445 -0.2445 -0.2445 -0.2445; -0.7131 -0.7131 -0.7131 -0.7131 -0.7131 -0.7131 -0.7131 -0.7131 -0.7131 -0.7131 -0.7131 -0.7131 -0.7131 -0.7131 -0.7131 -0.7131 -0.7131 -0.7131 -0.7131 -0.7131; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0] filepath = joinpath(@__DIR__, "data/data_missing.tsv") varIds = [Symbol("V$i") for i=1:40] sampleIds = [string('S',lpad(i,2,'0')) for i=1:20] groupAnnot = repeat(["A","B"],inner=10) timeAnnot = vcat(0.01:0.01:0.1, 0.01:0.01:0.1) app = MiniApp() init(app) # Open file setvalue(app, Any["samplefilepath", filepath]) setvalue(app, Any["lastsampleannot", "Time"]) setvalue(app, Any["normalizemethod", "None"]) put!(app.fromGUI, :normalize=>[]) @test runall(app) sampleData = app.jg.scheduler.jobs[app.jg.normalizeID].result @test sampleData.data ≈ reconstructed setvalue(app, Any["logtransform", "true"]) setvalue(app, Any["logtransformoffset", "0.57"]) put!(app.fromGUI, :normalize=>[]) @test runall(app) sampleData = app.jg.scheduler.jobs[app.jg.normalizeID].result @test sampleData.data ≈ logReconstructed atol=1e-3 end end
PrincipalMomentAnalysisApp
https://github.com/PrincipalMomentAnalysis/PrincipalMomentAnalysisApp.jl.git
[ "MIT" ]
0.2.6
7a89075c252d95cd9530f937158955939c218425
code
130
@testset "content" begin doc = read("../src/content.html",String) @test occursin("""<script type="text/javascript">""", doc) end
PrincipalMomentAnalysisApp
https://github.com/PrincipalMomentAnalysis/PrincipalMomentAnalysisApp.jl.git
[ "MIT" ]
0.2.6
7a89075c252d95cd9530f937158955939c218425
code
1957
struct MiniApp jg::JobGraph fromGUI::Channel{Pair{Symbol,Vector}} toGUI::Channel{Pair{Symbol,Any}} lastSchedulerTime::Ref{UInt64} end MiniApp() = MiniApp(JobGraph(verbose=true), Channel{Pair{Symbol,Vector}}(Inf), Channel{Pair{Symbol,Any}}(Inf), Ref{UInt64}(0)) setvalue(app::MiniApp, value::Array{Any}) = put!(app.fromGUI, :setvalue=>value) function init(app::MiniApp) setvalue(app, Any["samplesimplexmethod", "SA"]) setvalue(app, Any["loadrowsassamples", "true"]) setvalue(app, Any["logtransform", "false"]) setvalue(app, Any["logtransformoffset", "1"]) setvalue(app, Any["normalizemethod", "Mean=0"]) setvalue(app, Any["dimreductionmethod", "PMA"]) setvalue(app, Any["knearestneighbors", "0"]) setvalue(app, Any["distnearestneighbors", "0"]) setvalue(app, Any["xaxis", "1"]) setvalue(app, Any["yaxis", "2"]) setvalue(app, Any["zaxis", "3"]) setvalue(app, Any["plotwidth", "1024"]) setvalue(app, Any["plotheight", "768"]) setvalue(app, Any["showpoints", "true"]) setvalue(app, Any["showlines", "true"]) setvalue(app, Any["showtriangles", "false"]) setvalue(app, Any["markersize", "4"]) setvalue(app, Any["linewidth", "1"]) setvalue(app, Any["triangleopacity", "0.05"]) setvalue(app, Any["colorby", "Auto"]) setvalue(app, Any["exportmode", "Variables"]) setvalue(app, Any["exportsingledim", "1"]) setvalue(app, Any["exportsinglesort", "Abs"]) setvalue(app, Any["exportmultipledim", "3"] ) end function runall(app::MiniApp) while isready(app.fromGUI) || wantstorun(app.jg.scheduler) || isactive(app.jg.scheduler) process_step(app.jg, app.fromGUI, app.toGUI, app.lastSchedulerTime; verbosityLevel=2) || return false end true end function factorizationcmp(F1,F2) @test size(F1.U)==size(F2.U) @test size(F1.S)==size(F2.S) @test size(F1.V)==size(F2.V) @test size(F1.Vt)==size(F2.Vt) @test F1.S ≈ F2.S sgn = sign.(diag(F1.U'F2.U)) @test F1.U.*sgn' ≈ F2.U @test F1.V.*sgn' ≈ F2.V @test F1.Vt.*sgn ≈ F2.Vt nothing end
PrincipalMomentAnalysisApp
https://github.com/PrincipalMomentAnalysis/PrincipalMomentAnalysisApp.jl.git
[ "MIT" ]
0.2.6
7a89075c252d95cd9530f937158955939c218425
docs
5444
# Principal Moment Analysis App [![Build Status](https://github.com/PrincipalMomentAnalysis/PrincipalMomentAnalysisApp.jl/workflows/CI/badge.svg)](https://github.com/PrincipalMomentAnalysis/PrincipalMomentAnalysisApp.jl/actions) The Principal Moment Analysis App is a simple GUI Application for exploring data sets using Principal Moment Analysis. See below for usage instructions. For more information about Principal Moment Analysis, please refer to: * [Principal Moment Analysis home page](https://principalmomentanalysis.github.io/). * [PrincipalMomentAnalysis.jl](https://principalmomentanalysis.github.io/PrincipalMomentAnalysis.jl). If you want to cite our work, please use: > [Fontes, M., & Henningsson, R. (2020). Principal Moment Analysis. arXiv arXiv:2003.04208.](https://arxiv.org/abs/2003.04208) ## Installation To install PrincipalMomentAnalysisApp.jl, start Julia and type: ```julia using Pkg Pkg.add("PrincipalMomentAnalysisApp") ``` ## Running the App *Option 1* Start Julia and run: ```julia using PrincipalMomentAnalysisApp pmaapp() ``` *Option 2* Run the following command from a terminal/command prompt: ``` julia -e "using PrincipalMomentAnalysisApp; pmaapp()" ``` Note that this requires julia to be in the PATH. ## Using the App <img src="https://github.com/PrincipalMomentAnalysis/PrincipalMomentAnalysisApp.jl/blob/master/docs/src/images/app1.png" alt="App before loading a file" title="App before loading a file" width="341" height="563">&nbsp;&nbsp;<img src="https://github.com/PrincipalMomentAnalysis/PrincipalMomentAnalysisApp.jl/blob/master/docs/src/images/app2.png" alt="App after loading a file" title="App after loading a file" width="341" height="563"> ### Loading a file PrincipalMomentAnalysisApp can load *.csv* (comma-separated values) or *.tsv* (tab-separated values) files, *.txt* and other extensions are treated as *.tsv*. You can choose whether samples are described by rows or columns. Input file example: | Sample ID | Sample Annotation 1 | Sample Annotation 2 | ... | Variable 1 | Variable 2 | ... | | --------- | ------------------- | ------------------- | --- | ---------- | ---------- | --- | | A | Group1 | 0.1 | ... | 0.0 | 0.5 | ... | | B | Group1 | 0.4 | ... | 1.0 | 0.2 | ... | | C | Group2 | 2.0 | ... | 0.3 | 0.8 | ... | After loading a file, you need to choose the last sample annotation in the dropdown list. This is **important**, since the rest of the columns will be used as variables. ### Normalization * *None*: The data matrix is not modified. * *Mean=0*: Variables are centered. * *Mean=0,Std=1*: Variables are centered and their standard deviations are normalized to 1. ### Dimension Reduction In addition to **PMA** (Principal Moment Analysis), you can also choose **PCA** (Principal Component Analysis) for reference. **PCA** is a special case of **PMA** with point masses for each sample. **PMA** is a flexible method where we can use our knowledge about the data to improve the dimension reduction. In the GUI, you can choose between four different methods for how to create the simplices that represent our data set. * *Sample Annotation*: All samples sharing the same value of the chosen *sample annotation* will be connected to form a simplex. The total weight of each simplex is equal to the number of samples forming the simplex. * *Time Series*: First the samples are divided into groups by the chosen *sample annotation*. Then simplices are formed by connecting each sample to the previous and next sample according to the *time annotation*. (If there are ties, all samples at a timepoint will be connected to all samples at the previous/next timepoints.) * *Nearest Neighbors*: For each sample, a simplex is created by connecting to the chosen number of nearest neighbors. You can also chose to connect a sample to neighbours within a distance threshold (normalized such that a distance of 0.5 is the distance between the origin and the sample furthest away from the origin). To reduce noise, distances between samples are computed after reducing the dimension to 50 by PCA. * *Nearest Neighbors within groups*: As for *Nearest Neighbors*, but samples are only connected if they share the same value of the chosen *sample annotation*. ### Plotting The plotting options allow you to visualize the samples and the simplices after dimension reduction. (If you chose **PCA** above, the simplices will still be visualized, but the dimension reduction will be computed by PCA.) * Axes: You can choose which Principal Moment Axis (PMA) to display for the *x*, *y*, and *z* axes respectively. This is useful for exploring more than the first 3 dimensions. * Plot size: Control the width/height of the plotting area. * Color: Decide which *sample annotation* to use for coloring the samples. For numerical data, a continuous color scale will be used. * Points: Enable/disable drawing of the sample points and choose their size. * Lines: Enable/disable drawing of the simplex edges and choose line width. * Triangles: Enable/disable drawing of the simplex facets and choose opacity. Press the "Show Plot" button to open the plot in a new window. ### Export Principal Moment Axes The PMAs, giving you the low-dimensional representations of variables/samples, can be exported to text files. The exported files are tab-separated (or comma-separated if the file extension is *.csv*). When exporing a single PMA, you can also choose the sorting.
PrincipalMomentAnalysisApp
https://github.com/PrincipalMomentAnalysis/PrincipalMomentAnalysisApp.jl.git
[ "MIT" ]
0.1.2
b0b395f51a4bc5cc94bb7cc82fbab56df694d278
code
184
module ProjectEulerUtil # Write your package code here. include("proper_divisors.jl") include("abundant-numbers.jl") include("inverse_digits.jl") include("get_problem_title.jl") end
ProjectEulerUtil
https://github.com/xiaodaigh/ProjectEulerUtil.jl.git
[ "MIT" ]
0.1.2
b0b395f51a4bc5cc94bb7cc82fbab56df694d278
code
98
export proper_divisors, is_abundant is_abundant(n) = begin sum(proper_divisors(n)) > n end
ProjectEulerUtil
https://github.com/xiaodaigh/ProjectEulerUtil.jl.git
[ "MIT" ]
0.1.2
b0b395f51a4bc5cc94bb7cc82fbab56df694d278
code
361
using Gumbo, HTTP, AbstractTrees export get_problem_title get_problem_title(pn) = begin p = HTTP.get("https://projecteuler.net/problem=$pn").body |> String |> parsehtml for elem in PreOrderDFS(p.root) if elem isa HTMLElement if tag(elem) == :h2 return elem.children[1].text end end end end
ProjectEulerUtil
https://github.com/xiaodaigh/ProjectEulerUtil.jl.git
[ "MIT" ]
0.1.2
b0b395f51a4bc5cc94bb7cc82fbab56df694d278
code
115
export inverse_digits inverse_digits(digits, base = 10) = sum([digits[k] * base^(k - 1) for k = 1:length(digits)])
ProjectEulerUtil
https://github.com/xiaodaigh/ProjectEulerUtil.jl.git
[ "MIT" ]
0.1.2
b0b395f51a4bc5cc94bb7cc82fbab56df694d278
code
736
using Primes using Base.Iterators: drop, product proper_divisors(n) = begin if n == 1 return [1] end factors_of_n = factor(n) nfactors = prod(x -> x[2] + 1, factors_of_n) res = Vector{Int}(undef, nfactors) res .= 1 i = 1 for (factor, power) in factors_of_n if i == 1 res[1] = 1 res[2:power+1] .= factor .^ (1:power) i = power + 1 else next_few = i * power next_few_vals = [ existing * more for (existing, more) in product(res[1:i], factor .^ (1:power)) ] res[i+1:i+next_few] = vec(next_few_vals) i += next_few end end res[1:end-1] end
ProjectEulerUtil
https://github.com/xiaodaigh/ProjectEulerUtil.jl.git
[ "MIT" ]
0.1.2
b0b395f51a4bc5cc94bb7cc82fbab56df694d278
code
105
using ProjectEulerUtil using Test @testset "ProjectEulerUtil.jl" begin # Write your tests here. end
ProjectEulerUtil
https://github.com/xiaodaigh/ProjectEulerUtil.jl.git
[ "MIT" ]
0.1.2
b0b395f51a4bc5cc94bb7cc82fbab56df694d278
docs
220
# ProjectEulerUtil `is_abundant` checks if a number is abundant `get_problem_title(n)` get the title of the `n`th question `inverse_digits(digits(n))` gives `n` `proper_divisors(n)` gives the proper divisors of `n`
ProjectEulerUtil
https://github.com/xiaodaigh/ProjectEulerUtil.jl.git
[ "MIT" ]
0.1.2
90950ef1bc004499811fe377dabe84b3292a8f10
code
160
using Documenter, DocumenterMarkdown, LaurentPolynomials makedocs(sitename="Laurent polynomials documentation",format=Markdown(),modules=[LaurentPolynomials])
LaurentPolynomials
https://github.com/jmichel7/LaurentPolynomials.jl.git
[ "MIT" ]
0.1.2
90950ef1bc004499811fe377dabe84b3292a8f10
code
29919
""" This package implements univariate Laurent polynomials, and univariate rational fractions. The coefficients can be in any ring (possibly even non-commutative, like `Matrix{Int}). The initial motivation in 2018 was to have an easy way to port GAP polynomials to Julia. The reasons for still having my own package are multiple: - I need my polynomials to behave well when the coefficients are in a ring, in which case I use pseudo-division and subresultant gcd. - I need my polynomials to work as well as possible with coefficients of type `T` where the elements have a `zero` method but `T` itself does not have one, because `T` does not contain the necessary information. An example is modular arithmetic with a `BigInt` modulus which cannot be part of the type. For this reason the `zero` polynomial does not have an empty list of coefficients, but a list containing an element equal to zero, so it is always possible to get a zero of type T from the zero polynomial. - `LaurentPolynomials` is designed to be used by `PuiseuxPolynomials`. - Often my polynomials are several times faster than those in the `Polynomials` package. In addition, the interface is simple and flexible. The only package this package depends on is `LinearAlgebra`, through the use of the `exactdiv` function. Laurent polynomials are of the parametric type `Pol{T}`, where `T`is the type of the coefficients. They are constructed by giving a vector of coefficients of type `T`, and a valuation (an `Int`). We call true polynomials those whose valuation is `≥0`. There is a current variable name (a `Symbol`) which is used to print polynomials nicely at the repl or in IJulia or Pluto. This name can be changed globally, or just for printing a specific polynomial. However, polynomials do not individually record which symbol they should be printed with. # Examples ```julia-repl julia> Pol(:q) # define symbol used for printing and return Pol([1],1) Pol{Int64}: q julia> @Pol q # same as q=Pol(:q) useful to start session with polynomials Pol{Int64}: q julia> Pol([1,2]) # valuation is taken to be 0 if omitted Pol{Int64}: 2q+1 julia> 2q+1 # same polynomial Pol{Int64}: 2q+1 julia> Pol() # omitting all arguments gives Pol([1],1) Pol{Int64}: q julia> p=Pol([1,2,1],-1) # here the valuation is specified to be -1 Pol{Int64}: q+2+q⁻¹ julia> q+2+q^-1 # same polynomial Pol{Int64}: q+2+q⁻¹ ``` ```julia-rep1 julia> print(p) # if not nice printing give an output which can be read back Pol([1, 2, 1],-1) # change the variable for printing just this time julia> print(IOContext(stdout,:limit=>true,:varname=>"x"),p) x+2+x⁻¹ julia> print(IOContext(stdout,:TeX=>true),p) # TeXable output (used in Pluto, IJulia) q+2+q^{-1} ``` A polynomial can be taken apart with the functions `valuation`, `degree` and `getindex`. An index `p[i]` returns the coefficient of degree `i` of `p`. ```julia-repl julia> valuation(p),degree(p) (-1, 1) julia> p[0], p[1], p[-1], p[10] (2, 1, 1, 0) julia> p[valuation(p):degree(p)] 3-element Vector{Int64}: 1 2 1 julia> p[begin:end] # the same as the above line 3-element Vector{Int64}: 1 2 1 julia> coefficients(p) # the same again 3-element Vector{Int64}: 1 2 1 ``` The coefficients can come from any ring: ```julia-repl julia> h=Pol([[1 1;0 1],[1 0; 0 1]]) Pol{Matrix{Int64}}: [1 0; 0 1]q+[1 1; 0 1] julia> h^3 Pol{Matrix{Int64}}: [1 0; 0 1]q³+[3 3; 0 3]q²+[3 6; 0 3]q+[1 3; 0 1] ``` A polynomial is a *scalar* if its valuation and degree are `0`. The `scalar` function returns the constant coefficient if the polynomial is a scalar, and `nothing` otherwise. ```julia-repl julia> Pol(1) Pol{Int64}: 1 julia> convert(Pol{Int},1) # the same thing Pol{Int64}: 1 julia> scalar(Pol(1)) 1 julia> convert(Int,Pol(1)) # the same thing 1 julia> Int(Pol(1)) # the same thing 1 julia> scalar(q+1) # nothing; convert would give an error ``` In arrays `Pol{T}` of different types `T` are promoted to the same type `T` (if the `T` involved have a promotion) and a number is promoted to a polynomial. Usual arithmetic (`+`, `-`, `*`, `^`, `/`, `//`, `one`, `isone`, `zero`, `iszero`, `==`) works. Elements of type `<:Number` or of type `T` for a `Pol{T}` are considered as scalars for scalar operations on the coefficients. ```julia-repl julia> derivative(p) Pol{Int64}: 1-q⁻² julia> p=(q+1)^2 Pol{Int64}: q²+2q+1 julia> p/2 Pol{Float64}: 0.5q²+1.0q+0.5 julia> p//2 Pol{Rational{Int64}}: (1//2)q²+q+1//2 julia> p(1//2) # value of p at 1//2 9//4 julia> p(0.5) 2.25 julia> Pol([1,2,3],[2.0,1.0,3.0]) # find p taking values [2.0,1.0,3.0] at [1,2,3] Pol{Float64}: 1.5q²-5.5q+6.0 ``` Polynomials are scalars for broadcasting. They can be sorted (they have `cmp` and `isless` functions which compare the valuation and the coefficients), they can be keys in a `Dict` (they have a `hash` function). The functions `divrem`, `div`, `%`, `gcd`, `gcdx`, `lcm`, `powermod` operate between true polynomials over a field, using the polynomial division. Over a ring it is better to use `pseudodiv` and `srgcd` instead of `divrem` and `gcd` (by default `gcd` between integer polynomials delegates to `srgcd`). `LinearAlgebra.exactdiv` does division (over a field or a ring) when it is exact, otherwise gives an error. ```julia-repl julia> divrem(q^3+1,2q+1) # changes coefficients to field elements (0.5q²-0.25q+0.125, 0.875) julia> divrem(q^3+1,2q+1//1) # case of coefficients already field elements ((1//2)q²+(-1//4)q+1//8, 7//8) julia> pseudodiv(q^3+1,2q+1) # pseudo-division keeps the ring (4q²-2q+1, 7) julia> (4q^2-2q+1)*(2q+1)+7 # but multiplying back gives a multiple of the polynomial Pol{Int64}: 8q³+8 julia> LinearAlgebra.exactdiv(q+1,2.0) # LinearAlgebra.exactdiv(q+1,2) would give an error Pol{Float64}: 0.5q+0.5 ``` Finally, `Pol`s have methods `conj`, `adjoint` which operate on coefficients, methods `positive_part`, `negative_part` and `bar` (useful for Kazhdan-Lusztig theory) and a method `randpol` to produce random polynomials. Inverting polynomials is a way to get a rational fraction `Frac{Pol{T}}`, where `Frac` is a general type for fractions. Rational fractions are normalised so that the numerator and denominator are true polynomials that are prime to each other. They have the arithmetic operations `+`, `-` , `*`, `/`, `//`, `^`, `inv`, `one`, `isone`, `zero`, `iszero` (which can operate between a `Pol` or a `Number` and a `Frac{Pol{T}}`). ```julia-repl julia> a=1/(q+1) Frac{Pol{Int64}}: 1/(q+1) julia> Pol(2/a) # convert back to `Pol` Pol{Int64}: 2q+2 julia> numerator(a) Pol{Int64}: 1 julia> denominator(a) Pol{Int64}: q+1 julia> m=[q+1 q+2;q-2 q-3] 2×2 Matrix{Pol{Int64}}: q+1 q+2 q-2 q-3 julia> n=inv(Frac.(m)) # convert to rational fractions to invert the matrix 2×2 Matrix{Frac{Pol{Int64}}}: (-q+3)/(2q-1) (-q-2)/(-2q+1) (q-2)/(2q-1) (q+1)/(-2q+1) julia> map(x->x(1),n) # evaluate at 1 the inverse matrix 2×2 Matrix{Float64}: 2.0 3.0 -1.0 -2.0 julia> map(x->x(1;Rational=true),n) # evaluate at 1 using // 2×2 Matrix{Rational{Int64}}: 2 3 -1 -2 ``` Rational fractions are also scalars for broadcasting and can be sorted (have `cmp` and `isless` methods). """ module LaurentPolynomials export degree, valuation, Pol, derivative, shift, positive_part, negative_part, bar, derivative, srgcd, Frac, @Pol, scalar, coefficients, root, randpol, pseudodiv, resultant, discriminant using LinearAlgebra:LinearAlgebra, exactdiv, det_bareiss varname::Symbol=:x struct Pol{T} c::Vector{T} v::Int # Unexported inner constructor that bypasses all checks global Pol_(c::AbstractVector{T},v::Integer) where T=new{T}(c,v) end """ `Pol(c::AbstractVector,v::Integer=0;check=true,copy=true)` Make a polynomial of valuation `v` with coefficients `c`. Then, unless `check` is `false` normalize the result by making sure that `c` has no leading or trailing zeroes (do not set `check=false` unless you are sure this is already the case). Unless `copy=false` the contents of `c` are copied (you can gain one allocation by setting `copy=false` if you know the contents can be shared) """ function Pol(c::AbstractVector{T},v::Integer=0;check=true,copy=true)where T if check # normalize c so there are no leading or trailing zeroes b=findfirst(!iszero,c) if b===nothing if length(c)>0 return Pol_([c[1]],0) else return Pol_([T(0)],0) # try to avoid this case end end e=findlast(!iszero,c) if b!=1 || e!=length(c) || copy return Pol_(view(c,b:e),v+b-1) end end Pol_(copy ? Base.copy(c) : c,v) end Pol()=Pol_([1],1) Pol(a::T) where T<:Number=Pol_([a],0) """ `Pol(t::Symbol)` Sets the name of the variable for printing `Pol`s to `t`, and returns the polynomial of degree 1 equal to that variable. """ function Pol(t::Symbol) LaurentPolynomials.varname=t Pol() end """ `@Pol q` is equivalent to `q=Pol(:q)` except that it creates `q` in the global scope of the current module, since it uses `eval`. """ macro Pol(t) if !(t isa Symbol) error("usage: @Pol <variable name>") end Base.eval(Main,:($t=Pol($(Core.QuoteNode(t))))) end Base.broadcastable(p::Pol)=Ref(p) Base.copy(p::Pol)=Pol_(copy(p.c),p.v) degree(a::Number)=0 # convenient degree(p::Pol)=length(p.c)-1+p.v valuation(p::Pol)=p.v coefficients(p::Pol)=p.c Base.lastindex(p::Pol)=degree(p) Base.firstindex(p::Pol)=valuation(p) @inbounds Base.getindex(p::Pol{T},i::Integer) where T= i in firstindex(p):lastindex(p) ? p.c[i-p.v+1] : zero(p.c[1]) Base.getindex(p::Pol,i::AbstractVector{<:Integer})=getindex.(Ref(p),i) Base.convert(::Type{Pol{T}},a::Number) where T=Pol_([T(a)],0) (::Type{Pol{T}})(a) where T=convert(Pol{T},a) # like convert for vectors does not always make a copy Base.convert(::Type{Pol{T}},p::Pol{T1}) where {T,T1}=Pol_(Vector{T}(p.c),p.v) function Base.promote_rule(a::Type{Pol{T1}},b::Type{Pol{T2}})where {T1,T2} Pol{promote_type(T1,T2)} end function Base.promote_rule(a::Type{Pol{T1}},b::Type{T2})where {T1,T2<:Number} Pol{promote_type(T1,T2)} end Base.isinteger(p::Pol)=isinteger(scalar(p)) function scalar(p::Pol{T})where T if iszero(valuation(p)) && iszero(degree(p)) p[0] end end function Base.convert(::Type{T},p::Pol) where T<:Number res=scalar(p) if res===nothing throw(InexactError(:convert,T,p)) end convert(T,res) end (::Type{T})(p::Pol) where T<:Number=convert(T,p) Base.cmp(a::Pol,b::Pol)=cmp((!iszero(a),a.v,a.c),(!iszero(b),b.v,b.c)) Base.isless(a::Pol,b::Pol)=cmp(a,b)==-1 Base.hash(a::Pol, h::UInt)=hash(a.v,hash(a.c,h)) (p::Pol{T})(x) where T=evalpoly(x,p.c)*x^p.v """ `shift(p::Pol,s)` efficient way to multiply a polynomial by `Pol()^s`. """ shift(p::Pol{T},s) where T=Pol_(p.c,p.v+s) "`positive_part(p::Pol)` keep the terms of degree≥0" positive_part(p::Pol)=p.v>=0 ? copy(p) : Pol(view(p.c,1-p.v:length(p.c)),0) "`negative_part(p::Pol)` keep the terms of degree≤0" negative_part(p::Pol)=degree(p)<=0 ? copy(p) : Pol(view(p.c,1:1-p.v),p.v) # q↦ q⁻¹ on p "`bar(p::Pol)` transform p(q) into p(q⁻¹)" bar(p::Pol)=Pol_(reverse(p.c),-degree(p)) Base.:(==)(a::Pol, b::Pol)= a.c==b.c && a.v==b.v Base.:(==)(a::Pol{T},b::Union{Number,T}) where T=b!==nothing && scalar(a)==b Base.:(==)(b::Union{Number,T},a::Pol{T}) where T=b!==nothing && scalar(a)==b Base.one(a::Pol)=Pol_([one(a.c[1])],0) Base.one(::Type{Pol{T}}) where T=Pol_([one(T)],0) # try to avoid this Base.isone(a::Pol)=scalar(a)==1 Base.zero(::Type{Pol{T}}) where T=Pol_([T(0)],0) # try to avoid this Base.zero(a::Pol)=Pol_([zero(a.c[1])],0) Base.iszero(a::Pol)=length(a.c)==1 && iszero(a.c[1]) # next 4 stuff to make transpose and inv using LU work (abs is stupid) Base.conj(p::Pol{T}) where T=Pol_(conj.(p.c),p.v) Base.abs(p::Pol)=p Base.adjoint(a::Pol)=conj(a) Base.transpose(a::Pol)=a ismonomial(p::Pol)=length(p.c)==1 function Base.show(io::IO, ::MIME"text/html", a::Pol) print(io, "\$") show(IOContext(io,:TeX=>true),a) print(io, "\$") end function Base.show(io::IO, ::MIME"text/plain", a::Pol) if !haskey(io,:typeinfo) print(io,typeof(a),": ") io=IOContext(io,:typeinfo=>typeof(a)) end show(io,a) end # 3 next methods copied from Format.jl in order to have a self-contained file. # determines when coefficients should be bracketed for unambiguous display function bracket_if_needed(c::String) if match(r"^[-+]?([^-+*/]|√-|{-)*(\(.*\))?$",c)!==nothing c else "("*c*")" end end function format_coefficient(c::String) if c=="1" "" elseif c=="-1" "-" else bracket_if_needed(c) end end const supvec=['⁰','¹','²','³','⁴','⁵','⁶','⁷','⁸','⁹'] function stringexp(io::IO,n::Integer) if isone(n) "" elseif get(io,:TeX,false) n in 0:9 ? "^"*string(n) : "^{"*string(n)*"}" elseif get(io,:limit,false) res=Char[] if n<0 push!(res,'⁻'); n=-n end for i in reverse(digits(n)) push!(res,supvec[i+1]) end String(res) else "^"*string(n) end end function Base.show(io::IO,p::Pol{T})where T if !get(io,:limit,false) && !get(io,:TeX,false) if ismonomial(p) && isone(p.c[1]) && p.v==1 && T==Int print(io,"Pol()") else print(io,"Pol(",p.c) if !iszero(p.v) print(io,",",p.v) end print(io,")") end elseif iszero(p) print(io,"0") else var=string(get(io,:varname,varname)) for deg in degree(p):-1:valuation(p) c=p[deg] if iszero(c) continue end c=repr(c; context=IOContext(io,:typeinfo=>typeof(c))) if !iszero(deg) c=format_coefficient(c)*var*stringexp(io,deg) end if c[1]!='-' && deg!=degree(p) c="+"*c end print(io,c) end end end function Base.:*(a::Pol{T1},b::Pol{T2})where {T1,T2} T=promote_type(T1,T2) if iszero(a) || iszero(b) return Pol([a.c[1]*b.c[1]]) end # below not zero(T) for types T like Mod{T1} which have no zero method res=fill(zero(a.c[1]*b.c[1]),length(a.c)+length(b.c)-1) for i in eachindex(a.c), j in eachindex(b.c) @inbounds res[i+j-1]+=a.c[i]*b.c[j] end Pol_(res,a.v+b.v) end Base.:*(a::Pol, b::Number)=Pol(a.c.*Ref(b),a.v) Base.:*(a::Pol{T}, b::T) where T=Pol(a.c.*Ref(b),a.v;copy=false) Base.:*(b::Number, a::Pol)=Pol(Ref(b).*a.c,a.v) Base.:*(b::T, a::Pol{T}) where T=Pol(Ref(b).*a.c,a.v;copy=false) Base.:^(a::Pol, n::Real)=isinteger(n) ? a^Int(n) : root(a,1//n) Base.:^(a::Pol, n::Integer)=ismonomial(a) ? Pol_([a.c[1]^n],n*a.v) : n>=0 ? Base.power_by_squaring(a,n) : Base.power_by_squaring(inv(a),-n) function Base.:+(a::Pol,b::Pol) z=zero(a.c[1]+b.c[1]) d=b.v-a.v if d>=0 res=fill(z,max(length(a.c),d+length(b.c))) @inbounds view(res,eachindex(a.c)).=a.c @inbounds view(res,d.+eachindex(b.c)).+=b.c Pol(res,a.v;copy=false) else res=fill(z,max(length(a.c)-d,length(b.c))) @inbounds view(res,eachindex(a.c).-d).=a.c @inbounds view(res,eachindex(b.c)).+=b.c Pol(res,b.v;copy=false) end end function Base.:-(a::Pol,b::Pol) z=zero(a.c[1]+b.c[1]) d=b.v-a.v if d>=0 res=fill(z,max(length(a.c),d+length(b.c))) @inbounds view(res,eachindex(a.c)).=a.c @inbounds view(res,d.+eachindex(b.c)).-=b.c Pol(res,a.v;copy=false) else res=fill(z,max(length(a.c)-d,length(b.c))) @inbounds view(res,eachindex(a.c).-d).=a.c @inbounds view(res,eachindex(b.c)).-=b.c Pol(res,b.v;copy=false) end end Base.:+(a::Pol, b::Number)=a+Pol(b) Base.:+(b::Number, a::Pol)=Pol(b)+a Base.:-(a::Pol)=Pol_(-a.c,a.v) Base.:-(b::Number, a::Pol)=Pol(b)-a Base.:-(a::Pol,b::Number)=a-Pol(b) Base.div(a::Pol,b::Number)=Pol(div.(a.c,b),a.v;copy=false) # compared to LinearAlgebra.exactdiv this function gives an error if not exact #function exactdiv(a::Integer,b::Integer) # (d,r)=divrem(a,b) # if !iszero(r) error(b," does not exactly divide ",a) end # d #end function coeffexactdiv(a::Pol,b) if isone(b) return a end c=exactdiv.(a.c,b) Pol_(c,a.v) end LinearAlgebra.exactdiv(a::Pol,b::Number)=coeffexactdiv(a,b) Base.:/(p::Pol,q::Number)=Pol_(p.c./Ref(q),p.v) Base.://(p::Pol,q::Number)=Pol_(p.c.//Ref(q),p.v) Base.:/(p::Pol{T},q::T) where T=Pol_(p.c./Ref(q),p.v) Base.://(p::Pol{T},q::T) where T=Pol_(p.c.//Ref(q),p.v) derivative(a::Pol)=Pol([(i+a.v-1)*v for (i,v) in enumerate(a.c)],a.v-1,copy=false) """ `divrem(a::Pol, b::Pol)` `a` and `b` should be true polynomials (have a nonnegative valuation). Computes `(q,r)` such that `a=q*b+r` and `degree(r)<degree(b)`. It is type stable if the coefficients of `b` are in a field. """ function Base.divrem(a::Pol, b::Pol) if iszero(b) throw(DivideError) end if degree(b)>degree(a) return (zero(a),a) end if a.v<0 || b.v<0 error("arguments should be true polynomials") end a,b=promote(a,b) d=inv(b.c[end]) z=zero(a.c[1]+b.c[1]+d) r=fill(z,1+degree(a)) view(r,a.v+1:length(r)).=a.c q=fill(z,length(r)-degree(b)) for i in length(r):-1:degree(b)+1 if iszero(r[i]) c=zero(d) else c=r[i]*d view(r,i-length(b.c)+1:i).-=Ref(c).*b.c end q[i-degree(b)]=c end Pol(q),Pol(r) end function LinearAlgebra.exactdiv(a::Pol,b::Pol) if isone(b) || iszero(a) return a end if iszero(b) throw(DivideError) end d=a.v-b.v if !iszero(a.v) a=shift(a,-a.v) end if !iszero(b.v) b=shift(b,-b.v) end if degree(b)>degree(a) error(b," does not exactly divide ",a) end z=zero(a.c[1]+b.c[1]) r=fill(z,1+degree(a)) view(r,a.v+1:length(r)).=a.c q=fill(z,length(r)-degree(b)) for i in length(r):-1:degree(b)+1 c=exactdiv(r[i],b.c[end]) view(r,i-length(b.c)+1:i).-=Ref(c).*b.c q[i-length(b.c)+1]=c end if !iszero(r) error(b," does not exactly divide ",a) end res=Pol(q,d) end """ `pseudodiv(a::Pol, b::Pol)` pseudo-division of `a` by `b`. If `d` is the leading coefficient of `b`, computes `(q,r)` such that `d^(degree(a)+1-degree(b))a=q*b+r` and `degree(r)<degree(b)`. Does not do division so works over any ring. For true polynomials (errors if the valuation of `a` or of `b` is negative). ```julia-repl julia> pseudodiv(q^2+1,2q+1) (2q-1, 5) julia> (2q+1)*(2q-1)+5 Pol{Int64}: 4q²+4 ``` See Knuth AOCP2 4.6.1 Algorithm R """ function pseudodiv(a::Pol, b::Pol) if isone(b) || iszero(a) return a,zero(a) end if iszero(b) throw(DivideError) end d=b.c[end] if degree(a)<degree(b) return (zero(a),d^(degree(a)+1-degree(b))*a) end if a.v<0 || b.v<0 error("arguments should be true polynomials") end z=zero(a.c[1]+b.c[1]) r=fill(z,1+degree(a)) view(r,a.v+1:length(r)).=a.c q=fill(z,length(r)-degree(b)) for i in length(r):-1:degree(b)+1 c=r[i] r.*=Ref(d) q.*=Ref(d) if !iszero(c) for j in eachindex(b.c) r[j+i-length(b.c)]-=c*b.c[j] end end q[i-degree(b)]=c end Pol(q),Pol(r) end """ `srgcd(a::Pol,b::Pol)` sub-resultant gcd: gcd of polynomials over a unique factorization domain ```julia-repl julia> srgcd(4q+4,6q^2-6) Pol{Int64}: 2q+2 ``` See Knuth AOCP2 4.6.1 Algorithm C """ function srgcd(a::Pol,b::Pol) if iszero(b) return a end if iszero(a) return b end v=min(valuation(a),valuation(b)) a=shift(a,-valuation(a));b=shift(b,-valuation(b)) # reducing degree cheap if degree(b)>degree(a) return shift(srgcd(b,a),v) end ca=gcd(a.c);a=coeffexactdiv(a,ca) cb=gcd(b.c);b=coeffexactdiv(b,cb) d=gcd(ca,cb) g=one(a.c[1]) h=one(a.c[1]) while true δ=degree(a)-degree(b) q,r=pseudodiv(a,b) if iszero(r) cb=gcd(b.c);b=coeffexactdiv(b,cb) return isone(d) ? shift(b,v) : Pol_(b.c.*Ref(d),b.v+v) elseif degree(r)==0 return Pol_([d],v) end a=b gh=g*h^δ b=coeffexactdiv(r,gh) g=a[end] if δ>1 h=exactdiv(g^δ,h^(δ-1)) else h=g^δ*h^(1-δ) end end end Base.gcd(p::Pol{<:Integer},q::Pol{<:Integer})=srgcd(p,q) Base.gcd(v::AbstractArray{<:Pol})=reduce(gcd,v) Base.lcm(p::Pol,q::Pol)=exactdiv(p*q,gcd(p,q)) Base.lcm(m::AbstractArray{<:Pol})=reduce(lcm,m) Base.div(a::Pol, b::Pol)=divrem(a,b)[1] Base.:%(a::Pol, b::Pol)=divrem(a,b)[2] Base.:%(a::Pol{<:Integer}, b::Pol{<:Integer})=divrem(a,b)[2] """ `gcd(p::Pol, q::Pol)` computes the `gcd` of the polynomials. It uses the subresultant algorithms for the `gcd` of integer polynomials. ```julia-repl julia> gcd(2q+2,2q^2-2) Pol{Int64}: 2q+2 julia> gcd((2q+2)//1,(2q^2-2)//1) Pol{Rational{Int64}}: q+1 ``` """ function Base.gcd(p::Pol,q::Pol) if degree(q)>degree(p) p,q=q,p end p,q=promote(p,q) while !iszero(q) q=q/q.c[end] (q,p)=(divrem(p,q)[2],q) end p*inv(p.c[end]) end """ `gcdx(a::Pol,b::Pol)` for polynomials over a field returns `d,u,v` such that `d=ua+vb` and `d=gcd(a,b)`. ```julia-repl julia> gcdx(q^3-1//1,q^2-1//1) (q-1, 1, -q) ``` """ function Base.gcdx(a::Pol, b::Pol) a,b=promote(a, b) # a0, b0=a, b s0, s1=one(a), zero(a) t0, t1=s1, s0 # The loop invariant is: s0*a0 + t0*b0 == a x,y=a,b while y != 0 q,q1=divrem(x, y) x, y=y, q1 s0, s1=s1, s0 - q*s1 t0, t1=t1, t0 - q*t1 end (x, s0, t0)./Ref(x[end]) end """ `powermod(p::Pol, x::Integer, q::Pol)` computes ``p^x \\pmod m``. ```julia-repl julia> powermod(q-1//1,3,q^2+q+1) Pol{Rational{Int64}}: 6q+3 ``` """ function Base.powermod(p::Pol, x::Integer, q::Pol) x==0 && return one(q) b=p%q t=prevpow(2, x) r=one(p) while true if x>=t r=(r*b)%q x-=t end t >>>= 1 t<=0 && break r=(r*r)%q end r end """ `randpol(T,d)` random polynomial of degree `d` with coefficients from `T` """ randpol(T,d::Integer)=Pol(rand(T,d+1)) """ `Pol(x::AbstractVector,y::AbstractVector)` Interpolation: find a `Pol` (of nonnegative valuation) of smallest degree taking values `y` at points `x`. The values `y` should be in a field for the function to be type stable. ```julia-repl julia> p=Pol([1,1,1]) Pol{Int64}: q²+q+1 julia> vals=p.(1:5) 5-element Vector{Int64}: 3 7 13 21 31 julia> Pol(1:5,vals*1//1) Pol{Rational{Int64}}: q²+q+1 julia> Pol(1:5,vals*1.0) Pol{Float64}: 1.0q²+1.0q+1.0 ``` """ function Pol(pts::AbstractVector,vals::AbstractVector) vals=collect(vals) a=map(eachindex(pts))do i for k in i-1:-1:1 if pts[i]==pts[k] error("interpolating points must be distinct") end vals[k]=(vals[k+1]-vals[k])/(pts[i]-pts[k]) end vals[1] end p=Pol_([a[end]],0) for i in length(pts)-1:-1:1 p=p*(Pol()-pts[i])+a[i] end p end Base.denominator(p::Pol)=lcm(denominator.(p.c)) Base.numerator(p::Pol{<:Rational{T}}) where T=convert(Pol{T},p*denominator(p)) Base.numerator(p::Pol{<:Integer})=p function root(x::Pol,n::Union{Integer,Rational{<:Integer}}=2) n=Int(n) if !ismonomial(x) || !iszero(x.v%n) error("root($x,$n) not implemented") end c=x.c[1] Pol_([isone(c) ? c : root(c,n)],div(x.v,n)) end root(x::AbstractFloat,n=2)=x^(1/n) """ `resultant(p::Pol,q::Pol)` The function computes the resultant of the two polynomials, as the determinant of the Sylvester matrix. ``` """ function resultant(p::Pol,q::Pol) if iszero(p) || iszero(q) return zero(p) end l=max(0,degree(p)+degree(q)) if degree(p)==degree(q)==0 return one(p[end]) end m=fill(zero(p[end]),l,l) for i in 1:degree(q) m[i,i:i+degree(p)]=p[end:-1:0] end for i in 1:degree(p) m[i+degree(q),i:i+degree(q)]=q[end:-1:0] end det_bareiss(m) end """ `discriminant(p::Pol)` the resultant of the polynomial with its derivative. This detects multiple zeroes. """ discriminant(p::Pol)=resultant(p,derivative(p)) #---------------------- Frac------------------------------------- ## cannot use Rational{T} since it forces T<:Integer struct Frac{T} num::T den::T # Unexported inner constructor that bypasses all checks global Frac_(num::T,den::T) where T=new{T}(num,den) end Base.numerator(a::Frac)=a.num Base.denominator(a::Frac)=a.den Base.isfinite(x::Frac)=true function Base.convert(::Type{Frac{T}},p::Frac{T1}) where {T,T1} Frac_(convert(T,p.num),convert(T,p.den)) end (::Type{Frac{T}})(a::Frac) where {T}=convert(Frac{T},a) (::Type{Pol{T}})(a::Frac) where {T}=convert(Pol{T},a) (::Type{Frac{T}})(a::Number) where T=convert(Frac{T},a) Base.broadcastable(p::Frac)=Ref(p) Base.copy(a::Frac)=Frac_(a.num,a.den) Base.one(a::Frac)=Frac_(one(a.num),one(a.den)) Base.one(::Type{Frac{T}}) where T =Frac_(one(T),one(T)) # avoid this Base.isone(a::Frac)=a.num==a.den Base.zero(::Type{Frac{T}}) where T =Frac_(zero(T),one(T)) # avoid this Base.zero(a::Frac)=Frac_(zero(a.num),one(a.num)) Base.iszero(a::Frac)=iszero(a.num) # next 3 methods are to make inv using LU work (abs is stupid) Base.abs(p::Frac)=p Base.conj(p::Frac)=Frac_(conj(p.num),conj(p.den)) Base.adjoint(a::Frac)=conj(a) Base.:(==)(a::Frac,b::Frac)=a.num==b.num && a.den==b.den Base.cmp(a::Frac,b::Frac)=cmp((a.num,a.den),(b.num,b.den)) Base.hash(a::Frac, h::UInt)=hash(a.num,hash(a.den,h)) Base.isless(a::Frac,b::Frac)=cmp(a,b)==-1 function Base.show(io::IO, ::MIME"text/plain", a::Frac) if !haskey(io,:typeinfo) print(io,typeof(a),": ") io=IOContext(io,:typeinfo=>typeof(a)) end show(io,a) end function Base.show(io::IO,a::Frac) if !get(io, :limit, false) && !get(io, :TeX, false) print(io,"Frac(",a.num,",",a.den,")") return end if haskey(io,:typeinfo) && isone(a.den) print(io,a.num) return end n=sprint(show,a.num; context=io) print(io,bracket_if_needed(n)) n=sprint(show,a.den; context=io) print(io,"/",bracket_if_needed(n)) end Base.inv(a::Frac)=Frac_(a.den,a.num) Base.:^(a::Frac, n::Integer)= n>=0 ? Base.power_by_squaring(a,n) : Base.power_by_squaring(inv(a),-n) Base.:+(a::Frac,b::Frac)=Frac(a.num*b.den+a.den*b.num,a.den*b.den) Base.:+(a::Frac{<:T},b::Union{Number,T}) where T=+(promote(a,b)...) Base.:+(b::Union{Number,T},a::Frac{<:T}) where T=+(promote(a,b)...) Base.:-(a::Frac)=Frac_(-a.num,a.den) Base.:-(a::Frac,b::Frac)=Frac(a.num*b.den-a.den*b.num,a.den*b.den) Base.:-(a::Frac{<:T},b::Union{Number,T}) where T=-(promote(a,b)...) Base.:-(b::Union{Number,T},a::Frac{<:T}) where T=-(promote(b,a)...) Base.:*(a::Frac,b::Frac)=Frac(a.num*b.num,a.den*b.den) Base.:*(a::Frac{<:T},b::T) where T=Frac(a.num*b,a.den) Base.:*(b::T,a::Frac{<:T}) where T=Frac(a.num*b,a.den) Base.:*(a::Frac{<:Pol},b::Number)=Frac(a.num*b,a.den;prime=true) Base.:*(b::Number,a::Frac{<:Pol})=a*b #---------------------------------------------------------------------- # make both non-Laurent pols, one of valuation 0 function make_positive(a::Pol,b::Pol) v=a.v-b.v shift(a,max(v,0)-a.v),shift(b,-min(v,0)-b.v) end Frac(a::Pol,b::Pol;prime=false)=Frac(promote(a,b)...;prime) """ `Frac(a::Pol,b::Pol;prime=false) Polynomials `a` and `b` are promoted to same coefficient type, and checked for being true polynomials (otherwise they are both multiplied by the same power of the variable so they become true polynomials), and unless `prime=true` they are checked for having a non-trivial `gcd`. """ function Frac(a::T,b::T;prime=false)::Frac{T} where T<:Pol if iszero(b) error("division by 0") end a,b=make_positive(a,b) if !prime d=gcd(a,b) a,b=exactdiv(a,d),exactdiv(b,d) end if scalar(b)==-1 a,b=(-a,-b) end Frac_(a,b) end function Pol(p::Frac{<:Pol}) if ismonomial(p.den) if isone(p.den.c[1]^2) return Pol(p.num.c.*Ref(p.den.c[1]),p.num.v-p.den.v) else return Pol(p.num.c.//Ref(p.den.c[1]),p.num.v-p.den.v) end end error("cannot convert ",p," to Pol") end Base.convert(::Type{Pol{T}},p::Frac) where {T}=convert(Pol{T},Pol(p)) function Base.convert(::Type{Frac{T}},p::Pol) where T f=Frac(convert(T,p),convert(T,one(p));prime=true) Frac_(convert(T,f.num),convert(T,f.den)) end function Base.convert(::Type{Frac{Pol{T}}},a::Frac{<:Pol{<:Rational{T}}}) where T<:Integer n=numerator(a) d=denominator(a) Frac(numerator(n)*denominator(d),numerator(d)*denominator(n)) end function Base.convert(::Type{Frac{Pol{T}}},p::Pol{Rational{T1}}) where{T,T1} T2=Pol{promote_type(T,T1)} Frac_(convert(T2,numerator(p)),convert(T2,denominator(p))) end function Base.convert(::Type{Frac{T}},p::Number) where {T<:Pol} Frac_(convert(T,p),convert(T,1)) end function Base.promote_rule(a::Type{Pol{T1}},b::Type{Frac{Pol{T2}}})where {T1,T2} Frac{Pol{promote_type(T1,T2)}} end function Base.promote_rule(a::Type{Pol{Rational{T1}}},b::Type{Frac{Pol{T2}}})where {T1,T2} Frac{Pol{promote_type(T1,T2)}} end function Base.promote_rule(a::Type{T1},b::Type{Frac{T2}})where {T1<:Number,T2<:Pol} Frac{promote_type(T1,T2)} end function Base.promote_rule(a::Type{Frac{T1}},b::Type{Frac{T2}})where {T1<:Pol,T2<:Pol} Frac{promote_type(T1,T2)} end #@test (q+1)/(q-1)+q//1==(q^2+1)//(q-1) #@test q//1+(q+1)/(q-1)==(q^2+1)//(q-1) function Frac(a::Pol) if a.v>0 return Frac_(a,one(a)) end Frac(a,one(a);prime=true) end bestinv(x)=isone(x) ? x : isone(-x) ? x : inv(x) function Base.inv(p::Pol) if ismonomial(p) return Pol_([bestinv(p.c[1])],-p.v) end Frac_(make_positive(one(p),p)...) end function Base.:/(a::Pol,b::Pol) if ismonomial(b) return Pol_(a.c*bestinv(b.c[1]),a.v-b.v) end Frac(a,b) end Base.:/(a::Frac,b::Frac)=a//b Base.:/(p::Number,q::Pol)=p*inv(q) Base.:/(a::Union{Number,Pol},b::Frac{<:Pol})=a//b Base.:/(a::Frac{<:Pol},b::Union{Number,Pol})=a//b Base.://(a::Frac{<:Pol},b::Pol)=Frac(a.num,a.den*b) Base.://(a::Frac{<:Pol},b::Number)=Frac(a.num,a.den*b;prime=true) Base.://(a::Union{Number,Pol},b::Frac{<:Pol})=a*inv(b) Base.://(p::Number,q::Pol)=Frac(Pol(p),q;prime=true) Base.://(a::Frac,b::Frac)=Frac(a.num*b.den,a.den*b.num) function Base.://(a::Pol,b::Pol) if ismonomial(b) return Pol(a.c.//Ref(b.c[1]),a.v-b.v) end Frac(a,b) end (p::Frac{<:Pol})(x;Rational=false)=Rational ? p.num(x)//p.den(x) : p.num(x)/p.den(x) # @btime inv(Frac.([q+1 q+2;q-2 q-3])) setup=(q=Pol()) # 1.9.3 27.855 μs (673 allocations: 46.39 KiB) # 1.10.β3 23.769 μs (568 allocations: 33.12 KiB) end
LaurentPolynomials
https://github.com/jmichel7/LaurentPolynomials.jl.git
[ "MIT" ]
0.1.2
90950ef1bc004499811fe377dabe84b3292a8f10
code
4881
# auto-generated tests from julia-repl docstrings using Test, LaurentPolynomials, LinearAlgebra function mytest(file::String,cmd::String,man::String) println(file," ",cmd) exec=repr(MIME("text/plain"),eval(Meta.parse(cmd)),context=:limit=>true) if endswith(cmd,";") return true end exec=replace(exec,r"\s*$"m=>""); exec=replace(exec,r"\s*$"s=>"") exec=replace(exec,r"^\s*"=>"") if exec==man return true end i=findfirst(i->i<=lastindex(man) && exec[i]!=man[i],collect(eachindex(exec))) print("exec=$(repr(exec[i:end]))\nmanl=$(repr(man[i:end]))\n") false end @testset "LaurentPolynomials.jl" begin @test mytest("LaurentPolynomials.jl","Pol(:q)","Pol{Int64}: q") @test mytest("LaurentPolynomials.jl","@Pol q","Pol{Int64}: q") @test mytest("LaurentPolynomials.jl","Pol([1,2])","Pol{Int64}: 2q+1") @test mytest("LaurentPolynomials.jl","2q+1","Pol{Int64}: 2q+1") @test mytest("LaurentPolynomials.jl","Pol()","Pol{Int64}: q") @test mytest("LaurentPolynomials.jl","p=Pol([1,2,1],-1)","Pol{Int64}: q+2+q⁻¹") @test mytest("LaurentPolynomials.jl","q+2+q^-1","Pol{Int64}: q+2+q⁻¹") @test mytest("LaurentPolynomials.jl","valuation(p),degree(p)","(-1, 1)") @test mytest("LaurentPolynomials.jl","p[0], p[1], p[-1], p[10]","(2, 1, 1, 0)") @test mytest("LaurentPolynomials.jl","p[valuation(p):degree(p)]","3-element Vector{Int64}:\n 1\n 2\n 1") @test mytest("LaurentPolynomials.jl","p[begin:end]","3-element Vector{Int64}:\n 1\n 2\n 1") @test mytest("LaurentPolynomials.jl","coefficients(p)","3-element Vector{Int64}:\n 1\n 2\n 1") @test mytest("LaurentPolynomials.jl","h=Pol([[1 1;0 1],[1 0; 0 1]])","Pol{Matrix{Int64}}: [1 0; 0 1]q+[1 1; 0 1]") @test mytest("LaurentPolynomials.jl","h^3","Pol{Matrix{Int64}}: [1 0; 0 1]q³+[3 3; 0 3]q²+[3 6; 0 3]q+[1 3; 0 1]") @test mytest("LaurentPolynomials.jl","Pol(1)","Pol{Int64}: 1") @test mytest("LaurentPolynomials.jl","convert(Pol{Int},1)","Pol{Int64}: 1") @test mytest("LaurentPolynomials.jl","scalar(Pol(1))","1") @test mytest("LaurentPolynomials.jl","convert(Int,Pol(1))","1") @test mytest("LaurentPolynomials.jl","Int(Pol(1))","1") @test mytest("LaurentPolynomials.jl","scalar(q+1)","nothing") @test mytest("LaurentPolynomials.jl","derivative(p)","Pol{Int64}: 1-q⁻²") @test mytest("LaurentPolynomials.jl","p=(q+1)^2","Pol{Int64}: q²+2q+1") @test mytest("LaurentPolynomials.jl","p/2","Pol{Float64}: 0.5q²+1.0q+0.5") @test mytest("LaurentPolynomials.jl","p//2","Pol{Rational{Int64}}: (1//2)q²+q+1//2") @test mytest("LaurentPolynomials.jl","p(1//2)","9//4") @test mytest("LaurentPolynomials.jl","p(0.5)","2.25") @test mytest("LaurentPolynomials.jl","Pol([1,2,3],[2.0,1.0,3.0])","Pol{Float64}: 1.5q²-5.5q+6.0") @test mytest("LaurentPolynomials.jl","divrem(q^3+1,2q+1)","(0.5q²-0.25q+0.125, 0.875)") @test mytest("LaurentPolynomials.jl","divrem(q^3+1,2q+1//1)","((1//2)q²+(-1//4)q+1//8, 7//8)") @test mytest("LaurentPolynomials.jl","pseudodiv(q^3+1,2q+1)","(4q²-2q+1, 7)") @test mytest("LaurentPolynomials.jl","(4q^2-2q+1)*(2q+1)+7","Pol{Int64}: 8q³+8") @test mytest("LaurentPolynomials.jl","LinearAlgebra.exactdiv(q+1,2.0)","Pol{Float64}: 0.5q+0.5") @test mytest("LaurentPolynomials.jl","a=1/(q+1)","Frac{Pol{Int64}}: 1/(q+1)") @test mytest("LaurentPolynomials.jl","Pol(2/a)","Pol{Int64}: 2q+2") @test mytest("LaurentPolynomials.jl","numerator(a)","Pol{Int64}: 1") @test mytest("LaurentPolynomials.jl","denominator(a)","Pol{Int64}: q+1") @test mytest("LaurentPolynomials.jl","m=[q+1 q+2;q-2 q-3]","2×2 Matrix{Pol{Int64}}:\n q+1 q+2\n q-2 q-3") @test mytest("LaurentPolynomials.jl","n=inv(Frac.(m))","2×2 Matrix{Frac{Pol{Int64}}}:\n (-q+3)/(2q-1) (-q-2)/(-2q+1)\n (q-2)/(2q-1) (q+1)/(-2q+1)") @test mytest("LaurentPolynomials.jl","map(x->x(1),n)","2×2 Matrix{Float64}:\n 2.0 3.0\n -1.0 -2.0") @test mytest("LaurentPolynomials.jl","map(x->x(1;Rational=true),n)","2×2 Matrix{Rational{Int64}}:\n 2 3\n -1 -2") @test mytest("LaurentPolynomials.jl","pseudodiv(q^2+1,2q+1)","(2q-1, 5)") @test mytest("LaurentPolynomials.jl","(2q+1)*(2q-1)+5","Pol{Int64}: 4q²+4") @test mytest("LaurentPolynomials.jl","srgcd(4q+4,6q^2-6)","Pol{Int64}: 2q+2") @test mytest("LaurentPolynomials.jl","gcd(2q+2,2q^2-2)","Pol{Int64}: 2q+2") @test mytest("LaurentPolynomials.jl","gcd((2q+2)//1,(2q^2-2)//1)","Pol{Rational{Int64}}: q+1") @test mytest("LaurentPolynomials.jl","gcdx(q^3-1//1,q^2-1//1)","(q-1, 1, -q)") @test mytest("LaurentPolynomials.jl","powermod(q-1//1,3,q^2+q+1)","Pol{Rational{Int64}}: 6q+3") @test mytest("LaurentPolynomials.jl","p=Pol([1,1,1])","Pol{Int64}: q²+q+1") @test mytest("LaurentPolynomials.jl","vals=p.(1:5)","5-element Vector{Int64}:\n 3\n 7\n 13\n 21\n 31") @test mytest("LaurentPolynomials.jl","Pol(1:5,vals*1//1)","Pol{Rational{Int64}}: q²+q+1") @test mytest("LaurentPolynomials.jl","Pol(1:5,vals*1.0)","Pol{Float64}: 1.0q²+1.0q+1.0") @test (q+1)/(q-1)+q//1==(q^2+1)//(q-1) @test q//1+(q+1)/(q-1)==(q^2+1)//(q-1) end
LaurentPolynomials
https://github.com/jmichel7/LaurentPolynomials.jl.git
[ "MIT" ]
0.1.2
90950ef1bc004499811fe377dabe84b3292a8f10
docs
12919
<a id='Laurent-polynomials'></a> <a id='Laurent-polynomials-1'></a> # Laurent polynomials - [Laurent polynomials](index.md#Laurent-polynomials) <a id='LaurentPolynomials' href='#LaurentPolynomials'>#</a> **`LaurentPolynomials`** &mdash; *Module*. This package implements univariate Laurent polynomials, and univariate rational fractions. The coefficients can be in any ring (possibly even non-commutative, like `Matrix{Int}). The initial motivation in 2018 was to have an easy way to port GAP polynomials to Julia. The reasons for still having my own package are multiple: * I need my polynomials to behave well when coefficients are in a ring, in which case I use pseudo-division and subresultant gcd. * I need my polynomials to work as well as possible with coefficients of type `T` where the elements have a `zero` method but `T` itself does not have one, because `T` does not contain the necessary information. An example is modular arithmetic with a `BigInt` modulus which cannot be part of the type. For this reason the `zero` polynomial does not have an empty list of coefficients, but a list containing one element equal to zero, so it is always possible to get a zero of type T from the zero polynomial. * `LaurentPolynomials` is designed to be used by `PuiseuxPolynomials`. * In many cases, my polynomials are several times faster than those in the package `Polynomials`. Also the interface is simple and flexible. The only package on which this package depends is `LinearAlgebra`, through the use of the function `exactdiv`. Laurent polynomials have the parametric type `Pol{T}`, where `T`is the type of the coefficients. They are constructed by giving a vector of coefficients of type `T`, and a valuation (an `Int`). We call true polynomials those whose valuation is `≥0`. There is a current variable name (a `Symbol`) which is used to print polynomials nicely at the repl or in IJulia or Pluto. This name can be changed globally, or just for printing a specific polynomial. But polynomials do not record individually which symbol they should be printed with. **Examples** ```julia-repl julia> Pol(:q) # define symbol used for printing and return Pol([1],1) Pol{Int64}: q julia> @Pol q # same as q=Pol(:q) useful to start session with polynomials Pol{Int64}: q julia> Pol([1,2]) # valuation is taken to be 0 if omitted Pol{Int64}: 2q+1 julia> 2q+1 # same polynomial Pol{Int64}: 2q+1 julia> Pol() # omitting all arguments gives Pol([1],1) Pol{Int64}: q julia> p=Pol([1,2,1],-1) # here the valuation is specified to be -1 Pol{Int64}: q+2+q⁻¹ julia> q+2+q^-1 # same polynomial Pol{Int64}: q+2+q⁻¹ ``` ```julia-rep1 julia> print(p) # if not nice printing give an output which can be read back Pol([1, 2, 1],-1) # change the variable for printing just this time julia> print(IOContext(stdout,:limit=>true,:varname=>"x"),p) x+2+x⁻¹ julia> print(IOContext(stdout,:TeX=>true),p) # TeXable output (used in Pluto, IJulia) q+2+q^{-1} ``` A polynomial can be taken apart with the functions `valuation`, `degree` and `getindex`. An index `p[i]` gives the coefficient of degree `i` of `p`. ```julia-repl julia> valuation(p),degree(p) (-1, 1) julia> p[0], p[1], p[-1], p[10] (2, 1, 1, 0) julia> p[valuation(p):degree(p)] 3-element Vector{Int64}: 1 2 1 julia> p[begin:end] # the same as the above line 3-element Vector{Int64}: 1 2 1 julia> coefficients(p) # the same again 3-element Vector{Int64}: 1 2 1 ``` A polynomial is a *scalar* if the valuation and degree are `0`. The function `scalar` returns the constant coefficient if the polynomial is a scalar, and `nothing` otherwise. ```julia-repl julia> Pol(1) Pol{Int64}: 1 julia> convert(Pol{Int},1) # the same thing Pol{Int64}: 1 julia> scalar(Pol(1)) 1 julia> convert(Int,Pol(1)) # the same thing 1 julia> Int(Pol(1)) # the same thing 1 julia> scalar(q+1) # nothing; convert would give an error ``` In arrays `Pol{T}` of different types `T` are promoted to the same type `T` (when the `T` involved have a promotion) and a number is promoted to a polynomial. Usual arithmetic (`+`, `-`, `*`, `^`, `/`, `//`, `one`, `isone`, `zero`, `iszero`, `==`) works. Elements of type `<:Number` or of type `T` for a `Pol{T}` are considered as scalars for scalar operations on the coefficients. ```julia-repl julia> derivative(p) Pol{Int64}: 1-q⁻² julia> p=(q+1)^2 Pol{Int64}: q²+2q+1 julia> p/2 Pol{Float64}: 0.5q²+1.0q+0.5 julia> p//2 Pol{Rational{Int64}}: (1//2)q²+q+1//2 julia> p(1//2) # value of p at 1//2 9//4 julia> p(0.5) 2.25 julia> Pol([1,2,3],[2.0,1.0,3.0]) # find p taking values [2.0,1.0,3.0] at [1,2,3] Pol{Float64}: 1.5q²-5.5q+6.0 ``` Polynomials are scalars for broadcasting. They can be sorted (they have `cmp` and `isless` functions which compare the valuation and the coefficients), they can be keys in a `Dict` (they have a `hash` function). The functions `divrem`, `div`, `%`, `gcd`, `gcdx`, `lcm`, `powermod` operate between true polynomials over a field, using the polynomial division. Over a ring it is better to use `pseudodiv` and `srgcd` instead of `divrem` and `gcd` (by default `gcd` between integer polynomials delegates to `srgcd`). `LinearAlgebra.exactdiv` does division (over a field or a ring) when it is exact, otherwise gives an error. ```julia-repl julia> divrem(q^3+1,2q+1) # changes coefficients to field elements (0.5q²-0.25q+0.125, 0.875) julia> divrem(q^3+1,2q+1//1) # case of coefficients already field elements ((1//2)q²+(-1//4)q+1//8, 7//8) julia> pseudodiv(q^3+1,2q+1) # pseudo-division keeps the ring (4q²-2q+1, 7) julia> (4q^2-2q+1)*(2q+1)+7 # but multiplying back gives a multiple of the polynomial Pol{Int64}: 8q³+8 julia> LinearAlgebra.exactdiv(q+1,2.0) # LinearAlgebra.exactdiv(q+1,2) would give an error Pol{Float64}: 0.5q+0.5 ``` Finally, `Pol`s have methods `conj`, `adjoint` which operate on coefficients, methods `positive_part`, `negative_part` and `bar` (useful for Kazhdan-Lusztig theory) and a method `randpol` to produce random polynomials. Inverting polynomials is a way to get a rational fraction `Frac{Pol{T}}`, where `Frac` is a general type for fractions. Rational fractions are normalized so that the numerator and denominator are true polynomials prime to each other. They have the arithmetic operations `+`, `-` , `*`, `/`, `//`, `^`, `inv`, `one`, `isone`, `zero`, `iszero` (which can operate between a `Pol` or a `Number` and a `Frac{Pol{T}}`). ```julia-repl julia> a=1/(q+1) Frac{Pol{Int64}}: 1/(q+1) julia> Pol(2/a) # convert back to `Pol` Pol{Int64}: 2q+2 julia> numerator(a) Pol{Int64}: 1 julia> denominator(a) Pol{Int64}: q+1 julia> m=[q+1 q+2;q-2 q-3] 2×2 Matrix{Pol{Int64}}: q+1 q+2 q-2 q-3 julia> n=inv(Frac.(m)) # convert to rational fractions to invert the matrix 2×2 Matrix{Frac{Pol{Int64}}}: (-q+3)/(2q-1) (-q-2)/(-2q+1) (q-2)/(2q-1) (q+1)/(-2q+1) julia> map(x->x(1),n) # evaluate at 1 the inverse matrix 2×2 Matrix{Float64}: 2.0 3.0 -1.0 -2.0 julia> map(x->x(1;Rational=true),n) # evaluate at 1 using // 2×2 Matrix{Rational{Int64}}: 2 3 -1 -2 ``` Rational fractions are also scalars for broadcasting and can be sorted (have `cmp` and `isless` methods). <a id='LaurentPolynomials.Pol' href='#LaurentPolynomials.Pol'>#</a> **`LaurentPolynomials.Pol`** &mdash; *Type*. `Pol(c::AbstractVector,v::Integer=0;check=true,copy=true)` Make a polynomial of valuation `v` with coefficients `c`. Unless `check` is `false` normalize the result by making sure that `c` has no leading or trailing zeroes (do not set `check=false` unless you are sure this is already the case). Unless `copy=false` the contents of `c` are copied (you can gain one allocation by setting `copy=false` if you know the contents can be shared) `Pol(t::Symbol)` Sets the name of the variable for printing `Pol`s to `t`, and returns the polynomial of degree 1 equal to that variable. `Pol(x::AbstractVector,y::AbstractVector)` Interpolation: find a `Pol` (of nonnegative valuation) of smallest degree taking values `y` at points `x`. The values `y` should be in a field for the function to be type stable. ```julia-repl julia> p=Pol([1,1,1]) Pol{Int64}: q²+q+1 julia> vals=p.(1:5) 5-element Vector{Int64}: 3 7 13 21 31 julia> Pol(1:5,vals*1//1) Pol{Rational{Int64}}: q²+q+1 julia> Pol(1:5,vals*1.0) Pol{Float64}: 1.0q²+1.0q+1.0 ``` <a id='LaurentPolynomials.@Pol' href='#LaurentPolynomials.@Pol'>#</a> **`LaurentPolynomials.@Pol`** &mdash; *Macro*. `@Pol q` is equivalent to `q=Pol(:q)` excepted it creates `q` in the global scope of the current module, since it uses `eval`. <a id='Base.divrem' href='#Base.divrem'>#</a> **`Base.divrem`** &mdash; *Function*. `divrem(a::Pol, b::Pol)` `a` and `b` should be true polynomials (nonnegative valuation). Computes `(q,r)` such that `a=q*b+r` and `degree(r)<degree(b)`. Type stable if the coefficients of `b` are in a field. <a id='Base.gcd-Tuple{Pol, Pol}' href='#Base.gcd-Tuple{Pol, Pol}'>#</a> **`Base.gcd`** &mdash; *Method*. `gcd(p::Pol, q::Pol)` computes the `gcd` of the polynomials. It uses the subresultant algorithms for the `gcd` of integer polynomials. ```julia-repl julia> gcd(2q+2,2q^2-2) Pol{Int64}: 2q+2 julia> gcd((2q+2)//1,(2q^2-2)//1) Pol{Rational{Int64}}: q+1 ``` <a id='Base.gcdx-Tuple{Pol, Pol}' href='#Base.gcdx-Tuple{Pol, Pol}'>#</a> **`Base.gcdx`** &mdash; *Method*. `gcdx(a::Pol,b::Pol)` for polynomials over a field returns `d,u,v` such that `d=ua+vb` and `d=gcd(a,b)`. ```julia-repl julia> gcdx(q^3-1//1,q^2-1//1) (q-1, 1, -q) ``` <a id='LaurentPolynomials.pseudodiv' href='#LaurentPolynomials.pseudodiv'>#</a> **`LaurentPolynomials.pseudodiv`** &mdash; *Function*. `pseudodiv(a::Pol, b::Pol)` pseudo-division of `a` by `b`. If `d` is the leading coefficient of `b`, computes `(q,r)` such that `d^(degree(a)+1-degree(b))a=q*b+r` and `degree(r)<degree(b)`. Does not do division so works over any ring. For true polynomials (errors if the valuation of `a` or of `b` is negative). ```julia-repl julia> pseudodiv(q^2+1,2q+1) (2q-1, 5) julia> (2q+1)*(2q-1)+5 Pol{Int64}: 4q²+4 ``` See Knuth AOCP2 4.6.1 Algorithm R <a id='LaurentPolynomials.srgcd' href='#LaurentPolynomials.srgcd'>#</a> **`LaurentPolynomials.srgcd`** &mdash; *Function*. `srgcd(a::Pol,b::Pol)` sub-resultant gcd: gcd of polynomials over a unique factorization domain ```julia-repl julia> srgcd(4q+4,6q^2-6) Pol{Int64}: 2q+2 ``` See Knuth AOCP2 4.6.1 Algorithm C <a id='Base.powermod' href='#Base.powermod'>#</a> **`Base.powermod`** &mdash; *Function*. `powermod(p::Pol, x::Integer, q::Pol)` computes $p^x \pmod m$. ```julia-repl julia> powermod(q-1//1,3,q^2+q+1) Pol{Rational{Int64}}: 6q+3 ``` <a id='LaurentPolynomials.randpol' href='#LaurentPolynomials.randpol'>#</a> **`LaurentPolynomials.randpol`** &mdash; *Function*. `randpol(T,d)` random polynomial of degree `d` with coefficients from `T` <a id='LaurentPolynomials.Frac' href='#LaurentPolynomials.Frac'>#</a> **`LaurentPolynomials.Frac`** &mdash; *Type*. `Frac(a::Pol,b::Pol;prime=false) Polynomials `a` and `b` are promoted to same coefficient type, and checked for being true polynomials (otherwise they are both multiplied by the same power of the variable so they become true polynomials), and unless `prime=true` they are checked for having a non-trivial `gcd`. <a id='LaurentPolynomials.negative_part' href='#LaurentPolynomials.negative_part'>#</a> **`LaurentPolynomials.negative_part`** &mdash; *Function*. `negative_part(p::Pol)` keep the terms of degree≤0 <a id='LaurentPolynomials.positive_part' href='#LaurentPolynomials.positive_part'>#</a> **`LaurentPolynomials.positive_part`** &mdash; *Function*. `positive_part(p::Pol)` keep the terms of degree≥0 <a id='LaurentPolynomials.bar' href='#LaurentPolynomials.bar'>#</a> **`LaurentPolynomials.bar`** &mdash; *Function*. `bar(p::Pol)` transform p(q) into p(q⁻¹) <a id='LaurentPolynomials.shift' href='#LaurentPolynomials.shift'>#</a> **`LaurentPolynomials.shift`** &mdash; *Function*. `shift(p::Pol,s)` efficient way to multiply a polynomial by `Pol()^s`. <a id='LaurentPolynomials.resultant' href='#LaurentPolynomials.resultant'>#</a> **`LaurentPolynomials.resultant`** &mdash; *Function*. `resultant(p::Pol,q::Pol)` The function computes the resultant of the two polynomials, as the determinant of the Sylvester matrix. ``` <a id='LaurentPolynomials.discriminant' href='#LaurentPolynomials.discriminant'>#</a> **`LaurentPolynomials.discriminant`** &mdash; *Function*. `discriminant(p::Pol)` the resultant of the polynomial with its derivative. This detects multiple zeroes.
LaurentPolynomials
https://github.com/jmichel7/LaurentPolynomials.jl.git
[ "MIT" ]
0.1.2
90950ef1bc004499811fe377dabe84b3292a8f10
docs
230
# Laurent polynomials ```@contents Depth=3 ``` ```@docs LaurentPolynomials Pol @Pol divrem gcd(::Pol,::Pol) gcdx(::Pol,::Pol) pseudodiv srgcd powermod randpol Frac negative_part positive_part bar shift resultant discriminant ```
LaurentPolynomials
https://github.com/jmichel7/LaurentPolynomials.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
719
module PowerModelsAnnex import JuMP import JuMP: @variable, @constraint, @objective, @expression, optimize!, Model import InfrastructureModels; const _IM = InfrastructureModels import PowerModels; const _PM = PowerModels import PowerModels: ids, ref, var, con, sol, nw_id_default import Memento const LOGGER = Memento.getlogger(PowerModels) include("form/acr.jl") include("form/wr.jl") include("form/shared.jl") include("prob/opf.jl") include("model/pf.jl") include("model/opf.jl") include("pglib/shared.jl") include("pglib/api.jl") include("pglib/sad.jl") include("piecewise-linear/delta.jl") include("piecewise-linear/lambda.jl") include("piecewise-linear/phi.jl") include("piecewise-linear/psi.jl") end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
98
export NLACRPowerModel mutable struct NLACRPowerModel <: _PM.AbstractACRModel _PM.@pm_fields end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
517
NLPowerModels = Union{NLSOCWRPowerModel, NLACRPowerModel} "force JuMP to define an NLobjective" function _PM.objective_min_fuel_and_flow_cost(pm::NLPowerModels; kwargs...) _PM.expression_pg_cost(pm; kwargs...) _PM.expression_p_dc_cost(pm; kwargs...) return JuMP.@objective(pm.model, Min, sum( sum( var(pm, n, :pg_cost, i) for (i,gen) in nw_ref[:gen]) + sum( var(pm, n, :p_dc_cost, i) for (i,dcline) in nw_ref[:dcline]) for (n, nw_ref) in _PM.nws(pm)) ) end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
2648
# Defines a variant of the SOCWRForm which is appropriate for outer approximation export SOCWROAPowerModel mutable struct SOCWROAPowerModel <: _PM.AbstractSOCWRModel _PM.@pm_fields end function _PM.constraint_model_voltage(pm::SOCWROAPowerModel, n::Int) w = var(pm, n, :w) wr = var(pm, n, :wr) wi = var(pm, n, :wi) for (i,j) in _PM.ids(pm, n, :buspairs) @constraint(pm.model, (wr[(i,j)]^2 + wi[(i,j)]^2)/w[j] <= w[i]) end end function _PM.constraint_thermal_limit_from(pm::SOCWROAPowerModel, n::Int, f_idx, rate_a) p_fr = var(pm, n, :p, f_idx) q_fr = var(pm, n, :q, f_idx) @constraint(pm.model, sqrt(p_fr^2 + q_fr^2) <= rate_a) end function _PM.constraint_thermal_limit_to(pm::SOCWROAPowerModel, n::Int, t_idx, rate_a) p_to = var(pm, n, :p, t_idx) q_to = var(pm, n, :q, t_idx) @constraint(pm.model, sqrt(p_to^2 + q_to^2) <= rate_a) end # Defines a variant of the SOCWRForm which forces the NL solver path export NLSOCWRPowerModel mutable struct NLSOCWRPowerModel <: _PM.AbstractSOCWRModel _PM.@pm_fields end # Defines a variant of the QCWRTriForm without the linking constraints export QCLSNoLinkPowerModel mutable struct QCLSNoLinkPowerModel <: _PM.AbstractQCLSModel _PM.@pm_fields end function _PM.constraint_model_voltage(pm::QCLSNoLinkPowerModel, n::Int) v = var(pm, n, :vm) t = var(pm, n, :va) td = var(pm, n, :td) si = var(pm, n, :si) cs = var(pm, n, :cs) w = var(pm, n, :w) wr = var(pm, n, :wr) lambda_wr = var(pm, n, :lambda_wr) wi = var(pm, n, :wi) lambda_wi = var(pm, n, :lambda_wi) for (i,b) in ref(pm, n, :bus) _IM.relaxation_sqr(pm.model, v[i], w[i]) end for bp in _PM.ids(pm, n, :buspairs) i,j = bp @constraint(pm.model, t[i] - t[j] == td[bp]) _PM.relaxation_sin(pm.model, td[bp], si[bp]) _PM.relaxation_cos(pm.model, td[bp], cs[bp]) _IM.relaxation_trilinear(pm.model, v[i], v[j], cs[bp], wr[bp], lambda_wr[bp,:]) _IM.relaxation_trilinear(pm.model, v[i], v[j], si[bp], wi[bp], lambda_wi[bp,:]) # this constraint is redudant and useful for debugging #_IM.relaxation_complex_product(pm.model, w[i], w[j], wr[bp], wi[bp]) end for (i,branch) in ref(pm, n, :branch) pair = (branch["f_bus"], branch["t_bus"]) buspair = ref(pm, n, :buspairs, pair) # to prevent this constraint from being posted on multiple parallel branchs if buspair["branch"] == i _PM.constraint_power_magnitude_sqr(pm, i, nw=n) _PM.constraint_power_magnitude_link(pm, i, nw=n) end end end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
11057
#### AC Optimal Power Flow #### # This file provides a pedagogical example of modeling the AC Optimal Power # Flow problem using the Julia Mathematical Programming package (JuMP) and the # PowerModels package for data parsing. # This file can be run by calling `include("ac-opf.jl")` from the Julia REPL or # by calling `julia ac-opf.jl` in Julia v1. # Developed by Line Roald (@lroald) and Carleton Coffrin (@ccoffrin) ############################################################################### # 0. Initialization ############################################################################### # Load Julia Packages #-------------------- using PowerModels using Ipopt using JuMP # Load System Data # ---------------- powermodels_path = joinpath(dirname(pathof(PowerModels)), "..") file_name = "$(powermodels_path)/test/data/matpower/case5.m" # note: change this string to modify the network data that will be loaded # load the data file data = PowerModels.parse_file(file_name) # Add zeros to turn linear objective functions into quadratic ones # so that additional parameter checks are not required PowerModels.standardize_cost_terms!(data, order=2) # Adds reasonable rate_a values to branches without them PowerModels.calc_thermal_limits!(data) # use build_ref to filter out inactive components ref = PowerModels.build_ref(data)[:it][:pm][:nw][0] # note: ref contains all the relevant system parameters needed to build the OPF model # When we introduce constraints and variable bounds below, we use the parameters in ref. ############################################################################### # 1. Building the Optimal Power Flow Model ############################################################################### # Initialize a JuMP Optimization Model #------------------------------------- model = Model(Ipopt.Optimizer) set_optimizer_attribute(model, "print_level", 0) # note: print_level changes the amount of solver information printed to the terminal # Add Optimization and State Variables # ------------------------------------ # Add voltage angles va for each bus @variable(model, va[i in keys(ref[:bus])]) # note: [i in keys(ref[:bus])] adds one `va` variable for each bus in the network # Add voltage angles vm for each bus @variable(model, ref[:bus][i]["vmin"] <= vm[i in keys(ref[:bus])] <= ref[:bus][i]["vmax"], start=1.0) # note: this vairable also includes the voltage magnitude limits and a starting value # Add active power generation variable pg for each generator (including limits) @variable(model, ref[:gen][i]["pmin"] <= pg[i in keys(ref[:gen])] <= ref[:gen][i]["pmax"]) # Add reactive power generation variable qg for each generator (including limits) @variable(model, ref[:gen][i]["qmin"] <= qg[i in keys(ref[:gen])] <= ref[:gen][i]["qmax"]) # Add power flow variables p to represent the active power flow for each branch @variable(model, -ref[:branch][l]["rate_a"] <= p[(l,i,j) in ref[:arcs]] <= ref[:branch][l]["rate_a"]) # Add power flow variables q to represent the reactive power flow for each branch @variable(model, -ref[:branch][l]["rate_a"] <= q[(l,i,j) in ref[:arcs]] <= ref[:branch][l]["rate_a"]) # note: ref[:arcs] includes both the from (i,j) and the to (j,i) sides of a branch # Add power flow variables p_dc to represent the active power flow for each HVDC line @variable(model, p_dc[a in ref[:arcs_dc]]) # Add power flow variables q_dc to represent the reactive power flow at each HVDC terminal @variable(model, q_dc[a in ref[:arcs_dc]]) for (l,dcline) in ref[:dcline] f_idx = (l, dcline["f_bus"], dcline["t_bus"]) t_idx = (l, dcline["t_bus"], dcline["f_bus"]) JuMP.set_lower_bound(p_dc[f_idx], dcline["pminf"]) JuMP.set_upper_bound(p_dc[f_idx], dcline["pmaxf"]) JuMP.set_lower_bound(q_dc[f_idx], dcline["qminf"]) JuMP.set_upper_bound(q_dc[f_idx], dcline["qmaxf"]) JuMP.set_lower_bound(p_dc[t_idx], dcline["pmint"]) JuMP.set_upper_bound(p_dc[t_idx], dcline["pmaxt"]) JuMP.set_lower_bound(q_dc[f_idx], dcline["qmint"]) JuMP.set_upper_bound(q_dc[f_idx], dcline["qmaxt"]) end # Add Objective Function # ---------------------- # index representing which side the HVDC line is starting from_idx = Dict(arc[1] => arc for arc in ref[:arcs_from_dc]) # Minimize the cost of active power generation and cost of HVDC line usage # assumes costs are given as quadratic functions @objective(model, Min, sum(gen["cost"][1]*pg[i]^2 + gen["cost"][2]*pg[i] + gen["cost"][3] for (i,gen) in ref[:gen]) + sum(dcline["cost"][1]*p_dc[from_idx[i]]^2 + dcline["cost"][2]*p_dc[from_idx[i]] + dcline["cost"][3] for (i,dcline) in ref[:dcline]) ) # Add Constraints # --------------- # Fix the voltage angle to zero at the reference bus for (i,bus) in ref[:ref_buses] @constraint(model, va[i] == 0) end # Nodal power balance constraints for (i,bus) in ref[:bus] # Build a list of the loads and shunt elements connected to the bus i bus_loads = [ref[:load][l] for l in ref[:bus_loads][i]] bus_shunts = [ref[:shunt][s] for s in ref[:bus_shunts][i]] # Active power balance at node i @constraint(model, sum(p[a] for a in ref[:bus_arcs][i]) + # sum of active power flow on lines from bus i + sum(p_dc[a_dc] for a_dc in ref[:bus_arcs_dc][i]) == # sum of active power flow on HVDC lines from bus i = sum(pg[g] for g in ref[:bus_gens][i]) - # sum of active power generation at bus i - sum(load["pd"] for load in bus_loads) - # sum of active load consumption at bus i - sum(shunt["gs"] for shunt in bus_shunts)*vm[i]^2 # sum of active shunt element injections at bus i ) # Reactive power balance at node i @constraint(model, sum(q[a] for a in ref[:bus_arcs][i]) + # sum of reactive power flow on lines from bus i + sum(q_dc[a_dc] for a_dc in ref[:bus_arcs_dc][i]) == # sum of reactive power flow on HVDC lines from bus i = sum(qg[g] for g in ref[:bus_gens][i]) - # sum of reactive power generation at bus i - sum(load["qd"] for load in bus_loads) + # sum of reactive load consumption at bus i - sum(shunt["bs"] for shunt in bus_shunts)*vm[i]^2 # sum of reactive shunt element injections at bus i ) end # Branch power flow physics and limit constraints for (i,branch) in ref[:branch] # Build the from variable id of the i-th branch, which is a tuple given by (branch id, from bus, to bus) f_idx = (i, branch["f_bus"], branch["t_bus"]) # Build the to variable id of the i-th branch, which is a tuple given by (branch id, to bus, from bus) t_idx = (i, branch["t_bus"], branch["f_bus"]) # note: it is necessary to distinguish between the from and to sides of a branch due to power losses p_fr = p[f_idx] # p_fr is a reference to the optimization variable p[f_idx] q_fr = q[f_idx] # q_fr is a reference to the optimization variable q[f_idx] p_to = p[t_idx] # p_to is a reference to the optimization variable p[t_idx] q_to = q[t_idx] # q_to is a reference to the optimization variable q[t_idx] # note: adding constraints to p_fr is equivalent to adding constraints to p[f_idx], and so on vm_fr = vm[branch["f_bus"]] # vm_fr is a reference to the optimization variable vm on the from side of the branch vm_to = vm[branch["t_bus"]] # vm_to is a reference to the optimization variable vm on the to side of the branch va_fr = va[branch["f_bus"]] # va_fr is a reference to the optimization variable va on the from side of the branch va_to = va[branch["t_bus"]] # va_fr is a reference to the optimization variable va on the to side of the branch # Compute the branch parameters and transformer ratios from the data g, b = PowerModels.calc_branch_y(branch) tr, ti = PowerModels.calc_branch_t(branch) g_fr = branch["g_fr"] b_fr = branch["b_fr"] g_to = branch["g_to"] b_to = branch["b_to"] tm = branch["tap"]^2 # note: tap is assumed to be 1.0 on non-transformer branches # AC Power Flow Constraints # From side of the branch flow @constraint(model, p_fr == (g+g_fr)/tm*vm_fr^2 + (-g*tr+b*ti)/tm*(vm_fr*vm_to*cos(va_fr-va_to)) + (-b*tr-g*ti)/tm*(vm_fr*vm_to*sin(va_fr-va_to)) ) @constraint(model, q_fr == -(b+b_fr)/tm*vm_fr^2 - (-b*tr-g*ti)/tm*(vm_fr*vm_to*cos(va_fr-va_to)) + (-g*tr+b*ti)/tm*(vm_fr*vm_to*sin(va_fr-va_to)) ) # To side of the branch flow @constraint(model, p_to == (g+g_to)*vm_to^2 + (-g*tr-b*ti)/tm*(vm_to*vm_fr*cos(va_to-va_fr)) + (-b*tr+g*ti)/tm*(vm_to*vm_fr*sin(va_to-va_fr)) ) @constraint(model, q_to == -(b+b_to)*vm_to^2 - (-b*tr+g*ti)/tm*(vm_to*vm_fr*cos(va_fr-va_to)) + (-g*tr-b*ti)/tm*(vm_to*vm_fr*sin(va_to-va_fr)) ) # Voltage angle difference limit @constraint(model, va_fr - va_to <= branch["angmax"]) @constraint(model, va_fr - va_to >= branch["angmin"]) # Apparent power limit, from side and to side @constraint(model, p_fr^2 + q_fr^2 <= branch["rate_a"]^2) @constraint(model, p_to^2 + q_to^2 <= branch["rate_a"]^2) end # HVDC line constraints for (i,dcline) in ref[:dcline] # Build the from variable id of the i-th HVDC line, which is a tuple given by (hvdc line id, from bus, to bus) f_idx = (i, dcline["f_bus"], dcline["t_bus"]) # Build the to variable id of the i-th HVDC line, which is a tuple given by (hvdc line id, to bus, from bus) t_idx = (i, dcline["t_bus"], dcline["f_bus"]) # index of the ith HVDC line which is a tuple given by (line number, to bus, from bus) # note: it is necessary to distinguish between the from and to sides of a HVDC line due to power losses # Constraint defining the power flow and losses over the HVDC line @constraint(model, (1-dcline["loss1"])*p_dc[f_idx] + (p_dc[t_idx] - dcline["loss0"]) == 0) end ############################################################################### # 3. Solve the Optimal Power Flow Model and Review the Results ############################################################################### # Solve the optimization problem optimize!(model) # Check that the solver terminated without an error println("The solver termination status is $(termination_status(model))") # Check the value of the objective function cost = objective_value(model) println("The cost of generation is $(cost).") # Check the value of an optimization variable # Example: Active power generated at generator 1 pg1 = value(pg[1]) println("The active power generated at generator 1 is $(pg1*ref[:baseMVA]) MW.") # note: the optimization model is in per unit, so the baseMVA value is used to restore the physical units
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
7981
#### DC Optimal Power Flow #### # This file provides a pedagogical example of modeling the DC Optimal Power # Flow problem using the Julia Mathematical Programming package (JuMP) and the # PowerModels package for data parsing. # This file can be run by calling `include("dc-opf.jl")` from the Julia REPL or # by calling `julia dc-opf.jl` in Julia v1. # Developed by Line Roald (@lroald) and Carleton Coffrin (@ccoffrin) ############################################################################### # 0. Initialization ############################################################################### # Load Julia Packages #-------------------- using PowerModels using Ipopt using JuMP # Load System Data # ---------------- powermodels_path = joinpath(dirname(pathof(PowerModels)), "..") file_name = "$(powermodels_path)/test/data/matpower/case5.m" # note: change this string to modify the network data that will be loaded # load the data file data = PowerModels.parse_file(file_name) # Add zeros to turn linear objective functions into quadratic ones # so that additional parameter checks are not required PowerModels.standardize_cost_terms!(data, order=2) # Adds reasonable rate_a values to branches without them PowerModels.calc_thermal_limits!(data) # use build_ref to filter out inactive components ref = PowerModels.build_ref(data)[:it][:pm][:nw][0] # Note: ref contains all the relevant system parameters needed to build the OPF model # When we introduce constraints and variable bounds below, we use the parameters in ref. ############################################################################### # 1. Building the Optimal Power Flow Model ############################################################################### # Initialize a JuMP Optimization Model #------------------------------------- model = Model(Ipopt.Optimizer) set_optimizer_attribute(model, "print_level", 0) # note: print_level changes the amount of solver information printed to the terminal # Add Optimization and State Variables # ------------------------------------ # Add voltage angles va for each bus @variable(model, va[i in keys(ref[:bus])]) # note: [i in keys(ref[:bus])] adds one `va` variable for each bus in the network # Add active power generation variable pg for each generator (including limits) @variable(model, ref[:gen][i]["pmin"] <= pg[i in keys(ref[:gen])] <= ref[:gen][i]["pmax"]) # Add power flow variables p to represent the active power flow for each branch @variable(model, -ref[:branch][l]["rate_a"] <= p[(l,i,j) in ref[:arcs_from]] <= ref[:branch][l]["rate_a"]) # Build JuMP expressions for the value of p[(l,i,j)] and p[(l,j,i)] on the branches p_expr = Dict([((l,i,j), 1.0*p[(l,i,j)]) for (l,i,j) in ref[:arcs_from]]) p_expr = merge(p_expr, Dict([((l,j,i), -1.0*p[(l,i,j)]) for (l,i,j) in ref[:arcs_from]])) # note: this is used to make the definition of nodal power balance simpler # Add power flow variables p_dc to represent the active power flow for each HVDC line @variable(model, p_dc[a in ref[:arcs_dc]]) for (l,dcline) in ref[:dcline] f_idx = (l, dcline["f_bus"], dcline["t_bus"]) t_idx = (l, dcline["t_bus"], dcline["f_bus"]) JuMP.set_lower_bound(p_dc[f_idx], dcline["pminf"]) JuMP.set_upper_bound(p_dc[f_idx], dcline["pmaxf"]) JuMP.set_lower_bound(p_dc[t_idx], dcline["pmint"]) JuMP.set_upper_bound(p_dc[t_idx], dcline["pmaxt"]) end # Add Objective Function # ---------------------- # index representing which side the HVDC line is starting from_idx = Dict(arc[1] => arc for arc in ref[:arcs_from_dc]) # Minimize the cost of active power generation and cost of HVDC line usage # assumes costs are given as quadratic functions @objective(model, Min, sum(gen["cost"][1]*pg[i]^2 + gen["cost"][2]*pg[i] + gen["cost"][3] for (i,gen) in ref[:gen]) + sum(dcline["cost"][1]*p_dc[from_idx[i]]^2 + dcline["cost"][2]*p_dc[from_idx[i]] + dcline["cost"][3] for (i,dcline) in ref[:dcline]) ) # Add Constraints # --------------- # Fix the voltage angle to zero at the reference bus for (i,bus) in ref[:ref_buses] @constraint(model, va[i] == 0) end # Nodal power balance constraints for (i,bus) in ref[:bus] # Build a list of the loads and shunt elements connected to the bus i bus_loads = [ref[:load][l] for l in ref[:bus_loads][i]] bus_shunts = [ref[:shunt][s] for s in ref[:bus_shunts][i]] # Active power balance at node i @constraint(model, sum(p_expr[a] for a in ref[:bus_arcs][i]) + # sum of active power flow on lines from bus i + sum(p_dc[a_dc] for a_dc in ref[:bus_arcs_dc][i]) == # sum of active power flow on HVDC lines from bus i = sum(pg[g] for g in ref[:bus_gens][i]) - # sum of active power generation at bus i - sum(load["pd"] for load in bus_loads) - # sum of active load consumption at bus i - sum(shunt["gs"] for shunt in bus_shunts)*1.0^2 # sum of active shunt element injections at bus i ) end # Branch power flow physics and limit constraints for (i,branch) in ref[:branch] # Build the from variable id of the i-th branch, which is a tuple given by (branch id, from bus, to bus) f_idx = (i, branch["f_bus"], branch["t_bus"]) p_fr = p[f_idx] # p_fr is a reference to the optimization variable p[f_idx] va_fr = va[branch["f_bus"]] # va_fr is a reference to the optimization variable va on the from side of the branch va_to = va[branch["t_bus"]] # va_fr is a reference to the optimization variable va on the to side of the branch # Compute the branch parameters and transformer ratios from the data g, b = PowerModels.calc_branch_y(branch) # DC Power Flow Constraint @constraint(model, p_fr == -b*(va_fr - va_to)) # note: that upper and lower limits on the power flow (i.e. p_fr) are not included here. # these limits were already enforced for p (which is the same as p_fr) when # the optimization variable p was defined (around line 65). # Voltage angle difference limit @constraint(model, va_fr - va_to <= branch["angmax"]) @constraint(model, va_fr - va_to >= branch["angmin"]) end # HVDC line constraints for (i,dcline) in ref[:dcline] # Build the from variable id of the i-th HVDC line, which is a tuple given by (hvdc line id, from bus, to bus) f_idx = (i, dcline["f_bus"], dcline["t_bus"]) # Build the to variable id of the i-th HVDC line, which is a tuple given by (hvdc line id, to bus, from bus) t_idx = (i, dcline["t_bus"], dcline["f_bus"]) # index of the ith HVDC line which is a tuple given by (line number, to bus, from bus) # note: it is necessary to distinguish between the from and to sides of a HVDC line due to power losses # Constraint defining the power flow and losses over the HVDC line @constraint(model, (1-dcline["loss1"])*p_dc[f_idx] + (p_dc[t_idx] - dcline["loss0"]) == 0) end ############################################################################### # 3. Solve the Optimal Power Flow Model and Review the Results ############################################################################### # Solve the optimization problem optimize!(model) # Check that the solver terminated without an error println("The solver termination status is $(termination_status(model))") # Check the value of the objective function cost = objective_value(model) println("The cost of generation is $(cost).") # Check the value of an optimization variable # Example: Active power generated at generator 1 pg1 = value(pg[1]) println("The active power generated at generator 1 is $(pg1*ref[:baseMVA]) MW.") # note: the optimization model is in per unit, so the baseMVA value is used to restore the physical units
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
28655
export build_ac_opf, build_soc_opf, build_qc_opf, build_dc_opf """ Given a JuMP model and a PowerModels network data structure, Builds an AC-OPF formulation of the given data and returns the JuMP model """ function build_ac_opf(data::Dict{String,Any}, model=Model()) @assert !haskey(data, "multinetwork") @assert !haskey(data, "conductors") PowerModels.standardize_cost_terms!(data, order=2) ref = PowerModels.build_ref(data)[:it][_PM.pm_it_sym][:nw][nw_id_default] @variable(model, va[i in keys(ref[:bus])]) @variable(model, ref[:bus][i]["vmin"] <= vm[i in keys(ref[:bus])] <= ref[:bus][i]["vmax"], start=1.0) @variable(model, ref[:gen][i]["pmin"] <= pg[i in keys(ref[:gen])] <= ref[:gen][i]["pmax"]) @variable(model, ref[:gen][i]["qmin"] <= qg[i in keys(ref[:gen])] <= ref[:gen][i]["qmax"]) @variable(model, -Inf <= p[(l,i,j) in ref[:arcs]] <= Inf) @variable(model, -Inf <= q[(l,i,j) in ref[:arcs]] <= Inf) for arc in ref[:arcs] (l,i,j) = arc branch = ref[:branch][l] if haskey(branch, "rate_a") JuMP.set_lower_bound(p[arc], -branch["rate_a"]) JuMP.set_upper_bound(p[arc], branch["rate_a"]) JuMP.set_lower_bound(q[arc], -branch["rate_a"]) JuMP.set_upper_bound(q[arc], branch["rate_a"]) end end @variable(model, p_dc[a in ref[:arcs_dc]]) @variable(model, q_dc[a in ref[:arcs_dc]]) for (l,dcline) in ref[:dcline] f_idx = (l, dcline["f_bus"], dcline["t_bus"]) t_idx = (l, dcline["t_bus"], dcline["f_bus"]) JuMP.set_lower_bound(p_dc[f_idx], dcline["pminf"]) JuMP.set_upper_bound(p_dc[f_idx], dcline["pmaxf"]) JuMP.set_lower_bound(q_dc[f_idx], dcline["qminf"]) JuMP.set_upper_bound(q_dc[f_idx], dcline["qmaxf"]) JuMP.set_lower_bound(p_dc[t_idx], dcline["pmint"]) JuMP.set_upper_bound(p_dc[t_idx], dcline["pmaxt"]) JuMP.set_lower_bound(q_dc[t_idx], dcline["qmint"]) JuMP.set_upper_bound(q_dc[t_idx], dcline["qmaxt"]) end from_idx = Dict(arc[1] => arc for arc in ref[:arcs_from_dc]) @objective(model, Min, sum(gen["cost"][1]*pg[i]^2 + gen["cost"][2]*pg[i] + gen["cost"][3] for (i,gen) in ref[:gen]) + sum(dcline["cost"][1]*p_dc[from_idx[i]]^2 + dcline["cost"][2]*p_dc[from_idx[i]] + dcline["cost"][3] for (i,dcline) in ref[:dcline]) ) for (i,bus) in ref[:ref_buses] # Refrence Bus @constraint(model, va[i] == 0) end for (i,bus) in ref[:bus] bus_loads = [ref[:load][l] for l in ref[:bus_loads][i]] bus_shunts = [ref[:shunt][s] for s in ref[:bus_shunts][i]] # Bus KCL @constraint(model, sum(p[a] for a in ref[:bus_arcs][i]) + sum(p_dc[a_dc] for a_dc in ref[:bus_arcs_dc][i]) == sum(pg[g] for g in ref[:bus_gens][i]) - sum(load["pd"] for load in bus_loads) - sum(shunt["gs"] for shunt in bus_shunts)*vm[i]^2 ) @constraint(model, sum(q[a] for a in ref[:bus_arcs][i]) + sum(q_dc[a_dc] for a_dc in ref[:bus_arcs_dc][i]) == sum(qg[g] for g in ref[:bus_gens][i]) - sum(load["qd"] for load in bus_loads) + sum(shunt["bs"] for shunt in bus_shunts)*vm[i]^2 ) end for (i,branch) in ref[:branch] f_idx = (i, branch["f_bus"], branch["t_bus"]) t_idx = (i, branch["t_bus"], branch["f_bus"]) p_fr = p[f_idx] q_fr = q[f_idx] p_to = p[t_idx] q_to = q[t_idx] vm_fr = vm[branch["f_bus"]] vm_to = vm[branch["t_bus"]] va_fr = va[branch["f_bus"]] va_to = va[branch["t_bus"]] # Line Flow g, b = PowerModels.calc_branch_y(branch) tr, ti = PowerModels.calc_branch_t(branch) g_fr = branch["g_fr"] b_fr = branch["b_fr"] g_to = branch["g_to"] b_to = branch["b_to"] tm = branch["tap"]^2 # AC Line Flow Constraints @constraint(model, p_fr == (g+g_fr)/tm*vm_fr^2 + (-g*tr+b*ti)/tm*(vm_fr*vm_to*cos(va_fr-va_to)) + (-b*tr-g*ti)/tm*(vm_fr*vm_to*sin(va_fr-va_to)) ) @constraint(model, q_fr == -(b+b_fr)/tm*vm_fr^2 - (-b*tr-g*ti)/tm*(vm_fr*vm_to*cos(va_fr-va_to)) + (-g*tr+b*ti)/tm*(vm_fr*vm_to*sin(va_fr-va_to)) ) @constraint(model, p_to == (g+g_to)*vm_to^2 + (-g*tr-b*ti)/tm*(vm_to*vm_fr*cos(va_to-va_fr)) + (-b*tr+g*ti)/tm*(vm_to*vm_fr*sin(va_to-va_fr)) ) @constraint(model, q_to == -(b+b_to)*vm_to^2 - (-b*tr+g*ti)/tm*(vm_to*vm_fr*cos(va_fr-va_to)) + (-g*tr-b*ti)/tm*(vm_to*vm_fr*sin(va_to-va_fr)) ) # Phase Angle Difference Limit @constraint(model, va_fr - va_to <= branch["angmax"]) @constraint(model, va_fr - va_to >= branch["angmin"]) # Apparent Power Limit, From and To if haskey(branch, "rate_a") @constraint(model, p[f_idx]^2 + q[f_idx]^2 <= branch["rate_a"]^2) @constraint(model, p[t_idx]^2 + q[t_idx]^2 <= branch["rate_a"]^2) end end for (i,dcline) in ref[:dcline] # DC Line Flow Constraint f_idx = (i, dcline["f_bus"], dcline["t_bus"]) t_idx = (i, dcline["t_bus"], dcline["f_bus"]) @constraint(model, (1-dcline["loss1"])*p_dc[f_idx] + (p_dc[t_idx] - dcline["loss0"]) == 0) end return model end """ Given a JuMP model and a PowerModels network data structure, Builds an SOC-OPF formulation of the given data and returns the JuMP model """ function build_soc_opf(data::Dict{String,Any}, model=Model()) @assert !haskey(data, "multinetwork") @assert !haskey(data, "conductors") PowerModels.standardize_cost_terms!(data, order=2) ref = PowerModels.build_ref(data)[:it][_PM.pm_it_sym][:nw][nw_id_default] @variable(model, ref[:bus][i]["vmin"]^2 <= w[i in keys(ref[:bus])] <= ref[:bus][i]["vmax"]^2, start=1.001) wr_min, wr_max, wi_min, wi_max = PowerModels.ref_calc_voltage_product_bounds(ref[:buspairs]) @variable(model, wr_min[bp] <= wr[bp in keys(ref[:buspairs])] <= wr_max[bp], start=1.0) @variable(model, wi_min[bp] <= wi[bp in keys(ref[:buspairs])] <= wi_max[bp]) @variable(model, ref[:gen][i]["pmin"] <= pg[i in keys(ref[:gen])] <= ref[:gen][i]["pmax"]) @variable(model, ref[:gen][i]["qmin"] <= qg[i in keys(ref[:gen])] <= ref[:gen][i]["qmax"]) @variable(model, -Inf <= p[(l,i,j) in ref[:arcs]] <= Inf) @variable(model, -Inf <= q[(l,i,j) in ref[:arcs]] <= Inf) for arc in ref[:arcs] (l,i,j) = arc branch = ref[:branch][l] if haskey(branch, "rate_a") JuMP.set_lower_bound(p[arc], -branch["rate_a"]) JuMP.set_upper_bound(p[arc], branch["rate_a"]) JuMP.set_lower_bound(q[arc], -branch["rate_a"]) JuMP.set_upper_bound(q[arc], branch["rate_a"]) end end @variable(model, p_dc[a in ref[:arcs_dc]]) @variable(model, q_dc[a in ref[:arcs_dc]]) for (l,dcline) in ref[:dcline] f_idx = (l, dcline["f_bus"], dcline["t_bus"]) t_idx = (l, dcline["t_bus"], dcline["f_bus"]) JuMP.set_lower_bound(p_dc[f_idx], dcline["pminf"]) JuMP.set_upper_bound(p_dc[f_idx], dcline["pmaxf"]) JuMP.set_lower_bound(q_dc[f_idx], dcline["qminf"]) JuMP.set_upper_bound(q_dc[f_idx], dcline["qmaxf"]) JuMP.set_lower_bound(p_dc[t_idx], dcline["pmint"]) JuMP.set_upper_bound(p_dc[t_idx], dcline["pmaxt"]) JuMP.set_lower_bound(q_dc[f_idx], dcline["qmint"]) JuMP.set_upper_bound(q_dc[f_idx], dcline["qmaxt"]) end from_idx = Dict(arc[1] => arc for arc in ref[:arcs_from_dc]) @objective(model, Min, sum(gen["cost"][1]*pg[i]^2 + gen["cost"][2]*pg[i] + gen["cost"][3] for (i,gen) in ref[:gen]) + sum(dcline["cost"][1]*p_dc[from_idx[i]]^2 + dcline["cost"][2]*p_dc[from_idx[i]] + dcline["cost"][3] for (i,dcline) in ref[:dcline]) ) for (bp, buspair) in ref[:buspairs] i,j = bp # Voltage Product Relaxation Lowerbound @constraint(model, wr[(i,j)]^2 + wi[(i,j)]^2 <= w[i]*w[j]) vfub = buspair["vm_fr_max"] vflb = buspair["vm_fr_min"] vtub = buspair["vm_to_max"] vtlb = buspair["vm_to_min"] tdub = buspair["angmax"] tdlb = buspair["angmin"] phi = (tdub + tdlb)/2 d = (tdub - tdlb)/2 sf = vflb + vfub st = vtlb + vtub # Voltage Product Relaxation Upperbound @constraint(model, sf*st*(cos(phi)*wr[(i,j)] + sin(phi)*wi[(i,j)]) - vtub*cos(d)*st*w[i] - vfub*cos(d)*sf*w[j] >= vfub*vtub*cos(d)*(vflb*vtlb - vfub*vtub)) @constraint(model, sf*st*(cos(phi)*wr[(i,j)] + sin(phi)*wi[(i,j)]) - vtlb*cos(d)*st*w[i] - vflb*cos(d)*sf*w[j] >= -vflb*vtlb*cos(d)*(vflb*vtlb - vfub*vtub)) end for (i,bus) in ref[:bus] bus_loads = [ref[:load][l] for l in ref[:bus_loads][i]] bus_shunts = [ref[:shunt][s] for s in ref[:bus_shunts][i]] # Bus KCL @constraint(model, sum(p[a] for a in ref[:bus_arcs][i]) + sum(p_dc[a_dc] for a_dc in ref[:bus_arcs_dc][i]) == sum(pg[g] for g in ref[:bus_gens][i]) - sum(load["pd"] for load in bus_loads) - sum(shunt["gs"] for shunt in bus_shunts)*w[i] ) @constraint(model, sum(q[a] for a in ref[:bus_arcs][i]) + sum(q_dc[a_dc] for a_dc in ref[:bus_arcs_dc][i]) == sum(qg[g] for g in ref[:bus_gens][i]) - sum(load["qd"] for load in bus_loads) + sum(shunt["bs"] for shunt in bus_shunts)*w[i] ) end for (i,branch) in ref[:branch] f_idx = (i, branch["f_bus"], branch["t_bus"]) t_idx = (i, branch["t_bus"], branch["f_bus"]) bp_idx = (branch["f_bus"], branch["t_bus"]) p_fr = p[f_idx] q_fr = q[f_idx] p_to = p[t_idx] q_to = q[t_idx] w_fr = w[branch["f_bus"]] w_to = w[branch["t_bus"]] wr_br = wr[bp_idx] wi_br = wi[bp_idx] # Line Flow g, b = PowerModels.calc_branch_y(branch) tr, ti = PowerModels.calc_branch_t(branch) g_fr = branch["g_fr"] b_fr = branch["b_fr"] g_to = branch["g_to"] b_to = branch["b_to"] tm = branch["tap"]^2 # AC Line Flow Constraints @constraint(model, p_fr == (g+g_fr)/tm*w_fr + (-g*tr+b*ti)/tm*(wr_br) + (-b*tr-g*ti)/tm*(wi_br) ) @constraint(model, q_fr == -(b+b_fr)/tm*w_fr - (-b*tr-g*ti)/tm*(wr_br) + (-g*tr+b*ti)/tm*(wi_br) ) @constraint(model, p_to == (g+g_to)*w_to + (-g*tr-b*ti)/tm*(wr_br) + (-b*tr+g*ti)/tm*(-wi_br) ) @constraint(model, q_to == -(b+b_to)*w_to - (-b*tr+g*ti)/tm*(wr_br) + (-g*tr-b*ti)/tm*(-wi_br) ) # Phase Angle Difference Limit @constraint(model, wi_br <= tan(branch["angmax"])*wr_br) @constraint(model, wi_br >= tan(branch["angmin"])*wr_br) # Apparent Power Limit, From and To if haskey(branch, "rate_a") @constraint(model, p[f_idx]^2 + q[f_idx]^2 <= branch["rate_a"]^2) @constraint(model, p[t_idx]^2 + q[t_idx]^2 <= branch["rate_a"]^2) end end for (i,dcline) in ref[:dcline] # DC Line Flow Constraint f_idx = (i, dcline["f_bus"], dcline["t_bus"]) t_idx = (i, dcline["t_bus"], dcline["f_bus"]) @constraint(model, (1-dcline["loss1"])*p_dc[f_idx] + (p_dc[t_idx] - dcline["loss0"]) == 0) end return model end """ Given the JuMP model and the PowerModels network data structure, Builds the QC-OPF formulation of the given data and returns the JuMP model Implementation provided by @sidhant172 """ function build_qc_opf(data::Dict{String,Any}, model=Model()) @assert !haskey(data, "multinetwork") @assert !haskey(data, "conductors") PowerModels.standardize_cost_terms!(data, order=2) ref = PowerModels.build_ref(data)[:it][_PM.pm_it_sym][:nw][nw_id_default] # voltage angle and magnitude @variable(model, va[i in keys(ref[:bus])]) @variable(model, ref[:bus][i]["vmin"] <= vm[i in keys(ref[:bus])] <= ref[:bus][i]["vmax"], start=1.0) # voltage squared @variable(model, ref[:bus][i]["vmin"]^2 <= w[i in keys(ref[:bus])] <= ref[:bus][i]["vmax"]^2, start=1.001) # voltage product wr_min, wr_max, wi_min, wi_max = PowerModels.ref_calc_voltage_product_bounds(ref[:buspairs]) @variable(model, wr_min[bp] <= wr[bp in keys(ref[:buspairs])] <= wr_max[bp], start=1.0) @variable(model, wi_min[bp] <= wi[bp in keys(ref[:buspairs])] <= wi_max[bp]) # voltage angle differences @variable(model, ref[:buspairs][bp]["angmin"] <= td[bp in keys(ref[:buspairs])] <= ref[:buspairs][bp]["angmax"]) # variable multipliers in lambda formulation @variable(model, 0 <= lambda_wr[bp in keys(ref[:buspairs]), 1:8] <= 1) @variable(model, 0 <= lambda_wi[bp in keys(ref[:buspairs]), 1:8] <= 1) # cosine variables # computing bounds for cosine variables cos_min = Dict([(bp, -Inf) for bp in keys(ref[:buspairs])]) cos_max = Dict([(bp, Inf) for bp in keys(ref[:buspairs])]) for (bp, buspair) in ref[:buspairs] angmin = buspair["angmin"] angmax = buspair["angmax"] if angmin >= 0 cos_max[bp] = cos(angmin) cos_min[bp] = cos(angmax) end if angmax <= 0 cos_max[bp] = cos(angmax) cos_min[bp] = cos(angmin) end if angmin < 0 && angmax > 0 cos_max[bp] = 1.0 cos_min[bp] = min(cos(angmin), cos(angmax)) end end # end computing bounds for cosine variables # defining cosine variables @variable(model, cos_min[bp] <= cs[bp in keys(ref[:buspairs])] <= cos_max[bp]) # defining sine variables @variable(model, sin(ref[:buspairs][bp]["angmin"]) <= si[bp in keys(ref[:buspairs])] <= sin(ref[:buspairs][bp]["angmax"])) # current magnitude squared # compute upper bound cm_ub = Dict() for (bp, buspair) in ref[:buspairs] if haskey(buspair, "rate_a") cm_ub[bp] = ((buspair["rate_a"]*buspair["tap"])/buspair["vm_fr_min"])^2 else cm_ub[bp] = Inf end end # define current magnitude variable @variable(model, 0 <= cm[bp in keys(ref[:buspairs])] <= cm_ub[bp]) # line flow variables @variable(model, -Inf <= p[(l,i,j) in ref[:arcs]] <= Inf) @variable(model, -Inf <= q[(l,i,j) in ref[:arcs]] <= Inf) for arc in ref[:arcs] (l,i,j) = arc branch = ref[:branch][l] if haskey(branch, "rate_a") JuMP.set_lower_bound(p[arc], -branch["rate_a"]) JuMP.set_upper_bound(p[arc], branch["rate_a"]) JuMP.set_lower_bound(q[arc], -branch["rate_a"]) JuMP.set_upper_bound(q[arc], branch["rate_a"]) end end # generation pg and qg @variable(model, ref[:gen][i]["pmin"] <= pg[i in keys(ref[:gen])] <= ref[:gen][i]["pmax"]) @variable(model, ref[:gen][i]["qmin"] <= qg[i in keys(ref[:gen])] <= ref[:gen][i]["qmax"]) # dc line flows @variable(model, p_dc[a in ref[:arcs_dc]]) @variable(model, q_dc[a in ref[:arcs_dc]]) for (l,dcline) in ref[:dcline] f_idx = (l, dcline["f_bus"], dcline["t_bus"]) t_idx = (l, dcline["t_bus"], dcline["f_bus"]) JuMP.set_lower_bound(p_dc[f_idx], dcline["pminf"]) JuMP.set_upper_bound(p_dc[f_idx], dcline["pmaxf"]) JuMP.set_lower_bound(q_dc[f_idx], dcline["qminf"]) JuMP.set_upper_bound(q_dc[f_idx], dcline["qmaxf"]) JuMP.set_lower_bound(p_dc[t_idx], dcline["pmint"]) JuMP.set_upper_bound(p_dc[t_idx], dcline["pmaxt"]) JuMP.set_lower_bound(q_dc[f_idx], dcline["qmint"]) JuMP.set_upper_bound(q_dc[f_idx], dcline["qmaxt"]) end # objective from_idx = Dict(arc[1] => arc for arc in ref[:arcs_from_dc]) @objective(model, Min, sum(gen["cost"][1]*pg[i]^2 + gen["cost"][2]*pg[i] + gen["cost"][3] for (i,gen) in ref[:gen]) + sum(dcline["cost"][1]*p_dc[from_idx[i]]^2 + dcline["cost"][2]*p_dc[from_idx[i]] + dcline["cost"][3] for (i,dcline) in ref[:dcline]) ) #### beginning of constraints #### # relaxation of vm square for (i,bus) in ref[:bus] @constraint(model, w[i] >= vm[i]^2) @constraint(model, w[i] <= (bus["vmin"] + bus["vmax"])*vm[i] - bus["vmin"]*bus["vmax"]) end # buspair voltage constraints for (bp, buspair) in ref[:buspairs] i,j = bp @constraint(model, va[i] - va[j] == td[bp]) # relaxation sin ub = buspair["angmax"] lb = buspair["angmin"] max_ad = max(abs(lb),abs(ub)) if lb < 0 && ub > 0 @constraint(model, si[bp] <= cos(max_ad/2)*(td[bp] - max_ad/2) + sin(max_ad/2)) @constraint(model, si[bp] >= cos(max_ad/2)*(td[bp] + max_ad/2) - sin(max_ad/2)) end if ub <= 0 @constraint(model, si[bp] <= (sin(lb) - sin(ub))/(lb-ub)*(td[bp] - lb) + sin(lb)) @constraint(model, si[bp] >= cos(max_ad/2)*(td[bp] + max_ad/2) - sin(max_ad/2)) end if lb >= 0 @constraint(model, si[bp] <= cos(max_ad/2)*(td[bp] - max_ad/2) + sin(max_ad/2)) @constraint(model, si[bp] >= (sin(lb) - sin(ub))/(lb-ub)*(td[bp] - lb) + sin(lb)) end # end of relaxation sin # relaxation cos @constraint(model, cs[bp] <= 1 - (1-cos(max_ad))/(max_ad*max_ad)*(td[bp]^2)) @constraint(model, cs[bp] >= (cos(lb) - cos(ub))/(lb-ub)*(td[bp] - lb) + cos(lb)) # end of relaxation cos ##### relaxation trilinear wr val = [ ref[:bus][i]["vmin"] * ref[:bus][j]["vmin"] ref[:bus][i]["vmin"] * ref[:bus][j]["vmin"] ref[:bus][i]["vmin"] * ref[:bus][j]["vmax"] ref[:bus][i]["vmin"] * ref[:bus][j]["vmax"] ref[:bus][i]["vmax"] * ref[:bus][j]["vmin"] ref[:bus][i]["vmax"] * ref[:bus][j]["vmin"] ref[:bus][i]["vmax"] * ref[:bus][j]["vmax"] ref[:bus][i]["vmax"] * ref[:bus][j]["vmax"] ] wr_val = val .* [cos_min[bp], cos_max[bp], cos_min[bp], cos_max[bp], cos_min[bp], cos_max[bp], cos_min[bp], cos_max[bp]] @constraint(model, wr[bp] == sum(wr_val[ii]*lambda_wr[bp,ii] for ii in 1:8)) @constraint(model, vm[i] == (lambda_wr[bp,1] + lambda_wr[bp,2] + lambda_wr[bp,3] + lambda_wr[bp,4])*ref[:bus][i]["vmin"] + (lambda_wr[bp,5] + lambda_wr[bp,6] + lambda_wr[bp,7] + lambda_wr[bp,8])*ref[:bus][i]["vmax"]) @constraint(model, vm[j] == (lambda_wr[bp,1] + lambda_wr[bp,2] + lambda_wr[bp,5] + lambda_wr[bp,6])*ref[:bus][j]["vmin"] + (lambda_wr[bp,3] + lambda_wr[bp,4] + lambda_wr[bp,7] + lambda_wr[bp,8])*ref[:bus][j]["vmax"]) @constraint(model, cs[bp] == (lambda_wr[bp,1] + lambda_wr[bp,3] + lambda_wr[bp,5] + lambda_wr[bp,7])*cos_min[bp] + (lambda_wr[bp,2] + lambda_wr[bp,4] + lambda_wr[bp,6] + lambda_wr[bp,8])*cos_max[bp]) @constraint(model, sum(lambda_wr[bp,ii] for ii in 1:8) == 1) #### end of relaxation trilinear wr ##### relaxation trilinear wi sin_min = sin(buspair["angmin"]) sin_max = sin(buspair["angmax"]) wi_val = val .* [sin_min, sin_max, sin_min, sin_max, sin_min, sin_max, sin_min, sin_max] @constraint(model, wi[bp] == sum(wi_val[ii]*lambda_wi[bp,ii] for ii in 1:8)) @constraint(model, vm[i] == (lambda_wi[bp,1] + lambda_wi[bp,2] + lambda_wi[bp,3] + lambda_wi[bp,4])*ref[:bus][i]["vmin"] + (lambda_wi[bp,5] + lambda_wi[bp,6] + lambda_wi[bp,7] + lambda_wi[bp,8])*ref[:bus][i]["vmax"]) @constraint(model, vm[j] == (lambda_wi[bp,1] + lambda_wi[bp,2] + lambda_wi[bp,5] + lambda_wi[bp,6])*ref[:bus][j]["vmin"] + (lambda_wi[bp,3] + lambda_wi[bp,4] + lambda_wi[bp,7] + lambda_wi[bp,8])*ref[:bus][j]["vmax"]) @constraint(model, si[bp] == (lambda_wi[bp,1] + lambda_wi[bp,3] + lambda_wi[bp,5] + lambda_wi[bp,7])*sin(buspair["angmin"]) + (lambda_wi[bp,2] + lambda_wi[bp,4] + lambda_wi[bp,6] + lambda_wi[bp,8])*sin(buspair["angmax"])) @constraint(model, sum(lambda_wi[bp,ii] for ii in 1:8) == 1) #### end of relaxation trilinear wi # relaxation tighten vv - tying constraint @constraint(model, sum(lambda_wr[bp,ii]*val[ii] - lambda_wi[bp,ii]*val[ii] for ii in 1:8) == 0) # end of relaxation tighten vv vfub = buspair["vm_fr_max"] vflb = buspair["vm_fr_min"] vtub = buspair["vm_to_max"] vtlb = buspair["vm_to_min"] tdub = buspair["angmax"] tdlb = buspair["angmin"] phi = (tdub + tdlb)/2 d = (tdub - tdlb)/2 sf = vflb + vfub st = vtlb + vtub # Voltage Product Relaxation Upperbound @constraint(model, sf*st*(cos(phi)*wr[bp] + sin(phi)*wi[bp]) - vtub*cos(d)*st*w[i] - vfub*cos(d)*sf*w[j] >= vfub*vtub*cos(d)*(vflb*vtlb - vfub*vtub)) @constraint(model, sf*st*(cos(phi)*wr[bp] + sin(phi)*wi[bp]) - vtlb*cos(d)*st*w[i] - vflb*cos(d)*sf*w[j] >= -vflb*vtlb*cos(d)*(vflb*vtlb - vfub*vtub)) end # end of QC tri-form voltage constraint # end of voltage constraints for (i,branch) in ref[:branch] bp = (branch["f_bus"], branch["t_bus"]) buspair = ref[:buspairs][bp] tm = branch["tap"] # to prevent this constraint from being posted on multiple parallel branches if buspair["branch"] == i # extract quantities g, b = PowerModels.calc_branch_y(branch) tr, ti = PowerModels.calc_branch_t(branch) g_fr = branch["g_fr"] b_fr = branch["b_fr"] # extract variables p_fr = p[(i,branch["f_bus"],branch["t_bus"])] q_fr = q[(i,branch["f_bus"],branch["t_bus"])] w_fr = w[branch["f_bus"]] w_to = w[branch["t_bus"]] @constraint(model, p_fr^2 + q_fr^2 <= w_fr/tm^2*cm[bp]) ym_sh_sqr = g_fr^2 + b_fr^2 @constraint(model, cm[bp] == (g^2 + b^2)*(w_fr/tm^2 + w_to - 2*(tr*wr[bp] + ti*wi[bp])/tm^2) - ym_sh_sqr*(w_fr/tm^2) + 2*(g_fr*p_fr - b_fr*q_fr)) end end # constraint theta ref for i in keys(ref[:ref_buses]) @constraint(model, va[i] == 0) end # constraint KCL shunt for (i,bus) in ref[:bus] # Bus KCL gs = 0.0 bs = 0.0 if length(ref[:bus_shunts][i]) > 0 shunt_num = ref[:bus_shunts][i][1] gs = ref[:shunt][shunt_num]["gs"] bs = ref[:shunt][shunt_num]["bs"] end @constraint(model, sum(p[a] for a in ref[:bus_arcs][i]) + sum(p_dc[a_dc] for a_dc in ref[:bus_arcs_dc][i]) == sum(pg[g] for g in ref[:bus_gens][i]) - sum(load["pd"] for (l,load) in ref[:load] if load["load_bus"]==i) - gs*w[i] ) @constraint(model, sum(q[a] for a in ref[:bus_arcs][i]) + sum(q_dc[a_dc] for a_dc in ref[:bus_arcs_dc][i]) == sum(qg[g] for g in ref[:bus_gens][i]) - sum(load["qd"] for (l,load) in ref[:load] if load["load_bus"]==i) + bs*w[i] ) end # ohms laws, voltage angle difference limits for (i,branch) in ref[:branch] f_idx = (i, branch["f_bus"], branch["t_bus"]) t_idx = (i, branch["t_bus"], branch["f_bus"]) bp_idx = (branch["f_bus"], branch["t_bus"]) p_fr = p[f_idx] q_fr = q[f_idx] p_to = p[t_idx] q_to = q[t_idx] w_fr = w[branch["f_bus"]] w_to = w[branch["t_bus"]] wr_br = wr[bp_idx] wi_br = wi[bp_idx] # Line Flow g, b = PowerModels.calc_branch_y(branch) tr, ti = PowerModels.calc_branch_t(branch) g_fr = branch["g_fr"] g_to = branch["g_to"] b_fr = branch["b_fr"] b_to = branch["b_to"] tm = branch["tap"] # AC Line Flow Constraints @constraint(model, p_fr == (g+g_fr)/tm^2*w_fr + (-g*tr+b*ti)/tm^2*wr_br + (-b*tr-g*ti)/tm^2*wi_br ) @constraint(model, q_fr == -(b+b_fr)/tm^2*w_fr - (-b*tr-g*ti)/tm^2*wr_br + (-g*tr+b*ti)/tm^2*wi_br ) @constraint(model, p_to == (g+g_to)*w_to + (-g*tr-b*ti)/tm^2*wr_br + (-b*tr+g*ti)/tm^2*-wi_br ) @constraint(model, q_to == -(b+b_to)*w_to - (-b*tr+g*ti)/tm^2*wr_br + (-g*tr-b*ti)/tm^2*-wi_br ) # Phase Angle Difference Limit @constraint(model, wi_br <= tan(branch["angmax"])*wr_br) @constraint(model, wi_br >= tan(branch["angmin"])*wr_br) # Apparent Power Limit, From and To if haskey(branch, "rate_a") @constraint(model, p[f_idx]^2 + q[f_idx]^2 <= branch["rate_a"]^2) @constraint(model, p[t_idx]^2 + q[t_idx]^2 <= branch["rate_a"]^2) end end # DC line constraints for (i,dcline) in ref[:dcline] # DC Line Flow Constraint f_idx = (i, dcline["f_bus"], dcline["t_bus"]) t_idx = (i, dcline["t_bus"], dcline["f_bus"]) @constraint(model, (1-dcline["loss1"])*p_dc[f_idx] + (p_dc[t_idx] - dcline["loss0"]) == 0) end return model end """ Given a JuMP model and a PowerModels network data structure, Builds an DC-OPF formulation of the given data and returns the JuMP model """ function build_dc_opf(data::Dict{String,Any}, model=Model()) @assert !haskey(data, "multinetwork") @assert !haskey(data, "conductors") PowerModels.standardize_cost_terms!(data, order=2) ref = PowerModels.build_ref(data)[:it][_PM.pm_it_sym][:nw][nw_id_default] @variable(model, va[i in keys(ref[:bus])]) @variable(model, ref[:gen][i]["pmin"] <= pg[i in keys(ref[:gen])] <= ref[:gen][i]["pmax"]) @variable(model, -Inf <= p[(l,i,j) in ref[:arcs]] <= Inf) for arc in ref[:arcs] (l,i,j) = arc branch = ref[:branch][l] if haskey(branch, "rate_a") JuMP.set_lower_bound(p[arc], -branch["rate_a"]) JuMP.set_upper_bound(p[arc], branch["rate_a"]) end end p_expr = Dict([((l,i,j), 1.0*p[(l,i,j)]) for (l,i,j) in ref[:arcs_from]]) p_expr = merge(p_expr, Dict([((l,j,i), -1.0*p[(l,i,j)]) for (l,i,j) in ref[:arcs_from]])) @variable(model, p_dc[a in ref[:arcs_dc]]) for (l,dcline) in ref[:dcline] f_idx = (l, dcline["f_bus"], dcline["t_bus"]) t_idx = (l, dcline["t_bus"], dcline["f_bus"]) JuMP.set_lower_bound(p_dc[f_idx], dcline["pminf"]) JuMP.set_upper_bound(p_dc[f_idx], dcline["pmaxf"]) JuMP.set_lower_bound(p_dc[t_idx], dcline["pmint"]) JuMP.set_upper_bound(p_dc[t_idx], dcline["pmaxt"]) end from_idx = Dict(arc[1] => arc for arc in ref[:arcs_from_dc]) @objective(model, Min, sum(gen["cost"][1]*pg[i]^2 + gen["cost"][2]*pg[i] + gen["cost"][3] for (i,gen) in ref[:gen]) + sum(dcline["cost"][1]*p_dc[from_idx[i]]^2 + dcline["cost"][2]*p_dc[from_idx[i]] + dcline["cost"][3] for (i,dcline) in ref[:dcline]) ) for (i,bus) in ref[:ref_buses] # Refrence Bus @constraint(model, va[i] == 0) end for (i,bus) in ref[:bus] bus_loads = [ref[:load][l] for l in ref[:bus_loads][i]] bus_shunts = [ref[:shunt][s] for s in ref[:bus_shunts][i]] # Bus KCL @constraint(model, sum(p_expr[a] for a in ref[:bus_arcs][i]) + sum(p_dc[a_dc] for a_dc in ref[:bus_arcs_dc][i]) == sum(pg[g] for g in ref[:bus_gens][i]) - sum(load["pd"] for load in bus_loads) - sum(shunt["gs"] for shunt in bus_shunts)*1.0^2 ) end for (i,branch) in ref[:branch] f_idx = (i, branch["f_bus"], branch["t_bus"]) p_fr = p[f_idx] va_fr = va[branch["f_bus"]] va_to = va[branch["t_bus"]] g, b = PowerModels.calc_branch_y(branch) # DC Line Flow Constraints @constraint(model, p_fr == -b*(va_fr - va_to)) # Phase Angle Difference Limit @constraint(model, va_fr - va_to <= branch["angmax"]) @constraint(model, va_fr - va_to >= branch["angmin"]) # Apparent Power Limit, From and To # covered by variable bounds end for (i,dcline) in ref[:dcline] # DC Line Flow Constraint f_idx = (i, dcline["f_bus"], dcline["t_bus"]) t_idx = (i, dcline["t_bus"], dcline["f_bus"]) @constraint(model, (1-dcline["loss1"])*p_dc[f_idx] + (p_dc[t_idx] - dcline["loss0"]) == 0) end return model end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
10121
export build_ac_pf, build_soc_pf, build_dc_pf """ Given a JuMP model and a PowerModels network data structure, Builds an AC-PF formulation of the given data and returns the JuMP model """ function build_ac_pf(data::Dict{String,Any}, model=Model()) @assert !_IM.ismultinetwork(data) @assert !haskey(data, "conductors") ref = PowerModels.build_ref(data)[:it][_PM.pm_it_sym][:nw][nw_id_default] @variable(model, va[i in keys(ref[:bus])]) @variable(model, vm[i in keys(ref[:bus])], start=1.0) @variable(model, pg[i in keys(ref[:gen])]) @variable(model, qg[i in keys(ref[:gen])]) @variable(model, p_dc[(l,i,j) in ref[:arcs_dc]]) @variable(model, q_dc[(l,i,j) in ref[:arcs_dc]]) p = Dict() q = Dict() for (i,branch) in ref[:branch] # AC Line Flow Constraint f_idx = (i, branch["f_bus"], branch["t_bus"]) t_idx = (i, branch["t_bus"], branch["f_bus"]) vm_fr = vm[branch["f_bus"]] vm_to = vm[branch["t_bus"]] va_fr = va[branch["f_bus"]] va_to = va[branch["t_bus"]] # Line Flow g, b = PowerModels.calc_branch_y(branch) tr, ti = PowerModels.calc_branch_t(branch) g_fr = branch["g_fr"] b_fr = branch["b_fr"] g_to = branch["g_to"] b_to = branch["b_to"] tm = branch["tap"]^2 p[f_idx] = @expression(model, (g+g_fr)/tm*vm_fr^2 + (-g*tr+b*ti)/tm*(vm_fr*vm_to*cos(va_fr-va_to)) + (-b*tr-g*ti)/tm*(vm_fr*vm_to*sin(va_fr-va_to)) ) q[f_idx] = @expression(model, -(b+b_fr)/tm*vm_fr^2 - (-b*tr-g*ti)/tm*(vm_fr*vm_to*cos(va_fr-va_to)) + (-g*tr+b*ti)/tm*(vm_fr*vm_to*sin(va_fr-va_to)) ) p[t_idx] = @expression(model, (g+g_to)*vm_to^2 + (-g*tr-b*ti)/tm*(vm_to*vm_fr*cos(va_to-va_fr)) + (-b*tr+g*ti)/tm*(vm_to*vm_fr*sin(va_to-va_fr)) ) q[t_idx] = @expression(model, -(b+b_to)*vm_to^2 - (-b*tr+g*ti)/tm*(vm_to*vm_fr*cos(va_fr-va_to)) + (-g*tr-b*ti)/tm*(vm_to*vm_fr*sin(va_to-va_fr)) ) end for (i,bus) in ref[:ref_buses] # Refrence Bus @assert bus["bus_type"] == 3 @constraint(model, va[i] == 0) @constraint(model, vm[i] == bus["vm"]) end for (i,bus) in ref[:bus] bus_loads = [ref[:load][l] for l in ref[:bus_loads][i]] bus_shunts = [ref[:shunt][s] for s in ref[:bus_shunts][i]] # Bus KCL @constraint(model, sum(p[a] for a in ref[:bus_arcs][i]) + sum(p_dc[a_dc] for a_dc in ref[:bus_arcs_dc][i]) == sum(pg[g] for g in ref[:bus_gens][i]) - sum(load["pd"] for load in bus_loads) - sum(shunt["gs"] for shunt in bus_shunts)*vm[i]^2 ) @constraint(model, sum(q[a] for a in ref[:bus_arcs][i]) + sum(q_dc[a_dc] for a_dc in ref[:bus_arcs_dc][i]) == sum(qg[g] for g in ref[:bus_gens][i]) - sum(load["qd"] for load in bus_loads) + sum(shunt["bs"] for shunt in bus_shunts)*vm[i]^2 ) # PV Bus Constraints if length(ref[:bus_gens][i]) > 0 && !(i in keys(ref[:ref_buses])) # this assumes inactive generators are filtered out of bus_gens @assert bus["bus_type"] == 2 @constraint(model, vm[i] == bus["vm"]) for j in ref[:bus_gens][i] @constraint(model, pg[j] == ref[:gen][j]["pg"]) end end end for (i,dcline) in ref[:dcline] # DC Line Flow Constraint f_idx = (i, dcline["f_bus"], dcline["t_bus"]) t_idx = (i, dcline["t_bus"], dcline["f_bus"]) @constraint(model, p_dc[f_idx] == dcline["pf"]) @constraint(model, p_dc[t_idx] == dcline["pt"]) f_bus = ref[:bus][dcline["f_bus"]] if f_bus["bus_type"] == 1 @constraint(model, vm[dcline["f_bus"]] == f_bus["vm"]) end t_bus = ref[:bus][dcline["t_bus"]] if t_bus["bus_type"] == 1 @constraint(model, vm[dcline["t_bus"]] == t_bus["vm"]) end end return model end """ Given a JuMP model and a PowerModels network data structure, Builds an SOC-PF formulation of the given data and returns the JuMP model """ function build_soc_pf(data::Dict{String,Any}, model=Model()) @assert !_IM.ismultinetwork(data) @assert !haskey(data, "conductors") ref = PowerModels.build_ref(data)[:it][_PM.pm_it_sym][:nw][nw_id_default] @variable(model, w[i in keys(ref[:bus])] >= 0, start=1.001) @variable(model, wr[bp in keys(ref[:buspairs])], start=1.0) @variable(model, wi[bp in keys(ref[:buspairs])]) @variable(model, pg[i in keys(ref[:gen])]) @variable(model, qg[i in keys(ref[:gen])]) @variable(model, p_dc[(l,i,j) in ref[:arcs_dc]]) @variable(model, q_dc[(l,i,j) in ref[:arcs_dc]]) p = Dict() q = Dict() for (i,branch) in ref[:branch] # AC Line Flow Constraint f_idx = (i, branch["f_bus"], branch["t_bus"]) t_idx = (i, branch["t_bus"], branch["f_bus"]) bp_idx = (branch["f_bus"], branch["t_bus"]) w_fr = w[branch["f_bus"]] w_to = w[branch["t_bus"]] wr_br = wr[bp_idx] wi_br = wi[bp_idx] g, b = PowerModels.calc_branch_y(branch) tr, ti = PowerModels.calc_branch_t(branch) g_fr = branch["g_fr"] b_fr = branch["b_fr"] g_to = branch["g_to"] b_to = branch["b_to"] tm = branch["tap"]^2 p[f_idx] = (g+g_fr)/tm*w_fr + (-g*tr+b*ti)/tm*(wr_br) + (-b*tr-g*ti)/tm*(wi_br) q[f_idx] = -(b+b_fr)/tm*w_fr - (-b*tr-g*ti)/tm*(wr_br) + (-g*tr+b*ti)/tm*(wi_br) p[t_idx] = (g+g_to)*w_to + (-g*tr-b*ti)/tm*(wr_br) + (-b*tr+g*ti)/tm*(-wi_br) q[t_idx] = -(b+b_to)*w_to - (-b*tr+g*ti)/tm*(wr_br) + (-g*tr-b*ti)/tm*(-wi_br) end for (i,j) in keys(ref[:buspairs]) # Voltage Product Relaxation @constraint(model, wr[(i,j)]^2 + wi[(i,j)]^2 <= w[i]*w[j]) end for (i,bus) in ref[:ref_buses] # Refrence Bus @assert bus["bus_type"] == 3 @constraint(model, w[i] == bus["vm"]^2) end for (i,bus) in ref[:bus] bus_loads = [ref[:load][l] for l in ref[:bus_loads][i]] bus_shunts = [ref[:shunt][s] for s in ref[:bus_shunts][i]] # Bus KCL @constraint(model, sum(p[a] for a in ref[:bus_arcs][i]) + sum(p_dc[a_dc] for a_dc in ref[:bus_arcs_dc][i]) == sum(pg[g] for g in ref[:bus_gens][i]) - sum(load["pd"] for load in bus_loads) - sum(shunt["gs"] for shunt in bus_shunts)*w[i] ) @constraint(model, sum(q[a] for a in ref[:bus_arcs][i]) + sum(q_dc[a_dc] for a_dc in ref[:bus_arcs_dc][i]) == sum(qg[g] for g in ref[:bus_gens][i]) - sum(load["qd"] for load in bus_loads) + sum(shunt["bs"] for shunt in bus_shunts)*w[i] ) # PV Bus Constraints if length(ref[:bus_gens][i]) > 0 && !(i in keys(ref[:ref_buses])) # this assumes inactive generators are filtered out of bus_gens @assert bus["bus_type"] == 2 @constraint(model, w[i] == bus["vm"]^2) for j in ref[:bus_gens][i] @constraint(model, pg[j] == ref[:gen][j]["pg"]) end end end for (i,dcline) in ref[:dcline] # DC Line Flow Constraint f_idx = (i, dcline["f_bus"], dcline["t_bus"]) t_idx = (i, dcline["t_bus"], dcline["f_bus"]) @constraint(model, p_dc[f_idx] == dcline["pf"]) @constraint(model, p_dc[t_idx] == dcline["pt"]) f_bus = ref[:bus][dcline["f_bus"]] if f_bus["bus_type"] == 1 @constraint(model, w[dcline["f_bus"]] == f_bus["vm"]^2) end t_bus = ref[:bus][dcline["t_bus"]] if t_bus["bus_type"] == 1 @constraint(model, w[dcline["t_bus"]] == t_bus["vm"]^2) end end return model end """ Given a JuMP model and a PowerModels network data structure, Builds an DC-PF formulation of the given data and returns the JuMP model """ function build_dc_pf(data::Dict{String,Any}, model=Model()) @assert !_IM.ismultinetwork(data) @assert !haskey(data, "conductors") ref = PowerModels.build_ref(data)[:it][_PM.pm_it_sym][:nw][nw_id_default] @variable(model, va[i in keys(ref[:bus])]) @variable(model, pg[i in keys(ref[:gen])]) @variable(model, p_dc[(l,i,j) in ref[:arcs_dc]]) p = Dict() for (i,branch) in ref[:branch] f_idx = (i, branch["f_bus"], branch["t_bus"]) t_idx = (i, branch["t_bus"], branch["f_bus"]) va_fr = va[branch["f_bus"]] va_to = va[branch["t_bus"]] # Line Flow g, b = PowerModels.calc_branch_y(branch) p[f_idx] = -b*(va_fr - va_to) p[t_idx] = -b*(va_to - va_fr) end for (i,bus) in ref[:ref_buses] # Refrence Bus @constraint(model, va[i] == 0) end for (i,bus) in ref[:bus] bus_loads = [ref[:load][l] for l in ref[:bus_loads][i]] bus_shunts = [ref[:shunt][s] for s in ref[:bus_shunts][i]] # Bus KCL @constraint(model, sum(p[a] for a in ref[:bus_arcs][i]) + sum(p_dc[a_dc] for a_dc in ref[:bus_arcs_dc][i]) == sum(pg[g] for g in ref[:bus_gens][i]) - sum(load["pd"] for load in bus_loads) - sum(shunt["gs"] for shunt in bus_shunts)*1.0^2 ) # PV Bus Constraints if length(ref[:bus_gens][i]) > 0 && !(i in keys(ref[:ref_buses])) # this assumes inactive generators are filtered out of bus_gens @assert bus["bus_type"] == 2 for j in ref[:bus_gens][i] @constraint(model, pg[j] == ref[:gen][j]["pg"]) end end end for (i,dcline) in ref[:dcline] # DC Line Flow Constraint f_idx = (i, dcline["f_bus"], dcline["t_bus"]) t_idx = (i, dcline["t_bus"], dcline["f_bus"]) @constraint(model, p_dc[f_idx] == dcline["pf"]) @constraint(model, p_dc[t_idx] == dcline["pt"]) end return model end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
4793
export solve_opf_api "" function solve_opf_api(file, model_constructor, optimizer; kwargs...) return _PM.solve_model(file, model_constructor, optimizer, build_opf_api; kwargs...) end "" function build_opf_api(pm::_PM.AbstractPowerModel) _PM.variable_bus_voltage(pm) bounds_tighten_voltage(pm) _PM.variable_gen_power(pm, bounded = false) upperbound_negative_active_generation(pm) _PM.variable_branch_power(pm) _PM.variable_dcline_power(pm) variable_load_factor(pm) #objective_max_loading(pm) #objective_max_loading_voltage_norm(pm) objective_max_loading_gen_output(pm) _PM.constraint_model_voltage(pm) for i in _PM.ids(pm, :ref_buses) _PM.constraint_theta_ref(pm, i) end for (i,gen) in ref(pm, :gen) pg = var(pm, :pg, i) @constraint(pm.model, pg >= gen["pmin"]) end for i in _PM.ids(pm, :bus) constraint_power_balance_shunt_scaled(pm, i) end for i in _PM.ids(pm, :branch) _PM.constraint_ohms_yt_from(pm, i) _PM.constraint_ohms_yt_to(pm, i) _PM.constraint_voltage_angle_difference(pm, i) constraint_thermal_limit_from(pm, i; scale = 0.999) constraint_thermal_limit_to(pm, i; scale = 0.999) end for i in _PM.ids(pm, :dcline) _PM.constraint_dcline_power_losses(pm, i) end end "variable: load_factor >= 1.0" function variable_load_factor(pm::_PM.AbstractPowerModel, report::Bool=true) load_factor = var(pm)[:load_factor] = @variable(pm.model, base_name="load_factor", lower_bound=1.0, start = 1.0 ) sol(pm)[:load_factor] = load_factor for (i,load) in ref(pm, :load) if load["pd"] > 0 && load["qd"] > 0 sol(pm, :load, i)[:pd] = load["pd"]*load_factor else sol(pm, :load, i)[:pd] = load["pd"] end sol(pm, :load, i)[:qd] = load["qd"] end end "objective: Max. load_factor" function objective_max_loading(pm::_PM.AbstractPowerModel) @objective(pm.model, Max, var(pm, :load_factor)) end "" function objective_max_loading_voltage_norm(pm::_PM.AbstractPowerModel) # Seems to create too much reactive power and makes even small models hard to converge load_factor = var(pm, :load_factor) scale = length(_PM.ids(pm, :bus)) vm = var(pm, :vm) @objective(pm.model, Max, 10*scale*load_factor - sum(((bus["vmin"] + bus["vmax"])/2 - vm[i])^2 for (i,bus) in ref(pm, :bus))) end "" function objective_max_loading_gen_output(pm::_PM.AbstractPowerModel) # Works but adds unnecessary runtime load_factor = var(pm, :load_factor) scale = length(_PM.ids(pm, :gen)) pg = var(pm, :pg) qg = var(pm, :qg) @objective(pm.model, Max, 100*scale*load_factor - sum( ((gen["qmin"] + gen["qmax"])/2 - qg[i])^2 for (i,gen) in ref(pm, :gen))) end "" function bounds_tighten_voltage(pm::_PM.AbstractACPModel; epsilon = 0.001) for (i,bus) in ref(pm, :bus) v = var(pm, :vm, i) JuMP.set_upper_bound(v, bus["vmax"]*(1.0-epsilon)) JuMP.set_lower_bound(v, bus["vmin"]*(1.0+epsilon)) end end "" function upperbound_negative_active_generation(pm::_PM.AbstractPowerModel) for (i,gen) in ref(pm, :gen) if gen["pmax"] <= 0 pg = var(pm, :pg, i) JuMP.set_upper_bound(pg, gen["pmax"]) end end end "" function constraint_power_balance_shunt_scaled(pm::_PM.AbstractACPModel, n::Int, i::Int) bus = ref(pm, n, :bus, i) bus_arcs = ref(pm, n, :bus_arcs, i) bus_gens = ref(pm, n, :bus_gens, i) bus_loads = ref(pm, n, :bus_loads, i) bus_shunts = ref(pm, n, :bus_shunts, i) load_factor = var(pm, n, :load_factor) vm = var(pm, n, :vm, i) p = var(pm, n, :p) q = var(pm, n, :q) pg = var(pm, n, :pg) qg = var(pm, n, :qg) if length(bus_loads) > 0 pd = sum([ref(pm, n, :load, i, "pd") for i in bus_loads]) qd = sum([ref(pm, n, :load, i, "qd") for i in bus_loads]) else pd = 0.0 qd = 0.0 end if length(bus_shunts) > 0 gs = sum([ref(pm, n, :shunt, i, "gs") for i in bus_shunts]) bs = sum([ref(pm, n, :shunt, i, "bs") for i in bus_shunts]) else gs = 0.0 bs = 0.0 end if pd > 0.0 && qd > 0.0 @constraint(pm.model, sum(p[a] for a in bus_arcs) == sum(pg[g] for g in bus_gens) - pd*load_factor - gs*vm^2) else # super fallback impl @constraint(pm.model, sum(p[a] for a in bus_arcs) == sum(pg[g] for g in bus_gens) - pd - gs*vm^2) end @constraint(pm.model, sum(q[a] for a in bus_arcs) == sum(qg[g] for g in bus_gens) - qd + bs*vm^2) end constraint_power_balance_shunt_scaled(pm::_PM.AbstractPowerModel, i::Int) = constraint_power_balance_shunt_scaled(pm, nw_id_default, i)
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
1370
export solve_opf_sad "" function solve_opf_sad(file, model_constructor, optimizer; kwargs...) return _PM.solve_model(file, model_constructor, optimizer, build_opf_sad; kwargs...) end "" function build_opf_sad(pm::_PM.AbstractPowerModel) _PM.variable_bus_voltage(pm) _PM.variable_gen_power(pm) _PM.variable_branch_power(pm) _PM.variable_dcline_power(pm, bounded = false) @variable(pm.model, theta_delta_bound >= 0.0, start = 0.523598776) @objective(pm.model, Min, theta_delta_bound) _PM.constraint_model_voltage(pm) for i in _PM.ids(pm, :ref_buses) _PM.constraint_theta_ref(pm, i) end for i in _PM.ids(pm, :bus) _PM.constraint_power_balance(pm, i) end for (i, branch) in ref(pm, :branch) _PM.constraint_ohms_yt_from(pm, i) _PM.constraint_ohms_yt_to(pm, i) _PM.constraint_voltage_angle_difference(pm, i) theta_fr = var(pm, :va, branch["f_bus"]) theta_to = var(pm, :va, branch["t_bus"]) @constraint(pm.model, theta_fr - theta_to <= theta_delta_bound) @constraint(pm.model, theta_fr - theta_to >= -theta_delta_bound) constraint_thermal_limit_from(pm, i; scale = 0.999) constraint_thermal_limit_to(pm, i; scale = 0.999) end for i in _PM.ids(pm, :dcline) _PM.constraint_dcline_power_losses(pm, i) end end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
1023
### Branch - Thermal Limit Constraints ### "" function constraint_thermal_limit_from(pm::_PM.AbstractPowerModel, n::Int, i::Int; scale = 1.0) branch = ref(pm, n, :branch, i) f_bus = branch["f_bus"] t_bus = branch["t_bus"] f_idx = (i, f_bus, t_bus) if haskey(branch, "rate_a") _PM.constraint_thermal_limit_from(pm, n, f_idx, branch["rate_a"]*scale) end end constraint_thermal_limit_from(pm::_PM.AbstractPowerModel, i::Int; scale = 1.0) = constraint_thermal_limit_from(pm, nw_id_default, i; scale=scale) "" function constraint_thermal_limit_to(pm::_PM.AbstractPowerModel, n::Int, i::Int; scale = 1.0) branch = ref(pm, n, :branch, i) f_bus = branch["f_bus"] t_bus = branch["t_bus"] t_idx = (i, t_bus, f_bus) if haskey(branch, "rate_a") _PM.constraint_thermal_limit_to(pm, n, t_idx, branch["rate_a"]*scale) end end constraint_thermal_limit_to(pm::_PM.AbstractPowerModel, i::Int; scale = 1.0) = constraint_thermal_limit_to(pm, nw_id_default, i; scale=scale)
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
3656
export solve_opf_pwl_delta, build_opf_pwl_delta "" function solve_opf_pwl_delta(file, model_type::Type, optimizer; kwargs...) return _PM.solve_model(file, model_type, optimizer, build_opf_pwl_delta; kwargs...) end "a variant of the OPF problem specification that uses a max variant of the pwl cost function implementation" function build_opf_pwl_delta(pm::_PM.AbstractPowerModel) _PM.variable_bus_voltage(pm) _PM.variable_gen_power(pm) _PM.variable_branch_power(pm) _PM.variable_dcline_power(pm) objective_min_fuel_cost_delta(pm) _PM.constraint_model_voltage(pm) for i in ids(pm, :ref_buses) _PM.constraint_theta_ref(pm, i) end for i in ids(pm, :bus) _PM.constraint_power_balance(pm, i) end for i in ids(pm, :branch) _PM.constraint_ohms_yt_from(pm, i) _PM.constraint_ohms_yt_to(pm, i) _PM.constraint_voltage_angle_difference(pm, i) _PM.constraint_thermal_limit_from(pm, i) _PM.constraint_thermal_limit_to(pm, i) end for i in ids(pm, :dcline) _PM.constraint_dcline_power_losses(pm, i) end end "" function objective_min_fuel_cost_delta(pm::_PM.AbstractPowerModel; kwargs...) expression_pg_cost_delta(pm; kwargs...) return JuMP.@objective(pm.model, Min, sum( sum( var(pm, n, :pg_cost, i) for (i,gen) in nw_ref[:gen]) for (n, nw_ref) in _PM.nws(pm)) ) end "" function expression_pg_cost_delta(pm::_PM.AbstractPowerModel; report::Bool=true) for (n, nw_ref) in _PM.nws(pm) pg_cost = var(pm, n)[:pg_cost] = Dict{Int,Any}() for (i,gen) in ref(pm, n, :gen) pg_terms = [var(pm, n, :pg, i)] if gen["model"] == 1 if isa(pg_terms, Array{JuMP.VariableRef}) pmin = sum(JuMP.lower_bound.(pg_terms)) pmax = sum(JuMP.upper_bound.(pg_terms)) else pmin = gen["pmin"] pmax = gen["pmax"] end points = _PM.calc_pwl_points(gen["ncost"], gen["cost"], pmin, pmax) pg_cost[i] = _pwl_cost_expression_delta(pm, pg_terms, points, nw=n, id=i, var_name="pg") elseif gen["model"] == 2 cost_rev = reverse(gen["cost"]) pg_cost[i] = _PM._polynomial_cost_expression(pm, pg_terms, cost_rev, nw=n, id=i, var_name="pg") else Memento.error(_LOGGER, "Only cost models of types 1 and 2 are supported at this time, given cost model type of $(model) on generator $(i)") end end report && _PM.sol_component_value(pm, n, :gen, :pg_cost, ids(pm, n, :gen), pg_cost) end end "" function _pwl_cost_expression_delta(pm::_PM.AbstractPowerModel, x_list::Array{JuMP.VariableRef}, points; nw=0, id=1, var_name="x") cost_per_mw = Float64[0.0] for i in 2:length(points) x0 = points[i-1].mw y0 = points[i-1].cost x1 = points[i].mw y1 = points[i].cost m = (y1 - y0)/(x1 - x0) if !isnan(m) push!(cost_per_mw, m) else @assert isapprox(y0, y1) push!(cost_per_mw, 0.0) end end pg_cost_mw = JuMP.@variable(pm.model, [i in 2:length(points)], base_name="$(nw)_pg_$(id)_cost_mw_$(i)", lower_bound = 0.0, upper_bound = points[i].mw - points[i-1].mw ) JuMP.@constraint(pm.model, points[1].mw + sum(pg_cost_mw[i] for i in 2:length(points)) == var(pm, nw, :pg, id)) cost_expr = points[1].cost + sum(cost_per_mw[i]*pg_cost_mw[i] for i in 2:length(points)) return cost_expr end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
3357
export solve_opf_pwl_lambda, build_opf_pwl_lambda "" function solve_opf_pwl_lambda(file, model_type::Type, optimizer; kwargs...) return _PM.solve_model(file, model_type, optimizer, build_opf_pwl_lambda; kwargs...) end "a variant of the OPF problem specification that uses a max variant of the pwl cost function implementation" function build_opf_pwl_lambda(pm::_PM.AbstractPowerModel) _PM.variable_bus_voltage(pm) _PM.variable_gen_power(pm) _PM.variable_branch_power(pm) _PM.variable_dcline_power(pm) objective_min_fuel_cost_lambda(pm) _PM.constraint_model_voltage(pm) for i in ids(pm, :ref_buses) _PM.constraint_theta_ref(pm, i) end for i in ids(pm, :bus) _PM.constraint_power_balance(pm, i) end for i in ids(pm, :branch) _PM.constraint_ohms_yt_from(pm, i) _PM.constraint_ohms_yt_to(pm, i) _PM.constraint_voltage_angle_difference(pm, i) _PM.constraint_thermal_limit_from(pm, i) _PM.constraint_thermal_limit_to(pm, i) end for i in ids(pm, :dcline) _PM.constraint_dcline_power_losses(pm, i) end end "" function objective_min_fuel_cost_lambda(pm::_PM.AbstractPowerModel; kwargs...) expression_pg_cost_lambda(pm; kwargs...) return JuMP.@objective(pm.model, Min, sum( sum( var(pm, n, :pg_cost, i) for (i,gen) in nw_ref[:gen]) for (n, nw_ref) in _PM.nws(pm)) ) end "" function expression_pg_cost_lambda(pm::_PM.AbstractPowerModel; report::Bool=true) for (n, nw_ref) in _PM.nws(pm) pg_cost = var(pm, n)[:pg_cost] = Dict{Int,Any}() for (i,gen) in ref(pm, n, :gen) pg_terms = [var(pm, n, :pg, i)] if gen["model"] == 1 if isa(pg_terms, Array{JuMP.VariableRef}) pmin = sum(JuMP.lower_bound.(pg_terms)) pmax = sum(JuMP.upper_bound.(pg_terms)) else pmin = gen["pmin"] pmax = gen["pmax"] end points = _PM.calc_pwl_points(gen["ncost"], gen["cost"], pmin, pmax) pg_cost[i] = _pwl_cost_expression_lambda(pm, pg_terms, points, nw=n, id=i, var_name="pg") elseif gen["model"] == 2 cost_rev = reverse(gen["cost"]) pg_cost[i] = _PM._polynomial_cost_expression(pm, pg_terms, cost_rev, nw=n, id=i, var_name="pg") else Memento.error(_LOGGER, "Only cost models of types 1 and 2 are supported at this time, given cost model type of $(model) on generator $(i)") end end report && _PM.sol_component_value(pm, n, :gen, :pg_cost, ids(pm, n, :gen), pg_cost) end end "" function _pwl_cost_expression_lambda(pm::_PM.AbstractPowerModel, x_list::Array{JuMP.VariableRef}, points; nw=0, id=1, var_name="x") pg_cost_lambda = JuMP.@variable(pm.model, [i in 1:length(points)], base_name="$(nw)_pg_$(id)_cost_lambda_$(i)", lower_bound = 0.0, upper_bound = 1.0 ) JuMP.@constraint(pm.model, sum(pg_cost_lambda) == 1.0) pg_expr = sum(pt.mw*pg_cost_lambda[i] for (i,pt) in enumerate(points)) pg_cost_expr = sum(pt.cost*pg_cost_lambda[i] for (i,pt) in enumerate(points)) JuMP.@constraint(pm.model, pg_expr == var(pm, nw, :pg, id)) return pg_cost_expr end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
3846
export solve_opf_pwl_phi, build_opf_pwl_phi "" function solve_opf_pwl_phi(file, model_type::Type, optimizer; kwargs...) return _PM.solve_model(file, model_type, optimizer, build_opf_pwl_phi; kwargs...) end "a variant of the OPF problem specification that uses a max variant of the pwl cost function implementation" function build_opf_pwl_phi(pm::_PM.AbstractPowerModel) _PM.variable_bus_voltage(pm) _PM.variable_gen_power(pm) _PM.variable_branch_power(pm) _PM.variable_dcline_power(pm) objective_min_fuel_cost_phi(pm) _PM.constraint_model_voltage(pm) for i in ids(pm, :ref_buses) _PM.constraint_theta_ref(pm, i) end for i in ids(pm, :bus) _PM.constraint_power_balance(pm, i) end for i in ids(pm, :branch) _PM.constraint_ohms_yt_from(pm, i) _PM.constraint_ohms_yt_to(pm, i) _PM.constraint_voltage_angle_difference(pm, i) _PM.constraint_thermal_limit_from(pm, i) _PM.constraint_thermal_limit_to(pm, i) end for i in ids(pm, :dcline) _PM.constraint_dcline_power_losses(pm, i) end end "" function objective_min_fuel_cost_phi(pm::_PM.AbstractPowerModel; kwargs...) expression_pg_cost_phi(pm; kwargs...) return JuMP.@objective(pm.model, Min, sum( sum( var(pm, n, :pg_cost, i) for (i,gen) in nw_ref[:gen]) for (n, nw_ref) in _PM.nws(pm)) ) end "" function expression_pg_cost_phi(pm::_PM.AbstractPowerModel; report::Bool=true) for (n, nw_ref) in _PM.nws(pm) pg_cost = var(pm, n)[:pg_cost] = Dict{Int,Any}() for (i,gen) in ref(pm, n, :gen) pg_terms = [var(pm, n, :pg, i)] if gen["model"] == 1 if isa(pg_terms, Array{JuMP.VariableRef}) pmin = sum(JuMP.lower_bound.(pg_terms)) pmax = sum(JuMP.upper_bound.(pg_terms)) else pmin = gen["pmin"] pmax = gen["pmax"] end points = _PM.calc_pwl_points(gen["ncost"], gen["cost"], pmin, pmax) pg_cost[i] = _pwl_cost_expression_phi(pm, pg_terms, points, nw=n, id=i, var_name="pg") elseif gen["model"] == 2 cost_rev = reverse(gen["cost"]) pg_cost[i] = _PM._polynomial_cost_expression(pm, pg_terms, cost_rev, nw=n, id=i, var_name="pg") else Memento.error(_LOGGER, "Only cost models of types 1 and 2 are supported at this time, given cost model type of $(model) on generator $(i)") end end report && _PM.sol_component_value(pm, n, :gen, :pg_cost, ids(pm, n, :gen), pg_cost) end end "" function _pwl_cost_expression_phi(pm::_PM.AbstractPowerModel, x_list::Array{JuMP.VariableRef}, points; nw=0, id=1, var_name="x") gen_lines = [] for j in 2:length(points) x1 = points[j-1].mw y1 = points[j-1].cost x2 = points[j].mw y2 = points[j].cost m = (y2 - y1)/(x2 - x1) if !isnan(m) b = y1 - m * x1 else @assert isapprox(y1, y2) m = 0.0 b = y1 end push!(gen_lines, (slope=m, intercept=b)) end pmax = ref(pm, nw, :gen, id)["pmax"] pg_phi = JuMP.@variable(pm.model, [j in 3:length(points)], base_name="$(nw)_pg_$(id)_phi_$(j)", lower_bound = 0.0, upper_bound = pmax - points[j-1].mw ) for j in 3:length(points) JuMP.@constraint(pm.model, pg_phi[j] >= var(pm, nw, :pg, id) - points[j-1].mw) end pg_cost_expr = gen_lines[1].slope * var(pm, nw, :pg, id) + gen_lines[1].intercept if length(points) > 2 pg_cost_expr += sum((gen_lines[j-1].slope - gen_lines[j-2].slope)*pg_phi[j] for j in 3:length(points)) end return pg_cost_expr end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
3551
export solve_opf_pwl_psi, build_opf_pwl_psi "" function solve_opf_pwl_psi(file, model_type::Type, optimizer; kwargs...) return _PM.solve_model(file, model_type, optimizer, build_opf_pwl_psi; kwargs...) end "a variant of the OPF problem specification that uses a max variant of the pwl cost function implementation" function build_opf_pwl_psi(pm::_PM.AbstractPowerModel) _PM.variable_bus_voltage(pm) _PM.variable_gen_power(pm) _PM.variable_branch_power(pm) _PM.variable_dcline_power(pm) objective_min_fuel_cost_psi(pm) _PM.constraint_model_voltage(pm) for i in ids(pm, :ref_buses) _PM.constraint_theta_ref(pm, i) end for i in ids(pm, :bus) _PM.constraint_power_balance(pm, i) end for i in ids(pm, :branch) _PM.constraint_ohms_yt_from(pm, i) _PM.constraint_ohms_yt_to(pm, i) _PM.constraint_voltage_angle_difference(pm, i) _PM.constraint_thermal_limit_from(pm, i) _PM.constraint_thermal_limit_to(pm, i) end for i in ids(pm, :dcline) _PM.constraint_dcline_power_losses(pm, i) end end "" function objective_min_fuel_cost_psi(pm::_PM.AbstractPowerModel; kwargs...) expression_pg_cost_psi(pm; kwargs...) return JuMP.@objective(pm.model, Min, sum( sum( var(pm, n, :pg_cost, i) for (i,gen) in nw_ref[:gen]) for (n, nw_ref) in _PM.nws(pm)) ) end "" function expression_pg_cost_psi(pm::_PM.AbstractPowerModel; report::Bool=true) for (n, nw_ref) in _PM.nws(pm) pg_cost = var(pm, n)[:pg_cost] = Dict{Int,Any}() for (i,gen) in ref(pm, n, :gen) pg_terms = [var(pm, n, :pg, i)] if gen["model"] == 1 if isa(pg_terms, Array{JuMP.VariableRef}) pmin = sum(JuMP.lower_bound.(pg_terms)) pmax = sum(JuMP.upper_bound.(pg_terms)) else pmin = gen["pmin"] pmax = gen["pmax"] end points = _PM.calc_pwl_points(gen["ncost"], gen["cost"], pmin, pmax) pg_cost[i] = _pwl_cost_expression_psi(pm, pg_terms, points, nw=n, id=i, var_name="pg") elseif gen["model"] == 2 cost_rev = reverse(gen["cost"]) pg_cost[i] = _PM._polynomial_cost_expression(pm, pg_terms, cost_rev, nw=n, id=i, var_name="pg") else Memento.error(_LOGGER, "Only cost models of types 1 and 2 are supported at this time, given cost model type of $(model) on generator $(i)") end end report && _PM.sol_component_value(pm, n, :gen, :pg_cost, ids(pm, n, :gen), pg_cost) end end "" function _pwl_cost_expression_psi(pm::_PM.AbstractPowerModel, x_list::Array{JuMP.VariableRef}, points; nw=0, id=1, var_name="x") gen_lines = [] for j in 2:length(points) x1 = points[j-1].mw y1 = points[j-1].cost x2 = points[j].mw y2 = points[j].cost m = (y2 - y1)/(x2 - x1) if !isnan(m) b = y1 - m * x1 else @assert isapprox(y1, y2) m = 0.0 b = y1 end push!(gen_lines, (slope=m, intercept=b)) end pg_cost = JuMP.@variable(pm.model, base_name="$(nw)_pg_$(id)_cost", lower_bound = points[1].cost, upper_bound = points[end].cost ) for line in gen_lines JuMP.@constraint(pm.model, pg_cost >= line.slope*var(pm, nw, :pg, id) + line.intercept) end return pg_cost end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
1698
export solve_opf_cop "a closet operating point (cop) opf model variant that minimizes distance from the given operating point" function solve_opf_cop(file, model_type::Type, optimizer; kwargs...) return _PM.solve_model(file, model_type, optimizer, build_opf_cop; kwargs...) end "" function build_opf_cop(pm::_PM.AbstractPowerModel) _PM.variable_bus_voltage(pm) _PM.variable_gen_power(pm) _PM.variable_branch_power(pm) _PM.variable_dcline_power(pm) objective_min_pg_vm_distance(pm) _PM.constraint_model_voltage(pm) for i in ids(pm, :ref_buses) _PM.constraint_theta_ref(pm, i) end for i in ids(pm, :bus) _PM.constraint_power_balance(pm, i) end for i in ids(pm, :branch) _PM.constraint_ohms_yt_from(pm, i) _PM.constraint_ohms_yt_to(pm, i) _PM.constraint_voltage_angle_difference(pm, i) _PM.constraint_thermal_limit_from(pm, i) _PM.constraint_thermal_limit_to(pm, i) end for i in ids(pm, :dcline) _PM.constraint_dcline_power_losses(pm, i) end end function objective_min_pg_vm_distance(pm::_PM.AbstractPowerModel) nws = _PM.nw_ids(pm) return JuMP.@objective(pm.model, Min, sum( sum((gen["pg"] - var(pm, n, :pg, i))^2 for (i,gen) in ref(pm, n, :gen)) + sum((bus["vm"] - var(pm, n, :vm, i))^2 for (i,bus) in ref(pm, n, :bus)) for n in nws) ) end function objective_min_pg_vm_distance(pm::_PM.AbstractActivePowerModel) nws = _PM.nw_ids(pm) return JuMP.@objective(pm.model, Min, sum( sum((gen["pg"] - var(pm, n, :pg, i))^2 for (i,gen) in ref(pm, n, :gen)) for n in nws) ) end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
2789
@testset "test ac cop" begin @testset "3-bus case" begin result = solve_opf_cop(case_files["case3"], ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 0.0; atol = 1e-3) @test isapprox(result["solution"]["gen"]["1"]["pg"], 1.581; atol = 1e-2) @test isapprox(result["solution"]["gen"]["2"]["pg"], 1.599; atol = 1e-2) @test isapprox(result["solution"]["bus"]["1"]["vm"], 1.099; atol = 1e-3) @test isapprox(result["solution"]["bus"]["2"]["vm"], 0.926; atol = 1e-3) end @testset "5-bus pjm case" begin result = solve_opf_cop(case_files["case5"], ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 0.136996; atol = 1e-3) @test isapprox(result["solution"]["gen"]["1"]["pg"], 0.316; atol = 1e-2) @test isapprox(result["solution"]["gen"]["2"]["pg"], 1.616; atol = 1e-2) @test isapprox(result["solution"]["bus"]["1"]["vm"], 0.977; atol = 1e-3) @test isapprox(result["solution"]["bus"]["2"]["vm"], 0.975; atol = 1e-3) end @testset "14-bus ieee case" begin result = solve_opf_cop(case_files["case14"], ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 0.0024798; atol = 1e-3) @test isapprox(result["solution"]["gen"]["1"]["pg"], 2.323; atol = 1e-2) @test isapprox(result["solution"]["gen"]["2"]["pg"], 0.399; atol = 1e-2) @test isapprox(result["solution"]["bus"]["1"]["vm"], 1.059; atol = 1e-3) @test isapprox(result["solution"]["bus"]["2"]["vm"], 1.037; atol = 1e-3) end @testset "30-bus ieee case" begin result = solve_opf_cop(case_files["case30"], ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 0.0; atol = 1e-3) @test isapprox(result["solution"]["gen"]["1"]["pg"], 2.188; atol = 1e-2) @test isapprox(result["solution"]["gen"]["2"]["pg"], 0.800; atol = 1e-2) @test isapprox(result["solution"]["bus"]["1"]["vm"], 1.059; atol = 1e-3) @test isapprox(result["solution"]["bus"]["2"]["vm"], 1.036; atol = 1e-3) end end @testset "test dc cop" begin @testset "5-bus pjm case" begin result = solve_opf_cop(case_files["case5"], DCPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 0.00717; atol = 1e-3) @test isapprox(result["solution"]["gen"]["1"]["pg"], 0.369; atol = 1e-2) @test isapprox(result["solution"]["gen"]["2"]["pg"], 1.669; atol = 1e-2) end end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
4388
@testset "test pwl opf problems with polynomial costs" begin @testset "5-bus with pwl delta model" begin result = solve_opf_pwl_delta(case_files["case5"], ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 18269; atol = 1e0) end @testset "5-bus with pwl lambda model" begin result = solve_opf_pwl_lambda(case_files["case5"], ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 18269; atol = 1e0) end @testset "5-bus with pwl phi model" begin result = solve_opf_pwl_phi(case_files["case5"], ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 18269; atol = 1e0) end @testset "5-bus with pwl psi model" begin result = solve_opf_pwl_psi(case_files["case5"], ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 18269; atol = 1e0) end end @testset "test ac polar pwl opf" begin @testset "5-bus with pwl delta model" begin result = solve_opf_pwl_delta(case_file_pwl, ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 42905; atol = 1e0) end @testset "5-bus with pwl lambda model" begin result = solve_opf_pwl_lambda(case_file_pwl, ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 42905; atol = 1e0) end @testset "5-bus with pwl phi model" begin result = solve_opf_pwl_phi(case_file_pwl, ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 42905; atol = 1e0) end @testset "5-bus with pwl psi model" begin result = solve_opf_pwl_psi(case_file_pwl, ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 42905; atol = 1e0) end end @testset "test soc pwl opf" begin @testset "5-bus with pwl delta model" begin result = solve_opf_pwl_delta(case_file_pwl, SOCWRPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 42905; atol = 1e0) end @testset "5-bus with pwl lambda model" begin result = solve_opf_pwl_lambda(case_file_pwl, SOCWRPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 42905; atol = 1e0) end @testset "5-bus with pwl phi model" begin result = solve_opf_pwl_phi(case_file_pwl, SOCWRPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 42905; atol = 1e0) end @testset "5-bus with pwl psi model" begin result = solve_opf_pwl_psi(case_file_pwl, SOCWRPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 42905; atol = 1e0) end end @testset "test dc pwl opf" begin @testset "5-bus with pwl delta model" begin result = solve_opf_pwl_delta(case_file_pwl, DCPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 42575; atol = 1e0) end @testset "5-bus with pwl lambda model" begin result = solve_opf_pwl_lambda(case_file_pwl, DCPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 42575; atol = 1e0) end @testset "5-bus with pwl phi model" begin result = solve_opf_pwl_phi(case_file_pwl, DCPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 42575; atol = 1e0) end @testset "5-bus with pwl psi model" begin result = solve_opf_pwl_psi(case_file_pwl, DCPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 42575; atol = 1e0) end end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
1156
using PowerModelsAnnex PMA = PowerModelsAnnex using JuMP using PowerModels using Ipopt using Test PowerModels.silence() pms_path = joinpath(dirname(pathof(PowerModels)), "..") # default setup for solvers ipopt_solver = JuMP.optimizer_with_attributes(Ipopt.Optimizer, "tol"=>1e-6, "print_level"=>0) # this will work because PowerModels is a dependency case_files = Dict( "case3" => "$(pms_path)/test/data/matpower/case3.m", "case5" => "$(pms_path)/test/data/matpower/case5.m", "case5_asym" => "$(pms_path)/test/data/matpower/case5_asym.m", "case5_gap" => "$(pms_path)/test/data/matpower/case5_gap.m", "case5_dc" => "$(pms_path)/test/data/matpower/case5_dc.m", "case14" => "$(pms_path)/test/data/matpower/case14.m", "case30" => "$(pms_path)/test/data/matpower/case30.m" ) case_file_pwl = "$(pms_path)/test/data/matpower/case5_pwlc.m" @testset "PowerModelsAnnex" begin include("form/acr.jl") include("form/wr.jl") include("opf.jl") include("model/pf.jl") include("model/opf.jl") include("pglib/api.jl") include("pglib/sad.jl") include("piecewise-linear.jl") end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
1048
@testset "test acr nl" begin @testset "3-bus case" begin pm = instantiate_model(case_files["case3"], NLACRPowerModel, build_opf) result = optimize_model!(pm, optimizer=ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 5907; atol = 1e0) end @testset "5-bus pjm case" begin pm = instantiate_model(case_files["case5"], NLACRPowerModel, build_opf) result = optimize_model!(pm, optimizer=ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 18269; atol = 1e0) # Increasing tolerance # here as the result seems to depend on the machine end @testset "30-bus ieee case" begin pm = instantiate_model(case_files["case30"], NLACRPowerModel, build_opf) result = optimize_model!(pm, optimizer=ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 204.9; atol = 1e0) end end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
2691
@testset "test wr oa" begin @testset "3-bus case" begin pm = instantiate_model(case_files["case3"], SOCWROAPowerModel, build_opf) p = var(pm, :p) for v in values(p) JuMP.set_start_value(v, 1.0) end q = var(pm, :q) for v in values(q) JuMP.set_start_value(v, 1.0) end result = optimize_model!(pm, optimizer=ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 5746.7; atol = 1e0) end @testset "5-bus pjm case" begin pm = instantiate_model(case_files["case5"], SOCWROAPowerModel, build_opf) p = var(pm, :p) for v in values(p) JuMP.set_start_value(v, 1.0) end q = var(pm, :q) for v in values(q) JuMP.set_start_value(v, 1.0) end result = optimize_model!(pm, optimizer=ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 14999.71; atol = 1e2) # Increasing tolerance # here as the result seems to depend on the machine end @testset "30-bus ieee case" begin pm = instantiate_model(case_files["case30"], SOCWROAPowerModel, build_opf) p = var(pm, :p) for v in values(p) JuMP.set_start_value(v, 1.0) end q = var(pm, :q) for v in values(q) JuMP.set_start_value(v, 1.0) end result = optimize_model!(pm, optimizer=ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 172.41; atol = 1e0) end end @testset "test qc tri without linking" begin @testset "3-bus case" begin pm = instantiate_model(case_files["case3"], QCLSNoLinkPowerModel, build_opf) result = optimize_model!(pm, optimizer=ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 5817.58; atol = 1e0) end @testset "5-bus pjm case" begin pm = instantiate_model(case_files["case5"], QCLSNoLinkPowerModel, build_opf) result = optimize_model!(pm, optimizer=ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 15051.6; atol = 1e2) end @testset "30-bus ieee case" begin pm = instantiate_model(case_files["case30"], QCLSNoLinkPowerModel, build_opf) result = optimize_model!(pm, optimizer=ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 173.806; atol = 1e0) end end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
7406
function solve_ac_opf_model(data, optimizer) model = build_ac_opf(data, JuMP.Model(optimizer)) JuMP.optimize!(model) return JuMP.termination_status(model), model end @testset "test ac polar opf" begin @testset "case $(name)" for (name, case_file) in case_files data = parse_file(case_file) opf_status, opf_model = solve_ac_opf_model(data, ipopt_solver) pm_result = solve_ac_opf(data, ipopt_solver) pm_sol = pm_result["solution"] @test isapprox(JuMP.objective_value(opf_model), pm_result["objective"]; atol = 1e-5) base_mva = data["baseMVA"] for (i, bus) in data["bus"] if bus["bus_type"] != 4 index = parse(Int, i) #println("$i, $(JuMP.value(opf_model[:va][index])), $(pm_sol["bus"][i]["va"])") #println("$i, $(JuMP.value(opf_model[:vm][index])), $(pm_sol["bus"][i]["vm"])") @test isapprox(JuMP.value(opf_model[:va][index]), pm_sol["bus"][i]["va"]; atol = 1e-8) @test isapprox(JuMP.value(opf_model[:vm][index]), pm_sol["bus"][i]["vm"]) end end for (i, gen) in data["gen"] if gen["gen_status"] != 0 index = parse(Int, i) #println("$i, $(JuMP.value(opf_model[:pg][index])), $(pm_sol["gen"][i]["pg"])") @test isapprox(JuMP.value(opf_model[:pg][index]), pm_sol["gen"][i]["pg"]) # multiple generators at one bus can cause this to be non-unqiue #@test isapprox(JuMP.value(opf_model[:qg][index]), pm_sol["gen"][i]["qg"]) end end end end function solve_soc_opf_model(data, optimizer) model = build_soc_opf(data, JuMP.Model(optimizer)) JuMP.optimize!(model) return JuMP.termination_status(model), model end @testset "test soc w opf" begin @testset "case $(name)" for (name, case_file) in case_files data = parse_file(case_file) opf_status, opf_model = solve_soc_opf_model(data, ipopt_solver) pm_result = solve_opf(data, SOCWRPowerModel, ipopt_solver) pm_sol = pm_result["solution"] @test isapprox(JuMP.objective_value(opf_model), pm_result["objective"]; atol = 1e-5) base_mva = data["baseMVA"] for (i, bus) in data["bus"] if bus["bus_type"] != 4 index = parse(Int, i) #println("$i, $(JuMP.value(opf_model[:va][index])), $(pm_sol["bus"][i]["va"])") #@test isapprox(JuMP.value(opf_model[:va][index]), pm_sol["bus"][i]["va"]; atol = 1e-8) #println("$i, $(JuMP.value(opf_model[:w][index])), $(pm_sol["bus"][i]["vm"]^2)") @test isapprox(JuMP.value(opf_model[:w][index]), pm_sol["bus"][i]["w"]; atol = 1e-6) end end for (i, gen) in data["gen"] if gen["gen_status"] != 0 index = parse(Int, i) #println("$i, $(JuMP.value(opf_model[:pg][index])), $(pm_sol["gen"][i]["pg"])") @test isapprox(JuMP.value(opf_model[:pg][index]), pm_sol["gen"][i]["pg"]; atol = 1e-6) # multiple generators at one bus can cause this to be non-unqiue #@test isapprox(JuMP.value(opf_model[:qg][index]), pm_sol["gen"][i]["qg"]) end end end end function solve_qc_opf_model(data, optimizer) model = build_qc_opf(data, JuMP.Model(optimizer)) JuMP.optimize!(model) return JuMP.termination_status(model), model end @testset "test qc w+l opf" begin @testset "case $(name)" for (name, case_file) in case_files data = parse_file(case_file) opf_status, opf_model = solve_qc_opf_model(data, ipopt_solver) pm_result = solve_opf(data, QCLSPowerModel, ipopt_solver) pm_sol = pm_result["solution"] @test isapprox(JuMP.objective_value(opf_model), pm_result["objective"]; atol = 1e-5) base_mva = data["baseMVA"] for (i, bus) in data["bus"] if bus["bus_type"] != 4 index = parse(Int, i) #println("$i, $(JuMP.value(opf_model[:va][index])), $(pm_sol["bus"][i]["va"])") #@test isapprox(JuMP.value(opf_model[:va][index]), pm_sol["bus"][i]["va"]; atol = 1e-8) #println("$i, $(JuMP.value(opf_model[:vm][index])), $(pm_sol["bus"][i]["vm"])") @test isapprox(JuMP.value(opf_model[:vm][index]), pm_sol["bus"][i]["vm"]; atol = 1e-5) end end for (i, gen) in data["gen"] if gen["gen_status"] != 0 index = parse(Int, i) #println("$i, $(JuMP.value(opf_model[:pg][index])), $(pm_sol["gen"][i]["pg"])") @test isapprox(JuMP.value(opf_model[:pg][index]), pm_sol["gen"][i]["pg"]; atol = 1e-5) # multiple generators at one bus can cause this to be non-unqiue #@test isapprox(JuMP.value(opf_model[:qg][index]), pm_sol["gen"][i]["qg"]) end end end end function solve_dc_opf_model(data, optimizer) model = build_dc_opf(data, JuMP.Model(optimizer)) JuMP.optimize!(model) return JuMP.termination_status(model), model end @testset "test dc polar opf" begin @testset "case $(name)" for (name, case_file) in case_files data = parse_file(case_file) opf_status, opf_model = solve_dc_opf_model(data, ipopt_solver) pm_result = solve_dc_opf(data, ipopt_solver) pm_sol = pm_result["solution"] #println(opf_status) #println(pm_result["status"]) @test isapprox(JuMP.objective_value(opf_model), pm_result["objective"]; atol = 1e-5) # needed becouse some test networks are not DC feasible if pm_result["termination_status"] == LOCALLY_SOLVED @test opf_status == LOCALLY_SOLVED base_mva = data["baseMVA"] for (i, bus) in data["bus"] if bus["bus_type"] != 4 index = parse(Int, i) #println("$i, $(JuMP.value(opf_model[:va][index])), $(pm_sol["bus"][i]["va"])") @test isapprox(JuMP.value(opf_model[:va][index]), pm_sol["bus"][i]["va"]; atol = 1e-8) end end for (i, gen) in data["gen"] if gen["gen_status"] != 0 index = parse(Int, i) #println("$i, $(JuMP.value(opf_model[:pg][index])), $(pm_sol["gen"][i]["pg"])") @test isapprox(JuMP.value(opf_model[:pg][index]), pm_sol["gen"][i]["pg"]; atol = 1e-8) end end else @test opf_status == LOCALLY_INFEASIBLE @test pm_result["status"] == LOCALLY_INFEASIBLE end end end function solve_file(file_name) include(file_name) optimizer = JuMP.optimizer_with_attributes(Ipopt.Optimizer, "print_level"=>0) return optimizer, data, termination_status(model), cost end @testset "test ac polar opf" begin optimizer, data, status, cost = solve_file("../../src/model/ac-opf.jl") pm_result = solve_ac_opf(data, optimizer) @test isapprox(cost, pm_result["objective"]; atol = 1e-6) end @testset "test dc polar opf" begin optimizer, data, status, cost = solve_file("../../src/model/dc-opf.jl") pm_result = solve_dc_opf(data, optimizer) @test isapprox(cost, pm_result["objective"]; atol = 1e-6) end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
5066
function solve_ac_pf_model(data, optimizer) model = build_ac_pf(data, JuMP.Model(optimizer)) JuMP.optimize!(model) return JuMP.termination_status(model), model end @testset "test ac polar pf" begin @testset "case $(name)" for (name, case_file) in case_files data = parse_file(case_file) pf_status, pf_model = solve_ac_pf_model(data, ipopt_solver) pm_result = solve_ac_pf(data, ipopt_solver) pm_sol = pm_result["solution"] base_mva = data["baseMVA"] for (i, bus) in data["bus"] if bus["bus_type"] != 4 index = parse(Int, i) #println("$i, $(JuMP.value(pf_model[:va][index])), $(pm_sol["bus"][i]["va"])") @test isapprox(JuMP.value(pf_model[:va][index]), pm_sol["bus"][i]["va"]; atol = 1e-6) @test isapprox(JuMP.value(pf_model[:vm][index]), pm_sol["bus"][i]["vm"]) end end for (i, gen) in data["gen"] if gen["gen_status"] != 0 index = parse(Int, i) #println("$i, $(JuMP.value(pf_model[:pg][index])), $(pm_sol["gen"][i]["pg"])") @test isapprox(JuMP.value(pf_model[:pg][index]), pm_sol["gen"][i]["pg"]; atol = 1e-6) # multiple generators at one bus can cause this to be non-unqiue #@test isapprox(JuMP.value(pf_model[:qg][index]), pm_sol["gen"][i]["qg"]) end end end end function solve_soc_pf_model(data, optimizer) model = build_soc_pf(data, JuMP.Model(optimizer)) JuMP.optimize!(model) return JuMP.termination_status(model), model end @testset "test soc w pf" begin @testset "case $(name)" for (name, case_file) in case_files if name != "case3" && name != "case5_dc" # case3 started failing 06/18/2021 with latest package version, case5_dc started working againg # case5_dc started failing 05/22/2020 when ipopt moved to jll artifacts data = parse_file(case_file) pf_status, pf_model = solve_soc_pf_model(data, ipopt_solver) pm_result = solve_pf(data, SOCWRPowerModel, ipopt_solver) pm_sol = pm_result["solution"] #println(pf_status) #println(pm_result["status"]) base_mva = data["baseMVA"] for (i, bus) in data["bus"] if bus["bus_type"] != 4 index = parse(Int, i) #println("$i, $(JuMP.value(pf_model[:va][index])), $(pm_sol["bus"][i]["va"])") #@test isapprox(JuMP.value(pf_model[:va][index]), pm_sol["bus"][i]["va"]; atol = 1e-8) #println("$i, $(JuMP.value(pf_model[:w][index])), $(pm_sol["bus"][i]["vm"]^2)") @test isapprox(JuMP.value(pf_model[:w][index]), pm_sol["bus"][i]["w"]; atol = 1e-3) end end for (i, gen) in data["gen"] if gen["gen_status"] != 0 index = parse(Int, i) #println("$i, $(JuMP.value(pf_model[:pg][index])), $(pm_sol["gen"][i]["pg"])") @test isapprox(JuMP.value(pf_model[:pg][index]), pm_sol["gen"][i]["pg"]; atol = 1e-1) # multiple generators at one bus can cause this to be non-unqiue #@test isapprox(JuMP.value(pf_model[:qg][index]), pm_sol["gen"][i]["qg"]) end end end end end function solve_dc_pf_model(data, optimizer) model = build_dc_pf(data, JuMP.Model(optimizer)) JuMP.optimize!(model) return JuMP.termination_status(model), model end @testset "test dc polar pf" begin @testset "case $(name)" for (name, case_file) in case_files data = parse_file(case_file) pf_status, pf_model = solve_dc_pf_model(data, ipopt_solver) pm_result = solve_dc_pf(data, ipopt_solver) pm_sol = pm_result["solution"] #println(pf_status) #println(pm_result["status"]) # needed becouse some test networks are not DC feasible if pm_result["termination_status"] == LOCALLY_SOLVED @test pf_status == LOCALLY_SOLVED base_mva = data["baseMVA"] for (i, bus) in data["bus"] if bus["bus_type"] != 4 index = parse(Int, i) #println("$i, $(JuMP.value(pf_model[:va][index])), $(pm_sol["bus"][i]["va"])") @test isapprox(JuMP.value(pf_model[:va][index]), pm_sol["bus"][i]["va"]; atol = 1e-8) end end for (i, gen) in data["gen"] if gen["gen_status"] != 0 index = parse(Int, i) #println("$i, $(JuMP.value(pf_model[:pg][index])), $(pm_sol["gen"][i]["pg"])") @test isapprox(JuMP.value(pf_model[:pg][index]), pm_sol["gen"][i]["pg"]) end end else @test pf_status == LOCALLY_INFEASIBLE @test pm_result["status"] == LOCALLY_INFEASIBLE end end end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
1780
@testset "test ac api" begin @testset "3-bus case" begin result = solve_opf_api(case_files["case3"], ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 400.94; atol = 1e0) @test isapprox(result["solution"]["load"]["1"]["pd"], 1.471; atol = 1e-2) @test isapprox(result["solution"]["load"]["1"]["qd"], 0.4; atol = 1e-2) end # started failing 05/22/2020 when ipopt moved to jll artifacts # @testset "5-bus pjm case" begin # result = solve_opf_api(case_files["case5"], ACPPowerModel, ipopt_solver) # @test result["termination_status"] == LOCALLY_SOLVED # @test isapprox(result["objective"], 2.6872; atol = 1e-3) # @test isapprox(result["solution"]["load"]["3"]["pd"], 10.754; atol = 1e-2) # @test isapprox(result["solution"]["load"]["3"]["qd"], 1.3147; atol = 1e-2) # end @testset "14-bus ieee case" begin result = solve_opf_api(case_files["case14"], ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 1993.39; atol = 1e0) @test isapprox(result["solution"]["load"]["1"]["pd"], 0.8653; atol = 1e-2) @test isapprox(result["solution"]["load"]["1"]["qd"], 0.127; atol = 1e-2) end @testset "30-bus ieee case" begin result = solve_opf_api(case_files["case30"], ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 994.13; atol = 1e0) @test isapprox(result["solution"]["load"]["1"]["pd"], 0.361; atol = 1e-2) @test isapprox(result["solution"]["load"]["1"]["qd"], 0.127; atol = 1e-2) end end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
code
1047
@testset "test ac sad" begin @testset "3-bus case" begin result = solve_opf_sad(case_files["case3"], ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 0.3114; atol = 1e-2) end @testset "5-bus pjm case" begin result = solve_opf_sad(case_files["case5"], ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 0.02211; atol = 1e-2) end @testset "14-bus ieee case" begin result = solve_opf_sad(case_files["case14"], ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 0.033097; atol = 1e-2) end @testset "30-bus ieee case" begin result = solve_opf_sad(case_files["case30"], ACPPowerModel, ipopt_solver) @test result["termination_status"] == LOCALLY_SOLVED @test isapprox(result["objective"], 0.1522; atol = 1e-2) end end
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
docs
2246
PowerModelsAnnex.jl Change Log ============================== ### Staged - nothing ### v0.11.0 - Update to PowerModels v0.21 and JuMP's new nonlinear interface (breaking) ### v0.10.0 - Update PowerModels v0.20 - Drop `frontend` directory, lack of maintenance on dependent packages - Drop `islanding` directory, no tests ### v0.9.0 - Revise `solve_opf_api` to consider reactive power dispatch ### v0.8.5 - Add closest operating point formulation `solve_opf_cop` ### v0.8.4 - Update PowerModels `run_*` functions to `solve_*` - Add support for Memento v1.4 ### v0.8.3 - Add support for JuMP v1.0 ### v0.8.2 - Add support for JuMP v0.23 - Update minimum Julia version to v1.6 (LTS) ### v0.8.1 - Add support for Memento v1.3 ### v0.8.0 - Update to JuMP v0.22, PowerModels v0.19 - Drop support for JuMP v0.21 - Remove dependency on MathOptInterface package ### v0.7.1 - Add support for Memento v1.2 - Update use of `with_optimizer` to `optimizer_with_attributes` ### v0.7.0 - Update to InfrastructureModels v0.6 and PowerModels v0.18 ### v0.6.1 - Add variants of piecewise linear cost model formulations - Update to DataFrames v0.21 ### v0.6.0 - Update to PowerModels v0.17 - Added support for Memento v1.1 ### v0.5.0 - Update to PowerModels v0.16 ### v0.4.4 - Fixed solution reporting bug in api model ### v0.4.3 - Update pacakge internal short names to `_PM` and `_IM` - Add support for optional branch power flows in api and sad models ### v0.4.2 - Add support for Memento v0.13, v1.0 ### v0.4.1 - Add support for JuMP v0.21 - Drop Manifest.toml (#57) ### v0.4.0 - Update to PowerModels v0.15 ### v0.3.1 - Update to InfrastructureModels v0.4 ### v0.3.0 - Update to PowerModels v0.14 and new naming conventions (#65) ### v0.2.6 - Updates for PowerModels v0.13 ### v0.2.5 - Updates to frontend for MOI status values (#60) ### v0.2.4 - Updates for JuMP v0.20 and Julia v1.2 (#59) - Resolve Dataframes deprecations (#58) ### v0.2.3 - Updates for PowerSystemsUnits - Fixes for Frontend (#53) ### v0.2.2 - Update to PowerModels v0.12 ### v0.2.1 - Update to PowerModels v0.11 ### v0.2.0 - Update to JuMP v0.19/MathOptInterface ### v0.1.12 - Dropped support for Julia v0.6/v0.7 ### Previous - See Github releases for details
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
docs
2281
Copyright (c) 2016, Los Alamos National Security, LLC All rights reserved. Copyright 2016. Los Alamos National Security, LLC. This software was produced under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National Laboratory (LANL), which is operated by Los Alamos National Security, LLC for the U.S. Department of Energy. The U.S. Government has rights to use, reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified to produce derivative works, such modified software should be clearly marked, so as not to confuse it with the version available from LANL. Additionally, redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Los Alamos National Security, LLC, Los Alamos National Laboratory, LANL, the U.S. Government, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY LOS ALAMOS NATIONAL SECURITY, LLC AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LOS ALAMOS NATIONAL SECURITY, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
docs
1420
# PowerModelsAnnex.jl Dev: [![CI](https://github.com/lanl-ansi/PowerModelsAnnex.jl/workflows/CI/badge.svg)](https://github.com/lanl-ansi/PowerModelsAnnex.jl/actions/workflows/ci.yml) [![codecov](https://codecov.io/gh/lanl-ansi/PowerModelsAnnex.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/lanl-ansi/PowerModelsAnnex.jl) [PowerModels.jl](https://github.com/lanl-ansi/PowerModels.jl) provides an implementation reference for *established* formulations and methods in power system optimization, and hence is is not an appropriate location for more exploratory work. PowerModelsAnnex.jl is an extension of PowerModels.jl that provides a home for open-source sharing of preliminary and/or exploratory methods in power system optimization. Due to the exploratory nature of PowerModelsAnnex, - there is minimal documentation and testing - there are limited code quality and reliablity standards - anything goes in the annex, more-or-less Users should be prepared for features that break. Pull Requests to PowerModelsAnnex are always welcome and not subject to significant scrutiny. ## Acknowledgments This code has been developed as part of the Advanced Network Science Initiative at Los Alamos National Laboratory. The primary developer is Carleton Coffrin. ## License This code is provided under a BSD license as part of the Multi-Infrastructure Control and Optimization Toolkit (MICOT) project, C15024.
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
docs
1882
# PowerModelsAnnex JuMP Models ## Motivation Integrating novel power model formulations in to PowerModels.jl can be time consuming and requires significant understanding of the PowerModels software design. Consequently PowerModels.jl is not ideal for rapid prototyping of novel problem formulations. To address this issue the files provided in this directory defined functions that build JuMP models from scratch, which are identical to those produced by PowerModels.jl, for a few of the most common formulations. These functions leverage the data processing tools in PowerModels.jl and conform to the same naming conventions. Unit tests are used to ensure that the solutions produced by these from-scratch models match those of PowerModels.jl. ## Usage The functions provided here designed to setup a JuMP model. Notably, they are not concerned with reading data files, solving the model, or reporting the solution. These tasks are left to the user. For example, a simple AC OPF work flow would be as follows, ``` using PowerModelsAnnex using PowerModels using JuMP using Ipopt model = Model(Ipopt.Optimizer) data = PowerModels.parse_file("case3.m") build_ac_opf(data, model) optimize!(model) ``` Once the model is solved the solution can be extracted as follows, ``` for (i, bus) in data["bus"] if bus["bus_type"] != 4 println("$i, $(value(model[:t][bus["index"]])), $(value(model[:v][bus["index"]]))") end end for (i, gen) in data["gen"] if gen["gen_status"] != 0 println("$i, $(value(model[:pg][gen["index"]])), $(value(model[:qg][gen["index"]]))") end end ``` Note that all values are given in per unit and radians, as this is the internal PowerModels data format. For additional examples of how to use these functions see the files in `PowerModelsAnnex.jl/test/model`.
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "BSD-3-Clause" ]
0.11.0
9586539805324e50536586e2df1d8e26b87f9fb7
docs
188
# PowerModelsAnnex PGLib This directory includes model formulations are are used to develop AC-OPF test cases for [PGLib Optimal Power Flow](https://github.com/power-grid-lib/pglib-opf).
PowerModelsAnnex
https://github.com/lanl-ansi/PowerModelsAnnex.jl.git
[ "MIT" ]
0.6.1
51f56372090c3af1ce784610c5cf3c4c224563e4
code
394
using Documenter, FDM makedocs( modules=[FDM], format=:html, pages=[ "Home" => "index.md", "API" => "pages/api.md" ], sitename="FDM.jl", authors="Invenia Labs", assets=[ "assets/invenia.css", ], ) deploydocs( repo = "github.com/invenia/FDM.jl.git", julia = "1.0", target = "build", deps = nothing, make = nothing, )
FDM
https://github.com/invenia/FDM.jl.git
[ "MIT" ]
0.6.1
51f56372090c3af1ce784610c5cf3c4c224563e4
code
156
module FDM using Printf, LinearAlgebra const AV = AbstractVector include("methods.jl") include("numerics.jl") include("grad.jl") end
FDM
https://github.com/invenia/FDM.jl.git