text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

@doc raw"""ResourceRule is the list of actions the subject is allowed to perform on resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete.

    IoK8sApiAuthorizationV1beta1ResourceRule(;
        apiGroups=nothing,
        resourceNames=nothing,
        resources=nothing,
        verbs=nothing,
    )

    - apiGroups::Vector{String} : APIGroups is the name of the APIGroup that contains the resources.  If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed.  \"*\" means all.
    - resourceNames::Vector{String} : ResourceNames is an optional white list of names that the rule applies to.  An empty set means that everything is allowed.  \"*\" means all.
    - resources::Vector{String} : Resources is a list of resources this rule applies to.  \"*\" means all in the specified apiGroups.  \"*/foo\" represents the subresource 'foo' for all resources in the specified apiGroups.
    - verbs::Vector{String} : Verb is a list of kubernetes resource API verbs, like: get, list, watch, create, update, delete, proxy.  \"*\" means all.
"""
mutable struct IoK8sApiAuthorizationV1beta1ResourceRule <: SwaggerModel
    apiGroups::Any # spec type: Union{ Nothing, Vector{String} } # spec name: apiGroups
    resourceNames::Any # spec type: Union{ Nothing, Vector{String} } # spec name: resourceNames
    resources::Any # spec type: Union{ Nothing, Vector{String} } # spec name: resources
    verbs::Any # spec type: Union{ Nothing, Vector{String} } # spec name: verbs

    function IoK8sApiAuthorizationV1beta1ResourceRule(;apiGroups=nothing, resourceNames=nothing, resources=nothing, verbs=nothing)
        o = new()
        validate_property(IoK8sApiAuthorizationV1beta1ResourceRule, Symbol("apiGroups"), apiGroups)
        setfield!(o, Symbol("apiGroups"), apiGroups)
        validate_property(IoK8sApiAuthorizationV1beta1ResourceRule, Symbol("resourceNames"), resourceNames)
        setfield!(o, Symbol("resourceNames"), resourceNames)
        validate_property(IoK8sApiAuthorizationV1beta1ResourceRule, Symbol("resources"), resources)
        setfield!(o, Symbol("resources"), resources)
        validate_property(IoK8sApiAuthorizationV1beta1ResourceRule, Symbol("verbs"), verbs)
        setfield!(o, Symbol("verbs"), verbs)
        o
    end
end # type IoK8sApiAuthorizationV1beta1ResourceRule

const _property_map_IoK8sApiAuthorizationV1beta1ResourceRule = Dict{Symbol,Symbol}(Symbol("apiGroups")=>Symbol("apiGroups"), Symbol("resourceNames")=>Symbol("resourceNames"), Symbol("resources")=>Symbol("resources"), Symbol("verbs")=>Symbol("verbs"))
const _property_types_IoK8sApiAuthorizationV1beta1ResourceRule = Dict{Symbol,String}(Symbol("apiGroups")=>"Vector{String}", Symbol("resourceNames")=>"Vector{String}", Symbol("resources")=>"Vector{String}", Symbol("verbs")=>"Vector{String}")
Base.propertynames(::Type{ IoK8sApiAuthorizationV1beta1ResourceRule }) = collect(keys(_property_map_IoK8sApiAuthorizationV1beta1ResourceRule))
Swagger.property_type(::Type{ IoK8sApiAuthorizationV1beta1ResourceRule }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiAuthorizationV1beta1ResourceRule[name]))}
Swagger.field_name(::Type{ IoK8sApiAuthorizationV1beta1ResourceRule }, property_name::Symbol) =  _property_map_IoK8sApiAuthorizationV1beta1ResourceRule[property_name]

function check_required(o::IoK8sApiAuthorizationV1beta1ResourceRule)
    (getproperty(o, Symbol("verbs")) === nothing) && (return false)
    true
end

function validate_property(::Type{ IoK8sApiAuthorizationV1beta1ResourceRule }, name::Symbol, val)
end


text:
Lar = LinearAlgebraicRepresentation

@testset "View p_STRUCT" begin
	geom_0 = hcat([[x] for x=0.:1.]...);
	topol_0 = [[i,i+1] for i=1:1];
	geom_1 = hcat([[x] for x=0.:.5:1.]...);
	topol_1 = [[i,i+1] for i=1:2];
	model_0 = (geom_0,topol_0);
	model_1 = (geom_1,topol_1);
	model_2 = Lar.larModelProduct(model_0,model_1);
	model_3 = Lar.larModelProduct(model_2,model_0);
	V,CV = model_3;

	@test typeof(V) == Array{Float64,2}
	@test typeof(CV) == Array{Array{Int64,1},1}
	@test size(V) == (3,12)
	@test length(CV) == 2

	V = hcat(V[:,1],[V[:,k] for k in 1:size(V,2)]...);
	W = [Any[V[h,k] for h=1:size(V,1)] for k=1:size(V,2)];

	@test typeof(PyObject([W,CV,[]])) == PyCall.PyObject
	@test repr(W) == "Array{Any,1}[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.5, 0.0], [0.0, 0.5, 1.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [1.0, 0.5, 0.0], [1.0, 0.5, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0]]"
	@test repr(CV) == "Array{Int64,1}[[1, 2, 3, 4, 7, 8, 9, 10], [3, 4, 5, 6, 9, 10, 11, 12]]"
end

ext: jl


text:
using Econometrics

# sample size
n = 30

# draw n values of x between 0 and 4
x = 0:4/(n-1):4

# true function (unknown to researcher)
function f(x)
    10 + 3*x - x^2
end

# derivative of the function
function fprime(x)
    3 - 2x
end

# elasticity of the function: marginal function divided by average function
elasticity = x -> fprime(x)/(f(x)/x)
e = elasticity.(x) # elasticities at the x values

# noisy observation of true function
y = f.(x) + randn(n)
# researcher only observes y and x

# linear fit and elasticity according to linear fit
X = [ones(n) x]
Xprime = [zeros(n) ones(n)]
b, fit, junk = lsfit(y,X)
elinear = Xprime*b./(fit./x)

# Fourier fit and elasticity
#X = [ones(n) x cos.(x) sin.(x) cos.(2x) sin.(2x)]
#Xprime = [zeros(n) ones(n) -sin.(x) cos.(x) -2sin.(2x) 2cos.(2x)]
X = [ones(n) x cos.(x) sin.(x)]
Xprime = [zeros(n) ones(n) -sin.(x) cos.(x)]
b, fourierfit, junk = lsfit(y,X)
efourier = Xprime*b./(fourierfit./x)

# plot function and fits
p1 = plot(x,[f.(x) fit fourierfit], title = "Function and fits", legend=:bottomleft, label=["true" "linear" "fourier"])

# plot true elasticities and fits
p2 = plot(x, [e elinear efourier], title = "Elasticity and fitted elasticities", legend=:bottomleft, label=["true" "linear" "fourier"])

plot(p1, p2)

max_stars_repo_name: Hiroakiyusheng/Econometrics

max_issues_repo_name: Hiroakiyusheng/Econometrics

max_forks_repo_name: Hiroakiyusheng/Econometrics


text:
# The SteinParzenARKernel is a kernel derived by Parzen in 1961,
# which arises from a second order autoregressive process. Its
# inner product is for the Sobolev space H^2([a, b]) for any
# a < b.
#
# k(x, y) = (4*alpha*gamma^2)^-1 * exp{-alpha*|x - y|} cos(w*|x-y|)
#   + (alpha / w) * sin(w*|x-y|)
#
# where w^2 = gamma^2 - alpha^2 > 0. The associated norm is
#
# |u|_H = 4*alpha*gamma^2*u(a)^2 + 4*alpha*u'(a)^2 +
#  \int_[a,b] (u''(t) + 2*alpha^2*u'(t) + gamma^2*u(t))^2

type SteinParzenARKernel <: SteinTensorizedKernel
    # the alpha parameter
    alpha::Float64
    # the gamma parameter
    gamma::Float64
end

# have default parameters of alpha = 1/sqrt(2) and gamma = 1.0
SteinParzenARKernel() = SteinParzenARKernel(1.0/sqrt(2), 1.0)

# utility to get w
function getw(ker::SteinParzenARKernel)
    sqrt(ker.gamma^2 - ker.alpha^2)
end

# utility method for wacky constant
function getc1(ker::SteinParzenARKernel)
    1.0 / (4.0 * ker.alpha * ker.gamma^2)
end

function ki(ker::SteinParzenARKernel, x::Float64, y::Float64)
    w = getw(ker)
    c = getc1(ker)
    alpha = ker.alpha

    c * exp(-alpha * abs(x-y)) * cos(w * abs(x-y)) + (alpha/w) * sin(w * abs(x-y))
end

function gradxki(ker::SteinParzenARKernel, x::Float64, y::Float64)
    w = getw(ker)
    c = getc1(ker)
    alpha = ker.alpha
    s = sign(x - y)

    -c * s * exp(-alpha * abs(x-y)) * (
        alpha * cos(w * abs(x-y)) +
        w * sin(w * abs(x-y))
    ) + alpha * s * cos(w * abs(x-y))
end

function gradxyki(ker::SteinParzenARKernel, x::Float64, y::Float64)
    w = getw(ker)
    c = getc1(ker)
    alpha = ker.alpha
    s = sign(x - y)

    -c * exp(-alpha * abs(x-y)) * (
        (alpha^2 - w^2) * cos(w * abs(x-y)) +
        2 * alpha * w * sin(w * abs(x-y))
    ) + alpha * w * sin(w * abs(x-y))
end


text:
#=
Costas array in ConstraintSolver.jl

From http://mathworld.wolfram.com/CostasArray.html:
"""
An order-n Costas array is a permutation on {1,...,n} such
that the distances in each row of the triangular difference
table are distinct. For example, the permutation {1,3,4,2,5}
has triangular difference table {2,1,-2,3}, {3,-1,1}, {1,2},
and {4}. Since each row contains no duplications, the permutation
is therefore a Costas array.
"""
Also see
http://en.wikipedia.org/wiki/Costas_array

This model is based on Barry O'Sullivan's MiniZinc model
(http://www.g12.cs.mu.oz.au/mzn/costas_array/CostasArray.mzn)
Here are the two rather simple differences
(marked by "hakank" below)
 1) no symmetry breaking on the order of the Costas array
 2) fixes the lower triangular matrix in the difference
    matrix to -n+1

Since there is no symmetry breaking of the order of the Costas
array it gives all the solutions for a specific length of
the array, e.g. those
listed in http://mathworld.wolfram.com/CostasArray.html

1	1	(1)
2	2	(1, 2), (2,1)
3	4	(1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2)
4	12	(1, 2, 4, 3), (1, 3, 4, 2), (1, 4, 2, 3), (2, 1, 3, 4),
              (2, 3, 1, 4), (2, 4, 3, 1), (3, 1, 2, 4), (3, 2, 4, 1),
              (3, 4, 2, 1), (4, 1, 3, 2), (4, 2, 1, 3), (4, 3, 1, 2)
....

