text:
using StochasticDiffEq, DiffEqNoiseProcess, Test, Random
@testset "SDE Stratonovich Reversal Tests" begin
  Random.seed!(100)
  α=1.01
  β=0.87

  dt = 1e-3
  tspan = (0.0,1.0)
  u₀=1/2

  tarray =  collect(tspan[1]:dt:tspan[2])

  f!(du,u,p,t) = du .= α*u
  g!(du,u,p,t) = du .= β*u

  prob = SDEProblem(f!,g!,[u₀],tspan)
  sol = solve(prob,EulerHeun(),dt=dt,save_noise=true, adaptive=false)

  _sol = deepcopy(sol) # to make sure the plot is correct
  W1 = NoiseGrid(reverse!(_sol.t),reverse!(_sol.W.W))
  prob1 = SDEProblem(f!,g!,sol[end],reverse(tspan),noise=W1)
  sol1 = solve(prob1,EulerHeun(),dt=dt)

  _sol = deepcopy(sol)
  W2 = NoiseWrapper(_sol.W, reverse=true)
  prob2 = SDEProblem(f!,g!,sol[end],reverse(tspan),noise=W2)
  sol2 = solve(prob2,EulerHeun(),dt=dt, save_noise=false)

  # same time steps

  @test sol.u ≈ reverse(sol1.u) atol=1e-2
  @test sol.u ≈ reverse(sol2.u) atol=1e-2
  @test sol1.u ≈ sol2.u atol=1e-5

  # 1/10 size time steps

  _sol = deepcopy(sol) # to make sure the plot is correct
  W1 = NoiseGrid(reverse!(_sol.t),reverse!(_sol.W.W))
  prob1 = SDEProblem(f!,g!,sol[end],reverse(tspan),noise=W1)
  sol1 = solve(prob1,EulerHeun(),dt=0.1*dt)

  _sol = deepcopy(sol)
  W2 = NoiseWrapper(_sol.W, reverse=true)
  prob2 = SDEProblem(f!,g!,sol[end],reverse(tspan),noise=W2)
  sol2 = solve(prob2,EulerHeun(),dt=0.1*dt, save_noise=false)

  @test sol.u ≈ sol1(tarray).u atol=1e-2
  @test sol.u ≈ sol2(tarray).u atol=1e-2

  # diagonal noise

  prob = SDEProblem(f!,g!,[u₀,u₀],tspan)
  sol = solve(prob,EulerHeun(),dt=dt,save_noise=true)

  _sol = deepcopy(sol) # to make sure the plot is correct
  W1 = NoiseGrid(reverse!(_sol.t),reverse!(_sol.W.W))
  prob1 = SDEProblem(f!,g!,sol[end],reverse(tspan),noise=W1)
  sol1 = solve(prob1,EulerHeun(),dt=dt)

  _sol = deepcopy(sol)
  W2 = NoiseWrapper(_sol.W, reverse=true)
  prob2 = SDEProblem(f!,g!,sol[end],reverse(tspan),noise=W2)
  sol2 = solve(prob2,EulerHeun(),dt=dt)

  @test sol.u ≈ reverse(sol1.u) atol=5e-2
  @test sol.u ≈ reverse(sol2.u) atol=5e-2
  @test sol1.u ≈ sol2.u atol=1e-5

  # non-diagonal noise

  function gnd!(du,u,p,t)
    du[1,1] = 0.3u[1]
    du[1,2] = 0.6u[1]
    du[1,3] = 0.9u[1]
    du[1,4] = 0.12u[2]
    du[2,1] = 1.2u[1]
    du[2,2] = 0.2u[2]
    du[2,3] = 0.3u[2]
    du[2,4] = 1.8u[2]
  end
  prob = SDEProblem(f!,gnd!,[u₀,u₀],tspan,noise_rate_prototype=zeros(2,4))
  sol = solve(prob,EulerHeun(),dt=dt,save_noise=true)

  _sol = deepcopy(sol) # to make sure the plot is correct
  W1 = NoiseGrid(reverse!(_sol.t),reverse!(_sol.W.W))
  prob1 = SDEProblem(f!,gnd!,sol[end],reverse(tspan),noise=W1,noise_rate_prototype=zeros(2,4))
  sol1 = solve(prob1,EulerHeun(),dt=dt)

  _sol = deepcopy(sol)
  W2 = NoiseWrapper(_sol.W, reverse=true)
  prob2 = SDEProblem(f!,gnd!,sol[end],reverse(tspan),noise=W2, noise_rate_prototype=zeros(2,4))
  sol2 = solve(prob2,EulerHeun(),dt=dt)

  @test sol.u ≈ reverse(sol1.u) atol=5e-1
  @test sol.u ≈ reverse(sol2.u) atol=5e-1
  @test sol1.u ≈ sol2.u atol=1e-5

  ###
  ### OOP
  ###

  f(u,p,t) = α*u
  g(u,p,t) = β*u

  prob = SDEProblem(f,g,u₀,tspan)
  sol =solve(prob,EulerHeun(),dt=dt,save_noise=true)

  _sol = deepcopy(sol) # to make sure the plot is correct
  W1 = NoiseGrid(reverse!(_sol.t),reverse!(_sol.W.W))
  prob1 = SDEProblem(f,g,sol[end],reverse(tspan),noise=W1)
  sol1 = solve(prob1,EulerHeun(),dt=dt)

  _sol = deepcopy(sol)
  W2 = NoiseWrapper(_sol.W, reverse=true)
  prob2 = SDEProblem(f,g,sol[end],reverse(tspan),noise=W2)
  sol2 = solve(prob2,EulerHeun(),dt=dt)

  @test sol.u ≈ reverse(sol1.u) atol=2e-2
  @test sol.u ≈ reverse(sol2.u) atol=2e-2
  @test sol1.u ≈ sol2.u atol=1e-5

  # diagonal noise

  prob = SDEProblem(f,g,[u₀,u₀],tspan)
  sol = solve(prob,EulerHeun(),dt=dt,save_noise=true)

  _sol = deepcopy(sol) # to make sure the plot is correct
  W1 = NoiseGrid(reverse!(_sol.t),reverse!(_sol.W.W))
  prob1 = SDEProblem(f,g,sol[end],reverse(tspan),noise=W1)
  sol1 = solve(prob1,EulerHeun(),dt=dt)

  _sol = deepcopy(sol)
  W2 = NoiseWrapper(_sol.W, reverse=true)
  prob2 = SDEProblem(f,g,sol[end],reverse(tspan),noise=W2)
  sol2 = solve(prob2,EulerHeun(),dt=dt)

  @test sol.u ≈ reverse(sol1.u) atol=5e-2
  @test sol.u ≈ reverse(sol2.u) atol=5e-2
  @test sol1.u ≈ sol2.u atol=1e-5

end

@testset "Reverse a given NoiseProcess " begin
  # Noise Wrapper
  _W = WienerProcess(0.0,0.0,0.0)

  dt = 0.1
  calculate_step!(_W,dt,nothing,nothing)

  for i in 1:100
    accept_step!(_W,dt,nothing,nothing)
  end

  W1 = NoiseWrapper(_W, reverse=true)
  dt = -0.1
  calculate_step!(W1,dt,nothing,nothing)
  for i in 1:99
    accept_step!(W1,dt,nothing,nothing)
  end

  W2 = reverse(_W)
  dt = -0.1
  calculate_step!(W2,dt,nothing,nothing)
  for i in 1:99
    accept_step!(W2,dt,nothing,nothing)
  end

  @test isapprox(_W.W[2:end], reverse(W1.W), atol=1e-12)
  @test isapprox(_W.W[2:end], reverse(W2.W), atol=1e-12)
  @test isapprox(_W.Z[2:end], reverse(W1.Z), atol=1e-12)
  @test isapprox(_W.Z[2:end], reverse(W2.Z), atol=1e-12)

  # Noise Grid
  dt = 0.001
  t = 0:dt:1
  brownian_values = cumsum([0;[sqrt(dt)*randn() for i in 1:length(t)-1]])
  brownian_values2 = cumsum([0;[sqrt(dt)*randn() for i in 1:length(t)-1]])
  _W = NoiseGrid(t,brownian_values,brownian_values2)

  prob = NoiseProblem(_W,(0.0,1.0))
  sol = solve(prob;dt=dt)

  W1 = NoiseGrid(reverse(sol.t),reverse(sol.W),reverse(sol.Z))
  prob = NoiseProblem(W1,(1.0,0.0))
  sol1 = solve(prob;dt=-dt)

  W2 = reverse(_W)
  prob = NoiseProblem(W2,(1.0,0.0))
  sol2 = solve(prob;dt=-dt)

  @test isapprox(sol.W, reverse(sol1.W), atol=1e-12)
  @test isapprox(sol.W, reverse(sol2.W), atol=1e-12)
  @test isapprox(sol.Z, reverse(sol1.Z), atol=1e-12)
  @test isapprox(sol.Z, reverse(sol2.Z), atol=1e-12)
end

@testset "SDE Ito Basic Reversal Tests" begin

  n = 100000
  T = 2.0
  dt = T/n
  x0 = 0.3

  b(u,p,t) =  sin(t) + cos(u)
  σ(u,p,t) = pi + atan(u)

  seed = 10
  Random.seed!(seed)
  W = [0.0; cumsum(sqrt(dt)*randn(n))]
  #using Plots; plot(W)

  p = nothing

  """
  For ito integrals
  """

  x = x0 # starting point
  xs = [x]
  t = 0.0
  ts = [0.0]
  for i in 1:n
    t, x
    #@show x, dt, (W[i+1] - W[i]), x+b(x,p,t)*dt, σ(x,p,t)*(W[i+1] - W[i])
    x += b(x,p,t)*dt + σ(x,p,t)*(W[i+1] - W[i]) # this is an ito integral
    t += dt
    push!(xs, x)
	push!(ts, t)

  end

  z = xs[end]

  #plt = plot(ts,xs)
  #plt = plot(xs)
  # Now reverse... t

  dσ_dx(u,p,t) = 1/(1 + u^2) # d(arctan(x))/dx
  z = xs[end]
  @show "starting point" z
  ys = [z]
  t = T
  cs = [0.0]
  for i in n:-1:1
    t, z
    cor =  1/2*dσ_dx(z,p,t)*σ(z,p,t)
    z -= (b(z,p,t)-0*2*cor)*dt + σ(z,p,t)*(W[i+1] - W[i]) # reverse ito integral
    t -= dt
    push!(ys, z)
    push!(cs, cor)
  end

  #plot!(ts,reverse(ys))
  # difference between forward and backward
  #plot(reverse(ys)-xs)
  # correction terms
  #plot(cs)
  #using DiffEqNoiseProcess, StochasticDiffEq

  W1 = NoiseGrid(ts,W)
  prob1 = SDEProblem(b,σ,x0,(0.0,2.0-1e-11),noise=W1)
  sol1 = solve(prob1,EM(false),dt=dt,adaptive=false)

  @test isapprox(xs, sol1.u, atol=1e-8)

  W1rev = NoiseGrid(reverse(ts),reverse(W))
  prob1 = SDEProblem(b,σ,sol1.u[end],(sol1.t[end],sol1.t[1]),noise=W1rev)
  sol2 = solve(prob1,EM(false),dt=dt,adaptive=false)

  # plot(ts,reverse(ys))
  # plot!(reverse(ts), sol2.u)
  @test isapprox(ys,sol2.u, atol=3e-5)
  @test !isapprox(sol1.u,reverse(sol2.u), atol=1e-0)

  bwrong(u,p,t) =  b(u,p,t) - 1//2*dσ_dx(u,p,t)*σ(u,p,t)
  W1rev = NoiseGrid(reverse(ts),reverse(W))
  prob1 = SDEProblem(bwrong,σ,sol1.u[end],(sol1.t[end],sol1.t[1]),noise=W1rev)
  sol2 = solve(prob1,EM(false),dt=dt,adaptive=false)

  @test !isapprox(ys,sol2.u, atol=1e-0)
  @test !isapprox(sol1.u,reverse(sol2.u), atol=1e-0)

  bcorrected(u,p,t) =  b(u,p,t) - 2*1//2*dσ_dx(u,p,t)*σ(u,p,t)
  W1rev = NoiseGrid(reverse(ts),reverse(W))
  prob1 = SDEProblem(bcorrected,σ,sol1.u[end],(sol1.t[end],sol1.t[1]),noise=W1rev)
  sol2 = solve(prob1,EM(false),dt=dt,adaptive=false)

  #plot(ts, sol1.u - reverse(sol2.u))
  @test !isapprox(ys,sol2.u, atol=1e-6)
  @test isapprox(sol1.u,reverse(sol2.u), atol=1e-0)

