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.2.1
c591452c432a6c1d37930a3b36ef1f619eada3fa
code
683
using PlotIter using Documenter DocMeta.setdocmeta!(PlotIter, :DocTestSetup, :(using PlotIter); recursive=true) makedocs(; modules=[PlotIter], authors="Tom Gillam <[email protected]>", repo="https://github.com/tpgillam/PlotIter.jl/blob/{commit}{path}#{line}", sitename="PlotIter.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://tpgillam.github.io/PlotIter.jl", edit_link="main", assets=String[], ), pages=[ "Home" => "index.md", ], checkdocs=:exports, strict=true, ) deploydocs(; repo="github.com/tpgillam/PlotIter.jl", devbranch="main", )
PlotIter
https://github.com/tpgillam/PlotIter.jl.git
[ "MIT" ]
0.2.1
c591452c432a6c1d37930a3b36ef1f619eada3fa
code
8434
module PlotIter export xlims_convex_hull!, ylims_convex_hull!, zlims_convex_hull!, clims_convex_hull! export NoDisplay, DisplayEachRow, DisplayAtEnd export plot_iter using Plots # Functions for accessing and modifying colour limits. # Possibly these could belong inside Plots.jl clims(sp::Plots.Subplot) = Plots.get_clims(sp) clims(p::Plots.Plot, sp_idx::Int=1) = clims(p[sp_idx]) function clims!(p::Plots.Subplot, lims::Tuple{Float64,Float64}) p.attr[:clims_calculated] = lims return p end clims!(p::Plots.Subplot, cmin::Real, cmax::Real) = clims!(p, Float64.((cmin, cmax))) function clims!(p::Plots.Plot, cmin::Real, cmax::Real) foreach(1:length(p)) do sp_idx sp = p[sp_idx] clims!(sp, cmin, cmax) end end for dim in (:x, :y, :z, :c) dim_str = string(dim) func! = Symbol(dim, "lims_convex_hull!") lims = Symbol(dim, "lims") lims! = Symbol(dim, "lims!") @eval begin """ $($func!)(plots) $($func!)(plots...) Set the $($dim_str)-axis limits for all `plots` to the smallest interval that contains all the existing $($dim_str)-axis limits. If the arguments are `Subplot`s, then there is no ambiguity over the limits of a given argument. However, if they are `Plot`s, then we do the following: * Let `n` be the minimum number of subplots across all arguments. * For `i` in `1:n`, apply $($func!) to the all of the `i`th subplots. This is useful to ensure that two plots are visually comparable. """ function $func!( plots::Union{Tuple{Vararg{Plots.Subplot}},AbstractVector{<:Plots.Subplot}} ) isempty(plots) && throw(ArgumentError("Need at least one plot.")) x_min, x_max = $lims(first(plots)) for p in plots[2:end] this_x_min, this_x_max = $lims(p) x_min = min(x_min, this_x_min) x_max = max(x_max, this_x_max) end for p in plots $lims!(p, x_min, x_max) end return nothing end $func!(plots::Plots.Subplot...) = $func!(plots) function $func!( plots::Union{Tuple{Vararg{AbstractPlot}},AbstractVector{<:AbstractPlot}} ) isempty(plots) && throw(ArgumentError("Need at least one plot.")) # Determine the number of subplots for which we can apply convex hull behaviour. n = minimum( map(plots) do p length(p.subplots) end, ) # Apply convex hull logic. for i in 1:n $func!( map(plots) do p p.subplots[i] end, ) end end $func!(plots::Plots.AbstractPlot...) = $func!(plots) end end _blank_plot() = plot(; legend=false, grid=false, foreground_color_subplot=:white) function _display_row(plots, num_cols::Integer, row_size) # Pad with a "blank" subplot for any missing entries. plots = vcat(plots, [_blank_plot() for _ in 1:(num_cols - length(plots))]) p = plot(plots...; layout=(1, length(plots)), size=row_size) return display(p) end abstract type DisplayMode end """ struct NoDisplay <: DisplayMode Don't show any plots. """ struct NoDisplay <: DisplayMode end """ struct DisplayEachRow <: DisplayMode Show a row of plots as soon as it is complete. """ struct DisplayEachRow <: DisplayMode end """ struct DisplayAtEnd <: DisplayMode Wait until the iterable is exhausted, and then show all rows of plots. """ struct DisplayAtEnd <: DisplayMode end """ plot_iter(f::Function, iterable; kwargs...) Generate one plot per item of `iterable`. This function will call `f` for each item in `iterable`, with a new plot set as `Plots.current()`. It is optimised for use within a Jupyter notebook. It will let you quickly generate a number of plots, making use of the available page width. The plots are then close together, so easier to compare visually. This function avoids the need to manually construct a layout for this simple case. # Arguments - `f::Function`: A function that takes a single argument of type `eltype(iterable)`. Any return value is ignored. - `iterable`: Any iterable object. # Keyword arguments - `num_cols::Integer=3`: The number of of plots to put side-by-side. - `row_width=900`: The width of each row (that is for _all_ plots in the row) - `row_height=300`: The vertical extent of each plot. - `display_mode::DisplayMode=DisplayAtEnd()`: An instance of: - [`NoDisplay`](@ref): Don't `show` the plots. - [`DisplayEachRow`](@ref): Every time a row of plots is complete, `show` it. - [`DisplayAtEnd`](@ref): Wait until all plots are generated, and then show all at once. - `xlims_convex_hull::Bool=false`: Iff true, call [`xlims_convex_hull!`](@ref) on all plots. This requires the `display_mode` to be [`NoDisplay`](@ref) or [`DisplayAtEnd`](@ref). - `ylims_convex_hull::Bool=false`: Iff true, call [`ylims_convex_hull!`](@ref) on all plots. This requires the `display_mode` to be [`NoDisplay`](@ref) or [`DisplayAtEnd`](@ref). - `zlims_convex_hull::Bool=false`: Iff true, call [`zlims_convex_hull!`](@ref) on all plots. This requires the `display_mode` to be [`NoDisplay`](@ref) or [`DisplayAtEnd`](@ref). - `clims_convex_hull::Bool=false`: Iff true, call [`clims_convex_hull!`](@ref) on all plots. This requires the `display_mode` to be [`NoDisplay`](@ref) or [`DisplayAtEnd`](@ref). - `kwargs...`: Any other keyword arguments specified will be forwarded to an initial call to `plot`. # Returns A vector of all plots that have been generated. # Example Here is the simplest use, with no configuration: ```julia plot_iter(1:3) do i # Note: call to `plot!` rather than `plot` is important, since a new plot object has # already been created by `plot_iter`. plot!(i .* rand(30)) end; ``` We can also change the sizes, as well as make the y-axis limits match: ```julia plot_iter(1:3; num_cols=2, row_height=500, ylims_convex_hull=true) do i plot!(i .* rand(30)) end; ``` """ function plot_iter( f::Function, @nospecialize(iterable); num_cols::Integer=3, row_width=900, row_height=300, display_mode::DisplayMode=DisplayAtEnd(), xlims_convex_hull::Bool=false, ylims_convex_hull::Bool=false, zlims_convex_hull::Bool=false, clims_convex_hull::Bool=false, kwargs..., ) row_size = (row_width, row_height) if (xlims_convex_hull || ylims_convex_hull || zlims_convex_hull || clims_convex_hull) # If using any arguments that require all plots to have been generated prior to # displaying, ensure that our displaymode is correct. if !isa(display_mode, Union{NoDisplay,DisplayAtEnd}) throw( ArgumentError( "Invalid display mode $display_mode, since we need all plots first." ), ) end end # A vector of all subplots that we generate; we will return this. all_plots = AbstractPlot[] # A temporary store of plots prior to displaying. current_plots = AbstractPlot[] function flush_plots!() @assert length(current_plots) <= num_cols # Record the generated subplots. append!(all_plots, current_plots) isa(display_mode, DisplayEachRow) && _display_row(current_plots, num_cols, row_size) return empty!(current_plots) end for item in iterable # If buffer is full, pack into a single row. (length(current_plots) == num_cols) && flush_plots!() # Create a new plot on the stack, and call our function with the item. p = plot(; kwargs...) f(item) push!(current_plots, p) end # Ensure that we always empty the buffer flush_plots!() # Now rescale any axes which we need to. xlims_convex_hull && xlims_convex_hull!(all_plots) ylims_convex_hull && ylims_convex_hull!(all_plots) zlims_convex_hull && zlims_convex_hull!(all_plots) clims_convex_hull && clims_convex_hull!(all_plots) if isa(display_mode, DisplayAtEnd) for row_plots in Iterators.partition(all_plots, num_cols) _display_row(row_plots, num_cols, row_size) end end return all_plots end end
PlotIter
https://github.com/tpgillam/PlotIter.jl.git
[ "MIT" ]
0.2.1
c591452c432a6c1d37930a3b36ef1f619eada3fa
code
5565
using PlotIter using Plots using Test gr() function _test_lims_cover_range(lims::Tuple, range) @test first(range) - 1 <= first(lims) <= first(range) @test last(range) <= last(lims) <= last(range) + 1 end function _test_lims_in_range(lims::Tuple, range) @test first(range) <= first(lims) @test last(lims) <= last(range) end _allequal(things) = all(isequal(first(things)), things) @testset "PlotIter.jl" begin @testset "xyzlims_convex_hull!" begin range1 = 1:10 p1 = plot(range1, range1, range1) _test_lims_cover_range(xlims(p1), range1) _test_lims_cover_range(ylims(p1), range1) range2 = 3:15 p2 = plot(range2, range2, range2) _test_lims_cover_range(xlims(p2), range2) _test_lims_cover_range(ylims(p2), range2) # Modify the plots to share the same x limits. xlims_convex_hull!(p1, p2) lims1 = xlims(p1) lims2 = xlims(p2) @test lims1 == lims2 _test_lims_cover_range(lims1, 1:15) # At this point, the y and z limits should not have been touched. _test_lims_cover_range(ylims(p1), range1) _test_lims_cover_range(ylims(p2), range2) _test_lims_cover_range(zlims(p1), range1) _test_lims_cover_range(zlims(p2), range2) # Modify the plots to share the same y limits. ylims_convex_hull!(p1, p2) @test xlims(p1) == xlims(p2) lims1 = ylims(p1) lims2 = ylims(p2) @test lims1 == lims2 _test_lims_cover_range(lims1, 1:15) _test_lims_cover_range(zlims(p1), range1) _test_lims_cover_range(zlims(p2), range2) # And finally to show the same z limits. zlims_convex_hull!(p1, p2) @test xlims(p1) == xlims(p2) @test ylims(p1) == ylims(p2) lims1 = zlims(p1) lims2 = zlims(p2) @test lims1 == lims2 _test_lims_cover_range(lims1, 1:15) end @testset "ylims_convex_hull_twinx" begin # Ensure that we correctly scale each y-axis separately when we have a secondary # axis created with twinx. range1 = 1:10 range2 = 3:15 range3 = 4:19 range4 = 10:25 p1 = plot(range1, range1) plot!(twinx(p1), range2, range2) @test length(p1.subplots) == 2 _test_lims_cover_range(ylims(p1.subplots[1]), range1) _test_lims_cover_range(ylims(p1.subplots[2]), range2) p2 = plot(range3, range3) plot!(twinx(p2), range4, range4) @test length(p2.subplots) == 2 _test_lims_cover_range(ylims(p2.subplots[1]), range3) _test_lims_cover_range(ylims(p2.subplots[2]), range4) ylims_convex_hull!(p1, p2) @test ylims(p1.subplots[1]) == ylims(p2.subplots[1]) @test ylims(p1.subplots[2]) == ylims(p2.subplots[2]) _test_lims_cover_range(ylims(p1.subplots[1]), 1:19) _test_lims_cover_range(ylims(p1.subplots[2]), 3:25) end @testset "clims_convex_hull!" begin hm1 = heatmap(10 .* rand(5, 5)) hm2 = heatmap(3 .+ 12 .* rand(5, 5)) plot(hm1, hm2) _test_lims_in_range(PlotIter.clims(hm1), (0, 10)) _test_lims_in_range(PlotIter.clims(hm2), (3, 15)) clims_convex_hull!(hm1, hm2) lims1 = PlotIter.clims(hm1) lims2 = PlotIter.clims(hm2) @test lims1 == lims2 _test_lims_in_range(lims1, (0, 15)) end @testset "plot_iter" begin x = 1.0:0.01:(4 * pi) things = [ (; title="A", w=1), (; title="B", w=2), (; title="C", w=3), (; title="D", w=4), (; title="E", w=5), ] for (xch, ych, zch, cch) in Iterators.product(Iterators.repeated([false, true], 4)...) for num_cols in 1:4 for (row_width, row_height) in [(800, 300), (400, 100)] # Suppress visual output of any plots when calling `show` internally. all_plots = withenv("GKSwstype" => "nul") do plot_iter( things; num_cols=num_cols, row_width=row_width, row_height=row_height, xlims_convex_hull=xch, ylims_convex_hull=ych, zlims_convex_hull=zch, clims_convex_hull=cch, ) do thing plot!(x .+ thing.w, sin.(x) .* thing.w; title=thing.title) end end # We have access to all the plots that were made, so can check those. @test all_plots isa Vector{<:AbstractPlot} @test length(all_plots) == length(things) xch && @test _allequal(xlims.(all_plots)) ych && @test _allequal(ylims.(all_plots)) zch && @test _allequal(zlims.(all_plots)) cch && @test _allequal(PlotIter.clims.(all_plots)) # We can also verify some properties about the rows emitted, since the # last row will still be the "current" plot. last_row = Plots.current() @test length(last_row) == num_cols # Test row width and height match expectation. @test last_row.attr[:size] == (row_width, row_height) end end end end end
PlotIter
https://github.com/tpgillam/PlotIter.jl.git
[ "MIT" ]
0.2.1
c591452c432a6c1d37930a3b36ef1f619eada3fa
docs
1939
# PlotIter [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://tpgillam.github.io/PlotIter.jl/stable/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://tpgillam.github.io/PlotIter.jl/dev/) [![Build Status](https://github.com/tpgillam/PlotIter.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/tpgillam/PlotIter.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/tpgillam/PlotIter.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/tpgillam/PlotIter.jl) [![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle) [![ColPrac: Contributor's Guide on Collaborative Practices for Community Packages](https://img.shields.io/badge/ColPrac-Contributor's%20Guide-blueviolet)](https://github.com/SciML/ColPrac) You're in a Jupyter notebook, and have some `things`. You would like to make a plot based on each `thing`: ```julia using PlotIter using Plots # Example data x = 1.0:0.01:4*pi things = [ (; title="A", w=1), (; title="B", w=2), (; title="C", w=3), (; title="D", w=4), (; title="E", w=5), ]; # Make some plots! plot_iter(things; ylims_convex_hull=true) do thing plot!(x, sin.(x) .* thing.w; title=thing.title) end; ``` ![Example](/docs/src/assets/example_sin.png) Maybe you would like to ensure color scales match in all of them too: ```julia plot_iter( things; row_height=200, xlims_convex_hull=true, ylims_convex_hull=true, clims_convex_hull=true, ) do thing n = 10^(1 + thing.w) x = randn(Float64, n) y = randn(Float64, n) histogram2d!(x .* thing.w, y; title=thing.title, colorbar_scale=:log10) end; ``` ![Example](/docs/src/assets/example_dist.png) For further usage information, please refer to the [documentation](https://tpgillam.github.io/PlotIter.jl/stable/), and the [example notebook](/examples/example.ipynb).
PlotIter
https://github.com/tpgillam/PlotIter.jl.git
[ "MIT" ]
0.2.1
c591452c432a6c1d37930a3b36ef1f619eada3fa
docs
521
# PlotIter API documentation for [PlotIter](https://github.com/tpgillam/PlotIter.jl). For usage examples, please see the [example notebook](https://github.com/tpgillam/PlotIter.jl/blob/main/examples/example.ipynb). ## Plotting things from an iterable ```@docs plot_iter NoDisplay DisplayEachRow DisplayAtEnd ``` ## Axis limits These functions are used internally by [`plot_iter`](@ref), but they can also be useful standalone. ```@docs xlims_convex_hull! ylims_convex_hull! zlims_convex_hull! clims_convex_hull! ```
PlotIter
https://github.com/tpgillam/PlotIter.jl.git
[ "MIT" ]
0.1.2
ebec03e6aa53431851721ba9a69a5917ca10f646
code
589
using YaoQX using Documenter DocMeta.setdocmeta!(YaoQX, :DocTestSetup, :(using YaoQX); recursive=true) makedocs(; modules=[YaoQX], authors="Roger-Luo <[email protected]> and contributors", repo="https://github.com/Roger-luo/YaoQX.jl/blob/{commit}{path}#{line}", sitename="YaoQX.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://Roger-luo.github.io/YaoQX.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/Roger-luo/YaoQX.jl", )
YaoQX
https://github.com/JuliaQX/YaoQX.jl.git
[ "MIT" ]
0.1.2
ebec03e6aa53431851721ba9a69a5917ca10f646
code
256
# # Simple example demonstring use a Yao circuit with QX framework # using YaoQX # create a YaoBlocks circuit circ = ghz(3) # create a quantum register and apply the circuit reg = QXReg(3) apply!(reg, circ) # get 10 measurements measure(reg; nshots=10)
YaoQX
https://github.com/JuliaQX/YaoQX.jl.git
[ "MIT" ]
0.1.2
ebec03e6aa53431851721ba9a69a5917ca10f646
code
56
module YaoQX using YaoAPI include("register.jl") end
YaoQX
https://github.com/JuliaQX/YaoQX.jl.git
[ "MIT" ]
0.1.2
ebec03e6aa53431851721ba9a69a5917ca10f646
code
4433
using QXTns using QXTools using QXContexts using YaoBlocks using Reexport @reexport using YaoAPI export QXReg, ghz, qx_intrinsic_nodes """Register for QX""" mutable struct QXReg{B} <: AbstractRegister{B} qubits::Int tnc::TensorNetworkCircuit cg::ComputeGraph QXReg(n, tnc) = new{1}(n, tnc) end function QXReg(n::Int) tnc = TensorNetworkCircuit(n) QXReg(n, tnc) end """ YaoAPI.apply!(reg::QXReg, block::AbstractBlock) Apply the given block to the register """ function YaoAPI.apply!(reg::QXReg, block::AbstractBlock) for (locs, matrix) in qx_intrinsic_nodes(block) push!(reg.tnc, collect(locs), Matrix(matrix)) end return reg end YaoAPI.nactive(reg::QXReg) = reg.qubits YaoAPI.nqubits(reg::QXReg) = reg.qubits """Prepare a ghz circuit block""" function ghz(n) chain(put(1=>H), chain(map(x -> control(n, x, x+1=>X), 1:n-1)...)) end qx_intrinsic_nodes(blk::AbstractBlock) = qx_intrinsic_nodes!([], blk) function qx_intrinsic_nodes!(list, blk::AbstractBlock) for each in subblocks(blk) if each isa ControlBlock && length(each.ctrl_locs) < 2 && length(each.locs) == 1 if each.ctrl_locs[1] < each.locs[1] gate = control(2, 1, 2=>each.content) else gate = control(2, 2, 1=>each.content) end push!(list, occupied_locs(each) => mat(gate)) elseif each isa PutBlock push!(list, occupied_locs(each)=>mat(first(subblocks(each)))) elseif each isa PrimitiveBlock push!(list, 1=>mat(each)) else qx_intrinsic_nodes!(list, each) end end return list end find_primitive_blocks(blk::AbstractBlock) = find_primitive_blocks!([], blk) function find_primitive_blocks!(list, blk::AbstractBlock) for each in subblocks(blk) if each isa PrimitiveBlock push!(list, each) else find_primitive_blocks!(list, each) end end return list end """ YaoAPI.measure(reg::QXReg; nshots=10) Measure the register and return the measurements. Note that currently this returns an array of bitstrings and an array of corresponsing amplitudes. This should be replaced by a rejection sampler which should be able to return measurements distributed according to the expected output distribution. """ function YaoAPI.measure(reg::QXReg; nshots=10) if !isdefined(reg, :cg) add_input!(reg.tnc, "0"^nqubits(reg)) add_output!(reg.tnc, "0"^nqubits(reg)) # must be outputs on network currently to find a plan bond_groups, plan, _ = contraction_scheme(reg.tnc.tn, 2; seed=rand(Int), time=10) reg.cg = build_compute_graph(reg.tnc, plan, bond_groups) end ctx = QXContext(reg.cg) sampler_params = Dict(:method => "List", :params => Dict(:num_samples => nshots, :bitstrings => collect(amplitudes_uniform(nqubits(reg), nothing, nshots)))) sampler = ListSampler(ctx; sampler_params[:params]...) sampler() end """ QXTools._convert_to_tnc(block::AbstractBlock; kwargs...) Convert the given YaoBlocks circuit to a TensorNetworkCircuit """ function QXTools._convert_to_tnc(block::AbstractBlock; kwargs...) tnc = TensorNetworkCircuit(nqubits(block)) for (locs, matrix) in qx_intrinsic_nodes(block) push!(tnc, collect(locs), Matrix(matrix); kwargs...) end return tnc end """ QXTools.convert_to_tnc(circ::AbstractBlock; input::Union{String, Nothing}=nothing, output::Union{String, Nothing}=nothing, no_input::Bool=false, no_output::Bool=false, kwargs...) Function to convert a YaoBlocks circuit to a QXTools tensor network circuit """ function QXTools.convert_to_tnc(circ::AbstractBlock; input::Union{String, Nothing}=nothing, output::Union{String, Nothing}=nothing, no_input::Bool=false, no_output::Bool=false, kwargs...) tnc = QXTools._convert_to_tnc(circ; kwargs...) if !no_input add_input!(tnc, input) end if !no_output add_output!(tnc, output) end tnc end
YaoQX
https://github.com/JuliaQX/YaoQX.jl.git
[ "MIT" ]
0.1.2
ebec03e6aa53431851721ba9a69a5917ca10f646
code
117
using YaoQX using Test using TestSetExtensions @testset ExtendedTestSet "YaoQX.jl" begin @includetests ARGS end
YaoQX
https://github.com/JuliaQX/YaoQX.jl.git
[ "MIT" ]
0.1.2
ebec03e6aa53431851721ba9a69a5917ca10f646
code
437
using Test using YaoQX using QXTools @testset "Test register data structure" begin circ = YaoQX.ghz(3) reg = QXReg(3) apply!(reg, circ) @test length(reg.tnc) == 5 @test length.(measure(reg, nshots=10)) == (10, 10) end @testset "Test convert to tnc" begin circ = YaoQX.ghz(3) tnc = convert_to_tnc(circ) @test tnc.qubits == 3 # tnc has 5 gates and 6 input/output nodes @test length(tnc) == 11 end
YaoQX
https://github.com/JuliaQX/YaoQX.jl.git
[ "MIT" ]
0.1.2
ebec03e6aa53431851721ba9a69a5917ca10f646
docs
1133
# YaoQX ## Installation YaoQX is not yet registered so to install will need to provide full github path. ``` ] add YaoQX ``` ## Usage The following shows a very simple usage of YaoQX ``` using YaoQX # create a YaoBlocks circuit circ = ghz(3) # create a quantum register and apply the circuit reg = QXReg(3) apply!(reg, circ) # get 10 measurements measure(reg; nshots=10) ``` In this example a circuit of type `YaoBlocks` is created. This is applied to a quantum register. A measurement is then performed which returns 10 bitstrings and corresponding amplitudes. Note that the bistrings returned are currently not distributed according to the output distribution, but instead of just uniformly sampled. This will be addressed in future updates when more advanced sampling methods are added to JuliaQX. YaoQX can also be used to convert `YaoBlocks` circuits to a TensorNetworkCircuit struct that can then be used with the [QXTools](https://github.com/JuliaQX/QXTools.jl) framework. ``` using YaoQX using QXTools # create a YaoBlocks circuit circ = ghz(3) # convert to a TensorNetworkCircuit tnc = convert_to_tnc(circ) ```
YaoQX
https://github.com/JuliaQX/YaoQX.jl.git
[ "MIT" ]
0.1.2
ebec03e6aa53431851721ba9a69a5917ca10f646
docs
95
```@meta CurrentModule = YaoQX ``` # YaoQX ```@index ``` ```@autodocs Modules = [YaoQX] ```
YaoQX
https://github.com/JuliaQX/YaoQX.jl.git
[ "MIT" ]
0.1.0
211e0268094aa69b9bc0c58b15a2be7900343e98
code
470
using Documenter, Twitch makedocs(; modules = [Twitch], authors = "Johannes Schumann", format = Documenter.HTML( prettyurls = get(ENV, "CI", nothing) == "true", assets = ["assets/logo.ico"], ), pages=[ "Introduction" => "index.md", # "API" => "api.md", ], repo="https://github.com/8me/Twitch.jl/blob/{commit}{path}#L{line}", sitename="Twitch.jl", ) deploydocs(; repo="github.com/8me/Twitch.jl", )
Twitch
https://github.com/8me/Twitch.jl.git
[ "MIT" ]
0.1.0
211e0268094aa69b9bc0c58b15a2be7900343e98
code
869
#!/usr/bin/env julia using Twitch function main() server_addr = "irc.chat.twitch.tv" server_port = 6667 usernick = "justinfan1234" oauth = "kappa" c = Condition() message_queue = Channel{AbstractString}(10000) t = @task ChatCount.chatreceiver( server_addr, server_port, usernick, oauth, c, "twitch", message_queue ) schedule(t) while true while isready(message_queue) resp = take!(message_queue) data = response(resp) # ... do something end sleep(1) end schedule(t, InterruptExeception(), error=true) end main()
Twitch
https://github.com/8me/Twitch.jl.git
[ "MIT" ]
0.1.0
211e0268094aa69b9bc0c58b15a2be7900343e98
code
2098
module Twitch using Dates using UUIDs using Sockets using DocStringExtensions include("definitions.jl") include("parser.jl") """ $(SIGNATURES) Receiver for chat messages (see example) # Arguments - `addr::AbstractString`: Chat server address, e.g. irc.chat.twitch.tv - `port::Integer`: Chat server port (mostly 6667) - `user::AbstractString`: Twitch username - `oauth::AbstractString`: Twitch oauth token, format: 'oauth:...' - `channel::AbstractString`: Twitch channel chat which should be joined - `c::Condition`: Condition which indicates state changes - `queue::Channel{T}`: Queue of received messages (still raw format) """ function chatreceiver( addr::AbstractString, port::Integer, user::AbstractString, oauth::AbstractString, channel::AbstractString, c::Condition, queue::Channel{T} ) where { T <: AbstractString } @info "Reading for channel $(channel) started..." client = connect(addr, port) isconnected = false println(client, "NICK $(user)\n") println(client, "PASS $(oauth)\n") println(client, "JOIN #$(channel)\n") #Request additional infos println(client, "CAP REQ :twitch.tv/commands twitch.tv/tags") try while isopen(client) resp = readline(client, keep=true) @debug "Raw response: $(resp)" if startswith(resp, "PING") println(client, "PONG") continue elseif contains(resp, "RECONNECT") || isempty(resp) break elseif ~isconnected && contains(resp, "366") @info "Task for logging $(channel) is connected." notify(c) isconnected = true elseif isconnected put!(queue, resp) end end catch e @debug "Reading for $(channel) yields a problem -> $(e)" notify(c) end @info "Chat reader for channel $(channel) finished." close(client) end end # module Twitch
Twitch
https://github.com/8me/Twitch.jl.git
[ "MIT" ]
0.1.0
211e0268094aa69b9bc0c58b15a2be7900343e98
code
597
@enum MODACTION begin timeout = 1 deleted = 2 ban = 3 end struct Message messageid::UUID replyid::UUID viewernick::AbstractString vieweruid::Int64 channelname::AbstractString channelroomid::Int64 msg::AbstractString timestamp::DateTime ismod::Bool issubscriber::Bool isreturning::Bool isturbouser::Bool isvip::Bool end struct Notice messageid::UUID viewernick::AbstractString vieweruid::Int64 channelname::AbstractString channelroomid::Int64 action::MODACTION timeout::Int64 timestamp::DateTime end
Twitch
https://github.com/8me/Twitch.jl.git
[ "MIT" ]
0.1.0
211e0268094aa69b9bc0c58b15a2be7900343e98
code
3262
""" $(SIGNATURES) Interpret return from chat server # Arguments - `response::AbstractString`: Raw response string """ function response(response::AbstractString) response = strip(response) if occursin("PRIVMSG", response) return message(response) elseif occursin("CLEAR", response) return action(response) end nothing end function _parseheader(rawheader::AbstractString) fields = Dict() for line in split(rawheader, ';') kvsplit = split(line, '=') if ~isempty(kvsplit[2]) fields[kvsplit[1]] = kvsplit[2] end end Set(keys(fields)), fields end """ $(SIGNATURES) Interpret message string # Arguments - `msg::AbstractString`: Raw message string """ function message(msg::AbstractString) regex = r"(.*?) :(.*?)!(.*?)@(.*?)\.tmi\.twitch.tv PRIVMSG #(.*?) \:(.*)$" msgparts = collect(match(regex, msg)) k, fields = _parseheader(msgparts[1]) messageid = UUID(fields["id"]) if "reply-parent-msg-id" in k replyid = UUID(fields["reply-parent-msg-id"]) else replyid = messageid end ismod = parse(Bool, fields["mod"]) isreturning = parse(Bool, fields["returning-chatter"]) roomid = parse(Int64, fields["room-id"]) issubscriber = parse(Bool, fields["subscriber"]) timestamp = unix2datetime(parse(Int64, fields["tmi-sent-ts"]) * 1e-3) #Millisecond timestamp isturbouser = parse(Bool, fields["turbo"]) isvip = false if "vip" in k isvip = parse(Bool, fields["vip"][1]) end userid = parse(Int64, fields["user-id"]) nickname = msgparts[2] channel = msgparts[5] message = msgparts[6] Message(messageid, replyid, nickname, userid, channel, roomid, message, timestamp, ismod, issubscriber, isreturning, isturbouser, isvip) end """ $(SIGNATURES) Interpret actions string, e.g. information about timeout or ban # Arguments - `msg::AbstractString`: Raw message string """ function action(msg::AbstractString) if contains(msg, "CLEARMSG") action = deleted tmp = split(msg[2:end], " :tmi.twitch.tv CLEARMSG ") else action = ban tmp = split(msg[2:end], " :tmi.twitch.tv CLEARCHAT ") end k, fields = _parseheader(tmp[1]) timestamp = unix2datetime(parse(Int64, fields["tmi-sent-ts"]) * 1e-3) #Millisecond timestamp messageid = UUID(0) if "target-msg-id" in k && ~isempty(fields["target-msg-id"]) messageid = UUID(fields["target-msg-id"]) end duration = -1 if "ban-duration" in k duration = parse(Int64, fields["ban-duration"]) end channelroomid = -1 if "room-id" in k channelroomid = parse(Int64, fields["room-id"]) end regex = r"#(.*?) :(.*?)$" a = collect(match(regex, tmp[2])) channelname = a[1] viewernick = "" if "login" in k viewernick = fields["login"] elseif ~("target-msg-id" in keys(fields)) viewernick = strip(a[2]) end vieweruid = -1 if "target-user-id" in k vieweruid = parse(Int64, fields["target-user-id"]) end if duration > 0 action = timeout end Notice(messageid, viewernick, vieweruid, channelname, channelroomid, action, duration, timestamp) end
Twitch
https://github.com/8me/Twitch.jl.git
[ "MIT" ]
0.1.0
211e0268094aa69b9bc0c58b15a2be7900343e98
code
415
using Twitch using UUIDs using Dates testmsg = """@room-id=1234567;target-user-id=78910111213;tmi-sent-ts=167900689445 :tmi.twitch.tv CLEARCHAT #justinfan1 :justinfan2\r\n""" resp = Twitch.response(testmsg) @test resp.messageid == UUID("00000000-0000-0000-0000-000000000000") @test resp.viewernick == "justinfan2" @test resp.action == Twitch.ban @test resp.timestamp == Dates.DateTime("1975-04-28T07:04:49.445")
Twitch
https://github.com/8me/Twitch.jl.git
[ "MIT" ]
0.1.0
211e0268094aa69b9bc0c58b15a2be7900343e98
code
66
using Test @testset "Parse" begin include("parse_tests.jl") end
Twitch
https://github.com/8me/Twitch.jl.git
[ "MIT" ]
0.1.0
211e0268094aa69b9bc0c58b15a2be7900343e98
docs
301
# Code of Conduct The project sticks to the general code of conduct and community standards of the julia community. See: https://julialang.org/community/standards/ For any questions, remarks, conflicts, etc. please contact the [Julia Community Stewards](https://julialang.org/community/stewards/)
Twitch
https://github.com/8me/Twitch.jl.git
[ "MIT" ]
0.1.0
211e0268094aa69b9bc0c58b15a2be7900343e98
docs
1337
<img style="height:9em;" alt="UnROOT.jl" src="docs/src/assets/logo.svg"/> <!-- [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://8me.github.io/Twitch.jl/stable) --> [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://8me.github.io/Twitch.jl/dev) [![Build Status](https://github.com/8me/Twitch.jl/workflows/CI/badge.svg)](https://github.com/8me/Twitch.jl/actions) [![Codecov](https://codecov.io/gh/8me/Twitch.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/8me/Twitch.jl) <!-- [![DOI](https://zenodo.org/badge/xxx.svg)](https://zenodo.org/badge/latestdoi/xxx) --> # Twitch.jl **Twitch.jl** is a package for interfacting Twitch functionalities. At the moment this includes communication with the chat server, but is intented to include Helix API soon. ## Contribution You are invited to contribute to the project with ideas for improvements or bug reports via [issues](https://github.com/8me/Twitch.jl/issues) or event better with some code via a [PR](https://github.com/8me/Twitch.jl/pulls). #### Help Wanted Issues If some issue are marked [help wanted](https://github.com/8me/Twitch.jl/labels/help%20wanted) please feel free to jump in and help solve it if yoou have some ideas. <!-- ```@index --> <!-- ``` --> <!-- --> <!-- ```@autodocs --> <!-- Modules = [Twitch] --> <!-- ``` -->
Twitch
https://github.com/8me/Twitch.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
code
560
using TraceEstimators using Documenter makedocs(; modules=[TraceEstimators], authors="Akshay Jain and contributors", repo="https://github.com/mohamed82008/TraceEstimators.jl/blob/{commit}{path}#L{line}", sitename="TraceEstimators.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://mohamed82008.github.io/TraceEstimators.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/mohamed82008/TraceEstimators.jl", )
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
code
169
module TraceEstimators include("common.jl") include("hutchinson.jl") include("diagapp.jl") include("slq.jl") include("chebyhutch.jl") include("diagonalapprox.jl") end
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
code
6060
# Stochastic Chebyshev Polynomial method # Based on APPROXIMATING SPECTRAL SUMS OF LARGE-SCALE MATRICES USING STOCHASTIC CHEBYSHEV APPROXIMATIONS By Han, Malioutov, Avron and Shin export ChebyHutchSpace, chebyhutch, chebydiagonal, lczeigen using LinearAlgebra using Parameters using Statistics # Lanczos iteration for finding extremal eigenvalues of the matrix function lczeigen(A, fn, dfn) # Estimate eigmax and eigmin for Chebyshev bounds mval = Int64(ceil(log(ϵ/(1.648 * sqrt(size(A, 1))))/(-2 * sqrt(ξ)))) w = SLQWorkspace(A, fn = fn, dfn = dfn, m = mval) dfn(w.v) w.v .= w.v ./ norm(w.v) lcz(w) λₘ = eigmax(w.T) λ₁ = eigmin(w.T) return λ₁, λₘ end # Chebyshev polynomial method helper functions 𝓍(k, n) = cos((π * (k + 0.5))/(n+1)) function T(j, x, Tvals) if j == 0 return 1 end if j == 1 return x end if haskey(Tvals, j) return Tvals[j] else Tvals[j] = (2 * x * T(j-1, x, Tvals)) - T(j-2, x, Tvals) return Tvals[j] end end function coeff(j, n, a, b, fn) fs = zero(eltype(a)) for k in 0:n x = 𝓍(k, n) Tvals = Dict{Int, Float64}() fs = fs + fn((((b-a)/2) * x) + (b+a)/2) * T(j, x, Tvals) end if j == 0 return (1/(n+1)) * fs end return (2/(n+1)) * fs end mutable struct ChebyHutchSpace{elt, TM, FN<:Function, FN2<:Function, TA<:AbstractArray{elt, 1}, TV<:AbstractVecOrMat{elt}, I<:Int64} A::TM a::elt b::elt fn::FN dfn::FN2 C::TA w₀::TV w₁::TV w₂::TV v::TV u::TV m::I n::I end """ ChebyHutchSpace(A::AbstractMatrix, a::Number, b::Number; fn::Function=invfun, dfn::Function=rademacherDistribution!, m = 4, n = 6) Create Chebyshev-Hutchinson Workspace for chebyhutch or chebydiagonal methods. # Arguments - `A` : Symmetric Positive Definite Matrix - `a` : Bound for minimum eigenvalue of A - `b` : Bound for maximum eigenvalue of A - `fn` : Function to appy. By default uses inverse function. - `dfn` : Distribution function that returns a vector v. By default uses rademacherDistribution! - `m` : Iteration number, increase this for precision. By default m = 4 - `n` : Polynomial degree, increase this for accuracy. By default n = 6 """ function ChebyHutchSpace(A::AbstractMatrix, a::Number, b::Number; fn::Function=invfun, dfn::Function=rademacherDistribution!, m = 4, n = 6) elt = eltype(A) s = size(A, 1) C = elt[] v = Matrix{elt}(undef, s, m) w₀ = similar(v) w₁ = similar(v) w₂ = similar(v) u = similar(v) return ChebyHutchSpace(A, a, b, fn, dfn, C, w₀, w₁, w₂, v, u, m, n) end function chebypm(w::ChebyHutchSpace) @unpack A, a, b, C, fn, dfn, v, u, w₀, w₁, w₂, m, n = w tr = zero(eltype(A)) for j in 0:n push!(C, coeff(j, n, a, b, fn)) end dfn(v) w₀ .= v mul!(w₁, A, v) #rmul!(w₁, 2/(b-a)) w₁ .= 2/(b-a) .* w₁ .- (((b+a)/(b-a)) .* v) u .= (C[1] .* w₀) .+ (C[2] .* w₁) for j in 2:n mul!(w₂, A, w₁) #rmul!(w₂, 4/(b-a)) w₂ .= 4/(b-a) .* w₂ .- ((2(b+a)/(b-a)) .* w₁) .- w₀ u .= u .+ (C[j+1] .* w₂) w₀ .= w₁ w₁ .= w₂ end return v, u, m end """ chebyhutch(w::ChebyHutchSpace) chebyhutch(A::AbstractMatrix, m::Integer, n::Integer; a::Float64, b::Float64, fn::Function=invfun, dfn::Function=rademacherDistribution!) chebyhutch(A::AbstractMatrix; fn::Function=invfun, dfn::Function=rademacherDistribution!) Chebyshev-Hutchinson to estimate tr(fn(A)), for given matrix A and an analytic function fn. # Arguments - `A` : Symmetric Positive Definite Matrix - `m` : Iteration number, increase this for precision. By default m = 4 - `n` : Polynomial degree, increase this for accuracy. By default n = 6 - `fn` : Function to appy. By default uses inverse function. - `dfn` : Distribution function that returns a vector v. By default uses rademacherDistribution! """ function chebyhutch(w::ChebyHutchSpace) v, u, m = chebypm(w) return dot(v, u) / m end function chebyhutch(A::AbstractMatrix, m::Integer, n::Integer; a::Float64=-1.0, b::Float64=-1.0, fn::Function=invfun, dfn::Function=rademacherDistribution!) # calculate extremal eigenvals if a == -1.0 || b == -1.0 λ₁, λₘ = lczeigen(A, fn, dfn) end if a != -1.0 λ₁ = a end if b != -1.0 λₘ = b end wx = ChebyHutchSpace(A, λₘ, λ₁, fn=fn, dfn=dfn, m = m, n = n) return chebyhutch(wx) end function chebyhutch(A::AbstractMatrix; m = -1, n = -1, fn::Function=invfun, dfn::Function=rademacherDistribution!) # calculate extremal eigenvals λ₁, λₘ = lczeigen(A, fn, dfn) # calculate values of m and n # these bounds are for theoretical purposes only κ = λₘ/λ₁ ρ = sqrt(2 * κ - 1) - 1 if m == -1 m = Int64(ceil(54 * (ϵ)^(-2) * log(2/ξ)/16)) end if n == -1 nVal = Int64(ceil((log(8/ϵ)*ρ*κ)/(log((2/ρ) + 1))/16)) end wx = ChebyHutchSpace(A, λₘ, λ₁, fn=fn, dfn=dfn, m = m, n = n) return chebyhutch(wx) end """ chebydiagonal(w::ChebyHutchSpace) chebydiagonal(A::AbstractMatrix, m::Integer, n::Integer; fn::Function=invfun, dfn::Function=rademacherDistribution!) Chebyshev-Hutchinson to estimate diagonal elements of fn(A), for given matrix A and an analytic function fn. # Arguments - `A` : Symmetric Positive Definite Matrix - `m` : Iteration number, increase this for precision. By default m = 4 - `n` : Polynomial degree, increase this for accuracy. By default n = 6 - `fn` : Function to appy. By default uses inverse function. - `dfn` : Distribution function that returns a vector v. By default uses rademacherDistribution! """ function chebydiagonal(w::ChebyHutchSpace) v, u, m = chebypm(w) return vec(mean(v .* u, dims=2)) end function chebydiagonal(A, m, n; fn::Function=invfun, dfn::Function=rademacherDistribution!) # calculate extremal eigenvals λ₁, λₘ = lczeigen(A, fn, dfn) wx = ChebyHutchSpace(A, λₘ, λ₁, fn=fn, dfn=dfn, m = m, n = n) return chebydiagonal(wx) end
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
code
179
# Predefined functions and values const ϵ = 0.5 const ξ = 0.01 invfun(x) = 1/x function rademacherDistribution!(v) o = one(eltype(v)) v .= Base.rand.(Ref(-o:2*o:o)) end
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
code
1819
# Diagonal Approximation for trace of inverse of matrix # Values from Extrapolation Methods for Estimating Trace of the Matrix Inverse by P. Fika export diagapp using LinearAlgebra struct Diagappspace{T, TM <: AbstractMatrix{T}, TV <: AbstractVector{T}, F<:Function} A::TM x::TV y::TV randfunc::F end function Diagappspace(A::AbstractMatrix, randfunc::Function) x = randfunc(eltype(A) <: Integer ? Float64 : eltype(A), size(A, 1)) y = similar(x) return Diagappspace(A, x, y, randfunc) end # Extrapolation for c-1 and calculating value of v0 function v0(w::Diagappspace) copyto!(w.x, w.randfunc(-1:2:1, size(w.A, 1))) c0 = dot(w.x, w.x) mul!(w.y, w.A, w.x) c1 = dot(w.y, w.x) c2 = dot(w.y, w.y) mul!(w.x, w.A, w.y) c3 = dot(w.y, w.x) p = (c0 * c2)/(c1^2) v0 = log10((c1^2)/(c0 * c2)) / log10((c1 * c3)/(c2^2)) end # Calculating the Approximation for ith value of inverse diagonal function dfun(A, i, v) isum = zero(eltype(A)) s = size(A, 1) for k in 1:s isum = isum + A[k, i]^2 end #v = v0(A) p = isum / (A[i, i]^2) d = 1 / (p^v * A[i, i]) end # Calculating Diagonal Approximation for Matrix Inverse # This works a SPD Matrix with low condition number """ diagapp(A::AbstractMatrix; randfunc=Base.rand) Diagonal Approximation algorithm for inverse of matrix. # Arguments - `A` : Symmetric Positive Definite Matrix with Low Condtion Number (k < 500) - `randfunc` : Random function for the particular type of matrix A (An example can be found in test/diagapp.jl) """ function diagapp(A; randfunc::Function=Base.rand) tr = zero(eltype(A)) s = size(A, 1) w = Diagappspace(A, randfunc) v = v0(w) for i in 1:s tr = tr + dfun(w.A, i, v) end tr end
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
code
9894
# Diagonal Approximation algorithm using LinearAlgebra using SparseArrays using DataStructures using Preconditioners using IncompleteLU using Statistics using IterativeSolvers export diagonalapprox, tr_inv, diag_inv ## pchip start struct _pchip N :: Integer xs :: Array{Float64} ys :: Array{Float64} ds :: Array{Float64} end ϕ(t) = 3t^2 - 2t^3 ψ(t) = t^3 - t^2 function _interp(pchip :: _pchip, x :: Number) i = _pchip_index(pchip, x) x1, x2 = pchip.xs[i:i+1] y1, y2 = pchip.ys[i:i+1] d1, d2 = pchip.ds[i:i+1] h = x2 - x1 (y1 * ϕ((x2-x)/h) + y2 * ϕ((x-x1)/h) - d1*h * ψ((x2-x)/h) + d2*h * ψ((x-x1)/h)) end function _pchip_index(pchip :: _pchip, x) N = pchip.N if N < 200 # Approximate performance cross-over on my old intel i7-3517U i = _pchip_index_linear_search(pchip, x) else i = _pchip_index_bisectional_search(pchip, x) end if i == N # Treat right endpoint as part of rightmost interval @assert (x ≈ pchip.xs[N]) i = N-1 end i end function _pchip_index_linear_search(pchip :: _pchip, x) xmin = pchip.xs[1] @assert (x >= xmin) i = 1 N = pchip.N while i < N && x >= pchip.xs[i+1] i = i + 1 end i end function _pchip_index_bisectional_search(pchip :: _pchip, x) N = pchip.N imin, imax = 1, N xmin = pchip.xs[imin] xmax = pchip.xs[imax] @assert (x >= xmin && x <= xmax) i = imin + div(imax - imin + 1, 2) while imin < imax if x < pchip.xs[i] imax = i - 1 elseif x >= pchip.xs[i+1] imin = i + 1 else break end i = imin + div(imax - imin + 1, 2) end i end function _initial_ds_scipy(xs, ys) h(i) = xs[i+1]-xs[i] Δ(i) = (ys[i+1]-ys[i]) / h(i) N = length(xs) ds = similar(xs) if N == 2 ds[:] .= Δ(1) else Δl = Δ(1) hl = h(1) for i ∈ 2:N-1 Δr = Δ(i) hr = h(i) if sign(Δl) != sign(Δr) || Δl ≈ 0.0 || Δr ≈ 0.0 ds[i] = 0.0 else wl = 2hl + hr wr = hl + 2hr axx = (wl + wr) bxx = (wl/Δl + wr/Δr) ds[i] = axx / bxx end Δl = Δr hl = hr end ds[1] = _edge_derivative(h(1), h(2), Δ(1), Δ(2)) ds[N] = _edge_derivative(h(N-1), h(N-2), Δ(N-1), Δ(N-2)) end ds end function _edge_derivative(h1, h2, Δ1, Δ2) d = ((2h1 + h2)*Δ1 - h2*Δ2) / (h1 + h2) if sign(d) != sign(Δ1) d = 0.0 elseif sign(Δ1) != sign(Δ2) && abs(d) > abs(3Δ1) d = 3Δ1 end d end function interpolate(xs, ys) xs_ = [x for x ∈ xs] ys_ = [y for y ∈ ys] _assert_xs_ys(xs_, ys_) ds = _initial_ds_scipy(xs_, ys_) pchip = _pchip(length(xs_), xs_, ys_, ds) x -> _interp(pchip, x) end function _assert_xs_ys(xs, ys) N = length(xs) @assert (N > 1) @assert (N == length(ys)) assert_monotonic_increase(xs) end function assert_monotonic_increase(xs) foldl((a,b) -> (@assert (a < b); b), xs) end ## pcip end # find approximate inverse function z_approx_chol(A::AbstractMatrix, v) P = CholeskyPreconditioner(A) return (P.L \ v) , P end function z_approx_ilu(A::AbstractMatrix, v) P = ilu(A) L = P.L + I U = P.U return (U \ (L \ v)), P end function z_approx_amg(A::AbstractMatrix, v) P = AMGPreconditioner(A) z = P \ v return z, P end # Minimize this function for value of t # i < t < j, t ∈ 𝐙 function t_bisection(M, i, j) vals = [] for t in i+1:j-1 push!(vals, abs((M[i] - M[j])*(i - j) - (M[i] - M[t])*(i-t) - (M[t] - M[j])*(t-j))) end return argmin(vals)+i end # Create new index in the middle of the longest L-R range function middle_index!(S, Q = Nothing, Mₒ = Nothing) temp = 0 L = 0 R = 0 interval = 0 for i in S if temp != 0 if interval < i - temp interval = i - temp L = temp R = i end temp = i else temp = i end end t = Int64(ceil((L + R)/2)) push!(S, t) if Q != Nothing delete!(Q, (L, R)) if t - L > 1 enqueue!(Q, (L, t), abs(sum(Mₒ[L:t]) - (Mₒ[L] + Mₒ[t])*((t-L))/2)) end if R - t > 1 enqueue!(Q, (t, R), abs(sum(Mₒ[t:R]) - (Mₒ[t] + Mₒ[R])*((R-t))/2)) end end end function point_identification(M, maxPts) N = size(M, 1) Mₒ = sort(M) J = sortperm(M) numSamples = 1 initErr = abs(sum(Mₒ) - (Mₒ[1] + Mₒ[N])*(N/2)) tempErr = initErr Sₒ = SortedSet{Int64}() push!(Sₒ, 1) push!(Sₒ, N) Q = PriorityQueue{Tuple{Int64, Int64}, Float64}(Base.Order.Reverse) enqueue!(Q, (1, N), initErr) while numSamples < maxPts && peek(Q)[2] > 0.001*initErr # pop interval (L, R) with the largest error from Q interval = dequeue!(Q) L, R = interval[1], interval[2] # for t = L+1:R-1 find bisection index t t = t_bisection(Mₒ, L, R) # Add t to Sₒ and increase numsamples if t - L >= 1 && R - t >= 1 push!(Sₒ, t) numSamples = numSamples + 1 end # Push interval (L, t) and (t, R) with temperror into Q if t - L > 1 enqueue!(Q, (L, t), abs(sum(Mₒ[L:t]) - (Mₒ[L] + Mₒ[t])*((t-L)/2))) end if R - t > 1 enqueue!(Q, (t, R), abs(sum(Mₒ[t:R]) - (Mₒ[t] + Mₒ[R])*((R-t)/2))) end # insert midpoint into largest interval after every 5 samples if numSamples%5 == 0 middle_index!(Sₒ, Q, Mₒ) numSamples = numSamples + 1 end end # insert midpoints in the largest intervals while numSamples < maxPts middle_index!(Sₒ) numSamples = numSamples + 1 end ## unique Mₒ values and Sₒ indices temp = Set() S = [] for i in Sₒ if (Mₒ[i] in temp) == false push!(S, J[i]) push!(temp, Mₒ[i]) end end return S end function basis_vector!(e, k) e .= Ref(0) e[k] = one(eltype(e)) end function linreg(X, Y) n = size(Y, 1) sX = sum(X) sY = sum(Y) sXY = sum(X.*Y) sX2 = sum(X.^2) c = (sY*sX2 - sX*sXY)/(n*sX2 - sX^2) b = (n*sXY - sX*sY)/(n*sX2 - sX^2) return b, c end function linear_model(S, D, M, n) b, c = linreg(M[S], D) Tf = zero(eltype(D)) Ms = Vector{eltype(D)}(undef, n) for i in 1:n Ms[i] = b * M[i] + c Tf += b * M[i] + c end return Tf, Ms end function pchip_iterpolation(S, D, M, n) pchip = interpolate(M[S], D) Tf = zero(eltype(D)) Ms = Vector{eltype(D)}(undef, n) for i in 1:n Ms[i] = pchip(M[i]) Tf += pchip(M[i]) end return Tf, Ms end function diagonalapprox(A::AbstractMatrix, n::Int64, p::Int64, pc, model) # Compute M = diag(approximation of A⁻¹) v = Matrix{eltype(A)}(undef, size(A,1), n) rademacherDistribution!(v) if pc == "ilu" Z, pl = z_approx_ilu(A, v) elseif pc == "amg" Z, pl = z_approx_chol(A, v) elseif pc == "cheby" M = chebydiagonal(A, 4, 6) pl = ilu(A) else Z, pl = z_approx_chol(A, v) end if pc != "cheby" M = vec(mean(v .* Z , dims=2)) end # Compute fitting sample S, set of k indices S = point_identification(M, p) # Solve for D(i) = e'(i) A⁻¹ e(i) for i = 1 ... k e = zeros(size(A, 1)) D = eltype(A)[] if pc == "cheby" lmin, lmax = lczeigen(A, invfun, rademacherDistribution!) for i in 1:size(S, 1) basis_vector!(e,S[i]) push!(D, e' * chebyshev(A, e, lmin, lmax, Pl = pl)) end else for i in 1:size(S, 1) basis_vector!(e, S[i]) push!(D, e' * cg(A, e, Pl = pl)) end end # Obtain fitting model f(M) ≈ D by fitting f(M(S)) to D(S) Tf = zero(eltype(A)) Ms = Vector{eltype(A)}(undef, size(A, 1)) if model == "pchip" Tf, Ms = pchip_iterpolation(S, D, M, size(A, 1)) else Tf, Ms = linear_model(S, D, M, size(A, 1)) end return (Tf, Ms) end """ tr_inv(A::AbstractMatrix, n::Int64, p::Int64; pc = "chol", model = "linear") Diagonal Approximation algorithm for calculating trace of the matrix inverse. # Arguments - `A` : Symmetric Positive Definite Matrix - `n` : Probing vector count for initial approximation. - `p` : Sample Points count for interpolation - `pc` : Preconditioner used for initial approximation and cg ("chol" - Incomplete Cholesky, "ilu" - IncompleteLU, "amg" - AlgebraicMultigrid, "cheby" - Chebyshev Approximation). Default = "chol" - `model` : Fitting model used for calculation of trace ("linear" - Linear Regression, "pchip" - PCHIP interpolation). Default = "linear". """ function tr_inv(A::AbstractMatrix, n::Int64, p::Int64; pc = "chol", model = "linear") return diagonalapprox(A, n, p, pc, model)[1]; end """ diag_inv(A::AbstractMatrix, n::Int64, p::Int64; pc = "chol", model = "linear") Diagonal Approximation algorithm for the matrix inverse. # Arguments - `A` : Symmetric Positive Definite Matrix - `n` : Probing vector count for initial approximation. - `p` : Sample Points count for interpolation - `pc` : Preconditioner used for initial approximation and cg ("chol" - Incomplete Cholesky, "ilu" - IncompleteLU, "amg" - AlgebraicMultigrid, "cheby" - Chebyshev Approximation). Default = "chol" - `model` : Fitting model used for calculation of trace ("linear" - Linear Regression, "pchip" - PCHIP interpolation). Default = "linear". """ function diag_inv(A::AbstractMatrix, n::Int64, p::Int64; pc = "chol", model = "linear") return diagonalapprox(A, n, p, pc, model)[2]; end
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
code
4039
# Hutchinson Trace Estimator for Inverse of Matrix # Based on Hutchinson's Stochastic Estimation Proof # Values from Extrapolation Methods for Estimating Trace of the Matrix Inverse by P. Fika # (This method works for SPD with low condition number) export hutch, hutch!, HutchWorkspace using LinearAlgebra struct HutchWorkspace{T, TM <: AbstractMatrix{T}, F <: Function, TV <: AbstractVector{T}} A::TM randfunc::F x::TV y::TV N::Int64 skipverify::Bool end """ HutchWorkspace(A; N = 30, skipverify = false) HutchWorkspace(A, randfunc::Function; N = 30, skipverify = false) # Arguments - `A` : Symmetric Positive Definite Matrix with Low Condtion Number (k < 500) - `randfunc` : Function to generate random values for x distributed uniformly (Base: rand(-1.0:2.0:1.0, size(A,1)) Example: f(n) = rand(-1.0:2.0:1.0, n) - `N` : Number of iterations (Default: 30) - `skipverify` : If false, it will check isposdef(A) (Default: false) """ function HutchWorkspace(A, randfunc::Function; N = 30, skipverify = false) x = randfunc(size(A,1)) y = similar(x) return HutchWorkspace(A, randfunc, x, y, N, skipverify) end function HutchWorkspace(A; N = 30, skipverify = false) randfunc(n) = rand(-1:2:1, n) x = rand(eltype(A) <: Integer ? Float64 : eltype(A), size(A,1)) y = similar(x) return HutchWorkspace(A, randfunc, x, y, N, skipverify) end # Calculating the moments and extrapolating c-1 function ev(w::HutchWorkspace) # Create new random values for x copyto!(w.x, w.randfunc(size(w.A, 1))) # Find c(r) = x' * A^r * x = dot(x', A^r * x) c0 = dot(w.x, w.x) mul!(w.y, w.A, w.x) c1 = dot(w.y, w.x) c2 = dot(w.y, w.y) mul!(w.x, w.A, w.y) c3 = dot(w.y, w.x) # intermediate arguments for v0 nVal = (c1^2)/(c0 * c2) dVal = (c1 * c3)/(c2^2) if (nVal > 0) && (dVal > 0) # Find p (Page 175) p = (c0 * c2)/(c1^2) # Find v0 (Page 179, Numerical Example) -> Corollary 4 in [16] v0 = log10(nVal) / log10(dVal) # Finally find ev (Page 175) ev0 = (c0^2)/(p^v0 * c1) return ev0 else @warn "v0 cannot be calculated. Aitken's process may give inaccurate results!" w1 = HutchWorkspace(w.A, w.randfunc, w.x, w.y, w.N, w.skipverify) return hutch!(w1, aitken=true) end end # Aitken's Process to Predict the negative moment # (Page 176, eq 4) function gfun(w::HutchWorkspace) copyto!(w.x, w.randfunc(size(w.A, 1))) c0 = dot(w.x, w.x) mul!(w.y, w.A, w.x) c1 = dot(w.y, w.x) c2 = dot(w.y, w.y) mul!(w.x, w.A, w.y) c3 = dot(w.y, w.x) #g1 = c0 - (((c1 - c0)^2) / (c2 - c1)) g2 = c1 - (((c2 - c0) * (c2 - c1)) / (c3 - c2)) #g = (g1 + g2)/2 end """ hutch(A; N = 30, skipverify = false) Take a HutchWorkspace object as input, apply hutchinson estimation algorithm and solve for trace of inverse of the matrix. (in-place version also available) """ # Hutchinson trace estimation using extrapolation technique (Page 177) function hutch(A; N=30, skipverify = false, aitken = false) w = HutchWorkspace(A, N = N, skipverify = skipverify) return hutch!(w, aitken) end """ hutch!(w::HutchWorkspace; aitken = false) hutch!(A::AbstractArray; N = 30, skipverify = false, aitken = false) Take a HutchWorkspace object as input, apply hutchinson estimation algorithm and solve for trace of inverse of the matrix. (in-place version of hutch) """ function hutch!(w::HutchWorkspace; aitken = false) if w.skipverify == true || isposdef(w.A) tr = zero(eltype(w.A)) sum = zero(eltype(w.A)) for i in 1:w.N # if aitken == true => use aitken process to predict the terms via gfun sum = sum + (aitken ? gfun(w) : ev(w)) end tr = sum/w.N end end function hutch!(A::AbstractArray{<:Any, 2}; N = 30, skipverify = false, aitken = false) w = HutchWorkspace(A, N, skipverify) return hutch!(w, aitken) end
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
code
5630
# Stochastic Lanczos Quadrature method # Based on Ubaru, Shashanka, Jie Chen, and Yousef Saad. # "Fast estimation of tr(F(A)) via stochastic lanczos quadrature, 2016." # URL: http://www-users.cs.umn.edu/~saad/PDF/ys-2016-04.pdf. export SLQWorkspace, slq using LinearAlgebra using Parameters struct SLQWorkspace{ elt, TM<:AbstractMatrix{elt}, FN<:Function, FN2<:Function, I<:Integer, TV<:AbstractVector{elt}, AV<:AbstractVector{elt}, TS<:SymTridiagonal, TM2<:AbstractMatrix{elt}, R<:Real, } A::TM fn::FN dfn::FN2 m::I v::AV nᵥ::I ctol::R T::TS α::TV β::TV ω::TV Y::TM2 Θ::TV v₀::AV end # Using v = Vector{elt}(undef, n) will increase the performance but due to # support issue for CuArray, it must be kept similar(A, n). # This is a good use-case for full (which was removed in Julia 1.0) where # we could just get a dense vector from a sparse one solving the performance # issue """ SLQWorkspace(A::AbstractMatrix; fn::Function, dfn::Function, ctol, m, nv) Create an SLQWorkspace for supplied SPD Matrix A. Use it to calculate tr(fn(A)). # Arguments - `A` : Symmetric Positive Definite Matrix - `fn` : Function to apply. By default uses inverse function - `dfn` : Distribution function for v (random dist. with norm(v) = 1). By default uses rademacherDistribution!(v::Vector, t::Type) - `ctol` : SLQ Convergence Tolerance value. By default ctol = 0.1 - `m` : Specify value for lanczos steps. By default m = 15 - `nv` : Specify value for SLQ iterations. By default nb = 10 """ function SLQWorkspace(A; fn::Function=invfun, dfn::Function=rademacherDistribution!, ctol=0.1, m=15, nv=10) elt = eltype(A) Atype = typeof(A) n = size(A, 1) #v = Vector{elt}(undef, n) v = similar(A, n) v₀ = similar(v) α = Vector{elt}(undef, m) β = Vector{elt}(undef, m-1) ω = Vector{elt}(undef, n) Y = similar(A, m, m) Θ = similar(α) T = SymTridiagonal(α, β) return SLQWorkspace(A, fn, dfn, m, v, nv, ctol, T, α, β, ω, Y, Θ, v₀) end function lcz(w::SLQWorkspace) α₀ = zero(eltype(w.A)) β₀ = zero(eltype(w.A)) fill!(w.v₀, 0) # Following loop executes lanczos steps @unpack A, v, ω, v₀, α, β, m, T = w for i in 1:w.m mul!(ω, A, v) α₀ = dot(ω, v) ω .= ω .- (α₀ .* v) .- (β₀ .* v₀) β₀ = norm(ω) α[i] = α₀ if i < m β[i] = β₀ end # Sparse Vectors do not support copy! #copy!(v₀, v) v₀ .= v v .= ω ./ β₀ end end """ slq(w::SLQWorkspace; skipverify = false) slq(A::AbstractMatrix; skipverify = false, fn::Function = invfun, dfn::Function = Base.rand, ctol = 0.1, eps = ϵ, mtol = tol) SLQ method to calculate tr(fn(A)) for a Symmetric Positive Definite matrix A and an analytic function fn. # Arguments - `A` : Symmetric Positive Definite Matrix - `skipverify` : Skip isposdef(A) verification. By default skipverify = false - `fn` : Function to apply on A before trace calculation. fn must be analytic λₘ and λ₁ of A. By default fn = inv - `dfn` : Distribution function for v (random dist. with norm(v) = 1). By default uses rademacherDistribution!(v::Vector, t::Type) - `ctol` : SLQ Convergence Tolerance value. Decrease this for higher precision. By default ctol = 0.1 - `eps` : Error bound for lanczos steps calculation. Decrease this for higher accuracy. By default eps = 0.05 - `mtol` : Tolerance for eigenvalue Convergence. Decrease this for precision. By default mtol = 0.01 """ function slq(w::SLQWorkspace; skipverify = false) @unpack A, v, T, Y, Θ, m, nᵥ, ctol, fn, dfn = w tr = zero(eltype(w.A)) if skipverify || isposdef(w.A) actual_nᵥ = nᵥ for i in 1:w.nᵥ prev_tr = tr # Create a uniform random distribution with norm(v) = 1 dfn(v) v .= v ./ norm(v) # Run lanczos algorithm to find estimate Ritz SymTridiagonal lcz(w) Y .= eigvecs(T) Θ .= eigvals(T) for j in 1:m τ = Y[1,j] tr = tr + τ^2 * fn(Θ[j]) end if isapprox(prev_tr, tr, rtol = ctol) actual_nᵥ = i break end end tr = size(w.A, 1)/actual_nᵥ * tr else throw("Given Matrix is NOT Symmetric Positive Definite") end return tr end function slq(A::AbstractMatrix; skipverify = false, fn::Function = invfun, dfn::Function = rademacherDistribution!, ctol = 0.1, eps = ϵ, mtol = ξ) # Estimate eigmax and eigmin for SLQ bounds mval = Int64(ceil(log(eps/(1.648 * sqrt(size(A, 1))))/(-2 * sqrt(mtol)))) w = SLQWorkspace(A, fn = fn, dfn = dfn, m = mval) #rademacherDistribution!(w.v) w.dfn(w.v) w.v .= w.v ./ norm(w.v) lcz(w) λₘ = eigmax(w.T) λ₁ = eigmin(w.T) if λ₁ < 0 && λₘ > 0 @warn "Eigenvalues cross zero. Functions like log may not give correct results. Try scaling the input matrix." end # SLQ bounds # Todo: Research and create better bounds for λ₁ < 1 && λₘ > 1 case κ = λₘ/λ₁ Mₚ = fn(λₘ) mₚ = fn(λ₁) ρ = (sqrt(κ) + 1)/(sqrt(κ) - 1) K = ((λₘ - λ₁) * (sqrt(κ) - 1)^2 * Mₚ)/(sqrt(κ) * mₚ) mval = Int64(ceil((sqrt(κ)/4) * log(K/eps))) if mval < 10 @warn "Low lanczos step value. Try decreasing eps and mtol for better accuracy." mval = 5 end nval = Int64(ceil((24/ϵ^2) * log(2/mtol))) # Re-construct SLQWorkspace w = SLQWorkspace(A, fn = fn, dfn = dfn, m = mval, nv = nval, ctol = ctol) slq(w, skipverify = skipverify) end
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
code
5167
using Test using Random using LinearAlgebra using SparseArrays using MatrixDepot using JLD2, FileIO using TraceEstimators function MAPE(A::Vector, O::Vector) return 1/size(A, 1) * sum(abs.((A .- O) ./ A)) end @testset "Cheby-Hutch" begin Random.seed!(123432) @testset "Dense Matrices" begin @testset "a[i,j] = exp(-2 * abS(i - j)) (small size)" begin println("Executing Test 01: Dense SPD - Small Size - Inverse") A = rand(610, 610) for i in 1:610 for j in 1:610 A[i, j] = exp(-2 * abs(i - j)) end end obv = chebyhutch(A, 4, 6, fn = inv) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=0.01) end @testset "a[i,j] = exp(-2 * abS(i - j)) (large size)" begin println("Executing Test 02: Dense SPD - Large Size - Inverse") A = rand(4610, 4610) for i in 1:4610 for j in 1:4610 A[i, j] = exp(-2 * abs(i - j)) end end obv = chebyhutch(A, 4, 6, fn = inv) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=0.01) end @testset "Random SPD Matrix (large size)" begin println("Executing Test 03: Random Dense SPD - Large Size - Log Determinant") A = rand(4610, 4610) A = A + A' while !isposdef(A) A = A + 30I end obv = chebyhutch(A, 4, 8, fn = log) acv = logdet(A) @test isapprox(obv, acv, rtol=0.02) end @testset "Hilbert Matrix" begin println("Executing Test 04: Dense Hilbert SPD - Inverse") A = matrixdepot("hilb", 3000) A = A + I obv = chebyhutch(A, 4, 6, fn = inv) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=0.01) end end @testset "Sparse Matrices" begin @testset "Random Sparse Matrix" begin println("Executing Test 05: Random Sparse Matrix - SQRT") A = sprand(6000, 6000, 0.001) A = A + A' while !isposdef(A) A = A + 60I end obv = chebyhutch(A, 4, 6, fn = sqrt) M = Matrix(A) acv = tr(sqrt(M)) @test isapprox(obv, acv, rtol = 0.01) end #= @testset "Wathen Sparse Matrix" begin println("Executing Test 06: Finite Element Matrix - Wathen") A = matrixdepot("wathen", 40) #7601x7601 obv = chebyhutch(A, 6, 12, fn = inv) M = Matrix(A) acv = tr(inv(M)) @test isapprox(obv, acv, rtol = 0.1) end =# @testset "TopOpt Shift +1 Matrix" begin println("Executing Test 07: TopOpt Shift +1") println("Loading from JLD2 file") #= s = (40, 10) # increase to increase the matrix size xmin = 0.9 # decrease to increase the condition number problem = HalfMBB(Val{:Linear}, s, (1.0, 1.0), 1.0, 0.3, 1.0) solver = FEASolver(Displacement, Direct, problem, xmin = xmin) n = length(solver.vars) solver.vars[rand(1:n, n÷2)] .= 0 solver() K = solver.globalinfo.K K = K+1*I =# @load "topoptfile.jld2" K obv = chebyhutch(K, 4, 8, fn = inv) M = Matrix(K) acv = tr(inv(M)) @test isapprox(obv, acv, rtol=0.01) end end end @testset "Cheby-Diagonal" begin @testset "Dense Matrices" begin @testset "Random SPD Matrix (large size)" begin println("Executing Test 2.1: Random Dense SPD - Large Size - Inverse") A = rand(4610, 4610) A = A + A' while !isposdef(A) A = A + 30I end o = chebydiagonal(A, 4, 8, fn = inv) a = diag(inv(A)) @test MAPE(a, o) <= 0.2 end @testset "Hilbert Matrix" begin println("Executing Test 2.2: Dense Hilbert SPD - Inverse") A = matrixdepot("hilb", 3000) A = A + I o = chebydiagonal(A, 4, 22, fn = inv) a = diag(inv(A)) @test MAPE(a, o) <= 0.2 end end @testset "Sparse Matrices" begin @testset "Random Sparse Matrix" begin println("Executing Test 2.3: Random Sparse Matrix - SQRT") A = sprand(6000, 6000, 0.001) A = A + A' while !isposdef(A) A = A + 60I end o = chebydiagonal(A, 4, 6, fn = sqrt) M = Matrix(A) a = diag(sqrt(M)) @test MAPE(a, o) <= 0.2 end @testset "Wathen Sparse Matrix" begin println("Executing Test 2.4: Finite Element Matrix - Wathen") A = matrixdepot("wathen", 40) #7601x7601 o = chebydiagonal(A, 4, 22, fn = log) M = Matrix(A) a = diag(log(M)) @test MAPE(a, o) <= 0.2 end end end
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
code
5724
using Test using Random using LinearAlgebra using SparseArrays using JLD2, FileIO using TraceEstimators # Diagonal Approximation method as described by P. Fika works only for SPD matrix with low condition number (< 500) @testset "Diagonal Approximation (P.Fika)" begin Random.seed!(1234323) @testset "Dense SPD Hermitian Matrices" begin @testset "a[i,j] = exp(-2 * abS(i - j)) (small size)" begin println("Executing Test 01: Dense SPD Small Size") A = rand(610, 610) for i in 1:610 for j in 1:610 A[i, j] = exp(-2 * abs(i - j)) end end obv = diagapp(A) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=10) end @testset "a[i,j] = exp(-2 * abS(i - j)) (large size)" begin println("Executing Test 02: Dense SPD Large Size") A = rand(5100, 5100) for i in 1:5100 for j in 1:5100 A[i, j] = exp(-2 * abs(i - j)) end end obv = diagapp(A) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=10) end @testset "Random generated SPD matrix (small size) (N=30)" begin println("Executing Test 03: Random SPD Small Size (N = 30)") A = rand(810, 810) A = A + A' + 30I while isposdef(A) == false A = rand(810, 810) A = A + A' + 30I end obv = diagapp(A) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=10) end @testset "Random generated SPD matrix (small size) (N=60)" begin println("Executing Test 04: Random SPD Small Size (N=60)") A = rand(810, 810) A = A + A' + 30I while isposdef(A) == false A = rand(810, 810) A = A + A' + 30I end obv = diagapp(A) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=10) end @testset "Random generated SPD matrix (large size) (N=30)" begin println("Executing Test 05: Random SPD Large Size") A = rand(5100, 5100) A = A + A' + 300I while isposdef(A) == false A = rand(5100, 5100) A = A + A' + 300I end obv = diagapp(A) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=10) end end @testset "Random generated SPD matrix (large size, large condition number)" begin println("Executing Test 05.5: Random SPD Large Size Larger Condition") A = Symmetric(rand(5005, 5005)) A = A + 10I while isposdef(A) == false A = A + 10I end obv = diagapp(A) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=10) end @testset "Sparse SPD Hermitian Matrices" begin @testset "Random generated Sparse SPD (small size)" begin println("Executing Test 06: Sparse Random SPD Small Size") A = Symmetric(sprand(1000, 1000, 0.7)) A = A+50*I while isposdef(A) == false A = Symmetric(sprand(1000, 1000, 0.7)) A = A+50*I end obv = diagapp(A) A = Matrix(A) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=10) end #= Condition number too large (> 1000) @testset "TopOpt Test (Large Condition Number)" begin println("Executing Test 07: TopOpt Large Condition Number") s = (40, 10) # increase to increase the matrix size xmin = 0.9 # decrease to increase the condition number problem = HalfMBB(Val{:Linear}, s, (1.0, 1.0), 1.0, 0.3, 1.0) solver = FEASolver(Displacement, Direct, problem, xmin = xmin) n = length(solver.vars) solver.vars[rand(1:n, n÷2)] .= 0 solver() K = solver.globalinfo.K obv = diagapp(K) M = Matrix(K) acv = tr(inv(M)) @test isapprox(obv, acv, rtol=10) end =# @testset "TopOpt Test (Modified Condition Number)" begin println("Executing Test 08: TopOpt Modified Condition Number") println("Loading JLD2 file") #= s = (40, 10) # increase to increase the matrix size xmin = 0.9 # decrease to increase the condition number problem = HalfMBB(Val{:Linear}, s, (1.0, 1.0), 1.0, 0.3, 1.0) solver = FEASolver(Displacement, Direct, problem, xmin = xmin) n = length(solver.vars) solver.vars[rand(1:n, n÷2)] .= 0 solver() K = solver.globalinfo.K K = K+1*I =# @load "topoptfile.jld2" K obv = diagapp(K) M = Matrix(K) acv = tr(inv(M)) @test isapprox(obv, acv, rtol=10) end end #= @testset "CuArrays Test" begin @testset "Dense Random CuArray" begin println("Executing Test 09: CuArray Small Size") A = cu(rand(400,400)) A = A+A'+40*I function mycurand(type::Type, size::Int64) cu(rand(type, size)) end function mycurand(range::StepRange{<:Any, <:Any}, size::Int64) cu(rand(range, size)) end obv = diagapp(A, randfunc=mycurand) M = Matrix(A) acv = tr(inv(M)) @test isapprox(obv, acv, rtol=10) end end =# end
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
code
1822
using Test using Random using LinearAlgebra using SparseArrays using MatrixDepot using JLD2, FileIO using MatrixMarket using TraceEstimators @testset "DiagonalApprox" begin Random.seed!(123543) @testset "sprandmatrices" begin println("Executing Test 01: sprand matrix") A = sprand(3000,3000,0.004) A = A + A' + 30I M = Matrix(A) act = tr(inv(M)) obv = tr_inv(A, 4, 20) @test isapprox(act, obv, rtol = 0.2) end @testset "poissonmatrix" begin println("Executing Test 02: poisson matrix") A = matrixdepot("poisson", 50) M = Matrix(A) act = tr(inv(M)) obv = tr_inv(A, 8, 40) @test isapprox(act, obv, rtol = 0.2) end @testset "wathenmatrix" begin println("Executing Test 03: wathen matrix") A = matrixdepot("wathen", 35) M = Matrix(A) act = tr(inv(M)) obv = tr_inv(A, 8, 40, pc = "ilu") @test isapprox(act, obv, rtol = 0.2) end #= @testset "nasa2146" begin println("Executing Test 04: nasa2146 matrix") A = MatrixMarket.mmread("nasa2146.mtx") M = Matrix(A) act = tr(inv(M)) obv = tr_inv(A, 8, 40) @test isapprox(act, obv, rtol = 0.2) end @testset "kuu" begin println("Executing Test 05: kuu matrix") A = MatrixMarket.mmread("Kuu.mtx") M = Matrix(A) act = tr(inv(M)) obv = tr_inv(A, 8, 80) @test isapprox(act, obv, rtol = 0.2) end =# @testset "KMatrix" begin println("Executing Test 06: K matrix (high condition)") @load "topopt902.jld2" K K = SparseMatrixCSC(K) M = Matrix(K) act = tr(inv(M)) obv = tr_inv(K, 8, 150) @test isapprox(act, obv, rtol = 0.2) end end
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
code
6368
using Test using Random using LinearAlgebra using SparseArrays using JLD2, FileIO using TraceEstimators # Most of these tests will focus on Symmetric Positive Definite Matrices with low condition number (< 500) # as Hutchinson method works best for those in its original non-hybrid form. # For other kind of matrices and/or better accuracy Hybrid Hutchinson method or some other method should be used. @testset "Hutchinson" begin Random.seed!(1234323) @testset "Dense SPD Hermitian Matrices" begin @testset "a[i,j] = exp(-2 * abS(i - j)) (small size)" begin println("Executing Test 01: Dense SPD Small Size") A = rand(610, 610) for i in 1:610 for j in 1:610 A[i, j] = exp(-2 * abs(i - j)) end end w = HutchWorkspace(A, N = 20, skipverify = true) obv = hutch!(w) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=10) end @testset "a[i,j] = exp(-2 * abS(i - j)) (large size)" begin println("Executing Test 02: Dense SPD Large Size") A = rand(5100, 5100) for i in 1:5100 for j in 1:5100 A[i, j] = exp(-2 * abs(i - j)) end end w = HutchWorkspace(A, N = 20, skipverify = true) obv = hutch!(w) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=10) end @testset "Random generated SPD matrix (small size) (N=30)" begin println("Executing Test 03: Random SPD Small Size (N = 30)") A = rand(810, 810) A = A + A' + 30I while isposdef(A) == false A = rand(810, 810) A = A + A' + 30I end w = HutchWorkspace(A, N = 30, skipverify = true) obv = hutch!(w) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=10) end @testset "Random generated SPD matrix (small size) (N=60)" begin println("Executing Test 04: Random SPD Small Size (N=60)") A = rand(810, 810) A = A + A' + 30I while isposdef(A) == false A = rand(810, 810) A = A + A' + 30I end w = HutchWorkspace(A, N = 60, skipverify = true) obv = hutch!(w) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=10) end @testset "Random generated SPD matrix (large size) (N=30)" begin println("Executing Test 05: Random SPD Large Size") A = rand(5100, 5100) A = A + A' + 300I while isposdef(A) == false A = rand(5100, 5100) A = A + A' + 300I end w = HutchWorkspace(A, N = 30, skipverify = true) obv = hutch!(w) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=10) end @testset "Random generated SPD matrix (large size, large condition number)" begin println("Executing Test 05.5: Random SPD Large Size Larger Condition") A = Symmetric(rand(5005, 5005)) A = A + 10I while isposdef(A) == false A = A + 10I end w = HutchWorkspace(A, N = 30, skipverify = true) obv = hutch!(w) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=10) end end @testset "Sparse SPD Hermitian Matrices" begin @testset "Random generated Sparse SPD (small size)" begin println("Executing Test 06: Sparse Random SPD Small Size") A = Symmetric(sprand(1000, 1000, 0.7)) A = A+50*I while isposdef(A) == false A = Symmetric(sprand(1000, 1000, 0.7)) A = A+50*I end w = HutchWorkspace(A, N = 30, skipverify = true) obv = hutch!(w) A = Matrix(A) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=10) end #= Condtion Number too large ( > 1000) @testset "TopOpt Test (Large Condition Number)" begin println("Executing Test 07: TopOpt Large Condition Number") s = (40, 10) # increase to increase the matrix size xmin = 0.9 # decrease to increase the condition number problem = HalfMBB(Val{:Linear}, s, (1.0, 1.0), 1.0, 0.3, 1.0) solver = FEASolver(Displacement, Direct, problem, xmin = xmin) n = length(solver.vars) solver.vars[rand(1:n, n÷2)] .= 0 solver() K = solver.globalinfo.K w = HutchWorkspace(K) obv = hutch!(w) M = Matrix(K) acv = tr(inv(M)) @test isapprox(obv, acv, rtol=10) end =# @testset "TopOpt Test (Modified Condition Number)" begin println("Executing Test 08: TopOpt Modified Condition Number") println("Loading from JLD2 file") #= s = (40, 10) # increase to increase the matrix size xmin = 0.9 # decrease to increase the condition number problem = HalfMBB(Val{:Linear}, s, (1.0, 1.0), 1.0, 0.3, 1.0) solver = FEASolver(Displacement, Direct, problem, xmin = xmin) n = length(solver.vars) solver.vars[rand(1:n, n÷2)] .= 0 solver() K = solver.globalinfo.K K = K+1*I =# @load "topoptfile.jld2" K w = HutchWorkspace(K) obv = hutch!(w) M = Matrix(K) acv = tr(inv(M)) @test isapprox(obv, acv, rtol=10) end end #= @testset "CuArrays Test" begin @testset "Dense Random CuArray" begin println("Executing Test 09: CuArray Small Size") A = cu(rand(400,400)) A = A+A'+40*I f(n) = cu(rand(-1.0:2.0:1.0, n)) w = HutchWorkspace(A, f) obv = hutch!(w) M = Matrix(A) acv = tr(inv(M)) @test isapprox(obv, acv, rtol=10) end end =# end
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
code
958
using SafeTestsets using Test using TraceEstimators const METHOD = get(ENV, "METHOD", "all") # SLQ if METHOD in ("all", "slq") println("Running tests for SLQ") @safetestset "slq.jl" begin include("slq.jl") end end # cheby if METHOD in ("all", "chebyhutch") println("Running tests for ChebyHutch") @safetestset "chebyhutch.jl" begin include("chebyhutch.jl") end end # diagonalapprox if METHOD in ("all", "diagonalapprox") println("Running tests for DiagonalApprox") @safetestset "diagonalapprox.jl" begin include("diagonalapprox.jl") end end # Hutchinson if METHOD in ("all", "hutchinson") println("Running tests for Hutchinson") @safetestset "hutchinson.jl" begin include("hutchinson.jl") end end #Diagonal Approximation if METHOD in ("all", "diagapp") println("Running tests for diagapp") @safetestset "diagapp.jl" begin include("diagapp.jl") end end
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
code
3547
using Test using Random using LinearAlgebra using SparseArrays using MatrixDepot using JLD2, FileIO using TraceEstimators @testset "SLQ" begin Random.seed!(123543) @testset "Dense SPD Matrices" begin @testset "a[i,j] = exp(-2 * abS(i - j)) (small size)" begin println("Executing Test 01: Dense SPD - Small Size - Inverse") A = rand(610, 610) for i in 1:610 for j in 1:610 A[i, j] = exp(-2 * abs(i - j)) end end obv = slq(A, fn = inv, ctol = 0.01, eps = 0.05, mtol = 0.01) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=0.01) end @testset "a[i,j] = exp(-2 * abS(i - j)) (large size)" begin println("Executing Test 02: Dense SPD - Large Size - Inverse") A = rand(4610, 4610) for i in 1:4610 for j in 1:4610 A[i, j] = exp(-2 * abs(i - j)) end end obv = slq(A, fn = inv, ctol = 0.01, eps = 0.05, mtol = 0.01) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=0.01) end @testset "Random SPD Matrix (large size)" begin println("Executing Test 03: Random Dense SPD - Large Size - Log") A = rand(4000, 4000) A = A + A' while !isposdef(A) A = A + 30I end A = A + 30I obv = slq(A, fn = log, ctol = 0.01) acv = tr(log(A)) @test isapprox(obv, acv, rtol=0.01) end @testset "Hilbert Matrix" begin println("Executing Test 04: Dense Hilbert SPD - Inverse") A = matrixdepot("hilb", 3000) A = A + I obv = slq(A, fn = inv, ctol = 0.01) acv = tr(inv(A)) @test isapprox(obv, acv, rtol=0.01) end end @testset "Sparse SPD Matrices" begin @testset "Sparse Matrix" begin println("Executing Test 05: Random Sparse Matrix - SQRT") A = sprand(6000, 6000, 0.001) A = A + A' while !isposdef(A) A = A + 60I end obv = slq(A, fn = sqrt, ctol = 0.01) M = Matrix(A) acv = tr(sqrt(M)) @test isapprox(obv, acv, rtol = 0.01) end @testset "Wathen Sparse Matrix" begin println("Executing Test 06: Finite Element Matrix - Wathen") A = matrixdepot("wathen", 40) #7601x7601 obv = slq(A, fn = inv, eps = 0.05) M = Matrix(A) acv = tr(inv(M)) @test isapprox(obv, acv, rtol = 0.1) end @testset "TopOpt Shift +1 Matrix" begin println("Executing Test 07: TopOpt Shift +1") println("Loading from JLD2 file") #= s = (40, 10) # increase to increase the matrix size xmin = 0.9 # decrease to increase the condition number problem = HalfMBB(Val{:Linear}, s, (1.0, 1.0), 1.0, 0.3, 1.0) solver = FEASolver(Displacement, Direct, problem, xmin = xmin) n = length(solver.vars) solver.vars[rand(1:n, n÷2)] .= 0 solver() K = solver.globalinfo.K K = K+1*I =# @load "topoptfile.jld2" K obv = slq(K, fn = inv, eps = 0.005) M = Matrix(K) acv = tr(inv(M)) @test isapprox(obv, acv, rtol=0.01) end end end
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
docs
1112
# TraceEstimators [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://mohamed82008.github.io/TraceEstimators.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://mohamed82008.github.io/TraceEstimators.jl/dev) [![Build Status](https://github.com/mohamed82008/TraceEstimators.jl/workflows/CI/badge.svg)](https://github.com/mohamed82008/TraceEstimators.jl/actions) [![Coverage](https://codecov.io/gh/mohamed82008/TraceEstimators.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/mohamed82008/TraceEstimators.jl) Trace Estimation methods for implicitly available available matrix such as log determinant and inverse of a matrix. Documentation update coming soon. For now these articles should be sufficient. ### Initial Method with Examples https://nextjournal.com/akshayjain/traceEstimator01 ### SLQ and Chebyhutch and speed comparison with examples https://nextjournal.com/akshayjain/traceEstimator02/ ### Trace of Matrix Inverse https://nextjournal.com/akshayjain/traceEstimator03 ### Sparse MVNormal https://nextjournal.com/akshayjain/logdet-via-chebyhutch
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.0
ecd12c7a5efe0941b7334666a9b0c1e3374f29be
docs
125
```@meta CurrentModule = TraceEstimators ``` # TraceEstimators ```@index ``` ```@autodocs Modules = [TraceEstimators] ```
TraceEstimators
https://github.com/mohamed82008/TraceEstimators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
code
889
# Small script to prepare CI testing (see https://github.com/HolyLab/HolyLabRegistry # and https://github.com/HolyLab/ImagineInterface.jl). if VERSION ≥ v"0.7.0" using Pkg end if VERSION < v"1.1.0" using LibGit2 user_regs = joinpath(DEPOT_PATH[1],"registries") mkpath(user_regs) Base.shred!(LibGit2.CachedCredentials()) do creds for (reg, url) in ( "General" => "https://github.com/JuliaRegistries/General.git", "EmmtRegistry" => "https://github.com/emmt/EmmtRegistry") path = joinpath(user_regs, reg); LibGit2.with(Pkg.GitTools.clone( url, path; header = "registry $reg from $(repr(url))", credentials = creds)) do repo end end end else Pkg.Registry.add("General") Pkg.Registry.add(RegistrySpec(url="https://github.com/emmt/EmmtRegistry")) end
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
code
541
using Documenter push!(LOAD_PATH, "../src/") using LinearInterpolators DEPLOYDOCS = (get(ENV, "CI", nothing) == "true") makedocs( sitename = "Linear interpolators for Julia", format = Documenter.HTML( prettyurls = DEPLOYDOCS, ), authors = "Éric Thiébaut and contributors", pages = ["index.md", "install.md", "interpolation.md", "library.md", "notes.md"] ) if DEPLOYDOCS deploydocs( repo = "github.com/emmt/LinearInterpolators.jl.git", ) end
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
code
2751
# # LinearInterpolators.jl - # # Implement various interpolation methods as linear mappings. # #------------------------------------------------------------------------------ # # This file is part of the LinearInterpolators package licensed under the MIT # "Expat" License. # # Copyright (C) 2016-2018, Éric Thiébaut. # module LinearInterpolators # Export public types and methods. Methods like `translate`, `compose`, # `scale`, etc. which are accessible via operators like `+` or `*` or `∘` are # however not exported. export AffineTransform2D, Boundaries, CardinalCubicSpline, CardinalCubicSplinePrime, CatmullRomSpline, CatmullRomSplinePrime, CubicSpline, CubicSplinePrime, Flat, Kernel, KeysSpline, KeysSplinePrime, LanczosKernel, LanczosKernelPrime, LinearSpline, LinearSplinePrime, MitchellNetravaliSpline, MitchellNetravaliSplinePrime, QuadraticSpline, QuadraticSplinePrime, RectangularSpline, RectangularSplinePrime, SafeFlat, SparseInterpolator, SparseUnidimensionalInterpolator, TabulatedInterpolator, TwoDimensionalTransformInterpolator, boundaries, intercept, iscardinal, isnormalized, nameof, rotate using InterpolationKernels import InterpolationKernels: boundaries using TwoDimensional.AffineTransforms using TwoDimensional: AffineTransform2D using LazyAlgebra using LazyAlgebra.Foundations import LazyAlgebra: apply, apply!, vcreate, output_size, input_size, coefficients import Base: eltype, length, size, first, last, clamp, convert """ apply([P=Direct,] ker, x, src) -> dst interpolates source array `src` at positions `x` with interpolation kernel `ker` and yiedls the result as `dst`. Interpolation is equivalent to applying a linear mapping. Optional argument `P` can be `Direct` or `Adjoint` to respectively compute the interpolation or to apply the adjoint of the linear mapping implementing the interpolation. """ apply """ apply!(dst, [P=Direct,] ker, x, src) -> dst overwrites `dst` with the result of interpolating the source array `src` at positions `x` with interpolation kernel `ker`. Optional argument `P` can be `Direct` or `Adjoint`, see [`apply`](@ref) for details. """ apply! function rows end function columns end function fit end function regularize end function regularize! end function inferior end function superior end include("types.jl") include("meta.jl") import .Meta include("boundaries.jl") include("tabulated.jl") using .TabulatedInterpolators include("sparse.jl") using .SparseInterpolators include("unidimensional.jl") using .UnidimensionalInterpolators include("separable.jl") include("nonseparable.jl") include("init.jl") end # module
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
code
5459
# # boundaries -- # # Implement boundary conditions. # #------------------------------------------------------------------------------ # # This file is part of the LinearInterpolators package licensed under the MIT # "Expat" License. # # Copyright (C) 2016-2021, Éric Thiébaut. # eltype(B::Limits) = eltype(typeof(B)) eltype(::Type{<:Limits{T}}) where {T} = T length(B::Limits) = B.len size(B::Limits) = (B.len,) size(B::Limits, i::Integer) = (i == 1 ? B.len : i > 1 ? 1 : throw(BoundsError())) first(B::Limits) = 1 last(B::Limits) = B.len clamp(i, B::Limits) = clamp(i, first(B), last(B)) """ limits(ker, len) -> lim::Limits yields and instance of `Limits` combining the boundary conditions of kernel `ker` with the lengh `len` of the dimension of interpolation in the interpolated array. All interpolation limits inherit from the abstract type `Limits{T}` where `T` is the floating-point type. Interpolation limits are the combination of an extrapolation method and the length of the dimension to interpolate. """ limits limits(::Kernel{T,S,Flat}, len::Integer) where {T,S} = FlatLimits{T}(len) limits(::Kernel{T,S,SafeFlat}, len::Integer) where {T,S} = SafeFlatLimits{T}(prevfloat(T(2 - S/2)), nextfloat(T(len - 1 + S/2)), len) boundaries(::FlatLimits) = Flat boundaries(::SafeFlatLimits) = SafeFlat inferior(B::SafeFlatLimits) = B.inf superior(B::SafeFlatLimits) = B.sup """ getcoefs(ker, lim, x) -> j1, j2, ..., w1, w2, ... yields the indexes of the neighbors and the corresponding interpolation weights for interpolating at position `x` by kernel `ker` with the limits implemented by `lim`. If `x` is not a scalar of the same floating-point type, say `T`, as the kernel `ker`, it is converted to `T` by calling [`LinearInterpolators.convert_coordinate(T,x)`](@ref). This latter method may be extended for non-standard numerical types of `x`. """ getcoefs # The following is ugly (too specific) but necessary to avoid ambiguities. for (B,L) in ((:Flat, :FlatLimits), (:SafeFlat, :SafeFlatLimits),) @eval begin @inline function getcoefs(ker::Kernel{T,S,$B}, lim::$L{T}, x) where {T<:AbstractFloat,S} getcoefs(ker, lim, convert_coordinate(T, x)::T) end end end # Specialized code for S = 1 (i.e., take nearest neighbor). @inline function getcoefs(ker::Kernel{T,1,Flat}, lim::FlatLimits{T}, x::T) where {T<:AbstractFloat} r = round(x) j1 = clamp(trunc(Int, r), lim) w1 = getweights(ker, x - r) return j1, w1 end # For S > 1, code is automatically generated. @generated function getcoefs(ker::Kernel{T,S,Flat}, lim::FlatLimits{T}, x::T) where {T<:AbstractFloat,S} c = ((S + 1) >> 1) J = [Symbol(:j_,i) for i in 1:S] setindices = ([:( $(J[i]) = $(J[c]) - $(c - i) ) for i in 1:c-1]..., [:( $(J[i]) = $(J[c]) + $(i - c) ) for i in c+1:S]...) clampindices = [:( $(J[i]) = clamp($(J[i]), lim) ) for i in 1:S] if isodd(S) nearest = :(f = round(x)) else nearest = :(f = floor(x)) end quote $(Expr(:meta, :inline)) $(nearest) $(J[c]) = trunc(Int, f) $(setindices...) if $(J[1]) < first(lim) || $(J[S]) > last(lim) $(clampindices...) end return ($(J...), getweights(ker, x - f)...) end end @generated function getcoefs(ker::Kernel{T,S,SafeFlat}, lim::SafeFlatLimits{T}, x::T) where {T<:AbstractFloat,S} J = [Symbol(:j_,i) for i in 1:S] W = [Symbol(:w_,i) for i in 1:S] sameindices = [:( $(J[i]) = j ) for i in 1:S] beyondfirst = (:( j = first(lim) ), sameindices..., [:( $(W[i]) = zero(T) ) for i in 1:S-1]..., :( $(W[S]) = one(T) )) beyondlast = (:( j = last(lim) ), sameindices..., :( $(W[1]) = one(T) ), [:( $(W[i]) = zero(T) ) for i in 2:S]...) c = ((S + 1) >> 1) setindices = ([:( $(J[i]) = $(J[c]) - $(c - i) ) for i in 1:c-1]..., [:( $(J[i]) = $(J[c]) + $(i - c) ) for i in c+1:S]...) clampindices = [:( $(J[i]) = clamp($(J[i]), lim) ) for i in 1:S] if isodd(S) nearest = :(f = round(x)) else nearest = :(f = floor(x)) end quote $(Expr(:meta, :inline)) if x ≤ inferior(lim) $(beyondfirst...) elseif x ≥ superior(lim) $(beyondlast...) else $(nearest) $(J[c]) = trunc(Int, f) $(setindices...) if $(J[1]) < first(lim) || $(J[S]) > last(lim) $(clampindices...) end $(Expr(:tuple, W...)) = getweights(ker, x - f) end return ($(J...), $(W...)) end end """ LinearInterpolators.convert_coordinate(T, c) -> x::T yields interpolation coordinate `c` to floating-point type `T`. The default behavior is to yield `convert(T,c)` but this method may be extended to cope with non-standard numeric types. """ convert_coordinate(T::Type{<:AbstractFloat}, c::Number) = convert(T, c)
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
code
397
using Requires function __init__() @require Unitful="1986cc42-f94f-5a68-af5c-568840ba703d" begin # FIXME: Should be restricted to dimensionless quantities because the # argument of a kernel function is in units of the interpolation grid # step size. convert_coordinate(T::Type{<:AbstractFloat}, c::Unitful.Quantity) = convert(T, c.val) end end
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
code
5334
# # meta.jl -- # # Functions to generate code for interpolation methods. # #------------------------------------------------------------------------------ # # This file is part of the LinearInterpolators package licensed under the MIT # "Expat" License. # # Copyright (C) 2016-2021, Éric Thiébaut. # module Meta const Arg = Union{Number,Symbol,Expr} #""" #```julia #@getcoefs N j w ker lim pos #``` # #yields the code for extracting the interpolation coefficients, `N` is the #interpolation kernel size, `j` and `w` are prefixes for the variables to store #the indices and weights for interpolation (the actual variable names are given #by appending a `_i` suffix for `i` in `1:N`), `ker` is the interpolation #kernel, `lim` are the limits and `pos` is the position of interpolation. # #""" #macro getcoefs(N, j, w, ker, lim, pos) # generate_getcoefs(N, j, w, ker, lim, pos) #end # #macro nonsep_interp(alpha, src, beta, dst, # s1, ker1, lim1, pos1, # s2, ker2, lim2, pos2) # return generate_nonsep_interp(alpha, src, beta, dst, # s1, ker1, lim1, pos1, # s2, ker2, lim2, pos2) #end # #macro nonsep_interp_adj(src, dst, # s1, ker1, lim1, pos1, # s2, ker2, lim2, pos2) # return generate_nonsep_interp_adj(src, dst, # s1, ker1, lim1, pos1, # s2, ker2, lim2, pos2) #end """ generate_getcoefs(n, j, w, ker, lim, pos) generates the code for getting the interpolation coefficients. Here `n` is the size of `ker` the interpolation kernel, `j` and `w` are symbols or strings used as prefixes for local variables to store the interpolation indices and weights respectively, `ker` and `lim` are symbols with the name of the local variables which store the interpolation kernel and the limits along the dimension of interpolation, `pos` is a symbol or an expression which gives the position to interpolate. For instance: generate_getcoefs(2, :i, :c, :kr, :lm, :(x[i])) -> :((i_1, i_2, c_1, c_2) = getcoefs(kr, lm, x[i])) Another possibility is: generate_getcoefs(J, W, ker, lim, pos) where `J` and `W` are vectors of length `n`, the size of `ker` the interpolation kernel, with the symbolic names of the local variables to store the interpolation indices and weights respectively. """ function generate_getcoefs(n::Integer, j::Union{AbstractString,Symbol}, w::Union{AbstractString,Symbol}, ker::Symbol, lim::Symbol, pos::Arg) return generate_getcoefs([Symbol(j,"_",s) for s in 1:n], [Symbol(w,"_",s) for s in 1:n], ker, lim, pos) end function generate_getcoefs(J::AbstractVector{Symbol}, W::AbstractVector{Symbol}, ker::Symbol, lim::Symbol, pos::Arg) @assert length(J) == length(W) vars = Expr(:tuple, J..., W...) return :($vars = getcoefs($ker, $lim, $pos)) end """ generate_sum(ex) generates an expression whose result is the sum of the elements of the vector `ex` which are symbols (being interpreted as the name of variables) or expressions. """ generate_sum(args::Arg...) = generate_sum(args) generate_sum(ex::Union{AbstractVector,Tuple{Vararg{Arg}}}) = (length(ex) == 1 ? ex[1] : Expr(:call, :+, ex...)) """ group_expressions(ex...) -> code generates a single expression from all expressions given in argument. The result may be the same as the input if it is a single expression or a block of expressions if several expressions are specified. To insert the result as a block of statements (like a `begin` ... `end` block) in a quoted expression, write something like: quote some_pre_code \$code some_post_code end To strip the surrounding `begin` ... `end` keywords, write instead: quote some_pre_code \$(code.args...) some_post_code end """ group_expressions(args::Expr...) = group_expressions(args) group_expressions(ex::Union{AbstractVector{Expr},Tuple{Vararg{Expr}}}) = (length(ex) == 1 ? ex[1] : Expr(:block, ex...)) function generate_interp_expr(arr::Symbol, J::AbstractVector{Symbol}, W::AbstractVector{Symbol}) @assert length(J) == length(W) return generate_sum([:($arr[$(J[i])]*$(W[i])) for i in 1:length(J)]) end function generate_interp_expr(arr::Symbol, J::AbstractVector{Symbol}, W::AbstractVector{Symbol}, inds::Arg) @assert length(J) == length(W) return generate_sum([:($arr[$(J[i]),$inds]*$(W[i])) for i in 1:length(J)]) end function generate_interp_expr(arr::Symbol, J1::AbstractVector{Symbol}, W1::AbstractVector{Symbol}, J2::AbstractVector{Symbol}, W2::AbstractVector{Symbol}) @assert length(J2) == length(W2) n = length(J2) ex = Array{Expr}(undef, n) for i in 1:n sub = generate_interp_expr(arr, J1, W1, J2[i]) ex[i] = :($sub*$(W2[i])) end return generate_sum(ex) end end # module
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
code
9103
# # nonseparable.jl -- # # Non-separable multidimensional interpolation. # #------------------------------------------------------------------------------ # # This file is part of the LinearInterpolators package licensed under the MIT # "Expat" License. # # Copyright (C) 2016-2021, Éric Thiébaut. # # FIXME: if axes are aligned, use separable interpolation. """ TwoDimensionalTransformInterpolator(rows, cols, ker1, ker2, R) yields a linear mapping which interpolates its input of size `cols` to produce an output of size `rows` by 2-dimensional interpolation with kernels `ker1` and `ker2` along each dimension and applying the affine coordinate transform specified by `R`. As a shortcut: TwoDimensionalTransformInterpolator(rows, cols, ker, R) is equivalent to `TwoDimensionalTransformInterpolator(rows,cols,ker,ker,R)` that is the same kernel is used along all dimensions. """ TwoDimensionalTransformInterpolator struct TwoDimensionalTransformInterpolator{T<:AbstractFloat, K1<:Kernel{T}, K2<:Kernel{T}} <: LinearMapping rows::Dims{2} cols::Dims{2} ker1::K1 ker2::K2 R::AffineTransform2D{T} end function TwoDimensionalTransformInterpolator(rows::Dims{2}, cols::Dims{2}, ker::Kernel, R::AffineTransform2D) TwoDimensionalTransformInterpolator(rows, cols, ker, ker, R) end function TwoDimensionalTransformInterpolator(rows::Dims{2}, cols::Dims{2}, ker1::Kernel{T1}, ker2::Kernel{T2}, R::AffineTransform2D{Tr}) where {T1,T2,Tr} T = promote_type(T1, T2, Tr) TwoDimensionalTransformInterpolator(rows, cols, convert(Kernel{T}, ker1), convert(Kernel{T}, ker2), convert(AffineTransform2D{T}, R)) end # TODO: Replace assertions by error messages. input_size(A::TwoDimensionalTransformInterpolator) = A.cols output_size(A::TwoDimensionalTransformInterpolator) = A.rows function vcreate(::Type{Direct}, A::TwoDimensionalTransformInterpolator{T}, x::AbstractArray{T,2}, scratch::Bool = false) where {T} # Checking x is done by apply! Array{T,2}(undef, A.rows) end function vcreate(::Type{Adjoint}, A::TwoDimensionalTransformInterpolator{T}, x::AbstractArray{T,2}, scratch::Bool = false) where {T} # Checking x is done by apply! Array{T,2}(undef, A.cols) end function apply!(α::Real, ::Type{Direct}, A::TwoDimensionalTransformInterpolator{T}, x::AbstractArray{T,2}, scratch::Bool, β::Real, y::AbstractArray{T,2},) where {T} @assert !Base.has_offset_axes(x, y) @assert size(x) == A.cols @assert size(y) == A.rows apply!(α, Direct, A.ker1, A.ker2, A.R, x, β, y) end function apply!(α::Real, ::Type{Adjoint}, A::TwoDimensionalTransformInterpolator{T}, x::AbstractArray{T,2}, scratch::Bool, β::Real, y::AbstractArray{T,2},) where {T} @assert !Base.has_offset_axes(x, y) @assert size(x) == A.rows @assert size(y) == A.cols apply!(α, Adjoint, A.ker1, A.ker2, A.R, x, β, y) end # Provide default Direct operation. function apply!(dst::AbstractArray{T,2}, ker::Kernel{T}, R::AffineTransform2D{T}, src::AbstractArray{T,2}) where {T} apply!(dst, Direct, ker, R, src) end function apply!(dst::AbstractArray{T,2}, ker1::Kernel{T}, ker2::Kernel{T}, R::AffineTransform2D{T}, src::AbstractArray{T,2}) where {T} return apply!(dst, Direct, ker1, ker2, R, src) end # Provide default α=1 and β=0 factors. function apply!(dst::AbstractArray{T,2}, ::Type{P}, ker::Kernel{T}, R::AffineTransform2D{T}, src::AbstractArray{T,2}) where {P<:Operations,T} return apply!(1, P, ker, R, src, 0, dst) end function apply!(dst::AbstractArray{T,2}, ::Type{P}, ker1::Kernel{T}, ker2::Kernel{T}, R::AffineTransform2D{T}, src::AbstractArray{T,2}) where {P<:Operations,T} return apply!(1, P, ker1, ker2, R, src, 0, dst) end # Provide default pair of kernels (ker1,ker2) = ker. function apply!(α::Real, ::Type{P}, ker::Kernel{T}, R::AffineTransform2D{T}, src::AbstractArray{T,2}, β::Real, dst::AbstractArray{T,2}) where {P<:Operations,T} return apply!(α, P, ker, ker, R, src, β, dst) end @generated function apply!(α::Real, ::Type{Direct}, ker1::Kernel{T,S1}, ker2::Kernel{T,S2}, R::AffineTransform2D{T}, src::AbstractArray{T,2}, β::Real, dst::AbstractArray{T,2}) where {T<:AbstractFloat, S1,S2} # Generate pieces of code. J1 = [Symbol(:j1_,s) for s in 1:S1] W1 = [Symbol(:w1_,s) for s in 1:S1] J2 = [Symbol(:j2_,s) for s in 1:S2] W2 = [Symbol(:w2_,s) for s in 1:S2] code2 = (:( pos2 = convert(T, i2) ), :( off1 = R.xy*pos2 + R.x ), :( off2 = R.yy*pos2 + R.y )) code1 = (:( pos1 = convert(T, i1) ), Meta.generate_getcoefs(J1, W1, :ker1, :lim1, :(R.xx*pos1 + off1)), Meta.generate_getcoefs(J2, W2, :ker2, :lim2, :(R.yx*pos1 + off2))) expr = Meta.generate_interp_expr(:src, J1, W1, J2, W2) quote if α == 0 # Just scale destination. vscale!(dst, β) else # Get dimensions and limits. n1, n2 = size(dst) lim1 = limits(ker1, size(src, 1)) lim2 = limits(ker2, size(src, 2)) # Apply the operator considering the specific values of α and β. if α == 1 && β == 0 for i2 in 1:n2 $(code2...) @inbounds for i1 in 1:n1 $(code1...) dst[i1,i2] = $expr end end else alpha = convert(T, α) beta = convert(T, β) for i2 in 1:n2 $(code2...) @inbounds for i1 in 1:n1 $(code1...) dst[i1,i2] = $expr*alpha + dst[i1,i2]*beta end end end end return dst end end @generated function apply!(α::Real, ::Type{Adjoint}, ker1::Kernel{T,S1}, ker2::Kernel{T,S2}, R::AffineTransform2D{T}, src::AbstractArray{T,2}, β::Real, dst::AbstractArray{T,2}) where{T<:AbstractFloat, S1,S2} # Generate pieces of code. J1 = [Symbol(:j1_,s) for s in 1:S1] W1 = [Symbol(:w1_,s) for s in 1:S1] J2 = [Symbol(:j2_,s) for s in 1:S2] W2 = [Symbol(:w2_,s) for s in 1:S2] temp = [Symbol(:tmp_,s) for s in 1:S2] code2 = (:( pos2 = convert(T, i2) ), :( off1 = R.xy*pos2 + R.x ), :( off2 = R.yy*pos2 + R.y )) code1 = [:( pos1 = convert(T, i1) ), Meta.generate_getcoefs(J1, W1, :ker1, :lim1, :(R.xx*pos1 + off1)), Meta.generate_getcoefs(J2, W2, :ker2, :lim2, :(R.yx*pos1 + off2))] for i2 in 1:S2 push!(code1, :( $(temp[i2]) = $(W2[i2])*val )) for i1 in 1:S1 push!(code1, :( dst[$(J1[i1]),$(J2[i2])] += $(W1[i1])*$(temp[i2]) )) end end quote # Pres-scale or zero destination. vscale!(dst, β) # Get dimensions and limits. n1, n2 = size(src) lim1 = limits(ker1, size(dst, 1)) lim2 = limits(ker2, size(dst, 2)) # Apply adjoint operator. if α == 1 for i2 in 1:n2 $(code2...) @inbounds for i1 in 1:n1 val = src[i1,i2] $(code1...) end end elseif α != 0 alpha = convert(T, α) for i2 in 1:n2 $(code2...) @inbounds for i1 in 1:n1 val = alpha*src[i1,i2] $(code1...) end end end return dst end end
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
code
5314
# # separable.jl -- # # Separable Multidimensional interpolation. # #------------------------------------------------------------------------------ # # This file is part of the LinearInterpolators package licensed under the MIT # "Expat" License. # # Copyright (C) 2016-2021, Éric Thiébaut. # # FIXME: use a table for the innermost dimensions! function apply!(dst::AbstractArray{T,2}, ker::Kernel{T,S}, x1::AbstractVector{T}, x2::AbstractVector{T}, src::AbstractArray{T,2}) where {T,S} apply!(1, Direct, ker, x1, ker, x2, src, 0, dst) end function apply!(dst::AbstractArray{T,2}, ::Type{P}, ker::Kernel{T,S}, x1::AbstractVector{T}, x2::AbstractVector{T}, src::AbstractArray{T,2}) where {P<:Union{Direct,Adjoint},T,S} apply!(1, P, ker, x1, ker, x2, src, 0, dst) end function apply!(dst::AbstractArray{T,2}, ker1::Kernel{T,S1}, x1::AbstractVector{T}, ker2::Kernel{T,S2}, x2::AbstractVector{T}, src::AbstractArray{T,2}) where {T,S1,S2} return apply!(1, Direct, ker1, x1, ker2, x2, src, 0, dst) end function apply!(dst::AbstractArray{T,2}, ::Type{P}, ker1::Kernel{T,S1}, x1::AbstractVector{T}, ker2::Kernel{T,S2}, x2::AbstractVector{T}, src::AbstractArray{T,2}) where {P<:Union{Direct,Adjoint}, T,S1,S2} return apply!(1, P, ker1, x1, ker2, x2, src, 0, dst) end #------------------------------------------------------------------------------ # Direct operations. @generated function apply!(α::Real, ::Type{Direct}, ker1::Kernel{T,S1}, x1::AbstractVector{T}, ker2::Kernel{T,S2}, x2::AbstractVector{T}, src::AbstractArray{T,2}, β::Real, dst::AbstractArray{T,2}) where {T,S1,S2} # Generate pieces of code. J1 = [Symbol(:j1_,s) for s in 1:S1] W1 = [Symbol(:w1_,s) for s in 1:S1] J2 = [Symbol(:j2_,s) for s in 1:S2] W2 = [Symbol(:w2_,s) for s in 1:S2] code1 = (Meta.generate_getcoefs(J1, W1, :ker1, :lim1, :(x1[i1])),) code2 = (Meta.generate_getcoefs(J2, W2, :ker2, :lim2, :(x2[i2])), [:( $(W2[i]) *= alpha ) for i in 1:S2]...) expr = Meta.generate_interp_expr(:src, J1, W1, J2, W2) quote # Get dimensions and limits. @assert size(dst) == (length(x1), length(x2)) n1, n2 = size(dst) lim1 = limits(ker1, size(src, 1)) lim2 = limits(ker2, size(src, 2)) # Apply direct operator. if α == 0 vscale!(dst, β) elseif β == 0 alpha = convert(T, α) @inbounds for i2 in 1:n2 $(code2...) for i1 in 1:n1 $(code1...) dst[i1,i2] = $expr end end else alpha = convert(T, α) beta = convert(T, β) @inbounds for i2 in 1:n2 $(code2...) for i1 in 1:n1 $(code1...) dst[i1,i2] = $expr + beta*dst[i1,i2] end end end return dst end end #------------------------------------------------------------------------------ # In-place adjoint operation. @generated function apply!(α::Real, ::Type{Adjoint}, ker1::Kernel{T,S1}, x1::AbstractVector{T}, ker2::Kernel{T,S2}, x2::AbstractVector{T}, src::AbstractArray{T,2}, β::Real, dst::AbstractArray{T,2}) where {T<:AbstractFloat, S1,S2} # Generate pieces of code. J1 = [Symbol(:j1_,s) for s in 1:S1] W1 = [Symbol(:w1_,s) for s in 1:S1] J2 = [Symbol(:j2_,s) for s in 1:S2] W2 = [Symbol(:w2_,s) for s in 1:S2] temp = [Symbol(:tmp_,s) for s in 1:S2] code1 = [Meta.generate_getcoefs(J1, W1, :ker1, :lim1, :(x1[i1]))] code2 = [Meta.generate_getcoefs(J2, W2, :ker2, :lim2, :(x2[i2]))] for i2 in 1:S2 push!(code1, :( $(temp[i2]) = $(W2[i2])*val )) for i1 in 1:S1 push!(code1, :( dst[$(J1[i1]),$(J2[i2])] += $(W1[i1])*$(temp[i2]) )) end end quote # Get dimensions and limits. @assert size(src) == (length(x1), length(x2)) n1, n2 = size(src) lim1 = limits(ker1, size(dst, 1)) lim2 = limits(ker2, size(dst, 2)) # Apply adjoint operator. vscale!(dst, β) if α != 0 alpha = convert(T, α) @inbounds for i2 in 1:n2 $(code2...) for i1 in 1:n1 val = src[i1,i2]*alpha $(code1...) end end end return dst end end
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
code
27225
# # interp/sparse.jl -- # # Implement sparse linear interpolator. # #------------------------------------------------------------------------------ # # This file is part of the LinearInterpolators package licensed under the MIT # "Expat" License. # # Copyright (C) 2015-2016, Éric Thiébaut, Jonathan Léger & Matthew Ozon. # Copyright (C) 2016-2021, Éric Thiébaut. # # All code is in a module to "hide" private methods. module SparseInterpolators export SparseInterpolator, SparseUnidimensionalInterpolator using InterpolationKernels using LazyAlgebra using LazyAlgebra.Foundations import LazyAlgebra: apply, apply!, vcreate, output_size, input_size import Base: axes, eltype, size import SparseArrays: sparse using ..LinearInterpolators using ..LinearInterpolators: limits, getcoefs import ..LinearInterpolators.Meta import ..LinearInterpolators: coefficients, columns, rows, fit, regularize, regularize! abstract type AbstractSparseInterpolator{T<:AbstractFloat} <: LinearMapping end eltype(A::AbstractSparseInterpolator) = eltype(typeof(A)) eltype(::Type{<:AbstractSparseInterpolator{T}}) where {T} = T struct SparseInterpolator{T<:AbstractFloat,S,N} <: AbstractSparseInterpolator{T} C::Vector{T} J::Vector{Int} nrows::Int ncols::Int dims::Dims{N} # dimensions of result function SparseInterpolator{T,S,N}(C::Vector{T}, J::Vector{Int}, dims::Dims{N}, ncols::Int) where {T,S,N} @assert S ≥ 1 @assert minimum(dims) ≥ 1 nrows = prod(dims) nvals = S*nrows # number of non-zero coefficients @assert length(C) == nvals @assert length(J) == nvals new{T,S,N}(C, J, nrows, ncols, dims) end end # Interpolator can be used as a function. (A::SparseInterpolator)(x::AbstractVector) = apply(A, x) output_size(A::SparseInterpolator) = A.dims input_size(A::SparseInterpolator) = (A.ncols,) width(A::SparseInterpolator{T,S,N}) where {T,S,N} = S coefficients(A::SparseInterpolator) = A.C columns(A::SparseInterpolator) = A.J function rows(A::SparseInterpolator{T,S,N}) where {T,S,N} nrows = A.nrows nvals = S*nrows # number of non-zero coefficients @assert length(A.C) == nvals @assert length(A.J) == nvals I = Array{Int}(undef, nvals) k0 = 0 for i in 1:nrows for s in 1:S k = k0 + s @inbounds I[k] = i end k0 += S end return I end # Convert to a sparse matrix. sparse(A::SparseInterpolator) = sparse(rows(A), columns(A), coefficients(A), A.nrows, A.ncols) """ A = SparseInterpolator{T=eltype(ker)}(ker, pos, grd) yields a sparse linear interpolator suitable for interpolating with kernel `ker` at positions `pos` a function sampled on the grid `grd`. Optional parameter `T` is the floating-point type of the coefficients of the operator `A`. Call `eltype(A)` to query the type of the coefficients of the sparse interpolator `A`. Then `y = apply(A, x)` or `y = A(x)` or `y = A*x` yield the result of interpolation array `x`. The shape of `y` is the same as that of `pos`. Formally, this amounts to computing: y[i] = sum_j ker((pos[i] - grd[j])/step(grd))*x[j] with `step(grd)` the (constant) step size between the nodes of the grid `grd` and `grd[j]` the `j`-th position of the grid. """ SparseInterpolator(ker::Kernel{T}, args...) where {T<:AbstractFloat} = SparseInterpolator{T}(ker, args...) @deprecate SparseInterpolator(T::Type{<:AbstractFloat}, ker::Kernel, args...) SparseInterpolator{T}(ker, args...) SparseInterpolator{T}(ker::Kernel, args...) where {T<:AbstractFloat} = SparseInterpolator{T}(T(ker), args...) function SparseInterpolator{T}(ker::Kernel{T}, pos::AbstractArray{<:Real}, grd::AbstractRange) where {T<:AbstractFloat} SparseInterpolator{T}(ker, fractional_index(T, pos, grd), CartesianIndices(axes(pos)), length(grd)) end function SparseInterpolator{T}(ker::Kernel{T}, pos::AbstractArray{<:Real}, len::Integer) where {T<:AbstractFloat} SparseInterpolator{T}(ker, fractional_index(T, pos), CartesianIndices(axes(pos)), len) end function SparseInterpolator{T}(ker::Kernel{T,S}, f::Function, R::CartesianIndices{N}, ncols::Integer) where {T<:AbstractFloat,S,N} C, J = _sparsecoefs(R, Int(ncols), ker, f) return SparseInterpolator{T,S,N}(C, J, size(R), ncols) end @generated function _sparsecoefs(R::CartesianIndices{N}, ncols::Int, ker::Kernel{T,S}, f::Function) where {T,S,N} J_ = [Symbol(:j_,s) for s in 1:S] C_ = [Symbol(:c_,s) for s in 1:S] code = (Meta.generate_getcoefs(J_, C_, :ker, :lim, :x), [:( J[k+$s] = $(J_[s]) ) for s in 1:S]..., [:( C[k+$s] = $(C_[s]) ) for s in 1:S]...) quote lim = limits(ker, ncols) nvals = S*length(R) J = Array{Int}(undef, nvals) C = Array{T}(undef, nvals) k = 0 @inbounds for i in R x = convert(T, f(i)) $(code...) k += S end return C, J end end function _check(A::SparseInterpolator{T,S,N}, out::AbstractArray{T,N}, inp::AbstractVector{T}) where {T,S,N} nvals = S*A.nrows # number of non-zero coefficients J, ncols = A.J, A.ncols length(A.C) == nvals || error("corrupted sparse interpolator (bad number of coefficients)") length(J) == nvals || error("corrupted sparse interpolator (bad number of indices)") length(inp) == ncols || error("bad vector length (expecting $(A.ncols), got $(length(inp)))") size(out) == A.dims || error("bad output array size (expecting $(A.dims), got $(size(out)))") length(out) == A.nrows || error("corrupted sparse interpolator (bad number of \"rows\")") @inbounds for k in 1:nvals 1 ≤ J[k] ≤ ncols || error("corrupted sparse interpolator (out of bound indices)") end end function vcreate(::Type{Direct}, A::SparseInterpolator{T,S,N}, x::AbstractVector{T}, scratch::Bool=false) where {T,S,N} return Array{T}(undef, output_size(A)) end function vcreate(::Type{Adjoint}, A::SparseInterpolator{T,S,N}, x::AbstractArray{T,N}, scratch::Bool=false) where {T,S,N} return Array{T}(undef, input_size(A)) end function apply!(α::Real, ::Type{Direct}, A::SparseInterpolator{Ta,S,N}, x::AbstractVector{Tx}, scratch::Bool, β::Real, y::AbstractArray{Ty,N}) where {Ta,Tx<:Real, Ty<:AbstractFloat,S,N} _check(A, y, x) if α == 0 vscale!(y, β) else T = float(promote_type(Ta, Tx)) alpha = convert(T, α) nrows, ncols = A.nrows, A.ncols C, J = coefficients(A), columns(A) k0 = 0 if β == 0 @inbounds for i in 1:nrows sum = zero(T) @simd for s in 1:S k = k0 + s j = J[k] sum += C[k]*x[j] end y[i] = alpha*sum k0 += S end else beta = convert(Ty, β) @inbounds for i in 1:nrows sum = zero(T) @simd for s in 1:S k = k0 + s j = J[k] sum += C[k]*x[j] end y[i] = alpha*sum + beta*y[i] k0 += S end end end return y end function apply!(α::Real, ::Type{Adjoint}, A::SparseInterpolator{Ta,S,N}, x::AbstractArray{Tx,N}, scratch::Bool, β::Real, y::AbstractVector{Ty}) where {Ta,Tx<:Real, Ty<:AbstractFloat,S,N} _check(A, x, y) vscale!(y, β) if α != 0 T = float(promote_type(Ta, Tx)) alpha = convert(T, α) nrows, ncols = A.nrows, A.ncols C, J = coefficients(A), columns(A) k0 = 0 @inbounds for i in 1:nrows c = alpha*x[i] if c != 0 @simd for s in 1:S k = k0 + s j = J[k] y[j] += C[k]*c end end k0 += S end end return y end """ `AtWA(A,w)` yields the matrix `A'*W*A` from a sparse linear operator `A` and weights `W = diag(w)`. """ function AtWA(A::SparseInterpolator{T,S,N}, w::AbstractArray{T,N}) where {T,S,N} ncols = A.ncols AtWA!(Array{T}(undef, ncols, ncols), A, w) end """ `AtA(A)` yields the matrix `A'*A` from a sparse linear operator `A`. """ function AtA(A::SparseInterpolator{T,S,N}) where {T,S,N} ncols = A.ncols AtA!(Array{T}(undef, ncols, ncols), A) end # Build the `A'*A` matrix from a sparse linear operator `A`. function AtA!(dst::AbstractArray{T,2}, A::SparseInterpolator{T,S,N}) where {T,S,N} nrows, ncols = A.nrows, A.ncols @assert size(dst) == (ncols, ncols) fill!(dst, zero(T)) C, J = coefficients(A), columns(A) k0 = 0 @assert length(J) == length(C) @inbounds for i in 1:nrows for s in 1:S k = k0 + s 1 ≤ J[k] ≤ ncols || error("corrupted interpolator table") end for s1 in 1:S k1 = k0 + s1 j1, c1 = J[k1], C[k1] @simd for s2 in 1:S k2 = k0 + s2 j2, c2 = J[k2], C[k2] dst[j1,j2] += c1*c2 end end k0 += S end return dst end # Build the `A'*W*A` matrix from a sparse linear operator `A` and weights `W`. function AtWA!(dst::AbstractArray{T,2}, A::SparseInterpolator{T,S,N}, wgt::AbstractArray{T,N}) where {T,S,N} nrows, ncols = A.nrows, A.ncols @assert size(dst) == (ncols, ncols) @assert size(wgt) == output_size(A) fill!(dst, zero(T)) C, J = coefficients(A), columns(A) k0 = 0 @assert length(J) == length(C) @inbounds for i in 1:nrows for s in 1:S k = k0 + s 1 ≤ J[k] ≤ ncols || error("corrupted interpolator table") end w = wgt[i] for s1 in 1:S k1 = k0 + s1 j1 = J[k1] wc1 = w*C[k1] @simd for s2 in 1:S k2 = k0 + s2 j2 = J[k2] dst[j1,j2] += C[k2]*wc1 end end k0 += S end return dst end # Default regularization levels. const RGL_EPS = 1e-9 const RGL_MU = 0.0 """ fit(A, y [, w]; epsilon=1e-9, mu=0.0) -> x performs a linear fit of `y` by the model `A*x` with `A` a linear interpolator. The returned value `x` minimizes: sum(w.*(A*x - y).^2) where `w` are given weights. If `w` is not specified, all weights are assumed to be equal to one; otherwise `w` must be an array of nonnegative values and of same size as `y`. Keywords `epsilon` and `mu` may be specified to regularize the solution and minimize: sum(w.*(A*x - y).^2) + rho*(epsilon*norm(x)^2 + mu*norm(D*x)^2) where `D` is a finite difference operator, `rho` is the maximum diagonal element of `A'*diag(w)*A` and `norm` is the Euclidean norm. """ function fit(A::SparseInterpolator{T,S,N}, y::AbstractArray{T,N}, w::AbstractArray{T,N}; epsilon::Real = RGL_EPS, mu::Real = RGL_MU) where {T,S,N} @assert size(y) == output_size(A) @assert size(w) == size(y) # Compute RHS vector A'*W*y with W = diag(w). rhs = A'*(w.*y) # Compute LHS matrix A'*W*A with W = diag(w). lhs = AtWA(A, w) # Regularize a bit. regularize!(lhs, epsilon, mu) # Solve the linear equations. cholfact!(lhs,:U,Val{true})\rhs end function fit(A::SparseInterpolator{T,S,N}, y::AbstractArray{T,N}; epsilon::Real = RGL_EPS, mu::Real = RGL_MU) where {T,S,N} @assert size(y) == output_size(A) @assert size(w) == size(y) # Compute RHS vector A'*y. rhs = A'*y # Compute LHS matrix A'*W*A with W = diag(w). lhs = AtA(A) # Regularize a bit. regularize!(lhs, epsilon, mu) # Solve the linear equations. cholfact!(lhs,:U,Val{true})\rhs end """ regularize(A, ϵ, μ) -> R regularizes the symmetric matrix `A` to produce the matrix: R = A + ρ*(ϵ*I + μ*D'*D) where `I` is the identity, `D` is a finite difference operator and `ρ` is the maximum diagonal element of `A`. """ regularize(A::AbstractArray{T,2}, args...) where {T<:AbstractFloat} = regularize!(copyto!(Array{T}(undef, size(A)), A), args...) """ regularize!(A, ϵ, μ) -> A stores the regularized matrix in `A` (and returns it). This is the in-place version of [`LinearInterpolators.SparseInterpolators.regularize`]. """ function regularize!(A::AbstractArray{T,2}, eps::Real = RGL_EPS, mu::Real = RGL_MU) where {T<:AbstractFloat} regularize!(A, T(eps), T(mu)) end function regularize!(A::AbstractArray{T,2}, eps::T, mu::T) where {T<:AbstractFloat} local rho::T @assert eps ≥ zero(T) @assert mu ≥ zero(T) @assert size(A,1) == size(A,2) n = size(A,1) if eps > zero(T) || mu > zero(T) rho = A[1,1] for j in 2:n d = A[j,j] rho = max(rho, d) end rho > zero(T) || error("we have a problem!") end if eps > zero(T) q = eps*rho for j in 1:n A[j,j] += q end end if mu > zero(T) q = rho*mu if n ≥ 2 r = q + q A[1,1] += q A[2,1] -= q for i in 2:n-1 A[i-1,i] -= q A[i, i] += r A[i+1,i] -= q end A[n-1,n] -= q A[n, n] += q elseif n == 1 A[1,1] += q end end return A end # Yields a function that takes an index and returns the corresponding # interpolation position as fractional index into the source array. function fractional_index(T::Type{<:AbstractFloat}, pos::AbstractArray{<:Real}, grd::AbstractRange) # Use the central position of the grid to minimize rounding errors. c = (convert(T, first(grd)) + convert(T, last(grd)))/2 q = 1/convert(T, step(grd)) r = convert(T, 1 + length(grd))/2 return i -> q*(convert(T, pos[i]) - c) + r end function fractional_index(T::Type{<:AbstractFloat}, pos::AbstractArray{<:Real}) return i -> T(pos[i]) end #------------------------------------------------------------------------------ """ SparseUnidimensionalInterpolator{T<:AbstractFloat,S,D} <: AbstractSparseInterpolator{T} * `T` is the floating-point type of the coefficients, * `S` is the size of the kernel (number of nodes to combine for a single interpolator) * `D` is the dimension of interpolation. """ struct SparseUnidimensionalInterpolator{T<:AbstractFloat,S,D} <: AbstractSparseInterpolator{T} nrows::Int # number of rows ncols::Int # number of columns C::Vector{T} # coefficients along the dimension of interpolation J::Vector{Int} # columns indices along the dimension of interpolation end (A::SparseUnidimensionalInterpolator)(x) = apply(A, x) interp_dim(::SparseUnidimensionalInterpolator{T,S,D}) where {T,S,D} = D coefficients(A::SparseUnidimensionalInterpolator) = A.C columns(A::SparseUnidimensionalInterpolator) = A.J size(A::SparseUnidimensionalInterpolator) = (A.nrows, A.ncols) size(A::SparseUnidimensionalInterpolator, i::Integer) = (i == 1 ? A.nrows : i == 2 ? A.ncols : error("out of bounds dimension")) """ SparseUnidimensionalInterpolator{T=eltype(ker)}(ker, d, pos, grd) yields a linear mapping which interpolates the `d`-th dimension of an array with kernel `ker` at positions `pos` along the dimension of interpolation `d` and assuming the input array has grid coordinates `grd` along the the `d`-th dimension of interpolation. Argument `pos` is a vector of positions, argument `grd` may be a range or the length of the dimension of interpolation. Optional parameter `T` is the floating-point type of the coefficients of the operator. This kind of interpolator is suitable for separable multi-dimensional interpolation with precomputed interpolation coefficients. Having precomputed coefficients is mostly interesting when the operator is to be applied multiple times (for instance in iterative methods). Otherwise, separable operators which compute the coefficients *on the fly* may be preferable. A combination of instances of `SparseUnidimensionalInterpolator` can be built to achieve sperable multi-dimensional interpolation. For example: using LinearInterpolators ker = CatmullRomSpline() n1, n2 = 70, 50 x1 = linspace(1, 70, 201) x2 = linspace(1, 50, 201) A1 = SparseUnidimensionalInterpolator(ker, 1, x1, 1:n1) A2 = SparseUnidimensionalInterpolator(ker, 2, x2, 1:n2) A = A1*A2 """ SparseUnidimensionalInterpolator(ker::Kernel{T}, args...) where {T<:AbstractFloat} = SparseUnidimensionalInterpolator{T}(ker, args...) @deprecate SparseUnidimensionalInterpolator(T::Type{<:AbstractFloat}, ker::Kernel, args...) SparseUnidimensionalInterpolator{T}(ker, args...) SparseUnidimensionalInterpolator{T}(ker::Kernel, args...) where {T<:AbstractFloat} = SparseUnidimensionalInterpolator{T}(T(ker), args...) function SparseUnidimensionalInterpolator{T}(ker::Kernel{T}, d::Integer, pos::AbstractVector{<:Real}, len::Integer) where {T<:AbstractFloat} len ≥ 1 || throw(ArgumentError("invalid dimension length")) return SparseUnidimensionalInterpolator{T}(ker, d, pos, 1:Int(len)) end # FIXME: not type-stable function SparseUnidimensionalInterpolator{T}(ker::Kernel{T,S}, d::Integer, pos::AbstractVector{<:Real}, grd::AbstractRange ) where {T<:AbstractFloat,S} SparseUnidimensionalInterpolator{T,S,Int(d)}(ker, pos, grd) end function SparseUnidimensionalInterpolator{T,S,D}(ker::Kernel{T,S}, pos::AbstractVector{<:Real}, grd::AbstractRange ) where {D,T<:AbstractFloat,S} isa(D, Int) || throw(ArgumentError("invalid type for dimension of interpolation")) D ≥ 1 || throw(ArgumentError("invalid dimension of interpolation")) nrows = length(pos) ncols = length(grd) C, J = _sparsecoefs(CartesianIndices((nrows,)), ncols, ker, fractional_index(T, pos, grd)) return SparseUnidimensionalInterpolator{T,S,D}(nrows, ncols, C, J) end function vcreate(::Type{Direct}, A::SparseUnidimensionalInterpolator, x::AbstractArray, scratch::Bool=false) nrows, ncols = size(A) return _vcreate(nrows, ncols, A, x) end function vcreate(::Type{Adjoint}, A::SparseUnidimensionalInterpolator, x::AbstractArray, scratch::Bool=false) nrows, ncols = size(A) return _vcreate(ncols, nrows, A, x) end function _vcreate(ny::Int, nx::Int, A::SparseUnidimensionalInterpolator{Ta,S,D}, x::AbstractArray{Tx,N}) where {Ta,Tx<:Real,S,D,N} xdims = size(x) 1 ≤ D ≤ N || throw(DimensionMismatch("out of range dimension of interpolation")) xdims[D] == nx || throw(DimensionMismatch("dimension $D of `x` must be $nx")) Ty = float(promote_type(Ta, Tx)) ydims = [(d == D ? ny : xdims[d]) for d in 1:N] return Array{Ty,N}(undef, ydims...) end function apply!(α::Real, ::Type{Direct}, A::SparseUnidimensionalInterpolator{Ta,S,D}, x::AbstractArray{Tx,N}, scratch::Bool, β::Real, y::AbstractArray{Ty,N}) where {Ta<:AbstractFloat, Tx<:Real, Ty<:AbstractFloat,S,D,N} # Check arguments. _check(A, N) xdims = size(x) ydims = size(y) nrows, ncols = size(A) xdims[D] == ncols || throw(DimensionMismatch("dimension $D of `x` must be $ncols")) ydims[D] == nrows || throw(DimensionMismatch("dimension $D of `y` must be $nrows")) for k in 1:N k == D || xdims[k] == ydims[k] || throw(DimensionMismatch("`x` and `y` have incompatible dimensions")) end # Apply operator. if α == 0 vscale!(y, β) else C = coefficients(A) J = columns(A) I_pre = CartesianIndices(xdims[1:D-1]) I_post = CartesianIndices(xdims[D+1:N]) T = promote_type(Ta,Tx) alpha = convert(T, α) if β == 0 _apply_direct!(T, Val{S}, C, J, alpha, x, y, I_pre, nrows, I_post) else beta = convert(Ty, β) _apply_direct!(T, Val{S}, C, J, alpha, x, beta, y, I_pre, nrows, I_post) end end return y end function apply!(α::Real, ::Type{Adjoint}, A::SparseUnidimensionalInterpolator{Ta,S,D}, x::AbstractArray{Tx,N}, scratch::Bool, β::Real, y::AbstractArray{Ty,N}) where {Ta<:AbstractFloat, Tx<:Real, Ty<:AbstractFloat,S,D,N} # Check arguments. _check(A, N) xdims = size(x) ydims = size(y) nrows, ncols = size(A) xdims[D] == nrows || throw(DimensionMismatch("dimension $D of `x` must be $nrows")) ydims[D] == ncols || throw(DimensionMismatch("dimension $D of `y` must be $ncols")) for k in 1:N k == D || xdims[k] == ydims[k] || throw(DimensionMismatch("`x` and `y` have incompatible dimensions")) end # Apply adjoint operator. vscale!(y, β) if α != 0 T = promote_type(Ta,Tx) _apply_adjoint!(Val{S}, coefficients(A), columns(A), convert(T, α), x, y, CartesianIndices(xdims[1:D-1]), nrows, CartesianIndices(xdims[D+1:N])) end return y end # The 3 following private methods are needed to achieve type invariance and win # a factor ~1000 in speed! Also note the way the innermost loop is written # with a constant range and an offset k0 which is updated; this is critical for # saving a factor 2-3 in speed. # # The current version takes ~ 4ms (7 iterations of linear conjugate gradients) # to fit a 77×77 array of weights interpolated by Catmull-Rom splines to # approximate a 256×256 image. function _apply_direct!(::Type{T}, ::Type{Val{S}}, C::Vector{<:AbstractFloat}, J::Vector{Int}, α::AbstractFloat, x::AbstractArray{<:Real,N}, y::AbstractArray{<:AbstractFloat,N}, I_pre::CartesianIndices{N_pre}, len::Int, I_post::CartesianIndices{N_post} ) where {T<:AbstractFloat,S,N,N_post,N_pre} @assert N == N_post + N_pre + 1 @inbounds for i_post in I_post for i_pre in I_pre k0 = 0 for i in 1:len sum = zero(T) @simd for s in 1:S k = k0 + s sum += C[k]*x[i_pre,J[k],i_post] end y[i_pre,i,i_post] = α*sum k0 += S end end end end function _apply_direct!(::Type{T}, ::Type{Val{S}}, C::Vector{<:AbstractFloat}, J::Vector{Int}, α::AbstractFloat, x::AbstractArray{<:Real,N}, β::AbstractFloat, y::AbstractArray{<:AbstractFloat,N}, I_pre::CartesianIndices{N_pre}, len::Int, I_post::CartesianIndices{N_post} ) where {T<:AbstractFloat,S,N,N_post,N_pre} @assert N == N_post + N_pre + 1 @inbounds for i_post in I_post for i_pre in I_pre k0 = 0 for i in 1:len sum = zero(T) @simd for s in 1:S k = k0 + s sum += C[k]*x[i_pre,J[k],i_post] end y[i_pre,i,i_post] = α*sum + β*y[i_pre,i,i_post] k0 += S end end end end function _apply_adjoint!(::Type{Val{S}}, C::Vector{<:AbstractFloat}, J::Vector{Int}, α::AbstractFloat, x::AbstractArray{<:Real,N}, y::AbstractArray{<:AbstractFloat,N}, I_pre::CartesianIndices{N_pre}, len::Int, I_post::CartesianIndices{N_post} ) where {S,N,N_post,N_pre} @assert N == N_post + N_pre + 1 @inbounds for i_post in I_post for i_pre in I_pre k0 = 0 for i in 1:len c = α*x[i_pre,i,i_post] @simd for s in 1:S k = k0 + s y[i_pre,J[k],i_post] += C[k]*c end k0 += S end end end end function _check(A::SparseUnidimensionalInterpolator{T,S,D}, N::Int) where {T<:AbstractFloat,S,D} 1 ≤ D ≤ N || throw(DimensionMismatch("out of range dimension of interpolation")) nrows, ncols = size(A) nvals = S*nrows C = coefficients(A) J = columns(A) length(C) == nvals || throw(DimensionMismatch("array of coefficients must have $nvals elements (has $(length(C)))")) length(J) == nvals || throw(DimensionMismatch("array of indices must have $nvals elements (has $(length(C)))")) for k in eachindex(J) 1 ≤ J[k] ≤ ncols || throw(ErrorException("out of bounds indice(s)")) end end end # module
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
code
17637
# # tabulated.jl - # # Implement unidimensional interpolation operator using precomputed indices and # coefficients. # #------------------------------------------------------------------------------ # # This file is part of the LinearInterpolators package licensed under the MIT # "Expat" License. # # Copyright (C) 2016-2018, Éric Thiébaut. # module TabulatedInterpolators export TabulatedInterpolator using InterpolationKernels using LazyAlgebra using LazyAlgebra.Foundations import LazyAlgebra: vcreate, apply!, apply using ..LinearInterpolators using ..LinearInterpolators: limits, getcoefs import ..LinearInterpolators.Meta struct TabulatedInterpolator{T<:AbstractFloat,S,D} <: LinearMapping nrows::Int # length of output dimension ncols::Int # length of input dimension J::Matrix{Int} # indices along input dimension W::Matrix{T} # interpolation weights d::D # dimension to interpolate or nothing end # Interpolator can be used as a function. (A::TabulatedInterpolator)(x::AbstractArray) = apply(A, x) nrows(A::TabulatedInterpolator) = A.nrows ncols(A::TabulatedInterpolator) = A.ncols width(A::TabulatedInterpolator{T,S,D}) where {T,S,D} = S coefficients(A::TabulatedInterpolator) = A.W columns(A::TabulatedInterpolator) = A.J """ TabulatedInterpolator([T,] [d = nothing,] ker, pos, nrows, ncols) yields a linear map to interpolate with kernel `ker` along a dimension of length `ncols` to produce a dimension of length `nrows`. The function `pos(i)` for `i ∈ 1:nrows` gives the positions to interpolate in fractional index unit along a dimension of length `ncols`. Argument `d` is the rank of the dimension along which to interpolate when the operator is applied to a multidimensional array. If it is unspecifed when the operator is created, it will have to be specified each time the operator is applied (see below). The positions to interpolate can also be specified by a vector `x` as in: TabulatedInterpolator([T,] [d = nothing,] ker, x, ncols) to produce an interpolator whose output dimension is `nrows = length(x)`. Here `x` can be an abstract vector. Optional argument `T` is the floating-point type of the coefficients of the linear map. By default, it is given by the promotion of the element type of the arguments `ker` and, if specified, `x`. The tabulated operator, say `A`, can be applied to an argument `x`: apply!(α, P::Operations, A, [d,] x, scratch, β, y) -> y to overwrite `y` with `α*P(A)⋅x + β*y`. If `x` and `y` are multi-dimensional, the dimension `d` to interpolate must be specified. """ function TabulatedInterpolator(::Type{T}, d::D, ker::Kernel{T,S}, pos::Function, nrows::Integer, ncols::Integer) where {T<:AbstractFloat, D<:Union{Nothing,Int},S} nrows ≥ 1 || error("number of rows too small") ncols ≥ 1 || error("number of columns too small") J, W = __maketables(ker, pos, convert(Int, nrows), convert(Int, ncols)) return TabulatedInterpolator{T,S,D}(nrows, ncols, J, W, d) end function TabulatedInterpolator(::Type{T}, d::D, ker::Kernel{T,S}, x::AbstractVector{<:Real}, ncols::Integer) where {T<:AbstractFloat, D<:Union{Nothing,Int},S} nrows = length(x) nrows ≥ 1 || error("number of positions too small") ncols ≥ 1 || error("number of columns too small") J, W = __maketables(ker, x, nrows, convert(Int, ncols)) return TabulatedInterpolator{T,S,D}(nrows, ncols, J, W, d) end # This one forces the kernel to have the requested precision. function TabulatedInterpolator(::Type{T}, d::Union{Nothing,Int}, ker::Kernel, args...) where {T<:AbstractFloat} TabulatedInterpolator(T, d, T(ker), args...) end function TabulatedInterpolator(d::Union{Nothing,Int}, ker::Kernel{T}, pos::Function, nrows::Integer, ncols::Integer) where {T} TabulatedInterpolator(float(T), d, ker, pos, nrows, ncols) end function TabulatedInterpolator(d::Union{Nothing,Int}, ker::Kernel{Tk}, x::AbstractVector{Tx}, ncols::Integer) where {Tk,Tx} TabulatedInterpolator(float(promote_type(Tk, Tx)), d, ker, x, ncols) end TabulatedInterpolator(T::DataType, ker::Kernel, args...) = TabulatedInterpolator(T, nothing, ker, args...) TabulatedInterpolator(ker::Kernel, args...) = TabulatedInterpolator(nothing, ker, args...) TabulatedInterpolator(T::DataType, d::Integer, ker::Kernel, args...) = TabulatedInterpolator(T, convert(Int, d), ker, args...) TabulatedInterpolator(d::Integer, ker::Kernel, args...) = TabulatedInterpolator(convert(Int, d), ker, args...) @generated function __maketables(ker::Kernel{T,S}, X::AbstractVector, nrows::Int, ncols::Int) where {T,S} J_ = [Symbol(:j_,s) for s in 1:S] W_ = [Symbol(:w_,s) for s in 1:S] code = (Meta.generate_getcoefs(J_, W_, :ker, :lim, :x), [:( J[$s,i] = $(J_[s]) ) for s in 1:S]..., [:( W[$s,i] = $(W_[s]) ) for s in 1:S]...) quote J = Array{Int}(undef, S, nrows) W = Array{T}(undef, S, nrows) lim = limits(ker, ncols) # The following assertion is to cope with # https://github.com/JuliaLang/julia/issues/40276 if size(J,1) == S && size(W,1) == S @inbounds for i in 1:nrows x = convert(T, X[i]) $(code...) end else throw_unexpected_stride() end return J, W end end @generated function __maketables(ker::Kernel{T,S}, pos::Function, nrows::Int, ncols::Int) where {T,S} J_ = [Symbol(:j_,s) for s in 1:S] W_ = [Symbol(:w_,s) for s in 1:S] code = (Meta.generate_getcoefs(J_, W_, :ker, :lim, :x), [:( J[$s,i] = $(J_[s]) ) for s in 1:S]..., [:( W[$s,i] = $(W_[s]) ) for s in 1:S]...) quote J = Array{Int}(undef, S, nrows) W = Array{T}(undef, S, nrows) lim = limits(ker, ncols) # The following assertion is to cope with # https://github.com/JuliaLang/julia/issues/40276 if size(J,1) == S && size(W,1) == S @inbounds for i in 1:nrows x = convert(T, pos(i)) $(code...) end else throw_unexpected_stride() end return J, W end end throw_unexpected_stride() = throw(AssertionError("unexpected stride")) # Source and destination arrays may have elements which are either reals or # complexes. const RorC{T<:AbstractFloat} = Union{T,Complex{T}} @inline __errdims(msg::String) = throw(DimensionMismatch(msg)) @inline function __check(A::TabulatedInterpolator{T,S}) where {T,S} if !(size(A.J) == size(A.W) == (S, A.nrows)) error("corrupted interpolation table") end end @inline function __fullcheck(A::TabulatedInterpolator{T,S}) where {T,S} # The loop below is a bit faster than using `extrema`. __check(A) J, ncols = A.J, A.ncols @inbounds for k in eachindex(J) if !(1 ≤ J[k] ≤ ncols) error("out of bound index in interpolation table") end end end # For vectors, the dimension to interpolate is 1. function vcreate(::Type{P}, A::TabulatedInterpolator{R,S,Nothing}, src::AbstractVector{T}, scratch::Bool=false) where {P<:Operations, R<:AbstractFloat,S, T<:RorC{R}} __vcreate(P, A, 1, src) end function vcreate(::Type{P}, A::TabulatedInterpolator{R,S,Nothing}, src::AbstractArray{T,N}, scratch::Bool=false) where {P<:Operations, R<:AbstractFloat,S, T<:RorC{R},N} error("dimension to interpolate must be provided") end function vcreate(::Type{P}, A::TabulatedInterpolator{R,S,Nothing}, d::Integer, src::AbstractArray{T,N}, scratch::Bool=false) where {P<:Operations, R<:AbstractFloat,S, T<:RorC{R},N} __vcreate(P, A, convert(Int, d), src) end function apply!(alpha::Real, ::Type{P}, A::TabulatedInterpolator{R,S,Nothing}, d::Integer, src::AbstractArray{T,N}, scratch::Bool, beta::Real, dst::AbstractArray{T,N}) where {P<:Operations, R<:AbstractFloat,S, T<:RorC{R},N} __apply!(alpha, P, A, convert(Int, d), src, beta, dst) end # For vectors, the dimension to interpolate is 1. function apply!(alpha::Real, ::Type{P}, A::TabulatedInterpolator{R,S,Nothing}, src::AbstractVector{T}, scratch::Bool, beta::Real, dst::AbstractVector{T}) where {P<:Operations, R<:AbstractFloat,S, T<:RorC{R}} __apply!(alpha, P, A, 1, src, beta, dst) end function apply!(alpha::Real, ::Type{P}, A::TabulatedInterpolator{R,S,Nothing}, src::AbstractArray{T,N}, scratch::Bool, beta::Real, dst::AbstractArray{T,N}) where {P<:Operations, R<:AbstractFloat,S, T<:RorC{R},N} error("dimension to interpolate must be provided") end function vcreate(::Type{P}, A::TabulatedInterpolator{R,S,Int}, src::AbstractArray{T,N}, scratch::Bool=false) where {P<:Operations, R<:AbstractFloat,S, T<:RorC{R},N} __vcreate(P, A, A.d, src) end function apply!(alpha::Real, ::Type{P}, A::TabulatedInterpolator{R,S,Int}, src::AbstractArray{T,N}, scratch::Bool, beta::Real, dst::AbstractArray{T,N}) where {P<:Operations, R<:AbstractFloat,S, T<:RorC{R},N} __apply!(alpha, P, A, A.d, src, beta, dst) end function __vcreate(::Type{Direct}, A::TabulatedInterpolator{R,S,D}, d::Int, src::AbstractArray{T,N}) where {R<:AbstractFloat,S,D, T<:RorC{R},N} 1 ≤ d ≤ N || error("out of range dimension $d") nrows = A.nrows srcdims = size(src) dstdims = ntuple(i -> (i == d ? nrows : srcdims[i]), Val(N)) return Array{T}(undef, dstdims) end function __vcreate(::Type{Adjoint}, A::TabulatedInterpolator{R,S,D}, d::Int, src::AbstractArray{T,N}) where {R<:AbstractFloat,S,D, T<:RorC{R},N} 1 ≤ d ≤ N || error("out of range dimension $d") ncols = A.ncols srcdims = size(src) dstdims = ntuple(i -> (i == d ? ncols : srcdims[i]), Val(N)) return Array{T}(undef, dstdims) end function __apply!(alpha::Real, ::Type{Direct}, A::TabulatedInterpolator{R,S,D}, d::Int, src::AbstractArray{T,N}, beta::Real, dst::AbstractArray{T,N}) where {R<:AbstractFloat,S,D, T<:RorC{R},N} # Check arguments. __fullcheck(A) 1 ≤ d ≤ N || error("out of range dimension $d") nrows, ncols = A.nrows, A.ncols srcdims, dstdims = size(src), size(dst) dstdims[d] == nrows || __errdims("dimension $d of destination must be $nrows") srcdims[d] == ncols || __errdims("dimension $d of source must be $ncols") predims = srcdims[1:d-1] postdims = srcdims[d+1:end] (dstdims[1:d-1] == predims && dstdims[d+1:end] == postdims) || __errdims("incompatible destination and source dimensions") # Get rid of the case alpha = 0 and apply direct interpolation. if alpha == 0 vscale!(dst, beta) else __direct!(convert(R, alpha), A, src, CartesianIndices(predims), nrows, CartesianIndices(postdims), convert(R, beta), dst) end return dst end function __apply!(alpha::Real, ::Type{Adjoint}, A::TabulatedInterpolator{R,S,D}, d::Int, src::AbstractArray{T,N}, beta::Real, dst::AbstractArray{T,N}) where {R<:AbstractFloat,S,D, T<:RorC{R},N} # Check arguments. __fullcheck(A) 1 ≤ d ≤ N || error("out of range dimension $d") nrows, ncols = A.nrows, A.ncols srcdims, dstdims = size(src), size(dst) dstdims[d] == ncols || __errdims("dimension $d of destination must be $ncols") srcdims[d] == nrows || __errdims("dimension $d of source must be $nrows") predims = srcdims[1:d-1] postdims = srcdims[d+1:end] (dstdims[1:d-1] == predims && dstdims[d+1:end] == postdims) || __errdims("incompatible destination and source dimensions") # Scale destination by beta, and apply adjoint interpolation unless # alpha = 0. vscale!(dst, beta) if alpha != 0 __adjoint!(convert(R, alpha), A, src, CartesianIndices(predims), nrows, CartesianIndices(postdims), dst) end return dst end function __direct!(α::R, A::TabulatedInterpolator{R,S,D}, src::AbstractArray{T,N}, I_pre::CartesianIndices, nrows::Int, I_post::CartesianIndices, β::R, dst::AbstractArray{T,N}) where {R<:AbstractFloat,S,D, T<:RorC{R},N} J, W = A.J, A.W # The following assertion is to cope with # https://github.com/JuliaLang/julia/issues/40276 if size(J,1) == S && size(W,1) == S # We already know that α != 0. if α == 1 && β == 0 @inbounds for i_post in I_post, i_pre in I_pre, i in 1:nrows a = zero(T) @simd for s in 1:S j, w = J[s,i], W[s,i] a += src[i_pre,j,i_post]*w end dst[i_pre,i,i_post] = a end elseif β == 0 @inbounds for i_post in I_post, i_pre in I_pre, i in 1:nrows a = zero(T) @simd for s in 1:S j, w = J[s,i], W[s,i] a += src[i_pre,j,i_post]*w end dst[i_pre,i,i_post] = α*a end else @inbounds for i_post in I_post, i_pre in I_pre, i in 1:nrows a = zero(T) @simd for s in 1:S j, w = J[s,i], W[s,i] a += src[i_pre,j,i_post]*w end dst[i_pre,i,i_post] = α*a + β*dst[i_pre,i,i_post] end end else throw_unexpected_stride() end end function __adjoint!(α::R, A::TabulatedInterpolator{R,S,D}, src::AbstractArray{T,N}, I_pre::CartesianIndices, nrows::Int, I_post::CartesianIndices, dst::AbstractArray{T,N}) where {R<:AbstractFloat,S,D, T<:RorC{R},N} J, W = A.J, A.W # The following assertion is to cope with # https://github.com/JuliaLang/julia/issues/40276 if size(J,1) == S && size(W,1) == S # We already know that α != 0. if α == 1 @inbounds for i_post in I_post, i_pre in I_pre, i in 1:nrows x = src[i_pre,i,i_post] if x != zero(T) @simd for s in 1:S j, w = J[s,i], W[s,i] dst[i_pre,j,i_post] += w*x end end end else @inbounds for i_post in I_post, i_pre in I_pre, i in 1:nrows x = α*src[i_pre,i,i_post] if x != zero(T) @simd for s in 1:S j, w = J[s,i], W[s,i] dst[i_pre,j,i_post] += w*x end end end end else throw_unexpected_stride() end end end # module
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
code
1508
# # types.jl - # # Definitions of common type in `LinearInterpolators`. # #------------------------------------------------------------------------------ # # This file is part of the LinearInterpolators package licensed under the MIT # "Expat" License. # # Copyright (C) 2016-2021, Éric Thiébaut. # """ Limits{T<:AbstractFloat} Abstract type for defining boundary conditions. """ abstract type Limits{T<:AbstractFloat} end # FIXME: add parameter S """ `FlatLimits` are boundary conditions that implies that extrapolated positions yield the same value of the interpolated array at the nearest position. """ struct FlatLimits{T<:AbstractFloat} <: Limits{T} len::Int # length of dimension in interpolated array function FlatLimits{T}(len::Integer) where {T} @assert len ≥ 1 new{T}(len) end end """ `SafeFlatLimits` are boundary conditions that implies that extrapolated positions yield the same value of the interpolated array at the nearest position. Compared to `FlatLimits`, the operations are "safe" in the sense that no `InexactError` get thrown even for very large extrapolation distances. """ struct SafeFlatLimits{T<:AbstractFloat} <: Limits{T} inf::T # bound for all neighbors before range sup::T # bound for all neighbors after range len::Int # length of dimension in interpolated array function SafeFlatLimits{T}(inf, sup, len::Integer) where {T} @assert inf < sup @assert len ≥ 1 new{T}(inf, sup, len) end end
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
code
8091
# # unidimensional.jl -- # # Unidimensional interpolation (the result may however be multi-dimensional). # #------------------------------------------------------------------------------ # # This file is part of the LinearInterpolators package licensed under the MIT # "Expat" License. # # Copyright (C) 2016-2021, Éric Thiébaut. # # All code is in a module to "hide" private methods. module UnidimensionalInterpolators using InterpolationKernels using LazyAlgebra using LazyAlgebra.Foundations import LazyAlgebra: apply, apply!, vcreate using ..LinearInterpolators using ..LinearInterpolators: limits, getcoefs import ..LinearInterpolators.Meta #------------------------------------------------------------------------------ # Out-of place versions (coordinates cannot be a function). # FIXME: This is type-piracy because the only non-standard type, `Kernel`, comes # from another package. function apply(ker::Kernel, x::AbstractArray, src::AbstractVector) return apply(Direct, ker, x, src) end function apply(::Type{Direct}, ker::Kernel, x::AbstractArray, src::AbstractVector) # The element type of the result is the type T of the product of the # interpolation weights by the elements of the source array. T = promote_type(eltype(ker), eltype(src)) return apply!(Array{T}(undef, size(x)), Direct, ker, x, src) end function apply(::Type{Adjoint}, ker::Kernel, x::AbstractArray, src::AbstractArray, len::Integer) # The element type of the result is the type T of the product of the # interpolation weights by the elements of the source array. T = promote_type(eltype(ker), eltype(src)) return apply!(Array{T}(undef, len), Adjoint, ker, x, src) end #------------------------------------------------------------------------------ # In-place wrappers. function apply!(dst::AbstractArray{<:Any,N}, ker::Kernel, x::Union{Function,AbstractArray{<:Any,N}}, src::AbstractVector) where {N} apply!(1, Direct, ker, x, src, 0, dst) end function apply!(dst::AbstractArray{<:Any,N}, ::Type{Direct}, ker::Kernel, x::Union{Function,AbstractArray{<:Any,N}}, src::AbstractVector) where {N} apply!(1, Direct, ker, x, src, 0, dst) end function apply!(dst::AbstractVector, ::Type{Adjoint}, ker::Kernel, x::Union{Function,AbstractArray{<:Any,N}}, src::AbstractArray{<:Any,N}) where {N} apply!(1, Adjoint, ker, x, src, 0, dst) end #------------------------------------------------------------------------------ # In-place direct operation. function __generate_interp(n::Integer, ker::Symbol, lim::Meta.Arg, pos::Meta.Arg, arr::Symbol) J = [Symbol(:j_,s) for s in 1:n] W = [Symbol(:w_,s) for s in 1:n] code = Meta.generate_getcoefs(J, W, ker, lim, pos) expr = Meta.generate_interp_expr(arr, J, W) return (code, expr) end @generated function apply!(α::Number, ::Type{Direct}, ker::Kernel{<:Any,S}, x::AbstractArray{<:Any,N}, src::AbstractVector, β::Number, dst::AbstractArray{<:Any,N}) where {S,N} code, expr = __generate_interp(S, :ker, :lim, :pos, :src) quote @assert size(dst) == size(x) lim = limits(ker, length(src)) if α == 0 vscale!(dst, β) elseif β == 0 if α == 1 @inbounds for i in eachindex(dst, x) pos = x[i] $code dst[i] = $expr end else alpha = promote_multiplier(α, eltype(ker), eltype(src)) @inbounds for i in eachindex(dst, x) pos = x[i] $code dst[i] = $expr*alpha end end else alpha = promote_multiplier(α, eltype(ker), eltype(src)) beta = promote_multiplier(β, eltype(dst)) @inbounds for i in eachindex(dst, x) pos = x[i] $code dst[i] = $expr*alpha + beta*dst[i] end end return dst end end @generated function apply!(α::Number, ::Type{Direct}, ker::Kernel{<:Any,S}, f::Function, src::AbstractVector, β::Number, dst::AbstractArray{<:Any,N}) where {S,N} code, expr = __generate_interp(S, :ker, :lim, :pos, :src) quote lim = limits(ker, length(src)) if α == 0 vscale!(dst, β) elseif β == 0 if α == 1 @inbounds for i in eachindex(dst) pos = f(i) $code dst[i] = $expr end else alpha = promote_multiplier(α, eltype(ker), eltype(src)) @inbounds for i in eachindex(dst) pos = f(i) $code dst[i] = $expr*alpha end end else alpha = promote_multiplier(α, eltype(ker), eltype(src)) beta = promote_multiplier(β, eltype(dst)) @inbounds for i in eachindex(dst) pos = f(i) $code dst[i] = $expr*alpha + beta*dst[i] end end return dst end end #------------------------------------------------------------------------------ # In-place adjoint operation. function __generate_interp_adj(n::Integer, ker::Symbol, lim::Meta.Arg, pos::Meta.Arg, dst::Symbol, val::Symbol) J = [Symbol(:j_,s) for s in 1:n] W = [Symbol(:w_,s) for s in 1:n] return (Meta.generate_getcoefs(J, W, ker, lim, pos), [:($dst[$(J[i])] += $(W[i])*$val) for i in 1:n]...) end @generated function apply!(α::Number, ::Type{Adjoint}, ker::Kernel{<:Any,S}, x::AbstractArray{<:Any,N}, src::AbstractArray{<:Any,N}, β::Number, dst::AbstractVector) where {S,N} code = __generate_interp_adj(S, :ker, :lim, :pos, :dst, :val) quote @assert size(src) == size(x) vscale!(dst, β) lim = limits(ker, length(dst)) if α == 1 @inbounds for i in eachindex(src, x) pos = x[i] val = src[i] $(code...) end elseif α != 0 alpha = promote_multiplier(α, eltype(ker), eltype(src)) @inbounds for i in eachindex(src, x) pos = x[i] val = alpha*src[i] $(code...) end end return dst end end @generated function apply!(α::Number, ::Type{Adjoint}, ker::Kernel{<:Any,S}, f::Function, src::AbstractArray{<:Any,N}, β::Number, dst::AbstractVector) where {S,N} code = __generate_interp_adj(S, :ker, :lim, :pos, :dst, :val) quote vscale!(dst, β) lim = limits(ker, length(dst)) if α == 1 @inbounds for i in eachindex(src) pos = f(i) val = src[i] $(code...) end elseif α != 0 alpha = promote_multiplier(α, eltype(ker), eltype(src)) @inbounds for i in eachindex(src) pos = f(i) val = alpha*src[i] $(code...) end end return dst end end end # module
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
code
1818
module BenchmarkingLinearInterpolators using Printf using LinearInterpolators using LazyAlgebra using BenchmarkTools mimeshow(io::IO, x) = show(io, MIME"text/plain"(), x) mimeshow(x) = mimeshow(stdout, x) prt(op::AbstractString, t) = begin @printf("%s:\n", op) mimeshow(t) end prt(op::AbstractString, t, nops::Integer) = begin # times in nanoseconds, speed in Gigaflops @printf("%s [%.6f Gflops]:\n", op, nops/minimum(t.times)) mimeshow(t) println() end n1, n2 = 300, 200 m1, m2 = 43, 29 y = randn(n1, n2) ker = CatmullRomSpline() A1 = SparseUnidimensionalInterpolator(ker, 1, 1:n1, range(1,n1,length=m1)) A2 = SparseUnidimensionalInterpolator(ker, 2, 1:n2, range(1,n2,length=m2)) H = A1*A2 function LazyAlgebra.vcreate(::Type{LazyAlgebra.Direct}, ::Gram, x::AbstractArray{T,N}, scratch::Bool) where {T<:AbstractFloat,N} return similar(x) end r1 = 2*length(A1.C) r2 = 2*length(A2.C) x = conjgrad(H'*H, H'*y; verb=true, ftol=1e-8, maxiter=50) z = vcopy(y) prt("A1*x", @benchmark($A1*$x), r1*m2) prt("A2*x", @benchmark($A2*$x), r2*m1) prt("A2*A1*x", @benchmark($(A2*A1)*$x), r1*m2 + r2*n1) prt("A1*A2*x", @benchmark($(A1*A2)*$x), r2*m1 + r1*n2) prt("A1'*y", @benchmark($(A1')*$y), r1*m2) prt("A2'*y", @benchmark($(A2')*$y), r2*m1) prt("A2'*A1'*y", @benchmark($(A2'*A1')*$y), r1*m2 + r2*n1) prt("A1'*A2'*y", @benchmark($(A1'*A2')*$y), r2*m1 + r1*n2) println("") n = 100 pos = [1.1*i + 0.2*j for i in 1:n1, j in 1:n2] pmin, pmax = extrema(pos) A = SparseInterpolator(ker, pos, range(pmin, pmax, length=n)) x = randn(n) y = randn(n1,n2) nops = 2*length(A.C) prt("A*x", @benchmark($A*$x), nops) prt("A'*x", @benchmark($(A')*$y), nops) end # module
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
code
6838
module DemonstratingLinearInterpolatorsInterpolations using Printf using LazyAlgebra using LazyAlgebra: Direct, Adjoint using LinearInterpolators using InterpolationKernels using LinearInterpolators.Interpolations using PyCall # pygui(:gtk); # can be: :wx, :gtk, :qt using LaTeXStrings import PyPlot const plt = PyPlot function rundemos(::Type{T} = Float64) where {T<:AbstractFloat} z = T[0.5, 0.3, 0.1, 0.0, -0.2, -0.7, -0.7, 0.0, 1.7, 1.9, 2.1] # 1-D example t = range(-3, 14, length=2000); I0 = SparseInterpolator(RectangularSpline(T, Flat), t, length(z)) I1 = SparseInterpolator(LinearSpline(T, Flat), t, length(z)) I2 = SparseInterpolator(CatmullRomSpline(T, SafeFlat), t, length(z)) I3 = SparseInterpolator(LanczosKernel(T, 8), t, length(z)) plt.figure(1) plt.clf() plt.plot(t, I0(z), color="darkgreen", linewidth=1.5, linestyle="-", label="Rectangular spline"); plt.plot(t, I1(z), color="darkred", linewidth=1.5, linestyle="-", label="Linear spline"); plt.plot(t, I2(z), color="orange", linewidth=1.5, linestyle="-", label="Catmull-Rom"); plt.plot(t, I3(z), color="violet", linewidth=1.5, linestyle="-", label="Lanczos 8"); plt.plot(1:length(z), z, "o", color="darkblue", label="Points") plt.legend() plt.title("Interpolations with Cardinal Kernels") # Interpolation + smoothing t = range(-3, 14, length=2000); I5 = SparseInterpolator(QuadraticSpline(T), t, length(z)) I6 = SparseInterpolator(CubicSpline(T, Flat), t, length(z)) I7 = SparseInterpolator(MitchellNetravaliSpline(T, Flat), t, length(z)) plt.figure(2) plt.clf() plt.plot(t, I6(z), color="darkred", linewidth=1.5, linestyle="-", label="Cubic B-spline"); plt.plot(t, I5(z), color="darkgreen", linewidth=1.5, linestyle="-", label="Quadratic B-spline"); #plt.plot(t, I7(z), color="orange", # linewidth=1.5, linestyle="-", label="Mitchell & Netravali"); plt.plot(1:length(z), z, "o", color="darkblue", label="Points") plt.legend() plt.title("Interpolations with Smoothing Kernels") # Test conversion to a sparse matrix. S1 = sparse(I1) S2 = sparse(I2) println("max. error 1: ", maximum(abs.(I1(z) - S1*z))) println("max. error 2: ", maximum(abs.(I2(z) - S2*z))) # 2-D example t = reshape(range(-3, 14, length=20*21), (20,21)); I = SparseInterpolator(CatmullRomSpline(T, Flat), t, length(z)) plt.figure(3) plt.clf() plt.imshow(I(z)); end #rundemos() #------------------------------------------------------------------------------ const CPU = 2.94e9 function printtest(prefix::String, count::Integer, tup) elt, mem, gct = tup[2:4] @printf("%s %6.0f cycles (Mem. = %8d bytes GC = %3.0f%%)\n", prefix, CPU*elt/count, mem, 1e2*gct/elt) end function testdirect!(dst::Vector{T}, ker::Kernel{T,S,B}, x::AbstractVector{T}, src::Vector{T}, cnt::Integer) where {T,S,B} for k in 1:cnt apply!(dst, Direct, ker, x, src) end return dst end function testadjoint!(dst::Vector{T}, ker::Kernel{T,S,B}, x::AbstractVector{T}, src::Vector{T}, cnt::Integer) where {T,S,B} for k in 1:cnt apply!(dst, Adjoint, ker, x, src) end return dst end function runtests(::Type{T} = Float64, len::Integer = 1000, cnt::Integer = 100) where T<:AbstractFloat dim = 500 w = 10 K01 = RectangularSpline(T, Flat) K02 = RectangularSpline(T, SafeFlat) K03 = LinearSpline(T, Flat) K04 = LinearSpline(T, SafeFlat) K05 = QuadraticSpline(T, Flat) K06 = QuadraticSpline(T, SafeFlat) K07 = CardinalCubicSpline(T, -1, Flat) K08 = CardinalCubicSpline(T, -1, SafeFlat) K09 = CatmullRomSpline(T, Flat) K10 = CatmullRomSpline(T, SafeFlat) x = rand(T(1 - w):T(dim + w), len) y = randn(T, dim) z = Array{T}(undef, len) # compile methods testdirect!(z, K01, x, y, 3) testadjoint!(y, K01, x, z, 3) testdirect!(z, K02, x, y, 3) testadjoint!(y, K02, x, z, 3) testdirect!(z, K03, x, y, 3) testadjoint!(y, K03, x, z, 3) testdirect!(z, K04, x, y, 3) testadjoint!(y, K04, x, z, 3) testdirect!(z, K05, x, y, 3) testadjoint!(y, K05, x, z, 3) testdirect!(z, K06, x, y, 3) testadjoint!(y, K08, x, z, 3) testdirect!(z, K07, x, y, 3) testadjoint!(y, K07, x, z, 3) testdirect!(z, K08, x, y, 3) testadjoint!(y, K08, x, z, 3) testdirect!(z, K09, x, y, 3) testadjoint!(y, K09, x, z, 3) testdirect!(z, K10, x, y, 3) testadjoint!(y, K10, x, z, 3) # warm-up tmp = randn(T, 1_000_000) # run tests n = cnt*len printtest("RectangularSpline Flat direct ", n, @timed(testdirect!(z, K01, x, y, cnt))) printtest("RectangularSpline Flat adjoint", n, @timed(testadjoint!(y, K01, x, z, cnt))) printtest("RectangularSpline SafeFlat direct ", n, @timed(testdirect!(z, K02, x, y, cnt))) printtest("RectangularSpline SafeFlat adjoint", n, @timed(testadjoint!(y, K02, x, z, cnt))) println() printtest("LinearSpline Flat direct ", n, @timed(testdirect!(z, K03, x, y, cnt))) printtest("LinearSpline Flat adjoint", n, @timed(testadjoint!(y, K03, x, z, cnt))) printtest("LinearSpline SafeFlat direct ", n, @timed(testdirect!(z, K04, x, y, cnt))) printtest("LinearSpline SafeFlat adjoint", n, @timed(testadjoint!(y, K04, x, z, cnt))) println() printtest("QuadraticSpline Flat direct ", n, @timed(testdirect!(z, K05, x, y, cnt))) printtest("QuadraticSpline Flat adjoint", n, @timed(testadjoint!(y, K05, x, z, cnt))) printtest("QuadraticSpline SafeFlat direct ", n, @timed(testdirect!(z, K06, x, y, cnt))) printtest("QuadraticSpline SafeFlat adjoint", n, @timed(testadjoint!(y, K06, x, z, cnt))) println() printtest("CardinalCubicSpline Flat direct ", n, @timed(testdirect!(z, K07, x, y, cnt))) printtest("CardinalCubicSpline Flat adjoint", n, @timed(testadjoint!(y, K07, x, z, cnt))) printtest("CardinalCubicSpline SafeFlat direct ", n, @timed(testdirect!(z, K08, x, y, cnt))) printtest("CardinalCubicSpline SafeFlat adjoint", n, @timed(testadjoint!(y, K08, x, z, cnt))) println() printtest("CatmullRomSpline Flat direct ", n, @timed(testdirect!(z, K09, x, y, cnt))) printtest("CatmullRomSpline Flat adjoint", n, @timed(testadjoint!(y, K09, x, z, cnt))) printtest("CatmullRomSpline SafeFlat direct ", n, @timed(testdirect!(z, K10, x, y, cnt))) printtest("CatmullRomSpline SafeFlat adjoint", n, @timed(testadjoint!(y, K10, x, z, cnt))) end end # module
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
code
4561
module TestingLinearInterpolatorsInterpolations using TwoDimensional using LazyAlgebra using LazyAlgebra: Adjoint, Direct using LinearInterpolators using LinearInterpolators: getcoefs, limits using Printf using Test using Statistics: mean @testset "Unidimensional" begin ker = @inferred LinearSpline(Float32) src = [0, 0, 1, 0, 0] # Vector{Int} x = LinRange(-1,7,81) # Float64 out = @inferred apply(ker, x, src) # different eltypes @test out[x .== 2.5][1] == 0.5 out2 = similar(out) apply!(out2, ker, x, src) @test out2 == out apply!(2, Direct, ker, x, src, 0, out2) # α=2 β=0 @test out2 == 2*out out2[:] .= 1 @inferred apply!(1, Direct, ker, x, src, 2, out2) # α=1 β=2 @test out2 == out .+ 2 out2[:] .= 3 @inferred apply!(0, Direct, ker, x, src, 2, out2) # α=0 β=2 @test all(==(6), out2) adj = @inferred apply(Adjoint, ker, x, out, length(src)) adj2 = similar(adj) @inferred apply!(2, Adjoint, ker, x, out, 0, adj2) # α=2 β=0 @test adj2 == 2*adj adj2[:] .= 1 @inferred apply!(1, Adjoint, ker, x, out, 2, adj2) # α=1 β=2 @test adj2 ≈ adj .+ 2 adj2[:] .= 3 @inferred apply!(0, Adjoint, ker, x, out, 2, adj2) # α=0 β=2 @test all(==(6), adj2) end distance(a::Real, b::Real) = abs(a - b) distance(a::NTuple{2,Real}, b::NTuple{2,Real}) = hypot(a[1] - b[1], a[2] - b[2]) distance(A::AffineTransform2D, B::AffineTransform2D) = max(abs(A.xx - B.xx), abs(A.xy - B.xy), abs(A.x - B.x), abs(A.yx - B.yx), abs(A.yy - B.yy), abs(A.y - B.y)) distance(A::AbstractArray{Ta,N}, B::AbstractArray{Tb,N}) where {Ta,Tb,N} = mean(abs.(A - B)) shortname(::Nothing) = "" shortname(m::RegexMatch) = m.captures[1] shortname(::Type{T}) where {T} = shortname(string(T)) shortname(str::AbstractString) = shortname(match(r"([_A-Za-z][_A-Za-z0-9]*)([({]|$)", str)) struct CustomCoordinate{T<:Real} val::T end LinearInterpolators.convert_coordinate(T::Type, c::CustomCoordinate) = convert(T, c.val) kernels = (RectangularSpline(), LinearSpline(), QuadraticSpline(), CubicSpline(), CatmullRomSpline(), KeysSpline(-0.4), MitchellNetravaliSpline(), LanczosKernel(4), LanczosKernel(6)) conditions = (Flat, SafeFlat) const VERBOSE = true sub = 3 x = range(-1, stop=1, length=100*sub + 1); xsub = x[1:sub:end]; y = cos.(2 .* x .* (x .+ 2)); ysub = y[1:sub:end]; t = range(1, stop=length(xsub), length=length(x)); @testset "`getcoefs` method" begin T = Float64 ker = CatmullRomSpline(T) len = 4 lim = limits(ker, len) for x in (0, .1, -1.2) @test getcoefs(ker, lim, x) == getcoefs(ker, lim, CustomCoordinate(x)) end end @testset "TabulatedInterpolators" begin tol = 1e-14 for K in kernels, C in conditions tol = isa(K, RectangularSpline) ? 0.02 : 0.006 ker = C(K) T = @inferred TabulatedInterpolator(ker, t, length(xsub)) @inferred T(ysub) @test distance(T(ysub), T*ysub) ≤ 0 err = distance(T*ysub, y) if VERBOSE print(shortname(typeof(K)),"/",shortname(C)," max. err = ") @printf("%.3g\n", err) end @test err ≤ tol @test distance(T*ysub, apply(ker,t,ysub)) ≤ 1e-15 end end @testset "SparseInterpolators" begin for K in kernels, C in conditions tol = isa(K, RectangularSpline) ? 0.02 : 0.006 ker = C(K) S = @inferred SparseInterpolator(ker, t, length(xsub)) T = @inferred TabulatedInterpolator(ker, t, length(xsub)) @inferred S(ysub) @inferred T(ysub) @test distance(S(ysub), S*ysub) ≤ 1e-15 @test distance(S(ysub), T(ysub)) ≤ 1e-15 @test distance(S(ysub), y) ≤ tol @test distance(S(ysub), apply(ker,t,ysub)) ≤ 1e-15 end let ker = kernels[1], T = Float32 @test_deprecated SparseInterpolator(T, ker, t, length(xsub)) end end @testset "TwoDimensionalTransformInterpolator" begin kerlist = (RectangularSpline(), LinearSpline(), CatmullRomSpline()) rows = (11,16) cols = (10,15) # Define a rotation around c. c = (5.6, 6.4) R = c + rotate(AffineTransform2D{Float64}() - c, 0.2) for ker1 in kerlist, ker2 in kerlist A = @inferred TwoDimensionalTransformInterpolator(rows, cols, ker1, ker2, R) x = randn(cols) y = randn(rows) #x0 = randn(cols) #y0 = Array{Float64}(undef, rows) #x1 = Array{Float64}(undef, cols) @test vdot(A*x, y) ≈ vdot(x, A'*y) end end end # module
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
docs
1007
# User visible changes for LinearInterpolators ## Version 0.1.8 - Extend compatibility to `TwoDimensional` v0.4 ## Version 0.1.7 - Extend `getcoefs` to cope with other coordinate types. The coordinate type is converted on-the-fly if it is not exactly the floating-point type of the kernel. The method `convert_coordinate` can be specialized to extend this conversion to non-standard numeric types. This is automatically done for coordinates of type `Unitful.Quantity` when the `Unitful` package is loaded. ## Version 0.1.5 - Bug fixed. ## Version 0.1.3 - `SparseInterpolator(T,ker,...)` and `SparseUnidimensionalInterpolator(T,ker,...)` have been deprecated in favor of `SparseInterpolator{T}(ker,...)` and `SparseUnidimensionalInterpolator{T}(ker,...)`. - Some documentation is available at https://emmt.github.io/LinearInterpolators.jl/dev ## Version 0.1.2 - `LinearInterpolators` is registered in personal registry [`EmmtRegistry`](https://github.com/emmt/EmmtRegistry).
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
docs
2835
# LinearInterpolators [![Doc. Dev][doc-dev-img]][doc-dev-url] [![License][license-img]][license-url] [![Build Status][github-ci-img]][github-ci-url] [![Build Status][appveyor-img]][appveyor-url] [![Coverage][codecov-img]][codecov-url] The `LinearInterpolators` package provides many linear interpolation methods for [Julia][julia-url]. These interpolations are *linear* in the sense that the result depends linearly on the input. The documentation for the master version is [here][doc-dev-url]. ## Features * Separable interpolations are supported for arrays of any dimensionality. Interpolation kernels can be different along each interpolated dimension. * For 2D arrays, interpolations may be separable or not (*e.g.* to apply an image rotation). * Undimensional interpolations may be used to produce multi-dimensional results. * Many interpolation kernels are provided by the package [`InterpolationKernels`](https://github.com/emmt/InterpolationKernels.jl) (B-splines of degree 0 to 3, cardinal cubic splines, Catmull-Rom spline, Mitchell & Netravali spline, Lanczos resampling kernels of arbitrary size, *etc.*). * **Interpolators** are linear maps such as the ones defined by the [`LazyAlgebra`](https://github.com/emmt/LazyAlgebra.jl) framework. - Applying the adjoint of interpolators is fully supported. This can be exploited for iterative fitting of data given an interpolated model. - Interpolators may have coefficients computed *on the fly* or tabulated (that is computed once). The former requires almost no memory but can be slower than the latter if the same interpolation is applied more than once. ## Installation The easiest way to install `LinearInterpolators` is via Julia's package manager: ```julia using Pkg pkg"add LinearInterpolators" ``` [doc-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [doc-stable-url]: https://emmt.github.io/LinearInterpolators.jl/stable [doc-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg [doc-dev-url]: https://emmt.github.io/LinearInterpolators.jl/dev [license-url]: ./LICENSE.md [license-img]: http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat [github-ci-img]: https://github.com/emmt/LinearInterpolators.jl/actions/workflows/CI.yml/badge.svg?branch=master [github-ci-url]: https://github.com/emmt/LinearInterpolators.jl/actions/workflows/CI.yml?query=branch%3Amaster [appveyor-img]: https://ci.appveyor.com/api/projects/status/github/emmt/LinearInterpolators.jl?branch=master [appveyor-url]: https://ci.appveyor.com/project/emmt/LinearInterpolators-jl/branch/master [codecov-img]: http://codecov.io/github/emmt/LinearInterpolators.jl/coverage.svg?branch=master [codecov-url]: http://codecov.io/github/emmt/LinearInterpolators.jl?branch=master [julia-url]: https://julialang.org/
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
docs
1604
# Introduction The `LinearInterpolators` package provides many linear interpolation methods for [Julia](https://julialang.org/). These interpolations are *linear* in the sense that the result depends linearly on the input. The source code is on [GitHub](https://github.com/emmt/LinearInterpolators.jl). ## Features * Separable interpolations are supported for arrays of any dimensionality. Interpolation kernels can be different along each interpolated dimension. * For 2D arrays, interpolations may be separable or not (*e.g.* to apply an image rotation). * Undimensional interpolations may be used to produce multi-dimensional results. * Many interpolation kernels are provided by the package [`InterpolationKernels`](https://github.com/emmt/InterpolationKernels.jl) (B-splines of degree 0 to 3, cardinal cubic splines, Catmull-Rom spline, Mitchell & Netravali spline, Lanczos resampling kernels of arbitrary size, *etc.*). * **Interpolators** are linear maps such as the ones defined by the [`LazyAlgebra`](https://github.com/emmt/LazyAlgebra.jl) framework. - Applying the adjoint of interpolators is fully supported. This can be exploited for iterative fitting of data given an interpolated model. - Interpolators may have coefficients computed *on the fly* or tabulated (that is computed once). The former requires almost no memory but can be slower than the latter if the same interpolation is applied more than once. ## Table of contents ```@contents Pages = ["install.md", "interpolation.md", "library.md", "notes.md"] ``` ## Index ```@index ```
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
docs
251
# Installation The easiest way to install `LinearInterpolators` is via Julia registry [`EmmtRegistry`](https://github.com/emmt/EmmtRegistry): ```julia using Pkg pkg"registry add https://github.com/emmt/EmmtRegistry" pkg"add LinearInterpolators" ```
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
docs
2968
# Linear interpolation Here *linear* means that the result depends linearly on the interpolated array. The interpolation functions (or kernels) may be linear or not (*e.g.*, cubic spline). ## Unidimensional interpolation Unidimensional interpolation is done by: ```julia apply(ker, x, src) -> dst ``` which interpolates source array `src` with kernel `ker` at positions `x`, the result is an array of same dimensions as `x`. The destination array can be provided: ```julia apply!(dst, ker, x, src) -> dst ``` which overwrites `dst` with the result of the interpolation of source `src` with kernel `ker` at positions specified by `x`. If `x` is an array, `dst` must have the same size as `x`; otherwise, `x` may be a fonction which is applied to all indices of `dst` (as generated by `eachindex(dst)`) to produce the coordinates where to interpolate the source. The destination `dst` is returned. The adjoint/direct operation can be applied: ```julia apply(P, ker, x, src) -> dst apply!(dst, P, ker, x, src) -> dst ``` where `P` is either `Adjoint` or `Direct`. If `P` is omitted, `Direct` is assumed. To linearly combine the result and the contents of the destination array, the following syntax is also implemented: ```julia apply!(α, P, ker, x, src, β, dst) -> dst ``` which overwrites `dst` with `β*dst` plus `α` times the result of the operation implied by `P` (`Direct` or `Adjoint`) on source `src` with kernel `ker` at positions specified by `x`. ## Separable multi-dimensional interpolation Separable multi-dimensional interpolation consists in interpolating each dimension of the source array with, possibly, different kernels and at given positions. For instance: ```julia apply(ker1, x1, [ker2=ker1,] x2, src) -> dst ``` yields the 2D separable interpolation of `src` with kernel `ker1` at positions `x1` along the first dimension of `src` and with kernel `ker2` at positions `x2` along the second dimension of `src`. Note that, if omitted the second kernel is assumed to be the same as the first one. The above example extends to more dimensions (providing it is implemented). Positions `x1`, `x2`, ... must be unidimensional arrays their lengths give the size of the result of the interpolation. The apply the adjoint and/or linearly combine the result of the interpolation and the contents of the destination array, the same methods as for unidimensional interpolation are supported, it is sufficient to replace arguments `ker,x` by `ker1,x1,[ker2=ker1,]x2`. ## Nonseparable multi-dimensional interpolation Nonseparable 2D interpolation is implemented where the coordinates to interpolate are given by an affine transform which converts the indices in the destination array into fractional coordinates in the source array (for the direct operation). The syntax is: ```julia apply!(dst, [P=Direct,] ker1, [ker2=ker1,] R, src) -> dst ``` where `R` is an `AffineTransform2D` and `P` is `Direct` (the default) or `Adjoint`.
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
docs
1087
# Reference The following provides detailled documentation about types and methods provided by the `LinearInterpolators` package. This information is also available from the REPL by typing `?` followed by the name of a method or a type. ## Tabulated Interpolators ```@docs LinearInterpolators.Interpolations.TabulatedInterpolators.TabulatedInterpolator ``` ## Two Dimensional Interpolators ```@docs LinearInterpolators.Interpolations.TwoDimensionalTransformInterpolator ``` ## Sparse Interpolators ```@docs LinearInterpolators.Interpolations.SparseInterpolators.SparseInterpolator LinearInterpolators.Interpolations.SparseInterpolators.fit LinearInterpolators.Interpolations.SparseInterpolators.regularize LinearInterpolators.Interpolations.SparseInterpolators.regularize! LinearInterpolators.Interpolations.SparseInterpolators.SparseUnidimensionalInterpolator ``` ## Utilities ### Limits ```@docs LinearInterpolators.Interpolations.Limits LinearInterpolators.Interpolations.limits ``` ### Interpolation coefficients ```@docs LinearInterpolators.Interpolations.getcoefs ```
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.1.8
d51d3f606a6fa83f0e43a528f67bd591753a2762
docs
9738
# Notes about interpolation ## Definitions ### Notations Round parenthesis, as in `f(x)`, denote a continuous function (`x` is a real number), square brakets, as in `a[k]`, denote a sampled function (`k ∈ ℤ` is an integer number). ### Interpolation Interpolation amounts to convolving with a kernel `ker(x)`: ``` f(x) = sum_k a[clip(k)]*ker(x - k) ``` where `clip(k)` imposes the boundary conditions and makes sure that the resulting index is within the bounds of array `a`. It can be seen that interpolation acts as a linear filter. Finite impulse response (FIR) filters have a finite support. By convention we use centered kernels whose support is `(-s/2,+s/2)` with `s`the width of the support. Infinite impulse response (IIR) filters have an infinite support. ### Floor and ceil functions Definitions of the `floor()` and `ceil()` functions (`∀ x ∈ ℝ`): ``` floor(x) = ⌊x⌋ = k ∈ ℤ s.x. k ≤ x < k+1 ceil(x) = ⌈x⌉ = k ∈ ℤ s.x. k-1 < x ≤ k ``` As a consequence (`∀ x ∈ ℝ` and `∀ k ∈ ℤ`): ``` floor(x) ≤ k <=> x < k+1 (1a) floor(x) < k <=> x < k (1b) floor(x) ≥ k <=> x ≥ k (1c) floor(x) > k <=> x ≥ k+1 (1d) ceil(x) ≤ k <=> x ≤ k (2a) ceil(x) < k <=> x ≤ k-1 (2b) ceil(x) ≥ k <=> x > k-1 (2c) ceil(x) > k <=> x > k (2d) ``` ## Kernel support and neighbors indices ### General support Let `(a,b)` with `a < b` be the support of the kernel. We assume that the support size is strict, i.e. `ker(x) = 0` if `x ≤ a` or `x ≥ b`. Thus, for a given `x`, the *neighbors* indices `k` to take into account in the interpolation formula are such that: ``` a < x - k < b <=> x - b < k < x - a ``` because outside this range, `ker(x - k) = 0`. Using the equivalences `(1b)` and `(2d)`, the *neighbors* indices `k` are those for which: ``` floor(x - b) < k < ceil(x - a) ``` holds. Equivalently: ``` floor(x - b + 1) ≤ k ≤ ceil(x - a - 1) ``` The first index to take into account is `kfirst = floor(x - b + 1)` and the last index to take into account is `klast = ceil(x - a - 1)`. ### Symmetric integer support Let `s = |b - a|` denotes the width of the support of the kernel. We now assume that the support size is integer (`s ∈ ℕ`), symmetric (`a = -s/2` and `b = +s/2`), and strict (`ker(x) = 0` if `|x| ≥ s/2`). Thus, for a given `x`, the *neighbors* indices `k` to take into account are such that: ``` |x - k| < s/2 <=> x - s/2 < k < x + s/2 <=> floor(x - s/2 + 1) ≤ k ≤ ceil(x + s/2 - 1) ``` The number of indices in the above range is equal to `s` unless `x` is integer while `s` is even or `x` is half-integer while `s` is odd. For these specific cases, there are `s - 1` indices in the range. However, always having the same number (`s`) of indices to consider yields code easier to write and optimize. We therefore choose that the first index `k1` and last index `ks` to take into account are either: - `k1 = floor(x - s/2 + 1)` and `ks = k1 + s - 1`; - or `ks = ceil(x + s/2 - 1)` and `k1 = ks - s + 1`. For the specific values of `x` aforementioned, one of `ker(x - k1) = 0` or `ker(x - ks) = 0` holds. For other values of `x`, the two choices are equivalent. In what follows, we choose to define the first index (before clipping) by: ``` k1 = k0 + 1 ``` with ``` k0 = floor(x - s/2) ``` and all indices to consider are: ``` k = k0 + 1, k0 + 2, ..., k0 + s ``` ## Clipping Now we have the constraint that: `kmin ≤ k ≤ kmax`. If we apply a *"nearest bound"* condition, then: - if `ks = k0 + s ≤ kmin`, then **all** infices `k` are clipped to `kmin`; using the fact that `s` is integer and equivalence `(1a)`, this occurs whenever: ``` kmin ≥ k0 + s = floor(x - s/2) + s = floor(x + s/2) <=> x < kmin - s/2 + 1 ``` - if `kmax ≤ k1 = k0 + 1`, then **all** indices `k` are clipped to `kmax`; using equivalence `(1c)`, this occurs whenever: ``` kmax ≤ k0 + 1 = floor(x - s/2 + 1) <=> x ≥ kmax + s/2 - 1 ``` These cases have to be considered before computing `k0 = (int)floor(x - s/2)` not only for optimization reasons but also because `floor(...)` may be beyond the limits of a numerical integer. The most simple case is when all considered indices are within the bounds which, using equivalences `(1a)` and `(1c)`, implies: ``` kmin ≤ k0 + 1 and k0 + s ≤ kmax <=> kmin + s/2 - 1 ≤ x < kmax - s/2 + 1 ``` ## Efficient computation of coefficients For a given value of `x` the coefficients of the interpolation are given by: ``` w[i] = ker(x - k0 - i) ``` with `k0 = floor(x - s/2)` and for `i = 1, 2, ..., s`. Note that there must be no clipping of the indices here, clipping is only for indexing the interpolated array and depends on the boundary conditions. Many interpolation kernels (see below) are *splines* which are piecewise polynomials defined over sub-intervals of size 1. That is: ``` ker(x) = h[1](x) for -s/2 ≤ x ≤ 1 - s/2 h[2](x) for 1 - s/2 ≤ x ≤ 2 - s/2 ... h[j](x) for j - 1 - s/2 ≤ x ≤ j - s/2 ... h[s](x) for s/2 - 1 ≤ x ≤ s/2 ``` Hence ``` w[i] = ker(x - k0 - i) = h[s + 1 - i](x - k0 - i) ``` In Julia implementation the interpolation coefficients are computed by the `getweights()` method specialized for each type of kernel an called as: ```julia getweights(ker, t) -> w1, w2, ..., wS ``` to get the `S` interpolation weights for a given offset `t` computed as: ``` t = x - floor(x) if s is even x - round(x) if s is odd ``` Thus `t ∈ [0,1]` if `S` is even or or for `t ∈ [-1/2,+1/2]` if `S` is odd. There are 2 cases depending on the parity of `s`: - If `s` is even, then `k0 = floor(x - s/2) = floor(x) - s/2` hence `t = x - floor(x) = x - k0 - s/2`. - If `s` is odd, then `k0 = floor(x - s/2) = floor(x + 1/2) - (s + 1)/2` `round(x) = floor(x + 1/2) = k0 + (s + 1)/2` and `t = x - round(x) = x - k0 - (s + 1)/2`. Therefore the argument of `h[s + 1 - i](...)` is: ``` x - k0 - i = t + s/2 - i if s is even t + (s + 1)/2 - i if s is odd ``` or: ``` x - k0 - i = t + ⌊(s + 1)/2⌋ - i ``` whatever the parity of `s`. ## Cubic Interpolation Keys's cubic interpolation kernels are given by: ``` ker(x) = (a+2)*|x|^3 - (a+3)*|x|^2 + 1 for |x| ≤ 1 = a*|x|^3 - 5*a*|x|^2 + 8*a*|x| - 4*a for 1 ≤ |x| ≤ 2 = 0 else ``` Mitchell and Netravali family of piecewise cubic filters (which depend on 2 parameters, `b` and `c`) are given by: ``` ker(x) = (1/6)*((12 - 9*b - 6*c)*|x|^3 + (-18 + 12*b + 6*c)*|x|^2 + (6 - 2*B)) for |x| ≤ 1 = (1/6)*((-b - 6*c)*|x|^3 + (6*b + 30*c)*|x|^2 + (-12*b - 48*c)*|x| + (8*b + 24*c)) for 1 ≤ |x| ≤ 2 = 0 else ``` These kernels are continuous, symmetric, have continuous 1st derivatives and sum of coefficients is one (needs not be normalized). Using the constraint: ``` b + 2*c = 1 ``` yields a cubic filter with, at least, quadratic order approximation. ``` (b,c) = (1,0) ==> cubic B-spline (b,c) = (0, -a) ==> Keys's cardinal cubics (b,c) = (0,1/2) ==> Catmull-Rom cubics (b,c) = (b,0) ==> Duff's tensioned B-spline (b,c) = (1/3,1/3) ==> recommended by Mitchell-Netravali ``` See paper by [Mitchell and Netravali, *"Reconstruction Filters in Computer Graphics Computer Graphics"*, Volume **22**, Number 4, (1988)][Mitchell-Netravali-pdf]. ## Resampling Resampling/interpolation is done by: ``` dst[i] = sum_j ker(grd[j] - pos[i])*src[j] ``` with `dst` the resulting array, `src` the values of a function sampled on a regular grid `grd`, `ker` the interpolation kernel, and `pos` the coordinates where to interpolate the sampled function. To limit the storage and the number of operations, we want to determine the range of indices for which the kernel function is non-zero. We have that: ``` abs(x) ≥ s/2 ==> ker(x) = 0 ``` with `s = length(ker)`. Taking `x = grd[j] - pos[i]`, then: ``` abs(x) < s/2 <==> pos[i] - s/2 < grd[j] < pos[i] + s/2 ``` `grd` is a `Range` so an "exact" formula for its elements is given by a linear interpolation: ``` grd[j] = t0*(j1 - j)/(j1 - j0) + t1*(j - j0)/(j1 - j0) ``` with: ``` j0 = 1 # first grid index j1 = length(grd) # last grid index t0 = first(grd) # first grid coordinate t1 = last(grd) # last grid coordinate ``` Note that: ``` d = (t1 - t0)/(j1 - j0) = step(grd) ``` is the increment between adjacent grip nodes (may be negative). The reverse formula in the form of a linear interpolation is: ``` f[i] = j0*(t1 - pos[i])/(t1 - t0) + j1*(pos[i] - t0)/(t1 - t0) ``` which yields a (fractional) grid index `f` for coordinate `pos[i]`. Taking care of the fact that the grid step may be negative, the maximum number of non-zero coefficients is given by: ``` M = floor(Int, length(ker)/abs(step(grd))) = floor(Int, w) ``` with: ``` w = length(ker)/abs(d) # beware d = step(grd) may be negative ``` the size of the support in grid index units. The indices of the first non-zero coefficients are: ``` j = l[i] + k ``` for `k = 1, 2, ..., M` and ``` l[i] = ceil(Int, f[i] - w/2) - 1 ``` the corresponding offsets are (assuming the grid extends infinitely): ``` x[i,j] = pos[i] - grd[j] = pos[i] - (grd[0] + (l[i] + k)*d) = ((pos[i] - grd[0])/d - l[i] - k)*d = (f[i] - l[i] - k)*d ``` The final issue to address is to avoid `InexactError` exceptions. [Mitchell-Netravali-pdf]: http://www.cs.utexas.edu/users/fussell/courses/cs384g/lectures/mitchell/Mitchell.pdf
LinearInterpolators
https://github.com/emmt/LinearInterpolators.jl.git
[ "MIT" ]
0.5.0
79737366da299bd36a58b8779a5dcdcb0364befc
code
2500
# ref: https://www.geeksforgeeks.org/sdl-library-in-c-c-with-examples/ using SimpleDirectMediaLayer.LibSDL2 SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 16) SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 16) @assert SDL_Init(SDL_INIT_EVERYTHING) == 0 "error initializing SDL: $(unsafe_string(SDL_GetError()))" win = SDL_CreateWindow("Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1000, 1000, SDL_WINDOW_SHOWN) SDL_SetWindowResizable(win, SDL_TRUE) renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC) surface = IMG_Load(joinpath(@__DIR__, "..", "assets", "cat.png")) tex = SDL_CreateTextureFromSurface(renderer, surface) SDL_FreeSurface(surface) w_ref, h_ref = Ref{Cint}(0), Ref{Cint}(0) SDL_QueryTexture(tex, C_NULL, C_NULL, w_ref, h_ref) try w, h = w_ref[], h_ref[] x = (1000 - w) ÷ 2 y = (1000 - h) ÷ 2 dest_ref = Ref(SDL_Rect(x, y, w, h)) close = false speed = 300 while !close event_ref = Ref{SDL_Event}() while Bool(SDL_PollEvent(event_ref)) evt = event_ref[] evt_ty = evt.type if evt_ty == SDL_QUIT close = true break elseif evt_ty == SDL_KEYDOWN scan_code = evt.key.keysym.scancode if scan_code == SDL_SCANCODE_W || scan_code == SDL_SCANCODE_UP y -= speed / 30 break elseif scan_code == SDL_SCANCODE_A || scan_code == SDL_SCANCODE_LEFT x -= speed / 30 break elseif scan_code == SDL_SCANCODE_S || scan_code == SDL_SCANCODE_DOWN y += speed / 30 break elseif scan_code == SDL_SCANCODE_D || scan_code == SDL_SCANCODE_RIGHT x += speed / 30 break else break end end end x + w > 1000 && (x = 1000 - w;) x < 0 && (x = 0;) y + h > 1000 && (y = 1000 - h;) y < 0 && (y = 0;) dest_ref[] = SDL_Rect(x, y, w, h) SDL_RenderClear(renderer) SDL_RenderCopy(renderer, tex, C_NULL, dest_ref) dest = dest_ref[] x, y, w, h = dest.x, dest.y, dest.w, dest.h SDL_RenderPresent(renderer) SDL_Delay(1000 ÷ 60) end finally SDL_DestroyTexture(tex) SDL_DestroyRenderer(renderer) SDL_DestroyWindow(win) SDL_Quit() end
SimpleDirectMediaLayer
https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl.git
[ "MIT" ]
0.5.0
79737366da299bd36a58b8779a5dcdcb0364befc
code
910
# This file transformed from Lazy Foo' Productions "Playing Sounds" tutorial: # http://lazyfoo.net/SDL_tutorials/lesson11/index.php using SimpleDirectMediaLayer.LibSDL2 SDL_Init(SDL_INIT_AUDIO) if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 1, 1024) < 0) println("SDL_mixer could not initialize!", Mix_GetError()) end #Load the music aud_files = dirname(@__FILE__) music = Mix_LoadMUS("$aud_files/beat.wav") if (music == C_NULL) error("$aud_files/beat.wav not found.") end scratch = Mix_LoadWAV_RW(SDL_RWFromFile("$aud_files/scratch.wav", "rb"), 1) high = Mix_LoadWAV_RW(SDL_RWFromFile("$aud_files/high.wav", "rb"), 1) med = Mix_LoadWAV_RW(SDL_RWFromFile("$aud_files/medium.wav", "rb"), 1) low = Mix_LoadWAV_RW(SDL_RWFromFile("$aud_files/low.wav", "rb"), 1) Mix_PlayChannelTimed(-1, med, 0, -1) Mix_PlayMusic(music, -1) sleep(1) Mix_PauseMusic() sleep(1) Mix_ResumeMusic() sleep(1) Mix_HaltMusic()
SimpleDirectMediaLayer
https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl.git
[ "MIT" ]
0.5.0
79737366da299bd36a58b8779a5dcdcb0364befc
code
2553
using Clang using Clang.Generators using SDL2_jll using SDL2_mixer_jll using SDL2_image_jll using SDL2_ttf_jll using SDL2_gfx_jll cd(@__DIR__) sdl2_include_dir = joinpath(SDL2_jll.artifact_dir, "include") |> normpath sdl_gfx_include_dir = joinpath(SDL2_gfx_jll.artifact_dir, "include") |> normpath sdl_mixer_h = joinpath(SDL2_mixer_jll.artifact_dir, "include", "SDL2", "SDL_mixer.h") |> normpath sdl_image_h = joinpath(SDL2_image_jll.artifact_dir, "include", "SDL2", "SDL_image.h") |> normpath sdl_ttf_h = joinpath(SDL2_ttf_jll.artifact_dir, "include", "SDL2", "SDL_ttf.h") |> normpath sdl_h = joinpath(sdl2_include_dir, "SDL2", "SDL.h") sdl_framerate_h = joinpath(sdl_gfx_include_dir, "SDL2", "SDL2_framerate.h") sdl_gfxPrimitives_h = joinpath(sdl_gfx_include_dir, "SDL2", "SDL2_gfxPrimitives.h") sdl_imageFilter_h = joinpath(sdl_gfx_include_dir, "SDL2", "SDL2_imageFilter.h") sdl_rotozoom_h = joinpath(sdl_gfx_include_dir, "SDL2", "SDL2_rotozoom.h") local_include_dir = joinpath(@__DIR__, "include") isdir(local_include_dir) && rm(local_include_dir, recursive=true) cp(sdl2_include_dir, local_include_dir, force=true) cp(sdl_mixer_h, joinpath(@__DIR__, "include", "SDL2", basename(sdl_mixer_h))) cp(sdl_image_h, joinpath(@__DIR__, "include", "SDL2", basename(sdl_image_h))) cp(sdl_ttf_h, joinpath(@__DIR__, "include", "SDL2", basename(sdl_ttf_h))) cp(sdl_framerate_h, joinpath(@__DIR__, "include", "SDL2", basename(sdl_framerate_h))) cp(sdl_gfxPrimitives_h, joinpath(@__DIR__, "include", "SDL2", basename(sdl_gfxPrimitives_h))) cp(sdl_imageFilter_h, joinpath(@__DIR__, "include", "SDL2", basename(sdl_imageFilter_h))) cp(sdl_rotozoom_h, joinpath(@__DIR__, "include", "SDL2", basename(sdl_rotozoom_h))) sdl_mixer_h = joinpath(local_include_dir, "SDL2", "SDL_mixer.h") sdl_image_h = joinpath(local_include_dir, "SDL2", "SDL_image.h") sdl_ttf_h = joinpath(local_include_dir, "SDL2", "SDL_ttf.h") sdl_h = joinpath(local_include_dir, "SDL2", "SDL.h") sdl_framerate_h = joinpath(local_include_dir, "SDL2", "SDL2_framerate.h") sdl_gfxPrimitives_h = joinpath(local_include_dir, "SDL2", "SDL2_gfxPrimitives.h") sdl_imageFilter_h = joinpath(local_include_dir, "SDL2", "SDL2_imageFilter.h") sdl_rotozoom_h = joinpath(local_include_dir, "SDL2", "SDL2_rotozoom.h") options = load_options(joinpath(@__DIR__, "generator.toml")) args = get_default_args() push!(args, "-I$local_include_dir") ctx = create_context([sdl_h, sdl_mixer_h, sdl_image_h, sdl_ttf_h, sdl_framerate_h, sdl_gfxPrimitives_h, sdl_imageFilter_h, sdl_rotozoom_h], args, options) build!(ctx)
SimpleDirectMediaLayer
https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl.git
[ "MIT" ]
0.5.0
79737366da299bd36a58b8779a5dcdcb0364befc
code
473
const SDL_MIN_SINT8 = reinterpret(Int8, ~0x7F) const SDL_MIN_SINT16 = reinterpret(Int16, ~0x7FFF) const SDL_MIN_SINT32 = reinterpret(Int32, ~0x7FFFFFFF) const SDL_MIN_SINT64 = reinterpret(Int64, ~0x7FFFFFFFFFFFFFFF) const SDL_ICONV_ERROR = reinterpret(Csize_t, -1) const SDL_ICONV_E2BIG = reinterpret(Csize_t, -2) const SDL_ICONV_EILSEQ = reinterpret(Csize_t, -3) const SDL_ICONV_EINVAL = reinterpret(Csize_t, -4) const SDL_TOUCH_MOUSEID = reinterpret(UInt32, Int32(-1))
SimpleDirectMediaLayer
https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl.git
[ "MIT" ]
0.5.0
79737366da299bd36a58b8779a5dcdcb0364befc
code
242301
module LibSDL2 using SDL2_jll export SDL2_jll using SDL2_mixer_jll export SDL2_mixer_jll using SDL2_image_jll export SDL2_image_jll using SDL2_ttf_jll export SDL2_ttf_jll using SDL2_gfx_jll export SDL2_gfx_jll using CEnum const SDL_MIN_SINT8 = reinterpret(Int8, ~0x7F) const SDL_MIN_SINT16 = reinterpret(Int16, ~0x7FFF) const SDL_MIN_SINT32 = reinterpret(Int32, ~0x7FFFFFFF) const SDL_MIN_SINT64 = reinterpret(Int64, ~0x7FFFFFFFFFFFFFFF) const SDL_ICONV_ERROR = reinterpret(Csize_t, -1) const SDL_ICONV_E2BIG = reinterpret(Csize_t, -2) const SDL_ICONV_EILSEQ = reinterpret(Csize_t, -3) const SDL_ICONV_EINVAL = reinterpret(Csize_t, -4) const SDL_TOUCH_MOUSEID = reinterpret(UInt32, Int32(-1)) const Uint32 = UInt32 const Uint8 = UInt8 const Sint8 = Int8 const Sint16 = Int16 const Uint16 = UInt16 const Sint32 = Int32 const Sint64 = Int64 const Uint64 = UInt64 function SDL_memset(dst, c, len) ccall((:SDL_memset, libsdl2), Ptr{Cvoid}, (Ptr{Cvoid}, Cint, Csize_t), dst, c, len) end function SDL_memcpy(dst, src, len) ccall((:SDL_memcpy, libsdl2), Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), dst, src, len) end function SDL_iconv_string(tocode, fromcode, inbuf, inbytesleft) ccall((:SDL_iconv_string, libsdl2), Ptr{Cchar}, (Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, Csize_t), tocode, fromcode, inbuf, inbytesleft) end function SDL_strlen(str) ccall((:SDL_strlen, libsdl2), Csize_t, (Ptr{Cchar},), str) end function SDL_wcslen(wstr) ccall((:SDL_wcslen, libsdl2), Csize_t, (Ptr{Cwchar_t},), wstr) end function _SDL_size_mul_overflow_builtin(a, b, ret) ccall((:_SDL_size_mul_overflow_builtin, libsdl2), Cint, (Csize_t, Csize_t, Ptr{Csize_t}), a, b, ret) end function _SDL_size_add_overflow_builtin(a, b, ret) ccall((:_SDL_size_add_overflow_builtin, libsdl2), Cint, (Csize_t, Csize_t, Ptr{Csize_t}), a, b, ret) end struct SDL_AssertData always_ignore::Cint trigger_count::Cuint condition::Ptr{Cchar} filename::Ptr{Cchar} linenum::Cint _function::Ptr{Cchar} next::Ptr{SDL_AssertData} end @cenum SDL_AssertState::UInt32 begin SDL_ASSERTION_RETRY = 0 SDL_ASSERTION_BREAK = 1 SDL_ASSERTION_ABORT = 2 SDL_ASSERTION_IGNORE = 3 SDL_ASSERTION_ALWAYS_IGNORE = 4 end function SDL_ReportAssertion(arg1, arg2, arg3, arg4) ccall((:SDL_ReportAssertion, libsdl2), SDL_AssertState, (Ptr{SDL_AssertData}, Ptr{Cchar}, Ptr{Cchar}, Cint), arg1, arg2, arg3, arg4) end struct SDL_atomic_t value::Cint end function SDL_AtomicAdd(a, v) ccall((:SDL_AtomicAdd, libsdl2), Cint, (Ptr{SDL_atomic_t}, Cint), a, v) end @cenum SDL_errorcode::UInt32 begin SDL_ENOMEM = 0 SDL_EFREAD = 1 SDL_EFWRITE = 2 SDL_EFSEEK = 3 SDL_UNSUPPORTED = 4 SDL_LASTERROR = 5 end function SDL_Error(code) ccall((:SDL_Error, libsdl2), Cint, (SDL_errorcode,), code) end function SDL_SwapFloat(x) ccall((:SDL_SwapFloat, libsdl2), Cfloat, (Cfloat,), x) end mutable struct SDL_mutex end function SDL_LockMutex(mutex) ccall((:SDL_LockMutex, libsdl2), Cint, (Ptr{SDL_mutex},), mutex) end function SDL_UnlockMutex(mutex) ccall((:SDL_UnlockMutex, libsdl2), Cint, (Ptr{SDL_mutex},), mutex) end struct __JL_Ctag_559 data::NTuple{24, UInt8} end function Base.getproperty(x::Ptr{__JL_Ctag_559}, f::Symbol) f === :stdio && return Ptr{__JL_Ctag_560}(x + 0) f === :mem && return Ptr{__JL_Ctag_561}(x + 0) f === :unknown && return Ptr{__JL_Ctag_562}(x + 0) return getfield(x, f) end function Base.getproperty(x::__JL_Ctag_559, f::Symbol) r = Ref{__JL_Ctag_559}(x) ptr = Base.unsafe_convert(Ptr{__JL_Ctag_559}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{__JL_Ctag_559}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end struct SDL_RWops data::NTuple{72, UInt8} end function Base.getproperty(x::Ptr{SDL_RWops}, f::Symbol) f === :size && return Ptr{Ptr{Cvoid}}(x + 0) f === :seek && return Ptr{Ptr{Cvoid}}(x + 8) f === :read && return Ptr{Ptr{Cvoid}}(x + 16) f === :write && return Ptr{Ptr{Cvoid}}(x + 24) f === :close && return Ptr{Ptr{Cvoid}}(x + 32) f === :type && return Ptr{Uint32}(x + 40) f === :hidden && return Ptr{__JL_Ctag_559}(x + 48) return getfield(x, f) end function Base.getproperty(x::SDL_RWops, f::Symbol) r = Ref{SDL_RWops}(x) ptr = Base.unsafe_convert(Ptr{SDL_RWops}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{SDL_RWops}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end const SDL_AudioFormat = Uint16 # typedef void ( SDLCALL * SDL_AudioCallback ) ( void * userdata , Uint8 * stream , int len ) const SDL_AudioCallback = Ptr{Cvoid} struct SDL_AudioSpec freq::Cint format::SDL_AudioFormat channels::Uint8 silence::Uint8 samples::Uint16 padding::Uint16 size::Uint32 callback::SDL_AudioCallback userdata::Ptr{Cvoid} end function SDL_LoadWAV_RW(src, freesrc, spec, audio_buf, audio_len) ccall((:SDL_LoadWAV_RW, libsdl2), Ptr{SDL_AudioSpec}, (Ptr{SDL_RWops}, Cint, Ptr{SDL_AudioSpec}, Ptr{Ptr{Uint8}}, Ptr{Uint32}), src, freesrc, spec, audio_buf, audio_len) end function SDL_RWFromFile(file, mode) ccall((:SDL_RWFromFile, libsdl2), Ptr{SDL_RWops}, (Ptr{Cchar}, Ptr{Cchar}), file, mode) end struct SDL_Color r::Uint8 g::Uint8 b::Uint8 a::Uint8 end struct SDL_Palette ncolors::Cint colors::Ptr{SDL_Color} version::Uint32 refcount::Cint end struct SDL_PixelFormat format::Uint32 palette::Ptr{SDL_Palette} BitsPerPixel::Uint8 BytesPerPixel::Uint8 padding::NTuple{2, Uint8} Rmask::Uint32 Gmask::Uint32 Bmask::Uint32 Amask::Uint32 Rloss::Uint8 Gloss::Uint8 Bloss::Uint8 Aloss::Uint8 Rshift::Uint8 Gshift::Uint8 Bshift::Uint8 Ashift::Uint8 refcount::Cint next::Ptr{SDL_PixelFormat} end struct SDL_Rect x::Cint y::Cint w::Cint h::Cint end mutable struct SDL_BlitMap end struct SDL_Surface flags::Uint32 format::Ptr{SDL_PixelFormat} w::Cint h::Cint pitch::Cint pixels::Ptr{Cvoid} userdata::Ptr{Cvoid} locked::Cint list_blitmap::Ptr{Cvoid} clip_rect::SDL_Rect map::Ptr{SDL_BlitMap} refcount::Cint end function SDL_LoadBMP_RW(src, freesrc) ccall((:SDL_LoadBMP_RW, libsdl2), Ptr{SDL_Surface}, (Ptr{SDL_RWops}, Cint), src, freesrc) end function SDL_SaveBMP_RW(surface, dst, freedst) ccall((:SDL_SaveBMP_RW, libsdl2), Cint, (Ptr{SDL_Surface}, Ptr{SDL_RWops}, Cint), surface, dst, freedst) end function SDL_UpperBlit(src, srcrect, dst, dstrect) ccall((:SDL_UpperBlit, libsdl2), Cint, (Ptr{SDL_Surface}, Ptr{SDL_Rect}, Ptr{SDL_Surface}, Ptr{SDL_Rect}), src, srcrect, dst, dstrect) end function SDL_UpperBlitScaled(src, srcrect, dst, dstrect) ccall((:SDL_UpperBlitScaled, libsdl2), Cint, (Ptr{SDL_Surface}, Ptr{SDL_Rect}, Ptr{SDL_Surface}, Ptr{SDL_Rect}), src, srcrect, dst, dstrect) end function SDL_GameControllerAddMappingsFromRW(rw, freerw) ccall((:SDL_GameControllerAddMappingsFromRW, libsdl2), Cint, (Ptr{SDL_RWops}, Cint), rw, freerw) end function SDL_PumpEvents() ccall((:SDL_PumpEvents, libsdl2), Cvoid, ()) end struct SDL_Event data::NTuple{56, UInt8} end function Base.getproperty(x::Ptr{SDL_Event}, f::Symbol) f === :type && return Ptr{Uint32}(x + 0) f === :common && return Ptr{SDL_CommonEvent}(x + 0) f === :display && return Ptr{SDL_DisplayEvent}(x + 0) f === :window && return Ptr{SDL_WindowEvent}(x + 0) f === :key && return Ptr{SDL_KeyboardEvent}(x + 0) f === :edit && return Ptr{SDL_TextEditingEvent}(x + 0) f === :editExt && return Ptr{SDL_TextEditingExtEvent}(x + 0) f === :text && return Ptr{SDL_TextInputEvent}(x + 0) f === :motion && return Ptr{SDL_MouseMotionEvent}(x + 0) f === :button && return Ptr{SDL_MouseButtonEvent}(x + 0) f === :wheel && return Ptr{SDL_MouseWheelEvent}(x + 0) f === :jaxis && return Ptr{SDL_JoyAxisEvent}(x + 0) f === :jball && return Ptr{SDL_JoyBallEvent}(x + 0) f === :jhat && return Ptr{SDL_JoyHatEvent}(x + 0) f === :jbutton && return Ptr{SDL_JoyButtonEvent}(x + 0) f === :jdevice && return Ptr{SDL_JoyDeviceEvent}(x + 0) f === :jbattery && return Ptr{SDL_JoyBatteryEvent}(x + 0) f === :caxis && return Ptr{SDL_ControllerAxisEvent}(x + 0) f === :cbutton && return Ptr{SDL_ControllerButtonEvent}(x + 0) f === :cdevice && return Ptr{SDL_ControllerDeviceEvent}(x + 0) f === :ctouchpad && return Ptr{SDL_ControllerTouchpadEvent}(x + 0) f === :csensor && return Ptr{SDL_ControllerSensorEvent}(x + 0) f === :adevice && return Ptr{SDL_AudioDeviceEvent}(x + 0) f === :sensor && return Ptr{SDL_SensorEvent}(x + 0) f === :quit && return Ptr{SDL_QuitEvent}(x + 0) f === :user && return Ptr{SDL_UserEvent}(x + 0) f === :syswm && return Ptr{SDL_SysWMEvent}(x + 0) f === :tfinger && return Ptr{SDL_TouchFingerEvent}(x + 0) f === :mgesture && return Ptr{SDL_MultiGestureEvent}(x + 0) f === :dgesture && return Ptr{SDL_DollarGestureEvent}(x + 0) f === :drop && return Ptr{SDL_DropEvent}(x + 0) f === :padding && return Ptr{NTuple{56, Uint8}}(x + 0) return getfield(x, f) end function Base.getproperty(x::SDL_Event, f::Symbol) r = Ref{SDL_Event}(x) ptr = Base.unsafe_convert(Ptr{SDL_Event}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{SDL_Event}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end @cenum SDL_eventaction::UInt32 begin SDL_ADDEVENT = 0 SDL_PEEKEVENT = 1 SDL_GETEVENT = 2 end function SDL_PeepEvents(events, numevents, action, minType, maxType) ccall((:SDL_PeepEvents, libsdl2), Cint, (Ptr{SDL_Event}, Cint, SDL_eventaction, Uint32, Uint32), events, numevents, action, minType, maxType) end function SDL_EventState(type, state) ccall((:SDL_EventState, libsdl2), Uint8, (Uint32, Cint), type, state) end function SDL_GetPlatform() ccall((:SDL_GetPlatform, libsdl2), Ptr{Cchar}, ()) end @cenum SDL_bool::UInt32 begin SDL_FALSE = 0 SDL_TRUE = 1 end @cenum SDL_DUMMY_ENUM::UInt32 begin DUMMY_ENUM_VALUE = 0 end function SDL_malloc(size) ccall((:SDL_malloc, libsdl2), Ptr{Cvoid}, (Csize_t,), size) end function SDL_calloc(nmemb, size) ccall((:SDL_calloc, libsdl2), Ptr{Cvoid}, (Csize_t, Csize_t), nmemb, size) end function SDL_realloc(mem, size) ccall((:SDL_realloc, libsdl2), Ptr{Cvoid}, (Ptr{Cvoid}, Csize_t), mem, size) end function SDL_free(mem) ccall((:SDL_free, libsdl2), Cvoid, (Ptr{Cvoid},), mem) end # typedef void * ( SDLCALL * SDL_malloc_func ) ( size_t size ) const SDL_malloc_func = Ptr{Cvoid} # typedef void * ( SDLCALL * SDL_calloc_func ) ( size_t nmemb , size_t size ) const SDL_calloc_func = Ptr{Cvoid} # typedef void * ( SDLCALL * SDL_realloc_func ) ( void * mem , size_t size ) const SDL_realloc_func = Ptr{Cvoid} # typedef void ( SDLCALL * SDL_free_func ) ( void * mem ) const SDL_free_func = Ptr{Cvoid} function SDL_GetOriginalMemoryFunctions(malloc_func, calloc_func, realloc_func, free_func) ccall((:SDL_GetOriginalMemoryFunctions, libsdl2), Cvoid, (Ptr{SDL_malloc_func}, Ptr{SDL_calloc_func}, Ptr{SDL_realloc_func}, Ptr{SDL_free_func}), malloc_func, calloc_func, realloc_func, free_func) end function SDL_GetMemoryFunctions(malloc_func, calloc_func, realloc_func, free_func) ccall((:SDL_GetMemoryFunctions, libsdl2), Cvoid, (Ptr{SDL_malloc_func}, Ptr{SDL_calloc_func}, Ptr{SDL_realloc_func}, Ptr{SDL_free_func}), malloc_func, calloc_func, realloc_func, free_func) end function SDL_SetMemoryFunctions(malloc_func, calloc_func, realloc_func, free_func) ccall((:SDL_SetMemoryFunctions, libsdl2), Cint, (SDL_malloc_func, SDL_calloc_func, SDL_realloc_func, SDL_free_func), malloc_func, calloc_func, realloc_func, free_func) end function SDL_GetNumAllocations() ccall((:SDL_GetNumAllocations, libsdl2), Cint, ()) end function SDL_getenv(name) ccall((:SDL_getenv, libsdl2), Ptr{Cchar}, (Ptr{Cchar},), name) end function SDL_setenv(name, value, overwrite) ccall((:SDL_setenv, libsdl2), Cint, (Ptr{Cchar}, Ptr{Cchar}, Cint), name, value, overwrite) end function SDL_qsort(base, nmemb, size, compare) ccall((:SDL_qsort, libsdl2), Cvoid, (Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}), base, nmemb, size, compare) end function SDL_bsearch(key, base, nmemb, size, compare) ccall((:SDL_bsearch, libsdl2), Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}), key, base, nmemb, size, compare) end function SDL_abs(x) ccall((:SDL_abs, libsdl2), Cint, (Cint,), x) end function SDL_isalpha(x) ccall((:SDL_isalpha, libsdl2), Cint, (Cint,), x) end function SDL_isalnum(x) ccall((:SDL_isalnum, libsdl2), Cint, (Cint,), x) end function SDL_isblank(x) ccall((:SDL_isblank, libsdl2), Cint, (Cint,), x) end function SDL_iscntrl(x) ccall((:SDL_iscntrl, libsdl2), Cint, (Cint,), x) end function SDL_isdigit(x) ccall((:SDL_isdigit, libsdl2), Cint, (Cint,), x) end function SDL_isxdigit(x) ccall((:SDL_isxdigit, libsdl2), Cint, (Cint,), x) end function SDL_ispunct(x) ccall((:SDL_ispunct, libsdl2), Cint, (Cint,), x) end function SDL_isspace(x) ccall((:SDL_isspace, libsdl2), Cint, (Cint,), x) end function SDL_isupper(x) ccall((:SDL_isupper, libsdl2), Cint, (Cint,), x) end function SDL_islower(x) ccall((:SDL_islower, libsdl2), Cint, (Cint,), x) end function SDL_isprint(x) ccall((:SDL_isprint, libsdl2), Cint, (Cint,), x) end function SDL_isgraph(x) ccall((:SDL_isgraph, libsdl2), Cint, (Cint,), x) end function SDL_toupper(x) ccall((:SDL_toupper, libsdl2), Cint, (Cint,), x) end function SDL_tolower(x) ccall((:SDL_tolower, libsdl2), Cint, (Cint,), x) end function SDL_crc16(crc, data, len) ccall((:SDL_crc16, libsdl2), Uint16, (Uint16, Ptr{Cvoid}, Csize_t), crc, data, len) end function SDL_crc32(crc, data, len) ccall((:SDL_crc32, libsdl2), Uint32, (Uint32, Ptr{Cvoid}, Csize_t), crc, data, len) end function SDL_memset4(dst, val, dwords) ccall((:SDL_memset4, libsdl2), Cvoid, (Ptr{Cvoid}, Uint32, Csize_t), dst, val, dwords) end function SDL_memmove(dst, src, len) ccall((:SDL_memmove, libsdl2), Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), dst, src, len) end function SDL_memcmp(s1, s2, len) ccall((:SDL_memcmp, libsdl2), Cint, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), s1, s2, len) end function SDL_wcslcpy(dst, src, maxlen) ccall((:SDL_wcslcpy, libsdl2), Csize_t, (Ptr{Cwchar_t}, Ptr{Cwchar_t}, Csize_t), dst, src, maxlen) end function SDL_wcslcat(dst, src, maxlen) ccall((:SDL_wcslcat, libsdl2), Csize_t, (Ptr{Cwchar_t}, Ptr{Cwchar_t}, Csize_t), dst, src, maxlen) end function SDL_wcsdup(wstr) ccall((:SDL_wcsdup, libsdl2), Ptr{Cwchar_t}, (Ptr{Cwchar_t},), wstr) end function SDL_wcsstr(haystack, needle) ccall((:SDL_wcsstr, libsdl2), Ptr{Cwchar_t}, (Ptr{Cwchar_t}, Ptr{Cwchar_t}), haystack, needle) end function SDL_wcscmp(str1, str2) ccall((:SDL_wcscmp, libsdl2), Cint, (Ptr{Cwchar_t}, Ptr{Cwchar_t}), str1, str2) end function SDL_wcsncmp(str1, str2, maxlen) ccall((:SDL_wcsncmp, libsdl2), Cint, (Ptr{Cwchar_t}, Ptr{Cwchar_t}, Csize_t), str1, str2, maxlen) end function SDL_wcscasecmp(str1, str2) ccall((:SDL_wcscasecmp, libsdl2), Cint, (Ptr{Cwchar_t}, Ptr{Cwchar_t}), str1, str2) end function SDL_wcsncasecmp(str1, str2, len) ccall((:SDL_wcsncasecmp, libsdl2), Cint, (Ptr{Cwchar_t}, Ptr{Cwchar_t}, Csize_t), str1, str2, len) end function SDL_strlcpy(dst, src, maxlen) ccall((:SDL_strlcpy, libsdl2), Csize_t, (Ptr{Cchar}, Ptr{Cchar}, Csize_t), dst, src, maxlen) end function SDL_utf8strlcpy(dst, src, dst_bytes) ccall((:SDL_utf8strlcpy, libsdl2), Csize_t, (Ptr{Cchar}, Ptr{Cchar}, Csize_t), dst, src, dst_bytes) end function SDL_strlcat(dst, src, maxlen) ccall((:SDL_strlcat, libsdl2), Csize_t, (Ptr{Cchar}, Ptr{Cchar}, Csize_t), dst, src, maxlen) end function SDL_strdup(str) ccall((:SDL_strdup, libsdl2), Ptr{Cchar}, (Ptr{Cchar},), str) end function SDL_strrev(str) ccall((:SDL_strrev, libsdl2), Ptr{Cchar}, (Ptr{Cchar},), str) end function SDL_strupr(str) ccall((:SDL_strupr, libsdl2), Ptr{Cchar}, (Ptr{Cchar},), str) end function SDL_strlwr(str) ccall((:SDL_strlwr, libsdl2), Ptr{Cchar}, (Ptr{Cchar},), str) end function SDL_strchr(str, c) ccall((:SDL_strchr, libsdl2), Ptr{Cchar}, (Ptr{Cchar}, Cint), str, c) end function SDL_strrchr(str, c) ccall((:SDL_strrchr, libsdl2), Ptr{Cchar}, (Ptr{Cchar}, Cint), str, c) end function SDL_strstr(haystack, needle) ccall((:SDL_strstr, libsdl2), Ptr{Cchar}, (Ptr{Cchar}, Ptr{Cchar}), haystack, needle) end function SDL_strtokr(s1, s2, saveptr) ccall((:SDL_strtokr, libsdl2), Ptr{Cchar}, (Ptr{Cchar}, Ptr{Cchar}, Ptr{Ptr{Cchar}}), s1, s2, saveptr) end function SDL_utf8strlen(str) ccall((:SDL_utf8strlen, libsdl2), Csize_t, (Ptr{Cchar},), str) end function SDL_utf8strnlen(str, bytes) ccall((:SDL_utf8strnlen, libsdl2), Csize_t, (Ptr{Cchar}, Csize_t), str, bytes) end function SDL_itoa(value, str, radix) ccall((:SDL_itoa, libsdl2), Ptr{Cchar}, (Cint, Ptr{Cchar}, Cint), value, str, radix) end function SDL_uitoa(value, str, radix) ccall((:SDL_uitoa, libsdl2), Ptr{Cchar}, (Cuint, Ptr{Cchar}, Cint), value, str, radix) end function SDL_ltoa(value, str, radix) ccall((:SDL_ltoa, libsdl2), Ptr{Cchar}, (Clong, Ptr{Cchar}, Cint), value, str, radix) end function SDL_ultoa(value, str, radix) ccall((:SDL_ultoa, libsdl2), Ptr{Cchar}, (Culong, Ptr{Cchar}, Cint), value, str, radix) end function SDL_lltoa(value, str, radix) ccall((:SDL_lltoa, libsdl2), Ptr{Cchar}, (Sint64, Ptr{Cchar}, Cint), value, str, radix) end function SDL_ulltoa(value, str, radix) ccall((:SDL_ulltoa, libsdl2), Ptr{Cchar}, (Uint64, Ptr{Cchar}, Cint), value, str, radix) end function SDL_atoi(str) ccall((:SDL_atoi, libsdl2), Cint, (Ptr{Cchar},), str) end function SDL_atof(str) ccall((:SDL_atof, libsdl2), Cdouble, (Ptr{Cchar},), str) end function SDL_strtol(str, endp, base) ccall((:SDL_strtol, libsdl2), Clong, (Ptr{Cchar}, Ptr{Ptr{Cchar}}, Cint), str, endp, base) end function SDL_strtoul(str, endp, base) ccall((:SDL_strtoul, libsdl2), Culong, (Ptr{Cchar}, Ptr{Ptr{Cchar}}, Cint), str, endp, base) end function SDL_strtoll(str, endp, base) ccall((:SDL_strtoll, libsdl2), Sint64, (Ptr{Cchar}, Ptr{Ptr{Cchar}}, Cint), str, endp, base) end function SDL_strtoull(str, endp, base) ccall((:SDL_strtoull, libsdl2), Uint64, (Ptr{Cchar}, Ptr{Ptr{Cchar}}, Cint), str, endp, base) end function SDL_strtod(str, endp) ccall((:SDL_strtod, libsdl2), Cdouble, (Ptr{Cchar}, Ptr{Ptr{Cchar}}), str, endp) end function SDL_strcmp(str1, str2) ccall((:SDL_strcmp, libsdl2), Cint, (Ptr{Cchar}, Ptr{Cchar}), str1, str2) end function SDL_strncmp(str1, str2, maxlen) ccall((:SDL_strncmp, libsdl2), Cint, (Ptr{Cchar}, Ptr{Cchar}, Csize_t), str1, str2, maxlen) end function SDL_strcasecmp(str1, str2) ccall((:SDL_strcasecmp, libsdl2), Cint, (Ptr{Cchar}, Ptr{Cchar}), str1, str2) end function SDL_strncasecmp(str1, str2, len) ccall((:SDL_strncasecmp, libsdl2), Cint, (Ptr{Cchar}, Ptr{Cchar}, Csize_t), str1, str2, len) end function SDL_acos(x) ccall((:SDL_acos, libsdl2), Cdouble, (Cdouble,), x) end function SDL_acosf(x) ccall((:SDL_acosf, libsdl2), Cfloat, (Cfloat,), x) end function SDL_asin(x) ccall((:SDL_asin, libsdl2), Cdouble, (Cdouble,), x) end function SDL_asinf(x) ccall((:SDL_asinf, libsdl2), Cfloat, (Cfloat,), x) end function SDL_atan(x) ccall((:SDL_atan, libsdl2), Cdouble, (Cdouble,), x) end function SDL_atanf(x) ccall((:SDL_atanf, libsdl2), Cfloat, (Cfloat,), x) end function SDL_atan2(y, x) ccall((:SDL_atan2, libsdl2), Cdouble, (Cdouble, Cdouble), y, x) end function SDL_atan2f(y, x) ccall((:SDL_atan2f, libsdl2), Cfloat, (Cfloat, Cfloat), y, x) end function SDL_ceil(x) ccall((:SDL_ceil, libsdl2), Cdouble, (Cdouble,), x) end function SDL_ceilf(x) ccall((:SDL_ceilf, libsdl2), Cfloat, (Cfloat,), x) end function SDL_copysign(x, y) ccall((:SDL_copysign, libsdl2), Cdouble, (Cdouble, Cdouble), x, y) end function SDL_copysignf(x, y) ccall((:SDL_copysignf, libsdl2), Cfloat, (Cfloat, Cfloat), x, y) end function SDL_cos(x) ccall((:SDL_cos, libsdl2), Cdouble, (Cdouble,), x) end function SDL_cosf(x) ccall((:SDL_cosf, libsdl2), Cfloat, (Cfloat,), x) end function SDL_exp(x) ccall((:SDL_exp, libsdl2), Cdouble, (Cdouble,), x) end function SDL_expf(x) ccall((:SDL_expf, libsdl2), Cfloat, (Cfloat,), x) end function SDL_fabs(x) ccall((:SDL_fabs, libsdl2), Cdouble, (Cdouble,), x) end function SDL_fabsf(x) ccall((:SDL_fabsf, libsdl2), Cfloat, (Cfloat,), x) end function SDL_floor(x) ccall((:SDL_floor, libsdl2), Cdouble, (Cdouble,), x) end function SDL_floorf(x) ccall((:SDL_floorf, libsdl2), Cfloat, (Cfloat,), x) end function SDL_trunc(x) ccall((:SDL_trunc, libsdl2), Cdouble, (Cdouble,), x) end function SDL_truncf(x) ccall((:SDL_truncf, libsdl2), Cfloat, (Cfloat,), x) end function SDL_fmod(x, y) ccall((:SDL_fmod, libsdl2), Cdouble, (Cdouble, Cdouble), x, y) end function SDL_fmodf(x, y) ccall((:SDL_fmodf, libsdl2), Cfloat, (Cfloat, Cfloat), x, y) end function SDL_log(x) ccall((:SDL_log, libsdl2), Cdouble, (Cdouble,), x) end function SDL_logf(x) ccall((:SDL_logf, libsdl2), Cfloat, (Cfloat,), x) end function SDL_log10(x) ccall((:SDL_log10, libsdl2), Cdouble, (Cdouble,), x) end function SDL_log10f(x) ccall((:SDL_log10f, libsdl2), Cfloat, (Cfloat,), x) end function SDL_pow(x, y) ccall((:SDL_pow, libsdl2), Cdouble, (Cdouble, Cdouble), x, y) end function SDL_powf(x, y) ccall((:SDL_powf, libsdl2), Cfloat, (Cfloat, Cfloat), x, y) end function SDL_round(x) ccall((:SDL_round, libsdl2), Cdouble, (Cdouble,), x) end function SDL_roundf(x) ccall((:SDL_roundf, libsdl2), Cfloat, (Cfloat,), x) end function SDL_lround(x) ccall((:SDL_lround, libsdl2), Clong, (Cdouble,), x) end function SDL_lroundf(x) ccall((:SDL_lroundf, libsdl2), Clong, (Cfloat,), x) end function SDL_scalbn(x, n) ccall((:SDL_scalbn, libsdl2), Cdouble, (Cdouble, Cint), x, n) end function SDL_scalbnf(x, n) ccall((:SDL_scalbnf, libsdl2), Cfloat, (Cfloat, Cint), x, n) end function SDL_sin(x) ccall((:SDL_sin, libsdl2), Cdouble, (Cdouble,), x) end function SDL_sinf(x) ccall((:SDL_sinf, libsdl2), Cfloat, (Cfloat,), x) end function SDL_sqrt(x) ccall((:SDL_sqrt, libsdl2), Cdouble, (Cdouble,), x) end function SDL_sqrtf(x) ccall((:SDL_sqrtf, libsdl2), Cfloat, (Cfloat,), x) end function SDL_tan(x) ccall((:SDL_tan, libsdl2), Cdouble, (Cdouble,), x) end function SDL_tanf(x) ccall((:SDL_tanf, libsdl2), Cfloat, (Cfloat,), x) end mutable struct _SDL_iconv_t end const SDL_iconv_t = Ptr{_SDL_iconv_t} function SDL_iconv_open(tocode, fromcode) ccall((:SDL_iconv_open, libsdl2), SDL_iconv_t, (Ptr{Cchar}, Ptr{Cchar}), tocode, fromcode) end function SDL_iconv_close(cd) ccall((:SDL_iconv_close, libsdl2), Cint, (SDL_iconv_t,), cd) end function SDL_iconv(cd, inbuf, inbytesleft, outbuf, outbytesleft) ccall((:SDL_iconv, libsdl2), Csize_t, (SDL_iconv_t, Ptr{Ptr{Cchar}}, Ptr{Csize_t}, Ptr{Ptr{Cchar}}, Ptr{Csize_t}), cd, inbuf, inbytesleft, outbuf, outbytesleft) end function SDL_memcpy4(dst, src, dwords) ccall((:SDL_memcpy4, libsdl2), Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), dst, src, dwords) end # typedef int ( * SDL_main_func ) ( int argc , char * argv [ ] ) const SDL_main_func = Ptr{Cvoid} function SDL_main(argc, argv) ccall((:SDL_main, libsdl2), Cint, (Cint, Ptr{Ptr{Cchar}}), argc, argv) end function SDL_SetMainReady() ccall((:SDL_SetMainReady, libsdl2), Cvoid, ()) end # typedef SDL_AssertState ( SDLCALL * SDL_AssertionHandler ) ( const SDL_AssertData * data , void * userdata ) const SDL_AssertionHandler = Ptr{Cvoid} function SDL_SetAssertionHandler(handler, userdata) ccall((:SDL_SetAssertionHandler, libsdl2), Cvoid, (SDL_AssertionHandler, Ptr{Cvoid}), handler, userdata) end function SDL_GetDefaultAssertionHandler() ccall((:SDL_GetDefaultAssertionHandler, libsdl2), SDL_AssertionHandler, ()) end function SDL_GetAssertionHandler(puserdata) ccall((:SDL_GetAssertionHandler, libsdl2), SDL_AssertionHandler, (Ptr{Ptr{Cvoid}},), puserdata) end function SDL_GetAssertionReport() ccall((:SDL_GetAssertionReport, libsdl2), Ptr{SDL_AssertData}, ()) end function SDL_ResetAssertionReport() ccall((:SDL_ResetAssertionReport, libsdl2), Cvoid, ()) end const SDL_SpinLock = Cint function SDL_AtomicTryLock(lock) ccall((:SDL_AtomicTryLock, libsdl2), SDL_bool, (Ptr{SDL_SpinLock},), lock) end function SDL_AtomicLock(lock) ccall((:SDL_AtomicLock, libsdl2), Cvoid, (Ptr{SDL_SpinLock},), lock) end function SDL_AtomicUnlock(lock) ccall((:SDL_AtomicUnlock, libsdl2), Cvoid, (Ptr{SDL_SpinLock},), lock) end function SDL_MemoryBarrierReleaseFunction() ccall((:SDL_MemoryBarrierReleaseFunction, libsdl2), Cvoid, ()) end function SDL_MemoryBarrierAcquireFunction() ccall((:SDL_MemoryBarrierAcquireFunction, libsdl2), Cvoid, ()) end function SDL_AtomicCAS(a, oldval, newval) ccall((:SDL_AtomicCAS, libsdl2), SDL_bool, (Ptr{SDL_atomic_t}, Cint, Cint), a, oldval, newval) end function SDL_AtomicSet(a, v) ccall((:SDL_AtomicSet, libsdl2), Cint, (Ptr{SDL_atomic_t}, Cint), a, v) end function SDL_AtomicGet(a) ccall((:SDL_AtomicGet, libsdl2), Cint, (Ptr{SDL_atomic_t},), a) end function SDL_AtomicCASPtr(a, oldval, newval) ccall((:SDL_AtomicCASPtr, libsdl2), SDL_bool, (Ptr{Ptr{Cvoid}}, Ptr{Cvoid}, Ptr{Cvoid}), a, oldval, newval) end function SDL_AtomicSetPtr(a, v) ccall((:SDL_AtomicSetPtr, libsdl2), Ptr{Cvoid}, (Ptr{Ptr{Cvoid}}, Ptr{Cvoid}), a, v) end function SDL_AtomicGetPtr(a) ccall((:SDL_AtomicGetPtr, libsdl2), Ptr{Cvoid}, (Ptr{Ptr{Cvoid}},), a) end function SDL_GetError() ccall((:SDL_GetError, libsdl2), Ptr{Cchar}, ()) end function SDL_GetErrorMsg(errstr, maxlen) ccall((:SDL_GetErrorMsg, libsdl2), Ptr{Cchar}, (Ptr{Cchar}, Cint), errstr, maxlen) end function SDL_ClearError() ccall((:SDL_ClearError, libsdl2), Cvoid, ()) end function SDL_CreateMutex() ccall((:SDL_CreateMutex, libsdl2), Ptr{SDL_mutex}, ()) end function SDL_TryLockMutex(mutex) ccall((:SDL_TryLockMutex, libsdl2), Cint, (Ptr{SDL_mutex},), mutex) end function SDL_DestroyMutex(mutex) ccall((:SDL_DestroyMutex, libsdl2), Cvoid, (Ptr{SDL_mutex},), mutex) end mutable struct SDL_semaphore end const SDL_sem = SDL_semaphore function SDL_CreateSemaphore(initial_value) ccall((:SDL_CreateSemaphore, libsdl2), Ptr{SDL_sem}, (Uint32,), initial_value) end function SDL_DestroySemaphore(sem) ccall((:SDL_DestroySemaphore, libsdl2), Cvoid, (Ptr{SDL_sem},), sem) end function SDL_SemWait(sem) ccall((:SDL_SemWait, libsdl2), Cint, (Ptr{SDL_sem},), sem) end function SDL_SemTryWait(sem) ccall((:SDL_SemTryWait, libsdl2), Cint, (Ptr{SDL_sem},), sem) end function SDL_SemWaitTimeout(sem, ms) ccall((:SDL_SemWaitTimeout, libsdl2), Cint, (Ptr{SDL_sem}, Uint32), sem, ms) end function SDL_SemPost(sem) ccall((:SDL_SemPost, libsdl2), Cint, (Ptr{SDL_sem},), sem) end function SDL_SemValue(sem) ccall((:SDL_SemValue, libsdl2), Uint32, (Ptr{SDL_sem},), sem) end mutable struct SDL_cond end function SDL_CreateCond() ccall((:SDL_CreateCond, libsdl2), Ptr{SDL_cond}, ()) end function SDL_DestroyCond(cond) ccall((:SDL_DestroyCond, libsdl2), Cvoid, (Ptr{SDL_cond},), cond) end function SDL_CondSignal(cond) ccall((:SDL_CondSignal, libsdl2), Cint, (Ptr{SDL_cond},), cond) end function SDL_CondBroadcast(cond) ccall((:SDL_CondBroadcast, libsdl2), Cint, (Ptr{SDL_cond},), cond) end function SDL_CondWait(cond, mutex) ccall((:SDL_CondWait, libsdl2), Cint, (Ptr{SDL_cond}, Ptr{SDL_mutex}), cond, mutex) end function SDL_CondWaitTimeout(cond, mutex, ms) ccall((:SDL_CondWaitTimeout, libsdl2), Cint, (Ptr{SDL_cond}, Ptr{SDL_mutex}, Uint32), cond, mutex, ms) end mutable struct SDL_Thread end const SDL_threadID = Culong const SDL_TLSID = Cuint @cenum SDL_ThreadPriority::UInt32 begin SDL_THREAD_PRIORITY_LOW = 0 SDL_THREAD_PRIORITY_NORMAL = 1 SDL_THREAD_PRIORITY_HIGH = 2 SDL_THREAD_PRIORITY_TIME_CRITICAL = 3 end # typedef int ( SDLCALL * SDL_ThreadFunction ) ( void * data ) const SDL_ThreadFunction = Ptr{Cvoid} function SDL_CreateThread(fn, name, data) ccall((:SDL_CreateThread, libsdl2), Ptr{SDL_Thread}, (SDL_ThreadFunction, Ptr{Cchar}, Ptr{Cvoid}), fn, name, data) end function SDL_CreateThreadWithStackSize(fn, name, stacksize, data) ccall((:SDL_CreateThreadWithStackSize, libsdl2), Ptr{SDL_Thread}, (SDL_ThreadFunction, Ptr{Cchar}, Csize_t, Ptr{Cvoid}), fn, name, stacksize, data) end function SDL_GetThreadName(thread) ccall((:SDL_GetThreadName, libsdl2), Ptr{Cchar}, (Ptr{SDL_Thread},), thread) end function SDL_ThreadID() ccall((:SDL_ThreadID, libsdl2), SDL_threadID, ()) end function SDL_GetThreadID(thread) ccall((:SDL_GetThreadID, libsdl2), SDL_threadID, (Ptr{SDL_Thread},), thread) end function SDL_SetThreadPriority(priority) ccall((:SDL_SetThreadPriority, libsdl2), Cint, (SDL_ThreadPriority,), priority) end function SDL_WaitThread(thread, status) ccall((:SDL_WaitThread, libsdl2), Cvoid, (Ptr{SDL_Thread}, Ptr{Cint}), thread, status) end function SDL_DetachThread(thread) ccall((:SDL_DetachThread, libsdl2), Cvoid, (Ptr{SDL_Thread},), thread) end function SDL_TLSCreate() ccall((:SDL_TLSCreate, libsdl2), SDL_TLSID, ()) end function SDL_TLSGet(id) ccall((:SDL_TLSGet, libsdl2), Ptr{Cvoid}, (SDL_TLSID,), id) end function SDL_TLSSet(id, value, destructor) ccall((:SDL_TLSSet, libsdl2), Cint, (SDL_TLSID, Ptr{Cvoid}, Ptr{Cvoid}), id, value, destructor) end function SDL_TLSCleanup() ccall((:SDL_TLSCleanup, libsdl2), Cvoid, ()) end function SDL_RWFromFP(fp, autoclose) ccall((:SDL_RWFromFP, libsdl2), Ptr{SDL_RWops}, (Ptr{Libc.FILE}, SDL_bool), fp, autoclose) end function SDL_RWFromMem(mem, size) ccall((:SDL_RWFromMem, libsdl2), Ptr{SDL_RWops}, (Ptr{Cvoid}, Cint), mem, size) end function SDL_RWFromConstMem(mem, size) ccall((:SDL_RWFromConstMem, libsdl2), Ptr{SDL_RWops}, (Ptr{Cvoid}, Cint), mem, size) end function SDL_AllocRW() ccall((:SDL_AllocRW, libsdl2), Ptr{SDL_RWops}, ()) end function SDL_FreeRW(area) ccall((:SDL_FreeRW, libsdl2), Cvoid, (Ptr{SDL_RWops},), area) end function SDL_RWsize(context) ccall((:SDL_RWsize, libsdl2), Sint64, (Ptr{SDL_RWops},), context) end function SDL_RWseek(context, offset, whence) ccall((:SDL_RWseek, libsdl2), Sint64, (Ptr{SDL_RWops}, Sint64, Cint), context, offset, whence) end function SDL_RWtell(context) ccall((:SDL_RWtell, libsdl2), Sint64, (Ptr{SDL_RWops},), context) end function SDL_RWread(context, ptr, size, maxnum) ccall((:SDL_RWread, libsdl2), Csize_t, (Ptr{SDL_RWops}, Ptr{Cvoid}, Csize_t, Csize_t), context, ptr, size, maxnum) end function SDL_RWwrite(context, ptr, size, num) ccall((:SDL_RWwrite, libsdl2), Csize_t, (Ptr{SDL_RWops}, Ptr{Cvoid}, Csize_t, Csize_t), context, ptr, size, num) end function SDL_RWclose(context) ccall((:SDL_RWclose, libsdl2), Cint, (Ptr{SDL_RWops},), context) end function SDL_LoadFile_RW(src, datasize, freesrc) ccall((:SDL_LoadFile_RW, libsdl2), Ptr{Cvoid}, (Ptr{SDL_RWops}, Ptr{Csize_t}, Cint), src, datasize, freesrc) end function SDL_LoadFile(file, datasize) ccall((:SDL_LoadFile, libsdl2), Ptr{Cvoid}, (Ptr{Cchar}, Ptr{Csize_t}), file, datasize) end function SDL_ReadU8(src) ccall((:SDL_ReadU8, libsdl2), Uint8, (Ptr{SDL_RWops},), src) end function SDL_ReadLE16(src) ccall((:SDL_ReadLE16, libsdl2), Uint16, (Ptr{SDL_RWops},), src) end function SDL_ReadBE16(src) ccall((:SDL_ReadBE16, libsdl2), Uint16, (Ptr{SDL_RWops},), src) end function SDL_ReadLE32(src) ccall((:SDL_ReadLE32, libsdl2), Uint32, (Ptr{SDL_RWops},), src) end function SDL_ReadBE32(src) ccall((:SDL_ReadBE32, libsdl2), Uint32, (Ptr{SDL_RWops},), src) end function SDL_ReadLE64(src) ccall((:SDL_ReadLE64, libsdl2), Uint64, (Ptr{SDL_RWops},), src) end function SDL_ReadBE64(src) ccall((:SDL_ReadBE64, libsdl2), Uint64, (Ptr{SDL_RWops},), src) end function SDL_WriteU8(dst, value) ccall((:SDL_WriteU8, libsdl2), Csize_t, (Ptr{SDL_RWops}, Uint8), dst, value) end function SDL_WriteLE16(dst, value) ccall((:SDL_WriteLE16, libsdl2), Csize_t, (Ptr{SDL_RWops}, Uint16), dst, value) end function SDL_WriteBE16(dst, value) ccall((:SDL_WriteBE16, libsdl2), Csize_t, (Ptr{SDL_RWops}, Uint16), dst, value) end function SDL_WriteLE32(dst, value) ccall((:SDL_WriteLE32, libsdl2), Csize_t, (Ptr{SDL_RWops}, Uint32), dst, value) end function SDL_WriteBE32(dst, value) ccall((:SDL_WriteBE32, libsdl2), Csize_t, (Ptr{SDL_RWops}, Uint32), dst, value) end function SDL_WriteLE64(dst, value) ccall((:SDL_WriteLE64, libsdl2), Csize_t, (Ptr{SDL_RWops}, Uint64), dst, value) end function SDL_WriteBE64(dst, value) ccall((:SDL_WriteBE64, libsdl2), Csize_t, (Ptr{SDL_RWops}, Uint64), dst, value) end # typedef void ( SDLCALL * SDL_AudioFilter ) ( struct SDL_AudioCVT * cvt , SDL_AudioFormat format ) const SDL_AudioFilter = Ptr{Cvoid} struct SDL_AudioCVT data::NTuple{128, UInt8} end function Base.getproperty(x::Ptr{SDL_AudioCVT}, f::Symbol) f === :needed && return Ptr{Cint}(x + 0) f === :src_format && return Ptr{SDL_AudioFormat}(x + 4) f === :dst_format && return Ptr{SDL_AudioFormat}(x + 6) f === :rate_incr && return Ptr{Cdouble}(x + 8) f === :buf && return Ptr{Ptr{Uint8}}(x + 16) f === :len && return Ptr{Cint}(x + 24) f === :len_cvt && return Ptr{Cint}(x + 28) f === :len_mult && return Ptr{Cint}(x + 32) f === :len_ratio && return Ptr{Cdouble}(x + 36) f === :filters && return Ptr{NTuple{10, SDL_AudioFilter}}(x + 44) f === :filter_index && return Ptr{Cint}(x + 124) return getfield(x, f) end function Base.getproperty(x::SDL_AudioCVT, f::Symbol) r = Ref{SDL_AudioCVT}(x) ptr = Base.unsafe_convert(Ptr{SDL_AudioCVT}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{SDL_AudioCVT}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end function SDL_GetNumAudioDrivers() ccall((:SDL_GetNumAudioDrivers, libsdl2), Cint, ()) end function SDL_GetAudioDriver(index) ccall((:SDL_GetAudioDriver, libsdl2), Ptr{Cchar}, (Cint,), index) end function SDL_AudioInit(driver_name) ccall((:SDL_AudioInit, libsdl2), Cint, (Ptr{Cchar},), driver_name) end function SDL_AudioQuit() ccall((:SDL_AudioQuit, libsdl2), Cvoid, ()) end function SDL_GetCurrentAudioDriver() ccall((:SDL_GetCurrentAudioDriver, libsdl2), Ptr{Cchar}, ()) end function SDL_OpenAudio(desired, obtained) ccall((:SDL_OpenAudio, libsdl2), Cint, (Ptr{SDL_AudioSpec}, Ptr{SDL_AudioSpec}), desired, obtained) end const SDL_AudioDeviceID = Uint32 function SDL_GetNumAudioDevices(iscapture) ccall((:SDL_GetNumAudioDevices, libsdl2), Cint, (Cint,), iscapture) end function SDL_GetAudioDeviceName(index, iscapture) ccall((:SDL_GetAudioDeviceName, libsdl2), Ptr{Cchar}, (Cint, Cint), index, iscapture) end function SDL_GetAudioDeviceSpec(index, iscapture, spec) ccall((:SDL_GetAudioDeviceSpec, libsdl2), Cint, (Cint, Cint, Ptr{SDL_AudioSpec}), index, iscapture, spec) end function SDL_GetDefaultAudioInfo(name, spec, iscapture) ccall((:SDL_GetDefaultAudioInfo, libsdl2), Cint, (Ptr{Ptr{Cchar}}, Ptr{SDL_AudioSpec}, Cint), name, spec, iscapture) end function SDL_OpenAudioDevice(device, iscapture, desired, obtained, allowed_changes) ccall((:SDL_OpenAudioDevice, libsdl2), SDL_AudioDeviceID, (Ptr{Cchar}, Cint, Ptr{SDL_AudioSpec}, Ptr{SDL_AudioSpec}, Cint), device, iscapture, desired, obtained, allowed_changes) end @cenum SDL_AudioStatus::UInt32 begin SDL_AUDIO_STOPPED = 0 SDL_AUDIO_PLAYING = 1 SDL_AUDIO_PAUSED = 2 end function SDL_GetAudioStatus() ccall((:SDL_GetAudioStatus, libsdl2), SDL_AudioStatus, ()) end function SDL_GetAudioDeviceStatus(dev) ccall((:SDL_GetAudioDeviceStatus, libsdl2), SDL_AudioStatus, (SDL_AudioDeviceID,), dev) end function SDL_PauseAudio(pause_on) ccall((:SDL_PauseAudio, libsdl2), Cvoid, (Cint,), pause_on) end function SDL_PauseAudioDevice(dev, pause_on) ccall((:SDL_PauseAudioDevice, libsdl2), Cvoid, (SDL_AudioDeviceID, Cint), dev, pause_on) end function SDL_FreeWAV(audio_buf) ccall((:SDL_FreeWAV, libsdl2), Cvoid, (Ptr{Uint8},), audio_buf) end function SDL_BuildAudioCVT(cvt, src_format, src_channels, src_rate, dst_format, dst_channels, dst_rate) ccall((:SDL_BuildAudioCVT, libsdl2), Cint, (Ptr{SDL_AudioCVT}, SDL_AudioFormat, Uint8, Cint, SDL_AudioFormat, Uint8, Cint), cvt, src_format, src_channels, src_rate, dst_format, dst_channels, dst_rate) end function SDL_ConvertAudio(cvt) ccall((:SDL_ConvertAudio, libsdl2), Cint, (Ptr{SDL_AudioCVT},), cvt) end mutable struct _SDL_AudioStream end const SDL_AudioStream = _SDL_AudioStream function SDL_NewAudioStream(src_format, src_channels, src_rate, dst_format, dst_channels, dst_rate) ccall((:SDL_NewAudioStream, libsdl2), Ptr{SDL_AudioStream}, (SDL_AudioFormat, Uint8, Cint, SDL_AudioFormat, Uint8, Cint), src_format, src_channels, src_rate, dst_format, dst_channels, dst_rate) end function SDL_AudioStreamPut(stream, buf, len) ccall((:SDL_AudioStreamPut, libsdl2), Cint, (Ptr{SDL_AudioStream}, Ptr{Cvoid}, Cint), stream, buf, len) end function SDL_AudioStreamGet(stream, buf, len) ccall((:SDL_AudioStreamGet, libsdl2), Cint, (Ptr{SDL_AudioStream}, Ptr{Cvoid}, Cint), stream, buf, len) end function SDL_AudioStreamAvailable(stream) ccall((:SDL_AudioStreamAvailable, libsdl2), Cint, (Ptr{SDL_AudioStream},), stream) end function SDL_AudioStreamFlush(stream) ccall((:SDL_AudioStreamFlush, libsdl2), Cint, (Ptr{SDL_AudioStream},), stream) end function SDL_AudioStreamClear(stream) ccall((:SDL_AudioStreamClear, libsdl2), Cvoid, (Ptr{SDL_AudioStream},), stream) end function SDL_FreeAudioStream(stream) ccall((:SDL_FreeAudioStream, libsdl2), Cvoid, (Ptr{SDL_AudioStream},), stream) end function SDL_MixAudio(dst, src, len, volume) ccall((:SDL_MixAudio, libsdl2), Cvoid, (Ptr{Uint8}, Ptr{Uint8}, Uint32, Cint), dst, src, len, volume) end function SDL_MixAudioFormat(dst, src, format, len, volume) ccall((:SDL_MixAudioFormat, libsdl2), Cvoid, (Ptr{Uint8}, Ptr{Uint8}, SDL_AudioFormat, Uint32, Cint), dst, src, format, len, volume) end function SDL_QueueAudio(dev, data, len) ccall((:SDL_QueueAudio, libsdl2), Cint, (SDL_AudioDeviceID, Ptr{Cvoid}, Uint32), dev, data, len) end function SDL_DequeueAudio(dev, data, len) ccall((:SDL_DequeueAudio, libsdl2), Uint32, (SDL_AudioDeviceID, Ptr{Cvoid}, Uint32), dev, data, len) end function SDL_GetQueuedAudioSize(dev) ccall((:SDL_GetQueuedAudioSize, libsdl2), Uint32, (SDL_AudioDeviceID,), dev) end function SDL_ClearQueuedAudio(dev) ccall((:SDL_ClearQueuedAudio, libsdl2), Cvoid, (SDL_AudioDeviceID,), dev) end function SDL_LockAudio() ccall((:SDL_LockAudio, libsdl2), Cvoid, ()) end function SDL_LockAudioDevice(dev) ccall((:SDL_LockAudioDevice, libsdl2), Cvoid, (SDL_AudioDeviceID,), dev) end function SDL_UnlockAudio() ccall((:SDL_UnlockAudio, libsdl2), Cvoid, ()) end function SDL_UnlockAudioDevice(dev) ccall((:SDL_UnlockAudioDevice, libsdl2), Cvoid, (SDL_AudioDeviceID,), dev) end function SDL_CloseAudio() ccall((:SDL_CloseAudio, libsdl2), Cvoid, ()) end function SDL_CloseAudioDevice(dev) ccall((:SDL_CloseAudioDevice, libsdl2), Cvoid, (SDL_AudioDeviceID,), dev) end function SDL_SetClipboardText(text) ccall((:SDL_SetClipboardText, libsdl2), Cint, (Ptr{Cchar},), text) end function SDL_GetClipboardText() ccall((:SDL_GetClipboardText, libsdl2), Ptr{Cchar}, ()) end function SDL_HasClipboardText() ccall((:SDL_HasClipboardText, libsdl2), SDL_bool, ()) end function SDL_GetCPUCount() ccall((:SDL_GetCPUCount, libsdl2), Cint, ()) end function SDL_GetCPUCacheLineSize() ccall((:SDL_GetCPUCacheLineSize, libsdl2), Cint, ()) end function SDL_HasRDTSC() ccall((:SDL_HasRDTSC, libsdl2), SDL_bool, ()) end function SDL_HasAltiVec() ccall((:SDL_HasAltiVec, libsdl2), SDL_bool, ()) end function SDL_HasMMX() ccall((:SDL_HasMMX, libsdl2), SDL_bool, ()) end function SDL_Has3DNow() ccall((:SDL_Has3DNow, libsdl2), SDL_bool, ()) end function SDL_HasSSE() ccall((:SDL_HasSSE, libsdl2), SDL_bool, ()) end function SDL_HasSSE2() ccall((:SDL_HasSSE2, libsdl2), SDL_bool, ()) end function SDL_HasSSE3() ccall((:SDL_HasSSE3, libsdl2), SDL_bool, ()) end function SDL_HasSSE41() ccall((:SDL_HasSSE41, libsdl2), SDL_bool, ()) end function SDL_HasSSE42() ccall((:SDL_HasSSE42, libsdl2), SDL_bool, ()) end function SDL_HasAVX() ccall((:SDL_HasAVX, libsdl2), SDL_bool, ()) end function SDL_HasAVX2() ccall((:SDL_HasAVX2, libsdl2), SDL_bool, ()) end function SDL_HasAVX512F() ccall((:SDL_HasAVX512F, libsdl2), SDL_bool, ()) end function SDL_HasARMSIMD() ccall((:SDL_HasARMSIMD, libsdl2), SDL_bool, ()) end function SDL_HasNEON() ccall((:SDL_HasNEON, libsdl2), SDL_bool, ()) end function SDL_HasLSX() ccall((:SDL_HasLSX, libsdl2), SDL_bool, ()) end function SDL_HasLASX() ccall((:SDL_HasLASX, libsdl2), SDL_bool, ()) end function SDL_GetSystemRAM() ccall((:SDL_GetSystemRAM, libsdl2), Cint, ()) end function SDL_SIMDGetAlignment() ccall((:SDL_SIMDGetAlignment, libsdl2), Csize_t, ()) end function SDL_SIMDAlloc(len) ccall((:SDL_SIMDAlloc, libsdl2), Ptr{Cvoid}, (Csize_t,), len) end function SDL_SIMDRealloc(mem, len) ccall((:SDL_SIMDRealloc, libsdl2), Ptr{Cvoid}, (Ptr{Cvoid}, Csize_t), mem, len) end function SDL_SIMDFree(ptr) ccall((:SDL_SIMDFree, libsdl2), Cvoid, (Ptr{Cvoid},), ptr) end @cenum SDL_PixelType::UInt32 begin SDL_PIXELTYPE_UNKNOWN = 0 SDL_PIXELTYPE_INDEX1 = 1 SDL_PIXELTYPE_INDEX4 = 2 SDL_PIXELTYPE_INDEX8 = 3 SDL_PIXELTYPE_PACKED8 = 4 SDL_PIXELTYPE_PACKED16 = 5 SDL_PIXELTYPE_PACKED32 = 6 SDL_PIXELTYPE_ARRAYU8 = 7 SDL_PIXELTYPE_ARRAYU16 = 8 SDL_PIXELTYPE_ARRAYU32 = 9 SDL_PIXELTYPE_ARRAYF16 = 10 SDL_PIXELTYPE_ARRAYF32 = 11 end @cenum SDL_BitmapOrder::UInt32 begin SDL_BITMAPORDER_NONE = 0 SDL_BITMAPORDER_4321 = 1 SDL_BITMAPORDER_1234 = 2 end @cenum SDL_PackedOrder::UInt32 begin SDL_PACKEDORDER_NONE = 0 SDL_PACKEDORDER_XRGB = 1 SDL_PACKEDORDER_RGBX = 2 SDL_PACKEDORDER_ARGB = 3 SDL_PACKEDORDER_RGBA = 4 SDL_PACKEDORDER_XBGR = 5 SDL_PACKEDORDER_BGRX = 6 SDL_PACKEDORDER_ABGR = 7 SDL_PACKEDORDER_BGRA = 8 end @cenum SDL_ArrayOrder::UInt32 begin SDL_ARRAYORDER_NONE = 0 SDL_ARRAYORDER_RGB = 1 SDL_ARRAYORDER_RGBA = 2 SDL_ARRAYORDER_ARGB = 3 SDL_ARRAYORDER_BGR = 4 SDL_ARRAYORDER_BGRA = 5 SDL_ARRAYORDER_ABGR = 6 end @cenum SDL_PackedLayout::UInt32 begin SDL_PACKEDLAYOUT_NONE = 0 SDL_PACKEDLAYOUT_332 = 1 SDL_PACKEDLAYOUT_4444 = 2 SDL_PACKEDLAYOUT_1555 = 3 SDL_PACKEDLAYOUT_5551 = 4 SDL_PACKEDLAYOUT_565 = 5 SDL_PACKEDLAYOUT_8888 = 6 SDL_PACKEDLAYOUT_2101010 = 7 SDL_PACKEDLAYOUT_1010102 = 8 end @cenum SDL_PixelFormatEnum::UInt32 begin SDL_PIXELFORMAT_UNKNOWN = 0 SDL_PIXELFORMAT_INDEX1LSB = 286261504 SDL_PIXELFORMAT_INDEX1MSB = 287310080 SDL_PIXELFORMAT_INDEX4LSB = 303039488 SDL_PIXELFORMAT_INDEX4MSB = 304088064 SDL_PIXELFORMAT_INDEX8 = 318769153 SDL_PIXELFORMAT_RGB332 = 336660481 SDL_PIXELFORMAT_XRGB4444 = 353504258 SDL_PIXELFORMAT_RGB444 = 353504258 SDL_PIXELFORMAT_XBGR4444 = 357698562 SDL_PIXELFORMAT_BGR444 = 357698562 SDL_PIXELFORMAT_XRGB1555 = 353570562 SDL_PIXELFORMAT_RGB555 = 353570562 SDL_PIXELFORMAT_XBGR1555 = 357764866 SDL_PIXELFORMAT_BGR555 = 357764866 SDL_PIXELFORMAT_ARGB4444 = 355602434 SDL_PIXELFORMAT_RGBA4444 = 356651010 SDL_PIXELFORMAT_ABGR4444 = 359796738 SDL_PIXELFORMAT_BGRA4444 = 360845314 SDL_PIXELFORMAT_ARGB1555 = 355667970 SDL_PIXELFORMAT_RGBA5551 = 356782082 SDL_PIXELFORMAT_ABGR1555 = 359862274 SDL_PIXELFORMAT_BGRA5551 = 360976386 SDL_PIXELFORMAT_RGB565 = 353701890 SDL_PIXELFORMAT_BGR565 = 357896194 SDL_PIXELFORMAT_RGB24 = 386930691 SDL_PIXELFORMAT_BGR24 = 390076419 SDL_PIXELFORMAT_XRGB8888 = 370546692 SDL_PIXELFORMAT_RGB888 = 370546692 SDL_PIXELFORMAT_RGBX8888 = 371595268 SDL_PIXELFORMAT_XBGR8888 = 374740996 SDL_PIXELFORMAT_BGR888 = 374740996 SDL_PIXELFORMAT_BGRX8888 = 375789572 SDL_PIXELFORMAT_ARGB8888 = 372645892 SDL_PIXELFORMAT_RGBA8888 = 373694468 SDL_PIXELFORMAT_ABGR8888 = 376840196 SDL_PIXELFORMAT_BGRA8888 = 377888772 SDL_PIXELFORMAT_ARGB2101010 = 372711428 SDL_PIXELFORMAT_RGBA32 = 376840196 SDL_PIXELFORMAT_ARGB32 = 377888772 SDL_PIXELFORMAT_BGRA32 = 372645892 SDL_PIXELFORMAT_ABGR32 = 373694468 SDL_PIXELFORMAT_YV12 = 842094169 SDL_PIXELFORMAT_IYUV = 1448433993 SDL_PIXELFORMAT_YUY2 = 844715353 SDL_PIXELFORMAT_UYVY = 1498831189 SDL_PIXELFORMAT_YVYU = 1431918169 SDL_PIXELFORMAT_NV12 = 842094158 SDL_PIXELFORMAT_NV21 = 825382478 SDL_PIXELFORMAT_EXTERNAL_OES = 542328143 end function SDL_GetPixelFormatName(format) ccall((:SDL_GetPixelFormatName, libsdl2), Ptr{Cchar}, (Uint32,), format) end function SDL_PixelFormatEnumToMasks(format, bpp, Rmask, Gmask, Bmask, Amask) ccall((:SDL_PixelFormatEnumToMasks, libsdl2), SDL_bool, (Uint32, Ptr{Cint}, Ptr{Uint32}, Ptr{Uint32}, Ptr{Uint32}, Ptr{Uint32}), format, bpp, Rmask, Gmask, Bmask, Amask) end function SDL_MasksToPixelFormatEnum(bpp, Rmask, Gmask, Bmask, Amask) ccall((:SDL_MasksToPixelFormatEnum, libsdl2), Uint32, (Cint, Uint32, Uint32, Uint32, Uint32), bpp, Rmask, Gmask, Bmask, Amask) end function SDL_AllocFormat(pixel_format) ccall((:SDL_AllocFormat, libsdl2), Ptr{SDL_PixelFormat}, (Uint32,), pixel_format) end function SDL_FreeFormat(format) ccall((:SDL_FreeFormat, libsdl2), Cvoid, (Ptr{SDL_PixelFormat},), format) end function SDL_AllocPalette(ncolors) ccall((:SDL_AllocPalette, libsdl2), Ptr{SDL_Palette}, (Cint,), ncolors) end function SDL_SetPixelFormatPalette(format, palette) ccall((:SDL_SetPixelFormatPalette, libsdl2), Cint, (Ptr{SDL_PixelFormat}, Ptr{SDL_Palette}), format, palette) end function SDL_SetPaletteColors(palette, colors, firstcolor, ncolors) ccall((:SDL_SetPaletteColors, libsdl2), Cint, (Ptr{SDL_Palette}, Ptr{SDL_Color}, Cint, Cint), palette, colors, firstcolor, ncolors) end function SDL_FreePalette(palette) ccall((:SDL_FreePalette, libsdl2), Cvoid, (Ptr{SDL_Palette},), palette) end function SDL_MapRGB(format, r, g, b) ccall((:SDL_MapRGB, libsdl2), Uint32, (Ptr{SDL_PixelFormat}, Uint8, Uint8, Uint8), format, r, g, b) end function SDL_MapRGBA(format, r, g, b, a) ccall((:SDL_MapRGBA, libsdl2), Uint32, (Ptr{SDL_PixelFormat}, Uint8, Uint8, Uint8, Uint8), format, r, g, b, a) end function SDL_GetRGB(pixel, format, r, g, b) ccall((:SDL_GetRGB, libsdl2), Cvoid, (Uint32, Ptr{SDL_PixelFormat}, Ptr{Uint8}, Ptr{Uint8}, Ptr{Uint8}), pixel, format, r, g, b) end function SDL_GetRGBA(pixel, format, r, g, b, a) ccall((:SDL_GetRGBA, libsdl2), Cvoid, (Uint32, Ptr{SDL_PixelFormat}, Ptr{Uint8}, Ptr{Uint8}, Ptr{Uint8}, Ptr{Uint8}), pixel, format, r, g, b, a) end function SDL_CalculateGammaRamp(gamma, ramp) ccall((:SDL_CalculateGammaRamp, libsdl2), Cvoid, (Cfloat, Ptr{Uint16}), gamma, ramp) end struct SDL_Point x::Cint y::Cint end struct SDL_FPoint x::Cfloat y::Cfloat end struct SDL_FRect x::Cfloat y::Cfloat w::Cfloat h::Cfloat end function SDL_PointInRect(p, r) ccall((:SDL_PointInRect, libsdl2), SDL_bool, (Ptr{SDL_Point}, Ptr{SDL_Rect}), p, r) end function SDL_RectEmpty(r) ccall((:SDL_RectEmpty, libsdl2), SDL_bool, (Ptr{SDL_Rect},), r) end function SDL_RectEquals(a, b) ccall((:SDL_RectEquals, libsdl2), SDL_bool, (Ptr{SDL_Rect}, Ptr{SDL_Rect}), a, b) end function SDL_HasIntersection(A, B) ccall((:SDL_HasIntersection, libsdl2), SDL_bool, (Ptr{SDL_Rect}, Ptr{SDL_Rect}), A, B) end function SDL_IntersectRect(A, B, result) ccall((:SDL_IntersectRect, libsdl2), SDL_bool, (Ptr{SDL_Rect}, Ptr{SDL_Rect}, Ptr{SDL_Rect}), A, B, result) end function SDL_UnionRect(A, B, result) ccall((:SDL_UnionRect, libsdl2), Cvoid, (Ptr{SDL_Rect}, Ptr{SDL_Rect}, Ptr{SDL_Rect}), A, B, result) end function SDL_EnclosePoints(points, count, clip, result) ccall((:SDL_EnclosePoints, libsdl2), SDL_bool, (Ptr{SDL_Point}, Cint, Ptr{SDL_Rect}, Ptr{SDL_Rect}), points, count, clip, result) end function SDL_IntersectRectAndLine(rect, X1, Y1, X2, Y2) ccall((:SDL_IntersectRectAndLine, libsdl2), SDL_bool, (Ptr{SDL_Rect}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), rect, X1, Y1, X2, Y2) end function SDL_PointInFRect(p, r) ccall((:SDL_PointInFRect, libsdl2), SDL_bool, (Ptr{SDL_FPoint}, Ptr{SDL_FRect}), p, r) end function SDL_FRectEmpty(r) ccall((:SDL_FRectEmpty, libsdl2), SDL_bool, (Ptr{SDL_FRect},), r) end function SDL_FRectEqualsEpsilon(a, b, epsilon) ccall((:SDL_FRectEqualsEpsilon, libsdl2), SDL_bool, (Ptr{SDL_FRect}, Ptr{SDL_FRect}, Cfloat), a, b, epsilon) end function SDL_FRectEquals(a, b) ccall((:SDL_FRectEquals, libsdl2), SDL_bool, (Ptr{SDL_FRect}, Ptr{SDL_FRect}), a, b) end function SDL_HasIntersectionF(A, B) ccall((:SDL_HasIntersectionF, libsdl2), SDL_bool, (Ptr{SDL_FRect}, Ptr{SDL_FRect}), A, B) end function SDL_IntersectFRect(A, B, result) ccall((:SDL_IntersectFRect, libsdl2), SDL_bool, (Ptr{SDL_FRect}, Ptr{SDL_FRect}, Ptr{SDL_FRect}), A, B, result) end function SDL_UnionFRect(A, B, result) ccall((:SDL_UnionFRect, libsdl2), Cvoid, (Ptr{SDL_FRect}, Ptr{SDL_FRect}, Ptr{SDL_FRect}), A, B, result) end function SDL_EncloseFPoints(points, count, clip, result) ccall((:SDL_EncloseFPoints, libsdl2), SDL_bool, (Ptr{SDL_FPoint}, Cint, Ptr{SDL_FRect}, Ptr{SDL_FRect}), points, count, clip, result) end function SDL_IntersectFRectAndLine(rect, X1, Y1, X2, Y2) ccall((:SDL_IntersectFRectAndLine, libsdl2), SDL_bool, (Ptr{SDL_FRect}, Ptr{Cfloat}, Ptr{Cfloat}, Ptr{Cfloat}, Ptr{Cfloat}), rect, X1, Y1, X2, Y2) end @cenum SDL_BlendMode::UInt32 begin SDL_BLENDMODE_NONE = 0 SDL_BLENDMODE_BLEND = 1 SDL_BLENDMODE_ADD = 2 SDL_BLENDMODE_MOD = 4 SDL_BLENDMODE_MUL = 8 SDL_BLENDMODE_INVALID = 2147483647 end @cenum SDL_BlendOperation::UInt32 begin SDL_BLENDOPERATION_ADD = 1 SDL_BLENDOPERATION_SUBTRACT = 2 SDL_BLENDOPERATION_REV_SUBTRACT = 3 SDL_BLENDOPERATION_MINIMUM = 4 SDL_BLENDOPERATION_MAXIMUM = 5 end @cenum SDL_BlendFactor::UInt32 begin SDL_BLENDFACTOR_ZERO = 1 SDL_BLENDFACTOR_ONE = 2 SDL_BLENDFACTOR_SRC_COLOR = 3 SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR = 4 SDL_BLENDFACTOR_SRC_ALPHA = 5 SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA = 6 SDL_BLENDFACTOR_DST_COLOR = 7 SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR = 8 SDL_BLENDFACTOR_DST_ALPHA = 9 SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA = 10 end function SDL_ComposeCustomBlendMode(srcColorFactor, dstColorFactor, colorOperation, srcAlphaFactor, dstAlphaFactor, alphaOperation) ccall((:SDL_ComposeCustomBlendMode, libsdl2), SDL_BlendMode, (SDL_BlendFactor, SDL_BlendFactor, SDL_BlendOperation, SDL_BlendFactor, SDL_BlendFactor, SDL_BlendOperation), srcColorFactor, dstColorFactor, colorOperation, srcAlphaFactor, dstAlphaFactor, alphaOperation) end # typedef int ( SDLCALL * SDL_blit ) ( struct SDL_Surface * src , SDL_Rect * srcrect , struct SDL_Surface * dst , SDL_Rect * dstrect ) const SDL_blit = Ptr{Cvoid} @cenum SDL_YUV_CONVERSION_MODE::UInt32 begin SDL_YUV_CONVERSION_JPEG = 0 SDL_YUV_CONVERSION_BT601 = 1 SDL_YUV_CONVERSION_BT709 = 2 SDL_YUV_CONVERSION_AUTOMATIC = 3 end function SDL_CreateRGBSurface(flags, width, height, depth, Rmask, Gmask, Bmask, Amask) ccall((:SDL_CreateRGBSurface, libsdl2), Ptr{SDL_Surface}, (Uint32, Cint, Cint, Cint, Uint32, Uint32, Uint32, Uint32), flags, width, height, depth, Rmask, Gmask, Bmask, Amask) end function SDL_CreateRGBSurfaceWithFormat(flags, width, height, depth, format) ccall((:SDL_CreateRGBSurfaceWithFormat, libsdl2), Ptr{SDL_Surface}, (Uint32, Cint, Cint, Cint, Uint32), flags, width, height, depth, format) end function SDL_CreateRGBSurfaceFrom(pixels, width, height, depth, pitch, Rmask, Gmask, Bmask, Amask) ccall((:SDL_CreateRGBSurfaceFrom, libsdl2), Ptr{SDL_Surface}, (Ptr{Cvoid}, Cint, Cint, Cint, Cint, Uint32, Uint32, Uint32, Uint32), pixels, width, height, depth, pitch, Rmask, Gmask, Bmask, Amask) end function SDL_CreateRGBSurfaceWithFormatFrom(pixels, width, height, depth, pitch, format) ccall((:SDL_CreateRGBSurfaceWithFormatFrom, libsdl2), Ptr{SDL_Surface}, (Ptr{Cvoid}, Cint, Cint, Cint, Cint, Uint32), pixels, width, height, depth, pitch, format) end function SDL_FreeSurface(surface) ccall((:SDL_FreeSurface, libsdl2), Cvoid, (Ptr{SDL_Surface},), surface) end function SDL_SetSurfacePalette(surface, palette) ccall((:SDL_SetSurfacePalette, libsdl2), Cint, (Ptr{SDL_Surface}, Ptr{SDL_Palette}), surface, palette) end function SDL_LockSurface(surface) ccall((:SDL_LockSurface, libsdl2), Cint, (Ptr{SDL_Surface},), surface) end function SDL_UnlockSurface(surface) ccall((:SDL_UnlockSurface, libsdl2), Cvoid, (Ptr{SDL_Surface},), surface) end function SDL_SetSurfaceRLE(surface, flag) ccall((:SDL_SetSurfaceRLE, libsdl2), Cint, (Ptr{SDL_Surface}, Cint), surface, flag) end function SDL_HasSurfaceRLE(surface) ccall((:SDL_HasSurfaceRLE, libsdl2), SDL_bool, (Ptr{SDL_Surface},), surface) end function SDL_SetColorKey(surface, flag, key) ccall((:SDL_SetColorKey, libsdl2), Cint, (Ptr{SDL_Surface}, Cint, Uint32), surface, flag, key) end function SDL_HasColorKey(surface) ccall((:SDL_HasColorKey, libsdl2), SDL_bool, (Ptr{SDL_Surface},), surface) end function SDL_GetColorKey(surface, key) ccall((:SDL_GetColorKey, libsdl2), Cint, (Ptr{SDL_Surface}, Ptr{Uint32}), surface, key) end function SDL_SetSurfaceColorMod(surface, r, g, b) ccall((:SDL_SetSurfaceColorMod, libsdl2), Cint, (Ptr{SDL_Surface}, Uint8, Uint8, Uint8), surface, r, g, b) end function SDL_GetSurfaceColorMod(surface, r, g, b) ccall((:SDL_GetSurfaceColorMod, libsdl2), Cint, (Ptr{SDL_Surface}, Ptr{Uint8}, Ptr{Uint8}, Ptr{Uint8}), surface, r, g, b) end function SDL_SetSurfaceAlphaMod(surface, alpha) ccall((:SDL_SetSurfaceAlphaMod, libsdl2), Cint, (Ptr{SDL_Surface}, Uint8), surface, alpha) end function SDL_GetSurfaceAlphaMod(surface, alpha) ccall((:SDL_GetSurfaceAlphaMod, libsdl2), Cint, (Ptr{SDL_Surface}, Ptr{Uint8}), surface, alpha) end function SDL_SetSurfaceBlendMode(surface, blendMode) ccall((:SDL_SetSurfaceBlendMode, libsdl2), Cint, (Ptr{SDL_Surface}, SDL_BlendMode), surface, blendMode) end function SDL_GetSurfaceBlendMode(surface, blendMode) ccall((:SDL_GetSurfaceBlendMode, libsdl2), Cint, (Ptr{SDL_Surface}, Ptr{SDL_BlendMode}), surface, blendMode) end function SDL_SetClipRect(surface, rect) ccall((:SDL_SetClipRect, libsdl2), SDL_bool, (Ptr{SDL_Surface}, Ptr{SDL_Rect}), surface, rect) end function SDL_GetClipRect(surface, rect) ccall((:SDL_GetClipRect, libsdl2), Cvoid, (Ptr{SDL_Surface}, Ptr{SDL_Rect}), surface, rect) end function SDL_DuplicateSurface(surface) ccall((:SDL_DuplicateSurface, libsdl2), Ptr{SDL_Surface}, (Ptr{SDL_Surface},), surface) end function SDL_ConvertSurface(src, fmt, flags) ccall((:SDL_ConvertSurface, libsdl2), Ptr{SDL_Surface}, (Ptr{SDL_Surface}, Ptr{SDL_PixelFormat}, Uint32), src, fmt, flags) end function SDL_ConvertSurfaceFormat(src, pixel_format, flags) ccall((:SDL_ConvertSurfaceFormat, libsdl2), Ptr{SDL_Surface}, (Ptr{SDL_Surface}, Uint32, Uint32), src, pixel_format, flags) end function SDL_ConvertPixels(width, height, src_format, src, src_pitch, dst_format, dst, dst_pitch) ccall((:SDL_ConvertPixels, libsdl2), Cint, (Cint, Cint, Uint32, Ptr{Cvoid}, Cint, Uint32, Ptr{Cvoid}, Cint), width, height, src_format, src, src_pitch, dst_format, dst, dst_pitch) end function SDL_PremultiplyAlpha(width, height, src_format, src, src_pitch, dst_format, dst, dst_pitch) ccall((:SDL_PremultiplyAlpha, libsdl2), Cint, (Cint, Cint, Uint32, Ptr{Cvoid}, Cint, Uint32, Ptr{Cvoid}, Cint), width, height, src_format, src, src_pitch, dst_format, dst, dst_pitch) end function SDL_FillRect(dst, rect, color) ccall((:SDL_FillRect, libsdl2), Cint, (Ptr{SDL_Surface}, Ptr{SDL_Rect}, Uint32), dst, rect, color) end function SDL_FillRects(dst, rects, count, color) ccall((:SDL_FillRects, libsdl2), Cint, (Ptr{SDL_Surface}, Ptr{SDL_Rect}, Cint, Uint32), dst, rects, count, color) end function SDL_LowerBlit(src, srcrect, dst, dstrect) ccall((:SDL_LowerBlit, libsdl2), Cint, (Ptr{SDL_Surface}, Ptr{SDL_Rect}, Ptr{SDL_Surface}, Ptr{SDL_Rect}), src, srcrect, dst, dstrect) end function SDL_SoftStretch(src, srcrect, dst, dstrect) ccall((:SDL_SoftStretch, libsdl2), Cint, (Ptr{SDL_Surface}, Ptr{SDL_Rect}, Ptr{SDL_Surface}, Ptr{SDL_Rect}), src, srcrect, dst, dstrect) end function SDL_SoftStretchLinear(src, srcrect, dst, dstrect) ccall((:SDL_SoftStretchLinear, libsdl2), Cint, (Ptr{SDL_Surface}, Ptr{SDL_Rect}, Ptr{SDL_Surface}, Ptr{SDL_Rect}), src, srcrect, dst, dstrect) end function SDL_LowerBlitScaled(src, srcrect, dst, dstrect) ccall((:SDL_LowerBlitScaled, libsdl2), Cint, (Ptr{SDL_Surface}, Ptr{SDL_Rect}, Ptr{SDL_Surface}, Ptr{SDL_Rect}), src, srcrect, dst, dstrect) end function SDL_SetYUVConversionMode(mode) ccall((:SDL_SetYUVConversionMode, libsdl2), Cvoid, (SDL_YUV_CONVERSION_MODE,), mode) end function SDL_GetYUVConversionMode() ccall((:SDL_GetYUVConversionMode, libsdl2), SDL_YUV_CONVERSION_MODE, ()) end function SDL_GetYUVConversionModeForResolution(width, height) ccall((:SDL_GetYUVConversionModeForResolution, libsdl2), SDL_YUV_CONVERSION_MODE, (Cint, Cint), width, height) end struct SDL_DisplayMode format::Uint32 w::Cint h::Cint refresh_rate::Cint driverdata::Ptr{Cvoid} end mutable struct SDL_Window end @cenum SDL_WindowFlags::UInt32 begin SDL_WINDOW_FULLSCREEN = 1 SDL_WINDOW_OPENGL = 2 SDL_WINDOW_SHOWN = 4 SDL_WINDOW_HIDDEN = 8 SDL_WINDOW_BORDERLESS = 16 SDL_WINDOW_RESIZABLE = 32 SDL_WINDOW_MINIMIZED = 64 SDL_WINDOW_MAXIMIZED = 128 SDL_WINDOW_MOUSE_GRABBED = 256 SDL_WINDOW_INPUT_FOCUS = 512 SDL_WINDOW_MOUSE_FOCUS = 1024 SDL_WINDOW_FULLSCREEN_DESKTOP = 4097 SDL_WINDOW_FOREIGN = 2048 SDL_WINDOW_ALLOW_HIGHDPI = 8192 SDL_WINDOW_MOUSE_CAPTURE = 16384 SDL_WINDOW_ALWAYS_ON_TOP = 32768 SDL_WINDOW_SKIP_TASKBAR = 65536 SDL_WINDOW_UTILITY = 131072 SDL_WINDOW_TOOLTIP = 262144 SDL_WINDOW_POPUP_MENU = 524288 SDL_WINDOW_KEYBOARD_GRABBED = 1048576 SDL_WINDOW_VULKAN = 268435456 SDL_WINDOW_METAL = 536870912 SDL_WINDOW_INPUT_GRABBED = 256 end @cenum SDL_WindowEventID::UInt32 begin SDL_WINDOWEVENT_NONE = 0 SDL_WINDOWEVENT_SHOWN = 1 SDL_WINDOWEVENT_HIDDEN = 2 SDL_WINDOWEVENT_EXPOSED = 3 SDL_WINDOWEVENT_MOVED = 4 SDL_WINDOWEVENT_RESIZED = 5 SDL_WINDOWEVENT_SIZE_CHANGED = 6 SDL_WINDOWEVENT_MINIMIZED = 7 SDL_WINDOWEVENT_MAXIMIZED = 8 SDL_WINDOWEVENT_RESTORED = 9 SDL_WINDOWEVENT_ENTER = 10 SDL_WINDOWEVENT_LEAVE = 11 SDL_WINDOWEVENT_FOCUS_GAINED = 12 SDL_WINDOWEVENT_FOCUS_LOST = 13 SDL_WINDOWEVENT_CLOSE = 14 SDL_WINDOWEVENT_TAKE_FOCUS = 15 SDL_WINDOWEVENT_HIT_TEST = 16 SDL_WINDOWEVENT_ICCPROF_CHANGED = 17 SDL_WINDOWEVENT_DISPLAY_CHANGED = 18 end @cenum SDL_DisplayEventID::UInt32 begin SDL_DISPLAYEVENT_NONE = 0 SDL_DISPLAYEVENT_ORIENTATION = 1 SDL_DISPLAYEVENT_CONNECTED = 2 SDL_DISPLAYEVENT_DISCONNECTED = 3 end @cenum SDL_DisplayOrientation::UInt32 begin SDL_ORIENTATION_UNKNOWN = 0 SDL_ORIENTATION_LANDSCAPE = 1 SDL_ORIENTATION_LANDSCAPE_FLIPPED = 2 SDL_ORIENTATION_PORTRAIT = 3 SDL_ORIENTATION_PORTRAIT_FLIPPED = 4 end @cenum SDL_FlashOperation::UInt32 begin SDL_FLASH_CANCEL = 0 SDL_FLASH_BRIEFLY = 1 SDL_FLASH_UNTIL_FOCUSED = 2 end const SDL_GLContext = Ptr{Cvoid} @cenum SDL_GLattr::UInt32 begin SDL_GL_RED_SIZE = 0 SDL_GL_GREEN_SIZE = 1 SDL_GL_BLUE_SIZE = 2 SDL_GL_ALPHA_SIZE = 3 SDL_GL_BUFFER_SIZE = 4 SDL_GL_DOUBLEBUFFER = 5 SDL_GL_DEPTH_SIZE = 6 SDL_GL_STENCIL_SIZE = 7 SDL_GL_ACCUM_RED_SIZE = 8 SDL_GL_ACCUM_GREEN_SIZE = 9 SDL_GL_ACCUM_BLUE_SIZE = 10 SDL_GL_ACCUM_ALPHA_SIZE = 11 SDL_GL_STEREO = 12 SDL_GL_MULTISAMPLEBUFFERS = 13 SDL_GL_MULTISAMPLESAMPLES = 14 SDL_GL_ACCELERATED_VISUAL = 15 SDL_GL_RETAINED_BACKING = 16 SDL_GL_CONTEXT_MAJOR_VERSION = 17 SDL_GL_CONTEXT_MINOR_VERSION = 18 SDL_GL_CONTEXT_EGL = 19 SDL_GL_CONTEXT_FLAGS = 20 SDL_GL_CONTEXT_PROFILE_MASK = 21 SDL_GL_SHARE_WITH_CURRENT_CONTEXT = 22 SDL_GL_FRAMEBUFFER_SRGB_CAPABLE = 23 SDL_GL_CONTEXT_RELEASE_BEHAVIOR = 24 SDL_GL_CONTEXT_RESET_NOTIFICATION = 25 SDL_GL_CONTEXT_NO_ERROR = 26 SDL_GL_FLOATBUFFERS = 27 end @cenum SDL_GLprofile::UInt32 begin SDL_GL_CONTEXT_PROFILE_CORE = 1 SDL_GL_CONTEXT_PROFILE_COMPATIBILITY = 2 SDL_GL_CONTEXT_PROFILE_ES = 4 end @cenum SDL_GLcontextFlag::UInt32 begin SDL_GL_CONTEXT_DEBUG_FLAG = 1 SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG = 2 SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG = 4 SDL_GL_CONTEXT_RESET_ISOLATION_FLAG = 8 end @cenum SDL_GLcontextReleaseFlag::UInt32 begin SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE = 0 SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH = 1 end @cenum SDL_GLContextResetNotification::UInt32 begin SDL_GL_CONTEXT_RESET_NO_NOTIFICATION = 0 SDL_GL_CONTEXT_RESET_LOSE_CONTEXT = 1 end function SDL_GetNumVideoDrivers() ccall((:SDL_GetNumVideoDrivers, libsdl2), Cint, ()) end function SDL_GetVideoDriver(index) ccall((:SDL_GetVideoDriver, libsdl2), Ptr{Cchar}, (Cint,), index) end function SDL_VideoInit(driver_name) ccall((:SDL_VideoInit, libsdl2), Cint, (Ptr{Cchar},), driver_name) end function SDL_VideoQuit() ccall((:SDL_VideoQuit, libsdl2), Cvoid, ()) end function SDL_GetCurrentVideoDriver() ccall((:SDL_GetCurrentVideoDriver, libsdl2), Ptr{Cchar}, ()) end function SDL_GetNumVideoDisplays() ccall((:SDL_GetNumVideoDisplays, libsdl2), Cint, ()) end function SDL_GetDisplayName(displayIndex) ccall((:SDL_GetDisplayName, libsdl2), Ptr{Cchar}, (Cint,), displayIndex) end function SDL_GetDisplayBounds(displayIndex, rect) ccall((:SDL_GetDisplayBounds, libsdl2), Cint, (Cint, Ptr{SDL_Rect}), displayIndex, rect) end function SDL_GetDisplayUsableBounds(displayIndex, rect) ccall((:SDL_GetDisplayUsableBounds, libsdl2), Cint, (Cint, Ptr{SDL_Rect}), displayIndex, rect) end function SDL_GetDisplayDPI(displayIndex, ddpi, hdpi, vdpi) ccall((:SDL_GetDisplayDPI, libsdl2), Cint, (Cint, Ptr{Cfloat}, Ptr{Cfloat}, Ptr{Cfloat}), displayIndex, ddpi, hdpi, vdpi) end function SDL_GetDisplayOrientation(displayIndex) ccall((:SDL_GetDisplayOrientation, libsdl2), SDL_DisplayOrientation, (Cint,), displayIndex) end function SDL_GetNumDisplayModes(displayIndex) ccall((:SDL_GetNumDisplayModes, libsdl2), Cint, (Cint,), displayIndex) end function SDL_GetDisplayMode(displayIndex, modeIndex, mode) ccall((:SDL_GetDisplayMode, libsdl2), Cint, (Cint, Cint, Ptr{SDL_DisplayMode}), displayIndex, modeIndex, mode) end function SDL_GetDesktopDisplayMode(displayIndex, mode) ccall((:SDL_GetDesktopDisplayMode, libsdl2), Cint, (Cint, Ptr{SDL_DisplayMode}), displayIndex, mode) end function SDL_GetCurrentDisplayMode(displayIndex, mode) ccall((:SDL_GetCurrentDisplayMode, libsdl2), Cint, (Cint, Ptr{SDL_DisplayMode}), displayIndex, mode) end function SDL_GetClosestDisplayMode(displayIndex, mode, closest) ccall((:SDL_GetClosestDisplayMode, libsdl2), Ptr{SDL_DisplayMode}, (Cint, Ptr{SDL_DisplayMode}, Ptr{SDL_DisplayMode}), displayIndex, mode, closest) end function SDL_GetPointDisplayIndex(point) ccall((:SDL_GetPointDisplayIndex, libsdl2), Cint, (Ptr{SDL_Point},), point) end function SDL_GetRectDisplayIndex(rect) ccall((:SDL_GetRectDisplayIndex, libsdl2), Cint, (Ptr{SDL_Rect},), rect) end function SDL_GetWindowDisplayIndex(window) ccall((:SDL_GetWindowDisplayIndex, libsdl2), Cint, (Ptr{SDL_Window},), window) end function SDL_SetWindowDisplayMode(window, mode) ccall((:SDL_SetWindowDisplayMode, libsdl2), Cint, (Ptr{SDL_Window}, Ptr{SDL_DisplayMode}), window, mode) end function SDL_GetWindowDisplayMode(window, mode) ccall((:SDL_GetWindowDisplayMode, libsdl2), Cint, (Ptr{SDL_Window}, Ptr{SDL_DisplayMode}), window, mode) end function SDL_GetWindowICCProfile(window, size) ccall((:SDL_GetWindowICCProfile, libsdl2), Ptr{Cvoid}, (Ptr{SDL_Window}, Ptr{Csize_t}), window, size) end function SDL_GetWindowPixelFormat(window) ccall((:SDL_GetWindowPixelFormat, libsdl2), Uint32, (Ptr{SDL_Window},), window) end function SDL_CreateWindow(title, x, y, w, h, flags) ccall((:SDL_CreateWindow, libsdl2), Ptr{SDL_Window}, (Ptr{Cchar}, Cint, Cint, Cint, Cint, Uint32), title, x, y, w, h, flags) end function SDL_CreateWindowFrom(data) ccall((:SDL_CreateWindowFrom, libsdl2), Ptr{SDL_Window}, (Ptr{Cvoid},), data) end function SDL_GetWindowID(window) ccall((:SDL_GetWindowID, libsdl2), Uint32, (Ptr{SDL_Window},), window) end function SDL_GetWindowFromID(id) ccall((:SDL_GetWindowFromID, libsdl2), Ptr{SDL_Window}, (Uint32,), id) end function SDL_GetWindowFlags(window) ccall((:SDL_GetWindowFlags, libsdl2), Uint32, (Ptr{SDL_Window},), window) end function SDL_SetWindowTitle(window, title) ccall((:SDL_SetWindowTitle, libsdl2), Cvoid, (Ptr{SDL_Window}, Ptr{Cchar}), window, title) end function SDL_GetWindowTitle(window) ccall((:SDL_GetWindowTitle, libsdl2), Ptr{Cchar}, (Ptr{SDL_Window},), window) end function SDL_SetWindowIcon(window, icon) ccall((:SDL_SetWindowIcon, libsdl2), Cvoid, (Ptr{SDL_Window}, Ptr{SDL_Surface}), window, icon) end function SDL_SetWindowData(window, name, userdata) ccall((:SDL_SetWindowData, libsdl2), Ptr{Cvoid}, (Ptr{SDL_Window}, Ptr{Cchar}, Ptr{Cvoid}), window, name, userdata) end function SDL_GetWindowData(window, name) ccall((:SDL_GetWindowData, libsdl2), Ptr{Cvoid}, (Ptr{SDL_Window}, Ptr{Cchar}), window, name) end function SDL_SetWindowPosition(window, x, y) ccall((:SDL_SetWindowPosition, libsdl2), Cvoid, (Ptr{SDL_Window}, Cint, Cint), window, x, y) end function SDL_GetWindowPosition(window, x, y) ccall((:SDL_GetWindowPosition, libsdl2), Cvoid, (Ptr{SDL_Window}, Ptr{Cint}, Ptr{Cint}), window, x, y) end function SDL_SetWindowSize(window, w, h) ccall((:SDL_SetWindowSize, libsdl2), Cvoid, (Ptr{SDL_Window}, Cint, Cint), window, w, h) end function SDL_GetWindowSize(window, w, h) ccall((:SDL_GetWindowSize, libsdl2), Cvoid, (Ptr{SDL_Window}, Ptr{Cint}, Ptr{Cint}), window, w, h) end function SDL_GetWindowBordersSize(window, top, left, bottom, right) ccall((:SDL_GetWindowBordersSize, libsdl2), Cint, (Ptr{SDL_Window}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), window, top, left, bottom, right) end function SDL_SetWindowMinimumSize(window, min_w, min_h) ccall((:SDL_SetWindowMinimumSize, libsdl2), Cvoid, (Ptr{SDL_Window}, Cint, Cint), window, min_w, min_h) end function SDL_GetWindowMinimumSize(window, w, h) ccall((:SDL_GetWindowMinimumSize, libsdl2), Cvoid, (Ptr{SDL_Window}, Ptr{Cint}, Ptr{Cint}), window, w, h) end function SDL_SetWindowMaximumSize(window, max_w, max_h) ccall((:SDL_SetWindowMaximumSize, libsdl2), Cvoid, (Ptr{SDL_Window}, Cint, Cint), window, max_w, max_h) end function SDL_GetWindowMaximumSize(window, w, h) ccall((:SDL_GetWindowMaximumSize, libsdl2), Cvoid, (Ptr{SDL_Window}, Ptr{Cint}, Ptr{Cint}), window, w, h) end function SDL_SetWindowBordered(window, bordered) ccall((:SDL_SetWindowBordered, libsdl2), Cvoid, (Ptr{SDL_Window}, SDL_bool), window, bordered) end function SDL_SetWindowResizable(window, resizable) ccall((:SDL_SetWindowResizable, libsdl2), Cvoid, (Ptr{SDL_Window}, SDL_bool), window, resizable) end function SDL_SetWindowAlwaysOnTop(window, on_top) ccall((:SDL_SetWindowAlwaysOnTop, libsdl2), Cvoid, (Ptr{SDL_Window}, SDL_bool), window, on_top) end function SDL_ShowWindow(window) ccall((:SDL_ShowWindow, libsdl2), Cvoid, (Ptr{SDL_Window},), window) end function SDL_HideWindow(window) ccall((:SDL_HideWindow, libsdl2), Cvoid, (Ptr{SDL_Window},), window) end function SDL_RaiseWindow(window) ccall((:SDL_RaiseWindow, libsdl2), Cvoid, (Ptr{SDL_Window},), window) end function SDL_MaximizeWindow(window) ccall((:SDL_MaximizeWindow, libsdl2), Cvoid, (Ptr{SDL_Window},), window) end function SDL_MinimizeWindow(window) ccall((:SDL_MinimizeWindow, libsdl2), Cvoid, (Ptr{SDL_Window},), window) end function SDL_RestoreWindow(window) ccall((:SDL_RestoreWindow, libsdl2), Cvoid, (Ptr{SDL_Window},), window) end function SDL_SetWindowFullscreen(window, flags) ccall((:SDL_SetWindowFullscreen, libsdl2), Cint, (Ptr{SDL_Window}, Uint32), window, flags) end function SDL_GetWindowSurface(window) ccall((:SDL_GetWindowSurface, libsdl2), Ptr{SDL_Surface}, (Ptr{SDL_Window},), window) end function SDL_UpdateWindowSurface(window) ccall((:SDL_UpdateWindowSurface, libsdl2), Cint, (Ptr{SDL_Window},), window) end function SDL_UpdateWindowSurfaceRects(window, rects, numrects) ccall((:SDL_UpdateWindowSurfaceRects, libsdl2), Cint, (Ptr{SDL_Window}, Ptr{SDL_Rect}, Cint), window, rects, numrects) end function SDL_SetWindowGrab(window, grabbed) ccall((:SDL_SetWindowGrab, libsdl2), Cvoid, (Ptr{SDL_Window}, SDL_bool), window, grabbed) end function SDL_SetWindowKeyboardGrab(window, grabbed) ccall((:SDL_SetWindowKeyboardGrab, libsdl2), Cvoid, (Ptr{SDL_Window}, SDL_bool), window, grabbed) end function SDL_SetWindowMouseGrab(window, grabbed) ccall((:SDL_SetWindowMouseGrab, libsdl2), Cvoid, (Ptr{SDL_Window}, SDL_bool), window, grabbed) end function SDL_GetWindowGrab(window) ccall((:SDL_GetWindowGrab, libsdl2), SDL_bool, (Ptr{SDL_Window},), window) end function SDL_GetWindowKeyboardGrab(window) ccall((:SDL_GetWindowKeyboardGrab, libsdl2), SDL_bool, (Ptr{SDL_Window},), window) end function SDL_GetWindowMouseGrab(window) ccall((:SDL_GetWindowMouseGrab, libsdl2), SDL_bool, (Ptr{SDL_Window},), window) end function SDL_GetGrabbedWindow() ccall((:SDL_GetGrabbedWindow, libsdl2), Ptr{SDL_Window}, ()) end function SDL_SetWindowMouseRect(window, rect) ccall((:SDL_SetWindowMouseRect, libsdl2), Cint, (Ptr{SDL_Window}, Ptr{SDL_Rect}), window, rect) end function SDL_GetWindowMouseRect(window) ccall((:SDL_GetWindowMouseRect, libsdl2), Ptr{SDL_Rect}, (Ptr{SDL_Window},), window) end function SDL_SetWindowBrightness(window, brightness) ccall((:SDL_SetWindowBrightness, libsdl2), Cint, (Ptr{SDL_Window}, Cfloat), window, brightness) end function SDL_GetWindowBrightness(window) ccall((:SDL_GetWindowBrightness, libsdl2), Cfloat, (Ptr{SDL_Window},), window) end function SDL_SetWindowOpacity(window, opacity) ccall((:SDL_SetWindowOpacity, libsdl2), Cint, (Ptr{SDL_Window}, Cfloat), window, opacity) end function SDL_GetWindowOpacity(window, out_opacity) ccall((:SDL_GetWindowOpacity, libsdl2), Cint, (Ptr{SDL_Window}, Ptr{Cfloat}), window, out_opacity) end function SDL_SetWindowModalFor(modal_window, parent_window) ccall((:SDL_SetWindowModalFor, libsdl2), Cint, (Ptr{SDL_Window}, Ptr{SDL_Window}), modal_window, parent_window) end function SDL_SetWindowInputFocus(window) ccall((:SDL_SetWindowInputFocus, libsdl2), Cint, (Ptr{SDL_Window},), window) end function SDL_SetWindowGammaRamp(window, red, green, blue) ccall((:SDL_SetWindowGammaRamp, libsdl2), Cint, (Ptr{SDL_Window}, Ptr{Uint16}, Ptr{Uint16}, Ptr{Uint16}), window, red, green, blue) end function SDL_GetWindowGammaRamp(window, red, green, blue) ccall((:SDL_GetWindowGammaRamp, libsdl2), Cint, (Ptr{SDL_Window}, Ptr{Uint16}, Ptr{Uint16}, Ptr{Uint16}), window, red, green, blue) end @cenum SDL_HitTestResult::UInt32 begin SDL_HITTEST_NORMAL = 0 SDL_HITTEST_DRAGGABLE = 1 SDL_HITTEST_RESIZE_TOPLEFT = 2 SDL_HITTEST_RESIZE_TOP = 3 SDL_HITTEST_RESIZE_TOPRIGHT = 4 SDL_HITTEST_RESIZE_RIGHT = 5 SDL_HITTEST_RESIZE_BOTTOMRIGHT = 6 SDL_HITTEST_RESIZE_BOTTOM = 7 SDL_HITTEST_RESIZE_BOTTOMLEFT = 8 SDL_HITTEST_RESIZE_LEFT = 9 end # typedef SDL_HitTestResult ( SDLCALL * SDL_HitTest ) ( SDL_Window * win , const SDL_Point * area , void * data ) const SDL_HitTest = Ptr{Cvoid} function SDL_SetWindowHitTest(window, callback, callback_data) ccall((:SDL_SetWindowHitTest, libsdl2), Cint, (Ptr{SDL_Window}, SDL_HitTest, Ptr{Cvoid}), window, callback, callback_data) end function SDL_FlashWindow(window, operation) ccall((:SDL_FlashWindow, libsdl2), Cint, (Ptr{SDL_Window}, SDL_FlashOperation), window, operation) end function SDL_DestroyWindow(window) ccall((:SDL_DestroyWindow, libsdl2), Cvoid, (Ptr{SDL_Window},), window) end function SDL_IsScreenSaverEnabled() ccall((:SDL_IsScreenSaverEnabled, libsdl2), SDL_bool, ()) end function SDL_EnableScreenSaver() ccall((:SDL_EnableScreenSaver, libsdl2), Cvoid, ()) end function SDL_DisableScreenSaver() ccall((:SDL_DisableScreenSaver, libsdl2), Cvoid, ()) end function SDL_GL_LoadLibrary(path) ccall((:SDL_GL_LoadLibrary, libsdl2), Cint, (Ptr{Cchar},), path) end function SDL_GL_GetProcAddress(proc) ccall((:SDL_GL_GetProcAddress, libsdl2), Ptr{Cvoid}, (Ptr{Cchar},), proc) end function SDL_GL_UnloadLibrary() ccall((:SDL_GL_UnloadLibrary, libsdl2), Cvoid, ()) end function SDL_GL_ExtensionSupported(extension) ccall((:SDL_GL_ExtensionSupported, libsdl2), SDL_bool, (Ptr{Cchar},), extension) end function SDL_GL_ResetAttributes() ccall((:SDL_GL_ResetAttributes, libsdl2), Cvoid, ()) end function SDL_GL_SetAttribute(attr, value) ccall((:SDL_GL_SetAttribute, libsdl2), Cint, (SDL_GLattr, Cint), attr, value) end function SDL_GL_GetAttribute(attr, value) ccall((:SDL_GL_GetAttribute, libsdl2), Cint, (SDL_GLattr, Ptr{Cint}), attr, value) end function SDL_GL_CreateContext(window) ccall((:SDL_GL_CreateContext, libsdl2), SDL_GLContext, (Ptr{SDL_Window},), window) end function SDL_GL_MakeCurrent(window, context) ccall((:SDL_GL_MakeCurrent, libsdl2), Cint, (Ptr{SDL_Window}, SDL_GLContext), window, context) end function SDL_GL_GetCurrentWindow() ccall((:SDL_GL_GetCurrentWindow, libsdl2), Ptr{SDL_Window}, ()) end function SDL_GL_GetCurrentContext() ccall((:SDL_GL_GetCurrentContext, libsdl2), SDL_GLContext, ()) end function SDL_GL_GetDrawableSize(window, w, h) ccall((:SDL_GL_GetDrawableSize, libsdl2), Cvoid, (Ptr{SDL_Window}, Ptr{Cint}, Ptr{Cint}), window, w, h) end function SDL_GL_SetSwapInterval(interval) ccall((:SDL_GL_SetSwapInterval, libsdl2), Cint, (Cint,), interval) end function SDL_GL_GetSwapInterval() ccall((:SDL_GL_GetSwapInterval, libsdl2), Cint, ()) end function SDL_GL_SwapWindow(window) ccall((:SDL_GL_SwapWindow, libsdl2), Cvoid, (Ptr{SDL_Window},), window) end function SDL_GL_DeleteContext(context) ccall((:SDL_GL_DeleteContext, libsdl2), Cvoid, (SDL_GLContext,), context) end @cenum SDL_Scancode::UInt32 begin SDL_SCANCODE_UNKNOWN = 0 SDL_SCANCODE_A = 4 SDL_SCANCODE_B = 5 SDL_SCANCODE_C = 6 SDL_SCANCODE_D = 7 SDL_SCANCODE_E = 8 SDL_SCANCODE_F = 9 SDL_SCANCODE_G = 10 SDL_SCANCODE_H = 11 SDL_SCANCODE_I = 12 SDL_SCANCODE_J = 13 SDL_SCANCODE_K = 14 SDL_SCANCODE_L = 15 SDL_SCANCODE_M = 16 SDL_SCANCODE_N = 17 SDL_SCANCODE_O = 18 SDL_SCANCODE_P = 19 SDL_SCANCODE_Q = 20 SDL_SCANCODE_R = 21 SDL_SCANCODE_S = 22 SDL_SCANCODE_T = 23 SDL_SCANCODE_U = 24 SDL_SCANCODE_V = 25 SDL_SCANCODE_W = 26 SDL_SCANCODE_X = 27 SDL_SCANCODE_Y = 28 SDL_SCANCODE_Z = 29 SDL_SCANCODE_1 = 30 SDL_SCANCODE_2 = 31 SDL_SCANCODE_3 = 32 SDL_SCANCODE_4 = 33 SDL_SCANCODE_5 = 34 SDL_SCANCODE_6 = 35 SDL_SCANCODE_7 = 36 SDL_SCANCODE_8 = 37 SDL_SCANCODE_9 = 38 SDL_SCANCODE_0 = 39 SDL_SCANCODE_RETURN = 40 SDL_SCANCODE_ESCAPE = 41 SDL_SCANCODE_BACKSPACE = 42 SDL_SCANCODE_TAB = 43 SDL_SCANCODE_SPACE = 44 SDL_SCANCODE_MINUS = 45 SDL_SCANCODE_EQUALS = 46 SDL_SCANCODE_LEFTBRACKET = 47 SDL_SCANCODE_RIGHTBRACKET = 48 SDL_SCANCODE_BACKSLASH = 49 SDL_SCANCODE_NONUSHASH = 50 SDL_SCANCODE_SEMICOLON = 51 SDL_SCANCODE_APOSTROPHE = 52 SDL_SCANCODE_GRAVE = 53 SDL_SCANCODE_COMMA = 54 SDL_SCANCODE_PERIOD = 55 SDL_SCANCODE_SLASH = 56 SDL_SCANCODE_CAPSLOCK = 57 SDL_SCANCODE_F1 = 58 SDL_SCANCODE_F2 = 59 SDL_SCANCODE_F3 = 60 SDL_SCANCODE_F4 = 61 SDL_SCANCODE_F5 = 62 SDL_SCANCODE_F6 = 63 SDL_SCANCODE_F7 = 64 SDL_SCANCODE_F8 = 65 SDL_SCANCODE_F9 = 66 SDL_SCANCODE_F10 = 67 SDL_SCANCODE_F11 = 68 SDL_SCANCODE_F12 = 69 SDL_SCANCODE_PRINTSCREEN = 70 SDL_SCANCODE_SCROLLLOCK = 71 SDL_SCANCODE_PAUSE = 72 SDL_SCANCODE_INSERT = 73 SDL_SCANCODE_HOME = 74 SDL_SCANCODE_PAGEUP = 75 SDL_SCANCODE_DELETE = 76 SDL_SCANCODE_END = 77 SDL_SCANCODE_PAGEDOWN = 78 SDL_SCANCODE_RIGHT = 79 SDL_SCANCODE_LEFT = 80 SDL_SCANCODE_DOWN = 81 SDL_SCANCODE_UP = 82 SDL_SCANCODE_NUMLOCKCLEAR = 83 SDL_SCANCODE_KP_DIVIDE = 84 SDL_SCANCODE_KP_MULTIPLY = 85 SDL_SCANCODE_KP_MINUS = 86 SDL_SCANCODE_KP_PLUS = 87 SDL_SCANCODE_KP_ENTER = 88 SDL_SCANCODE_KP_1 = 89 SDL_SCANCODE_KP_2 = 90 SDL_SCANCODE_KP_3 = 91 SDL_SCANCODE_KP_4 = 92 SDL_SCANCODE_KP_5 = 93 SDL_SCANCODE_KP_6 = 94 SDL_SCANCODE_KP_7 = 95 SDL_SCANCODE_KP_8 = 96 SDL_SCANCODE_KP_9 = 97 SDL_SCANCODE_KP_0 = 98 SDL_SCANCODE_KP_PERIOD = 99 SDL_SCANCODE_NONUSBACKSLASH = 100 SDL_SCANCODE_APPLICATION = 101 SDL_SCANCODE_POWER = 102 SDL_SCANCODE_KP_EQUALS = 103 SDL_SCANCODE_F13 = 104 SDL_SCANCODE_F14 = 105 SDL_SCANCODE_F15 = 106 SDL_SCANCODE_F16 = 107 SDL_SCANCODE_F17 = 108 SDL_SCANCODE_F18 = 109 SDL_SCANCODE_F19 = 110 SDL_SCANCODE_F20 = 111 SDL_SCANCODE_F21 = 112 SDL_SCANCODE_F22 = 113 SDL_SCANCODE_F23 = 114 SDL_SCANCODE_F24 = 115 SDL_SCANCODE_EXECUTE = 116 SDL_SCANCODE_HELP = 117 SDL_SCANCODE_MENU = 118 SDL_SCANCODE_SELECT = 119 SDL_SCANCODE_STOP = 120 SDL_SCANCODE_AGAIN = 121 SDL_SCANCODE_UNDO = 122 SDL_SCANCODE_CUT = 123 SDL_SCANCODE_COPY = 124 SDL_SCANCODE_PASTE = 125 SDL_SCANCODE_FIND = 126 SDL_SCANCODE_MUTE = 127 SDL_SCANCODE_VOLUMEUP = 128 SDL_SCANCODE_VOLUMEDOWN = 129 SDL_SCANCODE_KP_COMMA = 133 SDL_SCANCODE_KP_EQUALSAS400 = 134 SDL_SCANCODE_INTERNATIONAL1 = 135 SDL_SCANCODE_INTERNATIONAL2 = 136 SDL_SCANCODE_INTERNATIONAL3 = 137 SDL_SCANCODE_INTERNATIONAL4 = 138 SDL_SCANCODE_INTERNATIONAL5 = 139 SDL_SCANCODE_INTERNATIONAL6 = 140 SDL_SCANCODE_INTERNATIONAL7 = 141 SDL_SCANCODE_INTERNATIONAL8 = 142 SDL_SCANCODE_INTERNATIONAL9 = 143 SDL_SCANCODE_LANG1 = 144 SDL_SCANCODE_LANG2 = 145 SDL_SCANCODE_LANG3 = 146 SDL_SCANCODE_LANG4 = 147 SDL_SCANCODE_LANG5 = 148 SDL_SCANCODE_LANG6 = 149 SDL_SCANCODE_LANG7 = 150 SDL_SCANCODE_LANG8 = 151 SDL_SCANCODE_LANG9 = 152 SDL_SCANCODE_ALTERASE = 153 SDL_SCANCODE_SYSREQ = 154 SDL_SCANCODE_CANCEL = 155 SDL_SCANCODE_CLEAR = 156 SDL_SCANCODE_PRIOR = 157 SDL_SCANCODE_RETURN2 = 158 SDL_SCANCODE_SEPARATOR = 159 SDL_SCANCODE_OUT = 160 SDL_SCANCODE_OPER = 161 SDL_SCANCODE_CLEARAGAIN = 162 SDL_SCANCODE_CRSEL = 163 SDL_SCANCODE_EXSEL = 164 SDL_SCANCODE_KP_00 = 176 SDL_SCANCODE_KP_000 = 177 SDL_SCANCODE_THOUSANDSSEPARATOR = 178 SDL_SCANCODE_DECIMALSEPARATOR = 179 SDL_SCANCODE_CURRENCYUNIT = 180 SDL_SCANCODE_CURRENCYSUBUNIT = 181 SDL_SCANCODE_KP_LEFTPAREN = 182 SDL_SCANCODE_KP_RIGHTPAREN = 183 SDL_SCANCODE_KP_LEFTBRACE = 184 SDL_SCANCODE_KP_RIGHTBRACE = 185 SDL_SCANCODE_KP_TAB = 186 SDL_SCANCODE_KP_BACKSPACE = 187 SDL_SCANCODE_KP_A = 188 SDL_SCANCODE_KP_B = 189 SDL_SCANCODE_KP_C = 190 SDL_SCANCODE_KP_D = 191 SDL_SCANCODE_KP_E = 192 SDL_SCANCODE_KP_F = 193 SDL_SCANCODE_KP_XOR = 194 SDL_SCANCODE_KP_POWER = 195 SDL_SCANCODE_KP_PERCENT = 196 SDL_SCANCODE_KP_LESS = 197 SDL_SCANCODE_KP_GREATER = 198 SDL_SCANCODE_KP_AMPERSAND = 199 SDL_SCANCODE_KP_DBLAMPERSAND = 200 SDL_SCANCODE_KP_VERTICALBAR = 201 SDL_SCANCODE_KP_DBLVERTICALBAR = 202 SDL_SCANCODE_KP_COLON = 203 SDL_SCANCODE_KP_HASH = 204 SDL_SCANCODE_KP_SPACE = 205 SDL_SCANCODE_KP_AT = 206 SDL_SCANCODE_KP_EXCLAM = 207 SDL_SCANCODE_KP_MEMSTORE = 208 SDL_SCANCODE_KP_MEMRECALL = 209 SDL_SCANCODE_KP_MEMCLEAR = 210 SDL_SCANCODE_KP_MEMADD = 211 SDL_SCANCODE_KP_MEMSUBTRACT = 212 SDL_SCANCODE_KP_MEMMULTIPLY = 213 SDL_SCANCODE_KP_MEMDIVIDE = 214 SDL_SCANCODE_KP_PLUSMINUS = 215 SDL_SCANCODE_KP_CLEAR = 216 SDL_SCANCODE_KP_CLEARENTRY = 217 SDL_SCANCODE_KP_BINARY = 218 SDL_SCANCODE_KP_OCTAL = 219 SDL_SCANCODE_KP_DECIMAL = 220 SDL_SCANCODE_KP_HEXADECIMAL = 221 SDL_SCANCODE_LCTRL = 224 SDL_SCANCODE_LSHIFT = 225 SDL_SCANCODE_LALT = 226 SDL_SCANCODE_LGUI = 227 SDL_SCANCODE_RCTRL = 228 SDL_SCANCODE_RSHIFT = 229 SDL_SCANCODE_RALT = 230 SDL_SCANCODE_RGUI = 231 SDL_SCANCODE_MODE = 257 SDL_SCANCODE_AUDIONEXT = 258 SDL_SCANCODE_AUDIOPREV = 259 SDL_SCANCODE_AUDIOSTOP = 260 SDL_SCANCODE_AUDIOPLAY = 261 SDL_SCANCODE_AUDIOMUTE = 262 SDL_SCANCODE_MEDIASELECT = 263 SDL_SCANCODE_WWW = 264 SDL_SCANCODE_MAIL = 265 SDL_SCANCODE_CALCULATOR = 266 SDL_SCANCODE_COMPUTER = 267 SDL_SCANCODE_AC_SEARCH = 268 SDL_SCANCODE_AC_HOME = 269 SDL_SCANCODE_AC_BACK = 270 SDL_SCANCODE_AC_FORWARD = 271 SDL_SCANCODE_AC_STOP = 272 SDL_SCANCODE_AC_REFRESH = 273 SDL_SCANCODE_AC_BOOKMARKS = 274 SDL_SCANCODE_BRIGHTNESSDOWN = 275 SDL_SCANCODE_BRIGHTNESSUP = 276 SDL_SCANCODE_DISPLAYSWITCH = 277 SDL_SCANCODE_KBDILLUMTOGGLE = 278 SDL_SCANCODE_KBDILLUMDOWN = 279 SDL_SCANCODE_KBDILLUMUP = 280 SDL_SCANCODE_EJECT = 281 SDL_SCANCODE_SLEEP = 282 SDL_SCANCODE_APP1 = 283 SDL_SCANCODE_APP2 = 284 SDL_SCANCODE_AUDIOREWIND = 285 SDL_SCANCODE_AUDIOFASTFORWARD = 286 SDL_SCANCODE_SOFTLEFT = 287 SDL_SCANCODE_SOFTRIGHT = 288 SDL_SCANCODE_CALL = 289 SDL_SCANCODE_ENDCALL = 290 SDL_NUM_SCANCODES = 512 end const SDL_Keycode = Sint32 @cenum SDL_KeyCode::UInt32 begin SDLK_UNKNOWN = 0 SDLK_RETURN = 13 SDLK_ESCAPE = 27 SDLK_BACKSPACE = 8 SDLK_TAB = 9 SDLK_SPACE = 32 SDLK_EXCLAIM = 33 SDLK_QUOTEDBL = 34 SDLK_HASH = 35 SDLK_PERCENT = 37 SDLK_DOLLAR = 36 SDLK_AMPERSAND = 38 SDLK_QUOTE = 39 SDLK_LEFTPAREN = 40 SDLK_RIGHTPAREN = 41 SDLK_ASTERISK = 42 SDLK_PLUS = 43 SDLK_COMMA = 44 SDLK_MINUS = 45 SDLK_PERIOD = 46 SDLK_SLASH = 47 SDLK_0 = 48 SDLK_1 = 49 SDLK_2 = 50 SDLK_3 = 51 SDLK_4 = 52 SDLK_5 = 53 SDLK_6 = 54 SDLK_7 = 55 SDLK_8 = 56 SDLK_9 = 57 SDLK_COLON = 58 SDLK_SEMICOLON = 59 SDLK_LESS = 60 SDLK_EQUALS = 61 SDLK_GREATER = 62 SDLK_QUESTION = 63 SDLK_AT = 64 SDLK_LEFTBRACKET = 91 SDLK_BACKSLASH = 92 SDLK_RIGHTBRACKET = 93 SDLK_CARET = 94 SDLK_UNDERSCORE = 95 SDLK_BACKQUOTE = 96 SDLK_a = 97 SDLK_b = 98 SDLK_c = 99 SDLK_d = 100 SDLK_e = 101 SDLK_f = 102 SDLK_g = 103 SDLK_h = 104 SDLK_i = 105 SDLK_j = 106 SDLK_k = 107 SDLK_l = 108 SDLK_m = 109 SDLK_n = 110 SDLK_o = 111 SDLK_p = 112 SDLK_q = 113 SDLK_r = 114 SDLK_s = 115 SDLK_t = 116 SDLK_u = 117 SDLK_v = 118 SDLK_w = 119 SDLK_x = 120 SDLK_y = 121 SDLK_z = 122 SDLK_CAPSLOCK = 1073741881 SDLK_F1 = 1073741882 SDLK_F2 = 1073741883 SDLK_F3 = 1073741884 SDLK_F4 = 1073741885 SDLK_F5 = 1073741886 SDLK_F6 = 1073741887 SDLK_F7 = 1073741888 SDLK_F8 = 1073741889 SDLK_F9 = 1073741890 SDLK_F10 = 1073741891 SDLK_F11 = 1073741892 SDLK_F12 = 1073741893 SDLK_PRINTSCREEN = 1073741894 SDLK_SCROLLLOCK = 1073741895 SDLK_PAUSE = 1073741896 SDLK_INSERT = 1073741897 SDLK_HOME = 1073741898 SDLK_PAGEUP = 1073741899 SDLK_DELETE = 127 SDLK_END = 1073741901 SDLK_PAGEDOWN = 1073741902 SDLK_RIGHT = 1073741903 SDLK_LEFT = 1073741904 SDLK_DOWN = 1073741905 SDLK_UP = 1073741906 SDLK_NUMLOCKCLEAR = 1073741907 SDLK_KP_DIVIDE = 1073741908 SDLK_KP_MULTIPLY = 1073741909 SDLK_KP_MINUS = 1073741910 SDLK_KP_PLUS = 1073741911 SDLK_KP_ENTER = 1073741912 SDLK_KP_1 = 1073741913 SDLK_KP_2 = 1073741914 SDLK_KP_3 = 1073741915 SDLK_KP_4 = 1073741916 SDLK_KP_5 = 1073741917 SDLK_KP_6 = 1073741918 SDLK_KP_7 = 1073741919 SDLK_KP_8 = 1073741920 SDLK_KP_9 = 1073741921 SDLK_KP_0 = 1073741922 SDLK_KP_PERIOD = 1073741923 SDLK_APPLICATION = 1073741925 SDLK_POWER = 1073741926 SDLK_KP_EQUALS = 1073741927 SDLK_F13 = 1073741928 SDLK_F14 = 1073741929 SDLK_F15 = 1073741930 SDLK_F16 = 1073741931 SDLK_F17 = 1073741932 SDLK_F18 = 1073741933 SDLK_F19 = 1073741934 SDLK_F20 = 1073741935 SDLK_F21 = 1073741936 SDLK_F22 = 1073741937 SDLK_F23 = 1073741938 SDLK_F24 = 1073741939 SDLK_EXECUTE = 1073741940 SDLK_HELP = 1073741941 SDLK_MENU = 1073741942 SDLK_SELECT = 1073741943 SDLK_STOP = 1073741944 SDLK_AGAIN = 1073741945 SDLK_UNDO = 1073741946 SDLK_CUT = 1073741947 SDLK_COPY = 1073741948 SDLK_PASTE = 1073741949 SDLK_FIND = 1073741950 SDLK_MUTE = 1073741951 SDLK_VOLUMEUP = 1073741952 SDLK_VOLUMEDOWN = 1073741953 SDLK_KP_COMMA = 1073741957 SDLK_KP_EQUALSAS400 = 1073741958 SDLK_ALTERASE = 1073741977 SDLK_SYSREQ = 1073741978 SDLK_CANCEL = 1073741979 SDLK_CLEAR = 1073741980 SDLK_PRIOR = 1073741981 SDLK_RETURN2 = 1073741982 SDLK_SEPARATOR = 1073741983 SDLK_OUT = 1073741984 SDLK_OPER = 1073741985 SDLK_CLEARAGAIN = 1073741986 SDLK_CRSEL = 1073741987 SDLK_EXSEL = 1073741988 SDLK_KP_00 = 1073742000 SDLK_KP_000 = 1073742001 SDLK_THOUSANDSSEPARATOR = 1073742002 SDLK_DECIMALSEPARATOR = 1073742003 SDLK_CURRENCYUNIT = 1073742004 SDLK_CURRENCYSUBUNIT = 1073742005 SDLK_KP_LEFTPAREN = 1073742006 SDLK_KP_RIGHTPAREN = 1073742007 SDLK_KP_LEFTBRACE = 1073742008 SDLK_KP_RIGHTBRACE = 1073742009 SDLK_KP_TAB = 1073742010 SDLK_KP_BACKSPACE = 1073742011 SDLK_KP_A = 1073742012 SDLK_KP_B = 1073742013 SDLK_KP_C = 1073742014 SDLK_KP_D = 1073742015 SDLK_KP_E = 1073742016 SDLK_KP_F = 1073742017 SDLK_KP_XOR = 1073742018 SDLK_KP_POWER = 1073742019 SDLK_KP_PERCENT = 1073742020 SDLK_KP_LESS = 1073742021 SDLK_KP_GREATER = 1073742022 SDLK_KP_AMPERSAND = 1073742023 SDLK_KP_DBLAMPERSAND = 1073742024 SDLK_KP_VERTICALBAR = 1073742025 SDLK_KP_DBLVERTICALBAR = 1073742026 SDLK_KP_COLON = 1073742027 SDLK_KP_HASH = 1073742028 SDLK_KP_SPACE = 1073742029 SDLK_KP_AT = 1073742030 SDLK_KP_EXCLAM = 1073742031 SDLK_KP_MEMSTORE = 1073742032 SDLK_KP_MEMRECALL = 1073742033 SDLK_KP_MEMCLEAR = 1073742034 SDLK_KP_MEMADD = 1073742035 SDLK_KP_MEMSUBTRACT = 1073742036 SDLK_KP_MEMMULTIPLY = 1073742037 SDLK_KP_MEMDIVIDE = 1073742038 SDLK_KP_PLUSMINUS = 1073742039 SDLK_KP_CLEAR = 1073742040 SDLK_KP_CLEARENTRY = 1073742041 SDLK_KP_BINARY = 1073742042 SDLK_KP_OCTAL = 1073742043 SDLK_KP_DECIMAL = 1073742044 SDLK_KP_HEXADECIMAL = 1073742045 SDLK_LCTRL = 1073742048 SDLK_LSHIFT = 1073742049 SDLK_LALT = 1073742050 SDLK_LGUI = 1073742051 SDLK_RCTRL = 1073742052 SDLK_RSHIFT = 1073742053 SDLK_RALT = 1073742054 SDLK_RGUI = 1073742055 SDLK_MODE = 1073742081 SDLK_AUDIONEXT = 1073742082 SDLK_AUDIOPREV = 1073742083 SDLK_AUDIOSTOP = 1073742084 SDLK_AUDIOPLAY = 1073742085 SDLK_AUDIOMUTE = 1073742086 SDLK_MEDIASELECT = 1073742087 SDLK_WWW = 1073742088 SDLK_MAIL = 1073742089 SDLK_CALCULATOR = 1073742090 SDLK_COMPUTER = 1073742091 SDLK_AC_SEARCH = 1073742092 SDLK_AC_HOME = 1073742093 SDLK_AC_BACK = 1073742094 SDLK_AC_FORWARD = 1073742095 SDLK_AC_STOP = 1073742096 SDLK_AC_REFRESH = 1073742097 SDLK_AC_BOOKMARKS = 1073742098 SDLK_BRIGHTNESSDOWN = 1073742099 SDLK_BRIGHTNESSUP = 1073742100 SDLK_DISPLAYSWITCH = 1073742101 SDLK_KBDILLUMTOGGLE = 1073742102 SDLK_KBDILLUMDOWN = 1073742103 SDLK_KBDILLUMUP = 1073742104 SDLK_EJECT = 1073742105 SDLK_SLEEP = 1073742106 SDLK_APP1 = 1073742107 SDLK_APP2 = 1073742108 SDLK_AUDIOREWIND = 1073742109 SDLK_AUDIOFASTFORWARD = 1073742110 SDLK_SOFTLEFT = 1073742111 SDLK_SOFTRIGHT = 1073742112 SDLK_CALL = 1073742113 SDLK_ENDCALL = 1073742114 end @cenum SDL_Keymod::UInt32 begin KMOD_NONE = 0 KMOD_LSHIFT = 1 KMOD_RSHIFT = 2 KMOD_LCTRL = 64 KMOD_RCTRL = 128 KMOD_LALT = 256 KMOD_RALT = 512 KMOD_LGUI = 1024 KMOD_RGUI = 2048 KMOD_NUM = 4096 KMOD_CAPS = 8192 KMOD_MODE = 16384 KMOD_SCROLL = 32768 KMOD_CTRL = 192 KMOD_SHIFT = 3 KMOD_ALT = 768 KMOD_GUI = 3072 KMOD_RESERVED = 32768 end struct SDL_Keysym scancode::SDL_Scancode sym::SDL_Keycode mod::Uint16 unused::Uint32 end function SDL_GetKeyboardFocus() ccall((:SDL_GetKeyboardFocus, libsdl2), Ptr{SDL_Window}, ()) end function SDL_GetKeyboardState(numkeys) ccall((:SDL_GetKeyboardState, libsdl2), Ptr{Uint8}, (Ptr{Cint},), numkeys) end function SDL_ResetKeyboard() ccall((:SDL_ResetKeyboard, libsdl2), Cvoid, ()) end function SDL_GetModState() ccall((:SDL_GetModState, libsdl2), SDL_Keymod, ()) end function SDL_SetModState(modstate) ccall((:SDL_SetModState, libsdl2), Cvoid, (SDL_Keymod,), modstate) end function SDL_GetKeyFromScancode(scancode) ccall((:SDL_GetKeyFromScancode, libsdl2), SDL_Keycode, (SDL_Scancode,), scancode) end function SDL_GetScancodeFromKey(key) ccall((:SDL_GetScancodeFromKey, libsdl2), SDL_Scancode, (SDL_Keycode,), key) end function SDL_GetScancodeName(scancode) ccall((:SDL_GetScancodeName, libsdl2), Ptr{Cchar}, (SDL_Scancode,), scancode) end function SDL_GetScancodeFromName(name) ccall((:SDL_GetScancodeFromName, libsdl2), SDL_Scancode, (Ptr{Cchar},), name) end function SDL_GetKeyName(key) ccall((:SDL_GetKeyName, libsdl2), Ptr{Cchar}, (SDL_Keycode,), key) end function SDL_GetKeyFromName(name) ccall((:SDL_GetKeyFromName, libsdl2), SDL_Keycode, (Ptr{Cchar},), name) end function SDL_StartTextInput() ccall((:SDL_StartTextInput, libsdl2), Cvoid, ()) end function SDL_IsTextInputActive() ccall((:SDL_IsTextInputActive, libsdl2), SDL_bool, ()) end function SDL_StopTextInput() ccall((:SDL_StopTextInput, libsdl2), Cvoid, ()) end function SDL_ClearComposition() ccall((:SDL_ClearComposition, libsdl2), Cvoid, ()) end function SDL_IsTextInputShown() ccall((:SDL_IsTextInputShown, libsdl2), SDL_bool, ()) end function SDL_SetTextInputRect(rect) ccall((:SDL_SetTextInputRect, libsdl2), Cvoid, (Ptr{SDL_Rect},), rect) end function SDL_HasScreenKeyboardSupport() ccall((:SDL_HasScreenKeyboardSupport, libsdl2), SDL_bool, ()) end function SDL_IsScreenKeyboardShown(window) ccall((:SDL_IsScreenKeyboardShown, libsdl2), SDL_bool, (Ptr{SDL_Window},), window) end mutable struct SDL_Cursor end @cenum SDL_SystemCursor::UInt32 begin SDL_SYSTEM_CURSOR_ARROW = 0 SDL_SYSTEM_CURSOR_IBEAM = 1 SDL_SYSTEM_CURSOR_WAIT = 2 SDL_SYSTEM_CURSOR_CROSSHAIR = 3 SDL_SYSTEM_CURSOR_WAITARROW = 4 SDL_SYSTEM_CURSOR_SIZENWSE = 5 SDL_SYSTEM_CURSOR_SIZENESW = 6 SDL_SYSTEM_CURSOR_SIZEWE = 7 SDL_SYSTEM_CURSOR_SIZENS = 8 SDL_SYSTEM_CURSOR_SIZEALL = 9 SDL_SYSTEM_CURSOR_NO = 10 SDL_SYSTEM_CURSOR_HAND = 11 SDL_NUM_SYSTEM_CURSORS = 12 end @cenum SDL_MouseWheelDirection::UInt32 begin SDL_MOUSEWHEEL_NORMAL = 0 SDL_MOUSEWHEEL_FLIPPED = 1 end function SDL_GetMouseFocus() ccall((:SDL_GetMouseFocus, libsdl2), Ptr{SDL_Window}, ()) end function SDL_GetMouseState(x, y) ccall((:SDL_GetMouseState, libsdl2), Uint32, (Ptr{Cint}, Ptr{Cint}), x, y) end function SDL_GetGlobalMouseState(x, y) ccall((:SDL_GetGlobalMouseState, libsdl2), Uint32, (Ptr{Cint}, Ptr{Cint}), x, y) end function SDL_GetRelativeMouseState(x, y) ccall((:SDL_GetRelativeMouseState, libsdl2), Uint32, (Ptr{Cint}, Ptr{Cint}), x, y) end function SDL_WarpMouseInWindow(window, x, y) ccall((:SDL_WarpMouseInWindow, libsdl2), Cvoid, (Ptr{SDL_Window}, Cint, Cint), window, x, y) end function SDL_WarpMouseGlobal(x, y) ccall((:SDL_WarpMouseGlobal, libsdl2), Cint, (Cint, Cint), x, y) end function SDL_SetRelativeMouseMode(enabled) ccall((:SDL_SetRelativeMouseMode, libsdl2), Cint, (SDL_bool,), enabled) end function SDL_CaptureMouse(enabled) ccall((:SDL_CaptureMouse, libsdl2), Cint, (SDL_bool,), enabled) end function SDL_GetRelativeMouseMode() ccall((:SDL_GetRelativeMouseMode, libsdl2), SDL_bool, ()) end function SDL_CreateCursor(data, mask, w, h, hot_x, hot_y) ccall((:SDL_CreateCursor, libsdl2), Ptr{SDL_Cursor}, (Ptr{Uint8}, Ptr{Uint8}, Cint, Cint, Cint, Cint), data, mask, w, h, hot_x, hot_y) end function SDL_CreateColorCursor(surface, hot_x, hot_y) ccall((:SDL_CreateColorCursor, libsdl2), Ptr{SDL_Cursor}, (Ptr{SDL_Surface}, Cint, Cint), surface, hot_x, hot_y) end function SDL_CreateSystemCursor(id) ccall((:SDL_CreateSystemCursor, libsdl2), Ptr{SDL_Cursor}, (SDL_SystemCursor,), id) end function SDL_SetCursor(cursor) ccall((:SDL_SetCursor, libsdl2), Cvoid, (Ptr{SDL_Cursor},), cursor) end function SDL_GetCursor() ccall((:SDL_GetCursor, libsdl2), Ptr{SDL_Cursor}, ()) end function SDL_GetDefaultCursor() ccall((:SDL_GetDefaultCursor, libsdl2), Ptr{SDL_Cursor}, ()) end function SDL_FreeCursor(cursor) ccall((:SDL_FreeCursor, libsdl2), Cvoid, (Ptr{SDL_Cursor},), cursor) end function SDL_ShowCursor(toggle) ccall((:SDL_ShowCursor, libsdl2), Cint, (Cint,), toggle) end struct SDL_GUID data::NTuple{16, Uint8} end function SDL_GUIDToString(guid, pszGUID, cbGUID) ccall((:SDL_GUIDToString, libsdl2), Cvoid, (SDL_GUID, Ptr{Cchar}, Cint), guid, pszGUID, cbGUID) end function SDL_GUIDFromString(pchGUID) ccall((:SDL_GUIDFromString, libsdl2), SDL_GUID, (Ptr{Cchar},), pchGUID) end mutable struct _SDL_Joystick end const SDL_Joystick = _SDL_Joystick const SDL_JoystickGUID = SDL_GUID const SDL_JoystickID = Sint32 @cenum SDL_JoystickType::UInt32 begin SDL_JOYSTICK_TYPE_UNKNOWN = 0 SDL_JOYSTICK_TYPE_GAMECONTROLLER = 1 SDL_JOYSTICK_TYPE_WHEEL = 2 SDL_JOYSTICK_TYPE_ARCADE_STICK = 3 SDL_JOYSTICK_TYPE_FLIGHT_STICK = 4 SDL_JOYSTICK_TYPE_DANCE_PAD = 5 SDL_JOYSTICK_TYPE_GUITAR = 6 SDL_JOYSTICK_TYPE_DRUM_KIT = 7 SDL_JOYSTICK_TYPE_ARCADE_PAD = 8 SDL_JOYSTICK_TYPE_THROTTLE = 9 end @cenum SDL_JoystickPowerLevel::Int32 begin SDL_JOYSTICK_POWER_UNKNOWN = -1 SDL_JOYSTICK_POWER_EMPTY = 0 SDL_JOYSTICK_POWER_LOW = 1 SDL_JOYSTICK_POWER_MEDIUM = 2 SDL_JOYSTICK_POWER_FULL = 3 SDL_JOYSTICK_POWER_WIRED = 4 SDL_JOYSTICK_POWER_MAX = 5 end function SDL_LockJoysticks() ccall((:SDL_LockJoysticks, libsdl2), Cvoid, ()) end function SDL_UnlockJoysticks() ccall((:SDL_UnlockJoysticks, libsdl2), Cvoid, ()) end function SDL_NumJoysticks() ccall((:SDL_NumJoysticks, libsdl2), Cint, ()) end function SDL_JoystickNameForIndex(device_index) ccall((:SDL_JoystickNameForIndex, libsdl2), Ptr{Cchar}, (Cint,), device_index) end function SDL_JoystickPathForIndex(device_index) ccall((:SDL_JoystickPathForIndex, libsdl2), Ptr{Cchar}, (Cint,), device_index) end function SDL_JoystickGetDevicePlayerIndex(device_index) ccall((:SDL_JoystickGetDevicePlayerIndex, libsdl2), Cint, (Cint,), device_index) end function SDL_JoystickGetDeviceGUID(device_index) ccall((:SDL_JoystickGetDeviceGUID, libsdl2), SDL_JoystickGUID, (Cint,), device_index) end function SDL_JoystickGetDeviceVendor(device_index) ccall((:SDL_JoystickGetDeviceVendor, libsdl2), Uint16, (Cint,), device_index) end function SDL_JoystickGetDeviceProduct(device_index) ccall((:SDL_JoystickGetDeviceProduct, libsdl2), Uint16, (Cint,), device_index) end function SDL_JoystickGetDeviceProductVersion(device_index) ccall((:SDL_JoystickGetDeviceProductVersion, libsdl2), Uint16, (Cint,), device_index) end function SDL_JoystickGetDeviceType(device_index) ccall((:SDL_JoystickGetDeviceType, libsdl2), SDL_JoystickType, (Cint,), device_index) end function SDL_JoystickGetDeviceInstanceID(device_index) ccall((:SDL_JoystickGetDeviceInstanceID, libsdl2), SDL_JoystickID, (Cint,), device_index) end function SDL_JoystickOpen(device_index) ccall((:SDL_JoystickOpen, libsdl2), Ptr{SDL_Joystick}, (Cint,), device_index) end function SDL_JoystickFromInstanceID(instance_id) ccall((:SDL_JoystickFromInstanceID, libsdl2), Ptr{SDL_Joystick}, (SDL_JoystickID,), instance_id) end function SDL_JoystickFromPlayerIndex(player_index) ccall((:SDL_JoystickFromPlayerIndex, libsdl2), Ptr{SDL_Joystick}, (Cint,), player_index) end function SDL_JoystickAttachVirtual(type, naxes, nbuttons, nhats) ccall((:SDL_JoystickAttachVirtual, libsdl2), Cint, (SDL_JoystickType, Cint, Cint, Cint), type, naxes, nbuttons, nhats) end struct SDL_VirtualJoystickDesc version::Uint16 type::Uint16 naxes::Uint16 nbuttons::Uint16 nhats::Uint16 vendor_id::Uint16 product_id::Uint16 padding::Uint16 button_mask::Uint32 axis_mask::Uint32 name::Ptr{Cchar} userdata::Ptr{Cvoid} Update::Ptr{Cvoid} SetPlayerIndex::Ptr{Cvoid} Rumble::Ptr{Cvoid} RumbleTriggers::Ptr{Cvoid} SetLED::Ptr{Cvoid} SendEffect::Ptr{Cvoid} end function SDL_JoystickAttachVirtualEx(desc) ccall((:SDL_JoystickAttachVirtualEx, libsdl2), Cint, (Ptr{SDL_VirtualJoystickDesc},), desc) end function SDL_JoystickDetachVirtual(device_index) ccall((:SDL_JoystickDetachVirtual, libsdl2), Cint, (Cint,), device_index) end function SDL_JoystickIsVirtual(device_index) ccall((:SDL_JoystickIsVirtual, libsdl2), SDL_bool, (Cint,), device_index) end function SDL_JoystickSetVirtualAxis(joystick, axis, value) ccall((:SDL_JoystickSetVirtualAxis, libsdl2), Cint, (Ptr{SDL_Joystick}, Cint, Sint16), joystick, axis, value) end function SDL_JoystickSetVirtualButton(joystick, button, value) ccall((:SDL_JoystickSetVirtualButton, libsdl2), Cint, (Ptr{SDL_Joystick}, Cint, Uint8), joystick, button, value) end function SDL_JoystickSetVirtualHat(joystick, hat, value) ccall((:SDL_JoystickSetVirtualHat, libsdl2), Cint, (Ptr{SDL_Joystick}, Cint, Uint8), joystick, hat, value) end function SDL_JoystickName(joystick) ccall((:SDL_JoystickName, libsdl2), Ptr{Cchar}, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickPath(joystick) ccall((:SDL_JoystickPath, libsdl2), Ptr{Cchar}, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickGetPlayerIndex(joystick) ccall((:SDL_JoystickGetPlayerIndex, libsdl2), Cint, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickSetPlayerIndex(joystick, player_index) ccall((:SDL_JoystickSetPlayerIndex, libsdl2), Cvoid, (Ptr{SDL_Joystick}, Cint), joystick, player_index) end function SDL_JoystickGetGUID(joystick) ccall((:SDL_JoystickGetGUID, libsdl2), SDL_JoystickGUID, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickGetVendor(joystick) ccall((:SDL_JoystickGetVendor, libsdl2), Uint16, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickGetProduct(joystick) ccall((:SDL_JoystickGetProduct, libsdl2), Uint16, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickGetProductVersion(joystick) ccall((:SDL_JoystickGetProductVersion, libsdl2), Uint16, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickGetFirmwareVersion(joystick) ccall((:SDL_JoystickGetFirmwareVersion, libsdl2), Uint16, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickGetSerial(joystick) ccall((:SDL_JoystickGetSerial, libsdl2), Ptr{Cchar}, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickGetType(joystick) ccall((:SDL_JoystickGetType, libsdl2), SDL_JoystickType, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickGetGUIDString(guid, pszGUID, cbGUID) ccall((:SDL_JoystickGetGUIDString, libsdl2), Cvoid, (SDL_JoystickGUID, Ptr{Cchar}, Cint), guid, pszGUID, cbGUID) end function SDL_JoystickGetGUIDFromString(pchGUID) ccall((:SDL_JoystickGetGUIDFromString, libsdl2), SDL_JoystickGUID, (Ptr{Cchar},), pchGUID) end function SDL_JoystickGetAttached(joystick) ccall((:SDL_JoystickGetAttached, libsdl2), SDL_bool, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickInstanceID(joystick) ccall((:SDL_JoystickInstanceID, libsdl2), SDL_JoystickID, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickNumAxes(joystick) ccall((:SDL_JoystickNumAxes, libsdl2), Cint, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickNumBalls(joystick) ccall((:SDL_JoystickNumBalls, libsdl2), Cint, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickNumHats(joystick) ccall((:SDL_JoystickNumHats, libsdl2), Cint, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickNumButtons(joystick) ccall((:SDL_JoystickNumButtons, libsdl2), Cint, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickUpdate() ccall((:SDL_JoystickUpdate, libsdl2), Cvoid, ()) end function SDL_JoystickEventState(state) ccall((:SDL_JoystickEventState, libsdl2), Cint, (Cint,), state) end function SDL_JoystickGetAxis(joystick, axis) ccall((:SDL_JoystickGetAxis, libsdl2), Sint16, (Ptr{SDL_Joystick}, Cint), joystick, axis) end function SDL_JoystickGetAxisInitialState(joystick, axis, state) ccall((:SDL_JoystickGetAxisInitialState, libsdl2), SDL_bool, (Ptr{SDL_Joystick}, Cint, Ptr{Sint16}), joystick, axis, state) end function SDL_JoystickGetHat(joystick, hat) ccall((:SDL_JoystickGetHat, libsdl2), Uint8, (Ptr{SDL_Joystick}, Cint), joystick, hat) end function SDL_JoystickGetBall(joystick, ball, dx, dy) ccall((:SDL_JoystickGetBall, libsdl2), Cint, (Ptr{SDL_Joystick}, Cint, Ptr{Cint}, Ptr{Cint}), joystick, ball, dx, dy) end function SDL_JoystickGetButton(joystick, button) ccall((:SDL_JoystickGetButton, libsdl2), Uint8, (Ptr{SDL_Joystick}, Cint), joystick, button) end function SDL_JoystickRumble(joystick, low_frequency_rumble, high_frequency_rumble, duration_ms) ccall((:SDL_JoystickRumble, libsdl2), Cint, (Ptr{SDL_Joystick}, Uint16, Uint16, Uint32), joystick, low_frequency_rumble, high_frequency_rumble, duration_ms) end function SDL_JoystickRumbleTriggers(joystick, left_rumble, right_rumble, duration_ms) ccall((:SDL_JoystickRumbleTriggers, libsdl2), Cint, (Ptr{SDL_Joystick}, Uint16, Uint16, Uint32), joystick, left_rumble, right_rumble, duration_ms) end function SDL_JoystickHasLED(joystick) ccall((:SDL_JoystickHasLED, libsdl2), SDL_bool, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickHasRumble(joystick) ccall((:SDL_JoystickHasRumble, libsdl2), SDL_bool, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickHasRumbleTriggers(joystick) ccall((:SDL_JoystickHasRumbleTriggers, libsdl2), SDL_bool, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickSetLED(joystick, red, green, blue) ccall((:SDL_JoystickSetLED, libsdl2), Cint, (Ptr{SDL_Joystick}, Uint8, Uint8, Uint8), joystick, red, green, blue) end function SDL_JoystickSendEffect(joystick, data, size) ccall((:SDL_JoystickSendEffect, libsdl2), Cint, (Ptr{SDL_Joystick}, Ptr{Cvoid}, Cint), joystick, data, size) end function SDL_JoystickClose(joystick) ccall((:SDL_JoystickClose, libsdl2), Cvoid, (Ptr{SDL_Joystick},), joystick) end function SDL_JoystickCurrentPowerLevel(joystick) ccall((:SDL_JoystickCurrentPowerLevel, libsdl2), SDL_JoystickPowerLevel, (Ptr{SDL_Joystick},), joystick) end mutable struct _SDL_Sensor end const SDL_Sensor = _SDL_Sensor const SDL_SensorID = Sint32 @cenum SDL_SensorType::Int32 begin SDL_SENSOR_INVALID = -1 SDL_SENSOR_UNKNOWN = 0 SDL_SENSOR_ACCEL = 1 SDL_SENSOR_GYRO = 2 end function SDL_LockSensors() ccall((:SDL_LockSensors, libsdl2), Cvoid, ()) end function SDL_UnlockSensors() ccall((:SDL_UnlockSensors, libsdl2), Cvoid, ()) end function SDL_NumSensors() ccall((:SDL_NumSensors, libsdl2), Cint, ()) end function SDL_SensorGetDeviceName(device_index) ccall((:SDL_SensorGetDeviceName, libsdl2), Ptr{Cchar}, (Cint,), device_index) end function SDL_SensorGetDeviceType(device_index) ccall((:SDL_SensorGetDeviceType, libsdl2), SDL_SensorType, (Cint,), device_index) end function SDL_SensorGetDeviceNonPortableType(device_index) ccall((:SDL_SensorGetDeviceNonPortableType, libsdl2), Cint, (Cint,), device_index) end function SDL_SensorGetDeviceInstanceID(device_index) ccall((:SDL_SensorGetDeviceInstanceID, libsdl2), SDL_SensorID, (Cint,), device_index) end function SDL_SensorOpen(device_index) ccall((:SDL_SensorOpen, libsdl2), Ptr{SDL_Sensor}, (Cint,), device_index) end function SDL_SensorFromInstanceID(instance_id) ccall((:SDL_SensorFromInstanceID, libsdl2), Ptr{SDL_Sensor}, (SDL_SensorID,), instance_id) end function SDL_SensorGetName(sensor) ccall((:SDL_SensorGetName, libsdl2), Ptr{Cchar}, (Ptr{SDL_Sensor},), sensor) end function SDL_SensorGetType(sensor) ccall((:SDL_SensorGetType, libsdl2), SDL_SensorType, (Ptr{SDL_Sensor},), sensor) end function SDL_SensorGetNonPortableType(sensor) ccall((:SDL_SensorGetNonPortableType, libsdl2), Cint, (Ptr{SDL_Sensor},), sensor) end function SDL_SensorGetInstanceID(sensor) ccall((:SDL_SensorGetInstanceID, libsdl2), SDL_SensorID, (Ptr{SDL_Sensor},), sensor) end function SDL_SensorGetData(sensor, data, num_values) ccall((:SDL_SensorGetData, libsdl2), Cint, (Ptr{SDL_Sensor}, Ptr{Cfloat}, Cint), sensor, data, num_values) end function SDL_SensorClose(sensor) ccall((:SDL_SensorClose, libsdl2), Cvoid, (Ptr{SDL_Sensor},), sensor) end function SDL_SensorUpdate() ccall((:SDL_SensorUpdate, libsdl2), Cvoid, ()) end mutable struct _SDL_GameController end const SDL_GameController = _SDL_GameController @cenum SDL_GameControllerType::UInt32 begin SDL_CONTROLLER_TYPE_UNKNOWN = 0 SDL_CONTROLLER_TYPE_XBOX360 = 1 SDL_CONTROLLER_TYPE_XBOXONE = 2 SDL_CONTROLLER_TYPE_PS3 = 3 SDL_CONTROLLER_TYPE_PS4 = 4 SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO = 5 SDL_CONTROLLER_TYPE_VIRTUAL = 6 SDL_CONTROLLER_TYPE_PS5 = 7 SDL_CONTROLLER_TYPE_AMAZON_LUNA = 8 SDL_CONTROLLER_TYPE_GOOGLE_STADIA = 9 SDL_CONTROLLER_TYPE_NVIDIA_SHIELD = 10 SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_LEFT = 11 SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT = 12 SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_PAIR = 13 end @cenum SDL_GameControllerBindType::UInt32 begin SDL_CONTROLLER_BINDTYPE_NONE = 0 SDL_CONTROLLER_BINDTYPE_BUTTON = 1 SDL_CONTROLLER_BINDTYPE_AXIS = 2 SDL_CONTROLLER_BINDTYPE_HAT = 3 end struct __JL_Ctag_563 data::NTuple{8, UInt8} end function Base.getproperty(x::Ptr{__JL_Ctag_563}, f::Symbol) f === :button && return Ptr{Cint}(x + 0) f === :axis && return Ptr{Cint}(x + 0) f === :hat && return Ptr{__JL_Ctag_564}(x + 0) return getfield(x, f) end function Base.getproperty(x::__JL_Ctag_563, f::Symbol) r = Ref{__JL_Ctag_563}(x) ptr = Base.unsafe_convert(Ptr{__JL_Ctag_563}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{__JL_Ctag_563}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end struct SDL_GameControllerButtonBind data::NTuple{12, UInt8} end function Base.getproperty(x::Ptr{SDL_GameControllerButtonBind}, f::Symbol) f === :bindType && return Ptr{SDL_GameControllerBindType}(x + 0) f === :value && return Ptr{__JL_Ctag_563}(x + 4) return getfield(x, f) end function Base.getproperty(x::SDL_GameControllerButtonBind, f::Symbol) r = Ref{SDL_GameControllerButtonBind}(x) ptr = Base.unsafe_convert(Ptr{SDL_GameControllerButtonBind}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{SDL_GameControllerButtonBind}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end function SDL_GameControllerAddMapping(mappingString) ccall((:SDL_GameControllerAddMapping, libsdl2), Cint, (Ptr{Cchar},), mappingString) end function SDL_GameControllerNumMappings() ccall((:SDL_GameControllerNumMappings, libsdl2), Cint, ()) end function SDL_GameControllerMappingForIndex(mapping_index) ccall((:SDL_GameControllerMappingForIndex, libsdl2), Ptr{Cchar}, (Cint,), mapping_index) end function SDL_GameControllerMappingForGUID(guid) ccall((:SDL_GameControllerMappingForGUID, libsdl2), Ptr{Cchar}, (SDL_JoystickGUID,), guid) end function SDL_GameControllerMapping(gamecontroller) ccall((:SDL_GameControllerMapping, libsdl2), Ptr{Cchar}, (Ptr{SDL_GameController},), gamecontroller) end function SDL_IsGameController(joystick_index) ccall((:SDL_IsGameController, libsdl2), SDL_bool, (Cint,), joystick_index) end function SDL_GameControllerNameForIndex(joystick_index) ccall((:SDL_GameControllerNameForIndex, libsdl2), Ptr{Cchar}, (Cint,), joystick_index) end function SDL_GameControllerPathForIndex(joystick_index) ccall((:SDL_GameControllerPathForIndex, libsdl2), Ptr{Cchar}, (Cint,), joystick_index) end function SDL_GameControllerTypeForIndex(joystick_index) ccall((:SDL_GameControllerTypeForIndex, libsdl2), SDL_GameControllerType, (Cint,), joystick_index) end function SDL_GameControllerMappingForDeviceIndex(joystick_index) ccall((:SDL_GameControllerMappingForDeviceIndex, libsdl2), Ptr{Cchar}, (Cint,), joystick_index) end function SDL_GameControllerOpen(joystick_index) ccall((:SDL_GameControllerOpen, libsdl2), Ptr{SDL_GameController}, (Cint,), joystick_index) end function SDL_GameControllerFromInstanceID(joyid) ccall((:SDL_GameControllerFromInstanceID, libsdl2), Ptr{SDL_GameController}, (SDL_JoystickID,), joyid) end function SDL_GameControllerFromPlayerIndex(player_index) ccall((:SDL_GameControllerFromPlayerIndex, libsdl2), Ptr{SDL_GameController}, (Cint,), player_index) end function SDL_GameControllerName(gamecontroller) ccall((:SDL_GameControllerName, libsdl2), Ptr{Cchar}, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerPath(gamecontroller) ccall((:SDL_GameControllerPath, libsdl2), Ptr{Cchar}, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerGetType(gamecontroller) ccall((:SDL_GameControllerGetType, libsdl2), SDL_GameControllerType, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerGetPlayerIndex(gamecontroller) ccall((:SDL_GameControllerGetPlayerIndex, libsdl2), Cint, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerSetPlayerIndex(gamecontroller, player_index) ccall((:SDL_GameControllerSetPlayerIndex, libsdl2), Cvoid, (Ptr{SDL_GameController}, Cint), gamecontroller, player_index) end function SDL_GameControllerGetVendor(gamecontroller) ccall((:SDL_GameControllerGetVendor, libsdl2), Uint16, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerGetProduct(gamecontroller) ccall((:SDL_GameControllerGetProduct, libsdl2), Uint16, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerGetProductVersion(gamecontroller) ccall((:SDL_GameControllerGetProductVersion, libsdl2), Uint16, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerGetFirmwareVersion(gamecontroller) ccall((:SDL_GameControllerGetFirmwareVersion, libsdl2), Uint16, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerGetSerial(gamecontroller) ccall((:SDL_GameControllerGetSerial, libsdl2), Ptr{Cchar}, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerGetAttached(gamecontroller) ccall((:SDL_GameControllerGetAttached, libsdl2), SDL_bool, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerGetJoystick(gamecontroller) ccall((:SDL_GameControllerGetJoystick, libsdl2), Ptr{SDL_Joystick}, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerEventState(state) ccall((:SDL_GameControllerEventState, libsdl2), Cint, (Cint,), state) end function SDL_GameControllerUpdate() ccall((:SDL_GameControllerUpdate, libsdl2), Cvoid, ()) end @cenum SDL_GameControllerAxis::Int32 begin SDL_CONTROLLER_AXIS_INVALID = -1 SDL_CONTROLLER_AXIS_LEFTX = 0 SDL_CONTROLLER_AXIS_LEFTY = 1 SDL_CONTROLLER_AXIS_RIGHTX = 2 SDL_CONTROLLER_AXIS_RIGHTY = 3 SDL_CONTROLLER_AXIS_TRIGGERLEFT = 4 SDL_CONTROLLER_AXIS_TRIGGERRIGHT = 5 SDL_CONTROLLER_AXIS_MAX = 6 end function SDL_GameControllerGetAxisFromString(str) ccall((:SDL_GameControllerGetAxisFromString, libsdl2), SDL_GameControllerAxis, (Ptr{Cchar},), str) end function SDL_GameControllerGetStringForAxis(axis) ccall((:SDL_GameControllerGetStringForAxis, libsdl2), Ptr{Cchar}, (SDL_GameControllerAxis,), axis) end function SDL_GameControllerGetBindForAxis(gamecontroller, axis) ccall((:SDL_GameControllerGetBindForAxis, libsdl2), SDL_GameControllerButtonBind, (Ptr{SDL_GameController}, SDL_GameControllerAxis), gamecontroller, axis) end function SDL_GameControllerHasAxis(gamecontroller, axis) ccall((:SDL_GameControllerHasAxis, libsdl2), SDL_bool, (Ptr{SDL_GameController}, SDL_GameControllerAxis), gamecontroller, axis) end function SDL_GameControllerGetAxis(gamecontroller, axis) ccall((:SDL_GameControllerGetAxis, libsdl2), Sint16, (Ptr{SDL_GameController}, SDL_GameControllerAxis), gamecontroller, axis) end @cenum SDL_GameControllerButton::Int32 begin SDL_CONTROLLER_BUTTON_INVALID = -1 SDL_CONTROLLER_BUTTON_A = 0 SDL_CONTROLLER_BUTTON_B = 1 SDL_CONTROLLER_BUTTON_X = 2 SDL_CONTROLLER_BUTTON_Y = 3 SDL_CONTROLLER_BUTTON_BACK = 4 SDL_CONTROLLER_BUTTON_GUIDE = 5 SDL_CONTROLLER_BUTTON_START = 6 SDL_CONTROLLER_BUTTON_LEFTSTICK = 7 SDL_CONTROLLER_BUTTON_RIGHTSTICK = 8 SDL_CONTROLLER_BUTTON_LEFTSHOULDER = 9 SDL_CONTROLLER_BUTTON_RIGHTSHOULDER = 10 SDL_CONTROLLER_BUTTON_DPAD_UP = 11 SDL_CONTROLLER_BUTTON_DPAD_DOWN = 12 SDL_CONTROLLER_BUTTON_DPAD_LEFT = 13 SDL_CONTROLLER_BUTTON_DPAD_RIGHT = 14 SDL_CONTROLLER_BUTTON_MISC1 = 15 SDL_CONTROLLER_BUTTON_PADDLE1 = 16 SDL_CONTROLLER_BUTTON_PADDLE2 = 17 SDL_CONTROLLER_BUTTON_PADDLE3 = 18 SDL_CONTROLLER_BUTTON_PADDLE4 = 19 SDL_CONTROLLER_BUTTON_TOUCHPAD = 20 SDL_CONTROLLER_BUTTON_MAX = 21 end function SDL_GameControllerGetButtonFromString(str) ccall((:SDL_GameControllerGetButtonFromString, libsdl2), SDL_GameControllerButton, (Ptr{Cchar},), str) end function SDL_GameControllerGetStringForButton(button) ccall((:SDL_GameControllerGetStringForButton, libsdl2), Ptr{Cchar}, (SDL_GameControllerButton,), button) end function SDL_GameControllerGetBindForButton(gamecontroller, button) ccall((:SDL_GameControllerGetBindForButton, libsdl2), SDL_GameControllerButtonBind, (Ptr{SDL_GameController}, SDL_GameControllerButton), gamecontroller, button) end function SDL_GameControllerHasButton(gamecontroller, button) ccall((:SDL_GameControllerHasButton, libsdl2), SDL_bool, (Ptr{SDL_GameController}, SDL_GameControllerButton), gamecontroller, button) end function SDL_GameControllerGetButton(gamecontroller, button) ccall((:SDL_GameControllerGetButton, libsdl2), Uint8, (Ptr{SDL_GameController}, SDL_GameControllerButton), gamecontroller, button) end function SDL_GameControllerGetNumTouchpads(gamecontroller) ccall((:SDL_GameControllerGetNumTouchpads, libsdl2), Cint, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerGetNumTouchpadFingers(gamecontroller, touchpad) ccall((:SDL_GameControllerGetNumTouchpadFingers, libsdl2), Cint, (Ptr{SDL_GameController}, Cint), gamecontroller, touchpad) end function SDL_GameControllerGetTouchpadFinger(gamecontroller, touchpad, finger, state, x, y, pressure) ccall((:SDL_GameControllerGetTouchpadFinger, libsdl2), Cint, (Ptr{SDL_GameController}, Cint, Cint, Ptr{Uint8}, Ptr{Cfloat}, Ptr{Cfloat}, Ptr{Cfloat}), gamecontroller, touchpad, finger, state, x, y, pressure) end function SDL_GameControllerHasSensor(gamecontroller, type) ccall((:SDL_GameControllerHasSensor, libsdl2), SDL_bool, (Ptr{SDL_GameController}, SDL_SensorType), gamecontroller, type) end function SDL_GameControllerSetSensorEnabled(gamecontroller, type, enabled) ccall((:SDL_GameControllerSetSensorEnabled, libsdl2), Cint, (Ptr{SDL_GameController}, SDL_SensorType, SDL_bool), gamecontroller, type, enabled) end function SDL_GameControllerIsSensorEnabled(gamecontroller, type) ccall((:SDL_GameControllerIsSensorEnabled, libsdl2), SDL_bool, (Ptr{SDL_GameController}, SDL_SensorType), gamecontroller, type) end function SDL_GameControllerGetSensorDataRate(gamecontroller, type) ccall((:SDL_GameControllerGetSensorDataRate, libsdl2), Cfloat, (Ptr{SDL_GameController}, SDL_SensorType), gamecontroller, type) end function SDL_GameControllerGetSensorData(gamecontroller, type, data, num_values) ccall((:SDL_GameControllerGetSensorData, libsdl2), Cint, (Ptr{SDL_GameController}, SDL_SensorType, Ptr{Cfloat}, Cint), gamecontroller, type, data, num_values) end function SDL_GameControllerRumble(gamecontroller, low_frequency_rumble, high_frequency_rumble, duration_ms) ccall((:SDL_GameControllerRumble, libsdl2), Cint, (Ptr{SDL_GameController}, Uint16, Uint16, Uint32), gamecontroller, low_frequency_rumble, high_frequency_rumble, duration_ms) end function SDL_GameControllerRumbleTriggers(gamecontroller, left_rumble, right_rumble, duration_ms) ccall((:SDL_GameControllerRumbleTriggers, libsdl2), Cint, (Ptr{SDL_GameController}, Uint16, Uint16, Uint32), gamecontroller, left_rumble, right_rumble, duration_ms) end function SDL_GameControllerHasLED(gamecontroller) ccall((:SDL_GameControllerHasLED, libsdl2), SDL_bool, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerHasRumble(gamecontroller) ccall((:SDL_GameControllerHasRumble, libsdl2), SDL_bool, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerHasRumbleTriggers(gamecontroller) ccall((:SDL_GameControllerHasRumbleTriggers, libsdl2), SDL_bool, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerSetLED(gamecontroller, red, green, blue) ccall((:SDL_GameControllerSetLED, libsdl2), Cint, (Ptr{SDL_GameController}, Uint8, Uint8, Uint8), gamecontroller, red, green, blue) end function SDL_GameControllerSendEffect(gamecontroller, data, size) ccall((:SDL_GameControllerSendEffect, libsdl2), Cint, (Ptr{SDL_GameController}, Ptr{Cvoid}, Cint), gamecontroller, data, size) end function SDL_GameControllerClose(gamecontroller) ccall((:SDL_GameControllerClose, libsdl2), Cvoid, (Ptr{SDL_GameController},), gamecontroller) end function SDL_GameControllerGetAppleSFSymbolsNameForButton(gamecontroller, button) ccall((:SDL_GameControllerGetAppleSFSymbolsNameForButton, libsdl2), Ptr{Cchar}, (Ptr{SDL_GameController}, SDL_GameControllerButton), gamecontroller, button) end function SDL_GameControllerGetAppleSFSymbolsNameForAxis(gamecontroller, axis) ccall((:SDL_GameControllerGetAppleSFSymbolsNameForAxis, libsdl2), Ptr{Cchar}, (Ptr{SDL_GameController}, SDL_GameControllerAxis), gamecontroller, axis) end const SDL_TouchID = Sint64 const SDL_FingerID = Sint64 @cenum SDL_TouchDeviceType::Int32 begin SDL_TOUCH_DEVICE_INVALID = -1 SDL_TOUCH_DEVICE_DIRECT = 0 SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE = 1 SDL_TOUCH_DEVICE_INDIRECT_RELATIVE = 2 end struct SDL_Finger id::SDL_FingerID x::Cfloat y::Cfloat pressure::Cfloat end function SDL_GetNumTouchDevices() ccall((:SDL_GetNumTouchDevices, libsdl2), Cint, ()) end function SDL_GetTouchDevice(index) ccall((:SDL_GetTouchDevice, libsdl2), SDL_TouchID, (Cint,), index) end function SDL_GetTouchName(index) ccall((:SDL_GetTouchName, libsdl2), Ptr{Cchar}, (Cint,), index) end function SDL_GetTouchDeviceType(touchID) ccall((:SDL_GetTouchDeviceType, libsdl2), SDL_TouchDeviceType, (SDL_TouchID,), touchID) end function SDL_GetNumTouchFingers(touchID) ccall((:SDL_GetNumTouchFingers, libsdl2), Cint, (SDL_TouchID,), touchID) end function SDL_GetTouchFinger(touchID, index) ccall((:SDL_GetTouchFinger, libsdl2), Ptr{SDL_Finger}, (SDL_TouchID, Cint), touchID, index) end const SDL_GestureID = Sint64 function SDL_RecordGesture(touchId) ccall((:SDL_RecordGesture, libsdl2), Cint, (SDL_TouchID,), touchId) end function SDL_SaveAllDollarTemplates(dst) ccall((:SDL_SaveAllDollarTemplates, libsdl2), Cint, (Ptr{SDL_RWops},), dst) end function SDL_SaveDollarTemplate(gestureId, dst) ccall((:SDL_SaveDollarTemplate, libsdl2), Cint, (SDL_GestureID, Ptr{SDL_RWops}), gestureId, dst) end function SDL_LoadDollarTemplates(touchId, src) ccall((:SDL_LoadDollarTemplates, libsdl2), Cint, (SDL_TouchID, Ptr{SDL_RWops}), touchId, src) end @cenum SDL_EventType::UInt32 begin SDL_FIRSTEVENT = 0 SDL_QUIT = 256 SDL_APP_TERMINATING = 257 SDL_APP_LOWMEMORY = 258 SDL_APP_WILLENTERBACKGROUND = 259 SDL_APP_DIDENTERBACKGROUND = 260 SDL_APP_WILLENTERFOREGROUND = 261 SDL_APP_DIDENTERFOREGROUND = 262 SDL_LOCALECHANGED = 263 SDL_DISPLAYEVENT = 336 SDL_WINDOWEVENT = 512 SDL_SYSWMEVENT = 513 SDL_KEYDOWN = 768 SDL_KEYUP = 769 SDL_TEXTEDITING = 770 SDL_TEXTINPUT = 771 SDL_KEYMAPCHANGED = 772 SDL_TEXTEDITING_EXT = 773 SDL_MOUSEMOTION = 1024 SDL_MOUSEBUTTONDOWN = 1025 SDL_MOUSEBUTTONUP = 1026 SDL_MOUSEWHEEL = 1027 SDL_JOYAXISMOTION = 1536 SDL_JOYBALLMOTION = 1537 SDL_JOYHATMOTION = 1538 SDL_JOYBUTTONDOWN = 1539 SDL_JOYBUTTONUP = 1540 SDL_JOYDEVICEADDED = 1541 SDL_JOYDEVICEREMOVED = 1542 SDL_JOYBATTERYUPDATED = 1543 SDL_CONTROLLERAXISMOTION = 1616 SDL_CONTROLLERBUTTONDOWN = 1617 SDL_CONTROLLERBUTTONUP = 1618 SDL_CONTROLLERDEVICEADDED = 1619 SDL_CONTROLLERDEVICEREMOVED = 1620 SDL_CONTROLLERDEVICEREMAPPED = 1621 SDL_CONTROLLERTOUCHPADDOWN = 1622 SDL_CONTROLLERTOUCHPADMOTION = 1623 SDL_CONTROLLERTOUCHPADUP = 1624 SDL_CONTROLLERSENSORUPDATE = 1625 SDL_FINGERDOWN = 1792 SDL_FINGERUP = 1793 SDL_FINGERMOTION = 1794 SDL_DOLLARGESTURE = 2048 SDL_DOLLARRECORD = 2049 SDL_MULTIGESTURE = 2050 SDL_CLIPBOARDUPDATE = 2304 SDL_DROPFILE = 4096 SDL_DROPTEXT = 4097 SDL_DROPBEGIN = 4098 SDL_DROPCOMPLETE = 4099 SDL_AUDIODEVICEADDED = 4352 SDL_AUDIODEVICEREMOVED = 4353 SDL_SENSORUPDATE = 4608 SDL_RENDER_TARGETS_RESET = 8192 SDL_RENDER_DEVICE_RESET = 8193 SDL_POLLSENTINEL = 32512 SDL_USEREVENT = 32768 SDL_LASTEVENT = 65535 end struct SDL_CommonEvent type::Uint32 timestamp::Uint32 end struct SDL_DisplayEvent type::Uint32 timestamp::Uint32 display::Uint32 event::Uint8 padding1::Uint8 padding2::Uint8 padding3::Uint8 data1::Sint32 end struct SDL_WindowEvent type::Uint32 timestamp::Uint32 windowID::Uint32 event::Uint8 padding1::Uint8 padding2::Uint8 padding3::Uint8 data1::Sint32 data2::Sint32 end struct SDL_KeyboardEvent type::Uint32 timestamp::Uint32 windowID::Uint32 state::Uint8 repeat::Uint8 padding2::Uint8 padding3::Uint8 keysym::SDL_Keysym end struct SDL_TextEditingEvent type::Uint32 timestamp::Uint32 windowID::Uint32 text::NTuple{32, Cchar} start::Sint32 length::Sint32 end struct SDL_TextEditingExtEvent type::Uint32 timestamp::Uint32 windowID::Uint32 text::Ptr{Cchar} start::Sint32 length::Sint32 end struct SDL_TextInputEvent type::Uint32 timestamp::Uint32 windowID::Uint32 text::NTuple{32, Cchar} end struct SDL_MouseMotionEvent type::Uint32 timestamp::Uint32 windowID::Uint32 which::Uint32 state::Uint32 x::Sint32 y::Sint32 xrel::Sint32 yrel::Sint32 end struct SDL_MouseButtonEvent type::Uint32 timestamp::Uint32 windowID::Uint32 which::Uint32 button::Uint8 state::Uint8 clicks::Uint8 padding1::Uint8 x::Sint32 y::Sint32 end struct SDL_MouseWheelEvent type::Uint32 timestamp::Uint32 windowID::Uint32 which::Uint32 x::Sint32 y::Sint32 direction::Uint32 preciseX::Cfloat preciseY::Cfloat end struct SDL_JoyAxisEvent type::Uint32 timestamp::Uint32 which::SDL_JoystickID axis::Uint8 padding1::Uint8 padding2::Uint8 padding3::Uint8 value::Sint16 padding4::Uint16 end struct SDL_JoyBallEvent type::Uint32 timestamp::Uint32 which::SDL_JoystickID ball::Uint8 padding1::Uint8 padding2::Uint8 padding3::Uint8 xrel::Sint16 yrel::Sint16 end struct SDL_JoyHatEvent type::Uint32 timestamp::Uint32 which::SDL_JoystickID hat::Uint8 value::Uint8 padding1::Uint8 padding2::Uint8 end struct SDL_JoyButtonEvent type::Uint32 timestamp::Uint32 which::SDL_JoystickID button::Uint8 state::Uint8 padding1::Uint8 padding2::Uint8 end struct SDL_JoyDeviceEvent type::Uint32 timestamp::Uint32 which::Sint32 end struct SDL_JoyBatteryEvent type::Uint32 timestamp::Uint32 which::SDL_JoystickID level::SDL_JoystickPowerLevel end struct SDL_ControllerAxisEvent type::Uint32 timestamp::Uint32 which::SDL_JoystickID axis::Uint8 padding1::Uint8 padding2::Uint8 padding3::Uint8 value::Sint16 padding4::Uint16 end struct SDL_ControllerButtonEvent type::Uint32 timestamp::Uint32 which::SDL_JoystickID button::Uint8 state::Uint8 padding1::Uint8 padding2::Uint8 end struct SDL_ControllerDeviceEvent type::Uint32 timestamp::Uint32 which::Sint32 end struct SDL_ControllerTouchpadEvent type::Uint32 timestamp::Uint32 which::SDL_JoystickID touchpad::Sint32 finger::Sint32 x::Cfloat y::Cfloat pressure::Cfloat end struct SDL_ControllerSensorEvent type::Uint32 timestamp::Uint32 which::SDL_JoystickID sensor::Sint32 data::NTuple{3, Cfloat} end struct SDL_AudioDeviceEvent type::Uint32 timestamp::Uint32 which::Uint32 iscapture::Uint8 padding1::Uint8 padding2::Uint8 padding3::Uint8 end struct SDL_TouchFingerEvent type::Uint32 timestamp::Uint32 touchId::SDL_TouchID fingerId::SDL_FingerID x::Cfloat y::Cfloat dx::Cfloat dy::Cfloat pressure::Cfloat windowID::Uint32 end struct SDL_MultiGestureEvent type::Uint32 timestamp::Uint32 touchId::SDL_TouchID dTheta::Cfloat dDist::Cfloat x::Cfloat y::Cfloat numFingers::Uint16 padding::Uint16 end struct SDL_DollarGestureEvent type::Uint32 timestamp::Uint32 touchId::SDL_TouchID gestureId::SDL_GestureID numFingers::Uint32 error::Cfloat x::Cfloat y::Cfloat end struct SDL_DropEvent type::Uint32 timestamp::Uint32 file::Ptr{Cchar} windowID::Uint32 end struct SDL_SensorEvent type::Uint32 timestamp::Uint32 which::Sint32 data::NTuple{6, Cfloat} end struct SDL_QuitEvent type::Uint32 timestamp::Uint32 end struct SDL_OSEvent type::Uint32 timestamp::Uint32 end struct SDL_UserEvent type::Uint32 timestamp::Uint32 windowID::Uint32 code::Sint32 data1::Ptr{Cvoid} data2::Ptr{Cvoid} end mutable struct SDL_SysWMmsg end struct SDL_SysWMEvent type::Uint32 timestamp::Uint32 msg::Ptr{SDL_SysWMmsg} end function SDL_HasEvent(type) ccall((:SDL_HasEvent, libsdl2), SDL_bool, (Uint32,), type) end function SDL_HasEvents(minType, maxType) ccall((:SDL_HasEvents, libsdl2), SDL_bool, (Uint32, Uint32), minType, maxType) end function SDL_FlushEvent(type) ccall((:SDL_FlushEvent, libsdl2), Cvoid, (Uint32,), type) end function SDL_FlushEvents(minType, maxType) ccall((:SDL_FlushEvents, libsdl2), Cvoid, (Uint32, Uint32), minType, maxType) end function SDL_PollEvent(event) ccall((:SDL_PollEvent, libsdl2), Cint, (Ptr{SDL_Event},), event) end function SDL_WaitEvent(event) ccall((:SDL_WaitEvent, libsdl2), Cint, (Ptr{SDL_Event},), event) end function SDL_WaitEventTimeout(event, timeout) ccall((:SDL_WaitEventTimeout, libsdl2), Cint, (Ptr{SDL_Event}, Cint), event, timeout) end function SDL_PushEvent(event) ccall((:SDL_PushEvent, libsdl2), Cint, (Ptr{SDL_Event},), event) end # typedef int ( SDLCALL * SDL_EventFilter ) ( void * userdata , SDL_Event * event ) const SDL_EventFilter = Ptr{Cvoid} function SDL_SetEventFilter(filter, userdata) ccall((:SDL_SetEventFilter, libsdl2), Cvoid, (SDL_EventFilter, Ptr{Cvoid}), filter, userdata) end function SDL_GetEventFilter(filter, userdata) ccall((:SDL_GetEventFilter, libsdl2), SDL_bool, (Ptr{SDL_EventFilter}, Ptr{Ptr{Cvoid}}), filter, userdata) end function SDL_AddEventWatch(filter, userdata) ccall((:SDL_AddEventWatch, libsdl2), Cvoid, (SDL_EventFilter, Ptr{Cvoid}), filter, userdata) end function SDL_DelEventWatch(filter, userdata) ccall((:SDL_DelEventWatch, libsdl2), Cvoid, (SDL_EventFilter, Ptr{Cvoid}), filter, userdata) end function SDL_FilterEvents(filter, userdata) ccall((:SDL_FilterEvents, libsdl2), Cvoid, (SDL_EventFilter, Ptr{Cvoid}), filter, userdata) end function SDL_RegisterEvents(numevents) ccall((:SDL_RegisterEvents, libsdl2), Uint32, (Cint,), numevents) end function SDL_GetBasePath() ccall((:SDL_GetBasePath, libsdl2), Ptr{Cchar}, ()) end function SDL_GetPrefPath(org, app) ccall((:SDL_GetPrefPath, libsdl2), Ptr{Cchar}, (Ptr{Cchar}, Ptr{Cchar}), org, app) end mutable struct _SDL_Haptic end const SDL_Haptic = _SDL_Haptic struct SDL_HapticDirection type::Uint8 dir::NTuple{3, Sint32} end struct SDL_HapticConstant type::Uint16 direction::SDL_HapticDirection length::Uint32 delay::Uint16 button::Uint16 interval::Uint16 level::Sint16 attack_length::Uint16 attack_level::Uint16 fade_length::Uint16 fade_level::Uint16 end struct SDL_HapticPeriodic type::Uint16 direction::SDL_HapticDirection length::Uint32 delay::Uint16 button::Uint16 interval::Uint16 period::Uint16 magnitude::Sint16 offset::Sint16 phase::Uint16 attack_length::Uint16 attack_level::Uint16 fade_length::Uint16 fade_level::Uint16 end struct SDL_HapticCondition type::Uint16 direction::SDL_HapticDirection length::Uint32 delay::Uint16 button::Uint16 interval::Uint16 right_sat::NTuple{3, Uint16} left_sat::NTuple{3, Uint16} right_coeff::NTuple{3, Sint16} left_coeff::NTuple{3, Sint16} deadband::NTuple{3, Uint16} center::NTuple{3, Sint16} end struct SDL_HapticRamp type::Uint16 direction::SDL_HapticDirection length::Uint32 delay::Uint16 button::Uint16 interval::Uint16 start::Sint16 _end::Sint16 attack_length::Uint16 attack_level::Uint16 fade_length::Uint16 fade_level::Uint16 end struct SDL_HapticLeftRight type::Uint16 length::Uint32 large_magnitude::Uint16 small_magnitude::Uint16 end struct SDL_HapticCustom type::Uint16 direction::SDL_HapticDirection length::Uint32 delay::Uint16 button::Uint16 interval::Uint16 channels::Uint8 period::Uint16 samples::Uint16 data::Ptr{Uint16} attack_length::Uint16 attack_level::Uint16 fade_length::Uint16 fade_level::Uint16 end struct SDL_HapticEffect data::NTuple{72, UInt8} end function Base.getproperty(x::Ptr{SDL_HapticEffect}, f::Symbol) f === :type && return Ptr{Uint16}(x + 0) f === :constant && return Ptr{SDL_HapticConstant}(x + 0) f === :periodic && return Ptr{SDL_HapticPeriodic}(x + 0) f === :condition && return Ptr{SDL_HapticCondition}(x + 0) f === :ramp && return Ptr{SDL_HapticRamp}(x + 0) f === :leftright && return Ptr{SDL_HapticLeftRight}(x + 0) f === :custom && return Ptr{SDL_HapticCustom}(x + 0) return getfield(x, f) end function Base.getproperty(x::SDL_HapticEffect, f::Symbol) r = Ref{SDL_HapticEffect}(x) ptr = Base.unsafe_convert(Ptr{SDL_HapticEffect}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{SDL_HapticEffect}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end function SDL_NumHaptics() ccall((:SDL_NumHaptics, libsdl2), Cint, ()) end function SDL_HapticName(device_index) ccall((:SDL_HapticName, libsdl2), Ptr{Cchar}, (Cint,), device_index) end function SDL_HapticOpen(device_index) ccall((:SDL_HapticOpen, libsdl2), Ptr{SDL_Haptic}, (Cint,), device_index) end function SDL_HapticOpened(device_index) ccall((:SDL_HapticOpened, libsdl2), Cint, (Cint,), device_index) end function SDL_HapticIndex(haptic) ccall((:SDL_HapticIndex, libsdl2), Cint, (Ptr{SDL_Haptic},), haptic) end function SDL_MouseIsHaptic() ccall((:SDL_MouseIsHaptic, libsdl2), Cint, ()) end function SDL_HapticOpenFromMouse() ccall((:SDL_HapticOpenFromMouse, libsdl2), Ptr{SDL_Haptic}, ()) end function SDL_JoystickIsHaptic(joystick) ccall((:SDL_JoystickIsHaptic, libsdl2), Cint, (Ptr{SDL_Joystick},), joystick) end function SDL_HapticOpenFromJoystick(joystick) ccall((:SDL_HapticOpenFromJoystick, libsdl2), Ptr{SDL_Haptic}, (Ptr{SDL_Joystick},), joystick) end function SDL_HapticClose(haptic) ccall((:SDL_HapticClose, libsdl2), Cvoid, (Ptr{SDL_Haptic},), haptic) end function SDL_HapticNumEffects(haptic) ccall((:SDL_HapticNumEffects, libsdl2), Cint, (Ptr{SDL_Haptic},), haptic) end function SDL_HapticNumEffectsPlaying(haptic) ccall((:SDL_HapticNumEffectsPlaying, libsdl2), Cint, (Ptr{SDL_Haptic},), haptic) end function SDL_HapticQuery(haptic) ccall((:SDL_HapticQuery, libsdl2), Cuint, (Ptr{SDL_Haptic},), haptic) end function SDL_HapticNumAxes(haptic) ccall((:SDL_HapticNumAxes, libsdl2), Cint, (Ptr{SDL_Haptic},), haptic) end function SDL_HapticEffectSupported(haptic, effect) ccall((:SDL_HapticEffectSupported, libsdl2), Cint, (Ptr{SDL_Haptic}, Ptr{SDL_HapticEffect}), haptic, effect) end function SDL_HapticNewEffect(haptic, effect) ccall((:SDL_HapticNewEffect, libsdl2), Cint, (Ptr{SDL_Haptic}, Ptr{SDL_HapticEffect}), haptic, effect) end function SDL_HapticUpdateEffect(haptic, effect, data) ccall((:SDL_HapticUpdateEffect, libsdl2), Cint, (Ptr{SDL_Haptic}, Cint, Ptr{SDL_HapticEffect}), haptic, effect, data) end function SDL_HapticRunEffect(haptic, effect, iterations) ccall((:SDL_HapticRunEffect, libsdl2), Cint, (Ptr{SDL_Haptic}, Cint, Uint32), haptic, effect, iterations) end function SDL_HapticStopEffect(haptic, effect) ccall((:SDL_HapticStopEffect, libsdl2), Cint, (Ptr{SDL_Haptic}, Cint), haptic, effect) end function SDL_HapticDestroyEffect(haptic, effect) ccall((:SDL_HapticDestroyEffect, libsdl2), Cvoid, (Ptr{SDL_Haptic}, Cint), haptic, effect) end function SDL_HapticGetEffectStatus(haptic, effect) ccall((:SDL_HapticGetEffectStatus, libsdl2), Cint, (Ptr{SDL_Haptic}, Cint), haptic, effect) end function SDL_HapticSetGain(haptic, gain) ccall((:SDL_HapticSetGain, libsdl2), Cint, (Ptr{SDL_Haptic}, Cint), haptic, gain) end function SDL_HapticSetAutocenter(haptic, autocenter) ccall((:SDL_HapticSetAutocenter, libsdl2), Cint, (Ptr{SDL_Haptic}, Cint), haptic, autocenter) end function SDL_HapticPause(haptic) ccall((:SDL_HapticPause, libsdl2), Cint, (Ptr{SDL_Haptic},), haptic) end function SDL_HapticUnpause(haptic) ccall((:SDL_HapticUnpause, libsdl2), Cint, (Ptr{SDL_Haptic},), haptic) end function SDL_HapticStopAll(haptic) ccall((:SDL_HapticStopAll, libsdl2), Cint, (Ptr{SDL_Haptic},), haptic) end function SDL_HapticRumbleSupported(haptic) ccall((:SDL_HapticRumbleSupported, libsdl2), Cint, (Ptr{SDL_Haptic},), haptic) end function SDL_HapticRumbleInit(haptic) ccall((:SDL_HapticRumbleInit, libsdl2), Cint, (Ptr{SDL_Haptic},), haptic) end function SDL_HapticRumblePlay(haptic, strength, length) ccall((:SDL_HapticRumblePlay, libsdl2), Cint, (Ptr{SDL_Haptic}, Cfloat, Uint32), haptic, strength, length) end function SDL_HapticRumbleStop(haptic) ccall((:SDL_HapticRumbleStop, libsdl2), Cint, (Ptr{SDL_Haptic},), haptic) end mutable struct SDL_hid_device_ end const SDL_hid_device = SDL_hid_device_ struct SDL_hid_device_info path::Ptr{Cchar} vendor_id::Cushort product_id::Cushort serial_number::Ptr{Cwchar_t} release_number::Cushort manufacturer_string::Ptr{Cwchar_t} product_string::Ptr{Cwchar_t} usage_page::Cushort usage::Cushort interface_number::Cint interface_class::Cint interface_subclass::Cint interface_protocol::Cint next::Ptr{SDL_hid_device_info} end function SDL_hid_init() ccall((:SDL_hid_init, libsdl2), Cint, ()) end function SDL_hid_exit() ccall((:SDL_hid_exit, libsdl2), Cint, ()) end function SDL_hid_device_change_count() ccall((:SDL_hid_device_change_count, libsdl2), Uint32, ()) end function SDL_hid_enumerate(vendor_id, product_id) ccall((:SDL_hid_enumerate, libsdl2), Ptr{SDL_hid_device_info}, (Cushort, Cushort), vendor_id, product_id) end function SDL_hid_free_enumeration(devs) ccall((:SDL_hid_free_enumeration, libsdl2), Cvoid, (Ptr{SDL_hid_device_info},), devs) end function SDL_hid_open(vendor_id, product_id, serial_number) ccall((:SDL_hid_open, libsdl2), Ptr{SDL_hid_device}, (Cushort, Cushort, Ptr{Cwchar_t}), vendor_id, product_id, serial_number) end function SDL_hid_open_path(path, bExclusive) ccall((:SDL_hid_open_path, libsdl2), Ptr{SDL_hid_device}, (Ptr{Cchar}, Cint), path, bExclusive) end function SDL_hid_write(dev, data, length) ccall((:SDL_hid_write, libsdl2), Cint, (Ptr{SDL_hid_device}, Ptr{Cuchar}, Csize_t), dev, data, length) end function SDL_hid_read_timeout(dev, data, length, milliseconds) ccall((:SDL_hid_read_timeout, libsdl2), Cint, (Ptr{SDL_hid_device}, Ptr{Cuchar}, Csize_t, Cint), dev, data, length, milliseconds) end function SDL_hid_read(dev, data, length) ccall((:SDL_hid_read, libsdl2), Cint, (Ptr{SDL_hid_device}, Ptr{Cuchar}, Csize_t), dev, data, length) end function SDL_hid_set_nonblocking(dev, nonblock) ccall((:SDL_hid_set_nonblocking, libsdl2), Cint, (Ptr{SDL_hid_device}, Cint), dev, nonblock) end function SDL_hid_send_feature_report(dev, data, length) ccall((:SDL_hid_send_feature_report, libsdl2), Cint, (Ptr{SDL_hid_device}, Ptr{Cuchar}, Csize_t), dev, data, length) end function SDL_hid_get_feature_report(dev, data, length) ccall((:SDL_hid_get_feature_report, libsdl2), Cint, (Ptr{SDL_hid_device}, Ptr{Cuchar}, Csize_t), dev, data, length) end function SDL_hid_close(dev) ccall((:SDL_hid_close, libsdl2), Cvoid, (Ptr{SDL_hid_device},), dev) end function SDL_hid_get_manufacturer_string(dev, string, maxlen) ccall((:SDL_hid_get_manufacturer_string, libsdl2), Cint, (Ptr{SDL_hid_device}, Ptr{Cwchar_t}, Csize_t), dev, string, maxlen) end function SDL_hid_get_product_string(dev, string, maxlen) ccall((:SDL_hid_get_product_string, libsdl2), Cint, (Ptr{SDL_hid_device}, Ptr{Cwchar_t}, Csize_t), dev, string, maxlen) end function SDL_hid_get_serial_number_string(dev, string, maxlen) ccall((:SDL_hid_get_serial_number_string, libsdl2), Cint, (Ptr{SDL_hid_device}, Ptr{Cwchar_t}, Csize_t), dev, string, maxlen) end function SDL_hid_get_indexed_string(dev, string_index, string, maxlen) ccall((:SDL_hid_get_indexed_string, libsdl2), Cint, (Ptr{SDL_hid_device}, Cint, Ptr{Cwchar_t}, Csize_t), dev, string_index, string, maxlen) end function SDL_hid_ble_scan(active) ccall((:SDL_hid_ble_scan, libsdl2), Cvoid, (SDL_bool,), active) end @cenum SDL_HintPriority::UInt32 begin SDL_HINT_DEFAULT = 0 SDL_HINT_NORMAL = 1 SDL_HINT_OVERRIDE = 2 end function SDL_SetHintWithPriority(name, value, priority) ccall((:SDL_SetHintWithPriority, libsdl2), SDL_bool, (Ptr{Cchar}, Ptr{Cchar}, SDL_HintPriority), name, value, priority) end function SDL_SetHint(name, value) ccall((:SDL_SetHint, libsdl2), SDL_bool, (Ptr{Cchar}, Ptr{Cchar}), name, value) end function SDL_ResetHint(name) ccall((:SDL_ResetHint, libsdl2), SDL_bool, (Ptr{Cchar},), name) end function SDL_GetHint(name) ccall((:SDL_GetHint, libsdl2), Ptr{Cchar}, (Ptr{Cchar},), name) end function SDL_GetHintBoolean(name, default_value) ccall((:SDL_GetHintBoolean, libsdl2), SDL_bool, (Ptr{Cchar}, SDL_bool), name, default_value) end # typedef void ( SDLCALL * SDL_HintCallback ) ( void * userdata , const char * name , const char * oldValue , const char * newValue ) const SDL_HintCallback = Ptr{Cvoid} function SDL_AddHintCallback(name, callback, userdata) ccall((:SDL_AddHintCallback, libsdl2), Cvoid, (Ptr{Cchar}, SDL_HintCallback, Ptr{Cvoid}), name, callback, userdata) end function SDL_DelHintCallback(name, callback, userdata) ccall((:SDL_DelHintCallback, libsdl2), Cvoid, (Ptr{Cchar}, SDL_HintCallback, Ptr{Cvoid}), name, callback, userdata) end function SDL_ClearHints() ccall((:SDL_ClearHints, libsdl2), Cvoid, ()) end function SDL_LoadObject(sofile) ccall((:SDL_LoadObject, libsdl2), Ptr{Cvoid}, (Ptr{Cchar},), sofile) end function SDL_LoadFunction(handle, name) ccall((:SDL_LoadFunction, libsdl2), Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cchar}), handle, name) end function SDL_UnloadObject(handle) ccall((:SDL_UnloadObject, libsdl2), Cvoid, (Ptr{Cvoid},), handle) end @cenum SDL_LogCategory::UInt32 begin SDL_LOG_CATEGORY_APPLICATION = 0 SDL_LOG_CATEGORY_ERROR = 1 SDL_LOG_CATEGORY_ASSERT = 2 SDL_LOG_CATEGORY_SYSTEM = 3 SDL_LOG_CATEGORY_AUDIO = 4 SDL_LOG_CATEGORY_VIDEO = 5 SDL_LOG_CATEGORY_RENDER = 6 SDL_LOG_CATEGORY_INPUT = 7 SDL_LOG_CATEGORY_TEST = 8 SDL_LOG_CATEGORY_RESERVED1 = 9 SDL_LOG_CATEGORY_RESERVED2 = 10 SDL_LOG_CATEGORY_RESERVED3 = 11 SDL_LOG_CATEGORY_RESERVED4 = 12 SDL_LOG_CATEGORY_RESERVED5 = 13 SDL_LOG_CATEGORY_RESERVED6 = 14 SDL_LOG_CATEGORY_RESERVED7 = 15 SDL_LOG_CATEGORY_RESERVED8 = 16 SDL_LOG_CATEGORY_RESERVED9 = 17 SDL_LOG_CATEGORY_RESERVED10 = 18 SDL_LOG_CATEGORY_CUSTOM = 19 end @cenum SDL_LogPriority::UInt32 begin SDL_LOG_PRIORITY_VERBOSE = 1 SDL_LOG_PRIORITY_DEBUG = 2 SDL_LOG_PRIORITY_INFO = 3 SDL_LOG_PRIORITY_WARN = 4 SDL_LOG_PRIORITY_ERROR = 5 SDL_LOG_PRIORITY_CRITICAL = 6 SDL_NUM_LOG_PRIORITIES = 7 end function SDL_LogSetAllPriority(priority) ccall((:SDL_LogSetAllPriority, libsdl2), Cvoid, (SDL_LogPriority,), priority) end function SDL_LogSetPriority(category, priority) ccall((:SDL_LogSetPriority, libsdl2), Cvoid, (Cint, SDL_LogPriority), category, priority) end function SDL_LogGetPriority(category) ccall((:SDL_LogGetPriority, libsdl2), SDL_LogPriority, (Cint,), category) end function SDL_LogResetPriorities() ccall((:SDL_LogResetPriorities, libsdl2), Cvoid, ()) end # typedef void ( SDLCALL * SDL_LogOutputFunction ) ( void * userdata , int category , SDL_LogPriority priority , const char * message ) const SDL_LogOutputFunction = Ptr{Cvoid} function SDL_LogGetOutputFunction(callback, userdata) ccall((:SDL_LogGetOutputFunction, libsdl2), Cvoid, (Ptr{SDL_LogOutputFunction}, Ptr{Ptr{Cvoid}}), callback, userdata) end function SDL_LogSetOutputFunction(callback, userdata) ccall((:SDL_LogSetOutputFunction, libsdl2), Cvoid, (SDL_LogOutputFunction, Ptr{Cvoid}), callback, userdata) end @cenum SDL_MessageBoxFlags::UInt32 begin SDL_MESSAGEBOX_ERROR = 16 SDL_MESSAGEBOX_WARNING = 32 SDL_MESSAGEBOX_INFORMATION = 64 SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT = 128 SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT = 256 end @cenum SDL_MessageBoxButtonFlags::UInt32 begin SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT = 1 SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT = 2 end struct SDL_MessageBoxButtonData flags::Uint32 buttonid::Cint text::Ptr{Cchar} end struct SDL_MessageBoxColor r::Uint8 g::Uint8 b::Uint8 end @cenum SDL_MessageBoxColorType::UInt32 begin SDL_MESSAGEBOX_COLOR_BACKGROUND = 0 SDL_MESSAGEBOX_COLOR_TEXT = 1 SDL_MESSAGEBOX_COLOR_BUTTON_BORDER = 2 SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND = 3 SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED = 4 SDL_MESSAGEBOX_COLOR_MAX = 5 end struct SDL_MessageBoxColorScheme colors::NTuple{5, SDL_MessageBoxColor} end struct SDL_MessageBoxData flags::Uint32 window::Ptr{SDL_Window} title::Ptr{Cchar} message::Ptr{Cchar} numbuttons::Cint buttons::Ptr{SDL_MessageBoxButtonData} colorScheme::Ptr{SDL_MessageBoxColorScheme} end function SDL_ShowMessageBox(messageboxdata, buttonid) ccall((:SDL_ShowMessageBox, libsdl2), Cint, (Ptr{SDL_MessageBoxData}, Ptr{Cint}), messageboxdata, buttonid) end function SDL_ShowSimpleMessageBox(flags, title, message, window) ccall((:SDL_ShowSimpleMessageBox, libsdl2), Cint, (Uint32, Ptr{Cchar}, Ptr{Cchar}, Ptr{SDL_Window}), flags, title, message, window) end const SDL_MetalView = Ptr{Cvoid} function SDL_Metal_CreateView(window) ccall((:SDL_Metal_CreateView, libsdl2), SDL_MetalView, (Ptr{SDL_Window},), window) end function SDL_Metal_DestroyView(view) ccall((:SDL_Metal_DestroyView, libsdl2), Cvoid, (SDL_MetalView,), view) end function SDL_Metal_GetLayer(view) ccall((:SDL_Metal_GetLayer, libsdl2), Ptr{Cvoid}, (SDL_MetalView,), view) end function SDL_Metal_GetDrawableSize(window, w, h) ccall((:SDL_Metal_GetDrawableSize, libsdl2), Cvoid, (Ptr{SDL_Window}, Ptr{Cint}, Ptr{Cint}), window, w, h) end @cenum SDL_PowerState::UInt32 begin SDL_POWERSTATE_UNKNOWN = 0 SDL_POWERSTATE_ON_BATTERY = 1 SDL_POWERSTATE_NO_BATTERY = 2 SDL_POWERSTATE_CHARGING = 3 SDL_POWERSTATE_CHARGED = 4 end function SDL_GetPowerInfo(secs, pct) ccall((:SDL_GetPowerInfo, libsdl2), SDL_PowerState, (Ptr{Cint}, Ptr{Cint}), secs, pct) end @cenum SDL_RendererFlags::UInt32 begin SDL_RENDERER_SOFTWARE = 1 SDL_RENDERER_ACCELERATED = 2 SDL_RENDERER_PRESENTVSYNC = 4 SDL_RENDERER_TARGETTEXTURE = 8 end struct SDL_RendererInfo name::Ptr{Cchar} flags::Uint32 num_texture_formats::Uint32 texture_formats::NTuple{16, Uint32} max_texture_width::Cint max_texture_height::Cint end struct SDL_Vertex position::SDL_FPoint color::SDL_Color tex_coord::SDL_FPoint end @cenum SDL_ScaleMode::UInt32 begin SDL_ScaleModeNearest = 0 SDL_ScaleModeLinear = 1 SDL_ScaleModeBest = 2 end @cenum SDL_TextureAccess::UInt32 begin SDL_TEXTUREACCESS_STATIC = 0 SDL_TEXTUREACCESS_STREAMING = 1 SDL_TEXTUREACCESS_TARGET = 2 end @cenum SDL_TextureModulate::UInt32 begin SDL_TEXTUREMODULATE_NONE = 0 SDL_TEXTUREMODULATE_COLOR = 1 SDL_TEXTUREMODULATE_ALPHA = 2 end @cenum SDL_RendererFlip::UInt32 begin SDL_FLIP_NONE = 0 SDL_FLIP_HORIZONTAL = 1 SDL_FLIP_VERTICAL = 2 end mutable struct SDL_Renderer end mutable struct SDL_Texture end function SDL_GetNumRenderDrivers() ccall((:SDL_GetNumRenderDrivers, libsdl2), Cint, ()) end function SDL_GetRenderDriverInfo(index, info) ccall((:SDL_GetRenderDriverInfo, libsdl2), Cint, (Cint, Ptr{SDL_RendererInfo}), index, info) end function SDL_CreateWindowAndRenderer(width, height, window_flags, window, renderer) ccall((:SDL_CreateWindowAndRenderer, libsdl2), Cint, (Cint, Cint, Uint32, Ptr{Ptr{SDL_Window}}, Ptr{Ptr{SDL_Renderer}}), width, height, window_flags, window, renderer) end function SDL_CreateRenderer(window, index, flags) ccall((:SDL_CreateRenderer, libsdl2), Ptr{SDL_Renderer}, (Ptr{SDL_Window}, Cint, Uint32), window, index, flags) end function SDL_CreateSoftwareRenderer(surface) ccall((:SDL_CreateSoftwareRenderer, libsdl2), Ptr{SDL_Renderer}, (Ptr{SDL_Surface},), surface) end function SDL_GetRenderer(window) ccall((:SDL_GetRenderer, libsdl2), Ptr{SDL_Renderer}, (Ptr{SDL_Window},), window) end function SDL_RenderGetWindow(renderer) ccall((:SDL_RenderGetWindow, libsdl2), Ptr{SDL_Window}, (Ptr{SDL_Renderer},), renderer) end function SDL_GetRendererInfo(renderer, info) ccall((:SDL_GetRendererInfo, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_RendererInfo}), renderer, info) end function SDL_GetRendererOutputSize(renderer, w, h) ccall((:SDL_GetRendererOutputSize, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{Cint}, Ptr{Cint}), renderer, w, h) end function SDL_CreateTexture(renderer, format, access, w, h) ccall((:SDL_CreateTexture, libsdl2), Ptr{SDL_Texture}, (Ptr{SDL_Renderer}, Uint32, Cint, Cint, Cint), renderer, format, access, w, h) end function SDL_CreateTextureFromSurface(renderer, surface) ccall((:SDL_CreateTextureFromSurface, libsdl2), Ptr{SDL_Texture}, (Ptr{SDL_Renderer}, Ptr{SDL_Surface}), renderer, surface) end function SDL_QueryTexture(texture, format, access, w, h) ccall((:SDL_QueryTexture, libsdl2), Cint, (Ptr{SDL_Texture}, Ptr{Uint32}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), texture, format, access, w, h) end function SDL_SetTextureColorMod(texture, r, g, b) ccall((:SDL_SetTextureColorMod, libsdl2), Cint, (Ptr{SDL_Texture}, Uint8, Uint8, Uint8), texture, r, g, b) end function SDL_GetTextureColorMod(texture, r, g, b) ccall((:SDL_GetTextureColorMod, libsdl2), Cint, (Ptr{SDL_Texture}, Ptr{Uint8}, Ptr{Uint8}, Ptr{Uint8}), texture, r, g, b) end function SDL_SetTextureAlphaMod(texture, alpha) ccall((:SDL_SetTextureAlphaMod, libsdl2), Cint, (Ptr{SDL_Texture}, Uint8), texture, alpha) end function SDL_GetTextureAlphaMod(texture, alpha) ccall((:SDL_GetTextureAlphaMod, libsdl2), Cint, (Ptr{SDL_Texture}, Ptr{Uint8}), texture, alpha) end function SDL_SetTextureBlendMode(texture, blendMode) ccall((:SDL_SetTextureBlendMode, libsdl2), Cint, (Ptr{SDL_Texture}, SDL_BlendMode), texture, blendMode) end function SDL_GetTextureBlendMode(texture, blendMode) ccall((:SDL_GetTextureBlendMode, libsdl2), Cint, (Ptr{SDL_Texture}, Ptr{SDL_BlendMode}), texture, blendMode) end function SDL_SetTextureScaleMode(texture, scaleMode) ccall((:SDL_SetTextureScaleMode, libsdl2), Cint, (Ptr{SDL_Texture}, SDL_ScaleMode), texture, scaleMode) end function SDL_GetTextureScaleMode(texture, scaleMode) ccall((:SDL_GetTextureScaleMode, libsdl2), Cint, (Ptr{SDL_Texture}, Ptr{SDL_ScaleMode}), texture, scaleMode) end function SDL_SetTextureUserData(texture, userdata) ccall((:SDL_SetTextureUserData, libsdl2), Cint, (Ptr{SDL_Texture}, Ptr{Cvoid}), texture, userdata) end function SDL_GetTextureUserData(texture) ccall((:SDL_GetTextureUserData, libsdl2), Ptr{Cvoid}, (Ptr{SDL_Texture},), texture) end function SDL_UpdateTexture(texture, rect, pixels, pitch) ccall((:SDL_UpdateTexture, libsdl2), Cint, (Ptr{SDL_Texture}, Ptr{SDL_Rect}, Ptr{Cvoid}, Cint), texture, rect, pixels, pitch) end function SDL_UpdateYUVTexture(texture, rect, Yplane, Ypitch, Uplane, Upitch, Vplane, Vpitch) ccall((:SDL_UpdateYUVTexture, libsdl2), Cint, (Ptr{SDL_Texture}, Ptr{SDL_Rect}, Ptr{Uint8}, Cint, Ptr{Uint8}, Cint, Ptr{Uint8}, Cint), texture, rect, Yplane, Ypitch, Uplane, Upitch, Vplane, Vpitch) end function SDL_UpdateNVTexture(texture, rect, Yplane, Ypitch, UVplane, UVpitch) ccall((:SDL_UpdateNVTexture, libsdl2), Cint, (Ptr{SDL_Texture}, Ptr{SDL_Rect}, Ptr{Uint8}, Cint, Ptr{Uint8}, Cint), texture, rect, Yplane, Ypitch, UVplane, UVpitch) end function SDL_LockTexture(texture, rect, pixels, pitch) ccall((:SDL_LockTexture, libsdl2), Cint, (Ptr{SDL_Texture}, Ptr{SDL_Rect}, Ptr{Ptr{Cvoid}}, Ptr{Cint}), texture, rect, pixels, pitch) end function SDL_LockTextureToSurface(texture, rect, surface) ccall((:SDL_LockTextureToSurface, libsdl2), Cint, (Ptr{SDL_Texture}, Ptr{SDL_Rect}, Ptr{Ptr{SDL_Surface}}), texture, rect, surface) end function SDL_UnlockTexture(texture) ccall((:SDL_UnlockTexture, libsdl2), Cvoid, (Ptr{SDL_Texture},), texture) end function SDL_RenderTargetSupported(renderer) ccall((:SDL_RenderTargetSupported, libsdl2), SDL_bool, (Ptr{SDL_Renderer},), renderer) end function SDL_SetRenderTarget(renderer, texture) ccall((:SDL_SetRenderTarget, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Texture}), renderer, texture) end function SDL_GetRenderTarget(renderer) ccall((:SDL_GetRenderTarget, libsdl2), Ptr{SDL_Texture}, (Ptr{SDL_Renderer},), renderer) end function SDL_RenderSetLogicalSize(renderer, w, h) ccall((:SDL_RenderSetLogicalSize, libsdl2), Cint, (Ptr{SDL_Renderer}, Cint, Cint), renderer, w, h) end function SDL_RenderGetLogicalSize(renderer, w, h) ccall((:SDL_RenderGetLogicalSize, libsdl2), Cvoid, (Ptr{SDL_Renderer}, Ptr{Cint}, Ptr{Cint}), renderer, w, h) end function SDL_RenderSetIntegerScale(renderer, enable) ccall((:SDL_RenderSetIntegerScale, libsdl2), Cint, (Ptr{SDL_Renderer}, SDL_bool), renderer, enable) end function SDL_RenderGetIntegerScale(renderer) ccall((:SDL_RenderGetIntegerScale, libsdl2), SDL_bool, (Ptr{SDL_Renderer},), renderer) end function SDL_RenderSetViewport(renderer, rect) ccall((:SDL_RenderSetViewport, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Rect}), renderer, rect) end function SDL_RenderGetViewport(renderer, rect) ccall((:SDL_RenderGetViewport, libsdl2), Cvoid, (Ptr{SDL_Renderer}, Ptr{SDL_Rect}), renderer, rect) end function SDL_RenderSetClipRect(renderer, rect) ccall((:SDL_RenderSetClipRect, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Rect}), renderer, rect) end function SDL_RenderGetClipRect(renderer, rect) ccall((:SDL_RenderGetClipRect, libsdl2), Cvoid, (Ptr{SDL_Renderer}, Ptr{SDL_Rect}), renderer, rect) end function SDL_RenderIsClipEnabled(renderer) ccall((:SDL_RenderIsClipEnabled, libsdl2), SDL_bool, (Ptr{SDL_Renderer},), renderer) end function SDL_RenderSetScale(renderer, scaleX, scaleY) ccall((:SDL_RenderSetScale, libsdl2), Cint, (Ptr{SDL_Renderer}, Cfloat, Cfloat), renderer, scaleX, scaleY) end function SDL_RenderGetScale(renderer, scaleX, scaleY) ccall((:SDL_RenderGetScale, libsdl2), Cvoid, (Ptr{SDL_Renderer}, Ptr{Cfloat}, Ptr{Cfloat}), renderer, scaleX, scaleY) end function SDL_RenderWindowToLogical(renderer, windowX, windowY, logicalX, logicalY) ccall((:SDL_RenderWindowToLogical, libsdl2), Cvoid, (Ptr{SDL_Renderer}, Cint, Cint, Ptr{Cfloat}, Ptr{Cfloat}), renderer, windowX, windowY, logicalX, logicalY) end function SDL_RenderLogicalToWindow(renderer, logicalX, logicalY, windowX, windowY) ccall((:SDL_RenderLogicalToWindow, libsdl2), Cvoid, (Ptr{SDL_Renderer}, Cfloat, Cfloat, Ptr{Cint}, Ptr{Cint}), renderer, logicalX, logicalY, windowX, windowY) end function SDL_SetRenderDrawColor(renderer, r, g, b, a) ccall((:SDL_SetRenderDrawColor, libsdl2), Cint, (Ptr{SDL_Renderer}, Uint8, Uint8, Uint8, Uint8), renderer, r, g, b, a) end function SDL_GetRenderDrawColor(renderer, r, g, b, a) ccall((:SDL_GetRenderDrawColor, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{Uint8}, Ptr{Uint8}, Ptr{Uint8}, Ptr{Uint8}), renderer, r, g, b, a) end function SDL_SetRenderDrawBlendMode(renderer, blendMode) ccall((:SDL_SetRenderDrawBlendMode, libsdl2), Cint, (Ptr{SDL_Renderer}, SDL_BlendMode), renderer, blendMode) end function SDL_GetRenderDrawBlendMode(renderer, blendMode) ccall((:SDL_GetRenderDrawBlendMode, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_BlendMode}), renderer, blendMode) end function SDL_RenderClear(renderer) ccall((:SDL_RenderClear, libsdl2), Cint, (Ptr{SDL_Renderer},), renderer) end function SDL_RenderDrawPoint(renderer, x, y) ccall((:SDL_RenderDrawPoint, libsdl2), Cint, (Ptr{SDL_Renderer}, Cint, Cint), renderer, x, y) end function SDL_RenderDrawPoints(renderer, points, count) ccall((:SDL_RenderDrawPoints, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Point}, Cint), renderer, points, count) end function SDL_RenderDrawLine(renderer, x1, y1, x2, y2) ccall((:SDL_RenderDrawLine, libsdl2), Cint, (Ptr{SDL_Renderer}, Cint, Cint, Cint, Cint), renderer, x1, y1, x2, y2) end function SDL_RenderDrawLines(renderer, points, count) ccall((:SDL_RenderDrawLines, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Point}, Cint), renderer, points, count) end function SDL_RenderDrawRect(renderer, rect) ccall((:SDL_RenderDrawRect, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Rect}), renderer, rect) end function SDL_RenderDrawRects(renderer, rects, count) ccall((:SDL_RenderDrawRects, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Rect}, Cint), renderer, rects, count) end function SDL_RenderFillRect(renderer, rect) ccall((:SDL_RenderFillRect, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Rect}), renderer, rect) end function SDL_RenderFillRects(renderer, rects, count) ccall((:SDL_RenderFillRects, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Rect}, Cint), renderer, rects, count) end function SDL_RenderCopy(renderer, texture, srcrect, dstrect) ccall((:SDL_RenderCopy, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Texture}, Ptr{SDL_Rect}, Ptr{SDL_Rect}), renderer, texture, srcrect, dstrect) end function SDL_RenderCopyEx(renderer, texture, srcrect, dstrect, angle, center, flip) ccall((:SDL_RenderCopyEx, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Texture}, Ptr{SDL_Rect}, Ptr{SDL_Rect}, Cdouble, Ptr{SDL_Point}, SDL_RendererFlip), renderer, texture, srcrect, dstrect, angle, center, flip) end function SDL_RenderDrawPointF(renderer, x, y) ccall((:SDL_RenderDrawPointF, libsdl2), Cint, (Ptr{SDL_Renderer}, Cfloat, Cfloat), renderer, x, y) end function SDL_RenderDrawPointsF(renderer, points, count) ccall((:SDL_RenderDrawPointsF, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_FPoint}, Cint), renderer, points, count) end function SDL_RenderDrawLineF(renderer, x1, y1, x2, y2) ccall((:SDL_RenderDrawLineF, libsdl2), Cint, (Ptr{SDL_Renderer}, Cfloat, Cfloat, Cfloat, Cfloat), renderer, x1, y1, x2, y2) end function SDL_RenderDrawLinesF(renderer, points, count) ccall((:SDL_RenderDrawLinesF, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_FPoint}, Cint), renderer, points, count) end function SDL_RenderDrawRectF(renderer, rect) ccall((:SDL_RenderDrawRectF, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_FRect}), renderer, rect) end function SDL_RenderDrawRectsF(renderer, rects, count) ccall((:SDL_RenderDrawRectsF, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_FRect}, Cint), renderer, rects, count) end function SDL_RenderFillRectF(renderer, rect) ccall((:SDL_RenderFillRectF, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_FRect}), renderer, rect) end function SDL_RenderFillRectsF(renderer, rects, count) ccall((:SDL_RenderFillRectsF, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_FRect}, Cint), renderer, rects, count) end function SDL_RenderCopyF(renderer, texture, srcrect, dstrect) ccall((:SDL_RenderCopyF, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Texture}, Ptr{SDL_Rect}, Ptr{SDL_FRect}), renderer, texture, srcrect, dstrect) end function SDL_RenderCopyExF(renderer, texture, srcrect, dstrect, angle, center, flip) ccall((:SDL_RenderCopyExF, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Texture}, Ptr{SDL_Rect}, Ptr{SDL_FRect}, Cdouble, Ptr{SDL_FPoint}, SDL_RendererFlip), renderer, texture, srcrect, dstrect, angle, center, flip) end function SDL_RenderGeometry(renderer, texture, vertices, num_vertices, indices, num_indices) ccall((:SDL_RenderGeometry, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Texture}, Ptr{SDL_Vertex}, Cint, Ptr{Cint}, Cint), renderer, texture, vertices, num_vertices, indices, num_indices) end function SDL_RenderGeometryRaw(renderer, texture, xy, xy_stride, color, color_stride, uv, uv_stride, num_vertices, indices, num_indices, size_indices) ccall((:SDL_RenderGeometryRaw, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Texture}, Ptr{Cfloat}, Cint, Ptr{SDL_Color}, Cint, Ptr{Cfloat}, Cint, Cint, Ptr{Cvoid}, Cint, Cint), renderer, texture, xy, xy_stride, color, color_stride, uv, uv_stride, num_vertices, indices, num_indices, size_indices) end function SDL_RenderReadPixels(renderer, rect, format, pixels, pitch) ccall((:SDL_RenderReadPixels, libsdl2), Cint, (Ptr{SDL_Renderer}, Ptr{SDL_Rect}, Uint32, Ptr{Cvoid}, Cint), renderer, rect, format, pixels, pitch) end function SDL_RenderPresent(renderer) ccall((:SDL_RenderPresent, libsdl2), Cvoid, (Ptr{SDL_Renderer},), renderer) end function SDL_DestroyTexture(texture) ccall((:SDL_DestroyTexture, libsdl2), Cvoid, (Ptr{SDL_Texture},), texture) end function SDL_DestroyRenderer(renderer) ccall((:SDL_DestroyRenderer, libsdl2), Cvoid, (Ptr{SDL_Renderer},), renderer) end function SDL_RenderFlush(renderer) ccall((:SDL_RenderFlush, libsdl2), Cint, (Ptr{SDL_Renderer},), renderer) end function SDL_GL_BindTexture(texture, texw, texh) ccall((:SDL_GL_BindTexture, libsdl2), Cint, (Ptr{SDL_Texture}, Ptr{Cfloat}, Ptr{Cfloat}), texture, texw, texh) end function SDL_GL_UnbindTexture(texture) ccall((:SDL_GL_UnbindTexture, libsdl2), Cint, (Ptr{SDL_Texture},), texture) end function SDL_RenderGetMetalLayer(renderer) ccall((:SDL_RenderGetMetalLayer, libsdl2), Ptr{Cvoid}, (Ptr{SDL_Renderer},), renderer) end function SDL_RenderGetMetalCommandEncoder(renderer) ccall((:SDL_RenderGetMetalCommandEncoder, libsdl2), Ptr{Cvoid}, (Ptr{SDL_Renderer},), renderer) end function SDL_RenderSetVSync(renderer, vsync) ccall((:SDL_RenderSetVSync, libsdl2), Cint, (Ptr{SDL_Renderer}, Cint), renderer, vsync) end function SDL_CreateShapedWindow(title, x, y, w, h, flags) ccall((:SDL_CreateShapedWindow, libsdl2), Ptr{SDL_Window}, (Ptr{Cchar}, Cuint, Cuint, Cuint, Cuint, Uint32), title, x, y, w, h, flags) end function SDL_IsShapedWindow(window) ccall((:SDL_IsShapedWindow, libsdl2), SDL_bool, (Ptr{SDL_Window},), window) end @cenum WindowShapeMode::UInt32 begin ShapeModeDefault = 0 ShapeModeBinarizeAlpha = 1 ShapeModeReverseBinarizeAlpha = 2 ShapeModeColorKey = 3 end struct SDL_WindowShapeParams data::NTuple{4, UInt8} end function Base.getproperty(x::Ptr{SDL_WindowShapeParams}, f::Symbol) f === :binarizationCutoff && return Ptr{Uint8}(x + 0) f === :colorKey && return Ptr{SDL_Color}(x + 0) return getfield(x, f) end function Base.getproperty(x::SDL_WindowShapeParams, f::Symbol) r = Ref{SDL_WindowShapeParams}(x) ptr = Base.unsafe_convert(Ptr{SDL_WindowShapeParams}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{SDL_WindowShapeParams}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end struct SDL_WindowShapeMode mode::WindowShapeMode parameters::SDL_WindowShapeParams end function SDL_SetWindowShape(window, shape, shape_mode) ccall((:SDL_SetWindowShape, libsdl2), Cint, (Ptr{SDL_Window}, Ptr{SDL_Surface}, Ptr{SDL_WindowShapeMode}), window, shape, shape_mode) end function SDL_GetShapedWindowMode(window, shape_mode) ccall((:SDL_GetShapedWindowMode, libsdl2), Cint, (Ptr{SDL_Window}, Ptr{SDL_WindowShapeMode}), window, shape_mode) end function SDL_LinuxSetThreadPriority(threadID, priority) ccall((:SDL_LinuxSetThreadPriority, libsdl2), Cint, (Sint64, Cint), threadID, priority) end function SDL_LinuxSetThreadPriorityAndPolicy(threadID, sdlPriority, schedPolicy) ccall((:SDL_LinuxSetThreadPriorityAndPolicy, libsdl2), Cint, (Sint64, Cint, Cint), threadID, sdlPriority, schedPolicy) end function SDL_IsTablet() ccall((:SDL_IsTablet, libsdl2), SDL_bool, ()) end function SDL_OnApplicationWillTerminate() ccall((:SDL_OnApplicationWillTerminate, libsdl2), Cvoid, ()) end function SDL_OnApplicationDidReceiveMemoryWarning() ccall((:SDL_OnApplicationDidReceiveMemoryWarning, libsdl2), Cvoid, ()) end function SDL_OnApplicationWillResignActive() ccall((:SDL_OnApplicationWillResignActive, libsdl2), Cvoid, ()) end function SDL_OnApplicationDidEnterBackground() ccall((:SDL_OnApplicationDidEnterBackground, libsdl2), Cvoid, ()) end function SDL_OnApplicationWillEnterForeground() ccall((:SDL_OnApplicationWillEnterForeground, libsdl2), Cvoid, ()) end function SDL_OnApplicationDidBecomeActive() ccall((:SDL_OnApplicationDidBecomeActive, libsdl2), Cvoid, ()) end function SDL_GetTicks() ccall((:SDL_GetTicks, libsdl2), Uint32, ()) end function SDL_GetTicks64() ccall((:SDL_GetTicks64, libsdl2), Uint64, ()) end function SDL_GetPerformanceCounter() ccall((:SDL_GetPerformanceCounter, libsdl2), Uint64, ()) end function SDL_GetPerformanceFrequency() ccall((:SDL_GetPerformanceFrequency, libsdl2), Uint64, ()) end function SDL_Delay(ms) ccall((:SDL_Delay, libsdl2), Cvoid, (Uint32,), ms) end # typedef Uint32 ( SDLCALL * SDL_TimerCallback ) ( Uint32 interval , void * param ) const SDL_TimerCallback = Ptr{Cvoid} const SDL_TimerID = Cint function SDL_AddTimer(interval, callback, param) ccall((:SDL_AddTimer, libsdl2), SDL_TimerID, (Uint32, SDL_TimerCallback, Ptr{Cvoid}), interval, callback, param) end function SDL_RemoveTimer(id) ccall((:SDL_RemoveTimer, libsdl2), SDL_bool, (SDL_TimerID,), id) end struct SDL_version major::Uint8 minor::Uint8 patch::Uint8 end function SDL_GetVersion(ver) ccall((:SDL_GetVersion, libsdl2), Cvoid, (Ptr{SDL_version},), ver) end function SDL_GetRevision() ccall((:SDL_GetRevision, libsdl2), Ptr{Cchar}, ()) end function SDL_GetRevisionNumber() ccall((:SDL_GetRevisionNumber, libsdl2), Cint, ()) end struct SDL_Locale language::Ptr{Cchar} country::Ptr{Cchar} end function SDL_GetPreferredLocales() ccall((:SDL_GetPreferredLocales, libsdl2), Ptr{SDL_Locale}, ()) end function SDL_OpenURL(url) ccall((:SDL_OpenURL, libsdl2), Cint, (Ptr{Cchar},), url) end function SDL_Init(flags) ccall((:SDL_Init, libsdl2), Cint, (Uint32,), flags) end function SDL_InitSubSystem(flags) ccall((:SDL_InitSubSystem, libsdl2), Cint, (Uint32,), flags) end function SDL_QuitSubSystem(flags) ccall((:SDL_QuitSubSystem, libsdl2), Cvoid, (Uint32,), flags) end function SDL_WasInit(flags) ccall((:SDL_WasInit, libsdl2), Uint32, (Uint32,), flags) end function SDL_Quit() ccall((:SDL_Quit, libsdl2), Cvoid, ()) end function Mix_Linked_Version() ccall((:Mix_Linked_Version, libsdl2_mixer), Ptr{SDL_version}, ()) end @cenum MIX_InitFlags::UInt32 begin MIX_INIT_FLAC = 1 MIX_INIT_MOD = 2 MIX_INIT_MP3 = 8 MIX_INIT_OGG = 16 MIX_INIT_MID = 32 MIX_INIT_OPUS = 64 end function Mix_Init(flags) ccall((:Mix_Init, libsdl2_mixer), Cint, (Cint,), flags) end function Mix_Quit() ccall((:Mix_Quit, libsdl2_mixer), Cvoid, ()) end struct Mix_Chunk allocated::Cint abuf::Ptr{Uint8} alen::Uint32 volume::Uint8 end @cenum Mix_Fading::UInt32 begin MIX_NO_FADING = 0 MIX_FADING_OUT = 1 MIX_FADING_IN = 2 end @cenum Mix_MusicType::UInt32 begin MUS_NONE = 0 MUS_CMD = 1 MUS_WAV = 2 MUS_MOD = 3 MUS_MID = 4 MUS_OGG = 5 MUS_MP3 = 6 MUS_MP3_MAD_UNUSED = 7 MUS_FLAC = 8 MUS_MODPLUG_UNUSED = 9 MUS_OPUS = 10 end mutable struct _Mix_Music end const Mix_Music = _Mix_Music function Mix_OpenAudio(frequency, format, channels, chunksize) ccall((:Mix_OpenAudio, libsdl2_mixer), Cint, (Cint, Uint16, Cint, Cint), frequency, format, channels, chunksize) end function Mix_OpenAudioDevice(frequency, format, channels, chunksize, device, allowed_changes) ccall((:Mix_OpenAudioDevice, libsdl2_mixer), Cint, (Cint, Uint16, Cint, Cint, Ptr{Cchar}, Cint), frequency, format, channels, chunksize, device, allowed_changes) end function Mix_QuerySpec(frequency, format, channels) ccall((:Mix_QuerySpec, libsdl2_mixer), Cint, (Ptr{Cint}, Ptr{Uint16}, Ptr{Cint}), frequency, format, channels) end function Mix_AllocateChannels(numchans) ccall((:Mix_AllocateChannels, libsdl2_mixer), Cint, (Cint,), numchans) end function Mix_LoadWAV_RW(src, freesrc) ccall((:Mix_LoadWAV_RW, libsdl2_mixer), Ptr{Mix_Chunk}, (Ptr{SDL_RWops}, Cint), src, freesrc) end function Mix_LoadWAV(file) ccall((:Mix_LoadWAV, libsdl2_mixer), Ptr{Mix_Chunk}, (Ptr{Cchar},), file) end function Mix_LoadMUS(file) ccall((:Mix_LoadMUS, libsdl2_mixer), Ptr{Mix_Music}, (Ptr{Cchar},), file) end function Mix_LoadMUS_RW(src, freesrc) ccall((:Mix_LoadMUS_RW, libsdl2_mixer), Ptr{Mix_Music}, (Ptr{SDL_RWops}, Cint), src, freesrc) end function Mix_LoadMUSType_RW(src, type, freesrc) ccall((:Mix_LoadMUSType_RW, libsdl2_mixer), Ptr{Mix_Music}, (Ptr{SDL_RWops}, Mix_MusicType, Cint), src, type, freesrc) end function Mix_QuickLoad_WAV(mem) ccall((:Mix_QuickLoad_WAV, libsdl2_mixer), Ptr{Mix_Chunk}, (Ptr{Uint8},), mem) end function Mix_QuickLoad_RAW(mem, len) ccall((:Mix_QuickLoad_RAW, libsdl2_mixer), Ptr{Mix_Chunk}, (Ptr{Uint8}, Uint32), mem, len) end function Mix_FreeChunk(chunk) ccall((:Mix_FreeChunk, libsdl2_mixer), Cvoid, (Ptr{Mix_Chunk},), chunk) end function Mix_FreeMusic(music) ccall((:Mix_FreeMusic, libsdl2_mixer), Cvoid, (Ptr{Mix_Music},), music) end function Mix_GetNumChunkDecoders() ccall((:Mix_GetNumChunkDecoders, libsdl2_mixer), Cint, ()) end function Mix_GetChunkDecoder(index) ccall((:Mix_GetChunkDecoder, libsdl2_mixer), Ptr{Cchar}, (Cint,), index) end function Mix_HasChunkDecoder(name) ccall((:Mix_HasChunkDecoder, libsdl2_mixer), SDL_bool, (Ptr{Cchar},), name) end function Mix_GetNumMusicDecoders() ccall((:Mix_GetNumMusicDecoders, libsdl2_mixer), Cint, ()) end function Mix_GetMusicDecoder(index) ccall((:Mix_GetMusicDecoder, libsdl2_mixer), Ptr{Cchar}, (Cint,), index) end function Mix_HasMusicDecoder(name) ccall((:Mix_HasMusicDecoder, libsdl2_mixer), SDL_bool, (Ptr{Cchar},), name) end function Mix_GetMusicType(music) ccall((:Mix_GetMusicType, libsdl2_mixer), Mix_MusicType, (Ptr{Mix_Music},), music) end function Mix_GetMusicTitle(music) ccall((:Mix_GetMusicTitle, libsdl2_mixer), Ptr{Cchar}, (Ptr{Mix_Music},), music) end function Mix_GetMusicTitleTag(music) ccall((:Mix_GetMusicTitleTag, libsdl2_mixer), Ptr{Cchar}, (Ptr{Mix_Music},), music) end function Mix_GetMusicArtistTag(music) ccall((:Mix_GetMusicArtistTag, libsdl2_mixer), Ptr{Cchar}, (Ptr{Mix_Music},), music) end function Mix_GetMusicAlbumTag(music) ccall((:Mix_GetMusicAlbumTag, libsdl2_mixer), Ptr{Cchar}, (Ptr{Mix_Music},), music) end function Mix_GetMusicCopyrightTag(music) ccall((:Mix_GetMusicCopyrightTag, libsdl2_mixer), Ptr{Cchar}, (Ptr{Mix_Music},), music) end function Mix_SetPostMix(mix_func, arg) ccall((:Mix_SetPostMix, libsdl2_mixer), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}), mix_func, arg) end function Mix_HookMusic(mix_func, arg) ccall((:Mix_HookMusic, libsdl2_mixer), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}), mix_func, arg) end function Mix_HookMusicFinished(music_finished) ccall((:Mix_HookMusicFinished, libsdl2_mixer), Cvoid, (Ptr{Cvoid},), music_finished) end function Mix_GetMusicHookData() ccall((:Mix_GetMusicHookData, libsdl2_mixer), Ptr{Cvoid}, ()) end function Mix_ChannelFinished(channel_finished) ccall((:Mix_ChannelFinished, libsdl2_mixer), Cvoid, (Ptr{Cvoid},), channel_finished) end # typedef void ( SDLCALL * Mix_EffectFunc_t ) ( int chan , void * stream , int len , void * udata ) const Mix_EffectFunc_t = Ptr{Cvoid} # typedef void ( SDLCALL * Mix_EffectDone_t ) ( int chan , void * udata ) const Mix_EffectDone_t = Ptr{Cvoid} function Mix_RegisterEffect(chan, f, d, arg) ccall((:Mix_RegisterEffect, libsdl2_mixer), Cint, (Cint, Mix_EffectFunc_t, Mix_EffectDone_t, Ptr{Cvoid}), chan, f, d, arg) end function Mix_UnregisterEffect(channel, f) ccall((:Mix_UnregisterEffect, libsdl2_mixer), Cint, (Cint, Mix_EffectFunc_t), channel, f) end function Mix_UnregisterAllEffects(channel) ccall((:Mix_UnregisterAllEffects, libsdl2_mixer), Cint, (Cint,), channel) end function Mix_SetPanning(channel, left, right) ccall((:Mix_SetPanning, libsdl2_mixer), Cint, (Cint, Uint8, Uint8), channel, left, right) end function Mix_SetPosition(channel, angle, distance) ccall((:Mix_SetPosition, libsdl2_mixer), Cint, (Cint, Sint16, Uint8), channel, angle, distance) end function Mix_SetDistance(channel, distance) ccall((:Mix_SetDistance, libsdl2_mixer), Cint, (Cint, Uint8), channel, distance) end function Mix_SetReverseStereo(channel, flip) ccall((:Mix_SetReverseStereo, libsdl2_mixer), Cint, (Cint, Cint), channel, flip) end function Mix_ReserveChannels(num) ccall((:Mix_ReserveChannels, libsdl2_mixer), Cint, (Cint,), num) end function Mix_GroupChannel(which, tag) ccall((:Mix_GroupChannel, libsdl2_mixer), Cint, (Cint, Cint), which, tag) end function Mix_GroupChannels(from, to, tag) ccall((:Mix_GroupChannels, libsdl2_mixer), Cint, (Cint, Cint, Cint), from, to, tag) end function Mix_GroupAvailable(tag) ccall((:Mix_GroupAvailable, libsdl2_mixer), Cint, (Cint,), tag) end function Mix_GroupCount(tag) ccall((:Mix_GroupCount, libsdl2_mixer), Cint, (Cint,), tag) end function Mix_GroupOldest(tag) ccall((:Mix_GroupOldest, libsdl2_mixer), Cint, (Cint,), tag) end function Mix_GroupNewer(tag) ccall((:Mix_GroupNewer, libsdl2_mixer), Cint, (Cint,), tag) end function Mix_PlayChannel(channel, chunk, loops) ccall((:Mix_PlayChannel, libsdl2_mixer), Cint, (Cint, Ptr{Mix_Chunk}, Cint), channel, chunk, loops) end function Mix_PlayChannelTimed(channel, chunk, loops, ticks) ccall((:Mix_PlayChannelTimed, libsdl2_mixer), Cint, (Cint, Ptr{Mix_Chunk}, Cint, Cint), channel, chunk, loops, ticks) end function Mix_PlayMusic(music, loops) ccall((:Mix_PlayMusic, libsdl2_mixer), Cint, (Ptr{Mix_Music}, Cint), music, loops) end function Mix_FadeInMusic(music, loops, ms) ccall((:Mix_FadeInMusic, libsdl2_mixer), Cint, (Ptr{Mix_Music}, Cint, Cint), music, loops, ms) end function Mix_FadeInMusicPos(music, loops, ms, position) ccall((:Mix_FadeInMusicPos, libsdl2_mixer), Cint, (Ptr{Mix_Music}, Cint, Cint, Cdouble), music, loops, ms, position) end function Mix_FadeInChannel(channel, chunk, loops, ms) ccall((:Mix_FadeInChannel, libsdl2_mixer), Cint, (Cint, Ptr{Mix_Chunk}, Cint, Cint), channel, chunk, loops, ms) end function Mix_FadeInChannelTimed(channel, chunk, loops, ms, ticks) ccall((:Mix_FadeInChannelTimed, libsdl2_mixer), Cint, (Cint, Ptr{Mix_Chunk}, Cint, Cint, Cint), channel, chunk, loops, ms, ticks) end function Mix_Volume(channel, volume) ccall((:Mix_Volume, libsdl2_mixer), Cint, (Cint, Cint), channel, volume) end function Mix_VolumeChunk(chunk, volume) ccall((:Mix_VolumeChunk, libsdl2_mixer), Cint, (Ptr{Mix_Chunk}, Cint), chunk, volume) end function Mix_VolumeMusic(volume) ccall((:Mix_VolumeMusic, libsdl2_mixer), Cint, (Cint,), volume) end function Mix_GetMusicVolume(music) ccall((:Mix_GetMusicVolume, libsdl2_mixer), Cint, (Ptr{Mix_Music},), music) end function Mix_MasterVolume(volume) ccall((:Mix_MasterVolume, libsdl2_mixer), Cint, (Cint,), volume) end function Mix_HaltChannel(channel) ccall((:Mix_HaltChannel, libsdl2_mixer), Cint, (Cint,), channel) end function Mix_HaltGroup(tag) ccall((:Mix_HaltGroup, libsdl2_mixer), Cint, (Cint,), tag) end function Mix_HaltMusic() ccall((:Mix_HaltMusic, libsdl2_mixer), Cint, ()) end function Mix_ExpireChannel(channel, ticks) ccall((:Mix_ExpireChannel, libsdl2_mixer), Cint, (Cint, Cint), channel, ticks) end function Mix_FadeOutChannel(which, ms) ccall((:Mix_FadeOutChannel, libsdl2_mixer), Cint, (Cint, Cint), which, ms) end function Mix_FadeOutGroup(tag, ms) ccall((:Mix_FadeOutGroup, libsdl2_mixer), Cint, (Cint, Cint), tag, ms) end function Mix_FadeOutMusic(ms) ccall((:Mix_FadeOutMusic, libsdl2_mixer), Cint, (Cint,), ms) end function Mix_FadingMusic() ccall((:Mix_FadingMusic, libsdl2_mixer), Mix_Fading, ()) end function Mix_FadingChannel(which) ccall((:Mix_FadingChannel, libsdl2_mixer), Mix_Fading, (Cint,), which) end function Mix_Pause(channel) ccall((:Mix_Pause, libsdl2_mixer), Cvoid, (Cint,), channel) end function Mix_Resume(channel) ccall((:Mix_Resume, libsdl2_mixer), Cvoid, (Cint,), channel) end function Mix_Paused(channel) ccall((:Mix_Paused, libsdl2_mixer), Cint, (Cint,), channel) end function Mix_PauseMusic() ccall((:Mix_PauseMusic, libsdl2_mixer), Cvoid, ()) end function Mix_ResumeMusic() ccall((:Mix_ResumeMusic, libsdl2_mixer), Cvoid, ()) end function Mix_RewindMusic() ccall((:Mix_RewindMusic, libsdl2_mixer), Cvoid, ()) end function Mix_PausedMusic() ccall((:Mix_PausedMusic, libsdl2_mixer), Cint, ()) end function Mix_ModMusicJumpToOrder(order) ccall((:Mix_ModMusicJumpToOrder, libsdl2_mixer), Cint, (Cint,), order) end function Mix_SetMusicPosition(position) ccall((:Mix_SetMusicPosition, libsdl2_mixer), Cint, (Cdouble,), position) end function Mix_GetMusicPosition(music) ccall((:Mix_GetMusicPosition, libsdl2_mixer), Cdouble, (Ptr{Mix_Music},), music) end function Mix_MusicDuration(music) ccall((:Mix_MusicDuration, libsdl2_mixer), Cdouble, (Ptr{Mix_Music},), music) end function Mix_GetMusicLoopStartTime(music) ccall((:Mix_GetMusicLoopStartTime, libsdl2_mixer), Cdouble, (Ptr{Mix_Music},), music) end function Mix_GetMusicLoopEndTime(music) ccall((:Mix_GetMusicLoopEndTime, libsdl2_mixer), Cdouble, (Ptr{Mix_Music},), music) end function Mix_GetMusicLoopLengthTime(music) ccall((:Mix_GetMusicLoopLengthTime, libsdl2_mixer), Cdouble, (Ptr{Mix_Music},), music) end function Mix_Playing(channel) ccall((:Mix_Playing, libsdl2_mixer), Cint, (Cint,), channel) end function Mix_PlayingMusic() ccall((:Mix_PlayingMusic, libsdl2_mixer), Cint, ()) end function Mix_SetMusicCMD(command) ccall((:Mix_SetMusicCMD, libsdl2_mixer), Cint, (Ptr{Cchar},), command) end function Mix_SetSynchroValue(value) ccall((:Mix_SetSynchroValue, libsdl2_mixer), Cint, (Cint,), value) end function Mix_GetSynchroValue() ccall((:Mix_GetSynchroValue, libsdl2_mixer), Cint, ()) end function Mix_SetSoundFonts(paths) ccall((:Mix_SetSoundFonts, libsdl2_mixer), Cint, (Ptr{Cchar},), paths) end function Mix_GetSoundFonts() ccall((:Mix_GetSoundFonts, libsdl2_mixer), Ptr{Cchar}, ()) end function Mix_EachSoundFont(_function, data) ccall((:Mix_EachSoundFont, libsdl2_mixer), Cint, (Ptr{Cvoid}, Ptr{Cvoid}), _function, data) end function Mix_SetTimidityCfg(path) ccall((:Mix_SetTimidityCfg, libsdl2_mixer), Cint, (Ptr{Cchar},), path) end function Mix_GetTimidityCfg() ccall((:Mix_GetTimidityCfg, libsdl2_mixer), Ptr{Cchar}, ()) end function Mix_GetChunk(channel) ccall((:Mix_GetChunk, libsdl2_mixer), Ptr{Mix_Chunk}, (Cint,), channel) end function Mix_CloseAudio() ccall((:Mix_CloseAudio, libsdl2_mixer), Cvoid, ()) end function IMG_Linked_Version() ccall((:IMG_Linked_Version, libsdl2_image), Ptr{SDL_version}, ()) end @cenum IMG_InitFlags::UInt32 begin IMG_INIT_JPG = 1 IMG_INIT_PNG = 2 IMG_INIT_TIF = 4 IMG_INIT_WEBP = 8 IMG_INIT_JXL = 16 IMG_INIT_AVIF = 32 end function IMG_Init(flags) ccall((:IMG_Init, libsdl2_image), Cint, (Cint,), flags) end function IMG_Quit() ccall((:IMG_Quit, libsdl2_image), Cvoid, ()) end function IMG_LoadTyped_RW(src, freesrc, type) ccall((:IMG_LoadTyped_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops}, Cint, Ptr{Cchar}), src, freesrc, type) end function IMG_Load(file) ccall((:IMG_Load, libsdl2_image), Ptr{SDL_Surface}, (Ptr{Cchar},), file) end function IMG_Load_RW(src, freesrc) ccall((:IMG_Load_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops}, Cint), src, freesrc) end function IMG_LoadTexture(renderer, file) ccall((:IMG_LoadTexture, libsdl2_image), Ptr{SDL_Texture}, (Ptr{SDL_Renderer}, Ptr{Cchar}), renderer, file) end function IMG_LoadTexture_RW(renderer, src, freesrc) ccall((:IMG_LoadTexture_RW, libsdl2_image), Ptr{SDL_Texture}, (Ptr{SDL_Renderer}, Ptr{SDL_RWops}, Cint), renderer, src, freesrc) end function IMG_LoadTextureTyped_RW(renderer, src, freesrc, type) ccall((:IMG_LoadTextureTyped_RW, libsdl2_image), Ptr{SDL_Texture}, (Ptr{SDL_Renderer}, Ptr{SDL_RWops}, Cint, Ptr{Cchar}), renderer, src, freesrc, type) end function IMG_isAVIF(src) ccall((:IMG_isAVIF, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isICO(src) ccall((:IMG_isICO, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isCUR(src) ccall((:IMG_isCUR, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isBMP(src) ccall((:IMG_isBMP, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isGIF(src) ccall((:IMG_isGIF, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isJPG(src) ccall((:IMG_isJPG, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isJXL(src) ccall((:IMG_isJXL, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isLBM(src) ccall((:IMG_isLBM, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isPCX(src) ccall((:IMG_isPCX, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isPNG(src) ccall((:IMG_isPNG, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isPNM(src) ccall((:IMG_isPNM, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isSVG(src) ccall((:IMG_isSVG, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isQOI(src) ccall((:IMG_isQOI, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isTIF(src) ccall((:IMG_isTIF, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isXCF(src) ccall((:IMG_isXCF, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isXPM(src) ccall((:IMG_isXPM, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isXV(src) ccall((:IMG_isXV, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_isWEBP(src) ccall((:IMG_isWEBP, libsdl2_image), Cint, (Ptr{SDL_RWops},), src) end function IMG_LoadAVIF_RW(src) ccall((:IMG_LoadAVIF_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadICO_RW(src) ccall((:IMG_LoadICO_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadCUR_RW(src) ccall((:IMG_LoadCUR_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadBMP_RW(src) ccall((:IMG_LoadBMP_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadGIF_RW(src) ccall((:IMG_LoadGIF_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadJPG_RW(src) ccall((:IMG_LoadJPG_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadJXL_RW(src) ccall((:IMG_LoadJXL_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadLBM_RW(src) ccall((:IMG_LoadLBM_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadPCX_RW(src) ccall((:IMG_LoadPCX_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadPNG_RW(src) ccall((:IMG_LoadPNG_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadPNM_RW(src) ccall((:IMG_LoadPNM_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadSVG_RW(src) ccall((:IMG_LoadSVG_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadQOI_RW(src) ccall((:IMG_LoadQOI_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadTGA_RW(src) ccall((:IMG_LoadTGA_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadTIF_RW(src) ccall((:IMG_LoadTIF_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadXCF_RW(src) ccall((:IMG_LoadXCF_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadXPM_RW(src) ccall((:IMG_LoadXPM_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadXV_RW(src) ccall((:IMG_LoadXV_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadWEBP_RW(src) ccall((:IMG_LoadWEBP_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops},), src) end function IMG_LoadSizedSVG_RW(src, width, height) ccall((:IMG_LoadSizedSVG_RW, libsdl2_image), Ptr{SDL_Surface}, (Ptr{SDL_RWops}, Cint, Cint), src, width, height) end function IMG_ReadXPMFromArray(xpm) ccall((:IMG_ReadXPMFromArray, libsdl2_image), Ptr{SDL_Surface}, (Ptr{Ptr{Cchar}},), xpm) end function IMG_ReadXPMFromArrayToRGB888(xpm) ccall((:IMG_ReadXPMFromArrayToRGB888, libsdl2_image), Ptr{SDL_Surface}, (Ptr{Ptr{Cchar}},), xpm) end function IMG_SavePNG(surface, file) ccall((:IMG_SavePNG, libsdl2_image), Cint, (Ptr{SDL_Surface}, Ptr{Cchar}), surface, file) end function IMG_SavePNG_RW(surface, dst, freedst) ccall((:IMG_SavePNG_RW, libsdl2_image), Cint, (Ptr{SDL_Surface}, Ptr{SDL_RWops}, Cint), surface, dst, freedst) end function IMG_SaveJPG(surface, file, quality) ccall((:IMG_SaveJPG, libsdl2_image), Cint, (Ptr{SDL_Surface}, Ptr{Cchar}, Cint), surface, file, quality) end function IMG_SaveJPG_RW(surface, dst, freedst, quality) ccall((:IMG_SaveJPG_RW, libsdl2_image), Cint, (Ptr{SDL_Surface}, Ptr{SDL_RWops}, Cint, Cint), surface, dst, freedst, quality) end struct IMG_Animation w::Cint h::Cint count::Cint frames::Ptr{Ptr{SDL_Surface}} delays::Ptr{Cint} end function IMG_LoadAnimation(file) ccall((:IMG_LoadAnimation, libsdl2_image), Ptr{IMG_Animation}, (Ptr{Cchar},), file) end function IMG_LoadAnimation_RW(src, freesrc) ccall((:IMG_LoadAnimation_RW, libsdl2_image), Ptr{IMG_Animation}, (Ptr{SDL_RWops}, Cint), src, freesrc) end function IMG_LoadAnimationTyped_RW(src, freesrc, type) ccall((:IMG_LoadAnimationTyped_RW, libsdl2_image), Ptr{IMG_Animation}, (Ptr{SDL_RWops}, Cint, Ptr{Cchar}), src, freesrc, type) end function IMG_FreeAnimation(anim) ccall((:IMG_FreeAnimation, libsdl2_image), Cvoid, (Ptr{IMG_Animation},), anim) end function IMG_LoadGIFAnimation_RW(src) ccall((:IMG_LoadGIFAnimation_RW, libsdl2_image), Ptr{IMG_Animation}, (Ptr{SDL_RWops},), src) end mutable struct _TTF_Font end const TTF_Font = _TTF_Font function TTF_RenderText_Shaded(font, text, fg, bg) ccall((:TTF_RenderText_Shaded, libsdl2_ttf), Ptr{SDL_Surface}, (Ptr{TTF_Font}, Ptr{Cchar}, SDL_Color, SDL_Color), font, text, fg, bg) end function TTF_RenderUTF8_Shaded(font, text, fg, bg) ccall((:TTF_RenderUTF8_Shaded, libsdl2_ttf), Ptr{SDL_Surface}, (Ptr{TTF_Font}, Ptr{Cchar}, SDL_Color, SDL_Color), font, text, fg, bg) end function TTF_RenderUNICODE_Shaded(font, text, fg, bg) ccall((:TTF_RenderUNICODE_Shaded, libsdl2_ttf), Ptr{SDL_Surface}, (Ptr{TTF_Font}, Ptr{Uint16}, SDL_Color, SDL_Color), font, text, fg, bg) end function TTF_Linked_Version() ccall((:TTF_Linked_Version, libsdl2_ttf), Ptr{SDL_version}, ()) end function TTF_ByteSwappedUNICODE(swapped) ccall((:TTF_ByteSwappedUNICODE, libsdl2_ttf), Cvoid, (Cint,), swapped) end function TTF_Init() ccall((:TTF_Init, libsdl2_ttf), Cint, ()) end function TTF_OpenFont(file, ptsize) ccall((:TTF_OpenFont, libsdl2_ttf), Ptr{TTF_Font}, (Ptr{Cchar}, Cint), file, ptsize) end function TTF_OpenFontIndex(file, ptsize, index) ccall((:TTF_OpenFontIndex, libsdl2_ttf), Ptr{TTF_Font}, (Ptr{Cchar}, Cint, Clong), file, ptsize, index) end function TTF_OpenFontRW(src, freesrc, ptsize) ccall((:TTF_OpenFontRW, libsdl2_ttf), Ptr{TTF_Font}, (Ptr{SDL_RWops}, Cint, Cint), src, freesrc, ptsize) end function TTF_OpenFontIndexRW(src, freesrc, ptsize, index) ccall((:TTF_OpenFontIndexRW, libsdl2_ttf), Ptr{TTF_Font}, (Ptr{SDL_RWops}, Cint, Cint, Clong), src, freesrc, ptsize, index) end function TTF_GetFontStyle(font) ccall((:TTF_GetFontStyle, libsdl2_ttf), Cint, (Ptr{TTF_Font},), font) end function TTF_SetFontStyle(font, style) ccall((:TTF_SetFontStyle, libsdl2_ttf), Cvoid, (Ptr{TTF_Font}, Cint), font, style) end function TTF_GetFontOutline(font) ccall((:TTF_GetFontOutline, libsdl2_ttf), Cint, (Ptr{TTF_Font},), font) end function TTF_SetFontOutline(font, outline) ccall((:TTF_SetFontOutline, libsdl2_ttf), Cvoid, (Ptr{TTF_Font}, Cint), font, outline) end function TTF_GetFontHinting(font) ccall((:TTF_GetFontHinting, libsdl2_ttf), Cint, (Ptr{TTF_Font},), font) end function TTF_SetFontHinting(font, hinting) ccall((:TTF_SetFontHinting, libsdl2_ttf), Cvoid, (Ptr{TTF_Font}, Cint), font, hinting) end function TTF_FontHeight(font) ccall((:TTF_FontHeight, libsdl2_ttf), Cint, (Ptr{TTF_Font},), font) end function TTF_FontAscent(font) ccall((:TTF_FontAscent, libsdl2_ttf), Cint, (Ptr{TTF_Font},), font) end function TTF_FontDescent(font) ccall((:TTF_FontDescent, libsdl2_ttf), Cint, (Ptr{TTF_Font},), font) end function TTF_FontLineSkip(font) ccall((:TTF_FontLineSkip, libsdl2_ttf), Cint, (Ptr{TTF_Font},), font) end function TTF_GetFontKerning(font) ccall((:TTF_GetFontKerning, libsdl2_ttf), Cint, (Ptr{TTF_Font},), font) end function TTF_SetFontKerning(font, allowed) ccall((:TTF_SetFontKerning, libsdl2_ttf), Cvoid, (Ptr{TTF_Font}, Cint), font, allowed) end function TTF_FontFaces(font) ccall((:TTF_FontFaces, libsdl2_ttf), Clong, (Ptr{TTF_Font},), font) end function TTF_FontFaceIsFixedWidth(font) ccall((:TTF_FontFaceIsFixedWidth, libsdl2_ttf), Cint, (Ptr{TTF_Font},), font) end function TTF_FontFaceFamilyName(font) ccall((:TTF_FontFaceFamilyName, libsdl2_ttf), Ptr{Cchar}, (Ptr{TTF_Font},), font) end function TTF_FontFaceStyleName(font) ccall((:TTF_FontFaceStyleName, libsdl2_ttf), Ptr{Cchar}, (Ptr{TTF_Font},), font) end function TTF_GlyphIsProvided(font, ch) ccall((:TTF_GlyphIsProvided, libsdl2_ttf), Cint, (Ptr{TTF_Font}, Uint16), font, ch) end function TTF_GlyphMetrics(font, ch, minx, maxx, miny, maxy, advance) ccall((:TTF_GlyphMetrics, libsdl2_ttf), Cint, (Ptr{TTF_Font}, Uint16, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), font, ch, minx, maxx, miny, maxy, advance) end function TTF_SizeText(font, text, w, h) ccall((:TTF_SizeText, libsdl2_ttf), Cint, (Ptr{TTF_Font}, Ptr{Cchar}, Ptr{Cint}, Ptr{Cint}), font, text, w, h) end function TTF_SizeUTF8(font, text, w, h) ccall((:TTF_SizeUTF8, libsdl2_ttf), Cint, (Ptr{TTF_Font}, Ptr{Cchar}, Ptr{Cint}, Ptr{Cint}), font, text, w, h) end function TTF_SizeUNICODE(font, text, w, h) ccall((:TTF_SizeUNICODE, libsdl2_ttf), Cint, (Ptr{TTF_Font}, Ptr{Uint16}, Ptr{Cint}, Ptr{Cint}), font, text, w, h) end function TTF_RenderText_Solid(font, text, fg) ccall((:TTF_RenderText_Solid, libsdl2_ttf), Ptr{SDL_Surface}, (Ptr{TTF_Font}, Ptr{Cchar}, SDL_Color), font, text, fg) end function TTF_RenderUTF8_Solid(font, text, fg) ccall((:TTF_RenderUTF8_Solid, libsdl2_ttf), Ptr{SDL_Surface}, (Ptr{TTF_Font}, Ptr{Cchar}, SDL_Color), font, text, fg) end function TTF_RenderUNICODE_Solid(font, text, fg) ccall((:TTF_RenderUNICODE_Solid, libsdl2_ttf), Ptr{SDL_Surface}, (Ptr{TTF_Font}, Ptr{Uint16}, SDL_Color), font, text, fg) end function TTF_RenderGlyph_Solid(font, ch, fg) ccall((:TTF_RenderGlyph_Solid, libsdl2_ttf), Ptr{SDL_Surface}, (Ptr{TTF_Font}, Uint16, SDL_Color), font, ch, fg) end function TTF_RenderGlyph_Shaded(font, ch, fg, bg) ccall((:TTF_RenderGlyph_Shaded, libsdl2_ttf), Ptr{SDL_Surface}, (Ptr{TTF_Font}, Uint16, SDL_Color, SDL_Color), font, ch, fg, bg) end function TTF_RenderText_Blended(font, text, fg) ccall((:TTF_RenderText_Blended, libsdl2_ttf), Ptr{SDL_Surface}, (Ptr{TTF_Font}, Ptr{Cchar}, SDL_Color), font, text, fg) end function TTF_RenderUTF8_Blended(font, text, fg) ccall((:TTF_RenderUTF8_Blended, libsdl2_ttf), Ptr{SDL_Surface}, (Ptr{TTF_Font}, Ptr{Cchar}, SDL_Color), font, text, fg) end function TTF_RenderUNICODE_Blended(font, text, fg) ccall((:TTF_RenderUNICODE_Blended, libsdl2_ttf), Ptr{SDL_Surface}, (Ptr{TTF_Font}, Ptr{Uint16}, SDL_Color), font, text, fg) end function TTF_RenderText_Blended_Wrapped(font, text, fg, wrapLength) ccall((:TTF_RenderText_Blended_Wrapped, libsdl2_ttf), Ptr{SDL_Surface}, (Ptr{TTF_Font}, Ptr{Cchar}, SDL_Color, Uint32), font, text, fg, wrapLength) end function TTF_RenderUTF8_Blended_Wrapped(font, text, fg, wrapLength) ccall((:TTF_RenderUTF8_Blended_Wrapped, libsdl2_ttf), Ptr{SDL_Surface}, (Ptr{TTF_Font}, Ptr{Cchar}, SDL_Color, Uint32), font, text, fg, wrapLength) end function TTF_RenderUNICODE_Blended_Wrapped(font, text, fg, wrapLength) ccall((:TTF_RenderUNICODE_Blended_Wrapped, libsdl2_ttf), Ptr{SDL_Surface}, (Ptr{TTF_Font}, Ptr{Uint16}, SDL_Color, Uint32), font, text, fg, wrapLength) end function TTF_RenderGlyph_Blended(font, ch, fg) ccall((:TTF_RenderGlyph_Blended, libsdl2_ttf), Ptr{SDL_Surface}, (Ptr{TTF_Font}, Uint16, SDL_Color), font, ch, fg) end function TTF_CloseFont(font) ccall((:TTF_CloseFont, libsdl2_ttf), Cvoid, (Ptr{TTF_Font},), font) end function TTF_Quit() ccall((:TTF_Quit, libsdl2_ttf), Cvoid, ()) end function TTF_WasInit() ccall((:TTF_WasInit, libsdl2_ttf), Cint, ()) end function TTF_GetFontKerningSize(font, prev_index, index) ccall((:TTF_GetFontKerningSize, libsdl2_ttf), Cint, (Ptr{TTF_Font}, Cint, Cint), font, prev_index, index) end function TTF_GetFontKerningSizeGlyphs(font, previous_ch, ch) ccall((:TTF_GetFontKerningSizeGlyphs, libsdl2_ttf), Cint, (Ptr{TTF_Font}, Uint16, Uint16), font, previous_ch, ch) end struct FPSmanager framecount::Uint32 rateticks::Cfloat baseticks::Uint32 lastticks::Uint32 rate::Uint32 end function SDL_initFramerate(manager) ccall((:SDL_initFramerate, libsdl2_gfx), Cvoid, (Ptr{FPSmanager},), manager) end function SDL_setFramerate(manager, rate) ccall((:SDL_setFramerate, libsdl2_gfx), Cint, (Ptr{FPSmanager}, Uint32), manager, rate) end function SDL_getFramerate(manager) ccall((:SDL_getFramerate, libsdl2_gfx), Cint, (Ptr{FPSmanager},), manager) end function SDL_getFramecount(manager) ccall((:SDL_getFramecount, libsdl2_gfx), Cint, (Ptr{FPSmanager},), manager) end function SDL_framerateDelay(manager) ccall((:SDL_framerateDelay, libsdl2_gfx), Uint32, (Ptr{FPSmanager},), manager) end function pixelColor(renderer, x, y, color) ccall((:pixelColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Uint32), renderer, x, y, color) end function pixelRGBA(renderer, x, y, r, g, b, a) ccall((:pixelRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x, y, r, g, b, a) end function hlineColor(renderer, x1, x2, y, color) ccall((:hlineColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Uint32), renderer, x1, x2, y, color) end function hlineRGBA(renderer, x1, x2, y, r, g, b, a) ccall((:hlineRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x1, x2, y, r, g, b, a) end function vlineColor(renderer, x, y1, y2, color) ccall((:vlineColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Uint32), renderer, x, y1, y2, color) end function vlineRGBA(renderer, x, y1, y2, r, g, b, a) ccall((:vlineRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x, y1, y2, r, g, b, a) end function rectangleColor(renderer, x1, y1, x2, y2, color) ccall((:rectangleColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint32), renderer, x1, y1, x2, y2, color) end function rectangleRGBA(renderer, x1, y1, x2, y2, r, g, b, a) ccall((:rectangleRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x1, y1, x2, y2, r, g, b, a) end function roundedRectangleColor(renderer, x1, y1, x2, y2, rad, color) ccall((:roundedRectangleColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Uint32), renderer, x1, y1, x2, y2, rad, color) end function roundedRectangleRGBA(renderer, x1, y1, x2, y2, rad, r, g, b, a) ccall((:roundedRectangleRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x1, y1, x2, y2, rad, r, g, b, a) end function boxColor(renderer, x1, y1, x2, y2, color) ccall((:boxColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint32), renderer, x1, y1, x2, y2, color) end function boxRGBA(renderer, x1, y1, x2, y2, r, g, b, a) ccall((:boxRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x1, y1, x2, y2, r, g, b, a) end function roundedBoxColor(renderer, x1, y1, x2, y2, rad, color) ccall((:roundedBoxColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Uint32), renderer, x1, y1, x2, y2, rad, color) end function roundedBoxRGBA(renderer, x1, y1, x2, y2, rad, r, g, b, a) ccall((:roundedBoxRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x1, y1, x2, y2, rad, r, g, b, a) end function lineColor(renderer, x1, y1, x2, y2, color) ccall((:lineColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint32), renderer, x1, y1, x2, y2, color) end function lineRGBA(renderer, x1, y1, x2, y2, r, g, b, a) ccall((:lineRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x1, y1, x2, y2, r, g, b, a) end function aalineColor(renderer, x1, y1, x2, y2, color) ccall((:aalineColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint32), renderer, x1, y1, x2, y2, color) end function aalineRGBA(renderer, x1, y1, x2, y2, r, g, b, a) ccall((:aalineRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x1, y1, x2, y2, r, g, b, a) end function thickLineColor(renderer, x1, y1, x2, y2, width, color) ccall((:thickLineColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint8, Uint32), renderer, x1, y1, x2, y2, width, color) end function thickLineRGBA(renderer, x1, y1, x2, y2, width, r, g, b, a) ccall((:thickLineRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8, Uint8), renderer, x1, y1, x2, y2, width, r, g, b, a) end function circleColor(renderer, x, y, rad, color) ccall((:circleColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Uint32), renderer, x, y, rad, color) end function circleRGBA(renderer, x, y, rad, r, g, b, a) ccall((:circleRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x, y, rad, r, g, b, a) end function arcColor(renderer, x, y, rad, start, _end, color) ccall((:arcColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Uint32), renderer, x, y, rad, start, _end, color) end function arcRGBA(renderer, x, y, rad, start, _end, r, g, b, a) ccall((:arcRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x, y, rad, start, _end, r, g, b, a) end function aacircleColor(renderer, x, y, rad, color) ccall((:aacircleColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Uint32), renderer, x, y, rad, color) end function aacircleRGBA(renderer, x, y, rad, r, g, b, a) ccall((:aacircleRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x, y, rad, r, g, b, a) end function filledCircleColor(renderer, x, y, r, color) ccall((:filledCircleColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Uint32), renderer, x, y, r, color) end function filledCircleRGBA(renderer, x, y, rad, r, g, b, a) ccall((:filledCircleRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x, y, rad, r, g, b, a) end function ellipseColor(renderer, x, y, rx, ry, color) ccall((:ellipseColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint32), renderer, x, y, rx, ry, color) end function ellipseRGBA(renderer, x, y, rx, ry, r, g, b, a) ccall((:ellipseRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x, y, rx, ry, r, g, b, a) end function aaellipseColor(renderer, x, y, rx, ry, color) ccall((:aaellipseColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint32), renderer, x, y, rx, ry, color) end function aaellipseRGBA(renderer, x, y, rx, ry, r, g, b, a) ccall((:aaellipseRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x, y, rx, ry, r, g, b, a) end function filledEllipseColor(renderer, x, y, rx, ry, color) ccall((:filledEllipseColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint32), renderer, x, y, rx, ry, color) end function filledEllipseRGBA(renderer, x, y, rx, ry, r, g, b, a) ccall((:filledEllipseRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x, y, rx, ry, r, g, b, a) end function pieColor(renderer, x, y, rad, start, _end, color) ccall((:pieColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Uint32), renderer, x, y, rad, start, _end, color) end function pieRGBA(renderer, x, y, rad, start, _end, r, g, b, a) ccall((:pieRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x, y, rad, start, _end, r, g, b, a) end function filledPieColor(renderer, x, y, rad, start, _end, color) ccall((:filledPieColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Uint32), renderer, x, y, rad, start, _end, color) end function filledPieRGBA(renderer, x, y, rad, start, _end, r, g, b, a) ccall((:filledPieRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x, y, rad, start, _end, r, g, b, a) end function trigonColor(renderer, x1, y1, x2, y2, x3, y3, color) ccall((:trigonColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Sint16, Uint32), renderer, x1, y1, x2, y2, x3, y3, color) end function trigonRGBA(renderer, x1, y1, x2, y2, x3, y3, r, g, b, a) ccall((:trigonRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x1, y1, x2, y2, x3, y3, r, g, b, a) end function aatrigonColor(renderer, x1, y1, x2, y2, x3, y3, color) ccall((:aatrigonColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Sint16, Uint32), renderer, x1, y1, x2, y2, x3, y3, color) end function aatrigonRGBA(renderer, x1, y1, x2, y2, x3, y3, r, g, b, a) ccall((:aatrigonRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x1, y1, x2, y2, x3, y3, r, g, b, a) end function filledTrigonColor(renderer, x1, y1, x2, y2, x3, y3, color) ccall((:filledTrigonColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Sint16, Uint32), renderer, x1, y1, x2, y2, x3, y3, color) end function filledTrigonRGBA(renderer, x1, y1, x2, y2, x3, y3, r, g, b, a) ccall((:filledTrigonRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Sint16, Sint16, Sint16, Sint16, Uint8, Uint8, Uint8, Uint8), renderer, x1, y1, x2, y2, x3, y3, r, g, b, a) end function polygonColor(renderer, vx, vy, n, color) ccall((:polygonColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Ptr{Sint16}, Ptr{Sint16}, Cint, Uint32), renderer, vx, vy, n, color) end function polygonRGBA(renderer, vx, vy, n, r, g, b, a) ccall((:polygonRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Ptr{Sint16}, Ptr{Sint16}, Cint, Uint8, Uint8, Uint8, Uint8), renderer, vx, vy, n, r, g, b, a) end function aapolygonColor(renderer, vx, vy, n, color) ccall((:aapolygonColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Ptr{Sint16}, Ptr{Sint16}, Cint, Uint32), renderer, vx, vy, n, color) end function aapolygonRGBA(renderer, vx, vy, n, r, g, b, a) ccall((:aapolygonRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Ptr{Sint16}, Ptr{Sint16}, Cint, Uint8, Uint8, Uint8, Uint8), renderer, vx, vy, n, r, g, b, a) end function filledPolygonColor(renderer, vx, vy, n, color) ccall((:filledPolygonColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Ptr{Sint16}, Ptr{Sint16}, Cint, Uint32), renderer, vx, vy, n, color) end function filledPolygonRGBA(renderer, vx, vy, n, r, g, b, a) ccall((:filledPolygonRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Ptr{Sint16}, Ptr{Sint16}, Cint, Uint8, Uint8, Uint8, Uint8), renderer, vx, vy, n, r, g, b, a) end function texturedPolygon(renderer, vx, vy, n, texture, texture_dx, texture_dy) ccall((:texturedPolygon, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Ptr{Sint16}, Ptr{Sint16}, Cint, Ptr{SDL_Surface}, Cint, Cint), renderer, vx, vy, n, texture, texture_dx, texture_dy) end function bezierColor(renderer, vx, vy, n, s, color) ccall((:bezierColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Ptr{Sint16}, Ptr{Sint16}, Cint, Cint, Uint32), renderer, vx, vy, n, s, color) end function bezierRGBA(renderer, vx, vy, n, s, r, g, b, a) ccall((:bezierRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Ptr{Sint16}, Ptr{Sint16}, Cint, Cint, Uint8, Uint8, Uint8, Uint8), renderer, vx, vy, n, s, r, g, b, a) end function gfxPrimitivesSetFont(fontdata, cw, ch) ccall((:gfxPrimitivesSetFont, libsdl2_gfx), Cvoid, (Ptr{Cvoid}, Uint32, Uint32), fontdata, cw, ch) end function gfxPrimitivesSetFontRotation(rotation) ccall((:gfxPrimitivesSetFontRotation, libsdl2_gfx), Cvoid, (Uint32,), rotation) end function characterColor(renderer, x, y, c, color) ccall((:characterColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Cchar, Uint32), renderer, x, y, c, color) end function characterRGBA(renderer, x, y, c, r, g, b, a) ccall((:characterRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Cchar, Uint8, Uint8, Uint8, Uint8), renderer, x, y, c, r, g, b, a) end function stringColor(renderer, x, y, s, color) ccall((:stringColor, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Ptr{Cchar}, Uint32), renderer, x, y, s, color) end function stringRGBA(renderer, x, y, s, r, g, b, a) ccall((:stringRGBA, libsdl2_gfx), Cint, (Ptr{SDL_Renderer}, Sint16, Sint16, Ptr{Cchar}, Uint8, Uint8, Uint8, Uint8), renderer, x, y, s, r, g, b, a) end function SDL_imageFilterMMXdetect() ccall((:SDL_imageFilterMMXdetect, libsdl2_gfx), Cint, ()) end function SDL_imageFilterMMXoff() ccall((:SDL_imageFilterMMXoff, libsdl2_gfx), Cvoid, ()) end function SDL_imageFilterMMXon() ccall((:SDL_imageFilterMMXon, libsdl2_gfx), Cvoid, ()) end function SDL_imageFilterAdd(Src1, Src2, Dest, length) ccall((:SDL_imageFilterAdd, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Ptr{Cuchar}, Cuint), Src1, Src2, Dest, length) end function SDL_imageFilterMean(Src1, Src2, Dest, length) ccall((:SDL_imageFilterMean, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Ptr{Cuchar}, Cuint), Src1, Src2, Dest, length) end function SDL_imageFilterSub(Src1, Src2, Dest, length) ccall((:SDL_imageFilterSub, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Ptr{Cuchar}, Cuint), Src1, Src2, Dest, length) end function SDL_imageFilterAbsDiff(Src1, Src2, Dest, length) ccall((:SDL_imageFilterAbsDiff, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Ptr{Cuchar}, Cuint), Src1, Src2, Dest, length) end function SDL_imageFilterMult(Src1, Src2, Dest, length) ccall((:SDL_imageFilterMult, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Ptr{Cuchar}, Cuint), Src1, Src2, Dest, length) end function SDL_imageFilterMultNor(Src1, Src2, Dest, length) ccall((:SDL_imageFilterMultNor, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Ptr{Cuchar}, Cuint), Src1, Src2, Dest, length) end function SDL_imageFilterMultDivby2(Src1, Src2, Dest, length) ccall((:SDL_imageFilterMultDivby2, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Ptr{Cuchar}, Cuint), Src1, Src2, Dest, length) end function SDL_imageFilterMultDivby4(Src1, Src2, Dest, length) ccall((:SDL_imageFilterMultDivby4, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Ptr{Cuchar}, Cuint), Src1, Src2, Dest, length) end function SDL_imageFilterBitAnd(Src1, Src2, Dest, length) ccall((:SDL_imageFilterBitAnd, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Ptr{Cuchar}, Cuint), Src1, Src2, Dest, length) end function SDL_imageFilterBitOr(Src1, Src2, Dest, length) ccall((:SDL_imageFilterBitOr, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Ptr{Cuchar}, Cuint), Src1, Src2, Dest, length) end function SDL_imageFilterDiv(Src1, Src2, Dest, length) ccall((:SDL_imageFilterDiv, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Ptr{Cuchar}, Cuint), Src1, Src2, Dest, length) end function SDL_imageFilterBitNegation(Src1, Dest, length) ccall((:SDL_imageFilterBitNegation, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint), Src1, Dest, length) end function SDL_imageFilterAddByte(Src1, Dest, length, C) ccall((:SDL_imageFilterAddByte, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint, Cuchar), Src1, Dest, length, C) end function SDL_imageFilterAddUint(Src1, Dest, length, C) ccall((:SDL_imageFilterAddUint, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint, Cuint), Src1, Dest, length, C) end function SDL_imageFilterAddByteToHalf(Src1, Dest, length, C) ccall((:SDL_imageFilterAddByteToHalf, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint, Cuchar), Src1, Dest, length, C) end function SDL_imageFilterSubByte(Src1, Dest, length, C) ccall((:SDL_imageFilterSubByte, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint, Cuchar), Src1, Dest, length, C) end function SDL_imageFilterSubUint(Src1, Dest, length, C) ccall((:SDL_imageFilterSubUint, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint, Cuint), Src1, Dest, length, C) end function SDL_imageFilterShiftRight(Src1, Dest, length, N) ccall((:SDL_imageFilterShiftRight, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint, Cuchar), Src1, Dest, length, N) end function SDL_imageFilterShiftRightUint(Src1, Dest, length, N) ccall((:SDL_imageFilterShiftRightUint, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint, Cuchar), Src1, Dest, length, N) end function SDL_imageFilterMultByByte(Src1, Dest, length, C) ccall((:SDL_imageFilterMultByByte, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint, Cuchar), Src1, Dest, length, C) end function SDL_imageFilterShiftRightAndMultByByte(Src1, Dest, length, N, C) ccall((:SDL_imageFilterShiftRightAndMultByByte, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint, Cuchar, Cuchar), Src1, Dest, length, N, C) end function SDL_imageFilterShiftLeftByte(Src1, Dest, length, N) ccall((:SDL_imageFilterShiftLeftByte, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint, Cuchar), Src1, Dest, length, N) end function SDL_imageFilterShiftLeftUint(Src1, Dest, length, N) ccall((:SDL_imageFilterShiftLeftUint, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint, Cuchar), Src1, Dest, length, N) end function SDL_imageFilterShiftLeft(Src1, Dest, length, N) ccall((:SDL_imageFilterShiftLeft, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint, Cuchar), Src1, Dest, length, N) end function SDL_imageFilterBinarizeUsingThreshold(Src1, Dest, length, T) ccall((:SDL_imageFilterBinarizeUsingThreshold, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint, Cuchar), Src1, Dest, length, T) end function SDL_imageFilterClipToRange(Src1, Dest, length, Tmin, Tmax) ccall((:SDL_imageFilterClipToRange, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint, Cuchar, Cuchar), Src1, Dest, length, Tmin, Tmax) end function SDL_imageFilterNormalizeLinear(Src, Dest, length, Cmin, Cmax, Nmin, Nmax) ccall((:SDL_imageFilterNormalizeLinear, libsdl2_gfx), Cint, (Ptr{Cuchar}, Ptr{Cuchar}, Cuint, Cint, Cint, Cint, Cint), Src, Dest, length, Cmin, Cmax, Nmin, Nmax) end function rotozoomSurface(src, angle, zoom, smooth) ccall((:rotozoomSurface, libsdl2_gfx), Ptr{SDL_Surface}, (Ptr{SDL_Surface}, Cdouble, Cdouble, Cint), src, angle, zoom, smooth) end function rotozoomSurfaceXY(src, angle, zoomx, zoomy, smooth) ccall((:rotozoomSurfaceXY, libsdl2_gfx), Ptr{SDL_Surface}, (Ptr{SDL_Surface}, Cdouble, Cdouble, Cdouble, Cint), src, angle, zoomx, zoomy, smooth) end function rotozoomSurfaceSize(width, height, angle, zoom, dstwidth, dstheight) ccall((:rotozoomSurfaceSize, libsdl2_gfx), Cvoid, (Cint, Cint, Cdouble, Cdouble, Ptr{Cint}, Ptr{Cint}), width, height, angle, zoom, dstwidth, dstheight) end function rotozoomSurfaceSizeXY(width, height, angle, zoomx, zoomy, dstwidth, dstheight) ccall((:rotozoomSurfaceSizeXY, libsdl2_gfx), Cvoid, (Cint, Cint, Cdouble, Cdouble, Cdouble, Ptr{Cint}, Ptr{Cint}), width, height, angle, zoomx, zoomy, dstwidth, dstheight) end function zoomSurface(src, zoomx, zoomy, smooth) ccall((:zoomSurface, libsdl2_gfx), Ptr{SDL_Surface}, (Ptr{SDL_Surface}, Cdouble, Cdouble, Cint), src, zoomx, zoomy, smooth) end function zoomSurfaceSize(width, height, zoomx, zoomy, dstwidth, dstheight) ccall((:zoomSurfaceSize, libsdl2_gfx), Cvoid, (Cint, Cint, Cdouble, Cdouble, Ptr{Cint}, Ptr{Cint}), width, height, zoomx, zoomy, dstwidth, dstheight) end function shrinkSurface(src, factorx, factory) ccall((:shrinkSurface, libsdl2_gfx), Ptr{SDL_Surface}, (Ptr{SDL_Surface}, Cint, Cint), src, factorx, factory) end function rotateSurface90Degrees(src, numClockwiseTurns) ccall((:rotateSurface90Degrees, libsdl2_gfx), Ptr{SDL_Surface}, (Ptr{SDL_Surface}, Cint), src, numClockwiseTurns) end struct __JL_Ctag_560 autoclose::SDL_bool fp::Ptr{Libc.FILE} end function Base.getproperty(x::Ptr{__JL_Ctag_560}, f::Symbol) f === :autoclose && return Ptr{SDL_bool}(x + 0) f === :fp && return Ptr{Ptr{Libc.FILE}}(x + 8) return getfield(x, f) end function Base.getproperty(x::__JL_Ctag_560, f::Symbol) r = Ref{__JL_Ctag_560}(x) ptr = Base.unsafe_convert(Ptr{__JL_Ctag_560}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{__JL_Ctag_560}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end struct __JL_Ctag_561 base::Ptr{Uint8} here::Ptr{Uint8} stop::Ptr{Uint8} end function Base.getproperty(x::Ptr{__JL_Ctag_561}, f::Symbol) f === :base && return Ptr{Ptr{Uint8}}(x + 0) f === :here && return Ptr{Ptr{Uint8}}(x + 8) f === :stop && return Ptr{Ptr{Uint8}}(x + 16) return getfield(x, f) end function Base.getproperty(x::__JL_Ctag_561, f::Symbol) r = Ref{__JL_Ctag_561}(x) ptr = Base.unsafe_convert(Ptr{__JL_Ctag_561}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{__JL_Ctag_561}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end struct __JL_Ctag_562 data1::Ptr{Cvoid} data2::Ptr{Cvoid} end function Base.getproperty(x::Ptr{__JL_Ctag_562}, f::Symbol) f === :data1 && return Ptr{Ptr{Cvoid}}(x + 0) f === :data2 && return Ptr{Ptr{Cvoid}}(x + 8) return getfield(x, f) end function Base.getproperty(x::__JL_Ctag_562, f::Symbol) r = Ref{__JL_Ctag_562}(x) ptr = Base.unsafe_convert(Ptr{__JL_Ctag_562}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{__JL_Ctag_562}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end struct __JL_Ctag_564 hat::Cint hat_mask::Cint end function Base.getproperty(x::Ptr{__JL_Ctag_564}, f::Symbol) f === :hat && return Ptr{Cint}(x + 0) f === :hat_mask && return Ptr{Cint}(x + 4) return getfield(x, f) end function Base.getproperty(x::__JL_Ctag_564, f::Symbol) r = Ref{__JL_Ctag_564}(x) ptr = Base.unsafe_convert(Ptr{__JL_Ctag_564}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{__JL_Ctag_564}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end const __LINUX__ = 1 # Skipping MacroDefinition: SDL_DEPRECATED __attribute__ ( ( deprecated ) ) # Skipping MacroDefinition: SDL_UNUSED __attribute__ ( ( unused ) ) # Skipping MacroDefinition: DECLSPEC __attribute__ ( ( visibility ( "default" ) ) ) # Skipping MacroDefinition: SDL_INLINE __inline__ # Skipping MacroDefinition: SDL_FORCE_INLINE __attribute__ ( ( always_inline ) ) static __inline__ # Skipping MacroDefinition: SDL_NORETURN __attribute__ ( ( noreturn ) ) # Skipping MacroDefinition: NULL ( ( void * ) 0 ) # Skipping MacroDefinition: SDL_FALLTHROUGH __attribute__ ( ( __fallthrough__ ) ) const SIZEOF_VOIDP = 8 const HAVE_GCC_ATOMICS = 1 const HAVE_LIBC = 1 const STDC_HEADERS = 1 const HAVE_DLOPEN = 1 const HAVE_MALLOC = 1 const HAVE_CALLOC = 1 const HAVE_REALLOC = 1 const HAVE_FREE = 1 const HAVE_ALLOCA = 1 const HAVE_GETENV = 1 const HAVE_SETENV = 1 const HAVE_PUTENV = 1 const HAVE_UNSETENV = 1 const HAVE_QSORT = 1 const HAVE_BSEARCH = 1 const HAVE_ABS = 1 const HAVE_BCOPY = 1 const HAVE_MEMSET = 1 const HAVE_MEMCPY = 1 const HAVE_MEMMOVE = 1 const HAVE_MEMCMP = 1 const HAVE_WCSLEN = 1 const HAVE_WCSDUP = 1 const HAVE_WCSSTR = 1 const HAVE_WCSCMP = 1 const HAVE_WCSNCMP = 1 const HAVE_WCSCASECMP = 1 const HAVE_WCSNCASECMP = 1 const HAVE_STRLEN = 1 const HAVE_INDEX = 1 const HAVE_RINDEX = 1 const HAVE_STRCHR = 1 const HAVE_STRRCHR = 1 const HAVE_STRSTR = 1 const HAVE_STRTOK_R = 1 const HAVE_STRTOL = 1 const HAVE_STRTOUL = 1 const HAVE_STRTOLL = 1 const HAVE_STRTOULL = 1 const HAVE_STRTOD = 1 const HAVE_ATOI = 1 const HAVE_ATOF = 1 const HAVE_STRCMP = 1 const HAVE_STRNCMP = 1 const HAVE_STRCASECMP = 1 const HAVE_STRNCASECMP = 1 const HAVE_VSSCANF = 1 const HAVE_VSNPRINTF = 1 const HAVE_ACOS = 1 const HAVE_ACOSF = 1 const HAVE_ASIN = 1 const HAVE_ASINF = 1 const HAVE_ATAN = 1 const HAVE_ATANF = 1 const HAVE_ATAN2 = 1 const HAVE_ATAN2F = 1 const HAVE_CEIL = 1 const HAVE_CEILF = 1 const HAVE_COPYSIGN = 1 const HAVE_COPYSIGNF = 1 const HAVE_COS = 1 const HAVE_COSF = 1 const HAVE_EXP = 1 const HAVE_EXPF = 1 const HAVE_FABS = 1 const HAVE_FABSF = 1 const HAVE_FLOOR = 1 const HAVE_FLOORF = 1 const HAVE_FMOD = 1 const HAVE_FMODF = 1 const HAVE_LOG = 1 const HAVE_LOGF = 1 const HAVE_LOG10 = 1 const HAVE_LOG10F = 1 const HAVE_LROUND = 1 const HAVE_LROUNDF = 1 const HAVE_POW = 1 const HAVE_POWF = 1 const HAVE_ROUND = 1 const HAVE_ROUNDF = 1 const HAVE_SCALBN = 1 const HAVE_SCALBNF = 1 const HAVE_SIN = 1 const HAVE_SINF = 1 const HAVE_SQRT = 1 const HAVE_SQRTF = 1 const HAVE_TAN = 1 const HAVE_TANF = 1 const HAVE_TRUNC = 1 const HAVE_TRUNCF = 1 const HAVE_FOPEN64 = 1 const HAVE_FSEEKO = 1 const HAVE_FSEEKO64 = 1 const HAVE_SIGACTION = 1 const HAVE_SA_SIGACTION = 1 const HAVE_SETJMP = 1 const HAVE_NANOSLEEP = 1 const HAVE_SYSCONF = 1 const HAVE_CLOCK_GETTIME = 1 const HAVE_MPROTECT = 1 const HAVE_ICONV = 1 const HAVE_PTHREAD_SETNAME_NP = 1 const HAVE_SEM_TIMEDWAIT = 1 const HAVE_POLL = 1 const HAVE__EXIT = 1 const HAVE_O_CLOEXEC = 1 const HAVE_FCITX = 1 const HAVE_INOTIFY_INIT = 1 const HAVE_INOTIFY_INIT1 = 1 const HAVE_INOTIFY = 1 const SDL_AUDIO_DRIVER_ALSA = 1 const SDL_AUDIO_DRIVER_DISK = 1 const SDL_AUDIO_DRIVER_DUMMY = 1 const SDL_AUDIO_DRIVER_OSS = 1 const SDL_AUDIO_DRIVER_PULSEAUDIO = 1 const SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC = "libpulse-simple.so.0" const SDL_INPUT_LINUXEV = 1 const SDL_INPUT_LINUXKD = 1 const SDL_JOYSTICK_LINUX = 1 const SDL_JOYSTICK_HIDAPI = 1 const SDL_JOYSTICK_VIRTUAL = 1 const SDL_HAPTIC_LINUX = 1 const SDL_SENSOR_DUMMY = 1 const SDL_LOADSO_DLOPEN = 1 const SDL_THREAD_PTHREAD = 1 const SDL_THREAD_PTHREAD_RECURSIVE_MUTEX = 1 const SDL_TIMER_UNIX = 1 const SDL_VIDEO_DRIVER_DUMMY = 1 const SDL_VIDEO_DRIVER_X11 = 1 const SDL_VIDEO_DRIVER_X11_XCURSOR = 1 const SDL_VIDEO_DRIVER_X11_XDBE = 1 const SDL_VIDEO_DRIVER_X11_XRANDR = 1 const SDL_VIDEO_DRIVER_X11_XSCRNSAVER = 1 const SDL_VIDEO_DRIVER_X11_XSHAPE = 1 const SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS = 1 const SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM = 1 const SDL_VIDEO_RENDER_OGL = 1 const SDL_VIDEO_RENDER_OGL_ES = 1 const SDL_VIDEO_RENDER_OGL_ES2 = 1 const SDL_VIDEO_OPENGL = 1 const SDL_VIDEO_OPENGL_ES = 1 const SDL_VIDEO_OPENGL_ES2 = 1 const SDL_VIDEO_OPENGL_EGL = 1 const SDL_VIDEO_OPENGL_GLX = 1 const SDL_VIDEO_VULKAN = 1 const SDL_POWER_LINUX = 1 const SDL_FILESYSTEM_UNIX = 1 const DYNAPI_NEEDS_DLOPEN = 1 const SDL_USE_IME = 1 const SDL_MAX_SINT8 = Sint8(0x7f) const SDL_MAX_UINT8 = Uint8(0xff) const SDL_MIN_UINT8 = Uint8(0x00) const SDL_MAX_SINT16 = Sint16(0x7fff) const SDL_MAX_UINT16 = Uint16(0xffff) const SDL_MIN_UINT16 = Uint16(0x0000) const SDL_MAX_SINT32 = Sint32(0x7fffffff) const SDL_MAX_UINT32 = Uint32(Cuint(0xffffffff)) const SDL_MIN_UINT32 = Uint32(0x00000000) const SDL_MAX_SINT64 = Sint64(Clonglong(0x7fffffffffffffff)) const SDL_MAX_UINT64 = Uint64(Culonglong(0xffffffffffffffff)) const SDL_MIN_UINT64 = Uint64(Culonglong(0x0000000000000000)) const SDL_PRIs64 = "ld" const SDL_ASSERT_LEVEL = 2 # Skipping MacroDefinition: SDL_FUNCTION __func__ const SDL_NULL_WHILE_LOOP_CONDITION = 0 const SDL_assert_state = SDL_AssertState const SDL_assert_data = SDL_AssertData const SDL_LIL_ENDIAN = 1234 const SDL_BIG_ENDIAN = 4321 const SDL_MUTEX_TIMEDOUT = 1 const SDL_MUTEX_MAXWAIT = ~(Uint32(0)) const SDL_RWOPS_UNKNOWN = Cuint(0) const SDL_RWOPS_WINFILE = Cuint(1) const SDL_RWOPS_STDFILE = Cuint(2) const SDL_RWOPS_JNIFILE = Cuint(3) const SDL_RWOPS_MEMORY = Cuint(4) const SDL_RWOPS_MEMORY_RO = Cuint(5) const RW_SEEK_SET = 0 const RW_SEEK_CUR = 1 const RW_SEEK_END = 2 const SDL_AUDIO_MASK_BITSIZE = 0xff const SDL_AUDIO_MASK_DATATYPE = 1 << 8 const SDL_AUDIO_MASK_ENDIAN = 1 << 12 const SDL_AUDIO_MASK_SIGNED = 1 << 15 const AUDIO_U8 = 0x0008 const AUDIO_S8 = 0x8008 const AUDIO_U16LSB = 0x0010 const AUDIO_S16LSB = 0x8010 const AUDIO_U16MSB = 0x1010 const AUDIO_S16MSB = 0x9010 const AUDIO_U16 = AUDIO_U16LSB const AUDIO_S16 = AUDIO_S16LSB const AUDIO_S32LSB = 0x8020 const AUDIO_S32MSB = 0x9020 const AUDIO_S32 = AUDIO_S32LSB const AUDIO_F32LSB = 0x8120 const AUDIO_F32MSB = 0x9120 const AUDIO_F32 = AUDIO_F32LSB const AUDIO_U16SYS = AUDIO_U16LSB const AUDIO_S16SYS = AUDIO_S16LSB const AUDIO_S32SYS = AUDIO_S32LSB const AUDIO_F32SYS = AUDIO_F32LSB const SDL_AUDIO_ALLOW_FREQUENCY_CHANGE = 0x00000001 const SDL_AUDIO_ALLOW_FORMAT_CHANGE = 0x00000002 const SDL_AUDIO_ALLOW_CHANNELS_CHANGE = 0x00000004 const SDL_AUDIO_ALLOW_SAMPLES_CHANGE = 0x00000008 const SDL_AUDIO_ALLOW_ANY_CHANGE = ((SDL_AUDIO_ALLOW_FREQUENCY_CHANGE | SDL_AUDIO_ALLOW_FORMAT_CHANGE) | SDL_AUDIO_ALLOW_CHANNELS_CHANGE) | SDL_AUDIO_ALLOW_SAMPLES_CHANGE const SDL_AUDIOCVT_MAX_FILTERS = 9 # Skipping MacroDefinition: SDL_AUDIOCVT_PACKED __attribute__ ( ( packed ) ) const SDL_MIX_MAXVOLUME = 128 const SDL_CACHELINE_SIZE = 128 const SDL_ALPHA_OPAQUE = 255 const SDL_ALPHA_TRANSPARENT = 0 const SDL_Colour = SDL_Color const SDL_SWSURFACE = 0 const SDL_PREALLOC = 0x00000001 const SDL_RLEACCEL = 0x00000002 const SDL_DONTFREE = 0x00000004 const SDL_SIMD_ALIGNED = 0x00000008 const SDL_BlitSurface = SDL_UpperBlit const SDL_BlitScaled = SDL_UpperBlitScaled const SDL_WINDOWPOS_UNDEFINED_MASK = Cuint(0x1fff0000) SDL_WINDOWPOS_UNDEFINED_DISPLAY(X) = SDL_WINDOWPOS_UNDEFINED_MASK | X const SDL_WINDOWPOS_UNDEFINED = SDL_WINDOWPOS_UNDEFINED_DISPLAY(0) const SDL_WINDOWPOS_CENTERED_MASK = Cuint(0x2fff0000) SDL_WINDOWPOS_CENTERED_DISPLAY(X) = SDL_WINDOWPOS_CENTERED_MASK | X const SDL_WINDOWPOS_CENTERED = SDL_WINDOWPOS_CENTERED_DISPLAY(0) const SDLK_SCANCODE_MASK = 1 << 30 SDL_BUTTON(X) = 1 << (X - 1) const SDL_BUTTON_LEFT = 1 const SDL_BUTTON_MIDDLE = 2 const SDL_BUTTON_RIGHT = 3 const SDL_BUTTON_X1 = 4 const SDL_BUTTON_X2 = 5 const SDL_BUTTON_LMASK = SDL_BUTTON(SDL_BUTTON_LEFT) const SDL_BUTTON_MMASK = SDL_BUTTON(SDL_BUTTON_MIDDLE) const SDL_BUTTON_RMASK = SDL_BUTTON(SDL_BUTTON_RIGHT) const SDL_BUTTON_X1MASK = SDL_BUTTON(SDL_BUTTON_X1) const SDL_BUTTON_X2MASK = SDL_BUTTON(SDL_BUTTON_X2) const SDL_IPHONE_MAX_GFORCE = 5.0 const SDL_VIRTUAL_JOYSTICK_DESC_VERSION = 1 const SDL_JOYSTICK_AXIS_MAX = 32767 const SDL_JOYSTICK_AXIS_MIN = -32768 const SDL_HAT_CENTERED = 0x00 const SDL_HAT_UP = 0x01 const SDL_HAT_RIGHT = 0x02 const SDL_HAT_DOWN = 0x04 const SDL_HAT_LEFT = 0x08 const SDL_HAT_RIGHTUP = SDL_HAT_RIGHT | SDL_HAT_UP const SDL_HAT_RIGHTDOWN = SDL_HAT_RIGHT | SDL_HAT_DOWN const SDL_HAT_LEFTUP = SDL_HAT_LEFT | SDL_HAT_UP const SDL_HAT_LEFTDOWN = SDL_HAT_LEFT | SDL_HAT_DOWN const SDL_STANDARD_GRAVITY = Float32(9.80665) const SDL_MOUSE_TOUCHID = Sint64(-1) const SDL_RELEASED = 0 const SDL_PRESSED = 1 const SDL_TEXTEDITINGEVENT_TEXT_SIZE = 32 const SDL_TEXTINPUTEVENT_TEXT_SIZE = 32 const SDL_QUERY = -1 const SDL_IGNORE = 0 const SDL_DISABLE = 0 const SDL_ENABLE = 1 const SDL_HAPTIC_CONSTANT = Cuint(1) << 0 const SDL_HAPTIC_SINE = Cuint(1) << 1 const SDL_HAPTIC_LEFTRIGHT = Cuint(1) << 2 const SDL_HAPTIC_TRIANGLE = Cuint(1) << 3 const SDL_HAPTIC_SAWTOOTHUP = Cuint(1) << 4 const SDL_HAPTIC_SAWTOOTHDOWN = Cuint(1) << 5 const SDL_HAPTIC_RAMP = Cuint(1) << 6 const SDL_HAPTIC_SPRING = Cuint(1) << 7 const SDL_HAPTIC_DAMPER = Cuint(1) << 8 const SDL_HAPTIC_INERTIA = Cuint(1) << 9 const SDL_HAPTIC_FRICTION = Cuint(1) << 10 const SDL_HAPTIC_CUSTOM = Cuint(1) << 11 const SDL_HAPTIC_GAIN = Cuint(1) << 12 const SDL_HAPTIC_AUTOCENTER = Cuint(1) << 13 const SDL_HAPTIC_STATUS = Cuint(1) << 14 const SDL_HAPTIC_PAUSE = Cuint(1) << 15 const SDL_HAPTIC_POLAR = 0 const SDL_HAPTIC_CARTESIAN = 1 const SDL_HAPTIC_SPHERICAL = 2 const SDL_HAPTIC_STEERING_AXIS = 3 const SDL_HAPTIC_INFINITY = Cuint(4294967295) const SDL_HINT_ACCELEROMETER_AS_JOYSTICK = "SDL_ACCELEROMETER_AS_JOYSTICK" const SDL_HINT_ALLOW_ALT_TAB_WHILE_GRABBED = "SDL_ALLOW_ALT_TAB_WHILE_GRABBED" const SDL_HINT_ALLOW_TOPMOST = "SDL_ALLOW_TOPMOST" const SDL_HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION = "SDL_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION" const SDL_HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION = "SDL_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION" const SDL_HINT_ANDROID_BLOCK_ON_PAUSE = "SDL_ANDROID_BLOCK_ON_PAUSE" const SDL_HINT_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO = "SDL_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO" const SDL_HINT_ANDROID_TRAP_BACK_BUTTON = "SDL_ANDROID_TRAP_BACK_BUTTON" const SDL_HINT_APP_NAME = "SDL_APP_NAME" const SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS = "SDL_APPLE_TV_CONTROLLER_UI_EVENTS" const SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION = "SDL_APPLE_TV_REMOTE_ALLOW_ROTATION" const SDL_HINT_AUDIO_CATEGORY = "SDL_AUDIO_CATEGORY" const SDL_HINT_AUDIO_DEVICE_APP_NAME = "SDL_AUDIO_DEVICE_APP_NAME" const SDL_HINT_AUDIO_DEVICE_STREAM_NAME = "SDL_AUDIO_DEVICE_STREAM_NAME" const SDL_HINT_AUDIO_DEVICE_STREAM_ROLE = "SDL_AUDIO_DEVICE_STREAM_ROLE" const SDL_HINT_AUDIO_RESAMPLING_MODE = "SDL_AUDIO_RESAMPLING_MODE" const SDL_HINT_AUTO_UPDATE_JOYSTICKS = "SDL_AUTO_UPDATE_JOYSTICKS" const SDL_HINT_AUTO_UPDATE_SENSORS = "SDL_AUTO_UPDATE_SENSORS" const SDL_HINT_BMP_SAVE_LEGACY_FORMAT = "SDL_BMP_SAVE_LEGACY_FORMAT" const SDL_HINT_DISPLAY_USABLE_BOUNDS = "SDL_DISPLAY_USABLE_BOUNDS" const SDL_HINT_EMSCRIPTEN_ASYNCIFY = "SDL_EMSCRIPTEN_ASYNCIFY" const SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT = "SDL_EMSCRIPTEN_KEYBOARD_ELEMENT" const SDL_HINT_ENABLE_STEAM_CONTROLLERS = "SDL_ENABLE_STEAM_CONTROLLERS" const SDL_HINT_EVENT_LOGGING = "SDL_EVENT_LOGGING" const SDL_HINT_FORCE_RAISEWINDOW = "SDL_HINT_FORCE_RAISEWINDOW" const SDL_HINT_FRAMEBUFFER_ACCELERATION = "SDL_FRAMEBUFFER_ACCELERATION" const SDL_HINT_GAMECONTROLLERCONFIG = "SDL_GAMECONTROLLERCONFIG" const SDL_HINT_GAMECONTROLLERCONFIG_FILE = "SDL_GAMECONTROLLERCONFIG_FILE" const SDL_HINT_GAMECONTROLLERTYPE = "SDL_GAMECONTROLLERTYPE" const SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES = "SDL_GAMECONTROLLER_IGNORE_DEVICES" const SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT = "SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT" const SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS = "SDL_GAMECONTROLLER_USE_BUTTON_LABELS" const SDL_HINT_GRAB_KEYBOARD = "SDL_GRAB_KEYBOARD" const SDL_HINT_IDLE_TIMER_DISABLED = "SDL_IOS_IDLE_TIMER_DISABLED" const SDL_HINT_IME_INTERNAL_EDITING = "SDL_IME_INTERNAL_EDITING" const SDL_HINT_IME_SHOW_UI = "SDL_IME_SHOW_UI" const SDL_HINT_IME_SUPPORT_EXTENDED_TEXT = "SDL_IME_SUPPORT_EXTENDED_TEXT" const SDL_HINT_IOS_HIDE_HOME_INDICATOR = "SDL_IOS_HIDE_HOME_INDICATOR" const SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS = "SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS" const SDL_HINT_JOYSTICK_HIDAPI = "SDL_JOYSTICK_HIDAPI" const SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE = "SDL_JOYSTICK_HIDAPI_GAMECUBE" const SDL_HINT_JOYSTICK_GAMECUBE_RUMBLE_BRAKE = "SDL_JOYSTICK_GAMECUBE_RUMBLE_BRAKE" const SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS = "SDL_JOYSTICK_HIDAPI_JOY_CONS" const SDL_HINT_JOYSTICK_HIDAPI_COMBINE_JOY_CONS = "SDL_JOYSTICK_HIDAPI_COMBINE_JOY_CONS" const SDL_HINT_JOYSTICK_HIDAPI_LUNA = "SDL_JOYSTICK_HIDAPI_LUNA" const SDL_HINT_JOYSTICK_HIDAPI_NINTENDO_CLASSIC = "SDL_JOYSTICK_HIDAPI_NINTENDO_CLASSIC" const SDL_HINT_JOYSTICK_HIDAPI_SHIELD = "SDL_JOYSTICK_HIDAPI_SHIELD" const SDL_HINT_JOYSTICK_HIDAPI_PS4 = "SDL_JOYSTICK_HIDAPI_PS4" const SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE = "SDL_JOYSTICK_HIDAPI_PS4_RUMBLE" const SDL_HINT_JOYSTICK_HIDAPI_PS5 = "SDL_JOYSTICK_HIDAPI_PS5" const SDL_HINT_JOYSTICK_HIDAPI_PS5_PLAYER_LED = "SDL_JOYSTICK_HIDAPI_PS5_PLAYER_LED" const SDL_HINT_JOYSTICK_HIDAPI_PS5_RUMBLE = "SDL_JOYSTICK_HIDAPI_PS5_RUMBLE" const SDL_HINT_JOYSTICK_HIDAPI_STADIA = "SDL_JOYSTICK_HIDAPI_STADIA" const SDL_HINT_JOYSTICK_HIDAPI_STEAM = "SDL_JOYSTICK_HIDAPI_STEAM" const SDL_HINT_JOYSTICK_HIDAPI_SWITCH = "SDL_JOYSTICK_HIDAPI_SWITCH" const SDL_HINT_JOYSTICK_HIDAPI_SWITCH_HOME_LED = "SDL_JOYSTICK_HIDAPI_SWITCH_HOME_LED" const SDL_HINT_JOYSTICK_HIDAPI_JOYCON_HOME_LED = "SDL_JOYSTICK_HIDAPI_JOYCON_HOME_LED" const SDL_HINT_JOYSTICK_HIDAPI_SWITCH_PLAYER_LED = "SDL_JOYSTICK_HIDAPI_SWITCH_PLAYER_LED" const SDL_HINT_JOYSTICK_HIDAPI_XBOX = "SDL_JOYSTICK_HIDAPI_XBOX" const SDL_HINT_JOYSTICK_RAWINPUT = "SDL_JOYSTICK_RAWINPUT" const SDL_HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT = "SDL_JOYSTICK_RAWINPUT_CORRELATE_XINPUT" const SDL_HINT_JOYSTICK_ROG_CHAKRAM = "SDL_JOYSTICK_ROG_CHAKRAM" const SDL_HINT_JOYSTICK_THREAD = "SDL_JOYSTICK_THREAD" const SDL_HINT_KMSDRM_REQUIRE_DRM_MASTER = "SDL_KMSDRM_REQUIRE_DRM_MASTER" const SDL_HINT_JOYSTICK_DEVICE = "SDL_JOYSTICK_DEVICE" const SDL_HINT_LINUX_DIGITAL_HATS = "SDL_LINUX_DIGITAL_HATS" const SDL_HINT_LINUX_HAT_DEADZONES = "SDL_LINUX_HAT_DEADZONES" const SDL_HINT_LINUX_JOYSTICK_CLASSIC = "SDL_LINUX_JOYSTICK_CLASSIC" const SDL_HINT_LINUX_JOYSTICK_DEADZONES = "SDL_LINUX_JOYSTICK_DEADZONES" const SDL_HINT_MAC_BACKGROUND_APP = "SDL_MAC_BACKGROUND_APP" const SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK = "SDL_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK" const SDL_HINT_MAC_OPENGL_ASYNC_DISPATCH = "SDL_MAC_OPENGL_ASYNC_DISPATCH" const SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS = "SDL_MOUSE_DOUBLE_CLICK_RADIUS" const SDL_HINT_MOUSE_DOUBLE_CLICK_TIME = "SDL_MOUSE_DOUBLE_CLICK_TIME" const SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH = "SDL_MOUSE_FOCUS_CLICKTHROUGH" const SDL_HINT_MOUSE_NORMAL_SPEED_SCALE = "SDL_MOUSE_NORMAL_SPEED_SCALE" const SDL_HINT_MOUSE_RELATIVE_MODE_CENTER = "SDL_MOUSE_RELATIVE_MODE_CENTER" const SDL_HINT_MOUSE_RELATIVE_MODE_WARP = "SDL_MOUSE_RELATIVE_MODE_WARP" const SDL_HINT_MOUSE_RELATIVE_SCALING = "SDL_MOUSE_RELATIVE_SCALING" const SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE = "SDL_MOUSE_RELATIVE_SPEED_SCALE" const SDL_HINT_MOUSE_RELATIVE_WARP_MOTION = "SDL_MOUSE_RELATIVE_WARP_MOTION" const SDL_HINT_MOUSE_TOUCH_EVENTS = "SDL_MOUSE_TOUCH_EVENTS" const SDL_HINT_MOUSE_AUTO_CAPTURE = "SDL_MOUSE_AUTO_CAPTURE" const SDL_HINT_NO_SIGNAL_HANDLERS = "SDL_NO_SIGNAL_HANDLERS" const SDL_HINT_OPENGL_ES_DRIVER = "SDL_OPENGL_ES_DRIVER" const SDL_HINT_ORIENTATIONS = "SDL_IOS_ORIENTATIONS" const SDL_HINT_POLL_SENTINEL = "SDL_POLL_SENTINEL" const SDL_HINT_PREFERRED_LOCALES = "SDL_PREFERRED_LOCALES" const SDL_HINT_QTWAYLAND_CONTENT_ORIENTATION = "SDL_QTWAYLAND_CONTENT_ORIENTATION" const SDL_HINT_QTWAYLAND_WINDOW_FLAGS = "SDL_QTWAYLAND_WINDOW_FLAGS" const SDL_HINT_RENDER_BATCHING = "SDL_RENDER_BATCHING" const SDL_HINT_RENDER_LINE_METHOD = "SDL_RENDER_LINE_METHOD" const SDL_HINT_RENDER_DIRECT3D11_DEBUG = "SDL_RENDER_DIRECT3D11_DEBUG" const SDL_HINT_RENDER_DIRECT3D_THREADSAFE = "SDL_RENDER_DIRECT3D_THREADSAFE" const SDL_HINT_RENDER_DRIVER = "SDL_RENDER_DRIVER" const SDL_HINT_RENDER_LOGICAL_SIZE_MODE = "SDL_RENDER_LOGICAL_SIZE_MODE" const SDL_HINT_RENDER_OPENGL_SHADERS = "SDL_RENDER_OPENGL_SHADERS" const SDL_HINT_RENDER_SCALE_QUALITY = "SDL_RENDER_SCALE_QUALITY" const SDL_HINT_RENDER_VSYNC = "SDL_RENDER_VSYNC" const SDL_HINT_RETURN_KEY_HIDES_IME = "SDL_RETURN_KEY_HIDES_IME" const SDL_HINT_RPI_VIDEO_LAYER = "SDL_RPI_VIDEO_LAYER" const SDL_HINT_SCREENSAVER_INHIBIT_ACTIVITY_NAME = "SDL_SCREENSAVER_INHIBIT_ACTIVITY_NAME" const SDL_HINT_THREAD_FORCE_REALTIME_TIME_CRITICAL = "SDL_THREAD_FORCE_REALTIME_TIME_CRITICAL" const SDL_HINT_THREAD_PRIORITY_POLICY = "SDL_THREAD_PRIORITY_POLICY" const SDL_HINT_THREAD_STACK_SIZE = "SDL_THREAD_STACK_SIZE" const SDL_HINT_TIMER_RESOLUTION = "SDL_TIMER_RESOLUTION" const SDL_HINT_TOUCH_MOUSE_EVENTS = "SDL_TOUCH_MOUSE_EVENTS" const SDL_HINT_VITA_TOUCH_MOUSE_DEVICE = "SDL_HINT_VITA_TOUCH_MOUSE_DEVICE" const SDL_HINT_TV_REMOTE_AS_JOYSTICK = "SDL_TV_REMOTE_AS_JOYSTICK" const SDL_HINT_VIDEO_ALLOW_SCREENSAVER = "SDL_VIDEO_ALLOW_SCREENSAVER" const SDL_HINT_VIDEO_DOUBLE_BUFFER = "SDL_VIDEO_DOUBLE_BUFFER" const SDL_HINT_VIDEO_EGL_ALLOW_TRANSPARENCY = "SDL_VIDEO_EGL_ALLOW_TRANSPARENCY" const SDL_HINT_VIDEO_EXTERNAL_CONTEXT = "SDL_VIDEO_EXTERNAL_CONTEXT" const SDL_HINT_VIDEO_HIGHDPI_DISABLED = "SDL_VIDEO_HIGHDPI_DISABLED" const SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES = "SDL_VIDEO_MAC_FULLSCREEN_SPACES" const SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS = "SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS" const SDL_HINT_VIDEO_WAYLAND_ALLOW_LIBDECOR = "SDL_VIDEO_WAYLAND_ALLOW_LIBDECOR" const SDL_HINT_VIDEO_WAYLAND_PREFER_LIBDECOR = "SDL_VIDEO_WAYLAND_PREFER_LIBDECOR" const SDL_HINT_VIDEO_WAYLAND_MODE_EMULATION = "SDL_VIDEO_WAYLAND_MODE_EMULATION" const SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT = "SDL_VIDEO_WINDOW_SHARE_PIXEL_FORMAT" const SDL_HINT_VIDEO_FOREIGN_WINDOW_OPENGL = "SDL_VIDEO_FOREIGN_WINDOW_OPENGL" const SDL_HINT_VIDEO_FOREIGN_WINDOW_VULKAN = "SDL_VIDEO_FOREIGN_WINDOW_VULKAN" const SDL_HINT_VIDEO_WIN_D3DCOMPILER = "SDL_VIDEO_WIN_D3DCOMPILER" const SDL_HINT_VIDEO_X11_FORCE_EGL = "SDL_VIDEO_X11_FORCE_EGL" const SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR = "SDL_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR" const SDL_HINT_VIDEO_X11_NET_WM_PING = "SDL_VIDEO_X11_NET_WM_PING" const SDL_HINT_VIDEO_X11_WINDOW_VISUALID = "SDL_VIDEO_X11_WINDOW_VISUALID" const SDL_HINT_VIDEO_X11_XINERAMA = "SDL_VIDEO_X11_XINERAMA" const SDL_HINT_VIDEO_X11_XRANDR = "SDL_VIDEO_X11_XRANDR" const SDL_HINT_VIDEO_X11_XVIDMODE = "SDL_VIDEO_X11_XVIDMODE" const SDL_HINT_WAVE_FACT_CHUNK = "SDL_WAVE_FACT_CHUNK" const SDL_HINT_WAVE_RIFF_CHUNK_SIZE = "SDL_WAVE_RIFF_CHUNK_SIZE" const SDL_HINT_WAVE_TRUNCATION = "SDL_WAVE_TRUNCATION" const SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING = "SDL_WINDOWS_DISABLE_THREAD_NAMING" const SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP = "SDL_WINDOWS_ENABLE_MESSAGELOOP" const SDL_HINT_WINDOWS_FORCE_MUTEX_CRITICAL_SECTIONS = "SDL_WINDOWS_FORCE_MUTEX_CRITICAL_SECTIONS" const SDL_HINT_WINDOWS_FORCE_SEMAPHORE_KERNEL = "SDL_WINDOWS_FORCE_SEMAPHORE_KERNEL" const SDL_HINT_WINDOWS_INTRESOURCE_ICON = "SDL_WINDOWS_INTRESOURCE_ICON" const SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL = "SDL_WINDOWS_INTRESOURCE_ICON_SMALL" const SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4 = "SDL_WINDOWS_NO_CLOSE_ON_ALT_F4" const SDL_HINT_WINDOWS_USE_D3D9EX = "SDL_WINDOWS_USE_D3D9EX" const SDL_HINT_WINDOWS_DPI_AWARENESS = "SDL_WINDOWS_DPI_AWARENESS" const SDL_HINT_WINDOWS_DPI_SCALING = "SDL_WINDOWS_DPI_SCALING" const SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN = "SDL_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN" const SDL_HINT_WINDOW_NO_ACTIVATION_WHEN_SHOWN = "SDL_WINDOW_NO_ACTIVATION_WHEN_SHOWN" const SDL_HINT_WINRT_HANDLE_BACK_BUTTON = "SDL_WINRT_HANDLE_BACK_BUTTON" const SDL_HINT_WINRT_PRIVACY_POLICY_LABEL = "SDL_WINRT_PRIVACY_POLICY_LABEL" const SDL_HINT_WINRT_PRIVACY_POLICY_URL = "SDL_WINRT_PRIVACY_POLICY_URL" const SDL_HINT_X11_FORCE_OVERRIDE_REDIRECT = "SDL_X11_FORCE_OVERRIDE_REDIRECT" const SDL_HINT_XINPUT_ENABLED = "SDL_XINPUT_ENABLED" const SDL_HINT_DIRECTINPUT_ENABLED = "SDL_DIRECTINPUT_ENABLED" const SDL_HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING = "SDL_XINPUT_USE_OLD_JOYSTICK_MAPPING" const SDL_HINT_AUDIO_INCLUDE_MONITORS = "SDL_AUDIO_INCLUDE_MONITORS" const SDL_HINT_X11_WINDOW_TYPE = "SDL_X11_WINDOW_TYPE" const SDL_HINT_QUIT_ON_LAST_WINDOW_CLOSE = "SDL_QUIT_ON_LAST_WINDOW_CLOSE" const SDL_HINT_VIDEODRIVER = "SDL_VIDEODRIVER" const SDL_HINT_AUDIODRIVER = "SDL_AUDIODRIVER" const SDL_HINT_KMSDRM_DEVICE_INDEX = "SDL_KMSDRM_DEVICE_INDEX" const SDL_HINT_TRACKPAD_IS_TOUCH_ONLY = "SDL_TRACKPAD_IS_TOUCH_ONLY" const SDL_MAX_LOG_MESSAGE = 4096 const SDL_NONSHAPEABLE_WINDOW = -1 const SDL_INVALID_SHAPE_ARGUMENT = -2 const SDL_WINDOW_LACKS_SHAPE = -3 const SDL_MAJOR_VERSION = 2 const SDL_MINOR_VERSION = 24 const SDL_PATCHLEVEL = 2 SDL_VERSIONNUM(X, Y, Z) = X * 1000 + Y * 100 + Z const SDL_COMPILEDVERSION = SDL_VERSIONNUM(SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL) const SDL_INIT_TIMER = Cuint(0x00000001) const SDL_INIT_AUDIO = Cuint(0x00000010) const SDL_INIT_VIDEO = Cuint(0x00000020) const SDL_INIT_JOYSTICK = Cuint(0x00000200) const SDL_INIT_HAPTIC = Cuint(0x00001000) const SDL_INIT_GAMECONTROLLER = Cuint(0x00002000) const SDL_INIT_EVENTS = Cuint(0x00004000) const SDL_INIT_SENSOR = Cuint(0x00008000) const SDL_INIT_NOPARACHUTE = Cuint(0x00100000) const SDL_INIT_EVERYTHING = ((((((SDL_INIT_TIMER | SDL_INIT_AUDIO) | SDL_INIT_VIDEO) | SDL_INIT_EVENTS) | SDL_INIT_JOYSTICK) | SDL_INIT_HAPTIC) | SDL_INIT_GAMECONTROLLER) | SDL_INIT_SENSOR const SDL_MIXER_MAJOR_VERSION = 2 const SDL_MIXER_MINOR_VERSION = 6 const SDL_MIXER_PATCHLEVEL = 2 const MIX_MAJOR_VERSION = SDL_MIXER_MAJOR_VERSION const MIX_MINOR_VERSION = SDL_MIXER_MINOR_VERSION const MIX_PATCHLEVEL = SDL_MIXER_PATCHLEVEL const SDL_MIXER_COMPILEDVERSION = SDL_VERSIONNUM(SDL_MIXER_MAJOR_VERSION, SDL_MIXER_MINOR_VERSION, SDL_MIXER_PATCHLEVEL) const MIX_CHANNELS = 8 const MIX_DEFAULT_FREQUENCY = 44100 const MIX_DEFAULT_FORMAT = AUDIO_S16LSB const MIX_DEFAULT_CHANNELS = 2 const MIX_MAX_VOLUME = SDL_MIX_MAXVOLUME const MIX_CHANNEL_POST = -2 const MIX_EFFECTSMAXSPEED = "MIX_EFFECTSMAXSPEED" const SDL_IMAGE_MAJOR_VERSION = 2 const SDL_IMAGE_MINOR_VERSION = 6 const SDL_IMAGE_PATCHLEVEL = 2 const SDL_IMAGE_COMPILEDVERSION = SDL_VERSIONNUM(SDL_IMAGE_MAJOR_VERSION, SDL_IMAGE_MINOR_VERSION, SDL_IMAGE_PATCHLEVEL) const SDL_TTF_MAJOR_VERSION = 2 const SDL_TTF_MINOR_VERSION = 0 const SDL_TTF_PATCHLEVEL = 15 const TTF_MAJOR_VERSION = SDL_TTF_MAJOR_VERSION const TTF_MINOR_VERSION = SDL_TTF_MINOR_VERSION const TTF_PATCHLEVEL = SDL_TTF_PATCHLEVEL const SDL_TTF_COMPILEDVERSION = SDL_VERSIONNUM(SDL_TTF_MAJOR_VERSION, SDL_TTF_MINOR_VERSION, SDL_TTF_PATCHLEVEL) const UNICODE_BOM_NATIVE = 0xfeff const UNICODE_BOM_SWAPPED = 0xfffe const TTF_STYLE_NORMAL = 0x00 const TTF_STYLE_BOLD = 0x01 const TTF_STYLE_ITALIC = 0x02 const TTF_STYLE_UNDERLINE = 0x04 const TTF_STYLE_STRIKETHROUGH = 0x08 const TTF_HINTING_NORMAL = 0 const TTF_HINTING_LIGHT = 1 const TTF_HINTING_MONO = 2 const TTF_HINTING_NONE = 3 const FPS_UPPER_LIMIT = 200 const FPS_LOWER_LIMIT = 1 const FPS_DEFAULT = 30 # Skipping MacroDefinition: SDL2_FRAMERATE_SCOPE extern const SDL2_GFXPRIMITIVES_MAJOR = 1 const SDL2_GFXPRIMITIVES_MINOR = 0 const SDL2_GFXPRIMITIVES_MICRO = 3 # Skipping MacroDefinition: SDL2_GFXPRIMITIVES_SCOPE extern # Skipping MacroDefinition: SDL2_IMAGEFILTER_SCOPE extern const SMOOTHING_OFF = 0 const SMOOTHING_ON = 1 # Skipping MacroDefinition: SDL2_ROTOZOOM_SCOPE extern # exports const PREFIXES = ["TTF_", "IMG_", "Mix_", "SDL_", "MIX_", "RW_", "AUDIO_", "KMOD_", "HAVE_"] for name in names(@__MODULE__; all=true), prefix in PREFIXES if startswith(string(name), prefix) @eval export $name end end end # module
SimpleDirectMediaLayer
https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl.git
[ "MIT" ]
0.5.0
79737366da299bd36a58b8779a5dcdcb0364befc
code
1847
module SimpleDirectMediaLayer if Sys.islinux() using alsa_plugins_jll ENV["ALSA_PLUGIN_DIR"] = joinpath(alsa_plugins_jll.artifact_dir, "lib", "alsa-lib") end include("LibSDL2.jl") using .LibSDL2 using ColorTypes import Base.unsafe_convert export TTF_Init, TTF_OpenFont, TTF_RenderText_Blended, TTF_SizeText mutable struct SDLWindow win::Ptr{SDL_Window} renderer::Ptr{SDL_Renderer} function SDLWindow(w,h,title="SDL Window") win = SDL_CreateWindow(title, Int32(100), Int32(100), Int32(w), Int32(h), UInt32(SDL_WINDOW_SHOWN | SDL_WINDOW_INPUT_FOCUS)) SDL_SetWindowResizable(win,true) renderer = SDL_CreateRenderer(win, Int32(-1), UInt32(SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC) ) new(win, renderer) end end function init() if Sys.islinux() && !haskey(ENV, "ALSA_CONFIG_PATH") ENV["ALSA_CONFIG_PATH"] = "/usr/share/alsa/alsa.conf" end SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 4) SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4) SDL_Init(UInt32(SDL_INIT_VIDEO)) TTF_Init() Mix_OpenAudio(Int32(22050), UInt16(MIX_DEFAULT_FORMAT), Int32(2), Int32(1024) ) end function mouse_position() x,y = Int[1], Int[1] SDL_GetMouseState(pointer(x), pointer(y)) x[1],y[1] end function event() ev = SDL_Event(ntuple(i->UInt8(0),56)) SDL_PollEvent(pointer_from_objref(ev)) == 0 && return nothing t = UInt32(0) for x in ev._Event[4:-1:1] t = t << (sizeof(x)*8) t |= x end evtype = SDL_Event(t) evtype == nothing && return nothing unsafe_load( Ptr{evtype}(pointer_from_objref(ev)) ) end end # module
SimpleDirectMediaLayer
https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl.git
[ "MIT" ]
0.5.0
79737366da299bd36a58b8779a5dcdcb0364befc
code
227
using SimpleDirectMediaLayer.LibSDL2 using Test if haskey(ENV, "CI") && !Sys.isapple() include("lib/SDL.jl") end include("lib/SDL_image.jl") include("lib/SDL_ttf.jl") include("lib/SDL_mixer.jl") include("lib/SDL_gfx.jl")
SimpleDirectMediaLayer
https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl.git
[ "MIT" ]
0.5.0
79737366da299bd36a58b8779a5dcdcb0364befc
code
3039
using SimpleDirectMediaLayer.LibSDL2 using Test SDL2_pkg_dir = joinpath(@__DIR__, "..", "..") @testset "Init+Quit" begin # Test that you can init and quit SDL multiple times correctly. @test SDL_Init(SDL_INIT_VIDEO) == 0 SDL_Quit() @test SDL_Init(SDL_INIT_VIDEO) == 0 SDL_Quit() end @testset "Window open+close" begin @test SDL_Init(SDL_INIT_VIDEO) == 0 # Create window win = SDL_CreateWindow("Hello World!", 100, 100, 300, 400, SDL_WINDOW_HIDDEN) @test win != C_NULL renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_SOFTWARE) @test renderer != C_NULL # Close window SDL_DestroyWindow(win) # Create window again win = SDL_CreateWindow("Hello World!", 100, 100, 300, 400, SDL_WINDOW_HIDDEN) @test win != C_NULL renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_SOFTWARE) @test renderer != C_NULL SDL_Quit() end @testset "Window" begin @test SDL_Init(SDL_INIT_VIDEO) == 0 win = SDL_CreateWindow("Hello World!", 100, 100, 300, 400, SDL_WINDOW_HIDDEN) # Test get size w, h = Ref{Cint}(-1), Ref{Cint}(-1) SDL_GetWindowSize(win, w, h) @test w[] == 300 @test h[] == 400 # Test drawing renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_SOFTWARE) rect = SDL_Rect(1, 1, 50, 50) @test SDL_RenderFillRect(renderer, Ref(rect)) == 0 @testset "Load/Save BMP" begin img = SDL_LoadBMP_RW(SDL_RWFromFile(joinpath(SDL2_pkg_dir, "assets/cat.bmp"), "rb"), 1) @test img != C_NULL img_tex = SDL_CreateTextureFromSurface(renderer, img) @test img_tex != C_NULL src = SDL_Rect(0,0,0,0) @test SDL_RenderCopy(renderer, img_tex, C_NULL, C_NULL) == 0 # Fill the renderer with img SDL_RenderPresent(renderer) # Save bmp tmpFile = tempname()*".bmp" @test SDL_SaveBMP_RW(img, SDL_RWFromFile(tmpFile, "w"), 1) == 0 img2 = SDL_LoadBMP_RW(SDL_RWFromFile(tmpFile, "r"), 1) @test img2 != C_NULL # Compare the two images # Some surfaces must be locked before accessing pixels. @test 0 == SDL_LockSurface(img) @test 0 == SDL_LockSurface(img2) img_surface1 = unsafe_load(img) img_surface2 = unsafe_load(img2) @test (img_surface1.w, img_surface1.h) == (img_surface2.w, img_surface2.h) @test img_surface1.format != C_NULL @test img_surface2.format != C_NULL # Test pixels are equal pxl_format1 = unsafe_load(img_surface1.format) numPixelBytes = img_surface1.w * img_surface1.h * pxl_format1.BytesPerPixel pixels1 = [unsafe_load(Ptr{UInt8}(img_surface1.pixels), i) for i in 1:numPixelBytes] pixels2 = [unsafe_load(Ptr{UInt8}(img_surface2.pixels), i) for i in 1:numPixelBytes] @test pixels1 == pixels2 # Some surfaces must be locked/unlocked while accessing pixels. SDL_UnlockSurface(img) SDL_UnlockSurface(img2) end # Close window SDL_DestroyWindow(win) SDL_Quit() end
SimpleDirectMediaLayer
https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl.git
[ "MIT" ]
0.5.0
79737366da299bd36a58b8779a5dcdcb0364befc
code
1984
using SimpleDirectMediaLayer using Test SDL2_pkg_dir = joinpath(@__DIR__, "..","..") @testset "FPS Manager" begin @test SDL_Init(SDL_INIT_VIDEO) == 0 fpsManager = Ref(LibSDL2.FPSmanager(UInt32(0), Cfloat(0.0), UInt32(0), UInt32(0), UInt32(0))) @test fpsManager != C_NULL SDL_initFramerate(fpsManager) @test SDL_getFramerate(fpsManager) == 30 # default value SDL_setFramerate(fpsManager, UInt32(60)) @test SDL_getFramerate(fpsManager) == 60 SDL_Quit() end @testset "GFX Primitives" begin @test SDL_Init(SDL_INIT_VIDEO) == 0 win = SDL_CreateWindow("Hello World!", 100, 100, 300, 400, 0) renderer = SDL_CreateRenderer(win, -1, 0) num_vertices = 100 # Number of vertices for the shape (e.g., 10 for a circle-like shape) size1 = 2000 size2 = 2000 centroid_x = round((size1 + size2 + size1) / 3) # calculate the original centroid x-coordinate centroid_y = round((size1 + size1 + size2) / 3) # calculate the original centroid y-coordinate offset_x = 500 - centroid_x offset_y = 500 - centroid_y radius = 100 # radius of the circle-like shape theta = 2 * pi / num_vertices # angle between each vertex x_coords = Vector{Int16}(undef, num_vertices) y_coords = Vector{Int16}(undef, num_vertices) for i in 1:num_vertices angle = i * theta x = centroid_x + offset_x + radius * cos(angle) y = centroid_y + offset_y + radius * sin(angle) x_coords[i] = round(x) y_coords[i] = round(y) end LibSDL2.filledPolygonRGBA(renderer, Ref(x_coords, 1), Ref(y_coords, 1), length(x_coords), 255, 255, 255, 255); SDL_Quit() end @testset "Image Filter" begin @test SDL_Init(SDL_INIT_VIDEO) == 0 LibSDL2.SDL_imageFilterMMXdetect() SDL_Quit() end @testset "Rotozoom" begin @test SDL_Init(SDL_INIT_VIDEO) == 0 cat = IMG_Load(joinpath(SDL2_pkg_dir, "assets", "cat.bmp")) LibSDL2.rotozoomSurface(cat, 1.0, 2.0, 2) SDL_Quit() end
SimpleDirectMediaLayer
https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl.git
[ "MIT" ]
0.5.0
79737366da299bd36a58b8779a5dcdcb0364befc
code
391
using SimpleDirectMediaLayer using Test SDL2_pkg_dir = joinpath(@__DIR__, "..","..") @testset "Image" begin @test SDL_Init(SDL_INIT_VIDEO) == 0 @test IMG_Load(joinpath(SDL2_pkg_dir, "assets", "cat.bmp")) != C_NULL @test IMG_Load(joinpath(SDL2_pkg_dir, "assets", "cat.png")) != C_NULL @test IMG_Load(joinpath(SDL2_pkg_dir, "assets", "cat.jpg")) != C_NULL SDL_Quit() end
SimpleDirectMediaLayer
https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl.git
[ "MIT" ]
0.5.0
79737366da299bd36a58b8779a5dcdcb0364befc
code
2602
using SimpleDirectMediaLayer.LibSDL2 using Test SDL2_pkg_dir = joinpath(@__DIR__, "..", "..") audio_example_assets_dir = joinpath(SDL2_pkg_dir, "examples", "audio_example") # check that an audio device if available SDL_Init(SDL_INIT_AUDIO) device = Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 1024) if device == 0 Mix_CloseAudio() SDL_Quit() @testset "Init+Quit" begin # Test that you can init and quit SDL_mixer multiple times correctly. @test SDL_Init(SDL_INIT_AUDIO) == 0 @test Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 1024) == 0 Mix_CloseAudio() SDL_Quit() @test SDL_Init(SDL_INIT_AUDIO) == 0 @test Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 1024) == 0 Mix_CloseAudio() SDL_Quit() end @testset "Sounds" begin SDL_Init(SDL_INIT_AUDIO) Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 1024) med = Mix_LoadWAV_RW(SDL_RWFromFile(joinpath(audio_example_assets_dir, "medium.wav"), "rb"), 1) @test med != C_NULL @test Mix_PlayChannelTimed(-1, med, 0, 500) != -1 # Test that can play multiple times successfully # (Note that if a sound overlaps with a previous sound, it will play on a # different channel. The return value is which channel it plays on.) @test Mix_PlayChannelTimed(-1, med, 0, 500) != -1 @test Mix_PlayChannelTimed(-1, med, 0, 500) != -1 # Test different overlapping sounds scratch = Mix_LoadWAV_RW(SDL_RWFromFile(joinpath(audio_example_assets_dir, "scratch.wav"), "rb"), 1) @test scratch != C_NULL @test Mix_PlayChannelTimed(-1, scratch, 0, 500) != -1 @test Mix_PlayChannelTimed(-1, med, 0, 500) != -1 @test Mix_PlayChannelTimed(-1, scratch, 0, 500) != -1 Mix_CloseAudio() SDL_Quit() end @testset "Music" begin SDL_Init(SDL_INIT_AUDIO) Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 1024) # Load the music music = Mix_LoadMUS(joinpath(audio_example_assets_dir, "beat.wav")) @test music != C_NULL # Test playing/pausing the music @test Mix_PlayMusic(music, -1) == 0 Mix_PauseMusic() Mix_ResumeMusic() @test Mix_HaltMusic() == 0 # Test noops if no music is playing. @test Mix_HaltMusic() == 0 Mix_PauseMusic() Mix_ResumeMusic() # Test playing multiple times @test Mix_PlayMusic(music, -1) == 0 @test Mix_PlayMusic(music, -1) == 0 Mix_CloseAudio() SDL_Quit() end end SDL_Quit()
SimpleDirectMediaLayer
https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl.git
[ "MIT" ]
0.5.0
79737366da299bd36a58b8779a5dcdcb0364befc
code
1985
using SimpleDirectMediaLayer.LibSDL2 using Test SDL2_pkg_dir = joinpath(@__DIR__, "..", "..") @testset "Init+Quit" begin # Test that you can init and quit SDL_ttf multiple times correctly. @test SDL_Init(SDL_INIT_EVERYTHING) == 0 @test TTF_Init() == 0 TTF_Quit() SDL_Quit() @test SDL_Init(SDL_INIT_EVERYTHING) == 0 @test TTF_Init() == 0 TTF_Quit() SDL_Quit() end @testset "Text" begin @test SDL_Init(SDL_INIT_EVERYTHING) == 0 @test TTF_Init() == 0 @testset "Simple text" begin font = TTF_OpenFont(joinpath(SDL2_pkg_dir, "assets/fonts/FiraCode/ttf/FiraCode-Regular.ttf"), 14) @test font != C_NULL txt = "Hello World!" text = TTF_RenderText_Blended(font, txt, SDL_Color(20, 20, 20, 255)) @test text != C_NULL fx, fy = Ref{Cint}(0), Ref{Cint}(0) @test TTF_SizeText(font, txt, fx, fy) == 0 @test fx[] > 0 @test fy[] > 0 end TTF_Quit() SDL_Quit() end @testset "Rendering" begin @test SDL_Init(SDL_INIT_EVERYTHING) == 0 @test TTF_Init() == 0 win = SDL_CreateWindow("Hello World!", 100, 100, 300, 400, 0) renderer = SDL_CreateRenderer(win, -1, 0) # try rendering with complicated text @testset "Special Characters text" begin font = TTF_OpenFont(joinpath(SDL2_pkg_dir, "assets/fonts/FiraCode/ttf/FiraCode-Regular.ttf"), 14) @test font != C_NULL txt = "@BinDeps.install Dict([ (:glib, :libglib) ])" text = TTF_RenderText_Blended(font, txt, SDL_Color(20, 20, 20, 255)) @test text != C_NULL tex = SDL_CreateTextureFromSurface(renderer, text) @test tex != C_NULL fx, fy = Ref{Cint}(0), Ref{Cint}(0) @test TTF_SizeText(font, txt, fx, fy) == 0 @test fx[] > 0 @test fy[] > 0 @test SDL_RenderCopy(renderer, tex, C_NULL, Ref(SDL_Rect(0, 0, fx[], fy[]))) == 0 SDL_RenderPresent(renderer) end TTF_Quit() SDL_Quit() end
SimpleDirectMediaLayer
https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl.git
[ "MIT" ]
0.5.0
79737366da299bd36a58b8779a5dcdcb0364befc
docs
4327
# Simple DirectMedia Layer [![CI](https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl/actions/workflows/ci.yml/badge.svg)](https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl/actions/workflows/ci.yml) [![TagBot](https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl/actions/workflows/TagBot.yml/badge.svg)](https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl/actions/workflows/TagBot.yml) [![Coverage Status](https://coveralls.io/repos/github/jonathanBieler/SimpleDirectMediaLayer.jl/badge.svg?branch=master)](https://coveralls.io/github/jonathanBieler/SimpleDirectMediaLayer.jl?branch=master) [![pkgeval](https://juliahub.com/docs/SimpleDirectMediaLayer/pkgeval.svg)](https://juliahub.com/ui/Packages/SimpleDirectMediaLayer/vVozl) [![version](https://juliahub.com/docs/SimpleDirectMediaLayer/version.svg)](https://juliahub.com/ui/Packages/SimpleDirectMediaLayer/vVozl) [![deps](https://juliahub.com/docs/SimpleDirectMediaLayer/deps.svg)](https://juliahub.com/ui/Packages/SimpleDirectMediaLayer/vVozl?t=2) [![Genie Downloads](https://shields.io/endpoint?url=https://pkgs.genieframework.com/api/v1/badge/SimpleDirectMediaLayer)](https://pkgs.genieframework.com?packages=SimpleDirectMediaLayer) Bindings for the [Simple DirectMedia Layer](https://www.libsdl.org/) library. The bindings were generated using [Clang.jl](https://github.com/JuliaInterop/Clang.jl). Documentation can be found on the [SDL wiki](https://wiki.libsdl.org/FrontPage). ## Installation ```julia pkg> add SimpleDirectMediaLayer ``` For Linux users, you probably need to manually config the environment variable `ALSA_CONFIG_PATH`. If the path is empty, the default value `/usr/share/alsa/alsa.conf` will be used. Please refer to https://github.com/JuliaPackaging/Yggdrasil/issues/1432 for more details. ## Quick start ```julia using SimpleDirectMediaLayer using SimpleDirectMediaLayer.LibSDL2 SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 16) SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 16) @assert SDL_Init(SDL_INIT_EVERYTHING) == 0 "error initializing SDL: $(unsafe_string(SDL_GetError()))" win = SDL_CreateWindow("Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1000, 1000, SDL_WINDOW_SHOWN) SDL_SetWindowResizable(win, SDL_TRUE) renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC) surface = IMG_Load(joinpath(dirname(pathof(SimpleDirectMediaLayer)), "..", "assets", "cat.png")) tex = SDL_CreateTextureFromSurface(renderer, surface) SDL_FreeSurface(surface) w_ref, h_ref = Ref{Cint}(0), Ref{Cint}(0) SDL_QueryTexture(tex, C_NULL, C_NULL, w_ref, h_ref) try w, h = w_ref[], h_ref[] x = (1000 - w) ÷ 2 y = (1000 - h) ÷ 2 dest_ref = Ref(SDL_Rect(x, y, w, h)) close = false speed = 300 while !close event_ref = Ref{SDL_Event}() while Bool(SDL_PollEvent(event_ref)) evt = event_ref[] evt_ty = evt.type if evt_ty == SDL_QUIT close = true break elseif evt_ty == SDL_KEYDOWN scan_code = evt.key.keysym.scancode if scan_code == SDL_SCANCODE_W || scan_code == SDL_SCANCODE_UP y -= speed / 30 break elseif scan_code == SDL_SCANCODE_A || scan_code == SDL_SCANCODE_LEFT x -= speed / 30 break elseif scan_code == SDL_SCANCODE_S || scan_code == SDL_SCANCODE_DOWN y += speed / 30 break elseif scan_code == SDL_SCANCODE_D || scan_code == SDL_SCANCODE_RIGHT x += speed / 30 break else break end end end x + w > 1000 && (x = 1000 - w;) x < 0 && (x = 0;) y + h > 1000 && (y = 1000 - h;) y < 0 && (y = 0;) dest_ref[] = SDL_Rect(x, y, w, h) SDL_RenderClear(renderer) SDL_RenderCopy(renderer, tex, C_NULL, dest_ref) dest = dest_ref[] x, y, w, h = dest.x, dest.y, dest.w, dest.h SDL_RenderPresent(renderer) SDL_Delay(1000 ÷ 60) end finally SDL_DestroyTexture(tex) SDL_DestroyRenderer(renderer) SDL_DestroyWindow(win) SDL_Quit() end ```
SimpleDirectMediaLayer
https://github.com/JuliaMultimedia/SimpleDirectMediaLayer.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
641
using Documenter, RipQP makedocs( modules = [RipQP], doctest = true, linkcheck = true, format = Documenter.HTML( assets = ["assets/style.css"], prettyurls = get(ENV, "CI", nothing) == "true", ), sitename = "RipQP.jl", pages = [ "Home" => "index.md", "API" => "API.md", "Tutorial" => "tutorial.md", "Switching solvers" => "switch_solv.md", "Multi-precision" => "multi_precision.md", "Reference" => "reference.md", ], ) deploydocs( deps = nothing, make = nothing, repo = "github.com/JuliaSmoothOptimizers/RipQP.jl.git", target = "build", devbranch = "main", push_preview = true, )
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
8008
module RipQP using DelimitedFiles, LinearAlgebra, MatrixMarket, SparseArrays, TimerOutputs using HSL, Krylov, LDLFactorizations, LimitedLDLFactorizations, LinearOperators, LLSModels, NLPModelsModifiers, OperatorScaling, QuadraticModels, SolverCore, SparseMatricesCOO using Requires function __init__() @require CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" include("gpu_utils.jl") @require QDLDL = "bfc457fd-c171-5ab7-bd9e-d5dbfc242d63" include( "iterations/solvers/sparse_fact_utils/qdldl_utils.jl", ) @require SuiteSparse = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9" include( "iterations/solvers/sparse_fact_utils/cholmod_utils.jl", ) end export ripqp include("types_definition.jl") include("iterations/iterations.jl") include("refinement.jl") include("data_initialization.jl") include("starting_points.jl") include("scaling.jl") include("multi_precision.jl") include("utils.jl") const to = TimerOutput() keep_init_prec(mode::Symbol) = (mode == :mono || mode == :ref || mode == :zoom) include("mono_solver.jl") include("two_steps_solver.jl") include("three_steps_solver.jl") function ripqp( QM::QuadraticModel{T, S}, ap::AbstractRipQPParameters{T}; ps::Bool = true, scaling::Bool = true, history::Bool = false, display::Bool = true, kwargs..., ) where {T, S <: AbstractVector{T}} start_time = time() # conversion function if QM.data.H and QM.data.A are not in the type required by sp QMi, ps, scaling = convert_QM(QM, ps, scaling, ap.sp, display) if ps stats_ps = presolve(QMi, fixed_vars_only = !ps) stats_ps.status != :unknown && (return stats_ps) QMps = stats_ps.solver_specific[:presolvedQM] else QMps = QMi end QM_inner, stats_inner, idi = get_inner_model_data(QM, QMps, ps, scaling, history) solver = RipQPSolver(QM_inner, ap; history = history, scaling = scaling, display = display, kwargs...) SolverCore.solve!(solver, QM_inner, stats_inner, ap) return get_stats_outer(stats_inner, QM, QMps, solver.id, idi, start_time, ps) end """ stats = ripqp(QM :: QuadraticModel{T0}; itol = InputTol(T0), scaling = true, ps = true, normalize_rtol = true, kc = 0, mode = :mono, perturb = false, early_multi_stop = true, sp = (mode == :mono) ? K2LDLParams{T0}() : K2LDLParams{Float32}(), sp2 = nothing, sp3 = nothing, solve_method = PC(), history = false, w = SystemWrite(), display = true) where {T0<:Real} Minimize a convex quadratic problem. Algorithm stops when the criteria in pdd, rb, and rc are valid. Returns a [GenericExecutionStats](https://juliasmoothoptimizers.github.io/SolverCore.jl/dev/reference/#SolverCore.GenericExecutionStats) containing information about the solved problem. - `QM :: QuadraticModel`: problem to solve - `itol :: InputTol{T, Int}` input Tolerances for the stopping criteria. See [`RipQP.InputTol`](@ref). - `scaling :: Bool`: activate/deactivate scaling of A and Q in `QM` - `ps :: Bool` : activate/deactivate presolve - `normalize_rtol :: Bool = true` : if `true`, the primal and dual tolerance for the stopping criteria are normalized by the initial primal and dual residuals - `kc :: Int`: number of centrality corrections (set to `-1` for automatic computation) - `perturb :: Bool` : activate / deativate perturbation of the current point when μ is too small - `mode :: Symbol`: should be `:mono` to use the mono-precision mode, `:multi` to use the multi-precision mode (start in single precision and gradually transitions to `T0`), `:zoom` to use the zoom procedure, `:multizoom` to use the zoom procedure with multi-precision, `ref` to use the QP refinement procedure, or `multiref` to use the QP refinement procedure with multi_precision - `early_multi_stop :: Bool` : stop the iterations in lower precision systems earlier in multi-precision mode, based on some quantities of the algorithm - `sp :: SolverParams` : choose a solver to solve linear systems that occurs at each iteration and during the initialization, see [`RipQP.SolverParams`](@ref) - `sp2 :: Union{Nothing, SolverParams}` and `sp3 :: Union{Nothing, SolverParams}` : choose second and third solvers to solve linear systems that occurs at each iteration in the second and third solving phase. When `mode != :mono`, leave to `nothing` if you want to keep using `sp`. If `sp2` is not nothing, then `mode` should be set to `:multi`, `:multiref` or `multizoom`. - `solve_method :: SolveMethod` : method used to solve the system at each iteration, use `solve_method = PC()` to use the Predictor-Corrector algorithm (default), and use `solve_method = IPF()` to use the Infeasible Path Following algorithm. `solve_method2 :: Union{Nothing, SolveMethod}` and `solve_method3 :: Union{Nothing, SolveMethod}` should be used with `sp2` and `sp3` to choose their respective solve method. If they are `nothing`, then the solve method used is `solve_method`. - `history :: Bool` : set to true to return the primal and dual norm histories, the primal-dual relative difference history, and the number of products if using a Krylov method in the `solver_specific` field of the [GenericExecutionStats](https://juliasmoothoptimizers.github.io/SolverCore.jl/dev/reference/#SolverCore.GenericExecutionStats) - `w :: SystemWrite`: configure writing of the systems to solve (no writing is done by default), see [`RipQP.SystemWrite`](@ref) - `display::Bool`: activate/deactivate iteration data display You can also use `ripqp` to solve a [LLSModel](https://juliasmoothoptimizers.github.io/LLSModels.jl/stable/#LLSModels.LLSModel): stats = ripqp(LLS::LLSModel{T0}; mode = :mono, sp = (mode == :mono) ? K2LDLParams{T0}() : K2LDLParams{Float32}(), kwargs...) where {T0 <: Real} """ function ripqp( QM::QuadraticModel{T, S}; mode::Symbol = :mono, sp::SolverParams = keep_init_prec(mode) ? K2LDLParams{T}() : K2LDLParams{Float32}(), sp2::Union{Nothing, SolverParams} = nothing, sp3::Union{Nothing, SolverParams} = nothing, solve_method::SolveMethod = PC(), solve_method2::Union{Nothing, SolveMethod} = nothing, solve_method3::Union{Nothing, SolveMethod} = nothing, kwargs..., ) where {T, S <: AbstractVector{T}} if mode == :mono ap = RipQPMonoParameters(sp, solve_method) else T1 = solver_type(sp) T2 = isnothing(sp2) ? next_type(T1, T) : solver_type(sp2) isnothing(sp2) && (sp2 = eval(typeof(sp).name.name){T2}()) isnothing(solve_method2) && (solve_method2 = solve_method) if T2 != T || !isnothing(sp3) isnothing(sp3) && (sp3 = eval(typeof(sp2).name.name){T}()) isnothing(solve_method3) && (solve_method3 = solve_method2) ap = RipQPTripleParameters(sp, sp2, sp3, solve_method, solve_method2, solve_method3) else ap = RipQPDoubleParameters(sp, sp2, solve_method, solve_method2) end end return ripqp(QM, ap; mode = mode, kwargs...) end function ripqp( LLS::LLSModel{T0}; mode::Symbol = :mono, sp::SolverParams = (mode == :mono) ? K2LDLParams{T0}() : K2LDLParams{Float32}(), kwargs..., ) where {T0 <: Real} sp.δ0 = 0.0 # equality constraints of least squares as QPs are already regularized FLLS = FeasibilityFormNLS(LLS) stats = ripqp(QuadraticModel(FLLS, FLLS.meta.x0, name = LLS.meta.name); mode = mode, sp = sp, kwargs...) n = LLS.meta.nvar x, r = stats.solution[1:n], stats.solution[(n + 1):end] solver_sp = stats.solver_specific solver_sp[:r] = r return GenericExecutionStats( LLS, status = stats.status, solution = x, objective = stats.objective, dual_feas = stats.dual_feas, primal_feas = stats.primal_feas, multipliers = stats.multipliers, multipliers_L = stats.multipliers_L, multipliers_U = stats.multipliers_U, iter = stats.iter, elapsed_time = stats.elapsed_time, solver_specific = solver_sp, ) end end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
10273
# conversion function if QM.data.H and QM.data.A are not in the type required by iconf.sp function convert_QM( QM::QuadraticModel{T, S, M1, M2}, presolve::Bool, scaling::Bool, sp::SolverParams, display::Bool, ) where {T, S, M1, M2} T_sp = typeof(sp) if (T_sp <: K2LDLParams || T_sp <: K2_5LDLParams) && !(M1 <: SparseMatrixCOO) && !(M2 <: SparseMatrixCOO) QM = convert(QuadraticModel{T, S, SparseMatrixCOO{T, Int}, SparseMatrixCOO{T, Int}}, QM) end # deactivate presolve and scaling if H and A are not SparseMatricesCOO # (TODO: write scaling and presolve for other types) M12, M22 = typeof(QM.data.H), typeof(QM.data.A) presolve_out, scaling_out = presolve, scaling if !(M12 <: SparseMatrixCOO) || !(M22 <: SparseMatrixCOO) display && presolve && @warn "No presolve operations available if QM.data.H and QM.data.A are not SparseMatricesCOO" presolve_out = false end if M12 <: AbstractLinearOperator || M22 <: AbstractLinearOperator display && scaling && @warn "No scaling operations available if QM.data.H and QM.data.A are LinearOperators" scaling_out = false end return QM, presolve_out, scaling_out end function vcatsort(v1, v2) n2 = length(v2) n2 == 0 && return v1 n1 = length(v1) n1 == 0 && return v2 n = n1 + n2 res = similar(v1, n) c1, c2 = 1, 1 @inbounds for i = 1:n if c2 == n2 + 1 res[i] = v1[c1] c1 += 1 elseif c1 == n1 + 1 res[i] = v2[c2] c2 += 1 else if v1[c1] < v2[c2] res[i] = v1[c1] c1 += 1 else res[i] = v2[c2] c2 += 1 end end end return res end function sparse_dropzeros(rows, cols, vals::Vector, nrows, ncols) M = sparse(rows, cols, vals, ncols, nrows) dropzeros!(M) return M end function get_mat_QPData( A::SparseMatrixCOO{T, Int}, H::SparseMatrixCOO{T, Int}, nvar::Int, ncon::Int, sp::SolverParams, ) where {T} if sp.uplo == :U # A is Aᵀ of QuadraticModel QM fdA = sparse_dropzeros(A.cols, A.rows, A.vals, ncon, nvar) fdQ = sparse_dropzeros(H.cols, H.rows, H.vals, nvar, nvar) else fdA = sparse_dropzeros(A.rows, A.cols, A.vals, nvar, ncon) fdQ = sparse_dropzeros(H.rows, H.cols, H.vals, nvar, nvar) end return fdA, Symmetric(fdQ, sp.uplo) end if LIBHSL_isfunctional() get_mat_QPData( A::SparseMatrixCOO{T, Int}, H::SparseMatrixCOO{T, Int}, nvar::Int, ncon::Int, sp::Union{K2LDLParams{T0, F}, K2_5LDLParams{T0, F}, K2KrylovParams{T0, LDL{DataType, F}}}, ) where {T, T0, F <: HSLMA57Fact} = A, Symmetric(H, sp.uplo) end function get_mat_QPData(A, H, nvar::Int, ncon::Int, sp::SolverParams) fdA = sp.uplo == :U ? transpose(A) : A return fdA, Symmetric(H, :L) end function get_QM_data(QM::AbstractQuadraticModel{T, S}, sp::SolverParams) where {T <: Real, S} # constructs A and Q transposed so we can create K upper triangular. A, Q = get_mat_QPData(QM.data.A, QM.data.H, QM.meta.nvar, QM.meta.ncon, sp) id = QM_IntData( vcatsort(QM.meta.ilow, QM.meta.irng), vcatsort(QM.meta.iupp, QM.meta.irng), QM.meta.irng, QM.meta.ifree, QM.meta.ifix, QM.meta.ncon, QM.meta.nvar, 0, 0, ) id.nlow, id.nupp = length(id.ilow), length(id.iupp) # number of finite constraints @assert QM.meta.lcon == QM.meta.ucon # equality constraint (Ax=b) @assert length(QM.meta.lvar) == length(QM.meta.uvar) == QM.meta.nvar fd = QM_FloatData(Q, A, QM.meta.lcon, QM.data.c, QM.data.c0, QM.meta.lvar, QM.meta.uvar, sp.uplo) return fd, id end function allocate_workspace( QM::AbstractQuadraticModel, iconf::InputConfig, itol::InputTol, start_time, ::Type{T0}, sp::SolverParams{Ti}, ) where {Ti, T0} sc = StopCrit(false, false, false, itol.max_iter, itol.max_time, start_time, 0.0) fd_T0, id = get_QM_data(QM, sp) # final tolerances ϵ = Tolerances( T0(itol.ϵ_pdd), T0(itol.ϵ_rb), T0(itol.ϵ_rc), one(T0), one(T0), T0(itol.ϵ_μ), T0(itol.ϵ_Δx), iconf.normalize_rtol, ) sd = ScaleData(fd_T0, id, iconf.scaling) # allocate data for iterations S0 = typeof(fd_T0.c) S = change_vector_eltype(S0, Ti) res = init_residuals(S(undef, id.ncon), S(undef, id.nvar), zero(Ti), zero(Ti), iconf, sp, id) itd = IterData( S(undef, id.nvar + id.ncon), # Δxy S(undef, id.nlow), # Δs_l S(undef, id.nupp), # Δs_u S(undef, id.nlow), # x_m_lvar S(undef, id.nupp), # uvar_m_x S(undef, id.nvar), # init Qx S(undef, id.nvar), # init ATy S(undef, id.ncon), # Ax zero(Ti), #xTQx zero(Ti), #cTx zero(Ti), #pri_obj zero(Ti), #dual_obj zero(Ti), #μ zero(Ti),#pdd typeof(fd_T0.Q) <: Union{AbstractLinearOperator, DenseMatrix} || nnz(fd_T0.Q.data) > 0, iconf.minimize, iconf.perturb, ) cnts = Counters(0.0, 0.0, 0, 0, 0, 0, zero(UInt64), zero(UInt64), iconf.kc, 0, iconf.w, true, 0, 0, 0) pt = Point(S(undef, id.nvar), S(undef, id.ncon), S(undef, id.nlow), S(undef, id.nupp)) spd = StartingPointData{Ti, S}(S(undef, id.nvar), S(undef, id.nlow), S(undef, id.nupp)) return sc, fd_T0, id, ϵ, res, itd, pt, sd, spd, cnts end function allocate_extra_workspace1( T::DataType, itol::InputTol, iconf::InputConfig, fd_T0::QM_FloatData, ) ϵ1 = Tolerances( T(itol.ϵ_pdd1), T(itol.ϵ_rb1), T(itol.ϵ_rc1), one(T), one(T), T(itol.ϵ_μ), T(itol.ϵ_Δx), iconf.normalize_rtol, ) fd1 = convert_FloatData(T, fd_T0) return fd1, ϵ1 end function allocate_extra_workspace2( ::Type{T}, itol::InputTol, iconf::InputConfig, fd_T0::QM_FloatData, ) where {T} ϵ2 = Tolerances( T(itol.ϵ_pdd2), T(itol.ϵ_rb2), T(itol.ϵ_rc2), one(T), one(T), T(itol.ϵ_μ), T(itol.ϵ_Δx), iconf.normalize_rtol, ) fd2 = convert_FloatData(T, fd_T0) return fd2, ϵ2 end function initialize!( fd::QM_FloatData{T}, id::QM_IntData, res::AbstractResiduals{T}, itd::IterData{T}, dda::DescentDirectionAllocs{T}, pad::PreallocatedData{T}, pt::Point{T}, spd::StartingPointData{T}, ϵ::Tolerances{T}, sc::StopCrit{Tc}, cnts::Counters, max_time::Float64, display::Bool, ::Type{T0}, ) where {T <: Real, Tc <: Real, T0 <: Real} # init system # solve [-Q-D A' ] [x] = [0] to initialize (x, y, s_l, s_u) # [ A 0 ] [y] = [b] itd.Δxy[1:(id.nvar)] .= 0 itd.Δxy[(id.nvar + 1):end] = fd.b if typeof(pad) <: PreallocatedDataNewton itd.Δs_l .= zero(T) itd.Δs_u .= zero(T) pt.s_l .= one(T) pt.s_u .= one(T) itd.x_m_lvar .= one(T) itd.uvar_m_x .= one(T) end # @timeit_debug to "init solver" begin init_pad!(pad) out = solver!(itd.Δxy, pad, dda, pt, itd, fd, id, res, cnts, :init) # end pt.x .= itd.Δxy[1:(id.nvar)] pt.y .= itd.Δxy[(id.nvar + 1):(id.nvar + id.ncon)] starting_points!(pt, fd, id, itd, spd) # stopping criterion # rcNorm, rbNorm = norm(rc), norm(rb) # optimal = pdd < ϵ_pdd && rbNorm < ϵ_rb && rcNorm < ϵ_rc @. res.rb = itd.Ax - fd.b @. res.rc = itd.ATy - itd.Qx - fd.c res.rc[id.ilow] .+= pt.s_l res.rc[id.iupp] .-= pt.s_u res.rcNorm, res.rbNorm = norm(res.rc, Inf), norm(res.rb, Inf) typeof(res) <: ResidualsHistory && push_history_residuals!(res, itd, pad, id) set_tol_residuals!(ϵ, res.rbNorm, res.rcNorm) sc.optimal = itd.pdd < ϵ.pdd && res.rbNorm < ϵ.tol_rb && res.rcNorm < ϵ.tol_rc sc.small_μ = itd.μ < ϵ.μ Δt = time() - cnts.time_solve sc.tired = Δt > max_time # display if display == true # @timeit_debug to "display" begin show_used_solver(pad) setup_log_header(pad) show_log_row(pad, itd, res, cnts, zero(T), zero(T)) # end end end function set_tol_residuals!(ϵ::Tolerances{T}, rbNorm::T, rcNorm::T) where {T <: Real} if ϵ.normalize_rtol == true ϵ.tol_rb, ϵ.tol_rc = ϵ.rb * (one(T) + rbNorm), ϵ.rc * (one(T) + rcNorm) else ϵ.tol_rb, ϵ.tol_rc = ϵ.rb, ϵ.rc end end ############ tools for sparse matrices ############## function get_diagind_K(K::Symmetric{T, <:SparseMatrixCSC{T}}, tri::Symbol) where {T} # get diagonal index of M.nzval # we assume all columns of M are non empty, and M triangular (:L or :U) K_colptr = K.data.colptr @assert tri == :U || tri == :L if tri == :U diagind = K_colptr[2:end] .- one(Int) else diagind = K_colptr[1:(end - 1)] end return diagind end function get_diagind_K(K::Symmetric{T, <:SparseMatrixCOO{T}}, tri::Symbol) where {T} # pb if regul = none / dynamic Krows, Kcols = K.data.rows, K.data.cols diagind = zeros(Int, size(K, 2)) for k = 1:length(Krows) i = Krows[k] (Kcols[k] == i) && (diagind[i] = k) end return diagind end function fill_diag_Q!(diagval, Q::SparseMatrixCSC{T}) where {T <: Real} n = size(Q, 2) Q_colptr, Q_rowval, Q_nzval = Q.colptr, Q.rowval, Q.nzval @inbounds @simd for j = 1:n for k = Q_colptr[j]:(Q_colptr[j + 1] - 1) if j == Q_rowval[k] diagval[j] = Q_nzval[k] end end end return diagval end function fill_diag_Q!(diagval, Q::SparseMatrixCOO{T}) where {T <: Real} Qrows, Qcols, Qvals = Q.rows, Q.cols, Q.vals @inbounds @simd for k = 1:length(Qrows) i = Qrows[k] if Qcols[k] == i diagval[i] = Qvals[k] end end return diagval end function get_diag_Q(Q::Symmetric{T, <:AbstractMatrix{T}}) where {T} n = size(Q, 2) diagval = spzeros(T, n) fill_diag_Q!(diagval, Q.data) return diagval end function get_diag_Q_dense(Q::SparseMatrixCSC{T, Int}, uplo::Symbol) where {T <: Real} n = size(Q, 1) diagval = zeros(T, n) fill_diag_Q_dense!(Q.colptr, Q.rowval, Q.nzval, diagval, n, uplo) return diagval end get_diag_Q_dense(Q::Symmetric{T, SparseMatrixCSC{T, Int}}, uplo::Symbol) where {T} = get_diag_Q_dense(Q.data, uplo) function fill_diag_Q_dense!( Q_colptr, Q_rowval, Q_nzval::Vector{T}, diagval::Vector{T}, n, uplo::Symbol, ) where {T <: Real} for j = 1:n if uplo == :U k = Q_colptr[j + 1] - 1 if k > 0 i = Q_rowval[k] if j == i diagval[j] = Q_nzval[k] end end elseif uplo == :L k = Q_colptr[j] nnzQ = length(Q_nzval) if k ≤ nnzQ i = Q_rowval[k] if j == i diagval[j] = Q_nzval[k] end end end end end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
6365
using .CUDA include("iterations/solvers/gpu/K2KrylovLDLGPU.jl") function get_mat_QPData( A::CUDA.CUSPARSE.CuSparseMatrixCOO{T, Ti}, H::CUDA.CUSPARSE.CuSparseMatrixCOO{T, Ti}, nvar::Int, ncon::Int, sp::K2KrylovGPUParams, ) where {T, Ti} # A is Aᵀ of QuadraticModel QM fdA = CUDA.CUSPARSE.CuSparseMatrixCSC( sparse(Vector(A.colInd), Vector(A.rowInd), Vector(A.nzVal), nvar, ncon), ) fdQ = CUDA.CUSPARSE.CuSparseMatrixCSC( sparse(Vector(H.colInd), Vector(H.rowInd), Vector(H.nzVal), nvar, nvar), ) return fdA, Symmetric(fdQ, sp.uplo) end change_vector_eltype(S0::Type{<:CUDA.CuVector}, ::Type{T}) where {T} = S0.name.wrapper{T, 1, CUDA.Mem.DeviceBuffer} convert_mat(M::CUDA.CUSPARSE.CuSparseMatrixCSC, ::Type{T}) where {T} = CUDA.CUSPARSE.CuSparseMatrixCSC( convert(CUDA.CuArray{Int, 1, CUDA.Mem.DeviceBuffer}, M.colPtr), convert(CUDA.CuArray{Int, 1, CUDA.Mem.DeviceBuffer}, M.rowVal), convert(CUDA.CuArray{T, 1, CUDA.Mem.DeviceBuffer}, M.nzVal), M.dims, ) convert_mat(M::CUDA.CUSPARSE.CuSparseMatrixCSR, ::Type{T}) where {T} = CUDA.CUSPARSE.CuSparseMatrixCSR( convert(CUDA.CuArray{Int, 1, CUDA.Mem.DeviceBuffer}, M.rowPtr), convert(CUDA.CuArray{Int, 1, CUDA.Mem.DeviceBuffer}, M.colVal), convert(CUDA.CuArray{T, 1, CUDA.Mem.DeviceBuffer}, M.nzVal), M.dims, ) convert_mat(M::CUDA.CuMatrix, ::Type{T}) where {T} = convert(typeof(M).name.wrapper{T, 2, CUDA.Mem.DeviceBuffer}, M) function sparse_dropzeros(rows, cols, vals::CuVector, nrows, ncols) CPUvals = Vector(vals) M = sparse(rows, cols, CPUvals, ncols, nrows) dropzeros!(M) MGPU = CUDA.CUSPARSE.CuSparseMatrixCSR(M) return MGPU end function get_diag_Q_dense(Q::CUDA.CUSPARSE.CuSparseMatrixCSR{T}) where {T <: Real} n = size(Q, 1) diagval = CUDA.zeros(T, n) fill_diag_Q_dense!(Q.rowPtr, Q.colVal, Q.nzVal, diagval, n) return diagval end function fill_diag_Q_dense!( Q_rowPtr, Q_colVal, Q_nzVal::CUDA.CuVector{T}, diagval::CUDA.CuVector{T}, n, ) where {T <: Real} function kernel(Q_rowPtr, Q_colVal, Q_nzVal, diagval, n) index = (blockIdx().x - 1) * blockDim().x + threadIdx().x k = Q_rowPtr[index + 1] - 1 if k > 0 i = Q_colVal[k] if index == i diagval[index] = Q_nzVal[k] end end return nothing end threads = min(n, 256) blocks = ceil(Int, n / threads) @cuda name = "diagq" threads = threads blocks = blocks kernel( Q_rowPtr, Q_colVal, Q_nzVal, diagval, n, ) end function check_bounds(x::T, lvar, uvar) where {T <: Real} ϵ = T(1.0e-4) if lvar >= x x = lvar + ϵ end if x >= uvar x = uvar - ϵ end if (lvar < x < uvar) == false x = (lvar + uvar) / 2 end return x end # starting points function update_rngbounds!(x, irng, lvar, uvar, ϵ) @views broadcast!(check_bounds, x[irng], x[irng], lvar[irng], uvar[irng]) end # α computation (in iterations.jl) function ddir(dir_vi::T, vi::T) where {T <: Real} if dir_vi < zero(T) α_new = -vi * T(0.999) / dir_vi return α_new end return one(T) end function compute_α_dual_gpu(v, dir_v, store_v) map!(ddir, store_v, dir_v, v) return minimum(store_v) end function pdir_l(dir_vi::T, lvari::T, vi::T) where {T <: Real} if dir_vi < zero(T) α_new = (lvari - vi) * T(0.999) / dir_vi return α_new end return one(T) end function pdir_u(dir_vi::T, uvari::T, vi::T) where {T <: Real} if dir_vi > zero(T) α_new = (uvari - vi) * T(0.999) / dir_vi return α_new end return one(T) end function compute_α_primal_gpu(v, dir_v, lvar, uvar, store_v) map!(pdir_l, store_v, dir_v, lvar, v) α_l = minimum(store_v) map!(pdir_u, store_v, dir_v, uvar, v) α_u = minimum(store_v) return min(α_l, α_u) end @inline function compute_αs_gpu( x::CuVector, s_l::CuVector, s_u::CuVector, lvar::CuVector, uvar::CuVector, Δxy::CuVector, Δs_l::CuVector, Δs_u::CuVector, nvar, store_vpri::CuVector, store_vdual_l::CuVector, store_vdual_u::CuVector, ) α_pri = @views compute_α_primal_gpu(x, Δxy[1:nvar], lvar, uvar, store_vpri) α_dual_l = compute_α_dual_gpu(s_l, Δs_l, store_vdual_l) α_dual_u = compute_α_dual_gpu(s_u, Δs_u, store_vdual_u) return α_pri, min(α_dual_l, α_dual_u) end # dot gpu with views function dual_obj_gpu( b, y, xTQx_2, s_l, s_u, lvar, uvar, c0, ilow, iupp, store_vdual_l, store_vdual_u, ) store_vdual_l .= @views lvar[ilow] store_vdual_u .= @views uvar[iupp] dual_obj = dot(b, y) - xTQx_2 + dot(s_l, store_vdual_l) - dot(s_u, store_vdual_u) + c0 return dual_obj end import LinearAlgebra.rdiv!, LinearAlgebra.ldiv! function LinearAlgebra.rdiv!(M::CUDA.AbstractGPUArray{T}, D::Diagonal) where {T} D.diag .= one(T) ./ D.diag rmul!(M, D) D.diag .= one(T) ./ D.diag return M end function LinearAlgebra.ldiv!(D::Diagonal, M::CUDA.AbstractGPUArray{T}) where {T} D.diag .= one(T) ./ D.diag lmul!(D, M) D.diag .= one(T) ./ D.diag return M end import NLPModelsModifiers.SlackModel function slackdata2( data::QuadraticModels.QPData{T, S, M1, M2}, meta::NLPModelsModifiers.NLPModelMeta{T}, ns::Int, ) where {T, S, M1 <: CUDA.CUSPARSE.CuSparseMatrixCOO, M2 <: CUDA.CUSPARSE.CuSparseMatrixCOO} nvar_slack = meta.nvar + ns Ti = (T == Float64) ? Int64 : Int32 return QuadraticModels.QPData( copy(data.c0), [data.c; fill!(similar(data.c, ns), zero(T))], CUDA.CUSPARSE.CuSparseMatrixCOO{T, Ti}( Ti.(data.H.rowInd), Ti.(data.H.colInd), data.H.nzVal, (nvar_slack, nvar_slack), length(data.H.nzVal), ), CUDA.CUSPARSE.CuSparseMatrixCOO{T, Ti}( CuVector{Ti}([Vector(data.A.rowInd); meta.jlow; meta.jupp; meta.jrng]), CuVector{Ti}([Vector(data.A.colInd); (meta.nvar + 1):(meta.nvar + ns)]), CuVector([Vector(data.A.nzVal); fill!(Vector{T}(undef, ns), -one(T))]), (meta.ncon, nvar_slack), length(data.A.nzVal), ), ) end function NLPModelsModifiers.SlackModel( qp::AbstractQuadraticModel{T, S}, name = qp.meta.name * "-slack", ) where {T, S <: CUDA.CuArray} qp.meta.ncon == length(qp.meta.jfix) && return qp nfix = length(qp.meta.jfix) ns = qp.meta.ncon - nfix data = slackdata2(qp.data, qp.meta, ns) meta = NLPModelsModifiers.slack_meta(qp.meta, name = qp.meta.name) return QuadraticModel(meta, NLPModelsModifiers.Counters(), data) end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
2424
RipQPMonoParameters{T}(; sp::SolverParams = K2LDLParams{T}(), solve_method::SolveMethod = PC(), ) where {T} = RipQPMonoParameters(sp, solve_method) RipQPSolver(QM::AbstractQuadraticModel{T}, ap::RipQPMonoParameters{T}; kwargs...) where {T} = RipQPMonoSolver(QM; ap = ap, kwargs...) function RipQPMonoSolver( QM::AbstractQuadraticModel{T, S}; itol::InputTol{T, Int} = InputTol(T), scaling::Bool = true, normalize_rtol::Bool = true, kc::I = 0, perturb::Bool = false, mode::Symbol = :mono, ap::RipQPMonoParameters{T} = RipQPMonoParameters{T}(), history::Bool = false, w::SystemWrite = SystemWrite(), display::Bool = true, ) where {T <: Real, S <: AbstractVector{T}, I <: Integer} start_time = time() elapsed_time = 0.0 typeof(ap.solve_method) <: IPF && kc != 0 && error("IPF method should not be used with centrality corrections") iconf = InputConfig(mode, true, scaling, normalize_rtol, kc, perturb, QM.meta.minimize, history, w) # allocate workspace sc, fd, id, ϵ, res, itd, pt, sd, spd, cnts = allocate_workspace(QM, iconf, itol, start_time, T, ap.sp) if iconf.scaling scaling!(fd, id, sd, T(1.0e-5)) end dda = DescentDirectionAllocs(id, ap.solve_method, S) pad = PreallocatedData(ap.sp, fd, id, itd, pt, iconf) pfd = PreallocatedFloatData(pt, res, itd, dda, pad) cnts.time_allocs = time() - start_time return RipQPMonoSolver(QM, id, iconf, itol, sd, spd, sc, cnts, display, fd, ϵ, pfd) end function SolverCore.solve!( solver::RipQPMonoSolver{T, S}, QM::AbstractQuadraticModel{T, S}, stats::GenericExecutionStats{T, S}, ap::RipQPMonoParameters{T}, ) where {T, S} id = solver.id iconf, itol = solver.iconf, solver.itol sd, spd = solver.sd, solver.spd sc, cnts = solver.sc, solver.cnts display = solver.display pfd = solver.pfd pt, res, itd, dda, pad = pfd.pt, pfd.res, pfd.itd, pfd.dda, pfd.pad fd, ϵ = solver.fd, solver.ϵ cnts.time_solve = time() # initialize data initialize!(fd, id, res, itd, dda, pad, pt, spd, ϵ, sc, cnts, itol.max_time, display, T) # IPM iterations 1st solver (mono mode: only this call to the iter! function) iter!(pt, itd, fd, id, res, sc, dda, pad, ϵ, cnts, iconf, display, last_iter = true) if iconf.scaling post_scale!(sd, pt, res, fd, id, itd) end cnts.iters_sp = cnts.k set_ripqp_stats!(stats, pt, res, pad, itd, id, sc, cnts, itol.max_iter) return stats end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
1876
convert_sym(::Type{T}, Q::Symmetric{T0, M0}) where {T, T0, M0 <: AbstractMatrix{T0}} = Symmetric(convert_mat(Q.data, T), Symbol(Q.uplo)) function convert_FloatData( ::Type{T}, fd_T0::QM_FloatData{T0, S0, M10, M20}, ) where {T <: Real, T0 <: Real, S0, M10, M20} if T == T0 return fd_T0 else return QM_FloatData( convert_sym(T, fd_T0.Q), convert_mat(fd_T0.A, T), convert(change_vector_eltype(S0, T), fd_T0.b), convert(change_vector_eltype(S0, T), fd_T0.c), T(fd_T0.c0), convert(change_vector_eltype(S0, T), fd_T0.lvar), convert(change_vector_eltype(S0, T), fd_T0.uvar), fd_T0.uplo, ) end end function convert_types( ::Type{T}, pt::Point{T_old, S_old}, itd::IterData{T_old, S_old}, res::AbstractResiduals{T_old, S_old}, dda::DescentDirectionAllocs{T_old, S_old}, pad::PreallocatedData{T_old}, sp_old::Union{Nothing, SolverParams}, sp_new::Union{Nothing, SolverParams}, id::QM_IntData, fd::Abstract_QM_FloatData, # type T solve_method_old::SolveMethod, solve_method_new::SolveMethod, ) where {T <: Real, T_old <: Real, S_old} S = S_old.name.wrapper{T, 1} (T == T_old) && ( return pt, itd, res, convert_solve_method(DescentDirectionAllocs{T, S}, dda, solve_method_old, solve_method_new, id), convertpad(PreallocatedData{T}, pad, sp_old, sp_new, id, fd) ) pt = convert(Point{T, S}, pt) res = convert(AbstractResiduals{T, S}, res) itd = convert(IterData{T, S}, itd) pad = convertpad(PreallocatedData{T}, pad, sp_old, sp_new, id, fd) dda = convert(DescentDirectionAllocs{T, S}, dda) dda = convert_solve_method(DescentDirectionAllocs{T, S}, dda, solve_method_old, solve_method_new, id) return pt, itd, res, dda, pad end small_αs(α_pri::T, α_dual::T, cnts::Counters) where {T} = (cnts.k ≥ 5) && ((α_pri < T(1.0e-1)) || (α_dual < T(1.0e-1)))
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
6982
mutable struct QM_FloatData_ref{T <: Real, S, M1, M2} <: Abstract_QM_FloatData{T, S, M1, M2} Q::M1 A::M2 # using AT is easier to form systems b::S c::S c0::T lvar::S uvar::S Δref::T x_approx::S x_approxQx_approx_2::T b_init::S bTy_approx::T c_init::S pri_obj_approx::T uplo::Symbol end function fd_refinement( fd::QM_FloatData{T}, id::QM_IntData, res::AbstractResiduals{T}, Δxy::Vector{T}, pt::Point{T}, itd::IterData{T}, ϵ::Tolerances{T}, dda::DescentDirectionAllocs{T}, pad::PreallocatedData{T}, spd::StartingPointData{T}, cnts::Counters, mode::Symbol; centering::Bool = false, ) where {T <: Real} # center Points before zoom if centering # if pad.fact_fail # re-factorize if it failed in a lower precision system # out = factorize_K2!(pad.K, pad.K_fact, pad.D, pad.diag_Q, pad.diagind_K, pad.regu, # pt.s_l, pt.s_u, itd.x_m_lvar, itd.uvar_m_x, id.ilow, id.iupp, # id.ncon, id.nvar, cnts, itd.qp, T, T0) # end # dda.rxs_l .= -itd.μ # dda.rxs_u .= itd.μ # solve_augmented_system_cc!(pad.K_fact, itd.Δxy, itd.Δs_l, itd.Δs_u, itd.x_m_lvar, itd.uvar_m_x, # pad.rxs_l, pad.rxs_u, pt.s_l, pt.s_u, id.ilow, id.iupp) @. itd.Δxy[1:(id.nvar)] = -res.rc @. itd.Δxy[(id.nvar + 1):(id.nvar + id.ncon)] = -res.rb @. itd.Δxy[id.ilow] += pt.s_l - itd.μ / itd.x_m_lvar @. itd.Δxy[id.iupp] -= pt.s_u - itd.μ / itd.uvar_m_x padT = typeof(pad) if (padT <: PreallocatedDataAugmentedLDL && !factorized(pad.K_fact)) || ( padT <: PreallocatedDataK2Krylov && typeof(pad.pdat) <: LDLData && !factorized(pad.pdat.K_fact) ) out = update_pad!(pad, dda, pt, itd, fd, id, res, cnts) out = solver!(itd.Δxy, pad, dda, pt, itd, fd, id, res, cnts, :IPF) else out = solver!(itd.Δxy, pad, dda, pt, itd, fd, id, res, cnts, :cc) end @. itd.Δs_l = @views (itd.μ - pt.s_l * itd.Δxy[id.ilow]) / itd.x_m_lvar - pt.s_l @. itd.Δs_u = @views (itd.μ + pt.s_u * itd.Δxy[id.iupp]) / itd.uvar_m_x - pt.s_u α_pri, α_dual = compute_αs(pt.x, pt.s_l, pt.s_u, fd.lvar, fd.uvar, itd.Δxy, itd.Δs_l, itd.Δs_u, id.nvar) update_data!(pt, α_pri, α_dual, itd, pad, res, fd, id) end c_ref = fd.c .- itd.ATy .+ itd.Qx αref = T(1.0e12) if mode == :zoom || mode == :multizoom # zoom parameter Δref = one(T) / res.rbNorm elseif mode == :ref || mode == :multiref Δref = one(T) δd = norm(c_ref, Inf) if id.nlow == 0 && id.nupp > 0 δp = max(res.rbNorm, minimum(itd.uvar_m_x)) elseif id.nlow > 0 && id.nupp == 0 δp = max(res.rbNorm, minimum(itd.x_m_lvar)) elseif id.nlow == 0 && id.nupp == 0 δp = max(res.rbNorm) else δp = max(res.rbNorm, minimum(itd.x_m_lvar), minimum(itd.uvar_m_x)) end Δref = min(αref / Δref, one(T) / δp, one(T) / δd) end if Δref == T(Inf) Δref = αref end c_ref .*= Δref fd_ref = QM_FloatData_ref( fd.Q, fd.A, .-res.rb .* Δref, c_ref, fd.c0, Δref .* (fd.lvar .- pt.x), Δref .* (fd.uvar .- pt.x), Δref, pt.x, copy(itd.xTQx_2), fd.b, dot(fd.b, pt.y), fd.c, copy(itd.pri_obj), fd.uplo, ) # init zoom Point S = typeof(fd.c) pt_z = Point( fill!(S(undef, id.nvar), zero(T)), fill!(S(undef, id.ncon), zero(T)), pt.s_l .* Δref, pt.s_u .* Δref, ) starting_points!(pt_z, fd_ref, id, itd, spd) # update residuals res.rb .= itd.Ax .- fd_ref.b res.rc .= itd.ATy .- itd.Qx .- fd_ref.c res.rc[id.ilow] .+= pt_z.s_l res.rc[id.iupp] .-= pt_z.s_u res.rcNorm, res.rbNorm = norm(res.rc, Inf), norm(res.rb, Inf) return fd_ref, pt_z end function update_pt_ref!( Δref::T, pt::Point{T}, pt_z::Point{T}, res::AbstractResiduals{T}, id::QM_IntData, fd::QM_FloatData{T}, itd::IterData{T}, ) where {T <: Real} # update Point @. pt.x += pt_z.x / Δref @. pt.y += pt_z.y / Δref @. pt.s_l = pt_z.s_l / Δref @. pt.s_u = pt_z.s_u / Δref # update IterData itd.Qx = mul!(itd.Qx, fd.Q, pt.x) itd.xTQx_2 = dot(pt.x, itd.Qx) / 2 fd.uplo == :U ? mul!(itd.ATy, fd.A, pt.y) : mul!(itd.ATy, fd.A', pt.y) fd.uplo == :U ? mul!(itd.Ax, fd.A', pt.x) : mul!(itd.Ax, fd.A, pt.x) itd.cTx = dot(fd.c, pt.x) itd.pri_obj = itd.xTQx_2 + itd.cTx + fd.c0 itd.dual_obj = @views dot(fd.b, pt.y) - itd.xTQx_2 + dot(pt.s_l, fd.lvar[id.ilow]) - dot(pt.s_u, fd.uvar[id.iupp]) + fd.c0 itd.pdd = abs(itd.pri_obj - itd.dual_obj) / (one(T) + abs(itd.pri_obj)) # update Residuals @. res.rb = itd.Ax - fd.b @. res.rc = itd.ATy - itd.Qx - fd.c res.rc[id.ilow] .+= pt.s_l res.rc[id.iupp] .-= pt.s_u res.rcNorm, res.rbNorm = norm(res.rc, Inf), norm(res.rb, Inf) res.rcNorm, res.rbNorm = norm(res.rc, Inf), norm(res.rb, Inf) end function update_data!( pt::Point{T}, α_pri::T, α_dual::T, itd::IterData{T}, pad::PreallocatedData{T}, res::AbstractResiduals{T}, fd::QM_FloatData_ref{T}, id::QM_IntData, ) where {T <: Real} # (x, y, s_l, s_u) += α * Δ update_pt!( pt.x, pt.y, pt.s_l, pt.s_u, α_pri, α_dual, itd.Δxy, itd.Δs_l, itd.Δs_u, id.ncon, id.nvar, ) # update IterData @. itd.x_m_lvar = @views pt.x[id.ilow] - fd.lvar[id.ilow] @. itd.uvar_m_x = @views fd.uvar[id.iupp] - pt.x[id.iupp] boundary_safety!(itd.x_m_lvar, itd.uvar_m_x) itd.μ = compute_μ(itd.x_m_lvar, itd.uvar_m_x, pt.s_l, pt.s_u, id.nlow, id.nupp) if itd.perturb && itd.μ ≤ eps(T) perturb_x!( pt.x, pt.s_l, pt.s_u, itd.x_m_lvar, itd.uvar_m_x, fd.lvar, fd.uvar, itd.μ, id.ilow, id.iupp, id.nlow, id.nupp, id.nvar, ) itd.μ = compute_μ(itd.x_m_lvar, itd.uvar_m_x, pt.s_l, pt.s_u, id.nlow, id.nupp) end itd.Qx = mul!(itd.Qx, fd.Q, pt.x) x_approxQx = dot(fd.x_approx, itd.Qx) itd.xTQx_2 = dot(pt.x, itd.Qx) / 2 fd.uplo == :U ? mul!(itd.ATy, fd.A, pt.y) : mul!(itd.ATy, fd.A', pt.y) fd.uplo == :U ? mul!(itd.Ax, fd.A', pt.x) : mul!(itd.Ax, fd.A, pt.x) itd.cTx = dot(fd.c_init, pt.x) itd.pri_obj = fd.pri_obj_approx + x_approxQx / fd.Δref + itd.xTQx_2 / fd.Δref^2 + dot(fd.c_init, pt.x) / fd.Δref itd.dual_obj = @views fd.bTy_approx + dot(fd.b_init, pt.y) / fd.Δref - fd.x_approxQx_approx_2 - dot(fd.x_approx, itd.Qx) / fd.Δref - itd.xTQx_2 / fd.Δref^2 + dot(pt.s_l, fd.lvar[id.ilow]) / fd.Δref^2 + dot(pt.s_l, fd.x_approx[id.ilow]) / fd.Δref - dot(pt.s_u, fd.uvar[id.iupp]) / fd.Δref^2 - dot(pt.s_u, fd.x_approx[id.iupp]) / fd.Δref + fd.c0 itd.pdd = abs(itd.pri_obj - itd.dual_obj) / (one(T) + abs(itd.pri_obj)) #update Residuals @. res.rb = itd.Ax - fd.b @. res.rc = itd.ATy - itd.Qx - fd.c res.rc[id.ilow] .+= pt.s_l res.rc[id.iupp] .-= pt.s_u res.rcNorm, res.rbNorm = norm(res.rc, Inf) / fd.Δref, norm(res.rb, Inf) / fd.Δref end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
8605
# Symmetric equilibration scaling (transform Q so that its rows and cols have an infinite norm close to 1): # Q ← D3 * Q * D3, C_k is a storage Diagonal Array that has the same size as D3 # ϵ is the norm tolerance on the row and cols infinite norm of A # max_iter is the maximum number of iterations function scaling!( fd_T0::QM_FloatData{T}, id::QM_IntData, sd::ScaleDataLP{T}, ϵ::T; max_iter::Int = 100, ) where {T <: Real} d1, d2, r_k, c_k = sd.d1, sd.d2, sd.r_k, sd.c_k d1 .= one(T) d2 .= one(T) D1 = Diagonal(d1) D2 = Diagonal(d2) R_k = Diagonal(r_k) C_k = Diagonal(c_k) # r (resp. c) norm of rows of AT (resp. cols) # scaling: D2 * AT * D1 A_transposed = (fd_T0.uplo == :U) equilibrate!(fd_T0.A, D2, D1, C_k, R_k; ϵ = ϵ, max_iter = max_iter, A_transposed = A_transposed) fd_T0.b .*= d2 fd_T0.c .*= d1 fd_T0.lvar ./= d1 fd_T0.uvar ./= d1 end function mul_Q_D2_CSC!(Q_colptr, Q_rowval, Q_nzval, d2) for j = 1:length(d2) @inbounds @simd for i = Q_colptr[j]:(Q_colptr[j + 1] - 1) Q_nzval[i] *= d2[Q_rowval[i]] * d2[j] end end end mul_Q_D2!(Q::SparseMatrixCSC, D2) = mul_Q_D2_CSC!(Q.colptr, Q.rowval, Q.nzval, D2.diag) function mul_Q_D2!(Q, D2) lmul!(D2, Q) rmul!(Q, D2) end function div_D_Q_D_CSC!(Q_colptr, Q_rowval, Q_nzval, d, n) for j = 1:n @inbounds @simd for i = Q_colptr[j]:(Q_colptr[j + 1] - 1) Q_nzval[i] /= d[Q_rowval[i]] * d[j] end end end div_D_Q_D!(Q::SparseMatrixCSC, D) = div_D_Q_D_CSC!(Q.colptr, Q.rowval, Q.nzval, D.diag, size(Q, 1)) function div_D_Q_D!(Q, D) ldiv!(D, Q) rdiv!(Q, D) end function div_D1_A_D2_CSC!(A_colptr, A_rowval, A_nzval, d1, d2, n, uplo) for j = 1:n @inbounds @simd for i = A_colptr[j]:(A_colptr[j + 1] - 1) A_nzval[i] /= (uplo == :U) ? d1[j] * d2[A_rowval[i]] : d1[A_rowval[i]] * d2[j] end end end div_D1_A_D2!(A::SparseMatrixCSC, D1, D2, uplo) = div_D1_A_D2_CSC!(A.colptr, A.rowval, A.nzval, D1.diag, D2.diag, size(A, 2), uplo) function div_D1_A_D2!(A, D1, D2, uplo) if uplo == :U rdiv!(A, D1) ldiv!(D2, A) else ldiv!(D1, A) rdiv!(A, D2) end end function post_scale!( sd::ScaleData{T}, pt::Point{T}, res::AbstractResiduals{T}, fd_T0::QM_FloatData{T}, id::QM_IntData, itd::IterData{T}, ) where {T <: Real} if typeof(sd) <: ScaleDataLP d1 = sd.d1 d2 = sd.d2 elseif typeof(sd) <: ScaleDataQP d1 = view(sd.deq, 1:(id.nvar)) d2 = view(sd.deq, (id.nvar + 1):(id.nvar + id.ncon)) end D1, D2 = Diagonal(d1), Diagonal(d2) # unscale problem data nnz(fd_T0.Q.data) > 0 && div_D_Q_D!(fd_T0.Q.data, D1) div_D1_A_D2!(fd_T0.A, D2, D1, fd_T0.uplo) fd_T0.b ./= d2 fd_T0.c ./= d1 fd_T0.lvar .*= d1 fd_T0.uvar .*= d1 # update final point pt.x .*= d1 pt.y .*= d2 pt.s_l ./= @views d1[id.ilow] pt.s_u ./= @views d1[id.iupp] # update iter data mul!(itd.Qx, fd_T0.Q, pt.x) itd.xTQx_2 = dot(pt.x, itd.Qx) / 2 fd_T0.uplo == :U ? mul!(itd.ATy, fd_T0.A, pt.y) : mul!(itd.ATy, fd_T0.A', pt.y) fd_T0.uplo == :U ? mul!(itd.Ax, fd_T0.A', pt.x) : mul!(itd.Ax, fd_T0.A, pt.x) itd.cTx = dot(fd_T0.c, pt.x) itd.pri_obj = itd.xTQx_2 + itd.cTx + fd_T0.c0 itd.dual_obj = dot(fd_T0.b, pt.y) - itd.xTQx_2 + dot(pt.s_l, view(fd_T0.lvar, id.ilow)) - dot(pt.s_u, view(fd_T0.uvar, id.iupp)) + fd_T0.c0 # update residuals res.rb .= itd.Ax .- fd_T0.b res.rc .= itd.ATy .- itd.Qx .- fd_T0.c res.rc[id.ilow] .+= pt.s_l res.rc[id.iupp] .-= pt.s_u # rcNorm, rbNorm = norm(rc), norm(rb) res.rcNorm, res.rbNorm = norm(res.rc, Inf), norm(res.rb, Inf) end # equilibrate K2 function get_norm_rc_K2_CSC!( v, Q_colptr, Q_rowval, Q_nzval, A_colptr, A_rowval, A_nzval, D, deq, δ, nvar, ncon, uplo, ) T = eltype(v) v .= zero(T) ignore_D = length(D) == 0 # ignore D if it is empty (in case we want to scale [Q Aᵀ; A δI]) for j = 1:nvar passed_diagj = false @inbounds for k = Q_colptr[j]:(Q_colptr[j + 1] - 1) i = Q_rowval[k] if i == j nzvalij = ignore_D ? -deq[i]^2 * Q_nzval[k] : deq[i]^2 * (-Q_nzval[k] + D[j]) passed_diagj = true else nzvalij = -deq[i] * Q_nzval[k] * deq[j] end if abs(nzvalij) > v[i] v[i] = abs(nzvalij) end if abs(nzvalij) > v[j] v[j] = abs(nzvalij) end end if !passed_diagj nzvalij = ignore_D ? zero(T) : deq[j]^2 * D[j] if abs(nzvalij) > v[j] v[j] = abs(nzvalij) end end end ncolA = (uplo == :L) ? nvar : ncon for j = 1:ncolA @inbounds for k = A_colptr[j]:(A_colptr[j + 1] - 1) if uplo == :L iup = A_rowval[k] + nvar jup = j else iup = A_rowval[k] jup = j + nvar end nzvalij = deq[iup] * A_nzval[k] * deq[jup] if abs(nzvalij) > v[iup] v[iup] = abs(nzvalij) end if abs(nzvalij) > v[jup] v[jup] = abs(nzvalij) end end end if δ > 0 @inbounds for j = (nvar + 1):(nvar + ncon) rdij = δ * deq[j]^2 if abs(rdij) > v[j] v[j] = abs(rdij) end end end v .= sqrt.(v) @inbounds @simd for i = 1:length(v) if v[i] == zero(T) v[i] = one(T) end end end get_norm_rc_K2!(v, Q::SparseMatrixCSC, A::SparseMatrixCSC, D, deq, δ, nvar, ncon, uplo) = get_norm_rc_K2_CSC!( v, Q.colptr, Q.rowval, Q.nzval, A.colptr, A.rowval, A.nzval, D, deq, δ, nvar, ncon, uplo, ) get_norm_rc_K2!( v, Q::Symmetric{T, SparseMatrixCSC{T, Int}}, A::SparseMatrixCSC, D, deq, δ, nvar, ncon, uplo, ) where {T} = get_norm_rc_K2!(v, Q.data, A, D, deq, δ, nvar, ncon, uplo) # not efficient but can be improved: function get_norm_rc_K2!(v, Q::Symmetric, A, D, deq, δ, nvar, ncon, uplo) # D as storage vec @assert δ == 0 T = eltype(v) v .= zero(T) v1 = view(v, 1:nvar) v2 = view(v, (nvar + 1):(nvar + ncon)) Deq1 = Diagonal(view(deq, 1:nvar)) Deq2 = Diagonal(view(deq, (nvar + 1):(nvar + ncon))) rmul!(Q.data, Deq1) lmul!(Deq1, Q.data) maximum!(abs, v1, Q) rdiv!(Q.data, Deq1) ldiv!(Deq1, Q.data) if uplo == :U lmul!(Deq1, A) rmul!(A, Deq2) maximum!(abs, D, A) maximum!(abs, v2', A) ldiv!(Deq1, A) rdiv!(A, Deq2) else lmul!(Deq2, A) rmul!(A, Deq1) maximum!(abs, v2, A) maximum!(abs, D', A) ldiv!(Deq2, A) rdiv!(A, Deq1) end v1 .= max.(v1, D) v .= OperatorScaling.return_one_if_zero.(sqrt.(v)) end function equilibrate_K2!( Q::SparseMatrixCSC{T}, A::SparseMatrixCSC{T}, D::Vector{T}, δ::T, nvar::Int, ncon::Int, Deq::Diagonal{T, S}, C_k::Diagonal{T, S}, uplo::Symbol; ϵ::T = T(1.0e-2), max_iter::Int = 100, ) where {T <: Real, S <: AbstractVector{T}} Deq.diag .= one(T) # get_norm_rc!(C_k.diag, Q.data, :col) get_norm_rc_K2!(C_k.diag, Q, A, D, Deq.diag, δ, nvar, ncon, uplo) Deq.diag ./= C_k.diag C_k.diag .= abs.(one(T) .- C_k.diag) convergence = maximum(C_k.diag) <= ϵ k = 1 while !convergence && k < max_iter # get_norm_rc!(C_k.diag, Q, :col) get_norm_rc_K2!(C_k.diag, Q, A, D, Deq.diag, δ, nvar, ncon, uplo) Deq.diag ./= C_k.diag C_k.diag .= abs.(one(T) .- C_k.diag) convergence = maximum(C_k.diag) <= ϵ k += 1 end end function scaling!( fd_T0::QM_FloatData{T}, id::QM_IntData, sd::ScaleDataQP{T}, ϵ::T; max_iter::Int = 100, ) where {T <: Real} size(fd_T0.Q) == 0 && min(size(fd_T0.A)...) == 0 && return deq, c_k = sd.deq, sd.c_k deq .= one(T) Deq = Diagonal(deq) C_k = Diagonal(c_k) # empty vector to use ignore_D in get_norm_rc_K2 or storage vector if not csc Dtmp = typeof(fd_T0.A) <: SparseMatrixCSC ? similar(deq, 0) : similar(deq, id.nvar) δ = zero(T) # scaling Q (symmetric) get_norm_rc_K2!(C_k.diag, fd_T0.Q, fd_T0.A, Dtmp, Deq.diag, δ, id.nvar, id.ncon, fd_T0.uplo) Deq.diag ./= C_k.diag C_k.diag .= abs.(one(T) .- C_k.diag) convergence = maximum(C_k.diag) <= ϵ k = 1 while !convergence && k < max_iter get_norm_rc_K2!(C_k.diag, fd_T0.Q, fd_T0.A, Dtmp, Deq.diag, δ, id.nvar, id.ncon, fd_T0.uplo) Deq.diag ./= C_k.diag C_k.diag .= abs.(one(T) .- C_k.diag) convergence = maximum(C_k.diag) <= ϵ k += 1 end D1 = Diagonal(view(deq, 1:(id.nvar))) D2 = Diagonal(view(deq, (id.nvar + 1):(id.nvar + id.ncon))) if fd_T0.uplo == :U lmul!(D1, fd_T0.A) rmul!(fd_T0.A, D2) else lmul!(D2, fd_T0.A) rmul!(fd_T0.A, D1) end mul_Q_D2!(fd_T0.Q.data, D1) fd_T0.c .*= D1.diag fd_T0.lvar ./= D1.diag fd_T0.uvar ./= D1.diag fd_T0.b .*= D2.diag end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
2337
function starting_points!( pt0::Point{T}, fd::Abstract_QM_FloatData{T}, id::QM_IntData, itd::IterData{T}, spd::StartingPointData{T}, ) where {T <: Real} mul!(itd.Qx, fd.Q, pt0.x) fd.uplo == :U ? mul!(itd.ATy, fd.A, pt0.y) : mul!(itd.ATy, fd.A', pt0.y) @. spd.dual_val = itd.Qx - itd.ATy + fd.c pt0.s_l = spd.dual_val[id.ilow] pt0.s_u = -spd.dual_val[id.iupp] # check distance to bounds δ for x, s_l and s_u @. itd.x_m_lvar = @views pt0.x[id.ilow] - fd.lvar[id.ilow] @. itd.uvar_m_x = @views fd.uvar[id.iupp] - pt0.x[id.iupp] if id.nlow == 0 δx_l1, δs_l1 = zero(T), zero(T) else δx_l1 = max(-T(1.5) * minimum(itd.x_m_lvar), eps(T)^(1 / 4)) δs_l1 = max(-T(1.5) * minimum(pt0.s_l), eps(T)^(1 / 4)) end if id.nupp == 0 δx_u1, δs_u1 = zero(T), zero(T) else δx_u1 = max(-T(1.5) * minimum(itd.uvar_m_x), eps(T)^(1 / 4)) δs_u1 = max(-T(1.5) * minimum(pt0.s_u), eps(T)^(1 / 4)) end # correct components that to not respect the bounds itd.x_m_lvar .+= δx_l1 itd.uvar_m_x .+= δx_u1 @. spd.s0_l1 = pt0.s_l + δs_l1 @. spd.s0_u1 = pt0.s_u + δs_u1 xs_l1, xs_u1 = dot(spd.s0_l1, itd.x_m_lvar), dot(spd.s0_u1, itd.uvar_m_x) if id.nlow == 0 δx_l2, δs_l2 = zero(T), zero(T) else δx_l2 = δx_l1 + xs_l1 / sum(spd.s0_l1) / 2 δs_l2 = δs_l1 + xs_l1 / sum(itd.x_m_lvar) / 2 end if id.nupp == 0 δx_u2, δs_u2 = zero(T), zero(T) else δx_u2 = δx_u1 + xs_u1 / sum(spd.s0_u1) / 2 δs_u2 = δs_u1 + xs_u1 / sum(itd.uvar_m_x) / 2 end δx = max(δx_l2, δx_u2) δs = max(δs_l2, δs_u2) pt0.x[id.ilow] .+= δx pt0.x[id.iupp] .-= δx pt0.s_l .+= δs pt0.s_u .+= δs # deal with the compensation phaenomenon in x if irng != [] update_rngbounds!(pt0.x, id.irng, fd.lvar, fd.uvar, eps(T)^(1 / 4)) # verify bounds @assert all(pt0.x .> fd.lvar) && all(pt0.x .< fd.uvar) id.nlow > 0 && @assert all(pt0.s_l .> zero(T)) id.nupp > 0 && @assert all(pt0.s_u .> zero(T)) # update itd update_IterData!(itd, pt0, fd, id, false) end function update_rngbounds!(x::Vector{T}, irng, lvar, uvar, ϵ) where {T <: Real} @inbounds @simd for i in irng if lvar[i] >= x[i] x[i] = lvar[i] + ϵ end if x[i] >= uvar[i] x[i] = uvar[i] - ϵ end if (lvar[i] < x[i] < uvar[i]) == false x[i] = (lvar[i] + uvar[i]) / 2 end end end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
5526
RipQPTripleParameters{T}(; sp::SolverParams = K2LDLParams{Float32}(), sp2::SolverParams = K2LDLParams{Float64}(), sp3::SolverParams{T} = K2LDLParams{T}(), solve_method::SolveMethod = PC(), solve_method2::SolveMethod = PC(), solve_method3::SolveMethod = PC(), ) where {T} = RipQPTripleParameters(sp, sp2, sp3, solve_method, solve_method2, solve_method3) RipQPSolver(QM::AbstractQuadraticModel{T}, ap::RipQPTripleParameters{T}; kwargs...) where {T} = RipQPTripleSolver(QM; ap = ap, kwargs...) function RipQPTripleSolver( QM::AbstractQuadraticModel{T0, S0}; itol::InputTol{T0, Int} = InputTol(T0), scaling::Bool = true, normalize_rtol::Bool = true, kc::I = 0, perturb::Bool = false, mode::Symbol = :multi, early_multi_stop::Bool = true, ap::RipQPTripleParameters{T0} = RipQPTripleParameters{T0}(), history::Bool = false, w::SystemWrite = SystemWrite(), display::Bool = true, ) where {T0 <: Real, S0 <: AbstractVector{T0}, I <: Integer} start_time = time() elapsed_time = 0.0 # config mode == :mono || mode == :multi || mode == :zoom || mode == :multizoom || mode == :ref || mode == :multiref || error("not a valid mode") if mode == :mono @warn "setting mode to multi because sp2 is provided" mode = :multi end typeof(ap.solve_method) <: IPF && kc != 0 && error("IPF method should not be used with centrality corrections") T = solver_type(ap.sp) # initial solve type iconf = InputConfig( mode, early_multi_stop, scaling, normalize_rtol, kc, perturb, QM.meta.minimize, history, w, ) # allocate workspace sc, fd_T0, id, ϵ_T0, res, itd, pt, sd, spd, cnts = allocate_workspace(QM, iconf, itol, start_time, T0, ap.sp) if iconf.scaling scaling!(fd_T0, id, sd, T0(1.0e-5)) end # extra workspace T2 = next_type(T, T0) # eltype of sp2 fd, ϵ = allocate_extra_workspace1(T, itol, iconf, fd_T0) fd2, ϵ2 = allocate_extra_workspace2(T2, itol, iconf, fd_T0) S = change_vector_eltype(S0, T) dda = DescentDirectionAllocs(id, ap.solve_method, S) pad = PreallocatedData(ap.sp, fd, id, itd, pt, iconf) pfd = PreallocatedFloatData(pt, res, itd, dda, pad) cnts.time_allocs = time() - start_time return RipQPTripleSolver( QM, id, iconf, itol, sd, spd, sc, cnts, display, fd, ϵ, fd2, ϵ2, fd_T0, ϵ_T0, pfd, ) end function SolverCore.solve!( solver::RipQPTripleSolver{T, S}, QM::AbstractQuadraticModel{T, S}, stats::GenericExecutionStats{T, S}, ap::RipQPTripleParameters, ) where {T, S} id = solver.id iconf, itol = solver.iconf, solver.itol sd, spd = solver.sd, solver.spd sc, cnts = solver.sc, solver.cnts display = solver.display sp, sp2, sp3 = ap.sp, ap.sp2, ap.sp3 solve_method, solve_method2, solve_method3 = ap.solve_method, ap.solve_method2, ap.solve_method3 pfd = solver.pfd pt, res, itd, dda, pad = pfd.pt, pfd.res, pfd.itd, pfd.dda, pfd.pad fd1, ϵ1 = solver.fd1, solver.ϵ1 fd2, ϵ2 = solver.fd2, solver.ϵ2 fd3, ϵ3 = solver.fd3, solver.ϵ3 cnts.time_solve = time() sc.max_iter = itol.max_iter1 # set max_iter for 1st solver cnts.last_sp = false # sp is not the last sp because sp2 is not nothing mode = iconf.mode T2, T3 = solver_type(sp2), solver_type(sp3) @assert T3 == T # initialize data initialize!(fd1, id, res, itd, dda, pad, pt, spd, ϵ1, sc, cnts, itol.max_time, display, T) if (mode == :multi || mode == :multizoom || mode == :multiref) set_tol_residuals!(ϵ2, T2(res.rbNorm), T2(res.rcNorm)) set_tol_residuals!(ϵ3, T3(res.rbNorm), T3(res.rcNorm)) end # IPM iterations 1st solver (mono mode: only this call to the iter! function) iter!(pt, itd, fd1, id, res, sc, dda, pad, ϵ1, cnts, iconf, display, last_iter = false) cnts.iters_sp = cnts.k sc.max_iter = itol.max_iter # set max_iter for 2nd solver cnts.last_sp = true # sp2 is the last sp because sp3 is nothing pt, itd, res, dda, pad = convert_types(T2, pt, itd, res, dda, pad, sp, sp2, id, fd2, solve_method, solve_method2) sc.optimal = itd.pdd < ϵ2.pdd && res.rbNorm < ϵ2.tol_rb && res.rcNorm < ϵ2.tol_rc sc.small_μ = itd.μ < ϵ2.μ display && show_used_solver(pad) display && setup_log_header(pad) iter!(pt, itd, fd2, id, res, sc, dda, pad, ϵ2, cnts, iconf, display, last_iter = false) cnts.iters_sp2 = cnts.k - cnts.iters_sp pt, itd, res, dda, pad = convert_types(T3, pt, itd, res, dda, pad, sp2, sp3, id, fd3, solve_method2, solve_method3) sc.optimal = itd.pdd < ϵ3.pdd && res.rbNorm < ϵ3.tol_rb && res.rcNorm < ϵ3.tol_rc sc.small_μ = itd.μ < ϵ3.μ display && show_used_solver(pad) display && setup_log_header(pad) # set max_iter for 3rd solver sc.max_iter = itol.max_iter cnts.last_sp = true # sp3 is the last sp if !sc.optimal && mode == :multi iter!(pt, itd, fd3, id, res, sc, dda, pad, ϵ3, cnts, iconf, display) elseif !sc.optimal && (mode == :multizoom || mode == :multiref) spd = convert(StartingPointData{T, typeof(pt.x)}, spd) fd_ref, pt_ref = fd_refinement(fd3, id, res, itd.Δxy, pt, itd, ϵ3, dda, pad, spd, cnts, mode, centering = true) iter!(pt_ref, itd, fd_ref, id, res, sc, dda, pad, ϵ3, cnts, iconf, display) update_pt_ref!(fd_ref.Δref, pt, pt_ref, res, id, fd3, itd) end cnts.iters_sp3 = cnts.k - cnts.iters_sp2 if iconf.scaling post_scale!(sd, pt, res, fd3, id, itd) end set_ripqp_stats!(stats, pt, res, pad, itd, id, sc, cnts, itol.max_iter) return stats end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
5126
RipQPDoubleParameters{T}(; sp::SolverParams = K2LDLParams{Float32}(), sp2::SolverParams{T} = K2LDLParams{T}(), solve_method::SolveMethod = PC(), solve_method2::SolveMethod = PC(), ) where {T} = RipQPDoubleParameters(sp, sp2, solve_method, solve_method2) RipQPSolver(QM::AbstractQuadraticModel{T}, ap::RipQPDoubleParameters{T}; kwargs...) where {T} = RipQPDoubleSolver(QM; ap = ap, kwargs...) function RipQPDoubleSolver( QM::AbstractQuadraticModel{T0, S0}; itol::InputTol{T0, Int} = InputTol(T0), scaling::Bool = true, normalize_rtol::Bool = true, kc::I = 0, perturb::Bool = false, mode::Symbol = :multi, early_multi_stop::Bool = true, ap::RipQPDoubleParameters{T0} = RipQPDoubleParameters{T0}(), history::Bool = false, w::SystemWrite = SystemWrite(), display::Bool = true, ) where {T0 <: Real, S0 <: AbstractVector{T0}, I <: Integer} start_time = time() elapsed_time = 0.0 # config mode == :mono || mode == :multi || mode == :zoom || mode == :multizoom || mode == :ref || mode == :multiref || error("not a valid mode") if mode == :mono @warn "setting mode to multi because sp2 is provided" mode = :multi end typeof(ap.solve_method) <: IPF && kc != 0 && error("IPF method should not be used with centrality corrections") T = solver_type(ap.sp) # initial solve type iconf = InputConfig( mode, early_multi_stop, scaling, normalize_rtol, kc, perturb, QM.meta.minimize, history, w, ) # allocate workspace sc, fd_T0, id, ϵ_T0, res, itd, pt, sd, spd, cnts = allocate_workspace(QM, iconf, itol, start_time, T0, ap.sp) if iconf.scaling scaling!(fd_T0, id, sd, T0(1.0e-5)) end # extra workspace if iconf.mode == :ref || iconf.mode == :zoom fd = fd_T0 ϵ = Tolerances( T(1), T(itol.ϵ_rbz), T(itol.ϵ_rbz), T(ϵ_T0.tol_rb * T(itol.ϵ_rbz / itol.ϵ_rb)), one(T), T(itol.ϵ_μ), T(itol.ϵ_Δx), iconf.normalize_rtol, ) else fd, ϵ = allocate_extra_workspace1(T, itol, iconf, fd_T0) end S = change_vector_eltype(S0, T) dda = DescentDirectionAllocs(id, ap.solve_method, S) pad = PreallocatedData(ap.sp, fd, id, itd, pt, iconf) pfd = PreallocatedFloatData(pt, res, itd, dda, pad) cnts.time_allocs = time() - start_time return RipQPDoubleSolver(QM, id, iconf, itol, sd, spd, sc, cnts, display, fd, ϵ, fd_T0, ϵ_T0, pfd) end function SolverCore.solve!( solver::RipQPDoubleSolver{T, S}, QM::AbstractQuadraticModel{T, S}, stats::GenericExecutionStats{T, S}, ap::RipQPDoubleParameters, ) where {T, S} id = solver.id iconf, itol = solver.iconf, solver.itol sd, spd = solver.sd, solver.spd sc, cnts = solver.sc, solver.cnts display = solver.display sp, sp2 = ap.sp, ap.sp2 solve_method, solve_method2 = ap.solve_method, ap.solve_method2 pfd = solver.pfd pt, res, itd, dda, pad = pfd.pt, pfd.res, pfd.itd, pfd.dda, pfd.pad fd1, ϵ1 = solver.fd1, solver.ϵ1 fd2, ϵ2 = solver.fd2, solver.ϵ2 cnts.time_solve = time() sc.max_iter = itol.max_iter1 # set max_iter for 1st solver cnts.last_sp = false # sp is not the last sp because sp2 is not nothing mode = iconf.mode T2 = solver_type(sp2) @assert T2 == T # initialize data initialize!(fd1, id, res, itd, dda, pad, pt, spd, ϵ1, sc, cnts, itol.max_time, display, T) if (mode == :multi || mode == :multizoom || mode == :multiref) set_tol_residuals!(ϵ2, T(res.rbNorm), T(res.rcNorm)) end # IPM iterations 1st solver (mono mode: only this call to the iter! function) iter!(pt, itd, fd1, id, res, sc, dda, pad, ϵ1, cnts, iconf, display, last_iter = false) cnts.iters_sp = cnts.k sc.max_iter = itol.max_iter # set max_iter for 2nd solver cnts.last_sp = true # sp2 is the last sp because sp3 is nothing pt, itd, res, dda, pad = convert_types(T2, pt, itd, res, dda, pad, sp, sp2, id, fd2, solve_method, solve_method2) sc.optimal = itd.pdd < ϵ2.pdd && res.rbNorm < ϵ2.tol_rb && res.rcNorm < ϵ2.tol_rc sc.small_μ = itd.μ < ϵ2.μ display && show_used_solver(pad) display && setup_log_header(pad) if !sc.optimal && mode == :multi iter!(pt, itd, fd2, id, res, sc, dda, pad, ϵ2, cnts, iconf, display) elseif !sc.optimal && (mode == :multizoom || mode == :multiref) spd = convert(StartingPointData{T, typeof(pt.x)}, spd) fd_ref, pt_ref = fd_refinement(fd2, id, res, itd.Δxy, pt, itd, ϵ2, dda, pad, spd, cnts, mode, centering = true) iter!(pt_ref, itd, fd_ref, id, res, sc, dda, pad, ϵ2, cnts, iconf, display) update_pt_ref!(fd_ref.Δref, pt, pt_ref, res, id, fd2, itd) elseif mode == :zoom || mode == :ref sc.optimal = false fd_ref, pt_ref = fd_refinement(fd2, id, res, itd.Δxy, pt, itd, ϵ2, dda, pad, spd, cnts, mode) iter!(pt_ref, itd, fd_ref, id, res, sc, dda, pad, ϵ2, cnts, iconf, display) update_pt_ref!(fd_ref.Δref, pt, pt_ref, res, id, fd2, itd) end cnts.iters_sp2 = cnts.k - cnts.iters_sp if iconf.scaling post_scale!(sd, pt, res, fd2, id, itd) end set_ripqp_stats!(stats, pt, res, pad, itd, id, sc, cnts, itol.max_iter) return stats end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
18330
import Base: convert export InputTol, SolveMethod, SystemWrite, SolverParams, PreallocatedData # problem: min 1/2 x'Qx + c'x + c0 s.t. Ax = b, lvar ≤ x ≤ uvar abstract type Abstract_QM_FloatData{ T <: Real, S, M1 <: Union{AbstractMatrix{T}, AbstractLinearOperator{T}}, M2 <: Union{AbstractMatrix{T}, AbstractLinearOperator{T}}, } end mutable struct QM_FloatData{T <: Real, S, M1, M2} <: Abstract_QM_FloatData{T, S, M1, M2} Q::M1 # size nvar * nvar A::M2 # size ncon * nvar, using Aᵀ is easier to form systems b::S # size ncon c::S # size nvar c0::T lvar::S # size nvar uvar::S # size nvar uplo::Symbol end mutable struct QM_IntData ilow::Vector{Int} # indices of finite elements in lvar iupp::Vector{Int} # indices of finite elements in uvar irng::Vector{Int} # indices of finite elements in both lvar and uvar ifree::Vector{Int} # indices of infinite elements in both lvar and uvar ifix::Vector{Int} ncon::Int # number of equality constraints after SlackModel! (= size of b) nvar::Int # number of variables nlow::Int # length(ilow) nupp::Int # length(iupp) end struct IntDataInit{I <: Integer} nvar::I ncon::I ilow::Vector{I} iupp::Vector{I} irng::Vector{I} ifix::Vector{I} jlow::Vector{I} jupp::Vector{I} jrng::Vector{I} jfix::Vector{I} end IntDataInit(QM::AbstractQuadraticModel) = IntDataInit( QM.meta.nvar, QM.meta.ncon, QM.meta.ilow, QM.meta.iupp, QM.meta.irng, QM.meta.ifix, QM.meta.jlow, QM.meta.jupp, QM.meta.jrng, QM.meta.jfix, ) """ Abstract type for tuning the parameters of the different solvers. Each solver has its own `SolverParams` type. """ abstract type SolverParams{T} end solver_type(::SolverParams{T}) where {T} = T function next_type(::Type{T}, ::Type{T0}) where {T, T0} T == T0 && return T0 T == Float32 && return Float64 T == Float64 && return T0 end """ Type to write the matrix (.mtx format) and the right hand side (.rhs format) of the system to solve at each iteration. - `write::Bool`: activate/deactivate writing of the system - `name::String`: name of the sytem to solve - `kfirst::Int`: first iteration where a system should be written - `kgap::Int`: iteration gap between two problem writings The constructor SystemWrite(; write = false, name = "", kfirst = 0, kgap = 1) returns a `SystemWrite` structure that should be used to tell RipQP to save the system. See the tutorial for more information. """ struct SystemWrite write::Bool name::String kfirst::Int kgap::Int end SystemWrite(; write::Bool = false, name::String = "", kfirst::Int = 0, kgap::Int = 1) = SystemWrite(write, name, kfirst, kgap) abstract type SolveMethod end abstract type DescentDirectionAllocs{T <: Real, S} end mutable struct InputConfig{I <: Integer} mode::Symbol early_multi_stop::Bool # stop earlier in multi-precision, based on some quantities of the algorithm scaling::Bool normalize_rtol::Bool # normalize the primal and dual tolerance to the initial starting primal and dual residuals kc::I # multiple centrality corrections, -1 = automatic computation perturb::Bool minimize::Bool # output tools history::Bool w::SystemWrite # write systems end """ Type to specify the tolerances used by RipQP. - `max_iter :: Int`: maximum number of iterations - `ϵ_pdd`: relative primal-dual difference tolerance - `ϵ_rb`: primal tolerance - `ϵ_rc`: dual tolerance - `max_iter1`, `ϵ_pdd1`, `ϵ_rb1`, `ϵ_rc1`: same as `max_iter`, `ϵ_pdd`, `ϵ_rb` and `ϵ_rc`, but used for switching from `sp1` to `sp2` (or from single to double precision if `sp2` is `nothing`). They are only usefull when `mode=:multi` - `max_iter2`, `ϵ_pdd2`, `ϵ_rb2`, `ϵ_rc2`: same as `max_iter`, `ϵ_pdd`, `ϵ_rb` and `ϵ_rc`, but used for switching from `sp2` to `sp3` (or from double to quadruple precision if `sp3` is `nothing`). They are only usefull when `mode=:multi` and/or `T0=Float128` - `ϵ_rbz` : primal transition tolerance for the zoom procedure, (used only if `refinement=:zoom`) - `ϵ_Δx`: step tolerance for the current point estimate (note: this criterion is currently disabled) - `ϵ_μ`: duality measure tolerance (note: this criterion is currently disabled) - `max_time`: maximum time to solve the QP The constructor itol = InputTol(::Type{T}; max_iter :: I = 200, max_iter1 :: I = 40, max_iter2 :: I = 180, ϵ_pdd :: T = 1e-8, ϵ_pdd1 :: T = 1e-2, ϵ_pdd2 :: T = 1e-4, ϵ_rb :: T = 1e-6, ϵ_rb1 :: T = 1e-4, ϵ_rb2 :: T = 1e-5, ϵ_rbz :: T = 1e-3, ϵ_rc :: T = 1e-6, ϵ_rc1 :: T = 1e-4, ϵ_rc2 :: T = 1e-5, ϵ_Δx :: T = 1e-16, ϵ_μ :: T = 1e-9) where {T<:Real, I<:Integer} InputTol(; kwargs...) = InputTol(Float64; kwargs...) returns a `InputTol` struct that initializes the stopping criteria for RipQP. The 1 and 2 characters refer to the transitions between the chosen solvers in `:multi`. If `sp2` and `sp3` are not precised when calling [`RipQP.ripqp`](@ref), they refer to transitions between floating-point systems. """ struct InputTol{T <: Real, I <: Integer} # maximum number of iterations max_iter::I max_iter1::I # only in multi mode max_iter2::I # only in multi mode with T0 = Float128 # relative primal-dual gap tolerance ϵ_pdd::T ϵ_pdd1::T # only in multi mode ϵ_pdd2::T # only in multi mode with T0 = Float128 # primal residual ϵ_rb::T ϵ_rb1::T # only in multi mode ϵ_rb2::T # only in multi mode with T0 = Float128 ϵ_rbz::T # only when using zoom refinement # dual residual ϵ_rc::T ϵ_rc1::T # only in multi mode ϵ_rc2::T # only in multi mode with T0 = Float128 # unused residuals (for now) ϵ_μ::T ϵ_Δx::T # maximum time for resolution max_time::Float64 end function InputTol( ::Type{T}; max_iter::I = 200, max_iter1::I = 40, max_iter2::I = 180, ϵ_pdd::T = (T == Float64) ? 1e-8 : sqrt(eps(T)), ϵ_pdd1::T = T(1e-2), ϵ_pdd2::T = T(1e-4), ϵ_rb::T = (T == Float64) ? 1e-6 : sqrt(eps(T)), ϵ_rb1::T = T(1e-4), ϵ_rb2::T = T(1e-5), ϵ_rbz::T = T(1e-5), ϵ_rc::T = (T == Float64) ? 1e-6 : sqrt(eps(T)), ϵ_rc1::T = T(1e-4), ϵ_rc2::T = T(1e-5), ϵ_Δx::T = eps(T), ϵ_μ::T = sqrt(eps(T)), max_time::Float64 = 1200.0, ) where {T <: Real, I <: Integer} return InputTol{T, I}( max_iter, max_iter1, max_iter2, ϵ_pdd, ϵ_pdd1, ϵ_pdd2, ϵ_rb, ϵ_rb1, ϵ_rb2, ϵ_rbz, ϵ_rc, ϵ_rc1, ϵ_rc2, ϵ_μ, ϵ_Δx, max_time, ) end InputTol(; kwargs...) = InputTol(Float64; kwargs...) mutable struct Tolerances{T <: Real} pdd::T # primal-dual difference (relative) rb::T # primal residuals tolerance rc::T # dual residuals tolerance tol_rb::T # ϵ_rb * (1 + ||r_b0||) tol_rc::T # ϵ_rc * (1 + ||r_c0||) μ::T # duality measure Δx::T normalize_rtol::Bool # true if normalize_rtol=true, then tol_rb, tol_rc = ϵ_rb, ϵ_rc end mutable struct Point{T <: Real, S} x::S # size nvar y::S # size ncon s_l::S # size nlow (useless zeros corresponding to infinite lower bounds are not stored) s_u::S # size nupp (useless zeros corresponding to infinite upper bounds are not stored) function Point( x::AbstractVector{T}, y::AbstractVector{T}, s_l::AbstractVector{T}, s_u::AbstractVector{T}, ) where {T <: Real} S = typeof(x) return new{T, S}(x, y, s_l, s_u) end end convert(::Type{Point{T, S}}, pt::Point) where {T <: Real, S} = Point(convert(S, pt.x), convert(S, pt.y), convert(S, pt.s_l), convert(S, pt.s_u)) abstract type AbstractResiduals{T <: Real, S} end mutable struct Residuals{T <: Real, S} <: AbstractResiduals{T, S} rb::S # primal residuals Ax - b rc::S # dual residuals -Qx + Aᵀy + s_l - s_u rbNorm::T # ||rb|| rcNorm::T # ||rc|| end convert(::Type{AbstractResiduals{T, S}}, res::Residuals) where {T <: Real, S <: AbstractVector{T}} = Residuals(convert(S, res.rb), convert(S, res.rc), convert(T, res.rbNorm), convert(T, res.rcNorm)) mutable struct ResidualsHistory{T <: Real, S} <: AbstractResiduals{T, S} rb::S # primal residuals Ax - b rc::S # dual residuals -Qx + Aᵀy + s_l - s_u rbNorm::T # ||rb|| rcNorm::T # ||rc|| rbNormH::Vector{T} # list of rb values rcNormH::Vector{T} # list of rc values pddH::Vector{T} # list of pdd values kiterH::Vector{Int} # number of matrix vector product if using a Krylov method μH::Vector{T} # list of μ values min_bound_distH::Vector{T} # list of minimum values of x - lvar and uvar - x KΔxy::S # K * Δxy Kres::S # ||KΔxy-rhs|| (residuals Krylov method) KresNormH::Vector{T} # list of ||KΔxy-rhs|| KresPNormH::Vector{T} KresDNormH::Vector{T} end convert( ::Type{AbstractResiduals{T, S}}, res::ResidualsHistory, ) where {T <: Real, S <: AbstractVector{T}} = ResidualsHistory( convert(S, res.rb), convert(S, res.rc), convert(T, res.rbNorm), convert(T, res.rcNorm), convert(Array{T, 1}, res.rbNormH), convert(Array{T, 1}, res.rcNormH), convert(Array{T, 1}, res.pddH), res.kiterH, convert(Array{T, 1}, res.μH), convert(Array{T, 1}, res.min_bound_distH), convert(S, res.KΔxy), convert(S, res.Kres), convert(Array{T, 1}, res.KresNormH), convert(Array{T, 1}, res.KresPNormH), convert(Array{T, 1}, res.KresDNormH), ) function init_residuals( rb::AbstractVector{T}, rc::AbstractVector{T}, rbNorm::T, rcNorm::T, iconf::InputConfig, sp::SolverParams, id::QM_IntData, ) where {T <: Real} S = typeof(rb) if iconf.history stype = typeof(sp) if stype <: NewtonParams Kn = length(rb) + length(rc) + id.nlow + id.nupp elseif stype <: NormalParams Kn = length(rb) else Kn = length(rb) + length(rc) end KΔxy = S(undef, Kn) Kres = S(undef, Kn) return ResidualsHistory{T, S}( rb, rc, rbNorm, rcNorm, T[], T[], T[], Int[], T[], T[], KΔxy, Kres, T[], T[], T[], ) else return Residuals{T, S}(rb, rc, rbNorm, rcNorm) end end mutable struct Regularization{T <: Real} ρ::T # curent top-left regularization parameter δ::T # cureent bottom-right regularization parameter ρ_min::T # ρ minimum value δ_min::T # δ minimum value regul::Symbol # regularization mode (:classic, :dynamic, or :none) end convert(::Type{Regularization{T}}, regu::Regularization{T0}) where {T <: Real, T0 <: Real} = Regularization(T(regu.ρ), T(regu.δ), T(regu.ρ_min), T(regu.δ_min), regu.regul) abstract type IterData{T <: Real, S} end mutable struct IterDataCPU{T <: Real, S} <: IterData{T, S} Δxy::S # Newton step [Δx; Δy] Δs_l::S Δs_u::S x_m_lvar::S # x - lvar uvar_m_x::S # uvar - x Qx::S ATy::S # Aᵀy Ax::S xTQx_2::T # xᵀQx cTx::T # cᵀx pri_obj::T # 1/2 xᵀQx + cᵀx + c0 dual_obj::T # -1/2 xᵀQx + yᵀb + s_lᵀlvar - s_uᵀuvar + c0 μ::T # duality measure (s_lᵀ(x-lvar) + s_uᵀ(uvar-x)) / (nlow+nupp) pdd::T # primal dual difference (relative) pri_obj - dual_obj / pri_obj qp::Bool # true if qp false if lp minimize::Bool perturb::Bool end mutable struct IterDataGPU{T <: Real, S} <: IterData{T, S} Δxy::S # Newton step [Δx; Δy] Δs_l::S Δs_u::S x_m_lvar::S # x - lvar uvar_m_x::S # uvar - x Qx::S ATy::S # Aᵀy Ax::S xTQx_2::T # xᵀQx cTx::T # cᵀx pri_obj::T # 1/2 xᵀQx + cᵀx + c0 dual_obj::T # -1/2 xᵀQx + yᵀb + s_lᵀlvar - s_uᵀuvar + c0 μ::T # duality measure (s_lᵀ(x-lvar) + s_uᵀ(uvar-x)) / (nlow+nupp) pdd::T # primal dual difference (relative) pri_obj - dual_obj / pri_obj qp::Bool # true if qp false if lp minimize::Bool perturb::Bool store_vpri::S store_vdual_l::S store_vdual_u::S IterDataGPU( Δxy::S, Δs_l::S, Δs_u::S, x_m_lvar::S, uvar_m_x::S, Qx::S, ATy::S, Ax::S, xTQx_2::T, cTx::T, pri_obj::T, dual_obj::T, μ::T, pdd::T, qp::Bool, minimize::Bool, perturb::Bool, ) where {T <: Real, S} = new{T, S}( Δxy, Δs_l, Δs_u, x_m_lvar, uvar_m_x, Qx, ATy, Ax, xTQx_2, cTx, pri_obj, dual_obj, μ, pdd, qp, minimize, perturb, similar(Qx), similar(Δs_l), similar(Δs_u), ) end function IterData( Δxy, Δs_l, Δs_u, x_m_lvar, uvar_m_x, Qx, ATy, Ax, xTQx_2, cTx, pri_obj, dual_obj, μ, pdd, qp, minimize, perturb, ) if typeof(Δxy) <: Vector return IterDataCPU( Δxy, Δs_l, Δs_u, x_m_lvar, uvar_m_x, Qx, ATy, Ax, xTQx_2, cTx, pri_obj, dual_obj, μ, pdd, qp, minimize, perturb, ) else return IterDataGPU( Δxy, Δs_l, Δs_u, x_m_lvar, uvar_m_x, Qx, ATy, Ax, xTQx_2, cTx, pri_obj, dual_obj, μ, pdd, qp, minimize, perturb, ) end end convert( ::Type{IterData{T, S}}, itd::IterData{T0, S0}, ) where {T <: Real, S <: AbstractVector{T}, T0 <: Real, S0} = IterData( convert(S, itd.Δxy), convert(S, itd.Δs_l), convert(S, itd.Δs_u), convert(S, itd.x_m_lvar), convert(S, itd.uvar_m_x), convert(S, itd.Qx), convert(S, itd.ATy), convert(S, itd.Ax), convert(T, itd.xTQx_2), convert(T, itd.cTx), convert(T, itd.pri_obj), convert(T, itd.dual_obj), convert(T, itd.μ), convert(T, itd.pdd), itd.qp, itd.minimize, itd.perturb, ) abstract type ScaleData{T <: Real, S} end mutable struct ScaleDataLP{T <: Real, S} <: ScaleData{T, S} d1::S d2::S r_k::S c_k::S end mutable struct ScaleDataQP{T <: Real, S} <: ScaleData{T, S} deq::S c_k::S end mutable struct StartingPointData{T <: Real, S} dual_val::S s0_l1::S s0_u1::S end function ScaleData(fd::QM_FloatData{T, S}, id::QM_IntData, scaling::Bool) where {T, S} if scaling if nnz(fd.Q) > 0 sd = ScaleDataQP{T, S}(fill!(S(undef, id.nvar + id.ncon), one(T)), S(undef, id.nvar + id.ncon)) else if fd.uplo == :U m, n = id.nvar, id.ncon else m, n = id.ncon, id.nvar end sd = ScaleDataLP{T, S}( fill!(S(undef, id.nvar), one(T)), fill!(S(undef, id.ncon), one(T)), S(undef, n), S(undef, m), ) end else empty_v = S(undef, 0) sd = ScaleDataQP{T, S}(empty_v, empty_v) end return sd end convert( ::Type{StartingPointData{T, S}}, spd::StartingPointData{T0, S0}, ) where {T, S <: AbstractVector{T}, T0, S0} = StartingPointData{T, S}(convert(S, spd.dual_val), convert(S, spd.s0_l1), convert(S, spd.s0_u1)) abstract type PreallocatedData{T <: Real, S} end mutable struct StopCrit{T} optimal::Bool small_μ::Bool tired::Bool max_iter::Int max_time::T start_time::T Δt::T end mutable struct Counters time_allocs::Float64 time_solve::Float64 c_catch::Int # safety try:cath c_regu_dim::Int # number of δ_min reductions k::Int # iter count km::Int # iter relative to precision: if k+=1 and T==Float128, km +=16 (km+=4 if T==Float64 and km+=1 if T==Float32) tfact::UInt64 # time linear solve tsolve::UInt64 # time linear solve kc::Int # maximum corrector steps c_ref::Int # current number of refinements w::SystemWrite # store SystemWrite data last_sp::Bool # true if currently using the last solver to iterate (always true in mono-precision) iters_sp::Int iters_sp2::Int iters_sp3::Int end mutable struct PreallocatedFloatData{ T, S, Res <: AbstractResiduals{T, S}, Dda <: DescentDirectionAllocs{T, S}, Pad <: PreallocatedData{T, S}, } pt::Point{T, S} res::Res itd::IterData{T, S} dda::Dda pad::Pad end abstract type AbstractRipQPSolver{T, S} <: SolverCore.AbstractOptimizationSolver end mutable struct RipQPMonoSolver{ T, S, I, QMType <: AbstractQuadraticModel{T, S}, Sd <: ScaleData{T, S}, Tsc <: Real, QMfd <: Abstract_QM_FloatData{T, S}, Pfd <: PreallocatedFloatData{T, S}, } <: AbstractRipQPSolver{T, S} QM::QMType id::QM_IntData iconf::InputConfig{I} itol::InputTol{T, I} sd::Sd spd::StartingPointData{T, S} sc::StopCrit{Tsc} cnts::Counters display::Bool fd::QMfd ϵ::Tolerances{T} pfd::Pfd # initial data in type of 1st solver end mutable struct RipQPDoubleSolver{ T, S, I, QMType <: AbstractQuadraticModel{T, S}, Sd <: ScaleData{T, S}, Tsc <: Real, T1, S1, QMfd1 <: Abstract_QM_FloatData{T1, S1}, QMfd2 <: Abstract_QM_FloatData{T, S}, Pfd <: PreallocatedFloatData{T1, S1}, } <: AbstractRipQPSolver{T, S} QM::QMType id::QM_IntData iconf::InputConfig{I} itol::InputTol{T, I} sd::Sd spd::StartingPointData{T1, S1} sc::StopCrit{Tsc} cnts::Counters display::Bool fd1::QMfd1 ϵ1::Tolerances{T1} fd2::QMfd2 ϵ2::Tolerances{T} pfd::Pfd # initial data in type of 1st solver end mutable struct RipQPTripleSolver{ T, S, I, QMType <: AbstractQuadraticModel{T, S}, Sd <: ScaleData{T, S}, Tsc <: Real, T1, S1, QMfd1 <: Abstract_QM_FloatData{T1, S1}, T2, QMfd2 <: Abstract_QM_FloatData{T2}, QMfd3 <: Abstract_QM_FloatData{T, S}, Pfd <: PreallocatedFloatData{T1, S1}, } <: AbstractRipQPSolver{T, S} QM::QMType id::QM_IntData iconf::InputConfig{I} itol::InputTol{T, I} sd::Sd spd::StartingPointData{T1, S1} sc::StopCrit{Tsc} cnts::Counters display::Bool fd1::QMfd1 ϵ1::Tolerances{T1} fd2::QMfd2 ϵ2::Tolerances{T2} fd3::QMfd3 ϵ3::Tolerances{T} pfd::Pfd # initial data in type of 1st solver end abstract type AbstractRipQPParameters{T} end struct RipQPMonoParameters{T <: Real, SP1 <: SolverParams{T}, SM1 <: SolveMethod} <: AbstractRipQPParameters{T} sp::SP1 solve_method::SM1 end struct RipQPDoubleParameters{ T <: Real, SP1 <: SolverParams, SP2 <: SolverParams{T}, SM1 <: SolveMethod, SM2 <: SolveMethod, } <: AbstractRipQPParameters{T} sp::SP1 sp2::SP2 solve_method::SM1 solve_method2::SM2 end struct RipQPTripleParameters{ T <: Real, SP1 <: SolverParams, SP2 <: SolverParams, SP3 <: SolverParams{T}, SM1 <: SolveMethod, SM2 <: SolveMethod, SM3 <: SolveMethod, } <: AbstractRipQPParameters{T} sp::SP1 sp2::SP2 sp3::SP3 solve_method::SM1 solve_method2::SM2 solve_method3::SM3 end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
10498
change_vector_eltype(S0::Type{<:Vector}, ::Type{T}) where {T} = S0.name.wrapper{T, 1} convert_mat(M::Union{SparseMatrixCOO, SparseMatrixCSC}, ::Type{T}) where {T} = convert(typeof(M).name.wrapper{T, Int}, M) convert_mat(M::Matrix, ::Type{T}) where {T} = convert(Matrix{T}, M) function push_history_residuals!( res::ResidualsHistory{T}, itd::IterData{T}, pad::PreallocatedData{T}, id::QM_IntData, ) where {T <: Real} push!(res.rbNormH, res.rbNorm) push!(res.rcNormH, res.rcNorm) push!(res.pddH, itd.pdd) push!(res.μH, itd.μ) bound_dist = zero(T) if id.nlow > 0 && id.nupp > 0 bound_dist = min(minimum(itd.x_m_lvar), minimum(itd.uvar_m_x)) elseif id.nlow > 0 && id.nupp == 0 bound_dist = min(minimum(itd.x_m_lvar)) elseif id.nlow == 0 && id.nupp > 0 bound_dist = min(minimum(itd.uvar_m_x)) end (id.nlow > 0 || id.nupp > 0) && push!(res.min_bound_distH, bound_dist) pad_type = typeof(pad) if pad_type <: PreallocatedDataAugmentedKrylov || pad_type <: PreallocatedDataNewtonKrylov push!(res.kiterH, pad.kiter) push!(res.KresNormH, norm(res.Kres)) push!(res.KresPNormH, @views norm(res.Kres[(id.nvar + 1):(id.nvar + id.ncon)])) push!(res.KresDNormH, @views norm(res.Kres[1:(id.nvar)])) elseif pad_type <: PreallocatedDataNormalKrylov push!(res.kiterH, niterations(pad.KS)) push!(res.KresNormH, norm(res.Kres)) end end # log utils uses_krylov(pad::PreallocatedData) = false function setup_log_header(pad::PreallocatedData{T}) where {T} if uses_krylov(pad) @info log_header( [:k, :pri_obj, :pdd, :rbNorm, :rcNorm, :α_pri, :α_du, :μ, :ρ, :δ, :kiter, :x], [Int, T, T, T, T, T, T, T, T, T, Int, Char], hdr_override = Dict( :k => "iter", :pri_obj => "obj", :pdd => "rgap", :rbNorm => "‖rb‖", :rcNorm => "‖rc‖", ), ) else @info log_header( [:k, :pri_obj, :pdd, :rbNorm, :rcNorm, :α_pri, :α_du, :μ, :ρ, :δ], [Int, T, T, T, T, T, T, T, T, T], hdr_override = Dict( :k => "iter", :pri_obj => "obj", :pdd => "rgap", :rbNorm => "‖rb‖", :rcNorm => "‖rc‖", ), ) end end function status_to_char(st::String) if st == "user-requested exit" return 'u' elseif st == "maximum number of iterations exceeded" return 'i' else return 's' end end status_to_char(KS::KrylovSolver) = status_to_char(KS.stats.status) function show_log_row_krylov( pad::PreallocatedData{T}, itd::IterData{T}, res::AbstractResiduals{T}, cnts::Counters, α_pri::T, α_dual::T, ) where {T} @info log_row( Any[ cnts.k, itd.minimize ? itd.pri_obj : -itd.pri_obj, itd.pdd, res.rbNorm, res.rcNorm, α_pri, α_dual, itd.μ, pad.regu.ρ, pad.regu.δ, pad.kiter, status_to_char(pad.KS), ], ) end function show_log_row( pad::PreallocatedData{T}, itd::IterData{T}, res::AbstractResiduals{T}, cnts::Counters, α_pri::T, α_dual::T, ) where {T} if uses_krylov(pad) show_log_row_krylov(pad, itd, res, cnts, α_pri, α_dual) else @info log_row( Any[ cnts.k, itd.minimize ? itd.pri_obj : -itd.pri_obj, itd.pdd, res.rbNorm, res.rcNorm, α_pri, α_dual, itd.μ, pad.regu.ρ, pad.regu.δ, ], ) end end solver_name(pad::PreallocatedData) = string(typeof(pad).name.name)[17:end] function show_used_solver(pad::PreallocatedData{T}) where {T} slv_name = solver_name(pad) @info "Solving in $T using $slv_name" end function set_ripqp_solver_specific!(stats::GenericExecutionStats, field::Symbol, value) stats.solver_specific[field] = value end # inner stats multipliers function set_ripqp_bounds_multipliers!( stats::GenericExecutionStats, s_l::AbstractVector{T}, s_u::AbstractVector{T}, ilow::AbstractVector{Int}, iupp::AbstractVector{Int}, ) where {T} stats.multipliers_L[ilow] .= s_l stats.multipliers_U[iupp] .= s_u end # outer stats multipliers function get_slack_multipliers( multipliers_in::AbstractVector{T}, multipliers_L_in::AbstractVector{T}, multipliers_U_in::AbstractVector{T}, id::QM_IntData, idi::IntDataInit{Int}, ) where {T <: Real} nlow, nupp, nrng = length(idi.ilow), length(idi.iupp), length(idi.irng) njlow, njupp, njrng = length(idi.jlow), length(idi.jupp), length(idi.jrng) S = typeof(multipliers_in) if idi.nvar != id.nvar multipliers_L = multipliers_L_in[1:(idi.nvar)] multipliers_U = multipliers_U_in[1:(idi.nvar)] else multipliers_L = multipliers_L_in multipliers_U = multipliers_U_in end multipliers = fill!(S(undef, idi.ncon), zero(T)) multipliers[idi.jfix] .= @views multipliers_in[idi.jfix] multipliers[idi.jlow] .+= @views multipliers_L_in[id.ilow[(nlow + nrng + 1):(nlow + nrng + njlow)]] multipliers[idi.jupp] .-= @views multipliers_U_in[id.iupp[(nupp + nrng + 1):(nupp + nrng + njupp)]] multipliers[idi.jrng] .+= @views multipliers_L_in[id.ilow[(nlow + nrng + njlow + 1):end]] .- multipliers_U_in[id.iupp[(nupp + nrng + njupp + 1):end]] return multipliers, multipliers_L, multipliers_U end function ripqp_solver_specific(QM::AbstractQuadraticModel{T}, history::Bool) where {T} if history solver_specific = Dict( :relative_iter_cnt => -1, :iters_sp => -1, :iters_sp2 => -1, :iters_sp3 => -1, :pdd => T(Inf), :psoperations => (typeof(QM) <: QuadraticModels.PresolvedQuadraticModel) ? QM.psd.operations : [], :rbNormH => T[], :rcNormH => T[], :pddH => T[], :nprodH => Int[], :min_bound_distH => T[], :KresNormH => T[], :KresPNormH => T[], :KresDNormH => T[], ) else solver_specific = Dict( :relative_iter_cnt => -1, :iters_sp => -1, :iters_sp2 => -1, :iters_sp3 => -1, :pdd => T(Inf), :psoperations => (typeof(QM) <: QuadraticModels.PresolvedQuadraticModel) ? QM.psd.operations : [], ) end return solver_specific end function set_ripqp_stats!( stats::GenericExecutionStats, pt::Point{T}, res::AbstractResiduals{T}, pad::PreallocatedData{T}, itd::IterData{T}, id::QM_IntData, sc::StopCrit, cnts::Counters, max_iter::Int, ) where {T} if cnts.k >= max_iter status = :max_iter elseif sc.tired status = :max_time elseif sc.optimal status = :first_order else status = :unknown end set_status!(stats, status) set_solution!(stats, pt.x) set_constraint_multipliers!(stats, pt.y) set_ripqp_bounds_multipliers!(stats, pt.s_l, pt.s_u, id.ilow, id.iupp) set_objective!(stats, itd.minimize ? itd.pri_obj : -itd.pri_obj) set_primal_residual!(stats, res.rbNorm) set_dual_residual!(stats, res.rcNorm) set_iter!(stats, cnts.k) elapsed_time = time() - cnts.time_solve set_time!(stats, elapsed_time) # set stats.solver_specific set_ripqp_solver_specific!(stats, :relative_iter_cnt, cnts.km) set_ripqp_solver_specific!(stats, :iters_sp, cnts.iters_sp) set_ripqp_solver_specific!(stats, :iters_sp2, cnts.iters_sp2) set_ripqp_solver_specific!(stats, :iters_sp3, cnts.iters_sp3) set_ripqp_solver_specific!(stats, :pdd, itd.pdd) if typeof(res) <: ResidualsHistory set_ripqp_solver_specific!(stats, :rbNormH, res.rbNormH) set_ripqp_solver_specific!(stats, :rcNormH, res.rcNormH) set_ripqp_solver_specific!(stats, :pddH, res.pddH) set_ripqp_solver_specific!(stats, :nprodH, res.kiterH) set_ripqp_solver_specific!(stats, :μH, res.μH) set_ripqp_solver_specific!(stats, :min_bound_distH, res.min_bound_distH) set_ripqp_solver_specific!(stats, :KresNormH, res.KresNormH) set_ripqp_solver_specific!(stats, :KresPNormH, res.KresPNormH) set_ripqp_solver_specific!(stats, :KresDNormH, res.KresDNormH) end if pad isa PreallocatedDataK2Krylov && pad.pdat isa LDLData && pad.pdat.K_fact isa LDLFactorizationData nnzLDL = length(pad.pdat.K_fact.LDL.Lx) + length(pad.pdat.K_fact.LDL.d) set_ripqp_solver_specific!(stats, :nnzLDL, nnzLDL) end end function get_inner_model_data( QM::QuadraticModel{T}, QMps::AbstractQuadraticModel{T}, ps::Bool, scaling::Bool, history::Bool, ) where {T <: Real} # save inital IntData to compute multipliers at the end of the algorithm idi = IntDataInit(QMps) QM_inner = SlackModel(QMps) if QM_inner.meta.ncon == length(QM_inner.meta.jfix) && !ps && scaling QM_inner = deepcopy(QM_inner) # if not modified by SlackModel and presolve end if !QM.meta.minimize && !ps # switch to min problem if not modified by presolve QuadraticModels.switch_H_to_max!(QM_inner.data) QM_inner.data.c .= .-QM_inner.data.c QM_inner.data.c0 = -QM_inner.data.c0 end stats_inner = GenericExecutionStats( QM_inner; solution = QM_inner.meta.x0, multipliers = QM_inner.meta.y0, multipliers_L = fill!(similar(QM_inner.meta.x0), zero(T)), multipliers_U = fill!(similar(QM_inner.meta.x0), zero(T)), solver_specific = ripqp_solver_specific(QM_inner, history), ) return QM_inner, stats_inner, idi end function get_stats_outer( stats_inner::GenericExecutionStats{T}, QM::QuadraticModel{T}, QMps::AbstractQuadraticModel{T}, id::QM_IntData, idi::IntDataInit, start_time::Float64, ps::Bool, ) where {T <: Real} multipliers, multipliers_L, multipliers_U = get_slack_multipliers( stats_inner.multipliers, stats_inner.multipliers_L, stats_inner.multipliers_U, id, idi, ) if ps sol_in = QMSolution( stats_inner.solution, stats_inner.multipliers, stats_inner.multipliers_L, stats_inner.multipliers_U, ) sol = postsolve(QM, QMps, sol_in) x, multipliers, multipliers_L, multipliers_U = sol.x, sol.y, sol.s_l, sol.s_u else x = stats_inner.solution[1:(idi.nvar)] end solver_specific = stats_inner.solver_specific solver_specific[:psoperations] = QMps isa QuadraticModels.PresolvedQuadraticModel ? QMps.psd.operations : [] elapsed_time = time() - start_time return GenericExecutionStats( QM, status = stats_inner.status, solution = x, objective = stats_inner.objective, dual_feas = stats_inner.dual_feas, primal_feas = stats_inner.primal_feas, multipliers = multipliers, multipliers_L = multipliers_L, multipliers_U = multipliers_U, iter = stats_inner.iter, elapsed_time = elapsed_time, solver_specific = solver_specific, ) end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
3481
# Gondzio's multiple centrality correctors method function update_rxs!(rxs_l, rxs_u, Hmin, Hmax, x_m_l_αΔp, u_m_x_αΔp, s_l_αΔp, s_u_αΔp, nlow, nupp) @inbounds @simd for i = 1:nlow rxs_l[i] = s_l_αΔp[i] * x_m_l_αΔp[i] if Hmin <= rxs_l[i] <= Hmax rxs_l[i] = 0 elseif rxs_l[i] < Hmin rxs_l[i] -= Hmin else rxs_l[i] -= Hmax end if rxs_l[i] > Hmax rxs_l[i] = Hmax end end @inbounds @simd for i = 1:nupp rxs_u[i] = -s_u_αΔp[i] * u_m_x_αΔp[i] if Hmin <= -rxs_u[i] <= Hmax rxs_u[i] = 0 elseif -rxs_u[i] < Hmin rxs_u[i] += Hmin else rxs_u[i] += Hmax end if rxs_u[i] < -Hmax rxs_u[i] = -Hmax end end end function multi_centrality_corr!( dda::DescentDirectionAllocsPC{T}, pad::PreallocatedData{T}, pt::Point{T}, α_pri::T, α_dual::T, itd::IterData{T}, fd::Abstract_QM_FloatData{T}, id::QM_IntData, cnts::Counters, res::AbstractResiduals{T}, ) where {T <: Real} iter_c = 0 # current number of correction iterations corr_flag = true #stop correction if false # for storage issues Δ_aff = Δp and Δ_cc = Δm dda.Δxy_aff .= itd.Δxy dda.Δs_l_aff .= itd.Δs_l dda.Δs_u_aff .= itd.Δs_u @inbounds while iter_c < cnts.kc && corr_flag # Δp = Δ_aff + Δ_cc δα, γ, βmin, βmax = T(0.1), T(0.1), T(0.1), T(10) α_p2, α_d2 = min(α_pri + δα, one(T)), min(α_dual + δα, one(T)) update_pt_aff!( dda.x_m_l_αΔ_aff, dda.u_m_x_αΔ_aff, dda.s_l_αΔ_aff, dda.s_u_αΔ_aff, dda.Δxy_aff, dda.Δs_l_aff, dda.Δs_u_aff, itd.x_m_lvar, itd.uvar_m_x, pt.s_l, pt.s_u, α_p2, α_d2, id.ilow, id.iupp, ) μ_p = compute_μ( dda.x_m_l_αΔ_aff, dda.u_m_x_αΔ_aff, dda.s_l_αΔ_aff, dda.s_u_αΔ_aff, id.nlow, id.nupp, ) σ = (μ_p / itd.μ)^3 Hmin, Hmax = βmin * σ * itd.μ, βmax * σ * itd.μ # corrector-centering step update_rxs!( dda.rxs_l, dda.rxs_u, Hmin, Hmax, dda.x_m_l_αΔ_aff, dda.u_m_x_αΔ_aff, dda.s_l_αΔ_aff, dda.s_u_αΔ_aff, id.nlow, id.nupp, ) itd.Δxy .= 0 @. itd.Δxy[id.ilow] += dda.rxs_l / itd.x_m_lvar @. itd.Δxy[id.iupp] += dda.rxs_u / itd.uvar_m_x out = solver!(itd.Δxy, pad, dda, pt, itd, fd, id, res, cnts, :cc) @. itd.Δs_l = @views -(dda.rxs_l + pt.s_l * itd.Δxy[id.ilow]) / itd.x_m_lvar @. itd.Δs_u = @views (dda.rxs_u + pt.s_u * itd.Δxy[id.iupp]) / itd.uvar_m_x itd.Δxy .+= dda.Δxy_aff itd.Δs_l .+= dda.Δs_l_aff itd.Δs_u .+= dda.Δs_u_aff α_p2, α_d2 = compute_αs(pt.x, pt.s_l, pt.s_u, fd.lvar, fd.uvar, itd.Δxy, itd.Δs_l, itd.Δs_u, id.nvar) if α_p2 >= α_pri + γ * δα && α_d2 >= α_dual + γ * δα iter_c += 1 dda.Δxy_aff .= itd.Δxy dda.Δs_l_aff .= itd.Δs_l dda.Δs_u_aff .= itd.Δs_u α_pri, α_dual = α_p2, α_d2 else itd.Δxy .= dda.Δxy_aff itd.Δs_l .= dda.Δs_l_aff itd.Δs_u .= dda.Δs_u_aff corr_flag = false end end return α_pri, α_dual end # function to determine the number of centrality corrections function nb_corrector_steps!(cnts::Counters) rfs = cnts.tfact / cnts.tsolve if rfs <= 10 cnts.kc = 0 elseif 10 < rfs <= 30 cnts.kc = 1 elseif 30 < rfs <= 50 cnts.kc = 2 elseif rfs > 50 cnts.kc = 3 else p = Int(round(rfs / 50)) cntd.kc = p + 2 if cnts.kc > 10 cnts.kc = 10 end end end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
7648
include("solvers/sparse_fact_utils/abstract-factorization.jl") include("solve_method.jl") include("centrality_corr.jl") include("regularization.jl") include("system_write.jl") include("preconditioners/abstract-precond.jl") include("solvers/linearsolvers.jl") include("preconditioners/include-preconds.jl") include("transitions/transitions.jl") function compute_α_dual(v, dir_v) n = length(v) T = eltype(v) if n == 0 return one(T) end α = one(T) @inbounds for i = 1:n if dir_v[i] < zero(T) α_new = -v[i] * T(0.999) / dir_v[i] if α_new < α α = α_new end end end return α end function compute_α_primal(v, dir_v, lvar, uvar) n = length(v) T = eltype(v) α_l, α_u = one(T), one(T) @inbounds for i = 1:n if dir_v[i] > zero(T) α_u_new = (uvar[i] - v[i]) * T(0.999) / dir_v[i] if α_u_new < α_u α_u = α_u_new end elseif dir_v[i] < zero(T) α_l_new = (lvar[i] - v[i]) * T(0.999) / dir_v[i] if α_l_new < α_l α_l = α_l_new end end end return min(α_l, α_u) end function compute_αs(x, s_l, s_u, lvar, uvar, Δxy, Δs_l, Δs_u, nvar) α_pri = @views compute_α_primal(x, Δxy[1:nvar], lvar, uvar) α_dual_l = compute_α_dual(s_l, Δs_l) α_dual_u = compute_α_dual(s_u, Δs_u) return α_pri, min(α_dual_l, α_dual_u) end function compute_μ(x_m_lvar, uvar_m_x, s_l, s_u, nb_low, nb_upp) return (dot(s_l, x_m_lvar) + dot(s_u, uvar_m_x)) / (nb_low + nb_upp) end function update_pt!(x, y, s_l, s_u, α_pri, α_dual, Δxy, Δs_l, Δs_u, ncon, nvar) @. x += @views α_pri * Δxy[1:nvar] @. y += @views α_dual * Δxy[(nvar + 1):(ncon + nvar)] @. s_l += α_dual * Δs_l @. s_u += α_dual * Δs_u end function safe_boundary(v::T) where {T <: Real} if v == zero(T) v = eps(T)^2 end return v end # "security" if x is too close from lvar or uvar function boundary_safety!(x_m_lvar, uvar_m_x) @. x_m_lvar = safe_boundary(x_m_lvar) @. uvar_m_x = safe_boundary(uvar_m_x) end function perturb_x!( x::AbstractVector{T}, s_l::AbstractVector{T}, s_u::AbstractVector{T}, x_m_lvar::AbstractVector{T}, uvar_m_x::AbstractVector{T}, lvar::AbstractVector{T}, uvar::AbstractVector{T}, μ::T, ilow::Vector{Int}, iupp::Vector{Int}, nlow::Int, nupp::Int, nvar::Int, ) where {T} pert = μ * 10 if pert > zero(T) for i = 1:nvar ldist_i = x[i] - lvar[i] udist_i = uvar[i] - x[i] alea = rand(T) + T(0.5) x[i] = (ldist_i < udist_i) ? x[i] + alea * pert : x[i] - alea * pert end for i = 1:nlow alea = rand(T) + T(0.5) s_l[i] += alea * pert end for i = 1:nupp alea = rand(T) + T(0.5) s_u[i] += alea * pert end end @. x_m_lvar = @views x[ilow] - lvar[ilow] @. uvar_m_x = @views uvar[iupp] - x[iupp] boundary_safety!(x_m_lvar, uvar_m_x) boundary_safety!(s_l, s_u) end function update_IterData!(itd, pt, fd, id, safety) T = eltype(itd.x_m_lvar) @. itd.x_m_lvar = @views pt.x[id.ilow] - fd.lvar[id.ilow] @. itd.uvar_m_x = @views fd.uvar[id.iupp] - pt.x[id.iupp] safety && boundary_safety!(itd.x_m_lvar, itd.uvar_m_x) itd.μ = compute_μ(itd.x_m_lvar, itd.uvar_m_x, pt.s_l, pt.s_u, id.nlow, id.nupp) if itd.perturb && itd.μ ≤ eps(T) perturb_x!( pt.x, pt.s_l, pt.s_u, itd.x_m_lvar, itd.uvar_m_x, fd.lvar, fd.uvar, itd.μ, id.ilow, id.iupp, id.nlow, id.nupp, id.nvar, ) itd.μ = compute_μ(itd.x_m_lvar, itd.uvar_m_x, pt.s_l, pt.s_u, id.nlow, id.nupp) end mul!(itd.Qx, fd.Q, pt.x) itd.xTQx_2 = dot(pt.x, itd.Qx) / 2 fd.uplo == :U ? mul!(itd.ATy, fd.A, pt.y) : mul!(itd.ATy, fd.A', pt.y) fd.uplo == :U ? mul!(itd.Ax, fd.A', pt.x) : mul!(itd.Ax, fd.A, pt.x) itd.cTx = dot(fd.c, pt.x) itd.pri_obj = itd.xTQx_2 + itd.cTx + fd.c0 if typeof(pt.x) <: Vector itd.dual_obj = @views dot(fd.b, pt.y) - itd.xTQx_2 + dot(pt.s_l, fd.lvar[id.ilow]) - dot(pt.s_u, fd.uvar[id.iupp]) + fd.c0 else # views and dot not working with GPU arrays itd.dual_obj = dual_obj_gpu( fd.b, pt.y, itd.xTQx_2, pt.s_l, pt.s_u, fd.lvar, fd.uvar, fd.c0, id.ilow, id.iupp, itd.store_vdual_l, itd.store_vdual_u, ) end itd.pdd = abs(itd.pri_obj - itd.dual_obj) / (one(T) + abs(itd.pri_obj)) end function update_data!( pt::Point{T}, α_pri::T, α_dual::T, itd::IterData{T}, pad::PreallocatedData{T}, res::AbstractResiduals{T}, fd::QM_FloatData{T}, id::QM_IntData, ) where {T <: Real} # (x, y, s_l, s_u) += α * Δ update_pt!( pt.x, pt.y, pt.s_l, pt.s_u, α_pri, α_dual, itd.Δxy, itd.Δs_l, itd.Δs_u, id.ncon, id.nvar, ) update_IterData!(itd, pt, fd, id, true) #update Residuals @. res.rb = itd.Ax - fd.b @. res.rc = itd.ATy - itd.Qx - fd.c res.rc[id.ilow] .+= pt.s_l res.rc[id.iupp] .-= pt.s_u # update stopping criterion values: # rcNorm, rbNorm = norm(rc), norm(rb) # xNorm = norm(x) # yNorm = norm(y) # optimal = pdd < ϵ_pdd && rbNorm < ϵ_rb * max(1, bNorm + ANorm * xNorm) && # rcNorm < ϵ_rc * max(1, cNorm + QNorm * xNorm + ANorm * yNorm) res.rcNorm, res.rbNorm = norm(res.rc, Inf), norm(res.rb, Inf) typeof(res) <: ResidualsHistory && push_history_residuals!(res, itd, pad, id) end function iter!( pt::Point{T}, itd::IterData{T}, fd::Abstract_QM_FloatData{T}, id::QM_IntData, res::AbstractResiduals{T}, sc::StopCrit{Tc}, dda::DescentDirectionAllocs{T}, pad::PreallocatedData{T}, ϵ::Tolerances{T}, cnts::Counters, iconf::InputConfig, display::Bool; last_iter::Bool = true, # false if there are several solvers sp and the current solve does not uses the last one ) where {T <: Real, Tc <: Real} @inbounds while cnts.k < sc.max_iter && !sc.optimal && !sc.tired (cnts.kc == -1) && (cnts.tfact = time_ns()) # timer centrality_corr factorization out = update_pad!(pad, dda, pt, itd, fd, id, res, cnts) # update data for the solver! function used (cnts.kc == -1) && (cnts.tfact = time_ns() - cnts.tfact) out == 1 && break # Solve system to find a direction of descent out = update_dd!(dda, pt, itd, fd, id, res, pad, cnts) out == 1 && break (cnts.kc == -1) && nb_corrector_steps!(cnts) if typeof(pt.x) <: Vector α_pri, α_dual = compute_αs(pt.x, pt.s_l, pt.s_u, fd.lvar, fd.uvar, itd.Δxy, itd.Δs_l, itd.Δs_u, id.nvar) else α_pri, α_dual = compute_αs_gpu( pt.x, pt.s_l, pt.s_u, fd.lvar, fd.uvar, itd.Δxy, itd.Δs_l, itd.Δs_u, id.nvar, itd.store_vpri, itd.store_vdual_l, itd.store_vdual_u, ) end if cnts.kc > 0 # centrality corrections α_pri, α_dual = multi_centrality_corr!(dda, pad, pt, α_pri, α_dual, itd, fd, id, cnts, res) ## TODO replace by centrality_corr.jl, deal with α end update_data!(pt, α_pri, α_dual, itd, pad, res, fd, id) # update point, residuals, objectives... sc.optimal = itd.pdd < ϵ.pdd && res.rbNorm < ϵ.tol_rb && res.rcNorm < ϵ.tol_rc sc.small_μ = itd.μ < ϵ.μ cnts.k += 1 if T == Float32 cnts.km += 1 elseif T == Float64 cnts.km += 4 else cnts.km += 16 end sc.Δt = time() - sc.start_time sc.tired = sc.Δt > sc.max_time display == true && (show_log_row(pad, itd, res, cnts, α_pri, α_dual)) # check alpha values in multi-precision !last_iter && iconf.early_multi_stop && small_αs(α_pri, α_dual, cnts) && break end end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
3674
# tools for the regularization of the system. # update regularization values in classic mode if there is a failure during factorization function update_regu_trycatch!(regu::Regularization{T}, cnts::Counters) where {T} !cnts.last_sp && return 1 if cnts.c_regu_dim == 0 && cnts.c_catch == 0 regu.δ *= T(1e2) regu.δ_min *= T(1e2) regu.ρ *= T(1e3) regu.ρ_min *= T(1e3) elseif cnts.c_regu_dim == 0 && cnts.c_catch != 0 regu.δ *= T(1e1) regu.δ_min *= T(1e1) regu.ρ *= T(1e0) regu.ρ_min *= T(1e0) elseif cnts.c_regu_dim != 0 && cnts.c_catch == 0 regu.δ *= T(1e5) regu.δ_min *= T(1e5) regu.ρ *= T(1e5) regu.ρ_min *= T(1e5) else regu.δ *= T(1e1) regu.δ_min *= T(1e1) regu.ρ *= T(1e1) regu.ρ_min *= T(1e1) end return 0 end function update_regu!(regu) if regu.δ >= regu.δ_min regu.δ /= 10 end if regu.ρ >= regu.ρ_min regu.ρ /= 10 end end # update regularization, and corrects if the magnitude of the diagonal of the matrix is too high function update_regu_diagK2!( regu::Regularization{T}, K::Symmetric{<:Real, <:SparseMatrixCSC}, diagind_K, μ::T, nvar::Int, cnts::Counters; safety_dist_bnd::Bool = true, ) where {T} update_regu_diagK2!(regu, K.data.nzval, diagind_K, μ, nvar, cnts, safety_dist_bnd) end function update_regu_diagK2!( regu::Regularization{T}, K::Symmetric{<:Real, <:SparseMatrixCOO}, diagind_K, μ, nvar::Int, cnts::Counters; safety_dist_bnd::Bool = false, ) where {T} update_regu_diagK2!(regu, K.data.vals, diagind_K, μ, nvar, cnts, safety_dist_bnd) end function update_regu_diagK2!( regu::Regularization{T}, K_nzval::AbstractVector{T}, diagind_K, μ::T, nvar::Int, cnts::Counters, safety_dist_bnd::Bool, ) where {T} if safety_dist_bnd if T == Float64 && regu.regul == :classic && cnts.k > 10 && μ ≤ eps(T) && cnts.c_regu_dim < 20 regu.δ_min /= 10 regu.δ /= 10 cnts.c_regu_dim += 1 end if T == Float64 && regu.regul == :classic && cnts.k > 10 && cnts.c_catch <= 1 && regu.δ_min >= eps(T)^(4 / 5) && @views minimum(K_nzval[diagind_K[1:nvar]]) < -one(T) / regu.δ / T(1e-6) regu.δ /= 10 regu.δ_min /= 10 cnts.c_regu_dim += 1 elseif !cnts.last_sp && cnts.c_regu_dim <= 2 && cnts.k ≥ 5 && @views minimum(K_nzval[diagind_K[1:nvar]]) < -one(T) / eps(T) && @views maximum(K_nzval[diagind_K[1:nvar]]) > -one(T) / 10 regu.regul == :classic && return 1 elseif T != Float32 && T != Float64 && cnts.k > 10 && cnts.c_catch <= 1 && @views minimum(K_nzval[diagind_K[1:nvar]]) < -one(T) / regu.δ / T(1e-15) regu.δ /= 10 regu.δ_min /= 10 cnts.c_regu_dim += 1 end end update_regu!(regu) return 0 end function update_regu_diagK2_5!( regu::Regularization{T}, D::AbstractVector{T}, μ::T, cnts::Counters, ) where {T} if T == Float64 && cnts.k > 10 && μ ≤ eps(T) && cnts.c_regu_dim < 5 regu.δ_min /= 10 regu.δ /= 10 cnts.c_regu_dim += 1 end if T == Float64 && cnts.k > 10 && cnts.c_catch <= 1 && @views minimum(D) < -one(T) / regu.δ / T(1e-6) regu.δ /= 10 regu.δ_min /= 10 cnts.c_regu_dim += 1 elseif !cnts.last_sp && cnts.c_regu_dim < 2 && @views minimum(D) < -one(T) / regu.δ / T(1e-5) return 1 elseif T != Float32 && T != Float64 && cnts.k > 10 && cnts.c_catch <= 1 && @views minimum(D) < -one(T) / regu.δ / T(1e-15) regu.δ /= 10 regu.δ_min /= 10 cnts.c_regu_dim += 1 end update_regu!(regu) return 0 end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
9130
export PC, IPF mutable struct PC <: SolveMethod end Base.isequal(sm1::PC, sm2::PC) = true mutable struct DescentDirectionAllocsPC{T <: Real, S} <: DescentDirectionAllocs{T, S} Δxy_aff::S # affine-step solution of the augmented system [Δx_aff; Δy_aff], size nvar + ncon Δs_l_aff::S # size nlow Δs_u_aff::S # size nupp x_m_l_αΔ_aff::S # x + α_aff * Δxy_aff - lvar , size nlow u_m_x_αΔ_aff::S # uvar - (x + α_aff * Δxy_aff) , size nupp s_l_αΔ_aff::S # s_l + α_aff * Δs_l_aff , size nlow s_u_αΔ_aff::S # s_u + α_aff * Δs_u_aff , size nupp rxs_l::S # - σ * μ * e + ΔX_aff * Δ_S_l_aff , size nlow rxs_u::S # σ * μ * e + ΔX_aff * Δ_S_u_aff , size nupp function DescentDirectionAllocsPC( Δxy_aff::S, Δs_l_aff::S, Δs_u_aff::S, x_m_l_αΔ_aff::S, u_m_x_αΔ_aff::S, s_l_αΔ_aff::S, s_u_αΔ_aff::S, rxs_l::S, rxs_u::S, ) where {S <: AbstractVector} T = eltype(Δxy_aff) return new{T, S}( Δxy_aff, Δs_l_aff, Δs_u_aff, x_m_l_αΔ_aff, u_m_x_αΔ_aff, s_l_αΔ_aff, s_u_αΔ_aff, rxs_l, rxs_u, ) end end DescentDirectionAllocs(id::QM_IntData, sm::PC, ::Type{S}) where {S <: AbstractVector} = DescentDirectionAllocsPC( S(undef, id.nvar + id.ncon), # Δxy_aff S(undef, id.nlow), # Δs_l_aff S(undef, id.nupp), # Δs_u_aff S(undef, id.nlow), # x_m_l_αΔ_aff S(undef, id.nupp), # u_m_x_αΔ_aff S(undef, id.nlow), # s_l_αΔ_aff S(undef, id.nupp), # s_u_αΔ_aff S(undef, id.nlow), # rxs_l S(undef, id.nupp), # rxs_u ) convert( ::Type{<:DescentDirectionAllocs{T, S}}, dda::DescentDirectionAllocsPC{T0, S0}, ) where {T <: Real, S <: AbstractVector{T}, T0 <: Real, S0} = DescentDirectionAllocsPC( convert(S, dda.Δxy_aff), convert(S, dda.Δs_l_aff), convert(S, dda.Δs_u_aff), convert(S, dda.x_m_l_αΔ_aff), convert(S, dda.u_m_x_αΔ_aff), convert(S, dda.s_l_αΔ_aff), convert(S, dda.s_u_αΔ_aff), convert(S, dda.rxs_l), convert(S, dda.rxs_u), ) function update_pt_aff!( x_m_l_αΔ_aff, u_m_x_αΔ_aff, s_l_αΔ_aff, s_u_αΔ_aff, Δxy_aff, Δs_l_aff, Δs_u_aff, x_m_lvar, uvar_m_x, s_l, s_u, α_aff_pri, α_aff_dual, ilow, iupp, ) @. x_m_l_αΔ_aff = @views x_m_lvar + α_aff_pri * Δxy_aff[ilow] @. u_m_x_αΔ_aff = @views uvar_m_x - α_aff_pri * Δxy_aff[iupp] @. s_l_αΔ_aff = s_l + α_aff_dual * Δs_l_aff @. s_u_αΔ_aff = s_u + α_aff_dual * Δs_u_aff end # Mehrotra's Predictor-Corrector algorithm function update_dd!( dda::DescentDirectionAllocsPC{T}, pt::Point{T}, itd::IterData{T}, fd::Abstract_QM_FloatData{T}, id::QM_IntData, res::AbstractResiduals{T}, pad::PreallocatedData{T}, cnts::Counters, ) where {T <: Real} # solve system aff dda.Δxy_aff[1:(id.nvar)] .= .-res.rc dda.Δxy_aff[(id.nvar + 1):(id.nvar + id.ncon)] .= .-res.rb if typeof(pad) <: PreallocatedDataAugmented || typeof(pad) <: PreallocatedDataNormal dda.Δxy_aff[id.ilow] .+= pt.s_l dda.Δxy_aff[id.iupp] .-= pt.s_u elseif typeof(pad) <: PreallocatedDataNewton @. dda.Δs_l_aff = -itd.x_m_lvar * pt.s_l @. dda.Δs_u_aff = -itd.uvar_m_x * pt.s_u end cnts.w.write == true && write_system(cnts.w, pad.K, dda.Δxy_aff, :aff, cnts.k) out = solver!(dda.Δxy_aff, pad, dda, pt, itd, fd, id, res, cnts, :aff) out == 1 && return out if typeof(pad) <: PreallocatedDataAugmented || typeof(pad) <: PreallocatedDataNormal @. dda.Δs_l_aff = @views -pt.s_l - pt.s_l * dda.Δxy_aff[id.ilow] / itd.x_m_lvar @. dda.Δs_u_aff = @views -pt.s_u + pt.s_u * dda.Δxy_aff[id.iupp] / itd.uvar_m_x end if typeof(pt.x) <: Vector α_aff_pri, α_aff_dual = compute_αs( pt.x, pt.s_l, pt.s_u, fd.lvar, fd.uvar, dda.Δxy_aff, dda.Δs_l_aff, dda.Δs_u_aff, id.nvar, ) else α_aff_pri, α_aff_dual = compute_αs_gpu( pt.x, pt.s_l, pt.s_u, fd.lvar, fd.uvar, dda.Δxy_aff, dda.Δs_l_aff, dda.Δs_u_aff, id.nvar, itd.store_vpri, itd.store_vdual_l, itd.store_vdual_u, ) end # (x-lvar, uvar-x, s_l, s_u) .+= α_aff * Δ_aff update_pt_aff!( dda.x_m_l_αΔ_aff, dda.u_m_x_αΔ_aff, dda.s_l_αΔ_aff, dda.s_u_αΔ_aff, dda.Δxy_aff, dda.Δs_l_aff, dda.Δs_u_aff, itd.x_m_lvar, itd.uvar_m_x, pt.s_l, pt.s_u, α_aff_pri, α_aff_dual, id.ilow, id.iupp, ) μ_aff = compute_μ(dda.x_m_l_αΔ_aff, dda.u_m_x_αΔ_aff, dda.s_l_αΔ_aff, dda.s_u_αΔ_aff, id.nlow, id.nupp) σ = (μ_aff / itd.μ)^3 # corrector-centering step if typeof(pad) <: PreallocatedDataAugmented || typeof(pad) <: PreallocatedDataNormal dda.rxs_l .= @views (-σ * itd.μ) .+ dda.Δxy_aff[id.ilow] .* dda.Δs_l_aff dda.rxs_u .= @views (σ * itd.μ) .+ dda.Δxy_aff[id.iupp] .* dda.Δs_u_aff itd.Δxy .= 0 @. itd.Δxy[id.ilow] += dda.rxs_l / itd.x_m_lvar @. itd.Δxy[id.iupp] += dda.rxs_u / itd.uvar_m_x elseif typeof(pad) <: PreallocatedDataNewton itd.Δxy[1:end] .= 0 itd.Δs_l .= @views (σ * itd.μ) .- dda.Δxy_aff[id.ilow] .* dda.Δs_l_aff itd.Δs_u .= @views (σ * itd.μ) .+ dda.Δxy_aff[id.iupp] .* dda.Δs_u_aff end cnts.w.write == true && write_system(cnts.w, pad.K, itd.Δxy, :cc, cnts.k) (cnts.kc == -1) && (cnts.tsolve = time_ns()) # timer centrality_corr solve out = solver!(itd.Δxy, pad, dda, pt, itd, fd, id, res, cnts, :cc) (cnts.kc == -1) && (cnts.tsolve = time_ns() - cnts.tsolve) out == 1 && return out if typeof(pad) <: PreallocatedDataAugmented || typeof(pad) <: PreallocatedDataNormal @. itd.Δs_l = @views -(dda.rxs_l + pt.s_l * itd.Δxy[id.ilow]) / itd.x_m_lvar @. itd.Δs_u = @views (dda.rxs_u + pt.s_u * itd.Δxy[id.iupp]) / itd.uvar_m_x end # final direction itd.Δxy .+= dda.Δxy_aff itd.Δs_l .+= dda.Δs_l_aff itd.Δs_u .+= dda.Δs_u_aff return out end mutable struct IPF <: SolveMethod r::Float64 γ::Float64 end Base.isequal(sm1::IPF, sm2::IPF) = (sm1.r == sm2.r) && (sm1.γ == sm2.γ) IPF(; r::Float64 = 0.999, γ::Float64 = 0.05) = IPF(r, γ) mutable struct DescentDirectionAllocsIPF{T <: Real, S} <: DescentDirectionAllocs{T, S} r::T γ::T compl_l::S # complementarity s_lᵀ(x-lvar) compl_u::S # complementarity s_uᵀ(uvar-x) function DescentDirectionAllocsIPF( r::T, γ::T, compl_l::S, compl_u::S, ) where {T <: Real, S <: AbstractVector{T}} return new{T, S}(r, γ, compl_l, compl_u) end end function DescentDirectionAllocs(id::QM_IntData, sm::IPF, ::Type{S}) where {S <: AbstractVector} T = eltype(S) return DescentDirectionAllocsIPF(T(sm.r), T(sm.γ), S(undef, id.nlow), S(undef, id.nupp)) end convert( ::Type{<:DescentDirectionAllocs{T, S}}, dda::DescentDirectionAllocsIPF{T0, S0}, ) where {T <: Real, S <: AbstractVector{T}, T0 <: Real, S0} = DescentDirectionAllocsIPF(T(dda.r), T(dda.γ), convert(S, dda.compl_l), convert(S, dda.compl_u)) function update_dd!( dda::DescentDirectionAllocsIPF{T}, pt::Point{T}, itd::IterData{T}, fd::Abstract_QM_FloatData{T}, id::QM_IntData, res::AbstractResiduals{T}, pad::PreallocatedData{T}, cnts::Counters, ) where {T <: Real} # D = [s_l (x-lvar) + s_u (uvar-x)] @. dda.compl_l = pt.s_l * itd.x_m_lvar @. dda.compl_u = pt.s_u * itd.uvar_m_x min_compl_l = (id.nlow > 0) ? minimum(dda.compl_l) / (sum(dda.compl_l) / id.nlow) : one(T) min_compl_u = (id.nupp > 0) ? minimum(dda.compl_u) / (sum(dda.compl_u) / id.nupp) : one(T) ξ = min(min_compl_l, min_compl_u) σ = dda.γ * min((one(T) - dda.r) * (one(T) - ξ) / ξ, T(2))^3 itd.Δxy[1:(id.nvar)] .= .-res.rc itd.Δxy[(id.nvar + 1):(id.nvar + id.ncon)] .= .-res.rb if typeof(pad) <: PreallocatedDataAugmented || typeof(pad) <: PreallocatedDataNormal itd.Δxy[id.ilow] .+= pt.s_l .- (σ * itd.μ) ./ itd.x_m_lvar itd.Δxy[id.iupp] .-= pt.s_u .- (σ * itd.μ) ./ itd.uvar_m_x elseif typeof(pad) <: PreallocatedDataNewton itd.Δs_l .= (σ * itd.μ) .- itd.x_m_lvar .* pt.s_l itd.Δs_u .= (σ * itd.μ) .- itd.uvar_m_x .* pt.s_u end cnts.w.write == true && write_system(cnts.w, pad.K, itd.Δxy, :IPF, cnts.k) out = solver!(itd.Δxy, pad, dda, pt, itd, fd, id, res, cnts, :IPF) out == 1 && return out if typeof(pad) <: PreallocatedDataAugmented || typeof(pad) <: PreallocatedDataNormal itd.Δs_l .= @views ((σ * itd.μ) .- pt.s_l .* itd.Δxy[id.ilow]) ./ itd.x_m_lvar .- pt.s_l itd.Δs_u .= @views ((σ * itd.μ) .+ pt.s_u .* itd.Δxy[id.iupp]) ./ itd.uvar_m_x .- pt.s_u end end function convert_solve_method( ::Type{<:DescentDirectionAllocs{T, S}}, dda::DescentDirectionAllocs{T_old}, solve_method_old::SolveMethod, solve_method_new::SolveMethod, id::QM_IntData, ) where {T, S, T_old} if isequal(solve_method_old, solve_method_new) if T_old == T return dda else return convert(DescentDirectionAllocs{T, S}, dda) end else if T_old == T && typeof(solve_method_old) <: IPF && typeof(solve_method_new) <: IPF # has to be IPF dda.r = T(solve_method_new.r) dda.γ = T(sole_method_new.γ) return dda else return DescentDirectionAllocs(id, solve_method_new, S) end end end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
462
function write_system( w::SystemWrite, K::Symmetric{T, SparseMatrixCSC{T, Int}}, rhs::Vector{T}, step::Symbol, iter::Int, ) where {T <: Real} if rem(iter + 1 - w.kfirst, w.kgap) == 0 if step != :cc K_str = string(w.name, "K_iter", iter + 1, ".mtx") MatrixMarket.mmwrite(K_str, K.data) end rhs_str = string(w.name, "rhs_iter", iter + 1, "_", step, ".rhs") open(rhs_str, "w") do io writedlm(io, rhs) end end end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
8799
export LDL """ preconditioner = LDL(; T = Float32, pos = :C, warm_start = true, fact_alg = LDLFact()) Preconditioner for [`K2KrylovParams`](@ref) using a LDL factorization in precision `T`. The `pos` argument is used to choose the type of preconditioning with an unsymmetric Krylov method. It can be `:C` (center), `:L` (left) or `:R` (right). The `warm_start` argument tells RipQP to solve the system with the LDL factorization before using the Krylov method with the LDLFactorization as a preconditioner. `fact_alg` should be a [`RipQP.AbstractFactorization`](@ref). """ mutable struct LDL{FloatType <: DataType, F <: AbstractFactorization} <: AbstractPreconditioner T::FloatType pos::Symbol # :L (left), :R (right) or :C (center) warm_start::Bool fact_alg::F end LDL(; T::DataType = Float32, pos = :R, warm_start = true, fact_alg = LDLFact()) = LDL(T, pos, warm_start, fact_alg) mutable struct LDLData{ T <: Real, S, Tlow, Op <: Union{LinearOperator, LRPrecond}, M <: Union{LinearOperator{T}, AbstractMatrix{T}}, F <: FactorizationData{Tlow}, } <: PreconditionerData{T, S} K::M regu::Regularization{Tlow} K_fact::F # factorized matrix tmp_res::Vector{Tlow} tmp_v::Vector{Tlow} fact_fail::Bool # true if factorization failed warm_start::Bool P::Op end precond_name(pdat::LDLData{T, S, Tlow}) where {T, S, Tlow} = string( Tlow, " ", string(typeof(pdat).name.name)[1:(end - 4)], " ", string(typeof(pdat.K_fact).name.name), ) types_linop(op::LinearOperator{T, I, F, Ftu, Faw, S}) where {T, I, F, Ftu, Faw, S} = T, I, F, Ftu, Faw, S lowtype(pdat::LDLData{T, S, Tlow}) where {T, S, Tlow} = Tlow function ldiv_stor!( res, K_fact::FactorizationData{T}, v, tmp_res::Vector{T}, tmp_v::Vector{T}, ) where {T} copyto!(tmp_v, v) ldiv!(tmp_res, K_fact, tmp_v) copyto!(res, tmp_res) end function ld_div!(y, b, n, Lp, Li, Lx, D, P) y .= b z = @views y[P] LDLFactorizations.ldl_lsolve!(n, z, Lp, Li, Lx) end function dlt_div!(y, b, n, Lp, Li, Lx, D, P) y .= b z = @views y[P] LDLFactorizations.ldl_dsolve!(n, z, D) LDLFactorizations.ldl_ltsolve!(n, z, Lp, Li, Lx) end function ld_div_stor!( res, K_fact::LDLFactorizations.LDLFactorization{T, Int, Int, Int}, v, tmp_res::Vector{T}, tmp_v::Vector{T}, ) where {T} copyto!(tmp_v, v) ld_div!(tmp_res, K_fact, tmp_v) copyto!(res, tmp_res) end function ld_div_stor!(res, v, tmp_res::Vector{T}, tmp_v::Vector{T}, n, Lp, Li, Lx, D, P) where {T} copyto!(tmp_v, v) ld_div!(tmp_res, tmp_v, n, Lp, Li, Lx, D, P) copyto!(res, tmp_res) end function dlt_div_stor!(res, v, tmp_res::Vector{T}, tmp_v::Vector{T}, n, Lp, Li, Lx, D, P) where {T} copyto!(tmp_v, v) dlt_div!(tmp_res, tmp_v, n, Lp, Li, Lx, D, P) copyto!(res, tmp_res) end function PreconditionerData( sp::AugmentedKrylovParams{T, <:LDL}, id::QM_IntData, fd::QM_FloatData{T}, regu::Regularization{T}, D::AbstractVector{T}, K, ) where {T <: Real} Tlow = sp.preconditioner.T @assert get_uplo(sp.preconditioner.fact_alg) == fd.uplo sp.form_mat = true regu_precond = Regularization( -Tlow(D[1]), Tlow(max(regu.δ, sqrt(eps(Tlow)))), sqrt(eps(Tlow)), sqrt(eps(Tlow)), regu.δ != 0 ? :classic : :dynamic, ) K_fact = @timeit_debug to "init factorization" init_fact(K, sp.preconditioner.fact_alg, Tlow) return PreconditionerData(sp, K_fact, id.nvar, id.ncon, regu_precond, K) end function PreconditionerData( sp::AugmentedKrylovParams{T, <:LDL}, K_fact::FactorizationData{Tlow}, nvar::Int, ncon::Int, regu_precond::Regularization{Tlow}, K, ) where {T, Tlow <: Real} regu_precond.regul = (K_fact isa LDLFactorizationData) ? :dynamic : :classic @assert T == eltype(K) if regu_precond.regul == :dynamic && K_fact isa LDLFactorizationData regu_precond.ρ, regu_precond.δ = -Tlow(eps(Tlow)^(3 / 4)), Tlow(eps(Tlow)^(0.45)) K_fact.LDL.r1, K_fact.LDL.r2 = regu_precond.ρ, regu_precond.δ K_fact.LDL.tol = Tlow(eps(Tlow)) K_fact.LDL.n_d = nvar end if T == Tlow if sp.kmethod == :gmres || sp.kmethod == :dqgmres || sp.kmethod == :gmresir || sp.kmethod == :ir if sp.preconditioner.pos == :C @assert K_fact isa LDLFactorizationData M = LinearOperator( T, nvar + ncon, nvar + ncon, false, false, (res, v) -> ld_div!( res, v, K_fact.LDL.n, K_fact.LDL.Lp, K_fact.LDL.Li, K_fact.LDL.Lx, K_fact.LDL.d, K_fact.LDL.P, ), ) N = LinearOperator( T, nvar + ncon, nvar + ncon, false, false, (res, v) -> dlt_div!( res, v, K_fact.LDL.n, K_fact.LDL.Lp, K_fact.LDL.Li, K_fact.LDL.Lx, K_fact.LDL.d, K_fact.LDL.P, ), ) elseif sp.preconditioner.pos == :L M = LinearOperator(T, nvar + ncon, nvar + ncon, true, true, (res, v) -> ldiv!(res, K_fact, v)) N = I elseif sp.preconditioner.pos == :R M = I N = LinearOperator(T, nvar + ncon, nvar + ncon, true, true, (res, v) -> ldiv!(res, K_fact, v)) end P = LRPrecond(M, N) else abs_diagonal!(K_fact) P = LinearOperator( Tlow, nvar + ncon, nvar + ncon, true, true, (res, v, α, β) -> ldiv!(res, K_fact, v), ) end else tmp_res = Vector{Tlow}(undef, nvar + ncon) tmp_v = Vector{Tlow}(undef, nvar + ncon) if sp.kmethod == :gmres || sp.kmethod == :dqgmres || sp.kmethod == :gmresir || sp.kmethod == :ir if sp.preconditioner.pos == :C @assert K_fact isa LDLFactorizationData M = LinearOperator( T, nvar + ncon, nvar + ncon, false, false, (res, v) -> ld_div_stor!( res, v, tmp_res, tmp_v, K_fact.LDL.n, K_fact.LDL.Lp, K_fact.LDL.Li, K_fact.LDL.Lx, K_fact.LDL.d, K_fact.LDL.P, ), ) N = LinearOperator( T, nvar + ncon, nvar + ncon, false, false, (res, v) -> dlt_div_stor!( res, v, tmp_res, tmp_v, K_fact.LDL.n, K_fact.LDL.Lp, K_fact.LDL.Li, K_fact.LDL.Lx, K_fact.LDL.d, K_fact.LDL.P, ), ) elseif sp.preconditioner.pos == :L M = LinearOperator( T, nvar + ncon, nvar + ncon, true, true, (res, v) -> ldiv_stor!(res, K_fact, v, tmp_res, tmp_v), ) N = I elseif sp.preconditioner.pos == :R M = I N = LinearOperator( T, nvar + ncon, nvar + ncon, true, true, (res, v) -> ldiv_stor!(res, K_fact, v, tmp_res, tmp_v), ) end P = LRPrecond(M, N) else abs_diagonal!(K_fact) P = LinearOperator( T, nvar + ncon, nvar + ncon, true, true, (res, v, α, β) -> ldiv_stor!(res, K_fact, v, tmp_res, tmp_v), ) end end return LDLData{T, Vector{T}, Tlow, typeof(P), typeof(K), typeof(K_fact)}( K, regu_precond, K_fact, T == Tlow ? T[] : tmp_res, T == Tlow ? T[] : tmp_v, false, sp.preconditioner.warm_start, P, ) end function update_preconditioner!( pdat::LDLData{T}, pad::PreallocatedData{T}, itd::IterData{T}, pt::Point{T}, id::QM_IntData, fd::Abstract_QM_FloatData{T}, cnts::Counters, ) where {T <: Real} Tlow = lowtype(pad.pdat) pad.pdat.regu.ρ, pad.pdat.regu.δ = max(pad.regu.ρ, sqrt(eps(Tlow))), max(pad.regu.ρ, sqrt(eps(Tlow))) out = factorize_K2!( pad.pdat.K, pad.pdat.K_fact, pad.D, pad.mt.diag_Q, pad.mt.diagind_K, pad.pdat.regu, pt.s_l, pt.s_u, itd.x_m_lvar, itd.uvar_m_x, id.ilow, id.iupp, id.ncon, id.nvar, cnts, itd.qp, ) # update D and factorize K if out == 1 pad.pdat.fact_fail = true return out end if pad.pdat.warm_start if T == Tlow ldiv!(pad.KS.x, pad.pdat.K_fact, pad.rhs) else ldiv_stor!(pad.KS.x, pad.pdat.K_fact, pad.rhs, pad.pdat.tmp_res, pad.pdat.tmp_v) end warm_start!(pad.KS, pad.KS.x) end if !( typeof(pad.KS) <: GmresSolver || typeof(pad.KS) <: DqgmresSolver || typeof(pad.KS) <: GmresIRSolver || typeof(pad.KS) <: IRSolver ) abs_diagonal!(pad.pdat.K_fact) end return 0 end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
396
export PreconditionerData, AbstractPreconditioner """ Abstract type for the preconditioners used with a solver using a Krylov method. """ abstract type AbstractPreconditioner end abstract type PreconditionerData{T <: Real, S} end precond_name(pdat::PreconditionerData) = string(typeof(pdat).name.name)[1:(end - 4)] # precond M⁻¹ K N⁻¹ mutable struct LRPrecond{Op1, Op2} M::Op1 N::Op2 end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
2959
export Equilibration """ preconditioner = Equilibration() Preconditioner using the equilibration algorithm in infinity norm. Works with: - [`K2KrylovParams`](@ref) - [`K3SKrylovParams`](@ref) - [`K3_5KrylovParams`](@ref) """ mutable struct Equilibration <: AbstractPreconditioner end mutable struct EquilibrationData{T <: Real, S} <: PreconditionerData{T, S} P::Diagonal{T, S} C_equi::Diagonal{T, S} end function PreconditionerData( sp::AugmentedKrylovParams{T, Equilibration}, id::QM_IntData, fd::QM_FloatData{T}, regu::Regularization{T}, D::AbstractVector{T}, K::Union{LinearOperator{T}, AbstractMatrix{T}}, ) where {T <: Real} P = Diagonal(similar(D, id.nvar + id.ncon)) P.diag .= one(T) C_equi = Diagonal(similar(D, id.nvar + id.ncon)) return EquilibrationData(P, C_equi) end function update_preconditioner!( pdat::EquilibrationData{T}, pad::PreallocatedData{T}, itd::IterData{T}, pt::Point{T}, id::QM_IntData, fd::QM_FloatData{T}, cnts::Counters, ) where {T <: Real} equilibrate_K2!( fd.Q.data, fd.A, pad.D, pad.regu.δ, id.nvar, id.ncon, pad.pdat.P, pad.pdat.C_equi, fd.uplo; ϵ = T(1.0e-4), max_iter = 100, ) pdat.P.diag .= pdat.P.diag .^ 2 end mutable struct EquilibrationK3SData{T <: Real, S, L <: LinearOperator{T}} <: PreconditionerData{T, S} P::L d_l::S d_u::S end function PreconditionerData( sp::NewtonKrylovParams{T, Equilibration}, id::QM_IntData, fd::QM_FloatData{T, S}, regu::Regularization{T}, K::Union{LinearOperator{T}, AbstractMatrix{T}}, ) where {T <: Real, S} d_l = fill!(S(undef, id.nlow), zero(T)) d_u = fill!(S(undef, id.nupp), zero(T)) P = BlockDiagonalOperator(opEye(T, id.nvar + id.ncon), opDiagonal(d_l), opDiagonal(d_u)) return EquilibrationK3SData(P, d_l, d_u) end function update_preconditioner!( pdat::EquilibrationK3SData{T}, pad::PreallocatedDataK3SKrylov{T}, itd::IterData{T}, pt::Point{T}, id::QM_IntData, fd::QM_FloatData{T}, cnts::Counters, ) where {T <: Real} TS = typeof(pad.KS) if TS <: GmresSolver || TS <: DqgmresSolver pad.pdat.d_l .= sqrt.(one(T) ./ max.(one(T), pad.x_m_lvar_div_s_l)) pad.pdat.d_u .= sqrt.(one(T) ./ max.(one(T), pad.uvar_m_x_div_s_u)) else pad.pdat.d_l .= one(T) ./ max.(one(T), pad.x_m_lvar_div_s_l) pad.pdat.d_u .= one(T) ./ max.(one(T), pad.uvar_m_x_div_s_u) end end function update_preconditioner!( pdat::EquilibrationK3SData{T}, pad::PreallocatedDataK3_5Krylov{T}, itd::IterData{T}, pt::Point{T}, id::QM_IntData, fd::QM_FloatData{T}, cnts::Counters, ) where {T <: Real} TS = typeof(pad.KS) if TS <: GmresSolver || TS <: DqgmresSolver pad.pdat.d_l .= sqrt.(one(T) ./ max.(pt.s_l, itd.x_m_lvar)) pad.pdat.d_u .= sqrt.(one(T) ./ max.(pt.s_u, itd.uvar_m_x)) else pad.pdat.d_l .= one(T) ./ max.(pt.s_l, itd.x_m_lvar) pad.pdat.d_u .= one(T) ./ max.(pt.s_u, itd.uvar_m_x) end end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
1035
export Identity """ preconditioner = Identity() Tells RipQP not to use a preconditioner. """ mutable struct Identity <: AbstractPreconditioner end mutable struct IdentityData{T <: Real, S, SI <: UniformScaling} <: PreconditionerData{T, S} P::SI end function PreconditionerData( sp::AugmentedKrylovParams{T, Identity}, id::QM_IntData, fd::QM_FloatData{T}, regu::Regularization{T}, D::AbstractVector{T}, K::Union{LinearOperator{T}, AbstractMatrix{T}}, ) where {T <: Real} P = I return IdentityData{T, typeof(fd.c), typeof(P)}(P) end function PreconditionerData( sp::NewtonKrylovParams{T, Identity}, id::QM_IntData, fd::QM_FloatData{T}, regu::Regularization{T}, K::Union{LinearOperator{T}, AbstractMatrix{T}}, ) where {T <: Real} P = I return IdentityData{T, typeof(fd.c), typeof(P)}(P) end function update_preconditioner!( pdat::IdentityData{T}, pad::PreallocatedData{T}, itd::IterData{T}, pt::Point{T}, id::QM_IntData, fd::QM_FloatData{T}, cnts::Counters, ) where {T <: Real} end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
90
include("identity.jl") include("jacobi.jl") include("equilibration.jl") include("LDL.jl")
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
1408
export Jacobi """ preconditioner = Jacobi() Preconditioner using the inverse of the diagonal of the system to solve. Works with: - [`K2KrylovParams`](@ref) - [`K2_5KrylovParams`](@ref) """ mutable struct Jacobi <: AbstractPreconditioner end mutable struct JacobiData{T <: Real, S, L <: LinearOperator} <: PreconditionerData{T, S} P::L diagQ::S invDiagK::S end function PreconditionerData( sp::AugmentedKrylovParams{T, Jacobi}, id::QM_IntData, fd::QM_FloatData{T}, regu::Regularization{T}, D::AbstractVector{T}, K::Union{LinearOperator{T}, AbstractMatrix{T}}, ) where {T <: Real} invDiagK = (one(T) / regu.δ) .* fill!(similar(fd.c, id.nvar + id.ncon), one(T)) diagQ = get_diag_Q_dense(fd.Q, fd.uplo) invDiagK[1:(id.nvar)] .= .-one(T) ./ (D .- diagQ) P = opDiagonal(invDiagK) return JacobiData{eltype(diagQ), typeof(diagQ), typeof(P)}(P, diagQ, invDiagK) end function update_preconditioner!( pdat::JacobiData{T}, pad::PreallocatedData{T}, itd::IterData{T}, pt::Point{T}, id::QM_IntData, fd::QM_FloatData{T}, cnts::Counters, ) where {T <: Real} if typeof(pad) <: PreallocatedDataK2_5Krylov pad.pdat.invDiagK[1:(id.nvar)] .= abs.(one(T) ./ (pad.D .- (pad.pdat.diagQ .* pad.sqrtX1X2 .^ 2))) else pad.pdat.invDiagK[1:(id.nvar)] .= abs.(one(T) ./ (pad.D .- pad.pdat.diagQ)) end pad.pdat.invDiagK[(id.nvar + 1):end] .= one(T) / pad.regu.δ end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
13865
import Krylov.KRYLOV_SOLVERS function init_Ksolver(M, v, sp::SolverParams) kmethod = sp.kmethod if kmethod ∈ (:gpmr, :diom, :fom, :dqgmres, :gmres) return eval(KRYLOV_SOLVERS[kmethod])(M, v, sp.mem) elseif kmethod == :gmresir return GmresIRSolver( GmresSolver(M, v, sp.mem), similar(v, sp.Tir), similar(v), similar(v), false, 0, ) elseif kmethod == :ir return IRSolver(similar(v), similar(v), similar(v, sp.Tir), similar(v), similar(v), false, 0) end return eval(KRYLOV_SOLVERS[kmethod])(M, v) end ksolve!( KS::MinresSolver{T}, K, rhs::AbstractVector{T}, M; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = minres!(KS, K, rhs, M = M, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax) ksolve!( KS::MinresQlpSolver{T}, K, rhs::AbstractVector{T}, M; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = minres_qlp!(KS, K, rhs, M = M, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax) ksolve!( KS::SymmlqSolver{T}, K, rhs::AbstractVector{T}, M; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = symmlq!(KS, K, rhs, M = M, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax) ksolve!( KS::CgSolver{T}, K, rhs::AbstractVector{T}, M; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = cg!(KS, K, rhs, M = M, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax) ksolve!( KS::CgLanczosSolver{T}, K, rhs::AbstractVector{T}, M; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = cg_lanczos!(KS, K, rhs, M = M, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax) ksolve!( KS::CrSolver{T}, K, rhs::AbstractVector{T}, M; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = cr!(KS, K, rhs, M = M, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax) ksolve!( KS::BilqSolver{T}, K, rhs::AbstractVector{T}, M; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = bilq!(KS, K, rhs, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax) ksolve!( KS::QmrSolver{T}, K, rhs::AbstractVector{T}, M; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = qmr!(KS, K, rhs, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax) ksolve!( KS::UsymlqSolver{T}, K, rhs::AbstractVector{T}, M; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = usymlq!(KS, K, rhs, rhs, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax) ksolve!( KS::UsymqrSolver{T}, K, rhs::AbstractVector{T}, M; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = usymqr!(KS, K, rhs, rhs, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax) ksolve!( KS::BicgstabSolver{T}, K, rhs::AbstractVector{T}, M; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = bicgstab!(KS, K, rhs, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax) ksolve!( KS::DiomSolver{T}, K, rhs::AbstractVector{T}, M; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = diom!(KS, K, rhs, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax) ksolve!( KS::FomSolver{T}, K, rhs::AbstractVector{T}, M; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = fom!(KS, K, rhs, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax) ksolve!( KS::DqgmresSolver{T}, K, rhs::AbstractVector{T}, M; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = dqgmres!(KS, K, rhs, M = M, N = I, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax) ksolve!( KS::DqgmresSolver{T}, K, rhs::AbstractVector{T}, P::LRPrecond; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = dqgmres!(KS, K, rhs, M = P.M, N = P.N, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax) ksolve!( KS::GmresSolver{T}, K, rhs::AbstractVector{T}, M; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = gmres!( KS, K, rhs, M = I, N = M, restart = true, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax, ) ksolve!( KS::GmresSolver{T}, K, rhs::AbstractVector{T}, P::LRPrecond; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} = gmres!( KS, K, rhs, M = P.M, N = P.N, restart = true, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax, ) ksolve!( KS::TricgSolver{T}, A, ξ1::AbstractVector{T}, ξ2::AbstractVector{T}, M, N; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), gsp::Bool = false, itmax::Int = 0, ) where {T} = tricg!( KS, A, ξ1, ξ2, M = M, N = N, flip = true, verbose = verbose, atol = atol, rtol = rtol, itmax = itmax, ) ksolve!( KS::TrimrSolver{T}, A, ξ1::AbstractVector{T}, ξ2::AbstractVector{T}, M, N; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), gsp::Bool = false, itmax::Int = 0, ) where {T} = trimr!( KS, A, ξ1, ξ2, M = M, N = (gsp == true ? I : N), τ = -one(T), ν = (gsp ? zero(T) : one(T)), verbose = verbose, atol = atol, rtol = rtol, itmax = itmax, ) function ksolve!( KS::GpmrSolver{T}, A, ξ1::AbstractVector{T}, ξ2::AbstractVector{T}, M, N; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), gsp::Bool = false, itmax::Int = 0, ) where {T} sqrtδI = sqrt(N.λ) * I return gpmr!( KS, A, A', ξ1, ξ2, C = sqrt.(M), D = gsp ? I : sqrtδI, E = sqrt.(M), F = gsp ? I : sqrtδI, λ = -one(T), μ = gsp ? zero(T) : one(T), verbose = verbose, atol = atol, rtol = rtol, itmax = itmax, ) end # gpmr solver for K3.5 function ksolve!( KS::GpmrSolver{T}, A, ξ1::AbstractVector{T}, ξ2::AbstractVector{T}, M, N::AbstractLinearOperator{T}; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} return gpmr!( KS, A, A', ξ1, ξ2, C = M, D = N, E = transpose(M), F = N, λ = -one(T), verbose = verbose, atol = atol, rtol = rtol, itmax = itmax, ) end function ksolve!( KS::LslqSolver{T}, A, ξ1::AbstractVector{T}, M, δ::T; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} return lslq!( KS, A, ξ1, M = M, N = δ > zero(T) ? (one(T) / δ) * I : I, verbose = verbose, atol = atol, btol = rtol, etol = zero(T), utol = zero(T), conlim = T(Inf), sqd = δ > zero(T), itmax = itmax, ) end function ksolve!( KS::LsqrSolver{T}, A, ξ1::AbstractVector{T}, M, δ::T; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} return lsqr!( KS, A, ξ1, M = M, N = δ > zero(T) ? (one(T) / δ) * I : I, verbose = verbose, axtol = atol, btol = rtol, # atol = atol, # rtol = rtol, etol = zero(T), conlim = T(Inf), sqd = δ > zero(T), itmax = itmax, ) end function ksolve!( KS::LsmrSolver{T}, A, ξ1::AbstractVector{T}, M, δ::T; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} return lsmr!( KS, A, ξ1, M = M, N = δ > zero(T) ? (one(T) / δ) * I : I, verbose = verbose, axtol = zero(T), # atol, btol = zero(T), # rtol, atol = atol, rtol = rtol, etol = zero(T), conlim = T(Inf), sqd = δ > zero(T), itmax = itmax, ) end function ksolve!( KS::LnlqSolver{T}, A, ξ2::AbstractVector{T}, M, δ::T; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} return lnlq!( KS, A, ξ2, N = M, M = δ > zero(T) ? (one(T) / δ) * I : I, verbose = verbose, atol = atol, rtol = rtol, sqd = δ > zero(T), itmax = itmax, ) end function ksolve!( KS::CraigSolver{T}, A, ξ2::AbstractVector{T}, M, δ::T; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} return craig!( KS, A, ξ2, N = M, M = δ > zero(T) ? (one(T) / δ) * I : I, λ = δ > zero(T) ? one(T) : zero(T), verbose = verbose, atol = atol, rtol = rtol, btol = zero(T), conlim = T(Inf), itmax = itmax, ) end function ksolve!( KS::CraigmrSolver{T}, A, ξ2::AbstractVector{T}, M, δ::T; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} return craigmr!( KS, A, ξ2, N = M, M = δ > zero(T) ? (one(T) / δ) * I : I, verbose = verbose, atol = atol, rtol = rtol, sqd = true, itmax = itmax, ) end function kscale!(rhs::AbstractVector{T}) where {T <: Real} rhsNorm = norm(rhs) if rhsNorm != zero(T) rhs ./= rhsNorm end return rhsNorm end function kunscale!(sol::AbstractVector{T}, rhsNorm::T) where {T <: Real} if rhsNorm != zero(T) sol .*= rhsNorm end end function update_kresiduals_history!( res::AbstractResiduals{T}, K, sol::AbstractVector{T}, rhs::AbstractVector{T}, ) where {T <: Real} if typeof(res) <: ResidualsHistory mul!(res.KΔxy, K, sol) # krylov residuals res.Kres .= res.KΔxy .- rhs end end function update_kresiduals_history_K1struct!( res::AbstractResiduals{T}, A, E, tmp, δ, sol::AbstractVector{T}, rhs::AbstractVector{T}, formul::Symbol, ) where {T <: Real} if typeof(res) <: ResidualsHistory mul!(tmp, A', sol) tmp ./= E @views mul!(res.KΔxy, A, tmp) if formul == :K1_1 mul!(res.Kres, A, rhs ./ E, -one(T), zero(T)) elseif formul == :K1_2 res.Kres .= .-rhs end res.Kres .+= res.KΔxy .+ δ .* sol # residual computation end end get_krylov_method_name(KS::KrylovSolver) = uppercase(string(typeof(KS).name.name)[1:(end - 6)]) solver_name(pad::Union{PreallocatedDataNewtonKrylov, PreallocatedDataAugmentedKrylov}) = string( string(typeof(pad).name.name)[17:end], " with $(get_krylov_method_name(pad.KS))", " and $(precond_name(pad.pdat)) preconditioner", ) solver_name(pad::PreallocatedDataNormalKrylov) = string(string(typeof(pad).name.name)[17:end], " with $(get_krylov_method_name(pad.KS))") mutable struct GmresIRSolver{T, FC, S, Tr, Sr <: AbstractVector{Tr}} <: KrylovSolver{T, FC, S} solver::GmresSolver{T, FC, S} r::Sr rsolves::S x::S warm_start::Bool itertot::Int end Krylov.niterations(KS::GmresIRSolver) = KS.itertot function Krylov.warm_start!(KS::GmresIRSolver, x) # only indicate to warm_start KS.warm_start = true end status_to_char(KS::GmresIRSolver) = status_to_char(KS.solver.stats.status) function ksolve!( KS::GmresIRSolver{T}, K, rhs::AbstractVector{T}, P::LRPrecond; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} r = KS.r Tr = eltype(r) rsolves = KS.rsolves if KS.warm_start mul!(r, K, KS.x) @. r = rhs - r else r .= zero(Tr) KS.x .= zero(T) end KS.solver.warm_start = false iter = 0 rsolves .= r optimal = iter ≥ itmax || norm(rsolves) ≤ atol while !optimal gmres!( KS.solver, K, rsolves, M = P.M, N = P.N, restart = false, verbose = verbose, atol = atol, rtol = rtol, itmax = length(KS.solver.c), ) KS.x .+= KS.solver.x mul!(r, K, KS.x) @. r = rhs - r iter += niterations(KS.solver) rsolves .= r optimal = iter ≥ itmax || niterations(KS.solver) == 0 || norm(rsolves) ≤ atol end KS.itertot = iter end mutable struct IRSolver{T, S <: AbstractVector{T}, Tr, Sr <: AbstractVector{Tr}} <: KrylovSolver{T, T, S} x_solve1::S x_solve2::S r::Sr rsolves::S x::S warm_start::Bool itertot::Int end Krylov.niterations(KS::IRSolver) = KS.itertot function Krylov.warm_start!(KS::IRSolver, x) # only indicate to warm_start KS.warm_start = true end status_to_char(KS::IRSolver) = 's' function ksolve!( KS::IRSolver{T}, K, rhs::AbstractVector{T}, P::LRPrecond; verbose::Integer = 0, atol::T = T(sqrt(eps(T))), rtol::T = T(sqrt(eps(T))), itmax::Int = 0, ) where {T} r = KS.r Tr = eltype(r) rsolves = KS.rsolves if KS.warm_start mul!(r, K, KS.x) @. r = rhs - r else r .= zero(Tr) KS.x .= zero(T) end iter = 0 rsolves .= r optimal = iter ≥ itmax || norm(rsolves) ≤ atol while !optimal mul!(KS.x_solve1, P.M, rsolves) mul!(KS.x_solve2, P.N, KS.x_solve1) KS.x .+= KS.x_solve2 mul!(r, K, KS.x) @. r = rhs - r iter += 1 rsolves .= r optimal = iter ≥ itmax || norm(rsolves) ≤ atol end KS.itertot = iter end function update_krylov_tol!(pad::PreallocatedData) if pad.atol > pad.atol_min pad.atol /= 10 end if pad.rtol > pad.rtol_min pad.rtol /= 10 end end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
1272
function ldl_dense!(A::Symmetric{T, Matrix{T}}) where {T <: Real} # use symmetric lower only @assert A.uplo == 'L' ldl_lowtri!(A.data) end function ldl_lowtri!(A::Matrix) n = size(A, 1) for j = 1:n djj = A[j, j] for k = 1:(j - 1) djj -= A[j, k]^2 * A[k, k] end A[j, j] = djj for i = (j + 1):n lij = A[i, j] # we use the lower block for k = 1:(j - 1) lij -= A[i, k] * A[j, k] * A[k, k] end A[i, j] = lij / djj end end end function solve_lowertri!(L, b) n = length(b) @inbounds for j = 1:n @simd for i = (j + 1):n b[i] -= L[i, j] * b[j] end end end function solve_lowertri_transpose!(LT, b) n = length(b) @inbounds for i = n:-1:1 @simd for j = (i - 1):-1:1 b[j] -= LT[i, j] * b[i] end end end function solve_diag!(D, b) n = length(b) @inbounds for j = 1:n b[j] /= D[j, j] end end # function solve(L, D, b) # x = copy(b) # solve_lowertri!(L, x) # solve_diag!(D, x) # solve_lowertri_transpose!(L, x) # return x # end function ldiv_dense!(LD, b) solve_lowertri!(LD, b) @views solve_diag!(Diagonal(LD[diagind(LD)]), b) solve_lowertri_transpose!(LD, b) return b end function ldiv_dense(x, LD, b) x .= b ldiv_dense!(LD, x) end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git
[ "MIT" ]
0.6.4
a734ff1ea463d482c7fad756d128810e829bd44b
code
201
include("augmented/augmented.jl") include("Newton/Newton.jl") include("normal/normal.jl") include("Krylov_utils.jl") include("ldl_dense.jl") function init_pad!(pad::PreallocatedData) return pad end
RipQP
https://github.com/JuliaSmoothOptimizers/RipQP.jl.git