licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.2.3
6484a27c35ecc680948c7dc7435c97f12c2bfaf7
code
6648
struct Pipeline{name, F} f::F function Pipeline{name, F}(f::F) where {name, F} name isa Symbol || name isa NTuple{N, Symbol} where N && !(name isa Tuple{}) || error("Pipeline name must be a Symbol or Tuple of Symbol: get $name") return new{name, F}(f) end end Pipeline{name}(f) where name = Pipeline{name, typeof(f)}(f) Pipeline{name}(f::ApplyN{N}) where {name, N} = (0 <= N <= 2) ? Pipeline{name, typeof(f)}(f) : error("attempt to access $N-th argument while pipeline only take 2") Pipeline{name}(f, n::Int) where name = Pipeline{name}(ApplyN{n}(f)) Pipeline{name}(f, syms::Union{Symbol, Tuple{Vararg{Symbol}}}) where name = Pipeline{name}(ApplySyms{syms}(f), 2) # replace name or syms Pipeline{name}(p::Pipeline) where name = Pipeline{name}(p.f) function Pipeline{name}(p::Pipeline, syms::Union{Symbol, Tuple{Vararg{Symbol}}}) where name @assert p.f isa ApplyN{2} && p.f.f isa ApplySyms "Cannot change applied symbols on a pipeline not operating on target" f = p.f.f S = _syms(f) @assert typeof(S) == typeof(syms) "Cannot change applied symbols to uncompatible one: form $S to $syms" return Pipeline{name}(ApplySyms{syms}(f.f), 2) end Pipeline(p::Pipeline{name}, syms::Union{Symbol, Tuple{Vararg{Symbol}}}) where name = Pipeline{name}(p, syms) """ target_name(p::Pipeline{name}) where name = name Get the target symbol(s). """ target_name(p::Pipeline{name}) where name = name @inline _result_namedtuple(p::Pipeline, result) = _result_namedtuple(target_name(p), result) @inline _result_namedtuple(name::Symbol, result) = NamedTuple{(name,)}(tuple(result)) @inline _result_namedtuple(name::NTuple{N, Symbol} where N, result) = NamedTuple{name}((result,)) @inline _result_namedtuple(name::NTuple{N, Symbol} where N, result::Tuple) = NamedTuple{name}(result) (p::Pipeline{name})(x, y = NamedTuple()) where name = merge(y, _result_namedtuple(p, p.f(x, y))) struct Pipelines{T<:NTuple{N, Pipeline} where N} pipes::T end Pipelines{Tuple{}}(::Tuple{}) = error("empty pipelines") Pipelines(p::Pipeline) = Pipelines{Tuple{typeof(p)}}((p,)) Pipelines(ps::Pipelines) = ps Pipelines(p1, ps...) = p1 |> Pipelines(ps...) Base.length(ps::Pipelines) = length(ps.pipes) Base.iterate(ps::Pipelines, state=1) = iterate(ps.pipes, state) Base.firstindex(ps::Pipelines) = firstindex(ps.pipes) Base.lastindex(ps::Pipelines) = lastindex(ps.pipes) @inline Base.getindex(ps::Pipelines, i) = ps.pipes[i] Base.getindex(ps::Pipelines, i::UnitRange{<:Integer}) = Pipelines(ps.pipes[i]) (ps::Pipelines{T})(x) where T = ps(x, NamedTuple()::NamedTuple{(), Tuple{}}) function (ps::Pipelines{T})(x, y) where T if @generated body = Expr[ :(y = _pipes[$n](x, y)) for n = 1:fieldcount(T)] return quote _pipes = ps.pipes $(body...) end else foldl((y, p)->p(x, y), ps.pipes; init=y) end end Base.:(|>)(p1::Pipeline, p2::Pipeline) = Pipelines((p1, p2)) Base.:(|>)(p1::Pipelines, p2::Pipeline) = Pipelines((p1.pipes..., p2)) Base.:(|>)(p1::Pipeline, p2::Pipelines) = Pipelines((p1, p2.pipes...)) Base.:(|>)(p1::Pipelines, p2::Pipelines) = Pipelines((p1.pipes..., p2.pipes...)) """ PipeGet{name}() A special pipeline that get the wanted `name`s from namedtuple. # Example ```julia-repl julia> p = Pipeline{:x}(identity, 1) |> Pipeline{(:sinx, :cosx)}(sincos, 1) |> PipeGet{(:x, :sinx)}() Pipelines: target[x] := identity(source) target[(sinx, cosx)] := sincos(source) target := (target.x, target.sinx) julia> p(0.5) (x = 0.5, sinx = 0.479425538604203) julia> p = Pipeline{:x}(identity, 1) |> Pipeline{(:sinx, :cosx)}(sincos, 1) |> PipeGet{:sinx}() Pipelines: target[x] := identity(source) target[(sinx, cosx)] := sincos(source) target := (target.sinx) julia> p(0.5) 0.479425538604203 ``` """ const PipeGet{name} = Pipeline{name, typeof(__getindex__)} PipeGet{name}() where name = PipeGet{name}(__getindex__) (p::PipeGet{name})(_, y) where name = __getindex__(y, name) """ PipeVar{name}(x) A special pipeline that set `x` as `name` to the namedtuple. # Example ```julia-repl julia> p = Pipeline{:x}(identity, 1) |> PipeVar{:y}(5) |> Pipeline{:z}(+, (:x, :y)) Pipelines: target[x] := identity(source) target[y] := 5 target[z] := +(target.x, target.y) julia> p(3) (x = 3, y = 5, z = 8) ``` """ const PipeVar{name} = Pipeline{name, <:ApplyN{0, <:Identity}} PipeVar{name}(x) where name = Pipeline{name}(Identity(x), 0) """ Pipeline{name}(f) Create a pipeline function with name. When calling the pipeline function, mark the result with `name`. `f` should take two arguemnt: the input and a namedtuple (can be ignored) that the result will be merged to. `name` can be either `Symbol` or tuple of `Symbol`s. Pipeline{name}(f, n) Create a pipline function with name. `f` should take one argument, it will be applied to either the input or namedtuple depend on the value of `n`. `n` should be either `1` or `2`. Equivalent to `f(n == 1 ? source : target)`. Pipeline{name}(f, syms) Create a pipline function with name. `syms` can be either a `Symbol` or a tuple of `Symbol`s. Equivalent to `f(target[syms])` or `f(target[syms]...)` depends on the type of `syms`. # Example ```julia-repl julia> p = Pipeline{:x}(1) do x 2x end Pipeline{x}(var"#19#20"()(source)) julia> p(3) (x = 6,) julia> p = Pipeline{:x}() do x, y y.a * x end Pipeline{x}(var"#21#22"()(source, target)) julia> p(2, (a=3, b=5)) (a = 3, b = 5, x = 6) julia> p = Pipeline{:x}(y->y.a^2, 2) Pipeline{x}(var"#23#24"()(target)) julia> p(2, (a = 3, b = 5)) (a = 3, b = 5, x = 9) julia> p = Pipeline{(:sinx, :cosx)}(sincos, 1) Pipeline{(sinx, cosx)}(sincos(source)) julia> p(0.5) (sinx = 0.479425538604203, cosx = 0.8775825618903728) julia> p = Pipeline{:z}((x, y)-> 2x+y, (:x, :y)) Pipeline{z}(var"#33#34"()(target.x, target.y)) julia> p(0, (x=3, y=5)) (x = 3, y = 5, z = 11) ``` """ Pipeline """ Pipelines(pipeline...) Chain of `Pipeline`s. # Example ```julia-repl julia> pipes = Pipelines(Pipeline{:x}((x,y)->x), Pipeline{(:sinx, :cosx)}((x,y)->sincos(x))) Pipelines: target[x] := var"#25#27"()(source, target) target[(sinx, cosx)] := var"#26#28"()(source, target) julia> pipes(0.3) (x = 0.3, sinx = 0.29552020666133955, cosx = 0.955336489125606) # or use `|>` julia> pipes = Pipeline{:x}((x,y)->x) |> Pipeline{(:sinx, :cosx)}((x,y)->sincos(x)) Pipelines: target[x] := var"#29#31"()(source, target) target[(sinx, cosx)] := var"#30#32"()(source, target) julia> pipes(0.3) (x = 0.3, sinx = 0.29552020666133955, cosx = 0.955336489125606) ``` """ Pipelines
FuncPipelines
https://github.com/chengchingwen/FuncPipelines.jl.git
[ "MIT" ]
0.2.3
6484a27c35ecc680948c7dc7435c97f12c2bfaf7
code
4363
# display @nospecialize function show_pipeline_function(io::IO, f1::Base.Fix1) print(io, "(x->") show_pipeline_function(io, f1.f) print(io, '(', f1.x, ", x))") end function show_pipeline_function(io::IO, f2::Base.Fix2) print(io, "(x->") show_pipeline_function(io, f2.f) print(io, "(x, ", f2.x, "))") end function show_pipeline_function(io::IO, a::ApplyN) print(io, "(args...->") show_pipeline_function(io, a.f) _nth(a) == 0 ? print(io, "()") : print(io, "(args[", _nth(a), "]))") end function show_pipeline_function(io::IO, a::ApplySyms) print(io, "((; kwargs...)->") show_pipeline_function(io, a.f) print(io, "(kwargs[", '(', _syms(a), ')', "]...))") end function show_pipeline_function(io::IO, fr::FixRest) show_pipeline_function(io, fr.f) print(io, '(') join(io, fr.arg, ", ") print(io, ')') end function show_pipeline_function(io::IO, c::ComposedFunction, nested=false) if nested show_pipeline_function(io, c.outer, nested) print(io, " ∘ ") show_pipeline_function(io, c.inner, nested) else print(io, '(', sprint(show_pipeline_function, c, true), ')') end end show_pipeline_function(io::IO, f, _) = show_pipeline_function(io, f) show_pipeline_function(io::IO, f) = show(io, f) _show_pipeline_fixf(io::IO, g, name) = (show_pipeline_function(io, g); print(io, '(', name, ')')) _show_pipeline_fixf(io::IO, g::Base.Fix1, name) = (show_pipeline_function(io, g.f); print(io, '(', g.x, ", ", name, ')')) _show_pipeline_fixf(io::IO, g::Base.Fix2, name) = (show_pipeline_function(io, g.f); print(io, '(', name, ", ", g.x, ')')) function _show_pipeline_fixf(io::IO, g::Pipelines, name) _prefix = get(io, :pipeline_display_prefix, nothing) prefix = isnothing(_prefix) ? " " : "$(_prefix) ╰─ " print(io, '(') show_pipeline(io, g; flat = get(io, :compact, false), prefix) print(io, '\n', _prefix, ')', '(', name, ')') end function show_pipeline_function(io::IO, p::Pipeline) if p.f isa ApplyN n = _nth(p.f) g = p.f.f if n == 0 _show_pipeline_fixf(io, g, "") elseif n == 1 _show_pipeline_fixf(io, g, :source) elseif n == 2 if g isa ApplySyms syms = _syms(g) _show_pipeline_fixf(io, g.f, syms isa Tuple ? join(map(x->"target.$x", syms), ", ") : "target.$syms") else _show_pipeline_fixf(io, g, :target) end else print(io, p.f) end else _show_pipeline_fixf(io, p.f, "source, target") end end function show_pipeline_function(io::IO, p::PipeGet) name = target_name(p) if name isa Tuple print(io, "(target.") join(io, name, ", target.") print(io, ')') else print(io, "(target.$name)") end end show_pipeline_function(io::IO, p::PipeVar) = show_pipeline_function(io, p.f.f.x) function Base.show(io::IO, p::Pipeline) print(io, "Pipeline{") name = target_name(p) name isa Tuple ? (print(io, '('); join(io, name, ", "); print(io, ')')) : print(io, name) print(io, "}(") show_pipeline_function(io, p) print(io, ')') end function show_pipeline(io::IO, ps::Pipelines; flat=false, prefix=nothing) print(io, "Pipelines") flat || print(io, ":\n") n = length(ps.pipes) sprefix = isnothing(prefix) ? " " : "$prefix" flat && print(io, '(') io = IOContext(io, :pipeline_display_prefix => sprefix) for (i, p) in enumerate(ps.pipes) flat || print(io, sprefix) if p isa PipeGet print(io, "target := ") show_pipeline_function(io, p) else print(io, "target[") name = target_name(p) if name isa Symbol print(io, name) else print(io, '(') join(io, name, ", ") print(io, ')') end print(io, "] := ") show_pipeline_function(io, p) end if i != n flat ? print(io, "; ") : print(io, '\n') end end flat && print(io, ')') end function Base.show(io::IO, ps::Pipelines) prefix = get(io, :pipeline_display_prefix, nothing) flat = get(io, :compact, false) show_pipeline(io, ps; flat, prefix) end @specialize
FuncPipelines
https://github.com/chengchingwen/FuncPipelines.jl.git
[ "MIT" ]
0.2.3
6484a27c35ecc680948c7dc7435c97f12c2bfaf7
code
912
@static if VERSION < v"1.7" @inline __getindex__(nt::NamedTuple, name) = name isa Symbol ? nt[name] : NamedTuple{name}(nt) else @inline __getindex__(nt::NamedTuple, name) = nt[name] end struct FixRest{F, A<:Tuple} <: Function f::F arg::A end FixRest(f, arg...) = FixRest(f, arg) (f::FixRest)(arg...) = f.f(arg..., f.arg...) struct ApplyN{N, F} <: Function f::F end ApplyN{N}(f) where N = ApplyN{N, typeof(f)}(f) _nth(::ApplyN{N}) where N = N (f::ApplyN)(args...) = f.f(args[_nth(f)]) (f::ApplyN{0})(args...) = f.f() struct ApplySyms{S, F} <: Function f::F end ApplySyms{S}(f) where S = ApplySyms{S, typeof(f)}(f) _syms(::ApplySyms{S}) where S = S function (f::ApplySyms)(nt::NamedTuple) s = _syms(f) if s isa Tuple f.f(__getindex__(nt, s)...) else f.f(__getindex__(nt,s)) end end struct Identity{T} <: Function x::T end (f::Identity)() = f.x
FuncPipelines
https://github.com/chengchingwen/FuncPipelines.jl.git
[ "MIT" ]
0.2.3
6484a27c35ecc680948c7dc7435c97f12c2bfaf7
code
4937
using FuncPipelines using FuncPipelines: get_pipeline_func, target_name using Test # quick and dirty macro for making @inferred as test case macro test_inferred(ex) esc(quote @test begin @inferred $ex true end end) end function trunc_and_pad(a, b, c) end trunc_and_pad(b, c) = FuncPipelines.FixRest(trunc_and_pad, b, c) @testset "FuncPipelines.jl" begin @testset "Pipelines" begin p1 = Pipeline{:x}((x,_)->x) p2 = Pipeline{(:sinx, :cosx)}((x, _)->sincos(x)) p3 = Pipeline{:z}(x->3x+5, :x) ps1 = Pipelines(p1, p2) ps2 = Pipelines(Pipeline{:x}(identity, 1), Pipeline{(:sinx, :cosx)}(y->sincos(y.x), 2)) ps3 = ps2 |> PipeGet{:x}() ps4 = ps2 |> PipeGet{(:x, :sinx)}() ps5 = p1 |> p2 |> Pipeline{:xsinx}(*, (:x, :sinx)) p4 = Pipeline{:r}(p3) p5 = Pipeline(p3, :y) p6 = Pipeline{:r}(p3, :y) @test ps5[begin:end] == ps5 @test get_pipeline_func(ps2[1]) === identity @test Base.setindex(ps1, p2, 1)[1] === p2 @test replace(p->target_name(p) == :x ? Pipeline{:y}(p) : p, ps1)[1] === Pipeline{:y}(p1) @test replace(identity, p3)(0, (x = 2,)) == (x = 2, z = 2) @test p3(0, (x = 2,)) == (x = 2, z = 11) @test p4(0, (x = 2,)) == (x = 2, r = 11) @test p5(0, (x = 2, y = 1)) == (x = 2, y = 1, z = 8) @test p6(0, (x = 2, y = 1)) == (x = 2, y = 1, r = 8) @test ps1(0.5) == ps2(0.5) @test ps3(0.2) == 0.2 @test ps4(0.3) == (x = 0.3, sinx = sin(0.3)) @test ps5(0.7) == (x = 0.7, sinx = sin(0.7), cosx = cos(0.7), xsinx = 0.7*sin(0.7)) @test_inferred p1(0.3) @test_inferred p2(0.5) @test_inferred p3(0, (x = 2,)) @test_inferred ps1(0.5) @test_inferred ps2(0.5) @test_inferred ps3(0.5) @test_inferred ps5(0.5) pn = Pipeline{:x}(Base.Fix1(ntuple, identity), 1) pnp = Pipeline{(:x,)}(Base.Fix1(ntuple, identity), 1) pn2 = Pipeline{(:x, :y)}(Base.Fix1(ntuple, identity), 1) @test pn(1) == (x = (1,),) @test pn(3) == (x = (1,2,3),) @test pnp(1) == (x = 1,) @test pn2(2) == (x = 1, y = 2) @test_inferred pn(Val(1)) @test_inferred pn(Val(3)) @test_inferred pn2(Val(2)) @test_throws Exception pnp(2) @test_throws Exception pn2(1) @test_throws Exception pn2(3) f() = 3 p0 = Pipeline{:x}(f, 0) p0i = Pipeline{:x}(FuncPipelines.Identity((a = 3, b = 5)), 0) @test p0(5) == (x = 3,) @test p0i(5) == (x = (a = 3, b = 5),) @test p1 |> p2 == ps1 @test ps1 |> p1 == Pipelines(p1, p2, p1) @test p1 |> ps1 == Pipelines(p1, p1, p2) @test ps1 |> ps1 == Pipelines(p1, p2, p1, p2) @test collect(ps1) == [p1, p2] @test_throws Exception Pipeline{:x}(identity, 3) @test_throws Exception Pipeline{()}(identity) @test_throws Exception Pipelines(()) @testset "show" begin @test sprint(show, Pipeline{:x}(-, 1)) == "Pipeline{x}(-(source))" @test sprint(show, Pipeline{(:sinx, :cosx)}(sincos, 1)) == "Pipeline{(sinx, cosx)}(sincos(source))" @test sprint(show, Pipeline{(:sinx, :cosx)}(sincos, :x)) == "Pipeline{(sinx, cosx)}(sincos(target.x))" @test sprint(show, Pipeline{(:tanx, :tany)}(Base.Fix1(map, tan), 2)) == "Pipeline{(tanx, tany)}(map(tan, target))" @test sprint(show, Pipeline{:x}(FuncPipelines.Identity((a = 3,b = 5)), 0)) == "Pipeline{x}((a = 3, b = 5))" @test sprint(show, Pipeline{:x2}(Base.Fix2(/, 2), :x)) == "Pipeline{x2}(/(target.x, 2))" @test sprint(show, Pipeline{:z}(sin∘cos, :x)) == "Pipeline{z}((sin ∘ cos)(target.x))" @test sprint(show, Pipeline{:z}(Base.Fix1(*, 2) ∘ Base.Fix2(+, 1))) == "Pipeline{z}(((x->*(2, x)) ∘ (x->+(x, 1)))(source, target))" @test sprint(show, Pipeline{:tok}(trunc_and_pad(nothing, 0), :tok)) == "Pipeline{tok}(trunc_and_pad(nothing, 0)(target.tok))" @test sprint(show, PipeGet{:x}()) == "Pipeline{x}((target.x))" @test sprint(show, PipeGet{(:a, :b)}()) == "Pipeline{(a, b)}((target.a, target.b))" foo(x, y) = x * y.sinx @test sprint( show, Pipeline{:x}(identity, 1) |> Pipeline{(:sinx, :cosx)}(sincos, :x) |> Pipeline{:xsinx}(foo) |> PipeGet{(:cosx, :xsinx)}() ; context=:compact=>true ) == "Pipelines(target[x] := identity(source); target[(sinx, cosx)] := sincos(target.x); target[xsinx] := foo(source, target); target := (target.cosx, target.xsinx))" @test sprint(show, Pipelines(Pipeline{:x}(identity, 1), PipeVar{:y}(3)); context=:compact=>true) == "Pipelines(target[x] := identity(source); target[y] := 3)" end end end
FuncPipelines
https://github.com/chengchingwen/FuncPipelines.jl.git
[ "MIT" ]
0.2.3
6484a27c35ecc680948c7dc7435c97f12c2bfaf7
docs
2472
# FuncPipelines [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://chengchingwen.github.io/FuncPipelines.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://chengchingwen.github.io/FuncPipelines.jl/dev) [![Build Status](https://github.com/chengchingwen/FuncPipelines.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/chengchingwen/FuncPipelines.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/chengchingwen/FuncPipelines.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/chengchingwen/FuncPipelines.jl) # Pipelines The Pipeline api help you define a series of functions that can easily be decomposed and then combined with other function to form a new pipeline. A function (`Pipeline`) is tagged with one (or multiple) `Symbol`s. The return values of that `Pipeline` will be bound to those symbols storing in a `NamedTuple`. Precisely, A `Pipeline` take two inputs, a regular input value (`source`) and a `NamedTuple` (`target`) that stores the results, applying the function to them, and then store the result with the name it carried with into `target`. We can then chaining multiple `Pipeline`s into a `Pipelines`. For example: ```julia julia> pipes = Pipeline{:x}(identity, 1) |> Pipeline{(:sinx, :cosx)}((x,y)->sincos(x)) julia> pipes(0.3) (x = 0.3, sinx = 0.29552020666133955, cosx = 0.955336489125606) # define a series of function julia> pipes = Pipeline{:θ}(Base.Fix1(*, 2), 1) |> Pipeline{(:sinθ, :cosθ)}(sincos, :θ) |> Pipeline{:tanθ}(2) do target target.sinθ / target.cosθ end Pipelines: target[θ] := *(2, source) target[(sinθ, cosθ)] := sincos(target.θ) target[tanθ] := #68(target) # get the wanted results julia> pipes2 = pipes |> PipeGet{(:tanθ, :θ)}() Pipelines: target[θ] := *(2, source) target[(sinθ, cosθ)] := sincos(target.θ) target[tanθ] := #68(target) target := (target.tanθ, target.θ) julia> pipes2(ℯ) (tanθ = -1.1306063769531505, θ = 5.43656365691809) # replace some functions in pipeline julia> pipes3 = pipes2[1] |> Pipeline{:tanθ}(tan, :θ) |> pipes2[end] Pipelines: target[θ] := *(2, source) target[tanθ] := tan(target.θ) target := (target.tanθ, target.θ) julia> pipes3(ℯ) (tanθ = -1.1306063769531507, θ = 5.43656365691809) # and the pipelines is type stable julia> using Test; @inferred pipes3(ℯ) (tanθ = -1.1306063769531507, θ = 5.43656365691809) ```
FuncPipelines
https://github.com/chengchingwen/FuncPipelines.jl.git
[ "MIT" ]
0.2.3
6484a27c35ecc680948c7dc7435c97f12c2bfaf7
docs
206
```@meta CurrentModule = FuncPipelines ``` # FuncPipelines Documentation for [FuncPipelines](https://github.com/chengchingwen/FuncPipelines.jl). ```@index ``` ```@autodocs Modules = [FuncPipelines] ```
FuncPipelines
https://github.com/chengchingwen/FuncPipelines.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
code
1588
using SubglobalSensitivityAnalysis import SubglobalSensitivityAnalysis as CP using Documenter # allow plot to work without display # https://discourse.julialang.org/t/generation-of-documentation-fails-qt-qpa-xcb-could-not-connect-to-display/60988/2 ENV["GKSwstype"] = "100" install_R_dependencies(["sensitivity"]) DocMeta.setdocmeta!(SubglobalSensitivityAnalysis, :DocTestSetup, :(using SubglobalSensitivityAnalysis); recursive=true) makedocs(; #modules=[SubglobalSensitivityAnalysis], # uncomment to show warnings on non-included docstrings authors="Thomas Wutzler <[email protected]> and contributors", repo="https://github.com/bgctw/SubglobalSensitivityAnalysis.jl/blob/{commit}{path}#{line}", sitename="SubglobalSensitivityAnalysis.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://bgctw.github.io/SubglobalSensitivityAnalysis.jl", edit_link="main", assets=String[], ), pages=[ "Home" => "index.md", "Getting started" => "getting_started.md", "How to" => [ "Reload the design matrix" => "reload_design.md" ], "Reference" => [ "Public" => [ "Subglobal SA" => "estimate_subglobal.md", "R dependencies" => "install_R_dependencies.md", "Sobol methods" => "SobolSensitivityEstimator.md", ], "Internal" => "internal.md", ], ], ) deploydocs(; repo="github.com/bgctw/SubglobalSensitivityAnalysis.jl", devbranch="main", )
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
code
2202
""" Trait that indicates that object can be called with method [`reload_design_matrix`](@ref). Implement this trait by `supports_reloading(subtype) = SupportsReloadingYes()` """ abstract type SupportsReloading end, struct SupportsReloadingNo <: SupportsReloading end, struct SupportsReloadingYes <: SupportsReloading end, function supports_reloading(::Any); SupportsReloadingNo(); end "Abstract supertype of Sensitivity Estimators" abstract type SensitivityEstimator end """ Abstract supertype of Sensitivity Estimators returning Sobol indices. Subtypes need to implement the following functions: - [`generate_design_matrix`](@ref) - [`get_design_matrix`](@ref) - [`estimate_sobol_indices`](@ref) If it implements trait , then it need also implement - [`reload_design_matrix`](@ref) """ abstract type SobolSensitivityEstimator <: SensitivityEstimator end "just for testing errors on non-defined methods of the interface." struct DummySobolSensitivityEstimator <: SobolSensitivityEstimator; end """ generate_design_matrix(estim::SobolSensitivityEstimator, X1, X2) Generate the design matrix based on the two samples of parameters, where each row is a parameter sample. For return value see [`get_design_matrix`](@ref). If the subtype `supports_reloading(subtype) != SupportsReloadingNo()`, then after this a call to `generate_design_matrix` it should be able to recreate its state using method [`reload_design_matrix`](@ref). """ function generate_design_matrix(estim::SobolSensitivityEstimator, X1, X2) error( "Define generate_design_matrix(estim, X1, X2) for concrete type $(typeof(estim)).") end """ reload_design_matrix(::SupportsReloadingYes, estim::SobolSensitivityEstimator) Reload the design matrix, i.e. recreate the state after last call to [`generate_design_matrix`](@ref). Called with trait type returned by [`supports_reloading`](@ref). """ function reload_design_matrix(estim::SobolSensitivityEstimator) reload_design_matrix(supports_reloading(estim), estim) end function reload_design_matrix(::SupportsReloadingNo, estim::SobolSensitivityEstimator) error("Estimator does not support reloading design matrix: " * string(estim)) end
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
code
772
module SubglobalSensitivityAnalysis # Write your package code here. using DistributionFits using DataFrames, Tables using RCall using Chain using StaticArrays using InlineStrings export SensitivityEstimator, SobolSensitivityEstimator export supports_reloading, SupportsReloading, SupportsReloadingNo, SupportsReloadingYes export generate_design_matrix, get_design_matrix, estimate_sobol_indices, reload_design_matrix include("Sobol.jl") export RSobolEstimator include("rsobol/RSobolEstimator.jl") export SobolTouati include("rsobol/SobolTouati.jl") export estimate_subglobal_sobol_indices, fit_distributions, set_reference_parameters! include("sens_util.jl") export install_R_dependencies include("r_helpers.jl") export ishigami_fun include("example_funs.jl") end
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
code
189
""" Ishigamis example function (https://www.sfu.ca/~ssurjano/ishigami.html) """ function ishigami_fun(x1,x2,x3) A = 7 B = 0.1 sin(x1) + A * sin(x2)^2 + B * x3^4 * sin(x1) end
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
code
2312
""" install_R_dependencies(packages; lib) Install R packages, vector `packages`, into R library, `lib`. The `lib` directory is created, if it does not exist yet, and prepended to the R library path. `lib` defaults to the user R-library. CAUTION: Installing packages to the R user library may interfere with other R projects, because it changes from where libraries and its versions are loaded. Alternatively, install into a R-session specific library path, by using `lib = RCall.rcopy(R"file.path(tempdir(),'session-library')")`. This does not interfere, but needs to be re-done on each new start of R, and needs adding `RCall.jl` to users project dependencies and imports. """ function install_R_dependencies(packages; lib = rcopy(R"Sys.getenv('R_LIBS_USER')")) # prepend lib path oldlib = rcopy(R".libPaths()") #readdir(lib) oldlib = oldlib isa AbstractVector ? oldlib : [oldlib] new_lib_paths = vcat(lib, setdiff(oldlib, lib)) isdir(lib) || mkpath(lib) # create dir if not existing rcopy(R".libPaths(unlist($(new_lib_paths)))") # check which packages need to be installed # edge case of sapply not returning a vector but a scalar res_sapply = rcopy(R"sapply($(packages), requireNamespace)") is_pkg_installed = res_sapply isa AbstractVector ? res_sapply : SA[res_sapply] all(is_pkg_installed) && return(0) pkgs_inst = packages[.!is_pkg_installed] @show pkgs_inst retcode = rcopy(R""" retcode = 0 packages = $(packages) lib = $(lib) suppressWarnings(dir.create(lib,recursive=TRUE)) withCallingHandlers( tryCatch({ install.packages(packages, lib) }, error=function(e) { retcode <<- 1 }), warning=function(w) { retcode <<- 2 }) if (retcode != 0) { print("retrying install.packages with method curl") retcode <- 0 withCallingHandlers( tryCatch({ install.packages(packages, lib, method='curl') }, error=function(e) { retcode <<- 1 }), warning=function(w) { retcode <<- 2 }) } retcode """) Integer(retcode) end
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
code
8350
""" estimate_subglobal_sobol_indices(f, paramsModeUpperRows, p0; estim::SobolSensitivityEstimator=SobolTouati(), n_sample = 500, δ_cp = 0.1, names_opt, targets) Estimate the Sobol sensitivity indices for a subspace of the global space around parameter vector `p0`. The subspace to sample is determined by an area in the cumulative probability function, specifically for parameter i_par: cdf(p0) ± δ_cp. Samples are drawn from this cdf-scale and converted back to quantiles at the parameter scale. Sobol indices are estimated using the method of Touati (2016), which has a total cost of ``(p+2)×n``, where p is the number of parameters and n is the number of samples in each of the two random parameter samples. ## Arguments - `f`: a function to compute a set of results, whose sensitivity is to be inspected, from parameters `(p1, p2, ...) -> NamedTuple{NTuple{N,NT}} where NT <: Number`, for example `fsens = (a,b) -> (;target1 = a + b -1, target2 = a + b -0.5)`. - `paramsModeUpperRows`: a Vector of Tuples of the form `(:par_name, Distribution, mode, 95%_quantile)` where Distribution is a non-parameterized Object from Distributions.jl such as `LogNormal`. Alternatively, the argument can be the DataFrame with columns `par` and `dist`, such as the result of [`fit_distributions`](@ref) - `p0`: the parameter vector around which subspace is constructed. Optional - `estim`: The [`SobolSensitivityEstimator`](@ref), responsible for generating the design matrix and computing the indices for a given result - `n_sample = 500`: the number of parameter-vectors in each of the samples used by the sensitivity method. - `δ_cp = 0.1`: the range around cdf(p0_i) to sample. - `min_quant=0.005` and `max_quant=0.995`: to constrain the range of cumulative probabilities when parameters are near the ends of the distribution. - `targets`: a `NTuple{Symbol}` of subset of the outputs of f, to constrain the computation to specific outputs. - `names_opt`: a `NTuple{Symbol}` of subset of the parameters given with paramsModeUpperRows ## Return value A DataFrame with columns - `par`: parameter name - `index`: which one of the SOBOL-indices, `:first_order` or `:total` - `value`: the estimate - `cf_lower` and `cf_upper`: estimates of the 95% confidence interval - `target`: the result, for which the sensitivity has been computed ## Example ```@example using Distributions paramsModeUpperRows = [ (:a, LogNormal, 0.2 , 0.5), (:b, LogitNormal, 0.7 , 0.9), ]; p0 = Dict(:a => 0.34, :b => 0.6) fsens = (a,b) -> (;target1 = 10a + b -1, target2 = a + b -0.5) # note, for real analysis use larger sample size df_sobol = estimate_subglobal_sobol_indices(fsens, paramsModeUpperRows, p0; n_sample = 50) ``` """ function estimate_subglobal_sobol_indices(f, paramsModeUpperRows, p0; kwargs...) df_dist = fit_distributions(paramsModeUpperRows) estimate_subglobal_sobol_indices(f, df_dist, p0; kwargs...) end function estimate_subglobal_sobol_indices( f, df_dist::DataFrame, p0; estim::SobolSensitivityEstimator=SobolTouati(), n_sample=500, δ_cp=0.1, targets=missing, names_opt=missing) # set_reference_parameters!(df_dist, p0) if ismissing(names_opt) names_opt = df_dist.par df_dist_opt = df_dist else df_dist_opt = subset(df_dist, :par => ByRow(x -> x ∈ names_opt)) end calculate_parbounds!(df_dist_opt; δ_cp) X1 = get_uniform_cp_sample(df_dist_opt, n_sample); X2 = get_uniform_cp_sample(df_dist_opt, n_sample); cp_design = generate_design_matrix(estim, X1, X2) q_design = transform_cp_design_to_quantiles(df_dist_opt, cp_design) res = map(r -> f(r...), eachrow(q_design)) if ismissing(targets); targets = propertynames(first(res)); end dfs = map(targets) do target y = [tup[target] for tup in res] df_sobol = estimate_sobol_indices(estim, y, df_dist_opt.par) transform!(df_sobol, [] => ByRow(() -> target) => :target) end vcat(dfs...) end """ check_R() load R libraries and if not found, try to install them before to session-specific library path. """ function check_R() lib = rcopy(R"file.path(tempdir(),'session-library')") install_R_dependencies(["sensitivity"]; lib) R"library(sensitivity)" end """ fit_distributions(tups) fit_distributions!(df) For each row, fit a distribution of type `dType` to `mode` and `upper` quantile. In the first variant, parameters are specified as a vector of tuples, which are converted to a `DataFrame`. A new column `:dist` with a concrete Distribution is added. The second variant modifies a `DataFrame` with corresponding input columns. """ function fit_distributions(paramsModeUpperRows::AbstractVector{T}; cols = (:par, :dType, :mode, :upper)) where T <: Tuple # df = rename!(DataFrame(Tables.columntable(paramsModeUpperRows)), collect(cols)) @assert all(df[:,2] .<: Distribution) "Expected all second tuple " * "components to be Distributions." # @assert all(isa.(df[:,3], Number)) "Expected all third tuple components (mode)" * # " to be Numbers." # @assert all(isa.(df[:,4], Number)) "Expected all forth tuple components " #* "(upper quantile) to be Numbers." @assert all(df[:,3] .<= df[:,4]) "Expected all third tuple components (mode) to be " * "smaller than forth tuple components (upper quantile)" fit_distributions!(df) end function fit_distributions!(df::DataFrame) f1v = (dType, mode, upper) -> fit(dType, @qp_m(mode), @qp_uu(upper)) transform!(df, Cols(:dType,:mode,:upper) => ByRow(f1v) => :dist) end """ set_reference_parameters!(df, par_dict) Set the :ref column to given parameters for keys in par_dict matching column :par. Non-matching keys are set to missing. """ function set_reference_parameters!(df, par_dict) df[!,:ref] = get.(Ref(par_dict), df.par, missing) df end """ calculate_parbounds(dist, x; δ_cp = 0.1 ) compute the values at quantiles ±δ_cp around x with δ_cp difference in the cumulated probability. The quantiles are constrained to not extend beyond `min_quant` and `max_quant`. It returns a NamedTuple of - sens_lowe: lower quantile - sens_upper: upper quantile - cp_ref: cdf of x (cumulative distribution function, i.e. p-value) - cp_sens_lower: cdf of lower quantile - cp_sens_upper: cdf of upper quantile A wider distribution prior distribution will result in a wider intervals. The DataFrame variant assumes x as column :ref to be present and adds/modifies output columns (named as above outputs). """ function calculate_parbounds(dist, x; δ_cp=0.1, min_quant=0.005, max_quant=0.995 ) ismissing(x) && return(NamedTuple{ (:sens_lower,:sens_upper,:cp_ref,:cp_sens_lower,:cp_sens_upper) }(ntuple(_ -> missing,5))) cp_ref = cdf(dist, x) cp_sens_lower = max(min_quant, cp_ref - δ_cp) cp_sens_upper = min(max_quant, cp_ref + δ_cp) qs = quantile.(dist, (cp_sens_lower, cp_sens_upper)) (;sens_lower=qs[1], sens_upper=qs[2], cp_ref, cp_sens_lower, cp_sens_upper) end, function calculate_parbounds!(df; kwargs...) f2v = (ref, dist) -> calculate_parbounds(dist,ref; kwargs...) transform!(df, [:ref,:dist,] => ByRow(f2v) => AsTable) end "get matrix (n_sample, n_par) with uniformly sampled in cumaltive p domain" function get_uniform_cp_sample(df_dist, n_sample) tmp = map(Tables.namedtupleiterator(select(df_dist, :cp_sens_lower, :cp_sens_upper))) do (lower,upper) rand(Uniform(lower, upper), n_sample) end hcat(tmp...) # # mutating single-allocation version # X1 = Matrix{eltype(df_dist.cp_sens_lower)}(undef, n_sample, nrow(df_dist)) # X2 = copy(X1) # for (i, (lower, upper)) in enumerate(Tables.namedtupleiterator(select(df_dist, :cp_sens_lower, :cp_sens_upper))) # dunif = Uniform(lower, upper) # X1[:,i] .= rand(dunif, n_sample) # X2[:,i] .= rand(dunif, n_sample) # end end """ transform_cp_design_to_quantiles(df_dist_opt, cp_design) Transform cumulative probabilities back to quantiles. """ function transform_cp_design_to_quantiles(df_dist_opt, cp_design) q_design = similar(cp_design) for (i_par, col_design) in enumerate(eachcol(cp_design)) q_design[:,i_par] .= quantile.(df_dist_opt.dist[i_par], col_design) end q_design end
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
code
3484
struct RSobolEstimator{NS} varname::String31 # the name of the object in R filename::NS # the filename to which R object is serialized RSobolEstimator{NS}(varname, filename::NS) where {NS <: Union{Nothing,AbstractString}} = NS <: Union{Nothing,AbstractString} ? new{NS}(varname, filename) : error("filename must be of type") end function RSobolEstimator(varname, filename::NS) where NS RSobolEstimator{NS}(varname, filename) end # Maybe avoid duplication - so far not able to first concantenate strings # and only thereafter interpolate. # """ # sens_object is set to the variable named as in String `rest.varname`. # If variable does not exist, try to initialize it from file `rest.filename`. # """ # const get_sens_object_str = raw""" # sens_object = if (exists($(rest.varname))){ # get($(rest.varname)) # } else { # .tmp = readRDS($(rest.filename)) # assign($(rest.varname), .tmp) # .tmp # } # """ """ get_design_matrix(estim) Return the design matrix: a matrix with parameters in rows, for which to compute the output, whose sensitivity is studied. """ function get_design_matrix(rest::RSobolEstimator) rcopy(R""" sens_object = if (exists($(rest.varname))){ get($(rest.varname)) } else { message(paste0("reading non-existing ",$(rest.varname)," from ",$(rest.filename))) .tmp = readRDS($(rest.filename)) assign($(rest.varname), .tmp) .tmp } data.matrix(sens_object$X) """) end """ estimate_sobol_indices(rest::RSobolEstimator, y, par_names=missing) Estimate the Sobol sensitivity indices for the given result, `y`, for each row of the design matrix. ## Value A DataFrame with columns - `par`: parameter name - `index`: which one of the SOBOL-indices, `:first_order` or `:total` - `value`: the estimate - `cf_lower` and `cf_upper`: estimates of the confidence interval. The meaning, i.e. with of the interval is usually parameterized when creating the sensitivity estimator object (see e.g. [`SobolTouati`](@ref)). """ function estimate_sobol_indices(rest::RSobolEstimator, y, par_names=missing) check_R() df_S, df_T = rcopy(R""" sens_object = if (exists($(rest.varname))){ get($(rest.varname)) } else { message(paste0("reading non-existing ",$(rest.varname)," from ",$(rest.filename))) .tmp = readRDS($(rest.filename)) assign($(rest.varname), .tmp) .tmp } tell(sens_object, $(y)) l <- list(sens_object$S, sens_object$T) """) tmp = rename!( vcat(df_S::DataFrame, df_T::DataFrame), SA[:value, :cf_lower, :cf_upper]) if ismissing(par_names); par_names = "p" .* string.(1:nrow(df_S)); end tmp[!,:par] = vcat(par_names,par_names) tmp[!,:index] = collect(Iterators.flatten( map(x -> Iterators.repeated(x, nrow(df_S)), (:first_order,:total)))) select!(tmp, :par, :index, Not([:par, :index])) end supports_reloading(rest::RSobolEstimator) = _supports_reloading(rest.filename) _supports_reloading(::Nothing) = SupportsReloadingNo() _supports_reloading(::AbstractString) = SupportsReloadingYes() function reload_design_matrix(rest::RSobolEstimator) R""" message(paste0("reading ",$(rest.varname)," from ",$(rest.filename))) .tmp = readRDS($(rest.filename)) assign($(rest.varname), .tmp) .tmp """ get_design_matrix(rest) end
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
code
1779
struct SobolTouati{NT, NS} <: SobolSensitivityEstimator conf::NT rest::RSobolEstimator{NS} end """ SobolTouati(;conf = 0.95, rest = RSobolEstimator("sens_touati", nothing)) Concrete type of `SobolSensitivityEstimator`, based on method `soboltouati` from the sensitivityR package . It computes both first-order and total indices using correlation coefficients-based formulas, at a total cost of ``n(p+2)×n`` model evaluations. It also computes their confidence intervals based on asymptotic properties of empirical correlation coefficients. # Arguments - `conf`: range of the confidence interval around Sobol indices to be estimated - `rest=RSobolEstimator(varname, filename)`: Can adjust R variable name of the sensitivity object, and the filename of the backupof this object. By providing a filename, the estimator can be recreated, after needing to restart the R session (see [How to reload the design matrix](@ref)). """ function SobolTouati(; conf = 0.95, rest = RSobolEstimator("sens_touati", nothing), ) SobolTouati(conf, rest) end function generate_design_matrix(estim::SobolTouati, X1, X2) check_R() R""" X1 = $(X1) X2 = $(X2) tmp <- soboltouati(NULL,X1,X2, conf=$(estim.conf)) assign($(estim.rest.varname), tmp) if (!is.null($(estim.rest.filename))) saveRDS(tmp, $(estim.rest.filename)) """ get_design_matrix(estim) end get_design_matrix(estim::SobolTouati) = get_design_matrix(estim.rest) estimate_sobol_indices(estim::SobolTouati, args...; kwargs...) = estimate_sobol_indices( estim.rest, args...; kwargs...) supports_reloading(estim::SobolTouati) = supports_reloading(estim.rest) reload_design_matrix(::SupportsReloadingYes, estim::SobolTouati) = reload_design_matrix(estim.rest)
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
code
1315
tmpf = () -> begin pop!(LOAD_PATH) push!(LOAD_PATH, joinpath(pwd(), "test/")) push!(LOAD_PATH, "@dev_$(VERSION.major).$(VERSION.minor)") push!(LOAD_PATH, expanduser("~/julia/devtools_$(VERSION.major).$(VERSION.minor)")) end using Test, SafeTestsets const GROUP = get(ENV, "GROUP", "All") # defined in in CI.yml @show GROUP @time begin if GROUP == "All" || GROUP == "Basic" #@safetestset "Tests" include("test/test_r_helpers.jl") @time @safetestset "test_r_helpers" include("test_r_helpers.jl") #@safetestset "Tests" include("test/test_example_funs.jl") @time @safetestset "test_example_funs" include("test_example_funs.jl") #@safetestset "Tests" include("test/test_SobolSensitivityEstimator.jl") @time @safetestset "test_SobolSensitivityEstimator" include("test_SobolSensitivityEstimator.jl") #@safetestset "Tests" include("test/test_subglobalsens.jl") @time @safetestset "test_subglobalsens" include("test_subglobalsens.jl") end if GROUP == "All" || GROUP == "JET" #@safetestset "Tests" include("test/test_JET.jl") @time @safetestset "test_JET" include("test_JET.jl") #@safetestset "Tests" include("test/test_aqua.jl") @time @safetestset "test_Aqua" include("test_aqua.jl") end end
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
code
348
using JET: JET using SubglobalSensitivityAnalysis @testset "JET" begin @static if VERSION ≥ v"1.9.2" JET.test_package(SubglobalSensitivityAnalysis; target_modules = (@__MODULE__,)) end end; # JET.report_package(MTKHelpers) # to debug the errors # JET.report_package(MTKHelpers; target_modules=(@__MODULE__,)) # to debug the errors
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
code
2564
using SubglobalSensitivityAnalysis using SubglobalSensitivityAnalysis: SubglobalSensitivityAnalysis as CP using Test using Distributions paramsModeUpperRows = [ (:a, LogNormal, 0.1 , 0.5), (:b, LogitNormal, 0.3 , 0.9), ] df_dist = df_dist_opt = fit_distributions(paramsModeUpperRows) p0 = Dict(:a => 0.2, :b => 0.4) set_reference_parameters!(df_dist, p0) CP.calculate_parbounds!(df_dist) n_sample = 10 X1 = CP.get_uniform_cp_sample(df_dist, n_sample); X2 = CP.get_uniform_cp_sample(df_dist, n_sample); @testset "generate design matrix" begin @test_throws ErrorException generate_design_matrix(CP.DummySobolSensitivityEstimator(), X1, X2) sens_estimator2 = CP.SobolTouati( ;rest = RSobolEstimator("sens_touati2", tempname()*".rds")) cp_design = generate_design_matrix(sens_estimator2, X1, X2) npar = size(df_dist, 1) @test size(cp_design) == ((npar+2)*n_sample, npar) end; sens_estimator = SobolTouati() cp_design = generate_design_matrix(sens_estimator, X1, X2); q_design = CP.transform_cp_design_to_quantiles(df_dist, cp_design); fsens = (a,b) -> (;s1 = a + b -1, s2 = a + b -0.5) res = map(r -> fsens(r...), eachrow(q_design)) target = :s1 y = [tup[target] for tup in res]; @testset "estimate_sobol_indices" begin df_sobol = estimate_sobol_indices(sens_estimator, y, df_dist.par) @test df_sobol.par == [:a,:b,:a,:b] @test df_sobol.index == [:first_order, :first_order, :total, :total] @test all([:value, :cf_lower, :cf_upper] .∈ Ref(propertynames(df_sobol))) end; @testset "reload_design_matrix" begin @test supports_reloading(3) == SupportsReloadingNo() @test supports_reloading(sens_estimator) == SupportsReloadingNo() @test_throws ErrorException reload_design_matrix(sens_estimator) #dir = mktempdir() mktempdir() do dir tmpfname = joinpath(dir,"sensobject.rds") estim2 = SobolTouati(;rest=RSobolEstimator("sens_touati2", tmpfname)) @test supports_reloading(estim2) == SupportsReloadingYes() @test_throws Exception reload_design_matrix(estim2) # from R file not found generate_design_matrix(estim2, X1, X2); cp_design2 = reload_design_matrix(estim2); @test cp_design2 isa Matrix end #rm(dir, recursive=true) end; i_tmp_inspecttrait = () -> begin # @code_llvm isnothing(sens_estimator.rest.filename) # @code_llvm supports_reloading(sens_estimator.rest) # @code_llvm supports_reloading(sens_estimator) # @code_llvm supports_reloading(estim2.rest) # @code_llvm supports_reloading(estim2) end
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
code
403
using SubglobalSensitivityAnalysis using Test using Aqua @testset "Code quality (Aqua.jl)" begin Aqua.test_all(SubglobalSensitivityAnalysis; #unbound_args = false, # does not recognize Union{NTuple{N, Symbol} stale_deps = (ignore = [:Requires],), ambiguities = false,) end; @testset "ambiguities package" begin Aqua.test_ambiguities(SubglobalSensitivityAnalysis;) end;
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
code
158
using SubglobalSensitivityAnalysis using Test @testset "ishigami_fun" begin ans = ishigami_fun(0.2,0.3,0.6) @test isapprox(ans, 0.81; atol=0.1) end
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
code
1100
using SubglobalSensitivityAnalysis using Test using RCall @testset "install packages to temporary directory" begin #packages = pkgs_inst = ["sensitivity","units","measurements"] packages = ["sensitivity"] lib = rcopy(R"file.path(tempdir(),'session-library')") retcode = install_R_dependencies(packages; lib) @test retcode == 0 end; i_debug = () -> begin packages = pkgs_inst = ["sensitivity","units","measurements"] pkgs_inst = ["units","measurements"] lib = rcopy(R"file.path(tempdir(),'session-library')") rcopy(R"str($(packages))") rcopy(R"remove.packages(c('measurements'))") rcopy(R"remove.packages(c('measurements'),$(lib))") retcode = install_R_dependencies(["measurements"]; lib) rcopy(R"system.file(package='measurements')") rcopy(R"requireNamespace('measurements')") rcopy(R"tmpf = function(){ return(1) }; tmpf()") new_lib_paths = vcat(lib, setdiff(rcopy(R".libPaths()"), lib)) rcopy(R".libPaths(unlist($(new_lib_paths)))") rcopy(R".libPaths()") install_R_dependencies(packages; lib) readdir(lib) end
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
code
3095
using SubglobalSensitivityAnalysis using Test using Distributions using DataFrames paramsModeUpperRows = [ (:a, LogNormal, 0.1 , 0.5), (:b, LogitNormal, 0.3 , 0.9), (:nonopt, LogitNormal, 0.3 , 0.9), ] df_dist = fit_distributions(paramsModeUpperRows) p0 = Dict(:a => 0.2, :b => 0.4) @testset "fitDistr tups" begin df2 = @inferred fit_distributions(paramsModeUpperRows) @test df2 isa DataFrame @test all([:par, :dType, :mode, :upper, :dist] .∈ Ref(propertynames(df2))) @test df2.dist[2] isa LogitNormal # @test_throws Exception fit_distributions([(:a, :not_a_Distribution, 0.001*365 , 0.005*365),]) @test_throws Exception fit_distributions([(:a, LogNormal, :not_a_number , 0.005*365),]) @test_throws Exception fit_distributions([(:a, LogNormal, :0.006*365 , 0.005*365),]) end; @testset "set_reference_parameters" begin df2 = copy(df_dist) # no b -> missing, key c is irrelevant set_reference_parameters!(df2, Dict(:a => 1.0, :c => 3.0)) @test isequal(df2.ref, [1.0, missing, missing]) end; using SubglobalSensitivityAnalysis: SubglobalSensitivityAnalysis as CP @testset "calculate_parbounds" begin (par,dist) = df_dist[1,[:par,:dist]] x = p0[par] (sens_lower, sens_upper, cp_ref, cp_sens_lower, cp_sens_upper) = CP.calculate_parbounds(dist, x) @test cp_sens_lower == cp_ref - 0.1 @test cp_sens_upper == cp_ref + 0.1 @test sens_lower < x @test sens_upper > x end; @testset "calculate_parbounds dataframe" begin df2 = copy(df_dist) CP.set_reference_parameters!(df2, p0) CP.calculate_parbounds!(df2) @test all([:sens_lower, :sens_upper, :cp_ref, :cp_sens_lower, :cp_sens_upper] .∈ Ref(propertynames(df2))) # # omit ref for parameter b CP.set_reference_parameters!(df2, Dict(:a => 0.2)) CP.calculate_parbounds!(df2) @test ismissing(df2.ref[2]) end; names_opt = [:a, :b] df_dist_ext = copy(df_dist) CP.set_reference_parameters!(df_dist_ext, p0) CP.calculate_parbounds!(df_dist_ext) estim=CP.SobolTouati() df_dist_opt = subset(df_dist_ext, :par => ByRow(x -> x ∈ names_opt)) n_sample = 20 X1 = CP.get_uniform_cp_sample(df_dist_opt, n_sample); X2 = CP.get_uniform_cp_sample(df_dist_opt, n_sample); cp_design = generate_design_matrix(SobolTouati(), X1, X2) @testset "transform_cp_design_to_quantiles" begin q_design = CP.transform_cp_design_to_quantiles(df_dist_opt, cp_design) @test size(q_design) == size(cp_design) end # for each row compute multiple results q_design = CP.transform_cp_design_to_quantiles(df_dist_opt, cp_design); fsens = (a,b) -> (;s1 = a + b -1, s2 = a + b -0.5) res = map(r -> fsens(r...), eachrow(q_design)); @testset "estimate_subglobal_sobol_indices" begin fsens = (a,b) -> (;target1 = a + b -1, target2 = a + b -0.5) df_sobol = estimate_subglobal_sobol_indices(fsens, paramsModeUpperRows, p0; n_sample = 10, names_opt=[:a,:b]) @test nrow(df_sobol) == 8 # repeat without the names_ope df_sobol2 = estimate_subglobal_sobol_indices(fsens, df_dist_opt, p0; n_sample = 10) @test nrow(df_sobol2) == 8 end;
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
docs
2914
# SubglobalSensitivityAnalysis [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://bgctw.github.io/SubglobalSensitivityAnalysis.jl/stable/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://bgctw.github.io/SubglobalSensitivityAnalysis.jl/dev/) [![Build Status](https://github.com/bgctw/SubglobalSensitivityAnalysis.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/bgctw/SubglobalSensitivityAnalysis.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/bgctw/SubglobalSensitivityAnalysis.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/bgctw/SubglobalSensitivityAnalysis.jl) [![Aqua](https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg)](https://github.com/JuliaTesting/Aqua.jl) Estimating Sobol sensitivity indices for a subspace of the global space around a parameter vector, `p0`. ## Problem Results of global sensitivity analysis (SA) are sometimes strongly influenced by outliers resulting from unreasonable parameter combinations. The idea is to still apply global SA, but only to a subset of the entire possible parameter space, specifically to a region around a reasonable parameter set. The user specifies a probability distribution function of each parameter, and the subglobal method ensures that a parameter range is sampled, so that a given proportion (default %20) of the area under its prior pdf is covered. This ensures that for a parameter with wide distribution also a wide range is sampled, and that more samples are drawn where the prior probability of the parameter is higher. ## Getting started Setup arguments and call the main function [`estimate_subglobal_sobol_indices`](https://bgctw.github.io/SubglobalSensitivityAnalysis.jl/dev/estimate_subglobal/#SubglobalSensitivityAnalysis.estimate_subglobal_sobol_indices), as described in [Getting started](https://bgctw.github.io/SubglobalSensitivityAnalysis.jl/dev/getting_started). ## Handle foreign dependencies This Julia package depends on `RCall.jl` and the `sensitivity` R package. If the R package is missing, this Julia package will try to automatically install it into a R session specific library and has to do it on each new R session. In order to permanently install the `sensitivity` package into one's R user library execute: ``` using SubglobalSensitivityAnalysis install_R_dependencies(["sensitivity"]) ``` Caution, this may interfere with other R projects (see [docu](https://bgctw.github.io/SubglobalSensitivityAnalysis.jl/dev/install_R_dependencies/#SubglobalSensitivityAnalysis.install_R_dependencies)). Note, this installation to R user library needs to be run in a Julia session before running other commands from the package. This is because otherwise the R package is maybe already installed at the R session specific library and the installation for already available packages is skipped.
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
docs
1235
## Provide different methods of estimating Sobol indices The Subglobal sensitivity analysis (SA) is a global SA around a subspace of the entire parameter space. One kind of global SA is the computation of Sobol indices and there are many methods of computing these (see e.g. help of the `sensitivity` R package ). In order to combine Subglobal SA with different methods of estimation of Sobol indices, there is interface [`SobolSensitivityEstimator`](@ref), which can be implemented to support other methods. The first method, [`generate_design_matrix`](@ref), creates a design matrix (n_rec × n_par) with parameter vectors in rows. The second method, [`estimate_sobol_indices`](@ref), takes a vector of computed results for each of the design matrix parameters, and computes first and total Sobol indices. ### Index ```@index Pages = ["SobolSensitivityEstimator.md",] ``` ### Types ```@docs SensitivityEstimator SobolSensitivityEstimator generate_design_matrix get_design_matrix estimate_sobol_indices ``` ### supports_reloading trait Reference for the concept explained at [How to reload the design matrix](@ref). ```@docs supports_reloading reload_design_matrix ``` ### Sobol estimation methods ```@docs SobolTouati ```
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
docs
148
## Subglobal sensitivity analysis ```@index Pages = ["estimate_subglobal.md",] ``` ```@docs estimate_subglobal_sobol_indices fit_distributions ```
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
docs
3411
## Getting started Assume we have a simple model, `fsens`, which depends on two parameters, `a` and `b` and produces two outputs, `target1` and `target2`. ```@example gs1 fsens = (a,b) -> (;target1 = 10a + b -1, target2 = a + b -0.5) nothing # hide ``` Our knowledge about reasonable model parameters is encoded by a prior probability distribution. We can specify those by the kind of distribution, its mode and an upper quantile. ```@example gs1 using SubglobalSensitivityAnalysis, Distributions install_R_dependencies(["sensitivity"]) paramsModeUpperRows = [ (:a, LogNormal, 0.2 , 0.5), (:b, LogitNormal, 0.7 , 0.9), ] nothing # hide ``` The output DataFrame reports - the estimated index and confidence bounds (column value, cf_lower, cf_upper) - for each of the parameter/index_type/output combinations We can provide this directly to `estimate_subglobal_sobol_indices` below, or we estimate/specify distribution parameters directly in a DataFrame with column `:dist`. ```@example gs1 df_dist = fit_distributions(paramsModeUpperRows) ``` While these distributions are reasonable for each parameter, there are probably parameter combinations that produce unreasonable results. Hence, we want to restrict our analysis to a parameter space around a central parameter vector, `p0`. ```@example gs1 p0 = Dict(:a => 0.34, :b => 0.6) nothing # hide ``` By default a range around `p0` is created that covers 20% of the cumulative probability range, i.e a span of 0.2. ```@setup gs1 import SubglobalSensitivityAnalysis as CP using Plots, StatsPlots df2 = copy(df_dist) set_reference_parameters!(df2, p0) CP.calculate_parbounds!(df2; δ_cp = 0.1) ipar = 2 ipar = 1 pl_cdf = plot(df2.dist[ipar], xlabel=df2.par[ipar], ylabel="cumulative probability", label=nothing; func = cdf) vline!([df2.ref[ipar]], color = "orange", label = "p0") hline!([df2.cp_ref[ipar]], color = "maroon", linestyle=:dash, label = "cdf(p0)") hspan!(collect(df2[ipar,[:cp_sens_lower,:cp_sens_upper]]), color = "maroon", alpha = 0.2, label = "cdf(sens_range)") vspan!(collect(df2[ipar,[:sens_lower,:sens_upper]]), color = "blue", label = "sens_range", alpha = 0.2) pl_pdf = plot(df2.dist[ipar], xlabel=df2.par[ipar], ylabel="probability density", label=nothing) vline!([df2.ref[ipar]], color = "orange", label = "p0") vspan!(collect(df2[ipar,[:sens_lower,:sens_upper]]), color = "blue", label = "sens_range", alpha = 0.2) ``` ```@example gs1 pl_cdf # hide ``` For this range 20% of the area under the probability density function is covered. ```@example gs1 pl_pdf # hide ``` The design matrix for the sensitivity analysis is constructed in the cumulative densities and transformed to parameter values. For each of the parameter vectors of the design matrix an output is computed. Now the Sobol indices and their confidence ranges can be computed for this output. All this encapsulated by function [`estimate_subglobal_sobol_indices`](@ref). ```@example gs1 install_R_dependencies(["sensitivity"]) # hide # note, for real analysis use a larger sample size df_sobol = estimate_subglobal_sobol_indices(fsens, df_dist, p0; n_sample = 50) df_sobol ``` The resulting DataFrame reports: - the estimated Sobol indices and their confidence bounds (columns value, cf_lower, cf_upper) - for all the combinations of parameter, which index, and output (columns par, index, target)
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
docs
1131
```@meta CurrentModule = SubglobalSensitivityAnalysis ``` # SubglobalSensitivityAnalysis Documentation for package [SubglobalSensitivityAnalysis.jl](https://github.com/bgctw/SubglobalSensitivityAnalysis.jl). Estimating Sobol sensitivity indices for a subspace of the global space around a parameter vector `p0`. ## Problem Results of global sensitivity analysis (SA) are sometimes strongly influenced by outliers resulting from unreasonable parameter combinations. The idea is to still apply global SA, but only to a subset of the entire possible parameter region around a reasonable parameter set. The user specifies a probability distribution function of each parameter, and the subglobal method ensures that a parameter range is sampled, so that a given proportion (default %20) under its prior pdf is covered. This ensures that for a parameter with wide distribution also a wide range is sampled, and that more samples are drawn where the prior probability of the parameter is higher. ## How Setup arguments and call the main function [`estimate_subglobal_sobol_indices`](@ref), as described in the example doctest.
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
docs
103
## Reference ```@index Pages = ["install_R_dependencies.md",] ``` ```@docs install_R_dependencies ```
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
docs
152
## Internal methods ```@index Pages = ["internal.md",] ``` ```@docs CP.calculate_parbounds!(df_dist) CP.get_uniform_cp_sample(df_dist, n_sample) ```
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.1.0
1cfa5a10af4d26a9075605e5456471df9df96f63
docs
3454
## How to reload the design matrix ### Problem Computation of outputs for many parameter vectors can take long. It may happen that the Julia session or the associated R session in which the sensitivity object was constructed has been lost such as a disconnected ssh-session. If the information on the design matrix has been lost, the computed outputs cannot be used any more. Hence, the SobolTouati estimator class provides a method to save intermediate results to file and to be reconstructed from there. ### Providing the filename We reuse the example from [Getting started](@ref). ```@example reload1 using SubglobalSensitivityAnalysis, Distributions install_R_dependencies(["sensitivity"]) fsens = (a,b) -> (;target1 = 10a + b -1, target2 = a + b -0.5) paramsModeUpperRows = [ (:a, LogNormal, 0.2 , 0.5), (:b, LogitNormal, 0.7 , 0.9), ] p0 = Dict(:a => 0.34, :b => 0.6) nothing # hide ``` The back-filename is provided to a a custom sobol estimator where we specify the filename argument: ```@example reload1 some_tmp_dir = mktempdir() fname = joinpath(some_tmp_dir,"sensobject.rds") estim_file = SobolTouati(;rest=RSobolEstimator("sens_touati", fname)) nothing # hide ``` ### Performing the sensitivity analysis Instead of letting [`estimate_subglobal_sobol_indices`](@ref) call our model, here, we do the steps by hand. First, we estimate the distributions and add the center parameter values. ```@example reload1 df_dist = fit_distributions(paramsModeUpperRows) set_reference_parameters!(df_dist, p0) nothing # hide ``` Next, we compute the ranges of the parameters in cumulative probability space and draw two samples. We need to use unexported functions and qualify their names. ```@example reload1 import SubglobalSensitivityAnalysis as CP CP.calculate_parbounds!(df_dist) n_sample = 10 X1 = CP.get_uniform_cp_sample(df_dist, n_sample); X2 = CP.get_uniform_cp_sample(df_dist, n_sample); nothing # hide ``` Next, we create the design matrix using the samples. ```@example reload1 cp_design = generate_design_matrix(estim_file, X1, X2); size(cp_design) ``` Next, we - transform the design matrix from cumulative to original parameter space, - compute outputs for each of the parameter vectors in rows, and - extract the first output from the result as a vector. ```@example reload1 q_design = CP.transform_cp_design_to_quantiles(df_dist, cp_design); res = map(r -> fsens(r...), eachrow(q_design)); y = [tup[:target1] for tup in res]; nothing # hide ``` Now we can tell the output to the estimator and compute sobol indices: ```@example reload1 df_sobol = estimate_sobol_indices(estim_file, y) ``` ### Reloading Assume that after computing the outputs and backing them up to a file, our Julia session has been lost. The original samples to create the design matrix are lost, and we need to recreate the estimator object. We set up a new estimator object with the same file name from above and tell it to reload the design matrix from the file. ```@example reload1 estim_file2 = SobolTouati(;rest=RSobolEstimator("sens_touati", fname)) cp_design2 = reload_design_matrix(estim_file2) nothing # hide ``` Now our new estimator object is in the state of the former estimator object and we can use is to compute sensitivity indices. ```@example reload1 df_sobol2 = estimate_sobol_indices(estim_file2, y) all(isapprox.(df_sobol2.value, df_sobol.value)) ``` ```@setup reload1 rm(some_tmp_dir, recursive=true) ```
SubglobalSensitivityAnalysis
https://github.com/bgctw/SubglobalSensitivityAnalysis.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
1012
using PlutoExtras using PlutoExtras.StructBondModule using Documenter DocMeta.setdocmeta!(PlutoExtras, :DocTestSetup, :(using PlutoExtras); recursive=true) makedocs(; modules= Module[], authors="Alberto Mengali <[email protected]>", repo="https://github.com/disberd/PlutoExtras.jl/blob/{commit}{path}#{line}", sitename="PlutoExtras.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", edit_link="master", assets=String[], ), pages=[ "index.md", "basic_widgets.md", "latex_equations.md", "toc.md", "structbond.md", ], ) # This controls whether or not deployment is attempted. It is based on the value # of the `SHOULD_DEPLOY` ENV variable, which defaults to the `CI` ENV variables or # false if not present. should_deploy = get(ENV,"SHOULD_DEPLOY", get(ENV, "CI", "") === "true") if should_deploy @info "Deploying" deploydocs( repo = "github.com/disberd/PlutoExtras.jl.git", ) end
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
8089
### A Pluto.jl notebook ### # v0.19.43 #> custom_attrs = ["hide-enabled"] using Markdown using InteractiveUtils # This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error). macro bind(def, element) quote local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end local el = $(esc(element)) global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el) el end end # ╔═╡ 1ffc6489-6a3d-4bd1-94e5-4a843b614b20 # ╠═╡ show_logs = false # ╠═╡ skip_as_script = true #=╠═╡ begin import Pkg Pkg.activate(Base.current_project()) using Revise end ╠═╡ =# # ╔═╡ 5a4abd25-143a-49ea-a6b9-2b6c55e70a2c begin using PlutoExtras using PlutoExtras.StructBondModule # This submodule has the features listed in this notebook using PlutoUI using HypertextLiteral end # ╔═╡ 5fbd1401-c7a1-4d4f-b16d-ac9d45e2fed5 md""" # Packages """ # ╔═╡ cfa79196-9e04-4d0e-a6b1-5641e123f3d3 ExtendedTableOfContents() # ╔═╡ 5a9b27c3-df02-415c-87bd-06ebd3c9d246 md""" # StructBond """ # ╔═╡ 9da65874-608a-4c84-a0e6-813c624c07ba md""" Generating automatic widgets for custom structs is quite straightforward with the aid of the `@fielddata` macro and the `StructBond` type. The top-left arrow can be used to show-hide the field elements (useful inside a `BondTable`, shown below), while the green toggle on the top-right can be used to disable temporarily the synch between the JS widgets and the bond values in Pluto. """ # ╔═╡ 9a9fc01e-c25d-11ed-0147-b155e63ffba7 begin """ struct ASD """ Base.@kwdef struct ASD a::Int b::Int c::String "This field is _special_" d::String e::Int end @fielddata ASD begin a = (md"Markdown description, including ``LaTeX``", Slider(1:10)) b = (@htl("<span>Field with <b>HTML</b> description</span>"), Scrubbable(1:10)) c = ("Normal String Description", TextField()) d = TextField() # No description, defaults to the docstring since it's present e = Slider(20:25) # No description, defaults to the fieldname as no docstring is present end asd_bond = @bind asd StructBond(ASD; description = "Custom Description") end # ╔═╡ 1442a2eb-b38b-4757-b02c-96b599084889 asd # ╔═╡ 65a3ed8e-6204-4aee-adfc-befe9ea5153e md""" # @NTBond """ # ╔═╡ 8c8fd549-0afc-4452-bd6a-6564862a1d63 md""" Sometimes custom structs are not needed and it would be useful to just use the same nice bond structure of `StructBond` to simply create arbitrary NamedTuples. This is possible with the convenience macro `@NTBond` which can be called as shown below to create a nice display for an interactive bond creating an arbitrary NamedTuple. The macro simply create a `StructBond` wrapping the desired NamedTuple type. """ # ╔═╡ 9faf2258-3f2b-450c-bbfe-d8231e0e4d74 nt_bond = @bind nt @NTBond "My Fancy NTuple" begin a = ("Description", Slider(1:10)) b = (md"**Bold** field", Slider(1:10)) c = Slider(1:10) # No description, defaults to the name of the field end # ╔═╡ c183e38f-84e3-4a1f-a631-6d1db39f1179 nt # ╔═╡ 8ab2af4c-92a2-429f-b641-95a028808ae5 md""" # @BondsList """ # ╔═╡ 29592194-2f89-49cc-9a20-7a8e9cd44ae9 md""" In some cases, one does not want to have a single bond wrapping either a Structure or a NamedTuple, and single independent bonds are more convenient. `@BondsList` is a convenience macro to create an object of type `BondsList` which simply allow to add a description to separate bonds and group them all together in a table-like format equivalent to those of `StructBond`. !!! note Unlike `StructBond`, a BondsList is already composed of bond created with `@bind` and it just groups them up with a description. The output of `@BondsList` is not supposed to be bound to a variable using `@bind`.\ The bonds grouped in a BondsList still act and update independently from one another. See the example below for understanding the synthax. The header of a BondsList is shown in an orange background to easily differentiate it from `StructBond`. """ # ╔═╡ 6091cdf4-c0ec-45f6-8aa0-d4faf6666d2d bl = @BondsList "My Group of Bonds" let tv = PlutoUI.Experimental.transformed_value # We use transformed_value to translate GHz to Hz in the bound variable `freq` "Frequency [GHz]" = @bind freq tv(x -> x * 1e9, Editable(20; suffix = " GHz")) md"Altitude ``h`` [m]" = @bind alt Scrubbable(100:10:200) end # ╔═╡ 8d912297-925e-4c8b-98b8-19b43c9b29d7 freq # ╔═╡ 9a1baa3d-1420-473c-8380-bb5c23881e00 md""" # Popout """ # ╔═╡ 93255c24-d486-416d-aefc-7575feff7543 md""" The structures above can also be used nested within one another. To facilitate accessing nested structures, one can use the `Popout` type. In its simple form, you can give an instance of a StructBond, a bond wrapping a StructBond or a BondsList as input to Popout to create a table that is hidden behind a popup window. If an instance present, but you want a custom type for which you have defined custom bonds and descriptions with `@fielddata` to appear as popout, you can use the function `popoutwrap(TYPE)` to generate a small icon which hides a popup containing the `StructBond` of the provided type `TYPE`. The StructBond table appears on hover upon the icon, can be made fixed by clicking on the icon and can then be moved around or resized. A double click on the header of the popout hides it again: """ # ╔═╡ 978f70ea-393e-4f3d-93fb-c5a83443d079 begin Base.@kwdef struct LOL a::Int b::Int end @fielddata LOL begin a = (md"Wonder!", Slider(1:10)) b = (@htl("<span>Field B</span>"), Scrubbable(1:10)) end end # ╔═╡ 6c56c205-ac72-4556-b95e-b278e4b3f822 popoutwrap(LOL) # ╔═╡ 38535cbe-093d-4452-b2a9-999183199801 md""" The ability to also wrap pre-existing bonds around StructBonds is convenient for organizing the various bonds one have in a `BondsList` or `BondTable` As an example, one can create a `BondsList` containing the two `StructBond` bonds generated at the beginning of this notebook with the follwing code. """ # ╔═╡ 95ad9428-73f8-4f57-9185-9685b9a2123f blc = @BondsList "Popout Container" begin "Structure ASD" = Popout(asd_bond) "NamedTuple" = Popout(nt_bond) end # ╔═╡ 373bc244-110a-43f8-aaa1-51b5cb751128 md""" # BondTable """ # ╔═╡ b3fb23b8-8652-469b-8d0c-0c6c2723b631 md""" The final convenience structure provided by this module is the `BondTable`. It can be created to group a list of bonds in a floating table that stays on the left side of the notebook (similar to the TableOfContents of PlutoUI) and can be moved around and resized or hidden for convenience. The BondTable is intended to be used either with bonds containing `StructBond` or with `BondsList`. Future types with similar structure will also be added. Here is an example of a bondtable containing all the examples of this notebook. """ # ╔═╡ 75fc40a3-4231-4125-b52c-ad21f5b8a388 BondTable([ asd_bond, nt_bond, bl, blc ]; description = "My Bonds") # ╔═╡ Cell order: # ╠═1ffc6489-6a3d-4bd1-94e5-4a843b614b20 # ╟─5fbd1401-c7a1-4d4f-b16d-ac9d45e2fed5 # ╠═5a4abd25-143a-49ea-a6b9-2b6c55e70a2c # ╠═cfa79196-9e04-4d0e-a6b1-5641e123f3d3 # ╟─5a9b27c3-df02-415c-87bd-06ebd3c9d246 # ╟─9da65874-608a-4c84-a0e6-813c624c07ba # ╠═9a9fc01e-c25d-11ed-0147-b155e63ffba7 # ╠═1442a2eb-b38b-4757-b02c-96b599084889 # ╟─65a3ed8e-6204-4aee-adfc-befe9ea5153e # ╟─8c8fd549-0afc-4452-bd6a-6564862a1d63 # ╠═9faf2258-3f2b-450c-bbfe-d8231e0e4d74 # ╠═c183e38f-84e3-4a1f-a631-6d1db39f1179 # ╟─8ab2af4c-92a2-429f-b641-95a028808ae5 # ╟─29592194-2f89-49cc-9a20-7a8e9cd44ae9 # ╠═6091cdf4-c0ec-45f6-8aa0-d4faf6666d2d # ╠═8d912297-925e-4c8b-98b8-19b43c9b29d7 # ╟─9a1baa3d-1420-473c-8380-bb5c23881e00 # ╟─93255c24-d486-416d-aefc-7575feff7543 # ╠═978f70ea-393e-4f3d-93fb-c5a83443d079 # ╠═6c56c205-ac72-4556-b95e-b278e4b3f822 # ╟─38535cbe-093d-4452-b2a9-999183199801 # ╠═95ad9428-73f8-4f57-9185-9685b9a2123f # ╟─373bc244-110a-43f8-aaa1-51b5cb751128 # ╟─b3fb23b8-8652-469b-8d0c-0c6c2723b631 # ╠═75fc40a3-4231-4125-b52c-ad21f5b8a388
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
931
module PlutoExtras using HypertextLiteral using AbstractPlutoDingetjes.Bonds using AbstractPlutoDingetjes import PlutoUI # This is similar to `@reexport` but does not exports undefined names and can # also avoid exporting the module name function re_export(m::Module; modname = false) mod_name = nameof(m) nms = names(m) exprts = filter(nms) do n isdefined(m, n) && (!modname || n != mod_name) end eval(:(using .$mod_name)) eval(:(export $(exprts...))) end export Editable, StringOnEnter # from basic_widgets.jl export ToggleReactiveBond # From within StructBondModule include("combine_htl/PlutoCombineHTL.jl") include("basic_widgets.jl") include("latex_equations.jl") module ExtendedToc include("extended_toc.jl") end include("structbond/StructBondModule.jl") using .StructBondModule ## ReExports ## re_export.((ExtendedToc, LaTeXEqModule); modname = false) re_export(PlutoUI) end # module
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
9490
# Editable # #= Create an element inspired by (and almost equivalent to) the Scrubbable from PlutoUI but with the possibility of changing the value by clicking on the number and editing the value =# ## Struct ## Base.@kwdef struct Editable{T <: Number} default::T format::Union{AbstractString,Nothing}=nothing prefix::AbstractString="" suffix::AbstractString="" end ### Real Version ### """ Editable(x::Real; [prefix, suffix, format]) Create a Pluto widget similar to [`Scrubbable`](@ref) from PlutoUI but that can contain an arbitrary (Real) number provided as input. The displayed HTML will create a span with a blue background which contains the number and is preceded by an optional text `prefix` and an optional text `suffix`. If `format` is specified, it will be used to format the shown number using the [d3-format](https://github.com/d3/d3-format#locale_format) specification. The widget will trigger a bond update only upon pressing Enter or moving the focus out of the widget itself. ![79f77981-2c53-4ff0-bd13-8213519e0bca](https://github.com/disberd/PlutoExtras.jl/assets/12846528/cb0f19e3-7dcb-46d6-88b1-1bbe1592dd1c) # Keyword Arguments - `prefix::AbstractString`: A string that will be inserted in the displayed HTML before the number. Clicking on the suffix will select the full text defining the number - `suffix::AbstractString`: A string that will be inserted in the displayed HTML after the number. Clicking on the suffix will select the full text defining the number - `format::AbstractString`: A string specifing the format to use for displaying the number in HTML. Uses the [d3-format](https://github.com/d3/d3-format#locale_format) specification """ Editable(x::Real; kwargs...) = Editable(; default=x, kwargs...) ### Bool Version ### """ Editable(x::Bool[, true_string="true", false_string="false") Create a Pluto widget that contain a Boolean value. The displayed HTML will create a span with a green background that displays the custom string `true_string` when true and the `false_string` when false. If not provided, the second argument `true_string` defaults to "true" and the third one the "false". The widget will trigger a bond update when clicking on it. ![991b712a-d62d-4036-b096-fe0fc52c9b25](https://github.com/disberd/PlutoExtras.jl/assets/12846528/f12e3bc3-f78c-45b5-b5fd-06f2083fc5c4) """ Editable(x::Bool,truestr::AbstractString="true",falsestr::AbstractString="false"; kwargs...) = Editable(; default=x, kwargs...,prefix=truestr,suffix=falsestr) ### AbstractPlutoDingetjes methods ### Base.get(s::Editable) = s.default Bonds.initial_value(s::Editable) = s.default Bonds.possible_values(s::Editable) = Bonds.InfinitePossibilities() Bonds.possible_values(s::Editable{Bool}) = (true, false) Bonds.validate_value(s::Editable, from_browser::Union{Real, Bool}) = true Bonds.validate_value(s::Editable, from_browser) = false ### Show - Bool ### # In case of Bool type, the prefix and suffix are used as strings to display for the 'true' and 'false' flags respectively function Base.show(io::IO, m::MIME"text/html", s::Editable{Bool}) show(io,m,@htl """ <script> const d3format = await import("https://cdn.jsdelivr.net/npm/d3-format@2/+esm") const el = html` <span class="bool_Editable" style=" cursor: pointer; touch-action: none; padding: 0em .2em; border-radius: .3em; font-weight: bold;">$(s.default)</span> ` const formatter = x => x ? $((s.prefix)) : $((s.suffix)) let localVal = $(s.default) el.innerText = formatter($(s.default)) Object.defineProperty(el,"value",{ get: () => Boolean(localVal), set: x => { localVal = Boolean(x) el.innerText = formatter(x) } }) el.addEventListener('click',(e) => { el.value = el.value ? false : true el.dispatchEvent(new CustomEvent("input")) }) el.onselectstart = () => false return el </script> <style> @media (prefers-color-scheme: light) { span.bool_Editable { background: hsl(133, 47%, 73%); } } @media (prefers-color-scheme: dark) { span.bool_Editable { background: hsl(133, 47%, 40%); } } </style> """) end ### Show - Generic ### function Base.show(io::IO, m::MIME"text/html", s::Editable) format = if s.format === nothing # TODO: auto format if eltype(s.default) <: Integer "" else ".4~g" end else String(s.format) end show(io,m,@htl """ <script> const d3format = await import("https://cdn.jsdelivr.net/npm/d3-format@2/+esm") const elp = html` <span class="number_Editable" style=" touch-action: none; padding: 0em .2em; border-radius: .3em; font-weight: bold;">$(HypertextLiteral.JavaScript(s.prefix))<span contentEditable=true>$(s.default)</span>$(HypertextLiteral.JavaScript(s.suffix))</span> ` const formatter = s => d3format.format($(format))(s) const el = elp.querySelector("span") let localVal = parseFloat($(s.default)) el.innerText = formatter($(s.default)) Object.defineProperty(elp,"value",{ get: () => localVal, set: x => { localVal = parseFloat(x) el.innerText = formatter(x) } }) const dispatchEvent = (e) => { if (el.innerText === "") { elp.value = $(s.default) } else { /* The replace is needed because d3-format outputs '-' as in U+2212 (math symbol) but fails to parse negative number correctly if they have that sign as negative sign. So we just replace it with the dash U+002D sign */ elp.value = el.innerText.replace('−', '-') } elp.dispatchEvent(new CustomEvent("input")) } // Function to blur the element when pressing enter instead of adding a newline const onEnter = (e) => { if (e.keyCode === 13) { e.preventDefault(); el.blur() } } el.addEventListener('input',(e) => { console.log(e) e.preventDefault() e.stopImmediatePropagation() }) function selectText(el){ var sel, range; if (window.getSelection && document.createRange) { //Browser compatibility sel = window.getSelection(); if(sel.toString() == ''){ //no text selection window.setTimeout(function(){ range = document.createRange(); //range object range.selectNodeContents(el); //sets Range sel.removeAllRanges(); //remove all ranges from selection sel.addRange(range);//add Range to a Selection. },1); } }else if (document.selection) { //older ie sel = document.selection.createRange(); if(sel.text == ''){ //no text selection range = document.body.createTextRange();//Creates TextRange object range.moveToElementText(el);//sets Range range.select(); //make selection. } } } el.addEventListener('focusout',dispatchEvent) el.addEventListener('keydown',onEnter) el.addEventListener('click',(e) => e.stopImmediatePropagation()) // modify text elp.addEventListener('click',(e) => selectText(el)) // Select all text return elp </script> <style> @media (prefers-color-scheme: light) { span.number_Editable { background: hsl(204, 95%, 84%); } } @media (prefers-color-scheme: dark) { span.number_Editable { background: hsl(204, 95%, 40%); } } </style> """) end # StringOnEnter # #= Create an element inspired by TextField from PlutoUI but with the possibility of updating the bond value only when `Enter` is pressed ot the focus is moved away from the field itself. =# ## Struct ## """ StringOnEnter(default::AbstractString) Creates a Pluto widget that allows to provide a string as output when used with `@bind`. Unlike the custom "TextField" from PlutoUI this only triggers a bond update upon pressing Enter or moving the focus out of the widget (similar to [`Editable`](@ref)) When rendered in HTML, the widget text will be shown with a dark yellow background. ![868c1c6e-8731-4465-959e-58cf551b9f61](https://github.com/disberd/PlutoExtras.jl/assets/12846528/782360f2-595a-4bbe-9769-5ddfaa144611) """ struct StringOnEnter default::String end ## StringOnEnter - Show ## Base.show(io::IO, mime::MIME"text/html", mt::StringOnEnter) = show(io, mime, @htl """ <span><span class="text_StringOnEnter" style=" padding: 0em .2em; border-radius: .3em; font-weight: bold;" contentEditable=true>$(mt.default)</span></span> <script> const elp = currentScript.previousElementSibling const el = elp.querySelector('span') Object.defineProperty(elp,"value",{ get: () => el.innerText, set: x => { el.innerText = x } }) const dispatchEvent = (e) => { if (el.innerText === "") { elp.value = $(mt.default) } else { elp.value = el.innerText } elp.dispatchEvent(new CustomEvent("input")) } el.addEventListener('input',(e) => { console.log(e) e.preventDefault() e.stopImmediatePropagation() }) const onEnter = (e) => { if (e.keyCode === 13) { e.preventDefault(); el.blur() } } elp.addEventListener('focusout',dispatchEvent) elp.addEventListener('keydown',onEnter) </script> <style> @media (prefers-color-scheme: light) { span.text_StringOnEnter { background: hsl(48, 90%, 61%); } } @media (prefers-color-scheme: dark) { span.text_StringOnEnter { background: hsl(48, 57%, 37%); } } </style> """) ## AbstractPlutoDingetjes Methods ## Base.get(t::StringOnEnter) = t.default Bonds.initial_value(t::StringOnEnter) = t.default Bonds.possible_values(t::StringOnEnter) = Bonds.InfinitePossibilities() function Bonds.validate_value(t::StringOnEnter, val) val isa AbstractString end
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
34082
using HypertextLiteral using PlutoUI using ..PlutoCombineHTL.WithTypes # Exports # export ExtendedTableOfContents, show_output_when_hidden # Script Parts # #= Smooth Scroll Since v0.7.51 PlutoUI directly supports the smooth scrolling library in the TableOfContents, so we just take it from there. =# _smooth_scroll = PlutoScript(""" // Load the library for consistent smooth scrolling const {default: scrollIntoView} = await import('$(PlutoUI.TableOfContentsNotebook.smooth_scoll_lib_url)') function scroll_to(h, config = { behavior: 'smooth', block: 'start', }) { scrollIntoView(h, config).then(() => // sometimes it doesn't scroll to the right place // solution: try a second time! scrollIntoView(h, config) ) } """) ## Script - Basic ## _basics = PlutoScript(""" let cell = currentScript.closest('pluto-cell') let pluto_actions = cell._internal_pluto_actions let toc = document.querySelector('nav.plutoui-toc') function getRow(el) { const row = el?.closest('.toc-row') return row } function get_link_id(el) { const row = getRow(el) if (_.isNil(row)) { return null } const a = row.querySelector('a') return a.href.slice(-36) // extract the last 36 characters, corresponding to the cell id } function getHeadingLevel(row) { const a = row.querySelector('a') // We return the link class without the first H return Number(a.classList[0].slice(1)) } function generateChecker(selector) { switch (typeof selector) { case 'string': const func = el => { return el.matches(selector) } return func case 'function': return selector default: console.error(`The type (\${typeof selector}) of the provided argument is not valid`) } } // Get next and previous sibling, adapted from: // https://gomakethings.com/finding-the-next-and-previous-sibling-elements-that-match-a-selector-with-vanilla-js/ var getNextSibling = function (elem, selector) { // Added to return undefined is called with undefined if (_.isNil(elem)) {return undefined} // Get the next sibling element var sibling = elem.nextElementSibling; // If there's no selector, return the first sibling if (!selector) return sibling; const checker = generateChecker(selector) // If the sibling matches our selector, use it // If not, jump to the next sibling and continue the loop while (sibling) { if (checker(sibling)) return sibling; sibling = sibling.nextElementSibling } }; var getPreviousSibling = function (elem, selector) { // Added to return undefined is called with undefined if (_.isNil(elem)) {return undefined} // Get the next sibling element var sibling = elem.previousElementSibling; // If there's no selector, return the first sibling if (!selector) return sibling; const checker = generateChecker(selector) // If the sibling matches our selector, use it // If not, jump to the next sibling and continue the loop while (sibling) { if (checker(sibling)) return sibling; sibling = sibling.previousElementSibling; } }; // Get the last toc entry descendant from the provided one function getLastDescendant(el) { const row = getRow(el) if (_.isNil(row)) {return} const children = row.directChildren if (_.isEmpty(children)) { return row } else { return getLastDescendant(_.last(children)) } } // Find all the cell ids contained within the target toc rows and all its descendants function getBlockIds(el) { const row = getRow(el) if (_.isNil(row)) {return} function getIndex(row) { return editor_state.notebook.cell_order.indexOf(get_link_id(row)) } const start = getIndex(row) const lastChild = getLastDescendant(row) const end = getIndex(getNextSibling(lastChild, '.toc-row')) return editor_state.notebook.cell_order.slice(start, end < 0 ? Infinity : end) } window.toc_utils = { getNextSibling, getPreviousSibling, getLastDescendant, getBlockIds, } // Functions to set and propagate hidden and collapsed states function propagate_parent(div, parent=null) { if (parent != null) { div.allParents = _.union(div.allParents, [parent]) } if (_.isEmpty(div.directChildren)) {return} for (const child of div.directChildren) { propagate_parent(child, parent ?? div) } } // Returns true if the current hidden/collapsed toc state is different from the one saved in the file within cell metadata function stateDiffersFile(state) { for (const [id, st] of _.entries(state)) { if (has_cell_attribute(id, 'toc-hidden') != st.hidden) { return true } if (has_cell_attribute(id, 'toc-collapsed') != st.collapsed) { return true } } return false } function set_state(div, state, value, init = false) { div.classList.toggle(state, value) if (!init) { window.toc_state[get_link_id(div)][state] = value toc.classList.toggle('file-state-differs', stateDiffersFile(window.toc_state)) } if (_.isEmpty(div.directChildren)) {return} for (const child of div.directChildren) { propagate_state(child, state) } } function propagate_state(div, state) { let new_state = `parent-\${state}` div.classList.toggle(new_state, false) // Check the parents for the state for (const parent of div.allParents) { if (parent.classList.contains(state)) { div.classList.toggle(new_state, true) break } } if (_.isEmpty(div.directChildren)) {return} for (const child of div.directChildren) { propagate_state(child, state) } } """) ## Script - Floating UI ## _floating_ui = PlutoScript(""" const floating_ui = await import('https://esm.sh/@floating-ui/dom') // window.floating_ui = floating_ui """) ## Script - Modify Cell Attributes ## _modify_cell_attributes = PlutoScript(""" function has_cell_attribute(cell_id, attr) { const md = editor_state.notebook.cell_inputs[cell_id].metadata return _.includes(md["custom_attrs"], attr) } function add_cell_attributes(cell_id, attrs) { pluto_actions.update_notebook((notebook) => { let md = notebook.cell_inputs[cell_id].metadata md["custom_attrs"] = _.union(md["custom_attrs"], attrs) }) let cell = document.getElementById(cell_id) for (let attr of attrs) { cell.toggleAttribute(attr, true) } } function remove_cell_attributes(cell_id, attrs) { pluto_actions.update_notebook((notebook) => { let md = notebook.cell_inputs[cell_id].metadata let after = _.difference(md["custom_attrs"], attrs) if (_.isEmpty(after)) { delete md["custom_attrs"] } else { md["custom_attrs"] = after } }) let cell = document.getElementById(cell_id) for (let attr of attrs) { cell.toggleAttribute(attr, false) } } function toggle_cell_attribute(cell_id, attr, force='toggle') { pluto_actions.update_notebook((notebook) => { let md = notebook.cell_inputs[cell_id].metadata let f = force == 'toggle' ? _.xor : force ? _.union : _.difference let after = f(md["custom_attrs"], [attr]) if (_.isEmpty(after)) { delete md["custom_attrs"] } else { md["custom_attrs"] = after } }) let cell = document.getElementById(cell_id) force == 'toggle' ? cell.toggleAttribute(attr) : cell.toggleAttribute(attr, force) } """) ## Script - Modify Notebook Attributes ## _modify_notebook_attributes = PlutoScript(""" function add_notebook_attributes(attrs) { pluto_actions.update_notebook((notebook) => { let md = notebook.metadata md["custom_attrs"] = _.union(md["custom_attrs"], attrs) }) let notebook = document.querySelector('pluto-notebook') for (let attr of attrs) { notebook.toggleAttribute(attr, true) } } function remove_notebook_attributes(attrs) { pluto_actions.update_notebook((notebook) => { let md = notebook.metadata let after = _.difference(md["custom_attrs"], attrs) if (_.isEmpty(after)) { delete md["custom_attrs"] } else { md["custom_attrs"] = after } }) let notebook = document.querySelector('pluto-notebook') for (let attr of attrs) { notebook.toggleAttribute(attr, false) } } function toggle_notebook_attribute(attr, force='toggle') { pluto_actions.update_notebook((notebook) => { let md = notebook.metadata let f = force == 'toggle' ? _.xor : force ? _.union : _.difference let after = f(md["custom_attrs"], [attr]) if (_.isEmpty(after)) { delete md["custom_attrs"] } else { md["custom_attrs"] = after } }) let notebook = document.querySelector('pluto-notebook') force == 'toggle' ? notebook.toggleAttribute(attr) : notebook.toggleAttribute(attr, force) } if (force_hide_enabled) { toggle_notebook_attribute('hide-enabled',true) } """) ## Script - Hide Cell Blocks ## _hide_cell_blocks = PlutoScript(""" // For each from and to, we have to specify `pluto-cell[id]` in the part before the comm and just `[id]` in the part after the comma to ensure the specificity of the two comma-separated selectors is the same (the part after the comma has the addition of `~ pluto-cell`, so it has inherently +1 element specificity) function hide_from_to_string(from_id, to_id) { if (_.isEmpty(from_id) && _.isEmpty(to_id)) {return ''} const from_preselector = _.isEmpty(from_id) ? '' : `pluto-cell[id='\${from_id}'], pluto-notebook[hide-enabled] [id='\${from_id}'] ~ ` const to_style = _.isEmpty(to_id) ? '' : `pluto-notebook[hide-enabled] pluto-cell[id='\${to_id}'], pluto-notebook[hide-enabled] [id='\${to_id}'] ~ pluto-cell { display: block; } ` const style_string = `pluto-notebook[hide-enabled] \${from_preselector}pluto-cell { display: none; } \${to_style} ` return style_string //return html`<style>\${style_string}</style>` } function hide_from_to_list_string(vector) { let out = `` for (const lims of vector) { const from = lims[0] const to = lims[1] out = `\${out}\t\${hide_from_to_string(from,to)}` } out = `\${out}\tpluto-cell[always-show] { display: block !important; } ` return out } function hide_from_to_list(vector) { const str = hide_from_to_list_string(vector) return html`<style>\${str}</style>` } function hide_list_style(vector) { let style = document.getElementById('hide-cells-style') if (style == null) { style = document.head.appendChild(html`<style id='hide-cells-style'></style>`) } style.innerHTML = hide_from_to_list_string(vector) } """) ## Script - Mutation Observer ## _mutation_observer = PlutoScript( body = """ function toggle_state(name) { return (e) => { e.preventDefault() e.stopPropagation() let div = e.target.closest('div') const new_val = !div.classList.contains(name) set_state(div, name, new_val) } } function update_hidden(e) { let new_hide = [] if (hide_preamble) { new_hide.push(['', get_link_id(toc.querySelector('div.toc-row'))]) } let tracking_hidden = null let divs = toc.querySelectorAll('div.toc-row') for (const div of divs) { if (tracking_hidden != null) { const hidden = div.classList.contains('hidden') || div.classList.contains('parent-hidden') if (!hidden) { new_hide.push([tracking_hidden, get_link_id(div)]) tracking_hidden = null } } else { const hidden = div.classList.contains('hidden') if (hidden) { tracking_hidden = get_link_id(div) } } } if (tracking_hidden != null) { new_hide.push([tracking_hidden, ""]) } hide_list_style(new_hide) } // Reposition the hide_container using the floating-ui library function repositionTooltip(e) { const { computePosition } = floating_ui const ref = e.target const tooltip = ref.querySelector('.toc-hide-container') if (_.isNil(tooltip)) { console.warn("Something went wrong, no tooltip found") return } computePosition(ref, tooltip, { placement: "left", strategy: "fixed", }).then(pos => { tooltip.style.top = pos.y + "px" }) } function process_row(div, history, old_state, new_state) { // We add the separator div.insertAdjacentElement('beforebegin', html`<div class='toc-row-separator'></div>`) // If we are just processing the first element (so the last row) we also add a separator at the bottom if (_.isEmpty(new_state) && _.every(history, _.isEmpty)) { div.insertAdjacentElement('afterend', html`<div class='toc-row-separator'></div>`) } // We add the reposition event to the row div.addEventListener('mouseenter', repositionTooltip) let id = get_link_id(div) const a = div.querySelector('a') let old_f = a.onclick; a.onclick = (e) => { e.preventDefault() // We avoid triggering the click if coming out of a drag if (toc.classList.contains('recent-drag')) { return } old_f(e) } const level = getHeadingLevel(div) if (level > 1) { history[level].unshift(div) } // We iterate through the history and assign the direct children if they exist, while clearing lower levels history for (let i = 6; i > level; i--) { if (_.isEmpty(history[i])) {continue} if (div.directChildren != undefined) {throw('multiple level with children, unexpected!')} div.directChildren = history[i] history[i] = [] // empty array } const collapse_span = a.insertAdjacentElement('afterbegin', html`<span class='toc-icon toc-collapse'>`) let hide_style = `--height: \${a.clientHeight}px` const hide_container = div.insertAdjacentElement('afterbegin', html`<span class='toc-hide-container' style='\${hide_style}'>`) const hide_span = hide_container.insertAdjacentElement('afterbegin', html`<span class='toc-icon toc-hide'>`) hide_span.addEventListener('click', (e) => { toggle_state('hidden')(e) update_hidden(e) }) if (div.directChildren == undefined) { collapse_span.classList.toggle('no-children', true) } else { propagate_parent(div) collapse_span.addEventListener('click', toggle_state('collapsed')) } let md = editor_state.notebook.cell_inputs[id].metadata let collapsed = old_state[id]?.collapsed ?? _.includes(md['custom_attrs'], 'toc-collapsed') let hidden = old_state[id]?.hidden ?? _.includes(md['custom_attrs'], 'toc-hidden') set_state(div, 'collapsed', collapsed, true) set_state(div, 'hidden', hidden, true) new_state[id] = { collapsed, hidden } } const observer = new MutationObserver(() => { const rows = toc.querySelectorAll('section div.toc-row') let old_state = window.toc_state ?? {} let new_state = {} let history = { 2: [], 3: [], 4: [], 5: [], 6: [], } for (const row of [...rows].reverse()) { process_row(row, history, old_state, new_state) } window.toc_state = new_state toc.classList.toggle('file-state-differs', stateDiffersFile(new_state)) update_hidden() }) observer.observe(toc, {childList: true}) """, invalidation = "observer.disconnect()" ) ## Script - Move Entries Handler ## _move_entries_handler = PlutoScript(; body = """ const { default: interact } = await import('https://esm.sh/interactjs') // We have to enable dynamicDrop to have dropzone recomputed on dragmove interact.dynamicDrop(true) function dragEnabler(e) { if (!toc.classList.contains('drag_enabled') || e.key !== 'Shift') { return true } switch (e.type) { case "keydown": toc.classList.add('allow_all_drop') break; case "keyup": toc.classList.remove('allow_all_drop') break; } updateActiveSeparator() } const window_events = { keydown: dragEnabler, keyup: dragEnabler, } addScriptEventListeners(window, window_events) // Interact.js part let activeDrop = undefined function tagAdjacentSeparators(el, active) { const next = getNextSibling(el, '.toc-row-separator') const prev = getPreviousSibling(el, '.toc-row-separator') if (active) { next?.classList.add('noshow') prev?.classList.add('noshow') } else { next?.classList.remove('noshow') prev?.classList.remove('noshow') } } function getSeparator(startElement, below, allowAll, headingLevel = 8) { let separator if (below) { const selector = '.toc-row:not(.parent-collapsed)' const checkerFunc = allowAll ? generateChecker(selector) : (el) => { if (!el.matches(selector)) { return false } // Check for the right heading level for (let i = headingLevel; i > 0; i--) { const cl = "H" + i if (el.classList.contains(cl)) { return true } } return false } const validRow = getNextSibling(startElement, checkerFunc) // If the activeDrop is the last row or the the last non-collapsed one, the validRow will be `undefined`, so in that case we take the last separator separator = getPreviousSibling(validRow, '.toc-row-separator') ?? _.last(toc.querySelectorAll('.toc-row-separator')) } else { separator = getPreviousSibling(startElement, '.toc-row-separator') } return separator } function getHigherParent(row, level) { const currentLevel = getHeadingLevel(row) if (currentLevel <= level) {return row} for (const par of row.allParents) { // Parents cycle from higher level to lower levels if (getHeadingLevel(par) <= level) {return par} } return row } let uncollapsed = [] function reCollapse(row) { const parents = row?.allParents ?? [] const toRemove = _.difference(uncollapsed, [...parents, row]) for (const el of toRemove) { // debugger set_state(el, "collapsed", true) _.remove(uncollapsed, x => x === el) } } function updateDropZone(row) { const prev = toc.querySelector('.toc-row.active_drop') if (_.isNil(row) || prev === row) {return} if (prev?.timeoutId) { clearTimeout(prev.timeoutId) prev.timeoutId = undefined } prev?.classList.remove('active_drop') row.classList.add('active_drop') reCollapse(row) if (row.classList.contains('collapsed')) { row.timeoutId = setTimeout(() => { uncollapsed.push(row) set_state(row, "collapsed", false) updateActiveSeparator() }, 500) } activeDrop = row } function updateActiveSeparator() { const e = toc.lastDragEvent if (_.isNil(e)) { return } const elBelow = document.elementFromPoint(e.client.x, e.client.y) if (!elBelow.matches('.plutoui-toc :scope')) { // We are out of the ToC, recollapse and remove active separator reCollapse(undefined) toc.querySelector('.toc-row-separator.active')?.classList.remove('active') return } const rowBelow = getRow(elBelow) updateDropZone(rowBelow) if (_.isNil(activeDrop)) {return} const allowAll = toc.classList.contains('allow_all_drop') const headingLevel = getHeadingLevel(toc.draggedElement) const { y, height } = activeDrop.getBoundingClientRect() let thresholdY = y + height/2 if (!allowAll) { // We only allow putting the dragged element above/below rows with equal or higher heading level const currentHeadingLevel = getHeadingLevel(activeDrop) if (currentHeadingLevel > headingLevel) { // We update the threshold based on the relevant parent const par = getHigherParent(activeDrop, headingLevel) const { y, height } = par.getBoundingClientRect() thresholdY = y + height/2 } } // Check if the current position of the mouse is below or above the middle of the active drop zone const isBelow = e.client.y > thresholdY const newSep = getSeparator(activeDrop, isBelow, allowAll, headingLevel) const currentSep = toc.querySelector('.toc-row-separator.active') ?? newSep if (currentSep !== newSep) { currentSep.classList.remove('active') } newSep.classList.add('active') } const dragHandles = interact('.toc-row').draggable({ cursorChecker (action, interactable, element, interacting) { // console.log({action, interactable, element, interacting}) return null }, manualStart: true, // needed for consistent start after hold listeners: { start: function (e) { toc.classList.add('drag_enabled') const row = e.target // console.log('start: ', e) toc.lastDragEvent = e row.classList.add('dragged') toc.draggedElement = row tagAdjacentSeparators(row, true) }, move: function (e) { toc.lastDragEvent = e updateActiveSeparator() }, // move: function (e) {console.log('move: ',e)}, end: function (e) { activeDrop = undefined e.preventDefault() toc.lastDragEvent = e // console.log('end: ', e) const row = e.target // Cleanup row.classList.remove('dragged') toc.classList.remove('drag_enabled') for (const el of toc.querySelectorAll('.active_drop')) { el.classList.remove('active_drop') } reCollapse() tagAdjacentSeparators(row, false) toc.classList.remove('allow_all_drop') // We temporary set the recentDrag flag toc.classList.add('recent-drag') setTimeout(() => { toc.classList.remove('recent-drag') }, 300) // Check if there is an active dropzone const dropZone = toc.querySelector('.toc-row-separator.active') if (_.isNil(dropZone) || dropZone.classList.contains('noshow')) {return} dropZone.classList.remove('active') // We find the cell after the active separator and move the dragged row before that const rowAfter = getNextSibling(dropZone) const cellIdsToMove = getBlockIds(row) // Find the index of the cell that will stay after our moved block const end = editor_state.notebook.cell_order.indexOf(get_link_id(rowAfter)) // If we got -1, it means we have to put the cells at the end pluto_actions.move_remote_cells(cellIdsToMove, end < 0 ? Infinity : end) toc.draggedElement = undefined }, } }).on('hold',function (e) { if (document.body.classList.contains('disable_ui')) { console.log('UI disabled, no interaction!'); return } e.preventDefault() e.stopImmediatePropagation() e.stopPropagation() // console.log('this is hold', e) var interaction = e.interaction if (!interaction.interacting()) { interaction.start( { name: 'drag' }, e.interactable, e.currentTarget, ) } }) """, invalidation = """ dragHandles.unset() """) ## Script - Header Manipulation ## _header_manipulation = PlutoScript(; body = """ const header = toc.querySelector('header') const header_container = header.insertAdjacentElement('afterbegin', html`<span class='toc-header-container'>`) const notebook_hide_icon = header_container.insertAdjacentElement('beforeend', html`<span class='toc-header-icon toc-header-hide'>`) const save_file_icon = header_container.insertAdjacentElement('beforeend', html`<span class='toc-header-icon toc-header-save'>`) save_file_icon.addEventListener('click', save_to_file) header_container.insertAdjacentElement('beforeend', html`<span class='toc-header-filler'>`) header.addEventListener('click', e => { if (e.target != header) {return} scroll_to(cell, {block: 'center', behavior: 'smooth'}) }) header.addEventListener('mouseenter', (e) => { floating_ui.computePosition(header, header_container, { placement: "left", strategy: "fixed", }).then(pos => { header_container.style.top = pos.y + "px" // header_container.style.left = pos.x + "px" // header_container.style.right = `calc(1rem + min(80vw, 300px))` }) }) notebook_hide_icon.addEventListener('click', (e) => { // We find the x coordinate of the pluto-notebook element, to avoid missing the cell when UI is disabled const { x } = document.querySelector('pluto-notebook').getBoundingClientRect() const ref = document.elementFromPoint(x+1,100).closest('pluto-cell') const { y } = ref.getBoundingClientRect() toggle_notebook_attribute('hide-enabled') const dy = ref.getBoundingClientRect().y - y window.scrollBy(0, dy) }) """) ## Script - Save to File ## _save_to_file = PlutoScript(""" function save_to_file() { const state = window.toc_state for (const [k,v] of Object.entries(state)) { toggle_cell_attribute(k, 'toc-hidden', v.hidden) toggle_cell_attribute(k, 'toc-collapsed', v.collapsed) } setTimeout(() => { toc.classList.toggle('file-state-differs', stateDiffersFile(state)) }, 500) } """) # Style # ## Style - Header ## _header_style = @htl(""" <style> .plutoui-toc header { cursor: pointer; } span.toc-header-container { position: fixed; display: none; --size: 25px; height: calc(51px - 1rem); flex-direction: row-reverse; right: calc(1rem + min(80vh, 300px)); } .toc-header-icon { margin-right: 0.3rem; align-self: stretch; display: inline-block; width: var(--size); background-size: var(--size) var(--size); background-repeat: no-repeat; background-position: center; filter: var(--image-filters); cursor: pointer; } .toc-header-filler { margin: .25rem; } header:hover span.toc-header-container, span.toc-header-container:hover { display: flex; } .toc-header-hide { background-image: url(https://cdn.jsdelivr.net/gh/ionic-team/[email protected]/src/svg/eye-outline.svg); opacity: 50%; --size: 1em; } .toc-header-save { background-image: url(https://cdn.jsdelivr.net/gh/ionic-team/[email protected]/src/svg/save-outline.svg); opacity: 50%; } nav:not(.file-state-differs) .toc-header-save { display: none; } pluto-notebook[hide-enabled] span.toc-header-hide { background-image: url(https://cdn.jsdelivr.net/gh/ionic-team/[email protected]/src/svg/eye-off-outline.svg); } </style> """) ## Style - Toc Row ## _toc_row_style = @htl(""" <style> span.toc-hide-container { --width: min(80vw, 300px); position: fixed; display: flex; right: calc(var(--width) + 1rem + 22px - 100px); height: var(--height); width: 100px; z-index: -1; } span.toc-hide { visibility: hidden; opacity: 50%; background-image: url(https://cdn.jsdelivr.net/gh/ionic-team/[email protected]/src/svg/eye-outline.svg); cursor: pointer; } div.toc-row.hidden span.toc-hide { background-image: url(https://cdn.jsdelivr.net/gh/ionic-team/[email protected]/src/svg/eye-off-outline.svg); } span.toc-hide-container:hover > .toc-hide, div.toc-row:hover .toc-hide { visibility: visible; } div.toc-row a { display: flex; } span.toc-icon { --size: 17px; display: block; align-self: stretch; background-size: var(--size) var(--size); background-repeat: no-repeat; background-position: center; width: var(--size); filter: var(--image-filters); } span.toc-collapse { background-image: url(https://cdn.jsdelivr.net/gh/ionic-team/[email protected]/src/svg/chevron-down.svg); margin-right: 3px; min-width: var(--size); } .plutoui-toc section div.toc-row.collapsed span.toc-collapse { background-image: url(https://cdn.jsdelivr.net/gh/ionic-team/[email protected]/src/svg/chevron-forward.svg); } .plutoui-toc section div.toc-row a span.toc-collapse.no-children { background-image: none; } div.toc-row.parent-hidden { text-decoration: underline dotted .5px; text-underline-offset: 2px; } div.toc-row.hidden { text-decoration: underline dashed 1px; text-underline-offset: 2px; } .plutoui-toc div.parent-collapsed { display: none; } pluto-notebook[hide-enabled] div.toc-row.hidden, pluto-notebook[hide-enabled] div.toc-row.parent-hidden { display: none; } .drag_enabled .toc-row.dragged { border: 2px dashed grey; } </style> """) ## Style - Row Separator ## _row_separator_style = @htl(""" <style> div.toc-row-separator { height: 2px; margin: 3px 0px; background: #aaa; display: none; } div.toc-row-separator.active { display: block; } div.toc-row-separator.active.noshow { display: none; } </style> """) ## Style - Always show output ## _always_show_output_style = @htl """ <style> /* This style permits to have a cell whose output is still being shown when the cell is hidden. This is useful for having hidden cells that still are sending HTML as output (like ToC and BondTable) */ pluto-notebook[hide-enabled] pluto-cell[always-show-output] { display: block !important; } pluto-notebook[hide-enabled] pluto-cell[always-show-output]:not(.code_differs) > pluto-input, pluto-notebook[hide-enabled] pluto-cell[always-show-output]:not(.code_differs) > pluto-shoulder, pluto-notebook[hide-enabled] pluto-cell[always-show-output]:not(.code_differs) > pluto-trafficlight, pluto-notebook[hide-enabled] pluto-cell[always-show-output]:not(.code_differs) > pluto-runarea, pluto-notebook[hide-enabled] pluto-cell[always-show-output]:not(.code_differs) > button { display: none; } pluto-notebook[hide-enabled] pluto-cell[always-show-output]:not(.code_differs) { margin-top: 0px; } </style> """ # Main Function # """ ExtendedTableOfContents(;hide_preamble = true, force_hide_enabled = hide_preamble, kwargs...) # Keyword Arguments - `hide_preamble` -> When true, all the cells from the beginning of the notebook till the first heading are hidden (when the notebook is in `hide-enabled` state) - `force_hide_enabled` -> Set the notebook `hide-enabled` status to true when creating the ToC. This status is used to decide whether to show or not hidden cells via CSS. - `kwargs` -> The remaining kwargs are simply passed to `TableOfContents` from PlutoUI which is used internally to generate the ToC. # Description Extends the `TableOfContents` from `PlutoUI` and adds the following functionality: ## Hiding Heading/Cells Hiding headings and all connected cells from notebook view can be done via ExtendedTableOfContents - All cells before the first heading are automatically hidden from the notebook - All hidden cells/headings can be shown by pressing the _eye_ button that appears while hovering on the ToC title. - When the hidden cells are being shown, the hidden headings in the ToC are underlined - Hidden status of specific headings in the notebook can be toggled by pressing on the eye button that appears to the left each heading when hovering over them ## Collapsing Headings in ToC ToC headings are grouped based on heading level, sub-headings at various levels can be collapsed by using the caret symbol that appears to the left of headings in the ToC upon hover. ## Save Hide/Collapsed status on notebook file Preserving the status of collapsed/hidden heading is supported by writing to the notebook file using notebook and cell metadata, allowing to maintain the status even upon reload of Julia/Pluto - When the current collapsed/hidden status of each heading is not reflected in the notebook file, a save icon/button appears on the left of the ToC title upon hover. Clicking the icon saves the current state in the notebook file. ## Changing Headings/Cells order The `ExtendedTableOfContents` allow to re-order the cell groups identified by each heading within the notebook: - Each cell group is identified by the cell containing the heading, plus all the cells below it and up to the next heading (excluded) - Holding the mouse on a ToC heading triggers the ability to move headings around - The target heading is surrounded by a dashed border - While moving the mouse within the ToC, a visual separator appears to indicate the position where the dragged heading will be moved to, depending on the mouse position - Hovering on collapsed headings for at least 300ms opens them up to allow moving headings within collapsed parents - By default, headings can only be moved below or above headings of equal or lower level (H1 < H2 < H3...) - Holding shift during the dragging process allows to put headings before/after any other heading regardless of the level # Example usage # State Manipulation ![State_Manipulation](https://user-images.githubusercontent.com/12846528/217245898-5166682d-b41d-4f1e-b71b-4d7f69c8f192.gif) # Cell Reordering ![Cell_Reordering](https://user-images.githubusercontent.com/12846528/217245256-58e4d537-9547-42ec-b1d8-2994b6bcaf51.gif) """ ExtendedTableOfContents(;hide_preamble = true, force_hide_enabled = hide_preamble,kwargs...) = @htl(""" $(TableOfContents(;kwargs...)) $(make_script([ "const hide_preamble = $hide_preamble", "const force_hide_enabled = $force_hide_enabled", _smooth_scroll, _basics, _floating_ui, _modify_notebook_attributes, _modify_cell_attributes, _hide_cell_blocks, _save_to_file, _header_manipulation, "cell.toggleAttribute('always-show', true)", _mutation_observer, _move_entries_handler, ])) $_header_style $_toc_row_style $_row_separator_style $_always_show_output_style """) # Other Functions # ## Show output when hidden ## """ show_output_when_hidden(x) Wraps the given input `x` inside a custom HTML code created with `HypertextLiteral.@htl` that adds the `always-show-output` attribute to the calling Pluto cell. This makes sure that the cell output remains visible in the HTML even when the cell is hidden using the [`ExtendedTableOfContents`](@ref) cell hiding feature. This is mostly useful to allow having cells that generate output to be rendered within the notebook as hidden cells. The provided attribute will make sure (via CSS) that cell will look exactly like a hidden cell except for its output element. When the output is floating (like for [`BondTable`](@ref) or [`ExtendedTableOfContents`](@ref)), this will make the cell hidden while the rendered output visible. # Example usage ```julia BondTable([bonds...]) |> show_output_when_hidden ``` The code above will allow putting the cell defining the `BondTable` within a hidden part of the notebook while still rendering the floating BondTable. Without this function, the `BondTable` generating cell would need to be located inside a non-hidden part of the notebook. # Note When calling this function with an input object that is not of type `HTML` or `HypertextLiteral.Result`, the function will wrap the object first using `@htl` and `PlutoRunner.embed_display`. Since the `embed_display` function is only available inside of Pluto, """ show_output_when_hidden(x::Union{HTML, HypertextLiteral.Result}) = @htl(""" $x <script> const cell = currentScript.closest('pluto-cell') cell.toggleAttribute('always-show-output', true) invalidation.then(() => { cell.toggleAttribute('always-show-output', false) }) </script> """) show_output_when_hidden(x) = isdefined(Main, :PlutoRunner) ? show_output_when_hidden(@htl("$(Main.PlutoRunner.embed_display(x))")) : error("You can't call this function outside Pluto")
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
9561
module LaTeXEqModule using HypertextLiteral export texeq, eqref, initialize_eqref, @texeq_str const js = HypertextLiteral.JavaScript # LaTeX equation using KaTeX # ## Initialization Function ## #= KaTeX [supports](https://katex.org/docs/supported.html) automatic numbering of *equation* environments. While it does not support equation reference and labelling, [this](https://github.com/KaTeX/KaTeX/issues/2003) hack on github shows how to achieve the label functionality. Unfortunately, since automatic numbering in KaTeX uses CSS counters, it is not possible to access the value of the counter at a specific DOM element. We then create a function that loops through all possible katex equation and counts them, putting the relevant number in the appropriate hyperlink innerText to create equation references that automatically update. The code for the mutationobservers to trigger re-computation of the numbers are taken from the **TableOfContents** in **PlutoUI** =# """ `initialize_eqref()` When run in a Pluto cell, this function generates the necessary javascript to correctly handle and display latex equations made with `texeq` and equation references made with `eqref` """ initialize_eqref() = @htl(""" <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-GvrOXuhMATgEsSwCs4smul74iXGOixntILdUW9XmUC6+HX0sLNAK3q71HotJqlAn" crossorigin="anonymous"> <style> a.eq_href { text-decoration: none; } </style> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js" integrity="sha384-cpW21h6RZv/phavutF+AuVYrr+dA8xD9zs6FwLpaCct6O9ctzYFfFr4dgmgccOTx" crossorigin="anonymous"></script> <script id="katex-eqnum-script"> const a_vec = [] // This will hold the list of a tags with custom click, used for cleaning listeners up upon invalidation const eqrefClick = (e) => { e.preventDefault() // This prevent normal scrolling to link const a = e.target const eq_id = a.getAttribute('eq_id') const eq = document.getElementById(eq_id) history.pushState({},'') // This is to allow going back to the previous position in the page after scroll with History Back eq.scrollIntoView({ behavior: 'smooth', block: 'center', }) } // We make a function to compute the vertical offset (from the top) of an object to the // closest parent containing the katex-html class. This is used to find the equation number // that is closest to the label const findOffsetTop = obj => { let offset = 0 let keepGoing = true while (keepGoing) { offset += obj.offsetTop // Check if the current offsetParent is the containing katex-html if (obj.offsetParent.classList.contains('katex-html')) { keepGoing = false } else { obj = obj.offsetParent } } return offset } // The katex equation numbers are wrapped in spans containing the class 'eqn-num'. WHen you // assign a label, another class ('enclosing') is assigned to some parts of the rendered // html containing the equation line. This means that equation containing labels will have // both 'eqn-num' and 'enclosing'. The new approach is to go through all the katex math // equations one by one and analyze how many numbered lines they contain by counting the // 'eqn-num' instances. const updateCallback = () => { a_vec.splice(0,a_vec.length) // Reset the array const katex_blocks = document.querySelectorAll('.katex-html') // This selects all the environments we created with texeq let i = 0; for (let blk of katex_blocks) { // Find the number of numbered equation in each sub-block let numeqs = blk.querySelectorAll('.eqn-num') let eqlen = numeqs.length if (eqlen == 0) { continue // There is nothing to do here since no equation is numbered } let labeleqs = blk.querySelectorAll('.enclosing') if (labeleqs.length == 0) { // There is no label, so we just have to increase the counter i += eqlen continue } // Find the offset from the katex-html parent of each equation number, the assumption // here is that the span containing the label tag has the same (or almost the same) offset as the related equation number let eqoffsets = Array.from(numeqs,findOffsetTop) for (let item of labeleqs) { const labelOffset = findOffsetTop(item) let prevDiff = -Infinity let currentOffset = eqoffsets.shift() let currentDiff = currentOffset - labelOffset i += 1 while (eqoffsets.length > 0 && currentDiff < 0) { // if currentOffset >= 0, it means that the current equ-num is lower than the label (or at the same height) prevDiff = currentDiff currentOffset = eqoffsets.shift() currentDiff = currentOffset - labelOffset i += 1 } // Now we have to check whether the previous number with offset < 0 or the first with offset > 0 is the closest to the label offset if (Math.abs(currentDiff) > Math.abs(prevDiff)) { // The previous entry was closer, so we reduce i by one and put back the last shifted element in the offset array i -= 1 eqoffsets.unshift(currentOffset) } // We now update all the links that refer to this label const id = item.id const a_vals = document.querySelectorAll(`[eq_id=\${id}]`) a_vals !== null && a_vals.forEach(a => { a_vec.push(a) // Add this to the vector a.innerText = `(\${i})` a.addEventListener('click',eqrefClick) }) } } } const notebook = document.querySelector("pluto-notebook") // We have a mutationobserver for each cell: const observers = { current: [], } const createCellObservers = () => { observers.current.forEach((o) => o.disconnect()) observers.current = Array.from(notebook.querySelectorAll("pluto-cell")).map(el => { const o = new MutationObserver(updateCallback) o.observe(el, {attributeFilter: ["class"]}) return o }) } createCellObservers() // And one for the notebook's child list, which updates our cell observers: const notebookObserver = new MutationObserver(() => { updateCallback() createCellObservers() }) notebookObserver.observe(notebook, {childList: true}) invalidation.then(() => { notebookObserver.disconnect() observers.current.forEach((o) => o.disconnect()) a_vec.forEach(a => a.removeEventListener('click',eqrefClick)) }) </script> """) # Function # ## Eq Ref ## """ `eqref(label::String)` Function that create an hyperlink pointing to a previously defined labelled equation using `texeq()` """ eqref(label) = @htl(""" <a eq_id="$label" id="eqref_$label" href="#$label" class="eq_href">(?)</a> """) ## String interpolation ## # Function to create interpolation inside string literal function _str_interpolate(s::String) str = Expr(:string) last_idx = 1 inside_interp = false parens_found = 0 inside_parens = false simple_interp = true @inbounds for (i,c) ∈ enumerate(s) if !inside_interp if c !== '$' continue end # Add the previous part of the string to the expr push!(str.args,s[last_idx:i-1]) last_idx = i+1 inside_interp = true if s[i+1] === '(' simple_interp = false else simple_interp = true end else if simple_interp if c ∈ (' ','.','\n','\t') # We found the end of the expression, translate this into an expr push!(str.args,Meta.parse(s[last_idx:i-1])) last_idx = i inside_interp = false end else if c === '(' parens_found += 1 inside_parens = true elseif c === ')' parens_found -= 1 if parens_found == 0 inside_parens = false # We found the end of the expression, translate this into an expr push!(str.args,Meta.parse(s[last_idx:i])) last_idx = i+1 inside_interp = false end end end end end if inside_interp push!(str.args,esc(Meta.parse(s[last_idx:end]))) else push!(str.args,s[last_idx:end]) end str end ## Main Function ## """ `texeq(code::String)` Take an input string and renders it inside an equation environemnt (numbered) using KaTeX Equations can be given labels by adding `"\\\\label{name}"` inside the `code` string and subsequently referenced in other cells using `eqref("name")` # Note To avoid the need of doubling backslashes, use the new [`@texeq_str`](@ref) macro if you are on Pluto ≥ v0.17 """ function texeq(code,env="equation") code_escaped = code |> x -> replace(x,"\\\n" => "\\\\\n") |> x -> replace(x,"\\" => "\\\\") |> x -> replace(x,"\n" => " ") #println(code_escaped) @htl """ <div> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-GvrOXuhMATgEsSwCs4smul74iXGOixntILdUW9XmUC6+HX0sLNAK3q71HotJqlAn" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js" integrity="sha384-cpW21h6RZv/phavutF+AuVYrr+dA8xD9zs6FwLpaCct6O9ctzYFfFr4dgmgccOTx" crossorigin="anonymous"></script> <script> katex.render('\\\\begin{$(js(env))} $(js(code_escaped)) \\\\end{$(js(env))}',currentScript.parentElement,{ displayMode: true, trust: context => [ '\\\\htmlId', '\\\\href' ].includes(context.command), macros: { "\\\\label": "\\\\htmlId{#1}{}" }, }) </script> </div> """ end ## Macro ## """ @texeq_str -> katex_html_code Use to generate an HTML output that when rendered in Pluto shows latex equation using KaTeX. Relies on [`texeq`](@ref) but avoids the need of double escaping backslashes. # Examples ```julia texeq" \\frac{q \\sqrt{2}}{15} + $(3 + 2 + (5 + 32)) " ``` """ macro texeq_str(code) # The tring literal macro automatically translates single backslash into double backslash, so we just have to output that expr = :(texeq()) push!(expr.args,esc(_str_interpolate(code))) expr end end
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
1606
module PlutoCombineHTL using Random using HypertextLiteral using HypertextLiteral: Result, Bypass, Reprint, Render using AbstractPlutoDingetjes: is_inside_pluto, AbstractPlutoDingetjes using AbstractPlutoDingetjes.Display using DocStringExtensions using Markdown export make_node, make_html, make_script, formatted_code const LOCAL_MODULE_URL = Ref("https://cdn.jsdelivr.net/gh/disberd/PlutoExtras@$(pkgversion(@__MODULE__))/src/combine_htl/pluto_compat.js") include("typedef.jl") include("helpers.jl") include("constructors.jl") include("js_events.jl") # include("combine.jl") include("show.jl") # include("docstrings.jl") module WithTypes _ex_names = ( :PlutoCombineHTL, :make_node, :make_html, :make_script, :formatted_code, :print_html, :print_javascript, :to_string, :ScriptContent, :PrintToScript, :Node, :DualNode, :CombinedNodes, :PlutoNode, :NormalNode, :Script, :DualScript, :CombinedScripts, :PlutoScript, :NormalScript, :SingleDisplayLocation, :DisplayLocation, :InsidePluto, :OutsidePluto, :InsideAndOutsidePluto, :ShowWithPrintHTML, :AbstractHTML ) for n in _ex_names eval(:(import ..PlutoCombineHTL: $n)) eval(:(export $n)) end end module HelperFunctions _ex_names = ( :shouldskip, :haslisteners, :hasreturn, :returned_element, :script_id, :add_pluto_compat, :hasinvalidation, :plutodefault, :displaylocation, :children, :inner_node, ) for n in _ex_names eval(:(import ..PlutoCombineHTL: $n)) eval(:(export $n)) end end end
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
5909
# Abstract Constructors # Script(::InsidePluto) = PlutoScript Script(::OutsidePluto) = NormalScript Script(::InsideAndOutsidePluto) = DualScript Node(::InsidePluto) = PlutoNode Node(::OutsidePluto) = NormalNode Node(::InsideAndOutsidePluto) = DualNode # ScriptContent # ## AbstractString constructor ## function ScriptContent(s::AbstractString; kwargs...) # We strip eventual leading newline or trailing `isspace` str = strip_nl(s) ael = get(kwargs, :addedEventListeners) do contains(str, "addScriptEventListeners(") end ScriptContent(str, ael) end ## Result constructor ## function ScriptContent(r::Result; iocontext = IOContext(devnull), kwargs...) temp = IOContext(IOBuffer(), iocontext) show(temp, r) str_content = strip(String(take!(temp.io))) isempty(str_content) && return ScriptContent() n_matches = 0 first_idx = 0 first_offset = 0 last_idx = 0 start_regexp = r"<script[^>]*>" end_regexp = r"</script>" for m in eachmatch(r"<script[^>]*>", str_content) n_matches += 1 n_matches > 1 && break first_offset = m.offset first_idx = first_offset + length(m.match) m_end = match(end_regexp, str_content, first_idx) m_end === nothing && error("No closing </script> tag was found in the input") last_idx = m_end.offset - 1 end if n_matches === 0 @warn "No <script> tag was found. Remember that the `ScriptContent` constructor only extract the content between the first <script> tag it finds when using an input of type `HypertextLiteral.Result`" maxlog = 1 return ScriptContent() elseif n_matches > 1 @warn "More than one <script> tag was found. Only the contents of the first one have been extracted" maxlog = 1 elseif first_offset > 1 || last_idx < length(str_content) - length("</script>") @warn "The provided input also contained contents outside of the <script> tag. This content has been discarded" maxlog = 1 end ScriptContent(str_content[first_idx:last_idx]; kwargs...) end ## Other Constructors ## ScriptContent(p::ScriptContent; kwargs...) = p ScriptContent() = ScriptContent("", false) ScriptContent(::Union{Missing, Nothing}; kwargs...) = missing # PlutoScript # PlutoScript(;body = missing, invalidation = missing, id = missing, returned_element = missing, kwargs...) = PlutoScript(body, invalidation, id, returned_element; kwargs...) # Custom Constructors PlutoScript(body; kwargs...) = PlutoScript(;body, kwargs...) PlutoScript(body, invalidation; kwargs...) = PlutoScript(body; invalidation, kwargs...) # Identity/Copy with modification function PlutoScript(s::PlutoScript; kwargs...) (;body, invalidation, id, returned_element) = s PlutoScript(;body, invalidation, id, returned_element, kwargs...) end # From other scripts PlutoScript(n::NormalScript; kwargs...) = error("You can't construct a PlutoScript with a NormalScript as input") PlutoScript(ds::DualScript; kwargs...) = PlutoScript(inner_node(ds, InsidePluto()); kwargs...) # NormalScript # NormalScript(;body = missing, add_pluto_compat = true, id = missing, returned_element = missing, kwargs...) = NormalScript(body, add_pluto_compat, id, returned_element; kwargs...) # Custom constructor NormalScript(body; kwargs...) = NormalScript(;body, kwargs...) # Identity/Copy with modification function NormalScript(s::NormalScript; kwargs...) (;body, add_pluto_compat, id, returned_element) = s NormalScript(;body, add_pluto_compat, id, returned_element, kwargs...) end # From other scripts NormalScript(ps::PlutoScript; kwargs...) = error("You can't construct a `NormalScript` from a `PlutoScript`") NormalScript(ds::DualScript; kwargs...) = NormalScript(inner_node(ds, OutsidePluto()); kwargs...) # DualScript # # Constructor with single non-script body. It mirrors the body both in the Pluto and Normal DualScript(body; kwargs...) = DualScript(body, body; kwargs...) # From Other Scripts DualScript(i::PlutoScript; kwargs...) = DualScript(i, NormalScript(); kwargs...) DualScript(o::NormalScript; kwargs...) = DualScript(PlutoScript(), o; kwargs...) DualScript(ds::DualScript; kwargs...) = DualScript(ds.inside_pluto, ds.outside_pluto; kwargs...) # CombinedScripts # function CombinedScripts(v::Vector; kwargs...) pts_vec = map(v) do el make_script(el) |> PrintToScript end filtered = filter(pts_vec) do el skip_both = shouldskip(el, InsidePluto()) && shouldskip(el, OutsidePluto()) !skip_both end CombinedScripts(filtered; kwargs...) end CombinedScripts(cs::CombinedScripts) = cs CombinedScripts(el) = CombinedScripts([el]) # CombinedNodes # CombinedNodes(cn::CombinedNodes) = cn CombinedNodes(el) = CombinedNodes([el]) # ShowWithPrintHTML # ShowWithPrintHTML(@nospecialize(t); display_type = displaylocation(t)) = ShowWithPrintHTML(t, displaylocation(display_type)) ShowWithPrintHTML(@nospecialize(t::ShowWithPrintHTML); display_type = displaylocation(t)) = ShowWithPrintHTML(t.el, displaylocation(display_type)) ShowWithPrintHTML(@nospecialize(t::PrintToScript); kwargs...) = error("You can't wrap object of type $(typeof(t)) with ShowWithPrintHTML") # PrintToScript # PrintToScript(@nospecialize(t); display_type = displaylocation(t)) = PrintToScript(t, displaylocation(display_type)) PrintToScript(@nospecialize(t::PrintToScript); display_type = displaylocation(t)) = PrintToScript(t.el, displaylocation(display_type)) PrintToScript(@nospecialize(t::AbstractHTML); kwargs...) = error("You can't wrap object of type $(typeof(t)) with PrintToScript") PrintToScript(@nospecialize(t::Union{SingleScript, DualScript}); display_type = displaylocation(t)) = PrintToScript(t, displaylocation(display_type)) PrintToScript(x::Union{AbstractString, ScriptContent, Result}; kwargs...) = PrintToScript(DualScript(ScriptContent(x)); kwargs...) # DualNode # DualNode(i, o) = DualNode(PlutoNode(i), NormalNode(o)) DualNode(i::PlutoNode) = DualNode(i, NormalNode()) DualNode(o::NormalNode) = DualNode(PlutoNode(), o) DualNode(dn::DualNode) = dn
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
9197
# Basics plutodefault(::Union{InsidePluto, InsideAndOutsidePluto}) = true plutodefault(::OutsidePluto) = false plutodefault(::Type{D}) where D <: DisplayLocation = plutodefault(D()) plutodefault(@nospecialize(x::Union{AbstractHTML, PrintToScript})) = plutodefault(displaylocation(x)) # Methods that gets IO as first argument and a ShowWithPrintHTML as second. # These are used to select the correct default for ShowWithPrintHTML plutodefault(io::IO, @nospecialize(x::ShowWithPrintHTML{InsideAndOutsidePluto})) = is_inside_pluto(io) plutodefault(::IO, @nospecialize(x::ShowWithPrintHTML)) = plutodefault(x) displaylocation(@nospecialize(x)) = InsideAndOutsidePluto() displaylocation(d::DisplayLocation) = d displaylocation(pluto::Bool) = pluto ? InsidePluto() : OutsidePluto() displaylocation(::AbstractHTML{D}) where D <: DisplayLocation = D() displaylocation(::PrintToScript{D}) where D <: DisplayLocation = D() function displaylocation(s::Symbol) if s in (:Pluto, :pluto, :inside, :Inside) InsidePluto() elseif s in (:Normal, :normal, :outside, :Outside) OutsidePluto() elseif s in (:both, :Both, :insideandoutside, :InsideAndOutside) InsideAndOutsidePluto() else error("The provided symbol can not identify a display location. Please use one of the following: - :Pluto, :pluto or :inside, :Inside to display inside Pluto - :Normal, :normal or :outside, :Outside to display outside Pluto - :both, :Both, :InsideAndOutside or :insideandoutside to display both inside and outside Pluto ") end end children(cs::CombinedScripts) = cs.scripts children(cn::CombinedNodes) = cn.nodes _eltype(pts::PrintToScript{<:DisplayLocation, T}) where T = T _eltype(swph::ShowWithPrintHTML{<:DisplayLocation, T}) where T = T # We create some common methods for the functions below for F in (:haslisteners, :hasreturn, :returned_element, :script_id) quote $F(l::DisplayLocation; kwargs...) = x -> $F(x, l; kwargs...) $F(ds::DualScript, l::SingleDisplayLocation; kwargs...) = $F(inner_node(ds, l); kwargs...) end |> eval end # shouldskip shouldskip(l::SingleDisplayLocation) = x -> shouldskip(x, l) shouldskip(source_location::DisplayLocation, display_location::SingleDisplayLocation) = source_location isa InsideAndOutsidePluto ? false : source_location !== display_location shouldskip(s::AbstractString, args...) = isempty(s) shouldskip(::Missing, args...) = true shouldskip(p::ScriptContent, args...) = shouldskip(p.content, args...) shouldskip(::Any, args...) = (@nospecialize; return false) shouldskip(n::AbstractHTML, l::SingleDisplayLocation) = (@nospecialize; shouldskip(displaylocation(n), l)) shouldskip(x::PlutoScript, ::InsidePluto) = shouldskip(x.body) && shouldskip(x.invalidation) && shouldskip(x.id) && !hasreturn(x) shouldskip(x::NormalScript, ::OutsidePluto) = shouldskip(x.body) && shouldskip(x.id) && !hasreturn(x) shouldskip(n::NonScript{L}, ::L) where L <: SingleDisplayLocation = n.empty # Dual Script/Node shouldskip(d::Dual, l::SingleDisplayLocation) = shouldskip(inner_node(d, l), l) # Combined shouldskip(c::Combined, l::SingleDisplayLocation) = all(shouldskip(l), children(c)) function shouldskip(wrapper::Union{ShowWithPrintHTML, PrintToScript}, l::SingleDisplayLocation) el = wrapper.el if el isa AbstractHTML shouldskip(el, l) else shouldskip(displaylocation(wrapper), l) end end # HypertextLiteral methods shouldskip(x::Bypass, args...) = shouldskip(x.content) shouldskip(x::Render, args...) = shouldskip(x.content) # add_pluto_compat add_pluto_compat(@nospecialize(::Any)) = false add_pluto_compat(ns::NormalScript) = ns.add_pluto_compat add_pluto_compat(ds::DualScript) = add_pluto_compat(inner_node(ds, OutsidePluto())) add_pluto_compat(v::Vector{<:PrintToScript}) = any(add_pluto_compat, v) add_pluto_compat(cs::CombinedScripts) = add_pluto_compat(children(cs)) add_pluto_compat(pts::PrintToScript) = add_pluto_compat(pts.el) # hasinvalidation hasinvalidation(@nospecialize(::Any)) = false hasinvalidation(s::PlutoScript) = !shouldskip(s.invalidation) hasinvalidation(ds::DualScript) = hasinvalidation(inner_node(ds, InsidePluto())) hasinvalidation(v::Vector{<:PrintToScript}) = any(hasinvalidation, v) hasinvalidation(cs::CombinedScripts) = hasinvalidation(children(cs)) hasinvalidation(ps::PrintToScript) = hasinvalidation(ps.el) # haslisteners haslisteners(::Missing) = false haslisteners(s::ScriptContent) = s.addedEventListeners haslisteners(s::SingleScript, l::DisplayLocation = displaylocation(s)) = l == displaylocation(s) ? haslisteners(s.body) : false haslisteners(cs::CombinedScripts, l::DisplayLocation) = any(haslisteners(l), children(cs)) haslisteners(::PrintToScript, args...) = (@nospecialize; false) haslisteners(pts::PrintToScript{<:DisplayLocation, <:Script}, args...) = (@nospecialize; haslisteners(pts.el, args...)) # hasreturn hasreturn(s::SingleScript, l::DisplayLocation = displaylocation(s)) = l == displaylocation(s) ? !ismissing(returned_element(s)) : false hasreturn(cs::CombinedScripts, l::DisplayLocation) = any(hasreturn(l), children(cs)) hasreturn(::PrintToScript, args...) = (@nospecialize; return false) hasreturn(pts::PrintToScript{<:DisplayLocation, <:Script}, args...) = (@nospecialize; hasreturn(pts.el, args...)) # returned_element returned_element(s::SingleScript, l::DisplayLocation = displaylocation(s)) = l == displaylocation(s) ? s.returned_element : missing # We check for duplicate returns in the constructor so we just get the return from the last script function returned_element(cs::CombinedScripts, l::DisplayLocation) @inbounds for pts in children(cs) hasreturn(pts, l) && return returned_element(pts, l) end return missing end returned_element(pts::PrintToScript{<:DisplayLocation, <:Script}, args...) = (@nospecialize; returned_element(pts.el, args...)) function script_id(s::SingleScript, l = displaylocation(s); default::Union{String, Missing} = randstring(6)) if l == displaylocation(s) ismissing(s.id) ? default : s.id else missing end end function script_id(cs::CombinedScripts, l::SingleDisplayLocation; default = randstring(6)) for pts in children(cs) id = script_id(pts, l; default = missing) id isa String && return id end return default end script_id(::PrintToScript, args...; kwargs...) = (@nospecialize; return missing) script_id(pts::PrintToScript{<:DisplayLocation, <:Script}, args...; kwargs...) = (@nospecialize; script_id(pts.el, args...; kwargs...)) inner_node(ds::Union{DualNode, DualScript}, ::InsidePluto) = ds.inside_pluto inner_node(ds::Union{DualNode, DualScript}, ::OutsidePluto) = ds.outside_pluto ## Make Script ## """ $TYPEDSIGNATURES GESU """ make_script(; type = :both, kwargs...) = make_script(displaylocation(type); kwargs...) make_script(type::Symbol, args...; kwargs...) = make_script(displaylocation(type), args...; kwargs...) # Basic location-based constructors make_script(::InsideAndOutsidePluto; body = missing, invalidation = missing, inside = PlutoScript(body, invalidation), outside = NormalScript(body), kwargs...) = DualScript(inside, outside; kwargs...) make_script(l::SingleDisplayLocation; kwargs...) = Script(l)(;kwargs...) # Take a Script as Second argument make_script(l::DisplayLocation, x::Union{SingleScript, DualScript}; kwargs...) = Script(l)(x; kwargs...) # Other with no location make_script(body; kwargs...) = make_script(;body, kwargs...) make_script(i, o; kwargs...) = DualScript(i, o; kwargs...) make_script(x::Script; kwargs...) = make_script(displaylocation(x), x; kwargs...) make_script(x::CombinedScripts) = x make_script(v::Vector; kwargs...) = CombinedScripts(v; kwargs...) # From ShowWithPrintHTML make_script(@nospecialize(s::ShowWithPrintHTML{<:DisplayLocation, <:Script})) = s.el make_script(@nospecialize(s::ShowWithPrintHTML)) = error("make_script on `ShowWithPrintHTML{T}` types is only valid if `T <: Script`") # From PrintToScript, this is just to have a no-op when calling make_script inside CombinedScripts make_script(@nospecialize(s::PrintToScript)) = s ## Make Node ## # only kwargs method make_node(; type = :both, kwargs...) = make_node(displaylocation(type); kwargs...) # Symbol + args method make_node(type::Symbol, args...; kwargs...) = make_node(displaylocation(type), args...; kwargs...) # Methods with location as first argument and kwargs... make_node(::InsideAndOutsidePluto; inside = "", outside = "") = DualNode(inside, outside) make_node(l::SingleDisplayLocation; content = "") = Node(l)(content) # Methods with location as first argument and args make_node(::InsideAndOutsidePluto, inside, outside=inside) = DualNode(inside, outside) make_node(l::SingleDisplayLocation, content, args...) = Node(l)(content, args...) # Defaults without location make_node(n::Node) = n make_node(i, o) = DualNode(i, o) make_node(content) = DualNode(content, content) make_node(v::Vector) = CombinedNodes(v) make_node(pts::PrintToScript) = CombinedScripts([pts]) ## Make HTML ## make_html(x; kwargs...) = ShowWithPrintHTML(make_node(x); kwargs...) make_html(@nospecialize(x::ShowWithPrintHTML); kwargs...) = ShowWithPrintHTML(x; kwargs...)
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
1712
## Automatic Event Listeners - DualScript ## _events_listeners_preamble = let body = ScriptContent(""" /* # JS Listeners Preamble added by PlutoExtras */ // Array where all the event listeners are stored const _events_listeners_ = [] // Function that can be called to add events listeners within the script function addScriptEventListeners(element, listeners) { if (listeners.constructor != Object) { error('Only objects with keys as event names and values as listener functions are supported') } _events_listeners_.push({element, listeners}) } /* # JS Listeners Preamble added by PlutoExtras */ """, false) # We for this to avoid detecting the listeners and avoid stripping newlines ds = DualScript(PlutoScript(body), NormalScript(body)) |> PrintToScript end _events_listeners_postamble = let body = ScriptContent(""" /* # JS Listeners Postamble added by PlutoExtras */ // Assign the various events listeners defined within the script for (const item of _events_listeners_) { const { element, listeners } = item for (const [name, func] of _.entries(listeners)) { element.addEventListener(name, func) } } /* # JS Listeners Postamble added by PlutoExtras */""", false) invalidation = ScriptContent(""" /* # JS Listeners invalidation added by PlutoExtras */ // Remove the events listeners during invalidation for (const item of _events_listeners_) { const { element, listeners } = item for (const [name, func] of _.entries(listeners)) { element.removeEventListener(name, func) } } /* # JS Listeners invalidation added by PlutoExtras */ """; addedEventListeners = false) ds = DualScript(PlutoScript(body, invalidation), NormalScript(body)) |> PrintToScript end
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
10946
# Helpers # # This function just iterates and print the javascript of an iterable containing DualScript elements function _iterate_scriptcontents(io::IO, iter, location::SingleDisplayLocation, kind::Symbol = :body) mime = MIME"text/javascript"() # We cycle through the DualScript iterable pluto = plutodefault(location) for pts in iter kwargs = if _eltype(pts) <: Script (; pluto, kind, ) else # We only print when iterating the body for non Script elements kind === :body || continue (;pluto) end print_javascript(io, pts; kwargs...) end return nothing end function write_script(io::IO, contents::Vector{<:PrintToScript}, location::InsidePluto; returns = missing, kwargs...) # We cycle through the contents to write the body part _iterate_scriptcontents(io, contents, location, :body) # If there is no valid invalidation, we simply return if hasinvalidation(contents) # We add a separating newline println(io) # Start processing the invalidation println(io, "invalidation.then(() => {") _iterate_scriptcontents(io, contents, location, :invalidation) println(io, "})") end maybe_add_return(io, returns, location) return end function write_script(io::IO, contents::Vector{<:PrintToScript}, location::OutsidePluto; returns = missing, only_contents = false) # We wrap everything in an async call as we want to use await only_contents || println(io, "(async (currentScript) => {") # If the script should have the added Pluto compat packages we load them if add_pluto_compat(contents) && !only_contents println(io, """ // Load the Pluto compat packages from the custom module const {DOM, Files, Generators, Promises, now, svg, html, require, _} = await import('$(LOCAL_MODULE_URL[])') """) end # We cycle through the contents to write the body part _iterate_scriptcontents(io, contents, location, :body) # We print the returned element if provided maybe_add_return(io, returns, location) # We close the async function definition and call it with the currentScript only_contents || println(io, "})(document.currentScript)") return end ## print_javascript ## # ScriptContent function print_javascript(io::IO, sc::ScriptContent; kwargs...) shouldskip(sc) && return println(io, sc.content) # Add the newline end # Script function print_javascript(io::IO, s::Union{SingleScript, DualScript}; pluto = plutodefault(s), kwargs...) print_javascript(io, CombinedScripts(s); pluto, kwargs...) end # CombinedScripts function print_javascript(io::IO, ms::CombinedScripts; pluto = plutodefault(io), only_contents = false) location = displaylocation(pluto) shouldskip(ms, location) && return # We add the listeners handlers if any of the script requires it contents = children(ms) |> copy # We copy to avoid mutating in the next line if haslisteners(ms, location) && !only_contents pushfirst!(contents, _events_listeners_preamble) push!(contents, _events_listeners_postamble) end write_script(io, contents, location; returns = returned_element(ms, location), only_contents) end # PrintToScript # Default version that just forwards function print_javascript(io::IO, pts::PrintToScript; pluto = plutodefault(pts), kwargs...) l = displaylocation(pluto) # We skip if the loction of pts is explicitly not compatible with l shouldskip(pts, l) && return print_javascript(io, pts.el; pluto, kwargs...) return nothing end # Here we add methods for PrintToScript containing scripts. These will simply print the relevant ScriptContent function print_javascript(io::IO, pts::PrintToScript{<:DisplayLocation, <:Script}; pluto = plutodefault(pts.el), kind = :body) l = displaylocation(pluto) el = pts.el s = el isa DualScript ? inner_node(el, l) : el # We return if the location we want to print is not supported by the script shouldskip(s, l) && return if kind === :invalidation && s isa NormalScript # We error if we are trying to print the invalidation field of a NormalScript error("You can't print invalidation for a NormalScript") end sc = getproperty(s, kind) shouldskip(sc, l) || print_javascript(io, sc) return nothing end # If the PrintToScript element is a function, we call it passing io and kwargs to it function print_javascript(io::IO, pts::PrintToScript{<:DisplayLocation, <:Function}; pluto = is_inside_pluto(io), kwargs...) l = displaylocation(pluto) # We skip if the loction of pts is explicitly not compatible with l shouldskip(pts, l) && return f = pts.el f(io; pluto, kwargs...) return nothing end # For AbstractDicts, we use HypertextLiteral.print_script function print_javascript(io::IO, d::Union{AbstractDict, NamedTuple, Tuple, AbstractVector}; pluto = is_inside_pluto(io), kwargs...) if pluto pjs = published_to_js(d) show(io, MIME"text/javascript"(), pjs) else HypertextLiteral.print_script(io, d) end return nothing end # Catchall method reverting to show text/javascript print_javascript(io::IO, x; kwargs...) = (@nospecialize; show(io, MIME"text/javascript"(), x)) ## Maybe add return ## maybe_add_return(::IO, ::Missing, ::SingleDisplayLocation) = nothing maybe_add_return(io::IO, name::String, ::InsidePluto) = println(io, "return $name") maybe_add_return(io::IO, name::String, ::OutsidePluto) = print(io, " /* code added by PlutoExtras to simulate script return */ currentScript.insertAdjacentElement('beforebegin', $name) ") # This function will simply write into IO the html code of the script, including the <script> tag # This is applicable for CombinedScripts and DualScript function print_html(io::IO, s::Script; pluto = plutodefault(s), only_contents = false) location = displaylocation(pluto) shouldskip(s, location) && return # We write the script tag id = script_id(s, location) println(io, "<script id='$id'>") # Print the content print_javascript(io, s; pluto, only_contents) # Print the closing tag println(io, "</script>") return end print_html(io::IO, s::AbstractString; kwargs...) = write(io, strip_nl(s)) function print_html(io::IO, n::NonScript{L}; pluto = plutodefault(n)) where L <: SingleDisplayLocation _pluto = plutodefault(n) # If the location doesn't match the provided kwarg we do nothing xor(pluto, _pluto) && return println(io, n.content) return end print_html(io::IO, dn::DualNode; pluto = plutodefault(dn)) = print_html(io, inner_node(dn, displaylocation(pluto)); pluto) function print_html(io::IO, cn::CombinedNodes; pluto = is_inside_pluto(io)) for n in children(cn) print_html(io, n; pluto) end end function print_html(io::IO, swph::ShowWithPrintHTML; pluto = plutodefault(io, swph)) l = displaylocation(pluto) # We skip if the loction of pts is explicitly not compatible with l shouldskip(swph, l) && return print_html(io, swph.el; pluto) return nothing end # If the ShowWithPrintHTML element is a function, we call it passing io and kwargs to it function print_html(io::IO, swph::ShowWithPrintHTML{<:DisplayLocation, <:Function}; pluto = plutodefault(io, swph), kwargs...) l = displaylocation(pluto) # We skip if the loction of pts is explicitly not compatible with l shouldskip(swph, l) && return f = swph.el f(io; pluto, kwargs...) return nothing end # Catchall method reverting to show text/javascript print_html(io::IO, x; kwargs...) = (@nospecialize; show(io, MIME"text/html"(), x)) ## Formatted Code ## # We simulate the Pluto iocontext even outside Pluto if want to force printing as in pluto _pluto_default_iocontext() = try Main.PlutoRunner.default_iocontext catch function core_published_to_js(io, x) write(io, "/* Here you'd have your published object on Pluto */") return nothing end IOContext(devnull, :color => false, :limit => true, :displaysize => (18, 88), :is_pluto => true, # :pluto_supported_integration_features => supported_integration_features, :pluto_published_to_js => (io, x) -> core_published_to_js(io, x), ) end function to_string(element, ::M, args...; kwargs...) where M <: MIME f = if M === MIME"text/javascript" print_javascript elseif M === MIME"text/html" print_html else error("Unsupported mime $M provided as input") end to_string(element, f, args...; kwargs...) end function to_string(element, f::Function, io::IO = IOBuffer(); kwargs...) iocontext = get(kwargs, :iocontext) do pluto = get(kwargs, :pluto, is_inside_pluto()) pluto ? _pluto_default_iocontext() : IOContext(devnull) end f(IOContext(io, iocontext), element; kwargs...) code = String(take!(io)) return code end function formatted_code(s::Union{Script, ScriptContent}, mime::MIME"text/javascript"; kwargs...) codestring = to_string(s, mime; kwargs...) Markdown.MD(Markdown.Code("js", codestring)) end function formatted_code(n::Node, mime::MIME"text/html"; kwargs...) codestring = to_string(n, mime; kwargs...) Markdown.MD(Markdown.Code("html", codestring)) end # Default MIMEs default_mime(::ScriptContent) = MIME"text/javascript"() default_mime(::Node) = MIME"text/html"() formatted_code(s::Union{ScriptContent, Node}; kwargs...) = formatted_code(s, default_mime(s); kwargs...) # Versions returning functions formatted_code(mime::MIME; kwargs...) = x -> formatted_code(x, mime; kwargs...) # This forces just the location using the DisplayLocation type formatted_code(l::SingleDisplayLocation; kwargs...) = x -> formatted_code(x; pluto = plutodefault(l), kwargs...) formatted_code(; kwargs...) = x -> formatted_code(x; kwargs...) # Default no argument version formatted_contents(args...; kwargs...) = formatted_code(args...; kwargs..., only_contents = true) HypertextLiteral.content(n::Node) = HypertextLiteral.Render(ShowWithPrintHTML(n, InsideAndOutsidePluto())) #= Fix for Julia 1.10 The `@generated` `print_script` from HypertextLiteral is broken in 1.10 See [issue 33](https://github.com/JuliaPluto/HypertextLiteral.jl/issues/33) We have to also define a method for `print_script` to avoid precompilation errors =# HypertextLiteral.print_script(io::IO, val::ScriptContent) = show(io, MIME"text/javascript"(), val) HypertextLiteral.print_script(io::IO, v::Vector{ScriptContent}) = for s in v HypertextLiteral.print_script(io, s) end HypertextLiteral.print_script(::IO, ::Script) = error("Interpolation of `Script` subtypes is not allowed within a script tag. Use `make_node` to generate a `<script>` node directly in HTML") # Show - text/javascript # function Base.show(io::IO, ::MIME"text/javascript", s::Union{ScriptContent, Script}) print_javascript(io, s) end Base.show(::IO, ::MIME"text/javascript", ::T) where T <: Union{ShowWithPrintHTML, NonScript} = error("Objects of type `$T` are not supposed to be shown with mime 'text/javascript'") # Show - text/html # Base.show(io::IO, mime::MIME"text/html", sc::ScriptContent) = show(io, mime, formatted_code(sc)) Base.show(io::IO, ::MIME"text/html", s::Node) = print_html(io, s; pluto = is_inside_pluto(io)) Base.show(io::IO, ::MIME"text/html", s::ShowWithPrintHTML) = print_html(io, s.el; pluto = plutodefault(io, s))
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
13457
abstract type DisplayLocation end abstract type SingleDisplayLocation <: DisplayLocation end struct InsidePluto <: SingleDisplayLocation end struct OutsidePluto <: SingleDisplayLocation end struct InsideAndOutsidePluto <: DisplayLocation end abstract type AbstractHTML{D<:DisplayLocation} end abstract type Node{D} <: AbstractHTML{D} end abstract type NonScript{D} <: Node{D} end abstract type Script{D} <: Node{D} end const SingleNode = Node{<:SingleDisplayLocation} const SingleScript = Script{<:SingleDisplayLocation} ## ScriptContent ## """ $TYPEDEF This struct is a simple wrapper for JS script content and is intended to provide pretty printing of script contents and custom interpolation inside the `<script>` tags of the `@htl` macro. It is used as building block for creating and combining JS scripts to correctly render inside and outside Pluto notebooks. # Field $TYPEDFIELDS ## Note The `addedEventListeners` field is usually automatically computed based on the provided `content` value when using one of the 2 main constructors below: # Main Constructors ScriptContent(s::AbstractString; kwargs...) ScriptContent(r::HypertextLiteral.Result; kwargs...) One would usually call the constructor either with a `String` or `HypertextLiteral.Result`. In this case, the provided content is parsed and checked for calls to the `addScriptEventListeners` function, eventually setting the `addedEventListeners` field accordingly. One can force the flag to a custom value either by directly calling the (default) inner constructor with 2 positional arguments, or by passing `addedEventListeners = value` kwarg to one of the two constructrs above. For what concerns construction with `HypertextLiteral.Result` as input, the provided `Result` needs to contain an opening and closing `<script>` tag. In the example below, the constructor will parse the `Result` and only extracts the content within the tags, so only the `code...` part below. All content appearing before or after the <script> tag (including additional script tags) will be ignored and a warning will be produced. ```julia wrapper = ScriptContent(@htl(\"\"\" something_before <script> code... </script> something_after \"\"\")) ``` When interpolating `wrapper` above inside another `@htl` macro as `@htl "<script>\$wrapper</script>"` it would be as equivalent to directly writing `code...` inside the script. This is clearly only beneficial if multiple `ScriptContent` variables are interpolated inside a single <script> block. On top of the interpolation, an object of type `ScriptContent` will show its contents as a formatted javascript code markdown element when shown in Pluto. See also: [`PlutoScript`](@ref), [`NormalScript`](@ref), [`DualScript`](@ref) # Examples ```julia let asd = ScriptContent(@htl \"\"\" <script> let out = html`<div></div>` console.log('first script') </script> \"\"\") lol = ScriptContent(@htl \"\"\" <script> let a = Math.random() out.innerText = a console.log('second script') return out </script> \"\"\") @htl \"\"\" <script> \$([ asd, lol ]) </script> \"\"\" end ``` """ struct ScriptContent "Content of the script part" content::String "Flag indicating if the script has custom listeners added via the `addScriptEventListeners` function." addedEventListeners::Bool end ## PlutoScript ## """ $TYPEDEF # Fields $TYPEDFIELDS ## Note Eventual elements that have to be returned from the script (this is a feature of Pluto) should not be directly _returned_ from the script content but should be simply assigned to a JS variable whose name is set to the `returned_element` field. This is necessary to prevent exiting early from a chain of Scripts. For example, the following code which is a valid JS code inside a Pluto cell to create a custom div as output: ```julia @htl \"\"\" <script> return html`<div>MY DIV</div>` </script> \"\"\" ``` must be constructed when using `PlutoScript` as: ```julia PlutoScript("let out = html`<div>MY DIV</div>`"; returned_element = "out") ``` # Additional Constructors PlutoScript(body; kwargs...) PlutoScript(body, invalidation; kwargs...) For the body and invalidation fields, the constructor also accepts inputs of type `String`, `HypertextLiteral.Result` and `IOBuffer`, translating them into `ScriptContent` internally. PlutoScript(s::PlutoScript; kwargs...) This constructor is used to copy the elements from another PlutoScript with the option of overwriting the fields provided as `kwargs` # Description This struct is used to create and compose scripts together with the `@htl` macro from HypertextLiteral. It is intended for use inside Pluto notebooks to ease composition of bigger scripts via smaller parts. When an PlutoScript is interpolated inside the `@htl` macro, the following code is generated: ```html <script id=\$id> \$body invalidation.then(() => { \$invalidation }) ``` If the `id = missing` (default), a random string id is associated to the script. If `id = nothing`, a script without id is created. If the `invalidation` field is `missing`, the whole invalidation block is skipped. Multiple `PlutoScript` elements can be combined together using the [`combine_script`](@ref) function also exported by this package, allowing to generate bigger scripts by composing multiple building blocks. When shown inside the output of Pluto cells, the PlutoScript object prints its containing formatted code as a `Markdown.Code` element. # Javascript Events Listeners `PlutoScript` provides some simplified way of adding event listeners in javascript that are automatically removed upon cell invalidation. Scripts created using `PlutoScript` expose an internal javascript function ```js addScriptEventListeners(element, listeners) ``` which accepts any givent JS `element` to which listeners have to be attached, and an object of with the following key-values: ```js { eventName1: listenerFunction1, eventName2: listenerFunction2, ... } ``` When generating the script to execute, `PlutoScript` automatically adds all the provided listeners to the provided element, and also takes care of removing all the listeners upon cell invalidation. For example, the following julia code: ```julia let script = PlutoScript(@htl(\"\"\" <script> addScriptEventListeners(window, { click: function (event) { console.log('click: ',event) }, keydown: function (event) { console.log('keydown: ',event) }, }) </script> \"\"\")) @htl"\$script" end ``` is functionally equivalent of writing the following javascript code within the script tag of the cell output ```js function onClick(event) { console.log('click: ',event) } function onKeyDown(event) { console.log('keydown: ',event) } window.addEventListener('click', onClick) window.addEventListener('keydown', onKeyDown) invalidation.then(() => { window.removeEventListener('click', onClick) window.removeEventListener('keydown', onKeyDown) }) ``` See also: [`ScriptContent`](@ref), [`combine_scripts`](@ref) # Examples: The following code: ```julia let a = PlutoScript("console.log('asd')") b = PlutoScript(@htl("<script>console.log('boh')</script>"), "console.log('lol')") script = combine_scripts([a,b];id="test") out = @htl("\$script") end ``` is equivalent to writing directly ```julia @htl \"\"\" <script id='test'> console.log('asd') console.log('boh') invalidation.then(() => { console.log('lol') }) \"\"\" </script> ``` """ struct PlutoScript <: Script{InsidePluto} "The main body of the script" body::Union{Missing,ScriptContent} "The code to be executed inside the invalidation promise. Defaults to `missing`" invalidation::Union{Missing,ScriptContent} "The id to assign to the script. Defaults to `missing`" id::Union{Missing, String} "The name of the JS element that is returned by the script. Defaults to `missing`" returned_element::Union{Missing, String} function PlutoScript(b,i,id::Union{Missing, Nothing, String}, returned_element; kwargs...) body = ScriptContent(b; kwargs...) invalidation = ScriptContent(i) @assert invalidation === missing || invalidation.addedEventListeners === false "You can't have added event listeners in the invalidation script" new(body,invalidation, something(id, missing), returned_element) end end ## NormalScript struct NormalScript <: Script{OutsidePluto} "The main body of the script" body::Union{Missing, ScriptContent} "A flag to indicate if the script should include basic JS libraries available from Pluto. Defaults to `true`" add_pluto_compat::Bool "The id to assign to the script. Defaults to `missing`" id::Union{Missing, String} "The name of the JS element that is returned by the script. Defaults to `missing`" returned_element::Union{Missing, String} function NormalScript(b, add_pluto_compat, id, returned_element; kwargs...) body = ScriptContent(b; kwargs...) new(body, add_pluto_compat, something(id, missing), returned_element) end end ## DualScript ## @kwdef struct DualScript <: Script{InsideAndOutsidePluto} inside_pluto::PlutoScript = PlutoScript() outside_pluto::NormalScript = NormalScript() function DualScript(i, o; kwargs...) ip = PlutoScript(i; kwargs...) op = NormalScript(o; kwargs...) new(ip, op) end end ## PrintToScript struct PrintToScript{D<:DisplayLocation, T} el::T PrintToScript(el::T, ::D) where {T, D<:DisplayLocation} = new{D,T}(el) end ## CombinedScripts ## struct CombinedScripts <: Script{InsideAndOutsidePluto} scripts::Vector{<:PrintToScript} function CombinedScripts(v::Vector{<:PrintToScript}; returned_element = missing) # We check for only one return expression and it being in the last script return_count = 0 return_idx = something(findfirst(x -> x isa Script, v), 0) for (i, s) in enumerate(v) # If no return is present we skip this script hasreturn(s, InsidePluto()) || hasreturn(s, OutsidePluto()) || continue return_count += 1 return_idx = i end @assert return_count < 2 "More than one return expression was found while constructing the CombinedScripts. This is not allowed." # If we don't have to set a custom returned_element we just create a new CombinedScripts returned_element === missing && return new(v) final_v = if return_idx === 0 # We have to add a DualScript that just returns the element new_v = vcat(v, DualScript(""; returned_element) |> PrintToScript) else new_v = copy(v) dn = new_v[return_idx].el new_v[return_idx] = DualScript(dn; returned_element) |> PrintToScript new_v end new(final_v) end end struct ShowWithPrintHTML{D<:DisplayLocation, T} <: AbstractHTML{D} el::T ShowWithPrintHTML(el::T, ::D) where {T, D<:DisplayLocation} = new{D,T}(el) end # HTML Nodes # # We use a custom IO to parse the HypertextLiteral.Result for removing newlines and checking if empty @kwdef struct ParseResultIO <: IO parts::Vector = [] end # Now we define custom print method to extract the Result parts. See # https://github.com/JuliaPluto/HypertextLiteral.jl/blob/2bb465047afdfbb227171222049f315545c307fb/src/primitives.jl for T in (Bypass, Render, Reprint) Base.print(io::ParseResultIO, x::T) = shouldskip(x) || push!(io.parts, x) end _isnewline(x) = x in ('\n', '\r') # This won't remove tabs and whitespace strip_nl(s::AbstractString) = lstrip(_isnewline, rstrip(s)) _remove_leading(x) = x _remove_leading(x::Bypass{<:AbstractString}) = Bypass(lstrip(_isnewline, x.content)) _remove_trailing(x) = x _remove_trailing(x::Bypass{<:AbstractString}) = Bypass(rstrip(isspace, x.content)) # We define PlutoNode and NormalNode for (T, P) in ((:PlutoNode, :InsidePluto), (:NormalNode, :OutsidePluto)) block = quote struct $T <: NonScript{$P} content::Result empty::Bool end # Empty Constructor $T() = $T(@htl(""), true) # Constructor from Result function $T(r::Result) io = ParseResultIO() # We don't use show directly to avoid the EscapeProxy here r.content(io) node = if isempty(io.parts) $T(r, true) else # We try to eventually remove trailing and leading redundant spaces xs = io.parts xs[begin] = _remove_leading(xs[begin]) xs[end] = _remove_trailing(xs[end]) $T(Result(xs...), false) end return node end # Constructor from AbstractString function $T(s::AbstractString) str = strip_nl(s) out = if isempty(str) $T(@htl(""), true) else r = @htl("$(ShowWithPrintHTML(str))") $T(r, false) end end # No-op constructor $T(t::$T) = t # Generic constructor $T(content) = $T(@htl("$content")) end # Create the function constructing from HypertextLiteral or HTML eval(block) end ## DualNode struct DualNode <: NonScript{InsideAndOutsidePluto} inside_pluto::PlutoNode outside_pluto::NormalNode DualNode(i::PlutoNode, o::NormalNode) = new(i, o) end ## CombinedNodes struct CombinedNodes <: NonScript{InsideAndOutsidePluto} nodes::Vector{<:ShowWithPrintHTML} function CombinedNodes(v::Vector) swph_vec = map(v) do el make_node(el) |> ShowWithPrintHTML end filtered = filter(swph_vec) do el skip_both = shouldskip(el, InsidePluto()) && shouldskip(el, OutsidePluto()) !skip_both end new(filtered) end end const Single = Union{SingleNode, SingleScript} const Dual = Union{DualScript, DualNode} const Combined = Union{CombinedScripts, CombinedNodes} function Base.getproperty(c::Combined, s::Symbol) if s === :children children(c) else getfield(c,s) end end
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
762
module StructBondModule import PlutoUI.Experimental: wrapped using ..PlutoCombineHTL.WithTypes import AbstractPlutoDingetjes.Bonds import REPL: fielddoc using HypertextLiteral using PlutoUI: combine export BondTable, StructBond, @NTBond, @BondsList, Popout, @popoutasfield, @typeasfield, popoutwrap, @fieldbond, @fielddescription, @fielddata export ToggleReactiveBond const CSS_Sheets = map(readdir(joinpath(@__DIR__, "css"))) do file name = replace(file, r"\.[\w]+$" => "") |> Symbol path = joinpath(@__DIR__, "css", file) name => read(path, String) end |> NamedTuple include("toggle_reactive.jl") include("basics.jl") include("main_definitions.jl") include("macro.jl") end
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
6408
# StructBond Helpers # ## Structs ## struct NotDefined end ## Field Functions ## ### Description ### # This is a wrapper to extract eventual documentation strings from struct fields _fielddoc(s,f) = try fielddoc(s,f) catch nothing end # Default implementation to be overrided for specific types and fields in order to provide custom descriptions function fielddescription(::Type, ::Val) @nospecialize return NotDefined() end function fielddescription(s::Type, f::Symbol) @nospecialize @assert hasfield(s, f) "The structure $s has no field $f" # We check if the structure has a specific method for the field out = fielddescription(s, Val(f)) out isa NotDefined || return out # Now we try with the docstring of the field out = _fielddoc(s, f) # When fielddoc doesn't find a specific field docstring (even when called with non-existing fields), it returns a standard markdown that lists the fields of the structure, se we test for a very weird symbol name to check if the returned value is actually coming from a docstring out == _fielddoc(s, :__Very_Long_Nonexisting_Field__) || return out # Lastly, we just give the name of the field if all else failed out = string(f) end ### Bond ### # Default implementation to be overrided for specific types and fields in order to provide custom Bond function fieldbond(::Type, ::Val) @nospecialize return NotDefined() end ### HTML ### # Default implementation to be overrided for specific types and fields in order to provide custom Bond function fieldhtml(::Type, ::Val) @nospecialize return NotDefined() end ## Struct Functions ## ### Description ### # Override the description of a Type typedescription(T::Type) = string(Base.nameof(T)) ### Bond ### # This function has to be overwritten if a custom show method for a Type is # intended when the type is shown as a filed of a BondTable typeasfield(T::Type) = NotDefined() # Basic function that is called for extracting the bond for a given field of a struct function fieldbond(s::Type, f::Symbol) @nospecialize @assert hasfield(s, f) "The structure $s has no field $f" Mod = @__MODULE__ # We check if the structure has a specific method for the field out = fieldbond(s, Val(f)) out isa NotDefined || return out # If we reach this point it means that no custom method was defined for the bond value of this field # We try to see if the type has a custom implementation when shown as field ft = fieldtype(s,f) out = typeasfield(ft) out isa NotDefined && error("`$(Mod).fieldbond` has no custom method for field ($f::$ft) of type $s and `$(Mod).typeasfield` has no custom method for type $ft.\n Please add one or the other using `@fieldsbond` or `@typeasfield`") return out end ### HTML ### # This function will be called for extracting the HTML for displaying a given field of a Type inside a BondTable # It defaults to just creating a description from `fielddescription` and a bond from `fieldbond` function fieldhtml(s::Type, f::Symbol) @nospecialize @assert hasfield(s, f) "The structure $s has no field $f" # We check if the structure has a specific method for the field out = fieldhtml(s, Val(f)) out isa NotDefined || return out # Now we try with the docstring of the field out = wrapped() do Child @htl(""" <field-html class='$f'> <field-description class='$f' title="This value is associated to field `$f`">$(fielddescription(s, f))</field-description> <field-bond class='$f'>$(Child(fieldbond(s, f)))</field-bond> </field-html> <style> field-html { display: grid; grid-template-columns: 1fr minmax(min(50px, 100%), .4fr); grid-auto-rows: fit-content(40px); justify-items: center; //padding: 2px 5px 10px 0px; align-items: center; row-gap: 5px; } field-bond { display: flex; } field-bond input { width: 100%; } field-description { text-align: center; } </style> """) end return out end function typehtml(T::Type) inner_bond = combine() do Child @htl """ $([ Child(string(name), fieldhtml(T, name)) for name in fieldnames(T) if !Base.isgensym(name) ]) """ end ToggleReactiveBond(wrapped() do Child @htl(""" $(Child(inner_bond)) <script> const trc = currentScript.closest('togglereactive-container') const header = trc.firstElementChild const desc = header.querySelector('.description') desc.setAttribute('title', "This generates a struct of type `$(nameof(T))`") // add the collapse button const collapse_btn = html`<span class='collapse'>` header.insertAdjacentElement('afterbegin', collapse_btn) trc.collapse = () => { trc.classList.toggle('collapsed') } collapse_btn.onclick = (e) => trc.collapse() </script> <style> togglereactive-container field-html { display: contents; } togglereactive-container { display: grid; grid-template-columns: 1fr minmax(min(50px, 100%), .4fr); grid-auto-rows: fit-content(40px); justify-items: center; align-items: center; row-gap: 5px; /* The flex below is needed in some weird cases where the bond is display flex and the child becomes small. */ flex: 1; } togglereactive-header { grid-column: 1 / -1; display: flex; } togglereactive-header > .collapse { --size: 17px; display: block; align-self: stretch; background-size: var(--size) var(--size); background-repeat: no-repeat; background-position: center; width: var(--size); filter: var(--image-filters); background-image: url(https://cdn.jsdelivr.net/gh/ionic-team/[email protected]/src/svg/chevron-down.svg); cursor: pointer; } togglereactive-container.collapsed > togglereactive-header > .collapse { background-image: url(https://cdn.jsdelivr.net/gh/ionic-team/[email protected]/src/svg/chevron-forward.svg); } togglereactive-header { display: flex; align-items: stretch; width: 100%; } togglereactive-header > .description { text-align: center; flex-grow: 1; font-size: 18px; font-weight: 600; } togglereactive-header > .toggle { align-self: center } togglereactive-container.collapsed togglereactive-header + * { display: none !important; } </style> """) end; description = typedescription(T)) end ### Constructor ### typeconstructor(T::Type) = f(args) = T(;args...) typeconstructor(::Type{<:NamedTuple}) = identity
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
12622
# Helper Functions # # Generic function for the convenience macros to add methods for the field functions function _add_generic_field(s, block, fnames) if !Meta.isexpr(block, [:block, :let]) error("The second argument to the `@fieldbond` macro has to be a begin or let block") end Mod = @__MODULE__ # We create the output block out = Expr(:block) for ex in block.args ex isa Expr || continue # We skip linenumbernodes Meta.isexpr(ex, :(=)) || error("Only expression of the type `fieldname = value` are allowed in the second argument block") symbol, value = ex.args symbol isa Symbol || error("The fieldname has to be provided as a symbol ($symbol was given instead)") symbol = Meta.quot(symbol) # Push the check of field name expression push!(out.args, esc(:(hasfield($s, $symbol) || error("The provided symbol name $($symbol) does not exist in the structure $($s)")))) # If the value is not already a tuple or vect or expressions, we wrap it in a tuple values = Meta.isexpr(value, [:vect, :tuple]) ? value.args : (value,) for (fname,val) in zip(reverse(fnames), reverse(values)) # Push the expression to overload the method push!(out.args, esc(:($Mod.$fname(::Type{$s}, ::Val{$symbol}) = $val))) end end out end # Generic function for the convenience macros to add methods for the type functions function _add_generic_type(block, fname) if !Meta.isexpr(block, [:block, :let]) error("The second argument to the `@fieldtype` macro has to be a begin or let block") end Mod = @__MODULE__ # We create the output block out = Expr(:block) for ex in block.args ex isa Expr || continue # We skip linenumbernodes Meta.isexpr(ex, :(=)) || error("Only expression of the type `Type = value` are allowed in the argument block") typename, value = ex.args typename isa Symbol || error("The typename has to be provided as a symbol ($typename was given instead)") # Push the expression to overload the method push!(out.args, esc(:($Mod.$fname(::Type{$typename}) = $value))) end out end # @fieldbond # """ @fieldbond typename block Convenience macro to define custom widgets for each field of `typename`. This is mostly inteded to be used in combintation with [`StructBond`](@ref). Given for example the following structure ``` Base.@kwdef struct ASD a::Int b::Int c::String end ``` one can create a nice widget to create instances of type `ASD` wih the following code: ``` @fieldbond ASD begin a = Slider(1:10) b = Scrubbable(1:10) c = TextField() end @fielddescription ASD begin a = md"Magical field with markdown description" b = @htl "<span>Field with HTML description</span>" c = "Normal String Description" end @bind asd StructBond(ASD) ``` where `asd` will be an instance of type `ASD` with each field interactively controllable by the specified widgets and showing the field description next to each widget. See also: [`BondTable`](@ref), [`StructBond`](@ref), [`Popout`](@ref), [`popoutwrap`](@ref), [`@fielddescription`](@ref), [`@fieldhtml`](@ref), [`@typeasfield`](@ref), [`@popoutasfield`](@ref) """ macro fieldbond(s, block) _add_generic_field(s, block, [:fieldbond]) end # @fielddescription # """ @fielddescription typename block Convenience macro to define custom descriptions for the widgets of each field of `typename`. This is mostly inteded to be used in combintation with [`StructBond`](@ref). Given for example the following structure ``` Base.@kwdef struct ASD a::Int b::Int c::String end ``` one can create a nice widget to create instances of type `ASD` wih the following code: ``` @fieldbond ASD begin a = Slider(1:10) b = Scrubbable(1:10) c = TextField() end @fielddescription ASD begin a = md"Magical field with markdown description" b = @htl "<span>Field with HTML description</span>" c = "Normal String Description" end @bind asd StructBond(ASD) ``` where `asd` will be an instance of type `ASD` with each field interactively controllable by the specified widgets and showing the field description next to each widget. See also: [`BondTable`](@ref), [`StructBond`](@ref), [`Popout`](@ref), [`popoutwrap`](@ref), [`@fieldbond`](@ref), [`@fieldhtml`](@ref), [`@typeasfield`](@ref), [`@popoutasfield`](@ref) """ macro fielddescription(s, block) _add_generic_field(s, block, [:fielddescription]) end # @fieldhtml # macro fieldhtml(s, block) _add_generic_field(s, block, [:fieldhtml]) end # @typeasfield # """ @typeasfield T = Widget @typeasfield begin T1 = Widget1 T2 = Widget2 ... end Macro to give a default widget for a specific type `T`, `T1`, or `T2`. This can be over-ridden by specifying a more specific default for a custom type using [`@fieldbond`](@ref) When a custom type is wrapped inside a [`StructBond`](@ref) and a custom widget for one of its field is not defined, the show method will use the one defined by this macro for the field type. # Examples The following julia code will error because a default widget is not defined for field `a` ``` using PlutoExtras.StructBondModule struct ASD a::Int end StructBond(ASD) ``` Apart from defining a specific value for `ASD` with [`@fieldbond`](@ref), one can also define a default widget for Int with: ```julia @typeasfield Int = Slider(1:10) ``` Now calling `StructBond(ASD)` will not error and will default to showing a `Slider(1:10)` as bond for field `a` of `ASD`. """ macro typeasfield(block) if Meta.isexpr(block, :(=)) block = Expr(:block, block) end _add_generic_type(block, :typeasfield) end # @popoutasfield # """ @popoutasfield T @popoutasfield T1 T2 ... This macro will make the default widget for fields of type `T` a [`Popout`](@ref) wrapping a `StructBond{T}` type. For this to work, the `StructBond{T}` must have a default widget associated to each of its field, either by using [`@fieldbond`](@ref) or [`@typeasfield`](@ref) # Example (in Pluto) ```julia # ╔═╡ 8db82e94-5c81-4c52-9228-7e22395fb68f using PlutoExtras.StructBondModule # ╔═╡ 86a80228-f495-43e8-b1d4-c93b7b52c8d8 begin @kwdef struct MAH a::Int end @kwdef struct BOH mah::MAH end # This will make the default widget for an Int a Slider @typeasfield Int = Slider(1:10) # This will make the default widget for fields of type ASD a popout that wraps a StructBond{ASD} @popoutasfield MAH @bind boh StructBond(BOH) end # ╔═╡ 2358f686-1950-40f9-9d5c-dac2d98f4c24 boh === BOH(MAH(1)) ``` """ macro popoutasfield(args...) block = Expr(:block) for arg in args arg isa Symbol || error("The types to show as popups have to be given as symbols") push!(block.args, :($arg = $(popoutwrap)($arg))) end _add_generic_type(block, :typeasfield) end # @fielddata # """ @fielddata typename block Convenience macro to define custom widgets for each field of `typename`. This is mostly inteded to be used in combintation with [`StructBond`](@ref). Given for example the following structure `ASD`, one can create a nice widget to create instances of type `ASD` wih the following code: ``` begin Base.@kwdef struct ASD a::Int b::Int c::String d::String end @fielddata ASD begin a = (md"Magical field with markdown description", Slider(1:10)) b = (@htl("<span>Field with HTML description</span>"), Scrubbable(1:10)) c = ("Normal String Description", TextField()) d = TextField() end @bind asd StructBond(ASD) end ``` where `asd` will be an instance of type `ASD` with each field interactively controllable by the specified widgets and showing the field description next to each widget. The rightside argument of each `:(=)` in the `block` can either be a single element or a tuple of 2 elements. In case a single elemnent is provided, the provided value is interpreted as the `fieldbond`, so the bond/widget to show for that field. If two elements are given, the first is assigned to the description and the second as the bond to show See also: [`BondTable`](@ref), [`StructBond`](@ref), [`@NTBond`](@ref), [`Popout`](@ref), [`popoutwrap`](@ref), [`@fieldbond`](@ref), [`@fielddescription`](@ref), [`@fieldhtml`](@ref), [`@typeasfield`](@ref), [`@popoutasfield`](@ref) """ macro fielddata(s, block) _add_generic_field(s, block, [:fielddescription, :fieldbond]) end # @NTBond # """ @NTBond description block Convenience macro to create a [`StructBond`](@ref) wrapping a NamedTuple with field names provided in the second argument `block`. Useful when one wants a quick way of generating a bond that creates a NamedTuple. An example usage is given in the code below: ``` @bind nt @NTBond "My Fancy NTuple" begin a = ("Description", Slider(1:10)) b = (md"*Bold* field", Slider(1:10)) c = Slider(1:10) # No description, defaults to the name of the field end ``` which will create a `NamedTuple{(:a, :b, :c)}` and assign it to variable `nt`. See also: [`BondTable`](@ref), [`@NTBond`](@ref), [`@BondsList`](@ref), [`Popout`](@ref), [`popoutwrap`](@ref), [`@fielddata`](@ref), [`@fieldhtml`](@ref), [`@typeasfield`](@ref), [`@popoutasfield`](@ref) """ macro NTBond(desc, block) Meta.isexpr(block, [:let, :block]) || error("You can only give `let` or `begin` blocks to the `@NTBond` macro") # We will return a let block at the end anyhow to avoid method redefinitino errors in Pluto. We already create the two blocks composing the let bindings, block = if block.head == :let block.args else # This is a normal begin-end so we create an empty bindings block Expr(:block), block end # We escape all the arguments in the bindings for i in eachindex(bindings.args) bindings.args[i] = esc(bindings.args[i]) end fields = Symbol[gensym()] # This will make this unique even when defining multiple times with the same set of parameters # now we just and find all the symbols defined in the block for arg in block.args arg isa LineNumberNode && continue Meta.isexpr(arg, :(=)) || error("Only expression of type `fieldname = fieldbond` or `fieldname = (fielddescription, fieldbond)` can be provided inside the block fed to @NTBond") push!(fields, arg.args[1]) end Mod = @__MODULE__ T = NamedTuple{Tuple(fields)} out = _add_generic_field(T, block, [:fielddescription, :fieldbond]) # We add the generation of the StructBond push!(out.args, :($(StructBond)($T;description = $desc))) Expr(:let, bindings, out) end # BondsList # """ @BondsList description block Convenience macro to create a `BondsList`, which is a grouping of a various bonds (created with `@bind`) inside a table-like HTML output that can be used inside [`BondTable`](@ref). Each bond can additionally be associated to a custom description. The `block` given as second input to this macro must be a `begin` or `let` block where each line is an assignment of the type `description = bond`. The description can be anything that has a `show` method for MIME type `text/html`. An example usage is given in the code below: ``` @BondsList "My Group of Bonds" let tv = PlutoUI.Experimental.transformed_value # We use transformed_value to translate GHz to Hz in the bound variable `freq` "Frequency [GHz]" = @bind freq tv(x -> x * 1e9, Slider(1:10)) md"Altitude ``h`` [m]" = @bind alt Scrubbable(100:10:200) end ``` which will create a table-like display grouping together the bonds for the frequency `freq` and the altitude `alt`. Unlike [`StructBond`](@ref), the output of `@BondsList` is not supposed to be bound using `@bind`, as it just groups pre-existing bonds. Also unlike `StructBond`, each row of a `BondsList` upates its corresponding bond independently from the other rows. To help identify and differentiate a `BondsList` from a `StructBond` See also: [`BondTable`](@ref), [`@NTBond`](@ref), [`StructBond`](@ref), [`Popout`](@ref), [`popoutwrap`](@ref), [`@fielddata`](@ref), [`@fieldhtml`](@ref), [`@typeasfield`](@ref), [`@popoutasfield`](@ref) """ macro BondsList(description, block) Meta.isexpr(block, [:block, :let]) || error("Only `let` or `begin` blocks are supported as second argument to the `@BondsList` macro") bindings, block = if block.head == :let block.args else # This is a normal begin-end so we create an empty bindings block Expr(:block), block end # We escape all the arguments in the bindings for i in eachindex(bindings.args) bindings.args[i] = esc(bindings.args[i]) end vec = Expr(:vect) for arg in block.args arg isa LineNumberNode && continue Meta.isexpr(arg, :(=)) || error("Only entries of the type `description = bond` are supported as arguments to the input block of `@BondsList`") desc, bond = arg.args push!(vec.args, esc(:($(BondWithDescription)($desc, $bond)))) end out = quote vec = $vec $BondsList($(esc(description)), vec) end Expr(:let, bindings, out) end
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
16435
# StructBond Definition # """ StructBond(T;description = typedescription(T)) Create an HTML widget to be used with `@bind` from Pluto that allows to define the custom type `T` by assigning a widget to each of its fields. The widget will automatically use the docstring of each field as its description if present, or the fieldname otherwise. When used with `@bind`, it automatically generates a instance of `T` by using the various fields as keyword arguments. *This means that the the structure `T` has to support a keyword-only contruction, such as those generated with `Base.@kwdef` or `Parameters.@with_kw`. In order to work, the widget (and optionally the description) to associate to eachfield of type `T` has to be provided using the convenience macro `@fielddata`. The optional `description` kwarg default to the Type name but can be overridden with anything showable as `MIME"text/html"` See also: [`BondTable`](@ref), [`@NTBond`](@ref), [`@BondsList`](@ref), [`Popout`](@ref), [`popoutwrap`](@ref), [`@fielddata`](@ref), [`@fieldhtml`](@ref), [`@typeasfield`](@ref), [`@popoutasfield`](@ref) """ Base.@kwdef struct StructBond{T} widget::Any description::Any secret_key::String=String(rand('a':'z', 10)) end StructBond(::Type{T}; description = typedescription(T)) where T = StructBond{T}(;widget = typehtml(T), description) ## structbondtype ## structbondtype(::StructBond{T}) where T = T structbondtype(::Type{StructBond{T}}) where T = T ## Show - StructBond ## # This does not seem used, leaving here for the moment _basics_script = ScriptContent(""" const parent = currentScript.parentElement const widget = currentScript.previousElementSibling // Overwrite the description const desc = widget.querySelector('.description') desc.innerHTML = // Set-Get bond const set_input_value = setBoundElementValueLikePluto const get_input_value = getBoundElementValueLikePluto Object.defineProperty(parent, 'value', { get: () => get_input_value(widget), set: (newval) => { set_input_value(widget, newval) }, configurable: true, }); const old_oninput = widget.oninput ?? function(e) {} widget.oninput = (e) => { old_oninput(e) e.stopPropagation() parent.dispatchEvent(new CustomEvent('input')) } """) # Basic script part used for the show method _show(t::StructBond{T}) where T = @htl(""" <struct-bond class='$T'> $(t.widget) <script id = $(t.secret_key)> const parent = currentScript.parentElement const widget = currentScript.previousElementSibling // Overwrite the description const desc = widget.querySelector('.description') desc.innerHTML = $(t.description) // Set-Get bond const set_input_value = setBoundElementValueLikePluto const get_input_value = getBoundElementValueLikePluto Object.defineProperty(parent, 'value', { get: () => get_input_value(widget), set: (newval) => { set_input_value(widget, newval) }, configurable: true, }); const old_oninput = widget.oninput ?? function(e) {} widget.oninput = (e) => { old_oninput(e) e.stopPropagation() parent.dispatchEvent(new CustomEvent('input')) } </script> <style> /* The flex below is needed in some weird cases where the bond is display flex and the child becomes small. */ struct-bond { flex: 1; } </style> </struct-bond> """) Base.show(io::IO, mime::MIME"text/html", t::StructBond) = show(io, mime, _show(t)) # Create methods for AbstractPlutoDingetjes.Bonds function Bonds.initial_value(t::StructBond{T}) where T transformed = Bonds.initial_value(t.widget) typeconstructor(T)(transformed) end # We have to parse the received array and collect reinterpretarrays as they are # likely the cause of the weird error in Issue #31 collect_reinterpret!(@nospecialize(x)) = x function collect_reinterpret!(x::AbstractArray) for i in eachindex(x) el = x[i] if el isa Base.ReinterpretArray x[i] = collect(el) elseif el isa AbstractArray # We do recursive processing collect_reinterpret!(el) end end return x end function Bonds.transform_value(t::StructBond{T}, from_js) where T # We remove reinterpreted_arrays (See Issue #31) transformed = Bonds.transform_value(t.widget, collect_reinterpret!(from_js)) typeconstructor(T)(transformed) end # BondWithDescription # struct BondWithDescription description bond function BondWithDescription(description, bond) _isvalid(BondWithDescription, bond) || error("It looks like the `bond` provided to `BondWithDescription` is not of the correct type, provide the bond given as output by the `Pluto.@bind` macro") new(description, bond) end end _isvalid(::Type{BondWithDescription}, value::T) where T = nameof(T) == :Bond && fieldnames(T) == (:element, :defines, :unique_id) _getbond(x::T) where T = let if nameof(T) == :Bond && fieldnames(T) == (:element, :defines, :unique_id) return x else error("The provided input is not a bond or does not seem to wrap a bond") end end ## Show - BondWithDescription ## Base.show(io::IO, mime::MIME"text/html", bd::BondWithDescription) = show(io, mime, @htl(""" <bond-with-description> <bond-description title=$(join(["This bond is assigned to variable `", String(_getbond(bd.bond).defines), "`"]))> $(bd.description) </bond-description> <bond-value> $(bd.bond) </bond-value> <style> $(CSS_Sheets.bondwithdescription) </style> </bond-with-description> """)) # Bonds List # Base.@kwdef struct BondsList description bonds::Vector{BondWithDescription} secret_key::String=String(rand('a':'z', 10)) end BondsList(description, bonds) = BondsList(;description, bonds) ## Show - BondsList ## Base.show(io::IO, mime::MIME"text/html", bl::BondsList) = show(io, mime, @htl(""" <bondslist-container class='no-popout'> <bondslist-header> <span class='collapse bondslist-icon'></span> <span class='description' title="This list contains independent bonds">$(bl.description)</span> <span class='toggle bondslist-icon'></span> </bondslist-header> <bondslist-contents> $(bl.bonds) </bondslist-contents> <script id=$(bl.secret_key)> const container = currentScript.parentElement container.collapse = (force) => { container.classList.toggle('collapsed', force) } const collapse_btn = container.querySelector('span.collapse') collapse_btn.onclick = (e) => container.collapse() </script> <style> $(CSS_Sheets.bondslist) </style> </bondslist-container> """)) # Popout # """ Popout(T) Create an HTML widget wrapping the widget `T` and showing it either on hover or upon click. This is useful to generat widgets to be used with [`StructBond`](@ref) for custom fields whose types are custom Types. The convenience function [`popoutwrap`](@ref) can be used to directly create a `Popup` of a `StructBond{T}` to facilitate nested `StructBond` views. See also: [`BondTable`](@ref), [`StructBond`](@ref), [`popoutwrap`](@ref), [`@fieldbond`](@ref), [`@fielddescription`](@ref), [`@fieldhtml`](@ref), [`@typeasfield`](@ref), [`@popoutasfield`](@ref) """ Base.@kwdef struct Popout{T} element::T secret_key::String=String(rand('a':'z', 10)) end Popout(element::T) where T = Popout{T}(;element) # Create methods for AbstractPlutoDingetjes.Bonds function Bonds.initial_value(t::Popout{T}) where T transformed = Bonds.initial_value(t.element) end function Bonds.transform_value(t::Popout{T}, from_js) where T transformed = Bonds.transform_value(t.element, from_js |> first) end """ popoutwrap(T) Convenience function to construct a `Popout` wrapping a `StructBond` of type `T`. This is convenient when one wants to create nested `StructBond` types. Given for example the following two structures ``` Base.@kwdef struct ASD a::Int b::Int c::String end Base.@kwdef struct LOL asd::ASD text::String end ``` one can create a nice widget to create instances of type `LOL` that also include a popout of widget generating `ASD` wih the following code: ``` # Define the widget for ASD @fieldbond ASD begin a = Slider(1:10) b = Scrubbable(1:10) c = TextField() end @fielddescription ASD begin a = md"Magical field with markdown description" b = @htl "<span>Field with HTML description</span>" c = "Normal String Description" end # Define the widget for LOL @fieldbond LOL begin asd = popoutwrap(ASD) text = TextField(;default = "Some Text") end @fielddescription LOL begin asd = "Click on the icon to show the widget to generate this field" text = "Boring Description" end @bind lol StructBond(LOL) ``` where `lol` will be an instance of type `LOL` with each field interactively controllable by the specified widgets and showing the field description next to each widget. See also: [`BondTable`](@ref), [`StructBond`](@ref), [`Popout`](@ref), [`@fieldbond`](@ref), [`@fielddescription`](@ref), [`@fieldhtml`](@ref), [`@typeasfield`](@ref), [`@popoutasfield`](@ref) """ popoutwrap(T::Type) = Popout(StructBond(T)) popoutwrap(t::Union{StructBond, BondsList}) = Popout(t) ## Interact.js - Popout ## popup_interaction_handler = ScriptContent(""" // We use the interactjs library to provide drag and resize handling across devices const { default: interact } = await import('https://esm.sh/interactjs') contents.offset = contents.offset ?? { x: 0, y: 0} const startPosition = {x: 0, y: 0} interact(contents.querySelector('togglereactive-header .description, bondslist-header .description')).draggable({ listeners: { start (event) { contents.offset.y = startPosition.y = contents.offsetTop contents.offset.x = startPosition.x = contents.offsetLeft }, move (event) { contents.offset.x += event.dx contents.offset.y += event.dy contents.style.top = `min(95vh, \${contents.offset.y}px` contents.style.left = `min(95vw, \${contents.offset.x}px` }, } }).on('doubletap', function (event) { // Double-tap on header reset the position container.popout() }) interact(contents) .resizable({ edges: { top: true, left: false, bottom: true, right: true }, listeners: { move: function (event) { Object.assign(event.target.style, { width: `\${event.rect.width}px`, height: `\${event.rect.height}px`, }) } } }).on('doubletap', function (event) { // Double-tap on resize reset the width contents.style.width = '' contents.style.height = '' }) """) ## Show - Popout ## _show_popout(p::Popout) = wrapped() do Child @htl(""" <popout-container key='$(p.secret_key)'> <popout-header><span class='popout-icon popout'></span></popout-header> <popout-contents>$(Child(p.element))</popout-contents> </popout-container> <script id='$(p.secret_key)'> // Load the floating-ui and interact libraries window.floating_ui = await import('https://esm.sh/@floating-ui/dom') const { computePosition, autoPlacement } = floating_ui const container = currentScript.previousElementSibling const header = container.firstElementChild const contents = container.lastElementChild // Load the interactjs part $popup_interaction_handler function positionContents() { computePosition(header, contents, { strategy: "fixed", middleware: [autoPlacement()], }).then((pos) => { contents.style.left = pos.x + "px" contents.style.top = pos.y + "px" }) } container.popout = (force = undefined) => { container.classList.toggle('popped', force) positionContents() } header.onclick = (e) => {container.popout()} contents.onmouseenter = (e) => container.classList.toggle('contents-hover', true) contents.onmouseleave = (e) => container.classList.toggle('contents-hover', false) header.onmouseenter = (e) => { container.classList.toggle('header-hover', true) container.classList.contains('popped') ? null : positionContents() } header.onmouseleave = (e) => container.classList.toggle('header-hover', false) </script> <style> $(CSS_Sheets.popout) </style> """) end # Base.show method Base.show(io::IO, mime::MIME"text/html", p::Popout) = show(io, mime, _show_popout(p)) ## Methods for other structs _isvalid(T::Type{BondWithDescription}, p::Popout) = _isvalid(T, p.element) _getbond(x::Popout) = _getbond(x.element) # BondTable # """ BondTable(bondarray; description) Take as input an array of bonds and creates a floating table that show all the bonds in the input array. If `description` is not provided, it defaults to the text *BondTable*. Description can be either a string or a HTML output. See also: [`StructBond`](@ref), [`Popout`](@ref), [`popoutwrap`](@ref), [`@fieldbond`](@ref), [`@fielddescription`](@ref), [`@fieldhtml`](@ref), [`@typeasfield`](@ref), [`@popoutasfield`](@ref) """ Base.@kwdef struct BondTable bonds::Array description::Any secret_key::String function BondTable(v::Array; description = NotDefined(), secret_key = String(rand('a':'z', 10))) for el in v T = typeof(el) valid = el isa BondsList || nameof(T) == :Bond && hasfield(T, :element) && hasfield(T, :defines) valid || error("All the elements provided as input to a `BondTable` have to be bonds themselves (i.e. created with the `@bind` macro from Pluto)") end new(v, description, secret_key) end end ## Interact.js - BondTable ## bondtable_interaction_handler = ScriptContent(""" // We use the interactjs library to provide drag and resize handling across devices const { default: interact } = await import('https://esm.sh/interactjs') container.offset = container.offset ?? { x: 0, y: 0} const startPosition = {x: 0, y: 0} interact(container.querySelector('bondtable-header .description')).draggable({ listeners: { start (event) { container.offset.y = startPosition.y = container.offsetTop container.offset.x = startPosition.x = container.offsetLeft }, move (event) { container.offset.x += event.dx container.offset.y += event.dy container.style.top = `min(95vh, \${container.offset.y}px` container.style.left = `min(95vw, \${container.offset.x}px` }, } }).on('doubletap', function (event) { // Double-tap on header reset the position container.style.top = '' container.style.left = '' }) interact(container) .resizable({ ignoreFrom: 'popout-container', edges: { top: true, left: false, bottom: true, right: true }, listeners: { move: function (event) { Object.assign(event.target.style, { width: `\${event.rect.width}px`, height: `\${event.rect.height}px`, maxHeight: 'none', }) } } }).on('doubletap', function (event) { // Double-tap on resize reset the width container.style.width = '' container.style.height = '' container.style.maxHeight = '' }) """) ## CSS - BondTable ## bondtable_style = @htl """ <style> $(CSS_Sheets.bondtable) </style> """; ## Show - BondTable ## function show_bondtable(b::BondTable; description = b.description) desc = description isa NotDefined ? "BondTable" : description @htl(""" <bondtable-container key='$(b.secret_key)'> <bondtable-header> <span class='table-help icon'></span> <span class='description'>$desc</span> <span class='table-collapse icon'></span> </bondtable-header> <bondtable-contents> $(b.bonds) </bondtable-contents> </bondtable-container> <script id='$(b.secret_key)'> const container = currentScript.previousElementSibling const header = container.firstElementChild const contents = container.lastElementChild const cell = container.closest('pluto-cell') const help_btn = header.firstElementChild const collapse_btn = header.lastElementChild container.collapse = (force) => { container.classList.toggle('collapsed', force) } collapse_btn.onclick = e => container.collapse() // Load the interact script $bondtable_interaction_handler // Now we assign a specific class to all toggle-container that are direct children for (const tr of contents.querySelectorAll('togglereactive-container')) { tr.closest('popout-container') ?? tr.classList.toggle('no-popout', true) } // We also flag the first togglereactive-container in the table contents.firstElementChild.querySelector('togglereactive-container.no-popout')?.classList.toggle('first',true) // Click to go to definition container.jumpToCell = () => { cell.scrollIntoView() } help_btn.onclick = container.jumpToCell </script> $bondtable_style """) end Base.show(io::IO, mime::MIME"text/html", b::BondTable) = show(io, mime, show_bondtable(b))
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
2128
# Struct # Base.@kwdef struct ToggleReactiveBond element::Any description::String secret_key::String=String(rand('a':'z', 10)) end ToggleReactiveBond(element; description = "") = ToggleReactiveBond(;element, description) # AbstractPlutoDingetjes Methods # function Bonds.initial_value(r::ToggleReactiveBond) Bonds.initial_value(r.element) end function Bonds.validate_value(r::ToggleReactiveBond, from_js) Bonds.validate_value(r.element, from_js) end function Bonds.transform_value(r::ToggleReactiveBond, from_js) Bonds.transform_value(r.element, from_js) end function Bonds.possible_values(r::ToggleReactiveBond) Bonds.possible_values(r.element) end # Show Method # Base.show(io::IO, mime::MIME"text/html", r::ToggleReactiveBond) = show(io, mime, @htl(""" <togglereactive-container> <togglereactive-header> <span class='description'>$(r.description)</span> <input type='checkbox' class='toggle' checked> </togglereactive-header> $(r.element) <script id=$(r.secret_key)> const parent = currentScript.parentElement const el = currentScript.previousElementSibling const toggle = parent.querySelector('togglereactive-header .toggle') const set_input_value = setBoundElementValueLikePluto const get_input_value = getBoundElementValueLikePluto // We use clone to avoid pointing to the same array let public_value = _.cloneDeep(get_input_value(el)) function dispatch() { public_value = _.cloneDeep(get_input_value(el)) parent.dispatchEvent(new CustomEvent('input')) } const old_oninput = el.oninput ?? function(e) {} el.oninput = (e) => { old_oninput(e) if (toggle.checked) {dispatch()} } toggle.oninput = e => { if (toggle.checked && !_.isEqual(get_input_value(el), public_value)) { dispatch() } e.stopPropagation() } Object.defineProperty(parent, 'value', { get: () => public_value, set: (newval) => { public_value = newval set_input_value(el, newval) toggle.checked = true }, configurable: true, }); </script> <style> $(CSS_Sheets.togglereactive) </style> </togglereactive-container> """))
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
2125
import Pluto: update_save_run!, update_run!, WorkspaceManager, ClientSession, ServerSession, Notebook, Cell, project_relative_path, SessionActions, load_notebook, Configuration, set_bond_values_reactive using PlutoExtras import PlutoExtras.AbstractPlutoDingetjes.Bonds using Test function noerror(cell; verbose=true) if cell.errored && verbose @show cell.output.body end !cell.errored end @testset "APD methods" begin ed = Editable(3) @test Base.get(ed) == 3 @test Bonds.initial_value(ed) == 3 @test Bonds.possible_values(ed) == Bonds.InfinitePossibilities() @test Bonds.possible_values(Editable(true)) == (true, false) @test Bonds.validate_value(ed, 5) === true @test Bonds.validate_value(ed, 3im) === false soe = StringOnEnter("asd") @test Base.get(soe) == "asd" @test Bonds.initial_value(soe) == "asd" @test Bonds.possible_values(soe) == Bonds.InfinitePossibilities() @test Bonds.validate_value(soe, 5) === false @test Bonds.validate_value(soe, "lol") === true end options = Configuration.from_flat_kwargs(; disable_writing_notebook_files=true, workspace_use_distributed_stdlib = true) srcdir = normpath(@__DIR__, "./notebooks") eval_in_nb(sn, expr) = WorkspaceManager.eval_fetch_in_workspace(sn, expr) function set_bond_value_sn(sn) (session, notebook) = sn function set_bond_value(name, value, is_first_value=false) notebook.bonds[name] = Dict("value" => value) set_bond_values_reactive(; session, notebook, bound_sym_names=[name], is_first_values=[is_first_value], run_async=false, ) end end @testset "Basic Widgets notebook" begin ss = ServerSession(; options) path = joinpath(srcdir, "basic_widgets.jl") nb = SessionActions.open(ss, path; run_async=false) sn = (ss, nb) set_bond_value = set_bond_value_sn(sn) for cell in nb.cells @test noerror(cell) end set_bond_value(:text, "asdasd") @test eval_in_nb(sn, :text) === "asdasd" set_bond_value(:num, 15) @test eval_in_nb(sn, :num) === 15 SessionActions.shutdown(ss, nb) end
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
20884
using Test using PlutoExtras.PlutoCombineHTL.WithTypes using PlutoExtras.PlutoCombineHTL: LOCAL_MODULE_URL using PlutoExtras.HypertextLiteral using PlutoExtras.PlutoCombineHTL: shouldskip, children, print_html, script_id, inner_node, plutodefault, haslisteners, is_inside_pluto, hasreturn, add_pluto_compat, hasinvalidation, displaylocation, returned_element, to_string, formatted_contents import PlutoExtras using PlutoExtras.PlutoCombineHTL.AbstractPlutoDingetjes.Display @testset "make_script" begin ds = make_script("test") @test make_script(ds) === ds @test ds isa DualScript @test inner_node(ds, InsidePluto()).body == inner_node(ds, OutsidePluto()).body @test ds.inside_pluto.body.content === "test" ds = make_script("lol"; id = "asdfasdf") @test script_id(ds, InsidePluto()) === "asdfasdf" @test script_id(ds, OutsidePluto()) === "asdfasdf" ds2 = make_script( make_script(:pluto; body = "lol", id = "asdfasdf"), make_script(:normal; body = "lol", id = "different"), ) @test ds.inside_pluto == ds2.inside_pluto @test ds.outside_pluto != ds2.outside_pluto @test shouldskip(ScriptContent()) === true @test ScriptContent(nothing) === missing @test ScriptContent(missing) === missing sc = ScriptContent("addScriptEventListeners('lol')") @test sc.addedEventListeners === true sc = ScriptContent("console.log('lol')") @test sc.addedEventListeners === false @test_logs (:warn, r"No <script> tag was found") make_script(;invalidation = @htl("lol")) @test_logs (:warn, r"More than one <script> tag was found") make_script(@htl(""" <script id='lol'>asd</script> <script class='asd'></script> """)) @test_logs (:warn, r"The provided input also contained contents outside") make_script(@htl(""" <script id='lol'>asd</script> magic """)) @test_throws "No closing </script>" make_script(@htl("<script>asd")) ds = make_script(;invalidation = @htl("lol")) @test shouldskip(ds, InsidePluto()) && shouldskip(ds, OutsidePluto()) # The script is empty because with `@htl` we only get the content between the first <script> tag. ds = make_script(;invalidation = "lol") @test shouldskip(ds, InsidePluto()) === false ds = make_script(;invalidation = @htl("<script>lol</script>")) @test !shouldskip(ds, InsidePluto()) @test shouldskip(ds, OutsidePluto()) @test shouldskip(ds.inside_pluto.body) @test ds.inside_pluto.invalidation.content === "lol" ps = PlutoScript("asd", "lol") @test PlutoScript(ps) === ps @test ps.body.content === "asd" @test ps.invalidation.content === "lol" @test shouldskip(ps, InsidePluto()) === false @test shouldskip(ps, OutsidePluto()) === true ns = NormalScript("lol") @test NormalScript(ns) === ns @test_throws "You can't construct" NormalScript(ps).body let ds = DualScript(ps) @test ds.inside_pluto === ps @test shouldskip(ds, OutsidePluto()) end let ds = DualScript(ns) @test ds.outside_pluto === ns @test shouldskip(ds, InsidePluto()) end cs = make_script([ "asd", "lol", ]) @test !(hasreturn(cs, InsidePluto()) || hasreturn(cs, OutsidePluto())) @test hasinvalidation(cs) === false @test add_pluto_compat(cs) === true @test cs isa CombinedScripts @test CombinedScripts(cs) === cs @test make_script(cs) === cs @test children(CombinedScripts(ds)) == children(make_script([ds])) @test isempty(children(make_script([PlutoScript("asd")]))) === false @test isempty(children(make_script([NormalScript("asd")]))) === false make_script(ShowWithPrintHTML(cs)) === cs @test_throws "only valid if `T <: Script`" make_script(ShowWithPrintHTML("asd")) # Now we test that constructing a CombinedScripts with a return in not the last script or more returns errors. ds1 = make_script(PlutoScript(;returned_element = "asd")) ds2 = make_script("asd") @test_throws "More than one return" make_script([ ds1, ds2, ds1, ]) ds3 = make_script(PlutoScript(;returned_element = "asd"), NormalScript(;returned_element = "boh")) cs = make_script([ ds2, ds3 ]; returned_element = "lol" ) @test returned_element(cs, InsidePluto()) === "lol" @test returned_element(cs, OutsidePluto()) === "lol" @test returned_element(ds3, InsidePluto()) === "asd" @test returned_element(ds3, OutsidePluto()) === "boh" cs = make_script([ PrintToScript(3) ]; returned_element = "asd") @test last(children(cs)).el isa DualScript @test make_script(:outside, ds2) === ds2.outside_pluto @test make_script(:Inside, ds2) === ds2.inside_pluto pts = PrintToScript(3) @test make_script(pts) === pts @test make_node(pts) isa CombinedScripts @test PrintToScript(pts) === pts @test_throws "You can't wrap" PrintToScript(PlutoNode("asd")) pts = PrintToScript("asd") @test pts.el isa DualScript end @testset "make_node" begin dn = make_node() @test dn isa DualNode @test shouldskip(dn, InsidePluto()) && shouldskip(dn, OutsidePluto()) s = make_script("asd") dn = make_node("asd") @test make_node(s) === s @test dn != s @test make_node(dn) === dn cn = make_node([ "asd", "", "lol" ]) @test cn isa CombinedNodes @test CombinedNodes(cn) === cn @test length(children(cn)) === 2 # We skipped the second empty element @test make_node(cn) === cn cn = CombinedNodes(dn) dn_test = cn.children[1].el @test dn_test == dn @test PlutoNode(dn.inside_pluto) === dn.inside_pluto @test PlutoNode(@htl("")).empty === true nn = NormalNode("lol") dn = DualNode(nn) @test inner_node(dn, OutsidePluto()) === nn @test shouldskip(dn, InsidePluto()) pn = PlutoNode("asd") dn = DualNode(pn) @test inner_node(dn, InsidePluto()) === pn @test shouldskip(dn, OutsidePluto()) @test shouldskip(dn, InsidePluto()) === false dn = DualNode("asd", "lol") @test inner_node(dn, InsidePluto()) == pn @test inner_node(dn, OutsidePluto()) == nn @test DualNode(dn) === dn function compare_content(n1, n2; pluto = missing) io1 = IOBuffer() io2 = IOBuffer() print_html(io1, n1; pluto = pluto === missing ? plutodefault(n1) : pluto) print_html(io2, n2; pluto = pluto === missing ? plutodefault(n2) : pluto) String(take!(io1)) == String(take!(io2)) end @test compare_content(make_node(HTML("asd")), make_node("asd")) @test compare_content(NormalNode("asd"), NormalNode(ShowWithPrintHTML("asd"))) @test compare_content(PlutoNode("asd"), NormalNode("asd")) @test compare_content(PlutoNode("asd"), NormalNode("asd"); pluto = true) === false @test compare_content(PlutoNode("asd"), NormalNode("asd"); pluto = false) === false function test_stripping(inp, expected) dn = make_node(inp) pn = inner_node(dn, InsidePluto()) io = IOBuffer() print_html(io, pn) s = String(take!(io)) s === expected end @test test_stripping("\n\n a\n\n"," a\n") # Only leading newlines (\r or \n) are removed @test test_stripping("\n\na \n\n","a\n") # Only leading newlines (\r or \n) are removed @test test_stripping(@htl("lol"), "lol\n") @test test_stripping(@htl(" lol "), " lol\n") # lol is right offset by 4 spaces @test isempty(children(make_node([PlutoNode("asd")]))) === false @test isempty(children(make_node([NormalNode("asd")]))) === false @test make_node(:pluto, "asd") === PlutoNode("asd") @test make_node(:outside; content = "lol") === NormalNode("lol") @test make_node(:both, "asd", "lol") === DualNode("asd", "lol") @test make_node(:both, "asd", "lol") === make_node("asd", "lol") end @testset "Other Helpers" begin @test shouldskip(3) === false s = make_html(PlutoScript()) @test s isa ShowWithPrintHTML @test make_html(s) === s for T in (HypertextLiteral.Render, HypertextLiteral.Bypass) @test shouldskip(T("lol")) === false @test shouldskip(T("")) === true end # We should not skip a script it is empty content but with an id @test shouldskip(PlutoScript(""), InsidePluto()) == true @test shouldskip(PlutoScript(""; id = "lol"), InsidePluto()) == false @test shouldskip(NormalScript(""; id = "lol"), OutsidePluto()) == false ds = DualScript(""; id = "lol") @test shouldskip(ds, InsidePluto()) == shouldskip(ds, OutsidePluto()) == false for l in (InsidePluto(), OutsidePluto()) @test haslisteners(make_script("asd"), l) === false end s = "addScriptEventListeners('lol')" @test haslisteners(make_script(s, "asd"), InsidePluto()) === true @test haslisteners(make_script(s, "asd"), OutsidePluto()) === false @test haslisteners(missing) === false @test_throws "can not identify a display location" displaylocation(:not_exist) @test hasreturn(make_script("asd","lol"), InsidePluto()) === false @test hasreturn(make_script("asd","lol"), OutsidePluto()) === false ds = make_script(PlutoScript(; returned_element = "asd"),"lol") @test shouldskip(ds.inside_pluto) === false @test hasreturn(ds, InsidePluto()) === true @test hasreturn(ds, OutsidePluto()) === false @test hasreturn(make_script(NormalScript(;returned_element = "lol")), OutsidePluto()) === true @test hasreturn(make_script(NormalScript(;returned_element = "lol")), InsidePluto()) === false cs = make_script([ "asd", "lol", ]) cn = make_node([ "asd", "lol", ]) # Test getproperty @test cs.children === children(cs) @test cn.children === children(cn) # We test the abstract type constructors @test Script(InsideAndOutsidePluto()) === DualScript @test Script(InsidePluto()) === PlutoScript @test Script(OutsidePluto()) === NormalScript @test Node(InsideAndOutsidePluto()) === DualNode @test Node(InsidePluto()) === PlutoNode @test Node(OutsidePluto()) === NormalNode ps = PlutoScript("asd") ns = NormalScript("asd") ds = make_script(ps,ns) @test DualScript("asd") == ds @test_throws "can't construct" PlutoScript(ns) @test_throws "can't construct" NormalScript(ps) @test PlutoScript(ds) === ps @test NormalScript(ds) === ns for D in (InsidePluto, OutsidePluto, InsideAndOutsidePluto) @test plutodefault(D) === plutodefault(D()) @test displaylocation(D()) === D() end io = IOBuffer() swp1 = ShowWithPrintHTML(make_node("asd"); display_type = :pluto) swp2 = ShowWithPrintHTML(make_node("asd"); display_type = :both) # :both is the default @test plutodefault(io, swp1) === plutodefault(swp1) @test plutodefault(io, swp2) === is_inside_pluto(io) !== plutodefault(swp1) @test displaylocation(PrintToScript(3)) === InsideAndOutsidePluto() @test displaylocation(PrintToScript(PlutoScript("asd"))) === InsidePluto() swph = ShowWithPrintHTML(3) @test PlutoCombineHTL._eltype(swph) === Int @test shouldskip(swph, InsidePluto()) === false swph = ShowWithPrintHTML(3; display_type = :outside) @test shouldskip(swph, InsidePluto()) === true @test add_pluto_compat(3) === false @test hasinvalidation(3) === false @test haslisteners(PrintToScript(3)) === false @test hasreturn(PrintToScript(3)) === false @test script_id(PlutoScript("asd"), OutsidePluto()) === missing pts = PrintToScript(3) @test script_id(pts) === missing @test_throws "You can't wrap object" ShowWithPrintHTML(PrintToScript(3)) end @testset "Show methods" begin ps = PlutoScript("asd", "lol") s = to_string(ps, MIME"text/javascript"()) hs = to_string(ps, MIME"text/html"()) @test contains(s, r"JS Listeners .* PlutoExtras") === false # No listeners helpers should be added @test contains(s, "invalidation.then(() => {\nlol") === true # Test that the invaliation script is printed @test contains(hs, r"<script id='\w+'") === true struct ASD end function PlutoCombineHTL.print_javascript(io::IO, ::ASD; pluto) if pluto println(io, "ASD_PLUTO") else println(io, "ASD_NONPLUTO") end end cs = make_script([ASD() |> PrintToScript]) s_in = to_string(cs, MIME"text/javascript"(); pluto = true) s_out = to_string(cs, MIME"text/javascript"(); pluto = false) @test contains(s_in, "ASD_PLUTO") @test contains(s_out, "ASD_NONPLUTO") struct LOL end function PlutoCombineHTL.print_javascript(io::IO, ::LOL; pluto) if pluto show(io, MIME"text/javascript"(), published_to_js(3)) println(io) else println(io, "LOL_NONPLUTO") end end # We test that the custom struct wrapped with PrintToScript is not also being printed as invalidaion cs = CombinedScripts([ PrintToScript(LOL()) PlutoScript("asd","lol") ]) s_in = to_string(cs, print_javascript; pluto = true) @test length(findall("published object on Pluto", s_in)) == 1 ds = DualScript("addScriptEventListeners('lol')", "magic"; id = "custom_id") s_in = to_string(ds, MIME"text/javascript"(); pluto = true) s_out = to_string(ds, MIME"text/javascript"(); pluto = false) @test contains(s_in, r"JS Listeners .* PlutoExtras") === true @test contains(s_out, r"JS Listeners .* PlutoExtras") === false # The listeners where only added in Pluto hs_in = to_string(ds, MIME"text/html"(); pluto = true) hs_out = to_string(ds, MIME"text/html"(); pluto = false) @test contains(hs_in, "<script id='custom_id'>") === true @test contains(hs_out, "<script id='custom_id'>") === true # Test error with print_script @test_throws "Interpolation of `Script` subtypes is not allowed" HypertextLiteral.print_script(IOBuffer(), ds) # Test error with show javascript ShowWithPrintHTML @test_throws "not supposed to be shown with mime 'text/javascript'" show(IOBuffer(), MIME"text/javascript"(), make_html("asd")) # Test error when trying to print invalidation of a NormalScript pts = PrintToScript(NormalScript("lol")) @test_throws "can't print invalidation" print_javascript(IOBuffer(), pts; pluto = false, kind = :invalidation) # Test that print_javascript goes to Base.show with mime text/javascript by default @test_throws r"matching show\(.*::Missing" print_javascript(IOBuffer(), missing) # Test that print_javascript goes to Base.show with mime text/javascript by default @test_throws r"matching show\(.*::Missing" print_html(IOBuffer(), missing) # Test that to_string only supports text/html and text/javascript @test_throws "Unsupported mime" to_string(1, MIME"text/plain"()) n = NormalNode("asd") # Test that interpolation of nodes in @htl works r = @htl("$n") s = to_string(r, MIME"text/html"(); pluto = false) @test contains(s, "asd") cn = make_node([n]) s = to_string(cn, MIME"text/html"(); pluto = false) @test contains(s, "asd") # Test that interpolation of ScriptContent inside @htl <script> tags work sc = ScriptContent("asd") r = @htl("<script>$([sc])</script>") s = to_string(r, MIME"text/html"()) @test contains(s, "<script>asd") # Show outside Pluto # PlutoScript should be empty when shown out of Pluto n = PlutoScript("asd") s_in = to_string(n, MIME"text/html"(); pluto = true) s_out = to_string(n, MIME"text/html"(); pluto = false) @test contains(s_in, "script id='") === true @test isempty(s_out) @test contains(string(formatted_code(n)), "```html\n<script id='") # ScriptContent should just show as repr outside of Pluto sc = ScriptContent("asd") s_in = formatted_code(sc; pluto = true) |> string s_out = formatted_code(sc; pluto = false) |> string @test contains(s_in, "```js\nasd\n") # This is language-js @test s_out === s_in # The pluto kwarg is ignored for script content when shown to text/html # DualScript n = DualScript("asd", "lol"; id = "asd") s_in = to_string(n, MIME"text/html"(); pluto = true) s_out = to_string(n, MIME"text/html"(); pluto = false) @test contains(s_in, "script id='asd'") === true @test contains(s_out, "script id='asd'") === true @test contains(string(formatted_code(n; pluto=true)), "```html\n<script id='asd'") @test add_pluto_compat(n) === true @test contains(s_out, LOCAL_MODULE_URL[]) @test contains(s_out, "async (currentScript) =>") # Opening async outside Pluto @test contains(s_out, "})(document.currentScript)") # Closing and calling async outside Pluto # Test when Pluto compat is false n = DualScript(n; add_pluto_compat = false) @test add_pluto_compat(n) === false s_out = to_string(n, MIME"text/html"(); pluto = false) @test contains(s_out, LOCAL_MODULE_URL[]) === false # Test the return n = DualScript(PlutoScript(;returned_element = "asd"), NormalScript(;returned_element = "lol")) s_in = to_string(n, MIME"text/html"(); pluto = true) s_out = to_string(n, MIME"text/html"(); pluto = false) @test contains(s_in, "return asd") @test contains(s_out, "currentScript.insertAdjacentElement('beforebegin', lol)") # NormalNode should be empty when shown out of Pluto n = NormalNode("asd") s_in = to_string(n, MIME"text/html"(); pluto = true) s_out = to_string(n, MIME"text/html"(); pluto = false) @test isempty(s_in) === true @test s_out === "asd\n" ds = DualScript("addScriptEventListeners(asd)", "lol"; id = "asd") # Forcing same id is necessary for equality for mime in (MIME"text/javascript"(), MIME"text/html"()) @test formatted_code(mime)(ds) == formatted_code(ds, mime) end @test formatted_contents()(ds) == formatted_code(ds; only_contents = true) mime = MIME"text/html"() for l in (InsidePluto(), OutsidePluto()) @test formatted_contents(l)(ds) != formatted_code(l; only_contents = false) end @test formatted_code(ds) == formatted_code(ds, MIME"text/html"()) sc = ScriptContent("asd") @test formatted_code(sc) == formatted_code(sc, MIME"text/javascript"()) s = let io = IOBuffer() show(io, MIME"text/html"(), sc) String(take!(io)) end @test contains(s, "<div class=\"markdown\"") s = let io = IOBuffer() n = NormalNode("lol") show(io, MIME"text/html"(), n) String(take!(io)) end @test contains(s, "lol") # We test PrintToScript and ShowWithPrintHTML with io accepting functions pts = PrintToScript((io; pluto, kwargs...) -> let # We wrap everything in an async call as we want to use await write(io, pluto ? "PLUTO" : "NONPLUTO") end) s_in = to_string(pts, print_javascript; pluto = true) s_out = to_string(pts, print_javascript; pluto = false) @test s_in === "PLUTO" @test s_out === "NONPLUTO" swph = ShowWithPrintHTML((io; pluto, kwargs...) -> let # We wrap everything in an async call as we want to use await write(io, pluto ? "PLUTO" : "NONPLUTO") end) s_in = to_string(swph, print_html; pluto = true) s_out = to_string(swph, print_html; pluto = false) @test s_in === "PLUTO" @test s_out === "NONPLUTO" # We test print_javascript for dicts d = Dict("asd" => "lol") s_in = to_string(d, print_javascript; pluto = true) s_out = to_string(d, print_javascript; pluto = false) @test contains(s_in, "published object on Pluto") @test s_out === """{"asd": "lol"}""" # We test print_javascript for vectors v = ["asd", "lol"] s_in = to_string(v, print_javascript; pluto = true) s_out = to_string(v, print_javascript; pluto = false) @test contains(s_in, "published object on Pluto") @test s_out === """["asd", "lol"]""" end # import Pluto: update_save_run!, update_run!, WorkspaceManager, ClientSession, # ServerSession, Notebook, Cell, project_relative_path, SessionActions, # load_notebook, Configuration # function noerror(cell; verbose=true) # if cell.errored && verbose # @show cell.output.body # end # !cell.errored # end # options = Configuration.from_flat_kwargs(; disable_writing_notebook_files=true, workspace_use_distributed_stdlib = true) # srcdir = normpath(@__DIR__, "./notebooks") # eval_in_nb(sn, expr) = WorkspaceManager.eval_fetch_in_workspace(sn, expr) # @testset "Script test notebook" begin # ss = ServerSession(; options) # path = joinpath(srcdir, "Script.jl") # nb = SessionActions.open(ss, path; run_async=false) # for cell in nb.cells # @test noerror(cell) # end # SessionActions.shutdown(ss, nb) # end
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
1288
import Pluto: update_save_run!, update_run!, WorkspaceManager, ClientSession, ServerSession, Notebook, Cell, project_relative_path, SessionActions, load_notebook, Configuration, set_bond_values_reactive using PlutoExtras function noerror(cell; verbose=true) if cell.errored && verbose @show cell.output.body end !cell.errored end options = Configuration.from_flat_kwargs(; disable_writing_notebook_files=true, workspace_use_distributed_stdlib = true) srcdir = normpath(@__DIR__, "./notebooks") eval_in_nb(sn, expr) = WorkspaceManager.eval_fetch_in_workspace(sn, expr) function set_bond_value_sn(sn) (session, notebook) = sn function set_bond_value(name, value, is_first_value=false) notebook.bonds[name] = Dict("value" => value) set_bond_values_reactive(; session, notebook, bound_sym_names=[name], is_first_values=[is_first_value], run_async=false, ) end end @testset "Latex Equations notebook" begin ss = ServerSession(; options) path = joinpath(srcdir, "latex_equations.jl") nb = SessionActions.open(ss, path; run_async=false) sn = (ss, nb) set_bond_value = set_bond_value_sn(sn) for cell in nb.cells @test noerror(cell) end SessionActions.shutdown(ss, nb) end
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
401
using SafeTestsets using Aqua using PlutoExtras Aqua.test_all(PlutoExtras) @safetestset "PlutoCombineHTL Module" begin include("combinehtl_module.jl") end @safetestset "Basic Widgets" begin include("basics.jl") end @safetestset "LaTeX Equations" begin include("latex.jl") end @safetestset "Extended Toc" begin include("toc.jl") end @safetestset "StructBond Module" begin include("structbond.jl") end
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
3969
import Pluto: update_save_run!, update_run!, WorkspaceManager, ClientSession, ServerSession, Notebook, Cell, project_relative_path, SessionActions, load_notebook, Configuration, set_bond_values_reactive using PlutoExtras using Markdown using PlutoExtras.StructBondModule using PlutoExtras.StructBondModule: structbondtype, popoutwrap, fieldbond, NotDefined, typeasfield, collect_reinterpret! import PlutoExtras.AbstractPlutoDingetjes.Bonds using Test @testset "APD methods and Coverage" begin tr = ToggleReactiveBond(Editable(3)) @testset "Toggle Reactive" begin @test Bonds.validate_value(tr, 3) === true @test Bonds.validate_value(tr, 3im) === false @test Bonds.transform_value(tr, 3) === 3 @test Bonds.possible_values(tr) === Bonds.InfinitePossibilities() end ntb = @NTBond "My Fancy NTuple" begin a = ("Description", Slider(1:10)) b = (md"**Bold** field", Slider(1:10)) c = Slider(1:10) # No description, defaults to the name of the field end nt = (;a=1,b=1,c=1) @testset "StructBond" begin @test structbondtype(ntb) <: NamedTuple @test structbondtype(typeof(ntb)) <: NamedTuple @test Bonds.transform_value(ntb, [[[1], [1], [1]]]) === nt @test fieldbond(structbondtype(ntb), Val(:a)) isa Slider @test fieldbond(structbondtype(ntb), Val(:asd)) isa NotDefined # Test custom field bonds struct ASD a::Int end # This is needed for local testing to reset the typeasfield to NotDefined StructBondModule.typeasfield(::Type{Int}) = NotDefined() @test_throws "no custom method" StructBond(ASD) @typeasfield Int = Slider(1:10) @test StructBond(ASD) isa StructBond struct BOH asd::ASD end # This is needed for local testing to reset the typeasfield to NotDefined StructBondModule.typeasfield(::Type{ASD}) = NotDefined() @test_throws "no custom method" StructBond(BOH) @popoutasfield ASD @test StructBond(BOH) isa StructBond @test typeasfield(ASD) isa Popout @test fieldbond(BOH, :asd) isa Popout end p = popoutwrap(ntb) @testset "Popout" begin @test Bonds.initial_value(p) === nt @test Bonds.transform_value(p, [[[[1], [1], [1]]]]) === nt end end function noerror(cell; verbose=true) if cell.errored && verbose @show cell.output.body end !cell.errored end @testset "collect_reinterpret!" begin @test collect_reinterpret!(3) === 3 re = collect(reinterpret(UInt8, [.5])) |> x -> reinterpret(Float64, x) arr = [ 0.2, [1.0], re, ] @test collect_reinterpret!(arr) == [ 0.2, [1.0], [0.5], ] end options = Configuration.from_flat_kwargs(; disable_writing_notebook_files=true, workspace_use_distributed_stdlib = true) srcdir = normpath(@__DIR__, "./notebooks") eval_in_nb(sn, expr) = WorkspaceManager.eval_fetch_in_workspace(sn, expr) function set_bond_value_sn(sn) (session, notebook) = sn function set_bond_value(name, value, is_first_value=false) notebook.bonds[name] = Dict("value" => value) set_bond_values_reactive(; session, notebook, bound_sym_names=[name], is_first_values=[is_first_value], run_async=false, ) end end @testset "Struct Bond notebook" begin ss = ServerSession(; options) path = joinpath(srcdir, "structbondmodule.jl") nb = SessionActions.open(ss, path; run_async=false) sn = (ss, nb) set_bond_value = set_bond_value_sn(sn) for cell in nb.cells @test noerror(cell) end @test eval_in_nb(sn, :nt) == (;a = 1, b = 1, c = 1) @test eval_in_nb(sn, :(asd == ASD(1,6,"","",20))) @test eval_in_nb(sn, :(boh == BOH(MAH(1)))) @test eval_in_nb(sn, :alt) == 150 @test eval_in_nb(sn, :freq) == 2e10 SessionActions.shutdown(ss, nb) end
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
833
import Pluto: update_save_run!, update_run!, WorkspaceManager, ClientSession, ServerSession, Notebook, Cell, project_relative_path, SessionActions, load_notebook, Configuration using PlutoExtras function noerror(cell; verbose=true) if cell.errored && verbose @show cell.output.body end !cell.errored end options = Configuration.from_flat_kwargs(; disable_writing_notebook_files=true, workspace_use_distributed_stdlib = true) srcdir = normpath(@__DIR__, "./notebooks") eval_in_nb(sn, expr) = WorkspaceManager.eval_fetch_in_workspace(sn, expr) @testset "ToC notebook" begin ss = ServerSession(; options) path = joinpath(srcdir, "extended_toc.jl") nb = SessionActions.open(ss, path; run_async=false) for cell in nb.cells @test noerror(cell) end SessionActions.shutdown(ss, nb) end
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
7102
### A Pluto.jl notebook ### # v0.19.29 using Markdown using InteractiveUtils # This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error). macro bind(def, element) quote local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end local el = $(esc(element)) global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el) el end end # ╔═╡ cfb4d354-e0b2-4a04-a559-4fb88df33954 using PlutoDevMacros # ╔═╡ 57c51c71-fd8d-440d-8262-9cccd1617c08 @frompackage "../.." begin using ^ end # ╔═╡ d9762fc1-fa2c-4315-a360-cc1cd9d70055 md""" This is an example of `StringOnEnter`: $(@bind text StringOnEnter("ciao")) """ # ╔═╡ cbeff2f3-3ffe-4aaa-8d4c-43c44ee6d59f text === "ciao" || error("Something went wrong") # ╔═╡ ecfdee44-3e6c-4e7e-a039-1f7d05a875f8 md""" This is a number: $(@bind num Editable(3)) """ # ╔═╡ 9a90e5be-6c38-440d-a6d6-99dc25be5727 num === 3 || error("something went wrong") # ╔═╡ ca6e57a2-667f-4a77-a1ea-5f42192056d4 @bind( number_editable, Editable(0.5123234; prefix = "Before: ", suffix = " After!", format = ".2f") ) # ╔═╡ 81c03bad-aed6-4b45-b3b5-edbba30c0bdb number_editable === 0.5123234 || error("something went wrong") # ╔═╡ ac83e4d6-1637-4646-865c-7d21ce010374 @bind( bool_editable, Editable(true) ) # ╔═╡ 09458943-15a4-4251-82a8-e43299db53b5 bool_editable || error("something went wrong") # ╔═╡ d171e8f9-c939-4747-a748-5568ae4a4064 num |> typeof # ╔═╡ 9dfb5236-9475-4bf6-990a-19f8f5519003 md""" This has also a unit $(@bind unitnum Editable(3.0;suffix=" dB")) """ # ╔═╡ 245fad1a-2f1e-4776-b048-6873e8c33f3b unitnum === 3.0 || error("Something went wrong") # ╔═╡ 456a3579-3c33-496c-bbf2-6e6e0d0ff102 bool_bond = @bind bool_val Editable(true) # ╔═╡ 8f7d7dac-d5e6-43f4-88e6-21179c78c3ef bool_val # ╔═╡ 00000000-0000-0000-0000-000000000001 PLUTO_PROJECT_TOML_CONTENTS = """ [deps] PlutoDevMacros = "a0499f29-c39b-4c5c-807c-88074221b949" """ # ╔═╡ 00000000-0000-0000-0000-000000000002 PLUTO_MANIFEST_TOML_CONTENTS = """ # This file is machine-generated - editing it directly is not advised [[AbstractPlutoDingetjes]] deps = ["Pkg"] git-tree-sha1 = "91bd53c39b9cbfb5ef4b015e8b582d344532bd0a" uuid = "6e696c72-6542-2067-7265-42206c756150" version = "1.2.0" [[ArgTools]] uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" version = "1.1.1" [[Artifacts]] uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" [[Base64]] uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" [[Dates]] deps = ["Printf"] uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" [[DocStringExtensions]] deps = ["LibGit2"] git-tree-sha1 = "2fb1e02f2b635d0845df5d7c167fec4dd739b00d" uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" version = "0.9.3" [[Downloads]] deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"] uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" version = "1.6.0" [[FileWatching]] uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" [[HypertextLiteral]] deps = ["Tricks"] git-tree-sha1 = "c47c5fa4c5308f27ccaac35504858d8914e102f9" uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2" version = "0.9.4" [[InteractiveUtils]] deps = ["Markdown"] uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" [[LibCURL]] deps = ["LibCURL_jll", "MozillaCACerts_jll"] uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" version = "0.6.4" [[LibCURL_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" version = "8.0.1+1" [[LibGit2]] deps = ["Base64", "NetworkOptions", "Printf", "SHA"] uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" [[LibSSH2_jll]] deps = ["Artifacts", "Libdl", "MbedTLS_jll"] uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" version = "1.11.0+1" [[Libdl]] uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" [[Logging]] uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" [[MacroTools]] deps = ["Markdown", "Random"] git-tree-sha1 = "9ee1618cbf5240e6d4e0371d6f24065083f60c48" uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" version = "0.5.11" [[Markdown]] deps = ["Base64"] uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" [[MbedTLS_jll]] deps = ["Artifacts", "Libdl"] uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" version = "2.28.2+1" [[MozillaCACerts_jll]] uuid = "14a3606d-f60d-562e-9121-12d972cd8159" version = "2023.1.10" [[NetworkOptions]] uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" version = "1.2.0" [[Pkg]] deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"] uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" version = "1.10.0" [[PlutoDevMacros]] deps = ["AbstractPlutoDingetjes", "DocStringExtensions", "HypertextLiteral", "InteractiveUtils", "MacroTools", "Markdown", "Pkg", "Random", "TOML"] git-tree-sha1 = "06fa4aa7a8f2239eec99cf54eeddd34f3d4359be" uuid = "a0499f29-c39b-4c5c-807c-88074221b949" version = "0.6.0" [[Printf]] deps = ["Unicode"] uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" [[REPL]] deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" [[Random]] deps = ["SHA"] uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [[SHA]] uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" version = "0.7.0" [[Serialization]] uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" [[Sockets]] uuid = "6462fe0b-24de-5631-8697-dd941f90decc" [[TOML]] deps = ["Dates"] uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" version = "1.0.3" [[Tar]] deps = ["ArgTools", "SHA"] uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" version = "1.10.0" [[Tricks]] git-tree-sha1 = "aadb748be58b492045b4f56166b5188aa63ce549" uuid = "410a4b4d-49e4-4fbc-ab6d-cb71b17b3775" version = "0.1.7" [[UUIDs]] deps = ["Random", "SHA"] uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" [[Unicode]] uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" [[Zlib_jll]] deps = ["Libdl"] uuid = "83775a58-1f1d-513f-b197-d71354ab007a" version = "1.2.13+1" [[nghttp2_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" version = "1.52.0+1" [[p7zip_jll]] deps = ["Artifacts", "Libdl"] uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" version = "17.4.0+2" """ # ╔═╡ Cell order: # ╠═cfb4d354-e0b2-4a04-a559-4fb88df33954 # ╠═57c51c71-fd8d-440d-8262-9cccd1617c08 # ╠═d9762fc1-fa2c-4315-a360-cc1cd9d70055 # ╠═cbeff2f3-3ffe-4aaa-8d4c-43c44ee6d59f # ╠═ecfdee44-3e6c-4e7e-a039-1f7d05a875f8 # ╠═9a90e5be-6c38-440d-a6d6-99dc25be5727 # ╠═ca6e57a2-667f-4a77-a1ea-5f42192056d4 # ╠═81c03bad-aed6-4b45-b3b5-edbba30c0bdb # ╠═ac83e4d6-1637-4646-865c-7d21ce010374 # ╠═09458943-15a4-4251-82a8-e43299db53b5 # ╠═d171e8f9-c939-4747-a748-5568ae4a4064 # ╠═9dfb5236-9475-4bf6-990a-19f8f5519003 # ╠═245fad1a-2f1e-4776-b048-6873e8c33f3b # ╠═456a3579-3c33-496c-bbf2-6e6e0d0ff102 # ╠═8f7d7dac-d5e6-43f4-88e6-21179c78c3ef # ╟─00000000-0000-0000-0000-000000000001 # ╟─00000000-0000-0000-0000-000000000002
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
12129
### A Pluto.jl notebook ### # v0.19.40 #> custom_attrs = ["enable_hidden"] using Markdown using InteractiveUtils # ╔═╡ 464fc674-5ed7-11ed-0aff-939456ebc5a8 begin using HypertextLiteral using PlutoUI using PlutoDevMacros.PlutoCombineHTL.WithTypes using PlutoDevMacros end # ╔═╡ e1d8a572-21ec-4db9-a640-f3521a16cb1f @frompackage "../.." begin using ^.ExtendedToc: * end # ╔═╡ d05d4e8c-bf50-4343-b6b5-9b77caa646cd ExtendedTableOfContents() # ╔═╡ 48540378-5b63-4c20-986b-75c08ceb24b7 md""" # Tests """ # ╔═╡ 7dce5ffb-48ad-4ef4-9e13-f7a34794170a md""" The weird looking 3 below is inside a hidden cell that has been tagged with `show_output_when_hidden` """ # ╔═╡ 4373ab10-d4e7-4e25-b7a8-da1fcf3dcb0c # ╠═╡ custom_attrs = ["toc-hidden"] md""" ## Hidden Heading """ # ╔═╡ 77e467b9-c86c-4f13-a259-c38dfd80a3aa 2 # This will be completely hidden # ╔═╡ f6e74270-bd75-4367-a0b2-1e10e1336b6c # ╠═╡ skip_as_script = true #=╠═╡ 3 |> show_output_when_hidden # This will keep showing ╠═╡ =# # ╔═╡ 091dbcb6-c5f6-469b-889a-e4b23197d2ad md""" ## very very very very very very very very very long """ # ╔═╡ c9bcf4b9-6769-4d5a-bbc0-a14675e11523 md""" ### Short """ # ╔═╡ 6ddee4cb-7d76-483e-aed5-bde46280cc5b md""" ## Random JS Tests """ # ╔═╡ 239b3956-69d7-43dc-80b8-92f43b84aada @htl """ <div class='parent'> <span class='child first'></span> <span class='child second'></span> <span class='child third'></span> </div> <style> div.parent { position: fixed; top: 30px; left: 30px; background: lightblue; display: flex; height: 30px; } span.child { align-self: stretch; width: 20px; display: inline-block; background: green; margin: 5px 0px; } </style> """; # ╔═╡ c4490c71-5994-4849-914b-ec1a88ec7881 # ╠═╡ custom_attrs = ["toc-collapsed"] md""" # Fillers """ # ╔═╡ fd6772f5-085a-4ffa-bf55-dfeb8e93d32b md""" ## More Fillers """ # ╔═╡ 863e6721-98f1-4311-8b9e-fa921030f7d7 md""" ## More Fillers """ # ╔═╡ 515b7fc0-1c03-4c82-819b-4bf70baf8f14 md""" ## More Fillers """ # ╔═╡ e4a29e2e-c2ec-463b-afb2-1681c849780b md""" ## More Fillers """ # ╔═╡ eb559060-5da1-4a9e-af51-9007392885eb md""" ## More Fillers """ # ╔═╡ 1aabb7b3-692f-4a27-bb34-672f8fdb0753 md""" ## More Fillers """ # ╔═╡ ac541f37-7af5-49c8-99f8-c5d6df1a6881 md""" ## More Fillers """ # ╔═╡ fdf482d1-f8fa-4628-9417-2816de367e94 md""" ## More Fillers """ # ╔═╡ 6de511d2-ad79-4f0e-95ff-ce7531f3f0c8 md""" ## More Fillers """ # ╔═╡ a8bcd2cc-ae01-4db7-822f-217c1f6bbc8f md""" ## More Fillers """ # ╔═╡ 9ddc7a20-c1c9-4af3-98cc-3b803ca181b5 md""" ## More Fillers """ # ╔═╡ 6dd2c458-e02c-4850-a933-fe9fb9dcdf39 md""" ## More Fillers """ # ╔═╡ 00000000-0000-0000-0000-000000000001 PLUTO_PROJECT_TOML_CONTENTS = """ [deps] HypertextLiteral = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2" PlutoDevMacros = "a0499f29-c39b-4c5c-807c-88074221b949" PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8" [compat] HypertextLiteral = "~0.9.4" PlutoDevMacros = "~0.6.0" PlutoUI = "~0.7.49" """ # ╔═╡ 00000000-0000-0000-0000-000000000002 PLUTO_MANIFEST_TOML_CONTENTS = """ # This file is machine-generated - editing it directly is not advised julia_version = "1.10.2" manifest_format = "2.0" project_hash = "8df05c84907ee1c13539c332821b80414e385894" [[deps.AbstractPlutoDingetjes]] deps = ["Pkg"] git-tree-sha1 = "91bd53c39b9cbfb5ef4b015e8b582d344532bd0a" uuid = "6e696c72-6542-2067-7265-42206c756150" version = "1.2.0" [[deps.ArgTools]] uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" version = "1.1.1" [[deps.Artifacts]] uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" [[deps.Base64]] uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" [[deps.ColorTypes]] deps = ["FixedPointNumbers", "Random"] git-tree-sha1 = "eb7f0f8307f71fac7c606984ea5fb2817275d6e4" uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f" version = "0.11.4" [[deps.CompilerSupportLibraries_jll]] deps = ["Artifacts", "Libdl"] uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae" version = "1.1.0+0" [[deps.Dates]] deps = ["Printf"] uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" [[deps.DocStringExtensions]] deps = ["LibGit2"] git-tree-sha1 = "2fb1e02f2b635d0845df5d7c167fec4dd739b00d" uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" version = "0.9.3" [[deps.Downloads]] deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"] uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" version = "1.6.0" [[deps.FileWatching]] uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" [[deps.FixedPointNumbers]] deps = ["Statistics"] git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc" uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93" version = "0.8.4" [[deps.Hyperscript]] deps = ["Test"] git-tree-sha1 = "8d511d5b81240fc8e6802386302675bdf47737b9" uuid = "47d2ed2b-36de-50cf-bf87-49c2cf4b8b91" version = "0.0.4" [[deps.HypertextLiteral]] deps = ["Tricks"] git-tree-sha1 = "c47c5fa4c5308f27ccaac35504858d8914e102f9" uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2" version = "0.9.4" [[deps.IOCapture]] deps = ["Logging", "Random"] git-tree-sha1 = "d75853a0bdbfb1ac815478bacd89cd27b550ace6" uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89" version = "0.2.3" [[deps.InteractiveUtils]] deps = ["Markdown"] uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" [[deps.JSON]] deps = ["Dates", "Mmap", "Parsers", "Unicode"] git-tree-sha1 = "31e996f0a15c7b280ba9f76636b3ff9e2ae58c9a" uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" version = "0.21.4" [[deps.LibCURL]] deps = ["LibCURL_jll", "MozillaCACerts_jll"] uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" version = "0.6.4" [[deps.LibCURL_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" version = "8.4.0+0" [[deps.LibGit2]] deps = ["Base64", "LibGit2_jll", "NetworkOptions", "Printf", "SHA"] uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" [[deps.LibGit2_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll"] uuid = "e37daf67-58a4-590a-8e99-b0245dd2ffc5" version = "1.6.4+0" [[deps.LibSSH2_jll]] deps = ["Artifacts", "Libdl", "MbedTLS_jll"] uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" version = "1.11.0+1" [[deps.Libdl]] uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" [[deps.LinearAlgebra]] deps = ["Libdl", "OpenBLAS_jll", "libblastrampoline_jll"] uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" [[deps.Logging]] uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" [[deps.MIMEs]] git-tree-sha1 = "65f28ad4b594aebe22157d6fac869786a255b7eb" uuid = "6c6e2e6c-3030-632d-7369-2d6c69616d65" version = "0.1.4" [[deps.MacroTools]] deps = ["Markdown", "Random"] git-tree-sha1 = "9ee1618cbf5240e6d4e0371d6f24065083f60c48" uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" version = "0.5.11" [[deps.Markdown]] deps = ["Base64"] uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" [[deps.MbedTLS_jll]] deps = ["Artifacts", "Libdl"] uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" version = "2.28.2+1" [[deps.Mmap]] uuid = "a63ad114-7e13-5084-954f-fe012c677804" [[deps.MozillaCACerts_jll]] uuid = "14a3606d-f60d-562e-9121-12d972cd8159" version = "2023.1.10" [[deps.NetworkOptions]] uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" version = "1.2.0" [[deps.OpenBLAS_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"] uuid = "4536629a-c528-5b80-bd46-f80d51c5b363" version = "0.3.23+4" [[deps.Parsers]] deps = ["Dates", "PrecompileTools", "UUIDs"] git-tree-sha1 = "716e24b21538abc91f6205fd1d8363f39b442851" uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" version = "2.7.2" [[deps.Pkg]] deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"] uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" version = "1.10.0" [[deps.PlutoDevMacros]] deps = ["AbstractPlutoDingetjes", "DocStringExtensions", "HypertextLiteral", "InteractiveUtils", "MacroTools", "Markdown", "Pkg", "Random", "TOML"] git-tree-sha1 = "06fa4aa7a8f2239eec99cf54eeddd34f3d4359be" uuid = "a0499f29-c39b-4c5c-807c-88074221b949" version = "0.6.0" [[deps.PlutoUI]] deps = ["AbstractPlutoDingetjes", "Base64", "ColorTypes", "Dates", "FixedPointNumbers", "Hyperscript", "HypertextLiteral", "IOCapture", "InteractiveUtils", "JSON", "Logging", "MIMEs", "Markdown", "Random", "Reexport", "URIs", "UUIDs"] git-tree-sha1 = "e47cd150dbe0443c3a3651bc5b9cbd5576ab75b7" uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8" version = "0.7.52" [[deps.PrecompileTools]] deps = ["Preferences"] git-tree-sha1 = "03b4c25b43cb84cee5c90aa9b5ea0a78fd848d2f" uuid = "aea7be01-6a6a-4083-8856-8a6e6704d82a" version = "1.2.0" [[deps.Preferences]] deps = ["TOML"] git-tree-sha1 = "7eb1686b4f04b82f96ed7a4ea5890a4f0c7a09f1" uuid = "21216c6a-2e73-6563-6e65-726566657250" version = "1.4.0" [[deps.Printf]] deps = ["Unicode"] uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" [[deps.REPL]] deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" [[deps.Random]] deps = ["SHA"] uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [[deps.Reexport]] git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b" uuid = "189a3867-3050-52da-a836-e630ba90ab69" version = "1.2.2" [[deps.SHA]] uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" version = "0.7.0" [[deps.Serialization]] uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" [[deps.Sockets]] uuid = "6462fe0b-24de-5631-8697-dd941f90decc" [[deps.SparseArrays]] deps = ["Libdl", "LinearAlgebra", "Random", "Serialization", "SuiteSparse_jll"] uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" version = "1.10.0" [[deps.Statistics]] deps = ["LinearAlgebra", "SparseArrays"] uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" version = "1.10.0" [[deps.SuiteSparse_jll]] deps = ["Artifacts", "Libdl", "libblastrampoline_jll"] uuid = "bea87d4a-7f5b-5778-9afe-8cc45184846c" version = "7.2.1+1" [[deps.TOML]] deps = ["Dates"] uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" version = "1.0.3" [[deps.Tar]] deps = ["ArgTools", "SHA"] uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" version = "1.10.0" [[deps.Test]] deps = ["InteractiveUtils", "Logging", "Random", "Serialization"] uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [[deps.Tricks]] git-tree-sha1 = "aadb748be58b492045b4f56166b5188aa63ce549" uuid = "410a4b4d-49e4-4fbc-ab6d-cb71b17b3775" version = "0.1.7" [[deps.URIs]] git-tree-sha1 = "b7a5e99f24892b6824a954199a45e9ffcc1c70f0" uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4" version = "1.5.0" [[deps.UUIDs]] deps = ["Random", "SHA"] uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" [[deps.Unicode]] uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" [[deps.Zlib_jll]] deps = ["Libdl"] uuid = "83775a58-1f1d-513f-b197-d71354ab007a" version = "1.2.13+1" [[deps.libblastrampoline_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850b90-86db-534c-a0d3-1478176c7d93" version = "5.8.0+1" [[deps.nghttp2_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" version = "1.52.0+1" [[deps.p7zip_jll]] deps = ["Artifacts", "Libdl"] uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" version = "17.4.0+2" """ # ╔═╡ Cell order: # ╠═464fc674-5ed7-11ed-0aff-939456ebc5a8 # ╠═e1d8a572-21ec-4db9-a640-f3521a16cb1f # ╠═d05d4e8c-bf50-4343-b6b5-9b77caa646cd # ╠═48540378-5b63-4c20-986b-75c08ceb24b7 # ╟─7dce5ffb-48ad-4ef4-9e13-f7a34794170a # ╟─4373ab10-d4e7-4e25-b7a8-da1fcf3dcb0c # ╠═77e467b9-c86c-4f13-a259-c38dfd80a3aa # ╠═f6e74270-bd75-4367-a0b2-1e10e1336b6c # ╠═091dbcb6-c5f6-469b-889a-e4b23197d2ad # ╠═c9bcf4b9-6769-4d5a-bbc0-a14675e11523 # ╟─6ddee4cb-7d76-483e-aed5-bde46280cc5b # ╠═239b3956-69d7-43dc-80b8-92f43b84aada # ╠═c4490c71-5994-4849-914b-ec1a88ec7881 # ╠═fd6772f5-085a-4ffa-bf55-dfeb8e93d32b # ╠═863e6721-98f1-4311-8b9e-fa921030f7d7 # ╠═515b7fc0-1c03-4c82-819b-4bf70baf8f14 # ╠═e4a29e2e-c2ec-463b-afb2-1681c849780b # ╠═eb559060-5da1-4a9e-af51-9007392885eb # ╠═1aabb7b3-692f-4a27-bb34-672f8fdb0753 # ╠═ac541f37-7af5-49c8-99f8-c5d6df1a6881 # ╠═fdf482d1-f8fa-4628-9417-2816de367e94 # ╠═6de511d2-ad79-4f0e-95ff-ce7531f3f0c8 # ╠═a8bcd2cc-ae01-4db7-822f-217c1f6bbc8f # ╠═9ddc7a20-c1c9-4af3-98cc-3b803ca181b5 # ╠═6dd2c458-e02c-4850-a933-fe9fb9dcdf39 # ╟─00000000-0000-0000-0000-000000000001 # ╟─00000000-0000-0000-0000-000000000002
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
9343
### A Pluto.jl notebook ### # v0.19.29 using Markdown using InteractiveUtils # ╔═╡ 945ee770-e082-11eb-0c8b-25e53f4d718c begin using HypertextLiteral using PlutoDevMacros end # ╔═╡ 57ec4f3e-ed4d-4c44-af8a-c1e32a3f4bd7 @frompackage "../.." begin using ^ end # ╔═╡ b35233a0-6d2f-4eac-8cb0-e317eef4c835 # ╠═╡ skip_as_script = true #=╠═╡ md""" ## TeX Equation environment """ ╠═╡ =# # ╔═╡ a78aa624-6504-4b3f-914a-833261b92f19 initialize_eqref() # This is important for making `eqref(label)` work! # ╔═╡ b8782294-d6b9-43ac-b745-b2cbb6ed06b1 a = 1:10 # ╔═╡ 0bfb8ee9-14e2-44ee-b0d5-98790d47f7b8 texeq("3+2=5") # ╔═╡ 958531c1-fa83-477c-be3d-927155800f1b texeq" \sum_{i=$(a[1])}^{$(a[end])} i=$(sum(a)) \label{interactive} " # ╔═╡ 1482e175-cf32-42f3-b8fb-64f1f14c1501 md""" The sum in $(eqref("interactive")) is interactive and its equation number reference automatically updates! """ # ╔═╡ 0df86e0e-6813-4f9f-9f36-7badf2f85597 md"""Multiple links to the same equation $(eqref("interactive")) also work! See also $(eqref("seven")) """ # ╔═╡ 0bd44757-90b8-452f-999f-6109239ac826 md""" $(texeq(" 3 + 2 ")) """ # ╔═╡ de8473c1-dea1-4221-9562-30679ae58e34 md""" $$3+2$$ """ # ╔═╡ b9213424-f814-4bb8-a05f-33249f4f0a8f md""" $(texeq(" (2 \\cdot 3) + (1 \\cdot 4) &= 6 + 4 \\label{test1} \\\\ &= 10 \\label{test2} \\\\ &= 10 \\\\ &= 10 \\label{test3} \\\\ &= 10 \\\\ &= 10 \\label{test4} \\\\ &= 10 \\\\ &= 10 \\label{test5}" ,"align")) """ # ╔═╡ 9e69e30e-506a-4bd7-b213-0b5c0b31a10d md"""Link to sub-parts of align environments are now fixed! $(eqref("test1")), $(eqref("test2")), $(eqref("test3")), $(eqref("test4")), $(eqref("test5")) """ # ╔═╡ ea09b6ec-8d39-4cd9-9c79-85c1fcce3828 texeq(" \\begin{align*} (2 \\cdot 3) + (1 \\cdot 4) &= 6 + 4 \\ &= 10 \\end{align*} ") # ╔═╡ 900f494b-690d-43cf-b1b7-61c5d3e68a6d "\n" # ╔═╡ 7879d7e3-38ad-4a06-8057-ec30da534d76 texeq("y=2x^2") # ╔═╡ 9446acfc-a310-4de6-8876-e30ede527e9c md""" $$Y = \overline {A} - m \phi (\overline {r} - \gamma \pi)$$ """ # ╔═╡ 6d750d01-b851-4614-b448-1a6e00fa5754 md""" $(texeq(" \\pi = \\pi^e + \\gamma (P - Y^P) + \\rho \\label{seven}" )) """ # ╔═╡ 1471265c-4934-45e3-a4b2-37da94ff7472 md"## Update eqref hyperlinks" # ╔═╡ b6b08bf0-7282-40b9-ae87-b776a64c519f md""" KaTeX [supports](https://katex.org/docs/supported.html) automatic numbering of *equation* environments. While it does not support equation reference and labelling, [this](https://github.com/KaTeX/KaTeX/issues/2003) hack on github shows how to achieve the label functionality. Unfortunately, since automatic numbering in KaTeX uses CSS counters, it is not possible to access the value of the counter at a specific DOM element. We then create a function that loops through all possible katex equation and counts them, putting the relevant number in the appropriate hyperlink innerText to create equation references that automatically update. The code for the mutationobservers to trigger re-computation of the numbers are taken from the **TableOfContents** in **PlutoUI** """ # ╔═╡ d14197d8-cab1-4d92-b81c-d826ea8183f3 # ╠═╡ skip_as_script = true #=╠═╡ md""" ## TeX equations """ ╠═╡ =# # ╔═╡ 943e5ef8-9187-4bfd-aefa-8f405b50e6aa asdasd = 3 # ╔═╡ 2078d2c8-1f38-42fe-9945-b2235e267b38 texeq" \frac{q \sqrt{2}}{15} + $(3 + 2 + (5 + 32)) - $asdasd " # ╔═╡ 2c82ab99-8e86-41c6-b938-3635d2d3ccde md""" The antenna pattern of a DRA antenna can at first approximation be expressed as: $(texeq("3+2")) """ # ╔═╡ 00000000-0000-0000-0000-000000000001 PLUTO_PROJECT_TOML_CONTENTS = """ [deps] HypertextLiteral = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2" PlutoDevMacros = "a0499f29-c39b-4c5c-807c-88074221b949" [compat] HypertextLiteral = "~0.9.4" PlutoDevMacros = "~0.6.0" """ # ╔═╡ 00000000-0000-0000-0000-000000000002 PLUTO_MANIFEST_TOML_CONTENTS = """ # This file is machine-generated - editing it directly is not advised julia_version = "1.10.0-beta2" manifest_format = "2.0" project_hash = "4db4ce3ca4328971f4bd140c0e8c876b89cd6192" [[deps.AbstractPlutoDingetjes]] deps = ["Pkg"] git-tree-sha1 = "91bd53c39b9cbfb5ef4b015e8b582d344532bd0a" uuid = "6e696c72-6542-2067-7265-42206c756150" version = "1.2.0" [[deps.ArgTools]] uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" version = "1.1.1" [[deps.Artifacts]] uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" [[deps.Base64]] uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" [[deps.Dates]] deps = ["Printf"] uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" [[deps.DocStringExtensions]] deps = ["LibGit2"] git-tree-sha1 = "2fb1e02f2b635d0845df5d7c167fec4dd739b00d" uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" version = "0.9.3" [[deps.Downloads]] deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"] uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" version = "1.6.0" [[deps.FileWatching]] uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" [[deps.HypertextLiteral]] deps = ["Tricks"] git-tree-sha1 = "c47c5fa4c5308f27ccaac35504858d8914e102f9" uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2" version = "0.9.4" [[deps.InteractiveUtils]] deps = ["Markdown"] uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" [[deps.LibCURL]] deps = ["LibCURL_jll", "MozillaCACerts_jll"] uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" version = "0.6.4" [[deps.LibCURL_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" version = "8.0.1+1" [[deps.LibGit2]] deps = ["Base64", "NetworkOptions", "Printf", "SHA"] uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" [[deps.LibSSH2_jll]] deps = ["Artifacts", "Libdl", "MbedTLS_jll"] uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" version = "1.11.0+1" [[deps.Libdl]] uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" [[deps.Logging]] uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" [[deps.MacroTools]] deps = ["Markdown", "Random"] git-tree-sha1 = "9ee1618cbf5240e6d4e0371d6f24065083f60c48" uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" version = "0.5.11" [[deps.Markdown]] deps = ["Base64"] uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" [[deps.MbedTLS_jll]] deps = ["Artifacts", "Libdl"] uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" version = "2.28.2+1" [[deps.MozillaCACerts_jll]] uuid = "14a3606d-f60d-562e-9121-12d972cd8159" version = "2023.1.10" [[deps.NetworkOptions]] uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" version = "1.2.0" [[deps.Pkg]] deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"] uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" version = "1.10.0" [[deps.PlutoDevMacros]] deps = ["AbstractPlutoDingetjes", "DocStringExtensions", "HypertextLiteral", "InteractiveUtils", "MacroTools", "Markdown", "Pkg", "Random", "TOML"] git-tree-sha1 = "06fa4aa7a8f2239eec99cf54eeddd34f3d4359be" uuid = "a0499f29-c39b-4c5c-807c-88074221b949" version = "0.6.0" [[deps.Printf]] deps = ["Unicode"] uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" [[deps.REPL]] deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" [[deps.Random]] deps = ["SHA"] uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [[deps.SHA]] uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" version = "0.7.0" [[deps.Serialization]] uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" [[deps.Sockets]] uuid = "6462fe0b-24de-5631-8697-dd941f90decc" [[deps.TOML]] deps = ["Dates"] uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" version = "1.0.3" [[deps.Tar]] deps = ["ArgTools", "SHA"] uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" version = "1.10.0" [[deps.Tricks]] git-tree-sha1 = "aadb748be58b492045b4f56166b5188aa63ce549" uuid = "410a4b4d-49e4-4fbc-ab6d-cb71b17b3775" version = "0.1.7" [[deps.UUIDs]] deps = ["Random", "SHA"] uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" [[deps.Unicode]] uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" [[deps.Zlib_jll]] deps = ["Libdl"] uuid = "83775a58-1f1d-513f-b197-d71354ab007a" version = "1.2.13+1" [[deps.nghttp2_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" version = "1.52.0+1" [[deps.p7zip_jll]] deps = ["Artifacts", "Libdl"] uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" version = "17.4.0+2" """ # ╔═╡ Cell order: # ╠═945ee770-e082-11eb-0c8b-25e53f4d718c # ╠═57ec4f3e-ed4d-4c44-af8a-c1e32a3f4bd7 # ╟─b35233a0-6d2f-4eac-8cb0-e317eef4c835 # ╠═a78aa624-6504-4b3f-914a-833261b92f19 # ╠═b8782294-d6b9-43ac-b745-b2cbb6ed06b1 # ╠═0bfb8ee9-14e2-44ee-b0d5-98790d47f7b8 # ╠═958531c1-fa83-477c-be3d-927155800f1b # ╠═1482e175-cf32-42f3-b8fb-64f1f14c1501 # ╠═0df86e0e-6813-4f9f-9f36-7badf2f85597 # ╠═0bd44757-90b8-452f-999f-6109239ac826 # ╠═de8473c1-dea1-4221-9562-30679ae58e34 # ╠═b9213424-f814-4bb8-a05f-33249f4f0a8f # ╠═9e69e30e-506a-4bd7-b213-0b5c0b31a10d # ╠═ea09b6ec-8d39-4cd9-9c79-85c1fcce3828 # ╠═900f494b-690d-43cf-b1b7-61c5d3e68a6d # ╠═7879d7e3-38ad-4a06-8057-ec30da534d76 # ╠═9446acfc-a310-4de6-8876-e30ede527e9c # ╠═6d750d01-b851-4614-b448-1a6e00fa5754 # ╟─1471265c-4934-45e3-a4b2-37da94ff7472 # ╟─b6b08bf0-7282-40b9-ae87-b776a64c519f # ╟─d14197d8-cab1-4d92-b81c-d826ea8183f3 # ╠═2078d2c8-1f38-42fe-9945-b2235e267b38 # ╠═943e5ef8-9187-4bfd-aefa-8f405b50e6aa # ╠═2c82ab99-8e86-41c6-b938-3635d2d3ccde # ╟─00000000-0000-0000-0000-000000000001 # ╟─00000000-0000-0000-0000-000000000002
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
code
14555
### A Pluto.jl notebook ### # v0.19.40 #> custom_attrs = ["hide-enabled"] using Markdown using InteractiveUtils # This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error). macro bind(def, element) quote local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end local el = $(esc(element)) global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el) el end end # ╔═╡ 8db82e94-5c81-4c52-9228-7e22395fb68f begin using PlutoDevMacros end # ╔═╡ 949ac1ef-c502-4e28-81ff-f99b0d19aa03 @frompackage "../.." begin using ^.StructBondModule using ^: ExtendedTableOfContents, Editable using >.HypertextLiteral using >.PlutoUI end # ╔═╡ 9d4455af-96f1-46d7-a4f3-434495b11c8a md""" # Packages """ # ╔═╡ 707175a9-d356-43cf-8038-620ebc401c93 ExtendedTableOfContents() # ╔═╡ cbfc6eec-8991-4a9c-ada0-295c8052854d # html""" # <style> # main { # margin-right: 350px !important; # } # </style> # """ # ╔═╡ 4843983c-df64-4b94-8634-7a10d9423a70 md""" # StructBond """ # ╔═╡ a8995224-83c6-4f82-b5a5-87a6f86fc7a0 md""" Generating automatic widgets for custom structs is quite straightforward with the aid of the `@fielddata` macro and the `StructBond` type. The top-left arrow can be used to show-hide the field elements (useful inside a `BondTable`, shown below), while the green toggle on the top-right can be used to disable temporarily the synch between the JS widgets and the bond values in Pluto. """ # ╔═╡ 9e3601f5-efc2-44e9-83d8-5b65ce7e9ccf begin """ struct ASD """ Base.@kwdef struct ASD a::Int b::Int c::String "This field is _special_" d::String e::Int end @typeasfield String = TextField() # String fields with no struct-specific default will use this @fielddata ASD begin a = (md"Markdown description, including ``LaTeX``", Slider(1:10)) b = (@htl("<span>Field with <b>HTML</b> description</span>"), Scrubbable(1:10)) c = ("Normal String Description", TextField()) # d has no ASD-specific custom bond, so it will use the field docstring as description and the default String widget as widget e = Slider(20:25) # No description, defaults to the fieldname as no docstring is present end asd_bond = @bind asd StructBond(ASD; description = "Custom Description") end # ╔═╡ cdc0a7ad-a3ac-4270-b707-35b1939da276 asd # ╔═╡ fe891b4e-f440-4823-b43b-72572f6a6c12 md""" ## Default Type Widgets """ # ╔═╡ 86a80228-f495-43e8-b1d4-c93b7b52c8d8 begin @kwdef struct MAH a::Int end @kwdef struct BOH mah::MAH end # This will make the default widget for an Int a Slider @typeasfield Int = Slider(1:10) # This will make the default widget for fields of type ASD a popout that wraps a StructBond{ASD} @popoutasfield MAH @bind boh StructBond(BOH) end # ╔═╡ 2358f686-1950-40f9-9d5c-dac2d98f4c24 boh # ╔═╡ 49516374-f625-4a84-ac5c-f92497d45025 md""" # @NTBond """ # ╔═╡ 8cc53cd2-9114-4067-ab0b-37fd8cd79240 md""" Sometimes custom structs are not needed and it would be useful to just use the same nice bond structure of `StructBond` to simply create arbitrary NamedTuples. This is possible with the convenience macro `@NTBond` which can be called as shown below to create a nice display for an interactive bond creating an arbitrary NamedTuple. The macro simply create a `StructBond` wrapping the desired NamedTuple type. """ # ╔═╡ 0db51d39-7c05-4e00-b951-7fe776a8e0f9 nt_bond = @bind nt @NTBond "My Fancy NTuple" begin a = ("Description", Slider(1:10)) b = (md"**Bold** field", Slider(1:10)) c = Slider(1:10) # No description, defaults to the name of the field end # ╔═╡ e2b79a58-e66e-4d40-8673-418823753b38 nt # ╔═╡ 9d23382c-cf35-4b20-a46c-0f4e2de17fc7 md""" # @BondsList """ # ╔═╡ 959acb40-1fd6-43f5-a1a6-73a6ceaae1d7 md""" In some cases, one does not want to have a single bond wrapping either a Structure or a NamedTuple because single independent bonds are more convenient. `@BondsList` is a convenience macro to create an object of type `BondsList` which simply allow to add a description to separate bonds and group them all together in a table-like format equivalent to those of `StructBond`. !!! note Unlike `StructBond`, a BondsList is already composed of bond created with `@bind` and it just groups them up with a description. The output of `@BondsList` is not supposed to be bound to a variable using `@bind`.\ The bonds grouped in a BondsList still act and update independently from one another. See the example below for understanding the synthax. The header of a BondsList is shown in an orange background to easily differentiate it from `StructBond`. """ # ╔═╡ 4d611425-c8e3-4bc3-912b-8bc0465363bc bl = @BondsList "My Group of Bonds" let tv = PlutoUI.Experimental.transformed_value # We use transformed_value to translate GHz to Hz in the bound variable `freq` "Frequency [GHz]" = @bind freq tv(x -> x * 1e9, Editable(20; suffix = " GHz")) md"Altitude ``h`` [m]" = @bind alt Scrubbable(100:10:200) end # ╔═╡ a5490a6b-dc11-42b7-87e0-d38870fc55e4 freq # ╔═╡ 705e30fe-77a3-4b06-8b99-1807290edffb alt # ╔═╡ 2ee7f26d-f383-4e7e-a69a-8fb72717467c md""" # Popout """ # ╔═╡ 79beba88-932f-4147-b3a0-d821ef1bc1e2 md""" The structures above can also be used nested within one another. To facilitate accessing nested structures, one can use the `Popout` type. In its simple form, you can give an instance of a StructBond, a bond wrapping a StructBond or a BondsList as input to Popout to create a table that is hidden behind a popup window. If an instance present, but you want a custom type for which you have defined custom bonds and descriptions with `@fielddata` to appear as popout, you can use the function `popoutwrap(TYPE)` to generate a small icon which hides a popup containing the `StructBond` of the provided type `TYPE`. The StructBond table appears on hover upon the icon, can be made fixed by clicking on the icon and can then be moved around or resized. A double click on the header of the popout hides it again: """ # ╔═╡ 63d6c2df-a411-407c-af11-4f5d09fbb322 begin Base.@kwdef struct LOL a::Int b::Int end @fielddata LOL begin a = (md"Wonder!", Slider(1:10)) b = (@htl("<span>Field B</span>"), Scrubbable(1:10)) end end # ╔═╡ 633029af-8cac-426e-b35c-c9fb3938b784 @bind lol_pop popoutwrap(LOL) # ╔═╡ 065bad73-5fa8-4496-ba33-9e66940b5806 lol_pop # ╔═╡ 2073f11e-8196-4ebc-922f-5fa589e91797 md""" The ability to also wrap pre-existing bonds around StructBonds is convenient for organizing the various bonds one have in a `BondsList` or `BondTable` As an example, one can create a `BondsList` containing the two `StructBond` bonds generated at the beginning of this notebook with the follwing code. """ # ╔═╡ 811cf78b-e870-45bb-9173-89a3b3d495f5 blc = @BondsList "Popout Container" begin "Structure ASD" = Popout(asd_bond) "NamedTuple" = Popout(nt_bond) end # ╔═╡ e7d67662-77b3-482a-b032-8db4afbc01a6 asd # ╔═╡ 996b4085-114c-48f4-9f90-8e637f29c06a nt # ╔═╡ 3a066bf4-3466-469e-90d0-6b14be3ed8d5 md""" # BondTable """ # ╔═╡ 3213d977-7b65-43b0-a881-10fcc2523f14 md""" The final convenience structure provided by this module is the `BondTable`. It can be created to group a list of bonds in a floating table that stays on the left side of the notebook (similar to the TableOfContents of PlutoUI) and can be moved around and resized or hidden for convenience. The BondTable is intended to be used either with bonds containing `StructBond` or with `BondsList`. Future types with similar structure will also be added. Here is an example of a bondtable containing all the examples of this notebook. """ # ╔═╡ 903fee67-6b23-41dc-a03d-f1040b696be6 BondTable([ asd_bond, nt_bond, bl, blc ]; description = "My Bonds") # ╔═╡ 08d711c0-e2cc-4444-94ca-0c4c3cfe901f nt # ╔═╡ 03e9d75e-e6c9-4199-933b-2be306daf978 asd # ╔═╡ 26d11600-2827-4e08-9195-109c8a8bddc3 freq # ╔═╡ be2a7820-e194-4410-b00d-a9332b234ad6 alt # ╔═╡ 00000000-0000-0000-0000-000000000001 PLUTO_PROJECT_TOML_CONTENTS = """ [deps] PlutoDevMacros = "a0499f29-c39b-4c5c-807c-88074221b949" [compat] PlutoDevMacros = "~0.7.0" """ # ╔═╡ 00000000-0000-0000-0000-000000000002 PLUTO_MANIFEST_TOML_CONTENTS = """ # This file is machine-generated - editing it directly is not advised julia_version = "1.10.2" manifest_format = "2.0" project_hash = "9088728c15a23247dcd792960c847dd5035deb53" [[deps.AbstractPlutoDingetjes]] deps = ["Pkg"] git-tree-sha1 = "0f748c81756f2e5e6854298f11ad8b2dfae6911a" uuid = "6e696c72-6542-2067-7265-42206c756150" version = "1.3.0" [[deps.ArgTools]] uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" version = "1.1.1" [[deps.Artifacts]] uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" [[deps.Base64]] uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" [[deps.Dates]] deps = ["Printf"] uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" [[deps.DocStringExtensions]] deps = ["LibGit2"] git-tree-sha1 = "2fb1e02f2b635d0845df5d7c167fec4dd739b00d" uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" version = "0.9.3" [[deps.Downloads]] deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"] uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" version = "1.6.0" [[deps.FileWatching]] uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" [[deps.HypertextLiteral]] deps = ["Tricks"] git-tree-sha1 = "7134810b1afce04bbc1045ca1985fbe81ce17653" uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2" version = "0.9.5" [[deps.InteractiveUtils]] deps = ["Markdown"] uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" [[deps.LibCURL]] deps = ["LibCURL_jll", "MozillaCACerts_jll"] uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" version = "0.6.4" [[deps.LibCURL_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" version = "8.4.0+0" [[deps.LibGit2]] deps = ["Base64", "LibGit2_jll", "NetworkOptions", "Printf", "SHA"] uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" [[deps.LibGit2_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll"] uuid = "e37daf67-58a4-590a-8e99-b0245dd2ffc5" version = "1.6.4+0" [[deps.LibSSH2_jll]] deps = ["Artifacts", "Libdl", "MbedTLS_jll"] uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" version = "1.11.0+1" [[deps.Libdl]] uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" [[deps.Logging]] uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" [[deps.MacroTools]] deps = ["Markdown", "Random"] git-tree-sha1 = "2fa9ee3e63fd3a4f7a9a4f4744a52f4856de82df" uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" version = "0.5.13" [[deps.Markdown]] deps = ["Base64"] uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" [[deps.MbedTLS_jll]] deps = ["Artifacts", "Libdl"] uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" version = "2.28.2+1" [[deps.MozillaCACerts_jll]] uuid = "14a3606d-f60d-562e-9121-12d972cd8159" version = "2023.1.10" [[deps.NetworkOptions]] uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" version = "1.2.0" [[deps.Pkg]] deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"] uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" version = "1.10.0" [[deps.PlutoDevMacros]] deps = ["AbstractPlutoDingetjes", "DocStringExtensions", "HypertextLiteral", "InteractiveUtils", "MacroTools", "Markdown", "Pkg", "Random", "TOML"] git-tree-sha1 = "2944f76ac8c11c913a620da0a6b035e2fadf94c1" uuid = "a0499f29-c39b-4c5c-807c-88074221b949" version = "0.7.2" [[deps.Printf]] deps = ["Unicode"] uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" [[deps.REPL]] deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" [[deps.Random]] deps = ["SHA"] uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [[deps.SHA]] uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" version = "0.7.0" [[deps.Serialization]] uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" [[deps.Sockets]] uuid = "6462fe0b-24de-5631-8697-dd941f90decc" [[deps.TOML]] deps = ["Dates"] uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" version = "1.0.3" [[deps.Tar]] deps = ["ArgTools", "SHA"] uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" version = "1.10.0" [[deps.Tricks]] git-tree-sha1 = "eae1bb484cd63b36999ee58be2de6c178105112f" uuid = "410a4b4d-49e4-4fbc-ab6d-cb71b17b3775" version = "0.1.8" [[deps.UUIDs]] deps = ["Random", "SHA"] uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" [[deps.Unicode]] uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" [[deps.Zlib_jll]] deps = ["Libdl"] uuid = "83775a58-1f1d-513f-b197-d71354ab007a" version = "1.2.13+1" [[deps.nghttp2_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" version = "1.52.0+1" [[deps.p7zip_jll]] deps = ["Artifacts", "Libdl"] uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" version = "17.4.0+2" """ # ╔═╡ Cell order: # ╟─9d4455af-96f1-46d7-a4f3-434495b11c8a # ╠═8db82e94-5c81-4c52-9228-7e22395fb68f # ╠═949ac1ef-c502-4e28-81ff-f99b0d19aa03 # ╠═707175a9-d356-43cf-8038-620ebc401c93 # ╠═cbfc6eec-8991-4a9c-ada0-295c8052854d # ╟─4843983c-df64-4b94-8634-7a10d9423a70 # ╟─a8995224-83c6-4f82-b5a5-87a6f86fc7a0 # ╠═9e3601f5-efc2-44e9-83d8-5b65ce7e9ccf # ╠═cdc0a7ad-a3ac-4270-b707-35b1939da276 # ╟─fe891b4e-f440-4823-b43b-72572f6a6c12 # ╠═86a80228-f495-43e8-b1d4-c93b7b52c8d8 # ╠═2358f686-1950-40f9-9d5c-dac2d98f4c24 # ╟─49516374-f625-4a84-ac5c-f92497d45025 # ╟─8cc53cd2-9114-4067-ab0b-37fd8cd79240 # ╠═0db51d39-7c05-4e00-b951-7fe776a8e0f9 # ╠═e2b79a58-e66e-4d40-8673-418823753b38 # ╟─9d23382c-cf35-4b20-a46c-0f4e2de17fc7 # ╟─959acb40-1fd6-43f5-a1a6-73a6ceaae1d7 # ╠═4d611425-c8e3-4bc3-912b-8bc0465363bc # ╠═a5490a6b-dc11-42b7-87e0-d38870fc55e4 # ╠═705e30fe-77a3-4b06-8b99-1807290edffb # ╟─2ee7f26d-f383-4e7e-a69a-8fb72717467c # ╟─79beba88-932f-4147-b3a0-d821ef1bc1e2 # ╠═63d6c2df-a411-407c-af11-4f5d09fbb322 # ╠═633029af-8cac-426e-b35c-c9fb3938b784 # ╠═065bad73-5fa8-4496-ba33-9e66940b5806 # ╟─2073f11e-8196-4ebc-922f-5fa589e91797 # ╠═811cf78b-e870-45bb-9173-89a3b3d495f5 # ╠═e7d67662-77b3-482a-b032-8db4afbc01a6 # ╠═996b4085-114c-48f4-9f90-8e637f29c06a # ╟─3a066bf4-3466-469e-90d0-6b14be3ed8d5 # ╟─3213d977-7b65-43b0-a881-10fcc2523f14 # ╠═903fee67-6b23-41dc-a03d-f1040b696be6 # ╠═08d711c0-e2cc-4444-94ca-0c4c3cfe901f # ╠═03e9d75e-e6c9-4199-933b-2be306daf978 # ╠═26d11600-2827-4e08-9195-109c8a8bddc3 # ╠═be2a7820-e194-4410-b00d-a9332b234ad6 # ╟─00000000-0000-0000-0000-000000000001 # ╟─00000000-0000-0000-0000-000000000002
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
docs
1295
# PlutoExtras [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://disberd.github.io/PlutoExtras.jl/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://disberd.github.io/PlutoExtras.jl/dev) [![Build Status](https://github.com/disberd/PlutoExtras.jl/actions/workflows/CI.yml/badge.svg?branch=master)](https://github.com/disberd/PlutoExtras.jl/actions/workflows/CI.yml?query=branch%3Amaster) [![Coverage](https://codecov.io/gh/disberd/PlutoExtras.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/disberd/PlutoExtras.jl) [![Aqua QA](https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg)](https://github.com/JuliaTesting/Aqua.jl) This package provides some widgets to be used in Pluto, including an extended version of the TableOfContents from PlutoUI and a new experimental bond container (`BondTable`). See the [documentation](https://disberd.github.io/PlutoExtras.jl/) for more details. This was formerly a non-registered package named PlutoUtils ## Note To check out the functionalities in more detail, check the notebooks located in the test folder at [test/notebooks](./test/notebooks/) (You have to execute them from their original folder within the package folder, or the loading of the package with `@frompackage` will fail.)
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
docs
166
# Basic Widgets This Package exports two basic widgets: `Editable` and `StringOnEnter` ## Editable ```@docs Editable ``` ## StringOnEnter ```@docs StringOnEnter ```
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
docs
226
# PlutoExtras Documentation for [PlutoExtras](https://github.com/disberd/PlutoExtras.jl). ## Outline ```@contents Pages = [ "basic_widgets.md", "latex_equations.md", "toc.md", "structbond.md", ] Depth = 1 ```
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
docs
1825
# LaTeX Equations PlutoExtras provides some convenience functions to display numbered equations using [KaTeX](https://katex.org). The use of KaTeX as opposed to Mathjax as in Markdown is that complex interpolation of Julia variables work better and automatic equation numbering based on the cell position in the notebook is possible. KaTeX [supports](https://katex.org/docs/supported.html) automatic numbering of *equation* environments. While it does not support equation reference and labelling, [this](https://github.com/KaTeX/KaTeX/issues/2003) hack on github shows how to achieve the label functionality. Unfortunately, since automatic numbering in KaTeX uses CSS counters, it is not possible to access the value of the counter at a specific DOM element. We then create a function that loops through all possible katex equation and counts them, putting the relevant number in the appropriate hyperlink innerText to create equation references that automatically update. If one wants the exploit equation referencing with automatic numbering update, this functionality **must be initialized** by having a cell which calls [`initialize_eqref`](@ref) as its last statement (so that the javascript code it generates is sent to the cell output) ## Example ```@raw html <video controls=true> <source src="https://user-images.githubusercontent.com/12846528/264626063-1dd7ca9b-9463-4e27-b1ac-d8b2a860ea9b.mp4" type="video/mp4"> </video> ``` Open the [latex test notebook](https://github.com/disberd/PlutoExtras.jl/blob/master/test/notebooks/latex_equations.jl) to check this functionality in action! !!! note The notebook must be run from the original folder (`test/notebooks`) within the `PlutoExtras` package folder to properly load the PlutoExtras package ## API ```@docs initialize_eqref texeq @texeq_str eqref ```
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
docs
6236
# StructBond Module The StructBondModule submodule of PlutoExtras defines and exports functionality to easily create widgets for custom structure and combine multiple bonds together in a convenient floating side table. !!! note The StructBondModule is currently not re-exported by PlutoExtras so it has to be explicitly used with `using PlutoExtras.StructBondModule` Open the [structbond test notebook static html](https://rawcdn.githack.com/disberd/PlutoExtras.jl/0e3153d29d3b112f93507c042a35b8161a3bb661/html_exports/test_bondstable.jl.html) to see the look of the widgets exported.\ Or open the [related notebook](https://github.com/disberd/PlutoExtras.jl/blob/master/test/notebooks/structbondmodule.jl) directy in Pluto to check their functionality in action! !!! note The notebook must be run from the original folder (`test/notebooks`) within the `PlutoExtras` package folder to properly load the PlutoExtras package ## StructBond Generating automatic widgets for custom structs is quite straightforward with the aid of the [`@fielddata`](@ref) macro and the [`StructBond`](@ref) type. The `StructBond` structure wraps another structure and generates a widget that can be used together with `@bind` to obtain instances of a custom structure. In order to correctly display the widget, the description and widget associated to each field of the structure must be specified either. This can be done either using [`@fielddata`](@ref) as in the example video below or by using the separate [`@fieldbond`](@ref) and [`@fielddescription`](@ref) separately. ```@raw html <video controls=true> <source src="https://user-images.githubusercontent.com/12846528/264639467-ecda1c22-141a-4297-98d7-0667d2e8d5a4.mp4" type="video/mp4"> </video> ``` ## @NTBond Sometimes custom structs are not needed and it would be useful to just use the same nice bond structure of [`StructBond`](@ref) to simply create arbitrary NamedTuples. This is possible with the convenience macro [`@NTBond`](@ref) which can be called as shown below to create a nice display for an interactive bond creating an arbitrary NamedTuple. The macro simply create a [`StructBond`](@ref) wrapping the desired NamedTuple type. ```@raw html <video controls=true> <source src="https://user-images.githubusercontent.com/12846528/264640510-c605d3af-77c8-4752-9b80-8bc85545d566.mp4" type="video/mp4"> </video> ``` ## @BondsList In some cases, one does not want to have a single bond wrapping either a Structure or a NamedTuple because single independent bonds are more convenient. [`@BondsList`](@ref) is a convenience macro to create an object of type [`BondsList`](@ref) which simply allow to add a description to separate bonds and group them all together in a table-like format equivalent to those of [`StructBond`](@ref). !!! note Unlike [`StructBond`](@ref), a BondsList is already composed of bond created with [`@bind`](@ref) and it just groups them up with a description. The output of [`@BondsList`](@ref) is not supposed to be bound to a variable using [`@bind`](@ref).\ The bonds grouped in a BondsList still act and update independently from one another. See the example below for understanding the synthax. The header of a BondsList is shown in an orange background to easily differentiate it from [`StructBond`](@ref). ```@raw html <video controls=true> <source src="https://user-images.githubusercontent.com/12846528/264641605-7ab58c12-2c30-47c3-a93a-d64784c34a71.mp4" type="video/mp4"> </video> ``` ## Popout/popoutwrap The structures above can also be used nested within one another. To facilitate accessing nested structures, one can use the [`Popout`](@ref) type. In its simple form, you can give an instance of a StructBond, a bond wrapping a StructBond or a BondsList as input to Popout to create a table that is hidden behind a popup window. If an instance present, but you want a custom type for which you have defined custom bonds and descriptions with [`@fielddata`](@ref) to appear as popout, you can use the function `popoutwrap(TYPE)` to generate a small icon which hides a popup containing the [`StructBond`](@ref) of the provided type `TYPE`. The StructBond table appears on hover upon the icon, can be made fixed by clicking on the icon and can then be moved around or resized. A double click on the header of the popout hides it again: ```@raw html <video controls=true> <source src="https://user-images.githubusercontent.com/12846528/264643126-cdf19078-70cb-46e2-aeb0-304a05ecf08a.mp4" type="video/mp4"> </video> ``` The ability to also wrap pre-existing bonds around StructBonds is convenient for organizing the various bonds one have in a [`BondsList`](@ref) or [`BondTable`](@ref) As an example, one can create a [`BondsList`](@ref) containing the two [`StructBond`](@ref) bonds generated at the beginning of this notebook (the videos in the [structbond section above](#StructBond)) like in the following example: ```@raw html <video controls=true> <source src="https://user-images.githubusercontent.com/12846528/264645841-263f0cb3-ac79-4fe2-b66a-f8d5a4a70896.mp4" type="video/mp4"> </video> ``` ## BondTable The final convenience structure provided by this module is the [`BondTable`](@ref). It can be created to group a list of bonds in a floating table that stays on the left side of the notebook (similar to the TableOfContents of PlutoUI) and can be moved around and resized or hidden for convenience. The BondTable is intended to be used either with bonds containing [`StructBond`](@ref) or with [`BondsList`](@ref). Future types with similar structure will also be added. Here is an example of a bondtable containing all the examples seen so far. ```@raw html <video controls=true> <source src="https://user-images.githubusercontent.com/12846528/264646632-8c1b3eed-1adf-434b-925a-d57b99fc3c29.mp4" type="video/mp4"> </video> ``` ## API ### Main ```@docs StructBondModule.StructBond StructBondModule.@fielddata StructBondModule.@NTBond StructBondModule.@BondsList StructBondModule.popoutwrap StructBondModule.BondTable ``` ### Secondary/Advanced ```@docs StructBondModule.@fieldbond StructBondModule.@fielddescription StructBondModule.Popout StructBondModule.@popoutasfield StructBondModule.@typeasfield ```
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.7.13
681f89bdd5c1da76b31a524af798efb5eb332ee9
docs
3570
# Extended ToC PlutoExtras defines and export an extension of the TableOfContents from PlutoUI. This alternative ToC just wraps the one from PlutoUI and adds functionality to it. It can be called by having a cell that contains the exported function [`ExtendedTableOfContents`](@ref) ## Functionalities This extended ToC provides the following functionalities: - Hiding Heading/Cells both from ToC and from the notebook visualization - Collapsing Headings within the ToC - Saving the hidden/collapsed status of ToC entries on the notebook file, for persistent state across notebook reload. - Moving groups of cells (below a common heading) around conveniently from the ToC ### Hiding Heading/Cells Hiding headings and all connected cells from notebook view can be done via ExtendedTableOfContents - All cells before the first heading are automatically hidden from the notebook - All hidden cells/headings can be shown by pressing the _eye_ button that appears while hovering on the ToC title. - When the hidden cells are being shown, the hidden headings in the ToC are underlined - Hidden status of specific headings in the notebook can be toggled by pressing on the eye button that appears to the left each heading when hovering over them ### Collapsing Headings in ToC ToC headings are grouped based on heading level, sub-headings at various levels can be collapsed by using the caret symbol that appears to the left of headings in the ToC upon hover. ### Save Hide/Collapsed status on notebook file Preserving the status of collapsed/hidden heading is supported by writing to the notebook file using notebook and cell metadata, allowing to maintain the status even upon reload of Julia/Pluto - When the current collapsed/hidden status of each heading is not reflected in the notebook file, a save icon/button appears on the left of the ToC title upon hover. Clicking the icon saves the current state in the notebook file. ### Changing Headings/Cells order The `ExtendedTableOfContents` allow to re-order the cell groups identified by each heading within the notebook: - Each cell group is identified by the cell containing the heading, plus all the cells below it and up to the next heading (excluded) - Holding the mouse on a ToC heading triggers the ability to move headings around - The target heading is surrounded by a dashed border - While moving the mouse within the ToC, a visual separator appears to indicate the position where the dragged heading will be moved to, depending on the mouse position - Hovering on collapsed headings for at least 300ms opens them up to allow moving headings within collapsed parents - By default, headings can only be moved below or above headings of equal or lower level (H1 < H2 < H3...) - Holding shift during the dragging process allows to put headings before/after any other heading regardless of the level ## Examples Open the [extended ToC test notebook](https://github.com/disberd/PlutoExtras.jl/blob/master/test/notebooks/extended_toc.jl) to check this functionality in action! !!! note The notebook must be run from the original folder (`test/notebooks`) within the `PlutoExtras` package folder to properly load the PlutoExtras package ### State Manipulation ![State_Manipulation](https://user-images.githubusercontent.com/12846528/217245898-5166682d-b41d-4f1e-b71b-4d7f69c8f192.gif) ### Cell Reordering ![Cell_Reordering](https://user-images.githubusercontent.com/12846528/217245256-58e4d537-9547-42ec-b1d8-2994b6bcaf51.gif) ## API ```@docs ExtendedTableOfContents show_output_when_hidden ```
PlutoExtras
https://github.com/disberd/PlutoExtras.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
690
push!(LOAD_PATH, "../src/") using Documenter , AbstractSDRs makedocs(sitename="AbstractSDRs.jl", format = Documenter.HTML(), pages = Any[ "Introduction to AbstractSDRs" => "index.md", "Function list" => "base.md", "Examples" => Any[ "Examples/example_setup.md" "Examples/example_parameters.md" "Examples/example_benchmark.md" "Examples/example_mimo.md" ], ], ); # makedocs(modules = [AbstractSDRs],sitename="AbstractSDRs Documentation", format = Documenter.HTML(prettyurls = false)) deploydocs( repo = "github.com/JuliaTelecom/AbstractSDRs.jl", )
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
4202
module Benchmark # ---------------------------------------------------- # --- Modules & Utils # ---------------------------------------------------- # --- External modules using AbstractSDRs # --- Functions """ Calculate rate based on Julia timing """ function getRate(tInit,tFinal,nbSamples) return nbSamples / (tFinal-tInit); end """ Main call to monitor Rx rate """ function main(radio,samplingRate,mode=:rx) # ---------------------------------------------------- # --- Physical layer and RF parameters # ---------------------------------------------------- # --- Create the radio object in function carrierFreq = 770e6; gain = 50.0; updateSamplingRate!(radio,samplingRate); # --- Print the configuration print(radio); # --- Init parameters # Get the radio size for buffer pre-allocation nbSamples = getBufferSize(radio) # We will get complex samples from recv! method # Fill with random value, as it will be overwritten (and not zero for tx benchmark) sig = randn(Complex{Cfloat},nbSamples); AbstractSDRs.fullScale!(sig) # --- Targeting 2 seconds acquisition # Init counter increment nS = 0; # Max counter definition nbBuffer = 2*samplingRate; # --- Timestamp init if mode == :rx pInit = recv!(sig,radio); else #pInit =send(sig,radio,true;maxNumSamp=nbBuffer); pInit = send(radio,sig) end timeInit = time(); while true # --- Direct call to avoid allocation if mode == :rx p = recv!(sig,radio); # --- Update counter nS += p; elseif mode == :tx #p = send(sig,radio,true;maxNumSamp=nbBuffer); p = send(radio,sig) nS += p; end # --- Interruption if nS > nbBuffer break end end # --- Last timeStamp and rate timeFinal = time(); # --- Getting effective rate radioRate = getSamplingRate(radio) effectiveRate = getRate(timeInit,timeFinal,nS); # --- Free all and return return (radioRate,effectiveRate); end function test(radioName,samplingRate;duration=2,kw...) # ---------------------------------------------------- # --- Physical layer and RF parameters # ---------------------------------------------------- # --- Create the radio object in function carrierFreq = 770e6; gain = 50.0; radio = openSDR(radioName,carrierFreq,samplingRate,gain;kw...) # --- Print the configuration print(radio); @show getBufferSize(radio) # --- Init parameters # Get the radio size for buffer pre-allocation nbSamples = getBufferSize(radio) # We will get complex samples from recv! method sig = zeros(Complex{Cfloat},nbSamples); # --- Targeting 2 seconds acquisition # Init counter increment nS = 0; # Max counter definition nbBuffer = duration*samplingRate; # --- Timestamp init pInit = recv!(sig,radio); timeInit = time(); while true # --- Direct call to avoid allocation p = recv!(sig,radio); # # --- Ensure packet is OK # err = getError(radio); # (p != pInit) && (print(".")); # --- Update counter nS += p; # --- Interruption if nS > nbBuffer break end end # --- Last timeStamp and rate timeFinal = time(); # --- Getting effective rate radioRate = getSamplingRate(radio) effectiveRate = getRate(timeInit,timeFinal,nS); # --- Free all and return close(radio); return (radioRate,effectiveRate); end struct Res radio::Symbol; carrierFreq::Float64; gain::Float64; rateVect::Array{Float64}; effectiveRate::Array{Float64}; radioRate::Array{Float64}; end export Res function benchmark_bench(;radioName=:radioSim,rateVect=[1e3;100e3;500e3;1e6:1e6:8e6;16e6],carrierFreq=770e6,gain=50.0,mode=:rx,args="addr=192.168.10.11") # --- Set priority # --- Configuration effectiveRate = zeros(Float64,length(rateVect)); radioRate = zeros(Float64,length(rateVect)); # --- Setting a very first configuration global radio = openSDR(radioName,carrierFreq,1e6,gain;args) for (iR,targetRate) in enumerate(rateVect) (rR,eR) = main(radio,targetRate,mode); radioRate[iR] = rR; effectiveRate[iR] = eR; end close(radio); strucRes = Res(radioName,carrierFreq,gain,rateVect,effectiveRate,radioRate); # @save "benchmark_UHD.jld2" res; return strucRes; end end
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
2993
# This is an example on how to use MIMO with AbstractSDRs assuming that SDR support several channels. # The following example has been built for a USRP e310 and should work for any multiple channel USRP. # ---------------------------------------------------- # --- Package dependencies # ---------------------------------------------------- using AbstractSDRs using Plots using FFTW # ---------------------------------------------------- # --- Radio parameters # ---------------------------------------------------- radioType = :uhd # We target UHDBindings here carrierFreq = 2410e6 # Carrier frequency (ISM band) samplingRate = 2e6 # Not high but issue with e310 stream :( gain = 50 # In dB # ---------------------------------------------------- # --- MIMO and board specificities # ---------------------------------------------------- # We need to specify the channels and the board as we use a USRP => Note that the way the parameters are set is based on how it is done at UHD level. You can have a look at the mimo example provided by UHD. # This may vary depending on the chosen hardware # /!\ We need to specify how many antenna we want. Be sure that the configuration is handled by the hardware you have otherwise UHD will raise an error (and maybe segfault ?) nbAntennaRx = 2 nbAntennaTx = 0 # Antenna and board config channels = [0;1] # First channel is the first path subdev = "A:0 A:1" # e310 board names # For the antenna, we need to specify the dictionnary of the allocated antenna for both Tx and Rx. In our case we will only do full Rx mode so we only specify the :Rx key antennas = Dict(:Rx => ["TX/RX";"RX2"]) # ---------------------------------------------------- # --- Open radio # ---------------------------------------------------- radio = openSDR( radioType, carrierFreq, samplingRate, gain ; nbAntennaTx, nbAntennaRx, channels, antennas, subdev) # --- Receive a buffer # We specify the size of each buffer # We will have one buffer per channel so a Vector of Vector # sigVect[1] and sigVect[2] will have the same size (of nbSamples) each for a channel nbSamples = 4096 sigVect = recv(radio,nbSamples) # ---------------------------------------------------- # --- Plot the spectrum # ---------------------------------------------------- # Get the rate from the radio using the accessor s = getSamplingRate(radio) # X axis xAx = ((0:nbSamples-1)./nbSamples .- 0.5) * s # PSD y = 10*log10.(abs2.(fftshift(fft(sigVect[1])))) plt = plot(xAx,y,label="First Channel") y = 10*log10.(abs2.(fftshift(fft(sigVect[2])))) plot!(plt,xAx,y,label="Second Channel") xlabel!("Frequency [Hz]") ylabel!("Magnitude [dB]") display(plt) # ---------------------------------------------------- # --- Close radio # ---------------------------------------------------- close(radio)
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
6048
# ---------------------------------------------------- # --- minimalTransceiver.jl # ---------------------------------------------------- # This file is intented to give an example on how we can use tree based network architecture with SDR # This file has to be run on a SDR based SoC that communicated with a remote PC # --------- # | # For instance, a USRP e310 with a julia session runs minimalTransceiver.jl # On the PC side, the backend SDROverNetworks can be used to recover data from the E310 @info "Julia-based minimal transceiver"; using Distributed module E310 # ---------------------------------------------------- # --- Module loading # ---------------------------------------------------- # --- Module dependency using UHDBindings using Distributed using ZMQ @everywhere using Sockets mutable struct Configuration carrierFreq::Float64; samplingRate::Float64; gain::Union{Float64,Int}; Antenna::String; nbSamples::Int; end mutable struct MD error::Cint; timeStamp::Timestamp; end # Setting max piority to avoid CPU congestion function setMaxPriority(); pid = getpid(); run(`renice -n -20 -p $pid`); run(`chrt -p 99 $pid`) end # ---------------------------------------------------- # --- Main call # ---------------------------------------------------- function main(mode,carrierFreq, samplingRate, gain, nbSamples) # --- Setting a very first configuration radio = openUHD(carrierFreq, samplingRate, gain); # --- Configuration socket rtcSocket = ZMQ.Socket(REP); bind(rtcSocket, "tcp://*:5555"); # --- RTT socket for Tx rttSocket = ZMQ.Socket(REQ); bind(rttSocket, "tcp://*:9999"); # --- Socket for broadcast Rx brSocket = ZMQ.Socket(PUB); bind(brSocket, "tcp://*:1111"); # --- Get samples sig = zeros(Complex{Cfloat}, radio.rx.packetSize); cnt = 0; # --- Mode used # mode = :rx; # --- Processing try print(radio); # --- Second order loop setup flag = false; # --- Interruption to update radio config @async begin while (true) # --- We wait in this @async for a reception receiver = ZMQ.recv(rtcSocket); # --- Here, we have receive something # Raise a flag because something happens flag = true; # we create an evaluation here res = Meta.parse(String(receiver)); # and we update the radio and get back the desired feeback level (requestConfig, requestMD, mode, buffer,updateBuffer) = updateUHD!(radio, res,mode); if requestConfig # --- Sending the configuration to Host sendConfig(rtcSocket, radio.rx, nbSamples); end if requestMD sendMD(rtcSocket, radio.rx); end if updateBuffer # --- Replace sig by obtained buffer sig = buffer; end end print(radio) end # if mode == :txbuffer # --- Send data to radio # UHDBindings.send(radio, sig,true); # else while (true) if mode == :rx # --- Direct call to avoid allocation recv!(sig, radio); # --- To UDP socket ZMQ.send(brSocket, sig) yield(); elseif mode == :tx # --- We now transmit data ! # Wait for RTT from host ZMQ.send(rttSocket,0x01); # --- Get the data sig = convert.(Complex{Cfloat},ZMQ.recv(rttSocket)); # --- Send data to radio UHDBindings.send(radio, sig,false); yield(); elseif mode == :txbuffer # --- Send data to radio using cyclic mode nbE = UHDBindings.send(radio, sig,false); (nbE == 0) && (break); yield(); end end catch exception; # --- Release USRP show(exception); end # --- Close UHD close(radio); # --- Close sockets close(rtcSocket); close(rttSocket); close(brSocket); return sig; end # --- To effectively update the radio config function updateUHD!(radio, res,mode) # --- Default output requestConfig = true; requestMD = false; updateBuffer = false; # --- We create the dictionnary entry to update the radio config D = eval(res); # --- Apply the changes buffer = zeros(Complex{Cfloat},1024); for key in keys(D) elem = D[key]; if key == :requestMD # --- We only ask for MD and not config requestMD = true; requestConfig = false; elseif key == :requestConfig # --- Nothing to do elseif key == :updateCarrierFreq # --- Update the carrier freq updateCarrierFreq!(radio, elem); elseif key == :updateSamplingRate # --- Update sampling frequency updateSamplingRate!(radio, elem); elseif key == :updateGain # --- Update Gain println("$elem"); updateGain!(radio, elem); elseif key == :buffer buffer = elem; updateBuffer = true; elseif key == :mode # --- We change mode mode = elem; requestConfig = false; requestMD = true; @info "Change mode to $mode"; else @warn "Unknown Host order. Ask to update $key field with value $elem which is unknwown" end end print(radio) return (requestConfig, requestMD, mode, buffer, updateBuffer); end function sendConfig(rtcSocket, radio, nbSamples) # --- get Configuration from radio config = (radio.carrierFreq, radio.samplingRate, radio.gain, radio.antenna, nbSamples); # --- Send config strF = "$(config)"; ZMQ.send(rtcSocket, strF); end function sendMD(rtcSocket, radio) md = (getTimestamp(radio)..., Cint(getError(radio))); # --- Send config strF = "$(md)"; ZMQ.send(rtcSocket, strF); end end tx() = E310.main(:tx,868e6,4e6,10,(512 + 36) * 2 * 32); txBuffer() = E310.main(:txbuffer,868e6,4e6,10,(512 + 36) * 2 * 32); rx() = E310.main(:rx,868e6,4e6,10,(512 + 36) * 2 * 32); # call main function # E310.main(:rx,868e6,4e6,10,(512 + 36) * 2 * 32); # E310.main(868e6,4e6,10,32768);
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
721
using AbstractSDRs """ A simple sine wave transmitter """ function main() carrierFreq = 868e6 samplingRate = 40e6 gain = 20 sdr = :bladerf #N = 1_000_000 N = 8192 * 16 fc = 0.5e6 fc = -1.0e6; ω = 2*pi * fc / samplingRate; # d = 0.5*[exp(1im*ω.*n) for n ∈ (0:N-1)]; radio = openSDR(sdr,carrierFreq,samplingRate,gain) print(radio) cnt = 0 ϕ = 0 try while(true) d = d * exp(1im*ϕ) ϕ = angle(d[end]) send(radio,d,false) cnt += 1 end catch(exception) close(radio) @info "Transmitted $cnt buffers" rethrow(exception) end end main()
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
1282
using AbstractSDRs C = AbstractSDRs.BladeRFBindings.LibBladeRF carrierFreq = 868e6 samplingRate = 50e6 gain = 12 sdr = AbstractSDRs.openBladeRF(carrierFreq,samplingRate,gain) @info "Initial config" print(sdr) ##sleep(2) @info "Update config" AbstractSDRs.BladeRFBindings.updateCarrierFreq!(sdr,2400e6) AbstractSDRs.BladeRFBindings.updateSamplingRate!(sdr,20e6) AbstractSDRs.BladeRFBindings.updateRFBandwidth!(sdr,15e6) AbstractSDRs.BladeRFBindings.updateGain!(sdr,15) print(sdr) close(sdr) #ptr_bladerf = Ref{Ptr{C.bladerf}}() #status = C.bladerf_open(ptr_bladerf,"") #@info "Open BladeRF with status $status" #@show theChannel = C.BLADERF_CHANNEL_RX(0) #@info "status Carrier is $status" #container = Ref{C.bladerf_sample_rate}(0) #status = C.bladerf_set_sample_rate(ptr_bladerf[],theChannel,convert(C.bladerf_sample_rate,samplingRate),container) #@info "status sampling is $status -> value $(container[])" #container = Ref{C.bladerf_bandwidth}(0) #status = C.bladerf_set_bandwidth(ptr_bladerf[],theChannel,convert(C.bladerf_bandwidth,gain),container) #@info "status band is $status-> value $(container[])" #status = C.bladerf_set_gain(ptr_bladerf[],theChannel,convert(C.bladerf_gain,gain)) #@info "status gain is $status" #C.bladerf_close(ptr_bladerf[])
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
8319
module AbstractSDRs # --- Define core module definitions using Libdl using Printf using Sockets using Reexport import Base:close; # ---------------------------------------------------- # --- Get Supported backends # ---------------------------------------------------- """ Returns an array of symbol which lists the supported SDR backends # --- Syntax l = getSupportedSDR() # --- Input parameters - # --- Output parameters - l : Array of symbols of supported SDRs """ function getSupportedSDRs() return [:uhd;:sdr_over_network;:radiosim;:pluto;:rtlsdr;:bladerf]; end export getSupportedSDRs # ---------------------------------------------------- # --- Utils # ---------------------------------------------------- # Common generic functions and glue required for the package # Nothing strictly related to radio here, only common stuff include("Utils.jl") # ---------------------------------------------------- # --- Backends # ---------------------------------------------------- # --- Load backend include("Backends.jl") # ---------------------------------------------------- # --- Scanning # ---------------------------------------------------- include("Scan.jl") export scan # ---------------------------------------------------- # --- Radio configuration (update radio parameters) # ---------------------------------------------------- include("Mutators.jl") export updateCarrierFreq! export updateSamplingRate! export updateGain! export updateGainMode! # ---------------------------------------------------- # --- Assessors (get radio parameters) # ---------------------------------------------------- include("Assessors.jl") export getError export getTimestamp export getSamplingRate export getCarrierFreq export getGain export isClosed export getBufferSize #---------------------------------------------------- # --- Common API # ---------------------------------------------------- # recv call """ Receive nbSamples from the SDR and fill them in the output buffer. The buffer format depends on the SDR backend # --- Syntax - buffer = recv(radio, nbSamples) # --- Input parameters - radio : SDR object - nbSamples : Desired number of samples # --- Output parameters - buffer : Output buffer from the radio filled with nbSamples samples """ recv(obj::SDROverNetwork,tul...) = SDROverNetworks.recv(obj,tul...); recv(obj::UHDBinding,tul...) = UHDBindings.recv(obj,tul...); recv(obj::RadioSim,tul...) = RadioSims.recv(obj,tul...); recv(obj::RTLSDRBinding,tul...) = RTLSDRBindings.recv(obj,tul...); recv(obj::BladeRFBinding,tul...) = BladeRFBindings.recv(obj,tul...); recv(obj::PlutoSDR,tul...) = AdalmPluto.recv(obj,tul...); export recv; # recv! call """ Receive from the SDR and fill them in the input buffer. # --- Syntax - nbSamples = recv!(sig,radio); # --- Input parameters - sig : Buffer to be filled - radio : SDR device # --- Output parameters - nbSamples : Number of samples filled """ recv!(sig,obj::SDROverNetwork,tul...) = SDROverNetworks.recv!(sig,obj,tul...); recv!(sig,obj::UHDBinding,tul...) = UHDBindings.recv!(sig,obj,tul...); recv!(sig,obj::RadioSim,tul...) = RadioSims.recv!(sig,obj,tul...); recv!(sig,obj::RTLSDRBinding,tul...) = RTLSDRBindings.recv!(sig,obj,tul...); recv!(sig,obj::BladeRFBinding,tul...) = BladeRFBindings.recv!(sig,obj,tul...); recv!(sig,obj::PlutoSDR,tul...) = AdalmPluto.recv!(sig,obj,tul...); # Send call """ Send a buffer though the radio device. It is possible to force a cyclic buffer send (the radio uninterruply send the same buffer) by setting the cyclic parameter to true # --- Syntax send(radio,buffer,cyclic=false) # --- Input parameters - radio : SDR device - buffer : Buffer to be send - cyclic : Send same buffer multiple times (default false) [Bool] # --- Output parameters - nbEch : Number of samples effectively send [Csize_t]. It corresponds to the number of complex samples sent. """ send(obj::SDROverNetwork,sig,tul...;kwarg...) = SDROverNetworks.send(obj,sig,tul...;kwarg...); send(obj::UHDBinding,sig,tul...;kwarg...) = UHDBindings.send(obj,sig,tul...) send(obj::RadioSim,sig,tul...;kwarg...) = RadioSims.send(obj,sig,tul...) send(obj::RTLSDRBinding,sig,tul...;kwarg...) = RTLSDRBindings.send(obj,sig,tul...) send(obj::BladeRFBinding,sig,tul...;kwarg...) = BladeRFBindings.send(obj,sig,tul...) send(obj::PlutoSDR,sig,tul...;kwarg...) = AdalmPluto.send(obj,sig,tul...;parseKeyword(kwarg,[:use_internal_buffer])...) export send """ Open a Software Defined Radio of backend 'type', tune accordingly based on input parameters and use the supported keywords. It returns a radio object, depending on the type of SDR that can be used with all AbstractSDRs supported functions # --- Syntax radio = openSDR(type,carrierFreq,samplingRate,gain,antenna;key) # --- Input parameters - type : Desired SDR type. The different supported radio format can be obtained with getSupportedSDR(); - carrierFreq : Carrier frequency [Hz] - samplingRate : Sampling frequency (Hz) - gain : Analog Rx gain (dB) # --- Output parameters - radio : Defined SDR object """ function openSDR(name::Symbol,tul...;key...) if name == :uhd suppKwargs = [:args;:channels;:antennas;:cpu_format;:otw_format;:subdev;:nbAntennaRx;:nbAntennaTx;:bypassStreamer]; radio = openUHD(tul...;parseKeyword(key,suppKwargs)...); elseif (name == :sdr_over_network || name == :e310) suppKwargs = [:addr]; keyOut = parseKeyword(key,suppKwargs); if haskey(key,:args) # For UHDBindings IP address is set as args="addr=192.168.10.14". We want to support this # We look at args and find addr inside and extract the IP address. Then create a dict entry str = key[:args]; ind = findfirst("addr",str)[1]; # If addr flag is here, convert it into IP if ~isnothing(ind) # --- Getting end of parameter indV = findfirst(",",str[ind:end]); # --- If last parameters, get the compelte string (isnothing(indV)) ? indF = length(str) : indF = indV[1];; # --- Extract ip address ip = str[ind+5:indF]; # --- Create a new input in dictionnary keyOut[:addr] = ip; end end radio = openUhdOverNetwork(tul...;keyOut...); elseif (name == :radiosim) suppKwargs = [:packetSize;:scaleSleep;:buffer]; radio = openRadioSim(tul...;parseKeyword(key,suppKwargs)...); elseif name == :rtlsdr suppKwargs = [:agc_mode;:tuner_gain_mode] radio = openRTLSDR(tul...;parseKeyword(key,suppKwargs)...); elseif name == :bladerf suppKwargs = [] #FIXME specific bladerf call radio = openBladeRF(tul...;parseKeyword(key,suppKwargs)...); elseif name == :pluto # --- List of supported keywords suppKwargs = [:addr; :backend; :bufferSize; :bandwidth]; # --- Managing Int argument # In Pluto the config uses Int parameter, and we specify Float as the top APi of AbstractSDRs. We should convert this # --- Opening radio device radio = openPluto(_toInt.(tul)...; parseKeyword(key, suppKwargs)...); else radio = nothing @error "Unknown or unsupported SDR device. use getSupportedSDR() to list supported SDR backends"; end return radio; end export openSDR; """ Ensure that the input buffer has full scale, i.e the input is between -1 and + 1 This function is inplace. This is usefull for radio that uses Int format, with input that should be normalized. 2 different policies - :same : A common scaling factor is used for both I anbd Q path - :independant : One scaling is used for real and one scaling is used for imag (default policy: :independent) """ function fullScale!(buffer::Vector{Complex{T}},policy=:independent) where T if policy == :independant max_i = maximum(abs.(real(buffer))) max_q = maximum(abs.(imag(buffer))) else max_i = maximum(abs.(real(buffer))) max_q = maximum(abs.(imag(buffer))) (max_i > max_q) && (max_q = max_i) (max_i < max_q) && (max_q = max_q) end for k ∈ eachindex(buffer) buffer[k] = real(buffer[k]) / max_i + 1im*imag(buffer[k]) / max_q end return nothing end end # module
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
2894
# ---------------------------------------------------- # --- Accessor.jl # ---------------------------------------------------- # Function to access to radio parameters getError(obj::UHDBinding) = UHDBindings.getError(obj); getError(obj::RadioSim) = RadioSims.getError(obj); getError(obj::SDROverNetwork) = SDROverNetworks.getMD(obj)[3]; getError(obj::RTLSDRBinding) = RTLSDRBindings.getError(obj); getError(obj::BladeRFBinding) = BladeRFBindings.getError(obj); getTimestamp(obj::UHDBinding) = UHDBindings.getTimestamp(obj); getTimestamp(obj::RadioSim) = RadioSims.getTimestamp(obj); getTimestamp(obj::SDROverNetwork) = SDROverNetworks.getMD(obj)[1:2]; getTimestamp(obj::RTLSDRBinding) = RTLSDRBindings.getTimestamp(obj); getTimestamp(obj::BladeRFBinding) = BladeRFBindings.getTimestamp(obj); """ Get the current sampling rate of the radio device The second parameter (optionnal) speicfies the Rx or Tx board (default : Rx) """ getSamplingRate(obj::AbstractSDR;mode=:rx) = ((mode == :rx) ? Float64(obj.rx.samplingRate) : Float64(obj.tx.samplingRate)) getSamplingRate(obj::PlutoSDR;mode=:rx) = ((mode == :rx) ? Float64(obj.rx.effectiveSamplingRate) : Float64(obj.tx.effectiveSamplingRate)) """ Get the current carrier frequency of the radio device The second parameter (optionnal) speicfies the Rx or Tx board (default : Rx) """ getCarrierFreq(obj::AbstractSDR;mode=:rx) = (mode == :rx) ? Float64(obj.rx.carrierFreq) : Float64(obj.tx.carrierFreq) getCarrierFreq(obj::PlutoSDR;mode=:rx) = (mode == :rx) ? Float64(obj.rx.effectiveCarrierFreq) : Float64(obj.tx.effectiveCarrierFreq) """ Get the current radio gain The second parameter (optionnal) specifies the Rx or Tx board (default : Rx) """ getGain(obj::AbstractSDR;mode=:rx) = (mode == :rx) ? Float64(obj.rx.gain) : Float64(obj.tx.gain) getGain(obj::PlutoSDR;mode=:rx) = AdalmPluto.getGain(obj) """ Check if a SDR has already been closed. The falg is true is the SDR ressources have been released and false otherwise. # --- Syntax flag = isClosed(radio) # --- Input parameters - radio : SDR device # --- Output parameters - flag : True is SDR is already closed, false otherwise """ isClosed(obj::AbstractSDR) = Bool(obj.tx.released) || Bool(obj.rx.released) isClosed(obj::PlutoSDR) = Bool(obj.released) """ Returns the radio packet size. Each radio backend encapsulates the IQ samples into chunks of data. The `recv` command can be used with any size but it can be more efficient to match the desired size with the one provided by the radio # --- Syntax bufferSize = getBufferSize(radio) # --- Input parameters - radio : SDR device # --- Output parameters bufferSize : Size of radio internal buffer """ getBufferSize(obj::AbstractSDR) = obj.rx.packetSize # We get the fields getBufferSize(obj::PlutoSDR) = obj.rx.buf.C_sample_size # For Pluto this is hidden in the buffer config
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
2516
# --------------------------------- # --- UHD Bindings # ---------------------------------------------------- # Backend to pilot USRP with UHD lib @reexport using UHDBindings # --- Specific UHD related functions # We export the UHD structure export UHDBinding # ---------------------------------------------------- # --- Adalm Pluto managment # ---------------------------------------------------- # Backend for Adalm Pluto @reexport using AdalmPluto # --- Specific Pluto exportation # We export the Adalm Pluto structure and the specific updateGainMode function export AdalmPluto; export updateGainMode!; # ---------------------------------------------------- # --- RTL-SDR bindings # ---------------------------------------------------- include("Backends/RTLSDR/RTLSDRBindings.jl"); @reexport using .RTLSDRBindings export RTLSDRBinding # ---------------------------------------------------- # --- BladeRF bindings # ---------------------------------------------------- include("Backends/BladeRF/BladeRFBindings.jl") @reexport using .BladeRFBindings export BladeRFBinding # ---------------------------------------------------- # --- Socket System # ---------------------------------------------------- # --- Create and load module to pilot E310 devices # To control this device we create a pure Socket based system # for which the AbstractSDRs package will help to bind the utils # Have a look on minimalTransceiver.jl for the code to be ran on E310 include("Backends/SDROverNetworks.jl"); @reexport using .SDROverNetworks # --- Specific E310 related functions export SDROverNetwork; # ---------------------------------------------------- # --- Simulation Radio # ---------------------------------------------------- # --- Create and module to emulate a radio device without any actual radio connected include("Backends/RadioSims.jl"); @reexport using .RadioSims # --- Specific simulation related function export updatePacketSize!; export updateBuffer!; export RadioSim; # ---------------------------------------------------- # --- Define common radio type # ---------------------------------------------------- # We define an Union type that gathers all SDR backends # This type will be used as default fallback methods to handle 2 things # - In case of functions not supported in the given backend to obtain a predictible (and non error) behaviour # - To simplify access to similar backends fields AbstractSDR = Union{RadioSim,UHDBinding,PlutoSDR,SDROverNetwork,RTLSDRBinding,BladeRFBinding}
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
3703
# ---------------------------------------------------- # --- Mutators.jl # ---------------------------------------------------- # Functions to update radio configuration and parameters """ Update carrier frequency of current radio device, and update radio object with the new obtained sampling frequency. # --- Syntax updateCarrierFreq!(radio,carrierFreq) # --- Input parameters - radio : SDR device - carrierFreq : New desired carrier frequency # --- Output parameters - carrierFreq : Effective carrier frequency """ updateCarrierFreq!(obj::SDROverNetwork,tul...) = SDROverNetworks.updateCarrierFreq!(obj,tul...); updateCarrierFreq!(obj::UHDBinding,tul...) = UHDBindings.updateCarrierFreq!(obj,tul...); updateCarrierFreq!(obj::RadioSim,tul...) = RadioSims.updateCarrierFreq!(obj,tul...); updateCarrierFreq!(obj::RTLSDRBinding,tul...) = RTLSDRBindings.updateCarrierFreq!(obj,tul...); updateCarrierFreq!(obj::BladeRFBinding,tul...) = BladeRFBindings.updateCarrierFreq!(obj,tul...); function updateCarrierFreq!(obj::PlutoSDR,tul...) # In pluto we only get a flag so we need to call to the accessor AdalmPluto.updateCarrierFreq!(obj,_toInt.(tul)...); return getCarrierFreq(obj) end """ Update sampling rate of current radio device, and update radio object with the new obtained sampling frequency. # --- Syntax updateSamplingRate!(radio,samplingRate) # --- Input parameters - radio : SDR device - samplingRate : New desired sampling rate # --- Output parameters - samplingRate : Effective sampling rate """ updateSamplingRate!(obj::SDROverNetwork,tul...) = SDROverNetworks.updateSamplingRate!(obj,tul...); updateSamplingRate!(obj::UHDBinding,tul...) = UHDBindings.updateSamplingRate!(obj,tul...); updateSamplingRate!(obj::RadioSim,tul...) = RadioSims.updateSamplingRate!(obj,tul...); updateSamplingRate!(obj::RTLSDRBinding,tul...) = RTLSDRBindings.updateSamplingRate!(obj,tul...); function updateSamplingRate!(obj::BladeRFBinding,tul...) BladeRFBindings.updateSamplingRate!(obj,tul...); BladeRFBindings.updateRFBandwidth!(obj,tul...); end function updateSamplingRate!(obj::PlutoSDR,tul...) # For Adalm Pluto we should also update the RF filter band AdalmPluto.updateSamplingRate!(obj,_toInt.(tul)...); fs = getSamplingRate(obj) # Which policy ? Here we use 25% roll off α = 1.00 brf = fs * α AdalmPluto.updateBandwidth!(obj,_toInt.(brf)...); # Update ADC policy (filter coefficients) based on frequency AdalmPluto.ad9361_baseband_auto_rate(C_iio_context_find_device(obj.ctx, "ad9361-phy"), Int(fs)); return fs end """ Update gain of current radio device, and update radio object with the new obtained gain. If the input is a [UHDRx] or a [UHDTx] object, it updates only the Rx or Tx gain # --- Syntax updateGain!(radio,gain) # --- Input parameters - radio : SDR device - gain : New desired gain # --- Output parameters - gain : New gain value """ updateGain!(obj::SDROverNetwork,tul...) = SDROverNetworks.updateGain!(obj,tul...); updateGain!(obj::UHDBinding,tul...) = UHDBindings.updateGain!(obj,tul...); updateGain!(obj::RadioSim,tul...) = RadioSims.updateGain!(obj,tul...); updateGain!(obj::RTLSDRBinding,tul...) = RTLSDRBindings.updateGain!(obj,tul...); updateGain!(obj::BladeRFBinding,tul...) = BladeRFBindings.updateGain!(obj,tul...); function updateGain!(obj::PlutoSDR,tul...) # In pluto we only get a flag so we have to access to gain value to return the updated gain value AdalmPluto.updateGain!(obj,_toInt.(tul)...); return getGain(obj) end """ Define Gain policy for the SDR radio. Only supported on AdalmPluto """ updateGainMode!(sdr::AbstractSDR) = "manual" # No need to redefine for Pluto backend
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
1264
module Printing using Printf # This module is intended to provide fancy macros to display warning export @inforx, @warnrx; export @infotx, @warntx; # ---------------------------------------------------- # --- Fancy prints # ---------------------------------------------------- # To print fancy message with different colors with Tx and Rx function customPrint(str,handler;style...) msglines = split(chomp(str), '\n') printstyled("┌",handler,": ";style...) println(msglines[1]) for i in 2:length(msglines) (i == length(msglines)) ? symb="└ " : symb = "|"; printstyled(symb;style...); println(msglines[i]); end end # define macro for printing Rx info macro inforx(str) quote customPrint($(esc(str)),"Rx";bold=true,color=:light_green) end end # define macro for printing Rx warning macro warnrx(str) quote customPrint($(esc(str)),"Rx Warning";bold=true,color=:light_yellow) end end # define macro for printing Tx info macro infotx(str) quote customPrint($(esc(str)),"Tx";bold=true,color=:light_blue) end end # define macro for printing Tx warning macro warntx(str) quote customPrint($(esc(str)),"Tx Warning";bold=true,color=:light_yellow) end end end
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
4917
# ---------------------------------------------------- # --- Find.jl # ---------------------------------------------------- # Methods to scan for SDR devices, based on backend specifications or parameters """ Scan interface and returns the founded SDR # --- Syntax sdr = scan() sdr = scan(backend;key...) # Input parameter If the function is called without parameters il will search for all available backends such as UHDBindings and AdalmPluto. Otherwise the search will be limited to the desired backend The optionnal arguments are the one supported by UHDBindings and AdalmPluto. See `uhd_find_devices()` in UHDBindings and `scan` function in AdalmPluto # Keywords - args : String used in UHD backend to specify USRP IP address. Example: scan(:uhd;args="addr=192.168.10.16") - backend : Sring used in Pluto backend to specify the interface used ("local", "xml", "ip", "usb") """ function scan(backend::Union{Nothing,Vector{Symbol}}=nothing;key...) # --- If call w/o argument we search for all potential backends # Note that we can not search for SDROverNetwork, RadioSims and RTLSDR # TODO => Scan methods for RTLSDR ? if isnothing(backend) backend = getSupportedSDRs() end allStr = String[]; for b in backend if b == :uhd println("----------------------------") println("--- Scan for UHD devices ---") println("----------------------------") # ---------------------------------------------------- # --- UHD Find device call # ---------------------------------------------------- # --- Restrict keywords to uhd_find_devices key = parseKeyword(key,[:args]) # scan keyword is uhd_find_devices parameter so we should handle empty case (isempty(key)) && (key[:args] = "") # --- Call scanner e = UHDBindings.uhd_find_devices(key[:args]) # --- Return the direct IP address based on the str cal for eN in e eM = eN[findfirst("addr=",eN)[end]+1:end] eM = split(eM,"\n")[1] push!(allStr,eM) end elseif b == :pluto println("------------------------------") println("--- Scan for Pluto devices ---") println("------------------------------") # ---------------------------------------------------- # --- Scan call # ---------------------------------------------------- # --- Restrict keywords to pluto key = parseKeyword(key,[:backend]) if (isempty(key)) # By default we look for all available backends backend = AdalmPluto.getBackends() else # Focus on given backend backend = [key[:backend]] end for b in backend # --- Call scanner eV = AdalmPluto.scan(b) # --- Push in Vector of string # AdalmPluto answer "" and this corresponds to nothing interessting. We push in the vector only if what we had was not empty for e in eV (!isempty(e)) && (push!(allStr,e)) end end elseif b == :radiosim # ---------------------------------------------------- # --- Radiosims backend # ---------------------------------------------------- # No need to worry, we always have the simulated backend # Returns an arbitrary String with description println("------------------------------") println("--- Scan for RadioSims ---") println("------------------------------") push!(allStr,"RadioSim backend is always there !") elseif b == :rtlsdr # ---------------------------------------------------- # --- RTLSDR scanning mode # ---------------------------------------------------- println("------------------------------") println("--- Scan for RTL-SDR ---") println("------------------------------") nE = RTLSDRBindings.scan() if nE > 0 push!(allStr,"RTL-SDR USB dongle") end elseif b == :bladerf # ---------------------------------------------------- # --- BladeRF scanning mode # ---------------------------------------------------- println("------------------------------") println("--- Scan for BladeRF ---") println("------------------------------") str = BladeRFBindings.scan() (!isempty(str)) && (push!(allStr,str)) end end return allStr end scan(backend::Symbol;key...) = scan([backend];key...)
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
1158
# ---------------------------------------------------- # --- Utils.jl # ---------------------------------------------------- # We put here common usefull stuff for SDR managment # --- Container for Radio use # We will have functions from different origin and different supported keywords # This function parse the input keywords and returns the ones supported by the function, listed in iteration function parseKeyword(kwargs,iteration) # We populate a new dictionnary based on the input keywords and the supported ones # In order not to create keywords that are not supported (i.e leaving the default value) # we only evaluate the keywords defined both in the 2 dictionnaries # This means that the default fallback should never happen kwargs = Dict(key=>get(kwargs,key,0) for key in intersect(iteration,keys(kwargs))) return kwargs end # --- Conversion # Adalm Pluto structure is based on Int parameters, and AbstractSDRs use massively Float. We need to convert just before dispatching. As some parameter may be float (as gain) we should round before conversion. The following function does that. _toInt(x) = Int(round(x));
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
10167
module RadioSims using Printf # --- Print radio config include("../Printing.jl"); using .Printing; # Methods extension import Base:close; # Symbols exportation export openRadioSim; export updateCarrierFreq!; export updateSamplingRate!; export updateGain!; export updatePacketSize!; export updateBuffer!; export recv; export recv!; export send; export print; export getError export getTimeStamp; # export RadioSim; # --- Main Rx structure mutable struct RadioSimRxWrapper circularBuffer::Vector{Complex{Cfloat}}; pointerBuffer::Int; buffer::Vector{Complex{Cfloat}}; sleepVal::Cint; scaleSleep::Float64; doCirc::UInt8; end; mutable struct RadioSimRx radioSim::RadioSimRxWrapper; carrierFreq::Float64; samplingRate::Float64; gain::Union{Int,Float64}; antenna::String; packetSize::Csize_t; released::Int; end # --- Main Tx structure mutable struct RadioSimTxWrapper sleepVal::Cint; scaleSleep::Float64; end; mutable struct RadioSimTx radioSim::RadioSimTxWrapper; carrierFreq::Float64; samplingRate::Float64; gain::Union{Int,Float64}; antenna::String; packetSize::Csize_t; released::Int; end # --- Complete structure mutable struct RadioSim radio::String; rx::RadioSimRx; tx::RadioSimTx; end usleep(usecs) = ccall(:usleep, Cint, (Cuint,), usecs); usleep(rx::RadioSimRx) = usleep(rx.radioSim.sleepVal); usleep(tx::RadioSimTx) = usleep(tx.radioSim.sleepVal); " Fill the output buffer with inputBuffer samples If lenght(outputBuffer) < length(inputBuffer) ==> truncate inputBuffer If lenght(outputBuffer) = length(inputBuffer) ==> fill with inputBuffer If lenght(outputBuffer) > length(inputBuffer) ==> repeat inputBuffer It returns the pointer position of inputBuffer (position of last filled data, modulo inputBuffer size) " function circularFill!(outputBuffer,inputBuffer) sO = length(outputBuffer); sI = length(inputBuffer); if sO ≤ sI # ---------------------------------------------------- # --- Buffer fill # ---------------------------------------------------- @inbounds @simd for n ∈ 1 : sO outputBuffer[n] = inputBuffer[n]; end return mod(sO,sI); else # ---------------------------------------------------- # --- Several rotation to do # ---------------------------------------------------- nbSeg = sO ÷ sI; rest = sO - sI*nbSeg; pos = 0; @inbounds @simd for p ∈ 1 : nbSeg offS = (p-1)*sI; for n ∈ 1 : sI outputBuffer[offS + n] = inputBuffer[n]; end end @inbounds @simd for n ∈ 1 : rest outputBuffer[n] = inputBuffer[n]; end return rest; end end function openRadioSim(carrierFreq,samplingRate,gain;antenna="RX2",packetSize=-1,scaleSleep=1/1.60,buffer=nothing) # ---------------------------------------------------- # --- Create the runtime structures # ---------------------------------------------------- # --- Create the Rx wrapper if buffer === nothing # --- Define packet size (packetSize == -1 ) && (packetSize = 1024) # --- Define random buffer buffer = randn(Complex{Cfloat},packetSize); circularBuffer = buffer; doCirc = false; else (packetSize == -1 ) && (packetSize = length(buffer)) #@assert packetSize ≤ length(buffer) "Packet size should be ≤ to the given circular buffer"; # TODO handle repeat system if not if length(buffer) == packetSize doCirc = false; else # We will emulate a circular buffer doCirc= true; end circularBuffer = buffer; buffer = zeros(Complex{Cfloat},packetSize); circularFill!(buffer,circularBuffer); # We populate end sleepVal = Cint(0); radioSimRxWrapper = RadioSimRxWrapper(circularBuffer,0,buffer,sleepVal,scaleSleep,doCirc); rx = RadioSimRx(radioSimRxWrapper,carrierFreq,samplingRate,gain,antenna,packetSize,0); # --- Create the Tx Wrapper radioSimTxWrapper = RadioSimTxWrapper(sleepVal,scaleSleep); tx = RadioSimTx(radioSimTxWrapper,carrierFreq,samplingRate,gain,antenna,packetSize,0); # ---- Create the complete Radio radio = RadioSim("radioSim",rx,tx); # ---------------------------------------------------- # --- Update the radio component # ---------------------------------------------------- # --- We should update the sampling rate as it will set the appropriate sleeping duration associated top the emulation of rate updateSamplingRate!(radio,samplingRate); # --- Return the radio object return radio; end function updateCarrierFreq!(radio::RadioSim,carrierFreq); radio.rx.carrierFreq = carrierFreq; radio.tx.carrierFreq = carrierFreq; return carrierFreq; end function updateGain!(radio::RadioSim,gain); radio.rx.gain = gain; radio.tx.gain = gain; return gain; end function updateSamplingRate!(radio::RadioSim,samplingRate); # --- We have to calculate the new sleeping value in μs sleepVal = Cint(floor( radio.rx.packetSize / samplingRate * radio.rx.radioSim.scaleSleep * 1e6)); # (sleepVal == 0) && @warn "Sleep val is 0 => rate may be affected"; radio.rx.radioSim.sleepVal = 0#sleepVal; radio.tx.radioSim.sleepVal = 0#sleepVal; # --- Update the sampling rate flag of the radio radio.rx.samplingRate = samplingRate; radio.tx.samplingRate = samplingRate; # --- Return the rate return samplingRate; end function Base.print(rx::RadioSimRx); strF = @sprintf(" Carrier Frequency: %2.3f MHz\n Sampling Frequency: %2.3f MHz\n Rx Gain: %2.2f dB\n",rx.carrierFreq/1e6,rx.samplingRate/1e6,rx.gain); @inforx "Current Simulated Radio Configuration in Rx mode\n$strF"; end function Base.print(tx::RadioSimTx); strF = @sprintf(" Carrier Frequency: %2.3f MHz\n Sampling Frequency: %2.3f MHz\n Rx Gain: %2.2f dB\n",tx.carrierFreq/1e6,tx.samplingRate/1e6,tx.gain); @inforx "Current Simulated Radio Configuration in Rx mode\n$strF"; end function Base.print(radio::RadioSim) print(radio.rx); print(radio.tx); end function recv(radio::RadioSim,packetSize) sig = zeros(Complex{Cfloat},packetSize); recv!(sig,radio); return sig; end function recv!(sig::Vector{Complex{Cfloat}},radio::RadioSim) # @assert length(sig) == radio.rx.packetSize; packetSize = length(sig); if radio.rx.radioSim.doCirc == false # ---------------------------------------------------- # --- Single shot output based in buffer field # ---------------------------------------------------- if packetSize ≤ radio.rx.packetSize # --- Everything is fine => Emulate radio time # usleep(radio.rx); # --- Return the previsouly stored buffer sig .= radio.rx.radioSim.buffer[1:packetSize]; else @warn "Need additionnal processing as required buffer is larger than the one in memory. Please consider to enlarge the radio packet size using updatePacketSize!"; # --- We want larger size than stored in the object, not a good idea nbSeg = 1 + packetSize ÷ radio.rx.packetSize; newBuff = repeat(radio.rx.radioSim.buffer,nbSeg); # --- Everything is fine => Emulate radio time # usleep(radio.rx); # sig .= newBuff[1:packetSize]; end else # ---------------------------------------------------- # --- Circular buffer emulation # ---------------------------------------------------- # --- Everything is fine => Emulate radio time mP = length(radio.rx.radioSim.circularBuffer); if packetSize ≤ mP # --- We take only a part of the circular buffer, and we updat the pointer # usleep(radio.rx); # Copy circular buffer part in working buffer radio.rx.radioSim.pointerBuffer for n ∈ 1 : packetSize pos = 1 + mod(radio.rx.radioSim.pointerBuffer + n - 1,length(radio.rx.radioSim.circularBuffer)); sig[n] = radio.rx.radioSim.circularBuffer[pos]; end # sig .= radio.rx.radioSim.circularBuffer[radio.rx.radioSim.pointerBuffer .+ 1:packetSize]; # Update circularBuffer pointer position radio.rx.radioSim.pointerBuffer += packetSize; # Circular buffer update (modulo) radio.rx.radioSim.pointerBuffer = mod(radio.rx.radioSim.pointerBuffer,length(radio.rx.radioSim.circularBuffer)); else # --- We ask for more than the circular buffer, so repeat several time the circular buffer. # Number of time we repeat nbSeg = 1 + packetSize ÷ mP; # Last chunk of data rest = nbSeg * mP - packetSize; # We need to repeat the circular buffer but not starting at first index. We use the pointer in memory cB = circshift(radio.rx.radioSim.circularBuffer,radio.rx.radioSim.pointerBuffer); # Filling input buffer rest = circularFill!(sig,cB); # --- End of filled signal is next beginning radio.rx.radioSim.pointerBuffer = rest; end end return packetSize; end function send(radio::RadioSim,sig::Vector{Complex{Cfloat}},flag::Bool=false) while(flag) # usleep(radio.tx); end end function updatePacketSize!(radio,packetSize) # --- Create a new buffer buffer = randn(Complex{Cfloat},packetSize); # --- Update structure radio.rx.radioSimRxWrapper.buffer = buffer; end function updateBuffer!(radio,buffer) radio.rx.radioSimRxWrapper.buffer = buffer; radio.rx.radioSimRxWrapper.circularBuffer = buffer; radio.rx.radioSimRxWrapper.pointerBuffer = 0; end function Base.close(radio::RadioSim) radio.rx.released = true radio.tx.released = true end function getError(radio::RadioSim) return nothing; end function getTimeStamp(radio::RadioSim) return time(); end end
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
12559
# uhdOverNetwork.jl # This module provides bind to monitor uhdOverNetwork based device from a Host PC # As the uhdOverNetwork is a SoC based device with ARM, the Host <-> uhdOverNetwork link is assumed to be done with the use of sockets. # With this module we construct utils to use the uhdOverNetwork device with same functions as it is a classic UHD device. # This is quite similar with the uhd_network_mode with some important difference # - We use a specific communication system socket # - uhdOverNetwork side: a Julia script has to be launched. This script can also be modified to embed additional processing module SDROverNetworks # --- Module dependency using Sockets using ZMQ using Printf # --- Print radio config include("../Printing.jl"); using .Printing # --- Method extension import Sockets:send; import Sockets:recv; import ZMQ:recv; import ZMQ:send; import ZMQ:close; import Sockets:close; # --- Symbol exportation export openUhdOverNetwork; export updateCarrierFreq!; export updateSamplingRate!; export updateGain!; export recv; export recv!; export print; struct SocketsuhdOverNetwork ip::IPAddr; rtcSocket::Socket; rttSocket::Socket; brSocket::Socket; end mutable struct Configuration carrierFreq::Float64; samplingRate::Float64; gain::Union{Float64,Int}; Antenna::String; packetSize::Int; end mutable struct MD intPart::Int32; fracPart::Cdouble; error::Int32; end mutable struct SDROverNetworkRx sockets::SocketsuhdOverNetwork; carrierFreq::Float64; samplingRate::Float64; gain::Union{Int,Float64}; antenna::String; packetSize::Csize_t; released::Int; end mutable struct SDROverNetworkTx sockets::SocketsuhdOverNetwork; carrierFreq::Float64; samplingRate::Float64; gain::Union{Int,Float64}; antenna::String; packetSize::Csize_t; released::Int; end mutable struct SDROverNetwork radio::String; rx::SDROverNetworkRx; tx::SDROverNetworkTx; end export SDROverNetwork; function initSockets(ip::String) # --- Format e310 IP address e310Address = IPv4(ip); # --- Configuration Socket # Socket used to send configuration and get configuration back rtcSocket = ZMQ.Socket(REQ); ZMQ.connect(rtcSocket,"tcp://$e310Address:5555"); # --- Tx socket # Socket used to transmit data from Host to e310 (Tx link) rttSocket = ZMQ.Socket(REP); ZMQ.connect(rttSocket,"tcp://$e310Address:9999"); # --- Rx socket # Socket used for e310 to broacast Rx stream brSocket = Socket(SUB); # Define IPv4 adress tcpSys = string("tcp://$e310Address:1111"); ZMQ.subscribe(brSocket); ZMQ.connect(brSocket,tcpSys); # --- Global socket packet sockets = SocketsuhdOverNetwork(e310Address,rtcSocket,rttSocket,brSocket); return sockets end """ Open a uhdOverNetwork remote device and initialize the sockets --- Syntax openUhdOverNetwork(carrierFreq,samplingRate,gain,antenna="RX2";ip="192.168.10.11") # --- Input parameters - carrierFreq : Desired Carrier frequency [Union{Int,Float64}] - samplingRate : Desired bandwidth [Union{Int,Float64}] - gain : Desired Rx Gain [Union{Int,Float64}] Keywords - ip : uhdOverNetwork IP address - antenna : Desired Antenna alias (default "TX-RX") [String] # --- Output parameters - structuhdOverNetwork : Structure with uhdOverNetwork parameters [SDROverNetwork] """ function openUhdOverNetwork(carrierFreq,samplingRate,gain;antenna="RX2",addr="192.168.10.11") # --- Create the Sockets sockets = initSockets(addr); # --- Create the initial configuration based on input parameters rx = SDROverNetworkRx( sockets, carrierFreq, samplingRate, gain, antenna, 0, 0 ); tx = SDROverNetworkTx( sockets, carrierFreq, samplingRate, gain, antenna, 0, 0 ); # --- Instantiate the complete radio radio = SDROverNetwork( addr, rx, tx ); # --- Update the radio based on input parameters updateCarrierFreq!(radio,carrierFreq); updateSamplingRate!(radio,samplingRate); updateGain!(radio,gain); # Get socket size requestConfig!(radio); # --- Print the configuration print(radio); # --- Return the final object return radio; end function Base.close(radio::SDROverNetwork) # @info "coucou" # --- We close here all the related sockets close(radio.rx.sockets.rtcSocket); close(radio.rx.sockets.rttSocket); close(radio.rx.sockets.brSocket); end sendConfig(uhdOverNetwork::SDROverNetwork,mess) = send(uhdOverNetwork.rx.sockets.rtcSocket,mess) function updateCarrierFreq!(uhdOverNetwork::SDROverNetwork,carrierFreq) # --- Create char with command to be transmitted # strF = "global carrierFreq = $carrierFreq"; strF = "Dict(:updateCarrierFreq=>$carrierFreq);"; # --- Send the command sendConfig(uhdOverNetwork,strF); # --- Get the effective radio configuration config = getuhdOverNetworkConfig(uhdOverNetwork); # --- Update the uhdOverNetwork object based on real radio config uhdOverNetwork.rx.carrierFreq = config.carrierFreq; uhdOverNetwork.tx.carrierFreq = config.carrierFreq; return uhdOverNetwork.rx.carrierFreq; end function updateSamplingRate!(uhdOverNetwork::SDROverNetwork,samplingRate) # --- Create char with command to be transmitted strF = "Dict(:updateSamplingRate=>$samplingRate);"; # --- Send the command sendConfig(uhdOverNetwork,strF); # --- Get the effective radio configuration config = getuhdOverNetworkConfig(uhdOverNetwork); # --- Update the uhdOverNetwork object based on real radio config uhdOverNetwork.rx.samplingRate = config.samplingRate; uhdOverNetwork.tx.samplingRate = config.samplingRate; return uhdOverNetwork.rx.samplingRate; end function updateGain!(uhdOverNetwork::SDROverNetwork,gain) # --- Create char with command to be transmitted strF = "Dict(:updateGain=>$gain);"; # --- Send the command sendConfig(uhdOverNetwork,strF); # --- Get the effective radio configuration config = getuhdOverNetworkConfig(uhdOverNetwork); # --- Update the uhdOverNetwork object based on real radio config uhdOverNetwork.rx.gain = config.gain; uhdOverNetwork.tx.gain = config.gain; return uhdOverNetwork.rx.gain; end function requestConfig!(uhdOverNetwork::SDROverNetwork); # --- Create char with command to be transmitted strF = "Dict(:requestConfig=>1);"; # --- Send the command sendConfig(uhdOverNetwork,strF); # --- Get the effective radio configuration config = getuhdOverNetworkConfig(uhdOverNetwork); uhdOverNetwork.rx.packetSize = config.packetSize; uhdOverNetwork.tx.packetSize = config.packetSize; end function setRxMode(uhdOverNetwork::SDROverNetwork) # --- Create char with command to be transmitted strF = "Dict(:mode=>:rx);"; # --- Send the command sendConfig(uhdOverNetwork,strF); receiver = recv(uhdOverNetwork.rx.sockets.rtcSocket); end function recv(uhdOverNetwork::SDROverNetwork,packetSize) # --- Create container sig = Vector{Complex{Cfloat}}(undef,packetSize); # --- fill the stuff recv!(sig,uhdOverNetwork); return sig; end function recv!(sig::Vector{Complex{Cfloat}},uhdOverNetwork::SDROverNetwork;packetSize=0,offset=0) # setRxMode(uhdOverNetwork); # --- Defined parameters for multiple buffer reception filled = false; # --- Fill the input buffer @ a specific offset if offset == 0 posT = 0; else posT = offset; end # --- Managing desired size and buffer size if packetSize == 0 # --- Fill all the buffer packetSize = length(sig); else packetSize = packetSize; # --- Ensure that the allocation is possible @assert packetSize < (length(sig)+posT) "Impossible to fill the buffer (number of samples > residual size"; end while !filled # --- Get a buffer: We should have radio.packetSize or less # radio.packetSize is the complex size, so x2 (posT+uhdOverNetwork.rx.packetSize> packetSize) ? n = packetSize - posT : n = uhdOverNetwork.rx.packetSize; # --- UDP recv. This allocs. This is bad. No idea how to use prealloc pointer without rewriting the stack. tmp = reinterpret(Complex{Cfloat},recv(uhdOverNetwork.rx.sockets.brSocket)); sig[posT .+ (1:n)] .= @view tmp[1:n]; # --- Update counters posT += n; # --- Breaking flag (posT == packetSize) ? filled = true : filled = false; end return posT end #FIXME: We have setTxMode call before each Tx. Shall we do a setRxMode before each rx frame ? function setTxMode(uhdOverNetwork::SDROverNetwork) # --- Create char with command to be transmitted strF = "Dict(:mode=>:tx);"; # --- Send the command sendConfig(uhdOverNetwork,strF); receiver = recv(uhdOverNetwork.rx.sockets.rtcSocket); end function setTxBufferMode(uhdOverNetwork::SDROverNetwork) # --- Create char with command to be transmitted strF = "Dict(:mode=>:txbuffer);"; # --- Send the command sendConfig(uhdOverNetwork,strF); receiver = recv(uhdOverNetwork.rx.sockets.rtcSocket); end function sendBuffer(buffer::Vector{Complex{Cfloat}},uhdOverNetwork::SDROverNetwork) # --- Create char with command to be transmitted strF = "Dict(:buffer:=>$buffer);"; # --- Send the command sendConfig(uhdOverNetwork,strF); config = getuhdOverNetworkConfig(uhdOverNetwork); return config; end function send(sig::Vector{Complex{Cfloat}},uhdOverNetwork::SDROverNetwork,cyclic=false;maxNumSamp=nothing) # --- Setting radio in Tx mode # setTxMode(uhdOverNetwork); nS = 0; it = length(sig); if cyclic == true # ---------------------------------------------------- # --- We handle Tx through metadata # ---------------------------------------------------- # setTxBufferMode(uhdOverNetwork): config = sendBuffer(sig,uhdOverNetwork); else # ---------------------------------------------------- # --- Using RTT socket to handle data exchange # ---------------------------------------------------- try # --- First while loop is to handle cyclic transmission # It turns to false in case of interruption or cyclic to false while (true) # --- Wait for RTT rtt = ZMQ.recv(uhdOverNetwork.tx.sockets.rttSocket); # --- Sending data to Host ZMQ.send(uhdOverNetwork.tx.sockets.rttSocket,sig); # --- Update counter nS += it; # --- Detection of cyclic mode (maxNumSamp !== nothing && nS > maxNumSamp) && break (cyclic == false ) && break # --- Forcing refresh yield(); end catch e; # --- Interruption handling print(e); print("\n"); @info "Interruption detected"; return 0; end end return nS; end function getuhdOverNetworkConfig(uhdOverNetwork::SDROverNetwork) receiver = recv(uhdOverNetwork.rx.sockets.rtcSocket); res = Meta.parse(String(receiver)) config = eval(res); return Configuration(config...); end function Base.print(uhdOverNetwork::SDROverNetwork) strF = @sprintf(" Carrier Frequency: %2.3f MHz\n Sampling Frequency: %2.3f MHz\n Rx Gain: %2.2f dB\n",uhdOverNetwork.rx.carrierFreq/1e6,uhdOverNetwork.rx.samplingRate/1e6,uhdOverNetwork.rx.gain); @inforx "Current uhdOverNetwork Configuration in Rx mode\n$strF"; strF = @sprintf(" Carrier Frequency: %2.3f MHz\n Sampling Frequency: %2.3f MHz\n Rx Gain: %2.2f dB\n",uhdOverNetwork.tx.carrierFreq/1e6,uhdOverNetwork.tx.samplingRate/1e6,uhdOverNetwork.tx.gain); @infotx "Current uhdOverNetwork Configuration in Tx mode\n$strF"; end function getMD(uhdOverNetwork::SDROverNetwork) # --- Create char with command to be transmitted strF = "Dict(:requestMD=>1);"; # --- Send the command sendConfig(uhdOverNetwork,strF); # --- Get the MD back receiver = recv(uhdOverNetwork.rx.sockets.rtcSocket); res = Meta.parse(String(receiver)) # --- Convert to a MD structure md = eval(res) return md; end end
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
17392
module BladeRFBindings # --- Print radio config include("../../Printing.jl"); using .Printing # -- Loading driver bindings include("./LibBladeRF.jl") using .LibBladeRF using Printf # Methods extension import Base:close; # Symbols exportation export openBladeRF export updateCarrierFreq!; export updateSamplingRate!; export updateGain!; export recv; export recv!; export print; export BladeRFBinding; # ---------------------------------------------------- # --- High level structures # ---------------------------------------------------- mutable struct BladeRFRxWrapper channel::Int buffer::Vector{Int16} ptr_metadata::Ref{bladerf_metadata} end mutable struct BladeRFTxWrapper channel::Int buffer::Vector{Int16} ptr_metadata::Ref{bladerf_metadata} end # --- Main Rx structure mutable struct BladeRFRx bladerf::BladeRFRxWrapper carrierFreq::bladerf_frequency samplingRate::bladerf_sample_rate gain::bladerf_gain rfBandwidth::bladerf_bandwidth antenna::String packetSize::Csize_t released::Int end # --- Main Tx structure mutable struct BladeRFTx bladerf::BladeRFTxWrapper carrierFreq::bladerf_frequency samplingRate::bladerf_sample_rate gain::bladerf_gain rfBandwidth::bladerf_bandwidth antenna::String packetSize::Csize_t released::Int end # --- Complete structure mutable struct BladeRFBinding radio::Ref{Ptr{bladerf}} rx::BladeRFRx tx::BladeRFTx released::Bool end # ---------------------------------------------------- # --- Methods call # ---------------------------------------------------- """ Init an empty string of size n, filled with space. Usefull to have container to get string from UHD. """ initEmptyString(n) = String(ones(UInt8,n)*UInt8(32)) # udev rules --> /etc/rules.d/88-nuand-bladerf2.rules # # Nuand bladeRF 2.0 micro # ATTR{idVendor}=="2cf0", ATTR{idProduct}=="5250", MODE="660", GROUP="@BLADERF_GROUP@" function openBladeRF(carrierFreq,samplingRate,gain;agc_mode=0,packet_size=4096) # ---------------------------------------------------- # --- Create Empty structure to open radio # ---------------------------------------------------- ptr_bladerf = Ref{Ptr{bladerf}}() status = bladerf_open(ptr_bladerf,"") #@info "Open BladeRF with status $status" if status < 0 @error "Unable to open the BladeRF SDR. Status error $status" return nothing end # Load FPGA #status = bladerf_load_fpga(ptr_bladerf[],"./hostedxA9.rbf") #sleep(1) rfBandwidth = samplingRate * 0.66 # ---------------------------------------------------- # --- Rx Configuration # ---------------------------------------------------- # Instantiate the first channel of the radio theChannelRx = LibBladeRF.BLADERF_CHANNEL_RX(0) # --- Instantiate carrier freq bladerf_set_frequency(ptr_bladerf[],theChannelRx,carrierFreq) container = Ref{bladerf_frequency}(0) bladerf_get_frequency(ptr_bladerf[],theChannelRx,container) effective_carrierFreq = container[] # --- Instantiate ADC rate container = Ref{bladerf_sample_rate}(0) status = bladerf_set_sample_rate(ptr_bladerf[],theChannelRx,convert(bladerf_sample_rate,samplingRate),container) effective_sampling_rate = container[] # --- Instantiate RF band container = Ref{bladerf_bandwidth}(0) status = bladerf_set_bandwidth(ptr_bladerf[],theChannelRx,convert(bladerf_bandwidth,rfBandwidth),container) effective_rf_bandwidth = container[] # --- Set up gain bladerf_set_gain_mode(ptr_bladerf[],theChannelRx,bladerf_gain_mode(agc_mode)) status = bladerf_set_gain(ptr_bladerf[],theChannelRx,convert(bladerf_gain,gain)) container = Ref{bladerf_gain}(0) bladerf_get_gain(ptr_bladerf[],theChannelRx,container) effective_gain = container[] # ---------------------------------------------------- # --- Tx config # ---------------------------------------------------- # Instantiate the first channel of the radio theChannelTx = LibBladeRF.BLADERF_CHANNEL_TX(0) # --- Instantiate carrier freq bladerf_set_frequency(ptr_bladerf[],theChannelTx,carrierFreq) container = Ref{bladerf_frequency}(0) bladerf_get_frequency(ptr_bladerf[],theChannelTx,container) effective_carrierFreq = container[] # --- Instantiate ADC rate container = Ref{bladerf_sample_rate}(0) status = bladerf_set_sample_rate(ptr_bladerf[],theChannelTx,convert(bladerf_sample_rate,samplingRate),container) effective_sampling_rate = container[] # --- Instantiate RF band container = Ref{bladerf_bandwidth}(0) status = bladerf_set_bandwidth(ptr_bladerf[],theChannelTx,convert(bladerf_bandwidth,rfBandwidth),container) effective_rf_bandwidth = container[] # --- Set up gain bladerf_set_gain_mode(ptr_bladerf[],theChannelTx,bladerf_gain_mode(agc_mode)) status = bladerf_set_gain(ptr_bladerf[],theChannelTx,convert(bladerf_gain,gain)) container = Ref{bladerf_gain}(0) bladerf_get_gain(ptr_bladerf[],theChannelTx,container) effective_gain = container[] # ---------------------------------------------------- # --- Configure Rx Streamer as sync structure # ---------------------------------------------------- # API should customize the sync parameter status = bladerf_sync_config(ptr_bladerf[],BLADERF_RX_X1,BLADERF_FORMAT_SC16_Q11,16,packet_size*2,8,10000) # Enable the module status = bladerf_enable_module(ptr_bladerf[], BLADERF_RX, true); # Metadata metadata_rx = bladerf_metadata(bladerf_timestamp(0),BLADERF_META_FLAG_RX_NOW,1,1,ntuple(x->UInt8(1), 32)) ptr_metadata_rx = Ref{bladerf_metadata}(metadata_rx); # ---------------------------------------------------- # --- Configure Tx Streamer as sync structure # ---------------------------------------------------- # API should customize the sync parameter status = bladerf_sync_config(ptr_bladerf[],BLADERF_TX_X1,BLADERF_FORMAT_SC16_Q11,16,packet_size*2,8,10000) # Enable the module status = bladerf_enable_module(ptr_bladerf[], BLADERF_TX, true); # Metadata flag = BLADERF_META_FLAG_TX_BURST_START | BLADERF_META_FLAG_TX_NOW | BLADERF_META_FLAG_TX_BURST_END metadata_tx = bladerf_metadata(bladerf_timestamp(0),flag,1,1,ntuple(x->UInt8(1), 32)) ptr_metadata_tx = Ref{bladerf_metadata}(metadata_tx); # ---------------------------------------------------- # --- Wrap all into a custom structure # ---------------------------------------------------- # Instantiate a buffer to handle async receive. Size is arbritrary and will be modified afterwards bufferTx = zeros(Int16,packet_size*2) bufferRx = zeros(Int16,packet_size*2) bladeRFRx = BladeRFRxWrapper(theChannelRx,bufferRx,ptr_metadata_rx) bladeRFTx = BladeRFTxWrapper(theChannelTx,bufferTx,ptr_metadata_tx) rx = BladeRFRx( bladeRFRx, effective_carrierFreq, effective_sampling_rate, effective_gain, effective_rf_bandwidth, "RX", packet_size, 0 ); tx = BladeRFTx( bladeRFTx, effective_carrierFreq, effective_sampling_rate, effective_gain, effective_rf_bandwidth, "TX", packet_size, 0 ); radio = BladeRFBinding( ptr_bladerf, rx, tx, false ) return radio end function Base.print(rx::BladeRFRx); strF = @sprintf("Carrier Frequency: %2.3f MHz\nSampling Frequency: %2.3f MHz\nRF Bandwidth: %2.3f MHz\nGain: %2.3f",rx.carrierFreq/1e6,rx.samplingRate/1e6,rx.rfBandwidth/1e6,rx.gain) @inforx "Current BladeRF Radio Configuration in Rx mode\n$strF"; end function Base.print(tx::BladeRFTx); strF = @sprintf("Carrier Frequency: %2.3f MHz\nSampling Frequency: %2.3f MHz\nRF Bandwidth: %2.3f MHz\nGain: %2.3f",tx.carrierFreq/1e6,tx.samplingRate/1e6,tx.rfBandwidth/1e6,tx.gain) @infotx "Current BladeRF Radio Configuration in Tx mode\n$strF"; end function Base.print(radio::BladeRFBinding) print(radio.rx); print(radio.tx); end """ Returns the channel index associated to the current TX/RX """ function getChannel(head::Union{BladeRFTx,BladeRFRx}) return head.bladerf.channel end """ Update the carrier frequency of the blade RF """ function updateCarrierFreq!(radio::BladeRFBinding,frequency) # Update Rx head bladerf_set_frequency(radio.radio[],getChannel(radio.rx),convert(bladerf_frequency,frequency)) container = Ref{bladerf_frequency}(0) bladerf_get_frequency(radio.radio[],getChannel(radio.rx),container) effective_carrierFreq = container[] radio.rx.carrierFreq = effective_carrierFreq # Update Tx head bladerf_set_frequency(radio.radio[],getChannel(radio.tx),convert(bladerf_frequency,frequency)) container = Ref{bladerf_frequency}(0) bladerf_get_frequency(radio.radio[],getChannel(radio.tx),container) effective_carrierFreq = container[] radio.tx.carrierFreq = effective_carrierFreq end """ Update the sampling frequency """ function updateSamplingRate!(radio::BladeRFBinding,samplingRate) # Rx Head container = Ref{bladerf_sample_rate}(0) status = bladerf_set_sample_rate(radio.radio[],getChannel(radio.rx),convert(bladerf_sample_rate,samplingRate),container) effective_sampling_rate = container[] radio.rx.samplingRate = effective_sampling_rate # Tx Head container = Ref{bladerf_sample_rate}(0) status = bladerf_set_sample_rate(radio.radio[],getChannel(radio.tx),convert(bladerf_sample_rate,samplingRate),container) effective_sampling_rate = container[] radio.tx.samplingRate = effective_sampling_rate end """ Update the sampling frequency """ function updateRFBandwidth!(radio::BladeRFBinding,rfBandwidth) # Rx Head container = Ref{bladerf_bandwidth}(0) status = bladerf_set_bandwidth(radio.radio[],getChannel(radio.rx),convert(bladerf_bandwidth,rfBandwidth),container) effective_sampling_rate = container[] radio.rx.rfBandwidth = effective_sampling_rate # Tx Head container = Ref{bladerf_bandwidth}(0) status = bladerf_set_bandwidth(radio.radio[],getChannel(radio.tx),convert(bladerf_bandwidth,rfBandwidth),container) effective_sampling_rate = container[] radio.tx.rfBandwidth = effective_sampling_rate end """ Update BladeRF Gain """ function updateGain!(radio::BladeRFBinding,gain) # Update Rx head bladerf_set_gain(radio.radio[],getChannel(radio.rx),convert(bladerf_gain,gain)) container = Ref{bladerf_gain}(0) bladerf_get_gain(radio.radio[],getChannel(radio.rx),container) effective_gain = container[] radio.rx.gain = effective_gain # Update Tx head bladerf_set_gain(radio.radio[],getChannel(radio.tx),convert(bladerf_gain,gain)) container = Ref{bladerf_gain}(0) bladerf_get_gain(radio.radio[],getChannel(radio.tx),container) effective_gain = container[] radio.tx.gain = effective_gain end """ Receive nbSamples from the radio. Allocates an external buffer. To do this without allocation, see recv! """ function recv(radio::BladeRFBinding,nbSamples) # --- Create an empty buffer with the appropriate size buffer = zeros(ComplexF32,nbSamples) # --- Call the bang method recv!(buffer,radio) return buffer end """ Allocates the input buffer `buffer` with samples from the radio. """ function recv!(buffer::Vector{Complex{Float32}},radio::BladeRFBinding) nS = length(buffer) p = radio.rx.packetSize nbB = nS ÷ p cnt = 0 for k ∈ 0:nbB-1 # Populate the blade internal buffer status = bladerf_sync_rx(radio.radio[], radio.rx.bladerf.buffer, p, radio.rx.bladerf.ptr_metadata, 10000); (status != 0) && (print("O")) # Fill the main buffer populateBuffer!(buffer, radio.rx.bladerf.buffer,k,p) # Update number of received samples cnt += radio.rx.bladerf.ptr_metadata[].actual_count end # Last call should take rest of samples residu = nS - nbB*p if residu > 0 bladerf_sync_rx(radio.radio[], radio.rx.bladerf.buffer, residu, radio.rx.bladerf.ptr_metadata, 10000); populateBuffer!(buffer, radio.rx.bladerf.buffer,nbB,residu) end return cnt end """ Take the Blade internal buffer and fill the output buffer (ComplexF32) """ function populateBuffer!(buffer::Vector{ComplexF32},bladeBuffer::Vector{Int16},index,burst_size) c = typemax(Int16) for n ∈ 1 : burst_size buffer[index*burst_size + n] = Float32.(bladeBuffer[2(n-1)+1])/c + 1im*Float32.(bladeBuffer[2(n-1)+2])/c end end #function getError(radio::BladeRFBinding,targetSample=0) #FIXME Radio or radio .rx ? #status = radio.rx.bladerf.ptr_metadata[].status #@u #if status != 0 ## We have an error parse it #if (status & BLADERF_META_STATUS_OVERRUN) == 1 #a = radio.rx.bladerf.ptr_metadata[].actual_count #print("O[$a/$targetSample]") #end #if (status & BLADERF_META_STATUS_UNDERRUN) == 1 #print("U") #end #end #return status #end function send(radio::BladeRFBinding,buffer::Array{Complex{T}},cyclic::Bool =false) where {T<:AbstractFloat} # Size of buffer to send nT = length(buffer) # Size of internal buffer nI = length(radio.tx.bladerf.buffer) ÷ 2 # 2 paths # Number of complete bursts nbB = nT ÷ nI # Size of residu r = nT - nbB * nI nbE = 0 # Number of elements sent # Buffers while(true) for n ∈ 1 : nbB # Current buffer _fill_tx_buffer!(radio.tx.bladerf.buffer,buffer,(n-1)*nI,nI) # Conversion to internal representation status = bladerf_sync_tx(radio.radio[], radio.tx.bladerf.buffer, nI , radio.tx.bladerf.ptr_metadata, 10000); if status == 0 nbE += nI else @error "Error when sending data : Status is $status" end end # Residu if r > 0 _fill_tx_buffer!(radio.tx.bladerf.buffer,buffer,nbB*nI,r) status = bladerf_sync_tx(radio.radio[], radio.tx.bladerf.buffer, r , radio.tx.bladerf.ptr_metadata, 10000); if status == 0 nbE += r else @error "Error when sending data : Status is $status" end end if cyclic == false break end end return nbE end function _fill_tx_buffer!(internal_buffer,buffer,offset,nI) vM = typemax(Int16) @inbounds @simd for k ∈ 1 : nI internal_buffer[2*(k-1)+1] = Int16(round(real(buffer[ offset + k] * vM))) >> 4 internal_buffer[2*(k-1)+2] = Int16(round(imag(buffer[ offset + k] * vM))) >> 4 end return nothing end """ Destroy and safely release bladeRF object """ function close(radio::BladeRFBinding) if radio.released == false # Deactive radio module status = bladerf_enable_module(radio.radio[], BLADERF_RX, false); status = bladerf_enable_module(radio.radio[], BLADERF_TX, false); # Safely close module bladerf_close(radio.radio[]); radio.released = true radio.rx.released = true radio.tx.released = true @info "BladeRF is closed" else @warn "Blade RF is already closed and released. Abort" end return nothing end function scan() # By default brute-forcing bladeRF open leads to the opening # of the SDR => We do this and control the status ptr_bladerf = Ref{Ptr{bladerf}}() status = bladerf_open(ptr_bladerf,"") if status < 0 # --- No BladeRF found @info "No BladeRF device found" return "" else strall = "BladeRF found with reference: " strall *= unsafe_string(bladerf_get_board_name(ptr_bladerf[])) strall *= "\n" # --- Device speed speed = bladerf_device_speed(ptr_bladerf[]) strall *= "Device speed : $speed\n" # --- Device infos ptr_dev_info = Ref{bladerf_devinfo}() bladerf_get_devinfo(ptr_bladerf[], ptr_dev_info) dev_info = ptr_dev_info[] strall *= "USB Bus : $(dev_info.usb_bus), " strall *= "USB Address : $(dev_info.usb_addr)\n" strall *= "USB serial: $(ntuple_to_string(dev_info.serial))\n" strall *= "Nanufacturer: $(ntuple_to_string(dev_info.manufacturer))\n" strall *= "Product : $(ntuple_to_string(dev_info.product))\n" # Display the stuff @info strall # --- Release the SDR bladerf_close(ptr_bladerf[]); return strall end end """ Convert a Ntuple of type T into a string. Usefull for block containers of LibBladeRF that uses NTuple(N,CChar) to contains strings """ function ntuple_to_string(t::NTuple{N,T}) where {N,T} b = Base.StringVector(N) # or N-1 if your tuples are NUL-terminated return String(b .= t) # or t[1:N-1] end end
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
39260
module LibBladeRF using BladeRFHardwareDriver_jll #export BladeRFHardwareDriver_jll using CEnum @cenum bladerf_lna_gain::UInt32 begin BLADERF_LNA_GAIN_UNKNOWN = 0 BLADERF_LNA_GAIN_BYPASS = 1 BLADERF_LNA_GAIN_MID = 2 BLADERF_LNA_GAIN_MAX = 3 end @cenum bladerf_sampling::UInt32 begin BLADERF_SAMPLING_UNKNOWN = 0 BLADERF_SAMPLING_INTERNAL = 1 BLADERF_SAMPLING_EXTERNAL = 2 end @cenum bladerf_lpf_mode::UInt32 begin BLADERF_LPF_NORMAL = 0 BLADERF_LPF_BYPASSED = 1 BLADERF_LPF_DISABLED = 2 end @cenum bladerf_smb_mode::Int32 begin BLADERF_SMB_MODE_INVALID = -1 BLADERF_SMB_MODE_DISABLED = 0 BLADERF_SMB_MODE_OUTPUT = 1 BLADERF_SMB_MODE_INPUT = 2 BLADERF_SMB_MODE_UNAVAILBLE = 3 end @cenum bladerf_xb200_filter::UInt32 begin BLADERF_XB200_50M = 0 BLADERF_XB200_144M = 1 BLADERF_XB200_222M = 2 BLADERF_XB200_CUSTOM = 3 BLADERF_XB200_AUTO_1DB = 4 BLADERF_XB200_AUTO_3DB = 5 end @cenum bladerf_xb200_path::UInt32 begin BLADERF_XB200_BYPASS = 0 BLADERF_XB200_MIX = 1 end @cenum bladerf_xb300_trx::Int32 begin BLADERF_XB300_TRX_INVAL = -1 BLADERF_XB300_TRX_TX = 0 BLADERF_XB300_TRX_RX = 1 BLADERF_XB300_TRX_UNSET = 2 end @cenum bladerf_xb300_amplifier::Int32 begin BLADERF_XB300_AMP_INVAL = -1 BLADERF_XB300_AMP_PA = 0 BLADERF_XB300_AMP_LNA = 1 BLADERF_XB300_AMP_PA_AUX = 2 end @cenum bladerf_cal_module::Int32 begin BLADERF_DC_CAL_INVALID = -1 BLADERF_DC_CAL_LPF_TUNING = 0 BLADERF_DC_CAL_TX_LPF = 1 BLADERF_DC_CAL_RX_LPF = 2 BLADERF_DC_CAL_RXVGA2 = 3 end struct bladerf_lms_dc_cals lpf_tuning::Cint tx_lpf_i::Cint tx_lpf_q::Cint rx_lpf_i::Cint rx_lpf_q::Cint dc_ref::Cint rxvga2a_i::Cint rxvga2a_q::Cint rxvga2b_i::Cint rxvga2b_q::Cint end @cenum bladerf_rfic_rxfir::UInt32 begin BLADERF_RFIC_RXFIR_BYPASS = 0 BLADERF_RFIC_RXFIR_CUSTOM = 1 BLADERF_RFIC_RXFIR_DEC1 = 2 BLADERF_RFIC_RXFIR_DEC2 = 3 BLADERF_RFIC_RXFIR_DEC4 = 4 end @cenum bladerf_rfic_txfir::UInt32 begin BLADERF_RFIC_TXFIR_BYPASS = 0 BLADERF_RFIC_TXFIR_CUSTOM = 1 BLADERF_RFIC_TXFIR_INT1 = 2 BLADERF_RFIC_TXFIR_INT2 = 3 BLADERF_RFIC_TXFIR_INT4 = 4 end @cenum bladerf_power_sources::UInt32 begin BLADERF_UNKNOWN = 0 BLADERF_PS_DC = 1 BLADERF_PS_USB_VBUS = 2 end @cenum bladerf_clock_select::UInt32 begin CLOCK_SELECT_ONBOARD = 0 CLOCK_SELECT_EXTERNAL = 1 end @cenum bladerf_pmic_register::UInt32 begin BLADERF_PMIC_CONFIGURATION = 0 BLADERF_PMIC_VOLTAGE_SHUNT = 1 BLADERF_PMIC_VOLTAGE_BUS = 2 BLADERF_PMIC_POWER = 3 BLADERF_PMIC_CURRENT = 4 BLADERF_PMIC_CALIBRATION = 5 end struct bladerf_rf_switch_config tx1_rfic_port::Cint tx1_spdt_port::Cint tx2_rfic_port::Cint tx2_spdt_port::Cint rx1_rfic_port::Cint rx1_spdt_port::Cint rx2_rfic_port::Cint rx2_spdt_port::Cint end const bladerf_channel = Cint const bladerf_timestamp = UInt64 mutable struct bladerf end @cenum bladerf_backend::UInt32 begin BLADERF_BACKEND_ANY = 0 BLADERF_BACKEND_LINUX = 1 BLADERF_BACKEND_LIBUSB = 2 BLADERF_BACKEND_CYPRESS = 3 BLADERF_BACKEND_DUMMY = 100 end struct bladerf_devinfo backend::bladerf_backend serial::NTuple{33, Cchar} usb_bus::UInt8 usb_addr::UInt8 instance::Cuint manufacturer::NTuple{33, Cchar} product::NTuple{33, Cchar} end struct bladerf_backendinfo handle_count::Cint handle::Ptr{Cvoid} lock_count::Cint lock::Ptr{Cvoid} end ## Anonylous functions BLADERF_XB_GPIO(n) = (1 << (n - 1)) BLADERF_CHANNEL_RX(ch) = ((ch << 1) | 0x0) BLADERF_CHANNEL_TX(ch) = ((ch << 1) | 0x1) function bladerf_open(device, device_identifier) ccall((:bladerf_open, libbladerf), Cint, (Ptr{Ptr{bladerf}}, Ptr{Cchar}), device, device_identifier) end function bladerf_close(device) ccall((:bladerf_close, libbladerf), Cvoid, (Ptr{bladerf},), device) end function bladerf_open_with_devinfo(device, devinfo) ccall((:bladerf_open_with_devinfo, libbladerf), Cint, (Ptr{Ptr{bladerf}}, Ptr{bladerf_devinfo}), device, devinfo) end function bladerf_get_device_list(devices) ccall((:bladerf_get_device_list, libbladerf), Cint, (Ptr{Ptr{bladerf_devinfo}},), devices) end function bladerf_free_device_list(devices) ccall((:bladerf_free_device_list, libbladerf), Cvoid, (Ptr{bladerf_devinfo},), devices) end function bladerf_init_devinfo(info) ccall((:bladerf_init_devinfo, libbladerf), Cvoid, (Ptr{bladerf_devinfo},), info) end function bladerf_get_devinfo(dev, info) ccall((:bladerf_get_devinfo, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_devinfo}), dev, info) end function bladerf_get_backendinfo(dev, info) ccall((:bladerf_get_backendinfo, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_backendinfo}), dev, info) end function bladerf_get_devinfo_from_str(devstr, info) ccall((:bladerf_get_devinfo_from_str, libbladerf), Cint, (Ptr{Cchar}, Ptr{bladerf_devinfo}), devstr, info) end function bladerf_devinfo_matches(a, b) ccall((:bladerf_devinfo_matches, libbladerf), Bool, (Ptr{bladerf_devinfo}, Ptr{bladerf_devinfo}), a, b) end function bladerf_devstr_matches(dev_str, info) ccall((:bladerf_devstr_matches, libbladerf), Bool, (Ptr{Cchar}, Ptr{bladerf_devinfo}), dev_str, info) end function bladerf_backend_str(backend) ccall((:bladerf_backend_str, libbladerf), Ptr{Cchar}, (bladerf_backend,), backend) end function bladerf_set_usb_reset_on_open(enabled) ccall((:bladerf_set_usb_reset_on_open, libbladerf), Cvoid, (Bool,), enabled) end struct bladerf_range min::Int64 max::Int64 step::Int64 scale::Cfloat end struct bladerf_serial serial::NTuple{33, Cchar} end struct bladerf_version major::UInt16 minor::UInt16 patch::UInt16 describe::Ptr{Cchar} end @cenum bladerf_fpga_size::UInt32 begin BLADERF_FPGA_UNKNOWN = 0 BLADERF_FPGA_40KLE = 40 BLADERF_FPGA_115KLE = 115 BLADERF_FPGA_A4 = 49 BLADERF_FPGA_A5 = 77 BLADERF_FPGA_A9 = 301 end @cenum bladerf_dev_speed::UInt32 begin BLADERF_DEVICE_SPEED_UNKNOWN = 0 BLADERF_DEVICE_SPEED_HIGH = 1 BLADERF_DEVICE_SPEED_SUPER = 2 end @cenum bladerf_fpga_source::UInt32 begin BLADERF_FPGA_SOURCE_UNKNOWN = 0 BLADERF_FPGA_SOURCE_FLASH = 1 BLADERF_FPGA_SOURCE_HOST = 2 end function bladerf_get_serial(dev, serial) ccall((:bladerf_get_serial, libbladerf), Cint, (Ptr{bladerf}, Ptr{Cchar}), dev, serial) end function bladerf_get_serial_struct(dev, serial) ccall((:bladerf_get_serial_struct, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_serial}), dev, serial) end function bladerf_get_fpga_size(dev, size) ccall((:bladerf_get_fpga_size, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_fpga_size}), dev, size) end function bladerf_get_fpga_bytes(dev, size) ccall((:bladerf_get_fpga_bytes, libbladerf), Cint, (Ptr{bladerf}, Ptr{Csize_t}), dev, size) end function bladerf_get_flash_size(dev, size, is_guess) ccall((:bladerf_get_flash_size, libbladerf), Cint, (Ptr{bladerf}, Ptr{UInt32}, Ptr{Bool}), dev, size, is_guess) end function bladerf_fw_version(dev, version) ccall((:bladerf_fw_version, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_version}), dev, version) end function bladerf_is_fpga_configured(dev) ccall((:bladerf_is_fpga_configured, libbladerf), Cint, (Ptr{bladerf},), dev) end function bladerf_fpga_version(dev, version) ccall((:bladerf_fpga_version, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_version}), dev, version) end function bladerf_get_fpga_source(dev, source) ccall((:bladerf_get_fpga_source, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_fpga_source}), dev, source) end function bladerf_device_speed(dev) ccall((:bladerf_device_speed, libbladerf), bladerf_dev_speed, (Ptr{bladerf},), dev) end function bladerf_get_board_name(dev) ccall((:bladerf_get_board_name, libbladerf), Ptr{Cchar}, (Ptr{bladerf},), dev) end const bladerf_module = bladerf_channel @cenum bladerf_direction::UInt32 begin BLADERF_RX = 0 BLADERF_TX = 1 end @cenum bladerf_channel_layout::UInt32 begin BLADERF_RX_X1 = 0 BLADERF_TX_X1 = 1 BLADERF_RX_X2 = 2 BLADERF_TX_X2 = 3 end function bladerf_get_channel_count(dev, dir) ccall((:bladerf_get_channel_count, libbladerf), Csize_t, (Ptr{bladerf}, bladerf_direction), dev, dir) end const bladerf_gain = Cint @cenum bladerf_gain_mode::UInt32 begin BLADERF_GAIN_DEFAULT = 0 BLADERF_GAIN_MGC = 1 BLADERF_GAIN_FASTATTACK_AGC = 2 BLADERF_GAIN_SLOWATTACK_AGC = 3 BLADERF_GAIN_HYBRID_AGC = 4 end struct bladerf_gain_modes name::Ptr{Cchar} mode::bladerf_gain_mode end function bladerf_set_gain(dev, ch, gain) ccall((:bladerf_set_gain, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, bladerf_gain), dev, ch, gain) end function bladerf_get_gain(dev, ch, gain) ccall((:bladerf_get_gain, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{bladerf_gain}), dev, ch, gain) end function bladerf_set_gain_mode(dev, ch, mode) ccall((:bladerf_set_gain_mode, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, bladerf_gain_mode), dev, ch, mode) end function bladerf_get_gain_mode(dev, ch, mode) ccall((:bladerf_get_gain_mode, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{bladerf_gain_mode}), dev, ch, mode) end function bladerf_get_gain_modes(dev, ch, modes) ccall((:bladerf_get_gain_modes, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{Ptr{bladerf_gain_modes}}), dev, ch, modes) end function bladerf_get_gain_range(dev, ch, range) ccall((:bladerf_get_gain_range, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{Ptr{bladerf_range}}), dev, ch, range) end function bladerf_set_gain_stage(dev, ch, stage, gain) ccall((:bladerf_set_gain_stage, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{Cchar}, bladerf_gain), dev, ch, stage, gain) end function bladerf_get_gain_stage(dev, ch, stage, gain) ccall((:bladerf_get_gain_stage, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{Cchar}, Ptr{bladerf_gain}), dev, ch, stage, gain) end function bladerf_get_gain_stage_range(dev, ch, stage, range) ccall((:bladerf_get_gain_stage_range, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{Cchar}, Ptr{Ptr{bladerf_range}}), dev, ch, stage, range) end function bladerf_get_gain_stages(dev, ch, stages, count) ccall((:bladerf_get_gain_stages, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{Ptr{Cchar}}, Csize_t), dev, ch, stages, count) end const bladerf_sample_rate = Cuint struct bladerf_rational_rate integer::UInt64 num::UInt64 den::UInt64 end function bladerf_set_sample_rate(dev, ch, rate, actual) ccall((:bladerf_set_sample_rate, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, bladerf_sample_rate, Ptr{bladerf_sample_rate}), dev, ch, rate, actual) end function bladerf_set_rational_sample_rate(dev, ch, rate, actual) ccall((:bladerf_set_rational_sample_rate, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{bladerf_rational_rate}, Ptr{bladerf_rational_rate}), dev, ch, rate, actual) end function bladerf_get_sample_rate(dev, ch, rate) ccall((:bladerf_get_sample_rate, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{bladerf_sample_rate}), dev, ch, rate) end function bladerf_get_sample_rate_range(dev, ch, range) ccall((:bladerf_get_sample_rate_range, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{Ptr{bladerf_range}}), dev, ch, range) end function bladerf_get_rational_sample_rate(dev, ch, rate) ccall((:bladerf_get_rational_sample_rate, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{bladerf_rational_rate}), dev, ch, rate) end const bladerf_bandwidth = Cuint function bladerf_set_bandwidth(dev, ch, bandwidth, actual) ccall((:bladerf_set_bandwidth, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, bladerf_bandwidth, Ptr{bladerf_bandwidth}), dev, ch, bandwidth, actual) end function bladerf_get_bandwidth(dev, ch, bandwidth) ccall((:bladerf_get_bandwidth, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{bladerf_bandwidth}), dev, ch, bandwidth) end function bladerf_get_bandwidth_range(dev, ch, range) ccall((:bladerf_get_bandwidth_range, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{Ptr{bladerf_range}}), dev, ch, range) end const bladerf_frequency = UInt64 function bladerf_select_band(dev, ch, frequency) ccall((:bladerf_select_band, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, bladerf_frequency), dev, ch, frequency) end function bladerf_set_frequency(dev, ch, frequency) ccall((:bladerf_set_frequency, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, bladerf_frequency), dev, ch, frequency) end function bladerf_get_frequency(dev, ch, frequency) ccall((:bladerf_get_frequency, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{bladerf_frequency}), dev, ch, frequency) end function bladerf_get_frequency_range(dev, ch, range) ccall((:bladerf_get_frequency_range, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{Ptr{bladerf_range}}), dev, ch, range) end @cenum bladerf_loopback::UInt32 begin BLADERF_LB_NONE = 0 BLADERF_LB_FIRMWARE = 1 BLADERF_LB_BB_TXLPF_RXVGA2 = 2 BLADERF_LB_BB_TXVGA1_RXVGA2 = 3 BLADERF_LB_BB_TXLPF_RXLPF = 4 BLADERF_LB_BB_TXVGA1_RXLPF = 5 BLADERF_LB_RF_LNA1 = 6 BLADERF_LB_RF_LNA2 = 7 BLADERF_LB_RF_LNA3 = 8 BLADERF_LB_RFIC_BIST = 9 end struct bladerf_loopback_modes name::Ptr{Cchar} mode::bladerf_loopback end function bladerf_get_loopback_modes(dev, modes) ccall((:bladerf_get_loopback_modes, libbladerf), Cint, (Ptr{bladerf}, Ptr{Ptr{bladerf_loopback_modes}}), dev, modes) end function bladerf_is_loopback_mode_supported(dev, mode) ccall((:bladerf_is_loopback_mode_supported, libbladerf), Bool, (Ptr{bladerf}, bladerf_loopback), dev, mode) end function bladerf_set_loopback(dev, lb) ccall((:bladerf_set_loopback, libbladerf), Cint, (Ptr{bladerf}, bladerf_loopback), dev, lb) end function bladerf_get_loopback(dev, lb) ccall((:bladerf_get_loopback, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_loopback}), dev, lb) end @cenum bladerf_trigger_role::Int32 begin BLADERF_TRIGGER_ROLE_INVALID = -1 BLADERF_TRIGGER_ROLE_DISABLED = 0 BLADERF_TRIGGER_ROLE_MASTER = 1 BLADERF_TRIGGER_ROLE_SLAVE = 2 end @cenum bladerf_trigger_signal::Int32 begin BLADERF_TRIGGER_INVALID = -1 BLADERF_TRIGGER_J71_4 = 0 BLADERF_TRIGGER_J51_1 = 1 BLADERF_TRIGGER_MINI_EXP_1 = 2 BLADERF_TRIGGER_USER_0 = 128 BLADERF_TRIGGER_USER_1 = 129 BLADERF_TRIGGER_USER_2 = 130 BLADERF_TRIGGER_USER_3 = 131 BLADERF_TRIGGER_USER_4 = 132 BLADERF_TRIGGER_USER_5 = 133 BLADERF_TRIGGER_USER_6 = 134 BLADERF_TRIGGER_USER_7 = 135 end struct bladerf_trigger channel::bladerf_channel role::bladerf_trigger_role signal::bladerf_trigger_signal options::UInt64 end function bladerf_trigger_init(dev, ch, signal, trigger) ccall((:bladerf_trigger_init, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, bladerf_trigger_signal, Ptr{bladerf_trigger}), dev, ch, signal, trigger) end function bladerf_trigger_arm(dev, trigger, arm, resv1, resv2) ccall((:bladerf_trigger_arm, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_trigger}, Bool, UInt64, UInt64), dev, trigger, arm, resv1, resv2) end function bladerf_trigger_fire(dev, trigger) ccall((:bladerf_trigger_fire, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_trigger}), dev, trigger) end function bladerf_trigger_state(dev, trigger, is_armed, has_fired, fire_requested, resv1, resv2) ccall((:bladerf_trigger_state, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_trigger}, Ptr{Bool}, Ptr{Bool}, Ptr{Bool}, Ptr{UInt64}, Ptr{UInt64}), dev, trigger, is_armed, has_fired, fire_requested, resv1, resv2) end @cenum bladerf_rx_mux::Int32 begin BLADERF_RX_MUX_INVALID = -1 BLADERF_RX_MUX_BASEBAND = 0 BLADERF_RX_MUX_12BIT_COUNTER = 1 BLADERF_RX_MUX_32BIT_COUNTER = 2 BLADERF_RX_MUX_DIGITAL_LOOPBACK = 4 end function bladerf_set_rx_mux(dev, mux) ccall((:bladerf_set_rx_mux, libbladerf), Cint, (Ptr{bladerf}, bladerf_rx_mux), dev, mux) end function bladerf_get_rx_mux(dev, mode) ccall((:bladerf_get_rx_mux, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_rx_mux}), dev, mode) end struct bladerf_quick_tune data::NTuple{12, UInt8} end function Base.getproperty(x::Ptr{bladerf_quick_tune}, f::Symbol) f === :freqsel && return Ptr{UInt8}(x + 0) f === :vcocap && return Ptr{UInt8}(x + 1) f === :nint && return Ptr{UInt16}(x + 2) f === :nfrac && return Ptr{UInt32}(x + 4) f === :flags && return Ptr{UInt8}(x + 8) f === :xb_gpio && return Ptr{UInt8}(x + 9) f === :nios_profile && return Ptr{UInt16}(x + 0) f === :rffe_profile && return Ptr{UInt8}(x + 2) f === :port && return Ptr{UInt8}(x + 3) f === :spdt && return Ptr{UInt8}(x + 4) return getfield(x, f) end function Base.getproperty(x::bladerf_quick_tune, f::Symbol) r = Ref{bladerf_quick_tune}(x) ptr = Base.unsafe_convert(Ptr{bladerf_quick_tune}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{bladerf_quick_tune}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end function bladerf_schedule_retune(dev, ch, timestamp, frequency, quick_tune) ccall((:bladerf_schedule_retune, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, bladerf_timestamp, bladerf_frequency, Ptr{bladerf_quick_tune}), dev, ch, timestamp, frequency, quick_tune) end function bladerf_cancel_scheduled_retunes(dev, ch) ccall((:bladerf_cancel_scheduled_retunes, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel), dev, ch) end function bladerf_get_quick_tune(dev, ch, quick_tune) ccall((:bladerf_get_quick_tune, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{bladerf_quick_tune}), dev, ch, quick_tune) end const bladerf_correction_value = Int16 @cenum bladerf_correction::UInt32 begin BLADERF_CORR_DCOFF_I = 0 BLADERF_CORR_DCOFF_Q = 1 BLADERF_CORR_PHASE = 2 BLADERF_CORR_GAIN = 3 end function bladerf_set_correction(dev, ch, corr, value) ccall((:bladerf_set_correction, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, bladerf_correction, bladerf_correction_value), dev, ch, corr, value) end function bladerf_get_correction(dev, ch, corr, value) ccall((:bladerf_get_correction, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, bladerf_correction, Ptr{bladerf_correction_value}), dev, ch, corr, value) end @cenum bladerf_format::UInt32 begin BLADERF_FORMAT_SC16_Q11 = 0 BLADERF_FORMAT_SC16_Q11_META = 1 BLADERF_FORMAT_PACKET_META = 2 end mutable struct bladerf_metadata timestamp::bladerf_timestamp flags::UInt32 status::UInt32 actual_count::Cuint reserved::NTuple{32, UInt8} end function bladerf_interleave_stream_buffer(layout, format, buffer_size, samples) ccall((:bladerf_interleave_stream_buffer, libbladerf), Cint, (bladerf_channel_layout, bladerf_format, Cuint, Ptr{Cvoid}), layout, format, buffer_size, samples) end function bladerf_deinterleave_stream_buffer(layout, format, buffer_size, samples) ccall((:bladerf_deinterleave_stream_buffer, libbladerf), Cint, (bladerf_channel_layout, bladerf_format, Cuint, Ptr{Cvoid}), layout, format, buffer_size, samples) end function bladerf_enable_module(dev, ch, enable) ccall((:bladerf_enable_module, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Bool), dev, ch, enable) end function bladerf_get_timestamp(dev, dir, timestamp) ccall((:bladerf_get_timestamp, libbladerf), Cint, (Ptr{bladerf}, bladerf_direction, Ptr{bladerf_timestamp}), dev, dir, timestamp) end function bladerf_sync_config(dev, layout, format, num_buffers, buffer_size, num_transfers, stream_timeout) ccall((:bladerf_sync_config, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel_layout, bladerf_format, Cuint, Cuint, Cuint, Cuint), dev, layout, format, num_buffers, buffer_size, num_transfers, stream_timeout) end function bladerf_sync_tx(dev, samples, num_samples, metadata, timeout_ms) ccall((:bladerf_sync_tx, libbladerf), Cint, (Ptr{bladerf}, Ptr{Cvoid}, Cuint, Ptr{bladerf_metadata}, Cuint), dev, samples, num_samples, metadata, timeout_ms) end function bladerf_sync_rx(dev, samples, num_samples, metadata, timeout_ms) ccall((:bladerf_sync_rx, libbladerf), Cint, (Ptr{bladerf}, Ptr{Cvoid}, Cuint, Ptr{bladerf_metadata}, Cuint), dev, samples, num_samples, metadata, timeout_ms) end mutable struct bladerf_stream end # typedef void * ( * bladerf_stream_cb ) ( struct bladerf * dev , struct bladerf_stream * stream , struct bladerf_metadata * meta , void * samples , size_t num_samples , void * user_data ) const bladerf_stream_cb = Ptr{Cvoid} function bladerf_init_stream(stream, dev, callback, buffers, num_buffers, format, samples_per_buffer, num_transfers, user_data) ccall((:bladerf_init_stream, libbladerf), Cint, (Ptr{Ptr{bladerf_stream}}, Ptr{bladerf}, bladerf_stream_cb, Ptr{Ptr{Ptr{Cvoid}}}, Csize_t, bladerf_format, Csize_t, Csize_t, Ptr{Cvoid}), stream, dev, callback, buffers, num_buffers, format, samples_per_buffer, num_transfers, user_data) end function bladerf_stream(stream, layout) ccall((:bladerf_stream, libbladerf), Cint, (Ptr{bladerf_stream}, bladerf_channel_layout), stream, layout) end function bladerf_submit_stream_buffer(stream, buffer, timeout_ms) ccall((:bladerf_submit_stream_buffer, libbladerf), Cint, (Ptr{bladerf_stream}, Ptr{Cvoid}, Cuint), stream, buffer, timeout_ms) end function bladerf_submit_stream_buffer_nb(stream, buffer) ccall((:bladerf_submit_stream_buffer_nb, libbladerf), Cint, (Ptr{bladerf_stream}, Ptr{Cvoid}), stream, buffer) end function bladerf_deinit_stream(stream) ccall((:bladerf_deinit_stream, libbladerf), Cvoid, (Ptr{bladerf_stream},), stream) end function bladerf_set_stream_timeout(dev, dir, timeout) ccall((:bladerf_set_stream_timeout, libbladerf), Cint, (Ptr{bladerf}, bladerf_direction, Cuint), dev, dir, timeout) end function bladerf_get_stream_timeout(dev, dir, timeout) ccall((:bladerf_get_stream_timeout, libbladerf), Cint, (Ptr{bladerf}, bladerf_direction, Ptr{Cuint}), dev, dir, timeout) end function bladerf_flash_firmware(dev, firmware) ccall((:bladerf_flash_firmware, libbladerf), Cint, (Ptr{bladerf}, Ptr{Cchar}), dev, firmware) end function bladerf_load_fpga(dev, fpga) ccall((:bladerf_load_fpga, libbladerf), Cint, (Ptr{bladerf}, Ptr{Cchar}), dev, fpga) end function bladerf_flash_fpga(dev, fpga_image) ccall((:bladerf_flash_fpga, libbladerf), Cint, (Ptr{bladerf}, Ptr{Cchar}), dev, fpga_image) end function bladerf_erase_stored_fpga(dev) ccall((:bladerf_erase_stored_fpga, libbladerf), Cint, (Ptr{bladerf},), dev) end function bladerf_device_reset(dev) ccall((:bladerf_device_reset, libbladerf), Cint, (Ptr{bladerf},), dev) end function bladerf_get_fw_log(dev, filename) ccall((:bladerf_get_fw_log, libbladerf), Cint, (Ptr{bladerf}, Ptr{Cchar}), dev, filename) end function bladerf_jump_to_bootloader(dev) ccall((:bladerf_jump_to_bootloader, libbladerf), Cint, (Ptr{bladerf},), dev) end function bladerf_get_bootloader_list(list) ccall((:bladerf_get_bootloader_list, libbladerf), Cint, (Ptr{Ptr{bladerf_devinfo}},), list) end function bladerf_load_fw_from_bootloader(device_identifier, backend, bus, addr, file) ccall((:bladerf_load_fw_from_bootloader, libbladerf), Cint, (Ptr{Cchar}, bladerf_backend, UInt8, UInt8, Ptr{Cchar}), device_identifier, backend, bus, addr, file) end @cenum bladerf_image_type::Int32 begin BLADERF_IMAGE_TYPE_INVALID = -1 BLADERF_IMAGE_TYPE_RAW = 0 BLADERF_IMAGE_TYPE_FIRMWARE = 1 BLADERF_IMAGE_TYPE_FPGA_40KLE = 2 BLADERF_IMAGE_TYPE_FPGA_115KLE = 3 BLADERF_IMAGE_TYPE_FPGA_A4 = 4 BLADERF_IMAGE_TYPE_FPGA_A9 = 5 BLADERF_IMAGE_TYPE_CALIBRATION = 6 BLADERF_IMAGE_TYPE_RX_DC_CAL = 7 BLADERF_IMAGE_TYPE_TX_DC_CAL = 8 BLADERF_IMAGE_TYPE_RX_IQ_CAL = 9 BLADERF_IMAGE_TYPE_TX_IQ_CAL = 10 BLADERF_IMAGE_TYPE_FPGA_A5 = 11 end struct bladerf_image magic::NTuple{8, Cchar} checksum::NTuple{32, UInt8} version::bladerf_version timestamp::UInt64 serial::NTuple{34, Cchar} reserved::NTuple{128, Cchar} type::bladerf_image_type address::UInt32 length::UInt32 data::Ptr{UInt8} end function bladerf_alloc_image(dev, type, address, length) ccall((:bladerf_alloc_image, libbladerf), Ptr{bladerf_image}, (Ptr{bladerf}, bladerf_image_type, UInt32, UInt32), dev, type, address, length) end function bladerf_alloc_cal_image(dev, fpga_size, vctcxo_trim) ccall((:bladerf_alloc_cal_image, libbladerf), Ptr{bladerf_image}, (Ptr{bladerf}, bladerf_fpga_size, UInt16), dev, fpga_size, vctcxo_trim) end function bladerf_free_image(image) ccall((:bladerf_free_image, libbladerf), Cvoid, (Ptr{bladerf_image},), image) end function bladerf_image_write(dev, image, file) ccall((:bladerf_image_write, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_image}, Ptr{Cchar}), dev, image, file) end function bladerf_image_read(image, file) ccall((:bladerf_image_read, libbladerf), Cint, (Ptr{bladerf_image}, Ptr{Cchar}), image, file) end @cenum bladerf_vctcxo_tamer_mode::Int32 begin BLADERF_VCTCXO_TAMER_INVALID = -1 BLADERF_VCTCXO_TAMER_DISABLED = 0 BLADERF_VCTCXO_TAMER_1_PPS = 1 BLADERF_VCTCXO_TAMER_10_MHZ = 2 end function bladerf_set_vctcxo_tamer_mode(dev, mode) ccall((:bladerf_set_vctcxo_tamer_mode, libbladerf), Cint, (Ptr{bladerf}, bladerf_vctcxo_tamer_mode), dev, mode) end function bladerf_get_vctcxo_tamer_mode(dev, mode) ccall((:bladerf_get_vctcxo_tamer_mode, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_vctcxo_tamer_mode}), dev, mode) end function bladerf_get_vctcxo_trim(dev, trim) ccall((:bladerf_get_vctcxo_trim, libbladerf), Cint, (Ptr{bladerf}, Ptr{UInt16}), dev, trim) end function bladerf_trim_dac_write(dev, val) ccall((:bladerf_trim_dac_write, libbladerf), Cint, (Ptr{bladerf}, UInt16), dev, val) end function bladerf_trim_dac_read(dev, val) ccall((:bladerf_trim_dac_read, libbladerf), Cint, (Ptr{bladerf}, Ptr{UInt16}), dev, val) end @cenum bladerf_tuning_mode::Int32 begin BLADERF_TUNING_MODE_INVALID = -1 BLADERF_TUNING_MODE_HOST = 0 BLADERF_TUNING_MODE_FPGA = 1 end function bladerf_set_tuning_mode(dev, mode) ccall((:bladerf_set_tuning_mode, libbladerf), Cint, (Ptr{bladerf}, bladerf_tuning_mode), dev, mode) end function bladerf_get_tuning_mode(dev, mode) ccall((:bladerf_get_tuning_mode, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_tuning_mode}), dev, mode) end function bladerf_read_trigger(dev, ch, signal, val) ccall((:bladerf_read_trigger, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, bladerf_trigger_signal, Ptr{UInt8}), dev, ch, signal, val) end function bladerf_write_trigger(dev, ch, signal, val) ccall((:bladerf_write_trigger, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, bladerf_trigger_signal, UInt8), dev, ch, signal, val) end function bladerf_wishbone_master_read(dev, addr, data) ccall((:bladerf_wishbone_master_read, libbladerf), Cint, (Ptr{bladerf}, UInt32, Ptr{UInt32}), dev, addr, data) end function bladerf_wishbone_master_write(dev, addr, val) ccall((:bladerf_wishbone_master_write, libbladerf), Cint, (Ptr{bladerf}, UInt32, UInt32), dev, addr, val) end function bladerf_config_gpio_read(dev, val) ccall((:bladerf_config_gpio_read, libbladerf), Cint, (Ptr{bladerf}, Ptr{UInt32}), dev, val) end function bladerf_config_gpio_write(dev, val) ccall((:bladerf_config_gpio_write, libbladerf), Cint, (Ptr{bladerf}, UInt32), dev, val) end function bladerf_erase_flash(dev, erase_block, count) ccall((:bladerf_erase_flash, libbladerf), Cint, (Ptr{bladerf}, UInt32, UInt32), dev, erase_block, count) end function bladerf_erase_flash_bytes(dev, address, length) ccall((:bladerf_erase_flash_bytes, libbladerf), Cint, (Ptr{bladerf}, UInt32, UInt32), dev, address, length) end function bladerf_read_flash(dev, buf, page, count) ccall((:bladerf_read_flash, libbladerf), Cint, (Ptr{bladerf}, Ptr{UInt8}, UInt32, UInt32), dev, buf, page, count) end function bladerf_read_flash_bytes(dev, buf, address, bytes) ccall((:bladerf_read_flash_bytes, libbladerf), Cint, (Ptr{bladerf}, Ptr{UInt8}, UInt32, UInt32), dev, buf, address, bytes) end function bladerf_write_flash(dev, buf, page, count) ccall((:bladerf_write_flash, libbladerf), Cint, (Ptr{bladerf}, Ptr{UInt8}, UInt32, UInt32), dev, buf, page, count) end function bladerf_write_flash_bytes(dev, buf, address, length) ccall((:bladerf_write_flash_bytes, libbladerf), Cint, (Ptr{bladerf}, Ptr{UInt8}, UInt32, UInt32), dev, buf, address, length) end function bladerf_lock_otp(dev) ccall((:bladerf_lock_otp, libbladerf), Cint, (Ptr{bladerf},), dev) end function bladerf_read_otp(dev, buf) ccall((:bladerf_read_otp, libbladerf), Cint, (Ptr{bladerf}, Ptr{UInt8}), dev, buf) end function bladerf_write_otp(dev, buf) ccall((:bladerf_write_otp, libbladerf), Cint, (Ptr{bladerf}, Ptr{UInt8}), dev, buf) end function bladerf_set_rf_port(dev, ch, port) ccall((:bladerf_set_rf_port, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{Cchar}), dev, ch, port) end function bladerf_get_rf_port(dev, ch, port) ccall((:bladerf_get_rf_port, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{Ptr{Cchar}}), dev, ch, port) end function bladerf_get_rf_ports(dev, ch, ports, count) ccall((:bladerf_get_rf_ports, libbladerf), Cint, (Ptr{bladerf}, bladerf_channel, Ptr{Ptr{Cchar}}, Cuint), dev, ch, ports, count) end @cenum bladerf_xb::UInt32 begin BLADERF_XB_NONE = 0 BLADERF_XB_100 = 1 BLADERF_XB_200 = 2 BLADERF_XB_300 = 3 end function bladerf_expansion_attach(dev, xb) ccall((:bladerf_expansion_attach, libbladerf), Cint, (Ptr{bladerf}, bladerf_xb), dev, xb) end function bladerf_expansion_get_attached(dev, xb) ccall((:bladerf_expansion_get_attached, libbladerf), Cint, (Ptr{bladerf}, Ptr{bladerf_xb}), dev, xb) end @cenum bladerf_log_level::UInt32 begin BLADERF_LOG_LEVEL_VERBOSE = 0 BLADERF_LOG_LEVEL_DEBUG = 1 BLADERF_LOG_LEVEL_INFO = 2 BLADERF_LOG_LEVEL_WARNING = 3 BLADERF_LOG_LEVEL_ERROR = 4 BLADERF_LOG_LEVEL_CRITICAL = 5 BLADERF_LOG_LEVEL_SILENT = 6 end function bladerf_log_set_verbosity(level) ccall((:bladerf_log_set_verbosity, libbladerf), Cvoid, (bladerf_log_level,), level) end function bladerf_version(version) ccall((:bladerf_version, libbladerf), Cvoid, (Ptr{bladerf_version},), version) end function bladerf_strerror(error) ccall((:bladerf_strerror, libbladerf), Ptr{Cchar}, (Cint,), error) end const BLADERF_SAMPLERATE_MIN = Cuint(80000) const BLADERF_SAMPLERATE_REC_MAX = Cuint(40000000) const BLADERF_BANDWIDTH_MIN = Cuint(1500000) const BLADERF_BANDWIDTH_MAX = Cuint(28000000) const BLADERF_FREQUENCY_MIN_XB200 = Cuint(0) const BLADERF_FREQUENCY_MIN = Cuint(237500000) const BLADERF_FREQUENCY_MAX = Cuint(3800000000) const BLADERF_FLASH_ADDR_FIRMWARE = 0x00000000 const BLADERF_FLASH_BYTE_LEN_FIRMWARE = 0x00030000 const BLADERF_FLASH_ADDR_CAL = 0x00030000 const BLADERF_FLASH_BYTE_LEN_CAL = 0x0100 const BLADERF_FLASH_ADDR_FPGA = 0x00040000 const BLADERF_RXVGA1_GAIN_MIN = 5 const BLADERF_RXVGA1_GAIN_MAX = 30 const BLADERF_RXVGA2_GAIN_MIN = 0 const BLADERF_RXVGA2_GAIN_MAX = 30 const BLADERF_TXVGA1_GAIN_MIN = -35 const BLADERF_TXVGA1_GAIN_MAX = -4 const BLADERF_TXVGA2_GAIN_MIN = 0 const BLADERF_TXVGA2_GAIN_MAX = 25 const BLADERF_LNA_GAIN_MID_DB = 3 const BLADERF_LNA_GAIN_MAX_DB = 6 const BLADERF_SMB_FREQUENCY_MAX = Cuint(200000000) const BLADERF_SMB_FREQUENCY_MIN = (Cuint(38400000) * Cuint(66)) ÷ (32 * 567) const BLADERF_XB_GPIO_01 = BLADERF_XB_GPIO(1) const BLADERF_XB_GPIO_02 = BLADERF_XB_GPIO(2) const BLADERF_XB_GPIO_03 = BLADERF_XB_GPIO(3) const BLADERF_XB_GPIO_04 = BLADERF_XB_GPIO(4) const BLADERF_XB_GPIO_05 = BLADERF_XB_GPIO(5) const BLADERF_XB_GPIO_06 = BLADERF_XB_GPIO(6) const BLADERF_XB_GPIO_07 = BLADERF_XB_GPIO(7) const BLADERF_XB_GPIO_08 = BLADERF_XB_GPIO(8) const BLADERF_XB_GPIO_09 = BLADERF_XB_GPIO(9) const BLADERF_XB_GPIO_10 = BLADERF_XB_GPIO(10) const BLADERF_XB_GPIO_11 = BLADERF_XB_GPIO(11) const BLADERF_XB_GPIO_12 = BLADERF_XB_GPIO(12) const BLADERF_XB_GPIO_13 = BLADERF_XB_GPIO(13) const BLADERF_XB_GPIO_14 = BLADERF_XB_GPIO(14) const BLADERF_XB_GPIO_15 = BLADERF_XB_GPIO(15) const BLADERF_XB_GPIO_16 = BLADERF_XB_GPIO(16) const BLADERF_XB_GPIO_17 = BLADERF_XB_GPIO(17) const BLADERF_XB_GPIO_18 = BLADERF_XB_GPIO(18) const BLADERF_XB_GPIO_19 = BLADERF_XB_GPIO(19) const BLADERF_XB_GPIO_20 = BLADERF_XB_GPIO(20) const BLADERF_XB_GPIO_21 = BLADERF_XB_GPIO(21) const BLADERF_XB_GPIO_22 = BLADERF_XB_GPIO(22) const BLADERF_XB_GPIO_23 = BLADERF_XB_GPIO(23) const BLADERF_XB_GPIO_24 = BLADERF_XB_GPIO(24) const BLADERF_XB_GPIO_25 = BLADERF_XB_GPIO(25) const BLADERF_XB_GPIO_26 = BLADERF_XB_GPIO(26) const BLADERF_XB_GPIO_27 = BLADERF_XB_GPIO(27) const BLADERF_XB_GPIO_28 = BLADERF_XB_GPIO(28) const BLADERF_XB_GPIO_29 = BLADERF_XB_GPIO(29) const BLADERF_XB_GPIO_30 = BLADERF_XB_GPIO(30) const BLADERF_XB_GPIO_31 = BLADERF_XB_GPIO(31) const BLADERF_XB_GPIO_32 = BLADERF_XB_GPIO(32) const BLADERF_XB200_PIN_J7_1 = BLADERF_XB_GPIO_10 const BLADERF_XB200_PIN_J7_2 = BLADERF_XB_GPIO_11 const BLADERF_XB200_PIN_J7_5 = BLADERF_XB_GPIO_08 const BLADERF_XB200_PIN_J7_6 = BLADERF_XB_GPIO_09 const BLADERF_XB200_PIN_J13_1 = BLADERF_XB_GPIO_17 const BLADERF_XB200_PIN_J13_2 = BLADERF_XB_GPIO_18 const BLADERF_XB200_PIN_J16_1 = BLADERF_XB_GPIO_31 const BLADERF_XB200_PIN_J16_2 = BLADERF_XB_GPIO_32 const BLADERF_XB200_PIN_J16_3 = BLADERF_XB_GPIO_19 const BLADERF_XB200_PIN_J16_4 = BLADERF_XB_GPIO_20 const BLADERF_XB200_PIN_J16_5 = BLADERF_XB_GPIO_21 const BLADERF_XB200_PIN_J16_6 = BLADERF_XB_GPIO_24 const BLADERF_XB100_PIN_J2_3 = BLADERF_XB_GPIO_07 const BLADERF_XB100_PIN_J2_4 = BLADERF_XB_GPIO_08 const BLADERF_XB100_PIN_J3_3 = BLADERF_XB_GPIO_09 const BLADERF_XB100_PIN_J3_4 = BLADERF_XB_GPIO_10 const BLADERF_XB100_PIN_J4_3 = BLADERF_XB_GPIO_11 const BLADERF_XB100_PIN_J4_4 = BLADERF_XB_GPIO_12 const BLADERF_XB100_PIN_J5_3 = BLADERF_XB_GPIO_13 const BLADERF_XB100_PIN_J5_4 = BLADERF_XB_GPIO_14 const BLADERF_XB100_PIN_J11_2 = BLADERF_XB_GPIO_05 const BLADERF_XB100_PIN_J11_3 = BLADERF_XB_GPIO_04 const BLADERF_XB100_PIN_J11_4 = BLADERF_XB_GPIO_03 const BLADERF_XB100_PIN_J11_5 = BLADERF_XB_GPIO_06 const BLADERF_XB100_PIN_J12_2 = BLADERF_XB_GPIO_01 const BLADERF_XB100_PIN_J12_5 = BLADERF_XB_GPIO_02 const BLADERF_XB100_LED_D1 = BLADERF_XB_GPIO_24 const BLADERF_XB100_LED_D2 = BLADERF_XB_GPIO_32 const BLADERF_XB100_LED_D3 = BLADERF_XB_GPIO_30 const BLADERF_XB100_LED_D4 = BLADERF_XB_GPIO_28 const BLADERF_XB100_LED_D5 = BLADERF_XB_GPIO_23 const BLADERF_XB100_LED_D6 = BLADERF_XB_GPIO_25 const BLADERF_XB100_LED_D7 = BLADERF_XB_GPIO_31 const BLADERF_XB100_LED_D8 = BLADERF_XB_GPIO_29 const BLADERF_XB100_TLED_RED = BLADERF_XB_GPIO_22 const BLADERF_XB100_TLED_GREEN = BLADERF_XB_GPIO_21 const BLADERF_XB100_TLED_BLUE = BLADERF_XB_GPIO_20 const BLADERF_XB100_DIP_SW1 = BLADERF_XB_GPIO_27 const BLADERF_XB100_DIP_SW2 = BLADERF_XB_GPIO_26 const BLADERF_XB100_DIP_SW3 = BLADERF_XB_GPIO_16 const BLADERF_XB100_DIP_SW4 = BLADERF_XB_GPIO_15 const BLADERF_XB100_BTN_J6 = BLADERF_XB_GPIO_19 const BLADERF_XB100_BTN_J7 = BLADERF_XB_GPIO_18 const BLADERF_XB100_BTN_J8 = BLADERF_XB_GPIO_17 const BLADERF_GPIO_LMS_RX_ENABLE = 1 << 1 const BLADERF_GPIO_LMS_TX_ENABLE = 1 << 2 const BLADERF_GPIO_TX_LB_ENABLE = 2 << 3 const BLADERF_GPIO_TX_HB_ENABLE = 1 << 3 const BLADERF_GPIO_COUNTER_ENABLE = 1 << 9 const BLADERF_GPIO_RX_MUX_SHIFT = 8 const BLADERF_GPIO_RX_MUX_MASK = 0x07 << BLADERF_GPIO_RX_MUX_SHIFT const BLADERF_GPIO_RX_LB_ENABLE = 2 << 5 const BLADERF_GPIO_RX_HB_ENABLE = 1 << 5 const BLADERF_GPIO_FEATURE_SMALL_DMA_XFER = 1 << 7 const BLADERF_GPIO_PACKET = 1 << 19 const BLADERF_GPIO_AGC_ENABLE = 1 << 18 const BLADERF_GPIO_TIMESTAMP = 1 << 16 const BLADERF_GPIO_TIMESTAMP_DIV2 = 1 << 17 const BLADERF_GPIO_PACKET_CORE_PRESENT = 1 << 28 const BLADERF_RFIC_RXFIR_DEFAULT = BLADERF_RFIC_RXFIR_DEC1 const BLADERF_RFIC_TXFIR_DEFAULT = BLADERF_RFIC_TXFIR_BYPASS const LIBBLADERF_API_VERSION = 0x02040100 # Skipping MacroDefinition: API_EXPORT __attribute__ ( ( visibility ( "default" ) ) ) const BLADERF_DESCRIPTION_LENGTH = 33 const BLADERF_SERIAL_LENGTH = 33 const BLADERF_CHANNEL_INVALID = bladerf_channel(-1) const BLADERF_DIRECTION_MASK = 0x01 const BLADERF_MODULE_INVALID = BLADERF_CHANNEL_INVALID const BLADERF_MODULE_RX = BLADERF_CHANNEL_RX(0) const BLADERF_MODULE_TX = BLADERF_CHANNEL_TX(0) const BLADERF_GAIN_AUTOMATIC = BLADERF_GAIN_DEFAULT const BLADERF_GAIN_MANUAL = BLADERF_GAIN_MGC #const BLADERF_PRIuFREQ = PRIu64 #const BLADERF_PRIxFREQ = PRIx64 #const BLADERF_SCNuFREQ = SCNu64 #const BLADERF_SCNxFREQ = SCNx64 const BLADERF_RX_MUX_BASEBAND_LMS = BLADERF_RX_MUX_BASEBAND const BLADERF_RETUNE_NOW = bladerf_timestamp(0) const BLADERF_CORR_LMS_DCOFF_I = BLADERF_CORR_DCOFF_I const BLADERF_CORR_LMS_DCOFF_Q = BLADERF_CORR_DCOFF_Q const BLADERF_CORR_FPGA_PHASE = BLADERF_CORR_PHASE const BLADERF_CORR_FPGA_GAIN = BLADERF_CORR_GAIN #const BLADERF_PRIuTS = PRIu64 #const BLADERF_PRIxTS = PRIx64 #const BLADERF_SCNuTS = SCNu64 #const BLADERF_SCNxTS = SCNx64 const BLADERF_META_STATUS_OVERRUN = 1 << 0 const BLADERF_META_STATUS_UNDERRUN = 1 << 1 const BLADERF_META_FLAG_TX_BURST_START = 1 << 0 const BLADERF_META_FLAG_TX_BURST_END = 1 << 1 const BLADERF_META_FLAG_TX_NOW = 1 << 2 const BLADERF_META_FLAG_TX_UPDATE_TIMESTAMP = 1 << 3 const BLADERF_META_FLAG_RX_NOW = 1 << 31 const BLADERF_META_FLAG_RX_HW_UNDERFLOW = 1 << 0 const BLADERF_META_FLAG_RX_HW_MINIEXP1 = 1 << 16 const BLADERF_META_FLAG_RX_HW_MINIEXP2 = 1 << 17 const BLADERF_STREAM_SHUTDOWN =nothing # Skipping MacroDefinition: BLADERF_STREAM_NO_DATA ( ( void * ) ( - 1 ) ) const BLADERF_IMAGE_MAGIC_LEN = 7 const BLADERF_IMAGE_CHECKSUM_LEN = 32 const BLADERF_IMAGE_RESERVED_LEN = 128 const BLADERF_TRIGGER_REG_ARM = UInt8(1 << 0) const BLADERF_TRIGGER_REG_FIRE = UInt8(1 << 1) const BLADERF_TRIGGER_REG_MASTER = UInt8(1 << 2) const BLADERF_TRIGGER_REG_LINE = UInt8(1 << 3) const BLADERF_ERR_UNEXPECTED = -1 const BLADERF_ERR_RANGE = -2 const BLADERF_ERR_INVAL = -3 const BLADERF_ERR_MEM = -4 const BLADERF_ERR_IO = -5 const BLADERF_ERR_TIMEOUT = -6 const BLADERF_ERR_NODEV = -7 const BLADERF_ERR_UNSUPPORTED = -8 const BLADERF_ERR_MISALIGNED = -9 const BLADERF_ERR_CHECKSUM = -10 const BLADERF_ERR_NO_FILE = -11 const BLADERF_ERR_UPDATE_FPGA = -12 const BLADERF_ERR_UPDATE_FW = -13 const BLADERF_ERR_TIME_PAST = -14 const BLADERF_ERR_QUEUE_FULL = -15 const BLADERF_ERR_FPGA_OP = -16 const BLADERF_ERR_PERMISSION = -17 const BLADERF_ERR_WOULD_BLOCK = -18 const BLADERF_ERR_NOT_INIT = -19 # exports const PREFIXES = ["bladerf_","BLADERF_"] for name in names(@__MODULE__; all=true), prefix in PREFIXES if startswith(string(name), prefix) @eval export $name end end export bladerf end # module
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
6425
# All bindings of RTLSDR exported by Clang module LibRtlsdr # --- Library call using librtlsdr_jll # --- Dependencies using CEnum # ---------------------------------------------------- # --- Enumeration # ---------------------------------------------------- @cenum rtlsdr_tuner::UInt32 begin RTLSDR_TUNER_UNKNOWN = 0 RTLSDR_TUNER_E4000 = 1 RTLSDR_TUNER_FC0012 = 2 RTLSDR_TUNER_FC0013 = 3 RTLSDR_TUNER_FC2580 = 4 RTLSDR_TUNER_R820T = 5 RTLSDR_TUNER_R828D = 6 end # ---------------------------------------------------- # --- Runtime structures # ---------------------------------------------------- mutable struct rtlsdr_dev end const rtlsdr_dev_t = rtlsdr_dev # typedef void ( * rtlsdr_read_async_cb_t ) ( unsigned char * buf , uint32_t len , void * ctx ) const rtlsdr_read_async_cb_t = Ptr{Cvoid} # ---------------------------------------------------- # --- Functions # ---------------------------------------------------- function rtlsdr_get_device_count() ccall((:rtlsdr_get_device_count, librtlsdr), UInt32, ()) end function rtlsdr_get_device_name(index) ccall((:rtlsdr_get_device_name, librtlsdr), Ptr{Cchar}, (UInt32,), index) end function rtlsdr_get_device_usb_strings(index, manufact, product, serial) ccall((:rtlsdr_get_device_usb_strings, librtlsdr), Cint, (UInt32, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}), index, manufact, product, serial) end function rtlsdr_get_index_by_serial(serial) ccall((:rtlsdr_get_index_by_serial, librtlsdr), Cint, (Ptr{Cchar},), serial) end function rtlsdr_open(dev, index) ccall((:rtlsdr_open, librtlsdr), Cint, (Ptr{Ptr{rtlsdr_dev_t}}, UInt32), dev, index) end function rtlsdr_close(dev) ccall((:rtlsdr_close, librtlsdr), Cint, (Ptr{rtlsdr_dev_t},), dev) end function rtlsdr_set_xtal_freq(dev, rtl_freq, tuner_freq) ccall((:rtlsdr_set_xtal_freq, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, UInt32, UInt32), dev, rtl_freq, tuner_freq) end function rtlsdr_get_xtal_freq(dev, rtl_freq, tuner_freq) ccall((:rtlsdr_get_xtal_freq, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, Ptr{UInt32}, Ptr{UInt32}), dev, rtl_freq, tuner_freq) end function rtlsdr_get_usb_strings(dev, manufact, product, serial) ccall((:rtlsdr_get_usb_strings, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}), dev, manufact, product, serial) end function rtlsdr_write_eeprom(dev, data, offset, len) ccall((:rtlsdr_write_eeprom, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, Ptr{UInt8}, UInt8, UInt16), dev, data, offset, len) end function rtlsdr_read_eeprom(dev, data, offset, len) ccall((:rtlsdr_read_eeprom, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, Ptr{UInt8}, UInt8, UInt16), dev, data, offset, len) end function rtlsdr_set_center_freq(dev, freq) ccall((:rtlsdr_set_center_freq, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, UInt32), dev, freq) end function rtlsdr_get_center_freq(dev) ccall((:rtlsdr_get_center_freq, librtlsdr), UInt32, (Ptr{rtlsdr_dev_t},), dev) end function rtlsdr_set_freq_correction(dev, ppm) ccall((:rtlsdr_set_freq_correction, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, Cint), dev, ppm) end function rtlsdr_get_freq_correction(dev) ccall((:rtlsdr_get_freq_correction, librtlsdr), Cint, (Ptr{rtlsdr_dev_t},), dev) end function rtlsdr_get_tuner_type(dev) ccall((:rtlsdr_get_tuner_type, librtlsdr), rtlsdr_tuner, (Ptr{rtlsdr_dev_t},), dev) end function rtlsdr_get_tuner_gains(dev, gains) ccall((:rtlsdr_get_tuner_gains, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, Ptr{Cint}), dev, gains) end function rtlsdr_set_tuner_gain(dev, gain) ccall((:rtlsdr_set_tuner_gain, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, Cint), dev, gain) end function rtlsdr_set_tuner_bandwidth(dev, bw) ccall((:rtlsdr_set_tuner_bandwidth, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, UInt32), dev, bw) end function rtlsdr_get_tuner_gain(dev) ccall((:rtlsdr_get_tuner_gain, librtlsdr), Cint, (Ptr{rtlsdr_dev_t},), dev) end function rtlsdr_set_tuner_if_gain(dev, stage, gain) ccall((:rtlsdr_set_tuner_if_gain, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, Cint, Cint), dev, stage, gain) end function rtlsdr_set_tuner_gain_mode(dev, manual) ccall((:rtlsdr_set_tuner_gain_mode, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, Cint), dev, manual) end function rtlsdr_set_sample_rate(dev, rate) ccall((:rtlsdr_set_sample_rate, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, UInt32), dev, rate) end function rtlsdr_get_sample_rate(dev) ccall((:rtlsdr_get_sample_rate, librtlsdr), UInt32, (Ptr{rtlsdr_dev_t},), dev) end function rtlsdr_set_testmode(dev, on) ccall((:rtlsdr_set_testmode, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, Cint), dev, on) end function rtlsdr_set_agc_mode(dev, on) ccall((:rtlsdr_set_agc_mode, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, Cint), dev, on) end function rtlsdr_set_direct_sampling(dev, on) ccall((:rtlsdr_set_direct_sampling, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, Cint), dev, on) end function rtlsdr_get_direct_sampling(dev) ccall((:rtlsdr_get_direct_sampling, librtlsdr), Cint, (Ptr{rtlsdr_dev_t},), dev) end function rtlsdr_set_offset_tuning(dev, on) ccall((:rtlsdr_set_offset_tuning, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, Cint), dev, on) end function rtlsdr_get_offset_tuning(dev) ccall((:rtlsdr_get_offset_tuning, librtlsdr), Cint, (Ptr{rtlsdr_dev_t},), dev) end function rtlsdr_reset_buffer(dev) ccall((:rtlsdr_reset_buffer, librtlsdr), Cint, (Ptr{rtlsdr_dev_t},), dev) end function rtlsdr_read_sync(dev, buf, len, n_read) ccall((:rtlsdr_read_sync, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, Ptr{Cvoid}, Cint, Ptr{Cint}), dev, buf, len, n_read) end function rtlsdr_wait_async(dev, cb, ctx) ccall((:rtlsdr_wait_async, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, rtlsdr_read_async_cb_t, Ptr{Cvoid}), dev, cb, ctx) end function rtlsdr_read_async(dev, cb, ctx, buf_num, buf_len) ccall((:rtlsdr_read_async, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, rtlsdr_read_async_cb_t, Ptr{Cvoid}, UInt32, UInt32), dev, cb, ctx, buf_num, buf_len) end function rtlsdr_cancel_async(dev) ccall((:rtlsdr_cancel_async, librtlsdr), Cint, (Ptr{rtlsdr_dev_t},), dev) end function rtlsdr_set_bias_tee(dev, on) ccall((:rtlsdr_set_bias_tee, librtlsdr), Cint, (Ptr{rtlsdr_dev_t}, Cint), dev, on) end # exports const PREFIXES = ["rtlsdr_"] for name in names(@__MODULE__; all=true), prefix in PREFIXES if startswith(string(name), prefix) @eval export $name end end end
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
7500
module RTLSDRBindings # --- Print radio config include("../../Printing.jl"); using .Printing # -- Loading driver bindings include("./LibRtlsdr.jl") using .LibRtlsdr using Printf # Methods extension import Base:close; # Symbols exportation export openRTLSDR; export updateCarrierFreq!; export updateSamplingRate!; export updateGain!; export recv; export recv!; export send; export print; export getError export RTLSDRBinding; # Utils to generate String containers """ Init an empty string of size n, filled with space. Usefull to have container to get string from UHD. """ initEmptyString(n) = String(ones(UInt8,n)*UInt8(32)) """ Retrict the big string used as log container to its usefull part """ function truncate(s::String) indexes = findfirst("\0",s) if isnothing(indexes) # No end of line, controls that it is not only whitespace if length(unique(s)) == 1 # String is empty, abord sO = " " else # Return the string as it is s0 = s end else # Truncated output sO = s[1: indexes[1] - 1] end return s end mutable struct RTLSDRRxWrapper buffer::Vector{UInt8} end # --- Main Rx structure mutable struct RTLSDRRx rtlsdr::RTLSDRRxWrapper carrierFreq::Float64 samplingRate::Float64; gain::Union{Int,Float64}; antenna::String; packetSize::Csize_t; released::Int; end # --- Main Tx structure mutable struct RTLSDRTx carrierFreq::Float64 samplingRate::Float64 gain::Union{Int,Float64} antenna::String packetSize::Csize_t released::Int end # --- Complete structure mutable struct RTLSDRBinding radio::Ref{Ptr{rtlsdr_dev_t}} rx::RTLSDRRx tx::RTLSDRTx end function openRTLSDR(carrierFreq,samplingRate,gain;agc_mode=0,tuner_gain_mode=0) # --- Instantiate a new RTLSDR device ptr_rtlsdr = Ref{Ptr{rtlsdr_dev_t}}() chan = 0 rtlsdr_open(ptr_rtlsdr,chan) # --- Get the instantiate object rtlsdr = ptr_rtlsdr[] rtlsdr_reset_buffer(rtlsdr) # --- Configure it based on what we want # Sampling rate (2MHz max ?) rtlsdr_set_sample_rate(rtlsdr,samplingRate) samplingRate = rtlsdr_get_sample_rate(rtlsdr) # Carrier freq rtlsdr_set_center_freq(rtlsdr,carrierFreq) carrierFreq = rtlsdr_get_center_freq(rtlsdr) # Gain mode rtlsdr_set_tuner_gain_mode(rtlsdr,tuner_gain_mode) rtlsdr_set_agc_mode(rtlsdr,agc_mode) # ---------------------------------------------------- # --- Wrap all into a custom structure # ---------------------------------------------------- # Instantiate a buffer to handle async receive. Size is arbritrary and will be modified afterwards buffer = zeros(UInt8,512) rtlsdrRx = RTLSDRRxWrapper(buffer) rx = RTLSDRRx( rtlsdrRx, carrierFreq, samplingRate, 0, "RX", 0, 0 ); tx = RTLSDRTx( carrierFreq, samplingRate, 0, "TX", 0, 0 ); radio = RTLSDRBinding( ptr_rtlsdr, rx, tx ) return radio end function updateCarrierFreq!(radio::RTLSDRBinding,carrierFreq) # --- Set the carrier frequency rtlsdr_set_center_freq(radio.radio[],carrierFreq) # --- Get the carrier frequency carrierFreq = rtlsdr_get_center_freq(radio.radio[]) # --- Update structure radio.rx.carrierFreq = carrierFreq; radio.tx.carrierFreq = carrierFreq; return carrierFreq; end function updateSamplingRate!(radio,samplingRate) # --- Set the sampling rate rtlsdr_set_sample_rate(radio.radio[],samplingRate) # --- Get the sampling rate samplingRate = rtlsdr_get_sample_rate(radio.radio[]) # --- Update Fields radio.rx.samplingRate = samplingRate; radio.tx.samplingRate = samplingRate; return samplingRate end function updateGain!(radio,gain) # @warn "Analog gain update is not supported for RTLSDR"; end function Base.print(rx::RTLSDRRx); strF = @sprintf(" Carrier Frequency: %2.3f MHz\n Sampling Frequency: %2.3f MHz\n",rx.carrierFreq/1e6,rx.samplingRate/1e6) @inforx "Current RTL-SDR Radio Configuration in Rx mode\n$strF"; end function Base.print(tx::RTLSDRTx); strF = @sprintf(" Carrier Frequency: %2.3f MHz\n Sampling Frequency: %2.3f MHz\n",tx.carrierFreq/1e6,tx.samplingRate/1e6) @infotx "Current RTL-SDR Radio Configuration in Rx mode\n$strF"; end function Base.print(radio::RTLSDRBinding) print(radio.rx); print(radio.tx); end function recv!(sig::Vector{ComplexF32},radio::RTLSDRBinding) nbSamples = length(sig) # --- Instantiation of UInt8 buffer if length(radio.rx.rtlsdr.buffer) !== 2*nbSamples # We need to redimension the size of the receive buffer buffer = zeros(UInt8,nbSamples * 2) radio.rx.rtlsdr.buffer = buffer end pointerSamples = Ref{Cint}(0) # --- Call the receive method ptr = pointer(radio.rx.rtlsdr.buffer,1) rtlsdr_read_sync(radio.radio[],ptr,nbSamples*2,pointerSamples) # --- Get the number of received complex symbols nbElem = pointerSamples[] ÷ 2 # --- From Bytes to complex byteToComplex!(sig,radio.rx.rtlsdr.buffer) return nbElem end function recv(radio::RTLSDRBinding,nbSamples) sig = zeros(ComplexF32,nbSamples) nbElem = recv!(sig,radio) (nbElem == 0) && @warnrx "No received samples !" return sig end """ Transform the input buffer of UInt8 into a complexF32 vector """ function byteToComplex!(sig::Vector{ComplexF32},buff::Vector{UInt8}) nbS = length(sig) @assert (length(buff) == 2nbS) "Complex buffer size should be 2 times lower (here $(length(sig)) than input Buffersize (here $(length(buff))" @inbounds @simd for n ∈ 1 : nbS sig[n] = _btoc(buff[2(n-1)+1]) + 1im*_btoc(buff[2(n-1)+2]) end end function byteToComplex(buff::Vector{UInt8}) N = length(buff) nbS = N ÷ 2 sig = zeros(ComplexF32,nbS) byteToComplex!(sig,buff) end """ Byte to float conversion """ function _btoc(in::UInt8) return in / 128 -1 end function close(radio::RTLSDRBinding) rtlsdr_close(radio.radio[]) radio.rx.released = 1; radio.tx.released = 1; @info "RTL-SDR device is now close" end function send(sig::Vector{Complex{Cfloat}},radio::RTLSDRBinding) @warntx "Unsupported send method for RTLSDR"; end function scan() # --- Using counting method to get the nbumber of devioes nE = LibRtlsdr.rtlsdr_get_device_count() if nE > 0 # Found a RTL SDR dongle println("Found $nE RTL-SDR dongle") # manufact = initEmptyString(200) # product = initEmptyString(200) # serial = initEmptyString(200) # radio = openRTLSDR(800e6,1e6,20) # rtlsdr_get_usb_strings(radio.radio[],manufact,product,serial) # (!isempty(manufact)) && (println("Manufact = $(truncate(manufact))")) # (!isempty(product)) && (println("Product = $(truncate(product))")) # (!isempty(serial)) && (println("Serial = $(truncate(serial))")) # close(radio) end return nE end function getError(radio::RTLSDRBinding) return 0 end function getMD(radio::RTLSDRBinding) return 0 end end
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
3348
# Testing SDR backends using Test using AbstractSDRs # ---------------------------------------------------- # --- Testing radioSim back end # ---------------------------------------------------- # This backend requires no SDR connected so we can use it by default # Most of the test are also sone in the comon API call but set a specific test call here # to test everything is OK on the API side and that specific RadioSim properties are OK (especially control that emulated received data is the one desired) include("test_RadioSim.jl") # ---------------------------------------------------- # --- Test functions # ---------------------------------------------------- # Define here key behaviour common for all radio # You can have a look here to find pratical examples of radio use include("test_functions.jl") # ---------------------------------------------------- # --- Common API call for all backend # ---------------------------------------------------- # Issue is that we need a connected device to perform all test so we will do as follows # => Try to scan for device. If detected then proceed to the test, otherwise drop the test # For UHD, we need to hardcode a potential IP address in case of non broadcast ehternet address. If we detect the UHD device with scan(:uhd) the we use the associated IP address. Otherwise we use UHD_ADDRESS. It means that in case of non broadcast ethernet link, you should modify the following line according to your UHD IP address # --- USRP address global UHD_ADDRESS = "192.168.10.16" # This address may vary from time to time, not really sure how to handle dynamic testing # --- Define test backend # backends = [:radiosim;:uhd;:pluto;:rtlsdr] backends = [:radiosim;:rtlsdr] # backends = [:radiosim;:pluto] for sdr ∈ backends # --- Flaging test println("######################################") println("# --- Testing $sdr backend ---") println("######################################") # --- Test scan str = scan(sdr) if isempty(str) println("No device found, rescan with IP address $UHD_ADDRESS") # If we have nothing, try with the USRP address str = scan(sdr;args="addr=$UHD_ADDRESS") end if isempty(str) # ---------------------------------------------------- # --- We have find nothing, drop the rest of the tests # ---------------------------------------------------- @warn "Unable to detect any SDR devices based on backend $sdr\n Abandon rest of tests" else # For UHD, we update str to be sure we can use the SDR latter on global UHD_ADDRESS = str[1] # ---------------------------------------------------- # --- Testing stuff # ---------------------------------------------------- @testset "Opening" begin # check_scan(sdr;UHD_ADDRESS) check_open(sdr) end @testset "Radio configuration" begin check_carrierFreq(sdr) check_samplingRate(sdr) check_gain(sdr) end @testset "Checking data retrieval" begin check_recv(sdr) check_recv_preAlloc(sdr) check_recv_iterative(sdr) end @testset "Checking data transmission" begin check_send(sdr) end end end
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
5531
# ---------------------------------------------------- # --- Radio Sim test file # ---------------------------------------------------- # This file is dedicated to RadioSim backend # ---------------------------------------------------- # --- Define test routines # ---------------------------------------------------- """ Test that the device can be open, configured and closed """ function check_open() # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain sdr = :radiosim # --- Create the E310 device global sdr =openSDR(sdr,carrierFreq,samplingRate,gain); # Type is OK @test typeof(sdr) == RadioSim # SDR is not released yet @test sdr.rx.released == false # Configuration : Carrier Freq @test sdr.rx.carrierFreq == carrierFreq @test sdr.tx.carrierFreq == carrierFreq # Configuration : Badnwidth @test sdr.rx.samplingRate == samplingRate @test sdr.tx.samplingRate == samplingRate # --- We close the SDR close(sdr) @test isClosed(sdr) == true end """ Check the carrier frequency update of the RadioSim device """ function check_carrierFreq() # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain sdr = :radiosim # --- Create the E310 device global sdr =openSDR(sdr,carrierFreq,samplingRate,gain); # Classic value, should work updateCarrierFreq!(sdr,800e6) @test sdr.rx.carrierFreq == 800e6 @test sdr.tx.carrierFreq == 800e6 # Targeting WiFi, should work updateCarrierFreq!(sdr,2400e6) @test sdr.rx.carrierFreq == 2400e6 @test sdr.tx.carrierFreq == 2400e6 close(sdr); @test isClosed(sdr) == true end """ Check the sampling frequency update of the RadioSim device """ function check_samplingRate() # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain sdr = :radiosim # --- Create the E310 device global sdr =openSDR(sdr,carrierFreq,samplingRate,gain); # Classic value, should work updateSamplingRate!(sdr,8e6) @test sdr.rx.samplingRate == 8e6 @test sdr.tx.samplingRate == 8e6 # Targeting WiFi, should work updateSamplingRate!(sdr,15.36e6) @test sdr.rx.samplingRate == 15.36e6 @test sdr.tx.samplingRate == 15.36e6 close(sdr); @test isClosed(sdr) == true end """ Check the gain update for RadioSim """ function check_gain() # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain sdr = :radiosim # --- Create the E310 device global sdr =openSDR(sdr,carrierFreq,samplingRate,gain); # Classic value, should work updateGain!(sdr,20) # @test sdr.rx.samplingRate == 8e6 # @test sdr.tx.samplingRate == 8e6 close(sdr); @test isClosed(sdr) == true end """ Test that the device can received data """ function check_recv() # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain sdr = :radiosim # --- Create the E310 device global sdr =openSDR(sdr,carrierFreq,samplingRate,gain); sig = recv(sdr,1024) @test length(sig) == 1024 @test eltype(sig) == Complex{Float32} close(sdr) @test isClosed(sdr) == true end """ Test that radiosim device can feed desired data """ function check_recv_prealloc() # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 100e6; # --- Targeted bandwdith gain = 0.0; # --- Rx gain sdr = :radiosim; nbSamples = 1024; # ---------------------------------------------------- # --- Buffer emulation # ---------------------------------------------------- buffer = collect(1:4096); # --- Create the E310 device global sdr =openSDR(sdr,carrierFreq,samplingRate,gain;packetSize=512,buffer=buffer); sig = recv(sdr,1024) @test length(sig) == 1024 @test eltype(sig) == Complex{Float32} # The first call should give the 1024 fist samples @test all(sig .== collect(1:1024)) # --- Second call give second part sig = recv(sdr,1024) @test length(sig) == 1024 @test eltype(sig) == Complex{Float32} @test all(sig .== collect(1025:2048)) # --- Third call to have the end sig = recv(sdr,2048) @test length(sig) == 2048 @test eltype(sig) == Complex{Float32} @test all(sig .== collect(2049:4096)) # --- Another complete call with complete buffer sig = recv(sdr,4096) @test length(sig) == 4096 @test eltype(sig) == Complex{Float32} @test all(sig .== buffer) # --- Close radio close(sdr) @test isClosed(sdr) == true end # ---------------------------------------------------- # --- Test calls # ---------------------------------------------------- @testset "RadioSims Backend " begin @testset "Scanning and opening" begin check_open() end @testset "Radio configuration" begin check_carrierFreq() check_samplingRate() check_gain() end @testset "Checking data retrieval" begin check_recv() check_recv_prealloc() end end
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
8877
# --- USRP address global USRP_ADDRESS = "192.168.10.16" # This address may vary from time to time, not really sure how to handle dynamic testing # # # ---------------------------------------------------- # --- Define test routines # ---------------------------------------------------- """ Scan with uhd_find_devices and return the USRP identifier """ function check_scan() # --- First we use no parameter (broadcast ethernet link) str = scan(:uhd) if length(str) == 0 println("No UHD device found. Be sure that a USRP is connected to your PC, and that the ethernet link is up. We try to use the direct IP address now (which is $USRP_ADDRESS). You can change its value depending on your ethernet setup") else # We find a device so we update the USRP address based on what we have found global USRP_ADDRESS = str[1][findfirst("_addr=",str[1])[end] .+ (1:13)] end # The direct call with the IP address should give something str = uhd_find_devices("addr=$USRP_ADDRESS") @test length(str) > 0 return str end """ Test that the device can be open, configured and closed """ function check_open() # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain sdr = :uhd # --- Create the device global sdr = openSDR(sdr,carrierFreq, samplingRate, gain;args="addr=$USRP_ADDRESS"); # Type is OK @test typeof(sdr) == UHDBinding # SDR is not released yet @test isClosed(sdr) == false # Configuration : Carrier Freq @test getCarrierFreq(sdr) == carrierFreq @test getCarrierFreq(sdr,mode=:rx) == carrierFreq @test getCarrierFreq(sdr,mode=:tx) == carrierFreq # Configuration : Badnwidth @test getSamplingRate(sdr) == samplingRate @test getSamplingRate(sdr,mode=:rx) == samplingRate @test getSamplingRate(sdr,mode=:tx) == samplingRate # --- We close the SDR close(sdr) @test isClosed(sdr) == true end """ Check the carrier frequency update of the USRP device """ function check_carrierFreq() # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain # --- Create the device sdr = :uhd # --- Create the device global sdr = openSDR(sdr,carrierFreq, samplingRate, gain;args="addr=$USRP_ADDRESS"); # Classic value, should work updateCarrierFreq!(sdr,800e6) @test getCarrierFreq(sdr) == 800e6 @test getCarrierFreq(sdr,mode=:rx) == 800e6 @test getCarrierFreq(sdr,mode=:tx) == 800e6 # Targeting WiFi, should work updateCarrierFreq!(sdr,2400e6) @test getCarrierFreq(sdr) == 2400e6 @test getCarrierFreq(sdr,mode=:rx) == 2400e6 @test getCarrierFreq(sdr,mode=:tx) == 2400e6 # If we specify a out of range frequency, it should bound to max val # TODO Check that is should be max freq range, but don't know the range as different USRP may be used # Adding tables with various ranges to check taht this is the expected value ? eF= updateCarrierFreq!(sdr,9e9) @test getCarrierFreq(sdr) != 9e9 @test getCarrierFreq(sdr,mode=:rx) != 9e9 @test getCarrierFreq(sdr,mode=:tx) != 9e9 @test getCarrierFreq(sdr) == eF @test getCarrierFreq(sdr,mode=:rx) == eF @test getCarrierFreq(sdr,mode=:tx) == eF close(sdr); @test isClosed(sdr) == true end """ Check the sampling frequency update of the USRP device """ function check_samplingRate() # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain sdr = :uhd # --- Create the device global sdr = openSDR(sdr,carrierFreq, samplingRate, gain;args="addr=$USRP_ADDRESS"); # Classic value, should work updateSamplingRate!(sdr,8e6) @test getSamplingRate(sdr) == 8e6 @test getSamplingRate(sdr,mode=:rx) == 8e6 @test getSamplingRate(sdr,mode=:tx) == 8e6 # Targeting WiFi, should work updateSamplingRate!(sdr,15.36e6) @test getSamplingRate(sdr) == 15.36e6 @test getSamplingRate(sdr,mode=:rx) == 15.36e6 @test getSamplingRate(sdr,mode=:tx) == 15.36e6 # If we specify a out of range frequency, it should bound to max val eS = updateSamplingRate!(sdr,100e9) # @test getSamplingRate(sdr) != 100e9 # @test getSamplingRate(sdr,mode=:rx) != 100e9 # @test getSamplingRate(sdr,mode=:tx) != 100e9 @test getSamplingRate(sdr) == eS @test getSamplingRate(sdr,mode=:rx) == eS @test getSamplingRate(sdr,mode=:tx) == eS close(sdr); @test isClosed(sdr) == true end """ Check the gain update for the USRP device """ function check_gain() # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain sdr = :uhd # --- Create the device global sdr = openSDR(sdr,carrierFreq, samplingRate, gain;args="addr=$USRP_ADDRESS"); # Classic value, should work nG = updateGain!(sdr,20) @test getGain(sdr) == 20 @test getGain(sdr;mode=:rx) == 20 @test getGain(sdr;mode=:tx) == 20 @test getGain(sdr) == nG @test getGain(sdr;mode=:rx) == nG @test getGain(sdr;mode=:tx) == nG close(sdr); @test isClosed(sdr) == true end """ Test that the device can received data """ function check_recv() # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain sdr = :uhd # --- Create the device global sdr = openSDR(sdr,carrierFreq, samplingRate, gain;args="addr=$USRP_ADDRESS"); sig = recv(sdr,1024) @test length(sig) == 1024 @test eltype(sig) == Complex{Float32} close(sdr) @test isClosed(sdr) == true end """ Test that the device can received data with pre-allocation """ function check_recv_preAlloc() # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain sdr = :uhd global sdr = openUHD(carrierFreq, samplingRate, gain;args="addr=$USRP_ADDRESS"); sig = zeros(ComplexF32,2*1024) recv!(sig,sdr) @test length(sig) == 1024*2 @test eltype(sig) == Complex{Float32} @test length(unique(sig)) > 1 # To be sure we have populated array with data close(sdr) @test isClosed(sdr) == true end """ Test that the device can received data several time """ function check_recv_iterative() # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain # --- Create the device sdr = :uhd global sdr = openUHD(carrierFreq, samplingRate, gain;args="addr=$USRP_ADDRESS"); sig = zeros(ComplexF32,2*1024) nbPackets = 0 maxPackets = 100_000 for _ ∈ 1 : 1 : maxPackets # --- Get a burst recv!(sig,sdr) # --- Increment packet index nbPackets += 1 end @test nbPackets == maxPackets close(sdr) @test isClosed(sdr) == true end """ Test that the device sucessfully transmit data """ function check_send() carrierFreq = 770e6; samplingRate = 4e6; gain = 50.0; nbSamples = 4096*2 sdr = :uhd # --- Create the device global sdr = openSDR(sdr,carrierFreq, samplingRate, gain;args="addr=$USRP_ADDRESS"); print(sdr); # --- Create a sine wave f_c = 3940; buffer = 0.5.*[exp.(2im * π * f_c / samplingRate * n) for n ∈ (0:nbSamples-1)]; buffer = convert.(Complex{Cfloat},buffer); buffer2 = 0.5.*[exp.(2im * π * 10 * f_c / samplingRate * n) for n ∈ (0:nbSamples-1)]; buffer2 = convert.(Complex{Cfloat},buffer2); buffer = [buffer;buffer2]; cntAll = 0; maxPackets = 10_000 nbPackets = 0 for _ ∈ 1 : maxPackets send(sdr,buffer,false); # --- Increment packet index nbPackets += 1 end @test nbPackets == maxPackets close(sdr) @test isClosed(sdr) == true end # # ---------------------------------------------------- # # --- Test calls # # ---------------------------------------------------- # @testset "UHDBindings backend" begin # @testset "Scanning and opening" begin # check_scan() # check_open() # end # @testset "Radio configuration" begin # check_carrierFreq() # check_samplingRate() # check_gain() # end # @testset "Checking data retrieval" begin # check_recv() # check_recv_preAlloc() # check_recv_iterative() # end # @testset "Checking data transmission" begin # check_send() # end # end
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
code
9398
# ---------------------------------------------------- # --- Define test routines # ---------------------------------------------------- """ Scan with uhd_find_devices and return the USRP identifier """ function check_scan(b::Symbol;UHD_ADDRESS) # --- First we use no parameter (broadcast ethernet link) str = scan(b) if length(str) == 0 println("No UHD device found. Be sure that a USRP is connected to your PC, and that the ethernet link is up. We try to use the direct IP address now (which is $UHD_ADDRESS). You can change its value depending on your ethernet setup") else # We find a device so we update the USRP address based on what we have found if b == :uhd global UHD_ADDRESS = str[1][findfirst("_addr=",str[1])[end] .+ (1:13)] end end # The direct call with the IP address should give something str = scan(b;args="addr=$UHD_ADDRESS") @test length(str) > 0 return str end """ Test that the device can be open, configured and closed """ function check_open(sdrName) # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 1e6; # --- Targeted bandwdith gain = 0; # --- Rx gain # --- Create the device global sdr = openSDR(sdrName,carrierFreq, samplingRate, gain;args="addr=$UHD_ADDRESS"); # Type is OK if sdrName == :uhd @test typeof(sdr) == UHDBinding elseif sdrName == :pluto @test typeof(sdr) == PlutoSDR elseif sdrName == :radiosim @test typeof(sdr) == RadioSim elseif sdrName == :rtlsdr @test typeof(sdr) == RTLSDRBinding else @error "Untested radio backend" end # SDR is not released yet @test isClosed(sdr) == false # Configuration : Carrier Freq @test getCarrierFreq(sdr) ≈ carrierFreq @test getCarrierFreq(sdr,mode=:rx) ≈ carrierFreq @test getCarrierFreq(sdr,mode=:tx) ≈ carrierFreq # Configuration : Bandwidth @test getSamplingRate(sdr) == samplingRate @test getSamplingRate(sdr,mode=:rx) ≈ samplingRate @test getSamplingRate(sdr,mode=:tx) ≈ samplingRate # --- We close the SDR close(sdr) @test isClosed(sdr) == true end """ Check the carrier frequency update of the USRP device """ function check_carrierFreq(sdrName) # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain # --- Create the device global sdr = openSDR(sdrName,carrierFreq, samplingRate, gain;args="addr=$UHD_ADDRESS"); # Classic value, should work updateCarrierFreq!(sdr,800e6) @test getCarrierFreq(sdr) ≈ 800e6 @test getCarrierFreq(sdr,mode=:rx) ≈ 800e6 @test getCarrierFreq(sdr,mode=:tx) ≈ 800e6 # Targeting WiFi, should work updateCarrierFreq!(sdr,2400e6) @test getCarrierFreq(sdr) ≈ 2400e6 @test getCarrierFreq(sdr,mode=:rx) ≈ 2400e6 @test getCarrierFreq(sdr,mode=:tx) ≈ 2400e6 # If we specify a out of range frequency, it should bound to max val # TODO Check that is should be max freq range, but don't know the range as different USRP may be used # Adding tables with various ranges to check taht this is the expected value ? # eF= updateCarrierFreq!(sdr,9e9) # @test getCarrierFreq(sdr) != 9e9 # @test getCarrierFreq(sdr,mode=:rx) != 9e9 # @test getCarrierFreq(sdr,mode=:tx) != 9e9 # @test getCarrierFreq(sdr) == eF # @test getCarrierFreq(sdr,mode=:rx) == eF # @test getCarrierFreq(sdr,mode=:tx) == eF close(sdr); @test isClosed(sdr) == true end """ Check the sampling frequency update of the USRP device """ function check_samplingRate(sdrName) # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain # --- Create the device global sdr = openSDR(sdrName,carrierFreq, samplingRate, gain;args="addr=$UHD_ADDRESS"); # Classic value, should work updateSamplingRate!(sdr,8e6) @test getSamplingRate(sdr) ≈ 8e6 @test getSamplingRate(sdr,mode=:rx) ≈ 8e6 @test getSamplingRate(sdr,mode=:tx) ≈ 8e6 # Targeting WiFi, should work updateSamplingRate!(sdr,15.36e6) @test getSamplingRate(sdr) ≈ 15.36e6 @test getSamplingRate(sdr,mode=:rx) ≈ 15.36e6 @test getSamplingRate(sdr,mode=:tx) ≈ 15.36e6 # If we specify a out of range frequency, it should bound to max val eS = updateSamplingRate!(sdr,1e9) # @test getSamplingRate(sdr) != 100e9 # @test getSamplingRate(sdr,mode=:rx) != 100e9 # @test getSamplingRate(sdr,mode=:tx) != 100e9 # @test getSamplingRate(sdr) == eS # @test getSamplingRate(sdr,mode=:rx) == eS # @test getSamplingRate(sdr,mode=:tx) == eS close(sdr); @test isClosed(sdr) == true end """ Check the gain update for the USRP device """ function check_gain(sdrName) if sdrName == :rtlsdr || sdrName == :bladerf # No gain support for RTLSDR # Auto gain fro bladerf else # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain # --- Create the device global sdr = openSDR(sdrName,carrierFreq, samplingRate, gain;args="addr=$UHD_ADDRESS"); # Classic value, should work nG = updateGain!(sdr,20) @test getGain(sdr) == 20 @test getGain(sdr;mode=:rx) == 20 @test getGain(sdr;mode=:tx) == 20 @test getGain(sdr) == nG @test getGain(sdr;mode=:rx) == nG @test getGain(sdr;mode=:tx) == nG close(sdr); @test isClosed(sdr) == true end end """ Test that the device can received data """ function check_recv(sdrName) # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain # --- Create the device global sdr = openSDR(sdrName,carrierFreq, samplingRate, gain;args="addr=$UHD_ADDRESS"); sig = recv(sdr,1024) @test length(sig) == 1024 @test eltype(sig) == Complex{Float32} close(sdr) @test isClosed(sdr) == true end """ Test that the device can received data with pre-allocation """ function check_recv_preAlloc(sdrName) # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain global sdr = openSDR(sdrName,carrierFreq, samplingRate, gain;args="addr=$UHD_ADDRESS",packetSize=4096); sig = zeros(ComplexF32,2*1024) recv!(sig,sdr) @test length(sig) == 1024*2 @test eltype(sig) == Complex{Float32} @test length(unique(sig)) > 1 # To be sure we have populated array with data close(sdr) @test isClosed(sdr) == true end """ Test that the device can received data several time """ function check_recv_iterative(sdrName) # --- Main parameters carrierFreq = 440e6; # --- The carrier frequency samplingRate = 8e6; # --- Targeted bandwdith gain = 0; # --- Rx gain # --- Create the device global sdr = openSDR(sdrName,carrierFreq, samplingRate, gain;args="addr=$UHD_ADDRESS",packetSize=4096); sig = zeros(ComplexF32,2*1024) nbPackets = 0 maxPackets = 10_000 for _ ∈ 1 : 1 : maxPackets # --- Get a burst recv!(sig,sdr) # --- Increment packet index nbPackets += 1 end @test nbPackets == maxPackets close(sdr) @test isClosed(sdr) == true end """ Test that the device sucessfully transmit data """ function check_send(sdrName) if sdrName == :rtlsdr # No need to do anything else carrierFreq = 770e6; samplingRate = 4e6; gain = 50.0; nbSamples = 4096*2 # --- Create the device global sdr = openSDR(sdrName,carrierFreq, samplingRate, gain;args="addr=$UHD_ADDRESS",packetSize=4096); # --- Create a sine wave f_c = 3940; buffer = 0.5.*[exp.(2im * π * f_c / samplingRate * n) for n ∈ (0:nbSamples-1)]; buffer = convert.(Complex{Cfloat},buffer); buffer2 = 0.5.*[exp.(2im * π * 10 * f_c / samplingRate * n) for n ∈ (0:nbSamples-1)]; buffer2 = convert.(Complex{Cfloat},buffer2); buffer = [buffer;buffer2]; cntAll = 0; maxPackets = 10_000 nbPackets = 0 for _ ∈ 1 : maxPackets send(sdr,buffer,false); # --- Increment packet index nbPackets += 1 end @test nbPackets == maxPackets close(sdr) @test isClosed(sdr) == true end end # # ---------------------------------------------------- # # --- Test calls # # ---------------------------------------------------- # @testset "UHDBindings backend" begin # @testset "Scanning and opening" begin # check_scan() # check_open() # end # @testset "Radio configuration" begin # check_carrierFreq() # check_samplingRate() # check_gain() # end # @testset "Checking data retrieval" begin # check_recv() # check_recv_preAlloc() # check_recv_iterative() # end # @testset "Checking data transmission" begin # check_send() # end # end
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
docs
6438
<div align="center"> <img src="docs/src/assets/logoAbstractSDRs.png" alt="UHDBindings.jl" width="420"> </div> # AbstractSDRs.jl [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://juliatelecom.github.io/AbstractSDRs.jl/dev/index.html) ## Purpose This package proposes a single API to monitor different kind of Software Defined Radio. We define several SDR backends that can be piloted by the same API. With AbstractSDRs, the following SDRs can be used - All Universal Software Radio Peripheral [USRP](https://files.ettus.com/manual/), based on [UHDBindings](https://github.com/JuliaTelecom/UHDBindings.jl) package - RTL SDR dongle, with inclusion of [RTLSDR package](https://github.com/dressel/RTLSDR.jl) - Any device connected to a remote PC with a network connection (for instance, Exxx USRP device) on which a Julia session works and run AbstractSDRs package. - The ADALM Pluto SDR, through [AdalmPluto](https://github.com/JuliaTelecom/AdalmPluto.jl) - A pure simulation package (RadioSims.jl) useful for testing without radio or do re-doing offline dataflow processing populated by a given buffer AbstractSDRs provides an unified API to open, transmit and received samples and close the SDRs. For instance, in order to get 4096 samples at 868MHz with a instantaneous bandwidth of 16MHz, with a 30dB Rx Gain, assuming that a USRP is connected, the following Julia code will do the trick and returns a vector with type Complex{Cfloat} with 4096 samples. function main() # ---------------------------------------------------- # --- Physical layer and RF parameters # ---------------------------------------------------- carrierFreq = 868e6; # --- The carrier frequency samplingRate = 16e6; # --- Targeted bandwdith rxGain = 30.0; # --- Rx gain nbSamples = 4096; # --- Desired number of samples # ---------------------------------------------------- # --- Getting all system with function calls # ---------------------------------------------------- # --- Creating the radio ressource # The first parameter is to tune the Rx board radio = openSDR(:uhd,carrierFreq,samplingRate,rxGain); # --- Display the current radio configuration print(radio); # --- Getting a buffer from the radio sig = recv(radio,nbSamples); # --- Release the radio ressources close(radio); # --- Output to signal return sig; end Note that the SDR discrimination is done through the "UHDRx" parameter when opening the device, which states here that the UHD driver should be used, and that the radio will receive samples. To get the same functionnality with a Adalm Pluto dongle, the same code can be used, changing only `radio = openSDR(:uhd,carrierFreq,samplingRate,rxGain);` by `radio = openSDR(:pluto,carrierFreq,samplingRate,rxGain); ` ## Installation The package can be installed with the Julia package manager. From the Julia REPL, type `]` to enter the Pkg REPL mode and run: ``` pkg> add AbstractSDRs ``` Or, equivalently, via the `Pkg` API: ```julia julia> import Pkg; Pkg.add("AbstractSDRs") ``` ## To cite this work If you use `AbstractSDRs.jl` we encourage you to cite this work that you can find [on HAL](https://hal.archives-ouvertes.fr/hal-03122623): ``` @InProceedings{Lavaud2021, author = {Lavaud, C and \textbf{Gerzaguet, R} and Gautier, M and Berder, O.}, title = {{AbstractSDRs: Bring down the two-language barrier with Julia Language for efficient SDR prototyping}}, booktitle = {IEEE Embedded Systems Letters (ESL)}, year = {2021}, doi = {10.1109/LES.2021.3054174}, } ``` ## Backends AbstractSDRs wraps and implements different SDR backends that can be used when opening a radio device. The current list of supported SDR backends can be obtained via `getSupportedSDRs`. When instantiate a radio device (with `openSDR`), the first argument is the radio backend and parameters associated to a specific backend can be used with keywords. Some specific functions can also be exported based in the selected backend. The list is given in the sub-backend part ### UHD backend AbstractSDRs can be used with Universal Radio Peripheral (USRP) with the use of `UHDBindings.jl` package. The backend is identified by the symbol `:uhd`. This backend supports ths following keywords - `args=""` to specify any UHD argument in initialisation. Please refer to the UHD doc. For instance, FPGA bitstream path can be specified with `args="fgpa=path/to/image.bit"`. The IP address of the USRP can be added with `args="addr=192.168.10.xx"`. AbstractSDRs package also exports the following specific functions - NONE. ### RadioSim This backend is useful when one wants to test a processing chain without having a radio as it simulates the behaviour of a SDR (configuration and buffer management). It is also useful when you have some acquisition in a given file (or buffer) as we can give the radio device a buffer which is then used to provide samples (as `recv` gives chunk of this buffer based on the desired size in a circular manner). This backend supports ths following keywords - `packetSize` to specify the size of each packet given by the radio. By default the value is 1024 complex samples - `buffer` to give to the radio a buffer to be used when emulating the reception. The following rules occur - If `packetSize` is not given, the provided buffer will be `buffer` each time the `recv` command is used - If `packetSize` is higher than the size of the proposed buffer, the buffer will be circulary copied to provive `packetSize` complex samples - If `packetSize` is lower than the size of the proposed buffer, `recv` will returns `packetSize` samples from `buffer` and the buffer will be browsed cicularly - If no buffer is given, `packetSize` random data will be generated at the init of the radio and proposed each time `recv`is called AbstractSDRs package also exports the following specific functions related to RadioSims - `updatePacketSize` to update the size of the radio packet. - `updateBuffer` to update the radio buffer ### Pluto This backend can be used with ADALM Pluto SDR device. ## SDROverNetworks ## Documentation - [**STABLE**](https://juliatelecom.github.io/AbstractSDRs.jl/dev/index.html) &mdash; **documentation of the most recently tagged version.** ## Changelog - 0.5.1 : Correct potential bug in data overflow for bladeRF backend
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
docs
136
# Common functions ```@autodocs Modules = [AbstractSDRs] Pages = ["AbstractSDRs.jl"]; Order = [:function, :type] Depth = 1 ```
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
docs
6377
# AbstractSDRs.jl [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://JuliaTelecom.github.io/AbstractSDRs.jl/dev/index.html) ## Purpose This package proposes a single API to monitor different kind of Software Defined Radio. We define several SDR backends that can be piloted by the same API. With AbstractSDRs, the following SDRs can be used - All Universal Software Radio Peripheral [USRP](https://files.ettus.com/manual/), based on [UHDBindings](https://github.com/RGerzaguet/UHDBindings.jl) package - RTL SDR dongle, with inclusion of [RTLSDR package](https://github.com/dressel/RTLSDR.jl) - Any device connected to a remote PC with a network connection (for instance, Exxx USRP device) on which a Julia session works and run AbstractSDRs package. - The ADALM Pluto SDR, through a specific package (WIP) - A pure simulation package usefull for testing without radio or do re-doing offline dataflow processing based on a given buffer AbstractSDRs provides an unified API to open, transmit and received samples and close the SDRs. For instance, in order to get 4096 samples at 868MHz with a instantaneous bandwidth of 16MHz, with a 30dB Rx Gain, assuming that a USRP is connected, the following Julia code will do the trick and returns a vector with type Complex{Cfloat} with 4096 samples. function main() # ---------------------------------------------------- # --- Physical layer and RF parameters # ---------------------------------------------------- carrierFreq = 868e6; # --- The carrier frequency samplingRate = 16e6; # --- Targeted bandwdith rxGain = 30.0; # --- Rx gain nbSamples = 4096; # --- Desired number of samples # ---------------------------------------------------- # --- Getting all system with function calls # ---------------------------------------------------- # --- Creating the radio ressource # The first parameter is to tune the Rx board radio = openSDR("UHDRx",carrierFreq,samplingRate,rxGain); # --- Display the current radio configuration print(radio); # --- Getting a buffer from the radio sig = recv(radio,nbSamples); # --- Release the radio ressources close(radio); # --- Output to signal return sig; end Note that the SDR discrimination is done through the "UHDRx" parameter when opening the device, which states here that the UHD driver should be used, and that the radio will receive samples. To get the same functionnality with a RTL SDR dongle, the following code can be used. function main() # ---------------------------------------------------- # --- Physical layer and RF parameters # ---------------------------------------------------- carrierFreq = 868e6; # --- The carrier frequency samplingRate = 16e6; # --- Targeted bandwdith rxGain = 30.0; # --- Rx gain nbSamples = 4096; # --- Desired number of samples # ---------------------------------------------------- # --- Getting all system with function calls # ---------------------------------------------------- # --- Creating the radio ressource # The first parameter is to tune the Rx board radio = openSDR("RTLRx",carrierFreq,samplingRate,rxGain); # --- Display the current radio configuration print(radio); # --- Getting a buffer from the radio sig = recv(radio,nbSamples); # --- Release the radio ressources close(radio); # --- Output to signal return sig; end Note that the only difference lies in the radio opening. ## Installation The package can be installed with the Julia package manager. From the Julia REPL, type `]` to enter the Pkg REPL mode and run: ``` pkg> add AbstractSDRs ``` Or, equivalently, via the `Pkg` API: ```julia julia> import Pkg; Pkg.add("AbstractSDRs") ``` ## Backends AbstractSDRs wraps and implements different SDR backends that can be used when opening a radio device. The current list of supported SDR backends can be obtained via `getSupportedSDR`. When instantiate a radio device (with `openSDR`), the first argument is the radio backend and parameters associated to a specific backend can be used with keywords. Some specific functions can also be exported based in the selected backend. The list is given in the sub-backend part ### UHD backend AbstractSDRs can be used with Universal Radio Peripheral (USRP) with the use of `UHDBindings.jl` package. The backend is identified by the symbol `:uhd`. This backend supports ths following keywords - `args=""` to specify any UHD argument in initialisation. Please refer to the UHD doc. For instance, FPGA bitstream path can be specified with `args="fgpa=path/to/image.bit"`. The IP address of the USRP can be added with `args="addr=192.168.10.xx"`. AbstractSDRs package also exports the following specific functions - NONE. ### RadioSim This backend is useful when one wants to test a processing chain without having a radio as it simulates the behaviour of a SDR (configuration and buffer management). It is also useful when you have some acquisition in a given file (or buffer) as we can give the radio device a buffer which is then used to provide samples (as `recv` gives chunk of this buffer based on the desired size in a circular manner). This backend supports ths following keywords - `packetSize` to specify the size of each packet given by the radio. By default the value is 1024 complex samples - `buffer` to give to the radio a buffer to be used when emulating the reception. The following rules occur - If `packetSize` is not given, the provided buffer will be `buffer` each time the `recv` command is used - If `packetSize` is higher than the size of the proposed buffer, the buffer will be circulary copied to provive `packetSize` complex samples - If `packetSize` is lower than the size of the proposed buffer, `recv` will returns `packetSize` samples from `buffer` and the buffer will be browsed cicularly - If no buffer is given, `packetSize` random data will be generated at the init of the radio and proposed each time `recv`is called AbstractSDRs package also exports the following specific functions related to RadioSims - `updatePacketSize` to update the size of the radio packet. - `updateBuffer` to update the radio buffer ### Pluto This backend can be used with ADALM Pluto SDR device. ### SDROverNetworks
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
docs
2116
# Benchmark for Rx link The following script allows to benchmark the effective rate from the receiver. To do so we compute the number of samples received in a given time. The timing is measured fro the timestamp obtained from the radio. module Benchmark # ---------------------------------------------------- # --- Modules & Utils # ---------------------------------------------------- # --- External modules using UHDBindings # --- Functions """ Calculate rate based on UHD timestamp """ function getRate(tInit,tFinal,nbSamples) sDeb = tInit.intPart + tInit.fracPart; sFin = tFinal.intPart + tFinal.fracPart; timing = sFin - sDeb; return nbSamples / timing; end """ Main call to monitor Rx rate """ function main(samplingRate) # ---------------------------------------------------- # --- Physical layer and RF parameters # ---------------------------------------------------- # --- Create the radio object in function carrierFreq = 770e6; gain = 50.0; radio = openSDR(:uhd,carrierFreq,samplingRate,gain); # --- Print the configuration print(radio); # --- Init parameters # Get the radio size for buffer pre-allocation nbSamples = radio.packetSize; # We will get complex samples from recv! method sig = zeros(Complex{Cfloat},nbSamples); # --- Targeting 2 seconds acquisition # Init counter increment nS = 0; # Max counter definition nbBuffer = 2*samplingRate; # --- Timestamp init p = recv!(sig,radio); nS += p; timeInit = Timestamp(getTimestamp(radio)...); while true # --- Direct call to avoid allocation p = recv!(sig,radio); # --- Ensure packet is OK err = getError(radio); # --- Update counter nS += p; # --- Interruption if nS > nbBuffer break end end # --- Last timeStamp and rate timeFinal = Timestamp(getTimestamp(radio)...); # --- Getting effective rate radioRate = radio.samplingRate; effectiveRate = getRate(timeInit,timeFinal,nS); # --- Free all and return close(radio); return (radioRate,effectiveRate); end end
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
docs
3583
# Example of MIMO use (with UHD) Multiple antenna support is handled with the USRP (at least) based on the API proposed by UHD. Some extra parameters (channels, board and antennas) have to be set up according to the targeted board. The following example works for the USRP e310 and configure the radio to have its two receive antenna. The spectrum of the two channel is then depicted. For other radio support, MIMO configuration should be modified to be compliant with the driver preriquisites. # ---------------------------------------------------- # --- Package dependencies # ---------------------------------------------------- using AbstractSDRs using Plots using FFTW # ---------------------------------------------------- # --- Radio parameters # ---------------------------------------------------- radioType = :uhd # We target UHDBindings here carrierFreq = 2410e6 # Carrier frequency (ISM band) samplingRate = 2e6 # Not high but issue with e310 stream :( gain = 50 # In dB # ---------------------------------------------------- # --- MIMO and board specificities # ---------------------------------------------------- # We need to specify the channels and the board as we use a USRP => Note that the way the parameters are set is based on how it is done at UHD level. You can have a look at the mimo example provided by UHD. # This may vary depending on the chosen hardware # /!\ We need to specify how many antenna we want. Be sure that the configuration is handled by the hardware you have otherwise UHD will raise an error (and maybe segfault ?) nbAntennaRx = 2 nbAntennaTx = 0 # Antenna and board config channels = [0;1] # First channel is the first path subdev = "A:0 A:1" # e310 board names # For the antenna, we need to specify the dictionnary of the allocated antenna for both Tx and Rx. In our case we will only do full Rx mode so we only specify the :Rx key antennas = Dict(:Rx => ["TX/RX";"RX2"]) # ---------------------------------------------------- # --- Open radio # ---------------------------------------------------- radio = openSDR( radioType, carrierFreq, samplingRate, gain ; nbAntennaTx, nbAntennaRx, channels, antennas, subdev) # --- Receive a buffer # We specify the size of each buffer # We will have one buffer per channel so a Vector of Vector # sigVect[1] and sigVect[2] will have the same size (of nbSamples) each for a channel nbSamples = 4096 sigVect = recv(radio,nbSamples) # ---------------------------------------------------- # --- Plot the spectrum # ---------------------------------------------------- # Get the rate from the radio using the accessor s = getSamplingRate(radio) # X axis xAx = ((0:nbSamples-1)./nbSamples .- 0.5) * s # PSD y = 10*log10.(abs2.(fftshift(fft(sigVect[1])))) plt = plot(xAx,y,label="First Channel") y = 10*log10.(abs2.(fftshift(fft(sigVect[2])))) plot!(plt,xAx,y,label="Second Channel") xlabel!("Frequency [Hz]") ylabel!("Magnitude [dB]") display(plt) # ---------------------------------------------------- # --- Close radio # ---------------------------------------------------- close(radio)
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
docs
1522
# Update parameters of the radio It is possible to update the radio parameter such as the gain, the bandwidth and the sampling rate. In this function, we change the carrier frequency to 2400MHz, the bandwidth from 16MHz to 100MHz and the Rx gain from 10 to 30dB. In some cases, the desired parameters cannot be obtained. In such a case, we let UHD decide what is the most appropriate value. A warning is raised and the output of the functions used to change the the radio parameters corresponds to the effective values of the radio. function main() # ---------------------------------------------------- # --- Physical layer and RF parameters # ---------------------------------------------------- carrierFreq = 868e6; # --- The carrier frequency (Hz) samplingRate = 16e6; # --- Targeted bandwidth (Hz) rxGain = 30.0; # --- Rx gain (dB) nbSamples = 4096; # --- Desired number of samples # ---------------------------------------------------- # --- Getting all system with function calls # ---------------------------------------------------- # --- Creating the radio resource radio = openSDR(:uhd,carrierFreq,samplingRate,rxGain); # --- Display the current radio configuration print(radio); # --- We what to change the parameters ! updateSamplingFreq!(radio,100e6); updateCarrierFreq!(radio,2400e6); updateGain!(radio,30) # --- Print the new radio configuration print(radio); # --- Release the radio resources close(radio); end
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
0.5.1
c3fab6b9318b55731149db35fbe897bb7872f486
docs
1077
# Set up a Radio Link and get some samples We use a UHD based device. In order to get 4096 samples at 868MHz with a instantaneous bandwidth of 16MHz, with a 30dB Rx Gain, the following Julia code should do the trick. function main() # ---------------------------------------------------- # --- Physical layer and RF parameters # ---------------------------------------------------- carrierFreq = 868e6; # --- The carrier frequency (Hz) samplingRate = 16e6; # --- Targeted bandwidth (Hz) rxGain = 30.0; # --- Rx gain (dB) nbSamples = 4096; # --- Desired number of samples # ---------------------------------------------------- # --- Getting all system with function calls # ---------------------------------------------------- # --- Creating the radio resource radio = openSDR(:uhd,carrierFreq,samplingRate,rxGain); # --- Display the current radio configuration print(radio); # --- Getting a buffer from the radio sigAll = recv(radio,nbSamples); # --- Release the radio resources close(radio); end
AbstractSDRs
https://github.com/JuliaTelecom/AbstractSDRs.jl.git
[ "MIT" ]
1.2.0
a22900f141fae3e8c6f2ab9e4d48dfca274fafb8
code
3690
using BinaryProvider # requires BinaryProvider 0.3.0 or later # Parse some basic command-line arguments const verbose = "--verbose" in ARGS const prefix = Prefix(get([a for a in ARGS if a != "--verbose"], 1, joinpath(@__DIR__, "usr"))) products = [ LibraryProduct(prefix, ["pa_ringbuffer"], :pa_ringbuffer), # FileProduct(prefix, "include/pa_ringbuffer.h", :pa_ringbuffer_h), ] # Download binaries from hosted location bin_prefix = "https://s3.us-east-2.amazonaws.com/ringbuffersbuilder" # Listing of files generated by BinaryBuilder: download_info = Dict( Linux(:aarch64, :glibc) => ("$bin_prefix/pa_ringbuffer.v19.6.0.aarch64-linux-gnu.tar.gz", "8724038e5c3bec6159e5f5816d9b2e4aea14f1006c019dcba3d2fe1f345b7639"), Linux(:aarch64, :musl) => ("$bin_prefix/pa_ringbuffer.v19.6.0.aarch64-linux-musl.tar.gz", "61818246bac6925543906319648eb50d8c2deac1380cb892f4ee0ecbd6fc8389"), Linux(:armv7l, :glibc, :eabihf) => ("$bin_prefix/pa_ringbuffer.v19.6.0.arm-linux-gnueabihf.tar.gz", "c24a9abc0a07e48d9cc2ebd332479e2affac505e295593d37585339680ad0a37"), Linux(:armv7l, :musl, :eabihf) => ("$bin_prefix/pa_ringbuffer.v19.6.0.arm-linux-musleabihf.tar.gz", "8301c7b87e75bd049a41d72c3ee1f902912fd73315fcc73bbb3705598aa32407"), Linux(:i686, :glibc) => ("$bin_prefix/pa_ringbuffer.v19.6.0.i686-linux-gnu.tar.gz", "f00ab4e1727ba60e4305363241ce834e32898448f1eec8c6664f3a4a729886f6"), Linux(:i686, :musl) => ("$bin_prefix/pa_ringbuffer.v19.6.0.i686-linux-musl.tar.gz", "a7c5bcac2f24448ced2b2b6ef350fc8b8124be3e834b410733a6f0b67a2f0df3"), Windows(:i686) => ("$bin_prefix/pa_ringbuffer.v19.6.0.i686-w64-mingw32.tar.gz", "134a1c5e27ed634183527aefab5e62715ebaf23b462ef006fc72d4e9eaac2b7b"), Linux(:powerpc64le, :glibc) => ("$bin_prefix/pa_ringbuffer.v19.6.0.powerpc64le-linux-gnu.tar.gz", "fb69d38b4221c6163072b86b7a11efd78d91c5279d89e005bc166bc74d805af7"), MacOS(:x86_64) => ("$bin_prefix/pa_ringbuffer.v19.6.0.x86_64-apple-darwin14.tar.gz", "d0441ce81f7dedd42e8fef353d946e3e45da8d3b4537d76ad0086d263e14da26"), Linux(:x86_64, :glibc) => ("$bin_prefix/pa_ringbuffer.v19.6.0.x86_64-linux-gnu.tar.gz", "7a7dfae0106f31e62f5f4a3de1860c84dfafb6395dd6a507027d9a0c405c42bb"), Linux(:x86_64, :musl) => ("$bin_prefix/pa_ringbuffer.v19.6.0.x86_64-linux-musl.tar.gz", "e6de813624b9023a638bce804de5df012093f90e2fecf7b9aad91cecc1a4dc7e"), FreeBSD(:x86_64) => ("$bin_prefix/pa_ringbuffer.v19.6.0.x86_64-unknown-freebsd11.1.tar.gz", "a5abb7de8881c59aadc6c3ff028ed360cdb6ad457f432808af4a4934aa11b44e"), Windows(:x86_64) => ("$bin_prefix/pa_ringbuffer.v19.6.0.x86_64-w64-mingw32.tar.gz", "2908d3cca37e8af3d307b290f8c0ccafd0c835f61a0f11707af9d90ccc055079"), ) # Install unsatisfied or updated dependencies: unsatisfied = any(!satisfied(p; verbose=verbose) for p in products) if haskey(download_info, platform_key()) url, tarball_hash = download_info[platform_key()] if unsatisfied || !isinstalled(url, tarball_hash; prefix=prefix) # Download and install binaries install(url, tarball_hash; prefix=prefix, force=true, verbose=verbose) end elseif unsatisfied # If we don't have a BinaryProvider-compatible .tar.gz to download, complain. # Alternatively, you could attempt to install from a separate provider, # build from source or something even more ambitious here. error(string("$(triplet(platform_key())) is not a supported platform. ", "Please see https://github.com/JuliaAudio/RingBuffersBuilder if ", "you'd like to build your own")) end # Write out a deps.jl file that will contain mappings for our products write_deps_file(joinpath(@__DIR__, "deps.jl"), products, verbose=verbose)
RingBuffers
https://github.com/JuliaAudio/RingBuffers.jl.git
[ "MIT" ]
1.2.0
a22900f141fae3e8c6f2ab9e4d48dfca274fafb8
code
13325
__precompile__(true) module RingBuffers export RingBuffer, notifyhandle, framesreadable, frameswritable export writeavailable, writeavailable!, readavailable! # these don't exist in Base export PaUtilRingBuffer import Base: read, read!, readavailable, write, flush import Base: wait, notify import Base: unsafe_convert, pointer import Base: isopen, close using Base: AsyncCondition import Compat import Compat: Libdl, Cvoid, undef, popfirst!, @compat depsjl = joinpath(@__DIR__, "..", "deps", "deps.jl") isfile(depsjl) ? include(depsjl) : error("RingBuffers not properly installed. Please run Pkg.build(\"RingBuffers\")") include("pa_ringbuffer.jl") function __init__() # we use this rather than the built-in BinaryProvider `check_deps` function # so we can customize the dlopen flags. We need to use `RTLD_GLOBAL` so # that the library functions are available to other C shim libraries that # other packages might need to add to handle their audio callbacks. if !isfile(pa_ringbuffer) error("$(pa_ringbuffer) does not exist, Please re-run Pkg.build(\"RingBuffers\"), and restart Julia.") end if Libdl.dlopen_e(pa_ringbuffer, Libdl.RTLD_LAZY | Libdl.RTLD_DEEPBIND | Libdl.RTLD_GLOBAL) == C_NULL error("$(pa_ringbuffer) cannot be opened, Please re-run Pkg.build(\"RingBuffers\"), and restart Julia.") end end """ RingBuffer{T}(nchannels, nframes) A lock-free ringbuffer wrapping PortAudio's implementation. The underlying representation stores multi-channel data as interleaved. The buffer will hold `nframes` frames. This ring buffer can be used to pass data between tasks similar to the built-in `Channel` type, but it has the additional ability to pass data to and from C code running on a different thread. The C code can use the API defined in `pa_ringbuffer.h`. Note that this is only safe with a single-threaded reader and single-threaded writer. """ struct RingBuffer{T} pabuf::PaUtilRingBuffer nchannels::Int readers::Vector{Condition} writers::Vector{Condition} datanotify::AsyncCondition function RingBuffer{T}(nchannels, frames) where {T} frames = nextpow(2, frames) buf = PaUtilRingBuffer(sizeof(T) * nchannels, frames) new(buf, nchannels, Condition[], Condition[], AsyncCondition()) end end ############### # Writing ############### """ write(rbuf::RingBuffer{T}, data::AbstractArray{T}[, nframes]) Write `nframes` frames to `rbuf` from `data`. Assumes the data is interleaved. If the buffer is full the call will block until space is available or the ring buffer is closed. If `data` is a `Vector`, it's treated as a block of memory from which to read the interleaved data. If it's a `Matrix`, it is treated as nchannels × nframes. Returns the number of frames written, which should be equal to the requested number unless the buffer was closed prematurely. """ function write(rbuf::RingBuffer{T}, data::AbstractArray{T}, nframes) where {T} if length(data) < nframes * rbuf.nchannels dframes = (div(length(data), rbuf.nchannels)) throw(ErrorException("data array is too short ($dframes frames) for requested write ($nframes frames)")) end isopen(rbuf) || return 0 cond = Condition() nwritten = 0 try push!(rbuf.writers, cond) if length(rbuf.writers) > 1 # we're behind someone in the queue wait(cond) isopen(rbuf) || return 0 end # now we're in the front of the queue n = PaUtil_WriteRingBuffer(rbuf.pabuf, pointer(data), nframes) nwritten += n # notify any waiting readers that there's data available notify_data(rbuf) while nwritten < nframes wait(rbuf.datanotify) isopen(rbuf) || return nwritten n = PaUtil_WriteRingBuffer(rbuf.pabuf, pointer(data)+(nwritten*rbuf.nchannels*sizeof(T)), nframes-nwritten) nwritten += n # notify any waiting readers that there's data available notify_data(rbuf) end finally # we're done, remove our condition and notify the next writer if necessary popfirst!(rbuf.writers) if length(rbuf.writers) > 0 notify(rbuf.writers[1]) end end nwritten end function write(rbuf::RingBuffer{T}, data::AbstractMatrix{T}) where {T} if size(data, 1) != rbuf.nchannels throw(ErrorException( "Tried to write a $(size(data, 1))-channel array to a $(rbuf.nchannels)-channel ring buffer")) end write(rbuf, data, size(data, 2)) end function write(rbuf::RingBuffer{T}, data::AbstractVector{T}) where {T} write(rbuf, data, div(length(data), rbuf.nchannels)) end """ frameswritable(rbuf::RingBuffer) Returns the number of frames that can be written to the ring buffer without blocking. """ function frameswritable(rbuf::RingBuffer) PaUtil_GetRingBufferWriteAvailable(rbuf.pabuf) end """ writeavailable(rbuf::RingBuffer{T}, data::AbstractArray{T}[, nframes]) Write up to `nframes` frames to `rbuf` from `data` without blocking. If `data` is a `Vector`, it's treated as a block of memory from which to read the interleaved data. If it's a `Matrix`, it is treated as nchannels × nframes. Returns the number of frames written. """ function writeavailable(rbuf::RingBuffer{T}, data::AbstractVector{T}, nframes=div(length(data), rbuf.nchannels)) where {T} write(rbuf, data, min(nframes, frameswritable(rbuf))) end function writeavailable(rbuf::RingBuffer{T}, data::AbstractMatrix{T}, nframes=size(data, 2)) where {T} write(rbuf, data, min(nframes, frameswritable(rbuf))) end # basically add ourselves to the queue as if we're a writer, but wait until the # ringbuf is emptied function flush(rbuf::RingBuffer) isopen(rbuf) || return cond = Condition() try push!(rbuf.writers, cond) if length(rbuf.writers) > 1 # we're behind someone in the queue wait(cond) isopen(rbuf) || return end # now we're in the front of the queue while frameswritable(rbuf) < rbuf.pabuf.bufferSize wait(rbuf.datanotify) isopen(rbuf) || return end finally # we're done, remove our condition and notify the next writer if necessary popfirst!(rbuf.writers) if length(rbuf.writers) > 0 notify(rbuf.writers[1]) end end end ############### # Reading ############### """ read!(rbuf::RingBuffer, data::AbstractArray[, nframes]) Read `nframes` frames from `rbuf` into `data`. Data will be interleaved. If the buffer is empty the call will block until data is available or the ring buffer is closed. If `data` is a `Vector`, it's treated as a block of memory in which to write the interleaved data. If it's a `Matrix`, it is treated as nchannels × nframes. Returns the number of frames read, which should be equal to the requested number unless the buffer was closed prematurely. """ function read!(rbuf::RingBuffer{T}, data::AbstractArray{T}, nframes) where {T} if length(data) < nframes * rbuf.nchannels dframes = (div(length(data), rbuf.nchannels)) throw(ErrorException("data array is too short ($dframes frames) for requested read ($nframes frames)")) end isopen(rbuf) || return 0 cond = Condition() nread = 0 try push!(rbuf.readers, cond) if length(rbuf.readers) > 1 # we're behind someone in the queue wait(cond) end # now we're in the front of the queue isopen(rbuf) || return 0 n = PaUtil_ReadRingBuffer(rbuf.pabuf, pointer(data), nframes) nread += n # notify any waiting writers that there's space available notify_data(rbuf) while nread < nframes wait(rbuf.datanotify) isopen(rbuf) || return nread n = PaUtil_ReadRingBuffer(rbuf.pabuf, pointer(data)+(nread*rbuf.nchannels*sizeof(T)), nframes-nread) nread += n # notify any waiting writers that there's space available notify_data(rbuf) end finally # we're done, remove our condition and notify the next reader if necessary popfirst!(rbuf.readers) if length(rbuf.readers) > 0 notify(rbuf.readers[1]) end end nread end function read!(rbuf::RingBuffer{T}, data::AbstractMatrix{T}) where {T} if size(data, 1) != rbuf.nchannels throw(ErrorException( "Tried to read a $(rbuf.nchannels)-channel ring buffer into a $(size(data, 1))-channel array")) end read!(rbuf, data, size(data, 2)) end function read!(rbuf::RingBuffer{T}, data::AbstractVector{T}) where {T} read!(rbuf, data, div(length(data), rbuf.nchannels)) end """ read(rbuf::RingBuffer, nframes) Read `nframes` frames from `rbuf` and return an (nchannels × nframes) `Array` holding the interleaved data. If the buffer is empty the call will block until data is available or the ring buffer is closed. """ function read(rbuf::RingBuffer{T}, nframes) where {T} data = Array{T}(undef, rbuf.nchannels, nframes) nread = read!(rbuf, data, nframes) if nread < nframes data[:, 1:nread] else data end end """ read(rbuf::RingBuffer; blocksize=4096) Read `blocksize` frames at a time from `rbuf` until the ringbuffer is closed, and return an (nchannels × nframes) `Array` holding the data. When no data is available the call will block until it can read more or the ring buffer is closed. """ function read(rbuf::RingBuffer{T}; blocksize=4096) where {T} readbuf = Array{T}(undef, rbuf.nchannels, blocksize) # during accumulation we keep the channels separate so we can grow the # arrays without needing to copy data around as much cumbufs = [Vector{T}() for _ in 1:rbuf.nchannels] while true n = read!(rbuf, readbuf) for ch in 1:length(cumbufs) append!(cumbufs[ch], @view readbuf[ch, 1:n]) end n == blocksize || break end vcat((x' for x in cumbufs)...) end """ frameswritable(rbuf::RingBuffer) Returns the number of frames that can be written to the ring buffer without blocking. """ function framesreadable(rbuf::RingBuffer) PaUtil_GetRingBufferReadAvailable(rbuf.pabuf) end """ readavailable!(rbuf::RingBuffer{T}, data::AbstractArray{T}[, nframes]) Read up to `nframes` frames from `rbuf` into `data` without blocking. If `data` is a `Vector`, it's treated as a block of memory to write the interleaved data to. If it's a `Matrix`, it is treated as nchannels × nframes. Returns the number of frames read. """ function readavailable!(rbuf::RingBuffer{T}, data::AbstractVector{T}, nframes=div(length(data), rbuf.nchannels)) where {T} read!(rbuf, data, min(nframes, framesreadable(rbuf))) end function readavailable!(rbuf::RingBuffer{T}, data::AbstractMatrix{T}, nframes=size(data, 2)) where {T} read!(rbuf, data, min(nframes, framesreadable(rbuf))) end """ readavailable(rbuf::RingBuffer[, nframes]) Read up to `nframes` frames from `rbuf` into `data` without blocking. If `data` is a `Vector`, it's treated as a block of memory to write the interleaved data to. If it's a `Matrix`, it is treated as nchannels × nframes. Returns an (nchannels × nframes) `Array`. """ function readavailable(rbuf::RingBuffer, nframes) read(rbuf, min(nframes, framesreadable(rbuf))) end function readavailable(rbuf::RingBuffer) read(rbuf, framesreadable(rbuf)) end ###################### # Resource Management ###################### function close(rbuf::RingBuffer) close(rbuf.pabuf) # wake up any waiting readers or writers notify_data(rbuf) end isopen(rbuf::RingBuffer) = isopen(rbuf.pabuf) # """ # notify_data(rbuf::RingBuffer) # # Notify the ringbuffer that new data might be available, which will wake up # any waiting readers or writers. This is safe to call from a separate thread # context. # """ function notify_data end if VERSION >= v"1.2" notify_data(rbuf::RingBuffer) = ccall(:uv_async_send, Cint, (Ptr{Cvoid},), rbuf.datanotify.handle) else notify_data(rbuf::RingBuffer) = notify(rbuf.datanotify.cond) end """ notifyhandle(rbuf::RingBuffer) Return the AsyncCondition handle that can be used to wake up the buffer from another thread. """ notifyhandle(rbuf::RingBuffer) = rbuf.datanotify.handle """ pointer(rbuf::RingBuffer) Return the pointer to the underlying PaUtilRingBuffer that can be passed to C code and manipulated with the pa_ringbuffer.h API. Note that this does not maintain any GC references, so it is imperative that there is an active reference to this RingBuffer for as long as this pointer might be accessed. """ pointer(rbuf::RingBuffer) = pointer_from_objref(rbuf.pabuf) end # module
RingBuffers
https://github.com/JuliaAudio/RingBuffers.jl.git
[ "MIT" ]
1.2.0
a22900f141fae3e8c6f2ab9e4d48dfca274fafb8
code
4885
@static if Compat.Sys.isapple() const RingBufferSize = Int32 else const RingBufferSize = Clong end """ PaUtilRingBuffer(elementSizeBytes, elementCount) Mirrors the C-side PaUtilRingBuffer struct that describes the ringbuffer state. """ mutable struct PaUtilRingBuffer bufferSize::RingBufferSize # Number of elements in FIFO. Power of 2. Set by PaUtil_InitializeRingBuffer. writeIndex::RingBufferSize # Index of next writable element. Set by PaUtil_AdvanceRingBufferWriteIndex. readIndex::RingBufferSize # Index of next readable element. Set by PaUtil_AdvanceRingBufferReadIndex. bigMask::RingBufferSize # Used for wrapping indices with extra bit to distinguish full/empty. smallMask::RingBufferSize # Used for fitting indices to buffer. elementSizeBytes::RingBufferSize # Number of bytes per element. buffer::Ptr{Cchar} # Pointer to the buffer containing the actual data. # allow it to be created uninitialized because we need to pass it to PaUtil_InitializeRingBuffer function PaUtilRingBuffer(elementSizeBytes, elementCount) data = Base.Libc.malloc(elementSizeBytes * elementCount) rbuf = new() PaUtil_InitializeRingBuffer(rbuf, elementSizeBytes, elementCount, data) # it's the responsibility of the parent to close the ringbuffer. Closing # in a finalizer is dangerous because the callback thread might have a # direct pointer to this ringbuffer, and we want to make sure the parent # is able to properly shut down the callback thread before this is # closed rbuf end end function close(rbuf::PaUtilRingBuffer) if rbuf.buffer != C_NULL Base.Libc.free(rbuf.buffer) rbuf.buffer = C_NULL end end isopen(rbuf::PaUtilRingBuffer) = rbuf.buffer != C_NULL """ PaUtil_InitializeRingBuffer(rbuf, elementSizeBytes, elementCount, dataPtr) Initialize Ring Buffer to empty state ready to have elements written to it. # Arguments * `rbuf::PaUtilRingBuffer`: The ring buffer. * `elementSizeBytes::RingBufferSize`: The size of a single data element in bytes. * `elementCount::RingBufferSize`: The number of elements in the buffer (must be a power of 2). * `dataPtr::Ptr{Cvoid}`: A pointer to a previously allocated area where the data will be maintained. It must be elementCount*elementSizeBytes long. """ function PaUtil_InitializeRingBuffer(rbuf, elementSizeBytes, elementCount, dataPtr) if !ispow2(elementCount) throw(ErrorException("elementCount($elementCount) must be a power of 2")) end status = ccall((:PaUtil_InitializeRingBuffer, pa_ringbuffer), RingBufferSize, (Ref{PaUtilRingBuffer}, RingBufferSize, RingBufferSize, Ptr{Cvoid}), rbuf, elementSizeBytes, elementCount, dataPtr) if status != 0 throw(ErrorException("PaUtil_InitializeRingBuffer returned status $status")) end nothing end """ PaUtil_FlushRingBuffer(rbuf::PaUtilRingBuffer) Reset buffer to empty. Should only be called when buffer is NOT being read or written. """ function PaUtil_FlushRingBuffer(rbuf) ccall((:PaUtil_FlushRingBuffer, pa_ringbuffer), Cvoid, (Ref{PaUtilRingBuffer}, ), rbuf) end """ PaUtil_GetRingBufferWriteAvailable(rbuf::PaUtilRingBuffer) Retrieve the number of elements available in the ring buffer for writing. """ function PaUtil_GetRingBufferWriteAvailable(rbuf) ccall((:PaUtil_GetRingBufferWriteAvailable, pa_ringbuffer), RingBufferSize, (Ref{PaUtilRingBuffer}, ), rbuf) end """ PaUtil_GetRingBufferReadAvailable(rbuf::PaUtilRingBuffer) Retrieve the number of elements available in the ring buffer for reading. """ function PaUtil_GetRingBufferReadAvailable(rbuf) ccall((:PaUtil_GetRingBufferReadAvailable, pa_ringbuffer), RingBufferSize, (Ref{PaUtilRingBuffer}, ), rbuf) end """ PaUtil_WriteRingBuffer(rbuf::PaUtilRingBuffer, data::Ptr{Cvoid}, elementCount::RingBufferSize) Write data to the ring buffer and return the number of elements written. """ function PaUtil_WriteRingBuffer(rbuf, data, elementCount) ccall((:PaUtil_WriteRingBuffer, pa_ringbuffer), RingBufferSize, (Ref{PaUtilRingBuffer}, Ptr{Cvoid}, RingBufferSize), rbuf, data, elementCount) end """ PaUtil_ReadRingBuffer(rbuf::PaUtilRingBuffer, data::Ptr{Cvoid}, elementCount::RingBufferSize) Read data from the ring buffer and return the number of elements read. """ function PaUtil_ReadRingBuffer(rbuf, data, elementCount) ccall((:PaUtil_ReadRingBuffer, pa_ringbuffer), RingBufferSize, (Ref{PaUtilRingBuffer}, Ptr{Cvoid}, RingBufferSize), rbuf, data, elementCount) end
RingBuffers
https://github.com/JuliaAudio/RingBuffers.jl.git
[ "MIT" ]
1.2.0
a22900f141fae3e8c6f2ab9e4d48dfca274fafb8
code
2469
@testset "Low-Level tests of the PortAudio ringbuf library" begin @testset "Can create PA ring buffer" begin buf = RingBuffers.PaUtilRingBuffer(8, 16) @test RingBuffers.PaUtil_GetRingBufferWriteAvailable(buf) == 16 @test RingBuffers.PaUtil_GetRingBufferReadAvailable(buf) == 0 end @testset "Throws on non power of two element count" begin @test_throws ErrorException RingBuffers.PaUtilRingBuffer(8, 15) end @testset "Can read/write to PA ring buffer" begin buf = RingBuffers.PaUtilRingBuffer(sizeof(Int), 16) writedata = collect(1:5) readdata = collect(6:10) @test RingBuffers.PaUtil_WriteRingBuffer(buf, writedata, 5) == 5 @test RingBuffers.PaUtil_GetRingBufferWriteAvailable(buf) == 11 @test RingBuffers.PaUtil_GetRingBufferReadAvailable(buf) == 5 @test RingBuffers.PaUtil_ReadRingBuffer(buf, readdata, 5) == 5 @test RingBuffers.PaUtil_GetRingBufferWriteAvailable(buf) == 16 @test RingBuffers.PaUtil_GetRingBufferReadAvailable(buf) == 0 @test readdata == writedata end @testset "Can flush PA ring buffer" begin buf = RingBuffers.PaUtilRingBuffer(sizeof(Int), 16) writedata = collect(1:5) readdata = collect(6:10) @test RingBuffers.PaUtil_WriteRingBuffer(buf, writedata, 5) == 5 @test RingBuffers.PaUtil_GetRingBufferWriteAvailable(buf) == 11 @test RingBuffers.PaUtil_GetRingBufferReadAvailable(buf) == 5 RingBuffers.PaUtil_FlushRingBuffer(buf) @test RingBuffers.PaUtil_GetRingBufferWriteAvailable(buf) == 16 @test RingBuffers.PaUtil_GetRingBufferReadAvailable(buf) == 0 end @testset "PA ring buffer handles overflow/underflow" begin buf = RingBuffers.PaUtilRingBuffer(sizeof(Int), 8) writedata = collect(1:5) readdata = collect(6:10) @test RingBuffers.PaUtil_WriteRingBuffer(buf, writedata, 5) == 5 @test RingBuffers.PaUtil_WriteRingBuffer(buf, writedata, 5) == 3 @test RingBuffers.PaUtil_GetRingBufferWriteAvailable(buf) == 0 @test RingBuffers.PaUtil_GetRingBufferReadAvailable(buf) == 8 @test RingBuffers.PaUtil_ReadRingBuffer(buf, readdata, 5) == 5 @test RingBuffers.PaUtil_ReadRingBuffer(buf, readdata, 5) == 3 @test RingBuffers.PaUtil_GetRingBufferWriteAvailable(buf) == 8 @test RingBuffers.PaUtil_GetRingBufferReadAvailable(buf) == 0 end end
RingBuffers
https://github.com/JuliaAudio/RingBuffers.jl.git
[ "MIT" ]
1.2.0
a22900f141fae3e8c6f2ab9e4d48dfca274fafb8
code
6482
using RingBuffers import Compat: undef, fetch using Compat.Test @testset "RingBuffer Tests" begin include("pa_ringbuffer.jl") @testset "Can check frames readable and writable" begin rb = RingBuffer{Float64}(2, 8) @test framesreadable(rb) == 0 @test frameswritable(rb) == 8 write(rb, rand(2, 5)) @test framesreadable(rb) == 5 @test frameswritable(rb) == 3 read(rb, 3) @test framesreadable(rb) == 2 @test frameswritable(rb) == 6 write(rb, rand(2, 6)) @test framesreadable(rb) == 8 @test frameswritable(rb) == 0 end @testset "Can read/write 2D arrays" begin writedata = collect(reshape(1:10, 2, 5)) readdata = collect(reshape(11:20, 2, 5)) rb = RingBuffer{Int}(2, 8) write(rb, writedata) read!(rb, readdata) @test readdata == writedata end @testset "Can read/write 1D arrays" begin writedata = collect(1:10) readdata = collect(11:20) rb = RingBuffer{Int}(2, 8) write(rb, writedata) read!(rb, readdata) @test readdata == writedata end @testset "throws error writing 2D array of wrong channel count" begin writedata = collect(reshape(1:15, 3, 5)) rb = RingBuffer{Int}(2, 8) @test_throws ErrorException write(rb, writedata) end @testset "throws error reading 2D array of wrong channel count" begin writedata = collect(reshape(1:10, 2, 5)) readdata = collect(reshape(11:25, 3, 5)) rb = RingBuffer{Int}(2, 8) write(rb, writedata) @test_throws ErrorException read!(rb, readdata) end @testset "throws error writing too-short array" begin writedata = collect(reshape(1:15, 3, 5)) rb = RingBuffer{Int}(2, 8) @test_throws ErrorException write(rb, writedata, 8) end @testset "throws error reading into too-short array" begin readdata = collect(reshape(1:15, 3, 5)) rb = RingBuffer{Int}(2, 8) @test_throws ErrorException read!(rb, readdata, 8) end @testset "multiple sequential writes work" begin writedata = collect(reshape(1:8, 2, 4)) rb = RingBuffer{Int}(2, 10) write(rb, writedata) write(rb, writedata) readdata = read(rb, 8) @test readdata == hcat(writedata, writedata) end @testset "multiple queued writes work" begin writedata = collect(reshape(1:14, 2, 7)) rb = RingBuffer{Int}(2, 4) writer1 = @async begin write(rb, writedata) end writer2 = @async begin write(rb, writedata) end readdata = read(rb, 14) @test readdata == hcat(writedata, writedata) end @testset "multiple sequential reads work" begin writedata = collect(reshape(1:16, 2, 8)) rb = RingBuffer{Int}(2, 10) write(rb, writedata) readdata1 = read(rb, 4) readdata2 = read(rb, 4) @test hcat(readdata1, readdata2) == writedata end @testset "overflow blocks writer" begin writedata = collect(reshape(1:10, 2, 5)) rb = RingBuffer{Int}(2, 8) write(rb, writedata) t = @async write(rb, writedata) sleep(0.1) @test t.state == :runnable readdata = read(rb, 8) @test fetch(t) == 5 @test t.state == :done @test readdata == hcat(writedata, writedata[:, 1:3]) end @testset "underflow blocks reader" begin writedata = collect(reshape(1:6, 2, 3)) rb = RingBuffer{Int}(2, 8) write(rb, writedata) t = @async read(rb, 6) sleep(0.1) @test t.state == :runnable write(rb, writedata) @test fetch(t) == hcat(writedata, writedata) @test t.state == :done end @testset "closing ringbuf cancels in-progress writes" begin writedata = collect(reshape(1:20, 2, 10)) rb = RingBuffer{Int}(2, 8) t1 = @async write(rb, writedata) t2 = @async write(rb, writedata) sleep(0.1) close(rb) @test fetch(t1) == 8 @test fetch(t2) == 0 end @testset "closing ringbuf cancels in-progress reads" begin writedata = collect(reshape(1:6, 2, 3)) rb = RingBuffer{Int}(2, 8) write(rb, writedata) t1 = @async read(rb, 5) t2 = @async read(rb, 5) sleep(0.1) close(rb) @test fetch(t1) == writedata[:, 1:3] @test fetch(t2) == Array{Int}(undef, 2, 0) end @testset "writeavailable works with Matrices" begin writedata = collect(reshape(1:20, 2, 10)) rb = RingBuffer{Int}(2, 8) @test writeavailable(rb, writedata) == 8 @test readavailable(rb) == writedata[:, 1:8] end @testset "writeavailable works with Vectors" begin writedata = collect(1:20) rb = RingBuffer{Int}(2, 8) @test writeavailable(rb, writedata) == 8 @test vec(readavailable(rb)) == writedata[1:16] end @testset "read reads until the buffer is closed" begin writedata = collect(reshape(1:8, 2, 4)) rb = RingBuffer{Int}(2, 8) write(rb, writedata) reader = @async read(rb; blocksize=6) for _ in 1:3 write(rb, writedata) end flush(rb) close(rb) if VERSION >= v"0.7.0-DEV.3977" # Julia PR 26039 @test fetch(reader) == repeat(writedata, 1, 4) else @test fetch(reader) == Compat.repmat(writedata, 1, 4) end end @testset "reading a closed ringbuf reads nothing" begin rb = RingBuffer{Int}(2,8) readbuf = zeros(Int, 4) write(rb, rand(Int, 2, 8)) close(rb) @test read(rb) == Array{Int}(undef, 2, 0) @test read!(rb, readbuf) == 0 end @testset "writing to a closed ringbuf writes nothing" begin rb = RingBuffer{Int}(2,8) close(rb) @test write(rb, rand(Int, 2, 8)) == 0 end @testset "flush works if we're queued behind a writer" begin writedata = collect(reshape(1:16, 2, 8)) rb = RingBuffer{Int}(2, 4) writer1 = @async write(rb, writedata) flusher = @async flush(rb) writer2 = @async write(rb, writedata) read(rb, 16) fetch(flusher) # as long as this gets through then we should be OK that the tasks # woke each other up @test true end end
RingBuffers
https://github.com/JuliaAudio/RingBuffers.jl.git
[ "MIT" ]
1.2.0
a22900f141fae3e8c6f2ab9e4d48dfca274fafb8
docs
1421
# RingBuffers [![Build Status](https://travis-ci.org/JuliaAudio/RingBuffers.jl.svg?branch=master)](https://travis-ci.org/JuliaAudio/RingBuffers.jl) [![Build status](https://ci.appveyor.com/api/projects/status/lpjc1mv9stbkdhih?svg=true)](https://ci.appveyor.com/project/ssfrr/ringbuffers-jl) [![codecov.io](https://codecov.io/github/JuliaAudio/RingBuffers.jl/coverage.svg?branch=master)](https://codecov.io/github/JuliaAudio/RingBuffers.jl?branch=master) This package provides the `RingBuffer` type, which is a circular, fixed-size multi-channel buffer. This package implements `read`, `read!`, and `write` methods on the `RingBuffer` type, and supports reading and writing NxM `AbstractArray` subtypes, where N is the channel count and M is the length in frames. It also supports reading and writing from `AbstractVector`s, in which case the memory is treated as a raw buffer with interleaved data. Under the hood this package uses the `pa_ringbuffer` C implementation from PortAudio, which is a lock-free single-reader single-writer ringbuffer. The benefit of building on this is that you can write C modules for other libraries that can communicate with Julia over this lock-free ringbuffer using the `portaudio.h` header file. See the [PortAudio](https://github.com/JuliaAudio/PortAudio.jl) library for an example of using this to pass data between Julia's main thread and an audio callback in a different thread.
RingBuffers
https://github.com/JuliaAudio/RingBuffers.jl.git
[ "MIT" ]
1.2.1
9cc5973b40a0f06030cbfc19dc1f79478488e546
code
4082
__precompile__() module SeisIO using Blosc, Dates, DSP, FFTW, LightXML, LinearAlgebra, Markdown, Mmap, Printf, Sockets using DelimitedFiles: readdlm using Glob: glob using HTTP: request, Messages.statustext using Statistics: mean Blosc.set_compressor("lz4") Blosc.set_num_threads(Sys.CPU_THREADS) path = Base.source_dir() # DO NOT CHANGE IMPORT ORDER include("imports.jl") include("constants.jl") # ========================================================= # CoreUtils: SeisIO needs these for core functions # DO NOT CHANGE ORDER OF INCLUSIONS include("CoreUtils/IO/FastIO.jl") using .FastIO include("CoreUtils/ls.jl") include("CoreUtils/time.jl") include("CoreUtils/namestrip.jl") include("CoreUtils/typ2code.jl") include("CoreUtils/poly.jl") include("CoreUtils/calculus.jl") include("CoreUtils/svn.jl") include("CoreUtils/IO/read_utils.jl") include("CoreUtils/IO/string_vec_and_misc.jl") # ========================================================= # Types and methods # DO NOT CHANGE ORDER OF INCLUSIONS # Back-end types include("Types/KWDefs.jl") # Prereqs for custom types include("Types/InstPosition.jl") include("Types/InstResp.jl") # IO buffer including location and instrument response buffers include("Types/SeisIOBuf.jl") # Abstract types include("Types/GphysData.jl") include("Types/GphysChannel.jl") # Custom types include("Types/SeisData.jl") include("Types/SeisChannel.jl") for i in ls(path*"/Types/Methods/") if endswith(i, ".jl") include(i) end end # ========================================================= # Logging for i in ls(path*"/Logging/*") if endswith(i, ".jl") include(i) end end # ========================================================= # Utilities that may require SeisIO types to work for i in ls(path*"/Utils/") if endswith(i, ".jl") include(i) end end include("Utils/Parsing/streams.jl") include("Utils/Parsing/strings.jl") include("Utils/Parsing/buffers.jl") # ========================================================= # Data processing operations for i in ls(path*"/Processing/*") if endswith(i, ".jl") include(i) end end # ========================================================= # Data formats for i in ls(path*"/Formats/") if endswith(i, ".jl") include(i) end end # ========================================================= # Web clients for i in ls(path*"/Web/") if endswith(i, ".jl") include(i) end end # ========================================================= # Submodules #= Dependencies .FastIO └---------------> Types/ ╭-----------┴-----------------------┐ .Quake | ╭-------┴---┬--------┬--------┐ ╭---┴---┐ .RandSeis .SeisHDF .UW .SUDS .ASCII .SEED └--------+--------┘ └---┬---┘ | | v | Wrappers/ <---------------┘ =# include("Submodules/FormatGuide.jl") using .Formats include("Submodules/ASCII.jl") using .ASCII include("Submodules/Nodal.jl") using .Nodal import .Nodal: convert include("Submodules/SEED.jl") using .SEED using .SEED: parserec!, read_seed_resp!, seed_cleanup! export mseed_support, read_dataless, read_seed_resp!, read_seed_resp, RESP_wont_read, seed_support # We need these types for the native file format include("Submodules/Quake.jl") using .Quake import .Quake: convert, fwrite_note_quake!, merge_ext! export read_qml, write_qml include("Submodules/RandSeis.jl") include("Submodules/SeisHDF.jl") using .SeisHDF: read_hdf5, read_hdf5!, scan_hdf5, write_hdf5 export read_hdf5, read_hdf5!, scan_hdf5, write_hdf5 include("Submodules/SUDS.jl") include("Submodules/UW.jl") # ========================================================= # Wrappers for i in ls(path*"/Wrappers/") if endswith(i, ".jl") include(i) end end formats["list"] = collect(keys(formats)) # Last steps include("Last/splat.jl") include("Last/native_file_io.jl") include("Last/read_legacy.jl") include("Last/set_file_ver.jl") # Module ends end
SeisIO
https://github.com/jpjones76/SeisIO.jl.git
[ "MIT" ]
1.2.1
9cc5973b40a0f06030cbfc19dc1f79478488e546
code
7172
export TimeSpec # Most constants are defined here, except: # # BUF src/Types/SeisIOBuf.jl # KW src/Types/KWDefs.jl # PhaseCat src/Types/Quake/PhaseCat.jl # flat_resp src/Types/InstResp.jl # RespStage src/Types/InstResp.jl # type_codes src/Types/Methods/0_type_codes.jl # # ...and submodule-specific constants, which are in the submodule declaration files (e.g. SEED.jl) # Type aliases const ChanSpec = Union{Integer, UnitRange, Array{Int64, 1}} const FloatArray = Union{AbstractArray{Float64, 1}, AbstractArray{Float32, 1}} @doc """ TimeSpec = Union{Real, DateTime, String} # Time Specification Most functions that allow time specification use two reserved keywords to track time: `s` (start/begin) time and `t` (termination/end) time. Exact behavior of each is given in the table below. * Real numbers are interpreted as seconds * DateTime values are as in the Dates package * Strings should use ISO 8601 *without* time zone (`YYYY-MM-DDThh:mm:ss.s`); UTC is assumed. Equivalent Unix `strftime` format codes are `%Y-%m-%dT%H:%M:%S` or `%FT%T`. ## **parsetimewin Behavior** In all cases, parsetimewin outputs a pair of strings, sorted so that the first string corresponds to the earlier start time. | typeof(s) | typeof(t) | Behavior | |:------ |:------ |:------------------------------------- | | DateTime | DateTime | sort | | DateTime | Real | add *t* seconds to *s*, then sort | | DateTime | String | convert *t* => DateTime, then sort | | DateTime | String | convert *t* => DateTime, then sort | | Real | DateTime | add *s* seconds to *t*, then sort | | Real | Real | treat *s*, *t* as seconds from current time; sort | | String | DateTime | convert *s* => DateTime, then sort | | String | Real | convert *s* => DateTime, then sort | Special behavior with (Real, Real): *s* and *t* are converted to seconds from the start of the current minute. Thus, for `s=0` (the default), the data request begins (or ends) at the start of the minute in which the request is submitted. See also: `Dates.DateTime` """ TimeSpec const TimeSpec = Union{Real, DateTime, String} const ChanOpts = Union{String, Array{String, 1}, Array{String, 2}} const bad_chars = Dict{String, Any}( "File" => (0x22, 0x24, 0x2a, 0x2f, 0x3a, 0x3c, 0x3e, 0x3f, 0x40, 0x5c, 0x5e, 0x7c, 0x7e, 0x7f), "HTML" => (0x22, 0x26, 0x27, 0x3b, 0x3c, 0x3e, 0xa9, 0x7f), "Julia" => (0x24, 0x5c, 0x7f), "Markdown" => (0x21, 0x23, 0x28, 0x29, 0x2a, 0x2b, 0x2d, 0x2e, 0x5b, 0x5c, 0x5d, 0x5f, 0x60, 0x7b, 0x7d), "SEED" => (0x2e, 0x7f), "Strict" => (0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x5b, 0x5c, 0x5d, 0x5e, 0x60, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f) ) const datafields = (:id, :name, :loc, :fs, :gain, :resp, :units, :src, :notes, :misc, :t, :x) const days_per_month = Int32[31,28,31,30,31,30,31,31,30,31,30,31] const default_fs = zero(Float64) const default_gain = one(Float64) const dtchars = (0x2d, 0x2e, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x54) const dtconst = 62135683200000000 const regex_chars = String[Sys.iswindows() ? "/" : "\\", "\$", "(", ")", "+", "?", "[", "\\0", "\\A", "\\B", "\\D", "\\E", "\\G", "\\N", "\\P", "\\Q", "\\S", "\\U", "\\U", "\\W", "\\X", "\\Z", "\\a", "\\b", "\\c", "\\d", "\\e", "\\f", "\\n", "\\n", "\\p", "\\r", "\\s", "\\t", "\\w", "\\x", "\\x", "\\z", "]", "^", "{", "|", "}"] const show_os = 8 const sac_float_k = String[ "delta", "depmin", "depmax", "scale", "odelta", "b", "e", "o", "a", "internal1", "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9", "f", "resp0", "resp1", "resp2", "resp3", "resp4", "resp5", "resp6", "resp7", "resp8", "resp9", "stla", "stlo", "stel", "stdp", "evla", "evlo", "evel", "evdp", "mag", "user0", "user1", "user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "dist", "az", "baz", "gcarc", "sb", "sdelta", "depmen", "cmpaz", "cmpinc", "xminimum", "xmaximum", "yminimum", "ymaximum", "adjtm", "unused2", "unused3", "unused4", "unused5", "unused6", "unused7" ] # was: "dist", "az", "baz", "gcarc", "internal2", # "internal3", "depmen", "cmpaz", "cmpinc", "xminimum", # "xmaximum", "yminimum", "ymaximum", "unused1", "unused2", # "unused3", "unused4", "unused5", "unused6", "unused7" ] const sac_int_k = String[ "nzyear", "nzjday", "nzhour", "nzmin", "nzsec", "nzmsec", "nvhdr", "norid", "nevid", "npts", "internal4", "nwfid", "nxsize", "nysize", "unused8", "iftype", "idep", "iztype", "unused9", "iinst", "istreg", "ievreg", "ievtyp", "iqual", "isynth", "imagtyp", "imagsrc", "unused10", "unused11", "unused12", "unused13", "unused14", "unused15", "unused16", "unused17", "leven", "lpspol", "lovrok", "lcalda", "unused18" ] const sac_string_k = String["kstnm", "kevnm", "khole", "ko", "ka", "kt0", "kt1", "kt2", "kt3", "kt4", "kt5", "kt6", "kt7", "kt8", "kt9", "kf", "kuser0", "kuser1", "kuser2", "kcmpnm", "knetwk", "kdatrd", "kinst" ] const sac_double_k = String[ "delta", "b", "e", "o", "a", "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9", "f", "evlo", "evla", "stlo", "stla", "sb", "sdelta"] const sac_nul_c = UInt8[0x2d, 0x31, 0x32, 0x33, 0x34, 0x35, 0x20, 0x20] const sac_nul_f = -12345.0f0 const sac_nul_d = -12345.0 const sac_nul_i = Int32(-12345) const sac_nul_start = 0x2d const sac_nul_Int8 = UInt8[0x31, 0x32, 0x33, 0x34, 0x35] const segy_ftypes = Array{DataType, 1}([UInt32, Int32, Int16, Any, Float32, Any, Any, Int8]) # Note: type 1 is IBM Float32 const segy_units = Dict{Int16, String}(0 => "unknown", 1 => "Pa", 2 => "V", 3 => "mV", 4 => "A", 5 => "m", 6 => "m/s", 7 => "m/s2", 8 => "N", 9 => "W") const seis_inst_codes = ('H', 'J', 'L', 'M', 'N', 'P', 'Z') const seisio_file_begin = UInt8[0x53, 0x45, 0x49, 0x53, 0x49, 0x4f] const sμ = 1000000.0 const vSeisIO = Float32(0.54) const unindexed_fields = (:c, :n) const webhdr = Dict("User-Agent" => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36") # lol const xml_endtime = 19880899199000000 const μs = 1.0e-6
SeisIO
https://github.com/jpjones76/SeisIO.jl.git