See http://www.research.att.com/~njas/sequences/A008404
for the number of solutions for n=1..
1, 2, 4, 12, 40, 116, 200, 444, 760, 2160, 4368, 7852, 12828,
17252, 19612, 21104, 18276, 15096, 10240, 6464, 3536, 2052,
872, 200, 88, 56, 204,...

Model created by Hakan Kjellerstrand, hakank@gmail.com
See also my Julia page: http://www.hakank.org/julia/

=#

using ConstraintSolver, JuMP
using Cbc, GLPK, Ipopt
using Printf
const CS = ConstraintSolver
include("constraints_utils.jl")

function costas_array(n=8, print_solutions=true,all_solutions=true,timeout=6)

    cbc_optimizer = optimizer_with_attributes(Cbc.Optimizer, "logLevel" => 0)
    glpk_optimizer = optimizer_with_attributes(GLPK.Optimizer)
    ipopt_optimizer = optimizer_with_attributes(Ipopt.Optimizer)

    model = Model(optimizer_with_attributes(CS.Optimizer,   "all_solutions"=> all_solutions,
                                                            # "all_optimal_solutions"=>all_solutions,
                                                            "logging"=>[],

                                                            "traverse_strategy"=>:BFS,
                                                            # "traverse_strategy"=>:DFS,
                                                            # "traverse_strategy"=>:DBFS,

                                                            # "branch_split"=>:Smallest,
                                                            # "branch_split"=>:Biggest,
                                                            "branch_split"=>:InHalf,

                                                            # https://wikunia.github.io/ConstraintSolver.jl/stable/options/#branch_strategy-(:Auto)
                                                            "branch_strategy" => :IMPS, # default
                                                            # "branch_strategy" => :ABS, # Activity Based Search
                                                            # "activity.decay" => 0.999, # default 0.999
                                                            # "activity.max_probes" => 10, # default, 10
                                                            # "activity.max_confidence_deviation" => 20, # default 20

                                                            # "simplify"=>false,
                                                            # "simplify"=>true, # default

                                                            "time_limit"=>timeout,

                                                            # "backtrack" => false, # default true
                                                            # "backtrack_sorting" => false, # default true

                                                            # "lp_optimizer" => cbc_optimizer,
                                                            # "lp_optimizer" => glpk_optimizer,
                                                            # "lp_optimizer" => ipopt_optimizer,
                                        ))

    @variable(model, 1 <= costas[1:n] <= n, Int)
    @variable(model, -n+1 <= differences[1:n,1:n] <= n-1, Int)

    #
    # hakank: Here are my two changes
    #
    # 1) I skipped this constraint since I want
    #    to generate all solutions.
    # @constraint(model, costas[1] <= costas[N] - 1)

    # 2) Fix the values in the lower triangle in the
    # difference matrix to -n+1. This removes variants
    # of the difference matrix for the the same Costas array.
    for i in 1:n, j in 1:i
        @constraint(model, differences[i,j] == -n+1)
    end

    # hakank: All the following constraints are from
    # Barry O'Sullivans's original MiniZinc model.
    @constraint(model, costas in CS.AllDifferent())

    # "How do the positions in the Costas array relate
    #  to the elements of the distance triangle."
    for i in 1:n, j in i+1:n
       @constraint(model, differences[i,j] == costas[j] - costas[j-i])
    end

    # "All entries in a particular row of the difference
    #  triangle must be distint."
    for i in 1:n-1
       @constraint(model,[differences[i,j] for j in i+1:n] in CS.AllDifferent())
    end

    # "All the following are redundant - only here to speed up search."

    # "We can never place a 'token' in the same row as any other."
    for i in 1:n, j in i+1:n
       @constraint(model, differences[i,j] != 0)
    end

    for k in 3:n, l in k+1:n
       @constraint(model, differences[k-2,l-1] + differences[k,l] ==
                          differences[k-1,l-1] + differences[k-1,l])
    end

    # Solve the problem
    optimize!(model)

    status = JuMP.termination_status(model)
    # println("status:$status")
    num_sols = 0
    if status == MOI.OPTIMAL
        num_sols = MOI.get(model, MOI.ResultCount())
        println("num_sols:$num_sols\n")
        if print_solutions
            for sol in 1:num_sols
                println("solution #$sol")
                costas_val = convert.(Integer,JuMP.value.(costas; result=sol))
                println("costas:$costas_val")
                differences_val = convert.(Integer,JuMP.value.(differences; result=sol))
                # println("differences:$differences_val")
                for i in 1:n
                    for j in 1:n
                        d = differences_val[i,j]
                        if d > -n+1
                            @printf "%2d " d
                        else
                            print(" ")
                        end
                    end
                    println()
                end
             end
             println()
        end
    else
        println("status:$status")
    end

    return status, num_sols
end

@time costas_array(8,true,true,6)

for n in 2:10
    println("\nn:$n")
    @time costas_array(n,false,true,16)
end

max_stars_repo_name: tias/hakank

max_issues_repo_name: tias/hakank

max_forks_repo_name: tias/hakank


text:
get_alg_hints(o) = :alg_hints ∈ keys(o) ? alg_hints = o[:alg_hints] : alg_hints = Symbol[:auto]

const LOW_TOL = 1e-6
const MED_TOL = 1e-2
const EXTREME_TOL = 1e-9

function get_tolerance_level(o)
  :reltol ∈ keys(o) ? reltol = o[:reltol] : reltol = 1e-3
  if reltol > MED_TOL
    return :high_tol
  elseif reltol > LOW_TOL
    return :med_tol
  elseif reltol > EXTREME_TOL
    return :low_tol
  else
    return :extreme_tol
  end
end

function callbacks_exists(o)
  :callback ∈ keys(o) ? callback = o[:callback] : callback = nothing
  callback != nothing
end

function mass_matrix_exists(prob)
  prob.f.mass_matrix != I
end

max_stars_repo_name: ChrisRackauckas/DiffEq


text:
using ColorTypes
using ColorTypes.FixedPointNumbers
using Test
using ColorTypes: ColorTypeResolutionError

@isdefined(CustomTypes) || include("customtypes.jl")
using .CustomTypes

@testset "RGB accessors" begin

    # This also checks that the constructor order is the same, even if the
    # storage order is not (e.g. RGB vs BGR)
    Crgb = filter(T -> T <: AbstractRGB, ColorTypes.parametric3)
    @testset "accessors for $C and its transparent color" for C in Crgb
        rgb = C(1, 0.5, 0)
        @test alpha(rgb) === 1.0
        @test red(rgb)   === rgb.r === 1.0
        @test green(rgb) === rgb.g === 0.5
        @test blue(rgb)  === rgb.b === 0.0

        argb = alphacolor(C)(1, 0.5, 0, 0.8)
        rgba = coloralpha(C)(1, 0.5, 0, 0.8)

        @test alpha(argb) === argb.alpha === 0.8
        @test red(argb)   === argb.r === 1.0
        @test green(argb) === argb.g === 0.5
        @test blue(argb)  === argb.b === 0.0

        @test alpha(rgba) === rgba.alpha === 0.8
        @test red(rgba)   === rgba.r === 1.0
        @test green(rgba) === rgba.g === 0.5
        @test blue(rgba)  === rgba.b === 0.0
    end
    @testset "accessors for RGB24 and ARGB32" begin
        rgb24 = RGB24(1, 0.5, 0)
        @test alpha(rgb24) === 1.0N0f8
        @test red(rgb24)   === 1.0N0f8
        @test green(rgb24) === 0.5N0f8
        @test blue(rgb24)  === 0.0N0f8

        argb32 = ARGB32(1, 0.5, 0, 0.8)
        @test alpha(argb32) === 0.8N0f8
        @test red(argb32)   === 1.0N0f8
        @test green(argb32) === 0.5N0f8
        @test blue(argb32)  === 0.0N0f8
    end
    @testset "accessors for custom RGBA" begin
        rgba32 = CustomTypes.RGBA32(1, 0.5, 0, 0.8)
        @test red(rgba32)   === 1.0N0f8
        @test green(rgba32) === 0.5N0f8
        @test blue(rgba32)  === 0.0N0f8
        @test alpha(rgba32) === 0.8N0f8
    end

    @test_throws MethodError red(HSV(100, 0.6, 0.4))
end

@testset "alpha" begin
    @test alpha(RGB24(0.2, 0.3, 0.4)) === 1N0f8
    @test alpha(ARGB32(0.2, 0.3, 0.4, 0.8)) === 0.8N0f8
    @test alpha(HSV(100, 0.4, 0.6)) === 1.0
    @test alpha(HSV{Float16}(100, 0.4, 0.6)) === Float16(1.0)
    @test alpha(HSVA(100, 0.4, 0.6, 0.8)) === 0.8
    @test alpha(AHSV{Float32}(100, 0.4, 0.6, 0.8)) === 0.8f0
    @test alpha(0)     === N0f8(1)
    @test alpha(0.0f0) === 1.0f0
end