end

"""
Some more Ito reversals
"""

@testset "SDE Ito Reversal Tests" begin
  Random.seed!(100)
  α=1.0
  β=0.3

  dt = 1e-3
  tspan = (0.0,1.0)
  u₀=1/2

  tarray =  collect(tspan[1]:dt:tspan[2])

  f!(du,u,p,t) = du .= α*u
  g!(du,u,p,t) = du .= β*u

  prob = SDEProblem(f!,g!,[u₀],tspan)
  sol = solve(prob,EM(),dt=dt,save_noise=true, adaptive=false)

  fcorrected!(du,u,p,t) = du .= (α-β^2)*u

  _sol = deepcopy(sol) # to make sure the plot is correct
  W1 = NoiseGrid(reverse(_sol.t),reverse(_sol.W.W)
   # ,reverse(_sol.W.Z)
    )
  prob1 = SDEProblem(fcorrected!,g!,sol[end],reverse(tspan),noise=W1)
  sol1 = solve(prob1,EM(),dt=dt, adaptive=false)

  _sol = deepcopy(sol)
  W2 = NoiseWrapper(_sol.W, reverse=true)
  prob2 = SDEProblem(fcorrected!,g!,sol[end],reverse(tspan),noise=W2)
  sol2 = solve(prob2,EM(),dt=dt, save_noise=false, adaptive=false)

  # same time steps

  @test sol.u ≈ reverse(sol1.u) rtol=1e-2
  @test sol.u ≈ reverse(sol2.u) rtol=1e-2
  @test sol1.u ≈ sol2.u atol=1e-8

  f(u,p,t) = α*u
  g(u,p,t) = β*u

  prob = SDEProblem(f,g,u₀,tspan)
  sol = solve(prob,EM(),dt=dt,save_noise=true, adaptive=false)

  fcorrected(u,p,t) = (α-β^2)*u

  _sol = deepcopy(sol) # to make sure the plot is correct
  W1 = NoiseGrid(reverse(_sol.t),reverse(_sol.W.W)
    # ,reverse(_sol.W.Z)
   )
  prob1 = SDEProblem(fcorrected,g,sol[end],reverse(tspan),noise=W1)
  sol1 = solve(prob1,EM(),dt=dt, adaptive=false)

  _sol = deepcopy(sol)
  W2 = NoiseWrapper(_sol.W, reverse=true)
  prob2 = SDEProblem(fcorrected,g,sol[end],reverse(tspan),noise=W2)
  sol2 = solve(prob2,EM(),dt=dt, adaptive=false)

  @test sol.u ≈ reverse(sol1.u) rtol=1e-2
  @test sol.u ≈ reverse(sol2.u) rtol=1e-2
  @test sol1.u ≈ sol2.u atol=1e-7

  # using Plots; plt = plot(sol)
  # plot!(reverse(sol1.t),reverse(sol1[1,:]))
  # plot(vcat(sol.u - reverse(sol1.u) ...))
end

@testset "SDE Ito additive noise Reversal Tests" begin
  using DiffEqProblemLibrary.SDEProblemLibrary: importsdeproblems
  importsdeproblems()
  using DiffEqProblemLibrary.SDEProblemLibrary: prob_sde_additive, prob_sde_additivesystem
  Random.seed!(100)
  dt = 1e-3

  @testset "OOP 1D" begin
    # OOP 1D
    prob = prob_sde_additive

    # non-adaptive

    ### SOSRA2
    sol = solve(prob,SOSRA2(),dt=dt,save_noise=true, adaptive=false)
    W1 = reverse(sol.W)

    prob1 = SDEProblem(prob.f,prob.g,sol[end],reverse(prob.tspan),prob.p,noise=W1)
    sol1 = solve(prob1,SOSRA2(),dt=dt, adaptive=false)

    @test sol.u ≈ reverse(sol1.u) rtol=1e-4
    @test sol.t ≈ reverse(sol1.t) rtol=1e-4

    ### SOSRI
    sol = solve(prob,SOSRI(),dt=dt,save_noise=true, adaptive=false)
    W1 = reverse(sol.W)

    prob1 = SDEProblem(prob.f,prob.g,sol[end],reverse(prob.tspan),prob.p,noise=W1)
    sol1 = solve(prob1,SOSRI(),dt=dt, adaptive=false)

    @test sol.u ≈ reverse(sol1.u) rtol=1e-4
    @test sol.t ≈ reverse(sol1.t) rtol=1e-4

    # adaptive

    ### SOSRA2
    sol = solve(prob,SOSRA2(),dt=dt,save_noise=true, adaptive=true)
    W1 = reverse(sol.W)

    prob1 = SDEProblem(prob.f,prob.g,sol[end],reverse(prob.tspan),prob.p,noise=W1)
    sol1 = solve(prob1,SOSRA2(),dt=dt, adaptive=true)

    ts = prob.tspan[1]:0.1:prob.tspan[2]
    @test sol(ts) ≈ sol1(ts) rtol=1e-3
    @test length(sol.t) != length(sol1.t)

    ### SOSRI
    sol = solve(prob,SOSRI(),dt=dt,save_noise=true, adaptive=true)
    W1 = reverse(sol.W)

    prob1 = SDEProblem(prob.f,prob.g,sol[end],reverse(prob.tspan),prob.p,noise=W1)
    sol1 = solve(prob1,SOSRI(),dt=dt, adaptive=true)

    ts = prob.tspan[1]:0.1:prob.tspan[2]
    @test sol(ts) ≈ sol1(ts) rtol=1e-3
    @test length(sol.t) != length(sol1.t)
  end

  @testset "iip 4D" begin
    # iip 4D
    prob = prob_sde_additivesystem

    # non-adaptive

    ### SOSRA2
    sol = solve(prob,SOSRA2(),dt=dt,save_noise=true, adaptive=false)
    W1 = reverse(sol.W)

    prob1 = SDEProblem(prob.f,prob.g,sol[end],reverse(prob.tspan),prob.p,noise=W1)
    sol1 = solve(prob1,SOSRA2(),dt=dt, adaptive=false)

    @test sol.u ≈ reverse(sol1.u) rtol=1e-4
    @test sol.t ≈ reverse(sol1.t) rtol=1e-4

    ### SOSRI
    sol = solve(prob,SOSRI(),dt=dt,save_noise=true, adaptive=false)
    W1 = reverse(sol.W)

    prob1 = SDEProblem(prob.f,prob.g,sol[end],reverse(prob.tspan),prob.p,noise=W1)
    sol1 = solve(prob1,SOSRI(),dt=dt, adaptive=false)

    @test sol.u ≈ reverse(sol1.u) rtol=1e-4
    @test sol.t ≈ reverse(sol1.t) rtol=1e-4

    # adaptive

    ### SOSRA2
    sol = solve(prob,SOSRA2(),dt=dt,save_noise=true, adaptive=true)
    W1 = reverse(sol.W)

    prob1 = SDEProblem(prob.f,prob.g,sol[end],reverse(prob.tspan),prob.p,noise=W1)
    sol1 = solve(prob1,SOSRA2(),dt=dt, adaptive=true)

    ts = prob.tspan[1]:0.1:prob.tspan[2]
    @test sol(ts) ≈ sol1(ts) rtol=1e-3
    @test length(sol.t) != length(sol1.t)

    ### SOSRI
    sol = solve(prob,SOSRI(),dt=dt,save_noise=true, adaptive=true)
    W1 = reverse(sol.W)

    prob1 = SDEProblem(prob.f,prob.g,sol[end],reverse(prob.tspan),prob.p,noise=W1)
    sol1 = solve(prob1,SOSRI(),dt=dt, adaptive=true)

    ts = prob.tspan[1]:0.1:prob.tspan[2]
    @test sol(ts) ≈ sol1(ts) rtol=1e-3
    @test length(sol.t) != length(sol1.t)
  end
end


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder

name = "Geant4"
version = v"0.1.0"

# Collection of sources required to build
sources = [
    ArchiveSource("https://github.com/Geant4/geant4/archive/v10.5.1.tar.gz",
                  "443efb0d16e8a5fd195176573d21d2e12415ae7853dd39cc0517171aea243227"),
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/geant4-*/
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=${prefix} -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} ..
make -j${nproc}
make install
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = filter(!Sys.iswindows, supported_platforms())

# The products that we will ensure are always built
products = [
    LibraryProduct("libG4vis_management", :libG4visManagement),
    LibraryProduct("libG4FR", :libG4FR),
    LibraryProduct("libG4event", :libG4Event),
    LibraryProduct("libG4analysis", :libG4Analysis),
    LibraryProduct("libG4digits_hits", :libG4Digits),
    LibraryProduct("libG4run", :libG4Run),
    LibraryProduct("libG4visXXX", :libG4VisXXX),
    LibraryProduct("libG4clhep", :libG4CLHEP),
    LibraryProduct("libG4GMocren", :libG4Mocren),
    LibraryProduct("libG4particles", :libG4Particles),
    LibraryProduct("libG4graphics_reps", :libG4Graphics),
    LibraryProduct("libG4zlib", :libG4Zlib),
    LibraryProduct("libG4geometry", :libG4Geometry),
    LibraryProduct("libG4modeling", :libG4Modeling),
    LibraryProduct("libG4interfaces", :libG4Interfaces),
    LibraryProduct("libG4persistency", :libG4Persistency),
    LibraryProduct("libG4track", :libG4Track),
    LibraryProduct("libG4error_propagation", :libG4ErrorPropagation),
    LibraryProduct("libG4parmodels", :libG4ParModels),
    LibraryProduct("libG4materials", :libG4Material),
    LibraryProduct("libG4physicslists", :libG4PhysicsLists),
    LibraryProduct("libG4VRML", :libG4VRML),
    LibraryProduct("libG4readout", :libG4Readout),
    LibraryProduct("libG4RayTracer", :libG4RayTracer),
    LibraryProduct("libG4visHepRep", :libG4VisHepRep),
    LibraryProduct("libG4Tree", :libG4Tree),
    LibraryProduct("libG4processes", :libG4Processes),
    LibraryProduct("libG4global", :libG4Global),
    LibraryProduct("libG4tracking", :libG4Tracking),
    LibraryProduct("libG4intercoms", :libG4Intercoms),
]

# Dependencies that must be installed before this package can be built
dependencies = [
    "Expat_jll",
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; preferred_gcc_version=v"7")

ext: jl

max_stars_repo_name: xrq-phys/Yggdrasil

max_issues_repo_name: xrq-phys/Yggdrasil

max_forks_repo_name: xrq-phys/Yggdrasil


text:
module DirichletProcessMixtures

using NumericExtensions
using Devectorize
using ArrayViews
using Distributions
using ConjugatePriors
using PDMats

include("TSBPMM.jl")
include("student.jl")
include("gaussian_mixture.jl")

end


text:
"""
	struct OptArgs

Storing parameters for `SplitGraph.runopt` function.

### General
- `γ::Real = 2`
- `itmax::Int64 = 15`: maximal number of iterations of naive MCCs / SA cycles.
- `likelihood_sort::Bool = true`: sort equivalent configurations using likelihood test
  based on branch length.
- `resolve::Bool = true`: try to resolve trees while finding MCCs.
- `seq_lengths`: lengths of sequences that trees were built from.
  Used in likelihood calculations.
  This is initialized from other input arguments, and defaults to sequences of length one.
### Simulated annealing
- `nMCMC::Int = 25`: The number of MCMC iterations for a tree of `n` leaves is `nMCMC*n`.
- `cooling_schedule = :geometric`: type of cooling schedule `(:geometric, :linear, :acos)`
- `Tmin::Float64 = 0.05`: minimal temperature of SA.
- `Tmax::Float64 = 0.8`: maximal temperature of SA.
- `nT::Int = 3000`: number of steps in the cooling schedule
### Verbosity
- `verbose::Bool=false`: first level of verbosity
- `vv::Bool = false`: second level of verbosity
"""
@with_kw struct OptArgs
	γ::Real = 2
	itmax::Int64 = 15
	likelihood_sort::Bool = true
	resolve::Bool = true
	seq_lengths::Vector{Int} = [1, 1]
	# For the annealing
	nMCMC::Int = 25
	Tmin::Float64 = 0.05; @assert Tmin > 0
	Tmax::Float64 = 0.8; @assert Tmax > Tmin
	nT::Int = 3000
	cooling_schedule = :linear
	Trange = get_cooling_schedule(Tmin, Tmax, nT, type=cooling_schedule)
	sa_rep::Int64 = 1
	# Verbosity
	verbose::Bool = false
	vv::Bool = false
