hexsha
stringlengths 40
40
| size
int64 38
969k
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
106
| max_stars_repo_name
stringlengths 8
104
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
4
| max_stars_count
int64 1
38.8k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
106
| max_issues_repo_name
stringlengths 8
104
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
4
| max_issues_count
int64 1
53.3k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
106
| max_forks_repo_name
stringlengths 8
104
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
4
| max_forks_count
int64 1
6.24k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 38
969k
| avg_line_length
float64 6.33
6.5k
| max_line_length
int64 15
269k
| alphanum_fraction
float64 0.18
0.91
| test_functions
listlengths 1
212
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f7005682f45127ca851469ce7a4ea680c9da5dc4
| 49
|
jl
|
Julia
|
AE/test/runtests.jl
|
foldfelis/ML101.jl
|
b4b217ac4af88ba460ec26c5c8a1ce322edae64a
|
[
"MIT"
] | 6
|
2021-02-23T05:48:18.000Z
|
2021-02-23T11:52:24.000Z
|
AE/test/runtests.jl
|
foldfelis/ML101.jl
|
b4b217ac4af88ba460ec26c5c8a1ce322edae64a
|
[
"MIT"
] | 5
|
2021-02-22T21:59:07.000Z
|
2021-05-05T07:29:55.000Z
|
AE/test/runtests.jl
|
foldfelis/ML101.jl
|
b4b217ac4af88ba460ec26c5c8a1ce322edae64a
|
[
"MIT"
] | 1
|
2021-02-28T07:04:06.000Z
|
2021-02-28T07:04:06.000Z
|
using AE
using Test
@testset "AE.jl" begin
end
| 7
| 22
| 0.714286
|
[
"@testset \"AE.jl\" begin\n\nend"
] |
f702b1e015efb351ee28034b390c3e7d1c8857bc
| 7,933
|
jl
|
Julia
|
src/OrthoPolynomials.jl
|
OpenLibMathSeq/Sequences
|
e53c1f30b7bf81669805f21d408d407b727615b5
|
[
"MIT"
] | 6
|
2019-06-25T08:54:44.000Z
|
2021-11-07T04:52:29.000Z
|
src/OrthoPolynomials.jl
|
OpenLibMathSeq/Sequences
|
e53c1f30b7bf81669805f21d408d407b727615b5
|
[
"MIT"
] | 3
|
2019-04-30T19:07:41.000Z
|
2019-06-04T15:51:34.000Z
|
src/OrthoPolynomials.jl
|
PeterLuschny/IntegerSequences.jl
|
1b9440bc8b86e3ae74fd26ee48fba412befbbdb5
|
[
"MIT"
] | 4
|
2019-04-30T17:00:10.000Z
|
2020-02-08T11:32:39.000Z
|
# This file is part of IntegerSequences.
# Copyright Peter Luschny. License is MIT.
(@__DIR__) ∉ LOAD_PATH && push!(LOAD_PATH, (@__DIR__))
module OrthoPolynomials
using Nemo, Triangles
export ModuleOrthoPolynomials
export OrthoPoly, InvOrthoPoly
export T053121, T216916, T217537, T064189, T202327, T111062, T099174
export T066325, T049310, T137338, T104562, T037027, T049218, T159834, T137286
export T053120, T053117, T111593, T059419
export L217924, L005773, L108624, L005425, L000085, L001464, L003723, L006229
"""
* OrthoPoly, InvOrthoPoly, T053121, T216916, T217537, T064189, T202327, T111062, T099174, T066325, T049310, T137338, T104562, T037027, T049218, T159834, T137286, T053120, T053117, T111593, T059419, L217924, L005773, L108624, L005425, L000085, L001464, L003723, L006229
"""
const ModuleOrthoPolynomials = ""
# Cf. http://oeis.org/wiki/User:Peter_Luschny/AignerTriangles
"""
By the theorem of Favard an orthogonal polynomial systems ``p_{n}(x)`` is a sequence of real polynomials with deg``(p_{n}(x)) = n`` for all ``n`` if and only if
`` p_{n+1}(x) = (x - s_n)p_n(x) - t_n p_{n-1}(x) ``
with ``p_{0}(x)=1`` for some pair of seq's ``s_k`` and ``t_k``. Return the coefficients of the polynomials as a triangular array with `dim` rows.
"""
function OrthoPoly(dim::Int, s::Function, t::Function)
dim ≤ 0 && return ZZ[]
T = fill(ZZ(0), dim, dim)
for n ∈ 1:dim T[n, n] = 1 end
for n ∈ 2:dim, k ∈ 1:n-1
T[n, k] = ((k > 1 ? T[n-1, k-1] : 0)
+ s(k - 1) * T[n-1, k] + t(k) * T[n-1, k+1])
end
[T[n, k] for n ∈ 1:dim for k ∈ 1:n] # flatt format
# [[T[n, k] for k ∈ 1:n] for n ∈ 1:dim] # triangle format
end
"""
Return the inverse of the coefficients of the orthogonal polynomials generated by ``s`` and ``t`` as a triangular array with `dim` rows.
"""
function InvOrthoPoly(dim::Int, s::Function, t::Function)
dim ≤ 0 && return ZZ[]
T = fill(ZZ(0), dim, dim)
for n ∈ 1:dim T[n, n] = 1 end
for n ∈ 1:dim-1, k ∈ 1:n+1
T[n+1, k] = ((k > 1 ? T[n, k-1] : 0)
- s(n - 1) * T[n, k] - (n > 1 ? t(n - 1) * T[n-1, k] : 0))
end
[T[n, k] for n ∈ 1:dim for k ∈ 1:n]
end
"""
Return the Catalan triangle (with 0's) read by rows.
"""
T053121(dim::Int) = OrthoPoly(dim, n -> 0, n -> 1)
# """
# binomial(n, floor(n/2)).
# """
# L001405(len::Int) = RowSums(T053121(len))
"""
Return the coefficients of some orthogonal polynomials related to set partitions without singletons (cf. A000296).
"""
T216916(dim::Int) = OrthoPoly(dim, n -> n + 1, n -> n + 1)
"""
Return the triangle ``T(n,k)`` of tangent numbers, coefficient of ``x^n/n!`` in the expansion of ``(tan x)^k/k!``.
"""
T059419(dim::Int) = OrthoPoly(dim, n -> 0, n -> n * (n - 1))
"""
Return the expansion of exp(tan(x)).
"""
L006229(len::Int) = RowSums(T059419(len))
"""
Return the first len integers defined as ``a(n) = n! [x^n] \\exp(2 \\exp (x) - x - 2)``.
"""
L217924(len::Int) = RowSums(T217537(len))
"""
Return the coefficients of some orthogonal polynomials related to indecomposable set partitions without singletons (cf. A098742).
"""
T217537(dim::Int) = OrthoPoly(dim, n -> n, n -> n)
"""
Return the (reflected) Motzkin triangle.
"""
T064189(dim::Int) = OrthoPoly(dim, n -> 1, n -> 1)
"""
Return the number of directed animals of size n as an array of length len.
"""
L005773(len::Int) = RowSums(T064189(len))
"""
Return the coefficients of ``x^n`` in the expansion of ``((-1-x+√(1+2x+5x^2))/2)^k`` as a triangle with dim rows.
"""
T202327(dim::Int) = OrthoPoly(dim, n -> -1, n -> -1)
"""
Return the sequence with generating function satisfying ``x = (A(x)+(A(x))^2)/(1-A(x)-(A(x))^2)``.
"""
L108624(len::Int) = RowSums(T202327(len))
"""
Return the triangle ``T(n, k) = \\binom{n}{k} \\times`` involutions``(n - k)``.
"""
T111062(dim::Int) = OrthoPoly(dim, n -> 1, n -> n)
"""
Return the number of self-inverse partial permutations.
"""
L005425(len::Int) = RowSums(T111062(len))
"""
Return the coefficients of the modified Hermite polynomials.
"""
T099174(dim::Int) = OrthoPoly(dim, n -> 0, n -> n)
# Also
# T099174(dim::Int) = InvOrthoPoly(dim, n -> 0, n -> -n)
"""
Return the number of involutions.
"""
L000085(len::Int) = RowSums(T099174(len))
"""
Return the coefficients of unitary Hermite polynomials He``_n(x)``.
"""
T066325(dim::Int) = InvOrthoPoly(dim, n -> 0, n -> n)
"""
Return the sequence defined by ``a(n) = n! [x^n] \\exp(-x-(x^2)/2)``.
"""
L001464(len::Int) = RowSums(T066325(len), true)
"""
Return the triangle of tanh numbers.
"""
T111593(dim::Int) = OrthoPoly(dim, n -> 0, n -> -n * (n - 1))
"""
Return the sequence defined by ``A(n) = n! [x^n] \\exp \\tan(x)`` as an array of length `len`.
"""
L003723(len::Int) = RowSums(T111593(len))
"""
Return the coefficients of Chebyshev's U``(n, x/2)`` polynomials.
"""
T049310(dim::Int) = InvOrthoPoly(dim, n -> 0, n -> 1)
"""
Return the coefficients of the Charlier polynomials with parameter ``a = 1``.
"""
T137338(dim::Int) = InvOrthoPoly(dim, n -> n + 1, n -> n + 1)
"""
Return the inverse of the Motzkin triangle (cf. A064189).
"""
T104562(dim::Int) = InvOrthoPoly(dim, n -> 1, n -> 1)
"""
Return the skew Fibonacci-Pascal triangle with `dim` rows.
"""
T037027(dim::Int) = InvOrthoPoly(dim, n -> -1, n -> -1)
"""
Return the arctangent numbers (expansion of arctan``(x)^n/n!``).
"""
T049218(dim::Int) = InvOrthoPoly(dim, n -> 0, n -> n * (n + 1))
"""
Return the coefficients of Hermite polynomials ``H(n, (x-1)/√(2))/(√(2))^n``.
"""
T159834(dim::Int) = InvOrthoPoly(dim, n -> 1, n -> n)
"""
Return the coefficients of a variant of the Hermite polynomials.
"""
T137286(dim::Int) = InvOrthoPoly(dim, n -> 0, n -> n + 1)
"""
Return the coefficients of the Chebyshev-T polynomials.
"""
function T053120(len)
T = ZTriangle(len)
R, x = PolynomialRing(ZZ, "x")
m = 1
for n ∈ 0:len-1
f = chebyshev_t(n, x)
for k ∈ 0:n
T[m] = coeff(f, k)
m += 1
end
end
T
end
"""
Return the coefficients of the Chebyshev-U polynomials.
"""
function T053117(len)
T = ZTriangle(len)
R, x = PolynomialRing(ZZ, "x")
m = 1
for n ∈ 0:len-1
f = chebyshev_u(n, x)
for k ∈ 0:n
T[m] = coeff(f, k)
m += 1
end
end
T
end
#START-TEST-########################################################
using Test, SeqTests
function test()
@testset "OrthoPoly" begin
@test isa(OrthoPoly(10, n -> 1, n -> n + 1)[end], fmpz)
@test isa(InvOrthoPoly(10, n -> 1, n -> n + 1)[end], fmpz)
@test RowSums(T217537(8)) == L217924(8)
if data_installed()
T = [
T066325,
T049310,
T137338,
T104562,
T037027,
T049218,
T159834,
T137286,
T053120,
T053117,
T053121,
T216916,
T217537,
T064189,
T202327,
T111062,
T099174,
T111593,
T064189
]
SeqTest(T, 'T')
L = [L217924, L005425, L000085, L001464, L003723, L108624, L006229]
SeqTest(L, 'L')
end
end
end
function demo()
T = T111593(8)
ShowAsΔ(T)
println(RowSums(T))
T = T217537(8)
ShowAsΔ(T)
println(RowSums(T))
T = T053117(8)
ShowAsΔ(T)
println(RowSums(T))
end
"""
T111062(500) :: 0.339080 seconds (750.52 k allocations: 15.375 MiB)
T066325(500) :: 0.157202 seconds (751.50 k allocations: 13.374 MiB)
T053120(500) :: 0.061058 seconds (375.75 k allocations: 6.705 MiB)
"""
function perf()
GC.gc()
@time T111062(500)
GC.gc()
@time T066325(500)
GC.gc()
@time T053120(500)
end
function main()
test()
demo()
perf()
end
main()
end # module
| 23.680597
| 268
| 0.577209
|
[
"@testset \"OrthoPoly\" begin\n\n @test isa(OrthoPoly(10, n -> 1, n -> n + 1)[end], fmpz)\n @test isa(InvOrthoPoly(10, n -> 1, n -> n + 1)[end], fmpz)\n @test RowSums(T217537(8)) == L217924(8)\n\n if data_installed()\n\n T = [\n T066325,\n T049310,\n T137338,\n T104562,\n T037027,\n T049218,\n T159834,\n T137286,\n T053120,\n T053117,\n T053121,\n T216916,\n T217537,\n T064189,\n T202327,\n T111062,\n T099174,\n T111593,\n T064189\n ]\n SeqTest(T, 'T')\n\n L = [L217924, L005425, L000085, L001464, L003723, L108624, L006229]\n SeqTest(L, 'L')\n end\n end"
] |
f702dea5779e5262fac4b7f8e161329cc0c3f6d4
| 2,303
|
jl
|
Julia
|
test/runtests.jl
|
felipenoris/SplitIterators.jl
|
6ad384e290feed1339e94ff169b58922a3785359
|
[
"MIT"
] | 2
|
2021-08-22T14:45:30.000Z
|
2022-03-19T19:34:46.000Z
|
test/runtests.jl
|
felipenoris/SplitIterators.jl
|
6ad384e290feed1339e94ff169b58922a3785359
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
felipenoris/SplitIterators.jl
|
6ad384e290feed1339e94ff169b58922a3785359
|
[
"MIT"
] | null | null | null |
using Test
import SplitIterators
@testset "split 11 by 3" begin
x = collect(1:11)
for (i, part) in enumerate(SplitIterators.split(x, 3))
if i == 1
@test part == collect(1:4)
elseif i == 2
@test part == collect(5:8)
elseif i == 3
@test part == collect(9:11)
else
@test false
end
end
@test length(SplitIterators.split(x, 3)) == 3
end
@testset "split range 11 by 3" begin
x = 1:11
for (i, part) in enumerate(SplitIterators.split(x, 3))
if i == 1
@test part == 1:4
elseif i == 2
@test part == 5:8
elseif i == 3
# TODO: should yield `9:11`
@test part == collect(9:11)
else
@test false
end
end
@test length(SplitIterators.split(x, 3)) == 3
end
@testset "split 11 by 11" begin
x = collect(1:11)
for (i, part) in enumerate(SplitIterators.split(x, 11))
@test part == [i]
end
end
@testset "split 11 by 15" begin
x = collect(1:11)
for (i, part) in enumerate(SplitIterators.split(x, 15))
@test part == [i]
end
end
@testset "split 11 by 1" begin
x = collect(1:11)
for (i, part) in enumerate(SplitIterators.split(x, 1))
if i == 1
@test part == collect(1:11)
else
@test false
end
end
end
@testset "split 12 by 2" begin
x = collect(1:12)
for (i, part) in enumerate(SplitIterators.split(x, 2))
if i == 1
@test part == collect(1:6)
elseif i == 2
@test part == collect(7:12)
else
@test false
end
end
end
@testset "split empty itr" begin
x = []
@test_throws ArgumentError SplitIterators.split(x, 10)
end
@testset "eltype" begin
x = [1]
if VERSION < v"1.4"
@test eltype(SplitIterators.split(x, 1)) == Vector{Int}
else
@test eltype(SplitIterators.split(x, 1)) == Union{SubArray{Int64, 1, Vector{Int64}, Tuple{UnitRange{Int64}}, true}, Vector{Int64}}
end
x = 1:2
if VERSION < v"1.4"
@test eltype(SplitIterators.split(x, 1)) == Vector{Int}
else
@test eltype(SplitIterators.split(x, 1)) == Union{UnitRange{Int64}, Vector{Int64}}
end
end
| 21.933333
| 138
| 0.539731
|
[
"@testset \"split 11 by 3\" begin\n x = collect(1:11)\n\n for (i, part) in enumerate(SplitIterators.split(x, 3))\n if i == 1\n @test part == collect(1:4)\n elseif i == 2\n @test part == collect(5:8)\n elseif i == 3\n @test part == collect(9:11)\n else\n @test false\n end\n end\n\n @test length(SplitIterators.split(x, 3)) == 3\nend",
"@testset \"split range 11 by 3\" begin\n x = 1:11\n\n for (i, part) in enumerate(SplitIterators.split(x, 3))\n if i == 1\n @test part == 1:4\n elseif i == 2\n @test part == 5:8\n elseif i == 3\n # TODO: should yield `9:11`\n @test part == collect(9:11)\n else\n @test false\n end\n end\n\n @test length(SplitIterators.split(x, 3)) == 3\nend",
"@testset \"split 11 by 11\" begin\n x = collect(1:11)\n\n for (i, part) in enumerate(SplitIterators.split(x, 11))\n @test part == [i]\n end\nend",
"@testset \"split 11 by 15\" begin\n x = collect(1:11)\n\n for (i, part) in enumerate(SplitIterators.split(x, 15))\n @test part == [i]\n end\nend",
"@testset \"split 11 by 1\" begin\n x = collect(1:11)\n\n for (i, part) in enumerate(SplitIterators.split(x, 1))\n if i == 1\n @test part == collect(1:11)\n else\n @test false\n end\n end\nend",
"@testset \"split 12 by 2\" begin\n x = collect(1:12)\n\n for (i, part) in enumerate(SplitIterators.split(x, 2))\n if i == 1\n @test part == collect(1:6)\n elseif i == 2\n @test part == collect(7:12)\n else\n @test false\n end\n end\nend",
"@testset \"split empty itr\" begin\n x = []\n @test_throws ArgumentError SplitIterators.split(x, 10)\nend",
"@testset \"eltype\" begin\n x = [1]\n if VERSION < v\"1.4\"\n @test eltype(SplitIterators.split(x, 1)) == Vector{Int}\n else\n @test eltype(SplitIterators.split(x, 1)) == Union{SubArray{Int64, 1, Vector{Int64}, Tuple{UnitRange{Int64}}, true}, Vector{Int64}}\n end\n\n x = 1:2\n if VERSION < v\"1.4\"\n @test eltype(SplitIterators.split(x, 1)) == Vector{Int}\n else\n @test eltype(SplitIterators.split(x, 1)) == Union{UnitRange{Int64}, Vector{Int64}}\n end\nend"
] |
f7065123fa9d24e80182de827c92598269a8c321
| 122
|
jl
|
Julia
|
test/runtests.jl
|
Teslos/MyExample.jl
|
014079e8dd99a63c1ff8340d1d9ed670ed8e91ad
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
Teslos/MyExample.jl
|
014079e8dd99a63c1ff8340d1d9ed670ed8e91ad
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
Teslos/MyExample.jl
|
014079e8dd99a63c1ff8340d1d9ed670ed8e91ad
|
[
"MIT"
] | null | null | null |
using MyExample
using Test
#2x + 3y
@testset "MyExample.jl" begin
@test my_f(2,1) == 7
@test my_f(2,3) == 13
end
| 13.555556
| 29
| 0.622951
|
[
"@testset \"MyExample.jl\" begin\n @test my_f(2,1) == 7\n @test my_f(2,3) == 13\nend"
] |
f7071fefba07848f0e49c2ef170c0eb46f03133d
| 1,564
|
jl
|
Julia
|
test/Ocean/SplitExplicit/test_coriolis.jl
|
ErikQQY/ClimateMachine.jl
|
ad128d457dd877bf21b5bcd845d6c3fa42de3f8a
|
[
"Apache-2.0"
] | 256
|
2020-05-06T08:03:16.000Z
|
2022-03-22T14:01:20.000Z
|
test/Ocean/SplitExplicit/test_coriolis.jl
|
ErikQQY/ClimateMachine.jl
|
ad128d457dd877bf21b5bcd845d6c3fa42de3f8a
|
[
"Apache-2.0"
] | 1,174
|
2020-05-06T16:19:51.000Z
|
2022-02-25T17:51:13.000Z
|
test/Ocean/SplitExplicit/test_coriolis.jl
|
ErikQQY/ClimateMachine.jl
|
ad128d457dd877bf21b5bcd845d6c3fa42de3f8a
|
[
"Apache-2.0"
] | 45
|
2020-05-08T02:28:36.000Z
|
2022-03-14T22:44:56.000Z
|
#!/usr/bin/env julia --project
using Test
include("hydrostatic_spindown.jl")
ClimateMachine.init()
const FT = Float64
#################
# RUN THE TESTS #
#################
@testset "$(@__FILE__)" begin
include("../refvals/hydrostatic_spindown_refvals.jl")
# simulation time
timeend = FT(15 * 24 * 3600) # s
tout = FT(24 * 3600) # s
timespan = (tout, timeend)
# DG polynomial order
N = Int(4)
# Domain resolution
Nˣ = Int(5)
Nʸ = Int(5)
Nᶻ = Int(8)
resolution = (N, Nˣ, Nʸ, Nᶻ)
# Domain size
Lˣ = 1e6 # m
Lʸ = 1e6 # m
H = 400 # m
dimensions = (Lˣ, Lʸ, H)
BC = (
OceanBC(Impenetrable(FreeSlip()), Insulating()),
OceanBC(Penetrable(FreeSlip()), Insulating()),
)
config = SplitConfig(
"rotating_bla",
resolution,
dimensions,
Coupled(),
Rotating();
solver = SplitExplicitSolver,
boundary_conditions = BC,
)
#=
BC = (
ClimateMachine.Ocean.SplitExplicit01.OceanFloorFreeSlip(),
ClimateMachine.Ocean.SplitExplicit01.OceanSurfaceNoStressNoForcing(),
)
config = SplitConfig(
"rotating_jmc",
resolution,
dimensions,
Coupled(),
Rotating();
solver = SplitExplicitLSRK2nSolver,
boundary_conditions = BC,
)
=#
run_split_explicit(
config,
timespan,
dt_fast = 300,
dt_slow = 300, # 90 * 60,
# refDat = refVals.ninety_minutes,
analytic_solution = true,
)
end
| 20.578947
| 77
| 0.555627
|
[
"@testset \"$(@__FILE__)\" begin\n\n include(\"../refvals/hydrostatic_spindown_refvals.jl\")\n\n # simulation time\n timeend = FT(15 * 24 * 3600) # s\n tout = FT(24 * 3600) # s\n timespan = (tout, timeend)\n\n # DG polynomial order\n N = Int(4)\n\n # Domain resolution\n Nˣ = Int(5)\n Nʸ = Int(5)\n Nᶻ = Int(8)\n resolution = (N, Nˣ, Nʸ, Nᶻ)\n\n # Domain size\n Lˣ = 1e6 # m\n Lʸ = 1e6 # m\n H = 400 # m\n dimensions = (Lˣ, Lʸ, H)\n\n BC = (\n OceanBC(Impenetrable(FreeSlip()), Insulating()),\n OceanBC(Penetrable(FreeSlip()), Insulating()),\n )\n config = SplitConfig(\n \"rotating_bla\",\n resolution,\n dimensions,\n Coupled(),\n Rotating();\n solver = SplitExplicitSolver,\n boundary_conditions = BC,\n )\n\n #=\n BC = (\n ClimateMachine.Ocean.SplitExplicit01.OceanFloorFreeSlip(),\n ClimateMachine.Ocean.SplitExplicit01.OceanSurfaceNoStressNoForcing(),\n )\n\n config = SplitConfig(\n \"rotating_jmc\",\n resolution,\n dimensions,\n Coupled(),\n Rotating();\n solver = SplitExplicitLSRK2nSolver,\n boundary_conditions = BC,\n )\n =#\n\n run_split_explicit(\n config,\n timespan,\n dt_fast = 300,\n dt_slow = 300, # 90 * 60,\n # refDat = refVals.ninety_minutes,\n analytic_solution = true,\n )\nend"
] |
f70bd5fdbd81a3e0a966c69edae9271ec76b4c57
| 396
|
jl
|
Julia
|
test/runtests.jl
|
hendri54/CollegeEntry
|
bcbd6434fdd7f66944075b0b85efbfd8f6e6ac29
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
hendri54/CollegeEntry
|
bcbd6434fdd7f66944075b0b85efbfd8f6e6ac29
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
hendri54/CollegeEntry
|
bcbd6434fdd7f66944075b0b85efbfd8f6e6ac29
|
[
"MIT"
] | null | null | null |
using CollegeEntry, ModelObjectsLH, ModelParams
using Test, TestSetExtensions
include("test_helpers.jl")
@testset "All" begin
include("helpers_test.jl")
include("admissions_test.jl");
include("admission_prob_test.jl");
include("student_rankings_test.jl")
include("entry_test.jl");
include("entry_decisions_test.jl")
include("entry_results_test.jl")
end
# ----------
| 24.75
| 47
| 0.719697
|
[
"@testset \"All\" begin\n include(\"helpers_test.jl\")\n include(\"admissions_test.jl\");\n include(\"admission_prob_test.jl\");\n include(\"student_rankings_test.jl\")\n include(\"entry_test.jl\");\n include(\"entry_decisions_test.jl\")\n include(\"entry_results_test.jl\")\nend"
] |
f70c3ff4968c391bb44e7f54b612f4bd73c46365
| 1,192
|
jl
|
Julia
|
test/GLMesh.jl
|
cvdlab/ViewerGL.js
|
ae28d7808699f9c34add4ad265b68a84bfa14842
|
[
"MIT"
] | 4
|
2019-07-25T23:07:18.000Z
|
2021-09-05T18:38:20.000Z
|
test/GLMesh.jl
|
cvdlab/ViewerGL.js
|
ae28d7808699f9c34add4ad265b68a84bfa14842
|
[
"MIT"
] | null | null | null |
test/GLMesh.jl
|
cvdlab/ViewerGL.js
|
ae28d7808699f9c34add4ad265b68a84bfa14842
|
[
"MIT"
] | 31
|
2019-10-09T14:09:51.000Z
|
2022-03-31T14:52:35.000Z
|
using Test
using LinearAlgebraicRepresentation
Lar = LinearAlgebraicRepresentation
using ViewerGL
GL = ViewerGL
@testset "GLMesh.jl" begin
# function GLMesh()
@testset "GLMesh" begin
@test
@test
@test
@test
end
# function GLMesh(primitive)
@testset "GLMesh" begin
@test
@test
@test
@test
end
# function releaseGpuResources(mesh::GLMesh)
@testset "releaseGpuResources" begin
@test
@test
@test
@test
end
# function computeNormal(p1::Point2d, p2::Point2d)
@testset "computeNormal" begin
@test
@test
@test
@test
end
# function computeNormal(p0::Point3d,p1::Point3d,p2::Point3d)
@testset "computeNormal" begin
@test
@test
@test
@test
end
# function getBoundingBox(mesh::GLMesh)
@testset "getBoundingBox" begin
@test
@test
@test
@test
end
# function GLCuboid(box::Box3d)
@testset "GLCuboid" begin
@test
@test
@test
@test
end
# function GLAxis(p0::Point3d,p1::Point3d)
@testset "GLAxis" begin
@test
@test
@test
@test
end
end
| 16.108108
| 64
| 0.589765
|
[
"@testset \"GLMesh.jl\" begin\n\n # function GLMesh()\n @testset \"GLMesh\" begin\n @test\n @test\n @test\n @test\n end\n\n # function GLMesh(primitive)\n @testset \"GLMesh\" begin\n @test\n @test\n @test\n @test\n end\n\n # function releaseGpuResources(mesh::GLMesh)\n @testset \"releaseGpuResources\" begin\n @test\n @test\n @test\n @test\n end\n\n # function computeNormal(p1::Point2d, p2::Point2d)\n @testset \"computeNormal\" begin\n @test\n @test\n @test\n @test\n end\n\n # function computeNormal(p0::Point3d,p1::Point3d,p2::Point3d)\n @testset \"computeNormal\" begin\n @test\n @test\n @test\n @test\n end\n\n # function getBoundingBox(mesh::GLMesh)\n @testset \"getBoundingBox\" begin\n @test\n @test\n @test\n @test\n end\n\n # function GLCuboid(box::Box3d)\n @testset \"GLCuboid\" begin\n @test\n @test\n @test\n @test\n end\n\n # function GLAxis(p0::Point3d,p1::Point3d)\n @testset \"GLAxis\" begin\n @test\n @test\n @test\n @test\n end\n\nend"
] |
f70ccf8b21eeac0bbd8a4ce08b4cb71e0206dba4
| 3,529
|
jl
|
Julia
|
test/knr/testknr.jl
|
UnofficialJuliaMirrorSnapshots/SimilaritySearch.jl-053f045d-5466-53fd-b400-a066f88fe02a
|
70c46490431ca7d0e5cf41052bc36afc4ba3c8fa
|
[
"Apache-2.0"
] | null | null | null |
test/knr/testknr.jl
|
UnofficialJuliaMirrorSnapshots/SimilaritySearch.jl-053f045d-5466-53fd-b400-a066f88fe02a
|
70c46490431ca7d0e5cf41052bc36afc4ba3c8fa
|
[
"Apache-2.0"
] | null | null | null |
test/knr/testknr.jl
|
UnofficialJuliaMirrorSnapshots/SimilaritySearch.jl-053f045d-5466-53fd-b400-a066f88fe02a
|
70c46490431ca7d0e5cf41052bc36afc4ba3c8fa
|
[
"Apache-2.0"
] | null | null | null |
using SimilaritySearch
using SimilaritySearch.SimilarReferences
using Test
function test_vectors(create_index, dist::Function, ksearch, nick)
@testset "indexing vectors with $nick and $dist" begin
n = 1000 # number of items in the dataset
m = 100 # number of queries
dim = 3 # vector's dimension
db = [rand(Float32, dim) |> normalize! for i in 1:n]
queries = [rand(Float32, dim) |> normalize! for i in 1:m]
index = create_index(db)
optimize!(index, dist, recall=0.9, k=10)
perf = Performance(dist, index.db, queries, expected_k=10)
p = probe(perf, index, dist)
@show dist, p
@test p.recall > 0.8
@info "adding more items"
for item in queries
push!(index, dist, item)
end
perf = Performance(dist, index.db, queries, expected_k=1)
p = probe(perf, index, dist)
@show dist, p
@test p.recall > 0.999
return p
end
end
function test_sequences(create_index, dist::Function, ksearch, nick)
@testset "indexing sequences with $nick and $dist" begin
n = 1000 # number of items in the dataset
m = 100 # number of queries
dim = 5 # the length of sequences
V = collect(1:10) # vocabulary of the sequences
function create_item()
s = rand(V, dim)
if dist == jaccard_distance || dist == dice_distance || dist == intersection_distance
sort!(s)
s = unique(s)
end
return s
end
db = [create_item() for i in 1:n]
queries = [create_item() for i in 1:m]
@info "inserting items into the index"
index = create_index(db)
# optimize!(index, recall=0.9, k=10)
perf = Performance(dist, index.db, queries, expected_k=10)
p = probe(perf, index, dist)
@show dist, p
@test p.recall > 0.1 ## Performance object tests object identifiers, but sequence distances have a lot of distance collisions
# for item in queries
# push!(index, dist, item)
# end
# perf = Performance(dist, index.db, queries, expected_k=1)
# p = probe(perf, index, dist)
# @show dist, p
# @test p.recall > 0.999
# return p
end
end
@testset "indexing vectors" begin
# NOTE: The following algorithms are complex enough to say we are testing it doesn't have syntax errors, a more grained test functions are required
ksearch = 10
σ = 127
κ = 3
for dist in [
l2_distance, # 1.0 -> metric, < 1.0 if dist is not a metric
l1_distance,
linf_distance,
lp_distance(3),
lp_distance(0.5),
angle_distance
]
p = test_vectors((db) -> fit(Knr, dist, db, numrefs=σ, k=κ), dist, ksearch, "KNR")
end
end
@testset "indexing sequences" begin
# NOTE: The following algorithms are complex enough to say we are testing it doesn't have syntax errors, a more grained test functions are required
ksearch = 10
σ = 127
κ = 3
# metric distances should achieve recall=1 (perhaps lesser because of numerical inestability)
for dist in [
jaccard_distance,
dice_distance,
intersection_distance,
common_prefix_distance,
levenshtein_distance,
lcs_distance,
hamming_distance,
]
p = test_sequences((db) -> fit(Knr, dist, db, numrefs=σ, k=κ), dist, ksearch, "KNR")
end
end
| 32.081818
| 151
| 0.597053
|
[
"@testset \"indexing vectors\" begin\n # NOTE: The following algorithms are complex enough to say we are testing it doesn't have syntax errors, a more grained test functions are required\n ksearch = 10\n σ = 127\n κ = 3\n\n for dist in [\n l2_distance, # 1.0 -> metric, < 1.0 if dist is not a metric\n l1_distance,\n linf_distance,\n lp_distance(3),\n lp_distance(0.5),\n angle_distance\n ]\n p = test_vectors((db) -> fit(Knr, dist, db, numrefs=σ, k=κ), dist, ksearch, \"KNR\")\n end\nend",
"@testset \"indexing sequences\" begin\n # NOTE: The following algorithms are complex enough to say we are testing it doesn't have syntax errors, a more grained test functions are required\n ksearch = 10\n σ = 127\n κ = 3\n \n # metric distances should achieve recall=1 (perhaps lesser because of numerical inestability)\n for dist in [\n jaccard_distance,\n dice_distance,\n intersection_distance,\n common_prefix_distance,\n levenshtein_distance,\n lcs_distance,\n hamming_distance,\n ] \n p = test_sequences((db) -> fit(Knr, dist, db, numrefs=σ, k=κ), dist, ksearch, \"KNR\")\n end\nend",
"@testset \"indexing vectors with $nick and $dist\" begin\n n = 1000 # number of items in the dataset\n m = 100 # number of queries\n dim = 3 # vector's dimension\n\n db = [rand(Float32, dim) |> normalize! for i in 1:n]\n queries = [rand(Float32, dim) |> normalize! for i in 1:m]\n\n index = create_index(db)\n optimize!(index, dist, recall=0.9, k=10)\n perf = Performance(dist, index.db, queries, expected_k=10)\n p = probe(perf, index, dist)\n @show dist, p\n @test p.recall > 0.8\n\n @info \"adding more items\"\n for item in queries\n push!(index, dist, item)\n end\n perf = Performance(dist, index.db, queries, expected_k=1)\n p = probe(perf, index, dist)\n @show dist, p\n @test p.recall > 0.999\n return p\n end",
"@testset \"indexing sequences with $nick and $dist\" begin\n n = 1000 # number of items in the dataset\n m = 100 # number of queries\n dim = 5 # the length of sequences\n V = collect(1:10) # vocabulary of the sequences\n\n function create_item()\n s = rand(V, dim)\n if dist == jaccard_distance || dist == dice_distance || dist == intersection_distance\n sort!(s)\n s = unique(s)\n end\n\n return s\n end\n \n db = [create_item() for i in 1:n]\n queries = [create_item() for i in 1:m]\n\n @info \"inserting items into the index\"\n index = create_index(db)\n # optimize!(index, recall=0.9, k=10)\n perf = Performance(dist, index.db, queries, expected_k=10)\n p = probe(perf, index, dist)\n @show dist, p\n @test p.recall > 0.1 ## Performance object tests object identifiers, but sequence distances have a lot of distance collisions\n\n # for item in queries\n # push!(index, dist, item)\n # end\n # perf = Performance(dist, index.db, queries, expected_k=1)\n # p = probe(perf, index, dist)\n # @show dist, p\n # @test p.recall > 0.999\n # return p\n end"
] |
f70e234e93c6e69904c72f38c7eaec1a83d715df
| 1,759
|
jl
|
Julia
|
test/rountines.jl
|
UnofficialJuliaMirror/YaoBlocks.jl-418bc28f-b43b-5e0b-a6e7-61bbc1a2c1df
|
703091b543e95e6e4a3d7fe451c29ce0dd423c73
|
[
"Apache-2.0"
] | null | null | null |
test/rountines.jl
|
UnofficialJuliaMirror/YaoBlocks.jl-418bc28f-b43b-5e0b-a6e7-61bbc1a2c1df
|
703091b543e95e6e4a3d7fe451c29ce0dd423c73
|
[
"Apache-2.0"
] | null | null | null |
test/rountines.jl
|
UnofficialJuliaMirror/YaoBlocks.jl-418bc28f-b43b-5e0b-a6e7-61bbc1a2c1df
|
703091b543e95e6e4a3d7fe451c29ce0dd423c73
|
[
"Apache-2.0"
] | null | null | null |
using Test, YaoBlocks, LuxurySparse, YaoBase
using YaoBlocks.ConstGate
import YaoBlocks: u1mat, unmat, cunmat, unij!
@testset "dense-u1mat-unmat" begin
nbit = 4
mmm = Rx(0.5) |> mat
m1 = u1mat(nbit, mmm, 2)
m2 = linop2dense(v -> instruct!(v, mmm, 2), nbit)
m3 = unmat(nbit, mmm, (2,))
@test m1 ≈ m2
@test m1 ≈ m3
# test control not
⊗ = kron
res = mat(I2) ⊗ mat(I2) ⊗ mat(P1) ⊗ mat(I2) + mat(I2) ⊗ mat(I2) ⊗ mat(P0) ⊗ mat(Rx(0.5))
m3 = cunmat(nbit, (2,), (0,), mmm, (1,))
@test m3 ≈ res
end
@testset "sparse-u1mat-unmat" begin
nbit = 4
# test control not
⊗ = kron
res = mat(I2) ⊗ mat(I2) ⊗ mat(P1) ⊗ mat(I2) + mat(I2) ⊗ mat(I2) ⊗ mat(P0) ⊗ mat(P1)
m3 = cunmat(nbit, (2,), (0,), mat(P1), (1,))
@test m3 ≈ res
end
@testset "perm-unij-unmat" begin
perm = PermMatrix([1, 2, 3, 4], [1, 1, 1, 1.0])
pm = unij!(copy(perm), [2, 3, 4], PermMatrix([3, 1, 2], [0.1, 0.2, 0.3]))
@test pm ≈ PermMatrix([1, 4, 2, 3], [1, 0.1, 0.2, 0.3])
pm = unij!(copy(perm), [2, 3, 4], PermMatrix([3, 1, 2], [0.1, 0.2, 0.3]) |> staticize)
@test pm ≈ PermMatrix([1, 4, 2, 3], [1, 0.1, 0.2, 0.3])
nbit = 4
mmm = X |> mat
m1 = unmat(nbit, mmm, (2,))
m2 = linop2dense(v -> instruct!(v, mmm, 2), nbit)
@test m1 ≈ m2
end
@testset "identity-unmat" begin
nbit = 4
mmm = Z |> mat
m1 = unmat(nbit, mmm, (2,))
m2 = linop2dense(v -> instruct!(v, mmm, 2), nbit)
@test m1 ≈ m2
end
@testset "fix-static and adjoint for mat" begin
G1 = matblock(rand_unitary(2))
G6 = matblock(rand_unitary(1 << 6))
@test mat(put(3, 2 => G1')) ≈ mat(put(3, 2 => matblock(G1)))'
@test mat(put(7, (3, 2, 1, 5, 4, 6) => G6')) ≈ mat(put(7, (3, 2, 1, 5, 4, 6) => G6))'
end
| 30.327586
| 92
| 0.529847
|
[
"@testset \"dense-u1mat-unmat\" begin\n nbit = 4\n mmm = Rx(0.5) |> mat\n m1 = u1mat(nbit, mmm, 2)\n m2 = linop2dense(v -> instruct!(v, mmm, 2), nbit)\n m3 = unmat(nbit, mmm, (2,))\n @test m1 ≈ m2\n @test m1 ≈ m3\n\n # test control not\n ⊗ = kron\n res = mat(I2) ⊗ mat(I2) ⊗ mat(P1) ⊗ mat(I2) + mat(I2) ⊗ mat(I2) ⊗ mat(P0) ⊗ mat(Rx(0.5))\n m3 = cunmat(nbit, (2,), (0,), mmm, (1,))\n @test m3 ≈ res\nend",
"@testset \"sparse-u1mat-unmat\" begin\n nbit = 4\n # test control not\n ⊗ = kron\n res = mat(I2) ⊗ mat(I2) ⊗ mat(P1) ⊗ mat(I2) + mat(I2) ⊗ mat(I2) ⊗ mat(P0) ⊗ mat(P1)\n m3 = cunmat(nbit, (2,), (0,), mat(P1), (1,))\n @test m3 ≈ res\nend",
"@testset \"perm-unij-unmat\" begin\n perm = PermMatrix([1, 2, 3, 4], [1, 1, 1, 1.0])\n pm = unij!(copy(perm), [2, 3, 4], PermMatrix([3, 1, 2], [0.1, 0.2, 0.3]))\n @test pm ≈ PermMatrix([1, 4, 2, 3], [1, 0.1, 0.2, 0.3])\n pm = unij!(copy(perm), [2, 3, 4], PermMatrix([3, 1, 2], [0.1, 0.2, 0.3]) |> staticize)\n @test pm ≈ PermMatrix([1, 4, 2, 3], [1, 0.1, 0.2, 0.3])\n\n nbit = 4\n mmm = X |> mat\n m1 = unmat(nbit, mmm, (2,))\n m2 = linop2dense(v -> instruct!(v, mmm, 2), nbit)\n @test m1 ≈ m2\nend",
"@testset \"identity-unmat\" begin\n nbit = 4\n mmm = Z |> mat\n m1 = unmat(nbit, mmm, (2,))\n m2 = linop2dense(v -> instruct!(v, mmm, 2), nbit)\n @test m1 ≈ m2\nend",
"@testset \"fix-static and adjoint for mat\" begin\n G1 = matblock(rand_unitary(2))\n G6 = matblock(rand_unitary(1 << 6))\n @test mat(put(3, 2 => G1')) ≈ mat(put(3, 2 => matblock(G1)))'\n @test mat(put(7, (3, 2, 1, 5, 4, 6) => G6')) ≈ mat(put(7, (3, 2, 1, 5, 4, 6) => G6))'\nend"
] |
f712c2d65d4c6d110cc2b0191f55497c456cc7a7
| 945
|
jl
|
Julia
|
Projects/Projet_Optinum/test/runtests.jl
|
faicaltoubali/ENSEEIHT
|
6db0aef64d68446b04f17d1eae574591026002b5
|
[
"Apache-2.0"
] | null | null | null |
Projects/Projet_Optinum/test/runtests.jl
|
faicaltoubali/ENSEEIHT
|
6db0aef64d68446b04f17d1eae574591026002b5
|
[
"Apache-2.0"
] | null | null | null |
Projects/Projet_Optinum/test/runtests.jl
|
faicaltoubali/ENSEEIHT
|
6db0aef64d68446b04f17d1eae574591026002b5
|
[
"Apache-2.0"
] | null | null | null |
using Markdown
using Test
using LinearAlgebra
using TestOptinum
using Optinum
include("../src/Algorithme_De_Newton.jl")
include("../src/Gradient_Conjugue_Tronque.jl")
include("../src/Lagrangien_Augmente.jl")
include("../src/Pas_De_Cauchy.jl")
include("../src/Regions_De_Confiance.jl")
#TestOptinum.cacher_stacktrace()
affiche = true
println("affiche = ",affiche)
# Tester l'ensemble des algorithmes
@testset "Test SujetOptinum" begin
# Tester l'algorithme de Newton
tester_algo_newton(affiche,Algorithme_De_Newton)
# Tester l'algorithme du pas de Cauchy
tester_pas_de_cauchy(affiche,Pas_De_Cauchy)
# Tester l'algorithme du gradient conjugué tronqué
tester_gct(affiche,Gradient_Conjugue_Tronque)
# Tester l'algorithme des Régions de confiance avec PasdeCauchy | GCT
tester_regions_de_confiance(affiche,Regions_De_Confiance)
# Tester l'algorithme du Lagrangien Augmenté
tester_lagrangien_augmente(affiche,Lagrangien_Augmente)
end
| 27.794118
| 70
| 0.812698
|
[
"@testset \"Test SujetOptinum\" begin\n\t# Tester l'algorithme de Newton\n\ttester_algo_newton(affiche,Algorithme_De_Newton)\n\n\t# Tester l'algorithme du pas de Cauchy\n\ttester_pas_de_cauchy(affiche,Pas_De_Cauchy)\n\n\t# Tester l'algorithme du gradient conjugué tronqué\n\ttester_gct(affiche,Gradient_Conjugue_Tronque)\n\n\t# Tester l'algorithme des Régions de confiance avec PasdeCauchy | GCT\n\ttester_regions_de_confiance(affiche,Regions_De_Confiance)\n\n\t# Tester l'algorithme du Lagrangien Augmenté\n\ttester_lagrangien_augmente(affiche,Lagrangien_Augmente)\nend"
] |
f71360a2dafb0db950b40e740ced0cc7c4d67b27
| 1,820
|
jl
|
Julia
|
test/test_returning_original.jl
|
TheRoniOne/Cleaner
|
7279c8e8e92a9763ed72f8614f9a77ddbd40fade
|
[
"MIT"
] | 16
|
2021-08-20T10:07:04.000Z
|
2022-02-07T18:09:40.000Z
|
test/test_returning_original.jl
|
TheRoniOne/Cleaner
|
7279c8e8e92a9763ed72f8614f9a77ddbd40fade
|
[
"MIT"
] | 2
|
2021-08-17T06:09:49.000Z
|
2022-02-06T01:36:49.000Z
|
test/test_returning_original.jl
|
TheRoniOne/Cleaner
|
7279c8e8e92a9763ed72f8614f9a77ddbd40fade
|
[
"MIT"
] | null | null | null |
using Test
using Cleaner:
materializer,
compact_table_ROT,
compact_columns_ROT,
compact_rows_ROT,
delete_const_columns_ROT,
polish_names_ROT,
reinfer_schema_ROT,
row_as_names_ROT,
rename_ROT,
drop_missing_ROT,
add_index_ROT
using DataFrames: DataFrame
@testset "ROT functions are working as expected" begin
testRM1 = DataFrame(;
A=[missing, missing, missing], B=[1, missing, 3], C=["x", "", "z"]
)
@test compact_columns_ROT(testRM1) isa DataFrame
@test compact_rows_ROT(testRM1) isa DataFrame
@test compact_table_ROT(testRM1) isa DataFrame
@test materializer(testRM1)((a=[1], b=[2])) isa DataFrame
let testDF = DataFrame(; A=[1, 1, 1], B=[4, 5, 6], C=String["2", "2", "2"])
@test delete_const_columns_ROT(testDF) isa DataFrame
end
let testDF = DataFrame(
" _aName with_loTsOfProblems" => [1, 2, 3],
" _aName with_loTsOfProblems1" => [4, 5, 6],
" _aName with_loTsOfProblems2" => [7, 8, 9],
)
@test polish_names_ROT(testDF) isa DataFrame
end
let testDF = DataFrame(; A=[1, 2, 3], B=Any[4, missing, "z"], C=Any["5", "6", "9"])
@test reinfer_schema_ROT(testDF) isa DataFrame
end
let testDF = DataFrame(; A=[1, 2, "x", 4], B=[5, 6, "y", 7], C=["x", "y", "z", "a"])
@test row_as_names_ROT(testDF, 3) isa DataFrame
end
let testDF = DataFrame(; A=[1, 2, "x", 4], B=[5, 6, "y", 7], C=["x", "y", "z", "a"])
@test rename_ROT(testDF, [:a, :b, :c]) isa DataFrame
end
let testDF = DataFrame(; A=[1, 2, "x", 4], B=[5, 6, "y", 7], C=["x", "y", "z", "a"])
@test drop_missing_ROT(testDF) isa DataFrame
end
let testDF = DataFrame(; A=[4, 5, 6])
@test add_index_ROT(testDF) isa DataFrame
end
end
| 31.37931
| 88
| 0.590659
|
[
"@testset \"ROT functions are working as expected\" begin\n testRM1 = DataFrame(;\n A=[missing, missing, missing], B=[1, missing, 3], C=[\"x\", \"\", \"z\"]\n )\n\n @test compact_columns_ROT(testRM1) isa DataFrame\n @test compact_rows_ROT(testRM1) isa DataFrame\n @test compact_table_ROT(testRM1) isa DataFrame\n @test materializer(testRM1)((a=[1], b=[2])) isa DataFrame\n\n let testDF = DataFrame(; A=[1, 1, 1], B=[4, 5, 6], C=String[\"2\", \"2\", \"2\"])\n @test delete_const_columns_ROT(testDF) isa DataFrame\n end\n\n let testDF = DataFrame(\n \" _aName with_loTsOfProblems\" => [1, 2, 3],\n \" _aName with_loTsOfProblems1\" => [4, 5, 6],\n \" _aName with_loTsOfProblems2\" => [7, 8, 9],\n )\n @test polish_names_ROT(testDF) isa DataFrame\n end\n\n let testDF = DataFrame(; A=[1, 2, 3], B=Any[4, missing, \"z\"], C=Any[\"5\", \"6\", \"9\"])\n @test reinfer_schema_ROT(testDF) isa DataFrame\n end\n\n let testDF = DataFrame(; A=[1, 2, \"x\", 4], B=[5, 6, \"y\", 7], C=[\"x\", \"y\", \"z\", \"a\"])\n @test row_as_names_ROT(testDF, 3) isa DataFrame\n end\n\n let testDF = DataFrame(; A=[1, 2, \"x\", 4], B=[5, 6, \"y\", 7], C=[\"x\", \"y\", \"z\", \"a\"])\n @test rename_ROT(testDF, [:a, :b, :c]) isa DataFrame\n end\n\n let testDF = DataFrame(; A=[1, 2, \"x\", 4], B=[5, 6, \"y\", 7], C=[\"x\", \"y\", \"z\", \"a\"])\n @test drop_missing_ROT(testDF) isa DataFrame\n end\n\n let testDF = DataFrame(; A=[4, 5, 6])\n @test add_index_ROT(testDF) isa DataFrame\n end\nend"
] |
f7139c61b9baf05db45b88230b03c8047a37b777
| 2,615
|
jl
|
Julia
|
test/testProductReproducable.jl
|
dehann/iSAM.jl
|
61869753a76717b1019756d09785a784fdafe3ab
|
[
"MIT"
] | null | null | null |
test/testProductReproducable.jl
|
dehann/iSAM.jl
|
61869753a76717b1019756d09785a784fdafe3ab
|
[
"MIT"
] | null | null | null |
test/testProductReproducable.jl
|
dehann/iSAM.jl
|
61869753a76717b1019756d09785a784fdafe3ab
|
[
"MIT"
] | null | null | null |
# test for conv and product repeatability
using Test
using Statistics
using IncrementalInference
##
@testset "forward backward convolutions and products sequence" begin
fg = initfg()
addVariable!(fg, :a, ContinuousScalar)
addVariable!(fg, :b, ContinuousScalar)
addVariable!(fg, :c, ContinuousScalar)
addVariable!(fg, :d, ContinuousScalar)
addVariable!(fg, :e, ContinuousScalar)
addFactor!(fg, [:a], Prior(Normal()))
addFactor!(fg, [:a;:b], LinearRelative(Normal(10, 1)))
addFactor!(fg, [:b;:c], LinearRelative(Normal(10, 1)))
addFactor!(fg, [:c;:d], LinearRelative(Normal(10, 1)))
addFactor!(fg, [:d;:e], LinearRelative(Normal(10, 1)))
initAll!(fg)
tree = solveTree!(fg)
@test (Statistics.mean(getPoints(getBelief(fg, :a)))- 0 |> abs) < 3
@test (Statistics.mean(getPoints(getBelief(fg, :b)))-10 |> abs) < 4
@test (Statistics.mean(getPoints(getBelief(fg, :c)))-20 |> abs) < 4
@test (Statistics.mean(getPoints(getBelief(fg, :d)))-30 |> abs) < 5
@test (Statistics.mean(getPoints(getBelief(fg, :e)))-40 |> abs) < 5
@test 0.3 < Statistics.std(getPoints(getBelief(fg, :a))) < 2
@test 0.5 < Statistics.std(getPoints(getBelief(fg, :b))) < 4
@test 0.9 < Statistics.std(getPoints(getBelief(fg, :c))) < 6
@test 1.2 < Statistics.std(getPoints(getBelief(fg, :d))) < 7
@test 1.5 < Statistics.std(getPoints(getBelief(fg, :e))) < 8
# drawTree(tree, show=true)
# using RoMEPlotting
# plotKDE(fg, ls(fg))
# spyCliqMat(tree, :b)
end
@testset "Basic back and forth convolution over LinearRelative should spread" begin
fg = initfg()
addVariable!(fg, :a, ContinuousScalar)
addVariable!(fg, :b, ContinuousScalar)
addFactor!(fg, [:a;:b], LinearRelative(Normal(10, 1)), graphinit=false)
initManual!(fg, :a, randn(1,100))
initManual!(fg, :b, 10 .+randn(1,100))
A = getBelief(fg, :a)
B = getBelief(fg, :b)
# plotKDE(fg, [:a; :b])
# repeat many times to ensure the means stay put and covariances spread out
for i in 1:10
pts = approxConv(fg, :abf1, :b)
B_ = manikde!(ContinuousScalar, pts)
# plotKDE([B_; B])
initManual!(fg, :b, B_)
pts = approxConv(fg, :abf1, :a)
A_ = manikde!(ContinuousScalar, pts)
# plotKDE([A_; A])
initManual!(fg, :a, A_)
end
A_ = getBelief(fg, :a)
B_ = getBelief(fg, :b)
# plotKDE([A_; B_; A; B])
@test (Statistics.mean(getPoints(A)) |> abs) < 1
@test (Statistics.mean(getPoints(A_))|> abs) < 2
@test (Statistics.mean(getPoints(B)) -10 |> abs) < 1
@test (Statistics.mean(getPoints(B_))-10 |> abs) < 2
@test Statistics.std(getPoints(A)) < 2
@test 3 < Statistics.std(getPoints(A_))
@test Statistics.std(getPoints(B)) < 2
@test 3 < Statistics.std(getPoints(B_))
##
end
##
| 25.144231
| 83
| 0.676482
|
[
"@testset \"forward backward convolutions and products sequence\" begin\n\nfg = initfg()\n\naddVariable!(fg, :a, ContinuousScalar)\naddVariable!(fg, :b, ContinuousScalar)\naddVariable!(fg, :c, ContinuousScalar)\naddVariable!(fg, :d, ContinuousScalar)\naddVariable!(fg, :e, ContinuousScalar)\n\naddFactor!(fg, [:a], Prior(Normal()))\naddFactor!(fg, [:a;:b], LinearRelative(Normal(10, 1)))\naddFactor!(fg, [:b;:c], LinearRelative(Normal(10, 1)))\naddFactor!(fg, [:c;:d], LinearRelative(Normal(10, 1)))\naddFactor!(fg, [:d;:e], LinearRelative(Normal(10, 1)))\n\ninitAll!(fg)\n\ntree = solveTree!(fg)\n\n\n@test (Statistics.mean(getPoints(getBelief(fg, :a)))- 0 |> abs) < 3\n@test (Statistics.mean(getPoints(getBelief(fg, :b)))-10 |> abs) < 4\n@test (Statistics.mean(getPoints(getBelief(fg, :c)))-20 |> abs) < 4\n@test (Statistics.mean(getPoints(getBelief(fg, :d)))-30 |> abs) < 5\n@test (Statistics.mean(getPoints(getBelief(fg, :e)))-40 |> abs) < 5\n\n@test 0.3 < Statistics.std(getPoints(getBelief(fg, :a))) < 2\n@test 0.5 < Statistics.std(getPoints(getBelief(fg, :b))) < 4\n@test 0.9 < Statistics.std(getPoints(getBelief(fg, :c))) < 6\n@test 1.2 < Statistics.std(getPoints(getBelief(fg, :d))) < 7\n@test 1.5 < Statistics.std(getPoints(getBelief(fg, :e))) < 8\n\n\n# drawTree(tree, show=true)\n# using RoMEPlotting\n# plotKDE(fg, ls(fg))\n# spyCliqMat(tree, :b)\n\nend",
"@testset \"Basic back and forth convolution over LinearRelative should spread\" begin\n\nfg = initfg()\n\naddVariable!(fg, :a, ContinuousScalar)\naddVariable!(fg, :b, ContinuousScalar)\n\naddFactor!(fg, [:a;:b], LinearRelative(Normal(10, 1)), graphinit=false)\n\ninitManual!(fg, :a, randn(1,100))\ninitManual!(fg, :b, 10 .+randn(1,100))\n\nA = getBelief(fg, :a)\nB = getBelief(fg, :b)\n# plotKDE(fg, [:a; :b])\n\n# repeat many times to ensure the means stay put and covariances spread out\nfor i in 1:10\n pts = approxConv(fg, :abf1, :b)\n B_ = manikde!(ContinuousScalar, pts)\n # plotKDE([B_; B])\n initManual!(fg, :b, B_)\n\n pts = approxConv(fg, :abf1, :a)\n A_ = manikde!(ContinuousScalar, pts)\n # plotKDE([A_; A])\n initManual!(fg, :a, A_)\nend\n\nA_ = getBelief(fg, :a)\nB_ = getBelief(fg, :b)\n# plotKDE([A_; B_; A; B])\n\n@test (Statistics.mean(getPoints(A)) |> abs) < 1\n@test (Statistics.mean(getPoints(A_))|> abs) < 2\n\n@test (Statistics.mean(getPoints(B)) -10 |> abs) < 1\n@test (Statistics.mean(getPoints(B_))-10 |> abs) < 2\n\n@test Statistics.std(getPoints(A)) < 2\n@test 3 < Statistics.std(getPoints(A_))\n\n@test Statistics.std(getPoints(B)) < 2\n@test 3 < Statistics.std(getPoints(B_))\n\n##\n\nend"
] |
f7153aaee71132dc4b60ff01c3f91af6c17752a3
| 5,750
|
jl
|
Julia
|
test/runtests.jl
|
burmecia/OpenAIGym.jl
|
087bec95d13ca85216a0eaa7d47f50cda2867367
|
[
"MIT"
] | 86
|
2017-02-24T20:25:05.000Z
|
2022-03-31T04:50:07.000Z
|
test/runtests.jl
|
burmecia/OpenAIGym.jl
|
087bec95d13ca85216a0eaa7d47f50cda2867367
|
[
"MIT"
] | 31
|
2017-08-06T17:27:08.000Z
|
2020-08-05T16:05:07.000Z
|
test/runtests.jl
|
burmecia/OpenAIGym.jl
|
087bec95d13ca85216a0eaa7d47f50cda2867367
|
[
"MIT"
] | 30
|
2017-03-20T22:06:01.000Z
|
2021-09-24T04:38:33.000Z
|
using OpenAIGym
using PyCall
using Test
"""
`function time_steps(env::GymEnv{T}, num_eps::Int) where T`
run through num_eps eps, recording the time taken for each step and
how many steps were made. Doesn't time the `reset!` or the first step of each
episode (since higher chance that it's slower/faster than the rest, and we want
to compare the average time taken for each step as fairly as possible)
"""
function time_steps(env::GymEnv, num_eps::Int)
t = 0.0
steps = 0
for i in 1:num_eps
reset!(env)
# step!(env, rand(env.actions)) # ignore the first step - it might be slow?
t += (@elapsed steps += epstep(env))
end
steps, t
end
"""
Steps through an episode until it's `done`
assumes env has been `reset!`
"""
function epstep(env::GymEnv)
steps = 0
while true
steps += 1
r, s′ = step!(env, rand(env.actions))
finished(env, s′) && break
end
steps
end
@testset "Gym Basics" begin
pong = GymEnv(:Pong, :v4)
pongnf = GymEnv(:PongNoFrameskip, :v4)
pacman = GymEnv(:MsPacman, :v4)
pacmannf = GymEnv(:MsPacmanNoFrameskip, :v4)
cartpole = GymEnv(:CartPole)
bj = GymEnv(:Blackjack)
allenvs = [pong, pongnf, pacman, pacmannf, cartpole, bj]
eps2trial = Dict(pong=>2, pongnf=>1, pacman=>2, pacmannf=>1, cartpole=>400, bj=>30000)
atarienvs = [pong, pongnf, pacman, pacmannf]
envs = allenvs
@testset "string constructor" begin
for name ∈ ("Pong-v4", "PongNoFrameskip-v4", "MsPacman-v4",
"MsPacmanNoFrameskip-v4", "CartPole-v0", "Blackjack-v0")
env = GymEnv(name)
@test !PyCall.ispynull(env.pyenv)
end
end
@testset "envs load" begin
# check they all work - no errors == no worries
println("------------------------------ Check envs load ------------------------------")
for (i, env) in enumerate(envs)
a = rand(env.actions) |> OpenAIGym.pyaction
action_type = a |> PyObject |> pytypeof
println("env.pyenv: $(env.pyenv) action_type: $action_type (e.g. $a)")
time_steps(env, 1)
@test !ispynull(env.pyenv)
println("------------------------------")
end
end
@testset "julia speed test" begin
println("------------------------------ Begin Julia Speed Check ------------------------------")
for env in envs
num_eps = eps2trial[env]
steps, t = time_steps(env, num_eps)
println("env.pyenv: $(env.pyenv) num_eps: $num_eps t: $t steps: $steps")
println("microsecs/step (lower is better): ", t*1e6/steps)
close(env)
println("------------------------------")
end
println("------------------------------ End Julia Speed Check ------------------------------\n")
end
@testset "python speed test" begin
println("------------------------------ Begin Python Speed Check ------------------------------")
py"""
import gym
import numpy as np
pong = gym.make("Pong-v4")
pongnf = gym.make("PongNoFrameskip-v4")
pacman = gym.make("MsPacman-v4");
pacmannf = gym.make("MsPacmanNoFrameskip-v4");
cartpole = gym.make("CartPole-v0")
bj = gym.make("Blackjack-v0")
allenvs = [pong, pongnf, pacman, pacmannf, cartpole, bj]
eps2trial = {pong: 2, pongnf: 1, pacman: 2, pacmannf: 1, cartpole: 400, bj: 30000}
atarienvs = [pong, pongnf, pacman, pacmannf];
envs = allenvs
import time
class Timer(object):
elapsed = 0.0
def __init__(self, name=None):
self.name = name
def __enter__(self):
self.tstart = time.time()
def __exit__(self, type, value, traceback):
Timer.elapsed = time.time() - self.tstart
def time_steps(env, num_eps):
t = 0.0
steps = 0
for i in range(num_eps):
env.reset()
with Timer():
steps += epstep(env)
t += Timer.elapsed
return steps, t
def epstep(env):
steps = 0
while True:
steps += 1
action = env.action_space.sample()
state, reward, done, info = env.step(action)
if done == True:
break
return steps
for env in envs:
num_eps = eps2trial[env]
with Timer():
steps, s = time_steps(env, num_eps)
t = Timer.elapsed
print("{env} num_eps: {num_eps} t: {t} steps: {steps} \n"
"microsecs/step (lower is better): {time}".format(
env=env, num_eps=num_eps, t=t, steps=steps,
time=t*1e6/steps))
print("------------------------------")
"""
println("------------------------------ End Python Speed Check ------------------------------")
end # @testset "python speed test"
@testset "Base.show" begin
let
io = IOBuffer()
env = GymEnv(:MsPacman, :v4)
show(io, env)
@test String(take!(io)) == "GymEnv MsPacman-v4\n" *
" TimeLimit\n" *
" r = 0.0\n" *
" ∑r = 0.0"
end
let
io = IOBuffer()
env = GymEnv(:Blackjack)
show(io, env)
@test String(take!(io)) == "GymEnv Blackjack-v0\n" *
" r = 0.0\n" *
" ∑r = 0.0"
end
end # @testset "Base.show"
end
| 33.430233
| 105
| 0.488348
|
[
"@testset \"Gym Basics\" begin\n\n pong = GymEnv(:Pong, :v4)\n pongnf = GymEnv(:PongNoFrameskip, :v4)\n pacman = GymEnv(:MsPacman, :v4)\n pacmannf = GymEnv(:MsPacmanNoFrameskip, :v4)\n cartpole = GymEnv(:CartPole)\n bj = GymEnv(:Blackjack)\n\n allenvs = [pong, pongnf, pacman, pacmannf, cartpole, bj]\n eps2trial = Dict(pong=>2, pongnf=>1, pacman=>2, pacmannf=>1, cartpole=>400, bj=>30000)\n atarienvs = [pong, pongnf, pacman, pacmannf]\n envs = allenvs\n\n @testset \"string constructor\" begin\n for name ∈ (\"Pong-v4\", \"PongNoFrameskip-v4\", \"MsPacman-v4\",\n \"MsPacmanNoFrameskip-v4\", \"CartPole-v0\", \"Blackjack-v0\")\n env = GymEnv(name)\n @test !PyCall.ispynull(env.pyenv)\n end\n end\n\n @testset \"envs load\" begin\n # check they all work - no errors == no worries\n println(\"------------------------------ Check envs load ------------------------------\")\n for (i, env) in enumerate(envs)\n a = rand(env.actions) |> OpenAIGym.pyaction\n action_type = a |> PyObject |> pytypeof\n println(\"env.pyenv: $(env.pyenv) action_type: $action_type (e.g. $a)\")\n time_steps(env, 1)\n @test !ispynull(env.pyenv)\n println(\"------------------------------\")\n end\n end\n\n @testset \"julia speed test\" begin\n println(\"------------------------------ Begin Julia Speed Check ------------------------------\")\n for env in envs\n num_eps = eps2trial[env]\n steps, t = time_steps(env, num_eps)\n println(\"env.pyenv: $(env.pyenv) num_eps: $num_eps t: $t steps: $steps\")\n println(\"microsecs/step (lower is better): \", t*1e6/steps)\n close(env)\n println(\"------------------------------\")\n end\n println(\"------------------------------ End Julia Speed Check ------------------------------\\n\")\n end\n\n @testset \"python speed test\" begin\n println(\"------------------------------ Begin Python Speed Check ------------------------------\")\n py\"\"\"\n import gym\n import numpy as np\n\n pong = gym.make(\"Pong-v4\")\n pongnf = gym.make(\"PongNoFrameskip-v4\")\n pacman = gym.make(\"MsPacman-v4\");\n pacmannf = gym.make(\"MsPacmanNoFrameskip-v4\");\n cartpole = gym.make(\"CartPole-v0\")\n bj = gym.make(\"Blackjack-v0\")\n\n allenvs = [pong, pongnf, pacman, pacmannf, cartpole, bj]\n eps2trial = {pong: 2, pongnf: 1, pacman: 2, pacmannf: 1, cartpole: 400, bj: 30000}\n atarienvs = [pong, pongnf, pacman, pacmannf];\n\n envs = allenvs\n\n import time\n class Timer(object):\n elapsed = 0.0\n def __init__(self, name=None):\n self.name = name\n\n def __enter__(self):\n self.tstart = time.time()\n\n def __exit__(self, type, value, traceback):\n Timer.elapsed = time.time() - self.tstart\n\n def time_steps(env, num_eps):\n t = 0.0\n steps = 0\n for i in range(num_eps):\n env.reset()\n with Timer():\n steps += epstep(env)\n t += Timer.elapsed\n return steps, t\n\n def epstep(env):\n steps = 0\n while True:\n steps += 1\n action = env.action_space.sample()\n state, reward, done, info = env.step(action)\n if done == True:\n break\n return steps\n\n for env in envs:\n num_eps = eps2trial[env]\n with Timer():\n steps, s = time_steps(env, num_eps)\n t = Timer.elapsed\n print(\"{env} num_eps: {num_eps} t: {t} steps: {steps} \\n\"\n \"microsecs/step (lower is better): {time}\".format(\n env=env, num_eps=num_eps, t=t, steps=steps,\n time=t*1e6/steps))\n print(\"------------------------------\")\n \"\"\"\n println(\"------------------------------ End Python Speed Check ------------------------------\")\n end # @testset \"python speed test\"\n\n @testset \"Base.show\" begin\n let\n io = IOBuffer()\n env = GymEnv(:MsPacman, :v4)\n show(io, env)\n @test String(take!(io)) == \"GymEnv MsPacman-v4\\n\" *\n \" TimeLimit\\n\" *\n \" r = 0.0\\n\" *\n \" ∑r = 0.0\"\n end\n\n let\n io = IOBuffer()\n env = GymEnv(:Blackjack)\n show(io, env)\n @test String(take!(io)) == \"GymEnv Blackjack-v0\\n\" *\n \" r = 0.0\\n\" *\n \" ∑r = 0.0\"\n end\n end # @testset \"Base.show\"\nend"
] |
f7183b3be5ea2b30e86fc2f42f90233e708e517b
| 2,245
|
jl
|
Julia
|
test/runtests.jl
|
maarten-keijzer/AdaptiveWindow.jl
|
5bd90a475110ac5f6dd88226286455da0f8d87bf
|
[
"MIT"
] | 1
|
2022-01-04T13:50:24.000Z
|
2022-01-04T13:50:24.000Z
|
test/runtests.jl
|
maarten-keijzer/AdaptiveWindow.jl
|
5bd90a475110ac5f6dd88226286455da0f8d87bf
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
maarten-keijzer/AdaptiveWindow.jl
|
5bd90a475110ac5f6dd88226286455da0f8d87bf
|
[
"MIT"
] | null | null | null |
using AdaptiveWindows
using Test
@testset verbose=true "Adaptive Mean" begin
@testset "Mean Computation " begin
m = AdaptiveMean(δ = 1e-9)
r = randn(1000)
fit!(m, r)
m1 = sum(r) / length(r)
m2 = value(m)
@test m1 ≈ m2
ad = AdaptiveMean()
# This should not trigger a truncated window
fit!(ad, randn(10_000))
@test stats(ad).n == 10_000
# Changing the distribution should trigger a truncated window
fit!(ad, 1 .+ randn(10_000))
@test 9_900 < stats(ad).n < 20_000
# check truncation of shifting using the callback function
shifted = false
m = AdaptiveMean(onshiftdetected = ad -> shifted = true)
for i in 1:1_000
r = randn()
if i > 500
r += 1
end
fit!(m, r)
end
@test shifted
end
function consistent(ad)
total = sum(nobs(v) for v in ad.window)
total == nobs(ad.stats)
end
@testset "Memory Management" begin
m = AdaptiveMean()
fit!(m, 1)
@test nobs(m.window[1]) == 0
@test nobs(m.window[2]) == 1
@test nobs(m.window[3]) == 0
fit!(m, 1)
@test nobs(m.window[1]) == 0
@test nobs(m.window[2]) == 1
@test nobs(m.window[3]) == 1
fit!(m, 1)
fit!(m, 1)
fit!(m, 1)
fit!(m, 1)
fit!(m, 1)
@test consistent(m)
m = AdaptiveMean()
n = AdaptiveWindows.M * ( 1 + 2 + 4)
fit!(m, ones(n))
@test length(m.window) <= AdaptiveWindows.M * log2(n)
@test nobs(m) == n
@test consistent(m)
mn = AdaptiveMean()
n = 1<<12
# withoutdropping for speed
fit!(withoutdropping(mn), ones(n))
m = AdaptiveWindows.M
expected = m * ceil(log2(n) - log2(m))
@test length(mn.window) == expected
@test nobs(mn) == n
@test consistent(mn)
# Maximum amount of memory
mn = withmaxlength(AdaptiveMean(), 3)
fit!(mn, rand(10000))
@test length(mn.ad.window) == AdaptiveWindows.M * 3
@test consistent(mn.ad)
end
end
| 23.385417
| 69
| 0.50245
|
[
"@testset verbose=true \"Adaptive Mean\" begin\n\n @testset \"Mean Computation \" begin\n m = AdaptiveMean(δ = 1e-9)\n\n r = randn(1000)\n\n fit!(m, r)\n\n m1 = sum(r) / length(r)\n m2 = value(m)\n\n @test m1 ≈ m2\n ad = AdaptiveMean()\n\n # This should not trigger a truncated window\n fit!(ad, randn(10_000))\n @test stats(ad).n == 10_000\n\n # Changing the distribution should trigger a truncated window\n fit!(ad, 1 .+ randn(10_000))\n @test 9_900 < stats(ad).n < 20_000\n\n # check truncation of shifting using the callback function\n shifted = false\n\n m = AdaptiveMean(onshiftdetected = ad -> shifted = true)\n\n for i in 1:1_000\n r = randn()\n if i > 500\n r += 1\n end\n fit!(m, r)\n end\n\n @test shifted\n end\n\n function consistent(ad)\n total = sum(nobs(v) for v in ad.window)\n total == nobs(ad.stats)\n end\n\n @testset \"Memory Management\" begin\n\n m = AdaptiveMean()\n fit!(m, 1)\n @test nobs(m.window[1]) == 0\n @test nobs(m.window[2]) == 1\n @test nobs(m.window[3]) == 0\n fit!(m, 1)\n @test nobs(m.window[1]) == 0\n @test nobs(m.window[2]) == 1\n @test nobs(m.window[3]) == 1\n fit!(m, 1)\n fit!(m, 1)\n fit!(m, 1)\n fit!(m, 1)\n fit!(m, 1)\n @test consistent(m)\n \n m = AdaptiveMean()\n n = AdaptiveWindows.M * ( 1 + 2 + 4)\n fit!(m, ones(n))\n\n @test length(m.window) <= AdaptiveWindows.M * log2(n)\n @test nobs(m) == n \n @test consistent(m)\n\n mn = AdaptiveMean()\n n = 1<<12\n\n # withoutdropping for speed\n fit!(withoutdropping(mn), ones(n))\n m = AdaptiveWindows.M \n expected = m * ceil(log2(n) - log2(m))\n @test length(mn.window) == expected\n @test nobs(mn) == n \n @test consistent(mn)\n \n # Maximum amount of memory\n mn = withmaxlength(AdaptiveMean(), 3)\n fit!(mn, rand(10000))\n @test length(mn.ad.window) == AdaptiveWindows.M * 3\n @test consistent(mn.ad)\n \n\n end\nend"
] |
f71fdd500cffb77f7512f74f826a1a508b234e8f
| 34,448
|
jl
|
Julia
|
test/runtests.jl
|
bkamins/Statistics.jl
|
81a1cdd6c2105d3e50f76375630bbed4744e67c1
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
bkamins/Statistics.jl
|
81a1cdd6c2105d3e50f76375630bbed4744e67c1
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
bkamins/Statistics.jl
|
81a1cdd6c2105d3e50f76375630bbed4744e67c1
|
[
"MIT"
] | null | null | null |
# This file is a part of Julia. License is MIT: https://julialang.org/license
using Statistics, Test, Random, LinearAlgebra, SparseArrays
using Test: guardseed
Random.seed!(123)
@testset "middle" begin
@test middle(3) === 3.0
@test middle(2, 3) === 2.5
let x = ((floatmax(1.0)/4)*3)
@test middle(x, x) === x
end
@test middle(1:8) === 4.5
@test middle([1:8;]) === 4.5
# ensure type-correctness
for T in [Bool,Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128,Float16,Float32,Float64]
@test middle(one(T)) === middle(one(T), one(T))
end
end
@testset "median" begin
@test median([1.]) === 1.
@test median([1.,3]) === 2.
@test median([1.,3,2]) === 2.
@test median([1,3,2]) === 2.0
@test median([1,3,2,4]) === 2.5
@test median([0.0,Inf]) == Inf
@test median([0.0,-Inf]) == -Inf
@test median([0.,Inf,-Inf]) == 0.0
@test median([1.,-1.,Inf,-Inf]) == 0.0
@test isnan(median([-Inf,Inf]))
X = [2 3 1 -1; 7 4 5 -4]
@test all(median(X, dims=2) .== [1.5, 4.5])
@test all(median(X, dims=1) .== [4.5 3.5 3.0 -2.5])
@test X == [2 3 1 -1; 7 4 5 -4] # issue #17153
@test_throws ArgumentError median([])
@test isnan(median([NaN]))
@test isnan(median([0.0,NaN]))
@test isnan(median([NaN,0.0]))
@test isnan(median([NaN,0.0,1.0]))
@test isnan(median(Any[NaN,0.0,1.0]))
@test isequal(median([NaN 0.0; 1.2 4.5], dims=2), reshape([NaN; 2.85], 2, 1))
@test ismissing(median([1, missing]))
@test ismissing(median([1, 2, missing]))
@test ismissing(median([NaN, 2.0, missing]))
@test ismissing(median([NaN, missing]))
@test ismissing(median([missing, NaN]))
@test ismissing(median(Any[missing, 2.0, 3.0, 4.0, NaN]))
@test median(skipmissing([1, missing, 2])) === 1.5
@test median!([1 2 3 4]) == 2.5
@test median!([1 2; 3 4]) == 2.5
@test invoke(median, Tuple{AbstractVector}, 1:10) == median(1:10) == 5.5
@test @inferred(median(Float16[1, 2, NaN])) === Float16(NaN)
@test @inferred(median(Float16[1, 2, 3])) === Float16(2)
@test @inferred(median(Float32[1, 2, NaN])) === NaN32
@test @inferred(median(Float32[1, 2, 3])) === 2.0f0
end
@testset "mean" begin
@test mean((1,2,3)) === 2.
@test mean([0]) === 0.
@test mean([1.]) === 1.
@test mean([1.,3]) == 2.
@test mean([1,2,3]) == 2.
@test mean([0 1 2; 4 5 6], dims=1) == [2. 3. 4.]
@test mean([1 2 3; 4 5 6], dims=1) == [2.5 3.5 4.5]
@test mean(-, [1 2 3 ; 4 5 6], dims=1) == [-2.5 -3.5 -4.5]
@test mean(-, [1 2 3 ; 4 5 6], dims=2) == transpose([-2.0 -5.0])
@test mean(-, [1 2 3 ; 4 5 6], dims=(1, 2)) == -3.5 .* ones(1, 1)
@test mean(-, [1 2 3 ; 4 5 6], dims=(1, 1)) == [-2.5 -3.5 -4.5]
@test mean(-, [1 2 3 ; 4 5 6], dims=()) == Float64[-1 -2 -3 ; -4 -5 -6]
@test mean(i->i+1, 0:2) === 2.
@test mean(isodd, [3]) === 1.
@test mean(x->3x, (1,1)) === 3.
# mean of iterables:
n = 10; a = randn(n); b = randn(n)
@test mean(Tuple(a)) ≈ mean(a)
@test mean(Tuple(a + b*im)) ≈ mean(a + b*im)
@test mean(cos, Tuple(a)) ≈ mean(cos, a)
@test mean(x->x/2, a + b*im) ≈ mean(a + b*im) / 2.
@test ismissing(mean(Tuple((1, 2, missing, 4, 5))))
@test isnan(mean([NaN]))
@test isnan(mean([0.0,NaN]))
@test isnan(mean([NaN,0.0]))
@test isnan(mean([0.,Inf,-Inf]))
@test isnan(mean([1.,-1.,Inf,-Inf]))
@test isnan(mean([-Inf,Inf]))
@test isequal(mean([NaN 0.0; 1.2 4.5], dims=2), reshape([NaN; 2.85], 2, 1))
@test ismissing(mean([1, missing]))
@test ismissing(mean([NaN, missing]))
@test ismissing(mean([missing, NaN]))
@test isequal(mean([missing 1.0; 2.0 3.0], dims=1), [missing 2.0])
@test mean(skipmissing([1, missing, 2])) === 1.5
@test isequal(mean(Complex{Float64}[]), NaN+NaN*im)
@test mean(Complex{Float64}[]) isa Complex{Float64}
@test isequal(mean(skipmissing(Complex{Float64}[])), NaN+NaN*im)
@test mean(skipmissing(Complex{Float64}[])) isa Complex{Float64}
@test isequal(mean(abs, Complex{Float64}[]), NaN)
@test mean(abs, Complex{Float64}[]) isa Float64
@test isequal(mean(abs, skipmissing(Complex{Float64}[])), NaN)
@test mean(abs, skipmissing(Complex{Float64}[])) isa Float64
@test isequal(mean(Int[]), NaN)
@test mean(Int[]) isa Float64
@test isequal(mean(skipmissing(Int[])), NaN)
@test mean(skipmissing(Int[])) isa Float64
@test_throws MethodError mean([])
@test_throws MethodError mean(skipmissing([]))
@test_throws ArgumentError mean((1 for i in 2:1))
if VERSION >= v"1.6.0-DEV.83"
@test_throws ArgumentError mean(())
@test_throws ArgumentError mean(Union{}[])
end
# Check that small types are accumulated using wider type
for T in (Int8, UInt8)
x = [typemax(T) typemax(T)]
g = (v for v in x)
@test mean(x) == mean(g) == typemax(T)
@test mean(identity, x) == mean(identity, g) == typemax(T)
@test mean(x, dims=2) == [typemax(T)]'
end
# Check that mean avoids integer overflow (#22)
let x = fill(typemax(Int), 10), a = tuple(x...)
@test (mean(x) == mean(x, dims=1)[] == mean(float, x)
== mean(a) == mean(v for v in x) == mean(v for v in a)
≈ float(typemax(Int)))
end
let x = rand(10000) # mean should use sum's accurate pairwise algorithm
@test mean(x) == sum(x) / length(x)
end
@test mean(Number[1, 1.5, 2+3im]) === 1.5+1im # mixed-type array
@test mean(v for v in Number[1, 1.5, 2+3im]) === 1.5+1im
@test (@inferred mean(Int[])) === 0/0
@test (@inferred mean(Float32[])) === 0.f0/0
@test (@inferred mean(Float64[])) === 0/0
@test (@inferred mean(Iterators.filter(x -> true, Int[]))) === 0/0
@test (@inferred mean(Iterators.filter(x -> true, Float32[]))) === 0.f0/0
@test (@inferred mean(Iterators.filter(x -> true, Float64[]))) === 0/0
end
@testset "mean/median for ranges" begin
for f in (mean, median)
for n = 2:5
@test f(2:n) == f([2:n;])
@test f(2:0.1:n) ≈ f([2:0.1:n;])
end
end
@test mean(2:1) === NaN
@test mean(big(2):1) isa BigFloat
end
@testset "var & std" begin
# edge case: empty vector
# iterable; this has to throw for type stability
@test_throws MethodError var(())
@test_throws MethodError var((); corrected=false)
@test_throws MethodError var((); mean=2)
@test_throws MethodError var((); mean=2, corrected=false)
# reduction
@test isnan(var(Int[]))
@test isnan(var(Int[]; corrected=false))
@test isnan(var(Int[]; mean=2))
@test isnan(var(Int[]; mean=2, corrected=false))
# reduction across dimensions
@test isequal(var(Int[], dims=1), [NaN])
@test isequal(var(Int[], dims=1; corrected=false), [NaN])
@test isequal(var(Int[], dims=1; mean=[2]), [NaN])
@test isequal(var(Int[], dims=1; mean=[2], corrected=false), [NaN])
# edge case: one-element vector
# iterable
@test isnan(@inferred(var((1,))))
@test var((1,); corrected=false) === 0.0
@test var((1,); mean=2) === Inf
@test var((1,); mean=2, corrected=false) === 1.0
# reduction
@test isnan(@inferred(var([1])))
@test var([1]; corrected=false) === 0.0
@test var([1]; mean=2) === Inf
@test var([1]; mean=2, corrected=false) === 1.0
# reduction across dimensions
@test isequal(@inferred(var([1], dims=1)), [NaN])
@test var([1], dims=1; corrected=false) ≈ [0.0]
@test var([1], dims=1; mean=[2]) ≈ [Inf]
@test var([1], dims=1; mean=[2], corrected=false) ≈ [1.0]
@test var(1:8) == 6.
@test varm(1:8,1) == varm(Vector(1:8),1)
@test isnan(varm(1:1,1))
@test isnan(var(1:1))
@test isnan(var(1:-1))
@test @inferred(var(1.0:8.0)) == 6.
@test varm(1.0:8.0,1.0) == varm(Vector(1.0:8.0),1)
@test isnan(varm(1.0:1.0,1.0))
@test isnan(var(1.0:1.0))
@test isnan(var(1.0:-1.0))
@test @inferred(var(1.0f0:8.0f0)) === 6.f0
@test varm(1.0f0:8.0f0,1.0f0) == varm(Vector(1.0f0:8.0f0),1)
@test isnan(varm(1.0f0:1.0f0,1.0f0))
@test isnan(var(1.0f0:1.0f0))
@test isnan(var(1.0f0:-1.0f0))
@test varm([1,2,3], 2) ≈ 1.
@test var([1,2,3]) ≈ 1.
@test var([1,2,3]; corrected=false) ≈ 2.0/3
@test var([1,2,3]; mean=0) ≈ 7.
@test var([1,2,3]; mean=0, corrected=false) ≈ 14.0/3
@test varm((1,2,3), 2) ≈ 1.
@test var((1,2,3)) ≈ 1.
@test var((1,2,3); corrected=false) ≈ 2.0/3
@test var((1,2,3); mean=0) ≈ 7.
@test var((1,2,3); mean=0, corrected=false) ≈ 14.0/3
@test_throws ArgumentError var((1,2,3); mean=())
@test var([1 2 3 4 5; 6 7 8 9 10], dims=2) ≈ [2.5 2.5]'
@test var([1 2 3 4 5; 6 7 8 9 10], dims=2; corrected=false) ≈ [2.0 2.0]'
@test var(collect(1:99), dims=1) ≈ [825]
@test var(Matrix(transpose(collect(1:99))), dims=2) ≈ [825]
@test stdm([1,2,3], 2) ≈ 1.
@test std([1,2,3]) ≈ 1.
@test std([1,2,3]; corrected=false) ≈ sqrt(2.0/3)
@test std([1,2,3]; mean=0) ≈ sqrt(7.0)
@test std([1,2,3]; mean=0, corrected=false) ≈ sqrt(14.0/3)
@test stdm([1.0,2,3], 2) ≈ 1.
@test std([1.0,2,3]) ≈ 1.
@test std([1.0,2,3]; corrected=false) ≈ sqrt(2.0/3)
@test std([1.0,2,3]; mean=0) ≈ sqrt(7.0)
@test std([1.0,2,3]; mean=0, corrected=false) ≈ sqrt(14.0/3)
@test std([1.0,2,3]; dims=1)[] ≈ 1.
@test std([1.0,2,3]; dims=1, corrected=false)[] ≈ sqrt(2.0/3)
@test std([1.0,2,3]; dims=1, mean=[0])[] ≈ sqrt(7.0)
@test std([1.0,2,3]; dims=1, mean=[0], corrected=false)[] ≈ sqrt(14.0/3)
@test stdm((1,2,3), 2) ≈ 1.
@test std((1,2,3)) ≈ 1.
@test std((1,2,3); corrected=false) ≈ sqrt(2.0/3)
@test std((1,2,3); mean=0) ≈ sqrt(7.0)
@test std((1,2,3); mean=0, corrected=false) ≈ sqrt(14.0/3)
@test std([1 2 3 4 5; 6 7 8 9 10], dims=2) ≈ sqrt.([2.5 2.5]')
@test std([1 2 3 4 5; 6 7 8 9 10], dims=2; corrected=false) ≈ sqrt.([2.0 2.0]')
let A = ComplexF64[exp(i*im) for i in 1:10^4]
@test varm(A, 0.) ≈ sum(map(abs2, A)) / (length(A) - 1)
@test varm(A, mean(A)) ≈ var(A)
end
@test var([1//1, 2//1]) isa Rational{Int}
@test var([1//1, 2//1], dims=1) isa Vector{Rational{Int}}
@test std([1//1, 2//1]) isa Float64
@test std([1//1, 2//1], dims=1) isa Vector{Float64}
@testset "var: empty cases" begin
A = Matrix{Int}(undef, 0,1)
@test var(A) === NaN
@test isequal(var(A, dims=1), fill(NaN, 1, 1))
@test isequal(var(A, dims=2), fill(NaN, 0, 1))
@test isequal(var(A, dims=(1, 2)), fill(NaN, 1, 1))
@test isequal(var(A, dims=3), fill(NaN, 0, 1))
end
# issue #6672
@test std(AbstractFloat[1,2,3], dims=1) == [1.0]
for f in (var, std)
@test ismissing(f([1, missing]))
@test ismissing(f([NaN, missing]))
@test ismissing(f([missing, NaN]))
@test isequal(f([missing 1.0; 2.0 3.0], dims=1), [missing f([1.0, 3.0])])
@test f(skipmissing([1, missing, 2])) === f([1, 2])
end
for f in (varm, stdm)
@test ismissing(f([1, missing], 0))
@test ismissing(f([1, 2], missing))
@test ismissing(f([1, NaN], missing))
@test ismissing(f([NaN, missing], 0))
@test ismissing(f([missing, NaN], 0))
@test ismissing(f([NaN, missing], missing))
@test ismissing(f([missing, NaN], missing))
@test f(skipmissing([1, missing, 2]), 0) === f([1, 2], 0)
end
@test isequal(var(Complex{Float64}[]), NaN)
@test var(Complex{Float64}[]) isa Float64
@test isequal(var(skipmissing(Complex{Float64}[])), NaN)
@test var(skipmissing(Complex{Float64}[])) isa Float64
@test_throws MethodError var([])
@test_throws MethodError var(skipmissing([]))
@test_throws MethodError var((1 for i in 2:1))
@test isequal(var(Int[]), NaN)
@test var(Int[]) isa Float64
@test isequal(var(skipmissing(Int[])), NaN)
@test var(skipmissing(Int[])) isa Float64
# over dimensions with provided means
for x in ([1 2 3; 4 5 6], sparse([1 2 3; 4 5 6]))
@test var(x, dims=1, mean=mean(x, dims=1)) == var(x, dims=1)
@test var(x, dims=1, mean=reshape(mean(x, dims=1), 1, :, 1)) == var(x, dims=1)
@test var(x, dims=2, mean=mean(x, dims=2)) == var(x, dims=2)
@test var(x, dims=2, mean=reshape(mean(x, dims=2), :)) == var(x, dims=2)
@test var(x, dims=2, mean=reshape(mean(x, dims=2), :, 1, 1)) == var(x, dims=2)
@test_throws DimensionMismatch var(x, dims=1, mean=ones(size(x, 1)))
@test_throws DimensionMismatch var(x, dims=1, mean=ones(size(x, 1), 1))
@test_throws DimensionMismatch var(x, dims=2, mean=ones(1, size(x, 2)))
@test_throws DimensionMismatch var(x, dims=1, mean=ones(1, 1, size(x, 2)))
@test_throws DimensionMismatch var(x, dims=2, mean=ones(1, size(x, 2), 1))
@test_throws DimensionMismatch var(x, dims=2, mean=ones(size(x, 1), 1, 5))
@test_throws DimensionMismatch var(x, dims=1, mean=ones(1, size(x, 2), 5))
end
end
function safe_cov(x, y, zm::Bool, cr::Bool)
n = length(x)
if !zm
x = x .- mean(x)
y = y .- mean(y)
end
dot(vec(x), vec(y)) / (n - Int(cr))
end
X = [1.0 5.0;
2.0 4.0;
3.0 6.0;
4.0 2.0;
5.0 1.0]
Y = [6.0 2.0;
1.0 7.0;
5.0 8.0;
3.0 4.0;
2.0 3.0]
@testset "covariance" begin
for vd in [1, 2], zm in [true, false], cr in [true, false]
# println("vd = $vd: zm = $zm, cr = $cr")
if vd == 1
k = size(X, 2)
Cxx = zeros(k, k)
Cxy = zeros(k, k)
for i = 1:k, j = 1:k
Cxx[i,j] = safe_cov(X[:,i], X[:,j], zm, cr)
Cxy[i,j] = safe_cov(X[:,i], Y[:,j], zm, cr)
end
x1 = vec(X[:,1])
y1 = vec(Y[:,1])
else
k = size(X, 1)
Cxx = zeros(k, k)
Cxy = zeros(k, k)
for i = 1:k, j = 1:k
Cxx[i,j] = safe_cov(X[i,:], X[j,:], zm, cr)
Cxy[i,j] = safe_cov(X[i,:], Y[j,:], zm, cr)
end
x1 = vec(X[1,:])
y1 = vec(Y[1,:])
end
c = zm ? Statistics.covm(x1, 0, corrected=cr) :
cov(x1, corrected=cr)
@test isa(c, Float64)
@test c ≈ Cxx[1,1]
@inferred cov(x1, corrected=cr)
@test cov(X) == Statistics.covm(X, mean(X, dims=1))
C = zm ? Statistics.covm(X, 0, vd, corrected=cr) :
cov(X, dims=vd, corrected=cr)
@test size(C) == (k, k)
@test C ≈ Cxx
@inferred cov(X, dims=vd, corrected=cr)
@test cov(x1, y1) == Statistics.covm(x1, mean(x1), y1, mean(y1))
c = zm ? Statistics.covm(x1, 0, y1, 0, corrected=cr) :
cov(x1, y1, corrected=cr)
@test isa(c, Float64)
@test c ≈ Cxy[1,1]
@inferred cov(x1, y1, corrected=cr)
if vd == 1
@test cov(x1, Y) == Statistics.covm(x1, mean(x1), Y, mean(Y, dims=1))
end
C = zm ? Statistics.covm(x1, 0, Y, 0, vd, corrected=cr) :
cov(x1, Y, dims=vd, corrected=cr)
@test size(C) == (1, k)
@test vec(C) ≈ Cxy[1,:]
@inferred cov(x1, Y, dims=vd, corrected=cr)
if vd == 1
@test cov(X, y1) == Statistics.covm(X, mean(X, dims=1), y1, mean(y1))
end
C = zm ? Statistics.covm(X, 0, y1, 0, vd, corrected=cr) :
cov(X, y1, dims=vd, corrected=cr)
@test size(C) == (k, 1)
@test vec(C) ≈ Cxy[:,1]
@inferred cov(X, y1, dims=vd, corrected=cr)
@test cov(X, Y) == Statistics.covm(X, mean(X, dims=1), Y, mean(Y, dims=1))
C = zm ? Statistics.covm(X, 0, Y, 0, vd, corrected=cr) :
cov(X, Y, dims=vd, corrected=cr)
@test size(C) == (k, k)
@test C ≈ Cxy
@inferred cov(X, Y, dims=vd, corrected=cr)
end
@testset "floating point accuracy for `cov` of large numbers" begin
A = [4.0, 7.0, 13.0, 16.0]
C = A .+ 1.0e10
@test cov(A, A) ≈ cov(C, C)
end
end
function safe_cor(x, y, zm::Bool)
if !zm
x = x .- mean(x)
y = y .- mean(y)
end
x = vec(x)
y = vec(y)
dot(x, y) / (sqrt(dot(x, x)) * sqrt(dot(y, y)))
end
@testset "correlation" begin
for vd in [1, 2], zm in [true, false]
# println("vd = $vd: zm = $zm")
if vd == 1
k = size(X, 2)
Cxx = zeros(k, k)
Cxy = zeros(k, k)
for i = 1:k, j = 1:k
Cxx[i,j] = safe_cor(X[:,i], X[:,j], zm)
Cxy[i,j] = safe_cor(X[:,i], Y[:,j], zm)
end
x1 = vec(X[:,1])
y1 = vec(Y[:,1])
else
k = size(X, 1)
Cxx = zeros(k, k)
Cxy = zeros(k, k)
for i = 1:k, j = 1:k
Cxx[i,j] = safe_cor(X[i,:], X[j,:], zm)
Cxy[i,j] = safe_cor(X[i,:], Y[j,:], zm)
end
x1 = vec(X[1,:])
y1 = vec(Y[1,:])
end
c = zm ? Statistics.corm(x1, 0) : cor(x1)
@test isa(c, Float64)
@test c ≈ Cxx[1,1]
@inferred cor(x1)
@test cor(X) == Statistics.corm(X, mean(X, dims=1))
C = zm ? Statistics.corm(X, 0, vd) : cor(X, dims=vd)
@test size(C) == (k, k)
@test C ≈ Cxx
@inferred cor(X, dims=vd)
@test cor(x1, y1) == Statistics.corm(x1, mean(x1), y1, mean(y1))
c = zm ? Statistics.corm(x1, 0, y1, 0) : cor(x1, y1)
@test isa(c, Float64)
@test c ≈ Cxy[1,1]
@inferred cor(x1, y1)
if vd == 1
@test cor(x1, Y) == Statistics.corm(x1, mean(x1), Y, mean(Y, dims=1))
end
C = zm ? Statistics.corm(x1, 0, Y, 0, vd) : cor(x1, Y, dims=vd)
@test size(C) == (1, k)
@test vec(C) ≈ Cxy[1,:]
@inferred cor(x1, Y, dims=vd)
if vd == 1
@test cor(X, y1) == Statistics.corm(X, mean(X, dims=1), y1, mean(y1))
end
C = zm ? Statistics.corm(X, 0, y1, 0, vd) : cor(X, y1, dims=vd)
@test size(C) == (k, 1)
@test vec(C) ≈ Cxy[:,1]
@inferred cor(X, y1, dims=vd)
@test cor(X, Y) == Statistics.corm(X, mean(X, dims=1), Y, mean(Y, dims=1))
C = zm ? Statistics.corm(X, 0, Y, 0, vd) : cor(X, Y, dims=vd)
@test size(C) == (k, k)
@test C ≈ Cxy
@inferred cor(X, Y, dims=vd)
end
@test cor(repeat(1:17, 1, 17))[2] <= 1.0
@test cor(1:17, 1:17) <= 1.0
@test cor(1:17, 18:34) <= 1.0
@test cor(Any[1, 2], Any[1, 2]) == 1.0
@test isnan(cor([0], Int8[81]))
let tmp = range(1, stop=85, length=100)
tmp2 = Vector(tmp)
@test cor(tmp, tmp) <= 1.0
@test cor(tmp, tmp2) <= 1.0
end
end
@testset "quantile" begin
@test quantile([1,2,3,4],0.5) ≈ 2.5
@test quantile([1,2,3,4],[0.5]) ≈ [2.5]
@test quantile([1., 3],[.25,.5,.75])[2] ≈ median([1., 3])
@test quantile(100.0:-1.0:0.0, 0.0:0.1:1.0) ≈ 0.0:10.0:100.0
@test quantile(0.0:100.0, 0.0:0.1:1.0, sorted=true) ≈ 0.0:10.0:100.0
@test quantile(100f0:-1f0:0.0, 0.0:0.1:1.0) ≈ 0f0:10f0:100f0
@test quantile([Inf,Inf],0.5) == Inf
@test quantile([-Inf,1],0.5) == -Inf
# here it is required to introduce an absolute tolerance because the calculated value is 0
@test quantile([0,1],1e-18) ≈ 1e-18 atol=1e-18
@test quantile([1, 2, 3, 4],[]) == []
@test quantile([1, 2, 3, 4], (0.5,)) == (2.5,)
@test quantile([4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11],
(0.1, 0.2, 0.4, 0.9)) == (2.0, 3.0, 5.0, 11.0)
@test quantile(Union{Int, Missing}[4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11],
[0.1, 0.2, 0.4, 0.9]) ≈ [2.0, 3.0, 5.0, 11.0]
@test quantile(Any[4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11],
[0.1, 0.2, 0.4, 0.9]) ≈ [2.0, 3.0, 5.0, 11.0]
@test quantile([4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11],
Any[0.1, 0.2, 0.4, 0.9]) ≈ [2.0, 3.0, 5.0, 11.0]
@test quantile([4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11],
Any[0.1, 0.2, 0.4, 0.9]) isa Vector{Float64}
@test quantile(Any[4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11],
Any[0.1, 0.2, 0.4, 0.9]) ≈ [2, 3, 5, 11]
@test quantile(Any[4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11],
Any[0.1, 0.2, 0.4, 0.9]) isa Vector{Float64}
@test quantile([1, 2, 3, 4], ()) == ()
@test isempty(quantile([1, 2, 3, 4], Float64[]))
@test quantile([1, 2, 3, 4], Float64[]) isa Vector{Float64}
@test quantile([1, 2, 3, 4], []) isa Vector{Any}
@test quantile([1, 2, 3, 4], [0, 1]) isa Vector{Int}
@test quantile(Any[1, 2, 3], 0.5) isa Float64
@test quantile(Any[1, big(2), 3], 0.5) isa BigFloat
@test quantile(Any[1, 2, 3], Float16(0.5)) isa Float16
@test quantile(Any[1, Float16(2), 3], Float16(0.5)) isa Float16
@test quantile(Any[1, big(2), 3], Float16(0.5)) isa BigFloat
@test_throws ArgumentError quantile([1, missing], 0.5)
@test_throws ArgumentError quantile([1, NaN], 0.5)
@test quantile(skipmissing([1, missing, 2]), 0.5) === 1.5
# make sure that type inference works correctly in normal cases
for T in [Int, BigInt, Float64, Float16, BigFloat, Rational{Int}, Rational{BigInt}]
for S in [Float64, Float16, BigFloat, Rational{Int}, Rational{BigInt}]
@inferred quantile(T[1, 2, 3], S(0.5))
@inferred quantile(T[1, 2, 3], S(0.6))
@inferred quantile(T[1, 2, 3], S[0.5, 0.6])
@inferred quantile(T[1, 2, 3], (S(0.5), S(0.6)))
end
end
x = [3; 2; 1]
y = zeros(3)
@test quantile!(y, x, [0.1, 0.5, 0.9]) === y
@test y ≈ [1.2, 2.0, 2.8]
#tests for quantile calculation with configurable alpha and beta parameters
v = [2, 3, 4, 6, 9, 2, 6, 2, 21, 17]
# tests against scipy.stats.mstats.mquantiles method
@test quantile(v, 0.0, alpha=0.0, beta=0.0) ≈ 2.0
@test quantile(v, 0.2, alpha=1.0, beta=1.0) ≈ 2.0
@test quantile(v, 0.4, alpha=0.0, beta=0.0) ≈ 3.4
@test quantile(v, 0.4, alpha=0.0, beta=0.2) ≈ 3.32
@test quantile(v, 0.4, alpha=0.0, beta=0.4) ≈ 3.24
@test quantile(v, 0.4, alpha=0.0, beta=0.6) ≈ 3.16
@test quantile(v, 0.4, alpha=0.0, beta=0.8) ≈ 3.08
@test quantile(v, 0.4, alpha=0.0, beta=1.0) ≈ 3.0
@test quantile(v, 0.4, alpha=0.2, beta=0.0) ≈ 3.52
@test quantile(v, 0.4, alpha=0.2, beta=0.2) ≈ 3.44
@test quantile(v, 0.4, alpha=0.2, beta=0.4) ≈ 3.36
@test quantile(v, 0.4, alpha=0.2, beta=0.6) ≈ 3.28
@test quantile(v, 0.4, alpha=0.2, beta=0.8) ≈ 3.2
@test quantile(v, 0.4, alpha=0.2, beta=1.0) ≈ 3.12
@test quantile(v, 0.4, alpha=0.4, beta=0.0) ≈ 3.64
@test quantile(v, 0.4, alpha=0.4, beta=0.2) ≈ 3.56
@test quantile(v, 0.4, alpha=0.4, beta=0.4) ≈ 3.48
@test quantile(v, 0.4, alpha=0.4, beta=0.6) ≈ 3.4
@test quantile(v, 0.4, alpha=0.4, beta=0.8) ≈ 3.32
@test quantile(v, 0.4, alpha=0.4, beta=1.0) ≈ 3.24
@test quantile(v, 0.4, alpha=0.6, beta=0.0) ≈ 3.76
@test quantile(v, 0.4, alpha=0.6, beta=0.2) ≈ 3.68
@test quantile(v, 0.4, alpha=0.6, beta=0.4) ≈ 3.6
@test quantile(v, 0.4, alpha=0.6, beta=0.6) ≈ 3.52
@test quantile(v, 0.4, alpha=0.6, beta=0.8) ≈ 3.44
@test quantile(v, 0.4, alpha=0.6, beta=1.0) ≈ 3.36
@test quantile(v, 0.4, alpha=0.8, beta=0.0) ≈ 3.88
@test quantile(v, 0.4, alpha=0.8, beta=0.2) ≈ 3.8
@test quantile(v, 0.4, alpha=0.8, beta=0.4) ≈ 3.72
@test quantile(v, 0.4, alpha=0.8, beta=0.6) ≈ 3.64
@test quantile(v, 0.4, alpha=0.8, beta=0.8) ≈ 3.56
@test quantile(v, 0.4, alpha=0.8, beta=1.0) ≈ 3.48
@test quantile(v, 0.4, alpha=1.0, beta=0.0) ≈ 4.0
@test quantile(v, 0.4, alpha=1.0, beta=0.2) ≈ 3.92
@test quantile(v, 0.4, alpha=1.0, beta=0.4) ≈ 3.84
@test quantile(v, 0.4, alpha=1.0, beta=0.6) ≈ 3.76
@test quantile(v, 0.4, alpha=1.0, beta=0.8) ≈ 3.68
@test quantile(v, 0.4, alpha=1.0, beta=1.0) ≈ 3.6
@test quantile(v, 0.6, alpha=0.0, beta=0.0) ≈ 6.0
@test quantile(v, 0.6, alpha=1.0, beta=1.0) ≈ 6.0
@test quantile(v, 0.8, alpha=0.0, beta=0.0) ≈ 15.4
@test quantile(v, 0.8, alpha=0.0, beta=0.2) ≈ 14.12
@test quantile(v, 0.8, alpha=0.0, beta=0.4) ≈ 12.84
@test quantile(v, 0.8, alpha=0.0, beta=0.6) ≈ 11.56
@test quantile(v, 0.8, alpha=0.0, beta=0.8) ≈ 10.28
@test quantile(v, 0.8, alpha=0.0, beta=1.0) ≈ 9.0
@test quantile(v, 0.8, alpha=0.2, beta=0.0) ≈ 15.72
@test quantile(v, 0.8, alpha=0.2, beta=0.2) ≈ 14.44
@test quantile(v, 0.8, alpha=0.2, beta=0.4) ≈ 13.16
@test quantile(v, 0.8, alpha=0.2, beta=0.6) ≈ 11.88
@test quantile(v, 0.8, alpha=0.2, beta=0.8) ≈ 10.6
@test quantile(v, 0.8, alpha=0.2, beta=1.0) ≈ 9.32
@test quantile(v, 0.8, alpha=0.4, beta=0.0) ≈ 16.04
@test quantile(v, 0.8, alpha=0.4, beta=0.2) ≈ 14.76
@test quantile(v, 0.8, alpha=0.4, beta=0.4) ≈ 13.48
@test quantile(v, 0.8, alpha=0.4, beta=0.6) ≈ 12.2
@test quantile(v, 0.8, alpha=0.4, beta=0.8) ≈ 10.92
@test quantile(v, 0.8, alpha=0.4, beta=1.0) ≈ 9.64
@test quantile(v, 0.8, alpha=0.6, beta=0.0) ≈ 16.36
@test quantile(v, 0.8, alpha=0.6, beta=0.2) ≈ 15.08
@test quantile(v, 0.8, alpha=0.6, beta=0.4) ≈ 13.8
@test quantile(v, 0.8, alpha=0.6, beta=0.6) ≈ 12.52
@test quantile(v, 0.8, alpha=0.6, beta=0.8) ≈ 11.24
@test quantile(v, 0.8, alpha=0.6, beta=1.0) ≈ 9.96
@test quantile(v, 0.8, alpha=0.8, beta=0.0) ≈ 16.68
@test quantile(v, 0.8, alpha=0.8, beta=0.2) ≈ 15.4
@test quantile(v, 0.8, alpha=0.8, beta=0.4) ≈ 14.12
@test quantile(v, 0.8, alpha=0.8, beta=0.6) ≈ 12.84
@test quantile(v, 0.8, alpha=0.8, beta=0.8) ≈ 11.56
@test quantile(v, 0.8, alpha=0.8, beta=1.0) ≈ 10.28
@test quantile(v, 0.8, alpha=1.0, beta=0.0) ≈ 17.0
@test quantile(v, 0.8, alpha=1.0, beta=0.2) ≈ 15.72
@test quantile(v, 0.8, alpha=1.0, beta=0.4) ≈ 14.44
@test quantile(v, 0.8, alpha=1.0, beta=0.6) ≈ 13.16
@test quantile(v, 0.8, alpha=1.0, beta=0.8) ≈ 11.88
@test quantile(v, 0.8, alpha=1.0, beta=1.0) ≈ 10.6
@test quantile(v, 1.0, alpha=0.0, beta=0.0) ≈ 21.0
@test quantile(v, 1.0, alpha=1.0, beta=1.0) ≈ 21.0
end
# StatsBase issue 164
let y = [0.40003674665581906, 0.4085630862624367, 0.41662034698690303, 0.41662034698690303, 0.42189053966652057, 0.42189053966652057, 0.42553514344518345, 0.43985732442991354]
@test issorted(quantile(y, range(0.01, stop=0.99, length=17)))
end
@testset "variance of complex arrays (#13309)" begin
z = rand(ComplexF64, 10)
@test var(z) ≈ invoke(var, Tuple{Any}, z) ≈ cov(z) ≈ var(z,dims=1)[1] ≈ sum(abs2, z .- mean(z))/9
@test isa(var(z), Float64)
@test isa(invoke(var, Tuple{Any}, z), Float64)
@test isa(cov(z), Float64)
@test isa(var(z,dims=1), Vector{Float64})
@test varm(z, 0.0) ≈ invoke(varm, Tuple{Any,Float64}, z, 0.0) ≈ sum(abs2, z)/9
@test isa(varm(z, 0.0), Float64)
@test isa(invoke(varm, Tuple{Any,Float64}, z, 0.0), Float64)
@test cor(z) === 1.0
v = varm([1.0+2.0im], 0; corrected = false)
@test v ≈ 5
@test isa(v, Float64)
end
@testset "cov and cor of complex arrays (issue #21093)" begin
x = [2.7 - 3.3im, 0.9 + 5.4im, 0.1 + 0.2im, -1.7 - 5.8im, 1.1 + 1.9im]
y = [-1.7 - 1.6im, -0.2 + 6.5im, 0.8 - 10.0im, 9.1 - 3.4im, 2.7 - 5.5im]
@test cov(x, y) ≈ 4.8365 - 12.119im
@test cov(y, x) ≈ 4.8365 + 12.119im
@test cov(x, reshape(y, :, 1)) ≈ reshape([4.8365 - 12.119im], 1, 1)
@test cov(reshape(x, :, 1), y) ≈ reshape([4.8365 - 12.119im], 1, 1)
@test cov(reshape(x, :, 1), reshape(y, :, 1)) ≈ reshape([4.8365 - 12.119im], 1, 1)
@test cov([x y]) ≈ [21.779 4.8365-12.119im;
4.8365+12.119im 54.548]
@test cor(x, y) ≈ 0.14032104449218274 - 0.35160772008699703im
@test cor(y, x) ≈ 0.14032104449218274 + 0.35160772008699703im
@test cor(x, reshape(y, :, 1)) ≈ reshape([0.14032104449218274 - 0.35160772008699703im], 1, 1)
@test cor(reshape(x, :, 1), y) ≈ reshape([0.14032104449218274 - 0.35160772008699703im], 1, 1)
@test cor(reshape(x, :, 1), reshape(y, :, 1)) ≈ reshape([0.14032104449218274 - 0.35160772008699703im], 1, 1)
@test cor([x y]) ≈ [1.0 0.14032104449218274-0.35160772008699703im
0.14032104449218274+0.35160772008699703im 1.0]
end
@testset "Issue #17153 and PR #17154" begin
a = rand(10,10)
b = copy(a)
x = median(a, dims=1)
@test b == a
x = median(a, dims=2)
@test b == a
x = mean(a, dims=1)
@test b == a
x = mean(a, dims=2)
@test b == a
x = var(a, dims=1)
@test b == a
x = var(a, dims=2)
@test b == a
x = std(a, dims=1)
@test b == a
x = std(a, dims=2)
@test b == a
end
# dimensional correctness
const BASE_TEST_PATH = joinpath(Sys.BINDIR, "..", "share", "julia", "test")
isdefined(Main, :Furlongs) || @eval Main include(joinpath($(BASE_TEST_PATH), "testhelpers", "Furlongs.jl"))
using .Main.Furlongs
Statistics.middle(x::Furlong{p}) where {p} = Furlong{p}(middle(x.val))
Statistics.middle(x::Furlong{p}, y::Furlong{p}) where {p} = Furlong{p}(middle(x.val, y.val))
@testset "Unitful elements" begin
r = Furlong(1):Furlong(1):Furlong(2)
a = Vector(r)
@test sum(r) == sum(a) == Furlong(3)
@test cumsum(r) == Furlong.([1,3])
@test mean(r) == mean(a) == median(a) == median(r) == Furlong(1.5)
@test var(r) == var(a) == Furlong{2}(0.5)
@test std(r) == std(a) == Furlong{1}(sqrt(0.5))
# Issue #21786
A = [Furlong{1}(rand(-5:5)) for i in 1:2, j in 1:2]
@test mean(mean(A, dims=1), dims=2)[1] === mean(A)
@test var(A, dims=1)[1] === var(A[:, 1])
@test std(A, dims=1)[1] === std(A[:, 1])
end
# Issue #22901
@testset "var and quantile of Any arrays" begin
x = Any[1, 2, 4, 10]
y = Any[1, 2, 4, 10//1]
@test var(x) === 16.25
@test var(y) === 16.25
@test std(x) === sqrt(16.25)
@test quantile(x, 0.5) === 3.0
@test quantile(x, 1//2) === 3//1
end
@testset "Promotion in covzm. Issue #8080" begin
A = [1 -1 -1; -1 1 1; -1 1 -1; 1 -1 -1; 1 -1 1]
@test Statistics.covzm(A) - mean(A, dims=1)'*mean(A, dims=1)*size(A, 1)/(size(A, 1) - 1) ≈ cov(A)
A = [1//1 -1 -1; -1 1 1; -1 1 -1; 1 -1 -1; 1 -1 1]
@test (A'A - size(A, 1)*mean(A, dims=1)'*mean(A, dims=1))/4 == cov(A)
end
@testset "Mean along dimension of empty array" begin
a0 = zeros(0)
a00 = zeros(0, 0)
a01 = zeros(0, 1)
a10 = zeros(1, 0)
@test isequal(mean(a0, dims=1) , fill(NaN, 1))
@test isequal(mean(a00, dims=(1, 2)), fill(NaN, 1, 1))
@test isequal(mean(a01, dims=1) , fill(NaN, 1, 1))
@test isequal(mean(a10, dims=2) , fill(NaN, 1, 1))
end
@testset "cov/var/std of Vector{Vector}" begin
x = [[2,4,6],[4,6,8]]
@test var(x) ≈ vec(var([x[1] x[2]], dims=2))
@test std(x) ≈ vec(std([x[1] x[2]], dims=2))
@test cov(x) ≈ cov([x[1] x[2]], dims=2)
end
@testset "var of sparse array" begin
se33 = SparseMatrixCSC{Float64}(I, 3, 3)
sA = sprandn(3, 7, 0.5)
pA = sparse(rand(3, 7))
for arr in (se33, sA, pA)
farr = Array(arr)
@test var(arr) ≈ var(farr)
@test var(arr, dims=1) ≈ var(farr, dims=1)
@test var(arr, dims=2) ≈ var(farr, dims=2)
@test var(arr, dims=(1, 2)) ≈ [var(farr)]
@test isequal(var(arr, dims=3), var(farr, dims=3))
end
@testset "empty cases" begin
@test var(sparse(Int[])) === NaN
@test isequal(var(spzeros(0, 1), dims=1), var(Matrix{Int}(I, 0, 1), dims=1))
@test isequal(var(spzeros(0, 1), dims=2), var(Matrix{Int}(I, 0, 1), dims=2))
@test isequal(var(spzeros(0, 1), dims=(1, 2)), var(Matrix{Int}(I, 0, 1), dims=(1, 2)))
@test isequal(var(spzeros(0, 1), dims=3), var(Matrix{Int}(I, 0, 1), dims=3))
end
end
# Faster covariance function for sparse matrices
# Prevents densifying the input matrix when subtracting the mean
# Test against dense implementation
# PR https://github.com/JuliaLang/julia/pull/22735
# Part of this test needed to be hacked due to the treatment
# of Inf in sparse matrix algebra
# https://github.com/JuliaLang/julia/issues/22921
# The issue will be resolved in
# https://github.com/JuliaLang/julia/issues/22733
@testset "optimizing sparse $elty covariance" for elty in (Float64, Complex{Float64})
n = 10
p = 5
np2 = div(n*p, 2)
nzvals, x_sparse = guardseed(1) do
if elty <: Real
nzvals = randn(np2)
else
nzvals = complex.(randn(np2), randn(np2))
end
nzvals, sparse(rand(1:n, np2), rand(1:p, np2), nzvals, n, p)
end
x_dense = convert(Matrix{elty}, x_sparse)
@testset "Test with no Infs and NaNs, vardim=$vardim, corrected=$corrected" for vardim in (1, 2),
corrected in (true, false)
@test cov(x_sparse, dims=vardim, corrected=corrected) ≈
cov(x_dense , dims=vardim, corrected=corrected)
end
@testset "Test with $x11, vardim=$vardim, corrected=$corrected" for x11 in (NaN, Inf),
vardim in (1, 2),
corrected in (true, false)
x_sparse[1,1] = x11
x_dense[1 ,1] = x11
cov_sparse = cov(x_sparse, dims=vardim, corrected=corrected)
cov_dense = cov(x_dense , dims=vardim, corrected=corrected)
@test cov_sparse[2:end, 2:end] ≈ cov_dense[2:end, 2:end]
@test isfinite.(cov_sparse) == isfinite.(cov_dense)
@test isfinite.(cov_sparse) == isfinite.(cov_dense)
end
@testset "Test with NaN and Inf, vardim=$vardim, corrected=$corrected" for vardim in (1, 2),
corrected in (true, false)
x_sparse[1,1] = Inf
x_dense[1 ,1] = Inf
x_sparse[2,1] = NaN
x_dense[2 ,1] = NaN
cov_sparse = cov(x_sparse, dims=vardim, corrected=corrected)
cov_dense = cov(x_dense , dims=vardim, corrected=corrected)
@test cov_sparse[(1 + vardim):end, (1 + vardim):end] ≈
cov_dense[ (1 + vardim):end, (1 + vardim):end]
@test isfinite.(cov_sparse) == isfinite.(cov_dense)
@test isfinite.(cov_sparse) == isfinite.(cov_dense)
end
end
| 40.102445
| 175
| 0.536054
|
[
"@testset \"middle\" begin\n @test middle(3) === 3.0\n @test middle(2, 3) === 2.5\n let x = ((floatmax(1.0)/4)*3)\n @test middle(x, x) === x\n end\n @test middle(1:8) === 4.5\n @test middle([1:8;]) === 4.5\n\n # ensure type-correctness\n for T in [Bool,Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128,Float16,Float32,Float64]\n @test middle(one(T)) === middle(one(T), one(T))\n end\nend",
"@testset \"median\" begin\n @test median([1.]) === 1.\n @test median([1.,3]) === 2.\n @test median([1.,3,2]) === 2.\n\n @test median([1,3,2]) === 2.0\n @test median([1,3,2,4]) === 2.5\n\n @test median([0.0,Inf]) == Inf\n @test median([0.0,-Inf]) == -Inf\n @test median([0.,Inf,-Inf]) == 0.0\n @test median([1.,-1.,Inf,-Inf]) == 0.0\n @test isnan(median([-Inf,Inf]))\n\n X = [2 3 1 -1; 7 4 5 -4]\n @test all(median(X, dims=2) .== [1.5, 4.5])\n @test all(median(X, dims=1) .== [4.5 3.5 3.0 -2.5])\n @test X == [2 3 1 -1; 7 4 5 -4] # issue #17153\n\n @test_throws ArgumentError median([])\n @test isnan(median([NaN]))\n @test isnan(median([0.0,NaN]))\n @test isnan(median([NaN,0.0]))\n @test isnan(median([NaN,0.0,1.0]))\n @test isnan(median(Any[NaN,0.0,1.0]))\n @test isequal(median([NaN 0.0; 1.2 4.5], dims=2), reshape([NaN; 2.85], 2, 1))\n\n @test ismissing(median([1, missing]))\n @test ismissing(median([1, 2, missing]))\n @test ismissing(median([NaN, 2.0, missing]))\n @test ismissing(median([NaN, missing]))\n @test ismissing(median([missing, NaN]))\n @test ismissing(median(Any[missing, 2.0, 3.0, 4.0, NaN]))\n @test median(skipmissing([1, missing, 2])) === 1.5\n\n @test median!([1 2 3 4]) == 2.5\n @test median!([1 2; 3 4]) == 2.5\n\n @test invoke(median, Tuple{AbstractVector}, 1:10) == median(1:10) == 5.5\n\n @test @inferred(median(Float16[1, 2, NaN])) === Float16(NaN)\n @test @inferred(median(Float16[1, 2, 3])) === Float16(2)\n @test @inferred(median(Float32[1, 2, NaN])) === NaN32\n @test @inferred(median(Float32[1, 2, 3])) === 2.0f0\nend",
"@testset \"mean\" begin\n @test mean((1,2,3)) === 2.\n @test mean([0]) === 0.\n @test mean([1.]) === 1.\n @test mean([1.,3]) == 2.\n @test mean([1,2,3]) == 2.\n @test mean([0 1 2; 4 5 6], dims=1) == [2. 3. 4.]\n @test mean([1 2 3; 4 5 6], dims=1) == [2.5 3.5 4.5]\n @test mean(-, [1 2 3 ; 4 5 6], dims=1) == [-2.5 -3.5 -4.5]\n @test mean(-, [1 2 3 ; 4 5 6], dims=2) == transpose([-2.0 -5.0])\n @test mean(-, [1 2 3 ; 4 5 6], dims=(1, 2)) == -3.5 .* ones(1, 1)\n @test mean(-, [1 2 3 ; 4 5 6], dims=(1, 1)) == [-2.5 -3.5 -4.5]\n @test mean(-, [1 2 3 ; 4 5 6], dims=()) == Float64[-1 -2 -3 ; -4 -5 -6]\n @test mean(i->i+1, 0:2) === 2.\n @test mean(isodd, [3]) === 1.\n @test mean(x->3x, (1,1)) === 3.\n\n # mean of iterables:\n n = 10; a = randn(n); b = randn(n)\n @test mean(Tuple(a)) ≈ mean(a)\n @test mean(Tuple(a + b*im)) ≈ mean(a + b*im)\n @test mean(cos, Tuple(a)) ≈ mean(cos, a)\n @test mean(x->x/2, a + b*im) ≈ mean(a + b*im) / 2.\n @test ismissing(mean(Tuple((1, 2, missing, 4, 5))))\n\n @test isnan(mean([NaN]))\n @test isnan(mean([0.0,NaN]))\n @test isnan(mean([NaN,0.0]))\n\n @test isnan(mean([0.,Inf,-Inf]))\n @test isnan(mean([1.,-1.,Inf,-Inf]))\n @test isnan(mean([-Inf,Inf]))\n @test isequal(mean([NaN 0.0; 1.2 4.5], dims=2), reshape([NaN; 2.85], 2, 1))\n\n @test ismissing(mean([1, missing]))\n @test ismissing(mean([NaN, missing]))\n @test ismissing(mean([missing, NaN]))\n @test isequal(mean([missing 1.0; 2.0 3.0], dims=1), [missing 2.0])\n @test mean(skipmissing([1, missing, 2])) === 1.5\n @test isequal(mean(Complex{Float64}[]), NaN+NaN*im)\n @test mean(Complex{Float64}[]) isa Complex{Float64}\n @test isequal(mean(skipmissing(Complex{Float64}[])), NaN+NaN*im)\n @test mean(skipmissing(Complex{Float64}[])) isa Complex{Float64}\n @test isequal(mean(abs, Complex{Float64}[]), NaN)\n @test mean(abs, Complex{Float64}[]) isa Float64\n @test isequal(mean(abs, skipmissing(Complex{Float64}[])), NaN)\n @test mean(abs, skipmissing(Complex{Float64}[])) isa Float64\n @test isequal(mean(Int[]), NaN)\n @test mean(Int[]) isa Float64\n @test isequal(mean(skipmissing(Int[])), NaN)\n @test mean(skipmissing(Int[])) isa Float64\n @test_throws MethodError mean([])\n @test_throws MethodError mean(skipmissing([]))\n @test_throws ArgumentError mean((1 for i in 2:1))\n if VERSION >= v\"1.6.0-DEV.83\"\n @test_throws ArgumentError mean(())\n @test_throws ArgumentError mean(Union{}[])\n end\n\n # Check that small types are accumulated using wider type\n for T in (Int8, UInt8)\n x = [typemax(T) typemax(T)]\n g = (v for v in x)\n @test mean(x) == mean(g) == typemax(T)\n @test mean(identity, x) == mean(identity, g) == typemax(T)\n @test mean(x, dims=2) == [typemax(T)]'\n end\n # Check that mean avoids integer overflow (#22)\n let x = fill(typemax(Int), 10), a = tuple(x...)\n @test (mean(x) == mean(x, dims=1)[] == mean(float, x)\n == mean(a) == mean(v for v in x) == mean(v for v in a)\n ≈ float(typemax(Int)))\n end\n let x = rand(10000) # mean should use sum's accurate pairwise algorithm\n @test mean(x) == sum(x) / length(x)\n end\n @test mean(Number[1, 1.5, 2+3im]) === 1.5+1im # mixed-type array\n @test mean(v for v in Number[1, 1.5, 2+3im]) === 1.5+1im\n @test (@inferred mean(Int[])) === 0/0\n @test (@inferred mean(Float32[])) === 0.f0/0 \n @test (@inferred mean(Float64[])) === 0/0\n @test (@inferred mean(Iterators.filter(x -> true, Int[]))) === 0/0\n @test (@inferred mean(Iterators.filter(x -> true, Float32[]))) === 0.f0/0\n @test (@inferred mean(Iterators.filter(x -> true, Float64[]))) === 0/0\nend",
"@testset \"mean/median for ranges\" begin\n for f in (mean, median)\n for n = 2:5\n @test f(2:n) == f([2:n;])\n @test f(2:0.1:n) ≈ f([2:0.1:n;])\n end\n end\n @test mean(2:1) === NaN\n @test mean(big(2):1) isa BigFloat\nend",
"@testset \"var & std\" begin\n # edge case: empty vector\n # iterable; this has to throw for type stability\n @test_throws MethodError var(())\n @test_throws MethodError var((); corrected=false)\n @test_throws MethodError var((); mean=2)\n @test_throws MethodError var((); mean=2, corrected=false)\n # reduction\n @test isnan(var(Int[]))\n @test isnan(var(Int[]; corrected=false))\n @test isnan(var(Int[]; mean=2))\n @test isnan(var(Int[]; mean=2, corrected=false))\n # reduction across dimensions\n @test isequal(var(Int[], dims=1), [NaN])\n @test isequal(var(Int[], dims=1; corrected=false), [NaN])\n @test isequal(var(Int[], dims=1; mean=[2]), [NaN])\n @test isequal(var(Int[], dims=1; mean=[2], corrected=false), [NaN])\n\n # edge case: one-element vector\n # iterable\n @test isnan(@inferred(var((1,))))\n @test var((1,); corrected=false) === 0.0\n @test var((1,); mean=2) === Inf\n @test var((1,); mean=2, corrected=false) === 1.0\n # reduction\n @test isnan(@inferred(var([1])))\n @test var([1]; corrected=false) === 0.0\n @test var([1]; mean=2) === Inf\n @test var([1]; mean=2, corrected=false) === 1.0\n # reduction across dimensions\n @test isequal(@inferred(var([1], dims=1)), [NaN])\n @test var([1], dims=1; corrected=false) ≈ [0.0]\n @test var([1], dims=1; mean=[2]) ≈ [Inf]\n @test var([1], dims=1; mean=[2], corrected=false) ≈ [1.0]\n\n @test var(1:8) == 6.\n @test varm(1:8,1) == varm(Vector(1:8),1)\n @test isnan(varm(1:1,1))\n @test isnan(var(1:1))\n @test isnan(var(1:-1))\n\n @test @inferred(var(1.0:8.0)) == 6.\n @test varm(1.0:8.0,1.0) == varm(Vector(1.0:8.0),1)\n @test isnan(varm(1.0:1.0,1.0))\n @test isnan(var(1.0:1.0))\n @test isnan(var(1.0:-1.0))\n\n @test @inferred(var(1.0f0:8.0f0)) === 6.f0\n @test varm(1.0f0:8.0f0,1.0f0) == varm(Vector(1.0f0:8.0f0),1)\n @test isnan(varm(1.0f0:1.0f0,1.0f0))\n @test isnan(var(1.0f0:1.0f0))\n @test isnan(var(1.0f0:-1.0f0))\n\n @test varm([1,2,3], 2) ≈ 1.\n @test var([1,2,3]) ≈ 1.\n @test var([1,2,3]; corrected=false) ≈ 2.0/3\n @test var([1,2,3]; mean=0) ≈ 7.\n @test var([1,2,3]; mean=0, corrected=false) ≈ 14.0/3\n\n @test varm((1,2,3), 2) ≈ 1.\n @test var((1,2,3)) ≈ 1.\n @test var((1,2,3); corrected=false) ≈ 2.0/3\n @test var((1,2,3); mean=0) ≈ 7.\n @test var((1,2,3); mean=0, corrected=false) ≈ 14.0/3\n @test_throws ArgumentError var((1,2,3); mean=())\n\n @test var([1 2 3 4 5; 6 7 8 9 10], dims=2) ≈ [2.5 2.5]'\n @test var([1 2 3 4 5; 6 7 8 9 10], dims=2; corrected=false) ≈ [2.0 2.0]'\n\n @test var(collect(1:99), dims=1) ≈ [825]\n @test var(Matrix(transpose(collect(1:99))), dims=2) ≈ [825]\n\n @test stdm([1,2,3], 2) ≈ 1.\n @test std([1,2,3]) ≈ 1.\n @test std([1,2,3]; corrected=false) ≈ sqrt(2.0/3)\n @test std([1,2,3]; mean=0) ≈ sqrt(7.0)\n @test std([1,2,3]; mean=0, corrected=false) ≈ sqrt(14.0/3)\n\n @test stdm([1.0,2,3], 2) ≈ 1.\n @test std([1.0,2,3]) ≈ 1.\n @test std([1.0,2,3]; corrected=false) ≈ sqrt(2.0/3)\n @test std([1.0,2,3]; mean=0) ≈ sqrt(7.0)\n @test std([1.0,2,3]; mean=0, corrected=false) ≈ sqrt(14.0/3)\n\n @test std([1.0,2,3]; dims=1)[] ≈ 1.\n @test std([1.0,2,3]; dims=1, corrected=false)[] ≈ sqrt(2.0/3)\n @test std([1.0,2,3]; dims=1, mean=[0])[] ≈ sqrt(7.0)\n @test std([1.0,2,3]; dims=1, mean=[0], corrected=false)[] ≈ sqrt(14.0/3)\n\n @test stdm((1,2,3), 2) ≈ 1.\n @test std((1,2,3)) ≈ 1.\n @test std((1,2,3); corrected=false) ≈ sqrt(2.0/3)\n @test std((1,2,3); mean=0) ≈ sqrt(7.0)\n @test std((1,2,3); mean=0, corrected=false) ≈ sqrt(14.0/3)\n\n @test std([1 2 3 4 5; 6 7 8 9 10], dims=2) ≈ sqrt.([2.5 2.5]')\n @test std([1 2 3 4 5; 6 7 8 9 10], dims=2; corrected=false) ≈ sqrt.([2.0 2.0]')\n\n let A = ComplexF64[exp(i*im) for i in 1:10^4]\n @test varm(A, 0.) ≈ sum(map(abs2, A)) / (length(A) - 1)\n @test varm(A, mean(A)) ≈ var(A)\n end\n\n @test var([1//1, 2//1]) isa Rational{Int}\n @test var([1//1, 2//1], dims=1) isa Vector{Rational{Int}}\n\n @test std([1//1, 2//1]) isa Float64\n @test std([1//1, 2//1], dims=1) isa Vector{Float64}\n\n @testset \"var: empty cases\" begin\n A = Matrix{Int}(undef, 0,1)\n @test var(A) === NaN\n\n @test isequal(var(A, dims=1), fill(NaN, 1, 1))\n @test isequal(var(A, dims=2), fill(NaN, 0, 1))\n @test isequal(var(A, dims=(1, 2)), fill(NaN, 1, 1))\n @test isequal(var(A, dims=3), fill(NaN, 0, 1))\n end\n\n # issue #6672\n @test std(AbstractFloat[1,2,3], dims=1) == [1.0]\n\n for f in (var, std)\n @test ismissing(f([1, missing]))\n @test ismissing(f([NaN, missing]))\n @test ismissing(f([missing, NaN]))\n @test isequal(f([missing 1.0; 2.0 3.0], dims=1), [missing f([1.0, 3.0])])\n @test f(skipmissing([1, missing, 2])) === f([1, 2])\n end\n for f in (varm, stdm)\n @test ismissing(f([1, missing], 0))\n @test ismissing(f([1, 2], missing))\n @test ismissing(f([1, NaN], missing))\n @test ismissing(f([NaN, missing], 0))\n @test ismissing(f([missing, NaN], 0))\n @test ismissing(f([NaN, missing], missing))\n @test ismissing(f([missing, NaN], missing))\n @test f(skipmissing([1, missing, 2]), 0) === f([1, 2], 0)\n end\n\n @test isequal(var(Complex{Float64}[]), NaN)\n @test var(Complex{Float64}[]) isa Float64\n @test isequal(var(skipmissing(Complex{Float64}[])), NaN)\n @test var(skipmissing(Complex{Float64}[])) isa Float64\n @test_throws MethodError var([])\n @test_throws MethodError var(skipmissing([]))\n @test_throws MethodError var((1 for i in 2:1))\n @test isequal(var(Int[]), NaN)\n @test var(Int[]) isa Float64\n @test isequal(var(skipmissing(Int[])), NaN)\n @test var(skipmissing(Int[])) isa Float64\n\n # over dimensions with provided means\n for x in ([1 2 3; 4 5 6], sparse([1 2 3; 4 5 6]))\n @test var(x, dims=1, mean=mean(x, dims=1)) == var(x, dims=1)\n @test var(x, dims=1, mean=reshape(mean(x, dims=1), 1, :, 1)) == var(x, dims=1)\n @test var(x, dims=2, mean=mean(x, dims=2)) == var(x, dims=2)\n @test var(x, dims=2, mean=reshape(mean(x, dims=2), :)) == var(x, dims=2)\n @test var(x, dims=2, mean=reshape(mean(x, dims=2), :, 1, 1)) == var(x, dims=2)\n @test_throws DimensionMismatch var(x, dims=1, mean=ones(size(x, 1)))\n @test_throws DimensionMismatch var(x, dims=1, mean=ones(size(x, 1), 1))\n @test_throws DimensionMismatch var(x, dims=2, mean=ones(1, size(x, 2)))\n @test_throws DimensionMismatch var(x, dims=1, mean=ones(1, 1, size(x, 2)))\n @test_throws DimensionMismatch var(x, dims=2, mean=ones(1, size(x, 2), 1))\n @test_throws DimensionMismatch var(x, dims=2, mean=ones(size(x, 1), 1, 5))\n @test_throws DimensionMismatch var(x, dims=1, mean=ones(1, size(x, 2), 5))\n end\nend",
"@testset \"covariance\" begin\n for vd in [1, 2], zm in [true, false], cr in [true, false]\n # println(\"vd = $vd: zm = $zm, cr = $cr\")\n if vd == 1\n k = size(X, 2)\n Cxx = zeros(k, k)\n Cxy = zeros(k, k)\n for i = 1:k, j = 1:k\n Cxx[i,j] = safe_cov(X[:,i], X[:,j], zm, cr)\n Cxy[i,j] = safe_cov(X[:,i], Y[:,j], zm, cr)\n end\n x1 = vec(X[:,1])\n y1 = vec(Y[:,1])\n else\n k = size(X, 1)\n Cxx = zeros(k, k)\n Cxy = zeros(k, k)\n for i = 1:k, j = 1:k\n Cxx[i,j] = safe_cov(X[i,:], X[j,:], zm, cr)\n Cxy[i,j] = safe_cov(X[i,:], Y[j,:], zm, cr)\n end\n x1 = vec(X[1,:])\n y1 = vec(Y[1,:])\n end\n\n c = zm ? Statistics.covm(x1, 0, corrected=cr) :\n cov(x1, corrected=cr)\n @test isa(c, Float64)\n @test c ≈ Cxx[1,1]\n @inferred cov(x1, corrected=cr)\n\n @test cov(X) == Statistics.covm(X, mean(X, dims=1))\n C = zm ? Statistics.covm(X, 0, vd, corrected=cr) :\n cov(X, dims=vd, corrected=cr)\n @test size(C) == (k, k)\n @test C ≈ Cxx\n @inferred cov(X, dims=vd, corrected=cr)\n\n @test cov(x1, y1) == Statistics.covm(x1, mean(x1), y1, mean(y1))\n c = zm ? Statistics.covm(x1, 0, y1, 0, corrected=cr) :\n cov(x1, y1, corrected=cr)\n @test isa(c, Float64)\n @test c ≈ Cxy[1,1]\n @inferred cov(x1, y1, corrected=cr)\n\n if vd == 1\n @test cov(x1, Y) == Statistics.covm(x1, mean(x1), Y, mean(Y, dims=1))\n end\n C = zm ? Statistics.covm(x1, 0, Y, 0, vd, corrected=cr) :\n cov(x1, Y, dims=vd, corrected=cr)\n @test size(C) == (1, k)\n @test vec(C) ≈ Cxy[1,:]\n @inferred cov(x1, Y, dims=vd, corrected=cr)\n\n if vd == 1\n @test cov(X, y1) == Statistics.covm(X, mean(X, dims=1), y1, mean(y1))\n end\n C = zm ? Statistics.covm(X, 0, y1, 0, vd, corrected=cr) :\n cov(X, y1, dims=vd, corrected=cr)\n @test size(C) == (k, 1)\n @test vec(C) ≈ Cxy[:,1]\n @inferred cov(X, y1, dims=vd, corrected=cr)\n\n @test cov(X, Y) == Statistics.covm(X, mean(X, dims=1), Y, mean(Y, dims=1))\n C = zm ? Statistics.covm(X, 0, Y, 0, vd, corrected=cr) :\n cov(X, Y, dims=vd, corrected=cr)\n @test size(C) == (k, k)\n @test C ≈ Cxy\n @inferred cov(X, Y, dims=vd, corrected=cr)\n end\n\n @testset \"floating point accuracy for `cov` of large numbers\" begin\n A = [4.0, 7.0, 13.0, 16.0]\n C = A .+ 1.0e10\n @test cov(A, A) ≈ cov(C, C)\n end\nend",
"@testset \"correlation\" begin\n for vd in [1, 2], zm in [true, false]\n # println(\"vd = $vd: zm = $zm\")\n if vd == 1\n k = size(X, 2)\n Cxx = zeros(k, k)\n Cxy = zeros(k, k)\n for i = 1:k, j = 1:k\n Cxx[i,j] = safe_cor(X[:,i], X[:,j], zm)\n Cxy[i,j] = safe_cor(X[:,i], Y[:,j], zm)\n end\n x1 = vec(X[:,1])\n y1 = vec(Y[:,1])\n else\n k = size(X, 1)\n Cxx = zeros(k, k)\n Cxy = zeros(k, k)\n for i = 1:k, j = 1:k\n Cxx[i,j] = safe_cor(X[i,:], X[j,:], zm)\n Cxy[i,j] = safe_cor(X[i,:], Y[j,:], zm)\n end\n x1 = vec(X[1,:])\n y1 = vec(Y[1,:])\n end\n\n c = zm ? Statistics.corm(x1, 0) : cor(x1)\n @test isa(c, Float64)\n @test c ≈ Cxx[1,1]\n @inferred cor(x1)\n\n @test cor(X) == Statistics.corm(X, mean(X, dims=1))\n C = zm ? Statistics.corm(X, 0, vd) : cor(X, dims=vd)\n @test size(C) == (k, k)\n @test C ≈ Cxx\n @inferred cor(X, dims=vd)\n\n @test cor(x1, y1) == Statistics.corm(x1, mean(x1), y1, mean(y1))\n c = zm ? Statistics.corm(x1, 0, y1, 0) : cor(x1, y1)\n @test isa(c, Float64)\n @test c ≈ Cxy[1,1]\n @inferred cor(x1, y1)\n\n if vd == 1\n @test cor(x1, Y) == Statistics.corm(x1, mean(x1), Y, mean(Y, dims=1))\n end\n C = zm ? Statistics.corm(x1, 0, Y, 0, vd) : cor(x1, Y, dims=vd)\n @test size(C) == (1, k)\n @test vec(C) ≈ Cxy[1,:]\n @inferred cor(x1, Y, dims=vd)\n\n if vd == 1\n @test cor(X, y1) == Statistics.corm(X, mean(X, dims=1), y1, mean(y1))\n end\n C = zm ? Statistics.corm(X, 0, y1, 0, vd) : cor(X, y1, dims=vd)\n @test size(C) == (k, 1)\n @test vec(C) ≈ Cxy[:,1]\n @inferred cor(X, y1, dims=vd)\n\n @test cor(X, Y) == Statistics.corm(X, mean(X, dims=1), Y, mean(Y, dims=1))\n C = zm ? Statistics.corm(X, 0, Y, 0, vd) : cor(X, Y, dims=vd)\n @test size(C) == (k, k)\n @test C ≈ Cxy\n @inferred cor(X, Y, dims=vd)\n end\n\n @test cor(repeat(1:17, 1, 17))[2] <= 1.0\n @test cor(1:17, 1:17) <= 1.0\n @test cor(1:17, 18:34) <= 1.0\n @test cor(Any[1, 2], Any[1, 2]) == 1.0\n @test isnan(cor([0], Int8[81]))\n let tmp = range(1, stop=85, length=100)\n tmp2 = Vector(tmp)\n @test cor(tmp, tmp) <= 1.0\n @test cor(tmp, tmp2) <= 1.0\n end\nend",
"@testset \"quantile\" begin\n @test quantile([1,2,3,4],0.5) ≈ 2.5\n @test quantile([1,2,3,4],[0.5]) ≈ [2.5]\n @test quantile([1., 3],[.25,.5,.75])[2] ≈ median([1., 3])\n @test quantile(100.0:-1.0:0.0, 0.0:0.1:1.0) ≈ 0.0:10.0:100.0\n @test quantile(0.0:100.0, 0.0:0.1:1.0, sorted=true) ≈ 0.0:10.0:100.0\n @test quantile(100f0:-1f0:0.0, 0.0:0.1:1.0) ≈ 0f0:10f0:100f0\n @test quantile([Inf,Inf],0.5) == Inf\n @test quantile([-Inf,1],0.5) == -Inf\n # here it is required to introduce an absolute tolerance because the calculated value is 0\n @test quantile([0,1],1e-18) ≈ 1e-18 atol=1e-18\n @test quantile([1, 2, 3, 4],[]) == []\n @test quantile([1, 2, 3, 4], (0.5,)) == (2.5,)\n @test quantile([4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11],\n (0.1, 0.2, 0.4, 0.9)) == (2.0, 3.0, 5.0, 11.0)\n @test quantile(Union{Int, Missing}[4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11],\n [0.1, 0.2, 0.4, 0.9]) ≈ [2.0, 3.0, 5.0, 11.0]\n @test quantile(Any[4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11],\n [0.1, 0.2, 0.4, 0.9]) ≈ [2.0, 3.0, 5.0, 11.0]\n @test quantile([4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11],\n Any[0.1, 0.2, 0.4, 0.9]) ≈ [2.0, 3.0, 5.0, 11.0]\n @test quantile([4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11],\n Any[0.1, 0.2, 0.4, 0.9]) isa Vector{Float64}\n @test quantile(Any[4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11],\n Any[0.1, 0.2, 0.4, 0.9]) ≈ [2, 3, 5, 11]\n @test quantile(Any[4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11],\n Any[0.1, 0.2, 0.4, 0.9]) isa Vector{Float64}\n @test quantile([1, 2, 3, 4], ()) == ()\n @test isempty(quantile([1, 2, 3, 4], Float64[]))\n @test quantile([1, 2, 3, 4], Float64[]) isa Vector{Float64}\n @test quantile([1, 2, 3, 4], []) isa Vector{Any}\n @test quantile([1, 2, 3, 4], [0, 1]) isa Vector{Int}\n\n @test quantile(Any[1, 2, 3], 0.5) isa Float64\n @test quantile(Any[1, big(2), 3], 0.5) isa BigFloat\n @test quantile(Any[1, 2, 3], Float16(0.5)) isa Float16\n @test quantile(Any[1, Float16(2), 3], Float16(0.5)) isa Float16\n @test quantile(Any[1, big(2), 3], Float16(0.5)) isa BigFloat\n\n @test_throws ArgumentError quantile([1, missing], 0.5)\n @test_throws ArgumentError quantile([1, NaN], 0.5)\n @test quantile(skipmissing([1, missing, 2]), 0.5) === 1.5\n\n # make sure that type inference works correctly in normal cases\n for T in [Int, BigInt, Float64, Float16, BigFloat, Rational{Int}, Rational{BigInt}]\n for S in [Float64, Float16, BigFloat, Rational{Int}, Rational{BigInt}]\n @inferred quantile(T[1, 2, 3], S(0.5))\n @inferred quantile(T[1, 2, 3], S(0.6))\n @inferred quantile(T[1, 2, 3], S[0.5, 0.6])\n @inferred quantile(T[1, 2, 3], (S(0.5), S(0.6)))\n end\n end\n x = [3; 2; 1]\n y = zeros(3)\n @test quantile!(y, x, [0.1, 0.5, 0.9]) === y\n @test y ≈ [1.2, 2.0, 2.8]\n\n #tests for quantile calculation with configurable alpha and beta parameters\n v = [2, 3, 4, 6, 9, 2, 6, 2, 21, 17]\n\n # tests against scipy.stats.mstats.mquantiles method\n @test quantile(v, 0.0, alpha=0.0, beta=0.0) ≈ 2.0\n @test quantile(v, 0.2, alpha=1.0, beta=1.0) ≈ 2.0\n @test quantile(v, 0.4, alpha=0.0, beta=0.0) ≈ 3.4\n @test quantile(v, 0.4, alpha=0.0, beta=0.2) ≈ 3.32\n @test quantile(v, 0.4, alpha=0.0, beta=0.4) ≈ 3.24\n @test quantile(v, 0.4, alpha=0.0, beta=0.6) ≈ 3.16\n @test quantile(v, 0.4, alpha=0.0, beta=0.8) ≈ 3.08\n @test quantile(v, 0.4, alpha=0.0, beta=1.0) ≈ 3.0\n @test quantile(v, 0.4, alpha=0.2, beta=0.0) ≈ 3.52\n @test quantile(v, 0.4, alpha=0.2, beta=0.2) ≈ 3.44\n @test quantile(v, 0.4, alpha=0.2, beta=0.4) ≈ 3.36\n @test quantile(v, 0.4, alpha=0.2, beta=0.6) ≈ 3.28\n @test quantile(v, 0.4, alpha=0.2, beta=0.8) ≈ 3.2\n @test quantile(v, 0.4, alpha=0.2, beta=1.0) ≈ 3.12\n @test quantile(v, 0.4, alpha=0.4, beta=0.0) ≈ 3.64\n @test quantile(v, 0.4, alpha=0.4, beta=0.2) ≈ 3.56\n @test quantile(v, 0.4, alpha=0.4, beta=0.4) ≈ 3.48\n @test quantile(v, 0.4, alpha=0.4, beta=0.6) ≈ 3.4\n @test quantile(v, 0.4, alpha=0.4, beta=0.8) ≈ 3.32\n @test quantile(v, 0.4, alpha=0.4, beta=1.0) ≈ 3.24\n @test quantile(v, 0.4, alpha=0.6, beta=0.0) ≈ 3.76\n @test quantile(v, 0.4, alpha=0.6, beta=0.2) ≈ 3.68\n @test quantile(v, 0.4, alpha=0.6, beta=0.4) ≈ 3.6\n @test quantile(v, 0.4, alpha=0.6, beta=0.6) ≈ 3.52\n @test quantile(v, 0.4, alpha=0.6, beta=0.8) ≈ 3.44\n @test quantile(v, 0.4, alpha=0.6, beta=1.0) ≈ 3.36\n @test quantile(v, 0.4, alpha=0.8, beta=0.0) ≈ 3.88\n @test quantile(v, 0.4, alpha=0.8, beta=0.2) ≈ 3.8\n @test quantile(v, 0.4, alpha=0.8, beta=0.4) ≈ 3.72\n @test quantile(v, 0.4, alpha=0.8, beta=0.6) ≈ 3.64\n @test quantile(v, 0.4, alpha=0.8, beta=0.8) ≈ 3.56\n @test quantile(v, 0.4, alpha=0.8, beta=1.0) ≈ 3.48\n @test quantile(v, 0.4, alpha=1.0, beta=0.0) ≈ 4.0\n @test quantile(v, 0.4, alpha=1.0, beta=0.2) ≈ 3.92\n @test quantile(v, 0.4, alpha=1.0, beta=0.4) ≈ 3.84\n @test quantile(v, 0.4, alpha=1.0, beta=0.6) ≈ 3.76\n @test quantile(v, 0.4, alpha=1.0, beta=0.8) ≈ 3.68\n @test quantile(v, 0.4, alpha=1.0, beta=1.0) ≈ 3.6\n @test quantile(v, 0.6, alpha=0.0, beta=0.0) ≈ 6.0\n @test quantile(v, 0.6, alpha=1.0, beta=1.0) ≈ 6.0\n @test quantile(v, 0.8, alpha=0.0, beta=0.0) ≈ 15.4\n @test quantile(v, 0.8, alpha=0.0, beta=0.2) ≈ 14.12\n @test quantile(v, 0.8, alpha=0.0, beta=0.4) ≈ 12.84\n @test quantile(v, 0.8, alpha=0.0, beta=0.6) ≈ 11.56\n @test quantile(v, 0.8, alpha=0.0, beta=0.8) ≈ 10.28\n @test quantile(v, 0.8, alpha=0.0, beta=1.0) ≈ 9.0\n @test quantile(v, 0.8, alpha=0.2, beta=0.0) ≈ 15.72\n @test quantile(v, 0.8, alpha=0.2, beta=0.2) ≈ 14.44\n @test quantile(v, 0.8, alpha=0.2, beta=0.4) ≈ 13.16\n @test quantile(v, 0.8, alpha=0.2, beta=0.6) ≈ 11.88\n @test quantile(v, 0.8, alpha=0.2, beta=0.8) ≈ 10.6\n @test quantile(v, 0.8, alpha=0.2, beta=1.0) ≈ 9.32\n @test quantile(v, 0.8, alpha=0.4, beta=0.0) ≈ 16.04\n @test quantile(v, 0.8, alpha=0.4, beta=0.2) ≈ 14.76\n @test quantile(v, 0.8, alpha=0.4, beta=0.4) ≈ 13.48\n @test quantile(v, 0.8, alpha=0.4, beta=0.6) ≈ 12.2\n @test quantile(v, 0.8, alpha=0.4, beta=0.8) ≈ 10.92\n @test quantile(v, 0.8, alpha=0.4, beta=1.0) ≈ 9.64\n @test quantile(v, 0.8, alpha=0.6, beta=0.0) ≈ 16.36\n @test quantile(v, 0.8, alpha=0.6, beta=0.2) ≈ 15.08\n @test quantile(v, 0.8, alpha=0.6, beta=0.4) ≈ 13.8\n @test quantile(v, 0.8, alpha=0.6, beta=0.6) ≈ 12.52\n @test quantile(v, 0.8, alpha=0.6, beta=0.8) ≈ 11.24\n @test quantile(v, 0.8, alpha=0.6, beta=1.0) ≈ 9.96\n @test quantile(v, 0.8, alpha=0.8, beta=0.0) ≈ 16.68\n @test quantile(v, 0.8, alpha=0.8, beta=0.2) ≈ 15.4\n @test quantile(v, 0.8, alpha=0.8, beta=0.4) ≈ 14.12\n @test quantile(v, 0.8, alpha=0.8, beta=0.6) ≈ 12.84\n @test quantile(v, 0.8, alpha=0.8, beta=0.8) ≈ 11.56\n @test quantile(v, 0.8, alpha=0.8, beta=1.0) ≈ 10.28\n @test quantile(v, 0.8, alpha=1.0, beta=0.0) ≈ 17.0\n @test quantile(v, 0.8, alpha=1.0, beta=0.2) ≈ 15.72\n @test quantile(v, 0.8, alpha=1.0, beta=0.4) ≈ 14.44\n @test quantile(v, 0.8, alpha=1.0, beta=0.6) ≈ 13.16\n @test quantile(v, 0.8, alpha=1.0, beta=0.8) ≈ 11.88\n @test quantile(v, 0.8, alpha=1.0, beta=1.0) ≈ 10.6\n @test quantile(v, 1.0, alpha=0.0, beta=0.0) ≈ 21.0\n @test quantile(v, 1.0, alpha=1.0, beta=1.0) ≈ 21.0\nend",
"@testset \"variance of complex arrays (#13309)\" begin\n z = rand(ComplexF64, 10)\n @test var(z) ≈ invoke(var, Tuple{Any}, z) ≈ cov(z) ≈ var(z,dims=1)[1] ≈ sum(abs2, z .- mean(z))/9\n @test isa(var(z), Float64)\n @test isa(invoke(var, Tuple{Any}, z), Float64)\n @test isa(cov(z), Float64)\n @test isa(var(z,dims=1), Vector{Float64})\n @test varm(z, 0.0) ≈ invoke(varm, Tuple{Any,Float64}, z, 0.0) ≈ sum(abs2, z)/9\n @test isa(varm(z, 0.0), Float64)\n @test isa(invoke(varm, Tuple{Any,Float64}, z, 0.0), Float64)\n @test cor(z) === 1.0\n v = varm([1.0+2.0im], 0; corrected = false)\n @test v ≈ 5\n @test isa(v, Float64)\nend",
"@testset \"cov and cor of complex arrays (issue #21093)\" begin\n x = [2.7 - 3.3im, 0.9 + 5.4im, 0.1 + 0.2im, -1.7 - 5.8im, 1.1 + 1.9im]\n y = [-1.7 - 1.6im, -0.2 + 6.5im, 0.8 - 10.0im, 9.1 - 3.4im, 2.7 - 5.5im]\n @test cov(x, y) ≈ 4.8365 - 12.119im\n @test cov(y, x) ≈ 4.8365 + 12.119im\n @test cov(x, reshape(y, :, 1)) ≈ reshape([4.8365 - 12.119im], 1, 1)\n @test cov(reshape(x, :, 1), y) ≈ reshape([4.8365 - 12.119im], 1, 1)\n @test cov(reshape(x, :, 1), reshape(y, :, 1)) ≈ reshape([4.8365 - 12.119im], 1, 1)\n @test cov([x y]) ≈ [21.779 4.8365-12.119im;\n 4.8365+12.119im 54.548]\n @test cor(x, y) ≈ 0.14032104449218274 - 0.35160772008699703im\n @test cor(y, x) ≈ 0.14032104449218274 + 0.35160772008699703im\n @test cor(x, reshape(y, :, 1)) ≈ reshape([0.14032104449218274 - 0.35160772008699703im], 1, 1)\n @test cor(reshape(x, :, 1), y) ≈ reshape([0.14032104449218274 - 0.35160772008699703im], 1, 1)\n @test cor(reshape(x, :, 1), reshape(y, :, 1)) ≈ reshape([0.14032104449218274 - 0.35160772008699703im], 1, 1)\n @test cor([x y]) ≈ [1.0 0.14032104449218274-0.35160772008699703im\n 0.14032104449218274+0.35160772008699703im 1.0]\nend",
"@testset \"Issue #17153 and PR #17154\" begin\n a = rand(10,10)\n b = copy(a)\n x = median(a, dims=1)\n @test b == a\n x = median(a, dims=2)\n @test b == a\n x = mean(a, dims=1)\n @test b == a\n x = mean(a, dims=2)\n @test b == a\n x = var(a, dims=1)\n @test b == a\n x = var(a, dims=2)\n @test b == a\n x = std(a, dims=1)\n @test b == a\n x = std(a, dims=2)\n @test b == a\nend",
"@testset \"Unitful elements\" begin\n r = Furlong(1):Furlong(1):Furlong(2)\n a = Vector(r)\n @test sum(r) == sum(a) == Furlong(3)\n @test cumsum(r) == Furlong.([1,3])\n @test mean(r) == mean(a) == median(a) == median(r) == Furlong(1.5)\n @test var(r) == var(a) == Furlong{2}(0.5)\n @test std(r) == std(a) == Furlong{1}(sqrt(0.5))\n\n # Issue #21786\n A = [Furlong{1}(rand(-5:5)) for i in 1:2, j in 1:2]\n @test mean(mean(A, dims=1), dims=2)[1] === mean(A)\n @test var(A, dims=1)[1] === var(A[:, 1])\n @test std(A, dims=1)[1] === std(A[:, 1])\nend",
"@testset \"var and quantile of Any arrays\" begin\n x = Any[1, 2, 4, 10]\n y = Any[1, 2, 4, 10//1]\n @test var(x) === 16.25\n @test var(y) === 16.25\n @test std(x) === sqrt(16.25)\n @test quantile(x, 0.5) === 3.0\n @test quantile(x, 1//2) === 3//1\nend",
"@testset \"Promotion in covzm. Issue #8080\" begin\n A = [1 -1 -1; -1 1 1; -1 1 -1; 1 -1 -1; 1 -1 1]\n @test Statistics.covzm(A) - mean(A, dims=1)'*mean(A, dims=1)*size(A, 1)/(size(A, 1) - 1) ≈ cov(A)\n A = [1//1 -1 -1; -1 1 1; -1 1 -1; 1 -1 -1; 1 -1 1]\n @test (A'A - size(A, 1)*mean(A, dims=1)'*mean(A, dims=1))/4 == cov(A)\nend",
"@testset \"Mean along dimension of empty array\" begin\n a0 = zeros(0)\n a00 = zeros(0, 0)\n a01 = zeros(0, 1)\n a10 = zeros(1, 0)\n @test isequal(mean(a0, dims=1) , fill(NaN, 1))\n @test isequal(mean(a00, dims=(1, 2)), fill(NaN, 1, 1))\n @test isequal(mean(a01, dims=1) , fill(NaN, 1, 1))\n @test isequal(mean(a10, dims=2) , fill(NaN, 1, 1))\nend",
"@testset \"cov/var/std of Vector{Vector}\" begin\n x = [[2,4,6],[4,6,8]]\n @test var(x) ≈ vec(var([x[1] x[2]], dims=2))\n @test std(x) ≈ vec(std([x[1] x[2]], dims=2))\n @test cov(x) ≈ cov([x[1] x[2]], dims=2)\nend",
"@testset \"var of sparse array\" begin\n se33 = SparseMatrixCSC{Float64}(I, 3, 3)\n sA = sprandn(3, 7, 0.5)\n pA = sparse(rand(3, 7))\n\n for arr in (se33, sA, pA)\n farr = Array(arr)\n @test var(arr) ≈ var(farr)\n @test var(arr, dims=1) ≈ var(farr, dims=1)\n @test var(arr, dims=2) ≈ var(farr, dims=2)\n @test var(arr, dims=(1, 2)) ≈ [var(farr)]\n @test isequal(var(arr, dims=3), var(farr, dims=3))\n end\n\n @testset \"empty cases\" begin\n @test var(sparse(Int[])) === NaN\n @test isequal(var(spzeros(0, 1), dims=1), var(Matrix{Int}(I, 0, 1), dims=1))\n @test isequal(var(spzeros(0, 1), dims=2), var(Matrix{Int}(I, 0, 1), dims=2))\n @test isequal(var(spzeros(0, 1), dims=(1, 2)), var(Matrix{Int}(I, 0, 1), dims=(1, 2)))\n @test isequal(var(spzeros(0, 1), dims=3), var(Matrix{Int}(I, 0, 1), dims=3))\n end\nend",
"@testset \"optimizing sparse $elty covariance\" for elty in (Float64, Complex{Float64})\n n = 10\n p = 5\n np2 = div(n*p, 2)\n nzvals, x_sparse = guardseed(1) do\n if elty <: Real\n nzvals = randn(np2)\n else\n nzvals = complex.(randn(np2), randn(np2))\n end\n nzvals, sparse(rand(1:n, np2), rand(1:p, np2), nzvals, n, p)\n end\n x_dense = convert(Matrix{elty}, x_sparse)\n @testset \"Test with no Infs and NaNs, vardim=$vardim, corrected=$corrected\" for vardim in (1, 2),\n corrected in (true, false)\n @test cov(x_sparse, dims=vardim, corrected=corrected) ≈\n cov(x_dense , dims=vardim, corrected=corrected)\n end\n\n @testset \"Test with $x11, vardim=$vardim, corrected=$corrected\" for x11 in (NaN, Inf),\n vardim in (1, 2),\n corrected in (true, false)\n x_sparse[1,1] = x11\n x_dense[1 ,1] = x11\n\n cov_sparse = cov(x_sparse, dims=vardim, corrected=corrected)\n cov_dense = cov(x_dense , dims=vardim, corrected=corrected)\n @test cov_sparse[2:end, 2:end] ≈ cov_dense[2:end, 2:end]\n @test isfinite.(cov_sparse) == isfinite.(cov_dense)\n @test isfinite.(cov_sparse) == isfinite.(cov_dense)\n end\n\n @testset \"Test with NaN and Inf, vardim=$vardim, corrected=$corrected\" for vardim in (1, 2),\n corrected in (true, false)\n x_sparse[1,1] = Inf\n x_dense[1 ,1] = Inf\n x_sparse[2,1] = NaN\n x_dense[2 ,1] = NaN\n\n cov_sparse = cov(x_sparse, dims=vardim, corrected=corrected)\n cov_dense = cov(x_dense , dims=vardim, corrected=corrected)\n @test cov_sparse[(1 + vardim):end, (1 + vardim):end] ≈\n cov_dense[ (1 + vardim):end, (1 + vardim):end]\n @test isfinite.(cov_sparse) == isfinite.(cov_dense)\n @test isfinite.(cov_sparse) == isfinite.(cov_dense)\n end\nend"
] |
f720458e4c141a29498437c4c4276797a74a93c1
| 1,913
|
jl
|
Julia
|
test/runtests.jl
|
JuliaGeo/GDAL.jl
|
3838e938642712cf8a98c52df5937dcfdb19221e
|
[
"MIT"
] | 61
|
2018-07-30T12:45:24.000Z
|
2022-03-31T20:23:46.000Z
|
test/runtests.jl
|
JuliaGeo/GDAL.jl
|
3838e938642712cf8a98c52df5937dcfdb19221e
|
[
"MIT"
] | 67
|
2018-06-11T15:59:17.000Z
|
2022-03-02T21:42:54.000Z
|
test/runtests.jl
|
JuliaGeo/GDAL.jl
|
3838e938642712cf8a98c52df5937dcfdb19221e
|
[
"MIT"
] | 14
|
2018-12-03T22:05:51.000Z
|
2021-09-30T10:58:04.000Z
|
using GDAL
using Test
@testset "GDAL" begin
# drivers
# before being able to use any drivers, they must be registered first
GDAL.gdalallregister()
version = GDAL.gdalversioninfo("--version")
n_gdal_driver = GDAL.gdalgetdrivercount()
n_ogr_driver = GDAL.ogrgetdrivercount()
@info """$version
$n_gdal_driver GDAL drivers found
$n_ogr_driver OGR drivers found
"""
@test n_gdal_driver > 0
@test n_ogr_driver > 0
srs = GDAL.osrnewspatialreference(C_NULL)
GDAL.osrimportfromepsg(srs, 4326) # fails if GDAL_DATA is not set correctly
xmlnode_pointer = GDAL.cplparsexmlstring("<a><b>hi</b></a>")
@test GDAL.cplgetxmlvalue(xmlnode_pointer, "b", "") == "hi"
# load into Julia struct, mutate, and put back as Ref into GDAL
xmlnode = unsafe_load(xmlnode_pointer)
@test GDAL.cplserializexmltree(Ref(xmlnode)) == "<a>\n <b>hi</b>\n</a>\n"
GDAL.cpldestroyxmlnode(xmlnode_pointer)
# ref https://github.com/JuliaGeo/GDAL.jl/pull/41#discussion_r143345433
gfld = GDAL.ogr_gfld_create("name-a", GDAL.wkbPoint)
@test gfld isa GDAL.OGRGeomFieldDefnH
@test GDAL.ogr_gfld_getnameref(gfld) == "name-a"
@test GDAL.ogr_gfld_gettype(gfld) == GDAL.wkbPoint
# same as above but for the lower level C API
gfld = GDAL.ogr_gfld_create("name-b", GDAL.wkbPolygon)
@test gfld isa Ptr{GDAL.OGRGeomFieldDefnHS}
@test GDAL.ogr_gfld_getnameref(gfld) == "name-b"
@test GDAL.ogr_gfld_gettype(gfld) == GDAL.wkbPolygon
cd(dirname(@__FILE__)) do
rm("tmp", recursive = true, force = true)
mkpath("tmp") # ensure it exists
include("tutorial_raster.jl")
include("tutorial_vector.jl")
include("tutorial_vrt.jl")
include("gdal_utils.jl")
include("gdal_jll_utils.jl")
include("drivers.jl")
include("error.jl")
end
GDAL.gdaldestroydrivermanager()
end
| 33.561404
| 79
| 0.679038
|
[
"@testset \"GDAL\" begin\n\n # drivers\n # before being able to use any drivers, they must be registered first\n GDAL.gdalallregister()\n\n version = GDAL.gdalversioninfo(\"--version\")\n n_gdal_driver = GDAL.gdalgetdrivercount()\n n_ogr_driver = GDAL.ogrgetdrivercount()\n @info \"\"\"$version\n $n_gdal_driver GDAL drivers found\n $n_ogr_driver OGR drivers found\n \"\"\"\n\n @test n_gdal_driver > 0\n @test n_ogr_driver > 0\n\n srs = GDAL.osrnewspatialreference(C_NULL)\n GDAL.osrimportfromepsg(srs, 4326) # fails if GDAL_DATA is not set correctly\n\n xmlnode_pointer = GDAL.cplparsexmlstring(\"<a><b>hi</b></a>\")\n @test GDAL.cplgetxmlvalue(xmlnode_pointer, \"b\", \"\") == \"hi\"\n # load into Julia struct, mutate, and put back as Ref into GDAL\n xmlnode = unsafe_load(xmlnode_pointer)\n @test GDAL.cplserializexmltree(Ref(xmlnode)) == \"<a>\\n <b>hi</b>\\n</a>\\n\"\n GDAL.cpldestroyxmlnode(xmlnode_pointer)\n\n # ref https://github.com/JuliaGeo/GDAL.jl/pull/41#discussion_r143345433\n gfld = GDAL.ogr_gfld_create(\"name-a\", GDAL.wkbPoint)\n @test gfld isa GDAL.OGRGeomFieldDefnH\n @test GDAL.ogr_gfld_getnameref(gfld) == \"name-a\"\n @test GDAL.ogr_gfld_gettype(gfld) == GDAL.wkbPoint\n # same as above but for the lower level C API\n gfld = GDAL.ogr_gfld_create(\"name-b\", GDAL.wkbPolygon)\n @test gfld isa Ptr{GDAL.OGRGeomFieldDefnHS}\n @test GDAL.ogr_gfld_getnameref(gfld) == \"name-b\"\n @test GDAL.ogr_gfld_gettype(gfld) == GDAL.wkbPolygon\n\n cd(dirname(@__FILE__)) do\n rm(\"tmp\", recursive = true, force = true)\n mkpath(\"tmp\") # ensure it exists\n include(\"tutorial_raster.jl\")\n include(\"tutorial_vector.jl\")\n include(\"tutorial_vrt.jl\")\n include(\"gdal_utils.jl\")\n include(\"gdal_jll_utils.jl\")\n include(\"drivers.jl\")\n include(\"error.jl\")\n end\n\n GDAL.gdaldestroydrivermanager()\n\nend"
] |
f7215512da0154c3cb3b231e83d4d4e0ca40097a
| 2,666
|
jl
|
Julia
|
test/test_fileio.jl
|
chenspc/OWEN.jl
|
842c8672dbc001180d980430e20652101929f32f
|
[
"MIT"
] | null | null | null |
test/test_fileio.jl
|
chenspc/OWEN.jl
|
842c8672dbc001180d980430e20652101929f32f
|
[
"MIT"
] | 2
|
2019-11-13T23:18:11.000Z
|
2020-02-08T16:40:57.000Z
|
test/test_fileio.jl
|
chenspc/OWEN.jl
|
842c8672dbc001180d980430e20652101929f32f
|
[
"MIT"
] | 1
|
2020-02-08T10:46:07.000Z
|
2020-02-08T10:46:07.000Z
|
using Kahuna
using Test
@testset "kahuna_read" begin
@testset ".dm3 files" begin
@test 2 + 2 == 4
end
@testset ".dm4 files" begin
@test 2 + 2 == 4
end
@testset ".hdf5/.h5 files" begin
@test 2 + 2 == 4
end
@testset ".mat files" begin
# matfile = "test/sample_files/test_fileio_mat.mat";
matfile = "sample_files/test_fileio_mat.mat";
@test typeof(kahuna_read(matfile, "mat0d")) == Float64
@test typeof(kahuna_read(matfile, "mat1d")) == Array{Float64,2} && size(kahuna_read(matfile, "mat1d")) == (1,10)
@test typeof(kahuna_read(matfile, "mat2d")) == Array{Float64,2} && size(kahuna_read(matfile, "mat2d")) == (10,10)
@test typeof(kahuna_read(matfile, "mat3d")) == Array{Float64,3} && size(kahuna_read(matfile, "mat3d")) == (10,10,10)
@test typeof(kahuna_read(matfile, "mat4d")) == Array{Float64,4} && size(kahuna_read(matfile, "mat4d")) == (10,10,10,10)
@test kahuna_read(matfile; mode="list") == Set(["mat0d", "mat1d", "mat2d", "mat4d", "mat3d"])
@test kahuna_read(matfile) == Dict(map(x -> x => kahuna_read(matfile, x), collect(kahuna_read(matfile; mode="list"))))
end
@testset ".mib files" begin
mibfile512_12bit = "sample_files/test_512_12bit_single.mib";
# mibfiles = [mibfile256_1bit, mibfile256_6bit, mibfile256_12bit,
# mibfile256_1bit_raw, mibfile256_6bit_raw, mibfile256_12bit_raw,
# mibfile512_1bit, mibfile512_6bit, mibfile512_12bit,
# mibfile512_1bit_raw, mibfile512_6bit_raw, mibfile512_12bit_raw];
mibfiles = [mibfile512_12bit]
for mibfile in mibfiles
mib_images, mib_headers = kahuna_read(mibfile)
@test typeof(mib_images) == Array{Array{UInt16,2},1}
@test typeof(mib_headers) == Array{MIBHeader,1}
# @test typeof(kahuna_read(mibfile, [1, 10])) == Array{Float64,2} && size(kahuna_read(mibfile, [1, 10])) == (1,10)
# @test typeof(kahuna_read(mibfile, [1, 10])) == Array{Float64,2} && size(kahuna_read(mibfile, [1, 10])) == (10,10)
# @test typeof(kahuna_read(mibfile, [1, 10])) == Array{Float64,2} && size(kahuna_read(mibfile, [1, 10])) == (10,10)
end
end
@testset ".toml files" begin
@test 2 + 2 == 4
end
@testset ".jld files" begin
@test 2 + 2 == 4
end
end
@testset "kahuna_write" begin
@testset ".hdf5/.h5 files" begin
@test 2 + 2 == 4
end
@testset ".toml files" begin
@test 2 + 2 == 4
end
@testset ".jld files" begin
@test 2 + 2 == 4
end
end
| 33.746835
| 127
| 0.594524
|
[
"@testset \"kahuna_read\" begin\n\n @testset \".dm3 files\" begin\n @test 2 + 2 == 4\n end\n\n @testset \".dm4 files\" begin\n @test 2 + 2 == 4\n end\n\n @testset \".hdf5/.h5 files\" begin\n @test 2 + 2 == 4\n end\n\n @testset \".mat files\" begin\n # matfile = \"test/sample_files/test_fileio_mat.mat\";\n matfile = \"sample_files/test_fileio_mat.mat\";\n @test typeof(kahuna_read(matfile, \"mat0d\")) == Float64\n @test typeof(kahuna_read(matfile, \"mat1d\")) == Array{Float64,2} && size(kahuna_read(matfile, \"mat1d\")) == (1,10)\n @test typeof(kahuna_read(matfile, \"mat2d\")) == Array{Float64,2} && size(kahuna_read(matfile, \"mat2d\")) == (10,10)\n @test typeof(kahuna_read(matfile, \"mat3d\")) == Array{Float64,3} && size(kahuna_read(matfile, \"mat3d\")) == (10,10,10)\n @test typeof(kahuna_read(matfile, \"mat4d\")) == Array{Float64,4} && size(kahuna_read(matfile, \"mat4d\")) == (10,10,10,10)\n\n @test kahuna_read(matfile; mode=\"list\") == Set([\"mat0d\", \"mat1d\", \"mat2d\", \"mat4d\", \"mat3d\"])\n\n @test kahuna_read(matfile) == Dict(map(x -> x => kahuna_read(matfile, x), collect(kahuna_read(matfile; mode=\"list\"))))\n end\n\n @testset \".mib files\" begin\n\n mibfile512_12bit = \"sample_files/test_512_12bit_single.mib\";\n\n # mibfiles = [mibfile256_1bit, mibfile256_6bit, mibfile256_12bit,\n # mibfile256_1bit_raw, mibfile256_6bit_raw, mibfile256_12bit_raw,\n # mibfile512_1bit, mibfile512_6bit, mibfile512_12bit,\n # mibfile512_1bit_raw, mibfile512_6bit_raw, mibfile512_12bit_raw];\n mibfiles = [mibfile512_12bit]\n\n for mibfile in mibfiles\n mib_images, mib_headers = kahuna_read(mibfile)\n @test typeof(mib_images) == Array{Array{UInt16,2},1}\n @test typeof(mib_headers) == Array{MIBHeader,1}\n # @test typeof(kahuna_read(mibfile, [1, 10])) == Array{Float64,2} && size(kahuna_read(mibfile, [1, 10])) == (1,10)\n # @test typeof(kahuna_read(mibfile, [1, 10])) == Array{Float64,2} && size(kahuna_read(mibfile, [1, 10])) == (10,10)\n # @test typeof(kahuna_read(mibfile, [1, 10])) == Array{Float64,2} && size(kahuna_read(mibfile, [1, 10])) == (10,10)\n end\n\n end\n\n @testset \".toml files\" begin\n @test 2 + 2 == 4\n end\n\n @testset \".jld files\" begin\n @test 2 + 2 == 4\n end\n\n\nend",
"@testset \"kahuna_write\" begin\n\n @testset \".hdf5/.h5 files\" begin\n @test 2 + 2 == 4\n end\n\n @testset \".toml files\" begin\n @test 2 + 2 == 4\n end\n\n @testset \".jld files\" begin\n @test 2 + 2 == 4\n end\n\nend"
] |
f7262dc1d65caed99f539aa39adc09adecee3524
| 1,713
|
jl
|
Julia
|
test/simple_runner_tests.jl
|
grahamstark/ScottishTaxBenefitModel.jl
|
42ca32a100c862c58bbcd98f6264f08d78453b5c
|
[
"MIT"
] | null | null | null |
test/simple_runner_tests.jl
|
grahamstark/ScottishTaxBenefitModel.jl
|
42ca32a100c862c58bbcd98f6264f08d78453b5c
|
[
"MIT"
] | null | null | null |
test/simple_runner_tests.jl
|
grahamstark/ScottishTaxBenefitModel.jl
|
42ca32a100c862c58bbcd98f6264f08d78453b5c
|
[
"MIT"
] | null | null | null |
using Test
using CSV
using DataFrames
using StatsBase
using BenchmarkTools
using ScottishTaxBenefitModel
using ScottishTaxBenefitModel.GeneralTaxComponents
using ScottishTaxBenefitModel.STBParameters
using ScottishTaxBenefitModel.Runner: do_one_run!
using ScottishTaxBenefitModel.RunSettings: Settings, MT_Routing
using .Utils
using .ExampleHelpers
settings = Settings()
BenchmarkTools.DEFAULT_PARAMETERS.seconds = 120
BenchmarkTools.DEFAULT_PARAMETERS.samples = 2
function basic_run( ; print_test :: Bool, mtrouting :: MT_Routing )
settings.means_tested_routing = mtrouting
settings.run_name="run-$(mtrouting)-$(date_string())"
sys = [get_system(scotland=false), get_system( scotland=true )]
results = do_one_run!( settings, sys )
end
@testset "basic run timing" begin
for mt in instances( MT_Routing )
println( "starting run using $mt routing")
@time basic_run( print_test=true, mtrouting = mt )
end
# @benchmark frames =
# print(t)
end
#=
if print_test
summary_output = summarise_results!( results=results, base_results=base_results )
print( " deciles = $( summary_output.deciles)\n\n" )
print( " poverty_line = $(summary_output.poverty_line)\n\n" )
print( " inequality = $(summary_output.inequality)\n\n" )
print( " poverty = $(summary_output.poverty)\n\n" )
print( " gainlose_by_sex = $(summary_output.gainlose_by_sex)\n\n" )
print( " gainlose_by_thing = $(summary_output.gainlose_by_thing)\n\n" )
print( " metr_histogram= $(summary_output.metr_histogram)\n\n")
println( "SUMMARY OUTPUT")
println( summary_output )
println( "as JSON")
println( JSON.json( summary_output ))
end
=#
| 32.320755
| 85
| 0.725044
|
[
"@testset \"basic run timing\" begin\n for mt in instances( MT_Routing )\n println( \"starting run using $mt routing\")\n @time basic_run( print_test=true, mtrouting = mt )\n end\n # @benchmark frames = \n # print(t)\nend"
] |
f727f80483dbefe80bf5db5ac82e2786aea040ee
| 1,036
|
jl
|
Julia
|
test/runtests.jl
|
mauro3/course-101-0250-00-L6Testing.jl
|
c7d47e770d5eabbf7f28784f9a9bd279a3042af8
|
[
"MIT"
] | 1
|
2022-03-01T09:48:55.000Z
|
2022-03-01T09:48:55.000Z
|
test/runtests.jl
|
mauro3/course-101-0250-00-L6Testing.jl
|
c7d47e770d5eabbf7f28784f9a9bd279a3042af8
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
mauro3/course-101-0250-00-L6Testing.jl
|
c7d47e770d5eabbf7f28784f9a9bd279a3042af8
|
[
"MIT"
] | 1
|
2021-11-02T10:16:55.000Z
|
2021-11-02T10:16:55.000Z
|
using Test, ReferenceTests, BSON
include("../scripts/car_travels.jl")
## Unit tests
@testset "update_position" begin
@test update_position(0.0, 10, 1, 1, 200)[1] ≈ 10.0
@test update_position(0.0, 10, 1, 1, 200)[2] == 1
@test update_position(0.0, 10, -1, 1, 200)[1] ≈ -10.0
@test update_position(0.0, 10, -1, 1, 200)[2] == 1
@test update_position(0.0, 10, -1, 1, 200)[1] ≈ -10.0
@test update_position(0.0, 10, -1, 1, 200)[2] == 1
end
## Reference Tests with ReferenceTests.jl
# We put both arrays X and T into a BSON.jl and then compare them
"Compare all dict entries"
comp(d1, d2) = keys(d1) == keys(d2) &&
all([ v1≈v2 for (v1,v2) in zip(values(d1), values(d2))])
# run the model
T, X = car_travel_1D()
# Test just at some random indices. As for larger models,
# storing the full output array would create really large files!
inds = [18, 27, 45, 68, 71, 71, 102, 110, 123, 144]
d = Dict(:X=> X[inds], :T=>T[inds])
@testset "Ref-tests" begin
@test_reference "reftest-files/X.bson" d by=comp
end
| 28.777778
| 65
| 0.642857
|
[
"@testset \"update_position\" begin\n @test update_position(0.0, 10, 1, 1, 200)[1] ≈ 10.0\n @test update_position(0.0, 10, 1, 1, 200)[2] == 1\n\n @test update_position(0.0, 10, -1, 1, 200)[1] ≈ -10.0\n @test update_position(0.0, 10, -1, 1, 200)[2] == 1\n\n @test update_position(0.0, 10, -1, 1, 200)[1] ≈ -10.0\n @test update_position(0.0, 10, -1, 1, 200)[2] == 1\nend",
"@testset \"Ref-tests\" begin\n @test_reference \"reftest-files/X.bson\" d by=comp\nend"
] |
f72e3f7fe6055a37c495d6361bfec1323eaa14a6
| 89
|
jl
|
Julia
|
test/runtests.jl
|
Shoram444/MPThemes.jl
|
86a6699f70a3b7f77d6ae6a248b285cb46f26852
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
Shoram444/MPThemes.jl
|
86a6699f70a3b7f77d6ae6a248b285cb46f26852
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
Shoram444/MPThemes.jl
|
86a6699f70a3b7f77d6ae6a248b285cb46f26852
|
[
"MIT"
] | null | null | null |
using MPThemes
using Test
@testset "MPThemes.jl" begin
# Write your tests here.
end
| 12.714286
| 28
| 0.730337
|
[
"@testset \"MPThemes.jl\" begin\n # Write your tests here.\nend"
] |
f72eb56564b1565aeb3c77581bcff74072f7b438
| 14,033
|
jl
|
Julia
|
test/runtests.jl
|
Physics-Simulations/UncValue.jl
|
0597853fc2951732d2c8e5cc1625e075de08b7b5
|
[
"Apache-2.0"
] | null | null | null |
test/runtests.jl
|
Physics-Simulations/UncValue.jl
|
0597853fc2951732d2c8e5cc1625e075de08b7b5
|
[
"Apache-2.0"
] | null | null | null |
test/runtests.jl
|
Physics-Simulations/UncValue.jl
|
0597853fc2951732d2c8e5cc1625e075de08b7b5
|
[
"Apache-2.0"
] | null | null | null |
using Test
using Statistics
include("../src/UncValue.jl")
using ..UncValue
a = Value(3.1415, 0.0012)
b = Value(2.7182818, 3.4e-6)
c = Value(36458.246, 25.64)
@testset "constructor" begin
@test a.x == 3.1415
@test a.σ == 0.0012
@test_throws ErrorException Value(4.1, -2.4)
d = Value(5.248)
@test d.x == 5.248
@test d.σ == 0
d = Value(8.0, 1)
@test typeof(d.x) == typeof(d.σ)
d = Value(8, 0.2)
@test typeof(d.x) == typeof(d.σ)
end
@testset "precision" begin
@test precision(a) == -4
@test precision(b) == -7
@test precision(c) == 0
end
@testset "addition" begin
@test typeof(a + 2) <: Value
@test typeof(2 + a) <: Value
s = a + b
@test typeof(s) <: Value
@test s.x == (a.x + b.x)
@test s.σ ≈ hypot(a.σ, b.σ)
n = -a
@test typeof(n) <: Value
@test n.x == (-a.x)
@test n.σ == a.σ
end
@testset "substraction" begin
@test typeof(a - 2) <: Value
@test typeof(2 - a) <: Value
s = a - b
@test typeof(s) <: Value
@test s.x ≈ (a.x - b.x)
@test s.σ ≈ hypot(a.σ, b.σ)
end
@testset "product" begin
@test typeof(a * 2) <: Value
@test typeof(2 * a) <: Value
s = a * b
@test typeof(s) <: Value
@test s.x ≈ (a.x * b.x)
@test s.σ ≈ hypot(a.σ * b.x, a.x * b.σ)
end
@testset "division" begin
@test typeof(a / 2) <: Value
@test typeof(2 / a) <: Value
s = a / b
@test typeof(s) <: Value
@test s.x ≈ (a.x / b.x)
@test s.σ ≈ hypot(a.σ / b.x, a.x * b.σ / b.x^2)
end
@testset "left division" begin
s = a \ 2
@test typeof(s) <: Value
@test s.x ≈ (a.x \ 2)
@test s.σ ≈ a.x^2 \ 2 * a.σ
s = 2 \ a
@test typeof(s) <: Value
@test s.x ≈ (2 \ a.x)
@test s.σ ≈ 2 \ a.σ
s = a \ b
@test typeof(s) <: Value
@test s.x ≈ (a.x \ b.x)
@test s.σ ≈ hypot(a.x \ b.σ, a.x^2 \ b.x * a.σ)
end
@testset "integer division" begin
j = Value{Int32}(2, 1)
k = Value{Int32}(7, 2)
s = j ÷ k.x
@test typeof(s) <: Value
@test s.x ≈ j.x ÷ k.x
@test s.σ ≈ j.σ ÷ k.x
s = k.x ÷ j
@test typeof(s) <: Value
@test s.x ≈ k.x ÷ j.x
@test s.σ ≈ k.x * j.σ ÷ j.x^2
s = k ÷ j
@test typeof(s) <: Value
@test s.x ≈ k.x ÷ j.x
@test s.σ ≈ hypot(k.x * j.σ ÷ j.x^2, j.σ ÷ k.x)
s = fld(j, k.x)
@test typeof(s) <: Value
@test s.x ≈ fld(j.x, k.x)
@test s.σ ≈ fld(j.σ, k.x)
s = fld(k.x, j)
@test typeof(s) <: Value
@test s.x ≈ fld(k.x, j.x)
@test s.σ ≈ fld(k.x * j.σ, j.x^2)
s = fld(k, j)
@test typeof(s) <: Value
@test s.x ≈ fld(k.x, j.x)
@test s.σ ≈ floor(hypot(fld(k.x * j.σ, j.x^2), fld(j.σ, k.x)))
s = cld(j, k.x)
@test typeof(s) <: Value
@test s.x ≈ cld(j.x, k.x)
@test s.σ ≈ cld(j.σ, k.x)
s = cld(k.x, j)
@test typeof(s) <: Value
@test s.x ≈ cld(k.x, j.x)
@test s.σ ≈ cld(k.x * j.σ, j.x^2)
s = cld(k, j)
@test typeof(s) <: Value
@test s.x ≈ cld(k.x, j.x)
@test s.σ ≈ ceil(hypot(cld(k.x * j.σ, j.x^2), cld(j.σ, k.x)))
end
@testset "power" begin
@test typeof(a^3) <: Value
@test typeof(3^a) <: Value
s = a^b
@test typeof(s) <: Value
@test s.x ≈ a.x^b.x
@test s.σ ≈ hypot(b.x * a.x^(b.x-1) * a.σ, a.x^b.x * log(abs(a.x)) * b.σ)
end
@testset "equality" begin
@test a == 3.1415
@test (a == 3.141) == false
@test a != 3.141
@test 3.1415 == a
@test (3.141 == a) == false
@test 3.141 != a
@test (a == b) == false
@test a != b
end
@testset "inequality" begin
@test a < 3.1416
@test (a < 3.141) == false
@test 3.1416 > a
@test (3.141 > a) == false
@test a <= 3.1415
@test a <= 3.1416
@test (a <= 3.141) == false
@test 3.1416 >= a
@test 3.1415 >= a
@test (3.141 >= a) == false
@test a > 3.141
@test (a > 3.1416) == false
@test 3.141 < a
@test (3.1416 < a) == false
@test a >= 3.1415
@test a >= 3.1414
@test (a >= 3.1416) == false
@test 3.1414 <= a
@test 3.1415 <= a
@test (3.146 <= a) == false
@test a > b
@test b < a
@test a >= a
@test a >= b
@test (b >= a) == false
@test a <= a
@test b <= a
@test (a <= b) == false
end
@testset "abs" begin
s = abs(a)
@test typeof(s) <: Value
@test s.x == a.x
@test s.σ == a.σ
s = abs(-a)
@test s.x == a.x
@test s.σ == a.σ
end
@testset "abs2" begin
s = abs2(a)
@test typeof(s) <: Value
@test s.x == a.x^2
@test s.σ == 2 * a.x * a.σ
s = abs2(-a)
@test s.x == a.x^2
@test s.σ == 2 * a.x * a.σ
end
@testset "sin/cos/tan" begin
s = sin(b)
@test typeof(s) <: Value
@test s.x ≈ sin(b.x)
@test s.σ ≈ abs(cos(b.x)) * b.σ
c = cos(b)
@test typeof(c) <: Value
@test c.x ≈ cos(b.x)
@test c.σ ≈ abs(sin(b.x)) * b.σ
t = tan(b)
@test typeof(t) <: Value
@test t.x ≈ tan(b.x)
@test t.σ ≈ sec(b.x)^2 * b.σ
end
@testset "sind/cosd/tand" begin
s = sind(b)
@test typeof(s) <: Value
@test s.x ≈ sind(b.x)
@test s.σ ≈ abs(cosd(b.x)) * b.σ
c = cosd(b)
@test typeof(c) <: Value
@test c.x ≈ cosd(b.x)
@test c.σ ≈ abs(sind(b.x)) * b.σ
t = tand(b)
@test typeof(t) <: Value
@test t.x ≈ tand(b.x)
@test t.σ ≈ secd(b.x)^2 * b.σ
end
@testset "sinh/cosh/tanh" begin
s = sinh(b)
@test typeof(s) <: Value
@test s.x ≈ sinh(b.x)
@test s.σ ≈ cosh(b.x) * b.σ
c = cosh(b)
@test typeof(c) <: Value
@test c.x ≈ cosh(b.x)
@test c.σ ≈ abs(sinh(b.x)) * b.σ
t = tanh(b)
@test typeof(t) <: Value
@test t.x ≈ tanh(b.x)
@test t.σ ≈ sech(b.x)^2 * b.σ
end
@testset "sinpi/cospi" begin
s = sinpi(b)
@test typeof(s) <: Value
@test s.x ≈ sinpi(b.x)
@test s.σ ≈ π * abs(cospi(b.x)) * b.σ
c = cospi(b)
@test typeof(c) <: Value
@test c.x ≈ cospi(b.x)
@test c.σ ≈ π * abs(sinpi(b.x)) * b.σ
end
@testset "asin/acos/atan" begin
d = Value(0.2435, 0.0658)
s = asin(d)
@test typeof(s) <: Value
@test s.x ≈ asin(d.x)
@test s.σ ≈ d.σ / sqrt(1 - d.x^2)
c = acos(d)
@test typeof(c) <: Value
@test c.x ≈ acos(d.x)
@test c.σ ≈ d.σ / sqrt(1 - d.x^2)
t = atan(d)
@test typeof(t) <: Value
@test t.x ≈ atan(d.x)
@test t.σ ≈ d.σ / (1 + d.x^2)
t = atan(a, b)
@test t.x ≈ atan(a.x, b.x)
@test t.σ ≈ hypot(b.x * a.σ, a.x * b.σ) / hypot(a.x, b.x)^2
t = atan(a, 0.1)
@test t.x ≈ atan(a.x, 0.1)
@test t.σ ≈ 0.1 * a.σ / hypot(a.x, 0.1)^2
t = atan(0.1, a)
@test t.x ≈ atan(0.1, a.x)
@test t.σ ≈ 0.1 * a.σ / hypot(a.x, 0.1)^2
end
@testset "asind/acosd/atand" begin
d = Value(0.2435, 0.0658)
s = asind(d)
@test typeof(s) <: Value
@test s.x ≈ asind(d.x)
@test s.σ ≈ d.σ / sqrt(1 - d.x^2)
c = acosd(d)
@test typeof(c) <: Value
@test c.x ≈ acosd(d.x)
@test c.σ ≈ d.σ / sqrt(1 - d.x^2)
t = atand(d)
@test typeof(t) <: Value
@test t.x ≈ atand(d.x)
@test t.σ ≈ d.σ / (1 + d.x^2)
t = atand(a, b)
@test t.x ≈ atand(a.x, b.x)
@test t.σ ≈ hypot(b.x * a.σ, a.x * b.σ) / hypot(a.x, b.x)^2
t = atand(a, 0.1)
@test t.x ≈ atand(a.x, 0.1)
@test t.σ ≈ 0.1 * a.σ / hypot(a.x, 0.1)^2
t = atand(0.1, a)
@test t.x ≈ atand(0.1, a.x)
@test t.σ ≈ 0.1 * a.σ / hypot(a.x, 0.1)^2
end
@testset "asinh/acosh/atanh" begin
d = Value(1.2435, 0.0658)
s = asinh(d)
@test typeof(s) <: Value
@test s.x ≈ asinh(d.x)
@test s.σ ≈ d.σ / sqrt(1 + d.x^2)
c = acosh(d)
@test typeof(c) <: Value
@test c.x ≈ acosh(d.x)
@test c.σ ≈ d.σ / sqrt(d.x^2 - 1)
d -= 1
t = atanh(d)
@test typeof(t) <: Value
@test t.x ≈ atanh(d.x)
@test t.σ ≈ d.σ / (1 - d.x^2)
end
@testset "csc/sec/cot" begin
s = csc(b)
@test typeof(s) <: Value
@test s.x ≈ csc(b.x)
@test s.σ ≈ abs(cot(b.x) * csc(b.x)) * b.σ
c = sec(b)
@test typeof(c) <: Value
@test c.x ≈ sec(b.x)
@test c.σ ≈ abs(tan(b.x) * sec(b.x)) * b.σ
t = cot(b)
@test typeof(t) <: Value
@test t.x ≈ cot(b.x)
@test t.σ ≈ csc(b.x)^2 * b.σ
end
@testset "cscd/secd/cotd" begin
s = cscd(b)
@test typeof(s) <: Value
@test s.x ≈ cscd(b.x)
@test s.σ ≈ abs(cotd(b.x) * cscd(b.x)) * b.σ
c = secd(b)
@test typeof(c) <: Value
@test c.x ≈ secd(b.x)
@test c.σ ≈ abs(tand(b.x) * secd(b.x)) * b.σ
t = cotd(b)
@test typeof(t) <: Value
@test t.x ≈ cotd(b.x)
@test t.σ ≈ cscd(b.x)^2 * b.σ
end
@testset "csch/sech/coth" begin
s = csch(b)
@test typeof(s) <: Value
@test s.x ≈ csch(b.x)
@test s.σ ≈ abs(coth(b.x) * csch(b.x)) * b.σ
c = sech(b)
@test typeof(c) <: Value
@test c.x ≈ sech(b.x)
@test c.σ ≈ abs(tanh(b.x) * sech(b.x)) * b.σ
t = coth(b)
@test typeof(t) <: Value
@test t.x ≈ coth(b.x)
@test t.σ ≈ csch(b.x)^2 * b.σ
end
@testset "acsc/asec/acot" begin
s = acsc(b)
@test typeof(s) <: Value
@test s.x ≈ acsc(b.x)
@test s.σ ≈ b.σ / sqrt(b.x^2 - 1)
c = asec(b)
@test typeof(c) <: Value
@test c.x ≈ asec(b.x)
@test c.σ ≈ b.σ / sqrt(b.x^2 - 1)
t = acot(b)
@test typeof(t) <: Value
@test t.x ≈ acot(b.x)
@test t.σ ≈ b.σ / (1 + b.x^2)
end
@testset "acscd/asecd/acotd" begin
s = acscd(b)
@test typeof(s) <: Value
@test s.x ≈ acscd(b.x)
@test s.σ ≈ b.σ / sqrt(b.x^2 - 1)
c = asecd(b)
@test typeof(c) <: Value
@test c.x ≈ asecd(b.x)
@test c.σ ≈ b.σ / sqrt(b.x^2 - 1)
t = acotd(b)
@test typeof(t) <: Value
@test t.x ≈ acotd(b.x)
@test t.σ ≈ b.σ / (1 + b.x^2)
end
@testset "acsch/asech/acoth" begin
d = Value(0.12435, 0.0658)
s = acsch(b)
@test typeof(s) <: Value
@test s.x ≈ acsch(b.x)
@test s.σ ≈ b.σ / sqrt(b.x^2 + 1)
c = asech(d)
@test typeof(c) <: Value
@test c.x ≈ asech(d.x)
@test c.σ ≈ d.σ / sqrt(1 - d.x^2)
t = acoth(b)
@test typeof(t) <: Value
@test t.x ≈ acoth(b.x)
@test t.σ ≈ b.σ / abs(1 - b.x^2)
end
@testset "deg2rad" begin
d = deg2rad(a)
@test typeof(d) <: Value
@test d.x == deg2rad(a.x)
@test d.σ == deg2rad(a.σ)
d = rad2deg(a)
@test typeof(d) <: Value
@test d.x == rad2deg(a.x)
@test d.σ == rad2deg(a.σ)
end
@testset "exp" begin
r = exp(a)
@test typeof(r) <: Value
@test r.x == exp(a.x)
@test r.σ ≈ r.x * a.σ
r = exp2(a)
@test typeof(r) <: Value
@test r.x == exp2(a.x)
@test r.σ ≈ r.x * a.σ * log(2)
r = exp10(a)
@test typeof(r) <: Value
@test r.x == exp10(a.x)
@test r.σ ≈ r.x * a.σ * log(10)
end
@testset "log" begin
r = log(a)
@test typeof(r) <: Value
@test r.x == log(a.x)
@test r.σ ≈ a.σ / a.x
r = log2(a)
@test typeof(r) <: Value
@test r.x == log2(a.x)
@test r.σ ≈ a.σ / (a.x * log(2))
r = log10(a)
@test typeof(r) <: Value
@test r.x == log10(a.x)
@test r.σ ≈ a.σ / (a.x * log(10))
r = log(3, a)
@test typeof(r) <: Value
@test r.x == log(3, a.x)
@test r.σ ≈ a.σ / (a.x * log(3))
r = log1p(a)
@test typeof(r) <: Value
@test r.x == log1p(a.x)
@test r.σ ≈ a.σ / (a.x + 1)
end
@testset "roots" begin
r = sqrt(a)
@test typeof(r) <: Value
@test r.x == sqrt(a.x)
@test r.σ == a.σ / (2 * sqrt(a.x))
r = cbrt(a)
@test typeof(r) <: Value
@test r.x == cbrt(a.x)
@test r.σ == a.σ / (3 * cbrt(a.x)^2)
h = hypot(a, 3)
@test typeof(h) <: Value
@test h.x == hypot(a.x, 3)
@test h.σ == a.σ * a.x / h
h = hypot(3, a)
@test typeof(h) <: Value
@test h.x == hypot(3, a.x)
@test h.σ == a.σ * a.x / h
h = hypot(a, b)
@test typeof(h) <: Value
@test h.x == hypot(a.x, b.x)
@test h.σ == hypot(a.σ * a.x, b.σ * b.x) / h
end
@testset "sign" begin
@test sign(a) == sign(a.x)
@test sign(Value(-2.4, 2.4)) == sign(-2.4)
@test signbit(a) == signbit(a.x)
@test signbit(Value(-2.4, 2.4)) == signbit(-2.4)
end
@testset "inv" begin
r = inv(a)
@test typeof(r) <: Value
@test r.x == inv(a.x)
@test r.σ == a.σ / a.x^2
end
@testset "approx" begin
@test a ≈ 3.141
@test (a ≈ 3.145) == false
@test isapprox(a, 3.145; significance=3)
@test 3.141 ≈ a
@test (3.145 ≈ a) == false
@test isapprox(3.145, a; significance=3)
@test (a ≈ b) == false
end
@testset "cmp" begin
@test cmp(a, 3) == 1
@test cmp(3, a) == -1
@test cmp(a, a) == 0
@test cmp(a, b) == 1
@test cmp(b, a) == -1
end
@testset "isless" begin
@test isless(a, b) == false
@test isless(b, a)
@test isless(a, 3) == false
@test isless(3, a)
end
@testset "clamp" begin
@test clamp(3, a) == a.x - a.σ
@test clamp(4, a) == a.x + a.σ
@test clamp(3.1414, a) == 3.1414
end
@testset "min/max" begin
@test min(a, b) == min(b, a) == b
@test max(a, b) == max(b, a) == a
@test min(a, 3) == min(3, a) == 3
@test max(a, 4) == max(4, a) == 4
@test typeof(min(a, 4)) <: Value
@test typeof(max(a, 3)) <: Value
@test max(a) == a.x + a.σ
@test min(a) == a.x - a.σ
@test min(a, b, c, -2, 10) == -2
@test min(a, b, c, 34, 13, 9) == b
@test max(a, b, c, 2, 10) == c
@test max(a, 4, b, 2, 1) == 4
end
@testset "val/unc" begin
@test val(a.x) == a.x
@test unc(a.x) == 0
@test val(a) == a.x
@test unc(a) == a.σ
A = fill(Value(a.x, a.σ), (5, 2, 6))
@test eltype(A) <: Value
@test eltype(val(A)) <: Real
@test mean(val(A)) ≈ a.x
@test mean(unc(A)) ≈ a.σ
end
@testset "set_unc" begin
A = zeros(3, 7, 2)
uncA = set_unc(A, 0.2)
@test eltype(uncA) <: Value
@test mean(unc(uncA)) ≈ 0.2
uncA = set_unc(A, fill(0.3, (3, 7, 2)))
@test eltype(uncA) <: Value
@test mean(unc(uncA)) ≈ 0.3
A = fill(Value(a.x, a.σ), (5, 2, 6))
uncA = set_unc(A, 0.2)
@test eltype(uncA) <: Value
@test mean(unc(uncA)) ≈ 0.2
uncA = set_unc(A, fill(0.3, (5, 2, 6)))
@test eltype(uncA) <: Value
@test mean(unc(uncA)) ≈ 0.3
end
| 21.326748
| 77
| 0.481579
|
[
"@testset \"constructor\" begin\n @test a.x == 3.1415\n @test a.σ == 0.0012\n\n @test_throws ErrorException Value(4.1, -2.4)\n\n d = Value(5.248)\n @test d.x == 5.248\n @test d.σ == 0\n\n d = Value(8.0, 1)\n @test typeof(d.x) == typeof(d.σ)\n\n d = Value(8, 0.2)\n @test typeof(d.x) == typeof(d.σ)\nend",
"@testset \"precision\" begin\n @test precision(a) == -4\n @test precision(b) == -7\n @test precision(c) == 0\nend",
"@testset \"addition\" begin\n @test typeof(a + 2) <: Value\n @test typeof(2 + a) <: Value\n s = a + b\n @test typeof(s) <: Value\n @test s.x == (a.x + b.x)\n @test s.σ ≈ hypot(a.σ, b.σ)\n\n n = -a\n @test typeof(n) <: Value\n @test n.x == (-a.x)\n @test n.σ == a.σ\nend",
"@testset \"substraction\" begin\n @test typeof(a - 2) <: Value\n @test typeof(2 - a) <: Value\n s = a - b\n @test typeof(s) <: Value\n @test s.x ≈ (a.x - b.x)\n @test s.σ ≈ hypot(a.σ, b.σ)\nend",
"@testset \"product\" begin\n @test typeof(a * 2) <: Value\n @test typeof(2 * a) <: Value\n s = a * b\n @test typeof(s) <: Value\n @test s.x ≈ (a.x * b.x)\n @test s.σ ≈ hypot(a.σ * b.x, a.x * b.σ)\nend",
"@testset \"division\" begin\n @test typeof(a / 2) <: Value\n @test typeof(2 / a) <: Value\n s = a / b\n @test typeof(s) <: Value\n @test s.x ≈ (a.x / b.x)\n @test s.σ ≈ hypot(a.σ / b.x, a.x * b.σ / b.x^2)\nend",
"@testset \"left division\" begin\n s = a \\ 2\n @test typeof(s) <: Value\n @test s.x ≈ (a.x \\ 2)\n @test s.σ ≈ a.x^2 \\ 2 * a.σ\n\n s = 2 \\ a\n @test typeof(s) <: Value\n @test s.x ≈ (2 \\ a.x)\n @test s.σ ≈ 2 \\ a.σ\n\n s = a \\ b\n @test typeof(s) <: Value\n @test s.x ≈ (a.x \\ b.x)\n @test s.σ ≈ hypot(a.x \\ b.σ, a.x^2 \\ b.x * a.σ)\nend",
"@testset \"integer division\" begin\n j = Value{Int32}(2, 1)\n k = Value{Int32}(7, 2)\n\n s = j ÷ k.x\n @test typeof(s) <: Value\n @test s.x ≈ j.x ÷ k.x\n @test s.σ ≈ j.σ ÷ k.x\n\n s = k.x ÷ j\n @test typeof(s) <: Value\n @test s.x ≈ k.x ÷ j.x\n @test s.σ ≈ k.x * j.σ ÷ j.x^2\n\n s = k ÷ j\n @test typeof(s) <: Value\n @test s.x ≈ k.x ÷ j.x\n @test s.σ ≈ hypot(k.x * j.σ ÷ j.x^2, j.σ ÷ k.x)\n\n s = fld(j, k.x)\n @test typeof(s) <: Value\n @test s.x ≈ fld(j.x, k.x)\n @test s.σ ≈ fld(j.σ, k.x)\n\n s = fld(k.x, j)\n @test typeof(s) <: Value\n @test s.x ≈ fld(k.x, j.x)\n @test s.σ ≈ fld(k.x * j.σ, j.x^2)\n\n s = fld(k, j)\n @test typeof(s) <: Value\n @test s.x ≈ fld(k.x, j.x)\n @test s.σ ≈ floor(hypot(fld(k.x * j.σ, j.x^2), fld(j.σ, k.x)))\n\n s = cld(j, k.x)\n @test typeof(s) <: Value\n @test s.x ≈ cld(j.x, k.x)\n @test s.σ ≈ cld(j.σ, k.x)\n\n s = cld(k.x, j)\n @test typeof(s) <: Value\n @test s.x ≈ cld(k.x, j.x)\n @test s.σ ≈ cld(k.x * j.σ, j.x^2)\n\n s = cld(k, j)\n @test typeof(s) <: Value\n @test s.x ≈ cld(k.x, j.x)\n @test s.σ ≈ ceil(hypot(cld(k.x * j.σ, j.x^2), cld(j.σ, k.x)))\nend",
"@testset \"power\" begin\n @test typeof(a^3) <: Value\n @test typeof(3^a) <: Value\n s = a^b\n @test typeof(s) <: Value\n @test s.x ≈ a.x^b.x\n @test s.σ ≈ hypot(b.x * a.x^(b.x-1) * a.σ, a.x^b.x * log(abs(a.x)) * b.σ)\nend",
"@testset \"equality\" begin\n @test a == 3.1415\n @test (a == 3.141) == false\n @test a != 3.141\n\n @test 3.1415 == a\n @test (3.141 == a) == false\n @test 3.141 != a\n\n @test (a == b) == false\n @test a != b\nend",
"@testset \"inequality\" begin\n @test a < 3.1416\n @test (a < 3.141) == false\n\n @test 3.1416 > a\n @test (3.141 > a) == false\n\n @test a <= 3.1415\n @test a <= 3.1416\n @test (a <= 3.141) == false\n\n @test 3.1416 >= a\n @test 3.1415 >= a\n @test (3.141 >= a) == false\n\n @test a > 3.141\n @test (a > 3.1416) == false\n\n @test 3.141 < a\n @test (3.1416 < a) == false\n\n @test a >= 3.1415\n @test a >= 3.1414\n @test (a >= 3.1416) == false\n\n @test 3.1414 <= a\n @test 3.1415 <= a\n @test (3.146 <= a) == false\n\n @test a > b\n @test b < a\n\n @test a >= a\n @test a >= b\n @test (b >= a) == false\n @test a <= a\n @test b <= a\n @test (a <= b) == false\nend",
"@testset \"abs\" begin\n s = abs(a)\n @test typeof(s) <: Value\n @test s.x == a.x\n @test s.σ == a.σ\n\n s = abs(-a)\n @test s.x == a.x\n @test s.σ == a.σ\nend",
"@testset \"abs2\" begin\n s = abs2(a)\n @test typeof(s) <: Value\n @test s.x == a.x^2\n @test s.σ == 2 * a.x * a.σ\n\n s = abs2(-a)\n @test s.x == a.x^2\n @test s.σ == 2 * a.x * a.σ\nend",
"@testset \"sin/cos/tan\" begin\n s = sin(b)\n @test typeof(s) <: Value\n @test s.x ≈ sin(b.x)\n @test s.σ ≈ abs(cos(b.x)) * b.σ\n\n c = cos(b)\n @test typeof(c) <: Value\n @test c.x ≈ cos(b.x)\n @test c.σ ≈ abs(sin(b.x)) * b.σ\n\n t = tan(b)\n @test typeof(t) <: Value\n @test t.x ≈ tan(b.x)\n @test t.σ ≈ sec(b.x)^2 * b.σ\nend",
"@testset \"sind/cosd/tand\" begin\n s = sind(b)\n @test typeof(s) <: Value\n @test s.x ≈ sind(b.x)\n @test s.σ ≈ abs(cosd(b.x)) * b.σ\n\n c = cosd(b)\n @test typeof(c) <: Value\n @test c.x ≈ cosd(b.x)\n @test c.σ ≈ abs(sind(b.x)) * b.σ\n\n t = tand(b)\n @test typeof(t) <: Value\n @test t.x ≈ tand(b.x)\n @test t.σ ≈ secd(b.x)^2 * b.σ\nend",
"@testset \"sinh/cosh/tanh\" begin\n s = sinh(b)\n @test typeof(s) <: Value\n @test s.x ≈ sinh(b.x)\n @test s.σ ≈ cosh(b.x) * b.σ\n\n c = cosh(b)\n @test typeof(c) <: Value\n @test c.x ≈ cosh(b.x)\n @test c.σ ≈ abs(sinh(b.x)) * b.σ\n\n t = tanh(b)\n @test typeof(t) <: Value\n @test t.x ≈ tanh(b.x)\n @test t.σ ≈ sech(b.x)^2 * b.σ\nend",
"@testset \"sinpi/cospi\" begin\n s = sinpi(b)\n @test typeof(s) <: Value\n @test s.x ≈ sinpi(b.x)\n @test s.σ ≈ π * abs(cospi(b.x)) * b.σ\n\n c = cospi(b)\n @test typeof(c) <: Value\n @test c.x ≈ cospi(b.x)\n @test c.σ ≈ π * abs(sinpi(b.x)) * b.σ\nend",
"@testset \"asin/acos/atan\" begin\n d = Value(0.2435, 0.0658)\n\n s = asin(d)\n @test typeof(s) <: Value\n @test s.x ≈ asin(d.x)\n @test s.σ ≈ d.σ / sqrt(1 - d.x^2)\n\n c = acos(d)\n @test typeof(c) <: Value\n @test c.x ≈ acos(d.x)\n @test c.σ ≈ d.σ / sqrt(1 - d.x^2)\n\n t = atan(d)\n @test typeof(t) <: Value\n @test t.x ≈ atan(d.x)\n @test t.σ ≈ d.σ / (1 + d.x^2)\n\n t = atan(a, b)\n @test t.x ≈ atan(a.x, b.x)\n @test t.σ ≈ hypot(b.x * a.σ, a.x * b.σ) / hypot(a.x, b.x)^2\n\n t = atan(a, 0.1)\n @test t.x ≈ atan(a.x, 0.1)\n @test t.σ ≈ 0.1 * a.σ / hypot(a.x, 0.1)^2\n\n t = atan(0.1, a)\n @test t.x ≈ atan(0.1, a.x)\n @test t.σ ≈ 0.1 * a.σ / hypot(a.x, 0.1)^2\nend",
"@testset \"asind/acosd/atand\" begin\n d = Value(0.2435, 0.0658)\n\n s = asind(d)\n @test typeof(s) <: Value\n @test s.x ≈ asind(d.x)\n @test s.σ ≈ d.σ / sqrt(1 - d.x^2)\n\n c = acosd(d)\n @test typeof(c) <: Value\n @test c.x ≈ acosd(d.x)\n @test c.σ ≈ d.σ / sqrt(1 - d.x^2)\n\n t = atand(d)\n @test typeof(t) <: Value\n @test t.x ≈ atand(d.x)\n @test t.σ ≈ d.σ / (1 + d.x^2)\n\n t = atand(a, b)\n @test t.x ≈ atand(a.x, b.x)\n @test t.σ ≈ hypot(b.x * a.σ, a.x * b.σ) / hypot(a.x, b.x)^2\n\n t = atand(a, 0.1)\n @test t.x ≈ atand(a.x, 0.1)\n @test t.σ ≈ 0.1 * a.σ / hypot(a.x, 0.1)^2\n\n t = atand(0.1, a)\n @test t.x ≈ atand(0.1, a.x)\n @test t.σ ≈ 0.1 * a.σ / hypot(a.x, 0.1)^2\nend",
"@testset \"asinh/acosh/atanh\" begin\n d = Value(1.2435, 0.0658)\n\n s = asinh(d)\n @test typeof(s) <: Value\n @test s.x ≈ asinh(d.x)\n @test s.σ ≈ d.σ / sqrt(1 + d.x^2)\n\n c = acosh(d)\n @test typeof(c) <: Value\n @test c.x ≈ acosh(d.x)\n @test c.σ ≈ d.σ / sqrt(d.x^2 - 1)\n\n d -= 1\n t = atanh(d)\n @test typeof(t) <: Value\n @test t.x ≈ atanh(d.x)\n @test t.σ ≈ d.σ / (1 - d.x^2)\nend",
"@testset \"csc/sec/cot\" begin\n s = csc(b)\n @test typeof(s) <: Value\n @test s.x ≈ csc(b.x)\n @test s.σ ≈ abs(cot(b.x) * csc(b.x)) * b.σ\n\n c = sec(b)\n @test typeof(c) <: Value\n @test c.x ≈ sec(b.x)\n @test c.σ ≈ abs(tan(b.x) * sec(b.x)) * b.σ\n\n t = cot(b)\n @test typeof(t) <: Value\n @test t.x ≈ cot(b.x)\n @test t.σ ≈ csc(b.x)^2 * b.σ\nend",
"@testset \"cscd/secd/cotd\" begin\n s = cscd(b)\n @test typeof(s) <: Value\n @test s.x ≈ cscd(b.x)\n @test s.σ ≈ abs(cotd(b.x) * cscd(b.x)) * b.σ\n\n c = secd(b)\n @test typeof(c) <: Value\n @test c.x ≈ secd(b.x)\n @test c.σ ≈ abs(tand(b.x) * secd(b.x)) * b.σ\n\n t = cotd(b)\n @test typeof(t) <: Value\n @test t.x ≈ cotd(b.x)\n @test t.σ ≈ cscd(b.x)^2 * b.σ\nend",
"@testset \"csch/sech/coth\" begin\n s = csch(b)\n @test typeof(s) <: Value\n @test s.x ≈ csch(b.x)\n @test s.σ ≈ abs(coth(b.x) * csch(b.x)) * b.σ\n\n c = sech(b)\n @test typeof(c) <: Value\n @test c.x ≈ sech(b.x)\n @test c.σ ≈ abs(tanh(b.x) * sech(b.x)) * b.σ\n\n t = coth(b)\n @test typeof(t) <: Value\n @test t.x ≈ coth(b.x)\n @test t.σ ≈ csch(b.x)^2 * b.σ\nend",
"@testset \"acsc/asec/acot\" begin\n s = acsc(b)\n @test typeof(s) <: Value\n @test s.x ≈ acsc(b.x)\n @test s.σ ≈ b.σ / sqrt(b.x^2 - 1)\n\n c = asec(b)\n @test typeof(c) <: Value\n @test c.x ≈ asec(b.x)\n @test c.σ ≈ b.σ / sqrt(b.x^2 - 1)\n\n t = acot(b)\n @test typeof(t) <: Value\n @test t.x ≈ acot(b.x)\n @test t.σ ≈ b.σ / (1 + b.x^2)\nend",
"@testset \"acscd/asecd/acotd\" begin\n s = acscd(b)\n @test typeof(s) <: Value\n @test s.x ≈ acscd(b.x)\n @test s.σ ≈ b.σ / sqrt(b.x^2 - 1)\n\n c = asecd(b)\n @test typeof(c) <: Value\n @test c.x ≈ asecd(b.x)\n @test c.σ ≈ b.σ / sqrt(b.x^2 - 1)\n\n t = acotd(b)\n @test typeof(t) <: Value\n @test t.x ≈ acotd(b.x)\n @test t.σ ≈ b.σ / (1 + b.x^2)\nend",
"@testset \"acsch/asech/acoth\" begin\n d = Value(0.12435, 0.0658)\n s = acsch(b)\n @test typeof(s) <: Value\n @test s.x ≈ acsch(b.x)\n @test s.σ ≈ b.σ / sqrt(b.x^2 + 1)\n\n c = asech(d)\n @test typeof(c) <: Value\n @test c.x ≈ asech(d.x)\n @test c.σ ≈ d.σ / sqrt(1 - d.x^2)\n\n t = acoth(b)\n @test typeof(t) <: Value\n @test t.x ≈ acoth(b.x)\n @test t.σ ≈ b.σ / abs(1 - b.x^2)\nend",
"@testset \"deg2rad\" begin\n d = deg2rad(a)\n @test typeof(d) <: Value\n @test d.x == deg2rad(a.x)\n @test d.σ == deg2rad(a.σ)\n\n d = rad2deg(a)\n @test typeof(d) <: Value\n @test d.x == rad2deg(a.x)\n @test d.σ == rad2deg(a.σ)\nend",
"@testset \"exp\" begin\n r = exp(a)\n @test typeof(r) <: Value\n @test r.x == exp(a.x)\n @test r.σ ≈ r.x * a.σ\n\n r = exp2(a)\n @test typeof(r) <: Value\n @test r.x == exp2(a.x)\n @test r.σ ≈ r.x * a.σ * log(2)\n\n r = exp10(a)\n @test typeof(r) <: Value\n @test r.x == exp10(a.x)\n @test r.σ ≈ r.x * a.σ * log(10)\nend",
"@testset \"log\" begin\n r = log(a)\n @test typeof(r) <: Value\n @test r.x == log(a.x)\n @test r.σ ≈ a.σ / a.x\n\n r = log2(a)\n @test typeof(r) <: Value\n @test r.x == log2(a.x)\n @test r.σ ≈ a.σ / (a.x * log(2))\n\n r = log10(a)\n @test typeof(r) <: Value\n @test r.x == log10(a.x)\n @test r.σ ≈ a.σ / (a.x * log(10))\n\n r = log(3, a)\n @test typeof(r) <: Value\n @test r.x == log(3, a.x)\n @test r.σ ≈ a.σ / (a.x * log(3))\n\n r = log1p(a)\n @test typeof(r) <: Value\n @test r.x == log1p(a.x)\n @test r.σ ≈ a.σ / (a.x + 1)\nend",
"@testset \"roots\" begin\n r = sqrt(a)\n @test typeof(r) <: Value\n @test r.x == sqrt(a.x)\n @test r.σ == a.σ / (2 * sqrt(a.x))\n\n r = cbrt(a)\n @test typeof(r) <: Value\n @test r.x == cbrt(a.x)\n @test r.σ == a.σ / (3 * cbrt(a.x)^2)\n\n h = hypot(a, 3)\n @test typeof(h) <: Value\n @test h.x == hypot(a.x, 3)\n @test h.σ == a.σ * a.x / h\n\n h = hypot(3, a)\n @test typeof(h) <: Value\n @test h.x == hypot(3, a.x)\n @test h.σ == a.σ * a.x / h\n\n h = hypot(a, b)\n @test typeof(h) <: Value\n @test h.x == hypot(a.x, b.x)\n @test h.σ == hypot(a.σ * a.x, b.σ * b.x) / h\nend",
"@testset \"sign\" begin\n @test sign(a) == sign(a.x)\n @test sign(Value(-2.4, 2.4)) == sign(-2.4)\n\n @test signbit(a) == signbit(a.x)\n @test signbit(Value(-2.4, 2.4)) == signbit(-2.4)\nend",
"@testset \"inv\" begin\n r = inv(a)\n @test typeof(r) <: Value\n @test r.x == inv(a.x)\n @test r.σ == a.σ / a.x^2\nend",
"@testset \"approx\" begin\n @test a ≈ 3.141\n @test (a ≈ 3.145) == false\n @test isapprox(a, 3.145; significance=3)\n\n @test 3.141 ≈ a\n @test (3.145 ≈ a) == false\n @test isapprox(3.145, a; significance=3)\n\n @test (a ≈ b) == false\nend",
"@testset \"cmp\" begin\n @test cmp(a, 3) == 1\n @test cmp(3, a) == -1\n @test cmp(a, a) == 0\n @test cmp(a, b) == 1\n @test cmp(b, a) == -1\nend",
"@testset \"isless\" begin\n @test isless(a, b) == false\n @test isless(b, a)\n @test isless(a, 3) == false\n @test isless(3, a)\nend",
"@testset \"clamp\" begin\n @test clamp(3, a) == a.x - a.σ\n @test clamp(4, a) == a.x + a.σ\n @test clamp(3.1414, a) == 3.1414\nend",
"@testset \"min/max\" begin\n @test min(a, b) == min(b, a) == b\n @test max(a, b) == max(b, a) == a\n @test min(a, 3) == min(3, a) == 3\n @test max(a, 4) == max(4, a) == 4\n\n @test typeof(min(a, 4)) <: Value\n @test typeof(max(a, 3)) <: Value\n\n @test max(a) == a.x + a.σ\n @test min(a) == a.x - a.σ\n\n @test min(a, b, c, -2, 10) == -2\n @test min(a, b, c, 34, 13, 9) == b\n @test max(a, b, c, 2, 10) == c\n @test max(a, 4, b, 2, 1) == 4\nend",
"@testset \"val/unc\" begin\n @test val(a.x) == a.x\n @test unc(a.x) == 0\n\n @test val(a) == a.x\n @test unc(a) == a.σ\n\n A = fill(Value(a.x, a.σ), (5, 2, 6))\n\n @test eltype(A) <: Value\n @test eltype(val(A)) <: Real\n @test mean(val(A)) ≈ a.x\n @test mean(unc(A)) ≈ a.σ\nend",
"@testset \"set_unc\" begin\n A = zeros(3, 7, 2)\n\n uncA = set_unc(A, 0.2)\n @test eltype(uncA) <: Value\n @test mean(unc(uncA)) ≈ 0.2\n\n uncA = set_unc(A, fill(0.3, (3, 7, 2)))\n @test eltype(uncA) <: Value\n @test mean(unc(uncA)) ≈ 0.3\n\n A = fill(Value(a.x, a.σ), (5, 2, 6))\n uncA = set_unc(A, 0.2)\n @test eltype(uncA) <: Value\n @test mean(unc(uncA)) ≈ 0.2\n\n uncA = set_unc(A, fill(0.3, (5, 2, 6)))\n @test eltype(uncA) <: Value\n @test mean(unc(uncA)) ≈ 0.3\nend"
] |
f72f043be09d590c6643ffb83677e3fd865d1d0f
| 47,300
|
jl
|
Julia
|
stdlib/SparseArrays/test/sparsevector.jl
|
ninjin/julia
|
2d589cca94c502a696fc5e234835560e28b9efd3
|
[
"Zlib"
] | null | null | null |
stdlib/SparseArrays/test/sparsevector.jl
|
ninjin/julia
|
2d589cca94c502a696fc5e234835560e28b9efd3
|
[
"Zlib"
] | null | null | null |
stdlib/SparseArrays/test/sparsevector.jl
|
ninjin/julia
|
2d589cca94c502a696fc5e234835560e28b9efd3
|
[
"Zlib"
] | null | null | null |
# This file is a part of Julia. License is MIT: https://julialang.org/license
module SparseVectorTests
using Test
using SparseArrays
using LinearAlgebra
using Random
### Data
spv_x1 = SparseVector(8, [2, 5, 6], [1.25, -0.75, 3.5])
@test isa(spv_x1, SparseVector{Float64,Int})
x1_full = zeros(length(spv_x1))
x1_full[SparseArrays.nonzeroinds(spv_x1)] = nonzeros(spv_x1)
@testset "basic properties" begin
x = spv_x1
@test eltype(x) == Float64
@test ndims(x) == 1
@test length(x) == 8
@test size(x) == (8,)
@test size(x,1) == 8
@test size(x,2) == 1
@test !isempty(x)
@test count(!iszero, x) == 3
@test nnz(x) == 3
@test SparseArrays.nonzeroinds(x) == [2, 5, 6]
@test nonzeros(x) == [1.25, -0.75, 3.5]
@test count(SparseVector(8, [2, 5, 6], [true,false,true])) == 2
end
@testset "conversion to dense Array" begin
for (x, xf) in [(spv_x1, x1_full)]
@test isa(Array(x), Vector{Float64})
@test Array(x) == xf
@test Vector(x) == xf
end
end
@testset "show" begin
@test occursin("1.25", string(spv_x1))
@test occursin("-0.75", string(spv_x1))
@test occursin("3.5", string(spv_x1))
end
### Comparison helper to ensure exact equality with internal structure
function exact_equal(x::AbstractSparseVector, y::AbstractSparseVector)
eltype(x) == eltype(y) &&
eltype(SparseArrays.nonzeroinds(x)) == eltype(SparseArrays.nonzeroinds(y)) &&
length(x) == length(y) &&
SparseArrays.nonzeroinds(x) == SparseArrays.nonzeroinds(y) &&
nonzeros(x) == nonzeros(y)
end
@testset "other constructors" begin
# construct empty sparse vector
@test exact_equal(spzeros(Float64, 8), SparseVector(8, Int[], Float64[]))
@testset "from list of indices and values" begin
@test exact_equal(
sparsevec(Int[], Float64[], 8),
SparseVector(8, Int[], Float64[]))
@test exact_equal(
sparsevec(Int[], Float64[]),
SparseVector(0, Int[], Float64[]))
@test exact_equal(
sparsevec([3, 3], [5.0, -5.0], 8),
SparseVector(8, [3], [0.0]))
@test exact_equal(
sparsevec([2, 3, 6], [12.0, 18.0, 25.0]),
SparseVector(6, [2, 3, 6], [12.0, 18.0, 25.0]))
let x0 = SparseVector(8, [2, 3, 6], [12.0, 18.0, 25.0])
@test exact_equal(
sparsevec([2, 3, 6], [12.0, 18.0, 25.0], 8), x0)
@test exact_equal(
sparsevec([3, 6, 2], [18.0, 25.0, 12.0], 8), x0)
@test exact_equal(
sparsevec([2, 3, 4, 4, 6], [12.0, 18.0, 5.0, -5.0, 25.0], 8),
SparseVector(8, [2, 3, 4, 6], [12.0, 18.0, 0.0, 25.0]))
@test exact_equal(
sparsevec([1, 1, 1, 2, 3, 3, 6], [2.0, 3.0, -5.0, 12.0, 10.0, 8.0, 25.0], 8),
SparseVector(8, [1, 2, 3, 6], [0.0, 12.0, 18.0, 25.0]))
@test exact_equal(
sparsevec([2, 3, 6, 7, 7], [12.0, 18.0, 25.0, 5.0, -5.0], 8),
SparseVector(8, [2, 3, 6, 7], [12.0, 18.0, 25.0, 0.0]))
end
@test exact_equal(
sparsevec(Any[1, 3], [1, 1]),
sparsevec([1, 3], [1, 1]))
@test exact_equal(
sparsevec(Any[1, 3], [1, 1], 5),
sparsevec([1, 3], [1, 1], 5))
end
@testset "from dictionary" begin
function my_intmap(x)
a = Dict{Int,eltype(x)}()
for i in SparseArrays.nonzeroinds(x)
a[i] = x[i]
end
return a
end
let x = spv_x1
a = my_intmap(x)
xc = sparsevec(a, 8)
@test exact_equal(x, xc)
xc = sparsevec(a)
@test exact_equal(xc, SparseVector(6, [2, 5, 6], [1.25, -0.75, 3.5]))
d = Dict{Int, Float64}((1 => 0.0, 2 => 1.0, 3 => 2.0))
@test exact_equal(sparsevec(d), SparseVector(3, [1, 2, 3], [0.0, 1.0, 2.0]))
end
end
@testset "fillstored!" begin
x = SparseVector(8, [2, 3, 6], [12.0, 18.0, 25.0])
y = LinearAlgebra.fillstored!(copy(x), 1)
@test (x .!= 0) == (y .!= 0)
@test y == SparseVector(8, [2, 3, 6], [1.0, 1.0, 1.0])
end
@testset "sprand & sprandn" begin
let xr = sprand(1000, 0.9)
@test isa(xr, SparseVector{Float64,Int})
@test length(xr) == 1000
@test all(nonzeros(xr) .>= 0.0)
end
let xr = sprand(Float32, 1000, 0.9)
@test isa(xr, SparseVector{Float32,Int})
@test length(xr) == 1000
@test all(nonzeros(xr) .>= 0.0)
end
let xr = sprandn(1000, 0.9)
@test isa(xr, SparseVector{Float64,Int})
@test length(xr) == 1000
if !isempty(nonzeros(xr))
@test any(nonzeros(xr) .> 0.0) && any(nonzeros(xr) .< 0.0)
end
end
let xr = sprand(Bool, 1000, 0.9)
@test isa(xr, SparseVector{Bool,Int})
@test length(xr) == 1000
@test all(nonzeros(xr))
end
let r1 = MersenneTwister(0), r2 = MersenneTwister(0)
@test sprand(r1, 100, .9) == sprand(r2, 100, .9)
@test sprandn(r1, 100, .9) == sprandn(r2, 100, .9)
@test sprand(r1, Bool, 100, .9) == sprand(r2, Bool, 100, .9)
end
end
end
### Element access
@testset "getindex" begin
@testset "single integer index" begin
for (x, xf) in [(spv_x1, x1_full)]
for i = 1:length(x)
@test x[i] == xf[i]
end
end
end
@testset "generic array index" begin
let x = sprand(100, 0.5)
I = rand(1:length(x), 20)
r = x[I]
@test isa(r, SparseVector{Float64,Int})
@test all(!iszero, nonzeros(r))
@test Array(r) == Array(x)[I]
end
# issue 24534
let x = convert(SparseVector{Float64,UInt32},sprandn(100,0.5))
I = rand(1:length(x), 20)
r = x[I]
@test isa(r, SparseVector{Float64,UInt32})
@test all(!iszero, nonzeros(r))
@test Array(r) == Array(x)[I]
end
# issue 24534
let x = convert(SparseVector{Float64,UInt32},sprandn(100,0.5))
I = rand(1:length(x), 20,1)
r = x[I]
@test isa(r, SparseMatrixCSC{Float64,UInt32})
@test all(!iszero, nonzeros(r))
@test Array(r) == Array(x)[I]
end
end
@testset "boolean array index" begin
let x = sprand(10, 10, 0.5)
I = rand(1:size(x, 2), 10)
bI = falses(size(x, 2))
bI[I] .= true
r = x[1,bI]
@test isa(r, SparseVector{Float64,Int})
@test all(!iszero, nonzeros(r))
@test Array(r) == Array(x)[1,bI]
end
let x = sprand(10, 0.5)
I = rand(1:length(x), 5)
bI = falses(length(x))
bI[I] .= true
r = x[bI]
@test isa(r, SparseVector{Float64,Int})
@test all(!iszero, nonzeros(r))
@test Array(r) == Array(x)[bI]
end
end
end
@testset "setindex" begin
let xc = spzeros(Float64, 8)
xc[3] = 2.0
@test exact_equal(xc, SparseVector(8, [3], [2.0]))
end
let xc = copy(spv_x1)
xc[5] = 2.0
@test exact_equal(xc, SparseVector(8, [2, 5, 6], [1.25, 2.0, 3.5]))
end
let xc = copy(spv_x1)
xc[3] = 4.0
@test exact_equal(xc, SparseVector(8, [2, 3, 5, 6], [1.25, 4.0, -0.75, 3.5]))
xc[1] = 6.0
@test exact_equal(xc, SparseVector(8, [1, 2, 3, 5, 6], [6.0, 1.25, 4.0, -0.75, 3.5]))
xc[8] = -1.5
@test exact_equal(xc, SparseVector(8, [1, 2, 3, 5, 6, 8], [6.0, 1.25, 4.0, -0.75, 3.5, -1.5]))
end
let xc = copy(spv_x1)
xc[5] = 0.0
@test exact_equal(xc, SparseVector(8, [2, 5, 6], [1.25, 0.0, 3.5]))
xc[6] = 0.0
@test exact_equal(xc, SparseVector(8, [2, 5, 6], [1.25, 0.0, 0.0]))
xc[2] = 0.0
@test exact_equal(xc, SparseVector(8, [2, 5, 6], [0.0, 0.0, 0.0]))
xc[1] = 0.0
@test exact_equal(xc, SparseVector(8, [2, 5, 6], [0.0, 0.0, 0.0]))
end
end
@testset "dropstored!" begin
x = SparseVector(10, [2, 7, 9], [2.0, 7.0, 9.0])
# Test argument bounds checking for dropstored!(x, i)
@test_throws BoundsError SparseArrays.dropstored!(x, 0)
@test_throws BoundsError SparseArrays.dropstored!(x, 11)
# Test behavior of dropstored!(x, i)
# --> Test dropping a single stored entry
@test SparseArrays.dropstored!(x, 2) == SparseVector(10, [7, 9], [7.0, 9.0])
# --> Test dropping a single nonstored entry
@test SparseArrays.dropstored!(x, 5) == SparseVector(10, [7, 9], [7.0, 9.0])
end
@testset "findall and findnz" begin
@test findall(!iszero, spv_x1) == findall(!iszero, x1_full)
@test findall(spv_x1 .> 1) == findall(x1_full .> 1)
@test findall(x->x>1, spv_x1) == findall(x->x>1, x1_full)
@test findnz(spv_x1) == (findall(!iszero, x1_full), filter(x->x!=0, x1_full))
let xc = SparseVector(8, [2, 3, 5], [1.25, 0, -0.75]), fc = Array(xc)
@test findall(!iszero, xc) == findall(!iszero, fc)
@test findnz(xc) == ([2, 3, 5], [1.25, 0, -0.75])
end
end
### Array manipulation
@testset "copy[!]" begin
let x = spv_x1
xc = copy(x)
@test isa(xc, SparseVector{Float64,Int})
@test x.nzind !== xc.nzval
@test x.nzval !== xc.nzval
@test exact_equal(x, xc)
end
let x1 = SparseVector(8, [2, 5, 6], [12.2, 1.4, 5.0])
x2 = SparseVector(8, [3, 4], [1.2, 3.4])
copyto!(x2, x1)
@test x2 == x1
x2 = SparseVector(8, [2, 4, 8], [10.3, 7.4, 3.1])
copyto!(x2, x1)
@test x2 == x1
x2 = SparseVector(8, [1, 3, 4, 7], [0.3, 1.2, 3.4, 0.1])
copyto!(x2, x1)
@test x2 == x1
x2 = SparseVector(10, [3, 4], [1.2, 3.4])
copyto!(x2, x1)
@test x2[1:8] == x1
@test x2[9:10] == spzeros(2)
x2 = SparseVector(10, [3, 4, 9], [1.2, 3.4, 17.8])
copyto!(x2, x1)
@test x2[1:8] == x1
@test x2[9] == 17.8
@test x2[10] == 0
x2 = SparseVector(10, [3, 4, 5, 6, 9], [8.3, 7.2, 1.2, 3.4, 17.8])
copyto!(x2, x1)
@test x2[1:8] == x1
@test x2[9] == 17.8
@test x2[10] == 0
x2 = SparseVector(6, [3, 4], [1.2, 3.4])
@test_throws BoundsError copyto!(x2, x1)
end
let x1 = sparse([2, 1, 2], [1, 3, 3], [12.2, 1.4, 5.0], 2, 4)
x2 = SparseVector(8, [3, 4], [1.2, 3.4])
copyto!(x2, x1)
@test x2[:] == x1[:]
x2 = SparseVector(8, [2, 4, 8], [10.3, 7.4, 3.1])
copyto!(x2, x1)
@test x2[:] == x1[:]
x2 = SparseVector(8, [1, 3, 4, 7], [0.3, 1.2, 3.4, 0.1])
copyto!(x2, x1)
@test x2[:] == x1[:]
x2 = SparseVector(10, [3, 4], [1.2, 3.4])
copyto!(x2, x1)
@test x2[1:8] == x1[:]
@test x2[9:10] == spzeros(2)
x2 = SparseVector(10, [3, 4, 9], [1.2, 3.4, 17.8])
copyto!(x2, x1)
@test x2[1:8] == x1[:]
@test x2[9] == 17.8
@test x2[10] == 0
x2 = SparseVector(10, [3, 4, 5, 6, 9], [8.3, 7.2, 1.2, 3.4, 17.8])
copyto!(x2, x1)
@test x2[1:8] == x1[:]
@test x2[9] == 17.8
@test x2[10] == 0
x2 = SparseVector(6, [3, 4], [1.2, 3.4])
@test_throws BoundsError copyto!(x2, x1)
end
let x1 = SparseVector(8, [2, 5, 6], [12.2, 1.4, 5.0])
x2 = sparse([1, 2], [2, 2], [1.2, 3.4], 2, 4)
copyto!(x2, x1)
@test x2[:] == x1[:]
x2 = sparse([2, 2, 2], [1, 3, 4], [10.3, 7.4, 3.1], 2, 4)
copyto!(x2, x1)
@test x2[:] == x1[:]
x2 = sparse([1, 1, 2, 1], [1, 2, 2, 4], [0.3, 1.2, 3.4, 0.1], 2, 4)
copyto!(x2, x1)
@test x2[:] == x1[:]
x2 = sparse([1, 2], [2, 2], [1.2, 3.4], 2, 5)
copyto!(x2, x1)
@test x2[1:8] == x1
@test x2[9:10] == spzeros(2)
x2 = sparse([1, 2, 1], [2, 2, 5], [1.2, 3.4, 17.8], 2, 5)
copyto!(x2, x1)
@test x2[1:8] == x1
@test x2[9] == 17.8
@test x2[10] == 0
x2 = sparse([1, 2, 1, 2, 1], [2, 2, 3, 3, 5], [8.3, 7.2, 1.2, 3.4, 17.8], 2, 5)
copyto!(x2, x1)
@test x2[1:8] == x1
@test x2[9] == 17.8
@test x2[10] == 0
x2 = sparse([1, 2], [2, 2], [1.2, 3.4], 2, 3)
@test_throws BoundsError copyto!(x2, x1)
end
end
@testset "vec/reinterpret/float/complex" begin
a = SparseVector(8, [2, 5, 6], Int32[12, 35, 72])
# vec
@test vec(a) == a
# float
af = float(a)
@test float(af) == af
@test isa(af, SparseVector{Float64,Int})
@test exact_equal(af, SparseVector(8, [2, 5, 6], [12., 35., 72.]))
@test sparsevec(transpose(transpose(af))) == af
# complex
acp = complex(af)
@test complex(acp) == acp
@test isa(acp, SparseVector{ComplexF64,Int})
@test exact_equal(acp, SparseVector(8, [2, 5, 6], complex([12., 35., 72.])))
@test sparsevec((acp')') == acp
end
@testset "Type conversion" begin
let x = convert(SparseVector, sparse([2, 5, 6], [1, 1, 1], [1.25, -0.75, 3.5], 8, 1))
@test isa(x, SparseVector{Float64,Int})
@test exact_equal(x, spv_x1)
end
let x = spv_x1, xf = x1_full
xc = convert(SparseVector, xf)
@test isa(xc, SparseVector{Float64,Int})
@test exact_equal(xc, x)
xc = convert(SparseVector{Float32,Int}, x)
xf32 = SparseVector(8, [2, 5, 6], [1.25f0, -0.75f0, 3.5f0])
@test isa(xc, SparseVector{Float32,Int})
@test exact_equal(xc, xf32)
xc = convert(SparseVector{Float32}, x)
@test isa(xc, SparseVector{Float32,Int})
@test exact_equal(xc, xf32)
xm = convert(SparseMatrixCSC, x)
@test isa(xm, SparseMatrixCSC{Float64,Int})
@test Array(xm) == reshape(xf, 8, 1)
xm = convert(SparseMatrixCSC{Float32}, x)
@test isa(xm, SparseMatrixCSC{Float32,Int})
@test Array(xm) == reshape(convert(Vector{Float32}, xf), 8, 1)
end
end
@testset "Concatenation" begin
let m = 80, n = 100
A = Vector{SparseVector{Float64,Int}}(undef, n)
tnnz = 0
for i = 1:length(A)
A[i] = sprand(m, 0.3)
tnnz += nnz(A[i])
end
H = hcat(A...)
@test isa(H, SparseMatrixCSC{Float64,Int})
@test size(H) == (m, n)
@test nnz(H) == tnnz
Hr = zeros(m, n)
for j = 1:n
Hr[:,j] = Array(A[j])
end
@test Array(H) == Hr
V = vcat(A...)
@test isa(V, SparseVector{Float64,Int})
@test length(V) == m * n
Vr = vec(Hr)
@test Array(V) == Vr
end
@testset "concatenation of sparse vectors with other types" begin
# Test that concatenations of combinations of sparse vectors with various other
# matrix/vector types yield sparse arrays
let N = 4
spvec = spzeros(N)
spmat = spzeros(N, 1)
densevec = fill(1., N)
densemat = fill(1., N, 1)
diagmat = Diagonal(densevec)
# Test that concatenations of pairwise combinations of sparse vectors with dense
# vectors/matrices, sparse matrices, or special matrices yield sparse arrays
for othervecormat in (densevec, densemat, spmat)
@test issparse(vcat(spvec, othervecormat))
@test issparse(vcat(othervecormat, spvec))
end
for othervecormat in (densevec, densemat, spmat, diagmat)
@test issparse(hcat(spvec, othervecormat))
@test issparse(hcat(othervecormat, spvec))
@test issparse(hvcat((2,), spvec, othervecormat))
@test issparse(hvcat((2,), othervecormat, spvec))
@test issparse(cat(spvec, othervecormat; dims=(1,2)))
@test issparse(cat(othervecormat, spvec; dims=(1,2)))
end
# The preceding tests should cover multi-way combinations of those types, but for good
# measure test a few multi-way combinations involving those types
@test issparse(vcat(spvec, densevec, spmat, densemat))
@test issparse(vcat(densevec, spvec, densemat, spmat))
@test issparse(hcat(spvec, densemat, spmat, densevec, diagmat))
@test issparse(hcat(densemat, spmat, spvec, densevec, diagmat))
@test issparse(hvcat((5,), diagmat, densevec, spvec, densemat, spmat))
@test issparse(hvcat((5,), spvec, densemat, diagmat, densevec, spmat))
@test issparse(cat(densemat, diagmat, spmat, densevec, spvec; dims=(1,2)))
@test issparse(cat(spvec, diagmat, densevec, spmat, densemat; dims=(1,2)))
end
@testset "vertical concatenation of SparseVectors with different el- and ind-type (#22225)" begin
spv6464 = SparseVector(0, Int64[], Int64[])
@test isa(vcat(spv6464, SparseVector(0, Int64[], Int32[])), SparseVector{Int64,Int64})
@test isa(vcat(spv6464, SparseVector(0, Int32[], Int64[])), SparseVector{Int64,Int64})
@test isa(vcat(spv6464, SparseVector(0, Int32[], Int32[])), SparseVector{Int64,Int64})
end
end
end
@testset "sparsemat: combinations with sparse matrix" begin
let S = sprand(4, 8, 0.5)
Sf = Array(S)
@assert isa(Sf, Matrix{Float64})
# get a single column
for j = 1:size(S,2)
col = S[:, j]
@test isa(col, SparseVector{Float64,Int})
@test length(col) == size(S,1)
@test Array(col) == Sf[:,j]
end
# Get a reshaped vector
v = S[:]
@test isa(v, SparseVector{Float64,Int})
@test length(v) == length(S)
@test Array(v) == Sf[:]
# Get a linear subset
for i=0:length(S)
v = S[1:i]
@test isa(v, SparseVector{Float64,Int})
@test length(v) == i
@test Array(v) == Sf[1:i]
end
for i=1:length(S)+1
v = S[i:end]
@test isa(v, SparseVector{Float64,Int})
@test length(v) == length(S) - i + 1
@test Array(v) == Sf[i:end]
end
for i=0:div(length(S),2)
v = S[1+i:end-i]
@test isa(v, SparseVector{Float64,Int})
@test length(v) == length(S) - 2i
@test Array(v) == Sf[1+i:end-i]
end
end
let r = [1,10], S = sparse(r, r, r)
Sf = Array(S)
@assert isa(Sf, Matrix{Int})
inds = [1,1,1,1,1,1]
v = S[inds]
@test isa(v, SparseVector{Int,Int})
@test length(v) == length(inds)
@test Array(v) == Sf[inds]
inds = [2,2,2,2,2,2]
v = S[inds]
@test isa(v, SparseVector{Int,Int})
@test length(v) == length(inds)
@test Array(v) == Sf[inds]
# get a single column
for j = 1:size(S,2)
col = S[:, j]
@test isa(col, SparseVector{Int,Int})
@test length(col) == size(S,1)
@test Array(col) == Sf[:,j]
end
# Get a reshaped vector
v = S[:]
@test isa(v, SparseVector{Int,Int})
@test length(v) == length(S)
@test Array(v) == Sf[:]
# Get a linear subset
for i=0:length(S)
v = S[1:i]
@test isa(v, SparseVector{Int,Int})
@test length(v) == i
@test Array(v) == Sf[1:i]
end
for i=1:length(S)+1
v = S[i:end]
@test isa(v, SparseVector{Int,Int})
@test length(v) == length(S) - i + 1
@test Array(v) == Sf[i:end]
end
for i=0:div(length(S),2)
v = S[1+i:end-i]
@test isa(v, SparseVector{Int,Int})
@test length(v) == length(S) - 2i
@test Array(v) == Sf[1+i:end-i]
end
end
end
## math
### Data
rnd_x0 = sprand(50, 0.6)
rnd_x0f = Array(rnd_x0)
rnd_x1 = sprand(50, 0.7) * 4.0
rnd_x1f = Array(rnd_x1)
spv_x1 = SparseVector(8, [2, 5, 6], [1.25, -0.75, 3.5])
spv_x2 = SparseVector(8, [1, 2, 6, 7], [3.25, 4.0, -5.5, -6.0])
@testset "Arithmetic operations" begin
let x = spv_x1, x2 = spv_x2
# negate
@test exact_equal(-x, SparseVector(8, [2, 5, 6], [-1.25, 0.75, -3.5]))
# abs and abs2
@test exact_equal(abs.(x), SparseVector(8, [2, 5, 6], abs.([1.25, -0.75, 3.5])))
@test exact_equal(abs2.(x), SparseVector(8, [2, 5, 6], abs2.([1.25, -0.75, 3.5])))
# plus and minus
xa = SparseVector(8, [1,2,5,6,7], [3.25,5.25,-0.75,-2.0,-6.0])
@test exact_equal(x + x, x * 2)
@test exact_equal(x + x2, xa)
@test exact_equal(x2 + x, xa)
xb = SparseVector(8, [1,2,5,6,7], [-3.25,-2.75,-0.75,9.0,6.0])
@test exact_equal(x - x, SparseVector(8, Int[], Float64[]))
@test exact_equal(x - x2, xb)
@test exact_equal(x2 - x, -xb)
@test Array(x) + x2 == Array(xa)
@test Array(x) - x2 == Array(xb)
@test x + Array(x2) == Array(xa)
@test x - Array(x2) == Array(xb)
# multiplies
xm = SparseVector(8, [2, 6], [5.0, -19.25])
@test exact_equal(x .* x, abs2.(x))
@test exact_equal(x .* x2, xm)
@test exact_equal(x2 .* x, xm)
@test Array(x) .* x2 == Array(xm)
@test x .* Array(x2) == Array(xm)
# max & min
@test exact_equal(max.(x, x), x)
@test exact_equal(min.(x, x), x)
@test exact_equal(max.(x, x2),
SparseVector(8, Int[1, 2, 6], Float64[3.25, 4.0, 3.5]))
@test exact_equal(min.(x, x2),
SparseVector(8, Int[2, 5, 6, 7], Float64[1.25, -0.75, -5.5, -6.0]))
end
### Complex
let x = spv_x1, x2 = spv_x2
# complex
@test exact_equal(complex.(x, x),
SparseVector(8, [2,5,6], [1.25+1.25im, -0.75-0.75im, 3.5+3.5im]))
@test exact_equal(complex.(x, x2),
SparseVector(8, [1,2,5,6,7], [3.25im, 1.25+4.0im, -0.75+0.0im, 3.5-5.5im, -6.0im]))
@test exact_equal(complex.(x2, x),
SparseVector(8, [1,2,5,6,7], [3.25+0.0im, 4.0+1.25im, -0.75im, -5.5+3.5im, -6.0+0.0im]))
# real, imag and conj
@test real(x) === x
@test exact_equal(imag(x), spzeros(Float64, length(x)))
@test conj(x) === x
xcp = complex.(x, x2)
@test exact_equal(real(xcp), x)
@test exact_equal(imag(xcp), x2)
@test exact_equal(conj(xcp), complex.(x, -x2))
end
end
@testset "Zero-preserving math functions: sparse -> sparse" begin
x1operations = (floor, ceil, trunc, round)
x0operations = (log1p, expm1, sinpi,
sin, tan, sind, tand,
asin, atan, asind, atand,
sinh, tanh, asinh, atanh)
for (spvec, densevec, operations) in (
(rnd_x0, rnd_x0f, x0operations),
(rnd_x1, rnd_x1f, x1operations) )
for op in operations
spresvec = op.(spvec)
@test spresvec == op.(densevec)
@test all(!iszero, spresvec.nzval)
resvaltype = typeof(op(zero(eltype(spvec))))
resindtype = SparseArrays.indtype(spvec)
@test isa(spresvec, SparseVector{resvaltype,resindtype})
end
end
end
@testset "Non-zero-preserving math functions: sparse -> dense" begin
for op in (exp, exp2, exp10, log, log2, log10,
cos, cosd, acos, cosh, cospi,
csc, cscd, acot, csch, acsch,
cot, cotd, acosd, coth,
sec, secd, acotd, sech, asech)
spvec = rnd_x0
densevec = rnd_x0f
spresvec = op.(spvec)
@test spresvec == op.(densevec)
resvaltype = typeof(op(zero(eltype(spvec))))
resindtype = SparseArrays.indtype(spvec)
@test isa(spresvec, SparseVector{resvaltype,resindtype})
end
end
### Reduction
@testset "sum, vecnorm" begin
x = spv_x1
@test sum(x) == 4.0
@test sum(abs, x) == 5.5
@test sum(abs2, x) == 14.375
@test vecnorm(x) == sqrt(14.375)
@test vecnorm(x, 1) == 5.5
@test vecnorm(x, 2) == sqrt(14.375)
@test vecnorm(x, Inf) == 3.5
end
@testset "maximum, minimum" begin
let x = spv_x1
@test maximum(x) == 3.5
@test minimum(x) == -0.75
@test maximum(abs, x) == 3.5
@test minimum(abs, x) == 0.0
end
let x = abs.(spv_x1)
@test maximum(x) == 3.5
@test minimum(x) == 0.0
end
let x = -abs.(spv_x1)
@test maximum(x) == 0.0
@test minimum(x) == -3.5
end
let x = SparseVector(3, [1, 2, 3], [-4.5, 2.5, 3.5])
@test maximum(x) == 3.5
@test minimum(x) == -4.5
@test maximum(abs, x) == 4.5
@test minimum(abs, x) == 2.5
end
let x = spzeros(Float64, 8)
@test maximum(x) == 0.0
@test minimum(x) == 0.0
@test maximum(abs, x) == 0.0
@test minimum(abs, x) == 0.0
end
end
### linalg
@testset "BLAS Level-1" begin
let x = sprand(16, 0.5), x2 = sprand(16, 0.4)
xf = Array(x)
xf2 = Array(x2)
@testset "axpy!" begin
for c in [1.0, -1.0, 2.0, -2.0]
y = Array(x)
@test LinearAlgebra.axpy!(c, x2, y) === y
@test y == Array(x2 * c + x)
end
end
@testset "scale" begin
α = 2.5
sx = SparseVector(x.n, x.nzind, x.nzval * α)
@test exact_equal(x * α, sx)
@test exact_equal(x * (α + 0.0*im), complex(sx))
@test exact_equal(α * x, sx)
@test exact_equal((α + 0.0*im) * x, complex(sx))
@test exact_equal(x * α, sx)
@test exact_equal(α * x, sx)
@test exact_equal(x .* α, sx)
@test exact_equal(α .* x, sx)
@test exact_equal(x / α, SparseVector(x.n, x.nzind, x.nzval / α))
xc = copy(x)
@test rmul!(xc, α) === xc
@test exact_equal(xc, sx)
xc = copy(x)
@test lmul!(α, xc) === xc
@test exact_equal(xc, sx)
xc = copy(x)
@test rmul!(xc, complex(α, 0.0)) === xc
@test exact_equal(xc, sx)
xc = copy(x)
@test lmul!(complex(α, 0.0), xc) === xc
@test exact_equal(xc, sx)
end
@testset "dot" begin
dv = dot(xf, xf2)
@test dot(x, x) == sum(abs2, x)
@test dot(x2, x2) == sum(abs2, x2)
@test dot(x, x2) ≈ dv
@test dot(x2, x) ≈ dv
@test dot(Array(x), x2) ≈ dv
@test dot(x, Array(x2)) ≈ dv
end
end
let x = complex.(sprand(32, 0.6), sprand(32, 0.6)),
y = complex.(sprand(32, 0.6), sprand(32, 0.6))
xf = Array(x)::Vector{ComplexF64}
yf = Array(y)::Vector{ComplexF64}
@test dot(x, x) ≈ dot(xf, xf)
@test dot(x, y) ≈ dot(xf, yf)
end
end
@testset "BLAS Level-2" begin
@testset "dense A * sparse x -> dense y" begin
let A = randn(9, 16), x = sprand(16, 0.7)
xf = Array(x)
for α in [0.0, 1.0, 2.0], β in [0.0, 0.5, 1.0]
y = rand(9)
rr = α*A*xf + β*y
@test mul!(y, A, x, α, β) === y
@test y ≈ rr
end
y = A*x
@test isa(y, Vector{Float64})
@test A*x ≈ A*xf
end
let A = randn(16, 9), x = sprand(16, 0.7)
xf = Array(x)
for α in [0.0, 1.0, 2.0], β in [0.0, 0.5, 1.0]
y = rand(9)
rr = α*A'xf + β*y
@test mul!(y, transpose(A), x, α, β) === y
@test y ≈ rr
end
y = *(transpose(A), x)
@test isa(y, Vector{Float64})
@test y ≈ *(transpose(A), xf)
end
end
@testset "sparse A * sparse x -> dense y" begin
let A = sprandn(9, 16, 0.5), x = sprand(16, 0.7)
Af = Array(A)
xf = Array(x)
for α in [0.0, 1.0, 2.0], β in [0.0, 0.5, 1.0]
y = rand(9)
rr = α*Af*xf + β*y
@test mul!(y, A, x, α, β) === y
@test y ≈ rr
end
y = SparseArrays.densemv(A, x)
@test isa(y, Vector{Float64})
@test y ≈ Af*xf
end
let A = sprandn(16, 9, 0.5), x = sprand(16, 0.7)
Af = Array(A)
xf = Array(x)
for α in [0.0, 1.0, 2.0], β in [0.0, 0.5, 1.0]
y = rand(9)
rr = α*Af'xf + β*y
@test mul!(y, transpose(A), x, α, β) === y
@test y ≈ rr
end
y = SparseArrays.densemv(A, x; trans='T')
@test isa(y, Vector{Float64})
@test y ≈ *(transpose(Af), xf)
end
let A = complex.(sprandn(7, 8, 0.5), sprandn(7, 8, 0.5)),
x = complex.(sprandn(8, 0.6), sprandn(8, 0.6)),
x2 = complex.(sprandn(7, 0.75), sprandn(7, 0.75))
Af = Array(A)
xf = Array(x)
x2f = Array(x2)
@test SparseArrays.densemv(A, x; trans='N') ≈ Af * xf
@test SparseArrays.densemv(A, x2; trans='T') ≈ transpose(Af) * x2f
@test SparseArrays.densemv(A, x2; trans='C') ≈ Af'x2f
@test_throws ArgumentError SparseArrays.densemv(A, x; trans='D')
end
end
@testset "sparse A * sparse x -> sparse y" begin
let A = sprandn(9, 16, 0.5), x = sprand(16, 0.7), x2 = sprand(9, 0.7)
Af = Array(A)
xf = Array(x)
x2f = Array(x2)
y = A*x
@test isa(y, SparseVector{Float64,Int})
@test all(nonzeros(y) .!= 0.0)
@test Array(y) ≈ Af * xf
y = *(transpose(A), x2)
@test isa(y, SparseVector{Float64,Int})
@test all(nonzeros(y) .!= 0.0)
@test Array(y) ≈ Af'x2f
end
let A = complex.(sprandn(7, 8, 0.5), sprandn(7, 8, 0.5)),
x = complex.(sprandn(8, 0.6), sprandn(8, 0.6)),
x2 = complex.(sprandn(7, 0.75), sprandn(7, 0.75))
Af = Array(A)
xf = Array(x)
x2f = Array(x2)
y = A*x
@test isa(y, SparseVector{ComplexF64,Int})
@test Array(y) ≈ Af * xf
y = *(transpose(A), x2)
@test isa(y, SparseVector{ComplexF64,Int})
@test Array(y) ≈ transpose(Af) * x2f
y = *(adjoint(A), x2)
@test isa(y, SparseVector{ComplexF64,Int})
@test Array(y) ≈ Af'x2f
end
end
@testset "ldiv ops with triangular matrices and sparse vecs (#14005)" begin
m = 10
sparsefloatvecs = SparseVector[sprand(m, 0.4) for k in 1:3]
sparseintvecs = SparseVector[SparseVector(m, sprvec.nzind, round.(Int, sprvec.nzval*10)) for sprvec in sparsefloatvecs]
sparsecomplexvecs = SparseVector[SparseVector(m, sprvec.nzind, complex.(sprvec.nzval, sprvec.nzval)) for sprvec in sparsefloatvecs]
sprmat = sprand(m, m, 0.2)
sparsefloatmat = I + sprmat/(2m)
sparsecomplexmat = I + SparseMatrixCSC(m, m, sprmat.colptr, sprmat.rowval, complex.(sprmat.nzval, sprmat.nzval)/(4m))
sparseintmat = 10m*I + SparseMatrixCSC(m, m, sprmat.colptr, sprmat.rowval, round.(Int, sprmat.nzval*10))
denseintmat = I*10m + rand(1:m, m, m)
densefloatmat = I + randn(m, m)/(2m)
densecomplexmat = I + randn(Complex{Float64}, m, m)/(4m)
inttypes = (Int32, Int64, BigInt)
floattypes = (Float32, Float64, BigFloat)
complextypes = (Complex{Float32}, Complex{Float64})
eltypes = (inttypes..., floattypes..., complextypes...)
for eltypemat in eltypes
(densemat, sparsemat) = eltypemat in inttypes ? (denseintmat, sparseintmat) :
eltypemat in floattypes ? (densefloatmat, sparsefloatmat) :
eltypemat in complextypes && (densecomplexmat, sparsecomplexmat)
densemat = convert(Matrix{eltypemat}, densemat)
sparsemat = convert(SparseMatrixCSC{eltypemat}, sparsemat)
trimats = (LowerTriangular(densemat), UpperTriangular(densemat),
LowerTriangular(sparsemat), UpperTriangular(sparsemat) )
unittrimats = (LinearAlgebra.UnitLowerTriangular(densemat), LinearAlgebra.UnitUpperTriangular(densemat),
LinearAlgebra.UnitLowerTriangular(sparsemat), LinearAlgebra.UnitUpperTriangular(sparsemat) )
for eltypevec in eltypes
spvecs = eltypevec in inttypes ? sparseintvecs :
eltypevec in floattypes ? sparsefloatvecs :
eltypevec in complextypes && sparsecomplexvecs
spvecs = SparseVector[SparseVector(m, spvec.nzind, convert(Vector{eltypevec}, spvec.nzval)) for spvec in spvecs]
for spvec in spvecs
fspvec = convert(Array, spvec)
# test out-of-place left-division methods
for mat in (trimats..., unittrimats...)
@test \(mat, spvec) ≈ \(mat, fspvec)
@test \(adjoint(mat), spvec) ≈ \(adjoint(mat), fspvec)
@test \(transpose(mat), spvec) ≈ \(transpose(mat), fspvec)
end
# test in-place left-division methods not involving quotients
if eltypevec == typeof(zero(eltypemat)*zero(eltypevec) + zero(eltypemat)*zero(eltypevec))
for mat in unittrimats
@test ldiv!(mat, copy(spvec)) ≈ ldiv!(mat, copy(fspvec))
@test ldiv!(adjoint(mat), copy(spvec)) ≈ ldiv!(adjoint(mat), copy(fspvec))
@test ldiv!(transpose(mat), copy(spvec)) ≈ ldiv!(transpose(mat), copy(fspvec))
end
end
# test in-place left-division methods involving quotients
if eltypevec == typeof((zero(eltypemat)*zero(eltypevec) + zero(eltypemat)*zero(eltypevec))/one(eltypemat))
for mat in trimats
@test ldiv!(mat, copy(spvec)) ≈ ldiv!(mat, copy(fspvec))
@test ldiv!(adjoint(mat), copy(spvec)) ≈ ldiv!(adjoint(mat), copy(fspvec))
@test ldiv!(transpose(mat), copy(spvec)) ≈ ldiv!(transpose(mat), copy(fspvec))
end
end
end
end
end
end
@testset "#16716" begin
# The preceding tests miss the edge case where the sparse vector is empty
origmat = [-1.5 -0.7; 0.0 1.0]
transmat = copy(origmat')
utmat = UpperTriangular(origmat)
ltmat = LowerTriangular(transmat)
uutmat = LinearAlgebra.UnitUpperTriangular(origmat)
ultmat = LinearAlgebra.UnitLowerTriangular(transmat)
zerospvec = spzeros(Float64, 2)
zerodvec = zeros(Float64, 2)
for mat in (utmat, ltmat, uutmat, ultmat)
@test isequal(\(mat, zerospvec), zerodvec)
@test isequal(\(adjoint(mat), zerospvec), zerodvec)
@test isequal(\(transpose(mat), zerospvec), zerodvec)
@test isequal(ldiv!(mat, copy(zerospvec)), zerospvec)
@test isequal(ldiv!(adjoint(mat), copy(zerospvec)), zerospvec)
@test isequal(ldiv!(transpose(mat), copy(zerospvec)), zerospvec)
end
end
end
@testset "kron" begin
testdims = ((5,10), (20,12), (25,30))
for (m,n) in testdims
x = sprand(m, 0.4)
y = sprand(n, 0.3)
@test Vector(kron(x,y)) == kron(Vector(x), Vector(y))
@test Vector(kron(Vector(x),y)) == kron(Vector(x), Vector(y))
@test Vector(kron(x,Vector(y))) == kron(Vector(x), Vector(y))
# test different types
z = convert(SparseVector{Float16, Int8}, y)
@test Vector(kron(x, z)) == kron(Vector(x), Vector(z))
end
end
@testset "fkeep!" begin
x = sparsevec(1:7, [3., 2., -1., 1., -2., -3., 3.], 7)
# droptol
xdrop = SparseArrays.droptol!(copy(x), 1.5)
@test exact_equal(xdrop, SparseVector(7, [1, 2, 5, 6, 7], [3., 2., -2., -3., 3.]))
SparseArrays.droptol!(xdrop, 2.5)
@test exact_equal(xdrop, SparseVector(7, [1, 6, 7], [3., -3., 3.]))
SparseArrays.droptol!(xdrop, 3.)
@test exact_equal(xdrop, SparseVector(7, Int[], Float64[]))
xdrop = copy(x)
# This will keep index 1, 3, 4, 7 in xdrop
f_drop(i, x) = (abs(x) == 1.) || (i in [1, 7])
SparseArrays.fkeep!(xdrop, f_drop)
@test exact_equal(xdrop, SparseVector(7, [1, 3, 4, 7], [3., -1., 1., 3.]))
end
@testset "dropzeros[!] with length=$m" for m in (10, 20, 30)
srand(123)
nzprob, targetnumposzeros, targetnumnegzeros = 0.4, 5, 5
v = sprand(m, nzprob)
struczerosv = findall(x -> x == 0, v)
poszerosinds = unique(rand(struczerosv, targetnumposzeros))
negzerosinds = unique(rand(struczerosv, targetnumnegzeros))
vposzeros = copy(v)
vposzeros[poszerosinds] .= 2
vnegzeros = copy(v)
vnegzeros[negzerosinds] .= -2
vbothsigns = copy(vposzeros)
vbothsigns[negzerosinds] .= -2
map!(x -> x == 2 ? 0.0 : x, vposzeros.nzval, vposzeros.nzval)
map!(x -> x == -2 ? -0.0 : x, vnegzeros.nzval, vnegzeros.nzval)
map!(x -> x == 2 ? 0.0 : x == -2 ? -0.0 : x, vbothsigns.nzval, vbothsigns.nzval)
for vwithzeros in (vposzeros, vnegzeros, vbothsigns)
# Basic functionality / dropzeros!
@test dropzeros!(copy(vwithzeros)) == v
@test dropzeros!(copy(vwithzeros), trim = false) == v
# Basic functionality / dropzeros
@test dropzeros(vwithzeros) == v
@test dropzeros(vwithzeros, trim = false) == v
# Check trimming works as expected
@test length(dropzeros!(copy(vwithzeros)).nzval) == length(v.nzval)
@test length(dropzeros!(copy(vwithzeros)).nzind) == length(v.nzind)
@test length(dropzeros!(copy(vwithzeros), trim = false).nzval) == length(vwithzeros.nzval)
@test length(dropzeros!(copy(vwithzeros), trim = false).nzind) == length(vwithzeros.nzind)
end
end
@testset "original dropzeros! test" begin
xdrop = sparsevec(1:7, [3., 2., -1., 1., -2., -3., 3.], 7)
xdrop.nzval[[2, 4, 6]] .= 0.0
SparseArrays.dropzeros!(xdrop)
@test exact_equal(xdrop, SparseVector(7, [1, 3, 5, 7], [3, -1., -2., 3.]))
end
# It's tempting to share data between a SparseVector and a SparseMatrix,
# but if that's done, then modifications to one or the other will cause
# an inconsistent state:
sv = sparse(1:10)
sm = convert(SparseMatrixCSC, sv)
sv[1] = 0
@test Array(sm)[2:end] == 2:10
# Ensure that sparsevec with all-zero values returns an array of zeros
@test sparsevec([1,2,3],[0,0,0]) == [0,0,0]
@testset "stored zero semantics" begin
# Compare stored zero semantics between SparseVector and SparseMatrixCSC
let S = SparseMatrixCSC(10,1,[1,6],[1,3,5,6,7],[0,1,2,0,3]), x = SparseVector(10,[1,3,5,6,7],[0,1,2,0,3])
@test nnz(S) == nnz(x) == 5
for I = (:, 1:10, Vector(1:10))
@test S[I,1] == S[I] == x[I] == x
@test nnz(S[I,1]) == nnz(S[I]) == nnz(x[I]) == nnz(x)
end
for I = (2:9, 1:2, 9:10, [3,6,1], [10,9,8], [])
@test S[I,1] == S[I] == x[I]
@test nnz(S[I,1]) == nnz(S[I]) == nnz(x[I])
end
@test S[[1 3 5; 2 4 6]] == x[[1 3 5; 2 4 6]]
@test nnz(S[[1 3 5; 2 4 6]]) == nnz(x[[1 3 5; 2 4 6]])
end
end
@testset "Issue 14013" begin
s14013 = sparse([10.0 0.0 30.0; 0.0 1.0 0.0])
a14013 = [10.0 0.0 30.0; 0.0 1.0 0.0]
@test s14013 == a14013
@test vec(s14013) == s14013[:] == a14013[:]
@test Array(s14013)[1,:] == s14013[1,:] == a14013[1,:] == [10.0, 0.0, 30.0]
@test Array(s14013)[2,:] == s14013[2,:] == a14013[2,:] == [0.0, 1.0, 0.0]
end
@testset "Issue 14046" begin
s14046 = sprand(5, 1.0)
@test spzeros(5) + s14046 == s14046
@test 2*s14046 == s14046 + s14046
end
@testset "Issue 14589" begin
# test vectors with no zero elements
let x = sparsevec(1:7, [3., 2., -1., 1., -2., -3., 3.], 7)
@test Vector(sort(x)) == sort(Vector(x))
end
# test vectors with all zero elements
let x = sparsevec(Int64[], Float64[], 7)
@test Vector(sort(x)) == sort(Vector(x))
end
# test vector with sparsity approx 1/2
let x = sparsevec(1:7, [3., 2., -1., 1., -2., -3., 3.], 15)
@test Vector(sort(x)) == sort(Vector(x))
# apply three distinct tranformations where zeros sort into start/middle/end
@test Vector(sort(x, by=abs)) == sort(Vector(x), by=abs)
@test Vector(sort(x, by=sign)) == sort(Vector(x), by=sign)
@test Vector(sort(x, by=inv)) == sort(Vector(x), by=inv)
end
end
@testset "fill!" begin
for Tv in [Float32, Float64, Int64, Int32, ComplexF64]
for Ti in [Int16, Int32, Int64, BigInt]
sptypes = (SparseMatrixCSC{Tv, Ti}, SparseVector{Tv, Ti})
sizes = [(3, 4), (3,)]
for (siz, Sp) in zip(sizes, sptypes)
arr = rand(Tv, siz...)
sparr = Sp(arr)
x = rand(Tv)
@test fill!(sparr, x) == fill(x, siz)
@test fill!(sparr, 0) == fill(0, siz)
end
end
end
end
@testset "13130 and 16661" begin
@test issparse([sprand(10,10,.1) sprand(10,.1)])
@test issparse([sprand(10,1,.1); sprand(10,.1)])
@test issparse([sprand(10,10,.1) rand(10)])
@test issparse([sprand(10,1,.1) rand(10)])
@test issparse([sprand(10,2,.1) sprand(10,1,.1) rand(10)])
@test issparse([sprand(10,1,.1); rand(10)])
@test issparse([sprand(10,.1) rand(10)])
@test issparse([sprand(10,.1); rand(10)])
end
mutable struct t20488 end
@testset "show" begin
io = IOBuffer()
show(io, MIME"text/plain"(), sparsevec(Int64[1], [1.0]))
@test String(take!(io)) == "1-element SparseArrays.SparseVector{Float64,Int64} with 1 stored entry:\n [1] = 1.0"
show(io, MIME"text/plain"(), spzeros(Float64, Int64, 2))
@test String(take!(io)) == "2-element SparseArrays.SparseVector{Float64,Int64} with 0 stored entries"
show(io, similar(sparsevec(rand(3) .+ 0.1), t20488))
@test String(take!(io)) == " [1] = #undef\n [2] = #undef\n [3] = #undef"
end
@testset "spzeros with index type" begin
@test typeof(spzeros(Float32, Int16, 3)) == SparseVector{Float32,Int16}
end
@testset "corner cases of broadcast arithmetic operations with scalars (#21515)" begin
# test both scalar literals and variables
areequal(a, b, c) = isequal(a, b) && isequal(b, c)
inf, zeroh, zv, spzv = Inf, 0.0, zeros(1), spzeros(1)
@test areequal(spzv .* Inf, spzv .* inf, sparsevec(zv .* Inf))
@test areequal(Inf .* spzv, inf .* spzv, sparsevec(Inf .* zv))
@test areequal(spzv ./ 0.0, spzv ./ zeroh, sparsevec(zv ./ 0.0))
@test areequal(0.0 .\ spzv, zeroh .\ spzv, sparsevec(0.0 .\ zv))
end
@testset "similar for SparseVector" begin
A = SparseVector(10, Int[1, 3, 5, 7], Float64[1.0, 3.0, 5.0, 7.0])
# test similar without specifications (preserves stored-entry structure)
simA = similar(A)
@test typeof(simA) == typeof(A)
@test size(simA) == size(A)
@test simA.nzind == A.nzind
@test length(simA.nzval) == length(A.nzval)
# test similar with entry type specification (preserves stored-entry structure)
simA = similar(A, Float32)
@test typeof(simA) == SparseVector{Float32,eltype(A.nzind)}
@test size(simA) == size(A)
@test simA.nzind == A.nzind
@test length(simA.nzval) == length(A.nzval)
# test similar with entry and index type specification (preserves stored-entry structure)
simA = similar(A, Float32, Int8)
@test typeof(simA) == SparseVector{Float32,Int8}
@test size(simA) == size(A)
@test simA.nzind == A.nzind
@test length(simA.nzval) == length(A.nzval)
# test similar with Dims{1} specification (preserves nothing)
simA = similar(A, (6,))
@test typeof(simA) == typeof(A)
@test size(simA) == (6,)
@test length(simA.nzind) == 0
@test length(simA.nzval) == 0
# test similar with entry type and Dims{1} specification (preserves nothing)
simA = similar(A, Float32, (6,))
@test typeof(simA) == SparseVector{Float32,eltype(A.nzind)}
@test size(simA) == (6,)
@test length(simA.nzind) == 0
@test length(simA.nzval) == 0
# test similar with entry type, index type, and Dims{1} specification (preserves nothing)
simA = similar(A, Float32, Int8, (6,))
@test typeof(simA) == SparseVector{Float32,Int8}
@test size(simA) == (6,)
@test length(simA.nzind) == 0
@test length(simA.nzval) == 0
# test entry points to similar with entry type, index type, and non-Dims shape specification
@test similar(A, Float32, Int8, 6, 6) == similar(A, Float32, Int8, (6, 6))
@test similar(A, Float32, Int8, 6) == similar(A, Float32, Int8, (6,))
# test similar with Dims{2} specification (preserves storage space only, not stored-entry structure)
simA = similar(A, (6,6))
@test typeof(simA) == SparseMatrixCSC{eltype(A.nzval),eltype(A.nzind)}
@test size(simA) == (6,6)
@test simA.colptr == fill(1, 6+1)
@test length(simA.rowval) == length(A.nzind)
@test length(simA.nzval) == length(A.nzval)
# test similar with entry type and Dims{2} specification (preserves storage space only)
simA = similar(A, Float32, (6,6))
@test typeof(simA) == SparseMatrixCSC{Float32,eltype(A.nzind)}
@test size(simA) == (6,6)
@test simA.colptr == fill(1, 6+1)
@test length(simA.rowval) == length(A.nzind)
@test length(simA.nzval) == length(A.nzval)
# test similar with entry type, index type, and Dims{2} specification (preserves storage space only)
simA = similar(A, Float32, Int8, (6,6))
@test typeof(simA) == SparseMatrixCSC{Float32, Int8}
@test size(simA) == (6,6)
@test simA.colptr == fill(1, 6+1)
@test length(simA.rowval) == length(A.nzind)
@test length(simA.nzval) == length(A.nzval)
end
@testset "Fast operations on full column views" begin
n = 1000
A = sprandn(n, n, 0.01)
for j in 1:5:n
Aj, Ajview = A[:, j], view(A, :, j)
@test norm(Aj) == norm(Ajview)
@test dot(Aj, copy(Aj)) == dot(Ajview, Aj) # don't alias since it takes a different code path
@test rmul!(Aj, 0.1) == rmul!(Ajview, 0.1)
@test Aj*0.1 == Ajview*0.1
@test 0.1*Aj == 0.1*Ajview
@test Aj/0.1 == Ajview/0.1
@test LinearAlgebra.axpy!(1.0, Aj, sparse(fill(1., n))) ==
LinearAlgebra.axpy!(1.0, Ajview, sparse(fill(1., n)))
@test LinearAlgebra.lowrankupdate!(Matrix(1.0*I, n, n), fill(1.0, n), Aj) ==
LinearAlgebra.lowrankupdate!(Matrix(1.0*I, n, n), fill(1.0, n), Ajview)
end
end
end # module
| 37.039937
| 139
| 0.525666
|
[
"@testset \"basic properties\" begin\n x = spv_x1\n @test eltype(x) == Float64\n @test ndims(x) == 1\n @test length(x) == 8\n @test size(x) == (8,)\n @test size(x,1) == 8\n @test size(x,2) == 1\n @test !isempty(x)\n\n @test count(!iszero, x) == 3\n @test nnz(x) == 3\n @test SparseArrays.nonzeroinds(x) == [2, 5, 6]\n @test nonzeros(x) == [1.25, -0.75, 3.5]\n @test count(SparseVector(8, [2, 5, 6], [true,false,true])) == 2\nend",
"@testset \"conversion to dense Array\" begin\n for (x, xf) in [(spv_x1, x1_full)]\n @test isa(Array(x), Vector{Float64})\n @test Array(x) == xf\n @test Vector(x) == xf\n end\nend",
"@testset \"show\" begin\n @test occursin(\"1.25\", string(spv_x1))\n @test occursin(\"-0.75\", string(spv_x1))\n @test occursin(\"3.5\", string(spv_x1))\nend",
"@testset \"other constructors\" begin\n # construct empty sparse vector\n\n @test exact_equal(spzeros(Float64, 8), SparseVector(8, Int[], Float64[]))\n\n @testset \"from list of indices and values\" begin\n @test exact_equal(\n sparsevec(Int[], Float64[], 8),\n SparseVector(8, Int[], Float64[]))\n\n @test exact_equal(\n sparsevec(Int[], Float64[]),\n SparseVector(0, Int[], Float64[]))\n\n @test exact_equal(\n sparsevec([3, 3], [5.0, -5.0], 8),\n SparseVector(8, [3], [0.0]))\n\n @test exact_equal(\n sparsevec([2, 3, 6], [12.0, 18.0, 25.0]),\n SparseVector(6, [2, 3, 6], [12.0, 18.0, 25.0]))\n\n let x0 = SparseVector(8, [2, 3, 6], [12.0, 18.0, 25.0])\n @test exact_equal(\n sparsevec([2, 3, 6], [12.0, 18.0, 25.0], 8), x0)\n\n @test exact_equal(\n sparsevec([3, 6, 2], [18.0, 25.0, 12.0], 8), x0)\n\n @test exact_equal(\n sparsevec([2, 3, 4, 4, 6], [12.0, 18.0, 5.0, -5.0, 25.0], 8),\n SparseVector(8, [2, 3, 4, 6], [12.0, 18.0, 0.0, 25.0]))\n\n @test exact_equal(\n sparsevec([1, 1, 1, 2, 3, 3, 6], [2.0, 3.0, -5.0, 12.0, 10.0, 8.0, 25.0], 8),\n SparseVector(8, [1, 2, 3, 6], [0.0, 12.0, 18.0, 25.0]))\n\n @test exact_equal(\n sparsevec([2, 3, 6, 7, 7], [12.0, 18.0, 25.0, 5.0, -5.0], 8),\n SparseVector(8, [2, 3, 6, 7], [12.0, 18.0, 25.0, 0.0]))\n end\n\n @test exact_equal(\n sparsevec(Any[1, 3], [1, 1]),\n sparsevec([1, 3], [1, 1]))\n\n @test exact_equal(\n sparsevec(Any[1, 3], [1, 1], 5),\n sparsevec([1, 3], [1, 1], 5))\n end\n @testset \"from dictionary\" begin\n function my_intmap(x)\n a = Dict{Int,eltype(x)}()\n for i in SparseArrays.nonzeroinds(x)\n a[i] = x[i]\n end\n return a\n end\n\n let x = spv_x1\n a = my_intmap(x)\n xc = sparsevec(a, 8)\n @test exact_equal(x, xc)\n\n xc = sparsevec(a)\n @test exact_equal(xc, SparseVector(6, [2, 5, 6], [1.25, -0.75, 3.5]))\n\n d = Dict{Int, Float64}((1 => 0.0, 2 => 1.0, 3 => 2.0))\n @test exact_equal(sparsevec(d), SparseVector(3, [1, 2, 3], [0.0, 1.0, 2.0]))\n end\n end\n @testset \"fillstored!\" begin\n x = SparseVector(8, [2, 3, 6], [12.0, 18.0, 25.0])\n y = LinearAlgebra.fillstored!(copy(x), 1)\n @test (x .!= 0) == (y .!= 0)\n @test y == SparseVector(8, [2, 3, 6], [1.0, 1.0, 1.0])\n end\n\n @testset \"sprand & sprandn\" begin\n let xr = sprand(1000, 0.9)\n @test isa(xr, SparseVector{Float64,Int})\n @test length(xr) == 1000\n @test all(nonzeros(xr) .>= 0.0)\n end\n\n let xr = sprand(Float32, 1000, 0.9)\n @test isa(xr, SparseVector{Float32,Int})\n @test length(xr) == 1000\n @test all(nonzeros(xr) .>= 0.0)\n end\n\n let xr = sprandn(1000, 0.9)\n @test isa(xr, SparseVector{Float64,Int})\n @test length(xr) == 1000\n if !isempty(nonzeros(xr))\n @test any(nonzeros(xr) .> 0.0) && any(nonzeros(xr) .< 0.0)\n end\n end\n\n let xr = sprand(Bool, 1000, 0.9)\n @test isa(xr, SparseVector{Bool,Int})\n @test length(xr) == 1000\n @test all(nonzeros(xr))\n end\n\n let r1 = MersenneTwister(0), r2 = MersenneTwister(0)\n @test sprand(r1, 100, .9) == sprand(r2, 100, .9)\n @test sprandn(r1, 100, .9) == sprandn(r2, 100, .9)\n @test sprand(r1, Bool, 100, .9) == sprand(r2, Bool, 100, .9)\n end\n end\nend",
"@testset \"getindex\" begin\n @testset \"single integer index\" begin\n for (x, xf) in [(spv_x1, x1_full)]\n for i = 1:length(x)\n @test x[i] == xf[i]\n end\n end\n end\n @testset \"generic array index\" begin\n let x = sprand(100, 0.5)\n I = rand(1:length(x), 20)\n r = x[I]\n @test isa(r, SparseVector{Float64,Int})\n @test all(!iszero, nonzeros(r))\n @test Array(r) == Array(x)[I]\n end\n\n # issue 24534\n let x = convert(SparseVector{Float64,UInt32},sprandn(100,0.5))\n I = rand(1:length(x), 20)\n r = x[I]\n @test isa(r, SparseVector{Float64,UInt32})\n @test all(!iszero, nonzeros(r))\n @test Array(r) == Array(x)[I]\n end\n\n # issue 24534\n let x = convert(SparseVector{Float64,UInt32},sprandn(100,0.5))\n I = rand(1:length(x), 20,1)\n r = x[I]\n @test isa(r, SparseMatrixCSC{Float64,UInt32})\n @test all(!iszero, nonzeros(r))\n @test Array(r) == Array(x)[I]\n end\n end\n @testset \"boolean array index\" begin\n let x = sprand(10, 10, 0.5)\n I = rand(1:size(x, 2), 10)\n bI = falses(size(x, 2))\n bI[I] .= true\n r = x[1,bI]\n @test isa(r, SparseVector{Float64,Int})\n @test all(!iszero, nonzeros(r))\n @test Array(r) == Array(x)[1,bI]\n end\n\n let x = sprand(10, 0.5)\n I = rand(1:length(x), 5)\n bI = falses(length(x))\n bI[I] .= true\n r = x[bI]\n @test isa(r, SparseVector{Float64,Int})\n @test all(!iszero, nonzeros(r))\n @test Array(r) == Array(x)[bI]\n end\n end\nend",
"@testset \"setindex\" begin\n let xc = spzeros(Float64, 8)\n xc[3] = 2.0\n @test exact_equal(xc, SparseVector(8, [3], [2.0]))\n end\n\n let xc = copy(spv_x1)\n xc[5] = 2.0\n @test exact_equal(xc, SparseVector(8, [2, 5, 6], [1.25, 2.0, 3.5]))\n end\n\n let xc = copy(spv_x1)\n xc[3] = 4.0\n @test exact_equal(xc, SparseVector(8, [2, 3, 5, 6], [1.25, 4.0, -0.75, 3.5]))\n\n xc[1] = 6.0\n @test exact_equal(xc, SparseVector(8, [1, 2, 3, 5, 6], [6.0, 1.25, 4.0, -0.75, 3.5]))\n\n xc[8] = -1.5\n @test exact_equal(xc, SparseVector(8, [1, 2, 3, 5, 6, 8], [6.0, 1.25, 4.0, -0.75, 3.5, -1.5]))\n end\n\n let xc = copy(spv_x1)\n xc[5] = 0.0\n @test exact_equal(xc, SparseVector(8, [2, 5, 6], [1.25, 0.0, 3.5]))\n\n xc[6] = 0.0\n @test exact_equal(xc, SparseVector(8, [2, 5, 6], [1.25, 0.0, 0.0]))\n\n xc[2] = 0.0\n @test exact_equal(xc, SparseVector(8, [2, 5, 6], [0.0, 0.0, 0.0]))\n\n xc[1] = 0.0\n @test exact_equal(xc, SparseVector(8, [2, 5, 6], [0.0, 0.0, 0.0]))\n end\nend",
"@testset \"dropstored!\" begin\n x = SparseVector(10, [2, 7, 9], [2.0, 7.0, 9.0])\n # Test argument bounds checking for dropstored!(x, i)\n @test_throws BoundsError SparseArrays.dropstored!(x, 0)\n @test_throws BoundsError SparseArrays.dropstored!(x, 11)\n # Test behavior of dropstored!(x, i)\n # --> Test dropping a single stored entry\n @test SparseArrays.dropstored!(x, 2) == SparseVector(10, [7, 9], [7.0, 9.0])\n # --> Test dropping a single nonstored entry\n @test SparseArrays.dropstored!(x, 5) == SparseVector(10, [7, 9], [7.0, 9.0])\nend",
"@testset \"findall and findnz\" begin\n @test findall(!iszero, spv_x1) == findall(!iszero, x1_full)\n @test findall(spv_x1 .> 1) == findall(x1_full .> 1)\n @test findall(x->x>1, spv_x1) == findall(x->x>1, x1_full)\n @test findnz(spv_x1) == (findall(!iszero, x1_full), filter(x->x!=0, x1_full))\n let xc = SparseVector(8, [2, 3, 5], [1.25, 0, -0.75]), fc = Array(xc)\n @test findall(!iszero, xc) == findall(!iszero, fc)\n @test findnz(xc) == ([2, 3, 5], [1.25, 0, -0.75])\n end\nend",
"@testset \"copy[!]\" begin\n\n let x = spv_x1\n xc = copy(x)\n @test isa(xc, SparseVector{Float64,Int})\n @test x.nzind !== xc.nzval\n @test x.nzval !== xc.nzval\n @test exact_equal(x, xc)\n end\n\n let x1 = SparseVector(8, [2, 5, 6], [12.2, 1.4, 5.0])\n x2 = SparseVector(8, [3, 4], [1.2, 3.4])\n copyto!(x2, x1)\n @test x2 == x1\n x2 = SparseVector(8, [2, 4, 8], [10.3, 7.4, 3.1])\n copyto!(x2, x1)\n @test x2 == x1\n x2 = SparseVector(8, [1, 3, 4, 7], [0.3, 1.2, 3.4, 0.1])\n copyto!(x2, x1)\n @test x2 == x1\n x2 = SparseVector(10, [3, 4], [1.2, 3.4])\n copyto!(x2, x1)\n @test x2[1:8] == x1\n @test x2[9:10] == spzeros(2)\n x2 = SparseVector(10, [3, 4, 9], [1.2, 3.4, 17.8])\n copyto!(x2, x1)\n @test x2[1:8] == x1\n @test x2[9] == 17.8\n @test x2[10] == 0\n x2 = SparseVector(10, [3, 4, 5, 6, 9], [8.3, 7.2, 1.2, 3.4, 17.8])\n copyto!(x2, x1)\n @test x2[1:8] == x1\n @test x2[9] == 17.8\n @test x2[10] == 0\n x2 = SparseVector(6, [3, 4], [1.2, 3.4])\n @test_throws BoundsError copyto!(x2, x1)\n end\n\n let x1 = sparse([2, 1, 2], [1, 3, 3], [12.2, 1.4, 5.0], 2, 4)\n x2 = SparseVector(8, [3, 4], [1.2, 3.4])\n copyto!(x2, x1)\n @test x2[:] == x1[:]\n x2 = SparseVector(8, [2, 4, 8], [10.3, 7.4, 3.1])\n copyto!(x2, x1)\n @test x2[:] == x1[:]\n x2 = SparseVector(8, [1, 3, 4, 7], [0.3, 1.2, 3.4, 0.1])\n copyto!(x2, x1)\n @test x2[:] == x1[:]\n x2 = SparseVector(10, [3, 4], [1.2, 3.4])\n copyto!(x2, x1)\n @test x2[1:8] == x1[:]\n @test x2[9:10] == spzeros(2)\n x2 = SparseVector(10, [3, 4, 9], [1.2, 3.4, 17.8])\n copyto!(x2, x1)\n @test x2[1:8] == x1[:]\n @test x2[9] == 17.8\n @test x2[10] == 0\n x2 = SparseVector(10, [3, 4, 5, 6, 9], [8.3, 7.2, 1.2, 3.4, 17.8])\n copyto!(x2, x1)\n @test x2[1:8] == x1[:]\n @test x2[9] == 17.8\n @test x2[10] == 0\n x2 = SparseVector(6, [3, 4], [1.2, 3.4])\n @test_throws BoundsError copyto!(x2, x1)\n end\n\n let x1 = SparseVector(8, [2, 5, 6], [12.2, 1.4, 5.0])\n x2 = sparse([1, 2], [2, 2], [1.2, 3.4], 2, 4)\n copyto!(x2, x1)\n @test x2[:] == x1[:]\n x2 = sparse([2, 2, 2], [1, 3, 4], [10.3, 7.4, 3.1], 2, 4)\n copyto!(x2, x1)\n @test x2[:] == x1[:]\n x2 = sparse([1, 1, 2, 1], [1, 2, 2, 4], [0.3, 1.2, 3.4, 0.1], 2, 4)\n copyto!(x2, x1)\n @test x2[:] == x1[:]\n x2 = sparse([1, 2], [2, 2], [1.2, 3.4], 2, 5)\n copyto!(x2, x1)\n @test x2[1:8] == x1\n @test x2[9:10] == spzeros(2)\n x2 = sparse([1, 2, 1], [2, 2, 5], [1.2, 3.4, 17.8], 2, 5)\n copyto!(x2, x1)\n @test x2[1:8] == x1\n @test x2[9] == 17.8\n @test x2[10] == 0\n x2 = sparse([1, 2, 1, 2, 1], [2, 2, 3, 3, 5], [8.3, 7.2, 1.2, 3.4, 17.8], 2, 5)\n copyto!(x2, x1)\n @test x2[1:8] == x1\n @test x2[9] == 17.8\n @test x2[10] == 0\n x2 = sparse([1, 2], [2, 2], [1.2, 3.4], 2, 3)\n @test_throws BoundsError copyto!(x2, x1)\n end\nend",
"@testset \"vec/reinterpret/float/complex\" begin\n a = SparseVector(8, [2, 5, 6], Int32[12, 35, 72])\n # vec\n @test vec(a) == a\n\n # float\n af = float(a)\n @test float(af) == af\n @test isa(af, SparseVector{Float64,Int})\n @test exact_equal(af, SparseVector(8, [2, 5, 6], [12., 35., 72.]))\n @test sparsevec(transpose(transpose(af))) == af\n\n # complex\n acp = complex(af)\n @test complex(acp) == acp\n @test isa(acp, SparseVector{ComplexF64,Int})\n @test exact_equal(acp, SparseVector(8, [2, 5, 6], complex([12., 35., 72.])))\n @test sparsevec((acp')') == acp\nend",
"@testset \"Type conversion\" begin\n let x = convert(SparseVector, sparse([2, 5, 6], [1, 1, 1], [1.25, -0.75, 3.5], 8, 1))\n @test isa(x, SparseVector{Float64,Int})\n @test exact_equal(x, spv_x1)\n end\n\n let x = spv_x1, xf = x1_full\n xc = convert(SparseVector, xf)\n @test isa(xc, SparseVector{Float64,Int})\n @test exact_equal(xc, x)\n\n xc = convert(SparseVector{Float32,Int}, x)\n xf32 = SparseVector(8, [2, 5, 6], [1.25f0, -0.75f0, 3.5f0])\n @test isa(xc, SparseVector{Float32,Int})\n @test exact_equal(xc, xf32)\n\n xc = convert(SparseVector{Float32}, x)\n @test isa(xc, SparseVector{Float32,Int})\n @test exact_equal(xc, xf32)\n\n xm = convert(SparseMatrixCSC, x)\n @test isa(xm, SparseMatrixCSC{Float64,Int})\n @test Array(xm) == reshape(xf, 8, 1)\n\n xm = convert(SparseMatrixCSC{Float32}, x)\n @test isa(xm, SparseMatrixCSC{Float32,Int})\n @test Array(xm) == reshape(convert(Vector{Float32}, xf), 8, 1)\n end\nend",
"@testset \"Concatenation\" begin\n let m = 80, n = 100\n A = Vector{SparseVector{Float64,Int}}(undef, n)\n tnnz = 0\n for i = 1:length(A)\n A[i] = sprand(m, 0.3)\n tnnz += nnz(A[i])\n end\n\n H = hcat(A...)\n @test isa(H, SparseMatrixCSC{Float64,Int})\n @test size(H) == (m, n)\n @test nnz(H) == tnnz\n Hr = zeros(m, n)\n for j = 1:n\n Hr[:,j] = Array(A[j])\n end\n @test Array(H) == Hr\n\n V = vcat(A...)\n @test isa(V, SparseVector{Float64,Int})\n @test length(V) == m * n\n Vr = vec(Hr)\n @test Array(V) == Vr\n end\n\n @testset \"concatenation of sparse vectors with other types\" begin\n # Test that concatenations of combinations of sparse vectors with various other\n # matrix/vector types yield sparse arrays\n let N = 4\n spvec = spzeros(N)\n spmat = spzeros(N, 1)\n densevec = fill(1., N)\n densemat = fill(1., N, 1)\n diagmat = Diagonal(densevec)\n # Test that concatenations of pairwise combinations of sparse vectors with dense\n # vectors/matrices, sparse matrices, or special matrices yield sparse arrays\n for othervecormat in (densevec, densemat, spmat)\n @test issparse(vcat(spvec, othervecormat))\n @test issparse(vcat(othervecormat, spvec))\n end\n for othervecormat in (densevec, densemat, spmat, diagmat)\n @test issparse(hcat(spvec, othervecormat))\n @test issparse(hcat(othervecormat, spvec))\n @test issparse(hvcat((2,), spvec, othervecormat))\n @test issparse(hvcat((2,), othervecormat, spvec))\n @test issparse(cat(spvec, othervecormat; dims=(1,2)))\n @test issparse(cat(othervecormat, spvec; dims=(1,2)))\n end\n # The preceding tests should cover multi-way combinations of those types, but for good\n # measure test a few multi-way combinations involving those types\n @test issparse(vcat(spvec, densevec, spmat, densemat))\n @test issparse(vcat(densevec, spvec, densemat, spmat))\n @test issparse(hcat(spvec, densemat, spmat, densevec, diagmat))\n @test issparse(hcat(densemat, spmat, spvec, densevec, diagmat))\n @test issparse(hvcat((5,), diagmat, densevec, spvec, densemat, spmat))\n @test issparse(hvcat((5,), spvec, densemat, diagmat, densevec, spmat))\n @test issparse(cat(densemat, diagmat, spmat, densevec, spvec; dims=(1,2)))\n @test issparse(cat(spvec, diagmat, densevec, spmat, densemat; dims=(1,2)))\n end\n @testset \"vertical concatenation of SparseVectors with different el- and ind-type (#22225)\" begin\n spv6464 = SparseVector(0, Int64[], Int64[])\n @test isa(vcat(spv6464, SparseVector(0, Int64[], Int32[])), SparseVector{Int64,Int64})\n @test isa(vcat(spv6464, SparseVector(0, Int32[], Int64[])), SparseVector{Int64,Int64})\n @test isa(vcat(spv6464, SparseVector(0, Int32[], Int32[])), SparseVector{Int64,Int64})\n end\n end\nend",
"@testset \"sparsemat: combinations with sparse matrix\" begin\n let S = sprand(4, 8, 0.5)\n Sf = Array(S)\n @assert isa(Sf, Matrix{Float64})\n\n # get a single column\n for j = 1:size(S,2)\n col = S[:, j]\n @test isa(col, SparseVector{Float64,Int})\n @test length(col) == size(S,1)\n @test Array(col) == Sf[:,j]\n end\n\n # Get a reshaped vector\n v = S[:]\n @test isa(v, SparseVector{Float64,Int})\n @test length(v) == length(S)\n @test Array(v) == Sf[:]\n\n # Get a linear subset\n for i=0:length(S)\n v = S[1:i]\n @test isa(v, SparseVector{Float64,Int})\n @test length(v) == i\n @test Array(v) == Sf[1:i]\n end\n for i=1:length(S)+1\n v = S[i:end]\n @test isa(v, SparseVector{Float64,Int})\n @test length(v) == length(S) - i + 1\n @test Array(v) == Sf[i:end]\n end\n for i=0:div(length(S),2)\n v = S[1+i:end-i]\n @test isa(v, SparseVector{Float64,Int})\n @test length(v) == length(S) - 2i\n @test Array(v) == Sf[1+i:end-i]\n end\n end\n\n let r = [1,10], S = sparse(r, r, r)\n Sf = Array(S)\n @assert isa(Sf, Matrix{Int})\n\n inds = [1,1,1,1,1,1]\n v = S[inds]\n @test isa(v, SparseVector{Int,Int})\n @test length(v) == length(inds)\n @test Array(v) == Sf[inds]\n\n inds = [2,2,2,2,2,2]\n v = S[inds]\n @test isa(v, SparseVector{Int,Int})\n @test length(v) == length(inds)\n @test Array(v) == Sf[inds]\n\n # get a single column\n for j = 1:size(S,2)\n col = S[:, j]\n @test isa(col, SparseVector{Int,Int})\n @test length(col) == size(S,1)\n @test Array(col) == Sf[:,j]\n end\n\n # Get a reshaped vector\n v = S[:]\n @test isa(v, SparseVector{Int,Int})\n @test length(v) == length(S)\n @test Array(v) == Sf[:]\n\n # Get a linear subset\n for i=0:length(S)\n v = S[1:i]\n @test isa(v, SparseVector{Int,Int})\n @test length(v) == i\n @test Array(v) == Sf[1:i]\n end\n for i=1:length(S)+1\n v = S[i:end]\n @test isa(v, SparseVector{Int,Int})\n @test length(v) == length(S) - i + 1\n @test Array(v) == Sf[i:end]\n end\n for i=0:div(length(S),2)\n v = S[1+i:end-i]\n @test isa(v, SparseVector{Int,Int})\n @test length(v) == length(S) - 2i\n @test Array(v) == Sf[1+i:end-i]\n end\n end\nend",
"@testset \"Arithmetic operations\" begin\n\n let x = spv_x1, x2 = spv_x2\n # negate\n @test exact_equal(-x, SparseVector(8, [2, 5, 6], [-1.25, 0.75, -3.5]))\n\n # abs and abs2\n @test exact_equal(abs.(x), SparseVector(8, [2, 5, 6], abs.([1.25, -0.75, 3.5])))\n @test exact_equal(abs2.(x), SparseVector(8, [2, 5, 6], abs2.([1.25, -0.75, 3.5])))\n\n # plus and minus\n xa = SparseVector(8, [1,2,5,6,7], [3.25,5.25,-0.75,-2.0,-6.0])\n\n @test exact_equal(x + x, x * 2)\n @test exact_equal(x + x2, xa)\n @test exact_equal(x2 + x, xa)\n\n xb = SparseVector(8, [1,2,5,6,7], [-3.25,-2.75,-0.75,9.0,6.0])\n @test exact_equal(x - x, SparseVector(8, Int[], Float64[]))\n @test exact_equal(x - x2, xb)\n @test exact_equal(x2 - x, -xb)\n\n @test Array(x) + x2 == Array(xa)\n @test Array(x) - x2 == Array(xb)\n @test x + Array(x2) == Array(xa)\n @test x - Array(x2) == Array(xb)\n\n # multiplies\n xm = SparseVector(8, [2, 6], [5.0, -19.25])\n @test exact_equal(x .* x, abs2.(x))\n @test exact_equal(x .* x2, xm)\n @test exact_equal(x2 .* x, xm)\n\n @test Array(x) .* x2 == Array(xm)\n @test x .* Array(x2) == Array(xm)\n\n # max & min\n @test exact_equal(max.(x, x), x)\n @test exact_equal(min.(x, x), x)\n @test exact_equal(max.(x, x2),\n SparseVector(8, Int[1, 2, 6], Float64[3.25, 4.0, 3.5]))\n @test exact_equal(min.(x, x2),\n SparseVector(8, Int[2, 5, 6, 7], Float64[1.25, -0.75, -5.5, -6.0]))\n end\n\n ### Complex\n\n let x = spv_x1, x2 = spv_x2\n # complex\n @test exact_equal(complex.(x, x),\n SparseVector(8, [2,5,6], [1.25+1.25im, -0.75-0.75im, 3.5+3.5im]))\n @test exact_equal(complex.(x, x2),\n SparseVector(8, [1,2,5,6,7], [3.25im, 1.25+4.0im, -0.75+0.0im, 3.5-5.5im, -6.0im]))\n @test exact_equal(complex.(x2, x),\n SparseVector(8, [1,2,5,6,7], [3.25+0.0im, 4.0+1.25im, -0.75im, -5.5+3.5im, -6.0+0.0im]))\n\n # real, imag and conj\n\n @test real(x) === x\n @test exact_equal(imag(x), spzeros(Float64, length(x)))\n @test conj(x) === x\n\n xcp = complex.(x, x2)\n @test exact_equal(real(xcp), x)\n @test exact_equal(imag(xcp), x2)\n @test exact_equal(conj(xcp), complex.(x, -x2))\n end\nend",
"@testset \"Zero-preserving math functions: sparse -> sparse\" begin\n x1operations = (floor, ceil, trunc, round)\n x0operations = (log1p, expm1, sinpi,\n sin, tan, sind, tand,\n asin, atan, asind, atand,\n sinh, tanh, asinh, atanh)\n\n for (spvec, densevec, operations) in (\n (rnd_x0, rnd_x0f, x0operations),\n (rnd_x1, rnd_x1f, x1operations) )\n for op in operations\n spresvec = op.(spvec)\n @test spresvec == op.(densevec)\n @test all(!iszero, spresvec.nzval)\n resvaltype = typeof(op(zero(eltype(spvec))))\n resindtype = SparseArrays.indtype(spvec)\n @test isa(spresvec, SparseVector{resvaltype,resindtype})\n end\n end\nend",
"@testset \"Non-zero-preserving math functions: sparse -> dense\" begin\n for op in (exp, exp2, exp10, log, log2, log10,\n cos, cosd, acos, cosh, cospi,\n csc, cscd, acot, csch, acsch,\n cot, cotd, acosd, coth,\n sec, secd, acotd, sech, asech)\n spvec = rnd_x0\n densevec = rnd_x0f\n spresvec = op.(spvec)\n @test spresvec == op.(densevec)\n resvaltype = typeof(op(zero(eltype(spvec))))\n resindtype = SparseArrays.indtype(spvec)\n @test isa(spresvec, SparseVector{resvaltype,resindtype})\n end\nend",
"@testset \"sum, vecnorm\" begin\n x = spv_x1\n @test sum(x) == 4.0\n @test sum(abs, x) == 5.5\n @test sum(abs2, x) == 14.375\n\n @test vecnorm(x) == sqrt(14.375)\n @test vecnorm(x, 1) == 5.5\n @test vecnorm(x, 2) == sqrt(14.375)\n @test vecnorm(x, Inf) == 3.5\nend",
"@testset \"maximum, minimum\" begin\n let x = spv_x1\n @test maximum(x) == 3.5\n @test minimum(x) == -0.75\n @test maximum(abs, x) == 3.5\n @test minimum(abs, x) == 0.0\n end\n\n let x = abs.(spv_x1)\n @test maximum(x) == 3.5\n @test minimum(x) == 0.0\n end\n\n let x = -abs.(spv_x1)\n @test maximum(x) == 0.0\n @test minimum(x) == -3.5\n end\n\n let x = SparseVector(3, [1, 2, 3], [-4.5, 2.5, 3.5])\n @test maximum(x) == 3.5\n @test minimum(x) == -4.5\n @test maximum(abs, x) == 4.5\n @test minimum(abs, x) == 2.5\n end\n\n let x = spzeros(Float64, 8)\n @test maximum(x) == 0.0\n @test minimum(x) == 0.0\n @test maximum(abs, x) == 0.0\n @test minimum(abs, x) == 0.0\n end\nend",
"@testset \"BLAS Level-1\" begin\n\n let x = sprand(16, 0.5), x2 = sprand(16, 0.4)\n xf = Array(x)\n xf2 = Array(x2)\n\n @testset \"axpy!\" begin\n for c in [1.0, -1.0, 2.0, -2.0]\n y = Array(x)\n @test LinearAlgebra.axpy!(c, x2, y) === y\n @test y == Array(x2 * c + x)\n end\n end\n @testset \"scale\" begin\n α = 2.5\n sx = SparseVector(x.n, x.nzind, x.nzval * α)\n @test exact_equal(x * α, sx)\n @test exact_equal(x * (α + 0.0*im), complex(sx))\n @test exact_equal(α * x, sx)\n @test exact_equal((α + 0.0*im) * x, complex(sx))\n @test exact_equal(x * α, sx)\n @test exact_equal(α * x, sx)\n @test exact_equal(x .* α, sx)\n @test exact_equal(α .* x, sx)\n @test exact_equal(x / α, SparseVector(x.n, x.nzind, x.nzval / α))\n\n xc = copy(x)\n @test rmul!(xc, α) === xc\n @test exact_equal(xc, sx)\n xc = copy(x)\n @test lmul!(α, xc) === xc\n @test exact_equal(xc, sx)\n xc = copy(x)\n @test rmul!(xc, complex(α, 0.0)) === xc\n @test exact_equal(xc, sx)\n xc = copy(x)\n @test lmul!(complex(α, 0.0), xc) === xc\n @test exact_equal(xc, sx)\n end\n\n @testset \"dot\" begin\n dv = dot(xf, xf2)\n @test dot(x, x) == sum(abs2, x)\n @test dot(x2, x2) == sum(abs2, x2)\n @test dot(x, x2) ≈ dv\n @test dot(x2, x) ≈ dv\n @test dot(Array(x), x2) ≈ dv\n @test dot(x, Array(x2)) ≈ dv\n end\n end\n\n let x = complex.(sprand(32, 0.6), sprand(32, 0.6)),\n y = complex.(sprand(32, 0.6), sprand(32, 0.6))\n xf = Array(x)::Vector{ComplexF64}\n yf = Array(y)::Vector{ComplexF64}\n @test dot(x, x) ≈ dot(xf, xf)\n @test dot(x, y) ≈ dot(xf, yf)\n end\nend",
"@testset \"BLAS Level-2\" begin\n @testset \"dense A * sparse x -> dense y\" begin\n let A = randn(9, 16), x = sprand(16, 0.7)\n xf = Array(x)\n for α in [0.0, 1.0, 2.0], β in [0.0, 0.5, 1.0]\n y = rand(9)\n rr = α*A*xf + β*y\n @test mul!(y, A, x, α, β) === y\n @test y ≈ rr\n end\n y = A*x\n @test isa(y, Vector{Float64})\n @test A*x ≈ A*xf\n end\n\n let A = randn(16, 9), x = sprand(16, 0.7)\n xf = Array(x)\n for α in [0.0, 1.0, 2.0], β in [0.0, 0.5, 1.0]\n y = rand(9)\n rr = α*A'xf + β*y\n @test mul!(y, transpose(A), x, α, β) === y\n @test y ≈ rr\n end\n y = *(transpose(A), x)\n @test isa(y, Vector{Float64})\n @test y ≈ *(transpose(A), xf)\n end\n end\n @testset \"sparse A * sparse x -> dense y\" begin\n let A = sprandn(9, 16, 0.5), x = sprand(16, 0.7)\n Af = Array(A)\n xf = Array(x)\n for α in [0.0, 1.0, 2.0], β in [0.0, 0.5, 1.0]\n y = rand(9)\n rr = α*Af*xf + β*y\n @test mul!(y, A, x, α, β) === y\n @test y ≈ rr\n end\n y = SparseArrays.densemv(A, x)\n @test isa(y, Vector{Float64})\n @test y ≈ Af*xf\n end\n\n let A = sprandn(16, 9, 0.5), x = sprand(16, 0.7)\n Af = Array(A)\n xf = Array(x)\n for α in [0.0, 1.0, 2.0], β in [0.0, 0.5, 1.0]\n y = rand(9)\n rr = α*Af'xf + β*y\n @test mul!(y, transpose(A), x, α, β) === y\n @test y ≈ rr\n end\n y = SparseArrays.densemv(A, x; trans='T')\n @test isa(y, Vector{Float64})\n @test y ≈ *(transpose(Af), xf)\n end\n\n let A = complex.(sprandn(7, 8, 0.5), sprandn(7, 8, 0.5)),\n x = complex.(sprandn(8, 0.6), sprandn(8, 0.6)),\n x2 = complex.(sprandn(7, 0.75), sprandn(7, 0.75))\n Af = Array(A)\n xf = Array(x)\n x2f = Array(x2)\n @test SparseArrays.densemv(A, x; trans='N') ≈ Af * xf\n @test SparseArrays.densemv(A, x2; trans='T') ≈ transpose(Af) * x2f\n @test SparseArrays.densemv(A, x2; trans='C') ≈ Af'x2f\n @test_throws ArgumentError SparseArrays.densemv(A, x; trans='D')\n end\n end\n @testset \"sparse A * sparse x -> sparse y\" begin\n let A = sprandn(9, 16, 0.5), x = sprand(16, 0.7), x2 = sprand(9, 0.7)\n Af = Array(A)\n xf = Array(x)\n x2f = Array(x2)\n\n y = A*x\n @test isa(y, SparseVector{Float64,Int})\n @test all(nonzeros(y) .!= 0.0)\n @test Array(y) ≈ Af * xf\n\n y = *(transpose(A), x2)\n @test isa(y, SparseVector{Float64,Int})\n @test all(nonzeros(y) .!= 0.0)\n @test Array(y) ≈ Af'x2f\n end\n\n let A = complex.(sprandn(7, 8, 0.5), sprandn(7, 8, 0.5)),\n x = complex.(sprandn(8, 0.6), sprandn(8, 0.6)),\n x2 = complex.(sprandn(7, 0.75), sprandn(7, 0.75))\n Af = Array(A)\n xf = Array(x)\n x2f = Array(x2)\n\n y = A*x\n @test isa(y, SparseVector{ComplexF64,Int})\n @test Array(y) ≈ Af * xf\n\n y = *(transpose(A), x2)\n @test isa(y, SparseVector{ComplexF64,Int})\n @test Array(y) ≈ transpose(Af) * x2f\n\n y = *(adjoint(A), x2)\n @test isa(y, SparseVector{ComplexF64,Int})\n @test Array(y) ≈ Af'x2f\n end\n end\n @testset \"ldiv ops with triangular matrices and sparse vecs (#14005)\" begin\n m = 10\n sparsefloatvecs = SparseVector[sprand(m, 0.4) for k in 1:3]\n sparseintvecs = SparseVector[SparseVector(m, sprvec.nzind, round.(Int, sprvec.nzval*10)) for sprvec in sparsefloatvecs]\n sparsecomplexvecs = SparseVector[SparseVector(m, sprvec.nzind, complex.(sprvec.nzval, sprvec.nzval)) for sprvec in sparsefloatvecs]\n\n sprmat = sprand(m, m, 0.2)\n sparsefloatmat = I + sprmat/(2m)\n sparsecomplexmat = I + SparseMatrixCSC(m, m, sprmat.colptr, sprmat.rowval, complex.(sprmat.nzval, sprmat.nzval)/(4m))\n sparseintmat = 10m*I + SparseMatrixCSC(m, m, sprmat.colptr, sprmat.rowval, round.(Int, sprmat.nzval*10))\n\n denseintmat = I*10m + rand(1:m, m, m)\n densefloatmat = I + randn(m, m)/(2m)\n densecomplexmat = I + randn(Complex{Float64}, m, m)/(4m)\n\n inttypes = (Int32, Int64, BigInt)\n floattypes = (Float32, Float64, BigFloat)\n complextypes = (Complex{Float32}, Complex{Float64})\n eltypes = (inttypes..., floattypes..., complextypes...)\n\n for eltypemat in eltypes\n (densemat, sparsemat) = eltypemat in inttypes ? (denseintmat, sparseintmat) :\n eltypemat in floattypes ? (densefloatmat, sparsefloatmat) :\n eltypemat in complextypes && (densecomplexmat, sparsecomplexmat)\n densemat = convert(Matrix{eltypemat}, densemat)\n sparsemat = convert(SparseMatrixCSC{eltypemat}, sparsemat)\n trimats = (LowerTriangular(densemat), UpperTriangular(densemat),\n LowerTriangular(sparsemat), UpperTriangular(sparsemat) )\n unittrimats = (LinearAlgebra.UnitLowerTriangular(densemat), LinearAlgebra.UnitUpperTriangular(densemat),\n LinearAlgebra.UnitLowerTriangular(sparsemat), LinearAlgebra.UnitUpperTriangular(sparsemat) )\n\n for eltypevec in eltypes\n spvecs = eltypevec in inttypes ? sparseintvecs :\n eltypevec in floattypes ? sparsefloatvecs :\n eltypevec in complextypes && sparsecomplexvecs\n spvecs = SparseVector[SparseVector(m, spvec.nzind, convert(Vector{eltypevec}, spvec.nzval)) for spvec in spvecs]\n\n for spvec in spvecs\n fspvec = convert(Array, spvec)\n # test out-of-place left-division methods\n for mat in (trimats..., unittrimats...)\n @test \\(mat, spvec) ≈ \\(mat, fspvec)\n @test \\(adjoint(mat), spvec) ≈ \\(adjoint(mat), fspvec)\n @test \\(transpose(mat), spvec) ≈ \\(transpose(mat), fspvec)\n end\n # test in-place left-division methods not involving quotients\n if eltypevec == typeof(zero(eltypemat)*zero(eltypevec) + zero(eltypemat)*zero(eltypevec))\n for mat in unittrimats\n @test ldiv!(mat, copy(spvec)) ≈ ldiv!(mat, copy(fspvec))\n @test ldiv!(adjoint(mat), copy(spvec)) ≈ ldiv!(adjoint(mat), copy(fspvec))\n @test ldiv!(transpose(mat), copy(spvec)) ≈ ldiv!(transpose(mat), copy(fspvec))\n end\n end\n # test in-place left-division methods involving quotients\n if eltypevec == typeof((zero(eltypemat)*zero(eltypevec) + zero(eltypemat)*zero(eltypevec))/one(eltypemat))\n for mat in trimats\n @test ldiv!(mat, copy(spvec)) ≈ ldiv!(mat, copy(fspvec))\n @test ldiv!(adjoint(mat), copy(spvec)) ≈ ldiv!(adjoint(mat), copy(fspvec))\n @test ldiv!(transpose(mat), copy(spvec)) ≈ ldiv!(transpose(mat), copy(fspvec))\n end\n end\n end\n end\n end\n end\n @testset \"#16716\" begin\n # The preceding tests miss the edge case where the sparse vector is empty\n origmat = [-1.5 -0.7; 0.0 1.0]\n transmat = copy(origmat')\n utmat = UpperTriangular(origmat)\n ltmat = LowerTriangular(transmat)\n uutmat = LinearAlgebra.UnitUpperTriangular(origmat)\n ultmat = LinearAlgebra.UnitLowerTriangular(transmat)\n\n zerospvec = spzeros(Float64, 2)\n zerodvec = zeros(Float64, 2)\n\n for mat in (utmat, ltmat, uutmat, ultmat)\n @test isequal(\\(mat, zerospvec), zerodvec)\n @test isequal(\\(adjoint(mat), zerospvec), zerodvec)\n @test isequal(\\(transpose(mat), zerospvec), zerodvec)\n @test isequal(ldiv!(mat, copy(zerospvec)), zerospvec)\n @test isequal(ldiv!(adjoint(mat), copy(zerospvec)), zerospvec)\n @test isequal(ldiv!(transpose(mat), copy(zerospvec)), zerospvec)\n end\n end\nend",
"@testset \"kron\" begin\n testdims = ((5,10), (20,12), (25,30))\n for (m,n) in testdims\n x = sprand(m, 0.4)\n y = sprand(n, 0.3)\n @test Vector(kron(x,y)) == kron(Vector(x), Vector(y))\n @test Vector(kron(Vector(x),y)) == kron(Vector(x), Vector(y))\n @test Vector(kron(x,Vector(y))) == kron(Vector(x), Vector(y))\n # test different types\n z = convert(SparseVector{Float16, Int8}, y)\n @test Vector(kron(x, z)) == kron(Vector(x), Vector(z))\n end\nend",
"@testset \"fkeep!\" begin\n x = sparsevec(1:7, [3., 2., -1., 1., -2., -3., 3.], 7)\n # droptol\n xdrop = SparseArrays.droptol!(copy(x), 1.5)\n @test exact_equal(xdrop, SparseVector(7, [1, 2, 5, 6, 7], [3., 2., -2., -3., 3.]))\n SparseArrays.droptol!(xdrop, 2.5)\n @test exact_equal(xdrop, SparseVector(7, [1, 6, 7], [3., -3., 3.]))\n SparseArrays.droptol!(xdrop, 3.)\n @test exact_equal(xdrop, SparseVector(7, Int[], Float64[]))\n\n xdrop = copy(x)\n # This will keep index 1, 3, 4, 7 in xdrop\n f_drop(i, x) = (abs(x) == 1.) || (i in [1, 7])\n SparseArrays.fkeep!(xdrop, f_drop)\n @test exact_equal(xdrop, SparseVector(7, [1, 3, 4, 7], [3., -1., 1., 3.]))\nend",
"@testset \"dropzeros[!] with length=$m\" for m in (10, 20, 30)\n srand(123)\n nzprob, targetnumposzeros, targetnumnegzeros = 0.4, 5, 5\n v = sprand(m, nzprob)\n struczerosv = findall(x -> x == 0, v)\n poszerosinds = unique(rand(struczerosv, targetnumposzeros))\n negzerosinds = unique(rand(struczerosv, targetnumnegzeros))\n vposzeros = copy(v)\n vposzeros[poszerosinds] .= 2\n vnegzeros = copy(v)\n vnegzeros[negzerosinds] .= -2\n vbothsigns = copy(vposzeros)\n vbothsigns[negzerosinds] .= -2\n map!(x -> x == 2 ? 0.0 : x, vposzeros.nzval, vposzeros.nzval)\n map!(x -> x == -2 ? -0.0 : x, vnegzeros.nzval, vnegzeros.nzval)\n map!(x -> x == 2 ? 0.0 : x == -2 ? -0.0 : x, vbothsigns.nzval, vbothsigns.nzval)\n for vwithzeros in (vposzeros, vnegzeros, vbothsigns)\n # Basic functionality / dropzeros!\n @test dropzeros!(copy(vwithzeros)) == v\n @test dropzeros!(copy(vwithzeros), trim = false) == v\n # Basic functionality / dropzeros\n @test dropzeros(vwithzeros) == v\n @test dropzeros(vwithzeros, trim = false) == v\n # Check trimming works as expected\n @test length(dropzeros!(copy(vwithzeros)).nzval) == length(v.nzval)\n @test length(dropzeros!(copy(vwithzeros)).nzind) == length(v.nzind)\n @test length(dropzeros!(copy(vwithzeros), trim = false).nzval) == length(vwithzeros.nzval)\n @test length(dropzeros!(copy(vwithzeros), trim = false).nzind) == length(vwithzeros.nzind)\n end\nend",
"@testset \"original dropzeros! test\" begin\n xdrop = sparsevec(1:7, [3., 2., -1., 1., -2., -3., 3.], 7)\n xdrop.nzval[[2, 4, 6]] .= 0.0\n SparseArrays.dropzeros!(xdrop)\n @test exact_equal(xdrop, SparseVector(7, [1, 3, 5, 7], [3, -1., -2., 3.]))\nend",
"@testset \"stored zero semantics\" begin\n # Compare stored zero semantics between SparseVector and SparseMatrixCSC\n let S = SparseMatrixCSC(10,1,[1,6],[1,3,5,6,7],[0,1,2,0,3]), x = SparseVector(10,[1,3,5,6,7],[0,1,2,0,3])\n @test nnz(S) == nnz(x) == 5\n for I = (:, 1:10, Vector(1:10))\n @test S[I,1] == S[I] == x[I] == x\n @test nnz(S[I,1]) == nnz(S[I]) == nnz(x[I]) == nnz(x)\n end\n for I = (2:9, 1:2, 9:10, [3,6,1], [10,9,8], [])\n @test S[I,1] == S[I] == x[I]\n @test nnz(S[I,1]) == nnz(S[I]) == nnz(x[I])\n end\n @test S[[1 3 5; 2 4 6]] == x[[1 3 5; 2 4 6]]\n @test nnz(S[[1 3 5; 2 4 6]]) == nnz(x[[1 3 5; 2 4 6]])\n end\nend",
"@testset \"Issue 14013\" begin\n s14013 = sparse([10.0 0.0 30.0; 0.0 1.0 0.0])\n a14013 = [10.0 0.0 30.0; 0.0 1.0 0.0]\n @test s14013 == a14013\n @test vec(s14013) == s14013[:] == a14013[:]\n @test Array(s14013)[1,:] == s14013[1,:] == a14013[1,:] == [10.0, 0.0, 30.0]\n @test Array(s14013)[2,:] == s14013[2,:] == a14013[2,:] == [0.0, 1.0, 0.0]\nend",
"@testset \"Issue 14046\" begin\n s14046 = sprand(5, 1.0)\n @test spzeros(5) + s14046 == s14046\n @test 2*s14046 == s14046 + s14046\nend",
"@testset \"Issue 14589\" begin\n # test vectors with no zero elements\n let x = sparsevec(1:7, [3., 2., -1., 1., -2., -3., 3.], 7)\n @test Vector(sort(x)) == sort(Vector(x))\n end\n # test vectors with all zero elements\n let x = sparsevec(Int64[], Float64[], 7)\n @test Vector(sort(x)) == sort(Vector(x))\n end\n # test vector with sparsity approx 1/2\n let x = sparsevec(1:7, [3., 2., -1., 1., -2., -3., 3.], 15)\n @test Vector(sort(x)) == sort(Vector(x))\n # apply three distinct tranformations where zeros sort into start/middle/end\n @test Vector(sort(x, by=abs)) == sort(Vector(x), by=abs)\n @test Vector(sort(x, by=sign)) == sort(Vector(x), by=sign)\n @test Vector(sort(x, by=inv)) == sort(Vector(x), by=inv)\n end\nend",
"@testset \"fill!\" begin\n for Tv in [Float32, Float64, Int64, Int32, ComplexF64]\n for Ti in [Int16, Int32, Int64, BigInt]\n sptypes = (SparseMatrixCSC{Tv, Ti}, SparseVector{Tv, Ti})\n sizes = [(3, 4), (3,)]\n for (siz, Sp) in zip(sizes, sptypes)\n arr = rand(Tv, siz...)\n sparr = Sp(arr)\n x = rand(Tv)\n @test fill!(sparr, x) == fill(x, siz)\n @test fill!(sparr, 0) == fill(0, siz)\n end\n end\n end\nend",
"@testset \"13130 and 16661\" begin\n @test issparse([sprand(10,10,.1) sprand(10,.1)])\n @test issparse([sprand(10,1,.1); sprand(10,.1)])\n\n @test issparse([sprand(10,10,.1) rand(10)])\n @test issparse([sprand(10,1,.1) rand(10)])\n @test issparse([sprand(10,2,.1) sprand(10,1,.1) rand(10)])\n @test issparse([sprand(10,1,.1); rand(10)])\n\n @test issparse([sprand(10,.1) rand(10)])\n @test issparse([sprand(10,.1); rand(10)])\nend",
"@testset \"show\" begin\n io = IOBuffer()\n show(io, MIME\"text/plain\"(), sparsevec(Int64[1], [1.0]))\n @test String(take!(io)) == \"1-element SparseArrays.SparseVector{Float64,Int64} with 1 stored entry:\\n [1] = 1.0\"\n show(io, MIME\"text/plain\"(), spzeros(Float64, Int64, 2))\n @test String(take!(io)) == \"2-element SparseArrays.SparseVector{Float64,Int64} with 0 stored entries\"\n show(io, similar(sparsevec(rand(3) .+ 0.1), t20488))\n @test String(take!(io)) == \" [1] = #undef\\n [2] = #undef\\n [3] = #undef\"\nend",
"@testset \"spzeros with index type\" begin\n @test typeof(spzeros(Float32, Int16, 3)) == SparseVector{Float32,Int16}\nend",
"@testset \"corner cases of broadcast arithmetic operations with scalars (#21515)\" begin\n # test both scalar literals and variables\n areequal(a, b, c) = isequal(a, b) && isequal(b, c)\n inf, zeroh, zv, spzv = Inf, 0.0, zeros(1), spzeros(1)\n @test areequal(spzv .* Inf, spzv .* inf, sparsevec(zv .* Inf))\n @test areequal(Inf .* spzv, inf .* spzv, sparsevec(Inf .* zv))\n @test areequal(spzv ./ 0.0, spzv ./ zeroh, sparsevec(zv ./ 0.0))\n @test areequal(0.0 .\\ spzv, zeroh .\\ spzv, sparsevec(0.0 .\\ zv))\nend",
"@testset \"similar for SparseVector\" begin\n A = SparseVector(10, Int[1, 3, 5, 7], Float64[1.0, 3.0, 5.0, 7.0])\n # test similar without specifications (preserves stored-entry structure)\n simA = similar(A)\n @test typeof(simA) == typeof(A)\n @test size(simA) == size(A)\n @test simA.nzind == A.nzind\n @test length(simA.nzval) == length(A.nzval)\n # test similar with entry type specification (preserves stored-entry structure)\n simA = similar(A, Float32)\n @test typeof(simA) == SparseVector{Float32,eltype(A.nzind)}\n @test size(simA) == size(A)\n @test simA.nzind == A.nzind\n @test length(simA.nzval) == length(A.nzval)\n # test similar with entry and index type specification (preserves stored-entry structure)\n simA = similar(A, Float32, Int8)\n @test typeof(simA) == SparseVector{Float32,Int8}\n @test size(simA) == size(A)\n @test simA.nzind == A.nzind\n @test length(simA.nzval) == length(A.nzval)\n # test similar with Dims{1} specification (preserves nothing)\n simA = similar(A, (6,))\n @test typeof(simA) == typeof(A)\n @test size(simA) == (6,)\n @test length(simA.nzind) == 0\n @test length(simA.nzval) == 0\n # test similar with entry type and Dims{1} specification (preserves nothing)\n simA = similar(A, Float32, (6,))\n @test typeof(simA) == SparseVector{Float32,eltype(A.nzind)}\n @test size(simA) == (6,)\n @test length(simA.nzind) == 0\n @test length(simA.nzval) == 0\n # test similar with entry type, index type, and Dims{1} specification (preserves nothing)\n simA = similar(A, Float32, Int8, (6,))\n @test typeof(simA) == SparseVector{Float32,Int8}\n @test size(simA) == (6,)\n @test length(simA.nzind) == 0\n @test length(simA.nzval) == 0\n # test entry points to similar with entry type, index type, and non-Dims shape specification\n @test similar(A, Float32, Int8, 6, 6) == similar(A, Float32, Int8, (6, 6))\n @test similar(A, Float32, Int8, 6) == similar(A, Float32, Int8, (6,))\n # test similar with Dims{2} specification (preserves storage space only, not stored-entry structure)\n simA = similar(A, (6,6))\n @test typeof(simA) == SparseMatrixCSC{eltype(A.nzval),eltype(A.nzind)}\n @test size(simA) == (6,6)\n @test simA.colptr == fill(1, 6+1)\n @test length(simA.rowval) == length(A.nzind)\n @test length(simA.nzval) == length(A.nzval)\n # test similar with entry type and Dims{2} specification (preserves storage space only)\n simA = similar(A, Float32, (6,6))\n @test typeof(simA) == SparseMatrixCSC{Float32,eltype(A.nzind)}\n @test size(simA) == (6,6)\n @test simA.colptr == fill(1, 6+1)\n @test length(simA.rowval) == length(A.nzind)\n @test length(simA.nzval) == length(A.nzval)\n # test similar with entry type, index type, and Dims{2} specification (preserves storage space only)\n simA = similar(A, Float32, Int8, (6,6))\n @test typeof(simA) == SparseMatrixCSC{Float32, Int8}\n @test size(simA) == (6,6)\n @test simA.colptr == fill(1, 6+1)\n @test length(simA.rowval) == length(A.nzind)\n @test length(simA.nzval) == length(A.nzval)\nend",
"@testset \"Fast operations on full column views\" begin\n n = 1000\n A = sprandn(n, n, 0.01)\n for j in 1:5:n\n Aj, Ajview = A[:, j], view(A, :, j)\n @test norm(Aj) == norm(Ajview)\n @test dot(Aj, copy(Aj)) == dot(Ajview, Aj) # don't alias since it takes a different code path\n @test rmul!(Aj, 0.1) == rmul!(Ajview, 0.1)\n @test Aj*0.1 == Ajview*0.1\n @test 0.1*Aj == 0.1*Ajview\n @test Aj/0.1 == Ajview/0.1\n @test LinearAlgebra.axpy!(1.0, Aj, sparse(fill(1., n))) ==\n LinearAlgebra.axpy!(1.0, Ajview, sparse(fill(1., n)))\n @test LinearAlgebra.lowrankupdate!(Matrix(1.0*I, n, n), fill(1.0, n), Aj) ==\n LinearAlgebra.lowrankupdate!(Matrix(1.0*I, n, n), fill(1.0, n), Ajview)\n end\nend"
] |
f730d51ff329e5659dc3f251a93b3a0a168c5381
| 1,610
|
jl
|
Julia
|
test/primitive/math_gate.jl
|
yihong-zhang/YaoBlocks.jl
|
9bd8f309b5c258968fb5ce4c2f12fc5e854d8b68
|
[
"Apache-2.0"
] | null | null | null |
test/primitive/math_gate.jl
|
yihong-zhang/YaoBlocks.jl
|
9bd8f309b5c258968fb5ce4c2f12fc5e854d8b68
|
[
"Apache-2.0"
] | null | null | null |
test/primitive/math_gate.jl
|
yihong-zhang/YaoBlocks.jl
|
9bd8f309b5c258968fb5ce4c2f12fc5e854d8b68
|
[
"Apache-2.0"
] | null | null | null |
using Test, YaoArrayRegister, YaoBlocks, BitBasis
function toffli(b::BitStr)
t = @inbounds b[1] ⊻ (b[3] & b[2])
return @inbounds bit_literal(t, b[2], b[3])
end
"""
pshift(n::Int) -> Function
return a peridoc shift function.
"""
pshift(n::Int) = (b::Int, nbit::Int) -> mod(b+n, 1<<nbit)
pshift(n::Float64) = (b::Float64, nbit::Int) -> mod(b+n, 1)
@testset "test toffli" begin
g = mathgate(toffli; nbits=3)
check_truth(b1, b2) = apply!(ArrayReg(b1), g) == ArrayReg(b2)
@test check_truth(bit"000", bit"000")
@test check_truth(bit"001", bit"001")
@test check_truth(bit"010", bit"010")
@test check_truth(bit"011", bit"011")
@test check_truth(bit"100", bit"100")
@test check_truth(bit"101", bit"101")
@test check_truth(bit"110", bit"111")
@test check_truth(bit"111", bit"110")
end
@testset "test pshift" begin
# bint
nbits = 5
ab = mathgate(pshift(3); nbits=nbits)
mb = mathgate(pshift(-3); nbits=nbits)
@test apply!(zero_state(nbits), ab) == product_state(nbits, 3)
@test apply!(zero_state(nbits), mb) == product_state(nbits, 1<<nbits-3)
@test isunitary(ab)
ab = mathgate(pshift(3); nbits=nbits, bview=bint_r)
@test apply!(zero_state(nbits), ab) == product_state(nbits, 0b11000)
@test isunitary(ab)
af = mathgate(pshift(0.5); nbits=nbits, bview=bfloat)
@test isunitary(af)
@test apply!(zero_state(nbits), af) == product_state(nbits, 1)
# bfloat_r
af = mathgate(pshift(0.5); nbits=nbits, bview=bfloat_r)
@test isunitary(af)
@test apply!(zero_state(nbits), af) == ArrayReg(bit"10000")
end
| 31.568627
| 75
| 0.642236
|
[
"@testset \"test toffli\" begin\n g = mathgate(toffli; nbits=3)\n check_truth(b1, b2) = apply!(ArrayReg(b1), g) == ArrayReg(b2)\n @test check_truth(bit\"000\", bit\"000\")\n @test check_truth(bit\"001\", bit\"001\")\n @test check_truth(bit\"010\", bit\"010\")\n @test check_truth(bit\"011\", bit\"011\")\n @test check_truth(bit\"100\", bit\"100\")\n @test check_truth(bit\"101\", bit\"101\")\n @test check_truth(bit\"110\", bit\"111\")\n @test check_truth(bit\"111\", bit\"110\")\nend",
"@testset \"test pshift\" begin\n # bint\n nbits = 5\n ab = mathgate(pshift(3); nbits=nbits)\n mb = mathgate(pshift(-3); nbits=nbits)\n @test apply!(zero_state(nbits), ab) == product_state(nbits, 3)\n @test apply!(zero_state(nbits), mb) == product_state(nbits, 1<<nbits-3)\n @test isunitary(ab)\n\n ab = mathgate(pshift(3); nbits=nbits, bview=bint_r)\n @test apply!(zero_state(nbits), ab) == product_state(nbits, 0b11000)\n @test isunitary(ab)\n\n af = mathgate(pshift(0.5); nbits=nbits, bview=bfloat)\n @test isunitary(af)\n @test apply!(zero_state(nbits), af) == product_state(nbits, 1)\n\n # bfloat_r\n af = mathgate(pshift(0.5); nbits=nbits, bview=bfloat_r)\n @test isunitary(af)\n @test apply!(zero_state(nbits), af) == ArrayReg(bit\"10000\")\nend"
] |
f734da2f58ca1f6ada84ab9f502fd62d59c0226b
| 3,542
|
jl
|
Julia
|
test/runtests.jl
|
andLaing/NReco
|
376b272cc0fe480295c07a54166dbf69e456a95f
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
andLaing/NReco
|
376b272cc0fe480295c07a54166dbf69e456a95f
|
[
"MIT"
] | 7
|
2021-09-09T16:28:35.000Z
|
2021-11-19T17:17:07.000Z
|
test/runtests.jl
|
andLaing/NReco
|
376b272cc0fe480295c07a54166dbf69e456a95f
|
[
"MIT"
] | 1
|
2021-09-01T09:29:39.000Z
|
2021-09-01T09:29:39.000Z
|
using NReco
using ATools
using Test
using DataFrames
using Distributions
using Statistics
using Logging
using DataFrames
#using StatsModels
# Lower function verbosity
logger = global_logger(SimpleLogger(stdout, Logging.Warn))
fname = "testdata/n3-window-1m-LXe-20mm-1-20.h5"
pdf = NReco.read_abc(fname)
dconf = NReco.DetConf(0.3f0, 0.05f0, 2.0f0, 100.0f0, 5000.0f0, 7)
sxyz = pdf.sensor_xyz
wfm = pdf.waveform
vdf = pdf.vertices
@testset "util" begin
@test NReco.select_by_index(sxyz,
"sensor_id", 0) == NReco.select_by_column_value(sxyz, "sensor_id", 0)
wevt = NReco.select_event(wfm, 4995000)
@test mean(wevt.time) ≈ 42.39652f0
@test NReco.select_by_column_value(wevt, "sensor_id", 1783).sensor_id[1] == 1783
@test mean(NReco.select_by_column_value_lt(wevt, "time", 5.0).time) < 5.0
@test mean(NReco.select_by_column_value_gt(wevt, "time", 5.0).time) > 5.0
@test mean(NReco.select_by_column_value_interval(wevt, "time", 5.0, 10.0).time) >5.0
@test mean(NReco.select_by_column_value_interval(wevt, "time", 5.0, 10.0).time) <10.0
_, imx, _ = NReco.find_max_xy(wevt, "sensor_id", "time")
m, i = findmax(wevt.time)
@test wevt.sensor_id[i] == imx
end
@testset "recof" begin
@test all(NReco.primary_in_lxe(vdf).parent_id .== 0)
df = DataFrame(:q1=>Float32[100.0, 120.5, 132.6],
:q2=>Float32[123.6, 122.9, 99.9])
filtered_df = NReco.filter_energies(df, 100.0f0, 150.0f0)
@test nrow(filtered_df) == 1
@test all(in(Array(filtered_df[1, :])).([120.5f0, 122.9f0]))
df[!, :zstd1] = Float32[2.5, 3.2, 4.9]
df[!, :zstd2] = Float32[7.9, 4.5, 2.3]
NReco.calculate_interaction_radius!(df, x -> 2*x, "zstd")
@test all(in(propertynames(df)).([:r1x, :r2x]))
@test all(isapprox.(2 * df[!, :zstd1], df[!, :r1x]))
@test all(isapprox.(2 * df[!, :zstd1], df[!, :r1x]))
end
@testset "nemareco" begin
exp_keys = [:event_id, :phot1, :phot2, :nsipm1, :nsipm2, :q1, :q2,
:E1, :E2, :r1, :r2, :r1x, :r2x,
:phistd1, :zstd1, :widz1, :widphi1, :corrzphi1,
:phistd2, :zstd2, :widz2, :widphi2, :corrzphi2,
:xs, :ys, :zs, :ux, :uy, :uz, :xt1, :yt1, :zt1,
:t1, :xt2, :yt2, :zt2, :t2, :x1, :y1, :z1,
:x2, :y2, :z2, :xr1, :yr1, :zr1, :tr1,
:xr2, :yr2, :zr2, :tr2, :xb1, :yb1, :zb1, :ta1,
:xb2, :yb2, :zb2, :ta2]
_, result = NReco.nemareco([fname], dconf)
result_fields = fieldnames(typeof(result[1]))
@test length(result_fields) == length(exp_keys)
@test all(in(exp_keys).(result_fields))
filter_func = ismissing, isnothing, isnan
corrzphi1 = filter(c -> !any(f -> f(c), filter_func), getfield.(result, :corrzphi1))
corrzphi2 = filter(c -> !any(f -> f(c), filter_func), getfield.(result, :corrzphi2))
@test all((corrzphi1 .<= 1.0) .& (corrzphi1 .>= -1.0))
@test all((corrzphi2 .<= 1.0) .& (corrzphi2 .>= -1.0))
end
@testset "classify_events" begin
evt_keys = [:total, :empty, :single, :prompt, :single_prompt, :good_prompt]
evt_counts = NReco.event_classifier([fname], dconf)
evt_fields = fieldnames(typeof(evt_counts))
@test length(evt_fields) == length(evt_keys)
@test all(in(evt_keys).(evt_fields))
@test evt_counts.total == 20
@test evt_counts.empty == 7
@test evt_counts.single == 11
@test evt_counts.prompt == 2
@test evt_counts.single_prompt == 11
@test evt_counts.good_prompt == 2
end
| 38.5
| 90
| 0.616036
|
[
"@testset \"util\" begin\n @test NReco.select_by_index(sxyz,\n \"sensor_id\", 0) == NReco.select_by_column_value(sxyz, \"sensor_id\", 0)\n\n wevt = NReco.select_event(wfm, 4995000)\n @test mean(wevt.time) ≈ 42.39652f0\n @test NReco.select_by_column_value(wevt, \"sensor_id\", 1783).sensor_id[1] == 1783\n @test mean(NReco.select_by_column_value_lt(wevt, \"time\", 5.0).time) < 5.0\n @test mean(NReco.select_by_column_value_gt(wevt, \"time\", 5.0).time) > 5.0\n @test mean(NReco.select_by_column_value_interval(wevt, \"time\", 5.0, 10.0).time) >5.0\n @test mean(NReco.select_by_column_value_interval(wevt, \"time\", 5.0, 10.0).time) <10.0\n\n _, imx, _ = NReco.find_max_xy(wevt, \"sensor_id\", \"time\")\n m, i = findmax(wevt.time)\n @test wevt.sensor_id[i] == imx\nend",
"@testset \"recof\" begin\n @test all(NReco.primary_in_lxe(vdf).parent_id .== 0)\n\n df = DataFrame(:q1=>Float32[100.0, 120.5, 132.6],\n :q2=>Float32[123.6, 122.9, 99.9])\n filtered_df = NReco.filter_energies(df, 100.0f0, 150.0f0)\n @test nrow(filtered_df) == 1\n @test all(in(Array(filtered_df[1, :])).([120.5f0, 122.9f0]))\n\n df[!, :zstd1] = Float32[2.5, 3.2, 4.9]\n df[!, :zstd2] = Float32[7.9, 4.5, 2.3]\n NReco.calculate_interaction_radius!(df, x -> 2*x, \"zstd\")\n @test all(in(propertynames(df)).([:r1x, :r2x]))\n @test all(isapprox.(2 * df[!, :zstd1], df[!, :r1x]))\n @test all(isapprox.(2 * df[!, :zstd1], df[!, :r1x]))\nend",
"@testset \"nemareco\" begin\n exp_keys = [:event_id, :phot1, :phot2, :nsipm1, :nsipm2, :q1, :q2,\n\t :E1, :E2, :r1, :r2, :r1x, :r2x,\n :phistd1, :zstd1, :widz1, :widphi1, :corrzphi1,\n :phistd2, :zstd2, :widz2, :widphi2, :corrzphi2,\n\t\t\t :xs, :ys, :zs, :ux, :uy, :uz, :xt1, :yt1, :zt1,\n :t1, :xt2, :yt2, :zt2, :t2, :x1, :y1, :z1,\n :x2, :y2, :z2, :xr1, :yr1, :zr1, :tr1,\n :xr2, :yr2, :zr2, :tr2, :xb1, :yb1, :zb1, :ta1,\n\t\t\t :xb2, :yb2, :zb2, :ta2]\n _, result = NReco.nemareco([fname], dconf)\n result_fields = fieldnames(typeof(result[1]))\n @test length(result_fields) == length(exp_keys)\n @test all(in(exp_keys).(result_fields))\n filter_func = ismissing, isnothing, isnan\n corrzphi1 = filter(c -> !any(f -> f(c), filter_func), getfield.(result, :corrzphi1))\n corrzphi2 = filter(c -> !any(f -> f(c), filter_func), getfield.(result, :corrzphi2))\n @test all((corrzphi1 .<= 1.0) .& (corrzphi1 .>= -1.0))\n @test all((corrzphi2 .<= 1.0) .& (corrzphi2 .>= -1.0))\nend",
"@testset \"classify_events\" begin\n evt_keys = [:total, :empty, :single, :prompt, :single_prompt, :good_prompt]\n evt_counts = NReco.event_classifier([fname], dconf)\n evt_fields = fieldnames(typeof(evt_counts))\n @test length(evt_fields) == length(evt_keys)\n @test all(in(evt_keys).(evt_fields))\n\n @test evt_counts.total == 20\n @test evt_counts.empty == 7\n @test evt_counts.single == 11\n @test evt_counts.prompt == 2\n @test evt_counts.single_prompt == 11\n @test evt_counts.good_prompt == 2\nend"
] |
f73aa376c1505d72bbbd394595028887abf04dd4
| 2,096
|
jl
|
Julia
|
test/test-partial.jl
|
JobJob/Partial.jl
|
7b2853c614b21ef2b89c700fa75db5c9d1efe60e
|
[
"MIT"
] | 1
|
2019-11-01T17:28:10.000Z
|
2019-11-01T17:28:10.000Z
|
test/test-partial.jl
|
JobJob/Partial.jl
|
7b2853c614b21ef2b89c700fa75db5c9d1efe60e
|
[
"MIT"
] | null | null | null |
test/test-partial.jl
|
JobJob/Partial.jl
|
7b2853c614b21ef2b89c700fa75db5c9d1efe60e
|
[
"MIT"
] | null | null | null |
using Test
@testset "Quite partial to it really" begin
add3 = @p(3 + _)
@test add3(7) == 10
add4r = @p(_ + 4)
@test add4r(7) == 11
lt10 = @partial _ < 10
@test lt10(7) == true
@test lt10(27) == false
gt10 = @p(10 < _)
@test gt10(17) == true
@test gt10(7) == false
fn_of7_and_10 = @p _(7,10)
@test fn_of7_and_10(*) == 70
@test fn_of7_and_10(+) == 17
@test fn_of7_and_10(-) == -3
@test fn_of7_and_10(/) == 0.7
@test fn_of7_and_10(%) == 7
@test map(@p(_(7,10)),[*,+,-,/,%]) == [70,17,-3,0.7,7]
v1 = 3
v2 = 5
fn_of_v1_and_v2 = @p _(v1,v2)
@test fn_of_v1_and_v2(*) == 15
@test fn_of_v1_and_v2(+) == 8
@test fn_of_v1_and_v2(-) == -2
@test fn_of_v1_and_v2(/) == 0.6
@test fn_of_v1_and_v2(%) == 3
end
@testset "partial multi sub" begin
d = 10
zeros_dxN = @p zeros(_,d,_)
@test zeros_dxN(Int,3) == zeros(Int,10,3)
T = Float64
d2 = 12
zerosF64 = @p zeros(T,_,_)
@test zerosF64(d2,4) == zeros(Float64,d2,4)
end
@testset "partial can handle nested syms" begin
len_gt_10 = @partial(length(_) > 10)
@test len_gt_10("fred") == false
@test len_gt_10("freddy mercury") == true
fred = Array{Real}[]
push!(fred, [1,2,3])
push!(fred, [4.0,5.0,6.0])
fred_sub_ind = @p(fred[_][_])
@test fred_sub_ind(1,2) == 2
@test fred_sub_ind(1,3) == 3
@test fred_sub_ind(2,1) == 4.0
@test fred_sub_ind(2,3) == 6.0
len_gt_x = @partial(length(_) > _)
@test len_gt_x("fred",2) == true
@test len_gt_x("fred",10) == false
end
@testset "partial indexed sub" begin
d = 10
zeros_dxN = @p zeros(Int,_1,_1)
@test zeros_dxN(3) == zeros(Int,3,3)
zeros_dxN = @p zeros(Int,_1,_)
@test zeros_dxN(5) == zeros(Int,5,5)
T = Float64
d2 = 12
zerosF64 = @p zeros(T,_,_1)
@test zerosF64(d2) == zeros(Float64,12,12)
end
@testset "partial chained" begin
# unary fn
x10plus3 = @p _*10 _+3
for (inp, outp) in zip((2,3,4), (23,33,43))
@test x10plus3(inp) == outp
end
# binary fn
b_minus_a_x3 = @p _2-_1 _*3
for (inp, outp) in zip([(2,4), (7,3), (9,2)], (6, -12, -21))
@test b_minus_a_x3(inp...) == outp
end
end
| 23.288889
| 62
| 0.59208
|
[
"@testset \"Quite partial to it really\" begin\n add3 = @p(3 + _)\n @test add3(7) == 10\n add4r = @p(_ + 4)\n @test add4r(7) == 11\n\n lt10 = @partial _ < 10\n @test lt10(7) == true\n @test lt10(27) == false\n\n gt10 = @p(10 < _)\n @test gt10(17) == true\n @test gt10(7) == false\n\n fn_of7_and_10 = @p _(7,10)\n @test fn_of7_and_10(*) == 70\n @test fn_of7_and_10(+) == 17\n @test fn_of7_and_10(-) == -3\n @test fn_of7_and_10(/) == 0.7\n @test fn_of7_and_10(%) == 7\n\n @test map(@p(_(7,10)),[*,+,-,/,%]) == [70,17,-3,0.7,7]\n\n v1 = 3\n v2 = 5\n fn_of_v1_and_v2 = @p _(v1,v2)\n @test fn_of_v1_and_v2(*) == 15\n @test fn_of_v1_and_v2(+) == 8\n @test fn_of_v1_and_v2(-) == -2\n @test fn_of_v1_and_v2(/) == 0.6\n @test fn_of_v1_and_v2(%) == 3\n\nend",
"@testset \"partial multi sub\" begin\n d = 10\n zeros_dxN = @p zeros(_,d,_)\n @test zeros_dxN(Int,3) == zeros(Int,10,3)\n T = Float64\n d2 = 12\n zerosF64 = @p zeros(T,_,_)\n @test zerosF64(d2,4) == zeros(Float64,d2,4)\nend",
"@testset \"partial can handle nested syms\" begin\n len_gt_10 = @partial(length(_) > 10)\n @test len_gt_10(\"fred\") == false\n @test len_gt_10(\"freddy mercury\") == true\n\n fred = Array{Real}[]\n push!(fred, [1,2,3])\n push!(fred, [4.0,5.0,6.0])\n fred_sub_ind = @p(fred[_][_])\n @test fred_sub_ind(1,2) == 2\n @test fred_sub_ind(1,3) == 3\n @test fred_sub_ind(2,1) == 4.0\n @test fred_sub_ind(2,3) == 6.0\n\n len_gt_x = @partial(length(_) > _)\n @test len_gt_x(\"fred\",2) == true\n @test len_gt_x(\"fred\",10) == false\nend",
"@testset \"partial indexed sub\" begin\n d = 10\n zeros_dxN = @p zeros(Int,_1,_1)\n @test zeros_dxN(3) == zeros(Int,3,3)\n zeros_dxN = @p zeros(Int,_1,_)\n @test zeros_dxN(5) == zeros(Int,5,5)\n T = Float64\n d2 = 12\n zerosF64 = @p zeros(T,_,_1)\n @test zerosF64(d2) == zeros(Float64,12,12)\nend",
"@testset \"partial chained\" begin\n # unary fn\n x10plus3 = @p _*10 _+3\n for (inp, outp) in zip((2,3,4), (23,33,43))\n @test x10plus3(inp) == outp\n end\n # binary fn\n b_minus_a_x3 = @p _2-_1 _*3\n for (inp, outp) in zip([(2,4), (7,3), (9,2)], (6, -12, -21))\n @test b_minus_a_x3(inp...) == outp\n end\nend"
] |
f73b2208bf8dde34eed198d7565342859f8c432d
| 11,102
|
jl
|
Julia
|
julia/test/runtests.jl
|
magland/FMM3D
|
49284e2270e164ac1c05478b74c3ccf5f1d3c9de
|
[
"Apache-2.0"
] | 71
|
2019-06-03T21:22:37.000Z
|
2022-03-03T01:15:45.000Z
|
julia/test/runtests.jl
|
magland/FMM3D
|
49284e2270e164ac1c05478b74c3ccf5f1d3c9de
|
[
"Apache-2.0"
] | 14
|
2019-08-22T19:58:36.000Z
|
2022-02-08T19:01:06.000Z
|
julia/test/runtests.jl
|
magland/FMM3D
|
49284e2270e164ac1c05478b74c3ccf5f1d3c9de
|
[
"Apache-2.0"
] | 23
|
2019-09-13T21:30:35.000Z
|
2022-02-26T12:34:42.000Z
|
using FMM3D
using Test
using Random
using LinearAlgebra
@testset "testing Helmholtz utilities" begin
n = 1000
nt = 1100
sources = randn(3,n)
targets = randn(3,nt)
charges = randn(n) + im*randn(n)
dipvecs = randn(3,n) + im*randn(3,n)
zk = 2.1
vals1c = h3ddir(zk,sources,targets,charges=charges,
pgt=2,thresh=1e-16)
vals1cs = h3ddir(zk,sources,sources,charges=charges,
pgt=2,thresh=1e-16)
vals1d = h3ddir(zk,sources,targets,dipvecs=dipvecs,
pgt=2,thresh=1e-16)
vals1ds = h3ddir(zk,sources,sources,dipvecs=dipvecs,
pgt=2,thresh=1e-16)
vals1dc = h3ddir(zk,sources,targets,charges=charges,
dipvecs=dipvecs,pgt=2,thresh=1e-16)
vals1dcs = h3ddir(zk,sources,sources,charges=charges,
dipvecs=dipvecs,pgt=2,thresh=1e-16)
eps = 1e-12
vals2c = hfmm3d(eps,zk,sources,targets=targets,charges=charges,
pg=2,pgt=2)
vals2d = hfmm3d(eps,zk,sources,targets=targets,dipvecs=dipvecs,
pg=2,pgt=2)
vals2dc = hfmm3d(eps,zk,sources,targets=targets,charges=charges,
dipvecs=dipvecs,pg=2,pgt=2)
@test norm(vals2c.pot-vals1cs.pottarg)/norm(vals1cs.pottarg) < eps
@test norm(vals2c.grad-vals1cs.gradtarg)/norm(vals1cs.gradtarg) < eps
@test norm(vals2c.pottarg-vals1c.pottarg)/norm(vals1c.pottarg) < eps
@test norm(vals2c.gradtarg-vals1c.gradtarg)/norm(vals1c.gradtarg) < eps
@test norm(vals2d.pot-vals1ds.pottarg)/norm(vals1ds.pottarg) < eps
@test norm(vals2d.grad-vals1ds.gradtarg)/norm(vals1ds.gradtarg) < eps
@test norm(vals2d.pottarg-vals1d.pottarg)/norm(vals1d.pottarg) < eps
@test norm(vals2d.gradtarg-vals1d.gradtarg)/norm(vals1d.gradtarg) < eps
@test norm(vals2dc.pot-vals1dcs.pottarg)/norm(vals1dcs.pottarg) < eps
@test norm(vals2dc.grad-vals1dcs.gradtarg)/norm(vals1dcs.gradtarg) < eps
@test norm(vals2dc.pottarg-vals1dc.pottarg)/norm(vals1dc.pottarg) < eps
@test norm(vals2dc.gradtarg-vals1dc.gradtarg)/norm(vals1dc.gradtarg) < eps
end
@testset "testing Laplace utilities" begin
n = 1000
nt = 1100
sources = randn(3,n)
targets = randn(3,nt)
charges = randn(n)
dipvecs = randn(3,n)
vals1c = l3ddir(sources,targets,charges=charges,
pgt=2,thresh=1e-16)
vals1cs = l3ddir(sources,sources,charges=charges,
pgt=2,thresh=1e-16)
vals1d = l3ddir(sources,targets,dipvecs=dipvecs,
pgt=2,thresh=1e-16)
vals1ds = l3ddir(sources,sources,dipvecs=dipvecs,
pgt=2,thresh=1e-16)
vals1dc = l3ddir(sources,targets,charges=charges,
dipvecs=dipvecs,pgt=2,thresh=1e-16)
vals1dcs = l3ddir(sources,sources,charges=charges,
dipvecs=dipvecs,pgt=2,thresh=1e-16)
eps = 1e-12
vals2c = lfmm3d(eps,sources,targets=targets,charges=charges,
pg=2,pgt=2)
vals2d = lfmm3d(eps,sources,targets=targets,dipvecs=dipvecs,
pg=2,pgt=2)
vals2dc = lfmm3d(eps,sources,targets=targets,charges=charges,
dipvecs=dipvecs,pg=2,pgt=2)
@test norm(vals2c.pot-vals1cs.pottarg)/norm(vals1cs.pottarg) < eps
@test norm(vals2c.grad-vals1cs.gradtarg)/norm(vals1cs.gradtarg) < eps
@test norm(vals2c.pottarg-vals1c.pottarg)/norm(vals1c.pottarg) < eps
@test norm(vals2c.gradtarg-vals1c.gradtarg)/norm(vals1c.gradtarg) < eps
@test norm(vals2d.pot-vals1ds.pottarg)/norm(vals1ds.pottarg) < eps
@test norm(vals2d.grad-vals1ds.gradtarg)/norm(vals1ds.gradtarg) < eps
@test norm(vals2d.pottarg-vals1d.pottarg)/norm(vals1d.pottarg) < eps
@test norm(vals2d.gradtarg-vals1d.gradtarg)/norm(vals1d.gradtarg) < eps
@test norm(vals2dc.pot-vals1dcs.pottarg)/norm(vals1dcs.pottarg) < eps
@test norm(vals2dc.grad-vals1dcs.gradtarg)/norm(vals1dcs.gradtarg) < eps
@test norm(vals2dc.pottarg-vals1dc.pottarg)/norm(vals1dc.pottarg) < eps
@test norm(vals2dc.gradtarg-vals1dc.gradtarg)/norm(vals1dc.gradtarg) < eps
end
@testset "testing Stokes utilities" begin
n = 1000
nt = 1100
sources = randn(3,n)
targets = randn(3,nt)
stoklet = randn(3,n)
strslet = randn(3,n)
strsvec = randn(3,n)
vals1c = st3ddir(sources,targets,stoklet=stoklet,
ppregt=3,thresh=1e-16)
vals1cs = st3ddir(sources,sources,stoklet=stoklet,
ppregt=3,thresh=1e-16)
vals1d = st3ddir(sources,targets,strslet=strslet,strsvec=strsvec,
ppregt=3,thresh=1e-16)
vals1ds = st3ddir(sources,sources,strslet=strslet,strsvec=strsvec,
ppregt=3,thresh=1e-16)
vals1dc = st3ddir(sources,targets,stoklet=stoklet,
strslet=strslet,strsvec=strsvec,ppregt=3,thresh=1e-16)
vals1dcs = st3ddir(sources,sources,stoklet=stoklet,
strslet=strslet,strsvec=strsvec,ppregt=3,thresh=1e-16)
eps = 1e-12
vals2c = stfmm3d(eps,sources,targets=targets,stoklet=stoklet,
ppreg=3,ppregt=3)
vals2d = stfmm3d(eps,sources,targets=targets,strslet=strslet,strsvec=strsvec,
ppreg=3,ppregt=3)
vals2dc = stfmm3d(eps,sources,targets=targets,stoklet=stoklet,
strslet=strslet,strsvec=strsvec,ppreg=3,ppregt=3)
@test norm(vals2c.pot-vals1cs.pottarg)/norm(vals1cs.pottarg) < eps
@test norm(vals2c.pre-vals1cs.pretarg)/norm(vals1cs.pretarg) < eps
@test norm(vals2c.grad-vals1cs.gradtarg)/norm(vals1cs.gradtarg) < eps
@test norm(vals2c.pottarg-vals1c.pottarg)/norm(vals1c.pottarg) < eps
@test norm(vals2c.gradtarg-vals1c.gradtarg)/norm(vals1c.gradtarg) < eps
@test norm(vals2c.pretarg-vals1c.pretarg)/norm(vals1c.pretarg) < eps
@test norm(vals2d.pot-vals1ds.pottarg)/norm(vals1ds.pottarg) < eps
@test norm(vals2d.pre-vals1ds.pretarg)/norm(vals1ds.pretarg) < eps
@test norm(vals2d.grad-vals1ds.gradtarg)/norm(vals1ds.gradtarg) < eps
@test norm(vals2d.pottarg-vals1d.pottarg)/norm(vals1d.pottarg) < eps
@test norm(vals2d.pretarg-vals1d.pretarg)/norm(vals1d.pretarg) < eps
@test norm(vals2d.gradtarg-vals1d.gradtarg)/norm(vals1d.gradtarg) < eps
@test norm(vals2dc.pot-vals1dcs.pottarg)/norm(vals1dcs.pottarg) < eps
@test norm(vals2dc.pre-vals1dcs.pretarg)/norm(vals1dcs.pretarg) < eps
@test norm(vals2dc.grad-vals1dcs.gradtarg)/norm(vals1dcs.gradtarg) < eps
@test norm(vals2dc.pottarg-vals1dc.pottarg)/norm(vals1dc.pottarg) < eps
@test norm(vals2dc.pretarg-vals1dc.pretarg)/norm(vals1dc.pretarg) < eps
@test norm(vals2dc.gradtarg-vals1dc.gradtarg)/norm(vals1dc.gradtarg) < eps
end
@testset "testing electromagnetics utilities" begin
n = 10
nt = 11
sources = randn(3,n)
targets = randn(3,nt)
A = randn(3,n) + im*randn(3,n)
B = randn(3,n) + im*randn(3,n)
lambda = randn(n) + im*randn(n)
zk = 2.1
vals1A = em3ddir(zk,sources,targets,A=A,
ifEtarg=true,ifdivEtarg=true,
ifcurlEtarg=true,thresh=1e-16)
vals1As = em3ddir(zk,sources,sources,A=A,
ifEtarg=true,ifdivEtarg=true,
ifcurlEtarg=true,thresh=1e-16)
vals1B = em3ddir(zk,sources,targets,B=B,
ifEtarg=true,ifdivEtarg=true,
ifcurlEtarg=true,thresh=1e-16)
vals1Bs = em3ddir(zk,sources,sources,B=B,
ifEtarg=true,ifdivEtarg=true,
ifcurlEtarg=true,thresh=1e-16)
vals1lambda = em3ddir(zk,sources,targets,lambda=lambda,
ifEtarg=true,ifdivEtarg=true,
ifcurlEtarg=true,thresh=1e-16)
vals1lambdas = em3ddir(zk,sources,sources,lambda=lambda,
ifEtarg=true,ifdivEtarg=true,
ifcurlEtarg=true,thresh=1e-16)
vals1all = em3ddir(zk,sources,targets,A=A,B=B,lambda=lambda,
ifEtarg=true,ifdivEtarg=true,
ifcurlEtarg=true,thresh=1e-16)
vals1alls = em3ddir(zk,sources,sources,A=A,B=B,lambda=lambda,
ifEtarg=true,ifdivEtarg=true,
ifcurlEtarg=true,thresh=1e-16)
eps = 1e-12
vals2A = emfmm3d(eps,zk,sources,targets=targets,A=A,
ifE=true,ifdivE=true,ifcurlE=true,
ifEtarg=true,ifdivEtarg=true,ifcurlEtarg=true)
vals2B = emfmm3d(eps,zk,sources,targets=targets,B=B,
ifE=true,ifdivE=true,ifcurlE=true,
ifEtarg=true,ifdivEtarg=true,ifcurlEtarg=true)
vals2lambda = emfmm3d(eps,zk,sources,targets=targets,lambda=lambda,
ifE=true,ifdivE=true,ifcurlE=true,
ifEtarg=true,ifdivEtarg=true,ifcurlEtarg=true)
vals2all = emfmm3d(eps,zk,sources,targets=targets,A=A,B=B,lambda=lambda,
ifE=true,ifdivE=true,ifcurlE=true,
ifEtarg=true,ifdivEtarg=true,ifcurlEtarg=true)
function absrelerr(vex,v)
return norm(vex-v)/max(norm(vex),1)
end
@test absrelerr(vals1As.Etarg,vals2A.E) < eps
@test absrelerr(vals1A.Etarg,vals2A.Etarg) < eps
@test absrelerr(vals1As.divEtarg,vals2A.divE) < eps
@test absrelerr(vals1A.divEtarg,vals2A.divEtarg) < eps
@test absrelerr(vals1As.curlEtarg,vals2A.curlE) < eps
@test absrelerr(vals1A.curlEtarg,vals2A.curlEtarg) < eps
@test absrelerr(vals1Bs.Etarg,vals2B.E) < eps
@test absrelerr(vals1B.Etarg,vals2B.Etarg) < eps
@test absrelerr(vals1Bs.divEtarg,vals2B.divE) < eps
@test absrelerr(vals1B.divEtarg,vals2B.divEtarg) < eps
@test absrelerr(vals1Bs.curlEtarg,vals2B.curlE) < eps
@test absrelerr(vals1B.curlEtarg,vals2B.curlEtarg) < eps
@test absrelerr(vals1lambdas.Etarg,vals2lambda.E) < eps
@test absrelerr(vals1lambda.Etarg,vals2lambda.Etarg) < eps
@test absrelerr(vals1lambdas.divEtarg,vals2lambda.divE) < eps
@test absrelerr(vals1lambda.divEtarg,vals2lambda.divEtarg) < eps
@test absrelerr(vals1lambdas.curlEtarg,vals2lambda.curlE) < eps
@test absrelerr(vals1lambda.curlEtarg,vals2lambda.curlEtarg) < eps
@test absrelerr(vals1alls.Etarg,vals2all.E) < eps
@test absrelerr(vals1all.Etarg,vals2all.Etarg) < eps
@test absrelerr(vals1alls.divEtarg,vals2all.divE) < eps
@test absrelerr(vals1all.divEtarg,vals2all.divEtarg) < eps
@test absrelerr(vals1alls.curlEtarg,vals2all.curlE) < eps
@test absrelerr(vals1all.curlEtarg,vals2all.curlEtarg) < eps
end
@testset "testing lower level routines" begin
# besseljs3d
nterms = 10
z = 1.1 + im*1.2
scale = 1.3
ifder = 1
fj10 = (-3.5183264829466616750769540*(1e-9) +
im*8.88237983492960538163695769*(1e-9))
fjs, fjder = besseljs3d(nterms,z,scale=scale,ifder=ifder)
@test (abs(fj10-fjs[11]*(scale^10))/abs(fj10) < 1e-10)
end
| 38.818182
| 83
| 0.647721
|
[
"@testset \"testing Helmholtz utilities\" begin\n\n n = 1000\n nt = 1100\n sources = randn(3,n)\n targets = randn(3,nt)\n charges = randn(n) + im*randn(n)\n dipvecs = randn(3,n) + im*randn(3,n)\n zk = 2.1\n\n vals1c = h3ddir(zk,sources,targets,charges=charges,\n pgt=2,thresh=1e-16)\n\n vals1cs = h3ddir(zk,sources,sources,charges=charges,\n pgt=2,thresh=1e-16)\n\n vals1d = h3ddir(zk,sources,targets,dipvecs=dipvecs,\n pgt=2,thresh=1e-16)\n\n vals1ds = h3ddir(zk,sources,sources,dipvecs=dipvecs,\n pgt=2,thresh=1e-16)\n\n vals1dc = h3ddir(zk,sources,targets,charges=charges,\n dipvecs=dipvecs,pgt=2,thresh=1e-16)\n\n vals1dcs = h3ddir(zk,sources,sources,charges=charges,\n dipvecs=dipvecs,pgt=2,thresh=1e-16)\n\n eps = 1e-12\n vals2c = hfmm3d(eps,zk,sources,targets=targets,charges=charges,\n pg=2,pgt=2)\n vals2d = hfmm3d(eps,zk,sources,targets=targets,dipvecs=dipvecs,\n pg=2,pgt=2)\n vals2dc = hfmm3d(eps,zk,sources,targets=targets,charges=charges,\n dipvecs=dipvecs,pg=2,pgt=2)\n\n @test norm(vals2c.pot-vals1cs.pottarg)/norm(vals1cs.pottarg) < eps\n @test norm(vals2c.grad-vals1cs.gradtarg)/norm(vals1cs.gradtarg) < eps\n @test norm(vals2c.pottarg-vals1c.pottarg)/norm(vals1c.pottarg) < eps\n @test norm(vals2c.gradtarg-vals1c.gradtarg)/norm(vals1c.gradtarg) < eps \n\n @test norm(vals2d.pot-vals1ds.pottarg)/norm(vals1ds.pottarg) < eps\n @test norm(vals2d.grad-vals1ds.gradtarg)/norm(vals1ds.gradtarg) < eps\n @test norm(vals2d.pottarg-vals1d.pottarg)/norm(vals1d.pottarg) < eps\n @test norm(vals2d.gradtarg-vals1d.gradtarg)/norm(vals1d.gradtarg) < eps \n\n @test norm(vals2dc.pot-vals1dcs.pottarg)/norm(vals1dcs.pottarg) < eps\n @test norm(vals2dc.grad-vals1dcs.gradtarg)/norm(vals1dcs.gradtarg) < eps\n @test norm(vals2dc.pottarg-vals1dc.pottarg)/norm(vals1dc.pottarg) < eps\n @test norm(vals2dc.gradtarg-vals1dc.gradtarg)/norm(vals1dc.gradtarg) < eps \n \n\nend",
"@testset \"testing Laplace utilities\" begin\n\n n = 1000\n nt = 1100\n sources = randn(3,n)\n targets = randn(3,nt)\n charges = randn(n)\n dipvecs = randn(3,n)\n\n vals1c = l3ddir(sources,targets,charges=charges,\n pgt=2,thresh=1e-16)\n\n vals1cs = l3ddir(sources,sources,charges=charges,\n pgt=2,thresh=1e-16)\n\n vals1d = l3ddir(sources,targets,dipvecs=dipvecs,\n pgt=2,thresh=1e-16)\n\n vals1ds = l3ddir(sources,sources,dipvecs=dipvecs,\n pgt=2,thresh=1e-16)\n\n vals1dc = l3ddir(sources,targets,charges=charges,\n dipvecs=dipvecs,pgt=2,thresh=1e-16)\n\n vals1dcs = l3ddir(sources,sources,charges=charges,\n dipvecs=dipvecs,pgt=2,thresh=1e-16)\n\n eps = 1e-12\n vals2c = lfmm3d(eps,sources,targets=targets,charges=charges,\n pg=2,pgt=2)\n vals2d = lfmm3d(eps,sources,targets=targets,dipvecs=dipvecs,\n pg=2,pgt=2)\n vals2dc = lfmm3d(eps,sources,targets=targets,charges=charges,\n dipvecs=dipvecs,pg=2,pgt=2)\n\n @test norm(vals2c.pot-vals1cs.pottarg)/norm(vals1cs.pottarg) < eps\n @test norm(vals2c.grad-vals1cs.gradtarg)/norm(vals1cs.gradtarg) < eps\n @test norm(vals2c.pottarg-vals1c.pottarg)/norm(vals1c.pottarg) < eps\n @test norm(vals2c.gradtarg-vals1c.gradtarg)/norm(vals1c.gradtarg) < eps \n\n @test norm(vals2d.pot-vals1ds.pottarg)/norm(vals1ds.pottarg) < eps\n @test norm(vals2d.grad-vals1ds.gradtarg)/norm(vals1ds.gradtarg) < eps\n @test norm(vals2d.pottarg-vals1d.pottarg)/norm(vals1d.pottarg) < eps\n @test norm(vals2d.gradtarg-vals1d.gradtarg)/norm(vals1d.gradtarg) < eps \n\n @test norm(vals2dc.pot-vals1dcs.pottarg)/norm(vals1dcs.pottarg) < eps\n @test norm(vals2dc.grad-vals1dcs.gradtarg)/norm(vals1dcs.gradtarg) < eps\n @test norm(vals2dc.pottarg-vals1dc.pottarg)/norm(vals1dc.pottarg) < eps\n @test norm(vals2dc.gradtarg-vals1dc.gradtarg)/norm(vals1dc.gradtarg) < eps \n \n\nend",
"@testset \"testing Stokes utilities\" begin\n\n n = 1000\n nt = 1100\n sources = randn(3,n)\n targets = randn(3,nt)\n stoklet = randn(3,n)\n strslet = randn(3,n)\n strsvec = randn(3,n)\n\n vals1c = st3ddir(sources,targets,stoklet=stoklet,\n ppregt=3,thresh=1e-16)\n\n vals1cs = st3ddir(sources,sources,stoklet=stoklet,\n ppregt=3,thresh=1e-16)\n\n vals1d = st3ddir(sources,targets,strslet=strslet,strsvec=strsvec,\n ppregt=3,thresh=1e-16)\n\n vals1ds = st3ddir(sources,sources,strslet=strslet,strsvec=strsvec,\n ppregt=3,thresh=1e-16)\n\n vals1dc = st3ddir(sources,targets,stoklet=stoklet,\n strslet=strslet,strsvec=strsvec,ppregt=3,thresh=1e-16)\n\n vals1dcs = st3ddir(sources,sources,stoklet=stoklet,\n strslet=strslet,strsvec=strsvec,ppregt=3,thresh=1e-16)\n\n eps = 1e-12\n vals2c = stfmm3d(eps,sources,targets=targets,stoklet=stoklet,\n ppreg=3,ppregt=3)\n vals2d = stfmm3d(eps,sources,targets=targets,strslet=strslet,strsvec=strsvec,\n ppreg=3,ppregt=3)\n vals2dc = stfmm3d(eps,sources,targets=targets,stoklet=stoklet,\n strslet=strslet,strsvec=strsvec,ppreg=3,ppregt=3)\n\n @test norm(vals2c.pot-vals1cs.pottarg)/norm(vals1cs.pottarg) < eps\n @test norm(vals2c.pre-vals1cs.pretarg)/norm(vals1cs.pretarg) < eps\n @test norm(vals2c.grad-vals1cs.gradtarg)/norm(vals1cs.gradtarg) < eps \n @test norm(vals2c.pottarg-vals1c.pottarg)/norm(vals1c.pottarg) < eps\n @test norm(vals2c.gradtarg-vals1c.gradtarg)/norm(vals1c.gradtarg) < eps\n @test norm(vals2c.pretarg-vals1c.pretarg)/norm(vals1c.pretarg) < eps \n\n @test norm(vals2d.pot-vals1ds.pottarg)/norm(vals1ds.pottarg) < eps\n @test norm(vals2d.pre-vals1ds.pretarg)/norm(vals1ds.pretarg) < eps\n @test norm(vals2d.grad-vals1ds.gradtarg)/norm(vals1ds.gradtarg) < eps\n @test norm(vals2d.pottarg-vals1d.pottarg)/norm(vals1d.pottarg) < eps\n @test norm(vals2d.pretarg-vals1d.pretarg)/norm(vals1d.pretarg) < eps\n @test norm(vals2d.gradtarg-vals1d.gradtarg)/norm(vals1d.gradtarg) < eps \n\n @test norm(vals2dc.pot-vals1dcs.pottarg)/norm(vals1dcs.pottarg) < eps\n @test norm(vals2dc.pre-vals1dcs.pretarg)/norm(vals1dcs.pretarg) < eps\n @test norm(vals2dc.grad-vals1dcs.gradtarg)/norm(vals1dcs.gradtarg) < eps\n @test norm(vals2dc.pottarg-vals1dc.pottarg)/norm(vals1dc.pottarg) < eps\n @test norm(vals2dc.pretarg-vals1dc.pretarg)/norm(vals1dc.pretarg) < eps \n @test norm(vals2dc.gradtarg-vals1dc.gradtarg)/norm(vals1dc.gradtarg) < eps \n \n\nend",
"@testset \"testing electromagnetics utilities\" begin\n\n n = 10\n nt = 11\n sources = randn(3,n)\n targets = randn(3,nt)\n A = randn(3,n) + im*randn(3,n)\n B = randn(3,n) + im*randn(3,n)\n lambda = randn(n) + im*randn(n)\n zk = 2.1\n\n vals1A = em3ddir(zk,sources,targets,A=A,\n ifEtarg=true,ifdivEtarg=true,\n ifcurlEtarg=true,thresh=1e-16)\n\n vals1As = em3ddir(zk,sources,sources,A=A,\n ifEtarg=true,ifdivEtarg=true,\n ifcurlEtarg=true,thresh=1e-16)\n\n vals1B = em3ddir(zk,sources,targets,B=B,\n ifEtarg=true,ifdivEtarg=true,\n ifcurlEtarg=true,thresh=1e-16)\n\n vals1Bs = em3ddir(zk,sources,sources,B=B,\n ifEtarg=true,ifdivEtarg=true,\n ifcurlEtarg=true,thresh=1e-16)\n\n vals1lambda = em3ddir(zk,sources,targets,lambda=lambda,\n ifEtarg=true,ifdivEtarg=true,\n ifcurlEtarg=true,thresh=1e-16)\n\n vals1lambdas = em3ddir(zk,sources,sources,lambda=lambda,\n ifEtarg=true,ifdivEtarg=true,\n ifcurlEtarg=true,thresh=1e-16)\n\n vals1all = em3ddir(zk,sources,targets,A=A,B=B,lambda=lambda,\n ifEtarg=true,ifdivEtarg=true,\n ifcurlEtarg=true,thresh=1e-16)\n\n vals1alls = em3ddir(zk,sources,sources,A=A,B=B,lambda=lambda,\n ifEtarg=true,ifdivEtarg=true,\n ifcurlEtarg=true,thresh=1e-16)\n\n eps = 1e-12\n vals2A = emfmm3d(eps,zk,sources,targets=targets,A=A,\n ifE=true,ifdivE=true,ifcurlE=true,\n ifEtarg=true,ifdivEtarg=true,ifcurlEtarg=true)\n \n vals2B = emfmm3d(eps,zk,sources,targets=targets,B=B,\n ifE=true,ifdivE=true,ifcurlE=true,\n ifEtarg=true,ifdivEtarg=true,ifcurlEtarg=true)\n \n vals2lambda = emfmm3d(eps,zk,sources,targets=targets,lambda=lambda,\n ifE=true,ifdivE=true,ifcurlE=true,\n ifEtarg=true,ifdivEtarg=true,ifcurlEtarg=true)\n \n vals2all = emfmm3d(eps,zk,sources,targets=targets,A=A,B=B,lambda=lambda,\n ifE=true,ifdivE=true,ifcurlE=true,\n ifEtarg=true,ifdivEtarg=true,ifcurlEtarg=true)\n\n function absrelerr(vex,v)\n return norm(vex-v)/max(norm(vex),1)\n end\n \n @test absrelerr(vals1As.Etarg,vals2A.E) < eps\n @test absrelerr(vals1A.Etarg,vals2A.Etarg) < eps \n @test absrelerr(vals1As.divEtarg,vals2A.divE) < eps\n @test absrelerr(vals1A.divEtarg,vals2A.divEtarg) < eps \n @test absrelerr(vals1As.curlEtarg,vals2A.curlE) < eps\n @test absrelerr(vals1A.curlEtarg,vals2A.curlEtarg) < eps \n \n @test absrelerr(vals1Bs.Etarg,vals2B.E) < eps\n @test absrelerr(vals1B.Etarg,vals2B.Etarg) < eps \n @test absrelerr(vals1Bs.divEtarg,vals2B.divE) < eps\n @test absrelerr(vals1B.divEtarg,vals2B.divEtarg) < eps \n @test absrelerr(vals1Bs.curlEtarg,vals2B.curlE) < eps\n @test absrelerr(vals1B.curlEtarg,vals2B.curlEtarg) < eps \n \n @test absrelerr(vals1lambdas.Etarg,vals2lambda.E) < eps\n @test absrelerr(vals1lambda.Etarg,vals2lambda.Etarg) < eps \n @test absrelerr(vals1lambdas.divEtarg,vals2lambda.divE) < eps\n @test absrelerr(vals1lambda.divEtarg,vals2lambda.divEtarg) < eps \n @test absrelerr(vals1lambdas.curlEtarg,vals2lambda.curlE) < eps\n @test absrelerr(vals1lambda.curlEtarg,vals2lambda.curlEtarg) < eps \n \n @test absrelerr(vals1alls.Etarg,vals2all.E) < eps\n @test absrelerr(vals1all.Etarg,vals2all.Etarg) < eps \n @test absrelerr(vals1alls.divEtarg,vals2all.divE) < eps\n @test absrelerr(vals1all.divEtarg,vals2all.divEtarg) < eps \n @test absrelerr(vals1alls.curlEtarg,vals2all.curlE) < eps\n @test absrelerr(vals1all.curlEtarg,vals2all.curlEtarg) < eps \n\nend",
"@testset \"testing lower level routines\" begin\n\n\n # besseljs3d\n\n nterms = 10\n z = 1.1 + im*1.2\n scale = 1.3\n ifder = 1\n\n fj10 = (-3.5183264829466616750769540*(1e-9) +\n im*8.88237983492960538163695769*(1e-9))\n\n fjs, fjder = besseljs3d(nterms,z,scale=scale,ifder=ifder)\n\n @test (abs(fj10-fjs[11]*(scale^10))/abs(fj10) < 1e-10)\n\nend"
] |
f73b80024cd7d4ea135105c3bba9a1f6640b5291
| 1,492
|
jl
|
Julia
|
test/runtests.jl
|
anubhavpcjha/lolPackage
|
5a1649076dba63c3dcef0bf9a7dadec1a6be755a
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
anubhavpcjha/lolPackage
|
5a1649076dba63c3dcef0bf9a7dadec1a6be755a
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
anubhavpcjha/lolPackage
|
5a1649076dba63c3dcef0bf9a7dadec1a6be755a
|
[
"MIT"
] | null | null | null |
using lolPackage
using Test
#TEST 1 WITH DERIVATIVES
f(x)=x^2
fprime(x)=2*x
@test Newtonsroot1(f,fprime,xiv=0.1)[1]≈0.0 atol=0.00001
f(x)=x^2-16
fprime(x)=2*x
@test Newtonsroot1(f,fprime,xiv=3.1)[1]≈4.0 atol=0.00001
f(x)=(x-2)^2
fprime(x)=2*(x-2)
@test Newtonsroot1(f,fprime,xiv=1.0)[1]≈2.0 atol=0.00001
#TEST 2 WITHOUT DERIVATIVES
f(x)=x^2
@test Newtonsroot1(f,xiv=1.0)[1]≈0.0 atol=0.00001
f(x)=x^2-16
@test Newtonsroot1(f,xiv=1.0)[1]≈4.0 atol=0.00001
f(x)=(x-2)^2
@test Newtonsroot1(f,xiv=1.0)[1]≈2.0 atol=0.00001
#TEST 3 BIGFLOAT
f(x)=(x-2)^2
a=BigFloat(2.0)
@testset "BigFloat" begin
@test Newtonsroot1(f,xiv=1.0)[1]≈2.0 atol=0.00001
@test Newtonsroot1(f,xiv=1.0)[1]≈a atol=0.00001
end
#TEST 4 tolerance (Accuracy dependent on tolerance)
f(x)=4x^3-16x+10
a=Newtonsroot1(f,xiv=1)[1]
b=Newtonsroot1(f,xiv=1, tol=0.0001)[1]
c=Newtonsroot1(f,xiv=1, tol=0.01)[1]
@test f(a)<f(b)<f(c)
#TEST 5 Non-Convergence
#Test non-convergence (return nothing)
f(x)=2+x^2
@test Newtonsroot1(f,xiv=0.2)==nothing
#TEST 6 Maxiter
f(x)=log(x)-20
a=Newtonsroot1(f,xiv=0.2)[1] #Algorithm needs 17 iterations in this case
b=Newtonsroot1(f,xiv=0.2,maxiter=5)
@testset "maxiter" begin
@test a≈4.851651954097909e8 atol=0.000001
@test b==nothing
end;
| 22.953846
| 76
| 0.577748
|
[
"@testset \"BigFloat\" begin\n @test Newtonsroot1(f,xiv=1.0)[1]≈2.0 atol=0.00001\n @test Newtonsroot1(f,xiv=1.0)[1]≈a atol=0.00001\n end",
"@testset \"maxiter\" begin\n @test a≈4.851651954097909e8 atol=0.000001 \n @test b==nothing\n end"
] |
f741fd5e32a0c3dbe2a6ade881ffd5908885f136
| 1,284
|
jl
|
Julia
|
test/rank_by_stability.jl
|
Durzot/MT_NMF
|
a3e3c2fb4a23cc09e78e1ad1e324787c6017a4fc
|
[
"MIT"
] | null | null | null |
test/rank_by_stability.jl
|
Durzot/MT_NMF
|
a3e3c2fb4a23cc09e78e1ad1e324787c6017a4fc
|
[
"MIT"
] | null | null | null |
test/rank_by_stability.jl
|
Durzot/MT_NMF
|
a3e3c2fb4a23cc09e78e1ad1e324787c6017a4fc
|
[
"MIT"
] | null | null | null |
using Distributions
using VariantsNMF
using Test
#### simulate
V = get_one_simulated_V()
V = round.(V .* 100)
@testset "nmf_MU" begin
#### params for rank selection
rs_params = RSParams(
K_min = 1,
K_max = 10,
n_iter = 50,
pert_meth = :multinomial,
seed = 123
)
#### nmf algorithm
nmf_global_params = NMFParams(
init = :random,
dist = Uniform(0, 1),
max_iter = 1_000,
stopping_crit = :conn,
stopping_iter = 10,
verbose = false,
)
nmf_local_params = MUParams(
β = 1,
div = :β,
scale_W_iter = false,
scale_W_last = false,
alg = :mu
)
nmf = NMF(
solver = nmf_MU,
global_params = nmf_global_params,
local_params = nmf_local_params
)
#### run rank selection by stability procedure
@time rs_results = rank_by_stability(V, rs_params, nmf)
@test "rank" in names(rs_results.df_metrics)
@test "stab_avg" in names(rs_results.df_metrics)
@test "stab_std" in names(rs_results.df_metrics)
@test "fid_avg" in names(rs_results.df_metrics)
@test "fid_std" in names(rs_results.df_metrics)
end
| 24.692308
| 59
| 0.561526
|
[
"@testset \"nmf_MU\" begin\n #### params for rank selection\n rs_params = RSParams(\n K_min = 1,\n K_max = 10,\n n_iter = 50,\n pert_meth = :multinomial,\n seed = 123\n )\n\n #### nmf algorithm\n nmf_global_params = NMFParams(\n init = :random,\n dist = Uniform(0, 1),\n max_iter = 1_000,\n stopping_crit = :conn,\n stopping_iter = 10,\n verbose = false,\n )\n\n nmf_local_params = MUParams(\n β = 1,\n div = :β,\n scale_W_iter = false,\n scale_W_last = false,\n alg = :mu\n )\n\n nmf = NMF(\n solver = nmf_MU,\n global_params = nmf_global_params,\n local_params = nmf_local_params\n )\n\n #### run rank selection by stability procedure\n @time rs_results = rank_by_stability(V, rs_params, nmf)\n\n @test \"rank\" in names(rs_results.df_metrics)\n @test \"stab_avg\" in names(rs_results.df_metrics)\n @test \"stab_std\" in names(rs_results.df_metrics)\n @test \"fid_avg\" in names(rs_results.df_metrics)\n @test \"fid_std\" in names(rs_results.df_metrics)\nend"
] |
f747730293c3fc3d56a4caca670cbd8c766fef15
| 333
|
jl
|
Julia
|
test/runtests.jl
|
NHDaly/SimpleMock.jl
|
5e79a57f5987f6d54fb7338eb424826ad4e10eac
|
[
"MIT"
] | 12
|
2020-06-17T23:17:23.000Z
|
2022-02-16T02:23:01.000Z
|
test/runtests.jl
|
NHDaly/SimpleMock.jl
|
5e79a57f5987f6d54fb7338eb424826ad4e10eac
|
[
"MIT"
] | 10
|
2019-09-23T06:43:26.000Z
|
2020-04-20T17:53:49.000Z
|
test/runtests.jl
|
NHDaly/SimpleMock.jl
|
5e79a57f5987f6d54fb7338eb424826ad4e10eac
|
[
"MIT"
] | 3
|
2019-11-28T06:12:59.000Z
|
2020-02-08T10:39:16.000Z
|
using Base: JLOptions
using Test: @test, @testset, @test_broken, @test_logs, @test_throws
using Suppressor: @capture_err, @suppress
using SimpleMock
@testset "SimpleMock.jl" begin
@testset "Mock type" begin
include("mock_type.jl")
end
@testset "mock function" begin
include("mock_fun.jl")
end
end
| 19.588235
| 67
| 0.690691
|
[
"@testset \"SimpleMock.jl\" begin\n @testset \"Mock type\" begin\n include(\"mock_type.jl\")\n end\n @testset \"mock function\" begin\n include(\"mock_fun.jl\")\n end\nend"
] |
f747edbb78daf49b533e6e6c02b4b91157cb7990
| 6,275
|
jl
|
Julia
|
lib/ClimaCorePlots/test/runtests.jl
|
CliMA/ClimaCore.jl
|
e28309249a4c0dea0e8bb897b4dc9ebc376fa94e
|
[
"Apache-2.0"
] | 32
|
2021-07-19T20:14:46.000Z
|
2022-03-26T00:18:43.000Z
|
lib/ClimaCorePlots/test/runtests.jl
|
CliMA/ClimaCore.jl
|
e28309249a4c0dea0e8bb897b4dc9ebc376fa94e
|
[
"Apache-2.0"
] | 543
|
2021-07-06T18:21:05.000Z
|
2022-03-31T20:39:02.000Z
|
lib/ClimaCorePlots/test/runtests.jl
|
CliMA/ClimaCore.jl
|
e28309249a4c0dea0e8bb897b4dc9ebc376fa94e
|
[
"Apache-2.0"
] | 1
|
2021-09-27T16:54:21.000Z
|
2021-09-27T16:54:21.000Z
|
ENV["GKSwstype"] = "nul"
using Test
using IntervalSets
import Plots
import ClimaCore
import ClimaCorePlots
OUTPUT_DIR = mkpath(get(ENV, "CI_OUTPUT_DIR", tempname()))
@testset "spectral element 2D cubed-sphere" begin
R = 6.37122e6
domain = ClimaCore.Domains.SphereDomain(R)
mesh = ClimaCore.Meshes.EquiangularCubedSphere(domain, 6)
grid_topology = ClimaCore.Topologies.Topology2D(mesh)
quad = ClimaCore.Spaces.Quadratures.GLL{5}()
space = ClimaCore.Spaces.SpectralElementSpace2D(grid_topology, quad)
coords = ClimaCore.Fields.coordinate_field(space)
u = map(coords) do coord
u0 = 20.0
α0 = 45.0
ϕ = coord.lat
λ = coord.long
uu = u0 * (cosd(α0) * cosd(ϕ) + sind(α0) * cosd(λ) * sind(ϕ))
uv = -u0 * sind(α0) * sind(λ)
ClimaCore.Geometry.UVVector(uu, uv)
end
field_fig = Plots.plot(u.components.data.:1)
@test field_fig !== nothing
fig_png = joinpath(OUTPUT_DIR, "2D_cubed_sphere_field.png")
Plots.png(field_fig, fig_png)
@test isfile(fig_png)
end
@testset "spectral element rectangle 2D" begin
domain = ClimaCore.Domains.RectangleDomain(
ClimaCore.Geometry.XPoint(0) .. ClimaCore.Geometry.XPoint(2π),
ClimaCore.Geometry.YPoint(0) .. ClimaCore.Geometry.YPoint(2π),
x1periodic = true,
x2periodic = true,
)
n1, n2 = 2, 2
Nq = 4
mesh = ClimaCore.Meshes.RectilinearMesh(domain, n1, n2)
grid_topology = ClimaCore.Topologies.Topology2D(mesh)
#quad = ClimaCore.Spaces.Quadratures.GLL{Nq}()
quad = ClimaCore.Spaces.Quadratures.ClosedUniform{Nq + 1}()
space = ClimaCore.Spaces.SpectralElementSpace2D(grid_topology, quad)
coords = ClimaCore.Fields.coordinate_field(space)
space_fig = Plots.plot(space)
@test space_fig !== nothing
sinxy = map(coords) do coord
cos(coord.x + coord.y)
end
field_fig = Plots.plot(sinxy)
@test field_fig !== nothing
space_png = joinpath(OUTPUT_DIR, "2D_rectangle_space.png")
field_png = joinpath(OUTPUT_DIR, "2D_rectangle_field.png")
Plots.png(space_fig, space_png)
Plots.png(field_fig, field_png)
@test isfile(space_png)
@test isfile(field_png)
end
@testset "hybrid finite difference / spectral element 2D" begin
FT = Float64
helem = 10
velem = 40
npoly = 4
vertdomain = ClimaCore.Domains.IntervalDomain(
ClimaCore.Geometry.ZPoint{FT}(0),
ClimaCore.Geometry.ZPoint{FT}(1000);
boundary_tags = (:bottom, :top),
)
vertmesh = ClimaCore.Meshes.IntervalMesh(vertdomain, nelems = velem)
vert_center_space = ClimaCore.Spaces.CenterFiniteDifferenceSpace(vertmesh)
horzdomain = ClimaCore.Domains.IntervalDomain(
ClimaCore.Geometry.XPoint{FT}(-500) ..
ClimaCore.Geometry.XPoint{FT}(500),
periodic = true,
)
horzmesh = ClimaCore.Meshes.IntervalMesh(horzdomain; nelems = helem)
horztopology = ClimaCore.Topologies.IntervalTopology(horzmesh)
quad = ClimaCore.Spaces.Quadratures.GLL{npoly + 1}()
horzspace = ClimaCore.Spaces.SpectralElementSpace1D(horztopology, quad)
hv_center_space = ClimaCore.Spaces.ExtrudedFiniteDifferenceSpace(
horzspace,
vert_center_space,
)
hv_face_space =
ClimaCore.Spaces.FaceExtrudedFiniteDifferenceSpace(hv_center_space)
coords = ClimaCore.Fields.coordinate_field(hv_center_space)
xcoords_fig = Plots.plot(coords.x)
@test xcoords_fig !== nothing
zcoords_fig = Plots.plot(coords.z)
@test zcoords_fig !== nothing
xcoords_png = joinpath(OUTPUT_DIR, "hybrid_xcoords_center_field.png")
zcoords_png = joinpath(OUTPUT_DIR, "hybrid_zcoords_center_field.png")
Plots.png(xcoords_fig, xcoords_png)
Plots.png(zcoords_fig, zcoords_png)
@test isfile(xcoords_png)
@test isfile(zcoords_png)
end
@testset "hybrid finite difference / spectral element 3D" begin
FT = Float64
xelem = 10
yelem = 5
velem = 40
npoly = 4
vertdomain = ClimaCore.Domains.IntervalDomain(
ClimaCore.Geometry.ZPoint{FT}(0),
ClimaCore.Geometry.ZPoint{FT}(1000);
boundary_tags = (:bottom, :top),
)
vertmesh = ClimaCore.Meshes.IntervalMesh(vertdomain, nelems = velem)
vert_center_space = ClimaCore.Spaces.CenterFiniteDifferenceSpace(vertmesh)
xdomain = ClimaCore.Domains.IntervalDomain(
ClimaCore.Geometry.XPoint{FT}(-500) ..
ClimaCore.Geometry.XPoint{FT}(500),
periodic = true,
)
ydomain = ClimaCore.Domains.IntervalDomain(
ClimaCore.Geometry.YPoint{FT}(-100) ..
ClimaCore.Geometry.YPoint{FT}(100),
periodic = true,
)
horzdomain = ClimaCore.Domains.RectangleDomain(xdomain, ydomain)
horzmesh = ClimaCore.Meshes.RectilinearMesh(horzdomain, xelem, yelem)
horztopology = ClimaCore.Topologies.Topology2D(horzmesh)
quad = ClimaCore.Spaces.Quadratures.GLL{npoly + 1}()
horzspace = ClimaCore.Spaces.SpectralElementSpace2D(horztopology, quad)
hv_center_space = ClimaCore.Spaces.ExtrudedFiniteDifferenceSpace(
horzspace,
vert_center_space,
)
hv_face_space =
ClimaCore.Spaces.FaceExtrudedFiniteDifferenceSpace(hv_center_space)
coords = ClimaCore.Fields.coordinate_field(hv_center_space)
xcoords_fig = Plots.plot(coords.x, slice = (:, 0.0, :))
@test xcoords_fig !== nothing
ycoords_fig = Plots.plot(coords.y, slice = (0.0, :, :))
@test ycoords_fig !== nothing
xzcoords_fig = Plots.plot(coords.z, slice = (:, 0.0, :))
@test xzcoords_fig !== nothing
yzcoords_fig = Plots.plot(coords.z, slice = (0.0, :, :))
@test yzcoords_fig !== nothing
xcoords_png = joinpath(OUTPUT_DIR, "hybrid_xcoords_center_field.png")
ycoords_png = joinpath(OUTPUT_DIR, "hybrid_ycoords_center_field.png")
xzcoords_png = joinpath(OUTPUT_DIR, "hybrid_xzcoords_center_field.png")
yzcoords_png = joinpath(OUTPUT_DIR, "hybrid_yzcoords_center_field.png")
Plots.png(xcoords_fig, xcoords_png)
Plots.png(ycoords_fig, ycoords_png)
Plots.png(xzcoords_fig, xzcoords_png)
Plots.png(yzcoords_fig, yzcoords_png)
@test isfile(xcoords_png)
@test isfile(ycoords_png)
@test isfile(xzcoords_png)
@test isfile(yzcoords_png)
end
| 32.512953
| 78
| 0.69753
|
[
"@testset \"spectral element 2D cubed-sphere\" begin\n R = 6.37122e6\n\n domain = ClimaCore.Domains.SphereDomain(R)\n mesh = ClimaCore.Meshes.EquiangularCubedSphere(domain, 6)\n grid_topology = ClimaCore.Topologies.Topology2D(mesh)\n quad = ClimaCore.Spaces.Quadratures.GLL{5}()\n space = ClimaCore.Spaces.SpectralElementSpace2D(grid_topology, quad)\n coords = ClimaCore.Fields.coordinate_field(space)\n\n u = map(coords) do coord\n u0 = 20.0\n α0 = 45.0\n ϕ = coord.lat\n λ = coord.long\n\n uu = u0 * (cosd(α0) * cosd(ϕ) + sind(α0) * cosd(λ) * sind(ϕ))\n uv = -u0 * sind(α0) * sind(λ)\n ClimaCore.Geometry.UVVector(uu, uv)\n end\n\n field_fig = Plots.plot(u.components.data.:1)\n @test field_fig !== nothing\n\n fig_png = joinpath(OUTPUT_DIR, \"2D_cubed_sphere_field.png\")\n Plots.png(field_fig, fig_png)\n @test isfile(fig_png)\nend",
"@testset \"spectral element rectangle 2D\" begin\n domain = ClimaCore.Domains.RectangleDomain(\n ClimaCore.Geometry.XPoint(0) .. ClimaCore.Geometry.XPoint(2π),\n ClimaCore.Geometry.YPoint(0) .. ClimaCore.Geometry.YPoint(2π),\n x1periodic = true,\n x2periodic = true,\n )\n\n n1, n2 = 2, 2\n Nq = 4\n mesh = ClimaCore.Meshes.RectilinearMesh(domain, n1, n2)\n grid_topology = ClimaCore.Topologies.Topology2D(mesh)\n #quad = ClimaCore.Spaces.Quadratures.GLL{Nq}()\n quad = ClimaCore.Spaces.Quadratures.ClosedUniform{Nq + 1}()\n space = ClimaCore.Spaces.SpectralElementSpace2D(grid_topology, quad)\n coords = ClimaCore.Fields.coordinate_field(space)\n\n space_fig = Plots.plot(space)\n @test space_fig !== nothing\n\n sinxy = map(coords) do coord\n cos(coord.x + coord.y)\n end\n\n field_fig = Plots.plot(sinxy)\n @test field_fig !== nothing\n\n space_png = joinpath(OUTPUT_DIR, \"2D_rectangle_space.png\")\n field_png = joinpath(OUTPUT_DIR, \"2D_rectangle_field.png\")\n Plots.png(space_fig, space_png)\n Plots.png(field_fig, field_png)\n @test isfile(space_png)\n @test isfile(field_png)\nend",
"@testset \"hybrid finite difference / spectral element 2D\" begin\n FT = Float64\n helem = 10\n velem = 40\n npoly = 4\n\n vertdomain = ClimaCore.Domains.IntervalDomain(\n ClimaCore.Geometry.ZPoint{FT}(0),\n ClimaCore.Geometry.ZPoint{FT}(1000);\n boundary_tags = (:bottom, :top),\n )\n vertmesh = ClimaCore.Meshes.IntervalMesh(vertdomain, nelems = velem)\n vert_center_space = ClimaCore.Spaces.CenterFiniteDifferenceSpace(vertmesh)\n\n horzdomain = ClimaCore.Domains.IntervalDomain(\n ClimaCore.Geometry.XPoint{FT}(-500) ..\n ClimaCore.Geometry.XPoint{FT}(500),\n periodic = true,\n )\n horzmesh = ClimaCore.Meshes.IntervalMesh(horzdomain; nelems = helem)\n horztopology = ClimaCore.Topologies.IntervalTopology(horzmesh)\n\n quad = ClimaCore.Spaces.Quadratures.GLL{npoly + 1}()\n horzspace = ClimaCore.Spaces.SpectralElementSpace1D(horztopology, quad)\n\n hv_center_space = ClimaCore.Spaces.ExtrudedFiniteDifferenceSpace(\n horzspace,\n vert_center_space,\n )\n hv_face_space =\n ClimaCore.Spaces.FaceExtrudedFiniteDifferenceSpace(hv_center_space)\n\n coords = ClimaCore.Fields.coordinate_field(hv_center_space)\n\n xcoords_fig = Plots.plot(coords.x)\n @test xcoords_fig !== nothing\n\n zcoords_fig = Plots.plot(coords.z)\n @test zcoords_fig !== nothing\n\n xcoords_png = joinpath(OUTPUT_DIR, \"hybrid_xcoords_center_field.png\")\n zcoords_png = joinpath(OUTPUT_DIR, \"hybrid_zcoords_center_field.png\")\n Plots.png(xcoords_fig, xcoords_png)\n Plots.png(zcoords_fig, zcoords_png)\n @test isfile(xcoords_png)\n @test isfile(zcoords_png)\nend",
"@testset \"hybrid finite difference / spectral element 3D\" begin\n FT = Float64\n xelem = 10\n yelem = 5\n velem = 40\n npoly = 4\n\n vertdomain = ClimaCore.Domains.IntervalDomain(\n ClimaCore.Geometry.ZPoint{FT}(0),\n ClimaCore.Geometry.ZPoint{FT}(1000);\n boundary_tags = (:bottom, :top),\n )\n vertmesh = ClimaCore.Meshes.IntervalMesh(vertdomain, nelems = velem)\n vert_center_space = ClimaCore.Spaces.CenterFiniteDifferenceSpace(vertmesh)\n\n xdomain = ClimaCore.Domains.IntervalDomain(\n ClimaCore.Geometry.XPoint{FT}(-500) ..\n ClimaCore.Geometry.XPoint{FT}(500),\n periodic = true,\n )\n ydomain = ClimaCore.Domains.IntervalDomain(\n ClimaCore.Geometry.YPoint{FT}(-100) ..\n ClimaCore.Geometry.YPoint{FT}(100),\n periodic = true,\n )\n\n horzdomain = ClimaCore.Domains.RectangleDomain(xdomain, ydomain)\n horzmesh = ClimaCore.Meshes.RectilinearMesh(horzdomain, xelem, yelem)\n horztopology = ClimaCore.Topologies.Topology2D(horzmesh)\n\n quad = ClimaCore.Spaces.Quadratures.GLL{npoly + 1}()\n horzspace = ClimaCore.Spaces.SpectralElementSpace2D(horztopology, quad)\n\n hv_center_space = ClimaCore.Spaces.ExtrudedFiniteDifferenceSpace(\n horzspace,\n vert_center_space,\n )\n hv_face_space =\n ClimaCore.Spaces.FaceExtrudedFiniteDifferenceSpace(hv_center_space)\n\n coords = ClimaCore.Fields.coordinate_field(hv_center_space)\n\n xcoords_fig = Plots.plot(coords.x, slice = (:, 0.0, :))\n @test xcoords_fig !== nothing\n\n ycoords_fig = Plots.plot(coords.y, slice = (0.0, :, :))\n @test ycoords_fig !== nothing\n\n xzcoords_fig = Plots.plot(coords.z, slice = (:, 0.0, :))\n @test xzcoords_fig !== nothing\n\n yzcoords_fig = Plots.plot(coords.z, slice = (0.0, :, :))\n @test yzcoords_fig !== nothing\n\n xcoords_png = joinpath(OUTPUT_DIR, \"hybrid_xcoords_center_field.png\")\n ycoords_png = joinpath(OUTPUT_DIR, \"hybrid_ycoords_center_field.png\")\n xzcoords_png = joinpath(OUTPUT_DIR, \"hybrid_xzcoords_center_field.png\")\n yzcoords_png = joinpath(OUTPUT_DIR, \"hybrid_yzcoords_center_field.png\")\n\n Plots.png(xcoords_fig, xcoords_png)\n Plots.png(ycoords_fig, ycoords_png)\n Plots.png(xzcoords_fig, xzcoords_png)\n Plots.png(yzcoords_fig, yzcoords_png)\n\n @test isfile(xcoords_png)\n @test isfile(ycoords_png)\n @test isfile(xzcoords_png)\n @test isfile(yzcoords_png)\nend"
] |
f748d0d5332b45ec25a7812dc2b8a3c93a7a5872
| 1,030
|
jl
|
Julia
|
test/integration/sequential/trained_weights/MNIST.WK17a_linf0.1_authors.jl
|
UnofficialJuliaMirror/MIPVerify.jl-e5e5f8be-2a6a-5994-adbb-5afbd0e30425
|
727a3fc020c03a949b501fbe4c684dca717b5b37
|
[
"MIT"
] | null | null | null |
test/integration/sequential/trained_weights/MNIST.WK17a_linf0.1_authors.jl
|
UnofficialJuliaMirror/MIPVerify.jl-e5e5f8be-2a6a-5994-adbb-5afbd0e30425
|
727a3fc020c03a949b501fbe4c684dca717b5b37
|
[
"MIT"
] | null | null | null |
test/integration/sequential/trained_weights/MNIST.WK17a_linf0.1_authors.jl
|
UnofficialJuliaMirror/MIPVerify.jl-e5e5f8be-2a6a-5994-adbb-5afbd0e30425
|
727a3fc020c03a949b501fbe4c684dca717b5b37
|
[
"MIT"
] | null | null | null |
using Test
using MIPVerify
using MIPVerify: LInfNormBoundedPerturbationFamily
using MIPVerify: get_example_network_params, read_datasets, get_image, get_label
@isdefined(TestHelpers) || include("../../../TestHelpers.jl")
@testset "MNIST.WK17a_linf0.1_authors" begin
nn = get_example_network_params("MNIST.WK17a_linf0.1_authors")
mnist = read_datasets("mnist")
test_cases = [
(1, NaN),
(2, NaN),
(9, 0.0940014207),
(248, 0),
]
for test_case in test_cases
(index, expected_objective_value) = test_case
@testset "Sample $index (1-indexed) with expected objective value $expected_objective_value" begin
input = get_image(mnist.test.images, index)
label = get_label(mnist.test.labels, index)
TestHelpers.test_find_adversarial_example(
nn, input, label+1, LInfNormBoundedPerturbationFamily(0.1), Inf, 0, expected_objective_value,
invert_target_selection=true
)
end
end
end
| 35.517241
| 110
| 0.670874
|
[
"@testset \"MNIST.WK17a_linf0.1_authors\" begin\n nn = get_example_network_params(\"MNIST.WK17a_linf0.1_authors\")\n mnist = read_datasets(\"mnist\")\n\n test_cases = [\n (1, NaN),\n (2, NaN),\n (9, 0.0940014207),\n (248, 0),\n ]\n\n for test_case in test_cases\n (index, expected_objective_value) = test_case\n @testset \"Sample $index (1-indexed) with expected objective value $expected_objective_value\" begin\n input = get_image(mnist.test.images, index)\n label = get_label(mnist.test.labels, index)\n TestHelpers.test_find_adversarial_example(\n nn, input, label+1, LInfNormBoundedPerturbationFamily(0.1), Inf, 0, expected_objective_value, \n invert_target_selection=true\n )\n end\n end\nend"
] |
f749e35e681fa741105c428224ace6bae42fd785
| 26,953
|
jl
|
Julia
|
test/periods.jl
|
JeffreySarnoff/DatesPlus.jl
|
bb263be7983efba2d2da2de40b39a915713ef04d
|
[
"MIT"
] | 1
|
2022-03-26T06:13:53.000Z
|
2022-03-26T06:13:53.000Z
|
test/periods.jl
|
JeffreySarnoff/DatesPlus.jl
|
bb263be7983efba2d2da2de40b39a915713ef04d
|
[
"MIT"
] | null | null | null |
test/periods.jl
|
JeffreySarnoff/DatesPlus.jl
|
bb263be7983efba2d2da2de40b39a915713ef04d
|
[
"MIT"
] | null | null | null |
# This file is a part of Julia. License is MIT: https://julialang.org/license
module PeriodsTest
using Dates
using Test
@testset "basic arithmetic" begin
@test -DatesPlus.Year(1) == DatesPlus.Year(-1)
@test DatesPlus.Year(1) > DatesPlus.Year(0)
@test (DatesPlus.Year(1) < DatesPlus.Year(0)) == false
@test DatesPlus.Year(1) == DatesPlus.Year(1)
@test DatesPlus.Year(1) != 1
@test DatesPlus.Year(1) + DatesPlus.Year(1) == DatesPlus.Year(2)
@test DatesPlus.Year(1) - DatesPlus.Year(1) == zero(DatesPlus.Year)
@test 1 == one(DatesPlus.Year)
@test_throws MethodError DatesPlus.Year(1) * DatesPlus.Year(1) == DatesPlus.Year(1)
t = DatesPlus.Year(1)
t2 = DatesPlus.Year(2)
@test ([t, t, t, t, t] .+ DatesPlus.Year(1)) == ([t2, t2, t2, t2, t2])
@test (DatesPlus.Year(1) .+ [t, t, t, t, t]) == ([t2, t2, t2, t2, t2])
@test ([t2, t2, t2, t2, t2] .- DatesPlus.Year(1)) == ([t, t, t, t, t])
@test_throws MethodError ([t, t, t, t, t] .* DatesPlus.Year(1)) == ([t, t, t, t, t])
@test ([t, t, t, t, t] * 1) == ([t, t, t, t, t])
@test ([t, t, t, t, t] .% t2) == ([t, t, t, t, t])
@test div.([t, t, t, t, t], DatesPlus.Year(1)) == ([1, 1, 1, 1, 1])
@test mod.([t, t, t, t, t], DatesPlus.Year(2)) == ([t, t, t, t, t])
@test [t, t, t] / t2 == [0.5, 0.5, 0.5]
@test abs(-t) == t
@test sign(t) == sign(t2) == 1
@test sign(-t) == sign(-t2) == -1
@test sign(DatesPlus.Year(0)) == 0
end
@testset "div/mod/gcd/lcm/rem" begin
@test DatesPlus.Year(10) % DatesPlus.Year(4) == DatesPlus.Year(2)
@test gcd(DatesPlus.Year(10), DatesPlus.Year(4)) == DatesPlus.Year(2)
@test lcm(DatesPlus.Year(10), DatesPlus.Year(4)) == DatesPlus.Year(20)
@test div(DatesPlus.Year(10), DatesPlus.Year(3)) == 3
@test div(DatesPlus.Year(10), DatesPlus.Year(4)) == 2
@test div(DatesPlus.Year(10), 4) == DatesPlus.Year(2)
@test DatesPlus.Year(10) / DatesPlus.Year(4) == 2.5
@test mod(DatesPlus.Year(10), DatesPlus.Year(4)) == DatesPlus.Year(2)
@test mod(DatesPlus.Year(-10), DatesPlus.Year(4)) == DatesPlus.Year(2)
@test mod(DatesPlus.Year(10), 4) == DatesPlus.Year(2)
@test mod(DatesPlus.Year(-10), 4) == DatesPlus.Year(2)
@test rem(DatesPlus.Year(10), DatesPlus.Year(4)) == DatesPlus.Year(2)
@test rem(DatesPlus.Year(-10), DatesPlus.Year(4)) == DatesPlus.Year(-2)
@test rem(DatesPlus.Year(10), 4) == DatesPlus.Year(2)
@test rem(DatesPlus.Year(-10), 4) == DatesPlus.Year(-2)
end
y = DatesPlus.Year(1)
q = DatesPlus.Quarter(1)
m = DatesPlus.Month(1)
w = DatesPlus.Week(1)
d = DatesPlus.Day(1)
h = DatesPlus.Hour(1)
mi = DatesPlus.Minute(1)
s = DatesPlus.Second(1)
ms = DatesPlus.Millisecond(1)
us = DatesPlus.Microsecond(1)
ns = DatesPlus.Nanosecond(1)
emptyperiod = ((y + d) - d) - y
@testset "Period arithmetic" begin
@test DatesPlus.Year(y) == y
@test DatesPlus.Quarter(q) == q
@test DatesPlus.Month(m) == m
@test DatesPlus.Week(w) == w
@test DatesPlus.Day(d) == d
@test DatesPlus.Hour(h) == h
@test DatesPlus.Minute(mi) == mi
@test DatesPlus.Second(s) == s
@test DatesPlus.Millisecond(ms) == ms
@test DatesPlus.Microsecond(us) == us
@test DatesPlus.Nanosecond(ns) == ns
@test DatesPlus.Year(convert(Int8, 1)) == y
@test DatesPlus.Year(convert(UInt8, 1)) == y
@test DatesPlus.Year(convert(Int16, 1)) == y
@test DatesPlus.Year(convert(UInt16, 1)) == y
@test DatesPlus.Year(convert(Int32, 1)) == y
@test DatesPlus.Year(convert(UInt32, 1)) == y
@test DatesPlus.Year(convert(Int64, 1)) == y
@test DatesPlus.Year(convert(UInt64, 1)) == y
@test DatesPlus.Year(convert(Int128, 1)) == y
@test DatesPlus.Year(convert(UInt128, 1)) == y
@test DatesPlus.Year(convert(BigInt, 1)) == y
@test DatesPlus.Year(convert(BigFloat, 1)) == y
@test DatesPlus.Year(convert(Complex, 1)) == y
@test DatesPlus.Year(convert(Rational, 1)) == y
@test DatesPlus.Year(convert(Float16, 1)) == y
@test DatesPlus.Year(convert(Float32, 1)) == y
@test DatesPlus.Year(convert(Float64, 1)) == y
@test y == y
@test m == m
@test w == w
@test d == d
@test h == h
@test mi == mi
@test s == s
@test ms == ms
@test us == us
@test ns == ns
y2 = DatesPlus.Year(2)
@test y < y2
@test y2 > y
@test y != y2
@test DatesPlus.Year(Int8(1)) == y
@test DatesPlus.Year(UInt8(1)) == y
@test DatesPlus.Year(Int16(1)) == y
@test DatesPlus.Year(UInt16(1)) == y
@test DatesPlus.Year(Int(1)) == y
@test DatesPlus.Year(UInt(1)) == y
@test DatesPlus.Year(Int64(1)) == y
@test DatesPlus.Year(UInt64(1)) == y
@test DatesPlus.Year(UInt128(1)) == y
@test DatesPlus.Year(UInt128(1)) == y
@test DatesPlus.Year(big(1)) == y
@test DatesPlus.Year(BigFloat(1)) == y
@test DatesPlus.Year(float(1)) == y
@test DatesPlus.Year(Float32(1)) == y
@test DatesPlus.Year(Rational(1)) == y
@test DatesPlus.Year(complex(1)) == y
@test_throws InexactError DatesPlus.Year(BigFloat(1.2)) == y
@test_throws InexactError DatesPlus.Year(1.2) == y
@test_throws InexactError DatesPlus.Year(Float32(1.2)) == y
@test_throws InexactError DatesPlus.Year(3//4) == y
@test_throws InexactError DatesPlus.Year(complex(1.2)) == y
@test_throws InexactError DatesPlus.Year(Float16(1.2)) == y
@test DatesPlus.Year(true) == y
@test DatesPlus.Year(false) != y
@test_throws MethodError DatesPlus.Year(:hey) == y
@test DatesPlus.Year(real(1)) == y
@test_throws InexactError DatesPlus.Year(m) == y
@test_throws MethodError DatesPlus.Year(w) == y
@test_throws MethodError DatesPlus.Year(d) == y
@test_throws MethodError DatesPlus.Year(h) == y
@test_throws MethodError DatesPlus.Year(mi) == y
@test_throws MethodError DatesPlus.Year(s) == y
@test_throws MethodError DatesPlus.Year(ms) == y
@test DatesPlus.Year(DatesPlus.Date(2013, 1, 1)) == DatesPlus.Year(2013)
@test DatesPlus.Year(DatesPlus.DateTime(2013, 1, 1)) == DatesPlus.Year(2013)
@test typeof(y + m) <: DatesPlus.CompoundPeriod
@test typeof(m + y) <: DatesPlus.CompoundPeriod
@test typeof(y + w) <: DatesPlus.CompoundPeriod
@test typeof(y + d) <: DatesPlus.CompoundPeriod
@test typeof(y + h) <: DatesPlus.CompoundPeriod
@test typeof(y + mi) <: DatesPlus.CompoundPeriod
@test typeof(y + s) <: DatesPlus.CompoundPeriod
@test typeof(y + ms) <: DatesPlus.CompoundPeriod
@test typeof(y + us) <: DatesPlus.CompoundPeriod
@test typeof(y + ns) <: DatesPlus.CompoundPeriod
@test y > m
@test d < w
@test mi < h
@test ms < h
@test ms < mi
@test us < ms
@test ns < ms
@test ns < us
@test ns < w
@test us < w
@test typemax(DatesPlus.Year) == DatesPlus.Year(typemax(Int64))
@test typemax(DatesPlus.Year) + y == DatesPlus.Year(-9223372036854775808)
@test typemin(DatesPlus.Year) == DatesPlus.Year(-9223372036854775808)
end
@testset "Period-Real arithmetic" begin
@test_throws MethodError y + 1 == DatesPlus.Year(2)
@test_throws MethodError y + true == DatesPlus.Year(2)
@test_throws InexactError y + DatesPlus.Year(1.2)
@test y + DatesPlus.Year(1f0) == DatesPlus.Year(2)
@test y * 4 == DatesPlus.Year(4)
@test y * 4f0 == DatesPlus.Year(4)
@test DatesPlus.Year(2) * 0.5 == y
@test DatesPlus.Year(2) * 3//2 == DatesPlus.Year(3)
@test_throws InexactError y * 0.5
@test_throws InexactError y * 3//4
@test (1:1:5)*Second(5) === Second(5)*(1:1:5) === Second(5):Second(5):Second(25) === (1:5)*Second(5)
@test collect(1:1:5)*Second(5) == Second(5)*collect(1:1:5) == (1:5)*Second(5)
@test (Second(2):Second(2):Second(10))/Second(2) === 1.0:1.0:5.0 == collect(Second(2):Second(2):Second(10))/Second(2)
@test (Second(2):Second(2):Second(10)) / 2 == Second(1):Second(1):Second(5) == collect(Second(2):Second(2):Second(10)) / 2
@test DatesPlus.Year(4) / 2 == DatesPlus.Year(2)
@test DatesPlus.Year(4) / 2f0 == DatesPlus.Year(2)
@test DatesPlus.Year(4) / 0.5 == DatesPlus.Year(8)
@test DatesPlus.Year(4) / 2//3 == DatesPlus.Year(6)
@test_throws InexactError DatesPlus.Year(4) / 3.0
@test_throws InexactError DatesPlus.Year(4) / 3//2
@test div(y, 2) == DatesPlus.Year(0)
@test_throws MethodError div(2, y) == DatesPlus.Year(2)
@test div(y, y) == 1
@test y*10 % DatesPlus.Year(5) == DatesPlus.Year(0)
@test_throws MethodError (y > 3) == false
@test_throws MethodError (4 < y) == false
@test 1 != y
t = [y, y, y, y, y]
@test t .+ DatesPlus.Year(2) == [DatesPlus.Year(3), DatesPlus.Year(3), DatesPlus.Year(3), DatesPlus.Year(3), DatesPlus.Year(3)]
let x = DatesPlus.Year(5), y = DatesPlus.Year(2)
@test div(x, y) * y + rem(x, y) == x
@test fld(x, y) * y + mod(x, y) == x
end
end
@testset "Associativity" begin
dt = DatesPlus.DateTime(2012, 12, 21)
test = ((((((((dt + y) - m) + w) - d) + h) - mi) + s) - ms)
@test test == dt + y - m + w - d + h - mi + s - ms
@test test == y - m + w - d + dt + h - mi + s - ms
@test test == dt - m + y - d + w - mi + h - ms + s
@test test == dt + (y - m + w - d + h - mi + s - ms)
@test test == dt + y - m + w - d + (h - mi + s - ms)
@test (dt + DatesPlus.Year(4)) + DatesPlus.Day(1) == dt + (DatesPlus.Year(4) + DatesPlus.Day(1))
@test DatesPlus.Date(2014, 1, 29) + DatesPlus.Month(1) + DatesPlus.Day(1) + DatesPlus.Month(1) + DatesPlus.Day(1) ==
DatesPlus.Date(2014, 1, 29) + DatesPlus.Day(1) + DatesPlus.Month(1) + DatesPlus.Month(1) + DatesPlus.Day(1)
@test DatesPlus.Date(2014, 1, 29) + DatesPlus.Month(1) + DatesPlus.Day(1) == DatesPlus.Date(2014, 1, 29) + DatesPlus.Day(1) + DatesPlus.Month(1)
end
@testset "traits" begin
@test DatesPlus._units(DatesPlus.Year(0)) == " years"
@test DatesPlus._units(DatesPlus.Year(1)) == " year"
@test DatesPlus._units(DatesPlus.Year(-1)) == " year"
@test DatesPlus._units(DatesPlus.Year(2)) == " years"
@test DatesPlus.string(DatesPlus.Year(0)) == "0 years"
@test DatesPlus.string(DatesPlus.Year(1)) == "1 year"
@test DatesPlus.string(DatesPlus.Year(-1)) == "-1 year"
@test DatesPlus.string(DatesPlus.Year(2)) == "2 years"
@test isfinite(DatesPlus.Year)
@test isfinite(DatesPlus.Year(0))
@test zero(DatesPlus.Year) == DatesPlus.Year(0)
@test zero(DatesPlus.Year(10)) == DatesPlus.Year(0)
@test zero(DatesPlus.Month) == DatesPlus.Month(0)
@test zero(DatesPlus.Month(10)) == DatesPlus.Month(0)
@test zero(DatesPlus.Day) == DatesPlus.Day(0)
@test zero(DatesPlus.Day(10)) == DatesPlus.Day(0)
@test zero(DatesPlus.Hour) == DatesPlus.Hour(0)
@test zero(DatesPlus.Hour(10)) == DatesPlus.Hour(0)
@test zero(DatesPlus.Minute) == DatesPlus.Minute(0)
@test zero(DatesPlus.Minute(10)) == DatesPlus.Minute(0)
@test zero(DatesPlus.Second) == DatesPlus.Second(0)
@test zero(DatesPlus.Second(10)) == DatesPlus.Second(0)
@test zero(DatesPlus.Millisecond) == DatesPlus.Millisecond(0)
@test zero(DatesPlus.Millisecond(10)) == DatesPlus.Millisecond(0)
@test DatesPlus.Year(-1) < DatesPlus.Year(1)
@test !(DatesPlus.Year(-1) > DatesPlus.Year(1))
@test DatesPlus.Year(1) == DatesPlus.Year(1)
@test DatesPlus.Year(1) != 1
@test 1 != DatesPlus.Year(1)
@test DatesPlus.Month(-1) < DatesPlus.Month(1)
@test !(DatesPlus.Month(-1) > DatesPlus.Month(1))
@test DatesPlus.Month(1) == DatesPlus.Month(1)
@test DatesPlus.Day(-1) < DatesPlus.Day(1)
@test !(DatesPlus.Day(-1) > DatesPlus.Day(1))
@test DatesPlus.Day(1) == DatesPlus.Day(1)
@test DatesPlus.Hour(-1) < DatesPlus.Hour(1)
@test !(DatesPlus.Hour(-1) > DatesPlus.Hour(1))
@test DatesPlus.Hour(1) == DatesPlus.Hour(1)
@test DatesPlus.Minute(-1) < DatesPlus.Minute(1)
@test !(DatesPlus.Minute(-1) > DatesPlus.Minute(1))
@test DatesPlus.Minute(1) == DatesPlus.Minute(1)
@test DatesPlus.Second(-1) < DatesPlus.Second(1)
@test !(DatesPlus.Second(-1) > DatesPlus.Second(1))
@test DatesPlus.Second(1) == DatesPlus.Second(1)
@test DatesPlus.Millisecond(-1) < DatesPlus.Millisecond(1)
@test !(DatesPlus.Millisecond(-1) > DatesPlus.Millisecond(1))
@test DatesPlus.Millisecond(1) == DatesPlus.Millisecond(1)
@test_throws MethodError DatesPlus.Year(1) < DatesPlus.Millisecond(1)
@test_throws MethodError DatesPlus.Millisecond(1) < DatesPlus.Year(1)
# issue #27076
@test DatesPlus.Year(1) != DatesPlus.Millisecond(1)
@test DatesPlus.Millisecond(1) != DatesPlus.Year(1)
end
struct Beat <: DatesPlus.Period
value::Int64
end
Beat(p::Period) = Beat(DatesPlus.toms(p) ÷ 86400)
@testset "comparisons with new subtypes of Period" begin
# https://en.wikipedia.org/wiki/Swatch_Internet_Time
DatesPlus.value(b::Beat) = b.value
DatesPlus.toms(b::Beat) = DatesPlus.value(b) * 86400
DatesPlus._units(b::Beat) = " beat" * (abs(DatesPlus.value(b)) == 1 ? "" : "s")
Base.promote_rule(::Type{DatesPlus.Day}, ::Type{Beat}) = DatesPlus.Millisecond
Base.convert(::Type{T}, b::Beat) where {T<:DatesPlus.Millisecond} = T(DatesPlus.toms(b))
@test Beat(1000) == DatesPlus.Day(1)
@test Beat(1) < DatesPlus.Day(1)
end
@testset "basic properties" begin
@test DatesPlus.Year("1") == y
@test DatesPlus.Quarter("1") == q
@test DatesPlus.Month("1") == m
@test DatesPlus.Week("1") == w
@test DatesPlus.Day("1") == d
@test DatesPlus.Hour("1") == h
@test DatesPlus.Minute("1") == mi
@test DatesPlus.Second("1") == s
@test DatesPlus.Millisecond("1") == ms
@test DatesPlus.Microsecond("1") == us
@test DatesPlus.Nanosecond("1") == ns
@test_throws ArgumentError DatesPlus.Year("1.0")
@test DatesPlus.Year(parse(Float64, "1.0")) == y
dt = DatesPlus.DateTime(2014)
@test typeof(DatesPlus.Year(dt)) <: DatesPlus.Year
@test typeof(DatesPlus.Quarter(dt)) <: DatesPlus.Quarter
@test typeof(DatesPlus.Month(dt)) <: DatesPlus.Month
@test typeof(DatesPlus.Week(dt)) <: DatesPlus.Week
@test typeof(DatesPlus.Day(dt)) <: DatesPlus.Day
@test typeof(DatesPlus.Hour(dt)) <: DatesPlus.Hour
@test typeof(DatesPlus.Minute(dt)) <: DatesPlus.Minute
@test typeof(DatesPlus.Second(dt)) <: DatesPlus.Second
@test typeof(DatesPlus.Millisecond(dt)) <: DatesPlus.Millisecond
end
@testset "Default values" begin
@test DatesPlus.default(DatesPlus.Year) == y
@test DatesPlus.default(DatesPlus.Quarter) == q
@test DatesPlus.default(DatesPlus.Month) == m
@test DatesPlus.default(DatesPlus.Week) == w
@test DatesPlus.default(DatesPlus.Day) == d
@test DatesPlus.default(DatesPlus.Hour) == zero(DatesPlus.Hour)
@test DatesPlus.default(DatesPlus.Minute) == zero(DatesPlus.Minute)
@test DatesPlus.default(DatesPlus.Second) == zero(DatesPlus.Second)
@test DatesPlus.default(DatesPlus.Millisecond) == zero(DatesPlus.Millisecond)
@test DatesPlus.default(DatesPlus.Microsecond) == zero(DatesPlus.Microsecond)
@test DatesPlus.default(DatesPlus.Nanosecond) == zero(DatesPlus.Nanosecond)
end
@testset "Conversions" begin
@test DatesPlus.toms(ms) == DatesPlus.value(DatesPlus.Millisecond(ms)) == 1
@test DatesPlus.toms(s) == DatesPlus.value(DatesPlus.Millisecond(s)) == 1000
@test DatesPlus.toms(mi) == DatesPlus.value(DatesPlus.Millisecond(mi)) == 60000
@test DatesPlus.toms(h) == DatesPlus.value(DatesPlus.Millisecond(h)) == 3600000
@test DatesPlus.toms(d) == DatesPlus.value(DatesPlus.Millisecond(d)) == 86400000
@test DatesPlus.toms(w) == DatesPlus.value(DatesPlus.Millisecond(w)) == 604800000
@test DatesPlus.days(ms) == DatesPlus.days(s) == DatesPlus.days(mi) == DatesPlus.days(h) == 0
@test DatesPlus.days(DatesPlus.Millisecond(86400000)) == 1
@test DatesPlus.days(DatesPlus.Second(86400)) == 1
@test DatesPlus.days(DatesPlus.Minute(1440)) == 1
@test DatesPlus.days(DatesPlus.Hour(24)) == 1
@test DatesPlus.days(d) == 1
@test DatesPlus.days(w) == 7
end
@testset "issue #9214" begin
@test 2s + (7ms + 1ms) == (2s + 7ms) + 1ms == 1ms + (2s + 7ms) == 1ms + (1s + 7ms) + 1s == 1ms + (2s + 3d + 7ms) + (-3d) == (1ms + (2s + 3d)) + (7ms - 3d) == (1ms + (2s + 3d)) - (3d - 7ms)
@test 1ms - (2s + 7ms) == -((2s + 7ms) - 1ms) == (-6ms) - 2s
@test emptyperiod == ((d + y) - y) - d == ((d + y) - d) - y
@test emptyperiod == 2y + (m - d) + ms - ((m - d) + 2y + ms)
@test emptyperiod == 0ms
@test string(emptyperiod) == "empty period"
@test string(ms + mi + d + m + y + w + h + s + 2y + m) == "3 years, 2 months, 1 week, 1 day, 1 hour, 1 minute, 1 second, 1 millisecond"
@test 8d - s == 1w + 23h + 59mi + 59s
@test h + 3mi == 63mi
@test y - m == 11m
end
@testset "compound periods and types" begin
# compound periods should avoid automatically converting period types
@test (d - h).periods == DatesPlus.Period[d, -h]
@test d - h == 23h
@test !isequal(d - h, 23h)
@test isequal(d - h, 2d - 2h - 1d + 1h)
@test sprint(show, y + m) == string(y + m)
@test convert(DatesPlus.CompoundPeriod, y) + m == y + m
@test DatesPlus.periods(convert(DatesPlus.CompoundPeriod, y)) == convert(DatesPlus.CompoundPeriod, y).periods
end
@testset "compound period simplification" begin
# reduce compound periods into the most basic form
@test DatesPlus.canonicalize(h - mi).periods == DatesPlus.Period[59mi]
@test DatesPlus.canonicalize(-h + mi).periods == DatesPlus.Period[-59mi]
@test DatesPlus.canonicalize(-y + d).periods == DatesPlus.Period[-y, d]
@test DatesPlus.canonicalize(-y + m - w + d).periods == DatesPlus.Period[-11m, -6d]
@test DatesPlus.canonicalize(-y + m - w + ms).periods == DatesPlus.Period[-11m, -6d, -23h, -59mi, -59s, -999ms]
@test DatesPlus.canonicalize(y - m + w - d + h - mi + s - ms).periods == DatesPlus.Period[11m, 6d, 59mi, 999ms]
@test DatesPlus.canonicalize(-y + m - w + d - h + mi - s + ms).periods == DatesPlus.Period[-11m, -6d, -59mi, -999ms]
@test DatesPlus.Date(2009, 2, 1) - (DatesPlus.Month(1) + DatesPlus.Day(1)) == DatesPlus.Date(2008, 12, 31)
@test_throws MethodError (DatesPlus.Month(1) + DatesPlus.Day(1)) - DatesPlus.Date(2009,2,1)
end
@testset "canonicalize Period" begin
# reduce individual Period into most basic CompoundPeriod
@test DatesPlus.canonicalize(DatesPlus.Nanosecond(1000000)) == DatesPlus.canonicalize(DatesPlus.Millisecond(1))
@test DatesPlus.canonicalize(DatesPlus.Millisecond(1000)) == DatesPlus.canonicalize(DatesPlus.Second(1))
@test DatesPlus.canonicalize(DatesPlus.Second(60)) == DatesPlus.canonicalize(DatesPlus.Minute(1))
@test DatesPlus.canonicalize(DatesPlus.Minute(60)) == DatesPlus.canonicalize(DatesPlus.Hour(1))
@test DatesPlus.canonicalize(DatesPlus.Hour(24)) == DatesPlus.canonicalize(DatesPlus.Day(1))
@test DatesPlus.canonicalize(DatesPlus.Day(7)) == DatesPlus.canonicalize(DatesPlus.Week(1))
@test DatesPlus.canonicalize(DatesPlus.Month(12)) == DatesPlus.canonicalize(DatesPlus.Year(1))
@test DatesPlus.canonicalize(DatesPlus.Minute(24*60*1 + 12*60)) == DatesPlus.canonicalize(DatesPlus.CompoundPeriod([DatesPlus.Day(1),DatesPlus.Hour(12)]))
end
@testset "unary ops and vectorized period arithmetic" begin
pa = [1y 1m 1w 1d; 1h 1mi 1s 1ms]
cpa = [1y + 1s 1m + 1s 1w + 1s 1d + 1s; 1h + 1s 1mi + 1s 2m + 1s 1s + 1ms]
@test +pa == pa == -(-pa)
@test -pa == map(-, pa)
@test 1y .+ pa == [2y 1y + 1m 1y + 1w 1y + 1d; 1y + 1h 1y + 1mi 1y + 1s 1y + 1ms]
@test (1y + 1m) .+ pa == [2y + 1m 1y + 2m 1y + 1m + 1w 1y + 1m + 1d; 1y + 1m + 1h 1y + 1m + 1mi 1y + 1m + 1s 1y + 1m + 1ms]
@test pa .+ 1y == [2y 1y + 1m 1y + 1w 1y + 1d; 1y + 1h 1y + 1mi 1y + 1s 1y + 1ms]
@test pa .+ (1y + 1m) == [2y + 1m 1y + 2m 1y + 1m + 1w 1y + 1m + 1d; 1y + 1m + 1h 1y + 1m + 1mi 1y + 1m + 1s 1y + 1m + 1ms]
@test 1y .+ cpa == [2y + 1s 1y + 1m + 1s 1y + 1w + 1s 1y + 1d + 1s; 1y + 1h + 1s 1y + 1mi + 1s 1y + 2m + 1s 1y + 1ms + 1s]
@test (1y + 1m) .+ cpa == [2y + 1m + 1s 1y + 2m + 1s 1y + 1m + 1w + 1s 1y + 1m + 1d + 1s; 1y + 1m + 1h + 1s 1y + 1m + 1mi + 1s 1y + 3m + 1s 1y + 1m + 1s + 1ms]
@test cpa .+ 1y == [2y + 1s 1y + 1m + 1s 1y + 1w + 1s 1y + 1d + 1s; 1y + 1h + 1s 1y + 1mi + 1s 1y + 2m + 1s 1y + 1ms + 1s]
@test cpa .+ (1y + 1m) == [2y + 1m + 1s 1y + 2m + 1s 1y + 1m + 1w + 1s 1y + 1m + 1d + 1s; 1y + 1m + 1h + 1s 1y + 1m + 1mi + 1s 1y + 3m + 1s 1y + 1m + 1s + 1ms]
@test 1y .+ pa == [2y 1y + 1m 1y + 1w 1y + 1d; 1y + 1h 1y + 1mi 1y + 1s 1y + 1ms]
@test (1y + 1m) .+ pa == [2y + 1m 1y + 2m 1y + 1m + 1w 1y + 1m + 1d; 1y + 1m + 1h 1y + 1m + 1mi 1y + 1m + 1s 1y + 1m + 1ms]
@test pa .+ 1y == [2y 1y + 1m 1y + 1w 1y + 1d; 1y + 1h 1y + 1mi 1y + 1s 1y + 1ms]
@test pa .+ (1y + 1m) == [2y + 1m 1y + 2m 1y + 1m + 1w 1y + 1m + 1d; 1y + 1m + 1h 1y + 1m + 1mi 1y + 1m + 1s 1y + 1m + 1ms]
@test 1y .+ cpa == [2y + 1s 1y + 1m + 1s 1y + 1w + 1s 1y + 1d + 1s; 1y + 1h + 1s 1y + 1mi + 1s 1y + 2m + 1s 1y + 1ms + 1s]
@test (1y + 1m) .+ cpa == [2y + 1m + 1s 1y + 2m + 1s 1y + 1m + 1w + 1s 1y + 1m + 1d + 1s; 1y + 1m + 1h + 1s 1y + 1m + 1mi + 1s 1y + 3m + 1s 1y + 1m + 1s + 1ms]
@test cpa .+ 1y == [2y + 1s 1y + 1m + 1s 1y + 1w + 1s 1y + 1d + 1s; 1y + 1h + 1s 1y + 1mi + 1s 1y + 2m + 1s 1y + 1ms + 1s]
@test cpa .+ (1y + 1m) == [2y + 1m + 1s 1y + 2m + 1s 1y + 1m + 1w + 1s 1y + 1m + 1d + 1s; 1y + 1m + 1h + 1s 1y + 1m + 1mi + 1s 1y + 3m + 1s 1y + 1m + 1s + 1ms]
@test 1y .- pa == [0y 1y-1m 1y-1w 1y-1d; 1y-1h 1y-1mi 1y-1s 1y-1ms]
@test (1y + 1m) .- pa == [1m 1y 1y + 1m-1w 1y + 1m-1d; 1y + 1m-1h 1y + 1m-1mi 1y + 1m-1s 1y + 1m-1ms]
@test pa .- (1y + 1m) == [-1m -1y -1y-1m + 1w -1y-1m + 1d; -1y-1m + 1h -1y-1m + 1mi -1y-1m + 1s -1y-1m + 1ms]
@test pa .- 1y == [0y 1m-1y -1y + 1w -1y + 1d; -1y + 1h -1y + 1mi -1y + 1s -1y + 1ms]
@test 1y .- cpa == [-1s 1y-1m-1s 1y-1w-1s 1y-1d-1s; 1y-1h-1s 1y-1mi-1s 1y-2m-1s 1y-1ms-1s]
@test (1y + 1m) .- cpa == [1m-1s 1y-1s 1y + 1m-1w-1s 1y + 1m-1d-1s; 1y + 1m-1h-1s 1y + 1m-1mi-1s 1y-1m-1s 1y + 1m-1s-1ms]
@test cpa .- 1y == [1s -1y + 1m + 1s -1y + 1w + 1s -1y + 1d + 1s; -1y + 1h + 1s -1y + 1mi + 1s -1y + 2m + 1s -1y + 1ms + 1s]
@test cpa .- (1y + 1m) == [-1m + 1s -1y + 1s -1y-1m + 1w + 1s -1y-1m + 1d + 1s; -1y-1m + 1h + 1s -1y-1m + 1mi + 1s -1y + 1m + 1s -1y + -1m + 1s + 1ms]
@test [1y 1m; 1w 1d] + [1h 1mi; 1s 1ms] == [1y + 1h 1m + 1mi; 1w + 1s 1d + 1ms]
@test [1y 1m; 1w 1d] - [1h 1mi; 1s 1ms] == [1y-1h 1m-1mi; 1w-1s 1d-1ms]
@test [1y 1m; 1w 1d] - [1h 1mi; 1s 1ms] - [1y-1h 1m-1mi; 1w-1s 1d-1ms] == [emptyperiod emptyperiod; emptyperiod emptyperiod]
@test [1y + 1s 1m + 1s; 1w + 1s 1d + 1s] + [1h 1mi; 1s 1ms] == [1y + 1h + 1s 1m + 1mi + 1s; 1w + 2s 1d + 1s + 1ms]
@test [1y + 1s 1m + 1s; 1w + 1s 1d + 1s] - [1h 1mi; 1s 1ms] == [1y-1h + 1s 1m-1mi + 1s; 1w 1d + 1s-1ms]
@test [1y 1m; 1w 1d] + [1h + 1s 1mi + 1s; 1m + 1s 1s + 1ms] == [1y + 1h + 1s 1m + 1mi + 1s; 1w + 1m + 1s 1d + 1s + 1ms]
@test [1y 1m; 1w 1d] - [1h + 1s 1mi + 1s; 1m + 1s 1s + 1ms] == [1y-1h-1s 1m-1mi-1s; 1w-1m-1s 1d-1s-1ms]
@test [1y + 1s 1m + 1s; 1w + 1s 1d + 1s] + [1y + 1h 1y + 1mi; 1y + 1s 1y + 1ms] == [2y + 1h + 1s 1y + 1m + 1mi + 1s; 1y + 1w + 2s 1y + 1d + 1s + 1ms]
@test [1y + 1s 1m + 1s; 1w + 1s 1d + 1s] - [1y + 1h 1y + 1mi; 1y + 1s 1y + 1ms] == [1s-1h 1m + 1s-1y-1mi; 1w-1y 1d + 1s-1y-1ms]
end
@testset "Equality and hashing between FixedPeriod types" begin
let types = (DatesPlus.Week, DatesPlus.Day, DatesPlus.Hour, DatesPlus.Minute,
DatesPlus.Second, DatesPlus.Millisecond, DatesPlus.Microsecond, DatesPlus.Nanosecond)
for i in 1:length(types), j in i:length(types), x in (0, 1, 235, -4677, 15250)
local T, U, y, z
T = types[i]
U = types[j]
y = T(x)
z = convert(U, y)
@test y == z
@test hash(y) == hash(z)
end
end
end
@testset "Equality and hashing between OtherPeriod types" begin
for x in (0, 1, 235, -4677, 15250)
local x, y, z
y = DatesPlus.Year(x)
z = convert(DatesPlus.Month, y)
@test y == z
@test hash(y) == hash(z)
y = DatesPlus.Quarter(x)
z = convert(DatesPlus.Month, y)
@test y == z
@test hash(y) == hash(z)
y = DatesPlus.Year(x)
z = convert(DatesPlus.Quarter, y)
@test y == z
@test hash(y) == hash(z)
end
end
@testset "Equality and hashing between FixedPeriod/OtherPeriod/CompoundPeriod (#37459)" begin
function test_hash_equality(x, y)
@test x == y
@test y == x
@test isequal(x, y)
@test isequal(y, x)
@test hash(x) == hash(y)
end
for FP = (DatesPlus.Week, DatesPlus.Day, DatesPlus.Hour, DatesPlus.Minute,
DatesPlus.Second, DatesPlus.Millisecond, DatesPlus.Microsecond, DatesPlus.Nanosecond)
for OP = (DatesPlus.Year, DatesPlus.Quarter, DatesPlus.Month)
test_hash_equality(FP(0), OP(0))
end
end
end
@testset "Hashing for CompoundPeriod (#37447)" begin
periods = [DatesPlus.Year(0), DatesPlus.Minute(0), DatesPlus.Second(0), DatesPlus.CompoundPeriod(),
DatesPlus.Minute(2), DatesPlus.Second(120), DatesPlus.CompoundPeriod(DatesPlus.Minute(2)),
DatesPlus.CompoundPeriod(DatesPlus.Second(120)), DatesPlus.CompoundPeriod(DatesPlus.Minute(1), DatesPlus.Second(60))]
for x = periods, y = periods
@test isequal(x,y) == (hash(x) == hash(y))
end
end
@testset "#30832" begin
@test DatesPlus.toms(DatesPlus.Second(1) + DatesPlus.Nanosecond(1)) == 1e3
@test DatesPlus.tons(DatesPlus.Second(1) + DatesPlus.Nanosecond(1)) == 1e9 + 1
@test DatesPlus.toms(DatesPlus.Second(1) + DatesPlus.Microsecond(1)) == 1e3
end
@testset "CompoundPeriod and Period isless()" begin
#tests for allowed comparisons
#FixedPeriod
@test (h - ms < h + ns) == true
@test (h + ns < h -ms) == false
@test (h < h -ms) == false
@test (h-ms < h) == true
#OtherPeriod
@test (2y-m < 25m+1y) == true
@test (2y < 25m+1y) == true
@test (25m+1y < 2y) == false
#Test combined Fixed and Other Periods
@test (1m + 1d < 1m + 1s) == false
end
@testset "Convert CompoundPeriod to Period" begin
@test convert(Month, Year(1) + Month(1)) === Month(13)
@test convert(Second, Minute(1) + Second(30)) === Second(90)
@test convert(Minute, Minute(1) + Second(60)) === Minute(2)
@test convert(Millisecond, Minute(1) + Second(30)) === Millisecond(90_000)
@test_throws InexactError convert(Minute, Minute(1) + Second(30))
@test_throws MethodError convert(Month, Minute(1) + Second(30))
@test_throws MethodError convert(Second, Month(1) + Second(30))
@test_throws MethodError convert(Period, Minute(1) + Second(30))
@test_throws MethodError convert(DatesPlus.FixedPeriod, Minute(1) + Second(30))
end
end
| 50.379439
| 192
| 0.610878
|
[
"@testset \"basic arithmetic\" begin\n @test -DatesPlus.Year(1) == DatesPlus.Year(-1)\n @test DatesPlus.Year(1) > DatesPlus.Year(0)\n @test (DatesPlus.Year(1) < DatesPlus.Year(0)) == false\n @test DatesPlus.Year(1) == DatesPlus.Year(1)\n @test DatesPlus.Year(1) != 1\n @test DatesPlus.Year(1) + DatesPlus.Year(1) == DatesPlus.Year(2)\n @test DatesPlus.Year(1) - DatesPlus.Year(1) == zero(DatesPlus.Year)\n @test 1 == one(DatesPlus.Year)\n @test_throws MethodError DatesPlus.Year(1) * DatesPlus.Year(1) == DatesPlus.Year(1)\n t = DatesPlus.Year(1)\n t2 = DatesPlus.Year(2)\n @test ([t, t, t, t, t] .+ DatesPlus.Year(1)) == ([t2, t2, t2, t2, t2])\n @test (DatesPlus.Year(1) .+ [t, t, t, t, t]) == ([t2, t2, t2, t2, t2])\n @test ([t2, t2, t2, t2, t2] .- DatesPlus.Year(1)) == ([t, t, t, t, t])\n @test_throws MethodError ([t, t, t, t, t] .* DatesPlus.Year(1)) == ([t, t, t, t, t])\n @test ([t, t, t, t, t] * 1) == ([t, t, t, t, t])\n @test ([t, t, t, t, t] .% t2) == ([t, t, t, t, t])\n @test div.([t, t, t, t, t], DatesPlus.Year(1)) == ([1, 1, 1, 1, 1])\n @test mod.([t, t, t, t, t], DatesPlus.Year(2)) == ([t, t, t, t, t])\n @test [t, t, t] / t2 == [0.5, 0.5, 0.5]\n @test abs(-t) == t\n @test sign(t) == sign(t2) == 1\n @test sign(-t) == sign(-t2) == -1\n @test sign(DatesPlus.Year(0)) == 0\nend",
"@testset \"div/mod/gcd/lcm/rem\" begin\n @test DatesPlus.Year(10) % DatesPlus.Year(4) == DatesPlus.Year(2)\n @test gcd(DatesPlus.Year(10), DatesPlus.Year(4)) == DatesPlus.Year(2)\n @test lcm(DatesPlus.Year(10), DatesPlus.Year(4)) == DatesPlus.Year(20)\n @test div(DatesPlus.Year(10), DatesPlus.Year(3)) == 3\n @test div(DatesPlus.Year(10), DatesPlus.Year(4)) == 2\n @test div(DatesPlus.Year(10), 4) == DatesPlus.Year(2)\n @test DatesPlus.Year(10) / DatesPlus.Year(4) == 2.5\n\n @test mod(DatesPlus.Year(10), DatesPlus.Year(4)) == DatesPlus.Year(2)\n @test mod(DatesPlus.Year(-10), DatesPlus.Year(4)) == DatesPlus.Year(2)\n @test mod(DatesPlus.Year(10), 4) == DatesPlus.Year(2)\n @test mod(DatesPlus.Year(-10), 4) == DatesPlus.Year(2)\n\n @test rem(DatesPlus.Year(10), DatesPlus.Year(4)) == DatesPlus.Year(2)\n @test rem(DatesPlus.Year(-10), DatesPlus.Year(4)) == DatesPlus.Year(-2)\n @test rem(DatesPlus.Year(10), 4) == DatesPlus.Year(2)\n @test rem(DatesPlus.Year(-10), 4) == DatesPlus.Year(-2)\nend",
"@testset \"Period arithmetic\" begin\n @test DatesPlus.Year(y) == y\n @test DatesPlus.Quarter(q) == q\n @test DatesPlus.Month(m) == m\n @test DatesPlus.Week(w) == w\n @test DatesPlus.Day(d) == d\n @test DatesPlus.Hour(h) == h\n @test DatesPlus.Minute(mi) == mi\n @test DatesPlus.Second(s) == s\n @test DatesPlus.Millisecond(ms) == ms\n @test DatesPlus.Microsecond(us) == us\n @test DatesPlus.Nanosecond(ns) == ns\n @test DatesPlus.Year(convert(Int8, 1)) == y\n @test DatesPlus.Year(convert(UInt8, 1)) == y\n @test DatesPlus.Year(convert(Int16, 1)) == y\n @test DatesPlus.Year(convert(UInt16, 1)) == y\n @test DatesPlus.Year(convert(Int32, 1)) == y\n @test DatesPlus.Year(convert(UInt32, 1)) == y\n @test DatesPlus.Year(convert(Int64, 1)) == y\n @test DatesPlus.Year(convert(UInt64, 1)) == y\n @test DatesPlus.Year(convert(Int128, 1)) == y\n @test DatesPlus.Year(convert(UInt128, 1)) == y\n @test DatesPlus.Year(convert(BigInt, 1)) == y\n @test DatesPlus.Year(convert(BigFloat, 1)) == y\n @test DatesPlus.Year(convert(Complex, 1)) == y\n @test DatesPlus.Year(convert(Rational, 1)) == y\n @test DatesPlus.Year(convert(Float16, 1)) == y\n @test DatesPlus.Year(convert(Float32, 1)) == y\n @test DatesPlus.Year(convert(Float64, 1)) == y\n @test y == y\n @test m == m\n @test w == w\n @test d == d\n @test h == h\n @test mi == mi\n @test s == s\n @test ms == ms\n @test us == us\n @test ns == ns\n y2 = DatesPlus.Year(2)\n @test y < y2\n @test y2 > y\n @test y != y2\n\n @test DatesPlus.Year(Int8(1)) == y\n @test DatesPlus.Year(UInt8(1)) == y\n @test DatesPlus.Year(Int16(1)) == y\n @test DatesPlus.Year(UInt16(1)) == y\n @test DatesPlus.Year(Int(1)) == y\n @test DatesPlus.Year(UInt(1)) == y\n @test DatesPlus.Year(Int64(1)) == y\n @test DatesPlus.Year(UInt64(1)) == y\n @test DatesPlus.Year(UInt128(1)) == y\n @test DatesPlus.Year(UInt128(1)) == y\n @test DatesPlus.Year(big(1)) == y\n @test DatesPlus.Year(BigFloat(1)) == y\n @test DatesPlus.Year(float(1)) == y\n @test DatesPlus.Year(Float32(1)) == y\n @test DatesPlus.Year(Rational(1)) == y\n @test DatesPlus.Year(complex(1)) == y\n @test_throws InexactError DatesPlus.Year(BigFloat(1.2)) == y\n @test_throws InexactError DatesPlus.Year(1.2) == y\n @test_throws InexactError DatesPlus.Year(Float32(1.2)) == y\n @test_throws InexactError DatesPlus.Year(3//4) == y\n @test_throws InexactError DatesPlus.Year(complex(1.2)) == y\n @test_throws InexactError DatesPlus.Year(Float16(1.2)) == y\n @test DatesPlus.Year(true) == y\n @test DatesPlus.Year(false) != y\n @test_throws MethodError DatesPlus.Year(:hey) == y\n @test DatesPlus.Year(real(1)) == y\n @test_throws InexactError DatesPlus.Year(m) == y\n @test_throws MethodError DatesPlus.Year(w) == y\n @test_throws MethodError DatesPlus.Year(d) == y\n @test_throws MethodError DatesPlus.Year(h) == y\n @test_throws MethodError DatesPlus.Year(mi) == y\n @test_throws MethodError DatesPlus.Year(s) == y\n @test_throws MethodError DatesPlus.Year(ms) == y\n @test DatesPlus.Year(DatesPlus.Date(2013, 1, 1)) == DatesPlus.Year(2013)\n @test DatesPlus.Year(DatesPlus.DateTime(2013, 1, 1)) == DatesPlus.Year(2013)\n @test typeof(y + m) <: DatesPlus.CompoundPeriod\n @test typeof(m + y) <: DatesPlus.CompoundPeriod\n @test typeof(y + w) <: DatesPlus.CompoundPeriod\n @test typeof(y + d) <: DatesPlus.CompoundPeriod\n @test typeof(y + h) <: DatesPlus.CompoundPeriod\n @test typeof(y + mi) <: DatesPlus.CompoundPeriod\n @test typeof(y + s) <: DatesPlus.CompoundPeriod\n @test typeof(y + ms) <: DatesPlus.CompoundPeriod\n @test typeof(y + us) <: DatesPlus.CompoundPeriod\n @test typeof(y + ns) <: DatesPlus.CompoundPeriod\n @test y > m\n @test d < w\n @test mi < h\n @test ms < h\n @test ms < mi\n @test us < ms\n @test ns < ms\n @test ns < us\n @test ns < w\n @test us < w\n @test typemax(DatesPlus.Year) == DatesPlus.Year(typemax(Int64))\n @test typemax(DatesPlus.Year) + y == DatesPlus.Year(-9223372036854775808)\n @test typemin(DatesPlus.Year) == DatesPlus.Year(-9223372036854775808)\nend",
"@testset \"Period-Real arithmetic\" begin\n @test_throws MethodError y + 1 == DatesPlus.Year(2)\n @test_throws MethodError y + true == DatesPlus.Year(2)\n @test_throws InexactError y + DatesPlus.Year(1.2)\n @test y + DatesPlus.Year(1f0) == DatesPlus.Year(2)\n @test y * 4 == DatesPlus.Year(4)\n @test y * 4f0 == DatesPlus.Year(4)\n @test DatesPlus.Year(2) * 0.5 == y\n @test DatesPlus.Year(2) * 3//2 == DatesPlus.Year(3)\n @test_throws InexactError y * 0.5\n @test_throws InexactError y * 3//4\n @test (1:1:5)*Second(5) === Second(5)*(1:1:5) === Second(5):Second(5):Second(25) === (1:5)*Second(5)\n @test collect(1:1:5)*Second(5) == Second(5)*collect(1:1:5) == (1:5)*Second(5)\n @test (Second(2):Second(2):Second(10))/Second(2) === 1.0:1.0:5.0 == collect(Second(2):Second(2):Second(10))/Second(2)\n @test (Second(2):Second(2):Second(10)) / 2 == Second(1):Second(1):Second(5) == collect(Second(2):Second(2):Second(10)) / 2\n @test DatesPlus.Year(4) / 2 == DatesPlus.Year(2)\n @test DatesPlus.Year(4) / 2f0 == DatesPlus.Year(2)\n @test DatesPlus.Year(4) / 0.5 == DatesPlus.Year(8)\n @test DatesPlus.Year(4) / 2//3 == DatesPlus.Year(6)\n @test_throws InexactError DatesPlus.Year(4) / 3.0\n @test_throws InexactError DatesPlus.Year(4) / 3//2\n @test div(y, 2) == DatesPlus.Year(0)\n @test_throws MethodError div(2, y) == DatesPlus.Year(2)\n @test div(y, y) == 1\n @test y*10 % DatesPlus.Year(5) == DatesPlus.Year(0)\n @test_throws MethodError (y > 3) == false\n @test_throws MethodError (4 < y) == false\n @test 1 != y\n t = [y, y, y, y, y]\n @test t .+ DatesPlus.Year(2) == [DatesPlus.Year(3), DatesPlus.Year(3), DatesPlus.Year(3), DatesPlus.Year(3), DatesPlus.Year(3)]\n\n let x = DatesPlus.Year(5), y = DatesPlus.Year(2)\n @test div(x, y) * y + rem(x, y) == x\n @test fld(x, y) * y + mod(x, y) == x\n end\nend",
"@testset \"Associativity\" begin\n dt = DatesPlus.DateTime(2012, 12, 21)\n test = ((((((((dt + y) - m) + w) - d) + h) - mi) + s) - ms)\n @test test == dt + y - m + w - d + h - mi + s - ms\n @test test == y - m + w - d + dt + h - mi + s - ms\n @test test == dt - m + y - d + w - mi + h - ms + s\n @test test == dt + (y - m + w - d + h - mi + s - ms)\n @test test == dt + y - m + w - d + (h - mi + s - ms)\n @test (dt + DatesPlus.Year(4)) + DatesPlus.Day(1) == dt + (DatesPlus.Year(4) + DatesPlus.Day(1))\n @test DatesPlus.Date(2014, 1, 29) + DatesPlus.Month(1) + DatesPlus.Day(1) + DatesPlus.Month(1) + DatesPlus.Day(1) ==\n DatesPlus.Date(2014, 1, 29) + DatesPlus.Day(1) + DatesPlus.Month(1) + DatesPlus.Month(1) + DatesPlus.Day(1)\n @test DatesPlus.Date(2014, 1, 29) + DatesPlus.Month(1) + DatesPlus.Day(1) == DatesPlus.Date(2014, 1, 29) + DatesPlus.Day(1) + DatesPlus.Month(1)\nend",
"@testset \"traits\" begin\n @test DatesPlus._units(DatesPlus.Year(0)) == \" years\"\n @test DatesPlus._units(DatesPlus.Year(1)) == \" year\"\n @test DatesPlus._units(DatesPlus.Year(-1)) == \" year\"\n @test DatesPlus._units(DatesPlus.Year(2)) == \" years\"\n @test DatesPlus.string(DatesPlus.Year(0)) == \"0 years\"\n @test DatesPlus.string(DatesPlus.Year(1)) == \"1 year\"\n @test DatesPlus.string(DatesPlus.Year(-1)) == \"-1 year\"\n @test DatesPlus.string(DatesPlus.Year(2)) == \"2 years\"\n @test isfinite(DatesPlus.Year)\n @test isfinite(DatesPlus.Year(0))\n @test zero(DatesPlus.Year) == DatesPlus.Year(0)\n @test zero(DatesPlus.Year(10)) == DatesPlus.Year(0)\n @test zero(DatesPlus.Month) == DatesPlus.Month(0)\n @test zero(DatesPlus.Month(10)) == DatesPlus.Month(0)\n @test zero(DatesPlus.Day) == DatesPlus.Day(0)\n @test zero(DatesPlus.Day(10)) == DatesPlus.Day(0)\n @test zero(DatesPlus.Hour) == DatesPlus.Hour(0)\n @test zero(DatesPlus.Hour(10)) == DatesPlus.Hour(0)\n @test zero(DatesPlus.Minute) == DatesPlus.Minute(0)\n @test zero(DatesPlus.Minute(10)) == DatesPlus.Minute(0)\n @test zero(DatesPlus.Second) == DatesPlus.Second(0)\n @test zero(DatesPlus.Second(10)) == DatesPlus.Second(0)\n @test zero(DatesPlus.Millisecond) == DatesPlus.Millisecond(0)\n @test zero(DatesPlus.Millisecond(10)) == DatesPlus.Millisecond(0)\n @test DatesPlus.Year(-1) < DatesPlus.Year(1)\n @test !(DatesPlus.Year(-1) > DatesPlus.Year(1))\n @test DatesPlus.Year(1) == DatesPlus.Year(1)\n @test DatesPlus.Year(1) != 1\n @test 1 != DatesPlus.Year(1)\n @test DatesPlus.Month(-1) < DatesPlus.Month(1)\n @test !(DatesPlus.Month(-1) > DatesPlus.Month(1))\n @test DatesPlus.Month(1) == DatesPlus.Month(1)\n @test DatesPlus.Day(-1) < DatesPlus.Day(1)\n @test !(DatesPlus.Day(-1) > DatesPlus.Day(1))\n @test DatesPlus.Day(1) == DatesPlus.Day(1)\n @test DatesPlus.Hour(-1) < DatesPlus.Hour(1)\n @test !(DatesPlus.Hour(-1) > DatesPlus.Hour(1))\n @test DatesPlus.Hour(1) == DatesPlus.Hour(1)\n @test DatesPlus.Minute(-1) < DatesPlus.Minute(1)\n @test !(DatesPlus.Minute(-1) > DatesPlus.Minute(1))\n @test DatesPlus.Minute(1) == DatesPlus.Minute(1)\n @test DatesPlus.Second(-1) < DatesPlus.Second(1)\n @test !(DatesPlus.Second(-1) > DatesPlus.Second(1))\n @test DatesPlus.Second(1) == DatesPlus.Second(1)\n @test DatesPlus.Millisecond(-1) < DatesPlus.Millisecond(1)\n @test !(DatesPlus.Millisecond(-1) > DatesPlus.Millisecond(1))\n @test DatesPlus.Millisecond(1) == DatesPlus.Millisecond(1)\n @test_throws MethodError DatesPlus.Year(1) < DatesPlus.Millisecond(1)\n @test_throws MethodError DatesPlus.Millisecond(1) < DatesPlus.Year(1)\n\n # issue #27076\n @test DatesPlus.Year(1) != DatesPlus.Millisecond(1)\n @test DatesPlus.Millisecond(1) != DatesPlus.Year(1)\nend",
"@testset \"comparisons with new subtypes of Period\" begin\n # https://en.wikipedia.org/wiki/Swatch_Internet_Time\n DatesPlus.value(b::Beat) = b.value\n DatesPlus.toms(b::Beat) = DatesPlus.value(b) * 86400\n DatesPlus._units(b::Beat) = \" beat\" * (abs(DatesPlus.value(b)) == 1 ? \"\" : \"s\")\n Base.promote_rule(::Type{DatesPlus.Day}, ::Type{Beat}) = DatesPlus.Millisecond\n Base.convert(::Type{T}, b::Beat) where {T<:DatesPlus.Millisecond} = T(DatesPlus.toms(b))\n\n @test Beat(1000) == DatesPlus.Day(1)\n @test Beat(1) < DatesPlus.Day(1)\nend",
"@testset \"basic properties\" begin\n @test DatesPlus.Year(\"1\") == y\n @test DatesPlus.Quarter(\"1\") == q\n @test DatesPlus.Month(\"1\") == m\n @test DatesPlus.Week(\"1\") == w\n @test DatesPlus.Day(\"1\") == d\n @test DatesPlus.Hour(\"1\") == h\n @test DatesPlus.Minute(\"1\") == mi\n @test DatesPlus.Second(\"1\") == s\n @test DatesPlus.Millisecond(\"1\") == ms\n @test DatesPlus.Microsecond(\"1\") == us\n @test DatesPlus.Nanosecond(\"1\") == ns\n @test_throws ArgumentError DatesPlus.Year(\"1.0\")\n @test DatesPlus.Year(parse(Float64, \"1.0\")) == y\n\n dt = DatesPlus.DateTime(2014)\n @test typeof(DatesPlus.Year(dt)) <: DatesPlus.Year\n @test typeof(DatesPlus.Quarter(dt)) <: DatesPlus.Quarter\n @test typeof(DatesPlus.Month(dt)) <: DatesPlus.Month\n @test typeof(DatesPlus.Week(dt)) <: DatesPlus.Week\n @test typeof(DatesPlus.Day(dt)) <: DatesPlus.Day\n @test typeof(DatesPlus.Hour(dt)) <: DatesPlus.Hour\n @test typeof(DatesPlus.Minute(dt)) <: DatesPlus.Minute\n @test typeof(DatesPlus.Second(dt)) <: DatesPlus.Second\n @test typeof(DatesPlus.Millisecond(dt)) <: DatesPlus.Millisecond\nend",
"@testset \"Default values\" begin\n @test DatesPlus.default(DatesPlus.Year) == y\n @test DatesPlus.default(DatesPlus.Quarter) == q\n @test DatesPlus.default(DatesPlus.Month) == m\n @test DatesPlus.default(DatesPlus.Week) == w\n @test DatesPlus.default(DatesPlus.Day) == d\n @test DatesPlus.default(DatesPlus.Hour) == zero(DatesPlus.Hour)\n @test DatesPlus.default(DatesPlus.Minute) == zero(DatesPlus.Minute)\n @test DatesPlus.default(DatesPlus.Second) == zero(DatesPlus.Second)\n @test DatesPlus.default(DatesPlus.Millisecond) == zero(DatesPlus.Millisecond)\n @test DatesPlus.default(DatesPlus.Microsecond) == zero(DatesPlus.Microsecond)\n @test DatesPlus.default(DatesPlus.Nanosecond) == zero(DatesPlus.Nanosecond)\nend",
"@testset \"Conversions\" begin\n @test DatesPlus.toms(ms) == DatesPlus.value(DatesPlus.Millisecond(ms)) == 1\n @test DatesPlus.toms(s) == DatesPlus.value(DatesPlus.Millisecond(s)) == 1000\n @test DatesPlus.toms(mi) == DatesPlus.value(DatesPlus.Millisecond(mi)) == 60000\n @test DatesPlus.toms(h) == DatesPlus.value(DatesPlus.Millisecond(h)) == 3600000\n @test DatesPlus.toms(d) == DatesPlus.value(DatesPlus.Millisecond(d)) == 86400000\n @test DatesPlus.toms(w) == DatesPlus.value(DatesPlus.Millisecond(w)) == 604800000\n\n @test DatesPlus.days(ms) == DatesPlus.days(s) == DatesPlus.days(mi) == DatesPlus.days(h) == 0\n @test DatesPlus.days(DatesPlus.Millisecond(86400000)) == 1\n @test DatesPlus.days(DatesPlus.Second(86400)) == 1\n @test DatesPlus.days(DatesPlus.Minute(1440)) == 1\n @test DatesPlus.days(DatesPlus.Hour(24)) == 1\n @test DatesPlus.days(d) == 1\n @test DatesPlus.days(w) == 7\nend",
"@testset \"issue #9214\" begin\n @test 2s + (7ms + 1ms) == (2s + 7ms) + 1ms == 1ms + (2s + 7ms) == 1ms + (1s + 7ms) + 1s == 1ms + (2s + 3d + 7ms) + (-3d) == (1ms + (2s + 3d)) + (7ms - 3d) == (1ms + (2s + 3d)) - (3d - 7ms)\n @test 1ms - (2s + 7ms) == -((2s + 7ms) - 1ms) == (-6ms) - 2s\n @test emptyperiod == ((d + y) - y) - d == ((d + y) - d) - y\n @test emptyperiod == 2y + (m - d) + ms - ((m - d) + 2y + ms)\n @test emptyperiod == 0ms\n @test string(emptyperiod) == \"empty period\"\n @test string(ms + mi + d + m + y + w + h + s + 2y + m) == \"3 years, 2 months, 1 week, 1 day, 1 hour, 1 minute, 1 second, 1 millisecond\"\n @test 8d - s == 1w + 23h + 59mi + 59s\n @test h + 3mi == 63mi\n @test y - m == 11m\nend",
"@testset \"compound periods and types\" begin\n # compound periods should avoid automatically converting period types\n @test (d - h).periods == DatesPlus.Period[d, -h]\n @test d - h == 23h\n @test !isequal(d - h, 23h)\n @test isequal(d - h, 2d - 2h - 1d + 1h)\n @test sprint(show, y + m) == string(y + m)\n @test convert(DatesPlus.CompoundPeriod, y) + m == y + m\n @test DatesPlus.periods(convert(DatesPlus.CompoundPeriod, y)) == convert(DatesPlus.CompoundPeriod, y).periods\nend",
"@testset \"compound period simplification\" begin\n # reduce compound periods into the most basic form\n @test DatesPlus.canonicalize(h - mi).periods == DatesPlus.Period[59mi]\n @test DatesPlus.canonicalize(-h + mi).periods == DatesPlus.Period[-59mi]\n @test DatesPlus.canonicalize(-y + d).periods == DatesPlus.Period[-y, d]\n @test DatesPlus.canonicalize(-y + m - w + d).periods == DatesPlus.Period[-11m, -6d]\n @test DatesPlus.canonicalize(-y + m - w + ms).periods == DatesPlus.Period[-11m, -6d, -23h, -59mi, -59s, -999ms]\n @test DatesPlus.canonicalize(y - m + w - d + h - mi + s - ms).periods == DatesPlus.Period[11m, 6d, 59mi, 999ms]\n @test DatesPlus.canonicalize(-y + m - w + d - h + mi - s + ms).periods == DatesPlus.Period[-11m, -6d, -59mi, -999ms]\n\n @test DatesPlus.Date(2009, 2, 1) - (DatesPlus.Month(1) + DatesPlus.Day(1)) == DatesPlus.Date(2008, 12, 31)\n @test_throws MethodError (DatesPlus.Month(1) + DatesPlus.Day(1)) - DatesPlus.Date(2009,2,1)\nend",
"@testset \"canonicalize Period\" begin\n # reduce individual Period into most basic CompoundPeriod\n @test DatesPlus.canonicalize(DatesPlus.Nanosecond(1000000)) == DatesPlus.canonicalize(DatesPlus.Millisecond(1))\n @test DatesPlus.canonicalize(DatesPlus.Millisecond(1000)) == DatesPlus.canonicalize(DatesPlus.Second(1))\n @test DatesPlus.canonicalize(DatesPlus.Second(60)) == DatesPlus.canonicalize(DatesPlus.Minute(1))\n @test DatesPlus.canonicalize(DatesPlus.Minute(60)) == DatesPlus.canonicalize(DatesPlus.Hour(1))\n @test DatesPlus.canonicalize(DatesPlus.Hour(24)) == DatesPlus.canonicalize(DatesPlus.Day(1))\n @test DatesPlus.canonicalize(DatesPlus.Day(7)) == DatesPlus.canonicalize(DatesPlus.Week(1))\n @test DatesPlus.canonicalize(DatesPlus.Month(12)) == DatesPlus.canonicalize(DatesPlus.Year(1))\n @test DatesPlus.canonicalize(DatesPlus.Minute(24*60*1 + 12*60)) == DatesPlus.canonicalize(DatesPlus.CompoundPeriod([DatesPlus.Day(1),DatesPlus.Hour(12)]))\nend",
"@testset \"unary ops and vectorized period arithmetic\" begin\n pa = [1y 1m 1w 1d; 1h 1mi 1s 1ms]\n cpa = [1y + 1s 1m + 1s 1w + 1s 1d + 1s; 1h + 1s 1mi + 1s 2m + 1s 1s + 1ms]\n\n @test +pa == pa == -(-pa)\n @test -pa == map(-, pa)\n @test 1y .+ pa == [2y 1y + 1m 1y + 1w 1y + 1d; 1y + 1h 1y + 1mi 1y + 1s 1y + 1ms]\n @test (1y + 1m) .+ pa == [2y + 1m 1y + 2m 1y + 1m + 1w 1y + 1m + 1d; 1y + 1m + 1h 1y + 1m + 1mi 1y + 1m + 1s 1y + 1m + 1ms]\n @test pa .+ 1y == [2y 1y + 1m 1y + 1w 1y + 1d; 1y + 1h 1y + 1mi 1y + 1s 1y + 1ms]\n @test pa .+ (1y + 1m) == [2y + 1m 1y + 2m 1y + 1m + 1w 1y + 1m + 1d; 1y + 1m + 1h 1y + 1m + 1mi 1y + 1m + 1s 1y + 1m + 1ms]\n\n @test 1y .+ cpa == [2y + 1s 1y + 1m + 1s 1y + 1w + 1s 1y + 1d + 1s; 1y + 1h + 1s 1y + 1mi + 1s 1y + 2m + 1s 1y + 1ms + 1s]\n @test (1y + 1m) .+ cpa == [2y + 1m + 1s 1y + 2m + 1s 1y + 1m + 1w + 1s 1y + 1m + 1d + 1s; 1y + 1m + 1h + 1s 1y + 1m + 1mi + 1s 1y + 3m + 1s 1y + 1m + 1s + 1ms]\n @test cpa .+ 1y == [2y + 1s 1y + 1m + 1s 1y + 1w + 1s 1y + 1d + 1s; 1y + 1h + 1s 1y + 1mi + 1s 1y + 2m + 1s 1y + 1ms + 1s]\n @test cpa .+ (1y + 1m) == [2y + 1m + 1s 1y + 2m + 1s 1y + 1m + 1w + 1s 1y + 1m + 1d + 1s; 1y + 1m + 1h + 1s 1y + 1m + 1mi + 1s 1y + 3m + 1s 1y + 1m + 1s + 1ms]\n\n @test 1y .+ pa == [2y 1y + 1m 1y + 1w 1y + 1d; 1y + 1h 1y + 1mi 1y + 1s 1y + 1ms]\n @test (1y + 1m) .+ pa == [2y + 1m 1y + 2m 1y + 1m + 1w 1y + 1m + 1d; 1y + 1m + 1h 1y + 1m + 1mi 1y + 1m + 1s 1y + 1m + 1ms]\n @test pa .+ 1y == [2y 1y + 1m 1y + 1w 1y + 1d; 1y + 1h 1y + 1mi 1y + 1s 1y + 1ms]\n @test pa .+ (1y + 1m) == [2y + 1m 1y + 2m 1y + 1m + 1w 1y + 1m + 1d; 1y + 1m + 1h 1y + 1m + 1mi 1y + 1m + 1s 1y + 1m + 1ms]\n\n @test 1y .+ cpa == [2y + 1s 1y + 1m + 1s 1y + 1w + 1s 1y + 1d + 1s; 1y + 1h + 1s 1y + 1mi + 1s 1y + 2m + 1s 1y + 1ms + 1s]\n @test (1y + 1m) .+ cpa == [2y + 1m + 1s 1y + 2m + 1s 1y + 1m + 1w + 1s 1y + 1m + 1d + 1s; 1y + 1m + 1h + 1s 1y + 1m + 1mi + 1s 1y + 3m + 1s 1y + 1m + 1s + 1ms]\n @test cpa .+ 1y == [2y + 1s 1y + 1m + 1s 1y + 1w + 1s 1y + 1d + 1s; 1y + 1h + 1s 1y + 1mi + 1s 1y + 2m + 1s 1y + 1ms + 1s]\n @test cpa .+ (1y + 1m) == [2y + 1m + 1s 1y + 2m + 1s 1y + 1m + 1w + 1s 1y + 1m + 1d + 1s; 1y + 1m + 1h + 1s 1y + 1m + 1mi + 1s 1y + 3m + 1s 1y + 1m + 1s + 1ms]\n\n @test 1y .- pa == [0y 1y-1m 1y-1w 1y-1d; 1y-1h 1y-1mi 1y-1s 1y-1ms]\n @test (1y + 1m) .- pa == [1m 1y 1y + 1m-1w 1y + 1m-1d; 1y + 1m-1h 1y + 1m-1mi 1y + 1m-1s 1y + 1m-1ms]\n @test pa .- (1y + 1m) == [-1m -1y -1y-1m + 1w -1y-1m + 1d; -1y-1m + 1h -1y-1m + 1mi -1y-1m + 1s -1y-1m + 1ms]\n @test pa .- 1y == [0y 1m-1y -1y + 1w -1y + 1d; -1y + 1h -1y + 1mi -1y + 1s -1y + 1ms]\n\n @test 1y .- cpa == [-1s 1y-1m-1s 1y-1w-1s 1y-1d-1s; 1y-1h-1s 1y-1mi-1s 1y-2m-1s 1y-1ms-1s]\n @test (1y + 1m) .- cpa == [1m-1s 1y-1s 1y + 1m-1w-1s 1y + 1m-1d-1s; 1y + 1m-1h-1s 1y + 1m-1mi-1s 1y-1m-1s 1y + 1m-1s-1ms]\n @test cpa .- 1y == [1s -1y + 1m + 1s -1y + 1w + 1s -1y + 1d + 1s; -1y + 1h + 1s -1y + 1mi + 1s -1y + 2m + 1s -1y + 1ms + 1s]\n @test cpa .- (1y + 1m) == [-1m + 1s -1y + 1s -1y-1m + 1w + 1s -1y-1m + 1d + 1s; -1y-1m + 1h + 1s -1y-1m + 1mi + 1s -1y + 1m + 1s -1y + -1m + 1s + 1ms]\n\n @test [1y 1m; 1w 1d] + [1h 1mi; 1s 1ms] == [1y + 1h 1m + 1mi; 1w + 1s 1d + 1ms]\n @test [1y 1m; 1w 1d] - [1h 1mi; 1s 1ms] == [1y-1h 1m-1mi; 1w-1s 1d-1ms]\n @test [1y 1m; 1w 1d] - [1h 1mi; 1s 1ms] - [1y-1h 1m-1mi; 1w-1s 1d-1ms] == [emptyperiod emptyperiod; emptyperiod emptyperiod]\n\n @test [1y + 1s 1m + 1s; 1w + 1s 1d + 1s] + [1h 1mi; 1s 1ms] == [1y + 1h + 1s 1m + 1mi + 1s; 1w + 2s 1d + 1s + 1ms]\n @test [1y + 1s 1m + 1s; 1w + 1s 1d + 1s] - [1h 1mi; 1s 1ms] == [1y-1h + 1s 1m-1mi + 1s; 1w 1d + 1s-1ms]\n\n @test [1y 1m; 1w 1d] + [1h + 1s 1mi + 1s; 1m + 1s 1s + 1ms] == [1y + 1h + 1s 1m + 1mi + 1s; 1w + 1m + 1s 1d + 1s + 1ms]\n @test [1y 1m; 1w 1d] - [1h + 1s 1mi + 1s; 1m + 1s 1s + 1ms] == [1y-1h-1s 1m-1mi-1s; 1w-1m-1s 1d-1s-1ms]\n\n @test [1y + 1s 1m + 1s; 1w + 1s 1d + 1s] + [1y + 1h 1y + 1mi; 1y + 1s 1y + 1ms] == [2y + 1h + 1s 1y + 1m + 1mi + 1s; 1y + 1w + 2s 1y + 1d + 1s + 1ms]\n @test [1y + 1s 1m + 1s; 1w + 1s 1d + 1s] - [1y + 1h 1y + 1mi; 1y + 1s 1y + 1ms] == [1s-1h 1m + 1s-1y-1mi; 1w-1y 1d + 1s-1y-1ms]\nend",
"@testset \"Equality and hashing between FixedPeriod types\" begin\n let types = (DatesPlus.Week, DatesPlus.Day, DatesPlus.Hour, DatesPlus.Minute,\n DatesPlus.Second, DatesPlus.Millisecond, DatesPlus.Microsecond, DatesPlus.Nanosecond)\n for i in 1:length(types), j in i:length(types), x in (0, 1, 235, -4677, 15250)\n local T, U, y, z\n T = types[i]\n U = types[j]\n y = T(x)\n z = convert(U, y)\n @test y == z\n @test hash(y) == hash(z)\n end\n end\nend",
"@testset \"Equality and hashing between OtherPeriod types\" begin\n for x in (0, 1, 235, -4677, 15250)\n local x, y, z\n y = DatesPlus.Year(x)\n z = convert(DatesPlus.Month, y)\n @test y == z\n @test hash(y) == hash(z)\n\n y = DatesPlus.Quarter(x)\n z = convert(DatesPlus.Month, y)\n @test y == z\n @test hash(y) == hash(z)\n\n y = DatesPlus.Year(x)\n z = convert(DatesPlus.Quarter, y)\n @test y == z\n @test hash(y) == hash(z)\n end\nend",
"@testset \"Equality and hashing between FixedPeriod/OtherPeriod/CompoundPeriod (#37459)\" begin\n function test_hash_equality(x, y)\n @test x == y\n @test y == x\n @test isequal(x, y)\n @test isequal(y, x)\n @test hash(x) == hash(y)\n end\n for FP = (DatesPlus.Week, DatesPlus.Day, DatesPlus.Hour, DatesPlus.Minute,\n DatesPlus.Second, DatesPlus.Millisecond, DatesPlus.Microsecond, DatesPlus.Nanosecond)\n for OP = (DatesPlus.Year, DatesPlus.Quarter, DatesPlus.Month)\n test_hash_equality(FP(0), OP(0))\n end\n end\nend",
"@testset \"Hashing for CompoundPeriod (#37447)\" begin\n periods = [DatesPlus.Year(0), DatesPlus.Minute(0), DatesPlus.Second(0), DatesPlus.CompoundPeriod(),\n DatesPlus.Minute(2), DatesPlus.Second(120), DatesPlus.CompoundPeriod(DatesPlus.Minute(2)),\n DatesPlus.CompoundPeriod(DatesPlus.Second(120)), DatesPlus.CompoundPeriod(DatesPlus.Minute(1), DatesPlus.Second(60))]\n for x = periods, y = periods\n @test isequal(x,y) == (hash(x) == hash(y))\n end\nend",
"@testset \"#30832\" begin\n @test DatesPlus.toms(DatesPlus.Second(1) + DatesPlus.Nanosecond(1)) == 1e3\n @test DatesPlus.tons(DatesPlus.Second(1) + DatesPlus.Nanosecond(1)) == 1e9 + 1\n @test DatesPlus.toms(DatesPlus.Second(1) + DatesPlus.Microsecond(1)) == 1e3\nend",
"@testset \"CompoundPeriod and Period isless()\" begin\n #tests for allowed comparisons\n #FixedPeriod\n @test (h - ms < h + ns) == true\n @test (h + ns < h -ms) == false\n @test (h < h -ms) == false\n @test (h-ms < h) == true\n #OtherPeriod\n @test (2y-m < 25m+1y) == true\n @test (2y < 25m+1y) == true\n @test (25m+1y < 2y) == false\n #Test combined Fixed and Other Periods\n @test (1m + 1d < 1m + 1s) == false\nend",
"@testset \"Convert CompoundPeriod to Period\" begin\n @test convert(Month, Year(1) + Month(1)) === Month(13)\n @test convert(Second, Minute(1) + Second(30)) === Second(90)\n @test convert(Minute, Minute(1) + Second(60)) === Minute(2)\n @test convert(Millisecond, Minute(1) + Second(30)) === Millisecond(90_000)\n @test_throws InexactError convert(Minute, Minute(1) + Second(30))\n @test_throws MethodError convert(Month, Minute(1) + Second(30))\n @test_throws MethodError convert(Second, Month(1) + Second(30))\n @test_throws MethodError convert(Period, Minute(1) + Second(30))\n @test_throws MethodError convert(DatesPlus.FixedPeriod, Minute(1) + Second(30))\nend"
] |
f74d5b33bbb3f7745f0f41c3edfe083921144872
| 6,805
|
jl
|
Julia
|
src/MINLPTests.jl
|
jump-dev/MINLPTests.jl
|
9dc2b751de7470dcb4d9a726e11339a8e0bf745c
|
[
"MIT"
] | 3
|
2020-07-04T22:02:43.000Z
|
2021-04-16T15:49:34.000Z
|
src/MINLPTests.jl
|
jump-dev/MINLPTests.jl
|
9dc2b751de7470dcb4d9a726e11339a8e0bf745c
|
[
"MIT"
] | 14
|
2020-06-14T16:44:08.000Z
|
2022-03-27T01:32:27.000Z
|
src/MINLPTests.jl
|
jump-dev/MINLPTests.jl
|
9dc2b751de7470dcb4d9a726e11339a8e0bf745c
|
[
"MIT"
] | 2
|
2020-07-24T16:22:09.000Z
|
2020-07-25T02:23:53.000Z
|
module MINLPTests
using JuMP
using Test
###
### Default tolerances that are used in the tests.
###
# Absolute tolerance when checking the objective value.
const OPT_TOL = 1e-6
# Absolute tolerance when checking the primal solution value.
const PRIMAL_TOL = 1e-6
# Absolue tolerance when checking the dual solution value.
const DUAL_TOL = 1e-6
###
### Default expected status codes for different types of problems and solvers.
###
# We only distinguish between feasible and infeasible problems now.
@enum ProblemTypeCode FEASIBLE_PROBLEM INFEASIBLE_PROBLEM
# Target status codes for local solvers:
const TERMINATION_TARGET_LOCAL = Dict(
FEASIBLE_PROBLEM => JuMP.MOI.LOCALLY_SOLVED,
INFEASIBLE_PROBLEM => JuMP.MOI.LOCALLY_INFEASIBLE,
)
const PRIMAL_TARGET_LOCAL = Dict(
FEASIBLE_PROBLEM => JuMP.MOI.FEASIBLE_POINT,
INFEASIBLE_PROBLEM => JuMP.MOI.INFEASIBLE_POINT,
)
# Target status codes for global solvers:
const TERMINATION_TARGET_GLOBAL = Dict(
FEASIBLE_PROBLEM => JuMP.MOI.OPTIMAL,
INFEASIBLE_PROBLEM => JuMP.MOI.INFEASIBLE,
)
const PRIMAL_TARGET_GLOBAL = Dict(
FEASIBLE_PROBLEM => JuMP.MOI.FEASIBLE_POINT,
INFEASIBLE_PROBLEM => JuMP.MOI.NO_SOLUTION,
)
###
### Helper functions for the tests.
###
function check_status(
model,
problem_type::ProblemTypeCode,
termination_target = TERMINATION_TARGET_LOCAL,
primal_target = PRIMAL_TARGET_LOCAL,
)
@test JuMP.termination_status(model) == termination_target[problem_type]
@test JuMP.primal_status(model) == primal_target[problem_type]
end
function check_objective(model, solution; tol = OPT_TOL)
if !isnan(tol)
@test isapprox(JuMP.objective_value(model), solution, atol = tol)
end
end
function check_solution(variables, solutions; tol = PRIMAL_TOL)
if !isnan(tol)
@assert length(variables) == length(solutions)
for (variable, solution) in zip(variables, solutions)
@test isapprox(JuMP.value(variable), solution, atol = tol)
end
end
end
function check_dual(constraints, solutions; tol = DUAL_TOL)
if !isnan(tol)
@assert length(constraints) == length(solutions)
for (constraint, solution) in zip(constraints, solutions)
@test isapprox(JuMP.dual(constraint), solution, atol = tol)
end
end
end
###
### Loop through and include every model function.
###
for directory in ["nlp", "nlp-cvx", "nlp-mi"]
files = readdir(joinpath(@__DIR__, directory))
for file_name in filter(f -> endswith(f, ".jl"), files)
include(joinpath(@__DIR__, directory, file_name))
end
end
"""
test_directory(
directory,
optimizer;
debug::Bool = false,
exclude = String[],
include = String[],
objective_tol = OPT_TOL,
primal_tol = PRIMAL_TOL,
dual_tol = DUAL_TOL,
termination_target = TERMINATION_TARGET_LOCAL,
primal_target = PRIMAL_TARGET_LOCAL,
)
Test all of the files in `directory` using `optimizer`.
If `debug`, print the name of the file befor running it.
Use `exclude` and `include` to run a subset of the files in a directory.
Use the remaining args to control tolerances and status targets.
## Example
Test all but nlp_001_010:
```julia
test_directory("nlp", optimizer; exclude = ["001_010"])
```
Test only nlp_001_010:
```julia
test_directory("nlp", optimizer; include = ["001_010"])
```
"""
function test_directory(
directory,
optimizer;
debug::Bool = false,
exclude = String[],
include = String[],
objective_tol = OPT_TOL,
primal_tol = PRIMAL_TOL,
dual_tol = DUAL_TOL,
termination_target = TERMINATION_TARGET_LOCAL,
primal_target = PRIMAL_TARGET_LOCAL,
)
@testset "$(directory)" begin
models = _list_of_models(directory, exclude, include)
@testset "$(model_name)" for model_name in models
if debug
println("Running $(model_name)")
end
getfield(MINLPTests, model_name)(
optimizer,
objective_tol,
primal_tol,
dual_tol,
termination_target,
primal_target,
)
end
end
end
function _list_of_models(
directory,
exclude::Vector{String},
include::Vector{String},
)
dir = replace(directory, "-" => "_")
if length(include) > 0
return [Symbol("$(dir)_$(i)") for i in include]
else
models = Symbol[]
for file in readdir(joinpath(@__DIR__, directory))
if !endswith(file, ".jl")
continue
end
file = replace(file, ".jl" => "")
if file in exclude
continue
end
push!(models, Symbol("$(dir)_$(file)"))
end
return models
end
end
###
### Helper functions to test a subset of models.
###
function test_nlp(
optimizer;
debug::Bool = false,
exclude = String[],
objective_tol = OPT_TOL,
primal_tol = PRIMAL_TOL,
dual_tol = DUAL_TOL,
termination_target = TERMINATION_TARGET_LOCAL,
primal_target = PRIMAL_TARGET_LOCAL,
)
return test_directory(
"nlp",
optimizer;
debug = debug,
exclude = exclude,
objective_tol = objective_tol,
primal_tol = primal_tol,
dual_tol = dual_tol,
termination_target = termination_target,
primal_target = primal_target,
)
end
function test_nlp_cvx(
optimizer;
debug::Bool = false,
exclude = String[],
objective_tol = OPT_TOL,
primal_tol = PRIMAL_TOL,
dual_tol = DUAL_TOL,
termination_target = TERMINATION_TARGET_LOCAL,
primal_target = PRIMAL_TARGET_LOCAL,
)
return test_directory(
"nlp-cvx",
optimizer;
debug = debug,
exclude = exclude,
objective_tol = objective_tol,
primal_tol = primal_tol,
dual_tol = dual_tol,
termination_target = termination_target,
primal_target = primal_target,
)
end
function test_nlp_mi(
optimizer;
debug::Bool = false,
exclude = String[],
objective_tol = OPT_TOL,
primal_tol = PRIMAL_TOL,
dual_tol = DUAL_TOL,
termination_target = TERMINATION_TARGET_LOCAL,
primal_target = PRIMAL_TARGET_LOCAL,
)
return test_directory(
"nlp-mi",
optimizer;
debug = debug,
exclude = exclude,
objective_tol = objective_tol,
primal_tol = primal_tol,
dual_tol = dual_tol,
termination_target = termination_target,
primal_target = primal_target,
)
end
### Tests that haven't been updated.
include("nlp-mi-cvx/tests.jl")
include("poly/tests.jl")
include("poly-cvx/tests.jl")
include("poly-mi/tests.jl")
include("poly-mi-cvx/tests.jl")
end
| 25.679245
| 78
| 0.653784
|
[
"@testset \"$(directory)\" begin\n models = _list_of_models(directory, exclude, include)\n @testset \"$(model_name)\" for model_name in models\n if debug\n println(\"Running $(model_name)\")\n end\n getfield(MINLPTests, model_name)(\n optimizer,\n objective_tol,\n primal_tol,\n dual_tol,\n termination_target,\n primal_target,\n )\n end\n end"
] |
f74f8bc643ba5b89eb387d157c45840ceeb54cf2
| 2,271
|
jl
|
Julia
|
aoc2019/day03/day03_test.jl
|
bfontaine/advent-of-code
|
fb0f8ff33064640125e8e0471939657f112a92d2
|
[
"MIT"
] | 1
|
2019-01-27T00:32:32.000Z
|
2019-01-27T00:32:32.000Z
|
aoc2019/day03/day03_test.jl
|
bfontaine/advent-of-code
|
fb0f8ff33064640125e8e0471939657f112a92d2
|
[
"MIT"
] | null | null | null |
aoc2019/day03/day03_test.jl
|
bfontaine/advent-of-code
|
fb0f8ff33064640125e8e0471939657f112a92d2
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env julia
using Test
include("day03.jl")
using .Wires: parse_wire, parse_direction, gen_segment, problem1, problem2
@testset "parse_direction" begin
for direction = ["U0", "L0", "R0", "D0"]
@test (0,0) == parse_direction(direction)
end
@test (1,0) == parse_direction("R1")
@test (0,1) == parse_direction("U1")
@test (-1,0) == parse_direction("L1")
@test (0,-1) == parse_direction("D1")
@test (45,0) == parse_direction("R45")
@test (0,10) == parse_direction("U10")
@test (-3,0) == parse_direction("L3")
@test (0,-6) == parse_direction("D6")
end
@testset "gen_segment" begin
origin = (0, 0)
@test Dict([]) == gen_segment(origin, origin, 1)
for direction = [(1,0), (0,1), (-1,0), (0,-1)]
@test Dict(direction => 1) == gen_segment(origin, direction, 1)
end
for y = [0, -1, 1, 5]
@test Dict((1,y)=>1, (2,y)=>2, (3,y)=>3) == gen_segment((0,y), (3,0), 1)
@test Dict((-1,y)=>1, (-2,y)=>2, (-3,y)=>3) == gen_segment((0,y), (-3,0), 1)
end
for x = [0, -1, 1, 5]
@test Dict((x,1)=>1, (x,2)=>2, (x,3)=>3) == gen_segment((x,0), (0,3), 1)
@test Dict((x,-1)=>1, (x,-2)=>2, (x,-3)=>3) == gen_segment((x,0), (0,-3), 1)
end
@test Dict((1,1)=>1) == gen_segment((0,1), (1,0), 1)
@test Dict((1,1)=>1) == gen_segment((1,0), (0,1), 1)
end
@testset "parse_wire" begin
wire = parse_wire("U7")
@test Dict((0,1)=>1, (0,2)=>2, (0,3)=>3, (0,4)=>4, (0,5)=>5, (0,6)=>6, (0,7)=>7) == wire
wire = parse_wire("U1,R1")
@test Dict((0,1)=>1, (1,1)=>2) == wire
wire = parse_wire("R1,U1")
@test Dict((1,0)=>1, (1,1)=>2) == wire
end
@testset "problem1" begin
@test 6 == problem1("R8,U5,L5,D3", "U7,R6,D4,L4")
@test 159 == problem1("R75,D30,R83,U83,L12,D49,R71,U7,L72",
"U62,R66,U55,R34,D71,R55,D58,R83")
@test 135 == problem1("R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51",
"U98,R91,D20,R16,D67,R40,U7,R15,U6,R7")
end
@testset "problem2" begin
@test 30 == problem2("R8,U5,L5,D3", "U7,R6,D4,L4")
@test 610 == problem2("R75,D30,R83,U83,L12,D49,R71,U7,L72",
"U62,R66,U55,R34,D71,R55,D58,R83")
@test 410 == problem2("R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51",
"U98,R91,D20,R16,D67,R40,U7,R15,U6,R7")
end
| 31.541667
| 90
| 0.547336
|
[
"@testset \"parse_direction\" begin\n for direction = [\"U0\", \"L0\", \"R0\", \"D0\"]\n @test (0,0) == parse_direction(direction)\n end\n\n @test (1,0) == parse_direction(\"R1\")\n @test (0,1) == parse_direction(\"U1\")\n @test (-1,0) == parse_direction(\"L1\")\n @test (0,-1) == parse_direction(\"D1\")\n\n @test (45,0) == parse_direction(\"R45\")\n @test (0,10) == parse_direction(\"U10\")\n @test (-3,0) == parse_direction(\"L3\")\n @test (0,-6) == parse_direction(\"D6\")\nend",
"@testset \"gen_segment\" begin\n origin = (0, 0)\n @test Dict([]) == gen_segment(origin, origin, 1)\n\n for direction = [(1,0), (0,1), (-1,0), (0,-1)]\n @test Dict(direction => 1) == gen_segment(origin, direction, 1)\n end\n\n for y = [0, -1, 1, 5]\n @test Dict((1,y)=>1, (2,y)=>2, (3,y)=>3) == gen_segment((0,y), (3,0), 1)\n @test Dict((-1,y)=>1, (-2,y)=>2, (-3,y)=>3) == gen_segment((0,y), (-3,0), 1)\n end\n\n for x = [0, -1, 1, 5]\n @test Dict((x,1)=>1, (x,2)=>2, (x,3)=>3) == gen_segment((x,0), (0,3), 1)\n @test Dict((x,-1)=>1, (x,-2)=>2, (x,-3)=>3) == gen_segment((x,0), (0,-3), 1)\n end\n\n @test Dict((1,1)=>1) == gen_segment((0,1), (1,0), 1)\n @test Dict((1,1)=>1) == gen_segment((1,0), (0,1), 1)\nend",
"@testset \"parse_wire\" begin\n wire = parse_wire(\"U7\")\n @test Dict((0,1)=>1, (0,2)=>2, (0,3)=>3, (0,4)=>4, (0,5)=>5, (0,6)=>6, (0,7)=>7) == wire\n\n wire = parse_wire(\"U1,R1\")\n @test Dict((0,1)=>1, (1,1)=>2) == wire\n\n wire = parse_wire(\"R1,U1\")\n @test Dict((1,0)=>1, (1,1)=>2) == wire\nend",
"@testset \"problem1\" begin\n @test 6 == problem1(\"R8,U5,L5,D3\", \"U7,R6,D4,L4\")\n @test 159 == problem1(\"R75,D30,R83,U83,L12,D49,R71,U7,L72\",\n \"U62,R66,U55,R34,D71,R55,D58,R83\")\n @test 135 == problem1(\"R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51\",\n \"U98,R91,D20,R16,D67,R40,U7,R15,U6,R7\")\nend",
"@testset \"problem2\" begin\n @test 30 == problem2(\"R8,U5,L5,D3\", \"U7,R6,D4,L4\")\n @test 610 == problem2(\"R75,D30,R83,U83,L12,D49,R71,U7,L72\",\n \"U62,R66,U55,R34,D71,R55,D58,R83\")\n @test 410 == problem2(\"R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51\",\n \"U98,R91,D20,R16,D67,R40,U7,R15,U6,R7\")\nend"
] |
f74fdd87f724ed5dd3ac1565760e11d30c7b4b91
| 2,548
|
jl
|
Julia
|
test/runtests.jl
|
ianshmean/SnoopCompile.jl
|
77856274a05f90a93bd9136ab6caef106ccebe96
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
ianshmean/SnoopCompile.jl
|
77856274a05f90a93bd9136ab6caef106ccebe96
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
ianshmean/SnoopCompile.jl
|
77856274a05f90a93bd9136ab6caef106ccebe96
|
[
"MIT"
] | null | null | null |
if VERSION >= v"1.2.0-DEV.573"
include("snoopi.jl")
end
using SnoopCompile
using JLD
using SparseArrays
using Test
# issue #26
logfile = joinpath(tempdir(), "anon.log")
@snoopc logfile begin
map(x->x^2, [1,2,3])
end
data = SnoopCompile.read(logfile)
pc = SnoopCompile.parcel(reverse!(data[2]))
@test length(pc[:Base]) <= 1
# issue #29
keep, pcstring, topmod, name = SnoopCompile.parse_call("Tuple{getfield(JLD, Symbol(\"##s27#8\")), Any, Any, Any, Any, Any}")
@test keep
@test pcstring == "Tuple{getfield(JLD, Symbol(\"##s27#8\")), Int, Int, Int, Int, Int}"
@test topmod == :JLD
@test name == "##s27#8"
matfile = joinpath(tempdir(), "mat.jld")
save(matfile, "mat", sprand(10, 10, 0.1))
logfile = joinpath(tempdir(), "jldanon.log")
@snoopc logfile begin
using JLD, SparseArrays
mat = load(joinpath(tempdir(), "mat.jld"), "mat")
end
data = SnoopCompile.read(logfile)
pc = SnoopCompile.parcel(reverse!(data[2]))
@test any(startswith.(pc[:JLD], "isdefined"))
#=
# Simple call
let str = "sum"
keep, pcstring, topmod = SnoopCompile.parse_call("Foo.any($str)")
@test keep
@test pcstring == "Tuple{$str}"
@test topmod == :Main
end
# Operator
let str = "Base.:*, Int, Int"
keep, pcstring, topmod = SnoopCompile.parse_call("Foo.any($str)")
@test keep
@test pcstring == "Tuple{$str}"
@test topmod == :Base
end
# Function as argument
let str = "typeof(Base.identity), Array{Bool, 1}"
keep, pcstring, topmod = SnoopCompile.parse_call("Foo.any($str, Vararg{Any, N} where N)")
@test keep
@test pcstring == "Tuple{$str, Int}"
@test topmod == :Base
end
# Anonymous function closure in a new module as argument
let func = (@eval Main module SnoopTestTemp
func = () -> (y = 2; (x -> x > y))
end).func
str = "getfield(SnoopTestTemp, Symbol(\"$(typeof(func()))\")), Array{Float32, 1}"
keep, pcstring, topmod = SnoopCompile.parse_call("Foo.any($str)")
@test keep
@test pcstring == "Tuple{$str}"
@test topmod == :SnoopTestTemp
end
# Function as a type
let str = "typeof(Base.Sort.sort!), Array{Any, 1}, Base.Sort.MergeSortAlg, Base.Order.By{typeof(Base.string)}"
keep, pcstring, topmod = SnoopCompile.parse_call("Foo.Bar.sort!($str)")
@test keep
@test pcstring == "Tuple{$str}"
@test topmod == :Base
end
=#
@static if VERSION >= v"1.2.0-DEV.573"
@testset "timesum" begin
loadSnoop = SnoopCompile.@snoopi using MatLang
@test typeof(timesum(loadSnoop)) == Float64
end
end
include("colortypes.jl")
include("bot/bot.jl")
| 28.311111
| 124
| 0.648744
|
[
"@static if VERSION >= v\"1.2.0-DEV.573\"\n @testset \"timesum\" begin\n loadSnoop = SnoopCompile.@snoopi using MatLang\n @test typeof(timesum(loadSnoop)) == Float64\n end\nend"
] |
f7503dc26338531e7f7300f9f2472f66d4066976
| 1,444
|
jl
|
Julia
|
test/testBasicCSM.jl
|
KristofferC/IncrementalInference.jl
|
708e62902104a8971a7cf1228abf01bbc2f0dac0
|
[
"MIT"
] | null | null | null |
test/testBasicCSM.jl
|
KristofferC/IncrementalInference.jl
|
708e62902104a8971a7cf1228abf01bbc2f0dac0
|
[
"MIT"
] | null | null | null |
test/testBasicCSM.jl
|
KristofferC/IncrementalInference.jl
|
708e62902104a8971a7cf1228abf01bbc2f0dac0
|
[
"MIT"
] | null | null | null |
# IIF #485 --
# using Revise
using Test
using Logging
using Statistics
using DistributedFactorGraphs
using IncrementalInference
@testset "test basic three variable graph with prior" begin
VAR1 = :a
VAR2 = :b
VAR3 = :c
logger = SimpleLogger(stdout, Logging.Debug)
global_logger(logger)
dfg = initfg() #LightDFG{SolverParams}(solverParams=SolverParams())
# Add some nodes.
v1 = addVariable!(dfg, VAR1, ContinuousScalar, labels = [:POSE])
v2 = addVariable!(dfg, VAR2, ContinuousScalar, labels = [:POSE])
v3 = addVariable!(dfg, VAR3, ContinuousScalar, labels = [:LANDMARK])
f1 = addFactor!(dfg, [VAR1; VAR2], LinearConditional(Normal(50.0,2.0)) )
f2 = addFactor!(dfg, [VAR2; VAR3], LinearConditional(Normal(50.0,2.0)) )
addFactor!(dfg, [VAR1], Prior(Normal()))
# drawGraph(dfg, show=true)
# tree = wipeBuildNewTree!(dfg)
# # drawTree(tree, show=true)
#
# getCliqFactors(tree, VAR3)
# getCliqFactors(tree, VAR1)
ensureAllInitialized!(dfg)
# cliq= getCliq(tree, VAR3)
# getData(cliq)
#
# cliq= getCliq(tree, VAR1)
# getData(cliq)
getSolverParams(dfg).limititers = 50
# getSolverParams(dfg).drawtree = true
# getSolverParams(dfg).showtree = true
# getSolverParams(dfg).dbg = true
## getSolverParams(dfg).async = true
tree, smtasks, hist = solveTree!(dfg) #, recordcliqs=ls(dfg))
@test 70 < Statistics.mean(getKDE(dfg, :c) |> getPoints) < 130
# #
# using Gadfly, Cairo, Fontconfig
# drawTree(tree, show=true, imgs=true)
end
#
| 20.055556
| 72
| 0.714681
|
[
"@testset \"test basic three variable graph with prior\" begin\n\nVAR1 = :a\nVAR2 = :b\nVAR3 = :c\n\nlogger = SimpleLogger(stdout, Logging.Debug)\nglobal_logger(logger)\ndfg = initfg() #LightDFG{SolverParams}(solverParams=SolverParams())\n# Add some nodes.\nv1 = addVariable!(dfg, VAR1, ContinuousScalar, labels = [:POSE])\nv2 = addVariable!(dfg, VAR2, ContinuousScalar, labels = [:POSE])\nv3 = addVariable!(dfg, VAR3, ContinuousScalar, labels = [:LANDMARK])\nf1 = addFactor!(dfg, [VAR1; VAR2], LinearConditional(Normal(50.0,2.0)) )\nf2 = addFactor!(dfg, [VAR2; VAR3], LinearConditional(Normal(50.0,2.0)) )\n\naddFactor!(dfg, [VAR1], Prior(Normal()))\n\n# drawGraph(dfg, show=true)\n\n\n# tree = wipeBuildNewTree!(dfg)\n# # drawTree(tree, show=true)\n#\n# getCliqFactors(tree, VAR3)\n# getCliqFactors(tree, VAR1)\n\nensureAllInitialized!(dfg)\n\n\n# cliq= getCliq(tree, VAR3)\n# getData(cliq)\n#\n# cliq= getCliq(tree, VAR1)\n# getData(cliq)\n\n\n\ngetSolverParams(dfg).limititers = 50\n# getSolverParams(dfg).drawtree = true\n# getSolverParams(dfg).showtree = true\n# getSolverParams(dfg).dbg = true\n## getSolverParams(dfg).async = true\n\n\ntree, smtasks, hist = solveTree!(dfg) #, recordcliqs=ls(dfg))\n\n\n@test 70 < Statistics.mean(getKDE(dfg, :c) |> getPoints) < 130\n\n# #\n# using Gadfly, Cairo, Fontconfig\n# drawTree(tree, show=true, imgs=true)\n\nend"
] |
f7523d184e789a517886d1d65014e78a3b50c4f2
| 3,523
|
jl
|
Julia
|
test/runtests.jl
|
rubsc/RiskMeasures.jl
|
6b0dd90bdb8428edc901dea7ac2e347746e8ce47
|
[
"MIT"
] | 1
|
2022-01-18T18:47:59.000Z
|
2022-01-18T18:47:59.000Z
|
test/runtests.jl
|
rubsc/RiskMeasures.jl
|
6b0dd90bdb8428edc901dea7ac2e347746e8ce47
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
rubsc/RiskMeasures.jl
|
6b0dd90bdb8428edc901dea7ac2e347746e8ce47
|
[
"MIT"
] | null | null | null |
using RiskMeasures
using Test
@testset "helper.jl" begin
# Write your tests here.
@test pnorm(2,[0.5 0.5],[1 2]) ≈ 1.5811 atol=0.01
@test ontoSimplex([0.3 0.3 0.3 0.3]) == [0.25 0.25 0.25 0.25]
@test ontoSimplex([-0.3 -0.3 0.3 0.3]) == [0.0 0.0 0.5 0.5]
@test goldenSearch(x -> x^2, 1.0)[2] < 1E-16
@test goldenSearch(x -> x^2, -1.0)[2] < 1E-16
@test checkSpectral(x -> x) == false
@test checkSpectral(x -> 2 .- 2 .*x) == false
@test checkSpectral(x -> 0 .*x .+ 1.0) == true
@test eval(math_expr(:+,1,2)) == 3
@test eval(math_expr(:+,1)) == 1
@test eval(add_expr(1, 2)) == 3
end
@testset "basic_RM.jl" begin
# Write your tests here.
states = [1.0, 2.0, 3.0, 4.0]; prob = [0.2, 0.4, 0.2, 0.2]
@test Expectation([1.0, 2.0, 3.0, 4.0],[0.0, 0.0, 0.0, 0.0]) == sum([1 2 3 4])/4
@test Expectation(states,prob) == 0.2*1 + 0.4*2 + 0.2*3 + 0.2*4
@test mSD(states,prob,0.0f0,2.0f0) == Expectation(states,prob)
@test mSD([1.0, 1.0], [0.0, 0.0],0.0f0,2.0f0) == 1
@test mSD(states,prob,1.0f0,2.0f0) ≈ 3.16419 atol = 0.001
@test mSD(states,prob,1.0f0,2.0f0) < mSD(states,prob,1.0f0,3.0f0)
@test VaR(states,prob,0.0f0) == minimum(states)
@test CTE(states,prob,0.0f0) == Expectation(states,prob)
end
@testset "valueRisk.jl" begin
# Write your tests here.
states = [1.0, 2.0, 3.0, 4.0]; prob = [0.2, 0.4, 0.2, 0.2]
@test EVaR2(states, prob,0.0f0)[1] == Expectation(states,prob)
@test EVaR2(states, prob,0.5f0)[1] ≈ 3.413183 atol = 0.001
@test EVaR2([1.0, 1.0], [0.0, 0.0],0.5f0)[1] == 0
@test EVaR(states, prob,0.0f0)[1] == Expectation(states,prob)
@test EVaR(states, prob,0.5f0)[1] ≈ 3.413183 atol = 0.001
@test EVaR([1.0, 1.0], [0.0, 0.0],0.5f0)[1] == 0.0
@test EVaR(states, prob,5.5f0)[1] == maximum(states)
@test AVaR(states,prob, 0.0f0)[1] == Expectation(states,prob)
@test AVaR(states,prob, 0.5f0)[1] ≈ CTE(states,prob,0.5f0) atol = 0.0001
end
@testset "genRM.jl" begin
# Write your tests here.
states = [1.0, 2.0, 3.0, 4.0]; prob = [0.2, 0.4, 0.2, 0.2]
@test entropic(states, prob,1.0f0) ≈ 2.91430 atol = 0.001
@test entropic([1.0, 1.0], [0.0, 0.0],0.5f0) == 1.0
@test entropic([1.0, 1.0], [0.0, 0.0],0.0f0) === nothing
@test meanVariance([1.0, 1.0], [0.0, 0.0],-1.0f0) === nothing
@test meanVariance([1.0, 1.0], [0.0, 0.0],1.0f0) == 1.0
@test meanDeviation([1.0, 1.0], [0.0, 0.0],-1.0f0,2.0f0) === nothing
@test meanDeviation([1.0, 1.0], [0.0, 0.0],1.0f0,2.0f0) == 1.0
@test meanDeviation([1.0, 1.0], [0.0, 0.0],-1.0f0,0.5f0) === nothing
@test meanDeviation([1.0, 1.0], [0.0, 0.0],1.0f0,0.5f0) === nothing
@test meanSemiVariance([1.0, 1.0], [0.0, 0.0],1.0f0, 0.0f0) == 2.0
@test meanSemiVariance([1.0, 1.0], [0.0, 0.0],-1.0f0, 0.0f0) === nothing
@test meanSemiDevi([1.0, 1.0], [0.0, 0.0],1.0f0, 0.0f0, 2.0f0) == 2.0
@test meanSemiDevi([1.0, 1.0], [0.0, 0.0],-1.0f0, 0.0f0, 2.0f0) === nothing
@test meanSemiDevi([1.0, 1.0], [0.0, 0.0],1.0f0, 0.0f0, -2.0f0) === nothing
@test spectral([0.0, 1.0], [0.2, 0.8], x -> 2.0*x) ≈ 0.96 atol = 0.0001
@test spectral([0.0, 1.0], [0.2, 0.8], x -> x) === nothing
@test distortion([0.0, 1.0], [1.0, 0.0], x -> x^2) == 0.0
o1 = :( (Y)^2 *p); o2 = :sqrt; conds = [o1 :+ o2];
states = [1.0, 2.0, 3.0]; prob = [0.3, 0.4, 0.3];
@test GenCoherent(states, prob,conds)[1] ≈ 3.0 atol = 0.0001
@test GenConvex(states, prob,conds,x->x) === nothing
end
| 39.58427
| 84
| 0.549248
|
[
"@testset \"helper.jl\" begin\n # Write your tests here.\n @test pnorm(2,[0.5 0.5],[1 2]) ≈ 1.5811 atol=0.01\n\n @test ontoSimplex([0.3 0.3 0.3 0.3]) == [0.25 0.25 0.25 0.25]\n @test ontoSimplex([-0.3 -0.3 0.3 0.3]) == [0.0 0.0 0.5 0.5]\n @test goldenSearch(x -> x^2, 1.0)[2] < 1E-16\n @test goldenSearch(x -> x^2, -1.0)[2] < 1E-16\n\n @test checkSpectral(x -> x) == false\n @test checkSpectral(x -> 2 .- 2 .*x) == false\n @test checkSpectral(x -> 0 .*x .+ 1.0) == true\n\n @test eval(math_expr(:+,1,2)) == 3\n @test eval(math_expr(:+,1)) == 1\n @test eval(add_expr(1, 2)) == 3\nend",
"@testset \"basic_RM.jl\" begin\n # Write your tests here.\n states = [1.0, 2.0, 3.0, 4.0]; prob = [0.2, 0.4, 0.2, 0.2]\n @test Expectation([1.0, 2.0, 3.0, 4.0],[0.0, 0.0, 0.0, 0.0]) == sum([1 2 3 4])/4\n @test Expectation(states,prob) == 0.2*1 + 0.4*2 + 0.2*3 + 0.2*4\n\n @test mSD(states,prob,0.0f0,2.0f0) == Expectation(states,prob)\n @test mSD([1.0, 1.0], [0.0, 0.0],0.0f0,2.0f0) == 1\n @test mSD(states,prob,1.0f0,2.0f0) ≈ 3.16419 atol = 0.001\n @test mSD(states,prob,1.0f0,2.0f0) < mSD(states,prob,1.0f0,3.0f0)\n\n @test VaR(states,prob,0.0f0) == minimum(states)\n @test CTE(states,prob,0.0f0) == Expectation(states,prob)\nend",
"@testset \"valueRisk.jl\" begin\n # Write your tests here.\n states = [1.0, 2.0, 3.0, 4.0]; prob = [0.2, 0.4, 0.2, 0.2]\n \n @test EVaR2(states, prob,0.0f0)[1] == Expectation(states,prob)\n @test EVaR2(states, prob,0.5f0)[1] ≈ 3.413183 atol = 0.001\n @test EVaR2([1.0, 1.0], [0.0, 0.0],0.5f0)[1] == 0 \n @test EVaR(states, prob,0.0f0)[1] == Expectation(states,prob)\n @test EVaR(states, prob,0.5f0)[1] ≈ 3.413183 atol = 0.001\n @test EVaR([1.0, 1.0], [0.0, 0.0],0.5f0)[1] == 0.0\n @test EVaR(states, prob,5.5f0)[1] == maximum(states)\n @test AVaR(states,prob, 0.0f0)[1] == Expectation(states,prob)\n @test AVaR(states,prob, 0.5f0)[1] ≈ CTE(states,prob,0.5f0) atol = 0.0001\nend",
"@testset \"genRM.jl\" begin\n # Write your tests here.\n states = [1.0, 2.0, 3.0, 4.0]; prob = [0.2, 0.4, 0.2, 0.2]\n\n \n @test entropic(states, prob,1.0f0) ≈ 2.91430 atol = 0.001\n @test entropic([1.0, 1.0], [0.0, 0.0],0.5f0) == 1.0\n @test entropic([1.0, 1.0], [0.0, 0.0],0.0f0) === nothing\n\n @test meanVariance([1.0, 1.0], [0.0, 0.0],-1.0f0) === nothing\n @test meanVariance([1.0, 1.0], [0.0, 0.0],1.0f0) == 1.0\n\n @test meanDeviation([1.0, 1.0], [0.0, 0.0],-1.0f0,2.0f0) === nothing\n @test meanDeviation([1.0, 1.0], [0.0, 0.0],1.0f0,2.0f0) == 1.0\n @test meanDeviation([1.0, 1.0], [0.0, 0.0],-1.0f0,0.5f0) === nothing\n @test meanDeviation([1.0, 1.0], [0.0, 0.0],1.0f0,0.5f0) === nothing\n\n @test meanSemiVariance([1.0, 1.0], [0.0, 0.0],1.0f0, 0.0f0) == 2.0\n @test meanSemiVariance([1.0, 1.0], [0.0, 0.0],-1.0f0, 0.0f0) === nothing\n\n @test meanSemiDevi([1.0, 1.0], [0.0, 0.0],1.0f0, 0.0f0, 2.0f0) == 2.0\n @test meanSemiDevi([1.0, 1.0], [0.0, 0.0],-1.0f0, 0.0f0, 2.0f0) === nothing\n @test meanSemiDevi([1.0, 1.0], [0.0, 0.0],1.0f0, 0.0f0, -2.0f0) === nothing\n\n @test spectral([0.0, 1.0], [0.2, 0.8], x -> 2.0*x) ≈ 0.96 atol = 0.0001\n @test spectral([0.0, 1.0], [0.2, 0.8], x -> x) === nothing\n\n @test distortion([0.0, 1.0], [1.0, 0.0], x -> x^2) == 0.0\n\n o1 = :( (Y)^2 *p); o2 = :sqrt; conds = [o1 :+ o2]; \n states = [1.0, 2.0, 3.0]; prob = [0.3, 0.4, 0.3];\n @test GenCoherent(states, prob,conds)[1] ≈ 3.0 atol = 0.0001\n\n @test GenConvex(states, prob,conds,x->x) === nothing\nend"
] |
f752982437a7e151c2b70f260582c8900d6997d0
| 99,087
|
jl
|
Julia
|
stdlib/SparseArrays/test/sparse.jl
|
domluna/julia
|
1c88c0e2bed347f35c641413f0c7f9cee25a8fe4
|
[
"Zlib"
] | null | null | null |
stdlib/SparseArrays/test/sparse.jl
|
domluna/julia
|
1c88c0e2bed347f35c641413f0c7f9cee25a8fe4
|
[
"Zlib"
] | null | null | null |
stdlib/SparseArrays/test/sparse.jl
|
domluna/julia
|
1c88c0e2bed347f35c641413f0c7f9cee25a8fe4
|
[
"Zlib"
] | null | null | null |
# This file is a part of Julia. License is MIT: https://julialang.org/license
module SparseTests
using Test
using SparseArrays
using LinearAlgebra
using Base.Printf: @printf
using Random
using Test: guardseed
using InteractiveUtils: @which
using Dates
@testset "issparse" begin
@test issparse(sparse(fill(1,5,5)))
@test !issparse(fill(1,5,5))
end
@testset "iszero specialization for SparseMatrixCSC" begin
@test !iszero(sparse(I, 3, 3)) # test failure
@test iszero(spzeros(3, 3)) # test success with no stored entries
S = sparse(I, 3, 3)
S[:] .= 0
@test iszero(S) # test success with stored zeros via broadcasting
S = sparse(I, 3, 3)
fill!(S, 0)
@test iszero(S) # test success with stored zeros via fill!
@test iszero(SparseMatrixCSC(2, 2, [1,2,3], [1,2], [0,0,1])) # test success with nonzeros beyond data range
end
@testset "isone specialization for SparseMatrixCSC" begin
@test isone(sparse(I, 3, 3)) # test success
@test !isone(sparse(I, 3, 4)) # test failure for non-square matrix
@test !isone(spzeros(3, 3)) # test failure for too few stored entries
@test !isone(sparse(2I, 3, 3)) # test failure for non-one diagonal entries
@test !isone(sparse(Bidiagonal(fill(1, 3), fill(1, 2), :U))) # test failure for non-zero off-diag entries
end
@testset "indtype" begin
@test SparseArrays.indtype(sparse(Int8[1,1],Int8[1,1],[1,1])) == Int8
end
@testset "sparse matrix construction" begin
@test (A = fill(1.0+im,5,5); isequal(Array(sparse(A)), A))
@test_throws ArgumentError sparse([1,2,3], [1,2], [1,2,3], 3, 3)
@test_throws ArgumentError sparse([1,2,3], [1,2,3], [1,2], 3, 3)
@test_throws ArgumentError sparse([1,2,3], [1,2,3], [1,2,3], 0, 1)
@test_throws ArgumentError sparse([1,2,3], [1,2,3], [1,2,3], 1, 0)
@test_throws ArgumentError sparse([1,2,4], [1,2,3], [1,2,3], 3, 3)
@test_throws ArgumentError sparse([1,2,3], [1,2,4], [1,2,3], 3, 3)
@test isequal(sparse(Int[], Int[], Int[], 0, 0), SparseMatrixCSC(0, 0, Int[1], Int[], Int[]))
@test sparse(Any[1,2,3], Any[1,2,3], Any[1,1,1]) == sparse([1,2,3], [1,2,3], [1,1,1])
@test sparse(Any[1,2,3], Any[1,2,3], Any[1,1,1], 5, 4) == sparse([1,2,3], [1,2,3], [1,1,1], 5, 4)
end
@testset "SparseMatrixCSC construction from UniformScaling" begin
@test_throws ArgumentError SparseMatrixCSC(I, -1, 3)
@test_throws ArgumentError SparseMatrixCSC(I, 3, -1)
@test SparseMatrixCSC(2I, 3, 3)::SparseMatrixCSC{Int,Int} == Matrix(2I, 3, 3)
@test SparseMatrixCSC(2I, 3, 4)::SparseMatrixCSC{Int,Int} == Matrix(2I, 3, 4)
@test SparseMatrixCSC(2I, 4, 3)::SparseMatrixCSC{Int,Int} == Matrix(2I, 4, 3)
@test SparseMatrixCSC(2.0I, 3, 3)::SparseMatrixCSC{Float64,Int} == Matrix(2I, 3, 3)
@test SparseMatrixCSC{Real}(2I, 3, 3)::SparseMatrixCSC{Real,Int} == Matrix(2I, 3, 3)
@test SparseMatrixCSC{Float64}(2I, 3, 3)::SparseMatrixCSC{Float64,Int} == Matrix(2I, 3, 3)
@test SparseMatrixCSC{Float64,Int32}(2I, 3, 3)::SparseMatrixCSC{Float64,Int32} == Matrix(2I, 3, 3)
@test SparseMatrixCSC{Float64,Int32}(0I, 3, 3)::SparseMatrixCSC{Float64,Int32} == Matrix(0I, 3, 3)
end
@testset "sparse(S::UniformScaling, shape...) convenience constructors" begin
# we exercise these methods only lightly as these methods call the SparseMatrixCSC
# constructor methods well-exercised by the immediately preceding testset
@test sparse(2I, 3, 4)::SparseMatrixCSC{Int,Int} == Matrix(2I, 3, 4)
@test sparse(2I, (3, 4))::SparseMatrixCSC{Int,Int} == Matrix(2I, 3, 4)
end
se33 = SparseMatrixCSC{Float64}(I, 3, 3)
do33 = fill(1.,3)
@testset "sparse binary operations" begin
@test isequal(se33 * se33, se33)
@test Array(se33 + convert(SparseMatrixCSC{Float32,Int32}, se33)) == Matrix(2I, 3, 3)
@test Array(se33 * convert(SparseMatrixCSC{Float32,Int32}, se33)) == Matrix(I, 3, 3)
@testset "shape checks for sparse elementwise binary operations equivalent to map" begin
sqrfloatmat, colfloatmat = sprand(4, 4, 0.5), sprand(4, 1, 0.5)
@test_throws DimensionMismatch (+)(sqrfloatmat, colfloatmat)
@test_throws DimensionMismatch (-)(sqrfloatmat, colfloatmat)
@test_throws DimensionMismatch map(min, sqrfloatmat, colfloatmat)
@test_throws DimensionMismatch map(max, sqrfloatmat, colfloatmat)
sqrboolmat, colboolmat = sprand(Bool, 4, 4, 0.5), sprand(Bool, 4, 1, 0.5)
@test_throws DimensionMismatch map(&, sqrboolmat, colboolmat)
@test_throws DimensionMismatch map(|, sqrboolmat, colboolmat)
@test_throws DimensionMismatch map(xor, sqrboolmat, colboolmat)
end
end
@testset "Issue #30006" begin
SparseMatrixCSC{Float64,Int32}(spzeros(3,3))[:, 1] == [1, 2, 3]
end
@testset "concatenation tests" begin
sp33 = sparse(1.0I, 3, 3)
@testset "horizontal concatenation" begin
@test [se33 se33] == [Array(se33) Array(se33)]
@test length(([sp33 0I]).nzval) == 3
end
@testset "vertical concatenation" begin
@test [se33; se33] == [Array(se33); Array(se33)]
se33_32bit = convert(SparseMatrixCSC{Float32,Int32}, se33)
@test [se33; se33_32bit] == [Array(se33); Array(se33_32bit)]
@test length(([sp33; 0I]).nzval) == 3
end
se44 = sparse(1.0I, 4, 4)
sz42 = spzeros(4, 2)
sz41 = spzeros(4, 1)
sz34 = spzeros(3, 4)
se77 = sparse(1.0I, 7, 7)
@testset "h+v concatenation" begin
@test [se44 sz42 sz41; sz34 se33] == se77
@test length(([sp33 0I; 1I 0I]).nzval) == 6
end
@testset "blockdiag concatenation" begin
@test blockdiag(se33, se33) == sparse(1:6,1:6,fill(1.,6))
@test blockdiag() == spzeros(0, 0)
@test nnz(blockdiag()) == 0
end
@testset "concatenation promotion" begin
sz41_f32 = spzeros(Float32, 4, 1)
se33_i32 = sparse(Int32(1)I, 3, 3)
@test [se44 sz42 sz41_f32; sz34 se33_i32] == se77
end
@testset "mixed sparse-dense concatenation" begin
sz33 = spzeros(3, 3)
de33 = Matrix(1.0I, 3, 3)
@test [se33 de33; sz33 se33] == Array([se33 se33; sz33 se33 ])
end
# check splicing + concatenation on random instances, with nested vcat and also side-checks sparse ref
@testset "splicing + concatenation on random instances" begin
for i = 1 : 10
a = sprand(5, 4, 0.5)
@test [a[1:2,1:2] a[1:2,3:4]; a[3:5,1] [a[3:4,2:4]; a[5:5,2:4]]] == a
end
end
end
let
a116 = copy(reshape(1:16, 4, 4))
s116 = sparse(a116)
@testset "sparse ref" begin
p = [4, 1, 2, 3, 2]
@test Array(s116[p,:]) == a116[p,:]
@test Array(s116[:,p]) == a116[:,p]
@test Array(s116[p,p]) == a116[p,p]
end
@testset "sparse assignment" begin
p = [4, 1, 3]
a116[p, p] .= -1
s116[p, p] .= -1
@test a116 == s116
p = [2, 1, 4]
a116[p, p] = reshape(1:9, 3, 3)
s116[p, p] = reshape(1:9, 3, 3)
@test a116 == s116
end
end
@testset "dropdims" begin
for i = 1:5
am = sprand(20, 1, 0.2)
av = dropdims(am, dims=2)
@test ndims(av) == 1
@test all(av.==am)
am = sprand(1, 20, 0.2)
av = dropdims(am, dims=1)
@test ndims(av) == 1
@test all(av' .== am)
end
end
@testset "Issue #28963" begin
@test_throws DimensionMismatch (spzeros(10,10)[:, :] = sprand(10,20,0.5))
end
@testset "matrix-vector multiplication (non-square)" begin
for i = 1:5
a = sprand(10, 5, 0.5)
b = rand(5)
@test maximum(abs.(a*b - Array(a)*b)) < 100*eps()
end
end
@testset "sparse matrix * BitArray" begin
A = sprand(5,5,0.2)
B = trues(5)
@test A*B ≈ Array(A)*B
B = trues(5,5)
@test A*B ≈ Array(A)*B
@test B*A ≈ B*Array(A)
end
@testset "complex matrix-vector multiplication and left-division" begin
if Base.USE_GPL_LIBS
for i = 1:5
a = I + 0.1*sprandn(5, 5, 0.2)
b = randn(5,3) + im*randn(5,3)
c = randn(5) + im*randn(5)
d = randn(5) + im*randn(5)
α = rand(ComplexF64)
β = rand(ComplexF64)
@test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())
@test (maximum(abs.(mul!(similar(b), a, b) - Array(a)*b)) < 100*eps()) # for compatibility with present matmul API. Should go away eventually.
@test (maximum(abs.(mul!(similar(c), a, c) - Array(a)*c)) < 100*eps()) # for compatibility with present matmul API. Should go away eventually.
@test (maximum(abs.(mul!(similar(b), transpose(a), b) - transpose(Array(a))*b)) < 100*eps()) # for compatibility with present matmul API. Should go away eventually.
@test (maximum(abs.(mul!(similar(c), transpose(a), c) - transpose(Array(a))*c)) < 100*eps()) # for compatibility with present matmul API. Should go away eventually.
@test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())
@test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())
@test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps())
@test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps())
@test (maximum(abs.(transpose(a)\b - Array(transpose(a))\b)) < 1000*eps())
@test (maximum(abs.((a'*c + d) - (Array(a)'*c + d))) < 1000*eps())
@test (maximum(abs.((α*transpose(a)*c + β*d) - (α*transpose(Array(a))*c + β*d))) < 1000*eps())
@test (maximum(abs.((transpose(a)*c + d) - (transpose(Array(a))*c + d))) < 1000*eps())
c = randn(6) + im*randn(6)
@test_throws DimensionMismatch α*transpose(a)*c + β*c
@test_throws DimensionMismatch α*transpose(a)*fill(1.,5) + β*c
a = I + 0.1*sprandn(5, 5, 0.2) + 0.1*im*sprandn(5, 5, 0.2)
b = randn(5,3)
@test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())
@test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())
@test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())
@test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps())
@test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps())
@test (maximum(abs.(transpose(a)\b - Array(transpose(a))\b)) < 1000*eps())
a = I + tril(0.1*sprandn(5, 5, 0.2))
b = randn(5,3) + im*randn(5,3)
@test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())
@test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())
@test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())
@test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps())
@test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps())
@test (maximum(abs.(transpose(a)\b - Array(transpose(a))\b)) < 1000*eps())
a = I + tril(0.1*sprandn(5, 5, 0.2) + 0.1*im*sprandn(5, 5, 0.2))
b = randn(5,3)
@test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())
@test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())
@test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())
@test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps())
@test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps())
@test (maximum(abs.(transpose(a)\b - Array(transpose(a))\b)) < 1000*eps())
a = I + triu(0.1*sprandn(5, 5, 0.2))
b = randn(5,3) + im*randn(5,3)
@test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())
@test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())
@test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())
@test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps())
@test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps())
@test (maximum(abs.(transpose(a)\b - Array(transpose(a))\b)) < 1000*eps())
a = I + triu(0.1*sprandn(5, 5, 0.2) + 0.1*im*sprandn(5, 5, 0.2))
b = randn(5,3)
@test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())
@test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())
@test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())
@test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps())
@test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps())
@test (maximum(abs.(transpose(a)\b - Array(transpose(a))\b)) < 1000*eps())
a = I + triu(0.1*sprandn(5, 5, 0.2))
b = randn(5,3) + im*randn(5,3)
@test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())
@test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())
@test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())
@test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps())
@test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps())
@test (maximum(abs.(transpose(a)\b - Array(transpose(a))\b)) < 1000*eps())
# UpperTriangular/LowerTriangular solve
a = UpperTriangular(I + triu(0.1*sprandn(5, 5, 0.2)))
b = sprandn(5, 5, 0.2)
@test (maximum(abs.(a\b - Array(a)\Array(b))) < 1000*eps())
# test error throwing for bwdTrisolve
@test_throws DimensionMismatch a\Matrix{Float64}(I, 6, 6)
a = LowerTriangular(I + tril(0.1*sprandn(5, 5, 0.2)))
b = sprandn(5, 5, 0.2)
@test (maximum(abs.(a\b - Array(a)\Array(b))) < 1000*eps())
# test error throwing for fwdTrisolve
@test_throws DimensionMismatch a\Matrix{Float64}(I, 6, 6)
a = sparse(Diagonal(randn(5) + im*randn(5)))
b = randn(5,3)
@test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())
@test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())
@test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())
@test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps())
@test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps())
@test (maximum(abs.(transpose(a)\b - Array(transpose(a))\b)) < 1000*eps())
b = randn(5,3) + im*randn(5,3)
@test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())
@test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())
@test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())
@test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps())
@test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps())
@test (maximum(abs.(transpose(a)\b - Array(transpose(a))\b)) < 1000*eps())
end
end
end
@testset "matrix multiplication" begin
for (m, p, n, q, k) in (
(10, 0.7, 5, 0.3, 15),
(100, 0.01, 100, 0.01, 20),
(100, 0.1, 100, 0.2, 100),
)
a = sprand(m, n, p)
b = sprand(n, k, q)
as = sparse(a')
bs = sparse(b')
ab = a * b
aab = Array(a) * Array(b)
@test maximum(abs.(ab - aab)) < 100*eps()
@test a*bs' == ab
@test as'*b == ab
@test as'*bs' == ab
f = Diagonal(rand(n))
@test Array(a*f) == Array(a)*f
@test Array(f*b) == f*Array(b)
A = rand(2n, 2n)
sA = view(A, 1:2:2n, 1:2:2n)
@test Array(sA*b) ≈ Array(sA)*Array(b)
@test Array(a*sA) ≈ Array(a)*Array(sA)
c = sprandn(ComplexF32, n, n, q)
@test Array(sA*c') ≈ Array(sA)*Array(c)'
@test Array(c'*sA) ≈ Array(c)'*Array(sA)
end
end
@testset "Issue #30502" begin
@test nnz(sprand(UInt8(16), UInt8(16), 1.0)) == 256
@test nnz(sprand(UInt8(16), UInt8(16), 1.0, ones)) == 256
end
@testset "kronecker product" begin
for (m,n) in ((5,10), (13,8), (14,10))
a = sprand(m, 5, 0.4); a_d = Matrix(a)
b = sprand(n, 6, 0.3); b_d = Matrix(b)
v = view(a, :, 1); v_d = Vector(v)
x = sprand(m, 0.4); x_d = Vector(x)
y = sprand(n, 0.3); y_d = Vector(y)
# mat ⊗ mat
@test Array(kron(a, b)) == kron(a_d, b_d)
@test Array(kron(a_d, b)) == kron(a_d, b_d)
@test Array(kron(a, b_d)) == kron(a_d, b_d)
# vec ⊗ vec
@test Vector(kron(x, y)) == kron(x_d, y_d)
@test Vector(kron(x_d, y)) == kron(x_d, y_d)
@test Vector(kron(x, y_d)) == kron(x_d, y_d)
# mat ⊗ vec
@test Array(kron(a, y)) == kron(a_d, y_d)
@test Array(kron(a_d, y)) == kron(a_d, y_d)
@test Array(kron(a, y_d)) == kron(a_d, y_d)
# vec ⊗ mat
@test Array(kron(x, b)) == kron(x_d, b_d)
@test Array(kron(x_d, b)) == kron(x_d, b_d)
@test Array(kron(x, b_d)) == kron(x_d, b_d)
# vec ⊗ vec'
@test issparse(kron(v, y'))
@test issparse(kron(x, y'))
@test Array(kron(v, y')) == kron(v_d, y_d')
@test Array(kron(x, y')) == kron(x_d, y_d')
# test different types
z = convert(SparseVector{Float16, Int8}, y); z_d = Vector(z)
@test Vector(kron(x, z)) == kron(x_d, z_d)
@test Array(kron(a, z)) == kron(a_d, z_d)
@test Array(kron(z, b)) == kron(z_d, b_d)
end
end
@testset "sparse Frobenius dot/inner product" begin
for i = 1:5
A = sprand(ComplexF64,10,15,0.4)
B = sprand(ComplexF64,10,15,0.5)
@test dot(A,B) ≈ dot(Matrix(A),Matrix(B))
end
@test_throws DimensionMismatch dot(sprand(5,5,0.2),sprand(5,6,0.2))
end
const BASE_TEST_PATH = joinpath(Sys.BINDIR, "..", "share", "julia", "test")
isdefined(Main, :Quaternions) || @eval Main include(joinpath($(BASE_TEST_PATH), "testhelpers", "Quaternions.jl"))
using .Main.Quaternions
sA = sprandn(3, 7, 0.5)
sC = similar(sA)
dA = Array(sA)
@testset "scaling with * and mul!, rmul!, and lmul!" begin
b = randn(7)
@test dA * Diagonal(b) == sA * Diagonal(b)
@test dA * Diagonal(b) == mul!(sC, sA, Diagonal(b))
@test dA * Diagonal(b) == rmul!(copy(sA), Diagonal(b))
b = randn(3)
@test Diagonal(b) * dA == Diagonal(b) * sA
@test Diagonal(b) * dA == mul!(sC, Diagonal(b), sA)
@test Diagonal(b) * dA == lmul!(Diagonal(b), copy(sA))
@test dA * 0.5 == sA * 0.5
@test dA * 0.5 == mul!(sC, sA, 0.5)
@test dA * 0.5 == rmul!(copy(sA), 0.5)
@test 0.5 * dA == 0.5 * sA
@test 0.5 * dA == mul!(sC, sA, 0.5)
@test 0.5 * dA == lmul!(0.5, copy(sA))
@test mul!(sC, 0.5, sA) == mul!(sC, sA, 0.5)
@testset "inverse scaling with mul!" begin
bi = inv.(b)
@test lmul!(Diagonal(bi), copy(dA)) ≈ ldiv!(Diagonal(b), copy(sA))
@test lmul!(Diagonal(bi), copy(dA)) ≈ ldiv!(transpose(Diagonal(b)), copy(sA))
@test lmul!(Diagonal(conj(bi)), copy(dA)) ≈ ldiv!(adjoint(Diagonal(b)), copy(sA))
@test_throws DimensionMismatch ldiv!(Diagonal(fill(1., length(b)+1)), copy(sA))
@test_throws LinearAlgebra.SingularException ldiv!(Diagonal(zeros(length(b))), copy(sA))
dAt = copy(transpose(dA))
sAt = copy(transpose(sA))
@test rmul!(copy(dAt), Diagonal(bi)) ≈ rdiv!(copy(sAt), Diagonal(b))
@test rmul!(copy(dAt), Diagonal(bi)) ≈ rdiv!(copy(sAt), transpose(Diagonal(b)))
@test rmul!(copy(dAt), Diagonal(conj(bi))) ≈ rdiv!(copy(sAt), adjoint(Diagonal(b)))
@test_throws DimensionMismatch rdiv!(copy(sAt), Diagonal(fill(1., length(b)+1)))
@test_throws LinearAlgebra.SingularException rdiv!(copy(sAt), Diagonal(zeros(length(b))))
end
@testset "non-commutative multiplication" begin
# non-commutative multiplication
Avals = Quaternion.(randn(10), randn(10), randn(10), randn(10))
sA = sparse(rand(1:3, 10), rand(1:7, 10), Avals, 3, 7)
sC = copy(sA)
dA = Array(sA)
b = Quaternion.(randn(7), randn(7), randn(7), randn(7))
D = Diagonal(b)
@test Array(sA * D) ≈ dA * D
@test rmul!(copy(sA), D) ≈ dA * D
@test mul!(sC, copy(sA), D) ≈ dA * D
b = Quaternion.(randn(3), randn(3), randn(3), randn(3))
D = Diagonal(b)
@test Array(D * sA) ≈ D * dA
@test lmul!(D, copy(sA)) ≈ D * dA
@test mul!(sC, D, copy(sA)) ≈ D * dA
end
end
@testset "copyto!" begin
A = sprand(5, 5, 0.2)
B = sprand(5, 5, 0.2)
copyto!(A, B)
@test A == B
@test pointer(A.nzval) != pointer(B.nzval)
@test pointer(A.rowval) != pointer(B.rowval)
@test pointer(A.colptr) != pointer(B.colptr)
# Test size(A) != size(B), but length(A) == length(B)
B = sprand(25, 1, 0.2)
copyto!(A, B)
@test A[:] == B[:]
# Test various size(A) / size(B) combinations
for mA in [5, 10, 20], nA in [5, 10, 20], mB in [5, 10, 20], nB in [5, 10, 20]
A = sprand(mA,nA,0.4)
Aorig = copy(A)
B = sprand(mB,nB,0.4)
if mA*nA >= mB*nB
copyto!(A,B)
@assert(A[1:length(B)] == B[:])
@assert(A[length(B)+1:end] == Aorig[length(B)+1:end])
else
@test_throws BoundsError copyto!(A,B)
end
end
# Test eltype(A) != eltype(B), size(A) != size(B)
A = sprand(5, 5, 0.2)
Aorig = copy(A)
B = sparse(rand(Float32, 3, 3))
copyto!(A, B)
@test A[1:9] == B[:]
@test A[10:end] == Aorig[10:end]
# Test eltype(A) != eltype(B), size(A) == size(B)
A = sparse(rand(Float64, 3, 3))
B = sparse(rand(Float32, 3, 3))
copyto!(A, B)
@test A == B
end
@testset "conj" begin
cA = sprandn(5,5,0.2) + im*sprandn(5,5,0.2)
@test Array(conj.(cA)) == conj(Array(cA))
@test Array(conj!(copy(cA))) == conj(Array(cA))
end
@testset "SparseMatrixCSC [c]transpose[!] and permute[!]" begin
smalldim = 5
largedim = 10
nzprob = 0.4
(m, n) = (smalldim, smalldim)
A = sprand(m, n, nzprob)
X = similar(A)
C = copy(transpose(A))
p = randperm(m)
q = randperm(n)
@testset "common error checking of [c]transpose! methods (ftranspose!)" begin
@test_throws DimensionMismatch transpose!(A[:, 1:(smalldim - 1)], A)
@test_throws DimensionMismatch transpose!(A[1:(smalldim - 1), 1], A)
@test_throws ArgumentError transpose!((B = similar(A); resize!(B.rowval, nnz(A) - 1); B), A)
@test_throws ArgumentError transpose!((B = similar(A); resize!(B.nzval, nnz(A) - 1); B), A)
end
@testset "common error checking of permute[!] methods / source-perm compat" begin
@test_throws DimensionMismatch permute(A, p[1:(end - 1)], q)
@test_throws DimensionMismatch permute(A, p, q[1:(end - 1)])
end
@testset "common error checking of permute[!] methods / source-dest compat" begin
@test_throws DimensionMismatch permute!(A[1:(m - 1), :], A, p, q)
@test_throws DimensionMismatch permute!(A[:, 1:(m - 1)], A, p, q)
@test_throws ArgumentError permute!((Y = copy(X); resize!(Y.rowval, nnz(A) - 1); Y), A, p, q)
@test_throws ArgumentError permute!((Y = copy(X); resize!(Y.nzval, nnz(A) - 1); Y), A, p, q)
end
@testset "common error checking of permute[!] methods / source-workmat compat" begin
@test_throws DimensionMismatch permute!(X, A, p, q, C[1:(m - 1), :])
@test_throws DimensionMismatch permute!(X, A, p, q, C[:, 1:(m - 1)])
@test_throws ArgumentError permute!(X, A, p, q, (D = copy(C); resize!(D.rowval, nnz(A) - 1); D))
@test_throws ArgumentError permute!(X, A, p, q, (D = copy(C); resize!(D.nzval, nnz(A) - 1); D))
end
@testset "common error checking of permute[!] methods / source-workcolptr compat" begin
@test_throws DimensionMismatch permute!(A, p, q, C, Vector{eltype(A.rowval)}(undef, length(A.colptr) - 1))
end
@testset "common error checking of permute[!] methods / permutation validity" begin
@test_throws ArgumentError permute!(A, (r = copy(p); r[2] = r[1]; r), q)
@test_throws ArgumentError permute!(A, (r = copy(p); r[2] = m + 1; r), q)
@test_throws ArgumentError permute!(A, p, (r = copy(q); r[2] = r[1]; r))
@test_throws ArgumentError permute!(A, p, (r = copy(q); r[2] = n + 1; r))
end
@testset "overall functionality of [c]transpose[!] and permute[!]" begin
for (m, n) in ((smalldim, smalldim), (smalldim, largedim), (largedim, smalldim))
A = sprand(m, n, nzprob)
At = copy(transpose(A))
# transpose[!]
fullAt = Array(transpose(A))
@test copy(transpose(A)) == fullAt
@test transpose!(similar(At), A) == fullAt
# adjoint[!]
C = A + im*A/2
fullCh = Array(C')
@test copy(C') == fullCh
@test adjoint!(similar(sparse(fullCh)), C) == fullCh
# permute[!]
p = randperm(m)
q = randperm(n)
fullPAQ = Array(A)[p,q]
@test permute(A, p, q) == sparse(Array(A[p,q]))
@test permute!(similar(A), A, p, q) == fullPAQ
@test permute!(similar(A), A, p, q, similar(At)) == fullPAQ
@test permute!(copy(A), p, q) == fullPAQ
@test permute!(copy(A), p, q, similar(At)) == fullPAQ
@test permute!(copy(A), p, q, similar(At), similar(A.colptr)) == fullPAQ
end
end
end
@testset "transpose of SubArrays" begin
A = view(sprandn(10, 10, 0.3), 1:4, 1:4)
@test copy(transpose(Array(A))) == Array(transpose(A))
@test copy(adjoint(Array(A))) == Array(adjoint(A))
end
@testset "exp" begin
A = sprandn(5,5,0.2)
@test ℯ.^A ≈ ℯ.^Array(A)
end
@testset "reductions" begin
pA = sparse(rand(3, 7))
p28227 = sparse(Real[0 0.5])
for arr in (se33, sA, pA, p28227)
for f in (sum, prod, minimum, maximum)
farr = Array(arr)
@test f(arr) ≈ f(farr)
@test f(arr, dims=1) ≈ f(farr, dims=1)
@test f(arr, dims=2) ≈ f(farr, dims=2)
@test f(arr, dims=(1, 2)) ≈ [f(farr)]
@test isequal(f(arr, dims=3), f(farr, dims=3))
end
end
for f in (sum, prod, minimum, maximum)
# Test with a map function that maps to non-zero
for arr in (se33, sA, pA)
@test f(x->x+1, arr) ≈ f(arr .+ 1)
end
# case where f(0) would throw
@test f(x->sqrt(x-1), pA .+ 1) ≈ f(sqrt.(pA))
# these actually throw due to #10533
# @test f(x->sqrt(x-1), pA .+ 1, dims=1) ≈ f(sqrt(pA), dims=1)
# @test f(x->sqrt(x-1), pA .+ 1, dims=2) ≈ f(sqrt(pA), dims=2)
# @test f(x->sqrt(x-1), pA .+ 1, dims=3) ≈ f(pA)
end
@testset "empty cases" begin
@test sum(sparse(Int[])) === 0
@test prod(sparse(Int[])) === 1
@test_throws ArgumentError minimum(sparse(Int[]))
@test_throws ArgumentError maximum(sparse(Int[]))
for f in (sum, prod)
@test isequal(f(spzeros(0, 1), dims=1), f(Matrix{Int}(I, 0, 1), dims=1))
@test isequal(f(spzeros(0, 1), dims=2), f(Matrix{Int}(I, 0, 1), dims=2))
@test isequal(f(spzeros(0, 1), dims=(1, 2)), f(Matrix{Int}(I, 0, 1), dims=(1, 2)))
@test isequal(f(spzeros(0, 1), dims=3), f(Matrix{Int}(I, 0, 1), dims=3))
end
for f in (minimum, maximum, findmin, findmax)
@test_throws ArgumentError f(spzeros(0, 1), dims=1)
@test isequal(f(spzeros(0, 1), dims=2), f(Matrix{Int}(I, 0, 1), dims=2))
@test_throws ArgumentError f(spzeros(0, 1), dims=(1, 2))
@test isequal(f(spzeros(0, 1), dims=3), f(Matrix{Int}(I, 0, 1), dims=3))
end
end
end
@testset "issue #5190" begin
@test_throws ArgumentError sparsevec([3,5,7],[0.1,0.0,3.2],4)
end
@testset "what used to be issue #5386" begin
K,J,V = findnz(SparseMatrixCSC(2,1,[1,3],[1,2],[1.0,0.0]))
@test length(K) == length(J) == length(V) == 2
end
@testset "findall" begin
# issue described in https://groups.google.com/d/msg/julia-users/Yq4dh8NOWBQ/GU57L90FZ3EJ
A = sparse(I, 5, 5)
@test findall(A) == findall(x -> x == true, A) == findall(Array(A))
# Non-stored entries are true
@test findall(x -> x == false, A) == findall(x -> x == false, Array(A))
# Not all stored entries are true
@test findall(sparse([true false])) == [CartesianIndex(1, 1)]
@test findall(x -> x > 1, sparse([1 2])) == [CartesianIndex(1, 2)]
end
@testset "issue #5824" begin
@test sprand(4,5,0.5).^0 == sparse(fill(1,4,5))
end
@testset "issue #5985" begin
@test sprand(Bool, 4, 5, 0.0) == sparse(zeros(Bool, 4, 5))
@test sprand(Bool, 4, 5, 1.00) == sparse(fill(true, 4, 5))
sprb45nnzs = zeros(5)
for i=1:5
sprb45 = sprand(Bool, 4, 5, 0.5)
@test length(sprb45) == 20
sprb45nnzs[i] = sum(sprb45)[1]
end
@test 4 <= sum(sprb45nnzs)/length(sprb45nnzs) <= 16
end
@testset "issue #5853, sparse diff" begin
for i=1:2, a=Any[[1 2 3], reshape([1, 2, 3],(3,1)), Matrix(1.0I, 3, 3)]
@test diff(sparse(a),dims=i) == diff(a,dims=i)
end
end
@testset "access to undefined error types that initially allocate elements as #undef" begin
@test sparse(1:2, 1:2, Number[1,2])^2 == sparse(1:2, 1:2, [1,4])
sd1 = diff(sparse([1,1,1], [1,2,3], Number[1,2,3]), dims=1)
end
@testset "issue #6036" begin
P = spzeros(Float64, 3, 3)
for i = 1:3
P[i,i] = i
end
@test minimum(P) === 0.0
@test maximum(P) === 3.0
@test minimum(-P) === -3.0
@test maximum(-P) === 0.0
@test maximum(P, dims=(1,)) == [1.0 2.0 3.0]
@test maximum(P, dims=(2,)) == reshape([1.0,2.0,3.0],3,1)
@test maximum(P, dims=(1,2)) == reshape([3.0],1,1)
@test maximum(sparse(fill(-1,3,3))) == -1
@test minimum(sparse(fill(1,3,3))) == 1
end
@testset "unary functions" begin
A = sprand(5, 15, 0.5)
C = A + im*A
Afull = Array(A)
Cfull = Array(C)
# Test representatives of [unary functions that map zeros to zeros and may map nonzeros to zeros]
@test sin.(Afull) == Array(sin.(A))
@test tan.(Afull) == Array(tan.(A)) # should be redundant with sin test
@test ceil.(Afull) == Array(ceil.(A))
@test floor.(Afull) == Array(floor.(A)) # should be redundant with ceil test
@test real.(Afull) == Array(real.(A)) == Array(real(A))
@test imag.(Afull) == Array(imag.(A)) == Array(imag(A))
@test conj.(Afull) == Array(conj.(A)) == Array(conj(A))
@test real.(Cfull) == Array(real.(C)) == Array(real(C))
@test imag.(Cfull) == Array(imag.(C)) == Array(imag(C))
@test conj.(Cfull) == Array(conj.(C)) == Array(conj(C))
# Test representatives of [unary functions that map zeros to zeros and nonzeros to nonzeros]
@test expm1.(Afull) == Array(expm1.(A))
@test abs.(Afull) == Array(abs.(A))
@test abs2.(Afull) == Array(abs2.(A))
@test abs.(Cfull) == Array(abs.(C))
@test abs2.(Cfull) == Array(abs2.(C))
# Test representatives of [unary functions that map both zeros and nonzeros to nonzeros]
@test cos.(Afull) == Array(cos.(A))
# Test representatives of remaining vectorized-nonbroadcast unary functions
@test ceil.(Int, Afull) == Array(ceil.(Int, A))
@test floor.(Int, Afull) == Array(floor.(Int, A))
# Tests of real, imag, abs, and abs2 for SparseMatrixCSC{Int,X}s previously elsewhere
for T in (Int, Float16, Float32, Float64, BigInt, BigFloat)
R = rand(T[1:100;], 2, 2)
I = rand(T[1:100;], 2, 2)
D = R + I*im
S = sparse(D)
spR = sparse(R)
@test R == real.(S) == real(S)
@test I == imag.(S) == imag(S)
@test conj(Array(S)) == conj.(S) == conj(S)
@test real.(spR) == R
@test nnz(imag.(spR)) == nnz(imag(spR)) == 0
@test abs.(S) == abs.(D)
@test abs2.(S) == abs2.(D)
# test aliasing of real and conj of real valued matrix
@test real(spR) === spR
@test conj(spR) === spR
end
end
@testset "getindex" begin
ni = 23
nj = 32
a116 = reshape(1:(ni*nj), ni, nj)
s116 = sparse(a116)
ad116 = diagm(0 => diag(a116))
sd116 = sparse(ad116)
for (aa116, ss116) in [(a116, s116), (ad116, sd116)]
ij=11; i=3; j=2
@test ss116[ij] == aa116[ij]
@test ss116[(i,j)] == aa116[i,j]
@test ss116[i,j] == aa116[i,j]
@test ss116[i-1,j] == aa116[i-1,j]
ss116[i,j] = 0
@test ss116[i,j] == 0
ss116 = sparse(aa116)
@test ss116[:,:] == copy(ss116)
@test convert(SparseMatrixCSC{Float32,Int32}, sd116)[2:5,:] == convert(SparseMatrixCSC{Float32,Int32}, sd116[2:5,:])
# range indexing
@test Array(ss116[i,:]) == aa116[i,:]
@test Array(ss116[:,j]) == aa116[:,j]
@test Array(ss116[i,1:2:end]) == aa116[i,1:2:end]
@test Array(ss116[1:2:end,j]) == aa116[1:2:end,j]
@test Array(ss116[i,end:-2:1]) == aa116[i,end:-2:1]
@test Array(ss116[end:-2:1,j]) == aa116[end:-2:1,j]
# float-range indexing is not supported
# sorted vector indexing
@test Array(ss116[i,[3:2:end-3;]]) == aa116[i,[3:2:end-3;]]
@test Array(ss116[[3:2:end-3;],j]) == aa116[[3:2:end-3;],j]
@test Array(ss116[i,[end-3:-2:1;]]) == aa116[i,[end-3:-2:1;]]
@test Array(ss116[[end-3:-2:1;],j]) == aa116[[end-3:-2:1;],j]
# unsorted vector indexing with repetition
p = [4, 1, 2, 3, 2, 6]
@test Array(ss116[p,:]) == aa116[p,:]
@test Array(ss116[:,p]) == aa116[:,p]
@test Array(ss116[p,p]) == aa116[p,p]
# bool indexing
li = bitrand(size(aa116,1))
lj = bitrand(size(aa116,2))
@test Array(ss116[li,j]) == aa116[li,j]
@test Array(ss116[li,:]) == aa116[li,:]
@test Array(ss116[i,lj]) == aa116[i,lj]
@test Array(ss116[:,lj]) == aa116[:,lj]
@test Array(ss116[li,lj]) == aa116[li,lj]
# empty indices
for empty in (1:0, Int[])
@test Array(ss116[empty,:]) == aa116[empty,:]
@test Array(ss116[:,empty]) == aa116[:,empty]
@test Array(ss116[empty,lj]) == aa116[empty,lj]
@test Array(ss116[li,empty]) == aa116[li,empty]
@test Array(ss116[empty,empty]) == aa116[empty,empty]
end
# out of bounds indexing
@test_throws BoundsError ss116[0, 1]
@test_throws BoundsError ss116[end+1, 1]
@test_throws BoundsError ss116[1, 0]
@test_throws BoundsError ss116[1, end+1]
for j in (1, 1:size(s116,2), 1:1, Int[1], trues(size(s116, 2)), 1:0, Int[])
@test_throws BoundsError ss116[0:1, j]
@test_throws BoundsError ss116[[0, 1], j]
@test_throws BoundsError ss116[end:end+1, j]
@test_throws BoundsError ss116[[end, end+1], j]
end
for i in (1, 1:size(s116,1), 1:1, Int[1], trues(size(s116, 1)), 1:0, Int[])
@test_throws BoundsError ss116[i, 0:1]
@test_throws BoundsError ss116[i, [0, 1]]
@test_throws BoundsError ss116[i, end:end+1]
@test_throws BoundsError ss116[i, [end, end+1]]
end
end
# workaround issue #7197: comment out let-block
#let S = SparseMatrixCSC(3, 3, UInt8[1,1,1,1], UInt8[], Int64[])
S1290 = SparseMatrixCSC(3, 3, UInt8[1,1,1,1], UInt8[], Int64[])
S1290[1,1] = 1
S1290[5] = 2
S1290[end] = 3
@test S1290[end] == (S1290[1] + S1290[2,2])
@test 6 == sum(diag(S1290))
@test Array(S1290)[[3,1],1] == Array(S1290[[3,1],1])
# check that indexing with an abstract array returns matrix
# with same colptr and rowval eltypes as input. Tests PR 24548
r1 = S1290[[5,9]]
r2 = S1290[[1 2;5 9]]
@test isa(r1, SparseVector{Int64,UInt8})
@test isa(r2, SparseMatrixCSC{Int64,UInt8})
# end
end
@testset "setindex" begin
a = spzeros(Int, 10, 10)
@test count(!iszero, a) == 0
a[1,:] .= 1
@test count(!iszero, a) == 10
@test a[1,:] == sparse(fill(1,10))
a[:,2] .= 2
@test count(!iszero, a) == 19
@test a[:,2] == sparse(fill(2,10))
b = copy(a)
# Zero-assignment behavior of setindex!(A, v, i, j)
a[1,3] = 0
@test nnz(a) == 19
@test count(!iszero, a) == 18
a[2,1] = 0
@test nnz(a) == 19
@test count(!iszero, a) == 18
# Zero-assignment behavior of setindex!(A, v, I, J)
a[1,:] .= 0
@test nnz(a) == 19
@test count(!iszero, a) == 9
a[2,:] .= 0
@test nnz(a) == 19
@test count(!iszero, a) == 8
a[:,1] .= 0
@test nnz(a) == 19
@test count(!iszero, a) == 8
a[:,2] .= 0
@test nnz(a) == 19
@test count(!iszero, a) == 0
a = copy(b)
a[:,:] .= 0
@test nnz(a) == 19
@test count(!iszero, a) == 0
# Zero-assignment behavior of setindex!(A, B::SparseMatrixCSC, I, J)
a = copy(b)
a[1:2,:] = spzeros(2, 10)
@test nnz(a) == 19
@test count(!iszero, a) == 8
a[1:2,1:3] = sparse([1 0 1; 0 0 1])
@test nnz(a) == 20
@test count(!iszero, a) == 11
a = copy(b)
a[1:2,:] = let c = sparse(fill(1,2,10)); fill!(c.nzval, 0); c; end
@test nnz(a) == 19
@test count(!iszero, a) == 8
a[1:2,1:3] = let c = sparse(fill(1,2,3)); c[1,2] = c[2,1] = c[2,2] = 0; c; end
@test nnz(a) == 20
@test count(!iszero, a) == 11
a[1,:] = 1:10
@test a[1,:] == sparse([1:10;])
a[:,2] = 1:10
@test a[:,2] == sparse([1:10;])
a[1,1:0] = []
@test a[1,:] == sparse([1; 1; 3:10])
a[1:0,2] = []
@test a[:,2] == sparse([1:10;])
a[1,1:0] .= 0
@test a[1,:] == sparse([1; 1; 3:10])
a[1:0,2] .= 0
@test a[:,2] == sparse([1:10;])
a[1,1:0] .= 1
@test a[1,:] == sparse([1; 1; 3:10])
a[1:0,2] .= 1
@test a[:,2] == sparse([1:10;])
@test_throws BoundsError a[:,11] = spzeros(10,1)
@test_throws BoundsError a[11,:] = spzeros(1,10)
@test_throws BoundsError a[:,-1] = spzeros(10,1)
@test_throws BoundsError a[-1,:] = spzeros(1,10)
@test_throws BoundsError a[0:9] = spzeros(1,10)
@test_throws BoundsError (a[:,11] .= 0; a)
@test_throws BoundsError (a[11,:] .= 0; a)
@test_throws BoundsError (a[:,-1] .= 0; a)
@test_throws BoundsError (a[-1,:] .= 0; a)
@test_throws BoundsError (a[0:9] .= 0; a)
@test_throws BoundsError (a[:,11] .= 1; a)
@test_throws BoundsError (a[11,:] .= 1; a)
@test_throws BoundsError (a[:,-1] .= 1; a)
@test_throws BoundsError (a[-1,:] .= 1; a)
@test_throws BoundsError (a[0:9] .= 1; a)
@test_throws DimensionMismatch a[1:2,1:2] = 1:3
@test_throws DimensionMismatch a[1:2,1] = 1:3
@test_throws DimensionMismatch a[1,1:2] = 1:3
@test_throws DimensionMismatch a[1:2] = 1:3
A = spzeros(Int, 10, 20)
A[1:5,1:10] .= 10
A[1:5,1:10] .= 10
@test count(!iszero, A) == 50
@test A[1:5,1:10] == fill(10, 5, 10)
A[6:10,11:20] .= 0
@test count(!iszero, A) == 50
A[6:10,11:20] .= 20
@test count(!iszero, A) == 100
@test A[6:10,11:20] == fill(20, 5, 10)
A[4:8,8:16] .= 15
@test count(!iszero, A) == 121
@test A[4:8,8:16] == fill(15, 5, 9)
ASZ = 1000
TSZ = 800
A = sprand(ASZ, 2*ASZ, 0.0001)
B = copy(A)
nA = count(!iszero, A)
x = A[1:TSZ, 1:(2*TSZ)]
nx = count(!iszero, x)
A[1:TSZ, 1:(2*TSZ)] .= 0
nB = count(!iszero, A)
@test nB == (nA - nx)
A[1:TSZ, 1:(2*TSZ)] = x
@test count(!iszero, A) == nA
@test A == B
A[1:TSZ, 1:(2*TSZ)] .= 10
@test count(!iszero, A) == nB + 2*TSZ*TSZ
A[1:TSZ, 1:(2*TSZ)] = x
@test count(!iszero, A) == nA
@test A == B
A = sparse(1I, 5, 5)
lininds = 1:10
X=reshape([trues(10); falses(15)],5,5)
@test A[lininds] == A[X] == [1,0,0,0,0,0,1,0,0,0]
A[lininds] = [1:10;]
@test A[lininds] == A[X] == 1:10
A[lininds] = zeros(Int, 10)
@test nnz(A) == 13
@test count(!iszero, A) == 3
@test A[lininds] == A[X] == zeros(Int, 10)
c = Vector(11:20); c[1] = c[3] = 0
A[lininds] = c
@test nnz(A) == 13
@test count(!iszero, A) == 11
@test A[lininds] == A[X] == c
A = sparse(1I, 5, 5)
A[lininds] = c
@test nnz(A) == 12
@test count(!iszero, A) == 11
@test A[lininds] == A[X] == c
let # prevent assignment to I from overwriting UniformSampling in enclosing scope
S = sprand(50, 30, 0.5, x -> round.(Int, rand(x) * 100))
I = sprand(Bool, 50, 30, 0.2)
FS = Array(S)
FI = Array(I)
@test sparse(FS[FI]) == S[I] == S[FI]
@test sum(S[FI]) + sum(S[.!FI]) == sum(S)
@test count(!iszero, I) == count(I)
sumS1 = sum(S)
sumFI = sum(S[FI])
nnzS1 = nnz(S)
S[FI] .= 0
sumS2 = sum(S)
cnzS2 = count(!iszero, S)
@test sum(S[FI]) == 0
@test nnz(S) == nnzS1
@test (sum(S) + sumFI) == sumS1
S[FI] .= 10
nnzS3 = nnz(S)
@test sum(S) == sumS2 + 10*sum(FI)
S[FI] .= 0
@test sum(S) == sumS2
@test nnz(S) == nnzS3
@test count(!iszero, S) == cnzS2
S[FI] .= [1:sum(FI);]
@test sum(S) == sumS2 + sum(1:sum(FI))
S = sprand(50, 30, 0.5, x -> round.(Int, rand(x) * 100))
N = length(S) >> 2
I = randperm(N) .* 4
J = randperm(N)
sumS1 = sum(S)
sumS2 = sum(S[I])
S[I] .= 0
@test sum(S) == (sumS1 - sumS2)
S[I] .= J
@test sum(S) == (sumS1 - sumS2 + sum(J))
end
end
@testset "dropstored!" begin
A = spzeros(Int, 10, 10)
# Introduce nonzeros in row and column two
A[1,:] .= 1
A[:,2] .= 2
@test nnz(A) == 19
# Test argument bounds checking for dropstored!(A, i, j)
@test_throws BoundsError SparseArrays.dropstored!(A, 0, 1)
@test_throws BoundsError SparseArrays.dropstored!(A, 1, 0)
@test_throws BoundsError SparseArrays.dropstored!(A, 1, 11)
@test_throws BoundsError SparseArrays.dropstored!(A, 11, 1)
# Test argument bounds checking for dropstored!(A, I, J)
@test_throws BoundsError SparseArrays.dropstored!(A, 0:1, 1:1)
@test_throws BoundsError SparseArrays.dropstored!(A, 1:1, 0:1)
@test_throws BoundsError SparseArrays.dropstored!(A, 10:11, 1:1)
@test_throws BoundsError SparseArrays.dropstored!(A, 1:1, 10:11)
# Test behavior of dropstored!(A, i, j)
# --> Test dropping a single stored entry
SparseArrays.dropstored!(A, 1, 2)
@test nnz(A) == 18
# --> Test dropping a single nonstored entry
SparseArrays.dropstored!(A, 2, 1)
@test nnz(A) == 18
# Test behavior of dropstored!(A, I, J) and derivs.
# --> Test dropping a single row including stored and nonstored entries
SparseArrays.dropstored!(A, 1, :)
@test nnz(A) == 9
# --> Test dropping a single column including stored and nonstored entries
SparseArrays.dropstored!(A, :, 2)
@test nnz(A) == 0
# --> Introduce nonzeros in rows one and two and columns two and three
A[1:2,:] .= 1
A[:,2:3] .= 2
@test nnz(A) == 36
# --> Test dropping multiple rows containing stored and nonstored entries
SparseArrays.dropstored!(A, 1:3, :)
@test nnz(A) == 14
# --> Test dropping multiple columns containing stored and nonstored entries
SparseArrays.dropstored!(A, :, 2:4)
@test nnz(A) == 0
# --> Introduce nonzeros in every other row
A[1:2:9, :] .= 1
@test nnz(A) == 50
# --> Test dropping a block of the matrix towards the upper left
SparseArrays.dropstored!(A, 2:5, 2:5)
@test nnz(A) == 42
end
@testset "issue #7507" begin
@test (i7507=sparsevec(Dict{Int64, Float64}(), 10))==spzeros(10)
end
@testset "issue #7650" begin
S = spzeros(3, 3)
@test size(reshape(S, 9, 1)) == (9,1)
end
@testset "sparsevec from matrices" begin
X = Matrix(1.0I, 5, 5)
M = rand(5,4)
C = spzeros(3,3)
SX = sparse(X); SM = sparse(M)
VX = vec(X); VSX = vec(SX)
VM = vec(M); VSM1 = vec(SM); VSM2 = sparsevec(M)
VC = vec(C)
@test VX == VSX
@test VM == VSM1
@test VM == VSM2
@test size(VC) == (9,)
@test nnz(VC) == 0
@test nnz(VSX) == 5
end
@testset "issue #7677" begin
A = sprand(5,5,0.5,(n)->rand(Float64,n))
ACPY = copy(A)
B = reshape(A,25,1)
@test A == ACPY
end
@testset "issue #8225" begin
@test_throws ArgumentError sparse([0],[-1],[1.0],2,2)
end
@testset "issue #8363" begin
@test_throws ArgumentError sparsevec(Dict(-1=>1,1=>2))
end
@testset "issue #8976" begin
@test conj.(sparse([1im])) == sparse(conj([1im]))
@test conj!(sparse([1im])) == sparse(conj!([1im]))
end
@testset "issue #9525" begin
@test_throws ArgumentError sparse([3], [5], 1.0, 3, 3)
end
@testset "argmax, argmin, findmax, findmin" begin
S = sprand(100,80, 0.5)
A = Array(S)
@test argmax(S) == argmax(A)
@test argmin(S) == argmin(A)
@test findmin(S) == findmin(A)
@test findmax(S) == findmax(A)
for region in [(1,), (2,), (1,2)], m in [findmax, findmin]
@test m(S, dims=region) == m(A, dims=region)
end
S = spzeros(10,8)
A = Array(S)
@test argmax(S) == argmax(A) == CartesianIndex(1,1)
@test argmin(S) == argmin(A) == CartesianIndex(1,1)
A = Matrix{Int}(I, 0, 0)
S = sparse(A)
iA = try argmax(A); catch; end
iS = try argmax(S); catch; end
@test iA === iS === nothing
iA = try argmin(A); catch; end
iS = try argmin(S); catch; end
@test iA === iS === nothing
end
@testset "findmin/findmax/minimum/maximum" begin
A = sparse([1.0 5.0 6.0;
5.0 2.0 4.0])
for (tup, rval, rind) in [((1,), [1.0 2.0 4.0], [CartesianIndex(1,1) CartesianIndex(2,2) CartesianIndex(2,3)]),
((2,), reshape([1.0,2.0], 2, 1), reshape([CartesianIndex(1,1),CartesianIndex(2,2)], 2, 1)),
((1,2), fill(1.0,1,1),fill(CartesianIndex(1,1),1,1))]
@test findmin(A, tup) == (rval, rind)
end
for (tup, rval, rind) in [((1,), [5.0 5.0 6.0], [CartesianIndex(2,1) CartesianIndex(1,2) CartesianIndex(1,3)]),
((2,), reshape([6.0,5.0], 2, 1), reshape([CartesianIndex(1,3),CartesianIndex(2,1)], 2, 1)),
((1,2), fill(6.0,1,1),fill(CartesianIndex(1,3),1,1))]
@test findmax(A, tup) == (rval, rind)
end
#issue 23209
A = sparse([1.0 5.0 6.0;
NaN 2.0 4.0])
for (tup, rval, rind) in [((1,), [NaN 2.0 4.0], [CartesianIndex(2,1) CartesianIndex(2,2) CartesianIndex(2,3)]),
((2,), reshape([1.0, NaN], 2, 1), reshape([CartesianIndex(1,1),CartesianIndex(2,1)], 2, 1)),
((1,2), fill(NaN,1,1),fill(CartesianIndex(2,1),1,1))]
@test isequal(findmin(A, tup), (rval, rind))
end
for (tup, rval, rind) in [((1,), [NaN 5.0 6.0], [CartesianIndex(2,1) CartesianIndex(1,2) CartesianIndex(1,3)]),
((2,), reshape([6.0, NaN], 2, 1), reshape([CartesianIndex(1,3),CartesianIndex(2,1)], 2, 1)),
((1,2), fill(NaN,1,1),fill(CartesianIndex(2,1),1,1))]
@test isequal(findmax(A, tup), (rval, rind))
end
A = sparse([1.0 NaN 6.0;
NaN 2.0 4.0])
for (tup, rval, rind) in [((1,), [NaN NaN 4.0], [CartesianIndex(2,1) CartesianIndex(1,2) CartesianIndex(2,3)]),
((2,), reshape([NaN, NaN], 2, 1), reshape([CartesianIndex(1,2),CartesianIndex(2,1)], 2, 1)),
((1,2), fill(NaN,1,1),fill(CartesianIndex(2,1),1,1))]
@test isequal(findmin(A, tup), (rval, rind))
end
for (tup, rval, rind) in [((1,), [NaN NaN 6.0], [CartesianIndex(2,1) CartesianIndex(1,2) CartesianIndex(1,3)]),
((2,), reshape([NaN, NaN], 2, 1), reshape([CartesianIndex(1,2),CartesianIndex(2,1)], 2, 1)),
((1,2), fill(NaN,1,1),fill(CartesianIndex(2,1),1,1))]
@test isequal(findmax(A, tup), (rval, rind))
end
A = sparse([Inf -Inf Inf -Inf;
Inf Inf -Inf -Inf])
for (tup, rval, rind) in [((1,), [Inf -Inf -Inf -Inf], [CartesianIndex(1,1) CartesianIndex(1,2) CartesianIndex(2,3) CartesianIndex(1,4)]),
((2,), reshape([-Inf -Inf], 2, 1), reshape([CartesianIndex(1,2),CartesianIndex(2,3)], 2, 1)),
((1,2), fill(-Inf,1,1),fill(CartesianIndex(1,2),1,1))]
@test isequal(findmin(A, tup), (rval, rind))
end
for (tup, rval, rind) in [((1,), [Inf Inf Inf -Inf], [CartesianIndex(1,1) CartesianIndex(2,2) CartesianIndex(1,3) CartesianIndex(1,4)]),
((2,), reshape([Inf Inf], 2, 1), reshape([CartesianIndex(1,1),CartesianIndex(2,1)], 2, 1)),
((1,2), fill(Inf,1,1),fill(CartesianIndex(1,1),1,1))]
@test isequal(findmax(A, tup), (rval, rind))
end
A = sparse([BigInt(10)])
for (tup, rval, rind) in [((2,), [BigInt(10)], [1])]
@test isequal(findmin(A, dims=tup), (rval, rind))
end
for (tup, rval, rind) in [((2,), [BigInt(10)], [1])]
@test isequal(findmax(A, dims=tup), (rval, rind))
end
A = sparse([BigInt(-10)])
for (tup, rval, rind) in [((2,), [BigInt(-10)], [1])]
@test isequal(findmin(A, dims=tup), (rval, rind))
end
for (tup, rval, rind) in [((2,), [BigInt(-10)], [1])]
@test isequal(findmax(A, dims=tup), (rval, rind))
end
A = sparse([BigInt(10) BigInt(-10)])
for (tup, rval, rind) in [((2,), reshape([BigInt(-10)], 1, 1), reshape([CartesianIndex(1,2)], 1, 1))]
@test isequal(findmin(A, dims=tup), (rval, rind))
end
for (tup, rval, rind) in [((2,), reshape([BigInt(10)], 1, 1), reshape([CartesianIndex(1,1)], 1, 1))]
@test isequal(findmax(A, dims=tup), (rval, rind))
end
A = sparse(["a", "b"])
@test_throws MethodError findmin(A, dims=1)
end
# Support the case when user defined `zero` and `isless` for non-numerical type
struct CustomType
x::String
end
Base.zero(::Type{CustomType}) = CustomType("")
Base.isless(x::CustomType, y::CustomType) = isless(x.x, y.x)
@testset "findmin/findmax for non-numerical type" begin
A = sparse([CustomType("a"), CustomType("b")])
for (tup, rval, rind) in [((1,), [CustomType("a")], [1])]
@test isequal(findmin(A, dims=tup), (rval, rind))
end
for (tup, rval, rind) in [((1,), [CustomType("b")], [2])]
@test isequal(findmax(A, dims=tup), (rval, rind))
end
end
@testset "rotations" begin
a = sparse( [1,1,2,3], [1,3,4,1], [1,2,3,4] )
@test rot180(a,2) == a
@test rot180(a,1) == sparse( [3,3,2,1], [4,2,1,4], [1,2,3,4] )
@test rotr90(a,1) == sparse( [1,3,4,1], [3,3,2,1], [1,2,3,4] )
@test rotl90(a,1) == sparse( [4,2,1,4], [1,1,2,3], [1,2,3,4] )
@test rotl90(a,2) == rot180(a)
@test rotr90(a,2) == rot180(a)
@test rotl90(a,3) == rotr90(a)
@test rotr90(a,3) == rotl90(a)
#ensure we have preserved the correct dimensions!
a = sparse(1.0I, 3, 5)
@test size(rot180(a)) == (3,5)
@test size(rotr90(a)) == (5,3)
@test size(rotl90(a)) == (5,3)
end
function test_getindex_algs(A::SparseMatrixCSC{Tv,Ti}, I::AbstractVector, J::AbstractVector, alg::Int) where {Tv,Ti}
# Sorted vectors for indexing rows.
# Similar to getindex_general but without the transpose trick.
(m, n) = size(A)
!isempty(I) && ((I[1] < 1) || (I[end] > m)) && BoundsError()
if !isempty(J)
minj, maxj = extrema(J)
((minj < 1) || (maxj > n)) && BoundsError()
end
(alg == 0) ? SparseArrays.getindex_I_sorted_bsearch_A(A, I, J) :
(alg == 1) ? SparseArrays.getindex_I_sorted_bsearch_I(A, I, J) :
SparseArrays.getindex_I_sorted_linear(A, I, J)
end
@testset "test_getindex_algs" begin
M=2^14
N=2^4
Irand = randperm(M)
Jrand = randperm(N)
SA = [sprand(M, N, d) for d in [1., 0.1, 0.01, 0.001, 0.0001, 0.]]
IA = [sort(Irand[1:round(Int,n)]) for n in [M, M*0.1, M*0.01, M*0.001, M*0.0001, 0.]]
debug = false
if debug
println("row sizes: $([round(Int,nnz(S)/S.n) for S in SA])")
println("I sizes: $([length(I) for I in IA])")
@printf(" S | I | binary S | binary I | linear | best\n")
end
J = Jrand
for I in IA
for S in SA
res = Any[1,2,3]
times = Float64[0,0,0]
best = [typemax(Float64), 0]
for searchtype in [0, 1, 2]
GC.gc()
tres = @timed test_getindex_algs(S, I, J, searchtype)
res[searchtype+1] = tres[1]
times[searchtype+1] = tres[2]
if best[1] > tres[2]
best[1] = tres[2]
best[2] = searchtype
end
end
if debug
@printf(" %7d | %7d | %4.2e | %4.2e | %4.2e | %s\n", round(Int,nnz(S)/S.n), length(I), times[1], times[2], times[3],
(0 == best[2]) ? "binary S" : (1 == best[2]) ? "binary I" : "linear")
end
if res[1] != res[2]
println("1 and 2")
elseif res[2] != res[3]
println("2, 3")
end
@test res[1] == res[2] == res[3]
end
end
M = 2^8
N=2^3
Irand = randperm(M)
Jrand = randperm(N)
II = sort([Irand; Irand; Irand])
J = [Jrand; Jrand]
SA = [sprand(M, N, d) for d in [1., 0.1, 0.01, 0.001, 0.0001, 0.]]
for S in SA
res = Any[1,2,3]
for searchtype in [0, 1, 2]
res[searchtype+1] = test_getindex_algs(S, II, J, searchtype)
end
@test res[1] == res[2] == res[3]
end
M = 2^14
N=2^4
II = randperm(M)
J = randperm(N)
Jsorted = sort(J)
SA = [sprand(M, N, d) for d in [1., 0.1, 0.01, 0.001, 0.0001, 0.]]
IA = [II[1:round(Int,n)] for n in [M, M*0.1, M*0.01, M*0.001, M*0.0001, 0.]]
debug = false
if debug
@printf(" | | | times | memory |\n")
@printf(" S | I | J | sorted | unsorted | sorted | unsorted |\n")
end
for I in IA
Isorted = sort(I)
for S in SA
GC.gc()
ru = @timed S[I, J]
GC.gc()
rs = @timed S[Isorted, Jsorted]
if debug
@printf(" %7d | %7d | %7d | %4.2e | %4.2e | %4.2e | %4.2e |\n", round(Int,nnz(S)/S.n), length(I), length(J), rs[2], ru[2], rs[3], ru[3])
end
end
end
end
@testset "getindex bounds checking" begin
S = sprand(10, 10, 0.1)
@test_throws BoundsError S[[0,1,2], [1,2]]
@test_throws BoundsError S[[1,2], [0,1,2]]
@test_throws BoundsError S[[0,2,1], [1,2]]
@test_throws BoundsError S[[2,1], [0,1,2]]
end
@testset "test that sparse / sparsevec constructors work for AbstractMatrix subtypes" begin
D = Diagonal(fill(1,10))
sm = sparse(D)
sv = sparsevec(D)
@test count(!iszero, sm) == 10
@test count(!iszero, sv) == 10
@test count(!iszero, sparse(Diagonal(Int[]))) == 0
@test count(!iszero, sparsevec(Diagonal(Int[]))) == 0
end
@testset "explicit zeros" begin
if Base.USE_GPL_LIBS
a = SparseMatrixCSC(2, 2, [1, 3, 5], [1, 2, 1, 2], [1.0, 0.0, 0.0, 1.0])
@test lu(a)\[2.0, 3.0] ≈ [2.0, 3.0]
@test cholesky(a)\[2.0, 3.0] ≈ [2.0, 3.0]
end
end
@testset "issue #9917" begin
@test sparse([]') == reshape(sparse([]), 1, 0)
@test Array(sparse([])) == zeros(0)
@test_throws BoundsError sparse([])[1]
@test_throws BoundsError sparse([])[1] = 1
x = sparse(1.0I, 100, 100)
@test_throws BoundsError x[-10:10]
end
@testset "issue #10407" begin
@test maximum(spzeros(5, 5)) == 0.0
@test minimum(spzeros(5, 5)) == 0.0
end
@testset "issue #10411" begin
for (m,n) in ((2,-2),(-2,2),(-2,-2))
@test_throws ArgumentError spzeros(m,n)
@test_throws ArgumentError sparse(1.0I, m, n)
@test_throws ArgumentError sprand(m,n,0.2)
end
end
@testset "issue #10837, sparse constructors from special matrices" begin
T = Tridiagonal(randn(4),randn(5),randn(4))
S = sparse(T)
@test norm(Array(T) - Array(S)) == 0.0
T = SymTridiagonal(randn(5),rand(4))
S = sparse(T)
@test norm(Array(T) - Array(S)) == 0.0
B = Bidiagonal(randn(5),randn(4),:U)
S = sparse(B)
@test norm(Array(B) - Array(S)) == 0.0
B = Bidiagonal(randn(5),randn(4),:L)
S = sparse(B)
@test norm(Array(B) - Array(S)) == 0.0
D = Diagonal(randn(5))
S = sparse(D)
@test norm(Array(D) - Array(S)) == 0.0
end
@testset "error conditions for reshape, and dropdims" begin
local A = sprand(Bool, 5, 5, 0.2)
@test_throws DimensionMismatch reshape(A,(20, 2))
@test_throws ArgumentError dropdims(A,dims=(1, 1))
end
@testset "float" begin
local A
A = sprand(Bool, 5, 5, 0.0)
@test eltype(float(A)) == Float64 # issue #11658
A = sprand(Bool, 5, 5, 0.2)
@test float(A) == float(Array(A))
end
@testset "sparsevec" begin
local A = sparse(fill(1, 5, 5))
@test sparsevec(A) == fill(1, 25)
@test sparsevec([1:5;], 1) == fill(1, 5)
@test_throws ArgumentError sparsevec([1:5;], [1:4;])
end
@testset "sparse" begin
local A = sparse(fill(1, 5, 5))
@test sparse(A) == A
@test sparse([1:5;], [1:5;], 1) == sparse(1.0I, 5, 5)
end
@testset "one(A::SparseMatrixCSC)" begin
@test_throws DimensionMismatch one(sparse([1 1 1; 1 1 1]))
@test one(sparse([1 1; 1 1]))::SparseMatrixCSC == [1 0; 0 1]
end
@testset "istriu/istril" begin
local A = fill(1, 5, 5)
@test istriu(sparse(triu(A)))
@test !istriu(sparse(A))
@test istril(sparse(tril(A)))
@test !istril(sparse(A))
end
@testset "droptol" begin
local A = guardseed(1234321) do
triu(sprand(10, 10, 0.2))
end
@test SparseArrays.droptol!(A, 0.01).colptr == [1, 2, 2, 3, 4, 5, 5, 6, 8, 10, 13]
@test isequal(SparseArrays.droptol!(sparse([1], [1], [1]), 1), SparseMatrixCSC(1, 1, Int[1, 1], Int[], Int[]))
end
@testset "dropzeros[!]" begin
smalldim = 5
largedim = 10
nzprob = 0.4
targetnumposzeros = 5
targetnumnegzeros = 5
for (m, n) in ((largedim, largedim), (smalldim, largedim), (largedim, smalldim))
local A = sprand(m, n, nzprob)
struczerosA = findall(x -> x == 0, A)
poszerosinds = unique(rand(struczerosA, targetnumposzeros))
negzerosinds = unique(rand(struczerosA, targetnumnegzeros))
Aposzeros = copy(A)
Aposzeros[poszerosinds] .= 2
Anegzeros = copy(A)
Anegzeros[negzerosinds] .= -2
Abothsigns = copy(Aposzeros)
Abothsigns[negzerosinds] .= -2
map!(x -> x == 2 ? 0.0 : x, Aposzeros.nzval, Aposzeros.nzval)
map!(x -> x == -2 ? -0.0 : x, Anegzeros.nzval, Anegzeros.nzval)
map!(x -> x == 2 ? 0.0 : x == -2 ? -0.0 : x, Abothsigns.nzval, Abothsigns.nzval)
for Awithzeros in (Aposzeros, Anegzeros, Abothsigns)
# Basic functionality / dropzeros!
@test dropzeros!(copy(Awithzeros)) == A
@test dropzeros!(copy(Awithzeros), trim = false) == A
# Basic functionality / dropzeros
@test dropzeros(Awithzeros) == A
@test dropzeros(Awithzeros, trim = false) == A
# Check trimming works as expected
@test length(dropzeros!(copy(Awithzeros)).nzval) == length(A.nzval)
@test length(dropzeros!(copy(Awithzeros)).rowval) == length(A.rowval)
@test length(dropzeros!(copy(Awithzeros), trim = false).nzval) == length(Awithzeros.nzval)
@test length(dropzeros!(copy(Awithzeros), trim = false).rowval) == length(Awithzeros.rowval)
end
end
# original lone dropzeros test
local A = sparse([1 2 3; 4 5 6; 7 8 9])
A.nzval[2] = A.nzval[6] = A.nzval[7] = 0
@test dropzeros!(A).colptr == [1, 3, 5, 7]
# test for issue #5169, modified for new behavior following #15242/#14798
@test nnz(sparse([1, 1], [1, 2], [0.0, -0.0])) == 2
@test nnz(dropzeros!(sparse([1, 1], [1, 2], [0.0, -0.0]))) == 0
# test for issue #5437, modified for new behavior following #15242/#14798
@test nnz(sparse([1, 2, 3], [1, 2, 3], [0.0, 1.0, 2.0])) == 3
@test nnz(dropzeros!(sparse([1, 2, 3],[1, 2, 3],[0.0, 1.0, 2.0]))) == 2
end
@testset "trace" begin
@test_throws DimensionMismatch tr(spzeros(5,6))
@test tr(sparse(1.0I, 5, 5)) == 5
end
@testset "spdiagm" begin
x = fill(1, 2)
@test spdiagm(0 => x, -1 => x) == [1 0 0; 1 1 0; 0 1 0]
@test spdiagm(0 => x, 1 => x) == [1 1 0; 0 1 1; 0 0 0]
for (x, y) in ((rand(5), rand(4)),(sparse(rand(5)), sparse(rand(4))))
@test spdiagm(-1 => x)::SparseMatrixCSC == diagm(-1 => x)
@test spdiagm( 0 => x)::SparseMatrixCSC == diagm( 0 => x) == sparse(Diagonal(x))
@test spdiagm(-1 => x)::SparseMatrixCSC == diagm(-1 => x)
@test spdiagm(0 => x, -1 => y)::SparseMatrixCSC == diagm(0 => x, -1 => y)
@test spdiagm(0 => x, 1 => y)::SparseMatrixCSC == diagm(0 => x, 1 => y)
end
# promotion
@test spdiagm(0 => [1,2], 1 => [3.5], -1 => [4+5im]) == [1 3.5; 4+5im 2]
end
@testset "diag" begin
for T in (Float64, ComplexF64)
S1 = sprand(T, 5, 5, 0.5)
S2 = sprand(T, 10, 5, 0.5)
S3 = sprand(T, 5, 10, 0.5)
for S in (S1, S2, S3)
local A = Matrix(S)
@test diag(S)::SparseVector{T,Int} == diag(A)
for k in -size(S,1):size(S,2)
@test diag(S, k)::SparseVector{T,Int} == diag(A, k)
end
@test_throws ArgumentError diag(S, -size(S,1)-1)
@test_throws ArgumentError diag(S, size(S,2)+1)
end
end
# test that stored zeros are still stored zeros in the diagonal
S = sparse([1,3],[1,3],[0.0,0.0]); V = diag(S)
@test V.nzind == [1,3]
@test V.nzval == [0.0,0.0]
end
@testset "expandptr" begin
local A = sparse(1.0I, 5, 5)
@test SparseArrays.expandptr(A.colptr) == 1:5
A[1,2] = 1
@test SparseArrays.expandptr(A.colptr) == [1; 2; 2; 3; 4; 5]
@test_throws ArgumentError SparseArrays.expandptr([2; 3])
end
@testset "triu/tril" begin
n = 5
local A = sprand(n, n, 0.2)
AF = Array(A)
@test Array(triu(A,1)) == triu(AF,1)
@test Array(tril(A,1)) == tril(AF,1)
@test Array(triu!(copy(A), 2)) == triu(AF,2)
@test Array(tril!(copy(A), 2)) == tril(AF,2)
@test tril(A, -n - 2) == zero(A)
@test tril(A, n) == A
@test triu(A, -n) == A
@test triu(A, n + 2) == zero(A)
# fkeep trim option
@test isequal(length(tril!(sparse([1,2,3], [1,2,3], [1,2,3], 3, 4), -1).rowval), 0)
end
@testset "norm" begin
local A
A = sparse(Int[],Int[],Float64[],0,0)
@test norm(A) == zero(eltype(A))
A = sparse([1.0])
@test norm(A) == 1.0
@test_throws ArgumentError opnorm(sprand(5,5,0.2),3)
@test_throws ArgumentError opnorm(sprand(5,5,0.2),2)
end
@testset "ishermitian/issymmetric" begin
local A
# real matrices
A = sparse(1.0I, 5, 5)
@test ishermitian(A) == true
@test issymmetric(A) == true
A[1,3] = 1.0
@test ishermitian(A) == false
@test issymmetric(A) == false
A[3,1] = 1.0
@test ishermitian(A) == true
@test issymmetric(A) == true
# complex matrices
A = sparse((1.0 + 1.0im)I, 5, 5)
@test ishermitian(A) == false
@test issymmetric(A) == true
A[1,4] = 1.0 + im
@test ishermitian(A) == false
@test issymmetric(A) == false
A = sparse(ComplexF64(1)I, 5, 5)
A[3,2] = 1.0 + im
@test ishermitian(A) == false
@test issymmetric(A) == false
A[2,3] = 1.0 - im
@test ishermitian(A) == true
@test issymmetric(A) == false
A = sparse(zeros(5,5))
@test ishermitian(A) == true
@test issymmetric(A) == true
# explicit zeros
A = sparse(ComplexF64(1)I, 5, 5)
A[3,1] = 2
A.nzval[2] = 0.0
@test ishermitian(A) == true
@test issymmetric(A) == true
# 15504
m = n = 5
colptr = [1, 5, 9, 13, 13, 17]
rowval = [1, 2, 3, 5, 1, 2, 3, 5, 1, 2, 3, 5, 1, 2, 3, 5]
nzval = [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0]
A = SparseMatrixCSC(m, n, colptr, rowval, nzval)
@test issymmetric(A) == true
A.nzval[end - 3] = 2.0
@test issymmetric(A) == false
# 16521
@test issymmetric(sparse([0 0; 1 0])) == false
@test issymmetric(sparse([0 1; 0 0])) == false
@test issymmetric(sparse([0 0; 1 1])) == false
@test issymmetric(sparse([1 0; 1 0])) == false
@test issymmetric(sparse([0 1; 1 0])) == true
@test issymmetric(sparse([1 1; 1 0])) == true
end
@testset "equality ==" begin
A1 = sparse(1.0I, 10, 10)
A2 = sparse(1.0I, 10, 10)
nonzeros(A1)[end]=0
@test A1!=A2
nonzeros(A1)[end]=1
@test A1==A2
A1[1:4,end] .= 1
@test A1!=A2
nonzeros(A1)[end-4:end-1].=0
@test A1==A2
A2[1:4,end-1] .= 1
@test A1!=A2
nonzeros(A2)[end-5:end-2].=0
@test A1==A2
A2[2:3,1] .= 1
@test A1!=A2
nonzeros(A2)[2:3].=0
@test A1==A2
A1[2:5,1] .= 1
@test A1!=A2
nonzeros(A1)[2:5].=0
@test A1==A2
@test sparse([1,1,0])!=sparse([0,1,1])
end
@testset "UniformScaling" begin
local A = sprandn(10, 10, 0.5)
@test A + I == Array(A) + I
@test I + A == I + Array(A)
@test A - I == Array(A) - I
@test I - A == I - Array(A)
end
@testset "issue #12177, error path if triplet vectors are not all the same length" begin
@test_throws ArgumentError sparse([1,2,3], [1,2], [1,2,3], 3, 3)
@test_throws ArgumentError sparse([1,2,3], [1,2,3], [1,2], 3, 3)
end
@testset "issue #12118: sparse matrices are closed under +, -, min, max" begin
A12118 = sparse([1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5])
B12118 = sparse([1,2,4,5], [1,2,3,5], [2,1,-1,-2])
@test A12118 + B12118 == sparse([1,2,3,4,4,5], [1,2,3,3,4,5], [3,3,3,-1,4,3])
@test typeof(A12118 + B12118) == SparseMatrixCSC{Int,Int}
@test A12118 - B12118 == sparse([1,2,3,4,4,5], [1,2,3,3,4,5], [-1,1,3,1,4,7])
@test typeof(A12118 - B12118) == SparseMatrixCSC{Int,Int}
@test max.(A12118, B12118) == sparse([1,2,3,4,5], [1,2,3,4,5], [2,2,3,4,5])
@test typeof(max.(A12118, B12118)) == SparseMatrixCSC{Int,Int}
@test min.(A12118, B12118) == sparse([1,2,4,5], [1,2,3,5], [1,1,-1,-2])
@test typeof(min.(A12118, B12118)) == SparseMatrixCSC{Int,Int}
end
@testset "sparse matrix norms" begin
Ac = sprandn(10,10,.1) + im* sprandn(10,10,.1)
Ar = sprandn(10,10,.1)
Ai = ceil.(Int,Ar*100)
@test opnorm(Ac,1) ≈ opnorm(Array(Ac),1)
@test opnorm(Ac,Inf) ≈ opnorm(Array(Ac),Inf)
@test norm(Ac) ≈ norm(Array(Ac))
@test opnorm(Ar,1) ≈ opnorm(Array(Ar),1)
@test opnorm(Ar,Inf) ≈ opnorm(Array(Ar),Inf)
@test norm(Ar) ≈ norm(Array(Ar))
@test opnorm(Ai,1) ≈ opnorm(Array(Ai),1)
@test opnorm(Ai,Inf) ≈ opnorm(Array(Ai),Inf)
@test norm(Ai) ≈ norm(Array(Ai))
Ai = trunc.(Int, Ar*100)
@test opnorm(Ai,1) ≈ opnorm(Array(Ai),1)
@test opnorm(Ai,Inf) ≈ opnorm(Array(Ai),Inf)
@test norm(Ai) ≈ norm(Array(Ai))
Ai = round.(Int, Ar*100)
@test opnorm(Ai,1) ≈ opnorm(Array(Ai),1)
@test opnorm(Ai,Inf) ≈ opnorm(Array(Ai),Inf)
@test norm(Ai) ≈ norm(Array(Ai))
# make certain entries in nzval beyond
# the range specified in colptr do not
# impact norm of a sparse matrix
foo = sparse(1.0I, 4, 4)
resize!(foo.nzval, 5)
setindex!(foo.nzval, NaN, 5)
@test norm(foo) == 2.0
end
@testset "sparse matrix cond" begin
local A = sparse(reshape([1.0], 1, 1))
Ac = sprandn(20, 20,.5) + im*sprandn(20, 20,.5)
Ar = sprandn(20, 20,.5) + eps()*I
@test cond(A, 1) == 1.0
# For a discussion of the tolerance, see #14778
if Base.USE_GPL_LIBS
@test 0.99 <= cond(Ar, 1) \ opnorm(Ar, 1) * opnorm(inv(Array(Ar)), 1) < 3
@test 0.99 <= cond(Ac, 1) \ opnorm(Ac, 1) * opnorm(inv(Array(Ac)), 1) < 3
@test 0.99 <= cond(Ar, Inf) \ opnorm(Ar, Inf) * opnorm(inv(Array(Ar)), Inf) < 3
@test 0.99 <= cond(Ac, Inf) \ opnorm(Ac, Inf) * opnorm(inv(Array(Ac)), Inf) < 3
end
@test_throws ArgumentError cond(A,2)
@test_throws ArgumentError cond(A,3)
Arect = spzeros(10, 6)
@test_throws DimensionMismatch cond(Arect, 1)
@test_throws ArgumentError cond(Arect,2)
@test_throws DimensionMismatch cond(Arect, Inf)
end
@testset "sparse matrix opnormestinv" begin
Random.seed!(1234)
Ac = sprandn(20,20,.5) + im* sprandn(20,20,.5)
Aci = ceil.(Int64, 100*sprand(20,20,.5)) + im*ceil.(Int64, sprand(20,20,.5))
Ar = sprandn(20,20,.5)
Ari = ceil.(Int64, 100*Ar)
if Base.USE_GPL_LIBS
# NOTE: opnormestinv is probabilistic, so requires a fixed seed (set above in Random.seed!(1234))
@test SparseArrays.opnormestinv(Ac,3) ≈ opnorm(inv(Array(Ac)),1) atol=1e-4
@test SparseArrays.opnormestinv(Aci,3) ≈ opnorm(inv(Array(Aci)),1) atol=1e-4
@test SparseArrays.opnormestinv(Ar) ≈ opnorm(inv(Array(Ar)),1) atol=1e-4
@test_throws ArgumentError SparseArrays.opnormestinv(Ac,0)
@test_throws ArgumentError SparseArrays.opnormestinv(Ac,21)
end
@test_throws DimensionMismatch SparseArrays.opnormestinv(sprand(3,5,.9))
end
@testset "issue #13008" begin
@test_throws ArgumentError sparse(Vector(1:100), Vector(1:100), fill(5,100), 5, 5)
@test_throws ArgumentError sparse(Int[], Vector(1:5), Vector(1:5))
end
@testset "issue #13024" begin
A13024 = sparse([1,2,3,4,5], [1,2,3,4,5], fill(true,5))
B13024 = sparse([1,2,4,5], [1,2,3,5], fill(true,4))
@test broadcast(&, A13024, B13024) == sparse([1,2,5], [1,2,5], fill(true,3))
@test typeof(broadcast(&, A13024, B13024)) == SparseMatrixCSC{Bool,Int}
@test broadcast(|, A13024, B13024) == sparse([1,2,3,4,4,5], [1,2,3,3,4,5], fill(true,6))
@test typeof(broadcast(|, A13024, B13024)) == SparseMatrixCSC{Bool,Int}
@test broadcast(⊻, A13024, B13024) == sparse([3,4,4], [3,3,4], fill(true,3), 5, 5)
@test typeof(broadcast(⊻, A13024, B13024)) == SparseMatrixCSC{Bool,Int}
@test broadcast(max, A13024, B13024) == sparse([1,2,3,4,4,5], [1,2,3,3,4,5], fill(true,6))
@test typeof(broadcast(max, A13024, B13024)) == SparseMatrixCSC{Bool,Int}
@test broadcast(min, A13024, B13024) == sparse([1,2,5], [1,2,5], fill(true,3))
@test typeof(broadcast(min, A13024, B13024)) == SparseMatrixCSC{Bool,Int}
for op in (+, -)
@test op(A13024, B13024) == op(Array(A13024), Array(B13024))
end
for op in (max, min, &, |, xor)
@test op.(A13024, B13024) == op.(Array(A13024), Array(B13024))
end
end
@testset "fillstored!" begin
@test LinearAlgebra.fillstored!(sparse(2.0I, 5, 5), 1) == Matrix(I, 5, 5)
end
@testset "factorization" begin
Random.seed!(123)
local A
A = sparse(Diagonal(rand(5))) + sprandn(5, 5, 0.2) + im*sprandn(5, 5, 0.2)
A = A + copy(A')
@test !Base.USE_GPL_LIBS || abs(det(factorize(Hermitian(A)))) ≈ abs(det(factorize(Array(A))))
A = sparse(Diagonal(rand(5))) + sprandn(5, 5, 0.2) + im*sprandn(5, 5, 0.2)
A = A*A'
@test !Base.USE_GPL_LIBS || abs(det(factorize(Hermitian(A)))) ≈ abs(det(factorize(Array(A))))
A = sparse(Diagonal(rand(5))) + sprandn(5, 5, 0.2)
A = A + copy(transpose(A))
@test !Base.USE_GPL_LIBS || abs(det(factorize(Symmetric(A)))) ≈ abs(det(factorize(Array(A))))
A = sparse(Diagonal(rand(5))) + sprandn(5, 5, 0.2)
A = A*transpose(A)
@test !Base.USE_GPL_LIBS || abs(det(factorize(Symmetric(A)))) ≈ abs(det(factorize(Array(A))))
@test factorize(triu(A)) == triu(A)
@test isa(factorize(triu(A)), UpperTriangular{Float64, SparseMatrixCSC{Float64, Int}})
@test factorize(tril(A)) == tril(A)
@test isa(factorize(tril(A)), LowerTriangular{Float64, SparseMatrixCSC{Float64, Int}})
C, b = A[:, 1:4], fill(1., size(A, 1))
@test !Base.USE_GPL_LIBS || factorize(C)\b ≈ Array(C)\b
@test_throws ErrorException eigen(A)
@test_throws ErrorException inv(A)
end
@testset "issue #13792, use sparse triangular solvers for sparse triangular solves" begin
local A, n, x
n = 100
A, b = sprandn(n, n, 0.5) + sqrt(n)*I, fill(1., n)
@test LowerTriangular(A)\(LowerTriangular(A)*b) ≈ b
@test UpperTriangular(A)\(UpperTriangular(A)*b) ≈ b
A[2,2] = 0
dropzeros!(A)
@test_throws LinearAlgebra.SingularException LowerTriangular(A)\b
@test_throws LinearAlgebra.SingularException UpperTriangular(A)\b
end
@testset "issue described in https://groups.google.com/forum/#!topic/julia-dev/QT7qpIpgOaA" begin
@test sparse([1,1], [1,1], [true, true]) == sparse([1,1], [1,1], [true, true], 1, 1) == fill(true, 1, 1)
@test sparsevec([1,1], [true, true]) == sparsevec([1,1], [true, true], 1) == fill(true, 1)
end
@testset "issparse for specialized matrix types" begin
m = sprand(10, 10, 0.1)
@test issparse(Symmetric(m))
@test issparse(Hermitian(m))
@test issparse(LowerTriangular(m))
@test issparse(LinearAlgebra.UnitLowerTriangular(m))
@test issparse(UpperTriangular(m))
@test issparse(LinearAlgebra.UnitUpperTriangular(m))
@test issparse(Symmetric(Array(m))) == false
@test issparse(Hermitian(Array(m))) == false
@test issparse(LowerTriangular(Array(m))) == false
@test issparse(LinearAlgebra.UnitLowerTriangular(Array(m))) == false
@test issparse(UpperTriangular(Array(m))) == false
@test issparse(LinearAlgebra.UnitUpperTriangular(Array(m))) == false
end
@testset "test created type of sprand{T}(::Type{T}, m::Integer, n::Integer, density::AbstractFloat)" begin
m = sprand(Float32, 10, 10, 0.1)
@test eltype(m) == Float32
m = sprand(Float64, 10, 10, 0.1)
@test eltype(m) == Float64
m = sprand(Int32, 10, 10, 0.1)
@test eltype(m) == Int32
end
@testset "issue #16073" begin
@inferred sprand(1, 1, 1.0)
@inferred sprand(1, 1, 1.0, rand, Float64)
@inferred sprand(1, 1, 1.0, x -> round.(Int, rand(x) * 100))
end
# Test that concatenations of combinations of sparse matrices with sparse matrices or dense
# matrices/vectors yield sparse arrays
@testset "sparse and dense concatenations" begin
N = 4
densevec = fill(1., N)
densemat = diagm(0 => densevec)
spmat = spdiagm(0 => densevec)
# Test that concatenations of pairs of sparse matrices yield sparse arrays
@test issparse(vcat(spmat, spmat))
@test issparse(hcat(spmat, spmat))
@test issparse(hvcat((2,), spmat, spmat))
@test issparse(cat(spmat, spmat; dims=(1,2)))
# Test that concatenations of a sparse matrice with a dense matrix/vector yield sparse arrays
@test issparse(vcat(spmat, densemat))
@test issparse(vcat(densemat, spmat))
for densearg in (densevec, densemat)
@test issparse(hcat(spmat, densearg))
@test issparse(hcat(densearg, spmat))
@test issparse(hvcat((2,), spmat, densearg))
@test issparse(hvcat((2,), densearg, spmat))
@test issparse(cat(spmat, densearg; dims=(1,2)))
@test issparse(cat(densearg, spmat; dims=(1,2)))
end
end
@testset "issue #14816" begin
m = 5
intmat = fill(1, m, m)
ltintmat = LowerTriangular(rand(1:5, m, m))
@test \(transpose(ltintmat), sparse(intmat)) ≈ \(transpose(ltintmat), intmat)
end
# Test temporary fix for issue #16548 in PR #16979. Somewhat brittle. Expect to remove with `\` revisions.
@testset "issue #16548" begin
ms = methods(\, (SparseMatrixCSC, AbstractVecOrMat)).ms
@test all(m -> m.module == SparseArrays, ms)
end
@testset "row indexing a SparseMatrixCSC with non-Int integer type" begin
local A = sparse(UInt32[1,2,3], UInt32[1,2,3], [1.0,2.0,3.0])
@test A[1,1:3] == A[1,:] == [1,0,0]
end
# Check that `broadcast` methods specialized for unary operations over `SparseMatrixCSC`s
# are called. (Issue #18705.) EDIT: #19239 unified broadcast over a single sparse matrix,
# eliminating the former operation classes.
@testset "issue #18705" begin
S = sparse(Diagonal(1.0:5.0))
@test isa(sin.(S), SparseMatrixCSC)
end
@testset "issue #19225" begin
X = sparse([1 -1; -1 1])
for T in (Symmetric, Hermitian)
Y = T(copy(X))
_Y = similar(Y)
copyto!(_Y, Y)
@test _Y == Y
W = T(copy(X), :L)
copyto!(W, Y)
@test W.data == Y.data
@test W.uplo != Y.uplo
W[1,1] = 4
@test W == T(sparse([4 -1; -1 1]))
@test_throws ArgumentError (W[1,2] = 2)
@test Y + I == T(sparse([2 -1; -1 2]))
@test Y - I == T(sparse([0 -1; -1 0]))
@test Y * I == Y
@test Y .+ 1 == T(sparse([2 0; 0 2]))
@test Y .- 1 == T(sparse([0 -2; -2 0]))
@test Y * 2 == T(sparse([2 -2; -2 2]))
@test Y / 1 == Y
end
end
@testset "issue #19304" begin
@inferred hcat(sparse(rand(2,1)), I)
@inferred hcat(sparse(rand(2,1)), 1.0I)
@inferred hcat(sparse(rand(2,1)), Matrix(I, 2, 2))
@inferred hcat(sparse(rand(2,1)), Matrix(1.0I, 2, 2))
end
# Check that `broadcast` methods specialized for unary operations over
# `SparseMatrixCSC`s determine a reasonable return type.
@testset "issue #18974" begin
S = sparse(Diagonal(Int64(1):Int64(4)))
@test eltype(sin.(S)) == Float64
end
# Check calling of unary minus method specialized for SparseMatrixCSCs
@testset "issue #19503" begin
@test which(-, (SparseMatrixCSC,)).module == SparseArrays
end
@testset "issue #14398" begin
@test collect(view(sparse(I, 10, 10), 1:5, 1:5)') ≈ Matrix(I, 5, 5)
end
@testset "dropstored issue #20513" begin
x = sparse(rand(3,3))
SparseArrays.dropstored!(x, 1, 1)
@test x[1, 1] == 0.0
@test x.colptr == [1, 3, 6, 9]
SparseArrays.dropstored!(x, 2, 1)
@test x.colptr == [1, 2, 5, 8]
@test x[2, 1] == 0.0
SparseArrays.dropstored!(x, 2, 2)
@test x.colptr == [1, 2, 4, 7]
@test x[2, 2] == 0.0
SparseArrays.dropstored!(x, 2, 3)
@test x.colptr == [1, 2, 4, 6]
@test x[2, 3] == 0.0
end
@testset "setindex issue #20657" begin
local A = spzeros(3, 3)
I = [1, 1, 1]; J = [1, 1, 1]
A[I, 1] .= 1
@test nnz(A) == 1
A[1, J] .= 1
@test nnz(A) == 1
A[I, J] .= 1
@test nnz(A) == 1
end
@testset "setindex with vector eltype (#29034)" begin
A = sparse([1], [1], [Vector{Float64}(undef, 3)], 3, 3)
A[1,1] = [1.0, 2.0, 3.0]
@test A[1,1] == [1.0, 2.0, 3.0]
end
@testset "show" begin
io = IOBuffer()
show(io, MIME"text/plain"(), sparse(Int64[1], Int64[1], [1.0]))
@test String(take!(io)) == "1×1 SparseArrays.SparseMatrixCSC{Float64,Int64} with 1 stored entry:\n [1, 1] = 1.0"
show(io, MIME"text/plain"(), spzeros(Float32, Int64, 2, 2))
@test String(take!(io)) == "2×2 SparseArrays.SparseMatrixCSC{Float32,Int64} with 0 stored entries"
ioc = IOContext(io, :displaysize => (5, 80), :limit => true)
show(ioc, MIME"text/plain"(), sparse(Int64[1], Int64[1], [1.0]))
@test String(take!(io)) == "1×1 SparseArrays.SparseMatrixCSC{Float64,Int64} with 1 stored entry:\n [1, 1] = 1.0"
show(ioc, MIME"text/plain"(), sparse(Int64[1, 1], Int64[1, 2], [1.0, 2.0]))
@test String(take!(io)) == "1×2 SparseArrays.SparseMatrixCSC{Float64,Int64} with 2 stored entries:\n ⋮"
# even number of rows
ioc = IOContext(io, :displaysize => (8, 80), :limit => true)
show(ioc, MIME"text/plain"(), sparse(Int64[1,2,3,4], Int64[1,1,2,2], [1.0,2.0,3.0,4.0]))
@test String(take!(io)) == string("4×2 SparseArrays.SparseMatrixCSC{Float64,Int64} with 4 stored entries:\n [1, 1]",
" = 1.0\n [2, 1] = 2.0\n [3, 2] = 3.0\n [4, 2] = 4.0")
show(ioc, MIME"text/plain"(), sparse(Int64[1,2,3,4,5], Int64[1,1,2,2,3], [1.0,2.0,3.0,4.0,5.0]))
@test String(take!(io)) == string("5×3 SparseArrays.SparseMatrixCSC{Float64,Int64} with 5 stored entries:\n [1, 1]",
" = 1.0\n ⋮\n [4, 2] = 4.0\n [5, 3] = 5.0")
show(ioc, MIME"text/plain"(), sparse(fill(1.,5,3)))
@test String(take!(io)) == string("5×3 SparseArrays.SparseMatrixCSC{Float64,$Int} with 15 stored entries:\n [1, 1]",
" = 1.0\n ⋮\n [4, 3] = 1.0\n [5, 3] = 1.0")
# odd number of rows
ioc = IOContext(io, :displaysize => (9, 80), :limit => true)
show(ioc, MIME"text/plain"(), sparse(Int64[1,2,3,4,5], Int64[1,1,2,2,3], [1.0,2.0,3.0,4.0,5.0]))
@test String(take!(io)) == string("5×3 SparseArrays.SparseMatrixCSC{Float64,Int64} with 5 stored entries:\n [1, 1]",
" = 1.0\n [2, 1] = 2.0\n [3, 2] = 3.0\n [4, 2] = 4.0\n [5, 3] = 5.0")
show(ioc, MIME"text/plain"(), sparse(Int64[1,2,3,4,5,6], Int64[1,1,2,2,3,3], [1.0,2.0,3.0,4.0,5.0,6.0]))
@test String(take!(io)) == string("6×3 SparseArrays.SparseMatrixCSC{Float64,Int64} with 6 stored entries:\n [1, 1]",
" = 1.0\n [2, 1] = 2.0\n ⋮\n [5, 3] = 5.0\n [6, 3] = 6.0")
show(ioc, MIME"text/plain"(), sparse(fill(1.,6,3)))
@test String(take!(io)) == string("6×3 SparseArrays.SparseMatrixCSC{Float64,$Int} with 18 stored entries:\n [1, 1]",
" = 1.0\n [2, 1] = 1.0\n ⋮\n [5, 3] = 1.0\n [6, 3] = 1.0")
ioc = IOContext(io, :displaysize => (9, 80))
show(ioc, MIME"text/plain"(), sparse(Int64[1,2,3,4,5,6], Int64[1,1,2,2,3,3], [1.0,2.0,3.0,4.0,5.0,6.0]))
@test String(take!(io)) == string("6×3 SparseArrays.SparseMatrixCSC{Float64,Int64} with 6 stored entries:\n [1, 1] = 1.0\n",
" [2, 1] = 2.0\n [3, 2] = 3.0\n [4, 2] = 4.0\n [5, 3] = 5.0\n [6, 3] = 6.0")
# issue #30589
@test repr("text/plain", sparse([true true])) == "1×2 SparseArrays.SparseMatrixCSC{Bool,$Int} with 2 stored entries:\n [1, 1] = 1\n [1, 2] = 1"
end
@testset "check buffers" for n in 1:3
local A
rowval = [1,2,3]
nzval1 = Int[]
nzval2 = [1,1,1]
A = SparseMatrixCSC(n, n, [1:n+1;], rowval, nzval1)
@test nnz(A) == n
@test_throws BoundsError A[n,n]
A = SparseMatrixCSC(n, n, [1:n+1;], rowval, nzval2)
@test nnz(A) == n
@test A == Matrix(I, n, n)
end
@testset "reverse search direction if step < 0 #21986" begin
local A, B
A = guardseed(1234) do
sprand(5, 5, 1/5)
end
A = max.(A, copy(A'))
LinearAlgebra.fillstored!(A, 1)
B = A[5:-1:1, 5:-1:1]
@test issymmetric(B)
end
@testset "similar should not alias the input sparse array" begin
a = sparse(rand(3,3) .+ 0.1)
b = similar(a, Float32, Int32)
c = similar(b, Float32, Int32)
SparseArrays.dropstored!(b, 1, 1)
@test length(c.rowval) == 9
@test length(c.nzval) == 9
end
@testset "similar with type conversion" begin
local A = sparse(1.0I, 5, 5)
@test size(similar(A, ComplexF64, Int)) == (5, 5)
@test typeof(similar(A, ComplexF64, Int)) == SparseMatrixCSC{ComplexF64, Int}
@test size(similar(A, ComplexF64, Int8)) == (5, 5)
@test typeof(similar(A, ComplexF64, Int8)) == SparseMatrixCSC{ComplexF64, Int8}
@test similar(A, ComplexF64,(6, 6)) == spzeros(ComplexF64, 6, 6)
@test convert(Matrix, A) == Array(A) # lolwut, are you lost, test?
end
@testset "similar for SparseMatrixCSC" begin
local A = sparse(1.0I, 5, 5)
# test similar without specifications (preserves stored-entry structure)
simA = similar(A)
@test typeof(simA) == typeof(A)
@test size(simA) == size(A)
@test simA.colptr == A.colptr
@test simA.rowval == A.rowval
@test length(simA.nzval) == length(A.nzval)
# test similar with entry type specification (preserves stored-entry structure)
simA = similar(A, Float32)
@test typeof(simA) == SparseMatrixCSC{Float32,eltype(A.colptr)}
@test size(simA) == size(A)
@test simA.colptr == A.colptr
@test simA.rowval == A.rowval
@test length(simA.nzval) == length(A.nzval)
# test similar with entry and index type specification (preserves stored-entry structure)
simA = similar(A, Float32, Int8)
@test typeof(simA) == SparseMatrixCSC{Float32,Int8}
@test size(simA) == size(A)
@test simA.colptr == A.colptr
@test simA.rowval == A.rowval
@test length(simA.nzval) == length(A.nzval)
# test similar with Dims{2} specification (preserves storage space only, not stored-entry structure)
simA = similar(A, (6,6))
@test typeof(simA) == typeof(A)
@test size(simA) == (6,6)
@test simA.colptr == fill(1, 6+1)
@test length(simA.rowval) == length(A.rowval)
@test length(simA.nzval) == length(A.nzval)
# test similar with entry type and Dims{2} specification (preserves storage space only)
simA = similar(A, Float32, (6,6))
@test typeof(simA) == SparseMatrixCSC{Float32,eltype(A.colptr)}
@test size(simA) == (6,6)
@test simA.colptr == fill(1, 6+1)
@test length(simA.rowval) == length(A.rowval)
@test length(simA.nzval) == length(A.nzval)
# test similar with entry type, index type, and Dims{2} specification (preserves storage space only)
simA = similar(A, Float32, Int8, (6,6))
@test typeof(simA) == SparseMatrixCSC{Float32, Int8}
@test size(simA) == (6,6)
@test simA.colptr == fill(1, 6+1)
@test length(simA.rowval) == length(A.rowval)
@test length(simA.nzval) == length(A.nzval)
# test similar with Dims{1} specification (preserves nothing)
simA = similar(A, (6,))
@test typeof(simA) == SparseVector{eltype(A.nzval),eltype(A.colptr)}
@test size(simA) == (6,)
@test length(simA.nzind) == 0
@test length(simA.nzval) == 0
# test similar with entry type and Dims{1} specification (preserves nothing)
simA = similar(A, Float32, (6,))
@test typeof(simA) == SparseVector{Float32,eltype(A.colptr)}
@test size(simA) == (6,)
@test length(simA.nzind) == 0
@test length(simA.nzval) == 0
# test similar with entry type, index type, and Dims{1} specification (preserves nothing)
simA = similar(A, Float32, Int8, (6,))
@test typeof(simA) == SparseVector{Float32,Int8}
@test size(simA) == (6,)
@test length(simA.nzind) == 0
@test length(simA.nzval) == 0
# test entry points to similar with entry type, index type, and non-Dims shape specification
@test similar(A, Float32, Int8, 6, 6) == similar(A, Float32, Int8, (6, 6))
@test similar(A, Float32, Int8, 6) == similar(A, Float32, Int8, (6,))
end
@testset "count specializations" begin
# count should throw for sparse arrays for which zero(eltype) does not exist
@test_throws MethodError count(SparseMatrixCSC(2, 2, Int[1, 2, 3], Int[1, 2], Any[true, true]))
@test_throws MethodError count(SparseVector(2, Int[1], Any[true]))
# count should run only over S.nzval[1:nnz(S)], not S.nzval in full
@test count(SparseMatrixCSC(2, 2, Int[1, 2, 3], Int[1, 2], Bool[true, true, true])) == 2
end
@testset "sparse findprev/findnext operations" begin
x = [0,0,0,0,1,0,1,0,1,1,0]
x_sp = sparse(x)
for i=1:length(x)
@test findnext(!iszero, x,i) == findnext(!iszero, x_sp,i)
@test findprev(!iszero, x,i) == findprev(!iszero, x_sp,i)
end
y = [7 0 0 0 0;
1 0 1 0 0;
1 7 0 7 1;
0 0 1 0 0;
1 0 1 1 0.0]
y_sp = [x == 7 ? -0.0 : x for x in sparse(y)]
y = Array(y_sp)
@test isequal(y_sp[1,1], -0.0)
for i in keys(y)
@test findnext(!iszero, y,i) == findnext(!iszero, y_sp,i)
@test findprev(!iszero, y,i) == findprev(!iszero, y_sp,i)
@test findnext(iszero, y,i) == findnext(iszero, y_sp,i)
@test findprev(iszero, y,i) == findprev(iszero, y_sp,i)
end
z_sp = sparsevec(Dict(1=>1, 5=>1, 8=>0, 10=>1))
z = collect(z_sp)
for i in keys(z)
@test findnext(!iszero, z,i) == findnext(!iszero, z_sp,i)
@test findprev(!iszero, z,i) == findprev(!iszero, z_sp,i)
end
w = [ "a" ""; "" "b"]
w_sp = sparse(w)
for i in keys(w)
@test findnext(!isequal(""), w,i) == findnext(!isequal(""), w_sp,i)
@test findprev(!isequal(""), w,i) == findprev(!isequal(""), w_sp,i)
@test findnext(isequal(""), w,i) == findnext(isequal(""), w_sp,i)
@test findprev(isequal(""), w,i) == findprev(isequal(""), w_sp,i)
end
end
# #20711
@testset "vec returns a view" begin
local A = sparse(Matrix(1.0I, 3, 3))
local v = vec(A)
v[1] = 2
@test A[1,1] == 2
end
# #25943
@testset "operations on Integer subtypes" begin
s = sparse(UInt8[1, 2, 3], UInt8[1, 2, 3], UInt8[1, 2, 3])
@test sum(s, dims=2) == reshape([1, 2, 3], 3, 1)
end
@testset "mapreduce of sparse matrices with trailing elements in nzval #26534" begin
B = SparseMatrixCSC{Int,Int}(2, 3,
[1, 3, 4, 5],
[1, 2, 1, 2, 999, 999, 999, 999],
[1, 2, 3, 6, 999, 999, 999, 999]
)
@test maximum(B) == 6
end
_length_or_count_or_five(::Colon) = 5
_length_or_count_or_five(x::AbstractVector{Bool}) = count(x)
_length_or_count_or_five(x) = length(x)
@testset "nonscalar setindex!" begin
for I in (1:4, :, 5:-1:2, [], trues(5), setindex!(falses(5), true, 2), 3),
J in (2:4, :, 4:-1:1, [], setindex!(trues(5), false, 3), falses(5), 4)
V = sparse(1 .+ zeros(_length_or_count_or_five(I)*_length_or_count_or_five(J)))
M = sparse(1 .+ zeros(_length_or_count_or_five(I), _length_or_count_or_five(J)))
if I isa Integer && J isa Integer
@test_throws MethodError spzeros(5,5)[I, J] = V
@test_throws MethodError spzeros(5,5)[I, J] = M
continue
end
@test setindex!(spzeros(5, 5), V, I, J) == setindex!(zeros(5,5), V, I, J)
@test setindex!(spzeros(5, 5), M, I, J) == setindex!(zeros(5,5), M, I, J)
@test setindex!(spzeros(5, 5), Array(M), I, J) == setindex!(zeros(5,5), M, I, J)
@test setindex!(spzeros(5, 5), Array(V), I, J) == setindex!(zeros(5,5), V, I, J)
end
@test setindex!(spzeros(5, 5), 1:25, :) == setindex!(zeros(5,5), 1:25, :) == reshape(1:25, 5, 5)
@test setindex!(spzeros(5, 5), (25:-1:1).+spzeros(25), :) == setindex!(zeros(5,5), (25:-1:1).+spzeros(25), :) == reshape(25:-1:1, 5, 5)
for X in (1:20, sparse(1:20), reshape(sparse(1:20), 20, 1), (1:20) .+ spzeros(20, 1), collect(1:20), collect(reshape(1:20, 20, 1)))
@test setindex!(spzeros(5, 5), X, 6:25) == setindex!(zeros(5,5), 1:20, 6:25)
@test setindex!(spzeros(5, 5), X, 21:-1:2) == setindex!(zeros(5,5), 1:20, 21:-1:2)
b = trues(25)
b[[6, 8, 13, 15, 23]] .= false
@test setindex!(spzeros(5, 5), X, b) == setindex!(zeros(5, 5), X, b)
end
end
@testset "sparse transpose adjoint" begin
A = sprand(10, 10, 0.75)
@test A' == SparseMatrixCSC(A')
@test SparseMatrixCSC(A') isa SparseMatrixCSC
@test transpose(A) == SparseMatrixCSC(transpose(A))
@test SparseMatrixCSC(transpose(A)) isa SparseMatrixCSC
end
# PR 28242
@testset "forward and backward solving of transpose/adjoint triangular matrices" begin
rng = MersenneTwister(20180730)
n = 10
A = sprandn(rng, n, n, 0.8); A += Diagonal((1:n) - diag(A))
B = ones(n, 2)
for (Ttri, triul ) in ((UpperTriangular, triu), (LowerTriangular, tril))
for trop in (adjoint, transpose)
AT = Ttri(A) # ...Triangular wrapped
AC = triul(A) # copied part of A
ATa = trop(AT) # wrapped Adjoint
ACa = sparse(trop(AC)) # copied and adjoint
@test AT \ B ≈ AC \ B
@test ATa \ B ≈ ACa \ B
@test ATa \ sparse(B) == ATa \ B
@test Matrix(ATa) \ B ≈ ATa \ B
@test ATa * ( ATa \ B ) ≈ B
end
end
end
@testset "Issue #28369" begin
M = reshape([[1 2; 3 4], [9 10; 11 12], [5 6; 7 8], [13 14; 15 16]], (2,2))
MP = reshape([[1 2; 3 4], [5 6; 7 8], [9 10; 11 12], [13 14; 15 16]], (2,2))
S = sparse(M)
SP = sparse(MP)
@test isa(transpose(S), Transpose)
@test transpose(S) == copy(transpose(S))
@test Array(transpose(S)) == copy(transpose(M))
@test permutedims(S) == SP
@test permutedims(S, (2,1)) == SP
@test permutedims(S, (1,2)) == S
@test permutedims(S, (1,2)) !== S
MC = reshape([[(1+im) 2; 3 4], [9 10; 11 12], [(5 + 2im) 6; 7 8], [13 14; 15 16]], (2,2))
SC = sparse(MC)
@test isa(adjoint(SC), Adjoint)
@test adjoint(SC) == copy(adjoint(SC))
@test adjoint(MC) == copy(adjoint(SC))
end
begin
rng = Random.MersenneTwister(0)
n = 1000
B = ones(n)
A = sprand(rng, n, n, 0.01)
MA = Matrix(A)
@testset "triangular multiply with $tr($wr)" for tr in (identity, adjoint, transpose),
wr in (UpperTriangular, LowerTriangular, UnitUpperTriangular, UnitLowerTriangular)
AW = tr(wr(A))
MAW = tr(wr(MA))
@test AW * B ≈ MAW * B
end
A = A - Diagonal(diag(A)) + 2I # avoid rounding errors by division
MA = Matrix(A)
@testset "triangular solver for $tr($wr)" for tr in (identity, adjoint, transpose),
wr in (UpperTriangular, LowerTriangular, UnitUpperTriangular, UnitLowerTriangular)
AW = tr(wr(A))
MAW = tr(wr(MA))
@test AW \ B ≈ MAW \ B
end
@testset "triangular singular exceptions" begin
A = LowerTriangular(sparse([0 2.0;0 1]))
@test_throws SingularException(1) A \ ones(2)
A = UpperTriangular(sparse([1.0 0;0 0]))
@test_throws SingularException(2) A \ ones(2)
end
end
@testset "Issue #28634" begin
a = SparseMatrixCSC{Int8, Int16}([1 2; 3 4])
na = SparseMatrixCSC(a)
@test typeof(a) === typeof(na)
end
#PR #29045
@testset "Issue #28934" begin
A = sprand(5,5,0.5)
D = Diagonal(rand(5))
C = copy(A)
m1 = @which mul!(C,A,D)
m2 = @which mul!(C,D,A)
@test m1.module == SparseArrays
@test m2.module == SparseArrays
end
@testset "Symmetric of sparse matrix mul! dense vector" begin
rng = Random.MersenneTwister(1)
n = 1000
p = 0.02
q = 1 - sqrt(1-p)
Areal = sprandn(rng, n, n, p)
Breal = randn(rng, n)
Acomplex = sprandn(rng, n, n, q) + sprandn(rng, n, n, q) * im
Bcomplex = Breal + randn(rng, n) * im
@testset "symmetric/Hermitian sparse multiply with $S($U)" for S in (Symmetric, Hermitian), U in (:U, :L), (A, B) in ((Areal,Breal), (Acomplex,Bcomplex))
Asym = S(A, U)
As = sparse(Asym) # takes most time
@test which(mul!, (typeof(B), typeof(Asym), typeof(B))).module == SparseArrays
@test norm(Asym * B - As * B, Inf) <= eps() * n * p * 10
end
end
@testset "Symmetric of view of sparse matrix mul! dense vector" begin
rng = Random.MersenneTwister(1)
n = 1000
p = 0.02
q = 1 - sqrt(1-p)
Areal = view(sprandn(rng, n, n+10, p), :, 6:n+5)
Breal = randn(rng, n)
Acomplex = view(sprandn(rng, n, n+10, q) + sprandn(rng, n, n+10, q) * im, :, 6:n+5)
Bcomplex = Breal + randn(rng, n) * im
@testset "symmetric/Hermitian sparseview multiply with $S($U)" for S in (Symmetric, Hermitian), U in (:U, :L), (A, B) in ((Areal,Breal), (Acomplex,Bcomplex))
Asym = S(A, U)
As = sparse(Asym) # takes most time
@test which(mul!, (typeof(B), typeof(Asym), typeof(B))).module == SparseArrays
@test norm(Asym * B - As * B, Inf) <= eps() * n * p * 10
end
end
@testset "sprand" begin
p=0.3; m=1000; n=2000;
for s in 1:10
# build a (dense) random matrix with randsubset + rand
Random.seed!(s);
v = randsubseq(1:m*n,p);
x = zeros(m,n);
x[v] .= rand(length(v));
# redo the same with sprand
Random.seed!(s);
a = sprand(m,n,p);
@test x == a
end
end
@testset "sprandn with type $T" for T in (Float64, Float32, Float16, ComplexF64, ComplexF32, ComplexF16)
@test sprandn(T, 5, 5, 0.5) isa AbstractSparseMatrix{T}
end
@testset "sprandn with invalid type $T" for T in (AbstractFloat, BigFloat, Complex)
@test_throws MethodError sprandn(T, 5, 5, 0.5)
end
@testset "method ambiguity" begin
# Ambiguity test is run inside a clean process.
# https://github.com/JuliaLang/julia/issues/28804
script = joinpath(@__DIR__, "ambiguous_exec.jl")
cmd = `$(Base.julia_cmd()) --startup-file=no $script`
@test success(pipeline(cmd; stdout=stdout, stderr=stderr))
end
@testset "oneunit of sparse matrix" begin
A = sparse([Second(0) Second(0); Second(0) Second(0)])
@test oneunit(sprand(2, 2, 0.5)) isa SparseMatrixCSC{Float64}
@test oneunit(A) isa SparseMatrixCSC{Second}
@test one(sprand(2, 2, 0.5)) isa SparseMatrixCSC{Float64}
@test one(A) isa SparseMatrixCSC{Int}
end
@testset "circshift" begin
m,n = 17,15
A = sprand(m, n, 0.5)
for rshift in (-1, 0, 1, 10), cshift in (-1, 0, 1, 10)
shifts = (rshift, cshift)
# using dense circshift to compare
B = circshift(Matrix(A), shifts)
# sparse circshift
C = circshift(A, shifts)
@test C == B
# sparse circshift should not add structural zeros
@test nnz(C) == nnz(A)
# test circshift!
D = similar(A)
circshift!(D, A, shifts)
@test D == B
@test nnz(D) == nnz(A)
# test different in/out types
A2 = floor.(100A)
E1 = spzeros(Int64, m, n)
E2 = spzeros(Int64, m, n)
circshift!(E1, A2, shifts)
circshift!(E2, Matrix(A2), shifts)
@test E1 == E2
end
end
@testset "wrappers of sparse" begin
m = n = 10
A = spzeros(ComplexF64, m, n)
A[:,1] = 1:m
A[:,2] = [1 3 0 0 0 0 0 0 0 0]'
A[:,3] = [2 4 0 0 0 0 0 0 0 0]'
A[:,4] = [0 0 0 0 5 3 0 0 0 0]'
A[:,5] = [0 0 0 0 6 2 0 0 0 0]'
A[:,6] = [0 0 0 0 7 4 0 0 0 0]'
A[:,7:n] = rand(ComplexF64, m, n-6)
B = Matrix(A)
dowrap(wr, A) = wr(A)
dowrap(wr::Tuple, A) = (wr[1])(A, wr[2:end]...)
@testset "sparse($wr(A))" for wr in (
Symmetric, (Symmetric, :L), Hermitian, (Hermitian, :L),
Transpose, Adjoint,
UpperTriangular, LowerTriangular,
UnitUpperTriangular, UnitLowerTriangular,
(view, 3:6, 2:5))
@test SparseMatrixCSC(dowrap(wr, A)) == Matrix(dowrap(wr, B))
end
@testset "sparse($at($wr))" for at = (Transpose, Adjoint), wr =
(UpperTriangular, LowerTriangular,
UnitUpperTriangular, UnitLowerTriangular)
@test SparseMatrixCSC(at(wr(A))) == Matrix(at(wr(B)))
end
@test sparse([1,2,3,4,5]') == SparseMatrixCSC([1 2 3 4 5])
@test sparse(UpperTriangular(A')) == UpperTriangular(B')
@test sparse(Adjoint(UpperTriangular(A'))) == Adjoint(UpperTriangular(B'))
end
@testset "unary operations on matrices where length(nzval)>nnz" begin
# this should create a sparse matrix with length(nzval)>nnz
A = SparseMatrixCSC(Complex{BigInt}[1+im 2+2im]')'[1:1, 2:2]
# ...ensure it does! If necessary, the test needs to be updated to use
# another mechanism to create a suitable A.
@assert length(A.nzval) > nnz(A)
@test -A == fill(-2-2im, 1, 1)
@test conj(A) == fill(2-2im, 1, 1)
conj!(A)
@test A == fill(2-2im, 1, 1)
end
@testset "issue #31453" for T in [UInt8, Int8, UInt16, Int16, UInt32, Int32]
i = Int[1, 2]
j = Int[2, 1]
i2 = T.(i)
j2 = T.(j)
v = [500, 600]
x1 = sparse(i, j, v)
x2 = sparse(i2, j2, v)
@test sum(x1) == sum(x2) == 1100
@test sum(x1, dims=1) == sum(x2, dims=1)
@test sum(x1, dims=2) == sum(x2, dims=2)
end
end # module
| 38.257529
| 172
| 0.562516
|
[
"@testset \"issparse\" begin\n @test issparse(sparse(fill(1,5,5)))\n @test !issparse(fill(1,5,5))\nend",
"@testset \"iszero specialization for SparseMatrixCSC\" begin\n @test !iszero(sparse(I, 3, 3)) # test failure\n @test iszero(spzeros(3, 3)) # test success with no stored entries\n S = sparse(I, 3, 3)\n S[:] .= 0\n @test iszero(S) # test success with stored zeros via broadcasting\n S = sparse(I, 3, 3)\n fill!(S, 0)\n @test iszero(S) # test success with stored zeros via fill!\n @test iszero(SparseMatrixCSC(2, 2, [1,2,3], [1,2], [0,0,1])) # test success with nonzeros beyond data range\nend",
"@testset \"isone specialization for SparseMatrixCSC\" begin\n @test isone(sparse(I, 3, 3)) # test success\n @test !isone(sparse(I, 3, 4)) # test failure for non-square matrix\n @test !isone(spzeros(3, 3)) # test failure for too few stored entries\n @test !isone(sparse(2I, 3, 3)) # test failure for non-one diagonal entries\n @test !isone(sparse(Bidiagonal(fill(1, 3), fill(1, 2), :U))) # test failure for non-zero off-diag entries\nend",
"@testset \"indtype\" begin\n @test SparseArrays.indtype(sparse(Int8[1,1],Int8[1,1],[1,1])) == Int8\nend",
"@testset \"sparse matrix construction\" begin\n @test (A = fill(1.0+im,5,5); isequal(Array(sparse(A)), A))\n @test_throws ArgumentError sparse([1,2,3], [1,2], [1,2,3], 3, 3)\n @test_throws ArgumentError sparse([1,2,3], [1,2,3], [1,2], 3, 3)\n @test_throws ArgumentError sparse([1,2,3], [1,2,3], [1,2,3], 0, 1)\n @test_throws ArgumentError sparse([1,2,3], [1,2,3], [1,2,3], 1, 0)\n @test_throws ArgumentError sparse([1,2,4], [1,2,3], [1,2,3], 3, 3)\n @test_throws ArgumentError sparse([1,2,3], [1,2,4], [1,2,3], 3, 3)\n @test isequal(sparse(Int[], Int[], Int[], 0, 0), SparseMatrixCSC(0, 0, Int[1], Int[], Int[]))\n @test sparse(Any[1,2,3], Any[1,2,3], Any[1,1,1]) == sparse([1,2,3], [1,2,3], [1,1,1])\n @test sparse(Any[1,2,3], Any[1,2,3], Any[1,1,1], 5, 4) == sparse([1,2,3], [1,2,3], [1,1,1], 5, 4)\nend",
"@testset \"SparseMatrixCSC construction from UniformScaling\" begin\n @test_throws ArgumentError SparseMatrixCSC(I, -1, 3)\n @test_throws ArgumentError SparseMatrixCSC(I, 3, -1)\n @test SparseMatrixCSC(2I, 3, 3)::SparseMatrixCSC{Int,Int} == Matrix(2I, 3, 3)\n @test SparseMatrixCSC(2I, 3, 4)::SparseMatrixCSC{Int,Int} == Matrix(2I, 3, 4)\n @test SparseMatrixCSC(2I, 4, 3)::SparseMatrixCSC{Int,Int} == Matrix(2I, 4, 3)\n @test SparseMatrixCSC(2.0I, 3, 3)::SparseMatrixCSC{Float64,Int} == Matrix(2I, 3, 3)\n @test SparseMatrixCSC{Real}(2I, 3, 3)::SparseMatrixCSC{Real,Int} == Matrix(2I, 3, 3)\n @test SparseMatrixCSC{Float64}(2I, 3, 3)::SparseMatrixCSC{Float64,Int} == Matrix(2I, 3, 3)\n @test SparseMatrixCSC{Float64,Int32}(2I, 3, 3)::SparseMatrixCSC{Float64,Int32} == Matrix(2I, 3, 3)\n @test SparseMatrixCSC{Float64,Int32}(0I, 3, 3)::SparseMatrixCSC{Float64,Int32} == Matrix(0I, 3, 3)\nend",
"@testset \"sparse(S::UniformScaling, shape...) convenience constructors\" begin\n # we exercise these methods only lightly as these methods call the SparseMatrixCSC\n # constructor methods well-exercised by the immediately preceding testset\n @test sparse(2I, 3, 4)::SparseMatrixCSC{Int,Int} == Matrix(2I, 3, 4)\n @test sparse(2I, (3, 4))::SparseMatrixCSC{Int,Int} == Matrix(2I, 3, 4)\nend",
"@testset \"sparse binary operations\" begin\n @test isequal(se33 * se33, se33)\n\n @test Array(se33 + convert(SparseMatrixCSC{Float32,Int32}, se33)) == Matrix(2I, 3, 3)\n @test Array(se33 * convert(SparseMatrixCSC{Float32,Int32}, se33)) == Matrix(I, 3, 3)\n\n @testset \"shape checks for sparse elementwise binary operations equivalent to map\" begin\n sqrfloatmat, colfloatmat = sprand(4, 4, 0.5), sprand(4, 1, 0.5)\n @test_throws DimensionMismatch (+)(sqrfloatmat, colfloatmat)\n @test_throws DimensionMismatch (-)(sqrfloatmat, colfloatmat)\n @test_throws DimensionMismatch map(min, sqrfloatmat, colfloatmat)\n @test_throws DimensionMismatch map(max, sqrfloatmat, colfloatmat)\n sqrboolmat, colboolmat = sprand(Bool, 4, 4, 0.5), sprand(Bool, 4, 1, 0.5)\n @test_throws DimensionMismatch map(&, sqrboolmat, colboolmat)\n @test_throws DimensionMismatch map(|, sqrboolmat, colboolmat)\n @test_throws DimensionMismatch map(xor, sqrboolmat, colboolmat)\n end\nend",
"@testset \"Issue #30006\" begin\n SparseMatrixCSC{Float64,Int32}(spzeros(3,3))[:, 1] == [1, 2, 3]\nend",
"@testset \"concatenation tests\" begin\n sp33 = sparse(1.0I, 3, 3)\n\n @testset \"horizontal concatenation\" begin\n @test [se33 se33] == [Array(se33) Array(se33)]\n @test length(([sp33 0I]).nzval) == 3\n end\n\n @testset \"vertical concatenation\" begin\n @test [se33; se33] == [Array(se33); Array(se33)]\n se33_32bit = convert(SparseMatrixCSC{Float32,Int32}, se33)\n @test [se33; se33_32bit] == [Array(se33); Array(se33_32bit)]\n @test length(([sp33; 0I]).nzval) == 3\n end\n\n se44 = sparse(1.0I, 4, 4)\n sz42 = spzeros(4, 2)\n sz41 = spzeros(4, 1)\n sz34 = spzeros(3, 4)\n se77 = sparse(1.0I, 7, 7)\n @testset \"h+v concatenation\" begin\n @test [se44 sz42 sz41; sz34 se33] == se77\n @test length(([sp33 0I; 1I 0I]).nzval) == 6\n end\n\n @testset \"blockdiag concatenation\" begin\n @test blockdiag(se33, se33) == sparse(1:6,1:6,fill(1.,6))\n @test blockdiag() == spzeros(0, 0)\n @test nnz(blockdiag()) == 0\n end\n\n @testset \"concatenation promotion\" begin\n sz41_f32 = spzeros(Float32, 4, 1)\n se33_i32 = sparse(Int32(1)I, 3, 3)\n @test [se44 sz42 sz41_f32; sz34 se33_i32] == se77\n end\n\n @testset \"mixed sparse-dense concatenation\" begin\n sz33 = spzeros(3, 3)\n de33 = Matrix(1.0I, 3, 3)\n @test [se33 de33; sz33 se33] == Array([se33 se33; sz33 se33 ])\n end\n\n # check splicing + concatenation on random instances, with nested vcat and also side-checks sparse ref\n @testset \"splicing + concatenation on random instances\" begin\n for i = 1 : 10\n a = sprand(5, 4, 0.5)\n @test [a[1:2,1:2] a[1:2,3:4]; a[3:5,1] [a[3:4,2:4]; a[5:5,2:4]]] == a\n end\n end\nend",
"@testset \"dropdims\" begin\n for i = 1:5\n am = sprand(20, 1, 0.2)\n av = dropdims(am, dims=2)\n @test ndims(av) == 1\n @test all(av.==am)\n am = sprand(1, 20, 0.2)\n av = dropdims(am, dims=1)\n @test ndims(av) == 1\n @test all(av' .== am)\n end\nend",
"@testset \"Issue #28963\" begin\n @test_throws DimensionMismatch (spzeros(10,10)[:, :] = sprand(10,20,0.5))\nend",
"@testset \"matrix-vector multiplication (non-square)\" begin\n for i = 1:5\n a = sprand(10, 5, 0.5)\n b = rand(5)\n @test maximum(abs.(a*b - Array(a)*b)) < 100*eps()\n end\nend",
"@testset \"sparse matrix * BitArray\" begin\n A = sprand(5,5,0.2)\n B = trues(5)\n @test A*B ≈ Array(A)*B\n B = trues(5,5)\n @test A*B ≈ Array(A)*B\n @test B*A ≈ B*Array(A)\nend",
"@testset \"complex matrix-vector multiplication and left-division\" begin\n if Base.USE_GPL_LIBS\n for i = 1:5\n a = I + 0.1*sprandn(5, 5, 0.2)\n b = randn(5,3) + im*randn(5,3)\n c = randn(5) + im*randn(5)\n d = randn(5) + im*randn(5)\n α = rand(ComplexF64)\n β = rand(ComplexF64)\n @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())\n @test (maximum(abs.(mul!(similar(b), a, b) - Array(a)*b)) < 100*eps()) # for compatibility with present matmul API. Should go away eventually.\n @test (maximum(abs.(mul!(similar(c), a, c) - Array(a)*c)) < 100*eps()) # for compatibility with present matmul API. Should go away eventually.\n @test (maximum(abs.(mul!(similar(b), transpose(a), b) - transpose(Array(a))*b)) < 100*eps()) # for compatibility with present matmul API. Should go away eventually.\n @test (maximum(abs.(mul!(similar(c), transpose(a), c) - transpose(Array(a))*c)) < 100*eps()) # for compatibility with present matmul API. Should go away eventually.\n @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())\n @test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())\n @test (maximum(abs.(a\\b - Array(a)\\b)) < 1000*eps())\n @test (maximum(abs.(a'\\b - Array(a')\\b)) < 1000*eps())\n @test (maximum(abs.(transpose(a)\\b - Array(transpose(a))\\b)) < 1000*eps())\n @test (maximum(abs.((a'*c + d) - (Array(a)'*c + d))) < 1000*eps())\n @test (maximum(abs.((α*transpose(a)*c + β*d) - (α*transpose(Array(a))*c + β*d))) < 1000*eps())\n @test (maximum(abs.((transpose(a)*c + d) - (transpose(Array(a))*c + d))) < 1000*eps())\n c = randn(6) + im*randn(6)\n @test_throws DimensionMismatch α*transpose(a)*c + β*c\n @test_throws DimensionMismatch α*transpose(a)*fill(1.,5) + β*c\n\n a = I + 0.1*sprandn(5, 5, 0.2) + 0.1*im*sprandn(5, 5, 0.2)\n b = randn(5,3)\n @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())\n @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())\n @test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())\n @test (maximum(abs.(a\\b - Array(a)\\b)) < 1000*eps())\n @test (maximum(abs.(a'\\b - Array(a')\\b)) < 1000*eps())\n @test (maximum(abs.(transpose(a)\\b - Array(transpose(a))\\b)) < 1000*eps())\n\n a = I + tril(0.1*sprandn(5, 5, 0.2))\n b = randn(5,3) + im*randn(5,3)\n @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())\n @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())\n @test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())\n @test (maximum(abs.(a\\b - Array(a)\\b)) < 1000*eps())\n @test (maximum(abs.(a'\\b - Array(a')\\b)) < 1000*eps())\n @test (maximum(abs.(transpose(a)\\b - Array(transpose(a))\\b)) < 1000*eps())\n\n a = I + tril(0.1*sprandn(5, 5, 0.2) + 0.1*im*sprandn(5, 5, 0.2))\n b = randn(5,3)\n @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())\n @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())\n @test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())\n @test (maximum(abs.(a\\b - Array(a)\\b)) < 1000*eps())\n @test (maximum(abs.(a'\\b - Array(a')\\b)) < 1000*eps())\n @test (maximum(abs.(transpose(a)\\b - Array(transpose(a))\\b)) < 1000*eps())\n\n a = I + triu(0.1*sprandn(5, 5, 0.2))\n b = randn(5,3) + im*randn(5,3)\n @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())\n @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())\n @test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())\n @test (maximum(abs.(a\\b - Array(a)\\b)) < 1000*eps())\n @test (maximum(abs.(a'\\b - Array(a')\\b)) < 1000*eps())\n @test (maximum(abs.(transpose(a)\\b - Array(transpose(a))\\b)) < 1000*eps())\n\n a = I + triu(0.1*sprandn(5, 5, 0.2) + 0.1*im*sprandn(5, 5, 0.2))\n b = randn(5,3)\n @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())\n @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())\n @test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())\n @test (maximum(abs.(a\\b - Array(a)\\b)) < 1000*eps())\n @test (maximum(abs.(a'\\b - Array(a')\\b)) < 1000*eps())\n @test (maximum(abs.(transpose(a)\\b - Array(transpose(a))\\b)) < 1000*eps())\n\n a = I + triu(0.1*sprandn(5, 5, 0.2))\n b = randn(5,3) + im*randn(5,3)\n @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())\n @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())\n @test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())\n @test (maximum(abs.(a\\b - Array(a)\\b)) < 1000*eps())\n @test (maximum(abs.(a'\\b - Array(a')\\b)) < 1000*eps())\n @test (maximum(abs.(transpose(a)\\b - Array(transpose(a))\\b)) < 1000*eps())\n\n # UpperTriangular/LowerTriangular solve\n a = UpperTriangular(I + triu(0.1*sprandn(5, 5, 0.2)))\n b = sprandn(5, 5, 0.2)\n @test (maximum(abs.(a\\b - Array(a)\\Array(b))) < 1000*eps())\n # test error throwing for bwdTrisolve\n @test_throws DimensionMismatch a\\Matrix{Float64}(I, 6, 6)\n a = LowerTriangular(I + tril(0.1*sprandn(5, 5, 0.2)))\n b = sprandn(5, 5, 0.2)\n @test (maximum(abs.(a\\b - Array(a)\\Array(b))) < 1000*eps())\n # test error throwing for fwdTrisolve\n @test_throws DimensionMismatch a\\Matrix{Float64}(I, 6, 6)\n\n\n\n a = sparse(Diagonal(randn(5) + im*randn(5)))\n b = randn(5,3)\n @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())\n @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())\n @test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())\n @test (maximum(abs.(a\\b - Array(a)\\b)) < 1000*eps())\n @test (maximum(abs.(a'\\b - Array(a')\\b)) < 1000*eps())\n @test (maximum(abs.(transpose(a)\\b - Array(transpose(a))\\b)) < 1000*eps())\n\n b = randn(5,3) + im*randn(5,3)\n @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps())\n @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps())\n @test (maximum(abs.(transpose(a)*b - transpose(Array(a))*b)) < 100*eps())\n @test (maximum(abs.(a\\b - Array(a)\\b)) < 1000*eps())\n @test (maximum(abs.(a'\\b - Array(a')\\b)) < 1000*eps())\n @test (maximum(abs.(transpose(a)\\b - Array(transpose(a))\\b)) < 1000*eps())\n end\n end\nend",
"@testset \"matrix multiplication\" begin\n for (m, p, n, q, k) in (\n (10, 0.7, 5, 0.3, 15),\n (100, 0.01, 100, 0.01, 20),\n (100, 0.1, 100, 0.2, 100),\n )\n a = sprand(m, n, p)\n b = sprand(n, k, q)\n as = sparse(a')\n bs = sparse(b')\n ab = a * b\n aab = Array(a) * Array(b)\n @test maximum(abs.(ab - aab)) < 100*eps()\n @test a*bs' == ab\n @test as'*b == ab\n @test as'*bs' == ab\n f = Diagonal(rand(n))\n @test Array(a*f) == Array(a)*f\n @test Array(f*b) == f*Array(b)\n A = rand(2n, 2n)\n sA = view(A, 1:2:2n, 1:2:2n)\n @test Array(sA*b) ≈ Array(sA)*Array(b)\n @test Array(a*sA) ≈ Array(a)*Array(sA)\n c = sprandn(ComplexF32, n, n, q)\n @test Array(sA*c') ≈ Array(sA)*Array(c)'\n @test Array(c'*sA) ≈ Array(c)'*Array(sA)\n end\nend",
"@testset \"Issue #30502\" begin\n @test nnz(sprand(UInt8(16), UInt8(16), 1.0)) == 256\n @test nnz(sprand(UInt8(16), UInt8(16), 1.0, ones)) == 256\nend",
"@testset \"kronecker product\" begin\n for (m,n) in ((5,10), (13,8), (14,10))\n a = sprand(m, 5, 0.4); a_d = Matrix(a)\n b = sprand(n, 6, 0.3); b_d = Matrix(b)\n v = view(a, :, 1); v_d = Vector(v)\n x = sprand(m, 0.4); x_d = Vector(x)\n y = sprand(n, 0.3); y_d = Vector(y)\n # mat ⊗ mat\n @test Array(kron(a, b)) == kron(a_d, b_d)\n @test Array(kron(a_d, b)) == kron(a_d, b_d)\n @test Array(kron(a, b_d)) == kron(a_d, b_d)\n # vec ⊗ vec\n @test Vector(kron(x, y)) == kron(x_d, y_d)\n @test Vector(kron(x_d, y)) == kron(x_d, y_d)\n @test Vector(kron(x, y_d)) == kron(x_d, y_d)\n # mat ⊗ vec\n @test Array(kron(a, y)) == kron(a_d, y_d)\n @test Array(kron(a_d, y)) == kron(a_d, y_d)\n @test Array(kron(a, y_d)) == kron(a_d, y_d)\n # vec ⊗ mat\n @test Array(kron(x, b)) == kron(x_d, b_d)\n @test Array(kron(x_d, b)) == kron(x_d, b_d)\n @test Array(kron(x, b_d)) == kron(x_d, b_d)\n # vec ⊗ vec'\n @test issparse(kron(v, y'))\n @test issparse(kron(x, y'))\n @test Array(kron(v, y')) == kron(v_d, y_d')\n @test Array(kron(x, y')) == kron(x_d, y_d')\n # test different types\n z = convert(SparseVector{Float16, Int8}, y); z_d = Vector(z)\n @test Vector(kron(x, z)) == kron(x_d, z_d)\n @test Array(kron(a, z)) == kron(a_d, z_d)\n @test Array(kron(z, b)) == kron(z_d, b_d)\n end\nend",
"@testset \"sparse Frobenius dot/inner product\" begin\n for i = 1:5\n A = sprand(ComplexF64,10,15,0.4)\n B = sprand(ComplexF64,10,15,0.5)\n @test dot(A,B) ≈ dot(Matrix(A),Matrix(B))\n end\n @test_throws DimensionMismatch dot(sprand(5,5,0.2),sprand(5,6,0.2))\nend",
"@testset \"scaling with * and mul!, rmul!, and lmul!\" begin\n b = randn(7)\n @test dA * Diagonal(b) == sA * Diagonal(b)\n @test dA * Diagonal(b) == mul!(sC, sA, Diagonal(b))\n @test dA * Diagonal(b) == rmul!(copy(sA), Diagonal(b))\n b = randn(3)\n @test Diagonal(b) * dA == Diagonal(b) * sA\n @test Diagonal(b) * dA == mul!(sC, Diagonal(b), sA)\n @test Diagonal(b) * dA == lmul!(Diagonal(b), copy(sA))\n\n @test dA * 0.5 == sA * 0.5\n @test dA * 0.5 == mul!(sC, sA, 0.5)\n @test dA * 0.5 == rmul!(copy(sA), 0.5)\n @test 0.5 * dA == 0.5 * sA\n @test 0.5 * dA == mul!(sC, sA, 0.5)\n @test 0.5 * dA == lmul!(0.5, copy(sA))\n @test mul!(sC, 0.5, sA) == mul!(sC, sA, 0.5)\n\n @testset \"inverse scaling with mul!\" begin\n bi = inv.(b)\n @test lmul!(Diagonal(bi), copy(dA)) ≈ ldiv!(Diagonal(b), copy(sA))\n @test lmul!(Diagonal(bi), copy(dA)) ≈ ldiv!(transpose(Diagonal(b)), copy(sA))\n @test lmul!(Diagonal(conj(bi)), copy(dA)) ≈ ldiv!(adjoint(Diagonal(b)), copy(sA))\n @test_throws DimensionMismatch ldiv!(Diagonal(fill(1., length(b)+1)), copy(sA))\n @test_throws LinearAlgebra.SingularException ldiv!(Diagonal(zeros(length(b))), copy(sA))\n\n dAt = copy(transpose(dA))\n sAt = copy(transpose(sA))\n @test rmul!(copy(dAt), Diagonal(bi)) ≈ rdiv!(copy(sAt), Diagonal(b))\n @test rmul!(copy(dAt), Diagonal(bi)) ≈ rdiv!(copy(sAt), transpose(Diagonal(b)))\n @test rmul!(copy(dAt), Diagonal(conj(bi))) ≈ rdiv!(copy(sAt), adjoint(Diagonal(b)))\n @test_throws DimensionMismatch rdiv!(copy(sAt), Diagonal(fill(1., length(b)+1)))\n @test_throws LinearAlgebra.SingularException rdiv!(copy(sAt), Diagonal(zeros(length(b))))\n end\n\n @testset \"non-commutative multiplication\" begin\n # non-commutative multiplication\n Avals = Quaternion.(randn(10), randn(10), randn(10), randn(10))\n sA = sparse(rand(1:3, 10), rand(1:7, 10), Avals, 3, 7)\n sC = copy(sA)\n dA = Array(sA)\n\n b = Quaternion.(randn(7), randn(7), randn(7), randn(7))\n D = Diagonal(b)\n @test Array(sA * D) ≈ dA * D\n @test rmul!(copy(sA), D) ≈ dA * D\n @test mul!(sC, copy(sA), D) ≈ dA * D\n\n b = Quaternion.(randn(3), randn(3), randn(3), randn(3))\n D = Diagonal(b)\n @test Array(D * sA) ≈ D * dA\n @test lmul!(D, copy(sA)) ≈ D * dA\n @test mul!(sC, D, copy(sA)) ≈ D * dA\n end\nend",
"@testset \"copyto!\" begin\n A = sprand(5, 5, 0.2)\n B = sprand(5, 5, 0.2)\n copyto!(A, B)\n @test A == B\n @test pointer(A.nzval) != pointer(B.nzval)\n @test pointer(A.rowval) != pointer(B.rowval)\n @test pointer(A.colptr) != pointer(B.colptr)\n # Test size(A) != size(B), but length(A) == length(B)\n B = sprand(25, 1, 0.2)\n copyto!(A, B)\n @test A[:] == B[:]\n # Test various size(A) / size(B) combinations\n for mA in [5, 10, 20], nA in [5, 10, 20], mB in [5, 10, 20], nB in [5, 10, 20]\n A = sprand(mA,nA,0.4)\n Aorig = copy(A)\n B = sprand(mB,nB,0.4)\n if mA*nA >= mB*nB\n copyto!(A,B)\n @assert(A[1:length(B)] == B[:])\n @assert(A[length(B)+1:end] == Aorig[length(B)+1:end])\n else\n @test_throws BoundsError copyto!(A,B)\n end\n end\n # Test eltype(A) != eltype(B), size(A) != size(B)\n A = sprand(5, 5, 0.2)\n Aorig = copy(A)\n B = sparse(rand(Float32, 3, 3))\n copyto!(A, B)\n @test A[1:9] == B[:]\n @test A[10:end] == Aorig[10:end]\n # Test eltype(A) != eltype(B), size(A) == size(B)\n A = sparse(rand(Float64, 3, 3))\n B = sparse(rand(Float32, 3, 3))\n copyto!(A, B)\n @test A == B\nend",
"@testset \"conj\" begin\n cA = sprandn(5,5,0.2) + im*sprandn(5,5,0.2)\n @test Array(conj.(cA)) == conj(Array(cA))\n @test Array(conj!(copy(cA))) == conj(Array(cA))\nend",
"@testset \"SparseMatrixCSC [c]transpose[!] and permute[!]\" begin\n smalldim = 5\n largedim = 10\n nzprob = 0.4\n (m, n) = (smalldim, smalldim)\n A = sprand(m, n, nzprob)\n X = similar(A)\n C = copy(transpose(A))\n p = randperm(m)\n q = randperm(n)\n @testset \"common error checking of [c]transpose! methods (ftranspose!)\" begin\n @test_throws DimensionMismatch transpose!(A[:, 1:(smalldim - 1)], A)\n @test_throws DimensionMismatch transpose!(A[1:(smalldim - 1), 1], A)\n @test_throws ArgumentError transpose!((B = similar(A); resize!(B.rowval, nnz(A) - 1); B), A)\n @test_throws ArgumentError transpose!((B = similar(A); resize!(B.nzval, nnz(A) - 1); B), A)\n end\n @testset \"common error checking of permute[!] methods / source-perm compat\" begin\n @test_throws DimensionMismatch permute(A, p[1:(end - 1)], q)\n @test_throws DimensionMismatch permute(A, p, q[1:(end - 1)])\n end\n @testset \"common error checking of permute[!] methods / source-dest compat\" begin\n @test_throws DimensionMismatch permute!(A[1:(m - 1), :], A, p, q)\n @test_throws DimensionMismatch permute!(A[:, 1:(m - 1)], A, p, q)\n @test_throws ArgumentError permute!((Y = copy(X); resize!(Y.rowval, nnz(A) - 1); Y), A, p, q)\n @test_throws ArgumentError permute!((Y = copy(X); resize!(Y.nzval, nnz(A) - 1); Y), A, p, q)\n end\n @testset \"common error checking of permute[!] methods / source-workmat compat\" begin\n @test_throws DimensionMismatch permute!(X, A, p, q, C[1:(m - 1), :])\n @test_throws DimensionMismatch permute!(X, A, p, q, C[:, 1:(m - 1)])\n @test_throws ArgumentError permute!(X, A, p, q, (D = copy(C); resize!(D.rowval, nnz(A) - 1); D))\n @test_throws ArgumentError permute!(X, A, p, q, (D = copy(C); resize!(D.nzval, nnz(A) - 1); D))\n end\n @testset \"common error checking of permute[!] methods / source-workcolptr compat\" begin\n @test_throws DimensionMismatch permute!(A, p, q, C, Vector{eltype(A.rowval)}(undef, length(A.colptr) - 1))\n end\n @testset \"common error checking of permute[!] methods / permutation validity\" begin\n @test_throws ArgumentError permute!(A, (r = copy(p); r[2] = r[1]; r), q)\n @test_throws ArgumentError permute!(A, (r = copy(p); r[2] = m + 1; r), q)\n @test_throws ArgumentError permute!(A, p, (r = copy(q); r[2] = r[1]; r))\n @test_throws ArgumentError permute!(A, p, (r = copy(q); r[2] = n + 1; r))\n end\n @testset \"overall functionality of [c]transpose[!] and permute[!]\" begin\n for (m, n) in ((smalldim, smalldim), (smalldim, largedim), (largedim, smalldim))\n A = sprand(m, n, nzprob)\n At = copy(transpose(A))\n # transpose[!]\n fullAt = Array(transpose(A))\n @test copy(transpose(A)) == fullAt\n @test transpose!(similar(At), A) == fullAt\n # adjoint[!]\n C = A + im*A/2\n fullCh = Array(C')\n @test copy(C') == fullCh\n @test adjoint!(similar(sparse(fullCh)), C) == fullCh\n # permute[!]\n p = randperm(m)\n q = randperm(n)\n fullPAQ = Array(A)[p,q]\n @test permute(A, p, q) == sparse(Array(A[p,q]))\n @test permute!(similar(A), A, p, q) == fullPAQ\n @test permute!(similar(A), A, p, q, similar(At)) == fullPAQ\n @test permute!(copy(A), p, q) == fullPAQ\n @test permute!(copy(A), p, q, similar(At)) == fullPAQ\n @test permute!(copy(A), p, q, similar(At), similar(A.colptr)) == fullPAQ\n end\n end\nend",
"@testset \"transpose of SubArrays\" begin\n A = view(sprandn(10, 10, 0.3), 1:4, 1:4)\n @test copy(transpose(Array(A))) == Array(transpose(A))\n @test copy(adjoint(Array(A))) == Array(adjoint(A))\nend",
"@testset \"exp\" begin\n A = sprandn(5,5,0.2)\n @test ℯ.^A ≈ ℯ.^Array(A)\nend",
"@testset \"reductions\" begin\n pA = sparse(rand(3, 7))\n p28227 = sparse(Real[0 0.5])\n\n for arr in (se33, sA, pA, p28227)\n for f in (sum, prod, minimum, maximum)\n farr = Array(arr)\n @test f(arr) ≈ f(farr)\n @test f(arr, dims=1) ≈ f(farr, dims=1)\n @test f(arr, dims=2) ≈ f(farr, dims=2)\n @test f(arr, dims=(1, 2)) ≈ [f(farr)]\n @test isequal(f(arr, dims=3), f(farr, dims=3))\n end\n end\n\n for f in (sum, prod, minimum, maximum)\n # Test with a map function that maps to non-zero\n for arr in (se33, sA, pA)\n @test f(x->x+1, arr) ≈ f(arr .+ 1)\n end\n\n # case where f(0) would throw\n @test f(x->sqrt(x-1), pA .+ 1) ≈ f(sqrt.(pA))\n # these actually throw due to #10533\n # @test f(x->sqrt(x-1), pA .+ 1, dims=1) ≈ f(sqrt(pA), dims=1)\n # @test f(x->sqrt(x-1), pA .+ 1, dims=2) ≈ f(sqrt(pA), dims=2)\n # @test f(x->sqrt(x-1), pA .+ 1, dims=3) ≈ f(pA)\n end\n\n @testset \"empty cases\" begin\n @test sum(sparse(Int[])) === 0\n @test prod(sparse(Int[])) === 1\n @test_throws ArgumentError minimum(sparse(Int[]))\n @test_throws ArgumentError maximum(sparse(Int[]))\n\n for f in (sum, prod)\n @test isequal(f(spzeros(0, 1), dims=1), f(Matrix{Int}(I, 0, 1), dims=1))\n @test isequal(f(spzeros(0, 1), dims=2), f(Matrix{Int}(I, 0, 1), dims=2))\n @test isequal(f(spzeros(0, 1), dims=(1, 2)), f(Matrix{Int}(I, 0, 1), dims=(1, 2)))\n @test isequal(f(spzeros(0, 1), dims=3), f(Matrix{Int}(I, 0, 1), dims=3))\n end\n for f in (minimum, maximum, findmin, findmax)\n @test_throws ArgumentError f(spzeros(0, 1), dims=1)\n @test isequal(f(spzeros(0, 1), dims=2), f(Matrix{Int}(I, 0, 1), dims=2))\n @test_throws ArgumentError f(spzeros(0, 1), dims=(1, 2))\n @test isequal(f(spzeros(0, 1), dims=3), f(Matrix{Int}(I, 0, 1), dims=3))\n end\n end\nend",
"@testset \"issue #5190\" begin\n @test_throws ArgumentError sparsevec([3,5,7],[0.1,0.0,3.2],4)\nend",
"@testset \"what used to be issue #5386\" begin\n K,J,V = findnz(SparseMatrixCSC(2,1,[1,3],[1,2],[1.0,0.0]))\n @test length(K) == length(J) == length(V) == 2\nend",
"@testset \"findall\" begin\n # issue described in https://groups.google.com/d/msg/julia-users/Yq4dh8NOWBQ/GU57L90FZ3EJ\n A = sparse(I, 5, 5)\n @test findall(A) == findall(x -> x == true, A) == findall(Array(A))\n # Non-stored entries are true\n @test findall(x -> x == false, A) == findall(x -> x == false, Array(A))\n\n # Not all stored entries are true\n @test findall(sparse([true false])) == [CartesianIndex(1, 1)]\n @test findall(x -> x > 1, sparse([1 2])) == [CartesianIndex(1, 2)]\nend",
"@testset \"issue #5824\" begin\n @test sprand(4,5,0.5).^0 == sparse(fill(1,4,5))\nend",
"@testset \"issue #5985\" begin\n @test sprand(Bool, 4, 5, 0.0) == sparse(zeros(Bool, 4, 5))\n @test sprand(Bool, 4, 5, 1.00) == sparse(fill(true, 4, 5))\n sprb45nnzs = zeros(5)\n for i=1:5\n sprb45 = sprand(Bool, 4, 5, 0.5)\n @test length(sprb45) == 20\n sprb45nnzs[i] = sum(sprb45)[1]\n end\n @test 4 <= sum(sprb45nnzs)/length(sprb45nnzs) <= 16\nend",
"@testset \"issue #5853, sparse diff\" begin\n for i=1:2, a=Any[[1 2 3], reshape([1, 2, 3],(3,1)), Matrix(1.0I, 3, 3)]\n @test diff(sparse(a),dims=i) == diff(a,dims=i)\n end\nend",
"@testset \"access to undefined error types that initially allocate elements as #undef\" begin\n @test sparse(1:2, 1:2, Number[1,2])^2 == sparse(1:2, 1:2, [1,4])\n sd1 = diff(sparse([1,1,1], [1,2,3], Number[1,2,3]), dims=1)\nend",
"@testset \"issue #6036\" begin\n P = spzeros(Float64, 3, 3)\n for i = 1:3\n P[i,i] = i\n end\n\n @test minimum(P) === 0.0\n @test maximum(P) === 3.0\n @test minimum(-P) === -3.0\n @test maximum(-P) === 0.0\n\n @test maximum(P, dims=(1,)) == [1.0 2.0 3.0]\n @test maximum(P, dims=(2,)) == reshape([1.0,2.0,3.0],3,1)\n @test maximum(P, dims=(1,2)) == reshape([3.0],1,1)\n\n @test maximum(sparse(fill(-1,3,3))) == -1\n @test minimum(sparse(fill(1,3,3))) == 1\nend",
"@testset \"unary functions\" begin\n A = sprand(5, 15, 0.5)\n C = A + im*A\n Afull = Array(A)\n Cfull = Array(C)\n # Test representatives of [unary functions that map zeros to zeros and may map nonzeros to zeros]\n @test sin.(Afull) == Array(sin.(A))\n @test tan.(Afull) == Array(tan.(A)) # should be redundant with sin test\n @test ceil.(Afull) == Array(ceil.(A))\n @test floor.(Afull) == Array(floor.(A)) # should be redundant with ceil test\n @test real.(Afull) == Array(real.(A)) == Array(real(A))\n @test imag.(Afull) == Array(imag.(A)) == Array(imag(A))\n @test conj.(Afull) == Array(conj.(A)) == Array(conj(A))\n @test real.(Cfull) == Array(real.(C)) == Array(real(C))\n @test imag.(Cfull) == Array(imag.(C)) == Array(imag(C))\n @test conj.(Cfull) == Array(conj.(C)) == Array(conj(C))\n # Test representatives of [unary functions that map zeros to zeros and nonzeros to nonzeros]\n @test expm1.(Afull) == Array(expm1.(A))\n @test abs.(Afull) == Array(abs.(A))\n @test abs2.(Afull) == Array(abs2.(A))\n @test abs.(Cfull) == Array(abs.(C))\n @test abs2.(Cfull) == Array(abs2.(C))\n # Test representatives of [unary functions that map both zeros and nonzeros to nonzeros]\n @test cos.(Afull) == Array(cos.(A))\n # Test representatives of remaining vectorized-nonbroadcast unary functions\n @test ceil.(Int, Afull) == Array(ceil.(Int, A))\n @test floor.(Int, Afull) == Array(floor.(Int, A))\n # Tests of real, imag, abs, and abs2 for SparseMatrixCSC{Int,X}s previously elsewhere\n for T in (Int, Float16, Float32, Float64, BigInt, BigFloat)\n R = rand(T[1:100;], 2, 2)\n I = rand(T[1:100;], 2, 2)\n D = R + I*im\n S = sparse(D)\n spR = sparse(R)\n\n @test R == real.(S) == real(S)\n @test I == imag.(S) == imag(S)\n @test conj(Array(S)) == conj.(S) == conj(S)\n @test real.(spR) == R\n @test nnz(imag.(spR)) == nnz(imag(spR)) == 0\n @test abs.(S) == abs.(D)\n @test abs2.(S) == abs2.(D)\n\n # test aliasing of real and conj of real valued matrix\n @test real(spR) === spR\n @test conj(spR) === spR\n end\nend",
"@testset \"getindex\" begin\n ni = 23\n nj = 32\n a116 = reshape(1:(ni*nj), ni, nj)\n s116 = sparse(a116)\n\n ad116 = diagm(0 => diag(a116))\n sd116 = sparse(ad116)\n\n for (aa116, ss116) in [(a116, s116), (ad116, sd116)]\n ij=11; i=3; j=2\n @test ss116[ij] == aa116[ij]\n @test ss116[(i,j)] == aa116[i,j]\n @test ss116[i,j] == aa116[i,j]\n @test ss116[i-1,j] == aa116[i-1,j]\n ss116[i,j] = 0\n @test ss116[i,j] == 0\n ss116 = sparse(aa116)\n\n @test ss116[:,:] == copy(ss116)\n\n @test convert(SparseMatrixCSC{Float32,Int32}, sd116)[2:5,:] == convert(SparseMatrixCSC{Float32,Int32}, sd116[2:5,:])\n\n # range indexing\n @test Array(ss116[i,:]) == aa116[i,:]\n @test Array(ss116[:,j]) == aa116[:,j]\n @test Array(ss116[i,1:2:end]) == aa116[i,1:2:end]\n @test Array(ss116[1:2:end,j]) == aa116[1:2:end,j]\n @test Array(ss116[i,end:-2:1]) == aa116[i,end:-2:1]\n @test Array(ss116[end:-2:1,j]) == aa116[end:-2:1,j]\n # float-range indexing is not supported\n\n # sorted vector indexing\n @test Array(ss116[i,[3:2:end-3;]]) == aa116[i,[3:2:end-3;]]\n @test Array(ss116[[3:2:end-3;],j]) == aa116[[3:2:end-3;],j]\n @test Array(ss116[i,[end-3:-2:1;]]) == aa116[i,[end-3:-2:1;]]\n @test Array(ss116[[end-3:-2:1;],j]) == aa116[[end-3:-2:1;],j]\n\n # unsorted vector indexing with repetition\n p = [4, 1, 2, 3, 2, 6]\n @test Array(ss116[p,:]) == aa116[p,:]\n @test Array(ss116[:,p]) == aa116[:,p]\n @test Array(ss116[p,p]) == aa116[p,p]\n\n # bool indexing\n li = bitrand(size(aa116,1))\n lj = bitrand(size(aa116,2))\n @test Array(ss116[li,j]) == aa116[li,j]\n @test Array(ss116[li,:]) == aa116[li,:]\n @test Array(ss116[i,lj]) == aa116[i,lj]\n @test Array(ss116[:,lj]) == aa116[:,lj]\n @test Array(ss116[li,lj]) == aa116[li,lj]\n\n # empty indices\n for empty in (1:0, Int[])\n @test Array(ss116[empty,:]) == aa116[empty,:]\n @test Array(ss116[:,empty]) == aa116[:,empty]\n @test Array(ss116[empty,lj]) == aa116[empty,lj]\n @test Array(ss116[li,empty]) == aa116[li,empty]\n @test Array(ss116[empty,empty]) == aa116[empty,empty]\n end\n\n # out of bounds indexing\n @test_throws BoundsError ss116[0, 1]\n @test_throws BoundsError ss116[end+1, 1]\n @test_throws BoundsError ss116[1, 0]\n @test_throws BoundsError ss116[1, end+1]\n for j in (1, 1:size(s116,2), 1:1, Int[1], trues(size(s116, 2)), 1:0, Int[])\n @test_throws BoundsError ss116[0:1, j]\n @test_throws BoundsError ss116[[0, 1], j]\n @test_throws BoundsError ss116[end:end+1, j]\n @test_throws BoundsError ss116[[end, end+1], j]\n end\n for i in (1, 1:size(s116,1), 1:1, Int[1], trues(size(s116, 1)), 1:0, Int[])\n @test_throws BoundsError ss116[i, 0:1]\n @test_throws BoundsError ss116[i, [0, 1]]\n @test_throws BoundsError ss116[i, end:end+1]\n @test_throws BoundsError ss116[i, [end, end+1]]\n end\n end\n\n # workaround issue #7197: comment out let-block\n #let S = SparseMatrixCSC(3, 3, UInt8[1,1,1,1], UInt8[], Int64[])\n S1290 = SparseMatrixCSC(3, 3, UInt8[1,1,1,1], UInt8[], Int64[])\n S1290[1,1] = 1\n S1290[5] = 2\n S1290[end] = 3\n @test S1290[end] == (S1290[1] + S1290[2,2])\n @test 6 == sum(diag(S1290))\n @test Array(S1290)[[3,1],1] == Array(S1290[[3,1],1])\n\n # check that indexing with an abstract array returns matrix\n # with same colptr and rowval eltypes as input. Tests PR 24548\n r1 = S1290[[5,9]]\n r2 = S1290[[1 2;5 9]]\n @test isa(r1, SparseVector{Int64,UInt8})\n @test isa(r2, SparseMatrixCSC{Int64,UInt8})\n # end\nend",
"@testset \"setindex\" begin\n a = spzeros(Int, 10, 10)\n @test count(!iszero, a) == 0\n a[1,:] .= 1\n @test count(!iszero, a) == 10\n @test a[1,:] == sparse(fill(1,10))\n a[:,2] .= 2\n @test count(!iszero, a) == 19\n @test a[:,2] == sparse(fill(2,10))\n b = copy(a)\n\n # Zero-assignment behavior of setindex!(A, v, i, j)\n a[1,3] = 0\n @test nnz(a) == 19\n @test count(!iszero, a) == 18\n a[2,1] = 0\n @test nnz(a) == 19\n @test count(!iszero, a) == 18\n\n # Zero-assignment behavior of setindex!(A, v, I, J)\n a[1,:] .= 0\n @test nnz(a) == 19\n @test count(!iszero, a) == 9\n a[2,:] .= 0\n @test nnz(a) == 19\n @test count(!iszero, a) == 8\n a[:,1] .= 0\n @test nnz(a) == 19\n @test count(!iszero, a) == 8\n a[:,2] .= 0\n @test nnz(a) == 19\n @test count(!iszero, a) == 0\n a = copy(b)\n a[:,:] .= 0\n @test nnz(a) == 19\n @test count(!iszero, a) == 0\n\n # Zero-assignment behavior of setindex!(A, B::SparseMatrixCSC, I, J)\n a = copy(b)\n a[1:2,:] = spzeros(2, 10)\n @test nnz(a) == 19\n @test count(!iszero, a) == 8\n a[1:2,1:3] = sparse([1 0 1; 0 0 1])\n @test nnz(a) == 20\n @test count(!iszero, a) == 11\n a = copy(b)\n a[1:2,:] = let c = sparse(fill(1,2,10)); fill!(c.nzval, 0); c; end\n @test nnz(a) == 19\n @test count(!iszero, a) == 8\n a[1:2,1:3] = let c = sparse(fill(1,2,3)); c[1,2] = c[2,1] = c[2,2] = 0; c; end\n @test nnz(a) == 20\n @test count(!iszero, a) == 11\n\n a[1,:] = 1:10\n @test a[1,:] == sparse([1:10;])\n a[:,2] = 1:10\n @test a[:,2] == sparse([1:10;])\n\n a[1,1:0] = []\n @test a[1,:] == sparse([1; 1; 3:10])\n a[1:0,2] = []\n @test a[:,2] == sparse([1:10;])\n a[1,1:0] .= 0\n @test a[1,:] == sparse([1; 1; 3:10])\n a[1:0,2] .= 0\n @test a[:,2] == sparse([1:10;])\n a[1,1:0] .= 1\n @test a[1,:] == sparse([1; 1; 3:10])\n a[1:0,2] .= 1\n @test a[:,2] == sparse([1:10;])\n\n @test_throws BoundsError a[:,11] = spzeros(10,1)\n @test_throws BoundsError a[11,:] = spzeros(1,10)\n @test_throws BoundsError a[:,-1] = spzeros(10,1)\n @test_throws BoundsError a[-1,:] = spzeros(1,10)\n @test_throws BoundsError a[0:9] = spzeros(1,10)\n @test_throws BoundsError (a[:,11] .= 0; a)\n @test_throws BoundsError (a[11,:] .= 0; a)\n @test_throws BoundsError (a[:,-1] .= 0; a)\n @test_throws BoundsError (a[-1,:] .= 0; a)\n @test_throws BoundsError (a[0:9] .= 0; a)\n @test_throws BoundsError (a[:,11] .= 1; a)\n @test_throws BoundsError (a[11,:] .= 1; a)\n @test_throws BoundsError (a[:,-1] .= 1; a)\n @test_throws BoundsError (a[-1,:] .= 1; a)\n @test_throws BoundsError (a[0:9] .= 1; a)\n\n @test_throws DimensionMismatch a[1:2,1:2] = 1:3\n @test_throws DimensionMismatch a[1:2,1] = 1:3\n @test_throws DimensionMismatch a[1,1:2] = 1:3\n @test_throws DimensionMismatch a[1:2] = 1:3\n\n A = spzeros(Int, 10, 20)\n A[1:5,1:10] .= 10\n A[1:5,1:10] .= 10\n @test count(!iszero, A) == 50\n @test A[1:5,1:10] == fill(10, 5, 10)\n A[6:10,11:20] .= 0\n @test count(!iszero, A) == 50\n A[6:10,11:20] .= 20\n @test count(!iszero, A) == 100\n @test A[6:10,11:20] == fill(20, 5, 10)\n A[4:8,8:16] .= 15\n @test count(!iszero, A) == 121\n @test A[4:8,8:16] == fill(15, 5, 9)\n\n ASZ = 1000\n TSZ = 800\n A = sprand(ASZ, 2*ASZ, 0.0001)\n B = copy(A)\n nA = count(!iszero, A)\n x = A[1:TSZ, 1:(2*TSZ)]\n nx = count(!iszero, x)\n A[1:TSZ, 1:(2*TSZ)] .= 0\n nB = count(!iszero, A)\n @test nB == (nA - nx)\n A[1:TSZ, 1:(2*TSZ)] = x\n @test count(!iszero, A) == nA\n @test A == B\n A[1:TSZ, 1:(2*TSZ)] .= 10\n @test count(!iszero, A) == nB + 2*TSZ*TSZ\n A[1:TSZ, 1:(2*TSZ)] = x\n @test count(!iszero, A) == nA\n @test A == B\n\n A = sparse(1I, 5, 5)\n lininds = 1:10\n X=reshape([trues(10); falses(15)],5,5)\n @test A[lininds] == A[X] == [1,0,0,0,0,0,1,0,0,0]\n A[lininds] = [1:10;]\n @test A[lininds] == A[X] == 1:10\n A[lininds] = zeros(Int, 10)\n @test nnz(A) == 13\n @test count(!iszero, A) == 3\n @test A[lininds] == A[X] == zeros(Int, 10)\n c = Vector(11:20); c[1] = c[3] = 0\n A[lininds] = c\n @test nnz(A) == 13\n @test count(!iszero, A) == 11\n @test A[lininds] == A[X] == c\n A = sparse(1I, 5, 5)\n A[lininds] = c\n @test nnz(A) == 12\n @test count(!iszero, A) == 11\n @test A[lininds] == A[X] == c\n\n let # prevent assignment to I from overwriting UniformSampling in enclosing scope\n S = sprand(50, 30, 0.5, x -> round.(Int, rand(x) * 100))\n I = sprand(Bool, 50, 30, 0.2)\n FS = Array(S)\n FI = Array(I)\n @test sparse(FS[FI]) == S[I] == S[FI]\n @test sum(S[FI]) + sum(S[.!FI]) == sum(S)\n @test count(!iszero, I) == count(I)\n\n sumS1 = sum(S)\n sumFI = sum(S[FI])\n nnzS1 = nnz(S)\n S[FI] .= 0\n sumS2 = sum(S)\n cnzS2 = count(!iszero, S)\n @test sum(S[FI]) == 0\n @test nnz(S) == nnzS1\n @test (sum(S) + sumFI) == sumS1\n\n S[FI] .= 10\n nnzS3 = nnz(S)\n @test sum(S) == sumS2 + 10*sum(FI)\n S[FI] .= 0\n @test sum(S) == sumS2\n @test nnz(S) == nnzS3\n @test count(!iszero, S) == cnzS2\n\n S[FI] .= [1:sum(FI);]\n @test sum(S) == sumS2 + sum(1:sum(FI))\n\n S = sprand(50, 30, 0.5, x -> round.(Int, rand(x) * 100))\n N = length(S) >> 2\n I = randperm(N) .* 4\n J = randperm(N)\n sumS1 = sum(S)\n sumS2 = sum(S[I])\n S[I] .= 0\n @test sum(S) == (sumS1 - sumS2)\n S[I] .= J\n @test sum(S) == (sumS1 - sumS2 + sum(J))\n end\nend",
"@testset \"dropstored!\" begin\n A = spzeros(Int, 10, 10)\n # Introduce nonzeros in row and column two\n A[1,:] .= 1\n A[:,2] .= 2\n @test nnz(A) == 19\n\n # Test argument bounds checking for dropstored!(A, i, j)\n @test_throws BoundsError SparseArrays.dropstored!(A, 0, 1)\n @test_throws BoundsError SparseArrays.dropstored!(A, 1, 0)\n @test_throws BoundsError SparseArrays.dropstored!(A, 1, 11)\n @test_throws BoundsError SparseArrays.dropstored!(A, 11, 1)\n\n # Test argument bounds checking for dropstored!(A, I, J)\n @test_throws BoundsError SparseArrays.dropstored!(A, 0:1, 1:1)\n @test_throws BoundsError SparseArrays.dropstored!(A, 1:1, 0:1)\n @test_throws BoundsError SparseArrays.dropstored!(A, 10:11, 1:1)\n @test_throws BoundsError SparseArrays.dropstored!(A, 1:1, 10:11)\n\n # Test behavior of dropstored!(A, i, j)\n # --> Test dropping a single stored entry\n SparseArrays.dropstored!(A, 1, 2)\n @test nnz(A) == 18\n # --> Test dropping a single nonstored entry\n SparseArrays.dropstored!(A, 2, 1)\n @test nnz(A) == 18\n\n # Test behavior of dropstored!(A, I, J) and derivs.\n # --> Test dropping a single row including stored and nonstored entries\n SparseArrays.dropstored!(A, 1, :)\n @test nnz(A) == 9\n # --> Test dropping a single column including stored and nonstored entries\n SparseArrays.dropstored!(A, :, 2)\n @test nnz(A) == 0\n # --> Introduce nonzeros in rows one and two and columns two and three\n A[1:2,:] .= 1\n A[:,2:3] .= 2\n @test nnz(A) == 36\n # --> Test dropping multiple rows containing stored and nonstored entries\n SparseArrays.dropstored!(A, 1:3, :)\n @test nnz(A) == 14\n # --> Test dropping multiple columns containing stored and nonstored entries\n SparseArrays.dropstored!(A, :, 2:4)\n @test nnz(A) == 0\n # --> Introduce nonzeros in every other row\n A[1:2:9, :] .= 1\n @test nnz(A) == 50\n # --> Test dropping a block of the matrix towards the upper left\n SparseArrays.dropstored!(A, 2:5, 2:5)\n @test nnz(A) == 42\nend",
"@testset \"issue #7507\" begin\n @test (i7507=sparsevec(Dict{Int64, Float64}(), 10))==spzeros(10)\nend",
"@testset \"issue #7650\" begin\n S = spzeros(3, 3)\n @test size(reshape(S, 9, 1)) == (9,1)\nend",
"@testset \"sparsevec from matrices\" begin\n X = Matrix(1.0I, 5, 5)\n M = rand(5,4)\n C = spzeros(3,3)\n SX = sparse(X); SM = sparse(M)\n VX = vec(X); VSX = vec(SX)\n VM = vec(M); VSM1 = vec(SM); VSM2 = sparsevec(M)\n VC = vec(C)\n @test VX == VSX\n @test VM == VSM1\n @test VM == VSM2\n @test size(VC) == (9,)\n @test nnz(VC) == 0\n @test nnz(VSX) == 5\nend",
"@testset \"issue #7677\" begin\n A = sprand(5,5,0.5,(n)->rand(Float64,n))\n ACPY = copy(A)\n B = reshape(A,25,1)\n @test A == ACPY\nend",
"@testset \"issue #8225\" begin\n @test_throws ArgumentError sparse([0],[-1],[1.0],2,2)\nend",
"@testset \"issue #8363\" begin\n @test_throws ArgumentError sparsevec(Dict(-1=>1,1=>2))\nend",
"@testset \"issue #8976\" begin\n @test conj.(sparse([1im])) == sparse(conj([1im]))\n @test conj!(sparse([1im])) == sparse(conj!([1im]))\nend",
"@testset \"issue #9525\" begin\n @test_throws ArgumentError sparse([3], [5], 1.0, 3, 3)\nend",
"@testset \"argmax, argmin, findmax, findmin\" begin\n S = sprand(100,80, 0.5)\n A = Array(S)\n @test argmax(S) == argmax(A)\n @test argmin(S) == argmin(A)\n @test findmin(S) == findmin(A)\n @test findmax(S) == findmax(A)\n for region in [(1,), (2,), (1,2)], m in [findmax, findmin]\n @test m(S, dims=region) == m(A, dims=region)\n end\n\n S = spzeros(10,8)\n A = Array(S)\n @test argmax(S) == argmax(A) == CartesianIndex(1,1)\n @test argmin(S) == argmin(A) == CartesianIndex(1,1)\n\n A = Matrix{Int}(I, 0, 0)\n S = sparse(A)\n iA = try argmax(A); catch; end\n iS = try argmax(S); catch; end\n @test iA === iS === nothing\n iA = try argmin(A); catch; end\n iS = try argmin(S); catch; end\n @test iA === iS === nothing\nend",
"@testset \"findmin/findmax/minimum/maximum\" begin\n A = sparse([1.0 5.0 6.0;\n 5.0 2.0 4.0])\n for (tup, rval, rind) in [((1,), [1.0 2.0 4.0], [CartesianIndex(1,1) CartesianIndex(2,2) CartesianIndex(2,3)]),\n ((2,), reshape([1.0,2.0], 2, 1), reshape([CartesianIndex(1,1),CartesianIndex(2,2)], 2, 1)),\n ((1,2), fill(1.0,1,1),fill(CartesianIndex(1,1),1,1))]\n @test findmin(A, tup) == (rval, rind)\n end\n\n for (tup, rval, rind) in [((1,), [5.0 5.0 6.0], [CartesianIndex(2,1) CartesianIndex(1,2) CartesianIndex(1,3)]),\n ((2,), reshape([6.0,5.0], 2, 1), reshape([CartesianIndex(1,3),CartesianIndex(2,1)], 2, 1)),\n ((1,2), fill(6.0,1,1),fill(CartesianIndex(1,3),1,1))]\n @test findmax(A, tup) == (rval, rind)\n end\n\n #issue 23209\n\n A = sparse([1.0 5.0 6.0;\n NaN 2.0 4.0])\n for (tup, rval, rind) in [((1,), [NaN 2.0 4.0], [CartesianIndex(2,1) CartesianIndex(2,2) CartesianIndex(2,3)]),\n ((2,), reshape([1.0, NaN], 2, 1), reshape([CartesianIndex(1,1),CartesianIndex(2,1)], 2, 1)),\n ((1,2), fill(NaN,1,1),fill(CartesianIndex(2,1),1,1))]\n @test isequal(findmin(A, tup), (rval, rind))\n end\n\n for (tup, rval, rind) in [((1,), [NaN 5.0 6.0], [CartesianIndex(2,1) CartesianIndex(1,2) CartesianIndex(1,3)]),\n ((2,), reshape([6.0, NaN], 2, 1), reshape([CartesianIndex(1,3),CartesianIndex(2,1)], 2, 1)),\n ((1,2), fill(NaN,1,1),fill(CartesianIndex(2,1),1,1))]\n @test isequal(findmax(A, tup), (rval, rind))\n end\n\n A = sparse([1.0 NaN 6.0;\n NaN 2.0 4.0])\n for (tup, rval, rind) in [((1,), [NaN NaN 4.0], [CartesianIndex(2,1) CartesianIndex(1,2) CartesianIndex(2,3)]),\n ((2,), reshape([NaN, NaN], 2, 1), reshape([CartesianIndex(1,2),CartesianIndex(2,1)], 2, 1)),\n ((1,2), fill(NaN,1,1),fill(CartesianIndex(2,1),1,1))]\n @test isequal(findmin(A, tup), (rval, rind))\n end\n\n for (tup, rval, rind) in [((1,), [NaN NaN 6.0], [CartesianIndex(2,1) CartesianIndex(1,2) CartesianIndex(1,3)]),\n ((2,), reshape([NaN, NaN], 2, 1), reshape([CartesianIndex(1,2),CartesianIndex(2,1)], 2, 1)),\n ((1,2), fill(NaN,1,1),fill(CartesianIndex(2,1),1,1))]\n @test isequal(findmax(A, tup), (rval, rind))\n end\n\n A = sparse([Inf -Inf Inf -Inf;\n Inf Inf -Inf -Inf])\n for (tup, rval, rind) in [((1,), [Inf -Inf -Inf -Inf], [CartesianIndex(1,1) CartesianIndex(1,2) CartesianIndex(2,3) CartesianIndex(1,4)]),\n ((2,), reshape([-Inf -Inf], 2, 1), reshape([CartesianIndex(1,2),CartesianIndex(2,3)], 2, 1)),\n ((1,2), fill(-Inf,1,1),fill(CartesianIndex(1,2),1,1))]\n @test isequal(findmin(A, tup), (rval, rind))\n end\n\n for (tup, rval, rind) in [((1,), [Inf Inf Inf -Inf], [CartesianIndex(1,1) CartesianIndex(2,2) CartesianIndex(1,3) CartesianIndex(1,4)]),\n ((2,), reshape([Inf Inf], 2, 1), reshape([CartesianIndex(1,1),CartesianIndex(2,1)], 2, 1)),\n ((1,2), fill(Inf,1,1),fill(CartesianIndex(1,1),1,1))]\n @test isequal(findmax(A, tup), (rval, rind))\n end\n\n A = sparse([BigInt(10)])\n for (tup, rval, rind) in [((2,), [BigInt(10)], [1])]\n @test isequal(findmin(A, dims=tup), (rval, rind))\n end\n\n for (tup, rval, rind) in [((2,), [BigInt(10)], [1])]\n @test isequal(findmax(A, dims=tup), (rval, rind))\n end\n\n A = sparse([BigInt(-10)])\n for (tup, rval, rind) in [((2,), [BigInt(-10)], [1])]\n @test isequal(findmin(A, dims=tup), (rval, rind))\n end\n\n for (tup, rval, rind) in [((2,), [BigInt(-10)], [1])]\n @test isequal(findmax(A, dims=tup), (rval, rind))\n end\n\n A = sparse([BigInt(10) BigInt(-10)])\n for (tup, rval, rind) in [((2,), reshape([BigInt(-10)], 1, 1), reshape([CartesianIndex(1,2)], 1, 1))]\n @test isequal(findmin(A, dims=tup), (rval, rind))\n end\n\n for (tup, rval, rind) in [((2,), reshape([BigInt(10)], 1, 1), reshape([CartesianIndex(1,1)], 1, 1))]\n @test isequal(findmax(A, dims=tup), (rval, rind))\n end\n\n A = sparse([\"a\", \"b\"])\n @test_throws MethodError findmin(A, dims=1)\nend",
"@testset \"findmin/findmax for non-numerical type\" begin\n A = sparse([CustomType(\"a\"), CustomType(\"b\")])\n\n for (tup, rval, rind) in [((1,), [CustomType(\"a\")], [1])]\n @test isequal(findmin(A, dims=tup), (rval, rind))\n end\n\n for (tup, rval, rind) in [((1,), [CustomType(\"b\")], [2])]\n @test isequal(findmax(A, dims=tup), (rval, rind))\n end\nend",
"@testset \"rotations\" begin\n a = sparse( [1,1,2,3], [1,3,4,1], [1,2,3,4] )\n\n @test rot180(a,2) == a\n @test rot180(a,1) == sparse( [3,3,2,1], [4,2,1,4], [1,2,3,4] )\n @test rotr90(a,1) == sparse( [1,3,4,1], [3,3,2,1], [1,2,3,4] )\n @test rotl90(a,1) == sparse( [4,2,1,4], [1,1,2,3], [1,2,3,4] )\n @test rotl90(a,2) == rot180(a)\n @test rotr90(a,2) == rot180(a)\n @test rotl90(a,3) == rotr90(a)\n @test rotr90(a,3) == rotl90(a)\n\n #ensure we have preserved the correct dimensions!\n\n a = sparse(1.0I, 3, 5)\n @test size(rot180(a)) == (3,5)\n @test size(rotr90(a)) == (5,3)\n @test size(rotl90(a)) == (5,3)\nend",
"@testset \"test_getindex_algs\" begin\n M=2^14\n N=2^4\n Irand = randperm(M)\n Jrand = randperm(N)\n SA = [sprand(M, N, d) for d in [1., 0.1, 0.01, 0.001, 0.0001, 0.]]\n IA = [sort(Irand[1:round(Int,n)]) for n in [M, M*0.1, M*0.01, M*0.001, M*0.0001, 0.]]\n debug = false\n\n if debug\n println(\"row sizes: $([round(Int,nnz(S)/S.n) for S in SA])\")\n println(\"I sizes: $([length(I) for I in IA])\")\n @printf(\" S | I | binary S | binary I | linear | best\\n\")\n end\n\n J = Jrand\n for I in IA\n for S in SA\n res = Any[1,2,3]\n times = Float64[0,0,0]\n best = [typemax(Float64), 0]\n for searchtype in [0, 1, 2]\n GC.gc()\n tres = @timed test_getindex_algs(S, I, J, searchtype)\n res[searchtype+1] = tres[1]\n times[searchtype+1] = tres[2]\n if best[1] > tres[2]\n best[1] = tres[2]\n best[2] = searchtype\n end\n end\n\n if debug\n @printf(\" %7d | %7d | %4.2e | %4.2e | %4.2e | %s\\n\", round(Int,nnz(S)/S.n), length(I), times[1], times[2], times[3],\n (0 == best[2]) ? \"binary S\" : (1 == best[2]) ? \"binary I\" : \"linear\")\n end\n if res[1] != res[2]\n println(\"1 and 2\")\n elseif res[2] != res[3]\n println(\"2, 3\")\n end\n @test res[1] == res[2] == res[3]\n end\n end\n\n M = 2^8\n N=2^3\n Irand = randperm(M)\n Jrand = randperm(N)\n II = sort([Irand; Irand; Irand])\n J = [Jrand; Jrand]\n\n SA = [sprand(M, N, d) for d in [1., 0.1, 0.01, 0.001, 0.0001, 0.]]\n for S in SA\n res = Any[1,2,3]\n for searchtype in [0, 1, 2]\n res[searchtype+1] = test_getindex_algs(S, II, J, searchtype)\n end\n\n @test res[1] == res[2] == res[3]\n end\n\n M = 2^14\n N=2^4\n II = randperm(M)\n J = randperm(N)\n Jsorted = sort(J)\n\n SA = [sprand(M, N, d) for d in [1., 0.1, 0.01, 0.001, 0.0001, 0.]]\n IA = [II[1:round(Int,n)] for n in [M, M*0.1, M*0.01, M*0.001, M*0.0001, 0.]]\n debug = false\n if debug\n @printf(\" | | | times | memory |\\n\")\n @printf(\" S | I | J | sorted | unsorted | sorted | unsorted |\\n\")\n end\n for I in IA\n Isorted = sort(I)\n for S in SA\n GC.gc()\n ru = @timed S[I, J]\n GC.gc()\n rs = @timed S[Isorted, Jsorted]\n if debug\n @printf(\" %7d | %7d | %7d | %4.2e | %4.2e | %4.2e | %4.2e |\\n\", round(Int,nnz(S)/S.n), length(I), length(J), rs[2], ru[2], rs[3], ru[3])\n end\n end\n end\nend",
"@testset \"getindex bounds checking\" begin\n S = sprand(10, 10, 0.1)\n @test_throws BoundsError S[[0,1,2], [1,2]]\n @test_throws BoundsError S[[1,2], [0,1,2]]\n @test_throws BoundsError S[[0,2,1], [1,2]]\n @test_throws BoundsError S[[2,1], [0,1,2]]\nend",
"@testset \"test that sparse / sparsevec constructors work for AbstractMatrix subtypes\" begin\n D = Diagonal(fill(1,10))\n sm = sparse(D)\n sv = sparsevec(D)\n\n @test count(!iszero, sm) == 10\n @test count(!iszero, sv) == 10\n\n @test count(!iszero, sparse(Diagonal(Int[]))) == 0\n @test count(!iszero, sparsevec(Diagonal(Int[]))) == 0\nend",
"@testset \"explicit zeros\" begin\n if Base.USE_GPL_LIBS\n a = SparseMatrixCSC(2, 2, [1, 3, 5], [1, 2, 1, 2], [1.0, 0.0, 0.0, 1.0])\n @test lu(a)\\[2.0, 3.0] ≈ [2.0, 3.0]\n @test cholesky(a)\\[2.0, 3.0] ≈ [2.0, 3.0]\n end\nend",
"@testset \"issue #9917\" begin\n @test sparse([]') == reshape(sparse([]), 1, 0)\n @test Array(sparse([])) == zeros(0)\n @test_throws BoundsError sparse([])[1]\n @test_throws BoundsError sparse([])[1] = 1\n x = sparse(1.0I, 100, 100)\n @test_throws BoundsError x[-10:10]\nend",
"@testset \"issue #10407\" begin\n @test maximum(spzeros(5, 5)) == 0.0\n @test minimum(spzeros(5, 5)) == 0.0\nend",
"@testset \"issue #10411\" begin\n for (m,n) in ((2,-2),(-2,2),(-2,-2))\n @test_throws ArgumentError spzeros(m,n)\n @test_throws ArgumentError sparse(1.0I, m, n)\n @test_throws ArgumentError sprand(m,n,0.2)\n end\nend",
"@testset \"issue #10837, sparse constructors from special matrices\" begin\n T = Tridiagonal(randn(4),randn(5),randn(4))\n S = sparse(T)\n @test norm(Array(T) - Array(S)) == 0.0\n T = SymTridiagonal(randn(5),rand(4))\n S = sparse(T)\n @test norm(Array(T) - Array(S)) == 0.0\n B = Bidiagonal(randn(5),randn(4),:U)\n S = sparse(B)\n @test norm(Array(B) - Array(S)) == 0.0\n B = Bidiagonal(randn(5),randn(4),:L)\n S = sparse(B)\n @test norm(Array(B) - Array(S)) == 0.0\n D = Diagonal(randn(5))\n S = sparse(D)\n @test norm(Array(D) - Array(S)) == 0.0\nend",
"@testset \"error conditions for reshape, and dropdims\" begin\n local A = sprand(Bool, 5, 5, 0.2)\n @test_throws DimensionMismatch reshape(A,(20, 2))\n @test_throws ArgumentError dropdims(A,dims=(1, 1))\nend",
"@testset \"float\" begin\n local A\n A = sprand(Bool, 5, 5, 0.0)\n @test eltype(float(A)) == Float64 # issue #11658\n A = sprand(Bool, 5, 5, 0.2)\n @test float(A) == float(Array(A))\nend",
"@testset \"sparsevec\" begin\n local A = sparse(fill(1, 5, 5))\n @test sparsevec(A) == fill(1, 25)\n @test sparsevec([1:5;], 1) == fill(1, 5)\n @test_throws ArgumentError sparsevec([1:5;], [1:4;])\nend",
"@testset \"sparse\" begin\n local A = sparse(fill(1, 5, 5))\n @test sparse(A) == A\n @test sparse([1:5;], [1:5;], 1) == sparse(1.0I, 5, 5)\nend",
"@testset \"one(A::SparseMatrixCSC)\" begin\n @test_throws DimensionMismatch one(sparse([1 1 1; 1 1 1]))\n @test one(sparse([1 1; 1 1]))::SparseMatrixCSC == [1 0; 0 1]\nend",
"@testset \"istriu/istril\" begin\n local A = fill(1, 5, 5)\n @test istriu(sparse(triu(A)))\n @test !istriu(sparse(A))\n @test istril(sparse(tril(A)))\n @test !istril(sparse(A))\nend",
"@testset \"droptol\" begin\n local A = guardseed(1234321) do\n triu(sprand(10, 10, 0.2))\n end\n @test SparseArrays.droptol!(A, 0.01).colptr == [1, 2, 2, 3, 4, 5, 5, 6, 8, 10, 13]\n @test isequal(SparseArrays.droptol!(sparse([1], [1], [1]), 1), SparseMatrixCSC(1, 1, Int[1, 1], Int[], Int[]))\nend",
"@testset \"dropzeros[!]\" begin\n smalldim = 5\n largedim = 10\n nzprob = 0.4\n targetnumposzeros = 5\n targetnumnegzeros = 5\n for (m, n) in ((largedim, largedim), (smalldim, largedim), (largedim, smalldim))\n local A = sprand(m, n, nzprob)\n struczerosA = findall(x -> x == 0, A)\n poszerosinds = unique(rand(struczerosA, targetnumposzeros))\n negzerosinds = unique(rand(struczerosA, targetnumnegzeros))\n Aposzeros = copy(A)\n Aposzeros[poszerosinds] .= 2\n Anegzeros = copy(A)\n Anegzeros[negzerosinds] .= -2\n Abothsigns = copy(Aposzeros)\n Abothsigns[negzerosinds] .= -2\n map!(x -> x == 2 ? 0.0 : x, Aposzeros.nzval, Aposzeros.nzval)\n map!(x -> x == -2 ? -0.0 : x, Anegzeros.nzval, Anegzeros.nzval)\n map!(x -> x == 2 ? 0.0 : x == -2 ? -0.0 : x, Abothsigns.nzval, Abothsigns.nzval)\n for Awithzeros in (Aposzeros, Anegzeros, Abothsigns)\n # Basic functionality / dropzeros!\n @test dropzeros!(copy(Awithzeros)) == A\n @test dropzeros!(copy(Awithzeros), trim = false) == A\n # Basic functionality / dropzeros\n @test dropzeros(Awithzeros) == A\n @test dropzeros(Awithzeros, trim = false) == A\n # Check trimming works as expected\n @test length(dropzeros!(copy(Awithzeros)).nzval) == length(A.nzval)\n @test length(dropzeros!(copy(Awithzeros)).rowval) == length(A.rowval)\n @test length(dropzeros!(copy(Awithzeros), trim = false).nzval) == length(Awithzeros.nzval)\n @test length(dropzeros!(copy(Awithzeros), trim = false).rowval) == length(Awithzeros.rowval)\n end\n end\n # original lone dropzeros test\n local A = sparse([1 2 3; 4 5 6; 7 8 9])\n A.nzval[2] = A.nzval[6] = A.nzval[7] = 0\n @test dropzeros!(A).colptr == [1, 3, 5, 7]\n # test for issue #5169, modified for new behavior following #15242/#14798\n @test nnz(sparse([1, 1], [1, 2], [0.0, -0.0])) == 2\n @test nnz(dropzeros!(sparse([1, 1], [1, 2], [0.0, -0.0]))) == 0\n # test for issue #5437, modified for new behavior following #15242/#14798\n @test nnz(sparse([1, 2, 3], [1, 2, 3], [0.0, 1.0, 2.0])) == 3\n @test nnz(dropzeros!(sparse([1, 2, 3],[1, 2, 3],[0.0, 1.0, 2.0]))) == 2\nend",
"@testset \"trace\" begin\n @test_throws DimensionMismatch tr(spzeros(5,6))\n @test tr(sparse(1.0I, 5, 5)) == 5\nend",
"@testset \"spdiagm\" begin\n x = fill(1, 2)\n @test spdiagm(0 => x, -1 => x) == [1 0 0; 1 1 0; 0 1 0]\n @test spdiagm(0 => x, 1 => x) == [1 1 0; 0 1 1; 0 0 0]\n\n for (x, y) in ((rand(5), rand(4)),(sparse(rand(5)), sparse(rand(4))))\n @test spdiagm(-1 => x)::SparseMatrixCSC == diagm(-1 => x)\n @test spdiagm( 0 => x)::SparseMatrixCSC == diagm( 0 => x) == sparse(Diagonal(x))\n @test spdiagm(-1 => x)::SparseMatrixCSC == diagm(-1 => x)\n @test spdiagm(0 => x, -1 => y)::SparseMatrixCSC == diagm(0 => x, -1 => y)\n @test spdiagm(0 => x, 1 => y)::SparseMatrixCSC == diagm(0 => x, 1 => y)\n end\n # promotion\n @test spdiagm(0 => [1,2], 1 => [3.5], -1 => [4+5im]) == [1 3.5; 4+5im 2]\nend",
"@testset \"diag\" begin\n for T in (Float64, ComplexF64)\n S1 = sprand(T, 5, 5, 0.5)\n S2 = sprand(T, 10, 5, 0.5)\n S3 = sprand(T, 5, 10, 0.5)\n for S in (S1, S2, S3)\n local A = Matrix(S)\n @test diag(S)::SparseVector{T,Int} == diag(A)\n for k in -size(S,1):size(S,2)\n @test diag(S, k)::SparseVector{T,Int} == diag(A, k)\n end\n @test_throws ArgumentError diag(S, -size(S,1)-1)\n @test_throws ArgumentError diag(S, size(S,2)+1)\n end\n end\n # test that stored zeros are still stored zeros in the diagonal\n S = sparse([1,3],[1,3],[0.0,0.0]); V = diag(S)\n @test V.nzind == [1,3]\n @test V.nzval == [0.0,0.0]\nend",
"@testset \"expandptr\" begin\n local A = sparse(1.0I, 5, 5)\n @test SparseArrays.expandptr(A.colptr) == 1:5\n A[1,2] = 1\n @test SparseArrays.expandptr(A.colptr) == [1; 2; 2; 3; 4; 5]\n @test_throws ArgumentError SparseArrays.expandptr([2; 3])\nend",
"@testset \"triu/tril\" begin\n n = 5\n local A = sprand(n, n, 0.2)\n AF = Array(A)\n @test Array(triu(A,1)) == triu(AF,1)\n @test Array(tril(A,1)) == tril(AF,1)\n @test Array(triu!(copy(A), 2)) == triu(AF,2)\n @test Array(tril!(copy(A), 2)) == tril(AF,2)\n @test tril(A, -n - 2) == zero(A)\n @test tril(A, n) == A\n @test triu(A, -n) == A\n @test triu(A, n + 2) == zero(A)\n\n # fkeep trim option\n @test isequal(length(tril!(sparse([1,2,3], [1,2,3], [1,2,3], 3, 4), -1).rowval), 0)\nend",
"@testset \"norm\" begin\n local A\n A = sparse(Int[],Int[],Float64[],0,0)\n @test norm(A) == zero(eltype(A))\n A = sparse([1.0])\n @test norm(A) == 1.0\n @test_throws ArgumentError opnorm(sprand(5,5,0.2),3)\n @test_throws ArgumentError opnorm(sprand(5,5,0.2),2)\nend",
"@testset \"ishermitian/issymmetric\" begin\n local A\n # real matrices\n A = sparse(1.0I, 5, 5)\n @test ishermitian(A) == true\n @test issymmetric(A) == true\n A[1,3] = 1.0\n @test ishermitian(A) == false\n @test issymmetric(A) == false\n A[3,1] = 1.0\n @test ishermitian(A) == true\n @test issymmetric(A) == true\n\n # complex matrices\n A = sparse((1.0 + 1.0im)I, 5, 5)\n @test ishermitian(A) == false\n @test issymmetric(A) == true\n A[1,4] = 1.0 + im\n @test ishermitian(A) == false\n @test issymmetric(A) == false\n\n A = sparse(ComplexF64(1)I, 5, 5)\n A[3,2] = 1.0 + im\n @test ishermitian(A) == false\n @test issymmetric(A) == false\n A[2,3] = 1.0 - im\n @test ishermitian(A) == true\n @test issymmetric(A) == false\n\n A = sparse(zeros(5,5))\n @test ishermitian(A) == true\n @test issymmetric(A) == true\n\n # explicit zeros\n A = sparse(ComplexF64(1)I, 5, 5)\n A[3,1] = 2\n A.nzval[2] = 0.0\n @test ishermitian(A) == true\n @test issymmetric(A) == true\n\n # 15504\n m = n = 5\n colptr = [1, 5, 9, 13, 13, 17]\n rowval = [1, 2, 3, 5, 1, 2, 3, 5, 1, 2, 3, 5, 1, 2, 3, 5]\n nzval = [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0]\n A = SparseMatrixCSC(m, n, colptr, rowval, nzval)\n @test issymmetric(A) == true\n A.nzval[end - 3] = 2.0\n @test issymmetric(A) == false\n\n # 16521\n @test issymmetric(sparse([0 0; 1 0])) == false\n @test issymmetric(sparse([0 1; 0 0])) == false\n @test issymmetric(sparse([0 0; 1 1])) == false\n @test issymmetric(sparse([1 0; 1 0])) == false\n @test issymmetric(sparse([0 1; 1 0])) == true\n @test issymmetric(sparse([1 1; 1 0])) == true\nend",
"@testset \"equality ==\" begin\n A1 = sparse(1.0I, 10, 10)\n A2 = sparse(1.0I, 10, 10)\n nonzeros(A1)[end]=0\n @test A1!=A2\n nonzeros(A1)[end]=1\n @test A1==A2\n A1[1:4,end] .= 1\n @test A1!=A2\n nonzeros(A1)[end-4:end-1].=0\n @test A1==A2\n A2[1:4,end-1] .= 1\n @test A1!=A2\n nonzeros(A2)[end-5:end-2].=0\n @test A1==A2\n A2[2:3,1] .= 1\n @test A1!=A2\n nonzeros(A2)[2:3].=0\n @test A1==A2\n A1[2:5,1] .= 1\n @test A1!=A2\n nonzeros(A1)[2:5].=0\n @test A1==A2\n @test sparse([1,1,0])!=sparse([0,1,1])\nend",
"@testset \"UniformScaling\" begin\n local A = sprandn(10, 10, 0.5)\n @test A + I == Array(A) + I\n @test I + A == I + Array(A)\n @test A - I == Array(A) - I\n @test I - A == I - Array(A)\nend",
"@testset \"issue #12177, error path if triplet vectors are not all the same length\" begin\n @test_throws ArgumentError sparse([1,2,3], [1,2], [1,2,3], 3, 3)\n @test_throws ArgumentError sparse([1,2,3], [1,2,3], [1,2], 3, 3)\nend",
"@testset \"issue #12118: sparse matrices are closed under +, -, min, max\" begin\n A12118 = sparse([1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5])\n B12118 = sparse([1,2,4,5], [1,2,3,5], [2,1,-1,-2])\n\n @test A12118 + B12118 == sparse([1,2,3,4,4,5], [1,2,3,3,4,5], [3,3,3,-1,4,3])\n @test typeof(A12118 + B12118) == SparseMatrixCSC{Int,Int}\n\n @test A12118 - B12118 == sparse([1,2,3,4,4,5], [1,2,3,3,4,5], [-1,1,3,1,4,7])\n @test typeof(A12118 - B12118) == SparseMatrixCSC{Int,Int}\n\n @test max.(A12118, B12118) == sparse([1,2,3,4,5], [1,2,3,4,5], [2,2,3,4,5])\n @test typeof(max.(A12118, B12118)) == SparseMatrixCSC{Int,Int}\n\n @test min.(A12118, B12118) == sparse([1,2,4,5], [1,2,3,5], [1,1,-1,-2])\n @test typeof(min.(A12118, B12118)) == SparseMatrixCSC{Int,Int}\nend",
"@testset \"sparse matrix norms\" begin\n Ac = sprandn(10,10,.1) + im* sprandn(10,10,.1)\n Ar = sprandn(10,10,.1)\n Ai = ceil.(Int,Ar*100)\n @test opnorm(Ac,1) ≈ opnorm(Array(Ac),1)\n @test opnorm(Ac,Inf) ≈ opnorm(Array(Ac),Inf)\n @test norm(Ac) ≈ norm(Array(Ac))\n @test opnorm(Ar,1) ≈ opnorm(Array(Ar),1)\n @test opnorm(Ar,Inf) ≈ opnorm(Array(Ar),Inf)\n @test norm(Ar) ≈ norm(Array(Ar))\n @test opnorm(Ai,1) ≈ opnorm(Array(Ai),1)\n @test opnorm(Ai,Inf) ≈ opnorm(Array(Ai),Inf)\n @test norm(Ai) ≈ norm(Array(Ai))\n Ai = trunc.(Int, Ar*100)\n @test opnorm(Ai,1) ≈ opnorm(Array(Ai),1)\n @test opnorm(Ai,Inf) ≈ opnorm(Array(Ai),Inf)\n @test norm(Ai) ≈ norm(Array(Ai))\n Ai = round.(Int, Ar*100)\n @test opnorm(Ai,1) ≈ opnorm(Array(Ai),1)\n @test opnorm(Ai,Inf) ≈ opnorm(Array(Ai),Inf)\n @test norm(Ai) ≈ norm(Array(Ai))\n # make certain entries in nzval beyond\n # the range specified in colptr do not\n # impact norm of a sparse matrix\n foo = sparse(1.0I, 4, 4)\n resize!(foo.nzval, 5)\n setindex!(foo.nzval, NaN, 5)\n @test norm(foo) == 2.0\nend",
"@testset \"sparse matrix cond\" begin\n local A = sparse(reshape([1.0], 1, 1))\n Ac = sprandn(20, 20,.5) + im*sprandn(20, 20,.5)\n Ar = sprandn(20, 20,.5) + eps()*I\n @test cond(A, 1) == 1.0\n # For a discussion of the tolerance, see #14778\n if Base.USE_GPL_LIBS\n @test 0.99 <= cond(Ar, 1) \\ opnorm(Ar, 1) * opnorm(inv(Array(Ar)), 1) < 3\n @test 0.99 <= cond(Ac, 1) \\ opnorm(Ac, 1) * opnorm(inv(Array(Ac)), 1) < 3\n @test 0.99 <= cond(Ar, Inf) \\ opnorm(Ar, Inf) * opnorm(inv(Array(Ar)), Inf) < 3\n @test 0.99 <= cond(Ac, Inf) \\ opnorm(Ac, Inf) * opnorm(inv(Array(Ac)), Inf) < 3\n end\n @test_throws ArgumentError cond(A,2)\n @test_throws ArgumentError cond(A,3)\n Arect = spzeros(10, 6)\n @test_throws DimensionMismatch cond(Arect, 1)\n @test_throws ArgumentError cond(Arect,2)\n @test_throws DimensionMismatch cond(Arect, Inf)\nend",
"@testset \"sparse matrix opnormestinv\" begin\n Random.seed!(1234)\n Ac = sprandn(20,20,.5) + im* sprandn(20,20,.5)\n Aci = ceil.(Int64, 100*sprand(20,20,.5)) + im*ceil.(Int64, sprand(20,20,.5))\n Ar = sprandn(20,20,.5)\n Ari = ceil.(Int64, 100*Ar)\n if Base.USE_GPL_LIBS\n # NOTE: opnormestinv is probabilistic, so requires a fixed seed (set above in Random.seed!(1234))\n @test SparseArrays.opnormestinv(Ac,3) ≈ opnorm(inv(Array(Ac)),1) atol=1e-4\n @test SparseArrays.opnormestinv(Aci,3) ≈ opnorm(inv(Array(Aci)),1) atol=1e-4\n @test SparseArrays.opnormestinv(Ar) ≈ opnorm(inv(Array(Ar)),1) atol=1e-4\n @test_throws ArgumentError SparseArrays.opnormestinv(Ac,0)\n @test_throws ArgumentError SparseArrays.opnormestinv(Ac,21)\n end\n @test_throws DimensionMismatch SparseArrays.opnormestinv(sprand(3,5,.9))\nend",
"@testset \"issue #13008\" begin\n @test_throws ArgumentError sparse(Vector(1:100), Vector(1:100), fill(5,100), 5, 5)\n @test_throws ArgumentError sparse(Int[], Vector(1:5), Vector(1:5))\nend",
"@testset \"issue #13024\" begin\n A13024 = sparse([1,2,3,4,5], [1,2,3,4,5], fill(true,5))\n B13024 = sparse([1,2,4,5], [1,2,3,5], fill(true,4))\n\n @test broadcast(&, A13024, B13024) == sparse([1,2,5], [1,2,5], fill(true,3))\n @test typeof(broadcast(&, A13024, B13024)) == SparseMatrixCSC{Bool,Int}\n\n @test broadcast(|, A13024, B13024) == sparse([1,2,3,4,4,5], [1,2,3,3,4,5], fill(true,6))\n @test typeof(broadcast(|, A13024, B13024)) == SparseMatrixCSC{Bool,Int}\n\n @test broadcast(⊻, A13024, B13024) == sparse([3,4,4], [3,3,4], fill(true,3), 5, 5)\n @test typeof(broadcast(⊻, A13024, B13024)) == SparseMatrixCSC{Bool,Int}\n\n @test broadcast(max, A13024, B13024) == sparse([1,2,3,4,4,5], [1,2,3,3,4,5], fill(true,6))\n @test typeof(broadcast(max, A13024, B13024)) == SparseMatrixCSC{Bool,Int}\n\n @test broadcast(min, A13024, B13024) == sparse([1,2,5], [1,2,5], fill(true,3))\n @test typeof(broadcast(min, A13024, B13024)) == SparseMatrixCSC{Bool,Int}\n\n for op in (+, -)\n @test op(A13024, B13024) == op(Array(A13024), Array(B13024))\n end\n for op in (max, min, &, |, xor)\n @test op.(A13024, B13024) == op.(Array(A13024), Array(B13024))\n end\nend",
"@testset \"fillstored!\" begin\n @test LinearAlgebra.fillstored!(sparse(2.0I, 5, 5), 1) == Matrix(I, 5, 5)\nend",
"@testset \"factorization\" begin\n Random.seed!(123)\n local A\n A = sparse(Diagonal(rand(5))) + sprandn(5, 5, 0.2) + im*sprandn(5, 5, 0.2)\n A = A + copy(A')\n @test !Base.USE_GPL_LIBS || abs(det(factorize(Hermitian(A)))) ≈ abs(det(factorize(Array(A))))\n A = sparse(Diagonal(rand(5))) + sprandn(5, 5, 0.2) + im*sprandn(5, 5, 0.2)\n A = A*A'\n @test !Base.USE_GPL_LIBS || abs(det(factorize(Hermitian(A)))) ≈ abs(det(factorize(Array(A))))\n A = sparse(Diagonal(rand(5))) + sprandn(5, 5, 0.2)\n A = A + copy(transpose(A))\n @test !Base.USE_GPL_LIBS || abs(det(factorize(Symmetric(A)))) ≈ abs(det(factorize(Array(A))))\n A = sparse(Diagonal(rand(5))) + sprandn(5, 5, 0.2)\n A = A*transpose(A)\n @test !Base.USE_GPL_LIBS || abs(det(factorize(Symmetric(A)))) ≈ abs(det(factorize(Array(A))))\n @test factorize(triu(A)) == triu(A)\n @test isa(factorize(triu(A)), UpperTriangular{Float64, SparseMatrixCSC{Float64, Int}})\n @test factorize(tril(A)) == tril(A)\n @test isa(factorize(tril(A)), LowerTriangular{Float64, SparseMatrixCSC{Float64, Int}})\n C, b = A[:, 1:4], fill(1., size(A, 1))\n @test !Base.USE_GPL_LIBS || factorize(C)\\b ≈ Array(C)\\b\n @test_throws ErrorException eigen(A)\n @test_throws ErrorException inv(A)\nend",
"@testset \"issue #13792, use sparse triangular solvers for sparse triangular solves\" begin\n local A, n, x\n n = 100\n A, b = sprandn(n, n, 0.5) + sqrt(n)*I, fill(1., n)\n @test LowerTriangular(A)\\(LowerTriangular(A)*b) ≈ b\n @test UpperTriangular(A)\\(UpperTriangular(A)*b) ≈ b\n A[2,2] = 0\n dropzeros!(A)\n @test_throws LinearAlgebra.SingularException LowerTriangular(A)\\b\n @test_throws LinearAlgebra.SingularException UpperTriangular(A)\\b\nend",
"@testset \"issue described in https://groups.google.com/forum/#!topic/julia-dev/QT7qpIpgOaA\" begin\n @test sparse([1,1], [1,1], [true, true]) == sparse([1,1], [1,1], [true, true], 1, 1) == fill(true, 1, 1)\n @test sparsevec([1,1], [true, true]) == sparsevec([1,1], [true, true], 1) == fill(true, 1)\nend",
"@testset \"issparse for specialized matrix types\" begin\n m = sprand(10, 10, 0.1)\n @test issparse(Symmetric(m))\n @test issparse(Hermitian(m))\n @test issparse(LowerTriangular(m))\n @test issparse(LinearAlgebra.UnitLowerTriangular(m))\n @test issparse(UpperTriangular(m))\n @test issparse(LinearAlgebra.UnitUpperTriangular(m))\n @test issparse(Symmetric(Array(m))) == false\n @test issparse(Hermitian(Array(m))) == false\n @test issparse(LowerTriangular(Array(m))) == false\n @test issparse(LinearAlgebra.UnitLowerTriangular(Array(m))) == false\n @test issparse(UpperTriangular(Array(m))) == false\n @test issparse(LinearAlgebra.UnitUpperTriangular(Array(m))) == false\nend",
"@testset \"test created type of sprand{T}(::Type{T}, m::Integer, n::Integer, density::AbstractFloat)\" begin\n m = sprand(Float32, 10, 10, 0.1)\n @test eltype(m) == Float32\n m = sprand(Float64, 10, 10, 0.1)\n @test eltype(m) == Float64\n m = sprand(Int32, 10, 10, 0.1)\n @test eltype(m) == Int32\nend",
"@testset \"issue #16073\" begin\n @inferred sprand(1, 1, 1.0)\n @inferred sprand(1, 1, 1.0, rand, Float64)\n @inferred sprand(1, 1, 1.0, x -> round.(Int, rand(x) * 100))\nend",
"@testset \"sparse and dense concatenations\" begin\n N = 4\n densevec = fill(1., N)\n densemat = diagm(0 => densevec)\n spmat = spdiagm(0 => densevec)\n # Test that concatenations of pairs of sparse matrices yield sparse arrays\n @test issparse(vcat(spmat, spmat))\n @test issparse(hcat(spmat, spmat))\n @test issparse(hvcat((2,), spmat, spmat))\n @test issparse(cat(spmat, spmat; dims=(1,2)))\n # Test that concatenations of a sparse matrice with a dense matrix/vector yield sparse arrays\n @test issparse(vcat(spmat, densemat))\n @test issparse(vcat(densemat, spmat))\n for densearg in (densevec, densemat)\n @test issparse(hcat(spmat, densearg))\n @test issparse(hcat(densearg, spmat))\n @test issparse(hvcat((2,), spmat, densearg))\n @test issparse(hvcat((2,), densearg, spmat))\n @test issparse(cat(spmat, densearg; dims=(1,2)))\n @test issparse(cat(densearg, spmat; dims=(1,2)))\n end\nend",
"@testset \"issue #14816\" begin\n m = 5\n intmat = fill(1, m, m)\n ltintmat = LowerTriangular(rand(1:5, m, m))\n @test \\(transpose(ltintmat), sparse(intmat)) ≈ \\(transpose(ltintmat), intmat)\nend",
"@testset \"issue #16548\" begin\n ms = methods(\\, (SparseMatrixCSC, AbstractVecOrMat)).ms\n @test all(m -> m.module == SparseArrays, ms)\nend",
"@testset \"row indexing a SparseMatrixCSC with non-Int integer type\" begin\n local A = sparse(UInt32[1,2,3], UInt32[1,2,3], [1.0,2.0,3.0])\n @test A[1,1:3] == A[1,:] == [1,0,0]\nend",
"@testset \"issue #18705\" begin\n S = sparse(Diagonal(1.0:5.0))\n @test isa(sin.(S), SparseMatrixCSC)\nend",
"@testset \"issue #19225\" begin\n X = sparse([1 -1; -1 1])\n for T in (Symmetric, Hermitian)\n Y = T(copy(X))\n _Y = similar(Y)\n copyto!(_Y, Y)\n @test _Y == Y\n\n W = T(copy(X), :L)\n copyto!(W, Y)\n @test W.data == Y.data\n @test W.uplo != Y.uplo\n\n W[1,1] = 4\n @test W == T(sparse([4 -1; -1 1]))\n @test_throws ArgumentError (W[1,2] = 2)\n\n @test Y + I == T(sparse([2 -1; -1 2]))\n @test Y - I == T(sparse([0 -1; -1 0]))\n @test Y * I == Y\n\n @test Y .+ 1 == T(sparse([2 0; 0 2]))\n @test Y .- 1 == T(sparse([0 -2; -2 0]))\n @test Y * 2 == T(sparse([2 -2; -2 2]))\n @test Y / 1 == Y\n end\nend",
"@testset \"issue #19304\" begin\n @inferred hcat(sparse(rand(2,1)), I)\n @inferred hcat(sparse(rand(2,1)), 1.0I)\n @inferred hcat(sparse(rand(2,1)), Matrix(I, 2, 2))\n @inferred hcat(sparse(rand(2,1)), Matrix(1.0I, 2, 2))\nend",
"@testset \"issue #18974\" begin\n S = sparse(Diagonal(Int64(1):Int64(4)))\n @test eltype(sin.(S)) == Float64\nend",
"@testset \"issue #19503\" begin\n @test which(-, (SparseMatrixCSC,)).module == SparseArrays\nend",
"@testset \"issue #14398\" begin\n @test collect(view(sparse(I, 10, 10), 1:5, 1:5)') ≈ Matrix(I, 5, 5)\nend",
"@testset \"dropstored issue #20513\" begin\n x = sparse(rand(3,3))\n SparseArrays.dropstored!(x, 1, 1)\n @test x[1, 1] == 0.0\n @test x.colptr == [1, 3, 6, 9]\n SparseArrays.dropstored!(x, 2, 1)\n @test x.colptr == [1, 2, 5, 8]\n @test x[2, 1] == 0.0\n SparseArrays.dropstored!(x, 2, 2)\n @test x.colptr == [1, 2, 4, 7]\n @test x[2, 2] == 0.0\n SparseArrays.dropstored!(x, 2, 3)\n @test x.colptr == [1, 2, 4, 6]\n @test x[2, 3] == 0.0\nend",
"@testset \"setindex issue #20657\" begin\n local A = spzeros(3, 3)\n I = [1, 1, 1]; J = [1, 1, 1]\n A[I, 1] .= 1\n @test nnz(A) == 1\n A[1, J] .= 1\n @test nnz(A) == 1\n A[I, J] .= 1\n @test nnz(A) == 1\nend",
"@testset \"setindex with vector eltype (#29034)\" begin\n A = sparse([1], [1], [Vector{Float64}(undef, 3)], 3, 3)\n A[1,1] = [1.0, 2.0, 3.0]\n @test A[1,1] == [1.0, 2.0, 3.0]\nend",
"@testset \"show\" begin\n io = IOBuffer()\n show(io, MIME\"text/plain\"(), sparse(Int64[1], Int64[1], [1.0]))\n @test String(take!(io)) == \"1×1 SparseArrays.SparseMatrixCSC{Float64,Int64} with 1 stored entry:\\n [1, 1] = 1.0\"\n show(io, MIME\"text/plain\"(), spzeros(Float32, Int64, 2, 2))\n @test String(take!(io)) == \"2×2 SparseArrays.SparseMatrixCSC{Float32,Int64} with 0 stored entries\"\n\n ioc = IOContext(io, :displaysize => (5, 80), :limit => true)\n show(ioc, MIME\"text/plain\"(), sparse(Int64[1], Int64[1], [1.0]))\n @test String(take!(io)) == \"1×1 SparseArrays.SparseMatrixCSC{Float64,Int64} with 1 stored entry:\\n [1, 1] = 1.0\"\n show(ioc, MIME\"text/plain\"(), sparse(Int64[1, 1], Int64[1, 2], [1.0, 2.0]))\n @test String(take!(io)) == \"1×2 SparseArrays.SparseMatrixCSC{Float64,Int64} with 2 stored entries:\\n ⋮\"\n\n # even number of rows\n ioc = IOContext(io, :displaysize => (8, 80), :limit => true)\n show(ioc, MIME\"text/plain\"(), sparse(Int64[1,2,3,4], Int64[1,1,2,2], [1.0,2.0,3.0,4.0]))\n @test String(take!(io)) == string(\"4×2 SparseArrays.SparseMatrixCSC{Float64,Int64} with 4 stored entries:\\n [1, 1]\",\n \" = 1.0\\n [2, 1] = 2.0\\n [3, 2] = 3.0\\n [4, 2] = 4.0\")\n\n show(ioc, MIME\"text/plain\"(), sparse(Int64[1,2,3,4,5], Int64[1,1,2,2,3], [1.0,2.0,3.0,4.0,5.0]))\n @test String(take!(io)) == string(\"5×3 SparseArrays.SparseMatrixCSC{Float64,Int64} with 5 stored entries:\\n [1, 1]\",\n \" = 1.0\\n ⋮\\n [4, 2] = 4.0\\n [5, 3] = 5.0\")\n\n show(ioc, MIME\"text/plain\"(), sparse(fill(1.,5,3)))\n @test String(take!(io)) == string(\"5×3 SparseArrays.SparseMatrixCSC{Float64,$Int} with 15 stored entries:\\n [1, 1]\",\n \" = 1.0\\n ⋮\\n [4, 3] = 1.0\\n [5, 3] = 1.0\")\n\n # odd number of rows\n ioc = IOContext(io, :displaysize => (9, 80), :limit => true)\n show(ioc, MIME\"text/plain\"(), sparse(Int64[1,2,3,4,5], Int64[1,1,2,2,3], [1.0,2.0,3.0,4.0,5.0]))\n @test String(take!(io)) == string(\"5×3 SparseArrays.SparseMatrixCSC{Float64,Int64} with 5 stored entries:\\n [1, 1]\",\n \" = 1.0\\n [2, 1] = 2.0\\n [3, 2] = 3.0\\n [4, 2] = 4.0\\n [5, 3] = 5.0\")\n\n show(ioc, MIME\"text/plain\"(), sparse(Int64[1,2,3,4,5,6], Int64[1,1,2,2,3,3], [1.0,2.0,3.0,4.0,5.0,6.0]))\n @test String(take!(io)) == string(\"6×3 SparseArrays.SparseMatrixCSC{Float64,Int64} with 6 stored entries:\\n [1, 1]\",\n \" = 1.0\\n [2, 1] = 2.0\\n ⋮\\n [5, 3] = 5.0\\n [6, 3] = 6.0\")\n\n show(ioc, MIME\"text/plain\"(), sparse(fill(1.,6,3)))\n @test String(take!(io)) == string(\"6×3 SparseArrays.SparseMatrixCSC{Float64,$Int} with 18 stored entries:\\n [1, 1]\",\n \" = 1.0\\n [2, 1] = 1.0\\n ⋮\\n [5, 3] = 1.0\\n [6, 3] = 1.0\")\n\n ioc = IOContext(io, :displaysize => (9, 80))\n show(ioc, MIME\"text/plain\"(), sparse(Int64[1,2,3,4,5,6], Int64[1,1,2,2,3,3], [1.0,2.0,3.0,4.0,5.0,6.0]))\n @test String(take!(io)) == string(\"6×3 SparseArrays.SparseMatrixCSC{Float64,Int64} with 6 stored entries:\\n [1, 1] = 1.0\\n\",\n \" [2, 1] = 2.0\\n [3, 2] = 3.0\\n [4, 2] = 4.0\\n [5, 3] = 5.0\\n [6, 3] = 6.0\")\n\n # issue #30589\n @test repr(\"text/plain\", sparse([true true])) == \"1×2 SparseArrays.SparseMatrixCSC{Bool,$Int} with 2 stored entries:\\n [1, 1] = 1\\n [1, 2] = 1\"\nend",
"@testset \"check buffers\" for n in 1:3\n local A\n rowval = [1,2,3]\n nzval1 = Int[]\n nzval2 = [1,1,1]\n A = SparseMatrixCSC(n, n, [1:n+1;], rowval, nzval1)\n @test nnz(A) == n\n @test_throws BoundsError A[n,n]\n A = SparseMatrixCSC(n, n, [1:n+1;], rowval, nzval2)\n @test nnz(A) == n\n @test A == Matrix(I, n, n)\nend",
"@testset \"reverse search direction if step < 0 #21986\" begin\n local A, B\n A = guardseed(1234) do\n sprand(5, 5, 1/5)\n end\n A = max.(A, copy(A'))\n LinearAlgebra.fillstored!(A, 1)\n B = A[5:-1:1, 5:-1:1]\n @test issymmetric(B)\nend",
"@testset \"similar should not alias the input sparse array\" begin\n a = sparse(rand(3,3) .+ 0.1)\n b = similar(a, Float32, Int32)\n c = similar(b, Float32, Int32)\n SparseArrays.dropstored!(b, 1, 1)\n @test length(c.rowval) == 9\n @test length(c.nzval) == 9\nend",
"@testset \"similar with type conversion\" begin\n local A = sparse(1.0I, 5, 5)\n @test size(similar(A, ComplexF64, Int)) == (5, 5)\n @test typeof(similar(A, ComplexF64, Int)) == SparseMatrixCSC{ComplexF64, Int}\n @test size(similar(A, ComplexF64, Int8)) == (5, 5)\n @test typeof(similar(A, ComplexF64, Int8)) == SparseMatrixCSC{ComplexF64, Int8}\n @test similar(A, ComplexF64,(6, 6)) == spzeros(ComplexF64, 6, 6)\n @test convert(Matrix, A) == Array(A) # lolwut, are you lost, test?\nend",
"@testset \"similar for SparseMatrixCSC\" begin\n local A = sparse(1.0I, 5, 5)\n # test similar without specifications (preserves stored-entry structure)\n simA = similar(A)\n @test typeof(simA) == typeof(A)\n @test size(simA) == size(A)\n @test simA.colptr == A.colptr\n @test simA.rowval == A.rowval\n @test length(simA.nzval) == length(A.nzval)\n # test similar with entry type specification (preserves stored-entry structure)\n simA = similar(A, Float32)\n @test typeof(simA) == SparseMatrixCSC{Float32,eltype(A.colptr)}\n @test size(simA) == size(A)\n @test simA.colptr == A.colptr\n @test simA.rowval == A.rowval\n @test length(simA.nzval) == length(A.nzval)\n # test similar with entry and index type specification (preserves stored-entry structure)\n simA = similar(A, Float32, Int8)\n @test typeof(simA) == SparseMatrixCSC{Float32,Int8}\n @test size(simA) == size(A)\n @test simA.colptr == A.colptr\n @test simA.rowval == A.rowval\n @test length(simA.nzval) == length(A.nzval)\n # test similar with Dims{2} specification (preserves storage space only, not stored-entry structure)\n simA = similar(A, (6,6))\n @test typeof(simA) == typeof(A)\n @test size(simA) == (6,6)\n @test simA.colptr == fill(1, 6+1)\n @test length(simA.rowval) == length(A.rowval)\n @test length(simA.nzval) == length(A.nzval)\n # test similar with entry type and Dims{2} specification (preserves storage space only)\n simA = similar(A, Float32, (6,6))\n @test typeof(simA) == SparseMatrixCSC{Float32,eltype(A.colptr)}\n @test size(simA) == (6,6)\n @test simA.colptr == fill(1, 6+1)\n @test length(simA.rowval) == length(A.rowval)\n @test length(simA.nzval) == length(A.nzval)\n # test similar with entry type, index type, and Dims{2} specification (preserves storage space only)\n simA = similar(A, Float32, Int8, (6,6))\n @test typeof(simA) == SparseMatrixCSC{Float32, Int8}\n @test size(simA) == (6,6)\n @test simA.colptr == fill(1, 6+1)\n @test length(simA.rowval) == length(A.rowval)\n @test length(simA.nzval) == length(A.nzval)\n # test similar with Dims{1} specification (preserves nothing)\n simA = similar(A, (6,))\n @test typeof(simA) == SparseVector{eltype(A.nzval),eltype(A.colptr)}\n @test size(simA) == (6,)\n @test length(simA.nzind) == 0\n @test length(simA.nzval) == 0\n # test similar with entry type and Dims{1} specification (preserves nothing)\n simA = similar(A, Float32, (6,))\n @test typeof(simA) == SparseVector{Float32,eltype(A.colptr)}\n @test size(simA) == (6,)\n @test length(simA.nzind) == 0\n @test length(simA.nzval) == 0\n # test similar with entry type, index type, and Dims{1} specification (preserves nothing)\n simA = similar(A, Float32, Int8, (6,))\n @test typeof(simA) == SparseVector{Float32,Int8}\n @test size(simA) == (6,)\n @test length(simA.nzind) == 0\n @test length(simA.nzval) == 0\n # test entry points to similar with entry type, index type, and non-Dims shape specification\n @test similar(A, Float32, Int8, 6, 6) == similar(A, Float32, Int8, (6, 6))\n @test similar(A, Float32, Int8, 6) == similar(A, Float32, Int8, (6,))\nend",
"@testset \"count specializations\" begin\n # count should throw for sparse arrays for which zero(eltype) does not exist\n @test_throws MethodError count(SparseMatrixCSC(2, 2, Int[1, 2, 3], Int[1, 2], Any[true, true]))\n @test_throws MethodError count(SparseVector(2, Int[1], Any[true]))\n # count should run only over S.nzval[1:nnz(S)], not S.nzval in full\n @test count(SparseMatrixCSC(2, 2, Int[1, 2, 3], Int[1, 2], Bool[true, true, true])) == 2\nend",
"@testset \"sparse findprev/findnext operations\" begin\n\n x = [0,0,0,0,1,0,1,0,1,1,0]\n x_sp = sparse(x)\n\n for i=1:length(x)\n @test findnext(!iszero, x,i) == findnext(!iszero, x_sp,i)\n @test findprev(!iszero, x,i) == findprev(!iszero, x_sp,i)\n end\n\n y = [7 0 0 0 0;\n 1 0 1 0 0;\n 1 7 0 7 1;\n 0 0 1 0 0;\n 1 0 1 1 0.0]\n y_sp = [x == 7 ? -0.0 : x for x in sparse(y)]\n y = Array(y_sp)\n @test isequal(y_sp[1,1], -0.0)\n\n for i in keys(y)\n @test findnext(!iszero, y,i) == findnext(!iszero, y_sp,i)\n @test findprev(!iszero, y,i) == findprev(!iszero, y_sp,i)\n @test findnext(iszero, y,i) == findnext(iszero, y_sp,i)\n @test findprev(iszero, y,i) == findprev(iszero, y_sp,i)\n end\n\n z_sp = sparsevec(Dict(1=>1, 5=>1, 8=>0, 10=>1))\n z = collect(z_sp)\n\n for i in keys(z)\n @test findnext(!iszero, z,i) == findnext(!iszero, z_sp,i)\n @test findprev(!iszero, z,i) == findprev(!iszero, z_sp,i)\n end\n\n w = [ \"a\" \"\"; \"\" \"b\"]\n w_sp = sparse(w)\n\n for i in keys(w)\n @test findnext(!isequal(\"\"), w,i) == findnext(!isequal(\"\"), w_sp,i)\n @test findprev(!isequal(\"\"), w,i) == findprev(!isequal(\"\"), w_sp,i)\n @test findnext(isequal(\"\"), w,i) == findnext(isequal(\"\"), w_sp,i)\n @test findprev(isequal(\"\"), w,i) == findprev(isequal(\"\"), w_sp,i)\n end\n\nend",
"@testset \"vec returns a view\" begin\n local A = sparse(Matrix(1.0I, 3, 3))\n local v = vec(A)\n v[1] = 2\n @test A[1,1] == 2\nend",
"@testset \"operations on Integer subtypes\" begin\n s = sparse(UInt8[1, 2, 3], UInt8[1, 2, 3], UInt8[1, 2, 3])\n @test sum(s, dims=2) == reshape([1, 2, 3], 3, 1)\nend",
"@testset \"mapreduce of sparse matrices with trailing elements in nzval #26534\" begin\n B = SparseMatrixCSC{Int,Int}(2, 3,\n [1, 3, 4, 5],\n [1, 2, 1, 2, 999, 999, 999, 999],\n [1, 2, 3, 6, 999, 999, 999, 999]\n )\n @test maximum(B) == 6\nend",
"@testset \"nonscalar setindex!\" begin\n for I in (1:4, :, 5:-1:2, [], trues(5), setindex!(falses(5), true, 2), 3),\n J in (2:4, :, 4:-1:1, [], setindex!(trues(5), false, 3), falses(5), 4)\n V = sparse(1 .+ zeros(_length_or_count_or_five(I)*_length_or_count_or_five(J)))\n M = sparse(1 .+ zeros(_length_or_count_or_five(I), _length_or_count_or_five(J)))\n if I isa Integer && J isa Integer\n @test_throws MethodError spzeros(5,5)[I, J] = V\n @test_throws MethodError spzeros(5,5)[I, J] = M\n continue\n end\n @test setindex!(spzeros(5, 5), V, I, J) == setindex!(zeros(5,5), V, I, J)\n @test setindex!(spzeros(5, 5), M, I, J) == setindex!(zeros(5,5), M, I, J)\n @test setindex!(spzeros(5, 5), Array(M), I, J) == setindex!(zeros(5,5), M, I, J)\n @test setindex!(spzeros(5, 5), Array(V), I, J) == setindex!(zeros(5,5), V, I, J)\n end\n @test setindex!(spzeros(5, 5), 1:25, :) == setindex!(zeros(5,5), 1:25, :) == reshape(1:25, 5, 5)\n @test setindex!(spzeros(5, 5), (25:-1:1).+spzeros(25), :) == setindex!(zeros(5,5), (25:-1:1).+spzeros(25), :) == reshape(25:-1:1, 5, 5)\n for X in (1:20, sparse(1:20), reshape(sparse(1:20), 20, 1), (1:20) .+ spzeros(20, 1), collect(1:20), collect(reshape(1:20, 20, 1)))\n @test setindex!(spzeros(5, 5), X, 6:25) == setindex!(zeros(5,5), 1:20, 6:25)\n @test setindex!(spzeros(5, 5), X, 21:-1:2) == setindex!(zeros(5,5), 1:20, 21:-1:2)\n b = trues(25)\n b[[6, 8, 13, 15, 23]] .= false\n @test setindex!(spzeros(5, 5), X, b) == setindex!(zeros(5, 5), X, b)\n end\nend",
"@testset \"sparse transpose adjoint\" begin\n A = sprand(10, 10, 0.75)\n @test A' == SparseMatrixCSC(A')\n @test SparseMatrixCSC(A') isa SparseMatrixCSC\n @test transpose(A) == SparseMatrixCSC(transpose(A))\n @test SparseMatrixCSC(transpose(A)) isa SparseMatrixCSC\nend",
"@testset \"forward and backward solving of transpose/adjoint triangular matrices\" begin\n rng = MersenneTwister(20180730)\n n = 10\n A = sprandn(rng, n, n, 0.8); A += Diagonal((1:n) - diag(A))\n B = ones(n, 2)\n for (Ttri, triul ) in ((UpperTriangular, triu), (LowerTriangular, tril))\n for trop in (adjoint, transpose)\n AT = Ttri(A) # ...Triangular wrapped\n AC = triul(A) # copied part of A\n ATa = trop(AT) # wrapped Adjoint\n ACa = sparse(trop(AC)) # copied and adjoint\n @test AT \\ B ≈ AC \\ B\n @test ATa \\ B ≈ ACa \\ B\n @test ATa \\ sparse(B) == ATa \\ B\n @test Matrix(ATa) \\ B ≈ ATa \\ B\n @test ATa * ( ATa \\ B ) ≈ B\n end\n end\nend",
"@testset \"Issue #28369\" begin\n M = reshape([[1 2; 3 4], [9 10; 11 12], [5 6; 7 8], [13 14; 15 16]], (2,2))\n MP = reshape([[1 2; 3 4], [5 6; 7 8], [9 10; 11 12], [13 14; 15 16]], (2,2))\n S = sparse(M)\n SP = sparse(MP)\n @test isa(transpose(S), Transpose)\n @test transpose(S) == copy(transpose(S))\n @test Array(transpose(S)) == copy(transpose(M))\n @test permutedims(S) == SP\n @test permutedims(S, (2,1)) == SP\n @test permutedims(S, (1,2)) == S\n @test permutedims(S, (1,2)) !== S\n MC = reshape([[(1+im) 2; 3 4], [9 10; 11 12], [(5 + 2im) 6; 7 8], [13 14; 15 16]], (2,2))\n SC = sparse(MC)\n @test isa(adjoint(SC), Adjoint)\n @test adjoint(SC) == copy(adjoint(SC))\n @test adjoint(MC) == copy(adjoint(SC))\nend",
"@testset \"Issue #28634\" begin\n a = SparseMatrixCSC{Int8, Int16}([1 2; 3 4])\n na = SparseMatrixCSC(a)\n @test typeof(a) === typeof(na)\nend",
"@testset \"Issue #28934\" begin\n A = sprand(5,5,0.5)\n D = Diagonal(rand(5))\n C = copy(A)\n m1 = @which mul!(C,A,D)\n m2 = @which mul!(C,D,A)\n @test m1.module == SparseArrays\n @test m2.module == SparseArrays\nend",
"@testset \"Symmetric of sparse matrix mul! dense vector\" begin\n rng = Random.MersenneTwister(1)\n n = 1000\n p = 0.02\n q = 1 - sqrt(1-p)\n Areal = sprandn(rng, n, n, p)\n Breal = randn(rng, n)\n Acomplex = sprandn(rng, n, n, q) + sprandn(rng, n, n, q) * im\n Bcomplex = Breal + randn(rng, n) * im\n @testset \"symmetric/Hermitian sparse multiply with $S($U)\" for S in (Symmetric, Hermitian), U in (:U, :L), (A, B) in ((Areal,Breal), (Acomplex,Bcomplex))\n Asym = S(A, U)\n As = sparse(Asym) # takes most time\n @test which(mul!, (typeof(B), typeof(Asym), typeof(B))).module == SparseArrays\n @test norm(Asym * B - As * B, Inf) <= eps() * n * p * 10\n end\nend",
"@testset \"Symmetric of view of sparse matrix mul! dense vector\" begin\n rng = Random.MersenneTwister(1)\n n = 1000\n p = 0.02\n q = 1 - sqrt(1-p)\n Areal = view(sprandn(rng, n, n+10, p), :, 6:n+5)\n Breal = randn(rng, n)\n Acomplex = view(sprandn(rng, n, n+10, q) + sprandn(rng, n, n+10, q) * im, :, 6:n+5)\n Bcomplex = Breal + randn(rng, n) * im\n @testset \"symmetric/Hermitian sparseview multiply with $S($U)\" for S in (Symmetric, Hermitian), U in (:U, :L), (A, B) in ((Areal,Breal), (Acomplex,Bcomplex))\n Asym = S(A, U)\n As = sparse(Asym) # takes most time\n @test which(mul!, (typeof(B), typeof(Asym), typeof(B))).module == SparseArrays\n @test norm(Asym * B - As * B, Inf) <= eps() * n * p * 10\n end\nend",
"@testset \"sprand\" begin\n p=0.3; m=1000; n=2000;\n for s in 1:10\n # build a (dense) random matrix with randsubset + rand\n Random.seed!(s);\n v = randsubseq(1:m*n,p);\n x = zeros(m,n);\n x[v] .= rand(length(v));\n # redo the same with sprand\n Random.seed!(s);\n a = sprand(m,n,p);\n @test x == a\n end\nend",
"@testset \"sprandn with type $T\" for T in (Float64, Float32, Float16, ComplexF64, ComplexF32, ComplexF16)\n @test sprandn(T, 5, 5, 0.5) isa AbstractSparseMatrix{T}\nend",
"@testset \"sprandn with invalid type $T\" for T in (AbstractFloat, BigFloat, Complex)\n @test_throws MethodError sprandn(T, 5, 5, 0.5)\nend",
"@testset \"method ambiguity\" begin\n # Ambiguity test is run inside a clean process.\n # https://github.com/JuliaLang/julia/issues/28804\n script = joinpath(@__DIR__, \"ambiguous_exec.jl\")\n cmd = `$(Base.julia_cmd()) --startup-file=no $script`\n @test success(pipeline(cmd; stdout=stdout, stderr=stderr))\nend",
"@testset \"oneunit of sparse matrix\" begin\n A = sparse([Second(0) Second(0); Second(0) Second(0)])\n @test oneunit(sprand(2, 2, 0.5)) isa SparseMatrixCSC{Float64}\n @test oneunit(A) isa SparseMatrixCSC{Second}\n @test one(sprand(2, 2, 0.5)) isa SparseMatrixCSC{Float64}\n @test one(A) isa SparseMatrixCSC{Int}\nend",
"@testset \"circshift\" begin\n m,n = 17,15\n A = sprand(m, n, 0.5)\n for rshift in (-1, 0, 1, 10), cshift in (-1, 0, 1, 10)\n shifts = (rshift, cshift)\n # using dense circshift to compare\n B = circshift(Matrix(A), shifts)\n # sparse circshift\n C = circshift(A, shifts)\n @test C == B\n # sparse circshift should not add structural zeros\n @test nnz(C) == nnz(A)\n # test circshift!\n D = similar(A)\n circshift!(D, A, shifts)\n @test D == B\n @test nnz(D) == nnz(A)\n # test different in/out types\n A2 = floor.(100A)\n E1 = spzeros(Int64, m, n)\n E2 = spzeros(Int64, m, n)\n circshift!(E1, A2, shifts)\n circshift!(E2, Matrix(A2), shifts)\n @test E1 == E2\n end\nend",
"@testset \"wrappers of sparse\" begin\n m = n = 10\n A = spzeros(ComplexF64, m, n)\n A[:,1] = 1:m\n A[:,2] = [1 3 0 0 0 0 0 0 0 0]'\n A[:,3] = [2 4 0 0 0 0 0 0 0 0]'\n A[:,4] = [0 0 0 0 5 3 0 0 0 0]'\n A[:,5] = [0 0 0 0 6 2 0 0 0 0]'\n A[:,6] = [0 0 0 0 7 4 0 0 0 0]'\n A[:,7:n] = rand(ComplexF64, m, n-6)\n B = Matrix(A)\n dowrap(wr, A) = wr(A)\n dowrap(wr::Tuple, A) = (wr[1])(A, wr[2:end]...)\n\n @testset \"sparse($wr(A))\" for wr in (\n Symmetric, (Symmetric, :L), Hermitian, (Hermitian, :L),\n Transpose, Adjoint,\n UpperTriangular, LowerTriangular,\n UnitUpperTriangular, UnitLowerTriangular,\n (view, 3:6, 2:5))\n\n @test SparseMatrixCSC(dowrap(wr, A)) == Matrix(dowrap(wr, B))\n end\n\n @testset \"sparse($at($wr))\" for at = (Transpose, Adjoint), wr =\n (UpperTriangular, LowerTriangular,\n UnitUpperTriangular, UnitLowerTriangular)\n\n @test SparseMatrixCSC(at(wr(A))) == Matrix(at(wr(B)))\n end\n\n @test sparse([1,2,3,4,5]') == SparseMatrixCSC([1 2 3 4 5])\n @test sparse(UpperTriangular(A')) == UpperTriangular(B')\n @test sparse(Adjoint(UpperTriangular(A'))) == Adjoint(UpperTriangular(B'))\nend",
"@testset \"unary operations on matrices where length(nzval)>nnz\" begin\n # this should create a sparse matrix with length(nzval)>nnz\n A = SparseMatrixCSC(Complex{BigInt}[1+im 2+2im]')'[1:1, 2:2]\n # ...ensure it does! If necessary, the test needs to be updated to use\n # another mechanism to create a suitable A.\n @assert length(A.nzval) > nnz(A)\n @test -A == fill(-2-2im, 1, 1)\n @test conj(A) == fill(2-2im, 1, 1)\n conj!(A)\n @test A == fill(2-2im, 1, 1)\nend",
"@testset \"issue #31453\" for T in [UInt8, Int8, UInt16, Int16, UInt32, Int32]\n i = Int[1, 2]\n j = Int[2, 1]\n i2 = T.(i)\n j2 = T.(j)\n v = [500, 600]\n x1 = sparse(i, j, v)\n x2 = sparse(i2, j2, v)\n @test sum(x1) == sum(x2) == 1100\n @test sum(x1, dims=1) == sum(x2, dims=1)\n @test sum(x1, dims=2) == sum(x2, dims=2)\nend",
"@testset \"sparse ref\" begin\n p = [4, 1, 2, 3, 2]\n @test Array(s116[p,:]) == a116[p,:]\n @test Array(s116[:,p]) == a116[:,p]\n @test Array(s116[p,p]) == a116[p,p]\n end",
"@testset \"sparse assignment\" begin\n p = [4, 1, 3]\n a116[p, p] .= -1\n s116[p, p] .= -1\n @test a116 == s116\n\n p = [2, 1, 4]\n a116[p, p] = reshape(1:9, 3, 3)\n s116[p, p] = reshape(1:9, 3, 3)\n @test a116 == s116\n end",
"@testset \"triangular multiply with $tr($wr)\" for tr in (identity, adjoint, transpose),\n wr in (UpperTriangular, LowerTriangular, UnitUpperTriangular, UnitLowerTriangular)\n AW = tr(wr(A))\n MAW = tr(wr(MA))\n @test AW * B ≈ MAW * B\n end",
"@testset \"triangular solver for $tr($wr)\" for tr in (identity, adjoint, transpose),\n wr in (UpperTriangular, LowerTriangular, UnitUpperTriangular, UnitLowerTriangular)\n AW = tr(wr(A))\n MAW = tr(wr(MA))\n @test AW \\ B ≈ MAW \\ B\n end",
"@testset \"triangular singular exceptions\" begin\n A = LowerTriangular(sparse([0 2.0;0 1]))\n @test_throws SingularException(1) A \\ ones(2)\n A = UpperTriangular(sparse([1.0 0;0 0]))\n @test_throws SingularException(2) A \\ ones(2)\n end"
] |
f7535830c743be2765fb3db17de351a083794962
| 1,565
|
jl
|
Julia
|
test/testlogfcns.jl
|
curtd/ThreadPools.jl
|
e36e82c51adfd22a7d0459912861bfaf1d43deff
|
[
"MIT"
] | 1
|
2021-05-25T05:04:38.000Z
|
2021-05-25T05:04:38.000Z
|
test/testlogfcns.jl
|
ppalmes/ThreadPools.jl
|
e36e82c51adfd22a7d0459912861bfaf1d43deff
|
[
"MIT"
] | null | null | null |
test/testlogfcns.jl
|
ppalmes/ThreadPools.jl
|
e36e82c51adfd22a7d0459912861bfaf1d43deff
|
[
"MIT"
] | null | null | null |
module TestLoggedFunctions
using Test
import ThreadPools: LoggedStaticPool
using ThreadPools
include("util.jl")
@testset "log functions" begin
@testset "read/write logs" begin
N = 2 * Threads.nthreads()
pool = LoggedStaticPool()
tforeach(pool, x->sleep(0.01*x), 1:N)
close(pool)
dumplog("_tmp.log", pool)
log2 = readlog("_tmp.log")
@test pool.log == log2
rm("_tmp.log")
end
@testset "showactivity" begin
io = IOBuffer()
showactivity(io, "$(@__DIR__)/testlog.txt", 0.1, nthreads=4)
@test replace(String(take!(io)), r"\s+\n"=>"\n") == """0.000 - - - -
0.100 4 1 3 2
0.200 4 5 3 2
0.300 4 5 3 6
0.400 4 5 7 6
0.500 8 5 7 6
0.600 8 5 7 6
0.700 8 - 7 6
0.800 8 - 7 6
0.900 8 - 7 -
1.000 8 - 7 -
1.100 8 - - -
1.200 8 - - -
1.300 - - - -
1.400 - - - -
1.500 - - - -
"""
end
@testset "showstats" begin
io = IOBuffer()
showstats(io, "$(@__DIR__)/testlog.txt")
@test String(take!(io)) == """
Total duration: 1.212 s
Number of jobs: 8
Average job duration: 0.457 s
Minimum job duration: 0.11 s
Maximum job duration: 0.805 s
Thread 1: Duration 1.211 s, Gap time 0.0 s
Thread 2: Duration 0.616 s, Gap time 0.0 s
Thread 3: Duration 1.024 s, Gap time 0.0 s
Thread 4: Duration 0.805 s, Gap time 0.0 s
"""
end
end
end # module
| 24.076923
| 84
| 0.506709
|
[
"@testset \"log functions\" begin\n\n @testset \"read/write logs\" begin\n N = 2 * Threads.nthreads()\n pool = LoggedStaticPool()\n tforeach(pool, x->sleep(0.01*x), 1:N)\n close(pool)\n dumplog(\"_tmp.log\", pool)\n log2 = readlog(\"_tmp.log\")\n @test pool.log == log2\n rm(\"_tmp.log\")\n end\n\n @testset \"showactivity\" begin\n io = IOBuffer()\n showactivity(io, \"$(@__DIR__)/testlog.txt\", 0.1, nthreads=4)\n @test replace(String(take!(io)), r\"\\s+\\n\"=>\"\\n\") == \"\"\"0.000 - - - -\n0.100 4 1 3 2\n0.200 4 5 3 2\n0.300 4 5 3 6\n0.400 4 5 7 6\n0.500 8 5 7 6\n0.600 8 5 7 6\n0.700 8 - 7 6\n0.800 8 - 7 6\n0.900 8 - 7 -\n1.000 8 - 7 -\n1.100 8 - - -\n1.200 8 - - -\n1.300 - - - -\n1.400 - - - -\n1.500 - - - -\n\"\"\"\n end\n\n @testset \"showstats\" begin\n io = IOBuffer()\n showstats(io, \"$(@__DIR__)/testlog.txt\")\n @test String(take!(io)) == \"\"\"\n\n Total duration: 1.212 s\n Number of jobs: 8\n Average job duration: 0.457 s\n Minimum job duration: 0.11 s\n Maximum job duration: 0.805 s\n \n Thread 1: Duration 1.211 s, Gap time 0.0 s\n Thread 2: Duration 0.616 s, Gap time 0.0 s\n Thread 3: Duration 1.024 s, Gap time 0.0 s\n Thread 4: Duration 0.805 s, Gap time 0.0 s\n \"\"\"\n end\n\nend"
] |
f753b345c945a2ed273aed4f174ea95f216beb25
| 238
|
jl
|
Julia
|
test/runtests.jl
|
UnofficialJuliaMirrorSnapshots/HilbertSpaceFillingCurve.jl-515b7ef8-bac0-55e1-a220-237e90591ccc
|
7a1acc28354cfa94cea28cf6b520a0cd8c1bd4c7
|
[
"MIT"
] | 7
|
2019-06-13T08:50:49.000Z
|
2022-01-06T04:31:29.000Z
|
test/runtests.jl
|
UnofficialJuliaMirrorSnapshots/HilbertSpaceFillingCurve.jl-515b7ef8-bac0-55e1-a220-237e90591ccc
|
7a1acc28354cfa94cea28cf6b520a0cd8c1bd4c7
|
[
"MIT"
] | 2
|
2019-04-23T14:16:05.000Z
|
2019-12-18T14:45:54.000Z
|
test/runtests.jl
|
UnofficialJuliaMirrorSnapshots/HilbertSpaceFillingCurve.jl-515b7ef8-bac0-55e1-a220-237e90591ccc
|
7a1acc28354cfa94cea28cf6b520a0cd8c1bd4c7
|
[
"MIT"
] | 2
|
2019-07-23T07:27:37.000Z
|
2020-02-08T10:42:45.000Z
|
using HilbertSpaceFillingCurve
using Test
@testset "hilbert" begin
d = 10
for ndims in 2:3, nbits in [8,16]
p = hilbert(d, ndims, nbits)
@test d == hilbert(p, ndims, nbits)
end
@test_throws AssertionError hilbert(d, 2, 64)
end
| 17
| 45
| 0.697479
|
[
"@testset \"hilbert\" begin\n\nd = 10\nfor ndims in 2:3, nbits in [8,16]\n p = hilbert(d, ndims, nbits)\n @test d == hilbert(p, ndims, nbits)\nend\n\n@test_throws AssertionError hilbert(d, 2, 64)\n\nend"
] |
f75891a3ba16be7ebc580614c60385f31554fd3b
| 5,964
|
jl
|
Julia
|
test/runtests.jl
|
m-wells/MappedArrays.jl
|
8fa8d7d9cc5cf99bd37a7d5f85376916aa7d0857
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
m-wells/MappedArrays.jl
|
8fa8d7d9cc5cf99bd37a7d5f85376916aa7d0857
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
m-wells/MappedArrays.jl
|
8fa8d7d9cc5cf99bd37a7d5f85376916aa7d0857
|
[
"MIT"
] | null | null | null |
using MappedArrays
using Test
@test isempty(detect_ambiguities(MappedArrays, Base, Core))
using FixedPointNumbers, OffsetArrays, ColorTypes
@testset "ReadonlyMappedArray" begin
a = [1,4,9,16]
s = view(a', 1:1, [1,2,4])
b = @inferred(mappedarray(sqrt, a))
@test parent(b) === a
@test eltype(b) == Float64
@test @inferred(getindex(b, 1)) == 1
@test b[2] == 2
@test b[3] == 3
@test b[4] == 4
@test_throws ErrorException b[3] = 0
@test isa(eachindex(b), AbstractUnitRange)
b = mappedarray(sqrt, a')
@test isa(eachindex(b), AbstractUnitRange)
b = mappedarray(sqrt, s)
@test isa(eachindex(b), CartesianIndices)
c = Base.unaliascopy(b)
@test c == b
@test c !== b
end
@testset "MappedArray" begin
intsym = Int == Int64 ? :Int64 : :Int32
a = [1,4,9,16]
s = view(a', 1:1, [1,2,4])
c = @inferred(mappedarray(sqrt, x->x*x, a))
@test parent(c) === a
@test @inferred(getindex(c, 1)) == 1
@test c[2] == 2
@test c[3] == 3
@test c[4] == 4
c[3] = 2
@test a[3] == 4
@test_throws InexactError(intsym, Int, 2.2^2) c[3] = 2.2 # because the backing array is Array{Int}
@test isa(eachindex(c), AbstractUnitRange)
b = @inferred(mappedarray(sqrt, a'))
@test isa(eachindex(b), AbstractUnitRange)
c = @inferred(mappedarray(sqrt, x->x*x, s))
@test isa(eachindex(c), CartesianIndices)
d = Base.unaliascopy(c)
@test c == d
@test c !== d
sb = similar(b)
@test isa(sb, Array{Float64})
@test size(sb) == size(b)
a = [0x01 0x03; 0x02 0x04]
b = @inferred(mappedarray(y->N0f8(y,0), x->x.i, a))
for i = 1:4
@test b[i] == N0f8(i/255)
end
b[2,1] = 10/255
@test a[2,1] == 0x0a
end
@testset "of_eltype" begin
a = [0.1 0.3; 0.2 0.4]
b = @inferred(of_eltype(N0f8, a))
@test b[1,1] === N0f8(0.1)
b = @inferred(of_eltype(zero(N0f8), a))
@test b[1,1] === N0f8(0.1)
b[2,1] = N0f8(0.5)
@test a[2,1] == N0f8(0.5)
@test !(b === a)
b = @inferred(of_eltype(Float64, a))
@test b === a
b = @inferred(of_eltype(0.0, a))
@test b === a
end
@testset "OffsetArrays" begin
a = OffsetArray(randn(5), -2:2)
aabs = mappedarray(abs, a)
@test axes(aabs) == (-2:2,)
for i = -2:2
@test aabs[i] == abs(a[i])
end
end
@testset "No zero(::T)" begin
astr = @inferred(mappedarray(length, ["abc", "onetwothree"]))
@test eltype(astr) == Int
@test astr == [3, 11]
a = @inferred(mappedarray(x->x+0.5, Int[]))
@test eltype(a) == Float64
# typestable string
astr = @inferred(mappedarray(uppercase, ["abc", "def"]))
@test eltype(astr) == String
@test astr == ["ABC","DEF"]
end
@testset "ReadOnlyMultiMappedArray" begin
a = reshape(1:6, 2, 3)
# @test @inferred(axes(a)) == (Base.OneTo(2), Base.OneTo(3))
b = fill(10.0f0, 2, 3)
M = @inferred(mappedarray(+, a, b))
@test @inferred(eltype(M)) == Float32
@test @inferred(IndexStyle(M)) == IndexLinear()
@test @inferred(IndexStyle(typeof(M))) == IndexLinear()
@test @inferred(size(M)) === size(a)
@test @inferred(axes(M)) === axes(a)
@test M == a + b
@test @inferred(M[1]) === 11.0f0
@test @inferred(M[CartesianIndex(1, 1)]) === 11.0f0
d = Base.unaliascopy(b)
@test d == b
@test d !== b
c = view(reshape(1:9, 3, 3), 1:2, :)
M = @inferred(mappedarray(+, c, b))
@test @inferred(eltype(M)) == Float32
@test @inferred(IndexStyle(M)) == IndexCartesian()
@test @inferred(IndexStyle(typeof(M))) == IndexCartesian()
@test @inferred(axes(M)) === axes(c)
@test M == c + b
@test @inferred(M[1]) === 11.0f0
@test @inferred(M[CartesianIndex(1, 1)]) === 11.0f0
end
@testset "MultiMappedArray" begin
intsym = Int == Int64 ? :Int64 : :Int32
a = [0.1 0.2; 0.3 0.4]
b = N0f8[0.6 0.5; 0.4 0.3]
c = [0 1; 0 1]
f = RGB{N0f8}
finv = c->(red(c), green(c), blue(c))
M = @inferred(mappedarray(f, finv, a, b, c))
@test @inferred(eltype(M)) == RGB{N0f8}
@test @inferred(IndexStyle(M)) == IndexLinear()
@test @inferred(IndexStyle(typeof(M))) == IndexLinear()
@test @inferred(size(M)) === size(a)
@test @inferred(axes(M)) === axes(a)
@test M[1,1] === RGB{N0f8}(0.1, 0.6, 0)
@test M[2,1] === RGB{N0f8}(0.3, 0.4, 0)
@test M[1,2] === RGB{N0f8}(0.2, 0.5, 1)
@test M[2,2] === RGB{N0f8}(0.4, 0.3, 1)
M[1,2] = RGB(0.25, 0.35, 0)
@test M[1,2] === RGB{N0f8}(0.25, 0.35, 0)
@test a[1,2] == N0f8(0.25)
@test b[1,2] == N0f8(0.35)
@test c[1,2] == 0
@test_throws InexactError(intsym, Int, N0f8(0.45)) M[1,2] = RGB(0.25, 0.35, 0.45)
R = reinterpret(N0f8, M)
@test R == N0f8[0.1 0.25; 0.6 0.35; 0 0; 0.3 0.4; 0.4 0.3; 0 1]
R[2,1] = 0.8
@test b[1,1] === N0f8(0.8)
a = view(reshape(0.1:0.1:0.6, 3, 2), 1:2, 1:2)
M = @inferred(mappedarray(f, finv, a, b, c))
@test @inferred(eltype(M)) == RGB{N0f8}
@test @inferred(IndexStyle(M)) == IndexCartesian()
@test @inferred(IndexStyle(typeof(M))) == IndexCartesian()
@test @inferred(axes(M)) === axes(a)
@test M[1,1] === RGB{N0f8}(0.1, 0.8, 0)
@test_throws ErrorException("indexed assignment fails for a reshaped range; consider calling collect") M[1,2] = RGB(0.25, 0.35, 0)
d = Base.unaliascopy(M)
@test d == M
@test d !== M
a = reshape(0.1:0.1:0.6, 3, 2)
@test_throws DimensionMismatch mappedarray(f, finv, a, b, c)
end
@testset "Display" begin
a = [1,2,3,4]
b = mappedarray(sqrt, a)
@test summary(b) == "4-element mappedarray(sqrt, ::Array{Int64,1}) with eltype Float64"
c = mappedarray(sqrt, x->x*x, a)
@test summary(c) == "4-element mappedarray(sqrt, x->x * x, ::Array{Int64,1}) with eltype Float64"
# issue #26
M = @inferred mappedarray((x1,x2)->x1+x2, a, a)
io = IOBuffer()
show(io, MIME("text/plain"), M)
str = String(take!(io))
@test occursin("x1 + x2", str)
end
| 31.389474
| 134
| 0.562039
|
[
"@testset \"ReadonlyMappedArray\" begin\n a = [1,4,9,16]\n s = view(a', 1:1, [1,2,4])\n\n b = @inferred(mappedarray(sqrt, a))\n @test parent(b) === a\n @test eltype(b) == Float64\n @test @inferred(getindex(b, 1)) == 1\n @test b[2] == 2\n @test b[3] == 3\n @test b[4] == 4\n @test_throws ErrorException b[3] = 0\n @test isa(eachindex(b), AbstractUnitRange)\n b = mappedarray(sqrt, a')\n @test isa(eachindex(b), AbstractUnitRange)\n b = mappedarray(sqrt, s)\n @test isa(eachindex(b), CartesianIndices)\n c = Base.unaliascopy(b)\n @test c == b\n @test c !== b\nend",
"@testset \"MappedArray\" begin\n intsym = Int == Int64 ? :Int64 : :Int32\n a = [1,4,9,16]\n s = view(a', 1:1, [1,2,4])\n c = @inferred(mappedarray(sqrt, x->x*x, a))\n @test parent(c) === a\n @test @inferred(getindex(c, 1)) == 1\n @test c[2] == 2\n @test c[3] == 3\n @test c[4] == 4\n c[3] = 2\n @test a[3] == 4\n @test_throws InexactError(intsym, Int, 2.2^2) c[3] = 2.2 # because the backing array is Array{Int}\n @test isa(eachindex(c), AbstractUnitRange)\n b = @inferred(mappedarray(sqrt, a'))\n @test isa(eachindex(b), AbstractUnitRange)\n c = @inferred(mappedarray(sqrt, x->x*x, s))\n @test isa(eachindex(c), CartesianIndices)\n\n d = Base.unaliascopy(c)\n @test c == d\n @test c !== d\n \n sb = similar(b)\n @test isa(sb, Array{Float64})\n @test size(sb) == size(b)\n\n a = [0x01 0x03; 0x02 0x04]\n b = @inferred(mappedarray(y->N0f8(y,0), x->x.i, a))\n for i = 1:4\n @test b[i] == N0f8(i/255)\n end\n b[2,1] = 10/255\n @test a[2,1] == 0x0a\nend",
"@testset \"of_eltype\" begin\n a = [0.1 0.3; 0.2 0.4]\n b = @inferred(of_eltype(N0f8, a))\n @test b[1,1] === N0f8(0.1)\n b = @inferred(of_eltype(zero(N0f8), a))\n @test b[1,1] === N0f8(0.1)\n b[2,1] = N0f8(0.5)\n @test a[2,1] == N0f8(0.5)\n @test !(b === a)\n b = @inferred(of_eltype(Float64, a))\n @test b === a\n b = @inferred(of_eltype(0.0, a))\n @test b === a\nend",
"@testset \"OffsetArrays\" begin\n a = OffsetArray(randn(5), -2:2)\n aabs = mappedarray(abs, a)\n @test axes(aabs) == (-2:2,)\n for i = -2:2\n @test aabs[i] == abs(a[i])\n end\nend",
"@testset \"No zero(::T)\" begin\n astr = @inferred(mappedarray(length, [\"abc\", \"onetwothree\"]))\n @test eltype(astr) == Int\n @test astr == [3, 11]\n a = @inferred(mappedarray(x->x+0.5, Int[]))\n @test eltype(a) == Float64\n\n # typestable string\n astr = @inferred(mappedarray(uppercase, [\"abc\", \"def\"]))\n @test eltype(astr) == String\n @test astr == [\"ABC\",\"DEF\"]\nend",
"@testset \"ReadOnlyMultiMappedArray\" begin\n a = reshape(1:6, 2, 3)\n# @test @inferred(axes(a)) == (Base.OneTo(2), Base.OneTo(3))\n b = fill(10.0f0, 2, 3)\n M = @inferred(mappedarray(+, a, b))\n @test @inferred(eltype(M)) == Float32\n @test @inferred(IndexStyle(M)) == IndexLinear()\n @test @inferred(IndexStyle(typeof(M))) == IndexLinear()\n @test @inferred(size(M)) === size(a)\n @test @inferred(axes(M)) === axes(a)\n @test M == a + b\n @test @inferred(M[1]) === 11.0f0\n @test @inferred(M[CartesianIndex(1, 1)]) === 11.0f0\n \n d = Base.unaliascopy(b)\n @test d == b\n @test d !== b\n\n c = view(reshape(1:9, 3, 3), 1:2, :)\n M = @inferred(mappedarray(+, c, b))\n @test @inferred(eltype(M)) == Float32\n @test @inferred(IndexStyle(M)) == IndexCartesian()\n @test @inferred(IndexStyle(typeof(M))) == IndexCartesian()\n @test @inferred(axes(M)) === axes(c)\n @test M == c + b\n @test @inferred(M[1]) === 11.0f0\n @test @inferred(M[CartesianIndex(1, 1)]) === 11.0f0\nend",
"@testset \"MultiMappedArray\" begin\n intsym = Int == Int64 ? :Int64 : :Int32\n a = [0.1 0.2; 0.3 0.4]\n b = N0f8[0.6 0.5; 0.4 0.3]\n c = [0 1; 0 1]\n f = RGB{N0f8}\n finv = c->(red(c), green(c), blue(c))\n M = @inferred(mappedarray(f, finv, a, b, c))\n @test @inferred(eltype(M)) == RGB{N0f8}\n @test @inferred(IndexStyle(M)) == IndexLinear()\n @test @inferred(IndexStyle(typeof(M))) == IndexLinear()\n @test @inferred(size(M)) === size(a)\n @test @inferred(axes(M)) === axes(a)\n @test M[1,1] === RGB{N0f8}(0.1, 0.6, 0)\n @test M[2,1] === RGB{N0f8}(0.3, 0.4, 0)\n @test M[1,2] === RGB{N0f8}(0.2, 0.5, 1)\n @test M[2,2] === RGB{N0f8}(0.4, 0.3, 1)\n M[1,2] = RGB(0.25, 0.35, 0)\n @test M[1,2] === RGB{N0f8}(0.25, 0.35, 0)\n @test a[1,2] == N0f8(0.25)\n @test b[1,2] == N0f8(0.35)\n @test c[1,2] == 0\n @test_throws InexactError(intsym, Int, N0f8(0.45)) M[1,2] = RGB(0.25, 0.35, 0.45)\n R = reinterpret(N0f8, M)\n @test R == N0f8[0.1 0.25; 0.6 0.35; 0 0; 0.3 0.4; 0.4 0.3; 0 1]\n R[2,1] = 0.8\n @test b[1,1] === N0f8(0.8)\n\n a = view(reshape(0.1:0.1:0.6, 3, 2), 1:2, 1:2)\n M = @inferred(mappedarray(f, finv, a, b, c))\n @test @inferred(eltype(M)) == RGB{N0f8}\n @test @inferred(IndexStyle(M)) == IndexCartesian()\n @test @inferred(IndexStyle(typeof(M))) == IndexCartesian()\n @test @inferred(axes(M)) === axes(a)\n @test M[1,1] === RGB{N0f8}(0.1, 0.8, 0)\n @test_throws ErrorException(\"indexed assignment fails for a reshaped range; consider calling collect\") M[1,2] = RGB(0.25, 0.35, 0)\n\n d = Base.unaliascopy(M)\n @test d == M\n @test d !== M\n \n a = reshape(0.1:0.1:0.6, 3, 2)\n @test_throws DimensionMismatch mappedarray(f, finv, a, b, c)\nend",
"@testset \"Display\" begin\n a = [1,2,3,4]\n b = mappedarray(sqrt, a)\n @test summary(b) == \"4-element mappedarray(sqrt, ::Array{Int64,1}) with eltype Float64\"\n c = mappedarray(sqrt, x->x*x, a)\n @test summary(c) == \"4-element mappedarray(sqrt, x->x * x, ::Array{Int64,1}) with eltype Float64\"\n # issue #26\n M = @inferred mappedarray((x1,x2)->x1+x2, a, a)\n io = IOBuffer()\n show(io, MIME(\"text/plain\"), M)\n str = String(take!(io))\n @test occursin(\"x1 + x2\", str)\nend"
] |
f75bdd053fb108ea728d4648c9d13f6cbd888302
| 3,087
|
jl
|
Julia
|
test/QecsimAdaptors.jl
|
qecsim/TensorNetworkCodes.jl
|
2b5850ab834cbeeaa35666c12042d08239c281fe
|
[
"BSD-3-Clause"
] | null | null | null |
test/QecsimAdaptors.jl
|
qecsim/TensorNetworkCodes.jl
|
2b5850ab834cbeeaa35666c12042d08239c281fe
|
[
"BSD-3-Clause"
] | 2
|
2022-02-21T09:04:57.000Z
|
2022-02-25T10:08:33.000Z
|
test/QecsimAdaptors.jl
|
qecsim/TensorNetworkCodes.jl
|
2b5850ab834cbeeaa35666c12042d08239c281fe
|
[
"BSD-3-Clause"
] | null | null | null |
using Qecsim
using Qecsim.GenericModels: DepolarizingErrorModel, NaiveDecoder
using TensorNetworkCodes
using TensorNetworkCodes.QecsimAdaptors
using Test
@testset "_tnpauli_to_bsf" begin
# single operator
str_pauli = "IXIYIZ"
int_pauli = pauli_rep_change.(collect(str_pauli))
bsf_pauli = QecsimAdaptors._tnpauli_to_bsf(int_pauli)
@test bsf_pauli == Qecsim.to_bsf(str_pauli)
# multiple operators
str_paulis = ["XZZXI", "IXZZX", "XIXZZ", "ZXIXZ"]
int_paulis = [pauli_rep_change.(collect(p)) for p in str_paulis]
bsf_paulis = QecsimAdaptors._tnpauli_to_bsf(int_paulis)
@test bsf_paulis == Qecsim.to_bsf(str_paulis)
end
@testset "_bsf_to_tnpauli" begin
# single operator
str_pauli = "IXIYIZ"
bsf_pauli = Qecsim.to_bsf(str_pauli)
int_pauli = QecsimAdaptors._bsf_to_tnpauli(bsf_pauli)
@test int_pauli == pauli_rep_change.(collect(str_pauli))
# multiple operators
str_paulis = ["XZZXI", "IXZZX", "XIXZZ", "ZXIXZ"]
bsf_paulis = Qecsim.to_bsf(str_paulis)
int_paulis = QecsimAdaptors._bsf_to_tnpauli(bsf_paulis)
@test int_paulis == [pauli_rep_change.(collect(p)) for p in str_paulis]
end
@testset "QecsimTNCode" begin
# default distance, label
tn_code = TensorNetworkCode(five_qubit_code())
qs_code = QecsimTNCode(tn_code)
@test validate(qs_code) === nothing # no error
@test isequal(nkd(qs_code), (5, 1, missing))
@test label(qs_code) == "QecsimTNCode: [5,1,missing]"
# kwargs distance, label
tn_code = TensorNetworkCode(steane_code())
qs_code = QecsimTNCode(tn_code; distance=3, label="Steane")
@test validate(qs_code) === nothing # no error
@test isequal(nkd(qs_code), (7, 1, 3))
@test label(qs_code) == "Steane"
end
@testset "QecsimTNDecoder" begin
# field test
@test label(QecsimTNDecoder()) == "QecsimTNDecoder"
@test label(QecsimTNDecoder(1)) == "QecsimTNDecoder (chi=1)"
# invalid parameters
@test_throws ArgumentError QecsimTNDecoder(-1)
# models
tn_code = rotated_surface_code(3)
qs_code = QecsimTNCode(tn_code; distance=3, label="Rotated Surface 3")
qs_error_model = DepolarizingErrorModel()
qs_decoder = QecsimTNDecoder()
p = 0.1
# direct test of decoder (exact contraction)
qs_error = generate(qs_error_model, qs_code, p)
qs_syndrome = bsp(stabilizers(qs_code), qs_error)
qs_result = decode(qs_decoder, qs_code, qs_syndrome; p=p)
@test bsp(stabilizers(qs_code), qs_result.recovery) == qs_syndrome
@test !any(bsp(stabilizers(qs_code), xor.(qs_error, qs_result.recovery)))
@test 0 <= qs_result.custom_values[1][1] <= 1 # success probability
# direct test of decoder (approx. contraction)
qs_result = decode(QecsimTNDecoder(1), qs_code, qs_syndrome; p=p)
@test bsp(stabilizers(qs_code), qs_result.recovery) == qs_syndrome
@test !any(bsp(stabilizers(qs_code), xor.(qs_error, qs_result.recovery)))
@test 0 <= qs_result.custom_values[1][1] <= 1 # success probability
# test via run_once
qec_run_once(qs_code, qs_error_model, qs_decoder, p) # no error
end
| 41.16
| 77
| 0.716553
|
[
"@testset \"_tnpauli_to_bsf\" begin\n # single operator\n str_pauli = \"IXIYIZ\"\n int_pauli = pauli_rep_change.(collect(str_pauli))\n bsf_pauli = QecsimAdaptors._tnpauli_to_bsf(int_pauli)\n @test bsf_pauli == Qecsim.to_bsf(str_pauli)\n # multiple operators\n str_paulis = [\"XZZXI\", \"IXZZX\", \"XIXZZ\", \"ZXIXZ\"]\n int_paulis = [pauli_rep_change.(collect(p)) for p in str_paulis]\n bsf_paulis = QecsimAdaptors._tnpauli_to_bsf(int_paulis)\n @test bsf_paulis == Qecsim.to_bsf(str_paulis)\nend",
"@testset \"_bsf_to_tnpauli\" begin\n # single operator\n str_pauli = \"IXIYIZ\"\n bsf_pauli = Qecsim.to_bsf(str_pauli)\n int_pauli = QecsimAdaptors._bsf_to_tnpauli(bsf_pauli)\n @test int_pauli == pauli_rep_change.(collect(str_pauli))\n # multiple operators\n str_paulis = [\"XZZXI\", \"IXZZX\", \"XIXZZ\", \"ZXIXZ\"]\n bsf_paulis = Qecsim.to_bsf(str_paulis)\n int_paulis = QecsimAdaptors._bsf_to_tnpauli(bsf_paulis)\n @test int_paulis == [pauli_rep_change.(collect(p)) for p in str_paulis]\nend",
"@testset \"QecsimTNCode\" begin\n # default distance, label\n tn_code = TensorNetworkCode(five_qubit_code())\n qs_code = QecsimTNCode(tn_code)\n @test validate(qs_code) === nothing # no error\n @test isequal(nkd(qs_code), (5, 1, missing))\n @test label(qs_code) == \"QecsimTNCode: [5,1,missing]\"\n # kwargs distance, label\n tn_code = TensorNetworkCode(steane_code())\n qs_code = QecsimTNCode(tn_code; distance=3, label=\"Steane\")\n @test validate(qs_code) === nothing # no error\n @test isequal(nkd(qs_code), (7, 1, 3))\n @test label(qs_code) == \"Steane\"\nend",
"@testset \"QecsimTNDecoder\" begin\n # field test\n @test label(QecsimTNDecoder()) == \"QecsimTNDecoder\"\n @test label(QecsimTNDecoder(1)) == \"QecsimTNDecoder (chi=1)\"\n # invalid parameters\n @test_throws ArgumentError QecsimTNDecoder(-1)\n # models\n tn_code = rotated_surface_code(3)\n qs_code = QecsimTNCode(tn_code; distance=3, label=\"Rotated Surface 3\")\n qs_error_model = DepolarizingErrorModel()\n qs_decoder = QecsimTNDecoder()\n p = 0.1\n # direct test of decoder (exact contraction)\n qs_error = generate(qs_error_model, qs_code, p)\n qs_syndrome = bsp(stabilizers(qs_code), qs_error)\n qs_result = decode(qs_decoder, qs_code, qs_syndrome; p=p)\n @test bsp(stabilizers(qs_code), qs_result.recovery) == qs_syndrome\n @test !any(bsp(stabilizers(qs_code), xor.(qs_error, qs_result.recovery)))\n @test 0 <= qs_result.custom_values[1][1] <= 1 # success probability\n # direct test of decoder (approx. contraction)\n qs_result = decode(QecsimTNDecoder(1), qs_code, qs_syndrome; p=p)\n @test bsp(stabilizers(qs_code), qs_result.recovery) == qs_syndrome\n @test !any(bsp(stabilizers(qs_code), xor.(qs_error, qs_result.recovery)))\n @test 0 <= qs_result.custom_values[1][1] <= 1 # success probability\n # test via run_once\n qec_run_once(qs_code, qs_error_model, qs_decoder, p) # no error\nend"
] |
f75d10073dff615904327de63e97cefcbbcf82ce
| 12,576
|
jl
|
Julia
|
test/runtests.jl
|
ChrisRackauckas/VectorizationBase.jl
|
edd756facb6dd591220f7e290d0b83283354e720
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
ChrisRackauckas/VectorizationBase.jl
|
edd756facb6dd591220f7e290d0b83283354e720
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
ChrisRackauckas/VectorizationBase.jl
|
edd756facb6dd591220f7e290d0b83283354e720
|
[
"MIT"
] | null | null | null |
using VectorizationBase
using Test
const W64 = VectorizationBase.REGISTER_SIZE ÷ sizeof(Float64)
const W32 = VectorizationBase.REGISTER_SIZE ÷ sizeof(Float32)
A = randn(13, 17); L = length(A); M, N = size(A);
@testset "VectorizationBase.jl" begin
# Write your own tests here.
@test isempty(detect_unbound_args(VectorizationBase))
@test first(A) === A[1]
@testset "Struct-Wrapped Vec" begin
@test extract_data(zero(SVec{4,Float64})) === (VE(0.0),VE(0.0),VE(0.0),VE(0.0)) === extract_data(SVec{4,Float64}(0.0))
@test extract_data(one(SVec{4,Float64})) === (VE(1.0),VE(1.0),VE(1.0),VE(1.0)) === extract_data(SVec{4,Float64}(1.0)) === extract_data(extract_data(SVec{4,Float64}(1.0)))
v = SVec((VE(1.0),VE(2.0),VE(3.0),VE(4.0)))
@test v === SVec{4,Float64}(1, 2, 3, 4) === conj(v) === v'
@test length(v) == 4 == first(size(v))
@test eltype(v) == Float64
for i in 1:4
@test i == v[i]
# @test i === SVec{4,Int}(v)[i] # should use fptosi (ie, vconvert defined in SIMDPirates).
end
@test zero(v) === zero(typeof(v))
@test one(v) === one(typeof(v))
# @test SVec{W32,Float32}(one(SVec{W32,Float64})) === SVec(one(SVec{W32,Float32})) === one(SVec{W32,Float32}) # conversions should be tested in SIMDPirates
@test firstval(v) === firstval(extract_data(v)) === 1.0
@test SVec{1,Int}(1) === SVec{1,Int}((Core.VecElement(1),))
end
@testset "alignment.jl" begin
@test all(i -> VectorizationBase.align(i) == VectorizationBase.REGISTER_SIZE, 1:VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.align(i) == 2VectorizationBase.REGISTER_SIZE, 1+VectorizationBase.REGISTER_SIZE:2VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.align(i) == 10VectorizationBase.REGISTER_SIZE, (1:VectorizationBase.REGISTER_SIZE) .+ 9VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.align(reinterpret(Ptr{Cvoid}, i)) == reinterpret(Ptr{Cvoid}, VectorizationBase.REGISTER_SIZE), 1:VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.align(reinterpret(Ptr{Cvoid}, i)) == reinterpret(Ptr{Cvoid}, 2VectorizationBase.REGISTER_SIZE), 1+VectorizationBase.REGISTER_SIZE:2VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.align(reinterpret(Ptr{Cvoid}, i)) == reinterpret(Ptr{Cvoid}, 20VectorizationBase.REGISTER_SIZE), (1:VectorizationBase.REGISTER_SIZE) .+ 19VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.align(i,W32) == VectorizationBase.align(i,Float32) == VectorizationBase.align(i,Int32) == W32*cld(i,W32), 1:VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.align(i,W32) == VectorizationBase.align(i,Float32) == VectorizationBase.align(i,Int32) == W32*cld(i,W32), 1+VectorizationBase.REGISTER_SIZE:2VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.align(i,W32) == VectorizationBase.align(i,Float32) == VectorizationBase.align(i,Int32) == W32*cld(i,W32), (1:VectorizationBase.REGISTER_SIZE) .+ 29VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.align(i,W64) == VectorizationBase.align(i,Float64) == VectorizationBase.align(i,Int64) == W64*cld(i,W64), 1:VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.align(i,W64) == VectorizationBase.align(i,Float64) == VectorizationBase.align(i,Int64) == W64*cld(i,W64), 1+VectorizationBase.REGISTER_SIZE:2VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.align(i,W64) == VectorizationBase.align(i,Float64) == VectorizationBase.align(i,Int64) == W64*cld(i,W64), (1:VectorizationBase.REGISTER_SIZE) .+ 29VectorizationBase.REGISTER_SIZE)
@test reinterpret(Int, VectorizationBase.align(pointer(A))) % VectorizationBase.REGISTER_SIZE === 0
@test all(i -> VectorizationBase.aligntrunc(i) == 0, 0:VectorizationBase.REGISTER_SIZE-1)
@test all(i -> VectorizationBase.aligntrunc(i) == VectorizationBase.REGISTER_SIZE, VectorizationBase.REGISTER_SIZE:2VectorizationBase.REGISTER_SIZE-1)
@test all(i -> VectorizationBase.aligntrunc(i) == 9VectorizationBase.REGISTER_SIZE, (0:VectorizationBase.REGISTER_SIZE-1) .+ 9VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.aligntrunc(i,W32) == VectorizationBase.aligntrunc(i,Float32) == VectorizationBase.aligntrunc(i,Int32) == W32*div(i,W32), 1:VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.aligntrunc(i,W32) == VectorizationBase.aligntrunc(i,Float32) == VectorizationBase.aligntrunc(i,Int32) == W32*div(i,W32), 1+VectorizationBase.REGISTER_SIZE:2VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.aligntrunc(i,W32) == VectorizationBase.aligntrunc(i,Float32) == VectorizationBase.aligntrunc(i,Int32) == W32*div(i,W32), (1:VectorizationBase.REGISTER_SIZE) .+ 29VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.aligntrunc(i,W64) == VectorizationBase.aligntrunc(i,Float64) == VectorizationBase.aligntrunc(i,Int64) == W64*div(i,W64), 1:VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.aligntrunc(i,W64) == VectorizationBase.aligntrunc(i,Float64) == VectorizationBase.aligntrunc(i,Int64) == W64*div(i,W64), 1+VectorizationBase.REGISTER_SIZE:2VectorizationBase.REGISTER_SIZE)
@test all(i -> VectorizationBase.aligntrunc(i,W64) == VectorizationBase.aligntrunc(i,Float64) == VectorizationBase.aligntrunc(i,Int64) == W64*div(i,W64), (1:VectorizationBase.REGISTER_SIZE) .+ 29VectorizationBase.REGISTER_SIZE)
a = Vector{Float64}(undef, 0)
ptr = pointer(a)
@test UInt(VectorizationBase.align(ptr, 1 << 12)) % (1 << 12) == 0
end
@testset "masks.jl" begin
@test Mask{8,UInt8}(0x0f) === @inferred Mask(0x0f)
@test Mask{16,UInt16}(0x0f0f) === @inferred Mask(0x0f0f)
@test Mask{8,UInt8}(0xff) == mask(Val(8), 0)
@test Mask{8,UInt8}(0xff) == mask(Val(8), 8)
@test Mask{8,UInt8}(0xff) == mask(Val(8), 16)
@test Mask{8,UInt8}(0xff) == mask(Val(8), VectorizationBase.Static(0))
@test Mask{16,UInt16}(0xffff) == mask(Val(16), 0)
@test Mask{16,UInt16}(0xffff) == mask(Val(16), 16)
@test Mask{16,UInt16}(0xffff) == mask(Val(16), 32)
@test all(w -> VectorizationBase.mask_type(w) == UInt8, 1:8)
@test all(w -> VectorizationBase.mask_type(w) == UInt16, 9:16)
@test all(w -> VectorizationBase.mask_type(w) == UInt32, 17:32)
@test all(w -> VectorizationBase.mask_type(w) == UInt64, 33:64)
@test all(w -> VectorizationBase.mask_type(w) == UInt128, 65:128)
if VectorizationBase.REGISTER_SIZE == 64 # avx512
@test VectorizationBase.mask_type(Float16) == UInt32
@test VectorizationBase.mask_type(Float32) == UInt16
@test VectorizationBase.mask_type(Float64) == UInt8
@test VectorizationBase.max_mask(Float16) == 0xffffffff # 32
@test VectorizationBase.max_mask(Float32) == 0xffff # 16
@test VectorizationBase.max_mask(Float64) == 0xff # 8
elseif VectorizationBase.REGISTER_SIZE == 32 # avx or avx2
@test VectorizationBase.mask_type(Float16) == UInt16
@test VectorizationBase.mask_type(Float32) == UInt8
@test VectorizationBase.mask_type(Float64) == UInt8
@test VectorizationBase.max_mask(Float16) == 0xffff # 16
@test VectorizationBase.max_mask(Float32) == 0xff # 8
@test VectorizationBase.max_mask(Float64) == 0x0f # 4
elseif VectorizationBase.REGISTER_SIZE == 16 # sse
@test VectorizationBase.mask_type(Float16) == UInt8
@test VectorizationBase.mask_type(Float32) == UInt8
@test VectorizationBase.mask_type(Float64) == UInt8
@test VectorizationBase.max_mask(Float16) == 0xff # 8
@test VectorizationBase.max_mask(Float32) == 0x0f # 4
@test VectorizationBase.max_mask(Float64) == 0x03 # 2
end
@test all(w -> bitstring(VectorizationBase.mask(Val( 8), w)) == reduce(*, ( 8 - i < w ? "1" : "0" for i in 1:8 )), 1:8 )
@test all(w -> bitstring(VectorizationBase.mask(Val(16), w)) == reduce(*, (16 - i < w ? "1" : "0" for i in 1:16)), 1:16)
@test all(w -> VectorizationBase.mask(Float64, w) === VectorizationBase.mask(VectorizationBase.pick_vector_width_val(Float64), w), 1:W64)
end
@testset "number_vectors.jl" begin
# eval(VectorizationBase.num_vector_load_expr(@__MODULE__, :(size(A)), 8)) # doesn't work?
@test VectorizationBase.length_loads(A, Val(8)) == eval(VectorizationBase.num_vector_load_expr(@__MODULE__, :((() -> 13*17)()), 8)) == eval(VectorizationBase.num_vector_load_expr(@__MODULE__, 13*17, 8)) == divrem(length(A), 8)
@test VectorizationBase.size_loads(A,1, Val(8)) == eval(VectorizationBase.num_vector_load_expr(@__MODULE__, :((() -> 13 )()), 8)) == eval(VectorizationBase.num_vector_load_expr(@__MODULE__, 13 , 8)) == divrem(size(A,1), 8)
@test VectorizationBase.size_loads(A,2, Val(8)) == eval(VectorizationBase.num_vector_load_expr(@__MODULE__, :((() -> 17)()), 8)) == eval(VectorizationBase.num_vector_load_expr(@__MODULE__, 17, 8)) == divrem(size(A,2), 8)
end
@testset "vector_width.jl" begin
@test all(VectorizationBase.ispow2, 0:1)
@test all(i -> !any(VectorizationBase.ispow2, 1+(1 << (i-1)):(1 << i)-1 ) && VectorizationBase.ispow2(1 << i), 2:9)
@test all(i -> VectorizationBase.intlog2(1 << i) == i, 0:(Int == Int64 ? 53 : 30))
FTypes = (Float16, Float32, Float64)
Wv = ntuple(i -> VectorizationBase.REGISTER_SIZE >> i, Val(3))
for (T, N) in zip(FTypes, Wv)
W, Wshift = VectorizationBase.pick_vector_width_shift(:IGNORE_ME, T)
@test W == 1 << Wshift == VectorizationBase.pick_vector_width(T) == N == VectorizationBase.pick_vector_width(:IGNORE_ME, T)
@test Vec{W,T} == VectorizationBase.pick_vector(Val(W), T) == VectorizationBase.pick_vector(T)
@test W == VectorizationBase.pick_vector_width(Val(W), T)
@test Val(W) === VectorizationBase.pick_vector_width_val(Val(W), T) == VectorizationBase.pick_vector_width_val(T)
while true
W >>= 1
W == 0 && break
W2, Wshift2 = VectorizationBase.pick_vector_width_shift(W, T)
@test W2 == 1 << Wshift2 == VectorizationBase.pick_vector_width(W, T) == VectorizationBase.pick_vector_width(Val(W),T) == W
@test Val(W) === VectorizationBase.pick_vector_width_val(Val(W), T)
for n in W+1:2W
W3, Wshift3 = VectorizationBase.pick_vector_width_shift(n, T)
@test W2 << 1 == W3 == 1 << (Wshift2+1) == 1 << Wshift3 == VectorizationBase.pick_vector_width(n, T) == VectorizationBase.pick_vector_width(Val(n),T) == W << 1
@test VectorizationBase.pick_vector(Val(W), T) == VectorizationBase.pick_vector(W, T) == Vec{W,T}
end
end
end
@test all(i -> VectorizationBase.nextpow2(i) == i, 0:2)
for j in 1:10
l, u = (1<<j)+1, 1<<(j+1)
@test all(i -> VectorizationBase.nextpow2(i) == u, l:u)
end
end
@testset "StridedPointer" begin
A = reshape(collect(Float64(0):Float64(63)), (16, 4))
ptr_A = pointer(A)
vA = VectorizationBase.stridedpointer(A)
Att = copy(A')'
vAtt = VectorizationBase.stridedpointer(Att)
@test eltype(vA) == Float64
@test Base.unsafe_convert(Ptr{Float64}, vA) === ptr_A === pointer(vA)
@test vA == VectorizationBase.stridedpointer(vA)
@test all(i -> A[i+1] === VectorizationBase.vload(ptr_A + 8i) === VectorizationBase.vload(vA, (i,)) === Float64(i), 0:15)
VectorizationBase.vstore!(vA, 99.9, (3,))
@test 99.9 === VectorizationBase.vload(ptr_A + 8*3) === VectorizationBase.vload(vA, (VectorizationBase.Static(3),)) === VectorizationBase.vload(vA, (3,0)) === A[4,1]
VectorizationBase.vstore!(vAtt, 99.9, (3,1))
@test 99.9 === VectorizationBase.vload(vAtt, (3,1)) === VectorizationBase.vload(vAtt, (VectorizationBase.Static(3),1)) === Att[4,2]
VectorizationBase.vnoaliasstore!(ptr_A+8*4, 999.9)
@test 999.9 === VectorizationBase.vload(ptr_A + 8*4) === VectorizationBase.vload(pointer(vA), 4*sizeof(eltype(A))) === VectorizationBase.vload(vA, (4,))
@test vload(vA, (7,2)) == vload(vAtt, (7,2)) == A[8,3]
@test vload(VectorizationBase.subsetview(vA, Val(1), 7), (2,)) == vload(VectorizationBase.subsetview(vAtt, Val(1), 7), (2,)) == A[8,3]
@test vload(VectorizationBase.subsetview(vA, Val(2), 2), (7,)) == vload(VectorizationBase.subsetview(vAtt, Val(2), 2), (7,)) == A[8,3]
@test vload(VectorizationBase.double_index(vA, Val(0), Val(1)), (2,)) == vload(VectorizationBase.double_index(vA, Val(0), Val(1)), (VectorizationBase.Static(2),)) == A[3,3]
@test vload(VectorizationBase.double_index(vAtt, Val(0), Val(1)), (1,)) == vload(VectorizationBase.double_index(vAtt, Val(0), Val(1)), (VectorizationBase.Static(1),)) == A[2,2]
B = rand(5, 5)
vB = VectorizationBase.stridedpointer(B)
@test vB[1, 2] == B[2, 3] == vload(VectorizationBase.stridedpointer(B, 2, 3))
@test vB[3] == B[4] == vload(VectorizationBase.stridedpointer(B, 4))
@test vload(SVec{4,Float64}, vB) == SVec{4,Float64}(ntuple(i->B[i], Val(4)))
end
end
| 69.480663
| 227
| 0.710083
|
[
"@testset \"VectorizationBase.jl\" begin\n # Write your own tests here.\n@test isempty(detect_unbound_args(VectorizationBase))\n\n@test first(A) === A[1]\n@testset \"Struct-Wrapped Vec\" begin\n@test extract_data(zero(SVec{4,Float64})) === (VE(0.0),VE(0.0),VE(0.0),VE(0.0)) === extract_data(SVec{4,Float64}(0.0))\n@test extract_data(one(SVec{4,Float64})) === (VE(1.0),VE(1.0),VE(1.0),VE(1.0)) === extract_data(SVec{4,Float64}(1.0)) === extract_data(extract_data(SVec{4,Float64}(1.0)))\nv = SVec((VE(1.0),VE(2.0),VE(3.0),VE(4.0)))\n@test v === SVec{4,Float64}(1, 2, 3, 4) === conj(v) === v'\n@test length(v) == 4 == first(size(v))\n@test eltype(v) == Float64\nfor i in 1:4\n @test i == v[i]\n # @test i === SVec{4,Int}(v)[i] # should use fptosi (ie, vconvert defined in SIMDPirates).\nend\n@test zero(v) === zero(typeof(v))\n@test one(v) === one(typeof(v))\n# @test SVec{W32,Float32}(one(SVec{W32,Float64})) === SVec(one(SVec{W32,Float32})) === one(SVec{W32,Float32}) # conversions should be tested in SIMDPirates\n @test firstval(v) === firstval(extract_data(v)) === 1.0\n @test SVec{1,Int}(1) === SVec{1,Int}((Core.VecElement(1),))\nend\n\n@testset \"alignment.jl\" begin\n\n@test all(i -> VectorizationBase.align(i) == VectorizationBase.REGISTER_SIZE, 1:VectorizationBase.REGISTER_SIZE)\n@test all(i -> VectorizationBase.align(i) == 2VectorizationBase.REGISTER_SIZE, 1+VectorizationBase.REGISTER_SIZE:2VectorizationBase.REGISTER_SIZE)\n@test all(i -> VectorizationBase.align(i) == 10VectorizationBase.REGISTER_SIZE, (1:VectorizationBase.REGISTER_SIZE) .+ 9VectorizationBase.REGISTER_SIZE)\n\n@test all(i -> VectorizationBase.align(reinterpret(Ptr{Cvoid}, i)) == reinterpret(Ptr{Cvoid}, VectorizationBase.REGISTER_SIZE), 1:VectorizationBase.REGISTER_SIZE)\n@test all(i -> VectorizationBase.align(reinterpret(Ptr{Cvoid}, i)) == reinterpret(Ptr{Cvoid}, 2VectorizationBase.REGISTER_SIZE), 1+VectorizationBase.REGISTER_SIZE:2VectorizationBase.REGISTER_SIZE)\n@test all(i -> VectorizationBase.align(reinterpret(Ptr{Cvoid}, i)) == reinterpret(Ptr{Cvoid}, 20VectorizationBase.REGISTER_SIZE), (1:VectorizationBase.REGISTER_SIZE) .+ 19VectorizationBase.REGISTER_SIZE)\n\n@test all(i -> VectorizationBase.align(i,W32) == VectorizationBase.align(i,Float32) == VectorizationBase.align(i,Int32) == W32*cld(i,W32), 1:VectorizationBase.REGISTER_SIZE)\n@test all(i -> VectorizationBase.align(i,W32) == VectorizationBase.align(i,Float32) == VectorizationBase.align(i,Int32) == W32*cld(i,W32), 1+VectorizationBase.REGISTER_SIZE:2VectorizationBase.REGISTER_SIZE)\n@test all(i -> VectorizationBase.align(i,W32) == VectorizationBase.align(i,Float32) == VectorizationBase.align(i,Int32) == W32*cld(i,W32), (1:VectorizationBase.REGISTER_SIZE) .+ 29VectorizationBase.REGISTER_SIZE)\n\n@test all(i -> VectorizationBase.align(i,W64) == VectorizationBase.align(i,Float64) == VectorizationBase.align(i,Int64) == W64*cld(i,W64), 1:VectorizationBase.REGISTER_SIZE)\n@test all(i -> VectorizationBase.align(i,W64) == VectorizationBase.align(i,Float64) == VectorizationBase.align(i,Int64) == W64*cld(i,W64), 1+VectorizationBase.REGISTER_SIZE:2VectorizationBase.REGISTER_SIZE)\n@test all(i -> VectorizationBase.align(i,W64) == VectorizationBase.align(i,Float64) == VectorizationBase.align(i,Int64) == W64*cld(i,W64), (1:VectorizationBase.REGISTER_SIZE) .+ 29VectorizationBase.REGISTER_SIZE)\n\n@test reinterpret(Int, VectorizationBase.align(pointer(A))) % VectorizationBase.REGISTER_SIZE === 0\n\n@test all(i -> VectorizationBase.aligntrunc(i) == 0, 0:VectorizationBase.REGISTER_SIZE-1)\n@test all(i -> VectorizationBase.aligntrunc(i) == VectorizationBase.REGISTER_SIZE, VectorizationBase.REGISTER_SIZE:2VectorizationBase.REGISTER_SIZE-1)\n@test all(i -> VectorizationBase.aligntrunc(i) == 9VectorizationBase.REGISTER_SIZE, (0:VectorizationBase.REGISTER_SIZE-1) .+ 9VectorizationBase.REGISTER_SIZE)\n\n@test all(i -> VectorizationBase.aligntrunc(i,W32) == VectorizationBase.aligntrunc(i,Float32) == VectorizationBase.aligntrunc(i,Int32) == W32*div(i,W32), 1:VectorizationBase.REGISTER_SIZE)\n@test all(i -> VectorizationBase.aligntrunc(i,W32) == VectorizationBase.aligntrunc(i,Float32) == VectorizationBase.aligntrunc(i,Int32) == W32*div(i,W32), 1+VectorizationBase.REGISTER_SIZE:2VectorizationBase.REGISTER_SIZE)\n@test all(i -> VectorizationBase.aligntrunc(i,W32) == VectorizationBase.aligntrunc(i,Float32) == VectorizationBase.aligntrunc(i,Int32) == W32*div(i,W32), (1:VectorizationBase.REGISTER_SIZE) .+ 29VectorizationBase.REGISTER_SIZE)\n\n@test all(i -> VectorizationBase.aligntrunc(i,W64) == VectorizationBase.aligntrunc(i,Float64) == VectorizationBase.aligntrunc(i,Int64) == W64*div(i,W64), 1:VectorizationBase.REGISTER_SIZE)\n@test all(i -> VectorizationBase.aligntrunc(i,W64) == VectorizationBase.aligntrunc(i,Float64) == VectorizationBase.aligntrunc(i,Int64) == W64*div(i,W64), 1+VectorizationBase.REGISTER_SIZE:2VectorizationBase.REGISTER_SIZE)\n@test all(i -> VectorizationBase.aligntrunc(i,W64) == VectorizationBase.aligntrunc(i,Float64) == VectorizationBase.aligntrunc(i,Int64) == W64*div(i,W64), (1:VectorizationBase.REGISTER_SIZE) .+ 29VectorizationBase.REGISTER_SIZE)\n\na = Vector{Float64}(undef, 0)\nptr = pointer(a)\n@test UInt(VectorizationBase.align(ptr, 1 << 12)) % (1 << 12) == 0\nend\n\n @testset \"masks.jl\" begin\n @test Mask{8,UInt8}(0x0f) === @inferred Mask(0x0f)\n @test Mask{16,UInt16}(0x0f0f) === @inferred Mask(0x0f0f)\n @test Mask{8,UInt8}(0xff) == mask(Val(8), 0)\n @test Mask{8,UInt8}(0xff) == mask(Val(8), 8)\n @test Mask{8,UInt8}(0xff) == mask(Val(8), 16)\n @test Mask{8,UInt8}(0xff) == mask(Val(8), VectorizationBase.Static(0))\n @test Mask{16,UInt16}(0xffff) == mask(Val(16), 0)\n @test Mask{16,UInt16}(0xffff) == mask(Val(16), 16)\n @test Mask{16,UInt16}(0xffff) == mask(Val(16), 32)\n@test all(w -> VectorizationBase.mask_type(w) == UInt8, 1:8)\n@test all(w -> VectorizationBase.mask_type(w) == UInt16, 9:16)\n@test all(w -> VectorizationBase.mask_type(w) == UInt32, 17:32)\n@test all(w -> VectorizationBase.mask_type(w) == UInt64, 33:64)\n@test all(w -> VectorizationBase.mask_type(w) == UInt128, 65:128)\nif VectorizationBase.REGISTER_SIZE == 64 # avx512\n @test VectorizationBase.mask_type(Float16) == UInt32\n @test VectorizationBase.mask_type(Float32) == UInt16\n @test VectorizationBase.mask_type(Float64) == UInt8\n @test VectorizationBase.max_mask(Float16) == 0xffffffff # 32\n @test VectorizationBase.max_mask(Float32) == 0xffff # 16\n @test VectorizationBase.max_mask(Float64) == 0xff # 8\nelseif VectorizationBase.REGISTER_SIZE == 32 # avx or avx2\n @test VectorizationBase.mask_type(Float16) == UInt16\n @test VectorizationBase.mask_type(Float32) == UInt8\n @test VectorizationBase.mask_type(Float64) == UInt8\n @test VectorizationBase.max_mask(Float16) == 0xffff # 16\n @test VectorizationBase.max_mask(Float32) == 0xff # 8\n @test VectorizationBase.max_mask(Float64) == 0x0f # 4\nelseif VectorizationBase.REGISTER_SIZE == 16 # sse\n @test VectorizationBase.mask_type(Float16) == UInt8\n @test VectorizationBase.mask_type(Float32) == UInt8\n @test VectorizationBase.mask_type(Float64) == UInt8\n @test VectorizationBase.max_mask(Float16) == 0xff # 8\n @test VectorizationBase.max_mask(Float32) == 0x0f # 4\n @test VectorizationBase.max_mask(Float64) == 0x03 # 2\nend\n@test all(w -> bitstring(VectorizationBase.mask(Val( 8), w)) == reduce(*, ( 8 - i < w ? \"1\" : \"0\" for i in 1:8 )), 1:8 )\n@test all(w -> bitstring(VectorizationBase.mask(Val(16), w)) == reduce(*, (16 - i < w ? \"1\" : \"0\" for i in 1:16)), 1:16)\n@test all(w -> VectorizationBase.mask(Float64, w) === VectorizationBase.mask(VectorizationBase.pick_vector_width_val(Float64), w), 1:W64)\nend\n\n@testset \"number_vectors.jl\" begin\n# eval(VectorizationBase.num_vector_load_expr(@__MODULE__, :(size(A)), 8)) # doesn't work?\n@test VectorizationBase.length_loads(A, Val(8)) == eval(VectorizationBase.num_vector_load_expr(@__MODULE__, :((() -> 13*17)()), 8)) == eval(VectorizationBase.num_vector_load_expr(@__MODULE__, 13*17, 8)) == divrem(length(A), 8)\n@test VectorizationBase.size_loads(A,1, Val(8)) == eval(VectorizationBase.num_vector_load_expr(@__MODULE__, :((() -> 13 )()), 8)) == eval(VectorizationBase.num_vector_load_expr(@__MODULE__, 13 , 8)) == divrem(size(A,1), 8)\n@test VectorizationBase.size_loads(A,2, Val(8)) == eval(VectorizationBase.num_vector_load_expr(@__MODULE__, :((() -> 17)()), 8)) == eval(VectorizationBase.num_vector_load_expr(@__MODULE__, 17, 8)) == divrem(size(A,2), 8)\nend\n\n@testset \"vector_width.jl\" begin\n@test all(VectorizationBase.ispow2, 0:1)\n@test all(i -> !any(VectorizationBase.ispow2, 1+(1 << (i-1)):(1 << i)-1 ) && VectorizationBase.ispow2(1 << i), 2:9)\n@test all(i -> VectorizationBase.intlog2(1 << i) == i, 0:(Int == Int64 ? 53 : 30))\nFTypes = (Float16, Float32, Float64)\nWv = ntuple(i -> VectorizationBase.REGISTER_SIZE >> i, Val(3))\nfor (T, N) in zip(FTypes, Wv)\n W, Wshift = VectorizationBase.pick_vector_width_shift(:IGNORE_ME, T)\n @test W == 1 << Wshift == VectorizationBase.pick_vector_width(T) == N == VectorizationBase.pick_vector_width(:IGNORE_ME, T)\n @test Vec{W,T} == VectorizationBase.pick_vector(Val(W), T) == VectorizationBase.pick_vector(T)\n @test W == VectorizationBase.pick_vector_width(Val(W), T)\n @test Val(W) === VectorizationBase.pick_vector_width_val(Val(W), T) == VectorizationBase.pick_vector_width_val(T)\n while true\n W >>= 1\n W == 0 && break\n W2, Wshift2 = VectorizationBase.pick_vector_width_shift(W, T)\n @test W2 == 1 << Wshift2 == VectorizationBase.pick_vector_width(W, T) == VectorizationBase.pick_vector_width(Val(W),T) == W\n @test Val(W) === VectorizationBase.pick_vector_width_val(Val(W), T)\n for n in W+1:2W\n W3, Wshift3 = VectorizationBase.pick_vector_width_shift(n, T)\n @test W2 << 1 == W3 == 1 << (Wshift2+1) == 1 << Wshift3 == VectorizationBase.pick_vector_width(n, T) == VectorizationBase.pick_vector_width(Val(n),T) == W << 1\n @test VectorizationBase.pick_vector(Val(W), T) == VectorizationBase.pick_vector(W, T) == Vec{W,T}\n end\n end\nend\n\n@test all(i -> VectorizationBase.nextpow2(i) == i, 0:2)\nfor j in 1:10\n l, u = (1<<j)+1, 1<<(j+1)\n @test all(i -> VectorizationBase.nextpow2(i) == u, l:u)\nend\n\nend\n\n@testset \"StridedPointer\" begin\nA = reshape(collect(Float64(0):Float64(63)), (16, 4))\nptr_A = pointer(A)\nvA = VectorizationBase.stridedpointer(A)\nAtt = copy(A')'\nvAtt = VectorizationBase.stridedpointer(Att)\n@test eltype(vA) == Float64\n@test Base.unsafe_convert(Ptr{Float64}, vA) === ptr_A === pointer(vA)\n@test vA == VectorizationBase.stridedpointer(vA)\n@test all(i -> A[i+1] === VectorizationBase.vload(ptr_A + 8i) === VectorizationBase.vload(vA, (i,)) === Float64(i), 0:15)\nVectorizationBase.vstore!(vA, 99.9, (3,))\n@test 99.9 === VectorizationBase.vload(ptr_A + 8*3) === VectorizationBase.vload(vA, (VectorizationBase.Static(3),)) === VectorizationBase.vload(vA, (3,0)) === A[4,1]\nVectorizationBase.vstore!(vAtt, 99.9, (3,1))\n@test 99.9 === VectorizationBase.vload(vAtt, (3,1)) === VectorizationBase.vload(vAtt, (VectorizationBase.Static(3),1)) === Att[4,2]\nVectorizationBase.vnoaliasstore!(ptr_A+8*4, 999.9)\n@test 999.9 === VectorizationBase.vload(ptr_A + 8*4) === VectorizationBase.vload(pointer(vA), 4*sizeof(eltype(A))) === VectorizationBase.vload(vA, (4,))\n@test vload(vA, (7,2)) == vload(vAtt, (7,2)) == A[8,3]\n@test vload(VectorizationBase.subsetview(vA, Val(1), 7), (2,)) == vload(VectorizationBase.subsetview(vAtt, Val(1), 7), (2,)) == A[8,3]\n@test vload(VectorizationBase.subsetview(vA, Val(2), 2), (7,)) == vload(VectorizationBase.subsetview(vAtt, Val(2), 2), (7,)) == A[8,3]\n @test vload(VectorizationBase.double_index(vA, Val(0), Val(1)), (2,)) == vload(VectorizationBase.double_index(vA, Val(0), Val(1)), (VectorizationBase.Static(2),)) == A[3,3]\n @test vload(VectorizationBase.double_index(vAtt, Val(0), Val(1)), (1,)) == vload(VectorizationBase.double_index(vAtt, Val(0), Val(1)), (VectorizationBase.Static(1),)) == A[2,2]\n B = rand(5, 5)\nvB = VectorizationBase.stridedpointer(B)\n@test vB[1, 2] == B[2, 3] == vload(VectorizationBase.stridedpointer(B, 2, 3))\n@test vB[3] == B[4] == vload(VectorizationBase.stridedpointer(B, 4))\n@test vload(SVec{4,Float64}, vB) == SVec{4,Float64}(ntuple(i->B[i], Val(4)))\nend\n\nend"
] |
f75e8ca096e7f649f1fb984ebc8212dddaffd164
| 268
|
jl
|
Julia
|
test/runtests.jl
|
adknudson/MvSim.jl
|
6c3085289a5e23441f5f0db90f2b3cbbb9b49afc
|
[
"MIT"
] | 1
|
2021-09-12T12:27:15.000Z
|
2021-09-12T12:27:15.000Z
|
test/runtests.jl
|
adknudson/MvSim.jl
|
6c3085289a5e23441f5f0db90f2b3cbbb9b49afc
|
[
"MIT"
] | 15
|
2020-07-08T20:07:03.000Z
|
2021-01-16T01:56:40.000Z
|
test/runtests.jl
|
adknudson/bigsimr.jl
|
1843a0607bcaee9b7724842df22aa42e176c910c
|
[
"MIT"
] | null | null | null |
using Test
const tests = [
"Correlation",
"PearsonMatching",
"GeneralizedSDistribution",
"RandomVector",
"Utilities"
]
printstyled("Running tests:\n", color=:blue)
for t in tests
@testset "Test $t" begin
include("$t.jl")
end
end
| 14.888889
| 44
| 0.623134
|
[
"@testset \"Test $t\" begin\n include(\"$t.jl\")\n end"
] |
f75e9ed559b23b57b9c1c5ad93fe1247c5639358
| 93
|
jl
|
Julia
|
test/runtests.jl
|
csimal/LazyGraphs.jl
|
d7b70b4110028fd1f29364298ca28ea3fabccfc2
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
csimal/LazyGraphs.jl
|
d7b70b4110028fd1f29364298ca28ea3fabccfc2
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
csimal/LazyGraphs.jl
|
d7b70b4110028fd1f29364298ca28ea3fabccfc2
|
[
"MIT"
] | null | null | null |
using LazyGraphs
using Test
@testset "LazyGraphs.jl" begin
# Write your tests here.
end
| 13.285714
| 30
| 0.741935
|
[
"@testset \"LazyGraphs.jl\" begin\n # Write your tests here.\nend"
] |
f75f0499a04fd3b597d5999efd1ddb12b0f42e8f
| 845
|
jl
|
Julia
|
test/Dynamics/mdef.jl
|
NQCD/NQCDynamics.jl
|
bf7f0ac5105aab72972cce4cd1f313e63878f474
|
[
"MIT"
] | 16
|
2022-01-17T14:34:39.000Z
|
2022-03-24T12:11:48.000Z
|
test/Dynamics/mdef.jl
|
NQCD/NonadiabaticMolecularDynamics.jl
|
491937e0878f15881201e7d637235a5e7f6feb6d
|
[
"MIT"
] | 37
|
2021-08-18T11:59:08.000Z
|
2022-01-02T14:32:58.000Z
|
test/Dynamics/mdef.jl
|
NQCD/NonadiabaticMolecularDynamics.jl
|
491937e0878f15881201e7d637235a5e7f6feb6d
|
[
"MIT"
] | 1
|
2022-02-01T16:00:02.000Z
|
2022-02-01T16:00:02.000Z
|
using Test
using NQCDynamics
using Unitful
using UnitfulAtomic
using RecursiveArrayTools: ArrayPartition
using LinearAlgebra: diag
using ComponentArrays
atoms = Atoms([:H, :H])
model = CompositeFrictionModel(Free(), ConstantFriction(1, atoms.masses[1]))
sim = Simulation{MDEF}(atoms, model; temperature=10u"K")
v = zeros(size(sim))
r = randn(size(sim))
u = ComponentVector(v=v, r=r)
du = zero(u)
@testset "friction!" begin
gtmp = zeros(length(r), length(r))
NQCDynamics.DynamicsMethods.ClassicalMethods.friction!(gtmp, r, sim, 0.0)
@test all(diag(gtmp) .≈ 1.0)
end
sol = run_trajectory(u, (0.0, 100.0), sim; dt=1)
@test sol.u[1] ≈ u
f(t) = 100u"K"*exp(-ustrip(t))
model = CompositeFrictionModel(Harmonic(), RandomFriction(1))
sim = Simulation{MDEF}(atoms, model; temperature=f)
sol = run_trajectory(u, (0.0, 100.0), sim; dt=1)
| 27.258065
| 77
| 0.711243
|
[
"@testset \"friction!\" begin\n gtmp = zeros(length(r), length(r))\n NQCDynamics.DynamicsMethods.ClassicalMethods.friction!(gtmp, r, sim, 0.0)\n @test all(diag(gtmp) .≈ 1.0)\nend"
] |
f75fb5e4074eacc9a5b14eb26f2d6e91e8814175
| 1,238
|
jl
|
Julia
|
test/conservation.jl
|
gvn22/ZonalFlow.jl
|
3ebfdd1d172f97321df13781239da28597137361
|
[
"MIT"
] | 3
|
2021-03-26T10:51:38.000Z
|
2022-02-10T03:36:34.000Z
|
test/conservation.jl
|
gvn22/ZonalFlow.jl
|
3ebfdd1d172f97321df13781239da28597137361
|
[
"MIT"
] | 17
|
2020-10-27T12:11:31.000Z
|
2021-10-19T14:54:44.000Z
|
test/conservation.jl
|
gvn22/ZonalFlow.jl
|
3ebfdd1d172f97321df13781239da28597137361
|
[
"MIT"
] | 1
|
2021-04-10T12:18:54.000Z
|
2021-04-10T12:18:54.000Z
|
using ZonalFlow
using Test
domain = Domain(extent=(2π,2π),res=(5,5));
coeffs = Coefficients(Ω=2π,θ=0.0,μ=0.0,ν=0.0,ν₄=1.0,linear=true);
forcing = Stochastic(kf=3,dk=1,ε=0.0);
prob = BetaPlane(domain,coeffs,forcing);
tspan = (0.0,1000.0);
tsargs = (
dt=0.001,
adaptive=false,
progress=true,
progress_steps=100000,
save_everystep=false,
saveat=500
);
eqs = [NL(),CE2()];
eqs = append!(eqs,[GQL(Λ=l) for l=0:prob.d.nx-1])
eqs = append!(eqs,[GCE2(Λ=l) for l=0:prob.d.nx-1])
sols = integrate(prob,eqs,tspan;tsargs...);
@testset "Linear Equations" begin
for sol in sols
E,Z = energy(length(prob.d)...,size(prob.d)...,sol.t,sol.u);
@test E[1] == E[end]
@test Z[1] == Z[end]
end
end
coeffs = Coefficients(Ω=2π,θ=0.0,μ=0.0,ν=0.0,ν₄=1.0,linear=false);
prob = BetaPlane(domain,coeffs,forcing);
sols = integrate(prob,eqs,tspan;tsargs...);
@testset "Nonlinear Equations" begin
for sol in sols
E,Z = energy(length(prob.d)...,size(prob.d)...,sol.t,sol.u);
@test E[1] == E[end]
@test Z[1] == Z[end]
end
end
| 28.790698
| 76
| 0.534733
|
[
"@testset \"Linear Equations\" begin\n for sol in sols\n E,Z = energy(length(prob.d)...,size(prob.d)...,sol.t,sol.u);\n @test E[1] == E[end]\n @test Z[1] == Z[end]\n end\nend",
"@testset \"Nonlinear Equations\" begin\n for sol in sols\n E,Z = energy(length(prob.d)...,size(prob.d)...,sol.t,sol.u);\n @test E[1] == E[end]\n @test Z[1] == Z[end]\n end\nend"
] |
f76003909b89eb5031185e7af51a319b12fea507
| 1,863
|
jl
|
Julia
|
test/models/m1010/m1010.jl
|
rokkuran/DSGE.jl
|
9e73c250fe477f941a0e49cff82a808f16048b23
|
[
"BSD-3-Clause"
] | null | null | null |
test/models/m1010/m1010.jl
|
rokkuran/DSGE.jl
|
9e73c250fe477f941a0e49cff82a808f16048b23
|
[
"BSD-3-Clause"
] | null | null | null |
test/models/m1010/m1010.jl
|
rokkuran/DSGE.jl
|
9e73c250fe477f941a0e49cff82a808f16048b23
|
[
"BSD-3-Clause"
] | 1
|
2020-01-08T12:10:44.000Z
|
2020-01-08T12:10:44.000Z
|
using DSGE
using Test
path = dirname(@__FILE__)
### Model
model = Model1010("ss18")
### Parameters
@testset "Test parameter bounds checking" begin
for θ in model.parameters
@test isa(θ, AbstractParameter)
if !θ.fixed
(left, right) = θ.valuebounds
@test left < θ.value < right
end
end
end
### Model indices
@testset "Checking model indices" begin
# Endogenous states
endo = model.endogenous_states
@test length(endo) == 73
@test endo[:Ez_t] == 61
# Exogenous shocks
exo = model.exogenous_shocks
@test length(exo) == 29
@test exo[:corepce_sh] == 19
# Expectation shocks
ex = model.expected_shocks
@test length(ex) == 13
@test ex[:EL_f_sh] == 12
# Equations
eq = model.equilibrium_conditions
@test length(eq) == 73
@test eq[:eq_Ez] == 60
# Additional states
endo_new = model.endogenous_states_augmented
@test length(endo_new) == 18
@test endo_new[:y_t1] == 74
# Observables
obs = model.observables
@test length(obs) == 20
@test obs[:obs_tfp] == 12
end
### Equilibrium conditions
Γ0, Γ1, C, Ψ, Π = eqcond(model)
# Transition and measurement equations
TTT, RRR, CCC = solve(model)
meas = measurement(model, TTT, RRR, CCC)
### Pseudo-measurement equation
pseudo_meas = pseudo_measurement(model, TTT, RRR, CCC)
@testset "Check eqcond and state-space dimensions" begin
# Matrices are of expected dimensions
@test size(Γ0) == (73, 73)
@test size(Γ1) == (73, 73)
@test size(C) == (73,)
@test size(Ψ) == (73, 29)
@test size(Π) == (73, 13)
@test size(meas[:ZZ]) == (20,91)
@test size(meas[:DD]) == (20,)
@test size(meas[:QQ]) == (29,29)
@test size(meas[:EE]) == (20,20)
@test size(TTT) == (91,91)
@test size(RRR) == (91,29)
@test size(CCC) == (91,)
end
| 22.445783
| 56
| 0.610843
|
[
"@testset \"Test parameter bounds checking\" begin\n for θ in model.parameters\n @test isa(θ, AbstractParameter)\n if !θ.fixed\n (left, right) = θ.valuebounds\n @test left < θ.value < right\n end\n end\nend",
"@testset \"Checking model indices\" begin\n # Endogenous states\n endo = model.endogenous_states\n @test length(endo) == 73\n @test endo[:Ez_t] == 61\n\n # Exogenous shocks\n exo = model.exogenous_shocks\n @test length(exo) == 29\n @test exo[:corepce_sh] == 19\n\n # Expectation shocks\n ex = model.expected_shocks\n @test length(ex) == 13\n @test ex[:EL_f_sh] == 12\n\n # Equations\n eq = model.equilibrium_conditions\n @test length(eq) == 73\n @test eq[:eq_Ez] == 60\n\n # Additional states\n endo_new = model.endogenous_states_augmented\n @test length(endo_new) == 18\n @test endo_new[:y_t1] == 74\n\n # Observables\n obs = model.observables\n @test length(obs) == 20\n @test obs[:obs_tfp] == 12\nend",
"@testset \"Check eqcond and state-space dimensions\" begin\n # Matrices are of expected dimensions\n @test size(Γ0) == (73, 73)\n @test size(Γ1) == (73, 73)\n @test size(C) == (73,)\n @test size(Ψ) == (73, 29)\n @test size(Π) == (73, 13)\n\n @test size(meas[:ZZ]) == (20,91)\n @test size(meas[:DD]) == (20,)\n @test size(meas[:QQ]) == (29,29)\n @test size(meas[:EE]) == (20,20)\n\n @test size(TTT) == (91,91)\n @test size(RRR) == (91,29)\n @test size(CCC) == (91,)\nend"
] |
f760210800c0cc18dc1c8f574ac26f95cd1ae748
| 1,747
|
jl
|
Julia
|
test/test_functionlenses.jl
|
UnofficialJuliaMirrorSnapshots/Setfield.jl-efcf1570-3423-57d1-acb7-fd33fddbac46
|
4536fae5c60fcea2cda4016b770381cfd4e6a774
|
[
"MIT"
] | null | null | null |
test/test_functionlenses.jl
|
UnofficialJuliaMirrorSnapshots/Setfield.jl-efcf1570-3423-57d1-acb7-fd33fddbac46
|
4536fae5c60fcea2cda4016b770381cfd4e6a774
|
[
"MIT"
] | null | null | null |
test/test_functionlenses.jl
|
UnofficialJuliaMirrorSnapshots/Setfield.jl-efcf1570-3423-57d1-acb7-fd33fddbac46
|
4536fae5c60fcea2cda4016b770381cfd4e6a774
|
[
"MIT"
] | null | null | null |
module TestFunctionLenses
using Test
using Setfield
@testset "first" begin
obj = (1, 2.0, '3')
l = @lens first(_)
@test get(obj, l) === 1
@test set(obj, l, "1") === ("1", 2.0, '3')
@test (@set first(obj) = "1") === ("1", 2.0, '3')
obj2 = (a=((b=1,), 2), c=3)
@test (@set first(obj2.a).b = '1') === (a=((b='1',), 2), c=3)
end
@testset "last" begin
obj = (1, 2.0, '3')
l = @lens last(_)
@test get(obj, l) === '3'
@test set(obj, l, '4') === (1, 2.0, '4')
@test (@set last(obj) = '4') === (1, 2.0, '4')
obj2 = (a=(1, (b=2,)), c=3)
@test (@set last(obj2.a).b = '2') === (a=(1, (b='2',)), c=3)
end
@testset "eltype(::Type{<:Array})" begin
obj = Vector{Int}
obj2 = @set eltype(obj) = Float64
@test obj2 === Vector{Float64}
end
@testset "eltype(::Array)" begin
obj = [1, 2, 3]
obj2 = @set eltype(obj) = Float64
@test eltype(obj2) == Float64
@test obj == obj2
end
@testset "(key|val|el)type(::Type{<:Dict})" begin
obj = Dict{Symbol, Int}
@test (@set keytype(obj) = String) === Dict{String, Int}
@test (@set valtype(obj) = String) === Dict{Symbol, String}
@test (@set eltype(obj) = Pair{String, Any}) === Dict{String, Any}
obj2 = Dict{Symbol, Dict{Int, Float64}}
@test (@set keytype(valtype(obj2)) = String) === Dict{Symbol, Dict{String, Float64}}
@test (@set valtype(valtype(obj2)) = String) === Dict{Symbol, Dict{Int, String}}
end
@testset "(key|val|el)type(::Dict)" begin
obj = Dict(1 => 2)
@test typeof(@set keytype(obj) = Float64) === Dict{Float64, Int}
@test typeof(@set valtype(obj) = Float64) === Dict{Int, Float64}
@test typeof(@set eltype(obj) = Pair{UInt, Float64}) === Dict{UInt, Float64}
end
end # module
| 29.610169
| 88
| 0.546079
|
[
"@testset \"first\" begin\n obj = (1, 2.0, '3')\n l = @lens first(_)\n @test get(obj, l) === 1\n @test set(obj, l, \"1\") === (\"1\", 2.0, '3')\n @test (@set first(obj) = \"1\") === (\"1\", 2.0, '3')\n\n obj2 = (a=((b=1,), 2), c=3)\n @test (@set first(obj2.a).b = '1') === (a=((b='1',), 2), c=3)\nend",
"@testset \"last\" begin\n obj = (1, 2.0, '3')\n l = @lens last(_)\n @test get(obj, l) === '3'\n @test set(obj, l, '4') === (1, 2.0, '4')\n @test (@set last(obj) = '4') === (1, 2.0, '4')\n\n obj2 = (a=(1, (b=2,)), c=3)\n @test (@set last(obj2.a).b = '2') === (a=(1, (b='2',)), c=3)\nend",
"@testset \"eltype(::Type{<:Array})\" begin\n obj = Vector{Int}\n obj2 = @set eltype(obj) = Float64\n @test obj2 === Vector{Float64}\nend",
"@testset \"eltype(::Array)\" begin\n obj = [1, 2, 3]\n obj2 = @set eltype(obj) = Float64\n @test eltype(obj2) == Float64\n @test obj == obj2\nend",
"@testset \"(key|val|el)type(::Type{<:Dict})\" begin\n obj = Dict{Symbol, Int}\n @test (@set keytype(obj) = String) === Dict{String, Int}\n @test (@set valtype(obj) = String) === Dict{Symbol, String}\n @test (@set eltype(obj) = Pair{String, Any}) === Dict{String, Any}\n\n obj2 = Dict{Symbol, Dict{Int, Float64}}\n @test (@set keytype(valtype(obj2)) = String) === Dict{Symbol, Dict{String, Float64}}\n @test (@set valtype(valtype(obj2)) = String) === Dict{Symbol, Dict{Int, String}}\nend",
"@testset \"(key|val|el)type(::Dict)\" begin\n obj = Dict(1 => 2)\n @test typeof(@set keytype(obj) = Float64) === Dict{Float64, Int}\n @test typeof(@set valtype(obj) = Float64) === Dict{Int, Float64}\n @test typeof(@set eltype(obj) = Pair{UInt, Float64}) === Dict{UInt, Float64}\nend"
] |
f762232335b00ad4ca076074cf4d778da83868bd
| 1,874
|
jl
|
Julia
|
test/testPartialRangeCrossCorrelations.jl
|
msaroufim/RoME.jl
|
1a34ca9b0012185d342070aab3a6c70bf19b6834
|
[
"MIT"
] | null | null | null |
test/testPartialRangeCrossCorrelations.jl
|
msaroufim/RoME.jl
|
1a34ca9b0012185d342070aab3a6c70bf19b6834
|
[
"MIT"
] | null | null | null |
test/testPartialRangeCrossCorrelations.jl
|
msaroufim/RoME.jl
|
1a34ca9b0012185d342070aab3a6c70bf19b6834
|
[
"MIT"
] | null | null | null |
# see correct result with slanted (narrow) L1 modes at y=+-5. L1 should not be round blobs
# https://github.com/JuliaRobotics/RoME.jl/pull/434#issuecomment-817246038
using RoME
using Test
##
@testset "Test correlation induced by partials" begin
##
# start with an empty factor graph object
N = 200
fg = initfg()
getSolverParams(fg).N = N
getSolverParams(fg).useMsgLikelihoods = true
addVariable!(fg, :x0, Pose2)
addVariable!(fg, :l1, Point2)
addFactor!(fg, [:x0], PriorPose2( MvNormal([0; 0; 0], diagm([0.3;0.3;0.3].^2)) ))
ppr = Pose2Point2Range(MvNormal([7.3], diagm([0.3].^2)))
addFactor!(fg, [:x0; :l1], ppr )
addVariable!(fg, :x1, Pose2)
pp = Pose2Pose2(MvNormal([9.8;0;0.8], diagm([0.3;0.3;0.05].^2)))
ppr = Pose2Point2Range(MvNormal([6.78], diagm([0.3].^2)))
addFactor!(fg, [:x0; :x1], pp )
addFactor!(fg, [:x1; :l1], ppr )
##
tree, smt, hist = solveTree!(fg)
## check that stuff is where it should be
L1_ = getPoints(getBelief(fg, :l1))
@test 0.3*N < sum(L1_[2,:] .< 0)
@test 0.3*N < sum(0 .< L1_[2,:])
L1_n = L1_[:, L1_[2,:] .< 0]
L1_p = L1_[:, 0 .< L1_[2,:]]
mvn = fit(MvNormal, L1_n)
mvp = fit(MvNormal, L1_p)
# check diagonal structure for correlation
@test isapprox(mvn.Σ.mat[1,1], 1.7, atol=1.2)
@test isapprox(mvn.Σ.mat[2,2], 1.7, atol=1.2)
@test isapprox(mvn.Σ.mat[1,2], 1.1, atol=1.2)
@test isapprox(mvp.Σ.mat[1,1], 1.7, atol=1.2)
@test isapprox(mvp.Σ.mat[2,2], 1.7, atol=1.2)
@test isapprox(mvp.Σ.mat[1,2], -1.1, atol=1.2)
# sanity check for symmetry
@test mvn.Σ.mat - mvn.Σ.mat' |> norm < 0.01
# test means in the right location
@test isapprox(mvn.μ[1], 5.4, atol=1.0)
@test isapprox(mvn.μ[2], -4.8, atol=0.75)
@test isapprox(mvp.μ[1], 5.4, atol=1.0)
@test isapprox(mvp.μ[2], 4.8, atol=0.75)
##
end
##
# using RoMEPlotting
# Gadfly.set_default_plot_size(35cm,25cm)
##
# plotSLAM2D(fg)
# plotKDE(fg, :l1, levels=3)
##
| 20.150538
| 91
| 0.642476
|
[
"@testset \"Test correlation induced by partials\" begin\n\n##\n\n# start with an empty factor graph object\nN = 200\nfg = initfg()\ngetSolverParams(fg).N = N\n\ngetSolverParams(fg).useMsgLikelihoods = true\n\naddVariable!(fg, :x0, Pose2)\naddVariable!(fg, :l1, Point2)\naddFactor!(fg, [:x0], PriorPose2( MvNormal([0; 0; 0], diagm([0.3;0.3;0.3].^2)) ))\nppr = Pose2Point2Range(MvNormal([7.3], diagm([0.3].^2)))\naddFactor!(fg, [:x0; :l1], ppr )\n\naddVariable!(fg, :x1, Pose2)\npp = Pose2Pose2(MvNormal([9.8;0;0.8], diagm([0.3;0.3;0.05].^2)))\nppr = Pose2Point2Range(MvNormal([6.78], diagm([0.3].^2)))\naddFactor!(fg, [:x0; :x1], pp )\naddFactor!(fg, [:x1; :l1], ppr )\n\n\n##\n\ntree, smt, hist = solveTree!(fg)\n\n\n## check that stuff is where it should be\n\nL1_ = getPoints(getBelief(fg, :l1))\n\n@test 0.3*N < sum(L1_[2,:] .< 0)\n@test 0.3*N < sum(0 .< L1_[2,:])\n\nL1_n = L1_[:, L1_[2,:] .< 0]\nL1_p = L1_[:, 0 .< L1_[2,:]]\n\nmvn = fit(MvNormal, L1_n)\nmvp = fit(MvNormal, L1_p)\n\n# check diagonal structure for correlation\n@test isapprox(mvn.Σ.mat[1,1], 1.7, atol=1.2)\n@test isapprox(mvn.Σ.mat[2,2], 1.7, atol=1.2)\n@test isapprox(mvn.Σ.mat[1,2], 1.1, atol=1.2)\n\n@test isapprox(mvp.Σ.mat[1,1], 1.7, atol=1.2)\n@test isapprox(mvp.Σ.mat[2,2], 1.7, atol=1.2)\n@test isapprox(mvp.Σ.mat[1,2], -1.1, atol=1.2)\n\n# sanity check for symmetry\n@test mvn.Σ.mat - mvn.Σ.mat' |> norm < 0.01\n\n# test means in the right location\n@test isapprox(mvn.μ[1], 5.4, atol=1.0)\n@test isapprox(mvn.μ[2], -4.8, atol=0.75)\n\n@test isapprox(mvp.μ[1], 5.4, atol=1.0)\n@test isapprox(mvp.μ[2], 4.8, atol=0.75)\n\n##\n\n\n\nend"
] |
f76235022ef2bc45a57772af3fc525f856dce7dc
| 5,615
|
jl
|
Julia
|
test/utility_tests.jl
|
itsdfish/DifferentialEvolutionMCMC.jl
|
3974509006e3df0eef74cf82be71586f2045d421
|
[
"MIT"
] | 11
|
2020-06-22T07:03:08.000Z
|
2022-03-01T06:47:34.000Z
|
test/utility_tests.jl
|
itsdfish/DifferentialEvolutionMCMC.jl
|
3974509006e3df0eef74cf82be71586f2045d421
|
[
"MIT"
] | 40
|
2020-05-28T11:51:19.000Z
|
2022-03-26T11:59:22.000Z
|
test/utility_tests.jl
|
itsdfish/DifferentialEvolutionMCMC.jl
|
3974509006e3df0eef74cf82be71586f2045d421
|
[
"MIT"
] | null | null | null |
@testset verbose = true "utility tests" begin
@safetestset "Discard Burnin" begin
using DifferentialEvolutionMCMC, Test, Random, Parameters, Distributions
Random.seed!(29542)
N = 10
k = rand(Binomial(N, .5))
data = (N = N,k = k)
prior_loglike(θ) = logpdf(Beta(1, 1), θ)
sample_prior() = rand(Beta(1, 1))
bounds = ((0,1),)
function loglike(data, θ)
return logpdf(Binomial(data.N, θ), data.k)
end
names = (:θ,)
model = DEModel(;
sample_prior,
prior_loglike,
loglike,
data,
names
)
burnin = 1500
n_iter = 3000
de = DE(; sample_prior, Np=4, bounds, burnin, discard_burnin=false)
chains = sample(model, de, n_iter)
@test length(chains) == n_iter
de = DE(; sample_prior, Np=4, bounds, burnin)
chains = sample(model, de, n_iter)
@test length(chains) == burnin
end
@safetestset "reset!" begin
using DifferentialEvolutionMCMC, Test
import DifferentialEvolutionMCMC: reset!
p1 = Particle(Θ = [[.7,.5,.1],.4,.6])
p2 = Particle(Θ = [[.9,.8,.5],.7,.8])
idx = [[true,false,false],false,true]
reset!(p1, p2, idx)
@test p1.Θ[1][1] ≠ p2.Θ[1][1]
@test p1.Θ[1][2] == p2.Θ[1][2]
@test p1.Θ[1][3] == p2.Θ[1][3]
@test p1.Θ[2] == p2.Θ[2]
@test p1.Θ[3] ≠ p2.Θ[3]
p1 = Particle(Θ = [[.7 .5;.1 .3],.4,.6])
p2 = Particle(Θ = [[.9 .8;.5 .2],.7,.8])
idx = [[true false; false true],false,true]
reset!(p1, p2, idx)
@test p1.Θ[1][1,1] ≠ p2.Θ[1][1,1]
@test p1.Θ[1][1,2] == p2.Θ[1][1,2]
@test p1.Θ[1][2,1] == p2.Θ[1][2,1]
@test p1.Θ[1][2,2] ≠ p2.Θ[1][2,2]
@test p1.Θ[1][3] == p2.Θ[1][3]
@test p1.Θ[2] == p2.Θ[2]
@test p1.Θ[3] ≠ p2.Θ[3]
end
@testset "projection" begin
using Test, DifferentialEvolutionMCMC
import DifferentialEvolutionMCMC: project
# for example, see: https://www.youtube.com/watch?v=xSu-0xcRBo8&ab_channel=FireflyLectures
proj(x1, x2) = (x1' * x2) / (x2' * x2) * x2
x1 = [-1.0,4.0]
x2 = [2.0,7.0]
p1 = Particle(Θ = x1)
p2 = Particle(Θ = x2)
p3 = project(p1, p2)
correct = proj(x1, x2)
@test correct ≈ [52/53,182/53]
@test p3.Θ ≈ correct
x1 = [[-1.0,],4.0]
x2 = [[2.0,],7.0]
p1 = Particle(Θ = x1)
p2 = Particle(Θ = x2)
p3 = project(p1, p2)
@test vcat(p3.Θ...) ≈ correct
end
@safetestset "Migration" begin
using DifferentialEvolutionMCMC, Test, Random, Parameters, Distributions
import DifferentialEvolutionMCMC: select_groups, select_particles, shift_particles!, sample_init
Random.seed!(459) #Random.seed!(0451) #
function equal(p1::Particle, p2::Particle)
fields = fieldnames(Particle)
for field in fields
if getfield(p1, field) != getfield(p2, field)
println(field)
return false
end
end
return true
end
N = 10
k = rand(Binomial(N, .5))
data = (N = N,k = k)
prior_loglike(θ) = logpdf(Beta(1, 1), θ)
sample_prior() = rand(Beta(1, 1))
bounds = ((0,1),)
function loglike(data, θ)
return logpdf(Binomial(data.N, θ), data.k)
end
names = (:θ,)
model = DEModel(;
sample_prior,
prior_loglike,
loglike,
data,
names
)
burnin = 1500
n_iter = 3000
de = DE(; sample_prior, Np=4, bounds, burnin, discard_burnin=false)
groups = sample_init(model, de, n_iter)
sub_group = select_groups(de, groups)
c_groups = deepcopy(groups)
c_sub_group = deepcopy(sub_group)
p_idx,particles = select_particles(sub_group)
c_particles = deepcopy(particles)
shift_particles!(sub_group, p_idx, particles)
gidx = 1:length(sub_group)
cidx = circshift(gidx, 1)
cp_idx = circshift(p_idx, 1)
for (i,c,p,cp) in zip(gidx, p_idx, cidx, cp_idx)
@test sub_group[i][c].Θ == c_sub_group[p][cp].Θ
end
ridx = [4,3]
for (i,c,r) in zip(1:2, p_idx[1:2], ridx)
@test sub_group[i][c].Θ == groups[r][c].Θ
end
end
@safetestset "particle operations" begin
using DifferentialEvolutionMCMC, Test, Random, Distributions
Random.seed!(29542)
p1 = Particle(Θ = [1.,2.0])
pr = p1 + 2
@test pr.Θ ≈ [3,4]
p1 = Particle(Θ = [1.,2.0])
pr = p1 * 4
@test pr.Θ ≈ [4,8]
p1 = Particle(Θ = [1.,2.0])
p2 = Particle(Θ = [1.,2.0])
pr = p1 + p2
@test pr.Θ ≈ [2,4]
p1 = Particle(Θ = [1.,2.0])
p2 = Particle(Θ = [1.,2.0])
pr = 3 * (p1 + p2)
@test pr.Θ ≈ [6,12]
p1 = Particle(Θ = [1.,2.0])
p2 = Particle(Θ = [-2.,3.0])
pr = 3 * (p1 - p2)
@test pr.Θ ≈ [9,-3]
p1 = Particle(Θ = [1.,2.0])
p2 = Particle(Θ = [-2.,3.0])
p3 = Particle(Θ = [-2.,3.0])
pr = 3 * (p1 - p2) + p3
@test pr.Θ ≈ [7,0]
p1 = Particle(Θ = [1.,2.0])
b = Uniform(-.1, .1)
pr = p1 + b
@test p1.Θ ≈ pr.Θ atol = .2 # cummulative error
@test p1.Θ ≠ pr.Θ
end
end
| 27.935323
| 104
| 0.488157
|
[
"@testset verbose = true \"utility tests\" begin \n @safetestset \"Discard Burnin\" begin\n using DifferentialEvolutionMCMC, Test, Random, Parameters, Distributions\n Random.seed!(29542)\n N = 10\n k = rand(Binomial(N, .5))\n data = (N = N,k = k)\n\n prior_loglike(θ) = logpdf(Beta(1, 1), θ)\n\n sample_prior() = rand(Beta(1, 1))\n\n bounds = ((0,1),)\n\n function loglike(data, θ)\n return logpdf(Binomial(data.N, θ), data.k)\n end\n\n names = (:θ,)\n\n model = DEModel(; \n sample_prior, \n prior_loglike, \n loglike, \n data,\n names\n )\n\n burnin = 1500\n n_iter = 3000\n\n de = DE(; sample_prior, Np=4, bounds, burnin, discard_burnin=false)\n\n chains = sample(model, de, n_iter)\n @test length(chains) == n_iter\n\n de = DE(; sample_prior, Np=4, bounds, burnin)\n chains = sample(model, de, n_iter)\n @test length(chains) == burnin\n end\n\n @safetestset \"reset!\" begin\n using DifferentialEvolutionMCMC, Test\n import DifferentialEvolutionMCMC: reset!\n\n p1 = Particle(Θ = [[.7,.5,.1],.4,.6])\n p2 = Particle(Θ = [[.9,.8,.5],.7,.8])\n idx = [[true,false,false],false,true]\n reset!(p1, p2, idx)\n\n @test p1.Θ[1][1] ≠ p2.Θ[1][1]\n @test p1.Θ[1][2] == p2.Θ[1][2]\n @test p1.Θ[1][3] == p2.Θ[1][3]\n @test p1.Θ[2] == p2.Θ[2]\n @test p1.Θ[3] ≠ p2.Θ[3]\n\n p1 = Particle(Θ = [[.7 .5;.1 .3],.4,.6])\n p2 = Particle(Θ = [[.9 .8;.5 .2],.7,.8])\n idx = [[true false; false true],false,true]\n reset!(p1, p2, idx)\n\n @test p1.Θ[1][1,1] ≠ p2.Θ[1][1,1]\n @test p1.Θ[1][1,2] == p2.Θ[1][1,2]\n @test p1.Θ[1][2,1] == p2.Θ[1][2,1]\n @test p1.Θ[1][2,2] ≠ p2.Θ[1][2,2]\n @test p1.Θ[1][3] == p2.Θ[1][3]\n @test p1.Θ[2] == p2.Θ[2]\n @test p1.Θ[3] ≠ p2.Θ[3]\n end\n\n @testset \"projection\" begin \n using Test, DifferentialEvolutionMCMC\n import DifferentialEvolutionMCMC: project\n\n # for example, see: https://www.youtube.com/watch?v=xSu-0xcRBo8&ab_channel=FireflyLectures\n proj(x1, x2) = (x1' * x2) / (x2' * x2) * x2\n x1 = [-1.0,4.0]\n x2 = [2.0,7.0]\n p1 = Particle(Θ = x1)\n p2 = Particle(Θ = x2)\n p3 = project(p1, p2)\n correct = proj(x1, x2)\n\n @test correct ≈ [52/53,182/53]\n @test p3.Θ ≈ correct\n\n x1 = [[-1.0,],4.0]\n x2 = [[2.0,],7.0]\n p1 = Particle(Θ = x1)\n p2 = Particle(Θ = x2)\n p3 = project(p1, p2)\n @test vcat(p3.Θ...) ≈ correct\n end\n\n @safetestset \"Migration\" begin\n using DifferentialEvolutionMCMC, Test, Random, Parameters, Distributions\n import DifferentialEvolutionMCMC: select_groups, select_particles, shift_particles!, sample_init\n\n Random.seed!(459) #Random.seed!(0451) # \n\n function equal(p1::Particle, p2::Particle)\n fields = fieldnames(Particle)\n for field in fields\n if getfield(p1, field) != getfield(p2, field)\n println(field)\n return false\n end\n end\n return true\n end\n\n N = 10\n k = rand(Binomial(N, .5))\n data = (N = N,k = k)\n \n prior_loglike(θ) = logpdf(Beta(1, 1), θ)\n\n sample_prior() = rand(Beta(1, 1))\n\n bounds = ((0,1),)\n\n function loglike(data, θ)\n return logpdf(Binomial(data.N, θ), data.k)\n end\n\n names = (:θ,)\n\n model = DEModel(; \n sample_prior, \n prior_loglike, \n loglike, \n data,\n names\n )\n\n burnin = 1500\n n_iter = 3000\n\n de = DE(; sample_prior, Np=4, bounds, burnin, discard_burnin=false)\n\n groups = sample_init(model, de, n_iter)\n sub_group = select_groups(de, groups)\n c_groups = deepcopy(groups)\n c_sub_group = deepcopy(sub_group)\n p_idx,particles = select_particles(sub_group)\n c_particles = deepcopy(particles)\n shift_particles!(sub_group, p_idx, particles)\n gidx = 1:length(sub_group)\n cidx = circshift(gidx, 1)\n cp_idx = circshift(p_idx, 1)\n for (i,c,p,cp) in zip(gidx, p_idx, cidx, cp_idx)\n @test sub_group[i][c].Θ == c_sub_group[p][cp].Θ\n end\n ridx = [4,3] \n for (i,c,r) in zip(1:2, p_idx[1:2], ridx)\n @test sub_group[i][c].Θ == groups[r][c].Θ\n end\n end\n\n @safetestset \"particle operations\" begin\n using DifferentialEvolutionMCMC, Test, Random, Distributions\n Random.seed!(29542)\n\n p1 = Particle(Θ = [1.,2.0])\n pr = p1 + 2\n @test pr.Θ ≈ [3,4]\n\n p1 = Particle(Θ = [1.,2.0])\n pr = p1 * 4\n @test pr.Θ ≈ [4,8]\n\n p1 = Particle(Θ = [1.,2.0])\n p2 = Particle(Θ = [1.,2.0])\n pr = p1 + p2\n @test pr.Θ ≈ [2,4]\n\n p1 = Particle(Θ = [1.,2.0])\n p2 = Particle(Θ = [1.,2.0])\n pr = 3 * (p1 + p2)\n @test pr.Θ ≈ [6,12]\n\n p1 = Particle(Θ = [1.,2.0])\n p2 = Particle(Θ = [-2.,3.0])\n pr = 3 * (p1 - p2)\n @test pr.Θ ≈ [9,-3]\n\n p1 = Particle(Θ = [1.,2.0])\n p2 = Particle(Θ = [-2.,3.0])\n p3 = Particle(Θ = [-2.,3.0])\n pr = 3 * (p1 - p2) + p3\n @test pr.Θ ≈ [7,0]\n\n\n p1 = Particle(Θ = [1.,2.0])\n b = Uniform(-.1, .1)\n pr = p1 + b\n @test p1.Θ ≈ pr.Θ atol = .2 # cummulative error\n @test p1.Θ ≠ pr.Θ\n end\nend"
] |
f763399e181001cf6dcf97bc016af653862993a0
| 1,842
|
jl
|
Julia
|
test/duplicates.jl
|
EarthGoddessDude/DataFrames.jl
|
936d1155414b61d46633417340b86181a8863c8e
|
[
"MIT"
] | 4
|
2020-05-11T18:52:59.000Z
|
2021-05-19T06:32:02.000Z
|
test/duplicates.jl
|
EarthGoddessDude/DataFrames.jl
|
936d1155414b61d46633417340b86181a8863c8e
|
[
"MIT"
] | 1
|
2019-01-14T17:35:31.000Z
|
2019-07-06T23:10:44.000Z
|
test/duplicates.jl
|
EarthGoddessDude/DataFrames.jl
|
936d1155414b61d46633417340b86181a8863c8e
|
[
"MIT"
] | null | null | null |
module TestDuplicates
using Test, DataFrames, CategoricalArrays
const ≅ = isequal
@testset "nonunique" begin
df = DataFrame(a = [1, 2, 3, 3, 4])
udf = DataFrame(a = [1, 2, 3, 4])
@test nonunique(df) == [false, false, false, true, false]
@test udf == unique(df)
unique!(df)
@test df == udf
@test_throws ArgumentError unique(df, true)
pdf = DataFrame(a = CategoricalArray(["a", "a", missing, missing, "b", missing, "a", missing]),
b = CategoricalArray(["a", "b", missing, missing, "b", "a", "a", "a"]))
updf = DataFrame(a = CategoricalArray(["a", "a", missing, "b", missing]),
b = CategoricalArray(["a", "b", missing, "b", "a"]))
@test nonunique(pdf) == [false, false, false, true, false, false, true, true]
@test nonunique(updf) == falses(5)
@test updf ≅ unique(pdf)
unique!(pdf)
@test pdf ≅ updf
@test_throws ArgumentError unique(pdf, true)
df = view(DataFrame(a = [1, 2, 3, 3, 4]), :, :)
udf = DataFrame(a = [1, 2, 3, 4])
@test nonunique(df) == [false, false, false, true, false]
@test udf == unique(df)
@test_throws ArgumentError unique!(df)
@test_throws ArgumentError unique(df, true)
pdf = view(DataFrame(a = CategoricalArray(["a", "a", missing, missing, "b", missing, "a", missing]),
b = CategoricalArray(["a", "b", missing, missing, "b", "a", "a", "a"])), :, :)
updf = DataFrame(a = CategoricalArray(["a", "a", missing, "b", missing]),
b = CategoricalArray(["a", "b", missing, "b", "a"]))
@test nonunique(pdf) == [false, false, false, true, false, false, true, true]
@test nonunique(updf) == falses(5)
@test updf ≅ unique(pdf)
@test_throws ArgumentError unique!(pdf)
@test_throws ArgumentError unique(pdf, true)
end
end # module
| 40.933333
| 105
| 0.579262
|
[
"@testset \"nonunique\" begin\n df = DataFrame(a = [1, 2, 3, 3, 4])\n udf = DataFrame(a = [1, 2, 3, 4])\n @test nonunique(df) == [false, false, false, true, false]\n @test udf == unique(df)\n unique!(df)\n @test df == udf\n @test_throws ArgumentError unique(df, true)\n\n pdf = DataFrame(a = CategoricalArray([\"a\", \"a\", missing, missing, \"b\", missing, \"a\", missing]),\n b = CategoricalArray([\"a\", \"b\", missing, missing, \"b\", \"a\", \"a\", \"a\"]))\n updf = DataFrame(a = CategoricalArray([\"a\", \"a\", missing, \"b\", missing]),\n b = CategoricalArray([\"a\", \"b\", missing, \"b\", \"a\"]))\n @test nonunique(pdf) == [false, false, false, true, false, false, true, true]\n @test nonunique(updf) == falses(5)\n @test updf ≅ unique(pdf)\n unique!(pdf)\n @test pdf ≅ updf\n @test_throws ArgumentError unique(pdf, true)\n\n df = view(DataFrame(a = [1, 2, 3, 3, 4]), :, :)\n udf = DataFrame(a = [1, 2, 3, 4])\n @test nonunique(df) == [false, false, false, true, false]\n @test udf == unique(df)\n @test_throws ArgumentError unique!(df)\n @test_throws ArgumentError unique(df, true)\n\n pdf = view(DataFrame(a = CategoricalArray([\"a\", \"a\", missing, missing, \"b\", missing, \"a\", missing]),\n b = CategoricalArray([\"a\", \"b\", missing, missing, \"b\", \"a\", \"a\", \"a\"])), :, :)\n updf = DataFrame(a = CategoricalArray([\"a\", \"a\", missing, \"b\", missing]),\n b = CategoricalArray([\"a\", \"b\", missing, \"b\", \"a\"]))\n @test nonunique(pdf) == [false, false, false, true, false, false, true, true]\n @test nonunique(updf) == falses(5)\n @test updf ≅ unique(pdf)\n @test_throws ArgumentError unique!(pdf)\n @test_throws ArgumentError unique(pdf, true)\nend"
] |
f7636223bf6071f8edcd3efac92cca54f4a221ff
| 9,698
|
jl
|
Julia
|
test/SLM/property.jl
|
chenwilliam77/EconFixedPointPDEs
|
50ce1f61fc796605a2d0e81b08dd472444182e2b
|
[
"MIT"
] | 1
|
2021-01-31T00:29:04.000Z
|
2021-01-31T00:29:04.000Z
|
test/SLM/property.jl
|
chenwilliam77/EconFixedPointPDEs
|
50ce1f61fc796605a2d0e81b08dd472444182e2b
|
[
"MIT"
] | null | null | null |
test/SLM/property.jl
|
chenwilliam77/EconFixedPointPDEs
|
50ce1f61fc796605a2d0e81b08dd472444182e2b
|
[
"MIT"
] | 1
|
2021-12-19T16:40:44.000Z
|
2021-12-19T16:40:44.000Z
|
using Test, FileIO, ModelConstructors
include(joinpath(dirname(@__FILE__), "../../src/includeall.jl"))
rp = joinpath(dirname(@__FILE__), "../reference/SLM") # reference path
# Set up inputs
input_inc = load(joinpath(rp, "find_solution_input.jld2"))
input_dec = load(joinpath(rp, "find_solution_input_decrease.jld2"))
input_sin = load(joinpath(rp, "find_solution_input_sine.jld2"))
in_inc = load(joinpath(rp, "design.jld2"))
in_dec = load(joinpath(rp, "design_decrease.jld2"))
in_sin = load(joinpath(rp, "design_sine.jld2"))
d = Dict()
default_slm_kwargs!(d)
d[:left_value] = input_inc["p0_norun"]
d[:right_value] = input_inc["p1_norun"]
d[:min_value] = input_inc["p0_norun"]
d[:max_value] = input_inc["p1_norun"]
# Scale problem
@testset "Scaling" begin
d_false = deepcopy(d)
d_false[:scaling] = false
yscale_inc = load(joinpath(rp, "scaleproblem.jld2"))
yscale_dec = load(joinpath(rp, "scaleproblem_decrease.jld2"))
yscale_sin = load(joinpath(rp, "scaleproblem_sine.jld2"))
leftval_inc = load(joinpath(rp, "left_value.jld2"))
rightval_inc = load(joinpath(rp, "right_value.jld2"))
for (i, in_data, yscale_data) in zip(1:3, [input_inc, input_dec, input_sin], [yscale_inc, yscale_dec, yscale_sin])
if i == 1
ŷ = scale_problem!(vec(in_data["w"]), vec(in_data["p_sol"]), d)
elseif i == 2
ŷ = scale_problem!(vec(in_data["w"]), vec(in_data["rev_p_sol"]), d)
else
ŷ = scale_problem!(vec(in_data["x"]), vec(in_data["y"]), d)
end
@test d[:y_scale] == yscale_data["YScale"]
@test d[:y_shift] == yscale_data["YShift"]
@test ŷ == vec(yscale_data["yhat"])
if i == 1
@test d[:left_value] == leftval_inc["left_value"]
@test d[:right_value] == rightval_inc["right_value"]
@test d[:min_value] == in_data["p0_norun"] * d[:y_scale] + d[:y_shift]
@test d[:max_value] == in_data["p1_norun"] * d[:y_scale] + d[:y_shift]
end
end
@test vec(in_inc["y"]) == scale_problem!(vec(in_inc["x"]), vec(in_inc["y"]), d_false)
@test d_false[:left_value] == input_inc["p0_norun"]
@test d_false[:right_value] == input_inc["p1_norun"]
@test d_false[:y_shift] == 0.
@test d_false[:y_scale] == 1.
end
# Design matrix
Mdes = Dict()
rhs = Dict()
Mineq = Dict()
rhsineq = Dict()
Meq = Dict()
rhseq = Dict()
for (name, in_data) in zip([:inc, :dec, :sin], [in_inc, in_dec, in_sin])
Mineq[name] = zeros(0, Int(in_data["nc"]))
Meq[name] = zeros(0, Int(in_data["nc"]))
rhsineq[name] = Vector{Float64}(undef, 0)
rhseq[name] = Vector{Float64}(undef, 0)
Mdes[name] = construct_design_matrix(vec(in_data["x"]), vec(in_data["knots"]),
vec(in_data["dx"]), Int.(vec(in_data["xbin"])),
Int(in_data["nx"]), Int(in_data["nk"]), Int(in_data["nc"]))
rhs[name] = in_data["y"]
end
@testset "Design matrix" begin
for (name, in_data) in zip([:inc, :dec, :sin], [in_inc, in_dec, in_sin])
@test @test_matrix_approx_eq Mdes[name] in_data["Mdes"]
@test rhs[name] == in_data["rhs"]
end
end
# Regularizer matrix
Mreg = Dict()
for (name, in_data) in zip([:inc, :dec, :sin], [in_inc, in_dec, in_sin])
Mreg[name] = construct_regularizer(vec(in_data["dx"]), Int(in_data["nk"]))
end
reg_inc = load(joinpath(rp, "regularizer.jld2"))
reg_dec = load(joinpath(rp, "regularizer_decrease.jld2"))
reg_sin = load(joinpath(rp, "regularizer_sine.jld2"))
@testset "Regularizer" begin
for (name, reg_data) in zip([:inc, :dec, :sin], [reg_inc, reg_dec, reg_sin])
@test @test_matrix_approx_eq Mreg[name] reg_data["Mreg"]
@test all(reg_data["rhsreg"] .== 0.)
end
end
# Test C2
C2_inc = load(joinpath(rp, "C2.jld2"))
C2_dec = load(joinpath(rp, "C2_decrease.jld2"))
C2_sin = load(joinpath(rp, "C2_sine.jld2"))
for (name, in_data) in zip([:inc, :dec, :sin], [in_inc, in_dec, in_sin])
Meq[name], rhseq[name] = C2_matrix(Int(in_data["nk"]), Int(in_data["nc"]), vec(in_data["dx"]), Meq[name], rhseq[name])
end
@testset "C2" begin
for (name, C2_data) in zip([:inc, :dec, :sin], [C2_inc, C2_dec, C2_sin])
@test @test_matrix_approx_eq Meq[name] C2_data["Meq"]
@test @test_matrix_approx_eq rhseq[name] C2_data["rhseq"]
end
end
# Left and right values
left_inc = load(joinpath(rp, "left_value.jld2"))
left_dec = load(joinpath(rp, "left_value.jld2")) # did not create a "decreasing" version, so we just use the same file as increasing
left_sin = load(joinpath(rp, "left_value_sine.jld2")) # and adjust accordingly, noting that the left and right values are the reverse ones
right_inc = load(joinpath(rp, "right_value.jld2"))
right_dec = load(joinpath(rp, "right_value.jld2"))
right_sin = load(joinpath(rp, "right_value_sine.jld2"))
for (i, name, side_data, in_data) in zip(1:3, [:inc, :dec, :sin], [left_inc, right_dec, left_sin], [in_inc, in_dec, in_sin])
if i == 2
Meq[name], rhseq[name] = set_right_value(side_data["right_value"], Int(in_data["nc"]), Int(in_data["nk"]), Meq[name], rhseq[name])
else
Meq[name], rhseq[name] = set_left_value(side_data["left_value"], Int(in_data["nc"]), Meq[name], rhseq[name])
end
end
for (i, name, side_data, in_data) in zip(1:3, [:inc, :dec, :sin], [right_inc, left_dec, right_sin], [in_inc, in_dec, in_sin])
if i == 2
Meq[name], rhseq[name] = set_left_value(side_data["left_value"], Int(in_data["nc"]), Meq[name], rhseq[name])
else
Meq[name], rhseq[name] = set_right_value(side_data["right_value"], Int(in_data["nc"]), Int(in_data["nk"]), Meq[name], rhseq[name])
end
end
@testset "Left and right value" begin
for (name, in_data) in zip([:inc, :sin], [right_inc, right_sin])
@test @test_matrix_approx_eq Meq[name] in_data["Meq"]
@test @test_matrix_approx_eq rhseq[name] in_data["rhseq"]
end
end
# Global minimum and maximum
minmax_inc = load(joinpath(rp, "min_max.jld2"))
minmax_dec = load(joinpath(rp, "min_max_decrease.jld2"))
minmax_sin = load(joinpath(rp, "min_max_sine.jld2"))
for (name, in_data, minmax_data) in zip([:inc, :dec], [in_inc, in_dec], [minmax_inc, minmax_dec])
Mineq[name], rhsineq[name] = set_min_value(minmax_data["min_value"], Int(in_data["nk"]), Int(in_data["nc"]),
vec(in_data["dx"]), Mineq[name], rhsineq[name])
Mineq[name], rhsineq[name] = set_max_value(minmax_data["max_value"], Int(in_data["nk"]), Int(in_data["nc"]),
vec(in_data["dx"]), Mineq[name], rhsineq[name])
end
@testset "Global minimum and maximum" begin
for (name, minmax_data) in zip([:inc, :dec], [minmax_inc, minmax_dec])
@test @test_matrix_approx_eq Mineq[name] minmax_data["Mineq"]
@test @test_matrix_approx_eq rhsineq[name] vec(minmax_data["rhsineq"])
end
end
# Monotonicity
mono_inc = load(joinpath(rp, "monotone.jld2"))
mono_dec = load(joinpath(rp, "monotone_decrease.jld2"))
mono_sin = load(joinpath(rp, "monotone_sine.jld2"))
inc_int = [0 π/2; 3*π/2 5*π/2; 7*π/2 4*pi]
dec_int = [π/2 3*π/2; 5*π/2 7*π/2]
for (i, name, in_data, mono_data) in zip(1:3, [:inc, :dec, :sin], [in_inc, in_dec, in_sin], [mono_inc, mono_dec, mono_sin])
monotone_settings = Vector{NamedTuple{(:knotlist, :increasing), Tuple{Tuple{Int, Int}, Bool}}}(undef, 0)
total_monotone_intervals = 0
if i == 1
total_monotone_intervals += monotone_increasing!(monotone_settings, Int(in_data["nk"]))
elseif i == 2
total_monotone_intervals += monotone_decreasing!(monotone_settings, Int(in_data["nk"]))
elseif i == 3
total_monotone_intervals += increasing_intervals_info!(monotone_settings, vec(in_data["knots"]), inc_int, Int(in_data["nk"]))
total_monotone_intervals += decreasing_intervals_info!(monotone_settings, vec(in_data["knots"]), dec_int, Int(in_data["nk"]))
end
Mineq[name], rhsineq[name] = construct_monotonicity_matrix(monotone_settings, Int(in_data["nc"]), Int(in_data["nk"]),
vec(in_data["dx"]), total_monotone_intervals, Mineq[name], rhsineq[name])
end
@testset "Monotonicity" begin
for (name, mono_data) in zip([:inc, :dec, :sin], [mono_inc, mono_dec, mono_sin])
@test @test_matrix_approx_eq Mineq[name] mono_data["Mineq"]
@test @test_matrix_approx_eq rhsineq[name] mono_data["rhsineq"]
end
end
# Curvature
curv_inc = load(joinpath(rp, "curvature.jld2"))
curv_dec = load(joinpath(rp, "curvature_decrease.jld2"))
curv_sin = load(joinpath(rp, "curvature_sine.jld2"))
cu_int = [π 2*π; 3*π 4*π]
cd_int = [0 π; 2*π 3*π]
for (i, name, in_data) in zip(1:3, [:inc, :dec, :sin], [in_inc, in_dec, in_sin])
curvature_settings = Vector{NamedTuple{(:concave_up, :range), Tuple{Bool, Vector{Float64}}}}(undef, 0)
if i == 1
concave_down_info!(curvature_settings)
elseif i == 2
concave_up_info!(curvature_settings)
elseif i == 3
concave_up_intervals_info!(curvature_settings, cu_int)
concave_down_intervals_info!(curvature_settings, cd_int)
end
Mineq[name], rhsineq[name] = construct_curvature_matrix(curvature_settings, Int(in_data["nc"]), Int(in_data["nk"]), vec(in_data["knots"]),
vec(in_data["dx"]), Mineq[name], rhsineq[name])
end
@testset "Curvature" begin
for (name, curv_data) in zip([:inc, :dec, :sin], [curv_inc, curv_dec, curv_sin])
@test @test_matrix_approx_eq Mineq[name] curv_data["Mineq"]
@test @test_matrix_approx_eq rhsineq[name] vec(curv_data["rhsineq"])
end
end
| 46.850242
| 142
| 0.648484
|
[
"@testset \"Scaling\" begin\n d_false = deepcopy(d)\n d_false[:scaling] = false\n yscale_inc = load(joinpath(rp, \"scaleproblem.jld2\"))\n yscale_dec = load(joinpath(rp, \"scaleproblem_decrease.jld2\"))\n yscale_sin = load(joinpath(rp, \"scaleproblem_sine.jld2\"))\n leftval_inc = load(joinpath(rp, \"left_value.jld2\"))\n rightval_inc = load(joinpath(rp, \"right_value.jld2\"))\n for (i, in_data, yscale_data) in zip(1:3, [input_inc, input_dec, input_sin], [yscale_inc, yscale_dec, yscale_sin])\n if i == 1\n ŷ = scale_problem!(vec(in_data[\"w\"]), vec(in_data[\"p_sol\"]), d)\n elseif i == 2\n ŷ = scale_problem!(vec(in_data[\"w\"]), vec(in_data[\"rev_p_sol\"]), d)\n else\n ŷ = scale_problem!(vec(in_data[\"x\"]), vec(in_data[\"y\"]), d)\n end\n\n @test d[:y_scale] == yscale_data[\"YScale\"]\n @test d[:y_shift] == yscale_data[\"YShift\"]\n @test ŷ == vec(yscale_data[\"yhat\"])\n\n if i == 1\n @test d[:left_value] == leftval_inc[\"left_value\"]\n @test d[:right_value] == rightval_inc[\"right_value\"]\n @test d[:min_value] == in_data[\"p0_norun\"] * d[:y_scale] + d[:y_shift]\n @test d[:max_value] == in_data[\"p1_norun\"] * d[:y_scale] + d[:y_shift]\n end\n end\n @test vec(in_inc[\"y\"]) == scale_problem!(vec(in_inc[\"x\"]), vec(in_inc[\"y\"]), d_false)\n @test d_false[:left_value] == input_inc[\"p0_norun\"]\n @test d_false[:right_value] == input_inc[\"p1_norun\"]\n @test d_false[:y_shift] == 0.\n @test d_false[:y_scale] == 1.\nend",
"@testset \"Design matrix\" begin\n for (name, in_data) in zip([:inc, :dec, :sin], [in_inc, in_dec, in_sin])\n @test @test_matrix_approx_eq Mdes[name] in_data[\"Mdes\"]\n @test rhs[name] == in_data[\"rhs\"]\n end\nend",
"@testset \"Regularizer\" begin\n for (name, reg_data) in zip([:inc, :dec, :sin], [reg_inc, reg_dec, reg_sin])\n @test @test_matrix_approx_eq Mreg[name] reg_data[\"Mreg\"]\n @test all(reg_data[\"rhsreg\"] .== 0.)\n end\nend",
"@testset \"C2\" begin\n for (name, C2_data) in zip([:inc, :dec, :sin], [C2_inc, C2_dec, C2_sin])\n @test @test_matrix_approx_eq Meq[name] C2_data[\"Meq\"]\n @test @test_matrix_approx_eq rhseq[name] C2_data[\"rhseq\"]\n end\nend",
"@testset \"Left and right value\" begin\n for (name, in_data) in zip([:inc, :sin], [right_inc, right_sin])\n @test @test_matrix_approx_eq Meq[name] in_data[\"Meq\"]\n @test @test_matrix_approx_eq rhseq[name] in_data[\"rhseq\"]\n end\nend",
"@testset \"Global minimum and maximum\" begin\n for (name, minmax_data) in zip([:inc, :dec], [minmax_inc, minmax_dec])\n @test @test_matrix_approx_eq Mineq[name] minmax_data[\"Mineq\"]\n @test @test_matrix_approx_eq rhsineq[name] vec(minmax_data[\"rhsineq\"])\n end\nend",
"@testset \"Monotonicity\" begin\n for (name, mono_data) in zip([:inc, :dec, :sin], [mono_inc, mono_dec, mono_sin])\n @test @test_matrix_approx_eq Mineq[name] mono_data[\"Mineq\"]\n @test @test_matrix_approx_eq rhsineq[name] mono_data[\"rhsineq\"]\n end\nend",
"@testset \"Curvature\" begin\n for (name, curv_data) in zip([:inc, :dec, :sin], [curv_inc, curv_dec, curv_sin])\n @test @test_matrix_approx_eq Mineq[name] curv_data[\"Mineq\"]\n @test @test_matrix_approx_eq rhsineq[name] vec(curv_data[\"rhsineq\"])\n end\nend"
] |
f7662de5a8e626b277fefe3ce8c479ff09c61bb2
| 1,245
|
jl
|
Julia
|
test/rank_by_consensus.jl
|
Durzot/MT_NMF
|
a3e3c2fb4a23cc09e78e1ad1e324787c6017a4fc
|
[
"MIT"
] | null | null | null |
test/rank_by_consensus.jl
|
Durzot/MT_NMF
|
a3e3c2fb4a23cc09e78e1ad1e324787c6017a4fc
|
[
"MIT"
] | null | null | null |
test/rank_by_consensus.jl
|
Durzot/MT_NMF
|
a3e3c2fb4a23cc09e78e1ad1e324787c6017a4fc
|
[
"MIT"
] | null | null | null |
using VariantsNMF
using Test
#### simulate
V = get_one_simulated_V()
@testset "nmf_FI" begin
#### params for rank selection
rc_params = RCParams(
K_min = 2,
K_max = 6,
n_iter = 10
)
#### nmf β-divergence, multiplicative updates
nmf_global_params = NMFParams(
init = :random,
dist = truncated(Normal(1, 1), 0, Inf),
max_iter = 1_000,
stopping_crit = :conn,
stopping_iter = 10,
verbose = false,
)
nmf_local_params = FIParams(
β = 1,
l₁ratio_H = 0,
α_H = 0,
alg = :mm
)
#### NMF struct
nmf = NMF(
solver = nmf_FI,
global_params = nmf_global_params,
local_params = nmf_local_params
)
#### get consensus metrics for each rank
@time rc_results = rank_by_consensus(V, rc_params, nmf)
@test "rank" in names(rc_results.df_metrics)
@test "cophenetic" in names(rc_results.df_metrics)
@test "dispersion" in names(rc_results.df_metrics)
@test "silhouette" in names(rc_results.df_metrics)
@test "sparse_W" in names(rc_results.df_metrics)
@test "sparse_H" in names(rc_results.df_metrics)
end
| 25.408163
| 59
| 0.583133
|
[
"@testset \"nmf_FI\" begin\n #### params for rank selection\n rc_params = RCParams(\n K_min = 2,\n K_max = 6,\n n_iter = 10\n )\n\n #### nmf β-divergence, multiplicative updates\n nmf_global_params = NMFParams(\n init = :random,\n dist = truncated(Normal(1, 1), 0, Inf),\n max_iter = 1_000,\n stopping_crit = :conn,\n stopping_iter = 10,\n verbose = false,\n )\n\n nmf_local_params = FIParams(\n β = 1,\n l₁ratio_H = 0,\n α_H = 0,\n alg = :mm\n )\n\n #### NMF struct\n nmf = NMF(\n solver = nmf_FI,\n global_params = nmf_global_params,\n local_params = nmf_local_params\n )\n\n #### get consensus metrics for each rank\n @time rc_results = rank_by_consensus(V, rc_params, nmf)\n\n @test \"rank\" in names(rc_results.df_metrics)\n @test \"cophenetic\" in names(rc_results.df_metrics)\n @test \"dispersion\" in names(rc_results.df_metrics)\n @test \"silhouette\" in names(rc_results.df_metrics)\n @test \"sparse_W\" in names(rc_results.df_metrics)\n @test \"sparse_H\" in names(rc_results.df_metrics)\nend"
] |
f76828962b7f157fe728585cfec434da7d31759b
| 33,111
|
jl
|
Julia
|
test/runtests.jl
|
harivnkochi/UnderwaterAcoustics.jl
|
23d090431f292890dad70e77c17dff414008fcfc
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
harivnkochi/UnderwaterAcoustics.jl
|
23d090431f292890dad70e77c17dff414008fcfc
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
harivnkochi/UnderwaterAcoustics.jl
|
23d090431f292890dad70e77c17dff414008fcfc
|
[
"MIT"
] | null | null | null |
using Test
using UnderwaterAcoustics
using UnderwaterAcoustics: amp2db, db2amp
using ForwardDiff
@testset "basic" begin
@test soundspeed() ≈ 1539.0 atol=0.1
@test soundspeed(; voidfrac=1e-5) ≈ 1402.1 atol=0.1
@test soundspeed(; voidfrac=1.0) ≈ 340.0
@test amp2db(absorption(10000, 1000.0, 35.0, 15.0)) ≈ -1.0 atol=0.5
@test amp2db(absorption(50000)) ≈ -11.0 atol=0.5
@test amp2db(absorption(100000)) ≈ -36.0 atol=0.5
@test amp2db(absorption(100000, 1000.0, 38.5, 14.0, 0.0)) ≈ -40.0 atol=0.5
@test amp2db(absorption(100000, 1000.0, 38.5, 14.0, 2000.0)) ≈ -30.0 atol=0.5
@test amp2db(absorption(100000, 1000.0, 38.5, 14.0, 6000.0)) ≈ -16.0 atol=0.5
@test waterdensity() ≈ 1022.7 atol=0.1
@test reflectioncoef(0.0, 1200.0/1023.0, 1600.0/1540.0, 0.0) isa Complex
@test reflectioncoef(0.0, 1200.0/1023.0, 1600.0/1540.0, 0.0) ≈ 0.0986 atol=0.0001
@test amp2db(abs(reflectioncoef(0.0, 2.5, 2.5, 0.01374))) ≈ -2.8 atol=0.1
@test amp2db(abs(reflectioncoef(0.0, 2.492, 1.3370, 0.01705))) ≈ -5 atol=0.5
@test amp2db(abs(reflectioncoef(0.0, 1.195, 1.0179, 0.02158))) ≈ -20 atol=0.5
@test amp2db(abs(reflectioncoef(1.22, 1.149, 0.9873, 0.00386))) ≈ -32 atol=0.5
@test amp2db(surfaceloss(15.0, 20000.0, 80°)) ≈ -6.5 atol=0.1
@test amp2db(surfaceloss(10.0, 20000.0, 80°)) ≈ -3.4 atol=0.1
@test amp2db(surfaceloss(5.0, 20000.0, 80°)) ≈ -0.5 atol=0.1
@test doppler(0.0, 50000.0) == 50000.0
@test doppler(10.0, 50000.0) ≈ 50325 atol=0.5
@test doppler(-10.0, 50000.0) ≈ 49675 atol=0.5
@test bubbleresonance(100e-6) ≈ 32500.0 atol=0.1
@test bubbleresonance(32e-6) ≈ 101562.5 atol=0.1
@test bubbleresonance(100e-6, 10.0) ≈ 45962.0 atol=0.1
end
@testset "pm-core-basic" begin
env = UnderwaterEnvironment()
@test models() isa AbstractArray
@test models(env) isa AbstractArray
@test env isa UnderwaterAcoustics.BasicUnderwaterEnvironment
@test altimetry(env) isa Altimetry
@test bathymetry(env) isa Bathymetry
@test ssp(env) isa SoundSpeedProfile
@test salinity(env) isa Real
@test seasurface(env) isa ReflectionModel
@test seabed(env) isa ReflectionModel
@test noise(env) isa NoiseModel
@test altitude(altimetry(env), 0.0, 0.0) isa Real
@test depth(bathymetry(env), 0.0, 0.0) isa Real
@test soundspeed(ssp(env), 0.0, 0.0, 0.0) isa Real
@test reflectioncoef(seasurface(env), 1000.0, 0.0) isa Complex
@test reflectioncoef(seabed(env), 1000.0, 0.0) isa Complex
sig = record(noise(env), 1.0, 44100.0)
@test length(sig) == 44100
@test sum(abs2.(sig)) > 0.0
@test AcousticReceiver(0.0, 0.0) isa AcousticReceiver
@test location(AcousticReceiver(100.0, 10.0, -50.0)) == (100, 10.0, -50.0)
@test location(AcousticReceiver(100.0, -50.0)) == (100, 0.0, -50.0)
src = AcousticSource(100.0, 10.0, -50.0, 4410.0; sourcelevel=1.0)
sig = record(src, 1.0, 44100.0)
@test src isa NarrowbandAcousticSource
@test location(src) == (100.0, 10.0, -50.0)
@test location(AcousticSource(100.0, -50.0, 1000.0)) == (100.0, 0.0, -50.0)
@test nominalfrequency(src) == 4410.0
@test phasor(src) == complex(1.0, 0.0)
@test length(sig) == 44100
@test eltype(sig) <: Complex
@test sum(abs2.(sig))/44100.0 ≈ 1.0 atol=1e-4
@test sig[1] != sig[2]
@test sig[1] ≈ sig[11]
@test sig[2] ≈ sig[12]
src = Pinger(10.0, -10.0, 1000.0; sourcelevel=1.0, interval=0.5)
sig = record(src, 1.0, 44100.0)
@test src isa AcousticSource
@test location(src) == (10.0, 0.0, -10.0)
@test nominalfrequency(src) == 1000.0
@test phasor(src) == complex(1.0, 0.0)
@test length(sig) == 44100
@test eltype(sig) <: Complex
@test sum(abs2.(sig))/44100.0 ≈ 0.04 atol=1e-4
@test maximum(abs2.(sig)) ≈ 1.0 atol=1e-4
src = SampledAcousticSource(10.0, -10.0, ones(1000); fs=1000.0, frequency=100.0)
@test src isa SampledAcousticSource
@test location(src) == (10.0, 0.0, -10.0)
@test nominalfrequency(src) == 100.0
sig = record(src, 1.0, 1000.0)
@test length(sig) == 1000
@test eltype(sig) === Float64
@test all(sig .== 1.0)
sig = record(src, 1.0, 1000.0; start=-0.5)
@test length(sig) == 1000
@test eltype(sig) === Float64
@test all(sig[1:500] .== 0.0)
@test all(sig[501:1000] .== 1.0)
sig = record(src, 1.0, 1000.0; start=0.5)
@test length(sig) == 1000
@test eltype(sig) === Float64
@test all(sig[1:500] .== 1.0)
@test all(sig[501:1000] .== 0.0)
sig = record(src, 1.0, 1000.0; start=-2.0)
@test length(sig) == 1000
@test eltype(sig) === Float64
@test all(sig .== 0.0)
sig = record(src, 1.0, 1000.0; start=2.0)
@test length(sig) == 1000
@test eltype(sig) === Float64
@test all(sig .== 0.0)
@test_throws ArgumentError record(src, 1.0, 2000.0)
src = SampledAcousticSource(10.0, 5.0, -10.0, cis.(2π * 1000 * (0:999) ./ 10000.0); fs=10000.0)
@test src isa SampledAcousticSource
@test location(src) == (10.0, 5.0, -10.0)
@test nominalfrequency(src) == 1000.0
sig = record(src, 0.1, 10000.0)
@test length(sig) == 1000
@test eltype(sig) === ComplexF64
@test IsoSSP(1500.0) isa SoundSpeedProfile
@test soundspeed(IsoSSP(1500.0), 100.0, 10.0, -50.0) == 1500.0
@test MunkSSP() isa SoundSpeedProfile
@test soundspeed(MunkSSP(), 0.0, 0.0, -2000.0) ≈ 1505.0 atol=1.0
@test soundspeed(MunkSSP(), 0.0, 0.0, -3000.0) ≈ 1518.0 atol=1.0
s = SampledSSP(0.0:500.0:1000.0, [1500.0, 1520.0, 1510.0])
@test s isa SoundSpeedProfile
@test soundspeed(s, 0.0, 0.0, 0.0) ≈ 1500.0
@test soundspeed(s, 0.0, 0.0, -250.0) ≈ 1510.0
@test soundspeed(s, 0.0, 0.0, -500.0) ≈ 1520.0
@test soundspeed(s, 0.0, 0.0, -750.0) ≈ 1515.0
@test soundspeed(s, 0.0, 0.0, -1000.0) ≈ 1510.0
s = SampledSSP(0.0:500.0:1000.0, [1500.0, 1520.0, 1510.0], :smooth)
@test s isa SoundSpeedProfile
@test soundspeed(s, 0.0, 0.0, 0.0) ≈ 1500.0
@test soundspeed(s, 0.0, 0.0, -250.0) > 1510.0
@test soundspeed(s, 0.0, 0.0, -500.0) ≈ 1520.0
@test soundspeed(s, 0.0, 0.0, -750.0) > 1515.0
@test soundspeed(s, 0.0, 0.0, -1000.0) ≈ 1510.0
@test ConstantDepth(20.0) isa Bathymetry
@test depth(ConstantDepth(20.0), 0.0, 0.0) == 20.0
@test maxdepth(ConstantDepth(20.0)) == 20.0
b = SampledDepth(0.0:500.0:1000.0, [20.0, 25.0, 15.0])
@test b isa Bathymetry
@test depth(b, 0.0, 0.0) ≈ 20.0
@test depth(b, 250.0, 0.0) ≈ 22.5
@test depth(b, 500.0, 0.0) ≈ 25.0
@test depth(b, 750.0, 0.0) ≈ 20.0
@test depth(b, 1000.0, 0.0) ≈ 15.0
@test maxdepth(b) ≈ 25.0
b = SampledDepth(0.0:500.0:1000.0, [20.0, 25.0, 15.0], :smooth)
@test b isa Bathymetry
@test depth(b, 0.0, 0.0) ≈ 20.0
@test depth(b, 250.0, 0.0) > 22.5
@test depth(b, 500.0, 0.0) ≈ 25.0
@test depth(b, 750.0, 0.0) > 20.0
@test depth(b, 1000.0, 0.0) ≈ 15.0
@test maxdepth(b) ≈ 25.0
@test FlatSurface() isa Altimetry
@test altitude(FlatSurface(), 0.0, 0.0) == 0.0
a = SampledAltitude(0.0:500.0:1000.0, [0.0, 1.0, -1.0])
@test a isa Altimetry
@test altitude(a, 0.0, 0.0) ≈ 0.0
@test altitude(a, 250.0, 0.0) ≈ 0.5
@test altitude(a, 500.0, 0.0) ≈ 1.0
@test altitude(a, 750.0, 0.0) ≈ 0.0
@test altitude(a, 1000.0, 0.0) ≈ -1.0
a = SampledAltitude(0.0:500.0:1000.0, [0.0, 1.0, -1.0], :smooth)
@test a isa Altimetry
@test altitude(a, 0.0, 0.0) ≈ 0.0 atol=1e-6
@test altitude(a, 250.0, 0.0) > 0.5
@test altitude(a, 500.0, 0.0) ≈ 1.0 atol=1e-6
@test altitude(a, 1000.0, 0.0) ≈ -1.0 atol=1e-6
@test ReflectionCoef(0.5 + 0.3im) isa ReflectionModel
@test reflectioncoef(ReflectionCoef(0.5 + 0.3im), 1000.0, 0.0) == 0.5 + 0.3im
@test RayleighReflectionCoef(1.0, 1.0) isa ReflectionModel
@test RayleighReflectionCoef(1.0, 1.0, 0.0) isa ReflectionModel
@test reflectioncoef(RayleighReflectionCoef(1.0, 1.0, 0.0), 1000.0, 0.0) ≈ 0.0
@test reflectioncoef(RayleighReflectionCoef(0.0, 1.0, 0.0), 1000.0, 0.0) ≈ -1.0
@test Rock isa RayleighReflectionCoef
@test Pebbles isa RayleighReflectionCoef
@test SandyGravel isa RayleighReflectionCoef
@test CoarseSand isa RayleighReflectionCoef
@test MediumSand isa RayleighReflectionCoef
@test FineSand isa RayleighReflectionCoef
@test VeryFineSand isa RayleighReflectionCoef
@test ClayeySand isa RayleighReflectionCoef
@test CoarseSilt isa RayleighReflectionCoef
@test SandySilt isa RayleighReflectionCoef
@test Silt isa RayleighReflectionCoef
@test FineSilt isa RayleighReflectionCoef
@test SandyClay isa RayleighReflectionCoef
@test SiltyClay isa RayleighReflectionCoef
@test Clay isa RayleighReflectionCoef
@test Vacuum isa ReflectionModel
@test reflectioncoef(Vacuum, 1000.0, 0.0) ≈ -1.0
@test 0.0 < abs(reflectioncoef(Rock, 1000.0, 0.0)) < 1.0
@test abs(reflectioncoef(Silt, 1000.0, 0.0)) < abs(reflectioncoef(SandyGravel, 1000.0, 0.0))
@test abs(reflectioncoef(CoarseSilt, 1000.0, 0.0)) < abs(reflectioncoef(Rock, 1000.0, 0.0))
@test SurfaceLoss(5.0) isa ReflectionModel
@test SeaState0 isa SurfaceLoss
@test SeaState1 isa SurfaceLoss
@test SeaState2 isa SurfaceLoss
@test SeaState3 isa SurfaceLoss
@test SeaState4 isa SurfaceLoss
@test SeaState5 isa SurfaceLoss
@test SeaState6 isa SurfaceLoss
@test SeaState7 isa SurfaceLoss
@test SeaState8 isa SurfaceLoss
@test SeaState9 isa SurfaceLoss
@test 0.0 < abs(reflectioncoef(SeaState2, 1000.0, 0.0)) < 1.0
@test abs(reflectioncoef(SeaState2, 1000.0, 0.0)) > abs(reflectioncoef(SeaState5, 1000.0, 0.0))
@test abs(reflectioncoef(SeaState5, 1000.0, 0.0)) > abs(reflectioncoef(SeaState5, 2000.0, 0.0))
rx = AcousticReceiverGrid2D(100.0, 2.0, 100, -100.0, 5.0, 10)
@test rx isa AcousticReceiverGrid2D
@test rx isa AbstractMatrix
@test size(rx) == (100, 10)
@test rx[1,1] == AcousticReceiver(100.0, -100.0)
@test rx[end,end] == AcousticReceiver(298.0, -55.0)
rx = AcousticReceiverGrid3D(100.0, 2.0, 100, 0.0, 1.0, 100, -100.0, 5.0, 10)
@test rx isa AcousticReceiverGrid3D
@test rx isa AbstractArray
@test size(rx) == (100, 100, 10)
@test rx[1,1,1] == AcousticReceiver(100.0, 0.0, -100.0)
@test rx[end,end,end] == AcousticReceiver(298.0, 99.0, -55.0)
end
@testset "pm-pekeris" begin
@test PekerisRayModel in models()
env = UnderwaterEnvironment()
pm = PekerisRayModel(env, 7)
@test pm isa PekerisRayModel
arr = arrivals(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))
@test arr isa AbstractArray{<:UnderwaterAcoustics.RayArrival}
@test length(arr) == 7
@test arr[1].time ≈ 0.0650 atol=0.0001
@test arr[2].time ≈ 0.0657 atol=0.0001
@test arr[3].time ≈ 0.0670 atol=0.0001
@test all([arr[j].time > arr[j-1].time for j ∈ 2:7])
@test abs(arr[1].phasor) ≈ 0.01 atol=0.001
@test real(arr[2].phasor) < 0.0
@test imag(arr[2].phasor) ≈ 0.0
@test all([abs(arr[j].phasor) < abs(arr[j-1].phasor) for j ∈ 2:7])
@test [(arr[j].surface, arr[j].bottom) for j ∈ 1:7] == [(0,0), (1,0), (0,1), (1,1), (1,1), (2,1), (1,2)]
@test all([abs(arr[j].arrivalangle) == abs(arr[j].launchangle) for j ∈ 1:7])
r = eigenrays(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))
@test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}
@test length(r) == 7
@test all([abs(r[j].arrivalangle) == abs(r[j].launchangle) for j ∈ 1:7])
@test all([r[j].raypath[1] == (0.0, 0.0, -5.0) for j ∈ 1:7])
@test all([r[j].raypath[end] == (100.0, 0.0, -10.0) for j ∈ 1:7])
@test all([length(r[j].raypath) == r[j].surface + r[j].bottom + 2 for j ∈ 1:7])
r = rays(pm, AcousticSource(0.0, -5.0, 1000.0), -60°:15°:60°, 100.0)
@test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}
@test length(r) == 9
@test all([r[j].launchangle for j ∈ 1:9] .≈ -60°:15°:60°)
@test all([abs(r[j].arrivalangle) == abs(r[j].launchangle) for j ∈ 1:9])
@test all([r[j].raypath[1] == (0.0, 0.0, -5.0) for j ∈ 1:9])
@test all([r[j].raypath[end][1] ≥ 100.0 for j ∈ 1:9])
@test all([length(r[j].raypath) == r[j].surface + r[j].bottom + 2 for j ∈ 1:9])
ir1 = impulseresponse(arr, 10000.0; reltime=true, approx=true)
ir2 = impulseresponse(arr, 10000.0; reltime=false, approx=true)
@test length(ir2) ≈ length(ir1) + round(Int, 10000.0 * arr[1].time) atol=1
@test length(ir2) == round(Int, 10000.0 * arr[end].time) + 1
@test sum(ir1 .!= 0.0) == 7
@test sum(ir2 .!= 0.0) == 7
ndx = findall(abs.(ir1) .> 0)
@test (ndx .- 1) ./ 10000.0 ≈ [arr[j].time - arr[1].time for j ∈ 1:7] atol=1e-4
ndx = findall(abs.(ir2) .> 0)
@test (ndx .- 1) ./ 10000.0 ≈ [arr[j].time for j ∈ 1:7] atol=1e-4
ir1a = impulseresponse(arr, 10000.0; reltime=true)
ir2a = impulseresponse(arr, 10000.0; reltime=false)
@test length(ir2a) ≈ length(ir1a) + round(Int, 10000.0 * arr[1].time) atol=1
@test length(ir2a) ≥ length(ir2)
@test sum(abs2.(ir1a))/sum(abs2.(ir1)) ≈ 1.0 atol=0.05
@test sum(abs2.(ir2a))/sum(abs2.(ir2)) ≈ 1.0 atol=0.05
@test length(impulseresponse(arr, 10000.0, 256; reltime=true, approx=true)) == 256
@test length(impulseresponse(arr, 10000.0, 64; reltime=true, approx=true)) == 64
@test length(impulseresponse(arr, 10000.0, 256; reltime=true, approx=false)) == 256
@test length(impulseresponse(arr, 10000.0, 64; reltime=true, approx=false)) == 64
@test length(impulseresponse(arr, 10000.0, 1024; reltime=false, approx=true)) == 1024
@test length(impulseresponse(arr, 10000.0, 700; reltime=false, approx=true)) == 700
@test length(impulseresponse(arr, 10000.0, 1024; reltime=false, approx=false)) == 1024
@test length(impulseresponse(arr, 10000.0, 700; reltime=false, approx=false)) == 700
env = UnderwaterEnvironment(ssp=IsoSSP(1500.0))
pm = PekerisRayModel(env, 2)
d = (√1209.0)/4.0
x = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d))
@test x isa Complex
@test abs(x) ≈ 0.0 atol=0.0002
x′ = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d); mode=:incoherent)
@test x′ isa Complex
@test imag(x′) == 0.0
@test abs(x′) > 1/100.0
d = (√2409.0)/8.0
x = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d))
@test abs(x) > abs(x′)
y = transmissionloss(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d))
@test -10 * log10(abs2(x)) ≈ y atol=0.1
x = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d); mode=:incoherent)
@test abs(x) ≈ abs(x′) atol=0.0001
y = transmissionloss(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d); mode=:incoherent)
@test -10 * log10(abs2(x)) ≈ y atol=0.1
x1 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))
x2 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))
x3 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -15.0))
x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), [AcousticReceiver(100.0, -d) for d ∈ 5.0:5.0:15.0])
@test x isa AbstractVector
@test [x1, x2, x3] == x
x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 0.0, 1, -5.0, -5.0, 3))
@test x isa AbstractMatrix
@test size(x) == (1, 3)
@test [x1 x2 x3] == x
x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 10.0, 3, -5.0, -5.0, 3))
@test x isa AbstractMatrix
@test size(x) == (3, 3)
@test [x1, x2, x3] == x[1,:]
x1 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))
x2 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))
x3 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -15.0))
x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), [AcousticReceiver(100.0, -d) for d ∈ 5.0:5.0:15.0])
@test x isa AbstractVector
@test [x1, x2, x3] == x
x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 0.0, 1, -5.0, -5.0, 3))
@test x isa AbstractMatrix
@test size(x) == (1, 3)
@test [x1 x2 x3] == x
x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 10.0, 3, -5.0, -5.0, 3))
@test x isa AbstractMatrix
@test size(x) == (3, 3)
@test [x1, x2, x3] == x[1,:]
env = UnderwaterEnvironment()
pm = PekerisRayModel(env, 7)
tx = AcousticSource(0.0, -5.0, 1000.0)
rx = AcousticReceiver(100.0, -10.0)
sig = record(pm, tx, rx, 1.0, 44100.0)
@test size(sig) == (44100,)
sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)
@test size(sig) == (44100,)
sig = recorder(pm, tx, rx)(1.0, 44100.0)
@test size(sig) == (44100,)
sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)
@test size(sig) == (44100,)
tx = [AcousticSource(0.0, -5.0, 1000.0), AcousticSource(0.0, -10.0, 2000.0)]
rx = AcousticReceiver(100.0, -10.0)
sig = record(pm, tx, rx, 1.0, 44100.0)
@test size(sig) == (44100,)
sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)
@test size(sig) == (44100,)
sig = recorder(pm, tx, rx)(1.0, 44100.0)
@test size(sig) == (44100,)
sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)
@test size(sig) == (44100,)
tx = [AcousticSource(0.0, -5.0, 1000.0), AcousticSource(0.0, -10.0, 2000.0)]
rx = [AcousticReceiver(100.0, -10.0), AcousticReceiver(100.0, -15.0)]
sig = record(pm, tx, rx, 1.0, 44100.0)
@test size(sig) == (44100,2)
sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)
@test size(sig) == (44100,2)
sig = recorder(pm, tx, rx)(1.0, 44100.0)
@test size(sig) == (44100,2)
sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)
@test size(sig) == (44100,2)
tx = AcousticSource(0.0, -5.0, 1000.0)
rx = [AcousticReceiver(100.0, -10.0), AcousticReceiver(100.0, -15.0)]
sig = record(pm, tx, rx, 1.0, 44100.0)
@test size(sig) == (44100,2)
sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)
@test size(sig) == (44100,2)
sig = recorder(pm, tx, rx)(1.0, 44100.0)
@test size(sig) == (44100,2)
sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)
@test size(sig) == (44100,2)
env = UnderwaterEnvironment(noise=missing)
pm = PekerisRayModel(env, 7)
tx = Pinger(0.0, -5.0, 1000.0; interval=0.3)
rx = AcousticReceiver(100.0, -10.0)
sig1 = record(pm, tx, rx, 1.0, 44100.0)
@test size(sig1) == (44100,)
sig2 = record(pm, tx, rx, 1.0, 44100.0; start=0.5)
@test size(sig2) == (44100,)
@test sig1[22051:end] ≈ sig2[1:22050]
rx = AcousticReceiver(100.0, -11.0)
sig3 = record(pm, tx, rx, 1.0, 44100.0)
@test size(sig3) == (44100,)
@test !(sig1 ≈ sig3)
rx = AcousticReceiver(100.0/√2, 100.0/√2, -10.0)
sig3 = record(pm, tx, rx, 1.0, 44100.0)
@test size(sig3) == (44100,)
@test sig1 ≈ sig3
tx = [Pinger(0.0, -5.0, 1000.0; interval=0.3), Pinger(1.0, -5.0, 2000.0; interval=0.5)]
rx = AcousticReceiver(100.0, 0.0, -10.0)
sig1 = record(pm, tx, rx, 1.0, 44100.0)
rx = AcousticReceiver(100.0/√2, 100.0/√2, -10.0)
rx = AcousticReceiver(-100.0, 0.0, -10.0)
sig2 = record(pm, tx, rx, 1.0, 44100.0)
@test !(sig1 ≈ sig2)
end
@testset "pm-bellhop" begin
if Bellhop in models()
env = UnderwaterEnvironment(seasurface=Vacuum)
pm = Bellhop(env)
@test pm isa Bellhop
arr = arrivals(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))
@test arr isa AbstractArray{<:UnderwaterAcoustics.RayArrival}
r = eigenrays(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))
@test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}
r = rays(pm, AcousticSource(0.0, -5.0, 1000.0), -60°:15°:60°, 100.0)
@test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}
x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))
@test x isa Complex
y = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))
@test -10 * log10(abs2(x)) ≈ y atol=0.1
x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0); mode=:incoherent)
@test x isa Complex
@test imag(x) == 0.0
y = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0); mode=:incoherent)
@test -10 * log10(abs2(x)) ≈ y atol=0.1
x1 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))
x2 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))
x3 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -15.0))
x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), [AcousticReceiver(100.0, -d) for d ∈ 5.0:5.0:15.0])
@test x isa AbstractVector
@test [x1, x2, x3] == x
x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 0.0, 1, -5.0, -5.0, 3))
@test x isa AbstractMatrix
@test size(x) == (1, 3)
@test [x1 x2 x3] == x
x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 10.0, 3, -5.0, -5.0, 3))
@test x isa AbstractMatrix
@test size(x) == (3, 3)
@test [x1, x2, x3] == x[1,:]
x1 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))
x2 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))
x3 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -15.0))
x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), [AcousticReceiver(100.0, -d) for d ∈ 5.0:5.0:15.0])
@test x isa AbstractVector
@test [x1, x2, x3] == x
x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 0.0, 1, -5.0, -5.0, 3))
@test x isa AbstractMatrix
@test size(x) == (1, 3)
@test [x1 x2 x3] == x
x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 10.0, 3, -5.0, -5.0, 3))
@test x isa AbstractMatrix
@test size(x) == (3, 3)
@test [x1, x2, x3] == x[1,:]
tx = AcousticSource(0.0, -5.0, 1000.0)
rx = AcousticReceiver(100.0, -10.0)
sig = record(pm, tx, rx, 1.0, 44100.0)
@test size(sig) == (44100,)
sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)
@test size(sig) == (44100,)
sig = recorder(pm, tx, rx)(1.0, 44100.0)
@test size(sig) == (44100,)
sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)
@test size(sig) == (44100,)
tx = [AcousticSource(0.0, -5.0, 1000.0), AcousticSource(0.0, -10.0, 2000.0)]
rx = AcousticReceiver(100.0, -10.0)
sig = record(pm, tx, rx, 1.0, 44100.0)
@test size(sig) == (44100,)
sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)
@test size(sig) == (44100,)
sig = recorder(pm, tx, rx)(1.0, 44100.0)
@test size(sig) == (44100,)
sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)
@test size(sig) == (44100,)
tx = [AcousticSource(0.0, -5.0, 1000.0), AcousticSource(0.0, -10.0, 2000.0)]
rx = [AcousticReceiver(100.0, -10.0), AcousticReceiver(100.0, -15.0)]
sig = record(pm, tx, rx, 1.0, 44100.0)
@test size(sig) == (44100,2)
sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)
@test size(sig) == (44100,2)
sig = recorder(pm, tx, rx)(1.0, 44100.0)
@test size(sig) == (44100,2)
sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)
@test size(sig) == (44100,2)
tx = AcousticSource(0.0, -5.0, 1000.0)
rx = [AcousticReceiver(100.0, -10.0), AcousticReceiver(100.0, -15.0)]
sig = record(pm, tx, rx, 1.0, 44100.0)
@test size(sig) == (44100,2)
sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)
@test size(sig) == (44100,2)
sig = recorder(pm, tx, rx)(1.0, 44100.0)
@test size(sig) == (44100,2)
sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)
@test size(sig) == (44100,2)
env = UnderwaterEnvironment(
seasurface=Vacuum,
ssp=SampledSSP(0.0:5.0:20.0, [1500.0, 1490.0, 1500.0, 1505.0, 1507.0]),
altimetry=SampledAltitude(0.0:25.0:100.0, [0.0, -1.0, 0.0, -1.0, 0.0]),
bathymetry=SampledDepth(0.0:25.0:100.0, [20.0, 17.0, 17.0, 19.0, 20.0])
)
pm = Bellhop(env)
@test pm isa Bellhop
r = eigenrays(pm, AcousticSource(0.0, -5.0, 5000.0), AcousticReceiver(100.0, -10.0))
@test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}
x = transmissionloss(pm, AcousticSource(0.0, -5.0, 5000.0), AcousticReceiverGrid2D(1.0, 1.0, 100, 0.0, -1.0, 20))
@test x isa AbstractMatrix
@test size(x) == (100, 20)
struct TestAlt <: Altimetry end
UnderwaterAcoustics.altitude(::TestAlt, x, y) = -1.0 + sin(2π*x/10.0)
struct TestBathy <: Bathymetry end
UnderwaterAcoustics.depth(::TestBathy, x, y) = 18.0 + 2*sin(2π*x/30.0)
UnderwaterAcoustics.maxdepth(::TestBathy) = 20.0
env = UnderwaterEnvironment(
seasurface=Vacuum,
ssp=MunkSSP(),
altimetry=TestAlt(),
bathymetry=TestBathy()
)
pm = Bellhop(env)
@test pm isa Bellhop
r = eigenrays(pm, AcousticSource(0.0, -5.0, 5000.0), AcousticReceiver(100.0, -10.0))
@test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}
x = transmissionloss(pm, AcousticSource(0.0, -5.0, 5000.0), AcousticReceiverGrid2D(1.0, 1.0, 100, 0.0, -1.0, 20))
@test x isa AbstractMatrix
@test size(x) == (100, 20)
else
@test_skip true
end
end
@testset "pm-raysolver" begin
@test RaySolver in models()
env = UnderwaterEnvironment()
pm = RaySolver(env)
@test pm isa RaySolver
arr = arrivals(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))
@test arr isa AbstractArray{<:UnderwaterAcoustics.RayArrival}
@test length(arr) >= 7
@test arr[1].time ≈ 0.0650 atol=0.0001
@test arr[2].time ≈ 0.0657 atol=0.0001
@test arr[3].time ≈ 0.0670 atol=0.0001
@test all([arr[j].time > arr[j-1].time for j ∈ 2:7])
@test abs(arr[1].phasor) ≈ 0.01 atol=0.001
@test real(arr[2].phasor) < 0.0
@test imag(arr[2].phasor) ≈ 0.0
@test all([abs(arr[j].phasor) < abs(arr[j-1].phasor) for j ∈ 2:7])
@test [(arr[j].surface, arr[j].bottom) for j ∈ 1:7] == [(0,0), (1,0), (0,1), (1,1), (1,1), (2,1), (1,2)]
@test abs.([a.arrivalangle for a ∈ arr]) ≈ abs.([a.launchangle for a ∈ arr])
r = eigenrays(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))
@test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}
@test length(r) >= 7
@test abs.([a.arrivalangle for a ∈ r]) ≈ abs.([a.launchangle for a ∈ r])
@test all([r[j].raypath[1] == (0.0, 0.0, -5.0) for j ∈ 1:7])
#@test all([r[j].raypath[end][k] .≈ (100.0, 0.0, -10.0)[k] for j ∈ 1:7, k ∈ 1:3])
r = rays(pm, AcousticSource(0.0, -5.0, 1000.0), -60°:15°:60°, 100.0)
@test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}
@test length(r) == 9
@test all([r[j].launchangle for j ∈ 1:9] .≈ -60°:15°:60°)
@test abs.([a.arrivalangle for a ∈ r]) ≈ abs.([a.launchangle for a ∈ r])
@test all([r[j].raypath[1] == (0.0, 0.0, -5.0) for j ∈ 1:9])
@test r[4].raypath[end][1] ≥ 99.9
@test r[5].raypath[end][1] ≥ 99.9
@test r[6].raypath[end][1] ≥ 99.9
@test r[7].raypath[end][1] ≥ 99.9
env = UnderwaterEnvironment(ssp=IsoSSP(1500.0), seabed=RayleighReflectionCoef(1.0, 1.0))
pm = RaySolver(env)
d = (√1209.0)/4.0
x = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d))
@test x isa Complex
@test abs(x) ≈ 0.0 atol=0.0002
x′ = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d); mode=:incoherent)
@test x′ isa Complex
@test imag(x′) == 0.0
@test abs(x′) > 1/100.0
d = (√2409.0)/8.0
x = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d))
@test abs(x) > abs(x′)
y = transmissionloss(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d))
@test -10 * log10(abs2(x)) ≈ y atol=0.1
x = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d); mode=:incoherent)
@test abs(x) ≈ abs(x′) atol=0.0001
y = transmissionloss(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d); mode=:incoherent)
@test -10 * log10(abs2(x)) ≈ y atol=0.1
x1 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))
x2 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))
x3 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -15.0))
x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), [AcousticReceiver(100.0, -d) for d ∈ 5.0:5.0:15.0])
@test x isa AbstractVector
@test [x1, x2, x3] == x
x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 0.0, 1, -5.0, -5.0, 3))
@test x isa AbstractMatrix
@test size(x) == (1, 3)
@test [x1 x2 x3] ≈ x atol=0.01
y = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 10.0, 3, -5.0, -5.0, 3))
@test y isa AbstractMatrix
@test size(y) == (3, 3)
@test x' ≈ y[1,:] atol=0.05
x1 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))
x2 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))
x3 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -15.0))
x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), [AcousticReceiver(100.0, -d) for d ∈ 5.0:5.0:15.0])
@test x isa AbstractVector
@test [x1, x2, x3] == x
x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 0.0, 1, -5.0, -5.0, 3))
@test x isa AbstractMatrix
@test size(x) == (1, 3)
@test [x1, x2] ≈ x[1:2] atol=1.5
y = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 10.0, 3, -5.0, -5.0, 3))
@test y isa AbstractMatrix
@test size(y) == (3, 3)
@test x' ≈ y[1,:] atol=0.1
tx = AcousticSource(0.0, -5.0, 1000.0)
rx = AcousticReceiver(100.0, -10.0)
sig = record(pm, tx, rx, 1.0, 44100.0)
@test size(sig) == (44100,)
sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)
@test size(sig) == (44100,)
sig = recorder(pm, tx, rx)(1.0, 44100.0)
@test size(sig) == (44100,)
sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)
@test size(sig) == (44100,)
tx = [AcousticSource(0.0, -5.0, 1000.0), AcousticSource(0.0, -10.0, 2000.0)]
rx = AcousticReceiver(100.0, -10.0)
sig = record(pm, tx, rx, 1.0, 44100.0)
@test size(sig) == (44100,)
sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)
@test size(sig) == (44100,)
sig = recorder(pm, tx, rx)(1.0, 44100.0)
@test size(sig) == (44100,)
sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)
@test size(sig) == (44100,)
tx = [AcousticSource(0.0, -5.0, 1000.0), AcousticSource(0.0, -10.0, 2000.0)]
rx = [AcousticReceiver(100.0, -10.0), AcousticReceiver(100.0, -15.0)]
sig = record(pm, tx, rx, 1.0, 44100.0)
@test size(sig) == (44100,2)
sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)
@test size(sig) == (44100,2)
sig = recorder(pm, tx, rx)(1.0, 44100.0)
@test size(sig) == (44100,2)
sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)
@test size(sig) == (44100,2)
tx = AcousticSource(0.0, -5.0, 1000.0)
rx = [AcousticReceiver(100.0, -10.0), AcousticReceiver(100.0, -15.0)]
sig = record(pm, tx, rx, 1.0, 44100.0)
@test size(sig) == (44100,2)
sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)
@test size(sig) == (44100,2)
sig = recorder(pm, tx, rx)(1.0, 44100.0)
@test size(sig) == (44100,2)
sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)
@test size(sig) == (44100,2)
end
function ∂(f, x, i, ϵ)
x1 = copy(x)
x1[i] = x[i] + ϵ
f1 = f(x1)
x1[i] = x[i] - ϵ
(f1 - f(x1)) / (2ϵ)
end
@testset "pm-∂pekeris" begin
function ℳ(x)
D, R, d1, d2, f, c = x
env = UnderwaterEnvironment(ssp=IsoSSP(c), bathymetry=ConstantDepth(D))
pm = PekerisRayModel(env, 7)
transmissionloss(pm, AcousticSource(0.0, -d1, f), AcousticReceiver(R, -d2))
end
x = [20.0, 100.0, 5.0, 10.0, 5000.0, 1500.0]
∇ℳ = ForwardDiff.gradient(ℳ, x)
for i ∈ 1:length(x)
@test ∇ℳ[i] ≈ ∂(ℳ, x, i, 0.0001) atol=0.1
end
x = [25.0, 200.0, 10.0, 8.0, 1000.0, 1540.0]
∇ℳ = ForwardDiff.gradient(ℳ, x)
for i ∈ 1:length(x)
@test ∇ℳ[i] ≈ ∂(ℳ, x, i, 0.0001) atol=0.1
end
end
@testset "pm-∂raysolver" begin
function ℳ₁(x)
D, R, d1, d2, f, c = x
env = UnderwaterEnvironment(ssp=IsoSSP(c), bathymetry=ConstantDepth(D))
pm = RaySolver(env)
transmissionloss(pm, AcousticSource(0.0, -d1, f), AcousticReceiver(R, -d2))
end
function ℳ₂(x)
D, R, d1, d2, f, c = x
env = UnderwaterEnvironment(ssp=IsoSSP(c), bathymetry=ConstantDepth(D))
pm = RaySolver(env)
transmissionloss(pm, AcousticSource(0.0, -d1, f), AcousticReceiverGrid2D(R, 0.0, 1, -d2, 0.0, 1))[1,1]
end
x = [20.0, 100.0, 5.0, 10.0, 5000.0, 1500.0]
∇ℳ = ForwardDiff.gradient(ℳ₁, x)
for i ∈ 1:length(x)
# skip i = 2 because it is not yet supported
i != 2 && @test ∇ℳ[i] ≈ ∂(ℳ₁, x, i, 0.0001) atol=0.1
end
x = [25.0, 200.0, 10.0, 8.0, 1000.0, 1540.0]
∇ℳ = ForwardDiff.gradient(ℳ₁, x)
for i ∈ 1:length(x)
# skip i = 2 because it is not yet supported
i != 2 && @test ∇ℳ[i] ≈ ∂(ℳ₁, x, i, 0.0001) atol=0.1
end
x = [20.0, 100.0, 5.0, 10.0, 5000.0, 1500.0]
∇ℳ = ForwardDiff.gradient(ℳ₂, x)
for i ∈ 1:length(x)
@test ∇ℳ[i] ≈ ∂(ℳ₂, x, i, 0.0001) atol=0.1
end
x = [25.0, 200.0, 10.0, 8.0, 1000.0, 1540.0]
∇ℳ = ForwardDiff.gradient(ℳ₂, x)
for i ∈ 1:length(x)
@test ∇ℳ[i] ≈ ∂(ℳ₂, x, i, 0.0001) atol=0.1
end
end
| 43.339005
| 118
| 0.627495
|
[
"@testset \"basic\" begin\n\n @test soundspeed() ≈ 1539.0 atol=0.1\n @test soundspeed(; voidfrac=1e-5) ≈ 1402.1 atol=0.1\n @test soundspeed(; voidfrac=1.0) ≈ 340.0\n\n @test amp2db(absorption(10000, 1000.0, 35.0, 15.0)) ≈ -1.0 atol=0.5\n @test amp2db(absorption(50000)) ≈ -11.0 atol=0.5\n @test amp2db(absorption(100000)) ≈ -36.0 atol=0.5\n @test amp2db(absorption(100000, 1000.0, 38.5, 14.0, 0.0)) ≈ -40.0 atol=0.5\n @test amp2db(absorption(100000, 1000.0, 38.5, 14.0, 2000.0)) ≈ -30.0 atol=0.5\n @test amp2db(absorption(100000, 1000.0, 38.5, 14.0, 6000.0)) ≈ -16.0 atol=0.5\n\n @test waterdensity() ≈ 1022.7 atol=0.1\n\n @test reflectioncoef(0.0, 1200.0/1023.0, 1600.0/1540.0, 0.0) isa Complex\n @test reflectioncoef(0.0, 1200.0/1023.0, 1600.0/1540.0, 0.0) ≈ 0.0986 atol=0.0001\n @test amp2db(abs(reflectioncoef(0.0, 2.5, 2.5, 0.01374))) ≈ -2.8 atol=0.1\n @test amp2db(abs(reflectioncoef(0.0, 2.492, 1.3370, 0.01705))) ≈ -5 atol=0.5\n @test amp2db(abs(reflectioncoef(0.0, 1.195, 1.0179, 0.02158))) ≈ -20 atol=0.5\n @test amp2db(abs(reflectioncoef(1.22, 1.149, 0.9873, 0.00386))) ≈ -32 atol=0.5\n\n @test amp2db(surfaceloss(15.0, 20000.0, 80°)) ≈ -6.5 atol=0.1\n @test amp2db(surfaceloss(10.0, 20000.0, 80°)) ≈ -3.4 atol=0.1\n @test amp2db(surfaceloss(5.0, 20000.0, 80°)) ≈ -0.5 atol=0.1\n\n @test doppler(0.0, 50000.0) == 50000.0\n @test doppler(10.0, 50000.0) ≈ 50325 atol=0.5\n @test doppler(-10.0, 50000.0) ≈ 49675 atol=0.5\n\n @test bubbleresonance(100e-6) ≈ 32500.0 atol=0.1\n @test bubbleresonance(32e-6) ≈ 101562.5 atol=0.1\n @test bubbleresonance(100e-6, 10.0) ≈ 45962.0 atol=0.1\n\nend",
"@testset \"pm-core-basic\" begin\n\n env = UnderwaterEnvironment()\n\n @test models() isa AbstractArray\n @test models(env) isa AbstractArray\n\n @test env isa UnderwaterAcoustics.BasicUnderwaterEnvironment\n @test altimetry(env) isa Altimetry\n @test bathymetry(env) isa Bathymetry\n @test ssp(env) isa SoundSpeedProfile\n @test salinity(env) isa Real\n @test seasurface(env) isa ReflectionModel\n @test seabed(env) isa ReflectionModel\n @test noise(env) isa NoiseModel\n\n @test altitude(altimetry(env), 0.0, 0.0) isa Real\n @test depth(bathymetry(env), 0.0, 0.0) isa Real\n @test soundspeed(ssp(env), 0.0, 0.0, 0.0) isa Real\n @test reflectioncoef(seasurface(env), 1000.0, 0.0) isa Complex\n @test reflectioncoef(seabed(env), 1000.0, 0.0) isa Complex\n sig = record(noise(env), 1.0, 44100.0)\n @test length(sig) == 44100\n @test sum(abs2.(sig)) > 0.0\n\n @test AcousticReceiver(0.0, 0.0) isa AcousticReceiver\n @test location(AcousticReceiver(100.0, 10.0, -50.0)) == (100, 10.0, -50.0)\n @test location(AcousticReceiver(100.0, -50.0)) == (100, 0.0, -50.0)\n\n src = AcousticSource(100.0, 10.0, -50.0, 4410.0; sourcelevel=1.0)\n sig = record(src, 1.0, 44100.0)\n @test src isa NarrowbandAcousticSource\n @test location(src) == (100.0, 10.0, -50.0)\n @test location(AcousticSource(100.0, -50.0, 1000.0)) == (100.0, 0.0, -50.0)\n @test nominalfrequency(src) == 4410.0\n @test phasor(src) == complex(1.0, 0.0)\n @test length(sig) == 44100\n @test eltype(sig) <: Complex\n @test sum(abs2.(sig))/44100.0 ≈ 1.0 atol=1e-4\n @test sig[1] != sig[2]\n @test sig[1] ≈ sig[11]\n @test sig[2] ≈ sig[12]\n src = Pinger(10.0, -10.0, 1000.0; sourcelevel=1.0, interval=0.5)\n sig = record(src, 1.0, 44100.0)\n @test src isa AcousticSource\n @test location(src) == (10.0, 0.0, -10.0)\n @test nominalfrequency(src) == 1000.0\n @test phasor(src) == complex(1.0, 0.0)\n @test length(sig) == 44100\n @test eltype(sig) <: Complex\n @test sum(abs2.(sig))/44100.0 ≈ 0.04 atol=1e-4\n @test maximum(abs2.(sig)) ≈ 1.0 atol=1e-4\n src = SampledAcousticSource(10.0, -10.0, ones(1000); fs=1000.0, frequency=100.0)\n @test src isa SampledAcousticSource\n @test location(src) == (10.0, 0.0, -10.0)\n @test nominalfrequency(src) == 100.0\n sig = record(src, 1.0, 1000.0)\n @test length(sig) == 1000\n @test eltype(sig) === Float64\n @test all(sig .== 1.0)\n sig = record(src, 1.0, 1000.0; start=-0.5)\n @test length(sig) == 1000\n @test eltype(sig) === Float64\n @test all(sig[1:500] .== 0.0)\n @test all(sig[501:1000] .== 1.0)\n sig = record(src, 1.0, 1000.0; start=0.5)\n @test length(sig) == 1000\n @test eltype(sig) === Float64\n @test all(sig[1:500] .== 1.0)\n @test all(sig[501:1000] .== 0.0)\n sig = record(src, 1.0, 1000.0; start=-2.0)\n @test length(sig) == 1000\n @test eltype(sig) === Float64\n @test all(sig .== 0.0)\n sig = record(src, 1.0, 1000.0; start=2.0)\n @test length(sig) == 1000\n @test eltype(sig) === Float64\n @test all(sig .== 0.0)\n @test_throws ArgumentError record(src, 1.0, 2000.0)\n src = SampledAcousticSource(10.0, 5.0, -10.0, cis.(2π * 1000 * (0:999) ./ 10000.0); fs=10000.0)\n @test src isa SampledAcousticSource\n @test location(src) == (10.0, 5.0, -10.0)\n @test nominalfrequency(src) == 1000.0\n sig = record(src, 0.1, 10000.0)\n @test length(sig) == 1000\n @test eltype(sig) === ComplexF64\n\n @test IsoSSP(1500.0) isa SoundSpeedProfile\n @test soundspeed(IsoSSP(1500.0), 100.0, 10.0, -50.0) == 1500.0\n @test MunkSSP() isa SoundSpeedProfile\n @test soundspeed(MunkSSP(), 0.0, 0.0, -2000.0) ≈ 1505.0 atol=1.0\n @test soundspeed(MunkSSP(), 0.0, 0.0, -3000.0) ≈ 1518.0 atol=1.0\n s = SampledSSP(0.0:500.0:1000.0, [1500.0, 1520.0, 1510.0])\n @test s isa SoundSpeedProfile\n @test soundspeed(s, 0.0, 0.0, 0.0) ≈ 1500.0\n @test soundspeed(s, 0.0, 0.0, -250.0) ≈ 1510.0\n @test soundspeed(s, 0.0, 0.0, -500.0) ≈ 1520.0\n @test soundspeed(s, 0.0, 0.0, -750.0) ≈ 1515.0\n @test soundspeed(s, 0.0, 0.0, -1000.0) ≈ 1510.0\n s = SampledSSP(0.0:500.0:1000.0, [1500.0, 1520.0, 1510.0], :smooth)\n @test s isa SoundSpeedProfile\n @test soundspeed(s, 0.0, 0.0, 0.0) ≈ 1500.0\n @test soundspeed(s, 0.0, 0.0, -250.0) > 1510.0\n @test soundspeed(s, 0.0, 0.0, -500.0) ≈ 1520.0\n @test soundspeed(s, 0.0, 0.0, -750.0) > 1515.0\n @test soundspeed(s, 0.0, 0.0, -1000.0) ≈ 1510.0\n\n @test ConstantDepth(20.0) isa Bathymetry\n @test depth(ConstantDepth(20.0), 0.0, 0.0) == 20.0\n @test maxdepth(ConstantDepth(20.0)) == 20.0\n b = SampledDepth(0.0:500.0:1000.0, [20.0, 25.0, 15.0])\n @test b isa Bathymetry\n @test depth(b, 0.0, 0.0) ≈ 20.0\n @test depth(b, 250.0, 0.0) ≈ 22.5\n @test depth(b, 500.0, 0.0) ≈ 25.0\n @test depth(b, 750.0, 0.0) ≈ 20.0\n @test depth(b, 1000.0, 0.0) ≈ 15.0\n @test maxdepth(b) ≈ 25.0\n b = SampledDepth(0.0:500.0:1000.0, [20.0, 25.0, 15.0], :smooth)\n @test b isa Bathymetry\n @test depth(b, 0.0, 0.0) ≈ 20.0\n @test depth(b, 250.0, 0.0) > 22.5\n @test depth(b, 500.0, 0.0) ≈ 25.0\n @test depth(b, 750.0, 0.0) > 20.0\n @test depth(b, 1000.0, 0.0) ≈ 15.0\n @test maxdepth(b) ≈ 25.0\n\n @test FlatSurface() isa Altimetry\n @test altitude(FlatSurface(), 0.0, 0.0) == 0.0\n a = SampledAltitude(0.0:500.0:1000.0, [0.0, 1.0, -1.0])\n @test a isa Altimetry\n @test altitude(a, 0.0, 0.0) ≈ 0.0\n @test altitude(a, 250.0, 0.0) ≈ 0.5\n @test altitude(a, 500.0, 0.0) ≈ 1.0\n @test altitude(a, 750.0, 0.0) ≈ 0.0\n @test altitude(a, 1000.0, 0.0) ≈ -1.0\n a = SampledAltitude(0.0:500.0:1000.0, [0.0, 1.0, -1.0], :smooth)\n @test a isa Altimetry\n @test altitude(a, 0.0, 0.0) ≈ 0.0 atol=1e-6\n @test altitude(a, 250.0, 0.0) > 0.5\n @test altitude(a, 500.0, 0.0) ≈ 1.0 atol=1e-6\n @test altitude(a, 1000.0, 0.0) ≈ -1.0 atol=1e-6\n\n @test ReflectionCoef(0.5 + 0.3im) isa ReflectionModel\n @test reflectioncoef(ReflectionCoef(0.5 + 0.3im), 1000.0, 0.0) == 0.5 + 0.3im\n @test RayleighReflectionCoef(1.0, 1.0) isa ReflectionModel\n @test RayleighReflectionCoef(1.0, 1.0, 0.0) isa ReflectionModel\n @test reflectioncoef(RayleighReflectionCoef(1.0, 1.0, 0.0), 1000.0, 0.0) ≈ 0.0\n @test reflectioncoef(RayleighReflectionCoef(0.0, 1.0, 0.0), 1000.0, 0.0) ≈ -1.0\n @test Rock isa RayleighReflectionCoef\n @test Pebbles isa RayleighReflectionCoef\n @test SandyGravel isa RayleighReflectionCoef\n @test CoarseSand isa RayleighReflectionCoef\n @test MediumSand isa RayleighReflectionCoef\n @test FineSand isa RayleighReflectionCoef\n @test VeryFineSand isa RayleighReflectionCoef\n @test ClayeySand isa RayleighReflectionCoef\n @test CoarseSilt isa RayleighReflectionCoef\n @test SandySilt isa RayleighReflectionCoef\n @test Silt isa RayleighReflectionCoef\n @test FineSilt isa RayleighReflectionCoef\n @test SandyClay isa RayleighReflectionCoef\n @test SiltyClay isa RayleighReflectionCoef\n @test Clay isa RayleighReflectionCoef\n @test Vacuum isa ReflectionModel\n @test reflectioncoef(Vacuum, 1000.0, 0.0) ≈ -1.0\n @test 0.0 < abs(reflectioncoef(Rock, 1000.0, 0.0)) < 1.0\n @test abs(reflectioncoef(Silt, 1000.0, 0.0)) < abs(reflectioncoef(SandyGravel, 1000.0, 0.0))\n @test abs(reflectioncoef(CoarseSilt, 1000.0, 0.0)) < abs(reflectioncoef(Rock, 1000.0, 0.0))\n @test SurfaceLoss(5.0) isa ReflectionModel\n @test SeaState0 isa SurfaceLoss\n @test SeaState1 isa SurfaceLoss\n @test SeaState2 isa SurfaceLoss\n @test SeaState3 isa SurfaceLoss\n @test SeaState4 isa SurfaceLoss\n @test SeaState5 isa SurfaceLoss\n @test SeaState6 isa SurfaceLoss\n @test SeaState7 isa SurfaceLoss\n @test SeaState8 isa SurfaceLoss\n @test SeaState9 isa SurfaceLoss\n @test 0.0 < abs(reflectioncoef(SeaState2, 1000.0, 0.0)) < 1.0\n @test abs(reflectioncoef(SeaState2, 1000.0, 0.0)) > abs(reflectioncoef(SeaState5, 1000.0, 0.0))\n @test abs(reflectioncoef(SeaState5, 1000.0, 0.0)) > abs(reflectioncoef(SeaState5, 2000.0, 0.0))\n\n rx = AcousticReceiverGrid2D(100.0, 2.0, 100, -100.0, 5.0, 10)\n @test rx isa AcousticReceiverGrid2D\n @test rx isa AbstractMatrix\n @test size(rx) == (100, 10)\n @test rx[1,1] == AcousticReceiver(100.0, -100.0)\n @test rx[end,end] == AcousticReceiver(298.0, -55.0)\n rx = AcousticReceiverGrid3D(100.0, 2.0, 100, 0.0, 1.0, 100, -100.0, 5.0, 10)\n @test rx isa AcousticReceiverGrid3D\n @test rx isa AbstractArray\n @test size(rx) == (100, 100, 10)\n @test rx[1,1,1] == AcousticReceiver(100.0, 0.0, -100.0)\n @test rx[end,end,end] == AcousticReceiver(298.0, 99.0, -55.0)\n\nend",
"@testset \"pm-pekeris\" begin\n\n @test PekerisRayModel in models()\n\n env = UnderwaterEnvironment()\n pm = PekerisRayModel(env, 7)\n @test pm isa PekerisRayModel\n\n arr = arrivals(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))\n @test arr isa AbstractArray{<:UnderwaterAcoustics.RayArrival}\n @test length(arr) == 7\n @test arr[1].time ≈ 0.0650 atol=0.0001\n @test arr[2].time ≈ 0.0657 atol=0.0001\n @test arr[3].time ≈ 0.0670 atol=0.0001\n @test all([arr[j].time > arr[j-1].time for j ∈ 2:7])\n @test abs(arr[1].phasor) ≈ 0.01 atol=0.001\n @test real(arr[2].phasor) < 0.0\n @test imag(arr[2].phasor) ≈ 0.0\n @test all([abs(arr[j].phasor) < abs(arr[j-1].phasor) for j ∈ 2:7])\n @test [(arr[j].surface, arr[j].bottom) for j ∈ 1:7] == [(0,0), (1,0), (0,1), (1,1), (1,1), (2,1), (1,2)]\n @test all([abs(arr[j].arrivalangle) == abs(arr[j].launchangle) for j ∈ 1:7])\n\n r = eigenrays(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))\n @test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}\n @test length(r) == 7\n @test all([abs(r[j].arrivalangle) == abs(r[j].launchangle) for j ∈ 1:7])\n @test all([r[j].raypath[1] == (0.0, 0.0, -5.0) for j ∈ 1:7])\n @test all([r[j].raypath[end] == (100.0, 0.0, -10.0) for j ∈ 1:7])\n @test all([length(r[j].raypath) == r[j].surface + r[j].bottom + 2 for j ∈ 1:7])\n\n r = rays(pm, AcousticSource(0.0, -5.0, 1000.0), -60°:15°:60°, 100.0)\n @test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}\n @test length(r) == 9\n @test all([r[j].launchangle for j ∈ 1:9] .≈ -60°:15°:60°)\n @test all([abs(r[j].arrivalangle) == abs(r[j].launchangle) for j ∈ 1:9])\n @test all([r[j].raypath[1] == (0.0, 0.0, -5.0) for j ∈ 1:9])\n @test all([r[j].raypath[end][1] ≥ 100.0 for j ∈ 1:9])\n @test all([length(r[j].raypath) == r[j].surface + r[j].bottom + 2 for j ∈ 1:9])\n\n ir1 = impulseresponse(arr, 10000.0; reltime=true, approx=true)\n ir2 = impulseresponse(arr, 10000.0; reltime=false, approx=true)\n @test length(ir2) ≈ length(ir1) + round(Int, 10000.0 * arr[1].time) atol=1\n @test length(ir2) == round(Int, 10000.0 * arr[end].time) + 1\n @test sum(ir1 .!= 0.0) == 7\n @test sum(ir2 .!= 0.0) == 7\n ndx = findall(abs.(ir1) .> 0)\n @test (ndx .- 1) ./ 10000.0 ≈ [arr[j].time - arr[1].time for j ∈ 1:7] atol=1e-4\n ndx = findall(abs.(ir2) .> 0)\n @test (ndx .- 1) ./ 10000.0 ≈ [arr[j].time for j ∈ 1:7] atol=1e-4\n\n ir1a = impulseresponse(arr, 10000.0; reltime=true)\n ir2a = impulseresponse(arr, 10000.0; reltime=false)\n @test length(ir2a) ≈ length(ir1a) + round(Int, 10000.0 * arr[1].time) atol=1\n @test length(ir2a) ≥ length(ir2)\n @test sum(abs2.(ir1a))/sum(abs2.(ir1)) ≈ 1.0 atol=0.05\n @test sum(abs2.(ir2a))/sum(abs2.(ir2)) ≈ 1.0 atol=0.05\n\n @test length(impulseresponse(arr, 10000.0, 256; reltime=true, approx=true)) == 256\n @test length(impulseresponse(arr, 10000.0, 64; reltime=true, approx=true)) == 64\n @test length(impulseresponse(arr, 10000.0, 256; reltime=true, approx=false)) == 256\n @test length(impulseresponse(arr, 10000.0, 64; reltime=true, approx=false)) == 64\n @test length(impulseresponse(arr, 10000.0, 1024; reltime=false, approx=true)) == 1024\n @test length(impulseresponse(arr, 10000.0, 700; reltime=false, approx=true)) == 700\n @test length(impulseresponse(arr, 10000.0, 1024; reltime=false, approx=false)) == 1024\n @test length(impulseresponse(arr, 10000.0, 700; reltime=false, approx=false)) == 700\n\n env = UnderwaterEnvironment(ssp=IsoSSP(1500.0))\n pm = PekerisRayModel(env, 2)\n d = (√1209.0)/4.0\n x = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d))\n @test x isa Complex\n @test abs(x) ≈ 0.0 atol=0.0002\n x′ = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d); mode=:incoherent)\n @test x′ isa Complex\n @test imag(x′) == 0.0\n @test abs(x′) > 1/100.0\n d = (√2409.0)/8.0\n x = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d))\n @test abs(x) > abs(x′)\n y = transmissionloss(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d))\n @test -10 * log10(abs2(x)) ≈ y atol=0.1\n x = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d); mode=:incoherent)\n @test abs(x) ≈ abs(x′) atol=0.0001\n y = transmissionloss(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d); mode=:incoherent)\n @test -10 * log10(abs2(x)) ≈ y atol=0.1\n x1 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))\n x2 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))\n x3 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -15.0))\n x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), [AcousticReceiver(100.0, -d) for d ∈ 5.0:5.0:15.0])\n @test x isa AbstractVector\n @test [x1, x2, x3] == x\n x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 0.0, 1, -5.0, -5.0, 3))\n @test x isa AbstractMatrix\n @test size(x) == (1, 3)\n @test [x1 x2 x3] == x\n x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 10.0, 3, -5.0, -5.0, 3))\n @test x isa AbstractMatrix\n @test size(x) == (3, 3)\n @test [x1, x2, x3] == x[1,:]\n x1 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))\n x2 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))\n x3 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -15.0))\n x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), [AcousticReceiver(100.0, -d) for d ∈ 5.0:5.0:15.0])\n @test x isa AbstractVector\n @test [x1, x2, x3] == x\n x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 0.0, 1, -5.0, -5.0, 3))\n @test x isa AbstractMatrix\n @test size(x) == (1, 3)\n @test [x1 x2 x3] == x\n x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 10.0, 3, -5.0, -5.0, 3))\n @test x isa AbstractMatrix\n @test size(x) == (3, 3)\n @test [x1, x2, x3] == x[1,:]\n\n env = UnderwaterEnvironment()\n pm = PekerisRayModel(env, 7)\n tx = AcousticSource(0.0, -5.0, 1000.0)\n rx = AcousticReceiver(100.0, -10.0)\n sig = record(pm, tx, rx, 1.0, 44100.0)\n @test size(sig) == (44100,)\n sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,)\n sig = recorder(pm, tx, rx)(1.0, 44100.0)\n @test size(sig) == (44100,)\n sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,)\n tx = [AcousticSource(0.0, -5.0, 1000.0), AcousticSource(0.0, -10.0, 2000.0)]\n rx = AcousticReceiver(100.0, -10.0)\n sig = record(pm, tx, rx, 1.0, 44100.0)\n @test size(sig) == (44100,)\n sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,)\n sig = recorder(pm, tx, rx)(1.0, 44100.0)\n @test size(sig) == (44100,)\n sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,)\n tx = [AcousticSource(0.0, -5.0, 1000.0), AcousticSource(0.0, -10.0, 2000.0)]\n rx = [AcousticReceiver(100.0, -10.0), AcousticReceiver(100.0, -15.0)]\n sig = record(pm, tx, rx, 1.0, 44100.0)\n @test size(sig) == (44100,2)\n sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,2)\n sig = recorder(pm, tx, rx)(1.0, 44100.0)\n @test size(sig) == (44100,2)\n sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,2)\n tx = AcousticSource(0.0, -5.0, 1000.0)\n rx = [AcousticReceiver(100.0, -10.0), AcousticReceiver(100.0, -15.0)]\n sig = record(pm, tx, rx, 1.0, 44100.0)\n @test size(sig) == (44100,2)\n sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,2)\n sig = recorder(pm, tx, rx)(1.0, 44100.0)\n @test size(sig) == (44100,2)\n sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,2)\n\n env = UnderwaterEnvironment(noise=missing)\n pm = PekerisRayModel(env, 7)\n tx = Pinger(0.0, -5.0, 1000.0; interval=0.3)\n rx = AcousticReceiver(100.0, -10.0)\n sig1 = record(pm, tx, rx, 1.0, 44100.0)\n @test size(sig1) == (44100,)\n sig2 = record(pm, tx, rx, 1.0, 44100.0; start=0.5)\n @test size(sig2) == (44100,)\n @test sig1[22051:end] ≈ sig2[1:22050]\n rx = AcousticReceiver(100.0, -11.0)\n sig3 = record(pm, tx, rx, 1.0, 44100.0)\n @test size(sig3) == (44100,)\n @test !(sig1 ≈ sig3)\n rx = AcousticReceiver(100.0/√2, 100.0/√2, -10.0)\n sig3 = record(pm, tx, rx, 1.0, 44100.0)\n @test size(sig3) == (44100,)\n @test sig1 ≈ sig3\n tx = [Pinger(0.0, -5.0, 1000.0; interval=0.3), Pinger(1.0, -5.0, 2000.0; interval=0.5)]\n rx = AcousticReceiver(100.0, 0.0, -10.0)\n sig1 = record(pm, tx, rx, 1.0, 44100.0)\n rx = AcousticReceiver(100.0/√2, 100.0/√2, -10.0)\n rx = AcousticReceiver(-100.0, 0.0, -10.0)\n sig2 = record(pm, tx, rx, 1.0, 44100.0)\n @test !(sig1 ≈ sig2)\n\nend",
"@testset \"pm-bellhop\" begin\n\n if Bellhop in models()\n\n env = UnderwaterEnvironment(seasurface=Vacuum)\n pm = Bellhop(env)\n @test pm isa Bellhop\n\n arr = arrivals(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))\n @test arr isa AbstractArray{<:UnderwaterAcoustics.RayArrival}\n r = eigenrays(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))\n @test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}\n r = rays(pm, AcousticSource(0.0, -5.0, 1000.0), -60°:15°:60°, 100.0)\n @test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}\n x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))\n @test x isa Complex\n y = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))\n @test -10 * log10(abs2(x)) ≈ y atol=0.1\n x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0); mode=:incoherent)\n @test x isa Complex\n @test imag(x) == 0.0\n y = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0); mode=:incoherent)\n @test -10 * log10(abs2(x)) ≈ y atol=0.1\n x1 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))\n x2 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))\n x3 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -15.0))\n x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), [AcousticReceiver(100.0, -d) for d ∈ 5.0:5.0:15.0])\n @test x isa AbstractVector\n @test [x1, x2, x3] == x\n x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 0.0, 1, -5.0, -5.0, 3))\n @test x isa AbstractMatrix\n @test size(x) == (1, 3)\n @test [x1 x2 x3] == x\n x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 10.0, 3, -5.0, -5.0, 3))\n @test x isa AbstractMatrix\n @test size(x) == (3, 3)\n @test [x1, x2, x3] == x[1,:]\n x1 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))\n x2 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))\n x3 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -15.0))\n x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), [AcousticReceiver(100.0, -d) for d ∈ 5.0:5.0:15.0])\n @test x isa AbstractVector\n @test [x1, x2, x3] == x\n x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 0.0, 1, -5.0, -5.0, 3))\n @test x isa AbstractMatrix\n @test size(x) == (1, 3)\n @test [x1 x2 x3] == x\n x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 10.0, 3, -5.0, -5.0, 3))\n @test x isa AbstractMatrix\n @test size(x) == (3, 3)\n @test [x1, x2, x3] == x[1,:]\n\n tx = AcousticSource(0.0, -5.0, 1000.0)\n rx = AcousticReceiver(100.0, -10.0)\n sig = record(pm, tx, rx, 1.0, 44100.0)\n @test size(sig) == (44100,)\n sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,)\n sig = recorder(pm, tx, rx)(1.0, 44100.0)\n @test size(sig) == (44100,)\n sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,)\n tx = [AcousticSource(0.0, -5.0, 1000.0), AcousticSource(0.0, -10.0, 2000.0)]\n rx = AcousticReceiver(100.0, -10.0)\n sig = record(pm, tx, rx, 1.0, 44100.0)\n @test size(sig) == (44100,)\n sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,)\n sig = recorder(pm, tx, rx)(1.0, 44100.0)\n @test size(sig) == (44100,)\n sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,)\n tx = [AcousticSource(0.0, -5.0, 1000.0), AcousticSource(0.0, -10.0, 2000.0)]\n rx = [AcousticReceiver(100.0, -10.0), AcousticReceiver(100.0, -15.0)]\n sig = record(pm, tx, rx, 1.0, 44100.0)\n @test size(sig) == (44100,2)\n sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,2)\n sig = recorder(pm, tx, rx)(1.0, 44100.0)\n @test size(sig) == (44100,2)\n sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,2)\n tx = AcousticSource(0.0, -5.0, 1000.0)\n rx = [AcousticReceiver(100.0, -10.0), AcousticReceiver(100.0, -15.0)]\n sig = record(pm, tx, rx, 1.0, 44100.0)\n @test size(sig) == (44100,2)\n sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,2)\n sig = recorder(pm, tx, rx)(1.0, 44100.0)\n @test size(sig) == (44100,2)\n sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,2)\n\n env = UnderwaterEnvironment(\n seasurface=Vacuum,\n ssp=SampledSSP(0.0:5.0:20.0, [1500.0, 1490.0, 1500.0, 1505.0, 1507.0]),\n altimetry=SampledAltitude(0.0:25.0:100.0, [0.0, -1.0, 0.0, -1.0, 0.0]),\n bathymetry=SampledDepth(0.0:25.0:100.0, [20.0, 17.0, 17.0, 19.0, 20.0])\n )\n pm = Bellhop(env)\n @test pm isa Bellhop\n r = eigenrays(pm, AcousticSource(0.0, -5.0, 5000.0), AcousticReceiver(100.0, -10.0))\n @test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}\n x = transmissionloss(pm, AcousticSource(0.0, -5.0, 5000.0), AcousticReceiverGrid2D(1.0, 1.0, 100, 0.0, -1.0, 20))\n @test x isa AbstractMatrix\n @test size(x) == (100, 20)\n\n struct TestAlt <: Altimetry end\n UnderwaterAcoustics.altitude(::TestAlt, x, y) = -1.0 + sin(2π*x/10.0)\n\n struct TestBathy <: Bathymetry end\n UnderwaterAcoustics.depth(::TestBathy, x, y) = 18.0 + 2*sin(2π*x/30.0)\n UnderwaterAcoustics.maxdepth(::TestBathy) = 20.0\n\n env = UnderwaterEnvironment(\n seasurface=Vacuum,\n ssp=MunkSSP(),\n altimetry=TestAlt(),\n bathymetry=TestBathy()\n )\n pm = Bellhop(env)\n @test pm isa Bellhop\n r = eigenrays(pm, AcousticSource(0.0, -5.0, 5000.0), AcousticReceiver(100.0, -10.0))\n @test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}\n x = transmissionloss(pm, AcousticSource(0.0, -5.0, 5000.0), AcousticReceiverGrid2D(1.0, 1.0, 100, 0.0, -1.0, 20))\n @test x isa AbstractMatrix\n @test size(x) == (100, 20)\n\n else\n @test_skip true\n end\n\nend",
"@testset \"pm-raysolver\" begin\n\n @test RaySolver in models()\n\n env = UnderwaterEnvironment()\n pm = RaySolver(env)\n @test pm isa RaySolver\n\n arr = arrivals(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))\n @test arr isa AbstractArray{<:UnderwaterAcoustics.RayArrival}\n @test length(arr) >= 7\n @test arr[1].time ≈ 0.0650 atol=0.0001\n @test arr[2].time ≈ 0.0657 atol=0.0001\n @test arr[3].time ≈ 0.0670 atol=0.0001\n @test all([arr[j].time > arr[j-1].time for j ∈ 2:7])\n @test abs(arr[1].phasor) ≈ 0.01 atol=0.001\n @test real(arr[2].phasor) < 0.0\n @test imag(arr[2].phasor) ≈ 0.0\n @test all([abs(arr[j].phasor) < abs(arr[j-1].phasor) for j ∈ 2:7])\n @test [(arr[j].surface, arr[j].bottom) for j ∈ 1:7] == [(0,0), (1,0), (0,1), (1,1), (1,1), (2,1), (1,2)]\n @test abs.([a.arrivalangle for a ∈ arr]) ≈ abs.([a.launchangle for a ∈ arr])\n\n r = eigenrays(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))\n @test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}\n @test length(r) >= 7\n @test abs.([a.arrivalangle for a ∈ r]) ≈ abs.([a.launchangle for a ∈ r])\n @test all([r[j].raypath[1] == (0.0, 0.0, -5.0) for j ∈ 1:7])\n #@test all([r[j].raypath[end][k] .≈ (100.0, 0.0, -10.0)[k] for j ∈ 1:7, k ∈ 1:3])\n\n r = rays(pm, AcousticSource(0.0, -5.0, 1000.0), -60°:15°:60°, 100.0)\n @test r isa AbstractArray{<:UnderwaterAcoustics.RayArrival}\n @test length(r) == 9\n @test all([r[j].launchangle for j ∈ 1:9] .≈ -60°:15°:60°)\n @test abs.([a.arrivalangle for a ∈ r]) ≈ abs.([a.launchangle for a ∈ r])\n @test all([r[j].raypath[1] == (0.0, 0.0, -5.0) for j ∈ 1:9])\n @test r[4].raypath[end][1] ≥ 99.9\n @test r[5].raypath[end][1] ≥ 99.9\n @test r[6].raypath[end][1] ≥ 99.9\n @test r[7].raypath[end][1] ≥ 99.9\n\n env = UnderwaterEnvironment(ssp=IsoSSP(1500.0), seabed=RayleighReflectionCoef(1.0, 1.0))\n pm = RaySolver(env)\n d = (√1209.0)/4.0\n x = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d))\n @test x isa Complex\n @test abs(x) ≈ 0.0 atol=0.0002\n x′ = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d); mode=:incoherent)\n @test x′ isa Complex\n @test imag(x′) == 0.0\n @test abs(x′) > 1/100.0\n d = (√2409.0)/8.0\n x = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d))\n @test abs(x) > abs(x′)\n y = transmissionloss(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d))\n @test -10 * log10(abs2(x)) ≈ y atol=0.1\n x = transfercoef(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d); mode=:incoherent)\n @test abs(x) ≈ abs(x′) atol=0.0001\n y = transmissionloss(pm, AcousticSource(0.0, -d, 1000.0), AcousticReceiver(100.0, -d); mode=:incoherent)\n @test -10 * log10(abs2(x)) ≈ y atol=0.1\n x1 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))\n x2 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))\n x3 = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -15.0))\n x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), [AcousticReceiver(100.0, -d) for d ∈ 5.0:5.0:15.0])\n @test x isa AbstractVector\n @test [x1, x2, x3] == x\n x = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 0.0, 1, -5.0, -5.0, 3))\n @test x isa AbstractMatrix\n @test size(x) == (1, 3)\n @test [x1 x2 x3] ≈ x atol=0.01\n y = transfercoef(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 10.0, 3, -5.0, -5.0, 3))\n @test y isa AbstractMatrix\n @test size(y) == (3, 3)\n @test x' ≈ y[1,:] atol=0.05\n x1 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -5.0))\n x2 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -10.0))\n x3 = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiver(100.0, -15.0))\n x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), [AcousticReceiver(100.0, -d) for d ∈ 5.0:5.0:15.0])\n @test x isa AbstractVector\n @test [x1, x2, x3] == x\n x = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 0.0, 1, -5.0, -5.0, 3))\n @test x isa AbstractMatrix\n @test size(x) == (1, 3)\n @test [x1, x2] ≈ x[1:2] atol=1.5\n y = transmissionloss(pm, AcousticSource(0.0, -5.0, 1000.0), AcousticReceiverGrid2D(100.0, 10.0, 3, -5.0, -5.0, 3))\n @test y isa AbstractMatrix\n @test size(y) == (3, 3)\n @test x' ≈ y[1,:] atol=0.1\n\n tx = AcousticSource(0.0, -5.0, 1000.0)\n rx = AcousticReceiver(100.0, -10.0)\n sig = record(pm, tx, rx, 1.0, 44100.0)\n @test size(sig) == (44100,)\n sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,)\n sig = recorder(pm, tx, rx)(1.0, 44100.0)\n @test size(sig) == (44100,)\n sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,)\n tx = [AcousticSource(0.0, -5.0, 1000.0), AcousticSource(0.0, -10.0, 2000.0)]\n rx = AcousticReceiver(100.0, -10.0)\n sig = record(pm, tx, rx, 1.0, 44100.0)\n @test size(sig) == (44100,)\n sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,)\n sig = recorder(pm, tx, rx)(1.0, 44100.0)\n @test size(sig) == (44100,)\n sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,)\n tx = [AcousticSource(0.0, -5.0, 1000.0), AcousticSource(0.0, -10.0, 2000.0)]\n rx = [AcousticReceiver(100.0, -10.0), AcousticReceiver(100.0, -15.0)]\n sig = record(pm, tx, rx, 1.0, 44100.0)\n @test size(sig) == (44100,2)\n sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,2)\n sig = recorder(pm, tx, rx)(1.0, 44100.0)\n @test size(sig) == (44100,2)\n sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,2)\n tx = AcousticSource(0.0, -5.0, 1000.0)\n rx = [AcousticReceiver(100.0, -10.0), AcousticReceiver(100.0, -15.0)]\n sig = record(pm, tx, rx, 1.0, 44100.0)\n @test size(sig) == (44100,2)\n sig = record(pm, tx, rx, 1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,2)\n sig = recorder(pm, tx, rx)(1.0, 44100.0)\n @test size(sig) == (44100,2)\n sig = recorder(pm, tx, rx)(1.0, 44100.0; start=0.5)\n @test size(sig) == (44100,2)\n\nend",
"@testset \"pm-∂pekeris\" begin\n\n function ℳ(x)\n D, R, d1, d2, f, c = x\n env = UnderwaterEnvironment(ssp=IsoSSP(c), bathymetry=ConstantDepth(D))\n pm = PekerisRayModel(env, 7)\n transmissionloss(pm, AcousticSource(0.0, -d1, f), AcousticReceiver(R, -d2))\n end\n\n x = [20.0, 100.0, 5.0, 10.0, 5000.0, 1500.0]\n ∇ℳ = ForwardDiff.gradient(ℳ, x)\n for i ∈ 1:length(x)\n @test ∇ℳ[i] ≈ ∂(ℳ, x, i, 0.0001) atol=0.1\n end\n\n x = [25.0, 200.0, 10.0, 8.0, 1000.0, 1540.0]\n ∇ℳ = ForwardDiff.gradient(ℳ, x)\n for i ∈ 1:length(x)\n @test ∇ℳ[i] ≈ ∂(ℳ, x, i, 0.0001) atol=0.1\n end\n\nend",
"@testset \"pm-∂raysolver\" begin\n\n function ℳ₁(x)\n D, R, d1, d2, f, c = x\n env = UnderwaterEnvironment(ssp=IsoSSP(c), bathymetry=ConstantDepth(D))\n pm = RaySolver(env)\n transmissionloss(pm, AcousticSource(0.0, -d1, f), AcousticReceiver(R, -d2))\n end\n\n function ℳ₂(x)\n D, R, d1, d2, f, c = x\n env = UnderwaterEnvironment(ssp=IsoSSP(c), bathymetry=ConstantDepth(D))\n pm = RaySolver(env)\n transmissionloss(pm, AcousticSource(0.0, -d1, f), AcousticReceiverGrid2D(R, 0.0, 1, -d2, 0.0, 1))[1,1]\n end\n\n x = [20.0, 100.0, 5.0, 10.0, 5000.0, 1500.0]\n ∇ℳ = ForwardDiff.gradient(ℳ₁, x)\n for i ∈ 1:length(x)\n # skip i = 2 because it is not yet supported\n i != 2 && @test ∇ℳ[i] ≈ ∂(ℳ₁, x, i, 0.0001) atol=0.1\n end\n\n x = [25.0, 200.0, 10.0, 8.0, 1000.0, 1540.0]\n ∇ℳ = ForwardDiff.gradient(ℳ₁, x)\n for i ∈ 1:length(x)\n # skip i = 2 because it is not yet supported\n i != 2 && @test ∇ℳ[i] ≈ ∂(ℳ₁, x, i, 0.0001) atol=0.1\n end\n\n x = [20.0, 100.0, 5.0, 10.0, 5000.0, 1500.0]\n ∇ℳ = ForwardDiff.gradient(ℳ₂, x)\n for i ∈ 1:length(x)\n @test ∇ℳ[i] ≈ ∂(ℳ₂, x, i, 0.0001) atol=0.1\n end\n\n x = [25.0, 200.0, 10.0, 8.0, 1000.0, 1540.0]\n ∇ℳ = ForwardDiff.gradient(ℳ₂, x)\n for i ∈ 1:length(x)\n @test ∇ℳ[i] ≈ ∂(ℳ₂, x, i, 0.0001) atol=0.1\n end\n\nend"
] |
f76a7a9c95f5a981d2ad23560f04ff76a7d19c8a
| 2,215
|
jl
|
Julia
|
test/_fast.jl
|
jw3126/AxisKeys.jl
|
ec293e172abfd832f2fa31ae190c4737b0a18f7d
|
[
"MIT"
] | 104
|
2020-03-18T17:16:47.000Z
|
2022-02-22T12:35:16.000Z
|
test/_fast.jl
|
jw3126/AxisKeys.jl
|
ec293e172abfd832f2fa31ae190c4737b0a18f7d
|
[
"MIT"
] | 88
|
2020-03-14T19:54:46.000Z
|
2022-03-22T20:33:48.000Z
|
test/_fast.jl
|
jw3126/AxisKeys.jl
|
ec293e172abfd832f2fa31ae190c4737b0a18f7d
|
[
"MIT"
] | 19
|
2020-03-20T11:57:50.000Z
|
2022-01-16T10:21:26.000Z
|
using Test, AxisKeys, BenchmarkTools
@testset "indexing & lookup" begin
A = wrapdims(rand(2,3), 11.0:12.0, [:a, :b, :c])
if VERSION >= v"1.2"
# getindex
@test 0 == @ballocated $A[1, 1]
@test 272 >= @ballocated $A[1, :]
@test (@inferred A[1, :]; true)
@test (@inferred view(A, 1, :); true)
# getkey
@test 32 >= @ballocated $A(11.0, :a)
end
al_A = @ballocated view($A,1,:) # 96
@test al_A == @ballocated $A(11.0,:)
@test al_A == @ballocated $A(11.0)
@test al_A == @ballocated $A(11)
@test 0 == @ballocated AxisKeys.inferdim(11, $(axiskeys(A)))
if VERSION >= v"1.2"
@test (@inferred A(11); true)
end
@test al_A/2 >= @ballocated $A[1,:] .= 0 # dotview skips view of key vector
# with names
N = wrapdims(rand(2,3), row=11.0:12.0, col=[:a, :b, :c])
if VERSION >= v"1.2"
@test 0 == @ballocated $N[1, 1]
@test 0 == @ballocated $N[col=1, row=1]
@test 288 >= @ballocated $N[row=1]
@test (@inferred N[row=1]; true)
end
# extraction
@test 0 == @ballocated axiskeys($N)
@test 0 == @ballocated axiskeys($N, 1)
@test 0 == @ballocated axiskeys($N, :row)
@test 0 == @ballocated dimnames($N)
@test 0 == @ballocated dimnames($N, 1)
@test 0 == @ballocated AxisKeys.hasnames($N)
@test 0 == @ballocated AxisKeys.haskeys($N)
end
@testset "construction" begin
M = rand(2,3);
@test 64 >= @ballocated KeyedArray($M, ('a':'b', 10:10:30))
@test 16 >= @ballocated NamedDimsArray($M, (:row, :col))
@test (@inferred KeyedArray(M, ('a':'b', 10:10:30)); true)
V = rand(3);
@test 64 >= @ballocated KeyedArray($V, 'a':'c')
# nested pair via keywords
if VERSION >= v"1.3" # 144 alloc on 1.2, have not tried 1.1
@test 80 >= @ballocated KeyedArray($M, row='a':'b', col=10:10:30) # 464 >=
@test 80 >= @ballocated NamedDimsArray($M, row='a':'b', col=10:10:30) # 400 >=
end
@test 560 >= @ballocated wrapdims($M, row='a':'b', col=10:10:30) # 560 >=
@test (@inferred KeyedArray(M, row='a':'b', col=10:10:30); true)
@test (@inferred NamedDimsArray(M, row='a':'b', col=10:10:30); true)
end
| 30.342466
| 86
| 0.550339
|
[
"@testset \"indexing & lookup\" begin\n\n A = wrapdims(rand(2,3), 11.0:12.0, [:a, :b, :c])\n\n if VERSION >= v\"1.2\"\n # getindex\n @test 0 == @ballocated $A[1, 1]\n @test 272 >= @ballocated $A[1, :]\n @test (@inferred A[1, :]; true)\n @test (@inferred view(A, 1, :); true)\n\n # getkey\n @test 32 >= @ballocated $A(11.0, :a)\n end\n\n al_A = @ballocated view($A,1,:) # 96\n\n @test al_A == @ballocated $A(11.0,:)\n @test al_A == @ballocated $A(11.0)\n @test al_A == @ballocated $A(11)\n @test 0 == @ballocated AxisKeys.inferdim(11, $(axiskeys(A)))\n if VERSION >= v\"1.2\"\n @test (@inferred A(11); true)\n end\n @test al_A/2 >= @ballocated $A[1,:] .= 0 # dotview skips view of key vector\n\n # with names\n N = wrapdims(rand(2,3), row=11.0:12.0, col=[:a, :b, :c])\n\n if VERSION >= v\"1.2\"\n @test 0 == @ballocated $N[1, 1]\n @test 0 == @ballocated $N[col=1, row=1]\n @test 288 >= @ballocated $N[row=1]\n @test (@inferred N[row=1]; true)\n end\n\n # extraction\n @test 0 == @ballocated axiskeys($N)\n @test 0 == @ballocated axiskeys($N, 1)\n @test 0 == @ballocated axiskeys($N, :row)\n\n @test 0 == @ballocated dimnames($N)\n @test 0 == @ballocated dimnames($N, 1)\n\n @test 0 == @ballocated AxisKeys.hasnames($N)\n @test 0 == @ballocated AxisKeys.haskeys($N)\n\nend",
"@testset \"construction\" begin\n\n M = rand(2,3);\n\n @test 64 >= @ballocated KeyedArray($M, ('a':'b', 10:10:30))\n @test 16 >= @ballocated NamedDimsArray($M, (:row, :col))\n @test (@inferred KeyedArray(M, ('a':'b', 10:10:30)); true)\n\n V = rand(3);\n @test 64 >= @ballocated KeyedArray($V, 'a':'c')\n\n # nested pair via keywords\n if VERSION >= v\"1.3\" # 144 alloc on 1.2, have not tried 1.1\n @test 80 >= @ballocated KeyedArray($M, row='a':'b', col=10:10:30) # 464 >=\n @test 80 >= @ballocated NamedDimsArray($M, row='a':'b', col=10:10:30) # 400 >=\n end\n @test 560 >= @ballocated wrapdims($M, row='a':'b', col=10:10:30) # 560 >=\n\n @test (@inferred KeyedArray(M, row='a':'b', col=10:10:30); true)\n @test (@inferred NamedDimsArray(M, row='a':'b', col=10:10:30); true)\n\nend"
] |
f76c5f73ffe2766fcae1a29dafa004ee9b851bc9
| 942
|
jl
|
Julia
|
test/datasets_test.jl
|
mjirik/LarSurf.jl
|
de2eaec62dfe8c63e7d621bc973aa01d8de019c6
|
[
"MIT"
] | 2
|
2019-09-17T22:56:08.000Z
|
2020-01-04T09:50:42.000Z
|
test/datasets_test.jl
|
mjirik/lario3d.jl
|
de2eaec62dfe8c63e7d621bc973aa01d8de019c6
|
[
"MIT"
] | 1
|
2019-11-16T15:47:22.000Z
|
2019-11-18T17:43:46.000Z
|
test/datasets_test.jl
|
mjirik/lario3d.jl
|
de2eaec62dfe8c63e7d621bc973aa01d8de019c6
|
[
"MIT"
] | 1
|
2021-03-05T15:01:47.000Z
|
2021-03-05T15:01:47.000Z
|
using Test
using Logging
# using Revise
using LarSurf
# Logging.configure(level==Logging.Debug)
# include("../src/LarSurf.jl")
# include("../src/block.jl")
@testset "Block basic function Tests" begin
data3d = LarSurf.random_image([7, 7, 7], [1,2,2], [3, 4, 5], 2)
@test maximum(data3d) > 2
@test minimum(data3d) < 1
end
@testset "Tetris" begin
segmentation = LarSurf.tetris_brick()
@test minimum(segmentation) == 0
@test maximum(segmentation) == 1
end
@testset "data234" begin
segmentation = LarSurf.data234()
@test minimum(segmentation) == 0
@test maximum(segmentation) == 1
end
@testset "half sphere generation" begin
segmentation = LarSurf.generate_truncated_sphere(10, [20,20,20])
@test minimum(segmentation) == 0
@test maximum(segmentation) == 1
segmentation = LarSurf.generate_truncated_sphere(10)
@test minimum(segmentation) == 0
@test maximum(segmentation) == 1
end
| 24.153846
| 68
| 0.686837
|
[
"@testset \"Block basic function Tests\" begin\n data3d = LarSurf.random_image([7, 7, 7], [1,2,2], [3, 4, 5], 2)\n @test maximum(data3d) > 2\n @test minimum(data3d) < 1\nend",
"@testset \"Tetris\" begin\n segmentation = LarSurf.tetris_brick()\n @test minimum(segmentation) == 0\n @test maximum(segmentation) == 1\nend",
"@testset \"data234\" begin\n segmentation = LarSurf.data234()\n @test minimum(segmentation) == 0\n @test maximum(segmentation) == 1\nend",
"@testset \"half sphere generation\" begin\n segmentation = LarSurf.generate_truncated_sphere(10, [20,20,20])\n @test minimum(segmentation) == 0\n @test maximum(segmentation) == 1\n\n segmentation = LarSurf.generate_truncated_sphere(10)\n @test minimum(segmentation) == 0\n @test maximum(segmentation) == 1\nend"
] |
f76ea9c014f7c98b9151b679053cecf996211dc3
| 2,867
|
jl
|
Julia
|
test/runtests.jl
|
tobydriscoll/fnc
|
dde6097e6a9efff3c8cd7748c96214b4fcec2dc4
|
[
"MIT"
] | 31
|
2020-07-15T15:31:47.000Z
|
2022-03-14T14:48:49.000Z
|
test/runtests.jl
|
tobydriscoll/fnc
|
dde6097e6a9efff3c8cd7748c96214b4fcec2dc4
|
[
"MIT"
] | 4
|
2020-07-20T15:42:58.000Z
|
2022-02-08T19:08:43.000Z
|
test/runtests.jl
|
tobydriscoll/fnc
|
dde6097e6a9efff3c8cd7748c96214b4fcec2dc4
|
[
"MIT"
] | 12
|
2020-07-26T17:42:14.000Z
|
2022-01-24T06:10:19.000Z
|
using FundamentalsNumericalComputation
using Test
@testset "Chapter 1" begin
@test FNC.horner([-1,3,-3,1],1.6) ≈ 0.6^3
end
@testset "Chapter 2" begin
A = [ 1 2 3 0; -1 1 2 -1; 3 1 2 4; 1 1 1 1 ]
L,U = FNC.lufact(A)
@test norm(L*U - A) < 100eps()
@test norm(U - triu(U)) < 100eps()
@test norm(L - tril(L)) < 100eps()
b = [1,10,0,-1] / 5;
@test norm(L\b - FNC.forwardsub(L,b)) < 100eps()
@test norm(U\b - FNC.backsub(U,b)) < 100eps()
end
@testset "Chapter 3" begin
A = [3 4 5;-1 0 1;4 2 0; 1 1 2; 3 -4 1]
b = 5:-1:1
@test FNC.lsnormal(A,b) ≈ A\b
@test FNC.lsqrfact(A,b) ≈ A\b
Q,R = qr(A)
QQ,RR = FNC.qrfact(A)
@test Q ≈ QQ
@test R ≈ RR[1:3,:]
end
@testset "Chapter 4" begin
for c = [2,4,7.5,11]
f = x -> exp(x) - x - c;
dfdx = x -> exp(x) - 1;
x = FNC.newton(f,dfdx,1.0); r = x[end];
@test abs(f(r)) < 100eps()
end
for c = [2,4,7.5,11]
f = x -> exp(x) - x - c;
dfdx = x -> exp(x) - 1;
x = FNC.secant(f,3,0.5); r = x[end];
@test abs(f(r)) < 100eps()
end
function nlfun(x)
f = zeros(3)
f[1] = exp(x[2]-x[1]) - 2;
f[2] = x[1]*x[2] + x[3];
f[3] = x[2]*x[3] + x[1]^2 - x[2];
return f
end
function nljac(x)
J = zeros(3,3)
J[1,:] = [-exp(x[2]-x[1]),exp(x[2]-x[1]), 0]
J[2,:] = [x[2], x[1], 1]
J[3,:] = [2*x[1], x[3]-1, x[2]]
return J
end
x = FNC.newtonsys(nlfun,nljac,[0,0,0]);
@test norm(nlfun(x[end])) < 100eps()
x = FNC.newtonsys(nlfun,nljac,[1,2,3]);
@test norm(nlfun(x[end])) < 100eps()
x = FNC.levenberg(nlfun,[10,-4,-3])
@test norm(nlfun(x[end])) < 1e-12
end
@testset "Chapter 5" begin
f = t->cos(5t)
Q,t = FNC.intadapt(f,-1,3,1e-8)
@test Q ≈ (sin(15)+sin(5))/5 rtol = 1e-5
T,_ = FNC.trapezoid(f,-1,3,820)
@test T ≈ (sin(15)+sin(5))/5 rtol = 1e-4
t = [-2,-0.5,0,1,1.5,3.5,4]/10
S = FNC.spinterp(t,exp.(t))
@test S(0.33) ≈ exp(0.33) rtol = 1e-5
w = FNC.fdweights(t.-0.12,2)
f = x->cos(3x)
@test dot(w,f.(t)) ≈ -9cos(0.36) rtol = 1e-3
y = FNC.hatfun(0.22,t,5)
@test y ≈ (0.22-t[5])/(t[6]-t[5])
@test FNC.hatfun(0.6,t,5)==0
p = FNC.plinterp(t,f.(t))
@test p(0.22) ≈ f(t[5]) + (f(t[6])-f(t[5]))*(0.22-t[5])/(t[6]-t[5])
end
@testset "Chapter 6" begin
f = (u,p,t) -> u + p*t^2
û = exp(1.5) - 2*(-2 + 2*exp(1.5) - 2*1.5 - 1.5^2)
ivp = ODEProblem(f,1,(0,1.5),-2)
t,u = FNC.euler(ivp,4000)
@test û ≈ u[end] rtol = 0.005
t,u = FNC.am2(ivp,4000)
@test û ≈ u[end] rtol = 0.005
g = (u,p,t) -> [t+p-sin(u[2]),u[1]]
ivp = ODEProblem(g,[-1.,4],(1.,2.),-6)
sol = solve(ivp,Tsit5())
t,u = FNC.euler(ivp,4000)
@test u[end] ≈ sol.u[end] rtol=0.004
t,u = FNC.ie2(ivp,4000)
@test u[end] ≈ sol.u[end] rtol=0.0005
t,u = FNC.rk4(ivp,800)
@test u[end] ≈ sol.u[end] rtol=0.0005
t,u = FNC.ab4(ivp,800)
@test u[end] ≈ sol.u[end] rtol=0.0005
t,u = FNC.rk23(ivp,1e-4)
@test u[end] ≈ sol.u[end] rtol=0.0005
t,u = FNC.am2(ivp,2000)
@test u[end] ≈ sol.u[end] rtol=0.0005
end
| 24.930435
| 69
| 0.531217
|
[
"@testset \"Chapter 1\" begin\n\t@test FNC.horner([-1,3,-3,1],1.6) ≈ 0.6^3\nend",
"@testset \"Chapter 2\" begin\n\tA = [ 1 2 3 0; -1 1 2 -1; 3 1 2 4; 1 1 1 1 ]\n\tL,U = FNC.lufact(A)\n\t@test norm(L*U - A) < 100eps()\n\t@test norm(U - triu(U)) < 100eps()\n\t@test norm(L - tril(L)) < 100eps()\n\tb = [1,10,0,-1] / 5;\n\t@test norm(L\\b - FNC.forwardsub(L,b)) < 100eps()\n\t@test norm(U\\b - FNC.backsub(U,b)) < 100eps()\nend",
"@testset \"Chapter 3\" begin\n\tA = [3 4 5;-1 0 1;4 2 0; 1 1 2; 3 -4 1]\n\tb = 5:-1:1\n\t@test FNC.lsnormal(A,b) ≈ A\\b\n\t@test FNC.lsqrfact(A,b) ≈ A\\b\n\tQ,R = qr(A)\n\tQQ,RR = FNC.qrfact(A)\n\t@test Q ≈ QQ\n\t@test R ≈ RR[1:3,:]\nend",
"@testset \"Chapter 4\" begin\n\n\tfor c = [2,4,7.5,11]\n\t\tf = x -> exp(x) - x - c;\n\t\tdfdx = x -> exp(x) - 1;\n\t\tx = FNC.newton(f,dfdx,1.0); r = x[end];\n\t\t@test abs(f(r)) < 100eps()\n\tend\n\n\tfor c = [2,4,7.5,11]\n\t\tf = x -> exp(x) - x - c;\n\t\tdfdx = x -> exp(x) - 1;\n\t\tx = FNC.secant(f,3,0.5); r = x[end];\n\t\t@test abs(f(r)) < 100eps()\n\tend\n\n\tfunction nlfun(x)\n\t\tf = zeros(3) \n\t\tf[1] = exp(x[2]-x[1]) - 2;\n\t\tf[2] = x[1]*x[2] + x[3];\n\t\tf[3] = x[2]*x[3] + x[1]^2 - x[2];\n\t\treturn f\n\tend\n\tfunction nljac(x)\n\t\tJ = zeros(3,3)\n\t\tJ[1,:] = [-exp(x[2]-x[1]),exp(x[2]-x[1]), 0]\n\t\tJ[2,:] = [x[2], x[1], 1]\n\t\tJ[3,:] = [2*x[1], x[3]-1, x[2]]\n\t\treturn J\n\tend\n\n\tx = FNC.newtonsys(nlfun,nljac,[0,0,0]);\n\t@test norm(nlfun(x[end])) < 100eps()\n\tx = FNC.newtonsys(nlfun,nljac,[1,2,3]);\n\t@test norm(nlfun(x[end])) < 100eps()\n\n\tx = FNC.levenberg(nlfun,[10,-4,-3])\n\t@test norm(nlfun(x[end])) < 1e-12\n\nend",
"@testset \"Chapter 5\" begin\n\tf = t->cos(5t)\n\tQ,t = FNC.intadapt(f,-1,3,1e-8)\n\t@test Q ≈ (sin(15)+sin(5))/5 rtol = 1e-5\n\tT,_ = FNC.trapezoid(f,-1,3,820)\n\t@test T ≈ (sin(15)+sin(5))/5 rtol = 1e-4\n\t\n\tt = [-2,-0.5,0,1,1.5,3.5,4]/10\n\tS = FNC.spinterp(t,exp.(t))\n\t@test S(0.33) ≈ exp(0.33) rtol = 1e-5\n\tw = FNC.fdweights(t.-0.12,2)\n\tf = x->cos(3x)\n\t@test dot(w,f.(t)) ≈ -9cos(0.36) rtol = 1e-3\n\ty = FNC.hatfun(0.22,t,5)\n\t@test y ≈ (0.22-t[5])/(t[6]-t[5])\n\t@test FNC.hatfun(0.6,t,5)==0\n\tp = FNC.plinterp(t,f.(t)) \n\t@test p(0.22) ≈ f(t[5]) + (f(t[6])-f(t[5]))*(0.22-t[5])/(t[6]-t[5])\t\nend",
"@testset \"Chapter 6\" begin\n\tf = (u,p,t) -> u + p*t^2\n\tû = exp(1.5) - 2*(-2 + 2*exp(1.5) - 2*1.5 - 1.5^2)\n\tivp = ODEProblem(f,1,(0,1.5),-2)\n\tt,u = FNC.euler(ivp,4000)\n\t@test û ≈ u[end] rtol = 0.005\n\tt,u = FNC.am2(ivp,4000)\n\t@test û ≈ u[end] rtol = 0.005\n\n\tg = (u,p,t) -> [t+p-sin(u[2]),u[1]]\n\tivp = ODEProblem(g,[-1.,4],(1.,2.),-6)\n\tsol = solve(ivp,Tsit5())\n\tt,u = FNC.euler(ivp,4000)\n\t@test u[end] ≈ sol.u[end] rtol=0.004\n\tt,u = FNC.ie2(ivp,4000)\n\t@test u[end] ≈ sol.u[end] rtol=0.0005\n\tt,u = FNC.rk4(ivp,800)\n\t@test u[end] ≈ sol.u[end] rtol=0.0005\n\tt,u = FNC.ab4(ivp,800)\n\t@test u[end] ≈ sol.u[end] rtol=0.0005\n\tt,u = FNC.rk23(ivp,1e-4)\n\t@test u[end] ≈ sol.u[end] rtol=0.0005\n\tt,u = FNC.am2(ivp,2000)\n\t@test u[end] ≈ sol.u[end] rtol=0.0005\nend"
] |
f774b41915333f01b265988666134303e7b44ba5
| 12,852
|
jl
|
Julia
|
test/fit.jl
|
pdeffebach/Distributions.jl
|
8aea3cc82ee2f8ffe1e8cd754e7fcd99369c7a1c
|
[
"MIT"
] | 852
|
2015-01-03T14:38:13.000Z
|
2022-03-31T19:04:52.000Z
|
test/fit.jl
|
pdeffebach/Distributions.jl
|
8aea3cc82ee2f8ffe1e8cd754e7fcd99369c7a1c
|
[
"MIT"
] | 1,133
|
2015-01-12T20:37:42.000Z
|
2022-03-28T16:18:57.000Z
|
test/fit.jl
|
pdeffebach/Distributions.jl
|
8aea3cc82ee2f8ffe1e8cd754e7fcd99369c7a1c
|
[
"MIT"
] | 467
|
2015-01-14T14:30:55.000Z
|
2022-03-30T22:32:51.000Z
|
# Testing:
#
# - computation of sufficient statistics
# - distribution fitting (i.e. estimation)
#
using Distributions
using Test, Random, LinearAlgebra
n0 = 100
N = 10^5
rng = MersenneTwister(123)
const funcs = ([rand,rand], [dist -> rand(rng, dist), (dist, n) -> rand(rng, dist, n)])
@testset "Testing fit for DiscreteUniform" begin
for func in funcs
w = func[1](n0)
x = func[2](DiscreteUniform(10, 15), n0)
d = fit(DiscreteUniform, x)
@test isa(d, DiscreteUniform)
@test minimum(d) == minimum(x)
@test maximum(d) == maximum(x)
d = fit(DiscreteUniform, func[2](DiscreteUniform(10, 15), N))
@test minimum(d) == 10
@test maximum(d) == 15
end
end
@testset "Testing fit for Bernoulli" begin
for func in funcs, dist in (Bernoulli, Bernoulli{Float64})
w = func[1](n0)
x = func[2](dist(0.7), n0)
ss = suffstats(dist, x)
@test isa(ss, Distributions.BernoulliStats)
@test ss.cnt0 == n0 - count(t->t != 0, x)
@test ss.cnt1 == count(t->t != 0, x)
ss = suffstats(dist, x, w)
@test isa(ss, Distributions.BernoulliStats)
@test ss.cnt0 ≈ sum(w[x .== 0])
@test ss.cnt1 ≈ sum(w[x .== 1])
d = fit(dist, x)
p = count(t->t != 0, x) / n0
@test isa(d, dist)
@test mean(d) ≈ p
d = fit(dist, x, w)
p = sum(w[x .== 1]) / sum(w)
@test isa(d, dist)
@test mean(d) ≈ p
d = fit(dist, func[2](dist(0.7), N))
@test isa(d, dist)
@test isapprox(mean(d), 0.7, atol=0.01)
end
end
@testset "Testing fit for Beta" begin
for func in funcs, dist in (Beta, Beta{Float64})
d = fit(dist, func[2](dist(1.3, 3.7), N))
@test isa(d, dist)
@test isapprox(d.α, 1.3, atol=0.1)
@test isapprox(d.β, 3.7, atol=0.1)
d = fit_mle(dist, func[2](dist(1.3, 3.7), N))
@test isa(d, dist)
@test isapprox(d.α, 1.3, atol=0.1)
@test isapprox(d.β, 3.7, atol=0.1)
end
end
@testset "Testing fit for Binomial" begin
for func in funcs, dist in (Binomial, Binomial{Float64})
w = func[1](n0)
x = func[2](dist(100, 0.3), n0)
ss = suffstats(dist, (100, x))
@test isa(ss, Distributions.BinomialStats)
@test ss.ns ≈ sum(x)
@test ss.ne == n0
@test ss.n == 100
ss = suffstats(dist, (100, x), w)
@test isa(ss, Distributions.BinomialStats)
@test ss.ns ≈ dot(Float64[xx for xx in x], w)
@test ss.ne ≈ sum(w)
@test ss.n == 100
d = fit(dist, (100, x))
@test isa(d, dist)
@test ntrials(d) == 100
@test succprob(d) ≈ sum(x) / (n0 * 100)
d = fit(dist, (100, x), w)
@test isa(d, dist)
@test ntrials(d) == 100
@test succprob(d) ≈ dot(x, w) / (sum(w) * 100)
d = fit(dist, 100, func[2](dist(100, 0.3), N))
@test isa(d, dist)
@test ntrials(d) == 100
@test isapprox(succprob(d), 0.3, atol=0.01)
end
end
# Categorical
@testset "Testing fit for Categorical" begin
for func in funcs
p = [0.2, 0.5, 0.3]
x = func[2](Categorical(p), n0)
w = func[1](n0)
ss = suffstats(Categorical, (3, x))
h = Float64[count(v->v == i, x) for i = 1 : 3]
@test isa(ss, Distributions.CategoricalStats)
@test ss.h ≈ h
d = fit(Categorical, (3, x))
@test isa(d, Categorical)
@test ncategories(d) == 3
@test probs(d) ≈ h / sum(h)
d2 = fit(Categorical, x)
@test isa(d2, Categorical)
@test probs(d2) == probs(d)
ss = suffstats(Categorical, (3, x), w)
h = Float64[sum(w[x .== i]) for i = 1 : 3]
@test isa(ss, Distributions.CategoricalStats)
@test ss.h ≈ h
d = fit(Categorical, (3, x), w)
@test isa(d, Categorical)
@test probs(d) ≈ h / sum(h)
d = fit(Categorical, suffstats(Categorical, 3, x, w))
@test isa(d, Categorical)
@test probs(d) ≈ (h / sum(h))
d = fit(Categorical, func[2](Categorical(p), N))
@test isa(d, Categorical)
@test isapprox(probs(d), p, atol=0.01)
end
end
@testset "Testing fit for Cauchy" begin
@test fit(Cauchy, collect(-4.0:4.0)) === Cauchy(0.0, 2.0)
@test fit(Cauchy{Float64}, collect(-4.0:4.0)) === Cauchy(0.0, 2.0)
end
@testset "Testing fit for Exponential" begin
for func in funcs, dist in (Exponential, Exponential{Float64})
w = func[1](n0)
x = func[2](dist(0.5), n0)
ss = suffstats(dist, x)
@test isa(ss, Distributions.ExponentialStats)
@test ss.sx ≈ sum(x)
@test ss.sw == n0
ss = suffstats(dist, x, w)
@test isa(ss, Distributions.ExponentialStats)
@test ss.sx ≈ dot(x, w)
@test ss.sw == sum(w)
d = fit(dist, x)
@test isa(d, dist)
@test scale(d) ≈ mean(x)
d = fit(dist, x, w)
@test isa(d, dist)
@test scale(d) ≈ dot(x, w) / sum(w)
d = fit(dist, func[2](dist(0.5), N))
@test isa(d, dist)
@test isapprox(scale(d), 0.5, atol=0.01)
end
end
@testset "Testing fit for Normal" begin
for func in funcs, dist in (Normal, Normal{Float64})
μ = 11.3
σ = 3.2
w = func[1](n0)
x = func[2](dist(μ, σ), n0)
ss = suffstats(dist, x)
@test isa(ss, Distributions.NormalStats)
@test ss.s ≈ sum(x)
@test ss.m ≈ mean(x)
@test ss.s2 ≈ sum((x .- ss.m).^2)
@test ss.tw ≈ n0
ss = suffstats(dist, x, w)
@test isa(ss, Distributions.NormalStats)
@test ss.s ≈ dot(x, w)
@test ss.m ≈ dot(x, w) / sum(w)
@test ss.s2 ≈ dot((x .- ss.m).^2, w)
@test ss.tw ≈ sum(w)
d = fit(dist, x)
@test isa(d, dist)
@test d.μ ≈ mean(x)
@test d.σ ≈ sqrt(mean((x .- d.μ).^2))
d = fit(dist, x, w)
@test isa(d, dist)
@test d.μ ≈ dot(x, w) / sum(w)
@test d.σ ≈ sqrt(dot((x .- d.μ).^2, w) / sum(w))
d = fit(dist, func[2](dist(μ, σ), N))
@test isa(d, dist)
@test isapprox(d.μ, μ, atol=0.1)
@test isapprox(d.σ, σ, atol=0.1)
end
end
@testset "Testing fit for Normal with known moments" begin
import Distributions.NormalKnownMu, Distributions.NormalKnownSigma
μ = 11.3
σ = 3.2
for func in funcs
w = func[1](n0)
x = func[2](Normal(μ, σ), n0)
ss = suffstats(NormalKnownMu(μ), x)
@test isa(ss, Distributions.NormalKnownMuStats)
@test ss.μ == μ
@test ss.s2 ≈ sum(abs2.(x .- μ))
@test ss.tw ≈ n0
ss = suffstats(NormalKnownMu(μ), x, w)
@test isa(ss, Distributions.NormalKnownMuStats)
@test ss.μ == μ
@test ss.s2 ≈ dot((x .- μ).^2, w)
@test ss.tw ≈ sum(w)
d = fit_mle(Normal, x; mu=μ)
@test isa(d, Normal)
@test d.μ == μ
@test d.σ ≈ sqrt(mean((x .- d.μ).^2))
d = fit_mle(Normal, x, w; mu=μ)
@test isa(d, Normal)
@test d.μ == μ
@test d.σ ≈ sqrt(dot((x .- d.μ).^2, w) / sum(w))
ss = suffstats(NormalKnownSigma(σ), x)
@test isa(ss, Distributions.NormalKnownSigmaStats)
@test ss.σ == σ
@test ss.sx ≈ sum(x)
@test ss.tw ≈ n0
ss = suffstats(NormalKnownSigma(σ), x, w)
@test isa(ss, Distributions.NormalKnownSigmaStats)
@test ss.σ == σ
@test ss.sx ≈ dot(x, w)
@test ss.tw ≈ sum(w)
d = fit_mle(Normal, x; sigma=σ)
@test isa(d, Normal)
@test d.σ == σ
@test d.μ ≈ mean(x)
d = fit_mle(Normal, x, w; sigma=σ)
@test isa(d, Normal)
@test d.σ == σ
@test d.μ ≈ dot(x, w) / sum(w)
end
end
@testset "Testing fit for Uniform" begin
for func in funcs, dist in (Uniform, Uniform{Float64})
x = func[2](dist(1.2, 5.8), n0)
d = fit(dist, x)
@test isa(d, dist)
@test 1.2 <= minimum(d) <= maximum(d) <= 5.8
@test minimum(d) == minimum(x)
@test maximum(d) == maximum(x)
d = fit(dist, func[2](dist(1.2, 5.8), N))
@test 1.2 <= minimum(d) <= maximum(d) <= 5.8
@test isapprox(minimum(d), 1.2, atol=0.02)
@test isapprox(maximum(d), 5.8, atol=0.02)
end
end
@testset "Testing fit for Gamma" begin
for func in funcs, dist in (Gamma, Gamma{Float64})
x = func[2](dist(3.9, 2.1), n0)
w = func[1](n0)
ss = suffstats(dist, x)
@test isa(ss, Distributions.GammaStats)
@test ss.sx ≈ sum(x)
@test ss.slogx ≈ sum(log.(x))
@test ss.tw ≈ n0
ss = suffstats(dist, x, w)
@test isa(ss, Distributions.GammaStats)
@test ss.sx ≈ dot(x, w)
@test ss.slogx ≈ dot(log.(x), w)
@test ss.tw ≈ sum(w)
d = fit(dist, func[2](dist(3.9, 2.1), N))
@test isa(d, dist)
@test isapprox(shape(d), 3.9, atol=0.1)
@test isapprox(scale(d), 2.1, atol=0.2)
end
end
@testset "Testing fit for Geometric" begin
for func in funcs, dist in (Geometric, Geometric{Float64})
x = func[2](dist(0.3), n0)
w = func[1](n0)
ss = suffstats(dist, x)
@test isa(ss, Distributions.GeometricStats)
@test ss.sx ≈ sum(x)
@test ss.tw ≈ n0
ss = suffstats(dist, x, w)
@test isa(ss, Distributions.GeometricStats)
@test ss.sx ≈ dot(x, w)
@test ss.tw ≈ sum(w)
d = fit(dist, x)
@test isa(d, dist)
@test succprob(d) ≈ inv(1. + mean(x))
d = fit(dist, x, w)
@test isa(d, dist)
@test succprob(d) ≈ inv(1. + dot(x, w) / sum(w))
d = fit(dist, func[2](dist(0.3), N))
@test isa(d, dist)
@test isapprox(succprob(d), 0.3, atol=0.01)
end
end
@testset "Testing fit for Laplace" begin
for func in funcs, dist in (Laplace, Laplace{Float64})
d = fit(dist, func[2](dist(5.0, 3.0), N + 1))
@test isa(d, dist)
@test isapprox(location(d), 5.0, atol=0.02)
@test isapprox(scale(d) , 3.0, atol=0.02)
end
end
@testset "Testing fit for Pareto" begin
for func in funcs, dist in (Pareto, Pareto{Float64})
x = func[2](dist(3., 7.), N)
d = fit(dist, x)
@test isa(d, dist)
@test isapprox(shape(d), 3., atol=0.1)
@test isapprox(scale(d), 7., atol=0.1)
end
end
@testset "Testing fit for Poisson" begin
for func in funcs, dist in (Poisson, Poisson{Float64})
x = func[2](dist(8.2), n0)
w = func[1](n0)
ss = suffstats(dist, x)
@test isa(ss, Distributions.PoissonStats)
@test ss.sx ≈ sum(x)
@test ss.tw ≈ n0
ss = suffstats(dist, x, w)
@test isa(ss, Distributions.PoissonStats)
@test ss.sx ≈ dot(x, w)
@test ss.tw ≈ sum(w)
d = fit(dist, x)
@test isa(d, dist)
@test mean(d) ≈ mean(x)
d = fit(dist, x, w)
@test isa(d, dist)
@test mean(d) ≈ dot(Float64[xx for xx in x], w) / sum(w)
d = fit(dist, func[2](dist(8.2), N))
@test isa(d, dist)
@test isapprox(mean(d), 8.2, atol=0.2)
end
end
@testset "Testing fit for InverseGaussian" begin
for func in funcs, dist in (InverseGaussian, InverseGaussian{Float64})
x = rand(dist(3.9, 2.1), n0)
w = func[1](n0)
ss = suffstats(dist, x)
@test isa(ss, Distributions.InverseGaussianStats)
@test ss.sx ≈ sum(x)
@test ss.sinvx ≈ sum(1 ./ x)
@test ss.sw ≈ n0
ss = suffstats(dist, x, w)
@test isa(ss, Distributions.InverseGaussianStats)
@test ss.sx ≈ dot(x, w)
@test ss.sinvx ≈ dot(1 ./ x, w)
@test ss.sw ≈ sum(w)
d = fit(dist, rand(dist(3.9, 2.1), N))
@test isa(d, dist)
@test isapprox(mean(d), 3.9, atol=0.1)
@test isapprox(shape(d), 2.1, atol=0.1)
d = fit_mle(dist, rand(dist(3.9, 2.1), N))
@test isapprox(mean(d), 3.9, atol=0.1)
@test isapprox(shape(d), 2.1, atol=0.1)
end
end
@testset "Testing fit for Rayleigh" begin
for func in funcs, dist in (Rayleigh, Rayleigh{Float64})
x = func[2](dist(3.6), N)
d = fit(dist, x)
@test isa(d, dist)
@test isapprox(mode(d), 3.6, atol=0.1)
# Test automatic differentiation
f(x) = mean(fit(Rayleigh, x))
@test all(ForwardDiff.gradient(f, x) .>= 0)
end
end
@testset "Testing fit for Weibull" begin
for func in funcs, dist in (Weibull, Weibull{Float64})
d = fit(dist, func[2](dist(8.1, 4.3), N))
@test isa(d, dist)
@test isapprox(d.α, 8.1, atol = 0.1)
@test isapprox(d.θ, 4.3, atol = 0.1)
end
end
| 28.184211
| 87
| 0.519297
|
[
"@testset \"Testing fit for DiscreteUniform\" begin\n for func in funcs\n w = func[1](n0)\n\n x = func[2](DiscreteUniform(10, 15), n0)\n d = fit(DiscreteUniform, x)\n @test isa(d, DiscreteUniform)\n @test minimum(d) == minimum(x)\n @test maximum(d) == maximum(x)\n\n d = fit(DiscreteUniform, func[2](DiscreteUniform(10, 15), N))\n @test minimum(d) == 10\n @test maximum(d) == 15\n end\nend",
"@testset \"Testing fit for Bernoulli\" begin\n for func in funcs, dist in (Bernoulli, Bernoulli{Float64})\n w = func[1](n0)\n x = func[2](dist(0.7), n0)\n\n ss = suffstats(dist, x)\n @test isa(ss, Distributions.BernoulliStats)\n @test ss.cnt0 == n0 - count(t->t != 0, x)\n @test ss.cnt1 == count(t->t != 0, x)\n\n ss = suffstats(dist, x, w)\n @test isa(ss, Distributions.BernoulliStats)\n @test ss.cnt0 ≈ sum(w[x .== 0])\n @test ss.cnt1 ≈ sum(w[x .== 1])\n\n d = fit(dist, x)\n p = count(t->t != 0, x) / n0\n @test isa(d, dist)\n @test mean(d) ≈ p\n\n d = fit(dist, x, w)\n p = sum(w[x .== 1]) / sum(w)\n @test isa(d, dist)\n @test mean(d) ≈ p\n\n d = fit(dist, func[2](dist(0.7), N))\n @test isa(d, dist)\n @test isapprox(mean(d), 0.7, atol=0.01)\n end\nend",
"@testset \"Testing fit for Beta\" begin\n for func in funcs, dist in (Beta, Beta{Float64})\n d = fit(dist, func[2](dist(1.3, 3.7), N))\n @test isa(d, dist)\n @test isapprox(d.α, 1.3, atol=0.1)\n @test isapprox(d.β, 3.7, atol=0.1)\n\n d = fit_mle(dist, func[2](dist(1.3, 3.7), N))\n @test isa(d, dist)\n @test isapprox(d.α, 1.3, atol=0.1)\n @test isapprox(d.β, 3.7, atol=0.1)\n\n end\nend",
"@testset \"Testing fit for Binomial\" begin\n for func in funcs, dist in (Binomial, Binomial{Float64})\n w = func[1](n0)\n\n x = func[2](dist(100, 0.3), n0)\n\n ss = suffstats(dist, (100, x))\n @test isa(ss, Distributions.BinomialStats)\n @test ss.ns ≈ sum(x)\n @test ss.ne == n0\n @test ss.n == 100\n\n ss = suffstats(dist, (100, x), w)\n @test isa(ss, Distributions.BinomialStats)\n @test ss.ns ≈ dot(Float64[xx for xx in x], w)\n @test ss.ne ≈ sum(w)\n @test ss.n == 100\n\n d = fit(dist, (100, x))\n @test isa(d, dist)\n @test ntrials(d) == 100\n @test succprob(d) ≈ sum(x) / (n0 * 100)\n\n d = fit(dist, (100, x), w)\n @test isa(d, dist)\n @test ntrials(d) == 100\n @test succprob(d) ≈ dot(x, w) / (sum(w) * 100)\n\n d = fit(dist, 100, func[2](dist(100, 0.3), N))\n @test isa(d, dist)\n @test ntrials(d) == 100\n @test isapprox(succprob(d), 0.3, atol=0.01)\n end\nend",
"@testset \"Testing fit for Categorical\" begin\n for func in funcs\n p = [0.2, 0.5, 0.3]\n x = func[2](Categorical(p), n0)\n w = func[1](n0)\n\n ss = suffstats(Categorical, (3, x))\n h = Float64[count(v->v == i, x) for i = 1 : 3]\n @test isa(ss, Distributions.CategoricalStats)\n @test ss.h ≈ h\n\n d = fit(Categorical, (3, x))\n @test isa(d, Categorical)\n @test ncategories(d) == 3\n @test probs(d) ≈ h / sum(h)\n\n d2 = fit(Categorical, x)\n @test isa(d2, Categorical)\n @test probs(d2) == probs(d)\n\n ss = suffstats(Categorical, (3, x), w)\n h = Float64[sum(w[x .== i]) for i = 1 : 3]\n @test isa(ss, Distributions.CategoricalStats)\n @test ss.h ≈ h\n\n d = fit(Categorical, (3, x), w)\n @test isa(d, Categorical)\n @test probs(d) ≈ h / sum(h)\n\n d = fit(Categorical, suffstats(Categorical, 3, x, w))\n @test isa(d, Categorical)\n @test probs(d) ≈ (h / sum(h))\n\n d = fit(Categorical, func[2](Categorical(p), N))\n @test isa(d, Categorical)\n @test isapprox(probs(d), p, atol=0.01)\n end\nend",
"@testset \"Testing fit for Cauchy\" begin\n @test fit(Cauchy, collect(-4.0:4.0)) === Cauchy(0.0, 2.0)\n @test fit(Cauchy{Float64}, collect(-4.0:4.0)) === Cauchy(0.0, 2.0)\nend",
"@testset \"Testing fit for Exponential\" begin\n for func in funcs, dist in (Exponential, Exponential{Float64})\n w = func[1](n0)\n x = func[2](dist(0.5), n0)\n\n ss = suffstats(dist, x)\n @test isa(ss, Distributions.ExponentialStats)\n @test ss.sx ≈ sum(x)\n @test ss.sw == n0\n\n ss = suffstats(dist, x, w)\n @test isa(ss, Distributions.ExponentialStats)\n @test ss.sx ≈ dot(x, w)\n @test ss.sw == sum(w)\n\n d = fit(dist, x)\n @test isa(d, dist)\n @test scale(d) ≈ mean(x)\n\n d = fit(dist, x, w)\n @test isa(d, dist)\n @test scale(d) ≈ dot(x, w) / sum(w)\n\n d = fit(dist, func[2](dist(0.5), N))\n @test isa(d, dist)\n @test isapprox(scale(d), 0.5, atol=0.01)\n end\nend",
"@testset \"Testing fit for Normal\" begin\n for func in funcs, dist in (Normal, Normal{Float64})\n μ = 11.3\n σ = 3.2\n w = func[1](n0)\n\n x = func[2](dist(μ, σ), n0)\n\n ss = suffstats(dist, x)\n @test isa(ss, Distributions.NormalStats)\n @test ss.s ≈ sum(x)\n @test ss.m ≈ mean(x)\n @test ss.s2 ≈ sum((x .- ss.m).^2)\n @test ss.tw ≈ n0\n\n ss = suffstats(dist, x, w)\n @test isa(ss, Distributions.NormalStats)\n @test ss.s ≈ dot(x, w)\n @test ss.m ≈ dot(x, w) / sum(w)\n @test ss.s2 ≈ dot((x .- ss.m).^2, w)\n @test ss.tw ≈ sum(w)\n\n d = fit(dist, x)\n @test isa(d, dist)\n @test d.μ ≈ mean(x)\n @test d.σ ≈ sqrt(mean((x .- d.μ).^2))\n\n d = fit(dist, x, w)\n @test isa(d, dist)\n @test d.μ ≈ dot(x, w) / sum(w)\n @test d.σ ≈ sqrt(dot((x .- d.μ).^2, w) / sum(w))\n\n d = fit(dist, func[2](dist(μ, σ), N))\n @test isa(d, dist)\n @test isapprox(d.μ, μ, atol=0.1)\n @test isapprox(d.σ, σ, atol=0.1)\n end\nend",
"@testset \"Testing fit for Normal with known moments\" begin\n import Distributions.NormalKnownMu, Distributions.NormalKnownSigma\n μ = 11.3\n σ = 3.2\n\n for func in funcs\n\n w = func[1](n0)\n x = func[2](Normal(μ, σ), n0)\n\n ss = suffstats(NormalKnownMu(μ), x)\n @test isa(ss, Distributions.NormalKnownMuStats)\n @test ss.μ == μ\n @test ss.s2 ≈ sum(abs2.(x .- μ))\n @test ss.tw ≈ n0\n\n ss = suffstats(NormalKnownMu(μ), x, w)\n @test isa(ss, Distributions.NormalKnownMuStats)\n @test ss.μ == μ\n @test ss.s2 ≈ dot((x .- μ).^2, w)\n @test ss.tw ≈ sum(w)\n\n d = fit_mle(Normal, x; mu=μ)\n @test isa(d, Normal)\n @test d.μ == μ\n @test d.σ ≈ sqrt(mean((x .- d.μ).^2))\n\n d = fit_mle(Normal, x, w; mu=μ)\n @test isa(d, Normal)\n @test d.μ == μ\n @test d.σ ≈ sqrt(dot((x .- d.μ).^2, w) / sum(w))\n\n\n ss = suffstats(NormalKnownSigma(σ), x)\n @test isa(ss, Distributions.NormalKnownSigmaStats)\n @test ss.σ == σ\n @test ss.sx ≈ sum(x)\n @test ss.tw ≈ n0\n\n ss = suffstats(NormalKnownSigma(σ), x, w)\n @test isa(ss, Distributions.NormalKnownSigmaStats)\n @test ss.σ == σ\n @test ss.sx ≈ dot(x, w)\n @test ss.tw ≈ sum(w)\n\n d = fit_mle(Normal, x; sigma=σ)\n @test isa(d, Normal)\n @test d.σ == σ\n @test d.μ ≈ mean(x)\n\n d = fit_mle(Normal, x, w; sigma=σ)\n @test isa(d, Normal)\n @test d.σ == σ\n @test d.μ ≈ dot(x, w) / sum(w)\n end\nend",
"@testset \"Testing fit for Uniform\" begin\n for func in funcs, dist in (Uniform, Uniform{Float64})\n x = func[2](dist(1.2, 5.8), n0)\n d = fit(dist, x)\n @test isa(d, dist)\n @test 1.2 <= minimum(d) <= maximum(d) <= 5.8\n @test minimum(d) == minimum(x)\n @test maximum(d) == maximum(x)\n\n d = fit(dist, func[2](dist(1.2, 5.8), N))\n @test 1.2 <= minimum(d) <= maximum(d) <= 5.8\n @test isapprox(minimum(d), 1.2, atol=0.02)\n @test isapprox(maximum(d), 5.8, atol=0.02)\n end\nend",
"@testset \"Testing fit for Gamma\" begin\n for func in funcs, dist in (Gamma, Gamma{Float64})\n x = func[2](dist(3.9, 2.1), n0)\n w = func[1](n0)\n\n ss = suffstats(dist, x)\n @test isa(ss, Distributions.GammaStats)\n @test ss.sx ≈ sum(x)\n @test ss.slogx ≈ sum(log.(x))\n @test ss.tw ≈ n0\n\n ss = suffstats(dist, x, w)\n @test isa(ss, Distributions.GammaStats)\n @test ss.sx ≈ dot(x, w)\n @test ss.slogx ≈ dot(log.(x), w)\n @test ss.tw ≈ sum(w)\n\n d = fit(dist, func[2](dist(3.9, 2.1), N))\n @test isa(d, dist)\n @test isapprox(shape(d), 3.9, atol=0.1)\n @test isapprox(scale(d), 2.1, atol=0.2)\n end\nend",
"@testset \"Testing fit for Geometric\" begin\n for func in funcs, dist in (Geometric, Geometric{Float64})\n x = func[2](dist(0.3), n0)\n w = func[1](n0)\n\n ss = suffstats(dist, x)\n @test isa(ss, Distributions.GeometricStats)\n @test ss.sx ≈ sum(x)\n @test ss.tw ≈ n0\n\n ss = suffstats(dist, x, w)\n @test isa(ss, Distributions.GeometricStats)\n @test ss.sx ≈ dot(x, w)\n @test ss.tw ≈ sum(w)\n\n d = fit(dist, x)\n @test isa(d, dist)\n @test succprob(d) ≈ inv(1. + mean(x))\n\n d = fit(dist, x, w)\n @test isa(d, dist)\n @test succprob(d) ≈ inv(1. + dot(x, w) / sum(w))\n\n d = fit(dist, func[2](dist(0.3), N))\n @test isa(d, dist)\n @test isapprox(succprob(d), 0.3, atol=0.01)\n end\nend",
"@testset \"Testing fit for Laplace\" begin\n for func in funcs, dist in (Laplace, Laplace{Float64})\n d = fit(dist, func[2](dist(5.0, 3.0), N + 1))\n @test isa(d, dist)\n @test isapprox(location(d), 5.0, atol=0.02)\n @test isapprox(scale(d) , 3.0, atol=0.02)\n end\nend",
"@testset \"Testing fit for Pareto\" begin\n for func in funcs, dist in (Pareto, Pareto{Float64})\n x = func[2](dist(3., 7.), N)\n d = fit(dist, x)\n\n @test isa(d, dist)\n @test isapprox(shape(d), 3., atol=0.1)\n @test isapprox(scale(d), 7., atol=0.1)\n end\nend",
"@testset \"Testing fit for Poisson\" begin\n for func in funcs, dist in (Poisson, Poisson{Float64})\n x = func[2](dist(8.2), n0)\n w = func[1](n0)\n\n ss = suffstats(dist, x)\n @test isa(ss, Distributions.PoissonStats)\n @test ss.sx ≈ sum(x)\n @test ss.tw ≈ n0\n\n ss = suffstats(dist, x, w)\n @test isa(ss, Distributions.PoissonStats)\n @test ss.sx ≈ dot(x, w)\n @test ss.tw ≈ sum(w)\n\n d = fit(dist, x)\n @test isa(d, dist)\n @test mean(d) ≈ mean(x)\n\n d = fit(dist, x, w)\n @test isa(d, dist)\n @test mean(d) ≈ dot(Float64[xx for xx in x], w) / sum(w)\n\n d = fit(dist, func[2](dist(8.2), N))\n @test isa(d, dist)\n @test isapprox(mean(d), 8.2, atol=0.2)\n end\nend",
"@testset \"Testing fit for InverseGaussian\" begin\n for func in funcs, dist in (InverseGaussian, InverseGaussian{Float64})\n x = rand(dist(3.9, 2.1), n0)\n w = func[1](n0)\n\n ss = suffstats(dist, x)\n @test isa(ss, Distributions.InverseGaussianStats)\n @test ss.sx ≈ sum(x)\n @test ss.sinvx ≈ sum(1 ./ x)\n @test ss.sw ≈ n0\n\n ss = suffstats(dist, x, w)\n @test isa(ss, Distributions.InverseGaussianStats)\n @test ss.sx ≈ dot(x, w)\n @test ss.sinvx ≈ dot(1 ./ x, w)\n @test ss.sw ≈ sum(w)\n\n d = fit(dist, rand(dist(3.9, 2.1), N))\n @test isa(d, dist)\n @test isapprox(mean(d), 3.9, atol=0.1)\n @test isapprox(shape(d), 2.1, atol=0.1)\n\n d = fit_mle(dist, rand(dist(3.9, 2.1), N))\n @test isapprox(mean(d), 3.9, atol=0.1)\n @test isapprox(shape(d), 2.1, atol=0.1)\n end\nend",
"@testset \"Testing fit for Rayleigh\" begin\n for func in funcs, dist in (Rayleigh, Rayleigh{Float64})\n x = func[2](dist(3.6), N)\n d = fit(dist, x)\n\n @test isa(d, dist)\n @test isapprox(mode(d), 3.6, atol=0.1)\n\n # Test automatic differentiation\n f(x) = mean(fit(Rayleigh, x))\n @test all(ForwardDiff.gradient(f, x) .>= 0)\n end\nend",
"@testset \"Testing fit for Weibull\" begin\n for func in funcs, dist in (Weibull, Weibull{Float64})\n d = fit(dist, func[2](dist(8.1, 4.3), N))\n @test isa(d, dist)\n @test isapprox(d.α, 8.1, atol = 0.1)\n @test isapprox(d.θ, 4.3, atol = 0.1)\n\n end\nend"
] |
f777386a69e39ffadf6bc200cc05b4a48c79f03a
| 50,351
|
jl
|
Julia
|
test/runtests.jl
|
kevmoor/GXBeam.jl
|
7536c97cc103d7ae53bb6e0b1d2ae4a5196a35a1
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
kevmoor/GXBeam.jl
|
7536c97cc103d7ae53bb6e0b1d2ae4a5196a35a1
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
kevmoor/GXBeam.jl
|
7536c97cc103d7ae53bb6e0b1d2ae4a5196a35a1
|
[
"MIT"
] | null | null | null |
using GXBeam
using LinearAlgebra
using DifferentialEquations
using Test
import Elliptic
using ForwardDiff
@testset "Math" begin
c = rand(3)
cdot = rand(3)
# get_C_θ
C_θ1, C_θ2, C_θ3 = GXBeam.get_C_θ(c)
@test isapprox(C_θ1, ForwardDiff.derivative(c1 -> GXBeam.get_C([c1, c[2], c[3]]), c[1]))
@test isapprox(C_θ2, ForwardDiff.derivative(c2 -> GXBeam.get_C([c[1], c2, c[3]]), c[2]))
@test isapprox(C_θ3, ForwardDiff.derivative(c3 -> GXBeam.get_C([c[1], c[2], c3]), c[3]))
# get_C_t_θ
Cdot_θ1, Cdot_θ2, Cdot_θ3 = GXBeam.get_C_t_θ(c, cdot)
@test isapprox(Cdot_θ1, ForwardDiff.derivative(c1 -> GXBeam.get_C_t([c1, c[2], c[3]], cdot), c[1]))
@test isapprox(Cdot_θ2, ForwardDiff.derivative(c2 -> GXBeam.get_C_t([c[1], c2, c[3]], cdot), c[2]))
@test isapprox(Cdot_θ3, ForwardDiff.derivative(c3 -> GXBeam.get_C_t([c[1], c[2], c3], cdot), c[3]))
# get_C_t_θdot
Cdot_θdot1, Cdot_θdot2, Cdot_θdot3 = GXBeam.get_C_t_θdot(c)
@test isapprox(Cdot_θdot1, ForwardDiff.derivative(cdot1 -> GXBeam.get_C_t(c, [cdot1, cdot[2], cdot[3]]), cdot[1]))
@test isapprox(Cdot_θdot2, ForwardDiff.derivative(cdot2 -> GXBeam.get_C_t(c, [cdot[1], cdot2, cdot[3]]), cdot[2]))
@test isapprox(Cdot_θdot3, ForwardDiff.derivative(cdot3 -> GXBeam.get_C_t(c, [cdot[1], cdot[2], cdot3]), cdot[3]))
# get_Q_θ
Q_θ1, Q_θ2, Q_θ3 = GXBeam.get_Q_θ(c)
@test isapprox(Q_θ1, ForwardDiff.derivative(c1 -> GXBeam.get_Q([c1, c[2], c[3]]), c[1]))
@test isapprox(Q_θ2, ForwardDiff.derivative(c2 -> GXBeam.get_Q([c[1], c2, c[3]]), c[2]))
@test isapprox(Q_θ3, ForwardDiff.derivative(c3 -> GXBeam.get_Q([c[1], c[2], c3]), c[3]))
# get_Qinv_θ
Qinv_θ1, Qinv_θ2, Qinv_θ3 = GXBeam.get_Qinv_θ(c)
@test isapprox(Qinv_θ1, ForwardDiff.derivative(c1 -> GXBeam.get_Qinv([c1, c[2], c[3]]), c[1]))
@test isapprox(Qinv_θ2, ForwardDiff.derivative(c2 -> GXBeam.get_Qinv([c[1], c2, c[3]]), c[2]))
@test isapprox(Qinv_θ3, ForwardDiff.derivative(c3 -> GXBeam.get_Qinv([c[1], c[2], c3]), c[3]))
end
@testset "Jacobian and Mass Matrix Calculations" begin
L = 60 # m
# create points
nelem = 1
x = range(0, L, length=nelem+1)
y = zero(x)
z = zero(x)
points = [[x[i],y[i],z[i]] for i = 1:length(x)]
# index of endpoints of each beam element
start = 1:nelem
stop = 2:nelem+1
# stiffness matrix for each beam element
stiffness = fill(
[2.389e9 1.524e6 6.734e6 -3.382e7 -2.627e7 -4.736e8
1.524e6 4.334e8 -3.741e6 -2.935e5 1.527e7 3.835e5
6.734e6 -3.741e6 2.743e7 -4.592e5 -6.869e5 -4.742e6
-3.382e7 -2.935e5 -4.592e5 2.167e7 -6.279e5 1.430e6
-2.627e7 1.527e7 -6.869e5 -6.279e5 1.970e7 1.209e7
-4.736e8 3.835e5 -4.742e6 1.430e6 1.209e7 4.406e8],
nelem)
# mass matrix for each beam element
mass = fill(
[258.053 0.0 0.0 0.0 7.07839 -71.6871
0.0 258.053 0.0 -7.07839 0.0 0.0
0.0 0.0 258.053 71.6871 0.0 0.0
0.0 -7.07839 71.6871 48.59 0.0 0.0
7.07839 0.0 0.0 0.0 2.172 0.0
-71.6871 0.0 0.0 0.0 0.0 46.418],
nelem)
# create assembly of interconnected nonlinear beams
assembly = Assembly(points, start, stop; stiffness=stiffness, mass=mass)
# prescribed conditions
pcond = Dict(
# fixed left side
1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),
)
# distributed loads
dload = Dict()
# point masses
pmass = Dict(
# point mass at the end of the beam
nelem => PointMass(Symmetric(rand(6,6)))
)
# gravity vector
gvec = rand(3)
# --- Static Analysis --- #
static_system = System(assembly, true)
force_scaling = static_system.force_scaling
irow_point = static_system.irow_point
irow_elem = static_system.irow_elem
irow_elem1 = static_system.irow_elem1
irow_elem2 = static_system.irow_elem2
icol_point = static_system.icol_point
icol_elem = static_system.icol_elem
x = rand(length(static_system.x))
J = similar(x, length(x), length(x))
f = (x) -> GXBeam.static_system_residual!(similar(x), x, assembly, pcond, dload, pmass, gvec,
force_scaling, irow_point, irow_elem1, irow_elem2, icol_point, icol_elem)
GXBeam.static_system_jacobian!(J, x, assembly, pcond, dload, pmass, gvec, force_scaling,
irow_point, irow_elem1, irow_elem2, icol_point, icol_elem)
@test all(isapprox.(J, ForwardDiff.jacobian(f, x), atol=1e-10))
# --- Steady State Analysis --- #
system = System(assembly, false)
force_scaling = system.force_scaling
irow_point = system.irow_point
irow_elem = system.irow_elem
irow_elem1 = system.irow_elem1
irow_elem2 = system.irow_elem2
icol_point = system.icol_point
icol_elem = system.icol_elem
x0 = rand(3)
v0 = rand(3)
ω0 = rand(3)
a0 = rand(3)
α0 = rand(3)
x = rand(length(system.x))
J = similar(x, length(x), length(x))
f = (x) -> GXBeam.steady_state_system_residual!(similar(x), x, assembly, pcond, dload,
pmass, gvec, force_scaling, irow_point, irow_elem, irow_elem1, irow_elem2,
icol_point, icol_elem, x0, v0, ω0, a0, α0)
GXBeam.steady_state_system_jacobian!(J, x, assembly, pcond, dload, pmass, gvec, force_scaling,
irow_point, irow_elem, irow_elem1, irow_elem2, icol_point,
icol_elem, x0, v0, ω0, a0, α0)
@test all(isapprox.(J, ForwardDiff.jacobian(f, x), atol=1e-10))
# --- Initial Condition Analysis --- #
u0 = [rand(3) for ielem = 1:length(assembly.elements)]
theta0 = [rand(3) for ielem = 1:length(assembly.elements)]
udot0 = [rand(3) for ielem = 1:length(assembly.elements)]
thetadot0 = [rand(3) for ielem = 1:length(assembly.elements)]
x = rand(length(system.x))
J = similar(x, length(x), length(x))
f = (x) -> GXBeam.initial_condition_system_residual!(similar(x), x, assembly, pcond, dload, pmass, gvec,
force_scaling, irow_point, irow_elem, irow_elem1, irow_elem2,
icol_point, icol_elem, x0, v0, ω0, a0, α0, u0, theta0, udot0, thetadot0)
GXBeam.initial_condition_system_jacobian!(J, x, assembly, pcond, dload, pmass, gvec, force_scaling,
irow_point, irow_elem, irow_elem1, irow_elem2, icol_point,
icol_elem, x0, v0, ω0, a0, α0, u0, theta0, udot0, thetadot0)
@test all(isapprox.(J, ForwardDiff.jacobian(f, x), atol=1e-10))
# --- Newmark Scheme Time-Marching Analysis --- #
udot = [rand(3) for ielem = 1:length(assembly.elements)]
θdot = [rand(3) for ielem = 1:length(assembly.elements)]
Vdot = [rand(3) for ielem = 1:length(assembly.elements)]
Ωdot = [rand(3) for ielem = 1:length(assembly.elements)]
dt = rand()
x = rand(length(system.x))
J = similar(x, length(x), length(x))
f = (x) -> GXBeam.newmark_system_residual!(similar(x), x, assembly, pcond, dload, pmass, gvec,
force_scaling, irow_point, irow_elem, irow_elem1, irow_elem2,
icol_point, icol_elem, x0, v0, ω0, a0, α0, udot, θdot, Vdot, Ωdot, dt)
GXBeam.newmark_system_jacobian!(J, x, assembly, pcond, dload, pmass, gvec, force_scaling,
irow_point, irow_elem, irow_elem1, irow_elem2, icol_point,
icol_elem, x0, v0, ω0, a0, α0, udot, θdot, Vdot, Ωdot, dt)
@test all(isapprox.(J, ForwardDiff.jacobian(f, x), atol=1e-10))
# --- General Dynamic Analysis --- #
dx = rand(length(system.x))
x = rand(length(system.x))
J = similar(x, length(x), length(x))
M = similar(x, length(x), length(x))
fx = (x) -> GXBeam.dynamic_system_residual!(similar(x), dx, x, assembly, pcond, dload,
pmass, gvec, force_scaling, irow_point, irow_elem, irow_elem1, irow_elem2,
icol_point, icol_elem, x0, v0, ω0, a0, α0)
fdx = (dx) -> GXBeam.dynamic_system_residual!(similar(dx), dx, x, assembly, pcond, dload,
pmass, gvec, force_scaling, irow_point, irow_elem, irow_elem1, irow_elem2,
icol_point, icol_elem, x0, v0, ω0, a0, α0)
GXBeam.dynamic_system_jacobian!(J, dx, x, assembly, pcond, dload, pmass, gvec, force_scaling,
irow_point, irow_elem, irow_elem1, irow_elem2, icol_point, icol_elem,
x0, v0, ω0, a0, α0)
GXBeam.system_mass_matrix!(M, x, assembly, pmass, force_scaling, irow_point,
irow_elem, irow_elem1, irow_elem2, icol_point, icol_elem)
@test all(isapprox.(J, ForwardDiff.jacobian(fx, x), atol=1e-10))
@test all(isapprox.(M, ForwardDiff.jacobian(fdx, x), atol=1e-10))
end
@testset "Linear Analysis of a Cantilever Partially Under a Uniform Distributed Load" begin
nelem = 12
# create points
a = 0.3
b = 0.7
L = 1.0
n1 = n3 = div(nelem, 3)
n2 = nelem - n1 - n3
x1 = range(0, a, length=n1+1)
x2 = range(a, b, length=n2+1)
x3 = range(b, L, length=n3+1)
x = vcat(x1, x2[2:end], x3[2:end])
y = zero(x)
z = zero(x)
points = [[x[i],y[i],z[i]] for i = 1:length(x)]
# index of endpoints for each beam element
start = 1:nelem
stop = 2:nelem+1
# create compliance matrix for each beam element
EI = 1e9
stiffness = fill(Diagonal([0, 0, 0, 0, EI, 0]), nelem)
# create the assembly
assembly = Assembly(points, start, stop, stiffness=stiffness)
# set prescribed conditions (fixed right endpoint)
prescribed_conditions = Dict(
nelem+1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0)
)
# create distributed load
q = 1000
distributed_loads = Dict()
for ielem in n1+1:n1+n2
distributed_loads[ielem] = DistributedLoads(assembly, ielem; fz = (s) -> q)
end
system, converged = static_analysis(assembly, prescribed_conditions=prescribed_conditions,
distributed_loads=distributed_loads, linear=true)
state = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)
# analytical solution obtained using superposition
initial_slope = -q/(6*EI)*((L-a)^3 - (L-b)^3)
initial_deflection = q/(24*EI)*((L-a)^3*(3*L + a) - (L-b)^3*(3*L + b))
analytical_M = function(x)
if 0 < x <= a
M = 0.0
elseif a < x <= b
M = q/2*(x-a)^2
else
M = q/2*((x-a)^2 - (x-b)^2)
end
return M
end
analytical_slope = function(x)
slope = initial_slope
if 0 < x <= a
slope += 0.0
elseif a < x <= b
slope += q/(6*EI)*(x-a)^3
else
slope += q/(6*EI)*((x-a)^3 - (x-b)^3)
end
return slope
end
analytical_deflection = function(x)
deflection = initial_deflection + initial_slope*x
if 0 < x <= a
deflection += 0.0
elseif a < x <= b
deflection += q/(24*EI)*(x-a)^4
else
deflection += q/(24*EI)*((x-a)^4 - (x-b)^4)
end
return deflection
end
# test element properties
for i = 1:length(assembly.elements)
xi = assembly.elements[i].x[1]
@test isapprox(state.elements[i].u[3], analytical_deflection(xi), atol=1e-9)
@test isapprox(state.elements[i].theta[2], -4*analytical_slope(xi)/4, atol=1e-9)
@test isapprox(state.elements[i].M[2], -analytical_M(xi), atol=2)
end
# test point properties
for i = 1:length(assembly.points)
xi = assembly.points[i][1]
@test isapprox(state.points[i].u[3], analytical_deflection(xi), atol=1e-8)
@test isapprox(state.points[i].theta[2], -4*analytical_slope(xi)/4, atol=1e-7)
end
end
@testset "Linear Analysis of a Beam Under a Linear Distributed Load" begin
nelem = 16
# create points
L = 1
x = range(0, L, length=nelem+1)
y = zero(x)
z = zero(x)
points = [[x[i],y[i],z[i]] for i = 1:length(x)]
# index of endpoints for each beam element
start = 1:nelem
stop = 2:nelem+1
# create compliance matrix for each beam element
EI = 1e7
compliance = fill(Diagonal([0, 0, 0, 0, 1/EI, 0]), nelem)
# create assembly
assembly = Assembly(points, start, stop, compliance=compliance)
# set prescribed conditions
prescribed_conditions = Dict(
# simply supported left endpoint
1 => PrescribedConditions(uz=0),
# clamped right endpoint
nelem+1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0)
)
# create distributed load
qmax = 1000
distributed_loads = Dict()
for i = 1:nelem
distributed_loads[i] = DistributedLoads(assembly, i; s1=x[i],
s2=x[i+1], fz = (s) -> qmax*s)
end
# solve system
system, converged = static_analysis(assembly, prescribed_conditions=prescribed_conditions,
distributed_loads=distributed_loads, linear=true)
# post-process the results
state = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)
# construct analytical solution
analytical_deflection = (x) -> qmax*(1-x)^2/(120*EI)*(4 - 8*(1-x) + 5*(1-x)^2 - (1-x)^3)
analytical_slope = (x) -> -qmax*(1-x)/(120*EI)*(8 - 24*(1-x) + 20*(1-x)^2 - 5*(1-x)^3)
analytical_M = (x) -> qmax/120*(8 - 48*(1-x) + 60*(1-x)^2 - 20*(1-x)^3)
# test element properties
for i = 1:length(assembly.elements)
xi = assembly.elements[i].x[1]
@test isapprox(state.elements[i].u[3], analytical_deflection(xi), atol=1e-8)
@test isapprox(state.elements[i].theta[2], -4*analytical_slope(xi)/4, atol=1e-7)
@test isapprox(state.elements[i].M[2], -analytical_M(xi), atol=1)
end
# test point properties
for i = 1:length(assembly.points)
xi = assembly.points[i][1]
@test isapprox(state.points[i].u[3], analytical_deflection(xi), atol=1e-8)
@test isapprox(state.points[i].theta[2], -4*analytical_slope(xi)/4, atol=1e-8)
end
end
@testset "Nonlinear Analysis of a Cantilever Subjected to a Constant Tip Load" begin
L = 1
EI = 1e6
# shear force (applied at end)
λ = 0:0.5:16
p = EI/L^2
P = λ*p
# create points
nelem = 16
x = range(0, L, length=nelem+1)
y = zero(x)
z = zero(x)
points = [[x[i],y[i],z[i]] for i = 1:length(x)]
# index of endpoints of each beam element
start = 1:nelem
stop = 2:nelem+1
# compliance matrix for each beam element
compliance = fill(Diagonal([0, 0, 0, 0, 1/EI, 0]), nelem)
# create assembly of interconnected nonlinear beams
assembly = Assembly(points, start, stop, compliance=compliance)
# pre-initialize system storage
system = System(assembly, true)
# run an analysis for each prescribed tip load
states = Vector{AssemblyState{Float64}}(undef, length(P))
for i = 1:length(P)
# create dictionary of prescribed conditions
prescribed_conditions = Dict(
# fixed left side
1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),
# shear force on right tip
nelem+1 => PrescribedConditions(Fz = P[i])
)
# perform a static analysis
static_analysis!(system, assembly, prescribed_conditions=prescribed_conditions)
# post-process the results
states[i] = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)
end
# construct analytical solution
δ = range(pi/4, pi/2, length=10^5)[2:end-1]
k = @. cos(pi/4)/sin(δ)
λ_a = @. (Elliptic.F(pi/2, k^2) - Elliptic.F(δ, k^2))^2
θ_a = @. 2*(pi/4 - acos(k))
ξ_a = @. sqrt(2*sin(θ_a)/λ_a) .- 1
η_a = @. 1-2/sqrt(λ_a)*(Elliptic.E(pi/2, k^2) - Elliptic.E(δ, k^2))
# test tip displacements
for i = 1:length(P)
i_a = argmin(abs.(λ[i] .- λ_a))
@test isapprox(states[i].points[end].u[1]/L, ξ_a[i_a], atol=1e-3)
@test isapprox(states[i].points[end].u[3]/L, η_a[i_a], atol=1e-3)
@test isapprox(states[i].points[end].theta[2], -4*tan(θ_a[i_a]/4), atol=1e-2)
end
end
@testset "Nonlinear Analysis of a Cantilever Subjected to a Constant Moment" begin
L = 12 # inches
h = w = 1 # inches
E = 30e6 # lb/in^4 Young's Modulus
A = h*w
Iyy = w*h^3/12
Izz = w^3*h/12
# bending moment (applied at end)
# note that solutions for λ > 1.8 do not converge
λ = [0.0, 0.4, 0.8, 1.2, 1.6, 1.8, 2.0]
m = pi*E*Iyy/L
M = λ*m
# create points
nelem = 16
x = range(0, L, length=nelem+1)
y = zero(x)
z = zero(x)
points = [[x[i],y[i],z[i]] for i = 1:length(x)]
# index of endpoints for each beam element
start = 1:nelem
stop = 2:nelem+1
# compliance matrix for each beam element
compliance = fill(Diagonal([1/(E*A), 0, 0, 0, 1/(E*Iyy), 1/(E*Izz)]), nelem)
# create assembly of interconnected nonlinear beams
assembly = Assembly(points, start, stop, compliance=compliance)
# pre-initialize system storage
system = System(assembly, true)
# run an analysis for each prescribed bending moment
states = Vector{AssemblyState{Float64}}(undef, length(M))
for i = 1:length(M)
# create dictionary of prescribed conditions
prescribed_conditions = Dict(
# fixed left side
1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),
# moment on right side
nelem+1 => PrescribedConditions(Mz = M[i])
)
# perform a static analysis
static_analysis!(system, assembly, prescribed_conditions=prescribed_conditions)
# post-process the results
states[i] = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)
end
# analytical solution (ρ = E*I/M)
analytical(x, ρ) = ifelse(ρ == Inf, zeros(3), [ρ*sin(x/ρ)-x, ρ*(1-cos(x/ρ)), 0])
# test element properties
for i = 1:length(M)
for ielem = 1:length(assembly.elements)
xi = assembly.elements[ielem].x[1]
u_a, v_a, w_a = analytical(xi, E*Iyy/M[i])
@test isapprox(states[i].elements[ielem].u[1], u_a, atol=5e-2)
@test isapprox(states[i].elements[ielem].u[2], v_a, atol=5e-2)
end
# test point properties
for ipoint = 1:length(assembly.points)
xi = assembly.points[ipoint][1]
u_a, v_a, w_a = analytical(xi, E*Iyy/M[i])
@test isapprox(states[i].points[ipoint].u[1], u_a, atol=5e-2)
@test isapprox(states[i].points[ipoint].u[2], v_a, atol=5e-2)
end
end
end
@testset "Nonlinear Analysis of the Bending of a Curved Beam in 3D Space" begin
# problem constants
R = 100
L = R*pi/4 # inches
h = w = 1 # inches
E = 1e7 # psi Young's Modulus
ν = 0.0
G = E/(2*(1+ν))
# beam starting point, frame, and curvature
r = [0, 0, 0]
frame = [0 -1 0; 1 0 0; 0 0 1]
curvature = [0, 0, -1/R]
# cross section properties
A = h*w
Ay = A
Az = A
Iyy = w*h^3/12
Izz = w^3*h/12
J = Iyy + Izz
# discretize the beam
nelem = 16
ΔL, xp, xm, Cab = discretize_beam(L, r, nelem; frame=frame, curvature = curvature)
# force
P = 600 # lbs
# index of left and right endpoints of each beam element
start = 1:nelem
stop = 2:nelem+1
# compliance matrix for each beam element
compliance = fill(Diagonal([1/(E*A), 1/(G*Ay), 1/(G*Az), 1/(G*J), 1/(E*Iyy), 1/(E*Izz)]), nelem)
# create assembly of interconnected nonlinear beams
assembly = Assembly(xp, start, stop, compliance=compliance, frames=Cab,
lengths=ΔL, midpoints=xm)
# create dictionary of prescribed conditions
prescribed_conditions = Dict(
# fixed left endpoint
1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),
# force on right endpoint
nelem+1 => PrescribedConditions(Fz=P)
)
# perform static analysis
system, converged = static_analysis(assembly, prescribed_conditions=prescribed_conditions)
# post-process results
state = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)
# Results from "Large Displacement Analysis of Three-Dimensional Beam
# Structures" by Bathe and Bolourch:
# - Tip Displacement: [-13.4, -23.5, 53.4]
# Note that these results are comparing computational solutions, rather than
# the computational to the analytical solution, so some variation is expected.
@test isapprox(state.points[end].u[1], -13.4, atol=0.2) # -13.577383726758564
@test isapprox(state.points[end].u[2], -23.5, atol=0.1) # -23.545303336988038
@test isapprox(state.points[end].u[3], 53.4, atol=0.1) # 53.45800757548929
end
@testset "Rotating Beam with a Swept Tip" begin
sweep = 45 * pi/180
rpm = 0:25:750
# straight section of the beam
L_b1 = 31.5 # inch
r_b1 = [2.5, 0, 0]
nelem_b1 = 13
lengths_b1, xp_b1, xm_b1, Cab_b1 = discretize_beam(L_b1, r_b1, nelem_b1)
# swept section of the beam
L_b2 = 6 # inch
r_b2 = [34, 0, 0]
nelem_b2 = 3
cs, ss = cos(sweep), sin(sweep)
frame_b2 = [cs ss 0; -ss cs 0; 0 0 1]
lengths_b2, xp_b2, xm_b2, Cab_b2 = discretize_beam(L_b2, r_b2, nelem_b2, frame=frame_b2)
# combine elements and points into one array
nelem = nelem_b1 + nelem_b2
points = vcat(xp_b1, xp_b2[2:end])
start = 1:nelem_b1 + nelem_b2
stop = 2:nelem_b1 + nelem_b2 + 1
lengths = vcat(lengths_b1, lengths_b2)
midpoints = vcat(xm_b1, xm_b2)
Cab = vcat(Cab_b1, Cab_b2)
# cross section
w = 1 # inch
h = 0.063 # inch
# material properties
E = 1.06e7 # lb/in^2
ν = 0.325
ρ = 2.51e-4 # lb sec^2/in^4
# shear and torsion correction factors
ky = 1.2000001839588001
kz = 14.625127919304001
kt = 65.85255016982444
A = h*w
Iyy = w*h^3/12
Izz = w^3*h/12
J = Iyy + Izz
# apply corrections
Ay = A/ky
Az = A/kz
Jx = J/kt
G = E/(2*(1+ν))
compliance = fill(Diagonal([1/(E*A), 1/(G*Ay), 1/(G*Az), 1/(G*Jx), 1/(E*Iyy), 1/(E*Izz)]), nelem)
mass = fill(Diagonal([ρ*A, ρ*A, ρ*A, ρ*J, ρ*Iyy, ρ*Izz]), nelem)
# create assembly
assembly = Assembly(points, start, stop, compliance=compliance, mass=mass, frames=Cab, lengths=lengths, midpoints=midpoints)
# create dictionary of prescribed conditions
prescribed_conditions = Dict(
# root section is fixed
1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0)
)
nonlinear_states = Vector{AssemblyState{Float64}}(undef, length(rpm))
linear_states = Vector{AssemblyState{Float64}}(undef, length(rpm))
for i = 1:length(rpm)
# global frame rotation
w0 = [0, 0, rpm[i]*(2*pi)/60]
# perform nonlinear steady state analysis
system, converged = steady_state_analysis(assembly,
angular_velocity = w0,
prescribed_conditions = prescribed_conditions)
nonlinear_states[i] = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)
# perform linear steady state analysis
system, converged = steady_state_analysis(assembly,
angular_velocity = w0,
prescribed_conditions = prescribed_conditions,
linear = true)
linear_states[i] = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)
end
sweep = (0:2.5:45) * pi/180
rpm = [0, 500, 750]
nev = 30
λ = Matrix{Vector{ComplexF64}}(undef, length(sweep), length(rpm))
U = Matrix{Matrix{ComplexF64}}(undef, length(sweep), length(rpm))
MV = Matrix{Matrix{ComplexF64}}(undef, length(sweep), length(rpm))
state = Matrix{AssemblyState{Float64}}(undef, length(sweep), length(rpm))
eigenstates = Matrix{Vector{AssemblyState{ComplexF64}}}(undef, length(sweep), length(rpm))
for i = 1:length(sweep)
local L_b1, r_b1, nelem_b1, lengths_b1 #hide
local xp_b1, xm_b1, Cab_b1 #hide
local cs, ss #hide
local L_b2, r_b2, nelem_b2, frame_b2, lengths_b2 #hide
local xp_b2, xm_b2, Cab_b2 #hide
local nelem, points, start, stop #hide
local lengths, midpoints, Cab, compliance, mass, assembly #hide
# straight section of the beam
L_b1 = 31.5 # inch
r_b1 = [2.5, 0, 0]
nelem_b1 = 20
lengths_b1, xp_b1, xm_b1, Cab_b1 = discretize_beam(L_b1, r_b1, nelem_b1)
# swept section of the beam
L_b2 = 6 # inch
r_b2 = [34, 0, 0]
nelem_b2 = 20
cs, ss = cos(sweep[i]), sin(sweep[i])
frame_b2 = [cs ss 0; -ss cs 0; 0 0 1]
lengths_b2, xp_b2, xm_b2, Cab_b2 = discretize_beam(L_b2, r_b2, nelem_b2, frame=frame_b2)
# combine elements and points into one array
nelem = nelem_b1 + nelem_b2
points = vcat(xp_b1, xp_b2[2:end])
start = 1:nelem_b1 + nelem_b2
stop = 2:nelem_b1 + nelem_b2 + 1
lengths = vcat(lengths_b1, lengths_b2)
midpoints = vcat(xm_b1, xm_b2)
Cab = vcat(Cab_b1, Cab_b2)
compliance = fill(Diagonal([1/(E*A), 1/(G*Ay), 1/(G*Az), 1/(G*Jx), 1/(E*Iyy), 1/(E*Izz)]), nelem)
mass = fill(Diagonal([ρ*A, ρ*A, ρ*A, ρ*J, ρ*Iyy, ρ*Izz]), nelem)
# create assembly
assembly = Assembly(points, start, stop, compliance=compliance, mass=mass, frames=Cab, lengths=lengths, midpoints=midpoints)
# create system
system = System(assembly, false)
for j = 1:length(rpm)
# global frame rotation
w0 = [0, 0, rpm[j]*(2*pi)/60]
# eigenvalues and (right) eigenvectors
system, λ[i,j], V, converged = eigenvalue_analysis!(system, assembly,
angular_velocity = w0,
prescribed_conditions = prescribed_conditions,
nev=nev)
# corresponding left eigenvectors
U[i,j] = left_eigenvectors(system, λ[i,j], V)
# post-multiply mass matrix with right eigenvector matrix
# (we use this later for correlating eigenvalues)
MV[i,j] = system.M * V
# process state and eigenstates
state[i,j] = AssemblyState(system, assembly; prescribed_conditions=prescribed_conditions)
eigenstates[i,j] = [AssemblyState(system, assembly, V[:,k];
prescribed_conditions=prescribed_conditions) for k = 1:nev]
end
end
# set previous left eigenvector matrix
U_p = copy(U[1,1])
for j = 1:length(rpm)
for i = 1:length(sweep)
# construct correlation matrix
C = U_p*MV[i,j]
# correlate eigenmodes
perm, corruption = correlate_eigenmodes(C)
# re-arrange eigenvalues and eigenvectors
λ[i,j] = λ[i,j][perm]
U[i,j] = U[i,j][perm,:]
MV[i,j] = MV[i,j][:,perm]
eigenstates[i,j] = eigenstates[i,j][perm]
# update previous eigenvector matrix
U_p .= U[i,j]
end
# update previous eigenvector matrix
U_p .= U[1,j]
end
frequency = [[imag(λ[i,j][k])/(2*pi) for i = 1:length(sweep), j=1:length(rpm)] for k = 1:2:nev]
indices = [1, 2, 4]
experiment_rpm = [0, 500, 750]
experiment_sweep = [0, 15, 30, 45]
experiment_frequencies = [
[1.4 1.8 1.7 1.6;
10.2 10.1 10.2 10.2;
14.8 14.4 14.9 14.7],
[10.3 10.2 10.4 10.4;
25.2 25.2 23.7 21.6;
36.1 34.8 30.7 26.1],
[27.7 27.2 26.6 24.8;
47.0 44.4 39.3 35.1;
62.9 55.9 48.6 44.8]
]
for k = 1:length(experiment_frequencies)
for j = 1:length(experiment_sweep)
for i = 1:length(experiment_rpm)
ii = argmin(abs.(rpm .- experiment_rpm[i]))
jj = argmin(abs.(sweep*180/pi .- experiment_sweep[j]))
kk = indices[k]
@test isapprox(frequency[kk][jj,ii], experiment_frequencies[k][i,j], atol=1, rtol=0.1)
end
end
end
indices = [5, 7, 6]
experiment_frequencies = [
95.4 87.5 83.7 78.8;
106.6 120.1 122.6 117.7;
132.7 147.3 166.2 162.0
]
for k = 1:size(experiment_frequencies, 1)
for j = 1:length(experiment_sweep)
ii = argmin(abs.(rpm .- 750))
jj = argmin(abs.(sweep*180/pi .- experiment_sweep[j]))
kk = indices[k]
@test isapprox(frequency[kk][jj,ii], experiment_frequencies[k,j], rtol=0.1)
end
end
end
@testset "Nonlinear Dynamic Analysis of a Wind Turbine Blade" begin
L = 60 # m
# create points
nelem = 10
x = range(0, L, length=nelem+1)
y = zero(x)
z = zero(x)
points = [[x[i],y[i],z[i]] for i = 1:length(x)]
# index of endpoints of each beam element
start = 1:nelem
stop = 2:nelem+1
# stiffness matrix for each beam element
stiffness = fill(
[2.389e9 1.524e6 6.734e6 -3.382e7 -2.627e7 -4.736e8
1.524e6 4.334e8 -3.741e6 -2.935e5 1.527e7 3.835e5
6.734e6 -3.741e6 2.743e7 -4.592e5 -6.869e5 -4.742e6
-3.382e7 -2.935e5 -4.592e5 2.167e7 -6.279e5 1.430e6
-2.627e7 1.527e7 -6.869e5 -6.279e5 1.970e7 1.209e7
-4.736e8 3.835e5 -4.742e6 1.430e6 1.209e7 4.406e8],
nelem)
# mass matrix for each beam element
mass = fill(
[258.053 0.0 0.0 0.0 7.07839 -71.6871
0.0 258.053 0.0 -7.07839 0.0 0.0
0.0 0.0 258.053 71.6871 0.0 0.0
0.0 -7.07839 71.6871 48.59 0.0 0.0
7.07839 0.0 0.0 0.0 2.172 0.0
-71.6871 0.0 0.0 0.0 0.0 46.418],
nelem)
# create assembly of interconnected nonlinear beams
assembly = Assembly(points, start, stop; stiffness=stiffness, mass=mass)
# simulation time
tvec = 0:0.001:2.0
# prescribed conditions
prescribed_conditions = (t) -> begin
Dict(
# fixed left side
1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),
# force on right side
nelem+1 => PrescribedConditions(Fz=1e5*sin(20*t))
)
end
system, history, converged = time_domain_analysis(assembly, tvec; prescribed_conditions=prescribed_conditions)
@test converged
end
@testset "Nonlinear Static Analysis of a Joined-Wing" begin
# Set endpoints of each beam
p1 = [-7.1726, -12, -3.21539]
p2 = [-5.37945, -9, -2.41154]
p3 = [-3.5863, -6, -1.6077]
p4 = [-1.79315, -3, -0.803848]
p5 = [0, 0, 0]
p6 = [7.1726, -12, 3.21539]
# get transformation matrix for left beams
# transformation from intermediate to global frame
tmp1 = sqrt(p1[1]^2 + p1[2]^2)
c1, s1 = -p1[1]/tmp1, -p1[2]/tmp1
rot1 = [c1 -s1 0; s1 c1 0; 0 0 1]
# transformation from local to intermediate frame
tmp2 = sqrt(p1[1]^2 + p1[2]^2 + p1[3]^2)
c2, s2 = tmp1/tmp2, -p1[3]/tmp2
rot2 = [c2 0 -s2; 0 1 0; s2 0 c2]
Cab_1 = rot1*rot2
# get transformation matrix for right beam
# transformation from intermediate frame to global frame
tmp1 = sqrt(p6[1]^2 + p6[2]^2)
c1, s1 = p6[1]/tmp1, p6[2]/tmp1
rot1 = [c1 -s1 0; s1 c1 0; 0 0 1]
# transformation from local beam frame to intermediate frame
tmp2 = sqrt(p6[1]^2 + p6[2]^2 + p6[3]^2)
c2, s2 = tmp1/tmp2, p6[3]/tmp2
rot2 = [c2 0 -s2; 0 1 0; s2 0 c2]
Cab_2 = rot1*rot2
# beam 1
L_b1 = norm(p2-p1)
r_b1 = p1
nelem_b1 = 5
lengths_b1, xp_b1, xm_b1, Cab_b1 = discretize_beam(L_b1, r_b1, nelem_b1, frame=Cab_1)
compliance_b1 = fill(Diagonal([1.05204e-9, 3.19659e-9, 2.13106e-8, 1.15475e-7, 1.52885e-7, 7.1672e-9]), nelem_b1)
# beam 2
L_b2 = norm(p3-p2)
r_b2 = p2
nelem_b2 = 5
lengths_b2, xp_b2, xm_b2, Cab_b2 = discretize_beam(L_b2, r_b2, nelem_b2, frame=Cab_1)
compliance_b2 = fill(Diagonal([1.24467e-9, 3.77682e-9, 2.51788e-8, 1.90461e-7, 2.55034e-7, 1.18646e-8]), nelem_b2)
# beam 3
L_b3 = norm(p4-p3)
r_b3 = p3
nelem_b3 = 5
lengths_b3, xp_b3, xm_b3, Cab_b3 = discretize_beam(L_b3, r_b3, nelem_b3, frame=Cab_1)
compliance_b3 = fill(Diagonal([1.60806e-9, 4.86724e-9, 3.24482e-8, 4.07637e-7, 5.57611e-7, 2.55684e-8]), nelem_b3)
# beam 4
L_b4 = norm(p5-p4)
r_b4 = p4
nelem_b4 = 5
lengths_b4, xp_b4, xm_b4, Cab_b4 = discretize_beam(L_b4, r_b4, nelem_b4, frame=Cab_1)
compliance_b4 = fill(Diagonal([2.56482e-9, 7.60456e-9, 5.67609e-8, 1.92171e-6, 2.8757e-6, 1.02718e-7]), nelem_b4)
# beam 5
L_b5 = norm(p6-p5)
r_b5 = p5
nelem_b5 = 20
lengths_b5, xp_b5, xm_b5, Cab_b5 = discretize_beam(L_b5, r_b5, nelem_b5, frame=Cab_2)
compliance_b5 = fill(Diagonal([2.77393e-9, 7.60456e-9, 1.52091e-7, 1.27757e-5, 2.7835e-5, 1.26026e-7]), nelem_b5)
# combine elements and points into one array
nelem = nelem_b1 + nelem_b2 + nelem_b3 + nelem_b4 + nelem_b5
points = vcat(xp_b1, xp_b2[2:end], xp_b3[2:end], xp_b4[2:end], xp_b5[2:end])
start = 1:nelem
stop = 2:nelem + 1
lengths = vcat(lengths_b1, lengths_b2, lengths_b3, lengths_b4, lengths_b5)
midpoints = vcat(xm_b1, xm_b2, xm_b3, xm_b4, xm_b5)
Cab = vcat(Cab_b1, Cab_b2, Cab_b3, Cab_b4, Cab_b5)
compliance = vcat(compliance_b1, compliance_b2, compliance_b3, compliance_b4, compliance_b5)
# create assembly
assembly = Assembly(points, start, stop, compliance=compliance,
frames=Cab, lengths=lengths, midpoints=midpoints)
Fz = range(0, 70e3, length=141)
# pre-allocate memory to reduce run-time
system = System(assembly, true)
linear_states = Vector{AssemblyState{Float64}}(undef, length(Fz))
for i = 1:length(Fz)
# create dictionary of prescribed conditions
prescribed_conditions = Dict(
# fixed endpoint on beam 1
1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),
# force applied on point 4
nelem_b1 + nelem_b2 + nelem_b3 + nelem_b4 + 1 => PrescribedConditions(Fz = Fz[i]),
# fixed endpoint on last beam
nelem+1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),
)
_, converged = static_analysis!(system, assembly, prescribed_conditions=prescribed_conditions, linear=true)
linear_states[i] = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)
@test converged
end
reset_state!(system)
nonlinear_states = Vector{AssemblyState{Float64}}(undef, length(Fz))
for i = 1:length(Fz)
# create dictionary of prescribed conditions
prescribed_conditions = Dict(
# fixed endpoint on beam 1
1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),
# force applied on point 4
nelem_b1 + nelem_b2 + nelem_b3 + nelem_b4 + 1 => PrescribedConditions(Fz = Fz[i]),
# fixed endpoint on last beam
nelem+1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),
)
_, converged = static_analysis!(system, assembly, prescribed_conditions=prescribed_conditions,
reset_state = false)
nonlinear_states[i] = AssemblyState(system, assembly;
prescribed_conditions=prescribed_conditions)
@test converged
end
reset_state!(system)
nonlinear_follower_states = Vector{AssemblyState{Float64}}(undef, length(Fz))
for i = 1:length(Fz)
# create dictionary of prescribed conditions
prescribed_conditions = Dict(
# fixed endpoint on beam 1
1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),
# force applied on point 4
nelem_b1 + nelem_b2 + nelem_b3 + nelem_b4 + 1 => PrescribedConditions(Fz_follower = Fz[i]),
# fixed endpoint on last beam
nelem+1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),
)
_, converged = static_analysis!(system, assembly, prescribed_conditions=prescribed_conditions,
reset_state = false)
nonlinear_follower_states[i] = AssemblyState(system, assembly;
prescribed_conditions=prescribed_conditions)
@test converged
end
end
@testset "Nonlinear Dynamic Analysis of a Joined-Wing" begin
# Set endpoints of each beam
p1 = [0, 0, 0]
p2 = [-7.1726, -12, -3.21539]
p3 = [7.1726, -12, 3.21539]
Cab_1 = [
0.5 0.866025 0.0
0.836516 -0.482963 0.258819
0.224144 -0.12941 -0.965926
]
Cab_2 = [
0.5 0.866025 0.0
-0.836516 0.482963 0.258819
0.224144 -0.12941 0.965926
]
# beam 1
L_b1 = norm(p1-p2)
r_b1 = p2
nelem_b1 = 8
lengths_b1, xp_b1, xm_b1, Cab_b1 = discretize_beam(L_b1, r_b1, nelem_b1, frame=Cab_1)
# beam 2
L_b2 = norm(p3-p1)
r_b2 = p1
nelem_b2 = 8
lengths_b2, xp_b2, xm_b2, Cab_b2 = discretize_beam(L_b2, r_b2, nelem_b2, frame=Cab_2)
# combine elements and points into one array
nelem = nelem_b1 + nelem_b2
points = vcat(xp_b1, xp_b2[2:end])
start = 1:nelem
stop = 2:nelem + 1
lengths = vcat(lengths_b1, lengths_b2)
midpoints = vcat(xm_b1, xm_b2)
Cab = vcat(Cab_b1, Cab_b2)
# assign all beams the same compliance and mass matrix
compliance = fill(Diagonal([2.93944738387698e-10, 8.42991725049126e-10, 3.38313996669689e-08,
4.69246721094557e-08, 6.79584100559513e-08, 1.37068861370898e-09]), nelem)
mass = fill(Diagonal([4.86e-2, 4.86e-2, 4.86e-2,
1.0632465e-2, 2.10195e-4, 1.042227e-2]), nelem)
# create assembly
assembly = Assembly(points, start, stop; compliance=compliance, mass=mass,
frames=Cab, lengths=lengths, midpoints=midpoints)
# time
tvec = range(0, 0.04, length=1001)
F_L = (t) -> begin
if 0.0 <= t < 0.01
1e6*t
elseif 0.01 <= t < 0.02
-1e6*(t-0.02)
else
zero(t)
end
end
F_S = (t) -> begin
if 0.0 <= t < 0.02
5e3*(1-cos(pi*t/0.02))
else
1e4
end
end
# assign boundary conditions and point load
prescribed_conditions = (t) -> begin
Dict(
# fixed endpoint on beam 1
1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),
# force applied on point 4
nelem_b1 + 1 => PrescribedConditions(Fx=F_L(t), Fy=F_L(t), Fz=F_S(t)),
# fixed endpoint on last beam
nelem+1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),
)
end
system, history, converged = time_domain_analysis(assembly, tvec;
prescribed_conditions=prescribed_conditions)
@test converged
end
@testset "DifferentialEquations" begin
L = 60 # m
# create points
nelem = 10
x = range(0, L, length=nelem+1)
y = zero(x)
z = zero(x)
points = [[x[i],y[i],z[i]] for i = 1:length(x)]
# index of endpoints of each beam element
start = 1:nelem
stop = 2:nelem+1
# stiffness matrix for each beam element
stiffness = fill(
[2.389e9 1.524e6 6.734e6 -3.382e7 -2.627e7 -4.736e8
1.524e6 4.334e8 -3.741e6 -2.935e5 1.527e7 3.835e5
6.734e6 -3.741e6 2.743e7 -4.592e5 -6.869e5 -4.742e6
-3.382e7 -2.935e5 -4.592e5 2.167e7 -6.279e5 1.430e6
-2.627e7 1.527e7 -6.869e5 -6.279e5 1.970e7 1.209e7
-4.736e8 3.835e5 -4.742e6 1.430e6 1.209e7 4.406e8],
nelem)
# mass matrix for each beam element
mass = fill(
[258.053 0.0 0.0 0.0 7.07839 -71.6871
0.0 258.053 0.0 -7.07839 0.0 0.0
0.0 0.0 258.053 71.6871 0.0 0.0
0.0 -7.07839 71.6871 48.59 0.0 0.0
7.07839 0.0 0.0 0.0 2.172 0.0
-71.6871 0.0 0.0 0.0 0.0 46.418],
nelem)
# create assembly of interconnected nonlinear beams
assembly = Assembly(points, start, stop; stiffness=stiffness, mass=mass)
# prescribed conditions
prescribed_conditions = (t) -> begin
Dict(
# fixed left side
1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),
# force on right side
nelem+1 => PrescribedConditions(Fz=1e5*sin(20*t))
)
end
# define simulation time
tspan = (0.0, 2.0)
# run initial condition analysis to get consistent set of initial conditions
system, converged = initial_condition_analysis(assembly, tspan[1]; prescribed_conditions)
# construct ODEProblem
prob = ODEProblem(system, assembly, tspan; prescribed_conditions)
# solve ODEProblem
sol = solve(prob, Rodas4())
# test that solution worked
@test sol.t[end] == 2.0
# construct DAEProblem
prob = DAEProblem(system, assembly, tspan; prescribed_conditions)
# solve DAEProblem
sol = solve(prob, DABDF2())
# test that solution worked
@test sol.t[end] == 2.0
end
@testset "ForwardDiff" begin
# Linear Analysis of a Beam Under a Linear Distributed Load
function linear_analysis_test_with_AD(length) # this should affect just about everything
nelem = 16
# create points
L = length[1]
x = collect(range(0, L, length=nelem+1))
y = zero(x)
z = zero(x)
points = [[x[i],y[i],z[i]] for i = 1:size(x,1)]
# index of endpoints for each beam element
start = 1:nelem
stop = 2:nelem+1
# create compliance matrix for each beam element
EI = 1e7
compliance = fill(Diagonal([0, 0, 0, 0, 1/EI, 0]), nelem)
# create assembly
assembly = Assembly(points, start, stop, compliance=compliance)
# set prescribed conditions
prescribed_conditions = Dict(
# simply supported left endpoint
1 => PrescribedConditions(uz=0),
# clamped right endpoint
nelem+1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0)
)
# create distributed load
qmax = 1000
distributed_loads = Dict()
for i = 1:nelem
distributed_loads[i] = DistributedLoads(assembly, i; s1=x[i],
s2=x[i+1], fz = (s) -> qmax*s)
end
# solve system
system, converged = static_analysis(assembly, prescribed_conditions=prescribed_conditions,
distributed_loads=distributed_loads, linear=true)
return system.x
end
# run FrowardDiff - no specific test, just make sure it runs fine
J = ForwardDiff.jacobian(linear_analysis_test_with_AD, [1.0]) #length=1
end
@testset "Zero Mass Matrix" begin
sweep = 45 * pi/180
rpm = 750
# straight section of the beam
L_b1 = 31.5 # inch
r_b1 = [2.5, 0, 0]
nelem_b1 = 13
lengths_b1, xp_b1, xm_b1, Cab_b1 = discretize_beam(L_b1, r_b1, nelem_b1)
# swept section of the beam
L_b2 = 6 # inch
r_b2 = [34, 0, 0]
nelem_b2 = 3
cs, ss = cos(sweep), sin(sweep)
frame_b2 = [cs ss 0; -ss cs 0; 0 0 1]
lengths_b2, xp_b2, xm_b2, Cab_b2 = discretize_beam(L_b2, r_b2, nelem_b2, frame=frame_b2)
# combine elements and points into one array
nelem = nelem_b1 + nelem_b2
points = vcat(xp_b1, xp_b2[2:end])
start = 1:nelem_b1 + nelem_b2
stop = 2:nelem_b1 + nelem_b2 + 1
lengths = vcat(lengths_b1, lengths_b2)
midpoints = vcat(xm_b1, xm_b2)
Cab = vcat(Cab_b1, Cab_b2)
# cross section
w = 1 # inch
h = 0.063 # inch
# material properties
E = 1.06e7 # lb/in^2
ν = 0.325
ρ = 2.51e-4 # lb sec^2/in^4
# shear and torsion correction factors
ky = 1.2000001839588001
kz = 14.625127919304001
kt = 65.85255016982444
A = h*w
Iyy = w*h^3/12
Izz = w^3*h/12
J = Iyy + Izz
# apply corrections
Ay = A/ky
Az = A/kz
Jx = J/kt
G = E/(2*(1+ν))
compliance = fill(Diagonal([1/(E*A), 1/(G*Ay), 1/(G*Az), 1/(G*Jx), 1/(E*Iyy), 1/(E*Izz)]), nelem)
mass = fill(Diagonal(zeros(6)), nelem)
# create assembly
assembly = Assembly(points, start, stop, compliance=compliance, mass=mass, frames=Cab, lengths=lengths, midpoints=midpoints)
# create dictionary of prescribed conditions
prescribed_conditions = Dict(
# root section is fixed
1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0)
)
# set angular velocity vector
w0 = [0, 0, rpm*(2*pi)/60]
# perform nonlinear steady state analysis
system, converged = steady_state_analysis(assembly,
angular_velocity = w0,
prescribed_conditions = prescribed_conditions)
# test convergence
@test converged
end
@testset "Zero Length Element" begin
sweep = 45 * pi/180
rpm = 750
# straight section of the beam
L_b1 = 31.5 # inch
r_b1 = [2.5, 0, 0]
nelem_b1 = 13
lengths_b1, xp_b1, xm_b1, Cab_b1 = discretize_beam(L_b1, r_b1, nelem_b1)
# zero length element between straight and swept sections
L_b12 = 0
r_b12 = [34, 0, 0]
nelem_b12 = 1
lengths_b12, xp_b12, xm_b12, Cab_b12 = discretize_beam(L_b12, r_b12, nelem_b12)
# swept section of the beam
L_b2 = 6 # inch
r_b2 = [34, 0, 0]
nelem_b2 = 3
cs, ss = cos(sweep), sin(sweep)
frame_b2 = [cs ss 0; -ss cs 0; 0 0 1]
lengths_b2, xp_b2, xm_b2, Cab_b2 = discretize_beam(L_b2, r_b2, nelem_b2, frame=frame_b2)
# combine elements and points into one array
nelem = nelem_b1 + nelem_b12 + nelem_b2
points = vcat(xp_b1, xp_b2[2:end]) # don't duplicate points
lengths = vcat(lengths_b1, lengths_b12, lengths_b2)
midpoints = vcat(xm_b1, xm_b12, xm_b2)
Cab = vcat(Cab_b1, Cab_b12, Cab_b2)
# specify connectivity
start = vcat(1:nelem_b1+1, nelem_b1+1:nelem_b1+nelem_b2)
stop = vcat(2:nelem_b1+1, nelem_b1+1:nelem_b1+nelem_b2+1)
# cross section
w = 1 # inch
h = 0.063 # inch
# material properties
E = 1.06e7 # lb/in^2
ν = 0.325
ρ = 2.51e-4 # lb sec^2/in^4
# shear and torsion correction factors
ky = 1.2000001839588001
kz = 14.625127919304001
kt = 65.85255016982444
A = h*w
Iyy = w*h^3/12
Izz = w^3*h/12
J = Iyy + Izz
# apply corrections
Ay = A/ky
Az = A/kz
Jx = J/kt
G = E/(2*(1+ν))
compliance = fill(Diagonal([1/(E*A), 1/(G*Ay), 1/(G*Az), 1/(G*Jx), 1/(E*Iyy), 1/(E*Izz)]), nelem)
mass = fill(Diagonal([ρ*A, ρ*A, ρ*A, ρ*J, ρ*Iyy, ρ*Izz]), nelem)
# create assembly
assembly = Assembly(points, start, stop, compliance=compliance, mass=mass, frames=Cab, lengths=lengths, midpoints=midpoints)
# create dictionary of prescribed conditions
prescribed_conditions = Dict(
# root section is fixed
1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0)
)
# set angular velocity vector
w0 = [0, 0, rpm*(2*pi)/60]
# perform nonlinear steady state analysis
system, converged = steady_state_analysis(assembly,
angular_velocity = w0,
prescribed_conditions = prescribed_conditions)
# test convergence
@test converged
end
@testset "Element Gravitational Loads" begin
# use arbitrary length
ΔL = rand()
# use random rotation matrix
CtCab = GXBeam.get_C(rand(3))
# create random mass matrix
μ = rand()
xm2 = rand()
xm3 = rand()
i22 = rand()
i33 = rand()
i23 = rand()
mass = [
μ 0 0 0 μ*xm3 -μ*xm2;
0 μ 0 -μ*xm3 0 0;
0 0 μ μ*xm2 0 0;
0 -μ*xm3 μ*xm2 i22+i33 0 0;
μ*xm3 0 0 0 i22 0;
-μ*xm2 0 0 0 0 i33
]
# use random gravity vector
gvec = rand(3)
# calculate integrated force and moment per unit length
f = μ*gvec
m = cross(CtCab*[0, xm2, xm3], f)
f1 = f2 = ΔL*f/2
m1 = m2 = ΔL*m/2
# test against gravitational load function results
mass11 = ΔL*mass[1:3, 1:3]
mass12 = ΔL*mass[1:3, 4:6]
mass21 = ΔL*mass[4:6, 1:3]
mass22 = ΔL*mass[4:6, 4:6]
a = -gvec
α = zero(a)
f1t, f2t, m1t, m2t = GXBeam.acceleration_loads(mass11, mass12, mass21, mass22, CtCab, a, α)
@test isapprox(f1, f1t)
@test isapprox(f2, f2t)
@test isapprox(m1, m1t)
@test isapprox(m2, m2t)
end
@testset "Point Masses" begin
nodes = [[0,i,0] for i in 0:.1:1]
nelem = length(nodes)-1
start = 1:nelem
stop = 2:(nelem+1)
frames = fill(wiener_milenkovic(rand(3)), nelem)
compliance = fill(Symmetric(rand(6,6)), nelem)
mass = fill(Symmetric(rand(6,6)), nelem)
prescribed_conditions = Dict(1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0));
# assembly of mass-containing beam elements
assembly = GXBeam.Assembly(nodes, start, stop;
compliance=compliance,
frames=frames,
mass=mass);
system, λ, V, converged = GXBeam.eigenvalue_analysis(assembly;
prescribed_conditions = prescribed_conditions,
nev = 14);
imagλ = imag(λ)
isort = sortperm(abs.(imagλ))
freq = imagλ[isort[1:2:10]]/(2*pi)
# assembly of massless beam elements with point masses
assembly = GXBeam.Assembly(nodes, start, stop;
compliance=compliance,
frames=frames);
point_masses = Dict{Int, PointMass{Float64}}()
for i = 1:nelem
T = [frames[i] zeros(3,3); zeros(3,3) frames[i]]
point_masses[i] = PointMass(T * mass[i] * T' .* assembly.elements[i].L)
end
system, λ, V, converged = GXBeam.eigenvalue_analysis(assembly;
prescribed_conditions = prescribed_conditions,
point_masses = point_masses,
nev = 14);
imagλ = imag(λ)
isort = sortperm(abs.(imagλ))
pfreq = imagλ[isort[1:2:10]]/(2*pi)
# test the two equivalent systems
@test isapprox(freq, pfreq)
end
| 32.844749
| 132
| 0.606363
|
[
"@testset \"Math\" begin\n \n c = rand(3)\n cdot = rand(3)\n\n # get_C_θ\n C_θ1, C_θ2, C_θ3 = GXBeam.get_C_θ(c)\n @test isapprox(C_θ1, ForwardDiff.derivative(c1 -> GXBeam.get_C([c1, c[2], c[3]]), c[1]))\n @test isapprox(C_θ2, ForwardDiff.derivative(c2 -> GXBeam.get_C([c[1], c2, c[3]]), c[2]))\n @test isapprox(C_θ3, ForwardDiff.derivative(c3 -> GXBeam.get_C([c[1], c[2], c3]), c[3]))\n\n # get_C_t_θ\n Cdot_θ1, Cdot_θ2, Cdot_θ3 = GXBeam.get_C_t_θ(c, cdot)\n @test isapprox(Cdot_θ1, ForwardDiff.derivative(c1 -> GXBeam.get_C_t([c1, c[2], c[3]], cdot), c[1]))\n @test isapprox(Cdot_θ2, ForwardDiff.derivative(c2 -> GXBeam.get_C_t([c[1], c2, c[3]], cdot), c[2]))\n @test isapprox(Cdot_θ3, ForwardDiff.derivative(c3 -> GXBeam.get_C_t([c[1], c[2], c3], cdot), c[3]))\n\n # get_C_t_θdot\n Cdot_θdot1, Cdot_θdot2, Cdot_θdot3 = GXBeam.get_C_t_θdot(c)\n @test isapprox(Cdot_θdot1, ForwardDiff.derivative(cdot1 -> GXBeam.get_C_t(c, [cdot1, cdot[2], cdot[3]]), cdot[1]))\n @test isapprox(Cdot_θdot2, ForwardDiff.derivative(cdot2 -> GXBeam.get_C_t(c, [cdot[1], cdot2, cdot[3]]), cdot[2]))\n @test isapprox(Cdot_θdot3, ForwardDiff.derivative(cdot3 -> GXBeam.get_C_t(c, [cdot[1], cdot[2], cdot3]), cdot[3]))\n \n # get_Q_θ\n Q_θ1, Q_θ2, Q_θ3 = GXBeam.get_Q_θ(c)\n @test isapprox(Q_θ1, ForwardDiff.derivative(c1 -> GXBeam.get_Q([c1, c[2], c[3]]), c[1]))\n @test isapprox(Q_θ2, ForwardDiff.derivative(c2 -> GXBeam.get_Q([c[1], c2, c[3]]), c[2]))\n @test isapprox(Q_θ3, ForwardDiff.derivative(c3 -> GXBeam.get_Q([c[1], c[2], c3]), c[3]))\n\n # get_Qinv_θ\n Qinv_θ1, Qinv_θ2, Qinv_θ3 = GXBeam.get_Qinv_θ(c)\n @test isapprox(Qinv_θ1, ForwardDiff.derivative(c1 -> GXBeam.get_Qinv([c1, c[2], c[3]]), c[1]))\n @test isapprox(Qinv_θ2, ForwardDiff.derivative(c2 -> GXBeam.get_Qinv([c[1], c2, c[3]]), c[2]))\n @test isapprox(Qinv_θ3, ForwardDiff.derivative(c3 -> GXBeam.get_Qinv([c[1], c[2], c3]), c[3]))\n\nend",
"@testset \"Jacobian and Mass Matrix Calculations\" begin\n\n L = 60 # m\n\n # create points\n nelem = 1\n x = range(0, L, length=nelem+1)\n y = zero(x)\n z = zero(x)\n points = [[x[i],y[i],z[i]] for i = 1:length(x)]\n\n # index of endpoints of each beam element\n start = 1:nelem\n stop = 2:nelem+1\n\n # stiffness matrix for each beam element\n stiffness = fill(\n [2.389e9 1.524e6 6.734e6 -3.382e7 -2.627e7 -4.736e8\n 1.524e6 4.334e8 -3.741e6 -2.935e5 1.527e7 3.835e5\n 6.734e6 -3.741e6 2.743e7 -4.592e5 -6.869e5 -4.742e6\n -3.382e7 -2.935e5 -4.592e5 2.167e7 -6.279e5 1.430e6\n -2.627e7 1.527e7 -6.869e5 -6.279e5 1.970e7 1.209e7\n -4.736e8 3.835e5 -4.742e6 1.430e6 1.209e7 4.406e8],\n nelem)\n\n # mass matrix for each beam element\n mass = fill(\n [258.053 0.0 0.0 0.0 7.07839 -71.6871\n 0.0 258.053 0.0 -7.07839 0.0 0.0\n 0.0 0.0 258.053 71.6871 0.0 0.0\n 0.0 -7.07839 71.6871 48.59 0.0 0.0\n 7.07839 0.0 0.0 0.0 2.172 0.0\n -71.6871 0.0 0.0 0.0 0.0 46.418],\n nelem)\n\n # create assembly of interconnected nonlinear beams\n assembly = Assembly(points, start, stop; stiffness=stiffness, mass=mass)\n\n # prescribed conditions\n pcond = Dict(\n # fixed left side\n 1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),\n )\n\n # distributed loads\n dload = Dict()\n\n # point masses\n pmass = Dict(\n # point mass at the end of the beam\n nelem => PointMass(Symmetric(rand(6,6)))\n )\n\n # gravity vector\n gvec = rand(3)\n\n # --- Static Analysis --- #\n static_system = System(assembly, true)\n\n force_scaling = static_system.force_scaling\n irow_point = static_system.irow_point\n irow_elem = static_system.irow_elem\n irow_elem1 = static_system.irow_elem1\n irow_elem2 = static_system.irow_elem2\n icol_point = static_system.icol_point\n icol_elem = static_system.icol_elem\n\n x = rand(length(static_system.x))\n J = similar(x, length(x), length(x))\n\n f = (x) -> GXBeam.static_system_residual!(similar(x), x, assembly, pcond, dload, pmass, gvec,\n force_scaling, irow_point, irow_elem1, irow_elem2, icol_point, icol_elem)\n\n GXBeam.static_system_jacobian!(J, x, assembly, pcond, dload, pmass, gvec, force_scaling,\n irow_point, irow_elem1, irow_elem2, icol_point, icol_elem)\n\n @test all(isapprox.(J, ForwardDiff.jacobian(f, x), atol=1e-10))\n\n # --- Steady State Analysis --- #\n\n system = System(assembly, false)\n\n force_scaling = system.force_scaling\n irow_point = system.irow_point\n irow_elem = system.irow_elem\n irow_elem1 = system.irow_elem1\n irow_elem2 = system.irow_elem2\n icol_point = system.icol_point\n icol_elem = system.icol_elem\n x0 = rand(3)\n v0 = rand(3)\n ω0 = rand(3)\n a0 = rand(3)\n α0 = rand(3)\n\n x = rand(length(system.x))\n J = similar(x, length(x), length(x))\n\n f = (x) -> GXBeam.steady_state_system_residual!(similar(x), x, assembly, pcond, dload, \n pmass, gvec, force_scaling, irow_point, irow_elem, irow_elem1, irow_elem2,\n icol_point, icol_elem, x0, v0, ω0, a0, α0)\n\n GXBeam.steady_state_system_jacobian!(J, x, assembly, pcond, dload, pmass, gvec, force_scaling,\n irow_point, irow_elem, irow_elem1, irow_elem2, icol_point,\n icol_elem, x0, v0, ω0, a0, α0)\n\n @test all(isapprox.(J, ForwardDiff.jacobian(f, x), atol=1e-10))\n\n # --- Initial Condition Analysis --- #\n\n u0 = [rand(3) for ielem = 1:length(assembly.elements)]\n theta0 = [rand(3) for ielem = 1:length(assembly.elements)]\n udot0 = [rand(3) for ielem = 1:length(assembly.elements)]\n thetadot0 = [rand(3) for ielem = 1:length(assembly.elements)]\n\n x = rand(length(system.x))\n J = similar(x, length(x), length(x))\n\n f = (x) -> GXBeam.initial_condition_system_residual!(similar(x), x, assembly, pcond, dload, pmass, gvec,\n force_scaling, irow_point, irow_elem, irow_elem1, irow_elem2,\n icol_point, icol_elem, x0, v0, ω0, a0, α0, u0, theta0, udot0, thetadot0)\n\n GXBeam.initial_condition_system_jacobian!(J, x, assembly, pcond, dload, pmass, gvec, force_scaling,\n irow_point, irow_elem, irow_elem1, irow_elem2, icol_point,\n icol_elem, x0, v0, ω0, a0, α0, u0, theta0, udot0, thetadot0)\n\n @test all(isapprox.(J, ForwardDiff.jacobian(f, x), atol=1e-10))\n\n # --- Newmark Scheme Time-Marching Analysis --- #\n\n udot = [rand(3) for ielem = 1:length(assembly.elements)]\n θdot = [rand(3) for ielem = 1:length(assembly.elements)]\n Vdot = [rand(3) for ielem = 1:length(assembly.elements)]\n Ωdot = [rand(3) for ielem = 1:length(assembly.elements)]\n dt = rand()\n\n x = rand(length(system.x))\n J = similar(x, length(x), length(x))\n\n f = (x) -> GXBeam.newmark_system_residual!(similar(x), x, assembly, pcond, dload, pmass, gvec,\n force_scaling, irow_point, irow_elem, irow_elem1, irow_elem2,\n icol_point, icol_elem, x0, v0, ω0, a0, α0, udot, θdot, Vdot, Ωdot, dt)\n\n GXBeam.newmark_system_jacobian!(J, x, assembly, pcond, dload, pmass, gvec, force_scaling,\n irow_point, irow_elem, irow_elem1, irow_elem2, icol_point,\n icol_elem, x0, v0, ω0, a0, α0, udot, θdot, Vdot, Ωdot, dt)\n\n @test all(isapprox.(J, ForwardDiff.jacobian(f, x), atol=1e-10))\n\n # --- General Dynamic Analysis --- #\n\n dx = rand(length(system.x))\n x = rand(length(system.x))\n J = similar(x, length(x), length(x))\n M = similar(x, length(x), length(x))\n\n fx = (x) -> GXBeam.dynamic_system_residual!(similar(x), dx, x, assembly, pcond, dload, \n pmass, gvec, force_scaling, irow_point, irow_elem, irow_elem1, irow_elem2,\n icol_point, icol_elem, x0, v0, ω0, a0, α0)\n\n fdx = (dx) -> GXBeam.dynamic_system_residual!(similar(dx), dx, x, assembly, pcond, dload, \n pmass, gvec, force_scaling, irow_point, irow_elem, irow_elem1, irow_elem2,\n icol_point, icol_elem, x0, v0, ω0, a0, α0)\n\n GXBeam.dynamic_system_jacobian!(J, dx, x, assembly, pcond, dload, pmass, gvec, force_scaling, \n irow_point, irow_elem, irow_elem1, irow_elem2, icol_point, icol_elem,\n x0, v0, ω0, a0, α0)\n\n GXBeam.system_mass_matrix!(M, x, assembly, pmass, force_scaling, irow_point,\n irow_elem, irow_elem1, irow_elem2, icol_point, icol_elem)\n\n @test all(isapprox.(J, ForwardDiff.jacobian(fx, x), atol=1e-10))\n\n @test all(isapprox.(M, ForwardDiff.jacobian(fdx, x), atol=1e-10))\n\nend",
"@testset \"Linear Analysis of a Cantilever Partially Under a Uniform Distributed Load\" begin\n\n nelem = 12\n\n # create points\n a = 0.3\n b = 0.7\n L = 1.0\n n1 = n3 = div(nelem, 3)\n n2 = nelem - n1 - n3\n x1 = range(0, a, length=n1+1)\n x2 = range(a, b, length=n2+1)\n x3 = range(b, L, length=n3+1)\n x = vcat(x1, x2[2:end], x3[2:end])\n y = zero(x)\n z = zero(x)\n points = [[x[i],y[i],z[i]] for i = 1:length(x)]\n\n # index of endpoints for each beam element\n start = 1:nelem\n stop = 2:nelem+1\n\n # create compliance matrix for each beam element\n EI = 1e9\n stiffness = fill(Diagonal([0, 0, 0, 0, EI, 0]), nelem)\n\n # create the assembly\n assembly = Assembly(points, start, stop, stiffness=stiffness)\n\n # set prescribed conditions (fixed right endpoint)\n prescribed_conditions = Dict(\n nelem+1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0)\n )\n\n # create distributed load\n q = 1000\n distributed_loads = Dict()\n for ielem in n1+1:n1+n2\n distributed_loads[ielem] = DistributedLoads(assembly, ielem; fz = (s) -> q)\n end\n\n system, converged = static_analysis(assembly, prescribed_conditions=prescribed_conditions,\n distributed_loads=distributed_loads, linear=true)\n\n state = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)\n\n # analytical solution obtained using superposition\n initial_slope = -q/(6*EI)*((L-a)^3 - (L-b)^3)\n initial_deflection = q/(24*EI)*((L-a)^3*(3*L + a) - (L-b)^3*(3*L + b))\n analytical_M = function(x)\n if 0 < x <= a\n M = 0.0\n elseif a < x <= b\n M = q/2*(x-a)^2\n else\n M = q/2*((x-a)^2 - (x-b)^2)\n end\n return M\n end\n analytical_slope = function(x)\n slope = initial_slope\n if 0 < x <= a\n slope += 0.0\n elseif a < x <= b\n slope += q/(6*EI)*(x-a)^3\n else\n slope += q/(6*EI)*((x-a)^3 - (x-b)^3)\n end\n return slope\n end\n analytical_deflection = function(x)\n deflection = initial_deflection + initial_slope*x\n if 0 < x <= a\n deflection += 0.0\n elseif a < x <= b\n deflection += q/(24*EI)*(x-a)^4\n else\n deflection += q/(24*EI)*((x-a)^4 - (x-b)^4)\n end\n return deflection\n end\n\n # test element properties\n for i = 1:length(assembly.elements)\n xi = assembly.elements[i].x[1]\n @test isapprox(state.elements[i].u[3], analytical_deflection(xi), atol=1e-9)\n @test isapprox(state.elements[i].theta[2], -4*analytical_slope(xi)/4, atol=1e-9)\n @test isapprox(state.elements[i].M[2], -analytical_M(xi), atol=2)\n end\n\n # test point properties\n for i = 1:length(assembly.points)\n xi = assembly.points[i][1]\n @test isapprox(state.points[i].u[3], analytical_deflection(xi), atol=1e-8)\n @test isapprox(state.points[i].theta[2], -4*analytical_slope(xi)/4, atol=1e-7)\n end\nend",
"@testset \"Linear Analysis of a Beam Under a Linear Distributed Load\" begin\n\n nelem = 16\n\n # create points\n L = 1\n x = range(0, L, length=nelem+1)\n y = zero(x)\n z = zero(x)\n points = [[x[i],y[i],z[i]] for i = 1:length(x)]\n\n # index of endpoints for each beam element\n start = 1:nelem\n stop = 2:nelem+1\n\n # create compliance matrix for each beam element\n EI = 1e7\n compliance = fill(Diagonal([0, 0, 0, 0, 1/EI, 0]), nelem)\n\n # create assembly\n assembly = Assembly(points, start, stop, compliance=compliance)\n\n # set prescribed conditions\n prescribed_conditions = Dict(\n # simply supported left endpoint\n 1 => PrescribedConditions(uz=0),\n # clamped right endpoint\n nelem+1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0)\n )\n\n # create distributed load\n qmax = 1000\n distributed_loads = Dict()\n for i = 1:nelem\n distributed_loads[i] = DistributedLoads(assembly, i; s1=x[i],\n s2=x[i+1], fz = (s) -> qmax*s)\n end\n\n # solve system\n system, converged = static_analysis(assembly, prescribed_conditions=prescribed_conditions,\n distributed_loads=distributed_loads, linear=true)\n\n # post-process the results\n state = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)\n\n # construct analytical solution\n analytical_deflection = (x) -> qmax*(1-x)^2/(120*EI)*(4 - 8*(1-x) + 5*(1-x)^2 - (1-x)^3)\n analytical_slope = (x) -> -qmax*(1-x)/(120*EI)*(8 - 24*(1-x) + 20*(1-x)^2 - 5*(1-x)^3)\n analytical_M = (x) -> qmax/120*(8 - 48*(1-x) + 60*(1-x)^2 - 20*(1-x)^3)\n\n # test element properties\n for i = 1:length(assembly.elements)\n xi = assembly.elements[i].x[1]\n @test isapprox(state.elements[i].u[3], analytical_deflection(xi), atol=1e-8)\n @test isapprox(state.elements[i].theta[2], -4*analytical_slope(xi)/4, atol=1e-7)\n @test isapprox(state.elements[i].M[2], -analytical_M(xi), atol=1)\n end\n\n # test point properties\n for i = 1:length(assembly.points)\n xi = assembly.points[i][1]\n @test isapprox(state.points[i].u[3], analytical_deflection(xi), atol=1e-8)\n @test isapprox(state.points[i].theta[2], -4*analytical_slope(xi)/4, atol=1e-8)\n end\nend",
"@testset \"Nonlinear Analysis of a Cantilever Subjected to a Constant Tip Load\" begin\n\n L = 1\n EI = 1e6\n\n # shear force (applied at end)\n λ = 0:0.5:16\n p = EI/L^2\n P = λ*p\n\n # create points\n nelem = 16\n x = range(0, L, length=nelem+1)\n y = zero(x)\n z = zero(x)\n points = [[x[i],y[i],z[i]] for i = 1:length(x)]\n\n # index of endpoints of each beam element\n start = 1:nelem\n stop = 2:nelem+1\n\n # compliance matrix for each beam element\n compliance = fill(Diagonal([0, 0, 0, 0, 1/EI, 0]), nelem)\n\n # create assembly of interconnected nonlinear beams\n assembly = Assembly(points, start, stop, compliance=compliance)\n\n # pre-initialize system storage\n system = System(assembly, true)\n\n # run an analysis for each prescribed tip load\n states = Vector{AssemblyState{Float64}}(undef, length(P))\n for i = 1:length(P)\n\n # create dictionary of prescribed conditions\n prescribed_conditions = Dict(\n # fixed left side\n 1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),\n # shear force on right tip\n nelem+1 => PrescribedConditions(Fz = P[i])\n )\n\n # perform a static analysis\n static_analysis!(system, assembly, prescribed_conditions=prescribed_conditions)\n\n # post-process the results\n states[i] = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)\n\n end\n\n # construct analytical solution\n δ = range(pi/4, pi/2, length=10^5)[2:end-1]\n\n k = @. cos(pi/4)/sin(δ)\n λ_a = @. (Elliptic.F(pi/2, k^2) - Elliptic.F(δ, k^2))^2\n\n θ_a = @. 2*(pi/4 - acos(k))\n\n ξ_a = @. sqrt(2*sin(θ_a)/λ_a) .- 1\n\n η_a = @. 1-2/sqrt(λ_a)*(Elliptic.E(pi/2, k^2) - Elliptic.E(δ, k^2))\n\n # test tip displacements\n for i = 1:length(P)\n i_a = argmin(abs.(λ[i] .- λ_a))\n @test isapprox(states[i].points[end].u[1]/L, ξ_a[i_a], atol=1e-3)\n @test isapprox(states[i].points[end].u[3]/L, η_a[i_a], atol=1e-3)\n @test isapprox(states[i].points[end].theta[2], -4*tan(θ_a[i_a]/4), atol=1e-2)\n end\nend",
"@testset \"Nonlinear Analysis of a Cantilever Subjected to a Constant Moment\" begin\n\n L = 12 # inches\n h = w = 1 # inches\n E = 30e6 # lb/in^4 Young's Modulus\n\n A = h*w\n Iyy = w*h^3/12\n Izz = w^3*h/12\n\n # bending moment (applied at end)\n # note that solutions for λ > 1.8 do not converge\n λ = [0.0, 0.4, 0.8, 1.2, 1.6, 1.8, 2.0]\n m = pi*E*Iyy/L\n M = λ*m\n\n # create points\n nelem = 16\n x = range(0, L, length=nelem+1)\n y = zero(x)\n z = zero(x)\n points = [[x[i],y[i],z[i]] for i = 1:length(x)]\n\n # index of endpoints for each beam element\n start = 1:nelem\n stop = 2:nelem+1\n\n # compliance matrix for each beam element\n compliance = fill(Diagonal([1/(E*A), 0, 0, 0, 1/(E*Iyy), 1/(E*Izz)]), nelem)\n\n # create assembly of interconnected nonlinear beams\n assembly = Assembly(points, start, stop, compliance=compliance)\n\n # pre-initialize system storage\n system = System(assembly, true)\n\n # run an analysis for each prescribed bending moment\n states = Vector{AssemblyState{Float64}}(undef, length(M))\n for i = 1:length(M)\n\n # create dictionary of prescribed conditions\n prescribed_conditions = Dict(\n # fixed left side\n 1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),\n # moment on right side\n nelem+1 => PrescribedConditions(Mz = M[i])\n )\n\n # perform a static analysis\n static_analysis!(system, assembly, prescribed_conditions=prescribed_conditions)\n\n # post-process the results\n states[i] = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)\n\n end\n\n # analytical solution (ρ = E*I/M)\n analytical(x, ρ) = ifelse(ρ == Inf, zeros(3), [ρ*sin(x/ρ)-x, ρ*(1-cos(x/ρ)), 0])\n\n # test element properties\n for i = 1:length(M)\n for ielem = 1:length(assembly.elements)\n xi = assembly.elements[ielem].x[1]\n u_a, v_a, w_a = analytical(xi, E*Iyy/M[i])\n @test isapprox(states[i].elements[ielem].u[1], u_a, atol=5e-2)\n @test isapprox(states[i].elements[ielem].u[2], v_a, atol=5e-2)\n end\n\n # test point properties\n for ipoint = 1:length(assembly.points)\n xi = assembly.points[ipoint][1]\n u_a, v_a, w_a = analytical(xi, E*Iyy/M[i])\n @test isapprox(states[i].points[ipoint].u[1], u_a, atol=5e-2)\n @test isapprox(states[i].points[ipoint].u[2], v_a, atol=5e-2)\n end\n end\nend",
"@testset \"Nonlinear Analysis of the Bending of a Curved Beam in 3D Space\" begin\n\n # problem constants\n R = 100\n L = R*pi/4 # inches\n h = w = 1 # inches\n E = 1e7 # psi Young's Modulus\n ν = 0.0\n G = E/(2*(1+ν))\n\n # beam starting point, frame, and curvature\n r = [0, 0, 0]\n frame = [0 -1 0; 1 0 0; 0 0 1]\n curvature = [0, 0, -1/R]\n\n # cross section properties\n A = h*w\n Ay = A\n Az = A\n Iyy = w*h^3/12\n Izz = w^3*h/12\n J = Iyy + Izz\n\n # discretize the beam\n nelem = 16\n ΔL, xp, xm, Cab = discretize_beam(L, r, nelem; frame=frame, curvature = curvature)\n\n # force\n P = 600 # lbs\n\n # index of left and right endpoints of each beam element\n start = 1:nelem\n stop = 2:nelem+1\n\n # compliance matrix for each beam element\n compliance = fill(Diagonal([1/(E*A), 1/(G*Ay), 1/(G*Az), 1/(G*J), 1/(E*Iyy), 1/(E*Izz)]), nelem)\n\n # create assembly of interconnected nonlinear beams\n assembly = Assembly(xp, start, stop, compliance=compliance, frames=Cab,\n lengths=ΔL, midpoints=xm)\n\n # create dictionary of prescribed conditions\n prescribed_conditions = Dict(\n # fixed left endpoint\n 1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),\n # force on right endpoint\n nelem+1 => PrescribedConditions(Fz=P)\n )\n\n # perform static analysis\n system, converged = static_analysis(assembly, prescribed_conditions=prescribed_conditions)\n\n # post-process results\n state = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)\n\n # Results from \"Large Displacement Analysis of Three-Dimensional Beam\n # Structures\" by Bathe and Bolourch:\n # - Tip Displacement: [-13.4, -23.5, 53.4]\n\n # Note that these results are comparing computational solutions, rather than\n # the computational to the analytical solution, so some variation is expected.\n\n @test isapprox(state.points[end].u[1], -13.4, atol=0.2) # -13.577383726758564\n @test isapprox(state.points[end].u[2], -23.5, atol=0.1) # -23.545303336988038\n @test isapprox(state.points[end].u[3], 53.4, atol=0.1) # 53.45800757548929\nend",
"@testset \"Rotating Beam with a Swept Tip\" begin\n sweep = 45 * pi/180\n rpm = 0:25:750\n\n # straight section of the beam\n L_b1 = 31.5 # inch\n r_b1 = [2.5, 0, 0]\n nelem_b1 = 13\n lengths_b1, xp_b1, xm_b1, Cab_b1 = discretize_beam(L_b1, r_b1, nelem_b1)\n\n # swept section of the beam\n L_b2 = 6 # inch\n r_b2 = [34, 0, 0]\n nelem_b2 = 3\n cs, ss = cos(sweep), sin(sweep)\n frame_b2 = [cs ss 0; -ss cs 0; 0 0 1]\n lengths_b2, xp_b2, xm_b2, Cab_b2 = discretize_beam(L_b2, r_b2, nelem_b2, frame=frame_b2)\n\n # combine elements and points into one array\n nelem = nelem_b1 + nelem_b2\n points = vcat(xp_b1, xp_b2[2:end])\n start = 1:nelem_b1 + nelem_b2\n stop = 2:nelem_b1 + nelem_b2 + 1\n lengths = vcat(lengths_b1, lengths_b2)\n midpoints = vcat(xm_b1, xm_b2)\n Cab = vcat(Cab_b1, Cab_b2)\n\n # cross section\n w = 1 # inch\n h = 0.063 # inch\n\n # material properties\n E = 1.06e7 # lb/in^2\n ν = 0.325\n ρ = 2.51e-4 # lb sec^2/in^4\n\n # shear and torsion correction factors\n ky = 1.2000001839588001\n kz = 14.625127919304001\n kt = 65.85255016982444\n\n A = h*w\n Iyy = w*h^3/12\n Izz = w^3*h/12\n J = Iyy + Izz\n\n # apply corrections\n Ay = A/ky\n Az = A/kz\n Jx = J/kt\n\n G = E/(2*(1+ν))\n\n compliance = fill(Diagonal([1/(E*A), 1/(G*Ay), 1/(G*Az), 1/(G*Jx), 1/(E*Iyy), 1/(E*Izz)]), nelem)\n\n mass = fill(Diagonal([ρ*A, ρ*A, ρ*A, ρ*J, ρ*Iyy, ρ*Izz]), nelem)\n\n # create assembly\n assembly = Assembly(points, start, stop, compliance=compliance, mass=mass, frames=Cab, lengths=lengths, midpoints=midpoints)\n\n # create dictionary of prescribed conditions\n prescribed_conditions = Dict(\n # root section is fixed\n 1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0)\n )\n\n nonlinear_states = Vector{AssemblyState{Float64}}(undef, length(rpm))\n linear_states = Vector{AssemblyState{Float64}}(undef, length(rpm))\n for i = 1:length(rpm)\n # global frame rotation\n w0 = [0, 0, rpm[i]*(2*pi)/60]\n\n # perform nonlinear steady state analysis\n system, converged = steady_state_analysis(assembly,\n angular_velocity = w0,\n prescribed_conditions = prescribed_conditions)\n\n nonlinear_states[i] = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)\n\n # perform linear steady state analysis\n system, converged = steady_state_analysis(assembly,\n angular_velocity = w0,\n prescribed_conditions = prescribed_conditions,\n linear = true)\n\n linear_states[i] = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)\n end\n\n\n sweep = (0:2.5:45) * pi/180\n rpm = [0, 500, 750]\n nev = 30\n\n λ = Matrix{Vector{ComplexF64}}(undef, length(sweep), length(rpm))\n U = Matrix{Matrix{ComplexF64}}(undef, length(sweep), length(rpm))\n MV = Matrix{Matrix{ComplexF64}}(undef, length(sweep), length(rpm))\n state = Matrix{AssemblyState{Float64}}(undef, length(sweep), length(rpm))\n eigenstates = Matrix{Vector{AssemblyState{ComplexF64}}}(undef, length(sweep), length(rpm))\n for i = 1:length(sweep)\n local L_b1, r_b1, nelem_b1, lengths_b1 #hide\n local xp_b1, xm_b1, Cab_b1 #hide\n local cs, ss #hide\n local L_b2, r_b2, nelem_b2, frame_b2, lengths_b2 #hide\n local xp_b2, xm_b2, Cab_b2 #hide\n local nelem, points, start, stop #hide\n local lengths, midpoints, Cab, compliance, mass, assembly #hide\n\n # straight section of the beam\n L_b1 = 31.5 # inch\n r_b1 = [2.5, 0, 0]\n nelem_b1 = 20\n lengths_b1, xp_b1, xm_b1, Cab_b1 = discretize_beam(L_b1, r_b1, nelem_b1)\n\n # swept section of the beam\n L_b2 = 6 # inch\n r_b2 = [34, 0, 0]\n nelem_b2 = 20\n cs, ss = cos(sweep[i]), sin(sweep[i])\n frame_b2 = [cs ss 0; -ss cs 0; 0 0 1]\n lengths_b2, xp_b2, xm_b2, Cab_b2 = discretize_beam(L_b2, r_b2, nelem_b2, frame=frame_b2)\n\n # combine elements and points into one array\n nelem = nelem_b1 + nelem_b2\n points = vcat(xp_b1, xp_b2[2:end])\n start = 1:nelem_b1 + nelem_b2\n stop = 2:nelem_b1 + nelem_b2 + 1\n lengths = vcat(lengths_b1, lengths_b2)\n midpoints = vcat(xm_b1, xm_b2)\n Cab = vcat(Cab_b1, Cab_b2)\n\n compliance = fill(Diagonal([1/(E*A), 1/(G*Ay), 1/(G*Az), 1/(G*Jx), 1/(E*Iyy), 1/(E*Izz)]), nelem)\n\n mass = fill(Diagonal([ρ*A, ρ*A, ρ*A, ρ*J, ρ*Iyy, ρ*Izz]), nelem)\n\n # create assembly\n assembly = Assembly(points, start, stop, compliance=compliance, mass=mass, frames=Cab, lengths=lengths, midpoints=midpoints)\n\n # create system\n system = System(assembly, false)\n\n for j = 1:length(rpm)\n # global frame rotation\n w0 = [0, 0, rpm[j]*(2*pi)/60]\n\n # eigenvalues and (right) eigenvectors\n system, λ[i,j], V, converged = eigenvalue_analysis!(system, assembly,\n angular_velocity = w0,\n prescribed_conditions = prescribed_conditions,\n nev=nev)\n\n # corresponding left eigenvectors\n U[i,j] = left_eigenvectors(system, λ[i,j], V)\n\n # post-multiply mass matrix with right eigenvector matrix\n # (we use this later for correlating eigenvalues)\n MV[i,j] = system.M * V\n\n # process state and eigenstates\n state[i,j] = AssemblyState(system, assembly; prescribed_conditions=prescribed_conditions)\n eigenstates[i,j] = [AssemblyState(system, assembly, V[:,k];\n prescribed_conditions=prescribed_conditions) for k = 1:nev]\n end\n end\n\n\n # set previous left eigenvector matrix\n U_p = copy(U[1,1])\n\n for j = 1:length(rpm)\n for i = 1:length(sweep)\n # construct correlation matrix\n C = U_p*MV[i,j]\n\n # correlate eigenmodes\n perm, corruption = correlate_eigenmodes(C)\n\n # re-arrange eigenvalues and eigenvectors\n λ[i,j] = λ[i,j][perm]\n U[i,j] = U[i,j][perm,:]\n MV[i,j] = MV[i,j][:,perm]\n eigenstates[i,j] = eigenstates[i,j][perm]\n\n # update previous eigenvector matrix\n U_p .= U[i,j]\n end\n # update previous eigenvector matrix\n U_p .= U[1,j]\n end\n\n frequency = [[imag(λ[i,j][k])/(2*pi) for i = 1:length(sweep), j=1:length(rpm)] for k = 1:2:nev]\n\n indices = [1, 2, 4]\n experiment_rpm = [0, 500, 750]\n experiment_sweep = [0, 15, 30, 45]\n experiment_frequencies = [\n [1.4 1.8 1.7 1.6;\n 10.2 10.1 10.2 10.2;\n 14.8 14.4 14.9 14.7],\n [10.3 10.2 10.4 10.4;\n 25.2 25.2 23.7 21.6;\n 36.1 34.8 30.7 26.1],\n [27.7 27.2 26.6 24.8;\n 47.0 44.4 39.3 35.1;\n 62.9 55.9 48.6 44.8]\n ]\n\n for k = 1:length(experiment_frequencies)\n for j = 1:length(experiment_sweep)\n for i = 1:length(experiment_rpm)\n ii = argmin(abs.(rpm .- experiment_rpm[i]))\n jj = argmin(abs.(sweep*180/pi .- experiment_sweep[j]))\n kk = indices[k]\n @test isapprox(frequency[kk][jj,ii], experiment_frequencies[k][i,j], atol=1, rtol=0.1)\n end\n end\n end\n\n indices = [5, 7, 6]\n experiment_frequencies = [\n 95.4 87.5 83.7 78.8;\n 106.6 120.1 122.6 117.7;\n 132.7 147.3 166.2 162.0\n ]\n\n for k = 1:size(experiment_frequencies, 1)\n for j = 1:length(experiment_sweep)\n ii = argmin(abs.(rpm .- 750))\n jj = argmin(abs.(sweep*180/pi .- experiment_sweep[j]))\n kk = indices[k]\n @test isapprox(frequency[kk][jj,ii], experiment_frequencies[k,j], rtol=0.1)\n end\n end\nend",
"@testset \"Nonlinear Dynamic Analysis of a Wind Turbine Blade\" begin\n\n L = 60 # m\n\n # create points\n nelem = 10\n x = range(0, L, length=nelem+1)\n y = zero(x)\n z = zero(x)\n points = [[x[i],y[i],z[i]] for i = 1:length(x)]\n\n # index of endpoints of each beam element\n start = 1:nelem\n stop = 2:nelem+1\n\n # stiffness matrix for each beam element\n stiffness = fill(\n [2.389e9 1.524e6 6.734e6 -3.382e7 -2.627e7 -4.736e8\n 1.524e6 4.334e8 -3.741e6 -2.935e5 1.527e7 3.835e5\n 6.734e6 -3.741e6 2.743e7 -4.592e5 -6.869e5 -4.742e6\n -3.382e7 -2.935e5 -4.592e5 2.167e7 -6.279e5 1.430e6\n -2.627e7 1.527e7 -6.869e5 -6.279e5 1.970e7 1.209e7\n -4.736e8 3.835e5 -4.742e6 1.430e6 1.209e7 4.406e8],\n nelem)\n\n # mass matrix for each beam element\n mass = fill(\n [258.053 0.0 0.0 0.0 7.07839 -71.6871\n 0.0 258.053 0.0 -7.07839 0.0 0.0\n 0.0 0.0 258.053 71.6871 0.0 0.0\n 0.0 -7.07839 71.6871 48.59 0.0 0.0\n 7.07839 0.0 0.0 0.0 2.172 0.0\n -71.6871 0.0 0.0 0.0 0.0 46.418],\n nelem)\n\n # create assembly of interconnected nonlinear beams\n assembly = Assembly(points, start, stop; stiffness=stiffness, mass=mass)\n\n # simulation time\n tvec = 0:0.001:2.0\n\n # prescribed conditions\n prescribed_conditions = (t) -> begin\n Dict(\n # fixed left side\n 1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),\n # force on right side\n nelem+1 => PrescribedConditions(Fz=1e5*sin(20*t))\n )\n end\n\n system, history, converged = time_domain_analysis(assembly, tvec; prescribed_conditions=prescribed_conditions)\n\n @test converged\nend",
"@testset \"Nonlinear Static Analysis of a Joined-Wing\" begin\n\n # Set endpoints of each beam\n p1 = [-7.1726, -12, -3.21539]\n p2 = [-5.37945, -9, -2.41154]\n p3 = [-3.5863, -6, -1.6077]\n p4 = [-1.79315, -3, -0.803848]\n p5 = [0, 0, 0]\n p6 = [7.1726, -12, 3.21539]\n\n # get transformation matrix for left beams\n\n # transformation from intermediate to global frame\n tmp1 = sqrt(p1[1]^2 + p1[2]^2)\n c1, s1 = -p1[1]/tmp1, -p1[2]/tmp1\n rot1 = [c1 -s1 0; s1 c1 0; 0 0 1]\n\n # transformation from local to intermediate frame\n tmp2 = sqrt(p1[1]^2 + p1[2]^2 + p1[3]^2)\n c2, s2 = tmp1/tmp2, -p1[3]/tmp2\n rot2 = [c2 0 -s2; 0 1 0; s2 0 c2]\n\n Cab_1 = rot1*rot2\n\n # get transformation matrix for right beam\n\n # transformation from intermediate frame to global frame\n tmp1 = sqrt(p6[1]^2 + p6[2]^2)\n c1, s1 = p6[1]/tmp1, p6[2]/tmp1\n rot1 = [c1 -s1 0; s1 c1 0; 0 0 1]\n\n # transformation from local beam frame to intermediate frame\n tmp2 = sqrt(p6[1]^2 + p6[2]^2 + p6[3]^2)\n c2, s2 = tmp1/tmp2, p6[3]/tmp2\n rot2 = [c2 0 -s2; 0 1 0; s2 0 c2]\n\n Cab_2 = rot1*rot2\n\n # beam 1\n L_b1 = norm(p2-p1)\n r_b1 = p1\n nelem_b1 = 5\n lengths_b1, xp_b1, xm_b1, Cab_b1 = discretize_beam(L_b1, r_b1, nelem_b1, frame=Cab_1)\n compliance_b1 = fill(Diagonal([1.05204e-9, 3.19659e-9, 2.13106e-8, 1.15475e-7, 1.52885e-7, 7.1672e-9]), nelem_b1)\n\n # beam 2\n L_b2 = norm(p3-p2)\n r_b2 = p2\n nelem_b2 = 5\n lengths_b2, xp_b2, xm_b2, Cab_b2 = discretize_beam(L_b2, r_b2, nelem_b2, frame=Cab_1)\n compliance_b2 = fill(Diagonal([1.24467e-9, 3.77682e-9, 2.51788e-8, 1.90461e-7, 2.55034e-7, 1.18646e-8]), nelem_b2)\n\n # beam 3\n L_b3 = norm(p4-p3)\n r_b3 = p3\n nelem_b3 = 5\n lengths_b3, xp_b3, xm_b3, Cab_b3 = discretize_beam(L_b3, r_b3, nelem_b3, frame=Cab_1)\n compliance_b3 = fill(Diagonal([1.60806e-9, 4.86724e-9, 3.24482e-8, 4.07637e-7, 5.57611e-7, 2.55684e-8]), nelem_b3)\n\n # beam 4\n L_b4 = norm(p5-p4)\n r_b4 = p4\n nelem_b4 = 5\n lengths_b4, xp_b4, xm_b4, Cab_b4 = discretize_beam(L_b4, r_b4, nelem_b4, frame=Cab_1)\n compliance_b4 = fill(Diagonal([2.56482e-9, 7.60456e-9, 5.67609e-8, 1.92171e-6, 2.8757e-6, 1.02718e-7]), nelem_b4)\n\n # beam 5\n L_b5 = norm(p6-p5)\n r_b5 = p5\n nelem_b5 = 20\n lengths_b5, xp_b5, xm_b5, Cab_b5 = discretize_beam(L_b5, r_b5, nelem_b5, frame=Cab_2)\n compliance_b5 = fill(Diagonal([2.77393e-9, 7.60456e-9, 1.52091e-7, 1.27757e-5, 2.7835e-5, 1.26026e-7]), nelem_b5)\n\n # combine elements and points into one array\n nelem = nelem_b1 + nelem_b2 + nelem_b3 + nelem_b4 + nelem_b5\n points = vcat(xp_b1, xp_b2[2:end], xp_b3[2:end], xp_b4[2:end], xp_b5[2:end])\n start = 1:nelem\n stop = 2:nelem + 1\n lengths = vcat(lengths_b1, lengths_b2, lengths_b3, lengths_b4, lengths_b5)\n midpoints = vcat(xm_b1, xm_b2, xm_b3, xm_b4, xm_b5)\n Cab = vcat(Cab_b1, Cab_b2, Cab_b3, Cab_b4, Cab_b5)\n compliance = vcat(compliance_b1, compliance_b2, compliance_b3, compliance_b4, compliance_b5)\n\n # create assembly\n assembly = Assembly(points, start, stop, compliance=compliance,\n frames=Cab, lengths=lengths, midpoints=midpoints)\n\n Fz = range(0, 70e3, length=141)\n\n # pre-allocate memory to reduce run-time\n system = System(assembly, true)\n\n linear_states = Vector{AssemblyState{Float64}}(undef, length(Fz))\n for i = 1:length(Fz)\n\n # create dictionary of prescribed conditions\n prescribed_conditions = Dict(\n # fixed endpoint on beam 1\n 1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),\n # force applied on point 4\n nelem_b1 + nelem_b2 + nelem_b3 + nelem_b4 + 1 => PrescribedConditions(Fz = Fz[i]),\n # fixed endpoint on last beam\n nelem+1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),\n )\n\n _, converged = static_analysis!(system, assembly, prescribed_conditions=prescribed_conditions, linear=true)\n\n linear_states[i] = AssemblyState(system, assembly, prescribed_conditions=prescribed_conditions)\n\n @test converged\n end\n\n reset_state!(system)\n nonlinear_states = Vector{AssemblyState{Float64}}(undef, length(Fz))\n for i = 1:length(Fz)\n\n # create dictionary of prescribed conditions\n prescribed_conditions = Dict(\n # fixed endpoint on beam 1\n 1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),\n # force applied on point 4\n nelem_b1 + nelem_b2 + nelem_b3 + nelem_b4 + 1 => PrescribedConditions(Fz = Fz[i]),\n # fixed endpoint on last beam\n nelem+1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),\n )\n\n _, converged = static_analysis!(system, assembly, prescribed_conditions=prescribed_conditions,\n reset_state = false)\n\n nonlinear_states[i] = AssemblyState(system, assembly;\n prescribed_conditions=prescribed_conditions)\n\n @test converged\n end\n\n reset_state!(system)\n nonlinear_follower_states = Vector{AssemblyState{Float64}}(undef, length(Fz))\n for i = 1:length(Fz)\n # create dictionary of prescribed conditions\n prescribed_conditions = Dict(\n # fixed endpoint on beam 1\n 1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),\n # force applied on point 4\n nelem_b1 + nelem_b2 + nelem_b3 + nelem_b4 + 1 => PrescribedConditions(Fz_follower = Fz[i]),\n # fixed endpoint on last beam\n nelem+1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),\n )\n\n _, converged = static_analysis!(system, assembly, prescribed_conditions=prescribed_conditions,\n reset_state = false)\n\n nonlinear_follower_states[i] = AssemblyState(system, assembly;\n prescribed_conditions=prescribed_conditions)\n\n @test converged\n end\nend",
"@testset \"Nonlinear Dynamic Analysis of a Joined-Wing\" begin\n\n # Set endpoints of each beam\n p1 = [0, 0, 0]\n p2 = [-7.1726, -12, -3.21539]\n p3 = [7.1726, -12, 3.21539]\n\n Cab_1 = [\n 0.5 0.866025 0.0\n 0.836516 -0.482963 0.258819\n 0.224144 -0.12941 -0.965926\n ]\n\n Cab_2 = [\n 0.5 0.866025 0.0\n -0.836516 0.482963 0.258819\n 0.224144 -0.12941 0.965926\n ]\n\n # beam 1\n L_b1 = norm(p1-p2)\n r_b1 = p2\n nelem_b1 = 8\n lengths_b1, xp_b1, xm_b1, Cab_b1 = discretize_beam(L_b1, r_b1, nelem_b1, frame=Cab_1)\n\n # beam 2\n L_b2 = norm(p3-p1)\n r_b2 = p1\n nelem_b2 = 8\n lengths_b2, xp_b2, xm_b2, Cab_b2 = discretize_beam(L_b2, r_b2, nelem_b2, frame=Cab_2)\n\n # combine elements and points into one array\n nelem = nelem_b1 + nelem_b2\n points = vcat(xp_b1, xp_b2[2:end])\n start = 1:nelem\n stop = 2:nelem + 1\n lengths = vcat(lengths_b1, lengths_b2)\n midpoints = vcat(xm_b1, xm_b2)\n Cab = vcat(Cab_b1, Cab_b2)\n\n # assign all beams the same compliance and mass matrix\n compliance = fill(Diagonal([2.93944738387698e-10, 8.42991725049126e-10, 3.38313996669689e-08,\n 4.69246721094557e-08, 6.79584100559513e-08, 1.37068861370898e-09]), nelem)\n mass = fill(Diagonal([4.86e-2, 4.86e-2, 4.86e-2,\n 1.0632465e-2, 2.10195e-4, 1.042227e-2]), nelem)\n\n # create assembly\n assembly = Assembly(points, start, stop; compliance=compliance, mass=mass,\n frames=Cab, lengths=lengths, midpoints=midpoints)\n\n # time\n tvec = range(0, 0.04, length=1001)\n\n F_L = (t) -> begin\n if 0.0 <= t < 0.01\n 1e6*t\n elseif 0.01 <= t < 0.02\n -1e6*(t-0.02)\n else\n zero(t)\n end\n end\n\n F_S = (t) -> begin\n if 0.0 <= t < 0.02\n 5e3*(1-cos(pi*t/0.02))\n else\n 1e4\n end\n end\n\n # assign boundary conditions and point load\n prescribed_conditions = (t) -> begin\n Dict(\n # fixed endpoint on beam 1\n 1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),\n # force applied on point 4\n nelem_b1 + 1 => PrescribedConditions(Fx=F_L(t), Fy=F_L(t), Fz=F_S(t)),\n # fixed endpoint on last beam\n nelem+1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),\n )\n end\n\n system, history, converged = time_domain_analysis(assembly, tvec;\n prescribed_conditions=prescribed_conditions)\n\n @test converged\nend",
"@testset \"DifferentialEquations\" begin\n\n L = 60 # m\n\n # create points\n nelem = 10\n x = range(0, L, length=nelem+1)\n y = zero(x)\n z = zero(x)\n points = [[x[i],y[i],z[i]] for i = 1:length(x)]\n\n # index of endpoints of each beam element\n start = 1:nelem\n stop = 2:nelem+1\n\n # stiffness matrix for each beam element\n stiffness = fill(\n [2.389e9 1.524e6 6.734e6 -3.382e7 -2.627e7 -4.736e8\n 1.524e6 4.334e8 -3.741e6 -2.935e5 1.527e7 3.835e5\n 6.734e6 -3.741e6 2.743e7 -4.592e5 -6.869e5 -4.742e6\n -3.382e7 -2.935e5 -4.592e5 2.167e7 -6.279e5 1.430e6\n -2.627e7 1.527e7 -6.869e5 -6.279e5 1.970e7 1.209e7\n -4.736e8 3.835e5 -4.742e6 1.430e6 1.209e7 4.406e8],\n nelem)\n\n # mass matrix for each beam element\n mass = fill(\n [258.053 0.0 0.0 0.0 7.07839 -71.6871\n 0.0 258.053 0.0 -7.07839 0.0 0.0\n 0.0 0.0 258.053 71.6871 0.0 0.0\n 0.0 -7.07839 71.6871 48.59 0.0 0.0\n 7.07839 0.0 0.0 0.0 2.172 0.0\n -71.6871 0.0 0.0 0.0 0.0 46.418],\n nelem)\n\n # create assembly of interconnected nonlinear beams\n assembly = Assembly(points, start, stop; stiffness=stiffness, mass=mass)\n\n # prescribed conditions\n prescribed_conditions = (t) -> begin\n Dict(\n # fixed left side\n 1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0),\n # force on right side\n nelem+1 => PrescribedConditions(Fz=1e5*sin(20*t))\n )\n end\n\n # define simulation time\n tspan = (0.0, 2.0)\n\n # run initial condition analysis to get consistent set of initial conditions\n system, converged = initial_condition_analysis(assembly, tspan[1]; prescribed_conditions)\n\n # construct ODEProblem\n prob = ODEProblem(system, assembly, tspan; prescribed_conditions)\n\n # solve ODEProblem\n sol = solve(prob, Rodas4())\n\n # test that solution worked\n @test sol.t[end] == 2.0\n\n # construct DAEProblem\n prob = DAEProblem(system, assembly, tspan; prescribed_conditions)\n\n # solve DAEProblem\n sol = solve(prob, DABDF2())\n\n # test that solution worked\n @test sol.t[end] == 2.0\nend",
"@testset \"ForwardDiff\" begin\n\n # Linear Analysis of a Beam Under a Linear Distributed Load\n\n function linear_analysis_test_with_AD(length) # this should affect just about everything\n\n nelem = 16\n\n # create points\n L = length[1]\n x = collect(range(0, L, length=nelem+1))\n y = zero(x)\n z = zero(x)\n\n points = [[x[i],y[i],z[i]] for i = 1:size(x,1)]\n\n # index of endpoints for each beam element\n start = 1:nelem\n stop = 2:nelem+1\n\n # create compliance matrix for each beam element\n EI = 1e7\n compliance = fill(Diagonal([0, 0, 0, 0, 1/EI, 0]), nelem)\n\n # create assembly\n assembly = Assembly(points, start, stop, compliance=compliance)\n\n # set prescribed conditions\n prescribed_conditions = Dict(\n # simply supported left endpoint\n 1 => PrescribedConditions(uz=0),\n # clamped right endpoint\n nelem+1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0)\n )\n\n # create distributed load\n qmax = 1000\n distributed_loads = Dict()\n for i = 1:nelem\n distributed_loads[i] = DistributedLoads(assembly, i; s1=x[i],\n s2=x[i+1], fz = (s) -> qmax*s)\n end\n\n # solve system\n system, converged = static_analysis(assembly, prescribed_conditions=prescribed_conditions,\n distributed_loads=distributed_loads, linear=true)\n\n return system.x\n end\n\n # run FrowardDiff - no specific test, just make sure it runs fine\n J = ForwardDiff.jacobian(linear_analysis_test_with_AD, [1.0]) #length=1\nend",
"@testset \"Zero Mass Matrix\" begin\n sweep = 45 * pi/180\n rpm = 750\n\n # straight section of the beam\n L_b1 = 31.5 # inch\n r_b1 = [2.5, 0, 0]\n nelem_b1 = 13\n lengths_b1, xp_b1, xm_b1, Cab_b1 = discretize_beam(L_b1, r_b1, nelem_b1)\n\n # swept section of the beam\n L_b2 = 6 # inch\n r_b2 = [34, 0, 0]\n nelem_b2 = 3\n cs, ss = cos(sweep), sin(sweep)\n frame_b2 = [cs ss 0; -ss cs 0; 0 0 1]\n lengths_b2, xp_b2, xm_b2, Cab_b2 = discretize_beam(L_b2, r_b2, nelem_b2, frame=frame_b2)\n\n # combine elements and points into one array\n nelem = nelem_b1 + nelem_b2\n points = vcat(xp_b1, xp_b2[2:end])\n start = 1:nelem_b1 + nelem_b2\n stop = 2:nelem_b1 + nelem_b2 + 1\n lengths = vcat(lengths_b1, lengths_b2)\n midpoints = vcat(xm_b1, xm_b2)\n Cab = vcat(Cab_b1, Cab_b2)\n\n # cross section\n w = 1 # inch\n h = 0.063 # inch\n\n # material properties\n E = 1.06e7 # lb/in^2\n ν = 0.325\n ρ = 2.51e-4 # lb sec^2/in^4\n\n # shear and torsion correction factors\n ky = 1.2000001839588001\n kz = 14.625127919304001\n kt = 65.85255016982444\n\n A = h*w\n Iyy = w*h^3/12\n Izz = w^3*h/12\n J = Iyy + Izz\n\n # apply corrections\n Ay = A/ky\n Az = A/kz\n Jx = J/kt\n\n G = E/(2*(1+ν))\n\n compliance = fill(Diagonal([1/(E*A), 1/(G*Ay), 1/(G*Az), 1/(G*Jx), 1/(E*Iyy), 1/(E*Izz)]), nelem)\n\n mass = fill(Diagonal(zeros(6)), nelem)\n\n # create assembly\n assembly = Assembly(points, start, stop, compliance=compliance, mass=mass, frames=Cab, lengths=lengths, midpoints=midpoints)\n\n # create dictionary of prescribed conditions\n prescribed_conditions = Dict(\n # root section is fixed\n 1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0)\n )\n\n # set angular velocity vector\n w0 = [0, 0, rpm*(2*pi)/60]\n\n # perform nonlinear steady state analysis\n system, converged = steady_state_analysis(assembly,\n angular_velocity = w0,\n prescribed_conditions = prescribed_conditions)\n\n # test convergence\n @test converged\nend",
"@testset \"Zero Length Element\" begin\n sweep = 45 * pi/180\n rpm = 750\n\n # straight section of the beam\n L_b1 = 31.5 # inch\n r_b1 = [2.5, 0, 0]\n nelem_b1 = 13\n lengths_b1, xp_b1, xm_b1, Cab_b1 = discretize_beam(L_b1, r_b1, nelem_b1)\n\n # zero length element between straight and swept sections\n L_b12 = 0\n r_b12 = [34, 0, 0]\n nelem_b12 = 1\n lengths_b12, xp_b12, xm_b12, Cab_b12 = discretize_beam(L_b12, r_b12, nelem_b12)\n\n # swept section of the beam\n L_b2 = 6 # inch\n r_b2 = [34, 0, 0]\n nelem_b2 = 3\n cs, ss = cos(sweep), sin(sweep)\n frame_b2 = [cs ss 0; -ss cs 0; 0 0 1]\n lengths_b2, xp_b2, xm_b2, Cab_b2 = discretize_beam(L_b2, r_b2, nelem_b2, frame=frame_b2)\n\n # combine elements and points into one array\n nelem = nelem_b1 + nelem_b12 + nelem_b2\n points = vcat(xp_b1, xp_b2[2:end]) # don't duplicate points\n lengths = vcat(lengths_b1, lengths_b12, lengths_b2)\n midpoints = vcat(xm_b1, xm_b12, xm_b2)\n Cab = vcat(Cab_b1, Cab_b12, Cab_b2)\n\n # specify connectivity\n start = vcat(1:nelem_b1+1, nelem_b1+1:nelem_b1+nelem_b2)\n stop = vcat(2:nelem_b1+1, nelem_b1+1:nelem_b1+nelem_b2+1)\n\n # cross section\n w = 1 # inch\n h = 0.063 # inch\n\n # material properties\n E = 1.06e7 # lb/in^2\n ν = 0.325\n ρ = 2.51e-4 # lb sec^2/in^4\n\n # shear and torsion correction factors\n ky = 1.2000001839588001\n kz = 14.625127919304001\n kt = 65.85255016982444\n\n A = h*w\n Iyy = w*h^3/12\n Izz = w^3*h/12\n J = Iyy + Izz\n\n # apply corrections\n Ay = A/ky\n Az = A/kz\n Jx = J/kt\n\n G = E/(2*(1+ν))\n\n compliance = fill(Diagonal([1/(E*A), 1/(G*Ay), 1/(G*Az), 1/(G*Jx), 1/(E*Iyy), 1/(E*Izz)]), nelem)\n\n mass = fill(Diagonal([ρ*A, ρ*A, ρ*A, ρ*J, ρ*Iyy, ρ*Izz]), nelem)\n\n # create assembly\n assembly = Assembly(points, start, stop, compliance=compliance, mass=mass, frames=Cab, lengths=lengths, midpoints=midpoints)\n\n # create dictionary of prescribed conditions\n prescribed_conditions = Dict(\n # root section is fixed\n 1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0)\n )\n\n # set angular velocity vector\n w0 = [0, 0, rpm*(2*pi)/60]\n\n # perform nonlinear steady state analysis\n system, converged = steady_state_analysis(assembly,\n angular_velocity = w0,\n prescribed_conditions = prescribed_conditions)\n\n # test convergence\n @test converged\nend",
"@testset \"Element Gravitational Loads\" begin\n\n # use arbitrary length\n ΔL = rand()\n\n # use random rotation matrix \n CtCab = GXBeam.get_C(rand(3))\n\n # create random mass matrix\n μ = rand()\n xm2 = rand()\n xm3 = rand()\n i22 = rand()\n i33 = rand()\n i23 = rand()\n\n mass = [\n μ 0 0 0 μ*xm3 -μ*xm2; \n 0 μ 0 -μ*xm3 0 0; \n 0 0 μ μ*xm2 0 0; \n 0 -μ*xm3 μ*xm2 i22+i33 0 0; \n μ*xm3 0 0 0 i22 0; \n -μ*xm2 0 0 0 0 i33\n ]\n\n # use random gravity vector\n gvec = rand(3)\n\n # calculate integrated force and moment per unit length\n f = μ*gvec\n m = cross(CtCab*[0, xm2, xm3], f)\n f1 = f2 = ΔL*f/2\n m1 = m2 = ΔL*m/2\n\n # test against gravitational load function results\n mass11 = ΔL*mass[1:3, 1:3]\n mass12 = ΔL*mass[1:3, 4:6]\n mass21 = ΔL*mass[4:6, 1:3]\n mass22 = ΔL*mass[4:6, 4:6]\n a = -gvec\n α = zero(a)\n f1t, f2t, m1t, m2t = GXBeam.acceleration_loads(mass11, mass12, mass21, mass22, CtCab, a, α)\n\n @test isapprox(f1, f1t)\n @test isapprox(f2, f2t)\n @test isapprox(m1, m1t)\n @test isapprox(m2, m2t)\n\nend",
"@testset \"Point Masses\" begin\n\n nodes = [[0,i,0] for i in 0:.1:1]\n nelem = length(nodes)-1\n start = 1:nelem\n stop = 2:(nelem+1)\n\n frames = fill(wiener_milenkovic(rand(3)), nelem)\n compliance = fill(Symmetric(rand(6,6)), nelem)\n mass = fill(Symmetric(rand(6,6)), nelem)\n \n prescribed_conditions = Dict(1 => PrescribedConditions(ux=0, uy=0, uz=0, theta_x=0, theta_y=0, theta_z=0));\n\n # assembly of mass-containing beam elements\n\n assembly = GXBeam.Assembly(nodes, start, stop;\n compliance=compliance, \n frames=frames, \n mass=mass);\n \n system, λ, V, converged = GXBeam.eigenvalue_analysis(assembly;\n prescribed_conditions = prescribed_conditions, \n nev = 14);\n\n imagλ = imag(λ)\n isort = sortperm(abs.(imagλ))\n freq = imagλ[isort[1:2:10]]/(2*pi)\n\n # assembly of massless beam elements with point masses\n \n assembly = GXBeam.Assembly(nodes, start, stop;\n compliance=compliance, \n frames=frames);\n \n point_masses = Dict{Int, PointMass{Float64}}()\n for i = 1:nelem\n T = [frames[i] zeros(3,3); zeros(3,3) frames[i]]\n point_masses[i] = PointMass(T * mass[i] * T' .* assembly.elements[i].L)\n end\n\n system, λ, V, converged = GXBeam.eigenvalue_analysis(assembly; \n prescribed_conditions = prescribed_conditions, \n point_masses = point_masses,\n nev = 14);\n \n imagλ = imag(λ)\n isort = sortperm(abs.(imagλ))\n pfreq = imagλ[isort[1:2:10]]/(2*pi)\n\n # test the two equivalent systems\n @test isapprox(freq, pfreq)\n\nend"
] |
f77aa451320125b4e96e109583a22fd866ac7168
| 798
|
jl
|
Julia
|
test/multithreaded.jl
|
ThomasRetornaz/ImageMorphology.jl
|
3181b69eab153fec9eeb0eaa55e97000252fa895
|
[
"MIT"
] | null | null | null |
test/multithreaded.jl
|
ThomasRetornaz/ImageMorphology.jl
|
3181b69eab153fec9eeb0eaa55e97000252fa895
|
[
"MIT"
] | null | null | null |
test/multithreaded.jl
|
ThomasRetornaz/ImageMorphology.jl
|
3181b69eab153fec9eeb0eaa55e97000252fa895
|
[
"MIT"
] | null | null | null |
# This doesn't run under "runtests.jl" but does under CI
using ImageMorphology
using Test
@testset "multithreaded" begin
@test Threads.nthreads() > 1
@testset "feature_transform" begin
img = rand(100, 128) .> 0.9
@test feature_transform(img; nthreads=Threads.nthreads()) ==
feature_transform(img; nthreads=1)
# Since the threaded implementation handles two dimensions specially, we should check 0d and 1d
img = reshape([true])
@test feature_transform(img; nthreads=Threads.nthreads()) ==
feature_transform(img; nthreads=1) ==
reshape([CartesianIndex()])
img = rand(100) .> 0.9
@test feature_transform(img; nthreads=Threads.nthreads()) ==
feature_transform(img; nthreads=1)
end
end
| 38
| 103
| 0.651629
|
[
"@testset \"multithreaded\" begin\n @test Threads.nthreads() > 1\n @testset \"feature_transform\" begin\n img = rand(100, 128) .> 0.9\n @test feature_transform(img; nthreads=Threads.nthreads()) ==\n feature_transform(img; nthreads=1)\n # Since the threaded implementation handles two dimensions specially, we should check 0d and 1d\n img = reshape([true])\n @test feature_transform(img; nthreads=Threads.nthreads()) ==\n feature_transform(img; nthreads=1) ==\n reshape([CartesianIndex()])\n img = rand(100) .> 0.9\n @test feature_transform(img; nthreads=Threads.nthreads()) ==\n feature_transform(img; nthreads=1)\n end\nend"
] |
f77ab07997532ed4da6cc0a744ee2f8ae77132ff
| 200
|
jl
|
Julia
|
test/runtests.jl
|
giandopal/MyExample
|
1cf4af029843abb069114e2bd3001564d7125811
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
giandopal/MyExample
|
1cf4af029843abb069114e2bd3001564d7125811
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
giandopal/MyExample
|
1cf4af029843abb069114e2bd3001564d7125811
|
[
"MIT"
] | null | null | null |
using MyExample
using Test
my_f(2,1)
MyExample.greet2()
MyExample.my_f2(1,1)
@testset "MyExample.jl" begin
@test MyExample.my_f(2,1)==5
@test MyExample.my_f(2,3)==7
@test my_f(2,3)=9
end
| 16.666667
| 32
| 0.685
|
[
"@testset \"MyExample.jl\" begin\n @test MyExample.my_f(2,1)==5\n @test MyExample.my_f(2,3)==7\n @test my_f(2,3)=9\nend"
] |
f77b1550f23602d89921d2589260ed7e29ff3059
| 1,554
|
jl
|
Julia
|
test/data.jl
|
EvilDonkey420/OpenML.jl
|
1a11b2a4aa761ff029e721e45d748c6282b750d6
|
[
"MIT"
] | 1
|
2021-09-24T14:21:05.000Z
|
2021-09-24T14:21:05.000Z
|
test/data.jl
|
EvilDonkey420/OpenML.jl
|
1a11b2a4aa761ff029e721e45d748c6282b750d6
|
[
"MIT"
] | null | null | null |
test/data.jl
|
EvilDonkey420/OpenML.jl
|
1a11b2a4aa761ff029e721e45d748c6282b750d6
|
[
"MIT"
] | null | null | null |
module TestOpenml
using Test
using HTTP
using OpenML
import Tables.istable
response_test = OpenML.load_Dataset_Description(61)
ntp_test = OpenML.load(61)
@test istable(ntp_test)
dqlist_test = OpenML.load_Data_Qualities_List()
data_features_test = OpenML.load_Data_Features(61)
data_qualities_test = OpenML.load_Data_Qualities(61)
limit = 5
offset = 8
filters_test = OpenML.load_List_And_Filter("limit/$limit/offset/$offset")
@testset "HTTP connection" begin
@test typeof(response_test) <: Dict
@test response_test["data_set_description"]["name"] == "iris"
@test response_test["data_set_description"]["format"] == "ARFF"
end
@testset "ARFF file conversion to NamedTuples" begin
@test isempty(ntp_test) == false
@test length(ntp_test[1]) == 150
@test length(ntp_test) == 5
end
@testset "data api functions" begin
@test typeof(dqlist_test["data_qualities_list"]) <: Dict
@test typeof(data_features_test) <: Dict
@test length(data_features_test["data_features"]["feature"]) == 5
@test data_features_test["data_features"]["feature"][1]["name"] == "sepallength"
@test typeof(data_qualities_test) <: Dict
@test length(filters_test["data"]["dataset"]) == limit
@test length(filters_test["data"]["dataset"][1]) == offset
end
if VERSION > v"1.3.0"
using Pkg.Artifacts
@testset "artifacts" begin
dir = first(Artifacts.artifacts_dirs())
toml = joinpath(dir, "OpenMLArtifacts.toml")
hash = artifact_hash("61", toml)
@test artifact_exists(hash)
end
end
end
true
| 28.254545
| 84
| 0.714929
|
[
"@testset \"HTTP connection\" begin\n @test typeof(response_test) <: Dict\n @test response_test[\"data_set_description\"][\"name\"] == \"iris\"\n @test response_test[\"data_set_description\"][\"format\"] == \"ARFF\"\nend",
"@testset \"ARFF file conversion to NamedTuples\" begin\n @test isempty(ntp_test) == false\n @test length(ntp_test[1]) == 150\n @test length(ntp_test) == 5\nend",
"@testset \"data api functions\" begin\n @test typeof(dqlist_test[\"data_qualities_list\"]) <: Dict\n\n @test typeof(data_features_test) <: Dict\n @test length(data_features_test[\"data_features\"][\"feature\"]) == 5\n @test data_features_test[\"data_features\"][\"feature\"][1][\"name\"] == \"sepallength\"\n\n @test typeof(data_qualities_test) <: Dict\n\n @test length(filters_test[\"data\"][\"dataset\"]) == limit\n @test length(filters_test[\"data\"][\"dataset\"][1]) == offset\nend",
"@testset \"artifacts\" begin\n dir = first(Artifacts.artifacts_dirs())\n toml = joinpath(dir, \"OpenMLArtifacts.toml\")\n hash = artifact_hash(\"61\", toml)\n @test artifact_exists(hash)\n end"
] |
f780005034669c2e2b793ced2dbf0c3570ec0184
| 8,418
|
jl
|
Julia
|
test/test_bracketing.jl
|
alecloudenback/Roots.jl
|
299e5ead40ad16d112d461ab2a736ccc44eeafd0
|
[
"MIT"
] | null | null | null |
test/test_bracketing.jl
|
alecloudenback/Roots.jl
|
299e5ead40ad16d112d461ab2a736ccc44eeafd0
|
[
"MIT"
] | null | null | null |
test/test_bracketing.jl
|
alecloudenback/Roots.jl
|
299e5ead40ad16d112d461ab2a736ccc44eeafd0
|
[
"MIT"
] | null | null | null |
using Roots
using Test
using Printf
## testing bracketing methods
## Orignially by John Travers
#
#
## This set of tests is very useful for benchmarking the number of function
## calls, failures, and max errors for the various bracketing methods.
## Table 1 from TOMS748 by Alefeld, Potra, Shi
mutable struct Func
name :: Symbol
val :: Function
bracket :: Function
params :: Vector{Any}
end
function show(io::IO, f::Func)
@printf io "Func(%s)" f.name
end
## Construct a function object, and check root brackets
macro Func(name)
@gensym f p b
esc(quote
$f = Func($name, val, bracket, params)
for $p in params
$b = bracket($p)
@assert val($p, $b[1]) * $f.val($p, $b[2]) < 0 "Invalid bracket"
end
push!(known_functions, $f)
$f
end)
end
known_functions = Func[]
## This set of tests is very useful for benchmarking the number of function
## calls, failures, and max errors for the various bracketing methods.
## Table 1 from TOMS748 by Alefeld, Potra, Shi
func1 = let
val = (_, x) -> sin(x) - x/2
bracket(_) = [0.5pi, pi]
params = [()]
@Func :func1
end
func2 = let
val = (n, x) -> -2*sum([(2i-5)^2/(x-i*i)^3 for i=1:20])
bracket(n) = [n^2+1e-9, (n+1)^2-1e-9]
params = 1:10
@Func :func2
end
func3 = let
val = (p, x) -> p[1]*x*exp(p[2]*x)
bracket(p) = [-9., 31.]
params = [(-40.,-1.), (-100., -2.), (-200., -3.)]
@Func :func3
end
func4 = let
val = (p, x) -> x^p[2] - p[1]
bracket(p) = p[3]
params = Tuple{Float64, Float64, Vector{Float64}}[]
for a_ in [0.2, 1.], n in 4:2:12
push!(params, (a_, n, [0., 5.]))
end
for n in 8:2:14
push!(params, (1., n, [-0.95, 4.05]))
end
@Func :func4
end
func5 = let
val = (p, x) -> sin(x) - 0.5
bracket(p) = [0., 1.5]
params = [()]
@Func :func5
end
func6 = let
val = (n, x) -> 2x*exp(-n)-2exp(-n*x)+1.
bracket(n) = [0., 1.]
params = vcat(1:5, 20:20:100)
@Func :func6
end
func7 = let
val = (n, x) -> (1+(1-n)^2)*x-(1-n*x)^2
bracket(n)= [0., 1.]
params = [5., 10., 20.]
@Func :func7
end
func8 = let
val = (n, x) -> x^2-(1-x)^n
bracket(n) = [0., 1.]
params = [2., 5., 10., 15., 20.]
@Func :func8
end
func9 = let
val = (n, x) -> (1+(1-n)^4)*x-(1-n*x)^4
bracket(n) = [0., 1.]
params = [1., 2., 4., 5., 8., 15., 20.]
@Func :func9
end
func10 = let
val = (n, x) -> exp(-n*x)*(x-1) + x^n
bracket(n) = [0., 1.]
params = [1, 5, 10, 15, 20]
@Func :func10
end
func11 = let
val = (n, x) -> (n*x-1)/((n-1)*x)
bracket(n) = [0.01, 1.]
params = [2, 5, 15, 20]
@Func :func11
end
func12 = let
val = (n, x) -> x^(1/n)-n^(1/n)
bracket(n) = [1., 100.]
params = vcat(2:6, 7:2:33)
@Func :func12
end
func13 = let
val = (n, x) -> x == 0. ? 0. : x/exp(1/(x*x))
bracket(n) = [-1., 4.]
params = [()]
@Func :func13
end
func14 = let
val = (n, x) -> x >= 0 ? n/20*(x/1.5+sin(x)-1) : -n/20
bracket(n) = [-1e4, 0.5pi]
params = 1:40
@Func :func14
end
func15 = let
val = (n, x) -> begin
if x > 2e-3/(1+n)
exp(1) - 1.859
elseif x < 0
-0.859
else
exp(0.5e3(n+1)x)-1.859
end
end
bracket(n) = [-1e4, 1e-4]
params = vcat(20:40, 100:100:1000)
@Func :func15
end
mutable struct MethodResults
name
evalcount :: Int
maxresidual :: Float64
failures :: Vector{Tuple{Func, Int}}
end
MethodResults() = MethodResults(nothing, 0, 0., Tuple{Func, Int}[])
show(io::IO, results::MethodResults) =
print(io, "MethodResults($(results.name), evalcount=$(results.evalcount), numfailures=$(length(results.failures)), maxresidual=$(results.maxresidual))")
## Run a method on all known functions.
function run_tests(method; verbose=false, trace=false, name=nothing, abandon=false)
results = MethodResults()
results.name = name
for f in known_functions
for i in 1:length(f.params)
p = f.params[i]
evalcount = 0
function feval(x)
evalcount += 1
result = f.val(p, x)
trace && @printf "%s[%d]: %s ⇒ %s\n" f i x result
result
end
result, residual = nothing, nothing
try
result = method(feval, f.bracket(p))
isnan(result) && error("NaN")
residual = f.val(p, result)
verbose && @printf "%s[%d] ⇒ %d / %s, residual %.5e\n" f i evalcount result residual
catch ex
verbose && @printf "%s[%d] ⇒ FAILED: %s\n" f i ex
push!(results.failures, (f, i))
abandon && rethrow(ex)
end
results.evalcount += evalcount
## Some functions might return non-real values on failures
if isa(result, AbstractFloat) && isa(residual, AbstractFloat) && isfinite(residual)
results.maxresidual = max(results.maxresidual, abs(residual))
end
end
end
results
end
avg(x) = sum(x)/length(x)
@testset "bracketing methods" begin
## Test for failures, ideally all of these would be 0
## test for residual, ideally small
## test for evaluation counts, ideally not so low for these problems
## exact_bracket
Ms = [Roots.A42(), Roots.AlefeldPotraShi(), Roots.Bisection()]
results = [run_tests((f,b) -> find_zero(f, b, M), name="$M") for M in Ms]
maxfailures = maximum([length(result.failures) for result in results])
maxresidual = maximum([result.maxresidual for result in results])
cnts = [result.evalcount for result in results]
@test maxfailures == 0
@test maxresidual <= 5e-15
@test avg(cnts) <= 4700
## brent has some failures
Ms = [Roots.Brent()]
results = [run_tests((f,b) -> find_zero(f, b, M), name="$M") for M in Ms]
maxfailures = maximum([length(result.failures) for result in results])
maxresidual = maximum([result.maxresidual for result in results])
cnts = [result.evalcount for result in results]
@test maxfailures <= 4
@test maxresidual <= 1e-13
@test avg(cnts) <= 2600
## False position has failures, and larger residuals
Ms = [Roots.FalsePosition(i) for i in 1:12]
results = [run_tests((f,b) -> find_zero(f, b, M), name="$M") for M in Ms]
maxfailures = maximum([length(result.failures) for result in results])
maxresidual = maximum([result.maxresidual for result in results])
cnts = [result.evalcount for result in results]
@test maxfailures <= 10
@test maxresidual <= 1e-5
@test avg(cnts) <= 2500
end
mutable struct Cnt
cnt::Int
f
Cnt(f) = new(0, f)
end
(f::Cnt)(x) = (f.cnt += 1; f.f(x))
## Some tests for FalsePosition methods
@testset "FalsePosition" begin
galadino_probs = [(x -> x^3 - 1, [.5, 1.5]),
(x -> x^2 * (x^2/3 + sqrt(2) * sin(x)) - sqrt(3)/18, [.1, 1]),
(x -> 11x^11 - 1, [0.1, 1]),
(x -> x^3 + 1, [-1.8, 0]),
(x -> x^3 - 2x - 5, [2.0, 3]),
((x,n=5) -> 2x * exp(-n) + 1 - 2exp(-n*x) , [0,1]),
((x,n=10) -> 2x * exp(-n) + 1 - 2exp(-n*x) , [0,1]),
((x,n=20) -> 2x * exp(-n) + 1 - 2exp(-n*x) , [0,1]),
((x,n=5) -> (1 + (1-n)^2) * x^2 - (1 - n*x)^2 , [0,1]),
((x,n=10) -> (1 + (1-n)^2) * x^2 - (1 - n*x)^2 , [0,1]),
((x,n=20) -> (1 + (1-n)^2) * x^2 - (1 - n*x)^2 , [0,1]),
((x,n=5) -> x^2 - (1-x)^n , [0,1]),
((x,n=10) -> x^2 - (1-x)^n , [0,1]),
((x,n=20) -> x^2 - (1-x)^n , [0,1]),
((x,n=5) -> (1 + (1-n)^4)*x - (1 - n*x)^4 , [0,1]),
((x,n=10) -> (1 + (1-n)^4)*x - (1 - n*x)^4 , [0,1]),
((x,n=20) -> (1 + (1-n)^4)*x - (1 - n*x)^4 , [0,1]),
((x,n=5) -> exp(-n*x)*(x-1) + x^n , [0,1]),
((x,n=10) -> exp(-n*x)*(x-1) + x^n , [0,1]),
((x,n=20) -> exp(-n*x)*(x-1) + x^n , [0,1]),
((x,n=5) -> x^2 + sin(x/n) - 1/4 , [0,1]),
((x,n=10) -> x^2 + sin(x/n) - 1/4 , [0,1]),
((x,n=20) -> x^2 + sin(x/n) - 1/4 , [0,1])
]
for (fn_, ab) in galadino_probs
for M in (FalsePosition(i) for i in 1:12)
g = Cnt(fn_)
x0_ = find_zero(g, ab, M)
@test abs(fn_(x0_)) <= 1e-7
@test g.cnt <= 50
end
end
end
| 27.509804
| 156
| 0.509979
|
[
"@testset \"bracketing methods\" begin\n\n ## Test for failures, ideally all of these would be 0\n ## test for residual, ideally small\n ## test for evaluation counts, ideally not so low for these problems\n\n\n ## exact_bracket\n Ms = [Roots.A42(), Roots.AlefeldPotraShi(), Roots.Bisection()]\n results = [run_tests((f,b) -> find_zero(f, b, M), name=\"$M\") for M in Ms]\n maxfailures = maximum([length(result.failures) for result in results])\n maxresidual = maximum([result.maxresidual for result in results])\n cnts = [result.evalcount for result in results]\n @test maxfailures == 0\n @test maxresidual <= 5e-15\n @test avg(cnts) <= 4700\n\n ## brent has some failures\n Ms = [Roots.Brent()]\n results = [run_tests((f,b) -> find_zero(f, b, M), name=\"$M\") for M in Ms]\n\n maxfailures = maximum([length(result.failures) for result in results])\n maxresidual = maximum([result.maxresidual for result in results])\n cnts = [result.evalcount for result in results]\n @test maxfailures <= 4\n @test maxresidual <= 1e-13\n @test avg(cnts) <= 2600\n\n ## False position has failures, and larger residuals\n Ms = [Roots.FalsePosition(i) for i in 1:12]\n results = [run_tests((f,b) -> find_zero(f, b, M), name=\"$M\") for M in Ms]\n maxfailures = maximum([length(result.failures) for result in results])\n maxresidual = maximum([result.maxresidual for result in results])\n cnts = [result.evalcount for result in results]\n @test maxfailures <= 10\n @test maxresidual <= 1e-5\n @test avg(cnts) <= 2500\n\n\n\n\nend",
"@testset \"FalsePosition\" begin\n galadino_probs = [(x -> x^3 - 1, [.5, 1.5]),\n (x -> x^2 * (x^2/3 + sqrt(2) * sin(x)) - sqrt(3)/18, [.1, 1]),\n (x -> 11x^11 - 1, [0.1, 1]),\n (x -> x^3 + 1, [-1.8, 0]),\n (x -> x^3 - 2x - 5, [2.0, 3]),\n\n ((x,n=5) -> 2x * exp(-n) + 1 - 2exp(-n*x) , [0,1]),\n ((x,n=10) -> 2x * exp(-n) + 1 - 2exp(-n*x) , [0,1]),\n ((x,n=20) -> 2x * exp(-n) + 1 - 2exp(-n*x) , [0,1]),\n\n ((x,n=5) -> (1 + (1-n)^2) * x^2 - (1 - n*x)^2 , [0,1]),\n ((x,n=10) -> (1 + (1-n)^2) * x^2 - (1 - n*x)^2 , [0,1]),\n ((x,n=20) -> (1 + (1-n)^2) * x^2 - (1 - n*x)^2 , [0,1]),\n\n ((x,n=5) -> x^2 - (1-x)^n , [0,1]),\n ((x,n=10) -> x^2 - (1-x)^n , [0,1]),\n ((x,n=20) -> x^2 - (1-x)^n , [0,1]),\n\n ((x,n=5) -> (1 + (1-n)^4)*x - (1 - n*x)^4 , [0,1]),\n ((x,n=10) -> (1 + (1-n)^4)*x - (1 - n*x)^4 , [0,1]),\n ((x,n=20) -> (1 + (1-n)^4)*x - (1 - n*x)^4 , [0,1]),\n\n ((x,n=5) -> exp(-n*x)*(x-1) + x^n , [0,1]),\n ((x,n=10) -> exp(-n*x)*(x-1) + x^n , [0,1]),\n ((x,n=20) -> exp(-n*x)*(x-1) + x^n , [0,1]),\n\n ((x,n=5) -> x^2 + sin(x/n) - 1/4 , [0,1]),\n ((x,n=10) -> x^2 + sin(x/n) - 1/4 , [0,1]),\n ((x,n=20) -> x^2 + sin(x/n) - 1/4 , [0,1])\n ]\n\n\n for (fn_, ab) in galadino_probs\n for M in (FalsePosition(i) for i in 1:12)\n g = Cnt(fn_)\n x0_ = find_zero(g, ab, M)\n @test abs(fn_(x0_)) <= 1e-7\n @test g.cnt <= 50\n end\n end\n\nend"
] |
f7814ef0e18bf636d2636df0a4aba72493a4483b
| 732
|
jl
|
Julia
|
test/codegen/julia/node.jl
|
xgdgsc/Comonicon.jl
|
8c8a46549bf7d88c0e4b3ea1cc02bdf5e0baa7cc
|
[
"MIT"
] | 52
|
2021-06-01T10:00:10.000Z
|
2022-03-13T07:15:42.000Z
|
test/codegen/julia/node.jl
|
Leticia-maria/Comonicon.jl
|
a7c38f9378f32a70396c5aaa5607b46391c921a4
|
[
"MIT"
] | 51
|
2021-05-24T19:35:35.000Z
|
2022-03-17T07:51:58.000Z
|
test/codegen/julia/node.jl
|
Leticia-maria/Comonicon.jl
|
a7c38f9378f32a70396c5aaa5607b46391c921a4
|
[
"MIT"
] | 7
|
2021-06-04T21:28:27.000Z
|
2022-02-21T03:26:01.000Z
|
module TestNodeCommand
using Comonicon.AST
using Comonicon.JuliaExpr
using Comonicon.JuliaExpr: emit, emit_body, emit_norm_body, emit_dash_body
using Test
function called()
@test true
end
cmd = Entry(;
version = v"1.2.0",
root = NodeCommand(;
name = "node",
subcmds = Dict(
"cmd1" => LeafCommand(; fn = called, name = "cmd1"),
"cmd2" => LeafCommand(; fn = called, name = "cmd2"),
),
),
)
eval(emit(cmd))
@testset "test node" begin
@test command_main(["cmd3"]) == 1
@test command_main(["cmd1", "foo"]) == 1
@test command_main(["cmd1", "foo", "-h"]) == 0
@test command_main(["cmd1", "foo", "-V"]) == 0
@test command_main(String[]) == 1
end
end
| 21.529412
| 74
| 0.586066
|
[
"@testset \"test node\" begin\n @test command_main([\"cmd3\"]) == 1\n @test command_main([\"cmd1\", \"foo\"]) == 1\n @test command_main([\"cmd1\", \"foo\", \"-h\"]) == 0\n @test command_main([\"cmd1\", \"foo\", \"-V\"]) == 0\n @test command_main(String[]) == 1\nend"
] |
f78279cfc365ded66a2110e44246f23fdc8f5253
| 48,698
|
jl
|
Julia
|
stdlib/LinearAlgebra/test/dense.jl
|
GiggleLiu/julia
|
6e894ccd56274b62b169d949b67ea150a12090bb
|
[
"Zlib"
] | null | null | null |
stdlib/LinearAlgebra/test/dense.jl
|
GiggleLiu/julia
|
6e894ccd56274b62b169d949b67ea150a12090bb
|
[
"Zlib"
] | null | null | null |
stdlib/LinearAlgebra/test/dense.jl
|
GiggleLiu/julia
|
6e894ccd56274b62b169d949b67ea150a12090bb
|
[
"Zlib"
] | null | null | null |
# This file is a part of Julia. License is MIT: https://julialang.org/license
module TestDense
using Test, LinearAlgebra, Random
using LinearAlgebra: BlasComplex, BlasFloat, BlasReal
@testset "Check that non-floats are correctly promoted" begin
@test [1 0 0; 0 1 0]\[1,1] ≈ [1;1;0]
end
n = 10
# Split n into 2 parts for tests needing two matrices
n1 = div(n, 2)
n2 = 2*n1
Random.seed!(1234321)
@testset "Matrix condition number" begin
ainit = rand(n,n)
@testset "for $elty" for elty in (Float32, Float64, ComplexF32, ComplexF64)
ainit = convert(Matrix{elty}, ainit)
for a in (copy(ainit), view(ainit, 1:n, 1:n))
@test cond(a,1) ≈ 4.837320054554436e+02 atol=0.01
@test cond(a,2) ≈ 1.960057871514615e+02 atol=0.01
@test cond(a,Inf) ≈ 3.757017682707787e+02 atol=0.01
@test cond(a[:,1:5]) ≈ 10.233059337453463 atol=0.01
@test_throws ArgumentError cond(a,3)
end
end
@testset "Singular matrices" for p in (1, 2, Inf)
@test cond(zeros(Int, 2, 2), p) == Inf
@test cond(zeros(2, 2), p) == Inf
@test cond([0 0; 1 1], p) == Inf
@test cond([0. 0.; 1. 1.], p) == Inf
end
@testset "Issue #33547, condition number of 2x2 matrix" begin
M = [1.0 -2.0; -2.0 -1.5]
@test cond(M, 1) ≈ 2.227272727272727
end
end
areal = randn(n,n)/2
aimg = randn(n,n)/2
a2real = randn(n,n)/2
a2img = randn(n,n)/2
breal = randn(n,2)/2
bimg = randn(n,2)/2
@testset "For A containing $eltya" for eltya in (Float32, Float64, ComplexF32, ComplexF64, Int)
ainit = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(areal, aimg) : areal)
ainit2 = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(a2real, a2img) : a2real)
ε = εa = eps(abs(float(one(eltya))))
apd = ainit'*ainit # symmetric positive-definite
@testset "Positive definiteness" begin
@test !isposdef(ainit)
@test isposdef(apd)
if eltya != Int # cannot perform cholesky! for Matrix{Int}
@test !isposdef!(copy(ainit))
@test isposdef!(copy(apd))
end
end
@testset "For b containing $eltyb" for eltyb in (Float32, Float64, ComplexF32, ComplexF64, Int)
binit = eltyb == Int ? rand(1:5, n, 2) : convert(Matrix{eltyb}, eltyb <: Complex ? complex.(breal, bimg) : breal)
εb = eps(abs(float(one(eltyb))))
ε = max(εa,εb)
for (a, b) in ((copy(ainit), copy(binit)), (view(ainit, 1:n, 1:n), view(binit, 1:n, 1:2)))
@testset "Solve square general system of equations" begin
κ = cond(a,1)
x = a \ b
@test_throws DimensionMismatch b'\b
@test_throws DimensionMismatch b\b'
@test norm(a*x - b, 1)/norm(b) < ε*κ*n*2 # Ad hoc, revisit!
@test zeros(eltya,n)\fill(eltya(1),n) ≈ (zeros(eltya,n,1)\fill(eltya(1),n,1))[1,1]
end
@testset "Test nullspace" begin
a15null = nullspace(a[:,1:n1]')
@test rank([a[:,1:n1] a15null]) == 10
@test norm(a[:,1:n1]'a15null,Inf) ≈ zero(eltya) atol=300ε
@test norm(a15null'a[:,1:n1],Inf) ≈ zero(eltya) atol=400ε
@test size(nullspace(b), 2) == 0
@test size(nullspace(b, rtol=0.001), 2) == 0
@test size(nullspace(b, atol=100*εb), 2) == 0
@test size(nullspace(b, 100*εb), 2) == 0
@test nullspace(zeros(eltya,n)) == Matrix(I, 1, 1)
@test nullspace(zeros(eltya,n), 0.1) == Matrix(I, 1, 1)
# test empty cases
@test @inferred(nullspace(zeros(n, 0))) == Matrix(I, 0, 0)
@test @inferred(nullspace(zeros(0, n))) == Matrix(I, n, n)
# test vector cases
@test size(@inferred nullspace(a[:, 1])) == (1, 0)
@test size(@inferred nullspace(zero(a[:, 1]))) == (1, 1)
@test nullspace(zero(a[:, 1]))[1,1] == 1
# test adjortrans vectors, including empty ones
@test size(@inferred nullspace(a[:, 1]')) == (n, n - 1)
@test @inferred(nullspace(a[1:0, 1]')) == Matrix(I, 0, 0)
@test size(@inferred nullspace(b[1, :]')) == (2, 1)
@test @inferred(nullspace(b[1, 1:0]')) == Matrix(I, 0, 0)
@test size(@inferred nullspace(transpose(a[:, 1]))) == (n, n - 1)
@test size(@inferred nullspace(transpose(b[1, :]))) == (2, 1)
end
end
end # for eltyb
@testset "Test diagm for vectors" begin
@test diagm(zeros(50)) == diagm(0 => zeros(50))
@test diagm(ones(50)) == diagm(0 => ones(50))
v = randn(500)
@test diagm(v) == diagm(0 => v)
@test diagm(500, 501, v) == diagm(500, 501, 0 => v)
end
@testset "Non-square diagm" begin
x = [7, 8]
for m=1:4, n=2:4
if m < 2 || n < 3
@test_throws DimensionMismatch diagm(m,n, 0 => x, 1 => x)
@test_throws DimensionMismatch diagm(n,m, 0 => x, -1 => x)
else
M = zeros(m,n)
M[1:2,1:3] = [7 7 0; 0 8 8]
@test diagm(m,n, 0 => x, 1 => x) == M
@test diagm(n,m, 0 => x, -1 => x) == M'
end
end
end
@testset "Test pinv (rtol, atol)" begin
M = [1 0 0; 0 1 0; 0 0 0]
@test pinv(M,atol=1)== zeros(3,3)
@test pinv(M,rtol=0.5)== M
end
for (a, a2) in ((copy(ainit), copy(ainit2)), (view(ainit, 1:n, 1:n), view(ainit2, 1:n, 1:n)))
@testset "Test pinv" begin
pinva15 = pinv(a[:,1:n1])
@test a[:,1:n1]*pinva15*a[:,1:n1] ≈ a[:,1:n1]
@test pinva15*a[:,1:n1]*pinva15 ≈ pinva15
pinva15 = pinv(a[:,1:n1]') # the Adjoint case
@test a[:,1:n1]'*pinva15*a[:,1:n1]' ≈ a[:,1:n1]'
@test pinva15*a[:,1:n1]'*pinva15 ≈ pinva15
@test size(pinv(Matrix{eltya}(undef,0,0))) == (0,0)
end
@testset "Lyapunov/Sylvester" begin
x = lyap(a, a2)
@test -a2 ≈ a*x + x*a'
x2 = sylvester(a[1:3, 1:3], a[4:n, 4:n], a2[1:3,4:n])
@test -a2[1:3, 4:n] ≈ a[1:3, 1:3]*x2 + x2*a[4:n, 4:n]
end
@testset "Matrix square root" begin
asq = sqrt(a)
@test asq*asq ≈ a
@test sqrt(transpose(a))*sqrt(transpose(a)) ≈ transpose(a)
@test sqrt(adjoint(a))*sqrt(adjoint(a)) ≈ adjoint(a)
asym = a + a' # symmetric indefinite
asymsq = sqrt(asym)
@test asymsq*asymsq ≈ asym
@test sqrt(transpose(asym))*sqrt(transpose(asym)) ≈ transpose(asym)
@test sqrt(adjoint(asym))*sqrt(adjoint(asym)) ≈ adjoint(asym)
if eltype(a) <: Real # real square root
apos = a * a
@test sqrt(apos)^2 ≈ apos
@test eltype(sqrt(apos)) <: Real
# test that real but Complex input produces Complex output
@test sqrt(complex(apos)) ≈ sqrt(apos)
@test eltype(sqrt(complex(apos))) <: Complex
end
end
@testset "Powers" begin
if eltya <: AbstractFloat
z = zero(eltya)
t = convert(eltya,2)
r = convert(eltya,2.5)
@test a^z ≈ Matrix(I, size(a))
@test a^t ≈ a^2
@test Matrix{eltya}(I, n, n)^r ≈ Matrix(I, size(a))
end
end
end # end for loop over arraytype
@testset "Factorize" begin
d = rand(eltya,n)
e = rand(eltya,n-1)
e2 = rand(eltya,n-1)
f = rand(eltya,n-2)
A = diagm(0 => d)
@test factorize(A) == Diagonal(d)
A += diagm(-1 => e)
@test factorize(A) == Bidiagonal(d,e,:L)
A += diagm(-2 => f)
@test factorize(A) == LowerTriangular(A)
A = diagm(0 => d, 1 => e)
@test factorize(A) == Bidiagonal(d,e,:U)
if eltya <: Real
A = diagm(0 => d, 1 => e, -1 => e)
@test Matrix(factorize(A)) ≈ Matrix(factorize(SymTridiagonal(d,e)))
A = diagm(0 => d, 1 => e, -1 => e, 2 => f, -2 => f)
@test inv(factorize(A)) ≈ inv(factorize(Symmetric(A)))
end
A = diagm(0 => d, 1 => e, -1 => e2)
@test Matrix(factorize(A)) ≈ Matrix(factorize(Tridiagonal(e2,d,e)))
A = diagm(0 => d, 1 => e, 2 => f)
@test factorize(A) == UpperTriangular(A)
end
end # for eltya
@testset "test out of bounds triu/tril" begin
local m, n = 5, 7
ainit = rand(m, n)
for a in (copy(ainit), view(ainit, 1:m, 1:n))
@test triu(a, -m) == a
@test triu(a, n + 2) == zero(a)
@test tril(a, -m - 2) == zero(a)
@test tril(a, n) == a
end
end
@testset "triu M > N case bug fix" begin
mat=[1 2;
3 4;
5 6;
7 8]
res=[1 2;
3 4;
0 6;
0 0]
@test triu(mat, -1) == res
end
@testset "Tests norms" begin
nnorm = 10
mmat = 10
nmat = 8
@testset "For $elty" for elty in (Float32, Float64, BigFloat, ComplexF32, ComplexF64, Complex{BigFloat}, Int32, Int64, BigInt)
x = fill(elty(1),10)
@testset "Vector" begin
xs = view(x,1:2:10)
@test norm(x, -Inf) ≈ 1
@test norm(x, -1) ≈ 1/10
@test norm(x, 0) ≈ 10
@test norm(x, 1) ≈ 10
@test norm(x, 2) ≈ sqrt(10)
@test norm(x, 3) ≈ cbrt(10)
@test norm(x, Inf) ≈ 1
if elty <: LinearAlgebra.BlasFloat
@test norm(x, 1:4) ≈ 2
@test_throws BoundsError norm(x,-1:4)
@test_throws BoundsError norm(x,1:11)
end
@test norm(xs, -Inf) ≈ 1
@test norm(xs, -1) ≈ 1/5
@test norm(xs, 0) ≈ 5
@test norm(xs, 1) ≈ 5
@test norm(xs, 2) ≈ sqrt(5)
@test norm(xs, 3) ≈ cbrt(5)
@test norm(xs, Inf) ≈ 1
end
@testset "Issue #12552:" begin
if real(elty) <: AbstractFloat
for p in [-Inf,-1,1,2,3,Inf]
@test isnan(norm(elty[0,NaN],p))
@test isnan(norm(elty[NaN,0],p))
end
end
end
@testset "Number" begin
norm(x[1:1]) === norm(x[1], -Inf)
norm(x[1:1]) === norm(x[1], 0)
norm(x[1:1]) === norm(x[1], 1)
norm(x[1:1]) === norm(x[1], 2)
norm(x[1:1]) === norm(x[1], Inf)
end
@testset "Absolute homogeneity, triangle inequality, & vectorized versions" begin
for i = 1:10
xinit = elty <: Integer ? convert(Vector{elty}, rand(1:10, nnorm)) :
elty <: Complex ? convert(Vector{elty}, complex.(randn(nnorm), randn(nnorm))) :
convert(Vector{elty}, randn(nnorm))
yinit = elty <: Integer ? convert(Vector{elty}, rand(1:10, nnorm)) :
elty <: Complex ? convert(Vector{elty}, complex.(randn(nnorm), randn(nnorm))) :
convert(Vector{elty}, randn(nnorm))
α = elty <: Integer ? randn() :
elty <: Complex ? convert(elty, complex(randn(),randn())) :
convert(elty, randn())
for (x, y) in ((copy(xinit), copy(yinit)), (view(xinit,1:2:nnorm), view(yinit,1:2:nnorm)))
# Absolute homogeneity
@test norm(α*x,-Inf) ≈ abs(α)*norm(x,-Inf)
@test norm(α*x,-1) ≈ abs(α)*norm(x,-1)
@test norm(α*x,1) ≈ abs(α)*norm(x,1)
@test norm(α*x) ≈ abs(α)*norm(x) # two is default
@test norm(α*x,3) ≈ abs(α)*norm(x,3)
@test norm(α*x,Inf) ≈ abs(α)*norm(x,Inf)
# Triangle inequality
@test norm(x + y,1) <= norm(x,1) + norm(y,1)
@test norm(x + y) <= norm(x) + norm(y) # two is default
@test norm(x + y,3) <= norm(x,3) + norm(y,3)
@test norm(x + y,Inf) <= norm(x,Inf) + norm(y,Inf)
# Against vectorized versions
@test norm(x,-Inf) ≈ minimum(abs.(x))
@test norm(x,-1) ≈ inv(sum(1 ./ abs.(x)))
@test norm(x,0) ≈ sum(x .!= 0)
@test norm(x,1) ≈ sum(abs.(x))
@test norm(x) ≈ sqrt(sum(abs2.(x)))
@test norm(x,3) ≈ cbrt(sum(abs.(x).^3.))
@test norm(x,Inf) ≈ maximum(abs.(x))
end
end
end
@testset "Matrix (Operator) opnorm" begin
A = fill(elty(1),10,10)
As = view(A,1:5,1:5)
@test opnorm(A, 1) ≈ 10
elty <: Union{BigFloat,Complex{BigFloat},BigInt} || @test opnorm(A, 2) ≈ 10
@test opnorm(A, Inf) ≈ 10
@test opnorm(As, 1) ≈ 5
elty <: Union{BigFloat,Complex{BigFloat},BigInt} || @test opnorm(As, 2) ≈ 5
@test opnorm(As, Inf) ≈ 5
end
@testset "Absolute homogeneity, triangle inequality, & norm" begin
for i = 1:10
Ainit = elty <: Integer ? convert(Matrix{elty}, rand(1:10, mmat, nmat)) :
elty <: Complex ? convert(Matrix{elty}, complex.(randn(mmat, nmat), randn(mmat, nmat))) :
convert(Matrix{elty}, randn(mmat, nmat))
Binit = elty <: Integer ? convert(Matrix{elty}, rand(1:10, mmat, nmat)) :
elty <: Complex ? convert(Matrix{elty}, complex.(randn(mmat, nmat), randn(mmat, nmat))) :
convert(Matrix{elty}, randn(mmat, nmat))
α = elty <: Integer ? randn() :
elty <: Complex ? convert(elty, complex(randn(),randn())) :
convert(elty, randn())
for (A, B) in ((copy(Ainit), copy(Binit)), (view(Ainit,1:nmat,1:nmat), view(Binit,1:nmat,1:nmat)))
# Absolute homogeneity
@test norm(α*A,1) ≈ abs(α)*norm(A,1)
elty <: Union{BigFloat,Complex{BigFloat},BigInt} || @test norm(α*A) ≈ abs(α)*norm(A) # two is default
@test norm(α*A,Inf) ≈ abs(α)*norm(A,Inf)
# Triangle inequality
@test norm(A + B,1) <= norm(A,1) + norm(B,1)
elty <: Union{BigFloat,Complex{BigFloat},BigInt} || @test norm(A + B) <= norm(A) + norm(B) # two is default
@test norm(A + B,Inf) <= norm(A,Inf) + norm(B,Inf)
# norm
for p in (-Inf, Inf, (-2:3)...)
@test norm(A, p) == norm(vec(A), p)
end
end
end
@testset "issue #10234" begin
if elty <: AbstractFloat || elty <: Complex
z = zeros(elty, 100)
z[1] = -Inf
for p in [-2,-1.5,-1,-0.5,0.5,1,1.5,2,Inf]
@test norm(z, p) == (p < 0 ? 0 : Inf)
@test norm(elty[Inf],p) == Inf
end
end
end
end
end
@testset "issue #10234" begin
@test norm(Any[Inf],-2) == norm(Any[Inf],-1) == norm(Any[Inf],1) == norm(Any[Inf],1.5) == norm(Any[Inf],2) == norm(Any[Inf],Inf) == Inf
end
@testset "overflow/underflow in norms" begin
@test norm(Float64[1e-300, 1], -3)*1e300 ≈ 1
@test norm(Float64[1e300, 1], 3)*1e-300 ≈ 1
end
end
## Issue related tests
@testset "issue #1447" begin
A = [1.0+0.0im 0; 0 1]
B = pinv(A)
for i = 1:4
@test A[i] ≈ B[i]
end
end
@testset "issue #2246" begin
A = [1 2 0 0; 0 1 0 0; 0 0 0 0; 0 0 0 0]
Asq = sqrt(A)
@test Asq*Asq ≈ A
A2 = view(A, 1:2, 1:2)
A2sq = sqrt(A2)
@test A2sq*A2sq ≈ A2
N = 3
@test log(det(Matrix(1.0I, N, N))) ≈ logdet(Matrix(1.0I, N, N))
end
@testset "issue #2637" begin
a = [1, 2, 3]
b = [4, 5, 6]
@test kron(Matrix(I, 2, 2), Matrix(I, 2, 2)) == Matrix(I, 4, 4)
@test kron(a,b) == [4,5,6,8,10,12,12,15,18]
@test kron(a',b') == [4 5 6 8 10 12 12 15 18]
@test kron(a,b') == [4 5 6; 8 10 12; 12 15 18]
@test kron(a',b) == [4 8 12; 5 10 15; 6 12 18]
@test kron(a, Matrix(1I, 2, 2)) == [1 0; 0 1; 2 0; 0 2; 3 0; 0 3]
@test kron(Matrix(1I, 2, 2), a) == [ 1 0; 2 0; 3 0; 0 1; 0 2; 0 3]
@test kron(Matrix(1I, 2, 2), 2) == Matrix(2I, 2, 2)
@test kron(3, Matrix(1I, 3, 3)) == Matrix(3I, 3, 3)
@test kron(a,2) == [2, 4, 6]
@test kron(b',2) == [8 10 12]
end
@testset "kron!" begin
a = [1.0, 0.0]
b = [0.0, 1.0]
@test kron!([1.0, 0.0], b, 0.5) == [0.0; 0.5]
@test kron!([1.0, 0.0], 0.5, b) == [0.0; 0.5]
c = Vector{Float64}(undef, 4)
kron!(c, a, b)
@test c == [0.0; 1.0; 0.0; 0.0]
c = Matrix{Float64}(undef, 2, 2)
kron!(c, a, b')
@test c == [0.0 1.0; 0.0 0.0]
end
@testset "kron adjoint" begin
a = [1+im, 2, 3]
b = [4, 5, 6+7im]
@test kron(a', b') isa Adjoint
@test kron(a', b') == kron(a, b)'
@test kron(transpose(a), b') isa Transpose
@test kron(transpose(a), b') == kron(permutedims(a), collect(b'))
@test kron(transpose(a), transpose(b)) isa Transpose
@test kron(transpose(a), transpose(b)) == transpose(kron(a, b))
end
@testset "issue #4796" begin
dim=2
S=zeros(Complex,dim,dim)
T=zeros(Complex,dim,dim)
fill!(T, 1)
z = 2.5 + 1.5im
S[1] = z
@test S*T == [z z; 0 0]
# similar issue for Array{Real}
@test Real[1 2] * Real[1.5; 2.0] == Real[5.5]
end
@testset "Matrix exponential" begin
@testset "Tests for $elty" for elty in (Float32, Float64, ComplexF32, ComplexF64)
A1 = convert(Matrix{elty}, [4 2 0; 1 4 1; 1 1 4])
eA1 = convert(Matrix{elty}, [147.866622446369 127.781085523181 127.781085523182;
183.765138646367 183.765138646366 163.679601723179;
71.797032399996 91.8825693231832 111.968106246371]')
@test exp(A1) ≈ eA1
@test exp(adjoint(A1)) ≈ adjoint(eA1)
@test exp(transpose(A1)) ≈ transpose(eA1)
for f in (sin, cos, sinh, cosh, tanh, tan)
@test f(adjoint(A1)) ≈ f(copy(adjoint(A1)))
end
A2 = convert(Matrix{elty},
[29.87942128909879 0.7815750847907159 -2.289519314033932;
0.7815750847907159 25.72656945571064 8.680737820540137;
-2.289519314033932 8.680737820540137 34.39400925519054])
eA2 = convert(Matrix{elty},
[ 5496313853692458.0 -18231880972009236.0 -30475770808580460.0;
-18231880972009252.0 60605228702221920.0 101291842930249760.0;
-30475770808580480.0 101291842930249728.0 169294411240851968.0])
@test exp(A2) ≈ eA2
@test exp(adjoint(A2)) ≈ adjoint(eA2)
@test exp(transpose(A2)) ≈ transpose(eA2)
A3 = convert(Matrix{elty}, [-131 19 18;-390 56 54;-387 57 52])
eA3 = convert(Matrix{elty}, [-1.50964415879218 -5.6325707998812 -4.934938326092;
0.367879439109187 1.47151775849686 1.10363831732856;
0.135335281175235 0.406005843524598 0.541341126763207]')
@test exp(A3) ≈ eA3
@test exp(adjoint(A3)) ≈ adjoint(eA3)
@test exp(transpose(A3)) ≈ transpose(eA3)
A4 = convert(Matrix{elty}, [0.25 0.25; 0 0])
eA4 = convert(Matrix{elty}, [1.2840254166877416 0.2840254166877415; 0 1])
@test exp(A4) ≈ eA4
@test exp(adjoint(A4)) ≈ adjoint(eA4)
@test exp(transpose(A4)) ≈ transpose(eA4)
A5 = convert(Matrix{elty}, [0 0.02; 0 0])
eA5 = convert(Matrix{elty}, [1 0.02; 0 1])
@test exp(A5) ≈ eA5
@test exp(adjoint(A5)) ≈ adjoint(eA5)
@test exp(transpose(A5)) ≈ transpose(eA5)
# Hessenberg
@test hessenberg(A1).H ≈ convert(Matrix{elty},
[4.000000000000000 -1.414213562373094 -1.414213562373095
-1.414213562373095 4.999999999999996 -0.000000000000000
0 -0.000000000000002 3.000000000000000])
# cis always returns a complex matrix
if elty <: Real
eltyim = Complex{elty}
else
eltyim = elty
end
@test cis(A1) ≈ convert(Matrix{eltyim}, [-0.339938 + 0.000941506im 0.772659 - 0.8469im 0.52745 + 0.566543im;
0.650054 - 0.140179im -0.0762135 + 0.284213im 0.38633 - 0.42345im ;
0.650054 - 0.140179im 0.913779 + 0.143093im -0.603663 - 0.28233im ]) rtol=7e-7
end
@testset "Additional tests for $elty" for elty in (Float64, ComplexF64)
A4 = convert(Matrix{elty}, [1/2 1/3 1/4 1/5+eps();
1/3 1/4 1/5 1/6;
1/4 1/5 1/6 1/7;
1/5 1/6 1/7 1/8])
@test exp(log(A4)) ≈ A4
@test exp(log(transpose(A4))) ≈ transpose(A4)
@test exp(log(adjoint(A4))) ≈ adjoint(A4)
A5 = convert(Matrix{elty}, [1 1 0 1; 0 1 1 0; 0 0 1 1; 1 0 0 1])
@test exp(log(A5)) ≈ A5
@test exp(log(transpose(A5))) ≈ transpose(A5)
@test exp(log(adjoint(A5))) ≈ adjoint(A5)
A6 = convert(Matrix{elty}, [-5 2 0 0 ; 1/2 -7 3 0; 0 1/3 -9 4; 0 0 1/4 -11])
@test exp(log(A6)) ≈ A6
@test exp(log(transpose(A6))) ≈ transpose(A6)
@test exp(log(adjoint(A6))) ≈ adjoint(A6)
A7 = convert(Matrix{elty}, [1 0 0 1e-8; 0 1 0 0; 0 0 1 0; 0 0 0 1])
@test exp(log(A7)) ≈ A7
@test exp(log(transpose(A7))) ≈ transpose(A7)
@test exp(log(adjoint(A7))) ≈ adjoint(A7)
end
@testset "Integer promotion tests" begin
for (elty1, elty2) in ((Int64, Float64), (Complex{Int64}, ComplexF64))
A4int = convert(Matrix{elty1}, [1 2; 3 4])
A4float = convert(Matrix{elty2}, A4int)
@test exp(A4int) == exp(A4float)
end
end
@testset "^ tests" for elty in (Float32, Float64, ComplexF32, ComplexF64, Int32, Int64)
# should all be exact as the lhs functions are simple aliases
@test ℯ^(fill(elty(2), (4,4))) == exp(fill(elty(2), (4,4)))
@test 2^(fill(elty(2), (4,4))) == exp(log(2)*fill(elty(2), (4,4)))
@test 2.0^(fill(elty(2), (4,4))) == exp(log(2.0)*fill(elty(2), (4,4)))
end
A8 = 100 * [-1+1im 0 0 1e-8; 0 1 0 0; 0 0 1 0; 0 0 0 1]
@test exp(log(A8)) ≈ A8
end
@testset "Matrix trigonometry" begin
@testset "Tests for $elty" for elty in (Float32, Float64, ComplexF32, ComplexF64)
A1 = convert(Matrix{elty}, [3 2 0; 1 3 1; 1 1 3])
A2 = convert(Matrix{elty},
[3.975884257819758 0.15631501695814318 -0.4579038628067864;
0.15631501695814318 4.545313891142127 1.7361475641080275;
-0.4579038628067864 1.7361475641080275 6.478801851038108])
A3 = convert(Matrix{elty}, [0.25 0.25; 0 0])
A4 = convert(Matrix{elty}, [0 0.02; 0 0])
cosA1 = convert(Matrix{elty},[-0.18287716254368605 -0.29517205254584633 0.761711400552759;
0.23326967400345625 0.19797853773269333 -0.14758602627292305;
0.23326967400345636 0.6141253742798355 -0.5637328628200653])
sinA1 = convert(Matrix{elty}, [0.2865568596627417 -1.107751980582015 -0.13772915374386513;
-0.6227405671629401 0.2176922827908092 -0.5538759902910078;
-0.6227405671629398 -0.6916051440348725 0.3554214365346742])
@test cos(A1) ≈ cosA1
@test sin(A1) ≈ sinA1
cosA2 = convert(Matrix{elty}, [-0.6331745163802187 0.12878366262380136 -0.17304181968301532;
0.12878366262380136 -0.5596234510748788 0.5210483146041339;
-0.17304181968301532 0.5210483146041339 0.002263776356015268])
sinA2 = convert(Matrix{elty},[-0.6677253518411841 -0.32599318928375437 0.020799609079003523;
-0.32599318928375437 -0.04568726058081066 0.5388748740270427;
0.020799609079003523 0.5388748740270427 0.6385462428126032])
@test cos(A2) ≈ cosA2
@test sin(A2) ≈ sinA2
cosA3 = convert(Matrix{elty}, [0.9689124217106446 -0.031087578289355197; 0.0 1.0])
sinA3 = convert(Matrix{elty}, [0.24740395925452285 0.24740395925452285; 0.0 0.0])
@test cos(A3) ≈ cosA3
@test sin(A3) ≈ sinA3
cosA4 = convert(Matrix{elty}, [1.0 0.0; 0.0 1.0])
sinA4 = convert(Matrix{elty}, [0.0 0.02; 0.0 0.0])
@test cos(A4) ≈ cosA4
@test sin(A4) ≈ sinA4
# Identities
for (i, A) in enumerate((A1, A2, A3, A4))
@test sincos(A) == (sin(A), cos(A))
@test cos(A)^2 + sin(A)^2 ≈ Matrix(I, size(A))
@test cos(A) ≈ cos(-A)
@test sin(A) ≈ -sin(-A)
@test tan(A) ≈ sin(A) / cos(A)
@test cos(A) ≈ real(exp(im*A))
@test sin(A) ≈ imag(exp(im*A))
@test cos(A) ≈ real(cis(A))
@test sin(A) ≈ imag(cis(A))
@test cis(A) ≈ cos(A) + im * sin(A)
@test cosh(A) ≈ 0.5 * (exp(A) + exp(-A))
@test sinh(A) ≈ 0.5 * (exp(A) - exp(-A))
@test cosh(A) ≈ cosh(-A)
@test sinh(A) ≈ -sinh(-A)
# Some of the following identities fail for A3, A4 because the matrices are singular
if i in (1, 2)
@test sec(A) ≈ inv(cos(A))
@test csc(A) ≈ inv(sin(A))
@test cot(A) ≈ inv(tan(A))
@test sech(A) ≈ inv(cosh(A))
@test csch(A) ≈ inv(sinh(A))
@test coth(A) ≈ inv(tanh(A))
end
# The following identities fail for A1, A2 due to rounding errors;
# probably needs better algorithm for the general case
if i in (3, 4)
@test cosh(A)^2 - sinh(A)^2 ≈ Matrix(I, size(A))
@test tanh(A) ≈ sinh(A) / cosh(A)
end
end
end
@testset "Additional tests for $elty" for elty in (ComplexF32, ComplexF64)
A5 = convert(Matrix{elty}, [1im 2; 0.02+0.5im 3])
@test sincos(A5) == (sin(A5), cos(A5))
@test cos(A5)^2 + sin(A5)^2 ≈ Matrix(I, size(A5))
@test cosh(A5)^2 - sinh(A5)^2 ≈ Matrix(I, size(A5))
@test cos(A5)^2 + sin(A5)^2 ≈ Matrix(I, size(A5))
@test tan(A5) ≈ sin(A5) / cos(A5)
@test tanh(A5) ≈ sinh(A5) / cosh(A5)
@test sec(A5) ≈ inv(cos(A5))
@test csc(A5) ≈ inv(sin(A5))
@test cot(A5) ≈ inv(tan(A5))
@test sech(A5) ≈ inv(cosh(A5))
@test csch(A5) ≈ inv(sinh(A5))
@test coth(A5) ≈ inv(tanh(A5))
@test cos(A5) ≈ 0.5 * (exp(im*A5) + exp(-im*A5))
@test sin(A5) ≈ -0.5im * (exp(im*A5) - exp(-im*A5))
@test cos(A5) ≈ 0.5 * (cis(A5) + cis(-A5))
@test sin(A5) ≈ -0.5im * (cis(A5) - cis(-A5))
@test cosh(A5) ≈ 0.5 * (exp(A5) + exp(-A5))
@test sinh(A5) ≈ 0.5 * (exp(A5) - exp(-A5))
end
@testset "Additional tests for $elty" for elty in (Int32, Int64, Complex{Int32}, Complex{Int64})
A1 = convert(Matrix{elty}, [1 2; 3 4])
A2 = convert(Matrix{elty}, [1 2; 2 1])
cosA1 = convert(Matrix{float(elty)}, [0.855423165077998 -0.11087638101074865;
-0.16631457151612294 0.689108593561875])
cosA2 = convert(Matrix{float(elty)}, [-0.22484509536615283 -0.7651474012342925;
-0.7651474012342925 -0.22484509536615283])
@test cos(A1) ≈ cosA1
@test cos(A2) ≈ cosA2
sinA1 = convert(Matrix{float(elty)}, [-0.46558148631373036 -0.14842445991317652;
-0.22263668986976476 -0.6882181761834951])
sinA2 = convert(Matrix{float(elty)}, [-0.3501754883740146 0.4912954964338818;
0.4912954964338818 -0.3501754883740146])
@test sin(A1) ≈ sinA1
@test sin(A2) ≈ sinA2
end
@testset "Inverse functions for $elty" for elty in (Float32, Float64)
A1 = convert(Matrix{elty}, [0.244637 -0.63578;
0.22002 0.189026])
A2 = convert(Matrix{elty}, [1.11656 -0.098672 0.158485;
-0.098672 0.100933 -0.107107;
0.158485 -0.107107 0.612404])
for A in (A1, A2)
@test cos(acos(cos(A))) ≈ cos(A)
@test sin(asin(sin(A))) ≈ sin(A)
@test tan(atan(tan(A))) ≈ tan(A)
@test cosh(acosh(cosh(A))) ≈ cosh(A)
@test sinh(asinh(sinh(A))) ≈ sinh(A)
@test tanh(atanh(tanh(A))) ≈ tanh(A)
@test sec(asec(sec(A))) ≈ sec(A)
@test csc(acsc(csc(A))) ≈ csc(A)
@test cot(acot(cot(A))) ≈ cot(A)
@test sech(asech(sech(A))) ≈ sech(A)
@test csch(acsch(csch(A))) ≈ csch(A)
@test coth(acoth(coth(A))) ≈ coth(A)
end
end
@testset "Inverse functions for $elty" for elty in (ComplexF32, ComplexF64)
A1 = convert(Matrix{elty}, [ 0.143721-0.0im -0.138386-0.106905im;
-0.138386+0.106905im 0.306224-0.0im])
A2 = convert(Matrix{elty}, [1im 2; 0.02+0.5im 3])
A3 = convert(Matrix{elty}, [0.138721-0.266836im 0.0971722-0.13715im 0.205046-0.137136im;
-0.0154974-0.00358254im 0.152163-0.445452im 0.0314575-0.536521im;
-0.387488+0.0294059im -0.0448773+0.114305im 0.230684-0.275894im])
for A in (A1, A2, A3)
@test cos(acos(cos(A))) ≈ cos(A)
@test sin(asin(sin(A))) ≈ sin(A)
@test tan(atan(tan(A))) ≈ tan(A)
@test cosh(acosh(cosh(A))) ≈ cosh(A)
@test sinh(asinh(sinh(A))) ≈ sinh(A)
@test tanh(atanh(tanh(A))) ≈ tanh(A)
@test sec(asec(sec(A))) ≈ sec(A)
@test csc(acsc(csc(A))) ≈ csc(A)
@test cot(acot(cot(A))) ≈ cot(A)
@test sech(asech(sech(A))) ≈ sech(A)
@test csch(acsch(csch(A))) ≈ csch(A)
@test coth(acoth(coth(A))) ≈ coth(A)
# Definition of principal values (Aprahamian & Higham, 2016, pp. 4-5)
abstol = sqrt(eps(real(elty))) * norm(acosh(A))
@test all(z -> (0 < real(z) < π ||
abs(real(z)) < abstol && imag(z) >= 0 ||
abs(real(z) - π) < abstol && imag(z) <= 0),
eigen(acos(A)).values)
@test all(z -> (-π/2 < real(z) < π/2 ||
abs(real(z) + π/2) < abstol && imag(z) >= 0 ||
abs(real(z) - π/2) < abstol && imag(z) <= 0),
eigen(asin(A)).values)
@test all(z -> (-π < imag(z) < π && real(z) > 0 ||
0 <= imag(z) < π && abs(real(z)) < abstol ||
abs(imag(z) - π) < abstol && real(z) >= 0),
eigen(acosh(A)).values)
@test all(z -> (-π/2 < imag(z) < π/2 ||
abs(imag(z) + π/2) < abstol && real(z) <= 0 ||
abs(imag(z) - π/2) < abstol && real(z) <= 0),
eigen(asinh(A)).values)
end
end
end
@testset "issue 5116" begin
A9 = [0 10 0 0; -1 0 0 0; 0 0 0 0; -2 0 0 0]
eA9 = [-0.999786072879326 -0.065407069689389 0.0 0.0
0.006540706968939 -0.999786072879326 0.0 0.0
0.0 0.0 1.0 0.0
0.013081413937878 -3.999572145758650 0.0 1.0]
@test exp(A9) ≈ eA9
A10 = [ 0. 0. 0. 0. ; 0. 0. -im 0.; 0. im 0. 0.; 0. 0. 0. 0.]
eA10 = [ 1.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im
0.0+0.0im 1.543080634815244+0.0im 0.0-1.175201193643801im 0.0+0.0im
0.0+0.0im 0.0+1.175201193643801im 1.543080634815243+0.0im 0.0+0.0im
0.0+0.0im 0.0+0.0im 0.0+0.0im 1.0+0.0im]
@test exp(A10) ≈ eA10
end
@testset "Additional matrix logarithm tests" for elty in (Float64, ComplexF64)
A11 = convert(Matrix{elty}, [3 2; -5 -3])
@test exp(log(A11)) ≈ A11
A13 = convert(Matrix{elty}, [2 0; 0 2])
@test typeof(log(A13)) == Array{elty, 2}
T = elty == Float64 ? Symmetric : Hermitian
@test typeof(log(T(A13))) == T{elty, Array{elty, 2}}
A1 = convert(Matrix{elty}, [4 2 0; 1 4 1; 1 1 4])
logA1 = convert(Matrix{elty}, [1.329661349 0.5302876358 -0.06818951543;
0.2310490602 1.295566591 0.2651438179;
0.2310490602 0.1969543025 1.363756107])
@test log(A1) ≈ logA1
@test exp(log(A1)) ≈ A1
@test typeof(log(A1)) == Matrix{elty}
A4 = convert(Matrix{elty}, [1/2 1/3 1/4 1/5+eps();
1/3 1/4 1/5 1/6;
1/4 1/5 1/6 1/7;
1/5 1/6 1/7 1/8])
logA4 = convert(Matrix{elty}, [-1.73297159 1.857349738 0.4462766564 0.2414170219;
1.857349738 -5.335033737 2.994142974 0.5865285289;
0.4462766564 2.994142974 -7.351095988 3.318413247;
0.2414170219 0.5865285289 3.318413247 -5.444632124])
@test log(A4) ≈ logA4
@test exp(log(A4)) ≈ A4
@test typeof(log(A4)) == Matrix{elty}
# real triu matrix
A5 = convert(Matrix{elty}, [1 2 3; 0 4 5; 0 0 6]) # triu
logA5 = convert(Matrix{elty}, [0.0 0.9241962407465937 0.5563245488984037;
0.0 1.3862943611198906 1.0136627702704109;
0.0 0.0 1.791759469228055])
@test log(A5) ≈ logA5
@test exp(log(A5)) ≈ A5
@test typeof(log(A5)) == Matrix{elty}
# real quasitriangular schur form with 2 2x2 blocks, 2 1x1 blocks, and all positive eigenvalues
A6 = convert(Matrix{elty}, [2 3 2 2 3 1;
1 3 3 2 3 1;
3 3 3 1 1 2;
2 1 2 2 2 2;
1 1 2 2 3 1;
2 2 2 2 1 3])
@test exp(log(A6)) ≈ A6
@test typeof(log(A6)) == Matrix{elty}
# real quasitriangular schur form with a negative eigenvalue
A7 = convert(Matrix{elty}, [1 3 3 2 2 2;
1 2 1 3 1 2;
3 1 2 3 2 1;
3 1 2 2 2 1;
3 1 3 1 2 1;
1 1 3 1 1 3])
@test exp(log(A7)) ≈ A7
@test typeof(log(A7)) == Matrix{complex(elty)}
if elty <: Complex
A8 = convert(Matrix{elty}, [1 + 1im 1 + 1im 1 - 1im;
1 + 1im -1 + 1im 1 + 1im;
1 - 1im 1 + 1im -1 - 1im])
logA8 = convert(
Matrix{elty},
[0.9478628953131517 + 1.3725201223387407im -0.2547157147532057 + 0.06352318334299434im 0.8560050197863862 - 1.0471975511965979im;
-0.2547157147532066 + 0.06352318334299467im -0.16285783922644065 + 0.2617993877991496im 0.2547157147532063 + 2.1579182857361894im;
0.8560050197863851 - 1.0471975511965974im 0.25471571475320665 + 2.1579182857361903im 0.9478628953131519 - 0.8489213467404436im],
)
@test log(A8) ≈ logA8
@test exp(log(A8)) ≈ A8
@test typeof(log(A8)) == Matrix{elty}
end
end
@testset "matrix logarithm is type-inferrable" for elty in (Float32,Float64,ComplexF32,ComplexF64)
A1 = randn(elty, 4, 4)
@inferred Union{Matrix{elty},Matrix{complex(elty)}} log(A1)
end
@testset "Additional matrix square root tests" for elty in (Float64, ComplexF64)
A11 = convert(Matrix{elty}, [3 2; -5 -3])
@test sqrt(A11)^2 ≈ A11
A13 = convert(Matrix{elty}, [2 0; 0 2])
@test typeof(sqrt(A13)) == Array{elty, 2}
T = elty == Float64 ? Symmetric : Hermitian
@test typeof(sqrt(T(A13))) == T{elty, Array{elty, 2}}
A1 = convert(Matrix{elty}, [4 2 0; 1 4 1; 1 1 4])
sqrtA1 = convert(Matrix{elty}, [1.971197119306979 0.5113118387140085 -0.03301921523780871;
0.23914631173809942 1.9546875116880718 0.2556559193570036;
0.23914631173810008 0.22263670411919556 1.9877067269258815])
@test sqrt(A1) ≈ sqrtA1
@test sqrt(A1)^2 ≈ A1
@test typeof(sqrt(A1)) == Matrix{elty}
A4 = convert(Matrix{elty}, [1/2 1/3 1/4 1/5+eps();
1/3 1/4 1/5 1/6;
1/4 1/5 1/6 1/7;
1/5 1/6 1/7 1/8])
sqrtA4 = convert(
Matrix{elty},
[0.590697761556362 0.3055006800405779 0.19525404749300546 0.14007621469988107;
0.30550068004057784 0.2825388389385975 0.21857572599211642 0.17048692323164674;
0.19525404749300565 0.21857572599211622 0.21155429252242863 0.18976816626246887;
0.14007621469988046 0.17048692323164724 0.1897681662624689 0.20075085592778794],
)
@test sqrt(A4) ≈ sqrtA4
@test sqrt(A4)^2 ≈ A4
@test typeof(sqrt(A4)) == Matrix{elty}
# real triu matrix
A5 = convert(Matrix{elty}, [1 2 3; 0 4 5; 0 0 6]) # triu
sqrtA5 = convert(Matrix{elty}, [1.0 0.6666666666666666 0.6525169217864183;
0.0 2.0 1.1237243569579454;
0.0 0.0 2.449489742783178])
@test sqrt(A5) ≈ sqrtA5
@test sqrt(A5)^2 ≈ A5
@test typeof(sqrt(A5)) == Matrix{elty}
# real quasitriangular schur form with 2 2x2 blocks, 2 1x1 blocks, and all positive eigenvalues
A6 = convert(Matrix{elty}, [2 3 2 2 3 1;
1 3 3 2 3 1;
3 3 3 1 1 2;
2 1 2 2 2 2;
1 1 2 2 3 1;
2 2 2 2 1 3])
@test sqrt(A6)^2 ≈ A6
@test typeof(sqrt(A6)) == Matrix{elty}
# real quasitriangular schur form with a negative eigenvalue
A7 = convert(Matrix{elty}, [1 3 3 2 2 2;
1 2 1 3 1 2;
3 1 2 3 2 1;
3 1 2 2 2 1;
3 1 3 1 2 1;
1 1 3 1 1 3])
@test sqrt(A7)^2 ≈ A7
@test typeof(sqrt(A7)) == Matrix{complex(elty)}
if elty <: Complex
A8 = convert(Matrix{elty}, [1 + 1im 1 + 1im 1 - 1im;
1 + 1im -1 + 1im 1 + 1im;
1 - 1im 1 + 1im -1 - 1im])
sqrtA8 = convert(
Matrix{elty},
[1.2559748527474284 + 0.6741878819930323im 0.20910077991005582 + 0.24969165051825476im 0.591784212275146 - 0.6741878819930327im;
0.2091007799100553 + 0.24969165051825515im 0.3320953202361413 + 0.2915044496279425im 0.33209532023614136 + 1.0568713143581219im;
0.5917842122751455 - 0.674187881993032im 0.33209532023614147 + 1.0568713143581223im 0.7147787526012315 - 0.6323750828833452im],
)
@test sqrt(A8) ≈ sqrtA8
@test sqrt(A8)^2 ≈ A8
@test typeof(sqrt(A8)) == Matrix{elty}
end
end
@testset "issue #40141" begin
x = [-1 -eps() 0 0; eps() -1 0 0; 0 0 -1 -eps(); 0 0 eps() -1]
@test sqrt(x)^2 ≈ x
x2 = [-1 -eps() 0 0; 3eps() -1 0 0; 0 0 -1 -3eps(); 0 0 eps() -1]
@test sqrt(x2)^2 ≈ x2
x3 = [-1 -eps() 0 0; eps() -1 0 0; 0 0 -1 -eps(); 0 0 eps() Inf]
@test all(isnan, sqrt(x3))
# test overflow/underflow handled
x4 = [0 -1e200; 1e200 0]
@test sqrt(x4)^2 ≈ x4
x5 = [0 -1e-200; 1e-200 0]
@test sqrt(x5)^2 ≈ x5
x6 = [1.0 1e200; -1e-200 1.0]
@test sqrt(x6)^2 ≈ x6
end
@testset "matrix logarithm block diagonal underflow/overflow" begin
x1 = [0 -1e200; 1e200 0]
@test exp(log(x1)) ≈ x1
x2 = [0 -1e-200; 1e-200 0]
@test exp(log(x2)) ≈ x2
x3 = [1.0 1e200; -1e-200 1.0]
@test exp(log(x3)) ≈ x3
end
@testset "issue #7181" begin
A = [ 1 5 9
2 6 10
3 7 11
4 8 12 ]
@test diag(A,-5) == []
@test diag(A,-4) == []
@test diag(A,-3) == [4]
@test diag(A,-2) == [3,8]
@test diag(A,-1) == [2,7,12]
@test diag(A, 0) == [1,6,11]
@test diag(A, 1) == [5,10]
@test diag(A, 2) == [9]
@test diag(A, 3) == []
@test diag(A, 4) == []
@test diag(zeros(0,0)) == []
@test diag(zeros(0,0),1) == []
@test diag(zeros(0,0),-1) == []
@test diag(zeros(1,0)) == []
@test diag(zeros(1,0),-1) == []
@test diag(zeros(1,0),1) == []
@test diag(zeros(1,0),-2) == []
@test diag(zeros(0,1)) == []
@test diag(zeros(0,1),1) == []
@test diag(zeros(0,1),-1) == []
@test diag(zeros(0,1),2) == []
end
@testset "issue #39857" begin
@test lyap(1.0+2.0im, 3.0+4.0im) == -1.5 - 2.0im
end
@testset "Matrix to real power" for elty in (Float64, ComplexF64)
# Tests proposed at Higham, Deadman: Testing Matrix Function Algorithms Using Identities, March 2014
#Aa : only positive real eigenvalues
Aa = convert(Matrix{elty}, [5 4 2 1; 0 1 -1 -1; -1 -1 3 0; 1 1 -1 2])
#Ab : both positive and negative real eigenvalues
Ab = convert(Matrix{elty}, [1 2 3; 4 7 1; 2 1 4])
#Ac : complex eigenvalues
Ac = convert(Matrix{elty}, [5 4 2 1;0 1 -1 -1;-1 -1 3 6;1 1 -1 5])
#Ad : defective Matrix
Ad = convert(Matrix{elty}, [3 1; 0 3])
#Ah : Hermitian Matrix
Ah = convert(Matrix{elty}, [3 1; 1 3])
if elty <: LinearAlgebra.BlasComplex
Ah += [0 im; -im 0]
end
#ADi : Diagonal Matrix
ADi = convert(Matrix{elty}, [3 0; 0 3])
if elty <: LinearAlgebra.BlasComplex
ADi += [im 0; 0 im]
end
for A in (Aa, Ab, Ac, Ad, Ah, ADi)
@test A^(1/2) ≈ sqrt(A)
@test A^(-1/2) ≈ inv(sqrt(A))
@test A^(3/4) ≈ sqrt(A) * sqrt(sqrt(A))
@test A^(-3/4) ≈ inv(A) * sqrt(sqrt(A))
@test A^(17/8) ≈ A^2 * sqrt(sqrt(sqrt(A)))
@test A^(-17/8) ≈ inv(A^2 * sqrt(sqrt(sqrt(A))))
@test (A^0.2)^5 ≈ A
@test (A^(2/3))*(A^(1/3)) ≈ A
@test (A^im)^(-im) ≈ A
end
end
@testset "diagonal integer matrix to real power" begin
A = Matrix(Diagonal([1, 2, 3]))
@test A^2.3 ≈ float(A)^2.3
end
@testset "issue #23366 (Int Matrix to Int power)" begin
@testset "Tests for $elty" for elty in (Int128, Int16, Int32, Int64, Int8,
UInt128, UInt16, UInt32, UInt64, UInt8,
BigInt)
#@info "Testing $elty"
@test elty[1 1;1 0]^-1 == [0 1; 1 -1]
@test elty[1 1;1 0]^-2 == [1 -1; -1 2]
@test (@inferred elty[1 1;1 0]^2) == elty[2 1;1 1]
I_ = elty[1 0;0 1]
@test I_^-1 == I_
if !(elty<:Unsigned)
@test (@inferred (-I_)^-1) == -I_
@test (@inferred (-I_)^-2) == I_
end
# make sure that type promotion for ^(::Matrix{<:Integer}, ::Integer)
# is analogous to type promotion for ^(::Integer, ::Integer)
# e.g. [1 1;1 0]^big(10000) should return Matrix{BigInt}, the same
# way as 2^big(10000) returns BigInt
for elty2 = (Int64, BigInt)
TT = Base.promote_op(^, elty, elty2)
@test (@inferred elty[1 1;1 0]^elty2(1))::Matrix{TT} == [1 1;1 0]
end
end
end
@testset "Least squares solutions" begin
a = [fill(1, 20) 1:20 1:20]
b = reshape(Matrix(1.0I, 8, 5), 20, 2)
@testset "Tests for type $elty" for elty in (Float32, Float64, ComplexF32, ComplexF64)
a = convert(Matrix{elty}, a)
b = convert(Matrix{elty}, b)
# Vector rhs
x = a[:,1:2]\b[:,1]
@test ((a[:,1:2]*x-b[:,1])'*(a[:,1:2]*x-b[:,1]))[1] ≈ convert(elty, 2.546616541353384)
# Matrix rhs
x = a[:,1:2]\b
@test det((a[:,1:2]*x-b)'*(a[:,1:2]*x-b)) ≈ convert(elty, 4.437969924812031)
# Rank deficient
x = a\b
@test det((a*x-b)'*(a*x-b)) ≈ convert(elty, 4.437969924812031)
# Underdetermined minimum norm
x = convert(Matrix{elty}, [1 0 0; 0 1 -1]) \ convert(Vector{elty}, [1,1])
@test x ≈ convert(Vector{elty}, [1, 0.5, -0.5])
# symmetric, positive definite
@test inv(convert(Matrix{elty}, [6. 2; 2 1])) ≈ convert(Matrix{elty}, [0.5 -1; -1 3])
# symmetric, indefinite
@test inv(convert(Matrix{elty}, [1. 2; 2 1])) ≈ convert(Matrix{elty}, [-1. 2; 2 -1]/3)
end
end
function test_rdiv_pinv_consistency(a, b)
@test (a*b)/b ≈ a*(b/b) ≈ (a*b)*pinv(b) ≈ a*(b*pinv(b))
@test typeof((a*b)/b) == typeof(a*(b/b)) == typeof((a*b)*pinv(b)) == typeof(a*(b*pinv(b)))
end
function test_ldiv_pinv_consistency(a, b)
@test a\(a*b) ≈ (a\a)*b ≈ (pinv(a)*a)*b ≈ pinv(a)*(a*b)
@test typeof(a\(a*b)) == typeof((a\a)*b) == typeof((pinv(a)*a)*b) == typeof(pinv(a)*(a*b))
end
function test_div_pinv_consistency(a, b)
test_rdiv_pinv_consistency(a, b)
test_ldiv_pinv_consistency(a, b)
end
@testset "/ and \\ consistency with pinv for vectors" begin
@testset "Tests for type $elty" for elty in (Float32, Float64, ComplexF32, ComplexF64)
c = rand(elty, 5)
r = (elty <: Complex ? adjoint : transpose)(rand(elty, 5))
cm = rand(elty, 5, 1)
rm = rand(elty, 1, 5)
@testset "dot products" begin
test_div_pinv_consistency(r, c)
test_div_pinv_consistency(rm, c)
test_div_pinv_consistency(r, cm)
test_div_pinv_consistency(rm, cm)
end
@testset "outer products" begin
test_div_pinv_consistency(c, r)
test_div_pinv_consistency(cm, rm)
end
@testset "matrix/vector" begin
m = rand(5, 5)
test_ldiv_pinv_consistency(m, c)
test_rdiv_pinv_consistency(r, m)
end
end
end
@testset "test ops on Numbers for $elty" for elty in [Float32,Float64,ComplexF32,ComplexF64]
a = rand(elty)
@test isposdef(one(elty))
@test lyap(one(elty),a) == -a/2
end
@testset "strides" begin
a = rand(10)
b = view(a,2:2:10)
@test LinearAlgebra.stride1(a) == 1
@test LinearAlgebra.stride1(b) == 2
end
@testset "inverse of Adjoint" begin
A = randn(n, n)
@test @inferred(inv(A'))*A' ≈ I
@test @inferred(inv(transpose(A)))*transpose(A) ≈ I
B = complex.(A, randn(n, n))
@test @inferred(inv(B'))*B' ≈ I
@test @inferred(inv(transpose(B)))*transpose(B) ≈ I
end
@testset "Factorize fallback for Adjoint/Transpose" begin
a = rand(Complex{Int8}, n, n)
@test Array(transpose(factorize(Transpose(a)))) ≈ Array(factorize(a))
@test transpose(factorize(transpose(a))) == factorize(a)
@test Array(adjoint(factorize(Adjoint(a)))) ≈ Array(factorize(a))
@test adjoint(factorize(adjoint(a))) == factorize(a)
end
@testset "Matrix log issue #32313" begin
for A in ([30 20; -50 -30], [10.0im 0; 0 -10.0im], randn(6,6))
@test exp(log(A)) ≈ A
end
end
@testset "Matrix log PR #33245" begin
# edge case for divided difference
A1 = triu(ones(3,3),1) + diagm([1.0, -2eps()-1im, -eps()+0.75im])
@test exp(log(A1)) ≈ A1
# case where no sqrt is needed (s=0)
A2 = [1.01 0.01 0.01; 0 1.01 0.01; 0 0 1.01]
@test exp(log(A2)) ≈ A2
end
struct TypeWithoutZero end
Base.zero(::Type{TypeWithoutZero}) = TypeWithZero()
struct TypeWithZero end
Base.promote_rule(::Type{TypeWithoutZero}, ::Type{TypeWithZero}) = TypeWithZero
Base.zero(::Type{<:Union{TypeWithoutZero, TypeWithZero}}) = TypeWithZero()
Base.:+(x::TypeWithZero, ::TypeWithoutZero) = x
@testset "diagm for type with no zero" begin
@test diagm(0 => [TypeWithoutZero()]) isa Matrix{TypeWithZero}
end
end # module TestDense
| 40.854027
| 143
| 0.505524
|
[
"@testset \"Check that non-floats are correctly promoted\" begin\n @test [1 0 0; 0 1 0]\\[1,1] ≈ [1;1;0]\nend",
"@testset \"Matrix condition number\" begin\n ainit = rand(n,n)\n @testset \"for $elty\" for elty in (Float32, Float64, ComplexF32, ComplexF64)\n ainit = convert(Matrix{elty}, ainit)\n for a in (copy(ainit), view(ainit, 1:n, 1:n))\n @test cond(a,1) ≈ 4.837320054554436e+02 atol=0.01\n @test cond(a,2) ≈ 1.960057871514615e+02 atol=0.01\n @test cond(a,Inf) ≈ 3.757017682707787e+02 atol=0.01\n @test cond(a[:,1:5]) ≈ 10.233059337453463 atol=0.01\n @test_throws ArgumentError cond(a,3)\n end\n end\n @testset \"Singular matrices\" for p in (1, 2, Inf)\n @test cond(zeros(Int, 2, 2), p) == Inf\n @test cond(zeros(2, 2), p) == Inf\n @test cond([0 0; 1 1], p) == Inf\n @test cond([0. 0.; 1. 1.], p) == Inf\n end\n @testset \"Issue #33547, condition number of 2x2 matrix\" begin\n M = [1.0 -2.0; -2.0 -1.5]\n @test cond(M, 1) ≈ 2.227272727272727\n end\nend",
"@testset \"For A containing $eltya\" for eltya in (Float32, Float64, ComplexF32, ComplexF64, Int)\n ainit = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(areal, aimg) : areal)\n ainit2 = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(a2real, a2img) : a2real)\n ε = εa = eps(abs(float(one(eltya))))\n\n apd = ainit'*ainit # symmetric positive-definite\n @testset \"Positive definiteness\" begin\n @test !isposdef(ainit)\n @test isposdef(apd)\n if eltya != Int # cannot perform cholesky! for Matrix{Int}\n @test !isposdef!(copy(ainit))\n @test isposdef!(copy(apd))\n end\n end\n @testset \"For b containing $eltyb\" for eltyb in (Float32, Float64, ComplexF32, ComplexF64, Int)\n binit = eltyb == Int ? rand(1:5, n, 2) : convert(Matrix{eltyb}, eltyb <: Complex ? complex.(breal, bimg) : breal)\n εb = eps(abs(float(one(eltyb))))\n ε = max(εa,εb)\n for (a, b) in ((copy(ainit), copy(binit)), (view(ainit, 1:n, 1:n), view(binit, 1:n, 1:2)))\n @testset \"Solve square general system of equations\" begin\n κ = cond(a,1)\n x = a \\ b\n @test_throws DimensionMismatch b'\\b\n @test_throws DimensionMismatch b\\b'\n @test norm(a*x - b, 1)/norm(b) < ε*κ*n*2 # Ad hoc, revisit!\n @test zeros(eltya,n)\\fill(eltya(1),n) ≈ (zeros(eltya,n,1)\\fill(eltya(1),n,1))[1,1]\n end\n\n @testset \"Test nullspace\" begin\n a15null = nullspace(a[:,1:n1]')\n @test rank([a[:,1:n1] a15null]) == 10\n @test norm(a[:,1:n1]'a15null,Inf) ≈ zero(eltya) atol=300ε\n @test norm(a15null'a[:,1:n1],Inf) ≈ zero(eltya) atol=400ε\n @test size(nullspace(b), 2) == 0\n @test size(nullspace(b, rtol=0.001), 2) == 0\n @test size(nullspace(b, atol=100*εb), 2) == 0\n @test size(nullspace(b, 100*εb), 2) == 0\n @test nullspace(zeros(eltya,n)) == Matrix(I, 1, 1)\n @test nullspace(zeros(eltya,n), 0.1) == Matrix(I, 1, 1)\n # test empty cases\n @test @inferred(nullspace(zeros(n, 0))) == Matrix(I, 0, 0)\n @test @inferred(nullspace(zeros(0, n))) == Matrix(I, n, n)\n # test vector cases\n @test size(@inferred nullspace(a[:, 1])) == (1, 0)\n @test size(@inferred nullspace(zero(a[:, 1]))) == (1, 1)\n @test nullspace(zero(a[:, 1]))[1,1] == 1\n # test adjortrans vectors, including empty ones\n @test size(@inferred nullspace(a[:, 1]')) == (n, n - 1)\n @test @inferred(nullspace(a[1:0, 1]')) == Matrix(I, 0, 0)\n @test size(@inferred nullspace(b[1, :]')) == (2, 1)\n @test @inferred(nullspace(b[1, 1:0]')) == Matrix(I, 0, 0)\n @test size(@inferred nullspace(transpose(a[:, 1]))) == (n, n - 1)\n @test size(@inferred nullspace(transpose(b[1, :]))) == (2, 1)\n end\n end\n end # for eltyb\n\n@testset \"Test diagm for vectors\" begin\n @test diagm(zeros(50)) == diagm(0 => zeros(50))\n @test diagm(ones(50)) == diagm(0 => ones(50))\n v = randn(500)\n @test diagm(v) == diagm(0 => v)\n @test diagm(500, 501, v) == diagm(500, 501, 0 => v)\nend\n\n@testset \"Non-square diagm\" begin\n x = [7, 8]\n for m=1:4, n=2:4\n if m < 2 || n < 3\n @test_throws DimensionMismatch diagm(m,n, 0 => x, 1 => x)\n @test_throws DimensionMismatch diagm(n,m, 0 => x, -1 => x)\n else\n M = zeros(m,n)\n M[1:2,1:3] = [7 7 0; 0 8 8]\n @test diagm(m,n, 0 => x, 1 => x) == M\n @test diagm(n,m, 0 => x, -1 => x) == M'\n end\n end\nend\n\n@testset \"Test pinv (rtol, atol)\" begin\n M = [1 0 0; 0 1 0; 0 0 0]\n @test pinv(M,atol=1)== zeros(3,3)\n @test pinv(M,rtol=0.5)== M\nend\n\n for (a, a2) in ((copy(ainit), copy(ainit2)), (view(ainit, 1:n, 1:n), view(ainit2, 1:n, 1:n)))\n @testset \"Test pinv\" begin\n pinva15 = pinv(a[:,1:n1])\n @test a[:,1:n1]*pinva15*a[:,1:n1] ≈ a[:,1:n1]\n @test pinva15*a[:,1:n1]*pinva15 ≈ pinva15\n pinva15 = pinv(a[:,1:n1]') # the Adjoint case\n @test a[:,1:n1]'*pinva15*a[:,1:n1]' ≈ a[:,1:n1]'\n @test pinva15*a[:,1:n1]'*pinva15 ≈ pinva15\n\n @test size(pinv(Matrix{eltya}(undef,0,0))) == (0,0)\n end\n\n @testset \"Lyapunov/Sylvester\" begin\n x = lyap(a, a2)\n @test -a2 ≈ a*x + x*a'\n x2 = sylvester(a[1:3, 1:3], a[4:n, 4:n], a2[1:3,4:n])\n @test -a2[1:3, 4:n] ≈ a[1:3, 1:3]*x2 + x2*a[4:n, 4:n]\n end\n\n @testset \"Matrix square root\" begin\n asq = sqrt(a)\n @test asq*asq ≈ a\n @test sqrt(transpose(a))*sqrt(transpose(a)) ≈ transpose(a)\n @test sqrt(adjoint(a))*sqrt(adjoint(a)) ≈ adjoint(a)\n asym = a + a' # symmetric indefinite\n asymsq = sqrt(asym)\n @test asymsq*asymsq ≈ asym\n @test sqrt(transpose(asym))*sqrt(transpose(asym)) ≈ transpose(asym)\n @test sqrt(adjoint(asym))*sqrt(adjoint(asym)) ≈ adjoint(asym)\n if eltype(a) <: Real # real square root\n apos = a * a\n @test sqrt(apos)^2 ≈ apos\n @test eltype(sqrt(apos)) <: Real\n # test that real but Complex input produces Complex output\n @test sqrt(complex(apos)) ≈ sqrt(apos)\n @test eltype(sqrt(complex(apos))) <: Complex\n end\n end\n\n @testset \"Powers\" begin\n if eltya <: AbstractFloat\n z = zero(eltya)\n t = convert(eltya,2)\n r = convert(eltya,2.5)\n @test a^z ≈ Matrix(I, size(a))\n @test a^t ≈ a^2\n @test Matrix{eltya}(I, n, n)^r ≈ Matrix(I, size(a))\n end\n end\n end # end for loop over arraytype\n\n @testset \"Factorize\" begin\n d = rand(eltya,n)\n e = rand(eltya,n-1)\n e2 = rand(eltya,n-1)\n f = rand(eltya,n-2)\n A = diagm(0 => d)\n @test factorize(A) == Diagonal(d)\n A += diagm(-1 => e)\n @test factorize(A) == Bidiagonal(d,e,:L)\n A += diagm(-2 => f)\n @test factorize(A) == LowerTriangular(A)\n A = diagm(0 => d, 1 => e)\n @test factorize(A) == Bidiagonal(d,e,:U)\n if eltya <: Real\n A = diagm(0 => d, 1 => e, -1 => e)\n @test Matrix(factorize(A)) ≈ Matrix(factorize(SymTridiagonal(d,e)))\n A = diagm(0 => d, 1 => e, -1 => e, 2 => f, -2 => f)\n @test inv(factorize(A)) ≈ inv(factorize(Symmetric(A)))\n end\n A = diagm(0 => d, 1 => e, -1 => e2)\n @test Matrix(factorize(A)) ≈ Matrix(factorize(Tridiagonal(e2,d,e)))\n A = diagm(0 => d, 1 => e, 2 => f)\n @test factorize(A) == UpperTriangular(A)\n end\nend",
"@testset \"test out of bounds triu/tril\" begin\n local m, n = 5, 7\n ainit = rand(m, n)\n for a in (copy(ainit), view(ainit, 1:m, 1:n))\n @test triu(a, -m) == a\n @test triu(a, n + 2) == zero(a)\n @test tril(a, -m - 2) == zero(a)\n @test tril(a, n) == a\n end\nend",
"@testset \"triu M > N case bug fix\" begin\n mat=[1 2;\n 3 4;\n 5 6;\n 7 8]\n res=[1 2;\n 3 4;\n 0 6;\n 0 0]\n @test triu(mat, -1) == res\nend",
"@testset \"Tests norms\" begin\n nnorm = 10\n mmat = 10\n nmat = 8\n @testset \"For $elty\" for elty in (Float32, Float64, BigFloat, ComplexF32, ComplexF64, Complex{BigFloat}, Int32, Int64, BigInt)\n x = fill(elty(1),10)\n @testset \"Vector\" begin\n xs = view(x,1:2:10)\n @test norm(x, -Inf) ≈ 1\n @test norm(x, -1) ≈ 1/10\n @test norm(x, 0) ≈ 10\n @test norm(x, 1) ≈ 10\n @test norm(x, 2) ≈ sqrt(10)\n @test norm(x, 3) ≈ cbrt(10)\n @test norm(x, Inf) ≈ 1\n if elty <: LinearAlgebra.BlasFloat\n @test norm(x, 1:4) ≈ 2\n @test_throws BoundsError norm(x,-1:4)\n @test_throws BoundsError norm(x,1:11)\n end\n @test norm(xs, -Inf) ≈ 1\n @test norm(xs, -1) ≈ 1/5\n @test norm(xs, 0) ≈ 5\n @test norm(xs, 1) ≈ 5\n @test norm(xs, 2) ≈ sqrt(5)\n @test norm(xs, 3) ≈ cbrt(5)\n @test norm(xs, Inf) ≈ 1\n end\n\n @testset \"Issue #12552:\" begin\n if real(elty) <: AbstractFloat\n for p in [-Inf,-1,1,2,3,Inf]\n @test isnan(norm(elty[0,NaN],p))\n @test isnan(norm(elty[NaN,0],p))\n end\n end\n end\n\n @testset \"Number\" begin\n norm(x[1:1]) === norm(x[1], -Inf)\n norm(x[1:1]) === norm(x[1], 0)\n norm(x[1:1]) === norm(x[1], 1)\n norm(x[1:1]) === norm(x[1], 2)\n norm(x[1:1]) === norm(x[1], Inf)\n end\n\n @testset \"Absolute homogeneity, triangle inequality, & vectorized versions\" begin\n for i = 1:10\n xinit = elty <: Integer ? convert(Vector{elty}, rand(1:10, nnorm)) :\n elty <: Complex ? convert(Vector{elty}, complex.(randn(nnorm), randn(nnorm))) :\n convert(Vector{elty}, randn(nnorm))\n yinit = elty <: Integer ? convert(Vector{elty}, rand(1:10, nnorm)) :\n elty <: Complex ? convert(Vector{elty}, complex.(randn(nnorm), randn(nnorm))) :\n convert(Vector{elty}, randn(nnorm))\n α = elty <: Integer ? randn() :\n elty <: Complex ? convert(elty, complex(randn(),randn())) :\n convert(elty, randn())\n for (x, y) in ((copy(xinit), copy(yinit)), (view(xinit,1:2:nnorm), view(yinit,1:2:nnorm)))\n # Absolute homogeneity\n @test norm(α*x,-Inf) ≈ abs(α)*norm(x,-Inf)\n @test norm(α*x,-1) ≈ abs(α)*norm(x,-1)\n @test norm(α*x,1) ≈ abs(α)*norm(x,1)\n @test norm(α*x) ≈ abs(α)*norm(x) # two is default\n @test norm(α*x,3) ≈ abs(α)*norm(x,3)\n @test norm(α*x,Inf) ≈ abs(α)*norm(x,Inf)\n\n # Triangle inequality\n @test norm(x + y,1) <= norm(x,1) + norm(y,1)\n @test norm(x + y) <= norm(x) + norm(y) # two is default\n @test norm(x + y,3) <= norm(x,3) + norm(y,3)\n @test norm(x + y,Inf) <= norm(x,Inf) + norm(y,Inf)\n\n # Against vectorized versions\n @test norm(x,-Inf) ≈ minimum(abs.(x))\n @test norm(x,-1) ≈ inv(sum(1 ./ abs.(x)))\n @test norm(x,0) ≈ sum(x .!= 0)\n @test norm(x,1) ≈ sum(abs.(x))\n @test norm(x) ≈ sqrt(sum(abs2.(x)))\n @test norm(x,3) ≈ cbrt(sum(abs.(x).^3.))\n @test norm(x,Inf) ≈ maximum(abs.(x))\n end\n end\n end\n\n @testset \"Matrix (Operator) opnorm\" begin\n A = fill(elty(1),10,10)\n As = view(A,1:5,1:5)\n @test opnorm(A, 1) ≈ 10\n elty <: Union{BigFloat,Complex{BigFloat},BigInt} || @test opnorm(A, 2) ≈ 10\n @test opnorm(A, Inf) ≈ 10\n @test opnorm(As, 1) ≈ 5\n elty <: Union{BigFloat,Complex{BigFloat},BigInt} || @test opnorm(As, 2) ≈ 5\n @test opnorm(As, Inf) ≈ 5\n end\n\n @testset \"Absolute homogeneity, triangle inequality, & norm\" begin\n for i = 1:10\n Ainit = elty <: Integer ? convert(Matrix{elty}, rand(1:10, mmat, nmat)) :\n elty <: Complex ? convert(Matrix{elty}, complex.(randn(mmat, nmat), randn(mmat, nmat))) :\n convert(Matrix{elty}, randn(mmat, nmat))\n Binit = elty <: Integer ? convert(Matrix{elty}, rand(1:10, mmat, nmat)) :\n elty <: Complex ? convert(Matrix{elty}, complex.(randn(mmat, nmat), randn(mmat, nmat))) :\n convert(Matrix{elty}, randn(mmat, nmat))\n α = elty <: Integer ? randn() :\n elty <: Complex ? convert(elty, complex(randn(),randn())) :\n convert(elty, randn())\n for (A, B) in ((copy(Ainit), copy(Binit)), (view(Ainit,1:nmat,1:nmat), view(Binit,1:nmat,1:nmat)))\n # Absolute homogeneity\n @test norm(α*A,1) ≈ abs(α)*norm(A,1)\n elty <: Union{BigFloat,Complex{BigFloat},BigInt} || @test norm(α*A) ≈ abs(α)*norm(A) # two is default\n @test norm(α*A,Inf) ≈ abs(α)*norm(A,Inf)\n\n # Triangle inequality\n @test norm(A + B,1) <= norm(A,1) + norm(B,1)\n elty <: Union{BigFloat,Complex{BigFloat},BigInt} || @test norm(A + B) <= norm(A) + norm(B) # two is default\n @test norm(A + B,Inf) <= norm(A,Inf) + norm(B,Inf)\n\n # norm\n for p in (-Inf, Inf, (-2:3)...)\n @test norm(A, p) == norm(vec(A), p)\n end\n end\n end\n\n @testset \"issue #10234\" begin\n if elty <: AbstractFloat || elty <: Complex\n z = zeros(elty, 100)\n z[1] = -Inf\n for p in [-2,-1.5,-1,-0.5,0.5,1,1.5,2,Inf]\n @test norm(z, p) == (p < 0 ? 0 : Inf)\n @test norm(elty[Inf],p) == Inf\n end\n end\n end\n end\n end\n\n @testset \"issue #10234\" begin\n @test norm(Any[Inf],-2) == norm(Any[Inf],-1) == norm(Any[Inf],1) == norm(Any[Inf],1.5) == norm(Any[Inf],2) == norm(Any[Inf],Inf) == Inf\n end\n\n @testset \"overflow/underflow in norms\" begin\n @test norm(Float64[1e-300, 1], -3)*1e300 ≈ 1\n @test norm(Float64[1e300, 1], 3)*1e-300 ≈ 1\n end\nend",
"@testset \"issue #1447\" begin\n A = [1.0+0.0im 0; 0 1]\n B = pinv(A)\n for i = 1:4\n @test A[i] ≈ B[i]\n end\nend",
"@testset \"issue #2246\" begin\n A = [1 2 0 0; 0 1 0 0; 0 0 0 0; 0 0 0 0]\n Asq = sqrt(A)\n @test Asq*Asq ≈ A\n A2 = view(A, 1:2, 1:2)\n A2sq = sqrt(A2)\n @test A2sq*A2sq ≈ A2\n\n N = 3\n @test log(det(Matrix(1.0I, N, N))) ≈ logdet(Matrix(1.0I, N, N))\nend",
"@testset \"issue #2637\" begin\n a = [1, 2, 3]\n b = [4, 5, 6]\n @test kron(Matrix(I, 2, 2), Matrix(I, 2, 2)) == Matrix(I, 4, 4)\n @test kron(a,b) == [4,5,6,8,10,12,12,15,18]\n @test kron(a',b') == [4 5 6 8 10 12 12 15 18]\n @test kron(a,b') == [4 5 6; 8 10 12; 12 15 18]\n @test kron(a',b) == [4 8 12; 5 10 15; 6 12 18]\n @test kron(a, Matrix(1I, 2, 2)) == [1 0; 0 1; 2 0; 0 2; 3 0; 0 3]\n @test kron(Matrix(1I, 2, 2), a) == [ 1 0; 2 0; 3 0; 0 1; 0 2; 0 3]\n @test kron(Matrix(1I, 2, 2), 2) == Matrix(2I, 2, 2)\n @test kron(3, Matrix(1I, 3, 3)) == Matrix(3I, 3, 3)\n @test kron(a,2) == [2, 4, 6]\n @test kron(b',2) == [8 10 12]\nend",
"@testset \"kron!\" begin\n a = [1.0, 0.0]\n b = [0.0, 1.0]\n @test kron!([1.0, 0.0], b, 0.5) == [0.0; 0.5]\n @test kron!([1.0, 0.0], 0.5, b) == [0.0; 0.5]\n c = Vector{Float64}(undef, 4)\n kron!(c, a, b)\n @test c == [0.0; 1.0; 0.0; 0.0]\n c = Matrix{Float64}(undef, 2, 2)\n kron!(c, a, b')\n @test c == [0.0 1.0; 0.0 0.0]\nend",
"@testset \"kron adjoint\" begin\n a = [1+im, 2, 3]\n b = [4, 5, 6+7im]\n @test kron(a', b') isa Adjoint\n @test kron(a', b') == kron(a, b)'\n @test kron(transpose(a), b') isa Transpose\n @test kron(transpose(a), b') == kron(permutedims(a), collect(b'))\n @test kron(transpose(a), transpose(b)) isa Transpose\n @test kron(transpose(a), transpose(b)) == transpose(kron(a, b))\nend",
"@testset \"issue #4796\" begin\n dim=2\n S=zeros(Complex,dim,dim)\n T=zeros(Complex,dim,dim)\n fill!(T, 1)\n z = 2.5 + 1.5im\n S[1] = z\n @test S*T == [z z; 0 0]\n\n # similar issue for Array{Real}\n @test Real[1 2] * Real[1.5; 2.0] == Real[5.5]\nend",
"@testset \"Matrix exponential\" begin\n @testset \"Tests for $elty\" for elty in (Float32, Float64, ComplexF32, ComplexF64)\n A1 = convert(Matrix{elty}, [4 2 0; 1 4 1; 1 1 4])\n eA1 = convert(Matrix{elty}, [147.866622446369 127.781085523181 127.781085523182;\n 183.765138646367 183.765138646366 163.679601723179;\n 71.797032399996 91.8825693231832 111.968106246371]')\n @test exp(A1) ≈ eA1\n @test exp(adjoint(A1)) ≈ adjoint(eA1)\n @test exp(transpose(A1)) ≈ transpose(eA1)\n for f in (sin, cos, sinh, cosh, tanh, tan)\n @test f(adjoint(A1)) ≈ f(copy(adjoint(A1)))\n end\n\n A2 = convert(Matrix{elty},\n [29.87942128909879 0.7815750847907159 -2.289519314033932;\n 0.7815750847907159 25.72656945571064 8.680737820540137;\n -2.289519314033932 8.680737820540137 34.39400925519054])\n eA2 = convert(Matrix{elty},\n [ 5496313853692458.0 -18231880972009236.0 -30475770808580460.0;\n -18231880972009252.0 60605228702221920.0 101291842930249760.0;\n -30475770808580480.0 101291842930249728.0 169294411240851968.0])\n @test exp(A2) ≈ eA2\n @test exp(adjoint(A2)) ≈ adjoint(eA2)\n @test exp(transpose(A2)) ≈ transpose(eA2)\n\n A3 = convert(Matrix{elty}, [-131 19 18;-390 56 54;-387 57 52])\n eA3 = convert(Matrix{elty}, [-1.50964415879218 -5.6325707998812 -4.934938326092;\n 0.367879439109187 1.47151775849686 1.10363831732856;\n 0.135335281175235 0.406005843524598 0.541341126763207]')\n @test exp(A3) ≈ eA3\n @test exp(adjoint(A3)) ≈ adjoint(eA3)\n @test exp(transpose(A3)) ≈ transpose(eA3)\n\n A4 = convert(Matrix{elty}, [0.25 0.25; 0 0])\n eA4 = convert(Matrix{elty}, [1.2840254166877416 0.2840254166877415; 0 1])\n @test exp(A4) ≈ eA4\n @test exp(adjoint(A4)) ≈ adjoint(eA4)\n @test exp(transpose(A4)) ≈ transpose(eA4)\n\n A5 = convert(Matrix{elty}, [0 0.02; 0 0])\n eA5 = convert(Matrix{elty}, [1 0.02; 0 1])\n @test exp(A5) ≈ eA5\n @test exp(adjoint(A5)) ≈ adjoint(eA5)\n @test exp(transpose(A5)) ≈ transpose(eA5)\n\n # Hessenberg\n @test hessenberg(A1).H ≈ convert(Matrix{elty},\n [4.000000000000000 -1.414213562373094 -1.414213562373095\n -1.414213562373095 4.999999999999996 -0.000000000000000\n 0 -0.000000000000002 3.000000000000000])\n\n # cis always returns a complex matrix\n if elty <: Real\n eltyim = Complex{elty}\n else\n eltyim = elty\n end\n\n @test cis(A1) ≈ convert(Matrix{eltyim}, [-0.339938 + 0.000941506im 0.772659 - 0.8469im 0.52745 + 0.566543im;\n 0.650054 - 0.140179im -0.0762135 + 0.284213im 0.38633 - 0.42345im ;\n 0.650054 - 0.140179im 0.913779 + 0.143093im -0.603663 - 0.28233im ]) rtol=7e-7\n end\n\n @testset \"Additional tests for $elty\" for elty in (Float64, ComplexF64)\n A4 = convert(Matrix{elty}, [1/2 1/3 1/4 1/5+eps();\n 1/3 1/4 1/5 1/6;\n 1/4 1/5 1/6 1/7;\n 1/5 1/6 1/7 1/8])\n @test exp(log(A4)) ≈ A4\n @test exp(log(transpose(A4))) ≈ transpose(A4)\n @test exp(log(adjoint(A4))) ≈ adjoint(A4)\n\n A5 = convert(Matrix{elty}, [1 1 0 1; 0 1 1 0; 0 0 1 1; 1 0 0 1])\n @test exp(log(A5)) ≈ A5\n @test exp(log(transpose(A5))) ≈ transpose(A5)\n @test exp(log(adjoint(A5))) ≈ adjoint(A5)\n\n A6 = convert(Matrix{elty}, [-5 2 0 0 ; 1/2 -7 3 0; 0 1/3 -9 4; 0 0 1/4 -11])\n @test exp(log(A6)) ≈ A6\n @test exp(log(transpose(A6))) ≈ transpose(A6)\n @test exp(log(adjoint(A6))) ≈ adjoint(A6)\n\n A7 = convert(Matrix{elty}, [1 0 0 1e-8; 0 1 0 0; 0 0 1 0; 0 0 0 1])\n @test exp(log(A7)) ≈ A7\n @test exp(log(transpose(A7))) ≈ transpose(A7)\n @test exp(log(adjoint(A7))) ≈ adjoint(A7)\n end\n\n @testset \"Integer promotion tests\" begin\n for (elty1, elty2) in ((Int64, Float64), (Complex{Int64}, ComplexF64))\n A4int = convert(Matrix{elty1}, [1 2; 3 4])\n A4float = convert(Matrix{elty2}, A4int)\n @test exp(A4int) == exp(A4float)\n end\n end\n\n @testset \"^ tests\" for elty in (Float32, Float64, ComplexF32, ComplexF64, Int32, Int64)\n # should all be exact as the lhs functions are simple aliases\n @test ℯ^(fill(elty(2), (4,4))) == exp(fill(elty(2), (4,4)))\n @test 2^(fill(elty(2), (4,4))) == exp(log(2)*fill(elty(2), (4,4)))\n @test 2.0^(fill(elty(2), (4,4))) == exp(log(2.0)*fill(elty(2), (4,4)))\n end\n\n A8 = 100 * [-1+1im 0 0 1e-8; 0 1 0 0; 0 0 1 0; 0 0 0 1]\n @test exp(log(A8)) ≈ A8\nend",
"@testset \"Matrix trigonometry\" begin\n @testset \"Tests for $elty\" for elty in (Float32, Float64, ComplexF32, ComplexF64)\n A1 = convert(Matrix{elty}, [3 2 0; 1 3 1; 1 1 3])\n A2 = convert(Matrix{elty},\n [3.975884257819758 0.15631501695814318 -0.4579038628067864;\n 0.15631501695814318 4.545313891142127 1.7361475641080275;\n -0.4579038628067864 1.7361475641080275 6.478801851038108])\n A3 = convert(Matrix{elty}, [0.25 0.25; 0 0])\n A4 = convert(Matrix{elty}, [0 0.02; 0 0])\n\n cosA1 = convert(Matrix{elty},[-0.18287716254368605 -0.29517205254584633 0.761711400552759;\n 0.23326967400345625 0.19797853773269333 -0.14758602627292305;\n 0.23326967400345636 0.6141253742798355 -0.5637328628200653])\n sinA1 = convert(Matrix{elty}, [0.2865568596627417 -1.107751980582015 -0.13772915374386513;\n -0.6227405671629401 0.2176922827908092 -0.5538759902910078;\n -0.6227405671629398 -0.6916051440348725 0.3554214365346742])\n @test cos(A1) ≈ cosA1\n @test sin(A1) ≈ sinA1\n\n cosA2 = convert(Matrix{elty}, [-0.6331745163802187 0.12878366262380136 -0.17304181968301532;\n 0.12878366262380136 -0.5596234510748788 0.5210483146041339;\n -0.17304181968301532 0.5210483146041339 0.002263776356015268])\n sinA2 = convert(Matrix{elty},[-0.6677253518411841 -0.32599318928375437 0.020799609079003523;\n -0.32599318928375437 -0.04568726058081066 0.5388748740270427;\n 0.020799609079003523 0.5388748740270427 0.6385462428126032])\n @test cos(A2) ≈ cosA2\n @test sin(A2) ≈ sinA2\n\n cosA3 = convert(Matrix{elty}, [0.9689124217106446 -0.031087578289355197; 0.0 1.0])\n sinA3 = convert(Matrix{elty}, [0.24740395925452285 0.24740395925452285; 0.0 0.0])\n @test cos(A3) ≈ cosA3\n @test sin(A3) ≈ sinA3\n\n cosA4 = convert(Matrix{elty}, [1.0 0.0; 0.0 1.0])\n sinA4 = convert(Matrix{elty}, [0.0 0.02; 0.0 0.0])\n @test cos(A4) ≈ cosA4\n @test sin(A4) ≈ sinA4\n\n # Identities\n for (i, A) in enumerate((A1, A2, A3, A4))\n @test sincos(A) == (sin(A), cos(A))\n @test cos(A)^2 + sin(A)^2 ≈ Matrix(I, size(A))\n @test cos(A) ≈ cos(-A)\n @test sin(A) ≈ -sin(-A)\n @test tan(A) ≈ sin(A) / cos(A)\n\n @test cos(A) ≈ real(exp(im*A))\n @test sin(A) ≈ imag(exp(im*A))\n @test cos(A) ≈ real(cis(A))\n @test sin(A) ≈ imag(cis(A))\n @test cis(A) ≈ cos(A) + im * sin(A)\n\n @test cosh(A) ≈ 0.5 * (exp(A) + exp(-A))\n @test sinh(A) ≈ 0.5 * (exp(A) - exp(-A))\n @test cosh(A) ≈ cosh(-A)\n @test sinh(A) ≈ -sinh(-A)\n\n # Some of the following identities fail for A3, A4 because the matrices are singular\n if i in (1, 2)\n @test sec(A) ≈ inv(cos(A))\n @test csc(A) ≈ inv(sin(A))\n @test cot(A) ≈ inv(tan(A))\n @test sech(A) ≈ inv(cosh(A))\n @test csch(A) ≈ inv(sinh(A))\n @test coth(A) ≈ inv(tanh(A))\n end\n # The following identities fail for A1, A2 due to rounding errors;\n # probably needs better algorithm for the general case\n if i in (3, 4)\n @test cosh(A)^2 - sinh(A)^2 ≈ Matrix(I, size(A))\n @test tanh(A) ≈ sinh(A) / cosh(A)\n end\n end\n end\n\n @testset \"Additional tests for $elty\" for elty in (ComplexF32, ComplexF64)\n A5 = convert(Matrix{elty}, [1im 2; 0.02+0.5im 3])\n\n @test sincos(A5) == (sin(A5), cos(A5))\n\n @test cos(A5)^2 + sin(A5)^2 ≈ Matrix(I, size(A5))\n @test cosh(A5)^2 - sinh(A5)^2 ≈ Matrix(I, size(A5))\n @test cos(A5)^2 + sin(A5)^2 ≈ Matrix(I, size(A5))\n @test tan(A5) ≈ sin(A5) / cos(A5)\n @test tanh(A5) ≈ sinh(A5) / cosh(A5)\n\n @test sec(A5) ≈ inv(cos(A5))\n @test csc(A5) ≈ inv(sin(A5))\n @test cot(A5) ≈ inv(tan(A5))\n @test sech(A5) ≈ inv(cosh(A5))\n @test csch(A5) ≈ inv(sinh(A5))\n @test coth(A5) ≈ inv(tanh(A5))\n\n @test cos(A5) ≈ 0.5 * (exp(im*A5) + exp(-im*A5))\n @test sin(A5) ≈ -0.5im * (exp(im*A5) - exp(-im*A5))\n @test cos(A5) ≈ 0.5 * (cis(A5) + cis(-A5))\n @test sin(A5) ≈ -0.5im * (cis(A5) - cis(-A5))\n\n @test cosh(A5) ≈ 0.5 * (exp(A5) + exp(-A5))\n @test sinh(A5) ≈ 0.5 * (exp(A5) - exp(-A5))\n end\n\n @testset \"Additional tests for $elty\" for elty in (Int32, Int64, Complex{Int32}, Complex{Int64})\n A1 = convert(Matrix{elty}, [1 2; 3 4])\n A2 = convert(Matrix{elty}, [1 2; 2 1])\n\n cosA1 = convert(Matrix{float(elty)}, [0.855423165077998 -0.11087638101074865;\n -0.16631457151612294 0.689108593561875])\n cosA2 = convert(Matrix{float(elty)}, [-0.22484509536615283 -0.7651474012342925;\n -0.7651474012342925 -0.22484509536615283])\n\n @test cos(A1) ≈ cosA1\n @test cos(A2) ≈ cosA2\n\n sinA1 = convert(Matrix{float(elty)}, [-0.46558148631373036 -0.14842445991317652;\n -0.22263668986976476 -0.6882181761834951])\n sinA2 = convert(Matrix{float(elty)}, [-0.3501754883740146 0.4912954964338818;\n 0.4912954964338818 -0.3501754883740146])\n\n @test sin(A1) ≈ sinA1\n @test sin(A2) ≈ sinA2\n end\n\n @testset \"Inverse functions for $elty\" for elty in (Float32, Float64)\n A1 = convert(Matrix{elty}, [0.244637 -0.63578;\n 0.22002 0.189026])\n A2 = convert(Matrix{elty}, [1.11656 -0.098672 0.158485;\n -0.098672 0.100933 -0.107107;\n 0.158485 -0.107107 0.612404])\n\n for A in (A1, A2)\n @test cos(acos(cos(A))) ≈ cos(A)\n @test sin(asin(sin(A))) ≈ sin(A)\n @test tan(atan(tan(A))) ≈ tan(A)\n @test cosh(acosh(cosh(A))) ≈ cosh(A)\n @test sinh(asinh(sinh(A))) ≈ sinh(A)\n @test tanh(atanh(tanh(A))) ≈ tanh(A)\n @test sec(asec(sec(A))) ≈ sec(A)\n @test csc(acsc(csc(A))) ≈ csc(A)\n @test cot(acot(cot(A))) ≈ cot(A)\n @test sech(asech(sech(A))) ≈ sech(A)\n @test csch(acsch(csch(A))) ≈ csch(A)\n @test coth(acoth(coth(A))) ≈ coth(A)\n end\n end\n\n @testset \"Inverse functions for $elty\" for elty in (ComplexF32, ComplexF64)\n A1 = convert(Matrix{elty}, [ 0.143721-0.0im -0.138386-0.106905im;\n -0.138386+0.106905im 0.306224-0.0im])\n A2 = convert(Matrix{elty}, [1im 2; 0.02+0.5im 3])\n A3 = convert(Matrix{elty}, [0.138721-0.266836im 0.0971722-0.13715im 0.205046-0.137136im;\n -0.0154974-0.00358254im 0.152163-0.445452im 0.0314575-0.536521im;\n -0.387488+0.0294059im -0.0448773+0.114305im 0.230684-0.275894im])\n for A in (A1, A2, A3)\n @test cos(acos(cos(A))) ≈ cos(A)\n @test sin(asin(sin(A))) ≈ sin(A)\n @test tan(atan(tan(A))) ≈ tan(A)\n @test cosh(acosh(cosh(A))) ≈ cosh(A)\n @test sinh(asinh(sinh(A))) ≈ sinh(A)\n @test tanh(atanh(tanh(A))) ≈ tanh(A)\n @test sec(asec(sec(A))) ≈ sec(A)\n @test csc(acsc(csc(A))) ≈ csc(A)\n @test cot(acot(cot(A))) ≈ cot(A)\n @test sech(asech(sech(A))) ≈ sech(A)\n @test csch(acsch(csch(A))) ≈ csch(A)\n @test coth(acoth(coth(A))) ≈ coth(A)\n\n # Definition of principal values (Aprahamian & Higham, 2016, pp. 4-5)\n abstol = sqrt(eps(real(elty))) * norm(acosh(A))\n @test all(z -> (0 < real(z) < π ||\n abs(real(z)) < abstol && imag(z) >= 0 ||\n abs(real(z) - π) < abstol && imag(z) <= 0),\n eigen(acos(A)).values)\n @test all(z -> (-π/2 < real(z) < π/2 ||\n abs(real(z) + π/2) < abstol && imag(z) >= 0 ||\n abs(real(z) - π/2) < abstol && imag(z) <= 0),\n eigen(asin(A)).values)\n @test all(z -> (-π < imag(z) < π && real(z) > 0 ||\n 0 <= imag(z) < π && abs(real(z)) < abstol ||\n abs(imag(z) - π) < abstol && real(z) >= 0),\n eigen(acosh(A)).values)\n @test all(z -> (-π/2 < imag(z) < π/2 ||\n abs(imag(z) + π/2) < abstol && real(z) <= 0 ||\n abs(imag(z) - π/2) < abstol && real(z) <= 0),\n eigen(asinh(A)).values)\n end\n end\nend",
"@testset \"issue 5116\" begin\n A9 = [0 10 0 0; -1 0 0 0; 0 0 0 0; -2 0 0 0]\n eA9 = [-0.999786072879326 -0.065407069689389 0.0 0.0\n 0.006540706968939 -0.999786072879326 0.0 0.0\n 0.0 0.0 1.0 0.0\n 0.013081413937878 -3.999572145758650 0.0 1.0]\n @test exp(A9) ≈ eA9\n\n A10 = [ 0. 0. 0. 0. ; 0. 0. -im 0.; 0. im 0. 0.; 0. 0. 0. 0.]\n eA10 = [ 1.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im\n 0.0+0.0im 1.543080634815244+0.0im 0.0-1.175201193643801im 0.0+0.0im\n 0.0+0.0im 0.0+1.175201193643801im 1.543080634815243+0.0im 0.0+0.0im\n 0.0+0.0im 0.0+0.0im 0.0+0.0im 1.0+0.0im]\n @test exp(A10) ≈ eA10\nend",
"@testset \"Additional matrix logarithm tests\" for elty in (Float64, ComplexF64)\n A11 = convert(Matrix{elty}, [3 2; -5 -3])\n @test exp(log(A11)) ≈ A11\n\n A13 = convert(Matrix{elty}, [2 0; 0 2])\n @test typeof(log(A13)) == Array{elty, 2}\n\n T = elty == Float64 ? Symmetric : Hermitian\n @test typeof(log(T(A13))) == T{elty, Array{elty, 2}}\n\n A1 = convert(Matrix{elty}, [4 2 0; 1 4 1; 1 1 4])\n logA1 = convert(Matrix{elty}, [1.329661349 0.5302876358 -0.06818951543;\n 0.2310490602 1.295566591 0.2651438179;\n 0.2310490602 0.1969543025 1.363756107])\n @test log(A1) ≈ logA1\n @test exp(log(A1)) ≈ A1\n @test typeof(log(A1)) == Matrix{elty}\n\n A4 = convert(Matrix{elty}, [1/2 1/3 1/4 1/5+eps();\n 1/3 1/4 1/5 1/6;\n 1/4 1/5 1/6 1/7;\n 1/5 1/6 1/7 1/8])\n logA4 = convert(Matrix{elty}, [-1.73297159 1.857349738 0.4462766564 0.2414170219;\n 1.857349738 -5.335033737 2.994142974 0.5865285289;\n 0.4462766564 2.994142974 -7.351095988 3.318413247;\n 0.2414170219 0.5865285289 3.318413247 -5.444632124])\n @test log(A4) ≈ logA4\n @test exp(log(A4)) ≈ A4\n @test typeof(log(A4)) == Matrix{elty}\n\n # real triu matrix\n A5 = convert(Matrix{elty}, [1 2 3; 0 4 5; 0 0 6]) # triu\n logA5 = convert(Matrix{elty}, [0.0 0.9241962407465937 0.5563245488984037;\n 0.0 1.3862943611198906 1.0136627702704109;\n 0.0 0.0 1.791759469228055])\n @test log(A5) ≈ logA5\n @test exp(log(A5)) ≈ A5\n @test typeof(log(A5)) == Matrix{elty}\n\n # real quasitriangular schur form with 2 2x2 blocks, 2 1x1 blocks, and all positive eigenvalues\n A6 = convert(Matrix{elty}, [2 3 2 2 3 1;\n 1 3 3 2 3 1;\n 3 3 3 1 1 2;\n 2 1 2 2 2 2;\n 1 1 2 2 3 1;\n 2 2 2 2 1 3])\n @test exp(log(A6)) ≈ A6\n @test typeof(log(A6)) == Matrix{elty}\n\n # real quasitriangular schur form with a negative eigenvalue\n A7 = convert(Matrix{elty}, [1 3 3 2 2 2;\n 1 2 1 3 1 2;\n 3 1 2 3 2 1;\n 3 1 2 2 2 1;\n 3 1 3 1 2 1;\n 1 1 3 1 1 3])\n @test exp(log(A7)) ≈ A7\n @test typeof(log(A7)) == Matrix{complex(elty)}\n\n if elty <: Complex\n A8 = convert(Matrix{elty}, [1 + 1im 1 + 1im 1 - 1im;\n 1 + 1im -1 + 1im 1 + 1im;\n 1 - 1im 1 + 1im -1 - 1im])\n logA8 = convert(\n Matrix{elty},\n [0.9478628953131517 + 1.3725201223387407im -0.2547157147532057 + 0.06352318334299434im 0.8560050197863862 - 1.0471975511965979im;\n -0.2547157147532066 + 0.06352318334299467im -0.16285783922644065 + 0.2617993877991496im 0.2547157147532063 + 2.1579182857361894im;\n 0.8560050197863851 - 1.0471975511965974im 0.25471571475320665 + 2.1579182857361903im 0.9478628953131519 - 0.8489213467404436im],\n )\n @test log(A8) ≈ logA8\n @test exp(log(A8)) ≈ A8\n @test typeof(log(A8)) == Matrix{elty}\n end\nend",
"@testset \"matrix logarithm is type-inferrable\" for elty in (Float32,Float64,ComplexF32,ComplexF64)\n A1 = randn(elty, 4, 4)\n @inferred Union{Matrix{elty},Matrix{complex(elty)}} log(A1)\nend",
"@testset \"Additional matrix square root tests\" for elty in (Float64, ComplexF64)\n A11 = convert(Matrix{elty}, [3 2; -5 -3])\n @test sqrt(A11)^2 ≈ A11\n\n A13 = convert(Matrix{elty}, [2 0; 0 2])\n @test typeof(sqrt(A13)) == Array{elty, 2}\n\n T = elty == Float64 ? Symmetric : Hermitian\n @test typeof(sqrt(T(A13))) == T{elty, Array{elty, 2}}\n\n A1 = convert(Matrix{elty}, [4 2 0; 1 4 1; 1 1 4])\n sqrtA1 = convert(Matrix{elty}, [1.971197119306979 0.5113118387140085 -0.03301921523780871;\n 0.23914631173809942 1.9546875116880718 0.2556559193570036;\n 0.23914631173810008 0.22263670411919556 1.9877067269258815])\n @test sqrt(A1) ≈ sqrtA1\n @test sqrt(A1)^2 ≈ A1\n @test typeof(sqrt(A1)) == Matrix{elty}\n\n A4 = convert(Matrix{elty}, [1/2 1/3 1/4 1/5+eps();\n 1/3 1/4 1/5 1/6;\n 1/4 1/5 1/6 1/7;\n 1/5 1/6 1/7 1/8])\n sqrtA4 = convert(\n Matrix{elty},\n [0.590697761556362 0.3055006800405779 0.19525404749300546 0.14007621469988107;\n 0.30550068004057784 0.2825388389385975 0.21857572599211642 0.17048692323164674;\n 0.19525404749300565 0.21857572599211622 0.21155429252242863 0.18976816626246887;\n 0.14007621469988046 0.17048692323164724 0.1897681662624689 0.20075085592778794],\n )\n @test sqrt(A4) ≈ sqrtA4\n @test sqrt(A4)^2 ≈ A4\n @test typeof(sqrt(A4)) == Matrix{elty}\n\n # real triu matrix\n A5 = convert(Matrix{elty}, [1 2 3; 0 4 5; 0 0 6]) # triu\n sqrtA5 = convert(Matrix{elty}, [1.0 0.6666666666666666 0.6525169217864183;\n 0.0 2.0 1.1237243569579454;\n 0.0 0.0 2.449489742783178])\n @test sqrt(A5) ≈ sqrtA5\n @test sqrt(A5)^2 ≈ A5\n @test typeof(sqrt(A5)) == Matrix{elty}\n\n # real quasitriangular schur form with 2 2x2 blocks, 2 1x1 blocks, and all positive eigenvalues\n A6 = convert(Matrix{elty}, [2 3 2 2 3 1;\n 1 3 3 2 3 1;\n 3 3 3 1 1 2;\n 2 1 2 2 2 2;\n 1 1 2 2 3 1;\n 2 2 2 2 1 3])\n @test sqrt(A6)^2 ≈ A6\n @test typeof(sqrt(A6)) == Matrix{elty}\n\n # real quasitriangular schur form with a negative eigenvalue\n A7 = convert(Matrix{elty}, [1 3 3 2 2 2;\n 1 2 1 3 1 2;\n 3 1 2 3 2 1;\n 3 1 2 2 2 1;\n 3 1 3 1 2 1;\n 1 1 3 1 1 3])\n @test sqrt(A7)^2 ≈ A7\n @test typeof(sqrt(A7)) == Matrix{complex(elty)}\n\n if elty <: Complex\n A8 = convert(Matrix{elty}, [1 + 1im 1 + 1im 1 - 1im;\n 1 + 1im -1 + 1im 1 + 1im;\n 1 - 1im 1 + 1im -1 - 1im])\n sqrtA8 = convert(\n Matrix{elty},\n [1.2559748527474284 + 0.6741878819930323im 0.20910077991005582 + 0.24969165051825476im 0.591784212275146 - 0.6741878819930327im;\n 0.2091007799100553 + 0.24969165051825515im 0.3320953202361413 + 0.2915044496279425im 0.33209532023614136 + 1.0568713143581219im;\n 0.5917842122751455 - 0.674187881993032im 0.33209532023614147 + 1.0568713143581223im 0.7147787526012315 - 0.6323750828833452im],\n )\n @test sqrt(A8) ≈ sqrtA8\n @test sqrt(A8)^2 ≈ A8\n @test typeof(sqrt(A8)) == Matrix{elty}\n end\nend",
"@testset \"issue #40141\" begin\n x = [-1 -eps() 0 0; eps() -1 0 0; 0 0 -1 -eps(); 0 0 eps() -1]\n @test sqrt(x)^2 ≈ x\n\n x2 = [-1 -eps() 0 0; 3eps() -1 0 0; 0 0 -1 -3eps(); 0 0 eps() -1]\n @test sqrt(x2)^2 ≈ x2\n\n x3 = [-1 -eps() 0 0; eps() -1 0 0; 0 0 -1 -eps(); 0 0 eps() Inf]\n @test all(isnan, sqrt(x3))\n\n # test overflow/underflow handled\n x4 = [0 -1e200; 1e200 0]\n @test sqrt(x4)^2 ≈ x4\n\n x5 = [0 -1e-200; 1e-200 0]\n @test sqrt(x5)^2 ≈ x5\n\n x6 = [1.0 1e200; -1e-200 1.0]\n @test sqrt(x6)^2 ≈ x6\nend",
"@testset \"matrix logarithm block diagonal underflow/overflow\" begin\n x1 = [0 -1e200; 1e200 0]\n @test exp(log(x1)) ≈ x1\n\n x2 = [0 -1e-200; 1e-200 0]\n @test exp(log(x2)) ≈ x2\n\n x3 = [1.0 1e200; -1e-200 1.0]\n @test exp(log(x3)) ≈ x3\nend",
"@testset \"issue #7181\" begin\n A = [ 1 5 9\n 2 6 10\n 3 7 11\n 4 8 12 ]\n @test diag(A,-5) == []\n @test diag(A,-4) == []\n @test diag(A,-3) == [4]\n @test diag(A,-2) == [3,8]\n @test diag(A,-1) == [2,7,12]\n @test diag(A, 0) == [1,6,11]\n @test diag(A, 1) == [5,10]\n @test diag(A, 2) == [9]\n @test diag(A, 3) == []\n @test diag(A, 4) == []\n\n @test diag(zeros(0,0)) == []\n @test diag(zeros(0,0),1) == []\n @test diag(zeros(0,0),-1) == []\n\n @test diag(zeros(1,0)) == []\n @test diag(zeros(1,0),-1) == []\n @test diag(zeros(1,0),1) == []\n @test diag(zeros(1,0),-2) == []\n\n @test diag(zeros(0,1)) == []\n @test diag(zeros(0,1),1) == []\n @test diag(zeros(0,1),-1) == []\n @test diag(zeros(0,1),2) == []\nend",
"@testset \"issue #39857\" begin\n @test lyap(1.0+2.0im, 3.0+4.0im) == -1.5 - 2.0im\nend",
"@testset \"Matrix to real power\" for elty in (Float64, ComplexF64)\n# Tests proposed at Higham, Deadman: Testing Matrix Function Algorithms Using Identities, March 2014\n #Aa : only positive real eigenvalues\n Aa = convert(Matrix{elty}, [5 4 2 1; 0 1 -1 -1; -1 -1 3 0; 1 1 -1 2])\n\n #Ab : both positive and negative real eigenvalues\n Ab = convert(Matrix{elty}, [1 2 3; 4 7 1; 2 1 4])\n\n #Ac : complex eigenvalues\n Ac = convert(Matrix{elty}, [5 4 2 1;0 1 -1 -1;-1 -1 3 6;1 1 -1 5])\n\n #Ad : defective Matrix\n Ad = convert(Matrix{elty}, [3 1; 0 3])\n\n #Ah : Hermitian Matrix\n Ah = convert(Matrix{elty}, [3 1; 1 3])\n if elty <: LinearAlgebra.BlasComplex\n Ah += [0 im; -im 0]\n end\n\n #ADi : Diagonal Matrix\n ADi = convert(Matrix{elty}, [3 0; 0 3])\n if elty <: LinearAlgebra.BlasComplex\n ADi += [im 0; 0 im]\n end\n\n for A in (Aa, Ab, Ac, Ad, Ah, ADi)\n @test A^(1/2) ≈ sqrt(A)\n @test A^(-1/2) ≈ inv(sqrt(A))\n @test A^(3/4) ≈ sqrt(A) * sqrt(sqrt(A))\n @test A^(-3/4) ≈ inv(A) * sqrt(sqrt(A))\n @test A^(17/8) ≈ A^2 * sqrt(sqrt(sqrt(A)))\n @test A^(-17/8) ≈ inv(A^2 * sqrt(sqrt(sqrt(A))))\n @test (A^0.2)^5 ≈ A\n @test (A^(2/3))*(A^(1/3)) ≈ A\n @test (A^im)^(-im) ≈ A\n end\nend",
"@testset \"diagonal integer matrix to real power\" begin\n A = Matrix(Diagonal([1, 2, 3]))\n @test A^2.3 ≈ float(A)^2.3\nend",
"@testset \"issue #23366 (Int Matrix to Int power)\" begin\n @testset \"Tests for $elty\" for elty in (Int128, Int16, Int32, Int64, Int8,\n UInt128, UInt16, UInt32, UInt64, UInt8,\n BigInt)\n #@info \"Testing $elty\"\n @test elty[1 1;1 0]^-1 == [0 1; 1 -1]\n @test elty[1 1;1 0]^-2 == [1 -1; -1 2]\n @test (@inferred elty[1 1;1 0]^2) == elty[2 1;1 1]\n I_ = elty[1 0;0 1]\n @test I_^-1 == I_\n if !(elty<:Unsigned)\n @test (@inferred (-I_)^-1) == -I_\n @test (@inferred (-I_)^-2) == I_\n end\n # make sure that type promotion for ^(::Matrix{<:Integer}, ::Integer)\n # is analogous to type promotion for ^(::Integer, ::Integer)\n # e.g. [1 1;1 0]^big(10000) should return Matrix{BigInt}, the same\n # way as 2^big(10000) returns BigInt\n for elty2 = (Int64, BigInt)\n TT = Base.promote_op(^, elty, elty2)\n @test (@inferred elty[1 1;1 0]^elty2(1))::Matrix{TT} == [1 1;1 0]\n end\n end\nend",
"@testset \"Least squares solutions\" begin\n a = [fill(1, 20) 1:20 1:20]\n b = reshape(Matrix(1.0I, 8, 5), 20, 2)\n @testset \"Tests for type $elty\" for elty in (Float32, Float64, ComplexF32, ComplexF64)\n a = convert(Matrix{elty}, a)\n b = convert(Matrix{elty}, b)\n\n # Vector rhs\n x = a[:,1:2]\\b[:,1]\n @test ((a[:,1:2]*x-b[:,1])'*(a[:,1:2]*x-b[:,1]))[1] ≈ convert(elty, 2.546616541353384)\n\n # Matrix rhs\n x = a[:,1:2]\\b\n @test det((a[:,1:2]*x-b)'*(a[:,1:2]*x-b)) ≈ convert(elty, 4.437969924812031)\n\n # Rank deficient\n x = a\\b\n @test det((a*x-b)'*(a*x-b)) ≈ convert(elty, 4.437969924812031)\n\n # Underdetermined minimum norm\n x = convert(Matrix{elty}, [1 0 0; 0 1 -1]) \\ convert(Vector{elty}, [1,1])\n @test x ≈ convert(Vector{elty}, [1, 0.5, -0.5])\n\n # symmetric, positive definite\n @test inv(convert(Matrix{elty}, [6. 2; 2 1])) ≈ convert(Matrix{elty}, [0.5 -1; -1 3])\n\n # symmetric, indefinite\n @test inv(convert(Matrix{elty}, [1. 2; 2 1])) ≈ convert(Matrix{elty}, [-1. 2; 2 -1]/3)\n end\nend",
"@testset \"/ and \\\\ consistency with pinv for vectors\" begin\n @testset \"Tests for type $elty\" for elty in (Float32, Float64, ComplexF32, ComplexF64)\n c = rand(elty, 5)\n r = (elty <: Complex ? adjoint : transpose)(rand(elty, 5))\n cm = rand(elty, 5, 1)\n rm = rand(elty, 1, 5)\n @testset \"dot products\" begin\n test_div_pinv_consistency(r, c)\n test_div_pinv_consistency(rm, c)\n test_div_pinv_consistency(r, cm)\n test_div_pinv_consistency(rm, cm)\n end\n @testset \"outer products\" begin\n test_div_pinv_consistency(c, r)\n test_div_pinv_consistency(cm, rm)\n end\n @testset \"matrix/vector\" begin\n m = rand(5, 5)\n test_ldiv_pinv_consistency(m, c)\n test_rdiv_pinv_consistency(r, m)\n end\n end\nend",
"@testset \"test ops on Numbers for $elty\" for elty in [Float32,Float64,ComplexF32,ComplexF64]\n a = rand(elty)\n @test isposdef(one(elty))\n @test lyap(one(elty),a) == -a/2\nend",
"@testset \"strides\" begin\n a = rand(10)\n b = view(a,2:2:10)\n @test LinearAlgebra.stride1(a) == 1\n @test LinearAlgebra.stride1(b) == 2\nend",
"@testset \"inverse of Adjoint\" begin\n A = randn(n, n)\n\n @test @inferred(inv(A'))*A' ≈ I\n @test @inferred(inv(transpose(A)))*transpose(A) ≈ I\n\n B = complex.(A, randn(n, n))\n\n @test @inferred(inv(B'))*B' ≈ I\n @test @inferred(inv(transpose(B)))*transpose(B) ≈ I\nend",
"@testset \"Factorize fallback for Adjoint/Transpose\" begin\n a = rand(Complex{Int8}, n, n)\n @test Array(transpose(factorize(Transpose(a)))) ≈ Array(factorize(a))\n @test transpose(factorize(transpose(a))) == factorize(a)\n @test Array(adjoint(factorize(Adjoint(a)))) ≈ Array(factorize(a))\n @test adjoint(factorize(adjoint(a))) == factorize(a)\nend",
"@testset \"Matrix log issue #32313\" begin\n for A in ([30 20; -50 -30], [10.0im 0; 0 -10.0im], randn(6,6))\n @test exp(log(A)) ≈ A\n end\nend",
"@testset \"Matrix log PR #33245\" begin\n # edge case for divided difference\n A1 = triu(ones(3,3),1) + diagm([1.0, -2eps()-1im, -eps()+0.75im])\n @test exp(log(A1)) ≈ A1\n # case where no sqrt is needed (s=0)\n A2 = [1.01 0.01 0.01; 0 1.01 0.01; 0 0 1.01]\n @test exp(log(A2)) ≈ A2\nend",
"@testset \"diagm for type with no zero\" begin\n @test diagm(0 => [TypeWithoutZero()]) isa Matrix{TypeWithZero}\nend"
] |
f786fb70e13de65553bb39105d496a5ba9839a83
| 3,294
|
jl
|
Julia
|
test/runtests.jl
|
sid-dey/PBDS.jl
|
d4d1d2af0753c60d7082e24c714734eb3ad5fda6
|
[
"MIT"
] | 13
|
2021-01-05T01:09:19.000Z
|
2022-02-24T03:10:45.000Z
|
test/runtests.jl
|
sid-dey/PBDS.jl
|
d4d1d2af0753c60d7082e24c714734eb3ad5fda6
|
[
"MIT"
] | 1
|
2021-09-03T03:39:30.000Z
|
2021-09-03T03:39:30.000Z
|
test/runtests.jl
|
sid-dey/PBDS.jl
|
d4d1d2af0753c60d7082e24c714734eb3ad5fda6
|
[
"MIT"
] | 1
|
2021-02-27T23:52:02.000Z
|
2021-02-27T23:52:02.000Z
|
using PBDS
using Test
using NBInclude
@testset "Examples" begin
"no_plots" in ARGS && (global const no_plots = true)
PBDS_dir = joinpath(@__DIR__, "..", "examples", "PBDS")
test_notebook = "R7Arm_DynamicMugGrasping"
@testset "$test_notebook" begin
file = string(test_notebook, ".ipynb")
@nbinclude(joinpath(PBDS_dir, file))
@test root.children[end-1].children[3].traj_log.x[end][1] .< 5e-3
robot_coord_rep = ChartRep()
traj = propagate_tasks(xm, vm, root, CM, Time, dt, robot_coord_rep, state, cache,
mugparams; time_dep, log_tasks=true)
@test root.children[end-1].children[3].traj_log.x[end][1] .< 5e-3
println("Finished example ", test_notebook)
end
test_notebooks = ["R1_To_R1PointPositionAttractor",
"R2_To_R1PointDistanceAttractor_S1Damping",
"R2_To_R1PointDistanceAttractor_S1Damping_R1BoxAvoidance",
"R2_To_R1PointDistanceAttractor_S1Damping_R1SphereAvoidance",
"R2_To_R2PointPositionAttractor",
"R3_To_R1PointDistanceAttractor_S2Damping_R1BoxAvoidance",
"R3_To_R1PointDistanceAttractor_S2Damping_R1SphereAvoidance",
"S2_To_R1Attractor_S2Damping_R1ObstacleAvoidance"]
for test_notebook in test_notebooks
@testset "$test_notebook" begin
file = string(test_notebook, ".ipynb")
@nbinclude(joinpath(PBDS_dir, file))
ε = 5e-2
@test all([norm(traj.xm[end] - xm_goal) for traj in trajs] .< ε)
if test_notebook == "R3_To_R1PointDistanceAttractor_S2Damping_R1SphereAvoidance"
log_tasks = true
robot_coord_rep = ChartRep()
traj = propagate_tasks(xm, vm, tasks, CM, CNs, Time, dt, robot_coord_rep; log_tasks)
@test norm(traj.xm[end] - xm_goal) < ε
robot_coord_rep = EmbRep()
traj = propagate_tasks(xm, vm, tasks, CM, CNs, Time, dt, robot_coord_rep; log_tasks)
@test norm(traj.xm[end] - xm_goal) < ε
end
println("Finished example ", test_notebook)
end
end
test_notebook = "S2_To_R1Attractor_S2Damping_ConsistencyTest"
@testset "$test_notebook" begin
file = string(test_notebook, ".ipynb")
@nbinclude(joinpath(PBDS_dir, file))
Δx = 0.
Δx += sum(@. norm(traj_north.xm - traj_south.xm))
Δx += sum(@. norm(traj_south.xm - traj_switching.xm))
Δx += sum(@. norm(traj_switching.xm - traj_north.xm))
@test Δx < 1e-4
ε = 5e-3
@test norm(traj_north.xm[end] - xm_goal) < ε
RMP_dir = joinpath(@__DIR__, "..", "examples", "RMPflow")
@nbinclude(joinpath(RMP_dir, file))
Δx = 0.
Δx += sum(@. norm(traj_north.xm - traj_south.xm))
Δx += sum(@. norm(traj_south.xm - traj_switching.xm))
Δx += sum(@. norm(traj_switching.xm - traj_north.xm))
@test Δx > 1e3
Δx = 0.
Δx += norm(traj_north.xm[end] - xm_goal)
Δx += norm(traj_south.xm[end] - xm_goal)
Δx += norm(traj_switching.xm[end] - xm_goal)
@test Δx < ε
println("Finished example ", test_notebook)
end
end
| 42.779221
| 100
| 0.60595
|
[
"@testset \"Examples\" begin\n \"no_plots\" in ARGS && (global const no_plots = true)\n PBDS_dir = joinpath(@__DIR__, \"..\", \"examples\", \"PBDS\")\n\n test_notebook = \"R7Arm_DynamicMugGrasping\"\n @testset \"$test_notebook\" begin\n file = string(test_notebook, \".ipynb\")\n @nbinclude(joinpath(PBDS_dir, file))\n @test root.children[end-1].children[3].traj_log.x[end][1] .< 5e-3\n robot_coord_rep = ChartRep()\n traj = propagate_tasks(xm, vm, root, CM, Time, dt, robot_coord_rep, state, cache, \n mugparams; time_dep, log_tasks=true)\n @test root.children[end-1].children[3].traj_log.x[end][1] .< 5e-3\n println(\"Finished example \", test_notebook)\n end\n\n test_notebooks = [\"R1_To_R1PointPositionAttractor\",\n \"R2_To_R1PointDistanceAttractor_S1Damping\",\n \"R2_To_R1PointDistanceAttractor_S1Damping_R1BoxAvoidance\",\n \"R2_To_R1PointDistanceAttractor_S1Damping_R1SphereAvoidance\",\n \"R2_To_R2PointPositionAttractor\",\n \"R3_To_R1PointDistanceAttractor_S2Damping_R1BoxAvoidance\",\n \"R3_To_R1PointDistanceAttractor_S2Damping_R1SphereAvoidance\",\n \"S2_To_R1Attractor_S2Damping_R1ObstacleAvoidance\"]\n\n for test_notebook in test_notebooks\n @testset \"$test_notebook\" begin\n file = string(test_notebook, \".ipynb\")\n @nbinclude(joinpath(PBDS_dir, file))\n ε = 5e-2\n @test all([norm(traj.xm[end] - xm_goal) for traj in trajs] .< ε)\n\n if test_notebook == \"R3_To_R1PointDistanceAttractor_S2Damping_R1SphereAvoidance\"\n log_tasks = true\n robot_coord_rep = ChartRep()\n traj = propagate_tasks(xm, vm, tasks, CM, CNs, Time, dt, robot_coord_rep; log_tasks)\n @test norm(traj.xm[end] - xm_goal) < ε\n robot_coord_rep = EmbRep()\n traj = propagate_tasks(xm, vm, tasks, CM, CNs, Time, dt, robot_coord_rep; log_tasks)\n @test norm(traj.xm[end] - xm_goal) < ε\n end\n println(\"Finished example \", test_notebook)\n end\n end\n\n test_notebook = \"S2_To_R1Attractor_S2Damping_ConsistencyTest\"\n @testset \"$test_notebook\" begin\n file = string(test_notebook, \".ipynb\")\n @nbinclude(joinpath(PBDS_dir, file))\n Δx = 0.\n Δx += sum(@. norm(traj_north.xm - traj_south.xm))\n Δx += sum(@. norm(traj_south.xm - traj_switching.xm))\n Δx += sum(@. norm(traj_switching.xm - traj_north.xm))\n @test Δx < 1e-4\n ε = 5e-3\n @test norm(traj_north.xm[end] - xm_goal) < ε\n\n RMP_dir = joinpath(@__DIR__, \"..\", \"examples\", \"RMPflow\")\n @nbinclude(joinpath(RMP_dir, file))\n Δx = 0.\n Δx += sum(@. norm(traj_north.xm - traj_south.xm))\n Δx += sum(@. norm(traj_south.xm - traj_switching.xm))\n Δx += sum(@. norm(traj_switching.xm - traj_north.xm))\n @test Δx > 1e3\n Δx = 0.\n Δx += norm(traj_north.xm[end] - xm_goal)\n Δx += norm(traj_south.xm[end] - xm_goal)\n Δx += norm(traj_switching.xm[end] - xm_goal)\n @test Δx < ε\n println(\"Finished example \", test_notebook)\n end\n\nend"
] |
f78a1288629efb613a10d2bcea6748e09d3df249
| 720
|
jl
|
Julia
|
test/tree.jl
|
eascarrunz/Phylodendron2.jl
|
e4164a2b6209536fcca9706890e53fba130f5165
|
[
"MIT"
] | null | null | null |
test/tree.jl
|
eascarrunz/Phylodendron2.jl
|
e4164a2b6209536fcca9706890e53fba130f5165
|
[
"MIT"
] | 2
|
2019-12-09T23:25:59.000Z
|
2019-12-23T19:44:05.000Z
|
test/tree.jl
|
eascarrunz/Phylodendron2.jl
|
e4164a2b6209536fcca9706890e53fba130f5165
|
[
"MIT"
] | null | null | null |
using Phylodendron2
using Test
@testset "Linking and unlinking" begin
a = Node("A")
b = Node("B")
c = Node("C")
d = Node("D")
e = Node("E")
br_ab = Branch()
link!(a, b, br_ab)
link!(a, c)
link!(c, d)
link!(c, e)
@test length(a.links) == 2
@test a.links[1].to == b
@test a.links[2].to == c
@test length(b.links) == 1
@test b.links[1].to == a
@test length(c.links) == 3
@test c.links[1].to == a
@test c.links[2].to == d
@test c.links[3].to == e
@test length(d.links) == 1
@test d.links[1].to == c
@test length(e.links) == 1
@test e.links[1].to == c
@test unlink!(a, b) == br_ab
@test isempty(b.links)
@test length(a.links) == 1
@test a.links[1].to == c
end # testset "Linking and unlinking"
| 20
| 38
| 0.581944
|
[
"@testset \"Linking and unlinking\" begin\n\ta = Node(\"A\")\n\tb = Node(\"B\")\n\tc = Node(\"C\")\n\td = Node(\"D\")\n\te = Node(\"E\")\n\n\tbr_ab = Branch()\n\n\tlink!(a, b, br_ab)\n\tlink!(a, c)\n\tlink!(c, d)\n\tlink!(c, e)\n\n\t@test length(a.links) == 2\n\t@test a.links[1].to == b\n\t@test a.links[2].to == c\n\t@test length(b.links) == 1\n\t@test b.links[1].to == a\n\t@test length(c.links) == 3\n\t@test c.links[1].to == a\n\t@test c.links[2].to == d\n\t@test c.links[3].to == e\n\t@test length(d.links) == 1\n\t@test d.links[1].to == c\n\t@test length(e.links) == 1\n\t@test e.links[1].to == c\n\n\t@test unlink!(a, b) == br_ab\n\t@test isempty(b.links)\n\t@test length(a.links) == 1\n\t@test a.links[1].to == c\nend"
] |
f78ca5527140bff7043a310d947902909a78e74d
| 681
|
jl
|
Julia
|
test/iterativesolvers.jl
|
saolof/ITensors.jl
|
ae84b80ef55271dca1aa39dfcd4db350c4e864e1
|
[
"Apache-2.0"
] | 1
|
2021-12-14T10:09:02.000Z
|
2021-12-14T10:09:02.000Z
|
test/iterativesolvers.jl
|
saolof/ITensors.jl
|
ae84b80ef55271dca1aa39dfcd4db350c4e864e1
|
[
"Apache-2.0"
] | null | null | null |
test/iterativesolvers.jl
|
saolof/ITensors.jl
|
ae84b80ef55271dca1aa39dfcd4db350c4e864e1
|
[
"Apache-2.0"
] | null | null | null |
using ITensors
using Test
# Wrap an ITensor with pairs of primed and
# unprimed indices to pass to davidson
struct ITensorMap
A::ITensor
end
Base.eltype(M::ITensorMap) = eltype(M.A)
Base.size(M::ITensorMap) = dim(IndexSet(filterinds(M.A; plev=0)...))
(M::ITensorMap)(v::ITensor) = noprime(M.A * v)
@testset "Complex davidson" begin
d = 10
i = Index(d, "i")
A = randomITensor(ComplexF64, i, i')
A = mapprime(A * mapprime(dag(A), 0 => 2), 2 => 1)
M = ITensorMap(A)
v = randomITensor(i)
λ, v = davidson(M, v; maxiter = 10)
@test M(v) ≈ λ * v
v = randomITensor(ComplexF64, i)
λ, v = davidson(M, v; maxiter = 10)
@test M(v) ≈ λ * v
end
nothing
| 21.967742
| 68
| 0.628488
|
[
"@testset \"Complex davidson\" begin\n d = 10\n i = Index(d, \"i\")\n A = randomITensor(ComplexF64, i, i')\n A = mapprime(A * mapprime(dag(A), 0 => 2), 2 => 1)\n M = ITensorMap(A)\n \n v = randomITensor(i)\n λ, v = davidson(M, v; maxiter = 10)\n @test M(v) ≈ λ * v\n \n v = randomITensor(ComplexF64, i)\n λ, v = davidson(M, v; maxiter = 10)\n @test M(v) ≈ λ * v\n \nend"
] |
f78f15a12b33756293cc7614ddd3a48769b91043
| 1,226
|
jl
|
Julia
|
test/runtests.jl
|
akio-tomiya/Gaugefields.jl
|
dd2180dfe54eba7826ddd45a13ab2f5a007857d1
|
[
"MIT"
] | 1
|
2022-01-24T14:21:45.000Z
|
2022-01-24T14:21:45.000Z
|
test/runtests.jl
|
akio-tomiya/Gaugefields.jl
|
dd2180dfe54eba7826ddd45a13ab2f5a007857d1
|
[
"MIT"
] | 12
|
2022-01-18T01:51:48.000Z
|
2022-03-25T01:14:03.000Z
|
test/runtests.jl
|
akio-tomiya/Gaugefields.jl
|
dd2180dfe54eba7826ddd45a13ab2f5a007857d1
|
[
"MIT"
] | null | null | null |
using Gaugefields
using Test
using Random
import Wilsonloop:loops_staple
const eps = 1e-1
@testset "gradientflow_general" begin
println("gradientflow with general action")
include("gradientflow_general.jl")
end
@testset "gradientflow nowing" begin
println("gradientflow nowing")
include("gradientflow_test_nowing.jl")
end
@testset "gradientflow" begin
println("gradientflow")
include("gradientflow_test.jl")
end
@testset "HMC nowing" begin
println("HMC nowing")
include("HMC_test_nowing.jl")
end
@testset "HMC" begin
println("HMC")
include("HMC_test.jl")
end
@testset "heatbath" begin
println("heatbath")
include("heatbathtest.jl")
end
@testset "heatbath nowing" begin
println("heatbath nowing")
include("heatbathtest_nowing.jl")
end
@testset "heatbath with plaq and rect actions" begin
println("heatbath with plaq and rect actions")
include("heatbathtest_general.jl")
end
@testset "ScalarNN" begin
println("Scalar neural networks")
include("scalarnn.jl")
end
@testset "Initialization" begin
println("Initialization")
include("init.jl")
end
@testset "Gaugefields.jl" begin
# Write your tests here.
end
| 13.775281
| 52
| 0.71044
|
[
"@testset \"gradientflow_general\" begin\n println(\"gradientflow with general action\")\n include(\"gradientflow_general.jl\")\nend",
"@testset \"gradientflow nowing\" begin\n println(\"gradientflow nowing\")\n include(\"gradientflow_test_nowing.jl\")\nend",
"@testset \"gradientflow\" begin\n println(\"gradientflow\")\n include(\"gradientflow_test.jl\")\nend",
"@testset \"HMC nowing\" begin\n println(\"HMC nowing\")\n include(\"HMC_test_nowing.jl\")\nend",
"@testset \"HMC\" begin\n println(\"HMC\")\n include(\"HMC_test.jl\")\nend",
"@testset \"heatbath\" begin\n println(\"heatbath\")\n include(\"heatbathtest.jl\")\nend",
"@testset \"heatbath nowing\" begin\n println(\"heatbath nowing\")\n include(\"heatbathtest_nowing.jl\")\nend",
"@testset \"heatbath with plaq and rect actions\" begin\n println(\"heatbath with plaq and rect actions\")\n include(\"heatbathtest_general.jl\")\nend",
"@testset \"ScalarNN\" begin\n println(\"Scalar neural networks\")\n include(\"scalarnn.jl\")\nend",
"@testset \"Initialization\" begin\n println(\"Initialization\")\n include(\"init.jl\")\nend",
"@testset \"Gaugefields.jl\" begin\n # Write your tests here.\nend"
] |
f79380ae33149f55e9f70eaec12827788dc2879f
| 5,480
|
jl
|
Julia
|
test/runtests.jl
|
JuliaTagBot/CharibdeOptim.jl
|
a1ec17ded88dbc8d0720bb3f220f4d728fecbba3
|
[
"ISC"
] | null | null | null |
test/runtests.jl
|
JuliaTagBot/CharibdeOptim.jl
|
a1ec17ded88dbc8d0720bb3f220f4d728fecbba3
|
[
"ISC"
] | null | null | null |
test/runtests.jl
|
JuliaTagBot/CharibdeOptim.jl
|
a1ec17ded88dbc8d0720bb3f220f4d728fecbba3
|
[
"ISC"
] | null | null | null |
using Test, JuMP
using Distributed
addprocs(2)
@everywhere using CharibdeOptim
@everywhere using IntervalArithmetic
@testset "Using Charibde for Constrained Optimsation" begin
@everywhere using ModelingToolkit
@everywhere vars = ModelingToolkit.@variables x y
@everywhere C1 = constraint(vars, x+y, -Inf..4)
@everywhere C2 = constraint(vars, x+3y, -Inf..9)
@everywhere constraints = [C1, C2]
(maxima, maximisers, info) = charibde_max(X->((x,y)=X;-(x-4)^2-(y-4)^2), IntervalBox(-4..4, -4..4), constraints)
@test maxima ⊆ -8.01 .. -7.99
@test maximisers[1] ⊆ (1.99 .. 2.01) × (1.99 .. 2.01)
end
@testset "Using JuMP syntax for Constrained Optimisation" begin
model = Model(with_optimizer(CharibdeOptim.Optimizer))
@variable(model, -4 <= x <= 4)
@variable(model, -4 <= y <= 4)
@NLconstraint(model, x+y<=4)
@NLconstraint(model, 5<=x+3y<=9)
@NLobjective(model, Max, -(x-4)^2-(y-4)^2)
optimize!(model)
@test JuMP.termination_status(model) == MOI.OPTIMAL
@test JuMP.primal_status(model) == MOI.FEASIBLE_POINT
@test JuMP.objective_value(model) ⊆ -8.01 .. -7.99
@test JuMP.value(x) ⊆ (1.99 .. 2.01)
@test JuMP.value(y) ⊆ (1.99 .. 2.01)
end
@testset "Using Interval bound and contract algorithm for Constrained Optimisation" begin
vars = ModelingToolkit.@variables x y
C1 = constraint(vars, x+y, -Inf..4)
C2 = constraint(vars, x+3y, -Inf..9)
(maxima, maximisers, info) = ibc_maximise(X->((x,y)=X;-(x-4)^2-(y-4)^2), IntervalBox(-4..4, -4..4),[C1, C2])
@test maxima ⊆ -8.01 .. -7.99
@test maximisers[1] ⊆ (1.99 .. 2.01) × (1.99 .. 2.01)
end
@testset "Optimising by Interval Branch and Contract Algorithm" begin
(global_min, minimisers)= ibc_minimise(X->((x,y)= X;x^2 + y^2), IntervalBox(2..3, 3..4))
@test global_min ⊆ 13 .. 13.01
@test minimisers[1] ⊆ (2.0 .. 2.001) × (3.0 .. 3.001)
end
@testset "Optimising by Charibde (A hybrid approach) using only one worker" begin
(global_min, minimisers, info) = charibde_min(X->((x,y)=X;x^2+y+1), IntervalBox(1..2, 2..3), workers = 1)
@test global_min ⊆ 4.0 .. 4.01
@test minimisers[1] ⊆ (1..1.001) × (2..2.001)
(global_min, minimisers, info)= charibde_min(X->((x,y)=X;x^2 + y^2), IntervalBox(2..3, 3..4), workers = 1)
@test global_min ⊆ 13 .. 13.01
@test minimisers[1] ⊆ (2.0 .. 2.001) × (3..3.001)
end
@testset "Using JuMP syntax by using only one worker " begin #for using two workers just dont pass 'workers' arguments as its value is set to 2
model = Model(with_optimizer(CharibdeOptim.Optimizer, workers = 1))
@variable(model, 1<=x<=2)
@variable(model, 1<=y<=2)
@NLobjective(model, Min, x^2+y^2)
optimize!(model)
@test JuMP.termination_status(model) == MOI.OPTIMAL
@test JuMP.primal_status(model) == MOI.FEASIBLE_POINT
@test JuMP.objective_value(model) ≈ 2.0
@test JuMP.value(x) ≈ 1.0
@test JuMP.value(y) ≈ 1.0
end
# No need to add worker because a worker is already added while running testset "Using Charibde for Constrained Optimsation".
# Otherwise we have to add a worker by using 'Distributed.addprocs(1)' and load the package on each worker
# by '@everywhere using CharibdeOptim'.
@testset "Optimising by Charibde (A hybrid approach) using 2 workers" begin
(global_min, minimisers, info) = charibde_min(X->((x,y)=X;x^3 + 2y + 5), IntervalBox(2..4, 2..3))
@test global_min ⊆ 17.0 .. 17.01
@test minimisers[1] ⊆ (2..2.001) × (2..2.001)
(global_min, minimisers, info)= charibde_min(X->((x,y)=X;x^2 + y^2), IntervalBox(2..3, 3..4))
@test global_min ⊆ 13 .. 13.01
@test minimisers[1] ⊆ (2.0 .. 2.001) × (3..3.001)
end
@testset "Optimising difficult problem using JuMP" begin
model = Model(with_optimizer(CharibdeOptim.Optimizer))
@variable(model, 2 <= x1 <= 3)
@variable(model, 3 <= x2 <= 4)
@variable(model, 9 <= x3 <= 14)
@variable(model, 2 <= x4 <= 3)
@variable(model, 3 <= x5 <= 4)
@variable(model, 9 <= x6 <= 14)
@variable(model, 2 <= x7 <= 3)
@variable(model, 3 <= x8 <= 4)
@variable(model, 9 <= x9 <= 14)
@NLobjective(model, Min, x1^2 + x2^2 + x3^4 - x4^7 - 200x5 - x6^5 - x7^9 + x8^5 - 8x9^3)
optimize!(model)
@test JuMP.termination_status(model) == MOI.OPTIMAL
@test JuMP.primal_status(model) == MOI.FEASIBLE_POINT
@test JuMP.objective_value(model) ≈ -575629.0
@test JuMP.value(x1) ⊆ 1.99 .. 2.01
@test JuMP.value(x2) ⊆ 2.99 .. 3.01
@test JuMP.value(x3) ⊆ 8.99 .. 9.01
@test JuMP.value(x4) ⊆ 2.99 .. 3.01
@test JuMP.value(x5) ⊆ 3.99 .. 4.01
@test JuMP.value(x6) ⊆ 13.99 .. 14.01
@test JuMP.value(x7) ⊆ 2.99 .. 3.01
@test JuMP.value(x8) ⊆ 2.99 .. 3.01
@test JuMP.value(x9) ⊆ 13.99 .. 14.01
end
@testset "Optimising difficult problems using Charibde" begin
f = X->((x1,x2,x3,x4,x5,x6,x7,x8,x9)=X;x1^2 + x2^2 + x3^4 - x4^7 - 200x5 - x6^5 - x7^9 + x8^5 - 8x9^3)
X = IntervalBox(2..3, 3..4, 9..14, 2..3, 3..4, 9..14, 2..3, 3..4, 9..14)
(global_min, minimisers, info) = charibde_min(f, X)
@test global_min ⊆ -575630 .. -575628
@test minimisers[1] ⊆ (1.99 .. 2.01) × (2.99 .. 3.01) × (8.99 .. 9.01) × (2.99 .. 3.01) × (3.99 .. 4.01) × (13.99 .. 14.01) × (2.99 .. 3.01) × (2.99 .. 3.01) × (13.99 .. 14.01)
end
| 40
| 182
| 0.598723
|
[
"@testset \"Using Charibde for Constrained Optimsation\" begin\n @everywhere using ModelingToolkit\n\n @everywhere vars = ModelingToolkit.@variables x y\n @everywhere C1 = constraint(vars, x+y, -Inf..4)\n @everywhere C2 = constraint(vars, x+3y, -Inf..9)\n @everywhere constraints = [C1, C2]\n (maxima, maximisers, info) = charibde_max(X->((x,y)=X;-(x-4)^2-(y-4)^2), IntervalBox(-4..4, -4..4), constraints)\n @test maxima ⊆ -8.01 .. -7.99\n @test maximisers[1] ⊆ (1.99 .. 2.01) × (1.99 .. 2.01)\nend",
"@testset \"Using JuMP syntax for Constrained Optimisation\" begin\n model = Model(with_optimizer(CharibdeOptim.Optimizer))\n @variable(model, -4 <= x <= 4)\n @variable(model, -4 <= y <= 4)\n @NLconstraint(model, x+y<=4)\n @NLconstraint(model, 5<=x+3y<=9)\n @NLobjective(model, Max, -(x-4)^2-(y-4)^2)\n optimize!(model)\n\n @test JuMP.termination_status(model) == MOI.OPTIMAL\n @test JuMP.primal_status(model) == MOI.FEASIBLE_POINT\n @test JuMP.objective_value(model) ⊆ -8.01 .. -7.99\n @test JuMP.value(x) ⊆ (1.99 .. 2.01)\n @test JuMP.value(y) ⊆ (1.99 .. 2.01)\nend",
"@testset \"Using Interval bound and contract algorithm for Constrained Optimisation\" begin\n vars = ModelingToolkit.@variables x y\n C1 = constraint(vars, x+y, -Inf..4)\n C2 = constraint(vars, x+3y, -Inf..9)\n\n (maxima, maximisers, info) = ibc_maximise(X->((x,y)=X;-(x-4)^2-(y-4)^2), IntervalBox(-4..4, -4..4),[C1, C2])\n @test maxima ⊆ -8.01 .. -7.99\n @test maximisers[1] ⊆ (1.99 .. 2.01) × (1.99 .. 2.01)\nend",
"@testset \"Optimising by Interval Branch and Contract Algorithm\" begin\n (global_min, minimisers)= ibc_minimise(X->((x,y)= X;x^2 + y^2), IntervalBox(2..3, 3..4))\n @test global_min ⊆ 13 .. 13.01\n @test minimisers[1] ⊆ (2.0 .. 2.001) × (3.0 .. 3.001)\nend",
"@testset \"Optimising by Charibde (A hybrid approach) using only one worker\" begin\n\n (global_min, minimisers, info) = charibde_min(X->((x,y)=X;x^2+y+1), IntervalBox(1..2, 2..3), workers = 1)\n @test global_min ⊆ 4.0 .. 4.01\n @test minimisers[1] ⊆ (1..1.001) × (2..2.001)\n\n (global_min, minimisers, info)= charibde_min(X->((x,y)=X;x^2 + y^2), IntervalBox(2..3, 3..4), workers = 1)\n @test global_min ⊆ 13 .. 13.01\n @test minimisers[1] ⊆ (2.0 .. 2.001) × (3..3.001)\nend",
"@testset \"Using JuMP syntax by using only one worker \" begin #for using two workers just dont pass 'workers' arguments as its value is set to 2\n model = Model(with_optimizer(CharibdeOptim.Optimizer, workers = 1))\n @variable(model, 1<=x<=2)\n @variable(model, 1<=y<=2)\n @NLobjective(model, Min, x^2+y^2)\n optimize!(model)\n\n @test JuMP.termination_status(model) == MOI.OPTIMAL\n @test JuMP.primal_status(model) == MOI.FEASIBLE_POINT\n @test JuMP.objective_value(model) ≈ 2.0\n @test JuMP.value(x) ≈ 1.0\n @test JuMP.value(y) ≈ 1.0\nend",
"@testset \"Optimising by Charibde (A hybrid approach) using 2 workers\" begin\n (global_min, minimisers, info) = charibde_min(X->((x,y)=X;x^3 + 2y + 5), IntervalBox(2..4, 2..3))\n @test global_min ⊆ 17.0 .. 17.01\n @test minimisers[1] ⊆ (2..2.001) × (2..2.001)\n\n (global_min, minimisers, info)= charibde_min(X->((x,y)=X;x^2 + y^2), IntervalBox(2..3, 3..4))\n @test global_min ⊆ 13 .. 13.01\n @test minimisers[1] ⊆ (2.0 .. 2.001) × (3..3.001)\n\nend",
"@testset \"Optimising difficult problem using JuMP\" begin\n model = Model(with_optimizer(CharibdeOptim.Optimizer))\n\n @variable(model, 2 <= x1 <= 3)\n @variable(model, 3 <= x2 <= 4)\n @variable(model, 9 <= x3 <= 14)\n @variable(model, 2 <= x4 <= 3)\n @variable(model, 3 <= x5 <= 4)\n @variable(model, 9 <= x6 <= 14)\n @variable(model, 2 <= x7 <= 3)\n @variable(model, 3 <= x8 <= 4)\n @variable(model, 9 <= x9 <= 14)\n\n @NLobjective(model, Min, x1^2 + x2^2 + x3^4 - x4^7 - 200x5 - x6^5 - x7^9 + x8^5 - 8x9^3)\n\n optimize!(model)\n\n @test JuMP.termination_status(model) == MOI.OPTIMAL\n @test JuMP.primal_status(model) == MOI.FEASIBLE_POINT\n @test JuMP.objective_value(model) ≈ -575629.0\n @test JuMP.value(x1) ⊆ 1.99 .. 2.01\n @test JuMP.value(x2) ⊆ 2.99 .. 3.01\n @test JuMP.value(x3) ⊆ 8.99 .. 9.01\n @test JuMP.value(x4) ⊆ 2.99 .. 3.01\n @test JuMP.value(x5) ⊆ 3.99 .. 4.01\n @test JuMP.value(x6) ⊆ 13.99 .. 14.01\n @test JuMP.value(x7) ⊆ 2.99 .. 3.01\n @test JuMP.value(x8) ⊆ 2.99 .. 3.01\n @test JuMP.value(x9) ⊆ 13.99 .. 14.01\nend",
"@testset \"Optimising difficult problems using Charibde\" begin\n f = X->((x1,x2,x3,x4,x5,x6,x7,x8,x9)=X;x1^2 + x2^2 + x3^4 - x4^7 - 200x5 - x6^5 - x7^9 + x8^5 - 8x9^3)\n X = IntervalBox(2..3, 3..4, 9..14, 2..3, 3..4, 9..14, 2..3, 3..4, 9..14)\n (global_min, minimisers, info) = charibde_min(f, X)\n\n @test global_min ⊆ -575630 .. -575628\n @test minimisers[1] ⊆ (1.99 .. 2.01) × (2.99 .. 3.01) × (8.99 .. 9.01) × (2.99 .. 3.01) × (3.99 .. 4.01) × (13.99 .. 14.01) × (2.99 .. 3.01) × (2.99 .. 3.01) × (13.99 .. 14.01)\n\nend"
] |
f7955887e028c72bfb30ed41a2e1d562fd0442b1
| 2,454
|
jl
|
Julia
|
test/runtests.jl
|
rbontekoe/AppliMaster.jl
|
cf0c5bf13120980650609480f13e836bcaabd622
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
rbontekoe/AppliMaster.jl
|
cf0c5bf13120980650609480f13e836bcaabd622
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
rbontekoe/AppliMaster.jl
|
cf0c5bf13120980650609480f13e836bcaabd622
|
[
"MIT"
] | null | null | null |
# runtests.jl
using AppliMaster
using Test
using AppliAR, AppliSales, AppliGeneralLedger
using Query
using DataFrames
using Dates
@testset "Test AppliSales" begin
orders = AppliSales.process()
@test length(orders) == 3
@test length(orders[1].students) == 1
@test length(orders[2].students) == 2
@test length(orders[3].students) == 1
@test orders[1].training.price == 1000
end
@testset " Test AppliAR - unpaid invoices" begin
orders = AppliSales.process()
AppliAR.process(orders)
unpaid_invoices = retrieve_unpaid_invoices()
@test length(unpaid_invoices) == 3
@test id(unpaid_invoices[1]) == "A1001"
cmd = `rm test_invoicing.txt invoicenbr.txt`
run(cmd)
end
@testset "Test AppliAR - entries unpaid invoices" begin
orders = AppliSales.process()
entries = AppliAR.process(orders)
@test length(entries) == 3
@test entries[1].from == 1300
@test entries[1].to == 8000
@test entries[1].debit == 1000
@test entries[1].credit == 0
@test entries[1].vat == 210.0
cmd = `rm test_invoicing.txt invoicenbr.txt`
run(cmd)
end
@testset "Test GeneralLedger - accounts receivable, bank, vat, sales" begin
orders = AppliSales.process()
journal_entries_unpaid_invoices = AppliAR.process(orders)
AppliGeneralLedger.process(journal_entries_unpaid_invoices)
unpaid_invoices = AppliAR.retrieve_unpaid_invoices()
stm1 = BankStatement(Date(2020-01-15), "Duck City Chronicals Invoice A1002", "NL39INGB", 2420.0)
stm2 = BankStatement(Date(2020-01-15), "Donalds Hardware Store Bill A1003", "NL39INGB", 1210.0)
stms = [stm1, stm2]
journal_entries_paid_invoices = AppliAR.process(unpaid_invoices, stms)
AppliGeneralLedger.process(journal_entries_paid_invoices)
df = DataFrame(AppliGeneralLedger.read_from_file("./test_ledger.txt"))
df2 = df |> @filter(_.accountid == 1300) |> DataFrame
@test sum(df2.debit - df2.credit) == 1210
df2 = df |> @filter(_.accountid == 1150) |> DataFrame # bank
@test sum(df2.debit - df2.credit) == 3630
df2 = df |> @filter(_.accountid == 4000) |> DataFrame # vat
@test sum(df2.credit - df2.debit) == 840
df2 = df |> @filter(_.accountid == 8000) |> DataFrame # sales
@test sum(df2.credit - df2.debit) == 4000
@test sum(df.debit - df.credit) == 0.0
cmd = `rm test_invoicing.txt test_invoicing_paid.txt test_journal.txt test_ledger.txt invoicenbr.txt`
run(cmd)
end
| 30.675
| 105
| 0.690709
|
[
"@testset \"Test AppliSales\" begin\n orders = AppliSales.process()\n @test length(orders) == 3\n @test length(orders[1].students) == 1\n @test length(orders[2].students) == 2\n @test length(orders[3].students) == 1\n @test orders[1].training.price == 1000\nend",
"@testset \" Test AppliAR - unpaid invoices\" begin\n orders = AppliSales.process()\n AppliAR.process(orders)\n unpaid_invoices = retrieve_unpaid_invoices()\n @test length(unpaid_invoices) == 3\n @test id(unpaid_invoices[1]) == \"A1001\"\n cmd = `rm test_invoicing.txt invoicenbr.txt`\n run(cmd)\nend",
"@testset \"Test AppliAR - entries unpaid invoices\" begin\n orders = AppliSales.process()\n entries = AppliAR.process(orders)\n @test length(entries) == 3\n @test entries[1].from == 1300\n @test entries[1].to == 8000\n @test entries[1].debit == 1000\n @test entries[1].credit == 0\n @test entries[1].vat == 210.0\n cmd = `rm test_invoicing.txt invoicenbr.txt`\n run(cmd)\nend",
"@testset \"Test GeneralLedger - accounts receivable, bank, vat, sales\" begin\n orders = AppliSales.process()\n\n journal_entries_unpaid_invoices = AppliAR.process(orders)\n AppliGeneralLedger.process(journal_entries_unpaid_invoices)\n\n unpaid_invoices = AppliAR.retrieve_unpaid_invoices()\n stm1 = BankStatement(Date(2020-01-15), \"Duck City Chronicals Invoice A1002\", \"NL39INGB\", 2420.0)\n stm2 = BankStatement(Date(2020-01-15), \"Donalds Hardware Store Bill A1003\", \"NL39INGB\", 1210.0)\n stms = [stm1, stm2]\n\n journal_entries_paid_invoices = AppliAR.process(unpaid_invoices, stms)\n AppliGeneralLedger.process(journal_entries_paid_invoices)\n\n df = DataFrame(AppliGeneralLedger.read_from_file(\"./test_ledger.txt\"))\n\n df2 = df |> @filter(_.accountid == 1300) |> DataFrame\n @test sum(df2.debit - df2.credit) == 1210\n\n df2 = df |> @filter(_.accountid == 1150) |> DataFrame # bank\n @test sum(df2.debit - df2.credit) == 3630\n\n df2 = df |> @filter(_.accountid == 4000) |> DataFrame # vat\n @test sum(df2.credit - df2.debit) == 840\n\n df2 = df |> @filter(_.accountid == 8000) |> DataFrame # sales\n @test sum(df2.credit - df2.debit) == 4000\n\n @test sum(df.debit - df.credit) == 0.0\n\n cmd = `rm test_invoicing.txt test_invoicing_paid.txt test_journal.txt test_ledger.txt invoicenbr.txt`\n run(cmd)\nend"
] |
f79651a2e460201b9a8e127eb2cf8b1e17288477
| 2,082
|
jl
|
Julia
|
test/box.jl
|
April-Hannah-Lena/GAIO.jl
|
5cc55575a615db337312a07fa295cf08f87d8cb4
|
[
"MIT"
] | 7
|
2020-07-12T13:48:31.000Z
|
2021-12-20T02:11:02.000Z
|
test/box.jl
|
April-Hannah-Lena/GAIO.jl
|
5cc55575a615db337312a07fa295cf08f87d8cb4
|
[
"MIT"
] | 25
|
2020-07-10T10:40:02.000Z
|
2022-03-30T09:01:02.000Z
|
test/box.jl
|
April-Hannah-Lena/GAIO.jl
|
5cc55575a615db337312a07fa295cf08f87d8cb4
|
[
"MIT"
] | 3
|
2020-07-15T11:23:28.000Z
|
2021-12-20T02:11:05.000Z
|
using GAIO
using StaticArrays
using Test
@testset "exported functionality" begin
@testset "basics" begin
center = SVector(0.0, 0.1)
radius = SVector(10.0, 10.0)
box = Box(center, radius)
@test box.center == center
@test box.radius == radius
end
@testset "types" begin
center = SVector(0, 0, 1)
radius = SVector(1.0, 0.1, 1.0)
box = Box(center, radius)
@test typeof(box.center) <: typeof(box.radius)
@test typeof(box.radius) <: typeof(box.center)
@test !(typeof(box.center) <: typeof(center))
end
@testset "containment" begin
center = SVector(0.0, 0.0, 0.0)
radius = SVector(1.0, 1.0, 1.0)
box = Box(center, radius)
inside = SVector(0.5, 0.5, 0.5)
left = SVector(-1.0, -1.0, -1.0)
right = SVector(1.0, 1.0, 1.0)
on_boundary_left = SVector(0.0, 0.0, -1.0)
on_boundary_right = SVector(0.0, 1.0, 0.0)
outside_left = SVector(0.0, 0.0, -2.0)
outside_right = SVector(0.0, 2.0, 0.0)
@test inside ∈ box
@test box.center ∈ box
#boxes are half open to the right
@test left ∈ box
@test right ∉ box
@test on_boundary_left ∈ box
@test on_boundary_right ∉ box
@test outside_left ∉ box
@test outside_right ∉ box
end
@testset "non matching dimensions" begin
center = SVector(0.0, 0.0, 0.0)
radius = SVector(1.0, 1.0)
@test_throws Exception Box(center, radius)
end
@testset "negative radii" begin
center = SVector(0.0, 0.0)
radius = SVector(1.0, -1.0)
@test_throws Exception Box(center, radius)
end
end
@testset "internal functionality" begin
box = Box(SVector(0.0, 0.0), SVector(1.0, 1.0))
@testset "integer point in box" begin
point_int_outside = SVector(2, 2)
point_int_inside = SVector(0, 0)
@test point_int_inside ∈ box
@test point_int_outside ∉ box
end
@test_throws DimensionMismatch SVector(0.0, 0.0, 0.0) ∈ box
end
| 33.047619
| 63
| 0.580211
|
[
"@testset \"exported functionality\" begin\n @testset \"basics\" begin\n center = SVector(0.0, 0.1)\n radius = SVector(10.0, 10.0)\n box = Box(center, radius)\n @test box.center == center\n @test box.radius == radius\n end\n @testset \"types\" begin\n center = SVector(0, 0, 1)\n radius = SVector(1.0, 0.1, 1.0)\n box = Box(center, radius)\n @test typeof(box.center) <: typeof(box.radius)\n @test typeof(box.radius) <: typeof(box.center)\n @test !(typeof(box.center) <: typeof(center))\n end\n @testset \"containment\" begin\n center = SVector(0.0, 0.0, 0.0)\n radius = SVector(1.0, 1.0, 1.0)\n box = Box(center, radius)\n inside = SVector(0.5, 0.5, 0.5)\n left = SVector(-1.0, -1.0, -1.0)\n right = SVector(1.0, 1.0, 1.0)\n on_boundary_left = SVector(0.0, 0.0, -1.0)\n on_boundary_right = SVector(0.0, 1.0, 0.0)\n outside_left = SVector(0.0, 0.0, -2.0)\n outside_right = SVector(0.0, 2.0, 0.0)\n @test inside ∈ box\n @test box.center ∈ box\n #boxes are half open to the right\n @test left ∈ box\n @test right ∉ box\n @test on_boundary_left ∈ box\n @test on_boundary_right ∉ box\n @test outside_left ∉ box\n @test outside_right ∉ box\n end\n @testset \"non matching dimensions\" begin\n center = SVector(0.0, 0.0, 0.0)\n radius = SVector(1.0, 1.0)\n @test_throws Exception Box(center, radius)\n end\n @testset \"negative radii\" begin\n center = SVector(0.0, 0.0)\n radius = SVector(1.0, -1.0)\n @test_throws Exception Box(center, radius)\n end\nend",
"@testset \"internal functionality\" begin\n box = Box(SVector(0.0, 0.0), SVector(1.0, 1.0))\n @testset \"integer point in box\" begin\n point_int_outside = SVector(2, 2)\n point_int_inside = SVector(0, 0)\n @test point_int_inside ∈ box\n @test point_int_outside ∉ box\n end\n @test_throws DimensionMismatch SVector(0.0, 0.0, 0.0) ∈ box\nend"
] |
f79b047288c0de98e54f43ae36be2f8248502143
| 8,483
|
jl
|
Julia
|
test/sample_test.jl
|
pitmonticone/MitosisStochasticDiffEq.jl
|
f9f3621e6610b0f29a0418de59d0a85fa7b401f9
|
[
"MIT"
] | 11
|
2021-02-21T20:52:11.000Z
|
2022-01-26T13:06:30.000Z
|
test/sample_test.jl
|
pitmonticone/MitosisStochasticDiffEq.jl
|
f9f3621e6610b0f29a0418de59d0a85fa7b401f9
|
[
"MIT"
] | 46
|
2020-10-18T15:38:19.000Z
|
2021-10-05T22:32:51.000Z
|
test/sample_test.jl
|
pitmonticone/MitosisStochasticDiffEq.jl
|
f9f3621e6610b0f29a0418de59d0a85fa7b401f9
|
[
"MIT"
] | 2
|
2021-04-02T21:54:59.000Z
|
2021-08-14T11:03:29.000Z
|
import MitosisStochasticDiffEq as MSDE
using StochasticDiffEq
using Mitosis
using LinearAlgebra
using SparseArrays
using DiffEqNoiseProcess
using Test, Random
"""
forwardsample(f, g, p, s, W, x) using the Euler-Maruyama scheme
on a time-grid s with associated noise values W
"""
function forwardsample(f, g, p, s, Ws, x)
xs = typeof(x)[]
for i in eachindex(s)[1:end-1]
dt = s[i+1] - s[i]
push!(xs, x)
x = x + f(x, p, s[i])*dt + g(x, p, s[i])*(Ws[i+1]-Ws[i])
end
push!(xs, x)
return xs
end
@testset "sampling tests" begin
# define SDE function
f(u,p,t) = p[1]*u + p[2] - 1.5*sin.(u*2pi)
g(u,p,t) = p[3] .- 0.2*(1 .-sin.(u))
# set estimate of model parameters or true model parameters
p = [-0.1,0.2,0.9]
# time range
tstart = 0.0
tend = 1.0
dt = 0.02
trange = tstart:dt:tend
# intial condition
u0 = 1.1
kernel = MSDE.SDEKernel(f,g,trange,p)
# sample using MSDE and EM default
sol, solend = MSDE.sample(kernel, u0)
kernel = MSDE.SDEKernel(f,g,collect(trange),p)
uend, (ts, u, noise) = MSDE.sample(kernel, u0, save_noise=true)
@test isapprox(u, forwardsample(f,g,p,ts,noise,u0), atol=1e-12)
end
@testset "multivariate sampling tests" begin
seed = 12345
Random.seed!(seed)
d = 2
u0 = randn(2)
θlin = (randn(d,d), randn(d), Diagonal([0.1, 0.1]))
Σ(θ) = Diagonal(θ[2]) # just to generate the noise_rate_prototype
f(u,p,t) = p[1]*u + p[2]
f!(du,u,p,t) = (du .= p[1]*u + p[2])
gvec(u,p,t) = diag(p[3])
function gvec!(du,u,p,t)
du[1] = p[3][1,1]
du[2] = p[3][2,2]
end
g(u,p,t) = p[3]
# Make `g` write the sparse matrix values
function g!(du,u,p,t)
du[1,1] = p[3][1,1]
du[2,2] = p[3][2,2]
end
function gstepvec!(dx, _, u, p, t, dw, _)
dx .+= diag(p[3]).*dw
end
function gstep!(dx, _, u, p, t, dw, _)
dx .+= p[3]*dw
end
# Define a sparse matrix by making a dense matrix and setting some values as not zero
A = zeros(2,2)
A[1,1] = 1
A[2,2] = 1
A = sparse(A)
# time range
tstart = 0.0
tend = 1.0
dt = 0.02
trange = tstart:dt:tend
# define kernels
k1 = MSDE.SDEKernel(f,gvec,trange,θlin)
k2 = MSDE.SDEKernel(f,g,trange,θlin,Σ(θlin))
k3 = MSDE.SDEKernel(f!,g!,trange,θlin,A)
k4 = MSDE.SDEKernel(Mitosis.AffineMap(θlin[1], θlin[2]), Mitosis.ConstantMap(θlin[3]), trange, θlin, Σ(θlin))
k5 = MSDE.SDEKernel!(f!,gvec!,gstepvec!,trange,θlin; ws = copy(u0))
k6 = MSDE.SDEKernel!(f!,g!,gstep!,trange,θlin,A; ws = copy(A))
@testset "StochasticDiffEq EM() solver" begin
uend1, (ts1, u1, noise1) = MSDE.sample(k1, u0, EM(false), save_noise=true)
NG = NoiseGrid(ts1, noise1)
Z = pCN(NG, 1.0)
uend2, (ts2, u2, noise2) = MSDE.sample(k2, u0, EM(false), Z, save_noise=true)
Z = pCN(NG, 1.0)
uend3, (ts3, u3, noise3) = MSDE.sample(k3, u0, EM(false), Z)
Z = pCN(NG, 1.0)
uend4, (ts4, u4, noise4) = MSDE.sample(k4, u0, EM(false), Z)
Z = pCN(NG, 1.0)
uend5, (ts5, u5, noise5) = MSDE.sample(k5, u0, EM(false), Z)
Z = pCN(NG, 1.0)
uend6, (ts6, u6, noise6) = MSDE.sample(k6, u0, EM(false), Z)
#@show solend1
@test isapprox(u1, u2, atol=1e-12)
@test isapprox(uend1, uend2, atol=1e-12)
@test isapprox(u1, u3, atol=1e-12)
@test isapprox(uend1, uend3, atol=1e-12)
@test isapprox(u1, u4, atol=1e-12)
@test isapprox(uend1, uend4, atol=1e-12)
@test isapprox(u1, u5, atol=1e-12)
@test isapprox(uend1, uend5, atol=1e-12)
@test isapprox(u1, u6, atol=1e-12)
@test isapprox(uend1, uend6, atol=1e-12)
end
@testset "internal solver" begin
@testset "without passing a noise" begin
Random.seed!(seed)
uend1, (ts1, u1, noise1) = MSDE.sample(k1, u0, MSDE.EulerMaruyama!(), save=true)
Random.seed!(seed)
uend2, (ts2, u2, noise2) = MSDE.sample(k2, u0, MSDE.EulerMaruyama!(), save=true)
Random.seed!(seed)
# inplace must be written out manually
@test_broken uend3, (ts3, u3, noise3) = MSDE.sample(k3, u0, MSDE.EulerMaruyama!(), save=true)
Random.seed!(seed)
uend4, (ts4, u4, noise4) = MSDE.sample(k4, u0, MSDE.EulerMaruyama!(), save=true)
Random.seed!(seed)
uend5, (ts5, u5, noise5) = MSDE.sample(k5, u0, MSDE.EulerMaruyama!(), save=true)
Random.seed!(seed)
uend6, (ts6, u6, noise6) = MSDE.sample(k6, u0, MSDE.EulerMaruyama!(), save=true)
@test length(ts1) == length(trange)
@test ts1[end] == trange[end]
@test uend1 == uend2
@test_broken uend1 == uend3
@test uend1 == uend4
@test uend1 == uend5
@test uend1 == uend6
Random.seed!(seed)
uend7, (ts7, u7, noise7) = MSDE.sample(k1, u0, MSDE.EulerMaruyama!(), save=false)
@test uend1 == uend7
@test u7 === nothing
end
@testset "passing a noise grid" begin
# pass noise process and compare with EM()
Ws = cumsum([[zero(u0)];[sqrt(trange[i+1]-ti)*randn(size(u0))
for (i,ti) in enumerate(trange[1:end-1])]])
NG = NoiseGrid(trange,Ws)
uendEM, (tsEM, uEM, noiseEM) = MSDE.sample(k1, u0, EM(false), NG)
uend1, (ts1, u1, noise1) = MSDE.sample(k1, u0, MSDE.EulerMaruyama!(), NG)
uend2, (ts2, u2, noise2) = MSDE.sample(k2, u0, MSDE.EulerMaruyama!(), NG)
@test_broken uend3, (ts3, u3, noise3) = MSDE.sample(k3, u0, MSDE.EulerMaruyama!(), NG)
uend4, (ts4, u4, noise4) = MSDE.sample(k4, u0, MSDE.EulerMaruyama!(), NG)
uend5, (ts5, u5, noise5) = MSDE.sample(k5, u0, MSDE.EulerMaruyama!(), NG)
uend6, (ts6, u6, noise6) = MSDE.sample(k6, u0, MSDE.EulerMaruyama!(), NG)
@test u1 ≈ uEM rtol=1e-12
@test uendEM ≈ uend1 rtol=1e-12
@test uendEM ≈ uend2 rtol=1e-12
@test_broken uendEM ≈ uend3 rtol=1e-12
@test uendEM ≈ uend4 rtol=1e-12
@test uendEM ≈ uend5 rtol=1e-12
@test uendEM ≈ uend6 rtol=1e-12
end
@testset "passing the noise values" begin
# pass noise process and compare with EM()
Ws = cumsum([[zero(u0)];[sqrt(trange[i+1]-ti)*randn(size(u0))
for (i,ti) in enumerate(trange[1:end-1])]])
NG = NoiseGrid(trange,Ws)
uendEM, (tsEM, uEM, noiseEM) = MSDE.sample(k1, u0, EM(false), NG)
uend1, (ts1, u1, noise1) = MSDE.sample(k1, u0, MSDE.EulerMaruyama!(), Ws)
uend2, (ts2, u2, noise2) = MSDE.sample(k2, u0, MSDE.EulerMaruyama!(), Ws)
@test_broken uend3, (ts3, u3, noise3) = MSDE.sample(k3, u0, MSDE.EulerMaruyama!(), Ws)
uend4, (ts4, u4, noise4) = MSDE.sample(k4, u0, MSDE.EulerMaruyama!(), Ws)
uend5, (ts5, u5, noise5) = MSDE.sample(k5, u0, MSDE.EulerMaruyama!(), Ws)
uend6, (ts6, u6, noise6) = MSDE.sample(k6, u0, MSDE.EulerMaruyama!(), Ws)
@test u1 ≈ uEM rtol=1e-12
@test uendEM ≈ uend1 rtol=1e-12
@test uendEM ≈ uend2 rtol=1e-12
@test_broken uendEM ≈ uend3 rtol=1e-12
@test uendEM ≈ uend4 rtol=1e-12
@test uendEM ≈ uend5 rtol=1e-12
@test uendEM ≈ uend6 rtol=1e-12
end
@testset "custom P" begin
# checks that defining and passing P manually works
struct customP{θType}
θ::θType
end
function MSDE.tangent!(du, u, dz, P::customP)
du[3] .= (P.θ[1]*u[3]+P.θ[2])*dz[2] + P.θ[3]*dz[3]
(dz[1], dz[2], du[3])
end
function MSDE.exponential_map!(u, du, P::customP)
x = u[3]
@. x += du[3]
(u[1] + du[1], u[2] + du[2], x)
end
# pass noise process and compare with EM()
Ws = cumsum([[zero(u0)];[sqrt(trange[i+1]-ti)*randn(size(u0))
for (i,ti) in enumerate(trange[1:end-1])]])
NG = NoiseGrid(trange,Ws)
uendEM, (tsEM, uEM, noiseEM) = MSDE.sample(k1, u0, EM(false), NG)
uend1, (ts1, u1, noise1) = MSDE.sample(k1, u0, MSDE.EulerMaruyama!(), Ws, P=customP(θlin))
uend2, (ts2, u2, noise2) = MSDE.sample(k2, u0, MSDE.EulerMaruyama!(), Ws, P=customP(θlin))
uend3, (ts3, u3, noise3) = MSDE.sample(k3, u0, MSDE.EulerMaruyama!(), Ws, P=customP(θlin))
uend4, (ts4, u4, noise4) = MSDE.sample(k4, u0, MSDE.EulerMaruyama!(), Ws)
uend5, (ts5, u5, noise5) = MSDE.sample(k5, u0, MSDE.EulerMaruyama!(), Ws)
uend6, (ts6, u6, noise6) = MSDE.sample(k6, u0, MSDE.EulerMaruyama!(), Ws)
@test u1 ≈ uEM rtol=1e-12
@test uendEM ≈ uend1 rtol=1e-12
@test uendEM ≈ uend2 rtol=1e-12
@test uendEM ≈ uend3 rtol=1e-12
@test uendEM ≈ uend4 rtol=1e-12
@test uendEM ≈ uend5 rtol=1e-12
@test uendEM ≈ uend6 rtol=1e-12
end
end
end
| 33.662698
| 111
| 0.597077
|
[
"@testset \"sampling tests\" begin\n # define SDE function\n f(u,p,t) = p[1]*u + p[2] - 1.5*sin.(u*2pi)\n g(u,p,t) = p[3] .- 0.2*(1 .-sin.(u))\n\n # set estimate of model parameters or true model parameters\n p = [-0.1,0.2,0.9]\n\n # time range\n tstart = 0.0\n tend = 1.0\n dt = 0.02\n trange = tstart:dt:tend\n\n # intial condition\n u0 = 1.1\n\n kernel = MSDE.SDEKernel(f,g,trange,p)\n # sample using MSDE and EM default\n sol, solend = MSDE.sample(kernel, u0)\n\n kernel = MSDE.SDEKernel(f,g,collect(trange),p)\n uend, (ts, u, noise) = MSDE.sample(kernel, u0, save_noise=true)\n\n @test isapprox(u, forwardsample(f,g,p,ts,noise,u0), atol=1e-12)\nend",
"@testset \"multivariate sampling tests\" begin\n seed = 12345\n Random.seed!(seed)\n d = 2\n u0 = randn(2)\n θlin = (randn(d,d), randn(d), Diagonal([0.1, 0.1]))\n\n Σ(θ) = Diagonal(θ[2]) # just to generate the noise_rate_prototype\n\n f(u,p,t) = p[1]*u + p[2]\n f!(du,u,p,t) = (du .= p[1]*u + p[2])\n gvec(u,p,t) = diag(p[3])\n function gvec!(du,u,p,t)\n du[1] = p[3][1,1]\n du[2] = p[3][2,2]\n end\n g(u,p,t) = p[3]\n # Make `g` write the sparse matrix values\n function g!(du,u,p,t)\n du[1,1] = p[3][1,1]\n du[2,2] = p[3][2,2]\n end\n\n function gstepvec!(dx, _, u, p, t, dw, _)\n dx .+= diag(p[3]).*dw\n end\n\n function gstep!(dx, _, u, p, t, dw, _)\n dx .+= p[3]*dw\n end\n\n # Define a sparse matrix by making a dense matrix and setting some values as not zero\n A = zeros(2,2)\n A[1,1] = 1\n A[2,2] = 1\n A = sparse(A)\n\n # time range\n tstart = 0.0\n tend = 1.0\n dt = 0.02\n trange = tstart:dt:tend\n\n # define kernels\n k1 = MSDE.SDEKernel(f,gvec,trange,θlin)\n k2 = MSDE.SDEKernel(f,g,trange,θlin,Σ(θlin))\n k3 = MSDE.SDEKernel(f!,g!,trange,θlin,A)\n k4 = MSDE.SDEKernel(Mitosis.AffineMap(θlin[1], θlin[2]), Mitosis.ConstantMap(θlin[3]), trange, θlin, Σ(θlin))\n k5 = MSDE.SDEKernel!(f!,gvec!,gstepvec!,trange,θlin; ws = copy(u0))\n k6 = MSDE.SDEKernel!(f!,g!,gstep!,trange,θlin,A; ws = copy(A))\n\n @testset \"StochasticDiffEq EM() solver\" begin\n uend1, (ts1, u1, noise1) = MSDE.sample(k1, u0, EM(false), save_noise=true)\n NG = NoiseGrid(ts1, noise1)\n Z = pCN(NG, 1.0)\n uend2, (ts2, u2, noise2) = MSDE.sample(k2, u0, EM(false), Z, save_noise=true)\n Z = pCN(NG, 1.0)\n uend3, (ts3, u3, noise3) = MSDE.sample(k3, u0, EM(false), Z)\n Z = pCN(NG, 1.0)\n uend4, (ts4, u4, noise4) = MSDE.sample(k4, u0, EM(false), Z)\n Z = pCN(NG, 1.0)\n uend5, (ts5, u5, noise5) = MSDE.sample(k5, u0, EM(false), Z)\n Z = pCN(NG, 1.0)\n uend6, (ts6, u6, noise6) = MSDE.sample(k6, u0, EM(false), Z)\n\n #@show solend1\n @test isapprox(u1, u2, atol=1e-12)\n @test isapprox(uend1, uend2, atol=1e-12)\n @test isapprox(u1, u3, atol=1e-12)\n @test isapprox(uend1, uend3, atol=1e-12)\n @test isapprox(u1, u4, atol=1e-12)\n @test isapprox(uend1, uend4, atol=1e-12)\n @test isapprox(u1, u5, atol=1e-12)\n @test isapprox(uend1, uend5, atol=1e-12)\n @test isapprox(u1, u6, atol=1e-12)\n @test isapprox(uend1, uend6, atol=1e-12)\n end\n\n @testset \"internal solver\" begin\n @testset \"without passing a noise\" begin\n Random.seed!(seed)\n uend1, (ts1, u1, noise1) = MSDE.sample(k1, u0, MSDE.EulerMaruyama!(), save=true)\n Random.seed!(seed)\n uend2, (ts2, u2, noise2) = MSDE.sample(k2, u0, MSDE.EulerMaruyama!(), save=true)\n Random.seed!(seed)\n # inplace must be written out manually\n @test_broken uend3, (ts3, u3, noise3) = MSDE.sample(k3, u0, MSDE.EulerMaruyama!(), save=true)\n Random.seed!(seed)\n uend4, (ts4, u4, noise4) = MSDE.sample(k4, u0, MSDE.EulerMaruyama!(), save=true)\n Random.seed!(seed)\n uend5, (ts5, u5, noise5) = MSDE.sample(k5, u0, MSDE.EulerMaruyama!(), save=true)\n Random.seed!(seed)\n uend6, (ts6, u6, noise6) = MSDE.sample(k6, u0, MSDE.EulerMaruyama!(), save=true)\n\n @test length(ts1) == length(trange)\n @test ts1[end] == trange[end]\n @test uend1 == uend2\n @test_broken uend1 == uend3\n @test uend1 == uend4\n @test uend1 == uend5\n @test uend1 == uend6\n\n Random.seed!(seed)\n uend7, (ts7, u7, noise7) = MSDE.sample(k1, u0, MSDE.EulerMaruyama!(), save=false)\n @test uend1 == uend7\n @test u7 === nothing\n end\n\n @testset \"passing a noise grid\" begin\n # pass noise process and compare with EM()\n Ws = cumsum([[zero(u0)];[sqrt(trange[i+1]-ti)*randn(size(u0))\n for (i,ti) in enumerate(trange[1:end-1])]])\n NG = NoiseGrid(trange,Ws)\n\n uendEM, (tsEM, uEM, noiseEM) = MSDE.sample(k1, u0, EM(false), NG)\n uend1, (ts1, u1, noise1) = MSDE.sample(k1, u0, MSDE.EulerMaruyama!(), NG)\n uend2, (ts2, u2, noise2) = MSDE.sample(k2, u0, MSDE.EulerMaruyama!(), NG)\n @test_broken uend3, (ts3, u3, noise3) = MSDE.sample(k3, u0, MSDE.EulerMaruyama!(), NG)\n uend4, (ts4, u4, noise4) = MSDE.sample(k4, u0, MSDE.EulerMaruyama!(), NG)\n uend5, (ts5, u5, noise5) = MSDE.sample(k5, u0, MSDE.EulerMaruyama!(), NG)\n uend6, (ts6, u6, noise6) = MSDE.sample(k6, u0, MSDE.EulerMaruyama!(), NG)\n\n @test u1 ≈ uEM rtol=1e-12\n @test uendEM ≈ uend1 rtol=1e-12\n @test uendEM ≈ uend2 rtol=1e-12\n @test_broken uendEM ≈ uend3 rtol=1e-12\n @test uendEM ≈ uend4 rtol=1e-12\n @test uendEM ≈ uend5 rtol=1e-12\n @test uendEM ≈ uend6 rtol=1e-12\n end\n\n @testset \"passing the noise values\" begin\n # pass noise process and compare with EM()\n Ws = cumsum([[zero(u0)];[sqrt(trange[i+1]-ti)*randn(size(u0))\n for (i,ti) in enumerate(trange[1:end-1])]])\n NG = NoiseGrid(trange,Ws)\n\n uendEM, (tsEM, uEM, noiseEM) = MSDE.sample(k1, u0, EM(false), NG)\n uend1, (ts1, u1, noise1) = MSDE.sample(k1, u0, MSDE.EulerMaruyama!(), Ws)\n uend2, (ts2, u2, noise2) = MSDE.sample(k2, u0, MSDE.EulerMaruyama!(), Ws)\n @test_broken uend3, (ts3, u3, noise3) = MSDE.sample(k3, u0, MSDE.EulerMaruyama!(), Ws)\n uend4, (ts4, u4, noise4) = MSDE.sample(k4, u0, MSDE.EulerMaruyama!(), Ws)\n uend5, (ts5, u5, noise5) = MSDE.sample(k5, u0, MSDE.EulerMaruyama!(), Ws)\n uend6, (ts6, u6, noise6) = MSDE.sample(k6, u0, MSDE.EulerMaruyama!(), Ws)\n\n @test u1 ≈ uEM rtol=1e-12\n @test uendEM ≈ uend1 rtol=1e-12\n @test uendEM ≈ uend2 rtol=1e-12\n @test_broken uendEM ≈ uend3 rtol=1e-12\n @test uendEM ≈ uend4 rtol=1e-12\n @test uendEM ≈ uend5 rtol=1e-12\n @test uendEM ≈ uend6 rtol=1e-12\n end\n\n @testset \"custom P\" begin\n # checks that defining and passing P manually works\n\n struct customP{θType}\n θ::θType\n end\n\n function MSDE.tangent!(du, u, dz, P::customP)\n du[3] .= (P.θ[1]*u[3]+P.θ[2])*dz[2] + P.θ[3]*dz[3]\n\n (dz[1], dz[2], du[3])\n end\n\n function MSDE.exponential_map!(u, du, P::customP)\n x = u[3]\n @. x += du[3]\n (u[1] + du[1], u[2] + du[2], x)\n end\n\n # pass noise process and compare with EM()\n Ws = cumsum([[zero(u0)];[sqrt(trange[i+1]-ti)*randn(size(u0))\n for (i,ti) in enumerate(trange[1:end-1])]])\n NG = NoiseGrid(trange,Ws)\n\n uendEM, (tsEM, uEM, noiseEM) = MSDE.sample(k1, u0, EM(false), NG)\n uend1, (ts1, u1, noise1) = MSDE.sample(k1, u0, MSDE.EulerMaruyama!(), Ws, P=customP(θlin))\n uend2, (ts2, u2, noise2) = MSDE.sample(k2, u0, MSDE.EulerMaruyama!(), Ws, P=customP(θlin))\n uend3, (ts3, u3, noise3) = MSDE.sample(k3, u0, MSDE.EulerMaruyama!(), Ws, P=customP(θlin))\n uend4, (ts4, u4, noise4) = MSDE.sample(k4, u0, MSDE.EulerMaruyama!(), Ws)\n uend5, (ts5, u5, noise5) = MSDE.sample(k5, u0, MSDE.EulerMaruyama!(), Ws)\n uend6, (ts6, u6, noise6) = MSDE.sample(k6, u0, MSDE.EulerMaruyama!(), Ws)\n\n @test u1 ≈ uEM rtol=1e-12\n @test uendEM ≈ uend1 rtol=1e-12\n @test uendEM ≈ uend2 rtol=1e-12\n @test uendEM ≈ uend3 rtol=1e-12\n @test uendEM ≈ uend4 rtol=1e-12\n @test uendEM ≈ uend5 rtol=1e-12\n @test uendEM ≈ uend6 rtol=1e-12\n end\n\n end\nend"
] |
f79bc25a4211811480a39c93622746f15296898e
| 30,461
|
jl
|
Julia
|
test/reflection.jl
|
rfourquet/julia
|
18674303bdfb5670f3bd36dd0e6ba0e6cf2bcd8b
|
[
"Zlib"
] | 1
|
2020-08-14T16:07:35.000Z
|
2020-08-14T16:07:35.000Z
|
test/reflection.jl
|
rfourquet/julia
|
18674303bdfb5670f3bd36dd0e6ba0e6cf2bcd8b
|
[
"Zlib"
] | null | null | null |
test/reflection.jl
|
rfourquet/julia
|
18674303bdfb5670f3bd36dd0e6ba0e6cf2bcd8b
|
[
"Zlib"
] | null | null | null |
# This file is a part of Julia. License is MIT: https://julialang.org/license
using Test
# code_native / code_llvm (issue #8239)
# It's hard to really test these, but just running them should be
# sufficient to catch segfault bugs.
module ReflectionTest
using Test, Random
function test_ir_reflection(freflect, f, types)
@test !isempty(freflect(f, types))
nothing
end
function test_bin_reflection(freflect, f, types)
iob = IOBuffer()
freflect(iob, f, types)
str = String(take!(iob))
@test !isempty(str)
nothing
end
function test_code_reflection(freflect, f, types, tester)
tester(freflect, f, types)
tester(freflect, f, (types.parameters...,))
nothing
end
function test_code_reflections(tester, freflect)
test_code_reflection(freflect, occursin,
Tuple{Regex, AbstractString}, tester) # abstract type
test_code_reflection(freflect, +, Tuple{Int, Int}, tester) # leaftype signature
test_code_reflection(freflect, +,
Tuple{Array{Float32}, Array{Float32}}, tester) # incomplete types
test_code_reflection(freflect, Module, Tuple{}, tester) # Module() constructor (transforms to call)
test_code_reflection(freflect, Array{Int64}, Tuple{Array{Int32}}, tester) # with incomplete types
test_code_reflection(freflect, muladd, Tuple{Float64, Float64, Float64}, tester)
end
test_code_reflections(test_ir_reflection, code_lowered)
test_code_reflections(test_ir_reflection, code_typed)
end # module ReflectionTest
# isbits, isbitstype
@test !isbitstype(Array{Int})
@test isbitstype(Float32)
@test isbitstype(Int)
@test !isbitstype(AbstractString)
@test isbitstype(Tuple{Int, Vararg{Int, 2}})
@test !isbitstype(Tuple{Int, Vararg{Int}})
@test !isbitstype(Tuple{Integer, Vararg{Int, 2}})
@test isbitstype(Tuple{Int, Vararg{Any, 0}})
@test isbitstype(Tuple{Vararg{Any, 0}})
@test isbits(1)
@test isbits((1,2))
@test !isbits([1])
@test isbits(nothing)
# issue #16670
@test isconcretetype(Int)
@test isconcretetype(Vector{Int})
@test isconcretetype(Tuple{Int, Vararg{Int, 2}})
@test !isconcretetype(Tuple{Any})
@test !isconcretetype(Tuple{Integer, Vararg{Int, 2}})
@test !isconcretetype(Tuple{Int, Vararg{Int}})
@test !isconcretetype(Type{Tuple{Integer, Vararg{Int}}})
@test !isconcretetype(Type{Vector})
@test !isconcretetype(Type{Int})
@test !isconcretetype(Tuple{Type{Int}})
@test isconcretetype(DataType)
@test isconcretetype(Union)
@test !isconcretetype(Union{})
@test isconcretetype(Tuple{Union{}})
@test !isconcretetype(Complex)
@test !isconcretetype(Complex.body)
@test !isconcretetype(AbstractArray{Int,1})
struct AlwaysHasLayout{T}
x
end
@test !isconcretetype(AlwaysHasLayout) && !isconcretetype(AlwaysHasLayout.body)
@test isconcretetype(AlwaysHasLayout{Any})
@test isconcretetype(Ptr{Cvoid})
@test !isconcretetype(Ptr) && !isconcretetype(Ptr.body)
# issue #10165
i10165(::Type) = 0
i10165(::Type{AbstractArray{T,n}}) where {T,n} = 1
@test i10165(AbstractArray{Int,n} where n) == 0
@test which(i10165, Tuple{Type{AbstractArray{Int,n} where n},}).sig == Tuple{typeof(i10165),Type}
# fullname
@test fullname(Base) == (:Base,)
@test fullname(Base.Iterators) == (:Base, :Iterators)
const a_const = 1
not_const = 1
@test isconst(@__MODULE__, :a_const) == true
@test isconst(Base, :pi) == true
@test isconst(@__MODULE__, :pi) == true
@test isconst(@__MODULE__, :not_const) == false
@test isconst(@__MODULE__, :is_not_defined) == false
@test ismutable(1) == false
@test ismutable([]) == true
## find bindings tests
@test ccall(:jl_get_module_of_binding, Any, (Any, Any), Base, :sin)==Base
# For curmod_*
include("testenv.jl")
module TestMod7648
using Test
import Base.convert
import ..curmod_name, ..curmod
export a9475, foo9475, c7648, foo7648, foo7648_nomethods, Foo7648
const c7648 = 8
d7648 = 9
const f7648 = 10
foo7648(x) = x
function foo7648_nomethods end
mutable struct Foo7648 end
module TestModSub9475
using Test
using ..TestMod7648
import ..curmod_name
export a9475, foo9475
a9475 = 5
b9475 = 7
foo9475(x) = x
let
@test Base.binding_module(@__MODULE__, :a9475) == @__MODULE__
@test Base.binding_module(@__MODULE__, :c7648) == TestMod7648
@test Base.nameof(@__MODULE__) == :TestModSub9475
@test Base.fullname(@__MODULE__) == (curmod_name..., :TestMod7648, :TestModSub9475)
@test Base.parentmodule(@__MODULE__) == TestMod7648
end
end # module TestModSub9475
using .TestModSub9475
let
@test Base.binding_module(@__MODULE__, :d7648) == @__MODULE__
@test Base.binding_module(@__MODULE__, :a9475) == TestModSub9475
@test Base.nameof(@__MODULE__) == :TestMod7648
@test Base.parentmodule(@__MODULE__) == curmod
end
end # module TestMod7648
let
@test Base.binding_module(TestMod7648, :d7648) == TestMod7648
@test Base.binding_module(TestMod7648, :a9475) == TestMod7648.TestModSub9475
@test Base.binding_module(TestMod7648.TestModSub9475, :b9475) == TestMod7648.TestModSub9475
@test Set(names(TestMod7648))==Set([:TestMod7648, :a9475, :foo9475, :c7648, :foo7648, :foo7648_nomethods, :Foo7648])
@test Set(names(TestMod7648, all = true)) == Set([:TestMod7648, :TestModSub9475, :a9475, :foo9475, :c7648, :d7648, :f7648,
:foo7648, Symbol("#foo7648"), :foo7648_nomethods, Symbol("#foo7648_nomethods"),
:Foo7648, :eval, Symbol("#eval"), :include, Symbol("#include")])
@test Set(names(TestMod7648, all = true, imported = true)) == Set([:TestMod7648, :TestModSub9475, :a9475, :foo9475, :c7648, :d7648, :f7648,
:foo7648, Symbol("#foo7648"), :foo7648_nomethods, Symbol("#foo7648_nomethods"),
:Foo7648, :eval, Symbol("#eval"), :include, Symbol("#include"),
:convert, :curmod_name, :curmod])
@test isconst(TestMod7648, :c7648)
@test !isconst(TestMod7648, :d7648)
end
let
using .TestMod7648
@test Base.binding_module(@__MODULE__, :a9475) == TestMod7648.TestModSub9475
@test Base.binding_module(@__MODULE__, :c7648) == TestMod7648
@test nameof(foo7648) == :foo7648
@test parentmodule(foo7648, (Any,)) == TestMod7648
@test parentmodule(foo7648) == TestMod7648
@test parentmodule(foo7648_nomethods) == TestMod7648
@test parentmodule(foo9475, (Any,)) == TestMod7648.TestModSub9475
@test parentmodule(foo9475) == TestMod7648.TestModSub9475
@test parentmodule(Foo7648) == TestMod7648
@test nameof(Foo7648) == :Foo7648
@test basename(functionloc(foo7648, (Any,))[1]) == "reflection.jl"
@test first(methods(TestMod7648.TestModSub9475.foo7648)) == which(foo7648, (Int,))
@test TestMod7648 == which(@__MODULE__, :foo7648)
@test TestMod7648.TestModSub9475 == which(@__MODULE__, :a9475)
end
@test_throws ArgumentError("argument is not a generic function") which(===, Tuple{Int, Int})
@test_throws ArgumentError("argument is not a generic function") code_typed(===, Tuple{Int, Int})
@test_throws ArgumentError("argument is not a generic function") Base.return_types(===, Tuple{Int, Int})
module TestingExported
using Test
include("testenv.jl") # for curmod_str
import Base.isexported
global this_is_not_defined
export this_is_not_defined
@test_throws ErrorException("\"this_is_not_defined\" is not defined in module Main") which(Main, :this_is_not_defined)
@test_throws ErrorException("\"this_is_not_exported\" is not defined in module Main") which(Main, :this_is_not_exported)
@test isexported(@__MODULE__, :this_is_not_defined)
@test !isexported(@__MODULE__, :this_is_not_exported)
const a_value = 1
@test which(@__MODULE__, :a_value) === @__MODULE__
@test_throws ErrorException("\"a_value\" is not defined in module Main") which(Main, :a_value)
@test which(Main, :Core) === Main
@test !isexported(@__MODULE__, :a_value)
end
# PR 13825
let ex = :(a + b)
@test string(ex) == "a + b"
end
foo13825(::Array{T, N}, ::Array, ::Vector) where {T, N} = nothing
@test startswith(string(first(methods(foo13825))),
"foo13825(::Array{T,N}, ::Array, ::Array{T,1} where T)")
mutable struct TLayout
x::Int8
y::Int16
z::Int32
end
tlayout = TLayout(5,7,11)
@test fieldnames(TLayout) == (:x, :y, :z) == Base.propertynames(tlayout)
@test hasfield(TLayout, :y)
@test !hasfield(TLayout, :a)
@test hasproperty(tlayout, :x)
@test !hasproperty(tlayout, :p)
@test [(fieldoffset(TLayout,i), fieldname(TLayout,i), fieldtype(TLayout,i)) for i = 1:fieldcount(TLayout)] ==
[(0, :x, Int8), (2, :y, Int16), (4, :z, Int32)]
@test fieldnames(Complex) === (:re, :im)
@test_throws BoundsError fieldtype(TLayout, 0)
@test_throws ArgumentError fieldname(TLayout, 0)
@test_throws BoundsError fieldoffset(TLayout, 0)
@test_throws BoundsError fieldtype(TLayout, 4)
@test_throws ArgumentError fieldname(TLayout, 4)
@test_throws BoundsError fieldoffset(TLayout, 4)
@test fieldtype(Tuple{Vararg{Int8}}, 1) === Int8
@test fieldtype(Tuple{Vararg{Int8}}, 10) === Int8
@test_throws BoundsError fieldtype(Tuple{Vararg{Int8}}, 0)
# issue #30505
@test fieldtype(Union{Tuple{Char},Tuple{Char,Char}},2) === Char
@test_throws BoundsError fieldtype(Union{Tuple{Char},Tuple{Char,Char}},3)
@test fieldnames(NTuple{3, Int}) == ntuple(i -> fieldname(NTuple{3, Int}, i), 3) == (1, 2, 3)
@test_throws ArgumentError fieldnames(Union{})
@test_throws BoundsError fieldname(NTuple{3, Int}, 0)
@test_throws BoundsError fieldname(NTuple{3, Int}, 4)
@test fieldnames(NamedTuple{(:z,:a)}) === (:z,:a)
@test fieldname(NamedTuple{(:z,:a)}, 1) === :z
@test fieldname(NamedTuple{(:z,:a)}, 2) === :a
@test_throws ArgumentError fieldname(NamedTuple{(:z,:a)}, 3)
@test_throws ArgumentError fieldnames(NamedTuple)
@test_throws ArgumentError fieldnames(NamedTuple{T,Tuple{Int,Int}} where T)
@test_throws ArgumentError fieldnames(Real)
@test_throws ArgumentError fieldnames(AbstractArray)
@test fieldtype((NamedTuple{T,Tuple{Int,String}} where T), 1) === Int
@test fieldtype((NamedTuple{T,Tuple{Int,String}} where T), 2) === String
@test_throws BoundsError fieldtype((NamedTuple{T,Tuple{Int,String}} where T), 3)
@test fieldtype(NamedTuple, 42) === Any
@test_throws BoundsError fieldtype(NamedTuple, 0)
@test_throws BoundsError fieldtype(NamedTuple, -1)
@test fieldtype(NamedTuple{(:a,:b)}, 1) === Any
@test fieldtype(NamedTuple{(:a,:b)}, 2) === Any
@test fieldtype((NamedTuple{(:a,:b),T} where T<:Tuple{Vararg{Integer}}), 2) === Integer
@test_throws BoundsError fieldtype(NamedTuple{(:a,:b)}, 3)
# issue #32697
@test fieldtype(NamedTuple{(:x,:y), T} where T <: Tuple{Int, Union{Float64, Missing}}, :x) == Int
@test fieldtype(NamedTuple{(:x,:y), T} where T <: Tuple{Int, Union{Float64, Missing}}, :y) == Union{Float64, Missing}
@test fieldtypes(NamedTuple{(:a,:b)}) == (Any, Any)
@test fieldtypes((NamedTuple{T,Tuple{Int,String}} where T)) === (Int, String)
@test fieldtypes(TLayout) === (Int8, Int16, Int32)
import Base: datatype_alignment, return_types
@test datatype_alignment(UInt16) == 2
@test datatype_alignment(TLayout) == 4
let rts = return_types(TLayout)
@test length(rts) == 2 # general constructor and specific constructor
@test all(rts .== TLayout)
end
# issue #15447
f15447_line = @__LINE__() + 1
@noinline function f15447(s, a)
if s
return a
else
nb = 0
return nb
end
end
@test functionloc(f15447)[2] == f15447_line
# issue #14346
@noinline function f14346(id, mask, limit)
if id <= limit && mask[id]
return true
end
end
@test functionloc(f14346)[2] == @__LINE__() - 5
# issue #15714
# show variable names for slots and suppress spurious type warnings
function f15714(array_var15714)
for index_var15714 in eachindex(array_var15714)
array_var15714[index_var15714] += 0
end
end
function g15714(array_var15714)
for index_var15714 in eachindex(array_var15714)
array_var15714[index_var15714] += 0
end
let index_var15714
for outer index_var15714 in eachindex(array_var15714)
array_var15714[index_var15714] += 0
end
index_var15714
end
let index_var15714
for outer index_var15714 in eachindex(array_var15714)
array_var15714[index_var15714] += 0
end
index_var15714
end
end
import InteractiveUtils.code_warntype
used_dup_var_tested15714 = false
used_unique_var_tested15714 = false
function test_typed_ir_printing(Base.@nospecialize(f), Base.@nospecialize(types), must_used_vars)
src, rettype = code_typed(f, types, optimize=false)[1]
dupnames = Set()
slotnames = Set()
for name in src.slotnames
if name in slotnames || name === Symbol("")
push!(dupnames, name)
else
push!(slotnames, name)
end
end
# Make sure must_used_vars are in slotnames
for name in must_used_vars
@test name in slotnames
end
must_used_checked = Dict{Symbol,Bool}()
for sym in must_used_vars
must_used_checked[sym] = false
end
for str in (sprint(io -> code_warntype(io, f, types, optimize=false)),
repr("text/plain", src))
for var in must_used_vars
@test occursin(string(var), str)
end
# Check that we are not printing the bare slot numbers
for i in 1:length(src.slotnames)
name = src.slotnames[i]
if name in dupnames
if name in must_used_vars && occursin(Regex("_$i\\b"), str)
must_used_checked[name] = true
global used_dup_var_tested15714 = true
end
else
@test !occursin(Regex("_$i\\b"), str)
if name in must_used_vars
global used_unique_var_tested15714 = true
end
end
end
end
for sym in must_used_vars
if sym in dupnames
@test must_used_checked[sym]
end
must_used_checked[sym] = false
end
# Make sure printing an AST outside CodeInfo still works.
str = sprint(show, src.code)
# Check that we are printing the slot numbers when we don't have the context
# Use the variable names that we know should be present in the optimized AST
for i in 2:length(src.slotnames)
name = src.slotnames[i]
if name in must_used_vars && occursin(Regex("_$i\\b"), str)
must_used_checked[name] = true
end
end
for sym in must_used_vars
@test must_used_checked[sym]
end
end
test_typed_ir_printing(f15714, Tuple{Vector{Float32}},
[:array_var15714, :index_var15714])
test_typed_ir_printing(g15714, Tuple{Vector{Float32}},
[:array_var15714, :index_var15714])
#This test doesn't work with the new optimizer because we drop slotnames
#We may want to test it against debug info eventually
#@test used_dup_var_tested15715
@test used_unique_var_tested15714
let li = typeof(fieldtype).name.mt.cache.func::Core.MethodInstance,
lrepr = string(li),
mrepr = string(li.def),
lmime = repr("text/plain", li),
mmime = repr("text/plain", li.def)
@test lrepr == lmime == "MethodInstance for fieldtype(...)"
@test mrepr == mmime == "fieldtype(...) in Core"
end
# Linfo Tracing test
function tracefoo end
# Method Tracing test
methtracer(x::Ptr{Cvoid}) = (@test isa(unsafe_pointer_to_objref(x), Method); global didtrace = true; nothing)
let cmethtracer = @cfunction(methtracer, Cvoid, (Ptr{Cvoid},))
ccall(:jl_register_newmeth_tracer, Cvoid, (Ptr{Cvoid},), cmethtracer)
end
didtrace = false
tracefoo2(x, y) = x*y
@test didtrace
didtrace = false
tracefoo(x::Int64, y::Int64) = x*y
@test didtrace
didtrace = false
ccall(:jl_register_newmeth_tracer, Cvoid, (Ptr{Cvoid},), C_NULL)
# test for reflection over large method tables
for i = 1:100; @eval fLargeTable(::Val{$i}, ::Any) = 1; end
for i = 1:100; @eval fLargeTable(::Any, ::Val{$i}) = 2; end
fLargeTable(::Any...) = 3
@test length(methods(fLargeTable, Tuple{})) == 1
fLargeTable(::Complex, ::Complex) = 4
fLargeTable(::Union{ComplexF32, ComplexF64}...) = 5
@test length(methods(fLargeTable, Tuple{})) == 1
fLargeTable() = 4
@test length(methods(fLargeTable)) == 204
@test length(methods(fLargeTable, Tuple{})) == 1
@test fLargeTable(1im, 2im) == 4
@test fLargeTable(1.0im, 2.0im) == 5
@test_throws MethodError fLargeTable(Val(1), Val(1))
@test fLargeTable(Val(1), 1) == 1
@test fLargeTable(1, Val(1)) == 2
# issue #15280
function f15280(x) end
@test functionloc(f15280)[2] > 0
# bug found in #16850, Base.url with backslashes on Windows
function module_depth(from::Module, to::Module)
if from === to || parentmodule(to) === to
return 0
else
return 1 + module_depth(from, parentmodule(to))
end
end
function has_backslashes(mod::Module)
for n in names(mod, all = true, imported = true)
isdefined(mod, n) || continue
Base.isdeprecated(mod, n) && continue
f = getfield(mod, n)
if isa(f, Module) && module_depth(Main, f) <= module_depth(Main, mod)
continue
end
h = has_backslashes(f)
h === nothing || return h
end
return nothing
end
function has_backslashes(f::Function)
for m in methods(f)
h = has_backslashes(m)
h === nothing || return h
end
return nothing
end
function has_backslashes(meth::Method)
if '\\' in string(meth.file)
return meth
else
return nothing
end
end
has_backslashes(x) = nothing
h16850 = has_backslashes(Base)
if Sys.iswindows()
if h16850 === nothing
@warn """No methods found in Base with backslashes in file name,
skipping test for `Base.url`"""
else
@test !('\\' in Base.url(h16850))
end
else
@test h16850 === nothing
end
# PR #18888: code_typed shouldn't cache, return_types should
f18888() = nothing
let
world = Core.Compiler.get_world_counter()
m = first(methods(f18888, Tuple{}))
@test isempty(m.specializations)
ft = typeof(f18888)
code_typed(f18888, Tuple{}; optimize=false)
@test !isempty(m.specializations) # uncached, but creates the specializations entry
mi = Core.Compiler.specialize_method(m, Tuple{ft}, Core.svec())
@test Core.Compiler.inf_for_methodinstance(mi, world) === nothing
@test !isdefined(mi, :cache)
code_typed(f18888, Tuple{}; optimize=true)
@test !isdefined(mi, :cache)
Base.return_types(f18888, Tuple{})
@test Core.Compiler.inf_for_methodinstance(mi, world) === mi.cache
@test mi.cache isa Core.CodeInstance
@test !isdefined(mi.cache, :next)
end
# New reflection methods in 0.6
struct ReflectionExample{T<:AbstractFloat, N}
x::Tuple{T, N}
end
@test !isabstracttype(Union{})
@test !isabstracttype(Union{Int,Float64})
@test isabstracttype(AbstractArray)
@test isabstracttype(AbstractSet{Int})
@test !isabstracttype(ReflectionExample)
@test !isabstracttype(Int)
@test !isabstracttype(TLayout)
@test !isprimitivetype(Union{})
@test !isprimitivetype(Union{Int,Float64})
@test !isprimitivetype(AbstractArray)
@test !isprimitivetype(AbstractSet{Int})
@test !isprimitivetype(ReflectionExample)
@test isprimitivetype(Int)
@test !isprimitivetype(TLayout)
@test !isstructtype(Union{})
@test !isstructtype(Union{Int,Float64})
@test !isstructtype(AbstractArray)
@test !isstructtype(AbstractSet{Int})
@test isstructtype(ReflectionExample)
@test !isstructtype(Int)
@test isstructtype(TLayout)
@test Base.parameter_upper_bound(ReflectionExample, 1) === AbstractFloat
@test Base.parameter_upper_bound(ReflectionExample, 2) === Any
@test Base.parameter_upper_bound(ReflectionExample{T, N} where T where N <: Real, 2) === Real
let
wrapperT(T) = Base.typename(T).wrapper
@test @inferred wrapperT(ReflectionExample{Float64, Int64}) == ReflectionExample
@test @inferred wrapperT(ReflectionExample{Float64, N} where N) == ReflectionExample
@test @inferred wrapperT(ReflectionExample{T, Int64} where T) == ReflectionExample
@test @inferred wrapperT(ReflectionExample) == ReflectionExample
@test @inferred wrapperT(Union{ReflectionExample{Union{},1},ReflectionExample{Float64,1}}) == ReflectionExample
@test_throws(ErrorException("typename does not apply to unions whose components have different typenames"),
Base.typename(Union{Int, Float64}))
end
# sizeof and nfields
@test sizeof(Int16) == 2
@test sizeof(ComplexF64) == 16
primitive type ParameterizedByte__{A,B} 8 end
@test sizeof(ParameterizedByte__) == 1
@test sizeof(nothing) == 0
@test sizeof(()) == 0
struct TypeWithIrrelevantParameter{T}
x::Int32
end
@test sizeof(TypeWithIrrelevantParameter) == sizeof(Int32)
@test sizeof(TypeWithIrrelevantParameter{Int8}) == sizeof(Int32)
@test sizeof(:abc) == 3
@test sizeof(Symbol("")) == 0
@test_throws(ErrorException("Abstract type Real does not have a definite size."),
sizeof(Real))
@test sizeof(Union{ComplexF32,ComplexF64}) == 16
@test sizeof(Union{Int8,UInt8}) == 1
@test_throws ErrorException sizeof(AbstractArray)
@test_throws ErrorException sizeof(Tuple)
@test_throws ErrorException sizeof(Tuple{Any,Any})
@test_throws ErrorException sizeof(String)
@test_throws ErrorException sizeof(Vector{Int})
@test_throws ErrorException sizeof(Symbol)
@test_throws ErrorException sizeof(Core.SimpleVector)
@test_throws ErrorException sizeof(Union{})
@test nfields((1,2)) == 2
@test nfields(()) == 0
@test nfields(nothing) == fieldcount(Nothing) == 0
@test nfields(1) == 0
@test_throws ArgumentError fieldcount(Union{})
@test fieldcount(Tuple{Any,Any,T} where T) == 3
@test fieldcount(Complex) == fieldcount(ComplexF32) == 2
@test fieldcount(Union{ComplexF32,ComplexF64}) == 2
@test fieldcount(Int) == 0
@test_throws(ArgumentError("type does not have a definite number of fields"),
fieldcount(Union{Complex,Pair}))
@test_throws ArgumentError fieldcount(Real)
@test_throws ArgumentError fieldcount(AbstractArray)
@test_throws ArgumentError fieldcount(Tuple{Any,Vararg{Any}})
# PR #22979
function test_similar_codeinfo(a, b)
@test a.code == b.code
@test a.slotnames == b.slotnames
@test a.slotflags == b.slotflags
end
@generated f22979(x...) = (y = 1; :(x[1] + x[2]))
let
x22979 = (1, 2.0, 3.0 + im)
T22979 = Tuple{typeof(f22979), typeof.(x22979)...}
world = Core.Compiler.get_world_counter()
mtypes, msp, m = Base._methods_by_ftype(T22979, -1, world)[1]
instance = Core.Compiler.specialize_method(m, mtypes, msp)
cinfo_generated = Core.Compiler.get_staged(instance)
@test_throws ErrorException Base.uncompressed_ir(m)
test_similar_codeinfo(code_lowered(f22979, typeof(x22979))[1], cinfo_generated)
cinfos = code_lowered(f22979, typeof.(x22979), generated=true)
@test length(cinfos) == 1
cinfo = cinfos[1]
test_similar_codeinfo(cinfo, cinfo_generated)
@test_throws ErrorException code_lowered(f22979, typeof.(x22979), generated=false)
end
module MethodDeletion
using Test, Random
# Deletion after compiling top-level call
bar1(x) = 1
bar1(x::Int) = 2
foo1(x) = bar1(x)
faz1(x) = foo1(x)
@test faz1(1) == 2
@test faz1(1.0) == 1
m = first(methods(bar1, Tuple{Int}))
Base.delete_method(m)
@test bar1(1) == 1
@test bar1(1.0) == 1
@test foo1(1) == 1
@test foo1(1.0) == 1
@test faz1(1) == 1
@test faz1(1.0) == 1
# Deletion after compiling middle-level call
bar2(x) = 1
bar2(x::Int) = 2
foo2(x) = bar2(x)
faz2(x) = foo2(x)
@test foo2(1) == 2
@test foo2(1.0) == 1
m = first(methods(bar2, Tuple{Int}))
Base.delete_method(m)
@test bar2(1.0) == 1
@test bar2(1) == 1
@test foo2(1) == 1
@test foo2(1.0) == 1
@test faz2(1) == 1
@test faz2(1.0) == 1
# Deletion after compiling low-level call
bar3(x) = 1
bar3(x::Int) = 2
foo3(x) = bar3(x)
faz3(x) = foo3(x)
@test bar3(1) == 2
@test bar3(1.0) == 1
m = first(methods(bar3, Tuple{Int}))
Base.delete_method(m)
@test bar3(1) == 1
@test bar3(1.0) == 1
@test foo3(1) == 1
@test foo3(1.0) == 1
@test faz3(1) == 1
@test faz3(1.0) == 1
# Deletion before any compilation
bar4(x) = 1
bar4(x::Int) = 2
foo4(x) = bar4(x)
faz4(x) = foo4(x)
m = first(methods(bar4, Tuple{Int}))
Base.delete_method(m)
@test bar4(1) == 1
@test bar4(1.0) == 1
@test foo4(1) == 1
@test foo4(1.0) == 1
@test faz4(1) == 1
@test faz4(1.0) == 1
# Methods with keyword arguments
fookw(x; direction=:up) = direction
fookw(y::Int) = 2
@test fookw("string") == :up
@test fookw(1) == 2
m = collect(methods(fookw))[2]
Base.delete_method(m)
@test fookw(1) == 2
@test_throws MethodError fookw("string")
# functions with many methods
types = (Float64, Int32, String)
for T1 in types, T2 in types, T3 in types
@eval foomany(x::$T1, y::$T2, z::$T3) = y
end
@test foomany(Int32(5), "hello", 3.2) == "hello"
m = first(methods(foomany, Tuple{Int32, String, Float64}))
Base.delete_method(m)
@test_throws MethodError foomany(Int32(5), "hello", 3.2)
struct EmptyType end
Base.convert(::Type{EmptyType}, x::Integer) = EmptyType()
m = first(methods(convert, Tuple{Type{EmptyType}, Integer}))
Base.delete_method(m)
@test_throws MethodError convert(EmptyType, 1)
# parametric methods
parametric(A::Array{T,N}, i::Vararg{Int,N}) where {T,N} = N
@test parametric(rand(2,2), 1, 1) == 2
m = first(methods(parametric))
Base.delete_method(m)
@test_throws MethodError parametric(rand(2,2), 1, 1)
# Deletion and ambiguity detection
foo(::Int, ::Int) = 1
foo(::Real, ::Int) = 2
foo(::Int, ::Real) = 3
@test all(map(g->g.ambig==nothing, methods(foo)))
Base.delete_method(first(methods(foo)))
@test !all(map(g->g.ambig==nothing, methods(foo)))
@test_throws MethodError foo(1, 1)
foo(::Int, ::Int) = 1
foo(1, 1)
@test map(g->g.ambig==nothing, methods(foo)) == [true, false, false]
Base.delete_method(first(methods(foo)))
@test_throws MethodError foo(1, 1)
@test map(g->g.ambig==nothing, methods(foo)) == [false, false]
# multiple deletions and ambiguities
typeparam(::Type{T}, a::Array{T}) where T<:AbstractFloat = 1
typeparam(::Type{T}, a::Array{T}) where T = 2
for mth in collect(methods(typeparam))
Base.delete_method(mth)
end
typeparam(::Type{T}, a::AbstractArray{T}) where T<:AbstractFloat = 1
typeparam(::Type{T}, a::AbstractArray{T}) where T = 2
@test typeparam(Float64, rand(2)) == 1
@test typeparam(Int, rand(Int, 2)) == 2
# prior ambiguities (issue #28899)
uambig(::Union{Int,Nothing}) = 1
uambig(::Union{Float64,Nothing}) = 2
@test uambig(1) == 1
@test uambig(1.0) == 2
@test_throws MethodError uambig(nothing)
m = which(uambig, Tuple{Int})
Base.delete_method(m)
@test_throws MethodError uambig(1)
@test uambig(1.0) == 2
@test uambig(nothing) == 2
end
module HasmethodKwargs
using Test
f(x::Int; y=3) = x + y
@test hasmethod(f, Tuple{Int})
@test hasmethod(f, Tuple{Int}, ())
@test hasmethod(f, Tuple{Int}, (:y,))
@test !hasmethod(f, Tuple{Int}, (:jeff,))
@test !hasmethod(f, Tuple{Int}, (:y,), world=typemin(UInt))
g(; b, c, a) = a + b + c
h(; kwargs...) = 4
for gh = (g, h)
@test hasmethod(gh, Tuple{})
@test hasmethod(gh, Tuple{}, ())
@test hasmethod(gh, Tuple{}, (:a,))
@test hasmethod(gh, Tuple{}, (:a, :b))
@test hasmethod(gh, Tuple{}, (:a, :b, :c))
end
@test !hasmethod(g, Tuple{}, (:a, :b, :c, :d))
@test hasmethod(h, Tuple{}, (:a, :b, :c, :d))
end
# issue #31353
function f31353(f, x::Array{<:Dict})
end
@test hasmethod(f31353, Tuple{Any, Array{D}} where D<:Dict)
@test !hasmethod(f31353, Tuple{Any, Array{D}} where D<:AbstractDict)
# issue #26267
module M26267
import Test
foo(x) = x
end
@test !(:Test in names(M26267, all=true, imported=false))
@test :Test in names(M26267, all=true, imported=true)
@test :Test in names(M26267, all=false, imported=true)
# issue #20872
f20872(::Val{N}, ::Val{N}) where {N} = true
f20872(::Val, ::Val) = false
@test which(f20872, Tuple{Val{N},Val{N}} where N).sig == Tuple{typeof(f20872), Val{N}, Val{N}} where N
@test which(f20872, Tuple{Val,Val}).sig == Tuple{typeof(f20872), Val, Val}
@test which(f20872, Tuple{Val,Val{N}} where N).sig == Tuple{typeof(f20872), Val, Val}
@test_throws ErrorException which(f20872, Tuple{Any,Val{N}} where N)
module M29962 end
# make sure checking if a binding is deprecated does not resolve it
@test !Base.isdeprecated(M29962, :sin) && !Base.isbindingresolved(M29962, :sin)
# @locals
using Base: @locals
let
local x, y
global z
@test isempty(keys(@locals))
x = 1
@test @locals() == Dict{Symbol,Any}(:x=>1)
y = ""
@test @locals() == Dict{Symbol,Any}(:x=>1,:y=>"")
for i = 8:8
@test @locals() == Dict{Symbol,Any}(:x=>1,:y=>"",:i=>8)
end
for i = 42:42
local x
@test @locals() == Dict{Symbol,Any}(:y=>"",:i=>42)
end
@test @locals() == Dict{Symbol,Any}(:x=>1,:y=>"")
x = (y,)
@test @locals() == Dict{Symbol,Any}(:x=>("",),:y=>"")
end
function _test_at_locals1(::Any, ::Any)
x = 1
@test @locals() == Dict{Symbol,Any}(:x=>1)
end
_test_at_locals1(1,1)
function _test_at_locals2(a::Any, ::Any, c::T) where T
x = 2
@test @locals() == Dict{Symbol,Any}(:x=>2,:a=>a,:c=>c,:T=>typeof(c))
end
_test_at_locals2(1,1,"")
_test_at_locals2(1,1,0.5f0)
@testset "issue #31687" begin
import InteractiveUtils._dump_function
@noinline f31687_child(i) = f31687_nonexistent(i)
f31687_parent() = f31687_child(0)
params = Base.CodegenParams()
_dump_function(f31687_parent, Tuple{},
#=native=#false, #=wrapper=#false, #=strip=#false,
#=dump_module=#true, #=syntax=#:att, #=optimize=#false, :none,
params)
end
@test nameof(Any) === :Any
@test nameof(:) === :Colon
@test nameof(Core.Intrinsics.mul_int) === :mul_int
@test nameof(Core.Intrinsics.arraylen) === :arraylen
module TestMod33403
f(x) = 1
f(x::Int) = 2
g() = 3
module Sub
import ..TestMod33403: f
f(x::Char) = 3
end
end
@testset "methods with module" begin
using .TestMod33403: f, g
@test length(methods(f)) == 3
@test length(methods(f, (Int,))) == 1
@test length(methods(f, TestMod33403)) == 2
@test length(methods(f, [TestMod33403])) == 2
@test length(methods(f, (Int,), TestMod33403)) == 1
@test length(methods(f, (Int,), [TestMod33403])) == 1
@test length(methods(f, TestMod33403.Sub)) == 1
@test length(methods(f, [TestMod33403.Sub])) == 1
@test length(methods(f, (Char,), TestMod33403.Sub)) == 1
@test length(methods(f, (Int,), TestMod33403.Sub)) == 0
@test length(methods(g, ())) == 1
end
| 33.584344
| 143
| 0.681593
|
[
"@testset \"issue #31687\" begin\n import InteractiveUtils._dump_function\n\n @noinline f31687_child(i) = f31687_nonexistent(i)\n f31687_parent() = f31687_child(0)\n params = Base.CodegenParams()\n _dump_function(f31687_parent, Tuple{},\n #=native=#false, #=wrapper=#false, #=strip=#false,\n #=dump_module=#true, #=syntax=#:att, #=optimize=#false, :none,\n params)\nend",
"@testset \"methods with module\" begin\n using .TestMod33403: f, g\n @test length(methods(f)) == 3\n @test length(methods(f, (Int,))) == 1\n\n @test length(methods(f, TestMod33403)) == 2\n @test length(methods(f, [TestMod33403])) == 2\n @test length(methods(f, (Int,), TestMod33403)) == 1\n @test length(methods(f, (Int,), [TestMod33403])) == 1\n\n @test length(methods(f, TestMod33403.Sub)) == 1\n @test length(methods(f, [TestMod33403.Sub])) == 1\n @test length(methods(f, (Char,), TestMod33403.Sub)) == 1\n @test length(methods(f, (Int,), TestMod33403.Sub)) == 0\n\n @test length(methods(g, ())) == 1\nend"
] |
f7a1dcb6a6e2de828dfa43c94a4ac74f64293ff1
| 61,402
|
jl
|
Julia
|
test/React.jl
|
lucifer1004/Pluto.jl
|
bfa99933273e8b6b989759db17e114b2f9879559
|
[
"MIT"
] | 1
|
2022-02-04T17:46:20.000Z
|
2022-02-04T17:46:20.000Z
|
test/React.jl
|
lucifer1004/Pluto.jl
|
bfa99933273e8b6b989759db17e114b2f9879559
|
[
"MIT"
] | 1
|
2022-02-28T12:50:51.000Z
|
2022-02-28T12:50:51.000Z
|
test/React.jl
|
lucifer1004/Pluto.jl
|
bfa99933273e8b6b989759db17e114b2f9879559
|
[
"MIT"
] | null | null | null |
using Test
import Pluto: Configuration, Notebook, ServerSession, ClientSession, update_run!, Cell, WorkspaceManager
import Pluto.Configuration: Options, EvaluationOptions
import Distributed
@testset "Reactivity" begin
🍭 = ServerSession()
🍭.options.evaluation.workspace_use_distributed = false
fakeclient = ClientSession(:fake, nothing)
🍭.connected_clients[fakeclient.id] = fakeclient
@testset "Basic $(parallel ? "distributed" : "single-process")" for parallel in [false, true]
🍭.options.evaluation.workspace_use_distributed = parallel
notebook = Notebook([
Cell("x = 1"),
Cell("y = x"),
Cell("f(x) = x + y"),
Cell("f(4)"),
Cell("""begin
g(a) = x
g(a,b) = y
end"""),
Cell("g(6) + g(6,6)"),
Cell("import Distributed"),
Cell("Distributed.myid()"),
])
fakeclient.connected_notebook = notebook
@test !haskey(WorkspaceManager.workspaces, notebook.notebook_id)
update_run!(🍭, notebook, notebook.cells[1:2])
@test notebook.cells[1].output.body == notebook.cells[2].output.body
@test notebook.cells[1].output.rootassignee == :x
@test notebook.cells[1].runtime !== nothing
setcode(notebook.cells[1], "x = 12")
update_run!(🍭, notebook, notebook.cells[1])
@test notebook.cells[1].output.body == notebook.cells[2].output.body
@test notebook.cells[2].runtime !== nothing
update_run!(🍭, notebook, notebook.cells[3])
@test notebook.cells[3].errored == false
@test notebook.cells[3].output.rootassignee === nothing
update_run!(🍭, notebook, notebook.cells[4])
@test notebook.cells[4].output.body == "16"
@test notebook.cells[4].errored == false
@test notebook.cells[4].output.rootassignee === nothing
setcode(notebook.cells[1], "x = 912")
update_run!(🍭, notebook, notebook.cells[1])
@test notebook.cells[4].output.body == "916"
setcode(notebook.cells[3], "f(x) = x")
update_run!(🍭, notebook, notebook.cells[3])
@test notebook.cells[4].output.body == "4"
setcode(notebook.cells[1], "x = 1")
setcode(notebook.cells[2], "y = 2")
update_run!(🍭, notebook, notebook.cells[1:2])
update_run!(🍭, notebook, notebook.cells[5:6])
@test notebook.cells[5].errored == false
@test notebook.cells[6].output.body == "3"
setcode(notebook.cells[2], "y = 1")
update_run!(🍭, notebook, notebook.cells[2])
@test notebook.cells[6].output.body == "2"
setcode(notebook.cells[1], "x = 2")
update_run!(🍭, notebook, notebook.cells[1])
@test notebook.cells[6].output.body == "3"
update_run!(🍭, notebook, notebook.cells[7:8])
@test if parallel
notebook.cells[8].output.body != string(Distributed.myid())
else
notebook.cells[8].output.body == string(Distributed.myid())
end
WorkspaceManager.unmake_workspace((🍭, notebook))
end
🍭.options.evaluation.workspace_use_distributed = false
@testset "Mutliple assignments" begin
notebook = Notebook([
Cell("x = 1"),
Cell("x = 2"),
Cell("f(x) = 3"),
Cell("f(x) = 4"),
Cell("g(x) = 5"),
Cell("g = 6"),
])
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells[1])
update_run!(🍭, notebook, notebook.cells[2])
@test occursinerror("Multiple", notebook.cells[1])
@test occursinerror("Multiple", notebook.cells[2])
setcode(notebook.cells[1], "")
update_run!(🍭, notebook, notebook.cells[1])
@test notebook.cells[1].errored == false
@test notebook.cells[2].errored == false
# https://github.com/fonsp/Pluto.jl/issues/26
setcode(notebook.cells[1], "x = 1")
update_run!(🍭, notebook, notebook.cells[1])
setcode(notebook.cells[2], "x")
update_run!(🍭, notebook, notebook.cells[2])
@test notebook.cells[1].errored == false
@test notebook.cells[2].errored == false
update_run!(🍭, notebook, notebook.cells[3])
update_run!(🍭, notebook, notebook.cells[4])
@test occursinerror("Multiple", notebook.cells[3])
@test occursinerror("Multiple", notebook.cells[4])
setcode(notebook.cells[3], "")
update_run!(🍭, notebook, notebook.cells[3])
@test notebook.cells[3].errored == false
@test notebook.cells[4].errored == false
update_run!(🍭, notebook, notebook.cells[5])
update_run!(🍭, notebook, notebook.cells[6])
@test occursinerror("Multiple", notebook.cells[5])
@test occursinerror("Multiple", notebook.cells[6])
setcode(notebook.cells[5], "")
update_run!(🍭, notebook, notebook.cells[5])
@test notebook.cells[5].errored == false
@test notebook.cells[6].errored == false
WorkspaceManager.unmake_workspace((🍭, notebook))
end
@testset "Mutliple assignments topology" begin
notebook = Notebook([
Cell("x = 1"),
Cell("z = 4 + y"),
Cell("y = x + 2"),
Cell("y = x + 3"),
])
notebook.topology = Pluto.updated_topology(notebook.topology, notebook, notebook.cells)
let topo_order = Pluto.topological_order(notebook, notebook.topology, notebook.cells[[1]])
@test indexin(topo_order.runnable, notebook.cells) == [1,2]
@test topo_order.errable |> keys == notebook.cells[[3,4]] |> Set
end
let topo_order = Pluto.topological_order(notebook, notebook.topology, notebook.cells[[1]], allow_multiple_defs=true)
@test indexin(topo_order.runnable, notebook.cells) == [1,3,4,2] # x first, y second and third, z last
# this also tests whether multiple defs run in page order
@test topo_order.errable == Dict()
end
end
# PlutoTest.jl is only working on Julia version >= 1.6
VERSION >= v"1.6" && @testset "Test Firebasey" begin
🍭.options.evaluation.workspace_use_distributed = true
file = tempname()
write(file, read(normpath(Pluto.project_relative_path("src", "webserver", "Firebasey.jl"))))
notebook = Pluto.load_notebook_nobackup(file)
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells)
# Test that the resulting file is runnable
@test jl_is_runnable(file)
# and also that Pluto can figure out the execution order on its own
@test all(noerror, notebook.cells)
WorkspaceManager.unmake_workspace((🍭, notebook))
🍭.options.evaluation.workspace_use_distributed = false
end
@testset "Pkg topology workarounds" begin
notebook = Notebook([
Cell("1 + 1"),
Cell("json([1,2])"),
Cell("using JSON"),
Cell("""Pkg.add("JSON")"""),
Cell("Pkg.activate(mktempdir())"),
Cell("import Pkg"),
Cell("using Revise"),
Cell("1 + 1"),
])
notebook.topology = Pluto.updated_topology(notebook.topology, notebook, notebook.cells)
topo_order = Pluto.topological_order(notebook, notebook.topology, notebook.cells)
@test indexin(topo_order.runnable, notebook.cells) == [6, 5, 4, 7, 3, 1, 2, 8]
# 6, 5, 4, 3 should run first (this is implemented using `cell_precedence_heuristic`), in that order
# 1, 2, 7 remain, and should run in notebook order.
# if the cells were placed in reverse order...
reverse!(notebook.cell_order)
topo_order = Pluto.topological_order(notebook, notebook.topology, notebook.cells)
@test indexin(topo_order.runnable, reverse(notebook.cells)) == [6, 5, 4, 7, 3, 8, 2, 1]
# 6, 5, 4, 3 should run first (this is implemented using `cell_precedence_heuristic`), in that order
# 1, 2, 7 remain, and should run in notebook order, which is 7, 2, 1.
reverse!(notebook.cell_order)
end
@testset "Pkg topology workarounds -- hard" begin
notebook = Notebook([
Cell("json([1,2])"),
Cell("using JSON"),
Cell("Pkg.add(package_name)"),
Cell(""" package_name = "JSON" """),
Cell("Pkg.activate(envdir)"),
Cell("envdir = mktempdir()"),
Cell("import Pkg"),
Cell("using JSON3, Revise"),
])
notebook.topology = Pluto.updated_topology(notebook.topology, notebook, notebook.cells)
topo_order = Pluto.topological_order(notebook, notebook.topology, notebook.cells)
comesbefore(A, first, second) = findfirst(isequal(first),A) < findfirst(isequal(second), A)
run_order = indexin(topo_order.runnable, notebook.cells)
# like in the previous test
@test comesbefore(run_order, 7, 5)
@test_broken comesbefore(run_order, 5, 3)
@test_broken comesbefore(run_order, 3, 2)
@test comesbefore(run_order, 2, 1)
@test comesbefore(run_order, 8, 2)
@test comesbefore(run_order, 8, 1)
# the variable dependencies
@test comesbefore(run_order, 6, 5)
@test comesbefore(run_order, 4, 3)
end
@testset "Mixed usings and reactivity" begin
notebook = Notebook([
Cell("a; using Dates"),
Cell("isleapyear(2)"),
Cell("a = 3; using LinearAlgebra"),
])
notebook.topology = Pluto.updated_topology(notebook.topology, notebook, notebook.cells)
topo_order = Pluto.topological_order(notebook, notebook.topology, notebook.cells)
run_order = indexin(topo_order.runnable, notebook.cells)
@test run_order == [3, 1, 2]
end
@testset "Reactive usings" begin
notebook = Notebook([
Cell("June"),
Cell("using Dates"),
Cell("July"),
])
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells[1:1])
@test notebook.cells[1].errored == true # this cell is before the using Dates and will error
@test notebook.cells[3].errored == false # using the position in the notebook this cell will not error
update_run!(🍭, notebook, notebook.cells[2:2])
@test notebook.cells[1].errored == false
@test notebook.cells[3].errored == false
end
@testset "Reactive usings 2" begin
notebook = Notebook([
Cell("October"),
Cell("using Dates"),
Cell("December"),
Cell(""),
])
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells)
@test notebook.cells[1].errored == false
@test notebook.cells[3].errored == false
setcode(notebook.cells[2], "")
update_run!(🍭, notebook, notebook.cells[2:2])
@test notebook.cells[1].errored == true
@test notebook.cells[3].errored == true
setcode(notebook.cells[4], "December = 13")
update_run!(🍭, notebook, notebook.cells[4:4])
@test notebook.cells[1].errored == true
@test notebook.cells[3] |> noerror
setcode(notebook.cells[2], "using Dates")
update_run!(🍭, notebook, notebook.cells[2:2])
@test notebook.cells[1] |> noerror
@test notebook.cells[3] |> noerror
@test notebook.cells[3].output.body == "13"
end
@testset "Reactive usings 3" begin
notebook = Notebook([
Cell("archive_artifact"),
Cell("using Unknown.Package"),
])
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells)
@test notebook.cells[1].errored == true
@test notebook.cells[2].errored == true
setcode(notebook.cells[2], "using Pkg.Artifacts")
update_run!(🍭, notebook, notebook.cells)
@test notebook.cells[1] |> noerror
@test notebook.cells[2] |> noerror
end
@testset "Reactive usings 4" begin
🍭.options.evaluation.workspace_use_distributed = true
notebook = Notebook([
Cell("@sprintf \"double_december = %d\" double_december"),
Cell("double_december = 2December"),
Cell("archive_artifact"),
Cell(""),
])
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells)
@test notebook.cells[1].errored == true
@test notebook.cells[2].errored == true
@test notebook.cells[3].errored == true
setcode(notebook.cells[4], "import Pkg; using Dates, Printf, Pkg.Artifacts")
update_run!(🍭, notebook, notebook.cells[4:4])
@test notebook.cells[1] |> noerror
@test notebook.cells[2] |> noerror
@test notebook.cells[3] |> noerror
@test notebook.cells[4] |> noerror
@test notebook.cells[1].output.body == "\"double_december = 24\""
WorkspaceManager.unmake_workspace((🍭, notebook))
🍭.options.evaluation.workspace_use_distributed = false
end
@testset "Reactive usings 5" begin
notebook = Notebook(Cell.([
"",
"x = ones(December * 2)",
"December = 3",
]))
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells)
@test all(noerror, notebook.cells)
setcode(notebook.cells[begin], raw"""
begin
@eval(module Hello
December = 12
export December
end)
using .Hello
end
""")
update_run!(🍭, notebook, notebook.cells[begin])
@test all(noerror, notebook.cells)
WorkspaceManager.unmake_workspace((🍭, notebook))
end
@testset "Function dependencies" begin
🍭.options.evaluation.workspace_use_distributed = true
notebook = Notebook(Cell.([
"a'b",
"import LinearAlgebra",
"LinearAlgebra.conj(b::Int) = 2b",
"a = 10",
"b = 10",
]))
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells)
@test :conj ∈ notebook.topology.nodes[notebook.cells[3]].soft_definitions
@test :conj ∈ notebook.topology.nodes[notebook.cells[1]].references
@test notebook.cells[1].output.body == "200"
WorkspaceManager.unmake_workspace((🍭, notebook))
🍭.options.evaluation.workspace_use_distributed = false
end
@testset "Function use inv in its def but also has a method on inv" begin
notebook = Notebook(Cell.([
"""
struct MyStruct
s
MyStruct(x) = new(inv(x))
end
""",
"""
Base.inv(s::MyStruct) = inv(s.s)
""",
"MyStruct(1.) |> inv"
]))
cell(idx) = notebook.cells[idx]
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells)
@test cell(1) |> noerror
@test cell(2) |> noerror
@test cell(3) |> noerror
# Empty and run cells to remove the Base overloads that we created, just to be sure
setcode.(notebook.cells, [""])
update_run!(🍭, notebook, notebook.cells)
WorkspaceManager.unmake_workspace((🍭, notebook))
end
@testset "More challenging reactivity of extended function" begin
notebook = Notebook(Cell.([
"Base.inv(s::String) = s",
"""
struct MyStruct
x
MyStruct(s::String) = new(inv(s))
end
""",
"Base.inv(ms::MyStruct) = inv(ms.x)",
"MyStruct(\"hoho\")",
"a = MyStruct(\"blahblah\")",
"inv(a)",
]))
cell(idx) = notebook.cells[idx]
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells)
@test all(noerror, notebook.cells)
@test notebook.cells[end].output.body == "\"blahblah\""
setcode(cell(1), "Base.inv(s::String) = s * \"suffix\"")
update_run!(🍭, notebook, cell(1))
@test all(noerror, notebook.cells)
@test notebook.cells[end].output.body == "\"blahblahsuffixsuffix\"" # 2 invs, 1 in constructor, 1 in inv(::MyStruct)
setcode(cell(3), "Base.inv(ms::MyStruct) = ms.x") # remove inv in inv(::MyStruct)
update_run!(🍭, notebook, cell(3))
@test all(noerror, notebook.cells)
@test notebook.cells[end].output.body == "\"blahblahsuffix\"" # only one inv
# Empty and run cells to remove the Base overloads that we created, just to be sure
setcode.(notebook.cells, [""])
update_run!(🍭, notebook, notebook.cells)
WorkspaceManager.unmake_workspace((🍭, notebook))
end
@testset "multiple cells cycle" begin
notebook = Notebook(Cell.([
"a = inv(1)",
"b = a",
"c = b",
"Base.inv(x::Float64) = a",
"d = Float64(c)",
]))
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells)
@test all(noerror, notebook.cells)
@test notebook.cells[end].output.body == "1.0" # a
end
@testset "one cell in two different cycles where one is not a real cycle" begin
notebook = Notebook(Cell.([
"x = inv(1) + z",
"y = x",
"z = y",
"Base.inv(::Float64) = y",
"inv(1.0)",
]))
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells)
@test notebook.cells[end].errored == true
@test occursinerror("Cyclic", notebook.cells[1])
@test occursinerror("UndefVarError: y", notebook.cells[end]) # this is an UndefVarError and not a CyclicError
setcode.(notebook.cells, [""])
update_run!(🍭, notebook, notebook.cells)
WorkspaceManager.unmake_workspace((🍭, notebook))
end
@testset "Reactive methods definitions" begin
notebook = Notebook(Cell.([
raw"""
Base.sqrt(s::String) = "sqrt($s)"
""",
"""
string((sqrt("🍕"), rand()))
""",
"",
]))
cell(idx) = notebook.cells[idx]
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells)
output_21 = cell(2).output.body
@test contains(output_21, "sqrt(🍕)")
setcode(cell(3), """
Base.sqrt(x::Int) = sqrt(Float64(x)^2)
""")
update_run!(🍭, notebook, cell(3))
output_22 = cell(2).output.body
@test cell(3) |> noerror
@test cell(2) |> noerror
@test cell(1) |> noerror
@test output_21 != output_22 # cell2 re-run
@test contains(output_22, "sqrt(🍕)")
setcode.(notebook.cells, [""])
update_run!(🍭, notebook, notebook.cells)
WorkspaceManager.unmake_workspace((🍭, notebook))
end
@testset "Don't lose basic generic types with macros" begin
notebook = Notebook(Cell.([
"f(::Val{1}) = @info x",
"f(::Val{2}) = @info x",
]))
update_run!(🍭, notebook, notebook.cells)
@test notebook.cells[1] |> noerror
@test notebook.cells[2] |> noerror
end
@testset "Two inter-twined cycles" begin
notebook = Notebook(Cell.([
"""
begin
struct A
x
A(x) = A(inv(x))
end
rand()
end
""",
"Base.inv(::A) = A(1)",
"""
struct B
x
B(x) = B(inv(x))
end
""",
"Base.inv(::B) = B(1)",
]))
update_run!(🍭, notebook, notebook.cells)
@test all(noerror, notebook.cells)
output_1 = notebook.cells[begin].output.body
update_run!(🍭, notebook, notebook.cells[2])
@test noerror(notebook.cells[1])
@test notebook.cells[1].output.body == output_1
@test noerror(notebook.cells[2])
setcode.(notebook.cells, [""])
update_run!(🍭, notebook, notebook.cells)
WorkspaceManager.unmake_workspace((🍭, notebook))
end
@testset "Multiple methods across cells" begin
notebook = Notebook([
Cell("a(x) = 1"),
Cell("a(x,y) = 2"),
Cell("a(3)"),
Cell("a(4,4)"),
Cell("b = 5"),
Cell("b(x) = 6"),
Cell("b + 7"),
Cell("b(8)"),
Cell("Base.tan(x::String) = 9"),
Cell("Base.tan(x::Missing) = 10"),
Cell("Base.tan(\"eleven\")"),
Cell("Base.tan(missing)"),
Cell("tan(missing)"),
Cell("d(x::Integer) = 14"),
Cell("d(x::String) = 15"),
Cell("d(16)"),
Cell("d(\"seventeen\")"),
Cell("d"),
Cell("struct asdf; x; y; end"),
Cell(""),
Cell("asdf(21, 21)"),
Cell("asdf(22)"),
Cell("@enum e1 e2 e3"),
Cell("@enum e4 e5=24"),
Cell("Base.@enum e6 e7=25 e8"),
Cell("Base.@enum e9 e10=26 e11"),
Cell("""@enum e12 begin
e13=27
e14
end"""),
])
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells[1:4])
@test notebook.cells[1].errored == false
@test notebook.cells[2].errored == false
@test notebook.cells[3].output.body == "1"
@test notebook.cells[4].output.body == "2"
setcode(notebook.cells[1], "a(x,x) = 999")
update_run!(🍭, notebook, notebook.cells[1])
@test notebook.cells[1].errored == true
@test notebook.cells[2].errored == true
@test notebook.cells[3].errored == true
@test notebook.cells[4].errored == true
setcode(notebook.cells[1], "a(x) = 1")
update_run!(🍭, notebook, notebook.cells[1])
@test notebook.cells[1].errored == false
@test notebook.cells[2].errored == false
@test notebook.cells[3].output.body == "1"
@test notebook.cells[4].output.body == "2"
setcode(notebook.cells[1], "")
update_run!(🍭, notebook, notebook.cells[1])
@test notebook.cells[1].errored == false
@test notebook.cells[2].errored == false
@test notebook.cells[3].errored == true
@test notebook.cells[4].output.body == "2"
update_run!(🍭, notebook, notebook.cells[5:8])
@test notebook.cells[5].errored == true
@test notebook.cells[6].errored == true
@test notebook.cells[7].errored == true
@test notebook.cells[8].errored == true
setcode(notebook.cells[5], "")
update_run!(🍭, notebook, notebook.cells[5])
@test notebook.cells[5].errored == false
@test notebook.cells[6].errored == false
@test notebook.cells[7].errored == true
@test notebook.cells[8].output.body == "6"
setcode(notebook.cells[5], "b = 5")
setcode(notebook.cells[6], "")
update_run!(🍭, notebook, notebook.cells[5:6])
@test notebook.cells[5].errored == false
@test notebook.cells[6].errored == false
@test notebook.cells[7].output.body == "12"
@test notebook.cells[8].errored == true
update_run!(🍭, notebook, notebook.cells[11:13])
@test notebook.cells[12].output.body == "missing"
update_run!(🍭, notebook, notebook.cells[9:10])
@test notebook.cells[9].errored == false
@test notebook.cells[10].errored == false
@test notebook.cells[11].output.body == "9"
@test notebook.cells[12].output.body == "10"
@test notebook.cells[13].output.body == "10"
update_run!(🍭, notebook, notebook.cells[13])
@test notebook.cells[13].output.body == "10"
setcode(notebook.cells[9], "")
update_run!(🍭, notebook, notebook.cells[9])
@test notebook.cells[11].errored == true
@test notebook.cells[12].output.body == "10"
setcode(notebook.cells[10], "")
update_run!(🍭, notebook, notebook.cells[10])
@test notebook.cells[11].errored == true
@test notebook.cells[12].output.body == "missing"
# Cell("d(x::Integer) = 14"),
# Cell("d(x::String) = 15"),
# Cell("d(16)"),
# Cell("d(\"seventeen\")"),
# Cell("d"),
update_run!(🍭, notebook, notebook.cells[16:18])
@test notebook.cells[16].errored == true
@test notebook.cells[17].errored == true
@test notebook.cells[18].errored == true
update_run!(🍭, notebook, notebook.cells[14])
@test notebook.cells[16].errored == false
@test notebook.cells[17].errored == true
@test notebook.cells[18].errored == false
update_run!(🍭, notebook, notebook.cells[15])
@test notebook.cells[16].errored == false
@test notebook.cells[17].errored == false
@test notebook.cells[18].errored == false
setcode(notebook.cells[14], "")
update_run!(🍭, notebook, notebook.cells[14])
@test notebook.cells[16].errored == true
@test notebook.cells[17].errored == false
@test notebook.cells[18].errored == false
setcode(notebook.cells[15], "")
update_run!(🍭, notebook, notebook.cells[15])
@test notebook.cells[16].errored == true
@test notebook.cells[17].errored == true
@test notebook.cells[18].errored == true
@test occursinerror("UndefVarError", notebook.cells[18])
# Cell("struct e; x; y; end"),
# Cell(""),
# Cell("e(21, 21)"),
# Cell("e(22)"),
update_run!(🍭, notebook, notebook.cells[19:22])
@test notebook.cells[19].errored == false
@test notebook.cells[21].errored == false
@test notebook.cells[22].errored == true
setcode(notebook.cells[20], "asdf(x) = asdf(x,x)")
update_run!(🍭, notebook, notebook.cells[20])
@test occursinerror("Multiple definitions", notebook.cells[19])
@test occursinerror("Multiple definitions", notebook.cells[20])
@test occursinerror("asdf", notebook.cells[20])
@test occursinerror("asdf", notebook.cells[20])
@test notebook.cells[21].errored == true
@test notebook.cells[22].errored == true
setcode(notebook.cells[20], "")
update_run!(🍭, notebook, notebook.cells[20])
@test notebook.cells[19].errored == false
@test notebook.cells[20].errored == false
@test notebook.cells[21].errored == false
@test notebook.cells[22].errored == true
setcode(notebook.cells[19], "begin struct asdf; x; y; end; asdf(x) = asdf(x,x); end")
setcode(notebook.cells[20], "")
update_run!(🍭, notebook, notebook.cells[19:20])
@test notebook.cells[19].errored == false
@test notebook.cells[20].errored == false
@test notebook.cells[21].errored == false
@test notebook.cells[22].errored == false
update_run!(🍭, notebook, notebook.cells[23:27])
@test notebook.cells[23].errored == false
@test notebook.cells[24].errored == false
@test notebook.cells[25].errored == false
@test notebook.cells[26].errored == false
@test notebook.cells[27].errored == false
update_run!(🍭, notebook, notebook.cells[23:27])
@test notebook.cells[23].errored == false
@test notebook.cells[24].errored == false
@test notebook.cells[25].errored == false
@test notebook.cells[26].errored == false
@test notebook.cells[27].errored == false
setcode.(notebook.cells[23:27], [""])
update_run!(🍭, notebook, notebook.cells[23:27])
setcode(notebook.cells[23], "@assert !any(isdefined.([@__MODULE__], [Symbol(:e,i) for i in 1:14]))")
update_run!(🍭, notebook, notebook.cells[23])
@test notebook.cells[23].errored == false
WorkspaceManager.unmake_workspace((🍭, notebook))
# for some unsupported edge cases, see:
# https://github.com/fonsp/Pluto.jl/issues/177#issuecomment-645039993
end
@testset "Cyclic" begin
notebook = Notebook([
Cell("xxx = yyy")
Cell("yyy = xxx")
Cell("zzz = yyy")
Cell("aaa() = bbb")
Cell("bbb = aaa()")
Cell("w1(x) = w2(x - 1) + 1")
Cell("w2(x) = x > 0 ? w1(x) : x")
Cell("w1(8)")
Cell("p1(x) = p2(x) + p1(x)")
Cell("p2(x) = p1(x)")
# 11
Cell("z(x::String) = z(1)")
Cell("z(x::Integer) = z()")
# 13
# some random Base function that we are overloading
Cell("Base.get(x::InterruptException) = Base.get(1)")
Cell("Base.get(x::ArgumentError) = Base.get()")
Cell("Base.step(x::InterruptException) = step(1)")
Cell("Base.step(x::ArgumentError) = step()")
Cell("Base.exponent(x::InterruptException) = Base.exponent(1)")
Cell("Base.exponent(x::ArgumentError) = exponent()")
# 19
Cell("Base.chomp(x::InterruptException) = split() + chomp()")
Cell("Base.chomp(x::ArgumentError) = chomp()")
Cell("Base.split(x::InterruptException) = split()")
# 22
Cell("Base.transpose(x::InterruptException) = Base.trylock() + Base.transpose()")
Cell("Base.transpose(x::ArgumentError) = Base.transpose()")
Cell("Base.trylock(x::InterruptException) = Base.trylock()")
# 25
Cell("Base.digits(x::ArgumentError) = Base.digits() + Base.isconst()")
Cell("Base.isconst(x::InterruptException) = digits()")
# 27
Cell("f(x) = g(x-1)")
Cell("g(x) = h(x-1)")
Cell("h(x) = i(x-1)")
Cell("i(x) = j(x-1)")
Cell("j(x) = (x > 0) ? f(x-1) : :done")
Cell("f(8)")
])
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells[1:3])
@test occursinerror("Cyclic reference", notebook.cells[1])
@test occursinerror("xxx", notebook.cells[1])
@test occursinerror("yyy", notebook.cells[1])
@test occursinerror("Cyclic reference", notebook.cells[2])
@test occursinerror("xxx", notebook.cells[2])
@test occursinerror("yyy", notebook.cells[2])
@test occursinerror("UndefVarError", notebook.cells[3])
setcode(notebook.cells[1], "xxx = 1")
update_run!(🍭, notebook, notebook.cells[1])
@test notebook.cells[1].output.body == "1"
@test notebook.cells[2].output.body == "1"
@test notebook.cells[3].output.body == "1"
setcode(notebook.cells[1], "xxx = zzz")
update_run!(🍭, notebook, notebook.cells[1])
@test occursinerror("Cyclic reference", notebook.cells[1])
@test occursinerror("Cyclic reference", notebook.cells[2])
@test occursinerror("Cyclic reference", notebook.cells[3])
@test occursinerror("xxx", notebook.cells[1])
@test occursinerror("yyy", notebook.cells[1])
@test occursinerror("zzz", notebook.cells[1])
@test occursinerror("xxx", notebook.cells[2])
@test occursinerror("yyy", notebook.cells[2])
@test occursinerror("zzz", notebook.cells[2])
@test occursinerror("xxx", notebook.cells[3])
@test occursinerror("yyy", notebook.cells[3])
@test occursinerror("zzz", notebook.cells[3])
setcode(notebook.cells[3], "zzz = 3")
update_run!(🍭, notebook, notebook.cells[3])
@test notebook.cells[1].output.body == "3"
@test notebook.cells[2].output.body == "3"
@test notebook.cells[3].output.body == "3"
##
update_run!(🍭, notebook, notebook.cells[4:5])
@test occursinerror("Cyclic reference", notebook.cells[4])
@test occursinerror("aaa", notebook.cells[4])
@test occursinerror("bbb", notebook.cells[4])
@test occursinerror("Cyclic reference", notebook.cells[5])
@test occursinerror("aaa", notebook.cells[5])
@test occursinerror("bbb", notebook.cells[5])
update_run!(🍭, notebook, notebook.cells[6:end])
@test noerror(notebook.cells[6])
@test noerror(notebook.cells[7])
@test noerror(notebook.cells[8])
@test noerror(notebook.cells[9])
@test noerror(notebook.cells[10])
@test noerror(notebook.cells[11])
@test noerror(notebook.cells[12])
@test noerror(notebook.cells[13])
@test noerror(notebook.cells[14])
@test noerror(notebook.cells[15])
@test noerror(notebook.cells[16])
@test noerror(notebook.cells[17])
@test noerror(notebook.cells[18])
@test noerror(notebook.cells[19])
@test noerror(notebook.cells[20])
@test noerror(notebook.cells[21])
@test noerror(notebook.cells[22])
@test noerror(notebook.cells[23])
@test noerror(notebook.cells[24])
@test noerror(notebook.cells[25])
@test noerror(notebook.cells[26])
##
@test noerror(notebook.cells[27])
@test noerror(notebook.cells[28])
@test noerror(notebook.cells[29])
@test noerror(notebook.cells[30])
@test noerror(notebook.cells[31])
@test noerror(notebook.cells[32])
@test notebook.cells[32].output.body == ":done"
@assert length(notebook.cells) == 32
# Empty and run cells to remove the Base overloads that we created, just to be sure
setcode.(notebook.cells, [""])
update_run!(🍭, notebook, notebook.cells)
WorkspaceManager.unmake_workspace((🍭, notebook))
end
@testset "Variable deletion" begin
notebook = Notebook([
Cell("x = 1"),
Cell("y = x"),
Cell("struct a; x end"),
Cell("a")
])
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells[1:2])
@test notebook.cells[1].output.body == notebook.cells[2].output.body
setcode(notebook.cells[1], "")
update_run!(🍭, notebook, notebook.cells[1])
@test notebook.cells[1].errored == false
@test occursinerror("x not defined", notebook.cells[2])
update_run!(🍭, notebook, notebook.cells[4])
update_run!(🍭, notebook, notebook.cells[3])
@test notebook.cells[3].errored == false
@test notebook.cells[4].errored == false
update_run!(🍭, notebook, notebook.cells[3])
@test notebook.cells[3].errored == false
@test notebook.cells[4].errored == false
setcode(notebook.cells[3], "struct a; x; y end")
update_run!(🍭, notebook, notebook.cells[3])
@test notebook.cells[3].errored == false
@test notebook.cells[4].errored == false
setcode(notebook.cells[3], "")
update_run!(🍭, notebook, notebook.cells[3])
@test notebook.cells[3].errored == false
@test notebook.cells[4].errored == true
WorkspaceManager.unmake_workspace((🍭, notebook))
end
@testset "Recursion" begin
notebook = Notebook([
Cell("f(n) = n * f(n-1)"),
Cell("k = 1"),
Cell("""begin
g(n) = h(n-1) + k
h(n) = n > 0 ? g(n-1) : 0
end"""),
Cell("h(4)"),
])
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells[1])
@test notebook.cells[1].output.body == "f" || startswith(notebook.cells[1].output.body, "f (generic function with ")
@test notebook.cells[1].errored == false
update_run!(🍭, notebook, notebook.cells[2:3])
@test notebook.cells[2].errored == false
@test notebook.cells[3].errored == false
update_run!(🍭, notebook, notebook.cells[3])
@test notebook.cells[3].errored == false
update_run!(🍭, notebook, notebook.cells[4])
@test notebook.cells[4].output.body == "2"
setcode(notebook.cells[2], "k = 2")
update_run!(🍭, notebook, notebook.cells[2])
@test notebook.cells[4].output.body == "4"
WorkspaceManager.unmake_workspace((🍭, notebook))
end
@testset "Variable cannot reference its previous value" begin
notebook = Notebook([
Cell("x = 3")
])
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells[1])
setcode(notebook.cells[1], "x = x + 1")
update_run!(🍭, notebook, notebook.cells[1])
@test occursinerror("UndefVarError", notebook.cells[1])
WorkspaceManager.unmake_workspace((🍭, notebook))
end
notebook = Notebook([
Cell("y = 1"),
Cell("f(x) = x + y"),
Cell("f(3)"),
Cell("g(a,b) = a+b"),
Cell("g(5,6)"),
Cell("h(x::Int) = x"),
Cell("h(7)"),
Cell("h(8.0)"),
Cell("p(x) = 9"),
Cell("p isa Function"),
Cell("module Something
export a
a(x::String) = \"🐟\"
end"),
Cell("using .Something"),
Cell("a(x::Int) = x"),
Cell("a(\"i am a \")"),
Cell("a(15)"),
Cell("module Different
export b
b(x::String) = \"🐟\"
end"),
Cell("import .Different: b"),
Cell("b(x::Int) = x"),
Cell("b(\"i am a \")"),
Cell("b(20)"),
Cell("module Wow
export c
c(x::String) = \"🐟\"
end"),
Cell("begin
import .Wow: c
c(x::Int) = x
end"),
Cell("c(\"i am a \")"),
Cell("c(24)"),
Cell("Ref((25,:fish))"),
Cell("begin
import Base: show
show(io::IO, x::Ref{Tuple{Int,Symbol}}) = write(io, \"🐟\")
end"),
Cell("Base.isodd(n::Integer) = \"🎈\""),
Cell("Base.isodd(28)"),
Cell("isodd(29)"),
Cell("using Dates"),
Cell("year(DateTime(31))"),
])
fakeclient.connected_notebook = notebook
@testset "Changing functions" begin
update_run!(🍭, notebook, notebook.cells[2])
@test notebook.cells[2].errored == false
update_run!(🍭, notebook, notebook.cells[1])
update_run!(🍭, notebook, notebook.cells[3])
@test notebook.cells[3].output.body == "4"
setcode(notebook.cells[1], "y = 2")
update_run!(🍭, notebook, notebook.cells[1])
@test notebook.cells[3].output.body == "5"
@test notebook.cells[2].errored == false
setcode(notebook.cells[1], "y")
update_run!(🍭, notebook, notebook.cells[1])
@test occursinerror("UndefVarError", notebook.cells[1])
@test notebook.cells[2].errored == false
@test occursinerror("UndefVarError", notebook.cells[3])
update_run!(🍭, notebook, notebook.cells[4])
update_run!(🍭, notebook, notebook.cells[5])
@test notebook.cells[5].output.body == "11"
setcode(notebook.cells[4], "g(a) = a+a")
update_run!(🍭, notebook, notebook.cells[4])
@test notebook.cells[4].errored == false
@test notebook.cells[5].errored == true
setcode(notebook.cells[5], "g(5)")
update_run!(🍭, notebook, notebook.cells[5])
@test notebook.cells[5].output.body == "10"
update_run!(🍭, notebook, notebook.cells[6])
update_run!(🍭, notebook, notebook.cells[7])
update_run!(🍭, notebook, notebook.cells[8])
@test notebook.cells[6].errored == false
@test notebook.cells[7].errored == false
@test notebook.cells[8].errored == true
setcode(notebook.cells[6], "h(x::Float64) = 2.0 * x")
update_run!(🍭, notebook, notebook.cells[6])
@test notebook.cells[6].errored == false
@test notebook.cells[7].errored == true
@test notebook.cells[8].errored == false
update_run!(🍭, notebook, notebook.cells[9:10])
@test notebook.cells[9].errored == false
@test notebook.cells[10].output.body == "true"
setcode(notebook.cells[9], "p = p")
update_run!(🍭, notebook, notebook.cells[9])
@test occursinerror("UndefVarError", notebook.cells[9])
setcode(notebook.cells[9], "p = 9")
update_run!(🍭, notebook, notebook.cells[9])
@test notebook.cells[9].errored == false
@test notebook.cells[10].output.body == "false"
setcode(notebook.cells[9], "p(x) = 9")
update_run!(🍭, notebook, notebook.cells[9])
@test notebook.cells[9].errored == false
@test notebook.cells[10].output.body == "true"
end
@testset "Extending imported functions" begin
update_run!(🍭, notebook, notebook.cells[11:15])
@test_broken notebook.cells[11].errored == false
@test_broken notebook.cells[12].errored == false # multiple definitions for `Something` should be okay? == false
@test notebook.cells[13].errored == false
@test notebook.cells[14].errored == true # the definition for a was created before `a` was used, so it hides the `a` from `Something`
@test notebook.cells[15].output.body == "15"
@test_nowarn update_run!(🍭, notebook, notebook.cells[13:15])
@test notebook.cells[13].errored == false
@test notebook.cells[14].errored == true # the definition for a was created before `a` was used, so it hides the `a` from `Something`
@test notebook.cells[15].output.body == "15"
@test_nowarn update_run!(🍭, notebook, notebook.cells[16:20])
@test notebook.cells[16].errored == false
@test occursinerror("Multiple", notebook.cells[17])
@test occursinerror("Multiple", notebook.cells[18])
@test occursinerror("UndefVarError", notebook.cells[19])
@test occursinerror("UndefVarError", notebook.cells[20])
@test_nowarn update_run!(🍭, notebook, notebook.cells[21:24])
@test notebook.cells[21].errored == false
@test notebook.cells[22].errored == false
@test notebook.cells[23].errored == false
@test notebook.cells[23].output.body == "\"🐟\""
@test notebook.cells[24].output.body == "24"
setcode(notebook.cells[22], "import .Wow: c")
@test_nowarn update_run!(🍭, notebook, notebook.cells[22])
@test notebook.cells[22].errored == false
@test notebook.cells[23].output.body == "\"🐟\""
@test notebook.cells[23].errored == false
@test notebook.cells[24].errored == true # the extension should no longer exist
# https://github.com/fonsp/Pluto.jl/issues/59
original_repr = Pluto.PlutoRunner.format_output(Ref((25, :fish)))[1]
@test_nowarn update_run!(🍭, notebook, notebook.cells[25])
@test notebook.cells[25].output.body isa Dict
@test_nowarn update_run!(🍭, notebook, notebook.cells[26])
@test_broken notebook.cells[25].output.body == "🐟" # cell'🍭 don't automatically call `show` again when a new overload is defined - that'🍭 a minor issue
@test_nowarn update_run!(🍭, notebook, notebook.cells[25])
@test notebook.cells[25].output.body == "🐟"
setcode(notebook.cells[26], "")
@test_nowarn update_run!(🍭, notebook, notebook.cells[26])
@test_nowarn update_run!(🍭, notebook, notebook.cells[25])
@test notebook.cells[25].output.body isa Dict
@test_nowarn update_run!(🍭, notebook, notebook.cells[28:29])
@test notebook.cells[28].output.body == "false"
@test notebook.cells[29].output.body == "true"
@test_nowarn update_run!(🍭, notebook, notebook.cells[27])
@test notebook.cells[28].output.body == "\"🎈\""
@test notebook.cells[29].output.body == "\"🎈\"" # adding the overload doesn't trigger automatic re-eval because `isodd` doesn't match `Base.isodd`
@test_nowarn update_run!(🍭, notebook, notebook.cells[28:29])
@test notebook.cells[28].output.body == "\"🎈\""
@test notebook.cells[29].output.body == "\"🎈\""
setcode(notebook.cells[27], "")
update_run!(🍭, notebook, notebook.cells[27])
@test notebook.cells[28].output.body == "false"
@test notebook.cells[29].output.body == "true" # removing the overload doesn't trigger automatic re-eval because `isodd` doesn't match `Base.isodd`
update_run!(🍭, notebook, notebook.cells[28:29])
@test notebook.cells[28].output.body == "false"
@test notebook.cells[29].output.body == "true"
end
@testset "Using external libraries" begin
update_run!(🍭, notebook, notebook.cells[30:31])
@test notebook.cells[30].errored == false
@test notebook.cells[31].output.body == "31"
update_run!(🍭, notebook, notebook.cells[31])
@test notebook.cells[31].output.body == "31"
setcode(notebook.cells[30], "")
update_run!(🍭, notebook, notebook.cells[30:31])
@test occursinerror("UndefVarError", notebook.cells[31])
end
WorkspaceManager.unmake_workspace((🍭, notebook))
@testset "Functional programming" begin
notebook = Notebook([
Cell("a = 1"),
Cell("map(2:2) do val; (a = val; 2*val) end |> last"),
Cell("b = 3"),
Cell("g = f"),
Cell("f(x) = x + b"),
Cell("g(6)"),
Cell("h = [x -> x + b][1]"),
Cell("h(8)"),
])
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells[1:2])
@test notebook.cells[1].output.body == "1"
@test notebook.cells[2].output.body == "4"
update_run!(🍭, notebook, notebook.cells[3:6])
@test notebook.cells[3].errored == false
@test notebook.cells[4].errored == false
@test notebook.cells[5].errored == false
@test notebook.cells[6].errored == false
@test notebook.cells[6].output.body == "9"
setcode(notebook.cells[3], "b = -3")
update_run!(🍭, notebook, notebook.cells[3])
@test notebook.cells[6].output.body == "3"
update_run!(🍭, notebook, notebook.cells[7:8])
@test notebook.cells[7].errored == false
@test notebook.cells[8].output.body == "5"
setcode(notebook.cells[3], "b = 3")
update_run!(🍭, notebook, notebook.cells[3])
@test notebook.cells[8].output.body == "11"
WorkspaceManager.unmake_workspace((🍭, notebook))
end
@testset "Global assignments inside functions" begin
# We currently have a slightly relaxed version of immutable globals:
# globals can only be mutated/assigned _in a single cell_.
notebook = Notebook([
Cell("x = 1"),
Cell("x = 2"),
Cell("y = -3; y = 3"),
Cell("z = 4"),
Cell("let global z = 5 end"),
Cell("wowow"),
Cell("function floep(x) global wowow = x end"),
Cell("floep(8)"),
Cell("v"),
Cell("function g(x) global v = x end; g(10)"),
Cell("g(11)"),
Cell("let
local r = 0
function f()
r = 12
end
f()
r
end"),
Cell("apple"),
Cell("map(14:14) do i; global apple = orange; end"),
Cell("orange = 15"),
])
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells[1])
update_run!(🍭, notebook, notebook.cells[2])
@test occursinerror("Multiple definitions for x", notebook.cells[1])
@test occursinerror("Multiple definitions for x", notebook.cells[1])
setcode(notebook.cells[2], "x + 1")
update_run!(🍭, notebook, notebook.cells[2])
@test notebook.cells[1].output.body == "1"
@test notebook.cells[2].output.body == "2"
update_run!(🍭, notebook, notebook.cells[3])
@test notebook.cells[3].output.body == "3"
update_run!(🍭, notebook, notebook.cells[4])
update_run!(🍭, notebook, notebook.cells[5])
@test occursinerror("Multiple definitions for z", notebook.cells[4])
@test occursinerror("Multiple definitions for z", notebook.cells[5])
update_run!(🍭, notebook, notebook.cells[6:7])
@test occursinerror("UndefVarError", notebook.cells[6])
# @test_broken occursinerror("assigns to global", notebook.cells[7])
# @test_broken occursinerror("wowow", notebook.cells[7])
# @test_broken occursinerror("floep", notebook.cells[7])
update_run!(🍭, notebook, notebook.cells[8])
@test_broken !occursinerror("UndefVarError", notebook.cells[6])
update_run!(🍭, notebook, notebook.cells[9:10])
@test !occursinerror("UndefVarError", notebook.cells[9])
@test notebook.cells[10].errored == false
update_run!(🍭, notebook, notebook.cells[11])
@test_broken notebook.cells[9].errored == true
@test_broken notebook.cells[10].errored == true
@test_broken notebook.cells[11].errored == true
update_run!(🍭, notebook, notebook.cells[12])
@test notebook.cells[12].output.body == "12"
update_run!(🍭, notebook, notebook.cells[13:15])
@test notebook.cells[13].output.body == "15"
@test notebook.cells[14].errored == false
setcode(notebook.cells[15], "orange = 10005")
update_run!(🍭, notebook, notebook.cells[15])
@test notebook.cells[13].output.body == "10005"
WorkspaceManager.unmake_workspace((🍭, notebook))
end
@testset "No top level return" begin
notebook = Notebook([
Cell("return 10"),
Cell("return (0, 0)"),
Cell("return (0, 0)"),
Cell("return (0, 0, 0)"),
Cell("begin return \"a string\" end"),
Cell("""
let
return []
end
"""),
Cell("""filter(1:3) do x
return true
end"""),
# create struct to disable the function-generating optimization
Cell("struct A1 end; return 10"),
Cell("struct A2 end; return (0, 0)"),
Cell("struct A3 end; return (0, 0)"),
Cell("struct A4 end; return (0, 0, 0)"),
Cell("struct A5 end; begin return \"a string\" end"),
Cell("""
struct A6 end; let
return []
end
"""),
Cell("""struct A7 end; filter(1:3) do x
return true
end"""),
# Function assignments
Cell("""f(x) = if x == 1
return false
else
return true
end"""),
Cell("""g(x::T) where {T} = if x == 1
return false
else
return true
end"""),
Cell("(h(x::T)::MyType) where {T} = return(x)"),
Cell("i(x)::MyType = return(x)"),
])
update_run!(🍭, notebook, notebook.cells)
@test occursinerror("You can only use return inside a function.", notebook.cells[1])
@test occursinerror("You can only use return inside a function.", notebook.cells[2])
@test occursinerror("You can only use return inside a function.", notebook.cells[3])
@test occursinerror("You can only use return inside a function.", notebook.cells[4])
@test occursinerror("You can only use return inside a function.", notebook.cells[5])
@test occursinerror("You can only use return inside a function.", notebook.cells[6])
@test notebook.cells[7] |> noerror
@test occursinerror("You can only use return inside a function.", notebook.cells[8])
@test occursinerror("You can only use return inside a function.", notebook.cells[9])
@test occursinerror("You can only use return inside a function.", notebook.cells[10])
@test occursinerror("You can only use return inside a function.", notebook.cells[11])
@test occursinerror("You can only use return inside a function.", notebook.cells[12])
@test occursinerror("You can only use return inside a function.", notebook.cells[13])
@test notebook.cells[14] |> noerror
# Function assignments
@test notebook.cells[15] |> noerror
@test notebook.cells[16] |> noerror
@test notebook.cells[17] |> noerror
@test notebook.cells[18] |> noerror
WorkspaceManager.unmake_workspace((🍭, notebook))
end
@testset "Function wrapping" begin
notebook = Notebook([
Cell("false && jlaksdfjalskdfj"),
Cell("fonsi = 2"),
Cell("""
filter(1:fonsi) do x
x = sum(1 for z in 1:x)
x = sum(1 for z in 1:x)
x = sum(1 for z in 1:x)
x = sum(1 for z in 1:x)
x = sum(1 for z in 1:x)
x = sum(1 for z in 1:x)
false
end |> length
"""),
Cell("4"),
Cell("[5]"),
Cell("6 / 66"),
Cell("false && (seven = 7)"),
Cell("seven"),
Cell("nine = :identity"),
Cell("nine"),
Cell("@__FILE__; nine"),
Cell("@__FILE__; twelve = :identity"),
Cell("@__FILE__; twelve"),
Cell("twelve"),
Cell("fifteen = :(1 + 1)"),
Cell("fifteen"),
Cell("@__FILE__; fifteen"),
Cell("@__FILE__; eighteen = :(1 + 1)"),
Cell("@__FILE__; eighteen"),
Cell("eighteen"),
Cell("qb = quote value end"),
Cell("typeof(qb)"),
Cell("qn0 = QuoteNode(:value)"),
Cell("qn1 = :(:value)"),
Cell("qn0"),
Cell("qn1"),
Cell("""
named_tuple(obj::T) where {T} = NamedTuple{fieldnames(T),Tuple{fieldtypes(T)...}}(ntuple(i -> getfield(obj, i), fieldcount(T)))
"""),
Cell("named_tuple"),
Cell("ln = LineNumberNode(29, \"asdf\")"),
Cell("@assert ln isa LineNumberNode"),
])
update_run!(🍭, notebook, notebook.cells)
@test notebook.cells[1].errored == false
@test notebook.cells[1].output.body == "false"
@test notebook.cells[22].output.body == "Expr"
@test notebook.cells[25].output.body == ":(:value)"
@test notebook.cells[26].output.body == ":(:value)"
function benchmark(fonsi)
filter(1:fonsi) do x
x = sum(1 for z in 1:x)
x = sum(1 for z in 1:x)
x = sum(1 for z in 1:x)
x = sum(1 for z in 1:x)
x = sum(1 for z in 1:x)
x = sum(1 for z in 1:x)
false
end |> length
end
bad = @elapsed benchmark(2)
good = 0.01 * @elapsed for i in 1:100
benchmark(2)
end
update_run!(🍭, notebook, notebook.cells)
@test 0.1 * good < notebook.cells[3].runtime / 1.0e9 < 0.5 * bad
old = notebook.cells[4].output.body
setcode(notebook.cells[4], "4.0")
update_run!(🍭, notebook, notebook.cells[4])
@test old != notebook.cells[4].output.body
old = notebook.cells[5].output.body
setcode(notebook.cells[5], "[5.0]")
update_run!(🍭, notebook, notebook.cells[5])
@test old != notebook.cells[5].output.body
old = notebook.cells[6].output.body
setcode(notebook.cells[6], "66 / 6")
update_run!(🍭, notebook, notebook.cells[6])
@test old != notebook.cells[6].output.body
@test notebook.cells[7].errored == false
@test notebook.cells[7].output.body == "false"
@test occursinerror("UndefVarError", notebook.cells[8])
@test notebook.cells[9].output.body == ":identity"
@test notebook.cells[10].output.body == ":identity"
@test notebook.cells[11].output.body == ":identity"
@test notebook.cells[12].output.body == ":identity"
@test notebook.cells[13].output.body == ":identity"
@test notebook.cells[14].output.body == ":identity"
@test notebook.cells[15].output.body == ":(1 + 1)"
@test notebook.cells[16].output.body == ":(1 + 1)"
@test notebook.cells[17].output.body == ":(1 + 1)"
@test notebook.cells[18].output.body == ":(1 + 1)"
@test notebook.cells[19].output.body == ":(1 + 1)"
@test notebook.cells[20].output.body == ":(1 + 1)"
@test notebook.cells[27].errored == false
@test notebook.topology.codes[notebook.cells[27]].function_wrapped == false
@test notebook.cells[28].errored == false
update_run!(🍭, notebook, notebook.cells[29:30])
@test notebook.cells[29].errored == false
@test notebook.cells[30].errored == false
WorkspaceManager.unmake_workspace((🍭, notebook))
@testset "Expression hash" begin
same(a,b) = Pluto.PlutoRunner.expr_hash(a) == Pluto.PlutoRunner.expr_hash(b)
@test same(:(1), :(1))
@test !same(:(1), :(1.0))
@test same(:(x + 1), :(x + 1))
@test !same(:(x + 1), :(x + 1.0))
@test same(:(1 |> a |> a |> a), :(1 |> a |> a |> a))
@test same(:(a(b(1,2))), :(a(b(1,2))))
@test !same(:(a(b(1,2))), :(a(b(1,3))))
@test !same(:(a(b(1,2))), :(a(b(1,1))))
@test !same(:(a(b(1,2))), :(a(b(2,1))))
end
end
@testset "Run multiple" begin
notebook = Notebook([
Cell("x = []"),
Cell("b = a + 2; push!(x,2)"),
Cell("c = b + a; push!(x,3)"),
Cell("a = 1; push!(x,4)"),
Cell("a + b +c; push!(x,5)"),
Cell("a = 1; push!(x,6)"),
Cell("n = m; push!(x,7)"),
Cell("m = n; push!(x,8)"),
Cell("n = 1; push!(x,9)"),
Cell("push!(x,10)"),
Cell("push!(x,11)"),
Cell("push!(x,12)"),
Cell("push!(x,13)"),
Cell("push!(x,14)"),
Cell("join(x, '-')"),
Cell("φ(16)"),
Cell("φ(χ) = χ + υ"),
Cell("υ = 18"),
Cell("f(19)"),
Cell("f(x) = x + g(x)"),
Cell("g(x) = x + y"),
Cell("y = 22"),
])
fakeclient.connected_notebook = notebook
update_run!(🍭, notebook, notebook.cells[1])
@testset "Basic" begin
update_run!(🍭, notebook, notebook.cells[2:5])
update_run!(🍭, notebook, notebook.cells[15])
@test notebook.cells[15].output.body == "\"4-2-3-5\""
end
@testset "Errors" begin
update_run!(🍭, notebook, notebook.cells[6:9])
# should all err, no change to `x`
update_run!(🍭, notebook, notebook.cells[15])
@test notebook.cells[15].output.body == "\"4-2-3-5\""
end
@testset "Maintain order when possible" begin
update_run!(🍭, notebook, notebook.cells[10:14])
update_run!(🍭, notebook, notebook.cells[15])
@test notebook.cells[15].output.body == "\"4-2-3-5-10-11-12-13-14\""
update_run!(🍭, notebook, notebook.cells[1]) # resets `x`, only 10-14 should run, in order
@test notebook.cells[15].output.body == "\"10-11-12-13-14\""
update_run!(🍭, notebook, notebook.cells[15])
@test notebook.cells[15].output.body == "\"10-11-12-13-14\""
end
update_run!(🍭, notebook, notebook.cells[16:18])
@test notebook.cells[16].errored == false
@test notebook.cells[16].output.body == "34"
@test notebook.cells[17].errored == false
@test notebook.cells[18].errored == false
setcode(notebook.cells[18], "υ = 8")
update_run!(🍭, notebook, notebook.cells[18])
@test notebook.cells[16].output.body == "24"
update_run!(🍭, notebook, notebook.cells[19:22])
@test notebook.cells[19].errored == false
@test notebook.cells[19].output.body == "60"
@test notebook.cells[20].errored == false
@test notebook.cells[21].errored == false
@test notebook.cells[22].errored == false
setcode(notebook.cells[22], "y = 0")
update_run!(🍭, notebook, notebook.cells[22])
@test notebook.cells[19].output.body == "38"
WorkspaceManager.unmake_workspace((🍭, notebook))
end
end
| 36.989157
| 159
| 0.55578
|
[
"@testset \"Reactivity\" begin\n 🍭 = ServerSession()\n 🍭.options.evaluation.workspace_use_distributed = false\n\n fakeclient = ClientSession(:fake, nothing)\n 🍭.connected_clients[fakeclient.id] = fakeclient\n\n @testset \"Basic $(parallel ? \"distributed\" : \"single-process\")\" for parallel in [false, true]\n 🍭.options.evaluation.workspace_use_distributed = parallel\n \n notebook = Notebook([\n Cell(\"x = 1\"),\n Cell(\"y = x\"),\n Cell(\"f(x) = x + y\"),\n Cell(\"f(4)\"),\n\n Cell(\"\"\"begin\n g(a) = x\n g(a,b) = y\n end\"\"\"),\n Cell(\"g(6) + g(6,6)\"),\n\n Cell(\"import Distributed\"),\n Cell(\"Distributed.myid()\"),\n ])\n fakeclient.connected_notebook = notebook\n\n @test !haskey(WorkspaceManager.workspaces, notebook.notebook_id)\n\n update_run!(🍭, notebook, notebook.cells[1:2])\n @test notebook.cells[1].output.body == notebook.cells[2].output.body\n @test notebook.cells[1].output.rootassignee == :x\n @test notebook.cells[1].runtime !== nothing\n setcode(notebook.cells[1], \"x = 12\")\n update_run!(🍭, notebook, notebook.cells[1])\n @test notebook.cells[1].output.body == notebook.cells[2].output.body\n @test notebook.cells[2].runtime !== nothing\n\n update_run!(🍭, notebook, notebook.cells[3])\n @test notebook.cells[3].errored == false\n @test notebook.cells[3].output.rootassignee === nothing\n \n update_run!(🍭, notebook, notebook.cells[4])\n @test notebook.cells[4].output.body == \"16\"\n @test notebook.cells[4].errored == false\n @test notebook.cells[4].output.rootassignee === nothing\n\n setcode(notebook.cells[1], \"x = 912\")\n update_run!(🍭, notebook, notebook.cells[1])\n @test notebook.cells[4].output.body == \"916\"\n\n setcode(notebook.cells[3], \"f(x) = x\")\n update_run!(🍭, notebook, notebook.cells[3])\n @test notebook.cells[4].output.body == \"4\"\n\n setcode(notebook.cells[1], \"x = 1\")\n setcode(notebook.cells[2], \"y = 2\")\n update_run!(🍭, notebook, notebook.cells[1:2])\n update_run!(🍭, notebook, notebook.cells[5:6])\n @test notebook.cells[5].errored == false\n @test notebook.cells[6].output.body == \"3\"\n\n setcode(notebook.cells[2], \"y = 1\")\n update_run!(🍭, notebook, notebook.cells[2])\n @test notebook.cells[6].output.body == \"2\"\n\n setcode(notebook.cells[1], \"x = 2\")\n update_run!(🍭, notebook, notebook.cells[1])\n @test notebook.cells[6].output.body == \"3\"\n\n update_run!(🍭, notebook, notebook.cells[7:8])\n @test if parallel\n notebook.cells[8].output.body != string(Distributed.myid())\n else\n notebook.cells[8].output.body == string(Distributed.myid())\n end\n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n \n end\n\n 🍭.options.evaluation.workspace_use_distributed = false\n\n @testset \"Mutliple assignments\" begin\n notebook = Notebook([\n Cell(\"x = 1\"),\n Cell(\"x = 2\"),\n Cell(\"f(x) = 3\"),\n Cell(\"f(x) = 4\"),\n Cell(\"g(x) = 5\"),\n Cell(\"g = 6\"),\n ])\n fakeclient.connected_notebook = notebook\n \n\n update_run!(🍭, notebook, notebook.cells[1])\n update_run!(🍭, notebook, notebook.cells[2])\n @test occursinerror(\"Multiple\", notebook.cells[1])\n @test occursinerror(\"Multiple\", notebook.cells[2])\n \n setcode(notebook.cells[1], \"\")\n update_run!(🍭, notebook, notebook.cells[1])\n @test notebook.cells[1].errored == false\n @test notebook.cells[2].errored == false\n \n # https://github.com/fonsp/Pluto.jl/issues/26\n setcode(notebook.cells[1], \"x = 1\")\n update_run!(🍭, notebook, notebook.cells[1])\n setcode(notebook.cells[2], \"x\")\n update_run!(🍭, notebook, notebook.cells[2])\n @test notebook.cells[1].errored == false\n @test notebook.cells[2].errored == false\n\n update_run!(🍭, notebook, notebook.cells[3])\n update_run!(🍭, notebook, notebook.cells[4])\n @test occursinerror(\"Multiple\", notebook.cells[3])\n @test occursinerror(\"Multiple\", notebook.cells[4])\n \n setcode(notebook.cells[3], \"\")\n update_run!(🍭, notebook, notebook.cells[3])\n @test notebook.cells[3].errored == false\n @test notebook.cells[4].errored == false\n \n update_run!(🍭, notebook, notebook.cells[5])\n update_run!(🍭, notebook, notebook.cells[6])\n @test occursinerror(\"Multiple\", notebook.cells[5])\n @test occursinerror(\"Multiple\", notebook.cells[6])\n \n setcode(notebook.cells[5], \"\")\n update_run!(🍭, notebook, notebook.cells[5])\n @test notebook.cells[5].errored == false\n @test notebook.cells[6].errored == false\n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n end\n\n @testset \"Mutliple assignments topology\" begin\n notebook = Notebook([\n Cell(\"x = 1\"),\n Cell(\"z = 4 + y\"),\n Cell(\"y = x + 2\"),\n Cell(\"y = x + 3\"),\n ])\n notebook.topology = Pluto.updated_topology(notebook.topology, notebook, notebook.cells)\n\n let topo_order = Pluto.topological_order(notebook, notebook.topology, notebook.cells[[1]])\n @test indexin(topo_order.runnable, notebook.cells) == [1,2]\n @test topo_order.errable |> keys == notebook.cells[[3,4]] |> Set\n end\n let topo_order = Pluto.topological_order(notebook, notebook.topology, notebook.cells[[1]], allow_multiple_defs=true)\n @test indexin(topo_order.runnable, notebook.cells) == [1,3,4,2] # x first, y second and third, z last\n # this also tests whether multiple defs run in page order\n @test topo_order.errable == Dict()\n end\n end\n\n\n # PlutoTest.jl is only working on Julia version >= 1.6\n VERSION >= v\"1.6\" && @testset \"Test Firebasey\" begin\n 🍭.options.evaluation.workspace_use_distributed = true\n\n file = tempname()\n write(file, read(normpath(Pluto.project_relative_path(\"src\", \"webserver\", \"Firebasey.jl\"))))\n\n notebook = Pluto.load_notebook_nobackup(file)\n fakeclient.connected_notebook = notebook\n\n update_run!(🍭, notebook, notebook.cells)\n\n # Test that the resulting file is runnable\n @test jl_is_runnable(file)\n # and also that Pluto can figure out the execution order on its own\n @test all(noerror, notebook.cells)\n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n 🍭.options.evaluation.workspace_use_distributed = false\n end\n\n @testset \"Pkg topology workarounds\" begin\n notebook = Notebook([\n Cell(\"1 + 1\"),\n Cell(\"json([1,2])\"),\n Cell(\"using JSON\"),\n Cell(\"\"\"Pkg.add(\"JSON\")\"\"\"),\n Cell(\"Pkg.activate(mktempdir())\"),\n Cell(\"import Pkg\"),\n Cell(\"using Revise\"),\n Cell(\"1 + 1\"),\n ])\n notebook.topology = Pluto.updated_topology(notebook.topology, notebook, notebook.cells)\n\n topo_order = Pluto.topological_order(notebook, notebook.topology, notebook.cells)\n @test indexin(topo_order.runnable, notebook.cells) == [6, 5, 4, 7, 3, 1, 2, 8]\n # 6, 5, 4, 3 should run first (this is implemented using `cell_precedence_heuristic`), in that order\n # 1, 2, 7 remain, and should run in notebook order.\n\n # if the cells were placed in reverse order...\n reverse!(notebook.cell_order)\n topo_order = Pluto.topological_order(notebook, notebook.topology, notebook.cells)\n @test indexin(topo_order.runnable, reverse(notebook.cells)) == [6, 5, 4, 7, 3, 8, 2, 1]\n # 6, 5, 4, 3 should run first (this is implemented using `cell_precedence_heuristic`), in that order\n # 1, 2, 7 remain, and should run in notebook order, which is 7, 2, 1.\n\n reverse!(notebook.cell_order)\n end\n\n @testset \"Pkg topology workarounds -- hard\" begin\n notebook = Notebook([\n Cell(\"json([1,2])\"),\n Cell(\"using JSON\"),\n Cell(\"Pkg.add(package_name)\"),\n Cell(\"\"\" package_name = \"JSON\" \"\"\"),\n Cell(\"Pkg.activate(envdir)\"),\n Cell(\"envdir = mktempdir()\"),\n Cell(\"import Pkg\"),\n Cell(\"using JSON3, Revise\"),\n ])\n\n notebook.topology = Pluto.updated_topology(notebook.topology, notebook, notebook.cells)\n\n topo_order = Pluto.topological_order(notebook, notebook.topology, notebook.cells)\n\n comesbefore(A, first, second) = findfirst(isequal(first),A) < findfirst(isequal(second), A)\n\n run_order = indexin(topo_order.runnable, notebook.cells)\n\n # like in the previous test\n @test comesbefore(run_order, 7, 5)\n @test_broken comesbefore(run_order, 5, 3)\n @test_broken comesbefore(run_order, 3, 2)\n @test comesbefore(run_order, 2, 1)\n @test comesbefore(run_order, 8, 2)\n @test comesbefore(run_order, 8, 1)\n\n # the variable dependencies\n @test comesbefore(run_order, 6, 5)\n @test comesbefore(run_order, 4, 3)\n end\n\n \n @testset \"Mixed usings and reactivity\" begin\n notebook = Notebook([\n Cell(\"a; using Dates\"),\n Cell(\"isleapyear(2)\"),\n Cell(\"a = 3; using LinearAlgebra\"),\n ])\n\n notebook.topology = Pluto.updated_topology(notebook.topology, notebook, notebook.cells)\n topo_order = Pluto.topological_order(notebook, notebook.topology, notebook.cells)\n run_order = indexin(topo_order.runnable, notebook.cells)\n\n @test run_order == [3, 1, 2]\n end\n\n @testset \"Reactive usings\" begin\n notebook = Notebook([\n Cell(\"June\"),\n Cell(\"using Dates\"),\n Cell(\"July\"),\n ])\n fakeclient.connected_notebook = notebook\n\n update_run!(🍭, notebook, notebook.cells[1:1])\n\n @test notebook.cells[1].errored == true # this cell is before the using Dates and will error\n @test notebook.cells[3].errored == false # using the position in the notebook this cell will not error\n\n update_run!(🍭, notebook, notebook.cells[2:2])\n\n @test notebook.cells[1].errored == false\n @test notebook.cells[3].errored == false\n end\n\n @testset \"Reactive usings 2\" begin\n notebook = Notebook([\n Cell(\"October\"),\n Cell(\"using Dates\"),\n Cell(\"December\"),\n Cell(\"\"),\n ])\n fakeclient.connected_notebook = notebook\n\n update_run!(🍭, notebook, notebook.cells)\n\n @test notebook.cells[1].errored == false\n @test notebook.cells[3].errored == false\n\n setcode(notebook.cells[2], \"\")\n update_run!(🍭, notebook, notebook.cells[2:2])\n\n @test notebook.cells[1].errored == true\n @test notebook.cells[3].errored == true\n\n setcode(notebook.cells[4], \"December = 13\")\n update_run!(🍭, notebook, notebook.cells[4:4])\n\n @test notebook.cells[1].errored == true\n @test notebook.cells[3] |> noerror\n\n setcode(notebook.cells[2], \"using Dates\")\n update_run!(🍭, notebook, notebook.cells[2:2])\n\n @test notebook.cells[1] |> noerror\n @test notebook.cells[3] |> noerror\n @test notebook.cells[3].output.body == \"13\"\n end\n\n @testset \"Reactive usings 3\" begin\n notebook = Notebook([\n Cell(\"archive_artifact\"),\n Cell(\"using Unknown.Package\"),\n ])\n fakeclient.connected_notebook = notebook\n\n update_run!(🍭, notebook, notebook.cells)\n\n @test notebook.cells[1].errored == true\n @test notebook.cells[2].errored == true\n\n setcode(notebook.cells[2], \"using Pkg.Artifacts\")\n update_run!(🍭, notebook, notebook.cells)\n\n @test notebook.cells[1] |> noerror\n @test notebook.cells[2] |> noerror\n end\n\n @testset \"Reactive usings 4\" begin\n 🍭.options.evaluation.workspace_use_distributed = true\n\n notebook = Notebook([\n Cell(\"@sprintf \\\"double_december = %d\\\" double_december\"),\n Cell(\"double_december = 2December\"),\n Cell(\"archive_artifact\"),\n Cell(\"\"),\n ])\n\n fakeclient.connected_notebook = notebook\n\n update_run!(🍭, notebook, notebook.cells)\n\n @test notebook.cells[1].errored == true\n @test notebook.cells[2].errored == true\n @test notebook.cells[3].errored == true\n\n setcode(notebook.cells[4], \"import Pkg; using Dates, Printf, Pkg.Artifacts\")\n update_run!(🍭, notebook, notebook.cells[4:4])\n\n @test notebook.cells[1] |> noerror\n @test notebook.cells[2] |> noerror\n @test notebook.cells[3] |> noerror\n @test notebook.cells[4] |> noerror\n @test notebook.cells[1].output.body == \"\\\"double_december = 24\\\"\"\n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n 🍭.options.evaluation.workspace_use_distributed = false\n end\n\n @testset \"Reactive usings 5\" begin\n notebook = Notebook(Cell.([\n \"\",\n \"x = ones(December * 2)\",\n \"December = 3\",\n ]))\n\n fakeclient.connected_notebook = notebook\n\n update_run!(🍭, notebook, notebook.cells)\n\n @test all(noerror, notebook.cells)\n\n setcode(notebook.cells[begin], raw\"\"\"\n begin\n @eval(module Hello\n December = 12\n export December\n end)\n using .Hello\n end\n \"\"\")\n update_run!(🍭, notebook, notebook.cells[begin])\n\n @test all(noerror, notebook.cells)\n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n end\n\n @testset \"Function dependencies\" begin\n 🍭.options.evaluation.workspace_use_distributed = true\n\n notebook = Notebook(Cell.([\n \"a'b\",\n \"import LinearAlgebra\",\n \"LinearAlgebra.conj(b::Int) = 2b\",\n \"a = 10\",\n \"b = 10\",\n ]))\n\n fakeclient.connected_notebook = notebook\n update_run!(🍭, notebook, notebook.cells)\n\n @test :conj ∈ notebook.topology.nodes[notebook.cells[3]].soft_definitions\n @test :conj ∈ notebook.topology.nodes[notebook.cells[1]].references\n @test notebook.cells[1].output.body == \"200\"\n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n 🍭.options.evaluation.workspace_use_distributed = false\n end\n\n @testset \"Function use inv in its def but also has a method on inv\" begin\n notebook = Notebook(Cell.([\n \"\"\"\n struct MyStruct\n s\n\n MyStruct(x) = new(inv(x))\n end\n \"\"\",\n \"\"\"\n Base.inv(s::MyStruct) = inv(s.s)\n \"\"\",\n \"MyStruct(1.) |> inv\"\n ]))\n cell(idx) = notebook.cells[idx]\n fakeclient.connected_notebook = notebook\n update_run!(🍭, notebook, notebook.cells)\n\n @test cell(1) |> noerror\n @test cell(2) |> noerror\n @test cell(3) |> noerror\n\n # Empty and run cells to remove the Base overloads that we created, just to be sure\n setcode.(notebook.cells, [\"\"])\n update_run!(🍭, notebook, notebook.cells)\n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n end\n\n @testset \"More challenging reactivity of extended function\" begin\n notebook = Notebook(Cell.([\n \"Base.inv(s::String) = s\",\n \"\"\"\n struct MyStruct\n x\n MyStruct(s::String) = new(inv(s))\n end\n \"\"\",\n \"Base.inv(ms::MyStruct) = inv(ms.x)\",\n \"MyStruct(\\\"hoho\\\")\",\n \"a = MyStruct(\\\"blahblah\\\")\",\n \"inv(a)\",\n ]))\n cell(idx) = notebook.cells[idx]\n fakeclient.connected_notebook = notebook\n update_run!(🍭, notebook, notebook.cells)\n\n @test all(noerror, notebook.cells)\n @test notebook.cells[end].output.body == \"\\\"blahblah\\\"\"\n\n setcode(cell(1), \"Base.inv(s::String) = s * \\\"suffix\\\"\")\n update_run!(🍭, notebook, cell(1))\n\n @test all(noerror, notebook.cells)\n @test notebook.cells[end].output.body == \"\\\"blahblahsuffixsuffix\\\"\" # 2 invs, 1 in constructor, 1 in inv(::MyStruct)\n\n setcode(cell(3), \"Base.inv(ms::MyStruct) = ms.x\") # remove inv in inv(::MyStruct)\n update_run!(🍭, notebook, cell(3))\n\n @test all(noerror, notebook.cells)\n @test notebook.cells[end].output.body == \"\\\"blahblahsuffix\\\"\" # only one inv\n\n # Empty and run cells to remove the Base overloads that we created, just to be sure\n setcode.(notebook.cells, [\"\"])\n update_run!(🍭, notebook, notebook.cells)\n WorkspaceManager.unmake_workspace((🍭, notebook))\n end\n\n @testset \"multiple cells cycle\" begin\n notebook = Notebook(Cell.([\n \"a = inv(1)\",\n \"b = a\",\n \"c = b\",\n \"Base.inv(x::Float64) = a\",\n \"d = Float64(c)\",\n ]))\n fakeclient.connected_notebook = notebook\n update_run!(🍭, notebook, notebook.cells)\n\n @test all(noerror, notebook.cells)\n @test notebook.cells[end].output.body == \"1.0\" # a\n end\n\n @testset \"one cell in two different cycles where one is not a real cycle\" begin\n notebook = Notebook(Cell.([\n \"x = inv(1) + z\",\n \"y = x\",\n \"z = y\",\n \"Base.inv(::Float64) = y\",\n \"inv(1.0)\",\n ]))\n fakeclient.connected_notebook = notebook\n update_run!(🍭, notebook, notebook.cells)\n\n @test notebook.cells[end].errored == true\n @test occursinerror(\"Cyclic\", notebook.cells[1])\n @test occursinerror(\"UndefVarError: y\", notebook.cells[end]) # this is an UndefVarError and not a CyclicError\n\n setcode.(notebook.cells, [\"\"])\n update_run!(🍭, notebook, notebook.cells)\n WorkspaceManager.unmake_workspace((🍭, notebook))\n end\n\n @testset \"Reactive methods definitions\" begin\n notebook = Notebook(Cell.([\n raw\"\"\"\n Base.sqrt(s::String) = \"sqrt($s)\"\n \"\"\",\n \"\"\"\n string((sqrt(\"🍕\"), rand()))\n \"\"\",\n \"\",\n ]))\n cell(idx) = notebook.cells[idx]\n fakeclient.connected_notebook = notebook\n update_run!(🍭, notebook, notebook.cells)\n\n output_21 = cell(2).output.body\n @test contains(output_21, \"sqrt(🍕)\")\n\n setcode(cell(3), \"\"\"\n Base.sqrt(x::Int) = sqrt(Float64(x)^2)\n \"\"\")\n update_run!(🍭, notebook, cell(3))\n\n output_22 = cell(2).output.body\n @test cell(3) |> noerror\n @test cell(2) |> noerror\n @test cell(1) |> noerror\n @test output_21 != output_22 # cell2 re-run\n @test contains(output_22, \"sqrt(🍕)\")\n\n setcode.(notebook.cells, [\"\"])\n update_run!(🍭, notebook, notebook.cells)\n WorkspaceManager.unmake_workspace((🍭, notebook))\n end\n\n @testset \"Don't lose basic generic types with macros\" begin\n notebook = Notebook(Cell.([\n \"f(::Val{1}) = @info x\",\n \"f(::Val{2}) = @info x\",\n ]))\n update_run!(🍭, notebook, notebook.cells)\n\n @test notebook.cells[1] |> noerror\n @test notebook.cells[2] |> noerror\n end\n\n @testset \"Two inter-twined cycles\" begin\n notebook = Notebook(Cell.([\n \"\"\"\n begin\n struct A\n x\n A(x) = A(inv(x))\n end\n rand()\n end\n \"\"\",\n \"Base.inv(::A) = A(1)\",\n \"\"\"\n struct B\n x\n B(x) = B(inv(x))\n end\n \"\"\",\n \"Base.inv(::B) = B(1)\",\n ]))\n update_run!(🍭, notebook, notebook.cells)\n\n @test all(noerror, notebook.cells)\n output_1 = notebook.cells[begin].output.body\n\n update_run!(🍭, notebook, notebook.cells[2])\n\n @test noerror(notebook.cells[1])\n @test notebook.cells[1].output.body == output_1\n @test noerror(notebook.cells[2])\n\n setcode.(notebook.cells, [\"\"])\n update_run!(🍭, notebook, notebook.cells)\n WorkspaceManager.unmake_workspace((🍭, notebook))\n end\n\n @testset \"Multiple methods across cells\" begin\n notebook = Notebook([\n Cell(\"a(x) = 1\"),\n Cell(\"a(x,y) = 2\"),\n Cell(\"a(3)\"),\n Cell(\"a(4,4)\"),\n\n Cell(\"b = 5\"),\n Cell(\"b(x) = 6\"),\n Cell(\"b + 7\"),\n Cell(\"b(8)\"),\n\n Cell(\"Base.tan(x::String) = 9\"),\n Cell(\"Base.tan(x::Missing) = 10\"),\n Cell(\"Base.tan(\\\"eleven\\\")\"),\n Cell(\"Base.tan(missing)\"),\n Cell(\"tan(missing)\"),\n\n Cell(\"d(x::Integer) = 14\"),\n Cell(\"d(x::String) = 15\"),\n Cell(\"d(16)\"),\n Cell(\"d(\\\"seventeen\\\")\"),\n Cell(\"d\"),\n\n Cell(\"struct asdf; x; y; end\"),\n Cell(\"\"),\n Cell(\"asdf(21, 21)\"),\n Cell(\"asdf(22)\"),\n\n Cell(\"@enum e1 e2 e3\"),\n Cell(\"@enum e4 e5=24\"),\n Cell(\"Base.@enum e6 e7=25 e8\"),\n Cell(\"Base.@enum e9 e10=26 e11\"),\n Cell(\"\"\"@enum e12 begin\n e13=27\n e14\n end\"\"\"),\n ])\n fakeclient.connected_notebook = notebook\n\n update_run!(🍭, notebook, notebook.cells[1:4])\n @test notebook.cells[1].errored == false\n @test notebook.cells[2].errored == false\n @test notebook.cells[3].output.body == \"1\"\n @test notebook.cells[4].output.body == \"2\"\n\n setcode(notebook.cells[1], \"a(x,x) = 999\")\n update_run!(🍭, notebook, notebook.cells[1])\n @test notebook.cells[1].errored == true\n @test notebook.cells[2].errored == true\n @test notebook.cells[3].errored == true\n @test notebook.cells[4].errored == true\n \n setcode(notebook.cells[1], \"a(x) = 1\")\n update_run!(🍭, notebook, notebook.cells[1])\n @test notebook.cells[1].errored == false\n @test notebook.cells[2].errored == false\n @test notebook.cells[3].output.body == \"1\"\n @test notebook.cells[4].output.body == \"2\"\n\n setcode(notebook.cells[1], \"\")\n update_run!(🍭, notebook, notebook.cells[1])\n @test notebook.cells[1].errored == false\n @test notebook.cells[2].errored == false\n @test notebook.cells[3].errored == true\n @test notebook.cells[4].output.body == \"2\"\n\n update_run!(🍭, notebook, notebook.cells[5:8])\n @test notebook.cells[5].errored == true\n @test notebook.cells[6].errored == true\n @test notebook.cells[7].errored == true\n @test notebook.cells[8].errored == true\n\n setcode(notebook.cells[5], \"\")\n update_run!(🍭, notebook, notebook.cells[5])\n @test notebook.cells[5].errored == false\n @test notebook.cells[6].errored == false\n @test notebook.cells[7].errored == true\n @test notebook.cells[8].output.body == \"6\"\n\n setcode(notebook.cells[5], \"b = 5\")\n setcode(notebook.cells[6], \"\")\n update_run!(🍭, notebook, notebook.cells[5:6])\n @test notebook.cells[5].errored == false\n @test notebook.cells[6].errored == false\n @test notebook.cells[7].output.body == \"12\"\n @test notebook.cells[8].errored == true\n\n update_run!(🍭, notebook, notebook.cells[11:13])\n @test notebook.cells[12].output.body == \"missing\"\n\n update_run!(🍭, notebook, notebook.cells[9:10])\n @test notebook.cells[9].errored == false\n @test notebook.cells[10].errored == false\n @test notebook.cells[11].output.body == \"9\"\n @test notebook.cells[12].output.body == \"10\"\n @test notebook.cells[13].output.body == \"10\"\n update_run!(🍭, notebook, notebook.cells[13])\n @test notebook.cells[13].output.body == \"10\"\n\n setcode(notebook.cells[9], \"\")\n update_run!(🍭, notebook, notebook.cells[9])\n @test notebook.cells[11].errored == true\n @test notebook.cells[12].output.body == \"10\"\n\n setcode(notebook.cells[10], \"\")\n update_run!(🍭, notebook, notebook.cells[10])\n @test notebook.cells[11].errored == true\n @test notebook.cells[12].output.body == \"missing\"\n\n # Cell(\"d(x::Integer) = 14\"),\n # Cell(\"d(x::String) = 15\"),\n # Cell(\"d(16)\"),\n # Cell(\"d(\\\"seventeen\\\")\"),\n # Cell(\"d\"),\n\n update_run!(🍭, notebook, notebook.cells[16:18])\n @test notebook.cells[16].errored == true\n @test notebook.cells[17].errored == true\n @test notebook.cells[18].errored == true\n\n update_run!(🍭, notebook, notebook.cells[14])\n @test notebook.cells[16].errored == false\n @test notebook.cells[17].errored == true\n @test notebook.cells[18].errored == false\n\n update_run!(🍭, notebook, notebook.cells[15])\n @test notebook.cells[16].errored == false\n @test notebook.cells[17].errored == false\n @test notebook.cells[18].errored == false\n\n setcode(notebook.cells[14], \"\")\n update_run!(🍭, notebook, notebook.cells[14])\n @test notebook.cells[16].errored == true\n @test notebook.cells[17].errored == false\n @test notebook.cells[18].errored == false\n\n setcode(notebook.cells[15], \"\")\n update_run!(🍭, notebook, notebook.cells[15])\n @test notebook.cells[16].errored == true\n @test notebook.cells[17].errored == true\n @test notebook.cells[18].errored == true\n @test occursinerror(\"UndefVarError\", notebook.cells[18])\n\n # Cell(\"struct e; x; y; end\"),\n # Cell(\"\"),\n # Cell(\"e(21, 21)\"),\n # Cell(\"e(22)\"),\n\n update_run!(🍭, notebook, notebook.cells[19:22])\n @test notebook.cells[19].errored == false\n @test notebook.cells[21].errored == false\n @test notebook.cells[22].errored == true\n\n setcode(notebook.cells[20], \"asdf(x) = asdf(x,x)\")\n update_run!(🍭, notebook, notebook.cells[20])\n @test occursinerror(\"Multiple definitions\", notebook.cells[19])\n @test occursinerror(\"Multiple definitions\", notebook.cells[20])\n @test occursinerror(\"asdf\", notebook.cells[20])\n @test occursinerror(\"asdf\", notebook.cells[20])\n @test notebook.cells[21].errored == true\n @test notebook.cells[22].errored == true\n\n setcode(notebook.cells[20], \"\")\n update_run!(🍭, notebook, notebook.cells[20])\n @test notebook.cells[19].errored == false\n @test notebook.cells[20].errored == false\n @test notebook.cells[21].errored == false\n @test notebook.cells[22].errored == true\n\n setcode(notebook.cells[19], \"begin struct asdf; x; y; end; asdf(x) = asdf(x,x); end\")\n setcode(notebook.cells[20], \"\")\n update_run!(🍭, notebook, notebook.cells[19:20])\n @test notebook.cells[19].errored == false\n @test notebook.cells[20].errored == false\n @test notebook.cells[21].errored == false\n @test notebook.cells[22].errored == false\n\n update_run!(🍭, notebook, notebook.cells[23:27])\n @test notebook.cells[23].errored == false\n @test notebook.cells[24].errored == false\n @test notebook.cells[25].errored == false\n @test notebook.cells[26].errored == false\n @test notebook.cells[27].errored == false\n update_run!(🍭, notebook, notebook.cells[23:27])\n @test notebook.cells[23].errored == false\n @test notebook.cells[24].errored == false\n @test notebook.cells[25].errored == false\n @test notebook.cells[26].errored == false\n @test notebook.cells[27].errored == false\n\n setcode.(notebook.cells[23:27], [\"\"])\n update_run!(🍭, notebook, notebook.cells[23:27])\n\n setcode(notebook.cells[23], \"@assert !any(isdefined.([@__MODULE__], [Symbol(:e,i) for i in 1:14]))\")\n update_run!(🍭, notebook, notebook.cells[23])\n @test notebook.cells[23].errored == false\n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n\n # for some unsupported edge cases, see:\n # https://github.com/fonsp/Pluto.jl/issues/177#issuecomment-645039993\n end\n\n @testset \"Cyclic\" begin\n notebook = Notebook([\n Cell(\"xxx = yyy\")\n Cell(\"yyy = xxx\")\n Cell(\"zzz = yyy\")\n\n Cell(\"aaa() = bbb\")\n Cell(\"bbb = aaa()\")\n \n Cell(\"w1(x) = w2(x - 1) + 1\")\n Cell(\"w2(x) = x > 0 ? w1(x) : x\")\n Cell(\"w1(8)\")\n \n Cell(\"p1(x) = p2(x) + p1(x)\")\n Cell(\"p2(x) = p1(x)\")\n\n # 11\n Cell(\"z(x::String) = z(1)\")\n Cell(\"z(x::Integer) = z()\")\n \n # 13\n # some random Base function that we are overloading \n Cell(\"Base.get(x::InterruptException) = Base.get(1)\")\n Cell(\"Base.get(x::ArgumentError) = Base.get()\")\n \n Cell(\"Base.step(x::InterruptException) = step(1)\")\n Cell(\"Base.step(x::ArgumentError) = step()\")\n \n Cell(\"Base.exponent(x::InterruptException) = Base.exponent(1)\")\n Cell(\"Base.exponent(x::ArgumentError) = exponent()\")\n \n # 19\n Cell(\"Base.chomp(x::InterruptException) = split() + chomp()\")\n Cell(\"Base.chomp(x::ArgumentError) = chomp()\")\n Cell(\"Base.split(x::InterruptException) = split()\")\n \n # 22\n Cell(\"Base.transpose(x::InterruptException) = Base.trylock() + Base.transpose()\")\n Cell(\"Base.transpose(x::ArgumentError) = Base.transpose()\")\n Cell(\"Base.trylock(x::InterruptException) = Base.trylock()\")\n\n # 25\n Cell(\"Base.digits(x::ArgumentError) = Base.digits() + Base.isconst()\")\n Cell(\"Base.isconst(x::InterruptException) = digits()\")\n\n # 27\n Cell(\"f(x) = g(x-1)\")\n Cell(\"g(x) = h(x-1)\")\n Cell(\"h(x) = i(x-1)\")\n Cell(\"i(x) = j(x-1)\")\n Cell(\"j(x) = (x > 0) ? f(x-1) : :done\")\n Cell(\"f(8)\")\n ])\n fakeclient.connected_notebook = notebook\n\n update_run!(🍭, notebook, notebook.cells[1:3])\n @test occursinerror(\"Cyclic reference\", notebook.cells[1])\n @test occursinerror(\"xxx\", notebook.cells[1])\n @test occursinerror(\"yyy\", notebook.cells[1])\n @test occursinerror(\"Cyclic reference\", notebook.cells[2])\n @test occursinerror(\"xxx\", notebook.cells[2])\n @test occursinerror(\"yyy\", notebook.cells[2])\n @test occursinerror(\"UndefVarError\", notebook.cells[3])\n\n setcode(notebook.cells[1], \"xxx = 1\")\n update_run!(🍭, notebook, notebook.cells[1])\n @test notebook.cells[1].output.body == \"1\"\n @test notebook.cells[2].output.body == \"1\"\n @test notebook.cells[3].output.body == \"1\"\n\n setcode(notebook.cells[1], \"xxx = zzz\")\n update_run!(🍭, notebook, notebook.cells[1])\n @test occursinerror(\"Cyclic reference\", notebook.cells[1])\n @test occursinerror(\"Cyclic reference\", notebook.cells[2])\n @test occursinerror(\"Cyclic reference\", notebook.cells[3])\n @test occursinerror(\"xxx\", notebook.cells[1])\n @test occursinerror(\"yyy\", notebook.cells[1])\n @test occursinerror(\"zzz\", notebook.cells[1])\n @test occursinerror(\"xxx\", notebook.cells[2])\n @test occursinerror(\"yyy\", notebook.cells[2])\n @test occursinerror(\"zzz\", notebook.cells[2])\n @test occursinerror(\"xxx\", notebook.cells[3])\n @test occursinerror(\"yyy\", notebook.cells[3])\n @test occursinerror(\"zzz\", notebook.cells[3])\n\n setcode(notebook.cells[3], \"zzz = 3\")\n update_run!(🍭, notebook, notebook.cells[3])\n @test notebook.cells[1].output.body == \"3\"\n @test notebook.cells[2].output.body == \"3\"\n @test notebook.cells[3].output.body == \"3\"\n\n ##\n \n \n update_run!(🍭, notebook, notebook.cells[4:5])\n @test occursinerror(\"Cyclic reference\", notebook.cells[4])\n @test occursinerror(\"aaa\", notebook.cells[4])\n @test occursinerror(\"bbb\", notebook.cells[4])\n @test occursinerror(\"Cyclic reference\", notebook.cells[5])\n @test occursinerror(\"aaa\", notebook.cells[5])\n @test occursinerror(\"bbb\", notebook.cells[5])\n\n \n \n \n \n update_run!(🍭, notebook, notebook.cells[6:end])\n @test noerror(notebook.cells[6])\n @test noerror(notebook.cells[7])\n @test noerror(notebook.cells[8])\n @test noerror(notebook.cells[9])\n @test noerror(notebook.cells[10])\n @test noerror(notebook.cells[11])\n @test noerror(notebook.cells[12])\n @test noerror(notebook.cells[13])\n @test noerror(notebook.cells[14])\n @test noerror(notebook.cells[15])\n @test noerror(notebook.cells[16])\n @test noerror(notebook.cells[17])\n @test noerror(notebook.cells[18])\n @test noerror(notebook.cells[19])\n @test noerror(notebook.cells[20])\n @test noerror(notebook.cells[21])\n @test noerror(notebook.cells[22])\n @test noerror(notebook.cells[23])\n @test noerror(notebook.cells[24])\n @test noerror(notebook.cells[25])\n @test noerror(notebook.cells[26])\n\n ##\n @test noerror(notebook.cells[27])\n @test noerror(notebook.cells[28])\n @test noerror(notebook.cells[29])\n @test noerror(notebook.cells[30])\n @test noerror(notebook.cells[31])\n @test noerror(notebook.cells[32])\n @test notebook.cells[32].output.body == \":done\"\n\n @assert length(notebook.cells) == 32\n \n # Empty and run cells to remove the Base overloads that we created, just to be sure\n setcode.(notebook.cells, [\"\"])\n update_run!(🍭, notebook, notebook.cells)\n \n WorkspaceManager.unmake_workspace((🍭, notebook))\n end\n\n @testset \"Variable deletion\" begin\n notebook = Notebook([\n Cell(\"x = 1\"),\n Cell(\"y = x\"),\n Cell(\"struct a; x end\"),\n Cell(\"a\")\n ])\n fakeclient.connected_notebook = notebook\n\n update_run!(🍭, notebook, notebook.cells[1:2])\n @test notebook.cells[1].output.body == notebook.cells[2].output.body\n \n setcode(notebook.cells[1], \"\")\n update_run!(🍭, notebook, notebook.cells[1])\n @test notebook.cells[1].errored == false\n @test occursinerror(\"x not defined\", notebook.cells[2])\n\n update_run!(🍭, notebook, notebook.cells[4])\n update_run!(🍭, notebook, notebook.cells[3])\n @test notebook.cells[3].errored == false\n @test notebook.cells[4].errored == false\n update_run!(🍭, notebook, notebook.cells[3])\n @test notebook.cells[3].errored == false\n @test notebook.cells[4].errored == false\n setcode(notebook.cells[3], \"struct a; x; y end\")\n update_run!(🍭, notebook, notebook.cells[3])\n @test notebook.cells[3].errored == false\n @test notebook.cells[4].errored == false\n setcode(notebook.cells[3], \"\")\n update_run!(🍭, notebook, notebook.cells[3])\n @test notebook.cells[3].errored == false\n @test notebook.cells[4].errored == true\n\n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n end\n\n @testset \"Recursion\" begin\n notebook = Notebook([\n Cell(\"f(n) = n * f(n-1)\"),\n\n Cell(\"k = 1\"),\n Cell(\"\"\"begin\n g(n) = h(n-1) + k\n h(n) = n > 0 ? g(n-1) : 0\n end\"\"\"),\n\n Cell(\"h(4)\"),\n ])\n fakeclient.connected_notebook = notebook\n\n update_run!(🍭, notebook, notebook.cells[1])\n @test notebook.cells[1].output.body == \"f\" || startswith(notebook.cells[1].output.body, \"f (generic function with \")\n @test notebook.cells[1].errored == false\n\n update_run!(🍭, notebook, notebook.cells[2:3])\n @test notebook.cells[2].errored == false\n @test notebook.cells[3].errored == false\n update_run!(🍭, notebook, notebook.cells[3])\n @test notebook.cells[3].errored == false\n\n update_run!(🍭, notebook, notebook.cells[4])\n @test notebook.cells[4].output.body == \"2\"\n\n setcode(notebook.cells[2], \"k = 2\")\n update_run!(🍭, notebook, notebook.cells[2])\n @test notebook.cells[4].output.body == \"4\"\n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n end\n\n @testset \"Variable cannot reference its previous value\" begin\n notebook = Notebook([\n Cell(\"x = 3\")\n ])\n fakeclient.connected_notebook = notebook\n\n update_run!(🍭, notebook, notebook.cells[1])\n setcode(notebook.cells[1], \"x = x + 1\")\n update_run!(🍭, notebook, notebook.cells[1])\n @test occursinerror(\"UndefVarError\", notebook.cells[1])\n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n end\n\n notebook = Notebook([\n Cell(\"y = 1\"),\n Cell(\"f(x) = x + y\"),\n Cell(\"f(3)\"),\n\n Cell(\"g(a,b) = a+b\"),\n Cell(\"g(5,6)\"),\n\n Cell(\"h(x::Int) = x\"),\n Cell(\"h(7)\"),\n Cell(\"h(8.0)\"),\n\n Cell(\"p(x) = 9\"),\n Cell(\"p isa Function\"),\n\n Cell(\"module Something\n export a\n a(x::String) = \\\"🐟\\\"\n end\"),\n Cell(\"using .Something\"),\n Cell(\"a(x::Int) = x\"),\n Cell(\"a(\\\"i am a \\\")\"),\n Cell(\"a(15)\"),\n \n Cell(\"module Different\n export b\n b(x::String) = \\\"🐟\\\"\n end\"),\n Cell(\"import .Different: b\"),\n Cell(\"b(x::Int) = x\"),\n Cell(\"b(\\\"i am a \\\")\"),\n Cell(\"b(20)\"),\n \n Cell(\"module Wow\n export c\n c(x::String) = \\\"🐟\\\"\n end\"),\n Cell(\"begin\n import .Wow: c\n c(x::Int) = x\n end\"),\n Cell(\"c(\\\"i am a \\\")\"),\n Cell(\"c(24)\"),\n\n Cell(\"Ref((25,:fish))\"),\n Cell(\"begin\n import Base: show\n show(io::IO, x::Ref{Tuple{Int,Symbol}}) = write(io, \\\"🐟\\\")\n end\"),\n\n Cell(\"Base.isodd(n::Integer) = \\\"🎈\\\"\"),\n Cell(\"Base.isodd(28)\"),\n Cell(\"isodd(29)\"),\n\n Cell(\"using Dates\"),\n Cell(\"year(DateTime(31))\"),\n ])\n fakeclient.connected_notebook = notebook\n\n @testset \"Changing functions\" begin\n\n update_run!(🍭, notebook, notebook.cells[2])\n @test notebook.cells[2].errored == false\n\n update_run!(🍭, notebook, notebook.cells[1])\n update_run!(🍭, notebook, notebook.cells[3])\n @test notebook.cells[3].output.body == \"4\"\n\n setcode(notebook.cells[1], \"y = 2\")\n update_run!(🍭, notebook, notebook.cells[1])\n @test notebook.cells[3].output.body == \"5\"\n @test notebook.cells[2].errored == false\n\n setcode(notebook.cells[1], \"y\")\n update_run!(🍭, notebook, notebook.cells[1])\n @test occursinerror(\"UndefVarError\", notebook.cells[1])\n @test notebook.cells[2].errored == false\n @test occursinerror(\"UndefVarError\", notebook.cells[3])\n\n update_run!(🍭, notebook, notebook.cells[4])\n update_run!(🍭, notebook, notebook.cells[5])\n @test notebook.cells[5].output.body == \"11\"\n\n setcode(notebook.cells[4], \"g(a) = a+a\")\n update_run!(🍭, notebook, notebook.cells[4])\n @test notebook.cells[4].errored == false\n @test notebook.cells[5].errored == true\n\n setcode(notebook.cells[5], \"g(5)\")\n update_run!(🍭, notebook, notebook.cells[5])\n @test notebook.cells[5].output.body == \"10\"\n\n update_run!(🍭, notebook, notebook.cells[6])\n update_run!(🍭, notebook, notebook.cells[7])\n update_run!(🍭, notebook, notebook.cells[8])\n @test notebook.cells[6].errored == false\n @test notebook.cells[7].errored == false\n @test notebook.cells[8].errored == true\n \n setcode(notebook.cells[6], \"h(x::Float64) = 2.0 * x\")\n update_run!(🍭, notebook, notebook.cells[6])\n @test notebook.cells[6].errored == false\n @test notebook.cells[7].errored == true\n @test notebook.cells[8].errored == false\n\n update_run!(🍭, notebook, notebook.cells[9:10])\n @test notebook.cells[9].errored == false\n @test notebook.cells[10].output.body == \"true\"\n\n setcode(notebook.cells[9], \"p = p\")\n update_run!(🍭, notebook, notebook.cells[9])\n @test occursinerror(\"UndefVarError\", notebook.cells[9])\n\n setcode(notebook.cells[9], \"p = 9\")\n update_run!(🍭, notebook, notebook.cells[9])\n @test notebook.cells[9].errored == false\n @test notebook.cells[10].output.body == \"false\"\n \n setcode(notebook.cells[9], \"p(x) = 9\")\n update_run!(🍭, notebook, notebook.cells[9])\n @test notebook.cells[9].errored == false\n @test notebook.cells[10].output.body == \"true\"\n end\n\n @testset \"Extending imported functions\" begin\n update_run!(🍭, notebook, notebook.cells[11:15])\n @test_broken notebook.cells[11].errored == false\n @test_broken notebook.cells[12].errored == false # multiple definitions for `Something` should be okay? == false\n @test notebook.cells[13].errored == false\n @test notebook.cells[14].errored == true # the definition for a was created before `a` was used, so it hides the `a` from `Something`\n @test notebook.cells[15].output.body == \"15\"\n\n \n @test_nowarn update_run!(🍭, notebook, notebook.cells[13:15])\n @test notebook.cells[13].errored == false\n @test notebook.cells[14].errored == true # the definition for a was created before `a` was used, so it hides the `a` from `Something`\n @test notebook.cells[15].output.body == \"15\"\n\n @test_nowarn update_run!(🍭, notebook, notebook.cells[16:20])\n @test notebook.cells[16].errored == false\n @test occursinerror(\"Multiple\", notebook.cells[17])\n @test occursinerror(\"Multiple\", notebook.cells[18])\n @test occursinerror(\"UndefVarError\", notebook.cells[19])\n @test occursinerror(\"UndefVarError\", notebook.cells[20])\n\n @test_nowarn update_run!(🍭, notebook, notebook.cells[21:24])\n @test notebook.cells[21].errored == false\n @test notebook.cells[22].errored == false\n @test notebook.cells[23].errored == false\n @test notebook.cells[23].output.body == \"\\\"🐟\\\"\"\n @test notebook.cells[24].output.body == \"24\"\n\n setcode(notebook.cells[22], \"import .Wow: c\")\n @test_nowarn update_run!(🍭, notebook, notebook.cells[22])\n @test notebook.cells[22].errored == false\n @test notebook.cells[23].output.body == \"\\\"🐟\\\"\"\n @test notebook.cells[23].errored == false\n @test notebook.cells[24].errored == true # the extension should no longer exist\n\n # https://github.com/fonsp/Pluto.jl/issues/59\n original_repr = Pluto.PlutoRunner.format_output(Ref((25, :fish)))[1]\n @test_nowarn update_run!(🍭, notebook, notebook.cells[25])\n @test notebook.cells[25].output.body isa Dict\n @test_nowarn update_run!(🍭, notebook, notebook.cells[26])\n @test_broken notebook.cells[25].output.body == \"🐟\" # cell'🍭 don't automatically call `show` again when a new overload is defined - that'🍭 a minor issue\n @test_nowarn update_run!(🍭, notebook, notebook.cells[25])\n @test notebook.cells[25].output.body == \"🐟\"\n\n setcode(notebook.cells[26], \"\")\n @test_nowarn update_run!(🍭, notebook, notebook.cells[26])\n @test_nowarn update_run!(🍭, notebook, notebook.cells[25])\n @test notebook.cells[25].output.body isa Dict\n\n @test_nowarn update_run!(🍭, notebook, notebook.cells[28:29])\n @test notebook.cells[28].output.body == \"false\"\n @test notebook.cells[29].output.body == \"true\"\n @test_nowarn update_run!(🍭, notebook, notebook.cells[27])\n @test notebook.cells[28].output.body == \"\\\"🎈\\\"\"\n @test notebook.cells[29].output.body == \"\\\"🎈\\\"\" # adding the overload doesn't trigger automatic re-eval because `isodd` doesn't match `Base.isodd`\n @test_nowarn update_run!(🍭, notebook, notebook.cells[28:29])\n @test notebook.cells[28].output.body == \"\\\"🎈\\\"\"\n @test notebook.cells[29].output.body == \"\\\"🎈\\\"\"\n\n setcode(notebook.cells[27], \"\")\n update_run!(🍭, notebook, notebook.cells[27])\n @test notebook.cells[28].output.body == \"false\"\n @test notebook.cells[29].output.body == \"true\" # removing the overload doesn't trigger automatic re-eval because `isodd` doesn't match `Base.isodd`\n update_run!(🍭, notebook, notebook.cells[28:29])\n @test notebook.cells[28].output.body == \"false\"\n @test notebook.cells[29].output.body == \"true\"\n end\n\n @testset \"Using external libraries\" begin\n update_run!(🍭, notebook, notebook.cells[30:31])\n @test notebook.cells[30].errored == false\n @test notebook.cells[31].output.body == \"31\"\n update_run!(🍭, notebook, notebook.cells[31])\n @test notebook.cells[31].output.body == \"31\"\n\n setcode(notebook.cells[30], \"\")\n update_run!(🍭, notebook, notebook.cells[30:31])\n @test occursinerror(\"UndefVarError\", notebook.cells[31])\n end\n WorkspaceManager.unmake_workspace((🍭, notebook))\n\n @testset \"Functional programming\" begin\n notebook = Notebook([\n Cell(\"a = 1\"),\n Cell(\"map(2:2) do val; (a = val; 2*val) end |> last\"),\n\n Cell(\"b = 3\"),\n Cell(\"g = f\"),\n Cell(\"f(x) = x + b\"),\n Cell(\"g(6)\"),\n\n Cell(\"h = [x -> x + b][1]\"),\n Cell(\"h(8)\"),\n ])\n fakeclient.connected_notebook = notebook\n\n update_run!(🍭, notebook, notebook.cells[1:2])\n @test notebook.cells[1].output.body == \"1\"\n @test notebook.cells[2].output.body == \"4\"\n\n update_run!(🍭, notebook, notebook.cells[3:6])\n @test notebook.cells[3].errored == false\n @test notebook.cells[4].errored == false\n @test notebook.cells[5].errored == false\n @test notebook.cells[6].errored == false\n @test notebook.cells[6].output.body == \"9\"\n\n setcode(notebook.cells[3], \"b = -3\")\n update_run!(🍭, notebook, notebook.cells[3])\n @test notebook.cells[6].output.body == \"3\"\n\n update_run!(🍭, notebook, notebook.cells[7:8])\n @test notebook.cells[7].errored == false\n @test notebook.cells[8].output.body == \"5\"\n\n setcode(notebook.cells[3], \"b = 3\")\n update_run!(🍭, notebook, notebook.cells[3])\n @test notebook.cells[8].output.body == \"11\"\n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n \n end\n\n @testset \"Global assignments inside functions\" begin\n # We currently have a slightly relaxed version of immutable globals:\n # globals can only be mutated/assigned _in a single cell_.\n notebook = Notebook([\n Cell(\"x = 1\"),\n Cell(\"x = 2\"),\n Cell(\"y = -3; y = 3\"),\n Cell(\"z = 4\"),\n Cell(\"let global z = 5 end\"),\n Cell(\"wowow\"),\n Cell(\"function floep(x) global wowow = x end\"),\n Cell(\"floep(8)\"),\n Cell(\"v\"),\n Cell(\"function g(x) global v = x end; g(10)\"),\n Cell(\"g(11)\"),\n Cell(\"let\n local r = 0\n function f()\n r = 12\n end\n f()\n r\n end\"),\n Cell(\"apple\"),\n Cell(\"map(14:14) do i; global apple = orange; end\"),\n Cell(\"orange = 15\"),\n ])\n fakeclient.connected_notebook = notebook\n\n update_run!(🍭, notebook, notebook.cells[1])\n update_run!(🍭, notebook, notebook.cells[2])\n @test occursinerror(\"Multiple definitions for x\", notebook.cells[1])\n @test occursinerror(\"Multiple definitions for x\", notebook.cells[1])\n \n setcode(notebook.cells[2], \"x + 1\")\n update_run!(🍭, notebook, notebook.cells[2])\n @test notebook.cells[1].output.body == \"1\"\n @test notebook.cells[2].output.body == \"2\"\n \n update_run!(🍭, notebook, notebook.cells[3])\n @test notebook.cells[3].output.body == \"3\"\n\n update_run!(🍭, notebook, notebook.cells[4])\n update_run!(🍭, notebook, notebook.cells[5])\n @test occursinerror(\"Multiple definitions for z\", notebook.cells[4])\n @test occursinerror(\"Multiple definitions for z\", notebook.cells[5])\n \n update_run!(🍭, notebook, notebook.cells[6:7])\n @test occursinerror(\"UndefVarError\", notebook.cells[6])\n\n # @test_broken occursinerror(\"assigns to global\", notebook.cells[7])\n # @test_broken occursinerror(\"wowow\", notebook.cells[7])\n # @test_broken occursinerror(\"floep\", notebook.cells[7])\n \n update_run!(🍭, notebook, notebook.cells[8])\n @test_broken !occursinerror(\"UndefVarError\", notebook.cells[6])\n\n update_run!(🍭, notebook, notebook.cells[9:10])\n @test !occursinerror(\"UndefVarError\", notebook.cells[9])\n @test notebook.cells[10].errored == false\n\n update_run!(🍭, notebook, notebook.cells[11])\n @test_broken notebook.cells[9].errored == true\n @test_broken notebook.cells[10].errored == true\n @test_broken notebook.cells[11].errored == true\n\n update_run!(🍭, notebook, notebook.cells[12])\n @test notebook.cells[12].output.body == \"12\"\n\n update_run!(🍭, notebook, notebook.cells[13:15])\n @test notebook.cells[13].output.body == \"15\"\n @test notebook.cells[14].errored == false\n\n setcode(notebook.cells[15], \"orange = 10005\")\n update_run!(🍭, notebook, notebook.cells[15])\n @test notebook.cells[13].output.body == \"10005\"\n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n end\n\n @testset \"No top level return\" begin\n notebook = Notebook([\n Cell(\"return 10\"),\n Cell(\"return (0, 0)\"),\n Cell(\"return (0, 0)\"),\n Cell(\"return (0, 0, 0)\"),\n Cell(\"begin return \\\"a string\\\" end\"),\n Cell(\"\"\"\n let\n return []\n end\n \"\"\"),\n Cell(\"\"\"filter(1:3) do x\n return true\n end\"\"\"),\n\n # create struct to disable the function-generating optimization\n Cell(\"struct A1 end; return 10\"),\n Cell(\"struct A2 end; return (0, 0)\"),\n Cell(\"struct A3 end; return (0, 0)\"),\n Cell(\"struct A4 end; return (0, 0, 0)\"),\n Cell(\"struct A5 end; begin return \\\"a string\\\" end\"),\n Cell(\"\"\"\n struct A6 end; let\n return []\n end\n \"\"\"),\n Cell(\"\"\"struct A7 end; filter(1:3) do x\n return true\n end\"\"\"),\n\n # Function assignments\n Cell(\"\"\"f(x) = if x == 1\n return false\n else\n return true\n end\"\"\"),\n Cell(\"\"\"g(x::T) where {T} = if x == 1\n return false\n else\n return true\n end\"\"\"),\n Cell(\"(h(x::T)::MyType) where {T} = return(x)\"),\n Cell(\"i(x)::MyType = return(x)\"),\n ])\n\n update_run!(🍭, notebook, notebook.cells)\n @test occursinerror(\"You can only use return inside a function.\", notebook.cells[1])\n @test occursinerror(\"You can only use return inside a function.\", notebook.cells[2])\n @test occursinerror(\"You can only use return inside a function.\", notebook.cells[3])\n @test occursinerror(\"You can only use return inside a function.\", notebook.cells[4])\n @test occursinerror(\"You can only use return inside a function.\", notebook.cells[5])\n @test occursinerror(\"You can only use return inside a function.\", notebook.cells[6])\n @test notebook.cells[7] |> noerror\n\n @test occursinerror(\"You can only use return inside a function.\", notebook.cells[8])\n @test occursinerror(\"You can only use return inside a function.\", notebook.cells[9])\n @test occursinerror(\"You can only use return inside a function.\", notebook.cells[10])\n @test occursinerror(\"You can only use return inside a function.\", notebook.cells[11])\n @test occursinerror(\"You can only use return inside a function.\", notebook.cells[12])\n @test occursinerror(\"You can only use return inside a function.\", notebook.cells[13])\n @test notebook.cells[14] |> noerror\n\n # Function assignments\n @test notebook.cells[15] |> noerror\n @test notebook.cells[16] |> noerror\n @test notebook.cells[17] |> noerror\n @test notebook.cells[18] |> noerror\n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n end\n\n @testset \"Function wrapping\" begin\n notebook = Notebook([\n Cell(\"false && jlaksdfjalskdfj\"),\n Cell(\"fonsi = 2\"),\n Cell(\"\"\"\n filter(1:fonsi) do x\n x = sum(1 for z in 1:x)\n x = sum(1 for z in 1:x)\n x = sum(1 for z in 1:x)\n x = sum(1 for z in 1:x)\n x = sum(1 for z in 1:x)\n x = sum(1 for z in 1:x)\n false\n end |> length\n \"\"\"),\n Cell(\"4\"),\n Cell(\"[5]\"),\n Cell(\"6 / 66\"),\n Cell(\"false && (seven = 7)\"),\n Cell(\"seven\"),\n \n Cell(\"nine = :identity\"),\n Cell(\"nine\"),\n Cell(\"@__FILE__; nine\"),\n Cell(\"@__FILE__; twelve = :identity\"),\n Cell(\"@__FILE__; twelve\"),\n Cell(\"twelve\"),\n\n Cell(\"fifteen = :(1 + 1)\"),\n Cell(\"fifteen\"),\n Cell(\"@__FILE__; fifteen\"),\n Cell(\"@__FILE__; eighteen = :(1 + 1)\"),\n Cell(\"@__FILE__; eighteen\"),\n Cell(\"eighteen\"),\n\n Cell(\"qb = quote value end\"),\n Cell(\"typeof(qb)\"),\n\n Cell(\"qn0 = QuoteNode(:value)\"),\n Cell(\"qn1 = :(:value)\"),\n Cell(\"qn0\"),\n Cell(\"qn1\"),\n\n Cell(\"\"\"\n named_tuple(obj::T) where {T} = NamedTuple{fieldnames(T),Tuple{fieldtypes(T)...}}(ntuple(i -> getfield(obj, i), fieldcount(T)))\n \"\"\"),\n Cell(\"named_tuple\"),\n \n Cell(\"ln = LineNumberNode(29, \\\"asdf\\\")\"),\n Cell(\"@assert ln isa LineNumberNode\"),\n ])\n\n update_run!(🍭, notebook, notebook.cells)\n @test notebook.cells[1].errored == false\n @test notebook.cells[1].output.body == \"false\"\n @test notebook.cells[22].output.body == \"Expr\"\n @test notebook.cells[25].output.body == \":(:value)\"\n @test notebook.cells[26].output.body == \":(:value)\"\n\n function benchmark(fonsi)\n filter(1:fonsi) do x\n x = sum(1 for z in 1:x)\n x = sum(1 for z in 1:x)\n x = sum(1 for z in 1:x)\n x = sum(1 for z in 1:x)\n x = sum(1 for z in 1:x)\n x = sum(1 for z in 1:x)\n false\n end |> length\n end\n\n bad = @elapsed benchmark(2)\n good = 0.01 * @elapsed for i in 1:100\n benchmark(2)\n end\n\n update_run!(🍭, notebook, notebook.cells)\n @test 0.1 * good < notebook.cells[3].runtime / 1.0e9 < 0.5 * bad\n\n old = notebook.cells[4].output.body\n setcode(notebook.cells[4], \"4.0\")\n update_run!(🍭, notebook, notebook.cells[4])\n @test old != notebook.cells[4].output.body\n \n old = notebook.cells[5].output.body\n setcode(notebook.cells[5], \"[5.0]\")\n update_run!(🍭, notebook, notebook.cells[5])\n @test old != notebook.cells[5].output.body\n\n old = notebook.cells[6].output.body\n setcode(notebook.cells[6], \"66 / 6\")\n update_run!(🍭, notebook, notebook.cells[6])\n @test old != notebook.cells[6].output.body\n\n @test notebook.cells[7].errored == false\n @test notebook.cells[7].output.body == \"false\"\n\n @test occursinerror(\"UndefVarError\", notebook.cells[8])\n\n @test notebook.cells[9].output.body == \":identity\"\n @test notebook.cells[10].output.body == \":identity\"\n @test notebook.cells[11].output.body == \":identity\"\n @test notebook.cells[12].output.body == \":identity\"\n @test notebook.cells[13].output.body == \":identity\"\n @test notebook.cells[14].output.body == \":identity\"\n\n @test notebook.cells[15].output.body == \":(1 + 1)\"\n @test notebook.cells[16].output.body == \":(1 + 1)\"\n @test notebook.cells[17].output.body == \":(1 + 1)\"\n @test notebook.cells[18].output.body == \":(1 + 1)\"\n @test notebook.cells[19].output.body == \":(1 + 1)\"\n @test notebook.cells[20].output.body == \":(1 + 1)\"\n\n @test notebook.cells[27].errored == false\n @test notebook.topology.codes[notebook.cells[27]].function_wrapped == false\n @test notebook.cells[28].errored == false\n \n update_run!(🍭, notebook, notebook.cells[29:30])\n @test notebook.cells[29].errored == false\n @test notebook.cells[30].errored == false\n \n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n\n\n @testset \"Expression hash\" begin\n same(a,b) = Pluto.PlutoRunner.expr_hash(a) == Pluto.PlutoRunner.expr_hash(b)\n\n @test same(:(1), :(1))\n @test !same(:(1), :(1.0))\n @test same(:(x + 1), :(x + 1))\n @test !same(:(x + 1), :(x + 1.0))\n @test same(:(1 |> a |> a |> a), :(1 |> a |> a |> a))\n @test same(:(a(b(1,2))), :(a(b(1,2))))\n @test !same(:(a(b(1,2))), :(a(b(1,3))))\n @test !same(:(a(b(1,2))), :(a(b(1,1))))\n @test !same(:(a(b(1,2))), :(a(b(2,1))))\n end\n end\n\n @testset \"Run multiple\" begin\n notebook = Notebook([\n Cell(\"x = []\"),\n Cell(\"b = a + 2; push!(x,2)\"),\n Cell(\"c = b + a; push!(x,3)\"),\n Cell(\"a = 1; push!(x,4)\"),\n Cell(\"a + b +c; push!(x,5)\"),\n\n Cell(\"a = 1; push!(x,6)\"),\n\n Cell(\"n = m; push!(x,7)\"),\n Cell(\"m = n; push!(x,8)\"),\n Cell(\"n = 1; push!(x,9)\"),\n\n Cell(\"push!(x,10)\"),\n Cell(\"push!(x,11)\"),\n Cell(\"push!(x,12)\"),\n Cell(\"push!(x,13)\"),\n Cell(\"push!(x,14)\"),\n\n Cell(\"join(x, '-')\"),\n\n Cell(\"φ(16)\"),\n Cell(\"φ(χ) = χ + υ\"),\n Cell(\"υ = 18\"),\n\n Cell(\"f(19)\"),\n Cell(\"f(x) = x + g(x)\"),\n Cell(\"g(x) = x + y\"),\n Cell(\"y = 22\"),\n ])\n fakeclient.connected_notebook = notebook\n\n update_run!(🍭, notebook, notebook.cells[1])\n\n @testset \"Basic\" begin\n update_run!(🍭, notebook, notebook.cells[2:5])\n\n update_run!(🍭, notebook, notebook.cells[15])\n @test notebook.cells[15].output.body == \"\\\"4-2-3-5\\\"\"\n end\n \n @testset \"Errors\" begin\n update_run!(🍭, notebook, notebook.cells[6:9])\n\n # should all err, no change to `x`\n update_run!(🍭, notebook, notebook.cells[15])\n @test notebook.cells[15].output.body == \"\\\"4-2-3-5\\\"\"\n end\n\n @testset \"Maintain order when possible\" begin\n update_run!(🍭, notebook, notebook.cells[10:14])\n\n update_run!(🍭, notebook, notebook.cells[15])\n @test notebook.cells[15].output.body == \"\\\"4-2-3-5-10-11-12-13-14\\\"\"\n\n update_run!(🍭, notebook, notebook.cells[1]) # resets `x`, only 10-14 should run, in order\n @test notebook.cells[15].output.body == \"\\\"10-11-12-13-14\\\"\"\n update_run!(🍭, notebook, notebook.cells[15])\n @test notebook.cells[15].output.body == \"\\\"10-11-12-13-14\\\"\"\n end\n \n\n update_run!(🍭, notebook, notebook.cells[16:18])\n @test notebook.cells[16].errored == false\n @test notebook.cells[16].output.body == \"34\"\n @test notebook.cells[17].errored == false\n @test notebook.cells[18].errored == false\n\n setcode(notebook.cells[18], \"υ = 8\")\n update_run!(🍭, notebook, notebook.cells[18])\n @test notebook.cells[16].output.body == \"24\"\n \n update_run!(🍭, notebook, notebook.cells[19:22])\n @test notebook.cells[19].errored == false\n @test notebook.cells[19].output.body == \"60\"\n @test notebook.cells[20].errored == false\n @test notebook.cells[21].errored == false\n @test notebook.cells[22].errored == false\n\n setcode(notebook.cells[22], \"y = 0\")\n update_run!(🍭, notebook, notebook.cells[22])\n @test notebook.cells[19].output.body == \"38\"\n\n WorkspaceManager.unmake_workspace((🍭, notebook))\n end\nend"
] |
f7ab34939f3e4311aa69f0e30b7b159e7529c94c
| 78
|
jl
|
Julia
|
test/data_driven/tokenize.jl
|
charleskawczynski/BetweenFlags.jl
|
ed922db49e17b6f7dd5e34f4856dc7a4fc7c3cd9
|
[
"Apache-2.0"
] | 3
|
2019-03-08T08:03:03.000Z
|
2019-07-26T14:24:14.000Z
|
test/data_driven/tokenize.jl
|
charleskawczynski/BetweenFlags.jl
|
ed922db49e17b6f7dd5e34f4856dc7a4fc7c3cd9
|
[
"Apache-2.0"
] | 18
|
2019-02-17T21:10:15.000Z
|
2020-10-16T23:54:10.000Z
|
test/data_driven/tokenize.jl
|
charleskawczynski/BetweenFlags.jl
|
ed922db49e17b6f7dd5e34f4856dc7a4fc7c3cd9
|
[
"Apache-2.0"
] | 4
|
2019-07-26T14:25:02.000Z
|
2020-02-08T11:13:31.000Z
|
using Test
@testset "Tokenize" begin
include("julia_simple_func.jl")
end
| 13
| 35
| 0.74359
|
[
"@testset \"Tokenize\" begin\n include(\"julia_simple_func.jl\")\nend"
] |
f7ac012ffcab6f0e6690d2a0b1bf07758228c768
| 2,790
|
jl
|
Julia
|
test/runtests.jl
|
lhnguyen-vn/TreeParzen.jl
|
d6b4181a45167663e8844330220f0c62c715c75f
|
[
"BSD-3-Clause"
] | null | null | null |
test/runtests.jl
|
lhnguyen-vn/TreeParzen.jl
|
d6b4181a45167663e8844330220f0c62c715c75f
|
[
"BSD-3-Clause"
] | null | null | null |
test/runtests.jl
|
lhnguyen-vn/TreeParzen.jl
|
d6b4181a45167663e8844330220f0c62c715c75f
|
[
"BSD-3-Clause"
] | null | null | null |
using Test
@time @testset "Unit Tests" begin
@testset "Small functions" begin
@info "Bincount"
@test include("bincount.jl")
@info "Configuration"
@test include("configuration.jl")
@info "dfs"
@test include("dfs.jl")
@info "graph"
@test include("graph.jl")
@info "forgettingweights"
@test include("forgettingweights.jl")
# Needs translation from Python
# include("adaptive_parzen_normal_orig.jl")
@info "Trials"
@test include("trials.jl")
@info "GMM1"
@test include("gmm.jl")
@info "GMM1 Math and QGMM1 Math"
@test include("gmm_math.jl")
@info "LGMM1"
@test include("lgmm.jl")
@info "Resolve"
include("resolvenodes.jl")
@info "Spaces"
include("spaces.jl")
end
@testset "Larger tests" begin
@info "Basic"
@test include("basic.jl")
@info "bjkomer/Squared"
@test include("bjkomer/squared.jl")
@info "bjkomer/Function fitting"
@test include("bjkomer/function_fitting.jl")
@info "Official Cases"
@test include("official_cases.jl")
@info "fmin/Quadratic"
@test include("fmin/quadratic.jl")
@info "fmin/Return Inf"
@test include("fmin/return_inf.jl")
@info "fmin/Submit points to Trial"
@test include("fmin/points.jl")
@info "Silvrback"
@test include("silvrback.jl")
@info "Vooban/Basic"
@test include("vooban/basic.jl")
@info "Vooban/Find min"
@test include("vooban/find_min.jl")
@info "Vooban/Status Fail skip"
@test include("vooban/status_fail_skip.jl")
end
@testset "Samplers" begin
@info "hp_pchoice"
@test include("hp.jl")
@info "LogQuantNormal"
@test include("logquantnormal.jl")
@info "QuanLogNormal"
@test include("quantlognormal.jl")
@info "LogUniform"
@test include("loguniform.jl")
@info "QuantUniform"
@test include("quantuniform.jl")
@info "QuantNormal"
@test include("quantnormal.jl")
@info "LogQuantUniform"
@test include("logquantuniform.jl")
@info "QuantLogUniform"
@test include("quantloguniform.jl")
@info "Uniform"
include("uniform.jl")
end
@testset "MLJ" begin
@info "MLJ Unit tests"
@test include("MLJ/unit.jl")
@info "MLJ integration"
@test include("MLJ/integration.jl")
end
@info "API"
@test include("api.jl")
# Run this test last so that the print output is just above the test report
@info "SpacePrint"
@test include("spaceprint.jl")
end
| 22.868852
| 79
| 0.573835
|
[
"@time @testset \"Unit Tests\" begin\n @testset \"Small functions\" begin\n\n @info \"Bincount\"\n @test include(\"bincount.jl\")\n\n @info \"Configuration\"\n @test include(\"configuration.jl\")\n\n @info \"dfs\"\n @test include(\"dfs.jl\")\n\n @info \"graph\"\n @test include(\"graph.jl\")\n\n @info \"forgettingweights\"\n @test include(\"forgettingweights.jl\")\n\n # Needs translation from Python\n # include(\"adaptive_parzen_normal_orig.jl\")\n\n @info \"Trials\"\n @test include(\"trials.jl\")\n\n @info \"GMM1\"\n @test include(\"gmm.jl\")\n\n @info \"GMM1 Math and QGMM1 Math\"\n @test include(\"gmm_math.jl\")\n\n @info \"LGMM1\"\n @test include(\"lgmm.jl\")\n\n @info \"Resolve\"\n include(\"resolvenodes.jl\")\n\n @info \"Spaces\"\n include(\"spaces.jl\")\n end\n\n @testset \"Larger tests\" begin\n @info \"Basic\"\n @test include(\"basic.jl\")\n\n @info \"bjkomer/Squared\"\n @test include(\"bjkomer/squared.jl\")\n\n @info \"bjkomer/Function fitting\"\n @test include(\"bjkomer/function_fitting.jl\")\n\n @info \"Official Cases\"\n @test include(\"official_cases.jl\")\n\n @info \"fmin/Quadratic\"\n @test include(\"fmin/quadratic.jl\")\n\n @info \"fmin/Return Inf\"\n @test include(\"fmin/return_inf.jl\")\n\n @info \"fmin/Submit points to Trial\"\n @test include(\"fmin/points.jl\")\n\n @info \"Silvrback\"\n @test include(\"silvrback.jl\")\n\n @info \"Vooban/Basic\"\n @test include(\"vooban/basic.jl\")\n\n @info \"Vooban/Find min\"\n @test include(\"vooban/find_min.jl\")\n\n @info \"Vooban/Status Fail skip\"\n @test include(\"vooban/status_fail_skip.jl\")\n end\n\n @testset \"Samplers\" begin\n @info \"hp_pchoice\"\n @test include(\"hp.jl\")\n\n @info \"LogQuantNormal\"\n @test include(\"logquantnormal.jl\")\n\n @info \"QuanLogNormal\"\n @test include(\"quantlognormal.jl\")\n\n @info \"LogUniform\"\n @test include(\"loguniform.jl\")\n\n @info \"QuantUniform\"\n @test include(\"quantuniform.jl\")\n\n @info \"QuantNormal\"\n @test include(\"quantnormal.jl\")\n\n @info \"LogQuantUniform\"\n @test include(\"logquantuniform.jl\")\n\n @info \"QuantLogUniform\"\n @test include(\"quantloguniform.jl\")\n\n @info \"Uniform\"\n include(\"uniform.jl\")\n end\n\n @testset \"MLJ\" begin\n @info \"MLJ Unit tests\"\n @test include(\"MLJ/unit.jl\")\n\n @info \"MLJ integration\"\n @test include(\"MLJ/integration.jl\")\n end\n\n @info \"API\"\n @test include(\"api.jl\")\n\n # Run this test last so that the print output is just above the test report\n @info \"SpacePrint\"\n @test include(\"spaceprint.jl\")\nend"
] |
f7ae89cdae5a436ac972ba83a753e52357249ef5
| 7,620
|
jl
|
Julia
|
test/runtests.jl
|
treigerm/EPT.jl
|
e4e28168e9f1192273d2882d180432de5aab5a71
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
treigerm/EPT.jl
|
e4e28168e9f1192273d2882d180432de5aab5a71
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
treigerm/EPT.jl
|
e4e28168e9f1192273d2882d180432de5aab5a71
|
[
"MIT"
] | null | null | null |
using EPT
using Turing
using Test
using Random
import AnnealedIS
# rng = MersenneTwister(42)
Random.seed!(42)
@testset "EPT.jl" begin
@testset "Expectation Macro" begin
@expectation function expct(y)
x ~ Normal(0, 1)
y ~ Normal(x, 1)
return x^2
end
yval = 1
expct_conditioned = expct(yval)
xval = 2
vi = Turing.VarInfo(expct_conditioned.gamma1_pos)
vi[@varname(x)] = [xval;]
# vi[@varname(y)] = [yval;]
# Check that the three different models return the right score for a given trace.
gamma2_lp = logpdf(Normal(0, 1), xval) + logpdf(Normal(xval, 1), yval)
@test expct_conditioned.gamma2(vi) == xval^2
@test Turing.getlogp(vi) == gamma2_lp
gamma1_pos_lp = gamma2_lp + log(max(xval^2, 0))
@test expct_conditioned.gamma1_pos(vi) == xval^2
@test Turing.getlogp(vi) == gamma1_pos_lp
gamma1_neg_lp = gamma2_lp + log(-min(xval^2, 0))
@test expct_conditioned.gamma1_neg(vi) == xval^2 # TODO: Should it return 0 instead?
@test Turing.getlogp(vi) == gamma1_neg_lp
end
@testset "Correct scoping" begin
# Checks that we can access functions that are in the current scope
# inside the model body (here f).
f(x) = x^2
@expectation function expct()
x ~ Normal(0, 1)
y ~ Normal(x, 1)
return f(x)
end
fx = expct.gamma1_pos()()
@test isa(fx, Float64)
end
@testset "Expectation Estimation" begin
@expectation function expct(y)
x ~ Normal(0, 1)
y ~ Normal(x, 1)
return x^2
end
yval = 3
expct_conditioned = expct(yval)
num_annealing_dists = 10
num_samples = 10
tabi = TABI(
AIS(num_annealing_dists, num_samples, SimpleRejection())
)
expct_estimate, diagnostics = estimate_expectation(expct_conditioned, tabi)
@test !isnan(expct_estimate)
end
# Comment this out because it takes a while.
# @testset "Convergence test" begin
# @expectation function expct(y)
# x ~ Normal(0, 1)
# y ~ Normal(x, 1)
# return x
# end
#
# yval = 3
# expct_conditioned = expct(yval)
# num_annealing_dists = 100
# num_samples = 1000
# tabi = TABI(
# AIS(num_samples, num_annealing_dists)
# )
# expct_estimate, diagnostics = estimate_expectation(expct_conditioned, tabi)
# @test_broken isapprox(expct_estimate, 1.5, atol=1e-2)
# end
@testset "Diagnostics" begin
@expectation function expct(y)
x ~ Normal(0, 1)
y ~ Normal(x, 1)
return x
end
yval = 3
expct_conditioned = expct(yval)
num_annealing_dists = 10
num_samples = 10
tabi = TABI(
AIS(num_samples, num_annealing_dists, SimpleRejection())
)
expct_estimate, diagnostics = estimate_expectation(
expct_conditioned,
tabi;
store_intermediate_samples=true
)
keys = [:Z2_info, :Z1_negative_info, :Z1_positive_info]
for k in keys
@test haskey(diagnostics, k)
@test typeof(diagnostics[k][:ess]) == Float64
@test typeof(diagnostics[k][:Z_estimate]) == Float64
@test size(diagnostics[k][:samples]) == (num_samples,)
@test haskey(diagnostics[k], :intermediate_samples)
end
end
@testset "Rejection Samplers" begin
@expectation function expct(y)
x ~ Normal(0, 1)
y ~ Normal(x, 1)
return x
end
yval = 3
expct_conditioned = expct(yval)
num_annealing_dists = 10
num_samples = 10
tabi_no_rejection = TABI(
AIS(num_samples, num_annealing_dists, SimpleRejection())
)
_, _ = estimate_expectation(
expct_conditioned,
tabi_no_rejection;
store_intermediate_samples=true
)
tabi_rejection = TABI(
AIS(num_samples, num_annealing_dists, RejectionResample())
)
_, _ = estimate_expectation(
expct_conditioned,
tabi_rejection;
store_intermediate_samples=true
)
end
@testset "Disable Z1_pos or Z1_neg" begin
@expectation function expct(y)
x ~ Normal(0, 1)
y ~ Normal(x, 1)
return x^2
end
yval = 3
expct_conditioned = expct(yval)
num_annealing_dists = 10
num_samples = 2
tabi_no_Z1_neg = TABI(
AIS(num_samples, num_annealing_dists, SimpleRejection()),
AIS(0, num_annealing_dists, SimpleRejection()),
AIS(num_samples, num_annealing_dists, SimpleRejection())
)
_, d = estimate_expectation(
expct_conditioned,
tabi_no_Z1_neg;
store_intermediate_samples=true
)
full_tabi = TABI(AIS(num_samples, num_annealing_dists, SimpleRejection()))
_, d_full = estimate_expectation(
expct_conditioned,
tabi_no_Z1_neg;
store_intermediate_samples=true
)
# Check that estimate_expectation is type-stable.
@test typeof(d_full) == typeof(d)
end
@testset "Turing Importance Sampling" begin
@expectation function expct(y)
x ~ Normal(0, 1)
y ~ Normal(x, 1)
return x
end
yval = 3
expct_conditioned = expct(yval)
num_samples = 10
tabi = TABI(
TuringAlgorithm(IS(), num_samples)
)
expct_estimate, diag = estimate_expectation(
expct_conditioned,
tabi;
progress=false
)
@test typeof(expct_estimate) == Float64
for key in [:Z1_positive_info, :Z1_negative_info, :Z2_info]
@test typeof(diag[key]) <: MCMCChains.Chains
end
end
@testset "Prior extraction" begin
@expectation function expct(y)
x ~ Normal(0, 1)
y ~ Normal(x, 1)
return x
end
yval = 3
expct_conditioned = expct(yval)
log_prior = AnnealedIS.make_log_prior_density(
expct_conditioned.gamma1_pos
)
xval = 0.0
true_prior = logpdf(Normal(0, 1), xval)
@test log_prior((x = xval,)) == true_prior
end
@testset "Turing AnIS" begin
@expectation function expct(y)
x ~ Normal(0, 1)
y ~ Normal(x, 1)
return x
end
yval = 3
expct_conditioned = expct(yval)
num_samples = 10
num_annealing_dists = 10
tabi = TABI(
TuringAlgorithm(AnnealedIS.AnIS(num_annealing_dists), num_samples)
)
expct_estimate, diag = estimate_expectation(expct_conditioned, tabi)
@test typeof(expct_estimate) == Float64
for key in [:Z1_positive_info, :Z1_negative_info, :Z2_info]
@test typeof(diag[key]) <: MCMCChains.Chains
end
end
@testset "Multiple Expectations" begin
@expectation function expct(y)
x ~ Normal(0, 1)
y ~ Normal(x, 1)
return x, x^2, x^3
end
@test isa(expct, Array{EPT.Expectation})
@test length(expct) == 3
end
end
| 26.830986
| 92
| 0.556955
|
[
"@testset \"EPT.jl\" begin\n @testset \"Expectation Macro\" begin\n @expectation function expct(y)\n x ~ Normal(0, 1) \n y ~ Normal(x, 1)\n return x^2\n end\n\n yval = 1\n expct_conditioned = expct(yval)\n\n xval = 2\n vi = Turing.VarInfo(expct_conditioned.gamma1_pos)\n vi[@varname(x)] = [xval;]\n # vi[@varname(y)] = [yval;]\n\n # Check that the three different models return the right score for a given trace.\n gamma2_lp = logpdf(Normal(0, 1), xval) + logpdf(Normal(xval, 1), yval) \n @test expct_conditioned.gamma2(vi) == xval^2\n @test Turing.getlogp(vi) == gamma2_lp\n\n gamma1_pos_lp = gamma2_lp + log(max(xval^2, 0))\n @test expct_conditioned.gamma1_pos(vi) == xval^2\n @test Turing.getlogp(vi) == gamma1_pos_lp\n\n gamma1_neg_lp = gamma2_lp + log(-min(xval^2, 0))\n @test expct_conditioned.gamma1_neg(vi) == xval^2 # TODO: Should it return 0 instead?\n @test Turing.getlogp(vi) == gamma1_neg_lp\n end\n\n @testset \"Correct scoping\" begin\n # Checks that we can access functions that are in the current scope \n # inside the model body (here f).\n f(x) = x^2\n @expectation function expct()\n x ~ Normal(0, 1) \n y ~ Normal(x, 1)\n return f(x)\n end\n\n fx = expct.gamma1_pos()()\n @test isa(fx, Float64)\n end\n\n @testset \"Expectation Estimation\" begin\n @expectation function expct(y)\n x ~ Normal(0, 1) \n y ~ Normal(x, 1)\n return x^2\n end\n\n yval = 3\n expct_conditioned = expct(yval)\n\n num_annealing_dists = 10\n num_samples = 10\n\n tabi = TABI(\n AIS(num_annealing_dists, num_samples, SimpleRejection())\n )\n\n expct_estimate, diagnostics = estimate_expectation(expct_conditioned, tabi)\n @test !isnan(expct_estimate)\n end\n\n # Comment this out because it takes a while.\n # @testset \"Convergence test\" begin\n # @expectation function expct(y)\n # x ~ Normal(0, 1) \n # y ~ Normal(x, 1)\n # return x\n # end\n # \n # yval = 3\n # expct_conditioned = expct(yval)\n\n # num_annealing_dists = 100\n # num_samples = 1000\n\n # tabi = TABI(\n # AIS(num_samples, num_annealing_dists)\n # )\n\n # expct_estimate, diagnostics = estimate_expectation(expct_conditioned, tabi)\n # @test_broken isapprox(expct_estimate, 1.5, atol=1e-2)\n # end\n\n @testset \"Diagnostics\" begin\n @expectation function expct(y)\n x ~ Normal(0, 1) \n y ~ Normal(x, 1)\n return x\n end\n\n yval = 3\n expct_conditioned = expct(yval)\n\n num_annealing_dists = 10\n num_samples = 10\n\n tabi = TABI(\n AIS(num_samples, num_annealing_dists, SimpleRejection())\n )\n\n expct_estimate, diagnostics = estimate_expectation(\n expct_conditioned, \n tabi;\n store_intermediate_samples=true\n )\n\n keys = [:Z2_info, :Z1_negative_info, :Z1_positive_info]\n\n for k in keys\n @test haskey(diagnostics, k)\n\n @test typeof(diagnostics[k][:ess]) == Float64\n @test typeof(diagnostics[k][:Z_estimate]) == Float64\n @test size(diagnostics[k][:samples]) == (num_samples,)\n @test haskey(diagnostics[k], :intermediate_samples)\n end\n end\n\n @testset \"Rejection Samplers\" begin\n @expectation function expct(y)\n x ~ Normal(0, 1) \n y ~ Normal(x, 1)\n return x\n end\n\n yval = 3\n expct_conditioned = expct(yval)\n\n num_annealing_dists = 10\n num_samples = 10\n\n tabi_no_rejection = TABI(\n AIS(num_samples, num_annealing_dists, SimpleRejection())\n )\n _, _ = estimate_expectation(\n expct_conditioned, \n tabi_no_rejection;\n store_intermediate_samples=true\n )\n\n tabi_rejection = TABI(\n AIS(num_samples, num_annealing_dists, RejectionResample())\n )\n _, _ = estimate_expectation(\n expct_conditioned, \n tabi_rejection;\n store_intermediate_samples=true\n )\n end\n\n @testset \"Disable Z1_pos or Z1_neg\" begin\n @expectation function expct(y)\n x ~ Normal(0, 1) \n y ~ Normal(x, 1)\n return x^2\n end\n\n yval = 3\n expct_conditioned = expct(yval)\n\n num_annealing_dists = 10\n num_samples = 2\n\n tabi_no_Z1_neg = TABI(\n AIS(num_samples, num_annealing_dists, SimpleRejection()),\n AIS(0, num_annealing_dists, SimpleRejection()),\n AIS(num_samples, num_annealing_dists, SimpleRejection())\n )\n\n _, d = estimate_expectation(\n expct_conditioned, \n tabi_no_Z1_neg;\n store_intermediate_samples=true\n )\n \n full_tabi = TABI(AIS(num_samples, num_annealing_dists, SimpleRejection()))\n _, d_full = estimate_expectation(\n expct_conditioned, \n tabi_no_Z1_neg;\n store_intermediate_samples=true\n )\n\n # Check that estimate_expectation is type-stable.\n @test typeof(d_full) == typeof(d)\n end\n\n @testset \"Turing Importance Sampling\" begin\n @expectation function expct(y)\n x ~ Normal(0, 1) \n y ~ Normal(x, 1)\n return x\n end\n\n yval = 3\n expct_conditioned = expct(yval)\n\n num_samples = 10\n\n tabi = TABI(\n TuringAlgorithm(IS(), num_samples)\n )\n \n expct_estimate, diag = estimate_expectation(\n expct_conditioned, \n tabi;\n progress=false\n )\n\n @test typeof(expct_estimate) == Float64\n for key in [:Z1_positive_info, :Z1_negative_info, :Z2_info]\n @test typeof(diag[key]) <: MCMCChains.Chains\n end\n end\n\n @testset \"Prior extraction\" begin\n @expectation function expct(y)\n x ~ Normal(0, 1) \n y ~ Normal(x, 1)\n return x\n end\n\n yval = 3\n expct_conditioned = expct(yval)\n\n log_prior = AnnealedIS.make_log_prior_density(\n expct_conditioned.gamma1_pos\n )\n \n xval = 0.0\n true_prior = logpdf(Normal(0, 1), xval)\n @test log_prior((x = xval,)) == true_prior\n end\n \n @testset \"Turing AnIS\" begin\n @expectation function expct(y)\n x ~ Normal(0, 1) \n y ~ Normal(x, 1)\n return x\n end\n\n yval = 3\n expct_conditioned = expct(yval)\n\n num_samples = 10\n num_annealing_dists = 10\n\n tabi = TABI(\n TuringAlgorithm(AnnealedIS.AnIS(num_annealing_dists), num_samples)\n )\n \n expct_estimate, diag = estimate_expectation(expct_conditioned, tabi)\n\n @test typeof(expct_estimate) == Float64\n for key in [:Z1_positive_info, :Z1_negative_info, :Z2_info]\n @test typeof(diag[key]) <: MCMCChains.Chains\n end\n end\n\n @testset \"Multiple Expectations\" begin\n @expectation function expct(y)\n x ~ Normal(0, 1) \n y ~ Normal(x, 1)\n return x, x^2, x^3\n end\n\n @test isa(expct, Array{EPT.Expectation})\n @test length(expct) == 3\n end\nend"
] |
f7b0637c15611f38918f57fc9d71790a92320927
| 14,702
|
jl
|
Julia
|
test/FileFormats/MOF/MOF.jl
|
egbuck/MathOptInterface.jl
|
a95e7d68adb2e60e40dd8c0bffe4fdbcfde24590
|
[
"MIT"
] | null | null | null |
test/FileFormats/MOF/MOF.jl
|
egbuck/MathOptInterface.jl
|
a95e7d68adb2e60e40dd8c0bffe4fdbcfde24590
|
[
"MIT"
] | null | null | null |
test/FileFormats/MOF/MOF.jl
|
egbuck/MathOptInterface.jl
|
a95e7d68adb2e60e40dd8c0bffe4fdbcfde24590
|
[
"MIT"
] | null | null | null |
import MathOptInterface
using Test
const MOI = MathOptInterface
const MOIU = MOI.Utilities
const MOF = MOI.FileFormats.MOF
const TEST_MOF_FILE = "test.mof.json"
@test sprint(show, MOF.Model()) == "A MathOptFormat Model"
include("nonlinear.jl")
struct UnsupportedSet <: MOI.AbstractSet end
struct UnsupportedFunction <: MOI.AbstractFunction end
function test_model_equality(model_string, variables, constraints; suffix="")
model = MOF.Model(validate = true)
MOIU.loadfromstring!(model, model_string)
MOI.write_to_file(model, TEST_MOF_FILE * suffix)
model_2 = MOF.Model()
MOI.read_from_file(model_2, TEST_MOF_FILE * suffix)
MOIU.test_models_equal(model, model_2, variables, constraints)
MOF.validate(TEST_MOF_FILE * suffix)
end
@testset "Error handling: read_from_file" begin
failing_models_dir = joinpath(@__DIR__, "failing_models")
@testset "Non-empty model" begin
model = MOF.Model(warn=true)
MOI.add_variable(model)
@test !MOI.is_empty(model)
exception = ErrorException(
"Cannot read model from file as destination model is not empty.")
@test_throws exception MOI.read_from_file(
model, joinpath(@__DIR__, "empty_model.mof.json"))
options = MOF.get_options(model)
@test options.warn
MOI.empty!(model)
@test MOI.is_empty(model)
MOI.read_from_file(
model, joinpath(@__DIR__, "empty_model.mof.json"))
options2 = MOF.get_options(model)
@test options2.warn
end
@testset "$(filename)" for filename in filter(
f -> endswith(f, ".mof.json"), readdir(failing_models_dir))
@test_throws Exception MOI.read_from_file(MOF.Model(),
joinpath(failing_models_dir, filename))
end
end
@testset "Names" begin
@testset "Blank variable name" begin
model = MOF.Model()
variable_index = MOI.add_variable(model)
@test_throws Exception MOF.moi_to_object(variable_index, model)
MOI.FileFormats.create_unique_names(model, warn=true)
@test MOF.moi_to_object(variable_index, model) ==
MOF.OrderedObject("name" => "x1")
end
@testset "Duplicate variable name" begin
model = MOF.Model()
x = MOI.add_variable(model)
MOI.set(model, MOI.VariableName(), x, "x")
y = MOI.add_variable(model)
MOI.set(model, MOI.VariableName(), y, "x")
@test MOF.moi_to_object(x, model) == MOF.OrderedObject("name" => "x")
@test MOF.moi_to_object(y, model) == MOF.OrderedObject("name" => "x")
MOI.FileFormats.create_unique_names(model, warn=true)
@test MOF.moi_to_object(x, model) == MOF.OrderedObject("name" => "x")
@test MOF.moi_to_object(y, model) == MOF.OrderedObject("name" => "x_1")
end
@testset "Blank constraint name" begin
model = MOF.Model()
x = MOI.add_variable(model)
MOI.set(model, MOI.VariableName(), x, "x")
c = MOI.add_constraint(model, MOI.SingleVariable(x), MOI.ZeroOne())
name_map = Dict(x => "x")
MOI.FileFormats.create_unique_names(model, warn=true)
@test MOF.moi_to_object(c, model, name_map)["name"] == "c1"
end
@testset "Duplicate constraint name" begin
model = MOF.Model()
x = MOI.add_variable(model)
MOI.set(model, MOI.VariableName(), x, "x")
c1 = MOI.add_constraint(model, MOI.SingleVariable(x), MOI.LessThan(1.0))
c2 = MOI.add_constraint(model, MOI.SingleVariable(x), MOI.GreaterThan(0.0))
MOI.set(model, MOI.ConstraintName(), c1, "c")
MOI.set(model, MOI.ConstraintName(), c2, "c")
name_map = Dict(x => "x")
@test MOF.moi_to_object(c1, model, name_map)["name"] == "c"
@test MOF.moi_to_object(c2, model, name_map)["name"] == "c"
MOI.FileFormats.create_unique_names(model, warn=true)
@test MOF.moi_to_object(c1, model, name_map)["name"] == "c_1"
@test MOF.moi_to_object(c2, model, name_map)["name"] == "c"
end
end
@testset "round trips" begin
@testset "Empty model" begin
model = MOF.Model(validate = true)
MOI.write_to_file(model, TEST_MOF_FILE)
model_2 = MOF.Model(validate = true)
MOI.read_from_file(model_2, TEST_MOF_FILE)
MOIU.test_models_equal(model, model_2, String[], String[])
end
@testset "FEASIBILITY_SENSE" begin
model = MOF.Model(validate = true)
x = MOI.add_variable(model)
MOI.set(model, MOI.VariableName(), x, "x")
MOI.set(model, MOI.ObjectiveSense(), MOI.FEASIBILITY_SENSE)
MOI.write_to_file(model, TEST_MOF_FILE)
model_2 = MOF.Model(validate = true)
MOI.read_from_file(model_2, TEST_MOF_FILE)
MOIU.test_models_equal(model, model_2, ["x"], String[])
end
@testset "Empty function term" begin
model = MOF.Model(validate = true)
x = MOI.add_variable(model)
MOI.set(model, MOI.VariableName(), x, "x")
c = MOI.add_constraint(model,
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm{Float64}[], 0.0),
MOI.GreaterThan(1.0)
)
MOI.set(model, MOI.ConstraintName(), c, "c")
MOI.write_to_file(model, TEST_MOF_FILE)
model_2 = MOF.Model(validate = true)
MOI.read_from_file(model_2, TEST_MOF_FILE)
MOIU.test_models_equal(model, model_2, ["x"], ["c"])
end
@testset "min objective" begin
test_model_equality("""
variables: x
minobjective: x
""", ["x"], String[])
end
@testset "max objective" begin
test_model_equality("""
variables: x
maxobjective: x
""", ["x"], String[], suffix=".gz")
end
@testset "min scalaraffine" begin
test_model_equality("""
variables: x
minobjective: 1.2x + 0.5
""", ["x"], String[])
end
@testset "max scalaraffine" begin
test_model_equality("""
variables: x
maxobjective: 1.2x + 0.5
""", ["x"], String[], suffix=".gz")
end
@testset "singlevariable-in-lower" begin
test_model_equality("""
variables: x
minobjective: 1.2x + 0.5
c1: x >= 1.0
""", ["x"], ["c1"])
end
@testset "singlevariable-in-upper" begin
test_model_equality("""
variables: x
maxobjective: 1.2x + 0.5
c1: x <= 1.0
""", ["x"], ["c1"], suffix=".gz")
end
@testset "singlevariable-in-interval" begin
test_model_equality("""
variables: x
minobjective: 1.2x + 0.5
c1: x in Interval(1.0, 2.0)
""", ["x"], ["c1"])
end
@testset "singlevariable-in-equalto" begin
test_model_equality("""
variables: x
minobjective: 1.2x + 0.5
c1: x == 1.0
""", ["x"], ["c1"])
end
@testset "singlevariable-in-zeroone" begin
test_model_equality("""
variables: x
minobjective: 1.2x + 0.5
c1: x in ZeroOne()
""", ["x"], ["c1"])
end
@testset "singlevariable-in-integer" begin
test_model_equality("""
variables: x
minobjective: 1.2x + 0.5
c1: x in Integer()
""", ["x"], ["c1"])
end
@testset "singlevariable-in-Semicontinuous" begin
test_model_equality("""
variables: x
minobjective: 1.2x + 0.5
c1: x in Semicontinuous(1.0, 2.0)
""", ["x"], ["c1"])
end
@testset "singlevariable-in-Semiinteger" begin
test_model_equality("""
variables: x
minobjective: 1.2x + 0.5
c1: x in Semiinteger(1.0, 2.0)
""", ["x"], ["c1"])
end
@testset "scalarquadratic-objective" begin
test_model_equality("""
variables: x
minobjective: 1.0*x*x + -2.0x + 1.0
""", ["x"], String[])
end
@testset "SOS1" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in SOS1([1.0, 2.0, 3.0])
""", ["x", "y", "z"], ["c1"])
end
@testset "SOS2" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in SOS2([1.0, 2.0, 3.0])
""", ["x", "y", "z"], ["c1"])
end
@testset "Reals" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in Reals(3)
""", ["x", "y", "z"], ["c1"])
end
@testset "Zeros" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in Zeros(3)
""", ["x", "y", "z"], ["c1"])
end
@testset "Nonnegatives" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in Nonnegatives(3)
""", ["x", "y", "z"], ["c1"])
end
@testset "Nonpositives" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in Nonpositives(3)
""", ["x", "y", "z"], ["c1"])
end
@testset "PowerCone" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in PowerCone(2.0)
""", ["x", "y", "z"], ["c1"])
end
@testset "DualPowerCone" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in DualPowerCone(0.5)
""", ["x", "y", "z"], ["c1"])
end
@testset "GeometricMeanCone" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in GeometricMeanCone(3)
""", ["x", "y", "z"], ["c1"])
end
@testset "vectoraffine-in-zeros" begin
test_model_equality("""
variables: x, y
minobjective: x
c1: [1.0x + -3.0, 2.0y + -4.0] in Zeros(2)
""", ["x", "y"], ["c1"])
end
@testset "vectorquadratic-in-nonnegatives" begin
test_model_equality("""
variables: x, y
minobjective: x
c1: [1.0*x*x + -2.0x + 1.0, 2.0y + -4.0] in Nonnegatives(2)
""", ["x", "y"], ["c1"])
end
@testset "ExponentialCone" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in ExponentialCone()
""", ["x", "y", "z"], ["c1"])
end
@testset "DualExponentialCone" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in DualExponentialCone()
""", ["x", "y", "z"], ["c1"])
end
@testset "SecondOrderCone" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in SecondOrderCone(3)
""", ["x", "y", "z"], ["c1"])
end
@testset "RotatedSecondOrderCone" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in RotatedSecondOrderCone(3)
""", ["x", "y", "z"], ["c1"])
end
@testset "PositiveSemidefiniteConeTriangle" begin
test_model_equality("""
variables: x1, x2, x3
minobjective: x1
c1: [x1, x2, x3] in PositiveSemidefiniteConeTriangle(2)
""", ["x1", "x2", "x3"], ["c1"])
end
@testset "PositiveSemidefiniteConeSquare" begin
test_model_equality("""
variables: x1, x2, x3, x4
minobjective: x1
c1: [x1, x2, x3, x4] in PositiveSemidefiniteConeSquare(2)
""", ["x1", "x2", "x3", "x4"], ["c1"])
end
@testset "LogDetConeTriangle" begin
test_model_equality("""
variables: t, u, x1, x2, x3
minobjective: x1
c1: [t, u, x1, x2, x3] in LogDetConeTriangle(2)
""", ["t", "u", "x1", "x2", "x3"], ["c1"])
end
@testset "LogDetConeSquare" begin
test_model_equality("""
variables: t, u, x1, x2, x3, x4
minobjective: x1
c1: [t, u, x1, x2, x3, x4] in LogDetConeSquare(2)
""", ["t", "u", "x1", "x2", "x3", "x4"], ["c1"])
end
@testset "RootDetConeTriangle" begin
test_model_equality("""
variables: t, x1, x2, x3
minobjective: x1
c1: [t, x1, x2, x3] in RootDetConeTriangle(2)
""", ["t", "x1", "x2", "x3"], ["c1"])
end
@testset "RootDetConeSquare" begin
test_model_equality("""
variables: t, x1, x2, x3, x4
minobjective: x1
c1: [t, x1, x2, x3, x4] in RootDetConeSquare(2)
""", ["t", "x1", "x2", "x3", "x4"], ["c1"])
end
@testset "IndicatorSet" begin
test_model_equality("""
variables: x, y
minobjective: x
c1: [x, y] in IndicatorSet{ACTIVATE_ON_ONE}(GreaterThan(1.0))
c2: x >= 0.0
""", ["x", "y"], ["c1", "c2"])
test_model_equality("""
variables: x, y
minobjective: x
c1: [x, y] in IndicatorSet{ACTIVATE_ON_ZERO}(GreaterThan(1.0))
c2: x >= 0.0
""", ["x", "y"], ["c1", "c2"])
end
@testset "NormOneCone" begin
test_model_equality("""
variables: x, y
minobjective: x
c1: [x, y] in NormOneCone(2)
c2: x >= 0.0
""", ["x", "y"], ["c1", "c2"])
end
@testset "NormInfinityCone" begin
test_model_equality("""
variables: x, y
minobjective: x
c1: [x, y] in NormInfinityCone(2)
c2: x >= 0.0
""", ["x", "y"], ["c1", "c2"])
end
@testset "RelativeEntropyCone" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in RelativeEntropyCone(3)
c2: x >= 0.0
""", ["x", "y", "z"], ["c1", "c2"])
end
@testset "NormSpectralCone" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in NormSpectralCone(1, 2)
""", ["x", "y", "z"], ["c1"])
end
@testset "NormNuclearCone" begin
test_model_equality("""
variables: x, y, z
minobjective: x
c1: [x, y, z] in NormNuclearCone(1, 2)
""", ["x", "y", "z"], ["c1"])
end
# Clean up
sleep(1.0) # allow time for unlink to happen
rm(TEST_MOF_FILE, force=true)
rm(TEST_MOF_FILE * ".gz", force=true)
end
| 34.756501
| 83
| 0.534009
|
[
"@testset \"Error handling: read_from_file\" begin\n failing_models_dir = joinpath(@__DIR__, \"failing_models\")\n\n @testset \"Non-empty model\" begin\n model = MOF.Model(warn=true)\n MOI.add_variable(model)\n @test !MOI.is_empty(model)\n exception = ErrorException(\n \"Cannot read model from file as destination model is not empty.\")\n @test_throws exception MOI.read_from_file(\n model, joinpath(@__DIR__, \"empty_model.mof.json\"))\n options = MOF.get_options(model)\n @test options.warn\n MOI.empty!(model)\n @test MOI.is_empty(model)\n MOI.read_from_file(\n model, joinpath(@__DIR__, \"empty_model.mof.json\"))\n options2 = MOF.get_options(model)\n @test options2.warn\n end\n\n @testset \"$(filename)\" for filename in filter(\n f -> endswith(f, \".mof.json\"), readdir(failing_models_dir))\n @test_throws Exception MOI.read_from_file(MOF.Model(),\n joinpath(failing_models_dir, filename))\n end\nend",
"@testset \"Names\" begin\n @testset \"Blank variable name\" begin\n model = MOF.Model()\n variable_index = MOI.add_variable(model)\n @test_throws Exception MOF.moi_to_object(variable_index, model)\n MOI.FileFormats.create_unique_names(model, warn=true)\n @test MOF.moi_to_object(variable_index, model) ==\n MOF.OrderedObject(\"name\" => \"x1\")\n end\n @testset \"Duplicate variable name\" begin\n model = MOF.Model()\n x = MOI.add_variable(model)\n MOI.set(model, MOI.VariableName(), x, \"x\")\n y = MOI.add_variable(model)\n MOI.set(model, MOI.VariableName(), y, \"x\")\n @test MOF.moi_to_object(x, model) == MOF.OrderedObject(\"name\" => \"x\")\n @test MOF.moi_to_object(y, model) == MOF.OrderedObject(\"name\" => \"x\")\n MOI.FileFormats.create_unique_names(model, warn=true)\n @test MOF.moi_to_object(x, model) == MOF.OrderedObject(\"name\" => \"x\")\n @test MOF.moi_to_object(y, model) == MOF.OrderedObject(\"name\" => \"x_1\")\n end\n @testset \"Blank constraint name\" begin\n model = MOF.Model()\n x = MOI.add_variable(model)\n MOI.set(model, MOI.VariableName(), x, \"x\")\n c = MOI.add_constraint(model, MOI.SingleVariable(x), MOI.ZeroOne())\n name_map = Dict(x => \"x\")\n MOI.FileFormats.create_unique_names(model, warn=true)\n @test MOF.moi_to_object(c, model, name_map)[\"name\"] == \"c1\"\n end\n @testset \"Duplicate constraint name\" begin\n model = MOF.Model()\n x = MOI.add_variable(model)\n MOI.set(model, MOI.VariableName(), x, \"x\")\n c1 = MOI.add_constraint(model, MOI.SingleVariable(x), MOI.LessThan(1.0))\n c2 = MOI.add_constraint(model, MOI.SingleVariable(x), MOI.GreaterThan(0.0))\n MOI.set(model, MOI.ConstraintName(), c1, \"c\")\n MOI.set(model, MOI.ConstraintName(), c2, \"c\")\n name_map = Dict(x => \"x\")\n @test MOF.moi_to_object(c1, model, name_map)[\"name\"] == \"c\"\n @test MOF.moi_to_object(c2, model, name_map)[\"name\"] == \"c\"\n MOI.FileFormats.create_unique_names(model, warn=true)\n @test MOF.moi_to_object(c1, model, name_map)[\"name\"] == \"c_1\"\n @test MOF.moi_to_object(c2, model, name_map)[\"name\"] == \"c\"\n end\nend",
"@testset \"round trips\" begin\n @testset \"Empty model\" begin\n model = MOF.Model(validate = true)\n MOI.write_to_file(model, TEST_MOF_FILE)\n model_2 = MOF.Model(validate = true)\n MOI.read_from_file(model_2, TEST_MOF_FILE)\n MOIU.test_models_equal(model, model_2, String[], String[])\n end\n @testset \"FEASIBILITY_SENSE\" begin\n model = MOF.Model(validate = true)\n x = MOI.add_variable(model)\n MOI.set(model, MOI.VariableName(), x, \"x\")\n MOI.set(model, MOI.ObjectiveSense(), MOI.FEASIBILITY_SENSE)\n MOI.write_to_file(model, TEST_MOF_FILE)\n model_2 = MOF.Model(validate = true)\n MOI.read_from_file(model_2, TEST_MOF_FILE)\n MOIU.test_models_equal(model, model_2, [\"x\"], String[])\n end\n @testset \"Empty function term\" begin\n model = MOF.Model(validate = true)\n x = MOI.add_variable(model)\n MOI.set(model, MOI.VariableName(), x, \"x\")\n c = MOI.add_constraint(model,\n MOI.ScalarAffineFunction(MOI.ScalarAffineTerm{Float64}[], 0.0),\n MOI.GreaterThan(1.0)\n )\n MOI.set(model, MOI.ConstraintName(), c, \"c\")\n MOI.write_to_file(model, TEST_MOF_FILE)\n model_2 = MOF.Model(validate = true)\n MOI.read_from_file(model_2, TEST_MOF_FILE)\n MOIU.test_models_equal(model, model_2, [\"x\"], [\"c\"])\n end\n @testset \"min objective\" begin\n test_model_equality(\"\"\"\n variables: x\n minobjective: x\n \"\"\", [\"x\"], String[])\n end\n @testset \"max objective\" begin\n test_model_equality(\"\"\"\n variables: x\n maxobjective: x\n \"\"\", [\"x\"], String[], suffix=\".gz\")\n end\n @testset \"min scalaraffine\" begin\n test_model_equality(\"\"\"\n variables: x\n minobjective: 1.2x + 0.5\n \"\"\", [\"x\"], String[])\n end\n @testset \"max scalaraffine\" begin\n test_model_equality(\"\"\"\n variables: x\n maxobjective: 1.2x + 0.5\n \"\"\", [\"x\"], String[], suffix=\".gz\")\n end\n @testset \"singlevariable-in-lower\" begin\n test_model_equality(\"\"\"\n variables: x\n minobjective: 1.2x + 0.5\n c1: x >= 1.0\n \"\"\", [\"x\"], [\"c1\"])\n end\n @testset \"singlevariable-in-upper\" begin\n test_model_equality(\"\"\"\n variables: x\n maxobjective: 1.2x + 0.5\n c1: x <= 1.0\n \"\"\", [\"x\"], [\"c1\"], suffix=\".gz\")\n end\n @testset \"singlevariable-in-interval\" begin\n test_model_equality(\"\"\"\n variables: x\n minobjective: 1.2x + 0.5\n c1: x in Interval(1.0, 2.0)\n \"\"\", [\"x\"], [\"c1\"])\n end\n @testset \"singlevariable-in-equalto\" begin\n test_model_equality(\"\"\"\n variables: x\n minobjective: 1.2x + 0.5\n c1: x == 1.0\n \"\"\", [\"x\"], [\"c1\"])\n end\n @testset \"singlevariable-in-zeroone\" begin\n test_model_equality(\"\"\"\n variables: x\n minobjective: 1.2x + 0.5\n c1: x in ZeroOne()\n \"\"\", [\"x\"], [\"c1\"])\n end\n @testset \"singlevariable-in-integer\" begin\n test_model_equality(\"\"\"\n variables: x\n minobjective: 1.2x + 0.5\n c1: x in Integer()\n \"\"\", [\"x\"], [\"c1\"])\n end\n @testset \"singlevariable-in-Semicontinuous\" begin\n test_model_equality(\"\"\"\n variables: x\n minobjective: 1.2x + 0.5\n c1: x in Semicontinuous(1.0, 2.0)\n \"\"\", [\"x\"], [\"c1\"])\n end\n @testset \"singlevariable-in-Semiinteger\" begin\n test_model_equality(\"\"\"\n variables: x\n minobjective: 1.2x + 0.5\n c1: x in Semiinteger(1.0, 2.0)\n \"\"\", [\"x\"], [\"c1\"])\n end\n @testset \"scalarquadratic-objective\" begin\n test_model_equality(\"\"\"\n variables: x\n minobjective: 1.0*x*x + -2.0x + 1.0\n \"\"\", [\"x\"], String[])\n end\n @testset \"SOS1\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in SOS1([1.0, 2.0, 3.0])\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\"])\n end\n @testset \"SOS2\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in SOS2([1.0, 2.0, 3.0])\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\"])\n end\n @testset \"Reals\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in Reals(3)\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\"])\n end\n @testset \"Zeros\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in Zeros(3)\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\"])\n end\n @testset \"Nonnegatives\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in Nonnegatives(3)\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\"])\n end\n @testset \"Nonpositives\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in Nonpositives(3)\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\"])\n end\n @testset \"PowerCone\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in PowerCone(2.0)\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\"])\n end\n @testset \"DualPowerCone\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in DualPowerCone(0.5)\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\"])\n end\n @testset \"GeometricMeanCone\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in GeometricMeanCone(3)\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\"])\n end\n @testset \"vectoraffine-in-zeros\" begin\n test_model_equality(\"\"\"\n variables: x, y\n minobjective: x\n c1: [1.0x + -3.0, 2.0y + -4.0] in Zeros(2)\n \"\"\", [\"x\", \"y\"], [\"c1\"])\n end\n @testset \"vectorquadratic-in-nonnegatives\" begin\n test_model_equality(\"\"\"\n variables: x, y\n minobjective: x\n c1: [1.0*x*x + -2.0x + 1.0, 2.0y + -4.0] in Nonnegatives(2)\n \"\"\", [\"x\", \"y\"], [\"c1\"])\n end\n @testset \"ExponentialCone\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in ExponentialCone()\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\"])\n end\n @testset \"DualExponentialCone\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in DualExponentialCone()\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\"])\n end\n @testset \"SecondOrderCone\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in SecondOrderCone(3)\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\"])\n end\n @testset \"RotatedSecondOrderCone\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in RotatedSecondOrderCone(3)\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\"])\n end\n @testset \"PositiveSemidefiniteConeTriangle\" begin\n test_model_equality(\"\"\"\n variables: x1, x2, x3\n minobjective: x1\n c1: [x1, x2, x3] in PositiveSemidefiniteConeTriangle(2)\n \"\"\", [\"x1\", \"x2\", \"x3\"], [\"c1\"])\n end\n @testset \"PositiveSemidefiniteConeSquare\" begin\n test_model_equality(\"\"\"\n variables: x1, x2, x3, x4\n minobjective: x1\n c1: [x1, x2, x3, x4] in PositiveSemidefiniteConeSquare(2)\n \"\"\", [\"x1\", \"x2\", \"x3\", \"x4\"], [\"c1\"])\n end\n @testset \"LogDetConeTriangle\" begin\n test_model_equality(\"\"\"\n variables: t, u, x1, x2, x3\n minobjective: x1\n c1: [t, u, x1, x2, x3] in LogDetConeTriangle(2)\n \"\"\", [\"t\", \"u\", \"x1\", \"x2\", \"x3\"], [\"c1\"])\n end\n @testset \"LogDetConeSquare\" begin\n test_model_equality(\"\"\"\n variables: t, u, x1, x2, x3, x4\n minobjective: x1\n c1: [t, u, x1, x2, x3, x4] in LogDetConeSquare(2)\n \"\"\", [\"t\", \"u\", \"x1\", \"x2\", \"x3\", \"x4\"], [\"c1\"])\n end\n @testset \"RootDetConeTriangle\" begin\n test_model_equality(\"\"\"\n variables: t, x1, x2, x3\n minobjective: x1\n c1: [t, x1, x2, x3] in RootDetConeTriangle(2)\n \"\"\", [\"t\", \"x1\", \"x2\", \"x3\"], [\"c1\"])\n end\n @testset \"RootDetConeSquare\" begin\n test_model_equality(\"\"\"\n variables: t, x1, x2, x3, x4\n minobjective: x1\n c1: [t, x1, x2, x3, x4] in RootDetConeSquare(2)\n \"\"\", [\"t\", \"x1\", \"x2\", \"x3\", \"x4\"], [\"c1\"])\n end\n @testset \"IndicatorSet\" begin\n test_model_equality(\"\"\"\n variables: x, y\n minobjective: x\n c1: [x, y] in IndicatorSet{ACTIVATE_ON_ONE}(GreaterThan(1.0))\n c2: x >= 0.0\n \"\"\", [\"x\", \"y\"], [\"c1\", \"c2\"])\n\n test_model_equality(\"\"\"\n variables: x, y\n minobjective: x\n c1: [x, y] in IndicatorSet{ACTIVATE_ON_ZERO}(GreaterThan(1.0))\n c2: x >= 0.0\n \"\"\", [\"x\", \"y\"], [\"c1\", \"c2\"])\n end\n @testset \"NormOneCone\" begin\n test_model_equality(\"\"\"\n variables: x, y\n minobjective: x\n c1: [x, y] in NormOneCone(2)\n c2: x >= 0.0\n \"\"\", [\"x\", \"y\"], [\"c1\", \"c2\"])\n end\n @testset \"NormInfinityCone\" begin\n test_model_equality(\"\"\"\n variables: x, y\n minobjective: x\n c1: [x, y] in NormInfinityCone(2)\n c2: x >= 0.0\n \"\"\", [\"x\", \"y\"], [\"c1\", \"c2\"])\n end\n @testset \"RelativeEntropyCone\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in RelativeEntropyCone(3)\n c2: x >= 0.0\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\", \"c2\"])\n end\n @testset \"NormSpectralCone\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in NormSpectralCone(1, 2)\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\"])\n end\n @testset \"NormNuclearCone\" begin\n test_model_equality(\"\"\"\n variables: x, y, z\n minobjective: x\n c1: [x, y, z] in NormNuclearCone(1, 2)\n \"\"\", [\"x\", \"y\", \"z\"], [\"c1\"])\n end\n # Clean up\n sleep(1.0) # allow time for unlink to happen\n rm(TEST_MOF_FILE, force=true)\n rm(TEST_MOF_FILE * \".gz\", force=true)\nend"
] |
f7b55b0bdcd7bd2c15b230c6128ec5df9f2b837f
| 6,487
|
jl
|
Julia
|
test/MiscTest.jl
|
dcelisgarza/DDD
|
9257c619240a2b3bbdddd813d5e08ab71a07f7be
|
[
"MIT"
] | 4
|
2020-05-30T03:22:57.000Z
|
2020-12-09T07:34:42.000Z
|
test/MiscTest.jl
|
dcelisgarza/DDD.jl
|
9257c619240a2b3bbdddd813d5e08ab71a07f7be
|
[
"MIT"
] | 12
|
2020-02-03T10:26:41.000Z
|
2021-11-11T10:01:38.000Z
|
test/MiscTest.jl
|
dcelisgarza/DDD
|
9257c619240a2b3bbdddd813d5e08ab71a07f7be
|
[
"MIT"
] | 2
|
2020-12-09T07:34:50.000Z
|
2021-11-10T03:24:45.000Z
|
using DDD
using Test
using DDD: makeInstanceDict, inclusiveComparison
cd(@__DIR__)
@testset "Geometry" begin
arr = Int[3; 4; 6]
@test isapprox(internalAngle(arr[1]), π / 3)
@test isapprox(internalAngle(arr[2]), π / 2)
@test isapprox(internalAngle(arr[3]), 2π / 3)
@test isapprox(externalAngle(arr[1]), 2π / 3)
@test isapprox(externalAngle(arr[2]), π / 2)
@test isapprox(externalAngle(arr[3]), π / 3)
xyz = [1.0, 0.0, 0.0]
θ = pi / 2
uvw = [0.0, 5.0, 0.0]
abc = [0.0, 0.0, 0.0]
p = rot3D(xyz, uvw, abc, θ)
@test isapprox(p, [0.0, 0.0, -1.0])
uvw = [0.0, 0.0, 20.0]
abc = [0.0, 0.0, 0.0]
p = rot3D(xyz, uvw, abc, θ)
@test isapprox(p, [0.0, 1.0, 0.0])
uvw = [1.0, 0.0, 0.0]
abc = [0.0, 0.0, 0.0]
p = rot3D(xyz, uvw, abc, θ)
@test isapprox(p, xyz)
xyz = [-23.0, 29.0, -31.0]
uvw = [11.0, -13.0, 17.0]
abc = [-2.0, 5.0, 7.0]
θ = 37 / 180 * pi
p = rot3D(xyz, uvw, abc, θ)
@test isapprox(p, [-21.1690, 31.0685, -30.6029]; atol = 1e-4)
@test compStruct(1, 1.2) == false
planenorm = Float64[0, 0, 1]
planepnt = Float64[0, 0, 5]
raydir = Float64[0, -1, -2]
raypnt = Float64[0, 0, 10]
ψ = linePlaneIntersect(planenorm, planepnt, raydir, raypnt)
@test isapprox(ψ, [0, -2.5, 5.0])
planenorm = Float64[0, 2, 1]
planepnt = Float64[0, 0, 5]
raydir = Float64[0, -1, -2]
raypnt = Float64[0, 0, 10]
ψ = linePlaneIntersect(planenorm, planepnt, raydir, raypnt)
@test isapprox(ψ, [0.0, -1.25, 7.5])
planenorm = Float64[0, 0, 1]
planepnt = Float64[0, 0, 5]
raydir = Float64[0, 1, 2]
raypnt = Float64[0, 0, 10]
ψ = linePlaneIntersect(planenorm, planepnt, raydir, raypnt)
@test isapprox(ψ, [0, -2.5, 5.0])
planenorm = Float64[0, 0, 1]
planepnt = Float64[0, 0, 5]
raydir = Float64[0, 1, -2]
raypnt = Float64[0, 0, 10]
ψ = linePlaneIntersect(planenorm, planepnt, raydir, raypnt)
@test isapprox(ψ, [0, 2.5, 5.0])
planenorm = Float64[0, 0, 1]
planepnt = Float64[0, 0, 5]
raydir = Float64[0, 1, 0]
raypnt = Float64[0, 0, 5]
ψ = linePlaneIntersect(planenorm, planepnt, raydir, raypnt)
@test isinf(ψ)
planenorm = Float64[0, 0, 1]
planepnt = Float64[0, 0, 5]
raydir = Float64[0, 1, 0]
raypnt = Float64[0, 0, 6]
ψ = linePlaneIntersect(planenorm, planepnt, raydir, raypnt)
@test isnothing(ψ)
x0, x1 = zeros(3), ones(3)
y0, y1 = zeros(3), zeros(3)
vx0, vx1 = zeros(3), zeros(3)
vy0, vy1 = zeros(3), zeros(3)
distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)
@test (distSq, dDistSqDt, L1, L2) == (0, 0, 0, 0)
x0, x1 = zeros(3), ones(3)
y0, y1 = ones(3), ones(3)
vx0, vx1 = zeros(3), zeros(3)
vy0, vy1 = zeros(3), zeros(3)
distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)
@test (distSq, dDistSqDt, L1, L2) == (0, 0, 1, 0)
y0, y1 = zeros(3), ones(3)
x0, x1 = zeros(3), zeros(3)
vx0, vx1 = zeros(3), zeros(3)
vy0, vy1 = zeros(3), zeros(3)
distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)
@test (distSq, dDistSqDt, L1, L2) == (0, 0, 0, 0)
y0, y1 = zeros(3), ones(3)
x0, x1 = ones(3), ones(3)
vx0, vx1 = zeros(3), zeros(3)
vy0, vy1 = zeros(3), zeros(3)
distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)
@test (distSq, dDistSqDt, L1, L2) == (0, 0, 0, 1)
x0, x1 = zeros(3), ones(3)
y0, y1 = 0.5 * ones(3), 0.5 * ones(3)
vx0, vx1 = zeros(3), zeros(3)
vy0, vy1 = zeros(3), zeros(3)
distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)
@test (distSq, dDistSqDt, L1, L2) == (0, 0, 0.5, 0)
y0, y1 = zeros(3), ones(3)
x0, x1 = 0.5 * ones(3), 0.5 * ones(3)
vx0, vx1 = zeros(3), zeros(3)
vy0, vy1 = zeros(3), zeros(3)
distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)
@test (distSq, dDistSqDt, L1, L2) == (0, 0, 0, 0.5)
x0, x1 = zeros(3), ones(3)
y0, y1 = zeros(3), ones(3) .+ eps(Float64)^2
vx0, vx1 = zeros(3), zeros(3)
vy0, vy1 = zeros(3), zeros(3)
distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)
@test (distSq, dDistSqDt, L1, L2) == (0, 0, 0, 0)
x0, x1 = zeros(3), ones(3)
y0, y1 = [1, 0, 0], [2, 1, 1]
vx0, vx1 = zeros(3), zeros(3)
vy0, vy1 = zeros(3), zeros(3)
distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)
@test (distSq, dDistSqDt, L1, L2) == (1, 0, 0, 0)
x1, x0 = zeros(3), ones(3)
y0, y1 = [1, 0, 0], [2, 1, 1]
vx0, vx1 = zeros(3), zeros(3)
vy0, vy1 = zeros(3), zeros(3)
distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)
@test (distSq, dDistSqDt, L1, L2) == (6, 0, 1, 1)
x0, x1 = zeros(3), ones(3)
y1, y0 = [1, 0, 0], [2, 1, 1]
vx0, vx1 = zeros(3), zeros(3)
vy0, vy1 = zeros(3), zeros(3)
distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)
@test (distSq, dDistSqDt, L1, L2) == (2, 0, 1, 1)
x1, x0 = zeros(3), ones(3)
y0, y1 = [1, 1, 0], [1.5, 0.5, 0.5]
vx0, vx1 = zeros(3), zeros(3)
vy0, vy1 = zeros(3), zeros(3)
distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)
@test (distSq, dDistSqDt, L1, L2) == (0.5, 0, 0.25, 0.5)
x0, x1 = zeros(3), zeros(3)
y0, y1 = zeros(3), zeros(3)
vx0, vx1 = zeros(3), zeros(3)
vy0, vy1 = zeros(3), zeros(3)
distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)
@test (distSq, dDistSqDt, L1, L2) == (0, 0, 0, 0)
end
@testset "Auxiliary" begin
dict = Dict(
"intFixDln" => nodeTypeDln(2),
"noneDln" => nodeTypeDln(0),
"intMobDln" => nodeTypeDln(1),
"srfFixDln" => nodeTypeDln(4),
"extDln" => nodeTypeDln(5),
"srfMobDln" => nodeTypeDln(3),
"tmpDln" => nodeTypeDln(6),
)
@test makeInstanceDict(nodeTypeDln) == dict
data = rand(5)
@test inclusiveComparison(data[rand(1:5)], data...)
@test !inclusiveComparison(data, data[rand(1:5)] * 6)
end
@testset "Quadrature" begin
n = 17
a = -13
b = 23
x, w = gausslegendre(n, a, b)
bma = (b - a) * 0.5
bpa = (b + a) * 0.5
x1, w1 = gausslegendre(n)
x1 = bma * x1 .+ bpa
w1 = bma * w1
@test x ≈ x1
@test w ≈ w1
end
| 32.59799
| 83
| 0.548327
|
[
"@testset \"Geometry\" begin\n arr = Int[3; 4; 6]\n @test isapprox(internalAngle(arr[1]), π / 3)\n @test isapprox(internalAngle(arr[2]), π / 2)\n @test isapprox(internalAngle(arr[3]), 2π / 3)\n @test isapprox(externalAngle(arr[1]), 2π / 3)\n @test isapprox(externalAngle(arr[2]), π / 2)\n @test isapprox(externalAngle(arr[3]), π / 3)\n xyz = [1.0, 0.0, 0.0]\n θ = pi / 2\n uvw = [0.0, 5.0, 0.0]\n abc = [0.0, 0.0, 0.0]\n p = rot3D(xyz, uvw, abc, θ)\n @test isapprox(p, [0.0, 0.0, -1.0])\n uvw = [0.0, 0.0, 20.0]\n abc = [0.0, 0.0, 0.0]\n p = rot3D(xyz, uvw, abc, θ)\n @test isapprox(p, [0.0, 1.0, 0.0])\n uvw = [1.0, 0.0, 0.0]\n abc = [0.0, 0.0, 0.0]\n p = rot3D(xyz, uvw, abc, θ)\n @test isapprox(p, xyz)\n xyz = [-23.0, 29.0, -31.0]\n uvw = [11.0, -13.0, 17.0]\n abc = [-2.0, 5.0, 7.0]\n θ = 37 / 180 * pi\n p = rot3D(xyz, uvw, abc, θ)\n @test isapprox(p, [-21.1690, 31.0685, -30.6029]; atol = 1e-4)\n @test compStruct(1, 1.2) == false\n\n planenorm = Float64[0, 0, 1]\n planepnt = Float64[0, 0, 5]\n raydir = Float64[0, -1, -2]\n raypnt = Float64[0, 0, 10]\n\n ψ = linePlaneIntersect(planenorm, planepnt, raydir, raypnt)\n @test isapprox(ψ, [0, -2.5, 5.0])\n\n planenorm = Float64[0, 2, 1]\n planepnt = Float64[0, 0, 5]\n raydir = Float64[0, -1, -2]\n raypnt = Float64[0, 0, 10]\n ψ = linePlaneIntersect(planenorm, planepnt, raydir, raypnt)\n @test isapprox(ψ, [0.0, -1.25, 7.5])\n\n planenorm = Float64[0, 0, 1]\n planepnt = Float64[0, 0, 5]\n raydir = Float64[0, 1, 2]\n raypnt = Float64[0, 0, 10]\n\n ψ = linePlaneIntersect(planenorm, planepnt, raydir, raypnt)\n @test isapprox(ψ, [0, -2.5, 5.0])\n\n planenorm = Float64[0, 0, 1]\n planepnt = Float64[0, 0, 5]\n raydir = Float64[0, 1, -2]\n raypnt = Float64[0, 0, 10]\n\n ψ = linePlaneIntersect(planenorm, planepnt, raydir, raypnt)\n @test isapprox(ψ, [0, 2.5, 5.0])\n\n planenorm = Float64[0, 0, 1]\n planepnt = Float64[0, 0, 5]\n raydir = Float64[0, 1, 0]\n raypnt = Float64[0, 0, 5]\n ψ = linePlaneIntersect(planenorm, planepnt, raydir, raypnt)\n @test isinf(ψ)\n\n planenorm = Float64[0, 0, 1]\n planepnt = Float64[0, 0, 5]\n raydir = Float64[0, 1, 0]\n raypnt = Float64[0, 0, 6]\n ψ = linePlaneIntersect(planenorm, planepnt, raydir, raypnt)\n @test isnothing(ψ)\n\n x0, x1 = zeros(3), ones(3)\n y0, y1 = zeros(3), zeros(3)\n vx0, vx1 = zeros(3), zeros(3)\n vy0, vy1 = zeros(3), zeros(3)\n distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)\n @test (distSq, dDistSqDt, L1, L2) == (0, 0, 0, 0)\n\n x0, x1 = zeros(3), ones(3)\n y0, y1 = ones(3), ones(3)\n vx0, vx1 = zeros(3), zeros(3)\n vy0, vy1 = zeros(3), zeros(3)\n distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)\n @test (distSq, dDistSqDt, L1, L2) == (0, 0, 1, 0)\n\n y0, y1 = zeros(3), ones(3)\n x0, x1 = zeros(3), zeros(3)\n vx0, vx1 = zeros(3), zeros(3)\n vy0, vy1 = zeros(3), zeros(3)\n distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)\n @test (distSq, dDistSqDt, L1, L2) == (0, 0, 0, 0)\n\n y0, y1 = zeros(3), ones(3)\n x0, x1 = ones(3), ones(3)\n vx0, vx1 = zeros(3), zeros(3)\n vy0, vy1 = zeros(3), zeros(3)\n distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)\n @test (distSq, dDistSqDt, L1, L2) == (0, 0, 0, 1)\n\n x0, x1 = zeros(3), ones(3)\n y0, y1 = 0.5 * ones(3), 0.5 * ones(3)\n vx0, vx1 = zeros(3), zeros(3)\n vy0, vy1 = zeros(3), zeros(3)\n distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)\n @test (distSq, dDistSqDt, L1, L2) == (0, 0, 0.5, 0)\n\n y0, y1 = zeros(3), ones(3)\n x0, x1 = 0.5 * ones(3), 0.5 * ones(3)\n vx0, vx1 = zeros(3), zeros(3)\n vy0, vy1 = zeros(3), zeros(3)\n distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)\n @test (distSq, dDistSqDt, L1, L2) == (0, 0, 0, 0.5)\n\n x0, x1 = zeros(3), ones(3)\n y0, y1 = zeros(3), ones(3) .+ eps(Float64)^2\n vx0, vx1 = zeros(3), zeros(3)\n vy0, vy1 = zeros(3), zeros(3)\n distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)\n @test (distSq, dDistSqDt, L1, L2) == (0, 0, 0, 0)\n\n x0, x1 = zeros(3), ones(3)\n y0, y1 = [1, 0, 0], [2, 1, 1]\n vx0, vx1 = zeros(3), zeros(3)\n vy0, vy1 = zeros(3), zeros(3)\n distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)\n @test (distSq, dDistSqDt, L1, L2) == (1, 0, 0, 0)\n\n x1, x0 = zeros(3), ones(3)\n y0, y1 = [1, 0, 0], [2, 1, 1]\n vx0, vx1 = zeros(3), zeros(3)\n vy0, vy1 = zeros(3), zeros(3)\n distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)\n @test (distSq, dDistSqDt, L1, L2) == (6, 0, 1, 1)\n\n x0, x1 = zeros(3), ones(3)\n y1, y0 = [1, 0, 0], [2, 1, 1]\n vx0, vx1 = zeros(3), zeros(3)\n vy0, vy1 = zeros(3), zeros(3)\n distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)\n @test (distSq, dDistSqDt, L1, L2) == (2, 0, 1, 1)\n\n x1, x0 = zeros(3), ones(3)\n y0, y1 = [1, 1, 0], [1.5, 0.5, 0.5]\n vx0, vx1 = zeros(3), zeros(3)\n vy0, vy1 = zeros(3), zeros(3)\n distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)\n @test (distSq, dDistSqDt, L1, L2) == (0.5, 0, 0.25, 0.5)\n\n x0, x1 = zeros(3), zeros(3)\n y0, y1 = zeros(3), zeros(3)\n vx0, vx1 = zeros(3), zeros(3)\n vy0, vy1 = zeros(3), zeros(3)\n distSq, dDistSqDt, L1, L2 = minimumDistance(x0, x1, y0, y1, vx0, vx1, vy0, vy1)\n @test (distSq, dDistSqDt, L1, L2) == (0, 0, 0, 0)\nend",
"@testset \"Auxiliary\" begin\n dict = Dict(\n \"intFixDln\" => nodeTypeDln(2),\n \"noneDln\" => nodeTypeDln(0),\n \"intMobDln\" => nodeTypeDln(1),\n \"srfFixDln\" => nodeTypeDln(4),\n \"extDln\" => nodeTypeDln(5),\n \"srfMobDln\" => nodeTypeDln(3),\n \"tmpDln\" => nodeTypeDln(6),\n )\n\n @test makeInstanceDict(nodeTypeDln) == dict\n data = rand(5)\n @test inclusiveComparison(data[rand(1:5)], data...)\n @test !inclusiveComparison(data, data[rand(1:5)] * 6)\nend",
"@testset \"Quadrature\" begin\n n = 17\n a = -13\n b = 23\n x, w = gausslegendre(n, a, b)\n\n bma = (b - a) * 0.5\n bpa = (b + a) * 0.5\n x1, w1 = gausslegendre(n)\n x1 = bma * x1 .+ bpa\n w1 = bma * w1\n\n @test x ≈ x1\n @test w ≈ w1\nend"
] |
f7b83eb9f5a639491aa268ad263f4e6435e368a3
| 3,007
|
jl
|
Julia
|
test/semipoly.jl
|
doppioandante/Symbolics.jl
|
b077a7935c515736916fa63469ad53b0abf2c2d2
|
[
"MIT"
] | 1
|
2021-11-06T13:10:46.000Z
|
2021-11-06T13:10:46.000Z
|
test/semipoly.jl
|
doppioandante/Symbolics.jl
|
b077a7935c515736916fa63469ad53b0abf2c2d2
|
[
"MIT"
] | 45
|
2021-02-26T12:14:48.000Z
|
2021-02-26T12:30:33.000Z
|
test/semipoly.jl
|
doppioandante/Symbolics.jl
|
b077a7935c515736916fa63469ad53b0abf2c2d2
|
[
"MIT"
] | null | null | null |
using Symbolics
using Test
using Random
@variables x y z
@test_throws ArgumentError semipolynomial_form(x,[x],0)
d, r = semipolynomial_form(x, [x], 1)
@test d == Dict(x=>1)
@test r == 0
d, r = semipolynomial_form(x + sin(x) + 1 + y, [x], 1)
@test d == Dict(x=>1)
@test iszero(r - sin(x) - 1 - y)
d, r = semipolynomial_form(x^2+1+y, [x], 1)
@test isempty(d)
@test iszero(r - (x^2+1+y))
d, r = semipolynomial_form((x+2)^12, [x], 1)
@test d == Dict(x => 24576)
@test iszero(r + 24576x - (x+2)^12)
@syms a b c
const components = [2, a, b, c, x, y, z, (1+x), (1+y)^2, z*y, z*x]
function verify(t, d, wrt, nl)
try
iszero(t - (isempty(d) ? nl : sum(k*v for (k, v) in d) + nl))
catch err
println("""Error verifying semi-pf result for $t
wrt = $wrt
d = $d
nl = $nl""")
rethrow(err)
end
end
seed = 0
function trial()
global seed += 1
Random.seed!(666+seed)
n = rand(2:length(components)-1)
l, r = rand(components, n), vcat(rand(components, n), [1, 0, 1//2, 1.5])
t = *(map(1:rand(1:3)) do _
pow = rand([1,1,1,1,1,1,1,1,2,3])
nterms = rand(2:5)
sum(rand(l, nterms) .* rand(r, nterms)) ^ pow
end...)
@show t
for _ = 1:4
wrt = unique(rand([a,b,c,x,y,z], rand(1:6)))
for deg=Any[1,2,3,4,Inf]
if deg == 1
A, c = semilinear_form([t], wrt)
res = iszero(A*wrt + c - [t])
if !res
println("Semi-linear form is wrong: [$t] w.r.t $wrt ")
@show A c
end
elseif deg == 2
A,B,v2, c = semiquadratic_form([t], wrt)
res = iszero(A * wrt + B * v2 + c - [t])
if !res
println("Semi-quadratic form is wrong: $t w.r.t $wrt")
@show A B v2 c
end
else
if isfinite(deg)
d, nl = semipolynomial_form(t, wrt, deg)
@test all(x->Symbolics.pdegree(x) <= deg, keys(d))
for x in wrt
d2, enl = semipolynomial_form(expand(nl), wrt, Inf)
elim = all(x->Symbolics.pdegree(x)>deg, keys(d2))
if !elim
println("Imperfect elimination:")
@show t wrt deg nl expand(nl)
end
@test elim
end
else
d, nl = polynomial_coeffs(t, wrt)
end
res = verify(t, d, wrt, nl)
if !res
println("""Semi-poly form is wrong: $t w.r.t $wrt deg=$deg
Result: $d + $nl""")
end
end
@test res
end
end
end
for i=1:20
@testset "fuzz semi-polynomial-form ($i/20)" begin
trial()
end
end
| 26.147826
| 82
| 0.438311
|
[
"@testset \"fuzz semi-polynomial-form ($i/20)\" begin\n trial()\n end"
] |
f7b957ba7d72638e0bd6915795639204a39d020f
| 1,141
|
jl
|
Julia
|
test/reduce_test.jl
|
rohanmclure/ArrayChannels.jl
|
0098cdb23d16cca0e87ab2cdfcc86f24f7ae1c19
|
[
"MIT"
] | 15
|
2019-07-06T14:01:29.000Z
|
2021-10-14T17:30:33.000Z
|
test/reduce_test.jl
|
rohanmclure/ArrayChannels.jl
|
0098cdb23d16cca0e87ab2cdfcc86f24f7ae1c19
|
[
"MIT"
] | 8
|
2019-07-11T18:55:30.000Z
|
2020-08-31T16:10:59.000Z
|
test/reduce_test.jl
|
rohanmclure/ArrayChannels.jl
|
0098cdb23d16cca0e87ab2cdfcc86f24f7ae1c19
|
[
"MIT"
] | null | null | null |
rmprocs(workers()...); addprocs(4); @assert nprocs() == 5
@everywhere using ArrayChannels
using Test
function test_reduce_two()
@testset "Two-process Reduction" begin
A = ArrayChannel(Float64, procs()[1:2], 10)
println("Procs one and two: $(procs()[1:2])")
fill!(A, 1.0)
proc_2 = procs()[2]
@sync @spawnat proc_2 fill!(A, 1.0)
@sync begin
@async reduce!(+, A, 1)
@spawnat proc_2 reduce!(+, A, 1)
end
@test A[1] == 2.0
@sync begin
@async reduce!(+, A, proc_2)
@spawnat proc_2 reduce!(+, A, proc_2)
end
@test (@fetchfrom proc_2 A[1]) == 3.0
end
end
function test_reduce_five()
@testset "Five-process reduction" begin
A = ArrayChannel(Float64, procs(), 100000)
proc_3 = procs()[3]
for k in 1:10
@sync for i in 1 : length(procs())
@spawnat procs()[i] begin
fill!(A, i)
reduce!(+, A, proc_3)
end
end
@test (@fetchfrom proc_3 A[1]) == 15.0
end
end
end
| 27.829268
| 57
| 0.501315
|
[
"@testset \"Two-process Reduction\" begin\n A = ArrayChannel(Float64, procs()[1:2], 10)\n println(\"Procs one and two: $(procs()[1:2])\")\n fill!(A, 1.0)\n proc_2 = procs()[2]\n @sync @spawnat proc_2 fill!(A, 1.0)\n @sync begin\n @async reduce!(+, A, 1)\n @spawnat proc_2 reduce!(+, A, 1)\n end\n @test A[1] == 2.0\n\n @sync begin\n @async reduce!(+, A, proc_2)\n @spawnat proc_2 reduce!(+, A, proc_2)\n end\n @test (@fetchfrom proc_2 A[1]) == 3.0\n end",
"@testset \"Five-process reduction\" begin\n A = ArrayChannel(Float64, procs(), 100000)\n proc_3 = procs()[3]\n for k in 1:10\n @sync for i in 1 : length(procs())\n @spawnat procs()[i] begin\n fill!(A, i)\n reduce!(+, A, proc_3)\n end\n end\n @test (@fetchfrom proc_3 A[1]) == 15.0\n end\n end"
] |
f7b98638d64b0962128ef15999ff2e396ade61be
| 14,812
|
jl
|
Julia
|
test/BlockSystems_test.jl
|
hexaeder/IOSystems_prototype
|
93ae0593bd6430a2d686a22f21f3c17688234124
|
[
"MIT"
] | 2
|
2020-12-21T14:29:32.000Z
|
2021-01-02T12:53:49.000Z
|
test/BlockSystems_test.jl
|
hexaeder/IOSystems_prototype
|
93ae0593bd6430a2d686a22f21f3c17688234124
|
[
"MIT"
] | null | null | null |
test/BlockSystems_test.jl
|
hexaeder/IOSystems_prototype
|
93ae0593bd6430a2d686a22f21f3c17688234124
|
[
"MIT"
] | 1
|
2021-01-02T12:54:54.000Z
|
2021-01-02T12:54:54.000Z
|
using Test
using BlockSystems
using ModelingToolkit
using ModelingToolkit: get_iv, get_eqs, get_states
using LightGraphs
@info "Tests of BlockSystems.jl"
@testset "BlockSystems.jl" begin
@testset "namespaced accessors" begin
@parameters t i1(t) i2(t) a
@variables x1(t) x2(t) o1(t) o2(t)
D = Differential(t)
eqs = [D(x1) ~ a*i1, o1~i1, D(x2) ~ i2, o2~i2]
iob = IOBlock(eqs, [i1, i2], [o1, o2], name=:ns)
@test Set(BlockSystems.namespace_inputs(iob)) == Set([iob.i1, iob.i2])
@test Set(BlockSystems.namespace_outputs(iob)) == Set([iob.o1, iob.o2])
@test Set(BlockSystems.namespace_istates(iob)) == Set([iob.x1, iob.x2])
@test Set(BlockSystems.namespace_iparams(iob)) == Set([iob.a])
end
@testset "creation of IOBlocks" begin
@parameters t i1(t) i2(t) a b
@variables x1(t) x2(t) o1(t) o2(t)
D = Differential(t)
eqs = [D(x1) ~ a*i1,
D(x2) ~ b*i2,
o1 ~ a*x1,
o2 ~ b*x2]
iob = IOBlock(eqs, [i1, i2], [o1, o2], name=:iob)
@test Set(iob.inputs) == Set([i1, i2])
@test Set(iob.iparams) == Set([a, b])
@test Set(iob.istates) == Set([x1, x2])
@test Set(iob.outputs) == Set([o1, o2])
@test Set(iob.removed_states) == Set()
@test_throws ArgumentError IOBlock(eqs, [x1], [o1,o2])
@test_throws ArgumentError IOBlock(eqs, [i1,i2], [i1,o1,o2])
@parameters i a(t)
@variables x(t) o(t)
sys = ODESystem( [D(x) ~ a * i], name=:foo)
aeq = [i ~ 2*a + i1]
@test_throws ArgumentError IOBlock(:name, [i.val], [a.val], [], [x.val], sys, aeq)
@parameters t a(t) p
@variables x(t) y(t)
D = Differential(t)
IOBlock([x ~ 2 + a], [], [x])
IOBlock([D(y) ~ 2 + a], [], [x])
@test_throws ArgumentError IOBlock([a ~ 2 + x], [], [x])
@test_throws ArgumentError IOBlock([p ~ 2 + x], [p], [x], iv=t)
@test_throws ArgumentError IOBlock([a ~ 2 + x], [a], [x], iv=t)
end
@testset "test of create_namespace_promotions" begin
using ModelingToolkit: value
using BlockSystems: create_namespace_promotions
@parameters t
Aa, Ba, Ab, Bc = value.(@parameters A₊a B₊a(t) A₊b B₊c)
Ax, Bx, Ay, Bz = value.(@variables A₊x(t) B₊x(t) A₊y(t) B₊z(t))
b, c = value.(@parameters b c)
y, z = value.(@variables y(t) z(t))
prom = create_namespace_promotions([Aa, Ba, Ab, Bc, Ax, Bx, Ay, Bz], [], true)
@test Set(values(prom)) == Set([Aa, Ba, b, c, Ax, Bx, y, z])
prom = create_namespace_promotions([Aa, Ba, Ab, Bc, Ax, Bx, Ay, Bz], [b, y], true)
@test Set(values(prom)) == Set([Aa, Ba, Ab, c, Ax, Bx, Ay, z])
prom = create_namespace_promotions([Aa, Ba, Ab, Bc, Ax, Bx, Ay, Bz], [], false)
@test Set(values(prom)) == Set([Aa, Ba, Ab, Bc, Ax, Bx, Ay, Bz])
prom = create_namespace_promotions([Aa, Ba, Ab, Bc, Ax, Bx, Ay, Bz], [b, y], false)
@test Set(values(prom)) == Set([Aa, Ba, Ab, Bc, Ax, Bx, Ay, Bz])
end
@testset "IOBlock from other IOBlock" begin
@parameters t i1(t) i2(t) a b
@variables x1(t) x2(t) o1(t) o2(t)
D = Differential(t)
eqs = [D(x1) ~ a*i1,
D(x2) ~ b*i2,
o1 ~ a*x1,
o2 ~ b*x2]
iob1 = IOBlock(eqs, [i1, i2], [o1, o2], name=:iob1)
iob2 = IOBlock(iob1, name=:iob2)
iob3 = IOBlock(iob1)
@test iob1.name != iob2.name != iob3.name
@test Set(iob1.inputs) == Set(iob2.inputs) == Set(iob3.inputs)
@test Set(iob1.iparams) == Set(iob2.iparams) == Set(iob3.iparams)
@test Set(iob1.istates) == Set(iob2.istates) == Set(iob3.istates)
@test Set(iob1.outputs) == Set(iob2.outputs) == Set(iob3.outputs)
@test get_eqs(iob1.system) == get_eqs(iob2.system) == get_eqs(iob3.system)
@test iob1.system.name == iob1.name == :iob1
@test iob2.system.name == iob2.name == :iob2
@test iob3.system.name == iob3.name
end
@testset "test creation of namespace map" begin
@parameters t i(t) a b
@variables x(t) o(t)
D = Differential(t)
eqs = [D(x) ~ a*i, o ~ b*i]
@parameters i2(t) a
@variables x2(t) o(t)
eqs2 = [D(x) ~ a*i2, D(x2) ~ i2, o~i2]
iob1 = IOBlock(eqs, [i], [o], name=:iob1)
iob2 = IOBlock(eqs2, [i2], [o], name=:iob2)
@test Set(iob1.inputs) == Set(i)
@test Set(iob2.inputs) == Set(i2)
@test Set(iob1.outputs) == Set(o)
@test Set(iob2.outputs) == Set(o)
@test Set(iob1.istates) == Set(x)
@test Set(iob2.istates) == Set([x, x2])
@test Set(iob1.iparams) == Set([a, b])
@test Set(iob2.iparams) == Set(a)
sys = IOSystem([], [iob1, iob2])
@test Set(sys.inputs) == Set([i, i2])
@test Set(sys.istates) == Set([iob1.x, iob2.x, x2])
@test Set(sys.iparams) == Set([iob1.a, iob2.a, b])
@test Set(sys.outputs) == Set([iob1.o, iob2.o])
end
@testset "iosystem asserts" begin
@parameters t i(t)
@variables o(t)
iob1 = IOBlock([o ~ i],[i],[o],name=:name)
iob2 = IOBlock([o ~ i],[i],[o],name=:name)
# namespace collision
@test_throws ArgumentError IOSystem([iob1.o => iob2.i], [iob1, iob2])
iob2 = IOBlock([o ~ i],[i],[o])
# mulitiple conneections to same input
@test_throws ArgumentError IOSystem([iob1.o => iob1.i, iob2.o => iob1.i], [iob1, iob2])
# make sure that alle of form input => output
@test_throws ArgumentError IOSystem([iob1.o => iob1.o], [iob1, iob2])
@test_throws ArgumentError IOSystem([iob1.i => iob1.i], [iob1, iob2])
# assert that input maps refere to open inputs
@test_throws ArgumentError IOSystem([iob1.o => iob2.i], [iob1, iob2],
namespace_map = [iob2.i => i])
# assert that rhs of input map is unique
iob3 = IOBlock([o ~ i],[i],[o])
@test_throws ArgumentError IOSystem([iob1.o => iob2.i],
[iob1, iob2, iob3],
namespace_map = [iob1.i => i, iob3.i => i])
# test assertions for iparams and istats map
@parameters t a i(t) b c
@variables x(t) o(t) y(t)
D = Differential(t)
iob1 = IOBlock([D(x)~ i, o~a*x], [i], [o], name=:iob1)
iob2 = IOBlock([D(x)~ i, o~a*x], [i], [o], name=:iob2)
IOSystem([iob1.o => iob2.i], [iob1, iob2])
# rhs unique
@test_throws ArgumentError IOSystem([iob1.o => iob2.i], [iob1, iob2],
namespace_map = [iob1.a=>b, iob2.a=>b])
@test_throws ArgumentError IOSystem([iob1.o => iob2.i], [iob1, iob2],
namespace_map = [iob1.x=>y, iob2.x=>y])
# rhs unique
@test_throws ArgumentError IOSystem([iob1.o => iob2.i], [iob1, iob2],
namespace_map = [iob1.o=>y, iob2.o=>y])
end
function test_complete_namespace_promotions(ios)
eqs = vcat([ModelingToolkit.namespace_equations(iob.system) for iob in ios.systems]...)
allvars = [(get_variables(eq.lhs) ∪ get_variables(eq.rhs)) for eq in eqs]
allvars = union(allvars...) |> unique
allvars = setdiff(allvars, [BlockSystems.get_iv(ios)])
allkeys = keys(ios.namespace_map)
# closed inputs should not appear in allkeys
@test isempty(Set(allkeys) ∩ Set(last.(ios.connections)))
# but there should be no namespace collision with them either..
allkeys = Set(allkeys) ∪ Set(last.(ios.connections))
@test allunique(allkeys)
@test Set(allkeys) == Set(allvars)
end
@testset "test creation of systems" begin
#=
+------------+
in1 --> i1 -| iob1 |
in2 --> i2 -|(x1, x2)(a) |-o--+ +-----+
+------------+ +-ina-| add |- add ---> out
+------------+ +-inb-| |
in3 --> i1 -| iob2 |-o--+ +-----+
in4 --> i2 -|(x1, x2)(b) |
+------------+
=#
@parameters t i1(t) i2(t) a b ina(t) inb(t)
@variables x1(t) x2(t) o(t) add(t)
D = Differential(t)
eqs1 = [D(x1) ~ a*i1, D(x2)~i2, o~x1+x2]
iob1 = IOBlock(eqs1, [i1, i2], [o], name=:iob1)
eqs2 = [D(x1) ~ b*i1, D(x2)~i2, o~x1+x2]
iob2 = IOBlock(eqs2, [i1, i2], [o], name=:iob2)
ioadd = IOBlock([add ~ ina + inb], [ina, inb], [add], name=:add)
# try with auto namespacing
sys = IOSystem([iob1.o => ioadd.ina, iob2.o => ioadd.inb],
[iob1, iob2, ioadd],
name=:sys)
@test Set(sys.inputs) == Set([iob1.i1, iob1.i2, iob2.i1, iob2.i2])
@test Set(sys.iparams) == Set([a, b])
@test Set(sys.istates) == Set([iob1.x1, iob1.x2, iob2.x1, iob2.x2])
@test Set(sys.outputs) == Set([iob1.o, iob2.o, add])
test_complete_namespace_promotions(sys)
# provide maps
@parameters in1(t) in2(t) in3(t) in4(t) p1 p2
@variables out(t) y1(t) y2(t)
sys1 = IOSystem([iob1.o => ioadd.ina, iob2.o => ioadd.inb],
[iob1, iob2, ioadd],
namespace_map = Dict(iob1.i1 => in1,
iob1.i2 => in2,
iob2.i1 => in3,
iob2.i2 => in4,
iob1.a => p1,
iob2.b => p2,
iob1.x1 => y1,
iob1.x2 => y2,
iob2.x1 => x1,
iob2.x2 => x2,
ioadd.add => out),
outputs = [ioadd.add],
name=:sys)
sys2 = IOSystem([iob1.o => ioadd.ina, iob2.o => ioadd.inb],
[iob1, iob2, ioadd],
namespace_map = Dict(iob1.i1 => :in1,
iob1.i2 => :in2,
iob2.i1 => :in3,
iob2.i2 => :in4,
iob1.a => :p1,
iob2.b => :p2,
iob1.x1 => :y1,
iob1.x2 => :y2,
iob2.x1 => :x1,
iob2.x2 => :x2,
ioadd.add => :out),
outputs = [:out],
name=:sys)
@test Set(sys1.inputs) == Set([in1, in2, in3, in4])
@test Set(sys1.iparams) == Set([p1, p2])
@test Set(sys1.istates) == Set([y1, y2, x1, x2, iob1.o, iob2.o])
@test Set(sys1.outputs) == Set([out])
test_complete_namespace_promotions(sys1)
@test Set(sys2.inputs) == Set([in1, in2, in3, in4])
@test Set(sys2.iparams) == Set([p1, p2])
@test Set(sys2.istates) == Set([y1, y2, x1, x2, iob1.o, iob2.o])
@test Set(sys2.outputs) == Set([out])
test_complete_namespace_promotions(sys2)
# provide partial maps
sys = IOSystem([iob1.o => ioadd.ina, iob2.o => ioadd.inb],
[iob1, iob2, ioadd],
namespace_map = Dict(iob1.i1 => in1,
iob1.i2 => in2,
iob1.a => p1,
iob1.x1 => y1,
iob1.x2 => y2,
ioadd.add => out),
outputs = [out], # provide outputs as namespaced variable
name=:sys)
@test Set(sys.inputs) == Set([in1, in2, i1, i2])
@test Set(sys.iparams) == Set([p1, b])
@test Set(sys.istates) == Set([y1, y2, x1, x2, iob1.o, iob2.o])
@test Set(sys.outputs) == Set([out])
test_complete_namespace_promotions(sys)
# check for argument error for bad outputs argument
sys1 = IOSystem([iob1.o => ioadd.ina, iob2.o => ioadd.inb],
[iob1, iob2, ioadd],
namespace_map = Dict(ioadd.add => out),
outputs = [ioadd.add], # provide outputs as namespaced variable
name=:sys)
sys2 = IOSystem([iob1.o => ioadd.ina, iob2.o => ioadd.inb],
[iob1, iob2, ioadd],
namespace_map = Dict(ioadd.add => out),
outputs = [out], # provide outputs as namespaced variable
name=:sys)
@test Set(sys1.istates) == Set(sys2.istates)
@test Set(sys1.outputs) == Set(sys2.outputs)
@test_throws ArgumentError IOSystem([iob1.o => ioadd.ina, iob2.o => ioadd.inb],
[iob1, iob2, ioadd],
namespace_map = Dict(ioadd.add => out),
outputs = [p1], # provide outputs as namespaced variable
name=:sys)
end
@testset "test BlockSpec" begin
@parameters t
@parameters uᵢ(t) uᵣ(t)
@variables x(t) iᵢ(t) iᵣ(t)
bs1 = BlockSpec([:uᵣ, :uᵢ], [:iᵣ, :iᵢ])
bs2 = BlockSpec(value.([uᵣ, uᵢ]), value.([iᵣ, iᵢ]))
bs3 = BlockSpec([uᵣ, uᵢ], [iᵣ, iᵢ])
@test bs1.inputs == bs2.inputs == bs3.inputs
@test bs1.outputs == bs2.outputs == bs3.outputs
D = Differential(t)
eqs = [D(x) ~ x, iᵢ ~ uᵢ, iᵣ ~ uᵣ]
iob1 = IOBlock(eqs, [uᵢ, uᵣ], [iᵢ, iᵣ])
iob2 = IOBlock(eqs, [uᵢ], [iᵢ, iᵣ])
iob3 = IOBlock(eqs, [uᵢ, uᵣ], [iᵢ])
@test fulfills(iob1, bs1) == bs1(iob1) == true
@test fulfills(iob2, bs1) == bs1(iob2) == false
@test fulfills(iob3, bs1) == bs1(iob3) == false
sys1 = IOSystem([], [iob1, iob2])
sys2 = IOSystem([], [iob1, iob2], outputs=[iᵢ, iᵣ],
namespace_map = [iob1.iᵢ => iᵢ,
iob1.iᵣ => iᵣ,
iob1.uᵢ => uᵢ,
iob1.uᵣ => uᵣ])
@test bs1(sys1) == false
@test bs1(sys2) == true
end
end
| 44.48048
| 100
| 0.466784
|
[
"@testset \"BlockSystems.jl\" begin\n @testset \"namespaced accessors\" begin\n @parameters t i1(t) i2(t) a\n @variables x1(t) x2(t) o1(t) o2(t)\n D = Differential(t)\n eqs = [D(x1) ~ a*i1, o1~i1, D(x2) ~ i2, o2~i2]\n iob = IOBlock(eqs, [i1, i2], [o1, o2], name=:ns)\n @test Set(BlockSystems.namespace_inputs(iob)) == Set([iob.i1, iob.i2])\n @test Set(BlockSystems.namespace_outputs(iob)) == Set([iob.o1, iob.o2])\n @test Set(BlockSystems.namespace_istates(iob)) == Set([iob.x1, iob.x2])\n @test Set(BlockSystems.namespace_iparams(iob)) == Set([iob.a])\n end\n\n @testset \"creation of IOBlocks\" begin\n @parameters t i1(t) i2(t) a b\n @variables x1(t) x2(t) o1(t) o2(t)\n D = Differential(t)\n eqs = [D(x1) ~ a*i1,\n D(x2) ~ b*i2,\n o1 ~ a*x1,\n o2 ~ b*x2]\n\n iob = IOBlock(eqs, [i1, i2], [o1, o2], name=:iob)\n @test Set(iob.inputs) == Set([i1, i2])\n @test Set(iob.iparams) == Set([a, b])\n @test Set(iob.istates) == Set([x1, x2])\n @test Set(iob.outputs) == Set([o1, o2])\n @test Set(iob.removed_states) == Set()\n\n @test_throws ArgumentError IOBlock(eqs, [x1], [o1,o2])\n @test_throws ArgumentError IOBlock(eqs, [i1,i2], [i1,o1,o2])\n\n @parameters i a(t)\n @variables x(t) o(t)\n sys = ODESystem( [D(x) ~ a * i], name=:foo)\n aeq = [i ~ 2*a + i1]\n @test_throws ArgumentError IOBlock(:name, [i.val], [a.val], [], [x.val], sys, aeq)\n\n @parameters t a(t) p\n @variables x(t) y(t)\n D = Differential(t)\n IOBlock([x ~ 2 + a], [], [x])\n IOBlock([D(y) ~ 2 + a], [], [x])\n\n @test_throws ArgumentError IOBlock([a ~ 2 + x], [], [x])\n @test_throws ArgumentError IOBlock([p ~ 2 + x], [p], [x], iv=t)\n @test_throws ArgumentError IOBlock([a ~ 2 + x], [a], [x], iv=t)\n end\n\n @testset \"test of create_namespace_promotions\" begin\n using ModelingToolkit: value\n using BlockSystems: create_namespace_promotions\n @parameters t\n Aa, Ba, Ab, Bc = value.(@parameters A₊a B₊a(t) A₊b B₊c)\n Ax, Bx, Ay, Bz = value.(@variables A₊x(t) B₊x(t) A₊y(t) B₊z(t))\n b, c = value.(@parameters b c)\n y, z = value.(@variables y(t) z(t))\n\n prom = create_namespace_promotions([Aa, Ba, Ab, Bc, Ax, Bx, Ay, Bz], [], true)\n @test Set(values(prom)) == Set([Aa, Ba, b, c, Ax, Bx, y, z])\n\n prom = create_namespace_promotions([Aa, Ba, Ab, Bc, Ax, Bx, Ay, Bz], [b, y], true)\n @test Set(values(prom)) == Set([Aa, Ba, Ab, c, Ax, Bx, Ay, z])\n\n prom = create_namespace_promotions([Aa, Ba, Ab, Bc, Ax, Bx, Ay, Bz], [], false)\n @test Set(values(prom)) == Set([Aa, Ba, Ab, Bc, Ax, Bx, Ay, Bz])\n\n prom = create_namespace_promotions([Aa, Ba, Ab, Bc, Ax, Bx, Ay, Bz], [b, y], false)\n @test Set(values(prom)) == Set([Aa, Ba, Ab, Bc, Ax, Bx, Ay, Bz])\n end\n\n @testset \"IOBlock from other IOBlock\" begin\n @parameters t i1(t) i2(t) a b\n @variables x1(t) x2(t) o1(t) o2(t)\n D = Differential(t)\n eqs = [D(x1) ~ a*i1,\n D(x2) ~ b*i2,\n o1 ~ a*x1,\n o2 ~ b*x2]\n iob1 = IOBlock(eqs, [i1, i2], [o1, o2], name=:iob1)\n iob2 = IOBlock(iob1, name=:iob2)\n iob3 = IOBlock(iob1)\n @test iob1.name != iob2.name != iob3.name\n @test Set(iob1.inputs) == Set(iob2.inputs) == Set(iob3.inputs)\n @test Set(iob1.iparams) == Set(iob2.iparams) == Set(iob3.iparams)\n @test Set(iob1.istates) == Set(iob2.istates) == Set(iob3.istates)\n @test Set(iob1.outputs) == Set(iob2.outputs) == Set(iob3.outputs)\n @test get_eqs(iob1.system) == get_eqs(iob2.system) == get_eqs(iob3.system)\n @test iob1.system.name == iob1.name == :iob1\n @test iob2.system.name == iob2.name == :iob2\n @test iob3.system.name == iob3.name\n end\n\n @testset \"test creation of namespace map\" begin\n @parameters t i(t) a b\n @variables x(t) o(t)\n D = Differential(t)\n eqs = [D(x) ~ a*i, o ~ b*i]\n\n @parameters i2(t) a\n @variables x2(t) o(t)\n eqs2 = [D(x) ~ a*i2, D(x2) ~ i2, o~i2]\n\n iob1 = IOBlock(eqs, [i], [o], name=:iob1)\n iob2 = IOBlock(eqs2, [i2], [o], name=:iob2)\n\n @test Set(iob1.inputs) == Set(i)\n @test Set(iob2.inputs) == Set(i2)\n @test Set(iob1.outputs) == Set(o)\n @test Set(iob2.outputs) == Set(o)\n @test Set(iob1.istates) == Set(x)\n @test Set(iob2.istates) == Set([x, x2])\n @test Set(iob1.iparams) == Set([a, b])\n @test Set(iob2.iparams) == Set(a)\n\n sys = IOSystem([], [iob1, iob2])\n @test Set(sys.inputs) == Set([i, i2])\n @test Set(sys.istates) == Set([iob1.x, iob2.x, x2])\n @test Set(sys.iparams) == Set([iob1.a, iob2.a, b])\n @test Set(sys.outputs) == Set([iob1.o, iob2.o])\n end\n\n @testset \"iosystem asserts\" begin\n @parameters t i(t)\n @variables o(t)\n iob1 = IOBlock([o ~ i],[i],[o],name=:name)\n iob2 = IOBlock([o ~ i],[i],[o],name=:name)\n\n # namespace collision\n @test_throws ArgumentError IOSystem([iob1.o => iob2.i], [iob1, iob2])\n\n iob2 = IOBlock([o ~ i],[i],[o])\n # mulitiple conneections to same input\n @test_throws ArgumentError IOSystem([iob1.o => iob1.i, iob2.o => iob1.i], [iob1, iob2])\n # make sure that alle of form input => output\n @test_throws ArgumentError IOSystem([iob1.o => iob1.o], [iob1, iob2])\n @test_throws ArgumentError IOSystem([iob1.i => iob1.i], [iob1, iob2])\n\n # assert that input maps refere to open inputs\n @test_throws ArgumentError IOSystem([iob1.o => iob2.i], [iob1, iob2],\n namespace_map = [iob2.i => i])\n # assert that rhs of input map is unique\n iob3 = IOBlock([o ~ i],[i],[o])\n @test_throws ArgumentError IOSystem([iob1.o => iob2.i],\n [iob1, iob2, iob3],\n namespace_map = [iob1.i => i, iob3.i => i])\n\n # test assertions for iparams and istats map\n @parameters t a i(t) b c\n @variables x(t) o(t) y(t)\n D = Differential(t)\n iob1 = IOBlock([D(x)~ i, o~a*x], [i], [o], name=:iob1)\n iob2 = IOBlock([D(x)~ i, o~a*x], [i], [o], name=:iob2)\n IOSystem([iob1.o => iob2.i], [iob1, iob2])\n # rhs unique\n @test_throws ArgumentError IOSystem([iob1.o => iob2.i], [iob1, iob2],\n namespace_map = [iob1.a=>b, iob2.a=>b])\n @test_throws ArgumentError IOSystem([iob1.o => iob2.i], [iob1, iob2],\n namespace_map = [iob1.x=>y, iob2.x=>y])\n\n # rhs unique\n @test_throws ArgumentError IOSystem([iob1.o => iob2.i], [iob1, iob2],\n namespace_map = [iob1.o=>y, iob2.o=>y])\n end\n\n function test_complete_namespace_promotions(ios)\n eqs = vcat([ModelingToolkit.namespace_equations(iob.system) for iob in ios.systems]...)\n allvars = [(get_variables(eq.lhs) ∪ get_variables(eq.rhs)) for eq in eqs]\n allvars = union(allvars...) |> unique\n allvars = setdiff(allvars, [BlockSystems.get_iv(ios)])\n allkeys = keys(ios.namespace_map)\n # closed inputs should not appear in allkeys\n @test isempty(Set(allkeys) ∩ Set(last.(ios.connections)))\n # but there should be no namespace collision with them either..\n allkeys = Set(allkeys) ∪ Set(last.(ios.connections))\n @test allunique(allkeys)\n @test Set(allkeys) == Set(allvars)\n end\n\n @testset \"test creation of systems\" begin\n #=\n +------------+\n in1 --> i1 -| iob1 |\n in2 --> i2 -|(x1, x2)(a) |-o--+ +-----+\n +------------+ +-ina-| add |- add ---> out\n +------------+ +-inb-| |\n in3 --> i1 -| iob2 |-o--+ +-----+\n in4 --> i2 -|(x1, x2)(b) |\n +------------+\n =#\n @parameters t i1(t) i2(t) a b ina(t) inb(t)\n @variables x1(t) x2(t) o(t) add(t)\n D = Differential(t)\n eqs1 = [D(x1) ~ a*i1, D(x2)~i2, o~x1+x2]\n iob1 = IOBlock(eqs1, [i1, i2], [o], name=:iob1)\n\n eqs2 = [D(x1) ~ b*i1, D(x2)~i2, o~x1+x2]\n iob2 = IOBlock(eqs2, [i1, i2], [o], name=:iob2)\n\n ioadd = IOBlock([add ~ ina + inb], [ina, inb], [add], name=:add)\n\n # try with auto namespacing\n sys = IOSystem([iob1.o => ioadd.ina, iob2.o => ioadd.inb],\n [iob1, iob2, ioadd],\n name=:sys)\n @test Set(sys.inputs) == Set([iob1.i1, iob1.i2, iob2.i1, iob2.i2])\n @test Set(sys.iparams) == Set([a, b])\n @test Set(sys.istates) == Set([iob1.x1, iob1.x2, iob2.x1, iob2.x2])\n @test Set(sys.outputs) == Set([iob1.o, iob2.o, add])\n test_complete_namespace_promotions(sys)\n\n # provide maps\n @parameters in1(t) in2(t) in3(t) in4(t) p1 p2\n @variables out(t) y1(t) y2(t)\n sys1 = IOSystem([iob1.o => ioadd.ina, iob2.o => ioadd.inb],\n [iob1, iob2, ioadd],\n namespace_map = Dict(iob1.i1 => in1,\n iob1.i2 => in2,\n iob2.i1 => in3,\n iob2.i2 => in4,\n iob1.a => p1,\n iob2.b => p2,\n iob1.x1 => y1,\n iob1.x2 => y2,\n iob2.x1 => x1,\n iob2.x2 => x2,\n ioadd.add => out),\n outputs = [ioadd.add],\n name=:sys)\n sys2 = IOSystem([iob1.o => ioadd.ina, iob2.o => ioadd.inb],\n [iob1, iob2, ioadd],\n namespace_map = Dict(iob1.i1 => :in1,\n iob1.i2 => :in2,\n iob2.i1 => :in3,\n iob2.i2 => :in4,\n iob1.a => :p1,\n iob2.b => :p2,\n iob1.x1 => :y1,\n iob1.x2 => :y2,\n iob2.x1 => :x1,\n iob2.x2 => :x2,\n ioadd.add => :out),\n outputs = [:out],\n name=:sys)\n @test Set(sys1.inputs) == Set([in1, in2, in3, in4])\n @test Set(sys1.iparams) == Set([p1, p2])\n @test Set(sys1.istates) == Set([y1, y2, x1, x2, iob1.o, iob2.o])\n @test Set(sys1.outputs) == Set([out])\n test_complete_namespace_promotions(sys1)\n\n @test Set(sys2.inputs) == Set([in1, in2, in3, in4])\n @test Set(sys2.iparams) == Set([p1, p2])\n @test Set(sys2.istates) == Set([y1, y2, x1, x2, iob1.o, iob2.o])\n @test Set(sys2.outputs) == Set([out])\n test_complete_namespace_promotions(sys2)\n\n # provide partial maps\n sys = IOSystem([iob1.o => ioadd.ina, iob2.o => ioadd.inb],\n [iob1, iob2, ioadd],\n namespace_map = Dict(iob1.i1 => in1,\n iob1.i2 => in2,\n iob1.a => p1,\n iob1.x1 => y1,\n iob1.x2 => y2,\n ioadd.add => out),\n outputs = [out], # provide outputs as namespaced variable\n name=:sys)\n @test Set(sys.inputs) == Set([in1, in2, i1, i2])\n @test Set(sys.iparams) == Set([p1, b])\n @test Set(sys.istates) == Set([y1, y2, x1, x2, iob1.o, iob2.o])\n @test Set(sys.outputs) == Set([out])\n test_complete_namespace_promotions(sys)\n\n # check for argument error for bad outputs argument\n sys1 = IOSystem([iob1.o => ioadd.ina, iob2.o => ioadd.inb],\n [iob1, iob2, ioadd],\n namespace_map = Dict(ioadd.add => out),\n outputs = [ioadd.add], # provide outputs as namespaced variable\n name=:sys)\n sys2 = IOSystem([iob1.o => ioadd.ina, iob2.o => ioadd.inb],\n [iob1, iob2, ioadd],\n namespace_map = Dict(ioadd.add => out),\n outputs = [out], # provide outputs as namespaced variable\n name=:sys)\n @test Set(sys1.istates) == Set(sys2.istates)\n @test Set(sys1.outputs) == Set(sys2.outputs)\n @test_throws ArgumentError IOSystem([iob1.o => ioadd.ina, iob2.o => ioadd.inb],\n [iob1, iob2, ioadd],\n namespace_map = Dict(ioadd.add => out),\n outputs = [p1], # provide outputs as namespaced variable\n name=:sys)\n end\n\n @testset \"test BlockSpec\" begin\n @parameters t\n @parameters uᵢ(t) uᵣ(t)\n @variables x(t) iᵢ(t) iᵣ(t)\n bs1 = BlockSpec([:uᵣ, :uᵢ], [:iᵣ, :iᵢ])\n bs2 = BlockSpec(value.([uᵣ, uᵢ]), value.([iᵣ, iᵢ]))\n bs3 = BlockSpec([uᵣ, uᵢ], [iᵣ, iᵢ])\n @test bs1.inputs == bs2.inputs == bs3.inputs\n @test bs1.outputs == bs2.outputs == bs3.outputs\n\n D = Differential(t)\n eqs = [D(x) ~ x, iᵢ ~ uᵢ, iᵣ ~ uᵣ]\n iob1 = IOBlock(eqs, [uᵢ, uᵣ], [iᵢ, iᵣ])\n iob2 = IOBlock(eqs, [uᵢ], [iᵢ, iᵣ])\n iob3 = IOBlock(eqs, [uᵢ, uᵣ], [iᵢ])\n\n @test fulfills(iob1, bs1) == bs1(iob1) == true\n @test fulfills(iob2, bs1) == bs1(iob2) == false\n @test fulfills(iob3, bs1) == bs1(iob3) == false\n\n sys1 = IOSystem([], [iob1, iob2])\n sys2 = IOSystem([], [iob1, iob2], outputs=[iᵢ, iᵣ],\n namespace_map = [iob1.iᵢ => iᵢ,\n iob1.iᵣ => iᵣ,\n iob1.uᵢ => uᵢ,\n iob1.uᵣ => uᵣ])\n\n @test bs1(sys1) == false\n @test bs1(sys2) == true\n end\nend"
] |
f7bad86a00d24607f18797a209af677bea40efd3
| 2,819
|
jl
|
Julia
|
script/investigate/two-sym-CV-gen-Siddhu-channel.jl
|
ChitambarLab/CVChannel.jl
|
479fa1e70d19b5434137f9017d99830796802d87
|
[
"MIT"
] | null | null | null |
script/investigate/two-sym-CV-gen-Siddhu-channel.jl
|
ChitambarLab/CVChannel.jl
|
479fa1e70d19b5434137f9017d99830796802d87
|
[
"MIT"
] | 4
|
2021-09-21T00:29:01.000Z
|
2021-10-15T00:35:15.000Z
|
script/investigate/two-sym-CV-gen-Siddhu-channel.jl
|
ChitambarLab/cv-channel
|
479fa1e70d19b5434137f9017d99830796802d87
|
[
"MIT"
] | null | null | null |
using CVChannel
using Test
using DelimitedFiles
"""
This script looks at the communication value of the
generalized Siddhu channel using SDP relaxations.
Specifically, it shows that 2-sym cv is effectively
the same as cv PPT, and that they are loose at least
some of the time. It also shows multiplicativity over PPT cone.
"""
@testset "Investigate generalized Siddhu channel" begin
println("We calculate cvPPT, 2symCV, and cvPPT of the channel ran in parallel.")
println("We then show that 2symCV provides no improvement to cvPPT and that cvPPT")
println("is effectively multiplicative for the gen Siddhu with itself.")
s_range = [0:0.1:0.5;]
μ_range = [0:0.1:1;]
cv_table = zeros(length(s_range),length(μ_range))
par_cv_table = zeros(length(s_range),length(μ_range))
twosym_cv_table = zeros(length(s_range),length(μ_range))
non_mult_table = zeros(length(s_range),length(μ_range))
s_ctr, μ_ctr = 1,1
for s_id in s_range
println("---Now scanning for s=",s_id,"---")
for μ_id in μ_range
println("μ=",μ_id)
genSidChan(X) = generalizedSiddhu(X,s_id,μ_id)
gensid_chan = Choi(genSidChan,3,3)
#To save time we only calculate cv once since its same channel
cv, = pptCV(gensid_chan, :dual)
par_choi = parChoi(gensid_chan,gensid_chan)
parcv, = pptCV(par_choi, :primal)
cv_2sym, = twoSymCVPrimal(gensid_chan)
cv_table[s_ctr,μ_ctr] =cv
par_cv_table[s_ctr,μ_ctr] = parcv
twosym_cv_table[s_ctr,μ_ctr] = cv_2sym
non_mult_table[s_ctr,μ_ctr] = parcv - cv^2
μ_ctr += 1
end
s_ctr += 1
μ_ctr = 1
end
println("First we verify that cvPPT is effectively multiplicative over the whole range.")
@test all(non_mult_table -> non_mult_table < 2e-5 , non_mult_table[:,:])
println("Next we verify that cvPPT is approximately 2symCV over the whole range.")
diff = twosym_cv_table - cv_table
@test all(diff -> diff < 3e-6, diff[:,:])
println("Given this we just look at the 2symCV of the channel.")
info_vec = Vector{Union{Nothing,String}}(nothing, length(s_range)+1)
label_vec = hcat("s↓ μ:",μ_range')
info_vec[1] = "INFO:"
info_vec[2] = "Generated by two-sym-CV-gen-Siddhu-channel.jl"
info_vec[3] = "s_range = " * string(s_range)
info_vec[4] = "μ_range = " * string(μ_range)
data_to_save = hcat(vcat(label_vec,hcat(s_range,twosym_cv_table)),info_vec)
println("Here is the 2symCV of the channel:")
show(stdout, "text/plain", data_to_save)
println("\nPlease name the file you'd like to write these results to: \n")
file_name = readline()
file_to_open = string(file_name,".csv")
writedlm(file_to_open, data_to_save, ',')
end
| 41.455882
| 93
| 0.668322
|
[
"@testset \"Investigate generalized Siddhu channel\" begin\n println(\"We calculate cvPPT, 2symCV, and cvPPT of the channel ran in parallel.\")\n println(\"We then show that 2symCV provides no improvement to cvPPT and that cvPPT\")\n println(\"is effectively multiplicative for the gen Siddhu with itself.\")\n s_range = [0:0.1:0.5;]\n μ_range = [0:0.1:1;]\n cv_table = zeros(length(s_range),length(μ_range))\n par_cv_table = zeros(length(s_range),length(μ_range))\n twosym_cv_table = zeros(length(s_range),length(μ_range))\n non_mult_table = zeros(length(s_range),length(μ_range))\n s_ctr, μ_ctr = 1,1\n for s_id in s_range\n println(\"---Now scanning for s=\",s_id,\"---\")\n for μ_id in μ_range\n println(\"μ=\",μ_id)\n genSidChan(X) = generalizedSiddhu(X,s_id,μ_id)\n gensid_chan = Choi(genSidChan,3,3)\n #To save time we only calculate cv once since its same channel\n cv, = pptCV(gensid_chan, :dual)\n par_choi = parChoi(gensid_chan,gensid_chan)\n parcv, = pptCV(par_choi, :primal)\n cv_2sym, = twoSymCVPrimal(gensid_chan)\n cv_table[s_ctr,μ_ctr] =cv\n par_cv_table[s_ctr,μ_ctr] = parcv\n twosym_cv_table[s_ctr,μ_ctr] = cv_2sym\n non_mult_table[s_ctr,μ_ctr] = parcv - cv^2\n μ_ctr += 1\n end\n s_ctr += 1\n μ_ctr = 1\n end\n\n println(\"First we verify that cvPPT is effectively multiplicative over the whole range.\")\n @test all(non_mult_table -> non_mult_table < 2e-5 , non_mult_table[:,:])\n\n println(\"Next we verify that cvPPT is approximately 2symCV over the whole range.\")\n diff = twosym_cv_table - cv_table\n @test all(diff -> diff < 3e-6, diff[:,:])\n\n println(\"Given this we just look at the 2symCV of the channel.\")\n\n info_vec = Vector{Union{Nothing,String}}(nothing, length(s_range)+1)\n label_vec = hcat(\"s↓ μ:\",μ_range')\n info_vec[1] = \"INFO:\"\n info_vec[2] = \"Generated by two-sym-CV-gen-Siddhu-channel.jl\"\n info_vec[3] = \"s_range = \" * string(s_range)\n info_vec[4] = \"μ_range = \" * string(μ_range)\n data_to_save = hcat(vcat(label_vec,hcat(s_range,twosym_cv_table)),info_vec)\n\n println(\"Here is the 2symCV of the channel:\")\n show(stdout, \"text/plain\", data_to_save)\n println(\"\\nPlease name the file you'd like to write these results to: \\n\")\n file_name = readline()\n file_to_open = string(file_name,\".csv\")\n writedlm(file_to_open, data_to_save, ',')\nend"
] |
f7bc9183de8b016fa5a1369493a28366ff6a961a
| 207
|
jl
|
Julia
|
test/runtests.jl
|
invenia/Hyperparameters.jl
|
625ff9f79d9f0347963147345ecaa06c90fdad21
|
[
"MIT"
] | 1
|
2022-01-25T09:24:39.000Z
|
2022-01-25T09:24:39.000Z
|
test/runtests.jl
|
invenia/Hyperparameters.jl
|
625ff9f79d9f0347963147345ecaa06c90fdad21
|
[
"MIT"
] | 15
|
2020-06-26T20:08:04.000Z
|
2021-08-16T19:44:21.000Z
|
test/runtests.jl
|
invenia/Hyperparameters.jl
|
625ff9f79d9f0347963147345ecaa06c90fdad21
|
[
"MIT"
] | null | null | null |
using Hyperparameters
using FilePathsBase
using JSON
using Memento
using Memento.TestUtils
using Test
const LOGGER = getlogger()
@testset "Hyperparameters.jl" begin
include("hyperparameters.jl")
end
| 13.8
| 35
| 0.797101
|
[
"@testset \"Hyperparameters.jl\" begin\n include(\"hyperparameters.jl\")\nend"
] |
f7c10b43cf6f04d7dfc243e511610325565f3496
| 7,689
|
jl
|
Julia
|
test/geometrytypes.jl
|
pauljurczak/GeometryBasics.jl
|
e9c9e0cc4b6b3aa28572d56c982af8588420c43d
|
[
"MIT"
] | null | null | null |
test/geometrytypes.jl
|
pauljurczak/GeometryBasics.jl
|
e9c9e0cc4b6b3aa28572d56c982af8588420c43d
|
[
"MIT"
] | null | null | null |
test/geometrytypes.jl
|
pauljurczak/GeometryBasics.jl
|
e9c9e0cc4b6b3aa28572d56c982af8588420c43d
|
[
"MIT"
] | null | null | null |
using Test, GeometryBasics
@testset "algorithms.jl" begin
cube = Rect(Vec3f0(-0.5), Vec3f0(1))
cube_faces = decompose(TriangleFace{Int}, QuadFace{Int}[
(1,3,4,2),
(2,4,8,6),
(4,3,7,8),
(1,5,7,3),
(1,2,6,5),
(5,6,8,7),
])
cube_vertices = decompose(Point{3,Float32}, cube)
@test area(cube_vertices, cube_faces) == 6
mesh = Mesh(cube_vertices, cube_faces)
@test GeometryBasics.volume(mesh) ≈ 1
end
@testset "Cylinder" begin
@testset "constructors" begin
o, extr, r = Point2f0(1, 2), Point2f0(3, 4), 5f0
s = Cylinder(o, extr, r)
@test typeof(s) == Cylinder{2,Float32}
@test typeof(s) == Cylinder2{Float32}
@test origin(s) == o
@test extremity(s) == extr
@test radius(s) == r
#@test abs(height(s)- norm([1,2]-[3,4]))<1e-5
h = norm(o - extr)
@test isapprox(height(s), h)
#@test norm(direction(s) - Point{2,Float32}([2,2]./norm([1,2]-[3,4])))<1e-5
@test isapprox(direction(s), Point2f0(2, 2) ./ h)
v1 = rand(Point{3, Float64}); v2 = rand(Point{3, Float64}); R = rand()
s = Cylinder(v1, v2, R)
@test typeof(s) == Cylinder{3, Float64}
@test typeof(s) == Cylinder3{Float64}
@test origin(s) == v1
@test extremity(s) == v2
@test radius(s) == R
@test height(s) == norm(v2 - v1)
#@test norm(direction(s) - Point{3,Float64}((v2-v1)./norm(v2-v1)))<1e-10
@test isapprox(direction(s), (v2-v1) ./ norm(v2 .- v1))
end
@testset "decompose" begin
o, extr, r = Point2f0(1, 2), Point2f0(3, 4), 5f0
s = Cylinder(o, extr, r)
positions = Point{3, Float32}[
(-0.7677671, 3.767767, 0.0),
(2.767767, 0.23223293, 0.0),
(0.23223293, 4.767767, 0.0),
(3.767767, 1.2322329, 0.0),
(1.2322329, 5.767767, 0.0),
(4.767767, 2.232233, 0.0)
]
@test decompose(Point3f0, s, (2, 3)) ≈ positions
FT = TriangleFace{Int}
faces = FT[
(1,2,4),
(1,4,3),
(3,4,6),
(3,6,5)
]
@test faces == decompose(FT, s, (2,3))
v1 = Point{3, Float64}(1,2,3); v2 = Point{3, Float64}(4,5,6); R = 5.0
s = Cylinder(v1, v2, R)
positions = Point{3,Float64}[
(4.535533905932738,-1.5355339059327373,3.0),
(7.535533905932738,1.4644660940672627,6.0),
(3.0412414523193148,4.041241452319315,-1.0824829046386295),
(6.041241452319315,7.041241452319315,1.9175170953613705),
(-2.535533905932737,5.535533905932738,2.9999999999999996),
(0.46446609406726314,8.535533905932738,6.0),
(-1.0412414523193152,-0.04124145231931431,7.0824829046386295),
(1.9587585476806848,2.9587585476806857,10.08248290463863),
(1,2,3),
(4,5,6)
]
@test decompose(Point3{Float64}, s, 8) ≈ positions
faces = TriangleFace{Int}[
(3, 2, 1),
(4, 2, 3),
(5, 4, 3),
(6, 4, 5),
(7, 6, 5),
(8, 6, 7),
(1, 8, 7),
(2, 8, 1),
(3, 1, 9),
(2, 4, 10),
(5, 3, 9),
(4, 6, 10),
(7, 5, 9),
(6, 8, 10),
(1, 7, 9),
(8, 2, 10)
]
@test faces == decompose(TriangleFace{Int}, s, 8)
m = triangle_mesh(s, nvertices=8)
@test GeometryBasics.faces(m) == faces
@test GeometryBasics.coordinates(m) ≈ positions
m = normal_mesh(s)# just test that it works without explicit resolution parameter
@test m isa GLNormalMesh
end
end
@testset "HyperRectangles" begin
a = Rect(Vec(0,0),Vec(1,1))
pt_expa = Point{2,Int}[(0,0), (1,0), (0,1), (1,1)]
@test decompose(Point{2,Int},a) == pt_expa
mesh = normal_mesh(a)
@test decompose(Point2f0, mesh) == pt_expa
b = Rect(Vec(1,1,1),Vec(1,1,1))
pt_expb = Point{3,Int}[(1,1,1),(2,1,1),(1,2,1),(2,2,1),(1,1,2),(2,1,2),(1,2,2),(2,2,2)]
@test decompose(Point{3,Int}, b) == pt_expb
mesh = normal_mesh(b)
end
NFace = NgonFace
@testset "Faces" begin
@test convert_simplex(GLTriangleFace, QuadFace{Int}(1,2,3,4)) == (GLTriangleFace(1,2,3), GLTriangleFace(1,3,4))
@test convert_simplex(NFace{3, ZeroIndex{Int}}, QuadFace{ZeroIndex{Int}}(1,2,3,4)) == (NFace{3,ZeroIndex{Int}}(1,2,3), NFace{3, ZeroIndex{Int}}(1,3,4))
@test convert_simplex(NFace{3, OffsetInteger{3, Int}}, NFace{4, OffsetInteger{2, Int}}(1,2,3,4)) == (
NFace{3, OffsetInteger{3, Int}}(1,2,3),
NFace{3, OffsetInteger{3, Int}}(1,3,4)
)
@test convert_simplex(LineFace{Int}, QuadFace{Int}(1,2,3,4)) == (
LineFace{Int}(1,2),
LineFace{Int}(2,3),
LineFace{Int}(3,4),
LineFace{Int}(4,1)
)
end
@testset "Normals" begin
n64 = Vec{3, Float64}[
(0.0,0.0,-1.0),
(0.0,0.0,-1.0),
(0.0,0.0,-1.0),
(0.0,0.0,-1.0),
(0.0,0.0,1.0),
(0.0,0.0,1.0),
(0.0,0.0,1.0),
(0.0,0.0,1.0),
(-1.0,0.0,0.0),
(-1.0,0.0,0.0),
(-1.0,0.0,0.0),
(-1.0,0.0,0.0),
(1.0,0.0,0.0),
(1.0,0.0,0.0),
(1.0,0.0,0.0),
(1.0,0.0,0.0),
(0.0,1.0,0.0),
(0.0,1.0,0.0),
(0.0,1.0,0.0),
(0.0,1.0,0.0),
(0.0,-1.0,0.0),
(0.0,-1.0,0.0),
(0.0,-1.0,0.0),
(0.0,-1.0,0.0),
]
n32 = map(Vec{3,Float32}, n64)
r = triangle_mesh(centered(Rect3D))
# @test normals(coordinates(r), GeometryBasics.faces(r)) == n32
# @test normals(coordinates(r), GeometryBasics.faces(r)) == n64
end
@testset "HyperSphere" begin
sphere = Sphere{Float32}(Point3f0(0), 1f0)
points = decompose(Point, sphere, 3)
point_target = Point{3,Float32}[
[0.0, 0.0, 1.0], [1.0, 0.0, 6.12323e-17], [1.22465e-16, 0.0, -1.0],
[-0.0, 0.0, 1.0], [-1.0, 1.22465e-16, 6.12323e-17],
[-1.22465e-16, 1.49976e-32, -1.0], [0.0, -0.0, 1.0],
[1.0, -2.44929e-16, 6.12323e-17], [1.22465e-16,-2.99952e-32, -1.0]
]
@test points ≈ point_target
f = decompose(TriangleFace{Int}, sphere, 3)
face_target = TriangleFace{Int}[
[1, 2, 5], [1, 5, 4], [2, 3, 6], [2, 6, 5],
[4, 5, 8], [4, 8, 7], [5, 6, 9], [5, 9, 8]
]
@test f == face_target
circle = Circle(Point2f0(0), 1f0)
points = decompose(Point2f0, circle, 20)
@test length(points) == 20
mesh = triangle_mesh(circle, nvertices=32)
@test decompose(Point2f0, mesh)[1:end] ≈ decompose(Point2f0, circle, 32)
end
@testset "Rectangles" begin
rect = FRect2D(0, 7, 20, 3)
@test (rect + 4) == FRect2D(4, 11, 20, 3)
@test (rect + Vec(2, -2)) == FRect2D(2, 5, 20, 3)
@test (rect - 4) == FRect2D(-4, 3, 20, 3)
@test (rect - Vec(2, -2)) == FRect2D(-2, 9, 20, 3)
base = Vec3f0(1, 2, 3)
wxyz = Vec3f0(-2, 4, 2)
rect = FRect3D(base, wxyz)
@test (rect + 4) == FRect3D(base .+ 4, wxyz)
@test (rect + Vec(2, -2, 3)) == FRect3D(base .+ Vec(2, -2, 3), wxyz)
@test (rect - 4) == FRect3D(base .- 4, wxyz)
@test (rect - Vec(2, -2, 7)) == FRect3D(base .- Vec(2, -2, 7), wxyz)
rect = FRect2D(0, 7, 20, 3)
@test (rect * 4) == FRect2D(0, 7*4, 20*4, 3*4)
@test (rect * Vec(2, -2)) == FRect2D(0, -7*2, 20*2, -3*2)
base = Vec3f0(1, 2, 3)
wxyz = Vec3f0(-2, 4, 2)
rect = FRect3D(base, wxyz)
@test (rect * 4) == FRect3D(base .* 4, wxyz .* 4)
@test (rect * Vec(2, -2, 3)) == FRect3D(base .* Vec(2, -2, 3), wxyz .* Vec(2, -2, 3))
end
| 32.306723
| 155
| 0.506048
|
[
"@testset \"algorithms.jl\" begin\n cube = Rect(Vec3f0(-0.5), Vec3f0(1))\n cube_faces = decompose(TriangleFace{Int}, QuadFace{Int}[\n (1,3,4,2),\n (2,4,8,6),\n (4,3,7,8),\n (1,5,7,3),\n (1,2,6,5),\n (5,6,8,7),\n ])\n cube_vertices = decompose(Point{3,Float32}, cube)\n @test area(cube_vertices, cube_faces) == 6\n mesh = Mesh(cube_vertices, cube_faces)\n @test GeometryBasics.volume(mesh) ≈ 1\nend",
"@testset \"Cylinder\" begin\n @testset \"constructors\" begin\n o, extr, r = Point2f0(1, 2), Point2f0(3, 4), 5f0\n s = Cylinder(o, extr, r)\n @test typeof(s) == Cylinder{2,Float32}\n @test typeof(s) == Cylinder2{Float32}\n @test origin(s) == o\n @test extremity(s) == extr\n @test radius(s) == r\n #@test abs(height(s)- norm([1,2]-[3,4]))<1e-5\n h = norm(o - extr)\n @test isapprox(height(s), h)\n #@test norm(direction(s) - Point{2,Float32}([2,2]./norm([1,2]-[3,4])))<1e-5\n @test isapprox(direction(s), Point2f0(2, 2) ./ h)\n v1 = rand(Point{3, Float64}); v2 = rand(Point{3, Float64}); R = rand()\n s = Cylinder(v1, v2, R)\n @test typeof(s) == Cylinder{3, Float64}\n @test typeof(s) == Cylinder3{Float64}\n @test origin(s) == v1\n @test extremity(s) == v2\n @test radius(s) == R\n @test height(s) == norm(v2 - v1)\n #@test norm(direction(s) - Point{3,Float64}((v2-v1)./norm(v2-v1)))<1e-10\n @test isapprox(direction(s), (v2-v1) ./ norm(v2 .- v1))\n end\n\n @testset \"decompose\" begin\n\n o, extr, r = Point2f0(1, 2), Point2f0(3, 4), 5f0\n s = Cylinder(o, extr, r)\n positions = Point{3, Float32}[\n (-0.7677671, 3.767767, 0.0),\n (2.767767, 0.23223293, 0.0),\n (0.23223293, 4.767767, 0.0),\n (3.767767, 1.2322329, 0.0),\n (1.2322329, 5.767767, 0.0),\n (4.767767, 2.232233, 0.0)\n ]\n @test decompose(Point3f0, s, (2, 3)) ≈ positions\n\n FT = TriangleFace{Int}\n faces = FT[\n (1,2,4),\n (1,4,3),\n (3,4,6),\n (3,6,5)\n ]\n @test faces == decompose(FT, s, (2,3))\n\n v1 = Point{3, Float64}(1,2,3); v2 = Point{3, Float64}(4,5,6); R = 5.0\n s = Cylinder(v1, v2, R)\n positions = Point{3,Float64}[\n (4.535533905932738,-1.5355339059327373,3.0),\n (7.535533905932738,1.4644660940672627,6.0),\n (3.0412414523193148,4.041241452319315,-1.0824829046386295),\n (6.041241452319315,7.041241452319315,1.9175170953613705),\n (-2.535533905932737,5.535533905932738,2.9999999999999996),\n (0.46446609406726314,8.535533905932738,6.0),\n (-1.0412414523193152,-0.04124145231931431,7.0824829046386295),\n (1.9587585476806848,2.9587585476806857,10.08248290463863),\n (1,2,3),\n (4,5,6)\n ]\n\n @test decompose(Point3{Float64}, s, 8) ≈ positions\n\n faces = TriangleFace{Int}[\n (3, 2, 1),\n (4, 2, 3),\n (5, 4, 3),\n (6, 4, 5),\n (7, 6, 5),\n (8, 6, 7),\n (1, 8, 7),\n (2, 8, 1),\n\n (3, 1, 9),\n (2, 4, 10),\n (5, 3, 9),\n (4, 6, 10),\n (7, 5, 9),\n (6, 8, 10),\n (1, 7, 9),\n (8, 2, 10)\n ]\n @test faces == decompose(TriangleFace{Int}, s, 8)\n\n m = triangle_mesh(s, nvertices=8)\n\n @test GeometryBasics.faces(m) == faces\n @test GeometryBasics.coordinates(m) ≈ positions\n m = normal_mesh(s)# just test that it works without explicit resolution parameter\n @test m isa GLNormalMesh\n end\nend",
"@testset \"HyperRectangles\" begin\n a = Rect(Vec(0,0),Vec(1,1))\n pt_expa = Point{2,Int}[(0,0), (1,0), (0,1), (1,1)]\n @test decompose(Point{2,Int},a) == pt_expa\n mesh = normal_mesh(a)\n @test decompose(Point2f0, mesh) == pt_expa\n\n b = Rect(Vec(1,1,1),Vec(1,1,1))\n pt_expb = Point{3,Int}[(1,1,1),(2,1,1),(1,2,1),(2,2,1),(1,1,2),(2,1,2),(1,2,2),(2,2,2)]\n @test decompose(Point{3,Int}, b) == pt_expb\n mesh = normal_mesh(b)\nend",
"@testset \"Faces\" begin\n @test convert_simplex(GLTriangleFace, QuadFace{Int}(1,2,3,4)) == (GLTriangleFace(1,2,3), GLTriangleFace(1,3,4))\n @test convert_simplex(NFace{3, ZeroIndex{Int}}, QuadFace{ZeroIndex{Int}}(1,2,3,4)) == (NFace{3,ZeroIndex{Int}}(1,2,3), NFace{3, ZeroIndex{Int}}(1,3,4))\n @test convert_simplex(NFace{3, OffsetInteger{3, Int}}, NFace{4, OffsetInteger{2, Int}}(1,2,3,4)) == (\n NFace{3, OffsetInteger{3, Int}}(1,2,3),\n NFace{3, OffsetInteger{3, Int}}(1,3,4)\n )\n @test convert_simplex(LineFace{Int}, QuadFace{Int}(1,2,3,4)) == (\n LineFace{Int}(1,2),\n LineFace{Int}(2,3),\n LineFace{Int}(3,4),\n LineFace{Int}(4,1)\n )\nend",
"@testset \"Normals\" begin\n n64 = Vec{3, Float64}[\n (0.0,0.0,-1.0),\n (0.0,0.0,-1.0),\n (0.0,0.0,-1.0),\n (0.0,0.0,-1.0),\n (0.0,0.0,1.0),\n (0.0,0.0,1.0),\n (0.0,0.0,1.0),\n (0.0,0.0,1.0),\n (-1.0,0.0,0.0),\n (-1.0,0.0,0.0),\n (-1.0,0.0,0.0),\n (-1.0,0.0,0.0),\n (1.0,0.0,0.0),\n (1.0,0.0,0.0),\n (1.0,0.0,0.0),\n (1.0,0.0,0.0),\n (0.0,1.0,0.0),\n (0.0,1.0,0.0),\n (0.0,1.0,0.0),\n (0.0,1.0,0.0),\n (0.0,-1.0,0.0),\n (0.0,-1.0,0.0),\n (0.0,-1.0,0.0),\n (0.0,-1.0,0.0),\n ]\n n32 = map(Vec{3,Float32}, n64)\n r = triangle_mesh(centered(Rect3D))\n # @test normals(coordinates(r), GeometryBasics.faces(r)) == n32\n # @test normals(coordinates(r), GeometryBasics.faces(r)) == n64\nend",
"@testset \"HyperSphere\" begin\n sphere = Sphere{Float32}(Point3f0(0), 1f0)\n\n points = decompose(Point, sphere, 3)\n point_target = Point{3,Float32}[\n [0.0, 0.0, 1.0], [1.0, 0.0, 6.12323e-17], [1.22465e-16, 0.0, -1.0],\n [-0.0, 0.0, 1.0], [-1.0, 1.22465e-16, 6.12323e-17],\n [-1.22465e-16, 1.49976e-32, -1.0], [0.0, -0.0, 1.0],\n [1.0, -2.44929e-16, 6.12323e-17], [1.22465e-16,-2.99952e-32, -1.0]\n ]\n @test points ≈ point_target\n\n f = decompose(TriangleFace{Int}, sphere, 3)\n face_target = TriangleFace{Int}[\n [1, 2, 5], [1, 5, 4], [2, 3, 6], [2, 6, 5],\n [4, 5, 8], [4, 8, 7], [5, 6, 9], [5, 9, 8]\n ]\n @test f == face_target\n circle = Circle(Point2f0(0), 1f0)\n points = decompose(Point2f0, circle, 20)\n @test length(points) == 20\n\n mesh = triangle_mesh(circle, nvertices=32)\n @test decompose(Point2f0, mesh)[1:end] ≈ decompose(Point2f0, circle, 32)\nend",
"@testset \"Rectangles\" begin\n rect = FRect2D(0, 7, 20, 3)\n @test (rect + 4) == FRect2D(4, 11, 20, 3)\n @test (rect + Vec(2, -2)) == FRect2D(2, 5, 20, 3)\n\n @test (rect - 4) == FRect2D(-4, 3, 20, 3)\n @test (rect - Vec(2, -2)) == FRect2D(-2, 9, 20, 3)\n\n base = Vec3f0(1, 2, 3)\n wxyz = Vec3f0(-2, 4, 2)\n rect = FRect3D(base, wxyz)\n @test (rect + 4) == FRect3D(base .+ 4, wxyz)\n @test (rect + Vec(2, -2, 3)) == FRect3D(base .+ Vec(2, -2, 3), wxyz)\n\n @test (rect - 4) == FRect3D(base .- 4, wxyz)\n @test (rect - Vec(2, -2, 7)) == FRect3D(base .- Vec(2, -2, 7), wxyz)\n\n\n rect = FRect2D(0, 7, 20, 3)\n @test (rect * 4) == FRect2D(0, 7*4, 20*4, 3*4)\n @test (rect * Vec(2, -2)) == FRect2D(0, -7*2, 20*2, -3*2)\n\n base = Vec3f0(1, 2, 3)\n wxyz = Vec3f0(-2, 4, 2)\n rect = FRect3D(base, wxyz)\n @test (rect * 4) == FRect3D(base .* 4, wxyz .* 4)\n @test (rect * Vec(2, -2, 3)) == FRect3D(base .* Vec(2, -2, 3), wxyz .* Vec(2, -2, 3))\nend"
] |
f7c267ff442a8c8ba73c58df7ba33a1f9ca64cdc
| 1,817
|
jl
|
Julia
|
test/compare_nearestneighbors.jl
|
UnofficialJuliaMirror/HNSW.jl-540f64fa-c57e-11e8-081c-41422cda4629
|
bdef8e7d2d47cb36a0c75feaf71dd89caef30312
|
[
"MIT"
] | null | null | null |
test/compare_nearestneighbors.jl
|
UnofficialJuliaMirror/HNSW.jl-540f64fa-c57e-11e8-081c-41422cda4629
|
bdef8e7d2d47cb36a0c75feaf71dd89caef30312
|
[
"MIT"
] | null | null | null |
test/compare_nearestneighbors.jl
|
UnofficialJuliaMirror/HNSW.jl-540f64fa-c57e-11e8-081c-41422cda4629
|
bdef8e7d2d47cb36a0c75feaf71dd89caef30312
|
[
"MIT"
] | null | null | null |
using NearestNeighbors
using HNSW
using StaticArrays
using Statistics
using Test
@testset "Compare To NearestNeighbors.jl" begin
dim = 5
num_elements = 10000
num_queries = 1000
data = [@SVector rand(Float32, dim) for n ∈ 1:num_elements]
tree = KDTree(data)
queries = [@SVector rand(Float32, dim) for n ∈ 1:num_queries]
@testset "M=$M, K=1" for M ∈ [5, 10]
k = 1
efConstruction = 20
ef = 20
realidxs, realdists = knn(tree, queries, k)
hnsw = HierarchicalNSW(data; efConstruction=efConstruction, M=M, ef=ef)
add_to_graph!(hnsw)
idxs, dists = knn_search(hnsw, queries, k)
ratio = mean(map(idxs, realidxs) do i,j
length(i ∩ j) / k
end)
@test ratio > 0.99
end
@testset "Large K, low M=$M" for M ∈ [5,10]
efConstruction = 100
ef = 50
hnsw = HierarchicalNSW(data; efConstruction=efConstruction, M=M, ef=ef)
add_to_graph!(hnsw)
@testset "K=$K" for K ∈ [10,20]
realidxs, realdists = knn(tree, queries, K)
idxs, dists = knn_search(hnsw, queries, K)
ratio = mean(map(idxs, realidxs) do i,j
length(i ∩ j) / K
end)
@test ratio > 0.9
end
end
@testset "Low Recall Test" begin
k = 1
efConstruction = 20
M = 5
hnsw = HierarchicalNSW(data; efConstruction=efConstruction, M=M)
add_to_graph!(hnsw)
set_ef!(hnsw, 2)
realidxs, realdists = knn(tree, queries, k)
idxs, dists = knn_search(hnsw, queries, k)
recall = mean(map(idxs, realidxs) do i,j
length(i ∩ j) / k
end)
@test recall > 0.6
end
end
| 30.283333
| 79
| 0.539351
|
[
"@testset \"Compare To NearestNeighbors.jl\" begin\n dim = 5\n num_elements = 10000\n num_queries = 1000\n data = [@SVector rand(Float32, dim) for n ∈ 1:num_elements]\n tree = KDTree(data)\n queries = [@SVector rand(Float32, dim) for n ∈ 1:num_queries]\n @testset \"M=$M, K=1\" for M ∈ [5, 10]\n k = 1\n efConstruction = 20\n ef = 20\n realidxs, realdists = knn(tree, queries, k)\n\n hnsw = HierarchicalNSW(data; efConstruction=efConstruction, M=M, ef=ef)\n add_to_graph!(hnsw)\n idxs, dists = knn_search(hnsw, queries, k)\n\n ratio = mean(map(idxs, realidxs) do i,j\n length(i ∩ j) / k\n end)\n @test ratio > 0.99\n end\n\n @testset \"Large K, low M=$M\" for M ∈ [5,10]\n efConstruction = 100\n ef = 50\n hnsw = HierarchicalNSW(data; efConstruction=efConstruction, M=M, ef=ef)\n add_to_graph!(hnsw)\n @testset \"K=$K\" for K ∈ [10,20]\n realidxs, realdists = knn(tree, queries, K)\n idxs, dists = knn_search(hnsw, queries, K)\n ratio = mean(map(idxs, realidxs) do i,j\n length(i ∩ j) / K\n end)\n @test ratio > 0.9\n end\n end\n @testset \"Low Recall Test\" begin\n k = 1\n efConstruction = 20\n M = 5\n hnsw = HierarchicalNSW(data; efConstruction=efConstruction, M=M)\n add_to_graph!(hnsw)\n set_ef!(hnsw, 2)\n realidxs, realdists = knn(tree, queries, k)\n idxs, dists = knn_search(hnsw, queries, k)\n\n recall = mean(map(idxs, realidxs) do i,j\n length(i ∩ j) / k\n end)\n @test recall > 0.6\n end\nend"
] |
f7cd37586fcfb537c3930fb632fb894a7b745bed
| 23,279
|
jl
|
Julia
|
test/filterfit.jl
|
NicholasWMRitchie/NeXLSpectrum
|
e40990f68850fc2e732d0c6e13acdfbfbf5b1a31
|
[
"Unlicense"
] | null | null | null |
test/filterfit.jl
|
NicholasWMRitchie/NeXLSpectrum
|
e40990f68850fc2e732d0c6e13acdfbfbf5b1a31
|
[
"Unlicense"
] | null | null | null |
test/filterfit.jl
|
NicholasWMRitchie/NeXLSpectrum
|
e40990f68850fc2e732d0c6e13acdfbfbf5b1a31
|
[
"Unlicense"
] | null | null | null |
using Test
using NeXLSpectrum
using Statistics
using LinearAlgebra
using DataFrames
@testset "Filter Fitting" begin
@testset "Filter" begin
eds = simpleEDS(2048, 10.0, 0.0, 135.0)
filt = buildfilter(eds)
# Each row sums to zero
@test all(
isapprox(sum(NeXLSpectrum.filterdata(filt, row)), 0.0, atol = 1.0e-8) for
row in size(filt)[1]
)
# Symmetric about the center line
@test all(
isapprox(
sum(NeXLSpectrum.filterdata(filt, r)[1:r-1]),
sum(NeXLSpectrum.filterdata(filt, r)[r+1:end]),
atol = 1.0e-8,
) for r = 2:(size(filt)[1]-1)
)
# Positive in the center
@test all(NeXLSpectrum.filterdata(filt, r)[r] ≥ 0.0 for r = 1:size(filt)[1])
# Symmetric one row off
@test all(
NeXLSpectrum.filterdata(filt, r)[r-1] == NeXLSpectrum.filterdata(filt, r)[r+1]
for r = 2:(size(filt)[1]-1)
)
# Check the old and new ways are equivalent
@test NeXLSpectrum.filterdata(filt, 1:size(filt)[1]) == NeXLSpectrum.filterdata(filt)
end
@testset "LLSQ_K412_1" begin
path = joinpath(@__DIR__, "K412 spectra")
unks = loadspectrum.(joinpath(path, "III-E K412[$i][4].msa") for i = 0:4)
al2o3 = loadspectrum(joinpath(path, "Al2O3 std.msa"))
caf2 = loadspectrum(joinpath(path, "CaF2 std.msa"))
fe = loadspectrum(joinpath(path, "Fe std.msa"))
mgo = loadspectrum(joinpath(path, "MgO std.msa"))
sio2 = loadspectrum(joinpath(path, "SiO2 std.msa"))
det = simpleEDS(4096, 10.0, 0.0, 132.0)
ff = buildfilter(det)
ok = tophatfilter(
CharXRayLabel(sio2, 34:66, characteristic(n"O", ktransitions)),
ff,
1.0 / dose(sio2),
)
mgk = tophatfilter(
CharXRayLabel(mgo, 110:142, characteristic(n"Mg", ktransitions)),
ff,
1.0 / dose(mgo),
)
alk = tophatfilter(
CharXRayLabel(al2o3, 135:170, characteristic(n"Al", ktransitions)),
ff,
1.0 / dose(al2o3),
)
sik = tophatfilter(
CharXRayLabel(sio2, 159:196, characteristic(n"Si", ktransitions)),
ff,
1.0 / dose(sio2),
)
cak = tophatfilter(
CharXRayLabel(caf2, 345:422, characteristic(n"Ca", ktransitions)),
ff,
1.0 / dose(caf2),
)
fel = tophatfilter(
CharXRayLabel(fe, 51:87, characteristic(n"Fe", ltransitions)),
ff,
1.0 / dose(fe),
)
feka = tophatfilter(
CharXRayLabel(fe, 615:666, characteristic(n"Fe", kalpha)),
ff,
1.0 / dose(fe),
)
fekb = tophatfilter(
CharXRayLabel(fe, 677:735, characteristic(n"Fe", kbeta)),
ff,
1.0 / dose(fe),
)
fds = [ok, mgk, alk, sik, cak, fel, feka, fekb]
unk = tophatfilter(unks[1], ff, 1.0 / dose(unks[1]))
#println("Performing the weighted fit takes:")
ff = filterfit(unk, fds)
#@btime filterfit(unk, fds)
#println("Performing the full generalized fit takes:")
#@btime filterfit(unk, fds, fitcontiguousp)
#@btime filterfit(unk, fds, fitcontiguousw)
## The comparison is against the k-ratios from DTSA-II.
# The results won't be identical because the filters and other assumptions are different.
@test isapprox(NeXLUncertainties.value(ff, ok.label), 0.6529, atol = 0.0016)
@test isapprox(NeXLUncertainties.value(ff, fekb.label), 0.0665, atol = 0.0002)
@test isapprox(NeXLUncertainties.value(ff, mgk.label), 0.1473, atol = 0.0004)
@test isapprox(NeXLUncertainties.value(ff, alk.label), 0.0668, atol = 0.0005)
@test isapprox(NeXLUncertainties.value(ff, sik.label), 0.3506, atol = 0.0008)
@test isapprox(NeXLUncertainties.value(ff, cak.label), 0.1921, atol = 0.0001)
@test isapprox(NeXLUncertainties.value(ff, fel.label), 0.0418, atol = 0.0002)
@test isapprox(NeXLUncertainties.value(ff, feka.label), 0.0669, atol = 0.0001)
@test isapprox(σ(ff, ok.label), 0.00081, atol = 0.0001)
@test isapprox(σ(ff, mgk.label), 0.00018, atol = 0.00005)
@test isapprox(σ(ff, alk.label), 0.00012, atol = 0.00005)
@test isapprox(σ(ff, sik.label), 0.00024, atol = 0.00005)
@test isapprox(σ(ff, cak.label), 0.00022, atol = 0.00005)
@test isapprox(σ(ff, fel.label), 0.00043, atol = 0.00006)
@test isapprox(σ(ff, feka.label), 0.00019, atol = 0.00005)
@test isapprox(σ(ff, fekb.label), 0.00078, atol = 0.0002)
end
@testset "LLSQ_K412_2" begin
path = joinpath(@__DIR__, "K412 spectra")
unks = loadspectrum.(joinpath(path, "III-E K412[$i][4].msa") for i = 0:4)
al2o3 = loadspectrum(joinpath(path, "Al2O3 std.msa"))
caf2 = loadspectrum(joinpath(path, "CaF2 std.msa"))
fe = loadspectrum(joinpath(path, "Fe std.msa"))
mgo = loadspectrum(joinpath(path, "MgO std.msa"))
sio2 = loadspectrum(joinpath(path, "SiO2 std.msa"))
det = BasicEDS(
4096,
0.0,
10.0,
132.0,
10,
Dict(
Shell(1) => n"Be",
Shell(2) => n"Sc",
Shell(3) => n"Cs",
Shell(4) => n"Pu",
),
)
ff = buildfilter(det)
e0 = sameproperty(unks, :BeamEnergy)
ampl = 0.00005
oroi = charXRayLabels(sio2, n"O", Set( ( n"Si", n"O" ) ), det, e0, ampl = ampl)
siroi = charXRayLabels(sio2, n"Si", Set( (n"Si", n"O") ), det, e0, ampl = ampl)
mgroi = charXRayLabels(mgo, n"Mg", Set( (n"Mg", n"O") ), det, e0, ampl = ampl)
alroi = charXRayLabels(al2o3, n"Al", Set( (n"Al", n"O") ), det, e0, ampl = ampl)
caroi = charXRayLabels(caf2, n"Ca", Set( (n"Ca", n"F") ), det, e0, ampl = ampl)
@test length(caroi) == 1
feroi = charXRayLabels(fe, n"Fe", Set( (n"Fe", ) ), det, e0, ampl = ampl)
@test length(feroi) == 3
ok = tophatfilter(oroi, ff, 1.0 / dose(sio2))
mgk = tophatfilter(mgroi, ff, 1.0 / dose(mgo))
alk = tophatfilter(alroi, ff, 1.0 / dose(al2o3))
sik = tophatfilter(siroi, ff, 1.0 / dose(sio2))
cak = tophatfilter(caroi, ff, 1.0 / dose(caf2))
fekl = tophatfilter(feroi, ff, 1.0 / dose(fe))
fds = collect(Iterators.flatten((ok, mgk, alk, sik, cak, fekl)))
unk = tophatfilter(unks[1], ff, 1.0 / dose(unks[1]))
ff = filterfit(unk, fds)
#println("Performing the full generalized fit takes:")
#@btime filterfit(unk, fds)
#println("Performing the weighted fit takes:")
#@btime filterfit(unk, fds, fitcontiguousw)
@test isapprox(NeXLUncertainties.value(ff, oroi[1]), 0.6624, atol = 0.0001)
@test isapprox(NeXLUncertainties.value(ff, mgroi[1]), 0.14728, atol = 0.0007)
@test isapprox(NeXLUncertainties.value(ff, alroi[1]), 0.06679, atol = 0.0006)
@test isapprox(NeXLUncertainties.value(ff, siroi[1]), 0.35063, atol = 0.0009)
@test isapprox(NeXLUncertainties.value(ff, caroi[1]), 0.19213, atol = 0.0003)
@test isapprox(NeXLUncertainties.value(ff, feroi[1]), 0.04185, atol = 0.0004)
@test isapprox(NeXLUncertainties.value(ff, feroi[2]), 0.06693, atol = 0.0001)
@test isapprox(NeXLUncertainties.value(ff, feroi[3]), 0.06652, atol = 0.0007)
@test isapprox(σ(ff, oroi[1]), 0.00082, atol = 0.0001)
@test isapprox(σ(ff, mgroi[1]), 0.00018, atol = 0.00004)
@test isapprox(σ(ff, alroi[1]), 0.00016, atol = 0.00003)
@test isapprox(σ(ff, siroi[1]), 0.00029, atol = 0.00003)
@test isapprox(σ(ff, caroi[1]), 0.00023, atol = 0.00001)
@test isapprox(σ(ff, feroi[1]), 0.00044, atol = 0.0001)
@test isapprox(σ(ff, feroi[2]), 0.00016, atol = 0.00001)
@test isapprox(σ(ff, feroi[3]), 0.00078, atol = 0.0002)
# Compare to naive peak integration
fekkr = kratio(unks[1], fe, 593:613, 636:647, 669:690)
@test isapprox(
NeXLUncertainties.value(ff, feroi[2]),
NeXLUncertainties.value(fekkr),
atol = 0.0005,
)
@test isapprox(σ(ff, feroi[2]), σ(fekkr), atol = 0.00004)
cakkr = kratio(unks[1], caf2, 334:347, 365:375, 422:439)
@test isapprox(
NeXLUncertainties.value(ff, caroi[1]),
NeXLUncertainties.value(cakkr),
atol = 0.0008,
)
@test isapprox(σ(ff, caroi[1]), σ(cakkr), atol = 0.00007)
end
@testset "ADM6005a" begin
path = joinpath(@__DIR__, "ADM6005a spectra")
unks = loadspectrum.(joinpath(path, "ADM-6005a_$(i).msa") for i = 1:15)
al = loadspectrum(joinpath(path, "Al std.msa"))
caf2 = loadspectrum(joinpath(path, "CaF2 std.msa"))
fe = loadspectrum(joinpath(path, "Fe std.msa"))
ge = loadspectrum(joinpath(path, "Ge std.msa"))
si = loadspectrum(joinpath(path, "Si std.msa"))
sio2 = loadspectrum(joinpath(path, "SiO2 std.msa"))
ti = loadspectrum(joinpath(path, "Ti trimmed.msa"))
zn = loadspectrum(joinpath(path, "Zn std.msa"))
det = matching(
unks[1],
128.0,
110,
Dict(
Shell(1) => n"Be",
Shell(2) => n"Sc",
Shell(3) => n"Cs",
Shell(4) => n"Pu",
),
)
ff = buildfilter(det)
ampl = 1e-4
e0 = sameproperty(unks, :BeamEnergy)
alroi = charXRayLabels(al, n"Al", Set( ( n"Al", )), det, e0, ampl = ampl)
caroi = charXRayLabels(caf2, n"Ca", [ n"Ca", n"F" ], det, e0, ampl = ampl)
feroi = charXRayLabels(fe, n"Fe", Set( ( n"Fe", )), det, e0, ampl = ampl)
geroi = charXRayLabels(ge, n"Ge", Set( ( n"Ge", )), det, e0, ampl = ampl)
oroi = charXRayLabels(sio2, n"O", Set( ( n"Si", n"O", )), det, e0, ampl = ampl)
siroi = charXRayLabels(si, n"Si", Set( ( n"Si", )), det, e0, ampl = ampl)
tiroi = charXRayLabels(ti, n"Ti", Set( ( n"Ti", )), det, e0, ampl = ampl)
znroi = charXRayLabels(zn, n"Zn", [ n"Zn" ], det, e0, ampl = ampl)
alk = tophatfilter(alroi, ff, 1.0 / dose(al))
cak = tophatfilter(caroi, ff, 1.0 / dose(caf2))
felk = tophatfilter(feroi, ff, 1.0 / dose(fe))
gelk = tophatfilter(geroi, ff, 1.0 / dose(ge))
ok = tophatfilter(oroi, ff, 1.0 / dose(sio2))
sik = tophatfilter(siroi, ff, 1.0 / dose(si))
tilk = tophatfilter(tiroi, ff, 1.0 / dose(ti))
znlk = tophatfilter(znroi, ff, 1.0 / dose(zn))
fds = collect(Iterators.flatten((alk, cak, felk, gelk, ok, sik, tilk, znlk)))
res = FilterFitResult[]
for i = 1:15
unk = tophatfilter(unks[i], ff, 1.0 / dose(unks[i]))
push!(res, filterfit(unk, fds))
end
# Compare against DTSA-II values
@test isapprox(mean(values(res, oroi[1])), 0.4923, rtol = 0.003)
@test isapprox(mean(values(res, siroi[1])), 0.0214, atol = 0.013)
@test isapprox(mean(values(res, alroi[1])), 0.0281, atol = 0.001)
@test isapprox(mean(values(res, caroi[1])), 0.1211, rtol = 0.0025)
@test isapprox(mean(values(res, znroi[1])), 0.0700, rtol = 0.05)
@test isapprox(mean(values(res, znroi[2])), 0.1115, atol = 0.0005)
@test isapprox(mean(values(res, znroi[3])), 0.1231, rtol = 0.01)
@test isapprox(mean(values(res, tiroi[1])), 0.0404, atol = 0.001)
@test isapprox(mean(values(res, tiroi[2])), 0.064, rtol = 0.0002)
@test isapprox(mean(values(res, tiroi[3])), 0.064, rtol = 0.06)
@test isapprox(mean(values(res, feroi[1])), 0.0, atol = 0.001)
@test isapprox(mean(values(res, feroi[2])), 0.0, atol = 0.0004)
@test isapprox(mean(values(res, feroi[3])), 0.0, atol = 0.001)
@test isapprox(mean(values(res, geroi[1])), 0.1789, rtol = 0.01)
@test isapprox(mean(values(res, geroi[2])), 0.2628, atol = 0.001)
@test isapprox(mean(values(res, geroi[3])), 0.279, atol = 0.011)
end
@testset "ADM6005a - Refs" begin
path = joinpath(@__DIR__, "ADM6005a spectra")
unks = loadspectrum.(joinpath(path, "ADM-6005a_$(i).msa") for i = 1:15)
det = matching(
unks[1],
128.0,
110,
Dict(
Shell(1) => n"Be",
Shell(2) => n"Sc",
Shell(3) => n"Cs",
Shell(4) => n"Pu",
),
)
ffp = references(
[
reference(n"Al", joinpath(path, "Al std.msa"), mat"Al"),
reference(n"Ca", joinpath(path, "CaF2 std.msa"), mat"CaF2"),
reference(n"Fe", joinpath(path, "Fe std.msa"), mat"Fe"),
reference(n"Ge", joinpath(path, "Ge std.msa"), mat"Ge"),
reference(n"Si", joinpath(path, "Si std.msa"), mat"Si"),
reference(n"O", joinpath(path, "SiO2 std.msa"), mat"SiO2"),
reference(n"Ti", joinpath(path, "Ti trimmed.msa"), mat"Ti"),
reference(n"Zn", joinpath(path, "Zn std.msa"), mat"Zn"),
],
det,
)
res = fit_spectrum(unks, ffp)
@test isapprox(
mean(values(res, findlabel(res[1], n"Al K-L3"))),
0.0279,
atol = 0.0001,
)
@test isapprox(
mean(values(res, findlabel(res[1], n"Ti K-L3"))),
0.0641,
atol = 0.0001,
)
@test isapprox(
mean(values(res, findlabel(res[1], n"Ge K-M3"))),
0.2734,
atol = 0.0001,
)
@test isapprox(
mean(values(res, findlabel(res[1], n"Zn K-M3"))),
0.1209,
atol = 0.0001,
)
@test isapprox(
mean(values(res, findlabel(res[1], n"Fe L3-M5"))),
0.00033,
atol = 0.00001,
)
@test isapprox(
mean(values(res, findlabel(res[1], n"Fe K-L3"))),
0.0003026,
atol = 0.00001,
)
end
# Check that the covariance of the filtered spectrum is calculated correctly as F*diagm(S)*transpose(F)
@testset "Filtered covariance" begin
spec = loadspectrum(joinpath(@__DIR__, "ADM6005a spectra", "ADM-6005a_1.msa"))
det = matching(
spec,
128.0,
110,
Dict(
Shell(1) => n"Be",
Shell(2) => n"Sc",
Shell(3) => n"Cs",
Shell(4) => n"Pu",
),
)
filt = buildfilter(VariableWidthFilter, det)
specdata = counts(spec)
cov1 = [
NeXLSpectrum.filteredcovar(filt, specdata, r, c) for
r in eachindex(specdata), c in eachindex(specdata)
]
filtd = NeXLSpectrum.filterdata(filt)
cov2 = filtd * diagm(specdata) * transpose(filtd)
# @show findmax(ii->abs(cov1[ii]-cov2[ii]), eachindex(cov1))
@test all(
isapprox(cov1[ii], cov2[ii], rtol = 1.0e-6, atol = 1.0e-12) for
ii in eachindex(cov1)
)
end
@testset "Repeated refs" begin
path = joinpath(@__DIR__, "K412 spectra")
fe = mat"Fe"
efs = references(
[
reference(n"Ca", joinpath(path,"III-E K412[0][4].msa"), srm470_k412),
reference(n"Fe", joinpath(path,"III-E K412[0][4].msa"), srm470_k412),
reference(n"O", joinpath(path, "SiO2 std.msa"), mat"SiO2"),
reference(n"Al", joinpath(path, "Al2O3 std.msa"), mat"Al2O3"),
reference(n"Ca", joinpath(path, "CaF2 std.msa"), mat"CaF2"),
reference(n"Fe", joinpath(path, "Fe std.msa"), fe),
reference(n"Mg", joinpath(path, "MgO std.msa"), mat"MgO"),
reference(n"Si", joinpath(path, "SiO2 std.msa"), mat"SiO2"),
],
132.0,
)
@test properties(efs.references[findfirst(r->n"Fe K-L3" in r.label.xrays, efs.references)].label)[:Composition] === srm470_k412
@test properties(efs.references[findfirst(r->n"Fe K-M3" in r.label.xrays, efs.references)].label)[:Composition] === srm470_k412
@test properties(efs.references[findfirst(r->n"Fe L3-M5" in r.label.xrays, efs.references)].label)[:Composition] === fe
@test properties(efs.references[findfirst(r->n"Ca K-L3" in r.label.xrays, efs.references)].label)[:Composition] === srm470_k412
end
@testset "Warnings" begin
s = loadspectrum(joinpath(@__DIR__, "Other", "K411 simulated.msa"))
@test_logs ( :warn, "The spectrum \"Noisy[MC simulation of bulk K411] #1\" cannot be used as a reference for the ROI \"O K-L3 + 1 other\" due to 2 peak interferences.")
charXRayLabels(s, n"O", Set( ( n"C", n"O",n"Mg",n"Si",n"Ca",n"Fe")), simpleEDS(2048,10.0,0.0,132.0), 1.0e6, ampl=1.0e-5)
@test_logs ( :warn, "The spectrum \"Noisy[MC simulation of bulk K411] #1\" cannot be used as a reference for the ROI \"Fe L3-M5 + 11 others\" due to 1 peak interference.")
charXRayLabels(s, n"Fe", Set( ( n"C", n"O",n"Mg",n"Si",n"Ca",n"Fe")), simpleEDS(2048,10.0,0.0,132.0), 1.0e6, ampl=1.0e-5)
end
@testset "Example 2" begin
path = joinpath(@__DIR__, "Example 2")
refs = references( [
reference( [ n"Mg", n"Si", n"Ca", n"Fe" ], joinpath(path, "K411 std.msa"), srm470_k411)...,
reference( n"O", joinpath(path,"MgO std.msa"), mat"MgO" ),
reference( n"Fe", joinpath(path,"Fe std.msa"), mat"Fe" ),
reference( n"Al", joinpath(path,"Al std.msa"), mat"Al" )
], 135.0)
unk = loadspectrum(joinpath(path, "K412 unk.msa"))
fr = fit_spectrum(unk, refs)
qr = quantify(fr)
@test isapprox(value(qr.comp[n"Al"]), 0.05099, atol=0.0001)
@test isapprox(value(qr.comp[n"Fe"]), 0.0783, atol=0.0001)
@test isapprox(value(qr.comp[n"Mg"]), 0.1183, atol=0.0001)
@test isapprox(value(qr.comp[n"O"]), 0.44715, atol=0.0001)
df = asa(DataFrame, [ fr, fr ], charOnly = false, withUnc = true, format = :normal)
@test startswith(repr(df[1,:Spectra]),"\"K412-0[Mon Oct 17 16:11:17 2011]")
@test ncol(df)==17
@test nrow(df)==2
@test isapprox(df[2,2],0.715218,atol=0.0001)
@test isapprox(df[2,3],0.001413,atol=0.0001)
df = asa(DataFrame, [ fr, ], charOnly = false, withUnc = true, format = :pivot)
@test ncol(df)==3 && nrow(df)==8
@test repr(df[1,:ROI])=="k[O K-L3 + 1 other, MgO]"
@test isapprox(df[2,2], 0.0511086, atol=0.00001)
@test isapprox(df[3,3], 0.00323159, atol=0.00001)
df = asa(DataFrame, [ fr, fr ], charOnly = false, withUnc = true, format = :long)
@test ncol(df)==4 && nrow(df)==16
@test df[2,:ROI]=="k[Fe L3-M5 + 13 others, Fe]"
@test isapprox(df[3,3], 1.38384, atol=0.00001)
@test isapprox(df[3,4], 0.00323159, atol=0.00001)
df = asa(DataFrame, fr, charOnly = false, material = srm470_k412, columns = ( :roi, :peakback, :counts, :dose))
@test all(r->startswith(repr(r[:Spectrum]),"K412-0[Mon Oct 17 16:11:17 2011]"), eachrow(df))
@test all(r->r[:LiveTime]==60.0,eachrow(df))
@test all(r->r[:ProbeCurrent]==1.1978,eachrow(df))
@test all(r->isapprox(r[:DeadPct],14.2529,atol=0.0001),eachrow(df))
@test df[1,:Start]==131
@test df[1,:Stop]==168
@test isapprox(df[1,:K], 0.0331066, atol=0.00001)
@test isapprox(df[1,:dK], 0.0001588, atol=0.00001)
@test isapprox(df[1,:Peak], 1.05241e5, atol=10.0)
@test isapprox(df[1,:Back], 1.02961e5, atol=10.0)
@test isapprox(df[1,:PtoB], 74.9106, atol=0.001)
@test isapprox(df[1,:KCalc], 0.032146, atol=0.00001)
@test isapprox(df[1,:KoKcalc], 1.02988, atol=0.00002)
@test isapprox(df[1,:RefCountsPernAs], 44231.6, atol=0.1)
@test isapprox(df[1,:CountsPernAs], 1464.36, atol=0.1)
end
@testset "Example 2 - 32-bit" begin
path = joinpath(@__DIR__, "Example 2")
refs = references( [
reference( [ n"Mg", n"Si", n"Ca", n"Fe" ], joinpath(path, "K411 std.msa"), srm470_k411)...,
reference( n"O", joinpath(path,"MgO std.msa"), mat"MgO" ),
reference( n"Fe", joinpath(path,"Fe std.msa"), mat"Fe" ),
reference( n"Al", joinpath(path,"Al std.msa"), mat"Al" )
], 135.0, ftype=Float32) # This line is the only difference with "Example 2"
unk = loadspectrum(joinpath(path, "K412 unk.msa"))
fr = fit_spectrum(unk, refs)
qr = quantify(fr)
@test isapprox(value(qr.comp[n"Al"]), 0.05099, atol=0.0001)
@test isapprox(value(qr.comp[n"Fe"]), 0.0783, atol=0.0001)
@test isapprox(value(qr.comp[n"Mg"]), 0.1183, atol=0.0001)
@test isapprox(value(qr.comp[n"O"]), 0.44715, atol=0.0001)
df = asa(DataFrame, [ fr, fr ], charOnly = false, withUnc = true, format = :normal)
@test startswith(repr(df[1,:Spectra]),"\"K412-0[Mon Oct 17 16:11:17 2011]")
@test ncol(df)==17
@test nrow(df)==2
@test isapprox(df[2,2],0.715218,atol=0.0001)
@test isapprox(df[2,3],0.001413,atol=0.0001)
df = asa(DataFrame, [ fr, ], charOnly = false, withUnc = true, format = :pivot)
@test ncol(df)==3 && nrow(df)==8
@test repr(df[1,:ROI])=="k[O K-L3 + 1 other, MgO]"
@test isapprox(df[2,2], 0.0511086, atol=0.00001)
@test isapprox(df[3,3], 0.00323159, atol=0.00001)
df = asa(DataFrame, [ fr, fr ], charOnly = false, withUnc = true, format = :long)
@test ncol(df)==4 && nrow(df)==16
@test df[2,:ROI]=="k[Fe L3-M5 + 13 others, Fe]"
@test isapprox(df[3,3], 1.38384, atol=0.00001)
@test isapprox(df[3,4], 0.00323159, atol=0.00001)
df = asa(DataFrame, fr, charOnly = false, material = srm470_k412, columns = ( :roi, :peakback, :counts, :dose))
@test all(r->startswith(repr(r[:Spectrum]),"K412-0[Mon Oct 17 16:11:17 2011]"), eachrow(df))
@test all(r->r[:LiveTime]==60.0,eachrow(df))
@test all(r->r[:ProbeCurrent]==1.1978,eachrow(df))
@test all(r->isapprox(r[:DeadPct],14.2529,atol=0.0001),eachrow(df))
@test df[1,:Start]==131
@test df[1,:Stop]==168
@test isapprox(df[1,:K], 0.0331066, atol=0.00001)
@test isapprox(df[1,:dK], 0.0001588, atol=0.00001)
@test isapprox(df[1,:Peak], 1.05241e5, atol=10.0)
@test isapprox(df[1,:Back], 1.02961e5, atol=10.0)
@test isapprox(df[1,:PtoB], 74.9106, atol=0.001)
@test isapprox(df[1,:KCalc], 0.032146, atol=0.00001)
@test isapprox(df[1,:KoKcalc], 1.02988, atol=0.00002)
@test isapprox(df[1,:RefCountsPernAs], 44231.6, atol=0.1)
@test isapprox(df[1,:CountsPernAs], 1464.36, atol=0.1)
end
end
| 46.280318
| 180
| 0.549594
|
[
"@testset \"Filter Fitting\" begin\n @testset \"Filter\" begin\n eds = simpleEDS(2048, 10.0, 0.0, 135.0)\n filt = buildfilter(eds)\n # Each row sums to zero\n @test all(\n isapprox(sum(NeXLSpectrum.filterdata(filt, row)), 0.0, atol = 1.0e-8) for\n row in size(filt)[1]\n )\n # Symmetric about the center line\n @test all(\n isapprox(\n sum(NeXLSpectrum.filterdata(filt, r)[1:r-1]),\n sum(NeXLSpectrum.filterdata(filt, r)[r+1:end]),\n atol = 1.0e-8,\n ) for r = 2:(size(filt)[1]-1)\n )\n # Positive in the center\n @test all(NeXLSpectrum.filterdata(filt, r)[r] ≥ 0.0 for r = 1:size(filt)[1])\n # Symmetric one row off\n @test all(\n NeXLSpectrum.filterdata(filt, r)[r-1] == NeXLSpectrum.filterdata(filt, r)[r+1]\n for r = 2:(size(filt)[1]-1)\n )\n # Check the old and new ways are equivalent\n @test NeXLSpectrum.filterdata(filt, 1:size(filt)[1]) == NeXLSpectrum.filterdata(filt)\n end\n\n @testset \"LLSQ_K412_1\" begin\n path = joinpath(@__DIR__, \"K412 spectra\")\n unks = loadspectrum.(joinpath(path, \"III-E K412[$i][4].msa\") for i = 0:4)\n al2o3 = loadspectrum(joinpath(path, \"Al2O3 std.msa\"))\n caf2 = loadspectrum(joinpath(path, \"CaF2 std.msa\"))\n fe = loadspectrum(joinpath(path, \"Fe std.msa\"))\n mgo = loadspectrum(joinpath(path, \"MgO std.msa\"))\n sio2 = loadspectrum(joinpath(path, \"SiO2 std.msa\"))\n\n det = simpleEDS(4096, 10.0, 0.0, 132.0)\n ff = buildfilter(det)\n\n ok = tophatfilter(\n CharXRayLabel(sio2, 34:66, characteristic(n\"O\", ktransitions)),\n ff,\n 1.0 / dose(sio2),\n )\n mgk = tophatfilter(\n CharXRayLabel(mgo, 110:142, characteristic(n\"Mg\", ktransitions)),\n ff,\n 1.0 / dose(mgo),\n )\n alk = tophatfilter(\n CharXRayLabel(al2o3, 135:170, characteristic(n\"Al\", ktransitions)),\n ff,\n 1.0 / dose(al2o3),\n )\n sik = tophatfilter(\n CharXRayLabel(sio2, 159:196, characteristic(n\"Si\", ktransitions)),\n ff,\n 1.0 / dose(sio2),\n )\n cak = tophatfilter(\n CharXRayLabel(caf2, 345:422, characteristic(n\"Ca\", ktransitions)),\n ff,\n 1.0 / dose(caf2),\n )\n fel = tophatfilter(\n CharXRayLabel(fe, 51:87, characteristic(n\"Fe\", ltransitions)),\n ff,\n 1.0 / dose(fe),\n )\n feka = tophatfilter(\n CharXRayLabel(fe, 615:666, characteristic(n\"Fe\", kalpha)),\n ff,\n 1.0 / dose(fe),\n )\n fekb = tophatfilter(\n CharXRayLabel(fe, 677:735, characteristic(n\"Fe\", kbeta)),\n ff,\n 1.0 / dose(fe),\n )\n\n fds = [ok, mgk, alk, sik, cak, fel, feka, fekb]\n\n unk = tophatfilter(unks[1], ff, 1.0 / dose(unks[1]))\n\n #println(\"Performing the weighted fit takes:\")\n ff = filterfit(unk, fds)\n #@btime filterfit(unk, fds)\n #println(\"Performing the full generalized fit takes:\")\n #@btime filterfit(unk, fds, fitcontiguousp)\n #@btime filterfit(unk, fds, fitcontiguousw)\n\n ## The comparison is against the k-ratios from DTSA-II.\n # The results won't be identical because the filters and other assumptions are different.\n @test isapprox(NeXLUncertainties.value(ff, ok.label), 0.6529, atol = 0.0016)\n @test isapprox(NeXLUncertainties.value(ff, fekb.label), 0.0665, atol = 0.0002)\n @test isapprox(NeXLUncertainties.value(ff, mgk.label), 0.1473, atol = 0.0004)\n @test isapprox(NeXLUncertainties.value(ff, alk.label), 0.0668, atol = 0.0005)\n @test isapprox(NeXLUncertainties.value(ff, sik.label), 0.3506, atol = 0.0008)\n @test isapprox(NeXLUncertainties.value(ff, cak.label), 0.1921, atol = 0.0001)\n @test isapprox(NeXLUncertainties.value(ff, fel.label), 0.0418, atol = 0.0002)\n @test isapprox(NeXLUncertainties.value(ff, feka.label), 0.0669, atol = 0.0001)\n\n @test isapprox(σ(ff, ok.label), 0.00081, atol = 0.0001)\n @test isapprox(σ(ff, mgk.label), 0.00018, atol = 0.00005)\n @test isapprox(σ(ff, alk.label), 0.00012, atol = 0.00005)\n @test isapprox(σ(ff, sik.label), 0.00024, atol = 0.00005)\n @test isapprox(σ(ff, cak.label), 0.00022, atol = 0.00005)\n @test isapprox(σ(ff, fel.label), 0.00043, atol = 0.00006)\n @test isapprox(σ(ff, feka.label), 0.00019, atol = 0.00005)\n @test isapprox(σ(ff, fekb.label), 0.00078, atol = 0.0002)\n end\n\n @testset \"LLSQ_K412_2\" begin\n path = joinpath(@__DIR__, \"K412 spectra\")\n unks = loadspectrum.(joinpath(path, \"III-E K412[$i][4].msa\") for i = 0:4)\n al2o3 = loadspectrum(joinpath(path, \"Al2O3 std.msa\"))\n caf2 = loadspectrum(joinpath(path, \"CaF2 std.msa\"))\n fe = loadspectrum(joinpath(path, \"Fe std.msa\"))\n mgo = loadspectrum(joinpath(path, \"MgO std.msa\"))\n sio2 = loadspectrum(joinpath(path, \"SiO2 std.msa\"))\n\n det = BasicEDS(\n 4096,\n 0.0,\n 10.0,\n 132.0,\n 10,\n Dict(\n Shell(1) => n\"Be\",\n Shell(2) => n\"Sc\",\n Shell(3) => n\"Cs\",\n Shell(4) => n\"Pu\",\n ),\n )\n ff = buildfilter(det)\n e0 = sameproperty(unks, :BeamEnergy)\n\n ampl = 0.00005\n oroi = charXRayLabels(sio2, n\"O\", Set( ( n\"Si\", n\"O\" ) ), det, e0, ampl = ampl)\n siroi = charXRayLabels(sio2, n\"Si\", Set( (n\"Si\", n\"O\") ), det, e0, ampl = ampl)\n mgroi = charXRayLabels(mgo, n\"Mg\", Set( (n\"Mg\", n\"O\") ), det, e0, ampl = ampl)\n alroi = charXRayLabels(al2o3, n\"Al\", Set( (n\"Al\", n\"O\") ), det, e0, ampl = ampl)\n caroi = charXRayLabels(caf2, n\"Ca\", Set( (n\"Ca\", n\"F\") ), det, e0, ampl = ampl)\n @test length(caroi) == 1\n feroi = charXRayLabels(fe, n\"Fe\", Set( (n\"Fe\", ) ), det, e0, ampl = ampl)\n @test length(feroi) == 3\n\n ok = tophatfilter(oroi, ff, 1.0 / dose(sio2))\n mgk = tophatfilter(mgroi, ff, 1.0 / dose(mgo))\n alk = tophatfilter(alroi, ff, 1.0 / dose(al2o3))\n sik = tophatfilter(siroi, ff, 1.0 / dose(sio2))\n cak = tophatfilter(caroi, ff, 1.0 / dose(caf2))\n fekl = tophatfilter(feroi, ff, 1.0 / dose(fe))\n\n fds = collect(Iterators.flatten((ok, mgk, alk, sik, cak, fekl)))\n\n unk = tophatfilter(unks[1], ff, 1.0 / dose(unks[1]))\n\n ff = filterfit(unk, fds)\n #println(\"Performing the full generalized fit takes:\")\n #@btime filterfit(unk, fds)\n #println(\"Performing the weighted fit takes:\")\n #@btime filterfit(unk, fds, fitcontiguousw)\n\n @test isapprox(NeXLUncertainties.value(ff, oroi[1]), 0.6624, atol = 0.0001)\n @test isapprox(NeXLUncertainties.value(ff, mgroi[1]), 0.14728, atol = 0.0007)\n @test isapprox(NeXLUncertainties.value(ff, alroi[1]), 0.06679, atol = 0.0006)\n @test isapprox(NeXLUncertainties.value(ff, siroi[1]), 0.35063, atol = 0.0009)\n @test isapprox(NeXLUncertainties.value(ff, caroi[1]), 0.19213, atol = 0.0003)\n @test isapprox(NeXLUncertainties.value(ff, feroi[1]), 0.04185, atol = 0.0004)\n @test isapprox(NeXLUncertainties.value(ff, feroi[2]), 0.06693, atol = 0.0001)\n @test isapprox(NeXLUncertainties.value(ff, feroi[3]), 0.06652, atol = 0.0007)\n\n @test isapprox(σ(ff, oroi[1]), 0.00082, atol = 0.0001)\n @test isapprox(σ(ff, mgroi[1]), 0.00018, atol = 0.00004)\n @test isapprox(σ(ff, alroi[1]), 0.00016, atol = 0.00003)\n @test isapprox(σ(ff, siroi[1]), 0.00029, atol = 0.00003)\n @test isapprox(σ(ff, caroi[1]), 0.00023, atol = 0.00001)\n @test isapprox(σ(ff, feroi[1]), 0.00044, atol = 0.0001)\n @test isapprox(σ(ff, feroi[2]), 0.00016, atol = 0.00001)\n @test isapprox(σ(ff, feroi[3]), 0.00078, atol = 0.0002)\n\n # Compare to naive peak integration\n fekkr = kratio(unks[1], fe, 593:613, 636:647, 669:690)\n @test isapprox(\n NeXLUncertainties.value(ff, feroi[2]),\n NeXLUncertainties.value(fekkr),\n atol = 0.0005,\n )\n @test isapprox(σ(ff, feroi[2]), σ(fekkr), atol = 0.00004)\n\n cakkr = kratio(unks[1], caf2, 334:347, 365:375, 422:439)\n @test isapprox(\n NeXLUncertainties.value(ff, caroi[1]),\n NeXLUncertainties.value(cakkr),\n atol = 0.0008,\n )\n @test isapprox(σ(ff, caroi[1]), σ(cakkr), atol = 0.00007)\n end\n\n @testset \"ADM6005a\" begin\n path = joinpath(@__DIR__, \"ADM6005a spectra\")\n unks = loadspectrum.(joinpath(path, \"ADM-6005a_$(i).msa\") for i = 1:15)\n al = loadspectrum(joinpath(path, \"Al std.msa\"))\n caf2 = loadspectrum(joinpath(path, \"CaF2 std.msa\"))\n fe = loadspectrum(joinpath(path, \"Fe std.msa\"))\n ge = loadspectrum(joinpath(path, \"Ge std.msa\"))\n si = loadspectrum(joinpath(path, \"Si std.msa\"))\n sio2 = loadspectrum(joinpath(path, \"SiO2 std.msa\"))\n ti = loadspectrum(joinpath(path, \"Ti trimmed.msa\"))\n zn = loadspectrum(joinpath(path, \"Zn std.msa\"))\n\n det = matching(\n unks[1],\n 128.0,\n 110,\n Dict(\n Shell(1) => n\"Be\",\n Shell(2) => n\"Sc\",\n Shell(3) => n\"Cs\",\n Shell(4) => n\"Pu\",\n ),\n )\n ff = buildfilter(det)\n\n ampl = 1e-4\n e0 = sameproperty(unks, :BeamEnergy)\n alroi = charXRayLabels(al, n\"Al\", Set( ( n\"Al\", )), det, e0, ampl = ampl)\n caroi = charXRayLabels(caf2, n\"Ca\", [ n\"Ca\", n\"F\" ], det, e0, ampl = ampl)\n feroi = charXRayLabels(fe, n\"Fe\", Set( ( n\"Fe\", )), det, e0, ampl = ampl)\n geroi = charXRayLabels(ge, n\"Ge\", Set( ( n\"Ge\", )), det, e0, ampl = ampl)\n oroi = charXRayLabels(sio2, n\"O\", Set( ( n\"Si\", n\"O\", )), det, e0, ampl = ampl)\n siroi = charXRayLabels(si, n\"Si\", Set( ( n\"Si\", )), det, e0, ampl = ampl)\n tiroi = charXRayLabels(ti, n\"Ti\", Set( ( n\"Ti\", )), det, e0, ampl = ampl)\n znroi = charXRayLabels(zn, n\"Zn\", [ n\"Zn\" ], det, e0, ampl = ampl)\n\n alk = tophatfilter(alroi, ff, 1.0 / dose(al))\n cak = tophatfilter(caroi, ff, 1.0 / dose(caf2))\n felk = tophatfilter(feroi, ff, 1.0 / dose(fe))\n gelk = tophatfilter(geroi, ff, 1.0 / dose(ge))\n ok = tophatfilter(oroi, ff, 1.0 / dose(sio2))\n sik = tophatfilter(siroi, ff, 1.0 / dose(si))\n tilk = tophatfilter(tiroi, ff, 1.0 / dose(ti))\n znlk = tophatfilter(znroi, ff, 1.0 / dose(zn))\n\n fds = collect(Iterators.flatten((alk, cak, felk, gelk, ok, sik, tilk, znlk)))\n\n res = FilterFitResult[]\n for i = 1:15\n unk = tophatfilter(unks[i], ff, 1.0 / dose(unks[i]))\n push!(res, filterfit(unk, fds))\n end\n\n # Compare against DTSA-II values\n @test isapprox(mean(values(res, oroi[1])), 0.4923, rtol = 0.003)\n @test isapprox(mean(values(res, siroi[1])), 0.0214, atol = 0.013)\n @test isapprox(mean(values(res, alroi[1])), 0.0281, atol = 0.001)\n @test isapprox(mean(values(res, caroi[1])), 0.1211, rtol = 0.0025)\n @test isapprox(mean(values(res, znroi[1])), 0.0700, rtol = 0.05)\n @test isapprox(mean(values(res, znroi[2])), 0.1115, atol = 0.0005)\n @test isapprox(mean(values(res, znroi[3])), 0.1231, rtol = 0.01)\n @test isapprox(mean(values(res, tiroi[1])), 0.0404, atol = 0.001)\n @test isapprox(mean(values(res, tiroi[2])), 0.064, rtol = 0.0002)\n @test isapprox(mean(values(res, tiroi[3])), 0.064, rtol = 0.06)\n @test isapprox(mean(values(res, feroi[1])), 0.0, atol = 0.001)\n @test isapprox(mean(values(res, feroi[2])), 0.0, atol = 0.0004)\n @test isapprox(mean(values(res, feroi[3])), 0.0, atol = 0.001)\n @test isapprox(mean(values(res, geroi[1])), 0.1789, rtol = 0.01)\n @test isapprox(mean(values(res, geroi[2])), 0.2628, atol = 0.001)\n @test isapprox(mean(values(res, geroi[3])), 0.279, atol = 0.011)\n end\n @testset \"ADM6005a - Refs\" begin\n path = joinpath(@__DIR__, \"ADM6005a spectra\")\n unks = loadspectrum.(joinpath(path, \"ADM-6005a_$(i).msa\") for i = 1:15)\n det = matching(\n unks[1],\n 128.0,\n 110,\n Dict(\n Shell(1) => n\"Be\",\n Shell(2) => n\"Sc\",\n Shell(3) => n\"Cs\",\n Shell(4) => n\"Pu\",\n ),\n )\n ffp = references(\n [\n reference(n\"Al\", joinpath(path, \"Al std.msa\"), mat\"Al\"),\n reference(n\"Ca\", joinpath(path, \"CaF2 std.msa\"), mat\"CaF2\"),\n reference(n\"Fe\", joinpath(path, \"Fe std.msa\"), mat\"Fe\"),\n reference(n\"Ge\", joinpath(path, \"Ge std.msa\"), mat\"Ge\"),\n reference(n\"Si\", joinpath(path, \"Si std.msa\"), mat\"Si\"),\n reference(n\"O\", joinpath(path, \"SiO2 std.msa\"), mat\"SiO2\"),\n reference(n\"Ti\", joinpath(path, \"Ti trimmed.msa\"), mat\"Ti\"),\n reference(n\"Zn\", joinpath(path, \"Zn std.msa\"), mat\"Zn\"),\n ],\n det,\n )\n res = fit_spectrum(unks, ffp)\n @test isapprox(\n mean(values(res, findlabel(res[1], n\"Al K-L3\"))),\n 0.0279,\n atol = 0.0001,\n )\n @test isapprox(\n mean(values(res, findlabel(res[1], n\"Ti K-L3\"))),\n 0.0641,\n atol = 0.0001,\n )\n @test isapprox(\n mean(values(res, findlabel(res[1], n\"Ge K-M3\"))),\n 0.2734,\n atol = 0.0001,\n )\n @test isapprox(\n mean(values(res, findlabel(res[1], n\"Zn K-M3\"))),\n 0.1209,\n atol = 0.0001,\n )\n @test isapprox(\n mean(values(res, findlabel(res[1], n\"Fe L3-M5\"))),\n 0.00033,\n atol = 0.00001,\n )\n @test isapprox(\n mean(values(res, findlabel(res[1], n\"Fe K-L3\"))),\n 0.0003026,\n atol = 0.00001,\n )\n end\n\n # Check that the covariance of the filtered spectrum is calculated correctly as F*diagm(S)*transpose(F)\n @testset \"Filtered covariance\" begin\n spec = loadspectrum(joinpath(@__DIR__, \"ADM6005a spectra\", \"ADM-6005a_1.msa\"))\n det = matching(\n spec,\n 128.0,\n 110,\n Dict(\n Shell(1) => n\"Be\",\n Shell(2) => n\"Sc\",\n Shell(3) => n\"Cs\",\n Shell(4) => n\"Pu\",\n ),\n )\n filt = buildfilter(VariableWidthFilter, det)\n specdata = counts(spec)\n cov1 = [\n NeXLSpectrum.filteredcovar(filt, specdata, r, c) for\n r in eachindex(specdata), c in eachindex(specdata)\n ]\n filtd = NeXLSpectrum.filterdata(filt)\n cov2 = filtd * diagm(specdata) * transpose(filtd)\n # @show findmax(ii->abs(cov1[ii]-cov2[ii]), eachindex(cov1))\n @test all(\n isapprox(cov1[ii], cov2[ii], rtol = 1.0e-6, atol = 1.0e-12) for\n ii in eachindex(cov1)\n )\n end\n\n @testset \"Repeated refs\" begin\n path = joinpath(@__DIR__, \"K412 spectra\")\n fe = mat\"Fe\"\n efs = references(\n [\n reference(n\"Ca\", joinpath(path,\"III-E K412[0][4].msa\"), srm470_k412),\n reference(n\"Fe\", joinpath(path,\"III-E K412[0][4].msa\"), srm470_k412),\n reference(n\"O\", joinpath(path, \"SiO2 std.msa\"), mat\"SiO2\"),\n reference(n\"Al\", joinpath(path, \"Al2O3 std.msa\"), mat\"Al2O3\"),\n reference(n\"Ca\", joinpath(path, \"CaF2 std.msa\"), mat\"CaF2\"),\n reference(n\"Fe\", joinpath(path, \"Fe std.msa\"), fe),\n reference(n\"Mg\", joinpath(path, \"MgO std.msa\"), mat\"MgO\"),\n reference(n\"Si\", joinpath(path, \"SiO2 std.msa\"), mat\"SiO2\"),\n ],\n 132.0,\n )\n @test properties(efs.references[findfirst(r->n\"Fe K-L3\" in r.label.xrays, efs.references)].label)[:Composition] === srm470_k412\n @test properties(efs.references[findfirst(r->n\"Fe K-M3\" in r.label.xrays, efs.references)].label)[:Composition] === srm470_k412\n @test properties(efs.references[findfirst(r->n\"Fe L3-M5\" in r.label.xrays, efs.references)].label)[:Composition] === fe\n @test properties(efs.references[findfirst(r->n\"Ca K-L3\" in r.label.xrays, efs.references)].label)[:Composition] === srm470_k412\n end\n\n @testset \"Warnings\" begin\n s = loadspectrum(joinpath(@__DIR__, \"Other\", \"K411 simulated.msa\"))\n @test_logs ( :warn, \"The spectrum \\\"Noisy[MC simulation of bulk K411] #1\\\" cannot be used as a reference for the ROI \\\"O K-L3 + 1 other\\\" due to 2 peak interferences.\") \n charXRayLabels(s, n\"O\", Set( ( n\"C\", n\"O\",n\"Mg\",n\"Si\",n\"Ca\",n\"Fe\")), simpleEDS(2048,10.0,0.0,132.0), 1.0e6, ampl=1.0e-5)\n @test_logs ( :warn, \"The spectrum \\\"Noisy[MC simulation of bulk K411] #1\\\" cannot be used as a reference for the ROI \\\"Fe L3-M5 + 11 others\\\" due to 1 peak interference.\") \n charXRayLabels(s, n\"Fe\", Set( ( n\"C\", n\"O\",n\"Mg\",n\"Si\",n\"Ca\",n\"Fe\")), simpleEDS(2048,10.0,0.0,132.0), 1.0e6, ampl=1.0e-5)\n end\n\n @testset \"Example 2\" begin\n path = joinpath(@__DIR__, \"Example 2\")\n refs = references( [\n reference( [ n\"Mg\", n\"Si\", n\"Ca\", n\"Fe\" ], joinpath(path, \"K411 std.msa\"), srm470_k411)...,\n reference( n\"O\", joinpath(path,\"MgO std.msa\"), mat\"MgO\" ),\n reference( n\"Fe\", joinpath(path,\"Fe std.msa\"), mat\"Fe\" ),\n reference( n\"Al\", joinpath(path,\"Al std.msa\"), mat\"Al\" )\n ], 135.0)\n unk = loadspectrum(joinpath(path, \"K412 unk.msa\"))\n fr = fit_spectrum(unk, refs)\n qr = quantify(fr)\n @test isapprox(value(qr.comp[n\"Al\"]), 0.05099, atol=0.0001) \n @test isapprox(value(qr.comp[n\"Fe\"]), 0.0783, atol=0.0001) \n @test isapprox(value(qr.comp[n\"Mg\"]), 0.1183, atol=0.0001) \n @test isapprox(value(qr.comp[n\"O\"]), 0.44715, atol=0.0001)\n\n df = asa(DataFrame, [ fr, fr ], charOnly = false, withUnc = true, format = :normal)\n @test startswith(repr(df[1,:Spectra]),\"\\\"K412-0[Mon Oct 17 16:11:17 2011]\")\n @test ncol(df)==17\n @test nrow(df)==2\n @test isapprox(df[2,2],0.715218,atol=0.0001)\n @test isapprox(df[2,3],0.001413,atol=0.0001)\n\n df = asa(DataFrame, [ fr, ], charOnly = false, withUnc = true, format = :pivot) \n @test ncol(df)==3 && nrow(df)==8\n @test repr(df[1,:ROI])==\"k[O K-L3 + 1 other, MgO]\"\n @test isapprox(df[2,2], 0.0511086, atol=0.00001)\n @test isapprox(df[3,3], 0.00323159, atol=0.00001)\n\n df = asa(DataFrame, [ fr, fr ], charOnly = false, withUnc = true, format = :long)\n @test ncol(df)==4 && nrow(df)==16\n @test df[2,:ROI]==\"k[Fe L3-M5 + 13 others, Fe]\"\n @test isapprox(df[3,3], 1.38384, atol=0.00001)\n @test isapprox(df[3,4], 0.00323159, atol=0.00001)\n\n df = asa(DataFrame, fr, charOnly = false, material = srm470_k412, columns = ( :roi, :peakback, :counts, :dose))\n @test all(r->startswith(repr(r[:Spectrum]),\"K412-0[Mon Oct 17 16:11:17 2011]\"), eachrow(df))\n @test all(r->r[:LiveTime]==60.0,eachrow(df))\n @test all(r->r[:ProbeCurrent]==1.1978,eachrow(df))\n @test all(r->isapprox(r[:DeadPct],14.2529,atol=0.0001),eachrow(df))\n @test df[1,:Start]==131\n @test df[1,:Stop]==168\n @test isapprox(df[1,:K], 0.0331066, atol=0.00001)\n @test isapprox(df[1,:dK], 0.0001588, atol=0.00001)\n @test isapprox(df[1,:Peak], 1.05241e5, atol=10.0)\n @test isapprox(df[1,:Back], 1.02961e5, atol=10.0)\n @test isapprox(df[1,:PtoB], 74.9106, atol=0.001)\n @test isapprox(df[1,:KCalc], 0.032146, atol=0.00001)\n @test isapprox(df[1,:KoKcalc], 1.02988, atol=0.00002)\n @test isapprox(df[1,:RefCountsPernAs], 44231.6, atol=0.1)\n @test isapprox(df[1,:CountsPernAs], 1464.36, atol=0.1)\n end\n @testset \"Example 2 - 32-bit\" begin\n path = joinpath(@__DIR__, \"Example 2\")\n refs = references( [\n reference( [ n\"Mg\", n\"Si\", n\"Ca\", n\"Fe\" ], joinpath(path, \"K411 std.msa\"), srm470_k411)...,\n reference( n\"O\", joinpath(path,\"MgO std.msa\"), mat\"MgO\" ),\n reference( n\"Fe\", joinpath(path,\"Fe std.msa\"), mat\"Fe\" ),\n reference( n\"Al\", joinpath(path,\"Al std.msa\"), mat\"Al\" )\n ], 135.0, ftype=Float32) # This line is the only difference with \"Example 2\"\n unk = loadspectrum(joinpath(path, \"K412 unk.msa\"))\n fr = fit_spectrum(unk, refs)\n qr = quantify(fr)\n @test isapprox(value(qr.comp[n\"Al\"]), 0.05099, atol=0.0001) \n @test isapprox(value(qr.comp[n\"Fe\"]), 0.0783, atol=0.0001) \n @test isapprox(value(qr.comp[n\"Mg\"]), 0.1183, atol=0.0001) \n @test isapprox(value(qr.comp[n\"O\"]), 0.44715, atol=0.0001)\n\n df = asa(DataFrame, [ fr, fr ], charOnly = false, withUnc = true, format = :normal)\n @test startswith(repr(df[1,:Spectra]),\"\\\"K412-0[Mon Oct 17 16:11:17 2011]\")\n @test ncol(df)==17\n @test nrow(df)==2\n @test isapprox(df[2,2],0.715218,atol=0.0001)\n @test isapprox(df[2,3],0.001413,atol=0.0001)\n\n df = asa(DataFrame, [ fr, ], charOnly = false, withUnc = true, format = :pivot) \n @test ncol(df)==3 && nrow(df)==8\n @test repr(df[1,:ROI])==\"k[O K-L3 + 1 other, MgO]\"\n @test isapprox(df[2,2], 0.0511086, atol=0.00001)\n @test isapprox(df[3,3], 0.00323159, atol=0.00001)\n\n df = asa(DataFrame, [ fr, fr ], charOnly = false, withUnc = true, format = :long)\n @test ncol(df)==4 && nrow(df)==16\n @test df[2,:ROI]==\"k[Fe L3-M5 + 13 others, Fe]\"\n @test isapprox(df[3,3], 1.38384, atol=0.00001)\n @test isapprox(df[3,4], 0.00323159, atol=0.00001)\n\n df = asa(DataFrame, fr, charOnly = false, material = srm470_k412, columns = ( :roi, :peakback, :counts, :dose))\n @test all(r->startswith(repr(r[:Spectrum]),\"K412-0[Mon Oct 17 16:11:17 2011]\"), eachrow(df))\n @test all(r->r[:LiveTime]==60.0,eachrow(df))\n @test all(r->r[:ProbeCurrent]==1.1978,eachrow(df))\n @test all(r->isapprox(r[:DeadPct],14.2529,atol=0.0001),eachrow(df))\n @test df[1,:Start]==131\n @test df[1,:Stop]==168\n @test isapprox(df[1,:K], 0.0331066, atol=0.00001)\n @test isapprox(df[1,:dK], 0.0001588, atol=0.00001)\n @test isapprox(df[1,:Peak], 1.05241e5, atol=10.0)\n @test isapprox(df[1,:Back], 1.02961e5, atol=10.0)\n @test isapprox(df[1,:PtoB], 74.9106, atol=0.001)\n @test isapprox(df[1,:KCalc], 0.032146, atol=0.00001)\n @test isapprox(df[1,:KoKcalc], 1.02988, atol=0.00002)\n @test isapprox(df[1,:RefCountsPernAs], 44231.6, atol=0.1)\n @test isapprox(df[1,:CountsPernAs], 1464.36, atol=0.1)\n end\nend"
] |
f7cf3f1d35f79bc4e63eb2273441f41ee6e86558
| 3,917
|
jl
|
Julia
|
20/src/11.jl
|
CmdQ/AoC
|
1ab6118e4d2c71df06326b08f1b0dc5f2e664f1d
|
[
"Unlicense"
] | 1
|
2020-12-07T10:27:26.000Z
|
2020-12-07T10:27:26.000Z
|
20/src/11.jl
|
CmdQ/AoC2020
|
78f96de7b050291df9e5ed56b314f8cb3aa5856c
|
[
"Unlicense"
] | null | null | null |
20/src/11.jl
|
CmdQ/AoC2020
|
78f96de7b050291df9e5ed56b314f8cb3aa5856c
|
[
"Unlicense"
] | null | null | null |
using Chain
using Underscores
using Utils
@enum Seat::Int8 floor=Int('.') empty=Int('L') occupied=Int('#') void=Int('?')
function parse_line(line::String)::Array{Seat}
@chain line begin
collect
map(Seat ∘ Int, _)
end
end
function embed(m)
a, b = size(m)
re = fill(void, (a+2, b+2))
re[2:end-1, 2:end-1] = m
re
end
function parse_file(f)
m = @chain f begin
eachline
map(parse_line, _)
foldl(hcat, _)
permutedims
end
embed(m)
end
function load()
open(joinpath(@__DIR__, "11_seats.txt"), "r") do f
parse_file(f)
end
end
is_occupied(c) = c == occupied
function step(counter, grid, tolerance)
a, b = axes(grid)
prev = copy(grid)
changed = false
for i in firstindex(a)+1:lastindex(a)-1, j in firstindex(b)+1:lastindex(b)-1
co = counter(prev, i, j)
if prev[i, j] == empty && co == 0
grid[i, j] = occupied
changed = true
elseif is_occupied(prev[i, j]) && co >= tolerance
grid[i, j] = empty
changed = true
end
end
changed
end
block_count(grid, i, j) = count(is_occupied, grid[i-1:i+1, j-1:j+1]) - Int(is_occupied(grid[i, j]))
function ex(counter, grid, tolerance)
grid = copy(grid)
loop = true
while loop
loop = step(counter, grid, tolerance)
end
count(is_occupied, grid)
end
ex1(grid) = ex(block_count, grid, 4)
function sight_count(grid, i, j)
count = 0
for row in -1:1, col in -1:1
if (row | col) != 0 # Don't count the center.
rr = i + row
cc = j + col
# No need to check indices, because there's definitely a void boundary.
while grid[rr, cc] == floor
rr += row
cc += col
end
count += is_occupied(grid[rr, cc]) |> Int
end
end
count
end
ex2(grid) = ex(sight_count, grid, 5)
grid = load()
println("Stable seating occupied: ", ex1(grid))
println("Number of combinations: ", ex2(grid))
using Test
@testset "Adapter Array" begin
input = """
L.LL.LL.LL
LLLLLLL.LL
L.L.L..L..
LLLL.LL.LL
L.LL.LL.LL
L.LLLLL.LL
..L.L.....
LLLLLLLLLL
L.LLLLLL.L
L.LLLLL.LL
"""
example = parse_file(IOBuffer(input))
@testset "example 1" begin
example = copy(example)
mini = parse_file(IOBuffer("L.\n.L"))
@test count(is_occupied, mini) == 0
step(block_count, mini, 4)
@test count(is_occupied, mini) == 2
@test mini[2:end-1, 2:end-1] == [occupied floor; floor occupied]
@test ex1(example) == 37
end
@testset "example 2" begin
see_eight = """
.......#.
...#.....
.#.......
.........
..#L....#
....#....
.........
#........
...#.....
"""
see_eight = see_eight |> IOBuffer |> parse_file
@test see_eight[5+1, 4+1] == empty
@test sight_count(see_eight, 5+1, 4+1) == 8
see_one = """
.............
.L.L.#.#.#.#.
.............
"""
see_one = see_one |> IOBuffer |> parse_file
@test see_one[2+1, 2+1] == empty
@test see_one[2+1, 4+1] == empty
@test sight_count(see_one, 2+1, 2+1) == 0
@test sight_count(see_one, 2+1, 4+1) == 1
see_none = """
.##.##.
#.#.#.#
##...##
...L...
##...##
#.#.#.#
.##.##.
"""
see_none = see_none |> IOBuffer |> parse_file
@test see_none[4+1, 4+1] == empty
@test sight_count(see_none, 4+1, 4+1) == 0
example = copy(example)
@test ex2(example) == 26
end
@testset "results" begin
@test ex1(grid) == 2204
@test ex2(grid) == 1986
end
end
| 21.288043
| 99
| 0.490426
|
[
"@testset \"Adapter Array\" begin\n input = \"\"\"\n L.LL.LL.LL\n LLLLLLL.LL\n L.L.L..L..\n LLLL.LL.LL\n L.LL.LL.LL\n L.LLLLL.LL\n ..L.L.....\n LLLLLLLLLL\n L.LLLLLL.L\n L.LLLLL.LL\n \"\"\"\n\n\n example = parse_file(IOBuffer(input))\n\n @testset \"example 1\" begin\n example = copy(example)\n mini = parse_file(IOBuffer(\"L.\\n.L\"))\n @test count(is_occupied, mini) == 0\n step(block_count, mini, 4)\n @test count(is_occupied, mini) == 2\n @test mini[2:end-1, 2:end-1] == [occupied floor; floor occupied]\n @test ex1(example) == 37\n end\n\n @testset \"example 2\" begin\n see_eight = \"\"\"\n .......#.\n ...#.....\n .#.......\n .........\n ..#L....#\n ....#....\n .........\n #........\n ...#.....\n \"\"\"\n see_eight = see_eight |> IOBuffer |> parse_file\n\n @test see_eight[5+1, 4+1] == empty\n @test sight_count(see_eight, 5+1, 4+1) == 8\n\n see_one = \"\"\"\n .............\n .L.L.#.#.#.#.\n .............\n \"\"\"\n see_one = see_one |> IOBuffer |> parse_file\n\n @test see_one[2+1, 2+1] == empty\n @test see_one[2+1, 4+1] == empty\n @test sight_count(see_one, 2+1, 2+1) == 0\n @test sight_count(see_one, 2+1, 4+1) == 1\n\n see_none = \"\"\"\n .##.##.\n #.#.#.#\n ##...##\n ...L...\n ##...##\n #.#.#.#\n .##.##.\n \"\"\"\n see_none = see_none |> IOBuffer |> parse_file\n\n @test see_none[4+1, 4+1] == empty\n @test sight_count(see_none, 4+1, 4+1) == 0\n\n example = copy(example)\n @test ex2(example) == 26\n end\n\n @testset \"results\" begin\n @test ex1(grid) == 2204\n @test ex2(grid) == 1986\n end\nend"
] |
f7d093827f0dbc35982c3a02d5ed3e5b94851ae1
| 28,567
|
jl
|
Julia
|
stdlib/REPL/test/lineedit.jl
|
greimel/julia
|
1c6f89f04a1ee4eba8380419a2b01426e84f52aa
|
[
"Zlib"
] | 18
|
2018-03-17T16:54:52.000Z
|
2021-11-14T20:28:51.000Z
|
stdlib/REPL/test/lineedit.jl
|
greimel/julia
|
1c6f89f04a1ee4eba8380419a2b01426e84f52aa
|
[
"Zlib"
] | 8
|
2018-09-27T01:16:58.000Z
|
2018-12-05T23:33:08.000Z
|
stdlib/REPL/test/lineedit.jl
|
greimel/julia
|
1c6f89f04a1ee4eba8380419a2b01426e84f52aa
|
[
"Zlib"
] | 3
|
2018-03-21T14:40:39.000Z
|
2020-05-04T19:15:03.000Z
|
# This file is a part of Julia. License is MIT: https://julialang.org/license
using Test
using REPL
import REPL.LineEdit
import REPL.LineEdit: edit_insert, buffer, content, setmark, getmark, region
include("FakeTerminals.jl")
import .FakeTerminals.FakeTerminal
# no need to have animation in tests
REPL.GlobalOptions.region_animation_duration=0.001
## helper functions
function new_state()
term = FakeTerminal(IOBuffer(), IOBuffer(), IOBuffer())
LineEdit.init_state(term, LineEdit.ModalInterface([LineEdit.Prompt("test> ")]))
end
charseek(buf, i) = seek(buf, nextind(content(buf), 0, i+1)-1)
charpos(buf, pos=position(buf)) = length(content(buf), 1, pos)
function transform!(f, s, i = -1) # i is char-based (not bytes) buffer position
buf = buffer(s)
i >= 0 && charseek(buf, i)
# simulate what happens in LineEdit.set_action!
s isa LineEdit.MIState && (s.current_action = :unknown)
status = f(s)
if s isa LineEdit.MIState && status != :ignore
# simulate what happens in LineEdit.prompt!
s.last_action = s.current_action
end
content(s), charpos(buf), charpos(buf, getmark(buf))
end
function run_test(d,buf)
global a_foo, b_foo, a_bar, b_bar
a_foo = b_foo = a_bar = b_bar = 0
while !eof(buf)
LineEdit.match_input(d, nothing, buf)(nothing,nothing)
end
end
a_foo = 0
const foo_keymap = Dict(
'a' => (o...)->(global a_foo; a_foo += 1)
)
b_foo = 0
const foo2_keymap = Dict(
'b' => (o...)->(global b_foo; b_foo += 1)
)
a_bar = 0
b_bar = 0
const bar_keymap = Dict(
'a' => (o...)->(global a_bar; a_bar += 1),
'b' => (o...)->(global b_bar; b_bar += 1)
)
test1_dict = LineEdit.keymap([foo_keymap])
run_test(test1_dict,IOBuffer("aa"))
@test a_foo == 2
test2_dict = LineEdit.keymap([foo2_keymap, foo_keymap])
run_test(test2_dict,IOBuffer("aaabb"))
@test a_foo == 3
@test b_foo == 2
test3_dict = LineEdit.keymap([bar_keymap, foo_keymap])
run_test(test3_dict,IOBuffer("aab"))
@test a_bar == 2
@test b_bar == 1
# Multiple spellings in the same keymap
const test_keymap_1 = Dict(
"^C" => (o...)->1,
"\\C-C" => (o...)->2
)
@test_throws ErrorException LineEdit.keymap([test_keymap_1])
a_foo = a_bar = 0
const test_keymap_2 = Dict(
"abc" => (o...)->(global a_foo = 1)
)
const test_keymap_3 = Dict(
"a" => (o...)->(global a_foo = 2),
"bc" => (o...)->(global a_bar = 3)
)
function keymap_fcn(keymaps)
d = LineEdit.keymap(keymaps)
f = buf->(LineEdit.match_input(d, nothing, buf)(nothing,nothing))
end
let f = keymap_fcn([test_keymap_3, test_keymap_2])
buf = IOBuffer("abc")
f(buf); f(buf)
@test a_foo == 2
@test a_bar == 3
@test eof(buf)
end
# Eager redirection when the redirected-to behavior is changed.
a_foo = 0
const test_keymap_4 = Dict(
"a" => (o...)->(global a_foo = 1),
"b" => "a",
"c" => (o...)->(global a_foo = 2),
)
const test_keymap_5 = Dict(
"a" => (o...)->(global a_foo = 3),
"d" => "c"
)
let f = keymap_fcn([test_keymap_5, test_keymap_4])
buf = IOBuffer("abd")
f(buf)
@test a_foo == 3
f(buf)
@test a_foo == 1
f(buf)
@test a_foo == 2
@test eof(buf)
end
# Eager redirection with cycles
const test_cycle = Dict(
"a" => "b",
"b" => "a"
)
@test_throws ErrorException LineEdit.keymap([test_cycle])
# Lazy redirection with Cycles
const level1 = Dict(
"a" => LineEdit.KeyAlias("b")
)
const level2a = Dict(
"b" => "a"
)
const level2b = Dict(
"b" => LineEdit.KeyAlias("a")
)
@test_throws ErrorException LineEdit.keymap([level2a,level1])
@test_throws ErrorException LineEdit.keymap([level2b,level1])
# Lazy redirection functionality test
a_foo = 0
const test_keymap_6 = Dict(
"a" => (o...)->(global a_foo = 1),
"b" => LineEdit.KeyAlias("a"),
"c" => (o...)->(global a_foo = 2),
)
const test_keymap_7 = Dict(
"a" => (o...)->(global a_foo = 3),
"d" => "c"
)
let f = keymap_fcn([test_keymap_7, test_keymap_6])
buf = IOBuffer("abd")
f(buf)
@test a_foo == 3
global a_foo = 0
f(buf)
@test a_foo == 3
f(buf)
@test a_foo == 2
@test eof(buf)
end
# Test requiring postprocessing (see conflict fixing in LineEdit.jl )
global path1 = 0
global path2 = 0
global path3 = 0
const test_keymap_8 = Dict(
"**" => (o...)->(global path1 += 1),
"ab" => (o...)->(global path2 += 1),
"cd" => (o...)->(global path3 += 1),
"d" => (o...)->(error("This is not the key you're looking for"))
)
let f = keymap_fcn([test_keymap_8])
buf = IOBuffer("bbabaccd")
f(buf)
@test path1 == 1
f(buf)
@test path2 == 1
f(buf)
@test path1 == 2
f(buf)
@test path3 == 1
@test eof(buf)
end
global path1 = 0
global path2 = 0
const test_keymap_9 = Dict(
"***" => (o...)->(global path1 += 1),
"*a*" => (o...)->(global path2 += 1)
)
let f = keymap_fcn([test_keymap_9])
buf = IOBuffer("abaaaa")
f(buf)
@test path1 == 1
f(buf)
@test path2 == 1
@test eof(buf)
end
## edit_move{left,right} ##
buf = IOBuffer("a\na\na\n")
seek(buf, 0)
for i = 1:6
LineEdit.edit_move_right(buf)
@test position(buf) == i
end
@test eof(buf)
for i = 5:0
LineEdit.edit_move_left(buf)
@test position(buf) == i
end
# skip unicode combining characters
buf = IOBuffer("ŷ")
seek(buf, 0)
LineEdit.edit_move_right(buf)
@test eof(buf)
LineEdit.edit_move_left(buf)
@test position(buf) == 0
## edit_move_{up,down} ##
buf = IOBuffer("type X\n a::Int\nend")
for i = 0:6
seek(buf,i)
@test !LineEdit.edit_move_up(buf)
@test position(buf) == i
seek(buf,i)
@test LineEdit.edit_move_down(buf)
@test position(buf) == i+7
end
for i = 7:17
seek(buf,i)
@test LineEdit.edit_move_up(buf)
@test position(buf) == min(i-7,6)
seek(buf,i)
@test LineEdit.edit_move_down(buf)
@test position(buf) == min(i+11,21)
end
for i = 18:21
seek(buf,i)
@test LineEdit.edit_move_up(buf)
@test position(buf) == i-11
seek(buf,i)
@test !LineEdit.edit_move_down(buf)
@test position(buf) == i
end
buf = IOBuffer("type X\n\n")
seekend(buf)
@test LineEdit.edit_move_up(buf)
@test position(buf) == 7
@test LineEdit.edit_move_up(buf)
@test position(buf) == 0
@test !LineEdit.edit_move_up(buf)
@test position(buf) == 0
seek(buf,0)
@test LineEdit.edit_move_down(buf)
@test position(buf) == 7
@test LineEdit.edit_move_down(buf)
@test position(buf) == 8
@test !LineEdit.edit_move_down(buf)
@test position(buf) == 8
## edit_delete_prev_word ##
buf = IOBuffer("type X\n ")
seekend(buf)
@test !isempty(LineEdit.edit_delete_prev_word(buf))
@test position(buf) == 5
@test buf.size == 5
@test content(buf) == "type "
buf = IOBuffer("4 +aaa+ x")
seek(buf,8)
@test !isempty(LineEdit.edit_delete_prev_word(buf))
@test position(buf) == 3
@test buf.size == 4
@test content(buf) == "4 +x"
buf = IOBuffer("x = func(arg1,arg2 , arg3)")
seekend(buf)
LineEdit.char_move_word_left(buf)
@test position(buf) == 21
@test !isempty(LineEdit.edit_delete_prev_word(buf))
@test content(buf) == "x = func(arg1,arg3)"
@test !isempty(LineEdit.edit_delete_prev_word(buf))
@test content(buf) == "x = func(arg3)"
@test !isempty(LineEdit.edit_delete_prev_word(buf))
@test content(buf) == "x = arg3)"
# Unicode combining characters
let buf = IOBuffer()
edit_insert(buf, "â")
LineEdit.edit_move_left(buf)
@test position(buf) == 0
LineEdit.edit_move_right(buf)
@test bytesavailable(buf) == 0
LineEdit.edit_backspace(buf, false, false)
@test content(buf) == "a"
end
## edit_transpose_chars ##
let buf = IOBuffer()
edit_insert(buf, "abcde")
seek(buf,0)
LineEdit.edit_transpose_chars(buf)
@test content(buf) == "abcde"
LineEdit.char_move_right(buf)
LineEdit.edit_transpose_chars(buf)
@test content(buf) == "bacde"
LineEdit.edit_transpose_chars(buf)
@test content(buf) == "bcade"
seekend(buf)
LineEdit.edit_transpose_chars(buf)
@test content(buf) == "bcaed"
LineEdit.edit_transpose_chars(buf)
@test content(buf) == "bcade"
seek(buf, 0)
LineEdit.edit_clear(buf)
edit_insert(buf, "αβγδε")
seek(buf,0)
LineEdit.edit_transpose_chars(buf)
@test content(buf) == "αβγδε"
LineEdit.char_move_right(buf)
LineEdit.edit_transpose_chars(buf)
@test content(buf) == "βαγδε"
LineEdit.edit_transpose_chars(buf)
@test content(buf) == "βγαδε"
seekend(buf)
LineEdit.edit_transpose_chars(buf)
@test content(buf) == "βγαεδ"
LineEdit.edit_transpose_chars(buf)
@test content(buf) == "βγαδε"
end
@testset "edit_word_transpose" begin
local buf, mode
buf = IOBuffer()
mode = Ref{Symbol}()
transpose!(i) = transform!(buf -> LineEdit.edit_transpose_words(buf, mode[]),
buf, i)[1:2]
mode[] = :readline
edit_insert(buf, "àbç def gh ")
@test transpose!(0) == ("àbç def gh ", 0)
@test transpose!(1) == ("àbç def gh ", 1)
@test transpose!(2) == ("àbç def gh ", 2)
@test transpose!(3) == ("def àbç gh ", 7)
@test transpose!(4) == ("àbç def gh ", 7)
@test transpose!(5) == ("def àbç gh ", 7)
@test transpose!(6) == ("àbç def gh ", 7)
@test transpose!(7) == ("àbç gh def ", 11)
@test transpose!(10) == ("àbç def gh ", 11)
@test transpose!(11) == ("àbç gh def", 12)
edit_insert(buf, " ")
@test transpose!(13) == ("àbç def gh", 13)
take!(buf)
mode[] = :emacs
edit_insert(buf, "àbç def gh ")
@test transpose!(0) == ("def àbç gh ", 7)
@test transpose!(4) == ("àbç def gh ", 7)
@test transpose!(5) == ("àbç gh def ", 11)
@test transpose!(10) == ("àbç def gh", 12)
edit_insert(buf, " ")
@test transpose!(13) == ("àbç gh def", 13)
end
let s = new_state(),
buf = buffer(s)
edit_insert(s,"first line\nsecond line\nthird line")
@test content(buf) == "first line\nsecond line\nthird line"
## edit_move_line_start/end ##
seek(buf, 0)
LineEdit.move_line_end(s)
@test position(buf) == sizeof("first line")
LineEdit.move_line_end(s) # Only move to input end on repeated keypresses
@test position(buf) == sizeof("first line")
s.key_repeats = 1 # Manually flag a repeated keypress
LineEdit.move_line_end(s)
s.key_repeats = 0
@test eof(buf)
seekend(buf)
LineEdit.move_line_start(s)
@test position(buf) == sizeof("first line\nsecond line\n")
LineEdit.move_line_start(s)
@test position(buf) == sizeof("first line\nsecond line\n")
s.key_repeats = 1 # Manually flag a repeated keypress
LineEdit.move_line_start(s)
s.key_repeats = 0
@test position(buf) == 0
## edit_kill_line, edit_yank ##
seek(buf, 0)
LineEdit.edit_kill_line(s)
s.key_repeats = 1 # Manually flag a repeated keypress
LineEdit.edit_kill_line(s)
s.key_repeats = 0
@test content(buf) == "second line\nthird line"
LineEdit.move_line_end(s)
LineEdit.edit_move_right(s)
LineEdit.edit_yank(s)
@test content(buf) == "second line\nfirst line\nthird line"
end
# Issue 7845
# First construct a problematic string:
# julia> is 6 characters + 1 character for space,
# so the rest of the terminal is 73 characters
#########################################################################
let buf = IOBuffer(
"begin\nprint(\"A very very very very very very very very very very very very ve\")\nend")
seek(buf, 4)
outbuf = IOBuffer()
termbuf = REPL.Terminals.TerminalBuffer(outbuf)
term = FakeTerminal(IOBuffer(), IOBuffer(), IOBuffer())
s = LineEdit.refresh_multi_line(termbuf, term, buf,
REPL.LineEdit.InputAreaState(0,0), "julia> ", indent = 7)
@test s == REPL.LineEdit.InputAreaState(3,1)
end
@testset "function prompt indentation" begin
local s, term, ps, buf, outbuf, termbuf
s = new_state()
term = REPL.LineEdit.terminal(s)
# default prompt: PromptState.indent should not be set to a final fixed value
ps::LineEdit.PromptState = s.mode_state[s.current_mode]
@test ps.indent == -1
# the prompt is modified afterwards to a function
ps.p.prompt = let i = 0
() -> ["Julia is Fun! > ", "> "][mod1(i+=1, 2)] # lengths are 16 and 2
end
buf = buffer(ps)
write(buf, "begin\n julia = :fun\nend")
outbuf = IOBuffer()
termbuf = REPL.Terminals.TerminalBuffer(outbuf)
LineEdit.refresh_multi_line(termbuf, term, ps)
@test String(take!(outbuf)) ==
"\r\e[0K\e[1mJulia is Fun! > \e[0m\r\e[16Cbegin\n" *
"\r\e[16C julia = :fun\n" *
"\r\e[16Cend\r\e[19C"
LineEdit.refresh_multi_line(termbuf, term, ps)
@test String(take!(outbuf)) ==
"\r\e[0K\e[1A\r\e[0K\e[1A\r\e[0K\e[1m> \e[0m\r\e[2Cbegin\n" *
"\r\e[2C julia = :fun\n" *
"\r\e[2Cend\r\e[5C"
end
@testset "shift selection" begin
s = new_state()
edit_insert(s, "αä🐨") # for issue #28183
s.current_action = :unknown
LineEdit.edit_shift_move(s, LineEdit.edit_move_left)
@test LineEdit.region(s) == (5=>9)
LineEdit.edit_shift_move(s, LineEdit.edit_move_left)
@test LineEdit.region(s) == (2=>9)
LineEdit.edit_shift_move(s, LineEdit.edit_move_left)
@test LineEdit.region(s) == (0=>9)
LineEdit.edit_shift_move(s, LineEdit.edit_move_right)
@test LineEdit.region(s) == (2=>9)
end
@testset "tab/backspace alignment feature" begin
s = new_state()
move_left(s, n) = for x = 1:n
LineEdit.edit_move_left(s)
end
edit_insert(s, "for x=1:10\n")
LineEdit.edit_tab(s)
@test content(s) == "for x=1:10\n "
LineEdit.edit_backspace(s, true, false)
@test content(s) == "for x=1:10\n"
edit_insert(s, " ")
@test position(s) == 13
LineEdit.edit_tab(s)
@test content(s) == "for x=1:10\n "
edit_insert(s, " ")
LineEdit.edit_backspace(s, true, false)
@test content(s) == "for x=1:10\n "
edit_insert(s, "éé=3 ")
LineEdit.edit_tab(s)
@test content(s) == "for x=1:10\n éé=3 "
LineEdit.edit_backspace(s, true, false)
@test content(s) == "for x=1:10\n éé=3"
edit_insert(s, "\n 1∉x ")
LineEdit.edit_tab(s)
@test content(s) == "for x=1:10\n éé=3\n 1∉x "
LineEdit.edit_backspace(s, false, false)
@test content(s) == "for x=1:10\n éé=3\n 1∉x "
LineEdit.edit_backspace(s, true, false)
@test content(s) == "for x=1:10\n éé=3\n 1∉x "
LineEdit.edit_move_word_left(s)
LineEdit.edit_tab(s)
@test content(s) == "for x=1:10\n éé=3\n 1∉x "
LineEdit.move_line_start(s)
@test position(s) == 22
LineEdit.edit_tab(s, true)
@test content(s) == "for x=1:10\n éé=3\n 1∉x "
@test position(s) == 30
LineEdit.edit_move_left(s)
@test position(s) == 29
LineEdit.edit_backspace(s, true, true)
@test content(s) == "for x=1:10\n éé=3\n 1∉x "
@test position(s) == 26
LineEdit.edit_tab(s, false) # same as edit_tab(s, true) here
@test position(s) == 30
move_left(s, 6)
@test position(s) == 24
LineEdit.edit_backspace(s, true, true)
@test content(s) == "for x=1:10\n éé=3\n 1∉x "
@test position(s) == 22
LineEdit.edit_kill_line(s)
edit_insert(s, ' '^10)
move_left(s, 7)
@test content(s) == "for x=1:10\n éé=3\n "
@test position(s) == 25
LineEdit.edit_tab(s, true, false)
@test position(s) == 32
move_left(s, 7)
LineEdit.edit_tab(s, true, true)
@test position(s) == 26
@test content(s) == "for x=1:10\n éé=3\n "
# test again the same, when there is a next line
edit_insert(s, " \nend")
move_left(s, 11)
@test position(s) == 25
LineEdit.edit_tab(s, true, false)
@test position(s) == 32
move_left(s, 7)
LineEdit.edit_tab(s, true, true)
@test position(s) == 26
@test content(s) == "for x=1:10\n éé=3\n \nend"
end
@testset "newline alignment feature" begin
s = new_state()
edit_insert(s, "for x=1:10\n é = 1")
LineEdit.edit_insert_newline(s)
@test content(s) == "for x=1:10\n é = 1\n "
edit_insert(s, " b = 2")
LineEdit.edit_insert_newline(s)
@test content(s) == "for x=1:10\n é = 1\n b = 2\n "
# after an empty line, should still insert the expected number of spaces
LineEdit.edit_insert_newline(s)
@test content(s) == "for x=1:10\n é = 1\n b = 2\n \n "
LineEdit.edit_insert_newline(s, 0)
@test content(s) == "for x=1:10\n é = 1\n b = 2\n \n \n"
LineEdit.edit_insert_newline(s, 2)
@test content(s) == "for x=1:10\n é = 1\n b = 2\n \n \n\n "
# test when point before first letter of the line
for i=6:10
LineEdit.edit_clear(s)
edit_insert(s, "begin\n x")
seek(LineEdit.buffer(s), i)
LineEdit.edit_insert_newline(s)
@test content(s) == "begin\n" * ' '^(i-6) * "\n x"
end
end
@testset "change case on the right" begin
local buf = IOBuffer()
edit_insert(buf, "aa bb CC")
seekstart(buf)
LineEdit.edit_upper_case(buf)
LineEdit.edit_title_case(buf)
@test String(take!(copy(buf))) == "AA Bb CC"
@test position(buf) == 5
LineEdit.edit_lower_case(buf)
@test String(take!(copy(buf))) == "AA Bb cc"
end
@testset "kill ring" begin
local buf
s = new_state()
buf = buffer(s)
edit_insert(s, "ça ≡ nothing")
@test transform!(LineEdit.edit_copy_region, s) == ("ça ≡ nothing", 12, 0)
@test s.kill_ring[end] == "ça ≡ nothing"
@test transform!(LineEdit.edit_exchange_point_and_mark, s)[2:3] == (0, 12)
charseek(buf, 8); setmark(s)
charseek(buf, 1)
@test transform!(LineEdit.edit_kill_region, s) == ("çhing", 1, 1)
@test s.kill_ring[end] == "a ≡ not"
charseek(buf, 0)
@test transform!(LineEdit.edit_yank, s) == ("a ≡ notçhing", 7, 0)
s.last_action = :unknown
# next action will fail, as yank-pop doesn't know a yank was just issued
@test transform!(LineEdit.edit_yank_pop, s) == ("a ≡ notçhing", 7, 0)
s.last_action = :edit_yank
# now this should work:
@test transform!(LineEdit.edit_yank_pop, s) == ("ça ≡ nothingçhing", 12, 0)
@test s.kill_idx == 1
LineEdit.edit_kill_line(s)
@test s.kill_ring[end] == "çhing"
@test s.kill_idx == 3
# check that edit_yank_pop works when passing require_previous_yank=false (#23635)
s.last_action = :unknown
@test transform!(s->LineEdit.edit_yank_pop(s, false), s) == ("ça ≡ nothinga ≡ not", 19, 12)
# repetition (concatenation of killed strings
edit_insert(s, "A B C")
LineEdit.edit_delete_prev_word(s)
s.key_repeats = 1
LineEdit.edit_delete_prev_word(s)
s.key_repeats = 0
@test s.kill_ring[end] == "B C"
LineEdit.edit_yank(s)
LineEdit.edit_werase(s)
@test s.kill_ring[end] == "C"
s.key_repeats = 1
LineEdit.edit_werase(s)
s.key_repeats = 0
@test s.kill_ring[end] == "B C"
LineEdit.edit_yank(s)
LineEdit.edit_move_word_left(s)
LineEdit.edit_move_word_left(s)
LineEdit.edit_delete_next_word(s)
@test s.kill_ring[end] == "B"
s.key_repeats = 1
LineEdit.edit_delete_next_word(s)
s.key_repeats = 0
@test s.kill_ring[end] == "B C"
# edit_kill_line_backwards
LineEdit.edit_clear(s)
edit_insert(s, "begin\n a=1\n b=2")
LineEdit.edit_kill_line_backwards(s)
@test s.kill_ring[end] == " b=2"
s.key_repeats = 1
LineEdit.edit_kill_line_backwards(s)
@test s.kill_ring[end] == "\n b=2"
LineEdit.edit_kill_line_backwards(s)
@test s.kill_ring[end] == " a=1\n b=2"
s.key_repeats = 0
end
@testset "undo" begin
s = new_state()
edit!(f) = transform!(f, s)[1]
edit_undo! = LineEdit.edit_undo!
edit_redo! = LineEdit.edit_redo!
edit_insert(s, "one two three")
@test edit!(LineEdit.edit_delete_prev_word) == "one two "
@test edit!(edit_undo!) == "one two three"
@test edit!(edit_redo!) == "one two "
@test edit!(edit_undo!) == "one two three"
edit_insert(s, " four")
@test edit!(s->edit_insert(s, " five")) == "one two three four five"
@test edit!(edit_undo!) == "one two three four"
@test edit!(edit_undo!) == "one two three"
@test edit!(edit_redo!) == "one two three four"
@test edit!(edit_redo!) == "one two three four five"
@test edit!(edit_undo!) == "one two three four"
@test edit!(edit_undo!) == "one two three"
@test edit!(LineEdit.edit_clear) == ""
@test edit!(LineEdit.edit_clear) == "" # should not be saved twice
@test edit!(edit_undo!) == "one two three"
@test edit!(LineEdit.edit_insert_newline) == "one two three\n"
@test edit!(edit_undo!) == "one two three"
LineEdit.edit_move_left(s)
LineEdit.edit_move_left(s)
@test edit!(LineEdit.edit_transpose_chars) == "one two there"
@test edit!(edit_undo!) == "one two three"
@test edit!(LineEdit.edit_transpose_words) == "one three two"
@test edit!(edit_undo!) == "one two three"
LineEdit.move_line_start(s)
@test edit!(LineEdit.edit_kill_line) == ""
@test edit!(edit_undo!) == "one two three"
# undo stack not updated if killing nothing:
LineEdit.move_line_start(s)
LineEdit.edit_kill_line(s)
LineEdit.edit_kill_line(s) # no effect
@test edit!(edit_undo!) == "one two three"
LineEdit.move_line_end(s)
@test edit!(LineEdit.edit_kill_line_backwards) == ""
@test edit!(edit_undo!) == "one two three"
LineEdit.move_line_start(s)
LineEdit.edit_kill_line(s)
LineEdit.edit_yank(s)
@test edit!(LineEdit.edit_yank) == "one two threeone two three"
@test edit!(edit_undo!) == "one two three"
@test edit!(edit_undo!) == ""
@test edit!(edit_undo!) == "one two three"
LineEdit.setmark(s)
LineEdit.edit_move_word_right(s)
@test edit!(LineEdit.edit_kill_region) == " two three"
@test edit!(LineEdit.edit_yank) == "one two three"
@test edit!(LineEdit.edit_yank_pop) == "one two three two three"
@test edit!(edit_undo!) == "one two three"
@test edit!(edit_undo!) == " two three"
@test edit!(edit_undo!) == "one two three"
LineEdit.move_line_end(s)
LineEdit.edit_backspace(s, false, false)
LineEdit.edit_backspace(s, false, false)
@test edit!(s->LineEdit.edit_backspace(s, false, false)) == "one two th"
@test edit!(edit_undo!) == "one two thr"
@test edit!(edit_undo!) == "one two thre"
@test edit!(edit_undo!) == "one two three"
LineEdit.push_undo(s) # TODO: incorporate push_undo into edit_splice! ?
LineEdit.edit_splice!(s, 4 => 7, "stott")
@test content(s) == "one stott three"
s.last_action = :not_undo
@test edit!(edit_undo!) == "one two three"
LineEdit.edit_move_left(s)
LineEdit.edit_move_left(s)
LineEdit.edit_move_left(s)
@test edit!(LineEdit.edit_delete) == "one two thee"
@test edit!(edit_undo!) == "one two three"
LineEdit.edit_move_word_left(s)
LineEdit.edit_werase(s)
@test edit!(LineEdit.edit_delete_next_word) == "one "
@test edit!(edit_undo!) == "one three"
@test edit!(edit_undo!) == "one two three"
@test edit!(edit_redo!) == "one three"
@test edit!(edit_redo!) == "one "
@test edit!(edit_redo!) == "one " # nothing more to redo (this "beeps")
@test edit!(edit_undo!) == "one three"
@test edit!(edit_undo!) == "one two three"
LineEdit.move_line_start(s)
@test edit!(LineEdit.edit_upper_case) == "ONE two three"
LineEdit.move_line_start(s)
@test edit!(LineEdit.edit_lower_case) == "one two three"
@test edit!(LineEdit.edit_title_case) == "one Two three"
@test edit!(edit_undo!) == "one two three"
@test edit!(edit_undo!) == "ONE two three"
@test edit!(edit_undo!) == "one two three"
LineEdit.move_line_end(s)
edit_insert(s, " ")
@test edit!(LineEdit.edit_tab) == "one two three "
@test edit!(edit_undo!) == "one two three "
@test edit!(edit_undo!) == "one two three"
LineEdit.move_line_start(s)
edit_insert(s, " ")
LineEdit.move_line_start(s)
@test edit!(s->LineEdit.edit_tab(s, true, true)) == " one two three" # tab moves cursor to position 2
@test edit!(edit_undo!) == "one two three" # undo didn't record cursor movement
# TODO: add tests for complete_line, which don't work directly
# pop initial insert of "one two three"
@test edit!(edit_undo!) == ""
@test edit!(edit_undo!) == "" # nothing more to undo (this "beeps")
end
@testset "edit_indent_{left,right}" begin
local buf = IOBuffer()
write(buf, "1\n22\n333")
seek(buf, 0)
@test LineEdit.edit_indent(buf, -1, false) == false
@test transform!(buf->LineEdit.edit_indent(buf, -1, false), buf) == ("1\n22\n333", 0, 0)
@test transform!(buf->LineEdit.edit_indent(buf, +1, false), buf) == (" 1\n22\n333", 1, 0)
@test transform!(buf->LineEdit.edit_indent(buf, +2, false), buf) == (" 1\n22\n333", 3, 0)
@test transform!(buf->LineEdit.edit_indent(buf, -2, false), buf) == (" 1\n22\n333", 1, 0)
seek(buf, 0) # if the cursor is already on the left column, it stays there
@test transform!(buf->LineEdit.edit_indent(buf, -2, false), buf) == ("1\n22\n333", 0, 0)
seek(buf, 3) # between the two "2"
@test transform!(buf->LineEdit.edit_indent(buf, +3, false), buf) == ("1\n 22\n333", 6, 0)
@test transform!(buf->LineEdit.edit_indent(buf, -9, false), buf) == ("1\n22\n333", 3, 0)
seekend(buf) # position 8
@test transform!(buf->LineEdit.edit_indent(buf, +3, false), buf) == ("1\n22\n 333", 11, 0)
@test transform!(buf->LineEdit.edit_indent(buf, -1, false), buf) == ("1\n22\n 333", 10, 0)
@test transform!(buf->LineEdit.edit_indent(buf, -2, false), buf) == ("1\n22\n333", 8, 0)
@test transform!(buf->LineEdit.edit_indent(buf, -1, false), buf) == ("1\n22\n333", 8, 0)
@test transform!(buf->LineEdit.edit_indent(buf, +3, false), buf) == ("1\n22\n 333", 11, 0)
seek(buf, 5) # left column
@test transform!(buf->LineEdit.edit_indent(buf, -2, false), buf) == ("1\n22\n 333", 5, 0)
# multiline tests
@test transform!(buf->LineEdit.edit_indent(buf, -2, true), buf) == ("1\n22\n 333", 5, 0)
@test transform!(buf->LineEdit.edit_indent(buf, +2, true), buf) == (" 1\n 22\n 333", 11, 0)
@test transform!(buf->LineEdit.edit_indent(buf, -1, true), buf) == (" 1\n 22\n 333", 8, 0)
REPL.LineEdit.edit_exchange_point_and_mark(buf)
seek(buf, 5)
@test transform!(buf->LineEdit.edit_indent(buf, -1, true), buf) == (" 1\n22\n 333", 4, 6)
# check that if the mark at the beginning of the line, it is moved when right-indenting,
# which is more natural when the region is active
seek(buf, 0)
buf.mark = 0
# @test transform!(buf->LineEdit.edit_indent(buf, +1, false), buf) == (" 1\n22\n 333", 1, 1)
end
@testset "edit_transpose_lines_{up,down}!" begin
transpose_lines_up!(buf) = LineEdit.edit_transpose_lines_up!(buf, position(buf)=>position(buf))
transpose_lines_up_reg!(buf) = LineEdit.edit_transpose_lines_up!(buf, region(buf))
transpose_lines_down!(buf) = LineEdit.edit_transpose_lines_down!(buf, position(buf)=>position(buf))
transpose_lines_down_reg!(buf) = LineEdit.edit_transpose_lines_down!(buf, region(buf))
local buf
buf = IOBuffer()
write(buf, "l1\nl2\nl3")
seek(buf, 0)
@test transpose_lines_up!(buf) == false
@test transform!(transpose_lines_up!, buf) == ("l1\nl2\nl3", 0, 0)
@test transform!(transpose_lines_down!, buf) == ("l2\nl1\nl3", 3, 0)
@test transpose_lines_down!(buf) == true
@test String(take!(copy(buf))) == "l2\nl3\nl1"
@test transpose_lines_down!(buf) == false
@test String(take!(copy(buf))) == "l2\nl3\nl1" # no change
LineEdit.edit_move_right(buf)
@test transform!(transpose_lines_up!, buf) == ("l2\nl1\nl3", 4, 0)
LineEdit.edit_move_right(buf)
@test transform!(transpose_lines_up!, buf) == ("l1\nl2\nl3", 2, 0)
# multiline
@test transpose_lines_up_reg!(buf) == false
@test transform!(transpose_lines_down_reg!, buf) == ("l2\nl1\nl3", 5, 0)
REPL.LineEdit.edit_exchange_point_and_mark(buf)
seek(buf, 1)
@test transpose_lines_up_reg!(buf) == false
@test transform!(transpose_lines_down_reg!, buf) == ("l3\nl2\nl1", 4, 8)
# check that if the mark is at the beginning of the line, it is moved when transposing down,
# which is necessary when the region is active: otherwise, the line which is moved up becomes
# included in the region
buf.mark = 0
seek(buf, 1)
@test transform!(transpose_lines_down_reg!, buf) == ("l2\nl3\nl1", 4, 3)
end
| 32.425653
| 106
| 0.627612
|
[
"@testset \"edit_word_transpose\" begin\n local buf, mode\n buf = IOBuffer()\n mode = Ref{Symbol}()\n transpose!(i) = transform!(buf -> LineEdit.edit_transpose_words(buf, mode[]),\n buf, i)[1:2]\n\n mode[] = :readline\n edit_insert(buf, \"àbç def gh \")\n @test transpose!(0) == (\"àbç def gh \", 0)\n @test transpose!(1) == (\"àbç def gh \", 1)\n @test transpose!(2) == (\"àbç def gh \", 2)\n @test transpose!(3) == (\"def àbç gh \", 7)\n @test transpose!(4) == (\"àbç def gh \", 7)\n @test transpose!(5) == (\"def àbç gh \", 7)\n @test transpose!(6) == (\"àbç def gh \", 7)\n @test transpose!(7) == (\"àbç gh def \", 11)\n @test transpose!(10) == (\"àbç def gh \", 11)\n @test transpose!(11) == (\"àbç gh def\", 12)\n edit_insert(buf, \" \")\n @test transpose!(13) == (\"àbç def gh\", 13)\n\n take!(buf)\n mode[] = :emacs\n edit_insert(buf, \"àbç def gh \")\n @test transpose!(0) == (\"def àbç gh \", 7)\n @test transpose!(4) == (\"àbç def gh \", 7)\n @test transpose!(5) == (\"àbç gh def \", 11)\n @test transpose!(10) == (\"àbç def gh\", 12)\n edit_insert(buf, \" \")\n @test transpose!(13) == (\"àbç gh def\", 13)\nend",
"@testset \"function prompt indentation\" begin\n local s, term, ps, buf, outbuf, termbuf\n s = new_state()\n term = REPL.LineEdit.terminal(s)\n # default prompt: PromptState.indent should not be set to a final fixed value\n ps::LineEdit.PromptState = s.mode_state[s.current_mode]\n @test ps.indent == -1\n # the prompt is modified afterwards to a function\n ps.p.prompt = let i = 0\n () -> [\"Julia is Fun! > \", \"> \"][mod1(i+=1, 2)] # lengths are 16 and 2\n end\n buf = buffer(ps)\n write(buf, \"begin\\n julia = :fun\\nend\")\n outbuf = IOBuffer()\n termbuf = REPL.Terminals.TerminalBuffer(outbuf)\n LineEdit.refresh_multi_line(termbuf, term, ps)\n @test String(take!(outbuf)) ==\n \"\\r\\e[0K\\e[1mJulia is Fun! > \\e[0m\\r\\e[16Cbegin\\n\" *\n \"\\r\\e[16C julia = :fun\\n\" *\n \"\\r\\e[16Cend\\r\\e[19C\"\n LineEdit.refresh_multi_line(termbuf, term, ps)\n @test String(take!(outbuf)) ==\n \"\\r\\e[0K\\e[1A\\r\\e[0K\\e[1A\\r\\e[0K\\e[1m> \\e[0m\\r\\e[2Cbegin\\n\" *\n \"\\r\\e[2C julia = :fun\\n\" *\n \"\\r\\e[2Cend\\r\\e[5C\"\nend",
"@testset \"shift selection\" begin\n s = new_state()\n edit_insert(s, \"αä🐨\") # for issue #28183\n s.current_action = :unknown\n LineEdit.edit_shift_move(s, LineEdit.edit_move_left)\n @test LineEdit.region(s) == (5=>9)\n LineEdit.edit_shift_move(s, LineEdit.edit_move_left)\n @test LineEdit.region(s) == (2=>9)\n LineEdit.edit_shift_move(s, LineEdit.edit_move_left)\n @test LineEdit.region(s) == (0=>9)\n LineEdit.edit_shift_move(s, LineEdit.edit_move_right)\n @test LineEdit.region(s) == (2=>9)\nend",
"@testset \"tab/backspace alignment feature\" begin\n s = new_state()\n move_left(s, n) = for x = 1:n\n LineEdit.edit_move_left(s)\n end\n\n edit_insert(s, \"for x=1:10\\n\")\n LineEdit.edit_tab(s)\n @test content(s) == \"for x=1:10\\n \"\n LineEdit.edit_backspace(s, true, false)\n @test content(s) == \"for x=1:10\\n\"\n edit_insert(s, \" \")\n @test position(s) == 13\n LineEdit.edit_tab(s)\n @test content(s) == \"for x=1:10\\n \"\n edit_insert(s, \" \")\n LineEdit.edit_backspace(s, true, false)\n @test content(s) == \"for x=1:10\\n \"\n edit_insert(s, \"éé=3 \")\n LineEdit.edit_tab(s)\n @test content(s) == \"for x=1:10\\n éé=3 \"\n LineEdit.edit_backspace(s, true, false)\n @test content(s) == \"for x=1:10\\n éé=3\"\n edit_insert(s, \"\\n 1∉x \")\n LineEdit.edit_tab(s)\n @test content(s) == \"for x=1:10\\n éé=3\\n 1∉x \"\n LineEdit.edit_backspace(s, false, false)\n @test content(s) == \"for x=1:10\\n éé=3\\n 1∉x \"\n LineEdit.edit_backspace(s, true, false)\n @test content(s) == \"for x=1:10\\n éé=3\\n 1∉x \"\n LineEdit.edit_move_word_left(s)\n LineEdit.edit_tab(s)\n @test content(s) == \"for x=1:10\\n éé=3\\n 1∉x \"\n LineEdit.move_line_start(s)\n @test position(s) == 22\n LineEdit.edit_tab(s, true)\n @test content(s) == \"for x=1:10\\n éé=3\\n 1∉x \"\n @test position(s) == 30\n LineEdit.edit_move_left(s)\n @test position(s) == 29\n LineEdit.edit_backspace(s, true, true)\n @test content(s) == \"for x=1:10\\n éé=3\\n 1∉x \"\n @test position(s) == 26\n LineEdit.edit_tab(s, false) # same as edit_tab(s, true) here\n @test position(s) == 30\n move_left(s, 6)\n @test position(s) == 24\n LineEdit.edit_backspace(s, true, true)\n @test content(s) == \"for x=1:10\\n éé=3\\n 1∉x \"\n @test position(s) == 22\n LineEdit.edit_kill_line(s)\n edit_insert(s, ' '^10)\n move_left(s, 7)\n @test content(s) == \"for x=1:10\\n éé=3\\n \"\n @test position(s) == 25\n LineEdit.edit_tab(s, true, false)\n @test position(s) == 32\n move_left(s, 7)\n LineEdit.edit_tab(s, true, true)\n @test position(s) == 26\n @test content(s) == \"for x=1:10\\n éé=3\\n \"\n # test again the same, when there is a next line\n edit_insert(s, \" \\nend\")\n move_left(s, 11)\n @test position(s) == 25\n LineEdit.edit_tab(s, true, false)\n @test position(s) == 32\n move_left(s, 7)\n LineEdit.edit_tab(s, true, true)\n @test position(s) == 26\n @test content(s) == \"for x=1:10\\n éé=3\\n \\nend\"\nend",
"@testset \"newline alignment feature\" begin\n s = new_state()\n edit_insert(s, \"for x=1:10\\n é = 1\")\n LineEdit.edit_insert_newline(s)\n @test content(s) == \"for x=1:10\\n é = 1\\n \"\n edit_insert(s, \" b = 2\")\n LineEdit.edit_insert_newline(s)\n @test content(s) == \"for x=1:10\\n é = 1\\n b = 2\\n \"\n # after an empty line, should still insert the expected number of spaces\n LineEdit.edit_insert_newline(s)\n @test content(s) == \"for x=1:10\\n é = 1\\n b = 2\\n \\n \"\n LineEdit.edit_insert_newline(s, 0)\n @test content(s) == \"for x=1:10\\n é = 1\\n b = 2\\n \\n \\n\"\n LineEdit.edit_insert_newline(s, 2)\n @test content(s) == \"for x=1:10\\n é = 1\\n b = 2\\n \\n \\n\\n \"\n # test when point before first letter of the line\n for i=6:10\n LineEdit.edit_clear(s)\n edit_insert(s, \"begin\\n x\")\n seek(LineEdit.buffer(s), i)\n LineEdit.edit_insert_newline(s)\n @test content(s) == \"begin\\n\" * ' '^(i-6) * \"\\n x\"\n end\nend",
"@testset \"change case on the right\" begin\n local buf = IOBuffer()\n edit_insert(buf, \"aa bb CC\")\n seekstart(buf)\n LineEdit.edit_upper_case(buf)\n LineEdit.edit_title_case(buf)\n @test String(take!(copy(buf))) == \"AA Bb CC\"\n @test position(buf) == 5\n LineEdit.edit_lower_case(buf)\n @test String(take!(copy(buf))) == \"AA Bb cc\"\nend",
"@testset \"kill ring\" begin\n local buf\n s = new_state()\n buf = buffer(s)\n edit_insert(s, \"ça ≡ nothing\")\n @test transform!(LineEdit.edit_copy_region, s) == (\"ça ≡ nothing\", 12, 0)\n @test s.kill_ring[end] == \"ça ≡ nothing\"\n @test transform!(LineEdit.edit_exchange_point_and_mark, s)[2:3] == (0, 12)\n charseek(buf, 8); setmark(s)\n charseek(buf, 1)\n @test transform!(LineEdit.edit_kill_region, s) == (\"çhing\", 1, 1)\n @test s.kill_ring[end] == \"a ≡ not\"\n charseek(buf, 0)\n @test transform!(LineEdit.edit_yank, s) == (\"a ≡ notçhing\", 7, 0)\n s.last_action = :unknown\n # next action will fail, as yank-pop doesn't know a yank was just issued\n @test transform!(LineEdit.edit_yank_pop, s) == (\"a ≡ notçhing\", 7, 0)\n s.last_action = :edit_yank\n # now this should work:\n @test transform!(LineEdit.edit_yank_pop, s) == (\"ça ≡ nothingçhing\", 12, 0)\n @test s.kill_idx == 1\n LineEdit.edit_kill_line(s)\n @test s.kill_ring[end] == \"çhing\"\n @test s.kill_idx == 3\n # check that edit_yank_pop works when passing require_previous_yank=false (#23635)\n s.last_action = :unknown\n @test transform!(s->LineEdit.edit_yank_pop(s, false), s) == (\"ça ≡ nothinga ≡ not\", 19, 12)\n\n # repetition (concatenation of killed strings\n edit_insert(s, \"A B C\")\n LineEdit.edit_delete_prev_word(s)\n s.key_repeats = 1\n LineEdit.edit_delete_prev_word(s)\n s.key_repeats = 0\n @test s.kill_ring[end] == \"B C\"\n LineEdit.edit_yank(s)\n LineEdit.edit_werase(s)\n @test s.kill_ring[end] == \"C\"\n s.key_repeats = 1\n LineEdit.edit_werase(s)\n s.key_repeats = 0\n @test s.kill_ring[end] == \"B C\"\n LineEdit.edit_yank(s)\n LineEdit.edit_move_word_left(s)\n LineEdit.edit_move_word_left(s)\n LineEdit.edit_delete_next_word(s)\n @test s.kill_ring[end] == \"B\"\n s.key_repeats = 1\n LineEdit.edit_delete_next_word(s)\n s.key_repeats = 0\n @test s.kill_ring[end] == \"B C\"\n\n # edit_kill_line_backwards\n LineEdit.edit_clear(s)\n edit_insert(s, \"begin\\n a=1\\n b=2\")\n LineEdit.edit_kill_line_backwards(s)\n @test s.kill_ring[end] == \" b=2\"\n s.key_repeats = 1\n LineEdit.edit_kill_line_backwards(s)\n @test s.kill_ring[end] == \"\\n b=2\"\n LineEdit.edit_kill_line_backwards(s)\n @test s.kill_ring[end] == \" a=1\\n b=2\"\n s.key_repeats = 0\nend",
"@testset \"undo\" begin\n s = new_state()\n edit!(f) = transform!(f, s)[1]\n edit_undo! = LineEdit.edit_undo!\n edit_redo! = LineEdit.edit_redo!\n\n edit_insert(s, \"one two three\")\n\n @test edit!(LineEdit.edit_delete_prev_word) == \"one two \"\n @test edit!(edit_undo!) == \"one two three\"\n @test edit!(edit_redo!) == \"one two \"\n @test edit!(edit_undo!) == \"one two three\"\n\n edit_insert(s, \" four\")\n @test edit!(s->edit_insert(s, \" five\")) == \"one two three four five\"\n @test edit!(edit_undo!) == \"one two three four\"\n @test edit!(edit_undo!) == \"one two three\"\n @test edit!(edit_redo!) == \"one two three four\"\n @test edit!(edit_redo!) == \"one two three four five\"\n @test edit!(edit_undo!) == \"one two three four\"\n @test edit!(edit_undo!) == \"one two three\"\n\n @test edit!(LineEdit.edit_clear) == \"\"\n @test edit!(LineEdit.edit_clear) == \"\" # should not be saved twice\n @test edit!(edit_undo!) == \"one two three\"\n\n @test edit!(LineEdit.edit_insert_newline) == \"one two three\\n\"\n @test edit!(edit_undo!) == \"one two three\"\n\n LineEdit.edit_move_left(s)\n LineEdit.edit_move_left(s)\n @test edit!(LineEdit.edit_transpose_chars) == \"one two there\"\n @test edit!(edit_undo!) == \"one two three\"\n @test edit!(LineEdit.edit_transpose_words) == \"one three two\"\n @test edit!(edit_undo!) == \"one two three\"\n\n LineEdit.move_line_start(s)\n @test edit!(LineEdit.edit_kill_line) == \"\"\n @test edit!(edit_undo!) == \"one two three\"\n # undo stack not updated if killing nothing:\n LineEdit.move_line_start(s)\n LineEdit.edit_kill_line(s)\n LineEdit.edit_kill_line(s) # no effect\n @test edit!(edit_undo!) == \"one two three\"\n\n LineEdit.move_line_end(s)\n @test edit!(LineEdit.edit_kill_line_backwards) == \"\"\n @test edit!(edit_undo!) == \"one two three\"\n\n LineEdit.move_line_start(s)\n LineEdit.edit_kill_line(s)\n LineEdit.edit_yank(s)\n @test edit!(LineEdit.edit_yank) == \"one two threeone two three\"\n @test edit!(edit_undo!) == \"one two three\"\n @test edit!(edit_undo!) == \"\"\n @test edit!(edit_undo!) == \"one two three\"\n\n LineEdit.setmark(s)\n LineEdit.edit_move_word_right(s)\n @test edit!(LineEdit.edit_kill_region) == \" two three\"\n @test edit!(LineEdit.edit_yank) == \"one two three\"\n @test edit!(LineEdit.edit_yank_pop) == \"one two three two three\"\n @test edit!(edit_undo!) == \"one two three\"\n @test edit!(edit_undo!) == \" two three\"\n @test edit!(edit_undo!) == \"one two three\"\n\n LineEdit.move_line_end(s)\n LineEdit.edit_backspace(s, false, false)\n LineEdit.edit_backspace(s, false, false)\n @test edit!(s->LineEdit.edit_backspace(s, false, false)) == \"one two th\"\n @test edit!(edit_undo!) == \"one two thr\"\n @test edit!(edit_undo!) == \"one two thre\"\n @test edit!(edit_undo!) == \"one two three\"\n\n LineEdit.push_undo(s) # TODO: incorporate push_undo into edit_splice! ?\n LineEdit.edit_splice!(s, 4 => 7, \"stott\")\n @test content(s) == \"one stott three\"\n s.last_action = :not_undo\n @test edit!(edit_undo!) == \"one two three\"\n\n LineEdit.edit_move_left(s)\n LineEdit.edit_move_left(s)\n LineEdit.edit_move_left(s)\n @test edit!(LineEdit.edit_delete) == \"one two thee\"\n @test edit!(edit_undo!) == \"one two three\"\n\n LineEdit.edit_move_word_left(s)\n LineEdit.edit_werase(s)\n @test edit!(LineEdit.edit_delete_next_word) == \"one \"\n @test edit!(edit_undo!) == \"one three\"\n @test edit!(edit_undo!) == \"one two three\"\n @test edit!(edit_redo!) == \"one three\"\n @test edit!(edit_redo!) == \"one \"\n @test edit!(edit_redo!) == \"one \" # nothing more to redo (this \"beeps\")\n @test edit!(edit_undo!) == \"one three\"\n @test edit!(edit_undo!) == \"one two three\"\n\n LineEdit.move_line_start(s)\n @test edit!(LineEdit.edit_upper_case) == \"ONE two three\"\n LineEdit.move_line_start(s)\n @test edit!(LineEdit.edit_lower_case) == \"one two three\"\n @test edit!(LineEdit.edit_title_case) == \"one Two three\"\n @test edit!(edit_undo!) == \"one two three\"\n @test edit!(edit_undo!) == \"ONE two three\"\n @test edit!(edit_undo!) == \"one two three\"\n\n LineEdit.move_line_end(s)\n edit_insert(s, \" \")\n @test edit!(LineEdit.edit_tab) == \"one two three \"\n @test edit!(edit_undo!) == \"one two three \"\n @test edit!(edit_undo!) == \"one two three\"\n LineEdit.move_line_start(s)\n edit_insert(s, \" \")\n LineEdit.move_line_start(s)\n @test edit!(s->LineEdit.edit_tab(s, true, true)) == \" one two three\" # tab moves cursor to position 2\n @test edit!(edit_undo!) == \"one two three\" # undo didn't record cursor movement\n # TODO: add tests for complete_line, which don't work directly\n\n # pop initial insert of \"one two three\"\n @test edit!(edit_undo!) == \"\"\n @test edit!(edit_undo!) == \"\" # nothing more to undo (this \"beeps\")\nend",
"@testset \"edit_indent_{left,right}\" begin\n local buf = IOBuffer()\n write(buf, \"1\\n22\\n333\")\n seek(buf, 0)\n @test LineEdit.edit_indent(buf, -1, false) == false\n @test transform!(buf->LineEdit.edit_indent(buf, -1, false), buf) == (\"1\\n22\\n333\", 0, 0)\n @test transform!(buf->LineEdit.edit_indent(buf, +1, false), buf) == (\" 1\\n22\\n333\", 1, 0)\n @test transform!(buf->LineEdit.edit_indent(buf, +2, false), buf) == (\" 1\\n22\\n333\", 3, 0)\n @test transform!(buf->LineEdit.edit_indent(buf, -2, false), buf) == (\" 1\\n22\\n333\", 1, 0)\n seek(buf, 0) # if the cursor is already on the left column, it stays there\n @test transform!(buf->LineEdit.edit_indent(buf, -2, false), buf) == (\"1\\n22\\n333\", 0, 0)\n seek(buf, 3) # between the two \"2\"\n @test transform!(buf->LineEdit.edit_indent(buf, +3, false), buf) == (\"1\\n 22\\n333\", 6, 0)\n @test transform!(buf->LineEdit.edit_indent(buf, -9, false), buf) == (\"1\\n22\\n333\", 3, 0)\n seekend(buf) # position 8\n @test transform!(buf->LineEdit.edit_indent(buf, +3, false), buf) == (\"1\\n22\\n 333\", 11, 0)\n @test transform!(buf->LineEdit.edit_indent(buf, -1, false), buf) == (\"1\\n22\\n 333\", 10, 0)\n @test transform!(buf->LineEdit.edit_indent(buf, -2, false), buf) == (\"1\\n22\\n333\", 8, 0)\n @test transform!(buf->LineEdit.edit_indent(buf, -1, false), buf) == (\"1\\n22\\n333\", 8, 0)\n @test transform!(buf->LineEdit.edit_indent(buf, +3, false), buf) == (\"1\\n22\\n 333\", 11, 0)\n seek(buf, 5) # left column\n @test transform!(buf->LineEdit.edit_indent(buf, -2, false), buf) == (\"1\\n22\\n 333\", 5, 0)\n # multiline tests\n @test transform!(buf->LineEdit.edit_indent(buf, -2, true), buf) == (\"1\\n22\\n 333\", 5, 0)\n @test transform!(buf->LineEdit.edit_indent(buf, +2, true), buf) == (\" 1\\n 22\\n 333\", 11, 0)\n @test transform!(buf->LineEdit.edit_indent(buf, -1, true), buf) == (\" 1\\n 22\\n 333\", 8, 0)\n REPL.LineEdit.edit_exchange_point_and_mark(buf)\n seek(buf, 5)\n @test transform!(buf->LineEdit.edit_indent(buf, -1, true), buf) == (\" 1\\n22\\n 333\", 4, 6)\n\n # check that if the mark at the beginning of the line, it is moved when right-indenting,\n # which is more natural when the region is active\n seek(buf, 0)\n buf.mark = 0\n# @test transform!(buf->LineEdit.edit_indent(buf, +1, false), buf) == (\" 1\\n22\\n 333\", 1, 1)\nend",
"@testset \"edit_transpose_lines_{up,down}!\" begin\n transpose_lines_up!(buf) = LineEdit.edit_transpose_lines_up!(buf, position(buf)=>position(buf))\n transpose_lines_up_reg!(buf) = LineEdit.edit_transpose_lines_up!(buf, region(buf))\n transpose_lines_down!(buf) = LineEdit.edit_transpose_lines_down!(buf, position(buf)=>position(buf))\n transpose_lines_down_reg!(buf) = LineEdit.edit_transpose_lines_down!(buf, region(buf))\n\n local buf\n buf = IOBuffer()\n\n write(buf, \"l1\\nl2\\nl3\")\n seek(buf, 0)\n @test transpose_lines_up!(buf) == false\n @test transform!(transpose_lines_up!, buf) == (\"l1\\nl2\\nl3\", 0, 0)\n @test transform!(transpose_lines_down!, buf) == (\"l2\\nl1\\nl3\", 3, 0)\n @test transpose_lines_down!(buf) == true\n @test String(take!(copy(buf))) == \"l2\\nl3\\nl1\"\n @test transpose_lines_down!(buf) == false\n @test String(take!(copy(buf))) == \"l2\\nl3\\nl1\" # no change\n LineEdit.edit_move_right(buf)\n @test transform!(transpose_lines_up!, buf) == (\"l2\\nl1\\nl3\", 4, 0)\n LineEdit.edit_move_right(buf)\n @test transform!(transpose_lines_up!, buf) == (\"l1\\nl2\\nl3\", 2, 0)\n\n # multiline\n @test transpose_lines_up_reg!(buf) == false\n @test transform!(transpose_lines_down_reg!, buf) == (\"l2\\nl1\\nl3\", 5, 0)\n REPL.LineEdit.edit_exchange_point_and_mark(buf)\n seek(buf, 1)\n @test transpose_lines_up_reg!(buf) == false\n @test transform!(transpose_lines_down_reg!, buf) == (\"l3\\nl2\\nl1\", 4, 8)\n\n # check that if the mark is at the beginning of the line, it is moved when transposing down,\n # which is necessary when the region is active: otherwise, the line which is moved up becomes\n # included in the region\n buf.mark = 0\n seek(buf, 1)\n @test transform!(transpose_lines_down_reg!, buf) == (\"l2\\nl3\\nl1\", 4, 3)\n\nend"
] |
f7d100424158c40fab8a56ecc76f0460d2477cb5
| 4,306
|
jl
|
Julia
|
test/runtests.jl
|
asinghvi17/ColorSchemes.jl
|
cb4d8314c4327d98b94ff7bc18826748e078de6d
|
[
"Apache-2.0",
"CC0-1.0"
] | null | null | null |
test/runtests.jl
|
asinghvi17/ColorSchemes.jl
|
cb4d8314c4327d98b94ff7bc18826748e078de6d
|
[
"Apache-2.0",
"CC0-1.0"
] | null | null | null |
test/runtests.jl
|
asinghvi17/ColorSchemes.jl
|
cb4d8314c4327d98b94ff7bc18826748e078de6d
|
[
"Apache-2.0",
"CC0-1.0"
] | null | null | null |
using Test, Colors, ColorSchemes, ColorTypes, FixedPointNumbers
monalisa = ColorScheme([
RGB(0.05482025926320272, 0.016508952654741622, 0.019315160361063788),
RGB(0.07508160782698388, 0.034110215845969745, 0.039708343938094984),
RGB(0.10884977211887092, 0.033667530751245296, 0.026120424375656533),
RGB(0.10025110094110237, 0.05342427394738222, 0.04975936729231899),
RGB(0.11004568002009293, 0.06764950003139521, 0.07202128202310687),
RGB(0.1520114897984492, 0.06721701384356317, 0.04758612657624729),
RGB(0.16121466572057147, 0.10737190368841328, 0.07491505937992286),
RGB(0.2272468746270438, 0.09450818887496519, 0.053122482545649836),
RGB(0.24275776450376843, 0.14465569383748178, 0.09254885719488251),
RGB(0.19832488479851235, 0.16827798680930195, 0.08146721610879516),
RGB(0.29030547394827216, 0.1566704731433784, 0.06955958896758961),
RGB(0.3486958875330028, 0.14413808439049522, 0.06517845643634491),
RGB(0.2631529920611145, 0.22896210929698424, 0.1119250237167965),
RGB(0.35775151767110114, 0.23955578484799914, 0.08566681526152695),
RGB(0.42895506355552904, 0.19814294026377038, 0.07315576139822164),
RGB(0.3359280058835734, 0.30177882691623686, 0.14764230985832),
RGB(0.5168174153887967, 0.2588008525490645, 0.07751817567374263),
RGB(0.44056726473192726, 0.3387984774995975, 0.10490250831857457),
RGB(0.4048595970607235, 0.40823989479512734, 0.2096109034699151),
RGB(0.619694338941659, 0.33787470822764315, 0.0871136546089913),
RGB(0.5108290351302369, 0.41506713362977327, 0.13590312315603137),
RGB(0.5272516131642648, 0.4706039514608196, 0.21392546020040532),
RGB(0.5942622209175139, 0.47822315473126586, 0.14678522310513448),
RGB(0.735266714513005, 0.4318652289706696, 0.1049661472744881),
RGB(0.6201870982552801, 0.5227924127640037, 0.2167074150596878),
RGB(0.6929049533440698, 0.5663098519207086, 0.18551505068207655),
RGB(0.6814114992549445, 0.5814898147520997, 0.27039081549715527),
RGB(0.8500397772474145, 0.5401215248181611, 0.1362117676724628),
RGB(0.7575520588269891, 0.6334254649343621, 0.25145144950124687),
RGB(0.8164723313500291, 0.6970150665478066, 0.32242062463720045),
RGB(0.9330273170314637, 0.6651641943114455, 0.19865164906805746),
RGB(0.9724409077178674, 0.7907008712807734, 0.2851364857083522)],
"testing",
"colors from Leonardo da Vinci's Mona Lisa")
@testset "basic tests" begin
@test length(monalisa) == 32
@test length(monalisa.colors) == 32
# test that sampling schemes yield different values
@test get(monalisa, 0.0) != get(monalisa, 0.5)
end
# getinverse() tests are now in ColorSchemes
@testset "conversion tests" begin
# convert an Array{T,2} to an RGB image
tmp = get(monalisa, rand(10, 10))
@test typeof(tmp) == Array{ColorTypes.RGB{Float64}, 2}
# test conversion with default clamp
x = [0.0 1.0 ; -1.0 2.0]
y = get(monalisa, x)
@test y[1,1] == y[2,1]
@test y[1,2] == y[2,2]
# test conversion with symbol clamp
y2 = get(monalisa, x, :clamp)
@test y2 == y
# test conversion with symbol extrema
y2=get(monalisa, x, :extrema)
@test y2[2,1] == y[1, 1] # Minimum now becomes one edge of ColorScheme
@test y2[2,2] == y[1, 2] # Maximum now becomes other edge of ColorScheme
@test y2[1,1] !== y2[2, 1] # Inbetween values or now different
# test conversion with manually supplied range
y3=get(monalisa, x, (-1.0, 2.0))
@test y3 == y2
# test gray value #23
c = get(monalisa, Gray(N0f16(1.0)))
@test typeof(c) == RGB{Float64}
@test c.r > 0.95
@test c.g > 0.75
@test c.b < 0.3
c = get(monalisa, Gray24(N0f16(1.0)))
@test typeof(c) == RGB{Float64}
@test c.r > 0.95
# Booleans
@test get(monalisa, 0.0) == get(monalisa, false)
@test get(monalisa, 1.0) == get(monalisa, true)
end
@testset "misc tests" begin
# test with steplen (#17)
r = range(0, stop=5, length=10)
y = get(monalisa, r)
y2 = get(monalisa, collect(r))
@test y == y2
# test for specific value
val = 0.2
y = get(monalisa, [val])
y2 = get(monalisa, val)
@test y2 == y[1]
col = get(reverse(monalisa), 0.0)
@test col.r > 0.9
@test col.g > 0.7
@test col.b > 0.2
end
| 41.009524
| 78
| 0.699721
|
[
"@testset \"basic tests\" begin\n @test length(monalisa) == 32\n @test length(monalisa.colors) == 32\n # test that sampling schemes yield different values\n @test get(monalisa, 0.0) != get(monalisa, 0.5)\nend",
"@testset \"conversion tests\" begin\n # convert an Array{T,2} to an RGB image\n tmp = get(monalisa, rand(10, 10))\n @test typeof(tmp) == Array{ColorTypes.RGB{Float64}, 2}\n\n # test conversion with default clamp\n x = [0.0 1.0 ; -1.0 2.0]\n y = get(monalisa, x)\n @test y[1,1] == y[2,1]\n @test y[1,2] == y[2,2]\n\n # test conversion with symbol clamp\n y2 = get(monalisa, x, :clamp)\n @test y2 == y\n\n # test conversion with symbol extrema\n y2=get(monalisa, x, :extrema)\n @test y2[2,1] == y[1, 1] # Minimum now becomes one edge of ColorScheme\n @test y2[2,2] == y[1, 2] # Maximum now becomes other edge of ColorScheme\n @test y2[1,1] !== y2[2, 1] # Inbetween values or now different\n\n # test conversion with manually supplied range\n y3=get(monalisa, x, (-1.0, 2.0))\n @test y3 == y2\n\n # test gray value #23\n c = get(monalisa, Gray(N0f16(1.0)))\n @test typeof(c) == RGB{Float64}\n @test c.r > 0.95\n @test c.g > 0.75\n @test c.b < 0.3\n c = get(monalisa, Gray24(N0f16(1.0)))\n @test typeof(c) == RGB{Float64}\n @test c.r > 0.95\n # Booleans\n @test get(monalisa, 0.0) == get(monalisa, false)\n @test get(monalisa, 1.0) == get(monalisa, true)\nend",
"@testset \"misc tests\" begin\n # test with steplen (#17)\n r = range(0, stop=5, length=10)\n y = get(monalisa, r)\n y2 = get(monalisa, collect(r))\n @test y == y2\n\n # test for specific value\n val = 0.2\n y = get(monalisa, [val])\n y2 = get(monalisa, val)\n @test y2 == y[1]\n\n col = get(reverse(monalisa), 0.0)\n @test col.r > 0.9\n @test col.g > 0.7\n @test col.b > 0.2\nend"
] |
f7d3ff4ee03842b391b967e0ebc86e413e6959cb
| 1,216
|
jl
|
Julia
|
test/test_ensemble.jl
|
quinnj/AMLPipelineBase.jl
|
ab244b3934d82c9036e309ce26e9797ffa89a1e4
|
[
"MIT"
] | null | null | null |
test/test_ensemble.jl
|
quinnj/AMLPipelineBase.jl
|
ab244b3934d82c9036e309ce26e9797ffa89a1e4
|
[
"MIT"
] | null | null | null |
test/test_ensemble.jl
|
quinnj/AMLPipelineBase.jl
|
ab244b3934d82c9036e309ce26e9797ffa89a1e4
|
[
"MIT"
] | null | null | null |
module TestEnsembleMethods
using Test
using Random
using AMLPipelineBase
using DataFrames
function generateXY()
Random.seed!(123)
iris = getiris()
indx = Random.shuffle(1:nrow(iris))
features=iris[indx,1:4]
sp = iris[indx,5] |> Vector
(features,sp)
end
function getprediction(model,features,output)
res = fit_transform!(model,features,output)
sum(res .== output)/length(output)*100
end
function test_ensembles()
tstfeatures,tstoutput = generateXY()
models = [VoteEnsemble(),StackEnsemble(),BestLearner()]
for model in models
@test getprediction(model,tstfeatures,tstoutput) > 90.0
end
end
@testset "Ensemble learners" begin
Random.seed!(123)
test_ensembles()
end
function test_vararg()
rf = RandomForest()
ada = Adaboost()
pt = PrunedTree()
X,Y = generateXY()
vote = VoteEnsemble(rf,ada,pt)
stack = StackEnsemble(rf,ada,pt)
best = BestLearner(rf,ada,pt)
v=fit_transform!(vote,X,Y)
s=fit_transform!(stack,X,Y)
p=fit_transform!(best,X,Y)
@test score(:accuracy,v,Y) > 90.0
@test score(:accuracy,s,Y) > 90.0
@test score(:accuracy,p,Y) > 90.0
end # module
@testset "Vararg Ensemble Test" begin
Random.seed!(123)
test_vararg()
end
end
| 21.714286
| 59
| 0.702303
|
[
"@testset \"Ensemble learners\" begin\n Random.seed!(123)\n test_ensembles()\nend",
"@testset \"Vararg Ensemble Test\" begin\n Random.seed!(123)\n test_vararg()\nend"
] |
f7d7e4492e2c22a8656ff9737d6962f470752ddc
| 19,228
|
jl
|
Julia
|
test/runtests.jl
|
UnofficialJuliaMirror/OffsetArrays.jl-6fe1bfb0-de20-5000-8ca7-80f57d26f881
|
950bb889753bfbdcd5313b6f1eb814b28f1a26c2
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
UnofficialJuliaMirror/OffsetArrays.jl-6fe1bfb0-de20-5000-8ca7-80f57d26f881
|
950bb889753bfbdcd5313b6f1eb814b28f1a26c2
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
UnofficialJuliaMirror/OffsetArrays.jl-6fe1bfb0-de20-5000-8ca7-80f57d26f881
|
950bb889753bfbdcd5313b6f1eb814b28f1a26c2
|
[
"MIT"
] | null | null | null |
using OffsetArrays
using Test
using DelimitedFiles
using OffsetArrays: IdentityUnitRange, no_offset_view
using CatIndices: BidirectionalVector
@test isempty(detect_ambiguities(OffsetArrays, Base, Core))
@testset "Single-entry arrays in dims 0:5" begin
for n = 0:5
for z in (OffsetArray(ones(Int,ntuple(d->1,n)), ntuple(x->x-1,n)),
fill!(OffsetArray{Float64}(undef, ntuple(x->x:x, n)), 1),
fill!(OffsetArray{Float64}(undef, ntuple(x->x:x, n)...), 1),
fill!(OffsetArray{Float64,n}(undef, ntuple(x->x:x, n)), 1),
fill!(OffsetArray{Float64,n}(undef, ntuple(x->x:x, n)...), 1))
@test length(LinearIndices(z)) == 1
@test axes(z) == ntuple(x->x:x, n)
@test z[1] == 1
end
end
a0 = reshape([3])
a = OffsetArray(a0)
@test axes(a) == ()
@test ndims(a) == 0
@test a[] == 3
end
@testset "OffsetVector constructors" begin
local v = rand(5)
@test OffsetVector(v, -2) == OffsetArray(v, -2)
@test OffsetVector(v, -2:2) == OffsetArray(v, -2:2)
@test typeof(OffsetVector{Float64}(undef, -2:2)) == typeof(OffsetArray{Float64}(undef, -2:2))
end
@testset "undef, missing, and nothing constructors" begin
y = OffsetArray{Float32}(undef, (IdentityUnitRange(-1:1),))
@test axes(y) === (IdentityUnitRange(-1:1),)
for (T, t) in ((Missing, missing), (Nothing, nothing))
@test !isassigned(OffsetArray{Union{T,Vector{Int}}}(undef, -1:1, -1:1), -1, -1)
@test OffsetArray{Union{T,Vector{Int}}}(t, -1:1, -1:1)[-1, -1] === t
@test !isassigned(OffsetVector{Union{T,Vector{Int}}}(undef, -1:1), -1)
@test OffsetVector{Union{T,Vector{Int}}}(t, -1:1)[-1] === t
end
end
@testset "high dimensionality" begin
y = OffsetArray{Float64}(undef, -1:1, -7:7, -128:512, -5:5, -1:1, -3:3, -2:2, -1:1)
@test axes(y) == (-1:1, -7:7, -128:512, -5:5, -1:1, -3:3, -2:2, -1:1)
y[-1,-7,-128,-5,-1,-3,-2,-1] = 14
y[-1,-7,-128,-5,-1,-3,-2,-1] += 5
@test y[-1,-7,-128,-5,-1,-3,-2,-1] == 19
end
@testset "Offset range construction" begin
r = -2:5
y = OffsetArray(r, r)
@test axes(y) == (r,)
y = OffsetArray(r, (r,))
@test axes(y) == (r,)
end
@testset "Traits" begin
A0 = [1 3; 2 4]
A = OffsetArray(A0, (-1,2)) # IndexLinear
S = OffsetArray(view(A0, 1:2, 1:2), (-1,2)) # IndexCartesian
@test axes(A) == axes(S) == (0:1, 3:4)
@test size(A) == size(A0)
@test size(A, 1) == size(A0, 1)
@test length(A) == length(A0)
@test A == OffsetArray(A0, 0:1, 3:4)
@test_throws DimensionMismatch OffsetArray(A0, 0:2, 3:4)
@test_throws DimensionMismatch OffsetArray(A0, 0:1, 2:4)
end
@testset "Scalar indexing" begin
A0 = [1 3; 2 4]
A = OffsetArray(A0, (-1,2))
S = OffsetArray(view(A0, 1:2, 1:2), (-1,2))
@test @inferred(A[0,3]) == @inferred(A[0,3,1]) == @inferred(A[1]) == @inferred(S[0,3]) == @inferred(S[0,3,1]) == @inferred(S[1]) == 1
@test A[1,3] == A[1,3,1] == A[2] == S[1,3] == S[1,3,1] == S[2] == 2
@test A[0,4] == A[0,4,1] == A[3] == S[0,4] == S[0,4,1] == S[3] == 3
@test A[1,4] == A[1,4,1] == A[4] == S[1,4] == S[1,4,1] == S[4] == 4
@test @inbounds(A[0,3]) == @inbounds(A[0,3,1]) == @inbounds(A[1]) == @inbounds(S[0,3]) == @inbounds(S[0,3,1]) == @inbounds(S[1]) == 1
@test @inbounds(A[1,3]) == @inbounds(A[1,3,1]) == @inbounds(A[2]) == @inbounds(S[1,3]) == @inbounds(S[1,3,1]) == @inbounds(S[2]) == 2
@test @inbounds(A[0,4]) == @inbounds(A[0,4,1]) == @inbounds(A[3]) == @inbounds(S[0,4]) == @inbounds(S[0,4,1]) == @inbounds(S[3]) == 3
@test @inbounds(A[1,4]) == @inbounds(A[1,4,1]) == @inbounds(A[4]) == @inbounds(S[1,4]) == @inbounds(S[1,4,1]) == @inbounds(S[4]) == 4
@test_throws BoundsError A[1,1]
@test_throws BoundsError S[1,1]
@test_throws BoundsError A[0,3,2]
@test_throws BoundsError A[0,3,0]
Ac = copy(A)
Ac[0,3] = 10
@test Ac[0,3] == 10
Ac[0,3,1] = 11
@test Ac[0,3] == 11
@inbounds Ac[0,3,1] = 12
@test Ac[0,3] == 12
end
@testset "Vector indexing" begin
A0 = [1 3; 2 4]
A = OffsetArray(A0, (-1,2))
S = OffsetArray(view(A0, 1:2, 1:2), (-1,2))
@test A[:, 3] == S[:, 3] == OffsetArray([1,2], (A.offsets[1],))
@test A[:, 4] == S[:, 4] == OffsetArray([3,4], (A.offsets[1],))
@test_throws BoundsError A[:, 1]
@test_throws BoundsError S[:, 1]
@test A[0, :] == S[0, :] == OffsetArray([1,3], (A.offsets[2],))
@test A[1, :] == S[1, :] == OffsetArray([2,4], (A.offsets[2],))
@test_throws BoundsError A[2, :]
@test_throws BoundsError S[2, :]
@test A[0:1, 3] == S[0:1, 3] == [1,2]
@test A[[1,0], 3] == S[[1,0], 3] == [2,1]
@test A[0, 3:4] == S[0, 3:4] == [1,3]
@test A[1, [4,3]] == S[1, [4,3]] == [4,2]
@test A[:, :] == S[:, :] == A
end
@testset "Vector indexing with offset ranges" begin
r = OffsetArray(8:10, -1:1)
r1 = r[0:1]
@test r1 === 9:10
r1 = (8:10)[OffsetArray(1:2, -5:-4)]
@test axes(r1) === (IdentityUnitRange(-5:-4),)
@test parent(r1) === 8:9
r1 = OffsetArray(8:10, -1:1)[OffsetArray(0:1, -5:-4)]
@test axes(r1) === (IdentityUnitRange(-5:-4),)
@test parent(r1) === 9:10
end
@testset "CartesianIndexing" begin
A0 = [1 3; 2 4]
A = OffsetArray(A0, (-1,2))
S = OffsetArray(view(A0, 1:2, 1:2), (-1,2))
@test A[CartesianIndex((0,3))] == S[CartesianIndex((0,3))] == 1
@test A[CartesianIndex((0,3)),1] == S[CartesianIndex((0,3)),1] == 1
@test @inbounds(A[CartesianIndex((0,3))]) == @inbounds(S[CartesianIndex((0,3))]) == 1
@test @inbounds(A[CartesianIndex((0,3)),1]) == @inbounds(S[CartesianIndex((0,3)),1]) == 1
@test_throws BoundsError A[CartesianIndex(1,1)]
@test_throws BoundsError A[CartesianIndex(1,1),0]
@test_throws BoundsError A[CartesianIndex(1,1),2]
@test_throws BoundsError S[CartesianIndex(1,1)]
@test_throws BoundsError S[CartesianIndex(1,1),0]
@test_throws BoundsError S[CartesianIndex(1,1),2]
@test eachindex(A) == 1:4
@test eachindex(S) == CartesianIndices(IdentityUnitRange.((0:1,3:4)))
end
@testset "view" begin
A0 = [1 3; 2 4]
A = OffsetArray(A0, (-1,2))
S = view(A, :, 3)
@test S == OffsetArray([1,2], (A.offsets[1],))
@test S[0] == 1
@test S[1] == 2
@test_throws BoundsError S[2]
@test axes(S) === (IdentityUnitRange(0:1),)
S = view(A, 0, :)
@test S == OffsetArray([1,3], (A.offsets[2],))
@test S[3] == 1
@test S[4] == 3
@test_throws BoundsError S[1]
@test axes(S) === (IdentityUnitRange(3:4),)
S = view(A, 0:0, 4)
@test S == [3]
@test S[1] == 3
@test_throws BoundsError S[0]
@test axes(S) === (Base.OneTo(1),)
S = view(A, 1, 3:4)
@test S == [2,4]
@test S[1] == 2
@test S[2] == 4
@test_throws BoundsError S[3]
@test axes(S) === (Base.OneTo(2),)
S = view(A, :, :)
@test S == A
@test S[0,3] == S[1] == 1
@test S[1,3] == S[2] == 2
@test S[0,4] == S[3] == 3
@test S[1,4] == S[4] == 4
@test_throws BoundsError S[1,1]
@test axes(S) === IdentityUnitRange.((0:1, 3:4))
end
@testset "iteration" begin
A0 = [1 3; 2 4]
A = OffsetArray(A0, (-1,2))
let a
for (a,d) in zip(A, A0)
@test a == d
end
end
end
@testset "show/summary" begin
A0 = [1 3; 2 4]
A = OffsetArray(A0, (-1,2))
S = OffsetArray(view(A0, 1:2, 1:2), (-1,2))
@test sprint(show, A) == "[1 3; 2 4]"
@test sprint(show, S) == "[1 3; 2 4]"
strs = split(strip(sprint(show, MIME("text/plain"), A)), '\n')
@test strs[2] == " 1 3"
@test strs[3] == " 2 4"
v = OffsetArray(rand(3), (-2,))
@test sprint(show, v) == sprint(show, parent(v))
io = IOBuffer()
function cmp_showf(printfunc, io, A)
ioc = IOContext(io, :limit=>true, :compact=>true)
printfunc(ioc, A)
str1 = String(take!(io))
printfunc(ioc, parent(A))
str2 = String(take!(io))
@test str1 == str2
end
cmp_showf(Base.print_matrix, io, OffsetArray(rand(5,5), (10,-9))) # rows&cols fit
cmp_showf(Base.print_matrix, io, OffsetArray(rand(10^3,5), (10,-9))) # columns fit
cmp_showf(Base.print_matrix, io, OffsetArray(rand(5,10^3), (10,-9))) # rows fit
cmp_showf(Base.print_matrix, io, OffsetArray(rand(10^3,10^3), (10,-9))) # neither fits
a = OffsetArray([1 2; 3 4], -1:0, 5:6)
shownsz = VERSION >= v"1.2.0-DEV.229" ? Base.dims2string(size(a))*' ' : ""
@test summary(a) == "$(shownsz)OffsetArray(::Array{$(Int),2}, -1:0, 5:6) with eltype $(Int) with indices -1:0×5:6"
shownsz = VERSION >= v"1.2.0-DEV.229" ? Base.dims2string(size(view(a, :, 5)))*' ' : ""
@test summary(view(a, :, 5)) == "$(shownsz)view(OffsetArray(::Array{$(Int),2}, -1:0, 5:6), :, 5) with eltype $(Int) with indices -1:0"
a = OffsetArray(reshape([1]))
@test summary(a) == "0-dimensional OffsetArray(::Array{$(Int),0}) with eltype $(Int)"
show(io, OffsetArray(3:5, 0:2))
@test String(take!(io)) == "3:5 with indices 0:2"
end
@testset "readdlm/writedlm" begin
A0 = [1 3; 2 4]
A = OffsetArray(A0, (-1,2))
io = IOBuffer()
writedlm(io, A)
seek(io, 0)
@test readdlm(io, eltype(A)) == parent(A)
end
@testset "similar" begin
A0 = [1 3; 2 4]
A = OffsetArray(A0, (-1,2))
B = similar(A, Float32)
@test isa(B, OffsetArray{Float32,2})
@test axes(B) === axes(A)
B = similar(A, (3,4))
@test isa(B, Array{Int,2})
@test size(B) == (3,4)
@test axes(B) === (Base.OneTo(3), Base.OneTo(4))
B = similar(A, (-3:3,1:4))
@test isa(B, OffsetArray{Int,2})
@test axes(B) === IdentityUnitRange.((-3:3, 1:4))
B = similar(parent(A), (-3:3,1:4))
@test isa(B, OffsetArray{Int,2})
@test axes(B) === IdentityUnitRange.((-3:3, 1:4))
@test isa([x for x in [1,2,3]], Vector{Int})
@test similar(Array{Int}, (0:0, 0:0)) isa OffsetArray{Int, 2}
@test similar(Array{Int}, (1, 1)) isa Matrix{Int}
@test similar(Array{Int}, (Base.OneTo(1), Base.OneTo(1))) isa Matrix{Int}
end
@testset "reshape" begin
A0 = [1 3; 2 4]
A = OffsetArray(A0, (-1,2))
B = reshape(A0, -10:-9, 9:10)
@test isa(B, OffsetArray{Int,2})
@test parent(B) === A0
@test axes(B) == IdentityUnitRange.((-10:-9, 9:10))
B = reshape(A, -10:-9, 9:10)
@test isa(B, OffsetArray{Int,2})
@test pointer(parent(B)) === pointer(A0)
@test axes(B) == IdentityUnitRange.((-10:-9, 9:10))
b = reshape(A, -7:-4)
@test axes(b) == (IdentityUnitRange(-7:-4),)
@test isa(parent(b), Vector{Int})
@test pointer(parent(b)) === pointer(parent(A))
@test parent(b) == A0[:]
a = OffsetArray(rand(3,3,3), -1:1, 0:2, 3:5)
# Offset axes are required for reshape(::OffsetArray, ::Val) support
b = reshape(a, Val(2))
@test isa(b, OffsetArray{Float64,2})
@test pointer(parent(b)) === pointer(parent(a))
@test axes(b) == IdentityUnitRange.((-1:1, 1:9))
b = reshape(a, Val(4))
@test isa(b, OffsetArray{Float64,4})
@test pointer(parent(b)) === pointer(parent(a))
@test axes(b) == (axes(a)..., IdentityUnitRange(1:1))
end
@testset "Indexing with OffsetArray axes" begin
A0 = [1 3; 2 4]
i1 = OffsetArray([2,1], (-5,))
i1 = OffsetArray([2,1], -5)
b = A0[i1, 1]
@test axes(b) === (IdentityUnitRange(-4:-3),)
@test b[-4] == 2
@test b[-3] == 1
b = A0[1,i1]
@test axes(b) === (IdentityUnitRange(-4:-3),)
@test b[-4] == 3
@test b[-3] == 1
v = view(A0, i1, 1)
@test axes(v) === (IdentityUnitRange(-4:-3),)
v = view(A0, 1:1, i1)
@test axes(v) === (Base.OneTo(1), IdentityUnitRange(-4:-3))
for r in (1:10, 1:1:10, StepRangeLen(1, 1, 10), LinRange(1, 10, 10))
for s in (IdentityUnitRange(2:3), OffsetArray(2:3, 2:3))
@test axes(r[s]) == axes(s)
end
end
end
@testset "logical indexing" begin
A0 = [1 3; 2 4]
A = OffsetArray(A0, (-1,2))
@test A[A .> 2] == [3,4]
end
@testset "copyto!" begin
a = OffsetArray{Int}(undef, (-3:-1,))
fill!(a, -1)
copyto!(a, (1,2)) # non-array iterables
@test a[-3] == 1
@test a[-2] == 2
@test a[-1] == -1
fill!(a, -1)
copyto!(a, -2, (1,2))
@test a[-3] == -1
@test a[-2] == 1
@test a[-1] == 2
@test_throws BoundsError copyto!(a, 1, (1,2))
fill!(a, -1)
copyto!(a, -2, (1,2,3), 2)
@test a[-3] == -1
@test a[-2] == 2
@test a[-1] == 3
@test_throws BoundsError copyto!(a, -2, (1,2,3), 1)
fill!(a, -1)
copyto!(a, -2, (1,2,3), 1, 2)
@test a[-3] == -1
@test a[-2] == 1
@test a[-1] == 2
b = 1:2 # copy between AbstractArrays
bo = OffsetArray(1:2, (-3,))
@test_throws BoundsError copyto!(a, b)
fill!(a, -1)
copyto!(a, bo)
@test a[-3] == -1
@test a[-2] == 1
@test a[-1] == 2
fill!(a, -1)
copyto!(a, -2, bo)
@test a[-3] == -1
@test a[-2] == 1
@test a[-1] == 2
@test_throws BoundsError copyto!(a, -4, bo)
@test_throws BoundsError copyto!(a, -1, bo)
fill!(a, -1)
copyto!(a, -3, b, 2)
@test a[-3] == 2
@test a[-2] == a[-1] == -1
@test_throws BoundsError copyto!(a, -3, b, 1, 4)
am = OffsetArray{Int}(undef, (1:1, 7:9)) # for testing linear indexing
fill!(am, -1)
copyto!(am, b)
@test am[1] == 1
@test am[2] == 2
@test am[3] == -1
@test am[1,7] == 1
@test am[1,8] == 2
@test am[1,9] == -1
end
@testset "map" begin
am = OffsetArray{Int}(undef, (1:1, 7:9)) # for testing linear indexing
fill!(am, -1)
copyto!(am, 1:2)
dest = similar(am)
map!(+, dest, am, am)
@test dest[1,7] == 2
@test dest[1,8] == 4
@test dest[1,9] == -2
end
@testset "reductions" begin
A = OffsetArray(rand(4,4), (-3,5))
@test maximum(A) == maximum(parent(A))
@test minimum(A) == minimum(parent(A))
@test extrema(A) == extrema(parent(A))
C = similar(A)
cumsum!(C, A, dims = 1)
@test parent(C) == cumsum(parent(A), dims = 1)
@test parent(cumsum(A, dims = 1)) == cumsum(parent(A), dims = 1)
cumsum!(C, A, dims = 2)
@test parent(C) == cumsum(parent(A), dims = 2)
R = similar(A, (1:1, 6:9))
maximum!(R, A)
@test parent(R) == maximum(parent(A), dims = 1)
R = similar(A, (-2:1, 1:1))
maximum!(R, A)
@test parent(R) == maximum(parent(A), dims = 2)
amin, iamin = findmin(A)
pmin, ipmin = findmin(parent(A))
@test amin == pmin
@test A[iamin] == amin
@test amin == parent(A)[ipmin]
amax, iamax = findmax(A)
pmax, ipmax = findmax(parent(A))
@test amax == pmax
@test A[iamax] == amax
@test amax == parent(A)[ipmax]
amin, amax = extrema(parent(A))
@test clamp.(A, (amax+amin)/2, amax) == OffsetArray(clamp.(parent(A), (amax+amin)/2, amax), axes(A))
end
# v = OffsetArray([1,1e100,1,-1e100], (-3,))*1000
# v2 = OffsetArray([1,-1e100,1,1e100], (5,))*1000
# @test isa(v, OffsetArray)
# cv = OffsetArray([1,1e100,1e100,2], (-3,))*1000
# cv2 = OffsetArray([1,-1e100,-1e100,2], (5,))*1000
# @test isequal(cumsum_kbn(v), cv)
# @test isequal(cumsum_kbn(v2), cv2)
# @test isequal(sum_kbn(v), sum_kbn(parent(v)))
@testset "Collections" begin
A = OffsetArray(rand(4,4), (-3,5))
@test unique(A, dims=1) == OffsetArray(parent(A), 0, first(axes(A, 2)) - 1)
@test unique(A, dims=2) == OffsetArray(parent(A), first(axes(A, 1)) - 1, 0)
v = OffsetArray(rand(8), (-2,))
@test sort(v) == OffsetArray(sort(parent(v)), v.offsets)
@test sortslices(A; dims=1) == OffsetArray(sortslices(parent(A); dims=1), A.offsets)
@test sortslices(A; dims=2) == OffsetArray(sortslices(parent(A); dims=2), A.offsets)
@test sort(A, dims = 1) == OffsetArray(sort(parent(A), dims = 1), A.offsets)
@test sort(A, dims = 2) == OffsetArray(sort(parent(A), dims = 2), A.offsets)
@test mapslices(v->sort(v), A, dims = 1) == OffsetArray(mapslices(v->sort(v), parent(A), dims = 1), A.offsets)
@test mapslices(v->sort(v), A, dims = 2) == OffsetArray(mapslices(v->sort(v), parent(A), dims = 2), A.offsets)
end
@testset "rot/reverse" begin
A = OffsetArray(rand(4,4), (-3,5))
@test rotl90(A) == OffsetArray(rotl90(parent(A)), A.offsets[[2,1]])
@test rotr90(A) == OffsetArray(rotr90(parent(A)), A.offsets[[2,1]])
@test reverse(A, dims = 1) == OffsetArray(reverse(parent(A), dims = 1), A.offsets)
@test reverse(A, dims = 2) == OffsetArray(reverse(parent(A), dims = 2), A.offsets)
end
@testset "fill" begin
B = fill(5, 1:3, -1:1)
@test axes(B) == (1:3,-1:1)
@test all(B.==5)
end
@testset "broadcasting" begin
A = OffsetArray(rand(4,4), (-3,5))
@test A.+1 == OffsetArray(parent(A).+1, A.offsets)
@test 2*A == OffsetArray(2*parent(A), A.offsets)
@test A+A == OffsetArray(parent(A)+parent(A), A.offsets)
@test A.*A == OffsetArray(parent(A).*parent(A), A.offsets)
end
@testset "@inbounds" begin
a = OffsetArray(zeros(7), -3:3)
unsafe_fill!(x) = @inbounds(for i in axes(x,1); x[i] = i; end)
function unsafe_sum(x)
s = zero(eltype(x))
@inbounds for i in axes(x,1)
s += x[i]
end
s
end
unsafe_fill!(a)
for i = -3:3
@test a[i] == i
end
@test unsafe_sum(a) == 0
end
@testset "Resizing OffsetVectors" begin
local a = OffsetVector(rand(5),-3)
axes(a,1) == -2:2
length(a) == 5
resize!(a,3)
length(a) == 3
axes(a,1) == -2:0
@test_throws ArgumentError resize!(a,-3)
end
####
#### type defined for testing no_offset_view
####
struct NegativeArray{T,N,S <: AbstractArray{T,N}} <: AbstractArray{T,N}
parent::S
end
Base.axes(A::NegativeArray) = map(n -> (-n):(-1), size(A.parent))
Base.size(A::NegativeArray) = size(A.parent)
function Base.getindex(A::NegativeArray{T,N}, I::Vararg{Int,N}) where {T,N}
getindex(A.parent, (I .+ size(A.parent) .+ 1)...)
end
@testset "no offset view" begin
# OffsetArray fallback
A = randn(3, 3)
O1 = OffsetArray(A, -1:1, 0:2)
O2 = OffsetArray(O1, -2:0, -3:(-1))
@test no_offset_view(O2) ≡ A
# generic fallback
A = collect(reshape(1:12, 3, 4))
N = NegativeArray(A)
@test N[-3, -4] == 1
V = no_offset_view(N)
@test collect(V) == A
# bidirectional
B = BidirectionalVector([1, 2, 3])
pushfirst!(B, 0)
OB = OffsetArrays.no_offset_view(B)
@test axes(OB, 1) == 1:4
@test collect(OB) == 0:3
end
@testset "no nesting" begin
A = randn(2, 3)
x = A[2, 2]
O1 = OffsetArray(A, -1:0, -1:1)
O2 = OffsetArray(O1, 0:1, 0:2)
@test parent(O1) ≡ parent(O2)
@test eltype(O1) ≡ eltype(O2)
O2[1, 1] = x + 1 # just a sanity check
@test A[2, 2] == x + 1
end
@testset "mutating functions for OffsetVector" begin
# push!
o = OffsetVector(Int[], -1)
@test push!(o) === o
@test axes(o, 1) == 0:-1
@test push!(o, 1) === o
@test axes(o, 1) == 0:0
@test o[end] == 1
@test push!(o, 2, 3) === o
@test axes(o, 1) == 0:2
@test o[end-1:end] == [2, 3]
# pop!
o = OffsetVector([1, 2, 3], -1)
@test pop!(o) == 3
@test axes(o, 1) == 0:1
# empty!
o = OffsetVector([1, 2, 3], -1)
@test empty!(o) === o
@test axes(o, 1) == 0:-1
end
| 33.266436
| 138
| 0.545611
|
[
"@testset \"Single-entry arrays in dims 0:5\" begin\n for n = 0:5\n for z in (OffsetArray(ones(Int,ntuple(d->1,n)), ntuple(x->x-1,n)),\n fill!(OffsetArray{Float64}(undef, ntuple(x->x:x, n)), 1),\n fill!(OffsetArray{Float64}(undef, ntuple(x->x:x, n)...), 1),\n fill!(OffsetArray{Float64,n}(undef, ntuple(x->x:x, n)), 1),\n fill!(OffsetArray{Float64,n}(undef, ntuple(x->x:x, n)...), 1))\n @test length(LinearIndices(z)) == 1\n @test axes(z) == ntuple(x->x:x, n)\n @test z[1] == 1\n end\n end\n a0 = reshape([3])\n a = OffsetArray(a0)\n @test axes(a) == ()\n @test ndims(a) == 0\n @test a[] == 3\nend",
"@testset \"OffsetVector constructors\" begin\n local v = rand(5)\n @test OffsetVector(v, -2) == OffsetArray(v, -2)\n @test OffsetVector(v, -2:2) == OffsetArray(v, -2:2)\n @test typeof(OffsetVector{Float64}(undef, -2:2)) == typeof(OffsetArray{Float64}(undef, -2:2))\nend",
"@testset \"undef, missing, and nothing constructors\" begin\n y = OffsetArray{Float32}(undef, (IdentityUnitRange(-1:1),))\n @test axes(y) === (IdentityUnitRange(-1:1),)\n\n for (T, t) in ((Missing, missing), (Nothing, nothing))\n @test !isassigned(OffsetArray{Union{T,Vector{Int}}}(undef, -1:1, -1:1), -1, -1)\n @test OffsetArray{Union{T,Vector{Int}}}(t, -1:1, -1:1)[-1, -1] === t\n @test !isassigned(OffsetVector{Union{T,Vector{Int}}}(undef, -1:1), -1)\n @test OffsetVector{Union{T,Vector{Int}}}(t, -1:1)[-1] === t\n end\nend",
"@testset \"high dimensionality\" begin\n y = OffsetArray{Float64}(undef, -1:1, -7:7, -128:512, -5:5, -1:1, -3:3, -2:2, -1:1)\n @test axes(y) == (-1:1, -7:7, -128:512, -5:5, -1:1, -3:3, -2:2, -1:1)\n y[-1,-7,-128,-5,-1,-3,-2,-1] = 14\n y[-1,-7,-128,-5,-1,-3,-2,-1] += 5\n @test y[-1,-7,-128,-5,-1,-3,-2,-1] == 19\nend",
"@testset \"Offset range construction\" begin\n r = -2:5\n y = OffsetArray(r, r)\n @test axes(y) == (r,)\n y = OffsetArray(r, (r,))\n @test axes(y) == (r,)\nend",
"@testset \"Traits\" begin\n A0 = [1 3; 2 4]\n A = OffsetArray(A0, (-1,2)) # IndexLinear\n S = OffsetArray(view(A0, 1:2, 1:2), (-1,2)) # IndexCartesian\n @test axes(A) == axes(S) == (0:1, 3:4)\n @test size(A) == size(A0)\n @test size(A, 1) == size(A0, 1)\n @test length(A) == length(A0)\n @test A == OffsetArray(A0, 0:1, 3:4)\n @test_throws DimensionMismatch OffsetArray(A0, 0:2, 3:4)\n @test_throws DimensionMismatch OffsetArray(A0, 0:1, 2:4)\nend",
"@testset \"Scalar indexing\" begin\n A0 = [1 3; 2 4]\n A = OffsetArray(A0, (-1,2))\n S = OffsetArray(view(A0, 1:2, 1:2), (-1,2))\n\n @test @inferred(A[0,3]) == @inferred(A[0,3,1]) == @inferred(A[1]) == @inferred(S[0,3]) == @inferred(S[0,3,1]) == @inferred(S[1]) == 1\n @test A[1,3] == A[1,3,1] == A[2] == S[1,3] == S[1,3,1] == S[2] == 2\n @test A[0,4] == A[0,4,1] == A[3] == S[0,4] == S[0,4,1] == S[3] == 3\n @test A[1,4] == A[1,4,1] == A[4] == S[1,4] == S[1,4,1] == S[4] == 4\n @test @inbounds(A[0,3]) == @inbounds(A[0,3,1]) == @inbounds(A[1]) == @inbounds(S[0,3]) == @inbounds(S[0,3,1]) == @inbounds(S[1]) == 1\n @test @inbounds(A[1,3]) == @inbounds(A[1,3,1]) == @inbounds(A[2]) == @inbounds(S[1,3]) == @inbounds(S[1,3,1]) == @inbounds(S[2]) == 2\n @test @inbounds(A[0,4]) == @inbounds(A[0,4,1]) == @inbounds(A[3]) == @inbounds(S[0,4]) == @inbounds(S[0,4,1]) == @inbounds(S[3]) == 3\n @test @inbounds(A[1,4]) == @inbounds(A[1,4,1]) == @inbounds(A[4]) == @inbounds(S[1,4]) == @inbounds(S[1,4,1]) == @inbounds(S[4]) == 4\n @test_throws BoundsError A[1,1]\n @test_throws BoundsError S[1,1]\n @test_throws BoundsError A[0,3,2]\n @test_throws BoundsError A[0,3,0]\n Ac = copy(A)\n Ac[0,3] = 10\n @test Ac[0,3] == 10\n Ac[0,3,1] = 11\n @test Ac[0,3] == 11\n @inbounds Ac[0,3,1] = 12\n @test Ac[0,3] == 12\nend",
"@testset \"Vector indexing\" begin\n A0 = [1 3; 2 4]\n A = OffsetArray(A0, (-1,2))\n S = OffsetArray(view(A0, 1:2, 1:2), (-1,2))\n\n @test A[:, 3] == S[:, 3] == OffsetArray([1,2], (A.offsets[1],))\n @test A[:, 4] == S[:, 4] == OffsetArray([3,4], (A.offsets[1],))\n @test_throws BoundsError A[:, 1]\n @test_throws BoundsError S[:, 1]\n @test A[0, :] == S[0, :] == OffsetArray([1,3], (A.offsets[2],))\n @test A[1, :] == S[1, :] == OffsetArray([2,4], (A.offsets[2],))\n @test_throws BoundsError A[2, :]\n @test_throws BoundsError S[2, :]\n @test A[0:1, 3] == S[0:1, 3] == [1,2]\n @test A[[1,0], 3] == S[[1,0], 3] == [2,1]\n @test A[0, 3:4] == S[0, 3:4] == [1,3]\n @test A[1, [4,3]] == S[1, [4,3]] == [4,2]\n @test A[:, :] == S[:, :] == A\nend",
"@testset \"Vector indexing with offset ranges\" begin\n r = OffsetArray(8:10, -1:1)\n r1 = r[0:1]\n @test r1 === 9:10\n r1 = (8:10)[OffsetArray(1:2, -5:-4)]\n @test axes(r1) === (IdentityUnitRange(-5:-4),)\n @test parent(r1) === 8:9\n r1 = OffsetArray(8:10, -1:1)[OffsetArray(0:1, -5:-4)]\n @test axes(r1) === (IdentityUnitRange(-5:-4),)\n @test parent(r1) === 9:10\nend",
"@testset \"CartesianIndexing\" begin\n A0 = [1 3; 2 4]\n A = OffsetArray(A0, (-1,2))\n S = OffsetArray(view(A0, 1:2, 1:2), (-1,2))\n\n @test A[CartesianIndex((0,3))] == S[CartesianIndex((0,3))] == 1\n @test A[CartesianIndex((0,3)),1] == S[CartesianIndex((0,3)),1] == 1\n @test @inbounds(A[CartesianIndex((0,3))]) == @inbounds(S[CartesianIndex((0,3))]) == 1\n @test @inbounds(A[CartesianIndex((0,3)),1]) == @inbounds(S[CartesianIndex((0,3)),1]) == 1\n @test_throws BoundsError A[CartesianIndex(1,1)]\n @test_throws BoundsError A[CartesianIndex(1,1),0]\n @test_throws BoundsError A[CartesianIndex(1,1),2]\n @test_throws BoundsError S[CartesianIndex(1,1)]\n @test_throws BoundsError S[CartesianIndex(1,1),0]\n @test_throws BoundsError S[CartesianIndex(1,1),2]\n @test eachindex(A) == 1:4\n @test eachindex(S) == CartesianIndices(IdentityUnitRange.((0:1,3:4)))\nend",
"@testset \"view\" begin\n A0 = [1 3; 2 4]\n A = OffsetArray(A0, (-1,2))\n\n S = view(A, :, 3)\n @test S == OffsetArray([1,2], (A.offsets[1],))\n @test S[0] == 1\n @test S[1] == 2\n @test_throws BoundsError S[2]\n @test axes(S) === (IdentityUnitRange(0:1),)\n S = view(A, 0, :)\n @test S == OffsetArray([1,3], (A.offsets[2],))\n @test S[3] == 1\n @test S[4] == 3\n @test_throws BoundsError S[1]\n @test axes(S) === (IdentityUnitRange(3:4),)\n S = view(A, 0:0, 4)\n @test S == [3]\n @test S[1] == 3\n @test_throws BoundsError S[0]\n @test axes(S) === (Base.OneTo(1),)\n S = view(A, 1, 3:4)\n @test S == [2,4]\n @test S[1] == 2\n @test S[2] == 4\n @test_throws BoundsError S[3]\n @test axes(S) === (Base.OneTo(2),)\n S = view(A, :, :)\n @test S == A\n @test S[0,3] == S[1] == 1\n @test S[1,3] == S[2] == 2\n @test S[0,4] == S[3] == 3\n @test S[1,4] == S[4] == 4\n @test_throws BoundsError S[1,1]\n @test axes(S) === IdentityUnitRange.((0:1, 3:4))\nend",
"@testset \"iteration\" begin\n A0 = [1 3; 2 4]\n A = OffsetArray(A0, (-1,2))\n\n let a\n for (a,d) in zip(A, A0)\n @test a == d\n end\n end\nend",
"@testset \"show/summary\" begin\n A0 = [1 3; 2 4]\n A = OffsetArray(A0, (-1,2))\n S = OffsetArray(view(A0, 1:2, 1:2), (-1,2))\n\n @test sprint(show, A) == \"[1 3; 2 4]\"\n @test sprint(show, S) == \"[1 3; 2 4]\"\n strs = split(strip(sprint(show, MIME(\"text/plain\"), A)), '\\n')\n @test strs[2] == \" 1 3\"\n @test strs[3] == \" 2 4\"\n v = OffsetArray(rand(3), (-2,))\n @test sprint(show, v) == sprint(show, parent(v))\n io = IOBuffer()\n function cmp_showf(printfunc, io, A)\n ioc = IOContext(io, :limit=>true, :compact=>true)\n printfunc(ioc, A)\n str1 = String(take!(io))\n printfunc(ioc, parent(A))\n str2 = String(take!(io))\n @test str1 == str2\n end\n cmp_showf(Base.print_matrix, io, OffsetArray(rand(5,5), (10,-9))) # rows&cols fit\n cmp_showf(Base.print_matrix, io, OffsetArray(rand(10^3,5), (10,-9))) # columns fit\n cmp_showf(Base.print_matrix, io, OffsetArray(rand(5,10^3), (10,-9))) # rows fit\n cmp_showf(Base.print_matrix, io, OffsetArray(rand(10^3,10^3), (10,-9))) # neither fits\n\n a = OffsetArray([1 2; 3 4], -1:0, 5:6)\n shownsz = VERSION >= v\"1.2.0-DEV.229\" ? Base.dims2string(size(a))*' ' : \"\"\n @test summary(a) == \"$(shownsz)OffsetArray(::Array{$(Int),2}, -1:0, 5:6) with eltype $(Int) with indices -1:0×5:6\"\n shownsz = VERSION >= v\"1.2.0-DEV.229\" ? Base.dims2string(size(view(a, :, 5)))*' ' : \"\"\n @test summary(view(a, :, 5)) == \"$(shownsz)view(OffsetArray(::Array{$(Int),2}, -1:0, 5:6), :, 5) with eltype $(Int) with indices -1:0\"\n a = OffsetArray(reshape([1]))\n @test summary(a) == \"0-dimensional OffsetArray(::Array{$(Int),0}) with eltype $(Int)\"\n\n show(io, OffsetArray(3:5, 0:2))\n @test String(take!(io)) == \"3:5 with indices 0:2\"\nend",
"@testset \"readdlm/writedlm\" begin\n A0 = [1 3; 2 4]\n A = OffsetArray(A0, (-1,2))\n\n io = IOBuffer()\n writedlm(io, A)\n seek(io, 0)\n @test readdlm(io, eltype(A)) == parent(A)\nend",
"@testset \"similar\" begin\n A0 = [1 3; 2 4]\n A = OffsetArray(A0, (-1,2))\n\n B = similar(A, Float32)\n @test isa(B, OffsetArray{Float32,2})\n @test axes(B) === axes(A)\n B = similar(A, (3,4))\n @test isa(B, Array{Int,2})\n @test size(B) == (3,4)\n @test axes(B) === (Base.OneTo(3), Base.OneTo(4))\n B = similar(A, (-3:3,1:4))\n @test isa(B, OffsetArray{Int,2})\n @test axes(B) === IdentityUnitRange.((-3:3, 1:4))\n B = similar(parent(A), (-3:3,1:4))\n @test isa(B, OffsetArray{Int,2})\n @test axes(B) === IdentityUnitRange.((-3:3, 1:4))\n @test isa([x for x in [1,2,3]], Vector{Int})\n @test similar(Array{Int}, (0:0, 0:0)) isa OffsetArray{Int, 2}\n @test similar(Array{Int}, (1, 1)) isa Matrix{Int}\n @test similar(Array{Int}, (Base.OneTo(1), Base.OneTo(1))) isa Matrix{Int}\nend",
"@testset \"reshape\" begin\n A0 = [1 3; 2 4]\n A = OffsetArray(A0, (-1,2))\n\n B = reshape(A0, -10:-9, 9:10)\n @test isa(B, OffsetArray{Int,2})\n @test parent(B) === A0\n @test axes(B) == IdentityUnitRange.((-10:-9, 9:10))\n B = reshape(A, -10:-9, 9:10)\n @test isa(B, OffsetArray{Int,2})\n @test pointer(parent(B)) === pointer(A0)\n @test axes(B) == IdentityUnitRange.((-10:-9, 9:10))\n b = reshape(A, -7:-4)\n @test axes(b) == (IdentityUnitRange(-7:-4),)\n @test isa(parent(b), Vector{Int})\n @test pointer(parent(b)) === pointer(parent(A))\n @test parent(b) == A0[:]\n a = OffsetArray(rand(3,3,3), -1:1, 0:2, 3:5)\n # Offset axes are required for reshape(::OffsetArray, ::Val) support\n b = reshape(a, Val(2))\n @test isa(b, OffsetArray{Float64,2})\n @test pointer(parent(b)) === pointer(parent(a))\n @test axes(b) == IdentityUnitRange.((-1:1, 1:9))\n b = reshape(a, Val(4))\n @test isa(b, OffsetArray{Float64,4})\n @test pointer(parent(b)) === pointer(parent(a))\n @test axes(b) == (axes(a)..., IdentityUnitRange(1:1))\nend",
"@testset \"Indexing with OffsetArray axes\" begin\n A0 = [1 3; 2 4]\n\n i1 = OffsetArray([2,1], (-5,))\n i1 = OffsetArray([2,1], -5)\n b = A0[i1, 1]\n @test axes(b) === (IdentityUnitRange(-4:-3),)\n @test b[-4] == 2\n @test b[-3] == 1\n b = A0[1,i1]\n @test axes(b) === (IdentityUnitRange(-4:-3),)\n @test b[-4] == 3\n @test b[-3] == 1\n v = view(A0, i1, 1)\n @test axes(v) === (IdentityUnitRange(-4:-3),)\n v = view(A0, 1:1, i1)\n @test axes(v) === (Base.OneTo(1), IdentityUnitRange(-4:-3))\n\n for r in (1:10, 1:1:10, StepRangeLen(1, 1, 10), LinRange(1, 10, 10))\n for s in (IdentityUnitRange(2:3), OffsetArray(2:3, 2:3))\n @test axes(r[s]) == axes(s)\n end\n end\nend",
"@testset \"logical indexing\" begin\n A0 = [1 3; 2 4]\n A = OffsetArray(A0, (-1,2))\n\n @test A[A .> 2] == [3,4]\nend",
"@testset \"copyto!\" begin\n a = OffsetArray{Int}(undef, (-3:-1,))\n fill!(a, -1)\n copyto!(a, (1,2)) # non-array iterables\n @test a[-3] == 1\n @test a[-2] == 2\n @test a[-1] == -1\n fill!(a, -1)\n copyto!(a, -2, (1,2))\n @test a[-3] == -1\n @test a[-2] == 1\n @test a[-1] == 2\n @test_throws BoundsError copyto!(a, 1, (1,2))\n fill!(a, -1)\n copyto!(a, -2, (1,2,3), 2)\n @test a[-3] == -1\n @test a[-2] == 2\n @test a[-1] == 3\n @test_throws BoundsError copyto!(a, -2, (1,2,3), 1)\n fill!(a, -1)\n copyto!(a, -2, (1,2,3), 1, 2)\n @test a[-3] == -1\n @test a[-2] == 1\n @test a[-1] == 2\n\n b = 1:2 # copy between AbstractArrays\n bo = OffsetArray(1:2, (-3,))\n @test_throws BoundsError copyto!(a, b)\n fill!(a, -1)\n copyto!(a, bo)\n @test a[-3] == -1\n @test a[-2] == 1\n @test a[-1] == 2\n fill!(a, -1)\n copyto!(a, -2, bo)\n @test a[-3] == -1\n @test a[-2] == 1\n @test a[-1] == 2\n @test_throws BoundsError copyto!(a, -4, bo)\n @test_throws BoundsError copyto!(a, -1, bo)\n fill!(a, -1)\n copyto!(a, -3, b, 2)\n @test a[-3] == 2\n @test a[-2] == a[-1] == -1\n @test_throws BoundsError copyto!(a, -3, b, 1, 4)\n am = OffsetArray{Int}(undef, (1:1, 7:9)) # for testing linear indexing\n fill!(am, -1)\n copyto!(am, b)\n @test am[1] == 1\n @test am[2] == 2\n @test am[3] == -1\n @test am[1,7] == 1\n @test am[1,8] == 2\n @test am[1,9] == -1\nend",
"@testset \"map\" begin\n am = OffsetArray{Int}(undef, (1:1, 7:9)) # for testing linear indexing\n fill!(am, -1)\n copyto!(am, 1:2)\n\n dest = similar(am)\n map!(+, dest, am, am)\n @test dest[1,7] == 2\n @test dest[1,8] == 4\n @test dest[1,9] == -2\nend",
"@testset \"reductions\" begin\n A = OffsetArray(rand(4,4), (-3,5))\n @test maximum(A) == maximum(parent(A))\n @test minimum(A) == minimum(parent(A))\n @test extrema(A) == extrema(parent(A))\n C = similar(A)\n cumsum!(C, A, dims = 1)\n @test parent(C) == cumsum(parent(A), dims = 1)\n @test parent(cumsum(A, dims = 1)) == cumsum(parent(A), dims = 1)\n cumsum!(C, A, dims = 2)\n @test parent(C) == cumsum(parent(A), dims = 2)\n R = similar(A, (1:1, 6:9))\n maximum!(R, A)\n @test parent(R) == maximum(parent(A), dims = 1)\n R = similar(A, (-2:1, 1:1))\n maximum!(R, A)\n @test parent(R) == maximum(parent(A), dims = 2)\n amin, iamin = findmin(A)\n pmin, ipmin = findmin(parent(A))\n @test amin == pmin\n @test A[iamin] == amin\n @test amin == parent(A)[ipmin]\n amax, iamax = findmax(A)\n pmax, ipmax = findmax(parent(A))\n @test amax == pmax\n @test A[iamax] == amax\n @test amax == parent(A)[ipmax]\n\n amin, amax = extrema(parent(A))\n @test clamp.(A, (amax+amin)/2, amax) == OffsetArray(clamp.(parent(A), (amax+amin)/2, amax), axes(A))\nend",
"@testset \"Collections\" begin\n A = OffsetArray(rand(4,4), (-3,5))\n\n @test unique(A, dims=1) == OffsetArray(parent(A), 0, first(axes(A, 2)) - 1)\n @test unique(A, dims=2) == OffsetArray(parent(A), first(axes(A, 1)) - 1, 0)\n v = OffsetArray(rand(8), (-2,))\n @test sort(v) == OffsetArray(sort(parent(v)), v.offsets)\n @test sortslices(A; dims=1) == OffsetArray(sortslices(parent(A); dims=1), A.offsets)\n @test sortslices(A; dims=2) == OffsetArray(sortslices(parent(A); dims=2), A.offsets)\n @test sort(A, dims = 1) == OffsetArray(sort(parent(A), dims = 1), A.offsets)\n @test sort(A, dims = 2) == OffsetArray(sort(parent(A), dims = 2), A.offsets)\n\n @test mapslices(v->sort(v), A, dims = 1) == OffsetArray(mapslices(v->sort(v), parent(A), dims = 1), A.offsets)\n @test mapslices(v->sort(v), A, dims = 2) == OffsetArray(mapslices(v->sort(v), parent(A), dims = 2), A.offsets)\nend",
"@testset \"rot/reverse\" begin\n A = OffsetArray(rand(4,4), (-3,5))\n\n @test rotl90(A) == OffsetArray(rotl90(parent(A)), A.offsets[[2,1]])\n @test rotr90(A) == OffsetArray(rotr90(parent(A)), A.offsets[[2,1]])\n @test reverse(A, dims = 1) == OffsetArray(reverse(parent(A), dims = 1), A.offsets)\n @test reverse(A, dims = 2) == OffsetArray(reverse(parent(A), dims = 2), A.offsets)\nend",
"@testset \"fill\" begin\n B = fill(5, 1:3, -1:1)\n @test axes(B) == (1:3,-1:1)\n @test all(B.==5)\nend",
"@testset \"broadcasting\" begin\n A = OffsetArray(rand(4,4), (-3,5))\n\n @test A.+1 == OffsetArray(parent(A).+1, A.offsets)\n @test 2*A == OffsetArray(2*parent(A), A.offsets)\n @test A+A == OffsetArray(parent(A)+parent(A), A.offsets)\n @test A.*A == OffsetArray(parent(A).*parent(A), A.offsets)\nend",
"@testset \"@inbounds\" begin\n a = OffsetArray(zeros(7), -3:3)\n unsafe_fill!(x) = @inbounds(for i in axes(x,1); x[i] = i; end)\n function unsafe_sum(x)\n s = zero(eltype(x))\n @inbounds for i in axes(x,1)\n s += x[i]\n end\n s\n end\n unsafe_fill!(a)\n for i = -3:3\n @test a[i] == i\n end\n @test unsafe_sum(a) == 0\nend",
"@testset \"Resizing OffsetVectors\" begin\n local a = OffsetVector(rand(5),-3)\n axes(a,1) == -2:2\n length(a) == 5\n resize!(a,3)\n length(a) == 3\n axes(a,1) == -2:0\n @test_throws ArgumentError resize!(a,-3)\nend",
"@testset \"no offset view\" begin\n # OffsetArray fallback\n A = randn(3, 3)\n O1 = OffsetArray(A, -1:1, 0:2)\n O2 = OffsetArray(O1, -2:0, -3:(-1))\n @test no_offset_view(O2) ≡ A\n\n # generic fallback\n A = collect(reshape(1:12, 3, 4))\n N = NegativeArray(A)\n @test N[-3, -4] == 1\n V = no_offset_view(N)\n @test collect(V) == A\n\n # bidirectional\n B = BidirectionalVector([1, 2, 3])\n pushfirst!(B, 0)\n OB = OffsetArrays.no_offset_view(B)\n @test axes(OB, 1) == 1:4\n @test collect(OB) == 0:3\nend",
"@testset \"no nesting\" begin\n A = randn(2, 3)\n x = A[2, 2]\n O1 = OffsetArray(A, -1:0, -1:1)\n O2 = OffsetArray(O1, 0:1, 0:2)\n @test parent(O1) ≡ parent(O2)\n @test eltype(O1) ≡ eltype(O2)\n O2[1, 1] = x + 1 # just a sanity check\n @test A[2, 2] == x + 1\nend",
"@testset \"mutating functions for OffsetVector\" begin\n # push!\n o = OffsetVector(Int[], -1)\n @test push!(o) === o\n @test axes(o, 1) == 0:-1\n @test push!(o, 1) === o\n @test axes(o, 1) == 0:0\n @test o[end] == 1\n @test push!(o, 2, 3) === o\n @test axes(o, 1) == 0:2\n @test o[end-1:end] == [2, 3]\n # pop!\n o = OffsetVector([1, 2, 3], -1)\n @test pop!(o) == 3\n @test axes(o, 1) == 0:1\n # empty!\n o = OffsetVector([1, 2, 3], -1)\n @test empty!(o) === o\n @test axes(o, 1) == 0:-1\nend"
] |
f7dba5dc67cea436c10e802319e6dfd2ff84489b
| 105
|
jl
|
Julia
|
test/runtests.jl
|
Lyceum/LyceumDevTools.jl
|
92bb0735bfc4f3921ca7396bf4e351b14ad811ca
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
Lyceum/LyceumDevTools.jl
|
92bb0735bfc4f3921ca7396bf4e351b14ad811ca
|
[
"MIT"
] | null | null | null |
test/runtests.jl
|
Lyceum/LyceumDevTools.jl
|
92bb0735bfc4f3921ca7396bf4e351b14ad811ca
|
[
"MIT"
] | null | null | null |
using LyceumDevTools
using Test
@testset "LyceumDevTools.jl" begin
# Write your own tests here.
end
| 15
| 34
| 0.761905
|
[
"@testset \"LyceumDevTools.jl\" begin\n # Write your own tests here.\nend"
] |
f7dedd6608a9b67dff230b090c5ceda250ff3368
| 10,407
|
jl
|
Julia
|
test/avio.jl
|
caleb-allen/VideoIO.jl
|
2dfa72e16c9b82107285a8a132ce1ec689a6b440
|
[
"MIT"
] | null | null | null |
test/avio.jl
|
caleb-allen/VideoIO.jl
|
2dfa72e16c9b82107285a8a132ce1ec689a6b440
|
[
"MIT"
] | null | null | null |
test/avio.jl
|
caleb-allen/VideoIO.jl
|
2dfa72e16c9b82107285a8a132ce1ec689a6b440
|
[
"MIT"
] | null | null | null |
using Test
using ColorTypes: RGB, Gray, N0f8
using FileIO, ImageCore, Dates, Statistics
using Statistics, StatsBase
import VideoIO
createmode = false
testdir = dirname(@__FILE__)
videodir = joinpath(testdir, "..", "videos")
VideoIO.TestVideos.available()
VideoIO.TestVideos.download_all()
swapext(f, new_ext) = "$(splitext(f)[1])$new_ext"
isarm() = Base.Sys.ARCH in (:arm,:arm32,:arm7l,:armv7l,:arm8l,:armv8l,:aarch64,:arm64)
#@show Base.Sys.ARCH
@noinline function isblank(img)
all(c->green(c) == 0, img) || all(c->blue(c) == 0, img) || all(c->red(c) == 0, img) || maximum(rawview(channelview(img))) < 0xcf
end
@testset "Reading of various example file formats" begin
for name in VideoIO.TestVideos.names()
@testset "Reading $name" begin
first_frame_file = joinpath(testdir, swapext(name, ".png"))
!createmode && (first_frame = load(first_frame_file))
f = VideoIO.testvideo(name)
v = VideoIO.openvideo(f)
time_seconds = VideoIO.gettime(v)
@test time_seconds == 0
if !createmode && (size(first_frame, 1) > v.height)
first_frame = first_frame[1+size(first_frame,1)-v.height:end,:]
end
# Find the first non-trivial image
img = read(v)
i=1
while isblank(img)
read!(v, img)
i += 1
end
# println("$name vs. $first_frame_file - First non-blank frame: $i") # for debugging
createmode && save(first_frame_file,img)
if isarm()
!createmode && (@test_skip img == first_frame)
else
!createmode && (@test img == first_frame)
end
for i in 1:50
read!(v,img)
end
fiftieth_frame = img
timebase = v.avin.video_info[1].stream.time_base
tstamp = v.aVideoFrame[1].pkt_dts
video_tstamp = v.avin.video_info[1].stream.first_dts
fiftytime = (tstamp-video_tstamp)/(convert(Float64,timebase.den)/convert(Float64,timebase.num))
while !eof(v)
read!(v, img)
end
seek(v,float(fiftytime))
read!(v,img)
@test img == fiftieth_frame
# read first frames again, and compare
seekstart(v)
read!(v, img)
while isblank(img)
read!(v, img)
end
if isarm()
!createmode && (@test_skip img == first_frame)
else
!createmode && (@test img == first_frame)
end
close(v)
end
end
end
@testset "IO reading of various example file formats" begin
for name in VideoIO.TestVideos.names()
# TODO: fix me?
(startswith(name, "ladybird") || startswith(name, "NPS")) && continue
@testset "Testing $name" begin
first_frame_file = joinpath(testdir, swapext(name, ".png"))
first_frame = load(first_frame_file)
filename = joinpath(videodir, name)
v = VideoIO.openvideo(open(filename))
if size(first_frame, 1) > v.height
first_frame = first_frame[1+size(first_frame,1)-v.height:end,:]
end
img = read(v)
# Find the first non-trivial image
while isblank(img)
read!(v, img)
end
if isarm()
@test_skip img == first_frame
else
@test img == first_frame
end
while !eof(v)
read!(v, img)
end
end
end
VideoIO.testvideo("ladybird") # coverage testing
@test_throws ErrorException VideoIO.testvideo("rickroll")
@test_throws ErrorException VideoIO.testvideo("")
end
@testset "Reading video metadata" begin
@testset "Reading Storage Aspect Ratio: SAR" begin
# currently, the SAR of all the test videos is 1, we should get another video with a valid SAR that is not equal to 1
vids = Dict("ladybird.mp4" => 1, "black_hole.webm" => 1, "crescent-moon.ogv" => 1, "annie_oakley.ogg" => 1)
@test all(VideoIO.aspect_ratio(VideoIO.openvideo(joinpath(videodir, k))) == v for (k,v) in vids)
end
@testset "Reading video duration, start date, and duration" begin
# tesing the duration and date & time functions:
file = joinpath(videodir, "annie_oakley.ogg")
@test VideoIO.get_duration(file) == 24224200/1e6
@test VideoIO.get_start_time(file) == DateTime(1970, 1, 1)
@test VideoIO.get_time_duration(file) == (DateTime(1970, 1, 1), 24224200/1e6)
end
end
@testset "Encoding video across all supported colortypes" begin
for el in [UInt8, RGB{N0f8}]
@testset "Encoding $el imagestack" begin
imgstack = map(x->rand(el,100,100),1:100)
props = [:priv_data => ("crf"=>"22","preset"=>"medium")]
encodedvideopath = VideoIO.encodevideo("testvideo.mp4",imgstack,framerate=30,AVCodecContextProperties=props, silent=true)
@test stat(encodedvideopath).size > 100
rm(encodedvideopath)
end
end
end
@testset "Video encode/decode accuracy (read, encode, read, compare)" begin
file = joinpath(videodir, "annie_oakley.ogg")
f = VideoIO.openvideo(file)
imgstack_rgb = []
imgstack_gray = []
while !eof(f)
img = collect(read(f))
img_gray = convert(Array{Gray{N0f8}},img)
push!(imgstack_rgb,img)
push!(imgstack_gray,img_gray)
end
@testset "Lossless Grayscale encoding" begin
file_lossless_gray_copy = joinpath(videodir, "annie_oakley_lossless_gray.mp4")
prop = [:color_range=>2, :priv_data => ("crf"=>"0","preset"=>"medium")]
codec_name="libx264"
VideoIO.encodevideo(file_lossless_gray_copy,imgstack_gray,codec_name=codec_name,AVCodecContextProperties=prop, silent=true)
fcopy = VideoIO.openvideo(file_lossless_gray_copy,target_format=VideoIO.AV_PIX_FMT_GRAY8)
imgstack_gray_copy = []
while !eof(fcopy)
push!(imgstack_gray_copy,collect(read(fcopy)))
end
close(f)
@test eltype(imgstack_gray) == eltype(imgstack_gray_copy)
@test length(imgstack_gray) == length(imgstack_gray_copy)
@test size(imgstack_gray[1]) == size(imgstack_gray_copy[1])
@test !any(.!(imgstack_gray .== imgstack_gray_copy))
end
@testset "Lossless RGB encoding" begin
file_lossless_rgb_copy = joinpath(videodir, "annie_oakley_lossless_rgb.mp4")
prop = [:priv_data => ("crf"=>"0","preset"=>"medium")]
codec_name="libx264rgb"
VideoIO.encodevideo(file_lossless_rgb_copy,imgstack_rgb,codec_name=codec_name,AVCodecContextProperties=prop, silent=true)
fcopy = VideoIO.openvideo(file_lossless_rgb_copy)
imgstack_rgb_copy = []
while !eof(fcopy)
img = collect(read(fcopy))
push!(imgstack_rgb_copy,img)
end
close(f)
@test eltype(imgstack_rgb) == eltype(imgstack_rgb_copy)
@test length(imgstack_rgb) == length(imgstack_rgb_copy)
@test size(imgstack_rgb[1]) == size(imgstack_rgb_copy[1])
@test !any(.!(imgstack_rgb .== imgstack_rgb_copy))
end
@testset "UInt8 accuracy during read & lossless encode" begin
# Test that reading truth video has one of each UInt8 value pixels (16x16 frames = 256 pixels)
f = VideoIO.openvideo(joinpath(testdir,"precisiontest_gray_truth.mp4"),target_format=VideoIO.AV_PIX_FMT_GRAY8)
frame_truth = collect(rawview(channelview(read(f))))
h_truth = fit(Histogram, frame_truth[:], 0:256)
@test h_truth.weights == fill(1,256) #Test that reading is precise
# Test that encoding new test video has one of each UInt8 value pixels (16x16 frames = 256 pixels)
img = Array{UInt8}(undef,16,16)
for i in 1:256
img[i] = UInt8(i-1)
end
imgstack = []
for i=1:24
push!(imgstack,img)
end
props = [:color_range=>2, :priv_data => ("crf"=>"0","preset"=>"medium")]
VideoIO.encodevideo(joinpath(testdir,"precisiontest_gray_test.mp4"), imgstack,
AVCodecContextProperties = props,silent=true)
f = VideoIO.openvideo(joinpath(testdir,"precisiontest_gray_test.mp4"),
target_format=VideoIO.AV_PIX_FMT_GRAY8)
frame_test = collect(rawview(channelview(read(f))))
h_test = fit(Histogram, frame_test[:], 0:256)
@test h_test.weights == fill(1,256) #Test that encoding is precise (if above passes)
end
@testset "Correct frame order when reading & encoding" begin
@testset "Frame order when reading ground truth video" begin
# Test that reading a video with frame-incremental pixel values is read in in-order
f = VideoIO.openvideo(joinpath(testdir,"ordertest_gray_truth.mp4"),target_format=VideoIO.AV_PIX_FMT_GRAY8)
frame_ids_truth = []
while !eof(f)
img = collect(rawview(channelview(read(f))))
push!(frame_ids_truth,img[1,1])
end
@test frame_ids_truth == collect(0:255) #Test that reading is in correct frame order
end
@testset "Frame order when encoding, then reading video" begin
# Test that writing and reading a video with frame-incremental pixel values is read in in-order
imgstack = []
img = Array{UInt8}(undef,16,16)
for i in 0:255
push!(imgstack,fill(UInt8(i),(16,16)))
end
props = [:color_range=>2, :priv_data => ("crf"=>"0","preset"=>"medium")]
VideoIO.encodevideo(joinpath(testdir,"ordertest_gray_test.mp4"), imgstack,
AVCodecContextProperties = props,silent=true)
f = VideoIO.openvideo(joinpath(testdir,"ordertest_gray_test.mp4"),
target_format=VideoIO.AV_PIX_FMT_GRAY8)
frame_ids_test = []
while !eof(f)
img = collect(rawview(channelview(read(f))))
push!(frame_ids_test,img[1,1])
end
@test frame_ids_test == collect(0:255) #Test that reading is in correct frame order
end
end
end
#VideoIO.TestVideos.remove_all()
| 38.83209
| 133
| 0.607284
|
[
"@testset \"Reading of various example file formats\" begin\n for name in VideoIO.TestVideos.names()\n @testset \"Reading $name\" begin\n first_frame_file = joinpath(testdir, swapext(name, \".png\"))\n !createmode && (first_frame = load(first_frame_file))\n\n f = VideoIO.testvideo(name)\n v = VideoIO.openvideo(f)\n\n time_seconds = VideoIO.gettime(v)\n @test time_seconds == 0\n\n if !createmode && (size(first_frame, 1) > v.height)\n first_frame = first_frame[1+size(first_frame,1)-v.height:end,:]\n end\n\n # Find the first non-trivial image\n img = read(v)\n i=1\n while isblank(img)\n read!(v, img)\n i += 1\n end\n # println(\"$name vs. $first_frame_file - First non-blank frame: $i\") # for debugging\n createmode && save(first_frame_file,img)\n if isarm()\n !createmode && (@test_skip img == first_frame)\n else\n !createmode && (@test img == first_frame)\n end\n\n for i in 1:50\n read!(v,img)\n end\n fiftieth_frame = img\n timebase = v.avin.video_info[1].stream.time_base\n tstamp = v.aVideoFrame[1].pkt_dts\n video_tstamp = v.avin.video_info[1].stream.first_dts\n fiftytime = (tstamp-video_tstamp)/(convert(Float64,timebase.den)/convert(Float64,timebase.num))\n\n while !eof(v)\n read!(v, img)\n end\n\n seek(v,float(fiftytime))\n read!(v,img)\n\n @test img == fiftieth_frame\n\n # read first frames again, and compare\n seekstart(v)\n\n read!(v, img)\n\n while isblank(img)\n read!(v, img)\n end\n\n if isarm()\n !createmode && (@test_skip img == first_frame)\n else\n !createmode && (@test img == first_frame)\n end\n\n close(v)\n end\n end\nend",
"@testset \"IO reading of various example file formats\" begin\n for name in VideoIO.TestVideos.names()\n # TODO: fix me?\n (startswith(name, \"ladybird\") || startswith(name, \"NPS\")) && continue\n @testset \"Testing $name\" begin\n first_frame_file = joinpath(testdir, swapext(name, \".png\"))\n first_frame = load(first_frame_file)\n\n filename = joinpath(videodir, name)\n v = VideoIO.openvideo(open(filename))\n\n if size(first_frame, 1) > v.height\n first_frame = first_frame[1+size(first_frame,1)-v.height:end,:]\n end\n img = read(v)\n # Find the first non-trivial image\n while isblank(img)\n read!(v, img)\n end\n\n if isarm()\n @test_skip img == first_frame\n else\n @test img == first_frame\n end\n while !eof(v)\n read!(v, img)\n end\n end\n end\n\n VideoIO.testvideo(\"ladybird\") # coverage testing\n @test_throws ErrorException VideoIO.testvideo(\"rickroll\")\n @test_throws ErrorException VideoIO.testvideo(\"\")\nend",
"@testset \"Reading video metadata\" begin\n @testset \"Reading Storage Aspect Ratio: SAR\" begin\n # currently, the SAR of all the test videos is 1, we should get another video with a valid SAR that is not equal to 1\n vids = Dict(\"ladybird.mp4\" => 1, \"black_hole.webm\" => 1, \"crescent-moon.ogv\" => 1, \"annie_oakley.ogg\" => 1)\n @test all(VideoIO.aspect_ratio(VideoIO.openvideo(joinpath(videodir, k))) == v for (k,v) in vids)\n end\n @testset \"Reading video duration, start date, and duration\" begin\n # tesing the duration and date & time functions:\n file = joinpath(videodir, \"annie_oakley.ogg\")\n @test VideoIO.get_duration(file) == 24224200/1e6\n @test VideoIO.get_start_time(file) == DateTime(1970, 1, 1)\n @test VideoIO.get_time_duration(file) == (DateTime(1970, 1, 1), 24224200/1e6)\n end\nend",
"@testset \"Encoding video across all supported colortypes\" begin\n for el in [UInt8, RGB{N0f8}]\n @testset \"Encoding $el imagestack\" begin\n imgstack = map(x->rand(el,100,100),1:100)\n props = [:priv_data => (\"crf\"=>\"22\",\"preset\"=>\"medium\")]\n encodedvideopath = VideoIO.encodevideo(\"testvideo.mp4\",imgstack,framerate=30,AVCodecContextProperties=props, silent=true)\n @test stat(encodedvideopath).size > 100\n rm(encodedvideopath)\n end\n end\nend",
"@testset \"Video encode/decode accuracy (read, encode, read, compare)\" begin\n file = joinpath(videodir, \"annie_oakley.ogg\")\n f = VideoIO.openvideo(file)\n imgstack_rgb = []\n imgstack_gray = []\n while !eof(f)\n img = collect(read(f))\n img_gray = convert(Array{Gray{N0f8}},img)\n push!(imgstack_rgb,img)\n push!(imgstack_gray,img_gray)\n end\n @testset \"Lossless Grayscale encoding\" begin\n file_lossless_gray_copy = joinpath(videodir, \"annie_oakley_lossless_gray.mp4\")\n prop = [:color_range=>2, :priv_data => (\"crf\"=>\"0\",\"preset\"=>\"medium\")]\n codec_name=\"libx264\"\n VideoIO.encodevideo(file_lossless_gray_copy,imgstack_gray,codec_name=codec_name,AVCodecContextProperties=prop, silent=true)\n\n fcopy = VideoIO.openvideo(file_lossless_gray_copy,target_format=VideoIO.AV_PIX_FMT_GRAY8)\n imgstack_gray_copy = []\n while !eof(fcopy)\n push!(imgstack_gray_copy,collect(read(fcopy)))\n end\n close(f)\n @test eltype(imgstack_gray) == eltype(imgstack_gray_copy)\n @test length(imgstack_gray) == length(imgstack_gray_copy)\n @test size(imgstack_gray[1]) == size(imgstack_gray_copy[1])\n @test !any(.!(imgstack_gray .== imgstack_gray_copy))\n end\n\n @testset \"Lossless RGB encoding\" begin\n file_lossless_rgb_copy = joinpath(videodir, \"annie_oakley_lossless_rgb.mp4\")\n prop = [:priv_data => (\"crf\"=>\"0\",\"preset\"=>\"medium\")]\n codec_name=\"libx264rgb\"\n VideoIO.encodevideo(file_lossless_rgb_copy,imgstack_rgb,codec_name=codec_name,AVCodecContextProperties=prop, silent=true)\n\n fcopy = VideoIO.openvideo(file_lossless_rgb_copy)\n imgstack_rgb_copy = []\n while !eof(fcopy)\n img = collect(read(fcopy))\n push!(imgstack_rgb_copy,img)\n end\n close(f)\n @test eltype(imgstack_rgb) == eltype(imgstack_rgb_copy)\n @test length(imgstack_rgb) == length(imgstack_rgb_copy)\n @test size(imgstack_rgb[1]) == size(imgstack_rgb_copy[1])\n @test !any(.!(imgstack_rgb .== imgstack_rgb_copy))\n end\n\n @testset \"UInt8 accuracy during read & lossless encode\" begin\n # Test that reading truth video has one of each UInt8 value pixels (16x16 frames = 256 pixels)\n f = VideoIO.openvideo(joinpath(testdir,\"precisiontest_gray_truth.mp4\"),target_format=VideoIO.AV_PIX_FMT_GRAY8)\n frame_truth = collect(rawview(channelview(read(f))))\n h_truth = fit(Histogram, frame_truth[:], 0:256)\n @test h_truth.weights == fill(1,256) #Test that reading is precise\n\n # Test that encoding new test video has one of each UInt8 value pixels (16x16 frames = 256 pixels)\n img = Array{UInt8}(undef,16,16)\n for i in 1:256\n img[i] = UInt8(i-1)\n end\n imgstack = []\n for i=1:24\n push!(imgstack,img)\n end\n props = [:color_range=>2, :priv_data => (\"crf\"=>\"0\",\"preset\"=>\"medium\")]\n VideoIO.encodevideo(joinpath(testdir,\"precisiontest_gray_test.mp4\"), imgstack,\n AVCodecContextProperties = props,silent=true)\n f = VideoIO.openvideo(joinpath(testdir,\"precisiontest_gray_test.mp4\"),\n target_format=VideoIO.AV_PIX_FMT_GRAY8)\n frame_test = collect(rawview(channelview(read(f))))\n h_test = fit(Histogram, frame_test[:], 0:256)\n @test h_test.weights == fill(1,256) #Test that encoding is precise (if above passes)\n end\n\n @testset \"Correct frame order when reading & encoding\" begin\n @testset \"Frame order when reading ground truth video\" begin\n # Test that reading a video with frame-incremental pixel values is read in in-order\n f = VideoIO.openvideo(joinpath(testdir,\"ordertest_gray_truth.mp4\"),target_format=VideoIO.AV_PIX_FMT_GRAY8)\n frame_ids_truth = []\n while !eof(f)\n img = collect(rawview(channelview(read(f))))\n push!(frame_ids_truth,img[1,1])\n end\n @test frame_ids_truth == collect(0:255) #Test that reading is in correct frame order\n end\n @testset \"Frame order when encoding, then reading video\" begin\n # Test that writing and reading a video with frame-incremental pixel values is read in in-order\n imgstack = []\n img = Array{UInt8}(undef,16,16)\n for i in 0:255\n push!(imgstack,fill(UInt8(i),(16,16)))\n end\n props = [:color_range=>2, :priv_data => (\"crf\"=>\"0\",\"preset\"=>\"medium\")]\n VideoIO.encodevideo(joinpath(testdir,\"ordertest_gray_test.mp4\"), imgstack,\n AVCodecContextProperties = props,silent=true)\n f = VideoIO.openvideo(joinpath(testdir,\"ordertest_gray_test.mp4\"),\n target_format=VideoIO.AV_PIX_FMT_GRAY8)\n frame_ids_test = []\n while !eof(f)\n img = collect(rawview(channelview(read(f))))\n push!(frame_ids_test,img[1,1])\n end\n @test frame_ids_test == collect(0:255) #Test that reading is in correct frame order\n end\n end\nend"
] |
f7e1de692c429e70b145e220a315b80be849b4a6
| 1,321
|
jl
|
Julia
|
test/loading.jl
|
JuliaAI/MLJModels.jl
|
b3e1b7973d30c275ace5713726322355ea976d97
|
[
"MIT"
] | 15
|
2021-07-06T16:11:32.000Z
|
2022-03-17T12:22:26.000Z
|
test/loading.jl
|
JuliaAI/MLJModels.jl
|
b3e1b7973d30c275ace5713726322355ea976d97
|
[
"MIT"
] | 63
|
2021-06-30T03:54:16.000Z
|
2022-03-15T21:02:42.000Z
|
test/loading.jl
|
JuliaAI/MLJModels.jl
|
b3e1b7973d30c275ace5713726322355ea976d97
|
[
"MIT"
] | 5
|
2021-08-28T10:43:44.000Z
|
2022-03-31T05:57:00.000Z
|
module TestLoading
using Test
using MLJModels
using MLJBase
function isloaded(name::String, pkg::String)
(name, pkg) in map(localmodels()) do m
(m.name, m.package_name)
end
end
@load AdaBoostStumpClassifier pkg=DecisionTree verbosity=0
@test isloaded("AdaBoostStumpClassifier", "DecisionTree")
# built-ins load fine:
@load Standardizer verbosity=0
# load one version of a RidgeRegressor:
@test !isloaded("RidgeRegressor", "MultivariateStats")
@load RidgeRegressor pkg=MultivariateStats verbosity=0
@test isloaded("RidgeRegressor", "MultivariateStats")
# error if ambiguous:
@test_throws ArgumentError @load RidgeRegressor
# error if not in project:
@test !isloaded("KMeans", "Clustering")
@test_throws ArgumentError @load KMeans pkg=Clustering verbosity=0
# use add option:
@load KMeans pkg=Clustering verbosity=0 add=true
@test isloaded("KMeans", "Clustering")
# deprecated methods:
@test_throws Exception load("model", pkg = "pkg")
@test_throws Exception load(models()[1])
module FooBar
using MLJModels
function regressor()
Regressor = @load LinearRegressor pkg=MultivariateStats verbosity=0
return Regressor()
end
end
using .FooBar
@testset "@load from within a function within a module" begin
model = FooBar.regressor()
@test isdefined(model, :bias)
end
end # module
true
| 23.589286
| 71
| 0.762301
|
[
"@testset \"@load from within a function within a module\" begin\n model = FooBar.regressor()\n @test isdefined(model, :bias)\nend"
] |
f7e3e93acd27e6c3303e713038cf65bb88ef80b8
| 44,775
|
jl
|
Julia
|
test/precompile.jl
|
TechPenguineer/julia
|
aa17702e0e24a8a2afd511e6e869e68f31daf709
|
[
"MIT"
] | null | null | null |
test/precompile.jl
|
TechPenguineer/julia
|
aa17702e0e24a8a2afd511e6e869e68f31daf709
|
[
"MIT"
] | null | null | null |
test/precompile.jl
|
TechPenguineer/julia
|
aa17702e0e24a8a2afd511e6e869e68f31daf709
|
[
"MIT"
] | null | null | null |
# This file is a part of Julia. License is MIT: https://julialang.org/license
using Test, Distributed, Random
Foo_module = :Foo4b3a94a1a081a8cb
Foo2_module = :F2oo4b3a94a1a081a8cb
FooBase_module = :FooBase4b3a94a1a081a8cb
@eval module ConflictingBindings
export $Foo_module, $FooBase_module
$Foo_module = 232
$FooBase_module = 9134
end
using .ConflictingBindings
function precompile_test_harness(@nospecialize(f), testset::String)
@testset "$testset" begin
precompile_test_harness(f, true)
end
end
function precompile_test_harness(@nospecialize(f), separate::Bool)
load_path = mktempdir()
load_cache_path = separate ? mktempdir() : load_path
try
pushfirst!(LOAD_PATH, load_path)
pushfirst!(DEPOT_PATH, load_cache_path)
f(load_path)
finally
rm(load_path, recursive=true, force=true)
separate && rm(load_cache_path, recursive=true, force=true)
filter!((≠)(load_path), LOAD_PATH)
separate && filter!((≠)(load_cache_path), DEPOT_PATH)
end
nothing
end
# method root provenance
rootid(m::Module) = ccall(:jl_module_build_id, UInt64, (Any,), Base.parentmodule(m))
rootid(m::Method) = rootid(m.module)
function root_provenance(m::Method, i::Int)
mid = rootid(m)
isdefined(m, :root_blocks) || return mid
idxs = view(m.root_blocks, 2:2:length(m.root_blocks))
j = searchsortedfirst(idxs, i) - 1 # RLE roots are 0-indexed
j == 0 && return mid
return m.root_blocks[2*j-1]
end
struct RLEIterator{T} # for method roots, T = UInt64 (even on 32-bit)
items::Vector{Any}
blocks::Vector{T}
defaultid::T
end
function RLEIterator(roots, blocks, defaultid)
T = promote_type(eltype(blocks), typeof(defaultid))
return RLEIterator{T}(convert(Vector{Any}, roots), blocks, defaultid)
end
RLEIterator(m::Method) = RLEIterator(m.roots, m.root_blocks, rootid(m))
Base.iterate(iter::RLEIterator) = iterate(iter, (0, 0, iter.defaultid))
function Base.iterate(iter::RLEIterator, (i, j, cid))
i += 1
i > length(iter.items) && return nothing
r = iter.items[i]
while (j + 1 < length(iter.blocks) && i > iter.blocks[j+2])
cid = iter.blocks[j+1]
j += 2
end
return cid => r, (i, j, cid)
end
function group_roots(m::Method)
mid = rootid(m)
isdefined(m, :root_blocks) || return Dict(mid => m.roots)
group_roots(RLEIterator(m.roots, m.root_blocks, mid))
end
function group_roots(iter::RLEIterator)
rootsby = Dict{typeof(iter.defaultid),Vector{Any}}()
for (id, r) in iter
list = get!(valtype(rootsby), rootsby, id)
push!(list, r)
end
return rootsby
end
precompile_test_harness("basic precompile functionality") do dir2
precompile_test_harness(false) do dir
Foo_file = joinpath(dir, "$Foo_module.jl")
Foo2_file = joinpath(dir, "$Foo2_module.jl")
FooBase_file = joinpath(dir, "$FooBase_module.jl")
write(FooBase_file,
"""
false && __precompile__(false)
module $FooBase_module
import Base: hash, >
struct fmpz end
struct typeA end
>(x::fmpz, y::Int) = Base.cmp(x, y) > 0
function hash(a::typeA, h::UInt)
d = den(a)
return h
end
end
""")
write(Foo2_file,
"""
module $Foo2_module
export override
override(x::Integer) = 2
override(x::AbstractFloat) = Float64(override(1))
end
""")
write(Foo_file,
"""
module $Foo_module
import $FooBase_module, $FooBase_module.typeA
import $Foo2_module: $Foo2_module, override
import $FooBase_module.hash
import Test
module Inner
import $FooBase_module.hash
using ..$Foo_module
import ..$Foo2_module
end
struct typeB
y::typeA
end
hash(x::typeB) = hash(x.y)
# test that docs get reconnected
@doc "foo function" foo(x) = x + 1
include_dependency("foo.jl")
include_dependency("foo.jl")
module Bar
include_dependency("bar.jl")
end
@doc "Bar module" Bar # this needs to define the META dictionary via eval
@eval Bar @doc "bar function" bar(x) = x + 2
# test for creation of some reasonably complicated type
struct MyType{T} end
const t17809s = Any[
Tuple{
Type{Ptr{MyType{i}}},
Ptr{Type{MyType{i}}},
Array{Ptr{MyType{MyType{:sym}()}}(0), 0},
Val{Complex{Int}(1, 2)},
Val{3},
Val{nothing}}
for i = 0:25]
# test that types and methods get reconnected correctly
# issue 16529 (adding a method to a type with no instances)
(::Task)(::UInt8, ::UInt16, ::UInt32) = 2
# issue 16471 (capturing references to a kwfunc)
Test.@test !isdefined(typeof(sin).name.mt, :kwsorter)
Base.sin(::UInt8, ::UInt16, ::UInt32; x = 52) = x
const sinkw = Core.kwfunc(Base.sin)
# issue 16908 (some complicated types and external method definitions)
abstract type CategoricalPool{T, R <: Integer, V} end
abstract type CategoricalValue{T, R <: Integer} end
struct NominalPool{T, R <: Integer, V} <: CategoricalPool{T, R, V}
index::Vector{T}
invindex::Dict{T, R}
order::Vector{R}
ordered::Vector{T}
valindex::Vector{V}
end
struct NominalValue{T, R <: Integer} <: CategoricalValue{T, R}
level::R
pool::NominalPool{T, R, NominalValue{T, R}}
end
struct OrdinalValue{T, R <: Integer} <: CategoricalValue{T, R}
level::R
pool::NominalPool{T, R, NominalValue{T, R}}
end
(::Union{Type{NominalValue}, Type{OrdinalValue}})() = 1
(::Union{Type{NominalValue{T}}, Type{OrdinalValue{T}}})() where {T} = 2
(::Type{Vector{NominalValue{T, R}}})() where {T, R} = 3
(::Type{Vector{NominalValue{T, T}}})() where {T} = 4
(::Type{Vector{NominalValue{Int, Int}}})() = 5
# more tests for method signature involving a complicated type
# issue 18343
struct Pool18343{R, V}
valindex::Vector{V}
end
struct Value18343{T, R}
pool::Pool18343{R, Value18343{T, R}}
end
Base.convert(::Type{Some{S}}, ::Value18343{Some}) where {S} = 2
Base.convert(::Type{Some{Value18343}}, ::Value18343{Some}) = 2
Base.convert(::Type{Ref}, ::Value18343{T}) where {T} = 3
# issue #28297
mutable struct Result
result::Union{Int,Missing}
end
const x28297 = Result(missing)
const d29936a = UnionAll(Dict.var, UnionAll(Dict.body.var, Dict.body.body))
const d29936b = UnionAll(Dict.body.var, UnionAll(Dict.var, Dict.body.body))
# issue #28998
const x28998 = [missing, 2, missing, 6, missing,
missing, missing, missing,
missing, missing, missing,
missing, missing, 6]
let some_method = which(Base.include, (Module, String,))
# global const some_method // FIXME: support for serializing a direct reference to an external Method not implemented
global const some_linfo = Core.Compiler.specialize_method(some_method,
Tuple{typeof(Base.include), Module, String}, Core.svec())
end
g() = override(1.0)
Test.@test g() === 2.0 # compile this
const abigfloat_f() = big"12.34"
const abigfloat_x = big"43.21"
const abigint_f() = big"123"
const abigint_x = big"124"
# issue #31488
_v31488 = Base.StringVector(2)
resize!(_v31488, 0)
const a31488 = fill(String(_v31488), 100)
const ptr1 = Ptr{UInt8}(1)
ptr2 = Ptr{UInt8}(1)
const ptr3 = Ptr{UInt8}(-1)
const layout1 = Ptr{Int8}[Ptr{Int8}(0), Ptr{Int8}(1), Ptr{Int8}(-1)]
const layout2 = Any[Ptr{Int8}(0), Ptr{Int16}(1), Ptr{Int32}(-1)]
const layout3 = collect(x.match for x in eachmatch(r"..", "abcdefghijk"))::Vector{SubString{String}}
# create a backedge that includes Type{Union{}}, to ensure lookup can handle that
call_bottom() = show(stdout, Union{})
Core.Compiler.return_type(call_bottom, Tuple{})
# check that @ccallable works from precompiled modules
Base.@ccallable Cint f35014(x::Cint) = x+Cint(1)
end
""")
# make sure `sin` didn't have a kwfunc (which would invalidate the attempted test)
@test !isdefined(typeof(sin).name.mt, :kwsorter)
# Issue #12623
@test __precompile__(false) === nothing
# Issue #21307
Foo2 = Base.require(Main, Foo2_module)
@eval $Foo2.override(::Int) = 'a'
@eval $Foo2.override(::Float32) = 'b'
Foo = Base.require(Main, Foo_module)
Base.invokelatest() do # use invokelatest to see the results of loading the compile
@test Foo.foo(17) == 18
@test Foo.Bar.bar(17) == 19
# Issue #21307
@test Foo.g() === 97.0
@test Foo.override(1.0e0) == Float64('a')
@test Foo.override(1.0f0) == 'b'
@test Foo.override(UInt(1)) == 2
# Issue #15722
@test Foo.abigfloat_f()::BigFloat == big"12.34"
@test (Foo.abigfloat_x::BigFloat + 21) == big"64.21"
@test Foo.abigint_f()::BigInt == big"123"
@test Foo.abigint_x::BigInt + 1 == big"125"
@test Foo.x28297.result === missing
@test Foo.d29936a === Dict
@test Foo.d29936b === Dict{K,V} where {V,K}
@test Foo.x28998[end] == 6
@test Foo.a31488 == fill("", 100)
@test Foo.ptr1 === Ptr{UInt8}(1)
@test Foo.ptr2 === Ptr{UInt8}(0)
@test Foo.ptr3 === Ptr{UInt8}(-1)
@test Foo.layout1::Vector{Ptr{Int8}} == Ptr{Int8}[Ptr{Int8}(0), Ptr{Int8}(0), Ptr{Int8}(-1)]
@test Foo.layout2 == Any[Ptr{Int8}(0), Ptr{Int16}(0), Ptr{Int32}(-1)]
@test typeof.(Foo.layout2) == [Ptr{Int8}, Ptr{Int16}, Ptr{Int32}]
@test Foo.layout3 == ["ab", "cd", "ef", "gh", "ij"]
end
@eval begin function ccallable_test()
Base.llvmcall(
("""declare i32 @f35014(i32)
define i32 @entry() {
0:
%1 = call i32 @f35014(i32 3)
ret i32 %1
}""", "entry"
), Cint, Tuple{})
end
@test ccallable_test() == 4
end
cachedir = joinpath(dir, "compiled", "v$(VERSION.major).$(VERSION.minor)")
cachedir2 = joinpath(dir2, "compiled", "v$(VERSION.major).$(VERSION.minor)")
cachefile = joinpath(cachedir, "$Foo_module.ji")
# use _require_from_serialized to ensure that the test fails if
# the module doesn't reload from the image:
@test_warn "@ccallable was already defined for this method name" begin
@test_logs (:warn, "Replacing module `$Foo_module`") begin
ms = Base._require_from_serialized(Base.PkgId(Foo), cachefile)
@test isa(ms, Array{Any,1})
end
end
@test_throws MethodError Foo.foo(17) # world shouldn't be visible yet
Base.invokelatest() do # use invokelatest to see the results of loading the compile
@test Foo.foo(17) == 18
@test Foo.Bar.bar(17) == 19
# Issue #21307
@test Foo.g() === 97.0
@test Foo.override(1.0e0) == Float64('a')
@test Foo.override(1.0f0) == 'b'
@test Foo.override(UInt(1)) == 2
# issue #12284:
@test string(Base.Docs.doc(Foo.foo)) == "foo function\n"
@test string(Base.Docs.doc(Foo.Bar.bar)) == "bar function\n"
@test string(Base.Docs.doc(Foo.Bar)) == "Bar module\n"
modules, (deps, requires), required_modules = Base.parse_cache_header(cachefile)
discard_module = mod_fl_mt -> (mod_fl_mt.filename, mod_fl_mt.mtime)
@test modules == [ Base.PkgId(Foo) => Base.module_build_id(Foo) ]
@test map(x -> x.filename, deps) == [ Foo_file, joinpath(dir, "foo.jl"), joinpath(dir, "bar.jl") ]
@test requires == [ Base.PkgId(Foo) => Base.PkgId(string(FooBase_module)),
Base.PkgId(Foo) => Base.PkgId(Foo2),
Base.PkgId(Foo) => Base.PkgId(Test),
Base.PkgId(Foo) => Base.PkgId(string(FooBase_module)) ]
srctxt = Base.read_dependency_src(cachefile, Foo_file)
@test !isempty(srctxt) && srctxt == read(Foo_file, String)
@test_throws ErrorException Base.read_dependency_src(cachefile, "/tmp/nonexistent.txt")
# dependencies declared with `include_dependency` should not be stored
@test_throws ErrorException Base.read_dependency_src(cachefile, joinpath(dir, "foo.jl"))
modules, deps1 = Base.cache_dependencies(cachefile)
@test Dict(modules) == merge(
Dict(let m = Base.PkgId(s)
m => Base.module_build_id(Base.root_module(m))
end for s in
[ "Base", "Core", "Main",
string(Foo2_module), string(FooBase_module) ]),
# plus modules included in the system image
Dict(let m = Base.root_module(Base, s)
Base.PkgId(m) => Base.module_build_id(m)
end for s in
[:ArgTools, :Artifacts, :Base64, :CompilerSupportLibraries_jll, :CRC32c, :Dates,
:Distributed, :Downloads, :FileWatching, :Future, :InteractiveUtils, :libblastrampoline_jll,
:LazyArtifacts, :LibCURL, :LibCURL_jll, :LibGit2, :Libdl, :LinearAlgebra,
:Logging, :Markdown, :Mmap, :MozillaCACerts_jll, :NetworkOptions, :OpenBLAS_jll, :Pkg, :Printf,
:Profile, :p7zip_jll, :REPL, :Random, :SHA, :Serialization, :SharedArrays, :Sockets,
:TOML, :Tar, :Test, :UUIDs, :Unicode,
:nghttp2_jll]
),
)
@test discard_module.(deps) == deps1
modules, (deps, requires), required_modules = Base.parse_cache_header(cachefile; srcfiles_only=true)
@test map(x -> x.filename, deps) == [Foo_file]
@test current_task()(0x01, 0x4000, 0x30031234) == 2
@test sin(0x01, 0x4000, 0x30031234) == 52
@test sin(0x01, 0x4000, 0x30031234; x = 9142) == 9142
@test Foo.sinkw === Core.kwfunc(Base.sin)
@test Foo.NominalValue() == 1
@test Foo.OrdinalValue() == 1
@test Foo.NominalValue{Int}() == 2
@test Foo.OrdinalValue{Int}() == 2
let T = Vector{Foo.NominalValue{Int}}
@test isa(T(), T)
end
@test Vector{Foo.NominalValue{Int32, Int64}}() == 3
@test Vector{Foo.NominalValue{UInt, UInt}}() == 4
@test Vector{Foo.NominalValue{Int, Int}}() == 5
@test all(i -> Foo.t17809s[i + 1] ===
Tuple{
Type{Ptr{Foo.MyType{i}}},
Ptr{Type{Foo.MyType{i}}},
Array{Ptr{Foo.MyType{Foo.MyType{:sym}()}}(0), 0},
Val{Complex{Int}(1, 2)},
Val{3},
Val{nothing}},
0:25)
some_method = which(Base.include, (Module, String,))
some_linfo = Core.Compiler.specialize_method(some_method, Tuple{typeof(Base.include), Module, String}, Core.svec())
@test Foo.some_linfo::Core.MethodInstance === some_linfo
ft = Base.datatype_fieldtypes
PV = ft(Foo.Value18343{Some}.body)[1]
VR = ft(PV)[1].parameters[1]
@test ft(PV)[1] === Array{VR,1}
@test pointer_from_objref(ft(PV)[1]) ===
pointer_from_objref(ft(ft(ft(PV)[1].parameters[1])[1])[1])
@test PV === ft(ft(PV)[1].parameters[1])[1]
@test pointer_from_objref(PV) === pointer_from_objref(ft(ft(PV)[1].parameters[1])[1])
end
Nest_module = :Nest4b3a94a1a081a8cb
Nest_file = joinpath(dir, "$Nest_module.jl")
NestInner_file = joinpath(dir, "$(Nest_module)Inner.jl")
NestInner2_file = joinpath(dir, "$(Nest_module)Inner2.jl")
write(Nest_file,
"""
module $Nest_module
include("$(escape_string(NestInner_file))")
end
""")
write(NestInner_file,
"""
module NestInner
include("$(escape_string(NestInner2_file))")
end
""")
write(NestInner2_file,
"""
f() = 22
""")
Nest = Base.require(Main, Nest_module)
cachefile = joinpath(cachedir, "$Nest_module.ji")
modules, (deps, requires), required_modules = Base.parse_cache_header(cachefile)
@test last(deps).modpath == ["NestInner"]
UsesB_module = :UsesB4b3a94a1a081a8cb
B_module = :UsesB4b3a94a1a081a8cb_B
UsesB_file = joinpath(dir, "$UsesB_module.jl")
B_file = joinpath(dir, "$(B_module).jl")
write(UsesB_file,
"""
module $UsesB_module
using $B_module
end
""")
write(B_file,
"""
module $B_module
export bfunc
bfunc() = 33
end
""")
UsesB = Base.require(Main, UsesB_module)
cachefile = joinpath(cachedir, "$UsesB_module.ji")
modules, (deps, requires), required_modules = Base.parse_cache_header(cachefile)
id1, id2 = only(requires)
@test Base.pkgorigins[id1].cachepath == cachefile
@test Base.pkgorigins[id2].cachepath == joinpath(cachedir, "$B_module.ji")
Baz_file = joinpath(dir, "Baz.jl")
write(Baz_file,
"""
true && __precompile__(false)
module Baz
baz() = 1
end
""")
@test Base.compilecache(Base.PkgId("Baz")) == Base.PrecompilableError() # due to __precompile__(false)
@eval using Baz
@test Base.invokelatest(Baz.baz) == 1
# Issue #12720
FooBar1_file = joinpath(dir, "FooBar1.jl")
write(FooBar1_file,
"""
module FooBar1
using FooBar
end
""")
sleep(2) # give FooBar and FooBar1 different timestamps, in reverse order too
FooBar_file = joinpath(dir, "FooBar.jl")
write(FooBar_file,
"""
module FooBar
end
""")
cachefile = Base.compilecache(Base.PkgId("FooBar"))
empty_prefs_hash = Base.get_preferences_hash(nothing, String[])
@test cachefile == Base.compilecache_path(Base.PkgId("FooBar"), empty_prefs_hash)
@test isfile(joinpath(cachedir, "FooBar.ji"))
@test Base.stale_cachefile(FooBar_file, joinpath(cachedir, "FooBar.ji")) isa Vector
@test !isdefined(Main, :FooBar)
@test !isdefined(Main, :FooBar1)
relFooBar_file = joinpath(dir, "subfolder", "..", "FooBar.jl")
@test Base.stale_cachefile(relFooBar_file, joinpath(cachedir, "FooBar.ji")) isa (Sys.iswindows() ? Vector : Bool) # `..` is not a symlink on Windows
mkdir(joinpath(dir, "subfolder"))
@test Base.stale_cachefile(relFooBar_file, joinpath(cachedir, "FooBar.ji")) isa Vector
@eval using FooBar
fb_uuid = Base.module_build_id(FooBar)
sleep(2); touch(FooBar_file)
insert!(DEPOT_PATH, 1, dir2)
@test Base.stale_cachefile(FooBar_file, joinpath(cachedir, "FooBar.ji")) === true
@eval using FooBar1
@test !isfile(joinpath(cachedir2, "FooBar.ji"))
@test !isfile(joinpath(cachedir, "FooBar1.ji"))
@test isfile(joinpath(cachedir2, "FooBar1.ji"))
@test Base.stale_cachefile(FooBar_file, joinpath(cachedir, "FooBar.ji")) === true
@test Base.stale_cachefile(FooBar1_file, joinpath(cachedir2, "FooBar1.ji")) isa Vector
@test fb_uuid == Base.module_build_id(FooBar)
fb_uuid1 = Base.module_build_id(FooBar1)
@test fb_uuid != fb_uuid1
# test checksum
open(joinpath(cachedir2, "FooBar1.ji"), "a") do f
write(f, 0x076cac96) # append 4 random bytes
end
@test Base.stale_cachefile(FooBar1_file, joinpath(cachedir2, "FooBar1.ji")) === true
# test behavior of precompile modules that throw errors
FooBar2_file = joinpath(dir, "FooBar2.jl")
write(FooBar2_file,
"""
module FooBar2
error("break me")
end
""")
@test_warn r"LoadError: break me\nStacktrace:\n \[1\] [\e01m\[]*error" try
Base.require(Main, :FooBar2)
error("the \"break me\" test failed")
catch exc
isa(exc, ErrorException) || rethrow()
occursin("ERROR: LoadError: break me", exc.msg) && rethrow()
end
# Test that trying to eval into closed modules during precompilation is an error
FooBar3_file = joinpath(dir, "FooBar3.jl")
FooBar3_inc = joinpath(dir, "FooBar3_inc.jl")
write(FooBar3_inc, "x=1\n")
for code in ["Core.eval(Base, :(x=1))", "Base.include(Base, \"FooBar3_inc.jl\")"]
write(FooBar3_file, code)
@test_warn "Evaluation into the closed module `Base` breaks incremental compilation" try
Base.require(Main, :FooBar3)
catch exc
isa(exc, ErrorException) || rethrow()
end
end
# Test transitive dependency for #21266
FooBarT_file = joinpath(dir, "FooBarT.jl")
write(FooBarT_file,
"""
module FooBarT
end
""")
FooBarT1_file = joinpath(dir, "FooBarT1.jl")
write(FooBarT1_file,
"""
module FooBarT1
using FooBarT
end
""")
FooBarT2_file = joinpath(dir, "FooBarT2.jl")
write(FooBarT2_file,
"""
module FooBarT2
using FooBarT1
end
""")
Base.compilecache(Base.PkgId("FooBarT2"))
write(FooBarT1_file,
"""
module FooBarT1
end
""")
rm(FooBarT_file)
@test Base.stale_cachefile(FooBarT2_file, joinpath(cachedir2, "FooBarT2.ji")) === true
@test Base.require(Main, :FooBarT2) isa Module
end
end
# method root provenance & external code caching
precompile_test_harness("code caching") do dir
Bid = rootid(Base)
Cache_module = :Cacheb8321416e8a3e2f1
# Note: calling setindex!(::Dict{K,V}, ::Any, ::K) adds both compression and codegen roots
write(joinpath(dir, "$Cache_module.jl"),
"""
module $Cache_module
struct X end
struct X2 end
@noinline function f(d)
@noinline
d[X()] = nothing
end
@noinline fpush(dest) = push!(dest, X())
function callboth()
f(Dict{X,Any}())
fpush(X[])
nothing
end
function getelsize(list::Vector{T}) where T
n = 0
for item in list
n += sizeof(T)
end
return n
end
precompile(callboth, ())
precompile(getelsize, (Vector{Int32},))
end
""")
Base.compilecache(Base.PkgId(string(Cache_module)))
@eval using $Cache_module
M = getfield(@__MODULE__, Cache_module)
# Test that this cache file "owns" all the roots
Mid = rootid(M)
for name in (:f, :fpush, :callboth)
func = getfield(M, name)
m = only(collect(methods(func)))
@test all(i -> root_provenance(m, i) == Mid, 1:length(m.roots))
end
# Check that we can cache external CodeInstances:
# size(::Vector) has an inferred specialization for Vector{X}
msize = which(size, (Vector{<:Any},))
hasspec = false
for i = 1:length(msize.specializations)
if isassigned(msize.specializations, i)
mi = msize.specializations[i]
if isa(mi, Core.MethodInstance)
tt = Base.unwrap_unionall(mi.specTypes)
if tt.parameters[2] == Vector{Cacheb8321416e8a3e2f1.X}
if isdefined(mi, :cache) && isa(mi.cache, Core.CodeInstance) && mi.cache.max_world == typemax(UInt) && mi.cache.inferred !== nothing
hasspec = true
break
end
end
end
end
end
@test hasspec
# Test that compilation adds to method roots with appropriate provenance
m = which(setindex!, (Dict{M.X,Any}, Any, M.X))
@test M.X ∈ m.roots
# Check that roots added outside of incremental builds get attributed to a moduleid of 0
Base.invokelatest() do
Dict{M.X2,Any}()[M.X2()] = nothing
end
@test M.X2 ∈ m.roots
groups = group_roots(m)
@test M.X ∈ groups[Mid] # attributed to M
@test M.X2 ∈ groups[0] # activate module is not known
@test !isempty(groups[Bid])
# Check that internal methods and their roots are accounted appropriately
minternal = which(M.getelsize, (Vector,))
mi = minternal.specializations[1]
@test Base.unwrap_unionall(mi.specTypes).parameters[2] == Vector{Int32}
ci = mi.cache
@test ci.relocatability == 1
@test ci.inferred !== nothing
# ...and that we can add "untracked" roots & non-relocatable CodeInstances to them too
Base.invokelatest() do
M.getelsize(M.X2[])
end
mi = minternal.specializations[2]
ci = mi.cache
@test ci.relocatability == 0
# PkgA loads PkgB, and both add roots to the same `push!` method (both before and after loading B)
Cache_module2 = :Cachea1544c83560f0c99
write(joinpath(dir, "$Cache_module2.jl"),
"""
module $Cache_module2
struct Y end
@noinline f(dest) = push!(dest, Y())
callf() = f(Y[])
callf()
using $(Cache_module)
struct Z end
@noinline g(dest) = push!(dest, Z())
callg() = g(Z[])
callg()
end
""")
Base.compilecache(Base.PkgId(string(Cache_module2)))
@eval using $Cache_module2
M2 = getfield(@__MODULE__, Cache_module2)
M2id = rootid(M2)
dest = []
Base.invokelatest() do # use invokelatest to see the results of loading the compile
M2.f(dest)
M.fpush(dest)
M2.g(dest)
@test dest == [M2.Y(), M.X(), M2.Z()]
@test M2.callf() == [M2.Y()]
@test M2.callg() == [M2.Z()]
@test M.fpush(M.X[]) == [M.X()]
end
mT = which(push!, (Vector{T} where T, Any))
groups = group_roots(mT)
@test M2.Y ∈ groups[M2id]
@test M2.Z ∈ groups[M2id]
@test M.X ∈ groups[Mid]
@test M.X ∉ groups[M2id]
# backedges of external MethodInstances
# Root gets used by RootA and RootB, and both consumers end up inferring the same MethodInstance from Root
# Do both callers get listed as backedges?
RootModule = :Root_0xab07d60518763a7e
write(joinpath(dir, "$RootModule.jl"),
"""
module $RootModule
function f(x)
while x < 10
x += oftype(x, 1)
end
return x
end
g1() = f(Int16(9))
g2() = f(Int16(9))
# all deliberately uncompiled
end
""")
RootA = :RootA_0xab07d60518763a7e
write(joinpath(dir, "$RootA.jl"),
"""
module $RootA
using $RootModule
fA() = $RootModule.f(Int8(4))
fA()
$RootModule.g1()
end
""")
RootB = :RootB_0xab07d60518763a7e
write(joinpath(dir, "$RootB.jl"),
"""
module $RootB
using $RootModule
fB() = $RootModule.f(Int8(4))
fB()
$RootModule.g2()
end
""")
Base.compilecache(Base.PkgId(string(RootA)))
Base.compilecache(Base.PkgId(string(RootB)))
@eval using $RootA
@eval using $RootB
MA = getfield(@__MODULE__, RootA)
MB = getfield(@__MODULE__, RootB)
M = getfield(MA, RootModule)
m = which(M.f, (Any,))
for mi in m.specializations
mi === nothing && continue
if mi.specTypes.parameters[2] === Int8
# external callers
mods = Module[]
for be in mi.backedges
push!(mods, be.def.module)
end
@test MA ∈ mods
@test MB ∈ mods
@test length(mods) == 2
elseif mi.specTypes.parameters[2] === Int16
# internal callers
meths = Method[]
for be in mi.backedges
push!(meths, be.def)
end
@test which(M.g1, ()) ∈ meths
@test which(M.g2, ()) ∈ meths
@test length(meths) == 2
end
end
# Invalidations (this test is adapted from from SnoopCompile)
function hasvalid(mi, world)
isdefined(mi, :cache) || return false
ci = mi.cache
while true
ci.max_world >= world && return true
isdefined(ci, :next) || return false
ci = ci.next
end
end
StaleA = :StaleA_0xab07d60518763a7e
StaleB = :StaleB_0xab07d60518763a7e
StaleC = :StaleC_0xab07d60518763a7e
write(joinpath(dir, "$StaleA.jl"),
"""
module $StaleA
stale(x) = rand(1:8)
stale(x::Int) = length(digits(x))
not_stale(x::String) = first(x)
use_stale(c) = stale(c[1]) + not_stale("hello")
build_stale(x) = use_stale(Any[x])
# force precompilation
build_stale(37)
stale('c')
end
"""
)
write(joinpath(dir, "$StaleB.jl"),
"""
module $StaleB
# StaleB does not know about StaleC when it is being built.
# However, if StaleC is loaded first, we get `"jl_insert_method_instance"`
# invalidations.
using $StaleA
# This will be invalidated if StaleC is loaded
useA() = $StaleA.stale("hello")
# force precompilation
useA()
end
"""
)
write(joinpath(dir, "$StaleC.jl"),
"""
module $StaleC
using $StaleA
$StaleA.stale(x::String) = length(x)
call_buildstale(x) = $StaleA.build_stale(x)
call_buildstale("hey")
end # module
"""
)
for pkg in (StaleA, StaleB, StaleC)
Base.compilecache(Base.PkgId(string(pkg)))
end
@eval using $StaleA
@eval using $StaleC
@eval using $StaleB
MA = getfield(@__MODULE__, StaleA)
MB = getfield(@__MODULE__, StaleB)
MC = getfield(@__MODULE__, StaleC)
world = Base.get_world_counter()
m = only(methods(MA.use_stale))
mi = m.specializations[1]
@test hasvalid(mi, world) # it was re-inferred by StaleC
m = only(methods(MA.build_stale))
mis = filter(!isnothing, collect(m.specializations))
@test length(mis) == 2
for mi in mis
if mi.specTypes.parameters[2] == Int
@test mi.cache.max_world < world
else
# The variant for String got "healed" by recompilation in StaleC
@test mi.specTypes.parameters[2] == String
@test mi.cache.max_world == typemax(UInt)
end
end
m = only(methods(MB.useA))
mi = m.specializations[1]
@test !hasvalid(mi, world) # invalidated by the stale(x::String) method in StaleC
m = only(methods(MC.call_buildstale))
mi = m.specializations[1]
@test hasvalid(mi, world) # was compiled with the new method
end
# test --compiled-modules=no command line option
precompile_test_harness("--compiled-modules=no") do dir
Time_module = :Time4b3a94a1a081a8cb
write(joinpath(dir, "$Time_module.jl"),
"""
module $Time_module
time = Base.time()
end
""")
Base.compilecache(Base.PkgId("Time4b3a94a1a081a8cb"))
exename = `$(Base.julia_cmd()) --compiled-modules=yes --startup-file=no`
testcode = """
insert!(LOAD_PATH, 1, $(repr(dir)))
insert!(DEPOT_PATH, 1, $(repr(dir)))
using $Time_module
getfield($Time_module, :time)
"""
t1_yes = readchomp(`$exename --compiled-modules=yes -E $(testcode)`)
t2_yes = readchomp(`$exename --compiled-modules=yes -E $(testcode)`)
@test t1_yes == t2_yes
t1_no = readchomp(`$exename --compiled-modules=no -E $(testcode)`)
t2_no = readchomp(`$exename --compiled-modules=no -E $(testcode)`)
@test t1_no != t2_no
@test parse(Float64, t1_no) < parse(Float64, t2_no)
end
# test loading a package with conflicting namespace
precompile_test_harness("conflicting namespaces") do dir
Test_module = :Test6c92f26
write(joinpath(dir, "Iterators.jl"),
"""
module Iterators
end
""")
write(joinpath(dir, "$Test_module.jl"),
"""
module $Test_module
import Iterators # FIXME: use `using`
end
""")
testcode = """
insert!(LOAD_PATH, 1, $(repr(dir)))
insert!(DEPOT_PATH, 1, $(repr(dir)))
using $Test_module
println(stderr, $Test_module.Iterators)
"""
exename = `$(Base.julia_cmd()) --startup-file=no`
let fname = tempname()
try
for i = 1:2
@test readchomp(pipeline(`$exename -E $(testcode)`, stderr=fname)) == "nothing"
@test read(fname, String) == "Iterators\n"
end
finally
rm(fname, force=true)
end
end
end
precompile_test_harness("package_callbacks") do dir
loaded_modules = Channel{Symbol}(32)
callback = (mod::Base.PkgId) -> put!(loaded_modules, Symbol(mod.name))
push!(Base.package_callbacks, callback)
try
Test1_module = :Teste4095a81
Test2_module = :Teste4095a82
Test3_module = :Teste4095a83
write(joinpath(dir, "$(Test1_module).jl"),
"""
module $(Test1_module)
end
""")
Base.compilecache(Base.PkgId("$(Test1_module)"))
write(joinpath(dir, "$(Test2_module).jl"),
"""
module $(Test2_module)
using $(Test1_module)
end
""")
Base.compilecache(Base.PkgId("$(Test2_module)"))
@test !Base.isbindingresolved(Main, Test2_module)
Base.require(Main, Test2_module)
@test take!(loaded_modules) == Test1_module
@test take!(loaded_modules) == Test2_module
write(joinpath(dir, "$(Test3_module).jl"),
"""
module $(Test3_module)
using $(Test3_module)
end
""")
Base.require(Main, Test3_module)
@test take!(loaded_modules) == Test3_module
finally
pop!(Base.package_callbacks)
end
L = ReentrantLock()
E = Base.Event()
t = errormonitor(@async lock(L) do
wait(E)
Base.root_module_key(Base)
end)
Test4_module = :Teste4095a84
write(joinpath(dir, "$(Test4_module).jl"),
"""
module $(Test4_module)
end
""")
Base.compilecache(Base.PkgId("$(Test4_module)"))
push!(Base.package_callbacks, _->(notify(E); lock(L) do; end))
# should not hang here
try
@eval using $(Symbol(Test4_module))
wait(t)
finally
pop!(Base.package_callbacks)
end
end
# Issue #19960
(f -> f())() do # wrap in function scope, so we can test world errors
test_workers = addprocs(1)
push!(test_workers, myid())
save_cwd = pwd()
temp_path = mktempdir()
try
cd(temp_path)
load_path = mktempdir(temp_path)
load_cache_path = mktempdir(temp_path)
ModuleA = :Issue19960A
ModuleB = :Issue19960B
write(joinpath(load_path, "$ModuleA.jl"),
"""
module $ModuleA
import Distributed: myid
export f
f() = myid()
end
""")
write(joinpath(load_path, "$ModuleB.jl"),
"""
module $ModuleB
using $ModuleA
export g
g() = f()
end
""")
@everywhere test_workers begin
pushfirst!(LOAD_PATH, $load_path)
pushfirst!(DEPOT_PATH, $load_cache_path)
end
try
@eval using $ModuleB
uuid = Base.module_build_id(Base.root_module(Main, ModuleB))
for wid in test_workers
@test Distributed.remotecall_eval(Main, wid, quote
Base.module_build_id(Base.root_module(Main, $(QuoteNode(ModuleB))))
end) == uuid
if wid != myid() # avoid world-age errors on the local proc
@test remotecall_fetch(g, wid) == wid
end
end
finally
@everywhere test_workers begin
popfirst!(LOAD_PATH)
popfirst!(DEPOT_PATH)
end
end
finally
cd(save_cwd)
rm(temp_path, recursive=true)
pop!(test_workers) # remove myid
rmprocs(test_workers)
end
end
# Ensure that module-loading plays nicely with Base.delete_method
# wrapped in function scope, so we can test world errors
precompile_test_harness("delete_method") do dir
A_module = :Aedb164bd3a126418
B_module = :Bedb164bd3a126418
A_file = joinpath(dir, "$A_module.jl")
B_file = joinpath(dir, "$B_module.jl")
write(A_file,
"""
module $A_module
export apc, anopc
apc(::Int, ::Int) = 1
apc(::Any, ::Any) = 2
anopc(::Int, ::Int) = 1
anopc(::Any, ::Any) = 2
end
""")
write(B_file,
"""
module $B_module
using $A_module
bpc(x) = apc(x, x)
bnopc(x) = anopc(x, x)
precompile(bpc, (Int,))
precompile(bpc, (Float64,))
end
""")
A = Base.require(Main, A_module)
for mths in (collect(methods(A.apc)), collect(methods(A.anopc)))
Base.delete_method(mths[1])
end
B = Base.require(Main, B_module)
@test Base.invokelatest(B.bpc, 1) == Base.invokelatest(B.bpc, 1.0) == 2
@test Base.invokelatest(B.bnopc, 1) == Base.invokelatest(B.bnopc, 1.0) == 2
end
precompile_test_harness("Issues #19030 and #25279") do load_path
ModuleA = :Issue19030
write(joinpath(load_path, "$ModuleA.jl"),
"""
module $ModuleA
__init__() = push!(Base.package_callbacks, sym->nothing)
end
""")
l0 = length(Base.package_callbacks)
@eval using $ModuleA
@test length(Base.package_callbacks) == l0 + 1
end
precompile_test_harness("Issue #25604") do load_path
write(joinpath(load_path, "A25604.jl"),
"""
module A25604
using B25604
using C25604
end
""")
write(joinpath(load_path, "B25604.jl"),
"""
module B25604
end
""")
write(joinpath(load_path, "C25604.jl"),
"""
module C25604
using B25604
end
""")
Base.compilecache(Base.PkgId("A25604"))
@test_nowarn @eval using A25604
end
precompile_test_harness("Issue #26028") do load_path
write(joinpath(load_path, "Foo26028.jl"),
"""
module Foo26028
module Bar26028
x = 0
end
function __init__()
include(joinpath(@__DIR__, "Baz26028.jl"))
end
end
""")
write(joinpath(load_path, "Baz26028.jl"),
"""
module Baz26028
import Foo26028.Bar26028.x
end
""")
Base.compilecache(Base.PkgId("Foo26028"))
@test_nowarn @eval using Foo26028
end
precompile_test_harness("Issue #29936") do load_path
write(joinpath(load_path, "Foo29936.jl"),
"""
module Foo29936
const global m = Val{nothing}()
const global h = Val{:hey}()
wab = [("a", m), ("b", h),]
end
""")
@eval using Foo29936
@test [("Plan", Foo29936.m), ("Plan", Foo29936.h),] isa Vector{Tuple{String,Val}}
end
precompile_test_harness("Issue #25971") do load_path
sourcefile = joinpath(load_path, "Foo25971.jl")
write(sourcefile, "module Foo25971 end")
chmod(sourcefile, 0o666)
cachefile = Base.compilecache(Base.PkgId("Foo25971"))
@test filemode(sourcefile) == filemode(cachefile)
chmod(sourcefile, 0o600)
cachefile = Base.compilecache(Base.PkgId("Foo25971"))
@test filemode(sourcefile) == filemode(cachefile)
chmod(sourcefile, 0o444)
cachefile = Base.compilecache(Base.PkgId("Foo25971"))
# Check writable
@test touch(cachefile) == cachefile
end
precompile_test_harness("Issue #38312") do load_path
TheType = """Array{Ref{Val{1}}, 1}"""
write(joinpath(load_path, "Foo38312.jl"),
"""
module Foo38312
const TheType = $TheType
end
""")
write(joinpath(load_path, "Bar38312.jl"),
"""
module Bar38312
const TheType = $TheType
end
""")
Base.compilecache(Base.PkgId("Foo38312"))
Base.compilecache(Base.PkgId("Bar38312"))
@test pointer_from_objref((@eval (using Foo38312; Foo38312)).TheType) ===
pointer_from_objref(eval(Meta.parse(TheType))) ===
pointer_from_objref((@eval (using Bar38312; Bar38312)).TheType)
end
precompile_test_harness("Opaque Closure") do load_path
write(joinpath(load_path, "OCPrecompile.jl"),
"""
module OCPrecompile
using Base.Experimental: @opaque
f(x) = @opaque y->x+y
end
""")
Base.compilecache(Base.PkgId("OCPrecompile"))
f = (@eval (using OCPrecompile; OCPrecompile)).f
@test Base.invokelatest(f, 1)(2) == 3
end
# issue #39405
precompile_test_harness("Renamed Imports") do load_path
write(joinpath(load_path, "RenameImports.jl"),
"""
module RenameImports
import Base.Experimental as ex
test() = ex
end
""")
Base.compilecache(Base.PkgId("RenameImports"))
@test (@eval (using RenameImports; RenameImports.test())) isa Module
end
# issue #41872 (example from #38983)
precompile_test_harness("No external edges") do load_path
write(joinpath(load_path, "NoExternalEdges.jl"),
"""
module NoExternalEdges
bar(x::Int) = hcat(rand())
@inline bar() = hcat(rand())
bar(x::Float64) = bar()
foo1() = bar(1)
foo2() = bar(1.0)
foo3() = bar()
foo4() = hcat(rand())
precompile(foo1, ())
precompile(foo2, ())
precompile(foo3, ())
precompile(foo4, ())
end
""")
Base.compilecache(Base.PkgId("NoExternalEdges"))
@eval begin
using NoExternalEdges
@test only(methods(NoExternalEdges.foo1)).specializations[1].cache.max_world != 0
@test only(methods(NoExternalEdges.foo2)).specializations[1].cache.max_world != 0
@test only(methods(NoExternalEdges.foo3)).specializations[1].cache.max_world != 0
@test only(methods(NoExternalEdges.foo4)).specializations[1].cache.max_world != 0
end
end
@testset "issue 38149" begin
M = Module()
@eval M begin
@nospecialize
f(x, y) = x + y
f(x::Int, y) = 2x + y
end
precompile(M.f, (Int, Any))
precompile(M.f, (AbstractFloat, Any))
mis = map(methods(M.f)) do m
m.specializations[1]
end
@test any(mi -> mi.specTypes.parameters[2] === Any, mis)
@test all(mi -> isa(mi.cache, Core.CodeInstance), mis)
end
# Test that the cachepath is available in pkgorigins during the
# __init__ callback
precompile_test_harness("__init__ cachepath") do load_path
write(joinpath(load_path, "InitCachePath.jl"),
"""
module InitCachePath
__init__() = Base.pkgorigins[Base.PkgId(InitCachePath)]
end
""")
@test isa((@eval (using InitCachePath; InitCachePath)), Module)
end
| 34.62877
| 152
| 0.566499
|
[
"@testset \"issue 38149\" begin\n M = Module()\n @eval M begin\n @nospecialize\n f(x, y) = x + y\n f(x::Int, y) = 2x + y\n end\n precompile(M.f, (Int, Any))\n precompile(M.f, (AbstractFloat, Any))\n mis = map(methods(M.f)) do m\n m.specializations[1]\n end\n @test any(mi -> mi.specTypes.parameters[2] === Any, mis)\n @test all(mi -> isa(mi.cache, Core.CodeInstance), mis)\nend",
"@testset \"$testset\" begin\n precompile_test_harness(f, true)\n end"
] |
f7e46ec3d41064780e59b866ae77ec4fd8d1c2ef
| 36,092
|
jl
|
Julia
|
stdlib/SuiteSparse/test/cholmod.jl
|
syntapy/julia
|
4fc446f1790fe04e227ff96ab75a01d130e2d930
|
[
"Zlib"
] | 1
|
2019-07-14T04:08:02.000Z
|
2019-07-14T04:08:02.000Z
|
stdlib/SuiteSparse/test/cholmod.jl
|
syntapy/julia
|
4fc446f1790fe04e227ff96ab75a01d130e2d930
|
[
"Zlib"
] | null | null | null |
stdlib/SuiteSparse/test/cholmod.jl
|
syntapy/julia
|
4fc446f1790fe04e227ff96ab75a01d130e2d930
|
[
"Zlib"
] | null | null | null |
# This file is a part of Julia. License is MIT: https://julialang.org/license
using SuiteSparse.CHOLMOD
using DelimitedFiles
using Test
using Random
using Serialization
using LinearAlgebra: issuccess, PosDefException
# CHOLMOD tests
Random.seed!(123)
@testset "based on deps/SuiteSparse-4.0.2/CHOLMOD/Demo/" begin
# chm_rdsp(joinpath(Sys.BINDIR, "../../deps/SuiteSparse-4.0.2/CHOLMOD/Demo/Matrix/bcsstk01.tri"))
# because the file may not exist in binary distributions and when a system suitesparse library
# is used
## Result from C program
## ---------------------------------- cholmod_demo:
## norm (A,inf) = 3.57095e+09
## norm (A,1) = 3.57095e+09
## CHOLMOD sparse: A: 48-by-48, nz 224, upper. OK
## CHOLMOD dense: B: 48-by-1, OK
## bnorm 1.97917
## Analyze: flop 6009 lnz 489
## Factorizing A
## CHOLMOD factor: L: 48-by-48 simplicial, LDL'. nzmax 489. nz 489 OK
## Ordering: AMD fl/lnz 12.3 lnz/anz 2.2
## ints in L: 782, doubles in L: 489
## factor flops 6009 nnz(L) 489 (w/no amalgamation)
## nnz(A*A'): 224
## flops / nnz(L): 12.3
## nnz(L) / nnz(A): 2.2
## analyze cputime: 0.0000
## factor cputime: 0.0000 mflop: 0.0
## solve cputime: 0.0000 mflop: 0.0
## overall cputime: 0.0000 mflop: 0.0
## peak memory usage: 0 (MB)
## residual 2.5e-19 (|Ax-b|/(|A||x|+|b|))
## residual 1.3e-19 (|Ax-b|/(|A||x|+|b|)) after iterative refinement
## rcond 9.5e-06
n = 48
A = CHOLMOD.Sparse(n, n,
CHOLMOD.SuiteSparse_long[0,1,2,3,6,9,12,15,18,20,25,30,34,36,39,43,47,52,58,
62,67,71,77,84,90,93,95,98,103,106,110,115,119,123,130,136,142,146,150,155,
161,167,174,182,189,197,207,215,224], # zero-based column pointers
CHOLMOD.SuiteSparse_long[0,1,2,1,2,3,0,2,4,0,1,5,0,4,6,1,3,7,2,8,1,3,7,8,9,
0,4,6,8,10,5,6,7,11,6,12,7,11,13,8,10,13,14,9,13,14,15,8,10,12,14,16,7,11,
12,13,16,17,0,12,16,18,1,5,13,15,19,2,4,14,20,3,13,15,19,20,21,2,4,12,16,18,
20,22,1,5,17,18,19,23,0,5,24,1,25,2,3,26,2,3,25,26,27,4,24,28,0,5,24,29,6,
11,24,28,30,7,25,27,31,8,9,26,32,8,9,25,27,31,32,33,10,24,28,30,32,34,6,11,
29,30,31,35,12,17,30,36,13,31,35,37,14,15,32,34,38,14,15,33,37,38,39,16,32,
34,36,38,40,12,17,31,35,36,37,41,12,16,17,18,23,36,40,42,13,14,15,19,37,39,
43,13,14,15,20,21,38,43,44,13,14,15,20,21,37,39,43,44,45,12,16,17,22,36,40,
42,46,12,16,17,18,23,41,42,46,47],
[2.83226851852e6,1.63544753086e6,1.72436728395e6,-2.0e6,-2.08333333333e6,
1.00333333333e9,1.0e6,-2.77777777778e6,1.0675e9,2.08333333333e6,
5.55555555555e6,1.53533333333e9,-3333.33333333,-1.0e6,2.83226851852e6,
-6666.66666667,2.0e6,1.63544753086e6,-1.68e6,1.72436728395e6,-2.0e6,4.0e8,
2.0e6,-2.08333333333e6,1.00333333333e9,1.0e6,2.0e8,-1.0e6,-2.77777777778e6,
1.0675e9,-2.0e6,2.08333333333e6,5.55555555555e6,1.53533333333e9,-2.8e6,
2.8360994695e6,-30864.1975309,-5.55555555555e6,1.76741074446e6,
-15432.0987654,2.77777777778e6,517922.131816,3.89003806848e6,
-3.33333333333e6,4.29857058902e6,-2.6349902747e6,1.97572063531e9,
-2.77777777778e6,3.33333333333e8,-2.14928529451e6,2.77777777778e6,
1.52734651547e9,5.55555555555e6,6.66666666667e8,2.35916180402e6,
-5.55555555555e6,-1.09779731332e8,1.56411143711e9,-2.8e6,-3333.33333333,
1.0e6,2.83226851852e6,-30864.1975309,-5.55555555555e6,-6666.66666667,
-2.0e6,1.63544753086e6,-15432.0987654,2.77777777778e6,-1.68e6,
1.72436728395e6,-3.33333333333e6,2.0e6,4.0e8,-2.0e6,-2.08333333333e6,
1.00333333333e9,-2.77777777778e6,3.33333333333e8,-1.0e6,2.0e8,1.0e6,
2.77777777778e6,1.0675e9,5.55555555555e6,6.66666666667e8,-2.0e6,
2.08333333333e6,-5.55555555555e6,1.53533333333e9,-28935.1851852,
-2.08333333333e6,60879.6296296,-1.59791666667e6,3.37291666667e6,
-28935.1851852,2.08333333333e6,2.41171296296e6,-2.08333333333e6,
1.0e8,-2.5e6,-416666.666667,1.5e9,-833333.333333,1.25e6,5.01833333333e8,
2.08333333333e6,1.0e8,416666.666667,5.025e8,-28935.1851852,
-2.08333333333e6,-4166.66666667,-1.25e6,3.98587962963e6,-1.59791666667e6,
-8333.33333333,2.5e6,3.41149691358e6,-28935.1851852,2.08333333333e6,
-2.355e6,2.43100308642e6,-2.08333333333e6,1.0e8,-2.5e6,5.0e8,2.5e6,
-416666.666667,1.50416666667e9,-833333.333333,1.25e6,2.5e8,-1.25e6,
-3.47222222222e6,1.33516666667e9,2.08333333333e6,1.0e8,-2.5e6,
416666.666667,6.94444444444e6,2.16916666667e9,-28935.1851852,
-2.08333333333e6,-3.925e6,3.98587962963e6,-1.59791666667e6,
-38580.2469136,-6.94444444444e6,3.41149691358e6,-28935.1851852,
2.08333333333e6,-19290.1234568,3.47222222222e6,2.43100308642e6,
-2.08333333333e6,1.0e8,-4.16666666667e6,2.5e6,-416666.666667,
1.50416666667e9,-833333.333333,-3.47222222222e6,4.16666666667e8,
-1.25e6,3.47222222222e6,1.33516666667e9,2.08333333333e6,1.0e8,
6.94444444445e6,8.33333333333e8,416666.666667,-6.94444444445e6,
2.16916666667e9,-3830.95098171,1.14928529451e6,-275828.470683,
-28935.1851852,-2.08333333333e6,-4166.66666667,1.25e6,64710.5806113,
-131963.213599,-517922.131816,-2.29857058902e6,-1.59791666667e6,
-8333.33333333,-2.5e6,3.50487988027e6,-517922.131816,-2.16567078453e6,
551656.941366,-28935.1851852,2.08333333333e6,-2.355e6,517922.131816,
4.57738374749e6,2.29857058902e6,-551656.941367,4.8619365099e8,
-2.08333333333e6,1.0e8,2.5e6,5.0e8,-4.79857058902e6,134990.2747,
2.47238730198e9,-1.14928529451e6,2.29724661236e8,-5.57173510779e7,
-833333.333333,-1.25e6,2.5e8,2.39928529451e6,9.61679848804e8,275828.470683,
-5.57173510779e7,1.09411960038e7,2.08333333333e6,1.0e8,-2.5e6,
140838.195984,-1.09779731332e8,5.31278103775e8], 1)
@test CHOLMOD.norm_sparse(A, 0) ≈ 3.570948074697437e9
@test CHOLMOD.norm_sparse(A, 1) ≈ 3.570948074697437e9
@test_throws ArgumentError CHOLMOD.norm_sparse(A, 2)
@test CHOLMOD.isvalid(A)
x = fill(1., n)
b = A*x
chma = ldlt(A) # LDL' form
@test CHOLMOD.isvalid(chma)
@test unsafe_load(pointer(chma)).is_ll == 0 # check that it is in fact an LDLt
@test chma\b ≈ x
@test nnz(ldlt(A, perm=1:size(A,1))) > nnz(chma)
@test size(chma) == size(A)
chmal = CHOLMOD.FactorComponent(chma, :L)
@test size(chmal) == size(A)
@test size(chmal, 1) == size(A, 1)
chma = cholesky(A) # LL' form
@test CHOLMOD.isvalid(chma)
@test unsafe_load(pointer(chma)).is_ll == 1 # check that it is in fact an LLt
@test chma\b ≈ x
@test nnz(chma) == 489
@test nnz(cholesky(A, perm=1:size(A,1))) > nnz(chma)
@test size(chma) == size(A)
chmal = CHOLMOD.FactorComponent(chma, :L)
@test size(chmal) == size(A)
@test size(chmal, 1) == size(A, 1)
@testset "eltype" begin
@test eltype(Dense(fill(1., 3))) == Float64
@test eltype(A) == Float64
@test eltype(chma) == Float64
end
end
@testset "lp_afiro example" begin
afiro = CHOLMOD.Sparse(27, 51,
CHOLMOD.SuiteSparse_long[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
23,25,27,29,33,37,41,45,47,49,51,53,55,57,59,63,65,67,69,71,75,79,83,87,89,
91,93,95,97,99,101,102],
CHOLMOD.SuiteSparse_long[2,3,6,7,8,9,12,13,16,17,18,19,20,21,22,23,24,25,26,
0,1,2,23,0,3,0,21,1,25,4,5,6,24,4,5,7,24,4,5,8,24,4,5,9,24,6,20,7,20,8,20,9,
20,3,4,4,22,5,26,10,11,12,21,10,13,10,23,10,20,11,25,14,15,16,22,14,15,17,
22,14,15,18,22,14,15,19,22,16,20,17,20,18,20,19,20,13,15,15,24,14,26,15],
[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,
1.0,-1.0,-1.06,1.0,0.301,1.0,-1.0,1.0,-1.0,1.0,1.0,-1.0,-1.06,1.0,0.301,
-1.0,-1.06,1.0,0.313,-1.0,-0.96,1.0,0.313,-1.0,-0.86,1.0,0.326,-1.0,2.364,
-1.0,2.386,-1.0,2.408,-1.0,2.429,1.4,1.0,1.0,-1.0,1.0,1.0,-1.0,-0.43,1.0,
0.109,1.0,-1.0,1.0,-1.0,1.0,-1.0,1.0,1.0,-0.43,1.0,1.0,0.109,-0.43,1.0,1.0,
0.108,-0.39,1.0,1.0,0.108,-0.37,1.0,1.0,0.107,-1.0,2.191,-1.0,2.219,-1.0,
2.249,-1.0,2.279,1.4,-1.0,1.0,-1.0,1.0,1.0,1.0], 0)
afiro2 = CHOLMOD.aat(afiro, CHOLMOD.SuiteSparse_long[0:50;], CHOLMOD.SuiteSparse_long(1))
CHOLMOD.change_stype!(afiro2, -1)
chmaf = cholesky(afiro2)
y = afiro'*fill(1., size(afiro,1))
sol = chmaf\(afiro*y) # least squares solution
@test CHOLMOD.isvalid(sol)
pred = afiro'*sol
@test norm(afiro * (convert(Matrix, y) - convert(Matrix, pred))) < 1e-8
end
@testset "Issue 9160" begin
local A, B
A = sprand(10, 10, 0.1)
A = convert(SparseMatrixCSC{Float64,CHOLMOD.SuiteSparse_long}, A)
cmA = CHOLMOD.Sparse(A)
B = sprand(10, 10, 0.1)
B = convert(SparseMatrixCSC{Float64,CHOLMOD.SuiteSparse_long}, B)
cmB = CHOLMOD.Sparse(B)
# Ac_mul_B
@test sparse(cmA'*cmB) ≈ A'*B
# A_mul_Bc
@test sparse(cmA*cmB') ≈ A*B'
# A_mul_Ac
@test sparse(cmA*cmA') ≈ A*A'
# Ac_mul_A
@test sparse(cmA'*cmA) ≈ A'*A
# A_mul_Ac for symmetric A
A = 0.5*(A + copy(A'))
cmA = CHOLMOD.Sparse(A)
@test sparse(cmA*cmA') ≈ A*A'
end
@testset "Issue #9915" begin
sparseI = sparse(1.0I, 2, 2)
@test sparseI \ sparseI == sparseI
end
@testset "test Sparse constructor Symmetric and Hermitian input (and issymmetric and ishermitian)" begin
ACSC = sprandn(10, 10, 0.3) + I
@test issymmetric(Sparse(Symmetric(ACSC, :L)))
@test issymmetric(Sparse(Symmetric(ACSC, :U)))
@test ishermitian(Sparse(Hermitian(complex(ACSC), :L)))
@test ishermitian(Sparse(Hermitian(complex(ACSC), :U)))
end
@testset "test Sparse constructor for C_Sparse{Cvoid} (and read_sparse)" begin
mktempdir() do temp_dir
testfile = joinpath(temp_dir, "tmp.mtx")
writedlm(testfile, ["%%MatrixMarket matrix coordinate real symmetric","3 3 4","1 1 1","2 2 1","3 2 0.5","3 3 1"])
@test sparse(CHOLMOD.Sparse(testfile)) == [1 0 0;0 1 0.5;0 0.5 1]
rm(testfile)
writedlm(testfile, ["%%MatrixMarket matrix coordinate complex Hermitian",
"3 3 4","1 1 1.0 0.0","2 2 1.0 0.0","3 2 0.5 0.5","3 3 1.0 0.0"])
@test sparse(CHOLMOD.Sparse(testfile)) == [1 0 0;0 1 0.5-0.5im;0 0.5+0.5im 1]
rm(testfile)
writedlm(testfile, ["%%MatrixMarket matrix coordinate real symmetric","%3 3 4","1 1 1","2 2 1","3 2 0.5","3 3 1"])
@test_throws ArgumentError sparse(CHOLMOD.Sparse(testfile))
rm(testfile)
end
end
@testset "test that Sparse(Ptr) constructor throws the right places" begin
@test_throws ArgumentError CHOLMOD.Sparse(convert(Ptr{CHOLMOD.C_Sparse{Float64}}, C_NULL))
@test_throws ArgumentError CHOLMOD.Sparse(convert(Ptr{CHOLMOD.C_Sparse{Cvoid}}, C_NULL))
end
## The struct pointer must be constructed by the library constructor and then modified afterwards to checks that the method throws
@testset "illegal dtype (for now but should be supported at some point)" begin
p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_Sparse{Cvoid}},
(Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Cvoid}),
1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common_struct)
puint = convert(Ptr{UInt32}, p)
unsafe_store!(puint, CHOLMOD.SINGLE, 3*div(sizeof(Csize_t), 4) + 5*div(sizeof(Ptr{Cvoid}), 4) + 4)
@test_throws CHOLMOD.CHOLMODException CHOLMOD.Sparse(p)
end
@testset "illegal dtype" begin
p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_Sparse{Cvoid}},
(Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Cvoid}),
1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common_struct)
puint = convert(Ptr{UInt32}, p)
unsafe_store!(puint, 5, 3*div(sizeof(Csize_t), 4) + 5*div(sizeof(Ptr{Cvoid}), 4) + 4)
@test_throws CHOLMOD.CHOLMODException CHOLMOD.Sparse(p)
end
@testset "illegal xtype" begin
p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_Sparse{Cvoid}},
(Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Cvoid}),
1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common_struct)
puint = convert(Ptr{UInt32}, p)
unsafe_store!(puint, 3, 3*div(sizeof(Csize_t), 4) + 5*div(sizeof(Ptr{Cvoid}), 4) + 3)
@test_throws CHOLMOD.CHOLMODException CHOLMOD.Sparse(p)
end
@testset "illegal itype I" begin
p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_Sparse{Cvoid}},
(Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Cvoid}),
1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common_struct)
puint = convert(Ptr{UInt32}, p)
unsafe_store!(puint, CHOLMOD.INTLONG, 3*div(sizeof(Csize_t), 4) + 5*div(sizeof(Ptr{Cvoid}), 4) + 2)
@test_throws CHOLMOD.CHOLMODException CHOLMOD.Sparse(p)
end
@testset "illegal itype II" begin
p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_Sparse{Cvoid}},
(Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Cvoid}),
1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common_struct)
puint = convert(Ptr{UInt32}, p)
unsafe_store!(puint, 5, 3*div(sizeof(Csize_t), 4) + 5*div(sizeof(Ptr{Cvoid}), 4) + 2)
@test_throws CHOLMOD.CHOLMODException CHOLMOD.Sparse(p)
end
# Test Dense wrappers (only Float64 supported a present)
@testset "High level interface" for elty in (Float64, Complex{Float64})
local A, b
if elty == Float64
A = randn(5, 5)
b = randn(5)
else
A = complex.(randn(5, 5), randn(5, 5))
b = complex.(randn(5), randn(5))
end
ADense = CHOLMOD.Dense(A)
bDense = CHOLMOD.Dense(b)
@test_throws BoundsError ADense[6, 1]
@test_throws BoundsError ADense[1, 6]
@test copy(ADense) == ADense
@test CHOLMOD.norm_dense(ADense, 1) ≈ opnorm(A, 1)
@test CHOLMOD.norm_dense(ADense, 0) ≈ opnorm(A, Inf)
@test_throws ArgumentError CHOLMOD.norm_dense(ADense, 2)
@test_throws ArgumentError CHOLMOD.norm_dense(ADense, 3)
@test CHOLMOD.norm_dense(bDense, 2) ≈ norm(b)
@test CHOLMOD.check_dense(bDense)
AA = CHOLMOD.eye(3)
unsafe_store!(convert(Ptr{Csize_t}, pointer(AA)), 2, 1) # change size, but not stride, of Dense
@test convert(Matrix, AA) == Matrix(I, 2, 3)
end
@testset "Low level interface" begin
@test isa(CHOLMOD.zeros(3, 3, Float64), CHOLMOD.Dense{Float64})
@test isa(CHOLMOD.zeros(3, 3), CHOLMOD.Dense{Float64})
@test isa(CHOLMOD.zeros(3, 3, Float64), CHOLMOD.Dense{Float64})
@test isa(CHOLMOD.ones(3, 3), CHOLMOD.Dense{Float64})
@test isa(CHOLMOD.eye(3, 4, Float64), CHOLMOD.Dense{Float64})
@test isa(CHOLMOD.eye(3, 4), CHOLMOD.Dense{Float64})
@test isa(CHOLMOD.eye(3), CHOLMOD.Dense{Float64})
@test isa(copy(CHOLMOD.eye(3)), CHOLMOD.Dense{Float64})
end
# Test Sparse and Factor
@testset "test free!" begin
p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_Sparse{Float64}},
(Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Cvoid}),
1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common_struct)
@test CHOLMOD.free!(p)
end
@testset "Core functionality" for elty in (Float64, Complex{Float64})
A1 = sparse([1:5; 1], [1:5; 2], elty == Float64 ? randn(6) : complex.(randn(6), randn(6)))
A2 = sparse([1:5; 1], [1:5; 2], elty == Float64 ? randn(6) : complex.(randn(6), randn(6)))
A1pd = A1'A1
A1Sparse = CHOLMOD.Sparse(A1)
A2Sparse = CHOLMOD.Sparse(A2)
A1pdSparse = CHOLMOD.Sparse(
A1pd.m,
A1pd.n,
SuiteSparse.decrement(A1pd.colptr),
SuiteSparse.decrement(A1pd.rowval),
A1pd.nzval)
## High level interface
@test isa(CHOLMOD.Sparse(3, 3, [0,1,3,4], [0,2,1,2], fill(1., 4)), CHOLMOD.Sparse) # Sparse doesn't require columns to be sorted
@test_throws BoundsError A1Sparse[6, 1]
@test_throws BoundsError A1Sparse[1, 6]
@test sparse(A1Sparse) == A1
for i = 1:size(A1, 1)
A1[i, i] = real(A1[i, i])
end #Construct Hermitian matrix properly
@test CHOLMOD.sparse(CHOLMOD.Sparse(Hermitian(A1, :L))) == Hermitian(A1, :L)
@test CHOLMOD.sparse(CHOLMOD.Sparse(Hermitian(A1, :U))) == Hermitian(A1, :U)
@test_throws ArgumentError convert(SparseMatrixCSC{elty,Int}, A1pdSparse)
if elty <: Real
@test_throws ArgumentError convert(Symmetric{Float64,SparseMatrixCSC{Float64,Int}}, A1Sparse)
else
@test_throws ArgumentError convert(Hermitian{Complex{Float64},SparseMatrixCSC{Complex{Float64},Int}}, A1Sparse)
end
@test copy(A1Sparse) == A1Sparse
@test size(A1Sparse, 3) == 1
if elty <: Real # multiplication only defined for real matrices in CHOLMOD
@test A1Sparse*A2Sparse ≈ A1*A2
@test_throws DimensionMismatch CHOLMOD.Sparse(A1[:,1:4])*A2Sparse
@test A1Sparse'A2Sparse ≈ A1'A2
@test A1Sparse*A2Sparse' ≈ A1*A2'
@test A1Sparse*A1Sparse ≈ A1*A1
@test A1Sparse'A1Sparse ≈ A1'A1
@test A1Sparse*A1Sparse' ≈ A1*A1'
@test A1pdSparse*A1pdSparse ≈ A1pd*A1pd
@test A1pdSparse'A1pdSparse ≈ A1pd'A1pd
@test A1pdSparse*A1pdSparse' ≈ A1pd*A1pd'
@test_throws DimensionMismatch A1Sparse*CHOLMOD.eye(4, 5, elty)
end
# Factor
@test_throws ArgumentError cholesky(A1)
@test_throws ArgumentError cholesky(A1)
@test_throws ArgumentError cholesky(A1, shift=1.0)
@test_throws ArgumentError ldlt(A1)
@test_throws ArgumentError ldlt(A1, shift=1.0)
C = A1 + copy(adjoint(A1))
λmaxC = eigmax(Array(C))
b = fill(1., size(A1, 1))
@test_throws PosDefException cholesky(C - 2λmaxC*I)
@test_throws PosDefException cholesky(C, shift=-2λmaxC)
@test_throws PosDefException ldlt(C - C[1,1]*I)
@test_throws PosDefException ldlt(C, shift=-real(C[1,1]))
@test !isposdef(cholesky(C - 2λmaxC*I; check = false))
@test !isposdef(cholesky(C, shift=-2λmaxC; check = false))
@test !issuccess(ldlt(C - C[1,1]*I; check = false))
@test !issuccess(ldlt(C, shift=-real(C[1,1]); check = false))
F = cholesky(A1pd)
tmp = IOBuffer()
show(tmp, F)
@test tmp.size > 0
@test isa(CHOLMOD.Sparse(F), CHOLMOD.Sparse{elty})
@test_throws DimensionMismatch F\CHOLMOD.Dense(fill(elty(1), 4))
@test_throws DimensionMismatch F\CHOLMOD.Sparse(sparse(fill(elty(1), 4)))
b = fill(1., 5)
bT = fill(elty(1), 5)
@test F'\bT ≈ Array(A1pd)'\b
@test F'\sparse(bT) ≈ Array(A1pd)'\b
@test transpose(F)\bT ≈ conj(A1pd)'\bT
@test F\CHOLMOD.Sparse(sparse(bT)) ≈ A1pd\b
@test logdet(F) ≈ logdet(Array(A1pd))
@test det(F) == exp(logdet(F))
let # to test supernodal, we must use a larger matrix
Ftmp = sprandn(100, 100, 0.1)
Ftmp = Ftmp'Ftmp + I
@test logdet(cholesky(Ftmp)) ≈ logdet(Array(Ftmp))
end
@test logdet(ldlt(A1pd)) ≈ logdet(Array(A1pd))
@test isposdef(A1pd)
@test !isposdef(A1)
@test !isposdef(A1 + copy(A1') |> t -> t - 2eigmax(Array(t))*I)
if elty <: Real
@test CHOLMOD.issymmetric(Sparse(A1pd, 0))
@test CHOLMOD.Sparse(cholesky(Symmetric(A1pd, :L))) == CHOLMOD.Sparse(cholesky(A1pd))
F1 = CHOLMOD.Sparse(cholesky(Symmetric(A1pd, :L), shift=2))
F2 = CHOLMOD.Sparse(cholesky(A1pd, shift=2))
@test F1 == F2
@test CHOLMOD.Sparse(ldlt(Symmetric(A1pd, :L))) == CHOLMOD.Sparse(ldlt(A1pd))
F1 = CHOLMOD.Sparse(ldlt(Symmetric(A1pd, :L), shift=2))
F2 = CHOLMOD.Sparse(ldlt(A1pd, shift=2))
@test F1 == F2
else
@test !CHOLMOD.issymmetric(Sparse(A1pd, 0))
@test CHOLMOD.ishermitian(Sparse(A1pd, 0))
@test CHOLMOD.Sparse(cholesky(Hermitian(A1pd, :L))) == CHOLMOD.Sparse(cholesky(A1pd))
F1 = CHOLMOD.Sparse(cholesky(Hermitian(A1pd, :L), shift=2))
F2 = CHOLMOD.Sparse(cholesky(A1pd, shift=2))
@test F1 == F2
@test CHOLMOD.Sparse(ldlt(Hermitian(A1pd, :L))) == CHOLMOD.Sparse(ldlt(A1pd))
F1 = CHOLMOD.Sparse(ldlt(Hermitian(A1pd, :L), shift=2))
F2 = CHOLMOD.Sparse(ldlt(A1pd, shift=2))
@test F1 == F2
end
### cholesky!/ldlt!
F = cholesky(A1pd)
CHOLMOD.change_factor!(F, false, false, true, true)
@test unsafe_load(pointer(F)).is_ll == 0
CHOLMOD.change_factor!(F, true, false, true, true)
@test CHOLMOD.Sparse(cholesky!(copy(F), A1pd)) ≈ CHOLMOD.Sparse(F) # surprisingly, this can cause small ulp size changes so we cannot test exact equality
@test size(F, 2) == 5
@test size(F, 3) == 1
@test_throws ArgumentError size(F, 0)
F = cholesky(A1pdSparse, shift=2)
@test isa(CHOLMOD.Sparse(F), CHOLMOD.Sparse{elty})
@test CHOLMOD.Sparse(cholesky!(copy(F), A1pd, shift=2.0)) ≈ CHOLMOD.Sparse(F) # surprisingly, this can cause small ulp size changes so we cannot test exact equality
F = ldlt(A1pd)
@test isa(CHOLMOD.Sparse(F), CHOLMOD.Sparse{elty})
@test CHOLMOD.Sparse(ldlt!(copy(F), A1pd)) ≈ CHOLMOD.Sparse(F) # surprisingly, this can cause small ulp size changes so we cannot test exact equality
F = ldlt(A1pdSparse, shift=2)
@test isa(CHOLMOD.Sparse(F), CHOLMOD.Sparse{elty})
@test CHOLMOD.Sparse(ldlt!(copy(F), A1pd, shift=2.0)) ≈ CHOLMOD.Sparse(F) # surprisingly, this can cause small ulp size changes so we cannot test exact equality
@test isa(CHOLMOD.factor_to_sparse!(F), CHOLMOD.Sparse)
@test_throws CHOLMOD.CHOLMODException CHOLMOD.factor_to_sparse!(F)
## Low level interface
@test CHOLMOD.nnz(A1Sparse) == nnz(A1)
@test CHOLMOD.speye(5, 5, elty) == Matrix(I, 5, 5)
@test CHOLMOD.spzeros(5, 5, 5, elty) == zeros(elty, 5, 5)
if elty <: Real
@test CHOLMOD.copy(A1Sparse, 0, 1) == A1Sparse
@test CHOLMOD.horzcat(A1Sparse, A2Sparse, true) == [A1 A2]
@test CHOLMOD.vertcat(A1Sparse, A2Sparse, true) == [A1; A2]
svec = fill(elty(1), 1)
@test CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.SCALAR, A1Sparse) == A1Sparse
svec = fill(elty(1), 5)
@test_throws DimensionMismatch CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.SCALAR, A1Sparse)
@test CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.ROW, A1Sparse) == A1Sparse
@test_throws DimensionMismatch CHOLMOD.scale!(CHOLMOD.Dense([svec; 1]), CHOLMOD.ROW, A1Sparse)
@test CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.COL, A1Sparse) == A1Sparse
@test_throws DimensionMismatch CHOLMOD.scale!(CHOLMOD.Dense([svec; 1]), CHOLMOD.COL, A1Sparse)
@test CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.SYM, A1Sparse) == A1Sparse
@test_throws DimensionMismatch CHOLMOD.scale!(CHOLMOD.Dense([svec; 1]), CHOLMOD.SYM, A1Sparse)
@test_throws DimensionMismatch CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.SYM, CHOLMOD.Sparse(A1[:,1:4]))
else
@test_throws MethodError CHOLMOD.copy(A1Sparse, 0, 1) == A1Sparse
@test_throws MethodError CHOLMOD.horzcat(A1Sparse, A2Sparse, true) == [A1 A2]
@test_throws MethodError CHOLMOD.vertcat(A1Sparse, A2Sparse, true) == [A1; A2]
end
if elty <: Real
@test CHOLMOD.ssmult(A1Sparse, A2Sparse, 0, true, true) ≈ A1*A2
@test CHOLMOD.aat(A1Sparse, [0:size(A1,2)-1;], 1) ≈ A1*A1'
@test CHOLMOD.aat(A1Sparse, [0:1;], 1) ≈ A1[:,1:2]*A1[:,1:2]'
@test CHOLMOD.copy(A1Sparse, 0, 1) == A1Sparse
end
@test CHOLMOD.Sparse(CHOLMOD.Dense(A1Sparse)) == A1Sparse
end
@testset "extract factors" begin
Af = float([4 12 -16; 12 37 -43; -16 -43 98])
As = sparse(Af)
Lf = float([2 0 0; 6 1 0; -8 5 3])
LDf = float([4 0 0; 3 1 0; -4 5 9]) # D is stored along the diagonal
L_f = float([1 0 0; 3 1 0; -4 5 1]) # L by itself in LDLt of Af
D_f = float([4 0 0; 0 1 0; 0 0 9])
p = [2,3,1]
p_inv = [3,1,2]
@testset "cholesky, no permutation" begin
Fs = cholesky(As, perm=[1:3;])
@test Fs.p == [1:3;]
@test sparse(Fs.L) ≈ Lf
@test sparse(Fs) ≈ As
b = rand(3)
@test Fs\b ≈ Af\b
@test Fs.UP\(Fs.PtL\b) ≈ Af\b
@test Fs.L\b ≈ Lf\b
@test Fs.U\b ≈ Lf'\b
@test Fs.L'\b ≈ Lf'\b
@test Fs.U'\b ≈ Lf\b
@test Fs.PtL\b ≈ Lf\b
@test Fs.UP\b ≈ Lf'\b
@test Fs.PtL'\b ≈ Lf'\b
@test Fs.UP'\b ≈ Lf\b
@test_throws CHOLMOD.CHOLMODException Fs.D
@test_throws CHOLMOD.CHOLMODException Fs.LD
@test_throws CHOLMOD.CHOLMODException Fs.DU
@test_throws CHOLMOD.CHOLMODException Fs.PLD
@test_throws CHOLMOD.CHOLMODException Fs.DUPt
end
@testset "cholesky, with permutation" begin
Fs = cholesky(As, perm=p)
@test Fs.p == p
Afp = Af[p,p]
Lfp = cholesky(Afp).L
Ls = sparse(Fs.L)
@test Ls ≈ Lfp
@test Ls * Ls' ≈ Afp
P = sparse(1:3, Fs.p, ones(3))
@test P' * Ls * Ls' * P ≈ As
@test sparse(Fs) ≈ As
b = rand(3)
@test Fs\b ≈ Af\b
@test Fs.UP\(Fs.PtL\b) ≈ Af\b
@test Fs.L\b ≈ Lfp\b
@test Fs.U'\b ≈ Lfp\b
@test Fs.U\b ≈ Lfp'\b
@test Fs.L'\b ≈ Lfp'\b
@test Fs.PtL\b ≈ Lfp\b[p]
@test Fs.UP\b ≈ (Lfp'\b)[p_inv]
@test Fs.PtL'\b ≈ (Lfp'\b)[p_inv]
@test Fs.UP'\b ≈ Lfp\b[p]
@test_throws CHOLMOD.CHOLMODException Fs.PL
@test_throws CHOLMOD.CHOLMODException Fs.UPt
@test_throws CHOLMOD.CHOLMODException Fs.D
@test_throws CHOLMOD.CHOLMODException Fs.LD
@test_throws CHOLMOD.CHOLMODException Fs.DU
@test_throws CHOLMOD.CHOLMODException Fs.PLD
@test_throws CHOLMOD.CHOLMODException Fs.DUPt
end
@testset "ldlt, no permutation" begin
Fs = ldlt(As, perm=[1:3;])
@test Fs.p == [1:3;]
@test sparse(Fs.LD) ≈ LDf
@test sparse(Fs) ≈ As
b = rand(3)
@test Fs\b ≈ Af\b
@test Fs.UP\(Fs.PtLD\b) ≈ Af\b
@test Fs.DUP\(Fs.PtL\b) ≈ Af\b
@test Fs.L\b ≈ L_f\b
@test Fs.U\b ≈ L_f'\b
@test Fs.L'\b ≈ L_f'\b
@test Fs.U'\b ≈ L_f\b
@test Fs.PtL\b ≈ L_f\b
@test Fs.UP\b ≈ L_f'\b
@test Fs.PtL'\b ≈ L_f'\b
@test Fs.UP'\b ≈ L_f\b
@test Fs.D\b ≈ D_f\b
@test Fs.D'\b ≈ D_f\b
@test Fs.LD\b ≈ D_f\(L_f\b)
@test Fs.DU'\b ≈ D_f\(L_f\b)
@test Fs.LD'\b ≈ L_f'\(D_f\b)
@test Fs.DU\b ≈ L_f'\(D_f\b)
@test Fs.PtLD\b ≈ D_f\(L_f\b)
@test Fs.DUP'\b ≈ D_f\(L_f\b)
@test Fs.PtLD'\b ≈ L_f'\(D_f\b)
@test Fs.DUP\b ≈ L_f'\(D_f\b)
end
@testset "ldlt, with permutation" begin
Fs = ldlt(As, perm=p)
@test Fs.p == p
@test sparse(Fs) ≈ As
b = rand(3)
Asp = As[p,p]
LDp = sparse(ldlt(Asp, perm=[1,2,3]).LD)
# LDp = sparse(Fs.LD)
Lp, dp = SuiteSparse.CHOLMOD.getLd!(copy(LDp))
Dp = sparse(Diagonal(dp))
@test Fs\b ≈ Af\b
@test Fs.UP\(Fs.PtLD\b) ≈ Af\b
@test Fs.DUP\(Fs.PtL\b) ≈ Af\b
@test Fs.L\b ≈ Lp\b
@test Fs.U\b ≈ Lp'\b
@test Fs.L'\b ≈ Lp'\b
@test Fs.U'\b ≈ Lp\b
@test Fs.PtL\b ≈ Lp\b[p]
@test Fs.UP\b ≈ (Lp'\b)[p_inv]
@test Fs.PtL'\b ≈ (Lp'\b)[p_inv]
@test Fs.UP'\b ≈ Lp\b[p]
@test Fs.LD\b ≈ Dp\(Lp\b)
@test Fs.DU'\b ≈ Dp\(Lp\b)
@test Fs.LD'\b ≈ Lp'\(Dp\b)
@test Fs.DU\b ≈ Lp'\(Dp\b)
@test Fs.PtLD\b ≈ Dp\(Lp\b[p])
@test Fs.DUP'\b ≈ Dp\(Lp\b[p])
@test Fs.PtLD'\b ≈ (Lp'\(Dp\b))[p_inv]
@test Fs.DUP\b ≈ (Lp'\(Dp\b))[p_inv]
@test_throws CHOLMOD.CHOLMODException Fs.DUPt
@test_throws CHOLMOD.CHOLMODException Fs.PLD
end
@testset "Element promotion and type inference" begin
@inferred cholesky(As)\fill(1, size(As, 1))
@inferred ldlt(As)\fill(1, size(As, 1))
end
end
@testset "Issue 11745 - row and column pointers were not sorted in sparse(Factor)" begin
A = Float64[10 1 1 1; 1 10 0 0; 1 0 10 0; 1 0 0 10]
@test sparse(cholesky(sparse(A))) ≈ A
end
GC.gc()
@testset "Issue 11747 - Wrong show method defined for FactorComponent" begin
v = cholesky(sparse(Float64[ 10 1 1 1; 1 10 0 0; 1 0 10 0; 1 0 0 10])).L
for s in (sprint(show, MIME("text/plain"), v), sprint(show, v))
@test occursin("method: simplicial", s)
@test !occursin("#undef", s)
end
end
@testset "Issue 14076" begin
@test cholesky(sparse([1,2,3,4], [1,2,3,4], Float32[1,4,16,64]))\[1,4,16,64] == fill(1, 4)
end
@testset "Issue 29367" begin
if Int != Int32
@test_throws MethodError cholesky(sparse(Int32[1,2,3,4], Int32[1,2,3,4], Float64[1,4,16,64]))
@test_throws MethodError cholesky(sparse(Int32[1,2,3,4], Int32[1,2,3,4], Float32[1,4,16,64]))
@test_throws MethodError ldlt(sparse(Int32[1,2,3,4], Int32[1,2,3,4], Float64[1,4,16,64]))
@test_throws MethodError ldlt(sparse(Int32[1,2,3,4], Int32[1,2,3,4], Float32[1,4,16,64]))
end
end
@testset "Issue 14134" begin
A = CHOLMOD.Sparse(sprandn(10,5,0.1) + I |> t -> t't)
b = IOBuffer()
serialize(b, A)
seekstart(b)
Anew = deserialize(b)
@test_throws ArgumentError show(Anew)
@test_throws ArgumentError size(Anew)
@test_throws ArgumentError Anew[1]
@test_throws ArgumentError Anew[2,1]
F = cholesky(A)
serialize(b, F)
seekstart(b)
Fnew = deserialize(b)
@test_throws ArgumentError Fnew\fill(1., 5)
@test_throws ArgumentError show(Fnew)
@test_throws ArgumentError size(Fnew)
@test_throws ArgumentError diag(Fnew)
@test_throws ArgumentError logdet(Fnew)
end
@testset "Issue with promotion during conversion to CHOLMOD.Dense" begin
@test CHOLMOD.Dense(fill(1, 5)) == fill(1, 5, 1)
@test CHOLMOD.Dense(fill(1f0, 5)) == fill(1, 5, 1)
@test CHOLMOD.Dense(fill(1f0 + 0im, 5, 2)) == fill(1, 5, 2)
end
@testset "Further issue with promotion #14894" begin
x = fill(1., 5)
@test cholesky(sparse(Float16(1)I, 5, 5))\x == x
@test cholesky(Symmetric(sparse(Float16(1)I, 5, 5)))\x == x
@test cholesky(Hermitian(sparse(Complex{Float16}(1)I, 5, 5)))\x == x
@test_throws TypeError cholesky(sparse(BigFloat(1)I, 5, 5))
@test_throws TypeError cholesky(Symmetric(sparse(BigFloat(1)I, 5, 5)))
@test_throws TypeError cholesky(Hermitian(sparse(Complex{BigFloat}(1)I, 5, 5)))
end
@testset "test \\ for Factor and StridedVecOrMat" begin
x = rand(5)
A = cholesky(sparse(Diagonal(x.\1)))
@test A\view(fill(1.,10),1:2:10) ≈ x
@test A\view(Matrix(1.0I, 5, 5), :, :) ≈ Matrix(Diagonal(x))
end
@testset "Real factorization and complex rhs" begin
A = sprandn(5, 5, 0.4) |> t -> t't + I
B = complex.(randn(5, 2), randn(5, 2))
@test cholesky(A)\B ≈ A\B
end
@testset "Make sure that ldlt performs an LDLt (Issue #19032)" begin
m, n = 400, 500
A = sprandn(m, n, .2)
M = [I copy(A'); A -I]
b = M * fill(1., m+n)
F = ldlt(M)
s = unsafe_load(pointer(F))
@test s.is_super == 0
@test F\b ≈ fill(1., m+n)
F2 = cholesky(M; check = false)
@test !issuccess(F2)
ldlt!(F2, M)
@test issuccess(F2)
@test F2\b ≈ fill(1., m+n)
end
@testset "Test that imaginary parts in Hermitian{T,SparseMatrixCSC{T}} are ignored" begin
A = sparse([1,2,3,4,1], [1,2,3,4,2], [complex(2.0,1),2,2,2,1])
Fs = cholesky(Hermitian(A))
Fd = cholesky(Hermitian(Array(A)))
@test sparse(Fs) ≈ Hermitian(A)
@test Fs\fill(1., 4) ≈ Fd\fill(1., 4)
end
@testset "\\ '\\ and transpose(...)\\" begin
# Test that \ and '\ and transpose(...)\ work for Symmetric and Hermitian. This is just
# a dispatch exercise so it doesn't matter that the complex matrix has
# zero imaginary parts
Apre = sprandn(10, 10, 0.2) - I
for A in (Symmetric(Apre), Hermitian(Apre),
Symmetric(Apre + 10I), Hermitian(Apre + 10I),
Hermitian(complex(Apre)), Hermitian(complex(Apre) + 10I))
local A, x, b
x = fill(1., 10)
b = A*x
@test x ≈ A\b
@test transpose(A)\b ≈ A'\b
end
end
@testset "Check that Symmetric{SparseMatrixCSC} can be constructed from CHOLMOD.Sparse" begin
Int === Int32 && Random.seed!(124)
A = sprandn(10, 10, 0.1)
B = CHOLMOD.Sparse(A)
C = B'B
# Change internal representation to symmetric (upper/lower)
o = fieldoffset(CHOLMOD.C_Sparse{eltype(C)}, findall(fieldnames(CHOLMOD.C_Sparse{eltype(C)}) .== :stype)[1])
for uplo in (1, -1)
unsafe_store!(Ptr{Int8}(pointer(C)), uplo, Int(o) + 1)
@test convert(Symmetric{Float64,SparseMatrixCSC{Float64,Int}}, C) ≈ Symmetric(A'A)
end
end
@testset "Check inputs to Sparse. Related to #20024" for A_ in (
SparseMatrixCSC(2, 2, [1, 2], CHOLMOD.SuiteSparse_long[], Float64[]),
SparseMatrixCSC(2, 2, [1, 2, 3], CHOLMOD.SuiteSparse_long[1], Float64[]),
SparseMatrixCSC(2, 2, [1, 2, 3], CHOLMOD.SuiteSparse_long[], Float64[1.0]),
SparseMatrixCSC(2, 2, [1, 2, 3], CHOLMOD.SuiteSparse_long[1], Float64[1.0]))
@test_throws ArgumentError CHOLMOD.Sparse(size(A_)..., A_.colptr .- 1, A_.rowval .- 1, A_.nzval)
@test_throws ArgumentError CHOLMOD.Sparse(A_)
end
@testset "sparse right multiplication of Symmetric and Hermitian matrices #21431" begin
S = sparse(1.0I, 2, 2)
@test issparse(S*S*S)
for T in (Symmetric, Hermitian)
@test issparse(S*T(S)*S)
@test issparse(S*(T(S)*S))
@test issparse((S*T(S))*S)
end
end
@testset "Test sparse low rank update for cholesky decomposion" begin
A = SparseMatrixCSC{Float64,CHOLMOD.SuiteSparse_long}(10, 5, [1,3,6,8,10,13], [6,7,1,2,9,3,5,1,7,6,7,9],
[-0.138843, 2.99571, -0.556814, 0.669704, -1.39252, 1.33814,
1.02371, -0.502384, 1.10686, 0.262229, -1.6935, 0.525239])
AtA = A'*A
C0 = [1., 2., 0, 0, 0]
# Test both cholesky and LDLt with and without automatic permutations
for F in (cholesky(AtA), cholesky(AtA, perm=1:5), ldlt(AtA), ldlt(AtA, perm=1:5))
local F
x0 = F\(b = fill(1., 5))
#Test both sparse/dense and vectors/matrices
for Ctest in (C0, sparse(C0), [C0 2*C0], sparse([C0 2*C0]))
local x, C, F1
C = copy(Ctest)
F1 = copy(F)
x = (AtA+C*C')\b
#Test update
F11 = CHOLMOD.lowrankupdate(F1, C)
@test Array(sparse(F11)) ≈ AtA+C*C'
@test F11\b ≈ x
#Make sure we get back the same factor again
F10 = CHOLMOD.lowrankdowndate(F11, C)
@test Array(sparse(F10)) ≈ AtA
@test F10\b ≈ x0
#Test in-place update
CHOLMOD.lowrankupdate!(F1, C)
@test Array(sparse(F1)) ≈ AtA+C*C'
@test F1\b ≈ x
#Test in-place downdate
CHOLMOD.lowrankdowndate!(F1, C)
@test Array(sparse(F1)) ≈ AtA
@test F1\b ≈ x0
@test C == Ctest #Make sure C didn't change
end
end
end
@testset "Issue #22335" begin
local A, F
A = sparse(1.0I, 3, 3)
@test issuccess(cholesky(A))
A[3, 3] = -1
F = cholesky(A; check = false)
@test !issuccess(F)
@test issuccess(ldlt!(F, A))
A[3, 3] = 1
@test A[:, 3:-1:1]\fill(1., 3) == [1, 1, 1]
end
@testset "Non-positive definite matrices" begin
A = sparse(Float64[1 2; 2 1])
B = sparse(ComplexF64[1 2; 2 1])
for M in (A, B, Symmetric(A), Hermitian(B))
F = cholesky(M; check = false)
@test_throws PosDefException cholesky(M)
@test_throws PosDefException cholesky!(F, M)
@test !issuccess(cholesky(M; check = false))
@test !issuccess(cholesky!(F, M; check = false))
end
A = sparse(Float64[0 0; 0 0])
B = sparse(ComplexF64[0 0; 0 0])
for M in (A, B, Symmetric(A), Hermitian(B))
F = ldlt(M; check = false)
@test_throws PosDefException ldlt(M)
@test_throws PosDefException ldlt!(F, M)
@test !issuccess(ldlt(M; check = false))
@test !issuccess(ldlt!(F, M; check = false))
end
end
| 42.361502
| 168
| 0.620442
|
[
"@testset \"based on deps/SuiteSparse-4.0.2/CHOLMOD/Demo/\" begin\n\n# chm_rdsp(joinpath(Sys.BINDIR, \"../../deps/SuiteSparse-4.0.2/CHOLMOD/Demo/Matrix/bcsstk01.tri\"))\n# because the file may not exist in binary distributions and when a system suitesparse library\n# is used\n\n## Result from C program\n## ---------------------------------- cholmod_demo:\n## norm (A,inf) = 3.57095e+09\n## norm (A,1) = 3.57095e+09\n## CHOLMOD sparse: A: 48-by-48, nz 224, upper. OK\n## CHOLMOD dense: B: 48-by-1, OK\n## bnorm 1.97917\n## Analyze: flop 6009 lnz 489\n## Factorizing A\n## CHOLMOD factor: L: 48-by-48 simplicial, LDL'. nzmax 489. nz 489 OK\n## Ordering: AMD fl/lnz 12.3 lnz/anz 2.2\n## ints in L: 782, doubles in L: 489\n## factor flops 6009 nnz(L) 489 (w/no amalgamation)\n## nnz(A*A'): 224\n## flops / nnz(L): 12.3\n## nnz(L) / nnz(A): 2.2\n## analyze cputime: 0.0000\n## factor cputime: 0.0000 mflop: 0.0\n## solve cputime: 0.0000 mflop: 0.0\n## overall cputime: 0.0000 mflop: 0.0\n## peak memory usage: 0 (MB)\n## residual 2.5e-19 (|Ax-b|/(|A||x|+|b|))\n## residual 1.3e-19 (|Ax-b|/(|A||x|+|b|)) after iterative refinement\n## rcond 9.5e-06\n\n n = 48\n A = CHOLMOD.Sparse(n, n,\n CHOLMOD.SuiteSparse_long[0,1,2,3,6,9,12,15,18,20,25,30,34,36,39,43,47,52,58,\n 62,67,71,77,84,90,93,95,98,103,106,110,115,119,123,130,136,142,146,150,155,\n 161,167,174,182,189,197,207,215,224], # zero-based column pointers\n CHOLMOD.SuiteSparse_long[0,1,2,1,2,3,0,2,4,0,1,5,0,4,6,1,3,7,2,8,1,3,7,8,9,\n 0,4,6,8,10,5,6,7,11,6,12,7,11,13,8,10,13,14,9,13,14,15,8,10,12,14,16,7,11,\n 12,13,16,17,0,12,16,18,1,5,13,15,19,2,4,14,20,3,13,15,19,20,21,2,4,12,16,18,\n 20,22,1,5,17,18,19,23,0,5,24,1,25,2,3,26,2,3,25,26,27,4,24,28,0,5,24,29,6,\n 11,24,28,30,7,25,27,31,8,9,26,32,8,9,25,27,31,32,33,10,24,28,30,32,34,6,11,\n 29,30,31,35,12,17,30,36,13,31,35,37,14,15,32,34,38,14,15,33,37,38,39,16,32,\n 34,36,38,40,12,17,31,35,36,37,41,12,16,17,18,23,36,40,42,13,14,15,19,37,39,\n 43,13,14,15,20,21,38,43,44,13,14,15,20,21,37,39,43,44,45,12,16,17,22,36,40,\n 42,46,12,16,17,18,23,41,42,46,47],\n [2.83226851852e6,1.63544753086e6,1.72436728395e6,-2.0e6,-2.08333333333e6,\n 1.00333333333e9,1.0e6,-2.77777777778e6,1.0675e9,2.08333333333e6,\n 5.55555555555e6,1.53533333333e9,-3333.33333333,-1.0e6,2.83226851852e6,\n -6666.66666667,2.0e6,1.63544753086e6,-1.68e6,1.72436728395e6,-2.0e6,4.0e8,\n 2.0e6,-2.08333333333e6,1.00333333333e9,1.0e6,2.0e8,-1.0e6,-2.77777777778e6,\n 1.0675e9,-2.0e6,2.08333333333e6,5.55555555555e6,1.53533333333e9,-2.8e6,\n 2.8360994695e6,-30864.1975309,-5.55555555555e6,1.76741074446e6,\n -15432.0987654,2.77777777778e6,517922.131816,3.89003806848e6,\n -3.33333333333e6,4.29857058902e6,-2.6349902747e6,1.97572063531e9,\n -2.77777777778e6,3.33333333333e8,-2.14928529451e6,2.77777777778e6,\n 1.52734651547e9,5.55555555555e6,6.66666666667e8,2.35916180402e6,\n -5.55555555555e6,-1.09779731332e8,1.56411143711e9,-2.8e6,-3333.33333333,\n 1.0e6,2.83226851852e6,-30864.1975309,-5.55555555555e6,-6666.66666667,\n -2.0e6,1.63544753086e6,-15432.0987654,2.77777777778e6,-1.68e6,\n 1.72436728395e6,-3.33333333333e6,2.0e6,4.0e8,-2.0e6,-2.08333333333e6,\n 1.00333333333e9,-2.77777777778e6,3.33333333333e8,-1.0e6,2.0e8,1.0e6,\n 2.77777777778e6,1.0675e9,5.55555555555e6,6.66666666667e8,-2.0e6,\n 2.08333333333e6,-5.55555555555e6,1.53533333333e9,-28935.1851852,\n -2.08333333333e6,60879.6296296,-1.59791666667e6,3.37291666667e6,\n -28935.1851852,2.08333333333e6,2.41171296296e6,-2.08333333333e6,\n 1.0e8,-2.5e6,-416666.666667,1.5e9,-833333.333333,1.25e6,5.01833333333e8,\n 2.08333333333e6,1.0e8,416666.666667,5.025e8,-28935.1851852,\n -2.08333333333e6,-4166.66666667,-1.25e6,3.98587962963e6,-1.59791666667e6,\n -8333.33333333,2.5e6,3.41149691358e6,-28935.1851852,2.08333333333e6,\n -2.355e6,2.43100308642e6,-2.08333333333e6,1.0e8,-2.5e6,5.0e8,2.5e6,\n -416666.666667,1.50416666667e9,-833333.333333,1.25e6,2.5e8,-1.25e6,\n -3.47222222222e6,1.33516666667e9,2.08333333333e6,1.0e8,-2.5e6,\n 416666.666667,6.94444444444e6,2.16916666667e9,-28935.1851852,\n -2.08333333333e6,-3.925e6,3.98587962963e6,-1.59791666667e6,\n -38580.2469136,-6.94444444444e6,3.41149691358e6,-28935.1851852,\n 2.08333333333e6,-19290.1234568,3.47222222222e6,2.43100308642e6,\n -2.08333333333e6,1.0e8,-4.16666666667e6,2.5e6,-416666.666667,\n 1.50416666667e9,-833333.333333,-3.47222222222e6,4.16666666667e8,\n -1.25e6,3.47222222222e6,1.33516666667e9,2.08333333333e6,1.0e8,\n 6.94444444445e6,8.33333333333e8,416666.666667,-6.94444444445e6,\n 2.16916666667e9,-3830.95098171,1.14928529451e6,-275828.470683,\n -28935.1851852,-2.08333333333e6,-4166.66666667,1.25e6,64710.5806113,\n -131963.213599,-517922.131816,-2.29857058902e6,-1.59791666667e6,\n -8333.33333333,-2.5e6,3.50487988027e6,-517922.131816,-2.16567078453e6,\n 551656.941366,-28935.1851852,2.08333333333e6,-2.355e6,517922.131816,\n 4.57738374749e6,2.29857058902e6,-551656.941367,4.8619365099e8,\n -2.08333333333e6,1.0e8,2.5e6,5.0e8,-4.79857058902e6,134990.2747,\n 2.47238730198e9,-1.14928529451e6,2.29724661236e8,-5.57173510779e7,\n -833333.333333,-1.25e6,2.5e8,2.39928529451e6,9.61679848804e8,275828.470683,\n -5.57173510779e7,1.09411960038e7,2.08333333333e6,1.0e8,-2.5e6,\n 140838.195984,-1.09779731332e8,5.31278103775e8], 1)\n @test CHOLMOD.norm_sparse(A, 0) ≈ 3.570948074697437e9\n @test CHOLMOD.norm_sparse(A, 1) ≈ 3.570948074697437e9\n @test_throws ArgumentError CHOLMOD.norm_sparse(A, 2)\n @test CHOLMOD.isvalid(A)\n\n x = fill(1., n)\n b = A*x\n\n chma = ldlt(A) # LDL' form\n @test CHOLMOD.isvalid(chma)\n @test unsafe_load(pointer(chma)).is_ll == 0 # check that it is in fact an LDLt\n @test chma\\b ≈ x\n @test nnz(ldlt(A, perm=1:size(A,1))) > nnz(chma)\n @test size(chma) == size(A)\n chmal = CHOLMOD.FactorComponent(chma, :L)\n @test size(chmal) == size(A)\n @test size(chmal, 1) == size(A, 1)\n\n chma = cholesky(A) # LL' form\n @test CHOLMOD.isvalid(chma)\n @test unsafe_load(pointer(chma)).is_ll == 1 # check that it is in fact an LLt\n @test chma\\b ≈ x\n @test nnz(chma) == 489\n @test nnz(cholesky(A, perm=1:size(A,1))) > nnz(chma)\n @test size(chma) == size(A)\n chmal = CHOLMOD.FactorComponent(chma, :L)\n @test size(chmal) == size(A)\n @test size(chmal, 1) == size(A, 1)\n\n @testset \"eltype\" begin\n @test eltype(Dense(fill(1., 3))) == Float64\n @test eltype(A) == Float64\n @test eltype(chma) == Float64\n end\nend",
"@testset \"lp_afiro example\" begin\n afiro = CHOLMOD.Sparse(27, 51,\n CHOLMOD.SuiteSparse_long[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,\n 23,25,27,29,33,37,41,45,47,49,51,53,55,57,59,63,65,67,69,71,75,79,83,87,89,\n 91,93,95,97,99,101,102],\n CHOLMOD.SuiteSparse_long[2,3,6,7,8,9,12,13,16,17,18,19,20,21,22,23,24,25,26,\n 0,1,2,23,0,3,0,21,1,25,4,5,6,24,4,5,7,24,4,5,8,24,4,5,9,24,6,20,7,20,8,20,9,\n 20,3,4,4,22,5,26,10,11,12,21,10,13,10,23,10,20,11,25,14,15,16,22,14,15,17,\n 22,14,15,18,22,14,15,19,22,16,20,17,20,18,20,19,20,13,15,15,24,14,26,15],\n [1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,\n 1.0,-1.0,-1.06,1.0,0.301,1.0,-1.0,1.0,-1.0,1.0,1.0,-1.0,-1.06,1.0,0.301,\n -1.0,-1.06,1.0,0.313,-1.0,-0.96,1.0,0.313,-1.0,-0.86,1.0,0.326,-1.0,2.364,\n -1.0,2.386,-1.0,2.408,-1.0,2.429,1.4,1.0,1.0,-1.0,1.0,1.0,-1.0,-0.43,1.0,\n 0.109,1.0,-1.0,1.0,-1.0,1.0,-1.0,1.0,1.0,-0.43,1.0,1.0,0.109,-0.43,1.0,1.0,\n 0.108,-0.39,1.0,1.0,0.108,-0.37,1.0,1.0,0.107,-1.0,2.191,-1.0,2.219,-1.0,\n 2.249,-1.0,2.279,1.4,-1.0,1.0,-1.0,1.0,1.0,1.0], 0)\n afiro2 = CHOLMOD.aat(afiro, CHOLMOD.SuiteSparse_long[0:50;], CHOLMOD.SuiteSparse_long(1))\n CHOLMOD.change_stype!(afiro2, -1)\n chmaf = cholesky(afiro2)\n y = afiro'*fill(1., size(afiro,1))\n sol = chmaf\\(afiro*y) # least squares solution\n @test CHOLMOD.isvalid(sol)\n pred = afiro'*sol\n @test norm(afiro * (convert(Matrix, y) - convert(Matrix, pred))) < 1e-8\nend",
"@testset \"Issue 9160\" begin\n local A, B\n A = sprand(10, 10, 0.1)\n A = convert(SparseMatrixCSC{Float64,CHOLMOD.SuiteSparse_long}, A)\n cmA = CHOLMOD.Sparse(A)\n\n B = sprand(10, 10, 0.1)\n B = convert(SparseMatrixCSC{Float64,CHOLMOD.SuiteSparse_long}, B)\n cmB = CHOLMOD.Sparse(B)\n\n # Ac_mul_B\n @test sparse(cmA'*cmB) ≈ A'*B\n\n # A_mul_Bc\n @test sparse(cmA*cmB') ≈ A*B'\n\n # A_mul_Ac\n @test sparse(cmA*cmA') ≈ A*A'\n\n # Ac_mul_A\n @test sparse(cmA'*cmA) ≈ A'*A\n\n # A_mul_Ac for symmetric A\n A = 0.5*(A + copy(A'))\n cmA = CHOLMOD.Sparse(A)\n @test sparse(cmA*cmA') ≈ A*A'\nend",
"@testset \"Issue #9915\" begin\n sparseI = sparse(1.0I, 2, 2)\n @test sparseI \\ sparseI == sparseI\nend",
"@testset \"test Sparse constructor Symmetric and Hermitian input (and issymmetric and ishermitian)\" begin\n ACSC = sprandn(10, 10, 0.3) + I\n @test issymmetric(Sparse(Symmetric(ACSC, :L)))\n @test issymmetric(Sparse(Symmetric(ACSC, :U)))\n @test ishermitian(Sparse(Hermitian(complex(ACSC), :L)))\n @test ishermitian(Sparse(Hermitian(complex(ACSC), :U)))\nend",
"@testset \"test Sparse constructor for C_Sparse{Cvoid} (and read_sparse)\" begin\n mktempdir() do temp_dir\n testfile = joinpath(temp_dir, \"tmp.mtx\")\n\n writedlm(testfile, [\"%%MatrixMarket matrix coordinate real symmetric\",\"3 3 4\",\"1 1 1\",\"2 2 1\",\"3 2 0.5\",\"3 3 1\"])\n @test sparse(CHOLMOD.Sparse(testfile)) == [1 0 0;0 1 0.5;0 0.5 1]\n rm(testfile)\n\n writedlm(testfile, [\"%%MatrixMarket matrix coordinate complex Hermitian\",\n \"3 3 4\",\"1 1 1.0 0.0\",\"2 2 1.0 0.0\",\"3 2 0.5 0.5\",\"3 3 1.0 0.0\"])\n @test sparse(CHOLMOD.Sparse(testfile)) == [1 0 0;0 1 0.5-0.5im;0 0.5+0.5im 1]\n rm(testfile)\n\n writedlm(testfile, [\"%%MatrixMarket matrix coordinate real symmetric\",\"%3 3 4\",\"1 1 1\",\"2 2 1\",\"3 2 0.5\",\"3 3 1\"])\n @test_throws ArgumentError sparse(CHOLMOD.Sparse(testfile))\n rm(testfile)\n end\nend",
"@testset \"test that Sparse(Ptr) constructor throws the right places\" begin\n @test_throws ArgumentError CHOLMOD.Sparse(convert(Ptr{CHOLMOD.C_Sparse{Float64}}, C_NULL))\n @test_throws ArgumentError CHOLMOD.Sparse(convert(Ptr{CHOLMOD.C_Sparse{Cvoid}}, C_NULL))\nend",
"@testset \"illegal dtype (for now but should be supported at some point)\" begin\n p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_Sparse{Cvoid}},\n (Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Cvoid}),\n 1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common_struct)\n puint = convert(Ptr{UInt32}, p)\n unsafe_store!(puint, CHOLMOD.SINGLE, 3*div(sizeof(Csize_t), 4) + 5*div(sizeof(Ptr{Cvoid}), 4) + 4)\n @test_throws CHOLMOD.CHOLMODException CHOLMOD.Sparse(p)\nend",
"@testset \"illegal dtype\" begin\n p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_Sparse{Cvoid}},\n (Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Cvoid}),\n 1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common_struct)\n puint = convert(Ptr{UInt32}, p)\n unsafe_store!(puint, 5, 3*div(sizeof(Csize_t), 4) + 5*div(sizeof(Ptr{Cvoid}), 4) + 4)\n @test_throws CHOLMOD.CHOLMODException CHOLMOD.Sparse(p)\nend",
"@testset \"illegal xtype\" begin\n p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_Sparse{Cvoid}},\n (Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Cvoid}),\n 1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common_struct)\n puint = convert(Ptr{UInt32}, p)\n unsafe_store!(puint, 3, 3*div(sizeof(Csize_t), 4) + 5*div(sizeof(Ptr{Cvoid}), 4) + 3)\n @test_throws CHOLMOD.CHOLMODException CHOLMOD.Sparse(p)\nend",
"@testset \"illegal itype I\" begin\n p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_Sparse{Cvoid}},\n (Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Cvoid}),\n 1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common_struct)\n puint = convert(Ptr{UInt32}, p)\n unsafe_store!(puint, CHOLMOD.INTLONG, 3*div(sizeof(Csize_t), 4) + 5*div(sizeof(Ptr{Cvoid}), 4) + 2)\n @test_throws CHOLMOD.CHOLMODException CHOLMOD.Sparse(p)\nend",
"@testset \"illegal itype II\" begin\n p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_Sparse{Cvoid}},\n (Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Cvoid}),\n 1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common_struct)\n puint = convert(Ptr{UInt32}, p)\n unsafe_store!(puint, 5, 3*div(sizeof(Csize_t), 4) + 5*div(sizeof(Ptr{Cvoid}), 4) + 2)\n @test_throws CHOLMOD.CHOLMODException CHOLMOD.Sparse(p)\nend",
"@testset \"High level interface\" for elty in (Float64, Complex{Float64})\n local A, b\n if elty == Float64\n A = randn(5, 5)\n b = randn(5)\n else\n A = complex.(randn(5, 5), randn(5, 5))\n b = complex.(randn(5), randn(5))\n end\n ADense = CHOLMOD.Dense(A)\n bDense = CHOLMOD.Dense(b)\n\n @test_throws BoundsError ADense[6, 1]\n @test_throws BoundsError ADense[1, 6]\n @test copy(ADense) == ADense\n @test CHOLMOD.norm_dense(ADense, 1) ≈ opnorm(A, 1)\n @test CHOLMOD.norm_dense(ADense, 0) ≈ opnorm(A, Inf)\n @test_throws ArgumentError CHOLMOD.norm_dense(ADense, 2)\n @test_throws ArgumentError CHOLMOD.norm_dense(ADense, 3)\n\n @test CHOLMOD.norm_dense(bDense, 2) ≈ norm(b)\n @test CHOLMOD.check_dense(bDense)\n\n AA = CHOLMOD.eye(3)\n unsafe_store!(convert(Ptr{Csize_t}, pointer(AA)), 2, 1) # change size, but not stride, of Dense\n @test convert(Matrix, AA) == Matrix(I, 2, 3)\nend",
"@testset \"Low level interface\" begin\n @test isa(CHOLMOD.zeros(3, 3, Float64), CHOLMOD.Dense{Float64})\n @test isa(CHOLMOD.zeros(3, 3), CHOLMOD.Dense{Float64})\n @test isa(CHOLMOD.zeros(3, 3, Float64), CHOLMOD.Dense{Float64})\n @test isa(CHOLMOD.ones(3, 3), CHOLMOD.Dense{Float64})\n @test isa(CHOLMOD.eye(3, 4, Float64), CHOLMOD.Dense{Float64})\n @test isa(CHOLMOD.eye(3, 4), CHOLMOD.Dense{Float64})\n @test isa(CHOLMOD.eye(3), CHOLMOD.Dense{Float64})\n @test isa(copy(CHOLMOD.eye(3)), CHOLMOD.Dense{Float64})\nend",
"@testset \"test free!\" begin\n p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_Sparse{Float64}},\n (Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Cvoid}),\n 1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common_struct)\n @test CHOLMOD.free!(p)\nend",
"@testset \"Core functionality\" for elty in (Float64, Complex{Float64})\n A1 = sparse([1:5; 1], [1:5; 2], elty == Float64 ? randn(6) : complex.(randn(6), randn(6)))\n A2 = sparse([1:5; 1], [1:5; 2], elty == Float64 ? randn(6) : complex.(randn(6), randn(6)))\n A1pd = A1'A1\n A1Sparse = CHOLMOD.Sparse(A1)\n A2Sparse = CHOLMOD.Sparse(A2)\n A1pdSparse = CHOLMOD.Sparse(\n A1pd.m,\n A1pd.n,\n SuiteSparse.decrement(A1pd.colptr),\n SuiteSparse.decrement(A1pd.rowval),\n A1pd.nzval)\n\n ## High level interface\n @test isa(CHOLMOD.Sparse(3, 3, [0,1,3,4], [0,2,1,2], fill(1., 4)), CHOLMOD.Sparse) # Sparse doesn't require columns to be sorted\n @test_throws BoundsError A1Sparse[6, 1]\n @test_throws BoundsError A1Sparse[1, 6]\n @test sparse(A1Sparse) == A1\n for i = 1:size(A1, 1)\n A1[i, i] = real(A1[i, i])\n end #Construct Hermitian matrix properly\n @test CHOLMOD.sparse(CHOLMOD.Sparse(Hermitian(A1, :L))) == Hermitian(A1, :L)\n @test CHOLMOD.sparse(CHOLMOD.Sparse(Hermitian(A1, :U))) == Hermitian(A1, :U)\n @test_throws ArgumentError convert(SparseMatrixCSC{elty,Int}, A1pdSparse)\n if elty <: Real\n @test_throws ArgumentError convert(Symmetric{Float64,SparseMatrixCSC{Float64,Int}}, A1Sparse)\n else\n @test_throws ArgumentError convert(Hermitian{Complex{Float64},SparseMatrixCSC{Complex{Float64},Int}}, A1Sparse)\n end\n @test copy(A1Sparse) == A1Sparse\n @test size(A1Sparse, 3) == 1\n if elty <: Real # multiplication only defined for real matrices in CHOLMOD\n @test A1Sparse*A2Sparse ≈ A1*A2\n @test_throws DimensionMismatch CHOLMOD.Sparse(A1[:,1:4])*A2Sparse\n @test A1Sparse'A2Sparse ≈ A1'A2\n @test A1Sparse*A2Sparse' ≈ A1*A2'\n\n @test A1Sparse*A1Sparse ≈ A1*A1\n @test A1Sparse'A1Sparse ≈ A1'A1\n @test A1Sparse*A1Sparse' ≈ A1*A1'\n\n @test A1pdSparse*A1pdSparse ≈ A1pd*A1pd\n @test A1pdSparse'A1pdSparse ≈ A1pd'A1pd\n @test A1pdSparse*A1pdSparse' ≈ A1pd*A1pd'\n\n @test_throws DimensionMismatch A1Sparse*CHOLMOD.eye(4, 5, elty)\n end\n\n # Factor\n @test_throws ArgumentError cholesky(A1)\n @test_throws ArgumentError cholesky(A1)\n @test_throws ArgumentError cholesky(A1, shift=1.0)\n @test_throws ArgumentError ldlt(A1)\n @test_throws ArgumentError ldlt(A1, shift=1.0)\n C = A1 + copy(adjoint(A1))\n λmaxC = eigmax(Array(C))\n b = fill(1., size(A1, 1))\n @test_throws PosDefException cholesky(C - 2λmaxC*I)\n @test_throws PosDefException cholesky(C, shift=-2λmaxC)\n @test_throws PosDefException ldlt(C - C[1,1]*I)\n @test_throws PosDefException ldlt(C, shift=-real(C[1,1]))\n @test !isposdef(cholesky(C - 2λmaxC*I; check = false))\n @test !isposdef(cholesky(C, shift=-2λmaxC; check = false))\n @test !issuccess(ldlt(C - C[1,1]*I; check = false))\n @test !issuccess(ldlt(C, shift=-real(C[1,1]); check = false))\n F = cholesky(A1pd)\n tmp = IOBuffer()\n show(tmp, F)\n @test tmp.size > 0\n @test isa(CHOLMOD.Sparse(F), CHOLMOD.Sparse{elty})\n @test_throws DimensionMismatch F\\CHOLMOD.Dense(fill(elty(1), 4))\n @test_throws DimensionMismatch F\\CHOLMOD.Sparse(sparse(fill(elty(1), 4)))\n b = fill(1., 5)\n bT = fill(elty(1), 5)\n @test F'\\bT ≈ Array(A1pd)'\\b\n @test F'\\sparse(bT) ≈ Array(A1pd)'\\b\n @test transpose(F)\\bT ≈ conj(A1pd)'\\bT\n @test F\\CHOLMOD.Sparse(sparse(bT)) ≈ A1pd\\b\n @test logdet(F) ≈ logdet(Array(A1pd))\n @test det(F) == exp(logdet(F))\n let # to test supernodal, we must use a larger matrix\n Ftmp = sprandn(100, 100, 0.1)\n Ftmp = Ftmp'Ftmp + I\n @test logdet(cholesky(Ftmp)) ≈ logdet(Array(Ftmp))\n end\n @test logdet(ldlt(A1pd)) ≈ logdet(Array(A1pd))\n @test isposdef(A1pd)\n @test !isposdef(A1)\n @test !isposdef(A1 + copy(A1') |> t -> t - 2eigmax(Array(t))*I)\n\n if elty <: Real\n @test CHOLMOD.issymmetric(Sparse(A1pd, 0))\n @test CHOLMOD.Sparse(cholesky(Symmetric(A1pd, :L))) == CHOLMOD.Sparse(cholesky(A1pd))\n F1 = CHOLMOD.Sparse(cholesky(Symmetric(A1pd, :L), shift=2))\n F2 = CHOLMOD.Sparse(cholesky(A1pd, shift=2))\n @test F1 == F2\n @test CHOLMOD.Sparse(ldlt(Symmetric(A1pd, :L))) == CHOLMOD.Sparse(ldlt(A1pd))\n F1 = CHOLMOD.Sparse(ldlt(Symmetric(A1pd, :L), shift=2))\n F2 = CHOLMOD.Sparse(ldlt(A1pd, shift=2))\n @test F1 == F2\n else\n @test !CHOLMOD.issymmetric(Sparse(A1pd, 0))\n @test CHOLMOD.ishermitian(Sparse(A1pd, 0))\n @test CHOLMOD.Sparse(cholesky(Hermitian(A1pd, :L))) == CHOLMOD.Sparse(cholesky(A1pd))\n F1 = CHOLMOD.Sparse(cholesky(Hermitian(A1pd, :L), shift=2))\n F2 = CHOLMOD.Sparse(cholesky(A1pd, shift=2))\n @test F1 == F2\n @test CHOLMOD.Sparse(ldlt(Hermitian(A1pd, :L))) == CHOLMOD.Sparse(ldlt(A1pd))\n F1 = CHOLMOD.Sparse(ldlt(Hermitian(A1pd, :L), shift=2))\n F2 = CHOLMOD.Sparse(ldlt(A1pd, shift=2))\n @test F1 == F2\n end\n\n ### cholesky!/ldlt!\n F = cholesky(A1pd)\n CHOLMOD.change_factor!(F, false, false, true, true)\n @test unsafe_load(pointer(F)).is_ll == 0\n CHOLMOD.change_factor!(F, true, false, true, true)\n @test CHOLMOD.Sparse(cholesky!(copy(F), A1pd)) ≈ CHOLMOD.Sparse(F) # surprisingly, this can cause small ulp size changes so we cannot test exact equality\n @test size(F, 2) == 5\n @test size(F, 3) == 1\n @test_throws ArgumentError size(F, 0)\n\n F = cholesky(A1pdSparse, shift=2)\n @test isa(CHOLMOD.Sparse(F), CHOLMOD.Sparse{elty})\n @test CHOLMOD.Sparse(cholesky!(copy(F), A1pd, shift=2.0)) ≈ CHOLMOD.Sparse(F) # surprisingly, this can cause small ulp size changes so we cannot test exact equality\n\n F = ldlt(A1pd)\n @test isa(CHOLMOD.Sparse(F), CHOLMOD.Sparse{elty})\n @test CHOLMOD.Sparse(ldlt!(copy(F), A1pd)) ≈ CHOLMOD.Sparse(F) # surprisingly, this can cause small ulp size changes so we cannot test exact equality\n\n F = ldlt(A1pdSparse, shift=2)\n @test isa(CHOLMOD.Sparse(F), CHOLMOD.Sparse{elty})\n @test CHOLMOD.Sparse(ldlt!(copy(F), A1pd, shift=2.0)) ≈ CHOLMOD.Sparse(F) # surprisingly, this can cause small ulp size changes so we cannot test exact equality\n\n @test isa(CHOLMOD.factor_to_sparse!(F), CHOLMOD.Sparse)\n @test_throws CHOLMOD.CHOLMODException CHOLMOD.factor_to_sparse!(F)\n\n ## Low level interface\n @test CHOLMOD.nnz(A1Sparse) == nnz(A1)\n @test CHOLMOD.speye(5, 5, elty) == Matrix(I, 5, 5)\n @test CHOLMOD.spzeros(5, 5, 5, elty) == zeros(elty, 5, 5)\n if elty <: Real\n @test CHOLMOD.copy(A1Sparse, 0, 1) == A1Sparse\n @test CHOLMOD.horzcat(A1Sparse, A2Sparse, true) == [A1 A2]\n @test CHOLMOD.vertcat(A1Sparse, A2Sparse, true) == [A1; A2]\n svec = fill(elty(1), 1)\n @test CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.SCALAR, A1Sparse) == A1Sparse\n svec = fill(elty(1), 5)\n @test_throws DimensionMismatch CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.SCALAR, A1Sparse)\n @test CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.ROW, A1Sparse) == A1Sparse\n @test_throws DimensionMismatch CHOLMOD.scale!(CHOLMOD.Dense([svec; 1]), CHOLMOD.ROW, A1Sparse)\n @test CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.COL, A1Sparse) == A1Sparse\n @test_throws DimensionMismatch CHOLMOD.scale!(CHOLMOD.Dense([svec; 1]), CHOLMOD.COL, A1Sparse)\n @test CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.SYM, A1Sparse) == A1Sparse\n @test_throws DimensionMismatch CHOLMOD.scale!(CHOLMOD.Dense([svec; 1]), CHOLMOD.SYM, A1Sparse)\n @test_throws DimensionMismatch CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.SYM, CHOLMOD.Sparse(A1[:,1:4]))\n else\n @test_throws MethodError CHOLMOD.copy(A1Sparse, 0, 1) == A1Sparse\n @test_throws MethodError CHOLMOD.horzcat(A1Sparse, A2Sparse, true) == [A1 A2]\n @test_throws MethodError CHOLMOD.vertcat(A1Sparse, A2Sparse, true) == [A1; A2]\n end\n\n if elty <: Real\n @test CHOLMOD.ssmult(A1Sparse, A2Sparse, 0, true, true) ≈ A1*A2\n @test CHOLMOD.aat(A1Sparse, [0:size(A1,2)-1;], 1) ≈ A1*A1'\n @test CHOLMOD.aat(A1Sparse, [0:1;], 1) ≈ A1[:,1:2]*A1[:,1:2]'\n @test CHOLMOD.copy(A1Sparse, 0, 1) == A1Sparse\n end\n\n @test CHOLMOD.Sparse(CHOLMOD.Dense(A1Sparse)) == A1Sparse\nend",
"@testset \"extract factors\" begin\n Af = float([4 12 -16; 12 37 -43; -16 -43 98])\n As = sparse(Af)\n Lf = float([2 0 0; 6 1 0; -8 5 3])\n LDf = float([4 0 0; 3 1 0; -4 5 9]) # D is stored along the diagonal\n L_f = float([1 0 0; 3 1 0; -4 5 1]) # L by itself in LDLt of Af\n D_f = float([4 0 0; 0 1 0; 0 0 9])\n p = [2,3,1]\n p_inv = [3,1,2]\n\n @testset \"cholesky, no permutation\" begin\n Fs = cholesky(As, perm=[1:3;])\n @test Fs.p == [1:3;]\n @test sparse(Fs.L) ≈ Lf\n @test sparse(Fs) ≈ As\n b = rand(3)\n @test Fs\\b ≈ Af\\b\n @test Fs.UP\\(Fs.PtL\\b) ≈ Af\\b\n @test Fs.L\\b ≈ Lf\\b\n @test Fs.U\\b ≈ Lf'\\b\n @test Fs.L'\\b ≈ Lf'\\b\n @test Fs.U'\\b ≈ Lf\\b\n @test Fs.PtL\\b ≈ Lf\\b\n @test Fs.UP\\b ≈ Lf'\\b\n @test Fs.PtL'\\b ≈ Lf'\\b\n @test Fs.UP'\\b ≈ Lf\\b\n @test_throws CHOLMOD.CHOLMODException Fs.D\n @test_throws CHOLMOD.CHOLMODException Fs.LD\n @test_throws CHOLMOD.CHOLMODException Fs.DU\n @test_throws CHOLMOD.CHOLMODException Fs.PLD\n @test_throws CHOLMOD.CHOLMODException Fs.DUPt\n end\n\n @testset \"cholesky, with permutation\" begin\n Fs = cholesky(As, perm=p)\n @test Fs.p == p\n Afp = Af[p,p]\n Lfp = cholesky(Afp).L\n Ls = sparse(Fs.L)\n @test Ls ≈ Lfp\n @test Ls * Ls' ≈ Afp\n P = sparse(1:3, Fs.p, ones(3))\n @test P' * Ls * Ls' * P ≈ As\n @test sparse(Fs) ≈ As\n b = rand(3)\n @test Fs\\b ≈ Af\\b\n @test Fs.UP\\(Fs.PtL\\b) ≈ Af\\b\n @test Fs.L\\b ≈ Lfp\\b\n @test Fs.U'\\b ≈ Lfp\\b\n @test Fs.U\\b ≈ Lfp'\\b\n @test Fs.L'\\b ≈ Lfp'\\b\n @test Fs.PtL\\b ≈ Lfp\\b[p]\n @test Fs.UP\\b ≈ (Lfp'\\b)[p_inv]\n @test Fs.PtL'\\b ≈ (Lfp'\\b)[p_inv]\n @test Fs.UP'\\b ≈ Lfp\\b[p]\n @test_throws CHOLMOD.CHOLMODException Fs.PL\n @test_throws CHOLMOD.CHOLMODException Fs.UPt\n @test_throws CHOLMOD.CHOLMODException Fs.D\n @test_throws CHOLMOD.CHOLMODException Fs.LD\n @test_throws CHOLMOD.CHOLMODException Fs.DU\n @test_throws CHOLMOD.CHOLMODException Fs.PLD\n @test_throws CHOLMOD.CHOLMODException Fs.DUPt\n end\n\n @testset \"ldlt, no permutation\" begin\n Fs = ldlt(As, perm=[1:3;])\n @test Fs.p == [1:3;]\n @test sparse(Fs.LD) ≈ LDf\n @test sparse(Fs) ≈ As\n b = rand(3)\n @test Fs\\b ≈ Af\\b\n @test Fs.UP\\(Fs.PtLD\\b) ≈ Af\\b\n @test Fs.DUP\\(Fs.PtL\\b) ≈ Af\\b\n @test Fs.L\\b ≈ L_f\\b\n @test Fs.U\\b ≈ L_f'\\b\n @test Fs.L'\\b ≈ L_f'\\b\n @test Fs.U'\\b ≈ L_f\\b\n @test Fs.PtL\\b ≈ L_f\\b\n @test Fs.UP\\b ≈ L_f'\\b\n @test Fs.PtL'\\b ≈ L_f'\\b\n @test Fs.UP'\\b ≈ L_f\\b\n @test Fs.D\\b ≈ D_f\\b\n @test Fs.D'\\b ≈ D_f\\b\n @test Fs.LD\\b ≈ D_f\\(L_f\\b)\n @test Fs.DU'\\b ≈ D_f\\(L_f\\b)\n @test Fs.LD'\\b ≈ L_f'\\(D_f\\b)\n @test Fs.DU\\b ≈ L_f'\\(D_f\\b)\n @test Fs.PtLD\\b ≈ D_f\\(L_f\\b)\n @test Fs.DUP'\\b ≈ D_f\\(L_f\\b)\n @test Fs.PtLD'\\b ≈ L_f'\\(D_f\\b)\n @test Fs.DUP\\b ≈ L_f'\\(D_f\\b)\n end\n\n @testset \"ldlt, with permutation\" begin\n Fs = ldlt(As, perm=p)\n @test Fs.p == p\n @test sparse(Fs) ≈ As\n b = rand(3)\n Asp = As[p,p]\n LDp = sparse(ldlt(Asp, perm=[1,2,3]).LD)\n # LDp = sparse(Fs.LD)\n Lp, dp = SuiteSparse.CHOLMOD.getLd!(copy(LDp))\n Dp = sparse(Diagonal(dp))\n @test Fs\\b ≈ Af\\b\n @test Fs.UP\\(Fs.PtLD\\b) ≈ Af\\b\n @test Fs.DUP\\(Fs.PtL\\b) ≈ Af\\b\n @test Fs.L\\b ≈ Lp\\b\n @test Fs.U\\b ≈ Lp'\\b\n @test Fs.L'\\b ≈ Lp'\\b\n @test Fs.U'\\b ≈ Lp\\b\n @test Fs.PtL\\b ≈ Lp\\b[p]\n @test Fs.UP\\b ≈ (Lp'\\b)[p_inv]\n @test Fs.PtL'\\b ≈ (Lp'\\b)[p_inv]\n @test Fs.UP'\\b ≈ Lp\\b[p]\n @test Fs.LD\\b ≈ Dp\\(Lp\\b)\n @test Fs.DU'\\b ≈ Dp\\(Lp\\b)\n @test Fs.LD'\\b ≈ Lp'\\(Dp\\b)\n @test Fs.DU\\b ≈ Lp'\\(Dp\\b)\n @test Fs.PtLD\\b ≈ Dp\\(Lp\\b[p])\n @test Fs.DUP'\\b ≈ Dp\\(Lp\\b[p])\n @test Fs.PtLD'\\b ≈ (Lp'\\(Dp\\b))[p_inv]\n @test Fs.DUP\\b ≈ (Lp'\\(Dp\\b))[p_inv]\n @test_throws CHOLMOD.CHOLMODException Fs.DUPt\n @test_throws CHOLMOD.CHOLMODException Fs.PLD\n end\n\n @testset \"Element promotion and type inference\" begin\n @inferred cholesky(As)\\fill(1, size(As, 1))\n @inferred ldlt(As)\\fill(1, size(As, 1))\n end\nend",
"@testset \"Issue 11745 - row and column pointers were not sorted in sparse(Factor)\" begin\n A = Float64[10 1 1 1; 1 10 0 0; 1 0 10 0; 1 0 0 10]\n @test sparse(cholesky(sparse(A))) ≈ A\nend",
"@testset \"Issue 11747 - Wrong show method defined for FactorComponent\" begin\n v = cholesky(sparse(Float64[ 10 1 1 1; 1 10 0 0; 1 0 10 0; 1 0 0 10])).L\n for s in (sprint(show, MIME(\"text/plain\"), v), sprint(show, v))\n @test occursin(\"method: simplicial\", s)\n @test !occursin(\"#undef\", s)\n end\nend",
"@testset \"Issue 14076\" begin\n @test cholesky(sparse([1,2,3,4], [1,2,3,4], Float32[1,4,16,64]))\\[1,4,16,64] == fill(1, 4)\nend",
"@testset \"Issue 29367\" begin\n if Int != Int32\n @test_throws MethodError cholesky(sparse(Int32[1,2,3,4], Int32[1,2,3,4], Float64[1,4,16,64]))\n @test_throws MethodError cholesky(sparse(Int32[1,2,3,4], Int32[1,2,3,4], Float32[1,4,16,64]))\n @test_throws MethodError ldlt(sparse(Int32[1,2,3,4], Int32[1,2,3,4], Float64[1,4,16,64]))\n @test_throws MethodError ldlt(sparse(Int32[1,2,3,4], Int32[1,2,3,4], Float32[1,4,16,64]))\n end\nend",
"@testset \"Issue 14134\" begin\n A = CHOLMOD.Sparse(sprandn(10,5,0.1) + I |> t -> t't)\n b = IOBuffer()\n serialize(b, A)\n seekstart(b)\n Anew = deserialize(b)\n @test_throws ArgumentError show(Anew)\n @test_throws ArgumentError size(Anew)\n @test_throws ArgumentError Anew[1]\n @test_throws ArgumentError Anew[2,1]\n F = cholesky(A)\n serialize(b, F)\n seekstart(b)\n Fnew = deserialize(b)\n @test_throws ArgumentError Fnew\\fill(1., 5)\n @test_throws ArgumentError show(Fnew)\n @test_throws ArgumentError size(Fnew)\n @test_throws ArgumentError diag(Fnew)\n @test_throws ArgumentError logdet(Fnew)\nend",
"@testset \"Issue with promotion during conversion to CHOLMOD.Dense\" begin\n @test CHOLMOD.Dense(fill(1, 5)) == fill(1, 5, 1)\n @test CHOLMOD.Dense(fill(1f0, 5)) == fill(1, 5, 1)\n @test CHOLMOD.Dense(fill(1f0 + 0im, 5, 2)) == fill(1, 5, 2)\nend",
"@testset \"Further issue with promotion #14894\" begin\n x = fill(1., 5)\n @test cholesky(sparse(Float16(1)I, 5, 5))\\x == x\n @test cholesky(Symmetric(sparse(Float16(1)I, 5, 5)))\\x == x\n @test cholesky(Hermitian(sparse(Complex{Float16}(1)I, 5, 5)))\\x == x\n @test_throws TypeError cholesky(sparse(BigFloat(1)I, 5, 5))\n @test_throws TypeError cholesky(Symmetric(sparse(BigFloat(1)I, 5, 5)))\n @test_throws TypeError cholesky(Hermitian(sparse(Complex{BigFloat}(1)I, 5, 5)))\nend",
"@testset \"test \\\\ for Factor and StridedVecOrMat\" begin\n x = rand(5)\n A = cholesky(sparse(Diagonal(x.\\1)))\n @test A\\view(fill(1.,10),1:2:10) ≈ x\n @test A\\view(Matrix(1.0I, 5, 5), :, :) ≈ Matrix(Diagonal(x))\nend",
"@testset \"Real factorization and complex rhs\" begin\n A = sprandn(5, 5, 0.4) |> t -> t't + I\n B = complex.(randn(5, 2), randn(5, 2))\n @test cholesky(A)\\B ≈ A\\B\nend",
"@testset \"Make sure that ldlt performs an LDLt (Issue #19032)\" begin\n m, n = 400, 500\n A = sprandn(m, n, .2)\n M = [I copy(A'); A -I]\n b = M * fill(1., m+n)\n F = ldlt(M)\n s = unsafe_load(pointer(F))\n @test s.is_super == 0\n @test F\\b ≈ fill(1., m+n)\n F2 = cholesky(M; check = false)\n @test !issuccess(F2)\n ldlt!(F2, M)\n @test issuccess(F2)\n @test F2\\b ≈ fill(1., m+n)\nend",
"@testset \"Test that imaginary parts in Hermitian{T,SparseMatrixCSC{T}} are ignored\" begin\n A = sparse([1,2,3,4,1], [1,2,3,4,2], [complex(2.0,1),2,2,2,1])\n Fs = cholesky(Hermitian(A))\n Fd = cholesky(Hermitian(Array(A)))\n @test sparse(Fs) ≈ Hermitian(A)\n @test Fs\\fill(1., 4) ≈ Fd\\fill(1., 4)\nend",
"@testset \"\\\\ '\\\\ and transpose(...)\\\\\" begin\n # Test that \\ and '\\ and transpose(...)\\ work for Symmetric and Hermitian. This is just\n # a dispatch exercise so it doesn't matter that the complex matrix has\n # zero imaginary parts\n Apre = sprandn(10, 10, 0.2) - I\n for A in (Symmetric(Apre), Hermitian(Apre),\n Symmetric(Apre + 10I), Hermitian(Apre + 10I),\n Hermitian(complex(Apre)), Hermitian(complex(Apre) + 10I))\n local A, x, b\n x = fill(1., 10)\n b = A*x\n @test x ≈ A\\b\n @test transpose(A)\\b ≈ A'\\b\n end\nend",
"@testset \"Check that Symmetric{SparseMatrixCSC} can be constructed from CHOLMOD.Sparse\" begin\n Int === Int32 && Random.seed!(124)\n A = sprandn(10, 10, 0.1)\n B = CHOLMOD.Sparse(A)\n C = B'B\n # Change internal representation to symmetric (upper/lower)\n o = fieldoffset(CHOLMOD.C_Sparse{eltype(C)}, findall(fieldnames(CHOLMOD.C_Sparse{eltype(C)}) .== :stype)[1])\n for uplo in (1, -1)\n unsafe_store!(Ptr{Int8}(pointer(C)), uplo, Int(o) + 1)\n @test convert(Symmetric{Float64,SparseMatrixCSC{Float64,Int}}, C) ≈ Symmetric(A'A)\n end\nend",
"@testset \"Check inputs to Sparse. Related to #20024\" for A_ in (\n SparseMatrixCSC(2, 2, [1, 2], CHOLMOD.SuiteSparse_long[], Float64[]),\n SparseMatrixCSC(2, 2, [1, 2, 3], CHOLMOD.SuiteSparse_long[1], Float64[]),\n SparseMatrixCSC(2, 2, [1, 2, 3], CHOLMOD.SuiteSparse_long[], Float64[1.0]),\n SparseMatrixCSC(2, 2, [1, 2, 3], CHOLMOD.SuiteSparse_long[1], Float64[1.0]))\n @test_throws ArgumentError CHOLMOD.Sparse(size(A_)..., A_.colptr .- 1, A_.rowval .- 1, A_.nzval)\n @test_throws ArgumentError CHOLMOD.Sparse(A_)\nend",
"@testset \"sparse right multiplication of Symmetric and Hermitian matrices #21431\" begin\n S = sparse(1.0I, 2, 2)\n @test issparse(S*S*S)\n for T in (Symmetric, Hermitian)\n @test issparse(S*T(S)*S)\n @test issparse(S*(T(S)*S))\n @test issparse((S*T(S))*S)\n end\nend",
"@testset \"Test sparse low rank update for cholesky decomposion\" begin\n A = SparseMatrixCSC{Float64,CHOLMOD.SuiteSparse_long}(10, 5, [1,3,6,8,10,13], [6,7,1,2,9,3,5,1,7,6,7,9],\n [-0.138843, 2.99571, -0.556814, 0.669704, -1.39252, 1.33814,\n 1.02371, -0.502384, 1.10686, 0.262229, -1.6935, 0.525239])\n AtA = A'*A\n C0 = [1., 2., 0, 0, 0]\n # Test both cholesky and LDLt with and without automatic permutations\n for F in (cholesky(AtA), cholesky(AtA, perm=1:5), ldlt(AtA), ldlt(AtA, perm=1:5))\n local F\n x0 = F\\(b = fill(1., 5))\n #Test both sparse/dense and vectors/matrices\n for Ctest in (C0, sparse(C0), [C0 2*C0], sparse([C0 2*C0]))\n local x, C, F1\n C = copy(Ctest)\n F1 = copy(F)\n x = (AtA+C*C')\\b\n\n #Test update\n F11 = CHOLMOD.lowrankupdate(F1, C)\n @test Array(sparse(F11)) ≈ AtA+C*C'\n @test F11\\b ≈ x\n #Make sure we get back the same factor again\n F10 = CHOLMOD.lowrankdowndate(F11, C)\n @test Array(sparse(F10)) ≈ AtA\n @test F10\\b ≈ x0\n\n #Test in-place update\n CHOLMOD.lowrankupdate!(F1, C)\n @test Array(sparse(F1)) ≈ AtA+C*C'\n @test F1\\b ≈ x\n #Test in-place downdate\n CHOLMOD.lowrankdowndate!(F1, C)\n @test Array(sparse(F1)) ≈ AtA\n @test F1\\b ≈ x0\n\n @test C == Ctest #Make sure C didn't change\n end\n end\nend",
"@testset \"Issue #22335\" begin\n local A, F\n A = sparse(1.0I, 3, 3)\n @test issuccess(cholesky(A))\n A[3, 3] = -1\n F = cholesky(A; check = false)\n @test !issuccess(F)\n @test issuccess(ldlt!(F, A))\n A[3, 3] = 1\n @test A[:, 3:-1:1]\\fill(1., 3) == [1, 1, 1]\nend",
"@testset \"Non-positive definite matrices\" begin\n A = sparse(Float64[1 2; 2 1])\n B = sparse(ComplexF64[1 2; 2 1])\n for M in (A, B, Symmetric(A), Hermitian(B))\n F = cholesky(M; check = false)\n @test_throws PosDefException cholesky(M)\n @test_throws PosDefException cholesky!(F, M)\n @test !issuccess(cholesky(M; check = false))\n @test !issuccess(cholesky!(F, M; check = false))\n end\n A = sparse(Float64[0 0; 0 0])\n B = sparse(ComplexF64[0 0; 0 0])\n for M in (A, B, Symmetric(A), Hermitian(B))\n F = ldlt(M; check = false)\n @test_throws PosDefException ldlt(M)\n @test_throws PosDefException ldlt!(F, M)\n @test !issuccess(ldlt(M; check = false))\n @test !issuccess(ldlt!(F, M; check = false))\n end\nend"
] |
f7e873f50aecf4ae0d56cb398b44a52cf2fe5459
| 155
|
jl
|
Julia
|
test/shallow_water/runtests.jl
|
sandreza/Atum.jl
|
c03d3ff0a6fd0a6891de93747437ad0931572db7
|
[
"MIT"
] | 3
|
2021-07-06T16:49:53.000Z
|
2021-11-30T20:05:40.000Z
|
test/shallow_water/runtests.jl
|
sandreza/Atum.jl
|
c03d3ff0a6fd0a6891de93747437ad0931572db7
|
[
"MIT"
] | 1
|
2022-03-08T00:43:04.000Z
|
2022-03-08T00:43:27.000Z
|
test/shallow_water/runtests.jl
|
sandreza/Atum.jl
|
c03d3ff0a6fd0a6891de93747437ad0931572db7
|
[
"MIT"
] | 2
|
2021-07-06T16:49:56.000Z
|
2022-03-03T20:40:30.000Z
|
using Test
using SafeTestsets
@testset "shallow_water" begin
@safetestset "entropy_conservation_1d" begin include("entropy_conservation_1d.jl") end
end
| 22.142857
| 88
| 0.825806
|
[
"@testset \"shallow_water\" begin\n @safetestset \"entropy_conservation_1d\" begin include(\"entropy_conservation_1d.jl\") end\nend"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.