@testset "gray" begin
    @test gray(Gray(0.2)) === 0.2
    @test gray(GrayA(0.2, 0.8)) === 0.2
    @test gray(AGray{Float32}(0.2, 0.8)) === 0.2f0
    @test gray(Gray24(0.2)) === N0f8(0.2)
    @test gray(AGray32(0.2, 0.8)) === N0f8(0.2)
    @test gray(Gray{Bool}(1)) === true
    @test gray(Gray{Bool}(0)) === false

    @testset "gray for Real" begin
        @test gray(1)       === N0f8(1)
        @test gray(0.8)     === 0.8
        @test gray(0.8N0f8) === 0.8N0f8
        @test gray(true)    === true
        @test gray(false)   === false
        @test gray(1//2)    === 1/2   # depends on https://github.com/JuliaMath/FixedPointNumbers.jl/pull/177
    end
    @test_throws MethodError gray(HSVA(100, 0.4, 0.6, 0.8))
    @test_throws MethodError gray(Cyanotype{Float32}(0.8)) # 1-component color but not a gray
end

@testset "chroma" begin
    for C in [Lab, DIN99, DIN99o, DIN99d, Luv]
        @test chroma(C(60, -40, 30)) ≈ 50.0
    end
    @test chroma(LCHab(60, 40, 30)) ≈ 40.0
    @test chroma(LCHuv(60, 40, 30)) ≈ 40.0
    @test chroma(LabA(60, -40, 30, 0.5)) ≈ 50.0
    @test chroma(ALab(60, -40, 30, 0.5)) ≈ 50.0
    @inferred chroma(LCHab(60, 40, 30))
    @inferred chroma(LCHuv(6f1, 4f1, 3f1))
    @inferred chroma(LabA(60, -40, 30, 0.5))
    @test_throws MethodError chroma(HSV(30, 0.4, 0.6))
end

@testset "hue" begin
    @test hue(HSV(30, 0.4, 0.6)) ≈ 30.0
    @test hue(HSL(30, 0.4, 0.6)) ≈ 30.0
    @test hue(HSI(30, 0.4, 0.6)) ≈ 30.0
    for C in [Lab, DIN99, DIN99o, DIN99d, Luv]
        @test hue(C(60, -30, 30)) ≈ 135.0
    end
    @test hue(LCHab(60, 40, 30)) ≈ 30.0
    @test hue(LCHuv(60, 40, 30)) ≈ 30.0
    @test hue(LabA(60, -30, 30, 0.5)) ≈ 135.0
    @test hue(ALab(60, -30, 30, 0.5)) ≈ 135.0
    @inferred hue(LCHab(60, -30, 30))
    @inferred hue(LCHuv(6f1, -3f1, 3f1))
    @inferred hue(LabA(60, -30, 30, 0.5))
    @test hue(HSV(999, 0.4, 0.6)) == 999 # without normalization
end

@testset "compN" begin
    g = Gray{Float32}(0.5)
    @test comp1(g) === 0.5f0
    @test_throws ArgumentError comp2(g)
    @test_throws ArgumentError comp3(g)
    @test_throws ArgumentError comp4(g)
    @test_throws ArgumentError comp5(g)
    argb32 = ARGB32(1, 0.5, 0, 0.8)
    @test comp1(argb32) === 1N0f8
    @test comp2(argb32) === 0.5N0f8
    @test comp3(argb32) === 0N0f8
    @test comp4(argb32) === 0.8N0f8
    @test_throws ArgumentError comp5(argb32)
    agray32 = AGray32(0.2, 0.8)
    @test comp1(agray32) === 0.2N0f8
    @test comp2(agray32) === 0.8N0f8
    xrgb = XRGB(1, 0.5, 0)
    @test comp1(xrgb) === 1.0
    @test comp2(xrgb) === 0.5
    @test comp3(xrgb) === 0.0
    ret = @test_throws ArgumentError comp4(xrgb)
    @test occursin("3-component color XRGB{Float64} with `comp4`", ret.value.msg)
    ahsv = AHSV(100f0, 0.4f0, 0.6f0, 0.8f0)
    @test comp1(ahsv) === 100f0
    @test comp2(ahsv) === 0.4f0
    @test comp3(ahsv) === 0.6f0
    @test comp4(ahsv) === 0.8f0
    ac4 = AC4{Float32}(0.1, 0.2, 0.3, 0.4, 0.5)
    @test comp1(ac4) === 0.1f0
    @test comp2(ac4) === 0.2f0
    @test comp3(ac4) === 0.3f0
    @test comp4(ac4) === 0.4f0
    @test comp5(ac4) === 0.5f0
    ct = Cyanotype{Float32}(0.8) # 1-component color but not a gray
    @test comp1(ct) === 0.8f0
    rgba32 = CustomTypes.RGBA32(1, 0.5, 0, 0.8)
    @test comp1(rgba32) === 1N0f8
    @test comp2(rgba32) === 0.5N0f8
    @test comp3(rgba32) === 0N0f8
    @test comp4(rgba32) === 0.8N0f8
end

@testset "color" begin
    @test color(RGB(1, 0.5, 0)) === RGB{Float64}(1, 0.5, 0)
    @test color(RGBA{N0f8}(1, 0.5, 0, 0.8)) === RGB{N0f8}(1, 0.5, 0)
    @test color(ARGB{Float32}(1, 0.5, 0, 0.8)) === RGB{Float32}(1, 0.5, 0)
    @test color(RGB24(1, 0.5, 0)) === RGB24(1, 0.5, 0)
    @test color(ARGB32(1, 0.5, 0, 0.8)) === RGB24(1, 0.5, 0)

    @test color(HSV(100, 0.4, 0.6)) === HSV{Float64}(100, 0.4, 0.6)
    @test color(HSVA(100, 0.4, 0.6, 0.8)) === HSV{Float64}(100, 0.4, 0.6)
    @test color(AHSV{Float32}(100, 0.4, 0.6, 0.8)) === HSV{Float32}(100, 0.4, 0.6)

    @test color(Gray(0.2)) === Gray{Float64}(0.2)
    @test color(GrayA{N0f8}(0.2, 0.8)) === Gray{N0f8}(0.2)
    @test color(AGray{Float32}(0.2, 0.8)) === Gray{Float32}(0.2)
    @test color(Gray24(0.2)) === Gray24(0.2)
    @test color(AGray32(0.2, 0.8)) === Gray24(0.2)

    @test color(C2A{Float64}(0.1, 0.2, 0.8)) === C2{Float64}(0.1, 0.2)
    @test color(AC4{Float32}(0.1, 0.2, 0.3, 0.4, 0.8)) === C4{Float32}(0.1, 0.2, 0.3, 0.4)
end

@testset "to_top" begin
    @test ColorTypes.to_top(RGB{N0f8}) === Colorant{N0f8,3}
    @test ColorTypes.to_top(RGB24) === Colorant{N0f8,3}
    @test ColorTypes.to_top(Gray24) === Colorant{N0f8,1}
    @test ColorTypes.to_top(HSVA{Float32}) === Colorant{Float32,4}
    @test_throws MethodError ColorTypes.to_top(RGB)

    # for instances
    @test ColorTypes.to_top(RGB(1, 0.5, 0)) === Colorant{Float64,3}
    @test ColorTypes.to_top(AGray32(.8)) === Colorant{N0f8,2}
end

@testset "length" begin
    @test length(RGB) == 3
    @test length(XRGB) == 3
    @test length(ARGB) == 4
    @test length(RGB24) == 3
    @test length(ARGB32) == 4
    @test length(Gray) == 1
    @test length(Gray24) == 1
    @test length(AGray32) == 2
    @test length(AGray{Float32}) == 2

    @test length(ARGB(1.0,0.8,0.6,0.4)) == 4
end

@testset "eltype" begin
    @test @inferred(eltype(Color{N0f8})) === N0f8
    @test @inferred(eltype(RGB{Float32})) === Float32
    @test @inferred(eltype(RGBA{Float64})) === Float64
    @test @inferred(eltype(RGB24)) === N0f8
    # @test eltype(RGB) == TypeVar(:T, Fractional)
    @inferred(eltype(RGB))      # just test that it doesn't error

    # for instances
    @test @inferred(eltype(RGB{N0f8}(1,0,0))) === N0f8
    @test @inferred(eltype(RGB(0x01,0x00,0x00))) === N0f8
    @test @inferred(eltype(RGB(1.0,0,0))) === Float64
    @test @inferred(eltype(ARGB(1.0,0.8,0.6,0.4))) === Float64
    @test @inferred(eltype(RGBA{Float32}(1.0,0.8,0.6,0.4))) === Float32
    @test @inferred(eltype(RGB24(1,0.5,0))) === N0f8
    @test @inferred(eltype(ARGB32(1,0.5,0,0.8))) === N0f8

    @test @inferred(eltype(Gray(1))) === N0f8
    @test @inferred(eltype(Gray(1.0))) === Float64
    @test @inferred(eltype(Gray24(0.8))) === N0f8
    @test @inferred(eltype(AGray32(0.8))) === N0f8

    @test @inferred(eltype(HSV(30,1,0))) === Float32
    @test @inferred(eltype(HSV(30,1.0,0.0))) === Float64
end

@testset "eltype_supported/issupported" begin
    @test Fractional <: @inferred(ColorTypes.eltypes_supported(RGB))
    @test N0f8 <: @inferred(ColorTypes.eltypes_supported(RGB(1,0,0)))
    @test @inferred(ColorTypes.issupported(Gray, Bool))
    @test @inferred(!ColorTypes.issupported(AGray, Bool))

    @test @inferred(ColorTypes.eltypes_supported(C2{Float32})) === Real
    @test_broken @inferred(ColorTypes.eltypes_supported(C2A)) === Real

    @test @inferred(ColorTypes.eltypes_supported(TransparentColor)) === Any

    ST = @inferred(ColorTypes.eltypes_supported(StrangeGray{:X}))
    @test ST == (Normed{T} where T <: Integer) # This is not a "strict" result.
    @test comp1(StrangeGray{UInt16}(1N14f2)) isa ST
end

@testset "color_type" begin
    @test @inferred(color_type(RGB)) === RGB
    @test @inferred(color_type(RGBA)) === RGB
    @test @inferred(color_type(ARGB)) === RGB
    @test @inferred(color_type(RGB{N0f8})) === RGB{N0f8}
    @test @inferred(color_type(RGBA{Float32})) === RGB{Float32}
    @test @inferred(color_type(ARGB{Float64})) === RGB{Float64}
    @test @inferred(color_type(RGB24)) === RGB24
    @test @inferred(color_type(ARGB32)) === RGB24

    @test @inferred(color_type(BGR)) === BGR
    @test @inferred(color_type(XRGB)) === XRGB
    @test @inferred(color_type(RGBX)) === RGBX

    @test @inferred(color_type(Gray)) === Gray
    @test @inferred(color_type(GrayA)) == Gray{<:ColorTypes.Fractional} # FIXME
    @test @inferred(color_type(AGray)) == Gray{<:ColorTypes.Fractional} # FIXME
    @test_broken @inferred(color_type(GrayA)) === Gray
    @test_broken @inferred(color_type(AGray)) === Gray
    @test @inferred(color_type(Gray{N0f8})) === Gray{N0f8}
    @test @inferred(color_type(GrayA{Float32})) === Gray{Float32}
    @test @inferred(color_type(AGray{Float64})) === Gray{Float64}
    @test @inferred(color_type(Gray24)) === Gray24
    @test @inferred(color_type(AGray32)) === Gray24

    @test @inferred(color_type(HSV)) === HSV
    @test @inferred(color_type(HSVA)) === HSV
    @test @inferred(color_type(AHSV)) === HSV
    @test @inferred(color_type(HSV{Float16})) === HSV{Float16}
    @test @inferred(color_type(HSVA{Float32})) === HSV{Float32}
    @test @inferred(color_type(AHSV{Float64})) === HSV{Float64}

    @test @inferred(color_type(AbstractRGB)) === AbstractRGB
    @test @inferred(color_type(AbstractRGBA)) === AbstractRGB
    @test @inferred(color_type(AbstractARGB)) === AbstractRGB
    @test @inferred(color_type(AbstractRGB{N0f8})) === AbstractRGB{N0f8}
    @test @inferred(color_type(AbstractRGBA{RGB,Float32})) === RGB
    @test @inferred(color_type(AbstractARGB{RGB{Float64},Float64})) === RGB{Float64}
    @test @inferred(color_type(TransparentRGB)) === AbstractRGB

    @test @inferred(color_type(AbstractGrayA)) === AbstractGray
    @test @inferred(color_type(AbstractAGray)) === AbstractGray
    @test @inferred(color_type(TransparentGray)) === AbstractGray

    @test @inferred(color_type(Color3)) === Color3
    @test @inferred(color_type(Transparent3)) === Color3

    @test @inferred(color_type(Color)) === Color
    @test @inferred(color_type(Color{Float16})) === Color{Float16}
    @test @inferred(color_type(Color{Float16,2})) === Color{Float16,2}

    @test @inferred(color_type(AlphaColor)) === Color
    @test @inferred(color_type(AlphaColor{Gray{Float16},Float16}))   === Gray{Float16}
    @test @inferred(color_type(AlphaColor{Gray{Float16},Float16,2})) === Gray{Float16}
    @test @inferred(color_type(AlphaColor{RGB{N0f8},Float16,2}))     === RGB{N0f8} # inconsistent source

    @test @inferred(color_type(ColorAlpha)) === Color
    @test @inferred(color_type(ColorAlpha{Gray{Float16},Float16}))   === Gray{Float16}
    @test @inferred(color_type(ColorAlpha{Gray{Float16},Float16,2})) === Gray{Float16}
    @test @inferred(color_type(ColorAlpha{RGB{N0f8},Float16,2}))     === RGB{N0f8} # inconsistent source

    @test @inferred(color_type(TransparentColor)) === Color
    @test @inferred(color_type(TransparentColor{RGB})) === RGB
    @test @inferred(color_type(TransparentColor{RGB,Float64})) === RGB
    @test @inferred(color_type(TransparentColor{RGB{Float64},Float64})) === RGB{Float64}
    @test @inferred(color_type(TransparentColor{Gray,T,2} where T)) == Gray
    @test @inferred(color_type(TransparentColor{Gray{T},T,2} where T)) === Gray{T} where T

    @test @inferred(color_type(Colorant)) === Color
    @test @inferred(color_type(Colorant{N0f8})) === Color{N0f8}
    @test @inferred(color_type(Colorant{N0f8,2})) === Color{N0f8,2}
    @test @inferred(color_type(Colorant{T,2} where T)) == Color{T,2} where T

    @test @inferred(color_type(N0f8)) === Gray{N0f8}

    # for instances
    @test @inferred(color_type(RGB{N0f8}(1,0,0))) === RGB{N0f8}
    @test @inferred(color_type(ARGB(1.0,0.8,0.6,0.4))) === RGB{Float64}
    @test @inferred(color_type(RGBA{Float32}(1.0,0.8,0.6,0.4))) === RGB{Float32}
    @test @inferred(color_type(1N0f8)) === Gray{N0f8}
end

@testset "base_color_type" begin
    @test @inferred(base_color_type(RGB)) === RGB
    @test @inferred(base_color_type(RGBA)) === RGB
    @test @inferred(base_color_type(ARGB)) === RGB
    @test @inferred(base_color_type(RGB{N0f8})) === RGB
    @test @inferred(base_color_type(RGBA{Float32})) === RGB
    @test @inferred(base_color_type(ARGB{Float64})) === RGB
    @test @inferred(base_color_type(RGB24)) === RGB24
    @test @inferred(base_color_type(ARGB32)) === RGB24

    @test @inferred(base_color_type(BGR)) === BGR
    @test @inferred(base_color_type(BGR{N0f8})) === BGR
    @test @inferred(base_color_type(XRGB)) === XRGB
    @test @inferred(base_color_type(RGBX)) === RGBX

    @test @inferred(base_color_type(Gray)) === Gray
    @test @inferred(base_color_type(GrayA)) === Gray
    @test @inferred(base_color_type(AGray)) === Gray
    @test @inferred(base_color_type(Gray{N0f8})) === Gray
    @test @inferred(base_color_type(GrayA{Float32})) === Gray
    @test @inferred(base_color_type(AGray{Float64})) === Gray
    @test @inferred(base_color_type(Gray24)) === Gray24
    @test @inferred(base_color_type(AGray32)) === Gray24

    @test @inferred(base_color_type(HSV)) === HSV
    @test @inferred(base_color_type(HSVA)) === HSV
    @test @inferred(base_color_type(AHSV)) === HSV
    @test @inferred(base_color_type(HSV{Float16})) === HSV
    @test @inferred(base_color_type(HSVA{Float32})) === HSV
    @test @inferred(base_color_type(AHSV{Float64})) === HSV

    @test @inferred(base_color_type(AbstractRGB)) === AbstractRGB
    @test @inferred(base_color_type(AbstractRGBA)) === AbstractRGB
    @test @inferred(base_color_type(AbstractARGB)) === AbstractRGB
    @test @inferred(base_color_type(AbstractRGB{N0f8})) === AbstractRGB
    @test @inferred(base_color_type(AbstractRGBA{RGB,Float32})) === RGB
    @test @inferred(base_color_type(AbstractARGB{RGB{Float64},Float64})) === RGB
    @test @inferred(base_color_type(TransparentRGB)) === AbstractRGB

    @test @inferred(base_color_type(AbstractGrayA)) === AbstractGray
    @test @inferred(base_color_type(AbstractAGray)) === AbstractGray
    @test @inferred(base_color_type(TransparentGray)) === AbstractGray

    @test @inferred(base_color_type(Color3)) === Color3
    @test @inferred(base_color_type(Transparent3)) === Color3

    @test @inferred(base_color_type(Color)) === Color
    @test @inferred(base_color_type(Color{Float16})) === Color
    @test @inferred(base_color_type(Color{Float16,2})) == Color{T,2} where T

    @test @inferred(base_color_type(AlphaColor)) === Color
    @test @inferred(base_color_type(AlphaColor{Gray{Float16},Float16}))   === Gray
    @test @inferred(base_color_type(AlphaColor{Gray{Float16},Float16,2})) === Gray
    @test @inferred(base_color_type(AlphaColor{RGB{N0f8},Float16,2}))     === RGB # inconsistent source

    @test @inferred(base_color_type(ColorAlpha)) === Color
    @test @inferred(base_color_type(ColorAlpha{Gray{Float16},Float16}))   === Gray
    @test @inferred(base_color_type(ColorAlpha{Gray{Float16},Float16,2})) === Gray
    @test @inferred(base_color_type(ColorAlpha{RGB{N0f8},Float16,2}))     === RGB # inconsistent source

    @test @inferred(base_color_type(TransparentColor)) === Color
    @test @inferred(base_color_type(TransparentColor{RGB})) === RGB
    @test @inferred(base_color_type(TransparentColor{RGB,Float64})) === RGB
    @test @inferred(base_color_type(TransparentColor{RGB{Float64},Float64})) === RGB
    @test @inferred(base_color_type(TransparentColor{Gray,T,2} where T)) == Gray
    @test @inferred(base_color_type(TransparentColor{Gray{T},T,2} where T)) == Gray

    @test @inferred(base_color_type(Colorant)) === Color
    @test @inferred(base_color_type(Colorant{N0f8})) === Color
    @test @inferred(base_color_type(Colorant{N0f8,2})) == Color{T,2} where T
    @test @inferred(base_color_type(Colorant{T,2} where T)) == Color{T,2} where T

    @test @inferred(base_color_type(N0f8)) === Gray

    # for instances
    @test @inferred(base_color_type(RGB{N0f8}(1,0,0))) === RGB
    @test @inferred(base_color_type(ARGB(1.0,0.8,0.6,0.4))) === RGB
    @test @inferred(base_color_type(RGBA{Float32}(1.0,0.8,0.6,0.4))) === RGB
    @test @inferred(base_color_type(1N0f8)) === Gray
end

@testset "base_colorant_type" begin
    @test @inferred(base_colorant_type(RGB)) === RGB
    @test @inferred(base_colorant_type(RGBA)) === RGBA
    @test @inferred(base_colorant_type(ARGB)) === ARGB
    @test @inferred(base_colorant_type(RGB{N0f8})) === RGB
    @test @inferred(base_colorant_type(RGBA{Float32})) === RGBA
    @test @inferred(base_colorant_type(ARGB{Float64})) === ARGB
    @test @inferred(base_colorant_type(RGB24)) === RGB24
    @test @inferred(base_colorant_type(ARGB32)) === ARGB32

    @test @inferred(base_colorant_type(BGR)) === BGR
    @test @inferred(base_colorant_type(BGR{N0f8})) === BGR
    @test @inferred(base_colorant_type(XRGB)) === XRGB
    @test @inferred(base_colorant_type(RGBX)) === RGBX

    @test @inferred(base_colorant_type(Gray)) === Gray
    @test @inferred(base_colorant_type(GrayA)) === GrayA
    @test @inferred(base_colorant_type(AGray)) === AGray
    @test @inferred(base_colorant_type(Gray{N0f8})) === Gray
    @test @inferred(base_colorant_type(GrayA{Float32})) === GrayA
    @test @inferred(base_colorant_type(AGray{Float64})) === AGray
    @test @inferred(base_colorant_type(Gray24)) === Gray24
    @test @inferred(base_colorant_type(AGray32)) === AGray32

    @test @inferred(base_colorant_type(HSV)) === HSV
    @test @inferred(base_colorant_type(HSVA)) === HSVA
    @test @inferred(base_colorant_type(AHSV)) === AHSV
    @test @inferred(base_colorant_type(HSV{Float16})) === HSV
    @test @inferred(base_colorant_type(HSVA{Float32})) === HSVA
    @test @inferred(base_colorant_type(AHSV{Float64})) === AHSV

    @test @inferred(base_colorant_type(AbstractRGB)) === AbstractRGB
    @test @inferred(base_colorant_type(AbstractRGBA)) === ColorAlpha{C,T,4} where C<:AbstractRGB{T} where T
    @test @inferred(base_colorant_type(AbstractARGB)) === AlphaColor{C,T,4} where C<:AbstractRGB{T} where T
    @test @inferred(base_colorant_type(AbstractRGB{N0f8})) === AbstractRGB
    @test @inferred(base_colorant_type(AbstractRGBA{RGB,Float32})) === ColorAlpha{RGB{T},T,4} where T
    @test @inferred(base_colorant_type(AbstractARGB{RGB{Float64},Float64})) === AlphaColor{RGB{T},T,4} where T
    @test @inferred(base_colorant_type(TransparentRGB)) === TransparentColor{C,T,4} where C<:AbstractRGB{T} where T

    @test @inferred(base_colorant_type(AbstractGrayA)) === ColorAlpha{C,T,2} where C<:AbstractGray{T} where T
    @test @inferred(base_colorant_type(AbstractAGray)) === AlphaColor{C,T,2} where C<:AbstractGray{T} where T
    @test @inferred(base_colorant_type(TransparentGray)) === TransparentColor{C,T,2} where C<:AbstractGray{T} where T

    @test @inferred(base_colorant_type(Color3)) === Color3
    @test @inferred(base_colorant_type(Transparent3)) === TransparentColor{C,T,4} where C<:Color{T,3} where T

    @test @inferred(base_colorant_type(Color)) === Color
    @test @inferred(base_colorant_type(Color{Float16})) === Color
    @test @inferred(base_colorant_type(Color{Float16,2})) == Color{T,2} where T

    @test @inferred(base_colorant_type(AlphaColor)) === AlphaColor
    @test @inferred(base_colorant_type(AlphaColor{Gray{Float16},Float16}))   == AlphaColor{Gray{T},T} where T
    @test @inferred(base_colorant_type(AlphaColor{Gray{Float16},Float16,2})) == AlphaColor{Gray{T},T,2} where T
    @test @inferred(base_colorant_type(AlphaColor{RGB{N0f8},Float16,2}))     == AlphaColor{RGB{T},T,2} where T # inconsistent source

    @test @inferred(base_colorant_type(ColorAlpha)) === ColorAlpha
    @test @inferred(base_colorant_type(ColorAlpha{Gray{Float16},Float16}))   == ColorAlpha{Gray{T},T} where T
    @test @inferred(base_colorant_type(ColorAlpha{Gray{Float16},Float16,2})) == ColorAlpha{Gray{T},T,2} where T
    @test @inferred(base_colorant_type(ColorAlpha{RGB{N0f8},Float16,2}))     == ColorAlpha{RGB{T},T,2} where T # inconsistent source

    @test @inferred(base_colorant_type(TransparentColor)) === TransparentColor
    @test @inferred(base_colorant_type(TransparentColor{RGB})) == TransparentColor{RGB{T},T} where T
    @test @inferred(base_colorant_type(TransparentColor{RGB,Float64})) == TransparentColor{RGB{T},T} where T
    @test @inferred(base_colorant_type(TransparentColor{RGB{Float64},Float64})) == TransparentColor{RGB{T},T} where T
    @test @inferred(base_colorant_type(TransparentColor{Gray,T,2} where T)) == TransparentColor{Gray{T},T,2} where T
    @test @inferred(base_colorant_type(TransparentColor{Gray{T},T,2} where T)) == TransparentColor{Gray{T},T,2} where T

    @test @inferred(base_colorant_type(Colorant)) === Colorant
    @test @inferred(base_colorant_type(Colorant{N0f8})) === Colorant
    @test @inferred(base_colorant_type(Colorant{N0f8,2})) == Colorant{T,2} where T
    @test @inferred(base_colorant_type(Colorant{T,2} where T)) == Colorant{T,2} where T

    @test @inferred(base_colorant_type(N0f8)) === Gray

    # for instances
    @test @inferred(base_colorant_type(RGB{N0f8}(1,0,0))) === RGB
    @test @inferred(base_colorant_type(ARGB(1.0,0.8,0.6,0.4))) === ARGB
    @test @inferred(base_colorant_type(RGBA{Float32}(1.0,0.8,0.6,0.4))) === RGBA
    @test @inferred(base_colorant_type(1N0f8)) === Gray
end

@testset "floattype" begin
    @test @inferred(floattype(RGBA{Float32})) === RGBA{Float32}
    @test @inferred(floattype(BGR{N0f8})    ) === BGR{Float32}
    @test @inferred(floattype(Gray{N0f8})   ) === Gray{Float32}
    @test @inferred(floattype(Gray{Bool})   ) === Gray{Float32}
    @test @inferred(floattype(N0f8)         ) === Float32
    @test @inferred(floattype(Bool)         ) === Float32
    @test @inferred(floattype(Float32)      ) === Float32
    @test @inferred(floattype(Float64)      ) === Float64

    @test @inferred(floattype(ARGB32)) == ARGB{Float32}
    @test @inferred(floattype(AGray32)) == AGray{Float32}
    @test @inferred(floattype(RGB24)) == RGB{Float32}
    @test @inferred(floattype(Gray24)) == Gray{Float32}

    @test_throws MethodError @inferred(floattype(RGB))

    @test_throws MethodError @inferred(floattype(RGB{N0f8}(1,0,0)))
end

@testset "parametric_colorant" begin
    @test parametric_colorant(RGB{Float32}) === RGB{Float32}
    @test parametric_colorant(RGB)          === RGB
    @test parametric_colorant(BGR{Float32}) === BGR{Float32}
    @test parametric_colorant(RGB24)        === RGB{N0f8}
    @test parametric_colorant(Gray24)       === Gray{N0f8}
    @test parametric_colorant(ARGB32)       === ARGB{N0f8}
    @test parametric_colorant(AGray32)      === AGray{N0f8}
end

@testset "ccolor" begin
    @test @inferred(ccolor(Colorant, XRGB{N0f8})) === XRGB{N0f8}
    @test @inferred(ccolor(Colorant{N0f8}, RGBX{Float32})) === RGBX{N0f8}
    @test @inferred(ccolor(Colorant{N0f8,3}, BGR{N0f8})) === BGR{N0f8}

    @test_throws ColorTypeResolutionError ccolor(AbstractRGB, HSV{Float32})
    @test_throws ColorTypeResolutionError ccolor(AbstractRGB{N0f8}, HSV{Float32})
    @test @inferred(ccolor(AbstractRGB, RGB24)) === RGB24
    @test_throws ErrorException ccolor(AbstractRGB{Float32}, RGB24)

    @test @inferred(ccolor(RGB, RGB)) === RGB
    @test @inferred(ccolor(RGB, HSV)) === RGB
    @test @inferred(ccolor(Gray, Gray)) === Gray
    @test @inferred(ccolor(Gray, HSV)) === Gray

    @test @inferred(ccolor(RGB{Float32}, HSV{Float32})) === RGB{Float32}
    @test @inferred(ccolor(RGB{N0f8}, HSV{Float32})) === RGB{N0f8}
    @test @inferred(ccolor(RGB, HSV{Float32})) === RGB{Float32}

    @test @inferred(ccolor(ARGB{Float32}, HSV{Float32})) === ARGB{Float32}
    @test @inferred(ccolor(ARGB{N0f8}, HSV{Float32})) === ARGB{N0f8}
    @test @inferred(ccolor(ARGB, HSV{Float32})) === ARGB{Float32}

    @test @inferred(ccolor(RGB{Float32}, AHSV{Float32})) === RGB{Float32}
    @test @inferred(ccolor(RGB{N0f8}, AHSV{Float32})) === RGB{N0f8}
    @test @inferred(ccolor(RGB, AHSV{Float32})) === RGB{Float32}

    @test @inferred(ccolor(RGBA{Float32}, AHSV{Float32})) === RGBA{Float32}
    @test @inferred(ccolor(RGBA{N0f8}, AHSV{Float32})) === RGBA{N0f8}
    @test @inferred(ccolor(RGBA, AHSV{Float32})) === RGBA{Float32}

    @test @inferred(ccolor(HSV{Float32}, RGB{N0f8})) === HSV{Float32}
    @test @inferred(ccolor(HSV, RGB{N0f8})) === HSV{Float32}

    @test @inferred(ccolor(Gray{N0f8}, Bool)) === Gray{N0f8}
    @test @inferred(ccolor(Gray, Bool)) === Gray{Bool}
    @test @inferred(ccolor(Gray, Int)) === Gray{N0f8}
    @test @inferred(ccolor(Gray, Float32)) === Gray{Float32}

    @test @inferred(ccolor(RGB{N0f8}, Bool)) === RGB{N0f8}
    @test @inferred(ccolor(RGB, Bool)) === RGB{N0f8}
    @test @inferred(ccolor(RGB, Int)) === RGB{N0f8}
    @test @inferred(ccolor(RGB, Float32)) === RGB{Float32}

    @test_throws ColorTypeResolutionError ccolor(HSV, Int)

    @test @inferred(ccolor(RGB24, HSV{Float32})) === RGB24
    @test @inferred(ccolor(ARGB32, HSV{Float32})) === ARGB32
    @test @inferred(ccolor(Gray24, HSV{Float32})) === Gray24
    @test @inferred(ccolor(AGray32, HSV{Float32})) === AGray32

    @test @inferred(ccolor(RGB{N0f8}, RGB24)) === RGB{N0f8}
    @test @inferred(ccolor(ARGB{N0f8}, ARGB32)) === ARGB{N0f8}
    @test @inferred(ccolor(Gray{N0f8}, Gray24)) === Gray{N0f8}
    @test @inferred(ccolor(AGray{N0f8}, AGray32)) === AGray{N0f8}

    @test @inferred(ccolor(TransparentColor, AHSV{Float32})) === AHSV{Float32}

    # Ambiguous storage order, choose AlphaColor or ColorAlpha
    @test_throws ColorTypeResolutionError ccolor(TransparentColor, HSV{Float32})
    @test_throws ColorTypeResolutionError ccolor(TransparentColor{RGB}, HSV{Float32})
    @test_throws ColorTypeResolutionError ccolor(TransparentColor{RGB,Float64}, HSV{Float32})
    @test_throws ColorTypeResolutionError ccolor(TransparentColor{RGB{Float64},Float64}, HSV{Float32})
    @test_throws ColorTypeResolutionError ccolor(TransparentColor{RGB{Float64},Float64,4}, HSV{Float32})

    @test @inferred(ccolor(AlphaColor, RGB)) === ARGB
    @test @inferred(ccolor(AlphaColor, RGB{N0f8})) === ARGB{N0f8}
    @test @inferred(ccolor(AlphaColor, RGB24)) === ARGB32
    @test @inferred(ccolor(AbstractARGB, RGB)) === ARGB
    @test @inferred(ccolor(AbstractARGB, RGB{N0f8})) === ARGB{N0f8}
    @test @inferred(ccolor(AbstractARGB, RGB24)) === ARGB32

    for C in filter(T -> T <: AbstractRGB, ColorTypes.parametric3)
        @test @inferred(ccolor(RGB24, C)) === RGB24
        @test @inferred(ccolor(ARGB32, C)) === ARGB32
        @test @inferred(ccolor(Gray24, C)) === Gray24
        @test @inferred(ccolor(AGray32, C)) === AGray32
    end

    @test_throws MethodError ccolor(RGB, RGB{N0f8}(1,0,0))
end

@testset "isfinite/isinf/isnan" begin
    cfff = RGB(1, 0, 0)
    @test isfinite(cfff) && !isinf(cfff) && !isnan(cfff)
    cfffn = ARGB(1, 0, 0, NaN32)
    @test !isfinite(cfffn) && !isinf(cfffn) && isnan(cfffn)
    cffif = HSVA(10, 0, Inf16, 0)
    @test !isfinite(cffif) && isinf(cffif) && !isnan(cffif)
    cni = GrayA(NaN, Inf)
    @test !isfinite(cni) && isinf(cni) && isnan(cni)
end

@testset "nan" begin
    @test ColorTypes.nan(Float32) === NaN32
    @test ColorTypes.nan(Gray{Float32}) === Gray{Float32}(NaN32)
    @test ColorTypes.nan(AGray{Float64}) === AGray{Float64}(NaN, NaN)
    @test ColorTypes.nan(GrayA{Float16}) === GrayA{Float16}(NaN16, NaN16)
    @test ColorTypes.nan(RGB{Float32}) === RGB{Float32}(NaN32, NaN32, NaN32)
    @test ColorTypes.nan(ARGB{Float64}) === ARGB{Float64}(NaN, NaN, NaN, NaN)
    @test ColorTypes.nan(RGBA{Float16}) === RGBA{Float16}(NaN16, NaN16, NaN16, NaN16)
    @test ColorTypes.nan(HSV{Float32}) === HSV{Float32}(NaN32, NaN32, NaN32)
    @test ColorTypes.nan(ALab{Float64}) === ALab{Float64}(NaN, NaN, NaN, NaN)
    @test ColorTypes.nan(LuvA{Float16}) === LuvA{Float16}(NaN16, NaN16, NaN16, NaN16)

    @test_throws MethodError ColorTypes.nan(RGB)
    @test_throws MethodError ColorTypes.nan(ARGB32)
    @test_throws MethodError ColorTypes.nan(Gray(1.0))
end

# see also ones/zeros test in "test/operations.jl"
@testset "identities for Gray" begin
    @test one(    Gray{N0f8}) === 1N0f8
    @test oneunit(Gray{N0f8}) === Gray{N0f8}(1)
    @test zero(   Gray{N0f8}) === Gray{N0f8}(0)
    @test @inferred(one(    Gray)) === 1N0f8
    @test @inferred(oneunit(Gray)) === Gray{N0f8}(1)
    @test @inferred(zero(   Gray)) === Gray{N0f8}(0)
    @test one(    Gray{Bool}) === true
    @test oneunit(Gray{Bool}) === Gray{Bool}(1)
    @test zero(   Gray{Bool}) === Gray{Bool}(0)

    @test one(    AGray{N0f8}) === 1N0f8
    @test oneunit(AGray{N0f8}) === AGray{N0f8}(1, 1)
    @test zero(   AGray{N0f8}) === AGray{N0f8}(0, 0)
    @test @inferred(one(    AGray)) === 1N0f8
    @test @inferred(oneunit(AGray)) === AGray{N0f8}(1, 1)
    @test @inferred(zero(   AGray)) === AGray{N0f8}(0, 0)
    @test one(    GrayA{Float32}) === 1.0f0
    @test oneunit(GrayA{Float32}) === GrayA{Float32}(1, 1)
    @test zero(   GrayA{Float32}) === GrayA{Float32}(0, 0)

    @test one(    Gray24) === 1N0f8
    @test oneunit(Gray24) === Gray24(1)
    @test zero(   Gray24) === Gray24(0)
    @test one(   AGray32) === 1N0f8
    @test oneunit(AGray32) === AGray32(1, 1)
    @test zero(   AGray32) === AGray32(0, 0)

    g = Gray{Float32}(0.8)
    @test one(    g) === 1.0f0
    @test oneunit(g) === Gray{Float32}(1)
    @test zero(   g) === Gray{Float32}(0)

    @test_broken one(Gray{Float32}) * g == g * one(Gray{Float32}) == g
end

@testset "identities for RGB" begin
    @test one(    RGB{N0f8}) === 1N0f8
    @test oneunit(RGB{N0f8}) === RGB{N0f8}(1, 1, 1)
    @test zero(   RGB{N0f8}) === RGB{N0f8}(0, 0, 0)
    @test @inferred(one(    RGB)) === 1N0f8
    @test @inferred(oneunit(RGB)) === RGB{N0f8}(1, 1, 1)
    @test @inferred(zero(   RGB)) === RGB{N0f8}(0, 0, 0)

    @test one(    ARGB{N0f8}) === 1N0f8
    @test oneunit(ARGB{N0f8}) === ARGB{N0f8}(1, 1, 1, 1)
    @test zero(   ARGB{N0f8}) === ARGB{N0f8}(0, 0, 0, 0)
    @test @inferred(one(    ARGB)) === 1N0f8
    @test @inferred(oneunit(ARGB)) === ARGB{N0f8}(1, 1, 1, 1)
    @test @inferred(zero(   ARGB)) === ARGB{N0f8}(0, 0, 0, 0)
    @test one(    RGBA{Float32}) === 1.0f0
    @test oneunit(RGBA{Float32}) === RGBA{Float32}(1, 1, 1, 1)
    @test zero(   RGBA{Float32}) === RGBA{Float32}(0, 0, 0, 0)

    @test one(    RGB24) === 1N0f8
    @test oneunit(RGB24) === RGB24(1, 1, 1)
    @test zero(   RGB24) === RGB24(0, 0, 0)
    @test one(    ARGB32) === 1N0f8
    @test oneunit(ARGB32) === ARGB32(1, 1, 1, 1)
    @test zero(   ARGB32) === ARGB32(0, 0, 0, 0)

    c = RGB{Float32}(0.4, 0.5, 0.6)
    @test one(    c) === 1.0f0
    @test oneunit(c) === RGB{Float32}(1, 1, 1)
    @test zero(   c) === RGB{Float32}(0, 0, 0)
end

@testset "identities for other colors" begin
    @test one(    XYZ{Float16}) === Float16(1)
    @test oneunit(XYZ{Float16}) === XYZ{Float16}(1, 1, 1)
    @test zero(   XYZ{Float16}) === XYZ{Float16}(0, 0, 0)

    @test @inferred(one(    LMS)) === 1.0f0
    @test @inferred(oneunit(LMS)) === LMS{Float32}(1, 1, 1)
    @test @inferred(zero(   LMS)) === LMS{Float32}(0, 0, 0)

    @test one( HSV{Float32}) === 1.0f0
    @test_throws ArgumentError oneunit(HSV{Float32})
    @test zero(HSV{Float32}) === HSV{Float32}(0, 0, 0)

    @test one( ALab{Float16}) === Float16(1)
    @test_throws ArgumentError oneunit(ALab{Float16})
    @test zero(ALab{Float16}) === ALab{Float16}(0, 0, 0, 0)

    @test one( LCHuvA{Float64}) === 1.0
    @test_throws ArgumentError oneunit(LCHuvA{Float64})
    @test zero(LCHuvA{Float64}) === LCHuvA{Float64}(0, 0, 0, 0)

    @test one( C2{Float64}) === 1.0
    @test_throws ArgumentError oneunit(C2{Float64})
    @test zero(C2{Float64}) === C2{Float64}(0, 0)

    @test one( C4{Float64}) === 1.0
    @test_throws ArgumentError oneunit(C4{Float64})
    @test zero(C4{Float64}) === C4{Float64}(0, 0, 0, 0)

    @test one(    CMYK{N0f8}) === 1N0f8
    @test oneunit(CMYK{N0f8}) === CMYK{N0f8}(1, 1, 1, 1)
    @test zero(   CMYK{N0f8}) === CMYK{N0f8}(0, 0, 0, 0)

    @test one(    ACMYK{N0f8}) === 1N0f8
    @test oneunit(ACMYK{N0f8}) === ACMYK{N0f8}(1, 1, 1, 1, 1)
    @test zero(   ACMYK{N0f8}) === ACMYK{N0f8}(0, 0, 0, 0, 0)
end


text:
push!(LOAD_PATH, pwd()*"/../../src/")
using Distributions
using DataFrames
using StatsFuns.logistic
using BVB

"""
evaluate ll for logistic regression, for a single β vector.
* y: vector of +1/-1
* λ: prior on β is N(β|0, 1/λ I)
"""
@inline function ll_logistic(β::Vector{Float64}, y::Vector{Float64}, X::Matrix{Float64}; λ=0.)
    return sum(log.(logistic.(y .* (X * β)))) - 0.5 * λ * sum(β.^2)
end

"matrix version for each column of β, return a vector"
@inline function ll_logistic(β::Matrix{Float64}, y::Vector{Float64}, X::Matrix{Float64}; λ=0.)
    return Vector{Float64}([ll_logistic(β[:,i], y, X, λ=λ) for i in 1:size(β, 2)])
end

"factory producing mini-batch ll"
function ll_logistic_factory(batch_size::Int, y::Vector{Float64}, X::Matrix{Float64}; λ=0.)
    N = length(y)
    @assert N == size(X, 1)
    @assert batch_size <= N
    idx = rand(1:N, batch_size)
    # must copy! otherwise too slow!
    _y = copy(y[idx])
    _X = copy(X[idx, :])
    @inline function _ll(β::Union{Vector{Float64}, Matrix{Float64}})
        return ll_logistic(β, _y, _X, λ=λ) ./ batch_size .* N
    end
    return _ll
end

"logistic prediction: +1/-1"
@inline function predict_logistic{T <: Real}(β::Vector{T}, X::Matrix{T})
    y = ones(size(X, 1))
    y[predict_prob_logistic(β, X) .< 0.5] = -1.
    return y
end

"logistic prediction: column-wise for matrix β"
@inline function predict_logistic{T <: Real}(β::Matrix{T}, X::Matrix{T})
    return hcat([predict_logistic(β[:,i], X) for i in size(β, 2)] ...)
end

"logistic prob prediction: prob of +1"
@inline function predict_prob_logistic{T <: Real}(β::Vector{T}, X::Matrix{T})
    return logistic.(X * β)
end

"logistic prob prediction: column-wise for matrix β"
@inline function predict_prob_logistic{T <: Real}(β::Matrix{T}, X::Matrix{T})
    return hcat([predict_prob_logistic(β[:,i], X) for i in size(β, 2)] ...)
end

"logistic prediction: Bayesian model averaging"
@inline function predict_logistic_BMA{T <: Real}(β::Matrix{T}, X::Matrix{T})
    y = ones(size(X, 1))
    P = predict_prob_logistic(β, X)
    for i in 1:length(y)
        if mean(P[i, :]) < 0.5
            y[i] = -1.
        end
    end
    return y
end

max_stars_repo_name: richardkwo/boosting-VB

max_issues_repo_name: richardkwo/boosting-VB

max_forks_repo_name: richardkwo/boosting-VB


text:
@doc raw"""
    Grassmann{n,k,𝔽} <: Manifold

The Grassmann manifold $\operatorname{Gr}(n,k)$ consists of all subspaces spanned by $k$ linear independent
vectors $𝔽^n$, where $𝔽  ∈ \{ℝ, ℂ\}$ is either the real- (or complex-) valued vectors.
This yields all $k$-dimensional subspaces of $ℝ^n$ for the real-valued case and all $2k$-dimensional subspaces
of $ℂ^n$ for the second.

The manifold can be represented as

````math
\operatorname{Gr}(n,k) := \bigl\{ \operatorname{span}(p) : p ∈ 𝔽^{n × k}, p^\mathrm{H}p = I_k\},
````

where $\cdot^{\mathrm{H}}$ denotes the complex conjugate transpose or Hermitian and
$I_k$ is the $k × k$ identity matrix. This means, that the columns of $p$
form an unitary basis of the subspace, that is a point on
$\operatorname{Gr}(n,k)$, and hence the subspace can actually be represented by
a whole equivalence class of representers.
Another interpretation is, that

````math
\operatorname{Gr}(n,k) = \operatorname{St}(n,k) / \operatorname{O}(k),
````

i.e the Grassmann manifold is the quotient of the [`Stiefel`](@ref) manifold and
the orthogonal group $\operatorname{O}(k)$ of orthogonal $k × k$ matrices.

The tangent space at a point (subspace) $x$ is given by

````math
T_x\mathrm{Gr}(n,k) = \bigl\{
X ∈ 𝔽^{n × k} :
X^{\mathrm{H}}p + p^{\mathrm{H}}X = 0_{k} \bigr\},
````

where $0_{k}$ denotes the $k × k$ zero matrix.

Note that a point $p ∈ \operatorname{Gr}(n,k)$ might be represented by
different matrices (i.e. matrices with unitary column vectors that span
the same subspace). Different representations of $p$ also lead to different
representation matrices for the tangent space $T_p\mathrm{Gr}(n,k)$

The manifold is named after
[Hermann G. Graßmann](https://en.wikipedia.org/wiki/Hermann_Grassmann) (1809-1877).

# Constructor

    Grassmann(n,k,field=ℝ)

Generate the Grassmann manifold $\operatorname{Gr}(n,k)$, where the real-valued
case $field = ℝ$ is the default.
"""
struct Grassmann{n,k,𝔽} <: AbstractEmbeddedManifold{DefaultIsometricEmbeddingType} end

Grassmann(n::Int, k::Int, field::AbstractNumbers = ℝ) = Grassmann{n,k,field}()

function allocation_promotion_function(
    M::Grassmann{n,k,ℂ},
    f,
    args::Tuple,
) where {n,k}
    return complex
end

@doc raw"""
    check_manifold_point(M::Grassmann{n,k,𝔽}, p)

Check whether `p` is representing a point on the [`Grassmann`](@ref) `M`, i.e. its
a `n`-by-`k` matrix of unitary column vectors and of correct `eltype` with respect to `𝔽`.
"""
function check_manifold_point(M::Grassmann{n,k,𝔽}, p; kwargs...) where {n,k,𝔽}
    mpv = invoke(check_manifold_point, Tuple{supertype(typeof(M)), typeof(p)}, M, p; kwargs...)
    mpv === nothing || return mpv
    c = p' * p
    if !isapprox(c, one(c); kwargs...)
        return DomainError(
            norm(c - one(c)),
            "The point $(p) does not lie on $(M), because x'x is not the unit matrix.",
        )
    end
end

@doc raw"""
    check_tangent_vector(M::Grassmann{n,k,𝔽}, p, X; check_base_point = true, kwargs...)

Check whether `X` is a tangent vector in the tangent space of `p` on
the [`Grassmann`](@ref) `M`, i.e. that `X` is of size and type as well as that

````math
    p^{\mathrm{H}}X + X^{\mathrm{H}}p = 0_k,
````

where $\cdot^{\mathrm{H}}$ denotes the complex conjugate transpose or Hermitian and $0_k$
denotes the $k × k$ zero natrix.
The optional parameter `check_base_point` indicates, whether to call [`check_manifold_point`](@ref)  for `p`.
"""
function check_tangent_vector(M::Grassmann{n,k,𝔽}, p, X; check_base_point = true, kwargs...) where {n,k,𝔽}
    if check_base_point
        mpe = check_manifold_point(M, p; kwargs...)
        mpe === nothing || return mpe
    end
    mpv = invoke(
        check_tangent_vector,
        Tuple{supertype(typeof(M)), typeof(p), typeof(X)},
        M,
        p,
        X;
        check_base_point = false, # already checked above
        kwargs...
    )
    mpv === nothing || return mpv
    if !isapprox(p' * X + X' * p, zeros(k, k); kwargs...)
        return DomainError(
            norm(p' * X + X' * p),
            "The matrix $(X) does not lie in the tangent space of $(p) on $(M), since p'X + X'p is not the zero matrix.",
        )
    end
end

decorated_manifold(M::Grassmann{N,K,𝔽}) where {N,K,𝔽} = Euclidean(N, K; field = 𝔽)

@doc raw"""
    distance(M::Grassmann, p, q)

Compute the Riemannian distance on [`Grassmann`](@ref) manifold `M`$= \mathrm{Gr}(n,k)$.

Let $USV = p^\mathrm{H}q$ denote the SVD decomposition of
$p^\mathrm{H}q$, where $\cdot^{\mathrm{H}}$ denotes the complex
conjugate transposed or Hermitian. Then the distance is given by
````math
d_{\mathrm{Gr}(n,k)}(p,q) = \operatorname{norm}(\operatorname{Re}(b)).
````
where

````math
b_{i}=\begin{cases}
0 & \text{if} \; S_i ≥ 1\\
\arccos(S_i) & \, \text{if} \; S_i<1.
\end{cases}
````
"""
function distance(M::Grassmann, p, q)
    p ≈ q && return zero(real(eltype(p)))
    a = svd(p' * q).S
    a[a.>1] .= 1
    return sqrt(sum((acos.(a)) .^ 2))
end

embed!(::Grassmann, q, p) = (q .= p)

embed!(::Grassmann, Y, p, X) = (Y .= X)

@doc raw"""
    exp(M::Grassmann, p, X)

Compute the exponential map on the [`Grassmann`](@ref) `M`$= \mathrm{Gr}(n,k)$ starting in
`p` with tangent vector (direction) `X`. Let $X = USV$ denote the SVD decomposition of $X$.
Then the exponential map is written using

````math
z = p V\cos(S)V^\mathrm{H} + U\sin(S)V^\mathrm{H},
````

where $\cdot^{\mathrm{H}}$ denotes the complex conjugate transposed or Hermitian and the
cosine and sine are applied element wise to the diagonal entries of $S$. A final QR
decomposition $z=QR$ is performed for numerical stability reasons, yielding the result as

````math
\exp_p X = Q.
````
"""
exp(::Grassmann, ::Any...)

function exp!(M::Grassmann, q, p, X)
    norm(M, p, X) ≈ 0 && return copyto!(q, p)
    d = svd(X)
    z = p * d.V * Diagonal(cos.(d.S)) * d.Vt + d.U * Diagonal(sin.(d.S)) * d.Vt
    return copyto!(q, Array(qr(z).Q))
end

@doc raw"""
    injectivity_radius(M::Grassmann)
    injectivity_radius(M::Grassmann, p)

Return the injectivity radius on the [`Grassmann`](@ref) `M`, which is $\frac{π}{2}$.
"""
injectivity_radius(::Grassmann) = π / 2
injectivity_radius(::Grassmann, ::ExponentialRetraction) = π / 2
injectivity_radius(::Grassmann, ::Any) = π / 2
injectivity_radius(::Grassmann, ::Any, ::ExponentialRetraction) = π / 2
eval(quote
    @invoke_maker 1 Manifold injectivity_radius(M::Grassmann, rm::AbstractRetractionMethod)
end)

@doc raw"""
    inner(M::Grassmann, p, X, Y)

Compute the inner product for two tangent vectors `X`, `Y` from the tangent space
of `p` on the [`Grassmann`](@ref) manifold `M`. The formula reads

````math
g_p(X,Y) = \operatorname{tr}(X^{\mathrm{H}}Y),
````

where $\cdot^{\mathrm{H}}$ denotes the complex conjugate transposed or Hermitian.
"""
inner(::Grassmann, p, X, Y) = dot(X, Y)

@doc raw"""
    inverse_retract(M::Grassmann, p, q, ::PolarInverseRetraction)

Compute the inverse retraction for the [`PolarRetraction`](@ref), on the
[`Grassmann`](@ref) manifold `M`, i.e.,

````math
\operatorname{retr}_p^{-1}q = q*(p^\mathrm{H}q)^{-1} - p,
````

where $\cdot^{\mathrm{H}}$ denotes the complex conjugate transposed or Hermitian.
"""
inverse_retract(::Grassmann, ::Any, ::Any, ::PolarInverseRetraction)

function inverse_retract!(::Grassmann, X, p, q, ::PolarInverseRetraction)
    return copyto!(X, q / (p' * q) - p)
end

@doc raw"""
    inverse_retract(M, p, q, ::QRInverseRetraction)

Compute the inverse retraction for the [`QRRetraction`](@ref), on the
[`Grassmann`](@ref) manifold `M`, i.e.,

````math
\operatorname{retr}_p^{-1}q = q(p^\mathrm{H}q)^{-1} - p,
````
where $\cdot^{\mathrm{H}}$ denotes the complex conjugate transposed or Hermitian.
"""
inverse_retract(::Grassmann, ::Any, ::Any, ::QRInverseRetraction)

inverse_retract!(::Grassmann, X, p, q, ::QRInverseRetraction) = copyto!(X, q / (p' * q) - p)

function isapprox(M::Grassmann, p, X, Y; kwargs...)
    return isapprox(sqrt(inner(M, p, zero_tangent_vector(M, p), X - Y)), 0; kwargs...)
end
isapprox(M::Grassmann, p, q; kwargs...) = isapprox(distance(M, p, q), 0.0; kwargs...)

@doc raw"""
    log(M::Grassmann, p, q)

Compute the logarithmic map on the [`Grassmann`](@ref) `M`$ = \mathcal M=\mathrm{Gr}(n,k)$,
i.e. the tangent vector `X` whose corresponding [`geodesic`](@ref) starting from `p`
reaches `q` after time 1 on `M`. The formula reads

````math
\log_p q = V\cdot \operatorname{atan}(S) \cdot U^\mathrm{H},
````

where $\cdot^{\mathrm{H}}$ denotes the complex conjugate transposed or Hermitian.
The matrices $U$ and $V$ are the unitary matrices, and $S$ is the diagonal matrix
containing the singular values of the SVD-decomposition

````math
USV = (q^\mathrm{H}p)^{-1} ( q^\mathrm{H} - q^\mathrm{H}pp^\mathrm{H}).
````

In this formula the $\operatorname{atan}$ is meant elementwise.
"""
log(::Grassmann, ::Any...)

function log!(M::Grassmann, X, p, q)
    z = q' * p
    At = q' - z * p'
    Bt = z \ At
    d = svd(Bt')
    return copyto!(X, d.U * Diagonal(atan.(d.S)) * d.Vt)
end

@doc raw"""
    manifold_dimension(M::Grassmann)

Return the dimension of the [`Grassmann(n,k,𝔽)`](@ref) manifold `M`, i.e.

````math
\dim \operatorname{Gr}(n,k) = k(n-k) \dim_ℝ 𝔽,
````

where $\dim_ℝ 𝔽$ is the [`real_dimension`](@ref) of `𝔽`.
"""
manifold_dimension(::Grassmann{n,k,𝔽}) where {n,k,𝔽} = k * (n - k) * real_dimension(𝔽)

"""
    mean(
        M::Grassmann,
        x::AbstractVector,
        [w::AbstractWeights,]
        method = GeodesicInterpolationWithinRadius(π/4);
        kwargs...,
    )

Compute the Riemannian [`mean`](@ref mean(M::Manifold, args...)) of `x` using
[`GeodesicInterpolationWithinRadius`](@ref).
"""
mean(::Grassmann{n,k} where {n,k}, ::Any...)

function mean!(
    M::Grassmann{n,k},
    p,
    x::AbstractVector,
    w::AbstractVector;
    kwargs...,
) where {n,k}
    return mean!(M, p, x, w, GeodesicInterpolationWithinRadius(π / 4); kwargs...)
end

@doc raw"""
    project(M::Grassmann, p, X)

Project the `n`-by-`k` `X` onto the tangent space of `p` on the [`Grassmann`](@ref) `M`,
which is computed by

````math
\operatorname{proj_p}(X) = X - pp^{\mathrm{H}}X,
````

where $\cdot^{\mathrm{H}}$ denotes the complex conjugate transposed or Hermitian.
"""
project(::Grassmann, ::Any...)

project!(M::Grassmann, v, x, w) = copyto!(v, w - x * x' * w)

@doc raw"""
    representation_size(M::Grassmann{n,k})

Return the represenation size or matrix dimension of a point on the [`Grassmann`](@ref)
`M`, i.e. $(n,k)$ for both the real-valued and the complex value case.
"""
@generated representation_size(::Grassmann{n,k}) where {n,k} = (n, k)

@doc raw"""
    retract(M::Grassmann, p, X, ::PolarRetraction)

Compute the SVD-based retraction [`PolarRetraction`](@ref) on the
[`Grassmann`](@ref) `M`. With $USV = p + X$ the retraction reads
````math
\operatorname{retr}_p X = UV^\mathrm{H},
````

where $\cdot^{\mathrm{H}}$ denotes the complex conjugate transposed or Hermitian.
"""
retract(::Grassmann, ::Any, ::Any, ::PolarRetraction)

@doc raw"""
    retract(M::Grassmann, p, X, ::QRRetraction )

Compute the QR-based retraction [`QRRetraction`](@ref) on the
[`Grassmann`](@ref) `M`. With $QR = p + X$ the retraction reads
````math
\operatorname{retr}_p X = QD,
````
where D is a $m × n$ matrix with
````math
D = \operatorname{diag}( \operatorname{sgn}(R_{ii}+0,5)_{i=1}^n ).
````
"""
retract(::Grassmann, ::Any, ::Any, ::QRRetraction)

function retract!(::Grassmann, q, p, X, ::PolarRetraction)
    s = svd(p + X)
    return mul!(q, s.U, s.Vt)
end
function retract!(::Grassmann{N,K}, q, p, X, ::QRRetraction) where {N,K}
    qrfac = qr(p + X)
    d = diag(qrfac.R)
    D = Diagonal(sign.(sign.(d .+ 0.5)))
    q .= zeros(N, K)
    q[1:K, 1:K] .= D
    return copyto!(q, Array(qrfac.Q) * D)
end

show(io::IO, ::Grassmann{n,k,𝔽}) where {n,k,𝔽} = print(io, "Grassmann($(n), $(k), $(𝔽))")

@doc raw"""
    zero_tangent_vector(M::Grassmann, p)

Return the zero tangent vector from the tangent space at `p` on the [`Grassmann`](@ref) `M`,
which is given by a zero matrix the same size as `p`.
"""
zero_tangent_vector(::Grassmann, ::Any...)

zero_tangent_vector!(::Grassmann, X, p) = fill!(X, 0)


text:
"""
## mesh_size

Function mesh_size returns the number of fin_els (nels) and the number
of nodes (nn) in a 1, 2 or 3-d geometry-created mesh.

### Method
```julia
(nels, nn) = mesh_size(fin_el, nxe, [nye[, nze]])
```

### Arguments
```julia
* fin_el::FiniteElement   : Shape of finite element
                            1D: Line
                            2D: Trangle or Quadrilateral
                            3D: Hexahedron
* nxe::Int              : Number of fin_els in x direction
* nye::Int              : Number of fin_els in y direction (for 2D and 3D)
* nze::Int              : Number of fin_els in z direction (3D only)
```
"""
function mesh_size(fe::Line, nxe::Int)
  nn=nxe+1; nels=nxe
  if fe.nod != 2
    println("Invalid number of nodes for Line fin_el.")
  end
  (nels, nn)
end

"""
# mesh_size

mesh_size: The function mesh_size returns the number of fin_els (nels) and the number
of nodes (nn) in a 2-d geometry-created mesh.

### Method
```julia
(nels, nn) = mesh_size(fin_el, nxe)
```
### Arguments
```julia
* `fin_el` : Shape of 2D finite element (Triangle)
* `nxe` : Number of fin_els in x direction
* `nxe` : Number of fin_els in y direction
```
"""
function mesh_size(fe::Triangle, nxe::Int, nye::Int)
  nn=0; nels=nxe*nye*2
  if fe.nod==3
    nn=(nxe+1)*(nye+1)
  elseif fe.nod==6
    nn=(2*nxe+1)*(2*nye+1)
  elseif fe.nod==10
    nn=(3*nxe+1)*(3*nye+1)
  elseif fe.nod==15
    nn=(4*nxe+1)*(4*nye+1)
  else
    println("Invalid number of nodes for Triangle fin_el.")
  end
  (nels, nn)
end

"""
# mesh_size

mesh_size: The function mesh_size returns the number of fin_els (nels) and the number
of nodes (nn) in a 2-d geometry-created mesh.

### Method
```julia
(nels, nn) = mesh_size(fin_el, nxe, nye)
```
### Arguments
```julia
* `fin_el` : Shape of 2D finite element (Quadrilateral)
* `nxe` : Number of fin_els in x direction
* `nye` : Number of fin_els in y direction
```
"""
function mesh_size(fe::Quadrilateral, nxe::Int, nye::Int)
  nn=0; nels=nxe*nye
  if fe.nod==4
    nn=(nxe+1)*(nye+1)
  elseif fe.nod==5
    nn=(nxe+1)*(nye+1)+nxe*nye
  elseif fe.nod==8
    nn=(2*nxe+1)*(nye+1)+(nxe+1)*nye
  elseif fe.nod==9
    nn=(2*nxe+1)*(2*nye+1)
  else
    println("Invalid number of nodes for Quadrilateral fin_el.")
  end
  (nels, nn)
end

"""
# mesh_size

mesh_size: The function mesh_size returns the number of fin_els (nels) and the number
of nodes (nn) in a 3-d geometry-created mesh.

### Method
```julia
(nels, nn) = mesh_size(fin_el, nxe, nye, nze)
```
### Arguments
```julia
* `fin_el` : Shape of 2D finite element (Hexahedron)
* `nxe` : Number of fin_els in x direction
* `nye` : Number of fin_els in y direction
* `nxe` : Number of fin_els in x direction
```
"""
function mesh_size(fe::Hexahedron, nxe::Int, nye::Int, nze::Int)
  nn=0; nels=nxe*nye*nze
  if fe.nod==8
    nn=(nxe+1)*(nye+1)*(nze+1)
  elseif fe.nod==14
    nn=4*nxe*nye*nze+2*(nxe*nye+nye*nze+nze*nxe)+nxe+nye+nze+1
  elseif fe.nod==20
    nn=((2*nxe+1)*(nze+1)+(nxe+1)*nze)*(nye+1)+(nxe+1)*(nze+1)*nye
  else
    println("Invalid number of nodes for Hexahedron fin_el.")
  end
  (nels, nn)
end


text:
#!/usr/bin/env julia
# vim:set ft=julia ts=4 sw=4 sts=4 autoindent:

# Sanity checking for the dependency graph module.
#
# Author:   Pontus Stenetorp    <pontus stenetorp se>
# Version:  2014-05-07

include("../hdr.jl")

require("conllx.jl")
require("dep.jl")

using CoNLLX
using DepGraph

# Coding/Decoding.
let
    coder = Coder()
    str = "foo"
    @test isequal(decode(encode(str, coder), coder), str)
end

# Sentence to dependency graph conversion.
open(debugpath, "r") do debug_f
    coder = Coder()
    for sent in conllxparse(debug_f)
        dgraph(sent, coder)
    end
end

# Equality checks.
let
    a = Vertex(1, 2, 3, NOHEAD, NOVAL)
    b = Vertex(4, 5, 6, NOHEAD, NOVAL)
    @test !isequal(a, b)
end

# Sentence to dependency graph conversion.
open(debugpath, "r") do debug_f
    coder = Coder()
    sents = collect(Sentence, conllxparse(debug_f))
    sent = sents[1]

    let
        g = dgraph(sent, coder)
        @test !isempty(g[1].rdependents)
    end
    let
        g = dgraph(sent, coder, blind=true)
        root = g[1]
        @test isempty(g[1].rdependents)
    end
end

# Adding and removing edges.
open(debugpath, "r") do debug_f
    coder = Coder()
    sents = collect(Sentence, conllxparse(debug_f, blind=true))
    sent = sents[1]

    graph = dgraph(sent, coder, blind=true)
    head = graph[1]
    dep = graph[3]
    headbefore = deepcopy(head)
    depbefore = deepcopy(dep)

    edge!(graph, dep, head)
    @test !isequal(head, headbefore)
    @test !isequal(dep, depbefore)

    deledge!(graph, dep, head)
    @test isequal(head, headbefore)
    @test isequal(dep, depbefore)
end

# Order independence for dependents.
open(debugpath, "r") do debug_f
    coder = Coder()
    sents = collect(Sentence, conllxparse(debug_f, blind=true))
    sent = sents[1]

    let
        g1 = dgraph(sent, coder)
        edge!(g1, g1[end], g1[1])
        edge!(g1, g1[end - 1], g1[1])

        g2 = dgraph(sent, coder)
        edge!(g2, g2[end - 1], g2[1])
        edge!(g2, g2[end], g2[1])

        @test isequal(g1[1], g2[1])
    end
    let
        g1 = dgraph(sent, coder)
        edge!(g1, g1[1], g1[end])
        edge!(g1, g1[2], g1[end])

        g2 = dgraph(sent, coder)
        edge!(g2, g2[1], g2[end])
        edge!(g2, g2[2], g2[end])

        @test isequal(g2[end], g2[end])
    end
end

max_stars_repo_name: ninjin/allen

max_issues_repo_name: ninjin/allen

max_forks_repo_name: ninjin/allen


text:
using Documenter, CacheServers

# make documents
makedocs(
    modules = [CacheServers],
    clean = false,
    format = :html,
    sitename = "CacheServers.jl",
    linkcheck = !("skiplinks" in ARGS),
    analytics = "UA-89508993-1",
    pages = [
        "Home" => "index.md",
        "Manual" => "man.md"
    ],
    html_prettyurls = !("local" in ARGS),
    html_canonical = "https://quantumbfs.github.io/CacheServers.jl/latest/",
)

deploydocs(
    repo = "github.com/QuantumBFS/CacheServers.jl.git",
    target = "build",
    deps = nothing,
    make = nothing,
)


text:
using TimeZones: build

build()


text:
@info "Plotting results..."
using DABenchmarks
using Plots
pyplot()
# L-shaped scaling
ls_scaling = load_results("ls_scaling.json", Val{:scaling}())
p = plot(ls_scaling)
savefig(p,"fig4.pdf")
# L-shaped (TR) bundled scaling
tr_bundle_8 = load_results("tr_bundle_8.json", Val{:bundle}())
p = plot(tr_bundle_8)
savefig(p,"fig5.pdf")
# Progressive-hedging scaling
ph_scaling = load_results("ph_scaling.json", Val{:scaling}())
p = plot(ph_scaling, yticks = [1000,2000,3000,4000])
savefig(p,"fig6.pdf")

max_stars_repo_name: martinbiel/mpc-reproducibility

max_issues_repo_name: martinbiel/mpc-reproducibility

max_forks_repo_name: martinbiel/mpc-reproducibility