end

function get_cooling_schedule(Tmin, Tmax, nT; type=:geometric)
	if type == :geometric
		return get_geometric_cooling_schedule(Tmin, Tmax, nT)
	elseif type == :linear
		return get_linear_cooling_schedule(Tmin, Tmax, nT)
	elseif type == :acos
		return get_acos_cooling_schedule(Tmin, Tmax, nT)
	else
		error("Unknown `cooling_schedule` field: $(type). See `?OptArgs` for allowed values.")
	end
end

function get_geometric_cooling_schedule(Tmin, Tmax, nT)
	α = (log(Tmin) - log(Tmax)) / nT
	n = ceil(Int, (log(Tmin) - log(Tmax)) / log(α))
	return [α^i * Tmax for i in 0:n]
end

function get_acos_cooling_schedule(Tmin, Tmax, nT)
	f(x, K=1.5) = if x < 0.5
		0.5 + 2^(K-1)*abs(acos(2*x-1)/3.14-0.5)^K
	elseif x == 0.5
		0.5
	else
		0.5 - 2^(K-1)*abs(acos(2*x-1)/3.14-0.5)^K
	end
	# f(0) = 1.0 and f(1) = 0.
	return [(Tmax - Tmin)*f(t) + Tmin for t in range(0,1,nT)]
end

get_linear_cooling_schedule(Tmin, Tmax, nT) = return collect(reverse(range(Tmin, Tmax, nT)))

max_stars_repo_name: PierreBarrat/RecombTools

max_issues_repo_name: PierreBarrat/RecombTools

max_forks_repo_name: PierreBarrat/RecombTools


text:
#!/home/asen/julia110/bin/julia

#================================
wh=8
using PyPlot

#plot(qwe1[1:wh],"b^--")
#plot(qwe2[1:wh],"yo--")
plot(qwe3[1:wh]-qwe2[1:wh],"ro--")
show()

	多进程和多线程 : still need to do

#using Distributed
#using SharedArrays
#addprocs(3)
#pmap
#fetch @spawn
#@everywhere
#@spawnat

		a = randn(1000)
		@parallel (+) for i=1:100000
		f(a[randi(end)])
		end

		M = {rand(1000,1000) for i=1:10}
		pmap(svd, M)

function use1_multi()
	sum_all()=begin
		tmp=0
		tmp=@distributed (+) for iter in num_list
			iter
		end
		return tmp
	end
	num_list=Array{Int64}([rand(1:1000) for i=1:1000000])
end

#@time use1_multi()
=============================#
function 同步与异步演示()
	@sync begin
		for id=1:10
			@async begin sleep(rand(1:5));@info  "$id is  a thead id";	end
		end
	end
end
#同步与异步演示()

#
#	使用傅立叶变换进行分词
#		1.形成 字符,结果->数字化表示 转换
#		2.形成输入输出数据:
#			2384,1903....
#			0	,1	,....
#		3.

#
#	使用递归方式的傅立叶函数
# 1.递归一次,表达式增加一项
# 2.复数表示:complex(x,y);数据存储使用 字典
# 3.正样本标注:分词:只标记词语的结束
#
#问题:
#	如何形成表达式?
#
function 万能表示函数(深度=10)
	参数=[] #n
	for i=1:深度
		push!(参数,(rand(-10:10),rand(-10:10),i))
	end
	result=0
	for (a,b,c) in 参数
		result+=a*exp(-2π*b*im/深度)
	end
end

function 随机数生成(c::Channel)
	while true
		put!(c,rand())
	end
end
function 计数(随机数管)
	计数=0
	加和=0
	for 随机数 in 随机数管
		加和+=随机数
		if 加和>1
			return 计数
		end
		计数+=1
	end
end
function 主函数()
	随机数管=Channel(随机数生成)
	单次结果=0
	结果=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
	for i=1:1_0000_000
		单次结果=计数(随机数管)
		#print(单次结果)
		if 0<单次结果<20
			结果[单次结果]+=1
		else
			println(单次结果)
		end
	end
	for i=1:20
		println(i,"次 : ",结果[i])
	end
end
#主函数()
#====
1次 : 5000551
2次 : 3332264
3次 : 1250392
4次 : 333559
5次 : 69379
6次 : 11836
7次 : 1766
8次 : 215
9次 : 33
10次 : 4
11次 : 1

C++重写:

#include<cstdlib>
#include <QString>
#include<vector>
using namespace std;
double get_rand()
{
    double tmp=(rand()%10000) /10000.0;
    //qDebug()<< tmp; //#include<QDebug>
    return tmp ;
}
unsigned long get_count()
{
    vector<double> rand_result(30);
    unsigned long count=0;
    double sum=0.0;
    for(unsigned long j=0;j<30;j++)
    {
        rand_result[j]=get_rand();
    }
    for(auto iter:rand_result)
    {
        if(sum<=1.0){
            sum+=iter;
            count++;
        }
        else{
            break;
        }
    }
    return count ;
}
void call_other_func(vector<long>& result)
{
    /*
     * 计算x个随机数(0~1)相加后大于1
     * 的分布及 期望(均值)
     *
     *结果:vector<long>& result
     *
     *
     */
    //srand(123); //get_rand
    long cishu=1000000;

    for(int i=0;i<cishu;i++){
        unsigned long tmp=get_count();
        if(tmp<15)
            result[tmp]+=1;
    }
    double value=0.0;//期望;该结果未返回
    int i=0;
    for(auto val:result){
        value+=(val/1000000.0)*i;
        i++;
    }
}

====#

#湍流，又称为乱流、紊流或扰流
#当流速很小时，流体分层流动，互不混合，称为层流

#曲线的内接正方形
# 证明或推翻，在平面中的任意一条简单封闭曲线上，总能找到四个点，它们恰能组成一个正方形。

#环形跑道难题
#有一个环形跑道，总长为 1 个单位。n 个人从跑道上的同一位置出发，沿着跑道顺时针一直跑下去。每个人的速度都是固定的，但不同人的速度不同。证明或推翻，对于每一个人，总会有一个时刻，他与其他所有人的距离都不小于 1/n

#排序问题加强版
#有 n 个盒子，从左至右依次编号为 1, 2, …, n 。第 1 个盒子里放两个编号为 n 的小球，第 2 个盒子里放两个编号为 n – 1的小球，以此类推，第 n 个盒子里放两个编号为 1 的小球。每一次，你可以在相邻两个盒子中各取一个小球，交换它们的位置。为了把所有小球放进正确的盒子里，最少需要几次交换？

#多面体的展开
#证明或推翻，总可以把一个凸多面体沿着棱剪开，展开成一个简单的平面多边形。

#用平面镜拼成的多边形
# 证明或推翻，对于任意一个内壁全是镜面的多边形，总能在里面找到一个点，使得位于这个点的光源可以照亮整个多边形内部

#Thrackle 猜想
#如果一个图中，每条边都与其它所有边相交恰好一次（顶点处相接也算相交），这个图就叫做一个 thrackle 。问，是否存在边数大于顶点数的 thrackle 图？

#Venn 图
#是否随便什么样的 n 个集合的 Venn 图都可以扩展到 n + 1 个集合{的venn图}呢

#令 U 是一个有限集，S1 , S2 , … , Sn 都是 U 的非空子集，它们满足任意多个集合的并集仍然在这些集合里。证明，一定能找到某个元素，它出现在了至少一半的集合里。

max_stars_repo_name: Jonson-Sun/C-plus-plus

max_issues_repo_name: Jonson-Sun/C-plus-plus

max_forks_repo_name: Jonson-Sun/C-plus-plus


text:
module Runtests

import ..ModiaMath
using Test

@testset "Test ModiaMath" begin
    include(joinpath("result", "_includes.jl"))
    include(joinpath("variables", "_includes.jl"))
    include(joinpath("frames", "_includes.jl"))
    include(joinpath("nonlinearEquations", "_includes.jl"))
    include(joinpath("simulation", "_includes.jl"))

    println("\n... close all open figures.")
    ModiaMath.closeAllFigures()
end

end


text:
graph = LocalCSRGraph{UInt16, UInt32}()
@test Array{UInt16, 1}(undef, 0) == graph.entries
@test Array{UInt32, 1}(undef, 0) == graph.rowMap
@test 0 == numRows(graph)
@test_throws InvalidArgumentError maxEntry(graph)
@test_throws InvalidArgumentError minEntry(graph)

entries = UInt16[248, 230, 17, 26, 143, 101, 251, 13, 97, 380,
                    28, 16, 139, 9, 820, 637, 879, 156, 42, 339]
rowMap = UInt32[1, 3, 8, 9, 15, 18, 21]
graph = LocalCSRGraph(entries, rowMap)
@test entries === graph.entries
@test rowMap === graph.rowMap
@test 6 == numRows(graph)
@test 879 == maxEntry(graph)
@test 9 == minEntry(graph)


text:
export BrickletRS485ReadLowLevel
struct BrickletRS485ReadLowLevel
    message_length::Integer
    message_chunk_offset::Integer
    message_chunk_data::Vector{Char}
end

export BrickletRS485RS485Configuration
struct BrickletRS485RS485Configuration
    baudrate::Integer
    parity::Integer
    stopbits::Integer
    wordlength::Integer
    duplex::Integer
end

export BrickletRS485ModbusConfiguration
struct BrickletRS485ModbusConfiguration
    slave_address::Integer
    master_request_timeout::Integer
end

export BrickletRS485BufferConfig
struct BrickletRS485BufferConfig
    send_buffer_size::Integer
    receive_buffer_size::Integer
end

export BrickletRS485BufferStatus
struct BrickletRS485BufferStatus
    send_buffer_used::Integer
    receive_buffer_used::Integer
end

export BrickletRS485ErrorCount
struct BrickletRS485ErrorCount
    overrun_error_count::Integer
    parity_error_count::Integer
end

export BrickletRS485ModbusCommonErrorCount
struct BrickletRS485ModbusCommonErrorCount
    timeout_error_count::Integer
    checksum_error_count::Integer
    frame_too_big_error_count::Integer
    illegal_function_error_count::Integer
    illegal_data_address_error_count::Integer
    illegal_data_value_error_count::Integer
    slave_device_failure_error_count::Integer
end

export BrickletRS485SPITFPErrorCount
struct BrickletRS485SPITFPErrorCount
    error_count_ack_checksum::Integer
    error_count_message_checksum::Integer
    error_count_frame::Integer
    error_count_overflow::Integer
end

export BrickletRS485Identity
struct BrickletRS485Identity
    uid::String
    connected_uid::String
    position::Char
    hardware_version::Vector{Integer}
    firmware_version::Vector{Integer}
    device_identifier::Integer
end

export BrickletRS485
"""
Communicates with RS485/Modbus devices with full- or half-duplex
"""
mutable struct BrickletRS485 <: TinkerforgeDevice
    ipcon::IPConnection
    deviceInternal::PyObject

    """
    Creates an object with the unique device ID *uid* and adds it to
    the IP Connection *ipcon*.
    """
    function BrickletRS485(uid::String, ipcon::IPConnection)
        package = pyimport("tinkerforge.bricklet_rs485")
        deviceInternal = package.BrickletRS485(uid, ipcon.ipconInternal)

        return new(ipcon, deviceInternal)
    end
end

export write_low_level
"""
    $(SIGNATURES)

Writes characters to the RS485 interface. The characters can be binary data,
ASCII or similar is not necessary.

The return value is the number of characters that were written.

See :func:`Set RS485 Configuration` for configuration possibilities
regarding baudrate, parity and so on.
"""
function write_low_level(device::BrickletRS485, message_length, message_chunk_offset, message_chunk_data)
    return device.deviceInternal.write_low_level(message_length, message_chunk_offset, message_chunk_data)
end

export read_low_level
"""
    $(SIGNATURES)

Returns up to *length* characters from receive buffer.

Instead of polling with this function, you can also use
callbacks. But note that this function will return available
data only when the read callback is disabled.
See :func:`Enable Read Callback` and :cb:`Read` callback.
"""
function read_low_level(device::BrickletRS485, length)
    return device.deviceInternal.read_low_level(length)
end

export enable_read_callback
"""
    $(SIGNATURES)

Enables the :cb:`Read` callback. This will disable the :cb:`Frame Readable` callback.

By default the callback is disabled.
"""
function enable_read_callback(device::BrickletRS485)
    device.deviceInternal.enable_read_callback()
