licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.1.2 | 391a62e72e22c580c675b403009c74e93792ee14 | docs | 1374 | # JetPackTransforms.jl
| **Documentation** | **Action Statuses** |
|:---:|:---:|
| [![][docs-dev-img]][docs-dev-url] [![][docs-stable-img]][docs-stable-url] | [![][doc-build-status-img]][doc-build-status-url] [![][build-status-img]][build-status-url] [![][code-coverage-img]][code-coverage-results] |
This package contains transform operators for Jets.jl that depend on FFTW.jl,
and Wavelets.jl. For more information, please see [Jets.jl](https://github.com/ChevronETC/Jets.jl).
[docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg
[docs-dev-url]: https://chevronetc.github.io/JetPackTransforms.jl/dev/
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: https://ChevronETC.github.io/JetPackTransforms.jl/stable
[doc-build-status-img]: https://github.com/ChevronETC/JetPackTransforms.jl/workflows/Documentation/badge.svg
[doc-build-status-url]: https://github.com/ChevronETC/JetPackTransforms.jl/actions?query=workflow%3ADocumentation
[build-status-img]: https://github.com/ChevronETC/JetPackTransforms.jl/workflows/Tests/badge.svg
[build-status-url]: https://github.com/ChevronETC/JetPackTransforms.jl/actions?query=workflow%3A"Tests"
[code-coverage-img]: https://codecov.io/gh/ChevronETC/JetPackTransforms.jl/branch/master/graph/badge.svg
[code-coverage-results]: https://codecov.io/gh/ChevronETC/JetPackTransforms.jl
| JetPackTransforms | https://github.com/ChevronETC/JetPackTransforms.jl.git |
|
[
"MIT"
] | 0.1.2 | 391a62e72e22c580c675b403009c74e93792ee14 | docs | 118 | # JetPackTransforms.jl
This package contains transform operators for Jets.jl. It depends on FFTW.jl
and Wavelets.jl.
| JetPackTransforms | https://github.com/ChevronETC/JetPackTransforms.jl.git |
|
[
"MIT"
] | 0.1.2 | 391a62e72e22c580c675b403009c74e93792ee14 | docs | 102 | # Reference
```@autodocs
Modules = [JetPackTransforms]
Order = [:function]
```
# Index
```@index
``` | JetPackTransforms | https://github.com/ChevronETC/JetPackTransforms.jl.git |
|
[
"MIT"
] | 0.1.12 | 5b969585f5de557c023e5423a016c019f864e514 | code | 156 | # execute this file in the docs directory with this
# julia --color=yes --project make.jl
using Documenter, Posets
makedocs(; sitename = "ImplicitGraphs")
| ImplicitGraphs | https://github.com/scheinerman/ImplicitGraphs.jl.git |
|
[
"MIT"
] | 0.1.12 | 5b969585f5de557c023e5423a016c019f864e514 | code | 1038 | using ImplicitGraphs
"""
Collatz()::ImplicitGraph{Int}
Create a directed graph represenation of the Collatz 3x+1 problem.
The vertices of the graph are positive integers. For a vertex `n`
there is exactly one edge emerging from `n` pointing either to
`n÷2` if `n` is even or to `3n+1` if `n` is odd.
"""
function Collatz()::ImplicitGraph{Int}
vcheck(v::Int) = v > 0
function outs(v::Int)
if v % 2 == 0
return [div(v, 2)]
else
return [3v + 1]
end
end
return ImplicitGraph{Int}(vcheck, outs)
end
"""
ReverseCollatz()::ImplicitGraph{Int}
This is the same as `Collatz()` except the edges are reversed.
"""
function ReverseCollatz()::ImplicitGraph{Int}
vcheck(v::Int) = v > 0
function outs(v::Int)
out_list = [2v]
if v % 3 == 1 # v = 3x+1
x = div(v - 1, 3)
if x % 2 == 1
push!(out_list, x)
end
end
return out_list
end
return ImplicitGraph{Int}(vcheck, outs)
end
| ImplicitGraphs | https://github.com/scheinerman/ImplicitGraphs.jl.git |
|
[
"MIT"
] | 0.1.12 | 5b969585f5de557c023e5423a016c019f864e514 | code | 977 | using SimpleGraphs, ImplicitGraphs
import SimpleGraphs: UndirectedGraph, DirectedGraph
"""
UndirectedGraph(G::ImplicitGraph{T}, A) where {T}
returns the induced `UndirectedGraph`
of `G` with vertices in the collection `A`.
"""
function UndirectedGraph(G::ImplicitGraph{T}, A) where {T}
H = UG{T}()
for v in A
if has(G, v)
add!(H, v)
end
end
for v in A
for w in A
if v != w && G[v, w]
add!(H, v, w)
end
end
end
return H
end
"""
DirectedGraph(G::ImplicitGraph{T}, A) where {T}
Returns the induced `DirectedGraph`
of `G` with vertices in the collection `A`.
"""
function DirectedGraph(G::ImplicitGraph{T}, A) where {T}
D = DG{T}()
for v in A
if has(G, v)
add!(D, v)
end
end
for v in A
for w in A
if G[v, w]
add!(D, v, w)
end
end
end
return D
end
| ImplicitGraphs | https://github.com/scheinerman/ImplicitGraphs.jl.git |
|
[
"MIT"
] | 0.1.12 | 5b969585f5de557c023e5423a016c019f864e514 | code | 620 | using ImplicitGraphs, Primes
"""
iPaley(p::Int)
Create an implicit Paley graph on `p` vertices.
Here `p` must be a prime congruent to 1 modulo 4.
The vertices of the graph are integers in the range
`0:p-1` and two vertices are adjacent if their difference
is a quadratic residue mod `p`.
"""
function iPaley(p::Int)::ImplicitGraph
if !isprime(p) || p % 4 != 1
error("Argument ($p) must be prime and congruent to 1 mod 4")
end
vcheck(v::Int) = (0 <= v < p)
function outs(v::Int)
return unique((v + k^2) % p for k = 1:p-1)
end
return ImplicitGraph{Int}(vcheck, outs)
end
| ImplicitGraphs | https://github.com/scheinerman/ImplicitGraphs.jl.git |
|
[
"MIT"
] | 0.1.12 | 5b969585f5de557c023e5423a016c019f864e514 | code | 2056 | using ImplicitGraphs, Permutations
"""
iTransposition(n::Int, adjacent::Bool=true)
Create an `ImplicitGraph` whose vertices are all permutations of `1:n`
in which two vertices are adjacent if they differ by a transpostion.
* If `adjacent` is true, then only consider transpositions of the form `(a,a+1)`
* Otherwise, consider all possible transpositions of the form `(a,b)` where `1≤a<b≤n`.
"""
function iTransposition(n::Int, adjacent::Bool = true)
@assert n > 0 "Require n>0, got n=$n"
vcheck(v::Permutation) = length(v) == n
function outs(v::Permutation)
if adjacent
return [v * Transposition(n, i, i + 1) for i = 1:n-1]
end
return [v * Transposition(n, i, j) for i = 1:n for j = 1:n if i ≠ j]
end
return ImplicitGraph{Permutation}(vcheck, outs)
end
"""
trans_string(p::Permutation)
We assume that `p` is a transposition.
"""
function trans_string(p::Permutation)::String
n = length(p)
FP = fixed_points(p)
@assert n == length(FP) + 2 "Permutation must be a transposition"
elts = sort(setdiff(1:n, FP))
a, b = elts
return "($a,$b)"
end
"""
pscore(p::Permutation)::Int
Measures the extent to which `p` is different from the identity permutation
using this formula:
`sum(abs(p[k]-k) for k=1:length(p))`
"""
function pscore(p::Permutation)::Int
n = length(p)
sum(abs(i - p(i)) for i = 1:n)
end
"""
crazy_trans_product(p::Permutation, adjacent::Bool=true)::String
Express `p` as the product of transpositions. With `adjacent=true` the transpositions
are all of the form `(a,a+1)`; otherwise, all possible transpositions are allowed.
Result is expressed as a `String`.
"""
function crazy_trans_product(p::Permutation, adjacent::Bool = true)::String
n = length(p)
G = iTransposition(n, adjacent)
P = reverse(guided_path_finder(G, p, Permutation(n), score = pscore))
nP = length(P)
if nP == 1
return "()"
end
Q = [P[k]' * P[k+1] for k = 1:nP-1]
prod(trans_string(Q[j]) for j = 1:length(Q))
end
| ImplicitGraphs | https://github.com/scheinerman/ImplicitGraphs.jl.git |
|
[
"MIT"
] | 0.1.12 | 5b969585f5de557c023e5423a016c019f864e514 | code | 1587 | module ImplicitGraphs
using DataStructures
export ImplicitGraph
import Base: getindex, show, eltype
import SimpleGraphs: deg, find_path, dist, has
export deg, find_path, dist, has
"""
`ImplicitGraph{T}(has_vertex, out_neighbors)` constructs a new `ImplicitGraph`
whose vertices have type `T`.
* `has_vertex(v::T)::Bool` is a function that checks if `v` is in the graph.
* `out_neighbors(v::T)::Vector{T}` is a function that takes an object `v` of
type `T` and returns a list of `v`'s out neighbors.
"""
struct ImplicitGraph{T}
has_vertex::Function
out_neighbors::Function
end
function getindex(G::ImplicitGraph{T}, v::T) where {T}
if !has(G, v)
error("This graph does not have a vertex $v")
end
G.out_neighbors(v)
end
eltype(::ImplicitGraph{T}) where {T} = T
function getindex(G::ImplicitGraph{T}, v::T, w::T) where {T}
if !has(G, v) || !has(G, w)
error("One or both of vertices $v and $w are not in this graph")
end
return in(w, G[v])
end
has(G::ImplicitGraph{T}, v::T, w::T) where {T} = G[v, w]
"""
`deg(G::ImplicitGraph,v)` returns the degree of vertex `v`
in the graph `G`.
"""
deg(G::ImplicitGraph{T}, v::T) where {T} = length(G[v])
"""
`has(G::ImplicitGraph,v)` checks if `v` is a vertex of `G`.
`has(G,v,w)` checks if `(v,w)` is an edge of `G`.
"""
function has(G::ImplicitGraph{T}, v::T) where {T}
return G.has_vertex(v)
end
function show(io::IO, G::ImplicitGraph{T}) where {T}
print(io, "ImplicitGraph{$T}")
end
include("iGraphs.jl")
include("find_path.jl")
include("guided_path_finder.jl")
end # module
| ImplicitGraphs | https://github.com/scheinerman/ImplicitGraphs.jl.git |
|
[
"MIT"
] | 0.1.12 | 5b969585f5de557c023e5423a016c019f864e514 | code | 5289 | export find_path, find_path_undirected, dist
"""
`find_path(G::ImplicitGraph{T}, s::T, is_target::Function, cutoff_depth::Int=0) where {T}`
Finds a shortest path from `s` to any vertex for which `is_target`
returns `true`.
Optionally, we include a `cutoff_depth` at which the search stops, to
avoid exponential memory usage.
"""
function find_path(
G::ImplicitGraph{T},
s::T,
is_target::Function,
cutoff_depth::Int = 0,
) where {T}
if is_target(s)
return [s]
end
# set up an array for vertex exploration
frontier = Array{T}(undef, 1)
frontier[1] = s
# the current search depth
depth = 0
# set up trace-back dictionary
tracer = Dict{T,T}()
tracer[s] = s
while length(frontier) > 0
# Check whether to abort
if (cutoff_depth != 0) && (depth == cutoff_depth)
break
end
# Move frontier forward
depth += 1
frontier = advance_frontier(G, is_target, frontier, tracer)
# Traceback and return if successful
if typeof(frontier) == T
return reverse(traceback_path(tracer, s, frontier))
end
end
return T[] # return empty array if no path found
end
"""
`advance_frontier(G::ImplicitGraph{T}, is_target::Function, frontier::Array{T}, tracer::Dict{T, T}) where {T}`
Advances the vertex frontier by one step. In other words, if all vertices in `frontier` are
at depth `d`, then the returned frontier will contain all vertices of depth `d+1`.
If a vertex `v` is found such that `is_target` returns `true`, then abort search and return
`v` instead. The return type may thus be one of
- T[]: the new frontier of depth `d+1`
- T: a vertex satisfying `is_target`
This will mutate `tracer`, inserting all the new vertices found.
"""
function advance_frontier(
G::ImplicitGraph{T},
is_target::Function,
frontier::Array{T},
tracer::Dict{T,T},
) where {T}
new_frontier = T[]
for v in frontier
Nv = G[v]
for w in Nv
if haskey(tracer, w)
continue
end
tracer[w] = v
push!(new_frontier, w)
if is_target(w) # success!
return w
end
end
end
new_frontier
end
"""
`traceback_path(tracer::Dict{T, T}, s::T, t::T) where {T}`
Traces back path from source `s` to target `t` using the tracer dictionary.
The path is returned in reversed order
"""
function traceback_path(tracer::Dict{T,T}, s::T, t::T) where {T}
rev_path = Array{T}(undef, 1)
rev_path[1] = t
while rev_path[end] != s
v = tracer[rev_path[end]]
push!(rev_path, v)
end
rev_path
end
"""
`find_path(G::ImplicitGraph,s,t)` finds a shortest path from `s` to `t`.
"""
function find_path(G::ImplicitGraph{T}, s::T, t::T, cutoff_depth::Int = 0) where {T}
if !has(G, s) || !has(G, t)
error("Source and/or target vertex is not in this graph")
end
find_path(G, s, isequal(t), cutoff_depth)
end
"""
`find_path_undirected(G::ImplicitGraph,s,t)`.
Finds a shortest path from `s` to `t`, assuming that `G` is undirected.
This will proceed from both ends of the path until finding a common vertex.
"""
function find_path_undirected(
G::ImplicitGraph{T},
s::T,
t::T,
cutoff_depth::Int = 0,
) where {T}
if !has(G, s) || !has(G, t)
error("Source and/or target vertex is not in this graph")
end
if s == t
return [s]
end
# set up two arrays for vertex exploration
# one frontier will proceed from the source, the other from the target
frontier_s = Array{T}(undef, 1)
frontier_s[1] = s
frontier_t = Array{T}(undef, 1)
frontier_t[1] = t
# the current search path depth (for both search directions)
depth = 0
# set up a trace-back dictionaries
tracer_s = Dict{T,T}()
tracer_s[s] = s
tracer_t = Dict{T,T}()
tracer_t[t] = t
while length(frontier_s) + length(frontier_t) > 0
# Check whether to abort
if (cutoff_depth != 0) && (depth == cutoff_depth)
break
end
# target vertex: a vertex present in the tracer for the other direction
is_target_s = v -> haskey(tracer_t, v)
is_target_t = v -> haskey(tracer_s, v)
# Move frontier forward in both directions
depth += 1
# Forward move
frontier_s = advance_frontier(G, is_target_s, frontier_s, tracer_s)
# Traceback and return if successful
if typeof(frontier_s) == T
s_to_middle = reverse(traceback_path(tracer_s, s, frontier_s))
middle_to_t = traceback_path(tracer_t, t, frontier_s)
return [s_to_middle[1:end-1]; middle_to_t]
end
# Backward move
frontier_t = advance_frontier(G, is_target_t, frontier_t, tracer_t)
# Traceback and return if successful
if typeof(frontier_t) == T
s_to_middle = reverse(traceback_path(tracer_s, s, frontier_t))
middle_to_t = traceback_path(tracer_t, t, frontier_t)
return [s_to_middle[1:end-1]; middle_to_t]
end
end
return T[] # return empty array if no path found
end
dist(G::ImplicitGraph{T}, s::T, t::T) where {T} = length(find_path(G, s, t)) - 1
| ImplicitGraphs | https://github.com/scheinerman/ImplicitGraphs.jl.git |
|
[
"MIT"
] | 0.1.12 | 5b969585f5de557c023e5423a016c019f864e514 | code | 2652 | export guided_path_finder
function _edge_generator(G::ImplicitGraph{T}, v::T, depth::Int = 1) where {T}
@assert depth > 0 "Depth must be positive, argument was $depth"
if depth == 1
return [(v, w) for w in G[v]]
end
edges = _edge_generator(G, v, depth - 1)
result = Tuple{T,T}[]
visited = Set(first.(edges)) ∪ Set(last.(edges))
for (x, y) in edges
push!(result, (x, y)) # keep this edge
for z in G[y]
if z ∉ visited
push!(result, (y, z))
end
end
end
return unique(result)
end
"""
guided_path_finder(G, s, t; score, depth)
Find a path from vertex `s` to vertex `t` in an `ImplicitGraph` `G`.
* `score` is a function mapping vertices to `Int` values. It should decrease
as vertices get closer to `t`. Ideally, `score(t)` should be the smallest
possible value.
* `depth` controls the amount of look ahead as we explore each vertex.
The default value is `1`.
* `verbose` controls how often status information is printed. Use `0` for
no information.
"""
function guided_path_finder(
G::ImplicitGraph{T},
s::T,
t::T;
score::Function = x -> 1,
depth::Int = 1,
verbose::Int = 0,
)::Vector{T} where {T}
PQ = PriorityQueue{T,Int}()
PQ[s] = score(s)
visited = Set{T}() # Visited positions
trace_back = Dict{T,T}() # Reverse edges
trace_back[s] = s
if s == t
return [t]
end
best_vtx = s
best_score = score(s)
count = 0
while length(PQ) > 0
count += 1
v = dequeue!(PQ)
if score(v) < best_score
best_score = score(v)
best_vtx = v
end
if verbose > 0 && count % verbose == 0
println("Iteration = $count")
println("Queue size = $(length(PQ))")
println("Current state")
println(v)
println(
"Score = $(score(v))\t trying for $(score(t))\t with best so far $best_score\n\n",
)
end
if v == t
break
end
push!(visited, v)
edges = _edge_generator(G, v, depth)
for (x, y) in edges
if y ∉ keys(trace_back)
trace_back[y] = x
PQ[y] = score(y)
end
end
end
rev_path = T[]
push!(rev_path, t)
while true
x = rev_path[end]
if x == s
break
end
push!(rev_path, trace_back[x])
end
if verbose > 0
println("Finished after $count iterations")
end
return reverse(rev_path)
end
| ImplicitGraphs | https://github.com/scheinerman/ImplicitGraphs.jl.git |
|
[
"MIT"
] | 0.1.12 | 5b969585f5de557c023e5423a016c019f864e514 | code | 3483 | export iCycle, iPath, iGrid, iKnight, iCube, iShift
"""
`iCycle(n::Int, simple::Bool=true)` creates an implicit graph that is
a cycle graph with `n` vertices `1` through `n`. When `simple`
is `true`, the graph is undirected; when `false` it's a directed
cycle `1 → 2 → 3 → ⋯ → n → 1`.
"""
function iCycle(n::Int, simple::Bool = true)::ImplicitGraph{Int}
if n < 3
error("Number of vertices must be at least 3")
end
function N(v::Int)
a = mod1(v + 1, n)
b = mod1(v - 1, n)
if simple
return [b, a]
end
return [a]
end
has_vertex(v::Int) = 1 <= v <= n
return ImplicitGraph{Int}(has_vertex, N)
end
"""
`iPath(simple::Bool=true)` creates an implicit graph that is
a path graph on the integers. If `simple` is `true` vertex `v` is
has an edge to `v-1` and `v+1`; otherwise, `v` has an edge only to
`v+1`.
"""
function iPath(simple::Bool = true)::ImplicitGraph{Int}
yes(v::Int)::Bool = true
function N(v::Int)::Vector{Int}
if simple
return [v - 1, v + 1]
else
return [v + 1]
end
end
return ImplicitGraph{Int}(yes, N)
end
"""
`iGrid()` returns an infinite two-dimensional grid graph. Vertices are
of type `Tuple{Int,Int}`.
"""
function iGrid()::ImplicitGraph{Tuple{Int,Int}}
yes(v::Tuple{Int,Int})::Bool = true
function N(v::Tuple{Int,Int})::Vector{Tuple{Int,Int}}
a, b = v
return [(a, b - 1), (a, b + 1), (a - 1, b), (a + 1, b)]
end
return ImplicitGraph{Tuple{Int,Int}}(yes, N)
end
"""
`iKnight()` returns the Knight's move graph on an infinite
chessboard.
"""
function iKnight()::ImplicitGraph{Tuple{Int,Int}}
yes(v::Tuple{Int,Int})::Bool = true
function N(v::Tuple{Int,Int})::Vector{Tuple{Int,Int}}
a, b = v
neigh = [
(a + 1, b + 2),
(a + 1, b - 2),
(a + 2, b + 1),
(a + 2, b - 1),
(a - 1, b + 2),
(a - 1, b - 2),
(a - 2, b + 1),
(a - 2, b - 1),
]
return neigh
end
return ImplicitGraph{Tuple{Int,Int}}(yes, N)
end
"""
`iCube(d::Int)` creates an (implict) `d`-dimensional cube graph.
"""
function iCube(d::Int)::ImplicitGraph{String}
if d < 1
error("Dimension must be positive")
end
function dvec_check(s::String)::Bool
if length(s) != d
return false
end
for i = 1:d
if s[i] ∉ "01"
return false
end
end
return true
end
function N(v::String)
result = Vector{String}(undef, d)
for i = 1:d
head = v[1:i-1]
c = v[i] == '0' ? "1" : "0"
tail = v[i+1:end]
result[i] = head * c * tail
end
return result
end
return ImplicitGraph{String}(dvec_check, N)
end
using IterTools
"""
`iShift(alphabet,n)` creates an implicit shift digraph whose vertices
are `n`-tuples of elements of `alphabet`.
"""
function iShift(alphabet, n::Int)::ImplicitGraph
elts = collect(distinct(alphabet))
T = eltype(elts)
function has_vertex(v)::Bool
for i = 1:n
if v[i] ∉ elts
return false
end
end
return true
end
function N(v)
base = v[2:end]
result = [(base..., j) for j in elts]
return result
end
return ImplicitGraph{NTuple{n,T}}(has_vertex, N)
end
| ImplicitGraphs | https://github.com/scheinerman/ImplicitGraphs.jl.git |
|
[
"MIT"
] | 0.1.12 | 5b969585f5de557c023e5423a016c019f864e514 | code | 981 | using Test
using ImplicitGraphs
G = iGrid()
@test G[(1, 1), (1, 2)]
@test length(G[(0, 0)]) == 4
@test dist(G, (0, 0), (1, 1)) == 2
G = iCycle(10)
@test has(G, 1, 10)
@test length(find_path(G, 1, 5)) == 5
@test length(find_path_undirected(G, 1, 5)) == 5
G = iCycle(10, false)
@test !has(G, 1, 10)
G = iKnight()
@test deg(G, (0, 0)) == 8
G = iCube(4)
@test dist(G, "0000", "1111") == 4
G = iShift([1, 2, 3], 5)
@test deg(G, (1, 1, 1, 1, 1)) == 3
G = iKnight()
s = (5, 5)
t = (0, 0)
score(vw) = sum(abs.(vw))
P = guided_path_finder(G, s, t, score = score, depth = 2)
@test length(P) > 0
# abstract target vertices
multiplies_to_16(point) = (point[1] * point[2]) == 16
G = iGrid()
@test find_path(G, (1, 1), multiplies_to_16)[end] == (4, 4)
# cutoff depth
@test find_path(G, (0, 0), (3, 5), 8) == find_path(G, (0, 0), (3, 5))
@test length(find_path(G, (0, 0), (3, 5))) ==
length(find_path_undirected(G, (0, 0), (3, 5)))
@test isempty(find_path(G, (0, 0), (3, 5), 7))
| ImplicitGraphs | https://github.com/scheinerman/ImplicitGraphs.jl.git |
|
[
"MIT"
] | 0.1.12 | 5b969585f5de557c023e5423a016c019f864e514 | docs | 7364 | # ImplicitGraphs
An `ImplicitGraph` is a graph in which the vertices and edges are implicitly defined by two functions: one that tests for vertex membership and one that returns a list of the (out) neighbors of a vertex.
The vertex set of an `ImplicitGraph` may be finite or (implicitly) infinite. The (out) degrees, however, must be finite.
## Creating Graphs
An `ImplicitGraph` is defined as follows:
```
ImplicitGraph{T}(has_vertex, out_neighbors)
```
where
* `T` is the data type of the vertices.
* `has_vertex(v::T)::Bool` is a function that takes objects of type `T` as input and returns `true` if `v` is a vertex of the graph.
* `out_neighbors(v::T)::Vector{T}` is a function that takes objects of type `T` as input and returns a list of the (out) neighbors of `v`.
For example, the following creates an (essentially) infinite path whose vertices are integers (see the `iPath` function):
```julia
yes(v::Int)::Bool = true
N(v::Int)::Vector{Int} = [v-1, v+1]
G = ImplicitGraph{Int}(yes, N)
```
The `yes` function always returns `true` for any `Int`. The `N` function returns the two neighbors of a vertex `v`. (For a truly infinite path, use `BigInt` in place of `Int`.)
Note that if `v` is an element of its own neighbor set, that represents a loop at vertex `v`.
### Undirected and directed graphs
The user-supplied `out_neighbors` function can be used to create both undirected and directed graphs. If an undirected graph is intended, be sure that if `{v,w}` is an edge of the graph, then `w` will be in the list returned by `out_neighbors(v)` and `v` will be in the list returned by `out_neighbors(w)`.
To create an infinite *directed* path, the earlier example can be modified like this:
```julia
yes(v::Int)::Bool = true
N(v::Int)::Vector{Int} = [v+1]
G = ImplicitGraph{Int}(yes, N)
```
## Predefined Graphs
We provide a few basic graphs that can be created using the following methods:
* `iCycle(n::Int)` creates an undirected cycle with vertex set `{1,2,...,n}`;
`iCycle(n,false)` creates a directed `n`-cycle.
* `iPath()` creates an (essentially) infinite undirected path whose vertex set contains all integers (objects of type `Int`); `iPath(false)` creates a one-way infinite path `⋯ → -2 → -1 → 0 → 1 → 2 → ⋯`.
* `iGrid()` creates an (essentially) infinite grid whose vertices are ordered pairs of integers (objects of type `Int`).
* `iCube(d::Int)` creates a `d`-dimensional cube graph. The vertices are all `d`-long strings of `0`s and `1`s. Two vertices are adjacent iff they differ in exactly one bit.
* `iKnight()` creates the Knight's move graph on an (essentially) infinite chessboard. The vertices are pairs of integers (objects of type `Int`).
* `iShift(alphabet, n::Int)` creates the shift digraph whose vertices are `n`-tuples of elements of `alphabet`.
## Inspection
* To test if `v` is a vertex of an `ImplicitGraph` `G`, use `has(G)`. Note that the data type of `v` must match the element type of `G`. (The function `eltype` returns the data type of the vertices of the `ImplicitGraph`.)
* To test if `{v,w}` is an edge of `G` use `G[v,w]` or `has(G,v,w)`. Note that `v` and `w` must both be vertices of `G` or an error is thrown.
* To get a list of the (out) neighbors of a vertex `v`, use `G[v]`.
* To get the degree of a vertex in a graph, use `deg(G,v)`.
```
julia> G = iGrid()
ImplicitGraph{Tuple{Int64,Int64}}
julia> has_vertex(G,(1,2))
true
julia> G[(1,2)]
4-element Array{Tuple{Int64,Int64},1}:
(1, 1)
(1, 3)
(0, 2)
(2, 2)
julia> G[(1,2),(1,3)]
true
julia> deg(G,(5,0))
4
```
## Path Finding
### Shortest path
The function `find_path` finds a shortest path between vertices of a graph. This function may run without returning if the graph is infinite and disconnected.
```
julia> G = iGrid()
ImplicitGraph{Tuple{Int64, Int64}}
julia> find_path(G, (0, 0), (3, 5))
9-element Array{Tuple{Int64, Int64}, 1}:
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(0, 5)
(1, 5)
(2, 5)
(3, 5)
```
The function `dist` returns the length of a shortest path between vertices in the graph.
```
julia> dist(G, (0, 0), (3, 5))
8
```
For large undirected graphs, you may find that `find_path_undirected` runs faster.
It uses bidirectional search to reduce memory usage and runtime. It does not support
directed graphs, however.
#### Option: abstract target vertices
Optionally, instead of a single target vertex whose type is the same as other vertices of the `ImplicitGraph`, we can call `find_path` with this signature:
```
find_path(G::ImplicitGraph{T}, s::T, is_target::Function) where {T}
```
The function `is_target` is expected to take a vertex of `G` as its only argument and return a `Bool` which is `true` if the vertex is a target. In this way, we can search for a path from the source vertex to one of many target vertices, or a vertex with a specified property.
#### Option: cutoff depth
Path finding can consume an amout of memory that is exponential in the length of the path, which can crash Julia. To avoid this, we can call `find_path` with this signature:
```
find_path(G::ImplicitGraph{T}, s::T, t::T, cutoff_depth::Int=0) where {T}
```
Paths with length at most `cutoff_depth` will be found, but attempting to find a longer path results in an empty output (as if the path did not exist):
```
julia> G = iGrid()
ImplicitGraph{Tuple{Int64,Int64}}
julia> find_path(G, (0, 0), (3, 5), 8)
9-element Array{Tuple{Int64 ,Int64}, 1}:
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(0, 5)
(1, 5)
(2, 5)
(3, 5)
julia> IG.find_path(G, (0, 0), (3, 5), 7)
Tuple{Int64, Int64}[]
```
> **Note**: Setting `cutoff_depth` to `0` allows a search for paths of unlimited length; only
positive values limit the length.
### Guided path finding
The function `guided_path_finder` employs a score function to try to find a
path between vertices. It may be faster than `find_path`, but might not give a shortest path.
This function is called as follows: `guided_path_finder(G,s,t,score=sc, depth=d, verbose=0)` where
* `G` is an `ImplicitGraph`,
* `s` is the starting vertex of the desired path,
* `t` is the ending vertex of the desired path,
* `sc` is a score function that mapping vertices to integers and should get smaller as vertices get closer to `t` (and should minimize at `t`),
* `d` controls amount of look ahead (default is `1`), and
* `verbose` sets how often to print progess information (or `0` for no diagnostics).
```
julia> G = iKnight();
julia> s = (9,9); t = (0,0);
julia> sc(v) = sum(abs.(v)); # score of (a,b) is |a| + |b|
julia> guided_path_finder(G,s,t,score=sc,depth=1)
9-element Vector{Tuple{Int64, Int64}}:
(9, 9)
(8, 7)
(7, 5)
(6, 3)
(5, 1)
(3, 0)
(1, -1)
(-1, -2)
(0, 0)
# With better look-ahead we find a shorter path
julia> guided_path_finder(G,s,t,score=sc,depth=3)
7-element Vector{Tuple{Int64, Int64}}:
(9, 9)
(8, 7)
(7, 5)
(6, 3)
(4, 2)
(2, 1)
(0, 0)
```
Greater depth can find a shorter path, but that comes at a cost:
```
julia> using BenchmarkTools
julia> @btime guided_path_finder(G,s,t,score=sc,depth=1);
52.361 μs (1308 allocations: 81.05 KiB)
julia> @btime guided_path_finder(G,s,t,score=sc,depth=3);
407.546 μs (8691 allocations: 696.47 KiB)
```
## Extras
The `extras` directory contains additional code and examples that may be
useful in conjunction with the `ImplicitGraph` type. See the `README`
in that directory. | ImplicitGraphs | https://github.com/scheinerman/ImplicitGraphs.jl.git |
|
[
"MIT"
] | 0.1.12 | 5b969585f5de557c023e5423a016c019f864e514 | docs | 7364 | # ImplicitGraphs
An `ImplicitGraph` is a graph in which the vertices and edges are implicitly defined by two functions: one that tests for vertex membership and one that returns a list of the (out) neighbors of a vertex.
The vertex set of an `ImplicitGraph` may be finite or (implicitly) infinite. The (out) degrees, however, must be finite.
## Creating Graphs
An `ImplicitGraph` is defined as follows:
```
ImplicitGraph{T}(has_vertex, out_neighbors)
```
where
* `T` is the data type of the vertices.
* `has_vertex(v::T)::Bool` is a function that takes objects of type `T` as input and returns `true` if `v` is a vertex of the graph.
* `out_neighbors(v::T)::Vector{T}` is a function that takes objects of type `T` as input and returns a list of the (out) neighbors of `v`.
For example, the following creates an (essentially) infinite path whose vertices are integers (see the `iPath` function):
```julia
yes(v::Int)::Bool = true
N(v::Int)::Vector{Int} = [v-1, v+1]
G = ImplicitGraph{Int}(yes, N)
```
The `yes` function always returns `true` for any `Int`. The `N` function returns the two neighbors of a vertex `v`. (For a truly infinite path, use `BigInt` in place of `Int`.)
Note that if `v` is an element of its own neighbor set, that represents a loop at vertex `v`.
### Undirected and directed graphs
The user-supplied `out_neighbors` function can be used to create both undirected and directed graphs. If an undirected graph is intended, be sure that if `{v,w}` is an edge of the graph, then `w` will be in the list returned by `out_neighbors(v)` and `v` will be in the list returned by `out_neighbors(w)`.
To create an infinite *directed* path, the earlier example can be modified like this:
```julia
yes(v::Int)::Bool = true
N(v::Int)::Vector{Int} = [v+1]
G = ImplicitGraph{Int}(yes, N)
```
## Predefined Graphs
We provide a few basic graphs that can be created using the following methods:
* `iCycle(n::Int)` creates an undirected cycle with vertex set `{1,2,...,n}`;
`iCycle(n,false)` creates a directed `n`-cycle.
* `iPath()` creates an (essentially) infinite undirected path whose vertex set contains all integers (objects of type `Int`); `iPath(false)` creates a one-way infinite path `⋯ → -2 → -1 → 0 → 1 → 2 → ⋯`.
* `iGrid()` creates an (essentially) infinite grid whose vertices are ordered pairs of integers (objects of type `Int`).
* `iCube(d::Int)` creates a `d`-dimensional cube graph. The vertices are all `d`-long strings of `0`s and `1`s. Two vertices are adjacent iff they differ in exactly one bit.
* `iKnight()` creates the Knight's move graph on an (essentially) infinite chessboard. The vertices are pairs of integers (objects of type `Int`).
* `iShift(alphabet, n::Int)` creates the shift digraph whose vertices are `n`-tuples of elements of `alphabet`.
## Inspection
* To test if `v` is a vertex of an `ImplicitGraph` `G`, use `has(G)`. Note that the data type of `v` must match the element type of `G`. (The function `eltype` returns the data type of the vertices of the `ImplicitGraph`.)
* To test if `{v,w}` is an edge of `G` use `G[v,w]` or `has(G,v,w)`. Note that `v` and `w` must both be vertices of `G` or an error is thrown.
* To get a list of the (out) neighbors of a vertex `v`, use `G[v]`.
* To get the degree of a vertex in a graph, use `deg(G,v)`.
```
julia> G = iGrid()
ImplicitGraph{Tuple{Int64,Int64}}
julia> has_vertex(G,(1,2))
true
julia> G[(1,2)]
4-element Array{Tuple{Int64,Int64},1}:
(1, 1)
(1, 3)
(0, 2)
(2, 2)
julia> G[(1,2),(1,3)]
true
julia> deg(G,(5,0))
4
```
## Path Finding
### Shortest path
The function `find_path` finds a shortest path between vertices of a graph. This function may run without returning if the graph is infinite and disconnected.
```
julia> G = iGrid()
ImplicitGraph{Tuple{Int64, Int64}}
julia> find_path(G, (0, 0), (3, 5))
9-element Array{Tuple{Int64, Int64}, 1}:
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(0, 5)
(1, 5)
(2, 5)
(3, 5)
```
The function `dist` returns the length of a shortest path between vertices in the graph.
```
julia> dist(G, (0, 0), (3, 5))
8
```
For large undirected graphs, you may find that `find_path_undirected` runs faster.
It uses bidirectional search to reduce memory usage and runtime. It does not support
directed graphs, however.
#### Option: abstract target vertices
Optionally, instead of a single target vertex whose type is the same as other vertices of the `ImplicitGraph`, we can call `find_path` with this signature:
```
find_path(G::ImplicitGraph{T}, s::T, is_target::Function) where {T}
```
The function `is_target` is expected to take a vertex of `G` as its only argument and return a `Bool` which is `true` if the vertex is a target. In this way, we can search for a path from the source vertex to one of many target vertices, or a vertex with a specified property.
#### Option: cutoff depth
Path finding can consume an amout of memory that is exponential in the length of the path, which can crash Julia. To avoid this, we can call `find_path` with this signature:
```
find_path(G::ImplicitGraph{T}, s::T, t::T, cutoff_depth::Int=0) where {T}
```
Paths with length at most `cutoff_depth` will be found, but attempting to find a longer path results in an empty output (as if the path did not exist):
```
julia> G = iGrid()
ImplicitGraph{Tuple{Int64,Int64}}
julia> find_path(G, (0, 0), (3, 5), 8)
9-element Array{Tuple{Int64 ,Int64}, 1}:
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(0, 5)
(1, 5)
(2, 5)
(3, 5)
julia> IG.find_path(G, (0, 0), (3, 5), 7)
Tuple{Int64, Int64}[]
```
> **Note**: Setting `cutoff_depth` to `0` allows a search for paths of unlimited length; only
positive values limit the length.
### Guided path finding
The function `guided_path_finder` employs a score function to try to find a
path between vertices. It may be faster than `find_path`, but might not give a shortest path.
This function is called as follows: `guided_path_finder(G,s,t,score=sc, depth=d, verbose=0)` where
* `G` is an `ImplicitGraph`,
* `s` is the starting vertex of the desired path,
* `t` is the ending vertex of the desired path,
* `sc` is a score function that mapping vertices to integers and should get smaller as vertices get closer to `t` (and should minimize at `t`),
* `d` controls amount of look ahead (default is `1`), and
* `verbose` sets how often to print progess information (or `0` for no diagnostics).
```
julia> G = iKnight();
julia> s = (9,9); t = (0,0);
julia> sc(v) = sum(abs.(v)); # score of (a,b) is |a| + |b|
julia> guided_path_finder(G,s,t,score=sc,depth=1)
9-element Vector{Tuple{Int64, Int64}}:
(9, 9)
(8, 7)
(7, 5)
(6, 3)
(5, 1)
(3, 0)
(1, -1)
(-1, -2)
(0, 0)
# With better look-ahead we find a shorter path
julia> guided_path_finder(G,s,t,score=sc,depth=3)
7-element Vector{Tuple{Int64, Int64}}:
(9, 9)
(8, 7)
(7, 5)
(6, 3)
(4, 2)
(2, 1)
(0, 0)
```
Greater depth can find a shorter path, but that comes at a cost:
```
julia> using BenchmarkTools
julia> @btime guided_path_finder(G,s,t,score=sc,depth=1);
52.361 μs (1308 allocations: 81.05 KiB)
julia> @btime guided_path_finder(G,s,t,score=sc,depth=3);
407.546 μs (8691 allocations: 696.47 KiB)
```
## Extras
The `extras` directory contains additional code and examples that may be
useful in conjunction with the `ImplicitGraph` type. See the `README`
in that directory. | ImplicitGraphs | https://github.com/scheinerman/ImplicitGraphs.jl.git |
|
[
"MIT"
] | 0.1.12 | 5b969585f5de557c023e5423a016c019f864e514 | docs | 3203 | # `ImplicitGraphs` Extras
This directory contains additional code and examples associated with the `ImplicitGraph` type.
## `conversion.jl`
An `ImplicitGraph` may be infinite and so there is no universal way to convert an `ImplicitGraph` to an `UndirectedGraph` or a `DirectedGraph`. However, given a finite subset of the vertices, we can form the induced subgraph (or sub-digraph) on that subset.
* `UndirectedGraph(G::ImplicitGraph, A)` returns an undirected graph
(type `UndirectedGraph`) whose
vertex set is `A` and is the induced subgraph of `G` on that set.
* Likewise, `DirectedGraph(G::ImplicitGraph, A)` returns a directed graph
(type `DirectedGraph`).
## `iPaley.jl`
The `iPaley` function creates an implicit Paley graph. In particular, `iPaley(p)`
(where `p` is a prime congruennt to 1 modulo 4) creates a graph with vertex set `0:p-1`
in which two vertices are adjacent iff their difference is a quadratic residue modulo `p`.
## `iTransposition.jl`
The function `iTransposition(n)` creates an `ImplicitGraph` whose vertices
are all permutation of `1:n`. Two vertices of this graph are adjacent iff
they differ by a transposition.
* `iTransposition(n,true)` [default] only considers transpositions of the form `(a,a+1)` where `0 < a < n`.
* `iTransposition(n,false)` considers all transpositions `(a,b)` where `0<a<b≤n`.
As a demonstration of guided path finding, we include the function `crazy_trans_product`
to find a representation of a `Permutation` as the product of transpositions.
The function is invoked as
`crazy_trans_product(p::Permutation, adjacent::Bool=true)::String`
Example:
```
julia> p = RandomPermutation(10)
(1)(2,7,8,6,3,9)(4)(5,10)
julia> println(crazy_trans_product(p,true))
true
(5,6)(6,7)(5,6)(2,3)(3,4)(4,5)(3,4)(2,3)(7,8)(8,9)(7,8)(5,6)(6,7)(5,6)(9,10)(7,8)(8,9)(7,8)(3,4)(4,5)(3,4)(6,7)(7,8)(5,6)
julia> println(crazy_trans_product(p,false))
true
(7,8)(6,8)(2,3)(2,6)(5,10)(3,9)
```
An analogous result is given by `CoxeterDecomposition`:
```
julia> CoxeterDecomposition(p)
Permutation of 1:10: (2,3)(3,4)(2,3)(5,6)(4,5)(6,7)(5,6)(4,5)(3,4)(2,3)(7,8)(6,7)(5,6)(8,9)(7,8)(6,7)(5,6)(4,5)(3,4)(9,10)(8,9)(7,8)(6,7)(5,6)
```
We include the adjective *crazy* in the function name because it is much slower and
memory intensive than `CoxeterDecomposition`:
```
julia> using BenchmarkTools
julia> p = RandomPermutation(30);
julia> @btime CoxeterDecomposition(p);
384.528 μs (11 allocations: 5.25 KiB)
julia> @btime crazy_trans_product(p,true);
109.266 ms (387316 allocations: 63.06 MiB)
```
## `Collatz.jl`
The function `Collatz()` returns a directed graph represenation of the Collatz 3x+1 problem.
The vertices of the graph are positive integers. For a vertex `n`
there is exactly one edge emerging from `n` pointing either to
`n÷2` if `n` is even or to `3n+1` if `n` is odd.
```
julia> G = Collatz();
julia> find_path(G,12,1)
10-element Vector{Int64}:
12
6
3
10
5
16
8
4
2
1
```
The function `ReverseCollatz()` is the same as `Collatz()` except the edges are reversed.
```
julia> H = ReverseCollatz();
julia> find_path(H,1,12)
10-element Vector{Int64}:
1
2
4
8
16
5
10
3
6
12
```
| ImplicitGraphs | https://github.com/scheinerman/ImplicitGraphs.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 1525 | using JuliaInterpreter
using BenchmarkTools
const SUITE = BenchmarkGroup()
# Recursively call itself
f(i, j) = i == 0 ? j : f(i - 1, j + 1)
SUITE["recursive self 1_000"] = @benchmarkable @interpret f(1_000, 0)
# Long stack trace calling other functions
f0(i) = i
for i in 1:1_000
@eval $(Symbol("f", i))(i) = $(Symbol("f", i-1))(i)
end
SUITE["recursive other 1_000"] = @benchmarkable @interpret f1000(1)
# Tight loop
function f(X)
s = 0
for x in X
s += x
end
return s
end
const X = rand(1:10, 10_000)
SUITE["tight loop 10_000"] = @benchmarkable @interpret f(X)
# Throwing and catching an error over a large stacktrace
function g0(i)
try
g1(i)
catch e
e
end
end
for i in 1:1_000
@eval $(Symbol("g", i))(i) = $(Symbol("g", i+1))(i)
end
g1001(i) = error()
SUITE["throw long 1_000"] = @benchmarkable @interpret g0(1)
# Function with many statements
macro do_thing(expr, N)
e = Expr(:block)
for i in 1:N
push!(e.args, esc(expr))
end
return e
end
function counter()
a = 0
@do_thing(a = a + 1, 5_000)
return a
end
SUITE["long function 5_000"] = @benchmarkable @interpret counter()
# Ccall
function ccall_ptr(ptr, x, y)
ccall(ptr, Int, (Int, Int), x, y)
end
const ptr = @cfunction(+, Int, (Int, Int))
SUITE["ccall ptr"] = @benchmarkable @interpret ccall_ptr(ptr, 1, 5)
function powf(a, b)
ccall(("powf", Base.Math.libm), Float32, (Float32,Float32), a, b)
end
SUITE["ccall library"] = @benchmarkable @interpret powf(2, 3) | JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 12108 | # This file generates builtins.jl.
# Should be run on the latest Julia nightly
using InteractiveUtils
# All builtins present in 1.6
const ALWAYS_PRESENT = Core.Builtin[
(<:), (===), Core._abstracttype, Core._apply_iterate, Core._apply_pure,
Core._call_in_world, Core._call_latest, Core._equiv_typedef, Core._expr,
Core._primitivetype, Core._setsuper!, Core._structtype, Core._typebody!,
Core._typevar, Core.apply_type, Core.ifelse, Core.sizeof, Core.svec,
applicable, fieldtype, getfield, invoke, isa, isdefined, nfields,
setfield!, throw, tuple, typeassert, typeof
]
# Builtins present from 1.6, not builtins (potentially still normal functions) anymore
const RECENTLY_REMOVED = GlobalRef.(Ref(Core), [
:arrayref, :arrayset, :arrayset, :const_arrayref, :memoryref, :set_binding_type!
])
const kwinvoke = Core.kwfunc(Core.invoke)
function scopedname(f)
io = IOBuffer()
show(io, f)
fstr = String(take!(io))
occursin('.', fstr) && return fstr
tn = typeof(f).name
Base.isexported(tn.module, Symbol(fstr)) && return fstr
fsym = Symbol(fstr)
isdefined(tn.module, fsym) && return string(tn.module) * '.' * fstr
return "Base." * fstr
end
function nargs(f, table, id)
# Look up the expected number of arguments in Core.Compiler.tfunc data
if id !== nothing
minarg, maxarg, tfunc = table[id]
else
minarg = 0
maxarg = typemax(Int)
end
# Specialize ~arrayref and arrayset~ memoryrefnew for small numbers of arguments
# TODO: how about other memory intrinsics?
if (@static isdefined(Core, :memoryrefnew) ? f == Core.memoryrefnew : f == Core.memoryref)
maxarg = 5
end
return minarg, maxarg
end
function generate_fcall_nargs(fname, minarg, maxarg)
# Generate a separate call for each number of arguments
maxarg < typemax(Int) || error("call this only for constrained number of arguments")
annotation = fname == "fieldtype" ? "::Type" : ""
wrapper = "if nargs == "
for nargs = minarg:maxarg
wrapper *= "$nargs\n "
argcall = ""
for i = 1:nargs
argcall *= "@lookup(frame, args[$(i+1)])"
if i < nargs
argcall *= ", "
end
end
wrapper *= "return Some{Any}($fname($argcall)$annotation)"
if nargs < maxarg
wrapper *= "\n elseif nargs == "
end
end
wrapper *= "\n else"
wrapper *= "\n return Some{Any}($fname(getargs(args, frame)...)$annotation)" # to throw the correct error
wrapper *= "\n end"
return wrapper
end
function generate_fcall(f, table, id)
minarg, maxarg = nargs(f, table, id)
fname = scopedname(f)
if maxarg < typemax(Int)
return generate_fcall_nargs(fname, minarg, maxarg)
end
# A built-in with arbitrary or unknown number of arguments.
# This will (unfortunately) use dynamic dispatch.
return "return Some{Any}($fname(getargs(args, frame)...))"
end
# `io` is for the generated source file
# `intrinsicsfile` is the path to Julia's `src/intrinsics.h` file
function generate_builtins(file::String)
open(file, "w") do io
generate_builtins(io::IO)
end
end
function generate_builtins(io::IO)
pat = r"(ADD_I|ALIAS)\((\w*),"
print(io,
"""
# This file is generated by `generate_builtins.jl`. Do not edit by hand.
function getargs(args, frame)
nargs = length(args)-1 # skip f
callargs = resize!(frame.framedata.callargs, nargs)
for i = 1:nargs
callargs[i] = @lookup(frame, args[i+1])
end
return callargs
end
const kwinvoke = Core.kwfunc(Core.invoke)
function maybe_recurse_expanded_builtin(frame, new_expr)
f = new_expr.args[1]
if isa(f, Core.Builtin) || isa(f, Core.IntrinsicFunction)
return maybe_evaluate_builtin(frame, new_expr, true)
else
return new_expr
end
end
\"\"\"
ret = maybe_evaluate_builtin(frame, call_expr, expand::Bool)
If `call_expr` is to a builtin function, evaluate it, returning the result inside a `Some` wrapper.
Otherwise, return `call_expr`.
If `expand` is true, `Core._apply_iterate` calls will be resolved as a call to the applied function.
\"\"\"
function maybe_evaluate_builtin(frame, call_expr, expand::Bool)
args = call_expr.args
nargs = length(args) - 1
fex = args[1]
if isa(fex, QuoteNode)
f = fex.value
else
f = @lookup(frame, fex)
end
if @static isdefined(Core, :OpaqueClosure) && f isa Core.OpaqueClosure
if expand
if !Core.Compiler.uncompressed_ir(f.source).inferred
return Expr(:call, f, args[2:end]...)
else
@debug "not interpreting opaque closure \$f since it contains inferred code"
end
end
return Some{Any}(f(args...))
end
if !(isa(f, Core.Builtin) || isa(f, Core.IntrinsicFunction))
return call_expr
end
# By having each call appearing statically in the "switch" block below,
# each gets call-site optimized.
""")
firstcall = true
for ft in subtypes(Core.Builtin)
ft === Core.IntrinsicFunction && continue
ft === typeof(kwinvoke) && continue # handle this one later
head = firstcall ? "if" : "elseif"
firstcall = false
f = ft.instance
fname = scopedname(f)
# Tuple is common, especially for returned values from calls. It's worth avoiding
# dynamic dispatch through a call to `ntuple`.
if f === tuple
print(io,
"""
$head f === tuple
return Some{Any}(ntupleany(i->@lookup(frame, args[i+1]), length(args)-1))
""")
continue
elseif f === Core._apply_iterate
# Resolve varargs calls
print(io,
"""
$head f === Core._apply_iterate
argswrapped = getargs(args, frame)
if !expand
return Some{Any}(Core._apply_iterate(argswrapped...))
end
aw1 = argswrapped[1]::Function
@assert aw1 === Core.iterate || aw1 === Core.Compiler.iterate || aw1 === Base.iterate "cannot handle `_apply_iterate` with non iterate as first argument, got \$(aw1), \$(typeof(aw1))"
new_expr = Expr(:call, argswrapped[2])
popfirst!(argswrapped) # pop the iterate
popfirst!(argswrapped) # pop the function
argsflat = append_any(argswrapped...)
for x in argsflat
push!(new_expr.args, QuoteNode(x))
end
return maybe_recurse_expanded_builtin(frame, new_expr)
""")
continue
elseif f === Core.invoke
fstr = scopedname(f)
print(io,
"""
$head f === $fstr
if !expand
argswrapped = getargs(args, frame)
return Some{Any}($fstr(argswrapped...))
end
# This uses the original arguments to avoid looking them up twice
# See #442
return Expr(:call, invoke, args[2:end]...)
""")
continue
elseif f === Core._call_latest
print(io,
"""
elseif f === Core._call_latest
args = getargs(args, frame)
if !expand
return Some{Any}(Core._call_latest(args...))
end
new_expr = Expr(:call, args[1])
popfirst!(args)
for x in args
push!(new_expr.args, QuoteNode(x))
end
return maybe_recurse_expanded_builtin(frame, new_expr)
""")
continue
elseif f === Core.current_scope
print(io,
"""
elseif @static isdefined(Core, :current_scope) && f === Core.current_scope
if nargs == 0
currscope = Core.current_scope()
for scope in frame.framedata.current_scopes
currscope = Scope(currscope, scope.values...)
end
return Some{Any}(currscope)
else
return Some{Any}(Core.current_scope(getargs(args, frame)...))
end
""")
continue
end
id = findfirst(isequal(f), Core.Compiler.T_FFUNC_KEY)
fcall = generate_fcall(f, Core.Compiler.T_FFUNC_VAL, id)
if !(f in ALWAYS_PRESENT)
print(io,
"""
$head @static isdefined($(ft.name.module), $(repr(nameof(f)))) && f === $fname
$fcall
""")
else
print(io,
"""
$head f === $fname
$fcall
""")
end
firstcall = false
end
print(io,
"""
# Intrinsics
""")
print(io,
"""
elseif f === Base.cglobal
if nargs == 1
call_expr = copy(call_expr)
args2 = args[2]
call_expr.args[2] = isa(args2, QuoteNode) ? args2 : @lookup(frame, args2)
return Some{Any}(Core.eval(moduleof(frame), call_expr))
elseif nargs == 2
call_expr = copy(call_expr)
args2 = args[2]
call_expr.args[2] = isa(args2, QuoteNode) ? args2 : @lookup(frame, args2)
call_expr.args[3] = @lookup(frame, args[3])
return Some{Any}(Core.eval(moduleof(frame), call_expr))
end
""")
# recently removed builtins
for (; mod, name) in RECENTLY_REMOVED
minarg = 1
if name in (:arrayref, :const_arrayref, :memoryref)
maxarg = 5
elseif name === :arrayset
maxarg = 6
elseif name === :arraysize
maxarg = 2
elseif name === :set_binding_type!
minarg = 2
maxarg = 3
end
_scopedname = "$mod.$name"
fcall = generate_fcall_nargs(_scopedname, minarg, maxarg)
rname = repr(name)
print(io,
"""
elseif @static (isdefined($mod, $rname) && $_scopedname isa Core.Builtin) && f === $_scopedname
$fcall
""")
end
# Extract any intrinsics that support varargs
fva = []
minmin, maxmax = typemax(Int), 0
for fsym in names(Core.Intrinsics)
fsym === :Intrinsics && continue
isdefined(Base, fsym) || continue
f = getfield(Base, fsym)
id = reinterpret(Int32, f) + 1
minarg, maxarg = nargs(f, Core.Compiler.T_IFUNC, id)
if maxarg == typemax(Int)
push!(fva, f)
else
minmin = min(minmin, minarg)
maxmax = max(maxmax, maxarg)
end
end
for f in fva
id = reinterpret(Int32, f) + 1
fname = scopedname(f)
fcall = generate_fcall(f, Core.Compiler.T_IFUNC, id)
print(io,
"""
elseif f === $fname
$fcall
end
""")
end
# Now handle calls with bounded numbers of args
print(io,
"""
if isa(f, Core.IntrinsicFunction)
cargs = getargs(args, frame)
@static if isdefined(Core.Intrinsics, :have_fma)
if f === Core.Intrinsics.have_fma && length(cargs) == 1
cargs1 = cargs[1]
if cargs1 == Float64
return Some{Any}(FMA_FLOAT64[])
elseif cargs1 == Float32
return Some{Any}(FMA_FLOAT32[])
elseif cargs1 == Float16
return Some{Any}(FMA_FLOAT16[])
end
end
end
if f === Core.Intrinsics.muladd_float && length(cargs) == 3
a, b, c = cargs
Ta, Tb, Tc = typeof(a), typeof(b), typeof(c)
if !(Ta == Tb == Tc)
error("muladd_float: types of a, b, and c must match")
end
if Ta == Float64 && FMA_FLOAT64[]
f = Core.Intrinsics.fma_float
elseif Ta == Float32 && FMA_FLOAT32[]
f = Core.Intrinsics.fma_float
elseif Ta == Float16 && FMA_FLOAT16[]
f = Core.Intrinsics.fma_float
end
end
return Some{Any}(ccall(:jl_f_intrinsic_call, Any, (Any, Ptr{Any}, UInt32), f, cargs, length(cargs)))
""")
print(io,
"""
end
if isa(f, typeof(kwinvoke))
return Some{Any}(kwinvoke(getargs(args, frame)...))
end
return call_expr
end
""")
end
builtins_dir = get(ENV, "JULIAINTERPRETER_BUILTINS_DIR", joinpath(@__DIR__, "..", "src"))
generate_builtins(joinpath(builtins_dir, "builtins.jl"))
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 768 | using Documenter, JuliaInterpreter, Test, CodeTracking
DocMeta.setdocmeta!(JuliaInterpreter, :DocTestSetup, :(
begin
using JuliaInterpreter
JuliaInterpreter.clear_caches()
JuliaInterpreter.remove()
end); recursive=true)
makedocs(
modules = [JuliaInterpreter],
clean = false,
format = Documenter.HTML(prettyurls = get(ENV, "CI", nothing) == "true"),
sitename = "JuliaInterpreter.jl",
authors = "Keno Fischer, Tim Holy, Kristoffer Carlsson, and others",
linkcheck = !("skiplinks" in ARGS),
pages = [
"Home" => "index.md",
"ast.md",
"internals.md",
"dev_reference.md",
],
)
deploydocs(
repo = "github.com/JuliaDebug/JuliaInterpreter.jl.git",
push_preview = true
)
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 537 | module JuliaInterpreter
# We use a code structure where all `using` and `import`
# statements in the package that load anything other than
# a Julia base or stdlib package are located in this file here.
# Nothing else should appear in this file here, apart from
# the `include("packagedef.jl")` statement, which loads what
# we would normally consider the bulk of the package code.
# This somewhat unusual structure is in place to support
# the VS Code extension integration.
using CodeTracking
include("packagedef.jl")
end # module
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 14352 | using Base: Callable
const _breakpoints = AbstractBreakpoint[]
"""
breakpoints()::Vector{AbstractBreakpoint}
Return an array with all breakpoints.
"""
breakpoints() = _breakpoints
const breakpoint_update_hooks = []
"""
on_breakpoints_updated(f)
Register a two-argument function to be called after any update to the set of all
breakpoints. This includes their creation, deletion, enabling and disabling.
The function `f` should take two inputs:
- First argument is the function doing to update, this is provided to allow to dispatch
on its type. It will be one:
- `::typeof(breakpoint)` for the creation,
- `::typeof(remove)` for the deletion.
- `::typeof(update_states)` for disable/enable/toggleing
- Second argument is the breakpoint object that was changed.
If only desiring to handle some kinds of update, `f` should have fallback methods
to do nothing in the general case.
!!! warning
This feature is experimental, and may be modified or removed in a minor release.
"""
on_breakpoints_updated(f) = push!(breakpoint_update_hooks, f)
"""
firehooks(hooked_fun, bp::AbstractBreakpoint)
Trigger all hooks that were registered with [`on_breakpoints_updated`](@ref),
passing them the `hooked_fun` and the `bp`.
This should be called whenever the set of breakpoints is updated.
`hooked_fun` is the function doing the update, and `bp` is the relevent breakpoint being
updated _after_ the update is applied.
!!! warning
This feature is experimental, and may be modified or removed in a minor release.
"""
function firehooks(hooked_fun, bp::AbstractBreakpoint)
for hook in breakpoint_update_hooks
try
hook(hooked_fun, bp)
catch err
@warn "Hook function errored" hook hooked_fun bp exception=err
end
end
end
function add_to_existing_framecodes(bp::AbstractBreakpoint)
for framecode in values(framedict)
add_breakpoint_if_match!(framecode, bp)
end
end
function add_breakpoint_if_match!(framecode::FrameCode, bp::BreakpointSignature)
if framecode_matches_breakpoint(framecode, bp)
scope = framecode.scope
matching_file = if scope isa Method
scope.file
else
# TODO: make more precise?
first(framecode.src.linetable).file
end
stmtidxs = bp.line === 0 ? [1] : statementnumbers(framecode, bp.line, matching_file::Symbol)
stmtidxs === nothing && return
breakpoint!(framecode, stmtidxs, bp.condition, bp.enabled[])
foreach(stmtidx -> push!(bp.instances, BreakpointRef(framecode, stmtidx)), stmtidxs)
return
end
end
function framecode_matches_breakpoint(framecode::FrameCode, bp::BreakpointSignature)
function extract_function_from_method(m::Method)
sig = Base.unwrap_unionall(m.sig)
ft0 = sig.parameters[1]
ft = Base.unwrap_unionall(ft0)
if ft <: Function && isa(ft, DataType) && isdefined(ft, :instance)
return ft.instance
elseif isa(ft, DataType) && ft.name === Type.body.name
return ft.parameters[1]
else
return ft
end
end
meth = framecode.scope
meth isa Method || return false
bp.f isa Method && return meth === bp.f
f = extract_function_from_method(meth)
if !(bp.f === f || @static isdefined(Core, :kwcall) ?
f === Core.kwcall && let ftype = Base.unwrap_unionall(meth.sig).parameters[3]
!Base.has_free_typevars(ftype) && bp.f isa ftype
end :
Core.kwfunc(bp.f) === f
)
return false
end
bp.sig === nothing && return true
return bp.sig <: meth.sig
end
"""
breakpoint(f, [sig], [line], [condition])
Add a breakpoint to `f` with the specified argument types `sig`.¨
If `sig` is not given, the breakpoint will apply to all methods of `f`.
If `f` is a method, the breakpoint will only apply to that method.
Optionally specify an absolute line number `line` in the source file; the default
is to break upon entry at the first line of the body.
Without `condition`, the breakpoint will be triggered every time it is encountered;
the second only if `condition` evaluates to `true`.
`condition` should be written in terms of the arguments and local variables of `f`.
# Example
```julia
function radius2(x, y)
return x^2 + y^2
end
breakpoint(radius2, Tuple{Int,Int}, :(y > x))
```
"""
function breakpoint(f::Union{Method, Callable}, sig=nothing, line::Integer=0, condition::Condition=nothing)
if sig !== nothing && f isa Callable
sig = Base.to_tuple_type(sig)
sig = Tuple{_Typeof(f), sig.parameters...}
end
bp = BreakpointSignature(f, sig, line, condition, Ref(true), BreakpointRef[])
add_to_existing_framecodes(bp)
idx = findfirst(bp2 -> same_location(bp, bp2), _breakpoints)
if idx === nothing # creating new
push!(_breakpoints, bp)
else #Replace existing breakpoint
old_bp = _breakpoints[idx]
_breakpoints[idx] = bp
firehooks(remove, old_bp)
end
firehooks(breakpoint, bp)
return bp
end
breakpoint(f::Union{Method, Callable}, sig, condition::Condition) = breakpoint(f, sig, 0, condition)
breakpoint(f::Union{Method, Callable}, line::Integer, condition::Condition=nothing) = breakpoint(f, nothing, line, condition)
breakpoint(f::Union{Method, Callable}, condition::Condition) = breakpoint(f, nothing, 0, condition)
"""
breakpoint(file, line, [condition])
Set a breakpoint in `file` at `line`. The argument `file` can be a filename, a partial path or absolute path.
For example, `file = foo.jl` will match against all files with the name `foo.jl`,
`file = src/foo.jl` will match against all paths containing `src/foo.jl`, e.g. both `Foo/src/foo.jl` and `Bar/src/foo.jl`.
Absolute paths only matches against the file with that exact absolute path.
"""
function breakpoint(file::AbstractString, line::Integer, condition::Condition=nothing)
file = normpath(file)
apath = CodeTracking.maybe_fix_path(abspath(file))
ispath(apath) && (apath = realpath(apath))
bp = BreakpointFileLocation(file, apath, line, condition, Ref(true), BreakpointRef[])
add_to_existing_framecodes(bp)
idx = findfirst(bp2 -> same_location(bp, bp2), _breakpoints)
idx === nothing ? push!(_breakpoints, bp) : (_breakpoints[idx] = bp)
firehooks(breakpoint, bp)
return bp
end
function add_breakpoint_if_match!(framecode::FrameCode, bp::BreakpointFileLocation)
framecode_contains_file = false
matching_file = nothing
for file in framecode.unique_files
filepath = CodeTracking.maybe_fix_path(String(file))
if Base.samefile(bp.abspath, filepath) || endswith(filepath, bp.path)
framecode_contains_file = true
matching_file = file
break
end
end
framecode_contains_file || return nothing
stmtidxs = bp.line === 0 ? [1] : statementnumbers(framecode, bp.line, matching_file::Symbol)
stmtidxs === nothing && return
breakpoint!(framecode, stmtidxs, bp.condition, bp.enabled[])
foreach(stmtidx -> push!(bp.instances, BreakpointRef(framecode, stmtidx)), stmtidxs)
return
end
function shouldbreak(frame::Frame, pc::Int)
bps = frame.framecode.breakpoints
isassigned(bps, pc) || return false
bp = bps[pc]
bp.isactive || return false
return Base.invokelatest(bp.condition, frame)::Bool
end
function prepare_slotfunction(framecode::FrameCode, body::Union{Symbol,Expr})
framename, dataname = gensym("frame"), gensym("data")
assignments = Expr[:($dataname = $framename.framedata)]
default = Unassigned()
for slotname in unique(framecode.src.slotnames)
list = framecode.slotnamelists[slotname]
if length(list) == 1
maxexpr = :($dataname.last_reference[$(list[1])] > 0 ? $(list[1]) : 0)
else
maxcounter, maxidx = gensym("maxcounter"), gensym("maxidx")
maxexpr = quote
begin
$maxcounter, $maxidx = 0, 0
for l in $list
counter = $dataname.last_reference[l]
if counter > $maxcounter
$maxcounter, $maxidx = counter, l
end
end
$maxidx
end
end
end
maxexsym = gensym("slotid")
push!(assignments, :($maxexsym = $maxexpr))
push!(assignments, :($slotname = $maxexsym > 0 ? something($dataname.locals[$maxexsym]) : $default))
end
scope = framecode.scope
if isa(scope, Method)
syms = sparam_syms(scope)
for i = 1:length(syms)
push!(assignments, Expr(:(=), syms[i], :($dataname.sparams[$i])))
end
end
funcname = isa(scope, Method) ? gensym("slotfunction") : gensym(Symbol(scope, "_slotfunction"))
return Expr(:function, Expr(:call, funcname, framename), Expr(:block, assignments..., body))
end
_unpack(condition) = isa(condition, Expr) ? (Main, condition) : condition
## The fundamental implementations of breakpoint-setting
function breakpoint!(framecode::FrameCode, pc, condition::Condition=nothing, enabled=true)
stmtidx = pc
if condition === nothing
framecode.breakpoints[stmtidx] = BreakpointState(enabled)
else
mod, cond = _unpack(condition)
fex = prepare_slotfunction(framecode, cond)
framecode.breakpoints[stmtidx] = BreakpointState(enabled, Core.eval(mod, fex))
end
end
breakpoint!(framecode::FrameCode, pcs::AbstractArray, condition::Condition=nothing, enabled=true) =
foreach(pc -> breakpoint!(framecode, pc, condition, enabled), pcs)
breakpoint!(frame::Frame, pc=frame.pc, condition::Condition=nothing) =
breakpoint!(frame.framecode, pc, condition)
function update_states!(bp::AbstractBreakpoint)
foreach(bpref -> update_state!(bpref, bp.enabled[]), bp.instances)
firehooks(update_states!, bp)
end
update_state!(bp::BreakpointRef, v::Bool) = bp[] = v
"""
enable(bp::AbstractBreakpoint)
Enable breakpoint `bp`.
"""
enable(bp::AbstractBreakpoint) = (bp.enabled[] = true; update_states!(bp))
enable(bp::BreakpointRef) = update_state!(bp, true)
"""
disable(bp::AbstractBreakpoint)
Disable breakpoint `bp`. Disabled breakpoints can be re-enabled with [`enable`](@ref).
"""
disable(bp::AbstractBreakpoint) = (bp.enabled[] = false; update_states!(bp))
disable(bp::BreakpointRef) = update_state!(bp, false)
"""
remove(bp::AbstractBreakpoint)
Remove (delete) breakpoint `bp`. Removed breakpoints cannot be re-enabled.
"""
function remove(bp::AbstractBreakpoint)
idx = findfirst(isequal(bp), _breakpoints)
if idx !== nothing
bp = _breakpoints[idx]
deleteat!(_breakpoints, idx)
firehooks(remove, bp)
end
foreach(remove, bp.instances)
end
function remove(bp::BreakpointRef)
bp.framecode.breakpoints[bp.stmtidx] = BreakpointState(false, falsecondition)
return nothing
end
"""
toggle(bp::AbstractBreakpoint)
Toggle breakpoint `bp`.
"""
toggle(bp::AbstractBreakpoint) = (bp.enabled[] = !bp.enabled[]; update_states!(bp))
toggle(bp::BreakpointRef) = update_state!(bp, !bp[].isactive)
"""
enable()
Enable all breakpoints.
"""
enable() = foreach(enable, _breakpoints)
"""
disable()
Disable all breakpoints.
"""
disable() = foreach(disable, _breakpoints)
"""
remove()
Remove all breakpoints.
"""
function remove()
for bp in _breakpoints
foreach(remove, bp.instances)
end
empty!(_breakpoints)
end
"""
break_on(states...)
Turn on automatic breakpoints when any of the conditions described in `states` occurs.
The supported states are:
- `:error`: trigger a breakpoint any time an uncaught exception is thrown
- `:throw` : trigger a breakpoint any time a throw is executed (even if it will eventually be caught)
"""
function break_on(states::Vararg{Symbol})
for state in states
if state === :error
break_on_error[] = true
elseif state === :throw
break_on_throw[] = true
else
throw(ArgumentError(string("unsupported state :", state)))
end
end
end
"""
break_off(states...)
Turn off automatic breakpoints when any of the conditions described in `states` occurs.
See [`break_on`](@ref) for a description of valid states.
"""
function break_off(states::Vararg{Symbol})
for state in states
if state === :error
break_on_error[] = false
elseif state === :throw
break_on_throw[] = false
else
throw(ArgumentError(string("unsupported state :", state)))
end
end
end
"""
@breakpoint f(args...) condition=nothing
@breakpoint f(args...) line condition=nothing
Break upon entry, or at the specified line number, in the method called by `f(args...)`.
Optionally supply a condition expressed in terms of the arguments and internal variables
of the method.
If `line` is supplied, it must be a literal integer.
# Example
Suppose a method `mysum` is defined as follows, where the numbers to the left are the line
number in the file:
```
12 function mysum(A)
13 s = zero(eltype(A))
14 for a in A
15 s += a
16 end
17 return s
18 end
```
Then
```
@breakpoint mysum(A) 15 s>10
```
would cause execution of the loop to break whenever `s>10`.
"""
macro breakpoint(call_expr, args...)
whichexpr = InteractiveUtils.gen_call_with_extracted_types(__module__, :which, call_expr)
haveline, line, condition = false, 0, nothing
while !isempty(args)
arg = first(args)
if isa(arg, Integer)
haveline, line = true, arg
else
condition = arg
end
args = Base.tail(args)
end
condexpr = condition === nothing ? nothing : esc(Expr(:quote, condition))
if haveline
return quote
local method = $whichexpr
$breakpoint(method, $line, $condexpr)
end
else
return quote
local method = $whichexpr
$breakpoint(method, $condexpr)
end
end
end
struct BreakPointMarker end
const __BREAK_POINT_MARKER__ = BreakPointMarker()
"""
@bp
Insert a breakpoint at a location in the source code.
"""
macro bp()
return :(__BREAK_POINT_MARKER__)
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 27967 | # This file is generated by `generate_builtins.jl`. Do not edit by hand.
function getargs(args, frame)
nargs = length(args)-1 # skip f
callargs = resize!(frame.framedata.callargs, nargs)
for i = 1:nargs
callargs[i] = @lookup(frame, args[i+1])
end
return callargs
end
const kwinvoke = Core.kwfunc(Core.invoke)
function maybe_recurse_expanded_builtin(frame, new_expr)
f = new_expr.args[1]
if isa(f, Core.Builtin) || isa(f, Core.IntrinsicFunction)
return maybe_evaluate_builtin(frame, new_expr, true)
else
return new_expr
end
end
"""
ret = maybe_evaluate_builtin(frame, call_expr, expand::Bool)
If `call_expr` is to a builtin function, evaluate it, returning the result inside a `Some` wrapper.
Otherwise, return `call_expr`.
If `expand` is true, `Core._apply_iterate` calls will be resolved as a call to the applied function.
"""
function maybe_evaluate_builtin(frame, call_expr, expand::Bool)
args = call_expr.args
nargs = length(args) - 1
fex = args[1]
if isa(fex, QuoteNode)
f = fex.value
else
f = @lookup(frame, fex)
end
if @static isdefined(Core, :OpaqueClosure) && f isa Core.OpaqueClosure
if expand
if !Core.Compiler.uncompressed_ir(f.source).inferred
return Expr(:call, f, args[2:end]...)
else
@debug "not interpreting opaque closure $f since it contains inferred code"
end
end
return Some{Any}(f(args...))
end
if !(isa(f, Core.Builtin) || isa(f, Core.IntrinsicFunction))
return call_expr
end
# By having each call appearing statically in the "switch" block below,
# each gets call-site optimized.
if f === <:
if nargs == 2
return Some{Any}(<:(@lookup(frame, args[2]), @lookup(frame, args[3])))
else
return Some{Any}(<:(getargs(args, frame)...))
end
elseif f === ===
if nargs == 2
return Some{Any}(===(@lookup(frame, args[2]), @lookup(frame, args[3])))
else
return Some{Any}(===(getargs(args, frame)...))
end
elseif f === Core._abstracttype
return Some{Any}(Core._abstracttype(getargs(args, frame)...))
elseif f === Core._apply_iterate
argswrapped = getargs(args, frame)
if !expand
return Some{Any}(Core._apply_iterate(argswrapped...))
end
aw1 = argswrapped[1]::Function
@assert aw1 === Core.iterate || aw1 === Core.Compiler.iterate || aw1 === Base.iterate "cannot handle `_apply_iterate` with non iterate as first argument, got $(aw1), $(typeof(aw1))"
new_expr = Expr(:call, argswrapped[2])
popfirst!(argswrapped) # pop the iterate
popfirst!(argswrapped) # pop the function
argsflat = append_any(argswrapped...)
for x in argsflat
push!(new_expr.args, QuoteNode(x))
end
return maybe_recurse_expanded_builtin(frame, new_expr)
elseif f === Core._apply_pure
return Some{Any}(Core._apply_pure(getargs(args, frame)...))
elseif f === Core._call_in_world
return Some{Any}(Core._call_in_world(getargs(args, frame)...))
elseif @static isdefined(Core, :_call_in_world_total) && f === Core._call_in_world_total
return Some{Any}(Core._call_in_world_total(getargs(args, frame)...))
elseif f === Core._call_latest
args = getargs(args, frame)
if !expand
return Some{Any}(Core._call_latest(args...))
end
new_expr = Expr(:call, args[1])
popfirst!(args)
for x in args
push!(new_expr.args, QuoteNode(x))
end
return maybe_recurse_expanded_builtin(frame, new_expr)
elseif @static isdefined(Core, :_compute_sparams) && f === Core._compute_sparams
return Some{Any}(Core._compute_sparams(getargs(args, frame)...))
elseif f === Core._equiv_typedef
return Some{Any}(Core._equiv_typedef(getargs(args, frame)...))
elseif f === Core._expr
return Some{Any}(Core._expr(getargs(args, frame)...))
elseif f === Core._primitivetype
return Some{Any}(Core._primitivetype(getargs(args, frame)...))
elseif f === Core._setsuper!
return Some{Any}(Core._setsuper!(getargs(args, frame)...))
elseif f === Core._structtype
return Some{Any}(Core._structtype(getargs(args, frame)...))
elseif @static isdefined(Core, :_svec_ref) && f === Core._svec_ref
return Some{Any}(Core._svec_ref(getargs(args, frame)...))
elseif f === Core._typebody!
return Some{Any}(Core._typebody!(getargs(args, frame)...))
elseif f === Core._typevar
if nargs == 3
return Some{Any}(Core._typevar(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
else
return Some{Any}(Core._typevar(getargs(args, frame)...))
end
elseif f === Core.apply_type
return Some{Any}(Core.apply_type(getargs(args, frame)...))
elseif @static isdefined(Core, :compilerbarrier) && f === Core.compilerbarrier
if nargs == 2
return Some{Any}(Core.compilerbarrier(@lookup(frame, args[2]), @lookup(frame, args[3])))
else
return Some{Any}(Core.compilerbarrier(getargs(args, frame)...))
end
elseif @static isdefined(Core, :current_scope) && f === Core.current_scope
if nargs == 0
currscope = Core.current_scope()
for scope in frame.framedata.current_scopes
currscope = Scope(currscope, scope.values...)
end
return Some{Any}(currscope)
else
return Some{Any}(Core.current_scope(getargs(args, frame)...))
end
elseif @static isdefined(Core, :donotdelete) && f === Core.donotdelete
return Some{Any}(Core.donotdelete(getargs(args, frame)...))
elseif @static isdefined(Core, :finalizer) && f === Core.finalizer
if nargs == 2
return Some{Any}(Core.finalizer(@lookup(frame, args[2]), @lookup(frame, args[3])))
elseif nargs == 3
return Some{Any}(Core.finalizer(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
elseif nargs == 4
return Some{Any}(Core.finalizer(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
else
return Some{Any}(Core.finalizer(getargs(args, frame)...))
end
elseif @static isdefined(Core, :get_binding_type) && f === Core.get_binding_type
if nargs == 2
return Some{Any}(Core.get_binding_type(@lookup(frame, args[2]), @lookup(frame, args[3])))
else
return Some{Any}(Core.get_binding_type(getargs(args, frame)...))
end
elseif f === Core.ifelse
if nargs == 3
return Some{Any}(Core.ifelse(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
else
return Some{Any}(Core.ifelse(getargs(args, frame)...))
end
elseif @static isdefined(Core, :memoryref_isassigned) && f === Core.memoryref_isassigned
if nargs == 3
return Some{Any}(Core.memoryref_isassigned(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
else
return Some{Any}(Core.memoryref_isassigned(getargs(args, frame)...))
end
elseif @static isdefined(Core, :memoryrefget) && f === Core.memoryrefget
if nargs == 3
return Some{Any}(Core.memoryrefget(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
else
return Some{Any}(Core.memoryrefget(getargs(args, frame)...))
end
elseif @static isdefined(Core, :memoryrefmodify!) && f === Core.memoryrefmodify!
if nargs == 5
return Some{Any}(Core.memoryrefmodify!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6])))
else
return Some{Any}(Core.memoryrefmodify!(getargs(args, frame)...))
end
elseif @static isdefined(Core, :memoryrefnew) && f === Core.memoryrefnew
if nargs == 1
return Some{Any}(Core.memoryrefnew(@lookup(frame, args[2])))
elseif nargs == 2
return Some{Any}(Core.memoryrefnew(@lookup(frame, args[2]), @lookup(frame, args[3])))
elseif nargs == 3
return Some{Any}(Core.memoryrefnew(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
elseif nargs == 4
return Some{Any}(Core.memoryrefnew(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
elseif nargs == 5
return Some{Any}(Core.memoryrefnew(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6])))
else
return Some{Any}(Core.memoryrefnew(getargs(args, frame)...))
end
elseif @static isdefined(Core, :memoryrefoffset) && f === Core.memoryrefoffset
if nargs == 1
return Some{Any}(Core.memoryrefoffset(@lookup(frame, args[2])))
else
return Some{Any}(Core.memoryrefoffset(getargs(args, frame)...))
end
elseif @static isdefined(Core, :memoryrefreplace!) && f === Core.memoryrefreplace!
if nargs == 6
return Some{Any}(Core.memoryrefreplace!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6]), @lookup(frame, args[7])))
else
return Some{Any}(Core.memoryrefreplace!(getargs(args, frame)...))
end
elseif @static isdefined(Core, :memoryrefset!) && f === Core.memoryrefset!
if nargs == 4
return Some{Any}(Core.memoryrefset!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
else
return Some{Any}(Core.memoryrefset!(getargs(args, frame)...))
end
elseif @static isdefined(Core, :memoryrefsetonce!) && f === Core.memoryrefsetonce!
if nargs == 5
return Some{Any}(Core.memoryrefsetonce!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6])))
else
return Some{Any}(Core.memoryrefsetonce!(getargs(args, frame)...))
end
elseif @static isdefined(Core, :memoryrefswap!) && f === Core.memoryrefswap!
if nargs == 4
return Some{Any}(Core.memoryrefswap!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
else
return Some{Any}(Core.memoryrefswap!(getargs(args, frame)...))
end
elseif f === Core.sizeof
if nargs == 1
return Some{Any}(Core.sizeof(@lookup(frame, args[2])))
else
return Some{Any}(Core.sizeof(getargs(args, frame)...))
end
elseif f === Core.svec
return Some{Any}(Core.svec(getargs(args, frame)...))
elseif @static isdefined(Core, :throw_methoderror) && f === Core.throw_methoderror
return Some{Any}(Core.throw_methoderror(getargs(args, frame)...))
elseif f === applicable
return Some{Any}(applicable(getargs(args, frame)...))
elseif f === fieldtype
if nargs == 2
return Some{Any}(fieldtype(@lookup(frame, args[2]), @lookup(frame, args[3]))::Type)
elseif nargs == 3
return Some{Any}(fieldtype(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]))::Type)
else
return Some{Any}(fieldtype(getargs(args, frame)...)::Type)
end
elseif f === getfield
if nargs == 2
return Some{Any}(getfield(@lookup(frame, args[2]), @lookup(frame, args[3])))
elseif nargs == 3
return Some{Any}(getfield(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
elseif nargs == 4
return Some{Any}(getfield(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
else
return Some{Any}(getfield(getargs(args, frame)...))
end
elseif @static isdefined(Core, :getglobal) && f === getglobal
if nargs == 2
return Some{Any}(getglobal(@lookup(frame, args[2]), @lookup(frame, args[3])))
elseif nargs == 3
return Some{Any}(getglobal(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
else
return Some{Any}(getglobal(getargs(args, frame)...))
end
elseif f === invoke
if !expand
argswrapped = getargs(args, frame)
return Some{Any}(invoke(argswrapped...))
end
# This uses the original arguments to avoid looking them up twice
# See #442
return Expr(:call, invoke, args[2:end]...)
elseif f === isa
if nargs == 2
return Some{Any}(isa(@lookup(frame, args[2]), @lookup(frame, args[3])))
else
return Some{Any}(isa(getargs(args, frame)...))
end
elseif f === isdefined
if nargs == 2
return Some{Any}(isdefined(@lookup(frame, args[2]), @lookup(frame, args[3])))
elseif nargs == 3
return Some{Any}(isdefined(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
else
return Some{Any}(isdefined(getargs(args, frame)...))
end
elseif @static isdefined(Core, :modifyfield!) && f === modifyfield!
if nargs == 4
return Some{Any}(modifyfield!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
elseif nargs == 5
return Some{Any}(modifyfield!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6])))
else
return Some{Any}(modifyfield!(getargs(args, frame)...))
end
elseif @static isdefined(Core, :modifyglobal!) && f === modifyglobal!
if nargs == 4
return Some{Any}(modifyglobal!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
elseif nargs == 5
return Some{Any}(modifyglobal!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6])))
else
return Some{Any}(modifyglobal!(getargs(args, frame)...))
end
elseif f === nfields
if nargs == 1
return Some{Any}(nfields(@lookup(frame, args[2])))
else
return Some{Any}(nfields(getargs(args, frame)...))
end
elseif @static isdefined(Core, :replacefield!) && f === replacefield!
if nargs == 4
return Some{Any}(replacefield!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
elseif nargs == 5
return Some{Any}(replacefield!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6])))
elseif nargs == 6
return Some{Any}(replacefield!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6]), @lookup(frame, args[7])))
else
return Some{Any}(replacefield!(getargs(args, frame)...))
end
elseif @static isdefined(Core, :replaceglobal!) && f === replaceglobal!
if nargs == 4
return Some{Any}(replaceglobal!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
elseif nargs == 5
return Some{Any}(replaceglobal!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6])))
elseif nargs == 6
return Some{Any}(replaceglobal!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6]), @lookup(frame, args[7])))
else
return Some{Any}(replaceglobal!(getargs(args, frame)...))
end
elseif f === setfield!
if nargs == 3
return Some{Any}(setfield!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
elseif nargs == 4
return Some{Any}(setfield!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
else
return Some{Any}(setfield!(getargs(args, frame)...))
end
elseif @static isdefined(Core, :setfieldonce!) && f === setfieldonce!
if nargs == 3
return Some{Any}(setfieldonce!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
elseif nargs == 4
return Some{Any}(setfieldonce!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
elseif nargs == 5
return Some{Any}(setfieldonce!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6])))
else
return Some{Any}(setfieldonce!(getargs(args, frame)...))
end
elseif @static isdefined(Core, :setglobal!) && f === setglobal!
if nargs == 3
return Some{Any}(setglobal!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
elseif nargs == 4
return Some{Any}(setglobal!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
else
return Some{Any}(setglobal!(getargs(args, frame)...))
end
elseif @static isdefined(Core, :setglobalonce!) && f === setglobalonce!
if nargs == 3
return Some{Any}(setglobalonce!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
elseif nargs == 4
return Some{Any}(setglobalonce!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
elseif nargs == 5
return Some{Any}(setglobalonce!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6])))
else
return Some{Any}(setglobalonce!(getargs(args, frame)...))
end
elseif @static isdefined(Core, :swapfield!) && f === swapfield!
if nargs == 3
return Some{Any}(swapfield!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
elseif nargs == 4
return Some{Any}(swapfield!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
else
return Some{Any}(swapfield!(getargs(args, frame)...))
end
elseif @static isdefined(Core, :swapglobal!) && f === swapglobal!
if nargs == 3
return Some{Any}(swapglobal!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
elseif nargs == 4
return Some{Any}(swapglobal!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
else
return Some{Any}(swapglobal!(getargs(args, frame)...))
end
elseif f === throw
if nargs == 1
return Some{Any}(throw(@lookup(frame, args[2])))
else
return Some{Any}(throw(getargs(args, frame)...))
end
elseif f === tuple
return Some{Any}(ntupleany(i->@lookup(frame, args[i+1]), length(args)-1))
elseif f === typeassert
if nargs == 2
return Some{Any}(typeassert(@lookup(frame, args[2]), @lookup(frame, args[3])))
else
return Some{Any}(typeassert(getargs(args, frame)...))
end
elseif f === typeof
if nargs == 1
return Some{Any}(typeof(@lookup(frame, args[2])))
else
return Some{Any}(typeof(getargs(args, frame)...))
end
# Intrinsics
elseif f === Base.cglobal
if nargs == 1
call_expr = copy(call_expr)
args2 = args[2]
call_expr.args[2] = isa(args2, QuoteNode) ? args2 : @lookup(frame, args2)
return Some{Any}(Core.eval(moduleof(frame), call_expr))
elseif nargs == 2
call_expr = copy(call_expr)
args2 = args[2]
call_expr.args[2] = isa(args2, QuoteNode) ? args2 : @lookup(frame, args2)
call_expr.args[3] = @lookup(frame, args[3])
return Some{Any}(Core.eval(moduleof(frame), call_expr))
end
elseif @static (isdefined(Core, :arrayref) && Core.arrayref isa Core.Builtin) && f === Core.arrayref
if nargs == 1
return Some{Any}(Core.arrayref(@lookup(frame, args[2])))
elseif nargs == 2
return Some{Any}(Core.arrayref(@lookup(frame, args[2]), @lookup(frame, args[3])))
elseif nargs == 3
return Some{Any}(Core.arrayref(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
elseif nargs == 4
return Some{Any}(Core.arrayref(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
elseif nargs == 5
return Some{Any}(Core.arrayref(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6])))
else
return Some{Any}(Core.arrayref(getargs(args, frame)...))
end
elseif @static (isdefined(Core, :arrayset) && Core.arrayset isa Core.Builtin) && f === Core.arrayset
if nargs == 1
return Some{Any}(Core.arrayset(@lookup(frame, args[2])))
elseif nargs == 2
return Some{Any}(Core.arrayset(@lookup(frame, args[2]), @lookup(frame, args[3])))
elseif nargs == 3
return Some{Any}(Core.arrayset(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
elseif nargs == 4
return Some{Any}(Core.arrayset(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
elseif nargs == 5
return Some{Any}(Core.arrayset(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6])))
elseif nargs == 6
return Some{Any}(Core.arrayset(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6]), @lookup(frame, args[7])))
else
return Some{Any}(Core.arrayset(getargs(args, frame)...))
end
elseif @static (isdefined(Core, :arrayset) && Core.arrayset isa Core.Builtin) && f === Core.arrayset
if nargs == 1
return Some{Any}(Core.arrayset(@lookup(frame, args[2])))
elseif nargs == 2
return Some{Any}(Core.arrayset(@lookup(frame, args[2]), @lookup(frame, args[3])))
elseif nargs == 3
return Some{Any}(Core.arrayset(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
elseif nargs == 4
return Some{Any}(Core.arrayset(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
elseif nargs == 5
return Some{Any}(Core.arrayset(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6])))
elseif nargs == 6
return Some{Any}(Core.arrayset(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6]), @lookup(frame, args[7])))
else
return Some{Any}(Core.arrayset(getargs(args, frame)...))
end
elseif @static (isdefined(Core, :const_arrayref) && Core.const_arrayref isa Core.Builtin) && f === Core.const_arrayref
if nargs == 1
return Some{Any}(Core.const_arrayref(@lookup(frame, args[2])))
elseif nargs == 2
return Some{Any}(Core.const_arrayref(@lookup(frame, args[2]), @lookup(frame, args[3])))
elseif nargs == 3
return Some{Any}(Core.const_arrayref(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
elseif nargs == 4
return Some{Any}(Core.const_arrayref(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
elseif nargs == 5
return Some{Any}(Core.const_arrayref(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6])))
else
return Some{Any}(Core.const_arrayref(getargs(args, frame)...))
end
elseif @static (isdefined(Core, :memoryref) && Core.memoryref isa Core.Builtin) && f === Core.memoryref
if nargs == 1
return Some{Any}(Core.memoryref(@lookup(frame, args[2])))
elseif nargs == 2
return Some{Any}(Core.memoryref(@lookup(frame, args[2]), @lookup(frame, args[3])))
elseif nargs == 3
return Some{Any}(Core.memoryref(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
elseif nargs == 4
return Some{Any}(Core.memoryref(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5])))
elseif nargs == 5
return Some{Any}(Core.memoryref(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4]), @lookup(frame, args[5]), @lookup(frame, args[6])))
else
return Some{Any}(Core.memoryref(getargs(args, frame)...))
end
elseif @static (isdefined(Core, :set_binding_type!) && Core.set_binding_type! isa Core.Builtin) && f === Core.set_binding_type!
if nargs == 2
return Some{Any}(Core.set_binding_type!(@lookup(frame, args[2]), @lookup(frame, args[3])))
elseif nargs == 3
return Some{Any}(Core.set_binding_type!(@lookup(frame, args[2]), @lookup(frame, args[3]), @lookup(frame, args[4])))
else
return Some{Any}(Core.set_binding_type!(getargs(args, frame)...))
end
elseif f === Core.Intrinsics.llvmcall
return Some{Any}(Core.Intrinsics.llvmcall(getargs(args, frame)...))
end
if isa(f, Core.IntrinsicFunction)
cargs = getargs(args, frame)
@static if isdefined(Core.Intrinsics, :have_fma)
if f === Core.Intrinsics.have_fma && length(cargs) == 1
cargs1 = cargs[1]
if cargs1 == Float64
return Some{Any}(FMA_FLOAT64[])
elseif cargs1 == Float32
return Some{Any}(FMA_FLOAT32[])
elseif cargs1 == Float16
return Some{Any}(FMA_FLOAT16[])
end
end
end
if f === Core.Intrinsics.muladd_float && length(cargs) == 3
a, b, c = cargs
Ta, Tb, Tc = typeof(a), typeof(b), typeof(c)
if !(Ta == Tb == Tc)
error("muladd_float: types of a, b, and c must match")
end
if Ta == Float64 && FMA_FLOAT64[]
f = Core.Intrinsics.fma_float
elseif Ta == Float32 && FMA_FLOAT32[]
f = Core.Intrinsics.fma_float
elseif Ta == Float16 && FMA_FLOAT16[]
f = Core.Intrinsics.fma_float
end
end
return Some{Any}(ccall(:jl_f_intrinsic_call, Any, (Any, Ptr{Any}, UInt32), f, cargs, length(cargs)))
end
if isa(f, typeof(kwinvoke))
return Some{Any}(kwinvoke(getargs(args, frame)...))
end
return call_expr
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 24021 | """
pc = finish!(recurse, frame, istoplevel=false)
pc = finish!(frame, istoplevel=false)
Run `frame` until execution terminates. `pc` is either `nothing` (if execution terminates
when it hits a `return` statement) or a reference to a breakpoint.
In the latter case, `leaf(frame)` returns the frame in which it hit the breakpoint.
`recurse` controls call evaluation; `recurse = Compiled()` evaluates :call expressions
by normal dispatch, whereas the default `recurse = finish_and_return!` uses recursive interpretation.
"""
function finish!(@nospecialize(recurse), frame::Frame, istoplevel::Bool=false)
while true
pc = step_expr!(recurse, frame, istoplevel)
pc === nothing && return pc
isa(pc, BreakpointRef) && return pc
shouldbreak(frame, pc) && return BreakpointRef(frame.framecode, pc)
end
end
finish!(frame::Frame, istoplevel::Bool=false) = finish!(finish_and_return!, frame, istoplevel)
"""
ret = finish_and_return!(recurse, frame, istoplevel::Bool=false)
ret = finish_and_return!(frame, istoplevel::Bool=false)
Call [`JuliaInterpreter.finish!`](@ref) and pass back the return value `ret`. If execution
pauses at a breakpoint, `ret` is the reference to the breakpoint.
"""
function finish_and_return!(@nospecialize(recurse), frame::Frame, istoplevel::Bool=false)
pc = finish!(recurse, frame, istoplevel)
isa(pc, BreakpointRef) && return pc
return get_return(frame)
end
finish_and_return!(frame::Frame, istoplevel::Bool=false) = finish_and_return!(finish_and_return!, frame, istoplevel)
"""
bpref = dummy_breakpoint(recurse, frame::Frame, istoplevel)
Return a fake breakpoint. `dummy_breakpoint` can be useful as the `recurse` argument to
`evaluate_call!` (or any of the higher-order commands) to ensure that you return immediately
after stepping into a call.
"""
dummy_breakpoint(@nospecialize(recurse), frame::Frame, istoplevel) = BreakpointRef(frame.framecode, 0)
"""
ret = finish_stack!(recurse, frame, rootistoplevel=false)
ret = finish_stack!(frame, rootistoplevel=false)
Unwind the callees of `frame`, finishing each before returning to the caller.
`frame` itself is also finished. `rootistoplevel` should be true if the root frame is top-level.
`ret` is typically the returned value. If execution hits a breakpoint, `ret` will be a
reference to the breakpoint.
"""
function finish_stack!(@nospecialize(recurse), frame::Frame, rootistoplevel::Bool=false)
frame0 = frame
frame = leaf(frame)
while true
istoplevel = rootistoplevel && frame.caller === nothing
ret = finish_and_return!(recurse, frame, istoplevel)
isa(ret, BreakpointRef) && return ret
frame === frame0 && return ret
frame = return_from(frame)
frame === nothing && return ret
pc = frame.pc
if isassign(frame, pc)
lhs = SSAValue(pc)
do_assignment!(frame, lhs, ret)
else
stmt = pc_expr(frame, pc)
if isexpr(stmt, :(=))
lhs = stmt.args[1]
do_assignment!(frame, lhs, ret)
end
end
pc += 1
frame.pc = pc
shouldbreak(frame, pc) && return BreakpointRef(frame.framecode, pc)
end
end
finish_stack!(frame::Frame, istoplevel::Bool=false) = finish_stack!(finish_and_return!, frame, istoplevel)
"""
pc = next_until!(predicate, recurse, frame, istoplevel=false)
pc = next_until!(predicate, frame, istoplevel=false)
Execute the current statement. Then step through statements of `frame` until the next
statement satisfies `predicate(frame)`. `pc` will be the index of the statement at which
evaluation terminates, `nothing` (if the frame reached a `return`), or a `BreakpointRef`.
"""
function next_until!(@nospecialize(predicate), @nospecialize(recurse), frame::Frame, istoplevel::Bool=false)
pc = step_expr!(recurse, frame, istoplevel)
while pc !== nothing && !isa(pc, BreakpointRef)
shouldbreak(frame, pc) && return BreakpointRef(frame.framecode, pc)
predicate(frame) && return pc
pc = step_expr!(recurse, frame, istoplevel)
end
return pc
end
next_until!(predicate, frame::Frame, istoplevel::Bool=false) =
next_until!(predicate, finish_and_return!, frame, istoplevel)
"""
pc = maybe_next_until!(predicate, recurse, frame, istoplevel=false)
pc = maybe_next_until!(predicate, frame, istoplevel=false)
Like [`next_until!`](@ref) except checks `predicate` before executing the current statment.
"""
function maybe_next_until!(@nospecialize(predicate), @nospecialize(recurse), frame::Frame, istoplevel::Bool=false)
predicate(frame) && return frame.pc
return next_until!(predicate, recurse, frame, istoplevel)
end
maybe_next_until!(@nospecialize(predicate), frame::Frame, istoplevel::Bool=false) =
maybe_next_until!(predicate, finish_and_return!, frame, istoplevel)
"""
pc = next_call!(recurse, frame, istoplevel=false)
pc = next_call!(frame, istoplevel=false)
Execute the current statement. Continue stepping through `frame` until the next
`ReturnNode` or `:call` expression.
"""
next_call!(@nospecialize(recurse), frame::Frame, istoplevel::Bool=false) =
next_until!(frame -> is_call_or_return(pc_expr(frame)), recurse, frame, istoplevel)
next_call!(frame::Frame, istoplevel::Bool=false) = next_call!(finish_and_return!, frame, istoplevel)
"""
pc = maybe_next_call!(recurse, frame, istoplevel=false)
pc = maybe_next_call!(frame, istoplevel=false)
Return the current program counter of `frame` if it is a `ReturnNode` or `:call` expression.
Otherwise, step through the statements of `frame` until the next `ReturnNode` or `:call` expression.
"""
maybe_next_call!(@nospecialize(recurse), frame::Frame, istoplevel::Bool=false) =
maybe_next_until!(frame -> is_call_or_return(pc_expr(frame)), recurse, frame, istoplevel)
maybe_next_call!(frame::Frame, istoplevel::Bool=false) = maybe_next_call!(finish_and_return!, frame, istoplevel)
"""
pc = through_methoddef_or_done!(recurse, frame)
pc = through_methoddef_or_done!(frame)
Runs `frame` at top level until it either finishes (e.g., hits a `return` statement)
or defines a new method.
"""
function through_methoddef_or_done!(@nospecialize(recurse), frame::Frame)
predicate(frame) = (stmt = pc_expr(frame); isexpr(stmt, :method, 3) || isexpr(stmt, :thunk))
pc = next_until!(predicate, recurse, frame, true)
(pc === nothing || isa(pc, BreakpointRef)) && return pc
return step_expr!(recurse, frame, true) # define the method and return
end
through_methoddef_or_done!(@nospecialize(recurse), t::Tuple{Module,Expr,Frame}) =
through_methoddef_or_done!(recurse, t[end])
through_methoddef_or_done!(@nospecialize(recurse), modex::Tuple{Module,Expr,Expr}) = Core.eval(modex[1], modex[3])
through_methoddef_or_done!(@nospecialize(recurse), ::Nothing) = nothing
through_methoddef_or_done!(arg) = through_methoddef_or_done!(finish_and_return!, arg)
# Sentinel to see if the call was a wrapper call
struct Wrapper end
"""
pc = next_line!(recurse, frame, istoplevel=false)
pc = next_line!(frame, istoplevel=false)
Execute until reaching the first call of the next line of the source code.
Upon return, `pc` is either the new program counter, `nothing` if a `return` is reached,
or a `BreakpointRef` if it encountered a wrapper call. In the latter case, call `leaf(frame)`
to obtain the new execution frame.
"""
function next_line!(@nospecialize(recurse), frame::Frame, istoplevel::Bool=false)
pc = frame.pc
initialline, initialfile = linenumber(frame, pc), getfile(frame, pc)
if initialline === nothing || initialfile === nothing
return step_expr!(recurse, frame, istoplevel)
end
return _next_line!(recurse, frame, istoplevel, initialline, initialfile) # avoid boxing
end
function _next_line!(@nospecialize(recurse), frame::Frame, istoplevel, initialline::Int, initialfile::String)
predicate(frame) = is_return(pc_expr(frame)) || (linenumber(frame) != initialline || getfile(frame) != initialfile)
pc = next_until!(predicate, recurse, frame, istoplevel)
(pc === nothing || isa(pc, BreakpointRef)) && return pc
maybe_step_through_kwprep!(recurse, frame, istoplevel)
maybe_next_call!(recurse, frame, istoplevel)
end
next_line!(frame::Frame, istoplevel::Bool=false) = next_line!(finish_and_return!, frame, istoplevel)
"""
pc = until_line!(recurse, frame, line=nothing istoplevel=false)
pc = until_line!(frame, line=nothing, istoplevel=false)
Execute until the current frame reaches a line greater than `line`. If `line == nothing`
execute until the current frame reaches any line greater than the current line.
"""
function until_line!(@nospecialize(recurse), frame::Frame, line::Union{Nothing, Integer}=nothing, istoplevel::Bool=false)
pc = frame.pc
initialline, initialfile = linenumber(frame, pc), getfile(frame, pc)
line === nothing && (line = initialline + 1)
predicate(frame) = is_return(pc_expr(frame)) || (linenumber(frame) >= line && getfile(frame) == initialfile)
pc = next_until!(predicate, frame, istoplevel)
(pc === nothing || isa(pc, BreakpointRef)) && return pc
maybe_step_through_kwprep!(recurse, frame, istoplevel)
maybe_next_call!(recurse, frame, istoplevel)
end
until_line!(frame::Frame, line::Union{Nothing, Integer}=nothing, istoplevel::Bool=false) = until_line!(finish_and_return!, frame, line, istoplevel)
"""
cframe = maybe_step_through_wrapper!(recurse, frame)
cframe = maybe_step_through_wrapper!(frame)
Return the new frame of execution, potentially stepping through "wrapper" methods like those
that supply default positional arguments or handle keywords. `cframe` is the leaf frame from
which execution should start.
"""
function maybe_step_through_wrapper!(@nospecialize(recurse), frame::Frame)
code = frame.framecode
src = code.src
stmts, scope = src.code, code.scope::Method
length(stmts) < 2 && return frame
last = stmts[end-1]
isexpr(last, :(=)) && (last = last.args[2])
is_kw = false
if isa(scope, Method)
unwrap1 = Base.unwrap_unionall(scope.sig)
if unwrap1 isa DataType
param1 = Base.unwrap_unionall(unwrap1.parameters[1])
if param1 isa DataType
is_kw = isdefined(Core, :kwcall) ? param1.name.name === Symbol("#kwcall") :
endswith(String(param1.name.name), "#kw")
end
end
end
has_selfarg = isexpr(last, :call) && any(@nospecialize(x) -> isa(x, SlotNumber) && x.id == 1, last.args) # isequal(SlotNumber(1)) vulnerable to invalidation
issplatcall, _callee = unpack_splatcall(last, src)
if is_kw || has_selfarg || (issplatcall && is_bodyfunc(_callee))
# If the last expr calls #self# or passes it to an implementation method,
# this is a wrapper function that we might want to step through
while frame.pc != length(stmts)-1
pc = next_call!(recurse, frame, false) # since we're in a Method we're not at toplevel
if pc === nothing || isa(pc, BreakpointRef)
return frame
end
end
ret = evaluate_call!(dummy_breakpoint, frame, last)
if !isa(ret, BreakpointRef) # Happens if next call is Compiled
return frame
end
frame.framedata.ssavalues[frame.pc] = Wrapper()
return maybe_step_through_wrapper!(recurse, callee(frame))
end
maybe_step_through_nkw_meta!(frame)
return frame
end
maybe_step_through_wrapper!(frame::Frame) = maybe_step_through_wrapper!(finish_and_return!, frame)
if isdefined(Core, :kwcall)
const kwhandler = Core.kwcall
const kwextrastep = 0
else
const kwhandler = Core.kwfunc
const kwextrastep = 1
end
"""
frame = maybe_step_through_kwprep!(recurse, frame)
frame = maybe_step_through_kwprep!(frame)
If `frame.pc` points to the beginning of preparatory work for calling a keyword-argument
function, advance forward until the actual call.
"""
function maybe_step_through_kwprep!(@nospecialize(recurse), frame::Frame, istoplevel::Bool=false)
# XXX This code just does pattern-matching based on the current state of the compiler
# internals, which means this is very fragile against any future changes to those
# internals. We really need a more general and robust solution, but achieving that
# would mean simplifying and unifying how "keyword function" is represented and
# implemented. For the time being, our best bet is to keep tweaking it as best as we can.
pc, src = frame.pc, frame.framecode.src
n = length(src.code)
stmt = pc_expr(frame, pc)
if isa(stmt, Tuple{Symbol,Vararg{Symbol}})
# Check to see if we're creating a NamedTuple followed by kwfunc call
pccall = pc + 4 + kwextrastep
if pccall <= n
stmt1 = src.code[pc+1]
# We deliberately check isexpr(stmt, :call) rather than is_call(stmt): if it's
# assigned to a local, it's *not* kwarg preparation.
if isexpr(stmt1, :call) && is_quotenode_egal(stmt1.args[1], Core.apply_type) && is_quoted_type(stmt1.args[2], :NamedTuple)
stmt4, stmt5 = src.code[pc+4], src.code[pc+5]
if isexpr(stmt4, :call) && is_quotenode_egal(stmt4.args[1], kwhandler)
while pc < pccall
pc = step_expr!(recurse, frame, istoplevel)
end
return frame
elseif isexpr(stmt5, :call) && is_quotenode_egal(stmt5.args[1], kwhandler) && pccall+1 <= n
# This happens when the call is scoped by a module
pccall += 1
while pc < pccall
pc = step_expr!(recurse, frame, istoplevel)
end
maybe_next_call!(recurse, frame, istoplevel)
return frame
end
end
end
elseif isexpr(stmt, :call) && is_quoted_type(stmt.args[1], :NamedTuple) && length(stmt.args) == 1
# Creating an empty NamedTuple, now split by type (no supplied kwargs vs kwargs...)
if pc + 1 <= n
stmt1 = src.code[pc+1]
if isexpr(stmt1, :call)
f = stmt1.args[1]
if is_quotenode_egal(f, Base.pairs)
# No supplied kwargs
pcsplat = pc + 3
if pcsplat <= n
issplatcall, callee = unpack_splatcall(src.code[pcsplat], src)
if issplatcall && is_bodyfunc(callee)
while pc < pcsplat
pc = step_expr!(recurse, frame, istoplevel)
end
return frame
end
end
pccall = pc + 2
if pccall <= n
stmt2 = src.code[pccall]
if isa(stmt2, Expr)
if stmt2.head === :call && length(stmt2.args) >= 3 && stmt2.args[2] === SSAValue(pc+1) && stmt2.args[3] === SlotNumber(1)
while pc < pccall
pc = step_expr!(recurse, frame, istoplevel)
end
end
end
end
elseif is_quotenode_egal(f, Base.merge) && ((pccall = pc + 7) <= n)
stmtk = src.code[pccall-1]
if isexpr(stmtk, :call) && is_quotenode_egal(stmtk.args[1], kwhandler)
for i = 1:4
pc = step_expr!(recurse, frame, istoplevel)
end
stmti = src.code[pc]
if isexpr(stmti, :call) && is_quotenode_egal(stmti.args[1], #= deliberately not kwhandler =# Core.kwfunc)
pc = step_expr!(recurse, frame, istoplevel)
end
end
end
end
end
end
return frame
end
maybe_step_through_kwprep!(frame::Frame, istoplevel::Bool=false) =
maybe_step_through_kwprep!(finish_and_return!, frame, istoplevel)
"""
ret = maybe_reset_frame!(recurse, frame, pc, rootistoplevel)
Perform a return to the caller, or descend to the level of a breakpoint.
`pc` is the return state from the previous command (e.g., `next_call!` or similar).
`rootistoplevel` should be true if the root frame is top-level.
`ret` will be `nothing` if we have just completed a top-level frame. Otherwise,
cframe, cpc = ret
where `cframe` is the frame from which execution should continue and `cpc` is the state
of `cframe` (the program counter, a `BreakpointRef`, or `nothing`).
"""
function maybe_reset_frame!(@nospecialize(recurse), frame::Frame, @nospecialize(pc), rootistoplevel::Bool)
isa(pc, BreakpointRef) && return leaf(frame), pc
if pc === nothing
val = get_return(frame)
frame = return_from(frame)
frame === nothing && return nothing
ssavals = frame.framedata.ssavalues
is_wrapper = isassigned(ssavals, frame.pc) && ssavals[frame.pc] === Wrapper()
maybe_assign!(frame, val)
frame.pc >= nstatements(frame.framecode) && return maybe_reset_frame!(recurse, frame, nothing, rootistoplevel)
frame.pc += 1
if is_wrapper
return maybe_reset_frame!(recurse, frame, finish!(recurse, frame), rootistoplevel)
end
pc = maybe_next_call!(recurse, frame, rootistoplevel && frame.caller===nothing)
return maybe_reset_frame!(recurse, frame, pc, rootistoplevel)
end
return frame, pc
end
maybe_reset_frame!(frame::Frame, @nospecialize(pc), rootistoplevel::Bool) =
maybe_reset_frame!(finish_and_return!, frame, pc, rootistoplevel)
# Unwind the stack until an exc is eventually caught, thereby
# returning the frame that caught the exception at the pc of the catch
# or rethrow the error
function unwind_exception(frame::Frame, @nospecialize(exc))
while frame !== nothing
if !isempty(frame.framedata.exception_frames)
# Exception caught
frame.pc = frame.framedata.exception_frames[end]
frame.framedata.last_exception[] = exc
return frame
end
frame = return_from(frame)
end
rethrow(exc)
end
function maybe_step_through_nkw_meta!(frame)
stmt = pc_expr(frame)
if stmt === nothing || (isexpr(stmt, :meta) && (stmt::Expr).args[1] === :nkw)
@assert frame.pc == 1
frame.pc += 1
end
end
function more_calls_on_current_line(frame)
_, curr_line = whereis(frame)
curr_pc = frame.pc + 1
while curr_pc <= length(frame.framecode.src.code)
_, new_line = whereis(frame, curr_pc)
new_line == curr_line || return false
is_call(pc_expr(frame, curr_pc)) && return true
curr_pc += 1
end
return false
end
"""
ret = debug_command(recurse, frame, cmd, rootistoplevel=false; line=nothing)
ret = debug_command(frame, cmd, rootistoplevel=false; line=nothing)
Perform one "debugger" command. The keyword arguments are not used for all debug commands.
`cmd` should be one of:
- `:n`: advance to the next line
- `:s`: step into the next call
- `:sl` step into the last call on the current line (e.g. steps into `f` if the line is `f(g(h(x)))`).
- `:sr` step until the current function will return
- `:until`: advance the frame to line `line` if given, otherwise advance to the line after the current line
- `:c`: continue execution until termination or reaching a breakpoint
- `:finish`: finish the current frame and return to the parent
or one of the 'advanced' commands
- `:nc`: step forward to the next call
- `:se`: execute a single statement
- `:si`: execute a single statement, stepping in if it's a call
- `:sg`: step into the generator of a generated function
`rootistoplevel` and `ret` are as described for [`JuliaInterpreter.maybe_reset_frame!`](@ref).
"""
function debug_command(@nospecialize(recurse), frame::Frame, cmd::Symbol, rootistoplevel::Bool=false; line=nothing)
function nicereturn!(@nospecialize(recurse), frame::Frame, pc, rootistoplevel)
if pc === nothing || isa(pc, BreakpointRef)
return maybe_reset_frame!(recurse, frame, pc, rootistoplevel)
end
maybe_step_through_kwprep!(recurse, frame, rootistoplevel && frame.caller === nothing)
return frame, frame.pc
end
istoplevel = rootistoplevel && frame.caller === nothing
cmd0 = cmd
is_si = false
if cmd === :si
stmt = pc_expr(frame)
cmd = is_call(stmt) ? :s : :se
is_si = true
end
try
cmd === :nc && return nicereturn!(recurse, frame, next_call!(recurse, frame, istoplevel), rootistoplevel)
cmd === :n && return maybe_reset_frame!(recurse, frame, next_line!(recurse, frame, istoplevel), rootistoplevel)
cmd === :se && return maybe_reset_frame!(recurse, frame, step_expr!(recurse, frame, istoplevel), rootistoplevel)
cmd === :until && return maybe_reset_frame!(recurse, frame, until_line!(recurse, frame, line, istoplevel), rootistoplevel)
if cmd === :sl
while more_calls_on_current_line(frame)
next_call!(recurse, frame, istoplevel)
end
return debug_command(recurse, frame, :s, rootistoplevel; line)
end
if cmd === :sr
maybe_next_until!(frame -> is_return(pc_expr(frame)), recurse, frame, istoplevel)
return frame, frame.pc
end
enter_generated = false
if cmd === :sg
enter_generated = true
cmd = :s
end
if cmd === :s
pc = maybe_next_call!(recurse, frame, istoplevel)
(isa(pc, BreakpointRef) || pc === nothing) && return maybe_reset_frame!(recurse, frame, pc, rootistoplevel)
is_si || maybe_step_through_kwprep!(recurse, frame, istoplevel)
pc = frame.pc
stmt0 = stmt = pc_expr(frame, pc)
is_return(stmt0) && return maybe_reset_frame!(recurse, frame, nothing, rootistoplevel)
if isexpr(stmt, :(=))
stmt = stmt.args[2]
end
local ret
try
ret = evaluate_call!(dummy_breakpoint, frame, stmt; enter_generated=enter_generated)
catch err
ret = handle_err(recurse, frame, err)
return isa(ret, BreakpointRef) ? (leaf(frame), ret) : ret
end
if isa(ret, BreakpointRef)
newframe = leaf(frame)
cmd0 === :si && return newframe, ret
is_si || (newframe = maybe_step_through_wrapper!(recurse, newframe))
is_si || maybe_step_through_kwprep!(recurse, newframe, istoplevel)
return newframe, BreakpointRef(newframe.framecode, 0)
end
# if we got here, the call returned a value
maybe_assign!(frame, stmt0, ret)
frame.pc += 1
return frame, frame.pc
end
if cmd === :c
r = root(frame)
ret = finish_stack!(recurse, r, rootistoplevel)
return isa(ret, BreakpointRef) ? (leaf(r), ret) : nothing
end
cmd === :finish && return maybe_reset_frame!(recurse, frame, finish!(recurse, frame, istoplevel), rootistoplevel)
catch err
frame = unwind_exception(frame, err)
if cmd === :c
return debug_command(recurse, frame, :c, istoplevel)
else
return debug_command(recurse, frame, :nc, istoplevel)
end
end
throw(ArgumentError("command $cmd not recognized"))
end
debug_command(frame::Frame, cmd::Symbol, rootistoplevel::Bool=false; kwargs...) =
debug_command(finish_and_return!, frame, cmd, rootistoplevel; kwargs...)
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 27043 | """
`framedict[method]` returns the `FrameCode` for `method`. For `@generated` methods,
see [`genframedict`](@ref).
"""
const framedict = Dict{Method,FrameCode}() # essentially a method table for lowered code
"""
`genframedict[(method,argtypes)]` returns the `FrameCode` for a `@generated` method `method`,
for the particular argument types `argtypes`.
The framecodes stored in `genframedict` are for the code returned by the generator
(i.e, what will run when you call the method on particular argument types);
for the generator itself, its framecode would be stored in [`framedict`](@ref).
"""
const genframedict = Dict{Tuple{Method,Type},FrameCode}() # the same for @generated functions
"""
`meth ∈ compiled_methods` indicates that `meth` should be run using [`Compiled`](@ref)
rather than recursed into via the interpreter.
"""
const compiled_methods = Set{Method}()
"""
`meth ∈ interpreted_methods` indicates that `meth` should *not* be run using [`Compiled`](@ref)
and recursed into via the interpreter. This takes precedence over [`compiled_methods`](@ref) and
[`compiled_modules`](@ref).
"""
const interpreted_methods = Set{Method}()
"""
`mod ∈ compiled_modules` indicates that any method in `mod` should be run using [`Compiled`](@ref)
rather than recursed into via the interpreter.
"""
const compiled_modules = Set{Module}()
const junk_framedata = FrameData[] # to allow re-use of allocated memory (this is otherwise a bottleneck)
const junk_frames = Frame[]
debug_mode() = false
@noinline function _check_frame_not_in_junk(frame)
@assert frame.framedata ∉ junk_framedata
@assert frame ∉ junk_frames
end
@inline function recycle(frame)
debug_mode() && _check_frame_not_in_junk(frame)
push!(junk_framedata, frame.framedata)
push!(junk_frames, frame)
end
function return_from(frame::Frame)
recycle(frame)
frame = caller(frame)
frame === nothing || (frame.callee = nothing)
return frame
end
function clear_caches()
empty!(junk_framedata)
empty!(framedict)
empty!(genframedict)
empty!(junk_frames)
for bp in breakpoints()
empty!(bp.instances)
end
end
const empty_svec = Core.svec()
function namedtuple(kwargs)
names, types, vals = Symbol[], [], []
for pr in kwargs
if isa(pr, Expr)
push!(names, pr.args[1])
val = pr.args[2]
push!(types, typeof(val))
push!(vals, val)
elseif isa(pr, Pair)
push!(names, pr.first)
val = pr.second
push!(types, typeof(val))
push!(vals, val)
else
error("unhandled entry type ", typeof(pr))
end
end
return NamedTuple{(names...,), Tuple{types...}}(vals)
end
get_source(meth::Method) = Base.uncompressed_ast(meth)
@static if VERSION < v"1.10.0-DEV.873" # julia#48766
function get_source(g::GeneratedFunctionStub, env, file, line)
b = g(env..., g.argnames...)
b isa CodeInfo && return b
return eval(b)
end
else
function get_source(g::GeneratedFunctionStub, env, file, line::Int)
b = g(Base.get_world_counter(), LineNumberNode(line, file), env..., g.argnames...)
b isa CodeInfo && return b
return eval(b)
end
end
"""
frun, allargs = prepare_args(fcall, fargs, kwargs)
Prepare the complete argument sequence for a call to `fcall`. `fargs = [fcall, args...]` is a list
containing both `fcall` (the `#self#` slot in lowered code) and the positional
arguments supplied to `fcall`. `kwargs` is a list of keyword arguments, supplied either as
list of expressions `:(kwname=kwval)` or pairs `:kwname=>kwval`.
For non-keyword methods, `frun === fcall`, but for methods with keywords `frun` will be the
keyword-sorter function for `fcall`.
# Example
```jldoctest
julia> mymethod(x) = 1;
julia> mymethod(x, y; verbose=false) = nothing;
julia> JuliaInterpreter.prepare_args(mymethod, [mymethod, 15], ())
(mymethod, Any[mymethod, 15])
julia> JuliaInterpreter.prepare_args(mymethod, [mymethod, 1, 2], [:verbose=>true])
(Core.kwcall, Any[Core.kwcall, (verbose = true,), mymethod, 1, 2])
```
"""
function prepare_args(@nospecialize(f), allargs, kwargs)
if !isempty(kwargs)
f = Core.kwfunc(f)
allargs = Any[f, namedtuple(kwargs), allargs...]
end
return f, allargs
end
function prepare_framecode(method::Method, @nospecialize(argtypes); enter_generated=false)
sig = method.sig
if (method.module ∈ compiled_modules || method ∈ compiled_methods) && !(method ∈ interpreted_methods)
return Compiled()
end
# Get static parameters
(ti, lenv::SimpleVector) = ccall(:jl_type_intersection_with_env, Any, (Any, Any),
argtypes, sig)::SimpleVector
enter_generated &= is_generated(method)
if is_generated(method) && !enter_generated
framecode = get(genframedict, (method, argtypes::Type), nothing)
else
framecode = get(framedict, method, nothing)
end
if framecode === nothing
if is_generated(method) && !enter_generated
# If we're stepping into a staged function, we need to use
# the specialization, rather than stepping through the
# unspecialized method.
code = get_staged(Core.Compiler.specialize_method(method, argtypes, lenv))
code === nothing && return nothing
generator = false
else
if is_generated(method)
code = get_source(method.generator, lenv, method.file, Int(method.line))
generator = true
else
code = get_source(method)
generator = false
end
end
code = code::CodeInfo
# Currenly, our strategy to deal with llvmcall can't handle parametric functions
# (the "mini interpreter" runs in module scope, not method scope)
if (!isempty(lenv) && (hasarg(isidentical(:llvmcall), code.code) ||
hasarg(isidentical(Base.llvmcall), code.code) ||
hasarg(a->is_global_ref(a, Base, :llvmcall), code.code))) ||
hasarg(isidentical(:iolock_begin), code.code)
return Compiled()
end
framecode = FrameCode(method, code; generator=generator)
if is_generated(method) && !enter_generated
genframedict[(method, argtypes)] = framecode
else
framedict[method] = framecode
end
end
return framecode, lenv
end
function get_framecode(method)
framecode = get(framedict, method, nothing)
if framecode === nothing
@assert !is_generated(method)
code = get_source(method)
framecode = FrameCode(method, code; generator=false)
framedict[method] = framecode
end
return framecode
end
"""
framecode, frameargs, lenv, argtypes = prepare_call(f, allargs; enter_generated=false)
Prepare all the information needed to execute lowered code for `f` given arguments `allargs`.
`f` and `allargs` are the outputs of [`prepare_args`](@ref).
For `@generated` methods, set `enter_generated=true` if you want to extract the lowered code
of the generator itself.
On return `framecode` is the [`FrameCode`](@ref) of the method.
`frameargs` contains the actual arguments needed for executing this frame (for generators,
this will be the types of `allargs`);
`lenv` is the "environment", i.e., the static parameters for `f` given `allargs`.
`argtypes` is the `Tuple`-type for this specific call (equivalent to the signature of the `MethodInstance`).
# Example
```jldoctest
julia> mymethod(x::Vector{T}) where T = 1;
julia> framecode, frameargs, lenv, argtypes = JuliaInterpreter.prepare_call(mymethod, [mymethod, [1.0,2.0]]);
julia> framecode
1 1 1 ─ return 1
julia> frameargs
2-element Vector{Any}:
mymethod (generic function with 1 method)
[1.0, 2.0]
julia> lenv
svec(Float64)
julia> argtypes
Tuple{typeof(mymethod), Vector{Float64}}
```
"""
function prepare_call(@nospecialize(f), allargs; enter_generated = false)
# Can happen for thunks created by generated functions
if isa(f, Core.Builtin) || isa(f, Core.IntrinsicFunction)
return nothing
elseif any(is_vararg_type, allargs)
return nothing # https://github.com/JuliaLang/julia/issues/30995
end
argtypesv = Any[_Typeof(a) for a in allargs]
argtypes = Tuple{argtypesv...}
if @static isdefined(Core, :OpaqueClosure) && f isa Core.OpaqueClosure
method = f.source
# don't try to interpret optimized ir
if Core.Compiler.uncompressed_ir(method).inferred
@debug "not interpreting opaque closure $f since it contains inferred code"
return nothing
end
else
method = whichtt(argtypes)
end
if method === nothing
# Call it to generate the exact error
return f(allargs[2:end]...)
end
ret = prepare_framecode(method, argtypes; enter_generated=enter_generated)
# Exceptional returns
if ret === nothing
# The generator threw an error. Let's generate the same error by calling it.
return f(allargs[2:end]...)
end
isa(ret, Compiled) && return ret, argtypes
# Typical return
framecode, lenv = ret
if is_generated(method) && enter_generated
allargs = Any[_Typeof(a) for a in allargs]
end
return framecode, allargs, lenv, argtypes
end
function prepare_framedata(framecode, argvals::Vector{Any}, lenv::SimpleVector=empty_svec, caller_will_catch_err::Bool=false)
src = framecode.src
slotnames = src.slotnames
ssavt = src.ssavaluetypes
ng, ns = isa(ssavt, Int) ? ssavt : length(ssavt::Vector{Any}), length(src.slotflags)
if length(junk_framedata) > 0
olddata = pop!(junk_framedata)
locals, ssavalues, sparams = olddata.locals, olddata.ssavalues, olddata.sparams
exception_frames, current_scopes, last_reference = olddata.exception_frames, olddata.current_scopes, olddata.last_reference
last_exception = olddata.last_exception
callargs = olddata.callargs
resize!(locals, ns)
fill!(locals, nothing)
resize!(ssavalues, 0)
resize!(ssavalues, ng)
# for check_isdefined to work properly, we need sparams to start out unassigned
resize!(sparams, 0)
empty!(exception_frames)
empty!(current_scopes)
resize!(last_reference, ns)
last_exception[] = _INACTIVE_EXCEPTION.instance
else
locals = Vector{Union{Nothing,Some{Any}}}(nothing, ns)
ssavalues = Vector{Any}(undef, ng)
sparams = Vector{Any}(undef, 0)
exception_frames = Int[]
current_scopes = Scope[]
last_reference = Vector{Int}(undef, ns)
callargs = Any[]
last_exception = Ref{Any}(_INACTIVE_EXCEPTION.instance)
end
fill!(last_reference, 0)
if isa(framecode.scope, Method)
meth = framecode.scope::Method
nargs, meth_nargs = length(argvals), Int(meth.nargs)
islastva = meth.isva && nargs >= meth_nargs
for i = 1:meth_nargs-islastva
# for OCs #self# actually refers to the captures instead
if @static isdefined(Core, :OpaqueClosure) && i == 1 && (oc = argvals[1]) isa Core.OpaqueClosure
locals[i], last_reference[i] = Some{Any}(oc.captures), 1
elseif i <= nargs
locals[i], last_reference[i] = Some{Any}(argvals[i]), 1
else
locals[i] = Some{Any}(())
end
end
if islastva
locals[meth_nargs] = (let i=meth_nargs; Some{Any}(ntupleany(k->argvals[i+k-1], nargs-i+1)); end)
last_reference[meth_nargs] = 1
end
end
resize!(sparams, length(lenv))
# Add static parameters to environment
for i = 1:length(lenv)
T = lenv[i]
isa(T, TypeVar) && continue # only fill concrete types
sparams[i] = T
end
return FrameData(locals, ssavalues, sparams, exception_frames, current_scopes,
last_exception, caller_will_catch_err, last_reference, callargs)
end
"""
frame = prepare_frame(framecode::FrameCode, frameargs, lenv)
Construct a new `Frame` for `framecode`, given lowered-code arguments `frameargs` and
static parameters `lenv`. See [`JuliaInterpreter.prepare_call`](@ref) for information about how to prepare the inputs.
"""
function prepare_frame(framecode::FrameCode, args::Vector{Any}, lenv::SimpleVector, caller_will_catch_err::Bool=false)
framedata = prepare_framedata(framecode, args, lenv, caller_will_catch_err)
return Frame(framecode, framedata)
end
function prepare_frame_caller(caller::Frame, framecode::FrameCode, args::Vector{Any}, lenv::SimpleVector)
caller_will_catch_err = !isempty(caller.framedata.exception_frames) || caller.framedata.caller_will_catch_err
caller.callee = frame = prepare_frame(framecode, args, lenv, caller_will_catch_err)
copy!(frame.framedata.current_scopes, caller.framedata.current_scopes)
frame.caller = caller
return frame
end
"""
ExprSplitter(mod::Module, ex::Expr; lnn=nothing)
Given a module `mod` and a top-level expression `ex` in `mod`, create an iterable that returns
individual expressions together with their module of evaluation.
Optionally supply an initial `LineNumberNode` `lnn`.
# Example
In a fresh session,
```
julia> expr = quote
public_fn(x::Integer) = true
module Private
private(y::String) = false
end
const threshold = 0.1
end;
julia> for (mod, ex) in ExprSplitter(Main, expr)
@show mod ex
end
mod = Main
ex = quote
#= REPL[7]:2 =#
public_fn(x::Integer) = begin
#= REPL[7]:2 =#
true
end
end
mod = Main.Private
ex = quote
#= REPL[7]:4 =#
private(y::String) = begin
#= REPL[7]:4 =#
false
end
end
mod = Main
ex = :($(Expr(:toplevel, :(#= REPL[7]:6 =#), :(const threshold = 0.1))))
```
`ExprSplitter` created `Main.Private` was created for you so that its internal expressions could be evaluated.
`ExprSplitter` will check to see whether the module already exists and if so return it rather than
try to create a new module with the same name.
In general each returned expression is a block with two parts: a `LineNumberNode` followed by a single expression.
In some cases the returned expression may be `:toplevel`, as shown in the `const` declaration,
but otherwise it will preserve its parent's `head` (e.g., `expr.head`).
# World age, frame creation, and evaluation
The primary purpose of `ExprSplitter` is to allow sequential return to top-level (e.g., the REPL)
after evaluation of each expression. Returning to top-level allows the world age to update, and hence allows one to call
methods and use types defined in earlier expressions in a block.
For evaluation by JuliaInterpreter, the returned module/expression pairs can be passed directly to
the `Frame` constructor. However, some expressions cannot be converted into `Frame`s and may need
special handling:
```julia
julia> for (mod, ex) in ExprSplitter(Main, expr)
if ex.head === :global
# global declarations can't be lowered to a CodeInfo.
# In this demo we choose to evaluate them, but you can do something else.
Core.eval(mod, ex)
continue
end
frame = Frame(mod, ex)
debug_command(frame, :c, true)
end
julia> threshold
0.1
julia> public_fn(3)
true
```
If you're parsing package code, `ex` might be a docstring-expression; you may wish
to check for such expressions and take distinct actions.
See [`Frame(mod::Module, ex::Expr)`](@ref) for more information about frame creation.
"""
mutable struct ExprSplitter
# Non-mutating fields
stack::Vector{Tuple{Module,Expr}} # mod[i] is module of evaluation for
index::Vector{Int} # next-to-handle argument index for :block or :toplevel exprs
# Mutating fields
lnn::Union{LineNumberNode,Nothing}
end
function ExprSplitter(mod::Module, ex::Expr; lnn=nothing)
iter = ExprSplitter(Tuple{Module,Expr}[], Int[], lnn)
push_modex!(iter, mod, ex)
queuenext!(iter)
return iter
end
Base.IteratorSize(::Type{ExprSplitter}) = Base.SizeUnknown()
Base.eltype(::Type{ExprSplitter}) = Tuple{Module,Expr}
function push_modex!(iter::ExprSplitter, mod::Module, ex::Expr)
push!(iter.stack, (mod, ex))
if ex.head === :toplevel || ex.head === :block
# Issue #427
modifies_scope = false
if ex.head === :block
for a in ex.args
if isa(a, Expr) && a.head === :local
modifies_scope = true
break
end
end
end
push!(iter.index, modifies_scope ? 0 : 1)
end
return iter
end
function pop_modex!(iter)
mod, ex = pop!(iter.stack)
if ex.head === :toplevel || ex.head === :block
pop!(iter.index)
end
return mod, ex
end
# Load the next-to-evaluate expression into `iter.stack[end]`.
function queuenext!(iter::ExprSplitter)
isempty(iter.stack) && return nothing
mod, ex = iter.stack[end]
head = ex.head
if head === :module
# Find or create the module
newname = ex.args[2]::Symbol
if isdefined(mod, newname)
newmod = getfield(mod, newname)
newmod isa Module || throw(ErrorException("invalid redefinition of constant $(newname)"))
mod = newmod
else
newnamestr = String(newname)
id = Base.identify_package(mod, newnamestr)
# If we're in a test environment and Julia's internal stdlibs are not a declared dependency of the package,
# we might fail to find it. Try really hard to find it.
if id === nothing && mod === Base.__toplevel__
for loaded_id in keys(Base.loaded_modules)
if loaded_id.name == newnamestr
id = loaded_id
break
end
end
end
if id !== nothing && haskey(Base.loaded_modules, id)
mod = Base.root_module(id)::Module
else
loc = firstline(ex)
mod = Core.eval(mod, Expr(:module, ex.args[1], ex.args[2], Expr(:block, loc, loc)))::Module
end
end
# We've handled the module declaration, remove it and queue the body
pop!(iter.stack)
ex = ex.args[3]::Expr
push_modex!(iter, mod, ex)
return queuenext!(iter)
elseif head === :macrocall
iter.lnn = ex.args[2]::LineNumberNode
elseif head === :block || head === :toplevel
# Container expression
idx = iter.index[end]
if idx == 0
# return the whole block (issue #427)
return nothing
end
while idx <= length(ex.args)
a = ex.args[idx]
if isa(a, LineNumberNode)
iter.lnn = a
elseif isa(a, Expr)
iter.index[end] = idx + 1
push_modex!(iter, mod, a)
return queuenext!(iter)
end
idx += 1
end
# We exhausted the expression without returning anything to evaluate
pop!(iter.stack)
pop!(iter.index)
return queuenext!(iter)
end
return nothing # mod, ex will be returned by iterate
end
function Base.iterate(iter::ExprSplitter, state=nothing)
isempty(iter.stack) && return nothing
mod, ex = pop_modex!(iter)
lnn = iter.lnn
if is_doc_expr(ex)
body = ex.args[4]
if isa(body, Expr) && body.head === :module
# Just document the module itself and push the module def onto the stack
excopy = Expr(ex.head, ex.args[1], ex.args[2], ex.args[3])
push!(excopy.args, body.args[2])
append!(excopy.args, ex.args[5:end]) # there should only be at most a 5th, but just for robustness
ex = excopy
push_modex!(iter, mod, body)
end
end
if ex.head === :block || ex.head === :toplevel
# This was a block that we couldn't safely descend into (issue #427)
if !isempty(iter.index) && iter.index[end] > length(iter.stack[end][2].args)
pop!(iter.stack)
pop!(iter.index)
queuenext!(iter)
end
return (mod, ex), nothing
end
queuenext!(iter)
# :global expressions can't be lowered. For debugging it might be nice
# to still return the lnn, but then we have to work harder on detecting them.
ex.head === :global && return (mod, ex), nothing
return (mod, Expr(:block, lnn, ex)), nothing
end
"""
framecode, frameargs, lenv, argtypes = determine_method_for_expr(expr; enter_generated = false)
Prepare all the information needed to execute a particular `:call` expression `expr`.
For example, try `JuliaInterpreter.determine_method_for_expr(:(\$sum([1,2])))`.
See [`JuliaInterpreter.prepare_call`](@ref) for information about the outputs.
"""
function determine_method_for_expr(expr; enter_generated = false)
f = to_function(expr.args[1])
allargs = expr.args
# Extract keyword args
kwargs = Expr(:parameters)
if length(allargs) > 1 && isexpr(allargs[2], :parameters)
kwargs = splice!(allargs, 2)::Expr
end
f, allargs = prepare_args(f, allargs, kwargs.args)
return prepare_call(f, allargs; enter_generated=enter_generated)
end
"""
frame = enter_call_expr(expr; enter_generated=false)
Build a `Frame` ready to execute the expression `expr`. Set `enter_generated=true`
if you want to execute the generator of a `@generated` function, rather than the code that
would be created by the generator.
# Example
```jldoctest
julia> mymethod(x) = x+1;
julia> JuliaInterpreter.enter_call_expr(:(\$mymethod(1)))
Frame for mymethod(x) @ Main none:1
1* 1 1 ─ %1 = x + 1
2 1 └── return %1
x = 1
julia> mymethod(x::Vector{T}) where T = 1;
julia> a = [1.0, 2.0]
2-element Vector{Float64}:
1.0
2.0
julia> JuliaInterpreter.enter_call_expr(:(\$mymethod(\$a)))
Frame for mymethod(x::Vector{T}) where T @ Main none:1
1* 1 1 ─ return 1
x = [1.0, 2.0]
T = Float64
```
See [`enter_call`](@ref) for a similar approach not based on expressions.
"""
function enter_call_expr(expr; enter_generated = false)
clear_caches()
r = determine_method_for_expr(expr; enter_generated = enter_generated)
if r !== nothing && !isa(r[1], Compiled)
return prepare_frame(Base.front(r)...)
end
nothing
end
"""
frame = enter_call(f, args...; kwargs...)
Build a `Frame` ready to execute `f` with the specified positional and keyword arguments.
# Example
```jldoctest
julia> mymethod(x) = x+1;
julia> JuliaInterpreter.enter_call(mymethod, 1)
Frame for mymethod(x) @ Main none:1
1* 1 1 ─ %1 = x + 1
2 1 └── return %1
x = 1
julia> mymethod(x::Vector{T}) where T = 1;
julia> JuliaInterpreter.enter_call(mymethod, [1.0, 2.0])
Frame for mymethod(x::Vector{T}) where T @ Main none:1
1* 1 1 ─ return 1
x = [1.0, 2.0]
T = Float64
```
For a `@generated` function you can use `enter_call((f, true), args...; kwargs...)`
to execute the generator of a `@generated` function, rather than the code that
would be created by the generator.
See [`enter_call_expr`](@ref) for a similar approach based on expressions.
"""
function enter_call(@nospecialize(finfo), @nospecialize(args...); kwargs...)
clear_caches()
if isa(finfo, Tuple)
f = finfo[1]
enter_generated = finfo[2]::Bool
else
f = finfo
enter_generated = false
end
f, allargs = prepare_args(f, Any[f, args...], kwargs)
# Can happen for thunks created by generated functions
if isa(f, Core.Builtin) || isa(f, Core.IntrinsicFunction)
error(f, " is a builtin or intrinsic")
end
r = prepare_call(f, allargs; enter_generated=enter_generated)
if r !== nothing && !isa(r[1], Compiled)
return prepare_frame(Base.front(r)...)
end
return nothing
end
# This is a version of InteractiveUtils.gen_call_with_extracted_types, except that is passes back the
# call expression for further processing.
function extract_args(__module__, ex0)
if isa(ex0, Expr)
if any(a->(isexpr(a, :kw) || isexpr(a, :parameters)), ex0.args)
arg1, args, kwargs = gensym("arg1"), gensym("args"), gensym("kwargs")
return quote
$arg1 = $(ex0.args[1])
$args, $kwargs = $separate_kwargs($(ex0.args[2:end]...))
tuple(Core.kwfunc($arg1), $kwargs, $arg1, $args...)
end
elseif ex0.head === :.
return Expr(:tuple, :getproperty, ex0.args...)
elseif ex0.head === :(<:)
return Expr(:tuple, :(<:), ex0.args...)
else
return Expr(:tuple,
mapany(x->isexpr(x,:parameters) ? QuoteNode(x) : x, ex0.args)...)
end
end
if isexpr(ex0, :macrocall) # Make @edit @time 1+2 edit the macro by using the types of the *expressions*
return error("Macros are not supported in @enter")
end
ex = Meta.lower(__module__, ex0)
if !isa(ex, Expr)
return error("expression is not a function call or symbol")
elseif ex.head === :call
return Expr(:tuple,
mapany(x->isexpr(x, :parameters) ? QuoteNode(x) : x, ex.args)...)
elseif ex.head === :body
a1 = ex.args[1]
if isexpr(a1, :call)
a11 = a1.args[1]
if a11 === :setindex!
return Expr(:tuple,
mapany(x->isexpr(x, :parameters) ? QuoteNode(x) : x, arg.args)...)
end
end
end
return error("expression is not a function call, "
* "or is too complex for @enter to analyze; "
* "break it down to simpler parts if possible")
end
"""
@interpret f(args; kwargs...)
Evaluate `f` on the specified arguments using the interpreter.
# Example
```jldoctest
julia> a = [1, 7];
julia> sum(a)
8
julia> @interpret sum(a)
8
```
"""
macro interpret(arg)
args = try
extract_args(__module__, arg)
catch e
return :(throw($e))
end
quote
local theargs = $(esc(args))
local frame = JuliaInterpreter.enter_call_expr(Expr(:call, theargs...))
if frame === nothing
eval(Expr(:call, map(QuoteNode, theargs)...))
elseif shouldbreak(frame, 1)
frame, BreakpointRef(frame.framecode, 1)
else
local ret = finish_and_return!(frame)
# We deliberately return the top frame here; future debugging commands
# via debug_command may alter the leaves, we want the top frame so we can
# ultimately do `get_return`.
isa(ret, BreakpointRef) ? (frame, ret) : ret
end
end
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 27885 | isassign(frame::Frame) = isassign(frame, frame.pc)
isassign(frame::Frame, pc::Int) = (pc in frame.framecode.used)
lookup_var(frame::Frame, val::SSAValue) = frame.framedata.ssavalues[val.id]
lookup_var(frame::Frame, ref::GlobalRef) = getfield(ref.mod, ref.name)
function lookup_var(frame::Frame, slot::SlotNumber)
val = frame.framedata.locals[slot.id]
val !== nothing && return val.value
throw(UndefVarError(frame.framecode.src.slotnames[slot.id]))
end
"""
rhs = @lookup(frame, node)
rhs = @lookup(mod, frame, node)
This macro looks up previously-computed values referenced as SSAValues, SlotNumbers,
GlobalRefs, QuoteNode, sparam or exception reference expression.
It will also lookup symbols in `moduleof(frame)`; this can be supplied ahead-of-time via
the 3-argument version.
If none of the above apply, the value of `node` will be returned.
"""
macro lookup(args...)
length(args) == 2 || length(args) == 3 || error("invalid number of arguments ", length(args))
havemod = length(args) == 3
local mod
if havemod
mod, frame, node = args
else
frame, node = args
end
nodetmp = gensym(:node) # used to hoist, e.g., args[4]
if havemod
fallback = quote
isa($nodetmp, Symbol) ? getfield($(esc(mod)), $nodetmp) :
$nodetmp
end
else
fallback = quote
$nodetmp
end
end
quote
$nodetmp = $(esc(node))
isa($nodetmp, SSAValue) ? lookup_var($(esc(frame)), $nodetmp) :
isa($nodetmp, GlobalRef) ? lookup_var($(esc(frame)), $nodetmp) :
isa($nodetmp, SlotNumber) ? lookup_var($(esc(frame)), $nodetmp) :
isa($nodetmp, QuoteNode) ? $nodetmp.value :
isa($nodetmp, Symbol) ? getfield(moduleof($(esc(frame))), $nodetmp) :
isa($nodetmp, Expr) ? lookup_expr($(esc(frame)), $nodetmp) :
$fallback
end
end
function lookup_expr(frame::Frame, e::Expr)
head = e.head
head === :the_exception && return frame.framedata.last_exception[]
if head === :static_parameter
arg = e.args[1]::Int
if isassigned(frame.framedata.sparams, arg)
return frame.framedata.sparams[arg]
else
syms = sparam_syms(frame.framecode.scope::Method)
throw(UndefVarError(syms[arg]))
end
end
head === :boundscheck && length(e.args) == 0 && return true
if head === :call
f = @lookup frame e.args[1]
if (@static VERSION < v"1.11.0-DEV.1180" && true) && f === Core.svec
# work around for a linearization bug in Julia (https://github.com/JuliaLang/julia/pull/52497)
return f(Any[@lookup(frame, e.args[i]) for i in 2:length(e.args)]...)
elseif f === Core.tuple
# handling for ccall literal syntax
return f(Any[@lookup(frame, e.args[i]) for i in 2:length(e.args)]...)
end
end
error("invalid lookup expr ", e)
end
# This is used only for new struct/abstract/primitive nodes.
# The most important issue is that in these expressions, :call Exprs can be nested,
# and hence our re-use of the `callargs` field of Frame would introduce
# bugs. Since these nodes use a very limited repertoire of calls, we can special-case
# this quite easily.
function lookup_or_eval(@nospecialize(recurse), frame::Frame, @nospecialize(node))
if isa(node, SSAValue)
return lookup_var(frame, node)
elseif isa(node, SlotNumber)
return lookup_var(frame, node)
elseif isa(node, GlobalRef)
return lookup_var(frame, node)
elseif isa(node, Symbol)
return getfield(moduleof(frame), node)
elseif isa(node, QuoteNode)
return node.value
elseif isa(node, Expr)
ex = Expr(node.head)
for arg in node.args
push!(ex.args, lookup_or_eval(recurse, frame, arg))
end
if ex.head === :call
f = ex.args[1]
if f === Core.svec
popfirst!(ex.args)
return Core.svec(ex.args...)
elseif f === Core.apply_type
popfirst!(ex.args)
return Core.apply_type(ex.args...)
elseif f === typeof && length(ex.args) == 2
return typeof(ex.args[2])
elseif f === typeassert && length(ex.args) == 3
return typeassert(ex.args[2], ex.args[3])
elseif f === Base.getproperty && length(ex.args) == 3
return Base.getproperty(ex.args[2], ex.args[3])
elseif f === Core.Compiler.Val && length(ex.args) == 2
return Core.Compiler.Val(ex.args[2])
elseif f === Val && length(ex.args) == 2
return Val(ex.args[2])
else
Base.invokelatest(error, "unknown call f introduced by ccall lowering ", f)
end
else
return lookup_expr(frame, ex)
end
elseif isa(node, Int) || isa(node, Number) # Number is slow, requires subtyping
return node
elseif isa(node, Type)
return node
end
return eval_rhs(recurse, frame, node)
end
function resolvefc(frame::Frame, @nospecialize(expr))
if isa(expr, SlotNumber)
expr = lookup_var(frame, expr)
elseif isa(expr, SSAValue)
expr = lookup_var(frame, expr)
isa(expr, Symbol) && return QuoteNode(expr)
end
(isa(expr, Symbol) || isa(expr, String) || isa(expr, Ptr) || isa(expr, QuoteNode)) && return expr
isa(expr, Tuple{Symbol,Symbol}) && return expr
isa(expr, Tuple{String,String}) && return expr
isa(expr, Tuple{Symbol,String}) && return expr
isa(expr, Tuple{String,Symbol}) && return expr
if isexpr(expr, :call)
a = (expr::Expr).args[1]
(isa(a, QuoteNode) && a.value === Core.tuple) || error("unexpected ccall to ", expr)
return Expr(:call, GlobalRef(Core, :tuple), (expr::Expr).args[2:end]...)
end
Base.invokelatest(error, "unexpected ccall to ", expr)
end
function collect_args(@nospecialize(recurse), frame::Frame, call_expr::Expr; isfc::Bool=false)
args = frame.framedata.callargs
resize!(args, length(call_expr.args))
mod = moduleof(frame)
args[1] = isfc ? resolvefc(frame, call_expr.args[1]) : @lookup(mod, frame, call_expr.args[1])
for i = 2:length(args)
if isexpr(call_expr.args[i], :call)
args[i] = lookup_or_eval(recurse, frame, call_expr.args[i])
else
args[i] = @lookup(mod, frame, call_expr.args[i])
end
end
return args
end
"""
ret = evaluate_foreigncall(recurse, frame::Frame, call_expr)
Evaluate a `:foreigncall` (from a `ccall`) statement `callexpr` in the context of `frame`.
"""
function evaluate_foreigncall(@nospecialize(recurse), frame::Frame, call_expr::Expr)
head = call_expr.head
args = collect_args(recurse, frame, call_expr; isfc = head === :foreigncall)
for i = 2:length(args)
arg = args[i]
args[i] = isa(arg, Symbol) ? QuoteNode(arg) : arg
end
head === :cfunction && (args[2] = QuoteNode(args[2]))
scope = frame.framecode.scope
data = frame.framedata
if !isempty(data.sparams) && scope isa Method
sig = scope.sig
args[2] = instantiate_type_in_env(args[2], sig, data.sparams)
arg3 = args[3]
if (@static VERSION < v"1.7.0" && arg3 isa Core.SimpleVector) ||
head === :foreigncall
args[3] = Core.svec(map(arg3) do arg
instantiate_type_in_env(arg, sig, data.sparams)
end...)
else
args[3] = instantiate_type_in_env(arg3, sig, data.sparams)
args[4] = Core.svec(map(args[4]::Core.SimpleVector) do arg
instantiate_type_in_env(arg, sig, data.sparams)
end...)
end
end
return Core.eval(moduleof(frame), Expr(head, args...))
end
# We have to intercept ccalls / llvmcalls before we try it as a builtin
function bypass_builtins(@nospecialize(recurse), frame::Frame, call_expr::Expr, pc::Int)
if isassigned(frame.framecode.methodtables, pc)
tme = frame.framecode.methodtables[pc]
if isa(tme, Compiled)
fargs = collect_args(recurse, frame, call_expr)
f = to_function(fargs[1])
fmod = parentmodule(f)::Module
if fmod === JuliaInterpreter.CompiledCalls || fmod === Core.Compiler
# Fixing https://github.com/JuliaDebug/JuliaInterpreter.jl/issues/432.
@static if VERSION >= v"1.7.0"
return Some{Any}(Base.invoke_in_world(get_world_counter(), f, fargs[2:end]...))
else
return Some{Any}(Base.invokelatest(f, fargs[2:end]...))
end
else
return Some{Any}(f(fargs[2:end]...))
end
end
end
return nothing
end
function native_call(fargs::Vector{Any}, frame::Frame)
f = popfirst!(fargs) # now it's really just `args`
if (@static isdefined(Core.IR, :EnterNode) && true)
newscope = Core.current_scope()
if newscope !== nothing || !isempty(frame.framedata.current_scopes)
for scope in frame.framedata.current_scopes
newscope = Scope(newscope, scope.values...)
end
ex = Expr(:tryfinally, :($f($fargs...)), nothing, newscope)
return Core.eval(moduleof(frame), ex)
end
end
return Base.invokelatest(f, fargs...)
end
function evaluate_call_compiled!(::Compiled, frame::Frame, call_expr::Expr; enter_generated::Bool=false)
# @assert !enter_generated
pc = frame.pc
ret = bypass_builtins(Compiled(), frame, call_expr, pc)
isa(ret, Some{Any}) && return ret.value
ret = maybe_evaluate_builtin(frame, call_expr, false)
isa(ret, Some{Any}) && return ret.value
fargs = collect_args(Compiled(), frame, call_expr)
return native_call(fargs, frame)
end
function evaluate_call_recurse!(@nospecialize(recurse), frame::Frame, call_expr::Expr; enter_generated::Bool=false)
pc = frame.pc
ret = bypass_builtins(recurse, frame, call_expr, pc)
isa(ret, Some{Any}) && return ret.value
ret = maybe_evaluate_builtin(frame, call_expr, true)
isa(ret, Some{Any}) && return ret.value
call_expr = ret
fargs = collect_args(recurse, frame, call_expr)
if fargs[1] === Core.eval
return Core.eval(fargs[2], fargs[3]) # not a builtin, but worth treating specially
elseif fargs[1] === Base.rethrow
err = length(fargs) > 1 ? fargs[2] : frame.framedata.last_exception[]
throw(err)
end
if fargs[1] === Core.invoke # invoke needs special handling
f_invoked = which(fargs[2], fargs[3])::Method
fargs_pruned = [fargs[2]; fargs[4:end]]
sig = Tuple{mapany(_Typeof, fargs_pruned)...}
ret = prepare_framecode(f_invoked, sig; enter_generated=enter_generated)
isa(ret, Compiled) && return invoke(fargs[2:end]...)
@assert ret !== nothing
framecode, lenv = ret
lenv === nothing && return framecode # this was a Builtin
fargs = fargs_pruned
else
framecode, lenv = get_call_framecode(fargs, frame.framecode, frame.pc; enter_generated=enter_generated)
if lenv === nothing
if isa(framecode, Compiled)
return native_call(fargs, frame)
end
return framecode # this was a Builtin
end
end
newframe = prepare_frame_caller(frame, framecode, fargs, lenv)
npc = newframe.pc
shouldbreak(newframe, npc) && return BreakpointRef(newframe.framecode, npc)
# if the following errors, handle_err will pop the stack and recycle newframe
if recurse === finish_and_return!
# Optimize this case to avoid dynamic dispatch
ret = finish_and_return!(finish_and_return!, newframe, false)
else
ret = recurse(recurse, newframe, false)
end
isa(ret, BreakpointRef) && return ret
frame.callee = nothing
return_from(newframe)
return ret
end
"""
ret = evaluate_call!(Compiled(), frame::Frame, call_expr)
ret = evaluate_call!(recurse, frame::Frame, call_expr)
Evaluate a `:call` expression `call_expr` in the context of `frame`.
The first causes it to be executed using Julia's normal dispatch (compiled code),
whereas the second recurses in via the interpreter.
`recurse` has a default value of [`JuliaInterpreter.finish_and_return!`](@ref).
"""
evaluate_call!(::Compiled, frame::Frame, call_expr::Expr; kwargs...) = evaluate_call_compiled!(Compiled(), frame, call_expr; kwargs...)
evaluate_call!(@nospecialize(recurse), frame::Frame, call_expr::Expr; kwargs...) = evaluate_call_recurse!(recurse, frame, call_expr; kwargs...)
evaluate_call!(frame::Frame, call_expr::Expr; kwargs...) = evaluate_call!(finish_and_return!, frame, call_expr; kwargs...)
# The following come up only when evaluating toplevel code
function evaluate_methoddef(frame::Frame, node::Expr)
f = node.args[1]
if f isa Symbol || f isa GlobalRef
mod = f isa Symbol ? moduleof(frame) : f.mod
name = f isa Symbol ? f : f.name
if Base.isbindingresolved(mod, name) && isdefined(mod, name) # `isdefined` accesses the binding, making it impossible to create a new one
f = getfield(mod, name)
else
f = Core.eval(mod, Expr(:function, name)) # create a new function
end
end
length(node.args) == 1 && return f
sig = @lookup(frame, node.args[2])::SimpleVector
body = @lookup(frame, node.args[3])::Union{CodeInfo, Expr}
# branching on https://github.com/JuliaLang/julia/pull/41137
@static if isdefined(Core.Compiler, :OverlayMethodTable)
ccall(:jl_method_def, Cvoid, (Any, Ptr{Cvoid}, Any, Any), sig, C_NULL, body, moduleof(frame)::Module)
else
ccall(:jl_method_def, Cvoid, (Any, Any, Any), sig, body, moduleof(frame)::Module)
end
return f
end
function do_assignment!(frame::Frame, @nospecialize(lhs), @nospecialize(rhs))
code, data = frame.framecode, frame.framedata
if isa(lhs, SSAValue)
data.ssavalues[lhs.id] = rhs
elseif isa(lhs, SlotNumber)
counter = (frame.assignment_counter += 1)
data.locals[lhs.id] = Some{Any}(rhs)
data.last_reference[lhs.id] = counter
elseif isa(lhs, Symbol) || isa(lhs, GlobalRef)
mod = lhs isa Symbol ? moduleof(frame) : lhs.mod
name = lhs isa Symbol ? lhs : lhs.name
Core.eval(mod, Expr(:global, name))
@static if @isdefined setglobal!
setglobal!(mod, name, rhs)
else
ccall(:jl_set_global, Cvoid, (Any, Any, Any), mod, name, rhs)
end
end
end
function maybe_assign!(frame::Frame, @nospecialize(stmt), @nospecialize(val))
pc = frame.pc
if isexpr(stmt, :(=))
lhs = stmt.args[1]
do_assignment!(frame, lhs, val)
elseif isassign(frame, pc)
lhs = SSAValue(pc)
do_assignment!(frame, lhs, val)
end
return nothing
end
maybe_assign!(frame::Frame, @nospecialize(val)) = maybe_assign!(frame, pc_expr(frame), val)
function eval_rhs(@nospecialize(recurse), frame::Frame, node::Expr)
head = node.head
if head === :new
mod = moduleof(frame)
args = let mod=mod
Any[@lookup(mod, frame, arg) for arg in node.args]
end
T = popfirst!(args)::DataType
rhs = ccall(:jl_new_structv, Any, (Any, Ptr{Any}, UInt32), T, args, length(args))
return rhs
elseif head === :splatnew # Julia 1.2+
mod = moduleof(frame)
T = @lookup(mod, frame, node.args[1])::DataType
args = @lookup(mod, frame, node.args[2])::Tuple
rhs = ccall(:jl_new_structt, Any, (Any, Any), T, args)
return rhs
elseif head === :isdefined
return check_isdefined(frame, node.args[1])
elseif head === :call
# here it's crucial to avoid dynamic dispatch
isa(recurse, Compiled) && return evaluate_call_compiled!(recurse, frame, node)
return evaluate_call_recurse!(recurse, frame, node)
elseif head === :foreigncall || head === :cfunction
return evaluate_foreigncall(recurse, frame, node)
elseif head === :copyast
val = (node.args[1]::QuoteNode).value
return isa(val, Expr) ? copy(val) : val
elseif head === :boundscheck
return true
elseif head === :meta || head === :inbounds || head === :loopinfo ||
head === :gc_preserve_begin || head === :gc_preserve_end ||
head === :aliasscope || head === :popaliasscope
return nothing
elseif head === :method && length(node.args) == 1
return evaluate_methoddef(frame, node)
end
return lookup_expr(frame, node)
end
function check_isdefined(frame::Frame, @nospecialize(node))
data = frame.framedata
if isa(node, SlotNumber)
return data.locals[node.id] !== nothing
elseif isa(node, Core.Compiler.Argument) # just to be safe, since base handles this
return data.locals[node.n] !== nothing
elseif isexpr(node, :static_parameter)
return isassigned(data.sparams, node.args[1]::Int)
elseif isa(node, GlobalRef)
return isdefined(node.mod, node.name)
elseif isa(node, Symbol)
return isdefined(moduleof(frame), node)
else # QuoteNode or other implicitly quoted object
return true
end
end
function coverage_visit_line!(frame::Frame)
pc, code = frame.pc, frame.framecode
code.report_coverage || return
src = code.src
@static if VERSION ≥ v"1.12.0-DEV.173"
lineinfo = linetable(src, pc)
if lineinfo !== nothing
file, line = lineinfo.file, lineinfo.line
if line != frame.last_codeloc
file isa Symbol || (file = Symbol(file)::Symbol)
@ccall jl_coverage_visit_line(file::Cstring, sizeof(file)::Csize_t, line::Cint)::Cvoid
frame.last_codeloc = line
end
end
else # VERSION < v"1.12.0-DEV.173"
codeloc = src.codelocs[pc]
if codeloc != frame.last_codeloc && codeloc != 0
linetable = src.linetable::Vector{Any}
lineinfo = linetable[codeloc]::Core.LineInfoNode
file, line = lineinfo.file, lineinfo.line
file isa Symbol || (file = Symbol(file)::Symbol)
@ccall jl_coverage_visit_line(file::Cstring, sizeof(file)::Csize_t, line::Cint)::Cvoid
frame.last_codeloc = codeloc
end
end # @static if
end
# For "profiling" where JuliaInterpreter spends its time. See the commented-out block
# in `step_expr!`
const _location = Dict{Tuple{Method,Int},Int}()
function step_expr!(@nospecialize(recurse), frame::Frame, @nospecialize(node), istoplevel::Bool)
pc, code, data = frame.pc, frame.framecode, frame.framedata
# if !is_leaf(frame)
# show_stackloc(frame)
# @show node
# end
@assert is_leaf(frame)
@static VERSION >= v"1.8.0-DEV.370" && coverage_visit_line!(frame)
local rhs
# For debugging:
# show_stackloc(frame)
# @show node
# For profiling:
# location_key = (scopeof(frame), pc)
# _location[location_key] = get(_location, location_key, 0) + 1
try
if isa(node, Expr)
if node.head === :(=)
lhs, rhs = node.args
if isa(rhs, Expr)
rhs = eval_rhs(recurse, frame, rhs)
else
rhs = istoplevel ? @lookup(moduleof(frame), frame, rhs) : @lookup(frame, rhs)
end
isa(rhs, BreakpointRef) && return rhs
do_assignment!(frame, lhs, rhs)
elseif node.head === :enter
rhs = node.args[1]::Int
push!(data.exception_frames, rhs)
elseif node.head === :leave
if length(node.args) == 1 && isa(node.args[1], Int)
arg = node.args[1]::Int
for _ = 1:arg
pop!(data.exception_frames)
end
else
for i = 1:length(node.args)
targ = node.args[i]
targ === nothing && continue
enterstmt = frame.framecode.src.code[(targ::SSAValue).id]
enterstmt === nothing && continue
pop!(data.exception_frames)
if isdefined(enterstmt, :scope)
pop!(data.current_scopes)
end
end
end
elseif node.head === :pop_exception
# TODO: This needs to handle the exception stack properly
# (https://github.com/JuliaDebug/JuliaInterpreter.jl/issues/591)
elseif istoplevel
if node.head === :method && length(node.args) > 1
evaluate_methoddef(frame, node)
elseif node.head === :module
error("this should have been handled by split_expressions")
elseif node.head === :using || node.head === :import || node.head === :export
Core.eval(moduleof(frame), node)
elseif node.head === :const || node.head === :globaldecl
g = node.args[1]
if length(node.args) == 2
Core.eval(moduleof(frame), Expr(:block, Expr(node.head, g, @lookup(frame, node.args[2])), nothing))
else
Core.eval(moduleof(frame), Expr(:block, Expr(node.head, g), nothing))
end
elseif node.head === :thunk
newframe = Frame(moduleof(frame), node.args[1]::CodeInfo)
if isa(recurse, Compiled)
finish!(recurse, newframe, true)
else
newframe.caller = frame
frame.callee = newframe
finish!(recurse, newframe, true)
frame.callee = nothing
end
return_from(newframe)
elseif node.head === :global
Core.eval(moduleof(frame), node)
elseif node.head === :toplevel
mod = moduleof(frame)
iter = ExprSplitter(mod, node)
rhs = Core.eval(mod, Expr(:toplevel,
:(for (mod, ex) in $iter
if ex.head === :toplevel
Core.eval(mod, ex)
continue
end
newframe = ($Frame)(mod, ex)
while true
($through_methoddef_or_done!)($recurse, newframe) === nothing && break
end
$return_from(newframe)
end)))
elseif node.head === :error
error("unexpected error statement ", node)
elseif node.head === :incomplete
error("incomplete statement ", node)
else
rhs = eval_rhs(recurse, frame, node)
end
elseif node.head === :thunk || node.head === :toplevel
error("this frame needs to be run at top level")
else
rhs = eval_rhs(recurse, frame, node)
end
elseif isa(node, GotoNode)
return (frame.pc = node.label)
elseif isa(node, GotoIfNot)
arg = @lookup(frame, node.cond)
if !isa(arg, Bool)
throw(TypeError(nameof(frame), "if", Bool, arg))
end
if !arg
return (frame.pc = node.dest)
end
elseif isa(node, ReturnNode)
return nothing
elseif isa(node, NewvarNode)
# FIXME: undefine the slot?
elseif istoplevel && isa(node, LineNumberNode)
elseif istoplevel && isa(node, Symbol)
rhs = getfield(moduleof(frame), node)
elseif @static (isdefined(Core.IR, :EnterNode) && true) && isa(node, Core.IR.EnterNode)
rhs = node.catch_dest
push!(data.exception_frames, rhs)
if isdefined(node, :scope)
push!(data.current_scopes, @lookup(frame, node.scope))
end
else
rhs = @lookup(frame, node)
end
catch err
return handle_err(recurse, frame, err)
end
@isdefined(rhs) && isa(rhs, BreakpointRef) && return rhs
if isassign(frame, pc)
# if !@isdefined(rhs)
# @show frame node
# end
lhs = SSAValue(pc)
do_assignment!(frame, lhs, rhs)
end
return (frame.pc = pc + 1)
end
"""
pc = step_expr!(recurse, frame, istoplevel=false)
pc = step_expr!(frame, istoplevel=false)
Execute the next statement in `frame`. `pc` is the new program counter, or `nothing`
if execution terminates, or a [`BreakpointRef`](@ref) if execution hits a breakpoint.
`recurse` controls call evaluation; `recurse = Compiled()` evaluates :call expressions
by normal dispatch. The default value `recurse = finish_and_return!` will use recursive
interpretation.
If you are evaluating `frame` at module scope you should pass `istoplevel=true`.
"""
step_expr!(@nospecialize(recurse), frame::Frame, istoplevel::Bool=false) =
step_expr!(recurse, frame, pc_expr(frame), istoplevel)
step_expr!(frame::Frame, istoplevel::Bool=false) =
step_expr!(finish_and_return!, frame, istoplevel)
"""
loc = handle_err(recurse, frame, err)
Deal with an error `err` that arose while evaluating `frame`. There are one of three
behaviors:
- if `frame` catches the error, `loc` is the program counter at which to resume
evaluation of `frame`;
- if `frame` doesn't catch the error, but `break_on_error[]` is `true`,
`loc` is a `BreakpointRef`;
- otherwise, `err` gets rethrown.
"""
function handle_err(@nospecialize(recurse), frame::Frame, @nospecialize(err))
data = frame.framedata
err_will_be_thrown_to_top_level = isempty(data.exception_frames) && !data.caller_will_catch_err
if break_on_throw[] || (break_on_error[] && err_will_be_thrown_to_top_level)
return BreakpointRef(frame.framecode, frame.pc, err)
end
if isempty(data.exception_frames)
if !err_will_be_thrown_to_top_level
return_from(frame)
end
# Check for world age errors, which generally indicate a failure to go back to toplevel
if isa(err, MethodError)
is_arg_types = isa(err.args, DataType)
arg_types = is_arg_types ? err.args : Base.typesof(err.args...)
if (err.world != typemax(UInt) &&
hasmethod(err.f, arg_types) &&
!hasmethod(err.f, arg_types, world = err.world))
@warn "likely failure to return to toplevel, try `ExprSplitter`"
end
end
rethrow(err)
end
data.last_exception[] = err
pc = @static VERSION >= v"1.11-" ? pop!(data.exception_frames) : data.exception_frames[end] # implicit :leave after https://github.com/JuliaLang/julia/pull/52245
frame.pc = pc
return pc
end
lookup_return(frame, node::ReturnNode) = @lookup(frame, node.val)
"""
ret = get_return(frame)
Get the return value of `frame`. Throws an error if `frame.pc` does not point to a `return` expression.
`frame` must have already been executed so that the return value has been computed (see,
e.g., [`JuliaInterpreter.finish!`](@ref)).
"""
function get_return(frame)
node = pc_expr(frame)
is_return(node) || Base.invokelatest(error, "expected return statement, got ", node)
return lookup_return(frame, node)
end
get_return(t::Tuple{Module,Expr,Frame}) = get_return(t[end])
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 4217 | const max_methods = 4 # maximum number of MethodInstances tracked for a particular :call statement
"""
framecode, lenv = get_call_framecode(fargs, parentframe::FrameCode, idx::Int)
Return the framecode and environment for a call specified by `fargs = [f, args...]` (see [`prepare_args`](@ref)).
`parentframecode` is the caller, and `idx` is the program-counter index.
If possible, `framecode` will be looked up from the local method tables of `parentframe`.
"""
function get_call_framecode(fargs::Vector{Any}, parentframe::FrameCode, idx::Int; enter_generated::Bool=false)
nargs = length(fargs) # includes f as the first "argument"
# Determine whether we can look up the appropriate framecode in the local method table
if isassigned(parentframe.methodtables, idx) # if this is the first call, this may not yet be set
# The case where `methodtables[idx]` is a `Compiled` has already been handled in `bypass_builtins`
d_meth = d_meth1 = parentframe.methodtables[idx]::DispatchableMethod
local d_methprev
depth = 1
while true
# TODO: consider using world age bounds to handle cache invalidation
# Determine whether the argument types match the signature
sig = d_meth.sig.parameters::SimpleVector
if length(sig) == nargs
# If this is generated, match only if `enter_generated` also matches
fi = d_meth.frameinstance
if fi isa FrameInstance
matches = !is_generated(scopeof(fi.framecode)::Method) || enter_generated == fi.enter_generated
else
matches = !enter_generated
end
if matches
for i = 1:nargs
if !isa(fargs[i], sig[i])
matches = false
break
end
end
end
if matches
# Rearrange the list to place this method first
# (if we're in a loop, we'll likely match this one again on the next iteration)
if depth > 1
parentframe.methodtables[idx] = d_meth
d_methprev.next = d_meth.next
d_meth.next = d_meth1
end
if fi isa Compiled
return Compiled(), nothing
else
fi = fi::FrameInstance
return fi.framecode, fi.sparam_vals
end
end
end
depth += 1
d_methprev = d_meth
d_meth = d_meth.next
d_meth === nothing && break
d_meth = d_meth::DispatchableMethod
end
end
# We haven't yet encountered this argtype combination and need to look it up by dispatch
fargs[1] = f = to_function(fargs[1])
ret = prepare_call(f, fargs; enter_generated=enter_generated)
ret === nothing && return f(fargs[2:end]...), nothing
is_compiled = isa(ret[1], Compiled)
local framecode
if is_compiled
d_meth = DispatchableMethod(nothing, Compiled(), ret[2])
else
framecode, args, env, argtypes = ret
# Store the results of the method lookup in the local method table
fi = FrameInstance(framecode, env, is_generated(scopeof(framecode::FrameCode)::Method) && enter_generated)
d_meth = DispatchableMethod(nothing, fi, argtypes)
end
if isassigned(parentframe.methodtables, idx)
# Drop the oldest d_meth, if necessary
d_methtmp = d_meth.next = parentframe.methodtables[idx]::DispatchableMethod
depth = 2
while d_methtmp.next !== nothing
depth += 1
depth >= max_methods && break
d_methtmp = d_methtmp.next::DispatchableMethod
end
if depth >= max_methods
d_methtmp.next = nothing
end
else
d_meth.next = nothing
end
parentframe.methodtables[idx] = d_meth
if is_compiled
return Compiled(), nothing
else
return framecode, env
end
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 12413 | const compiled_calls = Dict{Any,Any}()
# Pre-frame-construction lookup
function lookup_stmt(stmts::Vector{Any}, @nospecialize arg)
if isa(arg, SSAValue)
arg = stmts[arg.id]
end
if isa(arg, QuoteNode)
return arg.value
end
return arg
end
function smallest_ref(stmts, arg, idmin)
if isa(arg, SSAValue)
idmin = min(idmin, arg.id)
return smallest_ref(stmts, stmts[arg.id], idmin)
elseif isa(arg, Expr)
for a in arg.args
idmin = smallest_ref(stmts, a, idmin)
end
end
return idmin
end
function lookup_global_ref(a::GlobalRef)
if Base.isbindingresolved(a.mod, a.name) && isdefined(a.mod, a.name) && isconst(a.mod, a.name)
return QuoteNode(getfield(a.mod, a.name))
end
return a
end
function lookup_global_refs!(ex::Expr)
if isexpr(ex, (:isdefined, :thunk, :toplevel, :method, :global, :const, :globaldecl))
return nothing
end
for (i, a) in enumerate(ex.args)
ex.head === :(=) && i == 1 && continue # Don't look up globalrefs on the LHS of an assignment (issue #98)
if isa(a, GlobalRef)
ex.args[i] = lookup_global_ref(a)
elseif isa(a, Expr)
lookup_global_refs!(a)
end
end
return nothing
end
function lookup_getproperties(code::Vector{Any}, @nospecialize a)
isexpr(a, :call) || return a
length(a.args) == 3 || return a
arg1 = lookup_stmt(code, a.args[1])
arg1 === Base.getproperty || return a
arg2 = lookup_stmt(code, a.args[2])
arg2 isa Module || return a
arg3 = lookup_stmt(code, a.args[3])
arg3 isa Symbol || return a
return lookup_global_ref(GlobalRef(arg2, arg3))
end
# HACK This isn't optimization really, but necessary to bypass llvmcall and foreigncall
# TODO This "optimization" should be refactored into a "minimum compilation" necessary to
# execute `llvmcall` and `foreigncall` and pure optimizations on the lowered code representation.
# In particular, the optimization that replaces `GlobalRef` with `QuoteNode` is invalid and
# should be removed: This is because it is not possible to know when and where the binding
# will be resolved without executing the code.
# Since the current `build_compiled_[llvmcall|foreigncall]!` relies on this replacement,
# they also need to be reimplemented.
"""
optimize!(code::CodeInfo, mod::Module)
Perform minor optimizations on the lowered AST in `code` to reduce execution time
of the interpreter.
Currently it looks up `GlobalRef`s (for which it needs `mod` to know the scope in
which this will run) and ensures that no statement includes nested `:call` expressions
(splitting them out into multiple SSA-form statements if needed).
"""
function optimize!(code::CodeInfo, scope)
mod = moduleof(scope)
evalmod = mod == Core.Compiler ? Core.Compiler : CompiledCalls
sparams = scope isa Method ? sparam_syms(scope) : Symbol[]
replace_coretypes!(code)
# TODO: because of builtins.jl, for CodeInfos like
# %1 = Core.apply_type
# %2 = (%1)(args...)
# it would be best to *not* resolve the GlobalRef at %1
## Replace GlobalRefs with QuoteNodes
for (i, stmt) in enumerate(code.code)
if isa(stmt, GlobalRef)
code.code[i] = lookup_global_ref(stmt)
elseif isa(stmt, Expr)
if stmt.head === :call && stmt.args[1] === :cglobal # cglobal requires literals
continue
else
lookup_global_refs!(stmt)
code.code[i] = lookup_getproperties(code.code, stmt)
end
end
end
# Replace :llvmcall and :foreigncall with compiled variants. See
# https://github.com/JuliaDebug/JuliaInterpreter.jl/issues/13#issuecomment-464880123
# Insert the foreigncall wrappers at the updated idxs
methodtables = Vector{Union{Compiled,DispatchableMethod}}(undef, length(code.code))
for (idx, stmt) in enumerate(code.code)
# Foregincalls can be rhs of assignments
if isexpr(stmt, :(=))
stmt = (stmt::Expr).args[2]
end
if isa(stmt, Expr)
if stmt.head === :call
# Check for :llvmcall
arg1 = stmt.args[1]
if (arg1 === :llvmcall || lookup_stmt(code.code, arg1) === Base.llvmcall) && isempty(sparams) && scope isa Method
# Call via `invokelatest` to avoid compiling it until we need it
Base.invokelatest(build_compiled_llvmcall!, stmt, code, idx, evalmod)
methodtables[idx] = Compiled()
end
elseif stmt.head === :foreigncall && scope isa Method
# Call via `invokelatest` to avoid compiling it until we need it
Base.invokelatest(build_compiled_foreigncall!, stmt, code, sparams, evalmod)
methodtables[idx] = Compiled()
end
end
end
return code, methodtables
end
function parametric_type_to_expr(@nospecialize(t::Type))
t isa Core.TypeofBottom && return t
while t isa UnionAll
t = t.body
end
t = t::DataType
if Base.isvarargtype(t)
return Expr(:(...), t.parameters[1])
end
if Base.has_free_typevars(t)
params = map(t.parameters) do @nospecialize(p)
isa(p, TypeVar) ? p.name :
isa(p, DataType) && Base.has_free_typevars(p) ? parametric_type_to_expr(p) : p
end
return Expr(:curly, scopename(t.name), params...)::Expr
end
return t
end
function build_compiled_llvmcall!(stmt::Expr, code::CodeInfo, idx::Int, evalmod::Module)
# Run a mini-interpreter to extract the types
framecode = FrameCode(CompiledCalls, code; optimize=false)
frame = Frame(framecode, prepare_framedata(framecode, []))
idxstart = idx
for i = 2:4
idxstart = smallest_ref(code.code, stmt.args[i], idxstart)
end
frame.pc = idxstart
if idxstart < idx
while true
pc = step_expr!(Compiled(), frame)
pc === idx && break
pc === nothing && error("this should never happen")
end
end
llvmir, RetType, ArgType = @lookup(frame, stmt.args[2]), @lookup(frame, stmt.args[3]), @lookup(frame, stmt.args[4])::DataType
args = stmt.args[5:end]
argnames = Any[Symbol(:arg, i) for i = 1:length(args)]
cc_key = (llvmir, RetType, ArgType, evalmod) # compiled call key
f = get(compiled_calls, cc_key, nothing)
if f === nothing
methname = gensym("compiled_llvmcall")
def = :(
function $methname($(argnames...))
return $(Base.llvmcall)($llvmir, $RetType, $ArgType, $(argnames...))
end)
f = Core.eval(evalmod, def)
compiled_calls[cc_key] = f
end
stmt.args[1] = QuoteNode(f)
stmt.head = :call
deleteat!(stmt.args, 2:length(stmt.args))
append!(stmt.args, args)
end
# Handle :llvmcall & :foreigncall (issue #28)
function build_compiled_foreigncall!(stmt::Expr, code::CodeInfo, sparams::Vector{Symbol}, evalmod::Module)
TVal = evalmod == Core.Compiler ? Core.Compiler.Val : Val
cfunc, RetType, ArgType = lookup_stmt(code.code, stmt.args[1]), stmt.args[2], stmt.args[3]::SimpleVector
dynamic_ccall = false
oldcfunc = nothing
if isa(cfunc, Expr) # specification by tuple, e.g., (:clock, "libc")
cfunc = something(static_eval(cfunc), cfunc)
end
if isa(cfunc, Symbol)
cfunc = QuoteNode(cfunc)
elseif isa(cfunc, String) || isa(cfunc, Ptr) || isa(cfunc, Tuple)
# do nothing
else
dynamic_ccall = true
oldcfunc = cfunc
cfunc = gensym("ptr")
end
if isa(RetType, SimpleVector)
@assert length(RetType) == 1
RetType = RetType[1]
end
args = stmt.args[6:end]
# When the ccall is dynamic we pass the pointer as an argument so can reuse the function
cc_key = ((dynamic_ccall ? :ptr : cfunc), RetType, ArgType, evalmod, length(sparams), length(args)) # compiled call key
f = get(compiled_calls, cc_key, nothing)
if f === nothing
ArgType = Expr(:tuple, Any[parametric_type_to_expr(t) for t in ArgType::SimpleVector]...)
RetType = parametric_type_to_expr(RetType)
# #285: test whether we can evaluate an type constraints on parametric expressions
# this essentially comes down to having the names be available in CompiledCalls,
# if they are not then executing the method will fail
try
isa(RetType, Expr) && Core.eval(CompiledCalls, wrap_params(RetType, sparams))
isa(ArgType, Expr) && Core.eval(CompiledCalls, wrap_params(ArgType, sparams))
catch
return nothing
end
argnames = Any[Symbol(:arg, i) for i = 1:length(args)]
wrapargs = copy(argnames)
for sparam in sparams
push!(wrapargs, :(::$TVal{$sparam}))
end
if dynamic_ccall
pushfirst!(wrapargs, cfunc)
end
methname = gensym("compiled_ccall")
def = :(
function $methname($(wrapargs...)) where {$(sparams...)}
return $(Expr(:foreigncall, cfunc, RetType, stmt.args[3:5]..., argnames...))
end)
f = Core.eval(evalmod, def)
compiled_calls[cc_key] = f
end
stmt.args[1] = QuoteNode(f)
stmt.head = :call
deleteat!(stmt.args, 2:length(stmt.args))
if dynamic_ccall
push!(stmt.args, oldcfunc)
end
append!(stmt.args, args)
for i in 1:length(sparams)
push!(stmt.args, :($TVal($(Expr(:static_parameter, i)))))
end
return nothing
end
function replace_coretypes!(@nospecialize(src); rev::Bool=false)
if isa(src, CodeInfo)
replace_coretypes_list!(src.code; rev=rev)
elseif isa(src, Expr)
replace_coretypes_list!(src.args; rev=rev)
end
return src
end
function replace_coretypes_list!(list::AbstractVector; rev::Bool=false)
function rep(@nospecialize(x), rev::Bool)
if rev
isa(x, SSAValue) && return Core.SSAValue(x.id)
isa(x, SlotNumber) && return Core.SlotNumber(x.id)
return x
else
isa(x, Core.SSAValue) && return SSAValue(x.id)
isa(x, Core.SlotNumber) && return SlotNumber(x.id)
@static if VERSION < v"1.11.0-DEV.337"
@static if VERSION ≥ v"1.10.0-DEV.631"
isa(x, Core.Compiler.TypedSlot) && return SlotNumber(x.id)
else
isa(x, Core.TypedSlot) && return SlotNumber(x.id)
end
end
return x
end
end
for (i, stmt) in enumerate(list)
rstmt = rep(stmt, rev)
if rstmt !== stmt
list[i] = rstmt
elseif isa(stmt, GotoIfNot)
cond = stmt.cond
rcond = rep(cond, rev)
if rcond !== cond
list[i] = GotoIfNot(rcond, stmt.dest)
end
elseif isa(stmt, ReturnNode)
val = stmt.val
rval = rep(val, rev)
if rval !== val
list[i] = ReturnNode(rval)
end
elseif @static (isdefined(Core.IR, :EnterNode) && true) && isa(stmt, Core.IR.EnterNode)
if isdefined(stmt, :scope)
rscope = rep(stmt.scope, rev)
if rscope !== stmt.scope
list[i] = Core.IR.EnterNode(stmt.catch_dest, rscope)
end
end
elseif isa(stmt, Expr)
replace_coretypes!(stmt; rev=rev)
end
end
return nothing
end
function reverse_lookup_globalref!(list)
# This only handles the function in calls
for (i, stmt) in enumerate(list)
if isexpr(stmt, :(=))
stmt = (stmt::Expr).args[2]
end
if isexpr(stmt, :call)
stmt = stmt::Expr
f = stmt.args[1]
if isa(f, QuoteNode)
f = f.value
if isa(f, Function) && !isa(f, Core.IntrinsicFunction)
ft = typeof(f)
tn = ft.name::Core.TypeName
name = String(tn.name)
if startswith(name, '#')
name = name[2:end]
end
stmt.args[1] = GlobalRef(tn.module, Symbol(name))
end
end
end
end
return list
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 6740 | using Base.Meta
import Base: +, -, convert, isless, get_world_counter
using Core: CodeInfo, SimpleVector, LineInfoNode, GotoNode, GotoIfNot, ReturnNode,
GeneratedFunctionStub, MethodInstance, NewvarNode, TypeName
using UUIDs
using Random
# The following are for circumventing #28, memcpy invalid instruction error,
# in Base and stdlib
using Random.DSFMT
using InteractiveUtils
export @interpret, Compiled, Frame, root, leaf, ExprSplitter,
BreakpointRef, breakpoint, @breakpoint, breakpoints, enable, disable, remove, toggle,
debug_command, @bp, break_on, break_off, on_breakpoints_updated
module CompiledCalls
# This module is for handling intrinsics that must be compiled (llvmcall) as well as ccalls
end
const SlotNamesType = Vector{Symbol}
append_any(@nospecialize x...) = append!([], Core.svec((x...)...))
if isdefined(Base, :mapany)
const mapany = Base.mapany
else
mapany(f, itr) = map!(f, Vector{Any}(undef, length(itr)::Int), itr) # convenient for Expr.args
end
if isdefined(Base, :ntupleany)
const ntupleany = Base.ntupleany
else
@noinline function ntupleany(f, n)
(n >= 0) || throw(ArgumentError(string("tuple length should be ≥ 0, got ", n)))
(Any[f(i) for i = 1:n]...,)
end
end
if !isdefined(Base, Symbol("@something"))
macro something(x...)
:(something($(map(esc, x)...)))
end
end
if isdefined(Base, :ScopedValues)
using Base: ScopedValues.Scope
else
const Scope = Any
end
include("types.jl")
include("utils.jl")
include("construct.jl")
include("localmethtable.jl")
include("interpret.jl")
include("builtins.jl")
include("optimize.jl")
include("commands.jl")
include("breakpoints.jl")
function set_compiled_methods()
###########
# Methods #
###########
# Work around #28 by preventing interpretation of all Base methods that have a ccall to memcpy
push!(compiled_methods, which(vcat, (Vector,)))
push!(compiled_methods, first(methods(Base._getindex_ra)))
push!(compiled_methods, first(methods(Base._setindex_ra!)))
push!(compiled_methods, which(Base.decompose, (BigFloat,)))
push!(compiled_methods, which(DSFMT.dsfmt_jump, (DSFMT.DSFMT_state, DSFMT.GF2X)))
@static if Sys.iswindows()
push!(compiled_methods, which(InteractiveUtils.clipboard, (AbstractString,)))
end
# issue #76
push!(compiled_methods, which(unsafe_store!, (Ptr{Any}, Any, Int)))
push!(compiled_methods, which(unsafe_store!, (Ptr, Any, Int)))
# issue #92
push!(compiled_methods, which(objectid, Tuple{Any}))
# issue #106 --- anything that uses sigatomic_(begin|end)
push!(compiled_methods, which(flush, Tuple{IOStream}))
push!(compiled_methods, which(disable_sigint, Tuple{Function}))
push!(compiled_methods, which(reenable_sigint, Tuple{Function}))
# Signal-handling in the `print` dispatch hierarchy
push!(compiled_methods, which(Base.unsafe_write, Tuple{Base.LibuvStream,Ptr{UInt8},UInt}))
push!(compiled_methods, which(print, Tuple{IO,Any}))
push!(compiled_methods, which(print, Tuple{IO,Any,Any}))
# Libc.GetLastError()
@static if Sys.iswindows()
push!(compiled_methods, which(Base.access_env, Tuple{Function,AbstractString}))
push!(compiled_methods, which(Base._hasenv, Tuple{Vector{UInt16}}))
end
# These are currently extremely slow to interpret (https://github.com/JuliaDebug/JuliaInterpreter.jl/issues/193)
push!(compiled_methods, which(subtypes, Tuple{Module,Type}))
push!(compiled_methods, which(subtypes, Tuple{Type}))
push!(compiled_methods, which(match, Tuple{Regex,String,Int,UInt32}))
# Anything that ccalls jl_typeinf_begin cannot currently be handled
for finf in (Core.Compiler.typeinf_code, Core.Compiler.typeinf_ext, Core.Compiler.typeinf_type)
for m in methods(finf)
push!(compiled_methods, m)
end
end
# Does an atomic operation via llvmcall (this fixes #354)
if isdefined(Base, :load_state_acquire)
for m in methods(Base.load_state_acquire)
push!(compiled_methods, m)
end
end
# This is about performance, not safety (issue #462)
push!(compiled_methods, which(nameof, (Module,)))
push!(compiled_methods, which(Base.binding_module, (Module, Symbol)))
push!(compiled_methods, which(Base.unsafe_pointer_to_objref, (Ptr,)))
push!(compiled_methods, which(Vector{Int}, (UndefInitializer, Int)))
push!(compiled_methods, which(fill!, (Vector{Int8}, Int)))
###########
# Modules #
###########
push!(compiled_modules, Base.Threads)
end
_have_fma_compiled(::Type{T}) where {T} = Core.Intrinsics.have_fma(T)
const FMA_FLOAT64 = Ref(false)
const FMA_FLOAT32 = Ref(false)
const FMA_FLOAT16 = Ref(false)
function __init__()
set_compiled_methods()
COVERAGE[] = Base.JLOptions().code_coverage
# If we interpret into Core.Compiler, we need to take precautions to avoid needing
# inference of JuliaInterpreter methods in the middle of a `ccall(:jl_typeinf_begin, ...)`
# block.
# for (sym, RT, AT) in ((:jl_typeinf_begin, Cvoid, ()),
# (:jl_typeinf_end, Cvoid, ()),
# (:jl_isa_compileable_sig, Int32, (Any, Any)),
# (:jl_compress_ast, Any, (Any, Any)),
# # (:jl_set_method_inferred, Ref{Core.CodeInstance}, (Any, Any, Any, Any, Int32, UInt, UInt)),
# (:jl_method_instance_add_backedge, Cvoid, (Any, Any)),
# (:jl_method_table_add_backedge, Cvoid, (Any, Any, Any)),
# (:jl_new_code_info_uninit, Ref{CodeInfo}, ()),
# (:jl_uncompress_argnames, Vector{Symbol}, (Any,)),
# (:jl_get_tls_world_age, UInt, ()),
# (:jl_call_in_typeinf_world, Any, (Ptr{Ptr{Cvoid}}, Cint)),
# (:jl_value_ptr, Any, (Ptr{Cvoid},)),
# (:jl_value_ptr, Ptr{Cvoid}, (Any,)))
# fname = Symbol(:ccall_, sym)
# qsym = QuoteNode(sym)
# argnames = [Symbol(:arg_, string(i)) for i = 1:length(AT)]
# TAT = Expr(:tuple, [parametric_type_to_expr(t) for t in AT]...)
# def = :($fname($(argnames...)) = ccall($qsym, $RT, $TAT, $(argnames...)))
# f = Core.eval(Core.Compiler, def)
# compiled_calls[(qsym, RT, Core.svec(AT...), Core.Compiler)] = f
# precompile(f, AT)
# end
@static if isdefined(Base, :have_fma)
FMA_FLOAT64[] = _have_fma_compiled(Float64)
FMA_FLOAT32[] = _have_fma_compiled(Float32)
FMA_FLOAT16[] = _have_fma_compiled(Float16)
end
end
include("precompile.jl")
_precompile_()
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 479 | module var"#Internal"
public_fn(x::String) = false
end
function _precompile_()
ccall(:jl_generating_output, Cint, ()) == 1 || return nothing
@interpret sum(rand(10))
expr = quote
public_fn(x::Integer) = true
module Private
private(y::String) = false
end
const threshold = 0.1
end
for (mod, ex) in ExprSplitter(var"#Internal", expr)
frame = Frame(mod, ex)
debug_command(frame, :c, true)
end
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 18404 | """
`Compiled` is a trait indicating that any `:call` expressions should be evaluated
using Julia's normal compiled-code evaluation. The alternative is to pass `stack=Frame[]`,
which will cause all calls to be evaluated via the interpreter.
"""
struct Compiled end
Base.similar(::Compiled, sz) = Compiled() # to support similar(stack, 0)
# Our own replacements for Core types. We need to do this to ensure we can tell the difference
# between "data" (Core types) and "code" (our types) if we step into Core.Compiler
struct SSAValue
id::Int
end
struct SlotNumber
id::Int
end
Base.show(io::IO, ssa::SSAValue) = print(io, "%J", ssa.id)
Base.show(io::IO, slot::SlotNumber) = print(io, "_J", slot.id)
# Breakpoint support
truecondition(frame) = true
falsecondition(frame) = false
const break_on_error = Ref(false)
const break_on_throw = Ref(false)
"""
BreakpointState(isactive=true, condition=JuliaInterpreter.truecondition)
`BreakpointState` represents a breakpoint at a particular statement in
a `FrameCode`. `isactive` indicates whether the breakpoint is currently
[`enable`](@ref)d or [`disable`](@ref)d. `condition` is a function that accepts
a single `Frame`, and `condition(frame)` must return either
`true` or `false`. Execution will stop at a breakpoint only if `isactive`
and `condition(frame)` both evaluate as `true`. The default `condition` always
returns `true`.
To create these objects, see [`breakpoint`](@ref).
"""
struct BreakpointState
isactive::Bool
condition::Function
end
BreakpointState(isactive::Bool) = BreakpointState(isactive, truecondition)
BreakpointState() = BreakpointState(true)
function breakpointchar(bps::BreakpointState)
if bps.isactive
return bps.condition === truecondition ? 'b' : 'c' # unconditional : conditional
end
return bps.condition === falsecondition ? ' ' : 'd' # no breakpoint : disabled
end
struct _FrameInstance{FrameCode}
framecode::FrameCode
sparam_vals::SimpleVector
enter_generated::Bool
end
Base.show(io::IO, instance::_FrameInstance) =
print(io, "FrameInstance(", scopeof(instance.framecode), ", ", instance.sparam_vals, ", ", instance.enter_generated, ')')
mutable struct _DispatchableMethod{FrameCode}
next::Union{Nothing,_DispatchableMethod{FrameCode}} # linked-list representation
frameinstance::Union{Compiled,_FrameInstance{FrameCode}} # really a Union{Compiled, FrameInstance} but we have a cyclic dependency
sig::Type # for speed of matching, this is a *concrete* signature. `sig <: frameinstance.framecode.scope.sig`
end
# 0: none
# 1: user
# 2: all
const COVERAGE = Ref{Int8}()
function do_coverage(m::Module)
COVERAGE[] == 2 && return true
if COVERAGE[] == 1
root = Base.moduleroot(m)
return root !== Base && root !== Core
end
return false
end
"""
`FrameCode` holds static information about a method or toplevel code.
One `FrameCode` can be shared by many calling `Frame`s.
Important fields:
- `scope`: the `Method` or `Module` in which this frame is to be evaluated.
- `src`: the `CodeInfo` object storing (optimized) lowered source code.
- `methodtables`: a vector, each entry potentially stores a "local method table" for the corresponding
`:call` expression in `src` (undefined entries correspond to statements that do not
contain `:call` expressions).
- `used`: a `BitSet` storing the list of SSAValues that get referenced by later statements.
"""
struct FrameCode
scope::Union{Method,Module}
src::CodeInfo
methodtables::Vector{Union{Compiled,_DispatchableMethod{FrameCode}}} # line-by-line method tables for generic-function :call Exprs
breakpoints::Vector{BreakpointState}
slotnamelists::Dict{Symbol,Vector{Int}}
used::BitSet
generator::Bool # true if this is for the expression-generator of a @generated function
report_coverage::Bool
unique_files::Set{Symbol}
end
"""
`FrameInstance` represents a method specialized for particular argument types.
Fields:
- `framecode`: the [`FrameCode`](@ref) for the method.
- `sparam_vals`: the static parameter values for the method.
"""
const FrameInstance = _FrameInstance{FrameCode}
const DispatchableMethod = _DispatchableMethod{FrameCode}
const BREAKPOINT_EXPR = :($(QuoteNode(getproperty))($JuliaInterpreter, :__BREAKPOINT_MARKER__))
function is_breakpoint_expr(ex::Expr)
# Sadly, comparing QuoteNodes calls isequal(::Any, ::Any), and === seems not to work.
# To avoid invalidations, do it the hard way.
ex.head === :call || return false
length(ex.args) === 3 || return false
(q = ex.args[1]; isa(q, QuoteNode) && q.value === getproperty) || return false
ex.args[2] === JuliaInterpreter || return false
q = ex.args[3]
return isa(q, QuoteNode) && q.value === :__BREAKPOINT_MARKER__
end
function FrameCode(scope, src::CodeInfo; generator=false, optimize=true)
if optimize
src, methodtables = optimize!(copy(src), scope)
else
src = replace_coretypes!(copy(src))
methodtables = Vector{Union{Compiled,DispatchableMethod}}(undef, length(src.code))
end
breakpoints = Vector{BreakpointState}(undef, length(src.code))
for (i, pc_expr) in enumerate(src.code)
if lookup_stmt(src.code, pc_expr) === __BREAK_POINT_MARKER__
breakpoints[i] = BreakpointState()
src.code[i] = nothing
end
end
slotnamelists = Dict{Symbol,Vector{Int}}()
for (i, sym) in enumerate(src.slotnames)
list = get(slotnamelists, sym, Int[])
slotnamelists[sym] = push!(list, i)
end
used = find_used(src)
report_coverage = do_coverage(moduleof(scope))
lt = linetable(src)
unique_files = Set{Symbol}()
@static if VERSION ≥ v"1.12.0-DEV.173"
function pushuniquefiles!(unique_files::Set{Symbol}, lt)
for edge in lt.edges
pushuniquefiles!(unique_files, edge)
end
linetable = lt.linetable
if linetable === nothing
push!(unique_files, Base.IRShow.debuginfo_file1(lt))
else
pushuniquefiles!(unique_files, linetable)
end
end
pushuniquefiles!(unique_files, lt)
else # VERSION < v"1.12.0-DEV.173"
for entry in lt
push!(unique_files, entry.file)
end
end # @static if
framecode = FrameCode(scope, src, methodtables, breakpoints, slotnamelists, used, generator, report_coverage, unique_files)
if scope isa Method
for bp in _breakpoints
# Manual union splitting
if bp isa BreakpointSignature
add_breakpoint_if_match!(framecode, bp)
elseif bp isa BreakpointFileLocation
add_breakpoint_if_match!(framecode, bp)
else
error("unhandled breakpoint type")
end
end
else
for bp in _breakpoints
if bp isa BreakpointFileLocation
add_breakpoint_if_match!(framecode, bp)
end
end
end
return framecode
end
nstatements(framecode::FrameCode) = length(framecode.src.code)
Base.show(io::IO, framecode::FrameCode) = print_framecode(io, framecode)
"""
`FrameData` holds the arguments, local variables, and intermediate execution state
in a particular call frame.
Important fields:
- `locals`: a vector containing the input arguments and named local variables for this frame.
The indexing corresponds to the names in the `slotnames` of the src. Use [`locals`](@ref)
to extract the current value of local variables.
- `ssavalues`: a vector containing the
[Static Single Assignment](https://en.wikipedia.org/wiki/Static_single_assignment_form)
values produced at the current state of execution.
- `sparams`: the static type parameters, e.g., for `f(x::Vector{T}) where T` this would store
the value of `T` given the particular input `x`.
- `exception_frames`: a list of indexes to `catch` blocks for handling exceptions within
the current frame. The active handler is the last one on the list.
- `last_exception`: the exception `throw`n by this frame or one of its callees.
"""
struct FrameData
locals::Vector{Union{Nothing,Some{Any}}}
ssavalues::Vector{Any}
sparams::Vector{Any}
exception_frames::Vector{Int}
current_scopes::Vector{Scope}
last_exception::Base.RefValue{Any}
caller_will_catch_err::Bool
last_reference::Vector{Int}
callargs::Vector{Any} # a temporary for processing arguments of :call exprs
end
"""
_INACTIVE_EXCEPTION
Represents a case where no exceptions are thrown yet.
End users will not see this singleton type, otherwise it usually means there is missing
error handling in the interpretation process.
"""
struct _INACTIVE_EXCEPTION end
"""
`Frame` represents the current execution state in a particular call frame.
Fields:
- `framecode`: the [`FrameCode`](@ref) for this frame.
- `framedata`: the [`FrameData`](@ref) for this frame.
- `pc`: the program counter (integer index of the next statment to be evaluated) for this frame.
- `caller`: the parent caller of this frame, or `nothing`.
- `callee`: the frame called by this one, or `nothing`.
The `Base` functions `show_backtrace` and `display_error` are overloaded such that
`show_backtrace(io::IO, frame::Frame)` and `display_error(io::IO, er, frame::Frame)`
shows a backtrace or error, respectively, in a similar way as to how Base shows
them.
"""
mutable struct Frame
framecode::FrameCode
framedata::FrameData
pc::Int
assignment_counter::Int64
caller::Union{Frame,Nothing}
callee::Union{Frame,Nothing}
last_codeloc::Int
end
function Frame(framecode::FrameCode, framedata::FrameData, pc=1, caller=nothing)
if length(junk_frames) > 0
frame = pop!(junk_frames)
frame.framecode = framecode
frame.framedata = framedata
frame.pc = pc
frame.assignment_counter = 1
frame.caller = caller
frame.callee = nothing
frame.last_codeloc = 0
return frame
else
return Frame(framecode, framedata, pc, 1, caller, nothing, 0)
end
end
"""
frame = Frame(mod::Module, src::CodeInfo; kwargs...)
Construct a `Frame` to evaluate `src` in module `mod`.
"""
function Frame(mod::Module, src::CodeInfo; kwargs...)
framecode = FrameCode(mod, src; kwargs...)
return Frame(framecode, prepare_framedata(framecode, []))
end
"""
frame = Frame(mod::Module, ex::Expr)
Construct a `Frame` to evaluate `ex` in module `mod`.
This constructor can error, for example if lowering `ex` results in an `:error` or `:incomplete`
expression, or if it otherwise fails to return a `:thunk`.
"""
function Frame(mod::Module, ex::Expr)
lwr = Meta.lower(mod, ex)
isexpr(lwr, :thunk) && return Frame(mod, lwr.args[1])
if isexpr(lwr, :error) || isexpr(lwr, :incomplete)
throw(ArgumentError("lowering returned an error, $lwr"))
end
throw(ArgumentError("lowering did not return a `:thunk` expression, got $lwr"))
end
caller(frame) = frame.caller
callee(frame) = frame.callee
function traverse(f, frame)
while f(frame) !== nothing
frame = f(frame)
end
return frame
end
"""
rframe = root(frame)
Return the initial frame in the call stack.
"""
root(frame) = traverse(caller, frame)
"""
lframe = leaf(frame)
Return the deepest callee in the call stack.
"""
leaf(frame) = traverse(callee, frame)
function Base.show(io::IO, frame::Frame)
frame_loc = CodeTracking.replace_buildbot_stdlibpath(repr(scopeof(frame)))
println(io, "Frame for ", frame_loc)
pc = frame.pc
ns = nstatements(frame.framecode)
range = get(io, :limit, false) ? (max(1, pc-2):min(ns, pc+2)) : (1:ns)
first(range) > 1 && println(io, "⋮")
print_framecode(io, frame.framecode; pc=pc, range=range)
last(range) < ns && print(io, "\n⋮")
print_vars(IOContext(io, :limit=>true, :compact=>true), locals(frame))
if caller(frame) !== nothing
print(io, "\ncaller: ", scopeof(caller(frame)))
end
if callee(frame) !== nothing
print(io, "\ncallee: ", scopeof(callee(frame)))
end
end
"""
`Variable` is a struct representing a variable with an asigned value.
By calling the function [`locals`](@ref) on a [`Frame`](@ref) a
`Vector` of `Variable`'s is returned.
Important fields:
- `value::Any`: the value of the local variable.
- `name::Symbol`: the name of the variable as given in the source code.
- `isparam::Bool`: if the variable is a type parameter, for example `T` in `f(x::T) where {T} = x`.
- `is_captured_closure::Bool`: if the variable has been captured by a closure
"""
struct Variable
value::Any
name::Symbol
isparam::Bool
is_captured_closure::Bool
end
Variable(value, name) = Variable(value, name, false, false)
Variable(value, name, isparam) = Variable(value, name, isparam, false)
Base.show(io::IO, var::Variable) = (print(io, var.name, " = "); show(io,var.value))
Base.isequal(var1::Variable, var2::Variable) =
var1.value == var2.value && var1.name === var2.name && var1.isparam == var2.isparam &&
var1.is_captured_closure == var2.is_captured_closure
Base.:(==)(var1::Variable, var2::Variable) = isequal(var1, var2)
# A type that is unique to this package for which there are no valid operations
struct Unassigned end
"""
BreakpointRef(framecode, stmtidx)
BreakpointRef(framecode, stmtidx, err)
A reference to a breakpoint at a particular statement index `stmtidx` in `framecode`.
If the break was due to an error, supply that as well.
Commands that execute complex control-flow (e.g., `next_line!`) may also return a
`BreakpointRef` to indicate that the execution stack switched frames, even when no
breakpoint has been set at the corresponding statement.
"""
struct BreakpointRef
framecode::FrameCode
stmtidx::Int
err
end
BreakpointRef(framecode, stmtidx) = BreakpointRef(framecode, stmtidx, nothing)
Base.getindex(bp::BreakpointRef) = bp.framecode.breakpoints[bp.stmtidx]
Base.setindex!(bp::BreakpointRef, isactive::Bool) =
bp.framecode.breakpoints[bp.stmtidx] = BreakpointState(isactive, bp[].condition)
function Base.show(io::IO, bp::BreakpointRef)
if checkbounds(Bool, bp.framecode.breakpoints, bp.stmtidx)
lineno = linenumber(bp.framecode, bp.stmtidx)
print(io, "breakpoint(", bp.framecode.scope, ", line ", lineno)
else
print(io, "breakpoint(", bp.framecode.scope, ", %", bp.stmtidx)
end
if bp.err !== nothing
print(io, ", ", bp.err)
end
print(io, ')')
end
# Possible types for breakpoint condition
const Condition = Union{Nothing,Expr,Tuple{Module,Expr}}
"""
`AbstractBreakpoint` is the abstract type that is the supertype for breakpoints. Currently,
the concrete breakpoint types [`BreakpointSignature`](@ref) and [`BreakpointFileLocation`](@ref)
exist.
Common fields shared by the concrete breakpoints:
- `condition::Union{Nothing,Expr,Tuple{Module,Expr}}`: the condition when the breakpoint applies .
`nothing` means unconditionally, otherwise when the `Expr` (optionally in `Module`).
- `enabled::Ref{Bool}`: If the breakpoint is enabled (should not be directly modified, use [`enable()`](@ref) or [`disable()`](@ref)).
- `instances::Vector{BreakpointRef}`: All the [`BreakpointRef`](@ref) that the breakpoint has applied to.
- `line::Int` The line of the breakpoint (equal to 0 if unset).
See [`BreakpointSignature`](@ref) and [`BreakpointFileLocation`](@ref) for additional fields in the concrete types.
"""
abstract type AbstractBreakpoint end
same_location(::AbstractBreakpoint, ::AbstractBreakpoint) = false
function print_bp_condition(io::IO, cond::Condition)
if cond !== nothing
if isa(cond, Tuple{Module, Expr}) && (expr = expr[2])
cond = (cond[1], Base.remove_linenums!(copy(cond[2])))
elseif isa(cond, Expr)
cond = Base.remove_linenums!(copy(cond))
end
print(io, " ", cond)
end
end
"""
A `BreakpointSignature` is a breakpoint that is set on methods or functions.
Fields:
- `f::Union{Method, Function, Type}`: A method or function that the breakpoint should apply to.
- `sig::Union{Nothing, Type}`: if `f` is a `Method`, always equal to `nothing`. Otherwise, contains the method signature
as a tuple type for what methods the breakpoint should apply to.
For common fields shared by all breakpoints, see [`AbstractBreakpoint`](@ref).
"""
struct BreakpointSignature <: AbstractBreakpoint
f::Union{Method, Base.Callable}
sig::Union{Nothing, Type}
line::Int # 0 is a sentinel for first statement
condition::Condition
enabled::Ref{Bool}
instances::Vector{BreakpointRef}
end
same_location(bp2::BreakpointSignature, bp::BreakpointSignature) =
bp2.f == bp.f && bp2.sig == bp.sig && bp2.line == bp.line
function Base.show(io::IO, bp::BreakpointSignature)
print(io, bp.f)
bbsig = bp.sig
if bbsig !== nothing
print(io, '(', join("::" .* string.(bbsig.types), ", "), ')')
end
if bp.line !== 0
print(io, ":", bp.line)
end
print_bp_condition(io, bp.condition)
if !bp.enabled[]
print(io, " [disabled]")
end
end
"""
A `BreakpointFileLocation` is a breakpoint that is set on a line in a file.
Fields:
- `path::String`: The literal string that was used to create the breakpoint, e.g. `"path/file.jl"`.
- `abspath`::String: The absolute path to the file when the breakpoint was created, e.g. `"/Users/Someone/path/file.jl"`.
For common fields shared by all breakpoints, see [`AbstractBreakpoint`](@ref).
"""
struct BreakpointFileLocation <: AbstractBreakpoint
# Both the input path and the absolute path is stored to handle the case
# where a user sets a breakpoint on a relative path e.g. `../foo.jl`. The absolute path is needed
# to handle the case where the current working directory change, and
# the input path is needed to do "partial path matches", e.g match "src/foo.jl" against
# "Package/src/foo.jl".
path::String
abspath::String
line::Int
condition::Condition
enabled::Ref{Bool}
instances::Vector{BreakpointRef}
end
same_location(bp2::BreakpointFileLocation, bp::BreakpointFileLocation) =
bp2.path == bp.path && bp2.abspath == bp.abspath && bp2.line == bp.line
function Base.show(io::IO, bp::BreakpointFileLocation)
print(io, bp.path, ':', bp.line)
print_bp_condition(io, bp.condition)
if !bp.enabled[]
print(io, " [disabled]")
end
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 27580 | ## Simple utils
# Note: to avoid dynamic dispatch, many of these are coded as a single method using isa statements
function scopeof(@nospecialize(x))::Union{Method,Module}
(isa(x, Method) || isa(x, Module)) && return x
isa(x, FrameCode) && return x.scope
isa(x, Frame) && return x.framecode.scope
error("unknown scope for ", x)
end
function moduleof(@nospecialize(x))
s = scopeof(x)
return isa(s, Module) ? s : s.module
end
function Base.nameof(frame::Frame)
s = frame.framecode.scope
isa(s, Method) ? s.name : nameof(s)
end
_Typeof(x) = isa(x, Type) ? Type{x} : typeof(x)
function to_function(@nospecialize(x))
isa(x, GlobalRef) ? getfield(x.mod, x.name) : x
end
"""
method = whichtt(tt)
Like `which` except it operates on the complete tuple-type `tt`,
and doesn't throw when there is no matching method.
"""
function whichtt(@nospecialize(tt))
# TODO: provide explicit control over world age? In case we ever need to call "old" methods.
@static if VERSION ≥ v"1.8-beta2"
# branch on https://github.com/JuliaLang/julia/pull/44515
# for now, actual code execution doesn't ever need to consider overlayed method table
match, _ = Core.Compiler._findsup(tt, nothing, get_world_counter())
match === nothing && return nothing
return match.method
else
m = ccall(:jl_gf_invoke_lookup, Any, (Any, Csize_t), tt, get_world_counter())
m === nothing && return nothing
isa(m, Method) && return m
return m.func::Method
end
end
instantiate_type_in_env(arg, spsig::UnionAll, spvals::Vector{Any}) =
ccall(:jl_instantiate_type_in_env, Any, (Any, Any, Ptr{Any}), arg, spsig, spvals)
function sparam_syms(meth::Method)
s = Symbol[]
sig = meth.sig
while sig isa UnionAll
push!(s, Symbol(sig.var.name))
sig = sig.body
end
return s
end
separate_kwargs(args...; kwargs...) = (args, values(kwargs))
pc_expr(src::CodeInfo, pc) = src.code[pc]
pc_expr(framecode::FrameCode, pc) = pc_expr(framecode.src, pc)
pc_expr(frame::Frame, pc) = pc_expr(frame.framecode, pc)
pc_expr(frame::Frame) = pc_expr(frame, frame.pc)
function find_used(code::CodeInfo)
used = BitSet()
stmts = code.code
for stmt in stmts
scan_ssa_use!(used, stmt)
end
return used
end
function scan_ssa_use!(used::BitSet, @nospecialize(stmt))
if isa(stmt, SSAValue)
push!(used, stmt.id)
end
iter = Core.Compiler.userefs(stmt)
iterval = Core.Compiler.iterate(iter)
while iterval !== nothing
useref, state = iterval
val = Core.Compiler.getindex(useref)
if (@static VERSION < v"1.11.0-DEV.1180" && true) && isexpr(val, :call)
# work around for a linearization bug in Julia (https://github.com/JuliaLang/julia/pull/52497)
scan_ssa_use!(used, val)
end
if isa(val, SSAValue)
push!(used, val.id)
end
iterval = Core.Compiler.iterate(iter, state)
end
end
function hasarg(predicate, args)
predicate(args) && return true
for a in args
predicate(a) && return true
if isa(a, Expr)
hasarg(predicate, a.args) && return true
elseif isa(a, QuoteNode)
predicate(a.value) && return true
elseif isa(a, GlobalRef)
predicate(a.name) && return true
end
end
return false
end
function wrap_params(expr, sparams::Vector{Symbol})
isempty(sparams) && return expr
params = []
for p in sparams
hasarg(isidentical(p), expr.args) && push!(params, p)
end
return isempty(params) ? expr : Expr(:where, expr, params...)
end
function scopename(tn::TypeName)
modpath = Base.fullname(tn.module)
if isa(modpath, Tuple{Symbol})
return Expr(:., modpath[1], QuoteNode(tn.name))
end
ex = Expr(:., modpath[end-1], QuoteNode(modpath[end]))
for i = length(modpath)-2:-1:1
ex = Expr(:., modpath[i], ex)
end
return Expr(:., ex, QuoteNode(tn.name))
end
## Predicates
isidentical(x) = Base.Fix2(===, x) # recommended over isequal(::Symbol) since it cannot be invalidated
is_return(@nospecialize(node)) = node isa ReturnNode
is_loc_meta(@nospecialize(expr), @nospecialize(kind)) = isexpr(expr, :meta) && length(expr.args) >= 1 && expr.args[1] === kind
"""
is_global_ref(g, mod, name)
Tests whether `g` is equal to `GlobalRef(mod, name)`.
"""
is_global_ref(@nospecialize(g), mod::Module, name::Symbol) = isa(g, GlobalRef) && g.mod === mod && g.name == name
is_quotenode(@nospecialize(q), @nospecialize(val)) = isa(q, QuoteNode) && q.value == val
is_quotenode_egal(@nospecialize(q), @nospecialize(val)) = isa(q, QuoteNode) && q.value === val
function is_quoted_type(@nospecialize(a), name::Symbol)
if isa(a, QuoteNode)
T = a.value
if isa(T, UnionAll)
T = Base.unwrap_unionall(T)
end
isa(T, DataType) && return T.name.name === name
end
return false
end
function is_function_def(@nospecialize(ex))
(isexpr(ex, :(=)) && isexpr(ex.args[1], :call)) || isexpr(ex, :function)
end
function is_call(@nospecialize(node))
isexpr(node, :call) ||
(isexpr(node, :(=)) && (isexpr(node.args[2], :call)))
end
is_call_or_return(@nospecialize(node)) = is_call(node) || node isa ReturnNode
is_dummy(bpref::BreakpointRef) = bpref.stmtidx == 0 && bpref.err === nothing
function unpack_splatcall(stmt)
if isexpr(stmt, :call) && length(stmt.args) >= 3 && is_quotenode_egal(stmt.args[1], Core._apply_iterate)
return true, stmt.args[3]
end
return false, nothing
end
function unpack_splatcall(stmt, src::CodeInfo)
issplatcall, callee = unpack_splatcall(stmt)
if isa(callee, SSAValue)
callee = src.code[callee.id]
end
return issplatcall, callee
end
function is_bodyfunc(@nospecialize(arg))
if isa(arg, QuoteNode)
arg = arg.value
end
if isa(arg, Function)
fname = String((typeof(arg).name::Core.TypeName).name)
return startswith(fname, "##") && match(r"#\d+$", fname) !== nothing
end
return false
end
"""
Determine whether we are calling a function for which the current function
is a wrapper (either because of optional arguments or because of keyword arguments).
"""
function is_wrapper_call(@nospecialize(expr))
isexpr(expr, :(=)) && (expr = expr.args[2])
isexpr(expr, :call) && any(x->x==SlotNumber(1), expr.args)
end
is_generated(meth::Method) = isdefined(meth, :generator)
@static if VERSION < v"1.10.0-DEV.873" # julia#48766
get_staged(mi::MethodInstance) = Core.Compiler.get_staged(mi)
else
get_staged(mi::MethodInstance) = Core.Compiler.get_staged(mi, Base.get_world_counter())
end
"""
is_doc_expr(ex)
Test whether expression `ex` is a `@doc` expression.
"""
function is_doc_expr(@nospecialize(ex))
docsym = Symbol("@doc")
if isexpr(ex, :macrocall)
ex::Expr
length(ex.args) == 4 || return false
a = ex.args[1]
is_global_ref(a, Core, docsym) && return true
isa(a, Symbol) && a == docsym && return true
if isexpr(a, :.)
mod, name = (a::Expr).args[1], (a::Expr).args[2]
return mod === :Core && isa(name, QuoteNode) && name.value === docsym
end
end
return false
end
is_leaf(frame::Frame) = frame.callee === nothing
function is_vararg_type(x)
@static if isa(Vararg, Type)
if isa(x, Type)
(x <: Vararg && !(x <: Union{})) && return true
if isa(x, UnionAll)
x = Base.unwrap_unionall(x)
end
return isa(x, DataType) && nameof(x) === :Vararg
end
else
return isa(x, typeof(Vararg))
end
return false
end
## Location info
# These getters improve inference since fieldtype(CodeInfo, :linetable)
# and fieldtype(CodeInfo, :codelocs) are both Any
@static if VERSION ≥ v"1.12.0-DEV.173"
const LineTypes = Union{LineNumberNode,Base.IRShow.LineInfoNode}
else
const LineTypes = Union{LineNumberNode,Core.LineInfoNode}
end
function linetable(arg)
if isa(arg, Frame)
arg = arg.framecode
end
if isa(arg, FrameCode)
arg = arg.src
end
ci = arg::CodeInfo
@static if VERSION ≥ v"1.12.0-DEV.173"
return ci.debuginfo
else # VERSION < v"1.12.0-DEV.173"
return ci.linetable::Union{Vector{Core.LineInfoNode},Vector{Any}} # issue #264
end # @static if
end
function linetable(arg, i::Integer; macro_caller::Bool=false, def=:var"n/a")::Union{Expr,Nothing,LineTypes}
lt = linetable(arg)
@static if VERSION ≥ v"1.12.0-DEV.173"
# TODO: decode the linetable at this frame efficiently by reimplementing this here
nodes = Base.IRShow.buildLineInfoNode(lt, def, i)
isempty(nodes) && return nothing
return nodes[1] # ignore all inlining / macro expansion / etc :(
else # VERSION < v"1.12.0-DEV.173"
lin = lt[i]::Union{Expr,LineTypes}
if macro_caller
while lin isa Core.LineInfoNode && lin.method === Symbol("macro expansion") && lin.inlined_at != 0
lin = lt[lin.inlined_at]::Union{Expr,LineTypes}
end
end
return lin
end # @static if
end
@static if VERSION ≥ v"1.12.0-DEV.173"
getlastline(arg) = getlastline(linetable(arg))
function getlastline(debuginfo::Core.DebugInfo)
while true
ltnext = debuginfo.linetable
ltnext === nothing && break
debuginfo = ltnext
end
lastline = 0
for k = 0:typemax(Int)
codeloc = Core.Compiler.getdebugidx(debuginfo, k)
line::Int = codeloc[1]
line < 0 && break
lastline = max(lastline, line)
end
return lastline
end
function codelocs(arg, i::Integer)
debuginfo = linetable(arg)
codeloc = Core.Compiler.getdebugidx(debuginfo, i)
line::Int = codeloc[1]
line < 0 && return 0# broken or disabled debug info?
if line == 0 && codeloc[2] == 0
return 0 # no line number update
end
return i
end
else # VERSION < v"1.12.0-DEV.173"
getfirstline(arg) = getline(linetable(arg)[begin])
getlastline(arg) = getline(linetable(arg)[end])
function codelocs(arg)
if isa(arg, Frame)
arg = arg.framecode
end
if isa(arg, FrameCode)
arg = arg.src
end
ci = arg::CodeInfo
return ci.codelocs
end
codelocs(arg, i::Integer) = codelocs(arg)[i]
end # @static if
function lineoffset(framecode::FrameCode)
offset = 0
scope = framecode.scope
if isa(scope, Method)
_, line1 = whereis(scope)
offset = line1 - scope.line
end
return offset
end
function getline(ln::Union{LineTypes,Expr,Nothing})
_getline(ln::LineTypes) = Int(ln.line)
_getline(ln::Expr) = ln.args[1]::Int # assuming ln.head === :line
_getline(::Nothing) = nothing
return _getline(ln)
end
function getfile(ln::Union{LineTypes,Expr})
_getfile(ln::LineTypes) = ln.file::Symbol
_getfile(ln::Expr) = ln.args[2]::Symbol # assuming ln.head === :line
return CodeTracking.maybe_fixup_stdlib_path(String(_getfile(ln)))
end
function firstline(ex::Expr)
for a in ex.args
isa(a, LineNumberNode) && return a
if isa(a, Expr)
line = firstline(a)
isa(line, LineNumberNode) && return line
end
end
return nothing
end
"""
loc = whereis(frame, pc::Int=frame.pc; macro_caller=false)
Return the file and line number for `frame` at `pc`. If this cannot be
determined, `loc == nothing`. Otherwise `loc == (filepath, line)`.
By default, any statements expanded from a macro are attributed to the macro
definition, but with`macro_caller=true` you can obtain the location within the
method that issued the macro.
"""
function CodeTracking.whereis(framecode::FrameCode, pc::Int; kwargs...)
codeloc = codelocation(framecode.src, pc)
codeloc == 0 && return nothing
m = framecode.scope
lineinfo = linetable(framecode, codeloc; kwargs..., def=isa(m, Method) ? m : :var"n/a")
if m isa Method
return lineinfo === nothing ? (String(m.file), m.line) : whereis(lineinfo, m)
else
return lineinfo === nothing ? nothing : (getfile(lineinfo), getline(lineinfo))
end
end
CodeTracking.whereis(frame::Frame, pc::Int=frame.pc; kwargs...) = whereis(frame.framecode, pc; kwargs...)
"""
line = linenumber(framecode, pc)
Return the "static" line number at statement index `pc`. The static line number
is the location at the time the method was most recently defined.
See [`CodeTracking.whereis`](@ref) for dynamic line information.
"""
function linenumber(framecode::FrameCode, pc)
codeloc = codelocation(framecode.src, pc)
codeloc == 0 && return nothing
return getline(linetable(framecode, codeloc))
end
linenumber(frame::Frame, pc=frame.pc) = linenumber(frame.framecode, pc)
function getfile(framecode::FrameCode, pc)
codeloc = codelocation(framecode.src, pc)
codeloc == 0 && return nothing
return getfile(linetable(framecode, codeloc))
end
getfile(frame::Frame, pc=frame.pc) = getfile(frame.framecode, pc)
function codelocation(code::CodeInfo, idx::Int)
idx′ = idx
# look ahead if we are on a meta line
while idx′ < length(code.code)
codeloc = codelocs(code, idx′)
codeloc == 0 || return codeloc
ex = code.code[idx′]
ex === nothing || isexpr(ex, :meta) || break
idx′ += 1
end
idx′ = idx - 1
# if zero, look behind until we find where we last might have had a line
while idx′ > 0
ex = code.code[idx′]
codeloc = codelocs(code, idx′)
codeloc == 0 || return codeloc
idx′ -= 1
end
# for the start of the function, return index 1
return 1
end
function compute_corrected_linerange(method::Method)
_, line1 = whereis(method)
offset = line1 - method.line
@assert !is_generated(method)
src = JuliaInterpreter.get_source(method)
lastline = getlastline(src)
return line1:lastline + offset
end
compute_linerange(framecode) = getfirstline(framecode):getlastline(framecode)
function statementnumbers(framecode::FrameCode, line::Integer, file::Symbol)
# Check to see if this framecode really contains that line. Methods that fill in a default positional argument,
# keyword arguments, and @generated sections may not contain the line.
scope = framecode.scope
offset = if scope isa Method
method = scope
_, line1 = whereis(method)
Int(line1 - method.line)
else
0
end
lt = linetable(framecode)
# Check if the exact line number exist
idxs = findall(entry::Union{LineInfoNode,LineNumberNode} -> entry.line + offset == line && entry.file == file, lt)
locs = codelocs(framecode)
if !isempty(idxs)
stmtidxs = Int[]
stmtidx = 1
while stmtidx <= length(locs)
loc = locs[stmtidx]
if loc in idxs
push!(stmtidxs, stmtidx)
stmtidx += 1
# Skip continous statements that are on the same line
while stmtidx <= length(locs) && loc == locs[stmtidx]
stmtidx += 1
end
else
stmtidx += 1
end
end
return stmtidxs
end
# If the exact line number does not exist in the line table, take the one that is closest after that line
# restricted to the line range of the current scope.
scope = framecode.scope
range = (scope isa Method && !is_generated(scope)) ? compute_corrected_linerange(scope) : compute_linerange(framecode)
if line in range
closest = nothing
closest_idx = nothing
for (i, entry) in enumerate(lt)
entry = entry::Union{LineInfoNode,LineNumberNode}
if entry.file == file && entry.line in range && entry.line >= line
if closest === nothing
closest = entry
closest_idx = i
else
if entry.line < closest.line
closest = entry
closest_idx = i
end
end
end
end
if closest_idx !== nothing
idx = let closest_idx=closest_idx # julia #15276
findfirst(i-> i==closest_idx, locs)
end
return idx === nothing ? nothing : Int[idx]
end
end
return nothing
end
## Printing
function framecode_lines(src::CodeInfo)
buf = IOBuffer()
if isdefined(Base.IRShow, :show_ir_stmt)
lines = String[]
src = replace_coretypes!(copy(src); rev=true)
reverse_lookup_globalref!(src.code)
io = IOContext(buf, :displaysize => displaysize(stdout),
:SOURCE_SLOTNAMES => Base.sourceinfo_slotnames(src))
used = BitSet()
cfg = Core.Compiler.compute_basic_blocks(src.code)
for stmt in src.code
Core.Compiler.scan_ssa_use!(push!, used, stmt)
end
line_info_preprinter = Base.IRShow.lineinfo_disabled
line_info_postprinter = Base.IRShow.default_expr_type_printer
bb_idx = 1
for idx = 1:length(src.code)
bb_idx = Base.IRShow.show_ir_stmt(io, src, idx, line_info_preprinter, line_info_postprinter, used, cfg, bb_idx)
push!(lines, chomp(String(take!(buf))))
end
return lines
end
show(buf, src)
code = filter!(split(String(take!(buf)), '\n')) do line
!(line == "CodeInfo(" || line == ")" || isempty(line) || occursin("within `", line))
end
code .= replace.(code, Ref(r"\$\(QuoteNode\((.+?)\)\)" => s"\1"))
return code
end
framecode_lines(framecode::FrameCode) = framecode_lines(framecode.src)
breakpointchar(framecode, stmtidx) =
isassigned(framecode.breakpoints, stmtidx) ? breakpointchar(framecode.breakpoints[stmtidx]) : ' '
function print_framecode(io::IO, framecode::FrameCode; pc=0, range=1:nstatements(framecode), kwargs...)
iscolor = get(io, :color, false)
ndstmt = ndigits(nstatements(framecode))
ndline = ndigits(getlastline(framecode) + lineoffset(framecode))
nullline = " "^ndline
src = copy(framecode.src)
replace_coretypes!(src; rev=true)
code = framecode_lines(src)
isfirst = true
for (stmtidx, stmtline) in enumerate(code)
stmtidx ∈ range || continue
bpc = breakpointchar(framecode, stmtidx)
isfirst || print(io, '\n')
isfirst = false
print(io, bpc, ' ')
if iscolor
color = stmtidx == pc ? Base.warn_color() : :normal
printstyled(io, lpad(stmtidx, ndstmt); color=color, kwargs...)
else
print(io, lpad(stmtidx, ndstmt), stmtidx == pc ? '*' : ' ')
end
line = linenumber(framecode, stmtidx)
print(io, ' ', line === nothing ? nullline : lpad(line, ndline), " ", stmtline)
end
end
"""
local_variables = locals(frame::Frame)::Vector{Variable}
Return the local variables as a vector of [`Variable`](@ref).
"""
function locals(frame::Frame)
vars, var_counter = Variable[], Int[]
varlookup = Dict{Symbol,Int}()
data, code = frame.framedata, frame.framecode
slotnames = code.src.slotnames
for (sym, counter, val) in zip(slotnames, data.last_reference, data.locals)
counter == 0 && continue
val = something(val)
if val isa Core.Box && !isdefined(val, :contents)
continue
end
var = Variable(val, sym)
idx = get(varlookup, sym, 0)
if idx > 0
if counter > var_counter[idx]
vars[idx] = var
var_counter[idx] = counter
end
else
varlookup[sym] = length(vars)+1
push!(vars, var)
push!(var_counter, counter)
end
end
scope = code.scope
if scope isa Method
syms = sparam_syms(scope)
for i in 1:length(syms)
if isassigned(data.sparams, i)
push!(vars, Variable(data.sparams[i], syms[i], true))
end
end
end
for var in vars
if var.name === Symbol("#self#")
for field in fieldnames(typeof(var.value))
field = field::Symbol
if isdefined(var.value, field)
push!(vars, Variable(getfield(var.value, field), field, false, true))
end
end
end
end
return vars
end
function print_vars(io::IO, vars::Vector{Variable})
for v in vars
v.name === Symbol("#self#") && (isa(v.value, Type) || sizeof(v.value) == 0) && continue
print(io, '\n', v)
end
end
"""
eval_code(frame::Frame, code::Union{String, Expr})
Evaluate `code` in the context of `frame`, updating any local variables
(including type parameters) that are reassigned in `code`, however, new local variables
cannot be introduced.
```jldoctest
julia> foo(x, y) = x + y;
julia> frame = JuliaInterpreter.enter_call(foo, 1, 3);
julia> JuliaInterpreter.eval_code(frame, "x + y")
4
julia> JuliaInterpreter.eval_code(frame, "x = 5");
julia> JuliaInterpreter.finish_and_return!(frame)
8
```
When variables are captured in closures (and thus gets wrapped in a `Core.Box`)
they will be automatically unwrapped and rewrapped upon evaluating them:
```jldoctest
julia> function capture()
x = 1
f = ()->(x = 2) # x captured in closure and is thus a Core.Box
f()
x
end;
julia> frame = JuliaInterpreter.enter_call(capture);
julia> JuliaInterpreter.step_expr!(frame);
julia> JuliaInterpreter.step_expr!(frame);
julia> JuliaInterpreter.locals(frame)
2-element Vector{JuliaInterpreter.Variable}:
#self# = capture
x = Core.Box(1)
julia> JuliaInterpreter.eval_code(frame, "x")
1
julia> JuliaInterpreter.eval_code(frame, "x = 2")
2
julia> JuliaInterpreter.locals(frame)
2-element Vector{JuliaInterpreter.Variable}:
#self# = capture
x = Core.Box(2)
```
"Special" values like SSA values and slots (shown in lowered code as e.g. `%3` and `@_4`
respectively) can be evaluated using the syntax `var"%3"` and `var"@_4"` respectively.
"""
function eval_code end
function extract_usage!(s::Set{Symbol}, expr)
if expr isa Expr
for arg in expr.args
if arg isa Symbol
push!(s, arg)
elseif arg isa Expr
extract_usage!(s, arg)
end
end
elseif expr isa Symbol
push!(s, expr)
end
return s
end
function eval_code(frame::Frame, command::AbstractString)
expr = Base.parse_input_line(command)
expr === nothing && return nothing
return eval_code(frame, expr)
end
function eval_code(frame::Frame, expr::Expr)
code = frame.framecode
data = frame.framedata
isexpr(expr, :toplevel) && (expr = expr.args[end])
if isexpr(expr, :toplevel)
expr = Expr(:block, expr.args...)
end
used_symbols = Set{Symbol}((Symbol("#self#"),))
extract_usage!(used_symbols, expr)
# see https://github.com/JuliaLang/julia/issues/31255 for the Symbol("") check
vars = filter(v -> v.name != Symbol("") && v.name in used_symbols, locals(frame))
defined_ssa = findall(i -> isassigned(data.ssavalues, i) && Symbol("%$i") in used_symbols, 1:length(data.ssavalues))
defined_locals = findall(i-> data.locals[i] isa Some && Symbol("@_$i") in used_symbols, 1:length(data.locals))
res = gensym()
eval_expr = Expr(:let,
Expr(:block, map(x->Expr(:(=), x...), [(v.name, QuoteNode(v.value isa Core.Box ? v.value.contents : v.value)) for v in vars])...,
map(x->Expr(:(=), x...), [(Symbol("%$i"), QuoteNode(data.ssavalues[i])) for i in defined_ssa])...,
map(x->Expr(:(=), x...), [(Symbol("@_$i"), QuoteNode(data.locals[i].value)) for i in defined_locals])...,
),
Expr(:block,
Expr(:(=), res, expr),
Expr(:tuple, res, Expr(:tuple, [v.name for v in vars]...))
))
eval_res, res = Core.eval(moduleof(frame), eval_expr)
j = 1
for (i, v) in enumerate(vars)
if v.isparam
data.sparams[j] = res[i]
j += 1
elseif v.is_captured_closure
selfidx = findfirst(v -> v.name === Symbol("#self#"), vars)
@assert selfidx !== nothing
self = vars[selfidx].value
closed_over_var = getfield(self, v.name)
if closed_over_var isa Core.Box
setfield!(closed_over_var, :contents, res[i])
end
# We cannot rebind closed over variables that the frontend identified as constant
else
slot_indices = code.slotnamelists[v.name]
idx = argmax(data.last_reference[slot_indices])
slot_idx = slot_indices[idx]
data.last_reference[slot_idx] = (frame.assignment_counter += 1)
data.locals[slot_idx] = Some{Any}(v.value isa Core.Box ? Core.Box(res[i]) : res[i])
end
end
eval_res
end
function show_stackloc(io::IO, frame)
indent = ""
fr = root(frame)
shown = false
while fr !== nothing
print(io, indent, scopeof(fr))
if fr === frame
println(io, ", pc = ", frame.pc)
shown = true
else
print(io, '\n')
end
indent *= " "
fr = fr.callee
end
if !shown
println(io, indent, scopeof(frame), ", pc = ", frame.pc)
end
end
show_stackloc(frame) = show_stackloc(stdout, frame)
# Printing of stacktraces and errors with Frame
function Base.StackTraces.StackFrame(frame::Frame)
scope = scopeof(frame)
if scope isa Method
method = scope
method_args = Any[something(frame.framedata.locals[i]) for i in 1:method.nargs]
argt = Tuple{mapany(_Typeof, method_args)...}
sig = method.sig
atype, sparams = ccall(:jl_type_intersection_with_env, Any, (Any, Any), argt, sig)::SimpleVector
mi = Core.Compiler.specialize_method(method, atype, sparams::SimpleVector)
fname = method.name
else
mi = frame.framecode.src
fname = gensym()
end
Base.StackFrame(
fname,
Symbol(getfile(frame)),
@something(linenumber(frame), getfirstline(frame)),
mi,
false,
false,
C_NULL)
end
function Base.show_backtrace(io::IO, frame::Frame)
stackframes = Tuple{Base.StackTraces.StackFrame, Int}[]
while frame !== nothing
push!(stackframes, (Base.StackTraces.StackFrame(frame), 1))
frame = JuliaInterpreter.caller(frame)
end
print(io, "\nStacktrace:")
try invokelatest(Base.update_stackframes_callback[], stackframes) catch end
frame_counter = 0
nd = ndigits(length(stackframes))
for (i, (last_frame, n)) in enumerate(stackframes)
frame_counter += 1
if isdefined(Base, :print_stackframe)
println(io)
Base.print_stackframe(io, i, last_frame, n, nd, Base.info_color())
else
Base.show_trace_entry(IOContext(io, :backtrace => true), last_frame, n, prefix = string(" [", frame_counter, "] "))
end
end
end
function Base.display_error(io::IO, er, frame::Frame)
printstyled(io, "ERROR: "; bold=true, color=Base.error_color())
showerror(IOContext(io, :limit => true), er, frame)
println(io)
end
function static_eval(ex)
try
eval(ex)
catch
nothing
end
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 17614 | radius2(x, y) = x^2 + y^2
function loop_radius2(n)
s = 0
for i = 1:n
s += radius2(1, i)
end
s
end
tmppath = ""
global tmppath
tmppath, io = mktemp()
print(io, """
function jikwfunc(x, y=0; z="hello")
a = x + y
b = z^a
return length(b)
end
""")
close(io)
include(tmppath)
using JuliaInterpreter, CodeTracking, Test
function stacklength(frame)
n = 1
frame = frame.callee
while frame !== nothing
n += 1
frame = frame.callee
end
return n
end
struct Squarer end
@testset "Breakpoints" begin
Δ = CodeTracking.line_is_decl
breakpoint(radius2)
frame = JuliaInterpreter.enter_call(loop_radius2, 2)
bp = JuliaInterpreter.finish_and_return!(frame)
@test isa(bp, JuliaInterpreter.BreakpointRef)
@test stacklength(frame) == 2
@test leaf(frame).framecode.scope == @which radius2(0, 0)
bp = JuliaInterpreter.finish_stack!(frame)
@test isa(bp, JuliaInterpreter.BreakpointRef)
@test stacklength(frame) == 2
@test JuliaInterpreter.finish_stack!(frame) == loop_radius2(2)
# Conditional breakpoints
function runsimple()
frame = JuliaInterpreter.enter_call(loop_radius2, 2)
bp = JuliaInterpreter.finish_and_return!(frame)
@test isa(bp, JuliaInterpreter.BreakpointRef)
@test stacklength(frame) == 2
@test leaf(frame).framecode.scope == @which radius2(0, 0)
@test JuliaInterpreter.finish_stack!(frame) == loop_radius2(2)
end
remove()
breakpoint(radius2, :(y > x))
runsimple()
remove()
@breakpoint radius2(0,0) y>x
runsimple()
# Demonstrate the problem that we have with scope
local_identity(x) = identity(x)
remove()
@breakpoint radius2(0,0) y>local_identity(x)
@test_broken @interpret loop_radius2(2)
# Conditional breakpoints on local variables
remove()
halfthresh = loop_radius2(5)
bp = @breakpoint loop_radius2(10) 5 s>$halfthresh
frame, bpref = @interpret loop_radius2(10)
@test isa(bpref, JuliaInterpreter.BreakpointRef)
lframe = leaf(frame)
s_extractor = eval(JuliaInterpreter.prepare_slotfunction(lframe.framecode, :s))
@test s_extractor(lframe) == loop_radius2(6)
JuliaInterpreter.finish_stack!(frame)
@test s_extractor(lframe) == loop_radius2(7)
disable(bp)
@test JuliaInterpreter.finish_stack!(frame) == loop_radius2(10)
# Return value with breakpoints
@breakpoint sum([1,2]) any(x->x>4, a)
val = @interpret sum([1,2,3])
@test val == 6
frame, bp = @interpret sum([1,2,5])
@test isa(frame, Frame) && isa(bp, JuliaInterpreter.BreakpointRef)
# Next line with breakpoints
function outer(x)
inner(x)
end
function inner(x)
return 2
end
breakpoint(inner)
frame = JuliaInterpreter.enter_call(outer, 0)
bp = JuliaInterpreter.next_line!(frame)
@test isa(bp, JuliaInterpreter.BreakpointRef)
@test JuliaInterpreter.finish_stack!(frame) == 2
# Breakpoints by file/line
remove()
method = which(JuliaInterpreter.locals, Tuple{Frame})
breakpoint(String(method.file), method.line+1)
frame = JuliaInterpreter.enter_call(loop_radius2, 2)
ret = @interpret JuliaInterpreter.locals(frame)
@test isa(ret, Tuple{Frame,JuliaInterpreter.BreakpointRef})
# Test kwarg method
remove()
bp = breakpoint(tmppath, 3)
frame, bp2 = @interpret jikwfunc(2)
var = JuliaInterpreter.locals(leaf(frame))
@test !any(v->v.name === :b, var)
@test filter(v->v.name === :a, var)[1].value == 2
# Method with local scope (two slots with same name)
ln = @__LINE__
function ftwoslots()
y = 1
z = let y = y
y = y + 2
rand()
end
y = y + 1
return z
end
bp = breakpoint(@__FILE__, ln+5, :(y > 2))
frame, bp2 = @interpret ftwoslots()
var = JuliaInterpreter.locals(leaf(frame))
@test filter(v->v.name === :y, var)[1].value == 3
remove(bp)
bp = breakpoint(@__FILE__, ln+8, :(y > 2))
@test isa(@interpret(ftwoslots()), Float64)
# Direct return
@breakpoint gcd(1,1) a==5
@test @interpret(gcd(10,20)) == 10
# FIXME: even though they pass, these tests break Test!
# frame, bp = @interpret gcd(5, 20)
# @test stacklength(frame) == 1
# @test isa(bp, JuliaInterpreter.BreakpointRef)
remove()
# break on error
try
@test_throws ArgumentError("unsupported state :missing") break_on(:missing)
break_on(:error)
inner(x) = error("oops")
outer() = inner(1)
frame = JuliaInterpreter.enter_call(outer)
bp = JuliaInterpreter.finish_and_return!(frame)
@test bp.err == ErrorException("oops")
@test stacklength(frame) >= 2
@test frame.framecode.scope.name === :outer
cframe = frame.callee
@test cframe.framecode.scope.name === :inner
# Don't break on caught exceptions
function f_exc_outer()
try
f_exc_inner()
catch err
return err
end
end
function f_exc_inner()
error()
end
frame = JuliaInterpreter.enter_call(f_exc_outer);
v = JuliaInterpreter.finish_and_return!(frame)
@test v isa ErrorException
@test stacklength(frame) == 1
# Break on caught exception when enabled
break_on(:throw)
try
frame = JuliaInterpreter.enter_call(f_exc_outer);
v = JuliaInterpreter.finish_and_return!(frame)
@test v isa BreakpointRef
@test v.err isa ErrorException
@test v.framecode.scope == @which error()
finally
break_off(:throw)
end
finally
break_off(:error)
end
# Breakpoint display
io = IOBuffer()
frame = JuliaInterpreter.enter_call(loop_radius2, 2)
@static if VERSION < v"1.9.0-DEV.846" # https://github.com/JuliaLang/julia/pull/45069
LOC = " in $(@__MODULE__) at $(@__FILE__)"
else
LOC = " @ $(@__MODULE__) $(contractuser(@__FILE__))"
end
bp = JuliaInterpreter.BreakpointRef(frame.framecode, 1)
@test repr(bp) == "breakpoint(loop_radius2(n)$LOC:$(3-Δ), line 3)"
bp = JuliaInterpreter.BreakpointRef(frame.framecode, 0) # fictive breakpoint
@test repr(bp) == "breakpoint(loop_radius2(n)$LOC:$(3-Δ), %0)"
bp = JuliaInterpreter.BreakpointRef(frame.framecode, 1, ArgumentError("whoops"))
@test repr(bp) == "breakpoint(loop_radius2(n)$LOC:$(3-Δ), line 3, ArgumentError(\"whoops\"))"
# In source breakpointing
f_outer_bp(x) = g_inner_bp(x)
function g_inner_bp(x)
sin(x)
@bp
@bp
@bp
x = 3
return 2
end
fr, bp = @interpret f_outer_bp(3)
@test leaf(fr).framecode.scope.name === :g_inner_bp
@test bp.stmtidx == (@static VERSION >= v"1.11-" ? 4 : 3)
# Breakpoints on types
remove()
g() = Int(5.0)
@breakpoint Int(5.0)
frame, bp = @interpret g()
@test bp isa BreakpointRef
@test leaf(frame).framecode.scope === @which Int(5.0)
# Breakpoint on call overloads
(::Squarer)(x) = x^2
squarer = Squarer()
@breakpoint squarer(2)
frame, bp = @interpret squarer(3.0)
@test bp isa BreakpointRef
@test leaf(frame).framecode.scope === @which squarer(3.0)
end
mktemp() do path, io
print(io, """
function somefunc(x, y=0)
a = x + y
b = z^a
return a + b
end
""")
close(io)
breakpoint(path, 3)
include(path)
frame, bp = @interpret somefunc(2, 3)
@test bp isa BreakpointRef
@test JuliaInterpreter.whereis(frame) == (path, 3)
breakpoint(path, 2)
frame, bp = @interpret somefunc(2, 3)
@test bp isa BreakpointRef
@test JuliaInterpreter.whereis(frame) == (path, 2)
remove()
# Test relative paths
mktempdir(dirname(path)) do tmp
cd(tmp) do
breakpoint(joinpath("..", basename(path)), 3)
frame, bp = @interpret somefunc(2, 3)
@test bp isa BreakpointRef
@test JuliaInterpreter.whereis(frame) == (path, 3)
remove()
breakpoint(joinpath("..", basename(path)), 3)
cd(homedir()) do
frame, bp = @interpret somefunc(2, 3)
@test bp isa BreakpointRef
@test JuliaInterpreter.whereis(frame) == (path, 3)
end
end
end
end
if tmppath != ""
rm(tmppath)
end
@testset "toggling" begin
remove()
f_break(x::Int) = x
bp = breakpoint(f_break)
frame, bpref = @interpret f_break(5)
@test bpref isa BreakpointRef
toggle(bp)
@test (@interpret f_break(5)) == 5
f_break(x::Float64) = 2x
@test (@interpret f_break(2.0)) == 4.0
toggle(bp)
frame, bpref = @interpret f_break(5)
@test bpref isa BreakpointRef
frame, bpref = @interpret f_break(2.0)
@test bpref isa BreakpointRef
end
using Dates
@testset "breakpoint in stdlibs by path" begin
m = @which now() - Month(2)
f = String(m.file)
l = m.line + 1
for f in (f, basename(f))
remove()
breakpoint(f, l)
frame, bp = @interpret now() - Month(2)
@test bp isa BreakpointRef
@test JuliaInterpreter.whereis(frame)[2] == l
end
end
@testset "breakpoint in Base by path" begin
m = @which sin(2.0)
f = String(m.file)
l = m.line + 1
for f in (f, basename(f))
remove()
breakpoint(f, l)
frame, bp = @interpret sin(2.0)
@test bp isa BreakpointRef
@test JuliaInterpreter.whereis(frame)[2] == l
end
end
@testset "breakpoint by type" begin
remove()
breakpoint(sin, Tuple{Float64})
frame, bp = @interpret sin(2.0)
@test bp isa BreakpointRef
end
const breakpoint_update_hooks = JuliaInterpreter.breakpoint_update_hooks
const on_breakpoints_updated = JuliaInterpreter.on_breakpoints_updated
@testset "hooks" begin
remove()
f_break(x) = x
# Check creating hits hook
empty!(breakpoint_update_hooks)
hook_hit = false
on_breakpoints_updated((f,_)->hook_hit = f == breakpoint)
orig_bp = breakpoint(f_break)
@test hook_hit
# Check re-creating hits remove *and* breakpoint (create)
empty!(breakpoint_update_hooks)
hit_remove_old = false
hit_create_new = false
hit_other = false # don't want this
on_breakpoints_updated() do f, hbp
if f==remove
hit_remove_old = hbp === orig_bp
elseif f==breakpoint
hit_create_new = hbp !== orig_bp
else
hit_other = true
end
end
push!(breakpoint_update_hooks, (f,_)->hook_hit = f == breakpoint)
bp = breakpoint(f_break)
@test hit_remove_old
@test hit_create_new
@test !hit_other
@testset "update_states! $op hits hook" for op in (disable, enable, toggle)
empty!(breakpoint_update_hooks)
hook_hit = false
on_breakpoints_updated((f, _) -> hook_hit = f == JuliaInterpreter.update_states!)
op(bp)
@test hook_hit
end
# Test removing hits hooks
empty!(breakpoint_update_hooks)
hook_hit = false
on_breakpoints_updated((f, _) -> hook_hit = f === remove)
remove(bp)
@test hook_hit
@testset "make sure error in hook function doesn't throw" begin
empty!(breakpoint_update_hooks)
on_breakpoints_updated((_, _) -> error("bad hook"))
@test_logs (:warn, r"hook"i) breakpoint(f_break)
end
end
# Run outside testset so that if it fails, the hooks get removed. So other tests can pass
empty!(breakpoint_update_hooks)
@testset "toplevel breakpoints" begin
mktemp() do path, io
print(io, """
1+1 # bp
begin
2+2
3+3 # bp
end
function foo(x)
x
x # bp
x
end
""")
close(io)
expr = Base.parse_input_line(String(read(path)), filename = path)
exprs = collect(ExprSplitter(Main, expr))
breakpoint(path, 1)
breakpoint(path, 4)
breakpoint(path, 8)
# breakpoint in top-level line
mod, ex = exprs[1]
frame = Frame(mod, ex)
@test JuliaInterpreter.shouldbreak(frame, frame.pc)
ret = JuliaInterpreter.finish_and_return!(frame, true)
@test ret === 2
# breakpoint in top-level block
mod, ex = exprs[3]
frame = Frame(mod, ex)
@test JuliaInterpreter.shouldbreak(frame, frame.pc)
ret = JuliaInterpreter.finish_and_return!(frame, true)
@test ret === 6
# don't break for bp in function definition
mod, ex = exprs[4]
frame = Frame(mod, ex)
@test JuliaInterpreter.shouldbreak(frame, frame.pc) == false
ret = JuliaInterpreter.finish_and_return!(frame, true)
@test ret isa Function
remove()
end
end
@testset "duplicate slotnames" begin
tmp_dupl() = (1,2,3,4)
ln = @__LINE__
function duplnames(x)
for iter in CartesianIndices(x)
i = iter[1]
c = i
a, b, c, d = tmp_dupl()
end
return x
end
bp = breakpoint(@__FILE__, ln+5, :(i == 1))
c = @code_lowered(duplnames((1,2)))
if length(unique(c.slotnames)) < length(c.slotnames)
f = JuliaInterpreter.enter_call(duplnames, (1,2))
ex = JuliaInterpreter.prepare_slotfunction(f.framecode, :(i==1))
@test ex isa Expr
found = false
for arg in ex.args[end].args
if arg.args[1] === :i
found = true
end
end
@test found
@test last(JuliaInterpreter.debug_command(f, :c)) isa BreakpointRef
end
end
@testset "recursive builtins" begin
g(args...) = args
args = (iterate, g, (1,3))
h() = Core._apply_iterate(iterate, Core._apply_iterate, args)
breakpoint(g)
frame, bp = @interpret h()
var = JuliaInterpreter.locals(leaf(frame))
@test filter(v->v.name === :args, var)[1].value == (1,3)
end
struct Constructor
x::Int
end
Constructor(x::AbstractString, y::Int) = Constructor(x)
@testset "constructors" begin
breakpoint(Constructor, Tuple{String, Int})
frame, bp = @interpret Constructor("foo", 3)
@test bp isa BreakpointRef
@test @interpret Constructor(3) isa Constructor
breakpoint(Constructor)
frame, bp = @interpret Constructor(2)
@test bp isa BreakpointRef
end
@testset "test breaking on a line with no statement" begin
ln = @__LINE__
function f_emptylines()
sin(2.0)
return sin(2.0)
end
bp = breakpoint(@__FILE__, ln + 4)
frame, bpref = @interpret f_emptylines()
@test bpref isa BreakpointRef
@test JuliaInterpreter.whereis(frame) == (@__FILE__, ln + 6)
remove(bp)
# Don't break if the line is outside the function
breakpoint(@__FILE__, ln)
@test (@interpret f_emptylines()) == sin(2.0)
end
@testset "macro expansion breakpoint tests" begin
function f_macro()
sin(2.0)
@info "foo"
sin(2.0)
@info "foo"
return 2
end
frame = JuliaInterpreter.enter_call(f_macro)
file_logging = String(only(methods(var"@info")).file)
line_logging = 0
for entry in frame.framecode.src.linetable
if entry.file === Symbol(file_logging)
line_logging = entry.line
break
end
end
bp_log = breakpoint(file_logging, line_logging)
with_logger(NullLogger()) do
frame, bp = @interpret f_macro()
@test bp isa BreakpointRef
file, ln = JuliaInterpreter.whereis(frame)
@test ln == line_logging
@test basename(file) == basename(file_logging)
bp = JuliaInterpreter.finish_stack!(frame)
@test bp isa BreakpointRef
frame = leaf(frame)
ret = JuliaInterpreter.finish_stack!(frame)
@test ret == 2
end
JuliaInterpreter.remove(bp_log)
# Check that stopping on a line only stops in the correct file
mktemp() do path, io
for _ in 1:line_logging-5
print(io, "\n")
end
print(io,
"""
function f_check(x)
sin(x)
@info "foo"
sin(x)
sin(x)
sin(x)
sin(x)
sin(x)
return x
end
""")
bp_f = breakpoint(path, line_logging)
flush(io)
include(path)
with_logger(NullLogger()) do
frame, bp = @interpret f_check(1)
file, ln = JuliaInterpreter.whereis(frame)
@test file == path # Should not have stopped in logging.jl at line `line_logging`
@test ln == line_logging
remove(bp_f)
@test (@interpret f_check(1)) == 1
breakpoint(f_check, line_logging)
frame, bp = @interpret f_check(1)
file, ln = JuliaInterpreter.whereis(frame)
@test file == path # Should not have stopped in logging.jl at line `line_logging`
@test ln == line_logging
end
end
end
@testset "breakpoint in kwfuncs" begin
fkw(;x=1) = x
breakpoint(fkw)
g() = fkw(; x=1)
frame, bp = @interpret g()
@test isa(frame, Frame) && isa(bp, JuliaInterpreter.BreakpointRef)
fkw2(;x=1) = x
g2() = fkw2(; x=1)
@test @interpret g2() === 1
fkw3(::T; x=1) where {T} = x
breakpoint(fkw3)
g3() = fkw3(7; x=1)
frame, bp = @interpret g3()
@test isa(frame, Frame) && isa(bp, JuliaInterpreter.BreakpointRef)
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 784 | using Test, DeepDiffs
@static if !Base.GIT_VERSION_INFO.tagged_commit && # only run on nightly
!Sys.iswindows() # TODO: Understand why this fails, probably some line endings
@testset "Check builtin.jl consistency" begin
builtins_path = joinpath(@__DIR__, "..", "src", "builtins.jl")
old_builtins = read(builtins_path, String)
new_builtins_dir = mktempdir()
withenv("JULIAINTERPRETER_BUILTINS_DIR" => new_builtins_dir) do
include("../bin/generate_builtins.jl")
end
new_builtins = read(joinpath(new_builtins_dir, "builtins.jl"), String)
consistent = old_builtins == new_builtins
if !consistent
println(deepdiff(old_builtins, new_builtins))
end
@test consistent
end
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 1261 | using JuliaInterpreter
using Test
@testset "core" begin
@test JuliaInterpreter.is_quoted_type(QuoteNode(Int32), :Int32)
@test !JuliaInterpreter.is_quoted_type(QuoteNode(Int32), :Int64)
@test !JuliaInterpreter.is_quoted_type(QuoteNode(Int32(0)), :Int32)
@test !JuliaInterpreter.is_quoted_type(Int32, :Int32)
function buildexpr()
items = [7, 3]
ex = quote
X = $items
for x in X
println(x)
end
end
return ex
end
frame = JuliaInterpreter.enter_call(buildexpr)
lines = JuliaInterpreter.framecode_lines(frame.framecode.src)
# Test that the :copyast ends up on the same line as the println
if isdefined(Base.IRShow, :show_ir_stmt) # only works on Julia 1.6 and higher
@test any(str->occursin(":copyast", str) && occursin("println", str), lines)
end
thunk = Meta.lower(Main, :(return 1+2))
stmt = thunk.args[1].code[end]::Core.ReturnNode # the return
@test stmt.val isa Core.SSAValue
@test string(JuliaInterpreter.parametric_type_to_expr(Base.Iterators.Stateful{String})) ∈
("Base.Iterators.Stateful{String, VS}", "(Base.Iterators).Stateful{String, VS}", "Base.Iterators.Stateful{String, VS, N}")
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 21188 | using CodeTracking, JuliaInterpreter, Test
using JuliaInterpreter: enter_call, enter_call_expr, get_return, @lookup
using Base.Meta: isexpr
include("utils.jl")
const ALL_COMMANDS = (:n, :s, :c, :finish, :nc, :se, :si, :until)
function step_through_command(fr::Frame, cmd::Symbol)
while true
ret = JuliaInterpreter.debug_command(JuliaInterpreter.finish_and_return!, fr, cmd)
ret == nothing && break
fr, pc = ret
end
@test fr.callee === nothing
@test fr.caller === nothing
return get_return(fr)
end
function step_through_frame(frame_creator)
rets = []
for cmd in ALL_COMMANDS
frame = frame_creator()
ret = step_through_command(frame, cmd)
push!(rets, ret)
end
@test all(ret -> ret == rets[1], rets)
return rets[1]
end
step_through(f, args...; kwargs...) = step_through_frame(() -> enter_call(f, args...; kwargs...))
step_through(expr::Expr) = step_through_frame(() -> enter_call_expr(expr))
@generated function generatedfoo(T)
:(return $T)
end
callgenerated() = generatedfoo(1)
@generated function generatedparams(a::Array{T,N}) where {T,N}
:(return ($T,$N))
end
callgeneratedparams() = generatedparams([1 2; 3 4])
macro insert_some_calls()
esc(quote
x = sin(b)
y = asin(x)
z = sin(y)
end)
end
trivial(x) = x
struct B{T} end
# Putting this into a @testset introduces a closure that breaks the kwprep detection
function complicated_keyword_stuff(a, b=-1; x=1, y=2)
a == a
(a, b, :x=>x, :y=>y)
end
function complicated_keyword_stuff_splatargs(args...; x=1, y=2)
args[1] == args[1]
(args..., :x=>x, :y=>y)
end
function complicated_keyword_stuff_splatkws(a, b=-1; kw...)
a == a
(a, b, kw...)
end
function complicated_keyword_stuff_splat2(args...; kw...)
args[1] == args[1]
(args..., kw...)
end
# @testset "Debug" begin
@testset "Basics" begin
frame = enter_call(map, x->2x, 1:10)
@test debug_command(frame, :finish) === nothing
@test frame.caller === frame.callee === nothing
@test get_return(frame) == map(x->2x, 1:10)
for func in (complicated_keyword_stuff, complicated_keyword_stuff_splatargs,
complicated_keyword_stuff_splatkws, complicated_keyword_stuff_splat2)
for (args, kwargs) in (((1,), ()), ((1, 2), (x=7, y=33)))
oframe = frame = enter_call(func, args...; kwargs...)
frame = JuliaInterpreter.maybe_step_through_kwprep!(frame, false)
frame = JuliaInterpreter.maybe_step_through_wrapper!(frame)
@test JuliaInterpreter.hasarg(JuliaInterpreter.isidentical(QuoteNode(==)), frame.framecode.src.code)
f, pc = debug_command(frame, :n)
@test f === frame
@test isa(pc, Int)
@test oframe.callee !== nothing
@test debug_command(frame, :finish) === nothing
@test oframe.caller === oframe.callee === nothing
@test get_return(oframe) == func(args...; kwargs...)
@test @interpret(complicated_keyword_stuff(args...; kwargs...)) == complicated_keyword_stuff(args...; kwargs...)
end
end
let f22() = string(:(a+b))
@test step_through(f22) == "a + b"
end
let f22() = string(QuoteNode(:a))
@test step_through(f22) == ":a"
end
frame = enter_call(trivial, 2)
@test debug_command(frame, :s) === nothing
@test get_return(frame) == 2
@test step_through(trivial, 2) == 2
@test step_through(:($(+)(1,2.5))) == 3.5
@test step_through(:($(sin)(1))) == sin(1)
@test step_through(:($(gcd)(10,20))) == gcd(10, 20)
end
@testset "until" begin
function f_with_lines(s)
sin(2.0)
cos(2.0)
for i in 1:100
s += i
end
sin(2.0)
end
meth_def = @__LINE__() - 8
frame = enter_call(f_with_lines, 0)
@test whereis(frame)[2] == meth_def + 1
debug_command(frame, :until)
@test whereis(frame)[2] == meth_def + 2
debug_command(frame, :until; line=(meth_def + 4))
@test whereis(frame)[2] == meth_def + 4
debug_command(frame, :until; line=(meth_def + 6))
@test whereis(frame)[2] == meth_def + 6
end
@testset "generated" begin
let frame = enter_call_expr(:($(callgenerated)()))
cframe, pc = debug_command(frame, :s)
@test isa(pc, BreakpointRef)
@test JuliaInterpreter.scopeof(cframe).name === :generatedfoo
@test debug_command(cframe, :c) === nothing
@test cframe.callee === nothing
@test get_return(cframe) === Int
end
# This time, step into the generated function itself
let frame = enter_call_expr(:($(callgenerated)()))
cframe, pc = debug_command(frame, :sg)
# Aside: generators can have `Expr(:line, ...)` in their line tables, test that this is OK
lt = JuliaInterpreter.linetable(cframe, 2)
@test isexpr(lt, :line) || isa(lt, Core.LineInfoNode) ||
(isdefined(Base.IRShow, :LineInfoNode) && isa(lt, Base.IRShow.LineInfoNode))
@test isa(pc, BreakpointRef)
@test JuliaInterpreter.scopeof(cframe).name === :generatedfoo
cframe, pc = debug_command(cframe, :finish)
@test JuliaInterpreter.scopeof(cframe).name === :callgenerated
# Now finish the regular function
@test debug_command(cframe, :finish) === nothing
@test cframe.callee === nothing
@test get_return(cframe) === 1
end
# Parametric generated function (see #157)
let frame = fr = JuliaInterpreter.enter_call(callgeneratedparams)
while fr.pc < JuliaInterpreter.nstatements(fr.framecode) - 1
fr, pc = debug_command(fr, :se)
end
fr, pc = debug_command(fr, :sg)
@test JuliaInterpreter.scopeof(fr).name === :generatedparams
fr, pc = debug_command(fr, :finish)
@test debug_command(fr, :finish) === nothing
@test JuliaInterpreter.get_return(fr) == (Int, 2)
end
end
@testset "Optional arguments" begin
function optional(n = sin(1))
x = asin(n)
cos(x)
end
frame = JuliaInterpreter.enter_call_expr(:($(optional)()))
# Step through the wrapper
f = JuliaInterpreter.maybe_step_through_wrapper!(frame)
@test frame !== f
# asin(n)
f, pc = debug_command(f, :n)
# cos(1.0)
f, pc = debug_command(f, :n)
# return
@test debug_command(f, :n) === nothing
end
@testset "Keyword arguments" begin
f(x; b = 1) = x+b
g() = f(1; b = 2)
frame = JuliaInterpreter.enter_call_expr(:($(g)()));
fr, pc = debug_command(frame, :nc)
fr, pc = debug_command(fr, :nc)
fr, pc = debug_command(fr, :nc)
fr, pc = debug_command(fr, :s)
fr, pc = debug_command(fr, :finish)
@test debug_command(fr, :finish) === nothing
@test frame.callee === nothing
@test get_return(frame) == 3
frame = JuliaInterpreter.enter_call(f, 2; b = 4)
fr = JuliaInterpreter.maybe_step_through_wrapper!(frame)
fr, pc = debug_command(fr, :nc)
debug_command(fr, :nc)
@test get_return(frame) == 6
end
@testset "Optional + keyword wrappers" begin
opkw(a, b=1; c=2, d=3) = 1
callopkw1() = opkw(0)
callopkw2() = opkw(0, -1)
callopkw3() = opkw(0; c=-2)
callopkw4() = opkw(0, -1; c=-2)
callopkw5() = opkw(0; c=-2, d=-3)
callopkw6() = opkw(0, -1; c=-2, d=-3)
scopes = Method[]
for f in (callopkw1, callopkw2, callopkw3, callopkw4, callopkw5, callopkw6)
frame = fr = JuliaInterpreter.enter_call(f)
pc = fr.pc
while pc <= JuliaInterpreter.nstatements(fr.framecode) - 2
fr, pc = debug_command(fr, :se)
end
fr, pc = debug_command(frame, :si)
@test stacklength(frame) == 2
frame = fr = JuliaInterpreter.enter_call(f)
pc = fr.pc
while pc <= JuliaInterpreter.nstatements(fr.framecode) - 2
fr, pc = debug_command(fr, :se)
end
fr, pc = debug_command(frame, :s)
@test stacklength(frame) > 2
push!(scopes, JuliaInterpreter.scopeof(fr))
end
@test length(unique(scopes)) == 1 # all get to the body method
end
@testset "Macros" begin
# Work around the fact that we can't detect macro expansions if the macro
# is defined in the same file
include_string(Main, """
function test_macro()
a = sin(5)
b = asin(a)
@insert_some_calls
z
end
""","file.jl")
frame = JuliaInterpreter.enter_call_expr(:($(test_macro)()))
f, pc = debug_command(frame, :n) # a is set
f, pc = debug_command(f, :n) # b is set
f, pc = debug_command(f, :n) # x is set
f, pc = debug_command(f, :n) # y is set
f, pc = debug_command(f, :n) # z is set
@test debug_command(f, :n) === nothing # return
end
@testset "Quoting" begin
# Test that symbols don't get an extra QuoteNode
f_symbol() = :limit => true
frame = JuliaInterpreter.enter_call(f_symbol)
fr, pc = debug_command(frame, :s)
fr, pc = debug_command(fr, :finish)
@test debug_command(fr, :finish) === nothing
@test get_return(frame) == f_symbol()
end
@testset "Varargs" begin
f_va_inner(x) = x + 1
f_va_outer(args...) = f_va_inner(args...)
frame = fr = JuliaInterpreter.enter_call(f_va_outer, 1)
# depending on whether this is in or out of a @testset, the first statement may differ
stmt1 = fr.framecode.src.code[1]
if isexpr(stmt1, :call) && @lookup(frame, stmt1.args[1]) === getfield
fr, pc = debug_command(fr, :se)
end
fr, pc = debug_command(fr, :s)
fr, pc = debug_command(fr, :n)
@test root(fr) !== fr
fr, pc = debug_command(fr, :finish)
@test debug_command(fr, :finish) === nothing
@test get_return(frame) === 2
end
@testset "ASTI#17" begin
function (::B)(y)
x = 42*y
return x + y
end
B_inst = B{Int}()
step_through(B_inst, 10) == B_inst(10)
end
@testset "Exceptions" begin
# Don't break on caught exceptions
err_caught = Any[nothing]
function f_exc_outer()
try
f_exc_inner()
catch err;
err_caught[1] = err
end
x = 1 + 1
return x
end
f_exc_inner() = error()
fr = JuliaInterpreter.enter_call(f_exc_outer)
fr, pc = debug_command(fr, :s)
fr, pc = debug_command(fr, :n)
fr, pc = debug_command(fr, :n)
debug_command(fr, :finish)
@test get_return(fr) == 2
@test first(err_caught) isa ErrorException
@test stacklength(fr) == 1
err_caught = Any[nothing]
fr = JuliaInterpreter.enter_call(f_exc_outer)
fr, pc = debug_command(fr, :s)
debug_command(fr, :c)
@test get_return(root(fr)) == 2
@test first(err_caught) isa ErrorException
@test stacklength(root(fr)) == 1
# Rethrow on uncaught exceptions
f_outer() = g_inner()
g_inner() = error()
fr = JuliaInterpreter.enter_call(f_outer)
@test_throws ErrorException debug_command(fr, :finish)
@test stacklength(fr) == 3
# Break on error
try
break_on(:error)
fr = JuliaInterpreter.enter_call(f_outer)
fr, pc = debug_command(JuliaInterpreter.finish_and_return!, fr, :finish)
@test fr.framecode.scope.name === :error
fundef() = undef_func()
frame = JuliaInterpreter.enter_call(fundef)
fr, pc = debug_command(frame, :s)
@test isa(pc, BreakpointRef)
@test pc.err isa UndefVarError
finally
break_off(:error)
end
end
@testset "breakpoints" begin
# In source breakpoints
function f_bp(x)
#=1=# i = 1
#=2=# @label foo
#=3=# @bp
#=4=# repr("foo")
#=5=# i += 1
#=6=# i > 3 && return x
#=7=# @goto foo
end
ln = @__LINE__
method_start = ln - 9
fr = enter_call(f_bp, 2)
@test JuliaInterpreter.linenumber(fr) == method_start + 1
fr, pc = JuliaInterpreter.debug_command(fr, :c)
# Hit the breakpoint x1
@test JuliaInterpreter.linenumber(fr) == method_start + 3
@test pc isa BreakpointRef
fr, pc = JuliaInterpreter.debug_command(fr, :n)
@test JuliaInterpreter.linenumber(fr) == method_start + 4
fr, pc = JuliaInterpreter.debug_command(fr, :c)
# Hit the breakpoint again x2
@test pc isa BreakpointRef
@test JuliaInterpreter.linenumber(fr) == method_start + 3
fr, pc = JuliaInterpreter.debug_command(fr, :c)
# Hit the breakpoint for the last time x3
@test pc isa BreakpointRef
@test JuliaInterpreter.linenumber(fr) == method_start + 3
JuliaInterpreter.debug_command(fr, :c)
@test get_return(fr) == 2
end
f_inv(x::Real) = x^2;
f_inv(x::Integer) = 1 + invoke(f_inv, Tuple{Real}, x)
@testset "invoke" begin
fr = JuliaInterpreter.enter_call(f_inv, 2)
fr, pc = JuliaInterpreter.debug_command(fr, :s) # apply_type
frame, pc = JuliaInterpreter.debug_command(fr, :s) # step into invoke
@test frame.framecode.scope.sig == Tuple{typeof(f_inv),Real}
JuliaInterpreter.debug_command(frame, :c)
frame = root(frame)
@test get_return(frame) == f_inv(2)
end
f_inv_latest(x::Real) = 1 + (@static isdefined(Core, :_call_latest) ? Core._call_latest(f_inv, x) : Core._apply_latest(f_inv, x))
@testset "invokelatest" begin
fr = JuliaInterpreter.enter_call(f_inv_latest, 2.0)
fr, pc = JuliaInterpreter.debug_command(fr, :nc)
frame, pc = JuliaInterpreter.debug_command(fr, :s) # step into invokelatest
@test frame.framecode.scope.sig == Tuple{typeof(f_inv),Real}
JuliaInterpreter.debug_command(frame, :c)
frame = root(frame)
@test get_return(frame) == f_inv_latest(2.0)
end
@testset "Issue #178" begin
remove()
a = [1, 2, 3, 4]
@breakpoint length(LinearIndices(a))
frame, bp = @interpret sum(a)
@test debug_command(frame, :c) === nothing
@test get_return(frame) == sum(a)
end
@testset "Stepping over kwfunc preparation" begin
stepkw! = JuliaInterpreter.maybe_step_through_kwprep! # for brevity
a = [4, 1, 3, 2]
reversesort(x) = sort(x; rev=true)
frame = JuliaInterpreter.enter_call(reversesort, a)
frame = stepkw!(frame)
@test frame.pc == JuliaInterpreter.nstatements(frame.framecode) - 1
scopedreversesort(x) = Base.sort(x, rev=true) # https://github.com/JuliaDebug/Debugger.jl/issues/141
frame = JuliaInterpreter.enter_call(scopedreversesort, a)
frame = stepkw!(frame)
@test frame.pc == JuliaInterpreter.nstatements(frame.framecode) - 1
frame = JuliaInterpreter.enter_call(sort, a)
frame = stepkw!(frame)
@static if VERSION ≥ v"1.7"
# TODO fix this broken test (@aviatesk)
@test frame.pc == JuliaInterpreter.nstatements(frame.framecode) - 1 broken=VERSION≥v"1.11-"
else
@test frame.pc == JuliaInterpreter.nstatements(frame.framecode) - 1
end
frame, pc = debug_command(frame, :s)
frame, pc = debug_command(frame, :se) # get past copymutable
frame = stepkw!(frame)
@test frame.pc > 4
frame = JuliaInterpreter.enter_call(sort, a; rev=true)
frame, pc = debug_command(frame, :se)
frame, pc = debug_command(frame, :s)
frame, pc = debug_command(frame, :se) # get past copymutable
frame = stepkw!(frame)
@test frame.pc == JuliaInterpreter.nstatements(frame.framecode) - 1
end
function f(x, y)
sin(2.0)
g(x; y = 3)
end
g(x; y) = x + y
@testset "interaction of :n with kw functions" begin
frame = JuliaInterpreter.enter_call(f, 2, 3) # at sin
frame, pc = debug_command(frame, :n)
# Check that we are at the kw call to g
@test Core.kwfunc(g) == JuliaInterpreter.@lookup frame JuliaInterpreter.pc_expr(frame).args[1]
# Step into the inner g
frame, pc = debug_command(frame, :s)
# Finish the frame and make sure we step out of the wrapper
frame, pc = debug_command(frame, :finish)
@test frame.framecode.scope == @which f(2, 3)
end
h_1(x, y) = h_2(x, y)
h_2(x, y) = h_3(x; y=y)
h_3(x; y = 2) = x + y
@testset "stepping through kwprep after stepping through wrapper" begin
frame = JuliaInterpreter.enter_call(h_1, 2, 1)
frame, pc = debug_command(frame, :s)
# Should have skipped the kwprep in h_2 and be at call to kwfunc h_3
@test Core.kwfunc(h_3) == JuliaInterpreter.@lookup frame JuliaInterpreter.pc_expr(frame).args[1]
end
@testset "si should not step through wrappers or kwprep" begin
frame = JuliaInterpreter.enter_call(h_1, 2, 1)
frame, pc = debug_command(frame, :si)
@test frame.pc == (VERSION >= v"1.11-" ? 2 : 1)
end
@testset "breakpoints hit during wrapper step through" begin
f(x = g()) = x
g() = 5
@breakpoint g()
frame = JuliaInterpreter.enter_call(f)
JuliaInterpreter.maybe_step_through_wrapper!(frame)
@test leaf(frame).framecode.scope == @which g()
end
@testset "preservation of stack when throwing to toplevel" begin
f() = "αβ"[2]
frame1 = JuliaInterpreter.enter_call(f);
err = try debug_command(frame1, :c)
catch err
err
end
try
break_on(:error)
frame2, pc = @interpret f()
@test leaf(frame2).framecode.scope === leaf(frame1).framecode.scope
finally
break_off(:error)
end
end
@testset "breakpoint in next line" begin
function f(a, b)
a == 0 && return abs(b)
@bp
return b
end
frame = JuliaInterpreter.enter_call(f, 5, 10)
frame, pc = JuliaInterpreter.debug_command(frame, :n)
@test pc isa BreakpointRef
end
@testset "kw wrapper heuristic #435" begin
foo() = UInt8('\t')
frame = JuliaInterpreter.enter_call(foo)
frame, pc = debug_command(frame, :s)
@test pc isa BreakpointRef
end
# end
module InterpretedModuleTest
using ..JuliaInterpreter
function f(x)
x
@bp
x
end
end
@testset "interpreted methods" begin
push!(JuliaInterpreter.compiled_modules, InterpretedModuleTest)
frame = JuliaInterpreter.enter_call(5) do x
InterpretedModuleTest.f(5)
end
frame, pc = JuliaInterpreter.debug_command(frame, :n)
@test !(pc isa BreakpointRef)
push!(JuliaInterpreter.interpreted_methods, first(methods(InterpretedModuleTest.f)))
frame = JuliaInterpreter.enter_call(5) do x
InterpretedModuleTest.f(5)
end
frame, pc = JuliaInterpreter.debug_command(frame, :n)
@test pc isa BreakpointRef
end
@testset "step last call on line" begin
g(x) = x
f(x) = x
h(x) = x
function z(x)
a = h(f(x) + g(x) - 3)
x = 3
b = h(g(x))
end
frame = JuliaInterpreter.enter_call(z, 5)
frame, pc = JuliaInterpreter.debug_command(frame, :sl)
@test JuliaInterpreter.scopeof(frame).name === :h
frame, pc = JuliaInterpreter.debug_command(frame, :finish)
frame, pc = JuliaInterpreter.debug_command(frame, :sl)
@test JuliaInterpreter.scopeof(frame).name === :h
end
@testset "step until return" begin
function f(x)
if x == 1
return 2
end
return 3
end
frame = JuliaInterpreter.enter_call(f, 1)
frame, _ = JuliaInterpreter.debug_command(frame, :sr)
@test JuliaInterpreter.get_return(frame) == f(1)
frame = JuliaInterpreter.enter_call(f, 4)
frame, _ = JuliaInterpreter.debug_command(frame, :sr)
@test JuliaInterpreter.get_return(frame) == f(4)
function g()
y = f(1) + f(2)
return y
end
frame = JuliaInterpreter.enter_call(g)
frame, _ = JuliaInterpreter.debug_command(frame, :sr)
@test JuliaInterpreter.get_return(frame) == g()
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 66 | # Don't change the value below, it's used in an `include` test
55
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 3837 | using JuliaInterpreter: eval_code
# Simple evaling of function argument
function evalfoo1(x,y)
x+y
end
frame = JuliaInterpreter.enter_call(evalfoo1, 1, 2)
@test eval_code(frame, "x") == 1
@test eval_code(frame, "y") == 2
# Evaling with sparams
evalsparams(x::T) where T = x
frame = JuliaInterpreter.enter_call(evalsparams, 1)
@test eval_code(frame, "x") == 1
eval_code(frame, "x = 3")
@test eval_code(frame, "x") == 3
@test eval_code(frame, "T") == Int
eval_code(frame, "T = Float32")
@test eval_code(frame, "T") == Float32
# Evaling with keywords
evalkw(x; bar=true) = x
frame = JuliaInterpreter.enter_call(evalkw, 2)
frame = JuliaInterpreter.maybe_step_through_wrapper!(frame)
@test eval_code(frame, "x") == 2
@test eval_code(frame, "bar") == true
eval_code(frame, "bar = false")
@test eval_code(frame, "bar") == false
# Evaling with symbols
evalsym() = (x = :foo)
frame = JuliaInterpreter.enter_call(evalsym)
# Step until the local actually end up getting defined
JuliaInterpreter.step_expr!(frame)
JuliaInterpreter.step_expr!(frame)
@test eval_code(frame, "x") === :foo
# Evaling multiple statements (https://github.com/JuliaDebug/Debugger.jl/issues/188)
frame = JuliaInterpreter.enter_call(evalfoo1, 1, 2)
@test eval_code(frame, "x = 1; y = 2") == 2
@test eval_code(frame, "x") == 1
@test eval_code(frame, "y") == 2
# https://github.com/JuliaDebug/Debugger.jl/issues/177
function f()
x = 1
f = ()->(x = 2)
f()
x
end
frame = JuliaInterpreter.enter_call(f)
JuliaInterpreter.step_expr!(frame)
JuliaInterpreter.step_expr!(frame)
@static if VERSION >= v"1.11-"
JuliaInterpreter.step_expr!(frame)
end
@test eval_code(frame, "x") == 1
eval_code(frame, "x = 3")
@test eval_code(frame, "x") == 3
JuliaInterpreter.finish!(frame)
@test JuliaInterpreter.get_return(frame) == 2
function debugfun(non_accessible_variable)
garbage = ones(10)
map(1:10) do i
1+1
a = 5
@bp
garbage[i] + non_accessible_variable[i]
non_accessible_variable = 2
end
end
fr = JuliaInterpreter.enter_call(debugfun, [1,2])
fr, bp = debug_command(fr, :c)
@test eval_code(fr, "non_accessible_variable") == [1,2]
@test eval_code(fr, "garbage") == ones(10)
eval_code(fr, "non_accessible_variable = 5.0")
@test eval_code(fr, "non_accessible_variable") == 5.0
# Evaluating SSAValues
f(x) = x^2
frame = JuliaInterpreter.enter_call(f, 5)
id = let
pc, n = frame.pc, length(frame.framecode.src.code)
while pc < n - 1
pc = JuliaInterpreter.step_expr!(frame)
end
# Extract the SSAValue that corresponds to the power
stmt = frame.framecode.src.code[pc]::Expr # the `literal_pow` call
stmt.args[end].id
end
# This could change with changes to Julia lowering
@test eval_code(frame, "var\"%$(id)\"") == Val(2)
@test eval_code(frame, "var\"@_1\"") == f
function fun(;output=:sym)
x = 5
y = 3
end
fr = JuliaInterpreter.enter_call(fun)
fr = JuliaInterpreter.maybe_step_through_wrapper!(fr)
JuliaInterpreter.step_expr!(fr)
@test eval_code(fr, "x") == 5
@test eval_code(fr, "output") === :sym
eval_code(fr, "output = :foo")
@test eval_code(fr, "output") === :foo
let f() = GlobalRef(Main, :doesnotexist)
frame = JuliaInterpreter.enter_call(f)
retidx = findfirst(frame.framecode.src.code) do x
x isa Core.ReturnNode && x.val isa JuliaInterpreter.SSAValue
end
ssaidx = ((frame.framecode.src.code[retidx]::Core.ReturnNode).val::JuliaInterpreter.SSAValue).id
for _ = 1:ssaidx; JuliaInterpreter.step_expr!(frame); end
@test eval_code(frame, "var\"%$ssaidx\"") == GlobalRef(Main, :doesnotexist)
end
# Don't error on empty input string
function empty_code(x)
x+x
end
frame = JuliaInterpreter.enter_call(empty_code, 1)
@test eval_code(frame, "") === nothing
@test eval_code(frame, " ") === nothing
@test eval_code(frame, "\n") === nothing
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 30896 | using JuliaInterpreter
using Test, InteractiveUtils, CodeTracking
using Mmap
using LinearAlgebra
if !isdefined(@__MODULE__, :runframe)
include("utils.jl")
end
module Isolated end
function summer(A)
s = zero(eltype(A))
for a in A
s += a
end
return s
end
A = [0.12, -.99]
frame = JuliaInterpreter.enter_call(summer, A)
frame2 = JuliaInterpreter.enter_call(summer, A)
@test summer(A) == something(runframe(frame)) == something(runstack(frame2))
A = rand(1000)
@test @interpret(sum(A)) ≈ sum(A) # note: the compiler can leave things in registers to increase accuracy, doesn't happen with interpreted
fapply() = (Core.apply_type)(Base.NamedTuple, (), Tuple{})
@test @interpret(fapply()) == fapply()
function fbc()
bc = Broadcast.broadcasted(CartesianIndex, 6, [1, 2, 3])
copy(bc)
end
@test @interpret(fbc()) == fbc()
@test @interpret(repr("hi")) == repr("hi") # this tests kwargs and @generated functions
fkw(x::Int8; y=0, z="hello") = y
@test @interpret(fkw(Int8(1); y=22, z="world")) == fkw(Int8(1); y=22, z="world")
# generators that throw before returning the body expression
@test_throws ArgumentError("input tuple of length 3, requested 2") @interpret Base.fill_to_length((1,2,3), -1, Val(2))
# Throwing exceptions across frames
function f_exc_inner()
error("inner")
end
f_exc_inner2() = f_exc_inner()
const caught = Ref(false)
function f_exc_outer1()
try
f_exc_inner()
catch err # with an explicit err capture
caught[] = true
rethrow(err)
end
end
function f_exc_outer2()
try
f_exc_inner()
catch # implicit err capture
caught[] = true
rethrow()
end
end
function f_exc_outer3(f)
try
f()
catch err
return err
end
end
@test !caught[]
ret = @interpret f_exc_outer3(f_exc_outer1)
@test ret == ErrorException("inner")
@test caught[]
caught[] = false
ret = @interpret f_exc_outer3(f_exc_outer2)
@test ret == ErrorException("inner")
@test caught[]
caught[] = false
ret = @interpret f_exc_outer3(f_exc_inner2)
@test ret == ErrorException("inner")
@test !caught[]
stc = try f_exc_outer1() catch
stacktrace(catch_backtrace())
end
sti = try @interpret(f_exc_outer1()) catch
stacktrace(catch_backtrace())
end
@test_broken stc == sti
# issue #3
@test @interpret(joinpath("/home/julia/base", "sysimg.jl")) == joinpath("/home/julia/base", "sysimg.jl")
@test @interpret(10.0^4) == 10.0^4
# issue #6
@test @interpret(Array.body.body.name) === Array.body.body.name
if Vararg isa UnionAll
@test @interpret(Vararg.body.body.name) === Vararg.body.body.name
else
@test @interpret(Vararg{Int}.T) === Vararg{Int}.T
@test @interpret(Vararg{Any,3}.N) === Vararg{Any,3}.N
end
@test !JuliaInterpreter.is_vararg_type(Union{})
if Vararg isa UnionAll
frame = Frame(Main, :(Vararg.body.body.name))
@test JuliaInterpreter.finish_and_return!(frame, true) === Vararg.body.body.name
else
frame = Frame(Main, :(Vararg{Int}.T))
@test JuliaInterpreter.finish_and_return!(frame, true) === Vararg{Int}.T
frame = Frame(Main, :(Vararg{Any,3}.N))
@test JuliaInterpreter.finish_and_return!(frame, true) === Vararg{Any,3}.N
end
frame = Frame(Base, :(Union{AbstractChar,Tuple{Vararg{AbstractChar}},AbstractVector{<:AbstractChar},Set{<:AbstractChar}}))
@test JuliaInterpreter.finish_and_return!(frame, true) isa Union
# issue #8
ex = quote
if sizeof(JLOptions) === ccall(:jl_sizeof_jl_options, Int, ())
else
ccall(:jl_throw, Cvoid, (Any,), "Option structure mismatch")
end
end
frame = Frame(Base, ex)
JuliaInterpreter.finish_and_return!(frame, true)
# ccall with two Symbols
ex = quote
@testset "Some tests" begin
@test 2 > 1
end
end
frame = Frame(Main, ex)
JuliaInterpreter.finish_and_return!(frame, true)
@test @interpret Base.Math.DoubleFloat64(-0.5707963267948967, 4.9789962508669555e-17).hi ≈ -0.5707963267948967
# ccall with cfunction
fcfun(x::Int, y::Int) = 1
ex = quote # in lowered code, cf is a Symbol
cf = @eval @cfunction(fcfun, Int, (Int, Int))
ccall(cf, Int, (Int, Int), 1, 2)
end
frame = Frame(Main, ex)
@test JuliaInterpreter.finish_and_return!(frame, true) == 1
ex = quote
let # in lowered code, cf is a SlotNumber
cf = @eval @cfunction(fcfun, Int, (Int, Int))
ccall(cf, Int, (Int, Int), 1, 2)
end
end
frame = Frame(Main, ex)
@test JuliaInterpreter.finish_and_return!(frame, true) == 1
function cfcfun()
cf = @cfunction(fcfun, Int, (Int, Int))
ccall(cf, Int, (Int, Int), 1, 2)
end
@test @interpret(cfcfun()) == 1
# From Julia's test/ambiguous.jl. This tests whether we renumber :enter statements correctly.
ambig(x, y) = 1
ambig(x::Integer, y) = 2
ambig(x, y::Integer) = 3
ambig(x::Int, y::Int) = 4
ambig(x::Number, y) = 5
ex = quote
let
cf = @eval @cfunction(ambig, Int, (UInt8, Int))
@test_throws(MethodError, ccall(cf, Int, (UInt8, Int), 1, 2))
end
end
frame = Frame(Main, ex)
JuliaInterpreter.finish_and_return!(frame, true)
# Core.Compiler
ex = quote
length(code_typed(fcfun, (Int, Int)))
end
frame = Frame(Main, ex)
@test JuliaInterpreter.finish_and_return!(frame, true) == 1
# copyast
ex = quote
struct CodegenParams
cached::Cint
track_allocations::Cint
code_coverage::Cint
static_alloc::Cint
prefer_specsig::Cint
module_setup::Any
module_activation::Any
raise_exception::Any
emit_function::Any
emitted_function::Any
CodegenParams(;cached::Bool=true,
track_allocations::Bool=true, code_coverage::Bool=true,
static_alloc::Bool=true, prefer_specsig::Bool=false,
module_setup=nothing, module_activation=nothing, raise_exception=nothing,
emit_function=nothing, emitted_function=nothing) =
new(Cint(cached),
Cint(track_allocations), Cint(code_coverage),
Cint(static_alloc), Cint(prefer_specsig),
module_setup, module_activation, raise_exception,
emit_function, emitted_function)
end
end
frame = Frame(Isolated, ex)
JuliaInterpreter.finish_and_return!(frame, true)
@test Isolated.CodegenParams(cached=false).cached === Cint(false)
# cglobal
val = @interpret(BigInt())
@test isa(val, BigInt) && val == 0
@test isa(@interpret(Base.GMP.version()), VersionNumber)
# Issue #455
using PyCall
let np = pyimport("numpy")
@test @interpret(PyCall.pystring_query(np.zeros)) === Union{}
end
# Issue #354
using HTTP
headers = Dict("User-Agent" => "Debugger.jl")
@test @interpret(HTTP.request("GET", "https://httpbingo.julialang.org", headers)) isa HTTP.Messages.Response
# "correct" line numbers
defline = @__LINE__() + 1
function f(x)
x = 2x
# comment
# comment
x = 2x
# comment
return x*x
end
frame = JuliaInterpreter.enter_call(f, 3)
@test whereis(frame, 1)[2] == defline + 1
@test whereis(frame, (length(frame.framecode.src.code) + 1) ÷ 2)[2] == defline + 4
@test whereis(frame, length(frame.framecode.src.code) - 1)[2] == defline + 6
m = which(iterate, Tuple{Dict}) # this method has `nothing` as its first statement and codeloc == 0
framecode = JuliaInterpreter.get_framecode(m)
@test JuliaInterpreter.linenumber(framecode, 1) == m.line + CodeTracking.line_is_decl
# issue #28
let a = ['0'], b = ['a']
@test @interpret(vcat(a, b)) == vcat(a, b)
end
# issue #51
if isdefined(Core.Compiler, :SNCA)
ci = @code_lowered gcd(10, 20)
cfg = Core.Compiler.compute_basic_blocks(ci.code)
@test isa(@interpret(Core.Compiler.SNCA(cfg)), Vector{Int})
end
# llvmcall
function add1234(x::Tuple{Int32,Int32,Int32,Int32})
Base.llvmcall("""%3 = extractvalue [4 x i32] %0, 0
%4 = extractvalue [4 x i32] %0, 1
%5 = extractvalue [4 x i32] %0, 2
%6 = extractvalue [4 x i32] %0, 3
%7 = extractvalue [4 x i32] %1, 0
%8 = extractvalue [4 x i32] %1, 1
%9 = extractvalue [4 x i32] %1, 2
%10 = extractvalue [4 x i32] %1, 3
%11 = add i32 %3, %7
%12 = add i32 %4, %8
%13 = add i32 %5, %9
%14 = add i32 %6, %10
%15 = insertvalue [4 x i32] undef, i32 %11, 0
%16 = insertvalue [4 x i32] %15, i32 %12, 1
%17 = insertvalue [4 x i32] %16, i32 %13, 2
%18 = insertvalue [4 x i32] %17, i32 %14, 3
ret [4 x i32] %18""",Tuple{Int32,Int32,Int32,Int32},
Tuple{Tuple{Int32,Int32,Int32,Int32},Tuple{Int32,Int32,Int32,Int32}},
(Int32(1),Int32(2),Int32(3),Int32(4)),
x)
end
@test @interpret(add1234(map(Int32,(2,3,4,5)))) === map(Int32,(3,5,7,9))
# issue #74
let A = [1]
wkd = WeakKeyDict()
@interpret setindex!(wkd, 2, A)
@test wkd[A] == 2
end
# issue #76
let TT = Union{UInt8, Int8}
a = TT[0x0, 0x1]
pa = Ptr{UInt8}(pointer(a))
GC.@preserve a begin
@interpret unsafe_store!(pa, 0x2, 2)
end
@test a == TT[0x0, 0x2]
end
# issue #92
let x = Core.SlotNumber(1)
f(x) = objectid(x)
@test isa(@interpret(f(x)), UInt)
end
# issue #98
x98 = 5
function f98()
global x98
x98 = 7
return nothing
end
@interpret f98()
@test x98 == 7
# issue #106
function f106()
n = tempname()
w = open(n, "a")
write(w, "A")
flush(w)
return true
end
@test @interpret(f106()) == 1
f106b() = rand()
f106c() = disable_sigint(f106b)
function f106d()
disable_sigint() do
reenable_sigint(f106b)
end
end
@interpret f106c()
@interpret f106d()
# issue #113
f113(;x) = x
@test @interpret(f113(;x=[1,2,3])) == f113(;x=[1,2,3])
# Some expressions can appear nontrivial but lower to nothing
# @test isa(Frame(Main, :(@static if ccall(:jl_get_UNAME, Any, ()) === :NoOS 1+1 end)), Nothing)
# @test isa(Frame(Main, :(Base.BaseDocs.@kw_str "using")), Nothing)
@testset "locals" begin
f_locals(x::Int64, y::T, z::Vararg{Symbol}) where {T} = x
frame = JuliaInterpreter.enter_call(f_locals, Int64(1), 2.0, :a, :b)
locals = JuliaInterpreter.locals(frame)
@test JuliaInterpreter.Variable(Int64(1), :x, false) in locals
@test JuliaInterpreter.Variable(2.0, :y, false) in locals
@test JuliaInterpreter.Variable((:a, :b), :z, false) in locals
@test JuliaInterpreter.Variable(Float64, :T, true) in locals
function f_multi(x)
c = x
x = 2
x = 3
x = 4
return x
end
frame = JuliaInterpreter.enter_call(f_multi, 1)
nlocals = length(frame.framedata.locals)
@test_throws UndefVarError JuliaInterpreter.lookup_var(frame, JuliaInterpreter.SlotNumber(nlocals))
stack = [frame]
locals = JuliaInterpreter.locals(frame)
@test length(locals) == 2
@test JuliaInterpreter.Variable(1, :x, false) in locals
JuliaInterpreter.step_expr!(stack, frame)
JuliaInterpreter.step_expr!(stack, frame)
@static if VERSION >= v"1.11-"
locals = JuliaInterpreter.locals(frame)
@test length(locals) == 2
JuliaInterpreter.step_expr!(stack, frame)
end
locals = JuliaInterpreter.locals(frame)
@test length(locals) == 3
@test JuliaInterpreter.Variable(1, :c, false) in locals
JuliaInterpreter.step_expr!(stack, frame)
locals = JuliaInterpreter.locals(frame)
@test length(locals) == 3
@test JuliaInterpreter.Variable(2, :x, false) in locals
JuliaInterpreter.step_expr!(stack, frame)
locals = JuliaInterpreter.locals(frame)
@test length(locals) == 3
@test JuliaInterpreter.Variable(3, :x, false) in locals
# Issue #404
function aaa(F::Array{T,1}, Z::Array{T,1}) where {T}
M = length(Z)
J = [1:M;]
z = T[]
f = T[]
w = T[]
A = rand(10, 10)
G = svd(A[J, :])
w = G.V[:, m]
r = zz -> rhandle(zz, z, f, w)
end
function rhandle(zz, z, f, w)
nothing
end
fr = JuliaInterpreter.enter_call(aaa, rand(5), rand(5))
fr, bp = JuliaInterpreter.debug_command(fr, :n)
locs = JuliaInterpreter.locals(fr)
@test !any(x -> x.name === :w, locs)
end
@testset "getfield replacements" begin
f_gf(x) = false ? some_undef_var_zzzzzzz : x
@test @interpret f_gf(2) == 2
function g_gf()
eval(:(z = 2))
return z
end
@test @interpret g_gf() == 2
global q_gf = 0
function h_gf()
eval(:(q_gf = 2))
return q_gf
end
@test @interpret h_gf() == 2
# https://github.com/JuliaDebug/JuliaInterpreter.jl/issues/267
function test_never_different(x)
if x < 5
for g in never_defined
print(g)
end
end
end
@test @interpret(test_never_different(10)) === nothing
end
# https://github.com/JuliaDebug/JuliaInterpreter.jl/issues/130
@testset "vararg handling" begin
method_c1(x::Float64, s::AbstractString...) = true
buf = IOBuffer()
me = Base.MethodError(method_c1,(1, 1, ""))
@test (@interpret Base.show_method_candidates(buf, me)) == nothing
varargidentity(x) = x
x = Union{Array{UInt8,N},Array{Int8,N}} where N
@test isa(JuliaInterpreter.prepare_call(varargidentity, [varargidentity, x])[1], JuliaInterpreter.FrameCode)
end
# https://github.com/JuliaDebug/JuliaInterpreter.jl/issues/141
@test @interpret get(ENV, "THIS_IS_NOT_DEFINED_1234", "24") == "24"
# Test return value of whereis
fnone() = nothing
fr = JuliaInterpreter.enter_call(fnone)
file, line = JuliaInterpreter.whereis(fr)
@test file == @__FILE__
@test line == (@__LINE__() - 4)
# Test path to files in stdlib
fr = JuliaInterpreter.enter_call(Test.eval, 1)
file, line = JuliaInterpreter.whereis(fr)
@test isfile(file)
@static if VERSION < v"1.12.0-DEV.173"
@test isfile(JuliaInterpreter.getfile(fr.framecode.src.linetable[1]))
end
@static if VERSION < v"1.9.0-DEV.846" # https://github.com/JuliaLang/julia/pull/45069
@test occursin(Sys.STDLIB, repr(fr))
else
@test occursin(contractuser(Sys.STDLIB), repr(fr))
end
# Test undef sparam (https://github.com/JuliaDebug/JuliaInterpreter.jl/issues/165)
function foo(x::T) where {T <: AbstractString, S <: AbstractString}
return S
end
e = try
@interpret foo("")
catch err
err
end
@test e isa UndefVarError
@test e.var === :S
# https://github.com/JuliaDebug/JuliaInterpreter.jl/issues/200
locs = JuliaInterpreter.locals(JuliaInterpreter.enter_call(foo, ""))
@test length(locs) == 3 # #self# + 2 variables
@test JuliaInterpreter.Variable("", :x, false) in locs
@test JuliaInterpreter.Variable(String, :T, true) in locs
# Test interpreting subtypes finishes in a reasonable time
@test @interpret subtypes(Integer) == subtypes(Integer)
@test @interpret subtypes(Main, Integer) == subtypes(Main, Integer)
@test (@elapsed @interpret subtypes(Integer)) < 30
@test (@elapsed @interpret subtypes(Main, Integer)) < 30
# Test showing stacktraces from frames
g_1(x) = g_2(x)
g_2(x) = g_3(x)
g_3(x) = error("foo")
line_g = @__LINE__
if isdefined(Base, :replaceuserpath)
_contractuser = Base.replaceuserpath
else
_contractuser = Base.contractuser
end
try
break_on(:error)
local frame, bp = @interpret g_1(2.0)
stacktrace_lines = split(sprint(Base.display_error, bp.err, leaf(frame)), '\n')
@test occursin(string("ERROR: ", sprint(showerror, ErrorException("foo"))), stacktrace_lines[1])
if isdefined(Base, :print_stackframe)
@test occursin("[1] error(s::String)", stacktrace_lines[3])
@test occursin("[2] g_3(x::Float64)", stacktrace_lines[5])
thefile = _contractuser(@__FILE__)
@test occursin("$thefile:$(line_g - 1)", stacktrace_lines[6])
@test occursin("[3] g_2(x::Float64)", stacktrace_lines[7])
@test occursin("$thefile:$(line_g - 2)", stacktrace_lines[8])
@test occursin("[4] g_1(x::Float64)", stacktrace_lines[9])
@test occursin("$thefile:$(line_g - 3)", stacktrace_lines[10])
else
@test occursin("[1] error(::String) at error.jl:", stacktrace_lines[3])
@test occursin("[2] g_3(::Float64) at $(@__FILE__):$(line_g - 1)", stacktrace_lines[4])
@test occursin("[3] g_2(::Float64) at $(@__FILE__):$(line_g - 2)", stacktrace_lines[5])
@test occursin("[4] g_1(::Float64) at $(@__FILE__):$(line_g - 3)", stacktrace_lines[6])
end
finally
break_off(:error)
end
try
break_on(:error)
exs = collect(ExprSplitter(Main, quote
g_1(2.0)
end))
line2_g = @__LINE__
local frame = Frame(exs[1]...)
frame, bp = JuliaInterpreter.debug_command(frame, :c, true)
stacktrace_lines = split(sprint(Base.display_error, bp.err, leaf(frame)), '\n')
@test occursin(string("ERROR: ", sprint(showerror, ErrorException("foo"))), stacktrace_lines[1])
if isdefined(Base, :print_stackframe)
@test occursin("[1] error(s::String)", stacktrace_lines[3])
thefile = _contractuser(@__FILE__)
@test occursin("[2] g_3(x::Float64)", stacktrace_lines[5])
@test occursin("$thefile:$(line_g - 1)", stacktrace_lines[6])
@test occursin("[3] g_2(x::Float64)", stacktrace_lines[7])
@test occursin("$thefile:$(line_g - 2)", stacktrace_lines[8])
@test occursin("[4] g_1(x::Float64)", stacktrace_lines[9])
@test occursin("$thefile:$(line_g - 3)", stacktrace_lines[10])
@test occursin("[5] top-level scope", stacktrace_lines[11])
@test occursin("$thefile:$(line2_g - 2)", stacktrace_lines[12])
else
@test occursin("[1] error(::String) at error.jl:", stacktrace_lines[3])
@test occursin("[2] g_3(::Float64) at $(@__FILE__):$(line_g - 1)", stacktrace_lines[4])
@test occursin("[3] g_2(::Float64) at $(@__FILE__):$(line_g - 2)", stacktrace_lines[5])
@test occursin("[4] g_1(::Float64) at $(@__FILE__):$(line_g - 3)", stacktrace_lines[6])
@test occursin("[5] top-level scope at $(@__FILE__):$(line2_g - 2)", stacktrace_lines[7])
end
finally
break_off(:error)
end
f_562(x::Union{Vector{T}, Nothing}) where {T} = x + 1
try
break_on(:error)
local frame, bp = @interpret f_562(nothing)
stacktrace_lines = split(sprint(Base.display_error, bp.err, leaf(frame)), '\n')
@test stacktrace_lines[1] == "ERROR: MethodError: no method matching +(::Nothing, ::$Int)"
finally
break_off(:error)
end
# https://github.com/JuliaDebug/JuliaInterpreter.jl/issues/154
q = QuoteNode([1])
@test @interpret deepcopy(q) == q
# Check #args for builtins (#217)
f217() = <:(Float64, Float32, Float16)
@test_throws ArgumentError @interpret(f217())
# issue #220
function hash220(x::Tuple{Ptr{UInt8},Int}, h::UInt)
h += Base.memhash_seed
ccall(Base.memhash, UInt, (Ptr{UInt8}, Csize_t, UInt32), x[1], x[2], h % UInt32) + h
end
@test @interpret(hash220((Ptr{UInt8}(0),0), UInt(1))) == hash220((Ptr{UInt8}(0),0), UInt(1))
# ccall with type parameters
@static if VERSION < v"1.11-"
# TODO: in v1.11+ this function does not have a ccall
@test (@interpret Base.unsafe_convert(Ptr{Int}, [1,2])) isa Ptr{Int}
end
# ccall with call to get the pointer
cf = [@cfunction(fcfun, Int, (Int, Int))]
function call_cf()
ccall(cf[1], Int, (Int, Int), 1, 2)
end
@test (@interpret call_cf()) == call_cf()
let mt = JuliaInterpreter.enter_call(call_cf).framecode.methodtables
@test any(1:length(mt)) do i
isassigned(mt, i) && mt[i] === Compiled()
end
end
# ccall with integer static parameter
f_N() = Array{Float64, 4}(undef, 1, 3, 2, 1)
@test (@interpret f_N()) isa Array{Float64, 4}
f_clock() = ccall((:clock, "libc"), Int32, ())
# See that the method gets compiled
try @interpret f_clock()
catch
end
let mt = JuliaInterpreter.enter_call(f_clock).framecode.methodtables
@test any(1:length(mt)) do i
isassigned(mt, i) && mt[i] === Compiled()
end
end
# https://github.com/JuliaDebug/JuliaInterpreter.jl/issues/194
f_parse() = Meta.lower(Main, Meta.parse("(a=1,0)"))
@test @interpret f_parse() == f_parse()
# Test for vararg ccalls (used by mmap)
function f_mmap()
tmp = tempname()
local b_mmap
try
x = rand(10)
write(tmp, x)
b_mmap = Mmap.mmap(tmp, Vector{Float64})
@test b_mmap == x
finally
finalize(b_mmap)
rm(tmp)
end
end
@interpret f_mmap()
# parametric llvmcall (issues #112 and #288)
module VecTest
using Tensors
Vec{N,T} = NTuple{N,VecElement{T}}
# The following test mimic SIMD.jl
const _llvmtypes = Dict{DataType, String}(
Float64 => "double",
Float32 => "float",
Int32 => "i32",
Int64 => "i64"
)
@generated function vecadd(x::Vec{N, T}, y::Vec{N, T}) where {N, T}
llvmT = _llvmtypes[T]
func = T <: AbstractFloat ? "fadd" : "add"
exp = """
%3 = $(func) <$(N) x $(llvmT)> %0, %1
ret <$(N) x $(llvmT)> %3
"""
return quote
Base.@_inline_meta
Core.getfield(Base, :llvmcall)($exp, Vec{$N, $T}, Tuple{Vec{$N, $T}, Vec{$N, $T}}, x, y)
end
end
f() = 1.0 * one(Tensor{2,3})
end
let
# NOTE we need to make sure this code block is compiled, since vecadd is generated function,
# but currently `@interpret` doesn't handle a call to generated functions very well
@static if isdefined(Base.Experimental, Symbol("@force_compile"))
Base.Experimental.@force_compile
end
a = (VecElement{Float64}(1.0), VecElement{Float64}(2.0))
@test @interpret(VecTest.vecadd(a, a)) == VecTest.vecadd(a, a)
end
@test @interpret(VecTest.f()) == [1 0 0; 0 1 0; 0 0 1]
# Test exception type for undefined variables
f_undefvar() = s = s + 1
@test_throws UndefVarError @interpret f_undefvar()
# Handling of SSAValues
function f_ssaval()
z = [Core.SSAValue(5),]
repr(z[1])
end
@test @interpret f_ssaval() == f_ssaval()
# Test JuliaInterpreter version of #265
f(x) = x
g(x) = f(x)
@test (@interpret g(5)) == g(5)
f(x) = x*x
@test (@interpret g(5)) == g(5)
# Regression test https://github.com/JuliaDebug/JuliaInterpreter.jl/issues/328
module DataFramesTest
using Test
using JuliaInterpreter
using DataFrames
function df_debug1()
df = DataFrame(A=1:3, B=4:6)
df1 = hcat(df[!,[:A]], df[!,[:B]])
end
@test @interpret(df_debug1()) == df_debug1()
end
# issue #330
@test @interpret(Base.PipeEndpoint()) isa Base.PipeEndpoint
# issue #345
@noinline f_345() = 1
frame = JuliaInterpreter.enter_call(f_345)
@test JuliaInterpreter.whereis(frame) == (@__FILE__(), @__LINE__() - 2)
# issue #285
using LinearAlgebra, SparseArrays, Random
@testset "issue 285" begin
function solveit(A,b)
return A\b .+ det(A)
end
Random.seed!(123456)
n = 5
A = sprand(n,n,0.5)
A = A'*A
b = rand(n)
@test @interpret(solveit(A, b)) == solveit(A, b)
end
@testset "issue 351" begin
f() = map(x -> 2x, 1:10)
@test @interpret(f()) == f()
end
@testset "invoke" begin
# Example provided by jmert in #352
f(d::Diagonal{T}) where {T} = invoke(f, Tuple{AbstractMatrix}, d)
f(m::AbstractMatrix{T}) where {T} = T
D = Diagonal([1.0, 2.0])
@test @interpret(f(D)) === f(D)
# issue #441 & #535
f_log1() = @info "logging macros"
@test (@test_logs (:info, "logging macros") (@interpret f_log1())) === nothing
f_log2() = @error "this error is ok"
let frame = JuliaInterpreter.enter_call(f_log2)
@test (@test_logs (:error, "this error is ok") debug_command(frame, :c)) === nothing
end
end
struct A396
a::Int
end
@testset "constructor locals" begin
frame = JuliaInterpreter.enter_call(A396, 3)
@test length(JuliaInterpreter.locals(frame)) > 0
end
@static if Sys.islinux()
@testset "@ccall" begin
f(s) = @ccall strlen(s::Cstring)::Csize_t
@test @interpret(f("asd")) == 3
end
end
@testset "#466 parametric_type_to_expr" begin
@test JuliaInterpreter.parametric_type_to_expr(Array) == :(Core.Array{T, N})
end
@testset "#476 isdefined QuoteNode" begin
@eval function issue476()
return $(Expr(:isdefined, QuoteNode(Float64)))
end
@test (true === @interpret issue476())
end
@noinline foobar() = (GC.safepoint(); 42)
function run_foobar()
@eval foobar() = "nope"
return @interpret(foobar()), foobar()
end
@testset "unreachable worlds" begin
interpret, compiled = run_foobar()
@test_broken interpret == compiled == 42
end
@testset "issue #479" begin
function f()
ptr = @cfunction(+, Int, (Int, Int))
ccall(ptr::Ptr{Cvoid}, Int, (Int, Int), 1, 2)
end
@test @interpret(f()) === 3
end
@testset "https://github.com/JuliaLang/julia/pull/41018" begin
m = Module()
@eval m begin
struct Foo
foo::Int
bar
end
end
# this shouldn't throw "type DataType has no field hasfreetypevars"
# even after https://github.com/JuliaLang/julia/pull/41018
@static if VERSION ≥ v"1.9.0-DEV.1556"
@test Int === @interpret Core.Compiler.getfield_tfunc(Core.Compiler.fallback_lattice, m.Foo, Core.Compiler.Const(:foo))
else
@test Int === @interpret Core.Compiler.getfield_tfunc(m.Foo, Core.Compiler.Const(:foo))
end
end
@testset "https://github.com/JuliaDebug/JuliaInterpreter.jl/issues/488" begin
m = Module()
ex = :(foo() = return)
JuliaInterpreter.finish_and_return!(Frame(m, ex), true)
@test isdefined(m, :foo)
end
# Related to fixing https://github.com/timholy/Revise.jl/issues/625
module ForInclude end
@testset "include" begin
ex = :(include("dummy_file.jl"))
@test JuliaInterpreter.finish_and_return!(Frame(ForInclude, ex), true) == 55
end
@static if VERSION >= v"1.7.0"
@testset "issue #432" begin
function f()
t = @ccall time(C_NULL::Ptr{Cvoid})::Cint
end
@test @interpret(f()) !== 0
@test @interpret(f()) !== 0
end
end
@testset "issue #385" begin
using FunctionWrappers: FunctionWrapper
fw = @interpret FunctionWrapper{Int,Tuple{}}(()->42)
@test 42 === @interpret fw()
end
@testset "issue #550" begin
using FunctionWrappers: FunctionWrapper
f = (obs) -> (obs[1] = obs[3] * obs[4]; obs)
Tout = Vector{Int}
Tin = Tuple{Vector{Int}}
fw = FunctionWrapper{Tout, Tin}(f)
obs = [0,2,3,4]
@test @interpret(fw(obs)) == fw(obs)
end
@testset "TypedSlots" begin
function foo(x, y)
z = x + y
if z < 4
z += 1
end
u = (x -> x + z)(x)
v = Ref{Union{Int, Missing}}(x)[] + y
return u + v
end
ci = code_typed(foo, NTuple{2, Int}; optimize=false)[][1]
@static if VERSION ≥ v"1.10.0-DEV.873"
mi = Core.Compiler.method_instances(foo, NTuple{2, Int}, Base.get_world_counter())[]
else
mi = Core.Compiler.method_instances(foo, NTuple{2, Int})[]
end
frameargs = Any[foo, 1, 2]
framecode = JuliaInterpreter.FrameCode(mi.def, ci)
frame = JuliaInterpreter.prepare_frame(framecode, frameargs, mi.sparam_vals)
@test JuliaInterpreter.finish_and_return!(frame) === 8
end
@testset "interpretation of unoptimized frame" begin
let # should be able to interprete nested calls within `:foreigncall` expressions
M = Module()
lwr = Meta.@lower M begin
global foo = @ccall strlen("foo"::Cstring)::Csize_t
foo == 3
end
src = lwr.args[1]::Core.CodeInfo
frame = Frame(M, src; optimize=false)
@test length(frame.framecode.src.code) == length(src.code)
@test JuliaInterpreter.finish_and_return!(frame, true)
M = Module()
lwr = Meta.@lower M begin
strp = Ref{Ptr{Cchar}}(0)
fmt = "hi+%hhd-%hhd-%hhd-%hhd-%hhd-%hhd-%hhd-%hhd-%hhd-%hhd-%hhd-%hhd-%hhd-%hhd-%hhd-%.1f-%.1f-%.1f-%.1f-%.1f-%.1f-%.1f-%.1f-%.1f\n"
len = @ccall asprintf(
strp::Ptr{Ptr{Cchar}},
fmt::Cstring,
; # begin varargs
0x1::UInt8, 0x2::UInt8, 0x3::UInt8, 0x4::UInt8, 0x5::UInt8, 0x6::UInt8, 0x7::UInt8, 0x8::UInt8, 0x9::UInt8, 0xa::UInt8, 0xb::UInt8, 0xc::UInt8, 0xd::UInt8, 0xe::UInt8, 0xf::UInt8,
1.1::Cfloat, 2.2::Cfloat, 3.3::Cfloat, 4.4::Cfloat, 5.5::Cfloat, 6.6::Cfloat, 7.7::Cfloat, 8.8::Cfloat, 9.9::Cfloat,
)::Cint
str = unsafe_string(strp[], len)
@ccall free(strp[]::Cstring)::Cvoid
str == "hi+1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-1.1-2.2-3.3-4.4-5.5-6.6-7.7-8.8-9.9\n"
end
src = lwr.args[1]::Core.CodeInfo
frame = Frame(M, src; optimize=false)
@test length(frame.framecode.src.code) == length(src.code)
@test JuliaInterpreter.finish_and_return!(frame, true)
end
iscallexpr(ex::Expr) = ex.head === :call
@test (@interpret iscallexpr(:(sin(3.14))))
end
if isdefined(Base, :have_fma)
f_fma() = Base.have_fma(Float64)
@testset "fma" begin
@test (@interpret f_fma()) == f_fma()
a, b, c = (1.0585073227945125, -0.00040303348596386557, 1.5051263504758005e-16)
@test (@interpret muladd(a, b, c)) === muladd(a,b,c)
a = 1.0883740903666346; b = 2/3
@test (@interpret a^b) === a^b
end
end
# issue 536
function foo_536(y::T) where {T}
x = "A"
return ccall(:memcmp, Cint, (Ptr{UInt8}, Ref{T}, Csize_t),
pointer(x), Ref(y), 1) == 0
end
@test !@interpret foo_536(0x00)
@test @interpret foo_536(UInt8('A'))
@static if isdefined(Base.Experimental, Symbol("@opaque"))
@testset "opaque closures" begin
g(x) = 3x
f = Base.Experimental.@opaque x -> g(x)
@test @interpret f(4) == 12
# test stepping into opaque closures
@breakpoint g(1)
fr = JuliaInterpreter.enter_call_expr(Expr(:call, f, 4))
@test JuliaInterpreter.finish_and_return!(fr) isa JuliaInterpreter.BreakpointRef
end
end
# CassetteOverlay, issue #552
@static if VERSION >= v"1.8"
using CassetteOverlay
end
@static if VERSION >= v"1.8"
function foo()
x = IdDict()
x[:foo] = 1
end
@MethodTable SinTable;
@testset "CassetteOverlay" begin
pass = @overlaypass SinTable;
@test (@interpret pass(foo)) == 1
end
end
using LoopVectorization
@testset "interpolated llvmcall" begin
function f_lv!(A)
m, n = size(A)
k = 1
@turbo for j in (k + 1):n
for i in (k + 1):m
A[i, j] -= A[i, k] * A[k, j]
end
end
return A
end
A = rand(5,5)
B = copy(A)
@interpret f_lv!(A)
f_lv!(B)
@test A ≈ B
end
@testset "nargs foreigncall #560" begin
@test (@interpret string("", "pcre_h.jl")) == string("", "pcre_h.jl")
@test (@interpret Base.strcat("", "build_h.jl")) == Base.strcat("", "build_h.jl")
end
# test for using generic functions that were previously builtin
func_arrayref(a, i) = Core.arrayref(true, a, i)
@test 2 == @interpret func_arrayref([1,2,3], 2)
@static if isdefined(Base, :ScopedValues)
@testset "interpret_scopedvalues.jl" include("interpret_scopedvalues.jl")
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 1514 | module interpret_scopedvalues
using Test, JuliaInterpreter
using Base.ScopedValues
const sval1 = ScopedValue(1)
const sval2 = ScopedValue(1)
@test 1 == @interpret getindex(sval1)
# current_scope support for interpretation
sval1_func1() = @with sval1 => 2 begin
return sval1[]
end
@test 2 == @interpret sval1_func1()
sval12_func1() = @with sval1 => 2 begin
@with sval2 => 3 begin
return sval1[], sval2[]
end
end
@test (2, 3) == @interpret sval12_func1()
# current_scope support for compiled calls
_sval1_func2() = sval1[]
sval1_func2() = @with sval1 => 2 begin
return _sval1_func2()
end
let m = only(methods(_sval1_func2))
push!(JuliaInterpreter.compiled_methods, m)
try
@test 2 == @interpret sval1_func2()
finally
delete!(JuliaInterpreter.compiled_methods, m)
end
end
let frame = JuliaInterpreter.enter_call(sval1_func2)
@test 2 == JuliaInterpreter.finish_and_return!(Compiled(), frame)
end
# preset `current_scope` support
@test 2 == @with sval1 => 2 begin
@interpret getindex(sval1)
end
@test (2, 3) == @with sval1 => 2 sval2 => 3 begin
@interpret(getindex(sval1)), @interpret(getindex(sval2))
end
@test (2, 3) == @with sval1 => 2 begin @with sval2 => 3 begin
@interpret(getindex(sval1)), @interpret(getindex(sval2))
end end
let frame = JuliaInterpreter.enter_call() do
sval1[], sval2[]
end
@test (2, 3) == @with sval1 => 2 sval2 => 3 JuliaInterpreter.finish_and_return!(frame)
end
end # module interpret_scopedvalues
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 5511 | using JuliaInterpreter
using Test, Random, InteractiveUtils, Distributed, Dates
# Much of this file is taken from Julia's test/runtests.jl file.
if !isdefined(Main, :read_and_parse)
include("utils.jl")
end
const juliadir = dirname(dirname(Sys.BINDIR))
const testdir = joinpath(juliadir, "test")
if isdir(testdir)
include(joinpath(testdir, "choosetests.jl"))
else
@error "Julia's test/ directory not found, can't run Julia tests"
end
function test_path(test)
t = split(test, '/')
if t[1] in STDLIBS
if length(t) == 2
return joinpath(STDLIB_DIR, t[1], "test", t[2])
else
return joinpath(STDLIB_DIR, t[1], "test", "runtests")
end
else
return joinpath(testdir, test)
end
end
nstmts = 10^4 # very quick, aborts a lot
outputfile = "results.md"
i = 1
while i <= length(ARGS)
global i
a = ARGS[i]
if a == "--nstmts"
global nstmts = parse(Int, ARGS[i+1])
deleteat!(ARGS, i:i+1)
elseif a == "--output"
global outputfile = ARGS[i+1]
deleteat!(ARGS, i:i+1)
else
i += 1
end
end
tests, _, exit_on_error, seed = choosetests(ARGS)
function spin_up_worker()
p = addprocs(1)[1]
remotecall_wait(include, p, "utils.jl")
remotecall_wait(configure_test, p)
return p
end
function spin_up_workers(n)
procs = addprocs(n)
@sync begin
@async for p in procs
remotecall_wait(include, p, "utils.jl")
remotecall_wait(configure_test, p)
end
end
return procs
end
# Really, we're just going to skip all the tests that run on node1
const node1_tests = String[]
function move_to_node1(t)
if t in tests
splice!(tests, findfirst(isequal(t), tests))
push!(node1_tests, t)
end
nothing
end
move_to_node1("precompile")
move_to_node1("SharedArrays")
move_to_node1("stress")
move_to_node1("Distributed")
@testset "Julia tests" begin
nworkers = min(Sys.CPU_THREADS, length(tests))
println("Using $nworkers workers")
results = Dict{String,Any}()
tests0 = copy(tests)
all_tasks = Union{Task,Nothing}[]
try
@sync begin
for i = 1:nworkers
@async begin
push!(all_tasks, current_task())
while length(tests) > 0
nleft = length(tests)
test = popfirst!(tests)
println(nleft, " remaining, starting ", test, " on task ", i)
local resp
fullpath = test_path(test) * ".jl"
try
resp = disable_sigint() do
p = spin_up_worker()
result = remotecall_fetch(run_test_by_eval, p, test, fullpath, nstmts)
rmprocs(p; waitfor=5)
result
end
catch e
if isa(e, InterruptException)
println("interrupting ", test)
break # rethrow(e)
end
resp = e
if isa(e, ProcessExitedException)
println("exited on ", test)
end
end
results[test] = resp
if resp isa Exception && exit_on_error
skipped = length(tests)
empty!(tests)
end
end
println("Task ", i, " complete")
all_tasks[i] = nothing
end
end
end
catch err
isa(err, InterruptException) || rethrow(err)
# If the test suite was merely interrupted, still print the
# summary, which can be useful to diagnose what's going on
foreach(all_tasks) do task
try
if isa(task, Task)
println("trying to interrupt ", task)
schedule(task, InterruptException(); error=true)
end
catch
end
end
foreach(wait, all_tasks)
end
open(outputfile, "w") do io
versioninfo(io)
println(io, "Test run at: ", now())
println(io)
println(io, "Maximum number of statements per lowered expression: ", nstmts)
println(io)
println(io, "| Test file | Passes | Fails | Errors | Broken | Aborted blocks |")
println(io, "| --------- | ------:| -----:| ------:| ------:| --------------:|")
for test in tests0
result = get(results, test, "")
if isa(result, Tuple{Test.AbstractTestSet, Vector})
ts, aborts = result
passes, fails, errors, broken, c_passes, c_fails, c_errors, c_broken = Test.get_test_counts(ts)
naborts = length(aborts)
println(io, "| ", test, " | ", passes+c_passes, " | ", fails+c_fails, " | ", errors+c_errors, " | ", broken+c_broken, " | ", naborts, " |")
elseif isa(result, ProcessExitedException)
println(io, "| ", test, " | ☠️ | ☠️ | ☠️ | ☠️ | ☠️ |")
else
println(test, " => ", result)
println(io, "| ", test, " | X | X | X | X | X |")
end
end
end
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 4071 | using JuliaInterpreter
using CodeTracking
using Test
# This is a test-for-tests, verifying the code in utils.jl.
if !isdefined(@__MODULE__, :read_and_parse)
include("utils.jl")
end
@testset "Abort" begin
ex = Base.parse_input_line("""
x = 1
for i = 1:10
x += 1
end
let y = 0
z = 5
end
if 2 > 1
println("Hello, world!")
end
@elapsed sum(rand(5))
"""; filename="fake.jl")
modexs = collect(ExprSplitter(Main, ex))
# find the 3rd assignment statement in the 2nd frame (corresponding to the x += 1 line)
frame = Frame(modexs[2]...)
i = 0
for k = 1:3
i = findnext(stmt->isexpr(stmt, :(=)), frame.framecode.src.code, i+1)
end
@test Aborted(frame, i).at.line == 3
# Check interior of let block
frame = Frame(modexs[3]...)
i = 0
for k = 1:2
i = findnext(stmt->isexpr(stmt, :(=)), frame.framecode.src.code, i+1)
end
@test Aborted(frame, i).at.line == 6
# Check conditional
frame = Frame(modexs[4]...)
i = findfirst(stmt->isa(stmt, Core.GotoIfNot), frame.framecode.src.code) + 1
@test Aborted(frame, i).at.line == 9
# Check macro
frame = Frame(modexs[5]...)
@test Aborted(frame, 1).at.file === Symbol("fake.jl")
@test whereis(frame, 1; macro_caller=true) == ("fake.jl", 11)
end
module EvalLimited end
@testset "evaluate_limited" begin
aborts = Aborted[]
ex = Base.parse_input_line("""
s = 0
for i = 1:5
global s
s += 1
end
""")
modexs = collect(ExprSplitter(EvalLimited, ex))
nstmts = 1000 # enough to ensure it finishes
for (mod, ex) in modexs
frame = Frame(mod, ex)
@test isa(frame, Frame)
nstmtsleft = nstmts
while true
ret, nstmtsleft = evaluate_limited!(frame, nstmtsleft, true)
isa(ret, Some{Any}) && break
isa(ret, Aborted) && push!(aborts, ret)
end
end
@test EvalLimited.s == 5
@test isempty(aborts)
ex = Base.parse_input_line("""
s = 0
for i = 1:50
global s
s += 1
end
"""; filename="fake.jl")
if length(ex.args) == 2
# Sadly, on some Julia versions parse_input_line doesn't insert line info at toplevel, so do it manually
insert!(ex.args, 2, LineNumberNode(2, Symbol("fake.jl")))
insert!(ex.args, 1, LineNumberNode(1, Symbol("fake.jl")))
end
modexs = collect(ExprSplitter(EvalLimited, ex))
@static if VERSION >= v"1.11-"
nstmts = 10*17 + 20 # 10 * 17 statements per iteration + α
elseif VERSION >= v"1.10-"
nstmts = 10*15 + 20 # 10 * 15 statements per iteration + α
elseif isdefined(Core, :get_binding_type)
nstmts = 10*14 + 20 # 10 * 14 statements per iteration + α
elseif VERSION >= v"1.7-"
nstmts = 10*11 + 20 # 10 * 9 statements per iteration + α
else
nstmts = 10*10 + 20 # 10 * 10 statements per iteration + α
end
for (mod, ex) in modexs
frame = Frame(mod, ex)
@test isa(frame, Frame)
nstmtsleft = nstmts
while true
ret, nstmtsleft = evaluate_limited!(Compiled(), frame, nstmtsleft, true)
isa(ret, Some{Any}) && break
isa(ret, Aborted) && (push!(aborts, ret); break)
end
end
@test 10 ≤ EvalLimited.s < 50
@test length(aborts) == 1
@test aborts[1].at.line ∈ (2, 3, 4, 5) # 2 corresponds to lowering of the for loop
# Now try again with recursive stack
empty!(aborts)
modexs = collect(ExprSplitter(EvalLimited, ex))
for (mod, ex) in modexs
frame = Frame(mod, ex)
@test isa(frame, Frame)
nstmtsleft = nstmts
while true
ret, nstmtsleft = evaluate_limited!(frame, nstmtsleft, true)
isa(ret, Some{Any}) && break
isa(ret, Aborted) && (push!(aborts, ret); break)
end
end
@test EvalLimited.s < 5
@test length(aborts) == 1
lin = aborts[1].at
@test lin.file === Symbol("fake.jl")
@test lin.line ∈ (2, 3, 4, 5)
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 906 | using JuliaInterpreter
using Test
using Logging
@test isempty(detect_ambiguities(JuliaInterpreter, Base, Core))
if !isdefined(@__MODULE__, :read_and_parse)
include("utils.jl")
end
Core.eval(JuliaInterpreter, :(debug_mode() = true))
@testset "Main tests" begin
@testset "check_bulitins.jl" begin include("check_builtins.jl") end
@testset "core.jl" begin include("core.jl") end
@testset "interpret.jl" begin include("interpret.jl") end
@testset "toplevel.jl" begin include("toplevel.jl") end
@testset "limits.jl" begin include("limits.jl") end
@testset "eval_code.jl" begin include("eval_code.jl") end
@testset "breakpoints.jl" begin include("breakpoints.jl") end
@static VERSION >= v"1.8.0-DEV.370" && @testset "code_coverage/code_coverage.jl" begin include("code_coverage/code_coverage.jl") end
remove()
@testset "debug.jl" begin include("debug.jl") end
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 18939 | if !isdefined(@__MODULE__, :read_and_parse)
include("utils.jl")
end
module JIVisible
module JIInvisible
end
end
@testset "Basics" begin
@test JuliaInterpreter.is_doc_expr(:(@doc "string" sum))
@test JuliaInterpreter.is_doc_expr(:(Core.@doc "string" sum))
ex = quote
"""
a docstring
"""
sum
end
@test JuliaInterpreter.is_doc_expr(ex.args[2])
@test !JuliaInterpreter.is_doc_expr(:(1+1))
# https://github.com/JunoLab/Juno.jl/issues/271
ex = quote
"""
Special Docstring
"""
module DocStringTest
function foo()
x = 4 + 5
end
end
end
modexs = collect(ExprSplitter(JIVisible, ex))
m, ex = first(modexs) # FIXME don't use index in tests
@test JuliaInterpreter.is_doc_expr(ex.args[2])
Core.eval(m, ex)
io = IOBuffer()
show(io, @doc(JIVisible.DocStringTest))
@test occursin("Special", String(take!(io)))
ex = Base.parse_input_line("""
"docstring"
module OuterModDocstring
"docstring for InnerModDocstring"
module InnerModDocstring
end
end
""")
modexs = collect(ExprSplitter(JIVisible, ex))
@test isdefined(JIVisible, :OuterModDocstring)
@test isdefined(JIVisible.OuterModDocstring, :InnerModDocstring)
# issue #538
@test !JuliaInterpreter.is_doc_expr(:(Core.@doc "string"))
ex = quote
@doc("no docstring")
sum
end
modexs = collect(ExprSplitter(Main, ex))
m, ex = first(modexs) # FIXME don't use index in tests
@test !JuliaInterpreter.is_doc_expr(ex.args[2])
@test !isdefined(Main, :JIInvisible)
collect(ExprSplitter(JIVisible, :(module JIInvisible f() = 1 end))) # this looks up JIInvisible rather than create it
@test !isdefined(Main, :JIInvisible)
@test isdefined(JIVisible, :JIInvisible)
mktempdir() do path
push!(LOAD_PATH, path)
open(joinpath(path, "TmpPkg1.jl"), "w") do io
println(io, """
module TmpPkg1
using TmpPkg2
end
""")
end
open(joinpath(path, "TmpPkg2.jl"), "w") do io
println(io, """
module TmpPkg2
f() = 1
end
""")
end
@eval using TmpPkg1
# Every package is technically parented in Main but the name may not be visible in Main
@test isdefined(@__MODULE__, :TmpPkg1)
@test !isdefined(@__MODULE__, :TmpPkg2)
collect(ExprSplitter(@__MODULE__, quote
module TmpPkg2
f() = 2
end
end))
@test isdefined(@__MODULE__, :TmpPkg1)
@test !isdefined(@__MODULE__, :TmpPkg2)
end
# Revise issue #718
ex = Base.parse_input_line("""
module TestPkg718
module TestModule718
export _VARIABLE_UNASSIGNED
global _VARIABLE_UNASSIGNED = -84.0
end
using .TestModule718
end
""")
for (mod, ex) in ExprSplitter(JIVisible, ex)
@test JuliaInterpreter.finish!(Frame(mod, ex), true) === nothing
end
@test JIVisible.TestPkg718._VARIABLE_UNASSIGNED == -84.0
end
module Toplevel end
@testset "toplevel" begin
modexs = ExprSplitter(Toplevel, read_and_parse(joinpath(@__DIR__, "toplevel_script.jl")))
for (mod, ex) in modexs
frame = Frame(mod, ex)
while true
JuliaInterpreter.through_methoddef_or_done!(frame) === nothing && break
end
end
@test isconst(Toplevel, :StructParent)
@test isconst(Toplevel, :Struct)
@test isconst(Toplevel, :MyInt8)
s = Toplevel.Struct([2.0])
@test Toplevel.f1(0) == 1
@test Toplevel.f1(0.0) == 2
@test Toplevel.f1(0.0f0) == 3
@test Toplevel.f2("hi") == -1
@test Toplevel.f2(UInt16(1)) == UInt16
@test Toplevel.f2(3.2) == 0
@test Toplevel.f2(view([1,2], 1:1)) == 2
@test Toplevel.f2([1,2]) == 3
@test Toplevel.f2(reshape(view([1,2], 1:2), 2, 1)) == 4
@test Toplevel.f3(1, 1) == 1
@test Toplevel.f3(1, :hi) == 2
@test Toplevel.f3(UInt16(1), :hi) == Symbol
@test Toplevel.f3(rand(2, 2), :hi, :there) == 2
@test_throws MethodError Toplevel.f3([1.0], :hi, :there)
@test Toplevel.f4(1, 1.0) == 1
@test Toplevel.f4(1, 1) == Toplevel.f4(1) == 2
@test Toplevel.f4(UInt(1), "hey", 2) == 3
@test Toplevel.f4(rand(2,2)) == 2
@test Toplevel.f5(Int8(1); y=22) == 22
@test Toplevel.f5(Int16(1)) == 2
@test Toplevel.f5(Int32(1)) == 3
@test Toplevel.f5(Int64(1)) == 4
@test Toplevel.f5(rand(2,2); y=7) == 2
@test Toplevel.f6(1, "hi"; z=8) == 1
@test Toplevel.f7(1, (1, :hi)) == 1
@test Toplevel.f8(0) == 1
@test Toplevel.f9(3) == 9
@test Toplevel.f9(3.0) == 3.0
@test s("hello") == [2.0]
@test Toplevel.Struct{Float32}(Dict(1=>"two")) == 4
@test Toplevel.first_two_funcs == (Toplevel.f1, Toplevel.f2)
@test isconst(Toplevel, :first_two_funcs)
@test Toplevel.myint isa Toplevel.MyInt8
@test_throws UndefVarError Toplevel.ffalse(1)
@test Toplevel.ftrue(1) == 3
@test Toplevel.fctrue(0) == 1
@test_throws UndefVarError Toplevel.fcfalse(0)
@test !Toplevel.Consts.b2
@test Toplevel.fb1true(0) == 1
@test_throws UndefVarError Toplevel.fb1false(0)
@test Toplevel.fb2false(0) == 1
@test_throws UndefVarError Toplevel.fb2true(0)
@test Toplevel.fstrue(0) == 1
@test Toplevel.fouter(1) === 2
@test Toplevel.feval1(1.0) === 1
@test Toplevel.feval1(1.0f0) === 1
@test_throws MethodError Toplevel.feval1(1)
@test Toplevel.feval2(1.0, Int8(1)) == 2
@test length(s) === nothing
@test size(s) === nothing
@test Toplevel.nbytes(Float32) == 4
@test Toplevel.typestring(1.0) == "Float64"
@test Toplevel._feval3(0) == 3
@test Toplevel.feval_add!(0) == 1
@test Toplevel.feval_min!(0) == 1
@test Toplevel.paramtype(Vector{Int8}) == Int8
@test Toplevel.paramtype(Vector) == Toplevel.NoParam
@test Toplevel.Inner.g() == 5
@test Toplevel.Inner.InnerInner.g() == 6
@test isdefined(Toplevel, :Beat)
@test Toplevel.Beat <: Toplevel.DatesMod.Period
@test @interpret(Toplevel.f1(0)) == 1
@test @interpret(Toplevel.f1(0.0)) == 2
@test @interpret(Toplevel.f1(0.0f0)) == 3
@test @interpret(Toplevel.f2("hi")) == -1
@test @interpret(Toplevel.f2(UInt16(1))) == UInt16
@test @interpret(Toplevel.f2(3.2)) == 0
@test @interpret(Toplevel.f2(view([1,2], 1:1))) == 2
@test @interpret(Toplevel.f2([1,2])) == 3
@test @interpret(Toplevel.f2(reshape(view([1,2], 1:2), 2, 1))) == 4
@test @interpret(Toplevel.f3(1, 1)) == 1
@test @interpret(Toplevel.f3(1, :hi)) == 2
@test @interpret(Toplevel.f3(UInt16(1), :hi)) == Symbol
@test @interpret(Toplevel.f3(rand(2, 2), :hi, :there)) == 2
@test_throws MethodError @interpret(Toplevel.f3([1.0], :hi, :there))
@test @interpret(Toplevel.f4(1, 1.0)) == 1
@test @interpret(Toplevel.f4(1, 1)) == @interpret(Toplevel.f4(1)) == 2
@test @interpret(Toplevel.f4(UInt(1), "hey", 2)) == 3
@test @interpret(Toplevel.f4(rand(2,2))) == 2
@test @interpret(Toplevel.f5(Int8(1); y=22)) == 22
@test @interpret(Toplevel.f5(Int16(1))) == 2
@test @interpret(Toplevel.f5(Int32(1))) == 3
@test @interpret(Toplevel.f5(Int64(1))) == 4
@test @interpret(Toplevel.f5(rand(2,2); y=7)) == 2
@test @interpret(Toplevel.f6(1, "hi"; z=8)) == 1
@test @interpret(Toplevel.f7(1, (1, :hi))) == 1
@test @interpret(Toplevel.f8(0)) == 1
@test @interpret(Toplevel.f9(3)) == 9
@test @interpret(Toplevel.f9(3.0)) == 3.0
@test @interpret(s("hello")) == [2.0]
@test @interpret(Toplevel.Struct{Float32}(Dict(1=>"two"))) == 4
@test_throws UndefVarError @interpret(Toplevel.ffalse(1))
@test @interpret(Toplevel.ftrue(1)) == 3
@test @interpret(Toplevel.fctrue(0)) == 1
@test_throws UndefVarError @interpret(Toplevel.fcfalse(0))
@test @interpret(Toplevel.fb1true(0)) == 1
@test_throws UndefVarError @interpret(Toplevel.fb1false(0))
@test @interpret(Toplevel.fb2false(0)) == 1
@test_throws UndefVarError @interpret(Toplevel.fb2true(0))
@test @interpret(Toplevel.fstrue(0)) == 1
@test @interpret(Toplevel.fouter(1)) === 2
@test @interpret(Toplevel.feval1(1.0)) === 1
@test @interpret(Toplevel.feval1(1.0f0)) === 1
@test_throws MethodError @interpret(Toplevel.feval1(1))
@test @interpret(Toplevel.feval2(1.0, Int8(1))) == 2
@test @interpret(length(s)) === nothing
@test @interpret(size(s)) === nothing
@test @interpret(Toplevel.nbytes(Float32)) == 4
@test @interpret(Toplevel.typestring(1.0)) == "Float64"
@test @interpret(Toplevel._feval3(0)) == 3
@test @interpret(Toplevel.feval_add!(0)) == 1
@test @interpret(Toplevel.feval_min!(0)) == 1
@test @interpret(Toplevel.paramtype(Vector{Int8})) == Int8
@test @interpret(Toplevel.paramtype(Vector)) == Toplevel.NoParam
@test @interpret(Toplevel.Inner.g()) == 5
@test @interpret(Toplevel.Inner.InnerInner.g()) == 6
# FIXME: even though they pass, these tests break Test!
# @test @interpret(isdefined(Toplevel, :Beat))
# @test @interpret(Toplevel.Beat <: Toplevel.DatesMod.Period)
# Check that nested expressions are handled appropriately (module-in-block, internal `using`)
ex = quote
module Testing
if true
using JuliaInterpreter
end
end
end
modexs = ExprSplitter(Toplevel, ex)
for (mod, ex) in modexs
frame = Frame(mod, ex)
while true
JuliaInterpreter.through_methoddef_or_done!(frame) === nothing && break
end
end
@test Toplevel.Testing.Frame === Frame
end
# Proper handling of namespaces
# https://github.com/timholy/Revise.jl/issues/579
module Namespace end
@testset "Namespace" begin
frame = Frame(Namespace, :(sin(::Int) = 10))
while true
JuliaInterpreter.through_methoddef_or_done!(frame) === nothing && break
end
@test Namespace.sin(0) == 10
@test Base.sin(0) == 0
end
# When retrospectively parsing through modules to analyze code, Julia's stdlibs pose a bit
# of a namespace challenge too: we never want to redefine new modules with the same name.
@testset "Namespace stdlibs" begin
# Get the "real" LibCURL_jll module (Julia 1.6 and higher)
modref = nothing
for (id, mod) in Base.loaded_modules
if id.name == "LibCURL_jll"
modref = mod
break
end
end
if modref !== nothing
# Now try to find it by splitting
exsplit = JuliaInterpreter.ExprSplitter(Base.__toplevel__, :(
baremodule LibCURL_jll
using Base
Base.Experimental.@compiler_options compile=min optimize=0 infer=false
end))
(mod1, ex1), state1 = iterate(exsplit)
@test mod1 === modref
end
end
# incremental interpretation solves world-age problems
# Taken straight from Julia's test/tuple.jl
module IncTest
using Test
struct A_15703{N}
keys::NTuple{N, Int}
end
struct B_15703
x::A_15703
end
end
ex = quote
@testset "issue #15703" begin
function bug_15703(xs...)
[x for x in xs]
end
function test_15703()
s = (1,)
a = A_15703(s)
ss = B_15703(a).x.keys
@test ss === s
bug_15703(ss...)
end
test_15703()
end
end
modexs = collect(ExprSplitter(IncTest, ex))
for (i, (mod, ex)) in enumerate(modexs)
local frame = Frame(mod, ex)
while true
JuliaInterpreter.through_methoddef_or_done!(frame) === nothing && break
end
if i == length(modexs)
@test isa(JuliaInterpreter.get_return(frame), Test.DefaultTestSet)
end
end
@testset "Enum" begin
ex = Expr(:toplevel,
:(@enum EnumParent begin
EnumChild0
EnumChild1
end))
modexs = ExprSplitter(Toplevel, ex)
for (mod, ex) in modexs
frame = Frame(mod, ex)
while true
JuliaInterpreter.through_methoddef_or_done!(frame) === nothing && break
end
end
@test isa(Toplevel.EnumChild1, Toplevel.EnumParent)
end
module LowerAnon
ret = Ref{Any}(nothing)
end
@testset "Anonymous functions" begin
ex1 = quote
f = x -> parse(Int16, x)
ret[] = map(f, AbstractString[])
end
ex2 = quote
ret[] = map(x->parse(Int16, x), AbstractString[])
end
modexs = ExprSplitter(LowerAnon, ex1)
for (mod, ex) in modexs
frame = Frame(mod, ex)
while true
JuliaInterpreter.through_methoddef_or_done!(frame) === nothing && break
end
end
@test isa(LowerAnon.ret[], Vector{Int16})
LowerAnon.ret[] = nothing
modexs = ExprSplitter(LowerAnon, ex2)
for (mod, ex) in modexs
frame = Frame(mod, ex)
while true
JuliaInterpreter.through_methoddef_or_done!(frame) === nothing && break
end
end
@test isa(LowerAnon.ret[], Vector{Int16})
LowerAnon.ret[] = nothing
ex3 = quote
const BitIntegerType = Union{map(T->Type{T}, Base.BitInteger_types)...}
end
modexs = ExprSplitter(LowerAnon, ex3)
for (mod, ex) in modexs
frame = Frame(mod, ex)
while true
JuliaInterpreter.through_methoddef_or_done!(frame) === nothing && break
end
end
@test isa(LowerAnon.BitIntegerType, Union)
ex4 = quote
y = 3
z = map(x->x^2+y, [1,2,3])
y = 4
end
modexs = ExprSplitter(LowerAnon, ex4)
for (mod, ex) in modexs
frame = Frame(mod, ex)
while true
JuliaInterpreter.through_methoddef_or_done!(frame) === nothing && break
end
end
@test LowerAnon.z == [4,7,12]
end
@testset "Docstrings" begin
ex = quote
"""
A docstring
"""
f(x) = 1
g(T::Type) = 1
g(x) = 2
"""
Docstring 2
"""
g(T::Type)
module Sub
"""
Docstring 3
"""
f(x) = 2
end
end
Core.eval(Toplevel, Expr(:toplevel, ex.args...))
modexs = ExprSplitter(Toplevel, ex)
nt = nsub = 0
for (mod, ex) in modexs
if JuliaInterpreter.is_doc_expr(ex.args[2])
mod == Toplevel && (nt += 1)
mod == Toplevel.Sub && (nsub += 1)
ex = ex.args[2].args[4]
ex isa Expr || continue
ex.head === :call && continue
end
frame = Frame(mod, ex)
while true
JuliaInterpreter.through_methoddef_or_done!(frame) === nothing && break
end
end
@test nt == 2
@test nsub == 1
@test Toplevel.f("check") == 1
@test Toplevel.Sub.f("check") == 2
end
@testset "Self referential" begin
# Revise issue #304
ex = :(mutable struct Node t :: Node end)
frame = Frame(Toplevel, ex)
JuliaInterpreter.finish!(frame, true)
@test Toplevel.Node isa Type
end
@testset "Non-frames" begin
ex = Base.parse_input_line("""
\"\"\"
An expr that produces an `export nffoo` that doesn't produce a Frame
\"\"\"
module NonFrame
nfbar(x) = 1
@deprecate nffoo nfbar
global CoolStuff
const thresh = 1.0
export nfbar
end
""")
modexs = ExprSplitter(Toplevel, ex)
for (mod, ex) in modexs
if ex.head === :global
Core.eval(mod, ex)
continue
end
frame = Frame(mod, ex)
frame === nothing && continue
JuliaInterpreter.finish!(frame, true)
end
Core.eval(Toplevel, :(using .NonFrame))
@test isdefined(Toplevel, :nffoo)
end
@testset "LOAD_PATH and modules" begin
tmpdir = joinpath(tempdir(), randstring())
mkpath(tmpdir)
push!(LOAD_PATH, tmpdir)
filename = joinpath(tmpdir, "NewModule.jl")
open(filename, "w") do io
print(io, """
module NewModule
f() = 1
end""")
end
str = read(filename, String)
ex = Base.parse_input_line(str)
modexs = ExprSplitter(Main, ex)
@test !isempty(modexs)
pop!(LOAD_PATH)
rm(tmpdir, recursive=true)
end
@testset "`used` for abstract types" begin
ex = :(abstract type AbstractType <: AbstractArray{Union{Int,Missing},2} end)
frame = Frame(Toplevel, ex)
JuliaInterpreter.finish!(frame, true)
@test isabstracttype(Toplevel.AbstractType)
end
@testset "Recursive type definitions" begin
# See https://github.com/timholy/Revise.jl/issues/417
# See also the `Node` test above
ex = :(struct RecursiveType x::Vector{RecursiveType} end)
frame = Frame(Toplevel, ex)
JuliaInterpreter.finish!(frame, true)
@test Toplevel.RecursiveType(Vector{Toplevel.RecursiveType}()) isa Toplevel.RecursiveType
end
# https://github.com/timholy/Revise.jl/issues/420
module ToplevelParameters
Base.@kwdef struct MyStruct
x::Array{<:Real, 1} = [.05]
end
end
@testset "Nested references in type definitions" begin
ex = quote
Base.@kwdef struct MyStruct
x::Array{<:Real, 1} = [.05]
end
end
frame = Frame(ToplevelParameters, ex)
@test JuliaInterpreter.finish!(frame, true) === nothing
end
@testset "Issue #427" begin
ex = :(begin
local foo = 10
sin(foo)
end)
for (mod, ex) in ExprSplitter(@__MODULE__, ex)
@test JuliaInterpreter.finish_and_return!(Frame(mod, ex), true) == sin(10)
end
ex = :(begin
3 + 7
module Local
local foo = 10
sin(foo)
end
end)
modexs = collect(ExprSplitter(@__MODULE__, ex))
@test length(modexs) == 2 # FIXME don't use index in tests
@test modexs[2][1] == getfield(@__MODULE__, :Local)
for (mod, ex) in modexs
@test JuliaInterpreter.finish!(Frame(mod, ex), true) === nothing
end
ex = :(begin
3 + 7
module Local
local foo = 10
sin(foo)
end
3 + 7
end)
modexs = collect(ExprSplitter(@__MODULE__, ex))
@test length(modexs) == 3
end
@testset "toplevel scope annotation" begin
ex = Base.parse_input_line("""
global foo_g = 10
sin(foo_g)
""")
modexs = collect(ExprSplitter(@__MODULE__, ex))
for (mod, ex) in modexs
@test JuliaInterpreter.finish!(Frame(mod, ex), true) === nothing
end
@test length(modexs) == 2 # FIXME don't use index in tests
ex = Base.parse_input_line("""
local foo = 10
sin(42)
""")
modexs = collect(ExprSplitter(@__MODULE__, ex))
for (mod, ex) in modexs
@test JuliaInterpreter.finish!(Frame(mod, ex), true) === nothing
end
@test length(modexs) == 2 # FIXME don't use index in tests
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 2994 | abstract type StructParent{T,N} <: AbstractArray{T,N} end
struct Struct{T} <: StructParent{T,1}
x::Vector{T}
end
primitive type MyInt8 <: Integer 8 end
MyInt8(x::Integer) = Base.bitcast(MyInt8, convert(Int8, x))
myint = MyInt8(2)
const TypeAlias = Float32
# Methods and signatures
f1(x::Int) = 1
f1(x) = 2
f1(x::TypeAlias) = 3
# where signatures
f2(x::T) where T = -1
f2(x::T) where T<:Integer = T
f2(x::T) where Unsigned<:T<:Real = 0
f2(x::V) where V<:SubArray{T} where T = 2
f2(x::V) where V<:Array{T,N} where {T,N} = 3
f2(x::V) where V<:Base.ReshapedArray{T,N} where T where N = 4
# Varargs
f3(x::Int, y...) = 1
f3(x::Int, y::Symbol...) = 2
f3(x::T, y::U...) where {T<:Integer,U} = U
f3(x::Array{Float64,K}, y::Vararg{Symbol,K}) where K = K
# Default args
f4(x, y=0) = 1
f4(x, y::Int) = 2
f4(x::UInt, y="hello", z::Int=0) = 3
f4(x::Array{Float64,K}, y::Int=0) where K = K
# Keyword args
f5(x::Int8; y=0) = y
f5(x::Int16; y::Int=0) = 2
f5(x::Int32; y="hello", z::Int=0) = 3
f5(x::Int64;) = 4
f5(x::Array{Float64,K}; y::Int=0) where K = K
# Default and keyword args
f6(x, y="hello"; z::Int=0) = 1
# Destructured args
f7(x, (count, name)) = 1
# Return-type annotations
f8(x)::Int = 1
# generated functions
@generated function f9(x)
if x <: Integer
return :(x ^ 2)
else
return :(x)
end
end
# Call overloading
(i::Struct)(::String) = i.x
(::Type{Struct{T}})(::Dict) where T = sizeof(T)
const first_two_funcs = (f1, f2)
# Conditional methods
if false
ffalse(x) = 2
end
if true
ftrue(x) = 3
end
if 0.8 > 0.2
fctrue(x) = 1
else
fcfalse(x) = 1
end
module Consts
export b1
b1 = true
b2 = false
g() = 2
end
using .Consts
if b1
fb1true(x) = 1
else
fb1false(x) = 1
end
if Consts.b2
fb2true(x) = 1
else
fb2false(x) = 1
end
if @isdefined(sum)
fstrue(x) = 1
end
# Inner methods
function fouter(x)
finner(::Float16) = 2x
return finner(Float16(1))
end
## Evaled methods
for T in (Float32, Float64)
@eval feval1(::$T) = 1
end
for T1 in (Float32, Float64), T2 in (Int8,)
@eval feval2(::$T1, ::$T2) = 2
end
for f in (:length, :size)
@eval Base.$f(i::Struct, args...) = nothing
end
for (T, v) in Dict(Float32=>4, Float64=>8)
@eval nbytes(::Type{$T}) = $v
end
for x in (1, 1.1)
@eval typestring(::$(typeof(x))) = $(string(typeof(x)))
end
for name in (:feval3,)
_f = Symbol("_", name)
@eval ($_f)(arg) = 3
end
const opnames = Dict{Symbol, Symbol}(:+ => :add, :- => :sub)
for op in [:+, :-, :max, :min]
opname = get(opnames, op, op)
@eval $(Symbol("feval_", opname, "!"))(var) = 1
end
# Methods with @isdefined
struct NoParam end
myeltype(::Type{Vector{T}}) where T = @isdefined(T) ? T : NoParam
paramtype(::Type{V}) where V<:Vector = isa(V, UnionAll) ? myeltype(Base.unwrap_unionall(V)) : myeltype(V)
## Submodules
module Inner
g() = 5
module InnerInner
g() = 6
end
end
module DatesMod
abstract type Period end
end
struct Beat <: DatesMod.Period
value::Int64
end
module Empty end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 8547 | using JuliaInterpreter
using JuliaInterpreter: Frame, @lookup
using JuliaInterpreter: finish_and_return!, evaluate_call!, step_expr!, shouldbreak,
do_assignment!, SSAValue, isassign, pc_expr, handle_err, get_return,
moduleof
using Base.Meta: isexpr
using Test, Random, SHA
function stacklength(frame)
n = 1
frame = frame.callee
while frame !== nothing
n += 1
frame = frame.callee
end
return n
end
# Execute a frame using Julia's regular compiled-code dispatch for any :call expressions
runframe(frame) = Some{Any}(finish_and_return!(Compiled(), frame))
# Execute a frame using the interpreter for all :call expressions (except builtins & intrinsics)
runstack(frame) = Some{Any}(finish_and_return!(frame))
## For juliatests.jl
function read_and_parse(filename)
src = read(filename, String)
ex = Base.parse_input_line(src; filename=filename)
end
## For running interpreter frames under resource limitations
if isdefined(Base.IRShow, :LineInfoNode)
struct Aborted # for signaling that some statement or test blocks were interrupted
at::Base.IRShow.LineInfoNode
end
else
struct Aborted # for signaling that some statement or test blocks were interrupted
at::Core.LineInfoNode
end
end
function Aborted(frame::Frame, pc)
lineidx = JuliaInterpreter.codelocs(frame, pc)
lineinfo = JuliaInterpreter.linetable(frame, lineidx; macro_caller=true)
return Aborted(lineinfo)
end
"""
ret, nstmtsleft = evaluate_limited!(recurse, frame, nstmts, istoplevel::Bool=true)
Run `frame` until one of:
- execution terminates normally (`ret = Some{Any}(val)`, where `val` is the returned value of `frame`)
- if `istoplevel` and a `thunk` or `method` expression is encountered (`ret = nothing`)
- more than `nstmts` have been executed (`ret = Aborted(lin)`, where `lnn` is the `LineInfoNode` of termination).
"""
function evaluate_limited!(@nospecialize(recurse), frame::Frame, nstmts::Int, istoplevel::Bool=false)
refnstmts = Ref(nstmts)
limexec!(s, f, istl) = limited_exec!(s, f, refnstmts, istl)
# The following is like finish!, except we intercept :call expressions so that we can run them
# with limexec! rather than the default finish_and_return!
pc = frame.pc
while nstmts > 0
shouldbreak(frame, pc) && return BreakpointRef(frame.framecode, pc), refnstmts[]
stmt = pc_expr(frame, pc)
if isa(stmt, Expr)
if stmt.head === :call && !isa(recurse, Compiled)
refnstmts[] = nstmts
try
rhs = evaluate_call!(limexec!, frame, stmt)
isa(rhs, Aborted) && return rhs, refnstmts[]
lhs = SSAValue(pc)
do_assignment!(frame, lhs, rhs)
new_pc = pc + 1
catch err
new_pc = handle_err(recurse, frame, err)
end
nstmts = refnstmts[]
elseif stmt.head === :(=) && isexpr(stmt.args[2], :call) && !isa(recurse, Compiled)
refnstmts[] = nstmts
try
rhs = evaluate_call!(limexec!, frame, stmt.args[2])
isa(rhs, Aborted) && return rhs, refnstmts[]
do_assignment!(frame, stmt.args[1], rhs)
new_pc = pc + 1
catch err
new_pc = handle_err(recurse, frame, err)
end
nstmts = refnstmts[]
elseif istoplevel && stmt.head === :thunk
code = stmt.args[1]
if length(code.code) == 1 && JuliaInterpreter.is_return(code.code[end]) && isexpr(code.code[end].args[1], :method)
# Julia 1.2+ puts a :thunk before the start of each method
new_pc = pc + 1
else
refnstmts[] = nstmts
newframe = Frame(moduleof(frame), stmt)
if isa(recurse, Compiled)
finish!(recurse, newframe, true)
else
newframe.caller = frame
frame.callee = newframe
ret = limited_exec!(recurse, newframe, refnstmts, istoplevel)
isa(ret, Aborted) && return ret, refnstmts[]
frame.callee = nothing
end
JuliaInterpreter.recycle(newframe)
# Because thunks may define new methods, return to toplevel
frame.pc = pc + 1
return nothing, refnstmts[]
end
elseif istoplevel && stmt.head === :method && length(stmt.args) == 3
step_expr!(recurse, frame, stmt, istoplevel)
frame.pc = pc + 1
return nothing, nstmts - 1
else
new_pc = step_expr!(recurse, frame, stmt, istoplevel)
nstmts -= 1
end
else
new_pc = step_expr!(recurse, frame, stmt, istoplevel)
nstmts -= 1
end
(new_pc === nothing || isa(new_pc, BreakpointRef)) && break
pc = frame.pc = new_pc
end
# Handle the return
stmt = pc_expr(frame, pc)
if nstmts == 0 && !JuliaInterpreter.is_return(stmt)
ret = Aborted(frame, pc)
return ret, nstmts
end
ret = get_return(frame)
return Some{Any}(ret), nstmts
end
evaluate_limited!(@nospecialize(recurse), modex::Tuple{Module,Expr,Frame}, nstmts::Int, istoplevel::Bool=true) =
evaluate_limited!(recurse, modex[end], nstmts, istoplevel)
evaluate_limited!(@nospecialize(recurse), modex::Tuple{Module,Expr,Expr}, nstmts::Int, istoplevel::Bool=true) =
Some{Any}(Core.eval(modex[1], modex[3])), nstmts
evaluate_limited!(frame::Union{Frame, Tuple}, nstmts::Int, istoplevel::Bool=false) =
evaluate_limited!(finish_and_return!, frame, nstmts, istoplevel)
function limited_exec!(@nospecialize(recurse), newframe, refnstmts, istoplevel)
ret, nleft = evaluate_limited!(recurse, newframe, refnstmts[], istoplevel)
refnstmts[] = nleft
return isa(ret, Aborted) ? ret : something(ret)
end
### Functions needed on workers for running tests
function configure_test()
# To run tests efficiently, certain methods must be run in Compiled mode,
# in particular those that are used by the Test infrastructure
cm = JuliaInterpreter.compiled_methods
empty!(cm)
JuliaInterpreter.set_compiled_methods()
push!(cm, which(Test.eval_test, Tuple{Expr, Expr, LineNumberNode}))
push!(cm, which(Test.get_testset, Tuple{}))
push!(cm, which(Test.push_testset, Tuple{Test.AbstractTestSet}))
push!(cm, which(Test.pop_testset, Tuple{}))
for f in (Test.record, Test.finish)
for m in methods(f)
push!(cm, m)
end
end
push!(cm, which(Random.seed!, Tuple{Union{Integer,Vector{UInt32}}}))
push!(cm, which(copy!, Tuple{Random.MersenneTwister, Random.MersenneTwister}))
push!(cm, which(copy, Tuple{Random.MersenneTwister}))
push!(cm, which(Base.include, Tuple{Module, String}))
push!(cm, which(Base.show_backtrace, Tuple{IO, Vector}))
push!(cm, which(Base.show_backtrace, Tuple{IO, Vector{Any}}))
# issue #101
push!(cm, which(SHA.update!, Tuple{SHA.SHA1_CTX,Vector{UInt8}}))
end
function run_test_by_eval(test, fullpath, nstmts)
Core.eval(Main, Expr(:toplevel, :(module JuliaTests using Test, Random end), quote
# These must be run at top level, so we can't put this in a function
println("Working on ", $test, "...")
ex = read_and_parse($fullpath)
isexpr(ex, :error) && @error "error parsing $($test): $ex"
aborts = Aborted[]
ts = Test.DefaultTestSet($test)
Test.push_testset(ts)
current_task().storage[:SOURCE_PATH] = $fullpath
modexs = collect(ExprSplitter(JuliaTests, ex))
for (i, modex) in enumerate(modexs) # having the index can be useful for debugging
nstmtsleft = $nstmts
# mod, ex = modex
# @show mod ex
frame = Frame(modex)
yield() # allow communication between processes
ret, nstmtsleft = evaluate_limited!(frame, nstmtsleft, true)
if isa(ret, Aborted)
push!(aborts, ret)
JuliaInterpreter.finish_stack!(Compiled(), frame, true)
end
end
println("Finished ", $test)
return ts, aborts
end))
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 1971 | function cleanup_coverage_files(pid)
# clean up coverage files for source code
dir, _, files = first(walkdir(normpath(@__DIR__, "..", "..", "src")))
for file in files
reg = Regex(string(".+\\.jl\\.$pid\\.cov"))
if occursin(reg, file)
rm(joinpath(dir, file))
end
end
# clean up coverage files for this file
dir, _, files = first(walkdir(@__DIR__))
for file in files
reg = Regex(string("coverage_example\\.jl\\.$pid\\.cov"))
if occursin(reg, file)
rm(joinpath(dir, file))
end
end
end
# using DiffUtils
let
local pid
try
@testset "code coverage" begin
io = Base.PipeEndpoint()
filepath = normpath(@__DIR__, "coverage_example.jl")
cmd = `$(Base.julia_cmd()) --startup=no --project=$(dirname(dirname(@__DIR__)))
--code-coverage=user $filepath`
p = run(cmd, devnull, io, stderr; wait=false)
pid = Libc.getpid(p)
@test read(io, String) == "1 2 fizz 4 "
@test success(p)
dir, _, files = first(walkdir(@__DIR__))
i = findfirst(contains(r"coverage_example\.jl\.\d+\.cov"), files)
i === nothing && error("no coverage files found in $dir: $files")
cov_file = joinpath(dir, files[i])
cov_data = read(cov_file, String)
expected = "coverage_example.jl.cov"
expected = read(joinpath(dir, expected), String)
if Sys.iswindows()
cov_data = replace(cov_data, "\r\n" => "\n")
expected = replace(cov_data, "\r\n" => "\n")
end
# if cov_data != expected
# DiffUtils.diff(cov_data, expected)
# end
@test cov_data == expected
end
finally
if @isdefined(pid)
# clean up generated files
cleanup_coverage_files(pid)
end
end
end
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | code | 312 | fizz() = print("fizz ")
buzz() = print("buzz ")
function fizzbuzz(n)
for i in 1:n
if i % 3 == 0 || i % 5 == 0
i % 3 == 0 && fizz()
i % 5 == 0 && buzz()
else
print(i, " ")
end
end
return n
end
using JuliaInterpreter
@interpret fizzbuzz(4)
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | docs | 1147 | # JuliaInterpreter
*An interpreter for Julia code.*
| **Documentation** | **Build Status** |
|:-------------------------------------------------------------------------------:|:-----------------------------------------------------------------------------------------------:|
| [![][docs-stable-img]][docs-stable-url] | [![][gh-actions-img]][gh-actions-url] [![][codecov-img]][codecov-url] |
## Installation
```jl
]add JuliaInterpreter
```
## Usage
See the [documentation][docs-stable-url].
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: https://JuliaDebug.github.io/JuliaInterpreter.jl/stable
[gh-actions-img]: https://github.com/JuliaDebug/JuliaInterpreter.jl/actions/workflows/CI.yml/badge.svg
[gh-actions-url]: https://github.com/JuliaDebug/JuliaInterpreter.jl/actions/workflows/CI.yml
[codecov-img]: https://codecov.io/gh/JuliaDebug/JuliaInterpreter.jl/branch/master/graph/badge.svg
[codecov-url]: https://codecov.io/gh/JuliaDebug/JuliaInterpreter.jl
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | docs | 279 | The benchmarks are recommended to be run using PkgBenchmark.jl as:
```
using PkgBenchmark
results = benchmarkpkg("JuliaInterpreter")
```
See the [PkgBenchmark](https://juliaci.github.io/PkgBenchmark.jl/stable/index.html) documentation for what
analysis is possible on `result`. | JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | docs | 5921 | !!! note
This page and the next are designed to teach a little more about the internals.
Depending on your interest, you may be able to skip them.
# Lowered representation
JuliaInterpreter uses the lowered representation of code.
The key advantage of lowered representation is that it is fairly well circumscribed:
- There are only a limited number of legal statements that can appear in lowered code
- Each statement is "unpacked" to essentially do one thing
- Scoping of variables is simplified via the slot mechanism, described below
- Names are fully resolved by module
- Macros are expanded
[Julia AST](https://docs.julialang.org/en/v1/devdocs/ast/) describes the kinds of
objects that can appear in lowered code.
Let's start with a demonstration on a simple function:
```julia
function summer(A::AbstractArray{T}) where T
s = zero(T)
for a in A
s += a
end
return s
end
A = [1, 2, 5]
```
To interpret lowered representation, it maybe be useful to rewrite the body of `summer` in the following ways.
First let's use an intermediate representation that expands the `for a in A ... end` loop:
```julia
s = zero(T)
temp = iterate(A) # `for` loops get lowered to `iterate/while` loops
while temp !== nothing
a, state = temp
s += a
temp = iterate(A, state)
end
return s
```
The lowered code takes the additional step of resolving the names by module and turning all the
branching into `@goto/@label` equivalents:
```julia
# Code starting at line 2 (the first line of the body)
s = Main.zero(T) # T corresponds to the first parameter, i.e., $(Expr(:static_parameter, 1))
# Code starting at line 3
temp = Base.iterate(A) # here temp = @_4
if temp === nothing # this comparison gets stored as %4, and %5 stores !(temp===nothing)
@goto block4
end
@label block2
## BEGIN block2
a, state = temp[1], temp[2] # these correspond to the `getfield` calls, state is %9
# Code starting at line 4
s = s + a
# Code starting at line 5
temp = iterate(A, state) # A is also %2
if temp === nothing
@goto block4 # the `while` condition was false
end
## END block2
@goto block2 # here the `while` condition is still true
# Code starting at line 6
@label block4
## BEGIN block4
return s
## END block4
```
This has very close correspondence to the lowered representation:
```julia
julia> code = @code_lowered debuginfo=:source summer(A)
CodeInfo(
@ REPL[1]:2 within `summer'
1 ─ s = Main.zero($(Expr(:static_parameter, 1)))
│ @ REPL[1]:3 within `summer'
│ %2 = A
│ @_4 = Base.iterate(%2)
│ %4 = @_4 === nothing
│ %5 = Base.not_int(%4)
└── goto #4 if not %5
2 ┄ %7 = @_4
│ a = Core.getfield(%7, 1)
│ %9 = Core.getfield(%7, 2)
│ @ REPL[1]:4 within `summer'
│ s = s + a
│ @_4 = Base.iterate(%2, %9)
│ %12 = @_4 === nothing
│ %13 = Base.not_int(%12)
└── goto #4 if not %13
3 ─ goto #2
@ REPL[1]:6 within `summer'
4 ┄ return s
)
```
!!! note
Not all Julia versions support `debuginfo`. If the command above fails for you,
just omit the `debuginfo=:source` portion.
To understand this package's internals, you need to familiarize yourself with these
`CodeInfo` objects.
The lines that start with `@ REPL[1]:n` indicate the source line of the succeeding
block of statements; here we defined this method in the REPL, so the source file is `REPL[1]`;
the number after the colon is the line number.
The numbers on the left correspond to [basic blocks](https://en.wikipedia.org/wiki/Basic_block),
as we annotated with `@label block2` above.
When used in statements these are printed with a hash, e.g., in `goto #4 if not %5`, the
`#4` refers to basic block 4.
The numbers in the next column--e.g., `%2`, refer to
[single static assignment (SSA) values](https://en.wikipedia.org/wiki/Static_single_assignment_form).
Each statement (each line of this printout) corresponds to a single SSA value,
but only those used later in the code are printed using assignment syntax.
Wherever a previous SSA value is used, it's referenced by an `SSAValue` and printed as `%5`;
for example, in `goto #4 if not %5`, the `%5` is the result of evaluating the 5th statement,
which is `(Base.not_int)(%4)`, which in turn refers to the result of statement 4.
Finally, temporary variables here are shown as `@_4`; the `_` indicates a *slot*, either
one of the input arguments or a local variable, and the 4 means the 4th one.
Together lines 4 and 5 correspond to `!(@_4 === nothing)`, where `@_4` has been assigned the
result of the call to `iterate` occurring on line 3. (In some Julia versions, this may be printed as `#temp#`,
similar to how we named it in our alternative implementation above.)
Let's look at a couple of the fields of the `CodeInfo`. First, the statements themselves:
```julia
julia> code.code
16-element Array{Any,1}:
:(_3 = Main.zero($(Expr(:static_parameter, 1))))
:(_2)
:(_4 = Base.iterate(%2))
:(_4 === nothing)
:(Base.not_int(%4))
:(unless %5 goto %16)
:(_4)
:(_5 = Core.getfield(%7, 1))
:(Core.getfield(%7, 2))
:(_3 = _3 + _5)
:(_4 = Base.iterate(%2, %9))
:(_4 === nothing)
:(Base.not_int(%12))
:(unless %13 goto %16)
:(goto %7)
:(return _3)
```
You can see directly that the SSA assignments are implicit; they are not directly
present in the statement list.
The most noteworthy change here is the appearance of more objects like `_3`, which are
references that index into local variable slots:
```julia
julia> code.slotnames
5-element Array{Any,1}:
Symbol("#self#")
:A
:s
Symbol("")
:a
```
When printing the whole `CodeInfo` object, these `slotnames` are substituted in
(unless they are empty, as was the case for `@_4` above).
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | docs | 2244 | # Function reference
## Running the interpreter
```@docs
@interpret
```
## Frame creation
```@docs
Frame(mod::Module, ex::Expr)
ExprSplitter
JuliaInterpreter.enter_call
JuliaInterpreter.enter_call_expr
JuliaInterpreter.prepare_frame
JuliaInterpreter.determine_method_for_expr
JuliaInterpreter.prepare_args
JuliaInterpreter.prepare_call
JuliaInterpreter.get_call_framecode
JuliaInterpreter.optimize!
```
## Frame traversal
```@docs
root
leaf
```
## Frame execution
```@docs
JuliaInterpreter.Compiled
JuliaInterpreter.step_expr!
JuliaInterpreter.finish!
JuliaInterpreter.finish_and_return!
JuliaInterpreter.finish_stack!
JuliaInterpreter.get_return
JuliaInterpreter.next_until!
JuliaInterpreter.maybe_next_until!
JuliaInterpreter.through_methoddef_or_done!
JuliaInterpreter.evaluate_call!
JuliaInterpreter.evaluate_foreigncall
JuliaInterpreter.maybe_evaluate_builtin
JuliaInterpreter.next_call!
JuliaInterpreter.maybe_next_call!
JuliaInterpreter.next_line!
JuliaInterpreter.until_line!
JuliaInterpreter.maybe_reset_frame!
JuliaInterpreter.maybe_step_through_wrapper!
JuliaInterpreter.maybe_step_through_kwprep!
JuliaInterpreter.handle_err
JuliaInterpreter.debug_command
```
## Breakpoints
```@docs
@breakpoint
@bp
breakpoint
enable
disable
remove
toggle
break_on
break_off
breakpoints
JuliaInterpreter.dummy_breakpoint
```
## Types
```@docs
Frame
JuliaInterpreter.FrameCode
JuliaInterpreter.FrameData
JuliaInterpreter._INACTIVE_EXCEPTION
JuliaInterpreter.FrameInstance
JuliaInterpreter.BreakpointState
JuliaInterpreter.BreakpointRef
JuliaInterpreter.AbstractBreakpoint
JuliaInterpreter.BreakpointSignature
JuliaInterpreter.BreakpointFileLocation
```
## Internal storage
```@docs
JuliaInterpreter.framedict
JuliaInterpreter.genframedict
JuliaInterpreter.compiled_methods
JuliaInterpreter.compiled_modules
JuliaInterpreter.interpreted_methods
```
## Utilities
```@docs
JuliaInterpreter.eval_code
JuliaInterpreter.@lookup
JuliaInterpreter.is_wrapper_call
JuliaInterpreter.is_doc_expr
JuliaInterpreter.is_global_ref
CodeTracking.whereis
JuliaInterpreter.linenumber
JuliaInterpreter.Variable
JuliaInterpreter.locals
JuliaInterpreter.whichtt
```
## Hooks
```@docs
JuliaInterpreter.on_breakpoints_updated
JuliaInterpreter.firehooks
```
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | docs | 5504 | # JuliaInterpreter
This package implements an [interpreter](https://en.wikipedia.org/wiki/Interpreter_(computing)) for Julia code.
Normally, Julia compiles your code when you first execute it; using JuliaInterpreter you can
avoid compilation and execute the expressions that define your code directly.
Interpreters have a number of applications, including support for stepping debuggers.
## Use as an interpreter
Using this package as an interpreter is straightforward:
```@repl index
using JuliaInterpreter
list = [1, 2, 5]
sum(list)
@interpret sum(list)
```
## Breakpoints
You can interrupt execution by setting breakpoints.
You can set breakpoints via packages that explicitly target debugging,
like [Juno](https://junolab.org/), [Debugger](https://github.com/JuliaDebug/Debugger.jl), and
[Rebugger](https://github.com/timholy/Rebugger.jl).
But all of these just leverage the core functionality defined in JuliaInterpreter,
so here we'll illustrate it without using any of these other packages.
Let's set a conditional breakpoint, to be triggered any time one of the elements in the
argument to `sum` is bigger than 4:
```@repl index
bp = @breakpoint sum([1, 2]) any(x->x>4, a);
```
Note that in writing the condition, we used `a`, the name of the argument to the relevant
method of `sum`. Conditionals should be written using a combination of argument and parameter
names of the method into which you're inserting a breakpoint; you can also use any
globally-available name (as used here with the `any` function).
Now let's see what happens:
```@repl index
@interpret sum([1,2,3]) # no element bigger than 4, breakpoint should not trigger
frame, bpref = @interpret sum([1,2,5]) # should trigger breakpoint
```
`frame` is described in more detail on the next page; for now, suffice it to say
that the `c` in the leftmost column indicates the presence of a conditional breakpoint
upon entry to `sum`. `bpref` is a reference to the breakpoint of type [`BreakpointRef`](@ref).
The breakpoint `bp` we created can be manipulated at the command line
```@repl index
disable(bp)
@interpret sum([1,2,5])
enable(bp)
@interpret sum([1,2,5])
```
[`disable`](@ref) and [`enable`](@ref) allow you to turn breakpoints off and on without losing any
conditional statements you may have provided; [`remove`](@ref) allows a permanent removal of
the breakpoint. You can use `remove()` to remove all breakpoints in all methods.
[`@breakpoint`](@ref) allows you to optionally specify a line number at which the breakpoint
is to be set. You can also use a functional form, [`breakpoint`](@ref), to specify file/line
combinations or that you want to break on entry to *any* method of a particular function.
At present, note that some of this functionality requires that you be running
[Revise.jl](https://github.com/timholy/Revise.jl).
It is, in addition, possible to halt execution when otherwise an error would be thrown.
This functionality is enabled using [`break_on`](@ref) and disabled with [`break_off`](@ref):
```@repl index
function f_outer()
println("before error")
f_inner()
println("after error")
end;
f_inner() = error("inner error");
break_on(:error)
fr, pc = @interpret f_outer()
leaf(fr)
typeof(pc)
pc.err
break_off(:error)
@interpret f_outer()
```
Finally, you can set breakpoints using [`@bp`](@ref):
```@repl index
function myfunction(x, y)
a = 1
b = 2
x > 3 && @bp
return a + b + x + y
end;
@interpret myfunction(1, 2)
@interpret myfunction(5, 6)
```
Here the breakpoint is marked with a `b` indicating that it is an unconditional breakpoint.
Because we placed it inside the condition `x > 3`, we've achieved a conditional outcome.
When using `@bp` in source-code files, the use of Revise is recommended,
since it allows you to add breakpoints, test code, and then remove the breakpoints from the
code without restarting Julia.
## `debug_command`
You can control execution of frames via [`debug_command`](@ref).
Authors of debugging applications should target `debug_command` for their interaction
with JuliaInterpreter.
## Hooks
Consider if you were building a debugging application with a GUI component which displays a dot in the text editor margin where a breakpoint is.
If a user creates a breakpoint not via your GUI, but rather via a command in the REPL etc.
then you still wish to keep your GUI up to date.
How to do this? The answer is hooks.
JuliaInterpreter has experimental support for having a hook, or callback function invoked
whenever the set of all breakpoints is changed.
Hook functions are setup by invoking the [`JuliaInterpreter.on_breakpoints_updated`](@ref) function.
To return to our example of keeping GUI up to date, the hooks would look something like this:
```julia
using JuliaInterpreter
using JuliaInterpreter: AbstractBreakpoint, update_states!, on_breakpoints_updated
breakpoint_gui_elements = Dict{AbstractBreakpoint, MarginDot}()
# ...
function breakpoint_gui_hook(::typeof(breakpoint), bp::AbstractBreakpoint)
bp_dot = MarginDot(bp)
draw(bp_dot)
breakpoint_gui_elements[bp] = bp_dot
end
function breakpoint_gui_hook(::typeof(remove), bp::AbstractBreakpoint)
bp_dot = pop!(breakpoint_gui_elements, bp)
undraw(bp_dot)
end
function breakpoint_gui_hook(::typeof(update_states!), bp::AbstractBreakpoint)
is_enabled = bp.enabled[]
bp_dot = breakpoint_gui_elements[bp]
set_fill!(bp_dot, is_enabled ? :blue : :grey)
end
on_breakpoints_updated(breakpoint_gui_hook)
```
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"MIT"
] | 0.9.36 | 2984284a8abcfcc4784d95a9e2ea4e352dd8ede7 | docs | 7550 | # Internals
## Basic usage
The process of executing code in the interpreter is to prepare a `frame` and then
evaluate these statements one-by-one, branching via the `goto` statements as appropriate.
Using the `summer` example described in [Lowered representation](@ref),
let's build a frame:
```julia
julia> frame = JuliaInterpreter.enter_call(summer, A)
Frame for summer(A::AbstractArray{T,N} where N) where T in Main at REPL[2]:2
1* 2 1 ─ s = (zero)($(Expr(:static_parameter, 1)))
2 3 │ %2 = A
3 3 │ #temp# = (iterate)(%2)
⋮
A = [1, 2, 5]
T = Int64
```
This is a [`Frame`](@ref). Only a portion of the `CodeInfo` is shown, a small region surrounding
the current statement (marked with `*` or in yellow text). The full `CodeInfo` can be extracted
as `code = frame.framecode.src`. (It's a slightly modified form of one returned by `@code_lowered`,
in that it has been processed by [`JuliaInterpreter.optimize!`](@ref) to speed up run-time execution.)
`frame` has another field, `framedata`, that holds values needed for or generated by execution.
The input arguments and local variables are in `locals`:
```julia
julia> frame.framedata.locals
5-element Array{Union{Nothing, Some{Any}},1}:
Some(summer)
Some([1, 2, 5])
nothing
nothing
nothing
```
These correspond to the `code.slotnames`; the first is the `#self#` argument and the second
is the input array. The remaining local variables (e.g., `s` and `a`), have not yet been assigned---we've
only built the frame, but we haven't yet begun to execute it.
The static parameter, `T`, is stored in `frame.framedata.sparams`:
```julia
julia> frame.framedata.sparams
1-element Array{Any,1}:
Int64
```
The `Expr(:static_parameter, 1)` statement refers to this value.
The other main storage is for the generated SSA values:
```julia
julia> frame.framedata.ssavalues
16-element Array{Any,1}:
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
```
Since we haven't executed any statements yet, these are all undefined.
The other main entity is the so-called [program counter](https://en.wikipedia.org/wiki/Program_counter),
which just indicates the next statement to be executed:
```julia
julia> frame.pc
1
```
Let's try executing the first statement:
```julia
julia> JuliaInterpreter.step_expr!(frame)
2
```
This indicates that it ran statement 1 and is prepared to run statement 2.
(It's worth noting that the first line included a `call` to `zero`, so behind the scenes
JuliaInterpreter created a new frame for `zero`, executed all the statements, and then popped
back to `frame`.)
Since the first statement is an assignment of a local variable, let's check the
locals again:
```julia
julia> frame.framedata.locals
5-element Array{Union{Nothing, Some{Any}},1}:
Some(summer)
Some([1, 2, 5])
Some(0)
nothing
nothing
```
You can see that the entry corresponding to `s` has been initialized.
The next statement just retrieves one of the slots (the input argument `A`) and stores
it in an SSA value:
```julia
julia> JuliaInterpreter.step_expr!(frame)
3
julia> frame.framedata.ssavalues
16-element Array{Any,1}:
#undef
[1, 2, 5]
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
```
One can easily continue this until execution completes, which is indicated when `step_expr!`
returns `nothing`. Alternatively, use the higher-level `JuliaInterpreter.finish!(frame)`
to step through the entire frame,
or `JuliaInterpreter.finish_and_return!(frame)` to also obtain the return value.
## More complex expressions
Sometimes you might have a whole sequence of expressions you want to run.
In such cases, your first thought should be to construct the `Frame` manually.
Here's a demonstration:
```@setup internals
using JuliaInterpreter;
JuliaInterpreter.clear_caches()
```
```@repl internals
using Test
ex = quote
x, y = 1, 2
@test x + y == 3
end;
frame = Frame(Main, ex);
JuliaInterpreter.finish_and_return!(frame)
```
## Toplevel code and world age
Code that defines new `struct`s, new methods, or new modules is a bit more complicated
and requires special handling. In such cases, calling `finish_and_return!` on a frame that
defines these new objects and then calls them can trigger a
[world age error](https://docs.julialang.org/en/v1/manual/methods/#Redefining-Methods-1),
in which the method is considered to be too new to be run by the currently compiled code.
While one can resolve this by using `Base.invokelatest`, we'd have to use that strategy
throughout the entire package. This would cause a major reduction in performance.
To resolve this issue without leading to performance problems, care is required to
return to "top level" after defining such objects. This leads to altered syntax for executing
such expressions.
Here's a demonstration of the problem:
```julia
ex = :(map(x->x^2, [1, 2, 3]))
frame = Frame(Main, ex)
julia> JuliaInterpreter.finish_and_return!(frame)
ERROR: this frame needs to be run a top level
```
The reason for this error becomes clearer if we examine `frame` or look directly at the lowered code:
```julia
julia> Meta.lower(Main, ex)
:($(Expr(:thunk, CodeInfo(
@ none within `top-level scope`
1 ─ $(Expr(:thunk, CodeInfo(
@ none within `top-level scope`
1 ─ global var"#3#4"
│ const var"#3#4"
│ %3 = Core._structtype(Main, Symbol("#3#4"), Core.svec(), Core.svec(), Core.svec(), false, 0)
│ var"#3#4" = %3
│ Core._setsuper!(var"#3#4", Core.Function)
│ Core._typebody!(var"#3#4", Core.svec())
└── return nothing
)))
│ %2 = Core.svec(var"#3#4", Core.Any)
│ %3 = Core.svec()
│ %4 = Core.svec(%2, %3, $(QuoteNode(:(#= REPL[18]:1 =#))))
│ $(Expr(:method, false, :(%4), CodeInfo(
@ REPL[18]:1 within `none`
1 ─ %1 = Core.apply_type(Base.Val, 2)
│ %2 = (%1)()
│ %3 = Base.literal_pow(^, x, %2)
└── return %3
)))
│ #3 = %new(var"#3#4")
│ %7 = #3
│ %8 = Base.vect(1, 2, 3)
│ %9 = map(%7, %8)
└── return %9
))))
```
All of the code before the `%7` line is devoted to defining the anonymous function `x->x^2`:
it creates a new "anonymous type" (here written as `var"#3#4"`), and then defines a "call
function" for this type, equivalent to `(var"#3#4")(x) = x^2`.
In some cases one can fix this simply by indicating that we want to run this frame at top level:
```julia
julia> JuliaInterpreter.finish_and_return!(frame, true)
3-element Array{Int64,1}:
1
4
9
```
In other cases, such as nested calls of new methods, you may need to allow the world age to update
between evaluations. In such cases you want to use `ExprSplitter`:
```julia
for (mod, e) in ExprSplitter(Main, ex)
frame = Frame(mod, e)
while true
JuliaInterpreter.through_methoddef_or_done!(frame) === nothing && break
end
JuliaInterpreter.get_return(frame)
end
```
This splits the expression into a sequence of frames (here just one, but more complex blocks may be split up into many).
Then, each frame is executed until it finishes defining a new method, then returns to top level.
The return to top level causes an update in the world age.
If the frame hasn't been finished yet (if the return value wasn't `nothing`),
this continues executing where it left off.
(Incidentally, `JuliaInterpreter.enter_call(map, x->x^2, [1, 2, 3])` works fine on its own,
because the anonymous function is defined by the caller---you'll see that the created frame
is very simple.)
| JuliaInterpreter | https://github.com/JuliaDebug/JuliaInterpreter.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | c648ac50e68ca83915706ef2c82e8d40c9541317 | code | 8878 | __precompile__(true)
module FourierSeries
using FFTW
export
fourierSeriesStepReal,
fourierSeriesSampledReal,
fourierSeriesSynthesisReal,
repeatPeriodically
@doc raw"""
# Function call
`fourierSeriesStepReal(t, u, T, hMax)`
# Description
Calculates the real Fourier coefficients of a step function `u(t)` based on
the data pairs `t` and `u` according to the following variables:
```math
\mathtt{a[k]} =
\frac{2}{\mathtt{T}} \int_{\mathtt{t[1]}}^{\mathtt{t[1]+T}}
\mathtt{u(t)} \cos(k\omega \mathtt{t}) \operatorname{d}\mathtt{t} \\
```
```math
\mathtt{b[k]} =
\frac{2}{\mathtt{T}} \int_{\mathtt{t[1]}}^{\mathtt{t[1]+T}}
\mathtt{u(t)} \sin(k\omega \mathtt{t}) \operatorname{d}\mathtt{t}
```
# Function arguments
`t` Time vector instances where a step occurs
`u` Data vector of which Fourier coefficients shall be determined of, i.e.,
`u[k]` is the data value from the right at `t[k]`
`T` Time period of `u`
`hMax` Maximum harmonic number to be determined
# Return values
`h` Vector of harmonic numbers start at, i.e., `h[1] = 0` (dc value of `u`),
`h[hMax+1] = hMax`
`f` Frequency vector associated with harmonic numbers, i.e. `f = h / T`
`a` Cosine coefficients of Fourier series, where `a[1]` = dc value of `u`
`b` Sine coefficients of Fourier series, where `b[1] = 0`
# Examples
Copy and paste code:
```julia
# Fourier approximation of square wave form
ts = [0; 1] # Sampled time data
us = [-1; 1] # Step function of square wave
T = 2 # Period
hMax = 7 # Maximum harmonic number
(h, f, a, b) = fourierSeriesStepReal(ts, us, T, hMax)
(t, u) = fourierSeriesSynthesisReal(f, a, b)
using PyPlot
# Extend (t, u) by one element to right periodically
(tx, ux) = repeatPeriodically(ts, us, right=1)
step(tx, ux, where="post") # Square wave function
plot(t, u) # Fourier approximation up to hMax = 7
```
"""
function fourierSeriesStepReal(t, u, T, hMax)
# Check if t and have equal lengths
if length(t) != length(u)
error("module FourierSeries: function fourierSeriesStepReal:\n
Vectors t and u have different lengths")
end
# Check if vector u is NOT of type Complex
if u[1] isa Complex
error("module FourierSeries: function fourierSeriesStepReal:\n
The analyzed functions `u` must not be of Type ::Complex")
end
# Determine length of function u
N = length(u)
# Initialization of real result vectors
a = zeros(hMax+1)
b = zeros(hMax+1)
# Cycle through loop to determine coefficients
i = collect(1:N)
# Time vector, extended by period T
τ = cat(t, [T + t[1]], dims = 1)
# DC value
a[1] = sum(u .* (τ[i.+1] - τ[i])) / T
b[1] = 0.0
# Harmonic coefficiens
global a, b, τ, i
for k in collect(1:hMax)
a[k+1] = sum(u .* (+sin.(k * τ[i .+ 1] * 2 * pi / T)
.- sin.(k * τ[i] * 2 * pi / T))) / (k * pi)
b[k+1] = sum(u .* (-cos.(k * τ[i .+ 1] * 2 * pi / T)
.+ cos.(k * τ[i] * 2 * pi / T))) / (k * pi)
end
# Number of harmonics
h = collect(0:hMax)
# Frequencies
f = h / T
return (h, f, a, b)
end
"""
# Function call
`fourierSeriesSampledReal(t,u,T,hMax)`
# Description
Calculates the real Fourier coefficients of a sampled function `u(t)` based
on the data pairs `t` and `u`
# Function arguments
`t` Vector of sample times
`u` Data vector of which Fourier coefficients shall be determined of, i.e.,
`u[k]` is the sampled data value associated with `t[k]`
`T` Time period of `u`
`hMax` Maximum harmonic number to be determined
# Return values
`h` Vector of harmonic numbers start at, i.e., `h[1] = 0` (dc value of `u`),
`h[hMax+1] = hMax`
`f` Frequency vector associated with harmonic numbers, i.e. `f = h / T`
`a` Cosine coefficients of Fourier series, where `a[1]` = dc value of `u`
`b` Sine coefficients of Fourier series, where `b[1] = 0`
# Examples
Copy and paste code:
```julia
# Fourier approximation of square wave form
ts = [ 0; 1; 2; 3; 4; 5; 6; 7; 8; 9] # Sampled time data
us = [-1;-1;-1;-1;-1; 1; 1; 1; 1; 1] # Step function of square wave
T = 10 # Period
hMax = 7 # Maximum harmonic number
(h, f, a, b) = fourierSeriesSampledReal(ts, us, hMax)
(t, u) = fourierSeriesSynthesisReal(f, a, b)
using PyPlot
# Extend (t, u) by one element to right periodically
(tx, ux) = repeatPeriodically(ts, us, right=1)
plot(tx, ux, marker="o") # Square wave function
plot(t, u) # Fourier approximation up to hMax = 7
```
"""
function fourierSeriesSampledReal(t, u, hMax::Int64=typemax(Int64))
# Check if vector u is NOT of type Complex
if u[1] isa Complex
error("module FourierSeries: function fourierSeriesSampledReal:\n
The analyzed functions `u` must not be of Type ::Complex")
end
# Determine length of function u
N = length(u)
# Determine period of function u
T = t[end] - t[1] + t[2] - t[1]
# Apply fast Fourier transform
c = 2 * fft(u) / N
# Correct DC value by factor 1/2
c[1] = c[1] / 2;
if mod(N,2) == 1
# Number of sampled data, N, is odd
hMaxMax = div(N-1, 2)
else
# Number of sampled data, N, is even
hMaxMax = div(N, 2)
end
# Number of harmonics
h = collect(0:hMaxMax)
# Frequencies
f = h[1:min(hMax,hMaxMax) + 1] / T
# Real and imaginary coefficients
a = +real(c[1:min(hMax,hMaxMax) + 1])
b = -imag(c[1:min(hMax,hMaxMax) + 1])
# Resize vector h
h = h[1:min(hMax,hMaxMax) + 1]
# Return vectors
return (h, f, a, b)
end
function fourierSeriesSynthesisReal(f, a, b;hMax=length(a)-1, N=1000, t0=0)
# Check if vectors f, a and b have equal lengths
if length(f) != length(a)
error("module Fourier: function fourierSeriesSynthesisReal:\n
Vectors `f` and `a` have different lengths")
end
if length(a) != length(b)
error("module Fourier: function fourierSeriesSynthesisReal:\n
Vectors `a` and `b` have different lengths")
end
# Determine Period of synthesized function
T = 1 / f[2]
# Initialization of synthesis function f
u = fill(a[1],N)
# time samples of synthesis function, considering start time t0
t = collect(0:N-1) / N * T + fill(t0, N)
# hMax may either be a scalar of vector
if hMax isa Array
# If hMax is an array, then synthesize only harmonic numbers
# indicated by hMax
kRange = hMax
else
# If hMax is a scalar, then treat hMax as the maximum harmonic
# number, which may not exceed length(a)-1, as a[1] equals the dc
# component (harmonic 0) and a[hMax-1] represents harmonic number
# hMax
kRange = collect(1:min(hMax, length(a)-1))
end
# Calculate superosition
global u, T
for k in kRange
u = u + a[k+1] * cos.(k * t * 2 * pi / T) +
b[k+1] * sin.(k * t * 2 * pi / T)
end
return (t, u)
end
function repeatPeriodically(t, u; left = 0, right = 1)
# Check if vectors t and u have equal lengths
if length(t) != length(u)
error("module Fourier: function repeatPeriodically:\n
Vectors `t` and `u` have different lengths")
end
# Determine length of arrays t and u
N = length(t)
# Determine period of time axis
T = t[end] - t[1] + t[2] - t[1]
# Determine how many times the vectors t and u shall be repeated
outerRight = Int(floor((right-1)/N) + 1)
outerLeft = Int(floor((left -1)/N) + 1)
# Repeat vector t by full periods and consider period T
tx = repeat(t, outer = outerRight+outerLeft + 1) +
repeat(collect(-outerLeft: outerRight), inner = N) * T
# Repeat vector u by full periods
ux = repeat(u, outer = outerLeft + outerRight + 1)
# Limit output vectors elements
tx = tx[outerLeft * N - left + 1:(outerLeft * N) + N + right]
ux = ux[outerLeft * N - left + 1:(outerLeft * N) + N + right]
return (tx, ux)
end
end
| FourierSeries | https://github.com/christiankral/FourierSeries.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | c648ac50e68ca83915706ef2c82e8d40c9541317 | docs | 396 | # History.md
## v0.2.4 2023-03-15
- Fix array size mismatch
## v0.2.3 2023-03-08
- Fix syntax problem in Fourier synthesis
## v0.2.2 2023-03-07
- Fix error in global variable T, which is propagated as function parameter and
must thus not be global
## v0.2.1 2023-03-07
- Minor fixing of documentation
- Fix spacing error in code
## v0.2.0 2020-08-28
## v0.1.0 2020-08-23
- Inital version
| FourierSeries | https://github.com/christiankral/FourierSeries.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | c648ac50e68ca83915706ef2c82e8d40c9541317 | docs | 1070 | # FourierSeries.jl
This is a Julia package on the analysis and synthesis of Fourier series.
The determination of Fourier coefficients is based on real value data.
The Fourier coefficients may be calculated either real of complex. The package FourierSeries.jl v0.2.0 is tested with Julia 1.5.0.
The official package FourierSeries.jl can be installed by
```julia
]
add FourierSeries
<Backspace>
```
In order to update to the actual version of GitHub use:
```julia
]
update FourierSeries
```
The module FourierSeries.jl has to be loaded by `using FourierSeries`.
# Analysis Functions
- `fourierSeriesStepReal(t,u,hMax)` This function determines the real value Fourier coefficients of a piecewise constant time domain function u(t)
- `fourierSeriesSampledReal(t,u,hMax)` This function determines the real value Fourier coefficients of a sampled time domain function u(t)
# Synthesis Functions
- `fourierSeriesSynthesisReal(f,a,b,hMax,N)` This function synthesizes the time domain function from the frequency vector and real value Fourier coefficients `a` and `b`
| FourierSeries | https://github.com/christiankral/FourierSeries.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 515 | using Lighthouse
using Documenter
makedocs(; modules=[Lighthouse], sitename="Lighthouse",
authors="Beacon Biosignals and other contributors",
pages=["API Documentation" => "index.md",
"Plotting" => "plotting.md"],
# makes docs fail hard if there is any error building the examples,
# so we don't just miss a build failure!
strict=true)
deploydocs(; repo="github.com/beacon-biosignals/Lighthouse.jl.git",
devbranch="main", push_preview=true)
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 23605 | module LighthouseMakieExt
using Makie
using Lighthouse
using Printf
using Lighthouse: has_value, evaluation_metrics
using Lighthouse: XYVector, SeriesCurves, NumberLike, NumberVector, NumberMatrix
# all the methods we're actually defining and which call each other
using Lighthouse: evaluation_metrics_plot, plot_confusion_matrix, plot_confusion_matrix!,
plot_reliability_calibration_curves, plot_reliability_calibration_curves!,
plot_binary_discrimination_calibration_curves,
plot_binary_discrimination_calibration_curves!, plot_pr_curves,
plot_pr_curves!, plot_roc_curves, plot_roc_curves!,
plot_kappas, plot_kappas!, evaluation_metrics_plot
get_parent(x::Makie.GridPosition) = x.layout.parent
#####
##### Helpers for theming and color generation...May want to move them to Colors.jl / Makie.jl
#####
using Makie.Colors: LCHab, distinguishable_colors, RGB, Colorant
function get_theme(scene, key1::Symbol, key2::Symbol; defaults...)
return get_theme(Makie.get_scene(scene), key1, key2; defaults...)
end
function get_theme(fig::GridPosition, key1::Symbol, key2::Symbol; defaults...)
return get_theme(get_parent(fig), key1, key2; defaults...)
end
# This function helps us to get the theme from a scene, that we can apply to our plotting functions
function get_theme(scene::Scene, key1::Symbol, key2::Symbol; defaults...)
scene_theme = theme(scene)
sub_theme = get(scene_theme, key1, Theme())
# The priority is key1.key2 > defaults > key2
# this way defaults are overwritten by theme options specifically set for our theme.
# Consider Kappas.Axis for key1/2, what we want is, that if there are defaults in Kappas.Axis
# they should overwrite our generic lighthouse defaults. But anything not specified in Kappas.Axis/defaults,
# should fall back to scene_theme.Axis
return merge(get(sub_theme, key2, Theme()), Theme(; defaults...),
get(scene_theme, key2, Theme()))
end
function high_contrast(background_color::Colorant, target_color::Colorant;
# chose from whole lightness spectrum
lchoices=range(0; stop=100, length=15))
target = LCHab(target_color)
color = distinguishable_colors(1, [RGB(background_color)]; dropseed=true,
lchoices=lchoices,
cchoices=[target.c], hchoices=[target.h])
return RGBAf(color[1], Makie.Colors.alpha(target_color))
end
function series_plot!(subfig::GridPosition, per_class_pr_curves::SeriesCurves,
class_labels::Union{Nothing,AbstractVector{String}}; legend=:lt,
title="No title",
xlabel="x label", ylabel="y label", solid_color=nothing,
color=nothing,
linewidth=nothing, scatter=NamedTuple())
axis_theme = get_theme(subfig, :SeriesPlot, :Axis; title=title, titlealign=:left,
xlabel=xlabel,
ylabel=ylabel, aspect=AxisAspect(1),
xticks=0:0.2:1, yticks=0.2:0.2:1)
ax = Axis(subfig; axis_theme...)
# Not the most elegant, but this way we can let the theming to the Series theme, or
# pass it through explicitely
series_theme = get_theme(subfig, :SeriesPlot, :Series; scatter...)
isnothing(solid_color) || (series_theme[:solid_color] = solid_color)
isnothing(color) || (series_theme[:color] = color)
isnothing(linewidth) || (series_theme[:linewidth] = linewidth)
series_theme = merge(series_theme, Attributes(; scatter...))
hidedecorations!(ax; label=false, ticklabels=false, grid=false)
limits!(ax, 0, 1, 0, 1)
Makie.series!(ax, per_class_pr_curves; labels=class_labels, series_theme...)
if !isnothing(legend)
axislegend(ax; position=legend)
end
return ax
end
function Lighthouse.plot_pr_curves!(subfig::GridPosition, per_class_pr_curves::SeriesCurves,
class_labels::Union{Nothing,AbstractVector{String}};
legend=:lt,
title="PR curves",
xlabel="True positive rate", ylabel="Precision",
scatter=NamedTuple(),
solid_color=nothing)
return series_plot!(subfig, per_class_pr_curves, class_labels; legend=legend,
title=title, xlabel=xlabel,
ylabel=ylabel, scatter=scatter, solid_color=solid_color)
end
function Lighthouse.plot_roc_curves!(subfig::GridPosition,
per_class_roc_curves::SeriesCurves,
per_class_roc_aucs::NumberVector,
class_labels::AbstractVector{<:String};
legend=:rb, title="ROC curves",
xlabel="False positive rate",
ylabel="True positive rate")
auc_labels = [@sprintf("%s (AUC: %.3f)", class, per_class_roc_aucs[i])
for (i, class) in enumerate(class_labels)]
return series_plot!(subfig, per_class_roc_curves, auc_labels; legend=legend,
title=title, xlabel=xlabel,
ylabel=ylabel)
end
function Lighthouse.plot_reliability_calibration_curves!(subfig::GridPosition,
per_class_reliability_calibration_curves::SeriesCurves,
per_class_reliability_calibration_scores::NumberVector,
class_labels::AbstractVector{String};
legend=:rb)
calibration_score_labels = map(enumerate(class_labels)) do (i, class)
@sprintf("%s (MSE: %.3f)", class, per_class_reliability_calibration_scores[i])
end
scatter_theme = get_theme(subfig, :ReliabilityCalibrationCurves, :Scatter;
marker=Circle,
markersize=5, strokewidth=0)
ideal_theme = get_theme(subfig, :ReliabilityCalibrationCurves, :Ideal;
color=(:black, 0.5),
linestyle=:dash, linewidth=2)
ax = series_plot!(subfig, per_class_reliability_calibration_curves,
calibration_score_labels;
legend=legend, title="Prediction reliability calibration",
xlabel="Predicted probability bin", ylabel="Fraction of positives",
scatter=scatter_theme)
#TODO: mean predicted value histogram underneath?? Maybe important...
# https://scikit-learn.org/stable/modules/calibration.html
linesegments!(ax, [0, 1], [0, 1]; ideal_theme...)
return ax
end
function set_from_kw!(theme, key, kw, default)
if haskey(kw, key)
theme[key] = getproperty(kw, key)
elseif !haskey(theme, key)
theme[key] = default
end
return
end
function Lighthouse.plot_binary_discrimination_calibration_curves!(subfig::GridPosition,
calibration_curve::SeriesCurves,
calibration_score,
per_expert_calibration_curves::Union{SeriesCurves,
Missing},
per_expert_calibration_scores,
optimal_threshold,
discrimination_class::AbstractString;
kw...)
kw = values(kw)
scatter_theme = get_theme(subfig, :BinaryDiscriminationCalibrationCurves, :Scatter;
strokewidth=0)
# Hayaah, this theme merging is getting out of hand
# but we want kw > BinaryDiscriminationCalibrationCurves > Scatter, so we need to somehow set things
# after the theme merging above, especially, since we also pass those to series!,
# which then again tries to merge the kw args with the theme.
set_from_kw!(scatter_theme, :markersize, kw, 5)
set_from_kw!(scatter_theme, :marker, kw, :rect)
if ismissing(per_expert_calibration_curves)
ax = Axis(subfig; title="Detection calibration", xlabel="Expert agreement rate",
ylabel="Predicted positive probability")
else
per_expert = get_theme(subfig, :BinaryDiscriminationCalibrationCurves, :PerExpert;
solid_color=:darkgrey, color=nothing)
set_from_kw!(per_expert, :linewidth, kw, 2)
ax = series_plot!(subfig, per_expert_calibration_curves, nothing; legend=nothing,
title="Detection calibration", xlabel="Expert agreement rate",
ylabel="Predicted positive probability", scatter=scatter_theme,
per_expert...)
end
calibration = get_theme(subfig, :BinaryDiscriminationCalibrationCurves,
:CalibrationCurve;
solid_color=:navyblue)
set_from_kw!(calibration, :markersize, kw, 5)
set_from_kw!(calibration, :marker, kw, :rect)
set_from_kw!(calibration, :linewidth, kw, 2)
Makie.series!(ax, calibration_curve; calibration...)
ideal_theme = get_theme(subfig, :BinaryDiscriminationCalibrationCurves, :Ideal;
color=(:black, 0.5),
linestyle=:dash)
set_from_kw!(ideal_theme, :linewidth, kw, 2)
linesegments!(ax, [0, 1], [0, 1]; label="Ideal", ideal_theme...)
#TODO: expert agreement histogram underneath?? Maybe important...
# https://scikit-learn.org/stable/modules/calibration.html
return ax
end
function Lighthouse.plot_confusion_matrix!(subfig::GridPosition, confusion::NumberMatrix,
class_labels::AbstractVector{String},
normalize_by::Union{Symbol,Nothing}=nothing;
annotation_text_size=20, colormap=:Blues)
nclasses = length(class_labels)
if size(confusion) != (nclasses, nclasses)
throw(ArgumentError("Labels must match size of square confusion matrix. Found $(nclasses) labels for an $(size(confusion)) matrix"))
end
title = "Confusion Matrix"
if !isnothing(normalize_by)
normdim = get((Row=2, Column=1), normalize_by) do
throw(ArgumentError("normalize_by must be :Row, :Column, or `nothing`; found: $(normalize_by)"))
end
confusion = round.(confusion ./ sum(confusion; dims=normdim); digits=3)
title = "$(string(normalize_by))-Normalized Confusion"
end
class_indices = 1:nclasses
text_theme = get_theme(subfig, :ConfusionMatrix, :Text; fontsize=annotation_text_size)
heatmap_theme = get_theme(subfig, :ConfusionMatrix, :Heatmap; nan_color=(:black, 0.0))
axis_theme = get_theme(subfig, :ConfusionMatrix, :Axis; xticklabelrotation=pi / 4,
titlealign=:left, title,
xlabel="Elected Class", ylabel="Predicted Class",
xticks=(class_indices, class_labels),
yticks=(class_indices, class_labels),
aspect=AxisAspect(1))
ax = Axis(subfig; axis_theme...)
hidedecorations!(ax; label=false, ticklabels=false, grid=false)
ylims!(ax, nclasses + 0.5, 0.5)
tightlimits!(ax)
plot_bg_color = to_color(ax.backgroundcolor[])
crange = isnothing(normalize_by) ? (0.0, maximum(filter(!isnan, confusion))) :
(0.0, 1.0)
nan_color = to_color(heatmap_theme.nan_color[])
cmap = to_colormap(to_value(pop!(heatmap_theme, :colormap, colormap)))
heatmap!(ax, confusion'; colorrange=crange, colormap=cmap, nan_color=nan_color,
heatmap_theme...)
text_color = to_color(to_value(pop!(text_theme, :color, :black)))
function label_color(i, j)
c = confusion[i, j]
bg_color = if isnan(c) || ismissing(c)
Makie.Colors.alpha(nan_color) <= 0.0 ? plot_bg_color : nan_color
else
Makie.interpolated_getindex(cmap, c, crange)
end
return high_contrast(bg_color, text_color)
end
annos = vec([(string(confusion[i, j]), Point2f(j, i))
for i in class_indices, j in class_indices])
colors = vec([label_color(i, j) for i in class_indices, j in class_indices])
text!(ax, annos; align=(:center, :center), color=colors, fontsize=annotation_text_size,
text_theme...)
return ax
end
function text_attributes(values, groups, bar_colors, bg_color, text_color)
aligns = NTuple{2,Symbol}[]
offsets = NTuple{2,Int}[]
text_colors = RGBAf[]
for (i, k) in enumerate(values)
group = groups isa AbstractVector ? groups[i] : groups
bar_color = bar_colors[group]
# Plot text inside bar
if k > 0.85
push!(aligns, (:right, :center))
push!(offsets, (-10, 0))
push!(text_colors, high_contrast(bar_color, text_color))
else
# plot text next to bar
push!(aligns, (:left, :center))
push!(offsets, (10, 0))
push!(text_colors, high_contrast(bg_color, text_color))
end
end
return aligns, offsets, text_colors
end
function Lighthouse.plot_kappas!(subfig::GridPosition, per_class_kappas::NumberVector,
class_labels::AbstractVector{String},
per_class_IRA_kappas=nothing;
color=[:lightgrey, :lightblue], annotation_text_size=20)
nclasses = length(class_labels)
axis_theme = get_theme(subfig, :Kappas, :Axis; aspect=AxisAspect(1), titlealign=:left,
xlabel="Cohen's kappa", xticks=[0, 1], yreversed=true,
yticks=(1:nclasses, class_labels))
text_theme = get_theme(subfig, :Kappas, :Text; fontsize=annotation_text_size)
text_color = to_color(to_value(pop!(text_theme, :color, to_color(:black))))
bars_theme = get_theme(subfig, :Kappas, :BarPlot; color=color)
bar_colors = to_color.(bars_theme.color[])
ax = Axis(subfig[1, 1]; axis_theme...)
bg_color = to_color(ax.backgroundcolor[])
xlims!(ax, 0, 1)
if !has_value(per_class_IRA_kappas)
ax.title = "Algorithm-expert agreement"
annotations = map(enumerate(per_class_kappas)) do (i, k)
return (string(round(k; digits=3)), Point2f(max(0, k), i))
end
aligns, offsets, text_colors = text_attributes(per_class_kappas, 2, bar_colors,
bg_color, text_color)
barplot!(ax, per_class_kappas; direction=:x, color=bar_colors[2])
text!(ax, annotations; align=aligns, offset=offsets, color=text_colors,
text_theme...)
else
ax.title = "Inter-rater reliability"
values = vcat(per_class_kappas, per_class_IRA_kappas)
groups = vcat(fill(2, nclasses), fill(1, nclasses))
xvals = vcat(1:nclasses, 1:nclasses)
cmap = bar_colors
bars = barplot!(ax, xvals, max.(0, values); dodge=groups, color=groups,
direction=:x,
colormap=cmap)
# This is a bit hacky, but for now the easiest way to figure out the exact, dodged positions
rectangles = bars.plots[][1][]
dodged_y = last.(minimum.(rectangles)) .+ (last.(widths.(rectangles)) ./ 2)
textpos = Point2f.(max.(0, values), dodged_y)
labels = string.(round.(values; digits=3))
aligns, offsets, text_colors = text_attributes(values, groups, bar_colors, bg_color,
text_color)
text!(ax, labels; position=textpos, align=aligns, offset=offsets, color=text_colors,
text_theme...)
labels = ["Expert-vs-expert IRA", "Algorithm-vs-expert"]
entries = map(c -> PolyElement(; color=c, strokewidth=0, strokecolor=:white), cmap)
legend = Legend(subfig[1, 1, Bottom()], entries, labels; tellwidth=false,
tellheight=true,
labelsize=12, padding=(0, 0, 0, 0), framevisible=false,
patchsize=(10, 10),
patchlabelgap=6, labeljustification=:left)
legend.margin = (0, 0, 0, 60)
end
return ax
end
function Lighthouse.evaluation_metrics_plot(data::Dict; kwargs...)
return evaluation_metrics_plot(EvaluationV1(data); kwargs...)
end
function Lighthouse.evaluation_metrics_plot(row::EvaluationV1; size=(1000, 1000),
fontsize=12)
fig = Figure(; size=size, Axis=(titlesize=17,))
# Confusion
plot_confusion_matrix!(fig[1, 1], row.confusion_matrix, row.class_labels,
:Column;
annotation_text_size=fontsize)
plot_confusion_matrix!(fig[1, 2], row.confusion_matrix, row.class_labels, :Row;
annotation_text_size=fontsize)
# Kappas
IRA_kappa_data = nothing
multiclass = length(row.class_labels) > 2
labels = multiclass ? vcat("Multiclass", row.class_labels) : row.class_labels
kappa_data = multiclass ? vcat(row.multiclass_kappa, row.per_class_kappas) :
row.per_class_kappas
if issubset([:multiclass_IRA_kappas, :per_class_IRA_kappas], keys(row)) &&
all(has_value.([row.multiclass_IRA_kappas, row.per_class_IRA_kappas]))
IRA_kappa_data = multiclass ?
vcat(row.multiclass_IRA_kappas, row.per_class_IRA_kappas) :
row.per_class_IRA_kappas
end
plot_kappas!(fig[1, 3], kappa_data, labels, IRA_kappa_data;
annotation_text_size=fontsize)
# Curves
ax = plot_roc_curves!(fig[2, 1], row.per_class_roc_curves,
row.per_class_roc_aucs,
row.class_labels; legend=nothing)
plot_pr_curves!(fig[2, 2], row.per_class_pr_curves, row.class_labels;
legend=nothing)
plot_reliability_calibration_curves!(fig[3, 1],
row.per_class_reliability_calibration_curves,
row.per_class_reliability_calibration_scores,
row.class_labels; legend=nothing)
legend_pos = 2:3
if has_value(row.discrimination_calibration_curve)
legend_pos = 3
plot_binary_discrimination_calibration_curves!(fig[3, 2],
row.discrimination_calibration_curve,
row.discrimination_calibration_score,
row.per_expert_discrimination_calibration_curves,
row.per_expert_discrimination_calibration_scores,
row.optimal_threshold,
row.class_labels[row.optimal_threshold_class])
end
legend_plots = filter(Makie.get_plots(ax)) do plot
return haskey(plot, :label)
end
elements = map(legend_plots) do elem
return [PolyElement(; color=elem.color, strokecolor=:transparent)]
end
function label_str(i)
auc = round(row.per_class_roc_aucs[i]; digits=2)
mse = round(row.per_class_reliability_calibration_scores[i]; digits=2)
return ["""ROC AUC $auc
Cal. MSE $mse
"""]
end
classes = row.class_labels
nclasses = length(classes)
class_labels = label_str.(1:nclasses)
Legend(fig[3, legend_pos], elements, class_labels, classes; nbanks=2, tellwidth=false,
tellheight=false,
labelsize=11, titlesize=14, titlegap=5, groupgap=6, labelhalign=:left,
labelvalign=:center)
colgap!(fig.layout, 2)
rowgap!(fig.layout, 4)
return fig
end
# Helper to more easily define the non mutating versions
function axisplot(func, args; size=(800, 600), plot_kw...)
fig = Figure(; size=size)
ax = func(fig[1, 1], args...; plot_kw...)
# ax.plots[1] is not really that great, but there isn't a FigureAxis object right now
# this will need to wait for when we figure out a better recipe integration
return Makie.FigureAxisPlot(fig, ax, ax.scene.plots[1])
end
function Lighthouse.plot_confusion_matrix(args...; kw...)
return axisplot(plot_confusion_matrix!, args;
kw...)
end
function Lighthouse.plot_reliability_calibration_curves(args...; kw...)
return axisplot(plot_reliability_calibration_curves!, args; kw...)
end
function Lighthouse.plot_binary_discrimination_calibration_curves(args...; kw...)
return axisplot(plot_binary_discrimination_calibration_curves!, args; kw...)
end
Lighthouse.plot_pr_curves(args...; kw...) = axisplot(plot_pr_curves!, args; kw...)
Lighthouse.plot_roc_curves(args...; kw...) = axisplot(plot_roc_curves!, args; kw...)
Lighthouse.plot_kappas(args...; kw...) = axisplot(plot_kappas!, args; kw...)
#####
##### Deprecation support
#####
function Lighthouse.evaluation_metrics_plot(predicted_hard_labels::AbstractVector,
predicted_soft_labels::AbstractMatrix,
elected_hard_labels::AbstractVector, classes,
thresholds;
votes::Union{Nothing,AbstractMatrix}=nothing,
strata::Union{Nothing,
AbstractVector{Set{T}} where T}=nothing,
optimal_threshold_class::Union{Nothing,Integer}=nothing)
Base.depwarn("""
```
evaluation_metrics_plot(predicted_hard_labels::AbstractVector,
predicted_soft_labels::AbstractMatrix,
elected_hard_labels::AbstractVector, classes, thresholds;
votes::Union{Nothing,AbstractMatrix}=nothing,
strata::Union{Nothing,AbstractVector{Set{T}} where T}=nothing,
optimal_threshold_class::Union{Nothing,Integer}=nothing)
```
has been deprecated in favor of
```
plot_dict = evaluation_metrics(predicted_hard_labels, predicted_soft_labels,
elected_hard_labels, classes, thresholds;
votes, strata, optimal_threshold_class)
(evaluation_metrics_plot(plot_dict), plot_dict)
```
""", :evaluation_metrics_plot)
plot_dict = evaluation_metrics(predicted_hard_labels, predicted_soft_labels,
elected_hard_labels, classes, thresholds; votes, strata,
optimal_threshold_class)
return evaluation_metrics_plot(plot_dict), plot_dict
end
end # module
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 293 | using JuliaFormatter
function main()
perfect = format(joinpath(@__DIR__, ".."); style=YASStyle())
if perfect
@info "Linting complete - no files altered"
else
@info "Linting complete - files altered"
run(`git status`)
end
return nothing
end
main()
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 3465 | #####
##### `LearnLogger` implementation of logging interface
#####
"""
LearnLogger
A struct that wraps a `TensorBoardLogger.TBLogger` in order to enforce the following:
- all values logged to Tensorboard should be accessible to the `post_epoch_callback`
argument to [`learn!`](@ref)
- all values that are cached during [`learn!`](@ref) should be logged to Tensorboard
To access values logged to a `LearnLogger` instance, inspect the instance's `logged` field.
"""
struct LearnLogger
path::String
tensorboard_logger::TensorBoardLogger.TBLogger
logged::Dict{String,Vector{Any}}
end
function LearnLogger(path, run_name; kwargs...)
tensorboard_logger = TBLogger(joinpath(path, run_name); kwargs...)
return LearnLogger(path, tensorboard_logger, Dict{String,Any}())
end
function log_value!(logger::LearnLogger, field::AbstractString, value)
values = get!(() -> Any[], logger.logged, field)
push!(values, value)
TensorBoardLogger.log_value(logger.tensorboard_logger, field, value;
step=length(values))
return value
end
function log_event!(logger::LearnLogger, value::AbstractString)
logged = string(now(), " | ", value)
TensorBoardLogger.log_text(logger.tensorboard_logger, "events", logged)
return logged
end
function log_plot!(logger::LearnLogger, field::AbstractString, plot, plot_data)
values = get!(() -> Any[], logger.logged, field)
push!(values, plot_data)
TensorBoardLogger.log_image(logger.tensorboard_logger, field, plot; step=length(values))
return plot
end
function log_line_series!(logger::LearnLogger, field::AbstractString, curves,
labels=1:length(curves))
@warn "`log_line_series!` not implemented for `LearnLogger`" maxlog = 1
return nothing
end
"""
Base.flush(logger::LearnLogger)
Persist possibly transient logger state.
"""
Base.flush(logger::LearnLogger) = nothing
"""
forwarding_task = forward_logs(channel, logger::LearnLogger)
Forwards logs with values supported by `TensorBoardLogger` to `logger::LearnLogger`:
- string events of type `AbstractString`
- scalars of type `Union{Real,Complex}`
- plots that `TensorBoardLogger` can convert to raster images
returns the `forwarding_task:::Task` that does the forwarding.
To cleanly stop forwarding, `close(channel)` and `wait(forwarding_task)`.
outbox is a Channel or RemoteChannel of Pair{String, Any}
field names starting with "__plot__" forward to TensorBoardLogger.log_image
"""
function forward_logs(outbox, logger::LearnLogger)
@async try
while true
(field, value) = take!(outbox)
if typeof(value) <: AbstractString
log_event!(logger, value)
elseif startswith(field, "__plot__")
original_field = field[9:end]
values = get!(() -> Any[], logger.logged, original_field)
TensorBoardLogger.log_image(logger.tensorboard_logger, original_field,
value; step=length(values))
elseif typeof(value) <: Union{Real,Complex}
log_value!(logger, field, value)
end
end
catch e
if !(isa(e, InvalidStateException) && e.state == :closed)
@error "error forwarding logs, STOPPING FORWARDING!" exception = (e,
catch_backtrace())
end
end
end
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 1261 | module Lighthouse
using Statistics, Dates, LinearAlgebra, Random, Logging
using Base.Threads
using StatsBase: StatsBase
using TensorBoardLogger
using Printf
using Legolas: Legolas, @schema, @version, lift
using Tables
using DataFrames
using ArrowTypes
include("row.jl")
export EvaluationV1, ObservationV1, Curve, TradeoffMetricsV1, HardenedMetricsV1,
LabelMetricsV1
include("plotting.jl")
include("utilities.jl")
export majority
include("metrics.jl")
export confusion_matrix, accuracy, binary_statistics, cohens_kappa, calibration_curve,
get_tradeoff_metrics, get_tradeoff_metrics_binary_multirater, get_hardened_metrics,
get_hardened_metrics_multirater, get_hardened_metrics_multiclass,
get_label_metrics_multirater, get_label_metrics_multirater_multiclass,
harden_by_threshold
include("classifier.jl")
export AbstractClassifier
include("LearnLogger.jl")
export LearnLogger
include("learn.jl")
export learn!, upon, evaluate!, predict!
export log_event!, log_line_series!, log_plot!, step_logger!, log_value!, log_values!
export log_array!, log_arrays!
include("deprecations.jl")
@static if !isdefined(Base, :get_extension)
include("../ext/LighthouseMakieExt.jl")
using .LighthouseMakieExt
end
end # module
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 3794 | #####
##### `AbstractClassifier` Interface
#####
# This section contains all the functions that new `AbstractClassifier` subtypes
# should overload in order to utilize common Lighthouse functionality
"""
AbstractClassifier
An abstract type whose subtypes `C<:AbstractClassifier` must implement:
- [`Lighthouse.classes`](@ref)
- [`Lighthouse.train!`](@ref)
- [`Lighthouse.loss_and_prediction`](@ref)
Subtypes may additionally overload default implementations for:
- [`Lighthouse.onehot`](@ref)
- [`Lighthouse.onecold`](@ref)
- [`Lighthouse.is_early_stopping_exception`](@ref)
The `AbstractClassifier` interface is built upon the expectation that any
multiclass label will be represented in one of two standardized forms:
- "soft label": a probability distribution vector where the `i`th element is the
probability assigned to the `i`th class in `classes(classifier)`.
- "hard label": the interger index of a corresponding class in `classes(classifier)`.
Internally, Lighthouse converts hard labels to soft labels via `onehot` and soft
labels to hard labels via `onecold`.
See also: [`learn!`](@ref)
"""
abstract type AbstractClassifier end
"""
Lighthouse.classes(classifier::AbstractClassifier)
Return a `Vector` or `Tuple` of class values for `classifier`.
This method must be implemented for each `AbstractClassifier` subtype.
"""
function classes end
"""
Lighthouse.train!(classifier::AbstractClassifier, batches, logger)
Train `classifier` on the iterable `batches` for a single epoch. This function
is called once per epoch by [`learn!`](@ref).
This method must be implemented for each `AbstractClassifier` subtype. Implementers
should ensure that the training loss is properly logged to `logger` by calling
`Lighthouse.log_value!(logger, "train/loss_per_batch", batch_loss)` for
each batch in `batches`.
"""
function train! end
"""
Lighthouse.loss_and_prediction(classifier::AbstractClassifier,
input_batch::AbstractArray,
args...)
Return `(loss, soft_label_batch)` given `input_batch` and any additional `args`
provided by the caller; `loss` is a scalar, which `soft_label_batch` is a matrix
with `length(classes(classifier))` rows and `size(input_batch)`.
Specifically, the `i`th column of `soft_label_batch` is `classifier`'s soft
label prediction for the `i`th sample in `input_batch`.
This method must be implemented for each `AbstractClassifier` subtype.
"""
function loss_and_prediction end
"""
Lighthouse.onehot(classifier::AbstractClassifier, hard_label)
Return the one-hot encoded probability distribution vector corresponding to the
given `hard_label`. `hard_label` must be an integer index in the range
`1:length(classes(classifier))`.
"""
function onehot(classifier::AbstractClassifier, hard_label)
result = fill(false, length(classes(classifier)))
result[hard_label] = true
return result
end
"""
Lighthouse.onecold(classifier::AbstractClassifier, soft_label)
Return the hard label (integer index in the range `1:length(classes(classifier))`)
corresponding to the given `soft_label` (one-hot encoded probability distribution vector).
By default, this function returns `argmax(soft_label)`.
"""
onecold(classifier::AbstractClassifier, soft_label) = argmax(soft_label)
"""
Lighthouse.is_early_stopping_exception(classifier::AbstractClassifier, exception)
Return `true` if `exception` should be considered an "early-stopping exception"
(e.g. `Flux.Optimise.StopException`), rather than rethrown from [`learn!`](@ref).
This function returns `false` by default, but can be overloaded by subtypes of
`AbstractClassifier` that employ exceptions as early-stopping mechanisms.
"""
is_early_stopping_exception(::AbstractClassifier, ::Any) = false
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 208 | function evaluation_metrics_row(args...; kwargs...)
error("`Lighthouse.evaluation_metrics_row` has been removed in favor of " *
"`Lighthouse.evaluation_metrics_record`.")
return nothing
end
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 16996 | #####
##### Logging interface
#####
# These must be implemented by every logger type.
"""
log_plot!(logger, field::AbstractString, plot, plot_data)
Log a `plot` to `logger` under field `field`.
* `plot`: the plot itself
* `plot_data`: an unstructured dictionary of values used in creating `plot`.
See also [`log_line_series!`](@ref).
"""
log_plot!(logger, field::AbstractString, plot, plot_data)
"""
log_value!(logger, field::AbstractString, value)
Log a value `value` to `field`.
"""
log_value!(logger, field::AbstractString, value)
"""
log_line_series!(logger, field::AbstractString, curves, labels=1:length(curves))
Logs a series plot to `logger` under `field`, where...
- `curves` is an iterable of the form `Tuple{Vector{Real},Vector{Real}}`, where each tuple contains `(x-values, y-values)`, as in the `Lighthouse.EvaluationV1` field `per_class_roc_curves`
- `labels` is the class label for each curve, which defaults to the numeric index of each curve.
"""
log_line_series!(logger, field::AbstractString, curves, labels=1:length(curves))
# The following have default implementations.
"""
step_logger!(logger)
Increments the `logger`'s `step`, if any. Defaults to doing nothing.
"""
step_logger!(::Any) = nothing
"""
log_event!(logger, value::AbstractString)
Logs a string event given by `value` to `logger`. Defaults to calling `log_value!` with a field named `event`.
"""
function log_event!(logger, value::AbstractString)
return log_value!(logger, "event", string(now(), " | ", value))
end
"""
log_values!(logger, values)
Logs an iterable of `(field, value)` pairs to `logger`. Falls back to calling `log_value!` in a loop.
Loggers may specialize this method for improved performance.
"""
function log_values!(logger, values)
for (k, v) in values
log_value!(logger, k, v)
end
return nothing
end
"""
log_array!(logger::Any, field::AbstractString, value)
Log an array `value` to `field`.
Defaults to `log_value!(logger, mean(value))`.
"""
function log_array!(logger::Any, field::AbstractString, array)
return log_value!(logger, field, mean(array))
end
"""
log_arrays!(logger, values)
Logs an iterable of `(field, array)` pairs to `logger`. Falls back to calling `log_array!` in a loop.
Loggers may specialize this method for improved performance.
"""
function log_arrays!(logger, values)
for (k, v) in values
log_array!(logger, k, v)
end
return nothing
end
"""
log_evaluation_row!(logger, field::AbstractString, metrics)
From fields in [`EvaluationV1`](@ref), generate and plot the composite [`evaluation_metrics_plot`](@ref)
as well as `spearman_correlation` (if present).
"""
function log_evaluation_row!(logger, field::AbstractString, metrics)
metrics_plot = evaluation_metrics_plot(metrics)
metrics_dict = _evaluation_dict(metrics)
log_plot!(logger, field, metrics_plot, metrics_dict)
if haskey(metrics_dict, "spearman_correlation")
sp_field = replace(field, "metrics" => "spearman_correlation")
log_value!(logger, sp_field, metrics_dict["spearman_correlation"].ρ)
end
return metrics_plot
end
function log_resource_info!(logger, section::AbstractString, info::ResourceInfo;
suffix::AbstractString="")
log_values!(logger,
(section * "/time_in_seconds" * suffix => info.time_in_seconds,
section * "/gc_time_in_seconds" * suffix => info.gc_time_in_seconds,
section * "/allocations" * suffix => info.allocations,
section * "/memory_in_mb" * suffix => info.memory_in_mb))
return info
end
function log_resource_info!(f, logger, section::AbstractString; suffix::AbstractString="")
result, resource_info = call_with_resource_info(f)
log_resource_info!(logger, section, resource_info; suffix=suffix)
return result
end
#####
##### `predict!!`
#####
"""
predict!(model::AbstractClassifier,
predicted_soft_labels::AbstractMatrix,
batches, logger::LearnLogger;
logger_prefix::AbstractString)
Return `mean_loss` of all `batches` after using `model` to predict their soft labels
and storing those results in `predicted_soft_labels`.
The following quantities are logged to `logger`:
- `<logger_prefix>/loss_per_batch`
- `<logger_prefix>/mean_loss_per_epoch`
- `<logger_prefix>/\$resource_per_batch`
Where...
- `model` is a model that outputs soft labels when called on a batch of `batches`,
`model(batch)`.
- `predicted_soft_labels` is a matrix whose columns correspond to classes and
whose rows correspond to samples in batches, and which is filled in with soft-label
predictions.
- `batches` is an iterable of batches, where each element of
the iterable takes the form `(batch, votes_locations)`. Internally, `batch` is
passed to [`loss_and_prediction`](@ref) as `loss_and_prediction(model, batch...)`.
"""
function predict!(model::AbstractClassifier, predicted_soft_labels::AbstractMatrix, batches,
logger; logger_prefix::AbstractString)
losses = Float32[]
for (batch, votes_locations) in batches
batch_loss = log_resource_info!(logger, logger_prefix; suffix="_per_batch") do
batch_loss, soft_label_batch = loss_and_prediction(model, batch...)
for (i, soft_label) in enumerate(eachcol(soft_label_batch))
predicted_soft_labels[votes_locations[i], :] = soft_label
end
return batch_loss
end
log_value!(logger, logger_prefix * "/loss_per_batch", batch_loss)
push!(losses, batch_loss)
end
mean_loss = mean(losses)
log_value!(logger, logger_prefix * "/mean_loss_per_epoch", mean_loss)
return mean_loss
end
#####
##### `evaluate!`
#####
"""
evaluate!(predicted_hard_labels::AbstractVector,
predicted_soft_labels::AbstractMatrix,
elected_hard_labels::AbstractVector,
classes, logger;
logger_prefix, logger_suffix,
votes::Union{Nothing,AbstractMatrix}=nothing,
thresholds=0.0:0.01:1.0,
optimal_threshold_class::Union{Nothing,Integer}=nothing)
Return `nothing` after computing and logging a battery of classifier performance
metrics that each compare `predicted_soft_labels` and/or `predicted_hard_labels`
agaist `elected_hard_labels`.
The following quantities are logged to `logger`:
- `<logger_prefix>/metrics<logger_suffix>`
- `<logger_prefix>/\$resource<logger_suffix>`
Where...
- `predicted_soft_labels` is a matrix of soft labels whose columns correspond to
classes and whose rows correspond to samples in the evaluation set.
- `predicted_hard_labels` is a vector of hard labels where the `i`th element
is the hard label predicted by the model for sample `i` in the evaulation set.
- `elected_hard_labels` is a vector of hard labels where the `i`th element
is the hard label elected as "ground truth" for sample `i` in the evaulation set.
- `thresholds` are the range of thresholds used by metrics (e.g. PR curves) that
are calculated on the `predicted_soft_labels` for a range of thresholds.
- `votes` is a matrix of hard labels whose columns correspond to voters and whose
rows correspond to the samples in the test set that have been voted on. If
`votes[sample, voter]` is not a valid hard label for `model`, then `voter` will
simply be considered to have not assigned a hard label to `sample`.
- `optimal_threshold_class` is the class index (`1` or `2`) for which to calculate
an optimal threshold for converting the `predicted_soft_labels` to
`predicted_hard_labels`. If present, the input `predicted_hard_labels` will be
ignored and new `predicted_hard_labels` will be recalculated from the new threshold.
This is only a valid parameter when `length(classes) == 2`
"""
function evaluate!(predicted_hard_labels::AbstractVector,
predicted_soft_labels::AbstractMatrix,
elected_hard_labels::AbstractVector, classes, logger;
logger_prefix::AbstractString, logger_suffix::AbstractString="",
votes::Union{Nothing,Missing,AbstractMatrix}=nothing,
thresholds=0.0:0.01:1.0,
optimal_threshold_class::Union{Nothing,Integer,Missing}=nothing)
_validate_threshold_class(optimal_threshold_class, classes)
log_resource_info!(logger, logger_prefix; suffix=logger_suffix) do
metrics = evaluation_metrics_record(predicted_hard_labels, predicted_soft_labels,
elected_hard_labels, classes, thresholds;
votes, optimal_threshold_class)
log_evaluation_row!(logger, logger_prefix * "/metrics" * logger_suffix,
metrics)
return nothing
end
return nothing
end
#####
##### `learn!`
#####
"""
learn!(model::AbstractClassifier, logger,
get_train_batches, get_test_batches, votes,
elected=majority.(eachrow(votes), (1:length(classes(model)),));
epoch_limit=100, post_epoch_callback=(_ -> nothing),
optimal_threshold_class::Union{Nothing,Integer}=nothing,
test_set_logger_prefix="test_set")
Return `model` after optimizing its parameters across multiple epochs of
training and test, logging Lighthouse's standardized suite of classifier
performance metrics to `logger` throughout the optimization process.
The following phases are executed at each epoch (note: in the below lists
of logged values, `\$resource` takes the values of the field names of
`Lighthouse.ResourceInfo`):
1. Train `model` by calling `train!(model, get_train_batches(), logger)`.
The following quantities are logged to `logger` during this phase:
- `train/loss_per_batch`
- any additional quantities logged by the relevant model/framework-specific
implementation of `train!`.
2. Compute `model`'s predictions on test set provided by `get_test_batches()`
(see below for details). The following quantities are logged to `logger`
during this phase:
- `<test_set_logger_prefix>_prediction/loss_per_batch`
- `<test_set_logger_prefix>_prediction/mean_loss_per_epoch`
- `<test_set_logger_prefix>_prediction/\$resource_per_batch`
3. Compute a battery of metrics to evaluate `model`'s performance on the test
set based on the test set prediction phase. The following quantities are
logged to `logger` during this phase:
- `<test_set_logger_prefix>_evaluation/metrics_per_epoch`
- `<test_set_logger_prefix>_evaluation/\$resource_per_epoch`
4. Call `post_epoch_callback(current_epoch)`.
Where...
- `get_train_batches` is a zero-argument function that returns an iterable of
training set batches. Internally, `learn!` uses this function when it calls
`train!(model, get_train_batches(), logger)`.
- `get_test_batches` is a zero-argument function that returns an iterable
of test set batches used during the current epoch's test phase. Each element of
the iterable takes the form `(batch, votes_locations)`. Internally, `batch` is
passed to [`loss_and_prediction`](@ref) as `loss_and_prediction(model, batch...)`,
and `votes_locations[i]` is expected to yield the row index of `votes` that
corresponds to the `i`th sample in `batch`.
- `votes` is a matrix of hard labels whose columns correspond to voters and whose
rows correspond to the samples in the test set that have been voted on. If
`votes[sample, voter]` is not a valid hard label for `model`, then `voter` will
simply be considered to have not assigned a hard label to `sample`.
- `elected` is a vector of hard labels where the `i`th element is the hard label
elected as "ground truth" out of `votes[i, :]`.
- `optimal_threshold_class` is the class index (`1` or `2`) for which to calculate
an optimal threshold for converting `predicted_soft_labels` to `predicted_hard_labels`.
This is only a valid parameter when `length(classes) == 2`. If `optimal_threshold_class`
is present, test set evaluation will be based on predicted hard labels calculated
with this threshold; if `optimal_threshold_class` is `nothing`, predicted hard labels
will be calculated via `onecold(classifier, soft_label)`.
"""
function learn!(model::AbstractClassifier, logger, get_train_batches, get_test_batches,
votes, elected=majority.(eachrow(votes), (1:length(classes(model)),));
epoch_limit=100, post_epoch_callback=(_ -> nothing),
optimal_threshold_class::Union{Nothing,Integer}=nothing,
test_set_logger_prefix="test_set")
# NOTE `votes` is currently unused except to construct `elected` by default,
# but will be necessary for calculating multirater metrics e.g. Fleiss' kappa
# later so we still required it in the API
# TODO keeping `votes` alive might hog a lot of memory, so it would be convenient
# to provide callers with a wrapper around `channel_unordered` (or at least example
# code) for generating an iterator that batches `votes` rows to `soft labels` in
# a manner that's respectful to throughput/memory constraints.
# TODO is it better to pre-allocate these, or allocate them per-epoch? The
# former ensures fixed memory usage, but the latter gives the GC a chance
# to free up some RAM between epochs.
_validate_threshold_class(optimal_threshold_class, classes(model))
predicted = zeros(Float32, length(elected), length(classes(model)))
log_event!(logger, "started learning")
for current_epoch in 1:epoch_limit
try
train!(model, get_train_batches(), logger)
predict!(model, predicted, get_test_batches(), logger;
logger_prefix="$(test_set_logger_prefix)_prediction")
evaluate!(map(label -> onecold(model, label), eachrow(predicted)), predicted,
elected, classes(model), logger;
logger_prefix="$(test_set_logger_prefix)_evaluation",
logger_suffix="_per_epoch", votes=votes,
optimal_threshold_class=optimal_threshold_class)
post_epoch_callback(current_epoch)
flush(logger)
catch ex # support early stopping via exception handling
if is_early_stopping_exception(model, ex)
log_event!(logger, "`learn!` call stopped via $ex in epoch $current_epoch")
break
else
log_event!(logger,
"`learn!` call encountered exception in epoch $current_epoch")
rethrow(ex)
end
end
end
return model
end
#####
##### `post_epoch_callback` utilities
#####
"""
upon(logger::LearnLogger, field::AbstractString; condition, initial)
upon(logged::Dict{String,Any}, field::AbstractString; condition, initial)
Return a closure that can be called to check the most recent state of
`logger.logged[field]` and trigger a caller-provided function when
`condition(recent_state, previously_chosen_state)` is `true`.
For example:
```
upon_loss_decrease = upon(logger, "test_set_prediction/mean_loss_per_epoch";
condition=<, initial=Inf)
save_upon_loss_decrease = _ -> begin
upon_loss_decrease(new_lowest_loss -> save_my_model(model, new_lowest_loss),
consecutive_failures -> consecutive_failures > 10 && Flux.stop())
end
learn!(model, logger, get_train_batches, get_test_batches, votes;
post_epoch_callback=save_upon_loss_decrease)
```
Specifically, the form of the returned closure is `f(on_true, on_false)` where
`on_true(state)` is called if `condition(state, previously_chosen_state)` is
`true`. Otherwise, `on_false(consecutive_falses)` is called where `consecutive_falses`
is the number of `condition` calls that have returned `false` since the last
`condition` call returned `true`.
Note that the returned closure is a no-op if `logger.logged[field]` has not
been updated since the most recent call.
"""
function upon(logged::Dict{String,Vector{Any}}, field::AbstractString; condition, initial)
history = get!(() -> Any[], logged, field)
previous_length = length(history)
current = isempty(history) ? initial : last(history)
consecutive_false_count = 0
return (on_true, on_false=(_ -> nothing)) -> begin
length(history) == previous_length && return nothing
previous_length = length(history)
candidate = last(history)
if condition(candidate, current)
consecutive_false_count = 0
current = candidate
on_true(current)
else
consecutive_false_count += 1
on_false(consecutive_false_count)
end
end
end
function upon(logger::LearnLogger, field::AbstractString; condition, initial)
return upon(logger.logged, field; condition=condition, initial=initial)
end
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 44644 | const BINARIZE_NOTE = string("Supply a function to the keyword argument `binarize` ",
"which takes as input `(soft_label, threshold)` and ",
"outputs a `Bool` indicating whether or not the class of interest")
binarize_by_threshold(soft, threshold) = soft >= threshold
#####
##### confusion matrices
#####
"""
confusion_matrix(class_count::Integer, hard_label_pairs = ())
Given the iterable `hard_label_pairs` whose `k`th element takes the form
`(first_classifiers_label_for_sample_k, second_classifiers_label_for_sample_k)`,
return the corresponding confusion matrix where `matrix[i, j]` is the number of
samples that the first classifier labeled `i` and the second classifier labeled
`j`.
Note that the returned confusion matrix can be updated in-place with new labels
via `Lighthouse.increment_at!(matrix, more_hard_label_pairs)`.
"""
function confusion_matrix(class_count::Integer, hard_label_pairs=())
confusion = zeros(Int, class_count, class_count)
increment_at!(confusion, hard_label_pairs)
return confusion
end
"""
accuracy(confusion::AbstractMatrix)
Returns the percentage of matching classifications out of total classifications,
or `NaN` if `all(iszero, confusion)`.
Note that `accuracy(confusion)` is equivalent to overall percent agreement
between `confusion`'s row classifier and column classifier.
"""
function accuracy(confusion::AbstractMatrix)
total = sum(confusion)
total == 0 && return NaN
return tr(confusion) / total
end
"""
binary_statistics(confusion::AbstractMatrix, class_index)
Treating the rows of `confusion` as corresponding to predicted classifications
and the columns as corresponding to true classifications, return a `NamedTuple`
with the following fields for the given `class_index`:
- `predicted_positives`
- `predicted_negatives`
- `actual_positives`
- `actual_negatives`
- `true_positives`
- `true_negatives`
- `false_positives`
- `false_negatives`
- `true_positive_rate`
- `true_negative_rate`
- `false_positive_rate`
- `false_negative_rate`
- `precision`
- `f1`
"""
function binary_statistics(confusion::AbstractMatrix, class_index::Integer)
total = sum(confusion)
predicted_positives = sum(view(confusion, class_index, :))
predicted_negatives = total - predicted_positives
actual_positives = sum(view(confusion, :, class_index))
actual_negatives = total - actual_positives
true_positives = confusion[class_index, class_index]
false_positives = predicted_positives - true_positives
false_negatives = actual_positives - true_positives
true_negatives = actual_negatives - false_positives
true_positive_rate = (true_positives == 0 && actual_positives == 0) ?
(one(true_positives) / one(actual_positives)) :
(true_positives / actual_positives)
true_negative_rate = (true_negatives == 0 && actual_negatives == 0) ?
(one(true_negatives) / one(actual_negatives)) :
(true_negatives / actual_negatives)
false_positive_rate = (false_positives == 0 && actual_negatives == 0) ?
(zero(false_positives) / one(actual_negatives)) :
(false_positives / actual_negatives)
false_negative_rate = (false_negatives == 0 && actual_positives == 0) ?
(zero(false_negatives) / one(actual_positives)) :
(false_negatives / actual_positives)
precision = (true_positives == 0 && predicted_positives == 0) ? NaN :
(true_positives / predicted_positives)
f1 = true_positives / (true_positives + 0.5 * (false_positives + false_negatives))
return (; predicted_positives, predicted_negatives, actual_positives, actual_negatives,
true_positives, true_negatives, false_positives, false_negatives,
true_positive_rate, true_negative_rate, false_positive_rate,
false_negative_rate, precision, f1)
end
function binary_statistics(confusion::AbstractMatrix)
return [binary_statistics(confusion, i) for i in 1:size(confusion, 1)]
end
#####
##### interrater agreement
#####
"""
cohens_kappa(class_count, hard_label_pairs)
Return `(κ, p₀)` where `κ` is Cohen's kappa and `p₀` percent agreement given
`class_count` and `hard_label_pairs` (these arguments take the same form as
their equivalents in [`confusion_matrix`](@ref)).
"""
function cohens_kappa(class_count, hard_label_pairs)
all(issubset(pair, 1:class_count) for pair in hard_label_pairs) ||
throw(ArgumentError("Unexpected class in `hard_label_pairs`."))
p₀ = accuracy(confusion_matrix(class_count, hard_label_pairs))
pₑ = _probability_of_chance_agreement(class_count, hard_label_pairs)
return _cohens_kappa(p₀, pₑ), p₀
end
_cohens_kappa(p₀, pₑ) = (p₀ - pₑ) / (1 - ifelse(pₑ == 1, zero(pₑ), pₑ))
function _probability_of_chance_agreement(class_count, hard_label_pairs)
labels_1 = (pair[1] for pair in hard_label_pairs)
labels_2 = (pair[2] for pair in hard_label_pairs)
x = sum(k -> count(==(k), labels_1) * count(==(k), labels_2), 1:class_count)
return x / length(hard_label_pairs)^2
end
#####
##### probability distributions
#####
# source: https://github.com/FluxML/Flux.jl/blob/fe85a38d78e225e07a0b75c12b55c8398ae3fe5d/src/layers/stateless.jl#L6
mse(ŷ, y) = sum((ŷ .- y) .^ 2) * 1 // length(y)
"""
calibration_curve(probabilities, bitmask; bin_count=10)
Given `probabilities` (the predicted probabilities of the positive class) and
`bitmask` (a vector of `Bool`s indicating whether or not the element actually
belonged to the positive class), return `(bins, fractions, totals, mean_squared_error)`
where:
- `bins` a vector with `bin_count` `Pairs` specifying the calibration curve's probability bins
- `fractions`: a vector where `fractions[i]` is the number of values in `probabilities`
that falls within `bin[i]` over the total number of values within `bin[i]`, or `NaN`
if the total number of values in `bin[i]` is zero.
- `totals`: a vector where `totals[i]` the total number of values within `bin[i]`.
- `mean_squared_error`: The mean squared error of `fractions` vs. an ideal calibration curve.
This method is similar to the corresponding scikit-learn method:
https://scikit-learn.org/stable/modules/generated/sklearn.calibration.calibration_curve.html
"""
function calibration_curve(probabilities, bitmask; bin_count=10)
bins = probability_bins(bin_count)
per_bin = [fraction_within(probabilities, bitmask, bin...) for bin in bins]
fractions, totals = first.(per_bin), last.(per_bin)
nonempty_indices = findall(!isnan, fractions)
if !isempty(nonempty_indices)
ideal = range(mean(first(bins)), mean(last(bins)); length=length(bins))
mean_squared_error = mse(fractions[nonempty_indices], ideal[nonempty_indices])
else
mean_squared_error = NaN
end
return (bins=bins, fractions=fractions, totals=totals,
mean_squared_error=mean_squared_error)
end
function probability_bins(bin_count)
r = range(0.0, 1.0; length=(bin_count + 1))
return [begin
start, stop = r[i], r[i + 1]
stop = (i + 1) < length(r) ? prevfloat(stop) : stop
start => stop
end
for i in 1:(length(r) - 1)]
end
function fraction_within(values, bitmask, start, stop)
count = 0
total = 0
for (i, value) in enumerate(values)
if start <= value <= stop
count += bitmask[i]
total += 1
end
end
fraction = iszero(total) ? NaN : (count / total)
return (fraction=fraction, total=total)
end
#####
##### Aggregate metrics to calculate `metrics` schemas defined in `src/row.jl`
#####
"""
get_tradeoff_metrics(predicted_soft_labels, elected_hard_labels, class_index;
thresholds, binarize=binarize_by_threshold, class_labels=missing)
Return [`TradeoffMetricsV1`] calculated for the given `class_index`, with the following
fields guaranteed to be non-missing: `roc_curve`, `roc_auc`, pr_curve`,
`reliability_calibration_curve`, `reliability_calibration_score`.` $(BINARIZE_NOTE)
(`class_index`).
"""
function get_tradeoff_metrics(predicted_soft_labels, elected_hard_labels, class_index;
thresholds, binarize=binarize_by_threshold,
class_labels=missing)
stats = per_threshold_confusion_statistics(predicted_soft_labels, elected_hard_labels,
thresholds, class_index; binarize)
roc_curve = (map(t -> t.false_positive_rate, stats),
map(t -> t.true_positive_rate, stats))
pr_curve = (map(t -> t.true_positive_rate, stats), map(t -> t.precision, stats))
class_probabilities = view(predicted_soft_labels, :, class_index)
reliability_calibration = calibration_curve(class_probabilities,
elected_hard_labels .== class_index)
reliability_calibration_curve = (mean.(reliability_calibration.bins),
reliability_calibration.fractions)
reliability_calibration_score = reliability_calibration.mean_squared_error
return TradeoffMetricsV1(; class_index, class_labels, roc_curve,
roc_auc=area_under_curve(roc_curve...), pr_curve,
reliability_calibration_curve, reliability_calibration_score)
end
"""
get_tradeoff_metrics_binary_multirater(predicted_soft_labels, elected_hard_labels, class_index;
thresholds, binarize=binarize_by_threshold, class_labels=missing)
Return [`TradeoffMetricsV1`] calculated for the given `class_index`. In addition
to metrics calculated by [`get_tradeoff_metrics`](@ref), additionally calculates
`spearman_correlation`-based metrics. $(BINARIZE_NOTE) (`class_index`).
"""
function get_tradeoff_metrics_binary_multirater(predicted_soft_labels, elected_hard_labels,
votes, class_index; thresholds,
binarize=binarize_by_threshold,
class_labels=missing)
basic_row = get_tradeoff_metrics(predicted_soft_labels, elected_hard_labels,
class_index; thresholds, binarize, class_labels)
corr = _calculate_spearman_correlation(predicted_soft_labels, votes)
row = Tables.rowmerge(basic_row,
(; spearman_correlation=corr.ρ,
spearman_correlation_ci_upper=corr.ci_upper,
spearman_correlation_ci_lower=corr.ci_lower, n_samples=corr.n))
return TradeoffMetricsV1(; row...)
end
"""
get_hardened_metrics(predicted_hard_labels, elected_hard_labels, class_index;
class_labels=missing)
Return [`HardenedMetricsV1`] calculated for the given `class_index`, with the following
field guaranteed to be non-missing: expert-algorithm agreement (`ea_kappa`).
"""
function get_hardened_metrics(predicted_hard_labels, elected_hard_labels, class_index;
class_labels=missing)
return HardenedMetricsV1(; class_index, class_labels,
ea_kappa=_calculate_ea_kappa(predicted_hard_labels,
elected_hard_labels,
class_index))
end
"""
get_hardened_metrics_multirater(predicted_hard_labels, elected_hard_labels, class_index;
class_labels=missing)
Return [`HardenedMetricsV1`] calculated for the given `class_index`. In addition
to metrics calculated by [`get_hardened_metrics`](@ref), additionally calculates
`discrimination_calibration_curve` and `discrimination_calibration_score`.
"""
function get_hardened_metrics_multirater(predicted_hard_labels, elected_hard_labels, votes,
class_index; class_labels=missing)
basic_row = get_hardened_metrics(predicted_hard_labels, elected_hard_labels,
class_index; class_labels)
cal = _calculate_discrimination_calibration(predicted_hard_labels, votes;
class_of_interest_index=class_index)
row = Tables.rowmerge(basic_row,
(; discrimination_calibration_curve=cal.plot_curve_data,
discrimination_calibration_score=cal.mse))
return HardenedMetricsV1(; row...)
end
"""
get_hardened_metrics_multiclass(predicted_hard_labels, elected_hard_labels,
class_count; class_labels=missing)
Return [`HardenedMetricsV1`] calculated over all `class_count` classes. Calculates
expert-algorithm agreement (`ea_kappa`) over all classes, as well as the multiclass
`confusion_matrix`.
"""
function get_hardened_metrics_multiclass(predicted_hard_labels, elected_hard_labels,
class_count; class_labels=missing)
ea_kappa = first(cohens_kappa(class_count,
zip(predicted_hard_labels, elected_hard_labels)))
return HardenedMetricsV1(; class_index=:multiclass, class_labels,
confusion_matrix=confusion_matrix(class_count,
zip(predicted_hard_labels,
elected_hard_labels)),
ea_kappa)
end
"""
get_label_metrics_multirater(votes, class_index; class_labels=missing)
Return [`LabelMetricsV1`] calculated for the given `class_index`, with the following
field guaranteed to be non-missing: `per_expert_discrimination_calibration_curves`,
`per_expert_discrimination_calibration_scores`, interrater-agreement (`ira_kappa`).
"""
function get_label_metrics_multirater(votes, class_index; class_labels=missing)
size(votes, 2) > 1 ||
throw(ArgumentError("Input `votes` is not multirater (`size(votes) == $(size(votes))`)"))
expert_cal = _calculate_voter_discrimination_calibration(votes;
class_of_interest_index=class_index)
per_expert_discrimination_calibration_curves = expert_cal.plot_curve_data
per_expert_discrimination_calibration_scores = expert_cal.mse
return LabelMetricsV1(; class_index, class_labels,
per_expert_discrimination_calibration_curves,
per_expert_discrimination_calibration_scores,
ira_kappa=_calculate_ira_kappa(votes, class_index))
end
"""
get_label_metrics_multirater_multiclass(votes, class_count; class_labels=missing)
Return [`LabelMetricsV1`] calculated over all `class_count` classes. Calculates
the multiclass interrater agreement (`ira_kappa`).
"""
function get_label_metrics_multirater_multiclass(votes, class_count; class_labels=missing)
size(votes, 2) > 1 ||
throw(ArgumentError("Input `votes` is not multirater (`size(votes) == $(size(votes))`)"))
return LabelMetricsV1(; class_index=:multiclass, class_labels,
ira_kappa=_calculate_ira_kappa_multiclass(votes, class_count))
end
#####
##### Metrics pipelines
#####
"""
evaluation_metrics(args...; optimal_threshold_class=nothing, kwargs...)
Return [`evaluation_metrics_record`](@ref) after converting output `EvaluationV1`
into a `Dict`. For argument details, see [`evaluation_metrics_record`](@ref).
"""
function evaluation_metrics(args...; optimal_threshold_class=nothing, kwargs...)
row = evaluation_metrics_record(args...;
optimal_threshold_class=something(optimal_threshold_class,
missing), kwargs...)
return _evaluation_dict(row)
end
"""
evaluation_metrics_record(observation_table, classes, thresholds=0.0:0.01:1.0;
strata::Union{Nothing,AbstractVector{Set{T}} where T}=nothing,
optimal_threshold_class::Union{Missing,Nothing,Integer}=missing)
evaluation_metrics_record(predicted_hard_labels::AbstractVector,
predicted_soft_labels::AbstractMatrix,
elected_hard_labels::AbstractVector,
classes,
thresholds=0.0:0.01:1.0;
votes::Union{Nothing,Missing,AbstractMatrix}=nothing,
strata::Union{Nothing,AbstractVector{Set{T}} where T}=nothing,
optimal_threshold_class::Union{Missing,Nothing,Integer}=missing)
Returns `EvaluationV1` containing a battery of classifier performance
metrics that each compare `predicted_soft_labels` and/or `predicted_hard_labels`
agaist `elected_hard_labels`.
Where...
- `predicted_soft_labels` is a matrix of soft labels whose columns correspond to
classes and whose rows correspond to samples in the evaluation set.
- `predicted_hard_labels` is a vector of hard labels where the `i`th element
is the hard label predicted by the model for sample `i` in the evaulation set.
- `elected_hard_labels` is a vector of hard labels where the `i`th element
is the hard label elected as "ground truth" for sample `i` in the evaulation set.
- `thresholds` are the range of thresholds used by metrics (e.g. PR curves) that
are calculated on the `predicted_soft_labels` for a range of thresholds.
- `votes` is a matrix of hard labels whose columns correspond to voters and whose
rows correspond to the samples in the test set that have been voted on. If
`votes[sample, voter]` is not a valid hard label for `model`, then `voter` will
simply be considered to have not assigned a hard label to `sample`.
- `strata` is a vector of sets of (arbitrarily typed) groups/strata for each sample
in the evaluation set, or `nothing`. If not `nothing`, per-class and multiclass
kappas will also be calculated per group/stratum.
- `optimal_threshold_class` is the class index (`1` or `2`) for which to calculate
an optimal threshold for converting the `predicted_soft_labels` to
`predicted_hard_labels`. If present, the input `predicted_hard_labels` will be
ignored and new `predicted_hard_labels` will be recalculated from the new threshold.
This is only a valid parameter when `length(classes) == 2`
Alternatively, an `observation_table` that consists of rows of type [`ObservationV1`](@ref)
can be passed in in place of `predicted_soft_labels`,`predicted_hard_labels`,`elected_hard_labels`,
and `votes`. $(BINARIZE_NOTE).
See also [`evaluation_metrics_plot`](@ref).
"""
function evaluation_metrics_record(observation_table, classes, thresholds=0.0:0.01:1.0;
strata::Union{Nothing,AbstractVector{Set{T}} where T}=nothing,
optimal_threshold_class::Union{Missing,Nothing,Integer}=missing,
binarize=binarize_by_threshold)
inputs = _observation_table_to_inputs(observation_table)
return evaluation_metrics_record(inputs.predicted_hard_labels,
inputs.predicted_soft_labels,
inputs.elected_hard_labels,
classes, thresholds; inputs.votes, strata,
optimal_threshold_class, binarize)
end
function evaluation_metrics_record(predicted_hard_labels::AbstractVector,
predicted_soft_labels::AbstractMatrix,
elected_hard_labels::AbstractVector, classes,
thresholds=0.0:0.01:1.0;
votes::Union{Nothing,Missing,AbstractMatrix}=nothing,
strata::Union{Nothing,AbstractVector{Set{T}} where T}=nothing,
optimal_threshold_class::Union{Missing,Nothing,Integer}=missing,
binarize=binarize_by_threshold)
class_labels = string.(collect(classes)) # Plots.jl expects this to be an `AbstractVector`
class_indices = 1:length(classes)
# Step 1: Calculate all metrics that do not require hardened predictions
# In our `evaluation_metrics_record` we special-case multirater binary classification,
# so do that here as well.
tradeoff_metrics_rows = if length(classes) == 2 && has_value(votes)
map(ic -> get_tradeoff_metrics_binary_multirater(predicted_soft_labels,
elected_hard_labels, votes, ic;
thresholds, binarize),
class_indices)
else
map(ic -> get_tradeoff_metrics(predicted_soft_labels, elected_hard_labels, ic;
thresholds, binarize), class_indices)
end
# Step 2a: Choose optimal threshold and use it to harden predictions
optimal_threshold = missing
if has_value(optimal_threshold_class) && has_value(votes)
cal = _calculate_optimal_threshold_from_discrimination_calibration(predicted_soft_labels,
votes;
thresholds,
class_of_interest_index=optimal_threshold_class,
binarize)
optimal_threshold = cal.threshold
elseif has_value(optimal_threshold_class)
roc_curve = tradeoff_metrics_rows[findfirst(==(optimal_threshold_class),
tradeoff_metrics_rows.classes), :]
optimal_threshold = _get_optimal_threshold_from_ROC(roc_curve, thresholds)
else
@warn "Not selecting and/or using optimal threshold; using `predicted_hard_labels` provided by default"
end
# Step 2b: Harden predictions with new threshold
# Note: in new refactored world, should never have hard_predictions before this
# point, IFF using a threshold to choose a hard label
if !ismissing(optimal_threshold)
other_class = optimal_threshold_class == 1 ? 2 : 1
for (i, row) in enumerate(eachrow(predicted_soft_labels))
predicted_hard_labels[i] = binarize(row[optimal_threshold_class],
optimal_threshold) ?
optimal_threshold_class : other_class
end
end
# Step 3: Calculate all metrics derived from hardened predictions
hardened_metrics_table = if has_value(votes)
map(class_index -> get_hardened_metrics_multirater(predicted_hard_labels,
elected_hard_labels, votes,
class_index), class_indices)
else
map(class_index -> get_hardened_metrics(predicted_hard_labels, elected_hard_labels,
class_index), class_indices)
end
hardened_metrics_table = vcat(hardened_metrics_table,
get_hardened_metrics_multiclass(predicted_hard_labels,
elected_hard_labels,
length(classes)))
# Step 4: Calculate all metrics derived directly from labels (does not depend on
# predictions)
labels_metrics_table = LabelMetricsV1[]
if has_value(votes) && size(votes, 2) > 1
labels_metrics_table = map(c -> get_label_metrics_multirater(votes, c),
class_indices)
labels_metrics_table = vcat(labels_metrics_table,
get_label_metrics_multirater_multiclass(votes,
length(classes)))
end
# Adendum: Not including `stratified_kappas` by default in any of our metrics
# calculations; including here so as not to fail the deprecation sanity-check
stratified_kappas = has_value(strata) ?
_calculate_stratified_ea_kappas(predicted_hard_labels,
elected_hard_labels,
length(classes), strata) : missing
return _evaluation_record(tradeoff_metrics_rows, hardened_metrics_table,
labels_metrics_table; optimal_threshold_class, class_labels,
thresholds, optimal_threshold, stratified_kappas)
end
function _split_classes_from_multiclass(table)
table = DataFrame(table; copycols=false)
nrow(table) == 0 && return (missing, missing)
# Pull out individual classes
class_rows = filter(:class_index => c -> isa(c, Int), table)
sort!(class_rows, :class_index)
nrow(class_rows) == length(unique(class_rows.class_index)) ||
throw(ArgumentError("Multiple rows for same class!"))
# Pull out multiclass
multi_rows = filter(:class_index => ==(:multiclass), table)
nrow(multi_rows) > 1 &&
throw(ArgumentError("More than one `:multiclass` row in table!"))
multi = nrow(multi_rows) == 1 ? only(multi_rows) : missing
return class_rows, multi
end
function _values_or_missing(values)
has_value(values) || return missing
return if Base.IteratorSize(values) == Base.HasShape{0}()
values
else
T = nonmissingtype(eltype(values))
all(!ismissing, values) ? convert(Array{T}, values) : missing
end
end
_unpack_curves(curve::Missing) = missing
_unpack_curves(curve::Curve) = Tuple(curve)
_unpack_curves(curves::AbstractVector{Curve}) = Tuple.(curves)
"""
_evaluation_record(tradeoff_metrics_table, hardened_metrics_table, label_metrics_table;
optimal_threshold_class=missing, class_labels, thresholds,
optimal_threshold, stratified_kappas=missing)
Helper function to create an `EvaluationV1` from tables of constituent Metrics schemas,
to support [`evaluation_metrics_record`](@ref):
- `tradeoff_metrics_table`: table of [`TradeoffMetricsV1`](@ref)s
- `hardened_metrics_table`: table of [`HardenedMetricsV1`](@ref)s
- `label_metrics_table`: table of [`LabelMetricsV1`](@ref)s
"""
function _evaluation_record(tradeoff_metrics_table, hardened_metrics_table,
label_metrics_table; optimal_threshold_class=missing,
class_labels,
thresholds, optimal_threshold, stratified_kappas=missing)
tradeoff_rows, _ = _split_classes_from_multiclass(tradeoff_metrics_table)
hardened_rows, hardened_multi = _split_classes_from_multiclass(hardened_metrics_table)
label_rows, labels_multi = _split_classes_from_multiclass(label_metrics_table)
# Due to special casing, the following metrics should only be present
# in the resultant `EvaluationV1` if `optimal_threshold_class` is present
discrimination_calibration_curve = missing
discrimination_calibration_score = missing
if has_value(optimal_threshold_class)
hardened_row_optimal = only(filter(:class_index => ==(optimal_threshold_class),
hardened_rows))
discrimination_calibration_curve = hardened_row_optimal.discrimination_calibration_curve
discrimination_calibration_score = hardened_row_optimal.discrimination_calibration_score
end
# Similarly, the following metrics should only be present
# in the resultant `EvaluationV1` when doing multirater evaluation
per_expert_discrimination_calibration_curves = missing
per_expert_discrimination_calibration_scores = missing
if has_value(label_rows) && has_value(optimal_threshold_class)
label_row_optimal = only(filter(:class_index => ==(optimal_threshold_class),
label_rows))
per_expert_discrimination_calibration_curves = _unpack_curves(_values_or_missing(label_row_optimal.per_expert_discrimination_calibration_curves))
per_expert_discrimination_calibration_scores = label_row_optimal.per_expert_discrimination_calibration_scores
end
multiclass_IRA_kappas = has_value(labels_multi) ?
_values_or_missing(labels_multi.ira_kappa) : missing
per_class_IRA_kappas = has_value(label_rows) ?
_values_or_missing(label_rows.ira_kappa) : missing
# Similarly, due to separate special casing, only get the spearman correlation coefficient
# from a binary classification problem. It is calculated for both classes, but is
# identical, so grab it from the first
spearman_correlation = missing
if length(class_labels) == 2
row = first(tradeoff_rows)
spearman_correlation = ismissing(row.spearman_correlation) ? missing :
(; ρ=row.spearman_correlation, n=row.n_samples,
ci_lower=row.spearman_correlation_ci_lower,
ci_upper=row.spearman_correlation_ci_upper)
end
return EvaluationV1(; # ...from hardened_metrics_table
confusion_matrix=_values_or_missing(hardened_multi.confusion_matrix),
multiclass_kappa=_values_or_missing(hardened_multi.ea_kappa),
per_class_kappas=_values_or_missing(hardened_rows.ea_kappa),
discrimination_calibration_curve=_unpack_curves(discrimination_calibration_curve),
discrimination_calibration_score,
# ...from tradeoff_metrics_table
per_class_roc_curves=_unpack_curves(_values_or_missing(tradeoff_rows.roc_curve)),
per_class_roc_aucs=_values_or_missing(tradeoff_rows.roc_auc),
per_class_pr_curves=_unpack_curves(_values_or_missing(tradeoff_rows.pr_curve)),
spearman_correlation,
per_class_reliability_calibration_curves=_unpack_curves(_values_or_missing(tradeoff_rows.reliability_calibration_curve)),
per_class_reliability_calibration_scores=_values_or_missing(tradeoff_rows.reliability_calibration_score),
# from label_metrics_table
per_expert_discrimination_calibration_curves,
multiclass_IRA_kappas, per_class_IRA_kappas,
per_expert_discrimination_calibration_scores,
# from kwargs:
optimal_threshold_class=_values_or_missing(optimal_threshold_class),
class_labels, thresholds, optimal_threshold, stratified_kappas)
end
#####
##### Pipeline helper functions
#####
function _calculate_stratified_ea_kappas(predicted_hard_labels, elected_hard_labels,
class_count, strata)
groups = reduce(∪, strata)
kappas = Pair{String,Any}[]
for group in groups
index = group .∈ strata
predicted = predicted_hard_labels[index]
elected = elected_hard_labels[index]
k = _calculate_ea_kappas(predicted, elected, class_count)
push!(kappas,
group => (per_class=k.per_class_kappas, multiclass=k.multiclass_kappa,
n=sum(index)))
end
kappas = sort(kappas; by=p -> last(p).multiclass)
return [k = v for (k, v) in kappas]
end
"""
_calculate_ea_kappas(predicted_hard_labels, elected_hard_labels, classes)
Return `NamedTuple` with keys `:per_class_kappas`, `:multiclass_kappa` containing the Cohen's
Kappa per-class and over all classes, respectively. The value of output key
`:per_class_kappas` is an `Array` such that item `i` is the Cohen's kappa calculated
for class `i`.
Where...
- `predicted_hard_labels` is a vector of hard labels where the `i`th element
is the hard label predicted by the model for sample `i` in the evaulation set.
- `elected_hard_labels` is a vector of hard labels where the `i`th element
is the hard label elected as "ground truth" for sample `i` in the evaulation set.
- `class_count` is the number of possible classes.
"""
function _calculate_ea_kappas(predicted_hard_labels, elected_hard_labels, class_count)
multiclass_kappa = first(cohens_kappa(class_count,
zip(predicted_hard_labels, elected_hard_labels)))
per_class_kappas = map(1:class_count) do class_index
return _calculate_ea_kappa(predicted_hard_labels, elected_hard_labels, class_index)
end
return (; per_class_kappas, multiclass_kappa)
end
function _calculate_ea_kappa(predicted_hard_labels, elected_hard_labels, class_index)
CLASS_VS_ALL_CLASS_COUNT = 2
predicted = ((label == class_index) + 1 for label in predicted_hard_labels)
elected = ((label == class_index) + 1 for label in elected_hard_labels)
return first(cohens_kappa(CLASS_VS_ALL_CLASS_COUNT, zip(predicted, elected)))
end
"""
_calculate_ira_kappas(votes, classes)
Return `NamedTuple` with keys `:per_class_IRA_kappas`, `:multiclass_IRA_kappas` containing the Cohen's
Kappa for inter-rater agreement (IRA) per-class and over all classes, respectively.
The value of output key `:per_class_IRA_kappas` is an `Array` such that item `i` is the
IRA kappa calculated for class `i`.
Where...
- `votes` is a matrix of hard labels whose columns correspond to voters and whose
rows correspond to the samples in the test set that have been voted on. If
`votes[sample, voter]` is not a valid hard label for `model`, then `voter` will
simply be considered to have not assigned a hard label to `sample`.
- `classes` all possible classes voted on.
Returns `(per_class_IRA_kappas=missing, multiclass_IRA_kappas=missing)` if `votes` has only a single voter (i.e., a single column) or if
no two voters rated the same sample. Note that vote entries of `0` are taken to
mean that the voter did not rate that sample.
"""
function _calculate_ira_kappas(votes, classes)
hard_label_pairs = _prep_hard_label_pairs(votes)
length(hard_label_pairs) > 0 ||
return (; per_class_IRA_kappas=missing, multiclass_IRA_kappas=missing) # No common observations voted on
length(hard_label_pairs) < 10 &&
@warn "...only $(length(hard_label_pairs)) in common, potentially questionable IRA results"
multiclass_ira = first(cohens_kappa(length(classes), hard_label_pairs))
CLASS_VS_ALL_CLASS_COUNT = 2
per_class_ira = map(1:length(classes)) do class_index
class_v_other_hard_label_pair = map(row -> 1 .+ (row .== class_index),
hard_label_pairs)
return first(cohens_kappa(CLASS_VS_ALL_CLASS_COUNT, class_v_other_hard_label_pair))
end
return (; per_class_IRA_kappas=per_class_ira, multiclass_IRA_kappas=multiclass_ira)
end
function _prep_hard_label_pairs(votes)
if !has_value(votes) || size(votes, 2) < 2
# no votes given or only one expert
return Tuple{Int64,Int64}[]
end
all_hard_label_pairs = Array{Int}(undef, 0, 2)
num_voters = size(votes, 2)
for i_voter in 1:(num_voters - 1)
for j_voter in (i_voter + 1):num_voters
all_hard_label_pairs = vcat(all_hard_label_pairs, votes[:, [i_voter, j_voter]])
end
end
hard_label_pairs = filter(row -> all(row .!= 0), collect(eachrow(all_hard_label_pairs)))
return hard_label_pairs
end
function _calculate_ira_kappa_multiclass(votes, class_count)
hard_label_pairs = _prep_hard_label_pairs(votes)
length(hard_label_pairs) == 0 && return missing
return first(cohens_kappa(class_count, hard_label_pairs))
end
function _calculate_ira_kappa(votes, class_index)
hard_label_pairs = _prep_hard_label_pairs(votes)
length(hard_label_pairs) == 0 && return missing
CLASS_VS_ALL_CLASS_COUNT = 2
class_v_other_hard_label_pair = map(row -> 1 .+ (row .== class_index), hard_label_pairs)
return first(cohens_kappa(CLASS_VS_ALL_CLASS_COUNT, class_v_other_hard_label_pair))
end
function _spearman_corr(predicted_soft_labels, elected_soft_labels)
n = length(predicted_soft_labels)
ρ = StatsBase.corspearman(predicted_soft_labels, elected_soft_labels)
if isnan(ρ)
@warn "Uh oh, correlation is NaN! Probably because StatsBase.corspearman(...)
returns NaN when a set of labels is all the same!"
# Note: accounted for in https://github.com/JuliaStats/HypothesisTests.jl/pull/53/files;
# probably not worth implementing here until we need it (at which point maybe
# it will be ready in HypothesisTests!)
end
# 95% confidence interval calculated according to
# https://stats.stackexchange.com/questions/18887/how-to-calculate-a-confidence-interval-for-spearmans-rank-correlation
stderr = 1.0 / sqrt(n - 3)
delta = 1.96 * stderr
ci_lower = tanh(atanh(ρ) - delta)
ci_upper = tanh(atanh(ρ) + delta)
return (ρ=ρ, n=n, ci_lower=round(ci_lower; digits=3),
ci_upper=round(ci_upper; digits=3))
end
"""
_calculate_spearman_correlation(predicted_soft_labels, votes, classes)
Return `NamedTuple` with keys `:ρ`, `:n`, `:ci_lower`, and `ci_upper` that are
the Spearman correlation constant ρ and its 95% confidence interval bounds.
Only valid for binary classification problems (i.e., `length(classes) == 2`)
Where...
- `predicted_soft_labels` is a matrix of soft labels whose columns correspond to
the two classes and whose rows correspond to the samples in the test set that have been
classified. For a given sample, the two class column values must sum to 1 (i.e.,
softmax has been applied to the classification output).
- `votes` is a matrix of hard labels whose columns correspond to voters and whose
rows correspond to the samples in the test set that have been voted on. If
`votes[sample, voter]` is not a valid hard label for `model`, then `voter` will
simply be considered to have not assigned a hard label to `sample`. May contain
a single voter (i.e., a single column).
- `classes` are the two classes voted on.
"""
function _calculate_spearman_correlation(predicted_soft_labels, votes, classes=missing)
if !ismissing(classes)
length(classes) > 2 && throw(ArgumentError("Only valid for 2-class problems"))
end
if !all(x -> x ≈ 1, sum(predicted_soft_labels; dims=2))
throw(ArgumentError("Input probabiliities fail softmax assumption"))
end
class_index = 1 # Note: Result will be the same whether class 1 or class 2
elected_soft_labels = Vector{Float64}()
for sample_votes in eachrow(votes)
actual_sample_votes = filter(v -> v in Set([1, 2]), sample_votes)
push!(elected_soft_labels, mean(actual_sample_votes .== class_index))
end
return _spearman_corr(predicted_soft_labels[:, class_index], elected_soft_labels)
end
function _calculate_optimal_threshold_from_discrimination_calibration(predicted_soft_labels,
votes; thresholds,
class_of_interest_index,
binarize=binarize_by_threshold)
elected_probabilities = _elected_probabilities(votes, class_of_interest_index)
bin_count = min(size(votes, 2) + 1, 10)
per_threshold_curves = map(thresholds) do thresh
pred_soft = view(predicted_soft_labels, :, class_of_interest_index)
return calibration_curve(elected_probabilities, binarize.(pred_soft, thresh);
bin_count=bin_count)
end
i_min = argmin([c.mean_squared_error for c in per_threshold_curves])
curve = per_threshold_curves[i_min]
return (threshold=collect(thresholds)[i_min], mse=curve.mean_squared_error,
plot_curve_data=(mean.(curve.bins), curve.fractions))
end
function _calculate_discrimination_calibration(predicted_hard_labels, votes;
class_of_interest_index)
elected_probabilities = _elected_probabilities(votes, class_of_interest_index)
bin_count = min(size(votes, 2) + 1, 10)
curve = calibration_curve(elected_probabilities,
predicted_hard_labels .== class_of_interest_index; bin_count)
return (mse=curve.mean_squared_error,
plot_curve_data=(mean.(curve.bins), curve.fractions))
end
function _elected_probabilities(votes, class_of_interest_index)
elected_probabilities = Vector{Float64}()
for sample_votes in eachrow(votes)
actual_sample_votes = filter(v -> v in Set([1, 2]), sample_votes)
push!(elected_probabilities, mean(actual_sample_votes .== class_of_interest_index))
end
return elected_probabilities
end
function _calculate_voter_discrimination_calibration(votes; class_of_interest_index)
elected_probabilities = _elected_probabilities(votes, class_of_interest_index)
bin_count = min(size(votes, 2) + 1, 10)
per_voter_calibration_curves = map(1:size(votes, 2)) do i_voter
return calibration_curve(elected_probabilities,
votes[:, i_voter] .== class_of_interest_index;
bin_count=bin_count)
end
return (mse=map(curve -> curve.mean_squared_error, per_voter_calibration_curves),
plot_curve_data=map(curve -> (mean.(curve.bins), curve.fractions),
per_voter_calibration_curves))
end
function _get_optimal_threshold_from_ROC(per_class_roc_curves; thresholds,
class_of_interest_index)
return _get_optimal_threshold_from_ROC(per_class_roc_curves[class_of_interest_index],
thresholds)
end
function _get_optimal_threshold_from_ROC(roc_curve, thresholds)
dist = (p1, p2) -> sqrt((p1[1] - p2[1])^2 + (p1[2] - p2[2])^2)
min = Inf
curr_counter = 1
opt_point = nothing
threshold_idx = 1
for point in zip(roc_curve[1], roc_curve[2])
d = dist((0, 1), point)
if d < min
min = d
threshold_idx = curr_counter
opt_point = point
end
curr_counter += 1
end
return collect(thresholds)[threshold_idx]
end
function _validate_threshold_class(optimal_threshold_class, classes)
has_value(optimal_threshold_class) || return nothing
length(classes) == 2 ||
throw(ArgumentError("Only valid for binary classification problems"))
optimal_threshold_class in Set([1, 2]) ||
throw(ArgumentError("Invalid threshold class"))
return nothing
end
function per_class_confusion_statistics(predicted_soft_labels::AbstractMatrix,
elected_hard_labels::AbstractVector, thresholds;
binarize=binarize_by_threshold)
class_count = size(predicted_soft_labels, 2)
return map(1:class_count) do i
return per_threshold_confusion_statistics(predicted_soft_labels,
elected_hard_labels, thresholds, i;
binarize)
end
end
function per_threshold_confusion_statistics(predicted_soft_labels::AbstractMatrix,
elected_hard_labels::AbstractVector, thresholds,
class_index; binarize=binarize_by_threshold)
confusions = [confusion_matrix(2) for _ in 1:length(thresholds)]
for label_index in 1:length(elected_hard_labels)
predicted_soft_label = predicted_soft_labels[label_index, class_index]
elected = (elected_hard_labels[label_index] == class_index) + 1
for (threshold_index, threshold) in enumerate(thresholds)
# Convert from binarized output to 2-class labels (1, 2)
predicted = binarize(predicted_soft_label, threshold) + 1
confusions[threshold_index][predicted, elected] += 1
end
end
return binary_statistics.(confusions, 2)
end
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 7260 | # We can't rely on inference to always give us fully typed
# Vector{<: Number} so we add `{T} where T` to the the mix
# This makes the number like type a bit absurd, but is still nice for
# documentation purposes!
const NumberLike = Union{Number,Missing,Nothing,T} where {T}
const NumberVector = AbstractVector{<:NumberLike}
const NumberMatrix = AbstractMatrix{<:NumberLike}
"""
Tuple{<:NumberVector, <: NumberVector}
Tuple of X, Y coordinates
"""
const XYVector = Tuple{<:NumberVector,<:NumberVector}
"""
Union{XYVector, AbstractVector{<: XYVector}}
A series of XYVectors, or a single xyvector.
"""
const SeriesCurves = Union{XYVector,AbstractVector{<:XYVector}}
"""
evaluation_metrics_plot(data::Dict; size=(1000, 1000), fontsize=12)
evaluation_metrics_plot(row::EvaluationV1; kwargs...)
Plot all evaluation metrics generated via [`evaluation_metrics_record`](@ref) and/or
[`evaluation_metrics`](@ref) in a single image.
!!! note
This function requires a valid Makie backend (e.g. CairoMakie) to be loaded.
"""
function evaluation_metrics_plot end
"""
plot_confusion_matrix!(subfig::GridPosition, args...; kw...)
plot_confusion_matrix(confusion::AbstractMatrix{<: Number},
class_labels::AbstractVector{String},
normalize_by::Union{Symbol,Nothing}=nothing;
size=(800,600), annotation_text_size=20)
Lighthouse plots confusion matrices, which are simple tables
showing the empirical distribution of predicted class (the rows)
versus the elected class (the columns). These can optionally be normalized:
* row-normalized (`:Row`): this means each row has been normalized to sum to 1. Thus, the row-normalized confusion matrix shows the empirical distribution of elected classes for a given predicted class. E.g. the first row of the row-normalized confusion matrix shows the empirical probabilities of the elected classes for a sample which was predicted to be in the first class.
* column-normalized (`:Column`): this means each column has been normalized to sum to 1. Thus, the column-normalized confusion matrix shows the empirical distribution of predicted classes for a given elected class. E.g. the first column of the column-normalized confusion matrix shows the empirical probabilities of the predicted classes for a sample which was elected to be in the first class.
```
fig, ax, p = plot_confusion_matrix(rand(2, 2), ["1", "2"])
fig = Figure()
ax = plot_confusion_matrix!(fig[1, 1], rand(2, 2), ["1", "2"], :Row)
ax = plot_confusion_matrix!(fig[1, 2], rand(2, 2), ["1", "2"], :Column)
```
!!! note
This function requires a valid Makie backend (e.g. CairoMakie) to be loaded.
"""
function plot_confusion_matrix end
function plot_confusion_matrix! end
"""
plot_reliability_calibration_curves!(fig::SubFigure, args...; kw...)
plot_reliability_calibration_curves(per_class_reliability_calibration_curves::SeriesCurves,
per_class_reliability_calibration_scores::NumberVector,
class_labels::AbstractVector{String};
legend=:rb, size=(800, 600))
!!! note
This function requires a valid Makie backend (e.g. CairoMakie) to be loaded.
"""
function plot_reliability_calibration_curves end
function plot_reliability_calibration_curves! end
"""
plot_binary_discrimination_calibration_curves!(fig::SubFigure, args...; kw...)
plot_binary_discrimination_calibration_curves!(calibration_curve::SeriesCurves, calibration_score,
per_expert_calibration_curves::SeriesCurves,
per_expert_calibration_scores, optimal_threshold,
discrimination_class::AbstractString;
marker=:rect, markersize=5, linewidth=2)
!!! note
This function requires a valid Makie backend (e.g. CairoMakie) to be loaded.
"""
function plot_binary_discrimination_calibration_curves end
function plot_binary_discrimination_calibration_curves! end
"""
plot_pr_curves!(subfig::GridPosition, args...; kw...)
plot_pr_curves(per_class_pr_curves::SeriesCurves,
class_labels::AbstractVector{<: String};
size=(800, 600),
legend=:lt, title="PR curves",
xlabel="True positive rate", ylabel="Precision",
linewidth=2, scatter=NamedTuple(), color=:darktest)
- `scatter::Union{Nothing, NamedTuple}`: can be set to a named tuples of attributes that are forwarded to the scatter call (e.g. markersize). If nothing, no scatter is added.
!!! note
This function requires a valid Makie backend (e.g. CairoMakie) to be loaded.
"""
function plot_pr_curves end
function plot_pr_curves! end
"""
plot_roc_curves!(subfig::GridPosition, args...; kw...)
plot_roc_curves(per_class_roc_curves::SeriesCurves,
per_class_roc_aucs::NumberVector,
class_labels::AbstractVector{<: String};
size=(800, 600),
legend=:lt,
title="ROC curves",
xlabel="False positive rate",
ylabel="True positive rate",
linewidth=2, scatter=NamedTuple(), color=:darktest)
- `scatter::Union{Nothing, NamedTuple}`: can be set to a named tuples of attributes that are forwarded to the scatter call (e.g. markersize). If nothing, no scatter is added.
!!! note
This function requires a valid Makie backend (e.g. CairoMakie) to be loaded.
"""
function plot_roc_curves end
function plot_roc_curves! end
"""
plot_kappas!(subfig::GridPosition, args...; kw...)
plot_kappas(per_class_kappas::NumberVector,
class_labels::AbstractVector{String},
per_class_IRA_kappas=nothing;
size=(800, 600),
annotation_text_size=20)
!!! note
This function requires a valid Makie backend (e.g. CairoMakie) to be loaded.
"""
function plot_kappas end
function plot_kappas! end
#####
##### Deprecation support
#####
"""
evaluation_metrics_plot(predicted_hard_labels::AbstractVector,
predicted_soft_labels::AbstractMatrix,
elected_hard_labels::AbstractVector,
classes,
thresholds=0.0:0.01:1.0;
votes::Union{Nothing,AbstractMatrix}=nothing,
strata::Union{Nothing,AbstractVector{Set{T}} where T}=nothing,
optimal_threshold_class::Union{Nothing,Integer}=nothing)
Return a plot and dictionary containing a battery of classifier performance
metrics that each compare `predicted_soft_labels` and/or `predicted_hard_labels`
agaist `elected_hard_labels`.
See [`evaluation_metrics`](@ref) for a description of the arguments.
This method is deprecated in favor of calling `evaluation_metrics`
and [`evaluation_metrics_plot`](@ref) separately.
!!! note
This function requires a valid Makie backend (e.g. CairoMakie) to be loaded.
"""
function evaluation_metrics_plot end
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 14189 |
#####
##### `EvaluationObject
#####
# Arrow can't handle matrices---so when we write/read matrices, we have to pack and unpack them o_O
# https://github.com/apache/arrow-julia/issues/125
vec_to_mat(mat::AbstractMatrix) = mat
function vec_to_mat(vec::AbstractVector)
n = isqrt(length(vec))
return reshape(vec, n, n)
end
vec_to_mat(::Missing) = missing
const GenericCurve = Tuple{Vector{Float64},Vector{Float64}}
@schema "lighthouse.evaluation" Evaluation
@version EvaluationV1 begin
class_labels::Union{Missing,Vector{String}}
# XXX why do we spell out the different array types?
# For Arrow, we need to be able to serialize as a vector
# but we also want to be able to store a matrix directly.
# Then why not just use Array{Int64}? Because that's an
# abstract type, which creates serialization issues in
# unions with Missing.
confusion_matrix::Union{Missing,Array{Int64,1},Array{Int64,2}} = vec_to_mat(confusion_matrix)
discrimination_calibration_curve::Union{Missing,GenericCurve}
discrimination_calibration_score::Union{Missing,Float64}
multiclass_IRA_kappas::Union{Missing,Float64}
multiclass_kappa::Union{Missing,Float64}
optimal_threshold::Union{Missing,Float64}
optimal_threshold_class::Union{Missing,Int64}
per_class_IRA_kappas::Union{Missing,Vector{Float64}}
per_class_kappas::Union{Missing,Vector{Float64}}
stratified_kappas::Union{Missing,
Vector{@NamedTuple{per_class::Vector{Float64},
multiclass::Float64,
n::Int64}}}
per_class_pr_curves::Union{Missing,Vector{GenericCurve}}
per_class_reliability_calibration_curves::Union{Missing,Vector{GenericCurve}}
per_class_reliability_calibration_scores::Union{Missing,Vector{Float64}}
per_class_roc_aucs::Union{Missing,Vector{Float64}}
per_class_roc_curves::Union{Missing,Vector{GenericCurve}}
per_expert_discrimination_calibration_curves::Union{Missing,Vector{GenericCurve}}
per_expert_discrimination_calibration_scores::Union{Missing,Vector{Float64}}
spearman_correlation::Union{Missing,
@NamedTuple{ρ::Float64, # Note: is rho not 'p' 😢
n::Int64,
ci_lower::Float64,
ci_upper::Float64}}
thresholds::Union{Missing,Vector{Float64}}
end
"""
@version EvaluationV1 begin
class_labels::Union{Missing,Vector{String}}
confusion_matrix::Union{Missing,Array{Int64,1},Array{Int64,2}} = vec_to_mat(confusion_matrix)
discrimination_calibration_curve::Union{Missing,GenericCurve}
discrimination_calibration_score::Union{Missing,Float64}
multiclass_IRA_kappas::Union{Missing,Float64}
multiclass_kappa::Union{Missing,Float64}
optimal_threshold::Union{Missing,Float64}
optimal_threshold_class::Union{Missing,Int64}
per_class_IRA_kappas::Union{Missing,Vector{Float64}}
per_class_kappas::Union{Missing,Vector{Float64}}
stratified_kappas::Union{Missing,
Vector{@NamedTuple{per_class::Vector{Float64},
multiclass::Float64,
n::Int64}}}
per_class_pr_curves::Union{Missing,Vector{GenericCurve}}
per_class_reliability_calibration_curves::Union{Missing,Vector{GenericCurve}}
per_class_reliability_calibration_scores::Union{Missing,Vector{Float64}}
per_class_roc_aucs::Union{Missing,Vector{Float64}}
per_class_roc_curves::Union{Missing,Vector{GenericCurve}}
per_expert_discrimination_calibration_curves::Union{Missing,Vector{GenericCurve}}
per_expert_discrimination_calibration_scores::Union{Missing,Vector{Float64}}
spearman_correlation::Union{Missing,
@NamedTuple{ρ::Float64, # Note: is rho not 'p' 😢
n::Int64,
ci_lower::Float64,
ci_upper::Float64}}
thresholds::Union{Missing,Vector{Float64}}
end
A Legolas record representing the output metrics computed by
[`evaluation_metrics_record`](@ref) and [`evaluation_metrics`](@ref).
See [Legolas.jl](https://github.com/beacon-biosignals/Legolas.jl) for details regarding
Legolas record types.
"""
EvaluationV1
"""
EvaluationV1(d::Dict) -> EvaluationV1
`Dict` of metrics results (e.g. from Lighthouse <v0.14.0) into an [`EvaluationV1`](@ref).
"""
function EvaluationV1(d::Dict)
row = (; (Symbol(k) => v for (k, v) in pairs(d))...)
return EvaluationV1(row)
end
"""
_evaluation_row_dict(row::EvaluationV1) -> Dict{String,Any}
Convert [`EvaluationV1`](@ref) into `::Dict{String, Any}` results, as are
output by `[`evaluation_metrics`](@ref)` (and predated use of `EvaluationV1` in
Lighthouse <v0.14.0).
"""
function _evaluation_dict(row::EvaluationV1)
return Dict(string(k) => v for (k, v) in pairs(NamedTuple(row)) if !ismissing(v))
end
#####
##### `Observation
#####
@schema "lighthouse.observation" Observation
@version ObservationV1 begin
predicted_hard_label::Int64
predicted_soft_labels::Vector{Float32}
elected_hard_label::Int64
votes::Union{Missing,Vector{Int64}}
end
"""
@version ObservationV1 begin
predicted_hard_label::Int64
predicted_soft_labels::Vector{Float32}
elected_hard_label::Int64
votes::Union{Missing,Vector{Int64}}
end
A Legolas record representing the per-observation input values required to compute
[`evaluation_metrics_record`](@ref).
"""
ObservationV1
# Convert vector of per-class soft label vectors to expected matrix format, e.g.,
# [[0.1, .2, .7], [0.8, .1, .1]] for 2 observations of 3-class classification returns
# ```
# [0.1 0.2 0.7;
# 0.8 0.1 0.1]
# ```
function _predicted_soft_to_matrix(per_observation_soft_labels)
return transpose(reduce(hcat, per_observation_soft_labels))
end
function _observation_table_to_inputs(observation_table)
Legolas.validate(Tables.schema(observation_table), ObservationV1SchemaVersion())
df_table = Tables.columns(observation_table)
if any(ismissing, df_table.votes) && !all(ismissing, df_table.votes)
throw(ArgumentError("`:votes` must either be all `missing` or contain no `missing`"))
end
votes = any(ismissing, df_table.votes) ? missing :
transpose(reduce(hcat, df_table.votes))
predicted_soft_labels = _predicted_soft_to_matrix(df_table.predicted_soft_labels)
return (; predicted_hard_labels=df_table.predicted_hard_label, predicted_soft_labels,
elected_hard_labels=df_table.elected_hard_label, votes)
end
function _inputs_to_observation_table(; predicted_hard_labels::AbstractVector,
predicted_soft_labels::AbstractMatrix,
elected_hard_labels::AbstractVector,
votes::Union{Nothing,Missing,AbstractMatrix}=nothing)
votes_itr = has_value(votes) ? eachrow(votes) :
Iterators.repeated(missing, length(predicted_hard_labels))
predicted_soft_labels_itr = eachrow(predicted_soft_labels)
if !(length(predicted_hard_labels) ==
length(predicted_soft_labels_itr) ==
length(elected_hard_labels) ==
length(votes_itr))
throw(DimensionMismatch("Inputs do not all have the same number of observations"))
end
observation_table = map(predicted_hard_labels, elected_hard_labels,
predicted_soft_labels_itr,
votes_itr) do predicted_hard_label, elected_hard_label,
predicted_soft_labels, votes
return ObservationV1(; predicted_hard_label, elected_hard_label,
predicted_soft_labels, votes)
end
return observation_table
end
#####
##### Metrics
#####
"""
Curve(x, y)
Represents a (plot) curve of `x` and `y` points.
When constructing a `Curve`, `missing`'s are replaced with `NaN`, and values are converted to `Float64`.
Curve objects `c` support iteration, `x, y = c`, and indexing, `x = c[1]`, `y = c[2]`.
"""
struct Curve
x::Vector{Float64}
y::Vector{Float64}
function Curve(x::Vector{Float64}, y::Vector{Float64})
length(x) == length(y) ||
throw(DimensionMismatch("Arguments to `Curve` must have same length. Got `length(x)=$(length(x))` and `length(y)=$(length(y))`"))
return new(x, y)
end
end
floatify(x) = convert(Vector{Float64}, replace(x, missing => NaN))
Curve(x, y) = Curve(floatify(x), floatify(y))
function Curve(t::Tuple)
length(t) == 2 ||
throw(ArgumentError("Arguments to `Curve` must consist of x- and y- iterators"))
return Curve(floatify(first(t)), floatify(last(t)))
end
Curve(c::Curve) = c
Base.iterate(c::Curve, st=1) = st <= fieldcount(Curve) ? (getfield(c, st), st + 1) : nothing
Base.length(::Curve) = fieldcount(Curve)
Base.size(c::Curve) = (fieldcount(Curve), length(c.x))
Base.getindex(c::Curve, i::Int) = getfield(c, i)
for op in (:(==), :isequal)
@eval function Base.$(op)(c1::Curve, c2::Curve)
return $op(c1.x, c2.x) && $op(c1.y, c2.y)
end
end
Base.hash(c::Curve, h::UInt) = hash(:Curve, hash(c.x, hash(c.y, h)))
const CURVE_ARROW_NAME = Symbol("JuliaLang.Lighthouse.Curve")
ArrowTypes.arrowname(::Type{<:Curve}) = CURVE_ARROW_NAME
ArrowTypes.JuliaType(::Val{CURVE_ARROW_NAME}) = Curve
@schema "lighthouse.class" Class
@version ClassV1 begin
class_index::Union{Int64,Symbol} = check_valid_class(class_index)
class_labels::Union{Missing,Vector{String}}
end
"""
@version ClassV1 begin
class_index::Union{Int64,Symbol} = check_valid_class(class_index)
class_labels::Union{Missing,Vector{String}}
end
A Legolas record representing a single column `class_index` that holds either an integer or
the value `:multiclass`, and the class names associated to the integer class indices.
"""
ClassV1
check_valid_class(class_index::Integer) = Int64(class_index)
function check_valid_class(class_index::Any)
return class_index === :multiclass ? class_index :
throw(ArgumentError("Classes must be integer or the symbol `:multiclass`"))
end
@schema "lighthouse.label-metrics" LabelMetrics
@version LabelMetricsV1 > ClassV1 begin
ira_kappa::Union{Missing,Float64}
per_expert_discrimination_calibration_curves::Union{Missing,Vector{Curve}} = lift(v -> Curve.(v),
per_expert_discrimination_calibration_curves)
per_expert_discrimination_calibration_scores::Union{Missing,Vector{Float64}}
end
"""
@version LabelMetricsV1 > ClassV1 begin
ira_kappa::Union{Missing,Float64}
per_expert_discrimination_calibration_curves::Union{Missing,Vector{Curve}} = lift(v -> Curve.(v),
per_expert_discrimination_calibration_curves)
per_expert_discrimination_calibration_scores::Union{Missing,Vector{Float64}}
end
A Legolas record representing metrics calculated over labels provided by multiple labelers.
See also [`get_label_metrics_multirater`](@ref) and [`get_label_metrics_multirater_multiclass`](@ref).
"""
LabelMetricsV1
@schema "lighthouse.hardened-metrics" HardenedMetrics
@version HardenedMetricsV1 > ClassV1 begin
confusion_matrix::Union{Missing,Array{Int64,1},Array{Int64,2}} = vec_to_mat(confusion_matrix)
discrimination_calibration_curve::Union{Missing,Curve} = lift(Curve,
discrimination_calibration_curve)
discrimination_calibration_score::Union{Missing,Float64}
ea_kappa::Union{Missing,Float64}
end
"""
@version HardenedMetricsV1 > ClassV1 begin
confusion_matrix::Union{Missing,Array{Int64,1},Array{Int64,2}} = vec_to_mat(confusion_matrix)
discrimination_calibration_curve::Union{Missing,Curve} = lift(Curve,
discrimination_calibration_curve)
discrimination_calibration_score::Union{Missing,Float64}
ea_kappa::Union{Missing,Float64}
end
A Legolas record representing metrics calculated over predicted hard labels.
See also [`get_hardened_metrics`](@ref), [`get_hardened_metrics_multirater`](@ref),
and [`get_hardened_metrics_multiclass`](@ref).
"""
HardenedMetricsV1
@schema "lighthouse.tradeoff-metrics" TradeoffMetrics
@version TradeoffMetricsV1 > ClassV1 begin
roc_curve::Curve = lift(Curve, roc_curve)
roc_auc::Float64
pr_curve::Curve = lift(Curve, pr_curve)
spearman_correlation::Union{Missing,Float64}
spearman_correlation_ci_upper::Union{Missing,Float64}
spearman_correlation_ci_lower::Union{Missing,Float64}
n_samples::Union{Missing,Int}
reliability_calibration_curve::Union{Missing,Curve} = lift(Curve,
reliability_calibration_curve)
reliability_calibration_score::Union{Missing,Float64}
end
"""
@version TradeoffMetricsV1 > ClassV1 begin
roc_curve::Curve = lift(Curve, roc_curve)
roc_auc::Float64
pr_curve::Curve = lift(Curve, pr_curve)
spearman_correlation::Union{Missing,Float64}
spearman_correlation_ci_upper::Union{Missing,Float64}
spearman_correlation_ci_lower::Union{Missing,Float64}
n_samples::Union{Missing,Int}
reliability_calibration_curve::Union{Missing,Curve} = lift(Curve,
reliability_calibration_curve)
reliability_calibration_score::Union{Missing,Float64}
end
A Legolas record representing metrics calculated over predicted soft labels. See also
[`get_tradeoff_metrics`](@ref) and [`get_tradeoff_metrics_binary_multirater`](@ref).
"""
TradeoffMetricsV1
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 2881 | #####
##### miscellaneous
#####
has_value(x) = !isnothing(x) && !ismissing(x)
function increment_at!(array, index_lists)
for index_list in index_lists
array[index_list...] += 1
end
return array
end
"""
area_under_curve(x, y)
Calculates the area under the curve specified by the `x` vector and `y` vector
using the trapezoidal rule. If inputs are empty, return `missing`.
"""
function area_under_curve(x, y)
length(x) == length(y) || throw(ArgumentError("Length of inputs must match."))
length(x) == 0 && return missing
auc = zero(middle(one(eltype(x)), one(eltype(y))))
perms = sortperm(x)
sorted_x = view(x, perms)
sorted_y = view(y, perms)
# calculate the trapazoidal method https://en.wikipedia.org/wiki/Trapezoidal_rule
for i in 2:length(x)
auc += middle(sorted_y[i], sorted_y[i - 1]) * (sorted_x[i] - sorted_x[i - 1])
end
return auc
end
"""
area_under_curve_unit_square(x, y)
Calculates the area under the curve specified by the `x` vector and `y` vector
for a unit square, using the trapezoidal rule. If inputs are empty, return `missing`.
"""
function area_under_curve_unit_square(x, y)
length(x) == length(y) || throw(ArgumentError("Length of inputs must match."))
kept = [(i, j)
for (i, j) in zip(x, y)
if !(ismissing(i) || ismissing(j)) && (0 <= i <= 1 && 0 <= j <= 1)]
return area_under_curve(map(k -> k[1], kept), map(k -> k[2], kept))
end
"""
majority([rng::AbstractRNG=Random.GLOBAL_RNG], hard_labels, among::UnitRange)
Return the majority label within `among` out of `hard_labels`:
```
julia> majority([1, 2, 1, 3, 2, 2, 3], 1:3)
2
julia> majority([1, 2, 1, 3, 2, 2, 3, 4], 3:4)
3
```
In the event of a tie, a winner is randomly selected from the tied labels via `rng`.
"""
function majority(rng::AbstractRNG, labels, among::UnitRange)
return rand(rng, StatsBase.modes(labels, among))
end
majority(labels, among::UnitRange) = majority(Random.GLOBAL_RNG, labels, among)
#####
##### `ResourceInfo`
#####
struct ResourceInfo
time_in_seconds::Float64
gc_time_in_seconds::Float64
allocations::Int64
memory_in_mb::Float64
end
# NOTE: This is suitable for "coarse" (i.e. long-running) `f`, not "fine" `f`;
# the latter requires the kind of infrastructure provided by BenchmarkTools.
function call_with_resource_info(f)
gc_start = Base.gc_num()
time_start = time_ns()
result = f()
time_in_seconds = ((time_ns() - time_start) / 1_000_000_000)
gc_diff = Base.GC_Diff(Base.gc_num(), gc_start)
gc_time_in_seconds = gc_diff.total_time / 1_000_000_000
allocations = gc_diff.malloc + gc_diff.realloc + gc_diff.poolalloc + gc_diff.bigalloc
memory_in_mb = gc_diff.allocd / 1024 / 1024
info = ResourceInfo(time_in_seconds, gc_time_in_seconds, allocations, memory_in_mb)
return result, info
end
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 102 | @testest "deprecations" begin
@test_throws ErrorException Lighthouse.evaluation_metrics_row()
end
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 30575 | mutable struct TestClassifier <: AbstractClassifier
dummy_loss::Float64
classes::Vector
end
Lighthouse.classes(c::TestClassifier) = c.classes
function Lighthouse.train!(c::TestClassifier, dummy_batches, logger)
for (dummy_input_batch, loss_delta) in dummy_batches
c.dummy_loss += loss_delta
Lighthouse.log_value!(logger, "train/loss_per_batch", c.dummy_loss)
end
return c.dummy_loss
end
const RNG_LOSS = StableRNG(22)
function Lighthouse.loss_and_prediction(c::TestClassifier, dummy_input_batch)
dummy_soft_label_batch = rand(RNG_LOSS, length(c.classes), size(dummy_input_batch)[end])
# Fake a softmax
dummy_soft_label_batch .= dummy_soft_label_batch ./ sum(dummy_soft_label_batch; dims=1)
return c.dummy_loss, dummy_soft_label_batch
end
@testset "`_values_or_missing`" begin
@test Lighthouse._values_or_missing(nothing) === missing
@test Lighthouse._values_or_missing(missing) === missing
@test Lighthouse._values_or_missing(1) === 1
@test Lighthouse._values_or_missing([1, 2, 3]) == [1, 2, 3]
@test Lighthouse._values_or_missing([missing]) === missing
@test Lighthouse._values_or_missing([1, missing]) === missing
input = Union{Int,Missing}[1, 2, 3]
result = Lighthouse._values_or_missing(input)
@test result == input
@test result isa Vector{Int}
input = Union{Int,Missing}[1 2; 3 4]
result = Lighthouse._values_or_missing(input)
@test result == input
@test result isa Matrix{Int}
end
@testset "Multi-class learn!(::TestModel, ...)" begin
mktempdir() do tmpdir
model = TestClassifier(1000000.0, ["class_$i" for i in 1:5])
k, n = length(model.classes), 3
rng = StableRNG(22)
train_batches = [(rand(rng, 4 * k, n), -rand(rng)) for _ in 1:100]
test_batches = [((rand(rng, 4 * k, n),), (n * i - n + 1):(n * i)) for i in 1:10]
possible_vote_labels = collect(0:k)
votes = [rand(rng, possible_vote_labels) for sample in 1:(n * 10), voter in 1:7]
votes[:, [1, 2, 3]] .= votes[:, 4] # Voter 1-3 voted identically to voter 4 (force non-zero agreement)
logger = LearnLogger(joinpath(tmpdir, "logs"), "test_run")
limit = 5
let counted = 0
upon_loss_decrease = Lighthouse.upon(logger,
"test_set_prediction/mean_loss_per_epoch";
condition=<, initial=Inf)
callback = n -> begin
upon_loss_decrease() do _
counted += n
@debug counted n
end
end
elected = majority.((rng,), eachrow(votes),
(1:length(Lighthouse.classes(model)),))
Lighthouse.learn!(model, logger, () -> train_batches, () -> test_batches, votes,
elected; epoch_limit=limit, post_epoch_callback=callback)
@test counted == sum(1:limit)
end
@test length(logger.logged["train/loss_per_batch"]) == length(train_batches) * limit
for key in ["test_set_prediction/loss_per_batch",
"test_set_prediction/time_in_seconds_per_batch",
"test_set_prediction/gc_time_in_seconds_per_batch",
"test_set_prediction/allocations_per_batch",
"test_set_prediction/memory_in_mb_per_batch"]
@test length(logger.logged[key]) == length(test_batches) * limit
end
for key in ["test_set_prediction/mean_loss_per_epoch",
"test_set_evaluation/time_in_seconds_per_epoch",
"test_set_evaluation/gc_time_in_seconds_per_epoch",
"test_set_evaluation/allocations_per_epoch",
"test_set_evaluation/memory_in_mb_per_epoch"]
@test length(logger.logged[key]) == limit
end
@test length(logger.logged["test_set_evaluation/metrics_per_epoch"]) == limit
# Test multiclass optimal_threshold param invalid
@test_throws ArgumentError Lighthouse.learn!(model, logger, () -> train_batches,
() -> test_batches, votes;
epoch_limit=limit,
optimal_threshold_class=1)
# Test `predict!`
num_samples = sum(b -> size(b[1][1], 2), test_batches)
predicted_soft = zeros(num_samples, length(model.classes))
predict!(model, predicted_soft, test_batches, logger; logger_prefix="halloooo")
@test !all(predicted_soft .== 0)
@test length(logger.logged["halloooo/mean_loss_per_epoch"]) == 1
@test length(logger.logged["halloooo/loss_per_batch"]) == length(test_batches)
@test length(logger.logged["halloooo/time_in_seconds_per_batch"]) ==
length(test_batches)
# Test `evaluate!`
n_examples = 40
num_voters = 20
predicted_soft = rand(rng, Float32, n_examples, length(model.classes))
predicted_hard = map(label -> Lighthouse.onecold(model, label),
eachrow(predicted_soft))
votes = [rand(rng, possible_vote_labels)
for sample in 1:n_examples, voter in 1:num_voters]
votes[:, 3] .= votes[:, 4] # Voter 4 voted identically to voter 3 (force non-zero agreement)
elected_hard = map(row -> majority(rng, row, 1:length(model.classes)),
eachrow(votes))
evaluate!(predicted_hard, predicted_soft, elected_hard, model.classes, logger;
logger_prefix="wheeeeeee", logger_suffix="_for_all_time", votes)
@test length(logger.logged["wheeeeeee/time_in_seconds_for_all_time"]) == 1
@test length(logger.logged["wheeeeeee/metrics_for_all_time"]) == 1
# Test plotting with no votes directly with eval row
eval_row = Lighthouse.evaluation_metrics_record(predicted_hard, predicted_soft,
elected_hard, model.classes;
votes=nothing)
all_together_no_ira = evaluation_metrics_plot(eval_row)
@testplot all_together_no_ira
# Round-trip `onehot` for codecov
onehot_hard = map(h -> vec(Lighthouse.onehot(model, h)), predicted_hard)
@test map(h -> findfirst(h), onehot_hard) == predicted_hard
# Test startified eval
strata = [Set("group $(j % Int(ceil(sqrt(j))))" for j in 1:(i - 1))
for i in 1:size(votes, 1)]
plot_data = evaluation_metrics(predicted_hard, predicted_soft, elected_hard,
model.classes, 0.0:0.01:1.0; votes, strata)
@test haskey(plot_data, "stratified_kappas")
plot = evaluation_metrics_plot(plot_data)
test_evaluation_metrics_roundtrip(plot_data)
plot2, plot_data2 = @test_deprecated evaluation_metrics_plot(predicted_hard,
predicted_soft,
elected_hard,
model.classes,
0.0:0.01:1.0;
votes=votes,
strata=strata)
@test isequal(plot_data, plot_data2) # check these are the same
test_evaluation_metrics_roundtrip(plot_data2)
# Test plotting
plot_data = last(logger.logged["test_set_evaluation/metrics_per_epoch"])
@test isa(plot_data["thresholds"], AbstractVector)
@test isa(last(plot_data["per_class_pr_curves"]),
Tuple{Vector{Float64},Vector{Float64}})
pr = plot_pr_curves(plot_data["per_class_pr_curves"], plot_data["class_labels"])
@testplot pr
roc = plot_roc_curves(plot_data["per_class_roc_curves"],
plot_data["per_class_roc_aucs"], plot_data["class_labels"])
@testplot roc
# Kappa no IRA
kappas_no_ira = plot_kappas(vcat(plot_data["multiclass_kappa"],
plot_data["per_class_kappas"]),
vcat("Multiclass", plot_data["class_labels"]))
@testplot kappas_no_ira
# Kappa with IRA
kappas_ira = plot_kappas(vcat(plot_data["multiclass_kappa"],
plot_data["per_class_kappas"]),
vcat("Multiclass", plot_data["class_labels"]),
vcat(plot_data["multiclass_IRA_kappas"],
plot_data["per_class_IRA_kappas"]))
@testplot kappas_ira
reliability_calibration = plot_reliability_calibration_curves(plot_data["per_class_reliability_calibration_curves"],
plot_data["per_class_reliability_calibration_scores"],
plot_data["class_labels"])
@testplot reliability_calibration
confusion_row = plot_confusion_matrix(plot_data["confusion_matrix"],
plot_data["class_labels"], :Row)
@testplot confusion_row
confusion_col = plot_confusion_matrix(plot_data["confusion_matrix"],
plot_data["class_labels"], :Column)
@testplot confusion_col
confusion_basic = plot_confusion_matrix(plot_data["confusion_matrix"],
plot_data["class_labels"])
@testplot confusion_basic
@test_throws ArgumentError plot_confusion_matrix(plot_data["confusion_matrix"],
plot_data["class_labels"], :norm)
all_together_2 = evaluation_metrics_plot(plot_data)
@testplot all_together_2
all_together_3 = evaluation_metrics_plot(EvaluationV1(plot_data))
@testplot all_together_3
#savefig(all_together_2, "/tmp/multiclass.png")
end
end
@testset "2-class `learn!(::TestModel, ...)`" begin
mktempdir() do tmpdir
model = TestClassifier(1000000.0, ["class_$i" for i in 1:2])
k, n = length(model.classes), 3
rng = StableRNG(23)
train_batches = [(rand(rng, 4 * k, n), -rand(rng)) for _ in 1:100]
test_batches = [((rand(rng, 4 * k, n),), (n * i - n + 1):(n * i)) for i in 1:10]
possible_vote_labels = collect(0:k)
votes = [rand(rng, possible_vote_labels) for sample in 1:(n * 10), voter in 1:7]
votes[:, [1, 2, 3]] .= votes[:, 4] # Voter 1-3 voted identically to voter 4 (force non-zero agreement)
logger = LearnLogger(joinpath(tmpdir, "logs"), "test_run")
limit = 5
let counted = 0
upon_loss_decrease = Lighthouse.upon(logger,
"test_set_prediction/mean_loss_per_epoch";
condition=<, initial=Inf)
callback = n -> begin
upon_loss_decrease() do _
counted += n
@debug counted n
end
end
elected = majority.((rng,), eachrow(votes),
(1:length(Lighthouse.classes(model)),))
Lighthouse.learn!(model, logger, () -> train_batches, () -> test_batches, votes,
elected; epoch_limit=limit, post_epoch_callback=callback)
@test counted == sum(1:limit)
end
# Binary classification logs some additional metrics
@test length(logger.logged["test_set_evaluation/spearman_correlation_per_epoch"]) ==
limit
plot_data = last(logger.logged["test_set_evaluation/metrics_per_epoch"])
@test haskey(plot_data, "spearman_correlation")
test_evaluation_metrics_roundtrip(plot_data)
# No `optimal_threshold_class` during learning...
@test !haskey(plot_data, "optimal_threshold")
@test !haskey(plot_data, "optimal_threshold_class")
# And now, `optimal_threshold_class` during learning
elected = majority.((rng,), eachrow(votes), (1:length(Lighthouse.classes(model)),))
Lighthouse.learn!(model, logger, () -> train_batches, () -> test_batches, votes,
elected; epoch_limit=limit, optimal_threshold_class=2,
test_set_logger_prefix="validation_set")
plot_data = last(logger.logged["validation_set_evaluation/metrics_per_epoch"])
@test haskey(plot_data, "optimal_threshold")
@test haskey(plot_data, "optimal_threshold_class")
@test plot_data["optimal_threshold_class"] == 2
test_evaluation_metrics_roundtrip(plot_data)
# `optimal_threshold_class` param invalid
@test_throws ArgumentError Lighthouse.learn!(model, logger, () -> train_batches,
() -> test_batches, votes;
epoch_limit=limit,
optimal_threshold_class=3)
# Test `evaluate!` for votes, no votes
n_examples = 40
num_voters = 20
predicted_soft = rand(rng, Float32, n_examples, length(model.classes))
predicted_soft .= predicted_soft ./ sum(predicted_soft; dims=2)
predicted_hard = map(label -> Lighthouse.onecold(model, label),
eachrow(predicted_soft))
votes = [rand(rng, possible_vote_labels)
for sample in 1:n_examples, voter in 1:num_voters]
votes[:, 3] .= votes[:, 4] # Voter 4 voted identically to voter 3 (force non-zero agreement)
elected_hard = map(row -> majority(rng, row, 1:length(model.classes)),
eachrow(votes))
evaluate!(predicted_hard, predicted_soft, elected_hard, model.classes, logger;
logger_prefix="wheeeeeee", logger_suffix="_for_all_time", votes=nothing)
plot_data = last(logger.logged["wheeeeeee/metrics_for_all_time"])
@test !haskey(plot_data, "per_class_IRA_kappas")
@test !haskey(plot_data, "multiclass_IRA_kappas")
test_evaluation_metrics_roundtrip(plot_data)
evaluate!(predicted_hard, predicted_soft, elected_hard, model.classes, logger;
logger_prefix="wheeeeeee", logger_suffix="_for_all_time", votes=votes)
plot_data = last(logger.logged["wheeeeeee/metrics_for_all_time"])
@test haskey(plot_data, "per_class_IRA_kappas")
@test haskey(plot_data, "multiclass_IRA_kappas")
test_evaluation_metrics_roundtrip(plot_data)
# Test `evaluate` for different optimal_threshold classes
evaluate!(predicted_hard, predicted_soft, elected_hard, model.classes, logger;
logger_prefix="wheeeeeee", logger_suffix="_for_all_time", votes=votes,
optimal_threshold_class=1)
plot_data_1 = last(logger.logged["wheeeeeee/metrics_for_all_time"])
evaluate!(predicted_hard, predicted_soft, elected_hard, model.classes, logger;
logger_prefix="wheeeeeee", logger_suffix="_for_all_time", votes=votes,
optimal_threshold_class=2)
plot_data_2 = last(logger.logged["wheeeeeee/metrics_for_all_time"])
test_evaluation_metrics_roundtrip(plot_data_2)
# The thresholds should not be identical (since they are *inclusive* when applied:
# values greater than _or equal to_ the threshold are given the class value)
@test plot_data_1["optimal_threshold"] != plot_data_2["optimal_threshold"]
# The two threshold options yield different results
thresh_from_roc = Lighthouse._get_optimal_threshold_from_ROC(plot_data_2["per_class_roc_curves"];
thresholds=plot_data_2["thresholds"],
class_of_interest_index=plot_data_2["optimal_threshold_class"])
thresh_from_calibration = Lighthouse._calculate_optimal_threshold_from_discrimination_calibration(predicted_soft,
votes;
thresholds=plot_data_2["thresholds"],
class_of_interest_index=plot_data_2["optimal_threshold_class"]).threshold
@test !isequal(thresh_from_roc, thresh_from_calibration)
@test isequal(thresh_from_calibration, plot_data_2["optimal_threshold"])
# Also, let's make sure we get an isolated discrimination plots
discrimination_cal = Lighthouse.plot_binary_discrimination_calibration_curves(plot_data_1["discrimination_calibration_curve"],
plot_data_1["discrimination_calibration_score"],
plot_data_1["per_expert_discrimination_calibration_curves"],
plot_data_1["per_expert_discrimination_calibration_scores"],
plot_data_1["optimal_threshold"],
plot_data_1["class_labels"][plot_data_1["optimal_threshold_class"]])
@testplot discrimination_cal
discrimination_cal_no_experts = Lighthouse.plot_binary_discrimination_calibration_curves(plot_data_1["discrimination_calibration_curve"],
plot_data_1["discrimination_calibration_score"],
missing,
missing,
plot_data_1["optimal_threshold"],
plot_data_1["class_labels"][plot_data_1["optimal_threshold_class"]])
# Test binary discrimination with no multiclass votes
plot_data_1["per_expert_discrimination_calibration_curves"] = missing
no_expert_calibration = evaluation_metrics_plot(EvaluationV1(plot_data_1))
@testplot no_expert_calibration
# Test that plotting succeeds (no specialization relative to the multi-class tests)
plot_data = last(logger.logged["validation_set_evaluation/metrics_per_epoch"])
all_together = evaluation_metrics_plot(plot_data)
#savefig(all_together, "/tmp/binary.png")
@testplot all_together
@testplot discrimination_cal_no_experts
end
end
@testset "Invalid `_calculate_ira_kappas`" begin
classes = ["roy", "gee", "biv"]
@test isequal(Lighthouse._calculate_ira_kappas([1; 1; 1; 1], classes),
(; per_class_IRA_kappas=missing, multiclass_IRA_kappas=missing)) # Only one voter...
@test isequal(Lighthouse._calculate_ira_kappas([1 0; 1 0; 0 1], classes),
(; per_class_IRA_kappas=missing, multiclass_IRA_kappas=missing)) # No observations in common...
end
@testset "Calculate `_spearman_corr`" begin
# Test failures for...
# ...nonbinary input
@test_throws ArgumentError Lighthouse._calculate_spearman_correlation([0.9 0.1], [1],
["oh" "em" "gee"])
# ...non-softmax input
@test_throws ArgumentError Lighthouse._calculate_spearman_correlation([0.9 0.9], [1],
["oh" "em"])
# Test class order doesn't matter
predicted = [0.1 0.9; 0.3 0.7; 1 0]
votes = [0 1 1 2; 2 2 0 0; 0 2 2 1]
predicted_flipped = [0.9 0.1; 0.7 0.3; 0 1]
votes_flipped = [0 2 2 1; 1 1 0 0; 0 1 1 2]
@test Lighthouse._calculate_spearman_correlation(predicted, votes, ["oh" "em"]) ==
Lighthouse._calculate_spearman_correlation(predicted_flipped, votes_flipped,
["em" "oh"])
# Test complete agreement
predicted_soft = [0.0 1.0; 1.0 0.0; 1.0 0.0]
votes = [2; 1; 1]
sp = Lighthouse._calculate_spearman_correlation(predicted_soft, votes, ["oh" "em"])
@test sp.ρ == 1
# Test complete disagreement
votes = [1; 2; 2]
sp = Lighthouse._calculate_spearman_correlation(predicted_soft, votes, ["oh" "em"])
@test sp.ρ == -1
# Test NaN spearman due to unranked input
votes = [1; 2; 2]
predicted_soft = [0.3 0.7
0.3 0.7
0.3 0.7]
sp = Lighthouse._calculate_spearman_correlation(predicted_soft, votes, ["oh" "em"])
@test isnan(sp.ρ)
# Test CI
sp = Lighthouse._spearman_corr([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2],
[0.1, 0.3, 0.2, 0.1, 0.3, 0.1, 0.6])
@test -1.0 < sp.ci_lower < sp.ρ < sp.ci_upper < 1.0
end
@testset "Discrimination calibration" begin
# Test single voter has same calibration as "whole" by definition
votes = [1; 1; 1; 2; 2; 2]
@test length(Lighthouse._elected_probabilities(votes, 1)) == 6
@test Lighthouse._elected_probabilities(votes, 1) == [1; 1; 1; 0; 0; 0]
# Test single voter discrimination calibration
single_voter_calibration = Lighthouse._calculate_voter_discrimination_calibration(votes;
class_of_interest_index=1)
@test length(single_voter_calibration.mse) == 1
# Test multi-voter voter discrimination calibration
votes = [0 1 1 1
1 2 0 0
2 1 2 2] # Note: voters 3 and 4 have voted identically
voter_calibration = Lighthouse._calculate_voter_discrimination_calibration(votes;
class_of_interest_index=1)
@test length(voter_calibration.mse) == size(votes, 2)
@test length(voter_calibration.plot_curve_data) == size(votes, 2)
@test voter_calibration.mse[1] > voter_calibration.mse[3]
@test !isequal(voter_calibration.plot_curve_data[1],
voter_calibration.plot_curve_data[2])
@test isequal(voter_calibration.plot_curve_data[3],
voter_calibration.plot_curve_data[4])
# Test predicted voter discrimination calibration
predicted_soft_labels = [1.0 0.0; 0.0 1.0; 0.0 1.0]
cal = Lighthouse._calculate_optimal_threshold_from_discrimination_calibration(predicted_soft_labels,
votes;
thresholds=0.0:0.01:1.0,
class_of_interest_index=1)
@test all(cal.mse .<= voter_calibration.mse)
cal2 = Lighthouse._calculate_optimal_threshold_from_discrimination_calibration(predicted_soft_labels,
votes;
thresholds=0.0:0.01:1.0,
class_of_interest_index=2)
@test cal.mse == cal2.mse
@test cal.plot_curve_data[2] != cal2.plot_curve_data[2]
end
@testset "2-class per_class_confusion_statistics" begin
predicted_soft_labels = [0.51 0.49
0.49 0.51
0.1 0.9
0.9 0.1
0.0 1.0]
elected_hard_labels = [1, 2, 2, 2, 1]
thresholds = [0.25, 0.5, 0.75]
class_1, class_2 = Lighthouse.per_class_confusion_statistics(predicted_soft_labels,
elected_hard_labels,
thresholds)
stats_1, stats_2 = class_1[1], class_2[1] # threshold == 0.25
@test stats_1.actual_negatives == stats_2.actual_positives == 3
@test stats_1.actual_positives == stats_2.actual_negatives == 2
@test stats_1.predicted_positives == 3
@test stats_2.predicted_positives == 4
@test stats_1.predicted_negatives == 2
@test stats_2.predicted_negatives == 1
@test stats_1.true_positives == 1
@test stats_2.true_positives == 2
@test stats_1.true_negatives == 1
@test stats_2.true_negatives == 0
@test stats_1.false_positives == 2
@test stats_2.false_positives == 2
@test stats_1.false_negatives == 1
@test stats_2.false_negatives == 1
@test stats_1.true_positive_rate == 0.5
@test stats_2.true_positive_rate == 2 / 3
@test stats_1.true_negative_rate == 1 / 3
@test stats_2.true_negative_rate == 0.0
@test stats_1.false_positive_rate == 2 / 3
@test stats_2.false_positive_rate == 1.0
@test stats_1.false_negative_rate == 0.5
@test stats_2.false_negative_rate == 1 / 3
@test stats_1.precision == 1 / 3
@test stats_2.precision == 0.5
stats_1, stats_2 = class_1[2], class_2[2] # threshold == 0.5
@test stats_1.actual_negatives == stats_2.actual_positives == 3
@test stats_1.actual_positives == stats_2.actual_negatives == 2
@test stats_1.predicted_negatives == stats_2.predicted_positives == 3
@test stats_1.predicted_positives == stats_2.predicted_negatives == 2
@test stats_1.true_negatives == stats_2.true_positives == 2
@test stats_1.true_positives == stats_2.true_negatives == 1
@test stats_1.false_positives == stats_2.false_negatives == 1
@test stats_1.false_negatives == stats_2.false_positives == 1
@test stats_1.true_positive_rate == stats_2.true_negative_rate == 0.5
@test stats_1.true_negative_rate == stats_2.true_positive_rate == 2 / 3
@test stats_1.false_positive_rate == stats_2.false_negative_rate == 1 / 3
@test stats_1.false_negative_rate == stats_2.false_positive_rate == 0.5
@test stats_1.precision == 0.5 && stats_2.precision == 2 / 3
stats_1, stats_2 = class_1[3], class_2[3] # threshold == 0.75
@test stats_1.actual_negatives == stats_2.actual_positives == 3
@test stats_1.actual_positives == stats_2.actual_negatives == 2
@test stats_1.predicted_positives == 1
@test stats_2.predicted_positives == 2
@test stats_1.predicted_negatives == 4
@test stats_2.predicted_negatives == 3
@test stats_1.true_positives == 0
@test stats_2.true_positives == 1
@test stats_1.true_negatives == 2
@test stats_2.true_negatives == 1
@test stats_1.false_positives == 1
@test stats_2.false_positives == 1
@test stats_1.false_negatives == 2
@test stats_2.false_negatives == 2
@test stats_1.true_positive_rate == 0.0
@test stats_2.true_positive_rate == 1 / 3
@test stats_1.true_negative_rate == 2 / 3
@test stats_2.true_negative_rate == 0.5
@test stats_1.false_positive_rate == 1 / 3
@test stats_2.false_positive_rate == 0.5
@test stats_1.false_negative_rate == 1.0
@test stats_2.false_negative_rate == 2 / 3
@test stats_1.precision == 0.0
@test stats_2.precision == 0.5
end
@testset "3-class per_class_confusion_statistics" begin
predicted_soft_labels = [1/3 1/3 1/3
0.1 0.7 0.2
0.25 0.25 0.5
0.4 0.5 0.1
0.0 0.0 1.0
0.2 0.5 0.3
0.5 0.4 0.1]
elected_hard_labels = [1, 2, 2, 1, 3, 3, 1]
# TODO would be more robust to have multiple thresholds, but our naive tests
# here will have to be refactored to avoid becoming a nightmare if we do that
thresholds = [0.5]
class_1, class_2, class_3 = Lighthouse.per_class_confusion_statistics(predicted_soft_labels,
elected_hard_labels,
thresholds)
stats_1, stats_2, stats_3 = class_1[], class_2[], class_3[] # threshold == 0.5
@test stats_1.predicted_positives == 1
@test stats_2.predicted_positives == 3
@test stats_3.predicted_positives == 2
@test stats_1.predicted_negatives == 6
@test stats_2.predicted_negatives == 4
@test stats_3.predicted_negatives == 5
@test stats_1.actual_positives == 3
@test stats_2.actual_positives == 2
@test stats_3.actual_positives == 2
@test stats_1.actual_negatives == 4
@test stats_2.actual_negatives == 5
@test stats_3.actual_negatives == 5
@test stats_1.true_positives == 1
@test stats_2.true_positives == 1
@test stats_3.true_positives == 1
@test stats_1.true_negatives == 4
@test stats_2.true_negatives == 3
@test stats_3.true_negatives == 4
@test stats_1.false_positives == 0
@test stats_2.false_positives == 2
@test stats_3.false_positives == 1
@test stats_1.false_negatives == 2
@test stats_2.false_negatives == 1
@test stats_3.false_negatives == 1
@test stats_1.true_positive_rate == 1 / 3
@test stats_2.true_positive_rate == 0.5
@test stats_3.true_positive_rate == 0.5
@test stats_1.true_negative_rate == 1.0
@test stats_2.true_negative_rate == 0.6
@test stats_3.true_negative_rate == 0.8
@test stats_1.false_positive_rate == 0.0
@test stats_2.false_positive_rate == 0.4
@test stats_3.false_positive_rate == 0.2
@test stats_1.false_negative_rate == 2 / 3
@test stats_2.false_negative_rate == 0.5
@test stats_3.false_negative_rate == 0.5
@test stats_1.precision == 1.0
@test stats_2.precision == 1 / 3
@test stats_3.precision == 0.5
end
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 1863 | @testset "`Log forwarding`" begin
mktempdir() do logdir
vector = rand(10)
data = Dict("string" => "asdf", "int" => 42, "float64" => 42.0, "float32" => 42.0f0,
"vector" => vector, "dict" => Dict("a" => 0, 42 => identity))
logger = LearnLogger(logdir, "test_run")
channel = Channel()
forwarding_task = Lighthouse.forward_logs(channel, logger)
N = 5
for _ in 1:N
for (field, value) in data
put!(channel, field => value)
end
put!(channel, "events" => "happens")
end
put!(channel, "plotted" => vector)
close(channel)
wait(forwarding_task)
loaded = logger.logged
for (k, v) in data
if typeof(v) <: Union{Real,Complex}
@test length(loaded[k]) == N
@test first(loaded[k]) == v
end
end
end
end
@testset "`Generic datastructure logging`" begin
mktempdir() do logdir
logger = LearnLogger(logdir, "test_run")
@test isnothing(Lighthouse.log_line_series!(logger, "foo", 3, 2))
@test isnothing(step_logger!(logger))
end
end
@testset "log_values!" begin
mktempdir() do logdir
logger = LearnLogger(logdir, "test_run")
log_values!(logger, Dict("a" => 1, "b" => 2))
@test logger.logged["a"] == [1]
@test logger.logged["b"] == [2]
end
end
@testset "`log_array` and `log_arrays!`" begin
mktempdir() do logdir
logger = LearnLogger(logdir, "test_run")
log_array!(logger, "arr", [1.0, 2.0, 3.0])
@test logger.logged["arr"] == [2.0] # defaults to the mean
log_arrays!(logger, Dict("arr2" => [1.0, 2.0, 3.0], "arr3" => [1.0]))
@test logger.logged["arr2"] == [2.0]
@test logger.logged["arr3"] == [1.0]
end
end
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 11323 | @testset "agreement/confusion matrix tests" begin
hard_label_pairs = zip([1, 1, 3, 1, 3, 1, 2, 1], [2, 2, 1, 1, 3, 2, 3, 1])
c = confusion_matrix(3, hard_label_pairs)
@test c == [2 3 0
0 0 1
1 0 1]
kappa, percent_agreement = cohens_kappa(3, hard_label_pairs)
chance = Lighthouse._probability_of_chance_agreement(3, hard_label_pairs)
@test chance == (5 * 3 + 1 * 3 + 2 * 2) / 8^2
@test accuracy(c) == percent_agreement == 3 / 8
@test kappa == (3 / 8 - chance) / (1 - chance)
stats = binary_statistics(c, 3)
total = sum(c)
@test total == 8
@test stats.predicted_positives == 2
@test stats.predicted_negatives == 6
@test stats.actual_positives == 2
@test stats.actual_negatives == 6
@test stats.true_positives == 1
@test stats.true_negatives == 5
@test stats.false_positives == 1
@test stats.false_negatives == 1
@test stats.true_positive_rate == 0.5
@test stats.true_negative_rate == 5 / 6
@test stats.false_positive_rate == 1 / 6
@test stats.false_negative_rate == 0.5
@test stats.precision == 0.5
@test stats.f1 == 0.5
@test stats.true_positives + stats.true_negatives + stats.false_positives +
stats.false_negatives == total
@test stats.actual_positives + stats.actual_negatives == total
@test stats.predicted_positives + stats.predicted_negatives == total
labels = rand(StableRNG(42), 1:3, 100)
hard_label_pairs = zip(labels, labels)
c = confusion_matrix(3, hard_label_pairs)
@test tr(c) == length(labels) == sum(c)
kappa, percent_agreement = cohens_kappa(3, hard_label_pairs)
@test accuracy(c) == percent_agreement == 1
@test kappa == 1
for i in 1:3
stats = binary_statistics(c, i)
@test stats.predicted_positives == stats.true_positives == stats.actual_positives
@test stats.predicted_negatives == stats.true_negatives == stats.actual_negatives
@test stats.false_positives == stats.false_negatives == 0
@test stats.true_positive_rate == stats.true_negative_rate == 1
@test stats.false_positive_rate == stats.false_negative_rate == 0
@test stats.precision == 1
@test stats.f1 == 1
end
n, k = 1_000_000, 2
rng = StableRNG(42)
hard_label_pairs = zip(rand(rng, 1:k, n), rand(rng, 1:k, n))
c = confusion_matrix(k, hard_label_pairs)
kappa, percent_agreement = cohens_kappa(3, hard_label_pairs)
@test percent_agreement == accuracy(c)
@test isapprox(percent_agreement, 0.5; atol=0.02)
@test isapprox(kappa, 0.0; atol=0.02)
stats = binary_statistics(c, 1)
@test isapprox(stats.predicted_positives, 500_000; atol=2000)
@test isapprox(stats.predicted_negatives, 500_000; atol=2000)
@test isapprox(stats.actual_positives, 500_000; atol=2000)
@test isapprox(stats.actual_negatives, 500_000; atol=2000)
@test isapprox(stats.true_positives, 250_000; atol=2000)
@test isapprox(stats.true_negatives, 250_000; atol=2000)
@test isapprox(stats.false_positives, 250_000; atol=2000)
@test isapprox(stats.false_negatives, 250_000; atol=2000)
@test isapprox(stats.true_positive_rate, 0.5; atol=0.02)
@test isapprox(stats.true_negative_rate, 0.5; atol=0.02)
@test isapprox(stats.false_positive_rate, 0.5; atol=0.02)
@test isapprox(stats.false_negative_rate, 0.5; atol=0.02)
@test isapprox(stats.precision, 0.5; atol=0.02)
@test isapprox(stats.f1, 0.5; atol=0.02)
@test confusion_matrix(10, ()) == zeros(10, 10)
@test all(isnan, cohens_kappa(10, ()))
@test isnan(accuracy(zeros(10, 10)))
stats = binary_statistics(zeros(10, 10), 1)
@test stats.predicted_positives == 0
@test stats.predicted_negatives == 0
@test stats.actual_positives == 0
@test stats.actual_negatives == 0
@test stats.true_positives == 0
@test stats.true_negatives == 0
@test stats.false_positives == 0
@test stats.false_negatives == 0
@test stats.true_positive_rate == 1
@test stats.true_negative_rate == 1
@test stats.false_positive_rate == 0
@test stats.false_negative_rate == 0
@test isnan(stats.precision)
@test isnan(stats.f1)
c = [0 0
0 8]
stats = binary_statistics(c, 1)
@test stats.true_positives == 0
@test stats.true_negatives == 8
@test stats.false_positives == 0
@test stats.false_negatives == 0
@test isnan(stats.f1)
c = [0 2
0 6]
stats = binary_statistics(c, 1)
@test stats.true_positives == 0
@test stats.true_negatives == 6
@test stats.false_positives == 2
@test stats.false_negatives == 0
@test stats.f1 == 0
c = [0 0
2 6]
stats = binary_statistics(c, 1)
@test stats.true_positives == 0
@test stats.true_negatives == 6
@test stats.false_positives == 0
@test stats.false_negatives == 2
@test stats.f1 == 0
for p in 0:0.1:1
@test Lighthouse._cohens_kappa(p, p) == 0
if p > 0
@test Lighthouse._cohens_kappa(p / 2, p) < 0
@test Lighthouse._cohens_kappa(p, p / 2) > 0
end
end
@test_throws ArgumentError cohens_kappa(3, [(4, 5), (8, 2)])
end
@testset "`calibration_curve`" begin
rng = StableRNG(42)
probs = rand(rng, 1_000_000)
bitmask = rand(rng, Bool, 1_000_000)
bin_count = 12
bins, fractions, totals, mean_squared_error = calibration_curve(probs, bitmask;
bin_count=bin_count)
@test bin_count == length(bins)
@test first(first(bins)) == 0.0 && last(last(bins)) == 1.0
@test all(!ismissing, fractions)
@test all(!isnan, fractions)
@test all(!iszero, totals)
@test all(isapprox.(fractions, 0.5; atol=0.02))
@test all(isapprox.(totals, length(probs) / bin_count; atol=1000))
@test sum(totals) == length(probs)
@test isapprox(ceil(mean(fractions) * length(bitmask)), count(bitmask); atol=1)
@test isapprox(mean_squared_error, inv(bin_count); atol=0.002)
rng = StableRNG(42)
probs = range(0.0, 1.0; length=1_000_000)
bitmask = [rand(rng) <= p for p in probs]
bin_count = 10
bins, fractions, totals, mean_squared_error = calibration_curve(probs, bitmask;
bin_count=bin_count)
ideal = range(mean(first(bins)), mean(last(bins)); length=bin_count)
@test bin_count == length(bins)
@test first(first(bins)) == 0.0 && last(last(bins)) == 1.0
@test all(!ismissing, fractions)
@test all(!isnan, fractions)
@test all(!iszero, totals)
@test all(isapprox.(fractions, ideal; atol=0.01))
@test all(totals .== 1_000_000 / bin_count)
@test isapprox(ceil(mean(fractions) * length(bitmask)), count(bitmask); atol=1)
@test isapprox(mean_squared_error, 0.0; atol=0.00001)
bitmask = reverse(bitmask)
bins, fractions, totals, mean_squared_error = calibration_curve(probs, bitmask;
bin_count=bin_count)
@test bin_count == length(bins)
@test first(first(bins)) == 0.0 && last(last(bins)) == 1.0
@test all(!ismissing, fractions)
@test all(!isnan, fractions)
@test all(!iszero, totals)
@test all(isapprox.(fractions, reverse(ideal); atol=0.01))
@test all(totals .== 1_000_000 / bin_count)
@test isapprox(ceil(mean(fractions) * length(bitmask)), count(bitmask); atol=1)
@test isapprox(mean_squared_error, 1 / 3; atol=0.01)
# Handle garbage input---ensure non-existant results are NaN
probs = fill(-1, 40)
bitmask = zeros(Bool, 40)
bins, fractions, totals, mean_squared_error = calibration_curve(probs, bitmask;
bin_count)
@test bin_count == length(bins)
@test first(first(bins)) == 0.0 && last(last(bins)) == 1.0
@test all(isnan, fractions)
@test all(iszero, totals)
@test isnan(mean_squared_error)
end
@testset "`calibration_curve`" begin
@test binarize_by_threshold(0.2, 0.8) == false
@test binarize_by_threshold(0.2, 0.2) == true
@test binarize_by_threshold(0.3, 0.2) == true
@test binarize_by_threshold.([0, 0, 0], 0.2) == [0, 0, 0]
end
@testset "Metrics hardening/binarization" begin
predicted_soft_labels = [0.51 0.49
0.49 0.51
0.1 0.9
0.9 0.1
0.0 1.0]
elected_hard_labels = [1, 2, 2, 2, 1]
thresholds = [0.25, 0.5, 0.75]
i_class = 2
class_labels = ["a", "b"]
default_metrics = get_tradeoff_metrics(predicted_soft_labels,
elected_hard_labels,
i_class; thresholds, class_labels)
# Use bogus threshold/hardening function to prove that hardening function is
# used internally
scaled_binarize_by_threshold = (soft, threshold) -> soft >= threshold / 10
scaled_thresholds = 10 .* thresholds
scaled_metrics = get_tradeoff_metrics(predicted_soft_labels,
elected_hard_labels,
i_class; thresholds=scaled_thresholds,
binarize=scaled_binarize_by_threshold,
class_labels)
@test isequal(default_metrics, scaled_metrics)
# Discrim calibration
votes = [1 1 1
0 2 2
1 2 2
1 1 2
0 1 1]
cal = Lighthouse._calculate_optimal_threshold_from_discrimination_calibration(predicted_soft_labels,
votes;
thresholds,
class_of_interest_index=i_class)
scaled_cal = Lighthouse._calculate_optimal_threshold_from_discrimination_calibration(predicted_soft_labels,
votes;
class_of_interest_index=i_class,
thresholds=scaled_thresholds,
binarize=scaled_binarize_by_threshold)
for k in keys(cal)
if k == :threshold
@test cal[k] * 10 == scaled_cal[k] # Should be the same _relative_ threshold
else
@test isequal(cal[k], scaled_cal[k])
end
end
conf = Lighthouse.per_class_confusion_statistics(predicted_soft_labels,
elected_hard_labels, thresholds)
scaled_conf = Lighthouse.per_class_confusion_statistics(predicted_soft_labels,
elected_hard_labels,
scaled_thresholds;
binarize=scaled_binarize_by_threshold)
@test isequal(conf, scaled_conf)
end
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 2720 | # Make sure we cover all edge cases in the plotting code
using Makie.Colors: Gray
@testset "plotting" begin
@testset "NaN color" begin
confusion = [NaN 0;
1.0 0.5]
nan_confusion = plot_confusion_matrix(confusion, ["test1", "test2"], :Row)
@testplot nan_confusion
nan_custom_confusion = with_theme(;
ConfusionMatrix=(Heatmap=(nan_color=:red,),
Text=(color=:red,))) do
return plot_confusion_matrix(confusion, ["test1", "test2"], :Row)
end
@testplot nan_custom_confusion
end
@testset "Kappa placement" begin
classes = ["class $i" for i in 1:5]
kappa_text_placement = with_theme(; Kappas=(Text=(color=Gray(0.5),),)) do
return plot_kappas((1:5) ./ 5 .- 0.1, classes, (1:5) ./ 5;
color=[Gray(0.4), Gray(0.2)])
end
@testplot kappa_text_placement
kappa_text_placement_single = with_theme(; Kappas=(Text=(color=:red,),)) do
return plot_kappas((1:5) ./ 5, classes; color=[Gray(0.4), Gray(0.2)])
end
@testplot kappa_text_placement_single
end
@testset "binary discriminiation calibration curves" begin
rng = StableRNG(22)
curves = [(LinRange(0, 1, 10),
range(0; stop=i / 2, length=10) .+ (randn(rng, 10) .* 0.1))
for i in -1:3]
theme = (; Ideal=(linewidth=3, color=(:green, 0.5)),
CalibrationCurve=(solid_color=:green,
markersize=50, # should be overwritten by user kw
linewidth=5),
PerExpert=(solid_color=:red, linewidth=1))
plot = with_theme(; BinaryDiscriminationCalibrationCurves=theme) do
return Lighthouse.plot_binary_discrimination_calibration_curves(curves[3],
rand(rng, 5),
curves[[1, 2, 4,
5]],
nothing,
nothing,
"";
markersize=10)
end
binary_discrimination_calibration_curves_plot = plot
@testplot binary_discrimination_calibration_curves_plot
end
end
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 7830 | @testset "`vec_to_mat`" begin
mat = [3 5 6; 6 7 8; 9 10 11]
@test Lighthouse.vec_to_mat(vec(mat)) == mat
@test Lighthouse.vec_to_mat(mat) == mat
@test ismissing(Lighthouse.vec_to_mat(missing))
@test_throws DimensionMismatch Lighthouse.vec_to_mat(collect(1:6)) # Invalid dimensions
end
@testset "`EvaluationV1` basics" begin
# Most Evaluation testing happens via the `test_evaluation_metrics_roundtrip`
# in test/learn.jl
# Roundtrip from dict
dict = Dict("class_labels" => ["foo", "bar"], "multiclass_kappa" => 3)
test_evaluation_metrics_roundtrip(dict)
# Handle fun case
mat_dict = Dict("confusion_matrix" => [3 5 6; 6 7 8; 9 10 11])
test_evaluation_metrics_roundtrip(mat_dict)
end
function test_roundtrip_observation_table(; kwargs...)
table = Lighthouse._inputs_to_observation_table(; kwargs...)
rt_inputs = Lighthouse._observation_table_to_inputs(table)
@test issetequal(keys(kwargs), keys(rt_inputs))
for k in keys(kwargs)
@test isequal(kwargs[k], rt_inputs[k]) || k
end
return table
end
@testset "`ObservationV1`" begin
# Multiclass
num_observations = 100
classes = ["A", "B", "C", "D"]
predicted_soft_labels = rand(StableRNG(22), Float32, num_observations, length(classes))
predicted_hard_labels = map(argmax, eachrow(predicted_soft_labels))
# Single labeler: round-trip `ObservationV1`...
elected_hard_one_labeller = predicted_hard_labels[[1:50..., 1:50...]] # Force 50% TP overall
votes = missing
table = test_roundtrip_observation_table(; predicted_soft_labels, predicted_hard_labels,
elected_hard_labels=elected_hard_one_labeller,
votes)
# ...and parity in evaluation_metrics calculation:
metrics_from_inputs = Lighthouse.evaluation_metrics_record(predicted_hard_labels,
predicted_soft_labels,
elected_hard_one_labeller,
classes; votes)
metrics_from_table = Lighthouse.evaluation_metrics_record(table, classes)
@test isequal(metrics_from_inputs, metrics_from_table)
# Multiple labelers: round-trip `ObservationV1`...
for num_voters in (1, 5)
possible_vote_labels = collect(0:length(classes)) # vote 0 == "no vote"
vote_rng = StableRNG(22)
votes = [rand(vote_rng, possible_vote_labels)
for sample in 1:num_observations, voter in 1:num_voters]
if num_voters >= 4
votes[:, 3] .= votes[:, 4] # Voter 4 voted identically to voter 3 (force non-zero agreement)
end
elected_hard_multilabeller = map(row -> majority(vote_rng, row, 1:length(classes)),
eachrow(votes))
table = test_roundtrip_observation_table(; predicted_soft_labels,
predicted_hard_labels,
elected_hard_labels=elected_hard_multilabeller,
votes)
# ...is there parity in evaluation_metrics calculations?
metrics_from_inputs = Lighthouse.evaluation_metrics_record(predicted_hard_labels,
predicted_soft_labels,
elected_hard_multilabeller,
classes; votes)
metrics_from_table = Lighthouse.evaluation_metrics_record(table, classes)
@test isequal(metrics_from_inputs, metrics_from_table)
r_table = Lighthouse._inputs_to_observation_table(; predicted_soft_labels,
predicted_hard_labels,
elected_hard_labels=elected_hard_multilabeller,
votes)
@test Legolas.complies_with(Tables.schema(r_table),
Lighthouse.ObservationV1SchemaVersion())
# ...can we handle both dataframe input and more generic row iterators?
df_table = DataFrame(r_table)
output_r = Lighthouse._observation_table_to_inputs(r_table)
output_df = Lighthouse._observation_table_to_inputs(df_table)
@test isequal(output_r, output_df)
# Safety last!
transform!(df_table, :votes => ByRow(v -> isodd(sum(v)) ? missing : v);
renamecols=false)
@test_throws ArgumentError Lighthouse._observation_table_to_inputs(df_table)
transform!(df_table, :votes => ByRow(v -> ismissing(v) ? [1, 2, 3] : v);
renamecols=false)
@static if VERSION < v"1.10"
# the error type changed between Julia versions!
@test_throws ArgumentError Lighthouse._observation_table_to_inputs(df_table)
else
@test_throws DimensionMismatch Lighthouse._observation_table_to_inputs(df_table)
end
@test_throws DimensionMismatch Lighthouse._inputs_to_observation_table(;
predicted_soft_labels,
predicted_hard_labels=predicted_hard_labels[1:4],
elected_hard_labels=elected_hard_multilabeller,
votes)
end
end
@testset "`ClassV1" begin
@test isa(Lighthouse.ClassV1(; class_index=3, class_labels=missing).class_index, Int64)
@test isa(Lighthouse.ClassV1(; class_index=Int8(3), class_labels=missing).class_index,
Int64)
@test Lighthouse.ClassV1(; class_index=:multiclass).class_index == :multiclass
@test Lighthouse.ClassV1(; class_index=:multiclass,
class_labels=["a", "b"]).class_labels == ["a", "b"]
@test_throws ArgumentError Lighthouse.ClassV1(; class_index=3.0f0,
class_labels=missing)
@test_throws ArgumentError Lighthouse.ClassV1(; class_index=:mUlTiClAsS,
class_labels=missing)
end
@testset "class_labels" begin
predicted_soft_labels = [0.51 0.49
0.49 0.51
0.1 0.9
0.9 0.1
0.0 1.0]
elected_hard_labels = [1, 2, 2, 2, 1]
predicted_hard_labels = [1, 2, 2, 1, 2]
thresholds = [0.25, 0.5, 0.75]
i_class = 2
class_labels = ["a", "b"]
default_metrics = get_tradeoff_metrics(predicted_soft_labels,
elected_hard_labels,
i_class; thresholds, class_labels)
@test default_metrics.class_labels == class_labels
end
@testset "`Curve`" begin
c = ([1, 2, 3], [4, 5, 6])
@test Curve(c...) isa Curve
@test Curve(c) isa Curve
@test Curve(1:8, 2:9) isa Curve
@test Curve([], []) isa Curve
@test Curve(Float64[], Float64[]) isa Curve
@test_throws DimensionMismatch Curve([2], [])
@test_throws ArgumentError Curve((3, 2, 1))
@test isequal(Lighthouse.floatify([3, missing, 2.4]), Float64[3, NaN, 2.4])
curve = Curve(c...)
@test length(curve) == 2
@test size(curve) == (2, 3)
@test isequal(curve, Curve(c...))
@test first(Arrow.Table(Arrow.tobuffer([curve])).x) == curve.x
@test first(Arrow.Table(Arrow.tobuffer([curve])).y) == curve.y
end
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 2354 | using Test, LinearAlgebra, Statistics
using StableRNGs
using Lighthouse
using Lighthouse: plot_reliability_calibration_curves, plot_pr_curves,
plot_roc_curves, plot_kappas, plot_confusion_matrix,
evaluation_metrics_plot, evaluation_metrics, binarize_by_threshold
using Base.Threads
using CairoMakie
using Legolas, Tables
using DataFrames
using Arrow
# Needs to be set for figures
# returning true for showable("image/png", obj)
# which TensorBoardLogger.jl uses to determine output
CairoMakie.activate!(; type="png")
plot_results = joinpath(@__DIR__, "plot_results")
# Remove any old plots
isdir(plot_results) && rm(plot_results; force=true, recursive=true)
mkdir(plot_results)
macro testplot(fig_name)
path = joinpath(plot_results, string(fig_name, ".png"))
return quote
fig = $(esc(fig_name))
@test fig isa Makie.FigureLike
save($(path), fig)
end
end
const EVALUATION_V1_KEYS = string.(fieldnames(EvaluationV1))
function test_evaluation_metrics_roundtrip(row_dict::Dict{String,S}) where {S}
# Make sure all metrics keys are captured in our schema and are not thrown away
keys_not_in_schema = setdiff(keys(row_dict), EVALUATION_V1_KEYS)
@test isempty(keys_not_in_schema)
# Do the roundtripping (will fail if schema types do not validate after roundtrip)
record = EvaluationV1(row_dict)
rt_row = roundtrip_row(record)
# Make sure full row roundtrips correctly
@test issetequal(keys(record), keys(rt_row))
for (k, v) in pairs(record)
if ismissing(v)
@test ismissing(rt_row[k])
else
@test issetequal(v, rt_row[k])
end
end
# Make sure originating metrics dictionary roundtrips correctly
rt_dict = Lighthouse._evaluation_dict(rt_row)
for (k, v) in pairs(row_dict)
if ismissing(v)
@test ismissing(rt_dict[k])
else
@test issetequal(v, rt_dict[k])
end
end
return nothing
end
function roundtrip_row(row::EvaluationV1)
io = IOBuffer()
tbl = [row]
Legolas.write(io, tbl, Lighthouse.EvaluationV1SchemaVersion())
return EvaluationV1(only(Tables.rows(Legolas.read(seekstart(io)))))
end
include("plotting.jl")
include("metrics.jl")
include("learn.jl")
include("utilities.jl")
include("logger.jl")
include("row.jl")
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | code | 1328 | @testset "`majority`" begin
@test majority([1, 2, 1, 3, 2, 2, 3], 1:3) == 2
@test majority([1, 2, 1, 3, 2, 2, 3, 4], 3:4) == 3
rng = StableRNG(42)
picked = [majority(rng, 1:2, 1:2) for _ in 1:1_000_000]
@test isapprox(count(==(1), picked), 500_000; atol=1000)
end
@testset "`Lighthouse.area_under_curve`" begin
@test_throws ArgumentError Lighthouse.area_under_curve([0, 1, 2], [0, 1])
@test ismissing(Lighthouse.area_under_curve([], []))
@test isapprox(Lighthouse.area_under_curve(collect(0:0.01:1), collect(0:0.01:1)), 0.5;
atol=0.01)
@test isapprox(Lighthouse.area_under_curve(collect(0:0.01:(2π)), sin.(0:0.01:(2π))),
0.0; atol=0.01)
end
@testset "`Lighthouse.area_under_curve_unit_square`" begin
@test_throws ArgumentError Lighthouse.area_under_curve_unit_square([0, 1, 2], [0, 1])
@test ismissing(Lighthouse.area_under_curve_unit_square([], []))
@test isapprox(Lighthouse.area_under_curve_unit_square(collect(0:0.01:1),
collect(0:0.01:1)), 0.5;
atol=0.01)
@test isapprox(Lighthouse.area_under_curve_unit_square(collect(0:0.01:(2π)),
sin.(0:0.01:(2π))), 0.459;
atol=0.01)
end
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | docs | 2574 | <div align="center">
<img src="docs/src/assets/logo.svg"
alt="Lighthouse.jl"
height="128"
width="128">
</div>
# Lighthouse.jl
[](https://github.com/beacon-biosignals/Lighthouse.jl/actions/workflows/CI.yml)
[](https://codecov.io/gh/beacon-biosignals/Lighthouse.jl)
[](https://beacon-biosignals.github.io/Lighthouse.jl/stable)
[](https://beacon-biosignals.github.io/Lighthouse.jl/dev)
Lighthouse.jl is a Julia package that standardizes and automates performance evaluation for multiclass, multirater classification models. By implementing a minimal interface, your classifier automagically gains a thoroughly instrumented training/testing harness (`Lighthouse.learn!`) that computes and logs tons of meaningful performance metrics to TensorBoard in real-time, including:
- test set loss
- inter-rater agreement (e.g. Cohen's Kappa)
- PR curves
- ROC curves
- calibration curves
Lighthouse itself is framework-agnostic; end-users should use whichever extension package matches their desired framework (e.g. https://github.com/beacon-biosignals/LighthouseFlux.jl).
This package follows the [YASGuide](https://github.com/jrevels/YASGuide).
## Installation
To install Lighthouse for development, run:
```
julia -e 'using Pkg; Pkg.develop(PackageSpec(url="https://github.com/beacon-biosignals/Lighthouse.jl"))'
```
This will install Lighthouse to the default package development directory, `~/.julia/dev/Lighthouse`.
### TensorBoard
Note that Lighthouse's `LearnLogger` logs metrics to a user-specified path in [TensorBoard's](https://github.com/tensorflow/tensorboard) `logdir` format. TensorBoard can be installed via `python3 -m pip install tensorboard` (note: if you have `tensorflow>=1.14`, you should already have `tensorboard`). Once TensorBoard is installed, you can view Lighthouse-generated metrics via `tensorboard --logdir path` where `path` is the path specified by `Lighthouse.LearnLogger`. From there, TensorBoard itself can be used/configured however you like; see https://github.com/tensorflow/tensorboard for more information.
You can use alternative loggers, as long as they comply with the [logging interface](https://beacon-biosignals.github.io/Lighthouse.jl/dev#The-logging-interface).
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | docs | 2017 | # API Documentation
```@meta
CurrentModule = Lighthouse
```
## The `AbstractClassifier` Interface
```@docs
AbstractClassifier
Lighthouse.classes
Lighthouse.train!
Lighthouse.loss_and_prediction
Lighthouse.onehot
Lighthouse.onecold
Lighthouse.is_early_stopping_exception
```
## The `learn!` Interface
```@docs
learn!
evaluate!
predict!
```
## The logging interface
The following "primitives" must be defined for a logger to be used with Lighthouse:
```@docs
log_value!
log_line_series!
log_plot!
step_logger!
```
in addition to `Base.flush(logger)` (which can be a no-op by defining `Base.flush(::MyLoggingType) = nothing`).
These primitives can be used in implementations of [`train!`](@ref), [`evaluate!`](@ref), and [`predict!`](@ref), as well as in the following composite logging functions, which by default call the above primitives. Loggers may provide custom implementations of these.
```@docs
log_event!
Lighthouse.log_evaluation_row!
log_values!
log_array!
log_arrays!
```
### `LearnLogger`s
`LearnLoggers` are a Tensorboard-backed logger which comply with the above logging interface. They also support additional callback functionality with `upon`:
```@docs
LearnLogger
upon
Lighthouse.forward_logs
flush(::LearnLogger)
```
## Performance Metrics
```@docs
confusion_matrix
accuracy
binary_statistics
cohens_kappa
calibration_curve
EvaluationV1
ObservationV1
Lighthouse.evaluation_metrics
Lighthouse._evaluation_dict
Lighthouse.evaluation_metrics_record
Lighthouse.ClassV1
TradeoffMetricsV1
get_tradeoff_metrics
get_tradeoff_metrics_binary_multirater
HardenedMetricsV1
get_hardened_metrics
get_hardened_metrics_multirater
get_hardened_metrics_multiclass
LabelMetricsV1
get_label_metrics_multirater
get_label_metrics_multirater_multiclass
Lighthouse._evaluation_record
Lighthouse._calculate_ea_kappas
Lighthouse._calculate_ira_kappas
Lighthouse._calculate_spearman_correlation
```
## Utilities
```@docs
majority
Lighthouse.area_under_curve
Lighthouse.area_under_curve_unit_square
Curve
```
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 0.17.1 | 39fe73c0b93325c2b6054d26824d8178f878efca | docs | 7304 | !!! note
All plotting functions require a valid Makie backend, e.g. CairoMakie, to be loaded.
If there is no backend loaded, then functions won't do anything interesting.
On Julia 1.9+, Makie is a weak dependency and so won't incur any compilation/dependency
cost without a backend. On Julia < 1.9, Makie will still be loaded, but without a
backend, the resulting figure will not be rendered.
# Confusion matrices
```@docs
Lighthouse.plot_confusion_matrix
```
```@setup 1
using Lighthouse
using CairoMakie
CairoMakie.activate!(type = "png")
using StableRNGs
const RNG = StableRNG(22)
stable_rand(args...) = rand(RNG, args...)
stable_randn(args...) = randn(RNG, args...)
```
```@example 1
using Lighthouse: plot_confusion_matrix, plot_confusion_matrix!
classes = ["red", "orange", "yellow", "green"]
ground_truth = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
predicted_labels = [1, 1, 1, 1, 2, 2, 4, 4, 4, 4, 4, 3]
confusion = Lighthouse.confusion_matrix(length(classes), zip(predicted_labels, ground_truth))
fig, ax, p = plot_confusion_matrix(confusion, classes)
```
```@example 1
fig = Figure(size=(800, 400))
plot_confusion_matrix!(fig[1, 1], confusion, classes, :Row, annotation_text_size=14)
plot_confusion_matrix!(fig[1, 2], confusion, classes, :Column, annotation_text_size=14)
fig
```
## Theming
All plots are globally themeable, by setting their `camelcase(functionname)` to a theme. Usually, there are a few sub categories, for e.g. axis, text and subplots.
!!! warning
Make sure, that you spell names correctly and fully construct the named tuples in the calls. E.g. `(color=:red)` is _not_ a named tuple - it needs to be `(color=:red,)`. Misspelled names and badly constructed named tuples are not easy to error on, since those theming attributes are global, and may be valid for other plots.
```@example 1
with_theme(
ConfusionMatrix = (
Text = (
color=:yellow,
),
Heatmap = (
colormap=:greens,
),
Axis = (
backgroundcolor=:black,
xticklabelrotation=0.0,
)
)
) do
plot_confusion_matrix(confusion, classes, :Row)
end
```
# Reliability calibration curves
```@docs
Lighthouse.plot_reliability_calibration_curves
```
```@example 1
using Lighthouse: plot_reliability_calibration_curves
classes = ["class $i" for i in 1:5]
curves = [(LinRange(0, 1, 10), range(0, stop=i/2, length=10) .+ (stable_randn(10) .* 0.1)) for i in -1:3]
plot_reliability_calibration_curves(
curves,
stable_rand(5),
classes
)
```
Note that all curve plot types accepts these types:
```@docs
Lighthouse.XYVector
Lighthouse.SeriesCurves
```
## Theming
All generic series and axis attributes can be themed via `SeriesPlot.Series` / `SeriesPlot.Axis`.
You can have a look at [the series doc to get an idea about the applicable attributes](http://makie.juliaplots.org/stable/plotting_functions/series.html).
To style specifics of a subplot inside the curve plot, e.g. the ideal lineplot, one can use the camel case function name (without `plot_`) and pass those attributes there.
So e.g the `ideal` curve inside the reliability curve can be themed like this:
```@example 1
# The axis is getting created in the seriesplot,
# to always have these kind of probabilistic series have the same axis
series_theme = (
Axis = (
backgroundcolor = (:gray, 0.1),
bottomspinevisible = false,
leftspinevisible = false,
topspinevisible = false,
rightspinevisible = false,
),
Series = (
color=:darktest,
marker=:circle
)
)
with_theme(
ReliabilityCalibrationCurves = (
Ideal = (
color=:red, linewidth=3
),
),
SeriesPlot = series_theme
) do
plot_reliability_calibration_curves(
curves,
stable_rand(5),
classes
)
end
```
# Binary Discrimination Calibration Curves
```@docs
Lighthouse.plot_binary_discrimination_calibration_curves
```
```@example 1
using Lighthouse: plot_binary_discrimination_calibration_curves
Lighthouse.plot_binary_discrimination_calibration_curves(
curves[3],
stable_rand(5),
curves[[1, 2, 4, 5]],
nothing, nothing,
"",
)
```
# PR curves
```@docs
Lighthouse.plot_pr_curves
```
```@example 1
using Lighthouse: plot_pr_curves
plot_pr_curves(
curves,
classes
)
```
## Theming
```@example 1
# The plots with only a series don't have a special keyword
with_theme(SeriesPlot = series_theme) do
plot_pr_curves(
curves,
classes
)
end
```
# ROC curves
```@docs
Lighthouse.plot_roc_curves
```
```@example 1
using Lighthouse: plot_roc_curves
plot_roc_curves(
curves,
stable_rand(5),
classes,
legend=:lt)
```
## Theming
```@example 1
# The plots with only a series don't have a special keyword
with_theme(SeriesPlot = series_theme) do
plot_roc_curves(
curves,
stable_rand(5),
classes,
legend=:lt)
end
```
# Kappas (per expert agreement)
```@docs
Lighthouse.plot_kappas
```
```@example 1
using Lighthouse: plot_kappas
plot_kappas(stable_rand(5), classes)
```
```@example 1
using Lighthouse: plot_kappas
plot_kappas(stable_rand(5), classes, stable_rand(5))
```
## Theming
```@example 1
with_theme(
Kappas = (
Axis = (
xticklabelsvisible=false,
xticksvisible=false,
leftspinevisible = false,
rightspinevisible = false,
bottomspinevisible = false,
topspinevisible = false,
),
Text = (
color = :blue,
),
BarPlot = (color=[:black, :green],)
)) do
plot_kappas((1:5) ./ 5 .- 0.1, classes, (1:5) ./ 5)
end
```
# Evaluation metrics plot
```@docs
Lighthouse.evaluation_metrics_plot
```
```@example 1
using Lighthouse: evaluation_metrics_plot
data = Dict{String, Any}()
data["confusion_matrix"] = stable_rand(0:100, 5, 5)
data["class_labels"] = classes
data["per_class_kappas"] = stable_rand(5)
data["multiclass_kappa"] = stable_rand()
data["per_class_IRA_kappas"] = stable_rand(5)
data["multiclass_IRA_kappas"] = stable_rand()
data["per_class_pr_curves"] = curves
data["per_class_roc_curves"] = curves
data["per_class_roc_aucs"] = stable_rand(5)
data["per_class_reliability_calibration_curves"] = curves
data["per_class_reliability_calibration_scores"] = stable_rand(5)
evaluation_metrics_plot(data)
```
Optionally, one can also add a binary discrimination calibration curve plot:
```@example 1
data["discrimination_calibration_curve"] = (LinRange(0, 1, 10), LinRange(0,1, 10) .+ 0.1randn(10))
data["per_expert_discrimination_calibration_curves"] = curves
# These are currently not used in plotting, but are still passed to `plot_binary_discrimination_calibration_curves`!
data["discrimination_calibration_score"] = missing
data["optimal_threshold_class"] = 1
data["per_expert_discrimination_calibration_scores"] = missing
data["optimal_threshold"] = missing
evaluation_metrics_plot(data)
```
Plots can also be generated directly from an `EvaluationV1`:
```@example 1
data_row = EvaluationV1(data)
evaluation_metrics_plot(data_row)
```
| Lighthouse | https://github.com/beacon-biosignals/Lighthouse.jl.git |
|
[
"MIT"
] | 1.0.0 | 5bd6f2605028136b4bfae88c373f7ff1a85faad9 | code | 13373 | module LatticeAnimals
using Plots
using DataStructures
using Preferences
using ProgressMeter
export setDimension, Poly, Polyomino, Polyhex, polyPlot
"""
setDimension(d)
Set the number of dimensions for the polyforms as a disk-persistent setting. A rebuilt of the package is necessary afterwards
# Arguments
* `d`: Number of dimensions
"""
function setDimension(d::Int64)
if !(d >= 2)
throw(ArgumentError("Invalid dimension: $d"))
end
# Set it in our runtime values, as well as saving it to disk
@set_preferences!("dimension" => d)
@info("New dimension set; restart your Julia session for this change to take effect!")
end
const d = @load_preference("dimension", 2)
"""
Poly(tiles, perimeter, holes)
Struct to represent a d-dimensional polyform (Animal lattice).
# Arguments
* `tiles`: Lattice points which are part of the polyform
* `perimeter`: Lattice points which are in the side perimeter of the polyform, so are neighboring a tile in the polyform
* `holes`: Number of d-dimensional holes
"""
mutable struct Poly
tiles::Set{NTuple{d, Int64}}
perimeter::Set{NTuple{d, Int64}}
holes::Int64
end
"""
Poly(n, p, basis, neighbours; doPlot)
Generate a random d-dimensional polyform of size n from the percolation distribution at p using the Metropolis algorithm. neighbours
is a list of coordinate differences to each respective neighbouring lattice point defined by the lattice and should be sorted
clock-wise to improve performance of the connectivity checks during generation. The default mixing time is 2*n^2
# Arguments
* `n`: Size of the polyform
* `p`: Percolation factor in [0, 1)
* `basis`: Lattice basis of the polyform
* `neighbours`: List of difference to the respective neighbouring tiles for the current polyform
* `doPlot`: If a scatter plot visualizing the polyform should be created (only available for 2d-polyforms)
"""
function Poly(n::Int64, p::Float64, basis::Matrix{Float64}, neighbours::Vector{NTuple{d, Int64}}; doPlot = false)
# Initialize tiles as line
tiles = Set{NTuple{d, Int64}}()
for i in 0 : n - 1
push!(tiles, Tuple(fill(0, d)) .+ i .* neighbours[1])
end
# Determine initial perimeter
perimeter = Set{NTuple{d, Int64}}()
for tile in tiles
for neighbour in neighbours
neighbour_tile = tile .+ neighbour
if !(neighbour_tile in tiles)
push!(perimeter, neighbour_tile)
end
end
end
@showprogress 1 "Shuffling..." for _ in 1 : floor(Int, 2 * n^2)
while !shuffle(tiles, perimeter, p, neighbours)
# Keep trying shuffle until it succeeds
end
end
if doPlot
polyPlot(tiles, basis, "$p-$(Dates.format(now(), "HH-MM-SS-MS"))-plot.png")
#polyPlot(tiles, perimeter, basis, "$p-$(Dates.format(now(), "HH-MM-SS-MS"))-plot.png")
end
Poly(tiles, perimeter, holes(tiles, neighbours))
end
"""
Polyomino(n, p)
Generate a random polyomino of size n from the percolation distribution at p using the Metropolis algorithm. The basis consits
of the two unit-vectors as columns in a matrix. The four neighbours are then specified each as a linear combination of the basis
vectors.
# Arguments
* `n`: Size of the polyomino
* `p`: Percolation factor in [0, 1)
"""
function Polyomino(n::Int64, p::Float64)
Poly(n, p, [1. 0.; 0. 1.], [(1, 0), (0, -1), (-1, 0), (0, 1)])
end
"""
Polyhex(n, p)
Generate a random polyhex of size n from the percolation distribution at p using the Metropolis algorithm. The basis consits
of the first unit vector and the vector of length 1 at 120 degrees to the left. The six neighbours are then specified each as a
linear combination of the basis vectors.
# Arguments
* `n`: Size of the polyhex
* `p`: Percolation factor in [0, 1)
"""
function Polyhex(n::Int64, p::Float64)
Poly(n, p, [1. -1/2; 0. sqrt(3)/2], [(1, 0), (0, -1), (-1, -1), (-1, 0), (0, 1), (1, 1)])
end
"""
boundingBox(tiles)
Calculate the smallest d-dimensional bounding box enclosing the polyform and return it as (min, max) pair for each dimension.
# Arguments
* `tiles`: Lattice points in polyform
"""
function boundingBox(tiles::Set{NTuple{d, Int64}})
# Initialize vectors for min and max with extreme values
minVec = fill(typemax(Int), d)
maxVec = fill(typemin(Int), d)
for tile in tiles
for i in 1:d
minVec[i] = min(minVec[i], tile[i])
maxVec[i] = max(maxVec[i], tile[i])
end
end
return [(minVec[i] => maxVec[i]) for i in 1:d]
end
"""
polyPlot(tiles, basis, path)
Represent 2-dimensional polyform with a scatter plot.
# Arguments
* `tiles`: Lattice points in polyform
* `basis`: Lattice basis of the polyform
* `path`: Output path
"""
function polyPlot(tiles::Set{NTuple{d, Int64}}, basis::Matrix{Float64}, path::String)
@assert d == 2 "Only 2D-Plotting is supported"
# Transform tile coordinates using lattice basis
coords = [basis * [tile...] for tile in tiles]
# Extract transformed x and y coordinates
xCoords = [c[1] for c in coords]
yCoords = [c[2] for c in coords]
# Create the plot
pl = scatter(xCoords, yCoords, title="Polyform", legend=false, xlabel="", ylabel="", aspect_ratio=:equal)
savefig(pl, path)
end
"""
polyPlot(tiles, basis, path)
Represent 2-dimensional polyform (blue) and its side perimeter (red) with a scatter plot.
# Arguments
* `tiles`: Lattice points in polyform
* `perimeter`: Lattice points in side perimeter
* `basis`: Lattice basis of the polyform
* `path`: Output path
"""
function polyPlot(tiles::Set{NTuple{d, Int64}}, perimeter::Set{NTuple{d, Int64}}, basis::Matrix{Float64}, path::String)
@assert d == 2 "Only 2D-Plotting is supported"
# Transform tile coordinates using lattice basis
tileCoords = [basis * [tile...] for tile in tiles]
perimeterCoords = [basis * [adj...] for adj in perimeter]
# Extract transformed x and y coordinates for tiles
xCoordsTiles = [c[1] for c in tileCoords]
yCoordsTiles = [c[2] for c in tileCoords]
# Extract transformed x and y coordinates for perimeter
xCoordsPeri = [c[1] for c in perimeterCoords]
yCoordsPeri = [c[2] for c in perimeterCoords]
# Create the plot with tiles in blue and perimeter in red
pl = scatter(xCoordsTiles, yCoordsTiles, color=:blue, label="Tiles", marker=:circle, aspect_ratio=:equal)
scatter!(pl, xCoordsPeri, yCoordsPeri, color=:red, label="Perimeter", marker=:square)
title!(pl, "Polyform")
xlabel!(pl, "")
ylabel!(pl, "")
savefig(pl, path)
end
"""
bfs(tiles, start, finish, neighbours)
Determine if a path in the polyform exists connecting the lattice point start and the lattice point end using Breath-First Search.
# Arguments
* `tiles`: Lattice points in polyform
* `start`: Starting point of search
* `finish`: Ending point of search
* `neighbours`: List of difference to the respective neighbouring tiles for the current polyform
"""
@inline function bfs(tiles::Set{NTuple{d, Int64}}, start::NTuple{d, Int64}, finish::NTuple{d, Int64}, neighbours::Vector{NTuple{d, Int64}})
q = Queue{NTuple{d, Int64}}()
done = Set{NTuple{d, Int64}}()
enqueue!(q, start)
push!(done, start)
while !isempty(q)
tile = dequeue!(q)
if tile == finish
return true
end
for n in neighbours
nTile = tile .+ n
if (nTile in tiles) && !(nTile in done)
enqueue!(q, nTile)
push!(done, nTile)
end
end
end
return false
end
"""
shuffle(tiles, perimeter, p, neighbours)
Execute one Markov step of the Metropolis algorithm:
1) Uniformly at random, select a tile, x, in the polyform A
2) Uniformly at random, select a tile, y, on the site perimeter of A \\setminus {x}
3) If B = (A \\setminus {x}) U {y} is a still connected, then accept it as the next polyform with probability min(1, (1-p)^(t_B-t_A)), where
t_A and t_B are the site perimeters of A and B, respectively. Otherwise, keep the current polyform A.
# Arguments
* `tiles`: Lattice points in polyform
* `perimeter`: Lattice points in side perimeter
* `p`: Percolation factor in [0, 1)
* `neighbours`: List of difference to the respective neighbouring tiles for the current polyform
"""
@inline function shuffle(tiles::Set{NTuple{d, Int64}}, perimeter::Set{NTuple{d, Int64}}, p::Float64, neighbours::Vector{NTuple{d, Int64}})
tA = length(perimeter)
# Step 1: Uniformly at random, select a tile, x, in the polyform A
x = rand(tiles)
delete!(tiles, x)
push!(perimeter, x) # removed cell will always become part of side parameter
delPerimeter = Vector{NTuple{d, Int64}}() # tiles to be removed from side perimeter
for neighbour in neighbours
neighbourTile = x .+ neighbour
# neighbours of removed tile without any other neighbours in polyform
if !any(neighbourTile .+ n in tiles for n in neighbours) && (neighbourTile in perimeter)
push!(delPerimeter, neighbourTile)
end
end
for tile in delPerimeter
delete!(perimeter, tile)
end
# Step 2: Uniformly at random, select a tile, y, on the site perimeter of A \ {x}
y = rand(perimeter)
delete!(perimeter, y)
push!(tiles, y)
# tiles to be added to the side perimeter
addPerimeter = Vector{NTuple{d, Int64}}()
for neighbour in neighbours
neighbourTile = y .+ neighbour
# neighbours of added tile which aren't in polyform and not already in perimeter
if !(neighbourTile in tiles) && !(neighbourTile in perimeter)
push!(addPerimeter, neighbourTile)
end
end
for tile in addPerimeter
push!(perimeter, tile)
end
# Step 3: If B = (A \ {x}) U {y} is a polyform, then accept it as the next polyform with probability min(1, (1-p)^(t_B-t_A)), where
# t_A and t_B are the site perimeters of A and B, respectively. Otherwise, keep the current polynomino A.
# Find x's neighboring tiles in tiles
xNeighbours = [x .+ n for n in neighbours if (x .+ n in tiles)]
# Check for circular connectivity among the selected neighbours
allConnected = true
if length(xNeighbours) > 1
for i in 1:length(xNeighbours)
if !bfs(tiles, xNeighbours[i], xNeighbours[i % length(xNeighbours) + 1], neighbours)
allConnected = false
break
end
end
end
if allConnected
# difference in side perimeter
diff = length(perimeter) - tA
accepted = true # accepted shuffle with probability (1 - p)^diff
if !iszero(p)
accepted = rand() < (1 - p)^diff;
end
if accepted
return true
end
end
# Undo all moves if not connected or not accepted
# Revert to A \ {x}
delete!(tiles, y)
for tile in addPerimeter
delete!(perimeter, tile)
end
push!(perimeter, y)
# Revert to A
push!(tiles, x)
for tile in delPerimeter
push!(perimeter, tile)
end
delete!(perimeter, x)
return false
end
"""
holes(tiles, neighbours)
Count the number of d-dimensional holes of the polyform. This is done by determining the number of connected components of the complement, so
all lattice points not in the polyform.
# Arguments
* `tiles`: Lattice points in polyform
* `neighbours`: List of difference to the respective neighbouring tiles for the current polyform
"""
function holes(tiles::Set{NTuple{d, Int64}}, neighbours::Vector{NTuple{d, Int64}})
bounds = boundingBox(tiles)
m = length(bounds)
# Adjust bounds to include the boundary of the bounding box
expandedBounds = [(b.first - 1 => b.second + 1) for b in bounds]
# Generate all points within the expanded bounding box
ranges = [b.first : b.second for b in expandedBounds]
gridPoints = Set{NTuple{m, Int64}}(Iterators.product(ranges...))
# Difference set to find the points not occupied by tiles in the bounding box
emptyPoints = setdiff(gridPoints, tiles)
# BFS to count connected components of empty points
function countComponents(points)
visited = Set{NTuple{d, Int64}}()
components = 0
while !isempty(points)
startPoint = pop!(points)
queue = Queue{NTuple{d, Int64}}()
enqueue!(queue, startPoint)
push!(visited, startPoint)
while !isempty(queue)
current = dequeue!(queue)
for neighbour in neighbours
neighbourPoint = current .+ neighbour
if neighbourPoint in points && !(neighbourPoint in visited)
enqueue!(queue, neighbourPoint)
push!(visited, neighbourPoint)
end
end
end
components += 1
points = setdiff(points, visited)
end
return components
end
# Count the connected components in the empty points
numberOfHoles = countComponents(emptyPoints) - 1
return numberOfHoles
end
end # module LatticeAnimals | LatticeAnimals | https://github.com/PhoenixSmaug/LatticeAnimals.jl.git |
|
[
"MIT"
] | 1.0.0 | 5bd6f2605028136b4bfae88c373f7ff1a85faad9 | docs | 1369 | # LatticeAnimals.jl
This packages generates random lattice animals (or sometimes called [polyforms](https://en.wikipedia.org/wiki/Polyform)) from the standard percolation model using the [Metropolis-Hasting](https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm) algorithm.
The polyform is specified by its lattice basis matrix and a list of neighbours, where each entry is a linear combination of basis vectors leading to a neighbouring lattice point. So for example the square tesselation of the polyomino squares has the basis matrix $B$ and neighbours $N$:
```math
B = \begin{pmatrix}1 & 0 \\0 & 1 \end{pmatrix} \quad \quad \quad N = \left\{\begin{pmatrix}1 \\0 \end{pmatrix}, \begin{pmatrix}0 \\1 \end{pmatrix}, \begin{pmatrix}-1 \\0 \end{pmatrix}, \begin{pmatrix}0 \\-1 \end{pmatrix}\right\}
```
The following functions are exported:
* `Poly(n, p, basis, neighbours)`: Generate a random polyform - specified in the basis-neighbours notation - of size n and percolation factor p
* `Polyomino(n, p)`: Generate a random polyomino of size n and percolation factor p
* `Polyhex(n, p)`: Generate a random polyhex of size n and percolation factor p
* `polyPlot(tiles, basis, path)`: Draw the polyform as a scatter plot and save to path
* `setDimension(d)`: Change the number of dimensions (default value: 2), a Julia restart is required afterwards | LatticeAnimals | https://github.com/PhoenixSmaug/LatticeAnimals.jl.git |
|
[
"MIT"
] | 1.1.0 | 782dd5f4561f5d267313f23853baaaa4c52ea621 | code | 231 | using Documenter, DiffResults
makedocs(
modules=[DiffResults],
doctest = false,
sitename = "DiffResults",
pages = ["Documentation" => "index.md"])
deploydocs(
repo = "github.com/JuliaDiff/DiffResults.jl.git")
| DiffResults | https://github.com/JuliaDiff/DiffResults.jl.git |
|
[
"MIT"
] | 1.1.0 | 782dd5f4561f5d267313f23853baaaa4c52ea621 | code | 11508 | module DiffResults
using StaticArraysCore: StaticArray, similar_type, Size
#########
# Types #
#########
abstract type DiffResult{O,V,D<:Tuple} end
struct ImmutableDiffResult{O,V,D<:Tuple} <: DiffResult{O,V,D}
value::V
derivs::D # ith element = ith-order derivative
function ImmutableDiffResult(value::V, derivs::NTuple{O,Any}) where {O,V}
return new{O,V,typeof(derivs)}(value, derivs)
end
end
mutable struct MutableDiffResult{O,V,D<:Tuple} <: DiffResult{O,V,D}
value::V
derivs::D # ith element = ith-order derivative
function MutableDiffResult(value::V, derivs::NTuple{O,Any}) where {O,V}
return new{O,V,typeof(derivs)}(value, derivs)
end
end
################
# Constructors #
################
"""
DiffResult(value::Union{Number,AbstractArray}, derivs::Tuple{Vararg{Number}})
DiffResult(value::Union{Number,AbstractArray}, derivs::Tuple{Vararg{AbstractArray}})
Return `r::DiffResult`, with output value storage provided by `value` and output derivative
storage provided by `derivs`.
In reality, `DiffResult` is an abstract supertype of two concrete types, `MutableDiffResult`
and `ImmutableDiffResult`. If all `value`/`derivs` are all `Number`s or `StaticArray`s,
then `r` will be immutable (i.e. `r::ImmutableDiffResult`). Otherwise, `r` will be mutable
(i.e. `r::MutableDiffResult`).
Note that `derivs` can be provide in splatted form, i.e. `DiffResult(value, derivs...)`.
"""
DiffResult
DiffResult(value::Number, derivs::Tuple{Vararg{Number}}) = ImmutableDiffResult(value, derivs)
DiffResult(value::Number, derivs::Tuple{Vararg{StaticArray}}) = ImmutableDiffResult(value, derivs)
DiffResult(value::StaticArray, derivs::Tuple{Vararg{StaticArray}}) = ImmutableDiffResult(value, derivs)
DiffResult(value::Number, derivs::Tuple{Vararg{AbstractArray}}) = MutableDiffResult(value, derivs)
DiffResult(value::AbstractArray, derivs::Tuple{Vararg{AbstractArray}}) = MutableDiffResult(value, derivs)
DiffResult(value::Union{Number,AbstractArray}, derivs::Union{Number,AbstractArray}...) = DiffResult(value, derivs)
"""
GradientResult(x::AbstractArray)
Construct a `DiffResult` that can be used for gradient calculations where `x` is the input
to the target function.
Note that `GradientResult` allocates its own storage; `x` is only used for type and
shape information. If you want to allocate storage yourself, use the `DiffResult`
constructor instead.
"""
GradientResult(x::AbstractArray) = DiffResult(first(x), similar(x))
GradientResult(x::StaticArray) = DiffResult(first(x), x)
"""
JacobianResult(x::AbstractArray)
Construct a `DiffResult` that can be used for Jacobian calculations where `x` is the input
to the target function. This method assumes that the target function's output dimension
equals its input dimension.
Note that `JacobianResult` allocates its own storage; `x` is only used for type and
shape information. If you want to allocate storage yourself, use the `DiffResult`
constructor instead.
"""
JacobianResult(x::AbstractArray) = DiffResult(similar(x), similar(x, length(x), length(x)))
JacobianResult(x::StaticArray) = DiffResult(x, zeros(similar_type(typeof(x), Size(length(x),length(x)))))
"""
JacobianResult(y::AbstractArray, x::AbstractArray)
Construct a `DiffResult` that can be used for Jacobian calculations where `x` is the
input to the target function, and `y` is the output (e.g. when taking the Jacobian
of `f!(y, x)`).
Like the single argument version, `y` and `x` are only used for type and
shape information and are not stored in the returned `DiffResult`.
"""
JacobianResult(y::AbstractArray, x::AbstractArray) = DiffResult(similar(y), similar(y, length(y), length(x)))
JacobianResult(y::StaticArray, x::StaticArray) = DiffResult(y, zeros(similar_type(typeof(x), Size(length(y),length(x)))))
"""
HessianResult(x::AbstractArray)
Construct a `DiffResult` that can be used for Hessian calculations where `x` is the
input to the target function.
Note that `HessianResult` allocates its own storage; `x` is only used for type and
shape information. If you want to allocate storage yourself, use the `DiffResult`
constructor instead.
"""
HessianResult(x::AbstractArray) = DiffResult(first(x), zeros(eltype(x), size(x)), similar(x, length(x), length(x)))
HessianResult(x::StaticArray) = DiffResult(first(x), x, zeros(similar_type(typeof(x), Size(length(x),length(x)))))
#############
# Interface #
#############
@generated function tuple_eltype(x::Tuple, ::Type{Val{i}}) where {i}
return quote
$(Expr(:meta, :inline))
return $(x.parameters[i])
end
end
@generated function tuple_setindex(x::NTuple{N,Any}, y, ::Type{Val{i}}) where {N,i}
T = x.parameters[i]
new_tuple = Expr(:tuple, [ifelse(i == n, :(convert($T, y)), :(x[$n])) for n in 1:N]...)
return quote
$(Expr(:meta, :inline))
return $new_tuple
end
end
Base.eltype(r::DiffResult) = eltype(typeof(r))
Base.eltype(::Type{D}) where {O,V,D<:DiffResult{O,V}} = eltype(V)
Base.:(==)(a::DiffResult, b::DiffResult) = a.value == b.value && a.derivs == b.derivs
Base.copy(r::DiffResult) = DiffResult(copy(r.value), map(copy, r.derivs))
# value/value! #
#--------------#
"""
value(r::DiffResult)
Return the primal value stored in `r`.
Note that this method returns a reference, not a copy.
"""
value(r::DiffResult) = r.value
"""
value!(r::DiffResult, x)
Return `s::DiffResult` with the same data as `r`, except for `value(s) == x`.
This function may or may not mutate `r`. If `r::ImmutableDiffResult`, a totally new
instance will be created and returned, whereas if `r::MutableDiffResult`, then `r` will be
mutated in-place and returned. Thus, this function should be called as `r = value!(r, x)`.
"""
value!(r::MutableDiffResult, x::Number) = (r.value = x; return r)
value!(r::MutableDiffResult, x::AbstractArray) = (copyto!(value(r), x); return r)
value!(r::ImmutableDiffResult{O,V}, x::Union{Number,AbstractArray}) where {O,V} = ImmutableDiffResult(convert(V, x), r.derivs)
"""
value!(f, r::DiffResult, x)
Equivalent to `value!(r::DiffResult, map(f, x))`, but without the implied temporary
allocation (when possible).
"""
value!(f, r::MutableDiffResult, x::Number) = (r.value = f(x); return r)
value!(f, r::MutableDiffResult, x::AbstractArray) = (map!(f, value(r), x); return r)
value!(f, r::ImmutableDiffResult{O,V}, x::Number) where {O,V} = value!(r, convert(V, f(x)))
value!(f, r::ImmutableDiffResult{O,V}, x::AbstractArray) where {O,V} = value!(r, convert(V, map(f, x)))
# derivative/derivative! #
#------------------------#
"""
derivative(r::DiffResult, ::Type{Val{i}} = Val{1})
Return the `ith` derivative stored in `r`, defaulting to the first derivative.
Note that this method returns a reference, not a copy.
"""
derivative(r::DiffResult, ::Type{Val{i}} = Val{1}) where {i} = r.derivs[i]
"""
derivative!(r::DiffResult, x, ::Type{Val{i}} = Val{1})
Return `s::DiffResult` with the same data as `r`, except `derivative(s, Val{i}) == x`.
This function may or may not mutate `r`. If `r::ImmutableDiffResult`, a totally new
instance will be created and returned, whereas if `r::MutableDiffResult`, then `r` will be
mutated in-place and returned. Thus, this function should be called as
`r = derivative!(r, x, Val{i})`.
"""
function derivative!(r::MutableDiffResult, x::Number, ::Type{Val{i}} = Val{1}) where {i}
r.derivs = tuple_setindex(r.derivs, x, Val{i})
return r
end
function derivative!(r::MutableDiffResult, x::AbstractArray, ::Type{Val{i}} = Val{1}) where {i}
copyto!(derivative(r, Val{i}), x)
return r
end
function derivative!(r::ImmutableDiffResult, x::Union{Number,StaticArray}, ::Type{Val{i}} = Val{1}) where {i}
return ImmutableDiffResult(value(r), tuple_setindex(r.derivs, x, Val{i}))
end
function derivative!(r::ImmutableDiffResult, x::AbstractArray, ::Type{Val{i}} = Val{1}) where {i}
T = tuple_eltype(r.derivs, Val{i})
return ImmutableDiffResult(value(r), tuple_setindex(r.derivs, T(x), Val{i}))
end
"""
derivative!(f, r::DiffResult, x, ::Type{Val{i}} = Val{1})
Equivalent to `derivative!(r::DiffResult, map(f, x), Val{i})`, but without the implied
temporary allocation (when possible).
"""
function derivative!(f, r::MutableDiffResult, x::Number, ::Type{Val{i}} = Val{1}) where {i}
r.derivs = tuple_setindex(r.derivs, f(x), Val{i})
return r
end
function derivative!(f, r::MutableDiffResult, x::AbstractArray, ::Type{Val{i}} = Val{1}) where {i}
map!(f, derivative(r, Val{i}), x)
return r
end
function derivative!(f, r::ImmutableDiffResult, x::Number, ::Type{Val{i}} = Val{1}) where {i}
return derivative!(r, f(x), Val{i})
end
function derivative!(f, r::ImmutableDiffResult, x::StaticArray, ::Type{Val{i}} = Val{1}) where {i}
return derivative!(r, map(f, x), Val{i})
end
function derivative!(f, r::ImmutableDiffResult, x::AbstractArray, ::Type{Val{i}} = Val{1}) where {i}
T = tuple_eltype(r.derivs, Val{i})
return derivative!(r, map(f, T(x)), Val{i})
end
# special-cased methods #
#-----------------------#
"""
gradient(r::DiffResult)
Return the gradient stored in `r`.
Equivalent to `derivative(r, Val{1})`.
"""
gradient(r::DiffResult) = derivative(r)
"""
gradient!(r::DiffResult, x)
Return `s::DiffResult` with the same data as `r`, except `gradient(s) == x`.
Equivalent to `derivative!(r, x, Val{1})`; see `derivative!` docs for aliasing behavior.
"""
gradient!(r::DiffResult, x) = derivative!(r, x)
"""
gradient!(f, r::DiffResult, x)
Equivalent to `gradient!(r::DiffResult, map(f, x))`, but without the implied temporary
allocation (when possible).
Equivalent to `derivative!(f, r, x, Val{1})`; see `derivative!` docs for aliasing behavior.
"""
gradient!(f, r::DiffResult, x) = derivative!(f, r, x)
"""
jacobian(r::DiffResult)
Return the Jacobian stored in `r`.
Equivalent to `derivative(r, Val{1})`.
"""
jacobian(r::DiffResult) = derivative(r)
"""
jacobian!(r::DiffResult, x)
Return `s::DiffResult` with the same data as `r`, except `jacobian(s) == x`.
Equivalent to `derivative!(r, x, Val{1})`; see `derivative!` docs for aliasing behavior.
"""
jacobian!(r::DiffResult, x) = derivative!(r, x)
"""
jacobian!(f, r::DiffResult, x)
Equivalent to `jacobian!(r::DiffResult, map(f, x))`, but without the implied temporary
allocation (when possible).
Equivalent to `derivative!(f, r, x, Val{1})`; see `derivative!` docs for aliasing behavior.
"""
jacobian!(f, r::DiffResult, x) = derivative!(f, r, x)
"""
hessian(r::DiffResult)
Return the Hessian stored in `r`.
Equivalent to `derivative(r, Val{2})`.
"""
hessian(r::DiffResult) = derivative(r, Val{2})
"""
hessian!(r::DiffResult, x)
Return `s::DiffResult` with the same data as `r`, except `hessian(s) == x`.
Equivalent to `derivative!(r, x, Val{2})`; see `derivative!` docs for aliasing behavior.
"""
hessian!(r::DiffResult, x) = derivative!(r, x, Val{2})
"""
hessian!(f, r::DiffResult, x)
Equivalent to `hessian!(r::DiffResult, map(f, x))`, but without the implied temporary
allocation (when possible).
Equivalent to `derivative!(f, r, x, Val{2})`; see `derivative!` docs for aliasing behavior.
"""
hessian!(f, r::DiffResult, x) = derivative!(f, r, x, Val{2})
###################
# Pretty Printing #
###################
Base.show(io::IO, r::ImmutableDiffResult) = print(io, "ImmutableDiffResult($(r.value), $(r.derivs))")
Base.show(io::IO, r::MutableDiffResult) = print(io, "MutableDiffResult($(r.value), $(r.derivs))")
end # module
| DiffResults | https://github.com/JuliaDiff/DiffResults.jl.git |
|
[
"MIT"
] | 1.1.0 | 782dd5f4561f5d267313f23853baaaa4c52ea621 | code | 9943 | using DiffResults, StaticArrays, Test
using DiffResults: DiffResult, GradientResult, JacobianResult, HessianResult,
value, value!, derivative, derivative!, gradient, gradient!,
jacobian, jacobian!, hessian, hessian!
@testset "DiffResult" begin
k = 4
n0, n1, n2 = rand(), rand(), rand()
x0, x1, x2 = rand(k), rand(k, k), rand(k, k, k)
s0, s1, s2 = SVector{k}(rand(k)), SMatrix{k,k}(rand(k, k)), SArray{Tuple{k,k,k}}(rand(k, k, k))
rn = DiffResult(n0, n1, n2)
rx = DiffResult(x0, x1, x2)
rs = DiffResult(s0, s1, s2)
rsmix = DiffResult(n0, s0, s1)
issimilar(x, y) = typeof(x) == typeof(y) && size(x) == size(y)
issimilar(x::DiffResult, y::DiffResult) = issimilar(value(x), value(y)) && all(issimilar, zip(x.derivs, y.derivs))
issimilar(t::Tuple) = issimilar(t...)
@test rn === DiffResult(n0, n1, n2)
@test rx == DiffResult(x0, x1, x2)
@test rs === DiffResult(s0, s1, s2)
@test rsmix === DiffResult(n0, s0, s1)
@test issimilar(GradientResult(x0), DiffResult(first(x0), x0))
@test issimilar(JacobianResult(x0), DiffResult(x0, similar(x0, k, k)))
@test issimilar(JacobianResult(similar(x0, k + 1), x0), DiffResult(similar(x0, k + 1), similar(x0, k + 1, k)))
@test issimilar(HessianResult(x0), DiffResult(first(x0), x0, similar(x0, k, k)))
@test GradientResult(s0) === DiffResult(first(s0), s0)
@test JacobianResult(s0) === DiffResult(s0, zeros(SMatrix{k,k,Float64}))
@test JacobianResult(SVector{k+1}(vcat(s0, 0.0)), s0) === DiffResult(SVector{k+1}(vcat(s0, 0.0)), zeros(SMatrix{k+1,k,Float64}))
@test HessianResult(s0) === DiffResult(first(s0), s0, zeros(SMatrix{k,k,Float64}))
@test eltype(rn) === typeof(n0)
@test eltype(rx) === eltype(x0)
@test eltype(rs) === eltype(s0)
rn_copy = copy(rn)
@test rn == rn_copy
@test rn === rn_copy
rx_copy = copy(rx)
@test rx == rx_copy
@test rx !== rx_copy
rs_copy = copy(rs)
@test rs == rs_copy
@test rs === rs_copy
rsmix_copy = copy(rsmix)
@test rsmix == rsmix_copy
@test rsmix === rsmix_copy
@testset "value/value!" begin
@test value(rn) === n0
@test value(rx) === x0
@test value(rs) === s0
@test value(rsmix) === n0
rn = value!(rn, n1)
@test value(rn) === n1
rn = value!(rn, n0)
x0_new, x0_copy = rand(k), copy(x0)
rx = value!(rx, x0_new)
@test value(rx) === x0 == x0_new
rx = value!(rx, x0_copy)
s0_new = rand(k)
rs = value!(rs, s0_new)
@test value(rs) == s0_new
@test typeof(value(rs)) === typeof(s0)
rs = value!(rs, s0)
rsmix = value!(rsmix, n1)
@test value(rsmix) === n1
rsmix = value!(rsmix, n0)
rn = value!(exp, rn, n1)
@test value(rn) === exp(n1)
rn = value!(rn, n0)
x0_new, x0_copy = rand(k), copy(x0)
rx = value!(exp, rx, x0_new)
@test value(rx) === x0 == exp.(x0_new)
rx = value!(rx, x0_copy)
s0_new = rand(k)
rs = value!(exp, rs, s0_new)
@test value(rs) == exp.(s0_new)
@test typeof(value(rs)) === typeof(s0)
rs = value!(rs, s0)
rsmix = value!(exp, rsmix, n1)
@test value(rsmix) === exp(n1)
rsmix = value!(rsmix, n0)
ksqrt = Int(sqrt(k))
T = typeof(SMatrix{ksqrt,ksqrt}(rand(ksqrt,ksqrt)))
rs_new = value!(rs, convert(T, value(rs)))
@test rs_new === rs
end
@testset "derivative/derivative!" begin
@test derivative(rn) === n1
@test derivative(rn, Val{2}) === n2
@test derivative(rx) === x1
@test derivative(rx, Val{2}) === x2
@test derivative(rs) === s1
@test derivative(rs, Val{2}) === s2
@test derivative(rsmix) === s0
@test derivative(rsmix, Val{2}) === s1
rn = derivative!(rn, n0)
@test derivative(rn) === n0
rn = derivative!(rn, n1)
x1_new, x1_copy = rand(k, k), copy(x1)
rx = derivative!(rx, x1_new)
@test derivative(rx) === x1 == x1_new
rx = derivative!(rx, x1_copy)
s1_new = rand(k, k)
rs = derivative!(rs, s1_new)
@test derivative(rs) == s1_new
@test typeof(derivative(rs)) === typeof(s1)
rs = derivative!(rs, s1)
s0_new = rand(k)
rsmix = derivative!(rsmix, s0_new)
@test derivative(rsmix) == s0_new
@test typeof(derivative(rsmix)) === typeof(s0)
rsmix = derivative!(rsmix, s0)
rn = derivative!(rn, n1, Val{2})
@test derivative(rn, Val{2}) === n1
rn = derivative!(rn, n2, Val{2})
x2_new, x2_copy = rand(k, k, k), copy(x2)
rx = derivative!(rx, x2_new, Val{2})
@test derivative(rx, Val{2}) === x2 == x2_new
rx = derivative!(rx, x2_copy, Val{2})
s2_new = rand(k, k, k)
rs = derivative!(rs, s2_new, Val{2})
@test derivative(rs, Val{2}) == s2_new
@test typeof(derivative(rs, Val{2})) === typeof(s2)
rs = derivative!(rs, s2, Val{2})
s1_new = rand(k, k)
rsmix = derivative!(rsmix, s1_new, Val{2})
@test derivative(rsmix, Val{2}) == s1_new
@test typeof(derivative(rsmix, Val{2})) === typeof(s1)
rsmix = derivative!(rsmix, s1, Val{2})
rn = derivative!(exp, rn, n0)
@test derivative(rn) === exp(n0)
rn = derivative!(rn, n1)
x1_new, x1_copy = rand(k, k), copy(x1)
rx = derivative!(exp, rx, x1_new)
@test derivative(rx) === x1 == exp.(x1_new)
rx = derivative!(exp, rx, x1_copy)
s1_new = rand(k, k)
rs = derivative!(exp, rs, s1_new)
@test derivative(rs) == exp.(s1_new)
@test typeof(derivative(rs)) === typeof(s1)
rs = derivative!(exp, rs, s1)
s0_new = rand(k)
rsmix = derivative!(exp, rsmix, s0_new)
@test derivative(rsmix) == exp.(s0_new)
@test typeof(derivative(rsmix)) === typeof(s0)
rsmix = derivative!(exp, rsmix, s0)
rn = derivative!(exp, rn, n1, Val{2})
@test derivative(rn, Val{2}) === exp(n1)
rn = derivative!(rn, n2, Val{2})
x2_new, x2_copy = rand(k, k, k), copy(x2)
rx = derivative!(exp, rx, x2_new, Val{2})
@test derivative(rx, Val{2}) === x2 == exp.(x2_new)
rx = derivative!(exp, rx, x2_copy, Val{2})
s2_new = rand(k, k, k)
rs = derivative!(exp, rs, s2_new, Val{2})
@test derivative(rs, Val{2}) == exp.(s2_new)
@test typeof(derivative(rs, Val{2})) === typeof(s2)
rs = derivative!(exp, rs, s2, Val{2})
s1_new = rand(k, k)
rsmix = derivative!(exp, rsmix, s1_new, Val{2})
@test derivative(rsmix, Val{2}) == exp.(s1_new)
@test typeof(derivative(rsmix, Val{2})) === typeof(s1)
rsmix = derivative!(exp, rsmix, s1, Val{2})
end
@testset "gradient/gradient!" begin
x1_new, x1_copy = rand(k, k), copy(x1)
rx = gradient!(rx, x1_new)
@test gradient(rx) === x1 == x1_new
rx = gradient!(rx, x1_copy)
s1_new = rand(k, k)
rs = gradient!(rs, s1_new)
@test gradient(rs) == s1_new
@test typeof(gradient(rs)) === typeof(s1)
rs = gradient!(rs, s1)
x1_new, x1_copy = rand(k, k), copy(x1)
rx = gradient!(exp, rx, x1_new)
@test gradient(rx) === x1 == exp.(x1_new)
rx = gradient!(exp, rx, x1_copy)
s0_new = rand(k)
rsmix = gradient!(exp, rsmix, s0_new)
@test gradient(rsmix) == exp.(s0_new)
@test typeof(gradient(rsmix)) === typeof(s0)
rsmix = gradient!(exp, rsmix, s0)
T = typeof(SVector{k*k}(rand(k*k)))
rs_new = gradient!(rs, convert(T, gradient(rs)))
@test rs_new === rs
end
@testset "jacobian/jacobian!" begin
x1_new, x1_copy = rand(k, k), copy(x1)
rx = jacobian!(rx, x1_new)
@test jacobian(rx) === x1 == x1_new
rx = jacobian!(rx, x1_copy)
s1_new = rand(k, k)
rs = jacobian!(rs, s1_new)
@test jacobian(rs) == s1_new
@test typeof(jacobian(rs)) === typeof(s1)
rs = jacobian!(rs, s1)
x1_new, x1_copy = rand(k, k), copy(x1)
rx = jacobian!(exp, rx, x1_new)
@test jacobian(rx) === x1 == exp.(x1_new)
rx = jacobian!(exp, rx, x1_copy)
s0_new = rand(k)
rsmix = jacobian!(exp, rsmix, s0_new)
@test jacobian(rsmix) == exp.(s0_new)
@test typeof(jacobian(rsmix)) === typeof(s0)
rsmix = jacobian!(exp, rsmix, s0)
T = typeof(SVector{k*k}(rand(k*k)))
rs_new = jacobian!(rs, convert(T, jacobian(rs)))
@test rs_new === rs
end
@testset "hessian/hessian!" begin
x2_new, x2_copy = rand(k, k, k), copy(x2)
rx = hessian!(rx, x2_new)
@test hessian(rx) === x2 == x2_new
rx = hessian!(rx, x2_copy)
s2_new = rand(k, k, k)
rs = hessian!(rs, s2_new)
@test hessian(rs) == s2_new
@test typeof(hessian(rs)) === typeof(s2)
rs = hessian!(rs, s2)
x2_new, x2_copy = rand(k, k, k), copy(x2)
rx = hessian!(exp, rx, x2_new)
@test hessian(rx) === x2 == exp.(x2_new)
rx = hessian!(exp, rx, x2_copy)
s1_new = rand(k, k)
rsmix = hessian!(exp, rsmix, s1_new)
@test hessian(rsmix) == exp.(s1_new)
@test typeof(hessian(rsmix)) === typeof(s1)
rsmix = hessian!(exp, rsmix, s1)
T = typeof(SVector{k*k*k}(rand(k*k*k)))
rs_new = hessian!(rs, convert(T, hessian(rs)))
@test rs_new === rs
@test size(gradient(HessianResult(x0))) == size(x0)
@test size(gradient(HessianResult(x1))) == size(x1)
@test size(gradient(HessianResult(x2))) == size(x2)
@test HessianResult(Float32.(x0)).derivs[1] isa Vector{Float32}
end
end
| DiffResults | https://github.com/JuliaDiff/DiffResults.jl.git |
|
[
"MIT"
] | 1.1.0 | 782dd5f4561f5d267313f23853baaaa4c52ea621 | docs | 947 | # DiffResults

[](https://coveralls.io/github/JuliaDiff/DiffResults.jl?branch=master)
[](http://www.juliadiff.org/DiffResults.jl/stable)
[](http://www.juliadiff.org/DiffResults.jl/latest)
Many differentiation techniques can calculate primal values and multiple orders of
derivatives simultaneously. In other words, there are techniques for computing `f(x)`,
`∇f(x)` and `H(f(x))` in one fell swoop!
For this purpose, DiffResults provides the `DiffResult` type, which can be passed
to in-place differentiation methods instead of an output buffer. The method
then loads all computed results into the given `DiffResult`, which the user
can then query afterwards.
| DiffResults | https://github.com/JuliaDiff/DiffResults.jl.git |
|
[
"MIT"
] | 1.1.0 | 782dd5f4561f5d267313f23853baaaa4c52ea621 | docs | 2050 | # DiffResults
```@meta
CurrentModule = DiffResults
```
Many differentiation techniques can calculate primal values and multiple orders of
derivatives simultaneously. In other words, there are techniques for computing `f(x)`,
`∇f(x)` and `H(f(x))` in one fell swoop!
For this purpose, DiffResults provides the `DiffResult` type, which can be passed
to in-place differentiation methods instead of an output buffer. The method
then loads all computed results into the given `DiffResult`, which the user
can then query afterwards.
Here's an example of `DiffResult` in action using ForwardDiff:
```julia
julia> using ForwardDiff, DiffResults
julia> f(x) = sum(sin, x) + prod(tan, x) * sum(sqrt, x);
julia> x = rand(4);
# construct a `DiffResult` with storage for a Hessian, gradient,
# and primal value based on the type and shape of `x`.
julia> result = DiffResults.HessianResult(x)
# Instead of passing an output buffer to `hessian!`, we pass `result`.
# Note that we re-alias to `result` - this is important! See `hessian!`
# docs for why we do this.
julia> result = ForwardDiff.hessian!(result, f, x);
# ...and now we can get all the computed data from `result`
julia> DiffResults.value(result) == f(x)
true
julia> DiffResults.gradient(result) == ForwardDiff.gradient(f, x)
true
julia> DiffResults.hessian(result) == ForwardDiff.hessian(f, x)
true
```
The rest of this document describes the API for constructing, accessing, and mutating
`DiffResult` instances. For details on how to use a `DiffResult` with a specific
package's methods, please consult that package's documentation.
## Constructing a `DiffResult`
```@docs
DiffResults.DiffResult
DiffResults.JacobianResult
DiffResults.GradientResult
DiffResults.HessianResult
```
## Accessing data from a `DiffResult`
```@docs
DiffResults.value
DiffResults.derivative
DiffResults.gradient
DiffResults.jacobian
DiffResults.hessian
```
## Mutating a `DiffResult`
```@docs
DiffResults.value!
DiffResults.derivative!
DiffResults.gradient!
DiffResults.jacobian!
DiffResults.hessian!
```
| DiffResults | https://github.com/JuliaDiff/DiffResults.jl.git |
|
[
"MIT"
] | 0.1.0 | a3b188db2a3a3db251b76bb192240af70eb07344 | code | 971 | using Documenter, SIMDscan, DocumenterCitations
DocMeta.setdocmeta!(SIMDscan, :DocTestSetup, :(using SIMDscan); recursive=true)
bib = CitationBibliography(joinpath(@__DIR__,"simd.bib"), style=:authoryear)
makedocs(;
modules=[SIMDscan],
authors="Paul Schrimpf <[email protected]> and contributors",
repo=Remotes.GitHub("schrimpf","SIMDscan.jl"),
sitename="SIMDscan.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
edit_link="main",
assets=String[],
),
pages=[
"Home" => "index.md",
"Benchmarks" => "benchmarks.md",
"API" => "functions.md",
"References" => "references.md"
],
plugins=[bib]
)
deploydocs(;
repo="github.com/schrimpf/SIMDscan.jl",
devbranch="main"
)
| SIMDscan | https://github.com/schrimpf/SIMDscan.jl.git |
|
[
"MIT"
] | 0.1.0 | a3b188db2a3a3db251b76bb192240af70eb07344 | code | 87 | module SIMDscan
using SIMD
export scan_serial!, scan_simd!
include("scan.jl")
end
| SIMDscan | https://github.com/schrimpf/SIMDscan.jl.git |
|
[
"MIT"
] | 0.1.0 | a3b188db2a3a3db251b76bb192240af70eb07344 | code | 4933 | @doc raw"""
scan_serial!(f::F,x::AbstractVector) where {F <: Function}
Replaces the vector `x` with the scan of `x` using `f`. That is,
```
x[1]
f(x[2],x[1])
f(x[3],f(x[2],x[1]))
⋮
```
# Examples
```jl-doctest
julia> scan_serial!(+,[1,2,3,4])
4-element Vector{Int64}:
1
3
6
10
```
"""
function scan_serial!(f::F,x::AbstractVector) where {F <: Function}
for i=2:length(x)
x[i] = f(x[i],x[i-1])
end
return(x)
end
@doc raw"""
scan_serial!(f::F,x::NTuple{K, AbstractVector{T}}) where {F <: Function, K, T}
In place scan for a function that takes two `K` tuples as arguments.
Replaces the tuple of vectors `x` with the scan.
# Examples
```jl-doctest
julia> scan_serial!((x,y)->(x[1]+y[1], x[2]*y[2]),([1,2,3,4],[1,2,3,4]))
([1, 3, 6, 10], [1, 2, 6, 24])
```
"""
function scan_serial!(f::F,x::NTuple{K, AbstractVector{T}}) where {F <: Function, K, T}
@assert length(unique(length.(x)))==1
for i=2:length(x[1])
setindex!.(x, f(getindex.(x,i-1),getindex.(x,i)), i)
end
return(x)
end
m_to_n(::Val{N},::Val{N}) where N = (N,)
function m_to_n(::Val{M},::Val{N}) where {M, N}
@assert M < N
(m_to_n(Val(M),Val(N-1))..., N)
end
function shiftleftmask(::Val{N}, ::Val{S}) where {N,S}
@assert S>0
Val((m_to_n(Val(N),Val(N+S-1))...,m_to_n(Val(0),Val(N-S-1))...))
end
@generated function scan_vec(f::F, x::NTuple{K, Vec{N,T}},identity::NTuple{K, Vec{N,T}}) where {F, K, N, T}
@assert N & (N-1) == 0 # check that N is a power of 2
ex= :(
shx=shufflevector.(x,identity, shiftleftmask(Val(N),Val(1)));
x=f(shx,x);
)
for j=1:(ceil(Int,log2(N))-1)
ex= :($(ex);
shx=shufflevector.(x,identity, shiftleftmask(Val(N),Val($(2^j))));
x = f(shx,x);
)
end
return(ex)
end
@generated function scan_vec(f::F, x::Vec{N,T},identity::Vec{N,T}) where {F, N, T}
@assert N & (N-1) == 0 # check that N is a power of 2
ex= :(x = f(shufflevector(x,identity, shiftleftmask(Val(N),Val(1))),x))
for j=1:(ceil(Int,log2(N))-1)
ex = :($(ex); x = f(shufflevector(x,identity, shiftleftmask(Val(N),Val($(2^j)))),x))
end
return(ex)
end
@doc raw"""
scan_simd!(f::F, x::NTuple{K, AbstractVector{T}}, v::Val{N}=Val(8); identity::NTuple{K,T}=ntuple(i->zero(T),Val(K))) where {F, K, T, N}
In place scan for an associative function that takes two `K` tuples as arguments.
Replaces the tuple of vectors `x` with the scan.
`identity` should be a left identity under `f`. That is, `f(identity, y) = y` for all `y`.
`T`, must be a type that can be loaded onto registers, i.e. one of `SIMD.VecTypes`.
`f` must be associative. Otherwise, this will give incorrect results.
`Val(N)` specifies the SIMD vector width used. The default of `8` should give good performance on CPUs with AVX512 for which 8 Float64s fill the 512 bits available.
# Examples
```jl-doctest
julia> scan_simd!((x,y)->(x[1]+y[1], x[2]*y[2]),([1,2,3,4],[1,2,3,4]))
([1, 3, 6, 10], [1, 2, 6, 24])
```
"""
function scan_simd!(f::F, x::NTuple{K, AbstractVector{T}}, v::Val{N}=Val(8);
identity::NTuple{K,T}=ntuple(i->zero(T),Val(K))) where {F, K, T, N}
remainder = length(x[1]) % N
s = Vec{N,T}.(identity)
@inbounds for i=1:N:(length(x[1]) - remainder)
xvec=vload.(Vec{N,T},x,i)
xvec = scan_vec(f,xvec,s)
vstore.(xvec,x,i)
end
@inbounds for i=1:N:(length(x[1])-remainder)
lastx = Vec{N,T}.(getindex.(x,i+N-1))
xvec=vload.(Vec{N,T},x,i)
xvec=f(s,xvec)
vstore.(xvec,x,i)
s = f(s,lastx)
end
@inbounds for i=max(length(x[1])-remainder+1,2):length(x[1])
setindex!.(x,f(getindex.(x,i-1),getindex.(x,i)),i)
end
return(x)
end
@doc raw"""
scan_simd!(f::F, x::AbstractVector{T}, v::Val{N}=Val(8);identity::T=zero(T)) where {F, T, N}
In place scan for an associative function.
`identity` should be a left identity under `f`. That is, `f(identity, y) = y` for all `y`.
`T`, must be a type that can be loaded onto registers, i.e. one of `SIMD.VecTypes`.
`f` must be associative. Otherwise, this will give incorrect results.
`Val(N)` specifies the SIMD vector width used. The default of `8` should give good performance on CPUs with AVX512 for which 8 Float64s fill the 512 bits available.
# Examples
```jl-doctest
julia> scan_simd!(+,[1,2,3,4])
4-element Vector{Int64}:
1
3
6
10
```
"""
function scan_simd!(f::F, x::AbstractVector{T}, v::Val{N}=Val(8);
identity::T=zero(T)) where {F, T, N}
remainder = length(x) % N
s = Vec{N,T}(identity)
@inbounds for i=1:N:(length(x) - remainder)
xvec=vload(Vec{N,T},x,i)
xvec = scan_vec(f,xvec,s)
vstore(xvec,x,i)
end
@inbounds for i=1:N:(length(x)-remainder)
lastx = Vec{N,T}(getindex(x,i+N-1))
xvec=vload(Vec{N,T},x,i)
xvec=f(s,xvec)
vstore(xvec,x,i)
s = f(lastx,s)
end
@inbounds for i=max(length(x)-remainder+1,2):length(x)
setindex!(x,f(getindex(x,i-1),getindex(x,i)),i)
end
return(x)
end
| SIMDscan | https://github.com/schrimpf/SIMDscan.jl.git |
|
[
"MIT"
] | 0.1.0 | a3b188db2a3a3db251b76bb192240af70eb07344 | code | 1282 | using SIMDscan
using Test, TestItemRunner
@testitem "vector scans" begin
for N ∈ [2, 47, 1000, 1001]
for x ∈ [rand(N), rand(Float32,N), rand(Bool, N), rand(1:N,N)]
for (op, opidentity) ∈ zip([+, *], [0.0, 1.0])
scanxserial = copy(x)
scan_serial!(op,scanxserial)
scanxsimd = copy(x)
scan_simd!(op,scanxsimd, identity=opidentity)
@test isapprox(scanxserial, scanxsimd, rtol=sqrt(eps()))
@test isapprox(accumulate(op, x), scanxserial, rtol=sqrt(eps()))
end
end
end
end
@testitem "autoregressive" begin
T = 250
ϵ = randn(T)
y = similar(ϵ)
y[1] = ϵ[1]
α = 0.9
for t = 2:T
y[t] = α*y[t-1] + ϵ[t]
end
ar(y,e) = (e[1] + α*y[1]*e[2], α*y[2]*e[2])
e=collect(zip(ϵ, rand(T)))
@test all(ar(ar(ar(e[1],e[2]),e[3]),e[4]) .≈ ar(ar(e[1],ar(e[2],e[3])),e[4]) )
@test all(ar(ar(e[1],e[2]),ar(e[3],e[4])) .≈ ar(ar(ar(e[1],e[2]),e[3]),e[4]) )
yacc = [x[1] for x in accumulate(ar,zip(ϵ, Iterators.Repeated(1.0)))]
@test isapprox(y, yacc, rtol=sqrt(eps()))
yscanserial,as = scan_serial!(ar, (copy(ϵ), ones(T)))
@test yscanserial ≈ y
yscansimd,at = scan_simd!(ar, (copy(ϵ), ones(T)), identity=(0.0,1.0/α))
@test yscansimd ≈ y
end
@run_package_tests | SIMDscan | https://github.com/schrimpf/SIMDscan.jl.git |
|
[
"MIT"
] | 0.1.0 | a3b188db2a3a3db251b76bb192240af70eb07344 | docs | 1627 | # SIMDscan
A fast scan using SIMD instructions.
<!-- [](https://schrimpf.github.io/SIMDscan.jl/stable/) -->
[](https://schrimpf.github.io/SIMDscan.jl/dev/)
[](https://github.com/schrimpf/SIMDscan.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/schrimpf/SIMDscan.jl)
A scan or prefix operation is a generalization of a cumulative sum.
Given a sequence $x_1, x_2, ... , x_n$, and an associative operator, $\oplus$, the the scan is
```math
x_1, x_1 \oplus x_2, x_3 \oplus x_2 \oplus x_1, ... , x_n \oplus x_{n-1} \oplus \cdots \oplus x_1
```
The scan can be parallelized when $\oplus$ is associative. This package provides an in-place scan implementation using SIMD, `scan_simd!(⊕, x)`.
For testing and performance comparison, there is also a serial implementation, `scan_serial!(⊕, x)`.
## Usage
[See the docs](https://schrimpf.github.io/SIMDscan.jl/dev/)
## Benchmarks
[See the benchmarks section of the docs](https://schrimpf.github.io/SIMDscan.jl/dev/benchmarks/). With 512 bit SIMD vectors, `scan_simd!` appears to be about 4 time faster. With 256 bit SIMD vectors, the gain is smaller, but still notable. The benchmarks run on github actions, so the resuls and CPU will vary from commit to commit. Of course, the performance will also depend on problem size and the $\oplus$ operator.
| SIMDscan | https://github.com/schrimpf/SIMDscan.jl.git |
|
[
"MIT"
] | 0.1.0 | a3b188db2a3a3db251b76bb192240af70eb07344 | docs | 700 | # Benchmarks
## Cumulative Sum
```@example bench
using BenchmarkTools, CpuId, SIMDscan
N = 10_000
x = rand(N);
nothing
```
```@repl bench
cpuinfo()
@benchmark cumsum!($(copy(x)),$x)
@benchmark scan_serial!(+,$(copy(x)))
@benchmark scan_simd!(+,$(copy(x)), Val(16))
```
## AR(1)
```@example bench
T = 2500
ϵ = randn(T)
y = similar(ϵ)
α = 0.9
function ar1recursize!(y, ϵ, α)
y[1] = ϵ[1]
for t = 2:T
y[t] = α*y[t-1] + ϵ[t]
end
y
end
ar(y,e) = (e[1] + α*y[1]*e[2], α*y[2]*e[2]);
nothing
```
```@repl bench
@benchmark ar1recursize!($y,$ϵ,$α)
@benchmark scan_serial!($ar, $((copy(ϵ), ones(T))))
@benchmark scan_simd!($ar, $((copy(ϵ), ones(T))), identity=$((0.0,1.0/α)))
```
| SIMDscan | https://github.com/schrimpf/SIMDscan.jl.git |
|
[
"MIT"
] | 0.1.0 | a3b188db2a3a3db251b76bb192240af70eb07344 | docs | 67 | ```@index
```
## Functions
```@autodocs
Modules = [SIMDscan]
```
| SIMDscan | https://github.com/schrimpf/SIMDscan.jl.git |
|
[
"MIT"
] | 0.1.0 | a3b188db2a3a3db251b76bb192240af70eb07344 | docs | 1809 | ```@meta
CurrentModule = SIMDscan
```
# SIMDscan
Documentation for [SIMDscan](https://github.com/schrimpf/SIMDscan.jl).
This package provides code for doing a scan using SIMD instructions. Scans are also known as prefix operations.
The Base Julia function `accumulate` performs the same operation.
Given a sequence $x_1, x_2, ... , x_n$, and an associative operator, $\oplus$, the the scan is
```math
x_1, x_1 \oplus x_2, x_3 \oplus x_2 \oplus x_1, ... , x_n \oplus x_{n-1} \oplus \cdots \oplus x_1
```
For parallelization, it is essential that $\oplus$ be associative. The function `scan_simd!(⊕, x)`
computes the scan of `x` in place.
## Warnings
- `x` must be indexed from `1` to `length(x)`.
- `⊕` must be associative for `scan_simd!`
## Multivariate Operations
There is also a method for scanning `⊕: ℝᴷ→ℝᴷ`. In this case, `⊕` should accept two `NTuple{K,T}` tuples as arguments and return a `NTuple{K,T}`.
`x` should be a `NTuple{K,AbstractVector}` where each element of the tuple is the sequence of values.
The multivariate scan can be used to simulate an AR(1) model.
```@example
using SIMDscan # hide
T = 10
ϵ = randn(T)
# simple recursive version for comparison
y = similar(ϵ)
y[1] = ϵ[1]
α = 0.5
for t = 2:T
y[t] = α*y[t-1] + ϵ[t]
end
# to make ⊕ associative, augment ϵ[t] with a second element that keeps track of the appropriate power of α
⊕(y,e) = (e[1] + α*y[1]*e[2], α*y[2]*e[2])
id = (0.0,1.0/α) # a left identity; ⊕(id,x) = x ∀ x
yscansimd,at = scan_simd!(⊕, (copy(ϵ), ones(T)), identity=id)
[y yscansimd]
```
## Acknowledgements
The following sources were helpful while developing this package:
- [slotin2022](@cite) describes an SIMD implementation for prefix sum with C code
- [nash2021](@cite) has example code for a threaded scan (prefix sum) in Julia,
| SIMDscan | https://github.com/schrimpf/SIMDscan.jl.git |
|
[
"MIT"
] | 0.1.0 | a3b188db2a3a3db251b76bb192240af70eb07344 | docs | 34 | # References
```@bibliography
``` | SIMDscan | https://github.com/schrimpf/SIMDscan.jl.git |
|
[
"MIT"
] | 0.1.3 | 1e4928fb66735bb9fbc74a74e394d9bbd49f474d | code | 6612 | module LaTeXTabulars
using ArgCheck: @argcheck
using DocStringExtensions: SIGNATURES
using UnPack: @unpack
export Rule, CMidRule, MultiColumn, MultiRow, Tabular, LongTable, latex_tabular
# cells
"""
$(SIGNATURES)
Print a the contents of `cell` to `io` as LaTeX.
!!! NOTE
Methods are defined for some specific types, but if you want full control
(eg rounding), use an `<: AbstractString`, eg `String` or `LaTeXString`.
"""
function latex_cell(io::IO, cell::T) where T
@info "Define a `latex_cell` for writing $T objects to LaTeX."
throw(MethodError(latex_cell, Tuple{IO, T}))
end
latex_cell(io::IO, x::Real) = print(io, string(x))
latex_cell(io::IO, s::AbstractString) = print(io, s)
"""
MultiColumn(n, pos, cell)
For `\\multicolumn{n}{pos}{cell}`. Use the symbols `:l`, `:c`, `:r` for `pos`.
"""
struct MultiColumn
n::Int
pos::Symbol
cell
end
function latex_cell(io::IO, mc::MultiColumn)
@unpack n, pos, cell = mc
@argcheck(pos ∈ (:l, :c, :r),
"$pos is not a recognized position. Use :l, :c, :r.")
print(io, "\\multicolumn{$(n)}{$(pos)}{")
latex_cell(io, mc.cell)
print(io, "}")
end
"""
MultiRow(n::Int, vpos::Symbol, cell::Any, width::String)
MultiRow(n, vpos, cell; width="*")
For `\\multirow[vpos]{n}{width}{cell}`. Use the symbols `:t`, `:c`, `:b` for `vpos`.
"""
struct MultiRow
n::Int
vpos::Symbol
cell::Any
width::String
end
MultiRow(n, vpos, cell; width="*") = MultiRow(n, vpos, cell, width)
function latex_cell(io::IO, mr::MultiRow)
@unpack vpos, n, width = mr
@argcheck(vpos ∈ (:t, :c, :b),
"$vpos is not a recognized position. Use :t, :c, :b.")
print(io, "\\multirow[$vpos]{$(n)}{$width}{")
latex_cell(io, mr.cell)
print(io, "}")
end
# non-cell-like objects
struct Rule{T} end
"""
$SIGNATURES
Horizontal rule. The `kind` of the rule is specified by a symbol, which will
generally be printed as `\\KINDrule` for rules in `booktabs`, eg `Rule(:top)`
prints `\\toprule`. To obtain a `\\hline`, use `Rule{:h}`.
"""
Rule(kind::Symbol = :h) = Rule{kind}()
latex_line(io::IO, ::Rule{:top}) = println(io, "\\toprule ")
latex_line(io::IO, ::Rule{:mid}) = println(io, "\\midrule ")
latex_line(io::IO, ::Rule{:bottom}) = println(io, "\\bottomrule ")
latex_line(io::IO, ::Rule{:h}) = println(io, "\\hline ")
latex_line(io::IO, r::Rule) = error("Don't know how to print $(typeof(r)).")
"""
CMidRule([wd], [trim], left, right)
Will be printed as `\\cmidrule[wd](trim)[left-right]`. When `wd` or `trim` is
`nothing`, it is omitted. Use with the `booktabs` LaTeX package.
"""
struct CMidRule
wd::Union{Nothing, AbstractString}
trim::Union{Nothing, AbstractString}
left::Int
right::Int
function CMidRule(wd, trim, left, right)
@argcheck 1 ≤ left ≤ right
new(wd, trim, left, right)
end
end
CMidRule(trim, left, right) = CMidRule(nothing, trim, left, right)
CMidRule(left, right) = CMidRule(nothing, left, right)
function latex_line(io::IO, rule::CMidRule)
@unpack wd, trim, left, right = rule
print(io, "\\cmidrule")
wd ≠ nothing && print(io, "[$(wd)]")
trim ≠ nothing && print(io, "($(trim))")
print(io, "{$(left)-$(right)} ") # NOTE trailing space important
end
function latex_line(io::IO, cells)
for (column, cell) in enumerate(cells)
column == 1 || print(io, " & ")
latex_cell(io, cell)
end
println(io, " \\\\")
end
function latex_line(io::IO, M::AbstractMatrix)
for i in axes(M, 1)
latex_line(io, M[i, :])
end
end
function latex_line(io::IO, lines::Tuple)
for line in lines
latex_line(io, line)
end
end
# tabular and similar environments
abstract type TabularLike end
"""
Tabular(cols)
For the LaTeX environment `\\begin{tabular}{cols} ... \\end{tabular}`.
"""
struct Tabular <: TabularLike
"A column specification, eg `\"llrr\"`."
cols::AbstractString
end
latex_env_begin(io::IO, t::Tabular) = println(io, "\\begin{tabular}{$(t.cols)}")
latex_env_end(io::IO, t::Tabular) = println(io, "\\end{tabular}")
"""
$(SIGNATURES)
Print `lines` to `io` as a LaTeX using the given environment.
Each `line` in `lines` can be
- a rule-like object, eg [`Rule`] or [`CMidRule`],
- an iterable (eg `AbstractVector`) of cells,
- a `Tuple`, which is treated as multiple lines (“splat” in place), which is
useful for functions that generate lines with associated rules, or multiple
`CMidRule`s,
- a matrix, each row of which is treated as a line.
See [`latex_cell`](@ref) for the kinds of cell supported (particularly
[`MultiColumn`](@ref), but for full formatting control, use an `String` or
`LaTeXString` for cells.
"""
function latex_tabular(io::IO, t::TabularLike, lines)
latex_env_begin(io, t)
for line in lines
latex_line(io, line)
end
latex_env_end(io, t)
end
latex_tabular(io::IO, t::TabularLike, lines::AbstractMatrix) =
latex_tabular(io, t, [lines])
"""
$(SIGNATURES)
LaTeX output as a string. See other method for the other arguments.
"""
function latex_tabular(::Type{String}, t::TabularLike, lines)
io = IOBuffer()
latex_tabular(io, t, lines)
String(take!(io))
end
"""
$(SIGNATURES)
Write a `tabular`-like LaTeX environment to `filename`, which is **overwritten**
if it already exists.
"""
function latex_tabular(filename::AbstractString, t::TabularLike, lines)
open(filename, "w") do io
latex_tabular(io, t, lines)
end
end
struct LongTable <: TabularLike
"A column specification, eg `\"llrr\"`."
cols::AbstractString
"""
The table header, to be repeated at the top of each page, supplied an iterable of cells,
eg `[\"alpha\", \"beta\", \"gamma\"]`.
"""
header
end
function latex_env_begin(io::IO, t::LongTable)
println(io, "\\begin{longtable}[c]{$(t.cols)}")
latex_line(io, Rule(:h))
latex_line(io, t.header)
latex_line(io, Rule(:h))
println(io, "\\endfirsthead")
println(io, "\\multicolumn{$(length(t.cols))}{l}")
println(io, "{{\\bfseries \\tablename\\ \\thetable{} --- continued from previous page}} \\\\")
latex_line(io, Rule(:h))
latex_line(io, t.header)
latex_line(io, Rule(:h))
println(io, "\\endhead")
latex_line(io, Rule(:h))
println(io, "\\multicolumn{$(length(t.cols))}{r}{{\\bfseries Continued on next page}} \\\\")
latex_line(io, Rule(:h))
println(io, "\\endfoot")
latex_line(io, Rule(:h))
println(io, "\\endlastfoot")
end
latex_env_end(io::IO, t::LongTable) = println(io, "\\end{longtable}")
end # module
| LaTeXTabulars | https://github.com/tpapp/LaTeXTabulars.jl.git |
|
[
"MIT"
] | 0.1.3 | 1e4928fb66735bb9fbc74a74e394d9bbd49f474d | code | 3144 | using LaTeXTabulars, Test, LaTeXStrings
# for testing
using LaTeXTabulars: latex_cell
"Normalize whitespace, for more convenient testing."
squash_whitespace(string) = strip(replace(string, r"[ \n\t]+" => " "))
@test squash_whitespace(" something \n with line breaks \n and stuff \n") ==
"something with line breaks and stuff"
"Comparison using normalized whitespace. For testing."
≅(a, b) = squash_whitespace(a) == squash_whitespace(b)
@testset "tabular" begin
tb = Tabular("lcl")
tlines = [Rule(:top),
[L"\alpha", L"\beta", "sum"],
Rule(:mid),
[1, 2, 3],
Rule(), # a nice \hline to make it ugly
[4.0 "5" "six"; # a matrix
7 8 9],
[MultiRow(2, :c, "a11 \\& a21"), "a12", "a13"],
["", "a22", "a23"],
(CMidRule(1, 2), CMidRule("lr", 1, 1)), # just to test tuples
[MultiColumn(2, :c, "centered")], # ragged!
Rule(:bottom)]
tlatex = raw"\begin{tabular}{lcl}
\toprule
$\alpha$ & $\beta$ & sum \\
\midrule
1 & 2 & 3 \\
\hline
4.0 & 5 & six \\
7 & 8 & 9 \\
\multirow[c]{2}{*}{a11 \& a21} & a12 & a13 \\
& a22 & a23 \\ \cmidrule{1-2} \cmidrule(lr){1-1}
\multicolumn{2}{c}{centered} \\
\bottomrule
\end{tabular}"
tlatex = replace(tlatex, "\r\n"=>"\n")
@test latex_tabular(String, tb, tlines) ≅ tlatex
tmp = tempname()
latex_tabular(tmp, tb, tlines)
@test isfile(tmp) && read(tmp, String) ≅ tlatex
@test read(tmp, String) ≅ tlatex
end
@test_throws ArgumentError latex_cell(stdout, MultiColumn(2, :BAD, ""))
@test_throws ArgumentError CMidRule(3, 1) # not ≤
@test_throws MethodError latex_cell(stdout, ("un", "supported"))
@test_throws MethodError CMidRule(1, 1, 1, 2) # invalid types
@testset "longtable" begin
lt = LongTable("rrr", ["alpha", "beta", "gamma"])
tlines = [[1 2 3 ;
4.0 "5" "six"],
Rule(:h)]
tlatex = raw"\begin{longtable}[c]{rrr}
\hline
alpha & beta & gamma \\
\hline
\endfirsthead
\multicolumn{3}{l}
{{\bfseries \tablename\ \thetable{} --- continued from previous page}} \\
\hline
alpha & beta & gamma \\
\hline
\endhead
\hline
\multicolumn{3}{r}{{\bfseries Continued on next page}} \\
\hline
\endfoot
\hline
\endlastfoot
1 & 2 & 3 \\
4.0 & 5 & six \\
\hline
\end{longtable}"
tlatex = replace(tlatex, "\r\n"=>"\n")
@test latex_tabular(String, lt, tlines) ≅ tlatex
tmp = tempname()
latex_tabular(tmp, lt, tlines)
@test isfile(tmp) && read(tmp, String) ≅ tlatex
@test read(tmp, String) ≅ tlatex
end
| LaTeXTabulars | https://github.com/tpapp/LaTeXTabulars.jl.git |
|
[
"MIT"
] | 0.1.3 | 1e4928fb66735bb9fbc74a74e394d9bbd49f474d | code | 363 | ####
#### Coverage summary, printed as "(percentage) covered".
####
#### Useful for CI environments that just want a summary (eg a Gitlab setup).
####
using Coverage
cd(joinpath(@__DIR__, "..", "..")) do
covered_lines, total_lines = get_summary(process_folder())
percentage = covered_lines / total_lines * 100
println("($(percentage)%) covered")
end
| LaTeXTabulars | https://github.com/tpapp/LaTeXTabulars.jl.git |
|
[
"MIT"
] | 0.1.3 | 1e4928fb66735bb9fbc74a74e394d9bbd49f474d | code | 266 | # only push coverage from one bot
get(ENV, "TRAVIS_OS_NAME", nothing) == "linux" || exit(0)
get(ENV, "TRAVIS_JULIA_VERSION", nothing) == "1.0" || exit(0)
using Coverage
cd(joinpath(@__DIR__, "..", "..")) do
Codecov.submit(Codecov.process_folder())
end
| LaTeXTabulars | https://github.com/tpapp/LaTeXTabulars.jl.git |
|
[
"MIT"
] | 0.1.3 | 1e4928fb66735bb9fbc74a74e394d9bbd49f474d | docs | 2608 | # LaTeXTabulars.jl

[](https://github.com/tpapp/LaTeXTabulars.jl/actions?query=workflow%3ACI)
[](http://codecov.io/github/tpapp/LaTeXTabulars.jl?branch=master)
Write tabular data from Julia in LaTeX format.
This is a *very thin wrapper*, basically for avoiding some loops and repeatedly used strings. It assumes that you know how the LaTeX `tabular` environment works, and you have formatted the cells to strings if you want anything fancy like rounding or alignment on the decimal dot.
This is how it works:
```julia
using LaTeXTabulars
using LaTeXStrings # not a dependency, but works nicely
latex_tabular("/tmp/table.tex",
Tabular("lcl"),
[Rule(:top),
[L"\alpha", L"\beta", "sum"],
Rule(:mid),
[1, 2, 3],
Rule(), # a nice \hline to make it ugly
[4.0 "5" "six"; # a matrix
7 8 9],
CMidRule(1, 2),
[MultiColumn(2, :c, "centered")], # ragged!
Rule(:bottom)])
```
will write something like
```LaTeX
\begin{tabular}{lcl}
\toprule
$\alpha$ & $\beta$ & sum \\
\midrule
1 & 2 & 3 \\
\hline
4.0 & 5 & six \\
7 & 8 & 9 \\
\cmidrule{1-2}
\multicolumn{2}{c}{centered} \\
\bottomrule
\end{tabular}
```
to `/tmp/table.tex`.
Note that the position specifier `lcl` is not checked for valid syntax or consitency with the contents, just emitted as is, allowing the use of [dcolumn](https://ctan.org/pkg/dcolumn) or similar, and the number of cells in each line is not checked for consistency. This means that the usual LaTeX rules apply: fewer cells than position specifiers gives you a ragged table, more cells and LaTeX will complain about having to change `&` to `\\`.
See `?latex_tabular` for the documentation of the syntax, and the unit tests for examples.
Rule types in [booktabs](https://ctan.org/pkg/booktabs) are supported. Vertical rules of any kind are *not explicitly supported* and it would be difficult to convince me to add them. The documentation of [booktabs](https://ctan.org/pkg/booktabs) should explain why. That said, if you insist, you can use a cell like `\vline text`.
The other tabular type currently implemented is `LongTable`. The code is generic, so [other tabular-like types](https://en.wikibooks.org/wiki/LaTeX/Tables) can be easily added, just open an issue.
| LaTeXTabulars | https://github.com/tpapp/LaTeXTabulars.jl.git |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.