text:
module ChemometricsTools
    using DataFrames, LinearAlgebra, Statistics, StatsBase, SparseArrays,
            RecipesBase, Distributions, Dates, Combinatorics, FFTW
    using CSV: read
    #DSP.jl is currently broken and has been removed as a dependancy from
    #this project until further notice.
    #using DSP: conv

    #A generic function that I use everywhere to coerce a vector dim 0 to a row vector...
    forceMatrix( a ) = ( length( size( a ) ) == 1 ) ? reshape( a, length(a), 1 ) : a
    forceMatrixT( a ) = ( length( size( a ) ) == 1 ) ? reshape( a, 1, length(a) ) : a
    export forceMatrix, forceMatrixT

    include("DOE.jl") #Has Docs
    export SimplexCentroidDesign, SimplexLatticeDesign

    include("InHouseStats.jl") #Has Docs
    export EmpiricalQuantiles, Update!, Remove!, Update, Remove, RunningMean, RunningVar,
        Variance, Mean, rbinomial, Skewness, SampleSkewness, PermutedVectorPair,
        CorrelationMatrix, CorrelationVectors

    include("Univariate.jl") #Has Docs
    export Univariate, UnivariateCalibration, StandardAddition, Confidence_Offset,
        Confidence_Slope

    include("ClassificationMetrics.jl") #Has Docs
    export LabelEncoding, IsColdEncoded, HotToCold, ColdToHot, MulticlassStats,
        Threshold, MulticlassThreshold, HighestVote, StatsFromTFPN, StatsDictToDataFrame,
        StatsToCSVs, DataFrameToLaTeX, StatsToLaTeX

    include("RegressionMetrics.jl") #Has Docs
    export ME, MAE, MAPE, SSE, MSE, RMSE, SSTotal, SSReg, SSRes, RSquare,
        PearsonCorrelationCoefficient, PercentRMSE, FNorm

    include("DistanceMeasures.jl") #Has Docs
    export SquareEuclideanDistance, EuclideanDistance, ManhattanDistance,
        MinkowskiDistance, LevenshteinDistance, GaussianKernel, CauchyKernel,
        LinearKernel, Kernel, NearestNeighbors, AdjacencyMatrix,
        InClassAdjacencyMatrix, OutOfClassAdjacencyMatrix, CenterKernelMatrix

    include("Transformations.jl") #Has Docs: Box Cox Omitted for now...
    export Transform, PipelineInPlace, Pipeline, QuantileTrim, Center, Scale,
        CenterScale, RangeNorm, Logit, BoxCox

    include("Analysis.jl") #Has Docs
    export PCA_NIPALS, PCA, LDA, CanonicalCorrelationAnalysis, findpeaks,
        RAFFT, AssessHealth, DynamicTimeWarping, COW

    include("AnomalyDetection.jl") #Has docs
    export OneClassJKNN

    include("ClassificationModels.jl") #Has docs
    export KNN, ProbabilisticNeuralNetwork, GaussianDiscriminant, LogisticRegression, MultinomialSoftmaxRegression,
        GaussianNaiveBayes, HighestVoteOneHot, ConfidenceEllipse, LinearPerceptronSGD, LinearPerceptronBatch,
        HLDA, SIMCA

    include("Clustering.jl") #Has Docs
    export TotalClusterSS, WithinClusterSS, BetweenClusterSS, KMeansClustering, KMeans

    include("Preprocess.jl") #Has Docs
    export FirstDerivative, SecondDerivative, FractionalDerivative, SavitzkyGolay,
        DirectStandardization, OrthogonalSignalCorrection, MultiplicativeScatterCorrection,
        StandardNormalVariate, Scale1Norm, Scale2Norm, ScaleInfNorm, ScaleFNorm,
        ScaleMinMax, ScaleByIntensity, offsetToZero, boxcar, ALSSmoother,
        PerfectSmoother, CORAL, TransferByOrthogonalProjection, Noise, LinearResample,
        ConvFilter1DFFT, FourierUpsample, SincInterpolation

    include("RegressionModels.jl") # Has Docs
    export ClassicLeastSquares, OrdinaryLeastSquares, RidgeRegression,
        PrincipalComponentRegression, PartialLeastSquares, KernelRidgeRegression,
        LSSVM, ExtremeLearningMachine, PredictFn, sigmoid,
        MonotoneRegression

    include("ModelAnalysis.jl") #Has Docs - Not displaying?
    export ExplainedVariance, ExplainedVarianceX, ExplainedVarianceY,
            Q, Hotelling, Leverage

    include("Trees.jl") #Has Docs: Omitted StumpOrNode & StumpOrNodeRegress
    export OneHotOdds, entropy, gini, ssd, ClassificationTree, RegressionTree, CART

    include("Ensembles.jl") #Has Docs
    export MakeIntervals, stackedweights, RandomForest

    include("Sampling.jl") #Has Docs
    export VenetianBlinds, SplitByProportion, KennardStone

    include("Training.jl") #Has Docs
    export Shuffle, Shuffle!, LeaveOneOut, KFoldsValidation

    include("PSO.jl") #Has docs
    export PSO, Particle, Bounds

    include("CurveResolution.jl") #Has Docs
    export BTEMobjective, BTEM, NMF, SIMPLISMA, MCRALS, FNNLS, UnimodalFixedUpdate,
        UnimodalUpdate, UnimodalLeastSquares, ITTFA

    include("PlottingTools.jl") #Has Docs
    export residualsplotrecipe, QQ, BlandAltman, IntervalOverlay,
        DiscriminantAnalysisPlot, DAPlot

    include("TimeSeries.jl") #Has Docs
    export RollingWindow, EchoStateNetwork, TuneRidge, PredictFn, EWMA, Variance, Limits, update,
        SimpleAverage, NaiveForecast, update!, update

    include("MultiWay.jl") #Has Docs
    export Unfold, MultiCenter, MultiScale, MultiNorm, MultilinearPCA, HOSVD, HOOI,
        TensorProduct, MultilinearPLS

    include("KernelDensityGenerator.jl") #Has Docs
    export Universe, SpectralArray, GaussianBand, LorentzianBand

    include("SimpleGAs.jl") #Has Docs
    export BinaryLifeform, Lifeform, SinglePointCrossOver, Mutate

    include("DataUtils.jl") #Has Docs
    export ChemometricsToolsDataset, ChemometricsToolsDatasets,
        FindCommonVariables

end # module

max_issues_repo_name: caseykneale/ChemometricsTools

max_forks_repo_name: caseykneale/ChemometricsTools


text:
module DSR

export SDF, SDF_VD, SDF_FD, SDF_MYD_BW, SDF_MYD_EP, SDF_MAXWELL_VD, response
export readtxt, savetxt

const g = 9.8

function ode4(f::Function, y0::AbstractArray{Float64,1}, t::AbstractArray{Float64,1})
    # solve ODE dy/dt = f(y,t) using 4th-order Runge Kutta Method
    nstep = length(t)
    neq   = length(y0)

    y  = zeros(nstep, neq)
    y[1,:] = y0

    yn = copy(y0)

    for n in 2:nstep
        tn = t[n-1]
        h = t[n] - tn
        h2 = h*0.5

        k1 = f(yn      , tn   )
        k2 = f(yn+h2*k1, tn+h2)
        k3 = f(yn+h2*k2, tn+h2)
        k4 = f(yn+h*k3 , tn+h )

        yn += h/6.0*(k1+2.0*k2+2.0*k3+k4)
        y[n,:] = yn
    end

    y
end

function ode4hv(f::Function, y0::AbstractArray{Float64,1}, t::AbstractArray{Float64,1}, updateHistVar::Function)
    # solve ODE dy/dt = f(y,t,hv) using 4th-order Runge Kutta Method
    nstep = length(t)
    neq   = length(y0)

    y  = zeros(nstep, neq)
    y[1,:] = y0

    yn = copy(y0)
    fd = zeros(nstep)

    for n in 2:nstep
        tn = t[n-1]
        h = t[n] - tn
        h2 = h*0.5

        k1 = f(yn      , tn   )
        k2 = f(yn+h2*k1, tn+h2)
        k3 = f(yn+h2*k2, tn+h2)
        k4 = f(yn+h*k3 , tn+h )

        yn += h/6.0*(k1+2.0*k2+2.0*k3+k4)
        y[n,:] = yn
        fd[n] = updateHistVar(yn)
    end

    [y fd]
end

function readtxt(fn::String; skiprows::Int64=0, delim::Char=' ')
    data = readdlm(fn, delim; skipstart=skiprows)
    if size(data,2) == 1
        return data[:,1]
    elseif size(data,2) == 2
        return data[:,1], data[:,2]
    else
        return data
    end
end

function savetxt(fn::String, A::AbstractArray{Float64}; delim::Char=' ')
    writedlm(fn, A, delim)
end

function ds(t::Float64,dt::Float64,a_g::AbstractArray{Float64,1})
    # Convert a decrete signal into a continuous one via linear interpolation
    ind = convert(Int64, floor(t/dt)) + 1
    if ind == length(a_g)
        res = a_g[ind]
    elseif ind > length(a_g)
        res = 0.0
    elseif floor(t/dt)==ceil(t/dt)
        res = a_g[ind]
    else
        al = a_g[ind]
        ar = a_g[ind + 1]
        k = (ar - al) / dt
        return al+k*(t-(ind-1)*dt)
    end

    res
end

abstract DynamicSystem
abstract SDFDynamicSystem <: DynamicSystem

include("SDF.jl")
include("SDF_VD.jl")
include("SDF_FD.jl")
include("SDF_MYD_BW.jl")
include("SDF_MYD_EP.jl")
include("SDF_MAXWELL_VD.jl")
include("SDF_PID_VD.jl")

function response(s::SDFDynamicSystem, p::Function, t0::Float64, t1::Float64, dt::Float64)
    t = t0:dt:t1
    [t response(s, p, t)]
end

function response(s::SDFDynamicSystem, p::Function, t1::Float64, dt::Float64)
    t = 0.0:dt:t1
    [t response(s, p, t)]
end

function response(s::SDFDynamicSystem, p::Function, dt::Float64, nstep::Int64)
    t = 0.0:dt:dt*(nstep-1)
    [t response(s, p, t)]
end

function response(s::SDFDynamicSystem, a_g::AbstractArray{Float64,1}, t::AbstractArray{Float64,1})
    dt_g = t[2] - t[1]
    p = (t) -> ds(t, dt_g, -a_g)
    [t response(s, p, t)]
end

function response(s::SDFDynamicSystem, a_g::AbstractArray{Float64,1}, dt_g::Float64, t::AbstractArray{Float64,1})
    p = (t) -> ds(t, dt_g, -a_g)
    [t response(s, p, t)]
end

function response(s::SDFDynamicSystem, a_g::AbstractArray{Float64,1}, dt_g::Float64, t0::Float64, t1::Float64, dt::Float64)
    p = (t) -> ds(t, dt_g, -a_g)
    response(s, p, t0, t1, dt)
end

function response(s::SDFDynamicSystem, a_g::AbstractArray{Float64,1}, dt_g::Float64, t1::Float64, dt::Float64)
    p = (t) -> ds(t, dt_g, -a_g)
    response(s, p, t1, dt)
end

function response(s::SDFDynamicSystem, a_g::AbstractArray{Float64,1}, dt_g::Float64, dt::Float64, nstep::Int64)
    p = (t) -> ds(t, dt_g, -a_g)
    response(s, p, dt, nstep)
end

function response(s::SDFDynamicSystem, a_g::AbstractArray{Float64,1}, t1::Float64, dt::Float64)
    p = (t) -> ds(t, dt, -a_g)
    response(s, p, t1, dt)
end

function response(s::SDFDynamicSystem, a_g::AbstractArray{Float64,1}, dt::Float64, nstep::Int64)
    p = (t) -> ds(t, dt, -a_g)
    response(s, p, dt, nstep)
end

end

ext: jl

max_stars_repo_name: Panchatantra/DSR

max_issues_repo_name: Panchatantra/DSR

max_forks_repo_name: Panchatantra/DSR


text:
using ModelingToolkit, OrdinaryDiffEq, Test

@parameters t g e b
@variables v(t) w(t) F(t)
@derivatives D'~t
single_neuron_eqs = [
    D(v) ~ min(max(-2 - v, v), 2 - v) - w + F, # add the flux term
    D(w) ~ e * (v - g * w + b)
]
n1 = ODESystem(single_neuron_eqs, t, [v,w,F],[g,e,b], name = :n1)
n2 = ODESystem(single_neuron_eqs, t, [v,w,F],[g,e,b], name = :n2)
@parameters D Dk
connections = [
    0 ~ n1.F - D * Dk * max(n1.v - n2.v, 0)
    0 ~ n2.F - D * max(n2.v - n1.v, 0)
]
connected = ODESystem(connections,t,[],[D,Dk],systems=[n1,n2],name=:connected)

u0 = [
    n1.v => -2,
    n1.w => -2/3,
    n1.F => 0,
    n2.v => -2,
    n2.w => -.7,
    n2.F => 0,
]
tspan = (0.0, 1750.0)
p0 = [
    n1.g => 0.8,
    n1.e => 0.04,
    n1.b => 0,
    n2.g => 0.8,
    n2.e => 0.04,
    n2.b => 0.2,
    D => 0.047,
    Dk => 1
]

prob = ODEProblem(connected, u0, tspan, p0)
sol = solve(prob,Rodas5(),initializealg=BrownFullBasicInit())
@test prob.u0 == sol[1]
sol = solve(prob,Rodas5(),initiailizealg=ShampineCollocationInit())
@test prob.u0 == sol[1]


text:
struct SpeciesDataMatrix{T}
    data::Matrix{T}
    dir::SpeciesDirectory

    function SpeciesDataMatrix{T}(
        data::Matrix{T},
        sppdir::SpeciesDirectory
        ) where T
        n = length(sppdir)
        if n ≠ size(data, 1)
            msg = "the number of rows in the matrix should match the number of species given."
            throw(ArgumentError(msg))
        end

        return new{T}(data, sppdir)
    end
end

function SpeciesDataMatrix{T}(
    data::Matrix{T},
    sppdir::SpeciesDirectory,
    names::Vector{String}
    ) where T

    p = sortperm(sppdir[names])

    return SpeciesDataMatrix{T}(data[p,:], sppdir)