end

export disable_read_callback
"""
    $(SIGNATURES)

Disables the :cb:`Read` callback.

By default the callback is disabled.
"""
function disable_read_callback(device::BrickletRS485)
    device.deviceInternal.disable_read_callback()
end

export is_read_callback_enabled
"""
    $(SIGNATURES)

Returns *true* if the :cb:`Read` callback is enabled,
*false* otherwise.
"""
function is_read_callback_enabled(device::BrickletRS485)
    return device.deviceInternal.is_read_callback_enabled()
end

export set_rs485_configuration
"""
    $(SIGNATURES)

Sets the configuration for the RS485 communication.
"""
function set_rs485_configuration(device::BrickletRS485, baudrate, parity, stopbits, wordlength, duplex)
    device.deviceInternal.set_rs485_configuration(baudrate, parity, stopbits, wordlength, duplex)
end

export get_rs485_configuration
"""
    $(SIGNATURES)

Returns the configuration as set by :func:`Set RS485 Configuration`.
"""
function get_rs485_configuration(device::BrickletRS485)
    return device.deviceInternal.get_rs485_configuration()
end

export set_modbus_configuration
"""
    $(SIGNATURES)

Sets the configuration for the RS485 Modbus communication. Available options:

* Slave Address: Address to be used as the Modbus slave address in Modbus slave mode. Valid Modbus slave address range is 1 to 247.
* Master Request Timeout: Specifies how long the master should wait for a response from a slave when in Modbus master mode.
"""
function set_modbus_configuration(device::BrickletRS485, slave_address, master_request_timeout)
    device.deviceInternal.set_modbus_configuration(slave_address, master_request_timeout)
end

export get_modbus_configuration
"""
    $(SIGNATURES)

Returns the configuration as set by :func:`Set Modbus Configuration`.
"""
function get_modbus_configuration(device::BrickletRS485)
    return device.deviceInternal.get_modbus_configuration()
end

export set_mode
"""
    $(SIGNATURES)

Sets the mode of the Bricklet in which it operates. Available options are

* RS485,
* Modbus Master RTU and
* Modbus Slave RTU.
"""
function set_mode(device::BrickletRS485, mode)
    device.deviceInternal.set_mode(mode)
end

export get_mode
"""
    $(SIGNATURES)

Returns the configuration as set by :func:`Set Mode`.
"""
function get_mode(device::BrickletRS485)
    return device.deviceInternal.get_mode()
end

export set_communication_led_config
"""
    $(SIGNATURES)

Sets the communication LED configuration. By default the LED shows RS485
communication traffic by flickering.

You can also turn the LED permanently on/off or show a heartbeat.

If the Bricklet is in bootloader mode, the LED is off.
"""
function set_communication_led_config(device::BrickletRS485, config)
    device.deviceInternal.set_communication_led_config(config)
end

export get_communication_led_config
"""
    $(SIGNATURES)

Returns the configuration as set by :func:`Set Communication LED Config`
"""
function get_communication_led_config(device::BrickletRS485)
    return device.deviceInternal.get_communication_led_config()
end

export set_error_led_config
"""
    $(SIGNATURES)

Sets the error LED configuration.

By default the error LED turns on if there is any error (see :cb:`Error Count`
callback). If you call this function with the SHOW ERROR option again, the LED
will turn off until the next error occurs.

You can also turn the LED permanently on/off or show a heartbeat.

If the Bricklet is in bootloader mode, the LED is off.
"""
function set_error_led_config(device::BrickletRS485, config)
    device.deviceInternal.set_error_led_config(config)
end

export get_error_led_config
"""
    $(SIGNATURES)

Returns the configuration as set by :func:`Set Error LED Config`.
"""
function get_error_led_config(device::BrickletRS485)
    return device.deviceInternal.get_error_led_config()
end

export set_buffer_config
"""
    $(SIGNATURES)

Sets the send and receive buffer size in byte. In sum there is
10240 byte (10KiB) buffer available and the minimum buffer size
is 1024 byte (1KiB) for both.

The current buffer content is lost if this function is called.

The send buffer holds data that was given by :func:`Write` and
could not be written yet. The receive buffer holds data that is
received through RS485 but could not yet be send to the
user, either by :func:`Read` or through :cb:`Read` callback.
"""
function set_buffer_config(device::BrickletRS485, send_buffer_size, receive_buffer_size)
    device.deviceInternal.set_buffer_config(send_buffer_size, receive_buffer_size)
end

export get_buffer_config
"""
    $(SIGNATURES)

Returns the buffer configuration as set by :func:`Set Buffer Config`.
"""
function get_buffer_config(device::BrickletRS485)
    return device.deviceInternal.get_buffer_config()
end

export get_buffer_status
"""
    $(SIGNATURES)

Returns the currently used bytes for the send and received buffer.

See :func:`Set Buffer Config` for buffer size configuration.
"""
function get_buffer_status(device::BrickletRS485)
    return device.deviceInternal.get_buffer_status()
end

export enable_error_count_callback
"""
    $(SIGNATURES)

Enables the :cb:`Error Count` callback.

By default the callback is disabled.
"""
function enable_error_count_callback(device::BrickletRS485)
    device.deviceInternal.enable_error_count_callback()
end

export disable_error_count_callback
"""
    $(SIGNATURES)

Disables the :cb:`Error Count` callback.

By default the callback is disabled.
"""
function disable_error_count_callback(device::BrickletRS485)
    device.deviceInternal.disable_error_count_callback()
end

export is_error_count_callback_enabled
"""
    $(SIGNATURES)

Returns *true* if the :cb:`Error Count` callback is enabled,
*false* otherwise.
"""
function is_error_count_callback_enabled(device::BrickletRS485)
    return device.deviceInternal.is_error_count_callback_enabled()
end

export get_error_count
"""
    $(SIGNATURES)

Returns the current number of overrun and parity errors.
"""
function get_error_count(device::BrickletRS485)
    return device.deviceInternal.get_error_count()
end

export get_modbus_common_error_count
"""
    $(SIGNATURES)

Returns the current number of errors occurred in Modbus mode.

* Timeout Error Count: Number of timeouts occurred.
* Checksum Error Count: Number of failures due to Modbus frame CRC16 checksum mismatch.
* Frame Too Big Error Count: Number of times frames were rejected because they exceeded maximum Modbus frame size which is 256 bytes.
* Illegal Function Error Count: Number of errors when an unimplemented or illegal function is requested. This corresponds to Modbus exception code 1.
* Illegal Data Address Error Count: Number of errors due to invalid data address. This corresponds to Modbus exception code 2.
* Illegal Data Value Error Count: Number of errors due to invalid data value. This corresponds to Modbus exception code 3.
* Slave Device Failure Error Count: Number of errors occurred on the slave device which were unrecoverable. This corresponds to Modbus exception code 4.
"""
function get_modbus_common_error_count(device::BrickletRS485)
    return device.deviceInternal.get_modbus_common_error_count()
end

export modbus_slave_report_exception
"""
    $(SIGNATURES)

In Modbus slave mode this function can be used to report a Modbus exception for
a Modbus master request.

* Request ID: Request ID of the request received by the slave.
* Exception Code: Modbus exception code to report to the Modbus master.
"""
function modbus_slave_report_exception(device::BrickletRS485, request_id, exception_code)
    device.deviceInternal.modbus_slave_report_exception(request_id, exception_code)
end

export modbus_slave_answer_read_coils_request_low_level
"""
    $(SIGNATURES)

In Modbus slave mode this function can be used to answer a master request to
read coils.

* Request ID: Request ID of the corresponding request that is being answered.
* Coils: Data that is to be sent to the Modbus master for the corresponding request.

This function must be called from the :cb:`Modbus Slave Read Coils Request` callback
with the Request ID as provided by the argument of the callback.
"""
function modbus_slave_answer_read_coils_request_low_level(device::BrickletRS485, request_id, coils_length, coils_chunk_offset, coils_chunk_data)
    device.deviceInternal.modbus_slave_answer_read_coils_request_low_level(request_id, coils_length, coils_chunk_offset, coils_chunk_data)
end

export modbus_master_read_coils
"""
    $(SIGNATURES)

In Modbus master mode this function can be used to read coils from a slave. This
function creates a Modbus function code 1 request.

* Slave Address: Address of the target Modbus slave.
* Starting Address: Number of the first coil to read. For backwards compatibility reasons this parameter is called Starting Address. It is not an address, but instead a coil number in the range of 1 to 65536.
* Count: Number of coils to read.

Upon success the function will return a non-zero request ID which will represent
the current request initiated by the Modbus master. In case of failure the returned
request ID will be 0.

When successful this function will also invoke the :cb:`Modbus Master Read Coils Response`
callback. In this callback the Request ID provided by the callback argument must be
matched with the Request ID returned from this function to verify that the callback
is indeed for a particular request.
"""
function modbus_master_read_coils(device::BrickletRS485, slave_address, starting_address, count)
    return device.deviceInternal.modbus_master_read_coils(slave_address, starting_address, count)
end

export modbus_slave_answer_read_holding_registers_request_low_level
"""
    $(SIGNATURES)

In Modbus slave mode this function can be used to answer a master request to
read holding registers.

* Request ID: Request ID of the corresponding request that is being answered.
* Holding Registers: Data that is to be sent to the Modbus master for the corresponding request.

This function must be called from the :cb:`Modbus Slave Read Holding Registers Request`
callback with the Request ID as provided by the argument of the callback.
"""
function modbus_slave_answer_read_holding_registers_request_low_level(device::BrickletRS485, request_id, holding_registers_length, holding_registers_chunk_offset, holding_registers_chunk_data)
    device.deviceInternal.modbus_slave_answer_read_holding_registers_request_low_level(request_id, holding_registers_length, holding_registers_chunk_offset, holding_registers_chunk_data)
end

export modbus_master_read_holding_registers
"""
    $(SIGNATURES)

In Modbus master mode this function can be used to read holding registers from a slave.
This function creates a Modbus function code 3 request.

* Slave Address: Address of the target Modbus slave.
* Starting Address: Number of the first holding register to read. For backwards compatibility reasons this parameter is called Starting Address. It is not an address, but instead a holding register number in the range of 1 to 65536. The prefix digit 4 (for holding register) is implicit and must be omitted.
* Count: Number of holding registers to read.

Upon success the function will return a non-zero request ID which will represent
the current request initiated by the Modbus master. In case of failure the returned
request ID will be 0.

When successful this function will also invoke the :cb:`Modbus Master Read Holding Registers Response`
callback. In this callback the Request ID provided by the callback argument must be matched
with the Request ID returned from this function to verify that the callback is indeed for a
particular request.
"""
function modbus_master_read_holding_registers(device::BrickletRS485, slave_address, starting_address, count)
    return device.deviceInternal.modbus_master_read_holding_registers(slave_address, starting_address, count)
end

export modbus_slave_answer_write_single_coil_request
"""
    $(SIGNATURES)

In Modbus slave mode this function can be used to answer a master request to
write a single coil.

* Request ID: Request ID of the corresponding request that is being answered.

This function must be called from the :cb:`Modbus Slave Write Single Coil Request`
callback with the Request ID as provided by the arguments of the callback.
"""
function modbus_slave_answer_write_single_coil_request(device::BrickletRS485, request_id)
    device.deviceInternal.modbus_slave_answer_write_single_coil_request(request_id)
end

export modbus_master_write_single_coil
"""
    $(SIGNATURES)

In Modbus master mode this function can be used to write a single coil of a slave.
This function creates a Modbus function code 5 request.

* Slave Address: Address of the target Modbus slave.
* Coil Address: Number of the coil to be written. For backwards compatibility reasons, this parameter is called Starting Address. It is not an address, but instead a coil number in the range of 1 to 65536.
* Coil Value: Value to be written.

Upon success the function will return a non-zero request ID which will represent
the current request initiated by the Modbus master. In case of failure the returned
request ID will be 0.

When successful this function will also invoke the :cb:`Modbus Master Write Single Coil Response`
callback. In this callback the Request ID provided by the callback argument must be matched
with the Request ID returned from this function to verify that the callback is indeed for a
particular request.
"""
function modbus_master_write_single_coil(device::BrickletRS485, slave_address, coil_address, coil_value)
    return device.deviceInternal.modbus_master_write_single_coil(slave_address, coil_address, coil_value)
end

