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",
"BSD-3-Clause"
] | 0.1.0 | 6521428e41ae0924b30460ef1ffada3b07ab2bc1 | code | 1082 | # Portions translated from SLICOT-Reference distribution
# Copyright (c) 2002-2020 NICONET e.V.
function run_mc01wd(datfile, io=stdout)
NIN = 5
NOUT = 6
DPMAX = 10
P = Array{Float64,1}(undef, DPMAX+1)
Q = Array{Float64,1}(undef, DPMAX+1)
f = open(datfile,"r")
readline(f)
vs = split(readline(f))
DP = parse(BlasInt, vs[1])
if ( DP<=-1 || DP>DPMAX )
@error "Illegal DP=$DP"
end
vs = String[]
_isz = DP+1
while length(vs) < _isz
append!(vs, replace.(split(readline(f)),'D'=>'E'))
end
P[1:_isz] .= parsex.(Float64, vs)
vs = split(readline(f))
U1 = parse(Float64, replace(vs[1],'D'=>'E'))
U2 = parse(Float64, replace(vs[2],'D'=>'E'))
close(f)
# interp call 1
INFO = SLICOT.mc01wd!(DP, P, U1, U2, Q)
@test INFO == 0
INFO == 0 || return
println(io, "Q (power,coefft):")
show(io, "text/plain", hcat(0:DP-2,Q[3:DP+1]))
println(io)
println(io, "R (power, coefft):")
show(io, "text/plain", hcat(0:1,[Q[1]+Q[2]*U2,Q[2]]))
println(io)
end # run_mc01wd()
| SLICOTMath | https://github.com/RalphAS/SLICOTMath.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.1.0 | 6521428e41ae0924b30460ef1ffada3b07ab2bc1 | code | 1457 | # Julia code
# Copyright (c) 2022 the SLICOTMath.jl developers
# Portions extracted from SLICOT-Reference distribution:
# Copyright (c) 2002-2020 NICONET e.V.
function run_mc01xd(datfile, io=stdout)
NIN = 5
NOUT = 6
NEV = 3
LDWORK = 42
ZERO = 0.0e0
EVR = Array{Float64,1}(undef, NEV)
EVI = Array{Float64,1}(undef, NEV)
EVQ = Array{Float64,1}(undef, NEV)
DWORK = Array{Float64,1}(undef, LDWORK)
RT = Array{Float64,1}(undef, 2)
RTS = Array{ComplexF64,1}(undef, 3)
f = open(datfile,"r")
readline(f)
vs = split(readline(f))
ALPHA = parse(Float64, replace(vs[1],'D'=>'E'))
BETA = parse(Float64, replace(vs[2],'D'=>'E'))
GAMMA = parse(Float64, replace(vs[3],'D'=>'E'))
DELTA = parse(Float64, replace(vs[4],'D'=>'E'))
# interp call 1
INFO = SLICOT.mc01xd!(ALPHA, BETA, GAMMA, DELTA, EVR, EVI, EVQ)
@test INFO == 0
INFO == 0 || return
if ( INFO!=0 )
else
# interp output 1
println(io,"EVR:")
_nr = 3
show(io,"text/plain",EVR[1:_nr])
println(io,)
# interp output 2
println(io,"EVI:")
_nr = 3
show(io,"text/plain",EVI[1:_nr])
println(io,)
# interp output 3
println(io,"EVQ:")
_nr = 3
show(io,"text/plain",EVQ[1:_nr])
println(io,)
if ( true )
RTS = (EVR + im * EVI) ./ EVQ
# interp output 4
println(io,"RTS:")
_nr = 3
show(io,"text/plain",RTS[1:_nr])
println(io,)
end # if
end # if
close(f)
end # run_X()
| SLICOTMath | https://github.com/RalphAS/SLICOTMath.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.1.0 | 6521428e41ae0924b30460ef1ffada3b07ab2bc1 | code | 2413 | # Portions translated from SLICOT-Reference distribution
# Copyright (c) 2002-2020 NICONET e.V.
function run_mc03md(datfile, io=stdout)
NIN = 5
NOUT = 6
CP1MAX = 10
CP2MAX = 10
DP1MAX = 10
DP2MAX = 10
DP3MAX = 20
RP1MAX = 10
LDP11 = RP1MAX
LDP12 = CP1MAX
LDP21 = CP1MAX
LDP22 = CP2MAX
LDP31 = RP1MAX
LDP32 = CP2MAX
P1 = Array{Float64,3}(undef, LDP11,LDP12,DP1MAX+1)
P2 = Array{Float64,3}(undef, LDP21,LDP22,DP2MAX+1)
P3 = Array{Float64,3}(undef, LDP31,LDP32,DP3MAX+1)
DWORK = Array{Float64,1}(undef, CP1MAX)
f = open(datfile,"r")
readline(f)
vs = split(readline(f))
RP1 = parse(BlasInt, vs[1])
CP1 = parse(BlasInt, vs[2])
CP2 = parse(BlasInt, vs[3])
if ( RP1<0 || RP1>RP1MAX )
elseif ( CP1<0 || CP1>CP1MAX )
elseif ( CP2<0 || CP2>CP2MAX )
else
vs = split(readline(f))
DP1 = parse(BlasInt, vs[1])
if ( DP1<=-2 || DP1>DP1MAX )
else
_isz,_jsz,_ksz = (RP1,CP1,DP1 + 1)
for k in 1:_ksz
for j in 1:_jsz
vs = String[]
while length(vs) < _isz
append!(vs, replace.(split(readline(f)),'D'=>'E'))
end
P1[1:_isz,j,k] .= parsex.(Float64, vs)
end
end
vs = split(readline(f))
DP2 = parse(BlasInt, vs[1])
if ( DP2<=-2 || DP2>DP2MAX )
else
_isz,_jsz,_ksz = (CP1,CP2,DP2 + 1)
for k in 1:_ksz
for j in 1:_jsz
vs = String[]
while length(vs) < _isz
append!(vs, replace.(split(readline(f)),'D'=>'E'))
end
P2[1:_isz,j,k] .= parsex.(Float64, vs)
end
end
vs = split(readline(f))
DP3 = parse(BlasInt, vs[1])
if ( DP3<=-2 || DP3>DP3MAX )
else
_isz,_jsz,_ksz = (RP1,CP2,DP3 + 1)
for k in 1:_ksz
for j in 1:_jsz
vs = String[]
while length(vs) < _isz
append!(vs, replace.(split(readline(f)),'D'=>'E'))
end
P3[1:_isz,j,k] .= parsex.(Float64, vs)
end
end
vs = split(readline(f))
ALPHA = parse(Float64, replace(vs[1],'D'=>'E'))
# interp call 1
DP3, INFO = SLICOT.mc03md!(RP1, CP1, CP2, DP1, DP2, DP3, ALPHA, P1, P2, P3)
println(io, "DP3 = $DP3")
@test INFO == 0
INFO == 0 || return
if ( INFO!=0 )
else
for i in 1:RP1
for j in 1:CP2
println(io, "elt($i,$j): ",P3[i,j,1:DP3+1])
end
end
end # if
end # if
end # if
end # if
end # if
close(f)
end # run_mc03md()
| SLICOTMath | https://github.com/RalphAS/SLICOTMath.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.1.0 | 6521428e41ae0924b30460ef1ffada3b07ab2bc1 | code | 1898 | # Portions translated from SLICOT-Reference distribution
# Copyright (c) 2002-2020 NICONET e.V.
function run_mc03nd(datfile, io=stdout)
NIN = 5
NOUT = 6
DPMAX = 2
MPMAX = 5
NPMAX = 4
LDP1 = MPMAX
LDP2 = NPMAX
LDNULL = NPMAX
LDKER1 = NPMAX
LDKER2 = NPMAX
M = DPMAX*MPMAX
N = ( DPMAX-1 )*MPMAX+NPMAX
LIWORK = M+2*max( N,M+1 )+N
LDWORK = M*N^2+2*M*N+2*N^2
P = Array{Float64,3}(undef, LDP1,LDP2,DPMAX+1)
GAM = Array{BlasInt,1}(undef, M+1)
NULLSP = Array{Float64,2}(undef, LDNULL,(M+1))
KER = Array{Float64,3}(undef, LDKER1,LDKER2,M+1)
IWORK = Array{BlasInt,1}(undef, LIWORK)
DWORK = Array{Float64,1}(undef, LDWORK)
f = open(datfile,"r")
readline(f)
vs = split(readline(f))
MP = parse(BlasInt, vs[1])
NP = parse(BlasInt, vs[2])
DP = parse(BlasInt, vs[3])
TOL = parse(Float64, replace(vs[4],'D'=>'E'))
if ( MP<0 || MP>MPMAX )
elseif ( NP<0 || NP>NPMAX )
elseif ( DP<=0 || DP>DPMAX )
else
_isz,_jsz,_ksz = (MP,NP,DP + 1)
for k in 1:_ksz
for i in 1:_isz
vs = String[]
while length(vs) < _jsz
append!(vs, replace.(split(readline(f)),'D'=>'E'))
end
P[i,1:_jsz,k] .= parsex.(Float64, vs)
end
end
# interp call 1
DK, INFO = SLICOT.mc03nd!(MP, NP, DP, P, GAM, NULLSP, KER, TOL, IWORK, LDWORK)
println(io, "DK = $DK")
@test INFO == 0
INFO == 0 || return
if ( INFO!=0 )
elseif ( DK<0 )
else
NK = 0
M1 = 0
for i in 1:DK+1
NK = NK + GAM[i]
M1 = M1 + GAM[i]*i
end
# interp output 1
println(io, "NULLSP:")
_nc = M1
_nr = NP
show(io, "text/plain", NULLSP[1:_nr,1:_nc])
println(io)
println(io, "KER:")
for i in 1:NP
for j in 1:NK
println(io, "elt($i,$j: ",KER[i,j,1:DK+1])
end
end
end # if
end # if
close(f)
end # run_mc03nd()
| SLICOTMath | https://github.com/RalphAS/SLICOTMath.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.1.0 | 6521428e41ae0924b30460ef1ffada3b07ab2bc1 | code | 1652 | using SLICOTMath
const SLICOT=SLICOTMath
using Test
using LinearAlgebra
using LinearAlgebra: BlasInt
const BlasBool = BlasInt
LSAME(x,y) = uppercase(x) == uppercase(y)
# helpers for getting data from the examples
parsex(T,s) = parse(T,s)
# CAUTION: this relies on absence of spaces in complex constants
function parsex(::Type{ComplexF64}, s)
if s == "0"
return zero(ComplexF64)
end
s1 = split(s,",")
if length(s1) == 1
return parse(Float64,s1[1])+0.0im
end
if s1[2][1] in ['+','-']
impart = s1[2][1:end-1] * "im"
else
impart = '+' * s1[2][1:end-1] * "im"
end
s2 = s1[1][2:end] * impart
parse(ComplexF64, s2)
end
function parsex(::Type{Bool}, s)
return s[2] in ('T','t')
end
const quiet = Ref(true)
const tdir = joinpath(@__DIR__,"SLICOT-Reference")
if !isdir(joinpath(tdir,"examples"))
@error """Package tests require that 'test/SLICOT-Reference' hold the input data.
This can be prepared by installing a copy of the SLICOT distribution there,
or making a link to one.
"""
# force an early exit
@testset "installation" begin
@test false
end
end
files = readdir(@__DIR__)
funclist = [replace(s, "_test.jl" => "") for s in files if (length(s)>7) && (s[end-7:end] == "_test.jl")]
for func2test in funclist
testcode = lowercase(func2test) * "_test.jl"
include(testcode)
rname=Symbol("run_"*func2test)
eval(:(runme=$rname))
@testset "$func2test" begin
datfile = joinpath(tdir, "examples", uppercase(func2test) * ".dat")
if quiet[]
runme(datfile, devnull)
else
runme(datfile)
end
end # testset
end # for
| SLICOTMath | https://github.com/RalphAS/SLICOTMath.jl.git |
|
[
"MIT",
"BSD-3-Clause"
] | 0.1.0 | 6521428e41ae0924b30460ef1ffada3b07ab2bc1 | docs | 2570 | # SLICOTMath
[](https://github.com/RalphAS/SLICOTMath.jl/actions)
[](http://codecov.io/github/RalphAS/SLICOTMath.jl?branch=main)
# Introduction
This package provides Julia wrappers for some routines in the SLICOT library,
which contains Fortran implementations of control theory algorithms.
SLICOT is hosted at https://github.com//SLICOT/SLICOT-Reference.git
The group of mathematical routines (those starting with "M") are covered here,
except for a few which are awkward to call from Julia (there are preferable implementations
of those algorithms elsewhere in the Julia ecosystem).
For the most part the Julia API resembles that of LAPACK routines in the LinearAlgebra
standard library. Thus array dimension arguments are (almost always) suppressed and
workspace is usually allocated as needed within the wrappers. One difference is that
result arrays are only passed as arguments to be mutated, and are not among the explicitly
returned objects.
# Status: Caveat Emptor
This is work in progress. So far all of the wrappers and tests were mechanically generated
and edited to repair oversights.
For substantive documentation the user is referred to the HTML documents
in [the SLICOT repository](https://github.com//SLICOT/SLICOT-Reference.git)
Users will also need to refer to the method signatures. Argument names are lower case
versions of those in the wrapped routines.
## Tests
The test routines generally verify that the API is consistent. They were mechanically
translated from the SLICOT-Reference examples, so they include extra computations (beyond
merely invoking the wrappers). The output of most has been visually compared to the
analogous Fortran results, almost always agreeing (or differing in ways consistent with
floating-point and BLAS/LAPACK version variations). That comparison is *not* currently
part of the package test framework. The CI tests as such rarely check the accuracy of
algorithms, although residuals are occasionally reported.
Interfaces to routines which are not called by the reference example codes have been
quickly reviewed, but very few have been tested by the author.
# Related work
Many of the higher-level control-theoretic methods in SLICOT have been translated to
Julia in [packages written by Andreas Varga](https://github.com//AndreasVarga).
No endorsement or promotion of SLICOTMath.jl by the authors of SLICOT
is implied.
| SLICOTMath | https://github.com/RalphAS/SLICOTMath.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | code | 1896 | using BinDeps
isfile("deps.jl") && rm("deps.jl")
@BinDeps.setup
libtriangle = library_dependency("libtriangle", aliases = ["libtriangle.dylib"], runtime = true)
rootdir = BinDeps.depsdir(libtriangle)
srcdir = joinpath(rootdir, "src")
prefix = joinpath(rootdir, "usr")
libdir = joinpath(prefix, "lib")
headerdir = joinpath(prefix, "include")
if Sys.iswindows()
libfile = joinpath(libdir, "libtriangle.dll")
arch = "x86"
if Sys.WORD_SIZE == 64
arch = "x64"
end
@build_steps begin
FileRule(libfile, @build_steps begin
BinDeps.run(@build_steps begin
ChangeDirectory(srcdir)
`cmd /c compile.bat all $arch`
`cmd /c copy libtriangle.dll $libfile`
`cmd /c copy triangle.h $headerdir`
`cmd /c copy tricall.h $headerdir`
`cmd /c copy commondefine.h $headerdir`
`cmd /c compile.bat clean $arch`
end) end) end
provides(Binaries, URI(libfile), libtriangle)
else
libname = "libtriangle.so"
if Sys.isapple()
libname = "libtriangle.dylib"
end
libfile = joinpath(libdir, libname)
provides(BinDeps.BuildProcess, (@build_steps begin
FileRule(libfile, @build_steps begin
BinDeps.ChangeDirectory(srcdir)
`make clean`
`make`
`cp libtriangle.so $libfile`
`cp triangle.h $headerdir/`
`cp tricall.h $headerdir/`
`cp commondefine.h $headerdir/`
`make clean`
end)
end), libtriangle)
end
@BinDeps.install Dict(:libtriangle => :libtriangle)
| Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | code | 160 | push!(LOAD_PATH,"../src/")
using Documenter, Triangle
makedocs(
format = Documenter.HTML(),
sitename = "Triangle.jl",
pages = [
"Home" => "index.md"
]
)
| Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | code | 16407 | module Triangle
using Libdl
export basic_triangulation
export basic_triangulation_vertices
export constrained_triangulation
export constrained_triangulation_vertices
if !isfile(joinpath(dirname(@__FILE__), "..", "deps", "deps.jl"))
error("Triangle is not properly installed. Please run\nPkg.build(\"Triangle\")")
end
include("common.jl")
"""
basic_triangulation_vertices(vertices::Array{Float64,2})
Compute a Delaunay triangulation for a list of `vertices` in the form of `[x1 y1; x2 y2; ... ; xn yn]`
The function will return an array of array of 3-vertices lists (triangles with the correct vertices order) using the vertex coordinates in each triangle definition.
# Example
```jldoctest
julia> using Triangle
julia> points = Array{Float64,2}([0. 0.; 1. 0.; 0. 1.])
3×2 Array{Float64,2}:
0.0 0.0
1.0 0.0
0.0 1.0
julia> Triangle.basic_triangulation_vertices(points)
1-element Array{Array{Float64,2},1}:
[0.0 0.0; 1.0 0.0; 0.0 1.0]
```
"""
function basic_triangulation_vertices(vertices::Array{Float64,2})
basic_triangulation_vertices(vertices, Array{Int64,1}(collect(1:1:size(vertices)[1])))
end
"""
basic_triangulation(vertices::Array{Float64,2},vertices_map::Array{Int64,1})
Compute a Delaunay triangulation for a list of `vertices` in the form of `[x1 y1; x2 y2; ... ; xn yn]`
A list of indexes is provided in `vertices_map` so that each vertex can have a custom integer identifier.
The function will return an array of array of 3-vertices lists (triangles with the correct vertices order) using the vertex identifiers in each triangle definition.
# Example
```jldoctest
julia> using Triangle
julia> points = Array{Float64,2}([0. 0.; 1. 0.; 0. 1.])
3×2 Array{Float64,2}:
0.0 0.0
1.0 0.0
0.0 1.0
julia> points_map = [1, 2, 3]
3-element Array{Int64,1}:
1
2
3
julia> Triangle.basic_triangulation(points,points_map)
1-element Array{Array{Int64,1},1}:
[1, 2, 3]
```
"""
function basic_triangulation(vertices::Array{Float64,2}, vertices_map::Array{Int64,1})
Triangulate.basic_triangulation(vertices, vertices_map)
end
"""
basic_triangulation_vertices(vertices::Array{Float64,2},vertices_map::Array{Int64,1})
Compute a Delaunay triangulation for a list of `vertices` in the form of `[x1 y1; x2 y2; ... ; xn yn]`
A list of indexes is provided in `vertices_map` so that each vertex can have a custom integer identifier.
The function will return an array of array of 3-vertices lists (triangles with the correct vertices order) using the vertex coordinates in each triangle definition.
# Example
```jldoctest
julia> using Triangle
julia> points = Array{Float64,2}([0. 0.; 1. 0.; 0. 1.])
3×2 Array{Float64,2}:
0.0 0.0
1.0 0.0
0.0 1.0
julia> points_map = [1, 2, 3]
3-element Array{Int64,1}:
1
2
3
julia> Triangle.basic_triangulation_vertices(points,points_map)
1-element Array{Array{Float64,2},1}:
[0.0 0.0; 1.0 0.0; 0.0 1.0]
```
"""
function basic_triangulation_vertices(vertices::Array{Float64,2}, vertices_map::Array{Int64,1})
map_to_vertices( vertices, vertices_map, basic_triangulation(vertices, vertices_map) )
end
"""
constrained_triangulation(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2})
Compute a Constrained Delaunay triangulation for a list of `vertices` in the form of `[x1 y1; x2 y2; ... ; xn yn]` and a list of edges that will be kept.
A list of indexes is provided in `vertices_map` so that each vertex can have a custom integer identifier.
A list of edges (to be included in the final triangulation) is passed in `edges_list` in the form of `[ vertex-identifier-1 vertex-identifier-2; vertex-identifier-1 vertex-identifier-3; ... ; vertex-identifier-N vertex-identifier-M ]`
The function will return an array of array of 3-vertices lists (triangles with the correct vertices order) using the vertex identifiers in each triangle definition.
# Example
```jldoctest
julia> using Triangle
julia> points = [0. 0.; 0. 3.; 1. 3.; 1. 1.; 2. 1.; 2. 0.]
6×2 Array{Float64,2}:
0.0 0.0
0.0 3.0
1.0 3.0
1.0 1.0
2.0 1.0
2.0 0.0
julia> points_map = Array{Int64,1}(collect(1:1:size(points)[1]))
6-element Array{Int64,1}:
1
2
3
4
5
6
julia> edges_list = Array{Int64,2}([1 2; 2 3; 3 4; 4 5; 5 6; 6 1])
6×2 Array{Int64,2}:
1 2
2 3
3 4
4 5
5 6
6 1
julia> Triangle.constrained_triangulation(points,points_map,edges_list)
4-element Array{Array{Int64,1},1}:
[1, 4, 2]
[4, 1, 6]
[2, 4, 3]
[5, 4, 6]
```
"""
function constrained_triangulation(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2})
Triangulate.constrained_triangulation(vertices, vertices_map, edges_list, fill(true, size(edges_list)[1]) )
end
"""
constrained_triangulation_vertices(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2})
Compute a Constrained Delaunay triangulation for a list of `vertices` in the form of `[x1 y1; x2 y2; ... ; xn yn]` and a list of edges that will be kept.
A list of indexes is provided in `vertices_map` so that each vertex can have a custom integer identifier.
A list of edges (to be included in the final triangulation) is passed in `edges_list` in the form of `[ vertex-identifier-1 vertex-identifier-2; vertex-identifier-1 vertex-identifier-3; ... ; vertex-identifier-N vertex-identifier-M ]`
The function will return an array of array of 3-vertices lists (triangles with the correct vertices order) using the vertex coordinates in each triangle definition.
# Example
```jldoctest
julia> using Triangle
julia> points = [0. 0.; 0. 3.; 1. 3.; 1. 1.; 2. 1.; 2. 0.]
6×2 Array{Float64,2}:
0.0 0.0
0.0 3.0
1.0 3.0
1.0 1.0
2.0 1.0
2.0 0.0
julia> points_map = Array{Int64,1}(collect(1:1:size(points)[1]))
6-element Array{Int64,1}:
1
2
3
4
5
6
julia> edges_list = Array{Int64,2}([1 2; 2 3; 3 4; 4 5; 5 6; 6 1])
6×2 Array{Int64,2}:
1 2
2 3
3 4
4 5
5 6
6 1
julia> Triangle.constrained_triangulation_vertices(points,points_map,edges_list)
4-element Array{Array{Float64,2},1}:
[0.0 0.0; 1.0 1.0; 0.0 3.0]
[1.0 1.0; 0.0 0.0; 2.0 0.0]
[0.0 3.0; 1.0 1.0; 1.0 3.0]
[2.0 1.0; 1.0 1.0; 2.0 0.0]
```
"""
function constrained_triangulation_vertices(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2})
map_to_vertices( vertices, vertices_map, constrained_triangulation(vertices, vertices_map, edges_list, fill(true, size(edges_list)[1])) )
end
"""
constrained_triangulation(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2}, edges_boundary::Array{Bool,1})
Compute a Constrained Delaunay triangulation for a list of `vertices` in the form of `[x1 y1; x2 y2; ... ; xn yn]` and a list of edges that will be kept. Some of those edges can be marked as the boundary of the mesh.
A list of indexes is provided in `vertices_map` so that each vertex can have a custom integer identifier.
A list of edge (to be included in the final triangulation) is passed in `edges_list` in the form of `[ vertex-identifier-1 vertex-identifier-2; vertex-identifier-1 vertex-identifier-3; ... ; vertex-identifier-N vertex-identifier-M ]`
A list of boundary markers passed in `edges_boundary` in the form of booleans that tell the triangulator if the edge is on the boundary or not (the indexing is the same of `edges_list`).
The function will return an array of array of 3-vertices lists (triangles with the correct vertices order) using the vertex identifiers in each triangle definition.
# Example
```jldoctest
julia> using Triangle
julia> points = [0. 0.; 0. 3.; 1. 3.; 1. 1.; 2. 1.; 2. 0.]
6×2 Array{Float64,2}:
0.0 0.0
0.0 3.0
1.0 3.0
1.0 1.0
2.0 1.0
2.0 0.0
julia> points_map = Array{Int64,1}(collect(1:1:size(points)[1]))
6-element Array{Int64,1}:
1
2
3
4
5
6
julia> edges_list = Array{Int64,2}([1 2; 2 3; 3 4; 4 5; 5 6; 6 1])
6×2 Array{Int64,2}:
1 2
2 3
3 4
4 5
5 6
6 1
julia> edge_boundary = [false, false, true, true, false, false]
6-element Array{Bool,1}:
false
false
true
true
false
false
julia> Triangle.constrained_triangulation(points,points_map,edges_list,edge_boundary)
4-element Array{Array{Int64,1},1}:
[1, 4, 2]
[4, 1, 6]
[2, 4, 3]
[5, 4, 6]
```
"""
function constrained_triangulation(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2}, edges_boundary::Array{Bool,1})
Triangulate.constrained_triangulation(vertices, vertices_map, edges_list, edges_boundary)
end
"""
constrained_triangulation_vertices(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2}, edges_boundary::Array{Bool,1})
Compute a Constrained Delaunay triangulation for a list of `vertices` in the form of `[x1 y1; x2 y2; ... ; xn yn]` and a list of edges that will be kept. Some of those edges can be marked as the boundary of the mesh.
A list of indexes is provided in `vertices_map` so that each vertex can have a custom integer identifier.
A list of edge (to be included in the final triangulation) is passed in `edges_list` in the form of `[ vertex-identifier-1 vertex-identifier-2; vertex-identifier-1 vertex-identifier-3; ... ; vertex-identifier-N vertex-identifier-M ]`
A list of boundary markers passed in `edges_boundary` in the form of booleans that tell the triangulator if the edge is on the boundary or not (the indexing is the same of `edges_list`).
The function will return an array of array of 3-vertices lists (triangles with the correct vertices order) using the vertex coordinates in each triangle definition.
# Example
```jldoctest
julia> using Triangle
julia> points = [0. 0.; 0. 3.; 1. 3.; 1. 1.; 2. 1.; 2. 0.]
6×2 Array{Float64,2}:
0.0 0.0
0.0 3.0
1.0 3.0
1.0 1.0
2.0 1.0
2.0 0.0
julia> points_map = Array{Int64,1}(collect(1:1:size(points)[1]))
6-element Array{Int64,1}:
1
2
3
4
5
6
julia> edges_list = Array{Int64,2}([1 2; 2 3; 3 4; 4 5; 5 6; 6 1])
6×2 Array{Int64,2}:
1 2
2 3
3 4
4 5
5 6
6 1
julia> edge_boundary = [false, false, true, true, false, false]
6-element Array{Bool,1}:
false
false
true
true
false
false
julia> Triangle.constrained_triangulation_vertices(points,points_map,edges_list,edge_boundary)
4-element Array{Array{Float64,2},1}:
[0.0 0.0; 1.0 1.0; 0.0 3.0]
[1.0 1.0; 0.0 0.0; 2.0 0.0]
[0.0 3.0; 1.0 1.0; 1.0 3.0]
[2.0 1.0; 1.0 1.0; 2.0 0.0]
```
"""
function constrained_triangulation_vertices(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2}, edges_boundary::Array{Bool,1})
map_to_vertices( vertices, vertices_map, constrained_triangulation(vertices, vertices_map, edges_list, edges_boundary) )
end
"""
constrained_triangulation(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2}, edges_boundary::Array{Bool,1}, holes::Array{Float64,2})
Compute a Constrained Delaunay triangulation for a list of `vertices` in the form of `[x1 y1; x2 y2; ... ; xn yn]` and a list of edges that will be kept. Some of those edges can be marked as the boundary of the mesh.
A list of `holes` in the form of _[x1 y1; x2 y2; ... ; xn yn]_ can be passed to avoid triangulation in that part of the mesh.
A list of indexes is provided in `vertices_map` so that each vertex can have a custom integer identifier.
A list of edge (to be included in the final triangulation) is passed in `edges_list` in the form of `[ vertex-identifier-1 vertex-identifier-2; vertex-identifier-1 vertex-identifier-3; ... ; vertex-identifier-N vertex-identifier-M ]`
A list of boundary markers passed in `edges_boundary` in the form of booleans that tell the triangulator if the edge is on the boundary or not (the indexing is the same of `edges_list`).
The function will return an array of array of 3-vertices lists (triangles with the correct vertices order) using the vertex identifiers in each triangle definition.
# Example
```jldoctest
julia> using Triangle
julia> points = Array{Float64,2}([0. 0.; 4. 0.; 2. 3.; 8. 0.; 6. 3.; 4. 6.])
6×2 Array{Float64,2}:
0.0 0.0
4.0 0.0
2.0 3.0
8.0 0.0
6.0 3.0
4.0 6.0
julia> points_map = [1, 2, 4, 3, 5, 6]
6-element Array{Int64,1}:
1
2
4
3
5
6
julia> edges_list = Array{Int64,2}([1 2; 2 3; 3 1; 2 4; 4 5; 5 2; 3 5; 5 6; 6 3])
9×2 Array{Int64,2}:
1 2
2 3
3 1
2 4
4 5
5 2
3 5
5 6
6 3
julia> edge_boundary = [false,true,false,false,false,true,true,false,false]
9-element Array{Bool,1}:
false
true
false
false
false
true
true
false
false
julia> holes = [4. 2.]
1×2 Array{Float64,2}:
4.0 2.0
julia> Triangle.constrained_triangulation(points, points_map, edges_list, edge_boundary, holes)
3-element Array{Array{Int64,1},1}:
[1,2,3]
[5,6,3]
[4,5,2]
```
"""
function constrained_triangulation(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2}, edges_boundary::Array{Bool,1}, holes::Array{Float64,2})
Triangulate.constrained_triangulation(vertices, vertices_map, edges_list, edges_boundary, holes)
end
"""
constrained_triangulation_vertices(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2}, edges_boundary::Array{Bool,1}, holes::Array{Float64,2})
Compute a Constrained Delaunay triangulation for a list of `vertices` in the form of `[x1 y1; x2 y2; ... ; xn yn]` and a list of edges that will be kept. Some of those edges can be marked as the boundary of the mesh.
A list of `holes` in the form of _[x1 y1; x2 y2; ... ; xn yn]_ can be passed to avoid triangulation in that part of the mesh.
A list of indexes is provided in `vertices_map` so that each vertex can have a custom integer identifier.
A list of edge (to be included in the final triangulation) is passed in `edges_list` in the form of `[ vertex-identifier-1 vertex-identifier-2; vertex-identifier-1 vertex-identifier-3; ... ; vertex-identifier-N vertex-identifier-M ]`
A list of boundary markers passed in `edges_boundary` in the form of booleans that tell the triangulator if the edge is on the boundary or not (the indexing is the same of `edges_list`).
The function will return an array of array of 3-vertices lists (triangles with the correct vertices order) using the vertex coordinates in each triangle definition.
# Example
```jldoctest
julia> using Triangle
julia> points = Array{Float64,2}([0. 0.; 4. 0.; 2. 3.; 8. 0.; 6. 3.; 4. 6.])
6×2 Array{Float64,2}:
0.0 0.0
4.0 0.0
2.0 3.0
8.0 0.0
6.0 3.0
4.0 6.0
julia> points_map = [1, 2, 4, 3, 5, 6]
6-element Array{Int64,1}:
1
2
4
3
5
6
julia> edges_list = Array{Int64,2}([1 2; 2 3; 3 1; 2 4; 4 5; 5 2; 3 5; 5 6; 6 3])
9×2 Array{Int64,2}:
1 2
2 3
3 1
2 4
4 5
5 2
3 5
5 6
6 3
julia> edge_boundary = [false,true,false,false,false,true,true,false,false]
9-element Array{Bool,1}:
false
true
false
false
false
true
true
false
false
julia> holes = [4. 2.]
1×2 Array{Float64,2}:
4.0 2.0
julia> Triangle.constrained_triangulation_vertices(points, points_map, edges_list, edge_boundary, holes)
3-element Array{Array{Float64,2},1}:
[0.0 0.0; 4.0 0.0; 2.0 3.0]
[6.0 3.0; 4.0 6.0; 2.0 3.0]
[8.0 0.0; 6.0 3.0; 4.0 0.0]
```
"""
function constrained_triangulation_vertices(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2}, edges_boundary::Array{Bool,1}, holes::Array{Float64,2})
map_to_vertices( vertices, vertices_map, constrained_triangulation(vertices, vertices_map, edges_list, edges_boundary, holes) )
end
function map_to_vertices(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, triangle_list::Array{Array{Int64, 1},1})
vert_size = size(vertices)
map_positions = Array{Int64,1}(undef, length(vertices_map))
for i in 1:1:length(vertices_map)
map_positions[vertices_map[i]] = i
end
triangle_list_vertices = Array{Array{Float64,2},1}()
for i in 1:1:length(triangle_list)
triangle = Array{Float64}(undef, 3,2)
triangle[1] = vertices[map_positions[triangle_list[i][1]]]
triangle[4] = vertices[map_positions[triangle_list[i][1]]+vert_size[1]]
triangle[2] = vertices[map_positions[triangle_list[i][2]]]
triangle[5] = vertices[map_positions[triangle_list[i][2]]+vert_size[1]]
triangle[3] = vertices[map_positions[triangle_list[i][3]]]
triangle[6] = vertices[map_positions[triangle_list[i][3]]+vert_size[1]]
push!(triangle_list_vertices, triangle)
end
return triangle_list_vertices
end
end
| Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | code | 37 | include("Triangulate/triangulate.jl") | Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | code | 3186 | module NativeInterface
include("triangle_structure.jl")
include("options_structure.jl")
include("native_remapper.jl")
include("native_calls.jl")
export TriangulateOptions
export basic_triangulation
export constrained_triangulation
export constrained_triangulation_bounded
function basic_triangulation(vertices::Vector{Cdouble}, verticesMap::Vector{Cint}, options::TriangulateOptions = TriangulateOptions())
# Call C
return calculate_output(generate_basic_input(vertices, verticesMap), options)
end
function constrained_triangulation(vertices::Vector{Cdouble}, verticesMap::Vector{Cint}, edges::Vector{Cint}, options::TriangulateOptions = TriangulateOptions())
# Call C
return calculate_output(generate_basic_input(vertices, verticesMap, edges), options)
end
function constrained_triangulation_bounded(vertices::Vector{Cdouble}, verticesMap::Vector{Cint}, edges::Vector{Cint}, boundary_edges::Vector{Cint}, options::TriangulateOptions = TriangulateOptions())
# Call C
return calculate_output(generate_basic_input(vertices, verticesMap, edges, boundary_edges), options)
end
function constrained_triangulation_bounded(vertices::Vector{Cdouble}, verticesMap::Vector{Cint}, edges::Vector{Cint}, boundary_edges::Vector{Cint}, holes::Vector{Cdouble}, options::TriangulateOptions = TriangulateOptions())
# Call C
return calculate_output(generate_basic_input(vertices, verticesMap, edges, boundary_edges, holes), options)
end
function generate_basic_input(vertices::Vector{Cdouble}, verticesMap::Vector{Cint}, edges::Vector{Cint} = Vector{Cint}(), boundary_edges::Vector{Cint} = Vector{Cint}(), holes::Vector{Cdouble} = Vector{Cdouble}())
# Basic Tri
# println(vertices)
# println(verticesMap)
mapTri = trimap_to_native(verticesMap, edges)
inTri = TriangulateIO()
inTri.pointlist = pointer(vertices)
inTri.numberofpoints = length(mapTri.remappedVerticesMarkers)
inTri.pointmarkerlist = pointer(mapTri.remappedVerticesMarkers)
if length(edges) > 0
inTri.segmentlist = pointer(mapTri.remappedEdgesList)
inTri.numberofsegments = Int(length(mapTri.remappedEdgesList)/2)
end
if length(edges) > 0 && length(boundary_edges) > 0
inTri.segmentmarkerlist = pointer(boundary_edges)
end
if length(holes) > 0
inTri.holelist = pointer(holes)
inTri.numberofholes = Int(length(holes)/2)
end
return (inTri, mapTri)
end
function calculate_output(inputTriData::Tuple{TriangulateIO,TriangulateInputMapper}, options::TriangulateOptions)
inTri = inputTriData[1]
mapTri = inputTriData[2]
# Call C
tupleRes = ctriangulate(inTri, getTriangulateStringOptions(options))
# println( unsafe_wrap(Array, tupleRes[1].pointlist, tupleRes[1].numberofpoints * 2, false) )
# println( unsafe_wrap(Array, tupleRes[1].pointmarkerlist, tupleRes[1].numberofpoints, false) )
# println(tupleRes[1])
triangleList = unsafe_wrap(Array, tupleRes[1].trianglelist,
tupleRes[1].numberoftriangles * tupleRes[1].numberofcorners, own=true)
# Clean C
inTri.pointlist = C_NULL
inTri.pointmarkerlist = C_NULL
tupleRes[1].trianglelist = C_NULL
# println(triangleList)
return trimap_from_native(mapTri, triangleList)
end
end | Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | code | 432 | depsjl = joinpath(dirname(@__FILE__), "../..", "deps", "deps.jl")
include(depsjl)
function ctriangulate(inTri::TriangulateIO, options::String)
outTri = TriangulateIO()
voronoiTri = TriangulateIO()
ccall(
(:call_triangulate, libtriangle),
Nothing,
(Ptr{UInt8}, Ref{TriangulateIO}, Ref{TriangulateIO}, Ref{TriangulateIO}),
options, Ref(inTri), Ref(outTri), Ref(voronoiTri)
)
(outTri, voronoiTri)
end
| Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | code | 1232 | mutable struct TriangulateInputMapper
originalVerticesMarkers::Vector{Cint}
remappedVerticesMarkers::Vector{Cint}
originalEdgesList::Vector{Cint}
remappedEdgesList::Vector{Cint}
TriangulateInputMapper() = new(Vector{Cint}(), Vector{Cint}(), Vector{Cint}(), Vector{Cint}())
end
function trimap_to_native(verticesMap::Vector{Cint}, edges::Vector{Cint} = Vector{Cint}())
nativeMap = TriangulateInputMapper()
nativeMap.originalVerticesMarkers = verticesMap
nativeMap.remappedVerticesMarkers = collect(1:length(verticesMap))
dictVertices = Dict{Int64,Int64}()
for (idx,el) in enumerate(verticesMap)
dictVertices[el] = idx
end
if length(edges) > 0
nativeMap.originalEdgesList = edges
nativeMap.remappedEdgesList = Vector{Cint}()
for el in edges
push!(nativeMap.remappedEdgesList, dictVertices[el])
end
end
return nativeMap
end
function trimap_from_native(nativeMap::TriangulateInputMapper, trianglelist::Vector{Cint})
newtrianglelist = Vector{Cint}(undef, length(trianglelist))
for (idx,el) in enumerate(trianglelist)
newtrianglelist[idx] = nativeMap.originalVerticesMarkers[el]
end
return newtrianglelist
end | Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | code | 6821 | #=
/* Switches for the triangulator. */
-p Triangulates a Planar Straight Line Graph (.poly file).
-r Refines a previously generated mesh.
-q Quality mesh generation with no angles smaller than 20 degrees. An alternate minimum angle may be specified after the `q'.
-a Imposes a maximum triangle area constraint. A fixed area constraint (that applies to every triangle) may be specified after the `a', or varying area constraints may be read from a .poly file or .area file.
-u Imposes a user-defined constraint on triangle size.
-A Assigns a regional attribute to each triangle that identifies what segment-bounded region it belongs to.
-c Encloses the convex hull with segments.
-D Conforming Delaunay: use this switch if you want all triangles in the mesh to be Delaunay, and not just constrained Delaunay; or if you want to ensure that all Voronoi vertices lie within the triangulation.
-j Jettisons vertices that are not part of the final triangulation from the output .node file (including duplicate input vertices and vertices ``eaten'' by holes).
-e Outputs (to an .edge file) a list of edges of the triangulation.
-v Outputs the Voronoi diagram associated with the triangulation. Does not attempt to detect degeneracies, so some Voronoi vertices may be duplicated.
-n Outputs (to a .neigh file) a list of triangles neighboring each triangle.
-g Outputs the mesh to an Object File Format (.off) file, suitable for viewing with the Geometry Center's Geomview package.
-B Suppresses boundary markers in the output .node, .poly, and .edge output files.
-P Suppresses the output .poly file. Saves disk space, but you lose the ability to maintain constraining segments on later refinements of the mesh.
-N Suppresses the output .node file.
-E Suppresses the output .ele file.
-I Suppresses mesh iteration numbers.
-O Suppresses holes: ignores the holes in the .poly file.
-X Suppresses exact arithmetic.
-z Numbers all items starting from zero (rather than one). Note that this switch is normally overrided by the value used to number the first vertex of the input .node or .poly file. However, this switch is useful when calling Triangle from another program.
-o2 Generates second-order subparametric elements with six nodes each.
-Y Prohibits the insertion of Steiner points on the mesh boundary. If specified twice (-YY), it prohibits the insertion of Steiner points on any segment, including internal segments.
-S Specifies the maximum number of added Steiner points.
-i Uses the incremental algorithm for Delaunay triangulation, rather than the divide-and-conquer algorithm.
-F Uses Steven Fortune's sweepline algorithm for Delaunay triangulation, rather than the divide-and-conquer algorithm.
-l Uses only vertical cuts in the divide-and-conquer algorithm. By default, Triangle uses alternating vertical and horizontal cuts, which usually improve the speed except with vertex sets that are small or short and wide. This switch is primarily of theoretical interest.
-s Specifies that segments should be forced into the triangulation by recursively splitting them at their midpoints, rather than by generating a constrained Delaunay triangulation. Segment splitting is true to Ruppert's original algorithm, but can create needlessly small triangles. This switch is primarily of theoretical interest.
-C Check the consistency of the final mesh. Uses exact arithmetic for checking, even if the -X switch is used. Useful if you suspect Triangle is buggy.
-Q Quiet: Suppresses all explanation of what Triangle is doing, unless an error occurs.
-V Verbose: Gives detailed information about what Triangle is doing. Add more `V's for increasing amount of detail. `-V' gives information on algorithmic progress and detailed statistics.
-h Help: Displays complete instructions.
/* If the size of the object file is important to you, you may wish to */
/* generate a reduced version of triangle.o. The REDUCED symbol gets rid */
/* of all features that are primarily of research interest. Specifically, */
/* the -DREDUCED switch eliminates Triangle's -i, -F, -s, and -C switches. */
/* The CDT_ONLY symbol gets rid of all meshing algorithms above and beyond */
/* constrained Delaunay triangulation. Specifically, the -DCDT_ONLY switch */
/* eliminates Triangle's -r, -q, -a, -u, -D, -Y, -S, and -s switches. */
=#
mutable struct TriangulateOptions
pslg::Bool #p
regionattrib::Bool # A
convex::Bool # c
jettison::Bool # j
firstnumberiszero::Bool # z
edgesout::Bool # e
voronoi::Bool # v
neighbors::Bool # n
nobound::Bool # B
nopolywritten::Bool # P
nonodewritten::Bool # N
noelewritten::Bool # E
noiterationnum::Bool # I
noholes::Bool # O
noexactaritmetic::Bool # X
order::Bool # o
orderHow::Int64 # 1...2...3
dwyer::Bool # l
quiet::Bool # Q
verbose::Bool # V
TriangulateOptions() = new(false,
false, false, false, false, false, false, false,
# No_xyz_ selector(s)
true, true, false, false, true, false, false,
# order
false, 0,
false,
# Quiet Verbose
true, false)
end
function getTriangulateStringOptions(self::TriangulateOptions)
output_stri = ""
if self.pslg
output_stri = output_stri * "p"
end
if self.regionattrib
output_stri = output_stri * "A"
end
if self.convex
output_stri = output_stri * "c"
end
if self.jettison
output_stri = output_stri * "j"
end
if self.firstnumberiszero
output_stri = output_stri * "z"
end
if self.edgesout
output_stri = output_stri * "e"
end
if self.voronoi
output_stri = output_stri * "v"
end
if self.neighbors
output_stri = output_stri * "n"
end
if self.nobound
output_stri = output_stri * "B"
end
if self.nopolywritten
output_stri = output_stri * "P"
end
if self.nonodewritten
output_stri = output_stri * "N"
end
if self.noelewritten
output_stri = output_stri * "E"
end
if self.noiterationnum
output_stri = output_stri * "I"
end
if self.noholes
output_stri = output_stri * "O"
end
if self.noexactaritmetic
output_stri = output_stri * "X"
end
if self.order && self.orderHow > 0
output_stri = output_stri * "o" * string(self.orderHow)
end
if self.dwyer
output_stri = output_stri * "l"
end
if self.quiet
output_stri = output_stri * "Q"
end
if self.verbose
output_stri = output_stri * "V"
end
return output_stri
end | Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | code | 851 | # REAL = double = Cdouble
mutable struct TriangulateIO
pointlist::Ptr{Cdouble}
pointattributelist::Ptr{Cdouble}
pointmarkerlist::Ptr{Cint}
numberofpoints::Cint
numberofpointattributes::Cint
trianglelist::Ptr{Cint}
triangleattributelist::Ptr{Cdouble}
trianglearealist::Ptr{Cdouble}
neighborlist::Ptr{Cint}
numberoftriangles::Cint
numberofcorners::Cint
numberoftriangleattributes::Cint
segmentlist::Ptr{Cint}
segmentmarkerlist::Ptr{Cint}
numberofsegments::Cint
holelist::Ptr{Cdouble}
numberofholes::Cint
regionlist::Ptr{Cdouble}
numberofregions::Cint
edgelist::Ptr{Cint}
edgemarkerlist::Ptr{Cint}
normlist::Ptr{Cdouble}
numberofedges::Cint
TriangulateIO() = new(C_NULL, C_NULL, C_NULL, 0, 0, C_NULL, C_NULL, C_NULL, C_NULL, 0, 0, 0, C_NULL, C_NULL, 0, C_NULL, 0, C_NULL, 0, C_NULL, C_NULL, C_NULL, 0)
end | Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | code | 1332 | include("../NativeInterface/native.jl")
function call_basic_triangulation(flat_vertices::Vector{Cdouble}, flat_vertices_map::Vector{Cint})
return NativeInterface.basic_triangulation(flat_vertices, flat_vertices_map)
end
function call_constrained_triangulation(flat_vertices::Vector{Cdouble}, flat_vertices_map::Vector{Cint}, flat_vertices_edge::Vector{Cint})
return NativeInterface.constrained_triangulation(flat_vertices, flat_vertices_map, flat_vertices_edge)
end
function call_constrained_triangulation_bounded(flat_vertices::Vector{Cdouble}, flat_vertices_map::Vector{Cint}, flat_vertices_edge::Vector{Cint}, flat_boundary_edges::Vector{Cint})
options = NativeInterface.TriangulateOptions()
options.pslg = true
return NativeInterface.constrained_triangulation_bounded(flat_vertices, flat_vertices_map, flat_vertices_edge, flat_boundary_edges, options)
end
function call_constrained_triangulation_bounded(flat_vertices::Vector{Cdouble}, flat_vertices_map::Vector{Cint}, flat_vertices_edge::Vector{Cint}, flat_boundary_edges::Vector{Cint}, flat_holes::Vector{Cdouble})
options = NativeInterface.TriangulateOptions()
options.pslg = true
return NativeInterface.constrained_triangulation_bounded(flat_vertices, flat_vertices_map, flat_vertices_edge, flat_boundary_edges, flat_holes, options)
end | Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | code | 2269 | module Triangulate
include("call_native_iface.jl")
include("utils_methods.jl")
export basic_triangulation
export constrained_triangulation
function basic_triangulation(vertices::Array{Float64,2}, vertices_map::Array{Int64,1})
flat_triangle_list = call_basic_triangulation(flat_vertices(vertices, vertices_map), Vector{Cint}(vertices_map))
return triangle_list_from_marker(flat_triangle_list)
end
function constrained_triangulation(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2})
return constrained_triangulation(vertices, vertices_map, edges_list, Array{Bool,1}())
end
function constrained_triangulation(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2}, edges_boundary::Array{Bool,1})
return constrained_triangulation(vertices, vertices_map, edges_list, edges_boundary, Array{Float64,2}(undef, 0,0))
end
function constrained_triangulation(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2}, edges_boundary::Array{Bool,1}, holes::Array{Float64,2})
local flatted_vertices = flat_vertices(vertices, vertices_map)
local vector_map = Vector{Cint}(vertices_map)
local flatted_edges = flat_edges(edges_list)
local flat_triangle_list::Vector{Cdouble}
if length(edges_boundary) != size(edges_list)[1]
flat_triangle_list = call_constrained_triangulation(
flatted_vertices,
vector_map,
flatted_edges
)
else
boolEdges = Vector{Cint}(map(x -> x ? 1 : 0, edges_boundary))
if size(holes)[1] == 0
flat_triangle_list = call_constrained_triangulation_bounded(
flatted_vertices,
vector_map,
flatted_edges,
boolEdges
)
else
flat_triangle_list = call_constrained_triangulation_bounded(
flatted_vertices,
vector_map,
flatted_edges,
boolEdges,
flat_vertices(holes, collect(1:size(holes)[1]))
)
end
end
return triangle_list_from_marker(flat_triangle_list)
end
end | Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | code | 1036 | ## Utils
function triangle_list_from_marker(flat_triangle_list)
triangle_list = Array{Array{Int64,1},1}()
for i in 1:3:length(flat_triangle_list)
push!(triangle_list, flat_triangle_list[i:i+2])
end
return triangle_list
end
function flat_vertices(vertices::Array{Float64,2}, vertices_map::Array{Int64,1})
vert_size = size(vertices)
flat_vertices_vector = Vector{Cdouble}(undef, vert_size[1]*vert_size[2])
# for vert_id in vertices_map
for vert_id=1:vert_size[1]
flat_vertices_vector[(vert_id*2)-1]=vertices[vert_id]
flat_vertices_vector[(vert_id*2)]=vertices[vert_id+vert_size[1]]
end
return flat_vertices_vector
end
function flat_edges(edges::Array{Int64,2})
edge_size = size(edges)
flat_edges_vector = Vector{Cint}(undef, edge_size[1]*edge_size[2])
for edge_id=1:edge_size[1]
flat_edges_vector[(edge_id*2)-1]=edges[edge_id]
flat_edges_vector[(edge_id*2)]=edges[edge_id+edge_size[1]]
end
return flat_edges_vector
end | Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | code | 135 | module TestTriangle
using Test
using Triangle
include("test_Triangle_NativeInterface_trioptions.jl")
include("test_Triangle.jl")
end | Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | code | 5084 | @testset "Triangle.jl Interface" begin
@testset "Basic Triangulation" begin
@testset "basic_triangulation_vertices" begin
points = Array{Float64,2}([0. 0.; 1. 0.; 0. 1.])
@test Triangle.basic_triangulation_vertices(points)[1] == points
end
@testset "basic_triangulation with point map" begin
points = Array{Float64,2}([0. 0.; 1. 0.; 0. 1.])
points_map = [1, 2, 3]
@test Triangle.basic_triangulation(points,points_map)[1] == points_map
end
@testset "basic_triangulation_vertices with point map" begin
points = Array{Float64,2}([0. 0.; 1. 0.; 0. 1.])
points_map = [1, 2, 3]
@test Triangle.basic_triangulation_vertices(points,points_map)[1] == points
end
# Triforce
@testset "basic_triangulation with unordered point map" begin
points = Array{Float64,2}([0. 0.; 4. 0.; 2. 3.; 8. 0.; 6. 3.; 4. 6.])
points_map = [1, 2, 4, 3, 5, 6]
result_tri = [[1, 2, 4],[4, 2, 5],[5, 6, 4],[3, 5, 2]]
@test Triangle.basic_triangulation(points,points_map) == result_tri
end
# Tetris L (no boundary)
@testset "basic_triangulation on L tetris piece" begin
points = [0. 0.; 0. 3.; 1. 3.; 1. 1.; 2. 1.; 2. 0.]
points_map = Array{Int64,1}(collect(1:1:size(points)[1]))
triangles = Triangle.basic_triangulation(points,points_map)
@test length(triangles) == 5
end
@testset "basic_triangulation_vertices with point map on L tetris piece" begin
points = [0. 0.; 0. 3.; 1. 3.; 1. 1.; 2. 1.; 2. 0.]
points_map = Array{Int64,1}(collect(1:1:size(points)[1]))
triangles = Triangle.basic_triangulation_vertices(points,points_map)
@test length(triangles) == 5
end
# Tetris L (all boundary)
@testset "constrained_triangulation" begin
points = [0. 0.; 0. 3.; 1. 3.; 1. 1.; 2. 1.; 2. 0.]
points_map = Array{Int64,1}(collect(1:1:size(points)[1]))
edges_list = Array{Int64,2}([1 2; 2 3; 3 4; 4 5; 5 6; 6 1])
triangles = Triangle.constrained_triangulation(points,points_map,edges_list)
@test length(triangles) == 4
end
@testset "constrained_triangulation_vertices" begin
points = [0. 0.; 0. 3.; 1. 3.; 1. 1.; 2. 1.; 2. 0.]
points_map = Array{Int64,1}(collect(1:1:size(points)[1]))
edges_list = Array{Int64,2}([1 2; 2 3; 3 4; 4 5; 5 6; 6 1])
triangles = Triangle.constrained_triangulation_vertices(points,points_map,edges_list)
@test length(triangles) == 4
end
# Tetris L (custom boundary)
@testset "constrained_triangulation with boundary" begin
points = [0. 0.; 0. 3.; 1. 3.; 1. 1.; 2. 1.; 2. 0.]
points_map = Array{Int64,1}(collect(1:1:size(points)[1]))
edges_list = Array{Int64,2}([1 2; 2 3; 3 4; 4 5; 5 6; 6 1])
edge_boundary = [false, false, true, true, false, false]
triangles = Triangle.constrained_triangulation(points,points_map,edges_list,edge_boundary)
@test length(triangles) == 4
end
@testset "constrained_triangulation_vertices with boundary" begin
points = [0. 0.; 0. 3.; 1. 3.; 1. 1.; 2. 1.; 2. 0.]
points_map = Array{Int64,1}(collect(1:1:size(points)[1]))
edges_list = Array{Int64,2}([1 2; 2 3; 3 4; 4 5; 5 6; 6 1])
edge_boundary = [false, false, true, true, false, false]
triangles = Triangle.constrained_triangulation_vertices(points,points_map,edges_list,edge_boundary)
@test length(triangles) == 4
end
# Triforce (without center triangle)
@testset "constrained_triangulation with boundary and holes" begin
points = [0. 0.; 4. 0.; 2. 3.; 8. 0.; 6. 3.; 4. 6.]
points_map = Array{Int64,1}(collect(1:1:size(points)[1]))
edges_list = Array{Int64,2}([1 2; 2 3; 3 1; 2 4; 4 5; 5 2; 3 5; 5 6; 6 3])
edge_boundary = [false,true,false,false,false,true,true,false,false]
holes_list = [4. 2.]
triangles = Triangle.constrained_triangulation(points,points_map,edges_list,edge_boundary,holes_list)
@test length(triangles) == 3
end
@testset "constrained_triangulation_vertices with boundary and holes" begin
points = [0. 0.; 4. 0.; 2. 3.; 8. 0.; 6. 3.; 4. 6.]
points_map = Array{Int64,1}(collect(1:1:size(points)[1]))
edges_list = Array{Int64,2}([1 2; 2 3; 3 1; 2 4; 4 5; 5 2; 3 5; 5 6; 6 3])
edge_boundary = [false,true,false,false,false,true,true,false,false]
holes_list = [4. 2.]
triangles = Triangle.constrained_triangulation_vertices(points,points_map,edges_list,edge_boundary,holes_list)
@test length(triangles) == 3
end
end
end
| Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | code | 1451 | include("../src/NativeInterface/options_structure.jl")
@testset "Triangle.NativeInterface.TriangulateOptions" begin
@testset "getTriangulateStringOptions()" begin
@testset "Default" begin
opt = TriangulateOptions()
@test getTriangulateStringOptions(opt) == "BPIQ"
end
@testset "All disable" begin
opt = TriangulateOptions()
opt.nobound = false
opt.nopolywritten = false
opt.noiterationnum = false
opt.quiet = false
@test getTriangulateStringOptions(opt) == ""
end
@testset "All enable" begin
opt = TriangulateOptions()
opt.pslg = true
opt.regionattrib = true
opt.convex = true
opt.jettison = true
opt.firstnumberiszero = true
opt.edgesout = true
opt.voronoi = true
opt.neighbors = true
opt.nobound = true
opt.nopolywritten = true
opt.nonodewritten = true
opt.noelewritten = true
opt.noiterationnum = true
opt.noholes = true
opt.noexactaritmetic = true
opt.order = true
opt.orderHow = 1
opt.dwyer = true
opt.quiet = true
opt.verbose = true
@test getTriangulateStringOptions(opt) == "pAcjzevnBPNEIOXo1lQV"
end
end
end
| Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | docs | 1994 | # TRIANGLE.jl
[](https://travis-ci.org/cvdlab/Triangle.jl)
[](https://ci.appveyor.com/project/furio/triangle-jl/branch/master)
[](https://coveralls.io/github/cvdlab/Triangle.jl)
[](https://cvdlab.github.io/Triangle.jl/)
[](http://dx.doi.org/10.1007/BFb0014497)
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fcvdlab%2FTriangle.jl?ref=badge_shield)
A Julia interface to Jonathan Richard Shewchuk [Triangle](https://www.cs.cmu.edu/~quake/triangle.html).
### Library notes
At the moment the library will use only CDT, planning to expand later.
### Licensing note
Note that while this binding-library is under a permissive license ([MIT](LICENSE)), the original [Triangle](https://www.cs.cmu.edu/~quake/triangle.html) library isn't:
> Please note that although Triangle is freely available, it is copyrighted by the author and may not be sold or included in commercial products without a license.
So be wary of any possible conflict between your project license and [Triangle](https://www.cs.cmu.edu/~quake/triangle.html)'s
## Installation
```julia
using Pkg
add("Triangle")
# Pkg.add("Triangle") on julia prior to v0.7
```
### Windows
The build proces uses VC++ binary (2013 version) to build so be sure you have it before running the build part.
## API
Include the module (`using Triangle`).
You can use Julia `?Triangle.methodname` for inline documentation. Documentation can be read on https://cvdlab.github.io/Triangle.jl/ .
| Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.3.2 | ea6029621372cad54dcb43095f68e98f889b0546 | docs | 1094 | # Triangle.jl Documentation
A Julia interface to Jonathan Richard Shewchuk [Triangle](https://www.cs.cmu.edu/~quake/triangle.html).
The library builds the C version and then expose methods to calculate CDTs.
## Functions
```@docs
basic_triangulation_vertices(vertices::Array{Float64,2})
```
```@docs
basic_triangulation(vertices::Array{Float64,2},vertices_map::Array{Int64,1})
```
```@docs
basic_triangulation_vertices(vertices::Array{Float64,2},vertices_map::Array{Int64,1})
```
```@docs
constrained_triangulation(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2})
```
```@docs
constrained_triangulation_vertices(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2})
```
```@docs
constrained_triangulation(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2}, edges_boundary::Array{Bool,1})
```
```@docs
constrained_triangulation_vertices(vertices::Array{Float64,2}, vertices_map::Array{Int64,1}, edges_list::Array{Int64,2}, edges_boundary::Array{Bool,1})
```
## Index
```@index
``` | Triangle | https://github.com/cvdlab/Triangle.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 320 | using Documenter, IRTools
makedocs(
modules=[IRTools],
sitename="IRTools",
pages = [
"Home" => "index.md",
"Dynamo" => "dynamo.md",
"Reference" => "reference.md"],
format = Documenter.HTML(prettyurls = haskey(ENV, "CI")))
deploydocs(
repo = "github.com/MikeInnes/IRTools.jl.git",
)
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 791 | # Implementation of the amb operator using shift/reset
# http://community.schemewiki.org/?amb
include("continuations.jl");
struct Backtrack end
function require(x)
x || throw(Backtrack())
return
end
unwrap(e) = e
unwrap(e::CapturedException) = e.ex
function amb(iter)
shift() do k
for x in iter
try
return k(x)
catch e
unwrap(e) isa Backtrack || rethrow()
end
end
throw(Backtrack())
end
end
function ambrun(f)
try
@reset f()
catch e
e isa Backtrack || rethrow()
error("No possible combination found.")
end
end
ambrun() do
x = amb([1, 2, 3])
y = amb([1, 2, 3])
require(x^2 + y == 7)
(x, y)
end
ambrun() do
N = 20
i = amb(1:N)
j = amb(i:N)
k = amb(j:N)
require(i*i + j*j == k*k)
(i, j, k)
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 3015 | # An implementation of delimited continuations (the shift/reset operators) in
# Julia. Works by transforming all Julia code to continuation passing style.
# The `shift` operator then just has to return the continuation.
# https://en.wikipedia.org/wiki/Delimited_continuation
# https://en.wikipedia.org/wiki/Continuation-passing_style
using IRTools.All
struct Func
f # Avoid over-specialising on the continuation object.
end
(f::Func)(args...) = f.f(args...)
function captures(ir, vs)
us = Set()
for v in vs
isexpr(ir[v].expr) || continue
foreach(x -> x isa Variable && push!(us, x), ir[v].expr.args)
end
return setdiff(us, vs)
end
rename(env, x) = x
rename(env, x::Variable) = env[x]
rename(env, x::Expr) = Expr(x.head, rename.((env,), x.args)...)
rename(env, x::Statement) = stmt(x, expr = rename(env, x.expr))
excluded = [GlobalRef(Base, :getindex)]
function continuation!(bl, ir, env, vs, ret)
rename(x) = Main.rename(env, x)
local v, st
while true
isempty(vs) && return return!(bl, rename(Expr(:call, ret, returnvalue(block(ir, 1)))))
v = popfirst!(vs)
st = ir[v]
isexpr(st.expr, :call) && !(st.expr.args[1] ∈ excluded) && break
isexpr(st.expr, :lambda) &&
(st = stmt(st, expr = Expr(:lambda, cpslambda(st.expr.args[1]), st.expr.args[2:end]...)))
env[v] = push!(bl, rename(st))
end
cs = [ret, setdiff(captures(ir, vs), [v])...]
if isempty(vs)
next = rename(ret)
else
next = push!(bl, Expr(:lambda, continuation(ir, vs, cs, v, ret), rename.(cs)...))
next = xcall(Main, :Func, next)
end
ret = push!(bl, stmt(st, expr = xcall(Main, :cps, next, rename(st.expr).args...)))
return!(bl, ret)
end
function continuation(ir, vs, cs, in, ret)
bl = empty(ir)
env = Dict()
self = argument!(bl)
env[in] = argument!(bl)
for (i, c) in enumerate(cs)
env[c] = pushfirst!(bl, xcall(:getindex, self, i))
end
continuation!(bl, ir, env, vs, ret)
end
cpslambda(ir) = cpstransform(ir, true)
function cpstransform(ir, lambda = false)
lambda || (ir = functional(ir))
k = argument!(ir, at = lambda ? 2 : 1)
bl = empty(ir)
env = Dict()
for arg in arguments(ir)
env[arg] = argument!(bl)
end
continuation!(bl, ir, env, keys(ir), k)
end
cps(k, f::Core.IntrinsicFunction, args...) = k(f(args...))
cps(k, f::IRTools.Lambda{<:Tuple{typeof(cps),Vararg{Any}}}, args...) = f(k, args...)
cps(k, ::typeof(cond), c, t, f) = c ? cps(k, t) : cps(k, f)
cps(k, ::typeof(cps), args...) = k(cps(args...))
# Speed up compilation
for f in [Broadcast.broadcasted, Broadcast.materialize]
@eval cps(k, ::typeof($f), args...) = k($f(args...))
end
@dynamo function cps(k, args...)
ir = IR(args...)
ir == nothing && return :(args[1](args[2](args[3:end]...)))
cpstransform(IR(args...))
end
# shift/reset
reset(f) = cps(identity, f)
shift(f) = error("`shift` must be called inside `reset`")
cps(k, ::typeof(shift), f) = f(k)
macro reset(ex)
:(reset(() -> $(esc(ex))))
end
k = @reset begin
shift(k -> k)^2
end
k(4) == 16
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 3124 | # A simple forward-mode AD. Simplified so that many things don't work (e.g.
# control flow), but shows the basic ideas.
using IRTools.All
using IRTools: Pipe
using Base: tail
ntail(x, n) = n <= 0 ? x : xcall(:tail, ntail(x, n-1))
zerolike(x::Number) = zero(x)
zerolike(x::Tuple) = zerolike.(x)
zerolike(x::T) where T =
NamedTuple{fieldnames(T)}(map(f -> zerolike(getfield(x, f)), fieldnames(T)))
zerolike(x::Union{Module,Type}) = nothing
function instrument!(pr, v, st)
ex = st.expr
if isexpr(ex, :new)
st = stmt(st, expr = xcall(Main, :__new__, ex.args...))
pr[v] = st
end
return st
end
function dual(ir)
pr = Pipe(ir)
Δs = Dict()
partial(x::Variable) = Δs[x]
partial(v, x::Variable) = Δs[x]
partial(v, x) = insert!(pr, v, xcall(Main, :zerolike, x))
dx = argument!(pr, at = 1)
for (i, x) in enumerate(arguments(ir))
if i == length(arguments(ir)) && ir.meta.method.isva
Δs[x] = push!(pr, ntail(dx, i-1))
else
Δs[x] = push!(pr, xcall(:getindex, dx, i))
end
end
for (v, st) in pr
st = instrument!(pr, v, st)
if isexpr(st.expr, :call)
dargs = insert!(pr, v, xcall(:tuple, partial.((v,), st.expr.args)...))
result = insert!(pr, v, stmt(st, expr = xcall(Main, :diff, dargs, st.expr.args...)))
pr[v] = xcall(:getindex, result, 1)
Δs[v] = push!(pr, xcall(:getindex, result, 2))
elseif !isexpr(st.expr)
Δs[v] = push!(pr, xcall(Main, :zerolike, v))
else
error("Unsupported $(st.expr.head) expression")
end
end
ret = returnvalue(block(ir, 1))
return!(pr, xcall(:tuple, ret, partial(ret)))
return finish(pr)
end
@dynamo function diff(_, x...)
ir = IR(x...)
ir == nothing && return :(error("non-differentiable function $(args[2])"))
@assert length(blocks(ir)) == 1 "Control flow not yet supported"
return dual(ir)
end
@generated function __new__(T, args...)
quote
Base.@_inline_meta
$(Expr(:new, :T, [:(args[$i]) for i = 1:length(args)]...))
end
end
# Julia internal definitions
diff(_, ::typeof(zerolike), x) = zerolike(x), zerolike(x)
diff(_, ::typeof(one), x) = one(x), zerolike(x)
diff(_, ::typeof(println), x...) = println(x...), nothing
diff(_, ::typeof(typeof), x) = typeof(x), nothing
diff(_, ::typeof(Core.apply_type), args...) = Core.apply_type(args...), nothing
diff(ṫ, ::typeof(tuple), t...) = t, tail(ṫ)
diff((_, ṫ, _), ::typeof(getfield), t, i) = getfield(t, i), getfield(ṫ, i)
diff((_, ṫ, _), ::typeof(getindex), t, i) = getindex(t, i), getindex(ṫ, i)
diff(ṡ, ::typeof(__new__), T, s...) = __new__(T, s...), NamedTuple{fieldnames(T)}(tail(tail(ṡ)))
# Mathematical definitions
diff((_, ȧ, ḃ), ::typeof(+), a, b) = a + b, ȧ + ḃ
diff((_, ȧ, ḃ), ::typeof(-), a, b) = a - b, ȧ - ḃ
diff((_, ȧ, ḃ), ::typeof(*), a, b) = a*b, ȧ*b+ḃ*a
diff((_, ȧ), ::typeof(-), a) = -a, -ȧ
diff((_, ẋ), ::typeof(sin), x) = sin(x), ẋ*cos(x)
diff((_, ẋ), ::typeof(cos), x) = cos(x), -ẋ*sin(x)
# Test cases
D(f, x) = diff((zerolike(f), one(x)), f, x)[2]
D(x -> sin(cos(x)), 0.5) # -cos(cos(x))sin(x)
D(x -> D(cos, x), 0.5) # -cos(x)
D(x -> x*D(y -> x*y, 1), 4) # 8
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 446 | # A simple dynamo that logs all function calls being made by Julia.
using IRTools: @dynamo, IR, xcall, arguments, insertafter!, recurse!
function hook(f, args...)
print("Called ", f, "(")
join(stdout, args, ", ")
println(")")
end
@dynamo function logcalls(m...)
ir = IR(m...)
ir == nothing && return
recurse!(ir)
pushfirst!(ir, xcall(Main, :hook, arguments(ir)...))
return ir
end
# @code_ir logcalls 2+3.0
logcalls(+, 2, 3.0)
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 2296 | # A simple reverse-mode AD.
# Lots of simplifications have been made (in particular, there is no support for
# control flow). But this illustrates most of the principles behind Zygote.
# https://fluxml.ai/Zygote.jl/dev/internals/
using IRTools
using IRTools: @dynamo, IR, Pipe, finish, substitute, return!, block, blocks,
returnvalue, arguments, isexpr, xcall, self, stmt
struct Pullback{S,T}
data::T
end
Pullback{S}(data) where S = Pullback{S,typeof(data)}(data)
function primal(ir, T = Any)
pr = Pipe(ir)
calls = []
ret = []
for (v, st) in pr
ex = st.expr
if isexpr(ex, :call)
t = insert!(pr, v, stmt(xcall(Main, :forward, ex.args...), line = st.line))
pr[v] = xcall(:getindex, t, 1)
J = push!(pr, xcall(:getindex, t, 2))
push!(calls, v)
push!(ret, J)
end
end
pb = Expr(:call, Pullback{T}, xcall(:tuple, ret...))
return!(pr, xcall(:tuple, returnvalue(block(ir, 1)), pb))
return finish(pr), calls
end
_sum() = 0
_sum(x) = x
_sum(x...) = xcall(:+, x...)
function adjoint(pr)
ir = empty(pr)
grads = Dict()
grad(x) = _sum(get(grads, x, [])...)
grad(x, x̄) = push!(get!(grads, x, []), x̄)
grad(returnvalue(block(pr, 1)), IRTools.argument!(ir))
data = push!(ir, xcall(:getfield, self, QuoteNode(:data)))
_, pbs = primal(pr)
pbs = Dict(pbs[i] => push!(ir, xcall(:getindex, data, i)) for i = 1:length(pbs))
for v in reverse(keys(pr))
ex = pr[v].expr
isexpr(ex, :call) || continue
Δs = push!(ir, Expr(:call, pbs[v], grad(v)))
for (i, x) in enumerate(ex.args)
grad(x, push!(ir, xcall(:getindex, Δs, i)))
end
end
return!(ir, xcall(:tuple, [grad(x) for x in arguments(pr)]...))
end
@dynamo function forward(m...)
ir = IR(m...)
ir == nothing && return :(error("Non-differentiable function ", repr(args[1])))
length(blocks(ir)) == 1 || error("control flow is not supported")
return primal(ir, Tuple{m...})[1]
end
@dynamo function (pb::Pullback{S})(Δ) where S
return adjoint(IR(S.parameters...))
end
forward(::typeof(sin), x) = sin(x), ȳ -> (nothing, ȳ*cos(x))
forward(::typeof(cos), x) = cos(x), ȳ -> (nothing, -ȳ*sin(x))
gradient(f, x...) = Base.tail(forward(f, x...)[2](1))
foo(x) = sin(cos(x))
# ir = @code_ir foo(1.0)
# primal(ir)[1]
# adjoint(ir)
gradient(foo, 1.0)
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 499 | using IRTools: @dynamo, argument!, IR
# Implementation of `invoke(f, argtypes::Type, args...`, where `args` don't have
# to conform to `argtypes`. i.e., it allows you to call `f` on `args`, but using the
# method for `argtypes`.
# See https://julialang.slack.com/archives/CJ357CY2Y/p1579598240011500.
@dynamo function sneakyinvoke(f, ::Type{T}, args...) where T<:Tuple
ir = IR(f, T.parameters...)
argument!(ir, at = 2)
return ir
end
f(x::Float64) = x^2
sneakyinvoke(f, Tuple{Float64}, 2)
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 1869 | module IRTools
export @code_ir
module Inner
using MacroTools
using MacroTools: @q, prewalk, postwalk
import ..IRTools
export @code_ir
@nospecialize
include("reflection/reflection.jl")
include("utils.jl")
include("ir/ir.jl")
include("ir/utils.jl")
include("ir/wrap.jl")
include("ir/print.jl")
include("ir/parse.jl")
include("reflection/utils.jl")
include("reflection/dynamo.jl")
include("passes/passes.jl")
include("passes/inline.jl")
include("passes/cps.jl")
include("passes/relooper.jl")
include("passes/stackifier.jl")
include("passes/registers.jl")
include("interpret.jl")
include("eval.jl")
end
let exports = :[
# IR
IRTools, IR, Block, BasicBlock, Variable, Statement, Branch, Pipe, CFG, Slot, branch, var, stmt, arguments, argtypes,
branches, undef, unreachable, isreturn, isconditional, block!, deleteblock!, branch!, argument!, return!,
canbranch, returnvalue, returntype, emptyargs!, deletearg!, block, blocks, successors, predecessors,
xcall, exprtype, exprline, isexpr, insertafter!, explicitbranch!, prewalk, postwalk,
prewalk!, postwalk!, finish, substitute!, substitute,
# Passes/Analysis
definitions, usages, dominators, domtree, domorder, domorder!, renumber,
merge_returns!, expand!, prune!, ssa!, inlineable!, log!, pis!, func, evalir,
Simple, Loop, Multiple, reloop, stackify, functional, cond, WorkQueue,
Graph, liveness, interference, colouring, inline,
# Reflection, Dynamo
Meta, Lambda, meta, dynamo, transform, refresh, recurse!, self,
varargs!, slots!,
].args
append!(exports, Symbol.(["@code_ir", "@dynamo", "@meta"]))
for x in exports
@eval const $x = Inner.$x
end
@eval module All
$([:(import ..IRTools: $x) for x in exports]...)
export $(exports...)
end
end
end # module
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 1534 | using Base: invokelatest
dummy() = return
const dummy_m = which(dummy, Tuple{})
function build_codeinfo(ir::IR)
ir = copy(ir)
ci = Base.uncompressed_ir(dummy_m)
ci.inlineable = true
for arg in arguments(ir)
@static if VERSION >= v"1.10.0-DEV.870"
isnothing(ci.slottypes) && (ci.slottypes = Any[])
push!(ci.slottypes, Type)
end
push!(ci.slotnames, Symbol(""))
push!(ci.slotflags, 0)
end
if isdefined(Base, :__has_internal_change) && Base.__has_internal_change(v"1.12-alpha", :codeinfonargs)
ci.nargs = length(arguments(ir)) + 1
ci.isva = false
end
argument!(ir, at = 1)
update!(ci, ir)
end
# JuliaLang/julia#48611: world age is exposed to generated functions.
if VERSION >= v"1.10.0-DEV.873"
function func(m::Module, ir::IR)
generator = @eval m begin
function $(gensym())(world::UInt, source, self,
$([Symbol(:arg, i) for i = 1:length(arguments(ir))]...))
return $build_codeinfo($ir)
end
end
@eval m begin
function $(gensym())($([Symbol(:arg, i) for i = 1:length(arguments(ir))]...))
$(Expr(:meta, :generated, generator))
$(Expr(:meta, :generated_only))
end
end
end
else
function func(m::Module, ir::IR)
@eval m (@generated function $(gensym())($([Symbol(:arg, i) for i = 1:length(arguments(ir))]...))
return $build_codeinfo($ir)
end)
end
end
func(ir::IR) = func(Main, ir)
evalir(m::Module, ir::IR, args...) = invokelatest(func(m, ir), args...)
evalir(ir::IR, args...) = evalir(Main, ir, args...)
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 852 | # Unique Work Queue
struct WorkQueue{T}
items::Vector{T}
end
WorkQueue{T}() where T = WorkQueue(T[])
WorkQueue() = WorkQueue{Any}()
WorkQueue(xs) = WorkQueue(collect(xs))
function Base.push!(q::WorkQueue, x)
i = findfirst(==(x), q.items)
i === nothing || (deleteat!(q.items, i))
push!(q.items, x)
return q
end
Base.pop!(q::WorkQueue) = pop!(q.items)
Base.isempty(q::WorkQueue) = isempty(q.items)
# Simple Graph
struct Graph{T}
nodes::Dict{T,Int}
links::Vector{Set{T}}
end
Graph{T}() where T = Graph{T}(Dict(), [])
Base.length(g::Graph) = length(g.links)
Base.keys(g::Graph) = keys(g.nodes)
function Base.getindex(g::Graph, x)
if !haskey(g.nodes, x)
push!(g.links, Set())
g.nodes[x] = length(g)
end
return g.links[g.nodes[x]]
end
function connect!(g::Graph, a, b)
push!(g[a], b)
push!(g[b], a)
return g
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 24859 | import Base: push!, insert!, getindex, setindex!, iterate, length
# We have our own versions of these in order to
# (1) be more robust to Base IR changes, and
# (2) make sure that mistakes/bugs do not cause bad LLVM IR.
"""
LineInfoNode(file::Symbol, line::Int32, [inlined_at::Int32])
Represents line information about a statement; Inlined statements has a non-zero
`inlined_at` which represents the "parent" location in the linetable array.
"""
struct LineInfoNode
file::Symbol
line::Int32
inlined_at::Int32
end
LineInfoNode(file, line) = LineInfoNode(file, line, Int32(0))
struct Undefined end
const undef = Undefined()
"""
Variable(id::Integer)
var(id::Integer)
Represents an SSA variable. Primarily used as an index into `IR` objects.
"""
struct Variable
id::Int
end
var(id::Integer) = Variable(id)
"""
Branch(condition::Any, block::Int, args::Vector{Any})
Represents a generalized branching instruction, consisting of a `condition` (usually a `Variable` of
boolean type), a target `block`, and a vector of `args` passed to the jump target. There are three
types of branches that exist by the following convention:
- A return branch is represented by `Branch(nothing, 0, [<return value>])`.
- An unconditional branch is represented by `Branch(nothing, <target>, [<optional arguments ...>])`
- A conditional branch is represented by `Branch(<condition>, <target>, [<optional arguments ...>])`
See also: [`branch!`](@branch!), [`return!`](@return), [`isreturn`](@isreturn),
[`isconditional`](@isconditional)
"""
struct Branch
condition::Any
block::Int
args::Vector{Any}
end
Branch(br::Branch; condition = br.condition,
block = br.block, args = br.args) =
Branch(condition, block, args)
"""
isreturn(br::Branch)
Check whether `br` has the form of a return branch (see [`Branch`](@Branch)).
"""
isreturn(b::Branch) = b.block == 0 && length(b.args) == 1
"""
returnvalue(b::Branch)
Get the return value of `b` (the first argument of the branch).
"""
returnvalue(b::Branch) = b.args[1]
"""
isconditional(br::Branch)
Check whether `br` has the form of a conditional branch (see [`Branch`](@Branch)).
"""
isconditional(b::Branch) = b.condition != nothing
Base.:(==)(a::Branch, b::Branch) =
(a.condition, a.block, a.args) == (b.condition, b.block, b.args)
Base.copy(br::Branch) = Branch(br.condition, br.block, copy(br.args))
"""
arguments(br::Branch)
Return the argument vector of the branch `br`. (These are the arguments passed to a jumped-to
block.)
"""
arguments(b::Branch) = b.args
const unreachable = Branch(nothing, 0, [])
"""
Statement(expr; type, line)
stmt(expr; type, line)
Represents a single statement in the IR. The `expr` is a non-nested Julia
expression (`Expr`). `type` represents the return type of the statement; in most
cases this can be ignored and defaults to `Any`. `line` represents the source
location of the statement; it is an integer index into the IR's line table.
As a convenience, if `expr` is already a statement, the new statement will
inherit its type and line number.
"""
struct Statement
expr::Any
type::Any
line::Int
end
Statement(x; expr = x, type = Any, line = 0) =
Statement(expr, type, line)
"""
Statement(stmt::Statement; expr, type, line)
Copy of `stmt` with optionally updated fields.
"""
Statement(x::Statement; expr = x.expr, type = x.type, line = x.line) =
Statement(expr, type, line)
const stmt = Statement
"""
BasicBlock(stmts::Vector{Statement}, args::Vector{Any},
argtypes::Vector{Any}, branches::Vector{Branch})
BasicBlock([stmts])
Represents a [basic
block](https://en.wikipedia.org/wiki/Static_single_assignment_form#Converting_to_SSA) of code in
SSA form. A block consists of a list of statements, followed by optional branching instructions and
arguments, with optional types.
"""
struct BasicBlock
stmts::Vector{Statement}
args::Vector{Any}
argtypes::Vector{Any}
branches::Vector{Branch}
end
BasicBlock(stmts = []) = BasicBlock(stmts, [], [], Branch[])
Base.copy(bb::BasicBlock) = BasicBlock(copy(bb.stmts), copy(bb.args), copy(bb.argtypes), copy.(bb.branches))
"""
branches(bb::BasicBlock)
Return the vector of branching instructions in block `bb`.
"""
branches(bb::BasicBlock) = bb.branches
"""
arguments(bb::BasicBlock)
Return the argument vector of the basic block `bb`. (These are the arguments given by the branch
to this block.)
"""
arguments(bb::BasicBlock) = bb.args
"""
argtypes(bb::BasicBlock)
Return the argument types of the basic block `bb`. (These are the arguments given by the branch
to this block.)
"""
argtypes(bb::BasicBlock) = bb.argtypes
"""
IR()
IR(metadata; slots = false)
Represents a fragment of SSA-form code.
IR can be constructed from scratch, but more usually an existing Julia method is
used as a starting point (see [`meta`](@ref) for how to get metadata for a
method). The `slots` argument determines whether the IR preserves mutable
variable slots; by default, these are converted to SSA-style variables.
As a shortcut, IR can be constructed directly from a type signature, e.g.
julia> IR(typeof(gcd), Int, Int)
1: (%1, %2, %3)
%4 = %2 == 0
br 4 unless %4
2: ...
See also: [`code_ir`](@code_ir)
"""
struct IR
defs::Vector{Tuple{Int,Int}}
blocks::Vector{BasicBlock}
lines::Vector{LineInfoNode}
meta::Any
end
IR(; meta = nothing) = IR([],[BasicBlock()],[],meta)
IR(lines::Vector{LineInfoNode}; meta = nothing) = IR([],[BasicBlock()],lines,meta)
Base.copy(ir::IR) = IR(copy(ir.defs), copy.(ir.blocks), copy(ir.lines), ir.meta)
length(ir::IR) = sum(x -> x[2] > 0, ir.defs, init = 0)
"""
block!(ir::IR)
block!(ir::IR, i)
Insert a new block in `ir`. If `i` is given, the block is inserted at this position, otherwise it
is appended at the end. Branches in all other blocks are updated to preserve the original
behaviour.
"""
function block!(ir::IR, i = length(blocks(ir))+1)
insert!(ir.blocks, i, BasicBlock())
if i != length(blocks(ir))
for b in blocks(ir), bi = 1:length(branches(b))
br = branches(b)[bi]
br.block >= i && (branches(b)[bi] = Branch(br, block = br.block+1))
end
for (ii, (b, j)) = enumerate(ir.defs)
b >= i && (ir.defs[ii] = (b+1, j))
end
end
return block(ir, i)
end
"""
deleteblock!(ir::IR, i)
Delete the block at position `i`. Branches in all other blocks are updated to preserve the original
behaviour.
"""
function deleteblock!(ir::IR, i::Integer)
deleteat!(ir.blocks, i)
if i != length(blocks(ir))+1
for b in blocks(ir), bi = 1:length(branches(b))
br = branches(b)[bi]
br.block >= i && (branches(b)[bi] = Branch(br, block = br.block-1))
end
end
for (ii, (b, j)) = enumerate(ir.defs)
b == i && (ir.defs[ii] = (-1, -1))
b > i && (ir.defs[ii] = (b-1, j))
end
return
end
struct Block
ir::IR
id::Int
end
BasicBlock(b::Block) = b.ir.blocks[b.id]
branches(b::Block) = branches(BasicBlock(b))
branches(ir::IR) = length(blocks(ir)) == 1 ? branches(block(ir, 1)) :
error("IR has multiple blocks, so `branches(ir)` is ambiguous.")
arguments(b::Block) = arguments(BasicBlock(b))
arguments(ir::IR) = arguments(block(ir, 1))
argtypes(b::Block) = argtypes(BasicBlock(b))
argtypes(ir::IR) = argtypes(block(ir, 1))
"""
canbranch(b::Block)
Check whether adding a branch to block `b` will be valid (i.e, the last existing branch is not
conditional).
"""
canbranch(b::Block) = length(branches(b)) == 0 || isconditional(branches(b)[end])
"""
isreturn(b::Block)
Check whether the block `b` has a return branch.
"""
isreturn(b::Block) = any(isreturn, branches(b))
"""
explicitbranch!(b::Block)
explicitbranch!(ir::IR)
Convert implicit fallthroughs to explicit branches to the next block (these occur when the last
branch in a block is conditional):
1: (%1, %2)
%3 = %2 < 0
br 3 unless %3
2:
return 0
3:
return %2
will become
1: (%1, %2)
%3 = %2 < 0
br 3 unless %3
br 2
2:
return 0
3:
return %2
"""
function explicitbranch!(b::Block)
b.id == 1 && return
a = block(b.ir, b.id-1)
if all(isconditional, branches(a))
branch!(a, b.id)
end
return b
end
explicitbranch!(ir::IR) = (foreach(explicitbranch!, blocks(ir)); return ir)
"""
branches(b::Block, c::Block)
Return the vector of all branches from block `b` to block `c`.
"""
function branches(b::Block, c::Block)
c.id == b.id+1 && explicitbranch!(c)
filter(br -> br.block == c.id, branches(b))
end
branches(b::Block, c::Integer) = branches(b, block(b.ir, c))
"""
returnvalue(b::Block)
Retreive the return value of a block.
julia> f(x) = 3x + 2;
julia> IRTools.block(@code_ir(f(1)), 1)
1: (%1, %2)
%3 = 3 * %2
%4 = %3 + 2
return %4
julia> IRTools.returnvalue(ans)
%4
"""
function returnvalue(b::Block)
isreturn(branches(b)[end]) || error("Block does not return")
return returnvalue(branches(b)[end])
end
"""
returnvalue(b::Block)
Retreive the return type of a block.
"""
returntype(b::Block) = exprtype(b.ir, returnvalue(b))
"""
argument!(block, [value, type]; at, insert)
argument!(ir, [value, type]; at, insert)
Create a new argument for the given block / IR fragment, and return the variable
representing the argument.
julia> ir = IR();
julia> argument!(ir)
%1
julia> ir
1: (%1)
The `at` keyword argument can be used to specify where the new argument should
go; by default it is appended to the end of the argument list.
Unless `insert = false`, if there are branches to this block, they will be updated to pass `value`
(`nothing` by default) as an argument (by default, `insert = true`).
"""
function argument!(b::Block, value = nothing, t = Any;
insert = true, at = length(arguments(b))+1, type = t)
if at < length(arguments(b))
for i = 1:length(b.ir.defs)
(c, j) = b.ir.defs[i]
c == b.id && -j >= at && (b.ir.defs[i] = (c, j-1))
end
end
push!(b.ir.defs, (b.id, -at))
arg = var(length(b.ir.defs))
insert!(arguments(b), at, arg)
insert!(BasicBlock(b).argtypes, at, type)
if insert
explicitbranch!(b)
for c in blocks(b.ir), br in branches(c)
br.block == b.id && insert!(arguments(br), at, value)
end
end
return arg
end
argument!(ir::IR, a...; kw...) =
argument!(block(ir, 1), nothing, a...; kw..., insert = false)
"""
emptyargs!(b::Block)
Delete all arguments from block `b`, and automatically remove them from all
branches to this block.
"""
function emptyargs!(b::Block)
empty!(arguments(b))
for c in blocks(b.ir), br in branches(c)
br.block == b.id && empty!(arguments(br))
end
return
end
"""
deletearg!(b::Block, i::Integer)
Delete the `i`-th argument from block `b`, and automatically remove it from all
branches to this block.
"""
function deletearg!(b::Block, i::Integer)
arg = arguments(b)[i]
deleteat!(arguments(b), i)
deleteat!(argtypes(b), i)
for c in blocks(b.ir), br in branches(c)
br.block == b.id && deleteat!(arguments(br), i)
end
b.ir.defs[arg.id] = (-1, -1)
for arg in arguments(b)[i:end]
(bl, pos) = b.ir.defs[arg.id]
b.ir.defs[arg.id] = (bl, pos+1)
end
return
end
function deletearg!(b::Block, i::AbstractVector)
for i in sort(i, lt = >)
deletearg!(b, i)
end
end
"""
deletearg!(ir::IR, i)
Delete the `i`-th argument from the first block of `ir`, and automatically remove it from all
branches to this block.
"""
deletearg!(ir::IR, i) = deletearg!(block(ir, 1), i)
"""
block(ir, i)
Return the `i`-th `Block` of `ir`.
"""
block(ir::IR, i) = Block(ir, i)
block(ir::IR, v::Variable) = blockidx(ir, v)[1]
"""
blocks(ir)
Return the list of blocks `Block` of `ir`.
"""
blocks(ir::IR) = [block(ir, i) for i = 1:length(ir.blocks)]
function blockidx(ir::IR, x::Variable)
b, i = get(ir.defs, x.id, (-1, -1))
i > 0 || error("No such variable $x")
block(ir, b), i
end
"""
haskey(ir, var)
Check whether the variable `var` was defined in `ir`.
julia> f(x) = 3x + 2;
julia> ir = @code_ir f(1)
1: (%1, %2)
%3 = 3 * %2
%4 = %3 + 2
return %4
julia> haskey(ir, var(3))
true
julia> haskey(ir, var(7))
false
"""
function Base.haskey(ir::IR, x::Variable)
b, i = get(ir.defs, x.id, (-1, -1))
return i > 0
end
getindex(b::Block, i::Integer) = BasicBlock(b).stmts[i]
getindex(b::Block, i::Variable) = b.ir[i]
setindex!(b::Block, x::Statement, i::Integer) = (BasicBlock(b).stmts[i] = x)
setindex!(b::Block, x, i::Integer) = (b[i] = Statement(b[i], expr = x))
branch(block::Integer, args...; unless = nothing) =
Branch(unless, block, Any[args...])
branch(block::Block, args...; kw...) = branch(block.id, args...; kw...)
"""
branch!(b::Block, block, args...; unless = nothing)
Add to block `b` a new branch to `block`, with arguments `args` and condition `unless`,
and return it.
"""
function branch!(b::Block, block, args...; unless = nothing)
brs = branches(b)
unless === nothing && deleteat!(brs, findall(br -> br.condition === nothing, brs))
args = map(a -> a isa Expr ? push!(b, a) : a, args)
push!(brs, branch(block, args...; unless = unless))
return b
end
"""
branch!(ir::IR, block, args...; unless = nothing)
Add to the last block of `ir` a new branch to `block`, with arguments `args` and condition `unless`,
and return it.
"""
function branch!(ir::IR, args...; kw...)
branch!(blocks(ir)[end], args...; kw...)
return ir
end
"""
return!(block, x)
return!(ir, x)
Add to `block` or the last block of `ir` a return branch with argument `x`, and return it.
"""
return!(ir, x) = branch!(ir, 0, x)
function getindex(ir::IR, i::Variable)
b, i = blockidx(ir, i)
return b[i]
end
Base.get(ir::IR, i::Variable, default) = haskey(ir, i) ? ir[i] : default
function setindex!(ir::IR, x, i::Variable)
b, i = blockidx(ir, i)
b[i] = x
end
setindex!(b::Block, x, i::Variable) = setindex!(b.ir, x, i)
function Base.delete!(ir::IR, i::Variable)
ir[i] = nothing
ir.defs[i.id] = (-1, -1)
return ir
end
Base.delete!(b::Block, i::Variable) = delete!(b.ir, i)
length(b::Block) = count(x -> x[1] == b.id, b.ir.defs)
"""
successors(b::Block)
Returns all `Block`s from which you can reach `b` in one jump; basically, all x such that
`branches(x, b)` is non-empty. Implicit jumps by fall-through are noticed as well.
See: [`predecessors`](@predecessors)
"""
function successors(b::Block)
brs = BasicBlock(b).branches
succs = Int[br.block for br in brs if br.block > 0]
all(br -> br.condition != nothing, brs) && b.id < length(blocks(b.ir)) && push!(succs, b.id+1)
return [block(b.ir, succ) for succ in succs]
end
"""
predecessors(b::Block)
Returns all `Block`s of which `b` is a successor; basically, all x such that
`branches(x, b)` is non-empty. Implicit jumps by fall-through are noticed as well.
See: [`successors`](@successors)
"""
predecessors(b::Block) = [c for c in blocks(b.ir) if b in successors(c)]
"""
keys(ir)
Return the variable keys for all statements defined in `ir`.
julia> f(x) = 3x + 2;
julia> ir = @code_ir f(1)
1: (%1, %2)
%3 = 3 * %2
%4 = %3 + 2
return %4
julia> keys(ir)
2-element Array{IRTools.Variable,1}:
%3
%4
"""
Base.keys(b::Block) = first.(sort([Variable(i) => v for (i, v) in enumerate(b.ir.defs) if v[1] == b.id && v[2] > 0], by = x->x[2]))
function iterate(b::Block, (ks, i) = (keys(b), 1))
i > length(ks) && return
return (ks[i]=>b.ir[ks[i]], (ks, i+1))
end
Base.keys(ir::IR) = first.(sort([Variable(i) => v for (i, v) in enumerate(ir.defs) if v[2] > 0], by = x->x[2]))
function iterate(ir::IR, (ks, i) = (keys(ir), 1))
i > length(ks) && return
return (ks[i]=>ir[ks[i]], (ks, i+1))
end
applyex(f, x) = x
applyex(f, x::Expr) =
Expr(x.head, [x isa Expr ? f(x) : x for x in x.args]...)
applyex(f, x::Statement) = Statement(x, expr = applyex(f, x.expr))
"""
push!(ir, x)
Append the statement or expression `x` to the IR or block `ir`, returning the
new variable. See also [`pushfirst!`](@ref), [`insert!`](@ref).
julia> ir = IR();
julia> x = argument!(ir)
%1
julia> push!(ir, xcall(:*, x, x))
%2
julia> ir
1: (%1)
%2 = %1 * %1
"""
function push!(b::Block, x::Statement)
if !isexpr(x.expr, :foreigncall) # needed to avoid https://github.com/MikeInnes/IRTools.jl/issues/30
x = applyex(a -> push!(b, Statement(x, expr = a)), x)
end
x = Statement(x)
push!(BasicBlock(b).stmts, x)
push!(b.ir.defs, (b.id, length(BasicBlock(b).stmts)))
return Variable(length(b.ir.defs))
end
push!(b::Block, x) = push!(b, Statement(x))
push!(b::Block, x::Variable) = x
# TODO make this work on nested Exprs.
function insert!(b::Block, idx::Integer, x)
insert!(BasicBlock(b).stmts, idx, Statement(x))
for i = 1:length(b.ir.defs)
c, j = b.ir.defs[i]
if c == b.id && j >= idx
b.ir.defs[i] = (c, j+1)
end
end
push!(b.ir.defs, (b.id, idx))
return Variable(length(b.ir.defs))
end
Base.pushfirst!(b::Block, x) = insert!(b, 1, x)
push!(ir::IR, x) = push!(block(ir, length(ir.blocks)), x)
"""
pushfirst!(ir, x)
Insert the expression or statement `x` into the given IR or block at the
beginning, returning the new variable. See also [`push!`](@ref),
[`insert!`](@ref).
julia> f(x) = 3x + 2
f (generic function with 1 method)
julia> ir = @code_ir f(1)
1: (%1, %2)
%3 = 3 * %2
%4 = %3 + 2
return %4
julia> pushfirst!(ir, :(println("hello, world")))
%5
julia> ir
1: (%1, %2)
%5 = println("hello, world")
%3 = 3 * %2
%4 = %3 + 2
return %4
"""
Base.pushfirst!(ir::IR, x) = pushfirst!(block(ir, 1), x)
"""
insert!(ir, v, x)
Insert the expression or statement `x` into the given IR, just before the
variable `v` is defined, returning the new variable for `x`. See also
[`insertafter!`](@ref).
julia> f(x) = 3x + 2
f (generic function with 1 method)
julia> ir = @code_ir f(1)
1: (%1, %2)
%3 = 3 * %2
%4 = %3 + 2
return %4
julia> insert!(ir, IRTools.var(4), :(println("hello, world")))
%5
julia> ir
1: (%1, %2)
%3 = 3 * %2
%5 = println("hello, world")
%4 = %3 + 2
return %4
"""
function insert!(ir::IR, i::Variable, x; after = false)
if after && ir.defs[i.id][2] < 0
pushfirst!(block(ir, ir.defs[i.id][1]), x)
else
b, i = blockidx(ir, i)
insert!(b, i+after, x)
end
end
insert!(b::Block, i::Variable, x; after = false) =
insert!(b.ir, i, x; after = after)
"""
insertafter!(ir, v, x)
Insert the expression or statement `x` into the given IR, just before the
variable `v` is defined, returning the new variable for `x`. See also
[`insert!`](@ref).
julia> f(x) = 3x + 2
f (generic function with 1 method)
julia> ir = @code_ir f(1)
1: (%1, %2)
%3 = 3 * %2
%4 = %3 + 2
return %4
julia> IRTools.insertafter!(ir, IRTools.var(4), :(println("hello, world")))
%5
julia> ir
1: (%1, %2)
%3 = 3 * %2
%4 = %3 + 2
%5 = println("hello, world")
return %4
"""
insertafter!(ir, i, x) = insert!(ir, i, x, after=true)
"""
empty(ir)
Create an empty IR fragment based on the given IR. The line number table and
any metadata are preserved from the original IR.
julia> ir = empty(@code_ir gcd(10, 5))
1:
julia> ir.meta
Metadata for gcd(a::T, b::T) where T<:Union{Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8} in Base at intfuncs.jl:31
"""
Base.empty(ir::IR) = IR(copy(ir.lines), meta = ir.meta)
"""
permute!(ir::IR, perm::AbstractVector)
Permutes block order in-place, keeping track of internal references (like branch targets).
"""
function Base.permute!(ir::IR, perm::AbstractVector)
explicitbranch!(ir)
permute!(ir.blocks, perm)
iperm = invperm(perm)
for v = 1:length(ir.defs)
b, i = ir.defs[v]
b == -1 && continue
ir.defs[v] = (iperm[b], i)
end
for b in blocks(ir), i = 1:length(branches(b))
branches(b)[i].block > 0 || continue
br = branches(b)[i]
branches(b)[i] = Branch(br, block = iperm[br.block])
end
return ir
end
function IR(b::Block)
ir = IR(copy(b.ir.defs), [copy(BasicBlock(b))], b.ir.lines, b.ir.meta)
for i in 1:length(ir.defs)
if ir.defs[i][1] == b.id
ir.defs[i] = (1, ir.defs[i][2])
else
ir.defs[i] = (-1, -1)
end
end
return ir
end
# Pipe
struct NewVariable
id::Int
end
"""
Pipe(ir)
In general, it is not efficient to insert statements into IR; only appending is
fast, for the same reason as with `Vector`s.
For this reason, the `Pipe` construct makes it convenient to incrementally build
an new IR fragment from an old one, making efficient modifications as you go.
The general pattern looks like:
pr = IRTools.Pipe(ir)
for (v, st) in pr
# do stuff
end
ir = IRTools.finish(pr)
Iterating over `pr` is just like iterating over `ir`, except that within the
loop, inserting and deleting statements in `pr` around `v` is efficient. Later,
`finish(pr)` converts it back to a normal IR fragment (in this case just a plain
copy of the original).
"""
mutable struct Pipe
from::IR
to::IR
map::Dict{Any,Any}
var::Int
branch
block
end
var!(p::Pipe) = NewVariable(p.var += 1)
substitute!(p::Pipe, x, y) = (p.map[x] = y; x)
substitute(p::Pipe, x::Union{Variable,NewVariable}) = p.map[x]
substitute(p::Pipe, x) = get(p.map, x, x)
substitute(p::Pipe, x::Statement) = stmt(x, expr = substitute(p, x.expr))
substitute(p::Pipe, x::Expr) = Expr(x.head, substitute.((p,), x.args)...)
substitute(p::Pipe) = x -> substitute(p, x)
function Pipe(ir)
p = Pipe(ir, IR(copy(ir.lines), meta = ir.meta), Dict(), 0, identity, identity)
for (x, T) in zip(p.from.blocks[1].args, p.from.blocks[1].argtypes)
y = argument!(blocks(p.to)[end], nothing, T, insert = false)
substitute!(p, x, y)
end
return p
end
function pipestate(ir::IR)
ks = sort([Variable(i) => v for (i, v) in enumerate(ir.defs) if v[2] > 0], by = x->x[2])
[first.(filter(x -> x[2][1] == b, ks)) for b = 1:length(ir.blocks)]
end
branches(f, p::Pipe) = (p.branch = f)
blocks(f, p::Pipe) = (p.block = f)
function iterate(p::Pipe, (ks, b, i) = (pipestate(p.from), 1, 1))
i == 1 && b == 1 && p.block(b)
if i == 1 && b != 1
for (x, T) in zip(p.from.blocks[b].args, p.from.blocks[b].argtypes)
y = argument!(blocks(p.to)[end], nothing, T, insert = false)
substitute!(p, x, y)
end
end
if i > length(ks[b])
for br in branches(block(p.from, b))
br′ = p.branch(br)
br′ == nothing || push!(p.to.blocks[end].branches, map(substitute(p), br′))
end
b == length(ks) && return
p.block(b)
block!(p.to)
return iterate(p, (ks, b+1, 1))
end
v = ks[b][i]
st = p.from[v]
substitute!(p, v, push!(p.to, substitute(p, st)))
((v, st), (ks, b, i+1))
end
finish(p::Pipe) = p.to
islastdef(ir::IR, v::Variable) =
v.id == length(ir.defs) &&
ir.defs[v.id] == (length(ir.blocks), length(ir.blocks[end].stmts))
setindex!(p::Pipe, x, v) = p.to[substitute(p, v)] = substitute(p, x)
function setindex!(p::Pipe, x::Variable, v)
v′ = substitute(p, v)
if islastdef(p.to, v′)
delete!(p, v)
substitute!(p, v, substitute(p, x))
else
p.to[v′] = substitute(p, x)
end
end
function Base.push!(p::Pipe, x)
tmp = var!(p)
substitute!(p, tmp, push!(p.to, substitute(p, x)))
return tmp
end
function Base.pushfirst!(p::Pipe, x)
tmp = var!(p)
substitute!(p, tmp, pushfirst!(p.to, substitute(p, x)))
return tmp
end
function Base.delete!(p::Pipe, v)
v′ = substitute(p, v)
delete!(p.map, v)
if islastdef(p.to, v′)
pop!(p.to.defs)
pop!(p.to.blocks[end].stmts)
else
delete!(p.to, v′)
end
end
function insert!(p::Pipe, v, x; after = false)
v′ = substitute(p, v)
x = substitute(p, x)
tmp = var!(p)
if islastdef(p.to, v′) # we can make this case efficient by renumbering
if after
substitute!(p, tmp, push!(p.to, x))
else
substitute!(p, v, push!(p.to, p.to[v′]))
p.to[v′] = Statement(x)
substitute!(p, tmp, v′)
end
else
substitute!(p, tmp, insert!(p.to, v′, x, after = after))
end
return tmp
end
argument!(p::Pipe, a...; kw...) =
substitute!(p, var!(p), argument!(p.to, a...; kw...))
function branch!(ir::Pipe, b, args...; unless = nothing)
args = map(a -> substitute(ir, a), args)
cond = substitute(ir, unless)
branch!(blocks(ir.to)[end], b, args...; unless = cond)
return ir
end
function block!(p::Pipe)
block!(p.to)
return
end
function blockargument!(p::Pipe, type)
x = argument!(blocks(p.to)[end], nothing, type, insert = false)
substitute!(p, var!(p), x)
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 3016 | import Base: show
# TODO: real expression printing
function Base.show(io::IO, x::Variable)
bs = get(io, :bindings, Dict())
haskey(bs, x) ? print(io, bs[x]) : print(io, "%", x.id)
end
print_stmt(io::IO, ex::Expr) = print_stmt(io::IO, Val(ex.head), ex)
print_stmt(io::IO, ::Val, ex) = print(io, ex)
print_stmt(io::IO, ex) = print(io, ex)
function show(io::IO, b::Branch)
if b == unreachable
print(io, "unreachable")
elseif isreturn(b)
print(io, "return ", b.args[1])
else
print(io, "br $(b.block)")
if !isempty(b.args)
print(io, " (")
join(io, b.args, ", ")
print(io, ")")
end
b.condition != nothing && print(io, " unless $(b.condition)")
end
end
const tab = " "
function printargs(io::IO, args, types = [Any for arg in args])
print(io, "(")
for i = 1:length(args)
print(io, args[i])
types[i] != Any && print(io, " :: ", types[i])
i != length(args) && print(io, ", ")
end
print(io, ")")
end
function show(io::IO, b::Block)
indent = get(io, :indent, 0)
bs = get(io, :bindings, Dict())
bb = BasicBlock(b)
print(io, tab^indent)
print(io, b.id, ":")
if !isempty(bb.args)
print(io, " ")
printargs(io, bb.args, bb.argtypes)
end
for (x, st) in b
haskey(bs, x) && continue
println(io)
print(io, tab^indent, " ")
x == nothing || print(io, string("%", x.id), " = ")
st.expr == nothing ? print(io, "nothing") :
print_stmt(io, st.expr)
st.type == Any || print(io, " :: ", st.type)
end
for br in bb.branches
println(io)
print(io, tab^indent, " ", br)
end
end
function show(io::IO, ir::IR)
show(io, block(ir, 1))
for b in blocks(ir)[2:end]
println(io)
show(io, b)
end
end
function print_stmt(io::IO, ex::IR)
io = IOContext(io, :indent=>get(io, :indent, 0)+2)
println(io)
show(io, ex)
end
function print_stmt(io::IO, ::Val{:enter}, ex)
print(io, "try #$(ex.args[1])")
if length(ex.args) >= 2
print(io, " with scope ", ex.args[2])
end
end
function print_stmt(io::IO, ::Val{:leave}, ex)
print(io, "end try")
end
function print_stmt(io::IO, ::Val{:catch}, ex)
print(io, "catch $(ex.args[1])")
args = ex.args[2:end]
if !isempty(args)
print(io, " (")
join(io, args, ", ")
print(io, ")")
end
end
function print_stmt(io::IO, ::Val{:pop_exception}, ex)
print(io, "pop exception $(ex.args[1])")
end
function lambdacx(io, ex)
bs = get(io, :bindings, Dict())
ir = ex.args[1]
args = ex.args[2:end]
bs′ = Dict()
for (v, st) in ir
ex = st.expr
if iscall(ex, GlobalRef(Base, :getindex)) &&
ex.args[2] == arguments(ir)[1] &&
ex.args[3] isa Integer
x = args[ex.args[3]]
bs′[v] = string(get(bs, x, x), "'")
end
end
return bs′
end
function print_stmt(io::IO, ::Val{:lambda}, ex)
print(io, "λ :")
# printargs(io, ex.args[2:end])
io = IOContext(io, :indent => get(io, :indent, 0)+2,
:bindings => lambdacx(io, ex))
println(io)
print(io, ex.args[1])
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 2673 | import Base: map, map!
import Core.Compiler: PhiNode, PiNode, ssamap, userefs
import MacroTools: walk, prewalk, postwalk
walk(x::PhiNode, inner, outer) =
outer(PhiNode(x.edges,
[inner(isassigned(x.values, i) ? x.values[i] : undef)
for i in 1:length(x.values)]))
walk(x::PiNode, inner, outer) = outer(PiNode(inner(x.val), x.typ))
xcall(mod::Module, f::Symbol, args...) = Expr(:call, GlobalRef(mod, f), args...)
xcall(f::Symbol, args...) = xcall(Base, f, args...)
xcall(f, args...) = Expr(:call, f, args...)
map(f, br::Branch) = Branch(br, condition = f(br.condition), args = f.(br.args))
function map(f, b::BasicBlock)
stmts = map(x -> Statement(x, expr = f(x.expr)), b.stmts)
branches = map(br -> map(f, br), b.branches)
BasicBlock(stmts, b.args, b.argtypes, branches)
end
function map!(f, b::BasicBlock)
map!(x -> Statement(x, expr = f(x.expr)), b.stmts, b.stmts)
map!(br -> Branch(br, condition = f(br.condition), args = f.(br.args)), b.branches, b.branches)
return b
end
function map!(f, b::Block)
map!(f, BasicBlock(b))
end
function map(f, ir::IR)
IR(ir.defs, map.(f, ir.blocks), ir.lines, ir.meta)
end
function map!(f, ir::IR)
for b in blocks(ir)
map!(f, b)
end
return ir
end
walk(st::Statement, inner, outer) = Statement(st, expr = inner(st.expr))
walk(bb::BasicBlock, inner, outer) = map(inner, bb)
walk(bb::Branch, inner, outer) = map(inner, bb)
walk(b::Block, inner, outer) = walk(BasicBlock(b), inner, outer)
walk(ir::IR, inner, outer) = outer(map(inner, ir))
# Avoid recursing into lambdas
prewalk(f, ir::Union{IR,Block}) = walk(f(ir), x -> x isa IR ? x : prewalk(f, x), identity)
postwalk(f, ir::Union{IR,Block}) = walk(ir, x -> x isa IR ? x : postwalk(f, x), f)
prewalk!(f, ir::Union{IR,Block}) = map!(x -> x isa IR ? x : prewalk(f, x), ir)
postwalk!(f, ir::Union{IR,Block}) = map!(x -> x isa IR ? x : postwalk(f, x), ir)
varmap(f, x) = prewalk(x -> x isa Variable ? f(x) : x, x)
exprtype(x::GlobalRef; typeof = Typeof) = isconst(x.mod, x.name) ? typeof(getfield(x.mod, x.name)) : Any
exprtype(ir::IR, x::GlobalRef; typeof = Typeof) = exprtype(x, typeof = typeof)
exprtype(ir::IR, x::QuoteNode; typeof = Typeof) = typeof(x.value)
exprtype(ir::IR, x::Expr; typeof = Typeof) = error(x)
exprtype(ir::IR, x; typeof = Typeof) = typeof(x)
function exprtype(ir::IR, x::Variable; typeof = Typeof)
b, i = get(ir.defs, x.id, (-1, -1))
b == -1 && error("No such variable $x")
if i > 0
ir[x].type
else
ir.blocks[b].argtypes[-i]
end
end
function exprline(ir::IR, x::Variable)
b, i = get(ir.defs, x.id, (-1, -1))
i > 0 || return
get(ir.lines, ir[x].line, nothing)
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 7708 | module Wrap
using MacroTools: isexpr, prewalk
using ..Inner, ..IRTools
import ..Inner: IR, Variable, Statement, Branch, BasicBlock, Meta, block!,
unreachable, varmap, argument!, branch!, return!, LineInfoNode
import Core: CodeInfo, GotoNode, SSAValue
import Core.Compiler: IRCode, CFG, GotoIfNot, ReturnNode, StmtRange
@static if VERSION > v"1.6-"
import Core.Compiler: InstructionStream
end
@static if VERSION ≥ v"1.9.0-DEV.502"
const LineType = Int32
else
const LineType = Int
end
@static if VERSION ≥ v"1.12.0-DEV.173"
addline!(lines, li) = push!(lines, li, Int32(0), Int32(0))
else
addline!(lines, li) = push!(lines, li)
end
unvars(ex) = prewalk(x -> x isa Variable ? SSAValue(x.id) : x, ex)
function IRCode(ir::IR)
defs = Dict()
stmts, types, lines = [], [], Int32[]
index = Int[]
for b in IRTools.blocks(ir)
if b.id == 1
for (i, arg) in enumerate(IRTools.arguments(b))
defs[arg] = Core.SlotNumber(i)
end
else
@assert isempty(BasicBlock(b).args)
end
for (v, st) in b
defs[v] = Variable(length(stmts)+1)
ex = varmap(x -> get(defs, x, x), st.expr) |> unvars
@static if isdefined(Core.IR, :EnterNode)
ex = isexpr(ex, :enter) ? Core.EnterNode(ex.args...) : ex
end
push!(stmts, ex)
push!(types, st.type)
addline!(lines, st.line)
end
for br in BasicBlock(b).branches
if IRTools.isreturn(br)
x = get(defs, br.args[1], br.args[1]) |> unvars
push!(stmts, ReturnNode(x))
elseif br == unreachable
@static if VERSION >= v"1.10"
push!(stmts, ReturnNode())
else
push!(stmts, Expr(:call, GlobalRef(Core, :throw), "unreachable"))
end
elseif br.condition === nothing
push!(stmts, GotoNode(br.block))
else
cond = get(defs, br.condition, br.condition) |> unvars
push!(stmts, GotoIfNot(cond, br.block))
end
push!(types, Any); addline!(lines, Int32(0))
end
push!(index, length(stmts)+1)
end
ranges = StmtRange.([1, index[1:end-1]...], index.-1)
succs = map.(x -> x.id, IRTools.successors.(IRTools.blocks(ir)))
preds = map.(x -> x.id, IRTools.predecessors.(IRTools.blocks(ir)))
bs = Core.Compiler.BasicBlock.(ranges, preds, succs)
cfg = CFG(bs, index)
flags = UInt32[0x00 for _ in stmts]
sps = VERSION > v"1.2-" ? (VERSION >= v"1.10.0-DEV.552" ? Core.Compiler.VarState[] : []) : Core.svec()
@static if VERSION > v"1.6-"
@static if isdefined(Core.Compiler, :CallInfo)
stmtinfo = Core.Compiler.CallInfo[Core.Compiler.NoCallInfo() for _ in 1:length(stmts)]
else
stmtinfo = Any[nothing for _ in 1:length(stmts)]
end
stmts = InstructionStream(stmts, types, stmtinfo, lines, flags)
meta = @static VERSION < v"1.9.0-DEV.472" ? [] : Expr[]
@static if VERSION ≥ v"1.12.0-DEV.173"
nlocs = length(types)
codelocs = fill(Int32(0), 3nlocs)
if !isempty(ir.lines)
LI = first(ir.lines)
topfile, topline = LI.file, LI.line
for i in 1:nlocs
lineidx = lines[3i - 2]
if lineidx == 0
continue
end
# TODO: support inlining, see passes/inline.jl
@assert LI.file === topfile && LI.inlined_at == 0
LI = ir.lines[lineidx]
codelocs[3i - 2] = LI.line
end
else
topline = Int32(1)
end
codelocs = @ccall jl_compress_codelocs(topline::Int32, codelocs::Any, nlocs::Csize_t)::Any
debuginfo = Core.Compiler.DebugInfoStream(lines)
debuginfo.def = ir.meta isa Meta ? ir.meta.instance : :var"n/a"
debuginfo.linetable = Core.DebugInfo(debuginfo.def, nothing, Core.svec(), codelocs)
IRCode(stmts, cfg, debuginfo, ir.blocks[1].argtypes, meta, sps)
else
mod, meth = ir.meta isa Meta ? (ir.meta.method.module, ir.meta.method) : (Main, nothing)
linetable = map(li -> Core.LineInfoNode(mod, meth, li.file, LineType(li.line), LineType(li.inlined_at)),
ir.lines)
IRCode(stmts, cfg, linetable, ir.blocks[1].argtypes, meta, sps)
end
else
IRCode(stmts, types, lines, flags, cfg, ir.lines, ir.blocks[1].argtypes, [], sps)
end
end
if VERSION >= v"1.6.0-DEV.272"
isgotoifnot(@nospecialize(ex)) = (@assert !isexpr(ex, :gotoifnot); ex isa Core.GotoIfNot)
destruct_gotoifnot(@nospecialize(ex)) = Any[ex.cond, ex.dest]
isreturn(@nospecialize(ex)) = (@assert !isexpr(ex, :return); ex isa ReturnNode)
retval(@nospecialize(ex)) = ex.val
else
isgotoifnot(@nospecialize(ex)) = isexpr(ex, :gotoifnot)
destruct_gotoifnot(@nospecialize(ex)) = ex.args
isreturn(@nospecialize(ex)) = isexpr(ex, :return)
retval(@nospecialize(ex)) = ex.args[1]
end
function blockstarts(ci::CodeInfo)
bs = Int[]
terminator = false
for i = 1:length(ci.code)
ex = ci.code[i]
if isgotoifnot(ex)
_, dest = destruct_gotoifnot(ex)
push!(bs, dest)
terminator = true
elseif ex isa GotoNode || isreturn(ex)
ex isa GotoNode && push!(bs, ex.label)
i < length(ci.code) && push!(bs, i+1)
terminator = false
elseif terminator
push!(bs, i)
terminator = false
end
end
return sort(unique(bs))
end
# TODO more informative names, while avoiding clashes.
slotname(ci, s) = Symbol(:_, s.id)
function IR(ci::CodeInfo, nargs::Integer; meta = nothing)
bs = blockstarts(ci)
codelocs, linetable = @static if VERSION ≥ v"1.12.0-DEV.173"
def = isnothing(meta) ? :var"n/a" : meta.instance
N = length(ci.code)
codelocs = fill(0, N)
linetable = LineInfoNode[]
# NOTE: we could be faster about decoding here and support inlining?
for pc in 1:N
LI = Base.IRShow.buildLineInfoNode(ci.debuginfo, def, pc)
if !isempty(LI)
linode = first(LI) # ::Base.IRShow.LineInfoNode
push!(linetable, LineInfoNode(linode.file, linode.line))
codelocs[pc] = length(linetable)
end
end
codelocs, linetable
else
ci.codelocs, map(li -> LineInfoNode(li.file, li.line), ci.linetable)
end
ir = IR(linetable, meta = meta)
_rename = Dict()
rename(ex) = prewalk(ex) do x
haskey(_rename, x) && return _rename[x]
x isa Core.SlotNumber && return Inner.Slot(slotname(ci, x))
return x
end
for i = 1:nargs
_rename[Core.SlotNumber(i)] = argument!(ir)
end
for i = 1:length(ci.code)
i in bs && block!(ir)
ex = ci.code[i]
if ex isa Core.NewvarNode
continue
elseif @static if isdefined(Core.IR, :EnterNode); ex isa Core.IR.EnterNode else isexpr(ex, :enter) end
catch_dest = @static if isdefined(Core.IR, :EnterNode)
ex.catch_dest
else
ex.args[1]
end
enter_expr = Expr(:enter, findfirst(==(catch_dest), bs)+1)
isdefined(ex, :scope) && push!(enter_expr.args, ex.scope)
_rename[Core.SSAValue(i)] = push!(ir, enter_expr)
elseif ex isa GotoNode
branch!(ir, findfirst(==(ex.label), bs)+1)
elseif isgotoifnot(ex)
cond, dest = destruct_gotoifnot(ex)
branch!(ir, findfirst(==(dest), bs)+1,
unless = rename(cond))
elseif isreturn(ex)
return!(ir, rename(retval(ex)))
else
_rename[Core.SSAValue(i)] = push!(ir, IRTools.stmt(rename(ex), line = codelocs[i]))
end
end
return ir
end
function IR(meta::Meta; slots = false, prune = true)
ir = IR(meta.code, meta.nargs, meta = meta)
slots && return ir
ir = IRTools.ssa!(ir)
if prune
ir = ir |> IRTools.prune! |> IRTools.renumber
end
return ir
end
function IR(Ts::Type...; slots = false, prune = true)
m = IRTools.meta(Tuple{Ts...})
m == nothing && return
IR(m, slots = slots, prune = prune)
end
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 2037 | cond(c, t, f) = c ? t() : f()
allsuccs(ir, (id,chs)) =
union(map(b -> b.id, successors(block(ir, id))),
allsuccs.((ir,), chs)...)
function captures(ir, (id, chs), cs = Dict())
bl = block(ir, id)
captures.((ir,), chs, (cs,))
cs[id] = setdiff(union([cs[i] for (i, _) in chs]..., usages(bl)), definitions(bl))
return cs
end
function return_thunk(x)
ir = IR()
return!(ir, xcall(:getindex, argument!(ir), 1))
Expr(:lambda, ir, x)
end
function br_thunk(args...)
ir = IR()
self = argument!(ir)
return!(ir, xcall([xcall(:getindex, self, i) for i = 1:length(args)]...))
Expr(:lambda, ir, args...)
end
function functionalbranches!(bl, pr, labels)
if length(branches(bl)) == 1
br = branches(bl)[1]
if !isreturn(br)
r = push!(pr, Expr(:call, labels[br.block], br.args...))
empty!(branches(pr.to))
return!(pr, r)
end
else
@assert length(branches(bl)) == 2
f, t = branches(bl)
function brfunc(br)
isreturn(br) && return return_thunk(returnvalue(br))
isempty(arguments(br)) && return labels[br.block]
br_thunk(labels[br.block], arguments(br)...)
end
r = push!(pr, xcall(IRTools, :cond, f.condition, brfunc(t), brfunc(f)))
empty!(branches(pr.to))
return!(pr, r)
end
end
function _functional(ir, tree, vars = [], cs = captures(ir, tree))
id = tree[1]
bl = IR(block(ir, id))
labels = Dict()
labels[id] = self = id == 1 ? arguments(bl)[1] : argument!(bl, at = 1)
pr = Pipe(bl)
for (i, v) in enumerate(vars)
v′ = push!(pr, xcall(:getindex, self, i))
v isa Integer ? (labels[v] = v′) : substitute!(pr, v, substitute(pr, v′))
end
for _ in pr end
for t in reverse(tree[2])
bs = filter(id -> haskey(labels, id), allsuccs(ir, t))
λ = Expr(:lambda, _functional(ir, t, [bs..., cs[t[1]]...]),
map(b -> labels[b], bs)..., cs[t[1]]...)
labels[t[1]] = push!(pr, λ)
end
functionalbranches!(bl, pr, labels)
return finish(pr)
end
functional(ir) = _functional(explicitbranch!(ir), domtree(ir))
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 2336 | function fixup_blocks!(ir, n)
last = length(blocks(ir))
for bl in blocks(ir), i = 1:length(branches(bl))
br = branches(bl)[i]
if br.block > last
branches(bl)[i] = Branch(br, block = br.block + n - 1)
end
end
end
function inlinehere!(ir, line, source, args...)
source = merge_returns!(copy(source)) # TODO preserve type info
offset = length(blocks(ir.to))-1
env = Dict()
retvalue = nothing
rename(x::Variable) = env[x]
rename(x::Expr) = Expr(x.head, rename.(x.args)...)
rename(x::Statement) = stmt(x; expr=rename(x.expr), line=line)
rename(x) = x
for (name, arg) in zip(arguments(source), args)
env[name] = arg
end
for bl in blocks(source)
if bl.id != 1
block!(ir)
for (arg, T) in zip(arguments(bl), argtypes(bl))
env[arg] = blockargument!(ir, T)
end
end
for (v, st) in bl
env[v] = push!(ir, rename(st))
end
for br in branches(bl)
if isreturn(br)
retvalue = rename(returnvalue(br))
else
branch!(ir, br.block+offset, rename.(br.args)..., unless = rename(br.condition))
end
end
end
return retvalue
end
"""
inline(ir, location, source)
Replace the function call at `ir[location]` with the IR `source`. The inlined IR
will use the function arguments at `ir[location]` as its input.
```
julia> foo(x, y) = max(x, y)+1
julia> ir = @code_ir foo(1, 1)
1: (%1, %2, %3)
%4 = Main.max(%2, %3)
%5 = %4 + 1
return %5
julia> inline(ir, var(4), @code_ir(max(1,1)))
1: (%1, %2, %3)
%4 = %3 < %2
%5 = Base.ifelse(%4, %2, %3)
%6 = %5 + 1
return %6
```
"""
function inline(ir::IR, loc::Variable, source::IR)
pr = Pipe(ir)
startblock = 0
branches(pr) do br
if startblock != 0 && br.block > startblock
Branch(br, block = br.block + length(blocks(source)) - 1)
else
return br
end
end
for (v, st) in pr
if v === loc
startblock = length(blocks(pr.to))
fixup_blocks!(pr.to, length(blocks(source)))
# TODO: when inlining, we set all statements from source
# .... at the line from loc. Ideally, we use the `inlined_at` field.
line = ir[loc].line
ex = ir[loc].expr
delete!(pr, v)
v′ = inlinehere!(pr, line, source, ex.args...)
substitute!(pr, v, substitute(pr, v′))
end
end
return finish(pr)
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 9323 | struct CFG
graph::Vector{Vector{Int}}
end
function CFG(ir::IR)
graph = Vector{Int}[]
for b in blocks(ir)
push!(graph, Int[])
for c in successors(b)
push!(graph[end], c.id)
end
end
return CFG(graph)
end
Base.:(==)(a::CFG, b::CFG) = a.graph == b.graph
Base.length(c::CFG) = length(c.graph)
Base.getindex(c::CFG, b::Integer) = c.graph[b]
function Base.transpose(cfg::CFG)
cfg′ = CFG([Int[] for _ = 1:length(cfg)])
for i = 1:length(cfg), j in cfg[i]
push!(cfg′[j], i)
end
return cfg′
end
Base.adjoint(cfg::CFG) = transpose(cfg)
function definitions(b::Block)
defs = [Variable(i) for i = 1:length(b.ir.defs) if b.ir.defs[i][1] == b.id]
end
function usages(b::Block)
uses = Set{Variable}()
prewalk(b) do x
x isa Variable && push!(uses, x)
return x
end
return uses
end
function usecounts(ir::IR)
counts = Dict{Variable,Int}()
prewalk(ir) do x
x isa Variable && (counts[x] = get(counts, x, 0)+1)
return x
end
return counts
end
function dominators(cfg; entry = 1)
preds = cfg'
blocks = [1:length(cfg.graph);]
doms = Dict(b => Set(blocks) for b in blocks)
while !isempty(blocks)
b = popfirst!(blocks)
# We currently special case the first block here,
# since Julia sometimes creates blocks with no predecessors,
# which otherwise throw off the analysis.
ds = isempty(preds[b]) ? Set([b, entry]) :
push!(intersect([doms[c] for c in preds[b]]...), b)
if ds != doms[b]
doms[b] = ds
for c in cfg[b]
c in blocks || push!(blocks, c)
end
end
end
return doms
end
function domtree(cfg::CFG; entry = 1)
doms = dominators(cfg, entry = entry)
doms = Dict(b => filter(c -> b != c && b in doms[c], 1:length(cfg)) for b in 1:length(cfg))
children(b) = filter(c -> !(c in union(map(c -> doms[c], doms[b])...)), doms[b])
tree(b) = Pair{Int,Any}(b,tree.(children(b)))
tree(entry)
end
domtree(ir::IR; entry = 1) = domtree(CFG(ir), entry = entry)
function idoms(cfg; entry = 1)
ds = zeros(Int, length(cfg))
_idoms((a, bs)) = foreach(((b, cs),) -> (ds[b] = a; _idoms(b=>cs)), bs)
_idoms(domtree(cfg, entry = entry))
return ds
end
function domorder(ir, start = 1; full = false)
tree = domtree(CFG(ir), entry = start)
flatten((b,cs)) = vcat(b, flatten.(cs)...)
tree = flatten(tree)
if full
for b = 1:length(ir.blocks)
b in tree || push!(tree, b)
end
end
return tree
end
domorder!(ir::IR, start = 1) = permute!(ir, domorder(ir, start, full = true))
function verify(ir::IR)
@assert issorted(domorder(ir)) "Blocks are not in domtree order."
doms = dominators(ir)
# TODO check definitions within a block
for (b, ds) in doms
defs = union(definitions.(ds)...)
for x in setdiff(usages(b), defs)
error("Variable $x in block $(b.id) is not defined.")
end
end
return
end
function renumber(ir)
p = Pipe(ir)
for (v, st) in p
ex = st.expr
if isbits(ex) # Trivial expressions can be inlined
delete!(p, v)
substitute!(p, v, substitute(p, ex))
end
end
return finish(p)
end
function merge_returns!(ir)
bs = [b for b in blocks(ir) if isreturn(b)]
length(bs) == 1 && bs[1] == blocks(ir)[end] && return ir
block!(ir)
ret = argument!(blocks(ir)[end])
return!(ir, ret)
for b in bs
branches(b)[end] = branch(length(ir.blocks), arguments(branches(b)[end])[1])
end
return ir
end
function expand!(ir::IR)
worklist = blocks(ir)
spats = Dict(b => Dict() for b in blocks(ir))
while !isempty(worklist)
b = pop!(worklist)
b.id == 1 && continue
defs = definitions(b)
uses = usages(b)
for v in setdiff(uses, defs)
haskey(spats[b], v) && continue
spats[b][v] = argument!(b, v)
for c in predecessors(b)
c in worklist || push!(worklist, c)
end
end
ir.blocks[b.id] = prewalk(x -> get(spats[b], x, x), ir.blocks[b.id])
end
return ir
end
function prune!(ir::IR)
usages = usecounts(ir)
worklist = blocks(ir)
queue!(b) = (b in worklist || push!(worklist, b))
function rename!(env, ir)
for b in blocks(ir)
prewalk!(b) do x
haskey(env, x) || return x
foreach(queue!, successors(b))
env[x]
end
end
end
while !isempty(worklist)
b = popfirst!(worklist)
isempty(arguments(b)) && continue
brs = filter(br -> br.block == b.id, [br for a in blocks(ir) for br in branches(a)])
isempty(brs) && continue
# Redundant due to all inputs being the same
inputs = [setdiff(in, (a,)) for (a, in) in zip(arguments(b), zip(arguments.(brs)...))]
del = findall(x -> length(x) == 1, inputs)
rename = Dict(zip(arguments(b)[del], first.(inputs[del])))
if !isempty(rename)
deletearg!(b, del)
rename!(rename, ir)
end
# Redundant due to not being used
unused = findall(x -> get(usages, x, 0) == 0, arguments(b))
if !isempty(unused)
for a in predecessors(b)
for br in branches(a, b), i in unused
arguments(br)[i] isa Variable &&
(usages[arguments(br)[i]] -= 1)
end
a in worklist || push!(worklist, a)
end
deletearg!(b, unused)
end
end
return ir
end
struct CatchBranch
defs::Dict{Slot,Any}
v::Variable
end
function ssa!(ir::IR)
current = 1
defs = Dict(b => Dict{Slot,Any}() for b in 1:length(ir.blocks))
todo = Dict(b => Dict{Int,Vector{Slot}}() for b in 1:length(ir.blocks))
catch_branches = Dict{Int,Vector{CatchBranch}}()
handlers = Int[]
function reaching(b, slot)
haskey(defs[b.id], slot) && return defs[b.id][slot]
b.id == 1 && return undef
x = add_slot_argument!(b, slot)
return x
end
function add_slot_argument!(b, slot)
x = argument!(b, type = slot.type, insert = false)
if !haskey(defs[b.id], slot)
defs[b.id][slot] = x
end
for pred in predecessors(b)
if pred.id < current
for br in branches(pred, b)
push!(br.args, reaching(pred, slot))
end
else
push!(get!(Vector{Slot}, todo[pred.id], b.id), slot)
end
end
if haskey(catch_branches, b.id)
# for each 'catch' branch to this catch block (catch block has `length(predecessors(b)) == 0`),
# we try to find the dominating definition for slot v.
# defs[block(ir, cbr.v).id] contains the defs at the end of
# the block, so we use the cached defs in catch_branches instead.
for cbr in catch_branches[b.id]
# Get the definition for a slot from a given catch branch.
cbr_v = cbr.v
stmt = ir[cbr_v]
if haskey(cbr.defs, slot)
# Slot v was defined at catch branch
push!(stmt.expr.args, cbr.defs[slot])
else
# Find slot v definition from instruction cbr_v
cbr_b = block(ir, cbr_v)
if cbr_b.id == 1
push!(stmt.expr.args, undef)
continue
end
# there is already a def for this slot as an argument to the block
# but which was added after the catch branch.
if haskey(defs[cbr_b.id], slot) && defs[cbr_b.id][slot] isa Variable
bdef = defs[cbr_b.id][slot]
(def_b, loc) = ir.defs[bdef.id]
if def_b == cbr_b.id && loc < 0
push!(stmt.expr.args, bdef)
continue
end
end
# add an argument to cbr_b for slot
new_arg = add_slot_argument!(cbr_b, slot)
push!(stmt.expr.args, new_arg)
end
end
end
return x
end
function catchbranch!(v)
for handler in handlers
cbr = CatchBranch(copy(defs[current]), insertafter!(ir, v, Expr(:catch, handler)))
push!(get!(Vector{CatchBranch}, catch_branches, handler), cbr)
end
end
for b in blocks(ir)
current = b.id
rename(ex) = prewalk(x -> x isa Slot ? reaching(b, x) : x, ex)
for (v, st) in b
ex = st.expr
if isexpr(ex, :(=)) && ex.args[1] isa Slot
defs[b.id][ex.args[1]] = rename(ex.args[2])
catchbranch!(v)
delete!(ir, v)
elseif isexpr(ex, :enter)
push!(handlers, ex.args[1])
catchbranch!(v)
elseif isexpr(ex, :leave) && !haskey(catch_branches, current)
pop!(handlers)
else
ir[v] = rename(ex)
end
end
for i = 1:length(BasicBlock(b).branches)
BasicBlock(b).branches[i] = rename(BasicBlock(b).branches[i])
end
for (succ, ss) in todo[b.id], br in branches(b, succ)
append!(br.args, [reaching(b, v) for v in ss])
end
end
return ir
end
function reachable_blocks(cfg::CFG)
bs = Int[]
reaches(b) = b in bs || (push!(bs, b); reaches.(cfg[b]))
reaches(1)
return bs
end
function trimblocks!(ir::IR)
for b in sort(setdiff(1:length(blocks(ir)), reachable_blocks(CFG(ir))), rev = true)
deleteblock!(ir, b)
end
return ir
end
function inlineable!(ir)
pushfirst!(ir, Expr(:meta, :inline))
return ir
end
function log!(ir, msg)
pushfirst!(ir, xcall(Core, :println, msg))
return ir
end
totype(T::Type) = T
if isdefined(Core.Compiler, :PartialStruct)
totype(T::Core.Compiler.PartialStruct) = T.typ
end
function pis!(ir::IR)
for (v, st) in ir
ex = st.expr
ex isa PiNode || continue
ir[v] = xcall(Core, :typeassert, ex.val, totype(ex.typ))
end
return ir
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 1448 | # TODO: https://hal.inria.fr/inria-00558509v1/document
function liveness(ir)
result = Dict(v => Set{Variable}() for v in keys(ir))
result = merge(result, Dict(b.id => Set{Variable}() for b in blocks(ir)))
queue = WorkQueue(1:length(blocks(ir)))
while !isempty(queue)
b = block(ir, pop!(queue))
for br in branches(b)
foreach(x -> x isa Variable && push!(result[b.id], x), arguments(br))
br.condition isa Variable && push!(result[b.id], br.condition)
end
live = Set(result[b.id])
for v in reverse(keys(b))
delete!(live, v)
varmap(x -> push!(live, x), b[v])
union!(result[v], live)
end
setdiff!(live, arguments(b))
for a in predecessors(b)
isempty(setdiff(live, result[a.id])) && continue
union!(result[a.id], live)
push!(queue, a.id)
end
end
return result
end
function interference(liveness)
g = Graph{Variable}()
for set in liveness
set = collect(set)
for i = 1:length(set), j = i+1:length(set)
connect!(g, set[i], set[j])
end
end
return g
end
interference(ir::IR) = interference(values(liveness(ir)))
function colouring(g::Graph, pre = Dict())
nodes = sort(collect(keys(g)), by = x -> length(g[x]), rev = true)
colours = Dict(n => get(pre, n, -1) for n in nodes)
for n in nodes
colour = 1
while any(m -> colours[m] == colour, g[n])
colour += 1
end
colours[n] = colour
end
return colours
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 6316 | function reaching(c::CFG, i::Integer, rs = Int[]; ignore = Int[])
for j in c.graph[i]
j in rs && return rs
j in ignore && continue
push!(rs, j)
reaching(c, j, rs, ignore = ignore)
end
return rs
end
struct Simple
block::Int
next
end
Simple(n) = Simple(n, nothing)
struct Loop
inner
next
end
struct Multiple
inner::Vector{Any}
next
end
for T in [Simple, Loop, Multiple]
@eval Base.:(==)(a::$T, b::$T) = $(reduce((a, b) -> :($a&&$b), [:(a.$f == b.$f) for f in fieldnames(T)]))
end
function reaches_unique(rs)
rs = Dict(b => union(b, cs) for (b, cs) in rs)
others(b) = union([cs for (c, cs) in rs if b != c]...)
Dict(b => filter(c -> !any(rs -> c in rs, others(b)), cs) for (b, cs) in rs)
end
function reloop_loop(cfg::CFG, blocks, entry, done)
rs = Dict(b => reaching(cfg, b, ignore = done) for b in blocks)
body = filter(b -> any(e -> e in rs[b], entry), blocks)
next = setdiff(blocks, body)
Loop(reloop(cfg, blocks = body, entry = entry, done = union(done, entry)),
reloop(cfg, blocks = next, entry = union([intersect(cfg[b], next) for b in body]...), done = done))
end
function reloop(cfg::CFG; blocks = 1:length(cfg.graph), entry = [1], done = Int[])
(isempty(blocks) || isempty(entry)) && return
rs = Dict(b => reaching(cfg, b, ignore = done) for b in entry)
if length(entry) == 1 && entry[] ∉ rs[entry[]]
next = setdiff(blocks, entry[])
Simple(entry[],
reloop(cfg, blocks = next,
entry = intersect(cfg.graph[entry[]], blocks), done = done))
elseif all(b -> isempty(setdiff(entry, rs[b])), entry)
reloop_loop(cfg, blocks, entry, done)
elseif (rsu = reaches_unique(rs); !all(isempty, values(rsu)))
unique = filter(b -> !isempty(rsu[b]), entry)
inner = [reloop(cfg, blocks = union(b, rsu[b]), entry = [b], done = done) for b in unique]
next = setdiff(blocks, union([union(b, rsu[b]) for b in unique]...))
es = intersect(next, union(entry, reaching.((cfg,), unique)...))
Multiple(inner, reloop(cfg, blocks = next, entry = es, done = done))
else
reloop_loop(cfg, blocks, entry, done)
end
end
const indent = " "
printstructure(io::IO, ::Nothing, level) = nothing
function printstructure(io::IO, s::Simple, level)
println(io, indent^level, s.block)
printstructure(io, s.next, level)
end
_printstructure(io::IO, s, level) = printstructure(io, s, level)
function _printstructure(io::IO, s::Simple, level)
println(io, indent^level, "Simple:")
printstructure(io, s, level+1)
end
function printstructure(io::IO, s::Multiple, level)
println(io, indent^level, "Multiple:")
if length(s.inner) == 1
printstructure(io, s.inner[1], level+1)
else
for b in s.inner
_printstructure(io, b, level+1)
end
end
printstructure(io, s.next, level)
end
function printstructure(io::IO, s::Loop, level)
println(io, indent^level, "Loop:")
printstructure(io, s.inner, level+1)
printstructure(io, s.next, level)
end
function Base.show(io::IO, b::Union{Simple,Multiple,Loop})
println(io, "Structured CFG:")
printstructure(io, b, 0)
end
# AST Conversion
rename(env, ex) =
prewalk(x -> x isa Variable ? env[x] :
x isa Slot ? Symbol(x.id) :
x, ex)
entry(s::Simple) = [s.block]
entry(s::Loop) = entry(s.inner)
entry(s::Multiple) = union(entry.(s.inner)...)
entry(s::Nothing) = Int[]
struct ASTCtx
ir::IR
args::Dict{Variable,Symbol}
branches::Dict{Any,Any}
inline::Bool
end
function ast(cx::ASTCtx, b::Block)
usages = Dict()
prewalk(b) do x
x isa Variable && (usages[x] = get(usages, x, 0)+1)
x
end
exs = []
env = Dict{Any,Any}(cx.args)
for v in keys(b)
ex = b[v].expr
if cx.inline && get(usages, v, 0) == 1 && !(ex isa Slot) # TODO not correct
env[v] = rename(env, ex)
elseif get(usages, v, 0) == 0
isexpr(ex) && push!(exs, rename(env, ex))
else
tmp = gensym("tmp")
push!(exs, :($tmp = $(rename(env, ex))))
env[v] = tmp
end
end
return exs, env
end
ast(cx::ASTCtx, ::Nothing) = @q begin end
function ast(cx::ASTCtx, cfg::Simple)
b = block(cx.ir, cfg.block)
exs, env = ast(cx, b)
function nextblock(br)
if isreturn(br)
@q (return $(rename(env, returnvalue(br)));)
elseif haskey(cx.branches, br.block)
cx.branches[br.block] == :continue && cfg.next == nothing ? @q(begin end) :
@q ($(Expr(cx.branches[br.block]));)
elseif cfg.next isa Multiple && br.block in entry(cfg.next)
n = findfirst(i -> br.block in entry(i), cfg.next.inner)
ast(cx, cfg.next.inner[n])
elseif cfg.next isa Multiple && br.block in entry(cfg.next.next)
ast(cx, cfg.next.next)
elseif br.block in entry(cfg.next)
ast(cx, cfg.next)
else
@q begin end
end
end
@assert length(branches(b)) <= 2 "No more than 2 branches supported, currently."
ex = if length(branches(b)) == 1
@q begin
$(exs...)
$(nextblock(branches(b)[1]).args...)
end
else
@q begin
$(exs...)
if $(rename(env, branches(b)[1].condition))
$(nextblock(branches(b)[2]).args...)
else
$(nextblock(branches(b)[1]).args...)
end
end
end
cfg.next isa Multiple && (ex = @q ($(ex.args...); $(ast(cx, cfg.next.next).args...)))
return ex
end
function ast(cx::ASTCtx, cfg::Multiple)
error("Only structured control flow is currently supported.")
end
function ast(cx::ASTCtx, cfg::Loop)
for e in entry(cfg)
cx.branches[e] = :continue
end
for e in entry(cfg.next)
cx.branches[e] = :break
end
brs = branches(block(cx.ir, cfg.inner.block))
if length(brs) == 2 && brs[1].block in entry(cfg.next) && brs[2].block in entry(cfg.inner.next)
exs, env = ast(cx, block(cx.ir, cfg.inner.block))
cond = unblock(@q ($(exs...); $(rename(env, brs[1].condition))))
@q begin
while $cond
$(ast(cx, cfg.inner.next).args...)
end
$(ast(cx, cfg.next).args...)
end
else
@q begin
while true
$(ast(cx, cfg.inner).args...)
end
$(ast(cx, cfg.next).args...)
end
end
end
function reloop(ir::IR; inline = true)
ir = explicitbranch!(copy(ir))
cfg = reloop(CFG(ir))
args = Dict(v => Symbol(:arg, i) for (i, v) in enumerate(arguments(ir)))
ast(ASTCtx(ir, args, Dict(), inline), cfg)
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 2226 | # Find strongly connected components
function strongconnected(cfg; blocks = 1:length(cfg))
preorder = zeros(Int, length(cfg))
S, P = Int[], Int[]
C = Ref(0)
components = Vector{Int}[]
let # avoid boxing `search`
function search(v)
preorder[v] = (C[] += 1)
push!(S, v)
push!(P, v)
for w in cfg[v]
w in blocks || continue
if preorder[w] == 0
search(w)
elseif !any(c -> w in c, components)
while preorder[P[end]] > preorder[w] pop!(P) end
end
end
if P[end] == v
pop!(P)
pushfirst!(components, Int[])
while true
push!(components[1], pop!(S))
components[1][end] == v && break
end
end
end
for b in blocks
preorder[b] == 0 && search(b)
end
end
return components
end
struct Component
children::Vector{Union{Component,Int}}
end
blocks(c::Integer) = [c]
blocks(c::Component) = reduce(vcat, blocks.(c.children))
entries(c::Integer) = [c]
entries(c::Component) = entries(first(c.children))
function components(cfg::CFG; blocks = 1:length(cfg))
# Assume the first block is the entry.
cs = strongconnected(cfg, blocks = blocks[2:end])
Component([blocks[1],
[length(c) == 1 ? c[1] : components(cfg, blocks = sort(c)) for c in cs]...])
end
# Aaaargh
_union(xs...) = union(xs...)
_union() = []
function branchesto(cfg::CFG, cs, i)
c = cs.children[i]
valid = _union([entries(cs.children[j]) for j = 1:length(cs.children) if i != j]...)
preds = _union([cfg'[c] for c in blocks(c)]...)
forw = filter(next -> next < entries(c)[1] && next in valid, preds)
back = filter(next -> next > entries(c)[1] && next in valid, preds)
forw = isempty(forw) ? nothing : minimum(forw)
back = isempty(back) ? nothing : maximum(back)
forw, back
end
function stackify(cfg::CFG, cs::Component = components(cfg), forw = [], back = [])
entry = cs.children[1]
for (i, c) = enumerate(cs.children)
target = minimum(entries(c))
f, b = branchesto(cfg, cs, i)
f == nothing || push!(forw, entry=>target)
b == nothing || push!(back, b =>target)
c isa Component && stackify(cfg, c, forw, back)
end
return forw, back
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 6318 | struct CompileError
transform
args
err
end
struct Self end
const self = Self()
# S -> function signature
# I -> lambda index
# T -> environment type
struct Lambda{S,I,T}
data::T
end
Lambda{D,S}(data...) where {D,S} =
Lambda{D,S,typeof(data)}(data)
@inline Base.getindex(l::Lambda, i::Integer) = l.data[i]
Base.show(io::IO, l::Lambda) = print(io, "λ")
function Base.showerror(io::IO, err::CompileError)
println(io, "Error compiling @dynamo $(err.transform) on $(err.args):")
showerror(io, err.err)
end
function transform end
function refresh end
function fallthrough(args...)
Expr(:block,
Expr(:meta, :inline),
Expr(:call, [:(args[$i]) for i = 1:length(args)]...))
end
function lambdalift!(ir, S, I = ())
i = 0
for (v, st) in ir
isexpr(st.expr, :lambda) || continue
ir[v] = Expr(:call, Lambda{S,(I...,i+=1)}, st.expr.args[2:end]...)
end
return ir
end
function lambdaself!(ir, _self = self)
for (v, st) in ir
if isexpr(st.expr, :lambda)
push!(st.expr.args, _self)
λ = st.expr.args[1]
s = pushfirst!(λ, xcall(:getindex, arguments(λ)[1], length(st.expr.args)-1))
lambdaself!(λ, s)
else
ir[v] = prewalk(x -> x === self ? _self : x, st.expr)
end
end
return ir
end
function getlambda(ir, I)
isempty(I) && return ir
i = 0
for (v, st) in ir
isexpr(st.expr, :lambda) || continue
(i += 1) == I[1] && return getlambda(st.expr.args[1], Base.tail(I))
end
error("Something has gone wrong in IRTools; couldn't find lambda in IR")
end
# Used only for its CodeInfo
dummy(args...) = nothing
function dynamo(cache, world, f, args...)
try
# XXX: @dynamo should pass the world to the transform function, so that any
# IR look-ups are done in the correct world.
spoofed_world[] = world
ir = transform(f, args...)::Union{IR,Expr,Nothing}
catch e
rethrow(CompileError(f, args, e))
finally
spoofed_world[] = nothing
end
# TODO: how to set proper edges on the returned code info? we have to
# propagate the bounds from `methods_by_ftype`, but that lookup is
# done by `IRTools.meta` and is not available here.
ir isa Expr && return ir
ir == nothing && return fallthrough(args...)
ir = lambdaself!(ir)
cache[args] = ir
ir = lambdalift!(copy(ir), Tuple{f,args...})
if ir.meta isa Meta
m = ir.meta
ir = varargs!(m, ir)
argnames!(m, :args)
pushfirst!(m.code.slotnames, Symbol("#self#"))
else
m = @meta world dummy(1)
m === nothing && error("Error looking up metadata for $f")
m.code.method_for_inference_limit_heuristics = nothing
end
if isdefined(Base, :__has_internal_change) && Base.__has_internal_change(v"1.12-alpha", :codeinfonargs)
m.code.nargs = 2
m.code.isva = true
end
_self = splicearg!(ir)
prewalk!(x -> x === self ? _self : x, ir)
return update!(m.code, ir)
end
function dynamo_lambda(cache, world, f::Type{<:Lambda{S,I}}) where {S,I}
ir = cache[(S.parameters[2:end]...,)]
ir = getlambda(ir, I)
ir = lambdalift!(copy(ir), S, I)
closureargs!(ir)
m = @meta world dummy(1)
m.code.method_for_inference_limit_heuristics = nothing
if isdefined(Base, :__has_internal_change) && Base.__has_internal_change(v"1.12-alpha", :codeinfonargs)
m.code.nargs = 2
m.code.isva = true
end
return update!(m.code, ir)
end
unesc(x) = prewalk(x -> isexpr(x, :escape) ? x.args[1] : x, x)
function lifttype(x)
isexpr(x, :(::)) || return x
named = length(x.args) == 2
T = named ? x.args[2] : x.args[1]
T = :(Type{$T})
named ? Expr(:(::), x.args[1], T) : Expr(:(::), T)
end
const caches = Dict()
if VERSION >= v"1.10.0-DEV.873"
function dynamo_generator(world::UInt, source, self, args)
cache = if haskey(caches, self)
caches[self]
else
caches[self] = Dict()
end
ex = dynamo(cache, world, self, args...)
ex isa Core.CodeInfo && return ex
stub = Core.GeneratedFunctionStub(identity, Core.svec(:methodinstance, :args), Core.svec())
stub(world, source, ex)
end
function dynamo_lambda_generator(world::UInt, source, self, args)
f = self.parameters[1].parameters[1]
cache = caches[f]
ex = dynamo_lambda(cache, world, self)
ex isa Core.CodeInfo && return ex
stub = Core.GeneratedFunctionStub(identity, Core.svec(:methodinstance, :args), Core.svec())
stub(world, source, ex)
end
end
macro dynamo(ex)
@capture(shortdef(ex), (name_(args__) = body_) |
(name_(args__) where {Ts__} = body_)) ||
error("@dynamo needs a function definition.")
Ts = Ts == nothing ? [] : esc.(Ts)
f, T = isexpr(name, :(::)) ?
(length(name.args) == 1 ? (esc(gensym()), esc(name.args[1])) : esc.(name.args)) :
(esc(gensym()), :(Core.Typeof($(esc(name)))))
gendef = if VERSION >= v"1.10.0-DEV.873"
quote
function ($f::$T)($(esc(:args))...) where $(Ts...)
$(Expr(:meta, :generated, dynamo_generator))
$(Expr(:meta, :generated_only))
end
function (f::IRTools.Inner.Lambda{<:Tuple{<:$T,Vararg{Any}}})(args...) where $(Ts...)
$(Expr(:meta, :generated, dynamo_lambda_generator))
$(Expr(:meta, :generated_only))
end
end
else
quote
@generated function ($f::$T)($(esc(:args))...) where $(Ts...)
cache = if haskey($caches, $T)
$caches[$T]
else
$caches[$T] = Dict()
end
return IRTools.dynamo(cache, nothing, $f, args...)
end
@generated function (f::IRTools.Inner.Lambda{<:Tuple{<:$T,Vararg{Any}}})(args...) where $(Ts...)
cache = $caches[$T]
return IRTools.Inner.dynamo_lambda(cache, nothing, f)
end
end
end
quote
$(isexpr(name, :(::)) || esc(:(function $name end)))
function IRTools.transform(::Type{<:$T}, $(esc.(lifttype.(args))...)) where $(Ts...)
$(esc(body))
end
$gendef
IRTools.refresh(::$T) where $(Ts...) = (Core.eval($__module__, $(QuoteNode(unesc(gendef)))); return)
end
end
macro code_ir(dy, ex)
@capture(ex, f_(args__)) || error("@code_dynamo f(x...)")
:(transform(typeof($(esc(dy))), meta($typesof($(esc(f)), $(esc.(args)...)))))
end
# TODO could support lambdas
function recurse!(ir, to = self)
for (x, st) in ir
isexpr(st.expr, :call) || continue
ir[x] = Expr(:call, to, st.expr.args...)
end
return ir
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 5046 | using Core: CodeInfo, Typeof
using Core.Compiler: InferenceState, MethodInstance, svec
using InteractiveUtils: typesof
if isdefined(Base, :hasgenerator) # VERSION >= v"1.7.0"
hasgenerator(x) = Base.hasgenerator(x)
else
hasgenerator(x) = Base.isgenerated(x)
end
worldcounter() = ccall(:jl_get_world_counter, UInt, ())
isprecompiling() = ccall(:jl_generating_output, Cint, ()) == 1
struct Meta
method::Method
instance::MethodInstance
code::CodeInfo
nargs::Int
sparams
end
function Base.show(io::IO, meta::Meta)
print(io, "Metadata for ")
print(io, meta.method)
end
# Workaround for what appears to be a Base bug
untvar(t::TypeVar) = t.ub
untvar(x) = x
const spoofed_world = Ref{Union{Nothing,UInt}}(nothing)
"""
meta(Tuple{...})
Construct metadata for a given method signature. Metadata can then be used to
construct [`IR`](@ref) or used to perform other reflection on the method.
See also [`@meta`](@ref).
julia> IRTools.meta(Tuple{typeof(gcd),Int,Int})
Metadata for gcd(a::T, b::T) where T<:Union{Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8} in Base at intfuncs.jl:31
"""
function meta(T; types = T, world=nothing)
if world === nothing
# if the user didn't specify a world, use the current world,
# or a spoofed world if we're executing a dynamo
world = something(spoofed_world[], worldcounter())
end
F = T.parameters[1]
F == typeof(invoke) && return invoke_meta(T; world = world)
F isa DataType && (F.name.module === Core.Compiler ||
F <: Core.Builtin ||
F <: Core.Builtin) && return nothing
min_world = Ref{UInt}(typemin(UInt))
max_world = Ref{UInt}(typemax(UInt))
has_ambig = Ptr{Int32}(C_NULL) # don't care about ambiguous results
_methods = if VERSION >= v"1.7.0-DEV.1297"
Base._methods_by_ftype(T, #=mt=# nothing, #=lim=# -1,
world, #=ambig=# false,
min_world, max_world, has_ambig)
else
Base._methods_by_ftype(T, #=lim=# -1,
world, #=ambig=# false,
min_world, max_world, has_ambig)
end
_methods === nothing && return nothing
_methods isa Bool && return nothing
length(_methods) == 0 && return nothing
type_signature, sps, method = last(_methods)
sps = svec(map(untvar, sps)...)
@static if VERSION >= v"1.2-"
mi = Core.Compiler.specialize_method(method, types, sps)
ci = hasgenerator(mi) ? get_staged(mi, world) : Base.uncompressed_ast(method)
else
mi = Core.Compiler.code_for_method(method, types, sps, world, false)
ci = hasgenerator(mi) ? get_staged(mi, world) : Base.uncompressed_ast(mi)
end
Base.Meta.partially_inline!(ci.code, [], method.sig, Any[sps...], 0, 0, :propagate)
Meta(method, mi, ci, method.nargs, sps)
end
function invoke_tweaks!(ci::CodeInfo)
if VERSION >= v"1.10.0-DEV.870" && ci.slottypes !== nothing
ci.slottypes = [typeof(invoke), ci.slottypes[1], Type, ci.slottypes[2:end]...]
end
ci.slotnames = [:invoke, ci.slotnames[1], :T, ci.slotnames[2:end]...]
ci.slotflags = [0x00, ci.slotflags[1], 0x00, ci.slotflags[2:end]...]
ci.code = map(ci.code) do x
prewalk(x) do x
x isa SlotNumber ? SlotNumber(x.id == 1 ? 2 : x.id+2) : x
end
end
end
function invoke_meta(T; world)
F = T.parameters[2]
A = T.parameters[3]::Type{<:Type{<:Tuple}}
S = T.parameters[4:end]
T = Tuple{F,A.parameters[1].parameters...}
S = Tuple{F,S...}
m = meta(T, types = S, world = world)
invoke_tweaks!(m.code)
return Meta(m.method, m.instance, m.code, m.nargs+2, m.sparams)
end
"""
@meta [world] f(args...)
Convenience macro for retrieving metadata without writing a full type signature.
julia> IRTools.@meta gcd(10, 5)
Metadata for gcd(a::T, b::T) where T<:Union{Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8} in Base at intfuncs.jl:31
"""
macro meta(ex...)
if length(ex) == 1
world = nothing
call = ex[1]
elseif length(ex) == 2
world, call = ex
else
error("@meta [world] f(args...)")
end
isexpr(call, :call) || error("@meta [world] f(args...)")
f, args = call.args[1], call.args[2:end]
:(meta(typesof($(esc.((f, args...))...)); world=$(esc(world))))
end
function code_ir(f, T)
m = meta(Tuple{Typeof(f),T.parameters...})
return IR(m)
end
function code_irm(ex)
if isexpr(ex, :call)
f, args = ex.args[1], ex.args[2:end]
elseif isexpr(ex, :do)
f, args = ex.args[1].args[1], vcat(ex.args[2], ex.args[1].args[2:end])
else
error("@code_ir f(args...)")
end
:($code_ir($(esc(f)), typesof($(esc.(args)...))))
end
"""
@code_ir f(args...)
Convenience macro similar to `@code_lowered` or `@code_typed`. Retrieves the IR
for the given function call.
julia> @code_ir gcd(10, 5)
1: (%1, %2, %3)
%4 = %2 == 0
br 4 unless %4
2: ...
"""
macro code_ir(ex)
code_irm(ex)
end
codeinfo(m::Meta) = m.code
function argnames!(meta, names...)
meta.code.slotnames = [names...]
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 4730 | struct Slot
id::Symbol
type
end
Slot(id) = Slot(id, Any)
function Base.show(io::IO, s::Slot)
print(io, "@", s.id)
s.type != Any && print(io, "::", s.type)
end
phislot(b, i) = Slot(Symbol(:phi_, b, :_, i))
# TODO: handle undef arguments properly.
function slots!(ir::IR)
slots = Dict()
for b in blocks(ir)
# Block arguments
if b.id != 1
for (i, var) in enumerate(BasicBlock(b).args)
slots[var] = phislot(b.id, i)
end
empty!(BasicBlock(b).args)
empty!(BasicBlock(b).argtypes)
end
# Catch branches
for (v, st) in b
isexpr(st.expr, :catch) || continue
target = st.expr.args[1]
args = st.expr.args[2:end]
for (i, val) in enumerate(args)
insert!(b, v, :($(phislot(target, i)) = $val))
end
delete!(b, v)
end
# Branches
for br in BasicBlock(b).branches
isreturn(br) && continue
for (i, val) in enumerate(br.args)
ϕ = phislot(br.block, i)
push!(b, :($ϕ = $val))
end
empty!(br.args)
end
end
return varmap(x -> get(slots, x, x), ir)
end
using Core.Compiler: CodeInfo, SlotNumber
function slots!(ci::CodeInfo)
ss = Dict{Slot,SlotNumber}()
for i = 1:length(ci.code)
function f(x)
x isa Slot || return x
haskey(ss, x) && return ss[x]
@static if VERSION >= v"1.10.0-DEV.870"
push!(ci.slottypes, x.type)
end
push!(ci.slotnames, x.id)
push!(ci.slotflags, 0x00)
ss[x] = SlotNumber(length(ci.slotnames))
end
if VERSION >= v"1.6.0-DEV.272"
ci.code[i] = MacroTools.prewalk(ci.code[i]) do x
x isa Core.ReturnNode ? (isdefined(x,:val) ? Core.ReturnNode(f(x.val)) : x) :
x isa Core.GotoIfNot ? Core.GotoIfNot(f(x.cond), x.dest) :
f(x)
end
else
ci.code[i] = MacroTools.prewalk(f, ci.code[i])
end
end
return ci
end
function varargs!(meta, ir::IR, n = 0)
isva = meta.method.isva
argTs = ir.blocks[1].argtypes
Ts = Core.Compiler.widenconst.(argTs[n+1:end])
typed = !all(T -> T==Any, Ts)
allTs = !isva ?
Any[argTs[1:n]..., Tuple{Ts...}] :
Any[argTs[1:n]..., typed ? Tuple{Ts[1:end-1]...,Ts[end].parameters...} : Any]
args = copy(ir.blocks[1].args)
deletearg!(ir, length(allTs)+1:length(args))
empty!(argTs); append!(argTs, allTs)
argmap = Dict{Variable,Any}()
argis = 1:(length(Ts))
newargs = map(reverse(argis)) do i
argmap[args[i+n]] = pushfirst!(ir, Statement(nothing, type = Ts[i]))
end |> reverse
ir = varmap(x -> get(argmap, x, x), ir)
for i in argis
if isva && i == length(argis)
i = length(Ts)
xs, T = arguments(ir)[end], argTs[end]
for _ = 1:i-1
T = typed ? Tuple{T.parameters[2:end]...} : Any
st = Statement(xcall(Base, :tail, xs), type = T)
xs = insertafter!(ir, xs, st)
end
ir[newargs[i]] = xcall(:identity, xs)
else
ir[newargs[i]] = xcall(Base, :getfield, arguments(ir)[end], i)
end
end
return ir
end
function closureargs!(ir::IR)
args = arguments(ir)[2:end]
deletearg!(ir, 2:length(arguments(ir)))
argtuple = argument!(ir)
env = Dict()
for (i, a) in reverse(collect(enumerate(args)))
env[a] = pushfirst!(ir, xcall(:getindex, argtuple, i))
end
prewalk!(x -> get(env, x, x), ir)
return ir
end
# TODO this is hacky and leaves `ir.defs` incorrect
function splicearg!(ir::IR)
args = arguments(ir)
push!(ir.defs, (1, -1))
arg = var(length(ir.defs))
pushfirst!(args, arg)
pushfirst!(ir.blocks[1].argtypes, Any)
return arg
end
@static if VERSION >= v"1.10.0-DEV.870"
function replace_code_newstyle!(ci, ir, _)
isnothing(ci.slottypes) && (ci.slottypes = Any[])
return Core.Compiler.replace_code_newstyle!(ci, ir)
end
elseif VERSION < v"1.8.0-DEV.267"
function replace_code_newstyle!(ci, ir, n_argtypes)
return Core.Compiler.replace_code_newstyle!(ci, ir, n_argtypes-1)
end
else
using Core.Compiler: replace_code_newstyle!
end
@static if VERSION >= v"1.10.0-DEV.870"
function get_staged(mi, world)
return Core.Compiler.get_staged(mi, world)
end
else
function get_staged(mi, _)
return Core.Compiler.get_staged(mi)
end
end
function update!(ci::CodeInfo, ir::Core.Compiler.IRCode)
replace_code_newstyle!(ci, ir, length(ir.argtypes))
@static if VERSION < v"1.12.0-DEV.15"
ci.inferred = false
end
ci.ssavaluetypes = length(ci.code)
slots!(ci)
fill!(ci.slotflags, 0)
return ci
end
function update!(ci::CodeInfo, ir::IR)
if ir.meta isa Meta
ci.method_for_inference_limit_heuristics = ir.meta.method
if isdefined(ci, :edges)
ci.edges = Core.MethodInstance[ir.meta.instance]
end
end
update!(ci, Core.Compiler.IRCode(slots!(ir)))
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 355 | using IRTools, Test
using IRTools: CFG, dominators, domtree
relu(x) = (y = x > 0 ? x : 0)
ir = @code_ir relu(1)
@test dominators(CFG(ir)) ==
Dict(1 => Set([1]), 2 => Set([1, 2]), 3 => Set([1, 3]), 4 => Set([1, 4]))
@test domtree(CFG(ir)) == (1 => [2 => [], 3 => [], 4 => []])
@test domtree(CFG(ir)', entry = 4) == (4 => [1 => [], 2 => [], 3 => []])
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 6817 | using IRTools, MacroTools, InteractiveUtils, Test
using IRTools: @dynamo, IR, meta, isexpr, xcall, self, insertafter!, recurse!,
argument!, return!, block!, branch!, func, var, functional
using InteractiveUtils: code_typed
@dynamo roundtrip(a...) = IR(a...)
@dynamo function passthrough(a...)
ir = IR(a...)
ir == nothing && return
recurse!(ir)
return ir
end
add(a, b) = a+b
@test roundtrip(add, 2, 3) == 5
@test passthrough(add, 2, 3) == 5
@test passthrough(sin, 1.0) == sin(1.0)
f_returnnode(::T) where {T} = T
@test passthrough(f_returnnode, 1) == Int
f_gotoifnot(::Val{x}) where {x} = x ? 1 : 0
@test passthrough(f_gotoifnot, Val(true)) == 1
@test @code_ir(passthrough, add(2, 3)) isa IR
IRTools.refresh(roundtrip)
add(a, b) = a*b
@test roundtrip(add, 2, 3) == 6
relu(x) = x > 0 ? x : 0
@test roundtrip(relu, 1) == 1
@test passthrough(relu, 1) == 1
foo(x) = y = x > 0 ? x + 1 : x - 1
@test roundtrip(foo, 1) == 2
@test roundtrip(foo, -1) == -2
@test passthrough(foo, 1) == 2
@test passthrough(() -> [1, 2, 3]) == [1, 2, 3]
function err(f)
try
f()
catch e
e
end
end
@test passthrough(err, () -> 2+2) == 4
@test passthrough(err, () -> 0//0) isa ArgumentError
function err2(f)
x = 1
y = 1
try
y = f()
catch e
x, y
end
x, y
end
@test passthrough(err2, () -> 2+2) == (1, 4)
@test passthrough(err2, () -> 0//0) == (1, 1)
function err3(f)
y = 1
try
y = f()
catch
end
return y
end
@test passthrough(err3, () -> 2+2) == 4
@test passthrough(err3, () -> 0//0) == 1
@dynamo function mullify(a...)
ir = IR(a...)
ir == nothing && return
ir = MacroTools.prewalk(ir) do x
x isa GlobalRef && x.name == :(*) && return GlobalRef(Base, :+)
return x
end
for (x, st) in ir
isexpr(st.expr, :call) || continue
ir[x] = xcall(Main, :mullify, st.expr.args...)
end
return ir
end
@test mullify(prod, [5, 10]) == 15
@dynamo err(a...) = 0//0
@test_throws IRTools.Inner.CompileError err(+, 2, 3)
mutable struct Context
calls::Int
end
@dynamo function (cx::Context)(a...)
ir = IR(a...)
ir == nothing && return
recurse!(ir)
calls = pushfirst!(ir, xcall(:getfield, self, QuoteNode(:calls)))
calls = insertafter!(ir, calls, xcall(:+, calls, 1))
insertafter!(ir, calls, xcall(:setfield!, self, QuoteNode(:calls), calls))
return ir
end
@code_lowered Context(0)(add, 2, 3)
cx = Context(0)
@test cx(add, 2, 3.0) == 6
@test cx.calls > 5
ir = IR()
x = argument!(ir)
y = push!(ir, xcall(:*, x, x))
return!(ir, y)
@test IRTools.evalir(ir, 5) == 25
ir = IR()
x = argument!(ir)
y = argument!(ir)
z = push!(ir, xcall(:*, x, y))
return!(ir, z)
@test IRTools.evalir(ir, 5, 3) == 15
function pow(x, n)
r = 1
while n > 0
n -= 1
r *= x
end
return r
end
ir = @code_ir pow(2, 3)
ir[var(8)] = xcall(:+, var(5), var(2))
mul = func(ir)
@test mul(nothing, 10, 3) == 31
@dynamo function ir_add(_, _)
ir = IR()
args = argument!(ir)
x = push!(ir, xcall(:getindex, args, 1))
y = push!(ir, xcall(:getindex, args, 2))
return!(ir, xcall(:+, x, y))
end
@test ir_add(5, 2) == 7
@dynamo function test_lambda(x)
λ = IR()
self = argument!(λ)
y = argument!(λ)
x = push!(λ, xcall(:getindex, self, 1))
return!(λ, xcall(:+, x, y))
ir = IR()
args = argument!(ir)
x = push!(ir, xcall(:getindex, args, 1))
return!(ir, Expr(:lambda, λ, x))
end
let
f = test_lambda(3)
@test f(6) == 9
end
anf(f::Core.IntrinsicFunction, args...) = f(args...)
@dynamo function anf(args...)
ir = IR(args...)
ir == nothing && return
functional(recurse!(ir))
end
@test anf(pow, 2, 3) == 8
function f94(x)
i = x
while i > 0
i -= 1
end
return x
end
@test f94(1) == 1
@test passthrough(f94, 1) == 1
@testset "unreachable" begin
# 1: (%1)
# return nothing
# 2:
# unreachable
ir = IR()
argument!(ir)
return!(ir, nothing)
block!(ir)
branch!(ir, 0)
func_ir = IRTools.func(ir)
@test (code_typed(func_ir, Tuple{typeof(func_ir)}) |> only
isa Pair{Core.CodeInfo,DataType})
end
function f_try_catch(x)
y = 0.
try
y = sqrt(x)
catch
end
y
end
function f_try_catch2(x, cond)
local y
if cond
y = 2x
end
try
x = 3 * error()
catch
end
y
end
function f_try_catch3()
local x
try
error()
catch
x = 42
end
x
end
function f_try_catch4(x, cond)
local y
try
throw(x)
catch err
if cond
y = err + x
end
end
y
end
function f_try_catch5(x, cond)
local y
cond && (x = 2x)
try
y = x
cond && error()
catch
y = x + 1
end
y
end
function f_try_catch6(cond, y)
x = 1
if cond
y = 10y
else
y = 10y
end
try
cond && error()
catch
y = 2x
end
y+x
end
function f_try_catch7()
local x = 1.
for _ in 1:10
try
x = sqrt(x)
x -= 1.
catch
x = -x
end
x = x ^ 2
end
x
end
function f_try_catch8(x)
local z = x
try
z = z + sqrt(x)
z = 1 - log(z)
z = log(z)
catch
z = abs(z)
finally
return z
end
end
@testset "try/catch" begin
ir = @code_ir f_try_catch(1.)
fir = func(ir)
@test fir(nothing,1.) === 1.
@test fir(nothing,-1.) === 0.
ir = @code_ir f_try_catch2(1., false)
fir = func(ir)
# This should be @test_throws UndefVarError fir(nothing,42,false)
# See TODO in `IRTools.slots!`
@test_broken try
fir(nothing,42,false)
false
catch e
e isa UndefVarError
end
@test fir(nothing, 42, false) === IRTools.undef
@test fir(nothing, 42, true) === 84
ir = @code_ir f_try_catch3()
@test all(ir) do (_, stmt)
!IRTools.isexpr(stmt.expr, :catch) ||
length(stmt.expr.args) == 1
end
fir = func(ir)
@test fir(nothing) == 42
ir = @code_ir f_try_catch4(42, false)
fir = func(ir)
# This should be @test_throws UndefVarError fir(nothing,42,false)
@test_broken try
fir(nothing, 42, false)
false
catch e
e isa UndefVarError
end
@test fir(nothing, 42, false) === IRTools.undef
@test fir(nothing, 42, true) === 84
ir = @code_ir f_try_catch5(1, false)
fir = func(ir)
@test fir(nothing, 3, false) === 3
@test fir(nothing, 3, true) === 7
ir = @code_ir f_try_catch6(true, 1)
fir = func(ir)
@test fir(nothing, true, 1) === 3
@test fir(nothing, false, 1) === 11
ir = @code_ir f_try_catch7()
@test func(ir)(nothing) === 1.
ir = @code_ir f_try_catch8(1.)
fir = func(ir)
@test fir(nothing, 1.) == log(1. - log(2.))
@test fir(nothing, -1.) == 1.
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 1999 | using IRTools, Test
using IRTools: IR, @dynamo
function f(x)
N = 4
for i1 in 1:3 # single loop works without issue
for i2 in 1:N # needs to be a variable `1:4` works fine
end
end
0.0 # same error with `x`
end
@test @code_ir(f(1)) isa IR
function f(a, b)
u = 1
while true
if true
end
end
f(u)
end
@test @code_ir(f(1, 2)) isa IR
# issue 30
@dynamo function foo(a...)
ir = IR(a...)
return ir
end
mylog2(x) = ccall((:log2, Base.Math.libm), Float64, (Float64,), x)
@test foo(mylog2, 3.3) === mylog2(3.3)
bar(a, b) = a > b ? a : b
function foo(a, b)
bar(a, b)
end
let
ir1 = @code_ir foo(1, 2)
ir2 = @code_ir bar(1, 2)
inline_at = findfirst(ir1) do (_, stmt)
IRTools.isexpr(stmt.expr, :call) &&
stmt.expr.args[1] == GlobalRef(@__MODULE__, :bar)
end
@test inline_at !== nothing
ir = IRTools.inline(ir1, inline_at, ir2)
f = IRTools.func(ir)
@test f(nothing, 2, 3) == 3
@test f(nothing, 3, 2) == 3
end
function foo1(x)
while x < 10
x += 1
end
return x
end
function foo2(x)
if x < 100
x + foo1(x)
else
x
end
end
let
ir = @code_ir foo2(1)
ir2 = @code_ir foo1(1)
inline_at = findfirst(ir) do (_, stmt)
IRTools.isexpr(stmt.expr, :call) &&
stmt.expr.args[1] == GlobalRef(@__MODULE__, :foo1)
end
@test inline_at !== nothing
ir3 = IRTools.inline(ir, inline_at, ir2)
@test IRTools.func(ir3)(nothing, 2) == 12
@test IRTools.func(ir3)(nothing, 101) == 101
end
function foo1(x)
while x < 10
x += 1
end
return x
end
function foo2(x)
foo1(x)
x > 0 ? x : 0
end
let
ir = @code_ir foo2(1)
ir2 = @code_ir foo1(1)
inline_at = findfirst(ir) do (_, stmt)
IRTools.isexpr(stmt.expr, :call) &&
stmt.expr.args[1] == GlobalRef(@__MODULE__, :foo1)
end
@test inline_at !== nothing
ir3 = IRTools.inline(ir, inline_at, ir2)
@test IRTools.func(ir3)(nothing, 2) == foo2(2)
@test IRTools.func(ir3)(nothing, -2) == foo2(-2)
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 400 | using IRTools, Test
using IRTools: Meta, meta
@generated f(x) = :(x+x)
@test meta(Tuple{typeof(gcd),Int,Int}) isa Meta
@test meta(Tuple{typeof(f),Int}) isa Meta
# https://github.com/FluxML/IRTools.jl/issues/106
function g end
@test meta(Tuple{typeof(g),Int,Int}) === nothing
g(a) = 2a
@test meta(Tuple{typeof(g),Int,Int}) === nothing
@test @code_ir(map([1,2], [3,4]) do x, y
x + y
end) isa IR
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 1317 | using IRTools, Test
using IRTools: @meta, IR, CFG, Simple, Loop, Multiple, reloop, explicitbranch!, stackify
relu(x) = (y = x > 0 ? x : 0)
relu_cfg = CFG(@code_ir relu(1))
@test relu_cfg == CFG([[3,2],[4],[4],[]])
@test reloop(relu_cfg) == Simple(1, Multiple([Simple(3), Simple(2)], Simple(4)))
@test sort.(stackify(relu_cfg)) == ([1=>2,1=>3,1=>4],[])
function pow(x, n)
r = 1
while n > 0
n -= 1
r *= x
end
return r
end
pow_cfg = CFG(@code_ir pow(2, 3))
@test pow_cfg == CFG([[2],[4,3],[2],[]])
@test reloop(pow_cfg) == Simple(1, Loop(Simple(2, Simple(3)), Simple(4)))
@test sort.(stackify(pow_cfg)) == ([1=>2,1=>4,2=>3],[3=>2])
# AST recovery
relu(x) = (y = x > 0 ? x : 0)
ir = explicitbranch!(IR(@meta(relu(1)), slots = true))
ex = reloop(ir)
@test eval(:(let arg2 = 5; $ex; end)) == 5
@test eval(:(let arg2 = -5; $ex; end)) == 0
relu(x) = x > 0 ? x : 0
ir = explicitbranch!(IR(@meta(relu(1)), slots = true))
ex = reloop(ir)
@test eval(:(let arg2 = 5; $ex; end)) == 5
@test eval(:(let arg2 = -5; $ex; end)) == 0
ir = explicitbranch!(IR(@meta(pow(1,1)), slots = true))
ex = reloop(ir)
@test eval(:(let arg2 = 5, arg3 = 3; $ex; end)) == 125
ir = explicitbranch!(IR(@meta(gcd(1,1)), slots = true))
ex = reloop(ir)
@test eval(:(let arg2 = 85, arg3 = 391; $ex; end)) == gcd(85, 391)
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | code | 427 | using IRTools, Documenter, Test
@testset "IRTools" begin
@testset "IR" begin
include("ir.jl")
end
@testset "Analysis" begin
include("analysis.jl")
end
@testset "Reflection" begin
include("reflection.jl")
end
@testset "Compiler" begin
include("compiler.jl")
end
@testset "Relooper" begin
include("relooper.jl")
end
if Base.GIT_VERSION_INFO.tagged_commit # skip doctests on nightly
doctest(IRTools)
end
end
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | docs | 1608 | # IRTools
[](https://travis-ci.org/FluxML/IRTools.jl)
[](https://fluxml.github.io/IRTools.jl/latest/)
[](https://codecov.io/gh/FluxML/IRTools.jl)
IRTools aims to provide a simple and flexible IR format, expressive enough to work with both lowered and typed Julia code, as well as external IRs. It can be used with Julia metaprogramming tools such as [Cassette](https://github.com/jrevels/Cassette.jl).
```julia
julia> using IRTools
julia> function pow(x, n) # A simple Julia function
r = 1
while n > 0
n -= 1
r *= x
end
return r
end
julia> ir = @code_ir pow(1, 1) # Get its IR
1: (%1, %2, %3)
br 2 (%3, 1)
2: (%4, %5)
%6 = %4 > 0
br 4 unless %6
br 3
3:
%7 = %4 - 1
%8 = %5 * %2
br 2 (%7, %8)
4:
return %5
julia> using IRTools: var, xcall
julia> ir[var(8)] = xcall(:+, var(5), var(2)) # Tweak it
:(%5 + %2)
julia> ir
1: (%1, %2, %3)
br 2 (%3, 1)
2: (%4, %5)
%6 = %4 > 0
br 4 unless %6
br 3
3:
%7 = %4 - 1
%8 = %5 + %2
br 2 (%7, %8)
4:
return %5
julia> f = IRTools.func(ir); # Turn the new IR into a lambda
julia> f(nothing, 10, 5)
51
julia> @code_llvm f(nothing, 10, 5)
define i64 @"julia_##399_17438"(i64, i64) {
top:
%2 = icmp slt i64 %1, 1
%3 = mul i64 %1, %0
%4 = add i64 %3, 1
%value_phi1.lcssa = select i1 %2, i64 1, i64 %4
ret i64 %value_phi1.lcssa
}
```
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | docs | 8201 | # Dynamo
IRTools can be used with metaprogramming tools like [Cassette](https://github.com/jrevels/Cassette.jl), but it also provides a few of its own utilities. The main one is named the "dynamo" after the idea of a "dynamically-scoped macro".
Let me explain. If you write down
```julia
@foo begin
bar(baz())
end
```
then the `@foo` macro has access to the expression `bar(baz())` and can modify this however it pleases. However, the code of the functions `bar` and `baz` are completely invisible; in more technical terms the macro has lexical extent.
In contrast, a dynamo looks like this:
```julia
foo() do
bar(baz())
end
```
This can *also* freely modify the `bar(baz())` expression (though it sees it as an `IR` object rather than `Expr`). But more importantly, it can *recurse*, viewing and manipulating the source code of `bar` and `baz` and even any functions *they* call. In other words, it has dynamic extent.
For example, imagine a macro for replacing `*` with `+`:
```julia
julia> using MacroTools
julia> macro foo(ex)
MacroTools.prewalk(ex) do x
x == :* ? :+ : x
end |> esc
end
@foo (macro with 1 method)
julia> @foo 10*5
15
julia> @foo prod([5, 10])
50
```
The explicit `*` that appears to the macro gets changed, but the implicit one inside `prod` does not. This guide shows you how to do one better.
## A Simple Dynamo
The simplest possible dynamo is a no-op, analagous to the macro
```julia
macro roundtrip(ex)
esc(ex)
end
```
Here it is:
```jldoctest main
julia> using IRTools: IR, @dynamo
julia> @dynamo roundtrip(a...) = IR(a...)
julia> mul(a, b) = a*b
mul (generic function with 1 method)
julia> roundtrip(mul, 2, 3)
6
```
Here's how it works: our dynamo gets passed a set of *argument types* `a...`. We can use this to get IR for the method being called, with `IR(a...)`. Then we can transform that IR, return it, and it'll be compiled and run as usual.
In this case, we can easily check that the transformed code produced by `roundtrip` is identical to the original IR for `mul`.
```jldoctest main
julia> using IRTools: @code_ir
julia> @code_ir mul(2, 3)
1: (%1, %2, %3)
%4 = %2 * %3
return %4
julia> @code_ir roundtrip mul(1, 2)
1: (%1, %2, %3)
%4 = %2 * %3
return %4
```
Now we can recreate our `foo` macro. It's a little more verbose since simple symbols like `*` are resolved to `GlobalRef`s in lowered code, but it's broadly the same as our macro.
```@meta
DocTestSetup = quote
using IRTools
using IRTools: @dynamo, IR
mul(a, b) = a * b
end
```
```jldoctest main2
julia> using MacroTools, IRTools
julia> using IRTools: @dynamo, IR
julia> @dynamo function foo(a...)
ir = IR(a...)
ir = MacroTools.prewalk(ir) do x
x isa GlobalRef && x.name == :(*) && return GlobalRef(Base, :+)
return x
end
return ir
end
```
```@meta
DocTestSetup = nothing
```
It behaves identically, too.
```jldoctest main2
julia> foo() do
10*5
end
15
julia> foo() do
prod([10, 5])
end
50
```
To get different behaviour we need to *go deeper* – and talk about recursion.
## Recursing
A key difference between macros and dynamos is that dynamos get passed *functions* with they look inside, rather than expressions, so we don't need to write out `mul` when calling `foo(mul, 5, 10)`.
So what if `foo` actually inserted calls to itself when modifying a function? In other words, `prod([1, 2, 3])` would become `foo(prod, [1, 2, 3])`, and so on for each call inside a function. This lets us get the "dynamic extent" property that we talked about earlier.
```jldoctest main2
julia> using IRTools: xcall
julia> @dynamo function foo2(a...)
ir = IR(a...)
ir == nothing && return
ir = MacroTools.prewalk(ir) do x
x isa GlobalRef && x.name == :(*) && return GlobalRef(Base, :+)
return x
end
for (x, st) in ir
isexpr(st.expr, :call) || continue
ir[x] = xcall(foo2, st.expr.args...)
end
return ir
end
```
There are two changes here: firstly, walking over all IR statements to look for, and modify, `call` expressions. Secondly we handle the case where `ir == nothing`, which can happen when we hit things like intrinsic functions for which there is no source code. If we return `nothing`, the dynamo will just run that function as usual.
Check it does the transform we wanted:
```julia
julia> mul_wrapped(a, b) = mul(a, b)
mul_wrapped (generic function with 1 method)
julia> @code_ir mul_wrapped(5, 10)
1: (%1, %2, %3)
%4 = mul(%2, %3)
return %4
julia> @code_ir foo2 mul_wrapped(5, 10)
1: (%1, %2, %3)
%4 = (foo2)(mul, %2, %3)
return %4
```
And that it works as expected:
```jldoctest main2
julia> foo() do # Does not work (since there is no literal `*` here)
mul(5, 10)
end
50
julia> foo2() do # Works correctly
mul(5, 10)
end
15
julia> foo2() do
prod([5, 10])
end
15
```
This, we have rewritten the `prod` function to actually calculate `sum`, by *internally* rewriting all calls to `*` to instead use `+`.
## Using Dispatch
We can make our `foo2` dynamo simpler in a couple of ways. Firstly, IRTools provides a built-in utility `recurse!` which makes it easy to recurse into code.
```jldoctest main
julia> using MacroTools
julia> using IRTools: recurse!
julia> @dynamo function foo2(a...)
ir = IR(a...)
ir == nothing && return
ir = MacroTools.prewalk(ir) do x
x isa GlobalRef && x.name == :(*) && return GlobalRef(Base, :+)
return x
end
recurse!(ir)
return ir
end
julia> foo2() do
prod([5, 10])
end
15
```
Secondly, unlike in a macro, we don't actually need to look through source code for literal references to the `*` function. Because our dynamo is a normal function, we can actually use dispatch to decide what specific functions should do.
```jldoctest main
julia> foo3(::typeof(*), a, b) = a+b
foo3 (generic function with 1 method)
julia> foo3(*, 5, 10)
15
```
Now we can define a simpler version of `foo3` which *only* recurses, and let dispatch figure out when to turn `*`s into `+`s.
```jldoctest main
julia> @dynamo function foo3(a...)
ir = IR(a...)
ir == nothing && return
recurse!(ir)
return ir
end
julia> foo3() do
prod([5, 10])
end
15
```
## Contexts
We can achieve some interesting things by making our dynamo a *closure*, i.e. a callable object capable of holding some state. For example, consider an object which simply records a count.
```jldoctest counter
julia> mutable struct Counter
count::Int
end
julia> Counter() = Counter(0)
Counter
julia> count!(c::Counter) = (c.count += 1)
count! (generic function with 1 method)
```
We can turn this into a dynamo which inserts a single statement into the IR of each function, to increase the count by one.
```jldoctest counter
julia> using IRTools: @dynamo, IR, xcall, self, recurse!
julia> @dynamo function (c::Counter)(m...)
ir = IR(m...)
ir == nothing && return
recurse!(ir)
pushfirst!(ir, xcall(count!, self))
return ir
end
```
Now we can count how many function calls that happen in a given block of code.
```jldoctest counter
julia> c = Counter()
Counter(0)
julia> c() do
1 + 2.0
end
3.0
julia> c.count
18
```
!!! warning
On Julia versions older than 1.3, dynamos are _not_ automatically updated when you redefine functions. For example:
```julia
julia> @dynamo roundtrip(a...) = IR(a...)
julia> foo(x) = x^2
foo (generic function with 1 method)
julia> roundtrip(foo, 5)
25
julia> foo(x) = x+1
foo (generic function with 1 method)
julia> roundtrip(foo, 5)
25
```
In order to get the dynamo to see the new definition of `foo`, you can explicitly call `IRTools.refresh()`:
```julia
julia> IRTools.refresh(roundtrip)
julia> roundtrip(foo, 5)
6
```
With Julia 1.3 and later, `IRTools.refresh` is not required.
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | docs | 7810 | # IRTools
IRTools provides an IR format with several aims. The idea is to be:
* Expressive enough to represent all parts of Julia's IR pipeline, from lowered code to typed SSA IR;
* Easy to manipulate, like an AST, so that people can do powerful macro-like transformations of code;
* *safe* -- so no segfaults if you misplace an variable somewhere.
Note that before even attempting to understand IRTools, you should have a good handle on Julia's [metaprogramming and macros](https://docs.julialang.org/en/v1/manual/metaprogramming/).
## Reading the IR
### IR Basics
It's easiest to understand the IRTools IR by seeing some examples. We provide the macro `@code_ir` which behaves much like `@code_lowered`.
```jldoctest
julia> using IRTools
julia> f(x) = x+x
f (generic function with 1 method)
julia> @code_ir f(1)
1: (%1, %2)
%3 = %2 + %2
return %3
```
First things first. All variables are numbered (`%1`, `%2`, `%3` ...). IR will usually have a _lot_ of these, which is why numbers make more sense than names. At the start of the IR is a list of arguments that are provided as input to the function, `(%1, %2)`. You'll notice there's an extra argument, `%1`, that's ignored here; this represents the function `f` itself, which is used by callable objects and closures.
The main reason that there are a lot of intermediates is that, in IR, we only allow one function call per line. You can see how a nested Julia expression becomes a sequence of single instructions, kind of like an assembly language.
```jldoctest
julia> using IRTools
julia> f(x) = 3x*x + 2x + 1
f (generic function with 1 method)
julia> @code_ir f(1)
1: (%1, %2)
%3 = 3 * %2
%4 = %3 * %2
%5 = 2 * %2
%6 = %4 + %5 + 1
return %6
```
While this looks noisy and is at first a little hard to read, it's usually a helpful thing to do. IR is largely designed to be read by programs, rather than by humans, where it's usually easier to look at one instruction at a time.
Beyond that, this is essentially just very verbosely-written Julia code.
### Control Flow
The most significant difference between `IR` and `Expr` is how control flow is handled. There are no such thing as nested if statements, while loops and so on in IR, only *branches*.
```jldoctest
julia> using IRTools
julia> f(x) = x > 0 ? x : 0
f (generic function with 1 method)
julia> @code_ir f(1)
1: (%1, %2)
%3 = %2 > 0
br 2 unless %3
return %2
2:
return 0
```
The block labels `1:`, `2:` etc and the branch `br 2 unless %3` can be thought of as a version of `@label` and `@goto`. In this case the branch is conditional on the test `%3 = x > 0`; if that's true we'll skip the branch labeled `2` and return `x`.
IR is composed of a series of *basic blocks* that jump between each other like this. A basic block always starts with a label and ends with (optional) branches. No branches can appear in the middle of a basic block; that would just divide the block in two. Any structured control flow, however complex, can be turned into a series of blocks like this.
Here's a more interesting example.
```jldoctest
julia> using IRTools
julia> function f(x)
if x < 0
x = -x
end
return x
end
f (generic function with 1 method)
julia> @code_ir f(1)
1: (%1, %2)
%3 = %2 < 0
br 3 (%2) unless %3
br 2
2:
%4 = -%2
br 3 (%4)
3: (%5)
return %5
```
Basic blocks are actually like mini-functions, and they accept a series of arguments. In this case block `3` takes an argument called `%5` that tells it what to return. If you follow the branches as if they were function calls, you'll see that this IR behaves the same as the code we wrote down.
Why not just write this as `%2 = -%2`? It's important to understand that variables in SSA-form IR are *immutable*, in the same sense that variables in functional languages are. For this reason you'll never see a statement like `%2 = %2 + 1`. This again makes analysing IR programmatically a lot easier, because when code uses `%2` you know exactly which definition that refers to.
Loops work this way too: they are visible in the IR by branches that jump backwards, i.e. the `br 2` here. Variables that were modified inside the loop in the original code are explicitly passed between blocks.
```jldoctest envpow
julia> using IRTools
julia> function pow(x, n)
r = 1
while n > 0
n -= 1
r *= x
end
return r
end
pow (generic function with 1 method)
julia> @code_ir pow(1, 1)
1: (%1, %2, %3)
br 2 (%3, 1)
2: (%4, %5)
%6 = %4 > 0
br 4 unless %6
br 3
3:
%7 = %4 - 1
%8 = %5 * %2
br 2 (%7, %8)
4:
return %5
```
## Manipulating IR
### Statements
It's easy to get started by creating an empty fragment of IR.
```jldoctest ir_example
julia> using IRTools: IR, var, argument!, xcall
julia> ir = IR()
1:
```
We can push new statements into the IR. `push!` returns a variable name that we can reuse later on.
```jldoctest ir_example
julia> x = argument!(ir)
%1
julia> x2 = push!(ir, xcall(:*, x, x))
%2
julia> ir
1: (%1)
%2 = %1 * %1
```
The IR can be viewed as a mapping from variables to statements, and indexing and iteration are consistent with that.
```julia ir_example
julia> ir[var(2)]
IRTools.Statement(:(%1 * %1), Any, 0)
julia> collect(ir)
1-element Array{Any,1}:
%2 => IRTools.Statement(:(%1 * %1), Any, 0)
```
A `Statement` consists of an expression, a type (usually `Any` unless you're explicitly working with typed IR) and a line number. If you work directly with expressions IRTools will automatically wrap them with `Statement(x)`.
There are a few other functions that do obvious things: `pushfirst!`, `insert!`, `insertafter!`, and `delete!`.
In most cases you won't build IR from scratch, but will start from an existing function and modify its IR.
```jldoctest envpow
julia> ir = @code_ir pow(1, 1)
1: (%1, %2, %3)
br 2 (%3, 1)
2: (%4, %5)
%6 = %4 > 0
br 4 unless %6
br 3
3:
%7 = %4 - 1
%8 = %5 * %2
br 2 (%7, %8)
4:
return %5
```
### Blocks
You can work with a block at a time with `block(ir, n)` (all of them with `blocks(ir)`). Blocks similarly support functions like `push!`.
```jldoctest envpow
julia> using IRTools: block
julia> block(ir, 2)
2: (%4, %5)
%6 = %4 > 0
br 4 unless %6
br 3
```
## Evaluating IR
For testing purposes, you can run IR using `IRTools.evalir`.
```jldoctest eval
julia> using IRTools
julia> using IRTools: IR, argument!, return!, xcall, func
julia> ir = IR();
julia> x = argument!(ir);
julia> y = push!(ir, xcall(:*, x, x));
julia> return!(ir, y)
1: (%1)
%2 = %1 * %1
return %2
julia> IRTools.evalir(ir, 5)
25
```
More generally, you can turn an IR fragment into an anonymous function, useful
not just for evaluation but also to see the compiler's `@code_typed`,
`@code_llvm` output etc.
```julia
julia> f = func(ir)
##422 (generic function with 1 method)
julia> @code_typed f(5)
CodeInfo(
1 ─ %1 = Base.mul_int(@_2, @_2)::Int64
└── return %1
) => Int64
julia> @code_llvm f(5)
; @ /Users/mike/projects/flux/IRTools/src/eval.jl:18 within `##422'
define i64 @"julia_##422_17676"(i64) {
top:
; ┌ @ int.jl:54 within `*'
%1 = mul i64 %0, %0
ret i64 %1
; └
}
```
The same works for IR taken from existing functions.
```jldoctest
julia> using IRTools: IR, @code_ir, xcall, func, var
julia> function pow(x, n)
r = 1
while n > 0
n -= 1
r *= x
end
return r
end
pow (generic function with 1 method)
julia> ir = @code_ir pow(2, 3)
1: (%1, %2, %3)
br 2 (%3, 1)
2: (%4, %5)
%6 = %4 > 0
br 4 unless %6
br 3
3:
%7 = %4 - 1
%8 = %5 * %2
br 2 (%7, %8)
4:
return %5
julia> ir[var(8)] = xcall(:+, var(5), var(2))
:(%5 + %2)
julia> mul = func(ir);
julia> mul(nothing, 10, 3)
31
```
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.4.14 | 950c3717af761bc3ff906c2e8e52bd83390b6ec2 | docs | 734 | # API Reference
This page provides a comprehensive reference for IRTools functionality.
## Reflection
```@docs
@code_ir
IRTools.meta
IRTools.@meta
```
## IR Manipulation
```@docs
IRTools.IR
IRTools.Statement
IRTools.Variable
IRTools.Branch
IRTools.BasicBlock
IRTools.arguments
IRTools.argtypes
IRTools.branches
IRTools.isconditional
IRTools.isreturn
IRTools.returnvalue
IRTools.returntype
IRTools.canbranch
IRTools.explicitbranch!
IRTools.argument!
IRTools.emptyargs!
IRTools.deletearg!
IRTools.block!
IRTools.deleteblock!
IRTools.block
IRTools.blocks
IRTools.branch!
IRTools.return!
IRTools.successors
IRTools.predecessors
IRTools.inline
keys
haskey
push!
pushfirst!
insert!
IRTools.insertafter!
permute!
empty
IRTools.Pipe
```
| IRTools | https://github.com/FluxML/IRTools.jl.git |
|
[
"MIT"
] | 0.1.2 | f0de74163ea91daf9565c5b209506ce18a2d6d67 | code | 74880 |
module UnitRangesSortedSets
export AbstractUnitRangesSortedSet, AbstractUnitRangesSortedContainer, AbstractUnitRangesSortedSubSet
export UnitRangesSortedSet, VecUnitRangesSortedSet
export UnitRangesSortedSubSet, UnitRangesSortedSubSet1, UnitRangesSortedSubSet0
export searchsortedrange, searchsortedrangefirst, searchsortedrangelast
export getrange, getindex, beforefirstindex, pastlastindex
export subset
using Base: ForwardOrdering, Forward
const FOrd = ForwardOrdering
using DataStructures
using DataStructures: DataStructures.Tokens.IntSemiToken, DataStructures.SDMToken
safe_add(x::T, y) where {T} = x + T(y)
safe_add(x::T, y) where {T<:Integer} = ((z, flag) = Base.add_with_overflow(x, T(y)); !flag ? z : typemax(T))
safe_add(x::T, y) where {T<:AbstractChar} = (z = UInt64(x) + UInt64(y); z < UInt128(2)^(8 * sizeof(T)) ? T(z) : typemax(T))
safe_sub(x::T, y) where {T} = x - T(y)
safe_sub(x::T, y) where {T<:Integer} = ((z, flag) = Base.sub_with_overflow(x, T(y)); !flag ? z : typemin(T))
safe_sub(x::T, y) where {T<:AbstractChar} = (z = Int64(x) - Int64(y); z >= 0 ? T(z) : typemin(T))
@inline to_urange(::Type{TU}, l::L, r::L) where {TU<:UnitRange,L} =
TU(l, r)
@inline to_urange(::Type{TU}, l::L, r::R) where {TU<:UnitRange,L,R} =
TU(promote_type(L, R)(l), promote_type(L, R)(r))
@inline to_urange(::Type{TU}, kk::AbstractRange) where {TU<:UnitRange} =
TU(first(kk), last(kk))
@inline to_urange(::Type{TU}, l, r) where {TU<:StepRange{T,S}} where {T,S} =
TU(l, oneunit(S), r)
@inline to_urange(::Type{TU}, kk::AbstractRange) where {TU<:StepRange{T,S}} where {T,S} =
TU(first(kk), oneunit(S), last(kk))
@inline inferrangetype(::Type{K}) where {K<:Real} = UnitRange{K}
@inline function inferrangetype(::Type{K}) where K
T = typeof(K(0):K(0))
return T <: StepRange ? StepRange{K,UInt8} : T
end
abstract type AbstractUnitRangesSortedSet{K,TU} <: AbstractSet{TU} end
abstract type AbstractUnitRangesSortedContainer{K,TU} <: AbstractUnitRangesSortedSet{K,TU} end
abstract type AbstractUnitRangesSortedSubSet{K,TU,P} <: AbstractUnitRangesSortedSet{K,TU} end
"""
Sorted set of `UnitRange`s. Sorted in ascending order and no one range overlaps with another.
```julia
mutable struct UnitRangesSortedSet{K,TU} <: AbstractSet{TU}
"Index of last used range."
lastusedrangeindex::IntSemiToken
"Storage for ranges: the key of Dict is the `first(range)`, and the value of Dict is the `last(range)`."
ranges::SortedDict{K,K,FOrd}
end
```
Ranges stored in `SortedDict` as `first`s in keys and `last`s in values.
`UnitRangesSortedSet` can be created like the standard `Set`:
```julia
UnitRangesSortedSet(somecontainer)
```
for example
```julia
julia> using UnitRangesSortedSets
julia> UnitRangesSortedSet((1, 2, 4))
UnitRangesSortedSet{Int64} with 2 elements:
1:2
4:4
julia> UnitRangesSortedSet(('a':'z', 'α':'ω'))
UnitRangesSortedSet{Char} with 2 elements:
'a':'z'
'α':'ω'
julia> Random.seed!(1234);
julia> UnitRangesSortedSet(rand(1:20, 10))
UnitRangesSortedSet{Int64} with 6 elements:
5:5
7:8
10:11
15:16
18:18
20:20
```
or with `push!`:
```julia
julia> urs = UnitRangesSortedSet{Int}()
UnitRangesSortedSet{Int64}()
julia> push!(urs, 1)
UnitRangesSortedSet{Int64} with 1 element:
1:1
julia> push!(urs, 2)
UnitRangesSortedSet{Int64} with 1 element:
1:2
julia> push!(urs, 10:12)
UnitRangesSortedSet{Int64} with 2 elements:
1:2
10:12
```
Iterating over set of ranges:
```julia
julia> for r in urs @show(r) end
r = 1:2
r = 10:12
julia> for r in urs, i in r @show(i) end
i = 1
i = 2
i = 10
i = 11
i = 12
julia> for i in Iterators.flatten(urs) @show(i) end
i = 1
i = 2
i = 10
i = 11
i = 12
julia> collect(urs)
2-element Vector{UnitRange{Int64}}:
1:2
10:12
```
Deleting elements and ranges:
```julia
julia> delete!(urs, 10:11)
UnitRangesSortedSet{Int64} with 2 elements:
1:2
12:12
julia> delete!(urs, 1)
UnitRangesSortedSet{Int64} with 2 elements:
2:2
12:12
```
Note: for `Char` the `StepRange{Char,UInt8}` with `oneunit(UInt8)` step will be created.
"""
mutable struct UnitRangesSortedSet{K,TU} <: AbstractUnitRangesSortedContainer{K,TU}
"Index of last used range."
lastusedrangeindex::IntSemiToken
"Storage for ranges: the key of Dict is the `first(range)`, and the value of Dict is the `last(range)`."
ranges::SortedDict{K,K,FOrd}
end
function UnitRangesSortedSet{K,TU}() where {K,TU}
ranges = SortedDict{K,K,FOrd}(Forward)
UnitRangesSortedSet{K,TU}(beforestartsemitoken(ranges), ranges)
end
UnitRangesSortedSet{K}() where {K} = UnitRangesSortedSet{K,inferrangetype(K)}()
function UnitRangesSortedSet(rs::AbstractUnitRangesSortedSet{K,TU}) where {K,TU}
ranges = SortedDict{K,K,FOrd}(Forward)
for r in rs
ranges[first(r)] = last(r)
end
UnitRangesSortedSet{K,TU}(beforestartsemitoken(ranges), ranges)
end
"""
Sorted set of `UnitRange`s. Sorted in ascending order and no one range overlaps with another.
```julia
mutable struct VecUnitRangesSortedSet{K,TU} <: AbstractSet{TU}
"Index of last used range."
lastusedrangeindex::Int
"Storage for ranges starts,"
rstarts::Vector{K}
"and stops."
rstops::Vector{K}
end
```
Ranges stored in `Vector`s: in `rstarts` stored `first`s of ranges, and in `rstops` stored `last`s.
For further details see `UnitRangesSortedSet`.
"""
mutable struct VecUnitRangesSortedSet{K,TU} <: AbstractUnitRangesSortedContainer{K,TU}
"Index of last used range."
lastusedrangeindex::Int
"Storage for ranges starts,"
rstarts::Vector{K}
"and stops."
rstops::Vector{K}
end
VecUnitRangesSortedSet{K,TU}() where {K,TU} = VecUnitRangesSortedSet{K,TU}(0, Vector{K}(undef, 0), Vector{K}(undef, 0))
VecUnitRangesSortedSet{K}() where {K} = VecUnitRangesSortedSet{K,inferrangetype(K)}()
function VecUnitRangesSortedSet(rs::AbstractUnitRangesSortedSet{K,TU}) where {K,TU}
rstarts = Vector{K}(undef, length(rs))
rstops = Vector{K}(undef, length(rs))
for (i, r) in enumerate(rs)
rstarts[i] = first(r)
rstops[i] = last(r)
end
VecUnitRangesSortedSet{K,TU}(firstindex(rstarts) - 1, rstarts, rstops)
end
#
# SubSets
#
"""
It is possible to create the subset of any `AbstractUnitRangesSortedSet`, like a `view` for `Array`s:
```julia
julia> urs = UnitRangesSortedSet((1:2, 10:12))
UnitRangesSortedSet{Int64} with 2 elements:
1:2
10:12
julia> ss = subset(urs, 0:10)
2-element subset(UnitRangesSortedSet{Int64}, DataStructures.Tokens.IntSemiToken(3):DataStructures.Tokens.IntSemiToken(4)):
1:2
10:10
```
The `subset` object is an static, iterable view of the container
struct UnitRangesSortedSubSet{K, TU, P, Tix} <: AbstractUnitRangesSortedSubSet{K, TU, P}
"""
struct UnitRangesSortedSubSet{K,TU,P,Tix} <: AbstractUnitRangesSortedSubSet{K,TU,P}
"The `<:AbstractUnitRangesSortedSet` which subset point to."
parent::P
"`kstart:kstop` is the bounds of subset."
kstart::K
kstop::K
"Saved first range `parent[firstindex]` truncated to `kstart` from left."
firstrange::TU
"Saved last range `parent[lastindex]` truncated to `kstop` from right."
lastrange::TU
"Range `firstindex:lastindex` locates the indices diapason in `parent` where `kstart:kstop` should be inserted."
firstindex::Tix
lastindex::Tix
"Pre `firstindex` position, used for acceleration of `iterate`."
beforefirstindex::Tix
"Post `lastindex` position, used for acceleration of `iterate`."
pastlastindex::Tix
"Length of subset."
numranges::Int
end
"""
struct UnitRangesSortedSubSet1{K, TU, P, Tix} <: AbstractUnitRangesSortedSubSet{K, TU, P}
is like the `UnitRangesSortedSubSet` but with only one range or part of range in subset.
"""
struct UnitRangesSortedSubSet1{K,TU,P,Tix} <: AbstractUnitRangesSortedSubSet{K,TU,P}
"The `<:AbstractUnitRangesSortedSet` which subset point to."
parent::P
"`kstart:kstop` is the bounds of subset."
kstart::K
kstop::K
"Single continuous range `kstart:kstop` from `parent` stored for simplicity."
singlerange::TU
"Range `firstindex:lastindex` locates the point in `parent` where `kstart:kstop` should be inserted."
firstindex::Tix
lastindex::Tix
"Pre `firstindex` position, used for acceleration of `iteration`."
beforefirstindex::Tix
"Post `lastindex` position, used for acceleration of `iteration`."
pastlastindex::Tix
"Length of subset."
numranges::Int
end
"""
struct UnitRangesSortedSubSet0{K, TU, P, Tix} <: AbstractUnitRangesSortedSubSet{K, TU, P}
is like the `UnitRangesSortedSubSet` but with the zero-length subset range in subset.
"""
struct UnitRangesSortedSubSet0{K,TU,P,Tix} <: AbstractUnitRangesSortedSubSet{K,TU,P}
#"Empty range `kstart:kstop` for simplicity."
#singlerange::TU
"The `<:AbstractUnitRangesSortedSet` which subset point to."
parent::P
"`kstart:kstop` is the bounds of subset."
kstart::K
kstop::K
"Empty range `firstindex:lastindex` locates the point in `parent` where `kstart:kstop` should be inserted."
firstindex::Tix
lastindex::Tix
"Pre `firstindex` position, used for acceleration of `iteration`."
beforefirstindex::Tix
"Post `lastindex` position, used for acceleration of `iteration`."
pastlastindex::Tix
"Length of subset."
numranges::Int
end
subset(rs::P, ::Colon) where {P<:AbstractUnitRangesSortedSet{K,TU}} where {K,TU} =
subset(rs, to_urange(TU, first(first(rs)), last(last(rs))))
subset(rs::P, kk::AbstractRange) where {P<:AbstractUnitRangesSortedSubSet{K,TU}} where {K,TU} =
subset(rs.parent, to_urange(TU, max(first(first(rs)), K(first(kk))), min(last(last(rs)), K(last(kk)))))
function subset(rs::P, kk::AbstractRange) where {P<:AbstractUnitRangesSortedContainer{K,TU}} where {K,TU}
kk = to_urange(TU, kk)
iir_kk = searchsortedrange(rs, kk)
if length(kk) == 0 || length(iir_kk) == 0
if length(kk) == 0 && length(iir_kk) == 1
iir_kk = create_indexrange(rs, first(iir_kk), regress(rs, first(iir_kk)))
end
if length(kk) != 0
kk = to_urange(TU, last(kk), first(kk))
end
return UnitRangesSortedSubSet0{K,TU,P,typeof(first(iir_kk))}(rs, first(kk), last(kk), first(iir_kk), last(iir_kk),
regress(rs, first(iir_kk)), advance(rs, last(iir_kk)), length(iir_kk))
elseif length(iir_kk) == 1
singlerange = getindex(rs, first(iir_kk))
if first(singlerange) < first(kk)
singlerange = to_urange(TU, first(kk), last(singlerange))
end
if last(kk) < last(singlerange)
singlerange = to_urange(TU, first(singlerange), last(kk))
end
return UnitRangesSortedSubSet1{K,TU,P,typeof(first(iir_kk))}(rs, first(kk), last(kk), singlerange,
first(iir_kk), last(iir_kk), regress(rs, first(iir_kk)), advance(rs, last(iir_kk)), length(iir_kk))
else
firstrange = getindex(rs, first(iir_kk))
if first(firstrange) < first(kk)
firstrange = to_urange(TU, first(kk), last(firstrange))
end
lastrange = getindex(rs, last(iir_kk))
if last(kk) < last(lastrange)
lastrange = to_urange(TU, first(lastrange), last(kk))
end
return UnitRangesSortedSubSet{K,TU,P,typeof(first(iir_kk))}(rs, first(kk), last(kk), firstrange, lastrange,
first(iir_kk), last(iir_kk), regress(rs, first(iir_kk)), advance(rs, last(iir_kk)), length(iir_kk))
end
end
@inline Base.copy(rs::T) where {T<:AbstractUnitRangesSortedSubSet{K,TU}} where {K,TU} =
intersect(rs.parent, to_urange(TU, rs.kstart, rs.kstop))
@inline Base.parent(rs::T) where {T<:AbstractUnitRangesSortedSubSet{K,TU}} where {K,TU} = rs.parent
#
# Convert
#
(::Type{T})(values::Union{AbstractVector, AbstractSet, Tuple}) where {T<:AbstractUnitRangesSortedContainer} =
eltype(values) <: AbstractRange ? T{eltype(eltype(values))}(values) : T{eltype(values)}(values)
(::Type{T})(values::Union{AbstractVector, AbstractSet, Tuple}) where {T<:AbstractUnitRangesSortedContainer{K}} where {K} =
T{inferrangetype(K)}(values)
function (::Type{T})(values::Union{AbstractVector, AbstractSet, Tuple}) where {T<:AbstractUnitRangesSortedContainer{K,TU}} where {K,TU}
rs = T()
for r in values
push!(rs, r)
end
rs
end
Base.convert(::Type{<:VecUnitRangesSortedSet{K}}, rs::VecUnitRangesSortedSet{K}) where K = rs
Base.convert(::Type{<:UnitRangesSortedSet{K}}, rs::UnitRangesSortedSet{K}) where K = rs
function Base.convert(::Type{T}, rs::AbstractUnitRangesSortedContainer) where {T<:AbstractVector{Tv}} where {Tv<:AbstractRange}
V = T(undef, length(rs))
for (i, r) in enumerate(rs)
V[i] = to_urange(Tv, r)
end
V
end
function Base.convert(::Type{T}, rs::AbstractUnitRangesSortedContainer) where {T<:AbstractVector{Tv}} where {Tv}
V = T(undef, sum(length(r) for r in rs))
i = 0
for r in rs, v in r
V[i+=1] = Tv(v)
end
V
end
function Base.convert(::Type{T}, rs::AbstractUnitRangesSortedContainer{K,TU}) where {T<:AbstractVector,K,TU}
V = T{K}(undef, sum(length(r) for r in rs))
i = 0
for r in rs, v in r
V[i+=1] = K(v)
end
V
end
function Base.convert(::Type{T}, rs::AbstractUnitRangesSortedContainer) where {T<:AbstractSet{Tv}} where {Tv<:AbstractRange}
S = T()
for r in rs
push!(S, to_urange(Tv, r))
end
S
end
function Base.convert(::Type{T}, rs::AbstractUnitRangesSortedContainer) where {T<:AbstractSet{Tv}} where {Tv}
S = T()
for r in rs, v in r
push!(S, Tv(v))
end
S
end
function Base.convert(::Type{T}, rs::AbstractUnitRangesSortedContainer{K}) where {T<:AbstractSet,K}
S = T{K}()
for r in rs, v in r
push!(S, K(v))
end
S
end
"Type `UnitRange` for `DataStructures.Tokens.IntSemiToken`."
struct URSSIndexURange{P,Tix} <: AbstractUnitRange{Tix}
start::Tix
stop::Tix
parent::P
len::Int
end
"""
Returns `UnitRange` and `UnitRange`-alike ranges which are used for searching and indexing ranges in `AbstractUnitRangesSortedSet`.
Returned by `searchsorted()` function to point sought or missing ranges in given set.
The usual `searchsorted()` function returns just `UnitRange`, but `UnitRangesSortedSet` uses
`DataStructures.Tokens.IntSemiToken` to indexing keys/values and it is not possible to create `UnitRange{IntSemiToken}`,
thus was created custom one named `URSSIndexURange`.
"""
@inline create_indexrange(parent::P, l, r) where {P<:VecUnitRangesSortedSet} = UnitRange{Int}(l, r)
@inline create_indexrange(parent::P, l, r) where {P<:UnitRangesSortedSet} = URSSIndexURange(parent, l, r)
@inline function URSSIndexURange(rs::P, l::Tix, r::Tix) where {P<:VecUnitRangesSortedSet, Tix}
@boundscheck l < beforefirstindex(rs) || l > pastlastindex(rs) && return throw(BoundsError(rs, l))
@boundscheck r < beforefirstindex(rs) || r > pastlastindex(rs) && return throw(BoundsError(rs, r))
if l == pastlastindex(rs) ||
r == beforefirstindex(rs) ||
l > r
len = 0
else
len = r - l + 1
end
URSSIndexURange{P,Tix}(l, r, rs, len)
end
@inline function URSSIndexURange(rs::P, l::Tix, r::Tix) where {P<:UnitRangesSortedSet, Tix<:IntSemiToken}
@boundscheck status((rs.ranges, l)) == 0 && return throw(KeyError(l))
@boundscheck status((rs.ranges, r)) == 0 && return throw(KeyError(r))
if l == pastlastindex(rs) ||
r == beforefirstindex(rs) ||
compare(rs.ranges, l, r) == 1
len = 0
else
len = 0
i = l
while compare(rs.ranges, i, r) < 1
len += 1
i = advance(rs, i)
end
end
URSSIndexURange{P,Tix}(l, r, rs, len)
end
@inline Base.length(ur::URSSIndexURange) = ur.len
@inline Base.step(rs::URSSIndexURange) = 1
@inline Base.:(==)(l::URSSIndexURange{Pl,Tixl}, r::URSSIndexURange{Pr,Tixr}) where
{Pl<:UnitRangesSortedSet,Tixl,Pr<:VecUnitRangesSortedSet,Tixr} = false
@inline Base.:(==)(l::URSSIndexURange{Pl,Tixl}, r::URSSIndexURange{Pr,Tixr}) where
{Pl<:VecUnitRangesSortedSet,Tixl,Pr<:UnitRangesSortedSet,Tixr} = false
@inline Base.:(==)(l::URSSIndexURange{Pl,Tixl}, r::URSSIndexURange{Pr,Tixr}) where
{Pl<:VecUnitRangesSortedSet,Tixl,Pr<:VecUnitRangesSortedSet,Tixr} =
l.parent === r.parent &&
l.start == r.start &&
l.stop == r.stop
@inline Base.:(==)(l::URSSIndexURange{Pl,Tixl}, r::URSSIndexURange{Pr,Tixr}) where
{Pl<:UnitRangesSortedSet,Tixl,Pr<:UnitRangesSortedSet,Tixr} =
l.parent === r.parent &&
compare(l.parent.ranges, l.start, r.start) == 0 &&
compare(l.parent.ranges, l.stop, r.stop) == 0
@inline Base.first(ur::URSSIndexURange) = ur.start
@inline Base.last(ur::URSSIndexURange) = ur.stop
@inline Base.firstindex(ur::URSSIndexURange) = ur.start
@inline Base.lastindex(ur::URSSIndexURange) = ur.stop
#@inline Base.collect(ur::URSSIndexURange{P,Tix}) where {P<:VecUnitRangesSortedSet,Tix} =
# map(s->getindex(ur.parent, s), ur.start:ur.stop)
#@inline Base.collect(ur::URSSIndexURange{P,Tix}) where {P<:UnitRangesSortedSet,Tix} =
# map(s->getindex(ur.parent, s), onlysemitokens(inclusive(ur.parent.ranges, ur.start, ur.stop)))
@inline DataStructures.advance(ur::URSSIndexURange, st::IntSemiToken) = advance((ur.parent, st))
@inline DataStructures.regress(ur::URSSIndexURange, st::IntSemiToken) = regress((ur.parent, st))
@inline beforefirstindex(ur::URSSIndexURange) = beforestartsemitoken(ur.parent)
@inline pastlastindex(ur::URSSIndexURange) = pastendsemitoken(ur.parent)
Base.length(rs::VecUnitRangesSortedSet) = length(rs.rstarts)
Base.length(rs::UnitRangesSortedSet) = length(rs.ranges)
Base.length(rs::AbstractUnitRangesSortedSubSet) = rs.numranges
Base.haslength(rs::AbstractUnitRangesSortedSet) = true
Base.hasfastin(rs::AbstractUnitRangesSortedSet) = true
Base.isempty(rs::AbstractUnitRangesSortedSet) = length(rs) == 0
Base.size(rs::AbstractUnitRangesSortedSet) = (length(rs),)
#Base.axes(rs::AbstractUnitRangesSortedSet) = (Base.OneTo(rs.n),)
Base.eltype(::AbstractUnitRangesSortedSet{K,TU}) where {K,TU} = TU
#Base.IndexStyle(::AbstractUnitRangesSortedSet) = IndexLinear()
function Base.collect(::Type{ElType}, rs::AbstractUnitRangesSortedSet{K,TU}) where {ElType,K,TU}
T = inferrangetype(ElType)
res = Vector{T}(undef, length(rs))
i = 0
for r in rs
res[i+=1] = to_urange(T, ElType(first(r)), ElType(last(r)))
end
return res
end
function Base.collect(rs::AbstractUnitRangesSortedSet{K,TU}) where {K,TU}
res = Vector{TU}(undef, length(rs))
i = 0
for r in rs
res[i+=1] = to_urange(TU, r)
end
return res
end
@inline function indexcompare(rs::VecUnitRangesSortedSet, i, j)
if i < j
return -1
elseif i > j
return 1
else
return 0
end
end
@inline function indexcompare(rs::AbstractUnitRangesSortedSubSet{K,TU,P}, i, j) where {K,TU,P<:VecUnitRangesSortedSet}
if i < j
return -1
elseif i > j
return 1
else
return 0
end
end
@inline indexcompare(rs::UnitRangesSortedSet, i, j) = compare(rs.ranges, i, j)
@inline indexcompare(rs::AbstractUnitRangesSortedSubSet{K,TU,P}, i, j) where {K,TU,P<:UnitRangesSortedSet} =
compare(rs.parent.ranges, i, j)
@inline function getrange(rs::AbstractUnitRangesSortedSet{K,TU}, i) where {K,TU}
if in(i, rs)
return to_urange(TU, first(i), last(i))
else
return nothing
end
end
@inline getindex_tuple(rs::VecUnitRangesSortedSet, i) = (rs.rstarts[i], rs.rstops[i])
@inline getindex_tuple(rs::UnitRangesSortedSet, i::IntSemiToken) = tuple(deref((rs.ranges, i))...)
@inline getindex_tuple(rs::UnitRangesSortedSubSet0, i) = (r = getindex(rs, i); tuple(first(r), last(r)))
@inline getindex_tuple(rs::UnitRangesSortedSubSet1, i) = (r = getindex(rs, i); tuple(first(r), last(r)))
@inline getindex_tuple(rs::UnitRangesSortedSubSet, i) = (r = getindex(rs, i); tuple(first(r), last(r)))
@inline Base.getindex(rs::VecUnitRangesSortedSet{K,TU}, i) where {K,TU} =
to_urange(TU, rs.rstarts[i], rs.rstops[i])
@inline Base.getindex(rs::UnitRangesSortedSet{K,TU}, i::IntSemiToken) where {K,TU} =
to_urange(TU, deref((rs.ranges, i))...)
@inline Base.getindex(rs::UnitRangesSortedSet{K,TU}, t::SDMToken) where {K,TU} =
to_urange(TU, deref(t)...)
@inline Base.getindex(ur::URSSIndexURange, i::Integer) = _getindex(ur, i) # ambiguity
@inline Base.getindex(ur::URSSIndexURange, i::Colon) = _getindex(ur, i)
@inline Base.getindex(ur::URSSIndexURange, i::StepRange{T}) where {T<:Integer} = _getindex(ur, i)
@inline Base.getindex(ur::URSSIndexURange, i::AbstractUnitRange{T}) where {T<:Integer} = _getindex(ur, i)
@inline function _getindex(ur::URSSIndexURange, i)
@boundscheck indexcompare(ur.parent, first(ur), i) != 1 &&
indexcompare(ur.parent, i, last(ur)) != 1 || throw(BoundsError(ur, i))
getindex(ur.parent, i)
end
@inline Base.getindex(rs::UnitRangesSortedSubSet0{K,TU}, i) where {K,TU} =
(throw(BoundsError(rs)); to_urange(TU, rs.kstart, rs.kstop))
@inline function Base.getindex(rs::UnitRangesSortedSubSet1, i)
@boundscheck i == rs.firstindex || throw(BoundsError(rs, i))
rs.singlerange
end
@inline function Base.getindex(rs::UnitRangesSortedSubSet{K,TU,P}, i) where {K,TU,P<:VecUnitRangesSortedSet}
@boundscheck beforefirstindex(rs) < i < pastlastindex(rs) || throw(BoundsError(rs, i))
if i == rs.firstindex
return rs.firstrange
elseif i < rs.lastindex
return getindex(rs.parent, i)
else
return rs.lastrange
end
end
@inline function Base.getindex(rs::UnitRangesSortedSubSet, i)
@boundscheck indexcompare(rs.parent, rs.firstindex, i) != 1 &&
indexcompare(rs.parent, i, rs.lastindex) != 1 || throw(BoundsError(rs, i))
if indexcompare(rs, i, rs.firstindex) == 0
return rs.firstrange
elseif indexcompare(rs, i, rs.lastindex) == -1
return getindex(rs.parent, i)
else
return rs.lastrange
end
end
@inline getindex_rangestart(rs::VecUnitRangesSortedSet, i) = rs.rstarts[i]
@inline getindex_rangestop(rs::VecUnitRangesSortedSet, i) = rs.rstops[i]
@inline getindex_rangestart(rs::UnitRangesSortedSet, i) = deref_key((rs.ranges, i))
@inline getindex_rangestop(rs::UnitRangesSortedSet, i) = deref_value((rs.ranges, i))
@inline getindex_rangestart(rs::AbstractUnitRangesSortedSubSet, i) = first(getindex(rs, i))
@inline getindex_rangestop(rs::AbstractUnitRangesSortedSubSet, i) = last(getindex(rs, i))
@inline Base.firstindex(rs::VecUnitRangesSortedSet) = firstindex(rs.rstarts)
@inline Base.firstindex(rs::UnitRangesSortedSet) = startof(rs.ranges)
@inline Base.firstindex(rs::AbstractUnitRangesSortedSubSet) = rs.firstindex
@inline Base.lastindex(rs::VecUnitRangesSortedSet) = lastindex(rs.rstarts)
@inline Base.lastindex(rs::UnitRangesSortedSet) = lastindex(rs.ranges)
@inline Base.lastindex(rs::AbstractUnitRangesSortedSubSet) = rs.lastindex
"""
first(rs::AbstractUnitRangesSortedSet)
Returns first range from the set of ranges `rs`.
"""
@inline Base.first(rs::VecUnitRangesSortedSet{K,TU}) where {K,TU} =
to_urange(TU, rs.rstarts[1], rs.rstops[1])
@inline Base.first(rs::UnitRangesSortedSet{K,TU}) where {K,TU} =
to_urange(TU, deref((rs.ranges, startof(rs.ranges)))...)
@inline Base.first(rs::UnitRangesSortedSubSet0) = getindex(rs, firstindex(rs))
@inline Base.first(rs::UnitRangesSortedSubSet1) = rs.singlerange
@inline Base.first(rs::UnitRangesSortedSubSet) = getindex(rs, firstindex(rs))
"""
last(rs::AbstractUnitRangesSortedSet)
Returns last range from the set of ranges `rs`.
"""
@inline Base.last(rs::VecUnitRangesSortedSet{K,TU}) where {K,TU} =
to_urange(TU, rs.rstarts[end], rs.rstops[end])
@inline Base.last(rs::UnitRangesSortedSet{K,TU}) where {K,TU} =
to_urange(TU, deref((rs.ranges, lastindex(rs.ranges)))...)
@inline Base.last(rs::UnitRangesSortedSubSet0) = getindex(rs, lastindex(rs))
@inline Base.last(rs::UnitRangesSortedSubSet1) = rs.singlerange
@inline Base.last(rs::UnitRangesSortedSubSet) = getindex(rs, lastindex(rs))
@inline beforefirstindex(rs::VecUnitRangesSortedSet) = firstindex(rs.rstarts) - 1
@inline beforefirstindex(rs::UnitRangesSortedSet) = beforestartsemitoken(rs.ranges)
@inline beforefirstindex(rs::AbstractUnitRangesSortedSubSet) = rs.beforefirstindex
@inline pastlastindex(rs::VecUnitRangesSortedSet) = lastindex(rs.rstarts) + 1
@inline pastlastindex(rs::UnitRangesSortedSet) = pastendsemitoken(rs.ranges)
@inline pastlastindex(rs::AbstractUnitRangesSortedSubSet) = rs.pastlastindex
@inline DataStructures.advance(rs::VecUnitRangesSortedSet, state) = state + 1
@inline DataStructures.advance(rs::UnitRangesSortedSet, state) = advance((rs.ranges, state))
@inline DataStructures.advance(rs::AbstractUnitRangesSortedSubSet, state) = advance(rs.parent, state)
@inline DataStructures.regress(rs::VecUnitRangesSortedSet, state) = state - 1
@inline DataStructures.regress(rs::UnitRangesSortedSet, state) = regress((rs.ranges, state))
@inline DataStructures.regress(rs::AbstractUnitRangesSortedSubSet, state) = regress(rs.parent, state)
#
# Searching functions
#
"Returns index of range in which, or after, `k` is placed."
@inline searchsortedrangelast(rs::VecUnitRangesSortedSet{K}, k) where {K} = searchsortedlast(rs.rstarts, K(k); lt=<)
@inline searchsortedrangelast(rs::UnitRangesSortedSet{K}, k) where {K} = searchsortedlast(rs.ranges, K(k))
@inline searchsortedrangelast(rs::UnitRangesSortedSubSet0, k) = beforefirstindex(rs)
@inline searchsortedrangelast(rs::UnitRangesSortedSubSet1{K}, k) where {K} =
K(k) >= rs.kstart ? rs.firstindex : beforefirstindex(rs)
@inline searchsortedrangelast(rs::UnitRangesSortedSubSet{K,TU,P,Tix}, k) where {K,TU,P<:VecUnitRangesSortedSet,Tix} =
searchsortedlast(rs.parent.rstarts, K(k), rs.firstindex, rs.lastindex, Base.ord(isless, identity, false))
@inline function searchsortedrangelast(rs::UnitRangesSortedSubSet{K,TU,P,Tix}, k) where {K,TU,P<:UnitRangesSortedSet,Tix}
ir_k = searchsortedlast(rs.parent.ranges, K(k))
if compare(rs.parent.ranges, ir_k, beforefirstindex(rs)) == 1 && compare(rs.parent.ranges, ir_k, pastlastindex(rs)) == -1
return ir_k
else
return beforefirstindex(rs)
end
end
"Returns index of range in which, or before, `k` is placed."
@inline searchsortedrangefirst(rs::VecUnitRangesSortedSet{K}, k) where {K} = searchsortedfirst(rs.rstops, K(k); lt=isless)
@inline function searchsortedrangefirst(rs::UnitRangesSortedSet{K}, k) where {K}
ir_k = searchsortedrangelast(rs, K(k))
if ir_k != beforefirstindex(rs) && in(K(k), getindex(rs, ir_k))
return ir_k
else
return advance(rs, ir_k)
end
end
@inline searchsortedrangefirst(rs::UnitRangesSortedSubSet0, k) = pastlastindex(rs)
@inline searchsortedrangefirst(rs::UnitRangesSortedSubSet1{K}, k) where {K} = K(k) <= rs.kstop ? rs.lastindex : pastlastindex(rs)
@inline searchsortedrangefirst(rs::UnitRangesSortedSubSet{K,TU,P,Tix}, k) where {K,TU,P<:VecUnitRangesSortedSet,Tix} =
searchsortedfirst(rs.parent.rstops, K(k), rs.firstindex, rs.lastindex, Base.ord(isless, identity, false))
@inline function searchsortedrangefirst(rs::UnitRangesSortedSubSet{K,TU,P,Tix}, k) where {K,TU,P<:UnitRangesSortedSet,Tix}
ir_k = searchsortedrangelast(rs, K(k))
if ir_k != beforefirstindex(rs) && in(K(k), getindex(rs, ir_k))
return ir_k
else
return advance(rs, ir_k)
end
end
"Returns range of `rs` indexes which coincide or concluded in `kk` range."
@inline searchsortedrange(rs::AbstractUnitRangesSortedContainer, kk::AbstractRange) =
create_indexrange(rs, searchsortedrangefirst(rs, first(kk)), searchsortedrangelast(rs, last(kk)))
@inline searchsortedrange(rs::AbstractUnitRangesSortedSubSet, kk::AbstractRange) =
create_indexrange(rs.parent, searchsortedrangefirst(rs, first(kk)), searchsortedrangelast(rs, last(kk)))
"Returns indexes of range in `rs` in which `k` may be inserted. Or negative range in the case of `k` is
between `rs` ranges, and indices of resulted range is the indexes of that neighbors."
@inline function searchsortedrange(rs::AbstractUnitRangesSortedContainer{K}, k) where {K}
ir_k = searchsortedrangelast(rs, K(k))
if ir_k != beforefirstindex(rs) && in(K(k), getindex(rs, ir_k))
return create_indexrange(rs, ir_k, ir_k)
else
return create_indexrange(rs, advance(rs, ir_k), ir_k)
end
end
@inline index_status(rs::VecUnitRangesSortedSet, ir) = 0 <= ir <= length(rs)+1 ? 1 : 0
@inline index_status(rs::UnitRangesSortedSet, ir) = status((rs.ranges, ir))
@inline function Base.findfirst(pred::Function, rs::AbstractUnitRangesSortedSet)
for i in eachindex(rs)
pred(getindex(rs, i)) && return i
end
return nothing
end
Base.findall(pred::Function, rs::AbstractUnitRangesSortedSet) = collect(r for r in rs if pred(r))
#
# Iterators
#
@inline Base.iterate(rs::UnitRangesSortedSubSet0) = nothing
@inline Base.iterate(rs::UnitRangesSortedSubSet0, state) = nothing
@inline Base.iterate(rrs::Base.Iterators.Reverse{T}) where {T<:UnitRangesSortedSubSet0} = nothing
@inline Base.iterate(rrs::Base.Iterators.Reverse{T}, state) where {T<:UnitRangesSortedSubSet0} = nothing
@inline Base.iterate(rs::UnitRangesSortedSubSet1) = (rs.singlerange, 1)
@inline Base.iterate(rs::UnitRangesSortedSubSet1, state) = nothing
@inline Base.iterate(rrs::Base.Iterators.Reverse{T}) where {T<:UnitRangesSortedSubSet1} =
(rrs.itr.singlerange, 1)
@inline Base.iterate(rrs::Base.Iterators.Reverse{T}, state) where {T<:UnitRangesSortedSubSet1} = nothing
@inline Base.iterate(rs::AbstractUnitRangesSortedSubSet{K,TU,P}) where {K,TU,P<:VecUnitRangesSortedSet} =
(rs.firstrange, rs.firstindex + 1)
@inline function Base.iterate(rs::AbstractUnitRangesSortedSubSet{K,TU,P}, state) where {K,TU,P<:VecUnitRangesSortedSet}
if state < rs.lastindex
return (getindex(rs.parent, state), state + 1)
elseif state == rs.lastindex
return (rs.lastrange, state + 1)
else
return nothing
end
end
@inline function Base.iterate(rrs::Base.Iterators.Reverse{T}) where {T<:AbstractUnitRangesSortedSubSet{K,TU,P}} where
{K,TU,P<:VecUnitRangesSortedSet}
return (rrs.itr.lastrange, rrs.itr.lastindex - 1)
end
@inline function Base.iterate(rrs::Base.Iterators.Reverse{T}, state) where
{T<:AbstractUnitRangesSortedSubSet{K,TU,P}} where {K,TU,P<:VecUnitRangesSortedSet}
if rrs.itr.firstindex < state
return (getindex(rrs.itr.parent, state), state - 1)
elseif rrs.itr.firstindex == state
return (rrs.itr.firstrange, state - 1)
else
return nothing
end
end
@inline Base.iterate(rs::AbstractUnitRangesSortedSubSet{K,TU,P}) where {K,TU,P<:UnitRangesSortedSet} =
(rs.firstrange, advance((rs.parent.ranges, rs.firstindex)))
@inline function Base.iterate(rs::AbstractUnitRangesSortedSubSet{K,TU,P}, state) where {K,TU,P<:UnitRangesSortedSet}
if compare(rs.parent.ranges, state, rs.lastindex) == -1
return (getindex(rs.parent, state), advance((rs.parent.ranges, state)))
elseif compare(rs.parent.ranges, state, rs.lastindex) == 0
return (rs.lastrange, advance((rs.parent.ranges, state)))
else
return nothing
end
end
@inline function Base.iterate(rrs::Base.Iterators.Reverse{T}) where {T<:AbstractUnitRangesSortedSubSet{K,TU,P}} where
{K,TU,P<:UnitRangesSortedSet}
return (rrs.itr.lastrange, regress((rrs.itr.parent.ranges, rrs.itr.lastindex)))
end
@inline function Base.iterate(rrs::Base.Iterators.Reverse{T}, state) where
{T<:AbstractUnitRangesSortedSubSet{K,TU,P}} where {K,TU,P<:UnitRangesSortedSet}
if compare(rrs.itr.parent.ranges, rrs.itr.firstindex, state) == -1
return (getindex(rrs.itr.parent, state), regress((rrs.itr.parent.ranges, state)))
elseif compare(rrs.itr.parent.ranges, rrs.itr.firstindex, state) == 0
return (rrs.itr.firstrange, regress((rrs.itr.parent.ranges, state)))
else
return nothing
end
end
@inline function Base.iterate(rs::AbstractUnitRangesSortedSet, state = firstindex(rs))
if state != pastlastindex(rs)
return (getindex(rs, state), advance(rs, state))
else
return nothing
end
end
@inline function Base.iterate(rrs::Base.Iterators.Reverse{T}, state = lastindex(rrs.itr)) where {T<:AbstractUnitRangesSortedSet}
if state != beforefirstindex(rrs.itr)
return (getindex(rrs.itr, state), regress(rrs.itr, state))
else
return nothing
end
end
@inline function Base.iterate(ur::URSSIndexURange, state = (first(ur), 0))
st, i = state
if i < length(ur)
return (st, (advance(ur.parent, st), i + 1))
else
return nothing
end
end
@inline function eachindexiterate(rs::AbstractUnitRangesSortedSet, state = firstindex(rs))
if state != pastlastindex(rs)
return (state, advance(rs, state))
else
return nothing
end
end
@inline function eachindexiterate(rrs::Base.Iterators.Reverse{T}, state = lastindex(rrs.itr)) where {T<:AbstractUnitRangesSortedSet}
if state != beforefirstindex(rrs.itr)
return (state, regress(rrs.itr, state))
else
return nothing
end
end
struct EachIndexIterator{It}
itr::It
end
"`eachindex` iterator"
@inline eachindexiterator(itr) = EachIndexIterator(itr)
@inline function Base.iterate(it::EachIndexIterator, state...)
y = eachindexiterate(it.itr, state...)
if y !== nothing
return (y[1], y[2])
else
return nothing
end
end
Base.eltype(::Type{EachIndexIterator{It}}) where {It} = eltype(It)
Base.IteratorEltype(::Type{EachIndexIterator{It}}) where {It} = Base.HasEltype()
Base.IteratorSize(::Type{<:EachIndexIterator}) = Base.HasShape{1}()
Base.length(it::EachIndexIterator) = length(it.itr)
Base.size(it::EachIndexIterator) = (length(it.itr),)
Iterators.reverse(it::EachIndexIterator) = EachIndexIterator(Iterators.reverse(it.itr))
Base.eachindex(rs::VecUnitRangesSortedSet) = eachindex(rs.rstarts)
Base.eachindex(rs::UnitRangesSortedSet) = eachindexiterator(rs)
Base.eachindex(rs::T) where {T<:AbstractUnitRangesSortedSubSet} = eachindexiterator(rs)
Base.eachindex(rrs::Base.Iterators.Reverse{T}) where {T<:AbstractUnitRangesSortedSet} = Iterators.reverse(eachindex(rrs.itr))
# TODO: check for https://github.com/JuliaLang/julia/pull/43110/files
#
# Assignments
#
@inline Base.in(kk::AbstractRange, rs::AbstractUnitRangesSortedSet{K,TU}) where {K,TU} = _in(to_urange(TU, kk), rs)
@inline Base.in(kk::TU, rs::AbstractUnitRangesSortedSet{K,TU}) where {K,TU<:AbstractRange} = _in(kk, rs)
@inline function _in(kk::TU, rs::AbstractUnitRangesSortedSet{K,TU}) where {K,TU}
# fast check for cached range index
if (ir = rs.lastusedrangeindex) != beforefirstindex(rs)
if issubset(kk, getindex(rs, ir))
return true
end
end
# cached range' index miss (or index is not stored), thus try to search
iir_kk = searchsortedrange(rs, kk)
rs.lastusedrangeindex = last(iir_kk)
if length(iir_kk) != 1
return false
elseif issubset(kk, getindex(rs, first(iir_kk)))
return true
else
return false
end
end
@inline function Base.in(key, rs::AbstractUnitRangesSortedSet{K}) where K
k = K(key)
# fast check for cached range index
if (ir = rs.lastusedrangeindex) != beforefirstindex(rs)
r_start, r_stop = getindex_tuple(rs, ir)
if r_start <= k <= r_stop
return true
end
end
# cached range index miss (or index not stored), thus try search
ir_k = searchsortedrangelast(rs, k)
if ir_k != beforefirstindex(rs) # `k` is not before the start of first range
r_start, r_stop = getindex_tuple(rs, ir_k)
if k <= r_stop # is `k` inside of range
rs.lastusedrangeindex = ir_k
return true
end
end
rs.lastusedrangeindex = beforefirstindex(rs)
return false
end
@inline Base.in(kk::AbstractRange, su::UnitRangesSortedSubSet0) = false
@inline Base.in(key, su::UnitRangesSortedSubSet0) = false
@inline Base.in(kk::AbstractRange, su::UnitRangesSortedSubSet1{K,TU}) where {K,TU} = issubset(to_urange(TU, kk), su.singlerange)
@inline Base.in(kk::TU, su::UnitRangesSortedSubSet1{K,TU}) where {K,TU<:AbstractRange} = issubset(kk, su.singlerange)
@inline Base.in(key, su::UnitRangesSortedSubSet1{K}) where {K} = in(K(key), su.singlerange)
@inline Base.in(kk::AbstractRange, su::UnitRangesSortedSubSet{K,TU}) where {K,TU} = _in(to_urange(TU, kk), su)
@inline Base.in(kk::TU, su::UnitRangesSortedSubSet{K,TU}) where {K,TU<:AbstractRange} = _in(kk, su)
@inline function _in(kk::TU, su::UnitRangesSortedSubSet{K,TU,P}) where {K,TU,P<:VecUnitRangesSortedSet}
# bounds check
(su.kstart <= first(kk) <= last(kk) <= su.kstop) || return false
# fast check for cached range index
if (ir = su.parent.lastusedrangeindex) != beforefirstindex(su.parent) &&
su.firstindex <= first(ir) <= last(ir) <= su.lastindex
if issubset(kk, getindex(su, ir))
return true
end
end
# cached range' index miss (or index is not stored), thus try search
iir_kk = searchsortedrange(su, kk)
su.parent.lastusedrangeindex = last(iir_kk)
if length(iir_kk) != 1
return false
elseif issubset(kk, getindex(su, first(iir_kk)))
return true
else
return false
end
end
@inline function _in(kk::TU, su::UnitRangesSortedSubSet{K,TU}) where {K,TU}
# bounds check
issubset(kk, to_urange(TU, su.kstart, su.kstop)) || return false
iir_kk = searchsortedrange(su, kk)
su.parent.lastusedrangeindex = last(iir_kk)
if length(iir_kk) != 1
return false
elseif issubset(kk, getindex(su, first(iir_kk)))
return true
else
return false
end
end
@inline function Base.in(key, su::UnitRangesSortedSubSet{K}) where {K}
k = K(key)
# check outbound
(k < su.kstart || su.kstop < k) && return false
# fast check for cached range index
if (ir = su.parent.lastusedrangeindex) != beforefirstindex(su.parent) &&
indexcompare(su, su.firstindex, ir) < 1 &&
indexcompare(su, ir, su.lastindex) < 1
r_start, r_stop = getindex_tuple(su, ir)
if r_start <= k <= r_stop
return true
end
end
# cached range index miss (or index not stored), thus try search
ir_k = searchsortedrangelast(su, k)
if ir_k != beforefirstindex(su) # `k` is not before the start of first range
r_start, r_stop = getindex_tuple(su, ir_k)
if r_start <= k <= r_stop # is `k` inside of range
su.parent.lastusedrangeindex = ir_k
return true
end
end
su.parent.lastusedrangeindex = beforefirstindex(su.parent)
return false
end
function Base.push!(rs::VecUnitRangesSortedSet{K,TU}, II::Union{AbstractVector,AbstractSet,NTuple}) where {K,TU}
for r in II
push!(rs, r)
end
rs
end
@inline Base.push!(rs::VecUnitRangesSortedSet{K,TU}, kk::AbstractRange) where {K,TU} = _push!(rs, to_urange(TU, kk))
@inline Base.push!(rs::VecUnitRangesSortedSet{K,TU}, kk::TU) where {K,TU<:AbstractRange} = _push!(rs, kk)
function _push!(rs::VecUnitRangesSortedSet{K,TU}, kk::TU) where {K,TU}
if length(kk) == 0
return rs
elseif length(kk) == 1
push!(rs, first(kk))
return rs
end
rs.lastusedrangeindex = beforefirstindex(rs)
iir_kk = searchsortedrange(rs, kk)
# `kk` already exist in `rs` and the same as the corresponding range in `rs`, nothing to do
if length(iir_kk) == 1 && kk == getindex(rs, first(iir_kk))
return rs
# delete all inside `kk` ranged in `rs`
else
delete!(rs, kk)
end
# get neighbors pointers
# Note: the range will be zero-length, thus
# `first(iir_kk)` will be point to range in `rs` on right side to `kk` and
# `last(iir_kk)` will be point to range in `rs` on left side to `kk`.
iir_kk = searchsortedrange(rs, first(kk))
@boundscheck @assert iir_kk == searchsortedrange(rs, last(kk)) "FIXME: Something went wrong."
iir_kk_left = last(iir_kk)
iir_kk_right = first(iir_kk)
# `kk` is adjoined in both sides with `rs` ranges, thus join them all
if iir_kk_left != beforefirstindex(rs) && getindex_rangestop(rs, iir_kk_left) + 1 == first(kk) &&
iir_kk_right != pastlastindex(rs) && getindex_rangestart(rs, iir_kk_right) - 1 == last(kk)
rs.rstops[iir_kk_left] = getindex_rangestop(rs, iir_kk_right)
deleteat!(rs.rstarts, iir_kk_right)
deleteat!(rs.rstops, iir_kk_right)
# `kk` is adjoin with `rs` range on left side, thus append to left range
elseif iir_kk_left != beforefirstindex(rs) && getindex_rangestop(rs, iir_kk_left) + 1 == first(kk) &&
iir_kk_right != pastlastindex(rs) && getindex_rangestart(rs, iir_kk_right) - 1 != last(kk)
rs.rstops[iir_kk_left] = last(kk)
# `kk` is adjoin with `rs` range on right side, thus prepend to right range
elseif iir_kk_left != beforefirstindex(rs) && getindex_rangestop(rs, iir_kk_left) + 1 != first(kk) &&
iir_kk_right != pastlastindex(rs) && getindex_rangestart(rs, iir_kk_right) - 1 == last(kk)
rs.rstarts[iir_kk_right] = first(kk)
# `kk` is separate from both sides, insert it
elseif iir_kk_left != beforefirstindex(rs) && getindex_rangestop(rs, iir_kk_left) + 1 != first(kk) &&
iir_kk_right != pastlastindex(rs) && getindex_rangestart(rs, iir_kk_right) - 1 != last(kk)
insert!(rs.rstarts, iir_kk_right, first(kk))
insert!(rs.rstops, iir_kk_right, last(kk))
# `kk` is first range in `rs` and adjoin with range on right side, thus prepend `kk` to right range
elseif iir_kk_left == beforefirstindex(rs) &&
iir_kk_right != pastlastindex(rs) && getindex_rangestart(rs, iir_kk_right) - 1 == last(kk)
rs.rstarts[iir_kk_right] = first(kk)
# `kk` is separate first range in `rs`, insert it
elseif iir_kk_left == beforefirstindex(rs) &&
iir_kk_right != pastlastindex(rs) && getindex_rangestart(rs, iir_kk_right) - 1 != last(kk)
insert!(rs.rstarts, iir_kk_right, first(kk))
insert!(rs.rstops, iir_kk_right, last(kk))
# `kk` is last range in `rs` and adjoin with range on left side, thus append `kk` to left range
elseif iir_kk_left != beforefirstindex(rs) && getindex_rangestop(rs, iir_kk_left) + 1 == first(kk) &&
iir_kk_right == pastlastindex(rs)
rs.rstops[iir_kk_left] = last(kk)
# `kk` is separate last range in `rs`, insert it
elseif iir_kk_left != beforefirstindex(rs) && getindex_rangestop(rs, iir_kk_left) + 1 != first(kk) &&
iir_kk_right == pastlastindex(rs)
insert!(rs.rstarts, iir_kk_right, first(kk))
insert!(rs.rstops, iir_kk_right, last(kk))
# `rs` is empty
elseif iir_kk_left == beforefirstindex(rs) && iir_kk_right == pastlastindex(rs)
insert!(rs.rstarts, 1, first(kk))
insert!(rs.rstops, 1, last(kk))
else
throw(AssertionError("FIXME: Should be unreachable."))
end
return rs
end
function Base.push!(rs::UnitRangesSortedSet{K,TU}, II::Union{AbstractVector,AbstractSet,NTuple}) where {K,TU}
for r in II
push!(rs, r)
end
rs
end
@inline Base.push!(rs::UnitRangesSortedSet{K,TU}, kk::AbstractRange) where {K,TU} = _push!(rs, to_urange(TU, kk))
@inline Base.push!(rs::UnitRangesSortedSet{K,TU}, kk::TU) where {K,TU<:AbstractRange} = _push!(rs, kk)
function _push!(rs::UnitRangesSortedSet{K,TU}, kk::TU) where {K,TU}
if length(kk) == 0
return rs
elseif length(kk) == 1
push!(rs, first(kk))
return rs
end
rs.lastusedrangeindex = beforefirstindex(rs)
iir_kk = searchsortedrange(rs, kk)
# `kk` already exist in `rs` and the same as the corresponding range in `rs`, nothing to do
if length(iir_kk) == 1 && kk == getindex(rs, first(iir_kk))
return rs
# delete all inside `kk` ranged in `rs`
else
delete!(rs, kk)
end
# get neighbors pointers
# Note: the range will be zero-length, thus
# `first(iir_kk)` will be point to range in `rs` on right side to `kk` and
# `last(iir_kk)` will be point to range in `rs` on left side to `kk`.
iir_kk = searchsortedrange(rs, first(kk))
@boundscheck @assert iir_kk == searchsortedrange(rs, last(kk)) "FIXME: Something went wrong."
iir_kk_left = last(iir_kk)
iir_kk_right = first(iir_kk)
iir_kk_left_rangestop = iir_kk_left != beforefirstindex(rs) ? getindex_rangestop(rs, iir_kk_left) : K(0)
iir_kk_right_rangestart = iir_kk_right != pastlastindex(rs) ? getindex_rangestart(rs, iir_kk_right) : K(0)
#iir_kk_left_rangestop = iir_kk_left != beforefirstindex(rs) ?
# getindex_rangestop(rs, iir_kk_left) : typemin(K)
#iir_kk_right_rangestart = iir_kk_right != pastlastindex(rs) ?
# getindex_rangestart(rs, iir_kk_right) : typemax(K)
# `kk` is adjoined in both sides with `rs` ranges, thus join them all
if iir_kk_left != beforefirstindex(rs) && iir_kk_left_rangestop + 1 == first(kk) &&
iir_kk_right != pastlastindex(rs) && iir_kk_right_rangestart - 1 == last(kk)
rs.ranges[iir_kk_left] = getindex_rangestop(rs, iir_kk_right)
delete!((rs.ranges, iir_kk_right))
# `kk` is adjoin with `rs` range on left side, thus append to left range
elseif iir_kk_left != beforefirstindex(rs) && iir_kk_left_rangestop + 1 == first(kk) &&
iir_kk_right != pastlastindex(rs) && iir_kk_right_rangestart - 1 != last(kk)
rs.ranges[iir_kk_left] = last(kk)
# `kk` is adjoin with `rs` range on right side, thus prepend to right range
elseif iir_kk_left != beforefirstindex(rs) && iir_kk_left_rangestop + 1 != first(kk) &&
iir_kk_right != pastlastindex(rs) && iir_kk_right_rangestart - 1 == last(kk)
rs.ranges[first(kk)] = getindex_rangestop(rs, iir_kk_right)
delete!((rs.ranges, iir_kk_right))
# `kk` is separate from both sides, insert it
elseif iir_kk_left != beforefirstindex(rs) && iir_kk_left_rangestop + 1 != first(kk) &&
iir_kk_right != pastlastindex(rs) && iir_kk_right_rangestart - 1 != last(kk)
rs.ranges[first(kk)] = last(kk)
# `kk` is first range in `rs` and adjoin with range on right side, thus prepend `kk` to right range
elseif iir_kk_left == beforefirstindex(rs) &&
iir_kk_right != pastlastindex(rs) && iir_kk_right_rangestart - 1 == last(kk)
rs.ranges[first(kk)] = getindex_rangestop(rs, iir_kk_right)
delete!((rs.ranges, iir_kk_right))
# `kk` is separate first range in `rs`, insert it
elseif iir_kk_left == beforefirstindex(rs) &&
iir_kk_right != pastlastindex(rs) && iir_kk_right_rangestart - 1 != last(kk)
rs.ranges[first(kk)] = last(kk)
# `kk` is last range in `rs` and adjoin with range on left side, thus append `kk` to left range
elseif iir_kk_left != beforefirstindex(rs) && iir_kk_left_rangestop + 1 == first(kk) &&
iir_kk_right == pastlastindex(rs)
rs.ranges[iir_kk_left] = last(kk)
# `kk` is separate last range in `rs`, insert it
elseif iir_kk_left != beforefirstindex(rs) && iir_kk_left_rangestop + 1 != first(kk) &&
iir_kk_right == pastlastindex(rs)
rs.ranges[first(kk)] = last(kk)
# `rs` is empty
elseif iir_kk_left == beforefirstindex(rs) && iir_kk_right == pastlastindex(rs)
rs.ranges[first(kk)] = last(kk)
else
throw(AssertionError("FIXME: Should be unreachable."))
end
return rs
end
@inline function check_exist_and_update(rs, k)
# fast check for cached range index
if (ir = rs.lastusedrangeindex) != beforefirstindex(rs)
r_start, r_stop = getindex_tuple(rs, ir)
if r_start <= k <= r_stop
return nothing
end
end
ir_k = searchsortedrangelast(rs, k)
#
#sstatus = status((rs.ranges, ir_k))
@boundscheck if index_status(rs, ir_k) == 0 # invalid range index
throw(BoundsError(rs, k))
end
# check the index exist and update its data
if ir_k != beforefirstindex(rs) # `k` is not before the first index
if k <= getindex_rangestop(rs, ir_k)
rs.lastusedrangeindex = ir_k
return nothing
end
end
return ir_k
end
function Base.push!(rs::VecUnitRangesSortedSet{K,TU}, key) where {K,TU}
k = K(key)
ir_k = check_exist_and_update(rs, k)
ir_k == nothing && return rs
if length(rs) == 0
push!(rs.rstarts, k)
push!(rs.rstops, k)
rs.lastusedrangeindex = 1
return rs
end
if ir_k == beforefirstindex(rs) # `k` is before the first range
if rs.rstarts[1] - k > 1 # there is will be gap in indices after inserting
pushfirst!(rs.rstarts, k)
pushfirst!(rs.rstops, k)
else # prepend to first range
rs.rstarts[1] = k
end
rs.lastusedrangeindex = 1
return rs
end
r = getindex(rs, ir_k)
if k >= rs.rstarts[end] # `k` is after the last range start
if k > last(r) + 1 # there is will be the gap in indices after inserting
push!(rs.rstarts, k)
push!(rs.rstops, k)
else # just append to last range
rs.rstops[ir_k] += 1
end
rs.lastusedrangeindex = lastindex(rs)
return rs
end
# `k` is somewhere between indices
stnext = advance(rs, ir_k)
rnext = getindex(rs, stnext)
if first(rnext) - last(r) == 2 # join ranges
rs.rstarts[ir_k] = first(r)
rs.rstops[ir_k] = last(rnext)
deleteat!(rs.rstarts, stnext)
deleteat!(rs.rstops, stnext)
rs.lastusedrangeindex = ir_k
elseif k - last(r) == 1 # append to left range
rs.rstops[ir_k] += 1
rs.lastusedrangeindex = ir_k
elseif first(rnext) - k == 1 # prepend to right range
rs.rstarts[stnext] -= 1
rs.lastusedrangeindex = stnext
else # insert single element range
insert!(rs.rstarts, stnext, k)
insert!(rs.rstops, stnext, k)
rs.lastusedrangeindex = stnext
end
return rs
end
function Base.push!(rs::UnitRangesSortedSet{K,TU}, key) where {K,TU}
k = K(key)
ir_k = check_exist_and_update(rs, k)
ir_k == nothing && return rs
if length(rs) == 0
rs.ranges[k] = k
rs.lastusedrangeindex = firstindex(rs)
return rs
end
if ir_k == beforefirstindex(rs) # `k` is before the first index
stnext = advance(rs, ir_k)
rnext = getindex(rs, stnext)
if first(rnext) - k > 1 # there is will be gap in indices after inserting
rs.ranges[k] = k
else # prepend to first range
rs.ranges[k] = last(rnext)
delete!((rs.ranges, stnext))
end
rs.lastusedrangeindex = firstindex(rs)
return rs
end
r = getindex(rs, ir_k)
if k > last(last(rs)) # `k` is after the last range end index
if last(r) + 1 < k # there is will be the gap in indices after inserting
rs.ranges[k] = k
else # just append to last range
rs.ranges[ir_k] = last(r)+1
end
rs.lastusedrangeindex = lastindex(rs)
return rs
end
rs.lastusedrangeindex = beforefirstindex(rs)
# `k` is somewhere between indices
stnext = advance(rs, ir_k)
rnext = getindex(rs, stnext)
if first(rnext) - last(r) == 2 # join ranges
rs.ranges[ir_k] = last(rnext)
delete!((rs.ranges, stnext))
elseif k - last(r) == 1 # append to left range
rs.ranges[ir_k] = k
rs.lastusedrangeindex = ir_k
elseif first(rnext) - k == 1 # prepend to right range
rs.ranges[k] = last(rnext)
delete!((rs.ranges, stnext))
else # insert single element range
rs.ranges[k] = k
end
return rs
end
function Base.delete!(rs::VecUnitRangesSortedSet{K,TU}, II::T) where {K,TU, T<:Union{AbstractVector,AbstractSet,NTuple}}
if hasmethod(Iterators.reverse, Tuple{T}) &&
hasmethod(keys, Tuple{T})
for r in Iterators.reverse(II)
delete!(rs, r)
end
else
for r in II
delete!(rs, r)
end
end
rs
end
@inline Base.delete!(rs::VecUnitRangesSortedSet{K,TU}, kk::AbstractRange) where {K,TU} = _delete!(rs, to_urange(TU, kk))
@inline Base.delete!(rs::VecUnitRangesSortedSet{K,TU}, kk::TU) where {K,TU<:AbstractRange} = _delete!(rs, kk)
function _delete!(rs::VecUnitRangesSortedSet{K,TU}, kk::TU) where {K,TU}
length(kk) == 0 && return rs
iir_kk = searchsortedrange(rs, kk)
length(iir_kk) == 0 && return rs
rs.lastusedrangeindex = beforefirstindex(rs)
# delete all concluded ranges
todelete1 = getindex_rangestart(rs, first(iir_kk)) < first(kk) ? first(iir_kk) + 1 : first(iir_kk)
todelete2 = getindex_rangestop(rs, last(iir_kk)) > last(kk) ? last(iir_kk) - 1 : last(iir_kk)
splice!(rs.rstarts, todelete1:todelete2)
splice!(rs.rstops, todelete1:todelete2)
# remains the side ranges to delete
# Note: there is not possible `beforefirstindex` or `pastlastindex` in `iir_kk`
iir_kk = searchsortedrange(rs, kk)
length(iir_kk) == 0 && return rs
iir_kk_rangestart = getindex_rangestart(rs, first(iir_kk))
iir_kk_rangestop = getindex_rangestop(rs, last(iir_kk))
# `kk` intersects only one range in `rs`
if length(iir_kk) == 1
# inside one range, thus split it
if iir_kk_rangestart < first(kk) && last(kk) < iir_kk_rangestop
insert!(rs.rstarts, advance(rs, first(iir_kk)), last(kk) + 1)
insert!(rs.rstops, first(iir_kk), first(kk) - 1)
# `kk` intersects with, or inside in, one range from left side, thus shrink from left side
elseif iir_kk_rangestart >= first(kk) && last(kk) < iir_kk_rangestop
rs.rstarts[first(iir_kk)] = last(kk) + 1
# `kk` intersects with, or inside in, one range from right side, thus shrink from right side
# inside one range, ended to left side, thus shrink from right side
elseif iir_kk_rangestart < first(kk) && last(kk) >= iir_kk_rangestop
rs.rstops[first(iir_kk)] = first(kk) - 1
else
throw(AssertionError("FIXME: Should be unreachable."))
end
# All remaining cases are with two ranges from `rs`,
# and both side ranges only partly intersects with `kk`.
elseif length(iir_kk) == 2
# shrink second (right) range from the left side
rs.rstarts[last(iir_kk)] = last(kk) + 1
# shrink first (left) range from the right side
rs.rstops[first(iir_kk)] = first(kk) - 1
else
throw(AssertionError("FIXME: Should be unreachable."))
end
return rs
end
function Base.delete!(rs::UnitRangesSortedSet{K,TU}, II::Union{AbstractVector,AbstractSet,NTuple}) where {K,TU}
for r in II
delete!(rs, r)
end
rs
end
@inline Base.delete!(rs::UnitRangesSortedSet{K,TU}, kk::AbstractRange) where {K,TU} = _delete!(rs, to_urange(TU, kk))
@inline Base.delete!(rs::UnitRangesSortedSet{K,TU}, kk::TU) where {K,TU<:AbstractRange} = _delete!(rs, kk)
function _delete!(rs::UnitRangesSortedSet{K,TU}, kk::TU) where {K,TU}
length(kk) == 0 && return rs
iir_kk = searchsortedrange(rs, kk)
length(iir_kk) == 0 && return rs
rs.lastusedrangeindex = beforefirstindex(rs)
# delete all concluded ranges
todelete1 = getindex_rangestart(rs, first(iir_kk)) < first(kk) ? advance(rs, first(iir_kk)) : first(iir_kk)
todelete2 = getindex_rangestop(rs, last(iir_kk)) > last(kk) ? regress(rs, last(iir_kk)) : last(iir_kk)
for st in onlysemitokens(inclusive(rs.ranges, todelete1, todelete2))
delete!((rs.ranges, st))
end
# remains the side ranges to delete
# Note: there is not possible `beforefirstindex` or `pastlastindex` in `iir_kk`
iir_kk = searchsortedrange(rs, kk)
length(iir_kk) == 0 && return rs
iir_kk_rangestart = getindex_rangestart(rs, first(iir_kk))
iir_kk_rangestop = getindex_rangestop(rs, last(iir_kk))
# `kk` intersects only one range in `rs`
if length(iir_kk) == 1
# inside one range, thus split it
if iir_kk_rangestart < first(kk) && last(kk) < iir_kk_rangestop
rs.ranges[last(kk) + 1] = iir_kk_rangestop
rs.ranges[first(iir_kk)] = first(kk) - 1
# `kk` intersects with, or inside in, one range from left side, thus shrink from left side
elseif iir_kk_rangestart >= first(kk) && last(kk) < iir_kk_rangestop
rs.ranges[last(kk) + 1] = iir_kk_rangestop
delete!((rs.ranges, first(iir_kk)))
# `kk` intersects with, or inside in, one range from right side, thus shrink from right side
# inside one range, ended to left side, thus shrink from right side
elseif iir_kk_rangestart < first(kk) && last(kk) >= iir_kk_rangestop
rs.ranges[first(iir_kk)] = first(kk) - 1
else
throw(AssertionError("FIXME: Should be unreachable."))
end
# All remaining cases are with two ranges from `rs`,
# and both side ranges only partly intersects with `kk`.
elseif length(iir_kk) == 2
# shrink second (right) range from the left side
rs.ranges[last(kk) + 1] = iir_kk_rangestop
delete!((rs.ranges, last(iir_kk)))
# shrink first (left) range from the right side
rs.ranges[first(iir_kk)] = first(kk) - 1
else
throw(AssertionError("FIXME: Should be unreachable."))
end
return rs
end
function Base.delete!(rs::VecUnitRangesSortedSet{K,TU}, key) where {K,TU}
k = K(key)
length(rs) == 0 && return rs
ir_k = searchsortedrangelast(rs, k)
if ir_k == beforefirstindex(rs) # `k` is before first range
return rs
end
r = getindex(rs, ir_k)
if k > last(r) # `k` is outside of range
return rs
end
if last(r) - first(r) + 1 == 1
deleteat!(rs.rstarts, ir_k)
deleteat!(rs.rstops, ir_k)
elseif k == last(r) # last index in range
rs.rstops[ir_k] -= 1
elseif k == first(r) # first index in range
rs.rstarts[ir_k] += 1
else
insert!(rs.rstarts, advance(rs, ir_k), k+1)
insert!(rs.rstops, advance(rs, ir_k), last(r))
rs.rstops[ir_k] = k-1
end
rs.lastusedrangeindex = beforefirstindex(rs)
return rs
end
function Base.delete!(rs::UnitRangesSortedSet{K,TU}, key) where {K,TU}
k = K(key)
length(rs) == 0 && return rs
ir_k = searchsortedrangelast(rs, k)
if ir_k == beforefirstindex(rs) # `k` is before first index
return rs
end
r = getindex(rs, ir_k)
if k > last(r) # `k` is outside of range
return rs
end
if last(r) - first(r) + 1 == 1
delete!((rs.ranges, ir_k))
elseif k == last(r) # last index in range
rs.ranges[ir_k] = last(r) - 1
elseif k == first(r) # first index in range
delete!((rs.ranges, ir_k))
rs.ranges[k+1] = last(r)
else
rs.ranges[ir_k] = k - 1
rs.ranges[k+1] = last(r)
end
rs.lastusedrangeindex = beforefirstindex(rs)
return rs
end
function Base.pop!(rs::AbstractUnitRangesSortedContainer, k)
if (r = getrange(rs, k)) !== nothing
delete!(rs, k)
return r
else
throw(KeyError(k))
end
end
function Base.pop!(rs::AbstractUnitRangesSortedContainer, k, default)
if (r = getrange(rs, k)) !== nothing
delete!(rs, k)
return r
else
return default
end
end
Base.empty(rs::T) where {T<:AbstractUnitRangesSortedContainer} = T()
function Base.empty!(rs::VecUnitRangesSortedSet)
empty!(rs.rstarts)
empty!(rs.rstops)
rs.lastusedrangeindex = beforefirstindex(rs)
rs
end
function Base.empty!(rs::AbstractUnitRangesSortedContainer)
empty!(rs.ranges)
rs.lastusedrangeindex = beforefirstindex(rs)
rs
end
@inline Base.copy(rs::T) where {T<:VecUnitRangesSortedSet} = T(rs.lastusedrangeindex, copy(rs.rstarts), copy(rs.rstops))
@inline Base.copy(rs::T) where {T<:UnitRangesSortedSet} = T(beforefirstindex(rs), packcopy(rs.ranges))
@inline Base.union(rs::AbstractUnitRangesSortedSet, rss...) = union!(copy(rs), rss...)
@inline Base.union(rs::AbstractUnitRangesSortedSet, rs2) = union!(copy(rs), rs2)
@inline Base.union!(rs::AbstractUnitRangesSortedContainer, rss...) = union!(union!(rs, rss[1]), Base.tail(rss)...)
function Base.union!(rs::AbstractUnitRangesSortedContainer, rs2)
issubset(rs2, rs) && return rs
for r in rs2
push!(rs, r)
end
return rs
end
@inline Base.union!(rs::AbstractUnitRangesSortedContainer, r::AbstractRange) = push!(rs, r)
@inline Base.setdiff(rs::AbstractUnitRangesSortedSet, rss...) = setdiff!(copy(rs), rss...)
@inline Base.setdiff(rs::AbstractUnitRangesSortedSet, rs2) = setdiff!(copy(rs), rs2)
@inline Base.setdiff!(rs::AbstractUnitRangesSortedContainer, rss...) = setdiff!(setdiff!(rs, rss[1]), Base.tail(rss)...)
@inline Base.setdiff!(rs::AbstractUnitRangesSortedContainer, rs2::AbstractRange) = delete!(rs, rs2)
function Base.setdiff!(rs::AbstractUnitRangesSortedContainer, rs2)
if hasmethod(Iterators.reverse, Tuple{typeof(rs2)}) &&
hasmethod(keys, Tuple{typeof(rs2)})
for r in Iterators.reverse(rs2)
delete!(rs, r)
end
else
for r in rs2
delete!(rs, r)
end
end
return rs
end
@inline Base.symdiff(rs::AbstractUnitRangesSortedSet, sets...) = symdiff!(copy(rs), sets...)
@inline Base.symdiff(rs::AbstractUnitRangesSortedSet, s) = symdiff!(copy(rs), s)
@inline Base.symdiff!(rs::AbstractUnitRangesSortedContainer, rss...) = symdiff!(_symdiff!(rs, rss[1]), Base.tail(rss)...)
@inline Base.symdiff!(rs1::AbstractUnitRangesSortedContainer, rs2) = _symdiff!(rs1, rs2)
@inline Base.symdiff!(rs1::AbstractUnitRangesSortedContainer, rs2::AbstractSet) = _symdiff!(rs1, rs2) # AbstractSet ambiguity
function _symdiff!(rs1::AbstractUnitRangesSortedContainer{K,TU}, rs2) where {K,TU}
for r in rs2
ss = subset(rs1, r)
vv = collect(ss)
if length(vv) == 0
push!(rs1, r)
elseif length(vv) == 1
delete!(rs1, vv[1])
push!(rs1, to_urange(TU, first(r), safe_sub(first(vv[1]), 1)))
push!(rs1, to_urange(TU, safe_add(last(vv[1]), 1), last(r)))
else
push!(rs1, to_urange(TU, first(r), safe_sub(first(vv[1]), 1)))
push!(rs1, to_urange(TU, safe_add(last(vv[end]), 1), last(r)))
rnext, rhead = Iterators.peel(Iterators.reverse(vv))
delete!(rs1, rnext)
for rr in rhead
delete!(rs1, rr)
push!(rs1, to_urange(TU, last(rr)+1, first(rnext)-1))
rnext = rr
end
end
end
return rs1
end
@inline Base.:(==)(rs1::T1, rs2::T2) where {T1<:AbstractUnitRangesSortedSet, T2<:AbstractUnitRangesSortedSet} =
T1 == T2 && isequal(rs1, rs2)
function Base.isequal(rs1::AbstractUnitRangesSortedSet, rs2::AbstractUnitRangesSortedSet)
length(rs1) == length(rs2) || return false
for (r1,r2) in zip(rs1, rs2)
r1 == r2 || return false
end
return true
end
function Base.issubset(rs1::AbstractUnitRangesSortedSet, rs2::AbstractUnitRangesSortedSet)
for r1 in rs1
in(r1, rs2) || return false
end
return true
end
function Base.issubset(rs1::Union{AbstractSet,AbstractVector,AbstractRange,Tuple}, rs2::AbstractUnitRangesSortedSet)
for r1 in rs1
in(r1, rs2) || return false
end
return true
end
@inline Base.issubset(rs1::AbstractUnitRangesSortedSet, rs2::Union{AbstractSet,AbstractVector,AbstractRange,Tuple}) = _issubset1(rs1, rs2)
@inline Base.issubset(rs1::AbstractUnitRangesSortedSet, rs2::SortedSet) = _issubset1(rs1, rs2) # ambiguity
function _issubset1(rs1::AbstractUnitRangesSortedSet, rs2)
for r1 in rs1
issubset(r1, rs2) || return false
end
return true
end
@inline Base.issubset(rs1::AbstractUnitRangesSortedSet, rs2::AbstractSet{T}) where {T<:AbstractRange} = _issubset2(rs1, rs2)
@inline Base.issubset(rs1::AbstractUnitRangesSortedSet, rs2::SortedSet{T}) where {T<:AbstractRange} = _issubset2(rs1, rs2) # ambiguity
@inline Base.issubset(rs1::AbstractUnitRangesSortedSet, rs2::AbstractVector{T}) where {T<:AbstractRange} = _issubset2(rs1, rs2)
@inline Base.issubset(rs1::AbstractUnitRangesSortedSet, rs2::Tuple{Vararg{AbstractRange}}) = _issubset2(rs1, rs2)
function _issubset2(rs1::AbstractUnitRangesSortedSet, rs2)
for r1 in rs1
findfirst(s->issubset(r1, s), rs2) !== nothing || return false
end
return true
end
function Base.filter(pred::Function, rs::AbstractUnitRangesSortedContainer)
res = empty(rs)
for r in rs
pred(r) && push!(res, r)
end
res
end
function Base.filter!(pred::Function, rs::AbstractUnitRangesSortedContainer)
for r in Iterators.reverse(rs)
pred(r) || delete!(rs, r)
end
rs
end
@inline Base.intersect!(rs::AbstractUnitRangesSortedContainer{K,TU}, kk::AbstractRange) where {K,TU} = __intersect!(rs, to_urange(TU,kk))
@inline Base.intersect!(rs::AbstractUnitRangesSortedContainer{K,TU}, kk::TU) where {K,TU<:AbstractRange} = __intersect!(rs, kk)
function __intersect!(rs::AbstractUnitRangesSortedContainer{K,TU}, kk::TU) where {K,TU}
length(kk) == 0 && return empty!(rs)
delete!(rs, safe_add(last(kk), 1):getindex_rangestop(rs, lastindex(rs)))
delete!(rs, getindex_rangestart(rs, firstindex(rs)):safe_sub(first(kk), 1))
rs
end
function Base.intersect!(rs1::AbstractUnitRangesSortedContainer, rs2::AbstractUnitRangesSortedSet)
length(rs2) == 0 && return empty!(rs1)
# cut both sides up to `rs2` indices
intersect!(rs1, getindex_rangestart(rs2, firstindex(rs2)):getindex_rangestop(rs2, lastindex(rs2)))
length(rs2) == 1 && return rs1
if hasmethod(Iterators.reverse, Tuple{typeof(rs2)}) &&
hasmethod(keys, Tuple{typeof(rs2)})
rnext, rs2head = Iterators.peel(Iterators.reverse(rs2))
for r in rs2head
delete!(rs1, last(r)+1:first(rnext)-1)
rnext = r
end
else
rprev, rs2tail = Iterators.peel(rs2)
for r in rs2tail
delete!(rs1, last(rprev)+1:first(r)-1)
rprev = r
end
end
rs1
end
# AbstractSet ambiguity resolving
Base.intersect!(rs1::AbstractUnitRangesSortedContainer, rs2::AbstractSet) = _intersect1!(rs1, rs2)
Base.intersect!(rs1::AbstractUnitRangesSortedContainer, rs2::AbstractVector) = _intersect1!(rs1, rs2)
function _intersect1!(rs1::AbstractUnitRangesSortedContainer, rs2)
length(rs2) == 0 && return empty!(rs1)
rv2 = collect(rs2)
sort!(rv2)
intersect!(rs1, first(rv2):last(rv2))
length(rv2) == 1 && return rs1
if hasmethod(Iterators.reverse, Tuple{typeof(rv2)}) &&
hasmethod(keys, Tuple{typeof(rv2)})
rnext, rv2head = Iterators.peel(Iterators.reverse(rv2))
for r in rv2head
delete!(rs1, r+1:rnext-1)
rnext = r
end
else
rprev, rv2tail = Iterators.peel(rv2)
for r in rv2tail
delete!(rs1, rprev+1:r-1)
rprev = r
end
end
rs1
end
Base.intersect!(rs1::AbstractUnitRangesSortedContainer, rs2::AbstractSet{T}) where {T<:AbstractRange} = __intersect1!(rs1, rs2)
Base.intersect!(rs1::AbstractUnitRangesSortedContainer, rs2::AbstractVector{T}) where {T<:AbstractRange} = __intersect1!(rs1, rs2)
Base.intersect!(rs1::AbstractUnitRangesSortedContainer, rs2::Tuple{Vararg{AbstractRange}}) = __intersect1!(rs1, rs2)
function __intersect1!(rs1::AbstractUnitRangesSortedContainer, rs2)
length(rs2) == 0 && return empty!(rs1)
rv2 = collect(rs2)
sort!(rv2)
intersect!(rs1, first(rv2[firstindex(rv2)]):last(rv2[lastindex(rv2)]))
length(rv2) == 1 && return rs1
hasmethod(Iterators.reverse, Tuple{typeof(rv2)}) || throw(AssertionError("FIXME: TODO."))
rnext, rv2head = Iterators.peel(Iterators.reverse(rv2))
for r in rv2head
delete!(rs1, last(r)+1:first(rnext)-1)
rnext = r
end
rs1
end
function Base.intersect!(rs1::AbstractVector, rs2::AbstractUnitRangesSortedSet)
rs = UnitRangesSortedSet(rs1)
intersect!(rs, rs2)
if eltype(rs1) <: AbstractRange
resize!(rs1, length(rs))
for (i, r) in enumerate(rs)
rs1[i] = r
end
else
resize!(rs1, sum(length(r) for r in rs))
i = 0
for r in rs, v in r
rs1[i+=1] = v
end
end
rs1
end
function Base.intersect!(rs1::AbstractSet, rs2::AbstractUnitRangesSortedSet)
rs = UnitRangesSortedSet(rs1)
intersect!(rs, rs2)
empty!(rs1)
if eltype(rs1) <: AbstractRange
for r in rs
push!(rs1, r)
end
else
for r in rs, v in r
push!(rs1, v)
end
end
rs1
end
Base.intersect(rs1::AbstractUnitRangesSortedSet, rs2) = intersect!(copy(rs1), rs2)
Base.intersect(rs1::AbstractUnitRangesSortedSet, rs2::AbstractUnitRangesSortedSet) = intersect!(copy(rs1), rs2)
Base.intersect(rs1::AbstractSet, rs2::AbstractUnitRangesSortedSet) = _intersect2(rs1, rs2) # AbstractSet ambiguity resolving
Base.intersect(rs1::AbstractVector, rs2::AbstractUnitRangesSortedSet) = _intersect2(rs1, rs2)
function _intersect2(rs1, rs2::AbstractUnitRangesSortedSet)
rs = UnitRangesSortedSet(rs1)
intersect!(rs, rs2)
return convert(typeof(rs1), rs)
end
#
# Aux functions
#
# https://github.com/JuliaLang/julia/issues/39952
basetype(::Type{T}) where T = Base.typename(T).wrapper
## https://discourse.julialang.org/t/how-do-a-i-get-a-type-stripped-of-parameters/73465/8
#basetype(::Type{T}) where T = eval(nameof(T))
## https://discourse.julialang.org/t/deparametrising-types/41939/4
#basetype(T::DataType) = T.name.wrapper
#basetype(T::UnionAll) = basetype(T.body)
datatypeshortname(x) = (T = typeof(x); string(basetype(T)) * "{" * string(eltype(eltype(T))) * "}")
Base.show(io::IO, ur::URSSIndexURange) = print(io, repr(first(ur)), ':', length(ur) == 0 ? "0" : "1" , ':', repr(last(ur)))
function Base.show(io::IO, ::MIME"text/plain", x::URSSIndexURange)
len = length(x)
print(io, len, "-element range ", first(x), ":", last(x), " in ", datatypeshortname(x.parent))
if len != 0
println(io, " containing:")
show(IOContext(io, :typeinfo => eltype(x)), x)
end
end
function Base.show(io::IOContext, x::URSSIndexURange)
ranges = [getindex(x, s) for s in x]
n = length(ranges)
if isempty(ranges)
return show(io, MIME("text/plain"), x)
end
limit = get(io, :limit, false)::Bool
half_screen_rows = limit ? div(displaysize(io)[1] - 8, 2) : typemax(Int)
pad = get_max_pad(x.parent)
if !haskey(io, :compact)
io = IOContext(io, :compact => true)
end
for k = eachindex(ranges)
if k < half_screen_rows || k > length(ranges) - half_screen_rows
print(io, " ")
if isassigned(ranges, Int(k))
print(io, lpad(repr(first(ranges[k])), pad), ":", repr(last(ranges[k])))
else
print(io, Base.undef_ref_str)
end
k != length(ranges) && println(io)
elseif k == half_screen_rows
println(io, " "^(pad-1), " \u22ee")
end
end
end
function Base.show(io::IO, x::T) where {T<:AbstractUnitRangesSortedSubSet}
print(io, "subset(", datatypeshortname(x.parent), ", ", x.firstindex, ":", x.lastindex, "): (")
if length(x) > 0
el1, restx = Iterators.peel(x)
print(io, repr(first(el1)), ":", repr(last(el1)))
for r in restx
print(io, ", ", repr(first(r)), ":", repr(last(r)))
end
end
print(io, ")")
end
function Base.show(io::IO, ::MIME"text/plain", x::T) where {T<:AbstractUnitRangesSortedSubSet}
len = length(x)
print(io, len, "-element subset(", datatypeshortname(x.parent), ", ", x.firstindex, ":", x.lastindex, ")")
if len != 0
println(io, ":")
show(IOContext(io, :typeinfo => eltype(x)), x)
end
end
function Base.show(io::IO, x::T) where {T<:AbstractUnitRangesSortedSet}
print(io, datatypeshortname(x), "(")
if length(x) > 0
el1, restx = Iterators.peel(x)
print(io, repr(first(el1)), ":", repr(last(el1)))
for r in restx
print(io, ", ", repr(first(r)), ":", repr(last(r)))
end
end
print(io, ")")
end
# derived from stdlib/SparseArrays/src/sparsevector.jl
function Base.show(io::IO, ::MIME"text/plain", x::T) where {T<:AbstractUnitRangesSortedSet}
len = length(x)
if len == 0
println(io, datatypeshortname(x), "()")
else
println(io, datatypeshortname(x), " with ", len, len==1 ? " element:" : " elements:")
show(IOContext(io, :typeinfo => eltype(x)), x)
end
end
Base.show(io::IOContext, x::T) where {T<:AbstractUnitRangesSortedSubSet} = _display_AURSS(io, x)
Base.show(io::IOContext, x::T) where {T<:AbstractUnitRangesSortedSet} = _display_AURSS(io, x)
function _display_AURSS(io, x)
ranges = [v for v in x]
n = length(ranges)
if isempty(ranges)
return show(io, MIME("text/plain"), x)
end
limit = get(io, :limit, false)::Bool
half_screen_rows = limit ? div(displaysize(io)[1] - 8, 2) : typemax(Int)
pad = get_max_pad(x)
if !haskey(io, :compact)
io = IOContext(io, :compact => true)
end
for k = eachindex(ranges)
if k < half_screen_rows || k > length(ranges) - half_screen_rows
print(io, " ")
if isassigned(ranges, Int(k))
print(io, lpad(repr(first(ranges[k])), pad), ":", repr(last(ranges[k])))
else
print(io, Base.undef_ref_str)
end
k != length(ranges) && println(io)
elseif k == half_screen_rows
println(io, " "^(pad-1), " \u22ee")
end
end
end
function get_max_pad(rs::AbstractUnitRangesSortedSet)
len = length(rs)
pad = 0
for (i,r) in enumerate(rs)
if i < 100 || i > len - 100
pad = max(pad, length(repr(first(r))), length(repr(last(r))))
end
end
pad
end
end # of module UnitRangesSortedSets
| UnitRangesSortedSets | https://github.com/denius/UnitRangesSortedSets.jl.git |
|
[
"MIT"
] | 0.1.2 | f0de74163ea91daf9565c5b209506ce18a2d6d67 | code | 37609 |
using BenchmarkTools
using DataStructures
using UnitRangesSortedSets
using UnitRangesSortedSets: advance, beforefirstindex, inferrangetype, pastlastindex, regress, to_urange
using Test
using Aqua
Aqua.test_all(UnitRangesSortedSets)
# TODO:
# Custom Number Type, see Unitful: "runtests.jl"
#
# Try Test.GenericSet
#
# [rs[i] for i in searchsortedrange(rs, 10:40)]
#
# function VecUnitRangesSortedSet(rs::AbstractUnitRangesSortedSet{K,TU}) where {K,TU}
# function UnitRangesSortedSet(rs::AbstractUnitRangesSortedSet{K,TU}) where {K,TU}
# @inline function URSSIndexURange(rs::P, l::Tix, r::Tix) where {P<:VecUnitRangesSortedSet, Tix}
# URSSIndexURange for VecUnitRangesSortedSet?
# @inline Base.firstindex(ur::URSSIndexURange) = ur.start
# @inline Base.lastindex(ur::URSSIndexURange) = ur.stop
# @inline DataStructures.advance(ur::URSSIndexURange), beforefirstindex
# @inline function Base.iterate(ur::URSSIndexURange, state = (first(ur), 0))
# @inline function Base.getindex(ur::URSSIndexURange, i) ???
# @inline function indexcompare(rs::VecUnitRangesSortedSet, i, j)
# @inline function indexcompare(rs::AbstractSubUnitRangesSortedSet{K,TU,P}, i, j) where {K,TU,P<:VecUnitRangesSortedSet}
# @inline getindex_tuple(rs::Sub01XUnitRangesSortedSet, i)
# @inline searchsortedrangelast(rs::Sub01XUnitRangesSortedSet, k)
# @inline searchsortedrangefirst(rs::Sub01XUnitRangesSortedSet, k)
# @inline searchsortedrange(rs::AbstractSubUnitRangesSortedSet, kk::AbstractRange)
#
# function Base.show(io::IO, x::T) where {T<:AbstractUnitRangesSortedSubSet}
# function Base.show(io::IO, ::MIME"text/plain", x::T) where {T<:AbstractUnitRangesSortedSubSet}
#
# https://github.com/JuliaLang/julia/issues/39952
basetype(::Type{T}) where T = Base.typename(T).wrapper
const list_of_Ti_to_test = (Int, UInt16, Float64, Char)
#const list_of_Ti_to_test = (Int, UInt64, UInt16, Float64, Char)
const list_of_containers_types_to_test = (VecUnitRangesSortedSet, UnitRangesSortedSet)
function check_ranges_isequal(r, rs...)
for rr in rs
step(r) == step(rr) || return false
first(r) == first(rr) || return false
last(r) == last(rr) || return false
end
return true
end
function check_isequal(rs1, rs2)
length(rs1) == length(rs2) || return false
for (r1, r2) in zip(rs1, rs2)
check_ranges_isequal(r1, r2) || return false
end
return true
end
function test_isequal(rs1, rs2)
@test length(rs1) == length(rs2)
for (r1, r2) in zip(rs1, rs2)
@test step(r1) == step(r2)
@test first(r1) == first(r2)
@test last(r1) == last(r2)
end
end
function test_range_create(rs::T, vu, Tv::Type) where {T<:AbstractUnitRangesSortedContainer}
TRange = inferrangetype(Tv)
@test eltype(rs) === TRange
@test typeof(rs) === basetype(T){Tv,TRange}
test_isequal(rs, vu)
end
convertinfer(K::Type, rs::NTuple{N,T}) where{N,T<:AbstractRange} =
convert(NTuple{length(rs),inferrangetype(K)}, rs)
convertinfer(K::Type, rs::NTuple{N,T}) where{N,T} =
convert(NTuple{length(rs),K}, rs)
convertinfer(K::Type, rs::AbstractVector{T}) where{T<:AbstractRange} =
convert(Vector{inferrangetype(K)}, rs)
convertinfer(K::Type, rs::AbstractVector{T}) where{T} =
convert(Vector{K}, rs)
convertinfer(K::Type, r::AbstractRange) =
to_urange(inferrangetype(K), r)
function test_iterators(rs, vu)
@test length(rs) == length(vu)
@test regress(rs, firstindex(rs)) == beforefirstindex(rs)
@test advance(rs, lastindex(rs)) == pastlastindex(rs)
@test check_ranges_isequal(rs[firstindex(rs)], rs[begin], first(rs), first(vu))
@test check_ranges_isequal(rs[lastindex(rs)], rs[end], last(rs), last(vu))
@test check_isequal(rs, vu)
@test check_isequal(Iterators.reverse(rs), Iterators.reverse(vu))
@test check_isequal([r for r in rs], [r for r in vu])
@test check_isequal([r for r in Iterators.reverse(rs)], [r for r in Iterators.reverse(vu)])
@test sum(r->length(r), rs) ==
sum(r->length(r), Iterators.reverse(rs)) ==
sum(i->length(rs[i]), eachindex(rs)) ==
sum(i->length(rs[i]), eachindex(Iterators.reverse(rs))) ==
sum(i->length(rs[i]), Iterators.reverse(eachindex(rs))) ==
sum(r->length(r), vu)
end
function test_empty_iterators(rs, vu)
@test length(rs) == length(vu)
@test firstindex(rs) == pastlastindex(rs)
@test lastindex(rs) == beforefirstindex(rs)
@test_throws BoundsError rs[begin]
@test_throws BoundsError rs[end]
@test_throws BoundsError first(rs)
@test_throws BoundsError last(rs)
@test check_isequal(rs, vu)
@test check_isequal(Iterators.reverse(rs), Iterators.reverse(vu))
@test check_isequal([r for r in rs], [r for r in vu])
@test check_isequal([r for r in Iterators.reverse(rs)], [r for r in Iterators.reverse(vu)])
@test sum(r->length(r), rs, init=0) ==
sum(r->length(r), Iterators.reverse(rs), init=0) ==
sum(i->length(rs[i]), eachindex(rs), init=0) ==
sum(i->length(rs[i]), eachindex(Iterators.reverse(rs)), init=0) ==
sum(i->length(rs[i]), Iterators.reverse(eachindex(rs)), init=0) ==
sum(r->length(r), vu, init=0)
end
@testset "Creating" begin
for K in list_of_Ti_to_test
for TypeURSS in list_of_containers_types_to_test
@eval begin
vu = Vector{inferrangetype($K)}(undef, 0)
test_range_create($TypeURSS{$K}(), convertinfer($K, vu), $K)
v = [1, 2]
vu = [1:2]
test_range_create($TypeURSS{$K}(v), convertinfer($K, vu), $K)
v = [1, 3, 4]
vu = [1:1, 3:4]
test_range_create($TypeURSS{$K}(v), convertinfer($K, vu), $K)
v = [3:4, 1:1]
vu = [1:1, 3:4]
test_range_create($TypeURSS{$K}(v), convertinfer($K, vu), $K)
v = [3:4, 2:5, 1:1]
vu = [1:5]
test_range_create($TypeURSS{$K}(v), convertinfer($K, vu), $K)
v = [$K(1), $K(3), $K(4)]
vu = [1:1, 3:4]
test_range_create($TypeURSS(v), convertinfer($K, vu), $K)
v = [$K(3):$K(4), $K(1):$K(1)]
vu = [1:1, 3:4]
test_range_create($TypeURSS(v), convertinfer($K, vu), $K)
v = [UInt64(3):UInt64(4), UInt64(1):UInt64(1)]
vu = [1:1, 3:4]
test_range_create($TypeURSS{$K}(v), convertinfer($K, vu), $K)
v = [UInt64(3), UInt64(4), UInt64(1)]
vu = [1:1, 3:4]
test_range_create($TypeURSS(v), convertinfer(UInt64, vu), UInt64)
v = [UInt64(3):UInt64(4), UInt64(1):UInt64(1)]
vu = [1:1, 3:4]
test_range_create($TypeURSS(v), convertinfer(UInt64, vu), UInt64)
end
end
end
end
@testset "Searching" begin
for K in list_of_Ti_to_test
for TypeURSS in list_of_containers_types_to_test
@eval begin
rs = $TypeURSS{$K}((1:2, 4:4, 6:6))
ir = searchsortedrangelast(rs, 0)
@test ir == beforefirstindex(rs)
ir = searchsortedrangelast(rs, 1)
@test ir != beforefirstindex(rs) &&
getindex(rs, ir) == convertinfer($K, 1:2) &&
ir == firstindex(rs)
ir = searchsortedrangelast(rs, 2)
@test ir != beforefirstindex(rs) &&
getindex(rs, ir) == convertinfer($K, 1:2) &&
ir == firstindex(rs)
ir = searchsortedrangelast(rs, 3)
@test ir != beforefirstindex(rs) &&
getindex(rs, ir) == convertinfer($K, 1:2) &&
ir == firstindex(rs)
ir = searchsortedrangelast(rs, 4)
@test ir != beforefirstindex(rs) &&
getindex(rs, ir) == convertinfer($K, 4:4) &&
ir != firstindex(rs) && ir != lastindex(rs)
ir = searchsortedrangelast(rs, 5)
@test ir != beforefirstindex(rs) &&
getindex(rs, ir) == convertinfer($K, 4:4) &&
ir != firstindex(rs) && ir != lastindex(rs)
ir = searchsortedrangelast(rs, 6)
@test ir != beforefirstindex(rs) &&
getindex(rs, ir) == convertinfer($K, 6:6) &&
ir == lastindex(rs)
ir = searchsortedrangelast(rs, 7)
@test ir != beforefirstindex(rs) &&
getindex(rs, ir) == convertinfer($K, 6:6) &&
ir == lastindex(rs)
ir = searchsortedrangefirst(rs, 0)
@test ir != pastlastindex(rs) &&
getindex(rs, ir) == convertinfer($K, 1:2) &&
ir == firstindex(rs)
ir = searchsortedrangefirst(rs, 1)
@test ir != pastlastindex(rs) &&
getindex(rs, ir) == convertinfer($K, 1:2) &&
ir == firstindex(rs)
ir = searchsortedrangefirst(rs, 2)
@test ir != pastlastindex(rs) &&
getindex(rs, ir) == convertinfer($K, 1:2) &&
ir == firstindex(rs)
ir = searchsortedrangefirst(rs, 3)
@test ir != pastlastindex(rs) &&
getindex(rs, ir) == convertinfer($K, 4:4) &&
ir != firstindex(rs) && ir != lastindex(rs)
ir = searchsortedrangefirst(rs, 4)
@test ir != pastlastindex(rs) &&
getindex(rs, ir) == convertinfer($K, 4:4) &&
ir != firstindex(rs) && ir != lastindex(rs)
ir = searchsortedrangefirst(rs, 5)
@test ir != pastlastindex(rs) &&
getindex(rs, ir) == convertinfer($K, 6:6) &&
ir == lastindex(rs)
ir = searchsortedrangefirst(rs, 6)
@test ir != pastlastindex(rs) &&
getindex(rs, ir) == convertinfer($K, 6:6) &&
ir == lastindex(rs)
ir = searchsortedrangefirst(rs, 7)
@test ir == pastlastindex(rs)
rs = $TypeURSS{$K}((1:2, 4:4))
iir = searchsortedrange(rs, 0)
@test length(iir) == 0 && getindex(rs, first(iir)) == convertinfer($K, 1:2) &&
first(iir) == firstindex(rs) &&
last(iir) == beforefirstindex(rs)
iir = searchsortedrange(rs, 1)
@test length(iir) == 1 && getindex(rs, first(iir)) == convertinfer($K, 1:2) &&
first(iir) == firstindex(rs)
iir = searchsortedrange(rs, 2)
@test length(iir) == 1 && getindex(rs, first(iir)) == convertinfer($K, 1:2)
iir = searchsortedrange(rs, 3)
@test length(iir) == 0 && getindex(rs, first(iir)) == convertinfer($K, 4:4) &&
getindex(rs, last(iir)) == convertinfer($K, 1:2)
iir = searchsortedrange(rs, 4)
@test length(iir) == 1 && getindex(rs, first(iir)) == convertinfer($K, 4:4)
iir = searchsortedrange(rs, 5)
@test length(iir) == 0 && getindex(rs, last(iir)) == convertinfer($K, 4:4) &&
first(iir) == pastlastindex(rs) &&
last(iir) == lastindex(rs)
rs = $TypeURSS{$K}((1:2, 4:4))
@test getrange(rs, 0) === nothing
@test getrange(rs, 1) == convertinfer($K, 1:1)
@test getrange(rs, 1:1) == convertinfer($K, 1:1)
@test getrange(rs, 1:2) == convertinfer($K, 1:2)
@test getrange(rs, 1:3) === nothing
end
end
end
end
@testset "`in`" begin
for K in list_of_Ti_to_test
for TypeURSS in list_of_containers_types_to_test
@eval begin
v = [1, 2, 3, 5, 6, 8]
rs = $TypeURSS{$K}(v)
for i = 0:9
@test !xor(in(i, rs), in(i, v))
end
v = [2:3, 5:6]
rs = $TypeURSS{$K}(v)
@test !in(1:2, rs)
@test in(2:2, rs)
@test in(2:3, rs)
@test in(5:5, rs)
@test !in(2:4, rs)
@test !in(4:4, rs)
@test !in(2:6, rs)
@test !in(1:7, rs)
end
end
end
end
@testset "`push!`" begin
for K in list_of_Ti_to_test
for TypeURSS in list_of_containers_types_to_test
@eval begin
rs = $TypeURSS{$K}()
@test check_isequal(push!(rs, 3), convertinfer($K, (3:3,)))
@test check_isequal(push!(rs, 4), convertinfer($K, (3:4,)))
@test check_isequal(push!(rs, 18), convertinfer($K, (3:4, 18:18)))
@test check_isequal(push!(rs, 2), convertinfer($K, (2:4, 18:18)))
@test check_isequal(push!(rs, 0), convertinfer($K, (0:0, 2:4, 18:18)))
@test check_isequal(push!(rs, 20), convertinfer($K, (0:0, 2:4, 18:18, 20:20)))
@test check_isequal(push!(rs, 19), convertinfer($K, (0:0, 2:4, 18:20)))
@test check_isequal(push!(rs, 1), convertinfer($K, (0:4, 18:20)))
@test check_isequal(push!(rs, 9), convertinfer($K, (0:4, 9:9, 18:20)))
@test check_isequal(push!(rs, 9), convertinfer($K, (0:4, 9:9, 18:20)))
@test check_isequal(push!(rs, 10), convertinfer($K, (0:4, 9:10, 18:20)))
@test check_isequal(push!(rs, 8), convertinfer($K, (0:4, 8:10, 18:20)))
rs = $TypeURSS{$K}()
@test check_isequal(push!(rs, 13:14), convertinfer($K, (13:14,)))
@test check_isequal(push!(rs, 23:24), convertinfer($K, (13:14, 23:24)))
@test check_isequal(push!(rs, 12:12), convertinfer($K, (12:14, 23:24)))
@test check_isequal(push!(rs, 11:13), convertinfer($K, (11:14, 23:24)))
@test check_isequal(push!(rs, 8:9), convertinfer($K, (8:9, 11:14, 23:24)))
@test check_isequal(push!(copy(rs), [9:12]), convertinfer($K, (8:14, 23:24)))
@test check_isequal(push!(copy(rs), (9:12,)), convertinfer($K, (8:14, 23:24)))
@test check_isequal(push!(copy(rs), [9,10,11,12]), convertinfer($K, (8:14, 23:24)))
@test check_isequal(push!(rs, 9:12), convertinfer($K, (8:14, 23:24)))
@test check_isequal(push!(rs, 16:17), convertinfer($K, (8:14, 16:17, 23:24)))
@test check_isequal(push!(rs, 25:26), convertinfer($K, (8:14, 16:17, 23:26)))
@test check_isequal(push!(rs, 24:26), convertinfer($K, (8:14, 16:17, 23:26)))
@test check_isequal(push!(rs, 28:29), convertinfer($K, (8:14, 16:17, 23:26, 28:29)))
@test check_isequal(push!(rs, 28:29), convertinfer($K, (8:14, 16:17, 23:26, 28:29)))
@test check_isequal(push!(rs, 16:15), convertinfer($K, (8:14, 16:17, 23:26, 28:29)))
@test check_isequal(push!(rs, 18:19), convertinfer($K, (8:14, 16:19, 23:26, 28:29)))
end
end
end
end
@testset "`delete!`" begin
for K in list_of_Ti_to_test
for TypeURSS in list_of_containers_types_to_test
@eval begin
rs = $TypeURSS{$K}((0:0, 2:4, 8:8, 10:12))
@test check_isequal(delete!(rs, 5), convertinfer($K, (0:0, 2:4, 8:8, 10:12)))
@test check_isequal(delete!(rs, 0), convertinfer($K, (2:4, 8:8, 10:12)))
@test check_isequal(delete!(rs, 0), convertinfer($K, (2:4, 8:8, 10:12)))
@test check_isequal(delete!(rs, 8), convertinfer($K, (2:4, 10:12)))
@test check_isequal(delete!(rs, 12), convertinfer($K, (2:4, 10:11)))
@test check_isequal(delete!(rs, 10), convertinfer($K, (2:4, 11:11)))
@test check_isequal(delete!(rs, 11), convertinfer($K, (2:4,)))
@test check_isequal(delete!(rs, 3), convertinfer($K, (2:2, 4:4)))
@test delete!(rs, 3) === rs
rs = $TypeURSS{$K}((0:0, 2:6, 8:8, 10:13, 15:20))
@test check_isequal(delete!(rs, 17:17), convertinfer($K, (0:0, 2:6, 8:8, 10:13, 15:16, 18:20)))
@test check_isequal(delete!(rs, 16:18), convertinfer($K, (0:0, 2:6, 8:8, 10:13, 15:15, 19:20)))
@test check_isequal(delete!(rs, 15:20), convertinfer($K, (0:0, 2:6, 8:8, 10:13)))
@test check_isequal(delete!(rs, 7:7), convertinfer($K, (0:0, 2:6, 8:8, 10:13)))
@test check_isequal(delete!(rs, 6:7), convertinfer($K, (0:0, 2:5, 8:8, 10:13)))
@test check_isequal(delete!(rs, 0:1), convertinfer($K, (2:5, 8:8, 10:13)))
@test check_isequal(delete!(rs, 9:10), convertinfer($K, (2:5, 8:8, 11:13)))
@test check_isequal(delete!(rs, 13:14), convertinfer($K, (2:5, 8:8, 11:12)))
@test check_isequal(delete!(copy(rs), [1:3]), convertinfer($K, (4:5, 8:8, 11:12)))
@test check_isequal(delete!(copy(rs), (1:3,)), convertinfer($K, (4:5, 8:8, 11:12)))
@test check_isequal(delete!(copy(rs), [1,2,3]), convertinfer($K, (4:5, 8:8, 11:12)))
@test check_isequal(delete!(copy(rs), (1,2,3)), convertinfer($K, (4:5, 8:8, 11:12)))
@test check_isequal(delete!(rs, 1:3), convertinfer($K, (4:5, 8:8, 11:12)))
end
end
end
end
@testset "`subset`" begin
for K in list_of_Ti_to_test
for TypeURSS in list_of_containers_types_to_test
@eval begin
rs = $TypeURSS{$K}((0:0, 2:6, 8:16, 20:33, 35:47, 49:50))
it = searchsortedrangelast(rs, 1)
ss = subset(rs, :)
@test typeof(ss) == UnitRangesSortedSubSet{$K,inferrangetype($K),typeof(rs),typeof(it)}
vu = (0:0, 2:6, 8:16, 20:33, 35:47, 49:50)
test_iterators(ss, convertinfer($K, vu))
ss = subset(rs, 0:50)
vu = (0:0, 2:6, 8:16, 20:33, 35:47, 49:50)
test_iterators(ss, convertinfer($K, vu))
ss = subset(rs, 0:0)
@test typeof(ss) == UnitRangesSortedSubSet1{$K,inferrangetype($K),typeof(rs),typeof(it)}
vu = (0:0,)
test_iterators(ss, convertinfer($K, vu))
ss = subset(rs, 0:1)
@test typeof(ss) == UnitRangesSortedSubSet1{$K,inferrangetype($K),typeof(rs),typeof(it)}
vu = (0:0,)
test_iterators(ss, convertinfer($K, vu))
ss = subset(rs, 10:40)
@test typeof(ss) == UnitRangesSortedSubSet{$K,inferrangetype($K),typeof(rs),typeof(it)}
vu = (10:16, 20:33, 35:40)
test_iterators(ss, convertinfer($K, vu))
ss = subset(rs, 7:40)
vu = (8:16, 20:33, 35:40)
test_iterators(ss, convertinfer($K, vu))
ss = subset(rs, 11:48)
vu = (11:16, 20:33, 35:47)
test_iterators(ss, convertinfer($K, vu))
ss = subset(rs, 7:48)
vu = (8:16, 20:33, 35:47)
test_iterators(ss, convertinfer($K, vu))
ss = subset(rs, 21:32)
vu = (21:32,)
test_iterators(ss, convertinfer($K, vu))
ss = subset(rs, 20:33)
vu = (20:33,)
test_iterators(ss, convertinfer($K, vu))
ss = subset(rs, 19:34)
vu = (20:33,)
test_iterators(ss, convertinfer($K, vu))
ss = subset(rs, 22:34)
vu = (22:33,)
test_iterators(ss, convertinfer($K, vu))
ss = subset(rs, 19:30)
vu = (20:30,)
test_iterators(ss, convertinfer($K, vu))
ss = subset(rs, 18:19)
@test typeof(ss) == UnitRangesSortedSubSet0{$K,inferrangetype($K),typeof(rs),typeof(it)}
vu = Vector{eltype(ss)}([])
test_empty_iterators(ss, convertinfer($K, vu))
ss = subset(rs, 21:20)
@test typeof(ss) == UnitRangesSortedSubSet0{$K,inferrangetype($K),typeof(rs),typeof(it)}
vu = Vector{eltype(ss)}([])
test_empty_iterators(ss, convertinfer($K, vu))
ss = subset(rs, 51:51)
@test typeof(ss) == UnitRangesSortedSubSet0{$K,inferrangetype($K),typeof(rs),typeof(it)}
vu = Vector{eltype(ss)}([])
test_empty_iterators(ss, convertinfer($K, vu))
delete!(rs, 0:0)
ss = subset(rs, 0:1)
@test typeof(ss) == UnitRangesSortedSubSet0{$K,inferrangetype($K),typeof(rs),typeof(it)}
vu = Vector{eltype(ss)}([])
test_empty_iterators(ss, convertinfer($K, vu))
# subset of subset
rs = $TypeURSS{$K}((0:0, 2:6, 8:16, 20:33, 35:47, 49:50))
it = searchsortedrangelast(rs, 1)
ss = subset(rs, :)
sss = subset(ss, :)
@test typeof(sss) == UnitRangesSortedSubSet{$K,inferrangetype($K),typeof(rs),typeof(it)}
vu = (0:0, 2:6, 8:16, 20:33, 35:47, 49:50)
test_iterators(sss, convertinfer($K, vu))
sss = subset(ss, 0:0)
@test typeof(sss) == UnitRangesSortedSubSet1{$K,inferrangetype($K),typeof(rs),typeof(it)}
vu = (0:0,)
test_iterators(sss, convertinfer($K, vu))
ss = subset(rs, 10:40) # (10:16, 20:33, 35:40)
sss = subset(ss, 15:35)
@test typeof(sss) == UnitRangesSortedSubSet{$K,inferrangetype($K),typeof(rs),typeof(it)}
vu = (15:16, 20:33, 35:35)
test_iterators(sss, convertinfer($K, vu))
sss = subset(ss, 18:19)
@test typeof(sss) == UnitRangesSortedSubSet0{$K,inferrangetype($K),typeof(rs),typeof(it)}
vu = Vector{eltype(ss)}([])
test_empty_iterators(sss, convertinfer($K, vu))
end
end
end
end
@testset "`in` subsets" begin
for K in list_of_Ti_to_test
for TypeURSS in list_of_containers_types_to_test
@eval begin
v = [0, 1, 2, 3, 5, 6, 8, 9, 11, 12]
rs = $TypeURSS{$K}(v)
vu = [1, 2, 3, 5, 6, 8]
ss = subset(rs, 1:8)
for i = 0:13
@test !xor(in(i, ss), in(i, vu))
end
v = [0:0, 2:3, 5:6, 8:8]
rs = $TypeURSS{$K}(v)
ss = subset(rs, 2:6)
@test !in(1:2, ss)
@test in(2:2, ss)
@test in(2:3, ss)
@test in(5:5, ss)
@test !in(2:4, ss)
@test !in(4:4, ss)
@test !in(2:6, ss)
@test !in(1:7, ss)
v = [0:0, 2:3, 5:6, 8:8]
rs = $TypeURSS{$K}(v)
ss = subset(rs, 2:3)
@test !in(1:2, ss)
@test !in(1, ss)
@test in(2, ss)
@test in(2:2, ss)
@test in(2:3, ss)
@test in(3:3, ss)
@test !in(2:4, ss)
@test !in(3:4, ss)
@test !in(4:4, ss)
@test !in(5:5, ss)
v = [0:0, 2:3, 5:6, 8:8]
rs = $TypeURSS{$K}(v)
ss = subset(rs, 3:2)
@test !in(1, ss)
@test !in(2, ss)
@test !in(1:2, ss)
@test !in(2:2, ss)
@test !in(2:3, ss)
@test !in(3:3, ss)
@test !in(2:4, ss)
@test !in(3:4, ss)
@test !in(4:4, ss)
@test !in(5:5, ss)
end
end
end
end
@testset "Common functions" begin
for K in list_of_Ti_to_test
for TypeURSS in list_of_containers_types_to_test
@eval begin
rs = $TypeURSS{$K}()
vu = Vector{eltype(rs)}([])
test_empty_iterators(rs, convertinfer($K, vu))
rs = $TypeURSS{$K}((1:6,))
vu = (1:6,)
test_iterators(rs, convertinfer($K, vu))
rs = $TypeURSS{$K}((1:6, 8:16, 20:33))
vu = (1:6, 8:16, 20:33)
test_iterators(rs, convertinfer($K, vu))
rs = $TypeURSS{$K}((0:0, 2:4))
rs2 = copy(rs)
@test rs2 == rs && rs2 !== rs
rs2 = empty(rs)
@test rs2 == $TypeURSS{$K}()
empty!(rs2)
@test rs2 != rs && rs2 !== rs
@test length(rs2) == 0
rs = $TypeURSS{$K}((0:0, 2:4))
@test filter(s->length(s)==3, rs) == $TypeURSS{$K}((2:4))
@test (filter!(s->length(s)==1, rs); rs == $TypeURSS{$K}((0:0)))
rs = $TypeURSS{$K}((0:0, 2:4))
@test findfirst(s->issubset(s, $K(0):$K(4)), rs) == searchsortedrangelast(rs, $K(0))
@test findfirst(s->issubset(s, $K(1):$K(4)), rs) == searchsortedrangelast(rs, $K(2))
@test findall(s->length(s)==1, rs) == convertinfer($K, [0:0])
v = [0:0, 2:4]
rs = $TypeURSS{$K}(v)
@test collect(rs) == convertinfer($K, v)
@test collect(UInt64, rs) == convertinfer(UInt64, v)
@test convert(typeof(rs), rs) === rs
@test convert(SortedSet{inferrangetype($K)}, rs) == SortedSet(to_urange.(inferrangetype($K), v))
@test convert(SortedSet{UInt64}, rs) == SortedSet{UInt64}(collect(Iterators.flatten(v)))
@test convert(SortedSet{$K}, rs) == SortedSet{$K}(collect(Iterators.flatten(v)))
@test convert(SortedSet, rs) == SortedSet{$K}(collect(Iterators.flatten(v)))
@test convert(Vector{inferrangetype($K)}, rs) == Vector(to_urange.(inferrangetype($K), v))
@test convert(Vector{UInt64}, rs) == Vector{UInt64}(collect(Iterators.flatten(v)))
@test convert(Vector{$K}, rs) == Vector{$K}(collect(Iterators.flatten(v)))
@test convert(Vector, rs) == Vector{$K}(collect(Iterators.flatten(v)))
end
end
end
end
@testset "`Set` API" begin
for K in list_of_Ti_to_test
for TypeURSS in list_of_containers_types_to_test
@eval begin
@test union($TypeURSS{$K}((0:0, 2:4)), $TypeURSS{$K}((2:3, 5:6))) == $TypeURSS{$K}((0:0, 2:6))
@test union($TypeURSS{$K}((0:0, 2:4)), (2:3, 5:6)) == $TypeURSS{$K}((0:0, 2:6))
@test union($TypeURSS{$K}((0:0, 2:4)), (2, 3, 5, 6)) == $TypeURSS{$K}((0:0, 2:6))
@test union($TypeURSS{$K}((0:0, 2:4)), [2:3], [5:6]) == $TypeURSS{$K}((0:0, 2:6))
@test union($TypeURSS{$K}((0:0, 2:4)), [2:3, 5:6]) == $TypeURSS{$K}((0:0, 2:6))
@test union($TypeURSS{$K}((0:0, 2:4)), [2, 3, 5, 6]) == $TypeURSS{$K}((0:0, 2:6))
@test union($TypeURSS{$K}((0:0, 2:4)), 1:1) == $TypeURSS{$K}((0:4))
@test union($TypeURSS{$K}((0:0, 2:4)), 1) == $TypeURSS{$K}((0:4))
@test intersect($TypeURSS{$K}((0:0, 2:4)), $TypeURSS{$K}((2:3, 5:6))) == $TypeURSS{$K}((2:3))
@test intersect($TypeURSS{$K}((0:0, 2:4)), (2:3, 5:6)) == $TypeURSS{$K}((2:3))
@test intersect($TypeURSS{$K}((0:0, 2:4)), 2:3) == $TypeURSS{$K}((2:3))
@test intersect($TypeURSS{$K}((0:0, 2:4)), 2) == $TypeURSS{$K}((2:2))
rs = $TypeURSS{$K}((0:0, 2:4))
@test (intersect!(rs, $TypeURSS{$K}((2:3, 5:6, 8:8))); rs == $TypeURSS{$K}((2:3)))
rs = [0:0, 2:4, 8:10, 12:12]
@test (intersect(rs, $TypeURSS{$K}((2:3, 5:6, 8:8))) == [2:3, 8:8])
@test (intersect!(rs, $TypeURSS{$K}((2:3, 5:6, 8:8))); rs == [2:3, 8:8])
rs = Set((0:0, 2:4, 8:10, 12:12))
@test (intersect(rs, $TypeURSS{$K}((2:3, 5:6, 8:8))) == Set((2:3, 8:8)))
@test (intersect!(rs, $TypeURSS{$K}((2:3, 5:6, 8:8))); rs == Set((2:3, 8:8)))
rs = SortedSet((0:0, 2:4, 8:10, 12:12))
@test (intersect(rs, $TypeURSS{$K}((2:3, 5:6, 8:8))) == SortedSet((2:3, 8:8)))
@test (intersect!(rs, $TypeURSS{$K}((2:3, 5:6, 8:8))); rs == SortedSet((2:3, 8:8)))
rs = [0, 2,3,4, 8,9,10, 12]
@test (intersect(rs, $TypeURSS{$K}((2:3, 5:6, 8:8))) == [2,3, 8])
@test (intersect!(rs, $TypeURSS{$K}((2:3, 5:6, 8:8))); rs == [2,3, 8])
rs = Set((0, 2,3,4, 8,9,10, 12))
@test (intersect(rs, $TypeURSS{$K}((2:3, 5:6, 8:8))) == Set((2,3, 8)))
@test (intersect!(rs, $TypeURSS{$K}((2:3, 5:6, 8:8))); rs == Set((2,3, 8)))
rs = SortedSet((0, 2,3,4, 8,9,10, 12))
@test (intersect(rs, $TypeURSS{$K}((2:3, 5:6, 8:8))) == SortedSet((2,3, 8)))
@test (intersect!(rs, $TypeURSS{$K}((2:3, 5:6, 8:8))); rs == SortedSet((2,3, 8)))
rs = $TypeURSS{$K}((2:3, 5:6, 8:8))
@test (intersect!(rs, convertinfer($K, [0:0, 2:4, 8:10, 12:12])); rs == $TypeURSS{$K}((2:3, 8:8)))
rs = $TypeURSS{$K}((2:3, 5:6, 8:8))
@test (intersect!(rs, convertinfer($K, [0, 2,3,4, 8,9,10, 12])); rs == $TypeURSS{$K}((2:3, 8:8)))
rs = $TypeURSS{$K}((2:3, 5:6, 8:8))
@test (intersect!(rs, Set(convertinfer($K, [0:0, 2:4, 8:10, 12:12]))); rs == $TypeURSS{$K}((2:3, 8:8)))
rs = $TypeURSS{$K}((2:3, 5:6, 8:8))
@test (intersect!(rs, Set(convertinfer($K, [0, 2,3,4, 8,9,10, 12]))); rs == $TypeURSS{$K}((2:3, 8:8)))
rs = $TypeURSS{$K}((2:3, 5:6))
@test (setdiff(rs, Set(2:2)) == $TypeURSS{$K}((3:3, 5:6)))
@test (setdiff(rs, OrderedSet(2:2)) == $TypeURSS{$K}((3:3, 5:6)))
@test (setdiff(rs, 2:2) == $TypeURSS{$K}((3:3, 5:6)))
@test (setdiff(rs, 2:2, 3:5) == $TypeURSS{$K}((6:6,)))
rs1 = $TypeURSS{$K}((2:3, 5:6))
rs2 = $TypeURSS{$K}((3:3, 5:6, 8:8))
@inferred symdiff(rs1, rs2)
@test collect(Iterators.flatten(symdiff(rs1, rs2))) ==
symdiff(collect(Iterators.flatten(rs1)), collect(Iterators.flatten(rs2)))
@test collect(Iterators.flatten(symdiff(rs1, rs2, (9:9,)))) ==
symdiff(collect(Iterators.flatten(rs1)), collect(Iterators.flatten(rs2)), collect($K, Iterators.flatten((9:9,))))
@test collect(Iterators.flatten(symdiff(rs1, (1:9,)))) ==
symdiff(collect(Iterators.flatten(rs1)), collect($K, Iterators.flatten((1:9,))))
rs = $TypeURSS{$K}((0:0, 2:4))
@test (union!(rs, $TypeURSS{$K}((0:0, 6:6))); rs == $TypeURSS{$K}((0:0, 2:4, 6:6)))
@test pop!(rs, 0) == convertinfer($K, 0:0)
@test_throws KeyError pop!(rs, 0)
@test pop!(rs, 0, UInt64(1)) === UInt64(1)
@test pop!(rs, 2, UInt64(1)) === convertinfer($K, 2:2)
@test pop!(rs, 2, UInt64(1)) === UInt64(1)
@test pop!(rs, 3:3) == convertinfer($K, 3:3)
@test_throws KeyError pop!(rs, 3:3)
@test pop!(rs, 3:3, UInt64(1)) === UInt64(1)
@test rs == $TypeURSS{$K}((4:4, 6:6))
@test pop!(rs, 4:4, UInt64(1)) == convertinfer($K, 4:4)
@test pop!(rs, 4:4, UInt64(1)) === UInt64(1)
@test size(rs) == (1,)
@test isempty(rs) == false
@test empty(rs) == $TypeURSS{$K}()
empty!(rs)
@test rs == $TypeURSS{$K}()
@test size(rs) == (0,)
@test isempty(rs) == true
rs = $TypeURSS{$K}((0:0, 2:4))
@test issubset(0, rs)
@test issubset(0:0, rs)
@test !issubset(0:1, rs)
@test !issubset([0:1, 2:4], rs)
@test issubset(rs, convertinfer($K, [0:1, 2:4]))
@test issubset([0:0, 2:4], rs)
@test issubset(rs, convertinfer($K, [0:0, 2:4]))
@test !issubset(rs, convertinfer($K, [0:0, 3:4]))
@test issubset(rs, convertinfer($K, 0:4))
@test !issubset(rs, convertinfer($K, 0:3))
rs2 = copy(rs)
@test rs2 == rs && rs2 !== rs
@test issubset(rs2, rs)
@test issubset(rs, rs2)
delete!(rs2, 0)
@test issubset(rs2, rs)
@test !issubset(rs, rs2)
end
end
end
end
@testset "Iter allocations" begin
for TypeURSS in list_of_containers_types_to_test
@eval rs = $TypeURSS{UInt16}((1:6, 8:16))
@test (@ballocated (for r in $rs j += 1 end) setup = (j = 0)) == 0
@test (@ballocated (for r in $rs, i in r j += Int(i) end) setup = (j = 0)) == 0
@test (@ballocated (for i in Iterators.flatten($rs) j += Int(i) end) setup = (j = 0)) == 0
ss = subset(rs, 4:10)
@test (@ballocated (for r in $ss j += 1 end) setup = (j = 0)) == 0
@test (@ballocated (for r in $ss, i in r j += Int(i) end) setup = (j = 0)) == 0
@test (@ballocated (for i in Iterators.flatten($ss) j += Int(i) end) setup = (j = 0)) == 0
ss1 = subset(rs, 2:6)
@test (@ballocated (for r in $ss1 j += 1 end) setup = (j = 0)) == 0
@test (@ballocated (for r in $ss1, i in r j += Int(i) end) setup = (j = 0)) == 0
@test (@ballocated (for i in Iterators.flatten($ss1) j += Int(i) end) setup = (j = 0)) == 0
ss0 = subset(rs, 7:7)
@test (@ballocated (for r in $ss0 j += 1 end) setup = (j = 0)) == 0
@test (@ballocated (for r in $ss0, i in r j += Int(i) end) setup = (j = 0)) == 0
@test (@ballocated (for i in Iterators.flatten($ss0) j += Int(i) end) setup = (j = 0)) == 0
ss0 = subset(rs, 5:4)
@test (@ballocated (for r in $ss0 j += 1 end) setup = (j = 0)) == 0
@test (@ballocated (for r in $ss0, i in r j += Int(i) end) setup = (j = 0)) == 0
@test (@ballocated (for i in Iterators.flatten($ss0) j += Int(i) end) setup = (j = 0)) == 0
end
end
@testset "`show`" begin
for K in list_of_Ti_to_test
for TypeURSS in list_of_containers_types_to_test
@eval begin
io = IOBuffer()
rs = $TypeURSS{$K}((0:0, 2:4))
show(io, rs)
TT = $TypeURSS
KK = $K
@test String(take!(io)) == "$TT{$KK}(" *
repr($K(0)) * ":" * repr($K(0)) * ", " *
repr($K(2)) * ":" * repr($K(4)) * ")"
io = IOBuffer()
rs = $TypeURSS{$K}((0:0, 2:4))
show(io, MIME("text/plain"), rs)
TT = $TypeURSS
KK = $K
pad = UnitRangesSortedSets.get_max_pad(rs)
if length(rs) == 0
@test String(take!(io)) == "$TT{$KK}()\n"
elseif length(rs) == 1
@test String(take!(io)) == "$TT{$KK} with 1 element:\n" *
" " * " "^(pad-length(repr($K(0)))) * repr($K(0)) * ":" * repr($K(0)) * "\n" *
" " * " "^(pad-length(repr($K(2)))) * repr($K(2)) * ":" * repr($K(4))
else
@test String(take!(io)) == "$TT{$KK} with $(length(rs)) elements:\n" *
" " * " "^(pad-length(repr($K(0)))) * repr($K(0)) * ":" * repr($K(0)) * "\n" *
" " * " "^(pad-length(repr($K(2)))) * repr($K(2)) * ":" * repr($K(4))
end
end
end
end
end
@testset "Bugs" begin
@testset "#5" begin
for TypeURSS in list_of_containers_types_to_test
@eval begin
# provided by https://github.com/mnemnion
tamil = Any['ꣳ', '௦':'௯', '௰':'௲', '௳', '𑌁', '𑌃', '𑌻':'𑌼', '𑿐':'𑿑', '𑿓', '᳚', '॒', '॑', '।', '॥']
URvec = $TypeURSS[]
for elem in tamil
push!(URvec, $TypeURSS([elem]))
end
@test_nowarn reduce(union, URvec)
@test reduce(union, URvec) == $TypeURSS{Char}(('॑':'॒', '।':'॥', '௦':'௳', '᳚':'᳚', 'ꣳ':'ꣳ', '𑌁':'𑌁', '𑌃':'𑌃', '𑌻':'𑌼', '𑿐':'𑿑', '𑿓':'𑿓',))
end
end
end
end
| UnitRangesSortedSets | https://github.com/denius/UnitRangesSortedSets.jl.git |
|
[
"MIT"
] | 0.1.2 | f0de74163ea91daf9565c5b209506ce18a2d6d67 | code | 9801 |
using BenchmarkTools
using DataFrames
using DataStructures
using PrettyTables
using Random
using UnitRangesSortedSets
using Unitful
#
# Testing functions
#
function testfun_create(T::Type, N = 1_000_000, density = 0.9)
rs = T()
Random.seed!(1234)
randseq = randsubseq(1:N, density)
rrandseq = shuffle(randseq)
for (j,i) in enumerate(rrandseq)
push!(rs, i)
end
for i in randseq
in(i, rs) || println("Not coincide on index $i")
end
sum(length(r) for r in rs) == length(randseq) || println("Lost some indices")
rs
end
function testfun_create_cons(T::Type, N = 1_000_000, density = 0.9)
rs = T()
Random.seed!(1234)
randseq = randsubseq(1:N, density)
for i in randseq
push!(rs, i)
end
for i in randseq
in(i, rs) || println("Not coincide on index $i")
end
sum(length(r) for r in rs) == length(randseq) || println("Lost some indices")
rs
end
function testfun_create_ext(T::Type, idx)
rs = T()
for i in idx
push!(rs, i)
end
rs
end
function testfun_create_dense(T::Type, N = 1_000_000, nchunks = 800, density = 0.95)
rs = T()
chunklen = max(1, floor(Int, N / nchunks))
Random.seed!(1234)
for i = 0:nchunks-1
len = floor(Int, chunklen*density + randn() * chunklen * min(0.1, (1.0-density), density))
len = max(1, min(chunklen-2, len))
for j = 1:len
push!(rs, i*chunklen + j)
end
end
rs
end
function testfun_delete!(rs)
Random.seed!(1234)
indices = shuffle([x for r in rs for x in r])
for i in indices
delete!(rs, i)
end
length(rs) == 0 || println("Not all elements deleted")
rs
end
function testfun_in(rs)
start = first(first(rs))
stop = last(last(rs))
Random.seed!(1234)
indices = shuffle(collect(start:stop))
num = 0
for i in indices
in(i, rs) && (num += 1)
end
num
end
function testfun_in_ext(rs, idx)
num = 0
for i in idx
in(i, rs) && (num += 1)
end
num
end
function testfun_in_rand(rs)
len = sum(length(r) for r in rs)
Random.seed!(1234)
num = 0
for j = 1:len
i = rand(1:len)
in(i, rs) && (num += 1)
end
num
end
function testfun_in_cons(rs)
start = first(first(rs))
stop = last(last(rs))
num = 0
for i in start:stop
in(i, rs) && (num += 1)
end
num
end
function testfun_iter_cons(rs::AbstractUnitRangesSortedSet, N = length(rs))
num = 0
for r in rs, i in r
num += 1
end
num
end
function testfun_iter_cons(rs::Union{BitSet,SortedSet}, N = 0)
num = 0
for i in rs
num += 1
end
num
end
function testfun_iter_cons(rs::Set, N)
num = 0
inrange = false
for i = 1:N
in(i, rs) && (num += 1)
end
num
end
function testfun_iter_ranges(rs::AbstractUnitRangesSortedSet, N = length(rs))
num = 0
for r in rs
num += 1
end
num
end
function testfun_iter_ranges(rs::Union{BitSet,SortedSet}, N = 0)
num = 0
prev = first(rs)
for i in rs
if i != prev + 1
num += 1
end
prev = i
end
num
end
function testfun_iter_ranges(rs::Set, N)
num = 0
inrange = false
for i = 1:N
if in(i, rs) && inrange
continue
elseif in(i, rs) && !inrange
inrange = true
num += 1
elseif !in(i, rs) && inrange
inrange = false
else # !in(i, rs) && !inrange
continue
end
end
num
end
function output_results(results)
println("\nSizes:")
PrettyTables.pretty_table(results[:sz ], tf=PrettyTables.tf_markdown)
println("\nIterate ranges consecutively, ms:")
PrettyTables.pretty_table(results[:iter_ranges], tf=PrettyTables.tf_markdown)
println("\nIterate elements consecutively, ms:")
PrettyTables.pretty_table(results[:iter_con ], tf=PrettyTables.tf_markdown)
println("\nFill element-wise consecutively, ms:")
PrettyTables.pretty_table(results[:fill_con ], tf=PrettyTables.tf_markdown)
println("\nAccess element-wise consecutively (time per element, ns):")
PrettyTables.pretty_table(results[:accss_con ], tf=PrettyTables.tf_markdown)
println("\nFill element-wise in random order of elements, ms:")
PrettyTables.pretty_table(results[:fill_rnd ], tf=PrettyTables.tf_markdown)
println("\nAccess element-wise randomly (time per element, ns):")
PrettyTables.pretty_table(results[:accss_rnd ], tf=PrettyTables.tf_markdown)
nothing
end
function run_bench(name, N, indices, results, verbose = false)
indices = sort(indices)
Random.seed!(1234)
rnd_indices = shuffle(indices)
sizes = []
push!(sizes, name)
push!(sizes, length(indices))
push!(sizes, length(testfun_create_ext(UnitRangesSortedSet{Int}, indices)))
println("\nSizes:")
for T in (BitSet, Set{Int}, SortedSet{Int}, UnitRangesSortedSet{Int}, VecUnitRangesSortedSet{Int})
push!(sizes, Base.summarysize( testfun_create_ext(T, indices) ) )
end
push!(results[:sz], sizes)
verbose && PrettyTables.pretty_table(results[:sz], tf=PrettyTables.tf_markdown)
times_ir,
times_ic,
times_fc,
times_ac,
times_fr,
times_ar = ntuple(_->Any[name, length(indices), length(testfun_create_ext(UnitRangesSortedSet{Int}, indices))], 6)
for T in (BitSet, Set{Int}, SortedSet{Int}, UnitRangesSortedSet{Int}, VecUnitRangesSortedSet{Int})
@sync begin
# Iterate ranges consecutively, ms
Threads.@spawn push!(times_ir, round(sigdigits=3, mean( @benchmark testfun_iter_ranges(r, $N) setup = (r = testfun_create_ext($T, $indices) ) ; ).time / 1e6))
# Iterate elements consecutively, ms
Threads.@spawn push!(times_ic, round(sigdigits=3, mean( @benchmark testfun_iter_cons(r, $N) setup = (r = testfun_create_ext($T, $indices) ) ; ).time / 1e6))
# Fill element-wise consecutively, ms
Threads.@spawn push!(times_fc, round(sigdigits=3, mean( @benchmark testfun_create_ext($T, $indices) ; ).time / 1e6))
# Access element-wise consecutively (time per element, ns
Threads.@spawn push!(times_ac, round(sigdigits=3, mean( @benchmark testfun_in_ext(r, $indices) setup = (r = testfun_create_ext($T, $indices) ) ; ).time / N))
# Fill element-wise in random order of elements, ms
Threads.@spawn push!(times_fr, round(sigdigits=3, mean( @benchmark testfun_create_ext($T, $rnd_indices) ; ).time / 1e6))
# Access element-wise randomly (time per element, ns)
Threads.@spawn push!(times_ar, round(sigdigits=3, mean( @benchmark testfun_in_ext(r, $rnd_indices) setup = (r = testfun_create_ext($T, $indices) ) ; ).time / N))
end
end
push!(results[:iter_ranges], times_ir)
push!(results[:iter_con], times_ic)
push!(results[:fill_con], times_fc)
push!(results[:accss_con], times_ac)
push!(results[:fill_rnd], times_fr)
push!(results[:accss_rnd], times_ar)
verbose && output_results(results)
end
function run_benches(N = 1_000_000; verbose = false)
# Size, bytes => Int,
sz = DataFrame("ρ, %" => Float64[],
"nelems" => Int[],
"nranges" => Int[],
"BitSet" => Int[],
"Set" => Int[],
"SortedSet" => Int[],
"URSSet" => Int[],
"VURSSet" => Int[]
)
iter_ranges,
iter_con,
fill_con,
accss_con,
fill_rnd,
accss_rnd = ntuple(_->DataFrame("ρ, %" => Float64[],
"nelems" => Int[],
"nranges" => Int[],
"BitSet" => Float64[],
"Set" => Float64[],
"SortedSet" => Float64[],
"URSSet" => Float64[],
"VURSSet" => Float64[]
)
, 6)
results = Dict((
:sz => sz,
:iter_ranges => iter_ranges,
:iter_con => iter_con,
:fill_con => fill_con,
:accss_con => accss_con,
:fill_rnd => fill_rnd,
:accss_rnd => accss_rnd
))
for density in (0.001, 0.01, 0.1, 1.0, 10.0, 50.0, 90., 99.0, 99.9, 99.99, 99.999)
fraction = density / 100.0
println("\n\ndensity = ", density, "%")
nchunks = 1000
chunklen = max(1, floor(Int, N / nchunks))
Random.seed!(1234)
indices = Int[]
for i = 0:nchunks-1
len = floor(Int, chunklen*fraction + randn() * chunklen * min(0.1, (1.0-fraction), fraction))
len = max(1, min(chunklen-2, len))
for j = 1:len
push!(indices, i*chunklen + j)
end
end
indices = unique(sort(indices))
indices[1] != 1 && prepend!(indices, 1)
indices[end] != N && append!(indices, N)
run_bench(density, N, indices, results, verbose)
end
output_results(results)
for density in (0.001, 0.01, 0.1, 1.0, 10.0, 50.0, 90., 99.0, 99.9, 99.99, 99.999)
println("\n\ndensity = ", density, "%")
Random.seed!(1234)
indices = randsubseq(1:N, density / 100.0)
indices[1] != 1 && prepend!(indices, 1)
indices[end] != N && append!(indices, N)
run_bench(density, N, indices, results, verbose)
end
output_results(results)
end
| UnitRangesSortedSets | https://github.com/denius/UnitRangesSortedSets.jl.git |
|
[
"MIT"
] | 0.1.2 | f0de74163ea91daf9565c5b209506ce18a2d6d67 | docs | 4458 | # UnitRangesSortedSets
[](https://github.com/denius/UnitRangesSortedSets.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/denius/UnitRangesSortedSets.jl)
Sorted set of `UnitRange`s. Sorted in ascending order and no one range overlaps with another.
mutable struct UnitRangesSortedSet{K, TU} <: AbstractSet{TU}
`UnitRangesSortedSet` can be created like the standard `Set`:
```julia
UnitRangesSortedSet(somecontainer)
```
for example:
```julia
julia> using UnitRangesSortedSets
julia> UnitRangesSortedSet((1, 2, 4))
UnitRangesSortedSet{Int64} with 2 elements:
1:2
4:4
julia> UnitRangesSortedSet(('a':'z', 'α':'ω'))
UnitRangesSortedSet{Char} with 2 elements:
'a':'z'
'α':'ω'
julia> Random.seed!(1234);
julia> UnitRangesSortedSet(rand(1:20, 10))
UnitRangesSortedSet{Int64} with 6 elements:
5:5
7:8
10:11
15:16
18:18
20:20
```
or with `push!`:
```julia
julia> urs = UnitRangesSortedSet{Int}()
UnitRangesSortedSet{Int64}()
julia> push!(urs, 1)
UnitRangesSortedSet{Int64} with 1 element:
1:1
julia> push!(urs, 2)
UnitRangesSortedSet{Int64} with 1 element:
1:2
julia> push!(urs, 10:12)
UnitRangesSortedSet{Int64} with 2 elements:
1:2
10:12
```
Iterating over set of ranges:
```julia
julia> for r in urs @show(r) end
r = 1:2
r = 10:12
julia> for r in urs, i in r @show(i) end
i = 1
i = 2
i = 10
i = 11
i = 12
julia> for i in Iterators.flatten(urs) @show(i) end
i = 1
i = 2
i = 10
i = 11
i = 12
julia> collect(urs)
2-element Vector{UnitRange{Int64}}:
1:2
10:12
```
Deleting elements and ranges:
```julia
julia> delete!(urs, 10:11)
UnitRangesSortedSet{Int64} with 2 elements:
1:2
12:12
julia> delete!(urs, 1)
UnitRangesSortedSet{Int64} with 2 elements:
2:2
12:12
```
# SubSet
It is possible to create the subset of `UnitRangesSortedSet`, like a `view` for `Array`s:
```julia
julia> urs = UnitRangesSortedSet((1:2, 10:12))
UnitRangesSortedSet{Int64} with 2 elements:
1:2
10:12
julia> ss = subset(urs, 0:10)
2-element subset(UnitRangesSortedSet{Int64}, DataStructures.Tokens.IntSemiToken(3):DataStructures.Tokens.IntSemiToken(4)):
1:2
10:10
```
The `subset` object is an static, iterable view of the container.
# Two types of `UnitRangesSortedSet`
The first type `UnitRangesSortedSet{K}` contains `SortedDict{K,K}`,
```julia
mutable struct UnitRangesSortedSet{K,TU} <: AbstractUnitRangesSortedContainer{K,TU}
ranges::SortedDict{K,K,FOrd}
end
```
where each element of the dict contains the `first(range)` as key, and the `last(range)` as value.
The second implementation `VecUnitRangesSortedSet{K}` is based on `Vector{K}`s:
```julia
mutable struct VecUnitRangesSortedSet{K,TU} <: AbstractUnitRangesSortedContainer{K,TU}
rstarts::Vector{K}
rstops::Vector{K}
end
```
where `rstarts::Vector{K}` and `rstops::Vector{K}` are the starts and stops of
the ranges respectively.
These two implementations have a similar API but different speeds.
In either case, both of them can be converted to each other using the appropriate constructor.
# Benchmarking
All results of benchmarks in the file [test-bench-results.md](test/test-bench-results.md).
Main conclusions of benchmarking:
* in any case of iterating over `range`s or consecutively element-wise in any `AbstractUnitRangesSortedSet` is
much much faster then in any another variant.
* element-wise iterating, and over ranges iterating, in `VecUnitRangesSortedSet` is faster by
the orders over `UnitRangesSortedSet`.
* when created from elements in random order, `UnitRangesSortedSet` is vastly superior
to the `Vec` variant.
* creating in consecutively element-wise order, `VecUnitRangesSortedSet` is an order of magnitude faster
than creating a set of the second type.
* in searching operations (`in()`, `subset()`) `VecUnitRangesSortedSet` variant is faster:
in Julia-v1.6 it is twice as fast, in Julia-1.8 the speedup is about 20-30%.
* if your range diapason is about some millions of elements then the `BitSet` is the best choice
for creating. And then `convert(UnitRangesSortedSet, someBitSetContainer)` is the solution to
have the fast iteration over container.
### Note
For `Char`, `StepRange{Char,UInt8}` will be used, with a step of `oneunit(UInt8)` if needed.
| UnitRangesSortedSets | https://github.com/denius/UnitRangesSortedSets.jl.git |
|
[
"MIT"
] | 0.1.2 | f0de74163ea91daf9565c5b209506ce18a2d6d67 | docs | 14405 | Sizes, bytes:
| ρ, % | elements | ranges | BitSet | Set | SortedSet | URSSet | VURSSet |
|---------|--------|--------|--------|----------|-----------|----------|---------|
| 0.001 | 1001 | 1001 | 125064 | 37056 | 64360 | 72400 | 16120 |
| 0.01 | 1001 | 1001 | 125064 | 37056 | 64360 | 72400 | 16120 |
| 0.1 | 1193 | 1001 | 125064 | 37056 | 76768 | 72400 | 16120 |
| 1.0 | 10497 | 1001 | 125064 | 147648 | 673440 | 72400 | 16120 |
| 10.0 | 106832 | 1001 | 125064 | 2359488 | 6850824 | 72400 | 16120 |
| 50.0 | 498341 | 1001 | 125064 | 9437376 | 31956096 | 72400 | 16120 |
| 90.0 | 889750 | 1001 | 125064 | 18874560 | 57055296 | 72400 | 16120 |
| 99.0 | 988290 | 1001 | 125064 | 18874560 | 63374272 | 72400 | 16120 |
| 99.9 | 997815 | 1001 | 125064 | 18874560 | 63984816 | 72400 | 16120 |
| 99.99 | 998001 | 1001 | 125064 | 18874560 | 63996744 | 72400 | 16120 |
| 99.999 | 998001 | 1001 | 125064 | 18874560 | 63996744 | 72400 | 16120 |
| 0.001 | 13 | 13 | 125064 | 768 | 1200 | 1336 | 312 |
| 0.01 | 90 | 90 | 125064 | 2496 | 6136 | 6888 | 1544 |
| 0.1 | 985 | 985 | 125064 | 37056 | 63336 | 71248 | 15864 |
| 1.0 | 10126 | 10014 | 125064 | 147648 | 649600 | 722608 | 160328 |
| 10.0 | 99784 | 89966 | 125064 | 2359488 | 6398824 | 6488904 | 1439560 |
| 50.0 | 499795 | 249673 | 125064 | 9437376 | 32049480 | 18007680 | 3994872 |
| 90.0 | 900008 | 89882 | 125064 | 18874560 | 57712944 | 6482848 | 1438216 |
| 99.0 | 989970 | 9934 | 125064 | 18874560 | 63481904 | 716792 | 159048 |
| 99.9 | 998975 | 1025 | 125064 | 18874560 | 64059304 | 74376 | 16504 |
| 99.99 | 999898 | 103 | 125064 | 18874560 | 64118488 | 7824 | 1752 |
| 99.999 | 999985 | 16 | 125064 | 18874560 | 64124112 | 1648 | 360 |
Iterate ranges consecutively, ms:
| ρ, % | elements | ranges | BitSet | Set | SortedSet | URSSet | VURSSet |
|---------|--------|--------|---------|---------|-----------|----------|----------|
| 0.001 | 1001 | 1001 | 0.0147 | 36.2 | 0.0182 | 0.0179 | 3.63e-5 |
| 0.01 | 1001 | 1001 | 0.0147 | 33.8 | 0.0183 | 0.0189 | 3.94e-5 |
| 0.1 | 1193 | 1001 | 0.0157 | 30.6 | 0.0217 | 0.019 | 3.83e-5 |
| 1.0 | 10497 | 1001 | 0.0294 | 53.6 | 0.202 | 0.0188 | 3.93e-5 |
| 10.0 | 106832 | 1001 | 0.154 | 41.1 | 3.0 | 0.0179 | 3.74e-5 |
| 50.0 | 498341 | 1001 | 0.649 | 52.5 | 15.8 | 0.0234 | 4.13e-5 |
| 90.0 | 889750 | 1001 | 1.13 | 54.9 | 25.6 | 0.0243 | 3.95e-5 |
| 99.0 | 988290 | 1001 | 1.25 | 40.3 | 29.1 | 0.0262 | 3.94e-5 |
| 99.9 | 997815 | 1001 | 1.27 | 37.9 | 29.2 | 0.025 | 3.92e-5 |
| 99.99 | 998001 | 1001 | 1.26 | 51.7 | 28.9 | 0.0289 | 3.97e-5 |
| 99.999 | 998001 | 1001 | 1.26 | 53.2 | 29.3 | 0.0256 | 3.8e-5 |
| 0.001 | 13 | 13 | 0.00848 | 34.7 | 0.000251 | 0.000242 | 2.46e-5 |
| 0.01 | 90 | 90 | 0.00958 | 35.4 | 0.00154 | 0.00154 | 3.76e-5 |
| 0.1 | 985 | 985 | 0.0153 | 28.4 | 0.0188 | 0.0191 | 5.15e-5 |
| 1.0 | 10126 | 10014 | 0.077 | 45.9 | 0.189 | 0.193 | 0.00022 |
| 10.0 | 99784 | 89966 | 0.206 | 45.1 | 2.82 | 2.54 | 0.0015 |
| 50.0 | 499795 | 249673 | 0.687 | 63.3 | 14.6 | 7.3 | 0.00412 |
| 90.0 | 900008 | 89882 | 1.17 | 54.5 | 26.6 | 2.67 | 0.00152 |
| 99.0 | 989970 | 9934 | 1.27 | 53.2 | 29.3 | 0.204 | 0.000191 |
| 99.9 | 998975 | 1025 | 1.26 | 40.6 | 29.5 | 0.0295 | 5.17e-5 |
| 99.99 | 999898 | 103 | 1.26 | 53.1 | 29.1 | 0.00188 | 1.22e-5 |
| 99.999 | 999985 | 16 | 1.26 | 49.5 | 28.3 | 0.000327 | 2.65e-5 |
Iterate elements consecutively, ms:
| ρ, % | elements | ranges | BitSet | Set | SortedSet | URSSet | VURSSet |
|---------|--------|--------|---------|---------|-----------|----------|----------|
| 0.001 | 1001 | 1001 | 0.0142 | 14.5 | 0.0168 | 0.02 | 0.00177 |
| 0.01 | 1001 | 1001 | 0.014 | 14.0 | 0.0166 | 0.02 | 0.00171 |
| 0.1 | 1193 | 1001 | 0.0156 | 15.5 | 0.019 | 0.0202 | 0.00171 |
| 1.0 | 10497 | 1001 | 0.0257 | 23.1 | 0.178 | 0.0202 | 0.0017 |
| 10.0 | 106832 | 1001 | 0.081 | 21.0 | 2.71 | 0.0204 | 0.00171 |
| 50.0 | 498341 | 1001 | 0.285 | 40.9 | 13.0 | 0.0208 | 0.00173 |
| 90.0 | 889750 | 1001 | 0.479 | 49.2 | 22.4 | 0.0265 | 0.00176 |
| 99.0 | 988290 | 1001 | 0.517 | 49.8 | 27.0 | 0.0283 | 0.00177 |
| 99.9 | 997815 | 1001 | 0.527 | 50.8 | 27.6 | 0.0295 | 0.00184 |
| 99.99 | 998001 | 1001 | 0.525 | 40.5 | 26.3 | 0.028 | 0.00173 |
| 99.999 | 998001 | 1001 | 0.562 | 50.6 | 26.5 | 0.0289 | 0.00174 |
| 0.001 | 13 | 13 | 0.0137 | 13.5 | 0.000219 | 0.000256 | 4.67e-5 |
| 0.01 | 90 | 90 | 0.0152 | 16.4 | 0.00137 | 0.00176 | 0.000174 |
| 0.1 | 985 | 985 | 0.0194 | 14.6 | 0.0162 | 0.02 | 0.00166 |
| 1.0 | 10126 | 10014 | 0.0826 | 22.6 | 0.176 | 0.166 | 0.017 |
| 10.0 | 99784 | 89966 | 0.154 | 22.7 | 2.63 | 2.8 | 0.166 |
| 50.0 | 499795 | 249673 | 0.342 | 39.5 | 12.6 | 7.3 | 0.461 |
| 90.0 | 900008 | 89882 | 0.54 | 40.7 | 24.4 | 2.7 | 0.164 |
| 99.0 | 989970 | 9934 | 0.552 | 50.9 | 27.6 | 0.256 | 0.0184 |
| 99.9 | 998975 | 1025 | 0.524 | 51.7 | 27.3 | 0.0283 | 0.00179 |
| 99.99 | 999898 | 103 | 0.522 | 51.7 | 27.4 | 0.00197 | 0.000204 |
| 99.999 | 999985 | 16 | 0.522 | 50.9 | 27.1 | 0.000315 | 5.22e-5 |
Fill element-wise consecutively, ms:
| ρ, % | elements | ranges | BitSet | Set | SortedSet | URSSet | VURSSet |
|---------|--------|--------|---------|---------|-----------|---------|---------|
| 0.001 | 1001 | 1001 | 0.0753 | 0.0647 | 0.125 | 0.215 | 0.0549 |
| 0.01 | 1001 | 1001 | 0.0471 | 0.475 | 0.163 | 0.214 | 0.0527 |
| 0.1 | 1193 | 1001 | 0.0498 | 0.0607 | 0.154 | 0.231 | 0.0604 |
| 1.0 | 10497 | 1001 | 0.154 | 0.471 | 1.44 | 1.79 | 0.302 |
| 10.0 | 106832 | 1001 | 0.524 | 4.56 | 20.6 | 8.44 | 3.44 |
| 50.0 | 498341 | 1001 | 1.8 | 42.4 | 143.0 | 33.9 | 10.8 |
| 90.0 | 889750 | 1001 | 3.04 | 61.1 | 269.0 | 133.0 | 71.6 |
| 99.0 | 988290 | 1001 | 5.27 | 328.0 | 428.0 | 123.0 | 30.0 |
| 99.9 | 997815 | 1001 | 4.4 | 76.3 | 159.0 | 1160.0 | 16.9 |
| 99.99 | 998001 | 1001 | 4.34 | 155.0 | 623.0 | 174.0 | 20.5 |
| 99.999 | 998001 | 1001 | 3.44 | 58.0 | 230.0 | 68.2 | 27.8 |
| 0.001 | 13 | 13 | 0.277 | 0.0124 | 0.00372 | 0.00459 | 0.00152 |
| 0.01 | 90 | 90 | 0.237 | 0.00368 | 0.0098 | 0.0157 | 0.00661 |
| 0.1 | 985 | 985 | 0.0918 | 0.037 | 0.27 | 0.206 | 0.0652 |
| 1.0 | 10126 | 10014 | 0.297 | 0.463 | 14.7 | 8.49 | 0.569 |
| 10.0 | 99784 | 89966 | 1.51 | 167.0 | 24.4 | 25.7 | 14.5 |
| 50.0 | 499795 | 249673 | 2.0 | 28.7 | 1110.0 | 827.0 | 24.2 |
| 90.0 | 900008 | 89882 | 3.51 | 74.8 | 605.0 | 247.0 | 15300.0 |
| 99.0 | 989970 | 9934 | 3.83 | 82.2 | 454.0 | 96.0 | 26.1 |
| 99.9 | 998975 | 1025 | 4.36 | 118.0 | 1410.0 | 152.0 | 22.3 |
| 99.99 | 999898 | 103 | 3.6 | 65.4 | 1210.0 | 59.7 | 19.2 |
| 99.999 | 999985 | 16 | 2.48 | 87.0 | 425.0 | 1500.0 | 19.3 |
Access element-wise consecutively (time per element, ns):
| ρ, % | elements | ranges | BitSet | Set | SortedSet | URSSet | VURSSet |
|---------|--------|--------|----------|----------|-----------|----------|----------|
| 0.001 | 1001 | 1001 | 0.000863 | 0.011 | 0.0203 | 0.0293 | 0.0316 |
| 0.01 | 1001 | 1001 | 0.000862 | 0.011 | 0.0206 | 0.0299 | 0.0316 |
| 0.1 | 1193 | 1001 | 0.000972 | 0.0133 | 0.0255 | 0.0325 | 0.0367 |
| 1.0 | 10497 | 1001 | 0.0068 | 0.179 | 0.293 | 0.076 | 0.0595 |
| 10.0 | 106832 | 1001 | 0.0656 | 2.06 | 4.79 | 0.452 | 0.248 |
| 50.0 | 498341 | 1001 | 0.302 | 22.0 | 26.1 | 1.98 | 1.09 |
| 90.0 | 889750 | 1001 | 0.551 | 43.1 | 51.0 | 3.58 | 1.89 |
| 99.0 | 988290 | 1001 | 0.584 | 48.1 | 56.1 | 3.9 | 2.08 |
| 99.9 | 997815 | 1001 | 0.603 | 45.7 | 56.2 | 4.24 | 2.1 |
| 99.99 | 998001 | 1001 | 0.74 | 48.1 | 56.9 | 3.97 | 2.14 |
| 99.999 | 998001 | 1001 | 0.616 | 51.3 | 56.9 | 3.98 | 2.1 |
| 0.001 | 13 | 13 | 4.29e-5 | 0.000153 | 0.000103 | 0.000218 | 0.000115 |
| 0.01 | 90 | 90 | 8.65e-5 | 0.000959 | 0.00101 | 0.0017 | 0.000729 |
| 0.1 | 985 | 985 | 0.000777 | 0.0111 | 0.02 | 0.0287 | 0.031 |
| 1.0 | 10126 | 10014 | 0.00692 | 0.167 | 0.281 | 0.4 | 0.381 |
| 10.0 | 99784 | 89966 | 0.0678 | 1.81 | 4.71 | 5.53 | 3.85 |
| 50.0 | 499795 | 249673 | 0.339 | 17.0 | 27.5 | 19.5 | 13.2 |
| 90.0 | 900008 | 89882 | 0.544 | 44.5 | 51.6 | 9.18 | 5.8 |
| 99.0 | 989970 | 9934 | 0.689 | 50.1 | 62.7 | 4.45 | 2.36 |
| 99.9 | 998975 | 1025 | 0.616 | 47.2 | 58.7 | 3.97 | 2.12 |
| 99.99 | 999898 | 103 | 0.601 | 50.8 | 61.2 | 3.94 | 2.04 |
| 99.999 | 999985 | 16 | 0.578 | 48.0 | 64.1 | 3.98 | 1.8 |
Fill element-wise in random order of elements, ms:
| ρ, % | elements | ranges | BitSet | Set | SortedSet | URSSet | VURSSet |
|---------|--------|--------|---------|---------|-----------|---------|---------|
| 0.001 | 1001 | 1001 | 0.0159 | 0.0352 | 0.121 | 0.307 | 0.198 |
| 0.01 | 1001 | 1001 | 0.0136 | 0.12 | 0.288 | 0.505 | 0.156 |
| 0.1 | 1193 | 1001 | 0.031 | 0.195 | 0.227 | 0.281 | 0.175 |
| 1.0 | 10497 | 1001 | 0.0455 | 0.432 | 1.74 | 2.56 | 2.0 |
| 10.0 | 106832 | 1001 | 0.357 | 26.1 | 36.0 | 33.9 | 97.3 |
| 50.0 | 498341 | 1001 | 1.21 | 29.2 | 207.0 | 206.0 | 3080.0 |
| 90.0 | 889750 | 1001 | 1.95 | 81.4 | 424.0 | 400.0 | 10600.0 |
| 99.0 | 988290 | 1001 | 3.08 | 312.0 | 669.0 | 454.0 | 12600.0 |
| 99.9 | 997815 | 1001 | 3.87 | 708.0 | 747.0 | 629.0 | 16000.0 |
| 99.99 | 998001 | 1001 | 2.22 | 85.0 | 464.0 | 448.0 | 12900.0 |
| 99.999 | 998001 | 1001 | 2.48 | 69.9 | 1250.0 | 472.0 | 12800.0 |
| 0.001 | 13 | 13 | 0.264 | 0.0168 | 0.0205 | 0.00946 | 0.00166 |
| 0.01 | 90 | 90 | 0.105 | 0.0227 | 0.0341 | 0.0924 | 0.00925 |
| 0.1 | 985 | 985 | 0.13 | 0.289 | 0.13 | 0.558 | 0.602 |
| 1.0 | 10126 | 10014 | 0.222 | 0.649 | 1.82 | 4.06 | 4.77 |
| 10.0 | 99784 | 89966 | 0.248 | 7.39 | 32.4 | 60.6 | 297.0 |
| 50.0 | 499795 | 249673 | 1.95 | 243.0 | 296.0 | 422.0 | 7940.0 |
| 90.0 | 900008 | 89882 | 8.76 | 1030.0 | 421.0 | 447.0 | 12400.0 |
| 99.0 | 989970 | 9934 | 3.94 | 56.7 | 510.0 | 470.0 | 13000.0 |
| 99.9 | 998975 | 1025 | 2.2 | 90.0 | 442.0 | 468.0 | 13600.0 |
| 99.99 | 999898 | 103 | 9.65 | 59.5 | 438.0 | 726.0 | 13200.0 |
| 99.999 | 999985 | 16 | 2.8 | 287.0 | 715.0 | 480.0 | 12800.0 |
Access element-wise randomly (time per element, ns):
| ρ, % | elements | ranges | BitSet | Set | SortedSet | URSSet | VURSSet |
|---------|--------|--------|----------|----------|-----------|----------|----------|
| 0.001 | 1001 | 1001 | 0.000826 | 0.011 | 0.0278 | 0.0455 | 0.0483 |
| 0.01 | 1001 | 1001 | 0.000821 | 0.011 | 0.027 | 0.0442 | 0.0475 |
| 0.1 | 1193 | 1001 | 0.000952 | 0.0136 | 0.0341 | 0.0518 | 0.0571 |
| 1.0 | 10497 | 1001 | 0.00732 | 0.18 | 0.597 | 0.413 | 0.54 |
| 10.0 | 106832 | 1001 | 0.0759 | 2.08 | 26.4 | 4.18 | 5.46 |
| 50.0 | 498341 | 1001 | 0.364 | 21.8 | 240.0 | 19.7 | 25.7 |
| 90.0 | 889750 | 1001 | 0.669 | 43.4 | 519.0 | 35.0 | 46.2 |
| 99.0 | 988290 | 1001 | 0.743 | 43.3 | 518.0 | 38.8 | 51.5 |
| 99.9 | 997815 | 1001 | 0.961 | 51.8 | 599.0 | 39.4 | 51.7 |
| 99.99 | 998001 | 1001 | 0.861 | 50.1 | 558.0 | 39.0 | 52.2 |
| 99.999 | 998001 | 1001 | 0.797 | 48.9 | 505.0 | 39.4 | 51.7 |
| 0.001 | 13 | 13 | 4.24e-5 | 0.000153 | 0.000102 | 0.000189 | 0.000104 |
| 0.01 | 90 | 90 | 8.7e-5 | 0.000909 | 0.000974 | 0.00159 | 0.000716 |
| 0.1 | 985 | 985 | 0.000748 | 0.011 | 0.0274 | 0.0435 | 0.0465 |
| 1.0 | 10126 | 10014 | 0.00838 | 0.166 | 0.57 | 0.862 | 0.708 |
| 10.0 | 99784 | 89966 | 0.0944 | 1.81 | 24.8 | 25.8 | 9.51 |
| 50.0 | 499795 | 249673 | 0.453 | 20.5 | 209.0 | 162.0 | 57.7 |
| 90.0 | 900008 | 89882 | 0.809 | 40.9 | 489.0 | 157.0 | 80.5 |
| 99.0 | 989970 | 9934 | 0.928 | 51.2 | 576.0 | 65.2 | 69.1 |
| 99.9 | 998975 | 1025 | 0.981 | 51.2 | 587.0 | 36.7 | 51.2 |
| 99.99 | 999898 | 103 | 0.746 | 50.6 | 538.0 | 23.9 | 31.5 |
| 99.999 | 999985 | 16 | 0.881 | 50.8 | 549.0 | 20.0 | 18.4 |
| UnitRangesSortedSets | https://github.com/denius/UnitRangesSortedSets.jl.git |
|
[
"MIT"
] | 1.0.0 | 02b36706c287622dfa105ea2eb4dfa50a50819b4 | code | 5878 | module RawFile
export saveraw,readraw,rawsize,appendraw
export RawFile,RawFileIter,start,done,next
token = "RAWF"
version = 2
endtoken = "FIN"
mutable struct RawHeader
version::UInt8
eltype::Type
sizes::Vector{Int64}
end
import Base.write
function write(f::IO,x::RawHeader)
write(f,token)
write(f,x.version)
typename = string(x.eltype)
write(f,UInt8(length(typename)))
write(f,typename)
write(f,UInt8(length(x.sizes)))
write(f,x.sizes)
return nothing
end
function readheader(f::IO)
tok = String(read(f,length(token)))
tok != token && error("Invalid token in RawFile")
ver = read(f,UInt8)
ver != version && warn("Incorrect RawFile version ($ver, current version $version)")
lentypename = read(f,UInt8)
typename = String(read(f,lentypename))
eltype = eval(Meta.parse(typename))
nd = read(f,UInt8)
sizes = read!(f,Array{Int64}(undef,nd))
RawHeader(ver,eltype,sizes)
end
"""
saveraw{T<:Number,V}(a::AbstractArray{T,V},fname::String)
Save `a` to the file `fname`.
"""
function saveraw(a::AbstractArray{T,V},fname::String) where {T<:Number,V}
header = RawHeader(version,eltype(a),collect(size(a)))
open(fname,"w") do f
write(f,header)
write(f,a)
write(f,endtoken)
end
return nothing
end
"""
appendraw{T<:Number,V}(a::AbstractArray{T,V},fname::String)
Append the `AbstractArray` `a` to the file `fname`, along last dimension. Requires `a` to be the same
`Type` and shape (excluding last dimension)
"""
function appendraw(a::AbstractArray{T,V},fname::String) where {T<:Number,V}
open(fname,"r+") do f
h = readheader(f)
h.eltype != eltype(a) && error("Trying to append RawFile with different data Type")
Tuple(h.sizes[1:end-1]) != size(a)[1:end-1] && error("Trying to append RawFile with Array of different shape")
h.sizes[end] += size(a)[end]
seekstart(f)
write(f,h)
seekend(f)
seek(f,position(f)-length(endtoken))
write(f,a)
write(f,endtoken)
end
return nothing
end
appendraw(a::T,fname::String) where {T<:Number} = appendraw([a],fname)
"""
readraw(fname::String)
Read the file `fname` and return a reconstructed `Array` with the proper `Type` and size.
"""
function readraw(fname::String)
open(fname) do f
h = readheader(f)
d = read!(f,Array{h.eltype}(undef,Tuple(h.sizes)))
endtok = String(read(f,length(endtoken)))
endtok != endtoken && error("Invalid end of RawFile")
return d
end
end
"""
rawsize(fname::String)
Read size from file `fname`, returns `Tuple`
"""
function rawsize(fname::String)
open(fname) do f
h = readheader(f)
return Tuple(h.sizes)
end
end
mutable struct PartialRaw
f::IO
eltype::Type
sizes::Array{Int64,1}
total::Int
end
"""
saveraw(func::Function,fname::String)
Save `Array`s progressively produced in `func`. Each partial `Array` needs to have
the same dimensions (excluding the last dimension), and are concatenated along the
last dimension.
# Examples
```julia-repl
julia> saveraw("test.raw") do f
for i=1:10
write(f,rand(100,10,5))
end
end
julia> rawsize("test.raw")
(100, 10, 50)
```
"""
function saveraw(func::Function,fname::String)
open(fname,"w") do f
p = PartialRaw(f,Int,[],0)
func(p)
write(f,endtoken)
seekstart(f)
p.sizes[end] = p.total
write(f,RawHeader(version,p.eltype,p.sizes))
end
return nothing
end
function write(p::PartialRaw,d::AbstractArray{T,V}) where {T<:Number,V}
if length(p.sizes)==0
# This is the first Array we've seen
p.sizes = collect(size(d))
p.eltype = eltype(d)
write(p.f,RawHeader(version,p.eltype,p.sizes))
else
Tuple(p.sizes[1:end-1]) != size(d)[1:end-1] && error("Cannot write partial RawFile, all dimensions other than the last must be the same")
p.eltype != eltype(d) && error("Cannot write partial RawFile, all data must be the same type")
end
write(p.f,d)
p.total += size(d)[end]
return nothing
end
"""
RawFileIter(fname::String,num_batch::Int)
Creates an interator that will iterate through the file `fname`, returning `Array`s
with the last dimension `num_batch` (or less if EOF is reached).
# Examples
```julia-repl
julia> for d in RawFileIter("test.raw",20)
info(size(d))
end
INFO: (100, 10, 20)
INFO: (100, 10, 20)
INFO: (100, 10, 10)
```
"""
mutable struct RawFileIter
fname::String
num_batch::Int
end
mutable struct RawFileState
i::Int
total_length::Int
num_batch::Int
batch_step::Int
batch_size::Array{Int,1}
f::IO
eltype::Type
end
import Base.iterate,Base.length
function finalize(s::RawFileState)
close(s.f)
end
function iterate(r::RawFileIter)
f = open(r.fname)
h = readheader(f)
batch_step = reduce(*,h.sizes[1:end-1])
total_length = batch_step*h.sizes[end]
batch_size = copy(h.sizes)
i = 0
s = RawFileState(i,total_length,r.num_batch,batch_step,batch_size,f,h.eltype)
finalizer(finalize,s)
return iterate(r,s)
end
function iterate(r::RawFileIter,state::RawFileState)
if state.i < state.total_length
this_len = Int(min(state.num_batch,(state.total_length-state.i)/state.batch_step))
state.batch_size[end] = this_len
d = read!(state.f,Array{state.eltype}(undef,Tuple(state.batch_size)))
state.i += state.batch_step*this_len
return (d,state)
else
endtok = String(read(state.f,length(endtoken)))
endtok != endtoken && error("Invalid end of RawFile")
return nothing
end
end
function readraw(func::Function,fname::String,batch::Int)
for d in RawFileIter(fname,batch)
func(d)
end
end
end
| RawFile | https://github.com/azraq27/RawFile.jl.git |
|
[
"MIT"
] | 1.0.0 | 02b36706c287622dfa105ea2eb4dfa50a50819b4 | code | 1300 | using RawFile
sizes = [(100,),(75,100),(10,20,50)]
fname = "testfile.raw"
for t in [UInt8,Int32,Int64,Float32,Float64,ComplexF16,ComplexF32]
for s in sizes
d = rand(t,s)
saveraw(d,fname)
dd = readraw(fname)
dd_batch = t[]
readraw(fname,10) do d
append!(dd_batch,d[:])
end
dd_batch = reshape(dd_batch,s)
@assert d == dd
@assert d == dd_batch
@assert s == rawsize(fname)
saveraw(fname) do f
for i=0:Int(s[end]/10)-1
write(f,view(d,[Colon() for j=1:ndims(d)-1]...,i*10+1:i*10+10))
end
end
dd = readraw(fname)
@info size(d)
@info size(dd)
@info d[70:80]
@info dd[70:80]
@assert d == dd
saveraw(view(d,[Colon() for j=1:ndims(d)-1]...,1:10),fname)
for i=1:Int(s[end]/10)-1
appendraw(view(d,[Colon() for j=1:ndims(d)-1]...,i*10+1:i*10+10),fname)
end
dd = readraw(fname)
@assert d == dd
if length(s)==1
saveraw(view(d,1:10),fname)
for i=11:s[1]
appendraw(d[i],fname)
end
dd = readraw(fname)
@assert d == dd
end
isfile(fname) && rm(fname)
end
end
| RawFile | https://github.com/azraq27/RawFile.jl.git |
|
[
"MIT"
] | 1.0.0 | 02b36706c287622dfa105ea2eb4dfa50a50819b4 | docs | 600 | # RawFile
A simple, fast file format for storing numeric arrays.
I built this package because I was frustrated with the speed and complexity of other formats.
[](https://travis-ci.org/azraq27/RawFile.jl)
[](https://coveralls.io/github/azraq27/RawFile.jl?branch=master)
[](http://codecov.io/github/azraq27/RawFile.jl?branch=master)
| RawFile | https://github.com/azraq27/RawFile.jl.git |
|
[
"MIT"
] | 1.5.0 | 5a74ac22a9daef23705f010f72c81d6925b19df8 | code | 6483 | module Sobol
using Random
export SobolSeq, ScaledSobolSeq, next!
include("soboldata.jl") #loads `sobol_a` and `sobol_minit`
abstract type AbstractSobolSeq{N} end
# N iis the dimension of sequence being generated
mutable struct SobolSeq{N} <: AbstractSobolSeq{N}
m::Array{UInt32,2} #array of size (sdim, 32)
x::Array{UInt32,1} #previous x = x_n, array of length sdim
b::Array{UInt32,1} #position of fixed point in x[i] is after bit b[i]
n::UInt32 #number of x's generated so far
end
ndims(s::AbstractSobolSeq{N}) where {N} = N::Int
function SobolSeq(N::Int)
(N < 0 || N > (length(sobol_a) + 1)) && error("invalid Sobol dimension")
m = ones(UInt32, (N, 32))
#special cases
N == 0 && return(SobolSeq{0})(m,UInt32[],UInt32[],zero(UInt32))
#special cases 1
N == 1 && return(SobolSeq{N}(m,UInt32[0],UInt32[0],zero(UInt32)))
for i = 2:N
a = sobol_a[i-1]
d = floor(Int, log2(a)) #degree of poly
#set initial values of m from table
m[i, 1:d] = sobol_minit[1:d, i - 1]
#fill in remaining values using recurrence
for j = (d+1):32
ac = a
m[i,j] = m[i,j-d]
for k = 0:d-1
@inbounds m[i,j] = m[i,j] ⊻ (((ac & one(UInt32)) * m[i, j-d+k]) << (d-k))
ac >>= 1
end
end
end
SobolSeq{N}(m,zeros(UInt32,N),zeros(UInt32,N),zero(UInt32))
end
SobolSeq(N::Integer) = SobolSeq(Int(N))
function next!(s::SobolSeq, x::AbstractVector{<:AbstractFloat})
length(x) != ndims(s) && throw(BoundsError())
if s.n == typemax(s.n)
return rand!(x)
end
s.n += one(s.n)
c = UInt32(trailing_zeros(s.n))
sb = s.b
sx = s.x
sm = s.m
for i=1:ndims(s)
@inbounds b = sb[i]
# note: ldexp on Float64(sx[i]) is exact, independent of precision of x[i]
if b >= c
@inbounds sx[i] = sx[i] ⊻ (sm[i,c+1] << (b-c))
@inbounds x[i] = ldexp(Float64(sx[i]), ((~b) % Int32))
else
@inbounds sx[i] = (sx[i] << (c-b)) ⊻ sm[i,c+1]
@inbounds sb[i] = c
@inbounds x[i] = ldexp(Float64(sx[i]), ((~c) % Int32))
end
end
return x
end
next!(s::SobolSeq) = next!(s, Array{Float64,1}(undef, ndims(s)))
# if we know in advance how many points (n) we want to compute, then
# adopt a suggestion similar to the Joe and Kuo paper, which in turn
# is taken from Acworth et al (1998), of skipping a number of
# points one less than the largest power of 2 smaller than n+1.
# if exactly n points are to be skipped, use the keyword exact=true.
# (Ackworth and Joe and Kuo seem to suggest skipping exactly
# a power of 2, but skipping 1 less seems to produce much better
# results: issue #21.)
#
# skip!(s, n) skips 2^m - 1 such that 2^m < n ≤ 2^(m+1)
# skip!(s, n, exact=true) skips m = n
function skip!(s::SobolSeq, n::Integer, x; exact=false)
if n ≤ 0
n == 0 && return s
throw(ArgumentError("$n is not non-negative"))
end
nskip = exact ? n : (1 << floor(Int,log2(n+1)) - 1)
for unused=1:nskip; next!(s,x); end
return s
end
Base.skip(s::SobolSeq, n::Integer; exact=false) = skip!(s, n, Array{Float64,1}(undef, ndims(s)); exact=exact)
function Base.show(io::IO, s::SobolSeq)
print(io, "$(ndims(s))-dimensional Sobol sequence on [0,1]^$(ndims(s))")
end
function Base.show(io::IO, ::MIME"text/html", s::SobolSeq)
print(io, "$(ndims(s))-dimensional Sobol sequence on [0,1]<sup>$(ndims(s))</sup>")
end
# Make an iterator so that we can do "for x in SobolSeq(...)".
# Technically, the Sobol sequence ends after 2^32-1 points, but it
# falls back on pseudorandom numbers after this. In practice, one is
# unlikely to reach that point.
Base.iterate(s::AbstractSobolSeq, state=nothing) = (next!(s), state)
Base.eltype(::Type{<:AbstractSobolSeq}) = Vector{Float64}
Base.IteratorSize(::Type{<:AbstractSobolSeq}) = Base.IsInfinite()
Base.IteratorEltype(::Type{<:AbstractSobolSeq}) = Base.HasEltype()
# Convenience wrapper for scaled Sobol sequences
struct ScaledSobolSeq{N,T} <: AbstractSobolSeq{N}
s::SobolSeq{N}
lb::Vector{T}
ub::Vector{T}
function ScaledSobolSeq{N,T}(lb::Vector{T}, ub::Vector{T}) where {N,T}
length(lb)==length(ub)==N || throw(DimensionMismatch("lb and ub do not have length $N"))
new(SobolSeq(N), lb, ub)
end
end
function SobolSeq(N::Integer, lb, ub)
T = typeof(sum(ub) - sum(lb))
ScaledSobolSeq{Int(N),T}(copyto!(Vector{T}(undef,N), lb), copyto!(Vector{T}(undef,N), ub))
end
SobolSeq(lb, ub) = SobolSeq(length(lb), lb, ub)
function next!(s::SobolSeq, x::AbstractVector{<:AbstractFloat},
lb::AbstractVector, ub::AbstractVector)
length(x) < ndims(s) && throw(BoundsError())
next!(s,x)
for i=1:ndims(s)
x[i] = lb[i] + (ub[i]-lb[i]) * x[i]
end
return x
end
function next!(s::SobolSeq{N}, lb::AbstractVector, ub::AbstractVector) where {N}
T = typeof(float((zero(eltype(ub)) - zero(eltype(lb)))))
next!(s, Vector{T}(undef, N), lb, ub)
end
next!(s::ScaledSobolSeq, x::AbstractVector{<:AbstractFloat}) = next!(s.s, x, s.lb, s.ub)
next!(s::ScaledSobolSeq{N,T}) where {N,T} = next!(s.s, Vector{float(T)}(undef, N), s.lb, s.ub)
Base.eltype(::Type{ScaledSobolSeq{N,T}}) where {N,T} = Vector{float(T)}
Base.skip(s::ScaledSobolSeq, n; exact = false) = (skip(s.s, n; exact = exact); s)
function Base.show(io::IO, s::ScaledSobolSeq{N,T}) where {N,T}
lb = s.lb; ub = s.ub
print(io, "$N-dimensional scaled $(float(T)) Sobol sequence on [$(lb[1]),$(ub[1])]")
cnt = 1
for i = 2:N
if lb[i] == lb[i-1] && ub[i] == ub[i-1]
cnt += 1
else
if cnt > 1
print(io, "^", cnt)
end
print(io, " x [", lb[i], ",", ub[i], "]")
cnt = 1
end
end
if cnt > 1
print(io, "^", cnt)
end
end
function Base.show(io::IO, ::MIME"text/html", s::ScaledSobolSeq{N,T}) where {N,T}
lb = s.lb; ub = s.ub
print(io, "$N-dimensional scaled $(float(T)) Sobol sequence on [$(lb[1]),$(ub[1])]")
cnt = 1
for i = 2:N
if lb[i] == lb[i-1] && ub[i] == ub[i-1]
cnt += 1
else
if cnt > 1
print(io, "<sup>", cnt, "</sup>")
end
print(io, " × [", lb[i], ",", ub[i], "]")
cnt = 1
end
end
if cnt > 1
print(io, "<sup>", cnt, "</sup>")
end
end
end # module
| Sobol | https://github.com/stevengj/Sobol.jl.git |
|
[
"MIT"
] | 1.5.0 | 5a74ac22a9daef23705f010f72c81d6925b19df8 | code | 2834 | #=
Data on the primitive binary polynomials (a) and the corresponding
starting values m, for Sobol sequences in up to 21201 dimensions,
taken from:
S. Joe and F. Y. Kuo, Constructing Sobol sequences with better two-dimensional projections,
SIAM J. Sci. Comput. 30, 2635-2654 (2008).
Figures used were derived from files provided on Joe Kuo's website
http://web.maths.unsw.edu.au/~fkuo/sobol/ on 16/10/2010
and are provided under the license below.
Copyright (c) 2008, Frances Y. Kuo and Stephen Joe
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of the copyright holders nor the names of the
University of New South Wales and the University of Waikato
and its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=#
using DelimitedFiles
const sobol_a_file = joinpath(@__DIR__, "sobol_a.csv")
const sobol_minit_file = joinpath(@__DIR__, "sobol_minit.csv")
# we need to re-compile if these files change:
include_dependency(sobol_a_file)
include_dependency(sobol_minit_file)
#successive primitive binary-coefficient polynomials p(z)
# = a_0 + a_1 z + a_2 z^2 + ... a_31 z^31, where a_i is the
# i-th bit of sobol_a[j] for the j-th polynomial.
const sobol_a = vec(readdlm(sobol_a_file, ',', UInt32))
# starting direction #'s m[i] = sobol_minit[i][j] for i=0..d of the
# degree-d primitive polynomial sobol_a[j].
const sobol_minit = readdlm(sobol_minit_file, ',', UInt32)
| Sobol | https://github.com/stevengj/Sobol.jl.git |
|
[
"MIT"
] | 1.5.0 | 5a74ac22a9daef23705f010f72c81d6925b19df8 | code | 2347 | using Sobol, Test
# compare results with results from C++ code sobol.cc published on
# http://web.maths.unsw.edu.au/~fkuo/sobol/
# with new-joe-kuo-6.21201 file used as input.
#
# Command line used to generate output is
# ./sobol $N 1024 new-joe-kuo-6.21201 > exp_results_$N
#
# For each of the dimensions below
# (except 21201 where only 64 samples are generated)
@testset "published results" begin
dimensions = [5, 10, 20, 50, 100, 500, 21201]
for dim in dimensions
println("Testing dimension $(dim)")
open(joinpath(dirname(@__FILE__), "results", "exp_results_$(dim)")) do exp_results_file
s = SobolSeq(dim)
x = zeros(dim)
for line in eachline(exp_results_file)
values = [parse(Float64, item) for item in split(line)]
if length(values) > 0
@test x == values
next!(s, x)
end
end
end
end
end
using Base.Iterators: take
@testset "iterators" begin
# issue #8
@test [x[1] for x in collect(take(Sobol.SobolSeq(1),5))] == [0.5,0.75,0.25,0.375,0.875]
end
@testset "scaled" begin
# ScaledSobolSeq constructors
lb = [-1,0,0]
ub = [1,3,2]
N = length(lb)
s = SobolSeq(lb,ub)
@test s isa ScaledSobolSeq{3,Int}
@test eltype(s) == Vector{Float64}
@test eltype(SobolSeq(Float32.(lb),Float32.(ub))) == Vector{Float32}
@test first(s) == [0,1.5,1]
@test first(SobolSeq((x for x in lb), (x for x in ub))) == [0,1.5,1]
@test SobolSeq(N,lb,ub) isa ScaledSobolSeq{3,Int}
@test_throws BoundsError SobolSeq(2,lb,ub)
end
@testset "skip exactly n" begin
# issue #22
# want to get the nth element
for n in (1,10)
s1 = SobolSeq(1)
x1 = last([next!(s1)[1] for _ in 1:n])
s2 = skip(SobolSeq(1), n-1, exact=true)
x2 = next!(s2)[1]
@test x1 == x2
end
@test_throws ArgumentError skip(SobolSeq(1), -1)
end
@testset "default skip" begin
# issue #21
s = skip(SobolSeq(4), 16)
p = map(_->next!(s), 1:16)
sort!(map(x -> sum((x .≥ 0.5) .* (2 .^ (0:3))), p)) == 0:15
for n in (7,8)
s = skip(SobolSeq(2), n)
p = [next!(s) for _ = 1:n]
s2 = skip(SobolSeq(2), 7, exact=true)
p2 = [next!(s2) for _ = 1:n]
@test p == p2
end
end
| Sobol | https://github.com/stevengj/Sobol.jl.git |
|
[
"MIT"
] | 1.5.0 | 5a74ac22a9daef23705f010f72c81d6925b19df8 | docs | 5523 | # The Sobol module for Julia
[](https://travis-ci.org/stevengj/Sobol.jl)
This module provides a free [Julia-language](http://julialang.org/)
[Sobol low-discrepancy-sequence
(LDS)](https://en.wikipedia.org/wiki/Sobol_sequence) implementation. This
generates "quasi-random" sequences of points in N dimensions which are
equally distributed over an N-dimensional hypercube.
The advantage of an LDS over truly random (or pseudo-random) numbers is
that an LDS (which is *not* random) tends to be more evenly
distributed for finite numbers of points. This is used in
[quasi-Monte Carlo
methods](https://en.wikipedia.org/wiki/Quasi-Monte_Carlo_method) in
order to accelerate convergence compared to traditional [Monte Carlo
methods](https://en.wikipedia.org/wiki/Monte_Carlo_method) employing
random sequences.
It can be installed using the Julia package manager via `Pkg.add("Sobol")`.
## Algorithm
This is an independent implementation, originally by Steven G. Johnson, of the
algorithm for generation of Sobol sequences in up to 21201 dimensions
described in:
* P. Bratley and B. L. Fox, [Algorithm 659: Implementing Sobol's quasirandom sequence generator][bratley88],
*ACM Trans. Math. Soft.* **14** (1), pp. 88-100 (1988), [doi:10.1145/42288.214372][bratley88].
* S. Joe and F. Y. Kuo, [Remark on algorithm 659: Implementing Sobol's quasirandom sequence generator][joe03],
*ACM Trans. Math. Soft* **29** (1), 49-57 (2003), [doi:10.1145/641876.641879][joe03].
[bratley88]: https://dl.acm.org/citation.cfm?id=214372
[joe03]: https://dl.acm.org/citation.cfm?id=641879
Originally implemented in C in 2007 as
[part of](https://github.com/stevengj/nlopt/blob/master/util/sobolseq.c) the
[NLopt library](http://ab-initio.mit.edu/nlopt) for nonlinear optimization, the
code was subsequently converted by [Ken-B](https://github.com/Ken-B) into pure Julia with roughly the same performance.
It is important to emphasize that SGJ's implementation was based on the
mathematical description of the algorithms only, and was done without
reference to the Fortran code from the *Trans. Math. Soft.* (*TOMS*)
papers. The reason is that *TOMS* code is not free/open-source
software (it falls under [restrictive ACM copyright
terms](http://www.acm.org/publications/policies/softwarecrnotice)).
(SGJ did re-use a table of primitive polynomials and coefficients from
the *TOMS* code, but since this is merely a tabulation of mathematical
facts it is not copyrightable.) SGJ's implementation in NLopt, along
with this Julia translation, is free/open-source software under the [MIT
("expat") license](http://opensource.org/licenses/MIT).
Direction numbers used were derived from the file
http://web.maths.unsw.edu.au/~fkuo/sobol/new-joe-kuo-6.21201
Technically, we implement a 32-bit Sobol sequence. After
2<sup>32</sup>-1 points, the sequence terminates, and subsequently
our implementation returns pseudo-random numbers generated by the
[Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_twister) algorithm.
In practical applications, however, this point is rarely reached.
## Usage
To initialize a Sobol sequence `s` in `N` dimensions (`0 < N < 21201`), use
the `SobolSeq` constructor:
```julia
using Sobol
s = SobolSeq(N)
```
Then
```julia
x = next!(s)
```
returns the next point (a `Vector{Float64}`) in the sequence; each point
lies in the hypercube [0,1]<sup>N</sup>. You can also compute the next
point in-place with
```julia
next!(s, x)
```
where `x` should be a `Vector` of length `N` of some floating-point type (e.g. `Float64`, `Float32`, or `BigFloat`).
You can also use a `SobolSeq` as an iterator in Julia:
```julia
for x in SobolSeq(N)
...
end
```
Note, however, that the loop will *never terminate* unless you explicitly
call `break` (or similar) in the loop body at some point of your choosing.
We also provide a different `SobolSeq` constructor to provide
an `N`-dimensional Sobol sequence rescaled to an arbitrary hypercube:
```julia
s = SobolSeq(lb, ub)
```
where `lb` and `ub` are arrays (or other iterables) of length `N`, giving
the lower and upper bounds of the hypercube, respectively. For example,
`SobolSeq([-1,0,0],[1,3,2])` generates points in the box [-1,1]×[0,3]×[0,2]. (Although the generated points are `Float64` by default, in general the precision is determined by that of `lb` and `ub`.)
If you know in advance the number `n` of points that you plan to
generate, some authors suggest that better uniformity can be attained
by first skipping the initial portion of the LDS. In particular,
we skip 2ᵐ−1 for the largest `m` where `2ᵐ-1 ≤ n` (see [Joe and Kuo, 2003][joe03] for a similar suggestion). This
facility is provided by:
```julia
skip(s, n)
```
Skipping exactly `n` elements is also possible:
```julia
skip(s, n, exact=true)
```
`skip` returns `s`, so you can simply do `s = skip(SobolSeq(N))` or similar.
## Example
Here is a simple example, generating 1024 points in two dimensions and
plotting them with the [PyPlot](https://github.com/stevengj/PyPlot.jl)
package. Note the highly uniform, nonrandom distribution of points in
the [0,1]×[0,1] unit square!
```julia
using Sobol
using PyPlot
s = SobolSeq(2)
p = reduce(hcat, next!(s) for i = 1:1024)'
subplot(111, aspect="equal")
plot(p[:,1], p[:,2], "r.")
```

## Author
This module was written by [Steven G. Johnson](http://math.mit.edu/~stevenj/).
| Sobol | https://github.com/stevengj/Sobol.jl.git |
|
[
"MIT"
] | 0.1.18 | 9ef6267a378c9a7467f7557f1dbd1c021a9e967f | code | 3795 | @doc let path = joinpath(dirname(@__DIR__), "README.md")
include_dependency(path)
replace(read(path, String), "```julia" => "```jldoctest mylabel")
end module Difmap
using DataPipes: @p
using FlexiMaps: filtermap
using difmap_jll
using ImageMagick_jll: imagemagick_convert, identify
Base.@kwdef struct ExecutionResult
exitcode::Int
success::Bool
stdout::String
stderr::String
log::Union{String, Nothing}
outfiles::Vector
end
Base.success(r::ExecutionResult) = r.success
execute(script::Vector{String}; kwargs...) = execute(join(script, "\n"); kwargs...)
function execute(script::String; in_files=[], out_files=[], out_files_overwrite=false)
original_dir = pwd()
mktempdir() do tmp_dir
@debug "Running difmap in $tmp_dir"
if !isempty(in_files)
@debug "Copying files $in_files from $original_dir to $tmp_dir"
for (from, to) in in_files
@assert !occursin("/", to) to
cp(joinpath(original_dir, from), joinpath(tmp_dir, to))
end
end
@assert !isfile(joinpath(tmp_dir, "difmap.log"))
@assert !isfile(joinpath(tmp_dir, "commands"))
open(joinpath(tmp_dir, "commands"), "w") do f
write(f, script)
end
out = joinpath(tmp_dir, "__stdout")
err = joinpath(tmp_dir, "__stderr")
cmd = Cmd(`$(difmap())`, ignorestatus=true, dir=tmp_dir)
process = run(pipeline(cmd, stdin=joinpath(tmp_dir, "commands"), stdout=out, stderr=err), wait=true)
success = process.exitcode == 0
files = @p begin
readdir(tmp_dir)
filter(_ ∉ ["commands", "difmap.log"] && _ ∉ last.(in_files) && !startswith(_, "__"))
map() do f
if f ∈ first.(out_files)
tgt = @p out_files |> filter(_[1] == f) |> only() |> __[2]
isnothing(tgt) && return (name=f, path=nothing)
tgt = joinpath(original_dir, tgt)
cp(joinpath(tmp_dir, f), tgt, force=out_files_overwrite)
(name=f, path=tgt)
else
(name=f, path=nothing)
end
end
end
return ExecutionResult(
exitcode=process.exitcode,
success=success,
stdout=read(out, String),
stderr=read(err, String),
log=isfile(joinpath(tmp_dir, "difmap.log")) ? read(joinpath(tmp_dir, "difmap.log"), String) : nothing,
outfiles=files,
)
end
end
inputlines(res::ExecutionResult) = inputlines(res.log)
inputlines(log::String) = @p split(log, "\n") |> filter(!isempty(_) && !startswith(_, "! "))
outputlines(res::ExecutionResult) = outputlines(res.log)
outputlines(log::String) = @p split(log, "\n") |> filter(startswith(_, "! ")) |> map(strip(_[2:end]))
inout_pairs(res::ExecutionResult) = inout_pairs(res.log)
function inout_pairs(log::String)
lines = @p split(log, "\n") |> map((line=_, kind=startswith(_, "! ") ? :out : :in))
result = ["" => String[]]
for s in lines
if s.kind == :in && !isempty(s.line)
push!(result, s.line => [])
elseif s.kind == :out
push!(result[end].second, strip(s.line[2:end]))
end
end
return result
end
struct Plot
file::String
end
function Base.show(io::IO, ::MIME"image/png", p::Plot)
open(p.file) do f
write(io, f)
end
end
function plots(res::ExecutionResult, args=`-density 100`)
@p res.outfiles |> filtermap(_.path) |> filtermap() do p
outfile = tempname()
success(run(`$(identify()) $p`; wait=false)) || return nothing
run(`$(imagemagick_convert()) $args $(p) PNG:$(outfile)`)
Plot(outfile)
end
end
end
| Difmap | https://github.com/JuliaAPlavin/Difmap.jl.git |
|
[
"MIT"
] | 0.1.18 | 9ef6267a378c9a7467f7557f1dbd1c021a9e967f | code | 14229 | ### A Pluto.jl notebook ###
# v0.17.5
using Markdown
using InteractiveUtils
# ╔═╡ 5da52ffc-7944-11ec-3360-417816776f72
begin
# using Revise
# import Pkg
# Pkg.develop(path="..")
# Pkg.resolve()
using Difmap
end
# ╔═╡ b69e0747-ef95-45c2-b503-ab631d9bbcaa
using PlutoUI
# ╔═╡ 12f2e179-f4c6-4e21-86b2-763d6a973ed3
script = [
"observe vis.fits",
"select I",
"rflags=\"m3\"",
"device radplot.ps/VCPS",
"wobs abc.fits",
"radplot",
"exit",
]
# ╔═╡ 96cef750-dc47-49d2-81d4-1fe1440c99e6
dres = Difmap.execute(script, in_files=["./data/vis.fits" => "vis.fits"], out_files=["radplot.ps", "abc.fits"] .=> tempname.())
# ╔═╡ 5fd2e565-8314-48a3-90dc-20e8747a027c
Difmap.inout_pairs(dres)
# ╔═╡ 5f5e7e55-af31-405f-9930-8b87821eb6b3
Difmap.plots(dres)
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
Difmap = "697f6f98-b792-4bca-85fe-71b3d053de65"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
[compat]
Difmap = "~0.1.15"
PlutoUI = "~0.7.30"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.7.1"
manifest_format = "2.0"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "8eaf9f1b4921132a4cff3f36a1d9ba923b14a481"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.1.4"
[[deps.Accessors]]
deps = ["Compat", "CompositionsBase", "ConstructionBase", "Future", "LinearAlgebra", "MacroTools", "Requires", "Test"]
git-tree-sha1 = "2e427a6196c7aad4ee35054a9a90e9cb5df5c607"
uuid = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697"
version = "0.1.7"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "024fe24d83e4a5bf5fc80501a314ce0d1aa35597"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.0"
[[deps.Compat]]
deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "SHA", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"]
git-tree-sha1 = "44c37b4636bc54afac5c574d2d02b625349d6582"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "3.41.0"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
[[deps.CompositionsBase]]
git-tree-sha1 = "455419f7e328a1a2493cabc6428d79e951349769"
uuid = "a33af91c-f02d-484b-be07-31d278c5ca2b"
version = "0.1.1"
[[deps.ConstructionBase]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "f74e9d5388b8620b4cee35d4c5a618dd4dc547f4"
uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9"
version = "1.3.0"
[[deps.DataPipes]]
deps = ["Accessors", "SplitApplyCombine"]
git-tree-sha1 = "6da546248579d3084c06d1babd1431c64f981441"
uuid = "02685ad9-2d12-40c3-9f73-c6aeda6a7ff5"
version = "0.2.5"
[[deps.Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[deps.DelimitedFiles]]
deps = ["Mmap"]
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"
[[deps.Dictionaries]]
deps = ["Indexing", "Random"]
git-tree-sha1 = "66bde31636301f4d217a161cabe42536fa754ec8"
uuid = "85a47980-9c8c-11e8-2b9f-f7ca1fa99fb4"
version = "0.3.17"
[[deps.Difmap]]
deps = ["DataPipes", "ImageMagick_jll", "difmap_jll"]
path = "../../home/aplavin/.julia/dev/Difmap.jl"
uuid = "697f6f98-b792-4bca-85fe-71b3d053de65"
version = "0.1.15"
[[deps.Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
[[deps.Downloads]]
deps = ["ArgTools", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
[[deps.FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.4"
[[deps.Future]]
deps = ["Random"]
uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820"
[[deps.Hyperscript]]
deps = ["Test"]
git-tree-sha1 = "8d511d5b81240fc8e6802386302675bdf47737b9"
uuid = "47d2ed2b-36de-50cf-bf87-49c2cf4b8b91"
version = "0.0.4"
[[deps.HypertextLiteral]]
git-tree-sha1 = "2b078b5a615c6c0396c77810d92ee8c6f470d238"
uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2"
version = "0.9.3"
[[deps.IOCapture]]
deps = ["Logging", "Random"]
git-tree-sha1 = "f7be53659ab06ddc986428d3a9dcc95f6fa6705a"
uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89"
version = "0.2.2"
[[deps.ImageMagick_jll]]
deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pkg", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "d43c324d044dc8256e1470a561ee7a0cf5e122c9"
uuid = "c73af94c-d91f-53ed-93a7-00f77d67a9d7"
version = "6.9.12+1"
[[deps.Indexing]]
git-tree-sha1 = "ce1566720fd6b19ff3411404d4b977acd4814f9f"
uuid = "313cdc1a-70c2-5d6a-ae34-0150d3930a38"
version = "1.1.1"
[[deps.InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"
[[deps.JLLWrappers]]
deps = ["Preferences"]
git-tree-sha1 = "22df5b96feef82434b07327e2d3c770a9b21e023"
uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210"
version = "1.4.0"
[[deps.JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "8076680b162ada2a031f707ac7b4953e30667a37"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.2"
[[deps.JpegTurbo_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "d735490ac75c5cb9f1b00d8b5509c11984dc6943"
uuid = "aacddb02-875f-59d6-b918-886e6ef4fbf8"
version = "2.1.0+0"
[[deps.LibCURL]]
deps = ["LibCURL_jll", "MozillaCACerts_jll"]
uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21"
[[deps.LibCURL_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"]
uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0"
[[deps.LibGit2]]
deps = ["Base64", "NetworkOptions", "Printf", "SHA"]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"
[[deps.LibSSH2_jll]]
deps = ["Artifacts", "Libdl", "MbedTLS_jll"]
uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8"
[[deps.Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
[[deps.Libgcrypt_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgpg_error_jll", "Pkg"]
git-tree-sha1 = "64613c82a59c120435c067c2b809fc61cf5166ae"
uuid = "d4300ac3-e22c-5743-9152-c294e39db1e4"
version = "1.8.7+0"
[[deps.Libgpg_error_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "c333716e46366857753e273ce6a69ee0945a6db9"
uuid = "7add5ba3-2f88-524e-9cd5-f83b8a55f7b8"
version = "1.42.0+0"
[[deps.Libiconv_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "42b62845d70a619f063a7da093d995ec8e15e778"
uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531"
version = "1.16.1+1"
[[deps.Libtiff_jll]]
deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Pkg", "Zlib_jll", "Zstd_jll"]
git-tree-sha1 = "340e257aada13f95f98ee352d316c3bed37c8ab9"
uuid = "89763e89-9b03-5906-acba-b20f662cd828"
version = "4.3.0+0"
[[deps.LinearAlgebra]]
deps = ["Libdl", "libblastrampoline_jll"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
[[deps.Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"
[[deps.MacroTools]]
deps = ["Markdown", "Random"]
git-tree-sha1 = "3d3e902b31198a27340d0bf00d6ac452866021cf"
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
version = "0.5.9"
[[deps.Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"
[[deps.MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"
[[deps.Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"
[[deps.MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"
[[deps.Ncurses_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "e3fb71f3c971fdc8523f9ef3906691124f3048a2"
uuid = "68e3532b-a499-55ff-9963-d1c0c0748b3a"
version = "6.2.0+0"
[[deps.NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"
[[deps.OpenBLAS_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"]
uuid = "4536629a-c528-5b80-bd46-f80d51c5b363"
[[deps.PGPLOT_jll]]
deps = ["CompilerSupportLibraries_jll", "Libdl", "Pkg"]
git-tree-sha1 = "91bf88f8e171151bdc71e9615159f0a14339f54b"
uuid = "b11e30b1-63be-5002-9df0-88ee0fe906ff"
version = "5.2.0+0"
[[deps.Parsers]]
deps = ["Dates"]
git-tree-sha1 = "92f91ba9e5941fc781fecf5494ac1da87bdac775"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "2.2.0"
[[deps.Pkg]]
deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
[[deps.PlutoUI]]
deps = ["AbstractPlutoDingetjes", "Base64", "ColorTypes", "Dates", "Hyperscript", "HypertextLiteral", "IOCapture", "InteractiveUtils", "JSON", "Logging", "Markdown", "Random", "Reexport", "UUIDs"]
git-tree-sha1 = "5c0eb9099596090bb3215260ceca687b888a1575"
uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
version = "0.7.30"
[[deps.Preferences]]
deps = ["TOML"]
git-tree-sha1 = "2cf929d64681236a2e074ffafb8d568733d2e6af"
uuid = "21216c6a-2e73-6563-6e65-726566657250"
version = "1.2.3"
[[deps.Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"
[[deps.REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"
[[deps.Random]]
deps = ["SHA", "Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
[[deps.Reexport]]
git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.2.2"
[[deps.Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.3.0"
[[deps.SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"
[[deps.Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
[[deps.SharedArrays]]
deps = ["Distributed", "Mmap", "Random", "Serialization"]
uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383"
[[deps.Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"
[[deps.SparseArrays]]
deps = ["LinearAlgebra", "Random"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
[[deps.SplitApplyCombine]]
deps = ["Dictionaries", "Indexing"]
git-tree-sha1 = "35efd62f6f8d9142052d9c7a84e35cd1f9d2db29"
uuid = "03a91e81-4c3e-53e1-a0a4-9c0c8f19dd66"
version = "1.2.1"
[[deps.Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
[[deps.TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"
[[deps.Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"
[[deps.Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[[deps.UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
[[deps.Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"
[[deps.XML2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "1acf5bdf07aa0907e0a37d3718bb88d4b687b74a"
uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a"
version = "2.9.12+0"
[[deps.XSLT_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgcrypt_jll", "Libgpg_error_jll", "Libiconv_jll", "Pkg", "XML2_jll", "Zlib_jll"]
git-tree-sha1 = "91844873c4085240b95e795f692c4cec4d805f8a"
uuid = "aed1982a-8fda-507f-9586-7b0439959a61"
version = "1.1.34+0"
[[deps.Xorg_libX11_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxcb_jll", "Xorg_xtrans_jll"]
git-tree-sha1 = "5be649d550f3f4b95308bf0183b82e2582876527"
uuid = "4f6342f7-b3d2-589e-9d20-edeb45f2b2bc"
version = "1.6.9+4"
[[deps.Xorg_libXau_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "4e490d5c960c314f33885790ed410ff3a94ce67e"
uuid = "0c0b7dd1-d40b-584c-a123-a41640f87eec"
version = "1.0.9+4"
[[deps.Xorg_libXdmcp_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "4fe47bd2247248125c428978740e18a681372dd4"
uuid = "a3789734-cfe1-5b06-b2d0-1dd0d9d62d05"
version = "1.1.3+4"
[[deps.Xorg_libpthread_stubs_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "6783737e45d3c59a4a4c4091f5f88cdcf0908cbb"
uuid = "14d82f49-176c-5ed1-bb49-ad3f5cbd8c74"
version = "0.1.0+3"
[[deps.Xorg_libxcb_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "XSLT_jll", "Xorg_libXau_jll", "Xorg_libXdmcp_jll", "Xorg_libpthread_stubs_jll"]
git-tree-sha1 = "daf17f441228e7a3833846cd048892861cff16d6"
uuid = "c7cfdc94-dc32-55de-ac96-5a1b8d977c5b"
version = "1.13.0+3"
[[deps.Xorg_xtrans_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "79c31e7844f6ecf779705fbc12146eb190b7d845"
uuid = "c5fb5394-a638-5e4d-96e5-b29de1b5cf10"
version = "1.4.0+3"
[[deps.Zlib_jll]]
deps = ["Libdl"]
uuid = "83775a58-1f1d-513f-b197-d71354ab007a"
[[deps.Zstd_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6"
uuid = "3161d3a3-bdf6-5164-811a-617609db77b4"
version = "1.5.0+0"
[[deps.difmap_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Ncurses_jll", "PGPLOT_jll", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "2c9d61ab9189941639096a9f3dd3396da0d32652"
uuid = "43cd2700-e54a-5645-adf8-b9b288a87fe6"
version = "2.5.11+0"
[[deps.libblastrampoline_jll]]
deps = ["Artifacts", "Libdl", "OpenBLAS_jll"]
uuid = "8e850b90-86db-534c-a0d3-1478176c7d93"
[[deps.libpng_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"]
git-tree-sha1 = "94d180a6d2b5e55e447e2d27a29ed04fe79eb30c"
uuid = "b53b4c65-9356-5827-b1ea-8c7a1a84506f"
version = "1.6.38+0"
[[deps.nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"
[[deps.p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"
"""
# ╔═╡ Cell order:
# ╠═5da52ffc-7944-11ec-3360-417816776f72
# ╠═12f2e179-f4c6-4e21-86b2-763d6a973ed3
# ╠═96cef750-dc47-49d2-81d4-1fe1440c99e6
# ╠═5fd2e565-8314-48a3-90dc-20e8747a027c
# ╠═b69e0747-ef95-45c2-b503-ab631d9bbcaa
# ╠═5f5e7e55-af31-405f-9930-8b87821eb6b3
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002
| Difmap | https://github.com/JuliaAPlavin/Difmap.jl.git |
|
[
"MIT"
] | 0.1.18 | 9ef6267a378c9a7467f7557f1dbd1c021a9e967f | code | 2823 | using Test
using Difmap
@testset "execute" begin
script = [
"print(1 + 2)",
"exit",
]
res = Difmap.execute(script)
@test success(res)
@test isempty(res.outfiles)
@test res.stderr == "Exiting program\n"
@test Difmap.inputlines(res) == script
@test Difmap.outputlines(res) |> length == 4
@test occursin("Started logfile", Difmap.outputlines(res)[1])
@test Difmap.outputlines(res)[2] == "3"
@test occursin("Exiting program", Difmap.outputlines(res)[3])
@test occursin("difmap.log closed", Difmap.outputlines(res)[4])
@test Difmap.inout_pairs(res) |> length == length(script) + 1
@test Difmap.inout_pairs(res)[2] == ("print(1 + 2)" => ["3"])
end
@testset "copy file" begin
res = mktemp() do tempf, _
write(tempf, "\nprint \"2 * 2\"\n")
script = [
"print(1 + 2)",
"@my_script_file",
"exit",
]
Difmap.execute(script, in_files=[tempf => "my_script_file"])
end
@test success(res)
@test isempty(res.outfiles)
@test res.stderr == "Exiting program\n"
@test Difmap.outputlines(res) |> length == 5
@test occursin("Started logfile", Difmap.outputlines(res)[1])
@test Difmap.outputlines(res)[2] == "3"
@test "2 * 2" == Difmap.outputlines(res)[3]
@test Difmap.inout_pairs(res) |> length == 6
@test Difmap.inout_pairs(res)[2] == ("print(1 + 2)" => ["3"])
@test Difmap.inout_pairs(res)[3] == ("![@my_script_file]" => [])
@test Difmap.inout_pairs(res)[4] == ("print \"2 * 2\"" => ["2 * 2"])
end
@testset "process vis data" begin
script = [
"observe $(joinpath(@__DIR__, "./data/vis.fits"))",
"select I",
"mapsize 512, 0.2",
"clean 500",
"restore",
"device tmp.ps/PS",
"mapplot cln",
"save result",
"exit",
]
res = Difmap.execute(script)
@test success(res)
res = Difmap.execute(script, out_files=[["result.fits", "result.mod", "result.par", "result.uvf"] .=> nothing; "tmp.ps" => tempname()])
@test success(res)
@test map(f -> f[(:name,)], res.outfiles[[1, 2, 4]]) == [
(name = "result.fits",),
(name = "result.mod",),
(name = "result.uvf",),
]
@test res.outfiles[end].name == "tmp.ps"
@test res.stderr == "Polarization I is unavailable.\nExiting program\n"
iops = Difmap.inout_pairs(res)
@test length(iops) == length(script) + 1
@test occursin(r"^AN table", iops[2].second[2])
@test occursin(r" J0000\+0248$", iops[2].second[4])
@test occursin(" 1152 visibilities", iops[2].second[end])
@test occursin(" = 512x512 pixels ", iops[4].second[end])
@test length(Difmap.plots(res)) == 1
end
using Documenter
doctest(Difmap; manual=false)
import CompatHelperLocal as CHL
CHL.@check()
| Difmap | https://github.com/JuliaAPlavin/Difmap.jl.git |
|
[
"MIT"
] | 0.1.18 | 9ef6267a378c9a7467f7557f1dbd1c021a9e967f | docs | 4556 | # Overview
Julia wrapper for the [difmap](ftp://ftp.astro.caltech.edu/pub/difmap/) program.
Conveniently execute difmap scripts, handle input/output files and logs.
Relies on the `difmap_jll.jl` package to provide the `difmap` binary.
# Usage
See also the [Pluto notebook](https://aplavin.github.io/Difmap.jl/test/examples.html) that includes plots.
```julia
julia> using Difmap
julia> script = [
"print(1 + 2)",
"exit",
];
julia> res = Difmap.execute(script);
julia> res.success
true
julia> Difmap.inout_pairs(res)[begin+1:end-1] # first and last lines contain current time
1-element Vector{Pair{String, Vector{String}}}:
"print(1 + 2)" => ["3"]
```
```julia
julia> script = [
"observe vis.fits",
"select I",
"mapsize 512, 0.2",
"clean 500",
"restore",
"device tmp.ps/PS",
"mapplot cln",
"save result",
"exit",
];
julia> vis_file = joinpath(dirname(dirname(pathof(Difmap))), "test/data/vis.fits");
julia> res = Difmap.execute(script,
in_files=[vis_file => "vis.fits"],
out_files=["result.fits", "result.mod", "result.par", "result.uvf", "tmp.ps"] .=> nothing, # target is nothing - ignore these files
);
julia> res.success
true
julia> Difmap.inout_pairs(res)[begin+1:end-1] # first and last lines contain current time
8-element Vector{Pair{String, Vector{String}}}:
"observe vis.fits" => ["Reading UV FITS file: vis.fits", "AN table 1: 4 integrations on 36 of 36 possible baselines.", "Apparent sampling: 1 visibilities/baseline/integration-bin.", "Found source: J0000+0248", "", "There are 8 IFs, and a total of 8 channels:", "", "IF Channel Frequency Freq offset Number of Overall IF", "origin at origin per channel channels bandwidth", "------------------------------------------------------------- (Hz)" … "05 5 4.416e+09 3.2e+07 1 3.2e+07", "06 6 4.512e+09 3.2e+07 1 3.2e+07", "07 7 4.544e+09 3.2e+07 1 3.2e+07", "08 8 4.576e+09 3.2e+07 1 3.2e+07", "", "Polarization(s): RR", "", "Read 0 lines of history.", "", "Reading 1152 visibilities."]
"select I" => ["Polarization I is unavailable.", "Selecting polarization: RR, channels: 1..8", "Reading IF 1 channels: 1..1", "Reading IF 2 channels: 2..2", "Reading IF 3 channels: 3..3", "Reading IF 4 channels: 4..4", "Reading IF 5 channels: 5..5", "Reading IF 6 channels: 6..6", "Reading IF 7 channels: 7..7", "Reading IF 8 channels: 8..8"]
"mapsize 512, 0.2" => ["Map grid = 512x512 pixels with 0.200x0.200 milli-arcsec cellsize."]
"clean 500" => ["Inverting map and beam", "Estimated beam: bmin=1.195 mas, bmaj=3.79 mas, bpa=-3.012 degrees", "Estimated noise=0.541101 mJy/beam.", "clean: niter=500 gain=0.05 cutoff=0", "Component: 050 - total flux cleaned = 0.0188812 Jy", "Component: 100 - total flux cleaned = 0.0252178 Jy", "Component: 150 - total flux cleaned = 0.0277823 Jy", "Component: 200 - total flux cleaned = 0.0290343 Jy", "Component: 250 - total flux cleaned = 0.0300524 Jy", "Component: 300 - total flux cleaned = 0.0302839 Jy", "Component: 350 - total flux cleaned = 0.0304884 Jy", "Component: 400 - total flux cleaned = 0.0304353 Jy", "Component: 450 - total flux cleaned = 0.0305383 Jy", "Component: 500 - total flux cleaned = 0.030393 Jy", "Total flux subtracted in 500 components = 0.030393 Jy", "Clean residual min=-0.000455 max=0.000452 Jy/beam", "Clean residual mean=0.000001 rms=0.000189 Jy/beam", "Combined flux in latest and established models = 0.030393 Jy"]
"restore" => ["restore: Substituting estimate of restoring beam from last 'invert'.", "Restoring with beam: 1.195 x 3.79 at -3.012 degrees (North through East)", "Clean map min=-0.0010866 max=0.019272 Jy/beam"]
"device tmp.ps/PS" => ["Attempting to open device: 'tmp.ps/PS'"]
"mapplot cln" => []
"save result" => ["Writing UV FITS file: result.uvf", "Writing 174 model components to file: result.mod", "Adding 174 model components to the UV plane model.", "The established model now contains 174 components and 0.030393 Jy", "Inverting map", "restore: Substituting estimate of restoring beam from last 'invert'.", "Restoring with beam: 1.195 x 3.79 at -3.012 degrees (North through East)", "Clean map min=-0.0010295 max=0.019271 Jy/beam", "Writing clean map to FITS file: result.fits", "Writing difmap environment to: result.par"]
```
| Difmap | https://github.com/JuliaAPlavin/Difmap.jl.git |
|
[
"MIT"
] | 0.1.0 | 0a2efe02a81515634587fc69288c59fdb6a27e45 | code | 232 | module TernaryPlots
export ternary_axes, ternary_axes!
export tern2cart, cart2tern
using RecipesBase
using LinearAlgebra: normalize
include("user_helpers.jl")
include("recipe_helpers.jl")
include("ternary_axes.jl")
end # module
| TernaryPlots | https://github.com/jacobusmmsmit/TernaryPlots.jl.git |
|
[
"MIT"
] | 0.1.0 | 0a2efe02a81515634587fc69288c59fdb6a27e45 | code | 2387 | tupvec(vec) = Tuple([entry] for entry in vec)
coords_to_axes(src, dst) = [src[1], dst[1]], [src[2], dst[2]]
function calculate_guide_pos(axis, arrow_pos, dist_from_graph)
if axis == "x"
base_src_tern = (arrow_pos[1], arrow_pos[2], 0)
base_dst_tern = (arrow_pos[2], arrow_pos[1], 0)
oriented_dfg = [0, -1] .* dist_from_graph
elseif axis == "y"
base_src_tern = (0, arrow_pos[1], arrow_pos[2])
base_dst_tern = (0, arrow_pos[2], arrow_pos[1])
oriented_dfg = [1, 1] .* dist_from_graph
elseif axis == "z"
base_src_tern = (arrow_pos[2], 0, arrow_pos[1])
base_dst_tern = (arrow_pos[1], 0, arrow_pos[2])
oriented_dfg = [-1, 1] .* dist_from_graph
else
throw(ArgumentError("Invalid axis (\"x, y, z\""))
end
arrow_src = collect(tern2cart(base_src_tern)) .+ 2 .* oriented_dfg
arrow_dst = collect(tern2cart(base_dst_tern)) .+ 2 .* oriented_dfg
textpos = ((arrow_src .+ arrow_dst) ./ 2) .+ oriented_dfg
return (arrow_src, arrow_dst, textpos)
end
function calculate_ticks(axis, ticks, tick_length, tickmult)
tick_endpoints = Vector{Vector{Float64}}(undef, length(ticks))
tick_startpoints = Vector{Tuple{Float64, Float64}}(undef, length(ticks))
function start_structure(axis, tick_pos)
if axis == "x"
return 1 - tick_pos, tick_pos, 0
elseif axis == "y"
return 1 - tick_pos, 0, tick_pos
elseif axis == "z"
return 0, tick_pos, 1 - tick_pos
else
throw(ArgumentError("Invalid axis (\"x, y, z\""))
end
end
function end_structure(axis, tick_pos)
if axis == "x"
return 1 - tick_pos, 0, tick_pos
elseif axis == "y"
return 0, 1 - tick_pos, tick_pos
elseif axis == "z"
return 1 - tick_pos, tick_pos, 0
else
throw(ArgumentError("Invalid axis (\"x, y, z\""))
end
end
for (i, tick_pos) in enumerate(ticks)
start_point = tern2cart(start_structure(axis, tick_pos)...)
end_point = tern2cart(end_structure(axis, tick_pos)...)
tick_offset = normalize(collect(start_point .- end_point)) ./ (1 / tick_length)
tick_startpoints[i] = start_point
tick_endpoints[i] = start_point .+ tickmult .* tick_offset
end
return tick_startpoints, tick_endpoints
end
| TernaryPlots | https://github.com/jacobusmmsmit/TernaryPlots.jl.git |
|
[
"MIT"
] | 0.1.0 | 0a2efe02a81515634587fc69288c59fdb6a27e45 | code | 7110 | @userplot Ternary_Axes
@recipe function f(ta::Ternary_Axes)
# empty plot without axes
framestyle := :none
aspect_ratio := true
dist_from_graph = get(plotattributes, :arrow_length, 0.04)
arrow_length = get(plotattributes, :arrow_length, 0.4)
arrow_pos = (1 - arrow_length) / 2, 1 - (1 - arrow_length) / 2
tick_length = get(plotattributes, :tick_length, 0.015)
# calculate where arrows and labels should be
x_arrow_src, x_arrow_dst, x_guide_pos = calculate_guide_pos("x", arrow_pos, dist_from_graph)
y_arrow_src, y_arrow_dst, y_guide_pos = calculate_guide_pos("y", arrow_pos, dist_from_graph)
z_arrow_src, z_arrow_dst, z_guide_pos = calculate_guide_pos("z", arrow_pos, dist_from_graph)
x_arrow_xs, x_arrow_ys = coords_to_axes(x_arrow_src, x_arrow_dst)
y_arrow_xs, y_arrow_ys = coords_to_axes(y_arrow_src, y_arrow_dst)
z_arrow_xs, z_arrow_ys = coords_to_axes(z_arrow_src, z_arrow_dst)
arrow_axes_xs_yes = [(x_arrow_xs, x_arrow_ys), (y_arrow_xs, y_arrow_ys), (z_arrow_xs, z_arrow_ys)]
if !get(plotattributes, :axis_arrows, true)
x_guide_pos = (x_arrow_src .+ x_arrow_dst) ./ 2
y_guide_pos = (y_arrow_src .+ y_arrow_dst) ./ 2
z_guide_pos = (z_arrow_src .+ z_arrow_dst) ./ 2
else
# draw axis arrows
for xs_ys in arrow_axes_xs_yes
@series begin
seriestype := :path
primary := false
seriescolor := :black
arrow := true
xs_ys
end
end
end
# labels
xguide = get(plotattributes, :xguide, "")
@series begin
seriestype := :path
primary := false
series_annotations := [(xguide)] #[text(xguide),]
tupvec(x_guide_pos)
end
yguide = get(plotattributes, :yguide, "")
@series begin
seriestype := :path
primary := false
series_annotations := [(yguide, -60.0)]
tupvec(y_guide_pos)
end
zguide = get(plotattributes, :zguide, "")
@series begin
seriestype := :path
primary := false
series_annotations := [(zguide, 60.0)] #[text(zguide, 60.0),]
tupvec(z_guide_pos)
end
# grids
if get(plotattributes, :gridmajor, true)
if get(plotattributes, :xgrid, true)
ticks = get(plotattributes, :xticks, 0.2:0.2:0.8)
src = tern2cart.(1 .- ticks, ticks, 0)
dst = tern2cart.(1 .- ticks, 0, ticks)
sa = get(plotattributes, :xgridalpha, 0.5)
lw = get(plotattributes, :xgridlinewidth, 0.5)
ls = get(plotattributes, :xgridstyle, :solid)
for i in eachindex(ticks)
@series begin
primary := false
seriestype := :path
seriescolor := :black
seriesalpha := sa
linewidth := lw
linestyle := ls
arrow := false
[src[i], dst[i]]
end
end
end
if get(plotattributes, :ygrid, true)
ticks = get(plotattributes, :yticks, 0.2:0.2:0.8)
src = tern2cart.(1 .- ticks, ticks, 0)
dst = tern2cart.(0, ticks, 1 .- ticks)
sa = get(plotattributes, :ygridalpha, 0.5)
lw = get(plotattributes, :ygridlinewidth, 0.5)
ls = get(plotattributes, :ygridstyle, :solid)
for i in eachindex(ticks)
@series begin
primary := false
seriestype := :path
seriescolor := :black
seriesalpha := sa
linewidth := lw
linestyle := ls
[src[i], dst[i]]
end
end
end
if get(plotattributes, :zgrid, true)
ticks = get(plotattributes, :zticks, 0.2:0.2:0.8)
src = tern2cart.(1 .- ticks, 0, ticks)
dst = tern2cart.(0, 1 .- ticks, ticks)
sa = get(plotattributes, :zgridalpha, 0.5)
lw = get(plotattributes, :zgridlinewidth, 0.5)
ls = get(plotattributes, :zgridstyle, :solid)
for i in eachindex(ticks)
@series begin
primary := false
seriestype := :path
seriescolor := :black
seriesalpha := sa
linewidth := lw
linestyle := ls
[src[i], dst[i]]
end
end
end
end
tick_direction = get(plotattributes, :tick_direction, :in)
# axis ticks
if tick_direction != :none
if tick_direction == :in
tickmult = -1
else
tickmult = 1
end
xticks = get(plotattributes, :xticks, 0.2:0.2:0.8)
yticks = get(plotattributes, :yticks, 0.2:0.2:0.8)
zticks = get(plotattributes, :zticks, 0.2:0.2:0.8)
function text_structure(axis)
if axis == "x"
return 0.4, -0.8
elseif axis == "y"
return -1, 0.2
elseif axis == "z"
return 0.5, 1
else
throw(ArgumentError("Invalid axis (\"x, y, z\""))
end
end
function axis_angle(axis)
if axis == "x"
return 0.0
elseif axis == "y"
return -60.0
elseif axis == "z"
return 60.0
else
throw(ArgumentError("Invalid axis (\"x, y, z\""))
end
end
for (axis, axis_ticks) in zip(("x", "y", "z"), (xticks, yticks, zticks))
angle = axis_angle(axis)
ts = text_structure(axis)
# Better to calculate the offset once by calculating the tick_structure once
# then just adding the offset to each start_pos
calculated_ticks = calculate_ticks(axis, axis_ticks, tick_length, tickmult)
vec_tick_textpos = [start_pos .+ (dist_from_graph .* ts) for start_pos in calculated_ticks[1]]
vec_tick_coords = coords_to_axes.(calculated_ticks...)
if axis == "x"
axis_ticks = reverse(axis_ticks)
end
for tick_coords in vec_tick_coords
@series begin
primary := false
seriestype := :path
seriescolor := :black
tick_coords
end
end
for (tick, tick_textpos) in zip(collect(axis_ticks), vec_tick_textpos)
@series begin
seriestype := :path
primary := false
series_annotations := [(tick, angle, 10)] #[text(tick, angle, 10),]
[tick_textpos]
end
end
end
end
size --> (580, 550)
seriestype := :path
primary := false
seriescolor := :black
[1 0 1 / 2; 0 1 / 2 1], [0 0 √3 / 2; 0 √3 / 2 0]
end | TernaryPlots | https://github.com/jacobusmmsmit/TernaryPlots.jl.git |
|
[
"MIT"
] | 0.1.0 | 0a2efe02a81515634587fc69288c59fdb6a27e45 | code | 681 | """
tern2cart(a, b, c)
Takes a point in the ternary coordinate system and returns the cartesian co-ordinate of this point.
The ternary axes are all between 0 and 1 and the cartesian co-ordinates form an equilateral triangle at (0, 0), (1, 0), (1/2, √3/2)
"""
tern2cart(a, b, c) = (1 / 2 * (2b + c) / (a + b + c), √3 / 2 * (c / (a + b + c)))
tern2cart(vec) = tern2cart(vec[1], vec[2], vec[3])
"""
cart2tern(x, y)
Takes a point in the cartesian coordinate system and returns the ternary co-ordinate of this point.
"""
function cart2tern(x, y)
c = (2 * y) / √3
b = x - c / 2
a = 1 - b - c
return (a, b, c)
end
cart2tern(array) = cart2tern(array[1], array[2])
| TernaryPlots | https://github.com/jacobusmmsmit/TernaryPlots.jl.git |
|
[
"MIT"
] | 0.1.0 | 0a2efe02a81515634587fc69288c59fdb6a27e45 | code | 945 | push!(LOAD_PATH, "src")
using Plots
using TernaryPlots
using CSV
using DataFrames
using Downloads
#Downloading Global whole-rock geochemical database compilation from https://zenodo.org/record/3359791/files/major.csv?download=1
path = "https://zenodo.org/record/3359791/files/major.csv?download=1"
df = CSV.read(Downloads.download(path), DataFrame)
df = coalesce.(df, 0)
filter!(row -> row[:sio2] >= 0, df)
filter!(row -> row[:al2o3] >= 0, df)
filter!(row -> row[:mgo] >= 0, df)
filter!(row -> (row[:sio2] .+ row[:al2o3] .+ row[:mgo]) >= 0.9, df)
filter!(row -> (row[:sio2] .+ row[:al2o3] .+ row[:mgo]) <= 1.1, df)
compos = [df.sio2 df.al2o3 df.mgo]
a = [zeros(eltype(compos), size(compos, 1)) zeros(eltype(compos), size(compos, 1))]
for i in 1:size(compos, 1)
a[i, :] = collect(tern2cart(compos[i, :]))'
end
ternary_axes(title = "Rocks", xguide = "SiO2", yguide = "Al2O3", zguide = "MgO")
p = scatter!(a[:, 1], a[:, 2], legend = false)
| TernaryPlots | https://github.com/jacobusmmsmit/TernaryPlots.jl.git |
|
[
"MIT"
] | 0.1.0 | 0a2efe02a81515634587fc69288c59fdb6a27e45 | docs | 3267 | # TernaryPlots.jl
Ternary/simplex plotting recipe/addon for Plots.jl
Please note: this package is currently in _very early development stage_, this README is currently up to date as of 07/08/2021, but may not be in the coming days as problems are fixed and features are added. Please feel free to contact me via email with any questions jacobusmmsmit a gmail d com or open an issue on this repository.
## Installation:
In the REPL you can paste this code to install the package:
```
using Pkg; pkg"add https://github.com/jacobusmmsmit/TernaryPlots.jl"
```
and then load it with
```
using TernaryPlots
```
## Current functionality:
* Conversions between cartesian and ternary co-ordinates using the exported function `cart2tern` and `tern2cart`
* Construction of ternary axes using `ternary_axes`. (Currently not possible to reverse arrow/axis directions)
## How to use this package:
This package provides a function (more precisely: a recipe) to construct ternary plots via converting ternary co-ordinates to cartesian and plotting them:
```
push!(LOAD_PATH, "src")
using Plots
using TernaryPlots
using CSV
using DataFrames
#Downloading Global whole-rock geochemical database compilation from zenodo.org
path = "https://zenodo.org/record/3359791/files/major.csv?download=1"
df = CSV.read(download(path), DataFrame)
df = coalesce.(df,0)
filter!(row -> row[:sio2] >= 0, df)
filter!(row -> row[:al2o3] >= 0, df)
filter!(row -> row[:mgo] >= 0, df)
filter!(row -> (row[:sio2] .+ row[:al2o3] .+ row[:mgo]) >= 0.9, df)
filter!(row -> (row[:sio2] .+ row[:al2o3] .+ row[:mgo]) <= 1.1, df)
compos = [df.sio2 df.al2o3 df.mgo]
a = [zeros(eltype(compos), size(compos, 1)) zeros(eltype(compos), size(compos, 1))]
for i in 1:size(compos,1)
a[i,:] = collect(tern2cart(compos[i,:]))'
end
ternary_axes(
title="Rocks",
xguide="SiO2",
yguide="Al2O3",
zguide="MgO",
)
p = scatter!(a[:,1],a[:,2], legend=false)
```

## Work in progress:
* Different axis scales (as opposed to just 0 to 1) and ability to update ticks after definition.
* Performance improvements and code cleanup.
* Documentation.
* Plotting of ternary heatmaps by overloading `heatmap` on `Ternary_Axes`. Users will be able to define a function of cartesian co-ordinates or ternary co-ordinates:
```
f = ((a, b, c) -> 3a^2 + b - c) # Function of ternary co-ordinates
g = (x,y) -> f(cart2tern(x, y)...) # Same function, but taking ternary co-ordinates as input
```
* Plotting of ternary histograms possibly simply by converting it into a heatmap and using the previous heatmap functionality.
* Plotting of contour maps.
## Known issues:
* Rotation of labels is not consistent as you resize the graph, as such one needs to fiddle with the size parameter in order to get the angles correct, or specify them yourself.
* The figures are off-centered.
## Contributions:
* [@jacobusmmsmit](https://github.com/jacobusmmsmit) - Author and maintainer
* [@Hasnep](https://github.com/Hasnep) - Maintainer
* [@daschw](https://github.com/daschw) - Major contributions to recipe implementation
<!-- * [@brenhinkeller](https://github.com/brenhinkeller) - Major contributions for ternary histograms -->
| TernaryPlots | https://github.com/jacobusmmsmit/TernaryPlots.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 408 | using Documenter, UnionArrays
makedocs(;
modules=[UnionArrays],
format=Documenter.HTML(),
pages=[
"Home" => "index.md",
],
repo="https://github.com/JuliaFolds/UnionArrays.jl/blob/{commit}{path}#L{line}",
sitename="UnionArrays.jl",
authors="Takafumi Arakaki <[email protected]>",
)
deploydocs(;
repo="github.com/JuliaFolds/UnionArrays.jl",
push_preview = true,
)
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 668 | module UnionArrays
# Use README as the docstring of the module:
@doc let path = joinpath(dirname(@__DIR__), "README.md")
include_dependency(path)
replace(read(path, String), "```julia" => "```jldoctest README")
end UnionArrays
function unionof end
function buffereltypefor end
function buffereltypeof end
function eltypebyid end
include("abstract/abstract.jl")
include("impl/impl.jl")
Abstract.UnionVector(args...; kwargs...) = Impl.UnionVector(args...; kwargs...)
Abstract.UnionArray(args...; kwargs...) = Impl.UnionArray(args...; kwargs...)
using .Abstract: UnionArray, UnionVector, UnionMatrix
export UnionArray, UnionVector, UnionMatrix
end # module
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 681 | module Abstract
"""
UnionArray{T, N}
UnionVector{T}
UnionMatrix{T}
`UnionArray` stores heterogeneous elements without indirections (which
would happen in `Array{Any}`).
# Examples
```jldoctest
julia> using UnionArrays
julia> xs = UnionVector(Any[UInt8(1), 2.0, (a=1, b=2)]);
julia> xs[1]
0x01
julia> xs[2]
2.0
julia> xs[3]
(a = 1, b = 2)
julia> xs[1] = (a=3, b=4);
julia> xs[1]
(a = 3, b = 4)
julia> M = reshape(xs, (1, :)) :: UnionMatrix;
julia> M[1, 1]
(a = 3, b = 4)
```
"""
abstract type UnionArray{T, N} <: AbstractArray{T, N} end
const UnionVector{T} = UnionArray{T, 1}
const UnionMatrix{T} = UnionArray{T, 2}
include("interfaces.jl")
end # module
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 187 | using Adapt: adapt
default_collect(A::AbstractArray{T,N}) where {T,N} =
invoke(collect, Tuple{AbstractArray{T,N}}, A)
Base.collect(A::UnionArray) = default_collect(adapt(Array, A))
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 3137 | struct UnionArray{T, N, P} <: Abstract.UnionArray{T, N}
parent::P
function UnionArray(parent::P) where {T, N, P <: AbstractArray{T, N}}
# Make sure that `A.parent` is not a UnionArray/Vector
P <: UnionArrayImpls && throw(MethodError(UnionArray, (parent,)))
return new{T, N, P}(parent)
end
end
const UnionArrayImpls = Union{UnionVector, UnionArray}
function Adapt.adapt_structure(to, A::UnionArray)
B = Adapt.adapt(to, parent(A))
if B isa UnionArray
# `Adapt.adapt` might just call `reshape`, which then wraps the array
# to `UnionArray`. In this case, there is no need to re-wrap it:
return B
else
# Maybe just throw?
return UnionArray(B)
end
end
# TODO: handle `reshape` in Transducers.jl so that we only need one
# `parent(...)` call here:
executor_type(A::UnionArray) = executor_type(parent(parent(A)))
# A very minimal dummy array implementation just for implementing `default_reshape`:
struct DummyArray{N} <: AbstractArray{Any,N}
dims::NTuple{N,Int}
end
Base.size(A::DummyArray) = A.dims
function default_reshape(A::UnionVector, dims::T) where {T}
dummy = reshape(DummyArray(size(A)), dims)
return @set dummy.parent = A
end
ua_reshape(A::UnionVector, dims) = UnionArray(default_reshape(A, dims))
ua_reshape(A::UnionArray, dims) = UnionArray(reshape(A.parent, dims))
ua_reshape(A::UnionVector, ::Tuple{Colon}) = A
function ua_reshape(A::UnionArray, ::Tuple{Colon})
v = reshape(A.parent, :)
if v isa UnionVector
return v
else
return UnionArray(v)
end
end
Base.reshape(A::UnionArrayImpls, dims::Dims) =
ua_reshape(A, dims) :: UnionArrayImpls
Base.reshape(A::UnionArrayImpls, dims::Tuple{Vararg{Union{Int,Colon}}}) =
ua_reshape(A, dims) :: UnionArrayImpls
# disambiguation:
Base.reshape(A::UnionArrayImpls, dims::Tuple{Colon}) =
ua_reshape(A, dims) :: UnionArrayImpls
Base.parent(A::UnionArray) = A.parent
Base.size(A::UnionArray) = size(A.parent)
Base.getindex(A::UnionArray, I...) = A.parent[I...]
Base.setindex!(A::UnionArray, v, I...) = setindex!(A.parent, v, I...)
# Base.showarg(io::IO, A::UnionArray, toplevel) =
# Base.showarg(io, A.parent, toplevel)
Abstract.UnionArray(
undef::UndefInitializer,
VectorType::Type{<:AbstractVector},
ETS::ElTypeSpec,
dims::Union{Integer,Tuple{Vararg{Integer}}},
) = Abstract.UnionArray(undef, VectorType, VectorType{UInt8}, ETS, dims)
Abstract.UnionArray(
undef::UndefInitializer,
DataVectorType::Type{<:AbstractVector},
TypeTagVectorType::Type{<:AbstractVector{UInt8}},
ETS::ElTypeSpec,
n::Union{Integer,Tuple{Integer}},
) = UnionVector(undef, DataVectorType, TypeTagVectorType, ETS, first(n))
Abstract.UnionArray(
undef::UndefInitializer,
DataVectorType::Type{<:AbstractVector},
TypeTagVectorType::Type{<:AbstractVector{UInt8}},
ETS::ElTypeSpec,
dims::Tuple{Integer,Integer,Vararg{Integer}},
) = reshape(UnionVector(undef, DataVectorType, TypeTagVectorType, ETS, prod(dims)), dims)
function Base.fill!(A::UnionArray, x)
fill!(parent(parent(A)), x)
return A
end
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 1346 | """
unionof(T₁, T₂, ...)
Similar to `Union{T₁, T₂, ...}` but the order is preserved. This object can
be passed to `UnionArray` to specify the element type.
"""
function UnionArrays.unionof(types::Type...)
vals = foldlargs((), types...) do vals, T
(vals..., Val{T}())
end
return verify(UnionOf(vals))
end
const NTypes{N} = NTuple{N, Val}
struct UnionOf{T<:NTypes}
types::T
end
const ElTypeSpec = Union{Type, NTypes, UnionOf}
astupletype(u::UnionOf) =
foldrargs(u.types..., Tuple{}) do v, T
Base.tuple_type_cons(valueof(v), T)
end
asunion(u::UnionOf) = asunion(u.types)
asunion(types::NTypes) =
foldlargs(Union{}, types...) do T, v
Union{T,valueof(v)}
end
asntypes(types::NTypes) = types
asntypes(u::UnionOf) = u.types
@generated asntypes(::Type{T}) where {T} =
QuoteNode(foldrunion((S, types) -> (Val(S), types...), T, ()))
function verify(u::UnionOf)
if length(u.types) != union_ntypes(asunion(u))
error("non-unique types are provided")
end
return u
end
function Base.show(io::IO, u::UnionOf)
@nospecialize u
print(io, UnionArrays.unionof)
print(io, '(')
isfirst = true
for v in u.types
if !isfirst
print(io, ", ")
end
isfirst = false
print(io, valueof(v))
end
print(io, ')')
end
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 391 | module Impl
import Adapt
using Base: Dims
using Transducers
using Transducers: @return_if_reduced, next, complete
using Setfield: @set # using Setfield instead of Accessors for older Julia
import Transducers: executor_type
using ..UnionArrays: Abstract, UnionArrays, buffereltypefor
include("utils.jl")
include("eltypespec.jl")
include("vectors.jl")
include("arrays.jl")
end # module
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 3077 | valueof(::Val{x}) where {x} = x
# Not exactly `Base.aligned_sizeof`
Base.@pure function sizeof_aligned(T::Type)
if isbitstype(T)
al = Base.datatype_alignment(T)
return (Core.sizeof(T) + al - 1) & -al
else
return nothing
end
end
TypeTuple{N} = NTuple{N, Type}
astupleoftypes(x::TypeTuple) = x
astupleoftypes(::Type{T}) where {T <: Tuple} = Tuple(T.parameters)
@inline foldlargs(op, x) = x
@inline foldlargs(op, x1, x2, xs...) =
foldlargs(op,
@return_if_reduced(op(x1, x2)),
xs...)
@inline foldrargs(op, x) = x
@inline foldrargs(op, x1, x2, xs...) = op(x1, foldrargs(op, x2, xs...))
@inline foldltupletype(op, T, ::Type{<:Tuple{}}) = T
@inline foldltupletype(op, T, ::Type{S}) where {S <: Tuple} =
foldltupletype(op,
@return_if_reduced(op(T, Base.tuple_type_head(S))),
Base.tuple_type_tail(S))
@inline foldltupletype(op, ::Type{T}, ::Type{<:Tuple{}}) where T = T
@inline foldltupletype(op, ::Type{T}, ::Type{S}) where {T, S <: Tuple} =
foldltupletype(op,
@return_if_reduced(op(T, Base.tuple_type_head(S))),
Base.tuple_type_tail(S))
@inline foldrunion(op, ::Type{T}, init) where {T} =
if T isa Union
acc = @return_if_reduced foldrunion(op, T.b, init)
foldrunion(op, T.a, acc)
else
op(T, init)
end
uniontotuple(::Type{T}) where {T} = foldrunion(Base.tuple_type_cons, T, Tuple{})
asunion(T::Type{<:Tuple}) = foldltupletype((T, s) -> Union{T, s}, Union{}, T)
union_ntypes(::Type{T}) where {T} = foldrunion((_, n) -> n + 1, T, 0)
tuple_ntypes(::Type{T}) where {T} = foldltupletype((n, _) -> n + 1, 0, T)
terminating_foldlargs(op, fallback) = fallback()
@inline function terminating_foldlargs(op, fallback::F, x1, x2, xs...) where {F}
acc = op(x1, x2)
acc isa Reduced && return unreduced(acc)
return terminating_foldlargs(op, fallback, acc, xs...)
end
# Helping inference for CUDA.jl:
@inline function terminating_foldlargs(op, fallback, x1, x2)
acc = op(x1, x2)
acc isa Reduced && return unreduced(acc)
return fallback()
end
struct Padded{T, N}
value::T
pad::NTuple{N, UInt8}
end
Padded{T, N}(value::T) where {T, N} = Padded(value, zeropad(Val{N}()))
zeropad(N) = ntuple(_ -> UInt8(0), N)
addpadding(N::Integer, ::Type{T}) where T = Padded{T, N}
addpadding(N::Integer, value::T) where T = Padded{T, N}(value)
Base.convert(::Type{P}, x::T) where {T, P <: Padded{T}} = P(x)
unpad(x) = x
unpad(x::Padded) = x.value
unpad(::Type{<:Padded{T}}) where T = T
paddedtype(::T) where T = paddedtype(T)
paddedtype(::Type{<:Padded{T}}) where T = T
paddedtype(::Type{T}) where T = T
# not sure relying on `sizeof` is safe; so:
sizeoftype(::Type{T}) where T = sizeof(T)
sizeoftype(::T) where T = sizeof(T)
ofsamesize(bigger::Type, smaller) =
if sizeof(bigger) < sizeoftype(smaller)
error("Target type is not big enough")
elseif sizeof(bigger) == sizeoftype(smaller)
smaller
else
addpadding(sizeof(bigger) - sizeoftype(smaller), smaller)
end
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 5903 | struct UnionVector{
T,
ETS <: NTypes,
TD <: AbstractVector,
TM <: AbstractVector{UInt8},
TV <: Tuple
} <: Abstract.UnionVector{T}
types::ETS
data::TD
typeid::TM
views::TV
function UnionVector(
types::ETS,
data::TD,
typeid::TM,
views::TV,
) where {
ETS <: NTypes,
TD <: AbstractVector,
TM <: AbstractVector{UInt8},
TV <: Tuple,
}
A = new{asunion(types),ETS,TD,TM,TV}(types, data, typeid, views)
@static if VERSION >= v"1.6-"
return verify(A)
else
return A
end
end
end
if VERSION >= v"1.6-"
Adapt.adapt_structure(to, A::UnionVector) =
UnionVector(A.types, Adapt.adapt(to, A.data), Adapt.adapt(to, A.typeid))
else
Adapt.adapt_structure(to, A::UnionVector) = UnionVector(
A.types,
Adapt.adapt(to, A.data),
Adapt.adapt(to, A.typeid),
Adapt.adapt(to, A.views),
)
end
executor_type(A::UnionVector) = executor_type(A.data)
function UnionVector(ETS::ElTypeSpec, data::AbstractVector, typeid::AbstractVector{UInt8})
types = asntypes(ETS)
views = foldlargs((), types...) do views, v
return (views..., reinterpret(ofsamesize(eltype(data), valueof(v)), data))
end
return UnionVector(types, data, typeid, views)
end
UnionArrays.buffereltypefor(ETS::ElTypeSpec) =
foldlargs(Nothing, asntypes(ETS)...) do S, x
Base.@_inline_meta
T = valueof(x)
if sizeof_aligned(S) < sizeof_aligned(T)
T
else
S
end
end
UnionArrays.buffereltypeof(A::UnionVector) = eltype(A.data)
function UnionArrays.eltypebyid(A::UnionVector, ::Val{id}) where {id}
id > length(A.types) && return Union{}
id < 1 && return Union{}
return valueof(A.types[id])
end
Base.size(A::UnionVector) = size(A.data)
UnionVector(undef::UndefInitializer, ETS::ElTypeSpec, n::Integer) =
UnionVector(undef, Vector, ETS, n)
UnionVector(
undef::UndefInitializer,
VectorType::Type{<:AbstractVector},
ETS::ElTypeSpec,
n::Integer,
) = UnionVector(undef, VectorType, VectorType{UInt8}, ETS, n)
function UnionVector(
::UndefInitializer,
DataVectorType::Type{<:AbstractVector},
TypeTagVectorType::Type{<:AbstractVector{UInt8}},
ETS::ElTypeSpec,
n::Integer,
)
typeid = TypeTagVectorType(undef, n)
fill!(typeid, 0)
BT = buffereltypefor(ETS)
data = DataVectorType{BT}(undef, n)
return UnionVector(ETS, data, typeid)
end
function UnionVector(ETS::ElTypeSpec, items::AbstractVector)
A = UnionVector(undef, ETS, length(items))
for i in axes(A, 1)
# TODO: find the best way to support arrays with offset
@inbounds A[i] = items[i - firstindex(A) + firstindex(items)]
end
return A
end
function UnionVector(data::AbstractVector)
ETS = foldl(data, init=Union{}) do ETS, x
Union{ETS,typeof(x)}
end
return UnionVector(ETS, data)
end
struct InvalidUnionVector{T<:UnionVector} <: Exception
A::T
end
function Base.showerror(io::IO, err::InvalidUnionVector)
A = err.A
unmatches = filter!(collect(Pair{Int,Any}, pairs(A.views))) do (_, xs)
UInt(pointer(A.data)) != UInt(pointer(xs))
end
print(io, "invalid UnionVector: ")
println(io, length(unmatches), " incompatible views")
println(io, "data pointer: ", pointer(A.data))
for (i, xs) in unmatches
println(io, i, "-th view pointer: ", pointer(xs))
end
end
function verify(A::UnionVector)
foldlargs(true, A.views...) do ok, xs
Base.@_inline_meta
ok && UInt(pointer(A.data)) == UInt(pointer(xs))
end || throw(InvalidUnionVector(A))
return A
end
Base.@propagate_inbounds typeat(A::UnionVector{<:Any, ETS}, i) where ETS =
fieldtype(ETS, Int(A.typeid[i]))
struct TypeIDLookupFailed <: Exception
id::Int
end
Base.showerror(io::IO, err::TypeIDLookupFailed) =
print(io, "lookup of type id $(err.id) failed")
# Using CPS for begging the compiler to union split things:
@inline function view_by_id(f::F, A::UnionVector, id::Integer) where {F}
@noinline unreachable() = throw(TypeIDLookupFailed(id))
return terminating_foldlargs(unreachable, 1, A.views...) do j, xs
Base.@_inline_meta
if j == id
Reduced(f(xs))
else
j + 1
end
end
end
@inline function Base.getindex(A::UnionVector, i::Int)
@boundscheck checkbounds(A, i)
return view_by_id(A, A.typeid[i]) do xs
Base.@_inline_meta
unpad(@inbounds xs[i])
end
end
struct ElTypeLookupFailed{T} <: Exception end
Base.showerror(io::IO, ::ElTypeLookupFailed{T}) where {T} =
print(io, "unsupported element type (type conversion not implemented yet); $T")
# Using CPS for begging the compiler to union split things:
# TODO: handle conversion
@inline function view_and_id(f::F, A::UnionVector, ::Type{T}) where {F,T}
@noinline unreachable() = throw(ElTypeLookupFailed{T}())
V = Val(T)
return terminating_foldlargs(unreachable, 1, A.views...) do id, xs
Base.@_inline_meta
if paddedtype(eltype(xs)) === valueof(V)
Reduced(f(xs, id))
else
id + 1
end
end
end
# Base.checkbounds(::Type{Bool}, A::UnionVector, i) =
# checkbounds(Bool, A.data, i) && checkbounds(Bool, A.typeid, i)
@inline function Base.setindex!(A::UnionVector, v, i::Int)
@boundscheck checkbounds(A, i)
typeid = A.typeid
view_and_id(A, typeof(v)) do xs, id
Base.@_inline_meta
@inbounds typeid[i] = id
@inbounds xs[i] = v
nothing
end
end
function Base.fill!(A::UnionVector, x)
v = convert(eltype(A), x)
p = v # TODO: handle padding
view_and_id(A, typeof(v)) do xs, id
fill!(xs, p)
fill!(A.typeid, id)
nothing
end
return A
end
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 541 | using TestFunctionRunner
let env_test_cuda = lowercase(get(ENV, "UNIONARRAYS_JL_TEST_CUDA", "auto")),
test_cuda = if env_test_cuda == "auto"
try
import CUDA
true
catch
false
end
else
env_test_cuda == "true"
end
if test_cuda
TestFunctionRunner.@run(packages = ["UnionArraysCUDATests"])
using FoldsCUDATests
FoldsCUDATests.runtests_unionarrays()
else
TestFunctionRunner.@run(packages = ["UnionArraysTests"])
end
end
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 475 | module UnionArraysCUDATests
import CUDA
function include_tests(m = @__MODULE__, dir = @__DIR__)
for file in readdir(dir)
if match(r"^test_.*\.jl$", file) !== nothing
Base.include(m, joinpath(dir, file))
end
end
end
include_tests()
function before_test_module()
CUDA.allowscalar(false)
if lowercase(get(ENV, "CI", "false")) == "true"
CUDA.versioninfo()
println()
end
end
end # module UnionArraysCUDATests
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 867 | module TestBase
using CUDA
using Test
using UnionArrays
using UnionArrays: unionof
const ==′ = isequal
function test_unionvector()
xs = UnionVector(undef, CuVector, unionof(Float32, Missing), 3)
fill!(xs, 1)
CUDA.@allowscalar xs[2] = missing
@test (CUDA.@allowscalar xs[1]) === 1.0f0
@test (CUDA.@allowscalar xs[2]) === missing
@test (CUDA.@allowscalar xs[3]) === 1.0f0
@test collect(xs) ==′ [1.0f0, missing, 1.0f0]
end
function test_unionmatrix()
A = UnionArray(undef, CuVector, unionof(Float32, Missing), (3, 2))
fill!(A, 1)
CUDA.@allowscalar A[2, 2] = missing
@test (CUDA.@allowscalar A[1, 1]) === 1.0f0
@test (CUDA.@allowscalar A[2, 2]) === missing
@test (CUDA.@allowscalar A[3, 2]) === 1.0f0
@test collect(A) ==′ [
1.0f0 1.0f0
1.0f0 missing
1.0f0 1.0f0
]
end
end # module
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 179 | module TestDoctest
using UnionArrays
using Documenter: doctest
using Test
function test()
doctest(UnionArrays)
end
should_test_module() = VERSION >= v"1.6-"
end # module
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 1277 | module TestFolds
using CUDA
using Folds
using FoldsCUDA
using Test
using UnionArrays
const ==′ = isequal
function test_unionvector()
xs = UnionVector(undef, CuVector, Union{Float32, Missing}, 3)
fill!(xs, 1)
CUDA.@allowscalar xs[2] = missing
@test collect(xs) ==′ [1.0f0, missing, 1.0f0]
@test Folds.sum(x -> x isa Missing ? 0.0f0 : x, xs, CUDAEx()) == 2
@testset "setindex!" begin
ys = range(1.0f0, 3.0f0, length = 3)
Folds.map!(identity, xs, ys)
@test collect(xs) == 1:3
Folds.map!(==(missing), xs, ys)
@test collect(xs) ==′ [missing, missing, missing]
end
end
function test_unionmatrix()
A = UnionArray(undef, CuVector, Union{Float32, Missing}, (3, 2))
fill!(A, 1)
CUDA.@allowscalar A[2, 2] = missing
@test (CUDA.@allowscalar A[1, 1]) === 1.0f0
@test (CUDA.@allowscalar A[2, 2]) === missing
@test (CUDA.@allowscalar A[3, 2]) === 1.0f0
@test Folds.sum(x -> x isa Missing ? 0.0f0 : x, A, CUDAEx()) == 5
@testset "setindex!" begin
B = reshape(range(1.0f0, 6.0f0, length = 6), 3, 2)
Folds.map!(identity, A, B)
@test collect(A) == B
Folds.map!(==(missing), A, B)
@test collect(A) ==′ fill(missing, 3, 2)
end
end
end # module
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 1350 | module TestKernels
using CUDA
using Test
using UnionArrays
function kernel_test_shmem!(ys)
iglobal = threadIdx().x + (blockIdx().x - 1) * blockDim().x
T = Union{Nothing,Float32}
S = UnionArrays.buffereltypefor(T)
data = @cuDynamicSharedMem(S, (blockDim().x,))
typeids = @cuDynamicSharedMem(UInt8, (blockDim().x,), sizeof(data))
xs = UnionVector(T, data, typeids)
if isodd(threadIdx().x)
xs[threadIdx().x] = Float32(iglobal)
else
xs[threadIdx().x] = nothing
end
sync_threads()
i = mod1(threadIdx().x + 1, blockDim().x)
x = xs[i]
sync_threads()
xs[threadIdx().x] = x
sync_threads()
ys[iglobal] = xs[i]
return
end
function host_test_shmem()
threads = 8
blocks = 3
ys = UnionVector(undef, CuVector, Union{Float32, Nothing}, threads * blocks)
fill!(ys, 0)
shmem = (sizeof(UnionArrays.buffereltypeof(ys)) + sizeof(UInt8)) * threads
CUDA.@sync @cuda threads=threads blocks=blocks shmem=shmem kernel_test_shmem!(ys)
return ys
end
function test_shmem()
xs = collect(Union{Nothing,Float32}, 1:8 * 3)
xs[2:2:end] .= nothing
for block in Iterators.partition(eachindex(xs), 8)
xs[block] = circshift(xs[block], -2)
end
@test collect(host_test_shmem()) == xs
end
should_test_module() = VERSION >= v"1.6-"
end # module
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 306 | module UnionArraysTests
include("utils.jl")
function include_tests(m = @__MODULE__, dir = @__DIR__)
for file in readdir(dir)
if match(r"^test_.*\.jl$", file) !== nothing
Base.include(m, joinpath(dir, file))
end
end
end
include_tests()
end # module UnionArraysTests
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 325 | module TestAqua
import Aqua
import UnionArrays
using Test
# Default `Aqua.test_all(UnionArrays)` does not work due to ambiguities
# in upstream packages.
function test_aqua()
Aqua.test_all(UnionArrays; ambiguities = false)
end
function test_method_ambiguity()
Aqua.test_ambiguities(UnionArrays)
end
end # module
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 367 | module TestArrays
using UnionArrays
using Test
function test()
A = reshape(UnionVector(Any[1, 2.0]), 1, :)
@test A isa UnionArray
@test A[1] === 1
@test A[2] === 2.0
@test A[1, 1] === 1
@test A[1, 2] === 2.0
@test (A[1, 1] = 3.0) isa Any
@test A[1, 1] === 3.0
@test (A[1] = 3.0) isa Any
@test A[1] === 3.0
end
end # module
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 779 | module TestPadded
using UnionArrays
using UnionArrays.Impl: ofsamesize, unpad, Padded
using Test
function test_ofsamesize()
@testset "bigger = $bigger" for (bigger, value) in [
(Float64, UInt8(0)),
(NTuple{7, UInt8}, UInt8(0)),
]
@testset for smaller in [value, typeof(value)]
padded = ofsamesize(bigger, smaller)
@test sizeof(padded) == sizeof(bigger)
@test unpad(padded) === smaller
end
end
end
function test_convert()
xs = ofsamesize.(Float64, UInt8.(1:10)) :: Vector
@test eltype(xs) <: Padded
@test unpad(xs[1]) === UInt8(1)
xs[1] = UInt8(2)
@test unpad(xs[1]) === UInt8(2)
xs[1] = ofsamesize(Float64, UInt8(3))
@test unpad(xs[1]) === UInt8(3)
end
end # module
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 339 | module TestTransducers
using Test
using Transducers
using UnionArrays
using ..Utils: compile_enabled
function test()
xs = UnionVector(Any[1, 2.0])
@test foldl(+, Map(x -> 2x), xs) == 6
ys = eduction(Map(x -> 2x), xs)
if compile_enabled()
@test (@inferred foldl(+, ys, init=0.0)) == 6
end
end
end # module
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 471 | module TestVectors
using UnionArrays
using Test
function test_homogeneous_size()
xs = UnionVector(Any[1, 2.0])
@test xs[1] === 1
@test xs[2] === 2.0
@test (xs[1] = 3.0) isa Any
@test xs[1] === 3.0
end
function test_heterogeneous_size()
xs = UnionVector(Any[UInt8(1), 2.0, (a=1, b=2)])
@test xs[1] === UInt8(1)
@test xs[2] === 2.0
@test xs[3] === (a=1, b=2)
@test (xs[1] = 3.0) isa Any
@test xs[1] === 3.0
end
end # module
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | 9986eabab3dcfd90cf3a041b7ec5a64fca4aa508 | code | 129 | module Utils
compile_enabled() = Base.JLOptions().compile_enabled == 1
# allow `== 2` (`--compile=all`) as well?
end # module
| UnionArrays | https://github.com/JuliaFolds/UnionArrays.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.