end

function SpeciesDataMatrix{T}(dir::SpeciesDirectory, k::Int) where T
    x = Matrix{T}(undef, length(dir), k)
    return SpeciesDataMatrix{T}(x, dir)
end

function SpeciesDataMatrix{T}(value::T, dir::SpeciesDirectory, k::Int) where T
    x = Matrix{T}(undef, length(dir), k)
    fill!(x, value)
    return SpeciesDataMatrix{T}(x, dir)
end

Base.size(dm::SpeciesDataMatrix) = size(dm.data)

Base.size(dm::SpeciesDataMatrix, dim::Int) = size(dm.data, dim)

# getindex methods
Base.getindex(dm::SpeciesDataMatrix, inds...) = getindex(dm.data, inds...)

Base.getindex(dm::SpeciesDataMatrix, name::String) = dm.data[dm.dir[name], :]

Base.getindex(dm::SpeciesDataMatrix, name::String, inds...) =
    dm.data[dm.dir[name], inds...]

Base.getindex(dm::SpeciesDataMatrix, names::Vector{String}) =
    dm.data[dm.dir[names], :]

Base.getindex(dm::SpeciesDataMatrix, names::Vector{String}, inds...) =
    dm.data[dm.dir[names], inds...]

# view methods
Base.view(dm::SpeciesDataMatrix, inds...) = view(dm.data, inds...)

Base.view(dm::SpeciesDataMatrix, name::String) = @view dm.data[dm.dir[name], :]

Base.view(dm::SpeciesDataMatrix, name::String, inds...) =
    @view dm.data[dm.dir[name], inds...]

Base.view(dm::SpeciesDataMatrix, names::Vector{String}) =
    @view dm.data[dm.dir[names], :]

Base.view(dm::SpeciesDataMatrix, names::Vector{String}, inds...) =
    @view dm.data[dm.dir[names], inds...]

# index methods
Base.firstindex(dm::SpeciesDataMatrix) = 1

Base.firstindex(dm::SpeciesDataMatrix, d) = firstindex(dm.data, d)

Base.lastindex(dm::SpeciesDataMatrix) = prod(size(dm))

Base.lastindex(dm::SpeciesDataMatrix, d) = lastindex(dm.data, d)

function Base.setindex!(
    dm::SpeciesDataMatrix{T},
    v::Union{T, Array{T}},
    inds...
    ) where T

    setindex!(dm.data, v, inds...)
end

function Base.setindex!(
    dm::SpeciesDataMatrix{T},
    v::Union{T, Array{T}},
    name::String,
    inds...
    ) where T

    setindex!(dm.data, v, dm.dir[name], inds...)
end

function Base.setindex!(
    dm::SpeciesDataMatrix{T},
    v::Union{T, Array{T}},
    names::Vector{String},
    inds...
    ) where T

    setindex!(dm.data, v, dm.dir[names], inds...)
end

function Base.setindex!(
    dm::SpeciesDataMatrix{T},
    v::Union{T, Array{T}},
    name::String
    ) where T

    dm.data[dm.dir[name],:] = v
end

# function Base.setindex!(
#     dm::SpeciesDataMatrix{T},
#     v::Union{T, Array{T}},
#     names::Vector{String}
#     ) where T

#     dm.data[dm.dir[names],:] = v
# end

function Base.summary(io::IO, dm::SpeciesDataMatrix)
    dims = string.(size(dm))
    dims = dims[1] * "x" * dims[2]
    msg =  dims * " SpeciesDataMatrix{" *
        string(eltype(dm.data)) * "}"
    print(io, msg)

    return nothing
end

function Base.show(io::IO, dm::SpeciesDataMatrix)
    println(io, summary(dm))
    k = size(dm, 2)
    header = ["Species" collect(1:k)...]
    aln = [:l,fill(:r, k)...]
    pretty_table(io, [dm.dir.list dm.data], header; alignment=aln)

    return nothing
end

# function Base.show(io::IO, dm::SpeciesDataMatrix{Float64}; digits::Int=4)
#     println(io, summary(dm))
#     k = size(dm, 2)
#     header = ["Species" collect(1:k)...]
#     aln = [:l,fill(:r, k)...]
#     pretty_table(
#         io,
#         [dm.dir.list dm.data],
#         header;
#         alignment=aln,
#         formatter=ft_printf("%5."*string(digits)*"f", collect(2:k+1))
#         )

#     return nothing
# end

"""
    write(io::IO, x::SpeciesDataMatrix)
    write(f::String, x::SpeciesDataMatrix; append=false)

Write a species data matrix to a file or I/O stream in a plaintext tabular format.

Columns are delimited by white space. Species names are written in the first column. Use `append=true` to write at the end of the file instead of overwriting it.
"""
function Base.write(io::IO, x::SpeciesDataMatrix)
    pretty_table(
        io,
        [x.dir.list x.data];
        tf = tf_borderless,
        noheader=true,
        alignment=:l
        );

    return nothing
end

function Base.write(f::String, x::SpeciesDataMatrix; append=false)
    open(f; write=true, append=append) do io
        write(io, x)
    end;

    return nothing
end

"""
    write_phylip(io::IO, x::SpeciesDataMatrix; namelength=0)
    write_phylip(filename::String, x::SpeciesDataMatrix; namelength=0, append=false)

Write a `SpeciesDataMatrix` to a I/O stream or file in the non-interleaved Phylip file format.

By default, with the argument `namelength=0`, it writes files in a relaxed version of the Phylip format in which the names of the species are not fixed. To enforce fixed name lengths, set `namelength` to the desired name length (10 characters is Phylip's default). Thus names longer than `namelength` will be truncated.
"""
function write_phylip(io::IO, x::SpeciesDataMatrix; namelength=0)
    dims = string.(size(x))
    if namelength == 0
        maxlength = maximum(length.(x.dir.list))
        printnames = rpad.(x.dir.list, maxlength+1)
    else
        printnames = map(xx -> length(xx) > namelength ? xx[1:namelength] : xx, x.dir.list)
        printnames = rpad.(printnames, namelength)
    end
    println(io, dims[1], " ", dims[2])
    n, k = size(x.data)
    for i in 1:n
        print(io, printnames[i])
        for j in 1:k-1
            print(io, x.data[i, j], " ")
        end
        print(io, x.data[i, k], "\n")
    end

    return nothing
end

function write_phylip(filename::String, x::SpeciesDataMatrix; namelength=0, append=false)
    open(filename; write=true, append=append) do io
        write_phylip(io, x, namelength=namelength)
    end;

    return nothing
end

"""
    read_species_data(filename::String, T::Type)
    read_species_data(io::IO, T::Type)
    read_species_data(filename::String, T::Type, dir::SpeciesDirectory; addspecies=false)
    read_species_data(io::IO, T::Type, dir::SpeciesDirectory; addspecies=false)

Read in tabular species data from a file or I/O stream and return a `SpeciesDataMatrix` with data of type `T`.

This parses data in a simple tabular format with white space-delimited columns. The first column contains the species names and the following columns contain all the diferent variables (traits, characters, or other kind of data). The `SpeciesDataMatrix` produced will have the data type specified by `T`.

The `SpeciesDirectory` associated to the output `SpeciesDataMatrix` can be given by `dir`. If none is given, a new `SpeciesDirectory` will be created from the species names in the data file or I/O stream. If a `SpeciesDirectory` is given and the data file or I/O stream contains species names not present in the directory, the arugment `addspecies` can be set to `true` to add the new species to the directory or else the function will throw an error.
"""
function read_species_data(filename::String, T::Type, dir::SpeciesDirectory; addspecies=false)
    open(filename, "r") do io
        read_species_data(io, T, dir; addspecies=addspecies)
    end
end

function read_species_data(filename::String, T::Type)
    open(filename, "r") do io
        read_species_data(io, T)
    end
end

function read_species_data(io::IO, T::Type, dir::SpeciesDirectory; addspecies=false)
    inmat = readdlm(io)
    innames = string.(inmat[:,1])
    data = convert(Matrix{T}, inmat[:,2:end])
    newspp = setdiff(innames, dir.list)
    if addspecies
        addspecies!(dir, newspp)
    else
        length(newspp) ≠ 0 && throw(ErrorException("The file contains species missing from the species directory."))
    end

    return SpeciesDataMatrix{T}(data, dir, innames)
end

function read_species_data(io::IO, T::Type)
    inmat = readdlm(io)
    innames = string.(inmat[:,1])
    data = convert(Matrix{T}, inmat[:,2:end])
    dir = SpeciesDirectory(innames)

    return SpeciesDataMatrix{T}(data, dir)
end


text:
# This file is automatically executed if you call Pkg.test("ForneyLab")

module ForneyLabTest

using Test

@testset "ForneyLab" begin
    include("./test_helpers.jl")
    include("./test_factor_node.jl")
    include("./test_interface.jl")
    include("./test_probability_distribution.jl")
    include("./test_edge.jl")
    include("./test_variable.jl")
    include("./test_factor_graph.jl")

    # Factor nodes
    include("factor_nodes/test_clamp.jl")
    include("factor_nodes/test_equality.jl")
    include("factor_nodes/test_addition.jl")
    include("factor_nodes/test_multiplication.jl")
    include("factor_nodes/test_exponential.jl")
    include("factor_nodes/test_gaussian_mean_variance.jl")
    include("factor_nodes/test_gaussian_mean_precision.jl")
    include("factor_nodes/test_gaussian_weighted_mean_precision.jl")
    include("factor_nodes/test_gaussian.jl")
    include("factor_nodes/test_gamma.jl")
    include("factor_nodes/test_log_normal.jl")
    include("factor_nodes/test_wishart.jl")
    include("factor_nodes/test_bernoulli.jl")
    include("factor_nodes/test_categorical.jl")
    include("factor_nodes/test_contingency.jl")
    include("factor_nodes/test_transition.jl")
    include("factor_nodes/test_beta.jl")
    include("factor_nodes/test_dirichlet.jl")
    include("factor_nodes/test_gaussian_mixture.jl")
    include("factor_nodes/test_transition_mixture.jl")
    include("factor_nodes/test_probit.jl")
    include("factor_nodes/test_logit.jl")
    include("factor_nodes/test_softmax.jl")
    include("factor_nodes/test_dot_product.jl")
    include("factor_nodes/test_poisson.jl")
    include("factor_nodes/test_sample_list.jl")
    include("factor_nodes/test_moment_constraint.jl")
    include("factor_nodes/test_chance_constraint.jl")
    include("factor_nodes/test_point_mass_constraint.jl")
    include("factor_nodes/test_nonlinear_unscented.jl")
    include("factor_nodes/test_nonlinear_sampling.jl")
    include("factor_nodes/test_nonlinear_extended.jl")
    include("./test_dependency_graph.jl")
    include("./test_message_passing.jl")
    include("./test_marginals.jl")

    # Algorithms
    include("./algorithms/test_cluster.jl")
    include("./algorithms/test_posterior_factor.jl")
    include("./algorithms/test_posterior_factorization.jl")
    include("./algorithms/test_inference_algorithm.jl")
    include("./algorithms/test_joint_marginals.jl")
    include("./algorithms/test_sum_product.jl")
    include("./algorithms/test_naive_variational_bayes.jl")
    include("./algorithms/test_structured_variational_bayes.jl")
    include("./algorithms/test_expectation_propagation.jl")

    # Assemblers
    include("engines/test_message_passing_assemblers.jl")
    include("engines/test_free_energy_assemblers.jl")

    # Engines
    include("./engines/julia/test_generators.jl")

    # Composite node
    include("factor_nodes/test_composite.jl")
end

end


text:
@recipe function plot(match_wave::MatchWave{T}) where T <: AbstractFloat

    dx = match_wave.x_match[2] - match_wave.x_match[1]
    max_x = match_wave.x_match[end]
    x = [match_wave.x_match; (max_x:dx:(2*max_x)) .+ dx]
    @series (x, match_wave)
end

@recipe function plot(x::AbstractVector{T}, match_wave::MatchWave{T}; hankel_order = match_wave.effective_waves[1].hankel_order,
        hankel_indexes = 0:hankel_order,
        apply = real, match_region = true) where T <: AbstractFloat

    ho = hankel_order
    wave_eff = AverageWave(match_wave.x_match, match_wave.effective_waves)
    max_amp = maximum(apply.(wave_eff.amplitudes[:,(hankel_indexes) .+ (ho+1),:]))
    min_amp = minimum(apply.(wave_eff.amplitudes[:,(hankel_indexes) .+ (ho+1),:]))

    max_amp = (max_amp > 0) ? 1.1*max_amp : 0.0
    min_amp = (min_amp < 0) ? 1.1*min_amp : 0.0

    if match_region == true
        @series begin
            label --> "match region"
            fillalpha --> 0.3
            fill --> (0,:orange)
            line --> 0
            (x1 -> x1, y->max_amp, match_wave.x_match[1],  match_wave.x_match[end])
        end

        @series begin
            label --> ""
            fillalpha --> 0.3
            fill --> (0,:orange)
            line --> 0
            (x1 -> x1, y->min_amp, match_wave.x_match[1],  match_wave.x_match[end])
        end
    end

    @series begin
        apply --> apply
        hankel_indexes --> hankel_indexes
        # markeralpha --> 0.2
        markersize --> 4.0
        match_wave.average_wave
    end

    @series begin
        apply --> apply
        hankel_indexes --> hankel_indexes
        (x, match_wave.effective_waves)
    end

end


text:
 # function to calculate the distance between two points according to the minimal-distance convention

 function pbcseparation(x::Vector{Float64},y::Vector{Float64}, L)
   d = 0.
   for i in 1:2
     dx = (y[i] - x[i])%L       # difference between y and x
     if dx > L / 2
       dx = dx - L
     elseif dx < -L/2
       dx = dx + L
     end
     d = d + dx^2
   end
   return sqrt(d)
 end

 function pbcseparation(x::Float64,y::Float64,L)
   dx = (y - x)%L
   if dx > L / 2
     dx = dx - L
   elseif dx < -L/2
     dx = dx + L
   end

   return sqrt(dx^2)
 end

export pbcseparation


text:
include("09_two_site_state_optimization.jl")