export modbus_slave_answer_write_single_register_request
"""
    $(SIGNATURES)

In Modbus slave mode this function can be used to answer a master request to
write a single register.

* Request ID: Request ID of the corresponding request that is being answered.

This function must be called from the :cb:`Modbus Slave Write Single Register Request`
callback with the Request ID, Register Address and Register Value as provided by
the arguments of the callback.
"""
function modbus_slave_answer_write_single_register_request(device::BrickletRS485, request_id)
    device.deviceInternal.modbus_slave_answer_write_single_register_request(request_id)
end

export modbus_master_write_single_register
"""
    $(SIGNATURES)

In Modbus master mode this function can be used to write a single holding register of a
slave. This function creates a Modbus function code 6 request.

* Slave Address: Address of the target Modbus slave.
* Register Address: Number of the holding register to be written. For backwards compatibility reasons, this parameter is called Starting Address. It is not an address, but instead a holding register number in the range of 1 to 65536. The prefix digit 4 (for holding register) is implicit and must be omitted.
* Register Value: Value to be written.

Upon success the function will return a non-zero request ID which will represent
the current request initiated by the Modbus master. In case of failure the returned
request ID will be 0.

When successful this function will also invoke the :cb:`Modbus Master Write Single Register Response`
callback. In this callback the Request ID provided by the callback argument must be matched
with the Request ID returned from this function to verify that the callback is indeed for a
particular request.
"""
function modbus_master_write_single_register(device::BrickletRS485, slave_address, register_address, register_value)
    return device.deviceInternal.modbus_master_write_single_register(slave_address, register_address, register_value)
end

export modbus_slave_answer_write_multiple_coils_request
"""
    $(SIGNATURES)

In Modbus slave mode this function can be used to answer a master request to
write multiple coils.

* Request ID: Request ID of the corresponding request that is being answered.

This function must be called from the :cb:`Modbus Slave Write Multiple Coils Request`
callback with the Request ID of the callback.
"""
function modbus_slave_answer_write_multiple_coils_request(device::BrickletRS485, request_id)
    device.deviceInternal.modbus_slave_answer_write_multiple_coils_request(request_id)
end

export modbus_master_write_multiple_coils_low_level
"""
    $(SIGNATURES)

In Modbus master mode this function can be used to write multiple coils of a slave.
This function creates a Modbus function code 15 request.

* Slave Address: Address of the target Modbus slave.
* Starting Address: Number of the first coil to write. For backwards compatibility reasons, this parameter is called Starting Address.It is not an address, but instead a coil number in the range of 1 to 65536.

Upon success the function will return a non-zero request ID which will represent
the current request initiated by the Modbus master. In case of failure the returned
request ID will be 0.

When successful this function will also invoke the :cb:`Modbus Master Write Multiple Coils Response`
callback. In this callback the Request ID provided by the callback argument must be matched
with the Request ID returned from this function to verify that the callback is indeed for a
particular request.
"""
function modbus_master_write_multiple_coils_low_level(device::BrickletRS485, slave_address, starting_address, coils_length, coils_chunk_offset, coils_chunk_data)
    return device.deviceInternal.modbus_master_write_multiple_coils_low_level(slave_address, starting_address, coils_length, coils_chunk_offset, coils_chunk_data)
end

export modbus_slave_answer_write_multiple_registers_request
"""
    $(SIGNATURES)

In Modbus slave mode this function can be used to answer a master request to
write multiple registers.

* Request ID: Request ID of the corresponding request that is being answered.

This function must be called from the :cb:`Modbus Slave Write Multiple Registers Request`
callback with the Request ID of the callback.
"""
function modbus_slave_answer_write_multiple_registers_request(device::BrickletRS485, request_id)
    device.deviceInternal.modbus_slave_answer_write_multiple_registers_request(request_id)
end

export modbus_master_write_multiple_registers_low_level
"""
    $(SIGNATURES)

In Modbus master mode this function can be used to write multiple registers of a slave.
This function creates a Modbus function code 16 request.

* Slave Address: Address of the target Modbus slave.
* Starting Address: Number of the first holding register to write. For backwards compatibility reasons, this parameter is called Starting Address. It is not an address, but instead a holding register number in the range of 1 to 65536. The prefix digit 4 (for holding register) is implicit and must be omitted.

Upon success the function will return a non-zero request ID which will represent
the current request initiated by the Modbus master. In case of failure the returned
request ID will be 0.

When successful this function will also invoke the :cb:`Modbus Master Write Multiple Registers Response`
callback. In this callback the Request ID provided by the callback argument must be matched
with the Request ID returned from this function to verify that the callback is indeed for a
particular request.
"""
function modbus_master_write_multiple_registers_low_level(device::BrickletRS485, slave_address, starting_address, registers_length, registers_chunk_offset, registers_chunk_data)
    return device.deviceInternal.modbus_master_write_multiple_registers_low_level(slave_address, starting_address, registers_length, registers_chunk_offset, registers_chunk_data)
end

export modbus_slave_answer_read_discrete_inputs_request_low_level
"""
    $(SIGNATURES)

In Modbus slave mode this function can be used to answer a master request to
read discrete inputs.

* Request ID: Request ID of the corresponding request that is being answered.
* Discrete Inputs: Data that is to be sent to the Modbus master for the corresponding request.

This function must be called from the :cb:`Modbus Slave Read Discrete Inputs Request`
callback with the Request ID as provided by the argument of the callback.
"""
function modbus_slave_answer_read_discrete_inputs_request_low_level(device::BrickletRS485, request_id, discrete_inputs_length, discrete_inputs_chunk_offset, discrete_inputs_chunk_data)
    device.deviceInternal.modbus_slave_answer_read_discrete_inputs_request_low_level(request_id, discrete_inputs_length, discrete_inputs_chunk_offset, discrete_inputs_chunk_data)
end

export modbus_master_read_discrete_inputs
"""
    $(SIGNATURES)

In Modbus master mode this function can be used to read discrete inputs from a slave.
This function creates a Modbus function code 2 request.

* Slave Address: Address of the target Modbus slave.
* Starting Address: Number of the first discrete input to read. For backwards compatibility reasons, this parameter is called Starting Address. It is not an address, but instead a discrete input number in the range of 1 to 65536. The prefix digit 1 (for discrete input) is implicit and must be omitted.
* Count: Number of discrete inputs to read.

Upon success the function will return a non-zero request ID which will represent
the current request initiated by the Modbus master. In case of failure the returned
request ID will be 0.

When successful this function will also invoke the :cb:`Modbus Master Read Discrete Inputs Response`
callback. In this callback the Request ID provided by the callback argument must be matched
with the Request ID returned from this function to verify that the callback is indeed for a
particular request.
"""
function modbus_master_read_discrete_inputs(device::BrickletRS485, slave_address, starting_address, count)
    return device.deviceInternal.modbus_master_read_discrete_inputs(slave_address, starting_address, count)
end

export modbus_slave_answer_read_input_registers_request_low_level
"""
    $(SIGNATURES)

In Modbus slave mode this function can be used to answer a master request to
read input registers.

* Request ID: Request ID of the corresponding request that is being answered.
* Input Registers: Data that is to be sent to the Modbus master for the corresponding request.

This function must be called from the :cb:`Modbus Slave Read Input Registers Request` callback
with the Request ID as provided by the argument of the callback.
"""
function modbus_slave_answer_read_input_registers_request_low_level(device::BrickletRS485, request_id, input_registers_length, input_registers_chunk_offset, input_registers_chunk_data)
    device.deviceInternal.modbus_slave_answer_read_input_registers_request_low_level(request_id, input_registers_length, input_registers_chunk_offset, input_registers_chunk_data)
end

export modbus_master_read_input_registers
"""
    $(SIGNATURES)

In Modbus master mode this function can be used to read input registers from a slave.
This function creates a Modbus function code 4 request.

* Slave Address: Address of the target Modbus slave.
* Starting Address: Number of the first input register to read. For backwards compatibility reasons, this parameter is called Starting Address. It is not an address, but instead an input register number in the range of 1 to 65536. The prefix digit 3 (for input register) is implicit and must be omitted.
* Count: Number of input registers to read.

Upon success the function will return a non-zero request ID which will represent
the current request initiated by the Modbus master. In case of failure the returned
request ID will be 0.

When successful this function will also invoke the :cb:`Modbus Master Read Input Registers Response`
callback. In this callback the Request ID provided by the callback argument must be matched
with the Request ID returned from this function to verify that the callback is indeed for a
particular request.
"""
function modbus_master_read_input_registers(device::BrickletRS485, slave_address, starting_address, count)
    return device.deviceInternal.modbus_master_read_input_registers(slave_address, starting_address, count)
end

export set_frame_readable_callback_configuration
"""
    $(SIGNATURES)

Configures the :cb:`Frame Readable` callback. The frame size is the number of bytes, that have to be readable to trigger the callback.
A frame size of 0 disables the callback. A frame size greater than 0 enables the callback and disables the :cb:`Read` callback.

By default the callback is disabled.

.. versionadded:: 2.0.5\$nbsp;(Plugin)
"""
function set_frame_readable_callback_configuration(device::BrickletRS485, frame_size)
    device.deviceInternal.set_frame_readable_callback_configuration(frame_size)
end

export get_frame_readable_callback_configuration
"""
    $(SIGNATURES)

Returns the callback configuration as set by :func:`Set Frame Readable Callback Configuration`.

.. versionadded:: 2.0.5\$nbsp;(Plugin)
"""
function get_frame_readable_callback_configuration(device::BrickletRS485)
    return device.deviceInternal.get_frame_readable_callback_configuration()
end

export get_spitfp_error_count
"""
    $(SIGNATURES)

Returns the error count for the communication between Brick and Bricklet.

The errors are divided into

* ACK checksum errors,
* message checksum errors,
* framing errors and
* overflow errors.

The errors counts are for errors that occur on the Bricklet side. All
Bricks have a similar function that returns the errors on the Brick side.
"""
function get_spitfp_error_count(device::BrickletRS485)
    return device.deviceInternal.get_spitfp_error_count()
end

export set_bootloader_mode
"""
    $(SIGNATURES)

Sets the bootloader mode and returns the status after the requested
mode change was instigated.

You can change from bootloader mode to firmware mode and vice versa. A change
from bootloader mode to firmware mode will only take place if the entry function,
device identifier and CRC are present and correct.

This function is used by Brick Viewer during flashing. It should not be
necessary to call it in a normal user program.
"""
function set_bootloader_mode(device::BrickletRS485, mode)
    return device.deviceInternal.set_bootloader_mode(mode)
end

export get_bootloader_mode
"""
    $(SIGNATURES)

Returns the current bootloader mode, see :func:`Set Bootloader Mode`.
"""
function get_bootloader_mode(device::BrickletRS485)
    return device.deviceInternal.get_bootloader_mode()
end

export set_write_firmware_pointer
"""
    $(SIGNATURES)

Sets the firmware pointer for :func:`Write Firmware`. The pointer has
to be increased by chunks of size 64. The data is written to flash
every 4 chunks (which equals to one page of size 256).

This function is used by Brick Viewer during flashing. It should not be
necessary to call it in a normal user program.
"""
function set_write_firmware_pointer(device::BrickletRS485, pointer)
    device.deviceInternal.set_write_firmware_pointer(pointer)
end

export write_firmware
"""
    $(SIGNATURES)

Writes 64 Bytes of firmware at the position as written by
:func:`Set Write Firmware Pointer` before. The firmware is written
to flash every 4 chunks.

You can only write firmware in bootloader mode.

This function is used by Brick Viewer during flashing. It should not be
necessary to call it in a normal user program.
"""
function write_firmware(device::BrickletRS485, data)
    return device.deviceInternal.write_firmware(data)
end

export set_status_led_config
"""
    $(SIGNATURES)

Sets the status LED configuration. By default the LED shows
communication traffic between Brick and Bricklet, it flickers once
for every 10 received data packets.

You can also turn the LED permanently on/off or show a heartbeat.

If the Bricklet is in bootloader mode, the LED is will show heartbeat by default.
"""
function set_status_led_config(device::BrickletRS485, config)
    device.deviceInternal.set_status_led_config(config)
end

export get_status_led_config
"""
    $(SIGNATURES)

Returns the configuration as set by :func:`Set Status LED Config`
"""
function get_status_led_config(device::BrickletRS485)
    return device.deviceInternal.get_status_led_config()
end

export get_chip_temperature
"""
    $(SIGNATURES)

Returns the temperature as measured inside the microcontroller. The
value returned is not the ambient temperature!

The temperature is only proportional to the real temperature and it has bad
accuracy. Practically it is only useful as an indicator for
temperature changes.
"""
function get_chip_temperature(device::BrickletRS485)
    return device.deviceInternal.get_chip_temperature()
end

export reset
"""
    $(SIGNATURES)

Calling this function will reset the Bricklet. All configurations
will be lost.

After a reset you have to create new device objects,
calling functions on the existing ones will result in
undefined behavior!
"""
function reset(device::BrickletRS485)
    device.deviceInternal.reset()
end

export write_uid
"""
    $(SIGNATURES)

Writes a new UID into flash. If you want to set a new UID
you have to decode the Base58 encoded UID string into an
integer first.

We recommend that you use Brick Viewer to change the UID.
"""
function write_uid(device::BrickletRS485, uid)
    device.deviceInternal.write_uid(uid)
end

export read_uid
"""
    $(SIGNATURES)

Returns the current UID as an integer. Encode as
Base58 to get the usual string version.
"""
function read_uid(device::BrickletRS485)
    return device.deviceInternal.read_uid()
end

export get_identity
"""
    $(SIGNATURES)

Returns the UID, the UID where the Bricklet is connected to,
the position, the hardware and firmware version as well as the
device identifier.

The position can be 'a', 'b', 'c', 'd', 'e', 'f', 'g' or 'h' (Bricklet Port).
A Bricklet connected to an :ref:`Isolator Bricklet <isolator_bricklet>` is always at
position 'z'.

The device identifier numbers can be found :ref:`here <device_identifier>`.
|device_identifier_constant|
"""
function get_identity(device::BrickletRS485)
    return device.deviceInternal.get_identity()
end

export write
"""
Writes characters to the RS485 interface. The characters can be binary data,
ASCII or similar is not necessary.

The return value is the number of characters that were written.

See :func:`Set RS485 Configuration` for configuration possibilities
regarding baudrate, parity and so on.
"""
function write(device::BrickletRS485, message)

        message = convert(Vector{String}, message)

    if length(message) > 65535
        throw(TinkerforgeInvalidParameterError("Message can be at most 65535 items long"))
    end

    message_length = length(message)
    message_chunk_offset = 0

    if message_length == 0
        message_chunk_data = ['\0'] * 60
        ret = write_low_level(device, message_length, message_chunk_offset, message_chunk_data)
        message_written = ret
    else
        message_written = 0

        lock(device.stream_lock) do
            while message_chunk_offset < message_length
                message_chunk_data = create_chunk_data(message, message_chunk_offset, 60, '\0')
                ret = write_low_level(device, message_length, message_chunk_offset, message_chunk_data)
                message_written += ret

                if ret < 60
                    break # either last chunk or short write
                end

                message_chunk_offset += 60
            end
        end
    end

        return message_written
end

export read
"""
Returns up to *length* characters from receive buffer.

Instead of polling with this function, you can also use
callbacks. But note that this function will return available
data only when the read callback is disabled.
See :func:`Enable Read Callback` and :cb:`Read` callback.
"""
function read(device::BrickletRS485, length)

        length = UInt16(length)

    lock(device.stream_lock) do
        ret = read_low_level(device, length)
            message_length = ret.message_length
        message_out_of_sync = ret.message_chunk_offset != 0

        message_data = ret.message_chunk_data

        while !message_out_of_sync && length(message_data) < message_length
            ret = read_low_level(device, length)
                message_length = ret.message_length
            message_out_of_sync = ret.message_chunk_offset != length(message_data)
            message_data += ret.message_chunk_data
        end

        if message_out_of_sync # discard remaining stream to bring it back in-sync
            while ret.message_chunk_offset + 60 < message_length
                ret = read_low_level(device, length)
                    message_length = ret.message_length
            end

            throw(TinkerforgeStreamOutOfSyncError("Message stream is out-of-sync"))
        end
    end

        return message_data[:message_length]
end

export modbus_slave_answer_read_coils_request
"""
In Modbus slave mode this function can be used to answer a master request to
read coils.

* Request ID: Request ID of the corresponding request that is being answered.
* Coils: Data that is to be sent to the Modbus master for the corresponding request.

This function must be called from the :cb:`Modbus Slave Read Coils Request` callback
with the Request ID as provided by the argument of the callback.
"""
function modbus_slave_answer_read_coils_request(device::BrickletRS485, request_id, coils)

        request_id = UInt8(request_id)
    coils = convert(Vector{Bool}, coils)

    if length(coils) > 65535
        throw(TinkerforgeInvalidParameterError("Coils can be at most 65535 items long"))
    end

    coils_length = length(coils)
    coils_chunk_offset = 0

    if coils_length == 0
        coils_chunk_data = [False] * 472
        ret = modbus_slave_answer_read_coils_request_low_level(device, request_id, coils_length, coils_chunk_offset, coils_chunk_data)
    else
        lock(device.stream_lock) do
            while coils_chunk_offset < coils_length
                coils_chunk_data = create_chunk_data(coils, coils_chunk_offset, 472, False)
                ret = modbus_slave_answer_read_coils_request_low_level(device, request_id, coils_length, coils_chunk_offset, coils_chunk_data)
                coils_chunk_offset += 472
            end
        end
    end

        return ret
end

export modbus_slave_answer_read_holding_registers_request
"""
In Modbus slave mode this function can be used to answer a master request to
read holding registers.

* Request ID: Request ID of the corresponding request that is being answered.
* Holding Registers: Data that is to be sent to the Modbus master for the corresponding request.

This function must be called from the :cb:`Modbus Slave Read Holding Registers Request`
callback with the Request ID as provided by the argument of the callback.
"""
function modbus_slave_answer_read_holding_registers_request(device::BrickletRS485, request_id, holding_registers)

        request_id = UInt8(request_id)
    holding_registers = convert(Vector{UInt16}, holding_registers)

    if length(holding_registers) > 65535
        throw(TinkerforgeInvalidParameterError("Holding Registers can be at most 65535 items long"))
    end

    holding_registers_length = length(holding_registers)
    holding_registers_chunk_offset = 0

    if holding_registers_length == 0
        holding_registers_chunk_data = [0] * 29
        ret = modbus_slave_answer_read_holding_registers_request_low_level(device, request_id, holding_registers_length, holding_registers_chunk_offset, holding_registers_chunk_data)
    else
        lock(device.stream_lock) do
            while holding_registers_chunk_offset < holding_registers_length
                holding_registers_chunk_data = create_chunk_data(holding_registers, holding_registers_chunk_offset, 29, 0)
                ret = modbus_slave_answer_read_holding_registers_request_low_level(device, request_id, holding_registers_length, holding_registers_chunk_offset, holding_registers_chunk_data)
                holding_registers_chunk_offset += 29
            end
        end
    end

        return ret
end

export modbus_master_write_multiple_coils
"""
In Modbus master mode this function can be used to write multiple coils of a slave.
This function creates a Modbus function code 15 request.

* Slave Address: Address of the target Modbus slave.
* Starting Address: Number of the first coil to write. For backwards compatibility reasons, this parameter is called Starting Address.It is not an address, but instead a coil number in the range of 1 to 65536.

Upon success the function will return a non-zero request ID which will represent
the current request initiated by the Modbus master. In case of failure the returned
request ID will be 0.

When successful this function will also invoke the :cb:`Modbus Master Write Multiple Coils Response`
callback. In this callback the Request ID provided by the callback argument must be matched
with the Request ID returned from this function to verify that the callback is indeed for a
particular request.
"""
function modbus_master_write_multiple_coils(device::BrickletRS485, slave_address, starting_address, coils)

        slave_address = UInt8(slave_address)
    starting_address = UInt32(starting_address)
    coils = convert(Vector{Bool}, coils)

    if length(coils) > 65535
        throw(TinkerforgeInvalidParameterError("Coils can be at most 65535 items long"))
    end

    coils_length = length(coils)
    coils_chunk_offset = 0

    if coils_length == 0
        coils_chunk_data = [False] * 440
        ret = modbus_master_write_multiple_coils_low_level(device, slave_address, starting_address, coils_length, coils_chunk_offset, coils_chunk_data)
    else
        lock(device.stream_lock) do
            while coils_chunk_offset < coils_length
                coils_chunk_data = create_chunk_data(coils, coils_chunk_offset, 440, False)
                ret = modbus_master_write_multiple_coils_low_level(device, slave_address, starting_address, coils_length, coils_chunk_offset, coils_chunk_data)
                coils_chunk_offset += 440
            end
        end
    end

        return ret
end

export modbus_master_write_multiple_registers
"""
In Modbus master mode this function can be used to write multiple registers of a slave.
This function creates a Modbus function code 16 request.

* Slave Address: Address of the target Modbus slave.
* Starting Address: Number of the first holding register to write. For backwards compatibility reasons, this parameter is called Starting Address. It is not an address, but instead a holding register number in the range of 1 to 65536. The prefix digit 4 (for holding register) is implicit and must be omitted.

Upon success the function will return a non-zero request ID which will represent
the current request initiated by the Modbus master. In case of failure the returned
request ID will be 0.

When successful this function will also invoke the :cb:`Modbus Master Write Multiple Registers Response`
callback. In this callback the Request ID provided by the callback argument must be matched
with the Request ID returned from this function to verify that the callback is indeed for a
particular request.
"""
function modbus_master_write_multiple_registers(device::BrickletRS485, slave_address, starting_address, registers)

        slave_address = UInt8(slave_address)
    starting_address = UInt32(starting_address)
    registers = convert(Vector{UInt16}, registers)

    if length(registers) > 65535
        throw(TinkerforgeInvalidParameterError("Registers can be at most 65535 items long"))
    end

    registers_length = length(registers)
    registers_chunk_offset = 0

    if registers_length == 0
        registers_chunk_data = [0] * 27
        ret = modbus_master_write_multiple_registers_low_level(device, slave_address, starting_address, registers_length, registers_chunk_offset, registers_chunk_data)
    else
        lock(device.stream_lock) do
            while registers_chunk_offset < registers_length
                registers_chunk_data = create_chunk_data(registers, registers_chunk_offset, 27, 0)
                ret = modbus_master_write_multiple_registers_low_level(device, slave_address, starting_address, registers_length, registers_chunk_offset, registers_chunk_data)
                registers_chunk_offset += 27
            end
        end
    end

        return ret
end

export modbus_slave_answer_read_discrete_inputs_request
"""
In Modbus slave mode this function can be used to answer a master request to
read discrete inputs.

* Request ID: Request ID of the corresponding request that is being answered.
* Discrete Inputs: Data that is to be sent to the Modbus master for the corresponding request.

This function must be called from the :cb:`Modbus Slave Read Discrete Inputs Request`
callback with the Request ID as provided by the argument of the callback.
"""
function modbus_slave_answer_read_discrete_inputs_request(device::BrickletRS485, request_id, discrete_inputs)

        request_id = UInt8(request_id)
    discrete_inputs = convert(Vector{Bool}, discrete_inputs)

    if length(discrete_inputs) > 65535
        throw(TinkerforgeInvalidParameterError("Discrete Inputs can be at most 65535 items long"))
    end

    discrete_inputs_length = length(discrete_inputs)
    discrete_inputs_chunk_offset = 0

    if discrete_inputs_length == 0
        discrete_inputs_chunk_data = [False] * 472
        ret = modbus_slave_answer_read_discrete_inputs_request_low_level(device, request_id, discrete_inputs_length, discrete_inputs_chunk_offset, discrete_inputs_chunk_data)
    else
        lock(device.stream_lock) do
            while discrete_inputs_chunk_offset < discrete_inputs_length
                discrete_inputs_chunk_data = create_chunk_data(discrete_inputs, discrete_inputs_chunk_offset, 472, False)
                ret = modbus_slave_answer_read_discrete_inputs_request_low_level(device, request_id, discrete_inputs_length, discrete_inputs_chunk_offset, discrete_inputs_chunk_data)
                discrete_inputs_chunk_offset += 472
            end
        end
    end

        return ret
end