println("
#######################################################
# Tutorial 10                                         #
#                                                     #
# 2-site circuit minimization via gradient            #
# optimization                                        #
#######################################################
")

# References state `|0⟩ = |Z+Z+⟩`
ψ⁰ = Zp1 * Zp2

# Form the circuit from parameters
U(θ, i1, i2) = [
  op("Ry", i1; θ=θ[1]),
  op("Ry", i2; θ=θ[2]),
  op("CX", i1, i2),
  op("Ry", i1; θ=θ[3]),
  op("Ry", i2; θ=θ[4]),
]

# Find the circuit `U(θ)` that minimizes:
# energy_circuit(θ) = ⟨0|U(θ)† H U(θ)|0⟩ = ⟨θ|H|θ⟩
function E(θ)
  # Apply the circuit:
  # |θ⟩ = U(θ)|0⟩
  ψᶿ = apply(U(θ, i1, i2), ψ⁰)

  # Compute the expecation value: ⟨θ|H|θ⟩
  # No need to normalize!
  return inner(ψᶿ', H, ψᶿ)
end

println("Circuit optimization")
θ⁰ = zeros(4)
∂E(ψ) = gradient(E, ψ)[1]
θ = minimize(E, ∂E, θ⁰; nsteps=40, γ=0.5)

@show θ⁰, E(θ⁰), norm(∂E(θ⁰))
@show θ, E(θ), norm(∂E(θ))


text:
"""
	asympFit(x,columns)

Function to estimate the asmpytotic value of α(x).

# Arguments
 - `alphaValues::Array{Float64,1}`: α(x) array.
# Returns
 - `Array{Float64,2}`: Array of array containing asymptotic values, lower confidence interval, higher confidence interval
"""
function asympFit(alphaValues::Array{Float64,1})

	# Model
	asympModel(x,p) = @. p[1] + p[2]*exp(-x*p[3])

	# Fit values
	fitted1    = curve_fit(asympModel,collect(1:size(alphaValues,1)),alphaValues,[-1.0,-1.0,1.0];lower=[-1.0,-1.0,1.0],upper=[1.0, 1.0, 10.0])
	fitted2    = curve_fit(asympModel,collect(1:size(alphaValues,1)),alphaValues,fitted1.param)
	asymp      = asympModel(size(alphaValues,1),fitted2.param)

	ciLow, ciHigh   = try
		confidence_interval(fitted2)[1][1],LsqFit.confidence_interval(fitted2)[1][2]
	catch err
		(0.0,0.0)
	end

	return asymp,[ciLow,ciHigh],fitted2.param
	# return asymp
end

"""
	imputedMK(sfs,divergence,m,cutoff)

Function to estimate the asmpytotic value of α(x).

# Arguments
 - `alphaValues::Array{Float64,1}`: α(x) array.
# Returns
 - `Array{Float64,2}`: Array of array containing asymptotic values, lower confidence interval, higher confidence interval
"""
function impMK(;sfs::Array,divergence::Array,m::T,cutoff::Float64=0.15) where {T<:Union{Nothing,Array}}

	output = OrderedDict{String,Float64}()

	pn = sum(sfs[:,2])
	ps = sum(sfs[:,3])
	dn = divergence[1]
	ds = divergence[2]

	deleterious = 0
	### Estimating slightly deleterious with pn/ps ratio
	fltLow = (sfs[:, 1] .<= cutoff)
	pnLow   = sum(sfs[fltLow,2])
	psLow   = sum(sfs[fltLow,3])

	fltInter = (sfs[:, 1] .>= cutoff) .& (sfs[:, 1] .<= 1)
	pnInter = sum(sfs[fltInter,2])
	psInter = sum(sfs[fltInter,3])

	ratioPs       = psLow / psInter
	deleterious   = pnLow - (pnInter * ratioPs)

	if deleterious > pn
		deleterious = 0
		pnNeutral = round(pn - deleterious,digits=3)
	else
		pnNeutral = round(pn - deleterious,digits=3)
	end
	# output['alpha'] = 1 - (((pn - deleterious) / ps) * (ds / dn))
	output["alpha"] = round(1 - ((pnNeutral/ps) * (ds / dn)),digits=3)
	#  method = :minlike same results R, python two.sides
	output["pvalue"] = pvalue(FisherExactTest(Int(ps),Int(ceil(pnNeutral)),Int(ds),Int(dn)))

	if (!isnothing(m))

		mn = m[1]; ms = m[2]
		# ## Estimation of b: weakly deleterious
		output["b"] = (deleterious / ps) * (ms / mn)

		## Estimation of f: neutral sites
		output["f"] = (ms * pnNeutral) / (mn * ps)

		## Estimation of d, strongly deleterious sites
		output["d"] = 1 - (output["f"] + output["b"])

		ka      = dn / mn
		ks       = ds / ms
		output["omega"]    = ka/ ks

		# Omega A and Omega D
		output["omegaA"] = output["omega"] * output["alpha"]
		output["omegaD"] = output["omega"] - output["omegaA"]
	end

	return output
end

"""
	fwwMK(sfs,divergence,m,cutoff)

Function to estimate the asmpytotic value of α(x).

# Arguments
 - `alphaValues::Array{Float64,1}`: α(x) array.
# Returns
 - `Array{Float64,2}`: Array of array containing asymptotic values, lower confidence interval, higher confidence interval
"""
function fwwMK(;sfs::Array,divergence::Array,m::T,cutoff::Float64=0.15) where {T<:Union{Nothing,Array}}

	output = OrderedDict{String,Float64}()

	ps = sum(sfs[:,2])
	pn = sum(sfs[:,3])
	dn = divergence[1]
	ds = divergence[2]

	deleterious = 0
	### Estimating slightly deleterious with pn/ps ratio
	fltInter = (sfs[:, 1] .>= cutoff) .& (sfs[:, 1] .<= 1)
	pnInter = sum(sfs[fltInter,2])
	psInter = sum(sfs[fltInter,3])

	# output['alpha'] = 1 - (((pn - deleterious) / ps) * (ds / dn))
	output["alpha"] = round(1 - ((pnInter/psInter) * (ds / dn)),digits=3)
	#  method = :minlike same results R, python two.sides
	output["pvalue"] = pvalue(FisherExactTest(Int(psInter),Int(ceil(pnInter)),Int(ds),Int(dn)))

	if (!isnothing(m))

		mn = m[1]; ms = m[2]
		ka      = dn / mn
		ks       = ds / ms
		output["omega"]    = ka/ ks

		# Omega A and Omega D
		output["omegaA"] = output["omega"] * output["alpha"]
		output["omegaD"] = output["omega"] - output["omegaA"]
	end

	return output
end

"""
	standardMK(x,columns)

Function to estimate the original α value

# Arguments
 - `alphaValues::Array{Float64,1}`: α(x) array.
# Returns
 - `Array{Float64,2}`: Array of array containing asymptotic values, lower confidence interval, higher confidence interval
"""
function standardMK(;sfs::Array,divergence::Array,m::T=nothing) where {T<:Union{Nothing,Array}}

	output = OrderedDict{String,Float64}()

	pn = sum(sfs[:,2])
	ps = sum(sfs[:,3])
	dn = divergence[1]
	ds = divergence[2]

	output["alpha"] = round(1 - ((pn/ps) * (ds / dn)),digits=3)
	#  method = :mnnlike same results R, python two.sides
	output["pvalue"] = pvalue(FisherExactTest(Int(ps),Int(ceil(pn)),Int(ds),Int(dn)))

	if (!isnothing(m))

		mn = m[1]; ms = m[2]

		ka      = dn / mn
		ks       = ds / ms
		output["omega"]    = ka/ ks

		# Omega A and Omega D
		output["omegaA"] = output["omega"] * output["alpha"]
		output["omegaD"] = output["omega"] - output["omegaA"]
	end

	return output
end


text:
baremodule Terminators

function withtimeout end
function open end
function start end
function stop end

"""
    Terminators.withtimeout(f, seconds::Number, [terminator])

Run `f()` with the timeout `seconds`. This process is terminated if `f()` does
not finish after `seconds` seconds.
"""
withtimeout

"""
    Terminators.open() -> terminator
    Terminators.open(f)

Create a terminator.
"""
open

module Internal

using ..Terminators: Terminators

include("internal.jl")

end  # module Internal

end  # baremodule Terminators


text:
module TSSOS

using MosekTools
using JuMP
using LightGraphs
using ChordalGraph
using MultivariatePolynomials
using Ipopt
using LinearAlgebra
using MetaGraphs
using SemialgebraicSets
using COSMO
# using SDPT3

export tssos_first, tssos_higher!, cs_tssos_first, cs_tssos_higher!, local_solution, refine_sol,
nctssos_first, nctssos_higher!, cs_nctssos_first, cs_nctssos_higher!

include("clique_merge.jl")
include("blockpop_uncons.jl")
include("blockpop_cons.jl")
include("nblockmix.jl")
include("complex.jl")
include("local_solution.jl")
include("NCTSSOS/NCTSSOS.jl")
using .NCTSSOS

end


text:
using DelimitedFiles
function Demand24Load(filename_Load24)
    ## source from: http://www.pjm.com/markets-and-operations/ops-analysis/historical-load-data.aspx
    temp_data = readdlm(filename_Load24, ',',header=true)[1][:,2:end]
    raw_data = Array{Float64}(undef,size(temp_data))
    normalized_data = Array{Float64}(undef,size(temp_data))
    raw_data[:] = temp_data[:]
    max_load = [2586,1917,2744,538,1295,2358,2216,630,1388,9397,5214]
    N_bus = size(max_load,1)
    N_hours = size(temp_data,1)

    for k = 1:N_bus
        for m = 1:N_hours
        normalized_data[m,k] = raw_data[m,k] / max_load[k,1]
    end
end
    load24 = normalized_data
    return load24
end

max_stars_repo_name: JipKim/IA

max_issues_repo_name: JipKim/IA

max_forks_repo_name: JipKim/IA


text:
using Formatting

### math ###
type InlineMath
    text
    InlineMath(text, md::Markdown.MD) = return new(strip(text))
end

### math ###
type InlineCode
    text
    InlineCode(text, md::Markdown.MD) = return new(text)
end

### Tex ###
type InlineTex
    text
    InlineTex(text, md::Markdown.MD) = return new(text)
end

### Citation ###
type InlineCite
    sources
    InlineCite(text, md::Markdown.MD) = return new(split(text, ','))
end

### Reference ###
type InlineRef
    text
    InlineRef(text, md::Markdown.MD) = return new(text)
end

### Units ###
type InlineUnit
    units
    InlineUnit(text, md::Markdown.MD) = return new(split(text, ' '))
end

### Chemical Equation ###
type InlineCE
    text
    InlineCE(text, md::Markdown.MD) = return new(text)
end

### Chemical Equation ###
type InlineFootnote
    text
    InlineFootnote(text, md::Markdown.MD) = return new(Markdown.parseinline(text, md))
end

### Data ###
type InlineData
    text
    format
    function InlineData(raw, md::Markdown.MD)
        t = split(raw, '|')
        text = t[1]
        format  = get(t, 2, "{}") # Just print the value
        return new(text, format)
    end
end

""" Does more traditional Tex/Pandoc style inline math. """
function inline_math(stream::IO, md::Markdown.MD)
    # The follow does not support whitespace between delimeters, so we won't be using it
    result = Markdown.parse_inline_wrapper(stream, "\$")
    return result === nothing ? nothing : InlineMath(result, md)
end

""" Does more traditional Tex/Pandoc style inline math. """
function inline_code(stream::IO, md::Markdown.MD)
    result = Markdown.parse_inline_wrapper(stream, "`")
    return result === nothing ? nothing : InlineCode(result, md)
end

# Trigger is (
""" Parses inline tages of the form (key text) """
function interpreted_inline(stream::IO, md::Markdown.MD)
    # Memory allocation every time function is run
    tags = Dict(
        ".math" => InlineMath,
        ".tex" => InlineTex,
        "@" => InlineCite,
        "#" => InlineRef,
        ".unit" => InlineUnit,
        ".ce" => InlineCE,
        "\$" => InlineData,
        "^" => InlineFootnote
    )

    inline_key = ""
    for key in keys(tags)
        if Markdown.startswith(stream, "[$key")
            inline_key = key
            break
        end
    end

    if isempty(inline_key)
        return nothing
    end

    text = Markdown.readuntil(stream, ']', match='[')
    return text === nothing ? nothing : tags[inline_key](text, md)
end


text:
# Support for @simd for

module SimdLoop

export @simd

# Error thrown from ill-formed uses of @simd
type SimdError <: Exception
    msg::ASCIIString
end

# Parse iteration space expression
#       symbol '=' range
#       symbol 'in' range
function parse_iteration_space(x)
    Meta.isexpr(x, [:(=), :in]) || throw(SimdError("= or in expected"))
    length(x.args) == 2 || throw(SimdError("simd range syntax is wrong"))
    isa(x.args[1], Symbol) || throw(SimdError("simd loop index must be a symbol"))
    x.args # symbol, range
end

# Compile Expr x in context of @simd.
function compile(x)
    Meta.isexpr(x, :for) || throw(SimdError("for loop expected"))
    length(x.args) == 2 || throw(SimdError("1D for loop expected"))

    var,range = parse_iteration_space(x.args[1])
    r = gensym("r") # Range value
    n = gensym("n") # Trip count
    s = gensym("s") # Step
    i = gensym("i") # Index variable
    quote
        # Evaluate range value once, to enhance type and data flow analysis by optimizers.
        let $r = $range, $n = length($r)
            if zero($n) < $n
                let $var = first($r)
                    # LLVM vectorizer needs to compute a trip count, so make it obvious.
                    local $s = step($r)
                    local $i = zero($n)
                    while $i < $n
                        $(x.args[2])
                        $var += $s
                        $i += 1
                        $(Expr(:simdloop))  # Mark loop as SIMD loop
                    end
                end
                # Set index to last value just like a regular for loop would
                $var = last($r)
            end
        end
        nothing
    end
end

macro simd(forloop)
    esc(compile(forloop))
end

end # module SimdLoop

max_stars_repo_name: tobig/julia

max_issues_repo_name: tobig/julia

max_forks_repo_name: tobig/julia


text:
using Test
using Flux
using Flux.Losses: ctc_loss
using Zygote: gradient
using LinearAlgebra
using CUDA

# Custom function to check numerical gradient of ctc loss,
# based on `ngradient` in `Tracker.jl`
function ctc_ngradient(x, y)
  f = Flux.Losses.ctc_loss
  grads = zero(x)
  for i in 1:length(x)
    δ = sqrt(eps())
    tmp = x[i]
    x[i] = tmp - δ/2
    y1 = f(x, y)
    x[i] = tmp + δ/2
    y2 = f(x, y)
    x[i] = tmp
    grads[i] = (y2-y1)/δ
  end
  return grads
end

@testset "ctc-gpu" begin
  x = rand(10, 50)
  y = rand(1:9, 30)
  x_cu = CuArray(x)
  g1 = gradient(ctc_loss, x_cu, y)[1]
  g1 = g1 |> collect
  g2 = ctc_ngradient(x, y)
  @test g1 ≈ g2 rtol=1e-5 atol=1e-5

  # test that GPU loss matches CPU implementation
  l1 = ctc_loss(x_cu, y)
  l2 = ctc_loss(x, y)
  @test l1 ≈ l2

  # tests using hand-calculated values
  x_cu = [1. 2. 3.; 2. 1. 1.; 3. 3. 2.] |> CuArray
  y = [1, 2]
  @test ctc_loss(x_cu, y) ≈ 3.6990738275138035

  g = [-0.317671 -0.427729 0.665241; 0.244728 -0.0196172 -0.829811; 0.0729422 0.447346 0.16457]
  ghat = gradient(ctc_loss, x_cu, y)[1] |> collect
  @test g ≈ ghat rtol=1e-5 atol=1e-5

  x_cu = [-3. 12. 8. 15.; 4. 20. -2. 20.; 8. -33. 6. 5.] |> CuArray
  y = [1, 2] |> CuArray
  @test ctc_loss(x_cu, y) ≈ 8.02519869363453

  g = [-2.29294774655333e-06 -0.999662657278862 1.75500863563993e-06 0.00669284889063; 0.017985914969696 0.999662657278861 -1.9907078755387e-06 -0.006693150917307; -0.01798362202195 -2.52019580677916e-20 2.35699239251042e-07 3.02026677058789e-07]
  ghat = gradient(ctc_loss, x_cu, y)[1] |> collect
  @test g ≈ ghat rtol=1e-5 atol=1e-5
end


text:
struct Equation
    coeffA :: Float64
    coeffB :: Float64
    coeffC :: Float64

    function Equation(numPots :: Int64, aMult :: Int64, bMult :: Int64)
        coeffA = convert(Float64, aMult + bMult);
        coeffB = convert(Float64, -2 * bMult * numPots);
        coeffC = convert(Float64, bMult * (numPots ^ 2));
        return new(coeffA, coeffB, coeffC)
    end
end

function find_equation_min(eq :: Equation)
    numer = -eq.coeffB
    denom = 2 * eq.coeffA
    return numer / denom
end

function solve_equation_at(eq :: Equation, coord :: Float64)
    aTerm = eq.coeffA * (coord ^ 2)
    bTerm = eq.coeffB * coord
    cTerm = eq.coeffC
    return aTerm + bTerm + cTerm
end

function solve_case(numPots, aMult, bMult) :: Int64
    eq = Equation(numPots, aMult, bMult);
    eq_min = find_equation_min(eq);
    soln = solve_equation_at(eq, round(eq_min));
    return round(soln);
end

function run_case()
    test_case_data = [parse(Int64, x) for x in split(readline())];
    soln = solve_case(test_case_data[1], test_case_data[2], test_case_data[3]);
    println(soln);
end

function main_fn()
    num_ranges = parse(Int, readline());

    for i in 1:num_ranges
        run_case();
    end

    return nothing
end

main_fn();


text:
module io

const escaperules = Vector{String}[
    ["\"", """],
    ["\'", "'"],
    ["<",  "<"],
    [">",  ">"],
    ["&",  "&"]
    ]

function escape_xml(s::AbstractString)
    for (character, escapesequence) in reverse(escaperules)
        s = replace(s, character, escapesequence)
    end
    return s
end

function unescape_xml(s::AbstractString)
    for (character, escapesequence) in escaperules
        s = replace(s,escapesequence, character)
    end
    return s
end

function git_commitid(path)
    # return readall(`git --work-tree $path rev-parse HEAD`)[1:end-1]
    return readall(`cat $(path)/../.git/refs/heads/master`)[1:end-1]
end

function git_commitdate(path)
    return readall(`git --work-tree $path show -s --format=%ci`)[1:end-1]
end

function write_gitinfo(f, tag, gitpath)
    ID = escape_xml(git_commitid(gitpath))
    #date = escape_xml(git_commitdate(gitpath))
    write(f, "<$(tag)>\n")
    write(f, "<commit-id>$(ID)</commit-id>\n")
    #write(f, "<commit-date>$(date)</commit-date>\n")
    write(f, "</$(tag)>\n")
end

function write_libraryinfo_julia(f)
    write(f, "<julia>\n")
    write(f, escape_xml(string(VERSION)))
    write(f, "\n")
    write(f, "</julia>\n")
end

function write_libraryinfo_quantumoptics(f)
    tag = "quantumoptics-library"
    searchname = "quantumoptics-julia"
    for path in LOAD_PATH
        if contains(path, searchname)
            write_gitinfo(f, tag, path)
        end
    end
end

function write_libraryinfo_CollectiveSpins(f)
    tag = "CollectiveSpins-library"
    searchname = "CollectiveSpins-library"
    for path in LOAD_PATH
        if contains(path, searchname)
            write_gitinfo(f, tag, path)
        end
    end
end

function write_libraryinfo(f)
    write(f, "<libraries>\n")
    write_libraryinfo_julia(f)
    write_libraryinfo_quantumoptics(f)
    write_libraryinfo_CollectiveSpins(f)
    write(f, "</libraries>\n")
end

function write_systemdescription(f, system)
    write(f, "<systemdescription>\n")
    write(f, escape_xml(string(system)))
    write(f, "\n")
    write(f, "</systemdescription>\n")
end

function write_simulationparameters(f, parameters)
    write(f, "<simulationparameters>\n")
    write(f, escape_xml(string(parameters)))
    write(f, "\n")
    write(f, "</simulationparameters>\n")
end

function write_starttime(f)
    starttime = escape_xml(string(now()))
    write(f, "<starttime>\n")
    write(f, starttime)
    write(f, "\n")
    write(f, "</starttime>\n")
end

function write_head(f, system, parameters)
    write(f, "<head>\n")
    write_starttime(f)
    write_libraryinfo(f)
    write_systemdescription(f, system)
    write_simulationparameters(f, parameters)
    write(f, "</head>\n")
end

function write_state(f, statetype, state::Vector{T}; parameter=nothing, time=true) where T
    writetime = time ? " writetime = \"$(escape_xml(string(now())))\"" : ""
    statetype = escape_xml(statetype)
    datatype = escape_xml(string(T))
    parameter = parameter!=nothing ? " parameter = \"$(escape_xml(parameter))\"" : ""
    write(f, "<state statetype=\"$(statetype)\" datatype=\"$(datatype)\"$writetime$parameter>")
    for (i, x) in enumerate(state)
        if i!=1
            write(f, ',')
        end
        write(f, string(x))
    end
    write(f, "</state>\n")
end

function write_state_meanfield(f, state::Vector{T}, parameter) where T
    write_state(f, state, parameter, "meanfield")
end

function write_state_mpc(f, state::Vector{T}, parameter) where T
    write_state(f, state, parameter, "mpc")
end

function write_state_densityoperator(f, state::Matrix{T}, parameter) where T
    write_state(f, vec(state.data), parameter, "densityoperator")
end

function save_timeevolution(path, system, time, states, statetype, parameters)
    @assert length(time)==length(states)
    f = open(path, "w")
    write_head(f, system, parameters)
    for i=1:length(time)
        write_state(f, vec(states[i].data), "t=$(time[i])", statetype)
    end
    close(f)
end

end # module


text:
# Automatically generated using Clang.jl

# Skipping MacroDefinition: cuStreamBeginCapture __CUDA_API_PTSZ ( cuStreamBeginCapture_v2 )

const CUDA_VERSION = 10010
const CU_IPC_HANDLE_SIZE = 64

# Skipping MacroDefinition: CU_STREAM_LEGACY ( ( CUstream ) 0x1 )
# Skipping MacroDefinition: CU_STREAM_PER_THREAD ( ( CUstream ) 0x2 )

const CU_MEMHOSTALLOC_PORTABLE = 0x01
const CU_MEMHOSTALLOC_DEVICEMAP = 0x02
const CU_MEMHOSTALLOC_WRITECOMBINED = 0x04
const CU_MEMHOSTREGISTER_PORTABLE = 0x01
const CU_MEMHOSTREGISTER_DEVICEMAP = 0x02
const CU_MEMHOSTREGISTER_IOMEMORY = 0x04
const CUDA_EXTERNAL_MEMORY_DEDICATED = 0x01
const CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_NO_PRE_LAUNCH_SYNC = 0x01
const CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_NO_POST_LAUNCH_SYNC = 0x02
const CUDA_ARRAY3D_LAYERED = 0x01
const CUDA_ARRAY3D_2DARRAY = 0x01
const CUDA_ARRAY3D_SURFACE_LDST = 0x02
const CUDA_ARRAY3D_CUBEMAP = 0x04
const CUDA_ARRAY3D_TEXTURE_GATHER = 0x08
const CUDA_ARRAY3D_DEPTH_TEXTURE = 0x10
const CUDA_ARRAY3D_COLOR_ATTACHMENT = 0x20
const CU_TRSA_OVERRIDE_FORMAT = 0x01
const CU_TRSF_READ_AS_INTEGER = 0x01
const CU_TRSF_NORMALIZED_COORDINATES = 0x02
const CU_TRSF_SRGB = 0x10

# Skipping MacroDefinition: CU_LAUNCH_PARAM_END ( ( void * ) 0x00 )
# Skipping MacroDefinition: CU_LAUNCH_PARAM_BUFFER_POINTER ( ( void * ) 0x01 )
# Skipping MacroDefinition: CU_LAUNCH_PARAM_BUFFER_SIZE ( ( void * ) 0x02 )

const CU_PARAM_TR_DEFAULT = -1

# Skipping MacroDefinition: CU_DEVICE_CPU ( ( CUdevice ) - 1 )
# Skipping MacroDefinition: CU_DEVICE_INVALID ( ( CUdevice ) - 2 )

const cuuint32_t = UInt32
const cuuint64_t = UInt64
@assert sizeof(CUdeviceptr) == sizeof(Culonglong)
const CUdevice = Cint
const CUctx_st = Cvoid
const CUcontext = Ptr{CUctx_st}
const CUmod_st = Cvoid
const CUmodule = Ptr{CUmod_st}
const CUfunc_st = Cvoid
const CUfunction = Ptr{CUfunc_st}
const CUarray_st = Cvoid
const CUarray = Ptr{CUarray_st}
const CUmipmappedArray_st = Cvoid
const CUmipmappedArray = Ptr{CUmipmappedArray_st}
const CUtexref_st = Cvoid
const CUtexref = Ptr{CUtexref_st}
const CUsurfref_st = Cvoid
const CUsurfref = Ptr{CUsurfref_st}
const CUevent_st = Cvoid
const CUevent = Ptr{CUevent_st}
const CUstream_st = Cvoid
const CUstream = Ptr{CUstream_st}
const CUgraphicsResource_st = Cvoid
const CUgraphicsResource = Ptr{CUgraphicsResource_st}
const CUtexObject = Culonglong
const CUsurfObject = Culonglong
const CUextMemory_st = Cvoid
const CUexternalMemory = Ptr{CUextMemory_st}
const CUextSemaphore_st = Cvoid
const CUexternalSemaphore = Ptr{CUextSemaphore_st}
const CUgraph_st = Cvoid
const CUgraph = Ptr{CUgraph_st}
const CUgraphNode_st = Cvoid
const CUgraphNode = Ptr{CUgraphNode_st}
const CUgraphExec_st = Cvoid
const CUgraphExec = Ptr{CUgraphExec_st}

struct CUuuid_st
    bytes::NTuple{16, UInt8}
end

const CUuuid = CUuuid_st

struct CUipcEventHandle_st
    reserved::NTuple{64, UInt8}
end

const CUipcEventHandle = CUipcEventHandle_st

struct CUipcMemHandle_st
    reserved::NTuple{64, UInt8}
end

const CUipcMemHandle = CUipcMemHandle_st

@cenum CUipcMem_flags_enum::UInt32 begin
    CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS = 1
end

const CUipcMem_flags = CUipcMem_flags_enum

@cenum CUmemAttach_flags_enum::UInt32 begin
    CU_MEM_ATTACH_GLOBAL = 1
    CU_MEM_ATTACH_HOST = 2
    CU_MEM_ATTACH_SINGLE = 4
end

const CUmemAttach_flags = CUmemAttach_flags_enum

@cenum CUctx_flags_enum::UInt32 begin
    CU_CTX_SCHED_AUTO = 0
    CU_CTX_SCHED_SPIN = 1
    CU_CTX_SCHED_YIELD = 2
    CU_CTX_SCHED_BLOCKING_SYNC = 4
    CU_CTX_BLOCKING_SYNC = 4
    CU_CTX_SCHED_MASK = 7
    CU_CTX_MAP_HOST = 8
    CU_CTX_LMEM_RESIZE_TO_MAX = 16
    CU_CTX_FLAGS_MASK = 31
end

const CUctx_flags = CUctx_flags_enum

@cenum CUstream_flags_enum::UInt32 begin
    CU_STREAM_DEFAULT = 0
    CU_STREAM_NON_BLOCKING = 1
end

const CUstream_flags = CUstream_flags_enum

@cenum CUevent_flags_enum::UInt32 begin
    CU_EVENT_DEFAULT = 0
    CU_EVENT_BLOCKING_SYNC = 1
    CU_EVENT_DISABLE_TIMING = 2
    CU_EVENT_INTERPROCESS = 4
end

const CUevent_flags = CUevent_flags_enum

@cenum CUstreamWaitValue_flags_enum::UInt32 begin
    CU_STREAM_WAIT_VALUE_GEQ = 0
    CU_STREAM_WAIT_VALUE_EQ = 1
    CU_STREAM_WAIT_VALUE_AND = 2
    CU_STREAM_WAIT_VALUE_NOR = 3
    CU_STREAM_WAIT_VALUE_FLUSH = 1073741824
end

const CUstreamWaitValue_flags = CUstreamWaitValue_flags_enum

@cenum CUstreamWriteValue_flags_enum::UInt32 begin
    CU_STREAM_WRITE_VALUE_DEFAULT = 0
    CU_STREAM_WRITE_VALUE_NO_MEMORY_BARRIER = 1
end

@cenum CUoccupancy_flags_enum::UInt32 begin
    CU_OCCUPANCY_DEFAULT = 0
    CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE = 1
end

const CUoccupancy_flags = CUoccupancy_flags_enum

@cenum CUarray_format_enum::UInt32 begin
    CU_AD_FORMAT_UNSIGNED_INT8 = 1
    CU_AD_FORMAT_UNSIGNED_INT16 = 2
    CU_AD_FORMAT_UNSIGNED_INT32 = 3
    CU_AD_FORMAT_SIGNED_INT8 = 8
    CU_AD_FORMAT_SIGNED_INT16 = 9
    CU_AD_FORMAT_SIGNED_INT32 = 10
    CU_AD_FORMAT_HALF = 16
    CU_AD_FORMAT_FLOAT = 32
end

const CUarray_format = CUarray_format_enum

@cenum CUaddress_mode_enum::UInt32 begin
    CU_TR_ADDRESS_MODE_WRAP = 0
    CU_TR_ADDRESS_MODE_CLAMP = 1
    CU_TR_ADDRESS_MODE_MIRROR = 2
    CU_TR_ADDRESS_MODE_BORDER = 3
end

const CUaddress_mode = CUaddress_mode_enum

@cenum CUfilter_mode_enum::UInt32 begin
    CU_TR_FILTER_MODE_POINT = 0
    CU_TR_FILTER_MODE_LINEAR = 1
end

const CUfilter_mode = CUfilter_mode_enum

@cenum CUdevice_attribute_enum::UInt32 begin
    CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 1
    CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X = 2
    CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y = 3
    CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z = 4
    CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X = 5
    CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y = 6
    CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z = 7
    CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK = 8
    CU_DEVICE_ATTRIBUTE_SHARED_MEMORY_PER_BLOCK = 8
    CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY = 9
    CU_DEVICE_ATTRIBUTE_WARP_SIZE = 10
    CU_DEVICE_ATTRIBUTE_MAX_PITCH = 11
    CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK = 12
    CU_DEVICE_ATTRIBUTE_REGISTERS_PER_BLOCK = 12
    CU_DEVICE_ATTRIBUTE_CLOCK_RATE = 13
    CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT = 14
    CU_DEVICE_ATTRIBUTE_GPU_OVERLAP = 15
    CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT = 16
    CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT = 17
    CU_DEVICE_ATTRIBUTE_INTEGRATED = 18
    CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY = 19
    CU_DEVICE_ATTRIBUTE_COMPUTE_MODE = 20
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH = 21
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_WIDTH = 22
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_HEIGHT = 23
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH = 24
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT = 25
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH = 26
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH = 27
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT = 28
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS = 29
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_WIDTH = 27
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_HEIGHT = 28
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES = 29
    CU_DEVICE_ATTRIBUTE_SURFACE_ALIGNMENT = 30
    CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS = 31
    CU_DEVICE_ATTRIBUTE_ECC_ENABLED = 32
    CU_DEVICE_ATTRIBUTE_PCI_BUS_ID = 33
    CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID = 34
    CU_DEVICE_ATTRIBUTE_TCC_DRIVER = 35
    CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE = 36
    CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH = 37
    CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE = 38
    CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR = 39
    CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT = 40
    CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING = 41
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_WIDTH = 42
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_LAYERS = 43
    CU_DEVICE_ATTRIBUTE_CAN_TEX2D_GATHER = 44
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_WIDTH = 45
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_HEIGHT = 46
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH_ALTERNATE = 47
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT_ALTERNATE = 48
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH_ALTERNATE = 49
    CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID = 50
    CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT = 51
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_WIDTH = 52
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_WIDTH = 53
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_LAYERS = 54
    CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_WIDTH = 55
    CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_WIDTH = 56
    CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_HEIGHT = 57
    CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_WIDTH = 58
    CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_HEIGHT = 59
    CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_DEPTH = 60
    CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_WIDTH = 61
    CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_LAYERS = 62
    CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_WIDTH = 63
    CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_HEIGHT = 64
    CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_LAYERS = 65
    CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_WIDTH = 66
    CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_WIDTH = 67
    CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_LAYERS = 68
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH = 69
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH = 70
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT = 71
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH = 72
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_WIDTH = 73
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_HEIGHT = 74
    CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR = 75
    CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR = 76
    CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH = 77
    CU_DEVICE_ATTRIBUTE_STREAM_PRIORITIES_SUPPORTED = 78
    CU_DEVICE_ATTRIBUTE_GLOBAL_L1_CACHE_SUPPORTED = 79
    CU_DEVICE_ATTRIBUTE_LOCAL_L1_CACHE_SUPPORTED = 80
    CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR = 81
    CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR = 82
    CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY = 83
    CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD = 84
    CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD_GROUP_ID = 85
    CU_DEVICE_ATTRIBUTE_HOST_NATIVE_ATOMIC_SUPPORTED = 86
    CU_DEVICE_ATTRIBUTE_SINGLE_TO_DOUBLE_PRECISION_PERF_RATIO = 87
    CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS = 88
    CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS = 89
    CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED = 90
    CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM = 91
    CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_MEM_OPS = 92
    CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS = 93
    CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_WAIT_VALUE_NOR = 94
    CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH = 95
    CU_DEVICE_ATTRIBUTE_COOPERATIVE_MULTI_DEVICE_LAUNCH = 96
    CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN = 97
    CU_DEVICE_ATTRIBUTE_CAN_FLUSH_REMOTE_WRITES = 98
    CU_DEVICE_ATTRIBUTE_HOST_REGISTER_SUPPORTED = 99
    CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES = 100
    CU_DEVICE_ATTRIBUTE_DIRECT_MANAGED_MEM_ACCESS_FROM_HOST = 101
    CU_DEVICE_ATTRIBUTE_MAX = 102
end

const CUdevice_attribute = CUdevice_attribute_enum

struct CUdevprop_st
    maxThreadsPerBlock::Cint
    maxThreadsDim::NTuple{3, Cint}
    maxGridSize::NTuple{3, Cint}
    sharedMemPerBlock::Cint
    totalConstantMemory::Cint
    SIMDWidth::Cint
    memPitch::Cint
    regsPerBlock::Cint
    clockRate::Cint
    textureAlign::Cint
end

const CUdevprop = CUdevprop_st

@cenum CUpointer_attribute_enum::UInt32 begin
    CU_POINTER_ATTRIBUTE_CONTEXT = 1
    CU_POINTER_ATTRIBUTE_MEMORY_TYPE = 2
    CU_POINTER_ATTRIBUTE_DEVICE_POINTER = 3
    CU_POINTER_ATTRIBUTE_HOST_POINTER = 4
    CU_POINTER_ATTRIBUTE_P2P_TOKENS = 5
    CU_POINTER_ATTRIBUTE_SYNC_MEMOPS = 6
    CU_POINTER_ATTRIBUTE_BUFFER_ID = 7
    CU_POINTER_ATTRIBUTE_IS_MANAGED = 8
    CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL = 9
end

const CUpointer_attribute = CUpointer_attribute_enum

@cenum CUfunction_attribute_enum::UInt32 begin
    CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 0
    CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES = 1
    CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES = 2
    CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES = 3
    CU_FUNC_ATTRIBUTE_NUM_REGS = 4
    CU_FUNC_ATTRIBUTE_PTX_VERSION = 5
    CU_FUNC_ATTRIBUTE_BINARY_VERSION = 6
    CU_FUNC_ATTRIBUTE_CACHE_MODE_CA = 7
    CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES = 8
    CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT = 9
    CU_FUNC_ATTRIBUTE_MAX = 10
end

const CUfunction_attribute = CUfunction_attribute_enum

@cenum CUfunc_cache_enum::UInt32 begin
    CU_FUNC_CACHE_PREFER_NONE = 0
    CU_FUNC_CACHE_PREFER_SHARED = 1
    CU_FUNC_CACHE_PREFER_L1 = 2
    CU_FUNC_CACHE_PREFER_EQUAL = 3
end

const CUfunc_cache = CUfunc_cache_enum

@cenum CUsharedconfig_enum::UInt32 begin
    CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE = 0
    CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE = 1
    CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE = 2
end

const CUsharedconfig = CUsharedconfig_enum

@cenum CUshared_carveout_enum::Int32 begin
    CU_SHAREDMEM_CARVEOUT_DEFAULT = -1
    CU_SHAREDMEM_CARVEOUT_MAX_SHARED = 100
    CU_SHAREDMEM_CARVEOUT_MAX_L1 = 0
end

const CUshared_carveout = CUshared_carveout_enum

@cenum CUmemorytype_enum::UInt32 begin
    CU_MEMORYTYPE_HOST = 1
    CU_MEMORYTYPE_DEVICE = 2
    CU_MEMORYTYPE_ARRAY = 3
    CU_MEMORYTYPE_UNIFIED = 4
end

const CUmemorytype = CUmemorytype_enum

@cenum CUcomputemode_enum::UInt32 begin
    CU_COMPUTEMODE_DEFAULT = 0
    CU_COMPUTEMODE_PROHIBITED = 2
    CU_COMPUTEMODE_EXCLUSIVE_PROCESS = 3
end

const CUcomputemode = CUcomputemode_enum

@cenum CUmem_advise_enum::UInt32 begin
    CU_MEM_ADVISE_SET_READ_MOSTLY = 1
    CU_MEM_ADVISE_UNSET_READ_MOSTLY = 2
    CU_MEM_ADVISE_SET_PREFERRED_LOCATION = 3
    CU_MEM_ADVISE_UNSET_PREFERRED_LOCATION = 4
    CU_MEM_ADVISE_SET_ACCESSED_BY = 5
    CU_MEM_ADVISE_UNSET_ACCESSED_BY = 6
end

const CUmem_advise = CUmem_advise_enum

@cenum CUmem_range_attribute_enum::UInt32 begin
    CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY = 1
    CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION = 2
    CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY = 3
    CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION = 4
end

const CUmem_range_attribute = CUmem_range_attribute_enum

@cenum CUjit_option_enum::UInt32 begin
    CU_JIT_MAX_REGISTERS = 0
    CU_JIT_THREADS_PER_BLOCK = 1
    CU_JIT_WALL_TIME = 2
    CU_JIT_INFO_LOG_BUFFER = 3
    CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES = 4
    CU_JIT_ERROR_LOG_BUFFER = 5
    CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES = 6
    CU_JIT_OPTIMIZATION_LEVEL = 7
    CU_JIT_TARGET_FROM_CUCONTEXT = 8
    CU_JIT_TARGET = 9
    CU_JIT_FALLBACK_STRATEGY = 10
    CU_JIT_GENERATE_DEBUG_INFO = 11
    CU_JIT_LOG_VERBOSE = 12
    CU_JIT_GENERATE_LINE_INFO = 13
    CU_JIT_CACHE_MODE = 14
    CU_JIT_NEW_SM3X_OPT = 15
    CU_JIT_FAST_COMPILE = 16
    CU_JIT_GLOBAL_SYMBOL_NAMES = 17
    CU_JIT_GLOBAL_SYMBOL_ADDRESSES = 18
    CU_JIT_GLOBAL_SYMBOL_COUNT = 19
    CU_JIT_NUM_OPTIONS = 20
end

const CUjit_option = CUjit_option_enum

@cenum CUjit_target_enum::UInt32 begin
    CU_TARGET_COMPUTE_20 = 20
    CU_TARGET_COMPUTE_21 = 21
    CU_TARGET_COMPUTE_30 = 30
    CU_TARGET_COMPUTE_32 = 32
    CU_TARGET_COMPUTE_35 = 35
    CU_TARGET_COMPUTE_37 = 37
    CU_TARGET_COMPUTE_50 = 50
    CU_TARGET_COMPUTE_52 = 52
    CU_TARGET_COMPUTE_53 = 53
    CU_TARGET_COMPUTE_60 = 60
    CU_TARGET_COMPUTE_61 = 61
    CU_TARGET_COMPUTE_62 = 62
    CU_TARGET_COMPUTE_70 = 70
    CU_TARGET_COMPUTE_72 = 72
    CU_TARGET_COMPUTE_75 = 75
end

const CUjit_target = CUjit_target_enum

@cenum CUjit_fallback_enum::UInt32 begin
    CU_PREFER_PTX = 0
    CU_PREFER_BINARY = 1
end

const CUjit_fallback = CUjit_fallback_enum

@cenum CUjit_cacheMode_enum::UInt32 begin
    CU_JIT_CACHE_OPTION_NONE = 0
    CU_JIT_CACHE_OPTION_CG = 1
    CU_JIT_CACHE_OPTION_CA = 2
end

const CUjit_cacheMode = CUjit_cacheMode_enum

@cenum CUjitInputType_enum::UInt32 begin
    CU_JIT_INPUT_CUBIN = 0
    CU_JIT_INPUT_PTX = 1
    CU_JIT_INPUT_FATBINARY = 2
    CU_JIT_INPUT_OBJECT = 3
    CU_JIT_INPUT_LIBRARY = 4
    CU_JIT_NUM_INPUT_TYPES = 5
end

const CUjitInputType = CUjitInputType_enum
const CUlinkState_st = Cvoid
const CUlinkState = Ptr{CUlinkState_st}

@cenum CUgraphicsRegisterFlags_enum::UInt32 begin
    CU_GRAPHICS_REGISTER_FLAGS_NONE = 0
    CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY = 1
    CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD = 2
    CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST = 4
    CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER = 8
end

const CUgraphicsRegisterFlags = CUgraphicsRegisterFlags_enum

@cenum CUgraphicsMapResourceFlags_enum::UInt32 begin
    CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE = 0
    CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY = 1
    CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD = 2
end

const CUgraphicsMapResourceFlags = CUgraphicsMapResourceFlags_enum

@cenum CUarray_cubemap_face_enum::UInt32 begin
    CU_CUBEMAP_FACE_POSITIVE_X = 0
    CU_CUBEMAP_FACE_NEGATIVE_X = 1
    CU_CUBEMAP_FACE_POSITIVE_Y = 2
    CU_CUBEMAP_FACE_NEGATIVE_Y = 3
    CU_CUBEMAP_FACE_POSITIVE_Z = 4
    CU_CUBEMAP_FACE_NEGATIVE_Z = 5
end

const CUarray_cubemap_face = CUarray_cubemap_face_enum

@cenum CUlimit_enum::UInt32 begin
    CU_LIMIT_STACK_SIZE = 0
    CU_LIMIT_PRINTF_FIFO_SIZE = 1
    CU_LIMIT_MALLOC_HEAP_SIZE = 2
    CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH = 3
    CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT = 4
    CU_LIMIT_MAX_L2_FETCH_GRANULARITY = 5
    CU_LIMIT_MAX = 6
end

const CUlimit = CUlimit_enum

@cenum CUresourcetype_enum::UInt32 begin
    CU_RESOURCE_TYPE_ARRAY = 0
    CU_RESOURCE_TYPE_MIPMAPPED_ARRAY = 1
    CU_RESOURCE_TYPE_LINEAR = 2
    CU_RESOURCE_TYPE_PITCH2D = 3
end

const CUresourcetype = CUresourcetype_enum
const CUhostFn = Ptr{Cvoid}

struct CUDA_KERNEL_NODE_PARAMS_st
    func::CUfunction
    gridDimX::UInt32
    gridDimY::UInt32
    gridDimZ::UInt32
    blockDimX::UInt32
    blockDimY::UInt32
    blockDimZ::UInt32
    sharedMemBytes::UInt32
    kernelParams::Ptr{Ptr{Cvoid}}
    extra::Ptr{Ptr{Cvoid}}
end

const CUDA_KERNEL_NODE_PARAMS = CUDA_KERNEL_NODE_PARAMS_st

struct CUDA_MEMSET_NODE_PARAMS_st
    dst::CUdeviceptr
    pitch::Csize_t
    value::UInt32
    elementSize::UInt32
    width::Csize_t
    height::Csize_t
end

const CUDA_MEMSET_NODE_PARAMS = CUDA_MEMSET_NODE_PARAMS_st

struct CUDA_HOST_NODE_PARAMS_st
    fn::CUhostFn
    userData::Ptr{Cvoid}
end

const CUDA_HOST_NODE_PARAMS = CUDA_HOST_NODE_PARAMS_st

@cenum CUgraphNodeType_enum::UInt32 begin
    CU_GRAPH_NODE_TYPE_KERNEL = 0
    CU_GRAPH_NODE_TYPE_MEMCPY = 1
    CU_GRAPH_NODE_TYPE_MEMSET = 2
    CU_GRAPH_NODE_TYPE_HOST = 3
    CU_GRAPH_NODE_TYPE_GRAPH = 4
    CU_GRAPH_NODE_TYPE_EMPTY = 5
    CU_GRAPH_NODE_TYPE_COUNT = 6
end

const CUgraphNodeType = CUgraphNodeType_enum

@cenum CUstreamCaptureStatus_enum::UInt32 begin
    CU_STREAM_CAPTURE_STATUS_NONE = 0
    CU_STREAM_CAPTURE_STATUS_ACTIVE = 1
    CU_STREAM_CAPTURE_STATUS_INVALIDATED = 2
end

const CUstreamCaptureStatus = CUstreamCaptureStatus_enum

@cenum CUstreamCaptureMode_enum::UInt32 begin
    CU_STREAM_CAPTURE_MODE_GLOBAL = 0
    CU_STREAM_CAPTURE_MODE_THREAD_LOCAL = 1
    CU_STREAM_CAPTURE_MODE_RELAXED = 2
end

const CUstreamCaptureMode = CUstreamCaptureMode_enum

@cenum cudaError_enum::UInt32 begin
    CUDA_SUCCESS = 0
    CUDA_ERROR_INVALID_VALUE = 1
    CUDA_ERROR_OUT_OF_MEMORY = 2
    CUDA_ERROR_NOT_INITIALIZED = 3
    CUDA_ERROR_DEINITIALIZED = 4
    CUDA_ERROR_PROFILER_DISABLED = 5
    CUDA_ERROR_PROFILER_NOT_INITIALIZED = 6
    CUDA_ERROR_PROFILER_ALREADY_STARTED = 7
    CUDA_ERROR_PROFILER_ALREADY_STOPPED = 8
    CUDA_ERROR_NO_DEVICE = 100
    CUDA_ERROR_INVALID_DEVICE = 101
    CUDA_ERROR_INVALID_IMAGE = 200
    CUDA_ERROR_INVALID_CONTEXT = 201
    CUDA_ERROR_CONTEXT_ALREADY_CURRENT = 202
    CUDA_ERROR_MAP_FAILED = 205
    CUDA_ERROR_UNMAP_FAILED = 206
    CUDA_ERROR_ARRAY_IS_MAPPED = 207
    CUDA_ERROR_ALREADY_MAPPED = 208
    CUDA_ERROR_NO_BINARY_FOR_GPU = 209
    CUDA_ERROR_ALREADY_ACQUIRED = 210
    CUDA_ERROR_NOT_MAPPED = 211
    CUDA_ERROR_NOT_MAPPED_AS_ARRAY = 212
    CUDA_ERROR_NOT_MAPPED_AS_POINTER = 213
    CUDA_ERROR_ECC_UNCORRECTABLE = 214
    CUDA_ERROR_UNSUPPORTED_LIMIT = 215
    CUDA_ERROR_CONTEXT_ALREADY_IN_USE = 216
    CUDA_ERROR_PEER_ACCESS_UNSUPPORTED = 217
    CUDA_ERROR_INVALID_PTX = 218
    CUDA_ERROR_INVALID_GRAPHICS_CONTEXT = 219
    CUDA_ERROR_NVLINK_UNCORRECTABLE = 220
    CUDA_ERROR_JIT_COMPILER_NOT_FOUND = 221
    CUDA_ERROR_INVALID_SOURCE = 300
    CUDA_ERROR_FILE_NOT_FOUND = 301
    CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND = 302
    CUDA_ERROR_SHARED_OBJECT_INIT_FAILED = 303
    CUDA_ERROR_OPERATING_SYSTEM = 304
    CUDA_ERROR_INVALID_HANDLE = 400
    CUDA_ERROR_ILLEGAL_STATE = 401
    CUDA_ERROR_NOT_FOUND = 500
    CUDA_ERROR_NOT_READY = 600
    CUDA_ERROR_ILLEGAL_ADDRESS = 700
    CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES = 701
    CUDA_ERROR_LAUNCH_TIMEOUT = 702
    CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING = 703
    CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED = 704
    CUDA_ERROR_PEER_ACCESS_NOT_ENABLED = 705
    CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE = 708
    CUDA_ERROR_CONTEXT_IS_DESTROYED = 709
    CUDA_ERROR_ASSERT = 710
    CUDA_ERROR_TOO_MANY_PEERS = 711
    CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED = 712
    CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED = 713
    CUDA_ERROR_HARDWARE_STACK_ERROR = 714
    CUDA_ERROR_ILLEGAL_INSTRUCTION = 715
    CUDA_ERROR_MISALIGNED_ADDRESS = 716
    CUDA_ERROR_INVALID_ADDRESS_SPACE = 717
    CUDA_ERROR_INVALID_PC = 718
    CUDA_ERROR_LAUNCH_FAILED = 719
    CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE = 720
    CUDA_ERROR_NOT_PERMITTED = 800
    CUDA_ERROR_NOT_SUPPORTED = 801
    CUDA_ERROR_SYSTEM_NOT_READY = 802
    CUDA_ERROR_SYSTEM_DRIVER_MISMATCH = 803
    CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE = 804
    CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED = 900
    CUDA_ERROR_STREAM_CAPTURE_INVALIDATED = 901
    CUDA_ERROR_STREAM_CAPTURE_MERGE = 902
    CUDA_ERROR_STREAM_CAPTURE_UNMATCHED = 903
    CUDA_ERROR_STREAM_CAPTURE_UNJOINED = 904
    CUDA_ERROR_STREAM_CAPTURE_ISOLATION = 905
    CUDA_ERROR_STREAM_CAPTURE_IMPLICIT = 906
    CUDA_ERROR_CAPTURED_EVENT = 907
    CUDA_ERROR_STREAM_CAPTURE_WRONG_THREAD = 908
    CUDA_ERROR_UNKNOWN = 999
end

const CUresult = cudaError_enum

@cenum CUdevice_P2PAttribute_enum::UInt32 begin
    CU_DEVICE_P2P_ATTRIBUTE_PERFORMANCE_RANK = 1
    CU_DEVICE_P2P_ATTRIBUTE_ACCESS_SUPPORTED = 2
    CU_DEVICE_P2P_ATTRIBUTE_NATIVE_ATOMIC_SUPPORTED = 3
    CU_DEVICE_P2P_ATTRIBUTE_ACCESS_ACCESS_SUPPORTED = 4
    CU_DEVICE_P2P_ATTRIBUTE_CUDA_ARRAY_ACCESS_SUPPORTED = 4
end

const CUdevice_P2PAttribute = CUdevice_P2PAttribute_enum
const CUstreamCallback = Ptr{Cvoid}
const CUoccupancyB2DSize = Ptr{Cvoid}

struct CUDA_MEMCPY2D_st
    srcXInBytes::Csize_t
    srcY::Csize_t
    srcMemoryType::CUmemorytype
    srcHost::Ptr{Cvoid}
    srcDevice::CUdeviceptr
    srcArray::CUarray
    srcPitch::Csize_t
    dstXInBytes::Csize_t
    dstY::Csize_t
    dstMemoryType::CUmemorytype
    dstHost::Ptr{Cvoid}
    dstDevice::CUdeviceptr
    dstArray::CUarray
    dstPitch::Csize_t
    WidthInBytes::Csize_t
    Height::Csize_t
end

const CUDA_MEMCPY2D = CUDA_MEMCPY2D_st

struct CUDA_MEMCPY3D_st
    srcXInBytes::Csize_t
    srcY::Csize_t
    srcZ::Csize_t
    srcLOD::Csize_t
    srcMemoryType::CUmemorytype
    srcHost::Ptr{Cvoid}
    srcDevice::CUdeviceptr
    srcArray::CUarray
    reserved0::Ptr{Cvoid}
    srcPitch::Csize_t
    srcHeight::Csize_t
    dstXInBytes::Csize_t
    dstY::Csize_t
    dstZ::Csize_t
    dstLOD::Csize_t
    dstMemoryType::CUmemorytype
    dstHost::Ptr{Cvoid}
    dstDevice::CUdeviceptr
    dstArray::CUarray
    reserved1::Ptr{Cvoid}
    dstPitch::Csize_t
    dstHeight::Csize_t
    WidthInBytes::Csize_t
    Height::Csize_t
    Depth::Csize_t
end

const CUDA_MEMCPY3D = CUDA_MEMCPY3D_st

struct CUDA_MEMCPY3D_PEER_st
    srcXInBytes::Csize_t
    srcY::Csize_t
    srcZ::Csize_t
    srcLOD::Csize_t
    srcMemoryType::CUmemorytype
    srcHost::Ptr{Cvoid}
    srcDevice::CUdeviceptr
    srcArray::CUarray
    srcContext::CUcontext
    srcPitch::Csize_t
    srcHeight::Csize_t
    dstXInBytes::Csize_t
    dstY::Csize_t
    dstZ::Csize_t
    dstLOD::Csize_t
    dstMemoryType::CUmemorytype
    dstHost::Ptr{Cvoid}
    dstDevice::CUdeviceptr
    dstArray::CUarray
    dstContext::CUcontext
    dstPitch::Csize_t
    dstHeight::Csize_t
    WidthInBytes::Csize_t
    Height::Csize_t
    Depth::Csize_t
end

const CUDA_MEMCPY3D_PEER = CUDA_MEMCPY3D_PEER_st

struct CUDA_ARRAY_DESCRIPTOR_st
    Width::Csize_t
    Height::Csize_t
    Format::CUarray_format
    NumChannels::UInt32
end

const CUDA_ARRAY_DESCRIPTOR = CUDA_ARRAY_DESCRIPTOR_st

struct CUDA_ARRAY3D_DESCRIPTOR_st
    Width::Csize_t
    Height::Csize_t
    Depth::Csize_t
    Format::CUarray_format
    NumChannels::UInt32
    Flags::UInt32
end

const CUDA_ARRAY3D_DESCRIPTOR = CUDA_ARRAY3D_DESCRIPTOR_st

struct ANONYMOUS2_reserved
    reserved::NTuple{32, Cint}
end

struct ANONYMOUS1_res
    reserved::ANONYMOUS2_reserved
end

struct CUDA_RESOURCE_DESC_st
    resType::CUresourcetype
    res::ANONYMOUS1_res
    flags::UInt32
end

const CUDA_RESOURCE_DESC = CUDA_RESOURCE_DESC_st

struct CUDA_TEXTURE_DESC_st
    addressMode::NTuple{3, CUaddress_mode}
    filterMode::CUfilter_mode
    flags::UInt32
    maxAnisotropy::UInt32
    mipmapFilterMode::CUfilter_mode
    mipmapLevelBias::Cfloat
    minMipmapLevelClamp::Cfloat
    maxMipmapLevelClamp::Cfloat
    borderColor::NTuple{4, Cfloat}
    reserved::NTuple{12, Cint}
end

const CUDA_TEXTURE_DESC = CUDA_TEXTURE_DESC_st

@cenum CUresourceViewFormat_enum::UInt32 begin
    CU_RES_VIEW_FORMAT_NONE = 0
    CU_RES_VIEW_FORMAT_UINT_1X8 = 1
    CU_RES_VIEW_FORMAT_UINT_2X8 = 2
    CU_RES_VIEW_FORMAT_UINT_4X8 = 3
    CU_RES_VIEW_FORMAT_SINT_1X8 = 4
    CU_RES_VIEW_FORMAT_SINT_2X8 = 5
    CU_RES_VIEW_FORMAT_SINT_4X8 = 6
    CU_RES_VIEW_FORMAT_UINT_1X16 = 7
    CU_RES_VIEW_FORMAT_UINT_2X16 = 8
    CU_RES_VIEW_FORMAT_UINT_4X16 = 9
    CU_RES_VIEW_FORMAT_SINT_1X16 = 10
    CU_RES_VIEW_FORMAT_SINT_2X16 = 11
    CU_RES_VIEW_FORMAT_SINT_4X16 = 12
    CU_RES_VIEW_FORMAT_UINT_1X32 = 13
    CU_RES_VIEW_FORMAT_UINT_2X32 = 14
    CU_RES_VIEW_FORMAT_UINT_4X32 = 15
    CU_RES_VIEW_FORMAT_SINT_1X32 = 16
    CU_RES_VIEW_FORMAT_SINT_2X32 = 17
    CU_RES_VIEW_FORMAT_SINT_4X32 = 18
    CU_RES_VIEW_FORMAT_FLOAT_1X16 = 19
    CU_RES_VIEW_FORMAT_FLOAT_2X16 = 20
    CU_RES_VIEW_FORMAT_FLOAT_4X16 = 21
    CU_RES_VIEW_FORMAT_FLOAT_1X32 = 22
    CU_RES_VIEW_FORMAT_FLOAT_2X32 = 23
    CU_RES_VIEW_FORMAT_FLOAT_4X32 = 24
    CU_RES_VIEW_FORMAT_UNSIGNED_BC1 = 25
    CU_RES_VIEW_FORMAT_UNSIGNED_BC2 = 26
    CU_RES_VIEW_FORMAT_UNSIGNED_BC3 = 27
    CU_RES_VIEW_FORMAT_UNSIGNED_BC4 = 28
    CU_RES_VIEW_FORMAT_SIGNED_BC4 = 29
    CU_RES_VIEW_FORMAT_UNSIGNED_BC5 = 30
    CU_RES_VIEW_FORMAT_SIGNED_BC5 = 31
    CU_RES_VIEW_FORMAT_UNSIGNED_BC6H = 32
    CU_RES_VIEW_FORMAT_SIGNED_BC6H = 33
    CU_RES_VIEW_FORMAT_UNSIGNED_BC7 = 34
end

const CUresourceViewFormat = CUresourceViewFormat_enum

struct CUDA_RESOURCE_VIEW_DESC_st
    format::CUresourceViewFormat
    width::Csize_t
    height::Csize_t
    depth::Csize_t
    firstMipmapLevel::UInt32
    lastMipmapLevel::UInt32
    firstLayer::UInt32
    lastLayer::UInt32
    reserved::NTuple{16, UInt32}
end

const CUDA_RESOURCE_VIEW_DESC = CUDA_RESOURCE_VIEW_DESC_st

struct CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_st
    p2pToken::Culonglong
    vaSpaceToken::UInt32
end

const CUDA_POINTER_ATTRIBUTE_P2P_TOKENS = CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_st

struct CUDA_LAUNCH_PARAMS_st
    _function::CUfunction
    gridDimX::UInt32
    gridDimY::UInt32
    gridDimZ::UInt32
    blockDimX::UInt32
    blockDimY::UInt32
    blockDimZ::UInt32
    sharedMemBytes::UInt32
    hStream::CUstream
    kernelParams::Ptr{Ptr{Cvoid}}
end

const CUDA_LAUNCH_PARAMS = CUDA_LAUNCH_PARAMS_st

@cenum CUexternalMemoryHandleType_enum::UInt32 begin
    CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD = 1
    CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32 = 2
    CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT = 3
    CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP = 4
    CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE = 5
end

const CUexternalMemoryHandleType = CUexternalMemoryHandleType_enum

struct ANONYMOUS4_win32
    handle::Ptr{Cvoid}
    name::Ptr{Cvoid}
end

struct ANONYMOUS3_handle
    win32::ANONYMOUS4_win32
end

struct CUDA_EXTERNAL_MEMORY_HANDLE_DESC_st
    type::CUexternalMemoryHandleType
    handle::ANONYMOUS3_handle
    size::Culonglong
    flags::UInt32
    reserved::NTuple{16, UInt32}
end

const CUDA_EXTERNAL_MEMORY_HANDLE_DESC = CUDA_EXTERNAL_MEMORY_HANDLE_DESC_st

struct CUDA_EXTERNAL_MEMORY_BUFFER_DESC_st
    offset::Culonglong
    size::Culonglong
    flags::UInt32
    reserved::NTuple{16, UInt32}
end

const CUDA_EXTERNAL_MEMORY_BUFFER_DESC = CUDA_EXTERNAL_MEMORY_BUFFER_DESC_st

struct CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_st
    offset::Culonglong
    arrayDesc::CUDA_ARRAY3D_DESCRIPTOR
    numLevels::UInt32
    reserved::NTuple{16, UInt32}
end

const CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC = CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_st

@cenum CUexternalSemaphoreHandleType_enum::UInt32 begin
    CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD = 1
    CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32 = 2
    CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT = 3
    CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE = 4
end

const CUexternalSemaphoreHandleType = CUexternalSemaphoreHandleType_enum

struct ANONYMOUS6_win32
    handle::Ptr{Cvoid}
    name::Ptr{Cvoid}
end

struct ANONYMOUS5_handle
    win32::ANONYMOUS6_win32
end

struct CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_st
    type::CUexternalSemaphoreHandleType
    handle::ANONYMOUS5_handle
    flags::UInt32
    reserved::NTuple{16, UInt32}
end

const CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC = CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_st

struct ANONYMOUS8_fence
    value::Culonglong
end

struct ANONYMOUS7_params
    fence::ANONYMOUS8_fence
    reserved::NTuple{16, UInt32}
end

struct CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_st
    params::ANONYMOUS7_params
    flags::UInt32
    reserved::NTuple{16, UInt32}
end

const CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS = CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_st

struct ANONYMOUS10_fence
    value::Culonglong
end

struct ANONYMOUS9_params
    fence::ANONYMOUS10_fence
    reserved::NTuple{16, UInt32}
end

struct CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_st
    params::ANONYMOUS9_params
    flags::UInt32
    reserved::NTuple{16, UInt32}
end

const CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS = CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_st

@cenum CUoutput_mode_enum::UInt32 begin
    CU_OUT_KEY_VALUE_PAIR = 0
    CU_OUT_CSV = 1
end

const CUoutput_mode = CUoutput_mode_enum


text:
function output_graph_crossover(ind1::CGPInd, ind2::CGPInd)
    p1_nodes = Array{Int64}(undef, 0)
    p2_nodes = Array{Int64}(undef, 0)
    output_genes = Array{Float64}(undef, 0)
    for output in 1:ind1.n_out
        if rand() < 0.5
            append!(p1_nodes, get_output_trace(ind1, output))
            append!(output_genes, [ind1.chromosome[end-ind1.n_out+output]])
        else
            append!(p2_nodes, get_output_trace(ind2, output))
            append!(output_genes, [ind2.chromosome[end-ind2.n_out+output]])
        end
    end
    p1_nodes = sort!(unique(p1_nodes))
    p2_nodes = sort!(unique(p2_nodes))
    p1_nodes = p1_nodes[p1_nodes.>ind1.n_in]
    p2_nodes = p2_nodes[p2_nodes.>ind1.n_in]
    genes = [get_genes(ind1, p1_nodes)..., get_genes(ind2, p2_nodes)...,output_genes...]
    genes
end

function subgraph_crossover(ind1::CGPInd, ind2::CGPInd)
    # Take subgraphs from both parents equally, adding all nodes of the chosen
    # subgraphs to the child.
    fc1 = forward_connections(ind1)
    fc2 = forward_connections(ind2)
    c1_nodes = []; c2_nodes = []
    for i in (ind1.n_in+1):min(length(ind1.nodes), length(ind2.nodes))
        if rand(Bool)
            append!(c1_nodes, fc1[i])
        else
            append!(c2_nodes, fc2[i])
        end
    end
    if length(ind1.nodes) < length(ind2.nodes)
        for i in length(ind1.nodes):length(ind2.nodes)
            if rand(Bool)
                append!(ind2.nodes, fc2[i])
            end
        end
    elseif length(ind2.nodes) < length(ind1.nodes)
        for i in length(ind2.nodes):length(ind1.nodes)
            if rand(Bool)
                append!(c1_nodes, fc1[i])
            end
        end
    end
    c1_nodes = Array{Int64}(unique(intersect(collect((ind1.n_in+1):length(ind1.nodes)), c1_nodes)))
    c2_nodes = Array{Int64}(unique(intersect(collect((ind2.n_in+1):length(ind2.nodes)), c2_nodes)))
    genes = zeros(ind1.n_out)
    for i in 1:ind1.n_out
        if rand(Bool)
            genes[i] = ind1.chromosome[end-ind1.n_out+i]
        else
            genes[i] = ind2.chromosome[end-ind2.n_out+i]
        end
    end
    if length(c1_nodes) > 0
        genes = [get_genes(ind1, c1_nodes);genes]
    end
    if length(c2_nodes) > 0
        genes = [get_genes(ind2, c2_nodes);genes]
    end
    genes
end

function get_genes(ind::CGPInd, node_id::Int64)
    #Select corresponding genes to a given node
    ind.chromosome[(node_id-ind.n_in-1)*3+1:(node_id-ind.n_in-1)*3+3]
end

function get_genes(ind::CGPInd, nodes::Array{Int64})
    #Select corresponding genes to given nodes
    if length(nodes) > 0
        return reduce(vcat, map(x->get_genes(ind, x), nodes))
    else
        return Array{Int64}(undef, 0)
    end
end

function get_output_trace(ind::CGPInd, output_ind::Int64)
    # Find all nodes linked to an output
    recur_output_trace(ind, ind.outputs[output_ind], Array{Int64}(undef, 0))
end

function recur_output_trace(ind::CGPInd, iter::Int16, visited::Array{Int64})
    if ~(iter in visited)
        append!(visited, [iter])
        if iter > ind.n_in
            for i in [ind.nodes[iter].x,ind.nodes[iter].y]
                recur_output_trace(ind, i, visited)
            end
        end
    end
    visited
end

function forward_connections(ind::CGPInd)
    connections = [[i] for i in 1:length(ind.nodes)]
    for ci in eachindex(ind.nodes)
        connect=[ind.nodes[ci].x,ind.nodes[ci].y]
        for i in 1:2
            conn = connect[i]
            if conn > 0
                if ~(conn in connections[ci])
                    append!(connections[ci], [conn])
                end
                for j in eachindex(connections[conn])
                    if ~(j in connections[ci])
                        append!(connections[ci], [j])
                    end
                end
            end
        end
    end
    connections
end


text:
include("etcdserver.jl")

keys_prefix(etcd::EtcdServer,key::String) =
    "http://$(etcd.ip):$(etcd.port)/$(etcd.version)/keys$(key)"

function get(etcd::EtcdServer,key::String;
             sort::Bool=false,recursive::Bool=false)
   etcd_request(:get,keys_prefix(etcd,key),
                filter((k,v)->v,
                       {"sorted"=>sort,"recursive"=>recursive})) |>
   check_etcd_response
end

function set(etcd::EtcdServer,key::String,value::String;
             ttl::Union(Int,Nothing)=nothing)
   etcd_request(:put,keys_prefix(etcd,key),
                filter((k,v)->!is(v,nothing),
                       {"value"=>value,"ttl"=>ttl})) |>
   check_etcd_response
end

function set_dir(etcd::EtcdServer,key::String;
                 ttl::Union(Int,Nothing)=nothing)
   etcd_request(:put,keys_prefix(etcd,key),
                filter((k,v)->!is(v,nothing),
                       {"value"=>"","ttl"=>ttl,"dir"=>true})) |>
   check_etcd_response
end

function create_dir(etcd::EtcdServer,key::String;
                    ttl::Union(Int,Nothing)=nothing)
   etcd_request(:put,keys_prefix(etcd,key),
                filter((k,v)->!is(v,nothing),
                       {"value"=>"","ttl"=>ttl,
                        "prevExist"=>false,"dir"=>true})) |>
   check_etcd_response
end

function update_dir(etcd::EtcdServer,key::String;
                    ttl::Union(Int,Nothing)=nothing)
   etcd_request(:put,keys_prefix(etcd,key),
                filter((k,v)->!is(v,nothing),
                       {"value"=>"","ttl"=>ttl,
                        "prevExist"=>true,"dir"=>true})) |>
   check_etcd_response
end

function create(etcd::EtcdServer,key::String,value::String;
                ttl::Union(Int,Nothing)=nothing)
   etcd_request(:put,keys_prefix(etcd,key),
                filter((k,v)->!is(v,nothing),
                       {"value"=>value,"ttl"=>ttl,
                        "prevExist"=>false})) |>
   check_etcd_response
end

function update(etcd::EtcdServer,key::String,value::String;
                ttl::Union(Int,Nothing)=nothing)
   etcd_request(:put,keys_prefix(etcd,key),
                filter((k,v)->!is(v,nothing),
                       {"value"=>value,"ttl"=>ttl,
                        "prevExist"=>true})) |>
   check_etcd_response
end

function create_in_order(etcd::EtcdServer,key::String,value::String;
                         ttl::Union(Int,Nothing)=nothing)
   etcd_request(:post,keys_prefix(etcd,key),
                filter((k,v)->!is(v,nothing),
                       {"value"=>value,"ttl"=>ttl})) |>
   check_etcd_response
end

add_child(etcd::EtcdServer,key::String,value::String;
          ttl::Union(Int,Nothing)=nothing) = create_in_order(etcd,
                                                             key,
                                                             value,
                                                             ttl=ttl)

function create_in_order_dir(etcd::EtcdServer,key::String;
                             ttl::Union(Int,Nothing)=nothing)
   etcd_request(:post,keys_prefix(etcd,key),
                filter((k,v)->!is(v,nothing),
                       {"value"=>"","ttl"=>ttl})) |>
   check_etcd_response
end

add_child_dir(etcd::EtcdServer,key::String;
              ttl::Union(Int,Nothing)=nothing) = create_in_order_dir(etcd,
                                                                     key,
                                                                     ttl=ttl)

function exists(etcd::EtcdServer,key::String)
    rsp = etcd_request(:get,keys_prefix(etcd,key))
    if !isa(rsp,Nothing)
        JSON.parse(rsp) |>
        (rsp)->if isa(rsp,Dict)
                   !haskey(rsp,"errorCode")
               else
                   false
               end
    else
        false
    end
end

has_key(etcd::EtcdServer,key::String) = exists(etcd,key)

function delete(etcd::EtcdServer,key::String)
   etcd_request(:delete,keys_prefix(etcd,key)) |>
   check_etcd_response
end

function delete_dir(etcd::EtcdServer,key::String;recursive::Bool=false)
   etcd_request(:delete,keys_prefix(etcd,key),
                filter((k,v)->v,
                       {"dir"=>true,"recursive"=>recursive})) |>
   check_etcd_response
end

function compare_and_delete(etcd::EtcdServer,key::String;
                            prev_value::Union(String,Nothing)=nothing,
                            prev_index::Union(Int,Nothing)=nothing)
   if is(prev_value,nothing) && is(prev_index,nothing)
       warn("Must specify either prev_value (a string) or prev_index (an integer)")
   else
       etcd_request(:delete,keys_prefix(etcd,key),
                    filter((k,v)->!is(v,nothing),
                           {"prevValue"=>prev_value,
                            "prevIndex"=>prev_index})) |>
       check_etcd_response
    end
end

function compare_and_swap(etcd::EtcdServer,key::String,value::String;
                          prev_value::Union(String,Nothing)=nothing,
                          prev_index::Union(Int,Nothing)=nothing,
                          ttl::Union(Int,Nothing)=nothing)
   if is(prev_value,nothing) && is(prev_index,nothing)
       warn("Must specify either prev_value (a string) or prev_index (an integer)")
   else
       etcd_request(:put,keys_prefix(etcd,key),
                    filter((k,v)->!is(v,nothing),
                           {"value"=>value,
                            "prevValue"=>prev_value,
                            "prevIndex"=>prev_index,
                            "ttl"=>ttl})) |>
       check_etcd_response
    end
end

test_and_set(etcd::EtcdServer,key::String,value::String;
             prev_value::Union(String,Nothing)=nothing,
             prev_index::Union(Int,Nothing)=nothing,
             ttl::Union(Int,Nothing)=nothing) = compare_and_swap(etcd,key,value,
                                                                 prev_value=prev_value,
                                                                 prev_index=prev_index,
                                                                 ttl=ttl)

function watch(etcd::EtcdServer,key::String,cb::Function;
               wait_index::Union(Int,Bool)=false,
               recursive::Bool=false)
    @async begin
        try
            etcd_request(:get,keys_prefix(etcd,key),
                         filter((k,v)->v,
                                {"wait"=>true,
                                 "recursive"=>recursive,
                                 "waitIndex"=>wait_index})) |>
           check_etcd_response |>
           cb
        catch err
            warn("watch failed $err for key $key")
        end
    end
end

function keep_watching_index(etcd::EtcdServer,key::String,cb::Function,
                             wait_index::Int;
                             recursive::Bool=false)
    @async begin
        try
            while true
                options = filter({"wait"=>true,"recursive"=>recursive,
                                  "waitIndex"=>wait_index}) do k,v
                                  if typeof(v) == Bool
                                      v
                                  else
                                      true
                                  end
                           end
                resp = etcd_request(:get,keys_prefix(etcd,key),options)
                resp = try
                           JSON.parse(resp)
                       catch _
                           resp
                       end
                # we handle the error here, since it provides us with the
                # current index
                if isa(resp,Dict) && haskey(resp,"errorCode")
                    # extract index
                    if haskey(resp,"index")
                        wait_index = resp["index"] + 1
                    else
                        ec = resp["errorCode"]
                        warn("Request failed with error code $(ec)",
                             {:reason => Base.get(etcd_errors,ec,"Unknown Error")})
                        break
                    end
                elseif !isa(resp,Nothing)
                    cb(resp)
                    wait_index = maximum([Base.get(resp["node"],"createdIndex",0),
                                          Base.get(resp["node"],"modifiedIndex",0),
                                          wait_index])
                    wait_index += 1
                end
            end
        catch err
            warn("keep_watching_index failed $err for key $key")
        end
    end
end

function keep_watching(etcd::EtcdServer,key::String,cb::Function;
                       recursive::Bool=false)
    @async begin
        try
            while true
                etcd_request(:get,keys_prefix(etcd,key),
                             filter((k,v)->v,
                             {"wait"=>true,
                              "recursive"=>recursive})) |>
                check_etcd_response |>
                cb
            end
        catch err
            warn("keep_watching failed $err for key $key")
        end
    end
end

function watch_until(etcd::EtcdServer,key::String,
                     cb::Function,
                     should_terminate::Function;
                     wait_index::Union(Int,Bool)=false,
                     recursive::Bool=false)
    @async begin
        try
            while true
                ev = etcd_request(:get,keys_prefix(etcd,key),
                                  filter((k,v)->v,
                                  {"wait"=>true,
                                   "recursive"=>recursive,
                                   "waitIndex"=>wait_index})) |>
                check_etcd_response
                cb(ev)
                if should_terminate(ev)
                    break
                end
                if wait_index != false
                    wait_index += 1
                end
            end
        catch err
            warn("watch_until failed $err for key $key")
        end
    end
end


text:
# This file is a part of ElasticArrays.jl, licensed under the MIT License (MIT).

function _split_dims(dims::NTuple{N,Integer}) where {N}
    int_dims = Int.(dims)
    Base.front(int_dims), int_dims[end]
end


text:
function kross!(r)
    x = 0
    y = 0

    function set_corner(side1, side2, sides::AbstractArray)
        while !isborder(r, side1) || !isborder(r, side2)
            while !isborder(r, side2)
                move!(r, side2)
                push!(sides, side2)
                x += 1
            end
            while !isborder(r, side1)
                move!(r, side1)
                push!(sides, side1)
                y += 1
            end
        end
    end

    function put_markers(side1, side2)
        for i in 1:x
            move!(r, side1)
        end
        putmarker!(r)
        for i in 1:x
            move!(r, inverse_side(side1))
        end

        for i in 1:y
            move!(r, side2)
        end
        putmarker!(r)
        for i in 1:y
            move!(r, inverse_side(side2))
        end
    end

    function solve(s1, s2, s3, s4)
        x = 0
        y = 0

        sides = []
        set_corner(s1, s4, sides)

        put_markers(s2, s3)

        while length(sides) > 0
            move!(r, inverse_side(pop!(sides)))
        end
    end

    solve(Nord, Ost, Sud, West)
    solve(Ost, Nord, West, Sud)
end

max_stars_repo_name: dmitrii-a-piskunov/mirea-progs

max_issues_repo_name: dmitrii-a-piskunov/mirea-progs

max_forks_repo_name: dmitrii-a-piskunov/mirea-progs


text:
using Documenter, PowerSystems
import DataStructures: OrderedDict
using Literate

include(joinpath(@__DIR__, "../src/utils/data.jl"))
import .UtilsData: TestData
download(TestData; branch = "master")

# This is commented out because the output is not user-friendly. Deliberation on how to best
# communicate this information to users is ongoing.
#include(joinpath(@__DIR__, "src", "generate_validation_table.jl"))
include(joinpath(@__DIR__, "make_model_library.jl"))

pages = OrderedDict(
        "Welcome Page" => "index.md",
        "Quick Start Guide" => "quick_start_guide.md",
        "Tutorials" =>  "tutorials/intro_page.md",
        "Modeler Guide" =>
            Any[
            "modeler_guide/type_structure.md",
            "modeler_guide/system.md",
            "modeler_guide/time_series.md",
            "modeler_guide/example_dynamic_data.md",
            "modeler_guide/system_dynamic_data.md",
            "modeler_guide/market_bid_cost.md",
            #"modeler_guide/parsing.md"
            ],
        "Model Developer Guide" =>
            Any["Extending Parsing" => "model_developer_guide/extending_parsing.md",
                "Adding Types" => "model_developer_guide/adding_custom_types.md",
            ],
            "Code Base Developer Guide" =>
            Any["Developer Guide" => "code_base_developer_guide/developer.md",
            "Adding New Types" => "code_base_developer_guide/adding_new_types.md",
            "Troubleshooting" => "code_base_developer_guide/troubleshooting.md"
            ],
        "Model Library" => Any[],
        "Public API Reference" => "api/public.md",
        "Internal API Reference" => "api/internal.md"
)

pages["Model Library"] = make_model_library(
     categories = [
        Topology,
        StaticInjection,
        Service,
        Branch,
        PSY.DeviceParameter,
    ],
    exceptions = [PSY.DynamicComponent,
                  PSY.ActivePowerControl,
                  PSY.ReactivePowerControl,
                  PSY.DynamicBranch
                  ],
    manual_additions =
        Dict("Service" => ["Reserves" => "model_library/reserves.md"],
        "StaticInjection" => ["Regulation Device" => "model_library/regulation_device.md"],
        "DynamicInjection" => ["Dynamic Inverter" => "model_library/dynamic_inverter.md",
        "Dynamic Generator" => "model_library/dynamic_generator.md",
        ],
        "StaticInjection" => ["HybridSystem" => "model_library/hybrid_device.md"],
        "Branch" => ["Dynamic Lines" => "model_library/dynamic_branch.md"]
        )
)

# postprocess function to insert md
function insert_md(content)
    m = match(r"APPEND_MARKDOWN\(\"(.*)\"\)", content)
    if !isnothing(m)
        md_content = read(m.captures[1], String)
        content = replace(content, r"APPEND_MARKDOWN\(\"(.*)\"\)" => md_content)
    end
    return content
end

# This code performs the automated addition of Literate - Generated Markdowns. The desired
# section name should be the name of the file for instance network_matrices.jl -> Network Matrices
julia_file_filter = x -> occursin(".jl", x)
folders = Dict(
    "Model Library" => filter(julia_file_filter, readdir("docs/src/model_library")),
    "Modeler Guide" => filter(julia_file_filter, readdir("docs/src/modeler_guide")),
    "Model Developer Guide" => filter(julia_file_filter, readdir("docs/src/model_developer_guide")),
    "Code Base Developer Guide" => filter(julia_file_filter, readdir("docs/src/code_base_developer_guide")),
)

for (section, folder) in folders
    for file in folder
        section_folder_name = lowercase(replace(section, " " => "_"))
        outputdir = joinpath(pwd(), "docs", "src", "$section_folder_name")
        inputfile = joinpath("$section_folder_name", "$file")
        infile_path = joinpath(pwd(), "docs", "src", inputfile)
        outputfile = string("generated_", replace("$file", ".jl" => ""))
        execute = occursin("EXECUTE = TRUE", uppercase(readline(infile_path))) ? true : false
        Literate.markdown(infile_path,
                          outputdir;
                          name = outputfile,
                          credit = false,
                          documenter = true,
                          postprocess = insert_md,
                          execute = execute)
        subsection = titlecase(replace(split(file, ".")[1], "_" => " "))
        push!(pages[section], ("$subsection" =>  joinpath("$section_folder_name", "$(outputfile).md")))
    end
end

makedocs(
    modules = [PowerSystems, InfrastructureSystems],
    format = Documenter.HTML(prettyurls = haskey(ENV, "GITHUB_ACTIONS"),),
    sitename = "PowerSystems.jl",
    authors = "Jose Daniel Lara, Daniel Thom and Clayton Barrows",
    pages = Any[p for p in pages]
)

deploydocs(
    repo = "github.com/NREL-SIIP/PowerSystems.jl.git",
    target = "build",
    branch = "gh-pages",
    devbranch = "master",
    devurl = "dev",
    push_preview=true,
    versions = ["stable" => "v^", "v#.#"],
)


text:
if VERSION < v"1.7"
    macro something(args...)
        expr = :(nothing)
        for arg in reverse(args)
            expr = :(val = $(esc(arg)); val !== nothing ? val : ($expr))
        end
        something = GlobalRef(MuseInference, :something)
        return :($something($expr))
        end
    something() = throw(ArgumentError("No value arguments present"))
    something(x::Nothing, y...) = something(y...)
    something(x::Any, y...) = x
end

_map(args...; _...) = map(args...)

# modified version of https://github.com/JuliaDiff/FiniteDifferences.jl/blob/4d30c4389e06dd2295fd880be57bf58ca8dfc1ce/src/grad.jl#L9
# which allows
# * specifying the step-size
# * specificying a map function (like pmap instead)
# * (parallel-friendly) progress bar
function pjacobian(f, fdm, x, step; pmap=_map, batch_size=1, pbar=nothing)

    x, from_vec = to_vec(x)
    ẏs = pmap(tuple.(eachindex(x),step); batch_size) do (n, step)
        j = fdm(zero(eltype(x)), (step==nothing ? () : step)...) do ε
            xn = x[n]
            x[n] = xn + ε
            ret = copy(first(to_vec(f(from_vec(x)))))  # copy required incase `f(x)` returns something that aliases `x`
            x[n] = xn  # Can't do `x[n] -= ϵ` as floating-point math is not associative
            return ret
        end
        pbar == nothing || ProgressMeter.next!(pbar)
        return j
    end

    return (hcat(ẏs...), )

end

# ComponentArray constructor is ridiculousy slow, this type piracy
# speeds it up for the case that comes up all the time here where the
# named tuple is not nested
function ComponentArrays.make_carray_args(nt :: NamedTuple{<:Any,<:NTuple{N,Union{Number,Vector}} where N})
    i = 1
    ax = map(nt) do v
        len = length(v)
        s = len==1 ? i : i:i+len-1
        i += len
        s
    end
    vec = reduce(vcat, values(nt))
    (vec, ComponentArrays.Axis(ax))
end

function ComponentArrays.make_carray_args(nt :: NamedTuple{<:Any,<:Tuple{Number} where N})
    ([first(nt)], ComponentArrays.Axis(map(_->1, nt)))
end

_namedtuple(nt::NamedTuple) = nt
function _namedtuple(cv::ComponentVector)
    tp = map(k -> getproperty(cv, k), valkeys(cv))
    unval(::Val{k}) where k = k
    NamedTuple{map(unval,valkeys(cv))}(tp)
end

LinearAlgebra.inv(A::ComponentMatrix{<:Real, <:Symmetric}) = ComponentArray(Matrix(inv(getdata(A))), getaxes(A))