export modbus_slave_answer_read_input_registers_request
"""
In Modbus slave mode this function can be used to answer a master request to
read input registers.

* Request ID: Request ID of the corresponding request that is being answered.
* Input Registers: Data that is to be sent to the Modbus master for the corresponding request.

This function must be called from the :cb:`Modbus Slave Read Input Registers Request` callback
with the Request ID as provided by the argument of the callback.
"""
function modbus_slave_answer_read_input_registers_request(device::BrickletRS485, request_id, input_registers)

        request_id = UInt8(request_id)
    input_registers = convert(Vector{UInt16}, input_registers)

    if length(input_registers) > 65535
        throw(TinkerforgeInvalidParameterError("Input Registers can be at most 65535 items long"))
    end

    input_registers_length = length(input_registers)
    input_registers_chunk_offset = 0

    if input_registers_length == 0
        input_registers_chunk_data = [0] * 29
        ret = modbus_slave_answer_read_input_registers_request_low_level(device, request_id, input_registers_length, input_registers_chunk_offset, input_registers_chunk_data)
    else
        lock(device.stream_lock) do
            while input_registers_chunk_offset < input_registers_length
                input_registers_chunk_data = create_chunk_data(input_registers, input_registers_chunk_offset, 29, 0)
                ret = modbus_slave_answer_read_input_registers_request_low_level(device, request_id, input_registers_length, input_registers_chunk_offset, input_registers_chunk_data)
                input_registers_chunk_offset += 29
            end
        end
    end

        return ret
end

export register_callback
"""
Registers the given *function* with the given *callback_id*.
"""
function register_callback(device::BrickletRS485, callback_id, function_)
    if isnothing(function_)
        device.registered_callbacks.pop(callback_id, None)
    else
        device.registered_callbacks[callback_id] = function_
    end
end


text:
nparams(m) = (ps = params(m); length(ps) > 0 ? sum(length, ps) : 0)

function gradientandvalue(f, ps::Zygote.Params)
    y, back = Zygote.pullback(f, ps)
    losscheck(y)
    gs = back(Zygote.sensitivity(y))
    y, gs
end

####
#### FluxTrainerIterator
####

Base.@kwdef struct FluxTrainer{L, O, CB}
    lossfn::L = nothing
    optimiser::O = ADAM()
    szbatch::Union{Nothing,Int} = nothing
    batchdim::Union{Int,LearnBase.ObsDimension} = LearnBase.ObsDim.Last()
    stopcb::CB = infinitecb
end

function (p::FluxTrainer)(model, datas::Vararg{<:AbstractArray}; kwargs...)
    lossfn = haskey(kwargs, :lossfn) ? kwargs[:lossfn] : p.lossfn
    optimiser = haskey(kwargs, :optimiser) ? kwargs[:optimiser] : p.optimiser
    szbatch = haskey(kwargs, :szbatch) ? kwargs[:szbatch] : p.szbatch
    batchdim = haskey(kwargs, :batchdim) ? kwargs[:batchdim] : p.batchdim
    stopcb = haskey(kwargs, :stopcb) ? kwargs[:stopcb] : p.stopcb

    isnothing(lossfn) && error("`lossfn` not specified and no default provided")
    !(isnothing(szbatch) || szbatch isa Integer) && error("`szbatch` must be `nothing` or <:Integer")

    datas = isnothing(szbatch) ? (datas,) : eachbatch(datas, szbatch, batchdim)
    FluxTrainerIterator(model, datas, optimiser, lossfn, batchdim, stopcb)
end

struct FluxTrainerIterator{M,D,O,L,DIM,CB}
    model::M
    datas::D
    optimiser::O
    lossfn::L
    batchdim::DIM
    stopcb::CB
end

struct FluxTrainerState
    nepochs::Int
    nbatches::Int
    nsamples::Int
    avgloss::Float64
end
FluxTrainerState() = FluxTrainerState(0, 0, 0, 0)

function Base.iterate(ft::FluxTrainerIterator, state = FluxTrainerState())
    ft.stopcb(state) && return nothing

    model = ft.model
    nbatches = 0
    nsamples = 0
    totalloss = 0.0
    ps = params(ft.model)

    loss = let l=ft.lossfn, m=model
        (d...) -> l(m, d...)
    end

    for batch in ft.datas
        batchloss, gs = let batch=batch, ps=ps
            gradientandvalue(() -> loss(batch...), ps)
        end
        Flux.Optimise.update!(ft.optimiser, ps, gs)

        nbatches += 1
        nsamples += nobs(first(batch))
        totalloss += Float64(batchloss)
    end

    newstate = FluxTrainerState(
        state.nepochs + 1,
        state.nbatches + nbatches,
        state.nsamples + nsamples,
        totalloss / nsamples,
    )

    newstate, newstate
end

####
#### Utils
####
function multilayer_perceptron(
    d1,
    d2,
    d...;
    σ = identity,
    σ_final = identity,
    initW = Flux.glorot_uniform,
    initb = zeros,
    initW_final = Flux.glorot_uniform,
    initb_final = zeros,
    dtype = Float32,
)

    layers = []
    ds = (d1, d2, d...)
    for i = 2:(length(ds)-1)
        in, out = ds[i-1], ds[i]
        push!(layers, Flux.Dense(dtype.(initW(out, in)), dtype.(initb(out)), σ))
    end

    in, out = ds[end-1], ds[end]
    push!(
        layers,
        Flux.Dense(dtype.(initW_final(out, in)), dtype.(initb_final(out)), σ_final),
    )
    @assert length(layers) == length(ds) - 1

    Flux.Chain(layers...)
end

function flatupdate!(m, gs::AbstractVector)
    np = nparams(m)
    np == length(gs) || throw(ArgumentError("length(gs) != number of parameters"))

    from = firstindex(gs)
    @uviews gs for p in params(m)
        p = vec(Zygote.unwrap(p))
        to = from + length(p) - 1
        p .+= uview(gs, from:to)
        from += length(p)
    end
    m
end

function copygrad!(flatgrad::AbstractVector, ps::Zygote.Params, gs::Grads)
    from = firstindex(flatgrad)
    for p in ps
        g = gs[p]
        g === nothing && continue
        copyto!(flatgrad, from, g, firstindex(g), length(g))
        from += length(g)
    end
    flatgrad
end

# TODO support more than Matrix
function orthonormal(d1::Integer, d2::Integer)
    d1 > 0 && d2 > 0 || error("d1 and d2 must be > 0")

    shape = (d1, d2)
    A = randn(shape)
    U, _, Vt = svd(A)
    A = size(U) == shape ? U : Array(Vt')
    @assert size(A) == shape
    @assert !any(isnan, A)
    A
end

promote_modeltype(m, ms...) = promote_type(promote_modeltype(m), promote_modeltype(ms...))
function promote_modeltype(m)
    ls = filter(x -> x isa Union{Number,AbstractArray}, leaves(m))
    ls = map(Zygote.unwrap, ls) # iff any of ls is a TrackedArray/TrackedReal
    if length(ls) == 0
        throw(ArgumentError("m has no leaves <: Union{Number, AbstractArray}"))
    elseif length(ls) == 1
        return _paramtype(first(ls))
    else
        T = _paramtype(first(ls))
        for i = 2:length(ls)
            T = promote_type(T, _paramtype(ls[i]))
        end
        return T
    end
end

function _paramtype(x)
    if x isa Number
        return typeof(x)
    elseif x isa AbstractArray
        return eltype(x)
    else
        throw(ArgumentError("Expected x <: Union{Number, AbstractArray}"))
    end
end

function losscheck(x)
    x isa Real || error("Function output is not scalar")
    isinf(x) && error("Loss is infinite")
    isnan(x) && error("Loss is NaN")
end

function _leaves1(f, x)
    func, re = Flux.functor(x)
    map(f, func)
end

function leaves(x; cache = IdDict())
    haskey(cache, x) && return cache[x]
    cache[x] = Flux.isleaf(x) ? x : _leaves1(x -> leaves(x, cache = cache), x)
    collect(values(cache))
end


text:
# merge mutiple JSON objects garnered via `--meta-json`
function merge_json_objects(objs::Vector)
    merged = Dict()
    for obj in objs
        for k in keys(obj)
            if !haskey(merged, k)
                merged[k] = obj[k]
            else
                if merged[k] != obj[k]
                    if !isa(merged[k], Array)
                        merged[k] = [merged[k]]
                    end

                    if isa(obj[k], Array)
                        append!(merged[k], obj[k])
                    else
                        push!(merged[k], obj[k])
                    end
                    merged[k] = unique(merged[k])
                end
            end
        end
    end
    return merged
end

# Fix various things that go wrong with the JSON translation
function cleanup_merged_object!(meta::Dict)
    for idx in 1:length(meta["sources"])
        if isa(meta["sources"][idx], Dict) && length(meta["sources"][idx]) == 1
            meta["sources"][idx] = first(meta["sources"][idx])
        end
    end
    meta["version"] = VersionNumber(meta["version"])
    return meta
end


text:
"""
    v = normalized_legendre(x,n)

Calculates a single value of the `n`-th order Legendre polynomial of `x`.
It calls `Jacobi.legendre`.
"""
function normalized_legendre(x,n)
   a = sqrt((2*n+1)/2)
   return a*legendre(x,n)
end

"""
    M = normalized_legendre_matrix(t,n)

Calculates a matrix with the `n`-th order Legendre coefficients on time points `t`, a vector or range.

```juliadoctests
# up to 3rd order coefficients for 5 to 12
julia> M = normalized_legendre_matrix(5:12,3)

# same expression
julia> M = normalized_legendre_matrix([5,6,7,8,9,10,11,12],3)
```
"""
function normalized_legendre_matrix(t::Union{UnitRange,Vector},n)
   if !issorted(t)
      throw(ArgumentError("time points not sorted"))
   end
   tmin = minimum(t)
   tmax = maximum(t)
   x = -1 .+ 2*( (t .- tmin)/(tmax-tmin) )
   M = [normalized_legendre(y,k) for y=x,k=0:n]
   return M
end

"""
    vare = hrv_class(ve,rangeset)

Generate a vector containing residual variances from a vector of heterogeneous residual variances `ve` and a set of ranges `rangeset`.

```juliadoctests
julia> vare = hrv_class([10.0,20.0],[3:5,6:9])
7-element Vector{Float64}:
10.0
10.0
10.0
20.0
20.0
20.0
20.0
```
"""
function hrv_class(ve,rangeset)
   if length(ve)!=length(rangeset)
      throw(DimensionMismatch("ve and rangeset"))
   end
   tmin = minimum(rangeset[1])
   tmax = maximum(rangeset[end])
   vare = zeros(tmax-tmin+1)
   for i in 1:length(rangeset)
      for t in rangeset[i]
         vare[t-tmin+1] = ve[i]
      end
   end
   return vare
end


text:
using ArchGDAL, GeoData, Test, Statistics, Dates, Plots, NCDatasets
using GeoData: window, mode, span, sampling, name

include(joinpath(dirname(pathof(GeoData)), "../test/test_utils.jl"))

path = maybedownload("https://download.osgeo.org/geotiff/samples/gdal_eg/cea.tif")

@testset "GDALarray" begin
    gdalarray = GDALarray(path; mappedcrs=EPSG(4326), name=:test);
    metadata(dims(gdalarray))

    @testset "open" begin
        @test open(A -> A[Lat=1], gdalarray) == gdalarray[:, 1, :]
    end

    @testset "array properties" begin
        @test size(gdalarray) == (514, 515, 1)
        @test gdalarray isa GDALarray{UInt8,3}
    end

    @testset "dimensions" begin
        @test length(dims(gdalarray, Lon)) == 514
        @test ndims(gdalarray) == 3
        @test dims(gdalarray) isa Tuple{<:Lon,<:Lat,<:Band}
        @test mode(gdalarray, Band) == DimensionalData.Categorical(Ordered())
        @test span(gdalarray, (Lat, Lon)) ==
            (Regular(-60.02213698319351), Regular(60.02213698319374))
        @test sampling(gdalarray, (Lat, Lon)) ==
            (Intervals(Start()), Intervals(Start()))
        @test refdims(gdalarray) == ()
        # Bounds calculated in python using rasterio
        @test all(bounds(gdalarray, Lat) .≈ (4224973.143255847, 4255884.5438021915))
        @test all(bounds(gdalarray, Lon) .≈ (-28493.166784412522, 2358.211624949061))
    end

    @testset "other fields" begin
        # This file has an inorrect missing value
        @test missingval(gdalarray) == -1.0e10
        @test metadata(gdalarray) isa GDALarrayMetadata
        @test basename(metadata(gdalarray).val[:filepath]) == "cea.tif"
        @test name(gdalarray) == :test
        @test label(gdalarray) == "test"
        @test units(gdalarray) == nothing
        @test mappedcrs(dims(gdalarray, Lat)) == EPSG(4326)
        @test mappedcrs(dims(gdalarray, Lon)) == EPSG(4326)
        @test mappedcrs(gdalarray) == EPSG(4326)
        @test mappedcrs(gdalarray[Lat(1)]) == EPSG(4326)
        @test_throws ErrorException mappedcrs(gdalarray[Lat(1), Lon(1)])
        wkt = WellKnownText(GeoFormatTypes.CRS(),
          "PROJCS[\"unnamed\",GEOGCS[\"NAD27\",DATUM[\"North_American_Datum_1927\",SPHEROID[\"Clarke 1866\",6378206.4,294.978698213898,AUTHORITY[\"EPSG\",\"7008\"]],AUTHORITY[\"EPSG\",\"6267\"]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4267\"]],PROJECTION[\"Cylindrical_Equal_Area\"],PARAMETER[\"standard_parallel_1\",33.75],PARAMETER[\"central_meridian\",-117.333333333333],PARAMETER[\"false_easting\",0],PARAMETER[\"false_northing\",0],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]],AXIS[\"Easting\",EAST],AXIS[\"Northing\",NORTH]]")
        @test crs(dims(gdalarray, Lat)) == wkt
        @test crs(dims(gdalarray, Lon)) == wkt
        @test crs(gdalarray) == wkt
        @test crs(gdalarray[Lat(1)]) == wkt
        @test_throws ErrorException crs(gdalarray[Lat(1), Lon(1)])
    end

    @testset "indexing" begin
        @test gdalarray[Band(1)] isa GeoArray{UInt8,2}
        @test gdalarray[Lat(1), Band(1)] isa GeoArray{UInt8,1}
        @test gdalarray[Lon(1), Band(1)] isa GeoArray{UInt8,1}
        @test gdalarray[Lon(1), Lat(1), Band(1)] isa UInt8
        @test gdalarray[1, 1, 1] isa UInt8
        # Value indexed in python with rasterio
        @test gdalarray[Lat(21), Lon(21), Band(1)] == 82
    end

    @testset "methods" begin
        mean(gdalarray; dims=Lat) == mean(data(gdalarray); dims=2)
    end

    @testset "selectors" begin
        # TODO verify the value with R/gdal etc
        @test gdalarray[Lat(Contains(33.8)), Lon(Contains(-117.5)), Band(1)] isa UInt8
        @test gdalarray[Lat(Between(33.7, 33.9)), Band(1)] isa GeoArray
    end

    @testset "conversion to GeoArray" begin
        geoarray = gdalarray[Lon(1:50), Lat(1:1), Band(1)]
        @test size(geoarray) == (50, 1)
        @test eltype(geoarray) <: UInt8
        @time geoarray isa GeoArray{UInt8,1}
        @test dims(geoarray) isa Tuple{<:Lon,Lat}
        @test refdims(geoarray) isa Tuple{<:Band}
        @test metadata(geoarray) == metadata(gdalarray)
        @test missingval(geoarray) == -1.0e10
        @test name(geoarray) == :test
    end

    @testset "save" begin
        gdalarray = GDALarray(path; mappedcrs=EPSG(4326), name=:test);

        @testset "2d" begin
            geoarray1 = gdalarray[Band(1)]
            filename = tempname() * ".tif"
            write(filename, GDALarray, geoarray1)
            saved1 = GDALarray(filename; mappedcrs=EPSG(4326))[Band(1)];
            @test all(saved1 .== geoarray1)
            @test typeof(saved1) == typeof(geoarray1)
            @test val(dims(saved1, Lon)) == val(dims(geoarray1, Lon))
            @test val(dims(saved1, Lat)) == val(dims(geoarray1, Lat))
            @test all(metadata.(dims(saved1)) .== metadata.(dims(geoarray1)))
            @test metadata(dims(saved1)[1]) == metadata(dims(geoarray1)[1])
            @test missingval(saved1) === missingval(geoarray1)
            @test refdims(saved1) == refdims(geoarray1) end

        @testset "3d, with subsetting" begin
            geoarray2 = gdalarray[Lat(Between(33.7, 33.9)),
                                  Lon(Between(-117.6, -117.4))]
            filename2 = tempname() * ".img"
            write(filename2, GDALarray, geoarray2)
            saved2 = GeoArray(GDALarray(filename2; name=:test, mappedcrs=EPSG(4326)))
            @test size(saved2) == size(geoarray2) == length.(dims(saved2)) == length.(dims(geoarray2))
            @test refdims(saved2) == refdims(geoarray2)
            #TODO test a file with more metadata
            @test val(metadata(saved2))[:filepath] == filename2
            @test missingval(saved2) === missingval(geoarray2)
            @test GeoData.name(saved2) == GeoData.name(geoarray2)
            @test step(mode(dims(saved2, Lat))) ≈ step(mode(dims(geoarray2, Lat)))
            @test step(mode(dims(saved2, Lon))) ≈ step(mode(dims(geoarray2, Lon)))
            @test typeof(dims(saved2)) == typeof(dims(geoarray2))
            @test all(val(dims(saved2, Band)) .≈ val(dims(geoarray2, Band)))
            @test all(val(dims(saved2, Lon)) .≈ val(dims(geoarray2, Lon)))
            @test all(val(dims(saved2, Lat)) .≈ val(dims(geoarray2, Lat)))
            @test all(metadata.(dims(saved2)) .== metadata.(dims(geoarray2)))
            @test data(saved2) == data(geoarray2)
            @test typeof(saved2) == typeof(geoarray2)
            filename3 = tempname() * ".img"
            geoarray3 = cat(gdalarray[Band(1)], gdalarray[Band(1)], gdalarray[Band(1)]; dims=Band(1:3))
            write(filename3, GDALarray, geoarray3)
            saved3 = GeoArray(GDALarray(filename3; mappedcrs=EPSG(4326)))
            @test all(saved3 .== geoarray3)
            @test val(dims(saved3, Band)) == 1:3
        end

        @testset "resave current" begin
            filename = tempname() * ".tiff"
            write(filename, gdalarray)
            gdalarray2 = GDALarray(filename)
            write(gdalarray2)
            @test convert(GeoArray, GDALarray(filename)) == convert(GeoArray, gdalarray2)
        end

        @testset "to grd" begin
            write("testgrd", GRDarray, gdalarray)
            grdarray = GRDarray("testgrd")
            @test crs(grdarray) == convert(ProjString, crs(gdalarray))
            @test bounds(grdarray) == (bounds(gdalarray))
            @test val(dims(grdarray, Lat)) == reverse(val(dims(gdalarray, Lat)))
            @test val(dims(grdarray, Lon)) ≈ val(dims(gdalarray, Lon))
            @test all(GeoArray(grdarray) .== GeoArray(gdalarray))
            @test bounds(grdarray) == bounds(gdalarray)
        end

        @testset "to netcdf" begin
            filename2 = tempname()
            write(filename2, NCDarray, gdalarray[Band(1)])
            saved = GeoArray(NCDarray(filename2; crs=crs(gdalarray)))
            @test size(saved) == size(gdalarray[Band(1)])
            @test saved ≈ reverse(gdalarray[Band(1)]; dims=Lat)
            @test index(saved, Lon) ≈ mappedindex(dims(gdalarray, Lon)) .+ 0.5step(dims(saved, Lon))
            @test mappedindex(GeoData.shiftindexloci(Center(), dims(gdalarray, Lat))) ≈ reverse(index(saved, Lat))
            @test all(mappedbounds(saved, Lon) .≈ mappedbounds(gdalarray, Lon))
            @test all(mappedbounds(saved, Lat) .≈ mappedbounds(gdalarray, Lat))
            @test all(projectedbounds(saved, Lon) .≈ projectedbounds(gdalarray, Lon))
            # For some reason this crs conversion is less accrurate than the others
            @test all(map((a, b) -> isapprox(a, b; rtol=1e-6), projectedbounds(saved, Lat),  projectedbounds(gdalarray, Lat)))
        end

    end

    @testset "show" begin
        sh = sprint(show, gdalarray)
        # Test but don't lock this down too much
        @test occursin("GDALarray", sh)
        @test occursin("Latitude", sh)
        @test occursin("Longitude", sh)
        @test occursin("Band", sh)
    end

    @testset "plot and show" begin # TODO write some tests for this
        gdalarray |> show
        gdalarray |> plot
        gdalarray[Lat(1)] |> plot
    end

end

@testset "GDAL stack" begin
    gdalstack = GDALstack((a=path, b=path));

    @testset "child array properties" begin
        @test size(gdalstack[:a]) == (514, 515, 1)
        @test gdalstack[:a] isa GeoArray{UInt8,3}
    end

    @testset "indexing" begin
        @test gdalstack[:a][Lat(2:3), Lon(1), Band(1)] == [0x00, 0x6b]
        @test gdalstack[:a][Lat(1), Lon(1), Band(1)] == 0x00
        @test gdalstack[:b, Band(1)] == gdalstack[:b][Band(1)]
        @test typeof(gdalstack[:b, Band(1)]) == typeof(gdalstack[:b][Band(1)])
    end

    @testset "window" begin
        windowedstack = GDALstack((a=path, b=path); window=(Lat(1:5), Lon(1:5), Band(1)))
        @test window(windowedstack) == (Lat(1:5), Lon(1:5), Band(1))
        windowedarray = GeoArray(windowedstack[:a])
        @test windowedarray isa GeoArray{UInt8,2}
        @test length.(dims(windowedarray)) == (5, 5)
        @test size(windowedarray) == (5, 5)
        @test windowedarray[1:3, 2:2] == reshape([0x00, 0x00, 0x00], 3, 1)
        @test windowedarray[1:3, 2] == [0x00, 0x00, 0x00]
        @test windowedarray[1, 2] == 0x00
        windowedstack = GDALstack((a=path, b=path); window=(Lat(1:5), Lon(1:5), Band(1:1)))
        windowedarray = windowedstack[:b]
        @test windowedarray[1:3, 2:2, 1:1] == reshape([0x00, 0x00, 0x00], 3, 1, 1)
        @test windowedarray[1:3, 2:2, 1] == reshape([0x00, 0x00, 0x00], 3, 1)
        @test windowedarray[1:3, 2, 1] == [0x00, 0x00, 0x00]
        @test windowedarray[1, 2, 1] == 0x00
        windowedstack = GDALstack((a=path, b=path); window=(Band(1),))
        windowedarray = GeoArray(windowedstack[:b])
        @test windowedarray[1:3, 2:2] == reshape([0x00, 0x00, 0x00], 3, 1)
        @test windowedarray[1:3, 2] == [0x00, 0x00, 0x00]
        @test windowedarray[1, 2] == 0x00
    end

    # Stack Constructors
    @testset "conversion to GeoStack" begin
        stack = GeoStack(gdalstack)
        @test Symbol.(Tuple(keys(gdalstack))) == keys(stack)
        smallstack = GeoStack(gdalstack; keys=(:a,))
        @test keys(smallstack) == (:a,)
    end

    if VERSION > v"1.1-"
        @testset "copy" begin
            geoarray = zero(GeoArray(gdalstack[:a]))
            copy!(geoarray, gdalstack, :a)
            # First wrap with GeoArray() here or == loads from disk for each cell.
            # we need a general way of avoiding this in all disk-based sources
            @test all(geoarray .== GeoArray(gdalstack[:a]))
        end
    end

    @testset "save" begin
        geoarray = GeoArray(gdalstack[:a])
        filename = tempname()
        write(filename, GDALarray, gdalstack)
        base, ext = splitext(filename)
        filename_b = string(base, "_b", ext)
        saved = GeoArray(GDALarray(filename_b))
        @test all(saved .== geoarray)
    end

end

@testset "GDAL series" begin
    series = GeoSeries([path, path], (Ti,); childtype=GDALarray, childkwargs=(mappedcrs=EPSG(4326), name=:test))
    @test GeoArray(series[Ti(1)]) == GeoArray(GDALarray(path; mappedcrs=EPSG(4326), name=:test))

    gdalstack = GDALstack((a=path, b=path); childtype=GDALarray, childkwargs=(mappedcrs=EPSG(4326),))
    series = GeoSeries([gdalstack, gdalstack], (Ti,))
    @test series[1].childkwargs == gdalstack.childkwargs
    # Rebuild the series by wrapping the GDALarray data in Array.
    # `modify` forces `rebuild` on all containers as in-Memory variants
    modified_series = modify(Array, series)
    @test typeof(modified_series) <: GeoSeries{<:GeoStack{<:NamedTuple{(:a,:b),<:Tuple{<:GeoArray{UInt8,3,<:Tuple,<:Tuple,<:Array{UInt8,3}},Vararg}}}}
end

nothing