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.3.0
215ea07f170cd9732aa7d7745c672f69baf3dc02
code
2751
using Dierckx import TimeseriesTools: TimeSeries export getrunningspeed, smoothrunningspeed, getstimuli, stimulustrace export gettrials, getlicks, getrewards, geteyetracking, getrunningspeed, getbehavior, getpupilarea _getrunningspeed(S::AbstractSession) = S.pyObject.running_speed |> py2df geteyetracking(S::AbstractSession) = S.pyObject.eye_tracking |> py2df function getrunningspeed(S::AbstractSession) (df = _getrunningspeed(S); TimeSeries(df.timestamps, df.speed)) end # ? Units function getpupilarea(S::AbstractSession) (df = geteyetracking(S); TimeSeries(df.timestamps, df.pupil_area)) end # function getrunningspeed(S::AbstractSession) # f = h5open(getfile(S), "r") # r = f["processing"]["running"]["running_speed"]["data"] |> read # ts = f["processing"]["running"]["running_speed"]["timestamps"] |> read # return ToolsArray(r, (𝑡(ts),); metadata=Dict(:sessionid=>getid(S))) # end function smoothrunningspeed(S::AbstractSession; windowfunc = hanning, window = 1) r = getrunningspeed(S) ts = r.dims[1] dt = mean(diff(collect(r.dims[1]))) n = ceil(Int, window / dt / 2) * 2 w = windowfunc(n) w = w ./ sum(w) # Normalized wavelet. Outputs after convolution become averages x = DSP.conv(r, w) x = x[(n ÷ 2):(end - n ÷ 2)] return ToolsArray(x, (𝑡(collect(ts)),), metadata = r.metadata) end smoothrunningspeed(s::Integer; kwargs...) = smoothrunningspeed(Session(s); kwargs...) function stimulustrace(S::AbstractSession, feature, times) times = Interval(extrema(times)...) df = getstimuli(S, times) s = df[:, feature] x = zeros(length(s)) x[s .== "null"] .= NaN idxs = s .!= "null" x[idxs] .= Meta.parse.(s[idxs]) t = mean.(zip(df.start_time, df.stop_time)) return ToolsArray(x, (𝑡(t),)) end function stimulustrace(S::AbstractSession, feature, times::AbstractRange) s = stimulustrace(S, feature, extrema(times)) interpmatch(s, times) end function stimulustrace(S::AbstractSession, feature, x::LFPVector) t = dims(x, Ti) stimulustrace(S, feature, t) end function interpmatch(x::LFPVector, ts::AbstractRange) f = Spline1D(collect(dims(x, Ti)), x) x̂ = f(ts) return ToolsArray(x̂, (𝑡(ts),); metadata = x.metadata) end """ Match the time indices of the first input DimVector to the second by interpolating the first """ function interpmatch(x::LFPVector, y::LFPVector) ts = dims(y, Ti).val.data interpmatch(x, ts) end # function interpcorr(x::LFPVector, y::LFPVector) # x = interpmatch(x, y) # r = corspearman(x, y) # end # Consistent behaviour api function gettrials end function getlicks end function getrewards end function geteyetracking end function getrunningspeed end function getbehavior end
AllenNeuropixelsBase
https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl.git
[ "MIT" ]
0.3.0
215ea07f170cd9732aa7d7745c672f69baf3dc02
code
5672
using IntervalSets export brainobservatorycache, getophysexperiments, getspatialgrating, getdriftinggrating, getnaturalmovie, getnaturalstimulusframes, getdriftinggratingframes, getnaturalmovieframes, getstaticgratingframes, getstimulusframes function brainobservatorycache(manifest_file = brainobservatorymanifest) brain_observatory_cache.BrainObservatoryCache(manifest_file = manifest_file) end function getophysexperiments(; kwargs...) brainobservatorycache().get_ophys_experiments(; kwargs...) end function getspatialgrating(; height = 100, aspect_ratio = 2, ori = 45, pix_per_cycle = 1 / 0.04, phase = 0, p2p_amp = 0.8, baseline = p2p_amp / 2) if any([ori, pix_per_cycle, phase, p2p_amp, baseline] .== ["null"]) # They showed blank (gray) gratings f = stimulus_info.get_spatial_grating(; height, aspect_ratio, ori = 45, pix_per_cycle = height, phase = 0, p2p_amp = 0.8, baseline = 0) f .= 0.4 # A gray color, mean of sine between 0 and 0.8 end stimulus_info.get_spatial_grating(; height, aspect_ratio, ori, pix_per_cycle, phase, p2p_amp, baseline) end function getdriftinggrating(t::Real; temporal_frequency = 2, kwargs...) d = kwargs |> Dict{Symbol, Any} d[:phase] = pop!(d, :phase, 0) + (t * temporal_frequency) % 1 # ! This is how they do it in the allensdk getspatialgrating(; d...) end function getnaturalmovie(stimulus) boc = getophysexperiments(stimuli = [stimulus])[1] # Just need one of these sessions to get the template ds = brainobservatorycache().get_ophys_experiment_data(boc["id"]) template = ds.get_stimulus_template(stimulus) end function getnaturalstimulusframes(session, times) df = getstimuli(session, times) movies = unique(df.stimulus_name) @assert all(.∈(movies, (["natural_movie_one", "natural_movie_three", "natural_scenes"],))) movieframes = [getnaturalmovie(movie) for movie in movies] frames = Vector{Matrix{Float32}}(undef, length(times)) for t in 1:length(times) movieidx = indexin([df.stimulus_name[t]], movies)[1] frame = Int(Meta.parse(df.frame[t]) + 1) # Goddamn python frames start at 0 if frame < 1 frames[t] = fill(1.0, size(frames[t - 1])) else frames[t] = movieframes[movieidx][frame, :, :] ./ 256 end end return ToolsArray(frames, (𝑡(times))) end getnaturalmovieframes = getnaturalstimulusframes function getdriftinggratingframes(session, times) df = getstimuli(session, times) height = 100 aspect_ratio = 2 frames = [Matrix{Float32}(undef, height, aspect_ratio * height) for t in 1:length(times)] for t in 1:lastindex(times) if any((df.temporal_frequency[t], df.orientation[t], df.contrast) .== ["null"]) frames[t] .= 0.4 else frames[t] = getdriftinggrating(times[t] - df.start_time[t]; temporal_frequency = df.temporal_frequency[t] |> Meta.parse, height, aspect_ratio, ori = df.orientation[t] |> Meta.parse, pix_per_cycle = 1 / Meta.parse(df.spatial_frequency[t]), p2p_amp = df.contrast[t] |> Meta.parse) end end return ToolsArray(frames, (𝑡(times))) end function getstaticgratingframes(session, times, spontaneous = false) df = getstimuli(session, times) height = 100 aspect_ratio = 2 frames = [Matrix{Float32}(undef, height, aspect_ratio * height) for t in 1:length(times)] for t in 1:lastindex(times) if any((df.orientation[t], df.contrast) .== ["null"]) || spontaneous frames[t] .= 0.4 else frames[t] = getspatialgrating(; height, aspect_ratio, ori = df.orientation[t] |> Meta.parse, pix_per_cycle = 1 / Meta.parse(df.spatial_frequency[t]), p2p_amp = df.contrast[t] |> Meta.parse) end end return ToolsArray(frames, (𝑡(times))) end function _getstimulusframes(session, times, stimulus) if stimulus ∈ ["static_gratings", "spontaneous"] # Spontaneous is just a mean-luminance blank screen] getstaticgratingframes(session, times, stimulus == "spontaneous") elseif stimulus == "drifting_gratings" getdriftinggratingframes(session, times) elseif stimulus ∈ ["natural_movie_one", "natural_movie_three", "natural_scenes"] getnaturalstimulusframes(session, times) end end function getstimulusframes(session, times) epochs = getepochs(session) epochs = epochs[[any(times .∈ x.start_time .. x.stop_time) for x in eachrow(epochs)], :] # Get epochs that contain the times epochtimes = [[t for t in times if t ∈ x.start_time .. x.stop_time] for x in eachrow(epochs)] frames = [_getstimulusframes(session, epochtimes[x], epochs.stimulus_name[x]) for x in 1:length(epochtimes)] frames = ToolsArray(vcat(frames...), (𝑡(times))) end
AllenNeuropixelsBase
https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl.git
[ "MIT" ]
0.3.0
215ea07f170cd9732aa7d7745c672f69baf3dc02
code
14717
using IntervalSets export ecephyscache, behaviorcache, getsessiontable, getprobes, getchannels, listprobes, getsessiondata, AbstractSession, Session, getid, getprobes, getfile, getprobeids, getchannels, getprobecoordinates, getstructureacronyms, getstructureids, getprobestructures, getprobe, getunits, getepochs, getstimuli, getstimulustimes, getunitmetrics, getunitanalysismetrics, getunitanalysismetricsbysessiontype, isvalidunit, onlyvalid, getchannelcoordinates, getperformancemetrics function ecephyscache() ecephys_project_cache.EcephysProjectCache.from_warehouse(manifest = ecephysmanifest) end function __behaviorcache() cache = behavior_project_cache.VisualBehaviorNeuropixelsProjectCache if (isdir(behaviormanifest) || isfile(behaviormanifest)) && haskey(ENV, "ALLEN_NEUROPIXELS_OFFLINE") && ENV["ALLEN_NEUROPIXELS_OFFLINE"] == "true" cache.from_local_cache(; cache_dir = behaviormanifest) # So we can work offline else cache.from_s3_cache(cache_dir = behaviormanifest) end end behaviorcache() = _behaviorcache """ # getsessiontable — Read and return the session table from the EcephysProjectCache `getsessiontable()` Read the session table data from the `EcephysProjectCache` object returned by `ecephyscache` and returns it as a `DataFrame`. """ function getsessiontable() @info "Please wait, this can take a few seconds" df = py2df(ecephyscache().get_session_table()) df.ecephys_structure_acronyms = [string.(s) for s in df.ecephys_structure_acronyms] return df end export getsessiontable getperformancemetrics() = () """ `getprobes()` Read the probe data from the `EcephysProjectCache` object returned by `ecephyscache()` and return it as a `DataFrame`. ## Returns A `DataFrame` containing the probe data. """ function getprobes() py2df(ecephyscache().get_probes()) end export getprobes function getchannels() py2df(ecephyscache().get_channels()) end export getchannels listprobes(session) = getchannels.((session,), getprobeids(session)) export listprobes function getsessiondata(session_id::Int; filter_by_validity = true, amplitude_cutoff_maximum = 0.1, presence_ratio_minimum = 0.9, isi_violations_maximum = 0.5) if session_id > 1000000000 behaviorcache().get_ecephys_session(session_id) else ecephyscache().get_session_data(session_id; filter_by_validity = filter_by_validity, amplitude_cutoff_maximum = amplitude_cutoff_maximum, presence_ratio_minimum = presence_ratio_minimum, isi_violations_maximum = isi_violations_maximum) end end export getsessiondata abstract type AbstractSession end export AbstractSession struct Session <: AbstractSession pyObject::Any end export Session function Session(session_id::Int; kwargs...) if session_id > 1000000000 VisualBehavior.Session(session_id; kwargs...) else Session(getsessiondata(session_id; kwargs...)) end end Session(; params...) = Session(params[:sessionid]); getid(S::AbstractSession) = pyconvert(Int, S.pyObject.ecephys_session_id) _getprobes(S::AbstractSession) = S.pyObject.probes getprobes(S::AbstractSession) = py2df(_getprobes(S)) function getfile(S::AbstractSession) datadir * "Ecephys/session_" * string(getid(S)) * "/session_" * string(getid(S)) * ".nwb" end getprobeids(S::AbstractSession) = getprobes(S)[!, :id] function getchannels(df::DataFrame) if hasproperty(df, :ecephys_structure_acronym) df.structure_acronym = df.ecephys_structure_acronym elseif hasproperty(df, :structure_acronym) df.ecephys_structure_acronym = df.structure_acronym end return df end function getchannels(df::DataFrame, probeid::Number) subset(df, :probe_id => ByRow(==(probeid))) end function getchannels(df::DataFrame, probeids) subset(df, :probe_id => ByRow(∈(probeids))) end function getchannels(S::AbstractSession) df = py2df(S.pyObject.channels) return getchannels(df) end function getchannels(S::AbstractSession, probeid) df = getchannels(S) getchannels(df, probeid) end # function getprobecoordinates(S::AbstractSession) # c = subset(getchannels(S), :anterior_posterior_ccf_coordinate => ByRow(!ismissing), # :dorsal_ventral_ccf_coordinate => ByRow(!ismissing), # :left_right_ccf_coordinate => ByRow(!ismissing)) # x = c[!, :anterior_posterior_ccf_coordinate] # y = c[!, :dorsal_ventral_ccf_coordinate] # z = c[!, :left_right_ccf_coordinate] # return (x, y, z) # end function getprobecoordinates(args...)#; only_has_lfp=false) # if only_has_lfp # _c = getchannels() # _c = _c[_c.has_lfp_data.==true, :] # _c = _c.id # c = subset(getchannels(args...), :anterior_posterior_ccf_coordinate => ByRow(!ismissing), # :dorsal_ventral_ccf_coordinate => ByRow(!ismissing), # :left_right_ccf_coordinate => ByRow(!ismissing), # :id => ByRow(x -> x ∈ _c)) # else c = subset(getchannels(args...), :anterior_posterior_ccf_coordinate => ByRow(!ismissing), :dorsal_ventral_ccf_coordinate => ByRow(!ismissing), :left_right_ccf_coordinate => ByRow(!ismissing)) # end x = c[!, :anterior_posterior_ccf_coordinate] y = c[!, :dorsal_ventral_ccf_coordinate] z = c[!, :left_right_ccf_coordinate] return (x, y, z) end function getchannelcoordinates(args...) c = subset(getchannels(args...), :anterior_posterior_ccf_coordinate => ByRow(!ismissing), :dorsal_ventral_ccf_coordinate => ByRow(!ismissing), :left_right_ccf_coordinate => ByRow(!ismissing)) x = c[!, :anterior_posterior_ccf_coordinate] y = c[!, :dorsal_ventral_ccf_coordinate] z = c[!, :left_right_ccf_coordinate] return Dict(c.id .=> zip(x, y, z)) end notemptyfirst(x) = length(x) > 0 ? x[1] : missing # function getstructureacronyms(channelids::Vector{Int}) # channels = getchannels() # # acronyms = Vector{Any}(undef, size(channelids)) # acronyms = [notemptyfirst(channels[channels.id.==channelids[i], :ecephys_structure_acronym]) for i ∈ 1:length(channelids)] # return acronyms # end function getstructureacronyms(S::AbstractSession, channelids::Vector{Int}) channels = getchannels(S) acronyms = Vector{Any}(undef, size(channelids)) [acronyms[i] = notemptyfirst(channels[channels.id .== channelids[i], :structure_acronym]) for i in 1:length(channelids)] return acronyms end function getstructureids(channelids::Vector{Int}) channels = getchannels() acronyms = Vector{Any}(undef, size(channelids)) [acronyms[i] = notemptyfirst(channels[channels.id .== channelids[i], :ecephys_structure_id]) for i in 1:length(channelids)] return acronyms end function getprobestructures(S::AbstractSession) df = listprobes(S) acronyms = [unique(string.(d.structure_acronym)) for d in df] # acronyms = [a[.!ismissing.(a)] for a in acronyms] probeids = [unique(d.probe_id) |> first for d in df] return Dict(probeids .=> acronyms) end function getprobestructures(S::AbstractSession, structures::AbstractVector) D = getprobestructures(S) filter!(d -> any(structures .∈ (last(d),)), D) D = Dict(k => first(v[v .∈ [structures]]) for (k, v) in D) end function getprobe(S::AbstractSession, structure::AbstractString) D = getprobestructures(S, [structure]) return first(keys(D)) end function getprobes(S, structures::Vector) getprobe.((S,), structures) end getprobes(S, structure::String) = getprobe(S, structures) function getunits(; filter_by_validity = true, amplitude_cutoff_maximum = 0.1, presence_ratio_minimum = 0.9, isi_violations_maximum = 0.5) str = ecephyscache().get_units(filter_by_validity = filter_by_validity, amplitude_cutoff_maximum = amplitude_cutoff_maximum, presence_ratio_minimum = presence_ratio_minimum, isi_violations_maximum = isi_violations_maximum) py2df(str) end export getunits function getunits(structure::String; kwargs...) units = getunits(; kwargs...) units = subset(units, :structure_acronym, structure) end function getsessionunits(session::AbstractSession) # Much faster than the option below units = pyObject(session.pyObject.units.to_dataframe()) units.structure_acronym = units.ecephys_structure_acronym end function getsessionunits(session::AbstractSession, structure::String) subset(getsessionunits(session), :structure_acronym, structure) end function getunits(session::AbstractSession; kwargs...) units = getunits(; kwargs...) units = subset(units, :ecephys_session_id, getid(session)) end function getunits(session::AbstractSession, structure::String) subset(getunits(session), :structure_acronym, structure) end function getunitanalysismetricsbysessiontype(session_type; filter_by_validity = true, amplitude_cutoff_maximum = 0.1, presence_ratio_minimum = 0.9, isi_violations_maximum = 0.5) # Yeah thats python str = ecephyscache().get_unit_analysis_metrics_by_session_type(session_type, filter_by_validity = filter_by_validity, amplitude_cutoff_maximum = amplitude_cutoff_maximum, presence_ratio_minimum = presence_ratio_minimum, isi_violations_maximum = isi_violations_maximum) py2df(str) end export getunitanalysismetricsbysessiontype function getallunitmetrics() # This one is really slow metrics1 = get_unit_analysis_metrics_by_session_type("brain_observatory_1.1", amplitude_cutoff_maximum = Inf, presence_ratio_minimum = -Inf, isi_violations_maximum = Inf) metrics2 = get_unit_analysis_metrics_by_session_type("functional_connectivity", amplitude_cutoff_maximum = Inf, presence_ratio_minimum = -Inf, isi_violations_maximum = Inf) vcat(analysis_metrics1, analysis_metrics2) end export getallunitmetrics function getunitanalysismetrics(session::AbstractSession; annotate = true, filter_by_validity = true, kwargs...) str = ecephyscache().get_unit_analysis_metrics_for_session(getid(session); annotate, filter_by_validity, kwargs...) py2df(str) end function isvalidunit(S::AbstractSession, u::AbstractVector) metrics = getunitanalysismetrics(S) return u .∈ (metrics.ecephys_unit_id,) end function onlyvalid(s::AbstractSession, sp::Dict) K = keys(sp) |> collect V = values(sp) |> collect idxs = isvalidunit(s, (K)) K = K[idxs] V = V[idxs] return Dict(k => v for (k, v) in zip(K, V)) end function getstimuli(S::AbstractSession) str = S.pyObject.stimulus_presentations str = py2df(str) if !hasproperty(str, :stop_time) str.stop_time = str.end_time end return str end getstimulus = getstimuli function getunitmetrics(session::AbstractSession) str = session.pyObject.units py2df(str) end function getstimulusname(session::AbstractSession, time::Number; stimulus_table = getstimuli(session)) idx = findlast(stimulus_table.start_time .< time) if isnothing(idx) "blank" else stimulus_table.stimulus_name[idx] end end function getstimulusname(session::AbstractSession, times; stimulus_table = getstimuli(session), kwargs...) getstimulusname.([session], times; stimulus_table, kwargs...) end function getstimuli(S::AbstractSession, stimulusname::String) stimulus_table = getstimuli(S) df = subset(stimulus_table, :stimulus_name => ByRow(==(stimulusname))) end function getstimuli(session::AbstractSession, times::Union{Tuple, UnitRange, LinRange, Vector}) stimuli = getstimuli(session) idxs = [findfirst(time .< stimuli.stop_time) for time in times] # Find first frame that ends after each time point return stimuli[idxs, :] end function getstimuli(session::AbstractSession, times::Interval) stimuli = getstimuli(session) start = stimuli.start_time stop = stimuli.stop_time i1 = min(findfirst(start .> minimum(times)), findfirst(stop .> minimum(times))) i2 = max(findlast(start .< maximum(times)), findlast(stop .< maximum(times))) stimuli = stimuli[i1:i2, :] end function getepochs(S::Session) p = S.pyObject.get_stimulus_epochs() # Why is this so slow py2df(p) end function getepochs(S::AbstractSession, stimulusname::Regex) epoch_table = getepochs(S) df = subset(epoch_table, :stimulus_name => ByRow(x -> !isnothing(match(stimulusname, x)))) end function getepochs(S::AbstractSession, stimulusname) epoch_table = getepochs(S) df = subset(epoch_table, :stimulus_name => ByRow(==(stimulusname))) end getepochs(S::Int, args...; kwargs...) = getepochs(Session(S), args...; kwargs...) function getstimulustimes(S::Session, stimulusname) E = getepochs(S, stimulusname) ts = [E.start_time E.stop_time] times = [x .. y for (x, y) in eachrow(ts)] end function getstimulustimes(; params...) S = Session(params[:sessionid]) getstimulustimes(S, params[:stimulus])[params[:epoch]] end function getlfppath(session::AbstractSession, probeid) path = joinpath(datadir, "Ecephys", "session_" * string(getid(session)), "probe_" * string(probeid) * "_lfp.nwb") end # * Stimulus analysis # ReceptiveFieldMapping(S::AbstractSession) = stimulusmapping.ReceptiveFieldMapping(S.pyObject) # function getreceptivefield(S::AbstractSession, channel::Number) # rfm = ReceptiveFieldMapping(S) # rfm.get_receptive_field(channel) # end
AllenNeuropixelsBase
https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl.git
[ "MIT" ]
0.3.0
215ea07f170cd9732aa7d7745c672f69baf3dc02
code
6374
export HybridSession using NWBStream using PythonCall using NWBStream using DataFrames using Downloads using JSON import NWBStream.url2df mutable struct HybridSession <: AbstractNWBSession url::Any file::Any io::Any pyObject::Any function HybridSession(url::String, file, io, pyObject = ()) S = new(url, file, io, pyObject) f(S::HybridSession) = @async s3close(S.io) finalizer(f, S) end end HybridSession(url::String) = (S = HybridSession(url, s3open(url)...); initialize!(S); S) function HybridSession(session_id::Int, args...; kwargs...) HybridSession(VisualBehavior.getsessionfile(session_id), args...; kwargs...) end # Calls to getlfp should use the streaming approach if the length is less than some amount, otherwise download the file using the allensdk function _loadlfp(session::HybridSession, probeid::Int; channelidxs = 1:length(getlfpchannels(session, probeid)), timeidxs = 1:length(getlfptimes(session, probeid))) @assert(any(getprobeids(session) .== probeid), "Probe $probeid does not belong to session $(getid(session))") @assert(subset(getprobes(session), :id => ByRow(==(probeid)))[!, :has_lfp_data][1], @error "Probe $probeid does not have LFP data") path = getlfppath(session, probeid) if !isfile(path) downloadlfp(session, probeid) end if !isfile(path) @error "LFP data did not download correctly" end f = h5open(path) timedata = getlfptimes(session, probeid, timeidxs) dopermute = true channelids = getlfpchannels(session, probeid) channelids = channelids[channelidxs] if (channelidxs isa Union{Int64, AbstractRange{Int64}}) & (timeidxs isa Union{Int64, AbstractRange{Int64}}) # Can use HDF5 slicing lfp = f["acquisition"][splitext(basename(path))[1]][splitext(basename(path))[1] * "_data"]["data"][channelidxs, timeidxs] elseif timeidxs isa Union{Int64, AbstractRange{Int64}} lfp = [f["acquisition"][splitext(basename(path))[1]][splitext(basename(path))[1] * "_data"]["data"][i, timeidxs] for i in channelidxs] lfp = hcat(lfp...) dopermute = false else lfp = read(f["acquisition"][splitext(basename(path))[1]][splitext(basename(path))[1] * "_data"]["data"]) lfp = lfp[channelidxs, timeidxs] end if lfp isa Vector lfp = reshape(lfp, 1, length(lfp)) end if channelids isa Number channelids = [channelids] end if dopermute lfp = permutedims(lfp, reverse(1:ndims(lfp))) end X = ToolsArray(lfp, (𝑡(timedata), Chan(channelids)); metadata = Dict(:sessionid => getid(session), :probeid => probeid)) close(f) return X end function _streamlfp(session::AbstractNWBSession, probeid::Int; channelidxs = 1:length(getlfpchannels(session, probeid)), timeidxs = 1:length(getlfptimes(session, probeid))) @assert(any(getprobeids(session) .== probeid), "Probe $probeid does not belong to session $(getid(session))") _timeidxs = timeidxs .- 1 # Python sucks _channelidxs = channelidxs .- 1 # Python sucks f, io = getprobefile(session, probeid) |> NWBStream.s3open _lfp = Dict(f.acquisition)["probe_1108501239_lfp_data"] # timedata = getlfptimes(session, probeid) timedata = getlfptimes(session, probeid) timedata = timedata[timeidxs] channelids = getlfpchannels(session, probeid) channelids = channelids[channelidxs] lfp = zeros(Float32, length(timedata), length(channelids)) for (i, _channelidx) in enumerate(_channelidxs) d = diff(_timeidxs) # if all(d == d[1]) # We can do some efficient slicing # slc = @py slice(first(_timeidxs), last(_timeidxs), d[1]) # @time @py _lfp.data[slc] # else lfp[:, i] .= pyconvert(Vector{Float32}, _lfp.data[_timeidxs, _channelidx]) # end end if channelids isa Number channelids = [channelids] end X = ToolsArray(lfp, (𝑡(timedata), Chan(channelids))) return X end # """ # Get the lfp data for a probe, providing *indices* for channels and times. See function below for indexing by channel ids and time values/intervals # """ # function _getlfp(session::AbstractSession, probeid::Int; channelidxs=1:length(getlfpchannels(session, probeid)), timeidxs=1:length(getlfptimes(session, probeid))) # @assert(any(getprobeids(session) .== probeid), "Probe $probeid does not belong to session $(getid(session))") # @assert(subset(getprobes(session), :id=>ByRow(==(probeid)))[!, :has_lfp_data][1], @error "Probe $probeid does not have LFP data") # path = getlfppath(session, probeid) # if !isfile(path) # downloadlfp(session, probeid) # end # if !isfile(path) # @error "LFP data did not download correctly" # end # f = h5open(path) # timedata = getlfptimes(session, probeid, timeidxs) # dopermute = true # channelids = getlfpchannels(session, probeid) # channelids = channelids[channelidxs] # if (channelidxs isa Union{Int64, AbstractRange{Int64}}) & (timeidxs isa Union{Int64, AbstractRange{Int64}}) # Can use HDF5 slicing # lfp = f["acquisition"][splitext(basename(path))[1]][splitext(basename(path))[1]*"_data"]["data"][channelidxs, timeidxs] # elseif timeidxs isa Union{Int64, AbstractRange{Int64}} # lfp = [f["acquisition"][splitext(basename(path))[1]][splitext(basename(path))[1]*"_data"]["data"][i, timeidxs] for i ∈ channelidxs] # lfp = hcat(lfp...) # dopermute = false # else # lfp = read(f["acquisition"][splitext(basename(path))[1]][splitext(basename(path))[1]*"_data"]["data"]) # lfp = lfp[channelidxs, timeidxs] # end # if lfp isa Vector # lfp = reshape(lfp, 1, length(lfp)) # end # if channelids isa Number # channelids = [channelids] # end # if dopermute # lfp = permutedims(lfp, reverse(1:ndims(lfp))) # end # X = ToolsArray(lfp, (𝑡(timedata), Chan(channelids))) # close(f) # return X # end
AllenNeuropixelsBase
https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl.git
[ "MIT" ]
0.3.0
215ea07f170cd9732aa7d7745c672f69baf3dc02
code
32876
using IntervalSets using HDF5 using Statistics using Downloads import DataFrames.groupby export LFPVector, LFPMatrix, PSDMatrix, PSDVector, LogPSDVector, duration, samplingperiod, getlfp, getlfptimes, getlfpchannels, samplingrate, WaveletMatrix, LogWaveletMatrix, formatlfp, getchannels, getchanneldepths, waveletmatrix, getunitdepths, getdim, gettimes, sortbydepth, rectifytime, stimulusepochs, stimulusintervals, gaborintervals, alignlfp, logwaveletmatrix, matchlfp, joinlfp, catlfp, channels2depths, selectepochs, getchannellayers, getstreamlines LFPVector = AbstractToolsArray{T, 1, Tuple{A}, B} where {T, A <: TimeseriesTools.TimeDim, B} LFPMatrix = AbstractToolsArray{T, 2, Tuple{A, B}} where {T, A <: TimeseriesTools.TimeDim, B <: Chan} export LFPMatrix, LFPVector # For simpler dispatch function dimmatrix(a::Symbol, b::Symbol) AbstractToolsArray{T, 2, Tuple{A, B}} where {T, A <: Dim{a}, B <: Dim{b}} end function dimmatrix(a, b::Symbol) AbstractToolsArray{T, 2, Tuple{A, B}} where {T, A <: a, B <: Dim{b}} end dimmatrix(a, b) = AbstractToolsArray{T, 2, Tuple{A, B}} where {T, A <: a, B <: b} export dimmatrix PSDMatrix = dimmatrix(𝑓, Chan) PSDVector = AbstractToolsArray{T, 1, Tuple{A}, B} where {T, A <: 𝑓, B} LogPSDVector = AbstractToolsArray{T, 1, Tuple{A}, B} where {T, A <: Log𝑓, B} duration(X::AbstractToolsArray) = diff(extrema(dims(X, Ti)) |> collect) |> first function samplingperiod(X::AbstractToolsArray) if dims(X, Ti).val.data isa AbstractRange step(dims(X, Ti)) else mean(diff(collect(dims(X, Ti)))) end end samplingrate(X::AbstractToolsArray) = 1 / samplingperiod(X) WaveletMatrix = dimmatrix(Ti, 𝑓) # Type for ToolsArrays containing wavelet transform info LogWaveletMatrix = dimmatrix(Ti, Log𝑓) # Type for ToolsArrays containing wavelet transform info export WaveletMatrix, LogWaveletMatrix function Base.convert(::Type{LogWaveletMatrix}, x::WaveletMatrix) x = ToolsArray(x, (dims(x, Ti), Log𝑓(log10.(dims(x, 𝑓)))); metadata = metadata(x), refdims = refdims(x)) x = x[:, .!isinf.(dims(x, Log𝑓))] end function Base.convert(::Type{LogPSDVector}, x::PSDVector) x = ToolsArray(x, (Log𝑓(log10.(dims(x, 𝑓))),); metadata = metadata(x), refdims = refdims(x)) x = x[.!isinf.(dims(x, Log𝑓))] end function Base.convert(::Type{WaveletMatrix}, x::LogWaveletMatrix) x = ToolsArray(x, (dims(x, Ti), 𝑓(exp10.(dims(x, Log𝑓)))); metadata = metadata(x), refdims = refdims(x)) end waveletmatrix(res::LogWaveletMatrix) = convert(WaveletMatrix, res) logwaveletmatrix(res::WaveletMatrix) = convert(LogWaveletMatrix, res) logpsdvector(res::PSDVector) = convert(LogPSDVector, res) function downloadlfp(S::AbstractSession, probeid::Int) @assert(any(getprobeids(S) .== probeid), "Probe $probeid does not belong to session $(getid(S))") @assert(subset(getprobes(S), :id => ByRow(==(probeid)))[!, :has_lfp_data][1], @error "Probe $probeid does not have LFP data") _ = S.pyObject.get_lfp(probeid) return nothing end function structure2probe(S::AbstractSession, structure::String) channels = getchannels(S) channels = channels[.!ismissing.(channels.structure_acronym), :] channels = subset(channels, :structure_acronym, structure) @assert length(unique(channels.probe_id)) == 1 return channels.probe_id |> unique |> first end function getlfptimes(session::AbstractSession, probeid) path = getlfppath(session, probeid) if !isfile(path) @error "Probe lfp data file does not exist. This may be becuase you have not downloaded the probe data. Try using `getlfp`" end f = h5open(path) times = f["acquisition"][splitext(basename(path))[1]][splitext(basename(path))[1] * "_data"]["timestamps"][:] close(f) return times end function getlfptimes(session::AbstractSession, probeid, idxs) getlfptimes(session, probeid)[idxs] end function getlfptimes(session::AbstractSession, probeid::Int, i::Interval) ts = getlfptimes(session::AbstractSession, probeid::Int) ts = ts[ts .∈ (i,)] end function getlfpchannels(session::AbstractSession, probeid) if !isfile(getlfppath(session, probeid)) downloadlfp(session, probeid) end f = h5open(getlfppath(session, probeid)) channels = f["general"]["extracellular_ephys"]["electrodes"]["id"][:] close(f) return channels end function getprobeobj(S::AbstractSession, probeid) probes = S.pyObject.probes |> py2df probeids = probes.id thisprobe = findfirst(probeids .== probeid) probe = probes[thisprobe, :] end function resolvenwblfp(S::AbstractSession, probeid) probe = getprobeobj(S, probeid) res = "probe_$(probe.id)_lfp" end """ Get the lfp data for a probe, providing *indices* for channels and times. See function below for indexing by channel ids and time values/intervals """ function _getlfp(session::AbstractSession, probeid::Int; channelidxs = 1:length(getlfpchannels(session, probeid)), timeidxs = 1:length(getlfptimes(session, probeid))) @assert(any(getprobeids(session) .== probeid), "Probe $probeid does not belong to session $(getid(session))") @assert(subset(getprobes(session), :id => ByRow(==(probeid)))[!, :has_lfp_data][1], @error "Probe $probeid does not have LFP data") path = getlfppath(session, probeid) if !isfile(path) downloadlfp(session, probeid) end if !isfile(path) @error "LFP data did not download correctly" end f = h5open(path) timedata = getlfptimes(session, probeid, timeidxs) dopermute = true channelids = getlfpchannels(session, probeid) channelids = channelids[channelidxs] res = resolvenwblfp(session, probeid) if (channelidxs isa Union{Int64, AbstractRange{Int64}}) & (timeidxs isa Union{Int64, AbstractRange{Int64}}) # Can use HDF5 slicing lfp = f["acquisition"][res][res * "_data"]["data"][channelidxs, timeidxs] elseif timeidxs isa Union{Int64, AbstractRange{Int64}} lfp = [f["acquisition"][res][res * "_data"]["data"][i, timeidxs] for i in channelidxs] lfp = hcat(lfp...) dopermute = false else lfp = read(f["acquisition"][res][res * "_data"]["data"]) lfp = lfp[channelidxs, timeidxs] end if lfp isa Vector lfp = reshape(lfp, 1, length(lfp)) end if channelids isa Number channelids = [channelids] end if dopermute lfp = permutedims(lfp, reverse(1:ndims(lfp))) end X = ToolsArray(lfp, (𝑡(timedata), Chan(channelids)); metadata = Dict(:sessionid => getid(session), :probeid => probeid)) close(f) X = addchanneldepths(session, X; method = :probe) X = sortbydepth(session, probeid, X; method = :probe) return X end function isinvalidtime(session::AbstractSession, probeids = getprobeids(session), times = NaN) if hasproperty(session.pyObject, :get_invalid_times) && isempty(session.pyObject.get_invalid_times()) # No invalid times in this session! return false end intervals = [session.pyObject.get_invalid_times().start_time.values, session.pyObject.get_invalid_times().stop_time.values] intervals = [[pyconvert(Float64, intervals[1][i]), pyconvert(Float64, intervals[2][i])] for i in 0:(length(intervals[1]) - 1)] tags = session.pyObject.get_invalid_times().tags.values # tags = vcat([pyconvert(Array{Int64}, i) for i ∈ tags]...) # badprobes = tags[.!isnothing.(tags)] badprobes = [] if times isa Interval isininterval = [any(i .∈ (times,)) for i in intervals] else isininterval = [any((times .> i[1]) .& (times .< i[2])) for i in intervals] end return any(probeids .∈ (badprobes,)) & any(isininterval) end function isinvalidtime(session::AbstractNWBSession, probeids = getprobeids(session), times = NaN) return !pyconvert(Bool, getfile(session).invalid_times == @py None) end """ This is the one you should be using. Get lfp data by channel id and time intervals or vector. Also, throw error if you try to access an invalid time interval. """ function getlfp(session::AbstractSession, probeid::Int; channels = getlfpchannels(session, probeid), times = ClosedInterval(extrema(getlfptimes(session, probeid))...), inbrain = false) if isinvalidtime(session, probeid, times) @error "Requested LFP data contains an invalid time..." end if inbrain isa Symbol || inbrain isa Real || inbrain depths = getchanneldepths(session, probeid, channels; method = :probe) if inbrain isa Real # A depth cutoff channels = channels[depths .> inbrain] elseif inbrain isa Symbol # A mode else # Just cutoff at the surface channels = channels[depths .> 0] end end channelidxs = getlfpchannels(session, probeid) channelidxs = indexin(channels, channelidxs) channelidxs = filter(!isnothing, channelidxs) @assert length(channels) == length(channelidxs) timeidxs = getlfptimes(session, probeid) if !(times isa Interval) && length(times) == 2 times = ClosedInterval(times...) end if times isa Interval @debug "Getting LFP data for $(length(channelidxs)) channels at $(times) times" timeidxs = findall(timeidxs .∈ (times,)) if isempty(timeidxs) @warn "Session $(getid(session)), probe $probeid has no LFP for $(times)" end else timeidxs = indexin(times, timeidxs) timeidxs = filter(!isnothing, timeidxs) @assert length(timeidxs) == length(times) end # See if we can convert to unitranges for faster HDF5 reading via slicing if collect(UnitRange(extrema(timeidxs)...)) == timeidxs timeidxs = UnitRange(extrema(timeidxs)...) end if collect(UnitRange(extrema(channelidxs)...)) == channelidxs channelidxs = UnitRange(extrema(channelidxs)...) end @info "Accessing LFP data for session $(getid(session))" _getlfp(session, probeid; channelidxs, timeidxs) end """ If you want to downsample the LFP data, its quicker to use this function and then perform slicing afterwards (since getlfp() has to check all of the time coordinates you supply, which can be slow). """ function getdownsampledlfp(session, probeid; downsample = 100, timerange = ClosedInterval(extrema(getlfptimes(session, probeid))...), channels = getlfpchannels(session, probeid)) if !(timerange isa Interval) && length(timerange) == 2 timerange = ClosedInterval(timerange...) end timevals = getlfptimes(session, probeid) tidxs = timevals .∈ (timerange,) times = findfirst(tidxs):downsample:findlast(tidxs) _getlfp(session, probeid; timeidxs = times)[:, At(channels)] end """ Now we can overload `getlfp()` to index by structure """ function getlfp(session::AbstractSession, probeid::Int, structures::Union{Vector{<:AbstractString}, AbstractString}; kwargs...) if structures isa String structures = [structures] end channels = subset(getchannels(session, probeid), :structure_acronym => ByRow(in(structures)), skipmissing = true) channels = channels.id ∩ getlfpchannels(session, probeid) isempty(channels) && @error "No matching channels found for structure(s) $structures. Perhaps you have entered the wrong probe id?" getlfp(session, probeid; channels, kwargs...) end function getlfp(S::AbstractSession, structure::AbstractString; kwargs...) probeid = structure2probe(S, structure) getlfp(S, probeid, structure; kwargs...) end function getlfp(session::AbstractSession, probeids::Vector{Int}, args...; kwargs...) LFP = [getlfp(session, probeid, args...; kwargs...) for probeid in probeids] end function selectepochs(session, stimulus, epoch) epochs = getepochs(session, stimulus) isnothing(epoch) && (return epochs) isempty(epochs) && (@error "No '$stimulus' epoch found in session $(getid(session))") if !(epoch isa Symbol) && length(epoch) > 1 qualifier = epoch[2] epoch = epoch[1] if qualifier isa Symbol qualifier = qualifier => ByRow(==(true)) end _epochs = subset(epochs, qualifier) if !isempty(_epochs) epochs = _epochs else error("Invalid qualifier '$qualifier' for epoch '$epoch' in this session") end end if epoch == :longest _, epoch = findmax(epochs.duration) elseif epoch == :first epoch = 1 elseif epoch == :last epoch = size(epochs, 1) end epoch = epochs[epoch, :] |> DataFrame end function formatlfp(session::AbstractSession; probeid = nothing, tol = 6, stimulus, structure, epoch = :longest, rectify = true, inbrain = 0.0, kwargs...) if isnothing(probeid) probeid = getprobe(session, structure) end if isnothing(structure) structure = getstructureacronyms(session, getchannels(session, probeid).id) |> unique |> skipmissing |> collect |> Vector{String} structure = structure[structure .!= ["root"]] end if stimulus == "all" X = getlfp(session, probeid, structure; inbrain) else epoch = selectepochs(session, stimulus, epoch) times = first(epoch.start_time) .. first(epoch.stop_time) X = getlfp(session, probeid, structure; inbrain, times) end if rectify X = TimeseriesTools.rectify(X; dims = 𝑡, tol) end X = addmetadata(X; stimulus, structure) end function formatlfp(; sessionid = 757216464, probeid = nothing, kwargs...) if sessionid < 1000000000 session = Session(sessionid) else session = VisualBehavior.Session(sessionid) end formatlfp(session; probeid, kwargs...) end export formatlfp function getstreamlines() streamlines = load(streamlinepath) streamlines = ToolsArray(streamlines.data, (Dim{:L}(getproperty(streamlines.axes[1], :val)), Dim{:P}(getproperty(streamlines.axes[2], :val)), Dim{:S}(getproperty(streamlines.axes[3], :val)))) return streamlines end function getchannellayers(session, X::LFPMatrix, cdf = getchannels(session)) if Dim{:layer} ∈ refdims(X) return X end layers = getchannellayers(session, dims(X, Chan) |> collect, cdf) addrefdim(X, Dim{:layer}(layers[1])) end function getchannellayers(session, channels, cdf = getchannels(session)) channels = collect(channels) tre = getstructuretree() mp = getstructureidmap() function get_layer_name(acronym) try if !pyconvert(Bool, tre.structure_descends_from(mp[acronym], mp["Isocortex"])) return 0 end # * ! Check that the structure is in the isocortex using the structure tree layer = parse(Int, match(r"\d+", acronym).match) if layer == 3 layer = 0 end return layer catch return 0 end end function get_structure_ids(df, annotations) x = round.(Int, df.anterior_posterior_ccf_coordinate / 10) y = round.(Int, df.dorsal_ventral_ccf_coordinate / 10) z = round.(Int, df.left_right_ccf_coordinate / 10) x[x .< 0] .= 0 y[y .< 0] .= 0 z[z .< 0] .= 0 structure_ids = [annotations[_x .+ 1, _y .+ 1, _z .+ 1] for (_x, _y, _z) in zip(x, y, z)] # annotation volume is 1-indexed return structure_ids .|> Int |> vec end df = cdf[indexin(channels, cdf.id), :] annotations, _ = getannotationvolume(; resolution = 10) df = df[df.anterior_posterior_ccf_coordinate .> 0, :] x = floor.(Int, df.anterior_posterior_ccf_coordinate / 10) y = floor.(Int, df.dorsal_ventral_ccf_coordinate / 10) z = floor.(Int, df.left_right_ccf_coordinate / 10) structure_ids = get_structure_ids(df, annotations) structure_tree = Dict(v => k for (k, v) in getstructureidmap()) structure_acronyms = [s == 0 ? "root" : getindex(structure_tree, s) for s in structure_ids] layers = [get_layer_name(acronym) for acronym in structure_acronyms] structure_acronyms = map(structure_acronyms) do s if pyconvert(Bool, tre.structure_descends_from(mp[s], mp["Isocortex"])) while isnothing(tryparse(Float64, string(last(s)))) s = s[1:(end - 1)] # Truncating sublayer numbers end end s end return layers, structure_acronyms end function getchannels(data::AbstractToolsArray) dims(data, Chan).val end function getchanneldepths(session, d::TimeseriesTools.ToolsDimension; kwargs...) getchanneldepths(session, d.val.data; kwargs...) end function addchanneldepths(session::AbstractSession, X::LFPMatrix; method = :probe, kwargs...) if ((Depth ∈ refdims(X)) || any(isa.(refdims(X), [Depth]))) && haskey(metadata(X), :depth_method) && metadata(X)[:depth_method] === method @warn "Depth information already present in this LFP matrix, rewriting" end depths = getchanneldepths(session, dims(X, Chan); method, kwargs...) m = Dict(c => d for (c, d) in zip(dims(X, Chan), depths)) X = addmetadata(X; depths = m) return addmetadata(X; depthmethod = method) end function getchanneldepths(session, probeid, channels; kwargs...) cdf = getchannels(session, probeid) return _getchanneldepths(cdf, channels; kwargs...) end function getchanneldepths(session, channels::Union{AbstractVector, Tuple}; kwargs...) _cdf = getchannels(session) # Slightly slower than the above cdf = _cdf[indexin(channels, _cdf.id), :] cdfs = groupby(cdf, :probe_id) probeids = [unique(c.probe_id)[1] for c in cdfs] depths = vcat([_getchanneldepths(_cdf[_cdf.probe_id .== p, :], c.id; kwargs...) for (p, c) in zip(probeids, cdfs)]...) depths = depths[indexin(channels, vcat(cdfs...).id)] end function _getchanneldepths(cdf, channels; method = :probe) # surfaceposition = minimum(subset(cdf, :structure_acronym=>ByRow(ismissing)).probe_vertical_position) # Minimum because tip is at 0 if method === :dorsal_ventral if any(ismissing.(cdf.structure_acronym)) surfaceposition = maximum(subset(cdf, :structure_acronym => ByRow(ismissing)).dorsal_ventral_ccf_coordinate) elseif any(skipmissing(cdf.structure_acronym) .== ["root"]) # For VBN files, "root" rather than "missing" surfaceposition = maximum(subset(cdf, :structure_acronym => ByRow(==("root"))).dorsal_ventral_ccf_coordinate) end # Assume the first `missing` channel corresponds to the surfaceprobe_vertical_position idxs = indexin(channels, cdf.id)[:] # alldepths = surfaceposition .- cdf.probe_vertical_position # in μm alldepths = cdf.dorsal_ventral_ccf_coordinate .- surfaceposition # in μm depths = fill(NaN, size(idxs)) depths[.!isnothing.(idxs)] = alldepths[idxs[.!isnothing.(idxs)]] elseif method === :probe if any(ismissing.(cdf.structure_acronym)) surfaceposition = minimum(subset(cdf, :structure_acronym => ByRow(ismissing)).probe_vertical_position) elseif any(skipmissing(cdf.structure_acronym) .== ["root"]) # For VBN files, "root" rather than "missing" surfaceposition = minimum(subset(cdf, :structure_acronym => ByRow(==("root"))).probe_vertical_position) else display(unique(cdf.structure_acronym)) error("No missing channels found, cannot identify surface position") end # Assume the first `missing` channel corresponds to the surfaceprobe_vertical_position idxs = indexin(channels, cdf.id)[:] # alldepths = surfaceposition .- cdf.probe_vertical_position # in μm alldepths = surfaceposition .- cdf.probe_vertical_position # in μm depths = fill(NaN, size(idxs)) depths[.!isnothing.(idxs)] = alldepths[idxs[.!isnothing.(idxs)]] elseif method === :streamlines # This one only really works for the cortex. Anything outside the cortex is a guess based on linear extrapolation. # Also note that this gives what seems to be a proportion in the cortex # https://www.dropbox.com/sh/7me5sdmyt5wcxwu/AACB2idSLV-F_QOG894NnZS2a?dl=0&preview=layer_mapping_example.py # # The code used in the siegle 2021 paper # Assumes all channels are on the same probe? streamlines = getstreamlines() df = cdf[cdf.anterior_posterior_ccf_coordinate .> 0, :] x = df.anterior_posterior_ccf_coordinate y = df.dorsal_ventral_ccf_coordinate z = df.left_right_ccf_coordinate cortical_depth = [streamlines[Dim{:L}(Near(_x)), Dim{:P}(Near(_y)), Dim{:S}(Near(_z))] for (_x, _y, _z) in zip(x, y, z)] # 1-based indexing # Linearly extrapolate the zero depths _xs = findall(cortical_depth .> 0) _ys = cortical_depth[_xs] depthf(x) = first([1 x] * ([ones(length(_xs)) _xs] \ _ys)) cortical_depth[cortical_depth .== 0] .= depthf.(findall(cortical_depth .== 0)) # f = Figure() # ax = Axis3(f[1, 1]; aspect=:data) # volume!(ax, dims(streamlines, Dim{:L})[1:100:end] |> collect, # dims(streamlines, Dim{:P})[1:10:end] |> collect, # dims(streamlines, Dim{:S})[1:100:end] |> collect, # streamlines.data[1:100:end, 1:100:end, 1:100:end]) # meshscatter!(ax, x, y, z, markersize=100, color=getchanneldepths(session, channels; method=:dorsal_ventral)) # current_figure() df.cortical_depth .= 0.0 df[df.anterior_posterior_ccf_coordinate .> 0, :cortical_depth] .= cortical_depth df = df[indexin(channels, df.id), :] depths = df.cortical_depth else error("`$method` is not a valid method of calculating depths") end return depths end function getchanneldepths(session, probeid, X::LFPMatrix; kwargs...) if haskey(metadata(X), :depth) && haskey(metadata(X), :depth_method) && metadata(X)[:depth_method] === method @warn "Depth information already present in this LFP matrix" D = metadata(X, :depth) return getindex.([D], dims(X, Chan)) else channels = dims(X, Chan) |> collect getchanneldepths(session, probeid, channels; kwargs...) end end function getchanneldepths(S::AbstractSession, X::LFPMatrix; kwargs...) if haskey(metadata(X), :depth) && haskey(metadata(X), :depth_method) && metadata(X)[:depth_method] === method @warn "Depth information already present in this LFP matrix" D = metadata(X, :depth) return getindex.([D], dims(X, Chan)) else @assert haskey(metadata(X), :probeid) getchanneldepths(S, metadata(X)[:probeid], X; kwargs...) end end function getchanneldepths(X::LFPMatrix; kwargs...) if haskey(metadata(X), :depth) && haskey(metadata(X), :depth_method) && metadata(X)[:depth_method] === method @warn "Depth information already present in this LFP matrix" D = metadata(X, :depth) return getindex.([D], dims(X, Chan)) else @assert all(haskey.((metadata(X),), (:sessionid, :probeid))) @debug "Constructing a session to extract depth info" S = Session(metadata(X)[:sessionid]) getchanneldepths(S, metadata(X)[:probeid], X; kwargs...) end end function channels2depths(session, probeid::Integer, X::AbstractToolsArray, d::Integer; kwargs...) Y = deepcopy(X) _d = d c = dims(Y, _d) |> collect depths = getchanneldepths(session, probeid, c; kwargs...) Y = set(Y, dims(Y, _d) => Depth(depths)) Y = reorder(Y, dims(Y, _d) => DimensionalData.ForwardOrdered) return Y end function channels2depths(session, probeids::Vector, X::AbstractToolsArray, d; kwargs...) Y = deepcopy(X) d = [d...] for (i, _d) in d probeid = probeids[i] c = dims(Y, _d) |> collect depths = getchanneldepths(session, probeid, c; kwargs...) Y = set(Y, dims(Y, _d) => Depth(depths)) end return Y end function channels2depths(session, X::AbstractToolsArray; kwargs...) Y = deepcopy(X) probeid = X.metadata[:probeid] c = dims(Y, Chan) |> collect depths = getchanneldepths(session, probeid, c; kwargs...) Y = set(Y, dims(Y, Chan) => Depth(depths)) return Y end function getunitdepths(session, probeid, units; kwargs...) metrics = getunitanalysismetrics(session; filter_by_validity = false) check = units .∈ (metrics.ecephys_unit_id,) check = all(units .∈ (metrics.ecephys_unit_id,)) if !check @error "Some units do not have corresponding metrics" end metrics = subset(metrics, :ecephys_unit_id, units) channels = metrics.ecephys_channel_id getchanneldepths(session, probeid, channels; kwargs...) end getdim(X::AbstractToolsArray, dim) = dims(X, dim).val gettimes(X::AbstractToolsArray) = getdim(X, Ti) function sortbydepth(session, channels; kwargs...) depths = getchanneldepths(session, channels; kwargs...) indices = sortperm(depths) return channels[indices] end function sortbydepth(session, probeid, LFP::AbstractToolsArray; kwargs...) depths = getchanneldepths(session, LFP; kwargs...) indices = Array{Any}([1:size(LFP, i) for i in 1:length(size(LFP))]) indices[findfirst(isa.(dims(LFP), Chan))] = sortperm(depths) return LFP[indices...] end function rectifytime(X::AbstractToolsArray; tol = 6, zero = false) # tol gives significant figures for rounding ts = gettimes(X) stp = ts |> diff |> mean err = ts |> diff |> std if err > stp / 10.0^(-tol) @warn "Time step is not approximately constant, skipping rectification" else stp = round(stp; digits = tol) t0, t1 = round.(extrema(ts); digits = tol) if zero origts = t0:stp:(t1 + (10000 * stp)) t1 = t1 - t0 t0 = 0 end ts = t0:stp:(t1 + (10000 * stp)) ts = ts[1:size(X, Ti)] # Should be ok? end @assert length(ts) == size(X, Ti) X = set(X, Ti => ts) if zero X = rebuild(X; metadata = Dict(:time => origts, pairs(metadata(X))...)) end return X end function stimulusepochs(session, stim) stimtable = getepochs(session, stim) stimtable.interval = [a .. b for (a, b) in zip(stimtable.start_time, stimtable.stop_time)] return stimtable end function stimulusintervals(session, stim) stimtable = getstimuli(session, stim) stimtable.interval = [a .. b for (a, b) in zip(stimtable.start_time, stimtable.stop_time)] return stimtable end function gaborintervals(session) stimtable = getstimuli(session, "gabors") stimtable.combined_pos = sqrt.(Meta.parse.(stimtable.x_position) .^ 2 .+ Meta.parse.(stimtable.y_position) .^ 2) # Radial position of the gabor stimulus stimtable.interval = [a .. b for (a, b) in zip(stimtable.start_time, stimtable.stop_time)] return stimtable end function radialgaborseries(session, times) stimtable = getstimuli(session, "gabors") stimtable.combined_pos = sqrt.(Meta.parse.(stimtable.x_position) .^ 2 .+ Meta.parse.(stimtable.y_position) .^ 2) # Radial position of the gabor stimulus gaborseries = ToolsArray(zeros(length(times)), (𝑡(times),)) for pos in unique(stimtable.combined_pos) gabortimes = [a .. b for (a, b, x) in zip(stimtable.start_time, stimtable.stop_time, stimtable.combined_pos) if x == pos] for ts in gabortimes gaborseries[𝑡(ts)] .= pos end end return gaborseries end function alignlfp(session, X, ::Val{:gabors}; x_position = nothing, y_position = nothing) gaborstim = gaborintervals(session) X = TimeseriesTools.rectify(X; dims = 𝑡) isnothing(x_position) || (gaborstim = gaborstim[Meta.parse.(gaborstim.x_position) .== x_position, :]) isnothing(y_position) || (gaborstim = gaborstim[Meta.parse.(gaborstim.y_position) .== y_position, :]) _X = [X[𝑡(g)] for g in gaborstim.interval] _X = [x[1:minimum(size.(_X, Ti)), :] for x in _X] # Catch any that are one sample too long # _X = ToolsArray(mean(collect.(_X)), (𝑡(step(dims(X, Ti)):step(dims(X, Ti)):step(dims(X, Ti))*minimum(size.(_X, Ti))), dims(X, Chan))) return _X end function alignlfp(session, X, ::Val{:static_gratings}) stim = stimulusintervals(session, "static_gratings") stim = stim[stim.start_time .> minimum(dims(X, Ti)), :] stim = stim[stim.stop_time .< maximum(dims(X, Ti)), :] X = TimeseriesTools.rectify(X; dims = 𝑡) _X = [X[𝑡(g)] for g in stim.interval] _X = [x[1:minimum(size.(_X, Ti)), :] for x in _X] return _X end """ For flashes alignment, `trail=false` will return only the data from within the flash period. `trail=onset` will return the data from the onset of the flash to the onset of the flash through to the onset of the next flash. `trail=offset` will return the data from the offset of the flash to the onset of the next flash. """ function alignlfp(session, X, ::Val{:flashes}; trail = :offset) is = stimulusintervals(session, "flashes") if trail == :onset onsets = is.start_time is = [onsets[i] .. onsets[i + 1] for i in 1:(length(onsets) - 1)] elseif trail == :offset offsets = is.stop_time onsets = is.start_time[2:end] is = [offsets[i] .. onsets[i] for i in 1:(length(offsets) - 1)] else is = is.interval end X = TimeseriesTools.rectify(X; dims = 𝑡) _X = [X[𝑡(g)] for g in is] _X = [x[1:minimum(size.(_X, Ti)), :] for x in _X] # Catch any that are one sample too long return _X end function alignlfp(session, X, ::Val{:flash_250ms}; trail = :offset) is = stimulusintervals(session, "flash_250ms") if trail == :onset onsets = is.start_time is = [onsets[i] .. onsets[i + 1] for i in 1:(length(onsets) - 1)] elseif trail == :offset offsets = is.stop_time onsets = is.start_time[2:end] is = [offsets[i] .. onsets[i] for i in 1:(length(offsets) - 1)] else is = is.interval end X = TimeseriesTools.rectify(X; dims = 𝑡) _X = [X[𝑡(g)] for g in is] _X = [x[1:minimum(size.(_X, Ti)), :] for x in _X] # Catch any that are one sample too long return _X end # """ # For spontaneous alignment, we take each whole spontaneous interval as a trial # """ # function alignlfp(session, X, ::Val{:spontaneous}) # is =stimulusintervals(session, "spontaneous").interval # X = rectifytime(X) # _X = [X[𝑡(g)] for g in is] # return _X # end function alignlfp(session, X, stimulus::Union{String, Symbol} = "gabors"; kwargs...) alignlfp(session, X, stimulus |> Symbol |> Val; kwargs...) end """ Adjust the times of LFP matrix Y so that they match the matrix X """ function matchlfp(X, Y) _ts = Interval(X) ∩ Interval(Y) ts = dims(X, Ti) ts = ts[last(findfirst(ts .∈ (_ts,))):last(findlast(ts .∈ (_ts,)))] Y = Y[𝑡(Near(ts))] Y = DimensionalData.setdims(Y, ts) X = X[𝑡(_ts)] @assert dims(X, Ti) == dims(Y, Ti) return (X, Y) end function intersectlfp(X::AbstractVector) Y = [TimeseriesTools.rectify(x; dims = 𝑡, tol = 10) for x in X] ts = dims.(Y, Ti) ts = [Interval(extrema(t)...) for t in ts] int = reduce(intersect, ts) Y = [y[𝑡(int)] for y in Y] ts = dims.(Y, Ti) s = step.(ts) # @assert all(s .== s[1]) length = minimum(size.(Y, 1)) idxs = 1:length Y = cat([y[idxs, :] for y in Y]..., dims = 2) end function catlfp(X::AbstractVector) Y = [TimeseriesTools.rectify(x; dims = 𝑡, tol = 10) for x in X] ts = dims.(Y, Ti) s = step.(ts) @assert all([dims(Y[1], 2)] .== dims.(Y, (2,))) @assert all(s .≈ s[1]) s = s[1] Y = cat(Y..., dims = 𝑡) set(Y, Ti => 𝑡(s:s:(s * size(Y, 1)))) end
AllenNeuropixelsBase
https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl.git
[ "MIT" ]
0.3.0
215ea07f170cd9732aa7d7745c672f69baf3dc02
code
1275
export mouseconnectivitycache, getannotationvolume, getstructuremask, gettemplatevolume, getreferencespace function mouseconnectivitycache(; kwargs...) mcc = mouse_connectivity_cache.MouseConnectivityCache(; manifest_file = mouseconnectivitymanifest, kwargs...) end export MouseConnectivityCache function getannotationvolume(; resolution = 10, kwargs...) # vol, info = mouseconnectivitycache(; resolution, kwargs...).get_annotation_volume() rspc = referencespacecache(; resolution, kwargs...) vol, info = rspc.get_annotation_volume() return pyconvert(Array, vol), Dict(info) end function getstructuremask(structureid::Number) strucutreid = Int(structureid) mask, info = mouseconnectivitycache().get_structure_mask(structureid) return pyconvert(Array, mask), Dict(info) end function gettemplatevolume() template, template_info = mouseconnectivitycache().get_template_volume() return pyconvert(Array, template), Dict(template_info) end function getreferencespace() reference, reference_info = mouseconnectivitycache().get_reference_space() return pyconvert(Array, reference), Dict(reference_info) end
AllenNeuropixelsBase
https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl.git
[ "MIT" ]
0.3.0
215ea07f170cd9732aa7d7745c672f69baf3dc02
code
6288
using NWBStream export AbstractNWBSession, NWBSession, S3Session import DataFrames.groupby sessionfromnwb(S) = behavior_ecephys_session.BehaviorEcephysSession.from_nwb(S) abstract type AbstractNWBSession <: AbstractSession end struct NWBSession <: AbstractNWBSession file::Any end mutable struct S3Session <: AbstractNWBSession url::Any file::Any io::Any pyObject::Any function S3Session(url::String, file, io, pyObject = ()) S = new(url, file, io, pyObject) f(S::S3Session) = @async s3close(S.io) finalizer(f, S) end end initialize!(S::AbstractNWBSession) = (S.pyObject = sessionfromnwb(S.file); nothing) # Can take absolutely forever since dataframes suck S3Session(url::String) = (S = S3Session(url, s3open(url)...); initialize!(S); S) getid(S::AbstractNWBSession) = pyconvert(Int, getfile(S).identifier |> string |> Meta.parse) # getprobes(S::AbstractNWBSession) = Dict(getfile(S).ec_electrode_groups) # getprobeids(S::AbstractNWBSession) = Dict(first(s) => pyconvert(Int, last(s).probe_id) for s in getprobes(S)) # getprobefiles(S::AbstractNWBSession) = Dict(getfile(S).ec_electrode_groups) # getchannels() = manifest["project_metadata"]["channels.csv"] |> url2df function getfile(S::AbstractNWBSession) return S.file end function getlfpchannels(session::S3Session) f = getfile(session) channels = f["general"]["extracellular_ephys"]["electrodes"]["id"][:] close(f) return channels end # getprobes(S::AbstractNWBSession) = S.pyObject.get_probes_obj().to_dataframe() |> py2df function getsessionunits(session::AbstractNWBSession) units = session.pyObject.get_units() |> py2df end function py2df(p) df = p |> PyPandasDataFrame df = df |> DataFrame # if hasfield(p, :index) _index = p.index index = [pyconvert(Any, i) for i in _index] if string(p.index.name) == "None" df[!, "Index"] = index else df[!, pyconvert(Any, p.index.name)] = index end # Manual conversions for s in names(df) if eltype(df[:, s]) <: Union{Missing, AbstractArray{Bool, 0}} # && all(length.(df[:, s]) .< 2) df[!, s] = [ismissing(i) ? missing : pyconvert(Bool, i[1]) for i in df[:, s]] end if eltype(df[:, s]) <: PythonCall.PyArray df[!, s] = Array.(df[:, s]) end end # end return df[!, [end, (1:(size(df, 2) - 1))...]] end # getid(S::AbstractNWBSession) = pyconvert(Int, S.pyObject.behavior_ecephys_session_id) getprobes(S::AbstractNWBSession) = py2df(S.pyObject.probes) getchannels(S::AbstractNWBSession) = py2df(S.pyObject.get_channels()) Base.Dict(p::Py) = pyconvert(Dict, p) function Base.Dict(d::Dict{T, <:PythonCall.PyArray}) where {T} return Dict(k => pyconvert(Array{eltype(v)}, v) for (k, v) in d) end function getprobefile(session::AbstractNWBSession, name::AbstractString) files = getprobefiles(session) return files["probe_$(name)_lfp.nwb"] end function getprobefile(session::AbstractNWBSession, probeid::Int) getprobefile(session, first(subset(getprobes(session), :id => ByRow(==(probeid))).name)) end function getlfpchannels(session::AbstractNWBSession, probeid::Int) f = getprobefile(session, probeid) |> NWBStream.s3open |> first _lfp = Dict(f.acquisition)["probe_1108501239_lfp_data"] channelids = pyconvert(Vector{Int64}, _lfp.electrodes.to_dataframe().index.values) end function getlfptimes(session::AbstractNWBSession, probeid::Int) f = getprobefile(session, probeid) |> NWBStream.s3open |> first _lfp = Dict(f.acquisition)["probe_1108501239_lfp_data"] timedata = pyconvert(Vector{Float32}, _lfp.timestamps) end function getlfptimes(session::AbstractNWBSession, probeid::Int, idxs) d = diff(idxs) if all(d[1] .== d) idxs = @py slice(idxs[0] - 1, idxs[-1] - 1, d[1]) end f = getprobefile(session, probeid) |> NWBStream.s3open |> first _lfp = Dict(f.acquisition)["probe_1108501239_lfp_data"] timedata = _lfp.timestamps timedata = pyconvert(Vector{Float32}, timedata[idxs]) end function getlfptimes(session::AbstractNWBSession, probeid::Int, i::Interval) f = getprobefile(session, probeid) |> NWBStream.s3open |> first _lfp = Dict(f.acquisition)["probe_1108501239_lfp_data"] timedata = _lfp.timestamps # infer the timestep dt = mean(diff(pyconvert(Vector, timedata[0:1000]))) putativerange = pyconvert(Float64, timedata[0]):dt:pyconvert(Float64, timedata[-1] + dt) idxs = findall(putativerange .∈ (i,)) idxs = vcat(idxs[1] .- (100:-1:1), idxs, idxs[end] .+ (1:100)) idxs = idxs[idxs .> 0] idxs = idxs[idxs .< pyconvert(Int, timedata.len())] ts = getlfptimes(session::AbstractNWBSession, probeid::Int, idxs) ts = ts[ts .∈ (i,)] end function getepochs(S::AbstractNWBSession) df = S.pyObject.stimulus_presentations.groupby("stimulus_block").head(1) |> py2df df.stop_time = df.end_time return df end function _getlfp(session::AbstractNWBSession, probeid::Int; channelidxs = 1:length(getlfpchannels(session, probeid)), timeidxs = 1:length(getlfptimes(session, probeid))) @assert(any(getprobeids(session) .== probeid), "Probe $probeid does not belong to session $(getid(session))") _timeidxs = timeidxs .- 1 # Python sucks _channelidxs = channelidxs .- 1 # Python sucks f, io = getprobefile(session, probeid) |> NWBStream.s3open _lfp = Dict(f.acquisition)["probe_1108501239_lfp_data"] # timedata = getlfptimes(session, probeid) timedata = getlfptimes(session, probeid) timedata = timedata[timeidxs] channelids = getlfpchannels(session, probeid) channelids = channelids[channelidxs] lfp = zeros(Float32, length(timedata), length(channelids)) for (i, _channelidx) in enumerate(_channelidxs) d = diff(_timeidxs) # if all(d == d[1]) # We can do some efficient slicing # slc = @py slice(first(_timeidxs), last(_timeidxs), d[1]) # @time @py _lfp.data[slc] # else lfp[:, i] .= pyconvert(Vector{Float32}, _lfp.data[_timeidxs, _channelidx]) # end end if channelids isa Number channelids = [channelids] end X = ToolsArray(lfp, (𝑡(timedata), Chan(channelids))) return X end
AllenNeuropixelsBase
https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl.git
[ "MIT" ]
0.3.0
215ea07f170cd9732aa7d7745c672f69baf3dc02
code
118
export getstructuregraph function getstructuregraphs() ontologies_api.OntologiesApi().get_structure_graphs() end
AllenNeuropixelsBase
https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl.git
[ "MIT" ]
0.3.0
215ea07f170cd9732aa7d7745c672f69baf3dc02
code
3549
using Colors using GeometryBasics import FileIO: load export referencespacecache, getstructuretree, getstructurecolor, getstructurecolors, getstructuretreedepth, getstructurename, getstructuremesh, getstructureidmap function referencespacecache(reference_space_key = "annotation/ccf_2017"; resolution = 25, manifest = referencespacemanifest) reference_space_cache.ReferenceSpaceCache(resolution, reference_space_key, manifest = manifest) end function getstructuretree(space = referencespacecache(), id = 1) # Default id is mouse brain atlas id = Int(id) space.get_structure_tree(structure_graph_id = id) end function getstructurecolor(id::Union{Number, Missing}; tree = getstructuretree()) !ismissing(id) || return RGB(0.0, 0.0, 0.0) id = Int(id) d = tree.get_structures_by_id([id])[0] !isnothing(d) || return RGB(0.0, 0.0, 0.0) trip = pyconvert(Tuple, d["rgb_triplet"]) c = RGB((trip ./ 256)...) end function getstructurecolors(ids::AbstractVector) tree = getstructuretree() getstructurecolor.(ids; tree) end function getstructuretreedepth(id) # How many parents does this structure have (+1)? id = Int(id) tree = getstructuretree() d = tree.get_structures_by_id([id])[0] length(d["structure_id_path"]) end function getstructurename(id::Number) id = Int(id) tree = getstructuretree() d = tree.get_structures_by_id([id])[0] pyconvert(String, d["name"]) end function getstructurename(acronym::String) tree = getstructuretree() d = tree.get_structures_by_acronym([acronym])[0] pyconvert(String, d["name"]) end function getstructureid(acronym::String) tree = getstructuretree() d = tree.get_structures_by_acronym([acronym])[0] pyconvert(Int, d["id"]) end function getallstructureids(args...) t = getstructuretree(args...) d = t.get_name_map() ids = keys(d) end #! Can do the rest of this dict by eval? function buildreferencespace(tree = getstructuretree(), annotation = getannotationvolume(), resolution = (25, 25, 25)) if annotation isa Tuple annotation = annotation[1] end rsp = reference_space.ReferenceSpace(tree, annotation, resolution) end function buildstructuremask(id, referencespace = buildreferencespace()) referencespace.make_structure_mask([id]) end function getstructuremeshfile(id, r = referencespacecache()) filename = pyconvert(String, r.get_cache_path(nothing, r.STRUCTURE_MESH_KEY, r.reference_space_key, id)) r.api.download_structure_mesh(id, r.reference_space_key, filename, strategy = "lazy") return filename end function getstructureidmap() t = getstructuretree() D = t.get_id_acronym_map() |> Dict end function getstructuremesh(id, referencespace = referencespacecache(); hemisphere = :both) m = load(getstructuremeshfile(id, referencespace)) # Only take the right hemisphere, z > midpoint if hemisphere === :right idxs = findall(last.(m.position) .> median(last.(m.position))) elseif hemisphere == :left idxs = findall(last.(m.position) .< median(last.(m.position))) else idxs = 1:length(m.position) end fs = faces(m) checkf(f) = all([(_f.i |> Int) ∈ idxs for _f in f]) # filter out faces that arent in the chosen hemisphere fs = [f for f in fs if checkf(f)] m = GeometryBasics.Mesh(coordinates(m), fs) m end
AllenNeuropixelsBase
https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl.git
[ "MIT" ]
0.3.0
215ea07f170cd9732aa7d7745c672f69baf3dc02
code
2691
using SparseArrays using DimensionalData export AbstractSparseToolsArray, SparseToolsArray import DimensionalData: dims, refdims, data, name, metadata, parent, rebuild abstract type AbstractSparseToolsArray{T, N, D, A} <: AbstractToolsArray{T, N, D, A} end struct SparseToolsArray{T, N, D <: Tuple, R <: Tuple, A <: AbstractSparseArray{T, Int64, N}, Na, Me} <: AbstractSparseToolsArray{T, N, D, A} data::A dims::D refdims::R name::Na metadata::Me end function DimensionalData.format(dims, x::AbstractSparseToolsArray) DimensionalData.format(dims, axes(x)) end # DimensionalData.format(::Base.KeySet, ::Type, ::AbstractRange) = DimensionalData.format(DimensionalData.Dimensions.LookupArrays.Aligned, ::Type, ::AbstractRange) # format(val::AbstractSparseArray, D::Type, axis::AbstractRange) = format(AutoLookup(), D, val, axis) function SparseToolsArray(data::A, dims::D, refdims::R = (), name::Na = DimensionalData.NoName(), metadata = DimensionalData.NoMetadata()) where {D, R, A, Na} @info "Constructing a sparsedimarray properly" SparseToolsArray(data, DimensionalData.format(dims, axes(data)), refdims, name, metadata) end function goSparseToolsArray(data::A, dims::D, refdims::R = (), name::Na = DimensionalData.NoName(), metadata = DimensionalData.NoMetadata()) where {D, R, A, Na} @info "Constructing a sparsedimarray properly" SparseToolsArray(data, DimensionalData.format(dims, axes(data)), refdims, name, metadata) end # function FeatureArray(data::AbstractArray, features::Union{Tuple{Symbol}, Vector{Symbol}}, args...) # FeatureArray(data, (Dim{:feature}(features), fill(AnonDim(), ndims(data)-1)...), args...) # end # FeatureArray(D::ToolsArray) = FeatureArray(D.data, D.dims, D.refdims, D.name, D.metadata) # # DimensionalData.ToolsArray(D::FeatureArray) = ToolsArray(D.data, D.dims, D.refdims, D.name, D.metadata) dims(A::AbstractSparseToolsArray) = A.dims refdims(A::AbstractSparseToolsArray) = A.refdims data(A::AbstractSparseToolsArray) = A.data name(A::AbstractSparseToolsArray) = A.name metadata(A::AbstractSparseToolsArray) = A.metadata parent(A::AbstractSparseToolsArray) = data(A) Base.Array(A::AbstractSparseToolsArray) = parent(A) function DimensionalData.rebuild(A::AbstractSparseToolsArray, data::AbstractSparseArray, dims::Tuple, refdims::Tuple, name, metadata) SparseToolsArray(data, dims, refdims, name, metadata) end AbstractSparseDimVector = AbstractSparseToolsArray{T, 1, D, A} where {T, D, A}
AllenNeuropixelsBase
https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl.git
[ "MIT" ]
0.3.0
215ea07f170cd9732aa7d7745c672f69baf3dc02
code
13089
using SparseArrays using ProgressLogging using Random using IntervalSets import TimeseriesTools: spiketrain export downloadspikes, getspiketimes, getspikeamplitudes, formatspiketimes, spikematrix, getsessionpath, SpikeMatrix, spikematrix, alignspiketimes, countspikes, fanofactor, defaultfanobins, getspikes, getstructureacronyms, minspikediff, formatspikes, getisis, receptivefieldfilter, getmetric, getfano, getclosestchannels, getpeakchannels, getunitchannels, getspiketrains function downloadspikes(S::AbstractSession) _ = S.pyObject.spike_times _ = S.pyObject.spike_amplitudes return nothing end SpikeMatrix = SparseToolsArray{T, 2, Tuple{A, B}} where {T, A <: TimeseriesTools.TimeDim, B <: Unit} export SpikeMatrix function getsessionpath(session::AbstractSession) path = joinpath(datadir, "Ecephys", "session_" * string(getid(session)), "session_" * string(getid(session)) * ".nwb") end getspiketimes(S::AbstractSession) = S.pyObject.spike_times |> Dict getspiketimes(sessionid::Number, args...) = getspiketimes(Session(sessionid), args...) getspikeamplitudes(S::AbstractSession) = S.pyObject.spike_amplitudes |> Dict function getspikeamplitudes(sessionid::Number, args...) getspikeamplitudes(Session(sessionid), args...) end function getspiketimes(S::AbstractSession, structure::String) unitstructs = getunitmetrics(S) if hasproperty(unitstructs, :structure_acronym) structures = unitstructs.structure_acronym else structures = getstructureacronyms(S, unitstructs.ecephys_channel_id) end if hasproperty(unitstructs, :ecephys_unit_id) unitids = unitstructs[structures .== structure, :].ecephys_unit_id else unitids = unitstructs[structures .== structure, :].unit_id end spiketimes = filter(p -> p[1] in unitids, getspiketimes(S)) |> Dict end function getspiketimes(S::AbstractSession, unitids::Vector{Int}) spiketimes = getspiketimes(S) Dict(a => b for (a, b) in spiketimes if a in unitids) end function getspiketrains(args...; kwargs...) sp = getspiketimes(args...; kwargs...) sp = Dict(k => spiketrain(v; metadata = Dict(:unit_id => k)) for (k, v) in sp) end function formatspiketimes(; sessionid = 757216464, structure = "VISp", stimulus = "gabors", epoch = :longest, filter = true, kwargs...) S = Session(sessionid) spiketimes = getspiketimes(S, structure) Is = stimulusepochs(S, stimulus).interval if epoch === :longest _, epoch = findmax(IntervalSets.width, Is) end I = Is[epoch] ks = keys(spiketimes) vals = values(spiketimes) vals = [v[in.(v, (I,))] for v in vals] if filter metrics = getunitanalysismetrics(S) Sp = Dict(k => v for (k, v) in zip(ks, vals) if k ∈ metrics.ecephys_unit_id) else Sp = Dict(k => v for (k, v) in zip(ks, vals)) end end """ Construct a sparse array of spike counts from a Dict of spike times """ function spikematrix(Sp::AbstractDict, bin = 1e-4; rectify = 4) tmin, tmax = extrema(vcat(values(Sp)...)) units = Sp |> keys |> collect if rectify > 0 tmax = round(tmax; digits = rectify) tmin = round(tmin; digits = rectify) end ts = tmin:bin:tmax spikes = spzeros(Float32, length(ts), length(units)) spikes = goSparseToolsArray(spikes, (𝑡(ts), Unit(units))) @withprogress name="spikearray" begin for u in eachindex(units) _times = Sp[units[u]] for t in eachindex(_times) # Hella slow spikes[𝑡(Near(_times[t])), Unit(At(units[u]))] += 1 end @logprogress u / length(units) end end return spikes end # `count` is a boolean indicating whether to return the number of spikes in each bin, or sum the amplitudes function _getspikes(units, times, amplitudes, _times, bin, rectify, count) tmax = maximum(_times) tmin = minimum(_times) times = [filter(∈(tmin .. tmax), t) for t in times] if rectify > 0 tmax = round(tmax; digits = rectify) tmin = round(tmin; digits = rectify) end ts = tmin:bin:tmax spikes = spzeros(Float32, length(ts), length(units)) spikes = goSparseToolsArray(spikes, (𝑡(ts), Unit(units))) # SparseToolsArray? @withprogress name="spikearray" begin for u in eachindex(units) _times = times[u] _amplitudes = amplitudes[u] for t in eachindex(_times) # Hella slow spikes[𝑡(Near(_times[t])), Unit(At(units[u]))] += (count ? 1 : _amplitudes[t]) end @logprogress u / length(units) end end return spikes end """ We combine the spike times and spike amplitudes into one sparse array, using a given bin width. """ function getspikes(S, timebounds = nothing; bin = 1e-4, rectify = 4, structure = nothing, count = true) times = isnothing(structure) ? getspiketimes(S) : getspiketimes(S, structure) validunits = findvalidunits(S, keys(times)) times = Dict(k => v for (k, v) in times if k ∈ validunits) units = times |> keys |> collect times = times |> values |> collect amplitudes = S |> getspikeamplitudes amplitudes = getindex.((amplitudes,), units) @assert all(length.(times) .== length.(amplitudes)) # Set up the sparse dim array, then allocate spikes to the nearest time index _times = isnothing(times) ? vcat(_times...) : timebounds _getspikes(units, times, amplitudes, _times, bin, rectify, count) end function getspikes(S, stimulus::String; n = 1, kwargs...) timebounds = getstimulustimes(S, stimulus)[n] getspikes(S, timebounds; kwargs...) end function getspikes(S, stimulus::String, structure::String; kwargs...) spikes = getspikes(S, stimulus; kwargs...) structures = getstructureacronyms(S, dims(spikes, Unit)) spikes = spikes[:, findall(structures .== structure)] end """ A function to easily grab formatted spike data for a given session, using some sensible default parameters """ function formatspikes(; sessionid = 757216464, stimulus = "gabors", structure = "VISp", epoch = 1, bin = 1e-4, kwargs...) sesh = Session(sessionid) S = getspikes(sesh, stimulus, structure; bin, rectify = 4, structure, count = true, epoch) end function getunitstructureacronyms(session::AbstractSession, units) unittable = getunitmetrics(session) acronyms = Vector{Any}(undef, size(units)) [acronyms[i] = notemptyfirst(unittable[unittable.unit_id .== units[i], :structure_acronym]) for i in 1:length(units)] return acronyms end function minspikediff(S::AbstractSession) diffs = S |> getspiketimes |> values .|> diff return minimum(minimum.(diffs)) # Just greater than 1e-4 end # function clusterunits(spikes; dist=CosineDist()) # D = pairwise(dist, spikes|>Array, dims=2) # h = hclust(D) # end # function getreceptivefield(session, unit) # rf = stimulusmapping.ReceptiveFieldMapping(session.pyObject) # field = rf.get_receptive_field(unit) # end function getisis(x::AbstractSparseDimVector) s = findnz(x |> SparseVector)[1] t = dims(x, Ti) |> collect I = AN.ephys_features.get_isis(t, s) @assert I ≈ diff(t[s]) # Yeah there's this return I end function getisis(S::AbstractSession) ts = getspiketimes(S) isis = Dict(a => diff(b) for (a, b) in ts) end function getisis(S::AbstractSession, units) isis = getisis(S) isis = Dict(a => diff(b) for (a, b) in isis if a in units) end # function detectbursts(isis::AbstractVector) # AN.ephys_features.detect_bursts(isis, isi_types, fast_tr_v, fast_tr_t, slow_tr_v, slow_tr_t, thr_v, tol=0.5, pause_cost=1.0) # end import DataFrames.subset function subset(d::DataFrame, col, vals::AbstractVector) idxs = indexin(vals, d[:, col]) return d[idxs, :] end subset(d::DataFrame, col, vals::Base.KeySet) = subset(d, col, collect(vals)) subset(d::DataFrame, col, vals::Dim) = subset(d, col, collect(vals)) subset(d::DataFrame, col, vals::DataFrame) = subset(d, col, vals[:, col]) function subset(d::DataFrame, col, val) idxs = findall(d[:, col] .== val) return d[idxs, :] end export subset # function receptivefieldcentrality(unit; centre=(0, 0), metrics=AN.getunitanalysismetricsbysessiontype("brain_observatory_1.1")) # # rf = AN.getreceptivefield(session, unit) # end function receptivefieldfilter(am::DataFrame) am = am[[ismissing(𝑝) || 𝑝 < 0.01 for 𝑝 in am.p_value_rf], :] return am.unit_ids end function receptivefieldfilter(units::AbstractVector; am = AN.getunitanalysismetricsbysessiontype("brain_observatory_1.1")) am = AN.subset(am, :ecephys_unit_id, units) return receptivefieldfilter(am) end function alignspiketimes(session, X, ::Val{:flashes}; x_position = nothing, y_position = nothing) stims = stimulusintervals(session, "flashes") intervals = stims.interval times = values(X) units = keys(X) _times = [] for ts in times _ts = [] for i in intervals push!(_ts, ts[ts .∈ (i,)]) end push!(_times, _ts) end return Dict(units .=> _times) end function alignspiketimes(session, X, stimulus = "flashes"; kwargs...) alignspiketimes(session, X, stimulus |> Symbol |> Val; kwargs...) end function countspikes(ts::AbstractVector, T::Real) # ts should be sorted ts = deepcopy(ts) m = maximum(ts) _t = minimum(ts) x = zeros(floor(Int, (m - _t) / T)) for i in eachindex(x) idxs = (ts .≥ (_t + (i - 1) * T)) .& (ts .< (_t + i * T,)) x[i] = length(splice!(ts, findall(idxs))) # * Make x shorter so future searches are quicker end return x end function fanofactor(ts::AbstractVector, T::Real) # * Calculate the fano factor using non-overlapping windows ts = sort(ts) x = countspikes(ts, T) return var(x) / mean(x) end function defaultfanobins(ts) maxwidth = (first ∘ diff ∘ collect ∘ extrema)(ts) / 10 minwidth = max((mean ∘ diff)(ts), maxwidth / 10000) # spacing = minwidth return 10.0 .^ range(log10(minwidth), log10(maxwidth); length = 100) end function fanofactor(ts::AbstractVector, T::AbstractVector = defaultfanobins(ts)) (T, fanofactor.((ts,), T)) end function metricmap(stimulus) if stimulus == "flashes" return :fl elseif stimulus == "drifting_gratings" return :dg elseif stimulus == "natural_scenes" return :ns elseif stimulus == "gabors" return :rf elseif stimulus == "static_gratings" return :sg elseif isnothing(stimulus) return nothing end end function getmetric(metrics::DataFrame, metric, stimulus) sesh = metricmap(stimulus) if isnothing(sesh) return metrics[:, Symbol(metric)] else return metrics[:, Symbol(reduce(*, string.([metric, :_, sesh])))] end end function getfano(metrics::DataFrame, stimulus) sesh = metricmap(stimulus) return metrics[:, Symbol(reduce(*, string.([:fano_, sesh])))] end function findvalidunits(session, units; kwargs...) units = collect(units) metrics = getunitanalysismetrics(session; filter_by_validity = true, kwargs...) check = units .∈ (metrics.ecephys_unit_id,) return units[check] end function findvalidunits(session, spikes::Dict) units = findvalidunits(session, keys(spikes)) return Dict(units .=> getindex.((spikes,), units)) end function getclosestchannels(session, probeid, units, channels) channels = collect(channels) cdepths = getchanneldepths(session, probeid, channels) udepths = getunitdepths(session, probeid, units) dists = [abs.(cdepths .- u) for u in udepths] idxs = last.(findmin.(dists)) channels = channels[idxs] Dict(units .=> channels) end function getclosestchannels(sessionid::Int, args...) getclosestchannels(Session(sessionid), args...) end function getpeakchannels(session, units) metrics = getunitmetrics(session) k = hasproperty(metrics, :unit_id) ? :unit_id : :ecephys_unit_id check = all(units .∈ (getproperty(metrics, k),)) if !check @error "Some units do not have corresponding metrics" end metrics = subset(metrics, k, units) channels = Dict(zip(units, metrics.peak_channel_id)) end getpeakchannels(sessionid::Int, args...) = getpeakchannels(Session(sessionid), args...) function getunitchannels(session, units) metrics = getunitanalysismetrics(session) check = all(units .∈ (metrics.ecephys_unit_id,)) if !check @error "Some units do not have corresponding metrics" end metrics = subset(metrics, :ecephys_unit_id, units) channels = Dict(zip(metrics.ecephys_channel_id)) end getunitchannels(sessionid::Int, args...) = getunitchannels(Session(sessionid), args...)
AllenNeuropixelsBase
https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl.git
[ "MIT" ]
0.3.0
215ea07f170cd9732aa7d7745c672f69baf3dc02
code
15503
function getchangetrials end function getchangetrialtimeseries end export getchangetrials, getchangetrialtimeseries, stimulustimeseries module VisualBehavior # using ..AllenNeuropixelsBase import ..AllenNeuropixelsBase as ANB using PythonCall using NWBStream using DataFrames using Downloads using JSON using HDF5 using IntervalSets using TimeseriesTools import NWBStream.url2df import ..AllenNeuropixelsBase: AbstractNWBSession, AbstractSession, py2df import DataFrames.groupby const visualbehavior = "https://visual-behavior-neuropixels-data.s3.us-west-2.amazonaws.com/" const visualbehaviorbehavior = visualbehavior * "visual-behavior-neuropixels/" """ getmanifesturl(manifest_version="0.5.0") Return the URL for the neuropixels visual behavior project manifest file hosted on a given `hostname` server and version `manifest_version`. ## Arguments - `manifest_version::String`: The version of the manifest file. Default value is `"0.5.0"`. Other manifest version numbers can be identified here: https://s3.console.aws.amazon.com/s3/buckets/visual-behavior-neuropixels-data?prefix=visual-behavior-neuropixels%2Fmanifests%2F&region=us-west-2 """ function getmanifesturl(manifest_version = "0.5.0") object_key = "manifests/visual-behavior-neuropixels_project_manifest_v$manifest_version.json" return visualbehaviorbehavior * object_key end function getmanifest(args...) hostname = getmanifesturl(args...) data = String(take!(Downloads.download(hostname, IOBuffer()))) JSON.parse(data) end """ filetree(paths::Vector{String}) Creates a dictionary-like object representing the directory and file structure from a list of file paths. ## Arguments: * paths: A vector of file paths to include in the tree. ## Returns: * dict_tree : A dictionary-like object representing the directory and file structure. """ function filetree(paths::Vector{String}) dict_tree = Dict{String, Any}() for path in paths current_dict = dict_tree components = splitpath(path) for component in components[1:(end - 1)] if !haskey(current_dict, component) current_dict[component] = Dict{String, Any}() end current_dict = current_dict[component] end current_dict[components[end]] = path end return dict_tree end """ datapaths() Get the paths to the visual behavior neuropixels data on Amazon S3 as a tree-like dictionary. """ function datapaths() data = getmanifest() ks = merge([data[k] for k in keys(data) if data[k] isa Dict]...) ks = getindex.([ks[k] isa Dict ? ks[k] : Dict(k => ks[k]) for k in keys(ks)], ["url"]) tree = filetree(String.(ks)) return tree["https:"]["visual-behavior-neuropixels-data.s3.us-west-2.amazonaws.com"]["visual-behavior-neuropixels"] end const manifest = datapaths() struct Session <: AbstractSession pyObject::Any behavior_pyObject::Any function Session(pyObject) behavior_pyObject = ANB.behaviorcache().get_behavior_session(pyObject.behavior_session_id) new(pyObject, behavior_pyObject) end end function Session(session_id::Int; kwargs...) @debug "Constructing a session from id $session_id" ANB.getsessiondata(session_id; kwargs...) |> Session end Session(; params...) = Session(params[:sessionid]) getprobes() = manifest["project_metadata"]["probes.csv"] |> url2df getchannels() = manifest["project_metadata"]["channels.csv"] |> url2df ANB.getid(S::Session) = pyconvert(Int, S.pyObject.metadata["ecephys_session_id"]) getbehaviorid(S::Session) = pyconvert(Int, S.pyObject.behavior_session_id) function ANB.getchannels(S::Session, args...; kwargs...) df = py2df(S.pyObject.get_channels()) ANB.getchannels(df, args...; kwargs...) end const sources = Dict(:Allen_neuropixels_visual_behavior => "https://visual-behavior-neuropixels-data.s3.us-west-2.amazonaws.com") function ANB.getlfppath(session::Session, probeid) probe = ANB.getprobeobj(session, probeid) @assert pyconvert(Int, probe.id) == probeid name = probe.name try path = pyconvert(String, probe._lfp_meta.lfp_csd_filepath()._str) catch # Probe has no file name for some reason. Make a hacky guess @warn "Malformed probe object. Guessing path" path = joinpath(ANB.behaviormanifest, "visual-behavior-neuropixels-0.5.0", "behavior_ecephys_sessions", string(pyconvert(Int, session.pyObject.metadata["ecephys_session_id"])), "probe_$(name)_lfp.nwb") end end function ANB.isinvalidtime(session::Session, probeids = getprobeids(session), times = NaN) # paths = ANB.getlfppath.((session,), probeids) # for path in paths # f = h5open(path) # end false # no invalid times for VBN as far as I can see end function ANB.getlfptimes(session::Session, probeid) path = ANB.getlfppath(session, probeid) if !isfile(path) @error "Probe lfp data file does not exist. This may be becuase you have not downloaded the probe data. Try using `getlfp`" end f = h5open(path) stem = ANB.resolvenwblfp(session, probeid) times = f["acquisition"][stem][stem * "_data"]["timestamps"][:] close(f) return times end function ANB.getperformancemetrics(session::Session) pyconvert(Dict, session.behavior_pyObject.get_performance_metrics()) end function S3Session(session_id::Int, args...; kwargs...) ANB.S3Session(getsessionfile(session_id), args...; kwargs...) end """ getsessionfiles() Return a dictionary mapping session IDs to their corresponding file paths. """ function getsessionfiles() files = manifest["behavior_ecephys_sessions"] sessionids = keys(files) D = Dict() for s in sessionids subfiles = files[s] subfile = findfirst(subfiles) do f occursin("ecephys_session_$s", f) end push!(D, s => subfiles[subfile]) end return D end getsessionfile(session_id::Int, args...) = getsessionfiles(args...)["$session_id"] function getsessiontable() st = manifest["project_metadata"]["ecephys_sessions.csv"] |> url2df st.structure_acronyms = [replace.(split(a, ','), r"[\[\]\'\s]" => "") for a in st.structure_acronyms] st.ecephys_structure_acronyms = st.structure_acronyms return st end function getbehaviorsessiontable() st = manifest["project_metadata"]["behavior_sessions.csv"] |> url2df return st end getunits() = manifest["project_metadata"]["units.csv"] |> url2df function getunitanalysismetricsbysessiontype() session_table = ANB.VisualBehavior.getsessiontable() units = getunits() sessionmetrics = innerjoin(session_table, metrics, on = :ecephys_session_id) end function getprobes(session::AbstractNWBSession) probes = VisualBehavior.getprobes() return subset(probes, :ecephys_session_id => ByRow(==(ANB.getid(session)))) end function getprobefiles() files = manifest["behavior_ecephys_sessions"] sessionids = keys(files) D = deepcopy(files) for s in sessionids subfiles = D[s] subfile = findfirst(subfiles) do f occursin("ecephys_session_$s", f) end delete!(subfiles, subfile) end return D end getprobefiles(S::AbstractNWBSession) = getprobefiles()[string(ANB.getid(S))] function getprobefile(session::AbstractNWBSession, name::AbstractString) files = getprobefiles(session) return files["probe_$(name)_lfp.nwb"] end function getprobefile(session::AbstractNWBSession, probeid::Int) getprobefile(session, first(subset(getprobes(session), :ecephys_probe_id => ByRow(==(probeid))).name)) end function ANB.getepochs(S::Session) df = S.pyObject.stimulus_presentations |> py2df df.interval = [a .. b for (a, b) in zip(df.start_time, df.end_time)] df = groupby(df, :stimulus_block) _intersect(x) = minimum(minimum.(x)) .. maximum(maximum.(x)) df = DataFrames.combine(df, :interval => _intersect => :interval, :active => unique => :active, :stimulus_block => unique => :stimulus_block, :stimulus_name => unique => :stimulus_name) df.start_time = minimum.(df.interval) df.end_time = maximum.(df.interval) df.duration = df.end_time - df.start_time df.stop_time = df.end_time return df end # * The goal is now to copy all of the convenience functions in AllenAttention.jl to here... # Will just need to overload getlfp and getspikes, since we can use the allensdk to get all the session metadata and such. # Will need VisualBehaviorNeuropixelsProjectCache # from allensdk.brain_observatory.behavior.behavior_project_cache import VisualBehaviorNeuropixelsProjectCache # See from allensdk.brain_observatory.behavior.behavior_project_cache import VisualBehaviorNeuropixelsProjectCache # All the api above should go into allen neuropixels. This here is a small package. # Session(sessionid::Int) = sessionid |> getsessionfile |> ANB.Session # function getlfp(session::S3Session, probeid::Int; channels=getlfpchannels(session, probeid), times=ClosedInterval(extrema(getlfptimes(session, probeid))...), inbrain=false) # end # VisualBehaviorNeuropixelsProjectCache = ANB.behavior_project_cache.behavior_neuropixels_project_cache.VisualBehaviorNeuropixelsProjectCache # VisualBehaviorNeuropixelsProjectCache.from_s3_cache(mktempdir()) function ANB.getchannels(S::Session) s = py2df(S.pyObject.get_channels()) end function getunitanalysismetrics(; filter_by_validity = nothing) # Extra kwarg for Visual Coding compat session_table = ANB.VisualBehavior.getsessiontable() metrics = ANB.behaviorcache().get_unit_table() |> py2df metrics = outerjoin(metrics, session_table; on = :ecephys_session_id) end function ANB.getunitanalysismetrics(session::Session; kwargs...) ANB.getunitmetrics(session; kwargs...) end function ANB.getunitmetrics(session::Session; filter_by_validity = false) if filter_by_validity @warn "Filtering by validity is not implemented for visual behavior neuropixels data" end str = session.pyObject.get_units() df = py2df(str) df.ecephys_unit_id = df.id df.ecephys_channel_id = df.peak_channel_id df end function ANB.getprobeobj(S::Session, probeid) probes = S.pyObject.get_probes_obj() probeids = [pyconvert(Int, probe.id) for probe in probes.probes] i = findfirst(probeids .== probeid) if isempty(i) @error "Probe id $probeid not found in session $(getid(S))" end thisprobe = i - 1 probe = probes.probes[thisprobe] end ## Behavior metrics import AllenNeuropixelsBase: gettrials, getlicks, getrewards, geteyetracking, getrunningspeed, getbehavior, getchangetrials, getchangetrialtimeseries function gettrials(S::Session) df = S.pyObject.trials |> py2df df.interval = [a .. b for (a, b) in zip(df.start_time, df.stop_time)] return df end getlicks(S::Session) = S.pyObject.licks |> py2df getrewards(S::Session) = S.pyObject.rewards |> py2df geteyetracking(S::Session) = S.pyObject.eye_tracking |> py2df _getrunningspeed(S::Session) = S.pyObject.running_speed |> py2df function _getbehavior(S::Session) fs = (gettrials, getlicks, getrewards, geteyetracking, getrunningspeed) dfs = [f(S) for f in fs] end function stimulustimeseries(session; blanks = true) df = ANB.getstimuli(session) x = TimeseriesTools.TimeSeries(df.start_time, df.image_name) y = TimeseriesTools.TimeSeries(df.end_time, df.image_name) if blanks xx = TimeseriesTools.TimeSeries(times(x) .- 1 / 1250, fill("blank", length(x))) yy = TimeseriesTools.TimeSeries(times(y) .+ 1 / 1250, fill("blank", length(y))) x = TimeseriesTools.interlace(x, xx) y = TimeseriesTools.interlace(y, yy) end TimeseriesTools.interlace(x, y) end function getchangetrials(session) df = gettrials(session) df = df[df.is_change, :] # Get corrected change time by matching stimulus frame with start time in stimulus table stimuli = ANB.getstimuli(session) stimuli.change_frame = stimuli.start_frame stimuli = innerjoin(df, stimuli, on = :change_frame, makeunique = true) df.change_time_with_display_delay = stimuli.start_time_1 # Get response (lick) latency df.lick_latency = df.response_time - df.change_time_with_display_delay # ? Do we want to use the precise lick times from the licks dataframe? return df end function getchangetrialtimeseries(session) # Make an irregular time series of when the change trials occur trials = getchangetrials(session) t = trials.change_time_with_display_delay vars = [:go, :catch, :hit, :miss, :aborted, :false_alarm, :correct_reject, :lick_latency, :auto_rewarded, :initial_image_name, :change_image_name] X = hcat([trials[:, s] for s in vars]...) return TimeSeries(t, vars, X) end flashesset = (Val{:Natural_Images_Lum_Matched_set_ophys_G_2019}, Val{:Natural_Images_Lum_Matched_set_ophys_H_2019}) function ANB.alignlfp(session, X, stimulus::Union{flashesset...}; trail = :change, trials = nothing, conditions = nothing, nonconditions = nothing, zero = false) stimulus = string(typeof(stimulus).parameters[1]) flash = 0.250 # s see visual behavior white paper iti = 0.500 # s is = ANB.stimulusintervals(session, stimulus) if trail === :change # In this case the X should only be from around change trials is = getchangetrials(session) # idxs = indexin(stimuli.trials_id, ANB.getstimuli(session, stimulus).trials_id) # stimuli = stimuli[idxs, :] end if !isnothing(trials) is = is[is.trials_id .∈ (trials.trials_id,), :] end if !isnothing(conditions) for c in conditions is = is[is[:, c] .== true, :] end end if !isnothing(nonconditions) for c in nonconditions is = is[is[:, c] .== false, :] end end if trail == :onset # The programmed change time onsets = is.start_time is = [onsets[i] .. min(onsets[i + 1], onsets[i] + flash + iti) for i in 1:(length(onsets) - 1)] elseif trail == :offset # The programmed off time offsets = is.stop_time onsets = is.start_time[2:end] is = [offsets[i] .. min(offsets[i + 1], offsets[i] + iti) for i in 1:(length(offsets) - 1)] elseif trail == :change # The true change time, including display delay onsets = is.change_time_with_display_delay onsets = [onsets; Inf] is = [onsets[i] .. min(onsets[i + 1], onsets[i] + flash + iti) for i in 1:(length(onsets) - 1)] else is = is.interval end X = ANB.rectifytime(X) _X = [X[𝑡(g)] for g in is] _X = _X[.!isempty.(_X)] _X = [x for x in _X if size(x, Ti) > 100] # Remove short trials _X = [x[1:minimum(size.(_X, Ti)), :] for x in _X] # Catch any that are one sample too long _X = ANB.rectifytime.(_X; zero) @assert all(all(size.(x, 1) .== size(x[1], 1)) for x in _X) return _X end end export VisualBehavior getprobefiles(S::AbstractNWBSession; dataset = VisualBehavior) = dataset.getprobefiles(S)
AllenNeuropixelsBase
https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl.git
[ "MIT" ]
0.3.0
215ea07f170cd9732aa7d7745c672f69baf3dc02
code
13733
### A Pluto.jl notebook ### # v0.19.22 using Markdown using InteractiveUtils # ╔═╡ 98c9bbd2-aac5-4c90-ac0c-d8d935f5cdaf # For WGLMakie begin using Pkg Pkg.add("JSServe") using JSServe Page() end # ╔═╡ c445ccf4-cf10-43b9-9c01-4051abc400ba begin Pkg.activate("../") # Pkg.add(url="https://github.com/brendanjohnharris/NWBStream.jl#main") # Pkg.add(url="https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl#main") # # Pkg.add("WGLMakie") # Pkg.add("DataFrames") # Pkg.add("Statistics") # Pkg.add("FileIO") end # ╔═╡ 79b92c17-cc5f-4ca2-8b08-f6015729a9a9 using DataFrames # ╔═╡ 1a3eaeb7-db19-4bc3-b61a-84dd9caad009 using Statistics # ╔═╡ c1397e8e-3ac2-4f49-8d88-cc1400a3b93e using FileIO # ╔═╡ 0a622047-c238-49c3-bdf0-3248d0f0d261 # Just for me # begin # using Revise # cd("../../") # Pkg.activate() # Pkg.develop(path="./AllenNeuropixelsBase") # cd("./AllenNeuropixelsBase") # Pkg.activate("./") # end # ╔═╡ 766a8af5-4c89-4fe7-883d-d960ef91edfd md""" # Allen Neuropixels Visual Behavior _Accessing the Allen Neuropixels visual behavior dataset in Julia_ """ # ╔═╡ bea5de79-6e8a-42d8-ab76-bae8e3c23747 md""" ## Background Details on neuropixels and the visual coding dataset can be found in the Allen SDK [docs](https://allensdk.readthedocs.io/en/latest/visual_behavior_neuropixels.html) or the [white-paper](https://brainmapportal-live-4cc80a57cd6e400d854-f7fdcae.divio-media.net/filer_public/f7/06/f706855a-a3a1-4a3a-a6b0-3502ad64680f/visualbehaviorneuropixels_technicalwhitepaper.pdf). """ # ╔═╡ f9ac9f6e-f129-4542-81a8-36e6cef9857a md"## Required packages" # ╔═╡ c48bd78e-aab0-49c0-b137-567c208b8aa1 md""" Interfacing with the Python [Allen SDK](https://github.com/AllenInstitute/AllenSDK) is handled by the [AllenNeuropixelsBase](https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl) package. We will use the WGLMakie for plots, as well as DataFrames and Statistics for working with tables. """ # ╔═╡ d8fd4541-08a5-4ace-a998-769771c976e8 import AllenNeuropixelsBase as ANB # ╔═╡ 2e3d037c-932d-4d5a-afdb-351e836bdfb2 # using WGLMakie # ╔═╡ 5bfaefae-11a5-4567-8b83-d583f03a75a8 md""" ## Choosing a session The Allen neuropixels visual coding dataset is subdivided into sessions. A session contains data from one murine subject across a recording interval during which it was shown a variety of visual stimuli (such as natural scenes, drift gratings and gabors). These data include local field potentials (LFP) and spike times from each of the 374 data channels on, usually, six neuropixels probes inserted around the visual cortex. The LFP data is also downsampled by a half in time and a quarter over channels. The entire neuropixels visual coding dataset contains dozens of sessions and is hundreds of megabytes in size, so we will first choose one session (a few gigabytes of data) instead of performing group-level analyses. To produce a dataframe of session details: """ # ╔═╡ 754f94e0-ccb2-4dc0-a534-ae94dd02bc02 session_table = ANB.VisualBehavior.getsessiontable() # ╔═╡ a2f81f74-36ed-42d4-89d5-828327c67318 md"""We'll pick a session that has six probes:""" # ╔═╡ efd3ef52-4acb-4ffd-b794-1dfc4d9819c8 function numprobes(sessionid) session_table[session_table[!, :ecephys_session_id].==sessionid, :probe_count][1] end # ╔═╡ e30e349c-6ad7-402b-90d1-7720b85a9c2c md"And look for sessions that have probes intersecting the target regions listed in the white paper:" # ╔═╡ d2d20884-0fcd-4ac7-8a14-dbf936445c3b function targetintersections(sessionid) s = session_table[session_table.ecephys_session_id.==sessionid, :structure_acronyms][1] targets = ["VISp", "VISl", "VISrl", "VISal", "VISpm", "VISam", "CA1", "CA3", "DG", "SUB", "ProS", "LGd", "LP", "APN"] structures = eachmatch(r"'(.*?)'", s) structures = [replace(x.match, r"'" => s"") for x ∈ structures] targetsintersected = [x ∈ structures for x ∈ targets] return mean(targetsintersected) end; # ╔═╡ 99fe41d6-661d-4b9f-a853-2f32ace53d72 # md""" # We can filter down sessions in a few more ways. Firstly, the visaul coding data is divided into two stimulus sets. To summuraise the white paper: # - The **Brain Observatory 1.1** stimulus set: # - Gabor patches appearing randomly on a 9 x 9 grid # - Dark or light flashes # - Drift gratings in 8 directions and 5 temporal frequencies, with 15 repeats per condition # - Static gratings at 6 orientations, 5 spatial frequencies, and 4 phases # - 118 natural images # - Two natural movies from Touch of Evil; a 30 second clips repeated 20 times and a 120 second clip repeated 10 times # - The **Functional Connectivity** stimulus set: # - Gabor patches # - Dark or light flashes # - Drift gratings in 4 directions and one temporal frequency with 75-80 repeats # - Drift gratings in 4 directions and 9 contrasts # - One natural movie shown 60 times plus 20 repeats of a temporally shuffled version # - A dot motion stimulus of approximately 200 white dots on a gray background moving at one of 7 speeds in four different directions # In summary, the Brain Observatory dataset contains a greater variety of stimuli but a smaller number of repeats than the Functional Connectivity dataset. **We'll look at sessions in the Brain Observatory dataset.** # """ # ╔═╡ 82ce6d0f-b60b-41f2-bdce-c6ecf545bf65 md""" Next, we can inspect the unit quality metrics of each session. Three metric criteria have recommended values: - `amplitude_cutoff_maximum = 0.1`: Limits the approximate false negative rate in spike detection, calculated by assuming the distribution of amplitudes is symmetric. - `presence_ratio_minimum = 0.9`: Ensures proportion of 100 recording sub-intervals that have at least one spike detection is above 90% (i.e. the unit has not drifted and the sorting algorithm is correctly identifying spikes). - `isi_violations_maximum = 0.5`: Limits the number of units that record from multiple neurons. Inter-spike interval (ISI) violations are detections of spikes that occur during the typical refractory period of a single neuron, so are likely to originate from a second neuron. To access a dataframe of metrics: """ # ╔═╡ 5d47cb91-d8c7-41df-9778-c9a77266ba93 # This can take a while metrics = ANB.VisualBehavior.getunits() # ╔═╡ c62a118e-713e-424f-9420-f310131c7018 sessionmetrics = innerjoin(session_table, metrics, on=:ecephys_session_id) # ╔═╡ d3064ff9-798f-4469-9ac5-43b94c9e9a92 setindex!.([sessionmetrics], missing, findall(Matrix(sessionmetrics .== ""))) # ╔═╡ 7d00cd72-a2c0-45a9-b777-b347286f7390 md"Some session-level metrics are:" # ╔═╡ fd03139c-4bd1-4f26-a8c3-46c3feefd9c5 session_metrics = combine(groupby(sessionmetrics, :ecephys_session_id), :ecephys_session_id => numprobes ∘ unique => :num_probes, :ecephys_session_id => targetintersections ∘ unique => :target_intersections, :genotype => (x -> all(isequal.(x, ("wt/wt",)))) => :is_wt, :max_drift => median ∘ skipmissing, :d_prime => median ∘ skipmissing, :isolation_distance => median ∘ skipmissing, :silhouette_score => median ∘ skipmissing, :snr => median ∘ skipmissing) # ╔═╡ 51eccd32-d4e9-4330-99f5-fca0f8534e43 md""" Of particular importance are the first five columns. The ideal session will have 6 probes, LFP data for all units and for now we wish to choose a wild type mouse. It should also contain data for probes that intersect with the major regions of interest highlighted in the white paper. The maximum drift, which measures mean (and possibly variance) nonstationarity unrelated to the visual stimulus (such as probe motion relative to the brain) should also be minimised. We can also look for probes that intersect all of the target regions, given in the white paper as the visual areas, the hippocampal formation, the thalamus and the midbrain: """ # ╔═╡ 927605f4-0b59-4871-a13f-420aadedd487 oursession = subset(session_metrics, :target_intersections => ByRow(>(0.85)), :is_wt => ByRow(==(true)), :max_drift_median_skipmissing => ByRow(<(99))) # ╔═╡ 5973ddbe-f839-44d8-af08-46b1813e8750 sort!(oursession, :max_drift_median_skipmissing) # ╔═╡ 395a90c4-fe98-49bc-9883-d4278cd38bae session_id = oursession[1, :].ecephys_session_id # ╔═╡ 23d8fad0-5c51-4056-8df3-fd850db7b560 md""" For a smaller quantity of data we can also pick just one probe from this session: `probeC: 769322749` intersects a few interesting regions, like the primary visual cortex, the hippocampus and the thalamus. """ # ╔═╡ 99e2e888-c1cf-4370-b1b4-eccc6cbda7de # probeid = 769322749 # ╔═╡ d552f132-6f90-4aba-9e05-1e7e20929756 md""" ## Inspecting data To mimic the Allen SDK's interface we can use a custom type wrapping a session obect: """ # ╔═╡ c3093ce3-7b73-49d4-8ce8-aaea4b49b685 session = ANB.VisualBehavior.Session(session_id); ANB.initialize!(session); # ╔═╡ 3ec0b209-2287-4fcf-be04-688bd4fb327a # sessionid = AN.getid(session) # ╔═╡ ebe8631b-4248-4b5a-94e2-071c0b560747 md"The six probes for this session are:" # ╔═╡ c77034a4-a6b4-4970-bdc8-9a6b30cbb687 probes = ANB.getprobes(session) # ╔═╡ 12d66773-c567-4e5a-a119-4fa5e06ec98c md"We are only interested in channels located within the brain, so the `missing` structure ids are removed and the channels for this session become:" # ╔═╡ 5f944e90-5232-4508-9a3a-c678e6804104 channels = subset(ANB.getchannels(session), :structure_acronym => ByRow(!=("root"))) # ╔═╡ 423edd0f-60ed-4d9a-b84a-47e47e560ae2 md""" We can then plot the probe locations on the reference atlas. Note that the colored regions correspond to the target structures, and the straight probes have been warped into the common coordinate framework: """ # ╔═╡ 12f8e03b-4ea3-4211-a9b1-f8432dfae3a9 #s = AN.Plots.plotreferencevolume(session; dostructures=true, # ids=:targets, # show_axis=false, # shading=true); rotate_cam!(s, Vec3f0(0, 2.35, 0)); s # To save you from waiting for the structure masks to download: # @html_str read(download("https://dl.dropbox.com/s/se2doygr56ox8hs/probelocations.html?dl=0"), String) # This renders best in firefox # ╔═╡ bdb2de60-33c6-4d65-967e-92dcc9dafe69 md""" To identify a probe that passes through a given structure: """ # ╔═╡ 4b94916e-2316-442a-bf98-f6cc63ca0591 structure = "VISp" # ╔═╡ a61c6563-80ea-451c-82fd-7e6d1fcba752 probeid = ANB.getprobe(session, structure) # ╔═╡ b9c2e65c-03cf-45d7-9309-b601f486c62b md""" The LFP data for our probe can be accessed as (warning, it is slow): """ # ╔═╡ f0241126-912b-4863-9d4e-917af1426602 params = (; sessionid=ANB.getid(session), # stimulus="spontaneous", probeid, # structure, epoch=2 ) # ╔═╡ 2a9ccb08-29a2-4f4b-a01a-2c97c12a96b8 ANB.getid(session) # ╔═╡ 7ec55a76-e63e-4920-997c-af80610eba73 LFP = ANB.formatlfp(; params...) # ╔═╡ d0a301a0-038c-4827-8683-e9d8807186ea md"And sorted by depth with:" # ╔═╡ a5fca30e-531e-4b09-97e9-a762059dc66c # sortedLFP = AN.sortbydepth(session, probeid, LFP)[:, end:-1:1] # ╔═╡ 39ae3db9-b799-4389-80e7-e898e4e88a84 # fig = AN.Plots.neuroslidingcarpet(sortedLFP[1:5000, :]; size=(800, 1600)) # ╔═╡ 87ab5ec5-67a9-413d-8789-6a8b7113de65 md""" There are still channels with little signal outside of the brain and at the very surface of the isocortex. To remove these, downsample by 10x and use data from only one stimulus epoch: """ # ╔═╡ da9fa8b0-afcf-4f3d-bd6d-856b69ab6d28 # begin # depthcutoff = 200 # μm # times = AN.getepochs(session, "natural_movie_three")[1, :] # times = [times.start_time, times.stop_time] # inbrainLFP = AN.getlfp(session, probeid; inbrain=depthcutoff, times) # end # ╔═╡ Cell order: # ╠═98c9bbd2-aac5-4c90-ac0c-d8d935f5cdaf # ╟─0a622047-c238-49c3-bdf0-3248d0f0d261 # ╟─766a8af5-4c89-4fe7-883d-d960ef91edfd # ╟─bea5de79-6e8a-42d8-ab76-bae8e3c23747 # ╟─f9ac9f6e-f129-4542-81a8-36e6cef9857a # ╟─c48bd78e-aab0-49c0-b137-567c208b8aa1 # ╠═c445ccf4-cf10-43b9-9c01-4051abc400ba # ╠═d8fd4541-08a5-4ace-a998-769771c976e8 # ╠═2e3d037c-932d-4d5a-afdb-351e836bdfb2 # ╠═79b92c17-cc5f-4ca2-8b08-f6015729a9a9 # ╠═1a3eaeb7-db19-4bc3-b61a-84dd9caad009 # ╠═c1397e8e-3ac2-4f49-8d88-cc1400a3b93e # ╟─5bfaefae-11a5-4567-8b83-d583f03a75a8 # ╠═754f94e0-ccb2-4dc0-a534-ae94dd02bc02 # ╟─a2f81f74-36ed-42d4-89d5-828327c67318 # ╠═efd3ef52-4acb-4ffd-b794-1dfc4d9819c8 # ╟─e30e349c-6ad7-402b-90d1-7720b85a9c2c # ╠═d2d20884-0fcd-4ac7-8a14-dbf936445c3b # ╠═99fe41d6-661d-4b9f-a853-2f32ace53d72 # ╟─82ce6d0f-b60b-41f2-bdce-c6ecf545bf65 # ╠═5d47cb91-d8c7-41df-9778-c9a77266ba93 # ╠═c62a118e-713e-424f-9420-f310131c7018 # ╠═d3064ff9-798f-4469-9ac5-43b94c9e9a92 # ╟─7d00cd72-a2c0-45a9-b777-b347286f7390 # ╠═fd03139c-4bd1-4f26-a8c3-46c3feefd9c5 # ╟─51eccd32-d4e9-4330-99f5-fca0f8534e43 # ╠═927605f4-0b59-4871-a13f-420aadedd487 # ╠═5973ddbe-f839-44d8-af08-46b1813e8750 # ╠═395a90c4-fe98-49bc-9883-d4278cd38bae # ╟─23d8fad0-5c51-4056-8df3-fd850db7b560 # ╟─99e2e888-c1cf-4370-b1b4-eccc6cbda7de # ╟─d552f132-6f90-4aba-9e05-1e7e20929756 # ╠═c3093ce3-7b73-49d4-8ce8-aaea4b49b685 # ╟─3ec0b209-2287-4fcf-be04-688bd4fb327a # ╟─ebe8631b-4248-4b5a-94e2-071c0b560747 # ╠═c77034a4-a6b4-4970-bdc8-9a6b30cbb687 # ╟─12d66773-c567-4e5a-a119-4fa5e06ec98c # ╠═5f944e90-5232-4508-9a3a-c678e6804104 # ╟─423edd0f-60ed-4d9a-b84a-47e47e560ae2 # ╠═12f8e03b-4ea3-4211-a9b1-f8432dfae3a9 # ╠═bdb2de60-33c6-4d65-967e-92dcc9dafe69 # ╠═4b94916e-2316-442a-bf98-f6cc63ca0591 # ╠═a61c6563-80ea-451c-82fd-7e6d1fcba752 # ╟─b9c2e65c-03cf-45d7-9309-b601f486c62b # ╠═f0241126-912b-4863-9d4e-917af1426602 # ╠═2a9ccb08-29a2-4f4b-a01a-2c97c12a96b8 # ╠═7ec55a76-e63e-4920-997c-af80610eba73 # ╟─d0a301a0-038c-4827-8683-e9d8807186ea # ╠═a5fca30e-531e-4b09-97e9-a762059dc66c # ╠═39ae3db9-b799-4389-80e7-e898e4e88a84 # ╠═87ab5ec5-67a9-413d-8789-6a8b7113de65 # ╠═da9fa8b0-afcf-4f3d-bd6d-856b69ab6d28
AllenNeuropixelsBase
https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl.git
[ "MIT" ]
0.3.0
215ea07f170cd9732aa7d7745c672f69baf3dc02
code
4576
import AllenNeuropixelsBase as ANB using AllenNeuropixelsBase.TimeseriesTools using AllenNeuropixelsBase.NWBStream using Test using AllenNeuropixelsBase.DataFrames ENV["JULIA_DEBUG"] = "CUDAExt,AllenNeuropixelsBase,AllenNeuropixels" VCSESSIONID = 847657808 VCPROBEID = 848037574 VBSESSIONID = 1067588044 begin # * Download the files session_id = VCSESSIONID session = ANB.Session(session_id) ANB.getprobes(session) probeid = @test_nowarn ANB.getprobeids(session)[2] ANB.getprobestructures(session)[probeid] @test_nowarn ANB.listprobes(session) @test ANB.getepochs(session) isa DataFrame @test ANB.getprobes(session) isa DataFrame # * Check channels channels = ANB.getlfpchannels(session, probeid) cdf = ANB.getchannels(session, probeid) @test all(channels .∈ [cdf.id]) LFP = ANB._getlfp(session, probeid; channelidxs=1:length(ANB.getlfpchannels(session, probeid)), timeidxs=1:length(ANB.getlfptimes(session, probeid))) end # @testset "NWBStream.jl" begin # f, io = @test_nowarn s3open("https://visual-behavior-neuropixels-data.s3.us-west-2.amazonaws.com/visual-behavior-neuropixels/behavior_ecephys_sessions/VCSESSIONID/ecephys_session_VCSESSIONID.nwb") # s3close(io) # end # @testset "Stream Visual Behavior" begin # st = @test_nowarn ANB.VisualBehavior.getsessiontable() # @test st isa DataFrame # session_id = st[2, :ecephys_session_id] # url = ANB.VisualBehavior.getsessionfile(session_id) # file, io = s3open(url) # ANB.behavior_ecephys_session.BehaviorEcephysSession.from_nwb(file) # session = ANB.VisualBehavior.S3Session(session_id) # ANB.initialize!(session) # ANB.getprobes(session) # ANB.getprobeids(session) # @test_nowarn ANB.listprobes(session) # @test_nowarn ANB.getepochs(session) # end @testset "Format LFP" begin params = (; sessionid=VCSESSIONID, stimulus="spontaneous", probeid=VCPROBEID, structure="VISl", epoch=:longest, pass=(1, 100)) X = ANB.formatlfp(; params...) @test X isa ANB.LFPMatrix @test X isa TimeseriesTools.RegularTimeSeries end # @testset "HybridSession" begin # st = @test_nowarn ANB.VisualBehavior.getsessiontable() # @test st isa DataFrame # session_id = st[2, :ecephys_session_id] # session = ANB.VisualBehavior.S3Session(session_id) # ANB.initialize!(session) # ANB.getprobes(session) # ANB.getprobeids(session) # @test_nowarn ANB.listprobes(session) # @test_nowarn ANB.getepochs(session) # end @testset "Visual Behavior" begin # st = @test_nowarn ANB.VisualBehavior.getsessiontable() # @test st isa DataFrame # session_id = st[end, :ecephys_session_id] session_id = VBSESSIONID session = ANB.Session(session_id) # test_file = "/home/brendan/OneDrive/Masters/Code/Vortices/Julia/AllenSDK/test/ecephys_session_VBSESSIONID.nwb" # f = ANB.behavior_ecephys_session.BehaviorSession.from_nwb_path(test_file) probeid = @test_nowarn ANB.getprobeids(session)[2] @test_nowarn ANB.getprobestructures(session)[probeid] @test_nowarn ANB.listprobes(session) @test_nowarn ANB.getepochs(session) @test_nowarn ANB.getprobes(session) # Now try to get some LFP data @test ANB._getlfp(session, probeid; channelidxs=1:length(ANB.getlfpchannels(session, probeid)), timeidxs=1:length(ANB.getlfptimes(session, probeid))) isa TimeseriesTools.IrregularTimeSeries structure = ANB.getprobestructures(session)[probeid] structure = structure[occursin.(("VIS",), string.(structure))|>findfirst] channels = @test_nowarn ANB.getlfpchannels(session, probeid) cdf = @test_nowarn ANB.getchannels(session, probeid) ANB._getchanneldepths(cdf, channels) depths = @test_nowarn ANB.getchanneldepths(session, probeid, channels) x = ANB.getlfp(session, structure) @test x isa TimeseriesTools.IrregularTimeSeries @test x isa TimeseriesTools.MultivariateTimeSeries a = ANB.formatlfp(session; probeid, stimulus="spontaneous", structure=structure, epoch=:longest) b = ANB.formatlfp(; sessionid=session_id, probeid, stimulus="spontaneous", structure=structure, epoch=:longest) # Slower, has to build the session @assert a == b # Test behavior data S = session @test ANB.gettrials(S) isa DataFrame @test ANB.getlicks(S) isa DataFrame @test ANB.getrewards(S) isa DataFrame @test ANB.getstimuli(S) isa DataFrame @test ANB.geteyetracking(S) isa DataFrame end # s3clear() return
AllenNeuropixelsBase
https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl.git
[ "MIT" ]
0.3.0
215ea07f170cd9732aa7d7745c672f69baf3dc02
docs
1091
# AllenNeuropixelsBase <!-- [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://brendanjohnharris.github.io/AllenNeuropixelsBase.jl/stable/) --> <!-- [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://brendanjohnharris.github.io/AllenNeuropixelsBase.jl/dev/) --> [![Build Status](https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/brendanjohnharris/AllenNeuropixelsBase.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/brendanjohnharris/AllenNeuropixelsBase.jl) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.10584983.svg)](https://doi.org/10.5281/zenodo.10584983) This package lets you load the Allen Neuropixels data in a Julia-oriented format, using e.g. [DataFrames](https://github.com/JuliaData/DataFrames.jl) and [DimArrays](https://github.com/rafaqz/DimensionalData.jl). Can load both the 'Visual Coding' and 'Visual Behavior' datasets.
AllenNeuropixelsBase
https://github.com/brendanjohnharris/AllenNeuropixelsBase.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
458
using Documenter, ModiaResult, ModiaPlot_PyPlot makedocs( #modules = [ModiaResult], sitename = "ModiaResult", authors = "Martin Otter (DLR-SR)", format = Documenter.HTML(prettyurls = false), pages = [ "Home" => "index.md", "Getting Started" => "GettingStarted.md", "Functions" => "Functions.md", "Abstract Interface" => "AbstractInterface.md", "Internal" => "Internal.md", ] )
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
5186
# License for this file: MIT (expat) # Copyright 2021, DLR Institute of System Dynamics and Control (DLR-SR) # Developer: Martin Otter, DLR-SR # # This file is part of module ModiaResult """ @enum ModiaResult.SignalType Defines the type of the signal. Supported values: - `ModiaResult.Independent`: Independent variable (usually the time signal). - `ModiaResult.Continuous`: Piece-wise continuous signal (typically linearly interpolated). - `ModiaResult.Clocked`: Clocked signal (values are only defined at the corresponding `Time` signal time instants and have no value in between; the latter might be signaled by piece-wise constant dotted lines). """ @enum SignalType Independent=1 Continuous=2 Clocked=3 """ (timeSignal, signal, signalType) = ModiaResult.rawSignal(result, name) Given the result data structure `result` and a variable `name::AbstractString`, return the result values of the independent variable (= `timeSignal`), the corresponding result values of the variable (= `signal`) and the type of the signal `signalType::`[`SignalType`](@ref)). Note, an error shall be raised, if `name` is not known. The following figure sketches the returned `timeSignal` and `signal` data structures: ![SignalDefinition](https://modiasim.github.io/ModiaResult.jl/resources/images/signal-definition.png) Other signal types might be mapped to this basic signal type by introducing views. # Details of the return arguments `timeSignal::Vector{Vector{T1}}`: A result consists of one or more **segments**. `timeSignal[i][j]` is the value of time instant `j` in segment `i`. `timeSignal[i][:]` must have monotonically increasing values and type `T1<:Real` must be a subtype of `Real` for which a conversion to `AbstractFloat` is defined. For example, `T1::Rational` is fine, but `T1::Complex` is not allowed. `signal::Vector{Vector{T2}}` or `signal::Vector{Vector{Array{T2,N}}}`: `signal[i][j]` is the value of the variable at time instant `timeSignal[i][j]`. This value can be a scalar or an array. Type `T2` can have one of the following values: - `T2 <: Real`, must be a subtype of `Real` for which a conversion to `AbstractFloat` is defined, or - `T2 <: Measurements.Measurement{T1}`, or - `T2 <: MonteCarloMeasurements.StaticParticles{T1,N}`, or - `T2 <: MonteCarloMeasurements.Particles{T1,N}`. If the signal is a constant with value `value`, return `([[t_min, t_max]], [[value, value]], ModiaResult.Continuous)`. If the signal is the time signal, return `(timeSignal, timeSignal, ModiaResult.independent)`. The `timeSignal` might be a dummy vector consisting of the first and last time point in the result (if different timeSignals are present for different signals or if the signal is constant). `signal` and `timeSignal` may have units from package `Unitful`. The information `signalType::SignalType` defines how the signal can be interpolated and/or plotted. """ function rawSignal end """ ModiaResult.signalNames(result) Return a string vector of the signal names that are present in result. """ function signalNames end """ ModiaResult.timeSignalName(result) Return the name of the independent variable (typically: "time"). """ function timeSignalName end """ ModiaResult.hasOneTimeSignal(result) Return true if `result` has one time signal. Return false, if `result` has two or more time signals. """ function hasOneTimeSignal end """ (signal, timeSignal, timeSignalName, signalType, arrayName, arrayIndices, nScalarSignals) = getSignalDetails(result, name) Return the signal defined by `name::AbstractString` as `signal::Vector{Matrix{<:Real}}`. `name` may include an array range, such as "a.b.c[2:3,5]". In this case `arrayName` is the name without the array indices, such as `"a.b.c"`, `arrayIndices` is a tuple with the array indices, such as `(2:3, 5)` and `nScalarSignals` is the number of scalar signals, such as `3` if arrayIndices = `(2:3, 5)`. Otherwise `arrayName = name, arrayIndices=(), nScalarSignals=1`. In case the signal is not known or `name` cannot be interpreted, `(nothing, nothing, nothing, nothing, name, (), 0)` is returned. It is required that the value of the signal at a time instant has either `typeof(value) <: Real` or `typeof(value) = AbstractArray{Real, N}`. The following `Real` types are currently supported: 1. `convert(Float64, eltype(value)` is supported (for example Float32, Float64, DoubleFloat, Rational, Int32, Int64, Bool). 2. Measurements.Measurement{<Type of (1)>}. 3. MonteCarloMeasurements.StaticParticles{<Type of (1)>}. 4. MonteCarloMeasurements.Particles{<Type of (1)>}. """ function getSignalDetails end """ ModiaResult.hasSignal(result, name) Returns `true` if signal `name::AbstractString` is available in `result`. """ function hasSignal(result, name::AbstractString)::Bool hasName = true try sigInfo = rawSignal(result,name) catch hasName = false end return hasName end """ ModiaResult.defaultHeading(result) Return default heading of result as a string (can be used as default heading for a plot). """ defaultHeading(result) = ""
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
14110
# License for this file: MIT (expat) # Copyright 2021, DLR Institute of System Dynamics and Control # # This file is part of module ModiaResult # # Functions that are exported from ModiaResult import DataFrames import Unitful baseType(::Type{T}) where {T} = T numberType(value) = baseType(eltype(value)) function ifNecessaryStripUnits(s1,s2) if numberType(s1) <: Unitful.AbstractQuantity && !(numberType(s2) <: Unitful.AbstractQuantity) # s1 has units and s2 has no units -> remove units in s1 s1 = Unitful.ustrip.(s1) elseif !(numberType(s1) <: Unitful.AbstractQuantity) && numberType(s2) <: Unitful.AbstractQuantity # s1 has no units and s2 has units -> remove units in s2 s2 = Unitful.ustrip.(s2) end return (s1,s2) end # Provide Vector type with one value and fixed length struct OneValueVector{T} <: AbstractArray{T, 1} value::T nvalues::Int OneValueVector{T}(value,nvalues) where {T} = new(value,nvalues) end OneValueVector(value,nvalues) = OneValueVector{typeof(value)}(value,nvalues) Base.getindex(v::OneValueVector, i::Int) = v.value Base.size(v::OneValueVector) = (v.nvalues,) Base.IndexStyle(::Type{<:OneValueVector}) = IndexLinear() interpolate(tsig, sig, isig, t) = begin sig_ipo = sig[isig-1] + (sig[isig] - sig[isig-1])*((t - tsig[isig-1])/(tsig[isig] - tsig[isig-1])) isfinite(sig_ipo) ? sig_ipo : sig[isig] end """ (result1s, result2s, sameTimeRange) = makeSameTimeAxis(result1, result2; names = missing, timeName1 = "time", timeName2 = "time") The function makes the same time axis for the signals in result1 and result2 identified by the signal `select::Vector{String}`. It is required that `result1` and `result2` support functions - `hasSignal(result, name)` - `rawSignal(result, name)` - `names(result)` and that the time axis is identified by name `timeName1` and `timeName2` respectively. If `select == missing`, then the intersection of the `select` names of `result1` and of `result2` is used (but without signals `timeName1`, `timeName2). The function returns a dictionaries of type `DictionaryResult` of the signals `select` that are both in `result1` and in `result2` so that all signals have the same time axes. Notes: - If for example `select = ["n1", "n2", "n3", "n4"]` and `"n1"`, `"n3"` and `"n4"`are in `result1` and `"n2", "n3", "n4"` are in `result2` then `result1s` and `result2s` contain names `"n3", "n4"`. - If additional time instants are introduced in a time axis, then the corresponding signal values are computed by linear interpolation. - If possible, **references** are returned and **not copies** of the signals (for example, if the time axes of `result1` and `result2` are identical, then `result1s` is a reference of `result1` and `result2s` is a reference of `result2`). - If the first and last time point of result1 and result2 are identical, then `sameTimeRange = true`. If this is not the case, `sameTimeRange = false` and time vectors in `result1s, result2s` contain the time values that are both in time vectors `result1` and `result2`. If there is no common time range, an error occurs. """ function makeSameTimeAxis(result1, result2; select = missing, timeName1::String = "time", timeName2::String = "time") # Determine the names that are both in result1 and in result2 names_common::Vector{String} = ismissing(select) ? setdiff(intersect(names(result1), names(result2)), [timeName1, timeName2]) : intersect(select, names(result1), names(result2)) if length(names_common) == 0 @error "result1 and result2 have no names in common from $names" end # Check that timeName1 and timeName2 are in the results if !hasSignal(result1, timeName1) @error "result1 has no signal with name $timeName1" elseif !hasSignal(result2, timeName2) @error "result2 has no signal with name $timeName2" end # Get time axes (t1, t1b, t1Name, ipo1) = rawSignal(result1, timeName1) (t2, t2b, t2Name, ipo2) = rawSignal(result2, timeName2) if length(t1) != 1 @error "Only one segment is currently supported. Signal $timeName1 has " * length(t1) * " segments." elseif length(t2) != 1 @error "Only one segment is currently supported. Signal $timeName2 has " * length(t2) * " segments." end t1 = t1[1] t2 = t2[1] if !(typeof(t1) <: AbstractVector) type_t1 = typeof(t1) @error "The time signal $timeName1 of result1 is no vector (has type $type_t1)" elseif !(typeof(t2) <: AbstractVector) type_t2 = typeof(t2) @error "The time signal $timeName2 of result2 is no vector (has type $type_t2)" end (t1,t2) = ifNecessaryStripUnits(t1,t2) # Generate output DataFrames result1s = DataFrames.DataFrame() result2s = DataFrames.DataFrame() # Handle case, if the time axes are the same if t1 == t2 nt = length(t1) (tt1, tt1b, tt1Name, dummy) = rawSignal(result1, timeName1) if length(tt1) != length(t1) @error "Only one time signal is currently supported, but $result1 has several time signals." end result1s[!,timeName1] = tt1 (tt2, tt2b, tt2Name, dummy) = rawSignal(result2, timeName2) if length(tt2) != length(t2) @error "Only one time signal is currently supported, but $result2 has several time signals." end result2s[!,timeName2] = tt2 for name in names_common (sig1, tt1c, tt1cName, sigIpo1) = rawSignal(result1, name) result1s[!,name] = sig1 (sig2, tt2c, ttt2Name, sigIpo2) = rawSignal(result2, name) result2s[!,name] = sig2 end return (result1s, result2s, true) end # Determine common time range nt1 = length(t1) nt2 = length(t2) if t1[end] < t2[1] || t1[1] > t2[end] t1_begin = t1[1] t1_end = t1[end] t2_begin = t2[1] t2_end = t2[end] @error "result1 has time range [$t1_begin,$t1_end] and result2 has time range [$t1_begin,$t1_end]" end if t1[1] <= t2[1] i1_begin = findlast(v -> v <= t2[1], t1) i2_begin = 1 t_begin = t2[1] else i2_begin = findlast(v -> v <= t1[1], t2) i1_begin = 1 t_begin = t1[1] end # Allocate memory for common time axis nt = nt1 + nt2 t_common = similar(t1, promote_type(eltype(t1), eltype(t2)), nt) t = t_begin i1 = i1_begin i2 = i2_begin i = 1 while true t_common[i] = t if t >= t1[i1] i1 += 1 end if t >= t2[i2] i2 += 1 end i += 1 if i > nt break elseif i1 > nt1 || i2 > nt2 deleteat!(t_common, i:nt) break end t = t1[i1] <= t2[i2] ? t1[i1] : t2[i2] end result1s[!,timeName1] = t_common result2s[!,timeName2] = t_common nt = length(t_common) sameTimeRange = t1[1] == t2[1] && t1[end] == t2[end] # Make same time axis for name in names_common # Allocate memory for signals in result1s, result2s (sig1, t1, t1Name, ipo1) = rawSignal(result1, name) (sig2, t2, t2Name, ipo2) = rawSignal(result2, name) if length(sig1) == 0 @error "$name in result1 has no values" end if length(sig2) == 0 @error "$name in result2 has no values" end if typeof(sig1[1]) <: Number && typeof(sig2[1]) <: Number sig1_common = similar(sig1, promote_type(eltype(sig1), eltype(sig2)), nt) elseif typeof(sig1[1]) <: AbstractArray && typeof(sig2[1]) <: AbstractArray if size(sig1[1]) != size(sig2[1]) size1 = size(sig1[1]) size2 = size(sig2[1]) @error "$name array in result1 has element size $size1 and in result2 element size $size2" end sig1_common = similar(sig1, Array{promote_type(eltype(sig1[1]), eltype(sig2[1])), ndims(sig1[1])}, nt) else type1 = typeof(sig1[1]) type2 = typeof(sig2[1]) @error "$name in result1 has element type $type1 and in result2 element type $type2" end sig2_common = similar(sig1_common) # Make same time axis for signals sig1 and sig2 t = t_begin i = 1 i1 = i1_begin i2 = i2_begin while true #println("... i = $i, i1 = $i1, i2 = $i2, t = $t, t1[i1] = ", t1[i1], ", t2[i2] = ", t2[i2]) if t < t1[i1] sig1_common[i] = interpolate(t1,sig1,i1,t) else sig1_common[i] = sig1[i1] i1 += 1 end if t < t2[i2] sig2_common[i] = interpolate(t2,sig2,i2,t) else sig2_common[i] = sig2[i2] i2 += 1 end i += 1 if i > nt break end t = t1[i1] <= t2[i2] ? t1[i1] : t2[i2] end result1s[!,name] = sig1_common result2s[!,name] = sig2_common end return (result1s, result2s, sameTimeRange) end """ (success, diff, diff_names, max_error, within_tolerance) = compareResults(result, reference; tolerance = 1e-3, names = missing, timeResult = "time", timeReference = "time") Compare the signals identified by `names::Vector{String}` in `result` with the reference reults `reference` using the relative `tolerance`. The time axis is identified by name `timeResult` and `timeReference` respectively. If `names == missing`, then the intersection of the `names` of `result` and of `reference` is used (but without signals `timeResult`, `timeReference). Input arguments `result`, `reference` can be dictionaries, DataFrames or objects that support functions - `ModiaPlot.hasSignal(result, name)` - `rawSignal(result, name)` - `names(result)` # Output arguments - `success::Bool`: = true, if all compared signals are the same within the given tolerance (see below),. - `diff::DataFrame`: The difference of the compared signals (using `timeResult` as time-axis). - `diff_names::Vector{String}`: The names of the signals that are compared. - `max_error::Vector{Float64}`: max_error[i] is the maximum error in signal of diff_names[i]. - `within_tolerance::BitVector`: withinTolerance[i] = true, if signal of diff_names[i] is within the tolerance (see below). # Computation of the outputs Comparison is made in the following way (assuming `result` and `reference` have the same time axis and are DataFrames objects): ```julia smallestNominal = 1e-10 nt = DataFrames.nrow(reference) for (i,name) in enumerate(diff_names) diff[i] = result[!,name] - reference[!,name] max_error[i] = maximum( abs.(result[!,name] - reference[!,name]) ) nominal[i] = max( sum( abs.(reference[!,name])/nt ), smallestNominal ) within_tolerance[i] = max_error[i] <= nominal[i]*tolerance end success = all(within_tolerance) ``` # Notes Before the comparison, the function makes the same time axis for the signals in `result` and `reference` and selects the maximum time range that is both in `result` and in `reference`. If additional time instants are introduced in a time axis, then the corresponding signal values are computed by linear interpolation. This linear interpolation can introduce a significant error. It is therefore highly recommended to use the same time axis. """ function compareResults(result, reference; tolerance::Float64 = 1e-3, names::Union{Missing,Vector{String}} = missing, timeResult::String = "time", timeReference::String = "time") # Check tolerance if tolerance <= 0.0 @error "compareResults: Input argument tolerance = $tolerance <= 0.0" end # Make same time axis (result1s, result2s) = makeSameTimeAxis(result, reference; names = names, timeName1 = timeResult, timeName2 = timeReference) # Compute difference and tolerance diff_names = setdiff(DataFrames.names(result1s), [timeResult]) nnames = length(diff_names) diff = DataFrames.DataFrame() diff[!,timeResult] = result1s[!,timeResult] smallestNominal = 1e-10 nt = DataFrames.nrow(result1s) max_error = zeros(nnames) nominal = zeros(nnames) within_tolerance = fill(false, nnames) for (i,name) in enumerate(diff_names) s1 = result1s[!,name] s2 = result2s[!,name] (s1,s2) = ifNecessaryStripUnits(s1,s2) # Difference of the signals diff[!,name] = s1 - s2 # Error max_error[i] = Unitful.ustrip.( maximum( abs.(s1 - s2) ) ) nominal[i] = max( Unitful.ustrip(sum( abs.(s2)/nt )), smallestNominal ) within_tolerance[i] = max_error[i] <= nominal[i]*tolerance end success = all(within_tolerance) return (success, diff, diff_names, max_error, within_tolerance) end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
269
module ModiaResult const path = dirname(dirname(@__FILE__)) include("ResultViews.jl") include("AbstractInterface.jl") include("NoPlot.jl") include("SilentNoPlot.jl") include("Utilities.jl") include("OverloadedMethods.jl") #include("CompareResults.jl") end # module
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
1044
# License for this file: MIT (expat) # Copyright 2021, DLR Institute of System Dynamics and Control module NoPlot include("plot.jl") plot(result, names::AbstractMatrix; heading::AbstractString="", grid::Bool=true, xAxis="time", figure::Int=1, prefix::AbstractString="", reuse::Bool=false, maxLegend::Integer=10, minXaxisTickLabels::Bool=false, MonteCarloAsArea=false) = println("... plot(..): Call is ignored, because of usePlotPackage(\"NoPlot\").") showFigure(figure::Int) = println("... showFigure($figure): Call is ignored, because of usePlotPackage(\"NoPlot\").") closeFigure(figure::Int) = println("... closeFigure($figure): Call is ignored, because of usePlotPackage(\"NoPlot\").") saveFigure(figure::Int, fileName::AbstractString) = println("... saveFigure($figure,\"$fileName\"): Call is ignored, because of usePlotPackage(\"NoPlot\").") """ closeAllFigures() Close all figures. """ closeAllFigures() = println("... closeAllFigures(): Call is ignored, because of usePlotPackage(\"NoPlot\").") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
3553
# License for this file: MIT (expat) # Copyright 2021, DLR Institute of System Dynamics and Control # Developer: Martin Otter, DLR-SR # # This file is part of module ModiaResult # # Overloaded ModiaResult methods for # - AbstractDict{String,T} # - DataFrames # - Tables # - ModiaResult.ResultDict import ModiaResult import DataFrames import Tables import OrderedCollections # Overloaded methods for AbstractDict{String,T} ModiaResult.rawSignal( result::AbstractDict{T1,T2}, name::String) where {T1<:AbstractString,T2} = ([result["time"]], [result[name]], name == "time" ? ModiaResult.Independent : ModiaResult.Continuous) ModiaResult.signalNames( result::AbstractDict{T1,T2}) where {T1<:AbstractString,T2} = collect(keys(result)) ModiaResult.timeSignalName( result::AbstractDict{T1,T2}) where {T1<:AbstractString,T2} = "time" ModiaResult.hasOneTimeSignal(result::AbstractDict{T1,T2}) where {T1<:AbstractString,T2} = true ModiaResult.hasSignal( result::AbstractDict{T1,T2}, name::String) where {T1<:AbstractString,T2} = haskey(result, name) # Overloaded methods for ModiaResult.ResultDict ModiaResult.rawSignal( result::ResultDict, name::String) = result.dict[name] ModiaResult.signalNames( result::ResultDict) = collect(keys(result.dict)) ModiaResult.timeSignalName( result::ResultDict) = "time" ModiaResult.hasOneTimeSignal(result::ResultDict) = result.hasOneTimeSignal ModiaResult.hasSignal( result::ResultDict, name::String) = haskey(result.dict, name) ModiaResult.defaultHeading( result::ResultDict) = result.defaultHeading # Overloaded methods for DataFrames ModiaResult.timeSignalName( result::DataFrames.DataFrame) = DataFrames.names(result, 1)[1] ModiaResult.hasOneTimeSignal(result::DataFrames.DataFrame) = true ModiaResult.rawSignal( result::DataFrames.DataFrame, name::AbstractString) = ([result[!,1]], [result[!,name]], name == timeSignalName(result) ? ModiaResult.Independent : ModiaResult.Continuous) ModiaResult.signalNames( result::DataFrames.DataFrame) = DataFrames.names(result) # Overloaded methods for Tables function ModiaResult.rawSignal(result, name::AbstractString) if Tables.istable(result) && Tables.columnaccess(result) return ([Tables.getcolumn(result, 1)], [Tables.getcolumn(result, Symbol(name))], string(Tables.columnnames(result)[1]) == name ? ModiaResult.Independent : ModiaResult.Continuous) else @error "rawSignal(result, \"$name\") is not supported for typeof(result) = " * string(typeof(result)) end end function ModiaResult.signalNames(result) if Tables.istable(result) && Tables.columnaccess(result) return string.(Tables.columnnames(result)) else @error "signalNames(result) is not supported for typeof(result) = " * string(typeof(result)) end end function ModiaResult.timeSignalName(result) if Tables.istable(result) && Tables.columnaccess(result) return string(Tables.columnnames(result)[1]) else @error "timeSignalName(result) is not supported for typeof(result) = " * string(typeof(result)) end end function ModiaResult.hasOneTimeSignal(result) if Tables.istable(result) && Tables.columnaccess(result) return true else @error "hasOneTimeSignal(result) is not supported for typeof(result) = " * string(typeof(result)) end end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
3788
using Unitful """ vec = OneValueVector(value,nvalues) Provide a vector view of one value. # Example ```julia vec1 = OneValueVector(2.0, 10) # = Vector{Float64} with length(vec) = 10 vec2 = OneValueVector(true, 4) # = Vector{Bool} with length(vec) = 4 ``` """ struct OneValueVector{T} <: AbstractVector{T} value::T nvalues::Int OneValueVector{T}(value,nvalues) where {T} = new(value,nvalues) end OneValueVector(value,nvalues) = OneValueVector{typeof(value)}(value,nvalues) Base.getindex(v::OneValueVector, i::Int) = v.value Base.size(v::OneValueVector) = (v.nvalues,) Base.IndexStyle(::Type{<:OneValueVector}) = IndexLinear() struct FlattendVector{T} <: AbstractVector{T} vectorOfVector::Vector{T} ibeg::Int # start index iend::Int # end index end Base.getindex(v::FlattendVector, i::Int) = view(v.vectorOfVector[i], v.ibeg:v.iend) Base.size( v::FlattendVector) = (length(v.vectorOfVector), ) Base.IndexStyle(::Type{<:FlattendVector}) = IndexLinear() """ signal = SignalView(result,signalIndex,negate) Return a view of signal `result[ti][signalIndex]` where `ti` is the index of the time instant and `signalIndex` is the index of the variable. If negate=true, negate the signal values. ```julia signal[ti] = negate ? -result[ti][signalIndex] : result[ti][signalIndex] ``` """ struct SignalView{T} <: AbstractVector{T} result signalIndex::Int negate::Bool SignalView{T}(result,signalIndex,negate) where {T} = new(result,signalIndex,negate) end SignalView(result,signalIndex,negate) = SignalView{typeof(result[1][signalIndex])}(result,signalIndex,negate) Base.getindex(signal::SignalView, ti::Int) = signal.negate ? -signal.result[ti][signal.signalIndex] : signal.result[ti][signal.signalIndex] Base.size( signal::SignalView) = (length(signal.result),) Base.IndexStyle(::Type{<:SignalView}) = IndexLinear() """ signal = FlattenedSignalView(result,signalStartIndex,signalSize,negate) Return a view of flattened signal `result[ti][signalStartIndex:signalEndIndex]` where `ti` is the index of the time instant and the signal of size `signalSize` has been flattened into a vector (`signalEndIndex = signalStartIndex + prod(signalSize) - 1`). If negate=true, negate the signal values. ```julia baseSignal = reshape(result[ti][signalStartIndex:signalStartIndex+prod(signalSize)-1], signalSize) signal[ti] = negate ? -baseSignal : baseSignal ``` """ struct FlattenedSignalView{T} <: AbstractVector{T} result signalStartIndex::Int signalEndIndex::Int signalSize::Tuple negate::Bool FlattenedSignalView{T}(result,signalStartIndex,signalSize,negate) where {T} = new(result,signalStartIndex,signalStartIndex+prod(signalSize)-1,signalSize,negate) end FlattenedSignalView(result,signalStartIndex,signalSize,negate) = FlattenedSignalView{typeof(result[1][signalStartIndex])}(result,signalStartIndex,signalSize,negate) Base.getindex(signal::FlattenedSignalView, ti::Int) = signal.signalSize == () ? (signal.negate ? -signal.result[ti][signal.signalStartIndex] : signal.result[ti][signal.signalStartIndex]) : (signal.negate ? -reshape(signal.result[ti][signal.signalStartIndex:signal.signalEndIndex],signal.signalSize) : reshape(signal.result[ti][signal.signalStartIndex:signal.signalEndIndex],signal.signalSize)) Base.size( signal::FlattenedSignalView) = (length(signal.result),) Base.IndexStyle(::Type{<:FlattenedSignalView}) = IndexLinear()
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
612
# License for this file: MIT (expat) # Copyright 2021, DLR Institute of System Dynamics and Control module SilentNoPlot include("plot.jl") plot(result, names::AbstractMatrix; heading::AbstractString="", grid::Bool=true, xAxis="time", figure::Int=1, prefix::AbstractString="", reuse::Bool=false, maxLegend::Integer=10, minXaxisTickLabels::Bool=false, MonteCarloAsArea=false) = nothing showFigure(figure::Int) = nothing closeFigure(figure::Int) = nothing saveFigure(figure::Int, fileName::AbstractString) = nothing """ closeAllFigures() Close all figures. """ closeAllFigures() = nothing end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
27390
# License for this file: MIT (expat) # Copyright 2020, DLR Institute of System Dynamics and Control # Developer: Martin Otter, DLR-SR # # This file is part of module ModiaResult # # Utility functions that are usually not directly called. using Unitful import OrderedCollections import DataFrames import Measurements import MonteCarloMeasurements import Pkg isinstalled(pkg::String) = any(x -> x.name == pkg && x.is_direct_dep, values(Pkg.dependencies())) const AvailableModiaPlotPackages = ["GLMakie", "WGLMakie", "CairoMakie", "PyPlot", "NoPlot", "SilentNoPlot"] const ModiaPlotPackagesStack = String[] """ usePlotPackage(plotPackage::String) Define the ModiaPlot package that shall be used by command `ModiaResult.@usingModiaPlot`. If a ModiaPlot package is already defined, save it on an internal stack (can be reactivated with `usePreviousPlotPackage()`. Possible values for `plotPackage`: - `"GLMakie"` - `"WGLMakie"` - `"CairoMakie"` - `"PyPlot"` - `"NoPlot"` - `"SilentNoPlot"` # Example ```julia import ModiaResult ModiaResult.usePlotPackage("GLMakie") module MyTest ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) result = Dict{String,Any}("time" => t, "phi" => sin.(t)) plot(result, "phi") # use GLMakie for the rendering end ``` """ function usePlotPackage(plotPackage::String; pushPreviousOnStack=true)::Bool success = true if plotPackage == "NoPlot" || plotPackage == "SilentNoPlot" if pushPreviousOnStack && haskey(ENV, "MODIA_PLOT") push!(ModiaPlotPackagesStack, ENV["MODIA_PLOT"]) end if plotPackage == "NoPlot" ENV["MODIA_PLOT"] = "NoPlot" else ENV["MODIA_PLOT"] = "SilentNoPlot" end else plotPackageName = "ModiaPlot_" * plotPackage if plotPackage in AvailableModiaPlotPackages # Check that plotPackage is defined in current environment if isinstalled(plotPackageName) if pushPreviousOnStack && haskey(ENV, "MODIA_PLOT") push!(ModiaPlotPackagesStack, ENV["MODIA_PLOT"]) end ENV["MODIA_PLOT"] = plotPackage else @warn "... usePlotPackage(\"$plotPackage\"): Call ignored, since package $plotPackageName is not in your current environment" success = false end else @warn "\n... usePlotPackage(\"$plotPackage\"): Call ignored, since argument not in $AvailableModiaPlotPackages." success = false end end return success end """ usePreviousPlotPackage() Pop the last saved ModiaPlot package from an internal stack and call `usePlotPackage(<popped ModiaPlot package>)`. """ function usePreviousPlotPackage()::Bool if length(ModiaPlotPackagesStack) > 0 plotPackage = pop!(ModiaPlotPackagesStack) success = usePlotPackage(plotPackage, pushPreviousOnStack=false) else @warn "usePreviousPlotPackage(): Call ignored, because nothing saved." success = false end return success end """ currentPlotPackage() Return the name of the plot package as a string that was defined with [`usePlotPackage`](@ref). For example, the function may return "GLMakie", "PyPlot" or "NoPlot" or or "", if no PlotPackage is defined. """ currentPlotPackage() = haskey(ENV, "MODIA_PLOT") ? ENV["MODIA_PLOT"] : "" """ @usingModiaPlot() Execute `using XXX`, where `XXX` is the ModiaPlot package that was activated with `usePlotPackage(plotPackage)`. """ macro usingModiaPlot() if haskey(ENV, "MODIA_PLOT") ModiaPlotPackage = ENV["MODIA_PLOT"] if !(ModiaPlotPackage in AvailableModiaPlotPackages) @warn "ENV[\"MODIA_PLOT\"] = \"$ModiaPlotPackage\" is not supported!. Using \"NoPlot\"." @goto USE_NO_PLOT elseif ModiaPlotPackage == "NoPlot" @goto USE_NO_PLOT elseif ModiaPlotPackage == "SilentNoPlot" expr = :( import ModiaResult.SilentNoPlot: plot, showFigure, saveFigure, closeFigure, closeAllFigures ) return esc( expr ) else ModiaPlotPackage = Symbol("ModiaPlot_" * ModiaPlotPackage) expr = :(using $ModiaPlotPackage) println("$expr") return esc( :(using $ModiaPlotPackage) ) end else @warn "No plot package activated. Using \"NoPlot\"." @goto USE_NO_PLOT end @label USE_NO_PLOT expr = :( import ModiaResult.NoPlot: plot, showFigure, saveFigure, closeFigure, closeAllFigures ) println("$expr") return esc( expr ) end const signalTypeToString = ["Independent", "Continuous", "Clocked"] """ resultInfo(result) Return information about the result as DataFrames.DataFrame object with columns: ```julia name::String, unit::String, nTime::String, signalType::String, valueSize::String, eltype::String ``` """ function resultInfo(result) if isnothing(result) @info "The call of showInfo(result) is ignored, since the argument is nothing." return end name2 = String[] unit2 = String[] nTime2 = String[] signalType2 = String[] valueSize2 = String[] eltype2 = String[] timeSigName = timeSignalName(result) for name in signalNames(result) (signalType, nTime, valueSize, elType, sigUnit, oneSigValue) = signalInfo2(result, name) if isnothing(elType) sigUnit3 = "???" nTime3 = "???" signalType3 = "???" valueSize3 = "???" eltype3 = "???" else sigUnit3 = sigUnit isa Nothing ? "???" : string(sigUnit) nTime3 = name==timeSigName && !hasOneTimeSignal(result) ? "---" : (oneSigValue ? string(nTime)*"*" : string(nTime)) signalType3 = signalTypeToString[Int(signalType)] valueSize3 = valueSize isa Nothing ? "()" : string(valueSize) eltype3 = string(elType) end if signalType3 == "Independent" pushfirst!(name2 , name) pushfirst!(unit2 , sigUnit3) pushfirst!(nTime2 , nTime3) pushfirst!(signalType2, signalType3) pushfirst!(valueSize2 , valueSize3) pushfirst!(eltype2 , eltype3) else push!(name2 , name) push!(unit2 , sigUnit3) push!(nTime2 , nTime3) push!(signalType2, signalType3) push!(valueSize2 , valueSize3) push!(eltype2 , eltype3) end end resultInfoTable = DataFrames.DataFrame(name=name2, unit=unit2, nTime=nTime2, signalType=signalType2, valueSize=valueSize2, eltype=eltype2) return resultInfoTable end """ printResultInfo(result) Print info about result. # Example ```julia using ModiaResult using Unitful ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) result = OrderedDict{String,Any}("time"=> t*u"s", "phi" => sin.(t)*u"rad", "A" => OneValueVector(2.0, length(t))) printResultInfo(result) # Gives output: # │ name unit nTime signalType valueSize eltype ───┼─────────────────────────────────────────────────── 1 │ time s 100 Independent () Float64 2 │ phi rad 100 Continuous () Float64 3 | A 100* Continuous () Float64 *: Signal stored as ModiaResult.OneValueVector (e.g. parameter) ``` """ function printResultInfo(result)::Nothing resultInfoTable = resultInfo(result) show(stdout, resultInfoTable, summary=false, rowlabel=Symbol("#"), allcols=true, eltypes=false, truncate=50) println(stdout) println("*: Signal stored as ModiaResult.OneValueVector (e.g. parameter)\n") return nothing end """ ResultDict(args...; defaultHeading="", hasOneTimeSignal=true) Return a new ResultDict dictionary (is based on OrderedCollections.OrderedDict). - A key of the dictionary is a String. Key `"time"` characterizes the independent variable. - A value of the dictionary is a tuple `(timeSignal, signal, signalType)` where `timeSignal::Vector{AbstractVector}`, `signal::Vector{AbstractVector}` and `signalType::ModiaResult.SignalType. `signal[i][j]` is the signalValue at time instant `timeSignal[i][j]` in segment `i`. # Example ```julia using ModiaResult time0 = [0.0, 7.0] t = ([time0], [time0], ModiaResult.Independent) time1 = 0.0 : 0.1 : 2.0 time2 = 3.0 : 0.01 : 3.5 time3 = 5.0 : 0.1 : 7.0 sigA1 = sin.(time1)u"m" sigA2 = cos.(time2)u"m" sigA3 = sin.(time3)u"m" sigA = ([time1, time2, time3], [sigA1, sigA2, sigA3 ], ModiaResult.SignalType) sigB = ([time2], [sin.(time2)], ModiaResult.SignalType) sigC = ([time3], [sin.(time3)], ModiaResult.Clocked) result = ModiaResult.ResultDict("time" => t, "sigA" => sigA, "sigB" => sigB, "sigC" => sigC, defaultHeading = "Three test signals", hasOneTimeSignal = false) showInfo(result) ``` """ struct ResultDict <: AbstractDict{String,Tuple{Any,Any,SignalType}} dict::OrderedCollections.OrderedDict{String,Tuple{Any,Any,SignalType}} defaultHeading::String hasOneTimeSignal::Bool ResultDict(args...; defaultHeading="", hasOneTimeSignal=true) = new(OrderedCollections.OrderedDict{String,Tuple{Any,Any,SignalType}}(args...), defaultHeading, hasOneTimeSignal) end #new(OrderedCollections.OrderedDict{String,Tuple{Vector{AbstractVector}, # Vector{AbstractVector}, # ModiaResult.SignalType}}(args...), # Overload AbstractDict methods Base.haskey(result::ResultDict, key) = Base.haskey(result.dict, key) Base.get(result::ResultDict, key, default) = Base.get(result.dict, key, default) Base.get(f::Function, result::ResultDict, key) = Base.get(f, result.dict, key) Base.get!(result::ResultDict, key, default) = Base.get!(result.dict, key, default) Base.get!(f::Function, result::ResultDict, key) = Base.get!(f, result.dict, key) Base.getkey(result::ResultDict, key, default) = Base.getkey(result.dict, key, default) Base.delete!(result::ResultDict, key) = Base.delete!(result.dict, key) Base.keys(result::ResultDict) = Base.keys(result.dict) Base.pop!(result::ResultDict, key) = Base.pop!(result.dict, key) Base.pop!(result::ResultDict, key, default) = Base.pop!(result.dict, key, default) Base.setindex!(result::ResultDict, value, key...) = Base.setindex!(result.dict, value, key...) Base.values(result::ResultDict) = Base.values(result.dict) """ signalLength(signal) Return the total number of values of `signal::Vector{AbstractVector}`. If signal[i] is nothing or missing, a length of zero is returned. """ function signalLength(signal::AbstractVector) for s in signal if ismissing(s) || isnothing(s) return 0 end end return sum( length(s) for s in signal ) end """ hasSameSegments(signal1, signal2) Return true, if the lengths of the segments in `signal1` and in `signal2` are the same. """ function hasSameSegments(signal1::Vector{AbstractVector}, signal2::Vector{AbstractVector}) if length(signal1) != length(signal2) return false end for i = 1:length(signal1) if length(signal1[i]) != length(signal2[i]) return false end end return true end """ hasDimensionMismatch(signal, timeSignal, timeSignalName) Print a warning message if signalLength(signal) != signalLength(timeSignal) and return true. Otherwise, return false """ function hasDimensionMismatch(signal, signalName, timeSignal, timeSignalName::AbstractString) if signalLength(signal) != signalLength(timeSignal) lensignal = signalLength(signal) lentime = signalLength(timeSignal) @warn "signalLength of \"$signalName\" = $lensignal but signalLength of \"$timeSignalName\" = $lentime" return true end return false end """ (sigType, nTime, sigSize, sigElType, sigUnit) = signalInfo(result, name) Return information about a signal, given the `name` of the signal in `result`: - `sigType::SignalType`: Ìnterpolation type of signal. - `nTime::Int`: Number of signal time points. - `sigSize`: size(signal[1][1]) - `sigElType`: ustrip( eltype(signal[1][1]) ), that is the element type of the signal without unit. - `sigUnit`: Unit of signal If `name` is defined, but no signal is available (= nothing, missing or zero length), return `nTime=0` and `nothing` for `sigSize, sigElType, sigUnit`. """ function signalInfo(result, name::AbstractString) (sigType, nTime, valueSize, valueElType, valueUnit, oneSigValue) = signalInfo2(result,name) return (sigType, nTime, valueSize, valueElType, valueUnit) end """ (sigType, nTime, sigSize, sigElType, sigUnit, oneSigValue) = signalInfo2(result, name) Return information about a signal, given the `name` of the signal in `result`. The difference to `signalInfo(..)` is that additionally the information is returned, whether the signals consists only of one value. - `sigType::SignalType`: Ìnterpolation type of signal. - `nTime::Int`: Number of signal time points. - `sigSize`: size(signal[1][1]) - `sigElType`: ustrip( eltype(signal[1][1]) ), that is the element type of the signal without unit. - `sigUnit`: Unit of signal - `oneSigValue`: = true, at all time instants, the signal has identical values (e.g. if parameter defined with OneValueVector). = false, signal has potentially different values at different time instants (which might be an array If `name` is defined, but no signal is available (= nothing, missing or zero length), return `nTime=0` and `nothing` for `sigSize, sigElType, sigUnit, oneSigValue`. """ function signalInfo2(result, name::AbstractString) (timeSignal, signal, sigType) = rawSignal(result,name) if ismissing(signal) || isnothing(signal) || !(typeof(signal) <: AbstractArray) || signalLength(signal) == 0 hasDimensionMismatch(signal, name, timeSignal, timeSignalName(result)) return (sigType, 0, nothing, nothing, nothing, nothing) end oneSigValue = length(signal) == 1 && typeof(signal[1]) <: OneValueVector value = signal[1][1] if value isa Number || value isa AbstractArray valueSize = size(value) valueUnit = unit(value[1]) else hasDimensionMismatch(signal, name, timeSignal, timeSignalName(result)) return (sigType, signalLength(timeSignal), nothing, typeof(value), nothing, oneSigValue) end if typeof(value) <: MonteCarloMeasurements.Particles elTypeAsString = string(typeof(ustrip.(value[1]))) nparticles = length(value) valueElType = "MonteCarloMeasurements.Particles{" * elTypeAsString * ",$nparticles}" elseif typeof(value) <: MonteCarloMeasurements.StaticParticles elTypeAsString = string(typeof(ustrip.(value[1]))) nparticles = length(value) valueElType = "MonteCarloMeasurements.StaticParticles{" * elTypeAsString * ",$nparticles}" else valueElType = typeof( ustrip.(value) ) end nTime = signalLength(timeSignal) return (sigType, nTime, valueSize, valueElType, valueUnit, oneSigValue) end # Default implementation of getSignalDetails function getSignalDetails(result, name::AbstractString) sigPresent = false if hasSignal(result, name) (timeSig, sig2, sigType) = rawSignal(result, name) timeSigName = timeSignalName(result) if !( isnothing(sig2) || ismissing(sig2) || signalLength(sig2) == 0 || hasDimensionMismatch(sig2, name, timeSig, timeSigName) ) sigPresent = true value = sig2[1][1] if ndims(value) == 0 sig = sig2 arrayName = name arrayIndices = () nScalarSignals = 1 else arrayName = name arrayIndices = Tuple(1:Int(ni) for ni in size(value)) nScalarSignals = length(value) sig = Vector{Matrix{eltype(value)}}(undef, length(sig2)) for segment = 1:length(sig2) sig[segment] = zeros(eltype(value), length(sig2[segment]), nScalarSignals) siga = sig[segment] sig2a = sig2[segment] for (i, value_i) in enumerate(sig2a) for j in 1:nScalarSignals siga[i,j] = sig2a[i][j] end end end end end else # Handle signal arrays, such as a.b.c[3] or a.b.c[2:3, 1:5, 3] if name[end] == ']' i = findlast('[', name) if i >= 2 arrayName = name[1:i-1] indices = name[i+1:end-1] if hasSignal(result, arrayName) (timeSig, sig2, sigType) = rawSignal(result, arrayName) timeSigName = timeSignalName(result) if !( isnothing(sig2) || ismissing(sig2) || signalLength(sig2) == 0 || hasDimensionMismatch(sig2, arrayName, timeSig, timeSigName) ) sigPresent = true value = sig2[1][1] # Determine indices as tuple arrayIndices = eval( Meta.parse( "(" * indices * ",)" ) ) # Determine number of signals #nScalarSignals = sum( length(indexRange) for indexRange in arrayIndices ) # Extract sub-matrix sig = Vector{Any}(undef,length(sig2)) for segment = 1:length(sig2) sig2a = sig2[segment] sig[segment] = [getindex(sig2a[i], arrayIndices...) for i in eachindex(sig2a)] end # Determine number of signals nScalarSignals = length(sig[1][1]) # "flatten" array to matrix eltypeValue = eltype(value) if !(eltypeValue <: Number) @warn "eltype($name) = $eltypeValue and this is not <: Number!" return (nothing, nothing, nothing, nothing, name, (), 0) end for segment = 1:length(sig2) sig[segment] = zeros(eltypeValue, length(sig2[segment]), nScalarSignals) siga = sig[segment] sig2a = sig2[segment] for (i, value_i) in enumerate(sig2a) for j in 1:nScalarSignals siga[i,j] = sig2a[i][j] end end end end end end end end if sigPresent return (sig, timeSig, timeSigName, sigType, arrayName, arrayIndices, nScalarSignals) else return (nothing, nothing, nothing, nothing, name, (), 0) end end """ (signal, timeSignal, timeSignalName, signalType, arrayName, arrayIndices, nScalarSignals) = getSignalWithWarning(result, name) Call getSignal(result,name) and print a warning message if `signal == nothing` """ function getSignalDetailsWithWarning(result,name::AbstractString) (sig, timeSig, timeSigName, sigType, arrayName, arrayIndices, nScalarSignals) = getSignalDetails(result,name) if isnothing(sig) @warn "\"$name\" is not correct or is not defined or has no values." end return (sig, timeSig, timeSigName, sigType, arrayName, arrayIndices, nScalarSignals) end appendUnit2(name, unit) = unit == "" ? name : string(name, " [", unit, "]") function appendUnit(name, value) if typeof(value) <: MonteCarloMeasurements.StaticParticles || typeof(value) <: MonteCarloMeasurements.Particles appendUnit2(name, string(unit(value.particles[1]))) else appendUnit2(name, string(unit(value))) end end """ (xsig, xsigLegend, ysig, ysigLegend, ysigType) = getPlotSignal(result, ysigName; xsigName=nothing) Given the result data structure `result` and a variable `ysigName::AbstractString` with or without array range indices (for example `ysigName = "a.b.c[2,3:5]"`) and an optional variable name `xsigName::AbstractString` for the x-axis, return - `xsig::Vector{T1<:Real}`: The vector of the x-axis signal without a unit. Segments are concatenated and separated by NaN. - `xsigLegend::AbstractString`: The legend of the x-axis consisting of the x-axis name and its unit (if available). - `ysig::Vector{T2}` or `::Matrix{T2}`: the y-axis signal, either as a vector or as a matrix of values without units depending on the given name. For example, if `ysigName = "a.b.c[2,3:5]"`, then `ysig` consists of a matrix with three columns corresponding to the variable values of `"a.b.c[2,3]", "a.b.c[2,4]", "a.b.c[2,5]"` with the (potential) units are stripped off. Segments are concatenated and separated by NaN. - `ysigLegend::Vector{AbstractString}`: The legend of the y-axis as a vector of strings, where `ysigLegend[1]` is the legend for `ysig`, if `ysig` is a vector, and `ysigLegend[i]` is the legend for the i-th column of `ysig`, if `ysig` is a matrix. For example, if variable `"a.b.c"` has unit `m/s`, then `ysigName = "a.b.c[2,3:5]"` results in `ysigLegend = ["a.b.c[2,3] [m/s]", "a.b.c[2,3] [m/s]", "a.b.c[2,5] [m/s]"]`. - `ysigType::`[`SignalType`](@ref): The signal type of `ysig` (either `ModiaResult.Continuous` or `ModiaResult.Clocked`). If `ysigName` is not valid, or no signal values are available, the function returns `(nothing, nothing, nothing, nothing, nothing)`, and prints a warning message. """ function getPlotSignal(result, ysigName::AbstractString; xsigName=nothing) (ysig, xsig, timeSigName, ysigType, ysigArrayName, ysigArrayIndices, nysigScalarSignals) = getSignalDetailsWithWarning(result, ysigName) # Check y-axis signal and time signal if isnothing(ysig) || isnothing(xsig) || isnothing(timeSigName) || signalLength(ysig) == 0 @goto ERROR end # Get xSigName or check xSigName if isnothing(xsigName) xsigName = timeSigName elseif xsigName != timeSigName (xsig, xsigTime, xsigTimeName, xsigType, xsigArrayName, xsigArrayIndices, nxsigScalarSignals) = getSignalDetailsWithWarning(result, xsigName) if isnothing(xsig) || isnothing(xsigTime) || isnothing(xsigTimeName) || signalLength(xsig) == 0 @goto ERROR elseif !hasSameSegments(ysig, xsig) @warn "\"$xsigName\" (= x-axis) and \"$ysigName\" (= y-axis) have not the same time signal vector." @goto ERROR end end # Check x-axis signal xsigValue = first(first(xsig)) if length(xsigValue) != 1 @warn "\"$xsigName\" does not characterize a scalar variable as needed for the x-axis." @goto ERROR elseif !( typeof(xsigValue) <: Number ) @warn "\"$xsigName\" has no Number type values, but values of type " * string(typeof(xsigValue)) * "." @goto ERROR elseif typeof(xsigValue) <: Measurements.Measurement @warn "\"$xsigName\" is a Measurements.Measurement type and this is not (yet) supported for the x-axis." @goto ERROR elseif typeof(xsigValue) <: MonteCarloMeasurements.StaticParticles @warn "\"$xsigName\" is a MonteCarloMeasurements.StaticParticles type and this is not supported for the x-axis." @goto ERROR elseif typeof(xsigValue) <: MonteCarloMeasurements.Particles @warn "\"$xsigName\" is a MonteCarloMeasurements.Particles type and this is not supported for the x-axis." @goto ERROR end # Build xsigLegend xsigLegend = appendUnit(xsigName, xsigValue) # Get one segment of the y-axis and check it ysegment1 = first(ysig) if !( typeof(ysegment1) <: AbstractVector || typeof(ysegment1) <: AbstractMatrix ) @error "Bug in function: typeof of an y-axis segment is neither a vector nor a Matrix, but " * string(typeof(ysegment1)) elseif !(eltype(ysegment1) <: Number) @warn "\"$ysigName\" has no Number values but values of type " * string(eltype(ysegment1)) @goto ERROR end # Build ysigLegend value = ysegment1[1] if ysigArrayIndices == () # ysigName is a scalar variable ysigLegend = [appendUnit(ysigName, value)] else # ysigName is an array variable ysigLegend = [ysigArrayName * "[" for i = 1:nysigScalarSignals] i = 1 ySizeLength = Int[] for j1 in eachindex(ysigArrayIndices) push!(ySizeLength, length(ysigArrayIndices[j1])) i = 1 if j1 == 1 for j2 in 1:div(nysigScalarSignals, ySizeLength[1]) for j3 in ysigArrayIndices[1] ysigLegend[i] *= string(j3) i += 1 end end else ncum = prod( ySizeLength[1:j1-1] ) for j2 in ysigArrayIndices[j1] for j3 = 1:ncum ysigLegend[i] *= "," * string(j2) i += 1 end end end end for i = 1:nysigScalarSignals ysigLegend[i] *= appendUnit("]", ysegment1[1,i]) end end #xsig2 = Vector{Any}(undef, length(xsig)) #ysig2 = Vector{Any}(undef, length(ysig)) #for i = 1:length(xsig) # xsig2[i] = collect(ustrip.(xsig[i])) # ysig2[i] = collect(ustrip.(ysig[i])) #end #xsig2 = collect(ustrip.(first(xsig))) xsig2 = ustrip.(collect(first(xsig))) ysig2 = collect(ustrip.(first(ysig))) if length(xsig) > 1 xNaN = convert(eltype(xsig2), NaN) if ndims(ysig2) == 1 yNaN = convert(eltype(ysig2), NaN) else yNaN = fill(convert(eltype(ysig2), NaN), 1, size(ysig2,2)) end for i = 2:length(xsig) xsig2 = vcat(xsig2, xNaN, collect((xsig[i]))) ysig2 = vcat(ysig2, yNaN, collect(ustrip.(ysig[i]))) end end return (xsig2, xsigLegend, ysig2, ysigLegend, ysigType) @label ERROR return (nothing, nothing, nothing, nothing, nothing) end """ getHeading(result, heading) Return `heading` if no empty string. Otherwise, return `defaultHeading(result)`. """ getHeading(result, heading::AbstractString) = heading != "" ? heading : defaultHeading(result) """ prepend!(prefix, signalLegend) Add `prefix` string in front of every element of the `signalLegend` string-Vector. """ function prepend!(prefix::AbstractString, signalLegend::Vector{AbstractString}) for i in eachindex(signalLegend) signalLegend[i] = prefix*signalLegend[i] end return signalLegend end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
11884
# License for this file: MIT (expat) # Copyright 2020-2021, DLR Institute of System Dynamics and Control # # This file is part of module ModiaResult (is included by the ModiaPlot_XXMakie packages). export plot, showFigure, saveFigure, closeFigure, closeAllFigures #--------------------------- Utility definitions # color definitions const colors = ["blue1", "green4", "red1", "cyan1", "purple1", "orange1", "black", "blue2", "green3", "red2", "cyan2", "purple2", "orange2", "grey20", "blue3", "green2", "red3", "cyan3", "purple3", "orange3", "grey30", "blue4", "green1", "red4", "cyan4", "purple4", "orange4", "grey40"] mutable struct Diagram fig axis row::Int col::Int curves::Union{AbstractVector, Nothing} yLegend::Union{AbstractVector, Nothing} function Diagram(fig,row,col,title) axis = fig[row,col] = Axis(fig, title=title) new(fig, axis, row, col, nothing, nothing) end end # figures[i] is Figure instance of figureNumber = i const figures = Dict{Int,Any}() # Dictionary of MatrixFigures mutable struct MatrixFigure fig resolution diagrams::Union{Matrix{Diagram},Nothing} function MatrixFigure(figureNumber::Int, nrow::Int, ncol::Int, reuse::Bool, resolution) if haskey(figures, figureNumber) && reuse # Reuse existing figure matrixFigure = figures[figureNumber] if isnothing(matrixFigure.diagrams) || size(matrixFigure.diagrams) != (nrow,ncol) error("From ModiaPlot.plot: reuse=true, but figure=$figureNumber has not $nrow rows and $ncol columns.") end else # Create a new figure fig = Figure(resolution=resolution) diagrams = Matrix{Diagram}(undef,nrow,ncol) matrixFigure = new(fig, resolution, diagrams) figures[figureNumber] = matrixFigure end return matrixFigure end end getMatrixFigure(figureNumber::Int) = figures[figureNumber] setTheme() = set_theme!(fontsize = 12) """ getColor(i::Int) Return color, given an integer (from colors) """ function getColor(i::Int) j = mod(i, length(colors)) if j == 0 j = length(colors) end return colors[j] end """ createLegend(diagram::Diagram, maxLegend) Create a new legend in diagram """ function createLegend(diagram::Diagram, maxLegend::Int)::Nothing curves = diagram.curves yLegend = diagram.yLegend if length(curves) > 1 nc = min(length(curves), maxLegend) curves = curves[1:nc] yLegend = yLegend[1:nc] end fig = diagram.fig i = diagram.row j = diagram.col fig[i,j] = Legend(fig, curves, yLegend, margin=[0,0,0,0], padding=[5,5,0,0], rowgap=0, halign=:right, valign=:top, linewidth=1, labelsize=10, tellheight=false, tellwidth=false) return nothing end const reltol = 0.001 function sig_max(xsig, y_min, y_max) dy = y_max - y_min abstol = typemax(eltype(y_min)) for (i,v) in enumerate(dy) if v > 0.0 && v < abstol abstol = v end end @assert(abstol > 0.0) y_max2 = similar(y_max) for (i,value) = enumerate(y_max) y_max2[i] = max(y_max[i], y_min[i] + max(abstol, abs(y_min[i])*reltol)) end return y_max2 end # Something of the following is required in the file where makie.jl is included: # const Makie_Point2f = isdefined(GLMakie, :Point2f) ? Point2f : Point2f0 function fill_between(axis, xsig, ysig_min, ysig_max, color) ysig_max2 = sig_max(xsig, ysig_min, ysig_max) sig = Makie_Point2f.(xsig,ysig_min) append!(sig, reverse(Makie_Point2f.(xsig,ysig_max2))) push!(sig, sig[1]) return poly!(axis, sig, color = color) end function plotOneSignal(axis, xsig, ysig, color, ysigType, MonteCarloAsArea) if typeof(ysig[1]) <: Measurements.Measurement # Plot mean value signal xsig_mean = Measurements.value.(xsig) ysig_mean = Measurements.value.(ysig) curve = lines!(axis, xsig_mean, ysig_mean, color=color) # Plot area of uncertainty around mean value signal (use the same color, but transparent) ysig_u = Measurements.uncertainty.(ysig) ysig_max = ysig_mean + ysig_u ysig_min = ysig_mean - ysig_u fill_between(axis, xsig_mean, ysig_min, ysig_max, (color,0.2)) elseif typeof(ysig[1]) <: MonteCarloMeasurements.StaticParticles || typeof(ysig[1]) <: MonteCarloMeasurements.Particles # Plot mean value signal pfunctionsDefined = isdefined(MonteCarloMeasurements, :pmean) if pfunctionsDefined # MonteCarlMeasurements, version >= 1.0 xsig_mean = MonteCarloMeasurements.pmean.(xsig) ysig_mean = MonteCarloMeasurements.pmean.(ysig) else # MonteCarloMeasurements, version < 1.0 xsig_mean = MonteCarloMeasurements.mean.(xsig) ysig_mean = MonteCarloMeasurements.mean.(ysig) end xsig_mean = ustrip.(xsig_mean) ysig_mean = ustrip.(ysig_mean) curve = lines!(axis, xsig_mean, ysig_mean, color=color) if MonteCarloAsArea # Plot area of uncertainty around mean value signal (use the same color, but transparent) if pfunctionsDefined # MonteCarlMeasurements, version >= 1.0 ysig_max = MonteCarloMeasurements.pmaximum.(ysig) ysig_min = MonteCarloMeasurements.pminimum.(ysig) else # MonteCarloMeasurements, version < 1.0 ysig_max = MonteCarloMeasurements.maximum.(ysig) ysig_min = MonteCarloMeasurements.minimum.(ysig) end ysig_max = ustrip.(ysig_max) ysig_min = ustrip.(ysig_min) fill_between(axis, xsig_mean, ysig_min, ysig_max, (color,0.2)) else # Plot all particle signals value = ysig[1].particles ysig3 = zeros(eltype(value), length(xsig)) for j in 1:length(value) for i in eachindex(ysig) ysig3[i] = ysig[i].particles[j] end ysig3 = ustrip.(ysig3) lines!(axis, xsig, ysig3, color=(color,0.1)) end end else if typeof(xsig[1]) <: Measurements.Measurement xsig = Measurements.value.(xsig) elseif typeof(xsig[1]) <: MonteCarloMeasurements.StaticParticles || typeof(xsig[1]) <: MonteCarloMeasurements.Particles if isdefined(MonteCarloMeasurements, :pmean) # MonteCarlMeasurements, version >= 1.0 xsig = MonteCarloMeasurements.pmean.(xsig) else # MonteCarlMeasurements, version < 1.0 xsig = MonteCarloMeasurements.mean.(xsig) end xsig = ustrip.(xsig) end if ysigType == ModiaResult.Clocked curve = scatter!(axis, xsig, ysig, color=color, markersize = 2.0) else curve = lines!(axis, xsig, ysig, color=color) end end return curve end function addPlot(names::Tuple, diagram::Diagram, result, grid::Bool, xLabel::Bool, xAxis, prefix::AbstractString, reuse::Bool, maxLegend::Integer, MonteCarloAsArea::Bool) xsigLegend = "" yLegend = String[] curves = Any[] i0 = isnothing(diagram.curves) ? 0 : length(diagram.curves) for name in names name2 = string(name) (xsig, xsigLegend, ysig, ysigLegend, ysigType) = ModiaResult.getPlotSignal(result, name2; xsigName = xAxis) if !isnothing(xsig) if ndims(ysig) == 1 push!(yLegend, prefix*ysigLegend[1]) push!(curves, plotOneSignal(diagram.axis, xsig, ysig, getColor(i0+1), ysigType, MonteCarloAsArea)) i0 = i0 + 1 else for i = 1:size(ysig,2) curve = plotOneSignal(diagram.axis, xsig, ysig[:,i], getColor(i0+i), ysigType, MonteCarloAsArea) push!(yLegend, prefix*ysigLegend[i]) push!(curves, curve) end i0 = i0 + size(ysig,2) end end end #PyPlot.grid(grid) if reuse diagram.curves = append!(diagram.curves, curves) diagram.yLegend = append!(diagram.yLegend, yLegend) else diagram.curves = curves diagram.yLegend = yLegend end createLegend(diagram, maxLegend) if xLabel && !reuse && xsigLegend !== nothing diagram.axis.xlabel = xsigLegend end end addPlot(name::AbstractString, args...) = addPlot((name,) , args...) addPlot(name::Symbol , args...) = addPlot((string(name),), args...) #--------------------------- Plot function function plot(result, names::AbstractMatrix; heading::AbstractString="", grid::Bool=true, xAxis=nothing, figure::Int=1, prefix::AbstractString="", reuse::Bool=false, maxLegend::Integer=10, minXaxisTickLabels::Bool=false, MonteCarloAsArea=false) if isnothing(result) @info "The call of ModiaPlot.plot(result, ...) is ignored, since the first argument is nothing." return end if !reusePossible reuse=false end # Plot a vector or matrix of diagrams setTheme() (nrow, ncol) = size(names) matrixFigure = MatrixFigure(figure, nrow, ncol, reuse, (min(ncol*600,1500), min(nrow*350, 900))) fig = matrixFigure.fig xAxis2 = isnothing(xAxis) ? xAxis : string(xAxis) heading2 = ModiaResult.getHeading(result, heading) hasTopHeading = !reuse && ncol > 1 && heading2 != "" # Add diagrams lastRow = true xLabel = true for i = 1:nrow lastRow = i == nrow for j = 1:ncol if reuse diagram = matrixFigure.diagrams[i,j] else if ncol == 1 && i == 1 && !hasTopHeading diagram = Diagram(fig, i, j, heading2) else diagram = Diagram(fig, i, j, "") end matrixFigure.diagrams[i,j] = diagram end xLabel = !( minXaxisTickLabels && !lastRow ) addPlot(names[i,j], diagram, result, grid, xLabel, xAxis2, prefix, reuse, maxLegend, MonteCarloAsArea) end end # Add overall heading in case of a matrix of diagrams (ncol > 1) and add a figure label on the top level if hasTopHeading fig[0,:] = Label(fig, heading2, textsize = 14) end if showFigureStringInDiagram figText = fig[1,1,TopLeft()] = Label(fig, "showFigure(" * string(figure) * ")", textsize=9, color=:blue, halign = :left) if hasTopHeading figText.padding = (0, 0, 5, 0) else figText.padding = (0, 0, 30, 0) end end # Update and display fig trim!(fig.layout) #update!(fig.scene) if callDisplayFunction display(fig) end return matrixFigure end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
7357
# License for this file: MIT (expat) # Copyright 2020-2021, DLR Institute of System Dynamics and Control # # This file is part of module ModiaResult (is included by the ModiaPlot_xxxMakie packages). """ plot(result, names; heading = "", grid = true, xAxis = nothing, figure = 1, prefix = "", reuse = false, maxLegend = 10, minXaxisTickLabels = false, MonteCarloAsArea = true) Generate **line plots** of the signals of the `result` data structure that are identified with the `names` keys using the plot package defined with `ModiaResult.@usePlotPackage(xxx)`. Possible values for `xxx`: `"GLMakie", "WGLMakie", "CairoMakie", "PyPlot", "NoPlot", "SilentNoPlot"`). `result` is any data structures that supports the abstract interface of `ModiaResult`. Currently these are: - `result::ModiaResult.ResultDict` - `result::AbstractDict{String,T}` - `result::DataFrames.DataFrame` - `result` supports the `Tables.jl` interface with `Tables.columnaccess(result) = true`. Argument `names` defines the diagrams to be drawn and the result data to be included in the respective diagram: - If `names` is a **String**, generate one diagram with one time series of the variable with key `names`. - If `names` is a **Tuple** of Strings, generate one diagram with the time series of the variables with the keys given in the tuple. - If names is a **Vector** or a **Matrix** of **Strings** and/or **Tuples**, generate a vector or matrix of diagrams. Note, the names (and their units, if available in the result) are automatically used as legends in the respective diagram. A signal variable identified by a `String` key can be a scalar of type `<:Number` or an array of element type `<:Number`. A signal is defined by a vector of time values, a corresponding vector of signal values, and the signal type (continuous or clocked). Note, before passing data to the plot package, it is converted to Float64. This allows to, for example, also plot rational numbers, even if not supported by the plot package. `Measurements.Measurement{xxx}` and `MonteCarloMeasurements` is specially handled. # Optional Arguments - `heading::AbstractString`: Optional heading above the diagram. - `grid::Bool`: = true, to display a grid. - `xAxis::Union{AbstractString,Nothing}`: Name of x-axis. If `xAxis=nothing`, the independent variable of the result (usually `"time"` is used as x-axis. - `figure::Int`: Integer identifier of the window in which the diagrams shall be drawn. - `prefix::AbstractString`: String that is appended in front of every legend label (useful especially if `reuse=true`). - `reuse::Bool`: If figure already exists and reuse=false, clear the figure before adding the plot. Otherwise, include the plot in the existing figure without removing the curves present in the figure. `reuse = true` is ignored for `"WGLMakie"` (because not supported). - `maxLegend::Int`: If the number of legend entries in one plot command `> maxLegend`, the legend is suppressed. All curves have still their names as labels. In PyPlot, the curves can be inspected by their names by clicking in the toolbar of the plot on button `Edit axis, curve ..` and then on `Curves`. - `minXaxisTickLabels::Bool`: = true, if xaxis tick labels shall be removed in a vector or array of plots, if not the last row (useful when including plots in a document). = false, x axis tick labels are always shown (useful when interactively zooming into a plot). - `MonteCarloAsArea::Bool`: = true, if MonteCarloMeasurements values are shown with the mean value and the area between the minimum and the maximum value of all particles. = false, if all particles of MonteCarloMeasurements values are shown (e.g. if a value has 2000 particles, then 2000 curves are shown in the diagram). # Examples ```julia import ModiaResult using Unitful # Generate "using xxx" statement # (where "xxx" is from a previous ModiaResult.usePlotPackage("xxx")) ModiaResult.@usingModiaPlot # Construct result data t = range(0.0, stop=10.0, length=100); result = Dict{String,Any}(); result["time"] = t*u"s"; result["phi"] = sin.(t)*u"rad"; result["w"] = cos.(t)*u"rad/s"; result["a"] = 1.2*sin.(t)*u"rad/s^2"; result["r"] = hcat(0.4 * cos.(t), 0.5 * sin.(t), 0.3*cos.(t))*u"m"; # 1 signal in one diagram (legend = "phi [rad]") plot(result, "phi") # 3 signals in one diagram plot(result, ("phi", "w", "a"), figure=2) # 3 diagrams in form of a vector (every diagram has one signal) plot(result, ["phi", "w", "r"], figure=3) # 4 diagrams in form of a matrix (every diagram has one signal) plot(result, ["phi" "w"; "a" "r[2]" ], figure=4) # 2 diagrams in form of a vector plot(result, [ ("phi", "w"), ("a") ], figure=5) # 4 diagrams in form of a matrix plot(result, [ ("phi",) ("phi", "w"); ("phi", "w", "a") ("r[2:3]",) ],figure=6) # Plot w=f(phi) in one diagram plot(result, "w", xAxis="phi", figure=7) # Append signal of the next simulation run to figure=1 # (legend = "Sim 2: phi [rad]") result["phi"] = 0.5*result["phi"]; plot(result, "phi", prefix="Sim 2: ", reuse=true) ``` Example of a matrix of plots: ![Matrix of plots](../resources/images/matrix-of-plots.png) """ plot(result, names::AbstractString; kwargs...) = plot(result, [names] ; kwargs...) plot(result, names::Symbol ; kwargs...) = plot(result, [string(names)]; kwargs...) plot(result, names::Tuple ; kwargs...) = plot(result, [names] ; kwargs...) plot(result, names::AbstractVector; kwargs...) = plot(result, reshape(names, length(names), 1); kwargs...) """ showFigure(figure) | Plot package | Effect | |:-------------|:------------------------------------| | GLMakie | Show `figure` in the single window. | | WGLMakie | Show `figure` in the single window. | | CairoMakie | Call is ignored | | PyPlot | Call is ignored | | NoPlot | Call is ignored | # Example ```julia import ModiaResult ModiaResult.@usingModiaPlot ... plot(..., figure=1) plot(..., figure=2) plot(..., figure=3) showFigure(2) showFigure(1) ``` """ function showFigure end """ saveFigure(figure, file; kwargs...) Save figure on file. The file extension defines the image format (for example `*.png`). | Plot package | Supported file extensions | |:-------------|:------------------------------------| | GLMakie | png, jpg, bmp | | WGLMakie | png | | CairoMakie | png, pdf, svg, eps | | PyPlot | depends on [backend](https://matplotlib.org/stable/tutorials/introductory/usage.html) (png, pdf, jpg, tiff, svg, ps, eps) | | NoPlot | Call is ignored | # Keyword arguments - resolution: (width::Int, height::Int) of the scene in dimensionless units (equivalent to px for GLMakie and WGLMakie). # Example ```julia import ModiaResult ModiaResult.@usingModiaPlot ... plot(..., figure=1) plot(..., figure=2) saveFigure(1, "plot.png") # save in png-format saveFigure(2, "plot.svg") # save in svg-format ``` """ function saveFigure end """ closeFigure(figure) Close `figure`. """ function closeFigure end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
1122
include("test_01_OneScalarSignal.jl") include("test_02_OneScalarSignalWithUnit.jl") include("test_03_OneVectorSignalWithUnit.jl") include("test_04_ConstantSignalsWithUnit.jl") include("test_05_ArraySignalsWithUnit.jl") include("test_06_OneScalarMeasurementSignal.jl") include("test_07_OneScalarMeasurementSignalWithUnit.jl") include("test_20_SeveralSignalsInOneDiagram.jl") include("test_21_VectorOfPlots.jl") include("test_22_MatrixOfPlots.jl") include("test_23_MatrixOfPlotsWithTimeLabelsInLastRow.jl") include("test_24_Reuse.jl") include("test_25_SeveralFigures.jl") include("test_26_TooManyLegends.jl") include("test_51_OneScalarMonteCarloMeasurementsSignal.jl") include("test_52_MonteCarloMeasurementsWithDistributions.jl") include("test_70_ResultDict.jl") # include("test_71_Tables_Rotational_First.jl") # deactivated, because "using CSV" include("test_72_ResultDictWithMatrixOfPlots.jl") include("test_80_Warnings.jl") include("test_81_SaveFigure.jl") include("test_82_AllExportedFunctions.jl") # include("test_90_CompareOneScalarSignal.jl") # include("test_91_CompareOneScalarSignalWithUnit.jl")
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
263
module Runtests # Run all tests with SilentNoPlot (so not plots) import ModiaResult using Test @testset "Test ModiaResult/test" begin ModiaResult.usePlotPackage("SilentNoPlot") include("include_all.jl") ModiaResult.usePreviousPlotPackage() end end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
256
module Runtests_withPlot # Run all tests with the activated plot package import ModiaResult using Test const test_title = "Tests with plot package " * ModiaResult.currentPlotPackage() @testset "$test_title" begin include("include_all.jl") end end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
366
module test_01_OneScalarSignal using ModiaResult using ModiaResult.OrderedCollections ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) result = OrderedDict{String,Any}() result["time"] = t result["phi"] = sin.(t) println("\n... test_01_OneScalarSignal.jl:\n") ModiaResult.printResultInfo(result) plot(result, "phi", heading="sine(time)") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
420
module test_02_OneScalarSignalWithUnit using ModiaResult using ModiaResult.Unitful using ModiaResult.OrderedCollections ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) result = OrderedDict{String,Any}() result["time"] = t*u"s" result["phi"] = sin.(t)*u"rad" println("\n... test_02_OneScalarSignalWithUnit.jl:\n") ModiaResult.printResultInfo(result) plot(result, "phi", heading="Sine(time)") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
551
module test_03_OneVectorSignalWithUnit using ModiaResult using ModiaResult.Unitful using ModiaResult.OrderedCollections ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) result = OrderedDict{String,Any}() result["time"] = t*u"s" result["r"] = [[0.4 * cos(t[i]), 0.5 * sin(t[i]), 0.3 * cos(t[i])] for i in eachindex(t)]*u"m" println("\n... test_03_OneVectorSignalWithUnit.jl:") ModiaResult.printResultInfo(result) plot(result, ["r", "r[2]", "r[2:3]"], heading="Plot vector signals") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
691
module test_04_ConstantSignalsWithUnit using ModiaResult using ModiaResult.Unitful using ModiaResult.OrderedCollections ModiaResult.@usingModiaPlot inertia = [1.1 1.2 1.3; 2.1 2.2 2.3; 3.1 3.2 3.3]u"kg*m^2" result = OrderedDict{String,Any}() result["time"] = [0.0, 1.0]*u"s" result["phi_max"] = [1.1f0, 1.1f0]*u"rad" result["i_max"] = [2, 2] result["open"] = [true , true] result["Inertia"] = [inertia, inertia] println("\n... test_04_ConstantSignalsWithUnit.jl:") ModiaResult.printResultInfo(result) plot(result, ["phi_max", "i_max", "open", "Inertia[2,2]", "Inertia[1,2:3]", "Inertia"], heading="Constants") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
554
module test_05_ArraySignalsWithUnit using ModiaResult using ModiaResult.Unitful using ModiaResult.OrderedCollections ModiaResult.@usingModiaPlot t = range(0.0, stop=1.0, length=100) result = OrderedDict{String,Any}() Ibase = [1.1 1.2 1.3; 2.1 2.2 2.3; 3.1 3.2 3.3]u"kg*m^2" result["time"] = t*u"s" result["Inertia"] = [Ibase*t[i] for i in eachindex(t)] println("\n... test_05_ArraySignalsWithUnit:") ModiaResult.printResultInfo(result) plot(result, ["Inertia[2,2]", "Inertia[2:3,3]"], heading="Array signals") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
518
module test_06_OneScalarMeasurementSignal using ModiaResult using ModiaResult.OrderedCollections using ModiaResult.Unitful using ModiaResult.Measurements ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) c = ones(size(t,1)) result = OrderedDict{String,Any}() result["time"] = t result["phi"] = [sin(t[i]) ± 0.1*c[i] for i in eachindex(t)] println("\n... test_06_OneScalarMeasurementSignal.jl:") ModiaResult.printResultInfo(result) plot(result, "phi", heading="Sine(time) with Measurement") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
544
module test_07_OneScalarMeasurementSignalWithUnit using ModiaResult using ModiaResult.OrderedCollections using ModiaResult.Unitful using ModiaResult.Measurements ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) c = ones(size(t,1)) result = OrderedDict{String,Any}() result["time"] = t*u"s" result["phi"] = [sin(t[i]) ± 0.1*c[i] for i in eachindex(t)]*u"rad" println("\n... test_07_OneScalarMeasurementSignalWithUnit:") ModiaResult.printResultInfo(result) plot(result, "phi", heading="Sine(time) with Measurement") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
636
module test_20_SeveralSignalsInOneDiagram using ModiaResult using ModiaResult.Unitful using ModiaResult.OrderedCollections ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) result = OrderedDict{String,Any}() result["time"] = t*u"s" result["phi"] = sin.(t)u"rad" result["phi2"] = 0.5 * sin.(t)u"rad" result["w"] = cos.(t)u"rad/s" result["w2"] = 0.6 * cos.(t)u"rad/s" result["A"] = ModiaResult.OneValueVector(0.6, length(t)) println("\n... test_20_SeveralSignalsInOneDiagram:") ModiaResult.printResultInfo(result) plot(result, ("phi", "phi2", "w", "w2", "A"), heading="Several signals in one diagram") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
547
module test_21_VectorOfPlots using ModiaResult using ModiaResult.Unitful using ModiaResult.OrderedCollections ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) result = OrderedDict{String,Any}() result["time"] = t*u"s" result["phi"] = sin.(t)u"rad" result["phi2"] = 0.5 * sin.(t)u"rad" result["w"] = cos.(t)u"rad/s" result["w2"] = 0.6 * cos.(t)u"rad/s" println("\n... test_21_VectorOfPlots:") ModiaResult.printResultInfo(result) plot(result, ["phi2", ("w",), ("phi", "phi2", "w", "w2")], heading="Vector of plots") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
741
module test_22_MatrixOfPlots using ModiaResult using ModiaResult.OrderedCollections using ModiaResult.Unitful ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) result = OrderedDict{String,Any}() result["time"] = t*u"s" result["phi"] = sin.(t)u"rad" result["phi2"] = 0.5 * sin.(t)u"rad" result["w"] = cos.(t)u"rad/s" result["w2"] = 0.6 * cos.(t)u"rad/s" result["r"] = [[0.4 * cos(t[i]), 0.5 * sin(t[i]), 0.3 * cos(t[i])] for i in eachindex(t)]*u"m" println("\n... test_22_MatrixOfPlots:") ModiaResult.printResultInfo(result) plot(result, [ ("phi", "r") ("phi", "phi2", "w"); ("w", "w2", "phi2") "w" ], heading="Matrix of plots") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
874
module test_23_MatrixOfPlotsWithTimeLabelsInLastRow using ModiaResult using ModiaResult.OrderedCollections using ModiaResult.Unitful ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) result = OrderedDict{String,Any}() result["time"] = t*u"s" result["phi"] = sin.(t)u"rad" result["phi2"] = 0.5 * sin.(t)u"rad" result["w"] = cos.(t)u"rad/s" result["w2"] = 0.6 * cos.(t)u"rad/s" result["r"] = [[0.4 * cos(t[i]), 0.5 * sin(t[i]), 0.3 * cos(t[i])] for i in eachindex(t)]*u"m" println("\n... test_23_MatrixOfPlotsWithTimeLabelsInLastRow:") ModiaResult.printResultInfo(result) plot(result, [ ("phi", "r") ("phi", "phi2", "w"); ("w", "w2", "phi2") ("phi", "w") ], minXaxisTickLabels = true, heading="Matrix of plots with time labels in last row") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
671
module test_24_Reuse using ModiaResult using ModiaResult.Unitful using ModiaResult.OrderedCollections ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) result1 = OrderedDict{String,Any}() result1["time"] = t*u"s" result1["phi"] = sin.(t)u"rad" result1["w"] = cos.(t)u"rad/s" result2 = OrderedDict{String,Any}() result2["time"] = t*u"s" result2["phi"] = 1.2*sin.(t)u"rad" result2["w"] = 0.8*cos.(t)u"rad/s" println("\n... test_24_Reuse:") ModiaResult.printResultInfo(result1) ModiaResult.printResultInfo(result2) plot(result1, ("phi", "w"), prefix="Sim 1:", heading="Test reuse") plot(result2, ("phi", "w"), prefix="Sim 2:", reuse=true) end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
809
module test_25_SeveralFigures using ModiaResult using ModiaResult.OrderedCollections using ModiaResult.Unitful ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) result = OrderedDict{String,Any}() result["time"] = t*u"s" result["phi"] = sin.(t)u"rad" result["phi2"] = 0.5 * sin.(t)u"rad" result["w"] = cos.(t)u"rad/s" result["w2"] = 0.6 * cos.(t)u"rad/s" result["r"] = [[0.4 * cos(t[i]), 0.5 * sin(t[i]), 0.3 * cos(t[i])] for i in eachindex(t)]*u"m" println("\n... test_25_SeveralFigures:") ModiaResult.printResultInfo(result) plot(result, ("phi", "r") , heading="First figure" , figure=1) plot(result, ["w", "w2", "r[2]"], heading="Second figure", figure=2) plot(result, "r" , heading="Third figure" , figure=3) end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
698
module test_26_TooManyLegends using ModiaResult using ModiaResult.OrderedCollections using ModiaResult.Unitful ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) result = OrderedDict{String,Any}() result["time"] = t*u"s" result["phi"] = sin.(t)u"rad" result["phi2"] = 0.5 * sin.(t)u"rad" result["w"] = cos.(t)u"rad/s" result["w2"] = 0.6 * cos.(t)u"rad/s" result["r"] = [[0.4 * cos(t[i]), 0.5 * sin(t[i]), 0.3 * cos(t[i])] for i in eachindex(t)]*u"m" println("\n... test_26_TooManyLegends:") ModiaResult.printResultInfo(result) plot(result, ("phi", "r", "w", "w2"), maxLegend = 5, heading = "Too many legends") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
593
module test_51_OneScalarMonteCarloMeasurementsSignal using ModiaResult using ModiaResult.OrderedCollections using ModiaResult.Unitful using ModiaResult.MonteCarloMeasurements ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) c = ones(size(t,1)) result = OrderedDict{String,Any}() result["time"] = t*u"s" result["phi"] = [sin(t[i]) ± 0.1*c[i] for i in eachindex(t)]*u"rad" println("\n... test_51_OneScalarMonteCarloMeasurementsSignal:") ModiaResult.printResultInfo(result) plot(result, "phi", MonteCarloAsArea=true, heading="Sine(time) with MonteCarloMeasurements") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
1295
module test_52_MonteCarloMeasurementsWithDistributions using ModiaResult using ModiaResult.OrderedCollections using ModiaResult.Unitful using ModiaResult.MonteCarloMeasurements using ModiaResult.MonteCarloMeasurements.Distributions ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) uniform1(xmin,xmax) = MonteCarloMeasurements.Particles( 100,Distributions.Uniform(xmin,xmax)) uniform2(xmin,xmax) = MonteCarloMeasurements.StaticParticles(100,Distributions.Uniform(xmin,xmax)) particles1 = uniform1(-0.4, 0.4) particles2 = uniform2(-0.4, 0.4) result = OrderedDict{String,Any}() # ∓ are 100 StaticParticles uniform distribution result["time"] = t*u"s" result["phi1"] = [sin(t[i]) + particles1*t[i]/10.0 for i in eachindex(t)]*u"rad" result["phi2"] = [sin(t[i]) + particles2*t[i]/10.0 for i in eachindex(t)]*u"rad" result["phi3"] = [sin(t[i]) ∓ 0.4*t[i]/10.0 for i in eachindex(t)]*u"rad" println("\n... test_52_MonteCarloMeasurementsWithDistributions:") ModiaResult.printResultInfo(result) plot(result, ["phi1", "phi2", "phi3"], figure=1, heading="Sine(time) with MonteCarloParticles/StaticParticles (plot area)") plot(result, ["phi1", "phi2", "phi3"], figure=2, heading="Sine(time) with MonteCarloParticles/StaticParticles (plot all runs)") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
996
module test_0_ResultDict using ModiaResult using ModiaResult.Unitful ModiaResult.@usingModiaPlot time0 = [0.0, 15.0] t = ([time0], [time0], ModiaResult.Independent) time1 = 0.0 : 0.1 : 3.0 time2 = 5.0 : 0.1 : 9.5 time3 = 11.0 : 0.1 : 15.0 time4 = 0.0 : 0.1 : 15.0 sigA1 = 0.9*sin.(time1)u"m" sigA2 = cos.(time2)u"m" sigA3 = 1.1*sin.(time3)u"m" sigA = ([time1, time2, time3], [sigA1, sigA2, sigA3 ], ModiaResult.Continuous) sigB = ([time4], [0.7*sin.(time4)u"m/s"], ModiaResult.Continuous) sigC = ([time2], [sin.(time2)u"N*m"] , ModiaResult.Clocked) result = ModiaResult.ResultDict("time" => t, "sigA" => sigA, "sigB" => sigB, "sigC" => sigC, defaultHeading = "Signals from test_70_ResultDict.jl") println("\n... test_70_ResultDict.jl:\n") ModiaResult.printResultInfo(result) plot(result, ("sigA", "sigB", "sigC")) end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
647
module test_71_Tables_Rotational_First using ModiaResult using ModiaResult.DataFrames using CSV ModiaResult.@usingModiaPlot result1 = CSV.File("$(ModiaResult.path)/test/test_71_Tables_Rotational_First.csv") result2 = DataFrames.DataFrame(result1) println("\n... test_71_Tables_Rotational_First.jl:") println("CSV-Table (result1 = CSV.File(fileName)):\n") ModiaResult.printResultInfo(result1) println("\nDataFrame-Table (result2 = DataFrame(result1)):\n") ModiaResult.printResultInfo(result2) plot(result1, ["damper.w_rel", "inertia3.w"], prefix="result1: ") plot(result2, ["damper.w_rel", "inertia3.w"], prefix="result2: ", reuse=true) end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
1308
module test_72_ResultDictWithMatrixOfPlots using ModiaResult using ModiaResult.Unitful ModiaResult.@usingModiaPlot tr = [0.0, 15.0] t0 = (tr, tr, ModiaResult.Independent) t1 = (0.0 : 0.1 : 15.0) t2 = (0.0 : 0.1 : 3.0) t3 = (5.0 : 0.3 : 9.5) t4 = (11.0 : 0.1 : 15.0) sigA1 = 0.9*sin.(t2)u"m" sigA2 = cos.(t3)u"m" sigA3 = 1.1*sin.(t4)u"m" R2 = [[0.4 * cos(t), 0.5 * sin(t), 0.3 * cos(t)] for t in t2]u"m" R4 = [[0.2 * cos(t), 0.3 * sin(t), 0.2 * cos(t)] for t in t4]u"m" sigA = ([t2,t3,t4], [sigA1,sigA2,sigA3 ], ModiaResult.Continuous) sigB = ([t1] , [0.7*sin.(t1)u"m/s"], ModiaResult.Continuous) sigC = ([t3] , [sin.(t3)u"N*m"] , ModiaResult.Clocked) r = ([t2,t4] , [R2,R4] , ModiaResult.Continuous) result = ModiaResult.ResultDict("time" => t0, "sigA" => sigA, "sigB" => sigB, "sigC" => sigC, "r" => r, defaultHeading = "Signals from test_72_ResultDictWithMatrixOfPlots", hasOneTimeSignal = false) println("\n... test_72_ResultDictWithMatrixOfPlots.jl:\n") ModiaResult.printResultInfo(result) plot(result, [("sigA", "sigB", "sigC"), "r[2:3]"]) end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
1281
module test_72_ResultDictWithMatrixOfPlotsb using ModiaResult using ModiaResult.Unitful ModiaResult.@usingModiaPlot tr = [0.0, 15.0] t0 = (tr, tr, ModiaResult.Independent) t1 = (0.0 : 0.1 : 15.0) t2 = (0.0 : 0.1 : 3.0) t3 = (5.0 : 0.3 : 9.5) t4 = (11.0 : 0.1 : 15.0) sigA1 = 0.9*sin.(t2)u"m" sigA2 = cos.(t3)u"m" sigA3 = 1.1*sin.(t4)u"m" R2 = [[0.4 * cos(t), 0.5 * sin(t), 0.3 * cos(t)] for t in t2]u"m" R4 = [[0.2 * cos(t), 0.3 * sin(t), 0.2 * cos(t)] for t in t4]u"m" sigA = ([t2,t3,t4], [sigA1,sigA2,sigA3 ], ModiaResult.Continuous) sigB = ([t1] , [0.7*sin.(t1)u"m/s"], ModiaResult.Continuous) sigC = ([t3] , [sin.(t3)u"N*m"] , ModiaResult.Clocked) r = ([t2,t4] , [R2,R4] , ModiaResult.Continuous) result = ModiaResult.ResultDict("time" => t0, "sigA" => sigA, "sigB" => sigB, "sigC" => sigC, "r" => r, defaultHeading = "Segmented time signals", hasOneTimeSignal = false) println("\n... test_72_ResultDictWithMatrixOfPlots.jl:\n") ModiaResult.printResultInfo(result) plot(result, [("sigA", "sigB", "sigC"), "r[2:3]"]) end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
1019
module test_80_Warnings using ModiaResult using ModiaResult.OrderedCollections using ModiaResult.Unitful ModiaResult.@usingModiaPlot t = range(0.0, stop=10.0, length=100) t2 = range(0.0, stop=10.0, length=110) result = OrderedDict{String,Any}() result["time"] = t*u"s" result["phi"] = sin.(t)u"rad" result["phi2"] = 0.5 * sin.(t)u"rad" result["w"] = cos.(t)u"rad/s" result["w2"] = 0.6 * cos.(t)u"rad/s" result["r"] = [[0.4 * cos(t[i]), 0.5 * sin(t[i]), 0.3 * cos(t[i])] for i in eachindex(t)]*u"m" result["nothingSignal"] = nothing result["emptySignal"] = Float64[] result["wrongSizeSignal"] = sin.(t2)u"rad" println("\n... test_40_Warnings") ModiaResult.printResultInfo(result) plot(result, ("phi", "r", "signalNotDefined"), heading="Plot with warning 1" , figure=1) plot(result, ("signalNotDefined", "nothingSignal", "emptySignal", "wrongSizeSignal"), heading="Plot with warning 2" , figure=2) end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
368
module test_81_SaveFigure import ModiaResult ModiaResult.@usingModiaPlot println("\n... test test_81_SaveFigure.jl:\n") t = range(0.0, stop=10.0, length=100) result = Dict{String,Any}("time" => t, "phi" => sin.(t)) info = ModiaResult.resultInfo(result) ModiaResult.printResultInfo(result) plot(result, "phi", figure=2) saveFigure(2, "test_saveFigure2.png") end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
463
module test_82_AllExportedFunctions import ModiaResult ModiaResult.@usingModiaPlot # Test the Figure operations println("\n... test test_82_AllExportedFunctions.jl:\n") t = range(0.0, stop=10.0, length=100) result = Dict{String,Any}("time" => t, "phi" => sin.(t)) info = ModiaResult.resultInfo(result) ModiaResult.printResultInfo(result) plot(result, "phi", figure=2) showFigure(2) saveFigure(2, "test_saveFigure.png") closeFigure(2) closeAllFigures() end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
2352
module test_90_CompareOneScalarSignal using ModiaResult using ModiaResult.OrderedCollections using ModiaResult.DataFrames ModiaResult.@usingModiaPlotPackage t1 = range(0.0, stop=10.0, length=100) t2 = deepcopy(t1) t3 = range(0.0 , stop=10.0 , length=112) t4 = range(-0.1, stop=10.1, length=111) result1 = OrderedDict{String,Any}() result2 = DataFrame() result3 = DataFrame() result4 = DataFrame() result1["time"] = t1 result1["phi"] = sin.(t1) result2."time" = t2 result2."phi" = sin.(t2) result3[!,"time"] = t3 result3[!,"phi"] = sin.(t3) result4."time" = t4 result4."phi" = sin.(t4.+0.01) # Check makeSameTimeAxis (result1b, result2b, sameTimeRange1) = ModiaResult.makeSameTimeAxis(result1, result2, select=["phi", "w"]) println("sameTimeRange1 = ", sameTimeRange1) (result1c, result3b, sameTimeRange3) = ModiaResult.makeSameTimeAxis(result1, result3) println("sameTimeRange3 = ", sameTimeRange3) (result1d, result4b, sameTimeRange4) = ModiaResult.makeSameTimeAxis(result1, result4) println("sameTimeRange4 = ", sameTimeRange4) # check compareResults (success2, diff2, diff_names2, max_error2, within_tolerance2) = ModiaResult.compareResults(result1, result2) println("success2 = $success2, max_error2 = $max_error2, within_tolerance2 = $within_tolerance2") (success3, diff3, diff_names3, max_error3, within_tolerance3) = ModiaResult.compareResults(result1, result3) println("success3 = $success3, max_error3 = $max_error3, within_tolerance3 = $within_tolerance3") (success4, diff4, diff_names4, max_error4, within_tolerance4) = ModiaResult.compareResults(result1, result4) println("success4 = $success4, max_error4 = $max_error4, within_tolerance4 = $within_tolerance4") plot(result1, "phi", prefix="r1.") plot(result2, "phi", prefix="r2.", reuse=true) plot(result3, "phi", prefix="r3.", reuse=true) plot(result4, "phi", prefix="r4.", reuse=true) plot(result1b, "phi", prefix="r1b.", reuse=true) plot(result2b, "phi", prefix="r2b.", reuse=true) plot(result1c, "phi", prefix="r1c.", reuse=true) plot(result3b, "phi", prefix="r3b.", reuse=true) plot(result1d, "phi", prefix="r1d.", reuse=true) plot(result4b, "phi", prefix="r4b.", reuse=true) plot(diff2, "phi", prefix="diff2_", figure=2) plot(diff3, "phi", prefix="diff3_", figure=2, reuse=true) plot(diff4, "phi", prefix="diff4_", figure=2, reuse=true) end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
code
1097
module test_91_CompareOneScalarSignalWithUnit using ModiaResult using ModiaResult.Unitful using ModiaResult.DataFrames ModiaResult.@usingModiaPlotPackage t = range(0.0, stop=10.0, length=100) result1 = DataFrame() result2 = DataFrame() result3 = DataFrame() result1."time" = t*u"s" result1."w" = sin.(t)*u"rad/s" result2."time" = t*u"s" result2."w" = 0.0005*u"rad/s" .+ sin.(t)*u"rad/s" result3."time" = t result3."w" = sin.(t.+0.001) (success2, diff2, diff_names2, max_error2, within_tolerance2) = ModiaResult.compareResults(result1, result2) println("success2 = $success2, max_error2 = $max_error2, within_tolerance2 = $within_tolerance2") (success3, diff3, diff_names3, max_error3, within_tolerance3) = ModiaResult.compareResults(result1, result3) println("success3 = $success3, max_error3 = $max_error3, within_tolerance3 = $within_tolerance3") plot(result1, "w", prefix="r1.") plot(result2, "w", prefix="r2.", reuse=true) plot(result3, "w", prefix="r3.", reuse=true) plot(diff2, "w", prefix="diff2_", figure=2) plot(diff3, "w", prefix="diff3_", figure=2, reuse=true) end
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
docs
3916
# ModiaResult [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://modiasim.github.io/ModiaResult.jl/stable/index.html) [![The MIT License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/ModiaSim/ModiaResult.jl/blob/master/LICENSE.md) ModiaResult is part of [ModiaSim](https://modiasim.github.io/docs/). See also the ModiaResult [documentation](https://modiasim.github.io/ModiaResult.jl/stable/index.html). ModiaResult defines an abstract interface for **simulation results** and provides overloaded methods for: - Dictionaries, - [DataFrame](https://github.com/JuliaData/DataFrames.jl) tables, - [Tables](https://github.com/JuliaData/Tables.jl) (for example [CSV](https://github.com/JuliaData/CSV.jl)), and - ModiaResult.ResultDict (special dictionary with all features of the interface). Additionally, **operations** on simulation results are provided, especially to produce **line plots** in a **convenient way** based on - [GLMakie](https://github.com/JuliaPlots/GLMakie.jl) (interactive plots in an OpenGL window), - [WGLMakie](https://github.com/JuliaPlots/WGLMakie.jl) (interactive plots in a browser window), - [CairoMakie](https://github.com/JuliaPlots/CairoMakie.jl) (static plots on file with publication quality), - [PyPlot](https://github.com/JuliaPy/PyPlot.jl) (plots with Matplotlib from Python) and - NoPlot (= all plot calls are ignored; NoPlot is a module in ModiaResult), or - SilentNoPlot (= NoPlot without messages; SilentNoPlot is a module in ModiaResult). More details: - [Getting Started](https://modiasim.github.io/ModiaResult.jl/stable/GettingStarted.html) - [Functions](https://modiasim.github.io/ModiaResult.jl/stable/Functions.html) - [Abstract Interface](https://modiasim.github.io/ModiaResult.jl/stable/AbstractInterface.html) ## Installation All packages are registered and are installed with: ```julia julia> ]add ModiaResult add ModiaPlot_GLMakie # if plotting with GLMakie desired add ModiaPlot_WGLMakie # if plotting with WGLMakie desired add ModiaPlot_CairoMakie # if plotting with CairoMakie desired add ModiaPlot_PyPlot # if plotting with PyPlot desired ``` If you have trouble installing `ModiaPlot_PyPlot`, see [Installation of PyPlot.jl](https://modiasim.github.io/ModiaResult.jl/stable/index.html#Installation-of-PyPlot.jl) ## Example Assume that the result data structure is available, then the following commands ```julia import ModiaResult # Define plotting software globally ModiaResult.activate("PyPlot") # or ENV["MODIA_PLOT"] = "PyPlot" # Execute "using ModiaPlot_<globally defined plot package>" ModiaResult.@usingModiaPlot # = "using ModiaPlot_PyPlot" # Generate line plots plot(result, [("sigA", "sigB", "sigC"), "r[2:3]"]) ``` generate the following plot: ![SegmentedSignalsPlot](docs/resources/images/segmented-signals-plot.png) ## Abstract Result Interface For every result data structure a few access functions have to be defined (for details see [Abstract Interface](https://modiasim.github.io/ModiaResult.jl/stable/AbstractInterface.html)). Most importantly: ``` (timeSignal, signal, signalType) = ModiaResult.rawSignal(result, name) ``` Given the result data structure `result` and a variable `name::AbstractString`, return the result values of the independent variable (= `timeSignal`), the corresponding result values of the variable (= `signal`) and the type of the signal. The following figure sketches the returned `timeSignal` and `signal` data structures: ![SignalDefinition](docs/resources/images/signal-definition.png) Other signal types might be mapped to this basic signal type by introducing views. ## Main developer [Martin Otter](https://rmc.dlr.de/sr/en/staff/martin.otter/), [DLR - Institute of System Dynamics and Control](https://www.dlr.de/sr/en)
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
docs
1558
# Abstract Interface ```@meta CurrentModule = ModiaResult ``` This chapter documents the abstract interface to access a result data structure. | Functions | Description | |:--------------------------------|:------------------------------------------------------------| | [`SignalType`](@ref) | Predefined enumeration defining the supported signal types. | | [`rawSignal`](@ref) | Return raw signal data given the signal name (required). | | [`signalNames`](@ref) | Return all signal names (required). | | [`timeSignalName`](@ref) | Return the name of the time signal (required). | | [`hasOneTimeSignal`](@ref) | Return true if one time signal present (required). | | [`getSignalDetails`](@ref) | Return details of signal data (optional). | | [`hasSignal`](@ref) | Return true if signal name is known (optional). | | [`defaultHeading`](@ref) | Return default heading as string (optional). | ## Predefined enumeration ```@docs SignalType ``` ## Required functions The following functions must be defined for a new result data structure. ```@docs rawSignal signalNames timeSignalName hasOneTimeSignal ``` ## Optional functions The following functions can be defined for a new result data structure. If they are not defined, a default implementation is used. ```@docs getSignalDetails hasSignal defaultHeading ```
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
docs
4107
# Functions ## Overview ```@meta CurrentModule = ModiaResult ``` This chapter documents the functions that a user of this package typically utilizes. The following functions are available when prefixed with `ModiaResult`. !!! note `ModiaResult` does not `export` any symbols.\ (for example: `import ModiaResult; ModiaResult.usePlotPackage("PyPlot")`). Some packages, such as [Modia](https://github.com/ModiaSim/Modia.jl), export all the function names below and then the functions can be directly accessed.\ (for example: `using Modia; usePlotPackage("PyPlot")`). | Functions | Description | |:---------------------------------|:----------------------------------------------------------| | [`@usingModiaPlot`](@ref) | Expands into `using ModiaPlot_<PlotPackageName>` | | [`usePlotPackage`](@ref) | Define the plot package to be used. | | [`usePreviousPlotPackage`](@ref) | Define the previously defined plot package to be used. | | [`currentPlotPackage`](@ref) | Return name defined with [`usePlotPackage`](@ref) | | [`resultInfo`](@ref) | Return info about the result as [DataFrame](https://github.com/JuliaData/DataFrames.jl) table | | [`printResultInfo`](@ref) | Print info of the result on stdout. | | [`rawSignal`](@ref) | Return raw signal data given the signal name. | | [`getPlotSignal`](@ref) | Return signal data prepared for a plot package. | | [`defaultHeading`](@ref) | Return default heading of a result. | | [`signalNames`](@ref) | Return all signal names. | | [`timeSignalName`](@ref) | Return the name of the time signal. | | [`hasOneTimeSignal`](@ref) | Return true if one time signal present. | | [`hasSignal`](@ref) | Return true if a signal name is known. | The following functions are available after [`@usingModiaPlot`](@ref) has been executed: ```@meta CurrentModule = ModiaPlot_PyPlot ``` | Functions | Description | |:---------------------------------------------|:----------------------------------------------------------| | [`plot`](@ref) | Plot simulation results in multiple diagrams/figures. | | [`saveFigure`](@ref) | Save figure in different formats on file. | | [`closeFigure`](@ref) | Close one figure | | [`closeAllFigures`](@ref) | Close all figures | | [`showFigure`](@ref) | Show figure in window (only GLMakie, WGLMakie) | ```@meta CurrentModule = ModiaResult ``` The following function is typically only used for testing | Functions | Description | |:----------------------------------|:----------------------------------------------------------| | [`ModiaResult.ResultDict`](@ref) | Return a new instance of a ResultDict dictionary. | ## Functions of ModiaResult The following functions are provided by package `ModiaResult`. Other useful functions are available in the [Abstract Interface](@ref). ```@docs @usingModiaPlot usePlotPackage usePreviousPlotPackage currentPlotPackage resultInfo printResultInfo getPlotSignal ``` ## Functions of Plot Package The following functions are available after ```julia ModiaResult.@usingModiaPlot ``` has been executed. The documentation below was generated with `ModiaPlot_PyPlot`. ```@meta CurrentModule = ModiaPlot_PyPlot ``` ```@docs plot saveFigure closeFigure closeAllFigures showFigure ``` ## Functions for Testing ```@meta CurrentModule = ModiaResult ``` ```@docs ResultDict ```
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
docs
2853
# Getting Started Note, many examples are available at `$(ModiaResult.path)/test/*.jl`. ## Simple plot The following example defines a simple line plot of a sine wave: ```julia import ModiaResult # Define plotting software globally ModiaResult.usePlotPackage("GLMakie") # or ENV["MODIA_PLOT"] = "GLMakie" # Define result data structure t = range(0.0, stop=10.0, length=100) result = Dict("time" => t, "phi" => sin.(t)) # Generate line plot ModiaResult.@usingModiaPlot # = "using ModiaPlot_GLMakie" plot(result, "phi", heading = "Sine(time)") ``` Executing this code results in the following plot: ![SinePlot](../resources/images/sine-plot.png) ## Plot with segmented time axes A more complex example is shown in the next definition, where the signals have units, are scalars and vectors, have different time axes and are not always defined over the complete time range. ```julia import ModiaResult using Unitful # Define plotting software globally ModiaResult.usePlotPackage("PyPlot") # or ENV["MODIA_PLOT"] = "PyPlot" # Define result data structure t0 = ([0.0, 15.0], [0.0, 15.0], ModiaResult.TimeSignal) t1 = 0.0 : 0.1 : 15.0 t2 = 0.0 : 0.1 : 3.0 t3 = 5.0 : 0.3 : 9.5 t4 = 11.0 : 0.1 : 15.0 sigA1 = 0.9*sin.(t2)u"m" sigA2 = cos.(t3)u"m" sigA3 = 1.1*sin.(t4)u"m" R2 = [[0.4 * cos(t), 0.5 * sin(t), 0.3 * cos(t)] for t in t2]u"m" R4 = [[0.2 * cos(t), 0.3 * sin(t), 0.2 * cos(t)] for t in t4]u"m" sigA = ([t2,t3,t4], [sigA1,sigA2,sigA3 ], ModiaResult.Continuous) sigB = ([t1] , [0.7*sin.(t1)u"m/s"], ModiaResult.Continuous) sigC = ([t3] , [sin.(t3)u"N*m"] , ModiaResult.Clocked) r = ([t2,t4] , [R2,R4] , ModiaResult.Continuous) result = ModiaResult.ResultDict("time" => t0, "sigA" => sigA, "sigB" => sigB, "sigC" => sigC, "r" => r, defaultHeading = "Segmented signals", hasOneTimeSignal = false) # Generate line plots ModiaResult.@usingModiaPlot # = "using ModiaPlot_PyPlot" plot(result, [("sigA", "sigB", "sigC"), "r[2:3]"]) ``` Executing this code results in the following plot: ![SegmentedSignalsPlot](../resources/images/segmented-signals-plot.png) ## SilentNoPlot in runtests Typically, `runtests.jl` of a simulation package should utilize `SilentNoPlot` to perform all tests without using a plot package: ```julia module Runtests # File runtests.jl import ModiaResult using Test @testset "My Tests" begin ModiaResult.usePlotPackage("SilentNoPlot") # stores current plot package on a stack < run all tests > ModiaResult.usePreviousPlotPackage() # retrieves previous plot package from stack end end ```
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
docs
272
# Internal ```@meta CurrentModule = ModiaResult ``` This chapter documents internal functions that are typically only for use of the developers of package ModiaResult. ```@docs getSignalDetailsWithWarning signalLength hasSameSegments hasDimensionMismatch prepend! ```
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.4.3
02324a82efdb489c16bb6d008131a1447b125ad5
docs
7650
# ModiaResult Documentation ```@meta CurrentModule = ModiaResult ``` Package [ModiaResult](https://github.com/ModiaSim/ModiaResult.jl) defines an abstract interface for **simulation results** with a potentially segmented time axis (on different segments of the time axis, different variables might be defined) and provides overloaded methods for: - Dictionaries with String keys, - [DataFrame](https://github.com/JuliaData/DataFrames.jl) tables, - [Tables](https://github.com/JuliaData/Tables.jl) (for example [CSV](https://github.com/JuliaData/CSV.jl)), and - [`ModiaResult.ResultDict`](@ref) (special dictionary with all features of the interface). Additionally, **operations** on simulation results are provided, especially to produce **line plots** in a **convenient way** based on - [GLMakie](https://github.com/JuliaPlots/GLMakie.jl) (interactive plots in an OpenGL window), - [WGLMakie](https://github.com/JuliaPlots/WGLMakie.jl) (interactive plots in a browser window), - [CairoMakie](https://github.com/JuliaPlots/CairoMakie.jl) (static plots on file with publication quality), - [PyPlot](https://github.com/JuliaPy/PyPlot.jl) (plots with Matplotlib from Python), - NoPlot (= all plot calls are ignored; NoPlot is a module in ModiaResult), or - SilentNoPlot (= NoPlot without messages; SilentNoPlot is a module in ModiaResult). More details: - [Getting Started](GettingStarted.html) - [Functions](Functions.html) - [Abstract Interface](AbstractInterface.html) - [Internal](Internal.html) ## Example Assume that the result data structure is available, then the following commands ```julia import ModiaResult # Define plotting software globally ModiaResult.activate("PyPlot") # or ENV["MODIA_PLOT"] = "PyPlot" # Execute "using ModiaPlot_<globally defined plot package>" ModiaResult.@usingModiaPlot # = "using ModiaPlot_PyPlot" # Generate line plots plot(result, [("sigA", "sigB", "sigC"), "r[2:3]"]) ``` generate the following plot: ![SegmentedSignalsPlot](../resources/images/segmented-signals-plot.png) ## Abstract Result Interface For every result data structure a few access functions have to be defined (for details see [Abstract Interface](AbstractInterface.html)). Most importantly: ``` (timeSignal, signal, signalType) = ModiaResult.rawSignal(result, name) ``` Given the result data structure `result` and a variable `name::AbstractString`, return the result values of the independent variable (= `timeSignal`), the corresponding result values of the variable (= `signal`) and the type of the signal `signalType::`[`SignalType`](@ref)). The following figure sketches the returned `timeSignal` and `signal` data structures: ![SignalDefinition](../resources/images/signal-definition.png) Other signal types might be mapped to this basic signal type by introducing views. ## Installation All packages are registered and are installed with: ```julia julia> ]add ModiaResult add ModiaPlot_GLMakie # if plotting with GLMakie desired add ModiaPlot_WGLMakie # if plotting with WGLMakie desired add ModiaPlot_CairoMakie # if plotting with CairoMakie desired add ModiaPlot_PyPlot # if plotting with PyPlot desired ``` If you have trouble installing `ModiaPlot_PyPlot`, see [Installation of PyPlot.jl](https://modiasim.github.io/ModiaResult.jl/stable/index.html#Installation-of-PyPlot.jl) ## Installation of PyPlot.jl `ModiaPlot_PyPlot.jl` uses `PyPlot.jl` which in turn uses Python. Therefore a Python installation is needed. Installation might give problems in some cases. Here are some hints what to do (you may also consult the documentation of [PyPlot.jl](https://github.com/JuliaPy/PyPlot.jl)). Before installing `ModiaPlot_PyPlot.jl` make sure that `PyPlot.jl` is working: ```julia ]add PyPlot using PyPlot t = [0,1,2,3,4] plot(t,2*t) ``` If the commands above give a plot window. Everything is fine. If you get errors or no plot window appears or Julia crashes, try to first install a standard Python installation from Julia: ```julia # Start a new Julia session ENV["PYTHON"] = "" # Let Julia install Python ]build PyCall exit() # Exit Juila # Start a new Julia session ]add PyPlot using PyPlot t = [0,1,2,3,4] plot(t,2*t) ``` If the above does not work, or you want to use another Python distribution, install a [Python 3.x distribution](https://wiki.python.org/moin/PythonDistributions) that contains Matplotlib, set `ENV["PYTHON"] = "<path-above-python-installation>/python.exe"` and follow the steps above. Note, `ModiaPlot_PyPlot` is based on the Python 3.x version of Matplotlib where some keywords are different to the Python 2.x version. ## Release Notes ### Version 0.4.3 - Internal bug fixed. ### Version 0.4.2 - `printResultInfo(..)` and `resultInfo(..)` improved (signals with one value defined with ModiaResult.OneValueVector are specially marked, for example parameters). ### Version 0.4.1 - Update of Manifest.toml file ### Version 0.4.0 - Require Julia 1.7 - Upgrade Manifest.toml to version 2.0 - Update Project.toml/Manifest.toml ### Version 0.3.10 - Packages used in test models, prefixed with `ModiaResult.` to avoid missing package errors. ### Version 0.3.9 - Wrong link in README.md corrected - makie.jl: Adapted to newer Makie version (update!(..) no longer known and needed). - Issue with ustrip fixed. - Broken test_52_MonteCarloMeasurementsWithDistributions.jl reactivated - Manifest.toml updated. ### Version 0.3.8 - Better handling if some input arguments are `nothing`. - Bug corrected when accessing a vector element, such as `mvec[2]`. - Documentation slightly improved. ### Version 0.3.7 - Replaced Point2f0 by Makie_Point2f that needs to be defined according to the newest Makie version. ### Version 0.3.6 - Adapt to MonteCarloMeasurements, version >= 1.0 (e.g. pmean(..) instead of mean(..)) - Remove test_71_Tables_Rotational_First.jl from runtests.jl, because "using CSV" (in order that CSV.jl does not have to be added to the Project.toml file) ### Version 0.3.5 - Project.toml: Added version 1 of MonteCarloMeasurements. ### Version 0.3.4 - Project.toml: Added older versions to DataFrames, in order to reduce conflicts. ### Version 0.3.3 - ModiaResult/test/Project.toml: DataStructures replaced by OrderedCollections. ### Version 0.3.2 - DataStructures replaced by OrderedCollections. - Version numbers of used packages updated. ### Version 0.3.1 - Two new views on results added (SignalView and FlattenedSignalView). ### Version 0.3 - Major clean-up of the function interfaces. This version is not backwards compatible to previous versions. ### Version 0.2.2 - Overloaded AstractDicts generalized from `AbstractDict{String,T} where {T}` to\ `AbstractDict{T1,T2} where {T1<:AbstractString,T2}`. - Bug fixed. ### Version 0.2.1 - Bug fixed: `<: Vector` changed to `<: AbstractVector` ### Version 0.2.0 - Abstract Interface slightly redesigned (therefore 0.2.0 is not backwards compatible to 0.1.0). - Modules NoPlot and SilentNoPlot added as sub-modules of ModiaResult. These modules are activated if plot package "NoPlot" or "SilentNoPlot" are selected. - Content of directory src_plot moved into src. Afterwards src_plot was removed. - Directory test_plot merged into test (and then removed). ### Version 0.1.0 - Initial version (based on the result plotting developed for [ModiaMath](https://github.com/ModiaSim/ModiaMath.jl)). ## Main developer [Martin Otter](https://rmc.dlr.de/sr/en/staff/martin.otter/), [DLR - Institute of System Dynamics and Control](https://www.dlr.de/sr/en)
ModiaResult
https://github.com/ModiaSim/ModiaResult.jl.git
[ "MIT" ]
0.1.0
bb3f9a281118a9edfd63969405ce09bd35e20e4c
code
150
module Hygese include("main.jl") export solve_cvrp, solve_tsp, reporting, AlgorithmParameters end
Hygese
https://github.com/chkwon/Hygese.jl.git
[ "MIT" ]
0.1.0
bb3f9a281118a9edfd63969405ce09bd35e20e4c
code
4186
# # System Independent Types # @assert Cint == Int32 # @assert Cdouble == Float64 # Must match with AlgorithmParameters.h in HGS-CVRP: https://github.com/vidalt/HGS-CVRP Base.@kwdef mutable struct AlgorithmParameters nbGranular :: Int32 = 20 mu :: Int32 = 25 lambda :: Int32 = 40 nbElite :: Int32 = 4 nbClose :: Int32 = 5 targetFeasible :: Float64 = 0.2 seed :: Int32 = 0 nbIter :: Int32 = 20000 timeLimit :: Float64 = 0.0 useSwapStar :: Int32 = 1 # 1 = true, 0 = false end mutable struct C_SolutionRoute length :: Cint path :: Ptr{Cint} end mutable struct C_Solution cost :: Cdouble time :: Cdouble n_routes :: Cint routes :: Ptr{C_SolutionRoute} end mutable struct RoutingSolution cost :: Float64 time :: Float64 routes :: Vector{Vector{Int}} function RoutingSolution(sol_ptr::Ptr{C_Solution}) sol = unsafe_load(sol_ptr) routes = Vector{Vector{Int}}(undef, sol.n_routes) for i in eachindex(routes) r = unsafe_load(sol.routes, i) path = unsafe_wrap(Array, r.path, r.length) routes[i] = unsafe_wrap(Array, r.path, r.length) .+ 1 # customer numbering offset end return new(sol.cost, sol.time, routes) end end function convert_destroy(c_sol_ptr::Ptr{C_Solution}) # copy C structs to Julia structs j_sol = RoutingSolution(c_sol_ptr) # don't forget to delete pointers, important to avoid memory leaks ccall((:delete_solution, LIBHGSCVRP), Cvoid, (Ptr{C_Solution},), c_sol_ptr) return j_sol end """ function c_api_solve_cvrp( n::Integer, x::Vector, y::Vector, service_time::Vector, demand::Vector, vehicle_capacity::Float64, duration_limit::Float64, isRoundingInteger::Bool, isDurationConstraint::Bool, n_vehicles::Integer, parameters::AlgorithmParameters, verbose::Bool ) `x`, `y`, `service_time`, `demand` all require at least `n` elements. Anything after `n` elements are ignored. The first element should be the depot. The next `n-1` elements should be customers. """ function c_api_solve_cvrp( n::Integer, x::Vector, y::Vector, service_time::Vector, demand::Vector, vehicle_capacity::Real, duration_limit::Real, isRoundingInteger::Bool, isDurationConstraint::Bool, n_vehicles::Integer, parameters::AlgorithmParameters, verbose::Bool ) @assert service_time[1] == 0.0 @assert demand[1] == 0.0 c_solution_ptr = ccall( (:solve_cvrp, LIBHGSCVRP), Ptr{C_Solution}, ( Cint, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Cdouble, Cdouble, Cchar, Cchar, Cint, Ptr{AlgorithmParameters}, Cchar ), n, Cdouble.(x), Cdouble.(y), Cdouble.(service_time), Cdouble.(demand), vehicle_capacity, duration_limit, isRoundingInteger, isDurationConstraint, n_vehicles, Ref(parameters), verbose ) return convert_destroy(c_solution_ptr) end function c_api_solve_cvrp_dist_mtx( n::Integer, x::Vector, y::Vector, dist_mtx::Matrix, # row-first matrix as in C service_time::Vector, demand::Vector, vehicle_capacity::Real, duration_limit::Real, isDurationConstraint::Bool, n_vehicles::Integer, parameters::AlgorithmParameters, verbose::Bool ) @assert service_time[1] == 0.0 @assert demand[1] == 0.0 if length(x) == length(y) == n x_ptr = Cdouble.(x) y_ptr = Cdouble.(y) else x_ptr = y_ptr = C_NULL end c_solution_ptr = ccall( (:solve_cvrp_dist_mtx, LIBHGSCVRP), Ptr{C_Solution}, ( Cint, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Cdouble, Cdouble, Cchar, Cint, Ptr{AlgorithmParameters}, Cchar ), n, x_ptr, y_ptr, Cdouble.(dist_mtx), Cdouble.(service_time), Cdouble.(demand), vehicle_capacity, duration_limit, isDurationConstraint, n_vehicles, Ref(parameters), verbose ) return convert_destroy(c_solution_ptr) end
Hygese
https://github.com/chkwon/Hygese.jl.git
[ "MIT" ]
0.1.0
bb3f9a281118a9edfd63969405ce09bd35e20e4c
code
2965
function solve_cvrp( cvrp::CVRP, parameters=AlgorithmParameters(); n_vehicles=C_INT_MAX, verbose=true, use_dist_mtx=false, round=true ) n = cvrp.dimension x = cvrp.coordinates[:, 1] y = cvrp.coordinates[:, 2] demands = cvrp.demand vehicle_capacity = cvrp.capacity if cvrp.distance < Inf isDurationConstraint = true duration_limit = cvrp.distance else isDurationConstraint = false duration_limit = C_DBL_MAX end service_times = ones(size(x)) .* cvrp.service_time service_times[1] = 0.0 if use_dist_mtx dist_mtx = zeros(n, n) for i in 1:n, j in 1:n dist_mtx[i, j] = cvrp.weights[i, j] end # need to input dist_mtx' instead of dist_mtx # Julia: column-major indexing # C: row-major indexing return c_api_solve_cvrp_dist_mtx( n, x, y, Matrix(dist_mtx'), service_times, demands, vehicle_capacity, duration_limit, isDurationConstraint, n_vehicles, parameters, verbose ) else return c_api_solve_cvrp( n, x, y, service_times, demands, vehicle_capacity, duration_limit, round, isDurationConstraint, n_vehicles, parameters, verbose) end end function solve_cvrp( x::Vector, y::Vector, demands::Vector, vehicle_capacity::Real, parameters=AlgorithmParameters(); verbose=true, round=true, service_times=zeros(length(demands)), duration_limit=Inf, n_vehicles=C_INT_MAX ) @assert length(x) == length(y) == length(service_times) == length(demands) if duration_limit < Inf isDurationConstraint = true else isDurationConstraint = false duration_limit = C_DBL_MAX end return c_api_solve_cvrp( length(demands), x, y, service_times, demands, vehicle_capacity, duration_limit, round, isDurationConstraint, n_vehicles, parameters, verbose ) end function solve_cvrp( dist_mtx::Matrix, demands::Vector, vehicle_capacity::Real, parameters=AlgorithmParameters(); verbose=true, x_coordinates=Float64[], y_coordinates=Float64[], service_times=zeros(length(demands)), duration_limit=Inf, n_vehicles=C_INT_MAX ) if length(x_coordinates) == 0 && length(y_coordinates) == 0 @assert length(service_times) == length(demands) else @assert length(x_coordinates) == length(y_coordinates) == length(service_times) == length(demands) end if duration_limit < Inf isDurationConstraint = true else isDurationConstraint = false duration_limit = C_DBL_MAX end return c_api_solve_cvrp_dist_mtx( length(demands), x_coordinates, y_coordinates, Matrix(dist_mtx'), service_times, demands, vehicle_capacity, duration_limit, isDurationConstraint, n_vehicles, parameters, verbose ) end
Hygese
https://github.com/chkwon/Hygese.jl.git
[ "MIT" ]
0.1.0
bb3f9a281118a9edfd63969405ce09bd35e20e4c
code
371
using CVRPLIB, TSPLIB using HGSCVRP_jll const LIBHGSCVRP = HGSCVRP_jll.get_libhgscvrp_path() include("c_api.jl") include("cvrp.jl") include("tsp.jl") const C_DBL_MAX = floatmax(Cdouble) const C_INT_MAX = typemax(Cint) function reporting(visited_customers) routes = deepcopy(visited_customers) for r in routes r .-= 1 end return routes end
Hygese
https://github.com/chkwon/Hygese.jl.git
[ "MIT" ]
0.1.0
bb3f9a281118a9edfd63969405ce09bd35e20e4c
code
2328
function solve_tsp(tsp::TSP, parameters=AlgorithmParameters(); verbose=true, use_dist_mtx=false) n = tsp.dimension x = tsp.nodes[:, 1] y = tsp.nodes[:, 2] serv_time = zeros(size(x)) dem = ones(size(x)) dem[1] = 0.0 vehicleCapacity = n n_vehicles = 1 isRoundingInteger = true isDurationConstraint = false duration_limit = C_DBL_MAX if use_dist_mtx c_dist_mtx = Matrix(tsp.weights') for i in 1:n c_dist_mtx[i, i] = 0.0 end # need to input dist_mtx' instead of dist_mtx # Julia: column-first indexing # C: row-first indexing return c_api_solve_cvrp_dist_mtx( n, x, y, c_dist_mtx, serv_time, dem, vehicleCapacity, duration_limit, isDurationConstraint, n_vehicles, parameters, verbose ) else return c_api_solve_cvrp( n, x, y, serv_time, dem, vehicleCapacity, duration_limit, isRoundingInteger, isDurationConstraint, n_vehicles, parameters, verbose ) end end function solve_tsp(dist_mtx::Matrix, parameters=AlgorithmParameters(); verbose=true, x_coordinates=Float64[], y_coordinates=Float64[]) n = size(dist_mtx, 1) serv_time = zeros(n) dem = ones(n) dem[1] = 0.0 vehicleCapacity = n n_vehicles = 1 c_dist_mtx = Matrix(dist_mtx') for i in 1:n c_dist_mtx[i, i] = 0.0 end duration_limit = C_DBL_MAX isDurationConstraint = false # need to input dist_mtx' instead of dist_mtx # Julia: column-first indexing # C: row-first indexing return c_api_solve_cvrp_dist_mtx( n, x_coordinates, y_coordinates, c_dist_mtx, serv_time, dem, vehicleCapacity, duration_limit, isDurationConstraint, n_vehicles, parameters, verbose ) end function solve_tsp(x::Vector, y:: Vector, parameters=AlgorithmParameters(); verbose=true) n = length(x) serv_time = zeros(n) dem = ones(n) dem[1] = 0.0 vehicleCapacity = n n_vehicles = 1 isRoundingInteger = true duration_limit = C_DBL_MAX isDurationConstraint = false return c_api_solve_cvrp( n, x, y, serv_time, dem, vehicleCapacity, duration_limit, isRoundingInteger, isDurationConstraint, n_vehicles, parameters, verbose ) end
Hygese
https://github.com/chkwon/Hygese.jl.git
[ "MIT" ]
0.1.0
bb3f9a281118a9edfd63969405ce09bd35e20e4c
code
2988
@testset "durations" begin cvrp, _, _ = CVRPLIB.readCVRPLIB("CMT6") ap = AlgorithmParameters(timeLimit=3) result = solve_cvrp(cvrp, ap, verbose=true, use_dist_mtx=false, round=false) @show result.cost @test result.cost ≈ 555.43 atol=1e-2 cvrp, _, _ = CVRPLIB.readCVRPLIB("CMT7") service_times = cvrp.service_time .* ones(cvrp.dimension) service_times[1] = 0.0 ap = AlgorithmParameters(timeLimit=3) result = solve_cvrp( cvrp.coordinates[:, 1], cvrp.coordinates[:, 2], cvrp.demand, cvrp.capacity, ap; verbose = true, round = false, duration_limit = cvrp.distance, service_times = service_times ) @show result.cost @test result.cost ≈ 909.68 atol=1e-2 end @testset "P-n19-k2 by coordinates" begin cvrp, _, _ = CVRPLIB.readCVRPLIB("P-n19-k2") ap = AlgorithmParameters(timeLimit=1.8) result = solve_cvrp(cvrp, ap; verbose=true) @test result.cost <= 212 * 1.01 end @testset "P-n19-k2 by dist_mtx with coordinates" begin cvrp, _, _ = CVRPLIB.readCVRPLIB("P-n19-k2") ap = AlgorithmParameters(timeLimit=2.1) result = solve_cvrp(cvrp, ap; verbose=true, use_dist_mtx=true) @test result.cost <= 212 * 1.01 end @testset "P-n19-k2 by dist_mtx without coordinates" begin cvrp, _, _ = CVRPLIB.readCVRPLIB("P-n19-k2") cvrp.coordinates = zeros(size(cvrp.coordinates)) ap = AlgorithmParameters(timeLimit=1.23) result = solve_cvrp(cvrp, ap; verbose=true, use_dist_mtx=true) @test result.cost <= 212 * 1.01 end @testset "X-n101-k25" begin cvrp, _, _ = CVRPLIB.readCVRPLIB("X-n101-k25") ap = AlgorithmParameters(timeLimit=3) result = solve_cvrp(cvrp, ap; verbose=true) @show result.cost @show result.time visited_customers = result.routes @show typeof(visited_customers), size(visited_customers) report_visited_customers = reporting(visited_customers) for i in eachindex(report_visited_customers) @test report_visited_customers[i] == visited_customers[i] .- 1 end end @testset "A-n32-k5.vrp" begin cvrp = CVRPLIB.readCVRP("A-n32-k5.vrp") ap = AlgorithmParameters(timeLimit=2.3) result = solve_cvrp(cvrp, ap; verbose=true) @test result.cost <= 784 * 1.01 end @testset "x, y, dist_mtx CVRP" begin cvrp, _, _ = CVRPLIB.readCVRPLIB("A-n32-k5") x = cvrp.coordinates[:, 1] y = cvrp.coordinates[:, 2] dist_mtx = cvrp.weights demand = cvrp.demand capacity = cvrp.capacity n_vehicles = 5 ap = AlgorithmParameters(timeLimit=1.8) result1 = solve_cvrp(x, y, demand, cvrp.capacity, ap; n_vehicles=n_vehicles, verbose=true) result2 = solve_cvrp(dist_mtx, demand, cvrp.capacity, ap; verbose=true) result3 = solve_cvrp(dist_mtx, demand, cvrp.capacity, ap; x_coordinates=x, y_coordinates=y, verbose=true, n_vehicles=n_vehicles) @test result1.cost == result2.cost == result3.cost end
Hygese
https://github.com/chkwon/Hygese.jl.git
[ "MIT" ]
0.1.0
bb3f9a281118a9edfd63969405ce09bd35e20e4c
code
240
using Hygese using Test using CVRPLIB, TSPLIB @testset "Hygese.jl" begin # Write your tests here. @testset "CVRP" begin include("cvrp_test.jl") end @testset "TSP" begin include("tsp_test.jl") end end
Hygese
https://github.com/chkwon/Hygese.jl.git
[ "MIT" ]
0.1.0
bb3f9a281118a9edfd63969405ce09bd35e20e4c
code
1192
@testset "Symmetric TSP: pr76, by coordinates" begin tsp = TSPLIB.readTSPLIB(:pr76) ap = AlgorithmParameters(timeLimit=1) result = solve_tsp(tsp, ap) @show result.cost @show result.routes @test result.cost <= 108159 * 1.02 end @testset "Asymmetric TSP: br17, by dist_mtx" begin tsp = TSPLIB.readTSP("br17.atsp") ap = AlgorithmParameters(timeLimit=1) result = solve_tsp(tsp, ap; use_dist_mtx=true) @show result.cost @show result.routes @test result.cost <= 39 * 1.02 end @testset "Asymmetric TSP: ftv64, by dist_mtx" begin tsp = TSPLIB.readTSP("ftv64.atsp") ap = AlgorithmParameters(timeLimit=1) result = solve_tsp(tsp, ap; use_dist_mtx=true) @show result.cost @show result.routes @test result.cost <= 1839 * 1.02 end @testset "x, y, dist_mtx TSP" begin tsp = TSPLIB.readTSPLIB(:pr76) dist_mtx = tsp.weights x = tsp.nodes[:, 1] y = tsp.nodes[:, 2] ap = AlgorithmParameters(timeLimit=1) result1 = solve_tsp(x, y, ap) result2 = solve_tsp(dist_mtx, ap) result3 = solve_tsp(dist_mtx, ap; x_coordinates=x, y_coordinates=y) @test result1.cost == result2.cost == result3.cost end
Hygese
https://github.com/chkwon/Hygese.jl.git
[ "MIT" ]
0.1.0
bb3f9a281118a9edfd63969405ce09bd35e20e4c
docs
5533
# Hygese.jl [![Build Status](https://github.com/chkwon/Hygese.jl/workflows/CI/badge.svg?branch=master)](https://github.com/chkwon/Hygese.jl/actions?query=workflow%3ACI) [![codecov](https://codecov.io/gh/chkwon/Hygese.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/chkwon/Hygese.jl) *This package is under active development. It can introduce breaking changes anytime. Please use it at your own risk.* **A solver for the Capacitated Vehicle Routing Problem (CVRP)** This package provides a simple Julia wrapper for the Hybrid Genetic Search solver for Capacitated Vehicle Routing Problems [(HGS-CVRP)](https://github.com/vidalt/HGS-CVRP). This package requires a C++ compiler and `cmake` installed on your computer. Install: ```julia ] add https://github.com/chkwon/Hygese.jl ``` Use: ```julia using Hygese, CVRPLIB ap = AlgorithmParameters(timeLimit=1.3, seed=3) # `timeLimit` in seconds, `seed` is the seed for random values. cvrp = CVRPLIB.readCVRP(<path to .vrp file>) result = solve_cvrp(cvrp, ap; verbose=true) # verbose=false to turn off all outputs ``` - `result.cost` = the total cost of routes - `result.time` = the computational time taken by HGS - `results.routes` = the list of visited customers by each route, not including the depot (index 1). In the [CVRPLIB](http://vrp.atd-lab.inf.puc-rio.br/index.php/en/) instances, the node numbering starts from `1`, and the depot is typically node `1`. However, the solution reported in CVRPLIB uses numbering starts from `0`. For example, [`P-n19-k2`](http://vrp.atd-lab.inf.puc-rio.br/media/com_vrp/instances/P/P-n19-k2.vrp) instance has the following nodes: ``` 1 30 40 2 37 52 3 49 43 4 52 64 5 31 62 6 52 33 7 42 41 8 52 41 9 57 58 10 62 42 11 42 57 12 27 68 13 43 67 14 58 27 15 37 69 16 61 33 17 62 63 18 63 69 19 45 35 ``` and the depot is node `1`. But the [solution reported](http://vrp.atd-lab.inf.puc-rio.br/media/com_vrp/instances/P/P-n19-k2.sol) is: ``` Route #1: 4 11 14 12 3 17 16 8 6 Route #2: 18 5 13 15 9 7 2 10 1 Cost 212 ``` The last element `1` in Route #2 above represents the node number `2` with coordinate `(37, 52)`. This package returns `visited_customers` with the original node numbering. For the above example, ```julia using Hygese, CVRPLIB cvrp, cvrp_file, cvrp_sol_file = CVRPLIB.readCVRPLIB("P-n19-k2") result = solve_cvrp(cvrp) ``` returns ```julia julia> result.routes 2-element Vector{Vector{Int64}}: [19, 6, 14, 16, 10, 8, 3, 11, 2] [7, 9, 17, 18, 4, 13, 15, 12, 5] ``` To retrieve the CVRPLIB solution reporting format: ```julia julia> reporting(result.routes) 2-element Vector{Vector{Int64}}: [18, 5, 13, 15, 9, 7, 2, 10, 1] [6, 8, 16, 17, 3, 12, 14, 11, 4] ``` ## CVRP interfaces In all data the first element is for the depot. - `x` = x coordinates of nodes, size of `n` - `y` = x coordinates of nodes, size of `n` - `dist_mtx` = the distance matrix, size of `n` by `n`. - `service_times` = service time in each node - `demands` = the demand in each node - `vehicle_capacity` = the capacity of the vehicles - `duration_limit` = the duration limit for each vehicle - `n_vehicles` = the maximum number of available vehicles Three possibilities: - Only by the x, y coordinates. The Euclidean distances are used. ```julia ap = AlgorithmParameters(timeLimit=3.2) # seconds result = solve_cvrp(x, y, demands, vehicle_capacity, n_vehicles, ap; service_times=service_times, duration_limit=duration_limit, verbose=true) ``` - Only by the distance matrix. ```julia ap = AlgorithmParameters(timeLimit=3.2) # seconds result = solve_cvrp(dist_mtx, demand, vehicle_capacity, n_vehicles, ap; service_times=service_times, duration_limit=duration_limit, verbose=true) ``` - Using the distance matrix, with optional x, y coordinate information. The objective function is calculated based on the distance matrix, but the x, y coordinates just provide some helpful information. The distance matrix may not be consistent with the coordinates. ```julia ap = AlgorithmParameters(timeLimit=3.2) # seconds result = solve_cvrp(dist_mtx, demand, vehicle_capacity, n_vehicles, ap; x_coordinates=x, y_coordinates=y, service_times=service_times, duration_limit=duration_limit, verbose=true) ``` ## TSP interfaces As TSP is a special case of CVRP, the same solver can be used for solving TSP. The following interfaces are provided: - Reading `.tsp` or `.atsp` files via `TSPLIB.jl`: ```julia tsp = TSPLIB.readTSP("br17.atsp") ap = AlgorithmParameters(timeLimit=1.2) result = solve_tsp(tsp, ap; use_dist_mtx=true) ``` - By the coordinates, by the distance matrix, or by both: ```julia result1 = solve_tsp(x, y, ap) result2 = solve_tsp(dist_mtx, ap) result3 = solve_tsp(dist_mtx, ap; x_coordinates=x, y_coordinates=y) ``` ## AlgorithmParamters The paramters for the HGS algorithm with default values are: ```julia Base.@kwdef mutable struct AlgorithmParameters nbGranular :: Int32 = 20 mu :: Int32 = 25 lambda :: Int32 = 40 nbElite :: Int32 = 4 nbClose :: Int32 = 5 targetFeasible :: Float64 = 0.2 seed :: Int32 = 0 nbIter :: Int32 = 20000 timeLimit :: Float64 = 0.0 useSwapStar :: Int32 = 1 # 1 = true, 0 = false end ``` where `const C_DBL_MAX = floatmax(Cdouble)`. ## Related Packages - [CVRPLIB.jl](https://github.com/chkwon/CVRPLIB.jl) - [TSPLIB.jl](https://github.com/matago/TSPLIB.jl) - [LKH.jl](https://github.com/chkwon/LKH.jl) - [Concorde.jl](https://github.com/chkwon/Concorde.jl) - [PyHygese](https://github.com/chkwon/PyHygese): A Python wrapper for HGS-CVRP
Hygese
https://github.com/chkwon/Hygese.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
code
668
using Telegram using Documenter makedocs(; modules=[Telegram], authors="Andrey Oskin", repo="https://github.com/Arkoniak/Telegram.jl/blob/{commit}{path}#L{line}", sitename="Telegram.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://Arkoniak.github.io/Telegram.jl", siteurl="https://github.com/Arkoniak/Telegram.jl", assets=String[], ), pages=[ "Home" => "index.md", "API Reference" => "reference.md", "Usage" => "usage.md", "Developer guide" => "developers.md" ], ) deploydocs(; repo="github.com/Arkoniak/Telegram.jl", )
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
code
276
include("tg_scrape.jl") const main_html = getmain() const page = matchFirst(sel"div#dev_page_content", main_html) const funcs = process_page(page) create_api(funcs, joinpath("..", "src", "telegram_api.jl")) create_docs(funcs, joinpath("..", "docs", "src", "reference.md"))
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
code
5953
using UrlDownload using Gumbo using Cascadia using Cascadia: matchFirst using Underscores parser(x) = parsehtml(String(x)).root function getmain() urldownload("https://core.telegram.org/bots/api", parser = parser) end issmall(s) = s[1] in 'a':'z' function process_page(page = matchFirst(sel"div#dev_page_content", getmain())) topic = "" skip = true res = [] for c in children(page) if tag(c) == :h3 topic = nodeText(c) skip = true elseif tag(c) == :h4 name = nodeText(c) if issmall(name) skip = false methodname = name mthd = [:topic => topic, :name => methodname, :href => "https://core.telegram.org/bots/api" * matchFirst(sel"a", c).attributes["href"], :description => []] push!(res, mthd) else skip = true end elseif !skip push!(res[end][end].second, c) end end return Dict.(res) end function print_href(io, text, link, methods) if text in methods print(io, "[`", text, "`](@ref)") else print(io, "[", text, "](", "https://core.telegram.org/bots/api"*link, ")") end end function process_table(x, methods, io) optional = IOBuffer() required = IOBuffer() isoptional = false isrequired = false body = matchFirst(sel"tbody", x) for row in body.children cols = eachmatch(sel"td", row) req = nodeText(cols[3]) if req == "Yes" cio = required isrequired = true elseif req == "Optional" cio = optional isoptional = true else @error "Unknown requirement type: $req" cio = optional isoptional = true end # TODO Better types print(cio, "- `", nodeText(cols[1]),"`: (", nodeText(cols[2]), ") ") html2md(cols[4], methods, cio) print(cio, "\n") end if isrequired print(io, "# Required arguments\n") print(io, strip(String(take!(required)))) print(io, "\n\n") end if isoptional print(io, "# Optional arguments\n") print(io, strip(String(take!(optional)))) print(io, "\n") end return io end function process_description(x::Vector, methods, io = IOBuffer()) @_ foreach(html2md(_, methods, io), x) return @_ io |> String(take!(__)) |> strip end html2md(x::HTMLText, methods, io) = print(io, x.text) function html2md(x, methods, io = IOBuffer()) if tag(x) == :p @_ foreach(html2md(_, methods, io), x.children) print(io, "\n\n") elseif tag(x) == :a if x.attributes["href"][1] == '#' print_href(io, nodeText(x), x.attributes["href"], methods) else print(io, nodeText(x)) end elseif tag(x) == :table process_table(x, methods, io) elseif tag(x) == :code print(io, "`", nodeText(x), "`") else @_ foreach(html2md(_, methods, io), x.children) end return io end function create_api(funcs, output) f = open(output, "w") println(f, "const TELEGRAM_API = [") methods = @_ map(_[:name], funcs) for m in funcs println(f, "(:", m[:name], ", \"\"\"") print(f, "\t", m[:name], "([tg::TelegramClient]; kwargs...)\n\n") descr = process_description(m[:description], methods) println(f, descr) println(f, "\n[Function documentation source]($(m[:href]))") println(f, "\"\"\"),") end print(f, "]") close(f) end const DOC_PREAMBULE = """ ```@meta CurrentModule = Telegram ``` Word of caution: this documentation is generated automatically from [https://core.telegram.org/bots/api](https://core.telegram.org/bots/api) and can be incomplete or wrongly formatted. Also this documentation do not contain information about general principles of the Telegram API and response objects. So, if you have any doubts, consult original [api documentation](https://core.telegram.org/bots/api) and consider it as a ground truth. These docs were generated only for simpler navigation and better help hints in REPL and editors. Please notice that this package implements the [Bot API](https://core.telegram.org/api#bot-api). The Telegram Bot API is an API specifically for bots, which is simpler but less customisable. It acts as an intermediary between bots and the [Telegram API](https://core.telegram.org/api#telegram-api) which allow you to build your own customized Telegram clients. All API functions have [`TelegramClient`](@ref) as optional positional argument, which means that if it is not set explicitly, than global client is used, which is usually created during initial construction or by explicit call of [`useglobally!`](@ref) function. All arguments usually have `String`/`Boolean`/`Integer` types which is in one to one correspondence with julian types. Special arguments like `document`, `photo` and the like, which are intended for file sending, can accept either `IOStream` argument as in `open("picture.png", "r")` or `Pair{String, IO}` in case of in-memory `IO` objects without names. Read [Usage](@ref) for additional info. # API Reference """ function create_docs(funcs, output) f = open(output, "w") println(f, DOC_PREAMBULE) methods = @_ map(_[:name], funcs) prev_topic = "" io = IOBuffer() for m in funcs if prev_topic != m[:topic] print(f, "\n") print(f, strip(String(take!(io)))) print(f, "\n\n## ", m[:topic], "\n\n") prev_topic = m[:topic] io = IOBuffer() end println(f, "* [`Telegram.", m[:name], "`](@ref)") println(io, "```@docs") println(io, m[:name]) print(io, "```\n\n") end print(f, "\n") print(f, strip(String(take!(io)))) close(f) end
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
code
433
module Telegram using HTTP using JSON3 using Base.CoreLogging: global_logger, LogLevel, BelowMinLevel, Debug, Info, Warn, Error, AboveMaxLevel import Base.CoreLogging: AbstractLogger, handle_message, shouldlog, min_enabled_level, catch_exceptions export TelegramClient, useglobally!, TelegramLogger, run_bot include("client.jl") include("api.jl") using .API include("logging.jl") include("bot.jl") end # module
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
code
554
module API using ..Telegram include("telegram_api.jl") for (f, fdoc) in TELEGRAM_API fs=string(f) @eval begin function $f(client::Telegram.TelegramClient = Telegram.DEFAULT_OPTS.client; kwargs...) params = Dict{Symbol, Any}(kwargs) params[:chat_id] = get(params, :chat_id, Telegram.chatid(client)) params[:parse_mode] = get(params, :parse_mode, client.parse_mode) Telegram.query(client, $fs, params = params) end @doc $fdoc $f export $f end end end # module
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
code
2101
""" run_bot(f::Function, [tg::TelegramClient]; timeout = 10, brute_force_alive = false, offset = -1) Run telegram bot, which executes function `f` repeatedly. # Arguments - `f`: function to run with the bot. As an input it receive [Message](https://core.telegram.org/bots/api#message) in the form of JSON3 object. - `tg`: Telegram client, if not set then global telegram client is used. - `timeout`: timeout limit of messages, defines when longpoll messages should be interrupted - `brute_force_alive`: despite all measures, messages sometimes "hangs". You may use this argument to wake up telegram server regularly. When this option is set to `true` it works, but it is not recommended, since it makes additional calls. Consider this feature experimental and use at your own risk. - `offset`: telegram message offset, useful if you have processed messages, but bot was interrupted and messages state was lost. """ function run_bot(f, tg::TelegramClient = DEFAULT_OPTS.client; timeout = 20, brute_force_alive = false, offset = -1) if brute_force_alive @async while true try getMe(tg) sleep(timeout ÷ 2) catch err @error err end end end while true try ignore_errors = true res = offset == -1 ? getUpdates(tg, timeout = timeout) : (ignore_errors = false;getUpdates(tg, timeout = timeout, offset = offset) ) for msg in res try f(msg) offset = offset <= get(msg, :update_id, -1) ? get(msg, :update_id, -1) + 1 : offset catch err @error err if ignore_errors offset = offset <= get(msg, :update_id, -1) ? get(msg, :update_id, -1) + 1 : offset else rethrow() end end end catch err @error err if err isa InterruptException break end end end end
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
code
4375
struct TelegramError{T} <: Exception msg::T end mutable struct TelegramClient token::String chat_id::String parse_mode::String ep::String end """ TelegramClient(token; chat_id, parse_mode, ep, use_globally = true) Creates telegram client, which can be used to run telegram commands. # Arguments - `token::String`: telegram token, which can be obtained in telegram from @BotFather. - `chat_id`: if set, used as default `chat_id` argument for all chat related commands. To get specific `chat_id`, send message to the bot in telegram application and use [`getUpdates`](@ref) command. - `parse_mode`: if set, used as default for text messaging commands. - `use_globally::Bool`: default `true`. If set to `true` then it current client can be used as default in all telegram commands. - `ep`: endpoint for telegram api. By default `https://api.telegram.org/bot` is used, but you may change it, if you are using proxy or for testing purposes. """ function TelegramClient(token = get(ENV, "TELEGRAM_BOT_TOKEN", ""); chat_id = get(ENV, "TELEGRAM_BOT_CHAT_ID" ,""), parse_mode = "", ep = "https://api.telegram.org/bot", use_globally = true) client = TelegramClient(token, chat_id, parse_mode, ep) if use_globally useglobally!(client) end return client end mutable struct TelegramOpts client::TelegramClient upload_kw::Vector{Symbol} timeout::Int end const DEFAULT_OPTS = TelegramOpts(TelegramClient(use_globally = false), [:photo, :audio, :thumb, :document, :video, :animation, :voice, :video_note, :sticker, :png_sticker, :tgs_sticker, :certificate, :files], 30) """ useglobally!(tg::TelegramClient) Set `tg` as default client in all `Telegram.API` functions. # Example ```julia tg = TelegramClient(ENV["TG_TOKEN"]) useglobally!(tg) getMe() # new client is used in this command by default. ``` """ function useglobally!(client::TelegramClient) DEFAULT_OPTS.client = client return client end function token(client::TelegramClient) isempty(client.token) || return client.token token = get(ENV, "TELEGRAM_BOT_TOKEN", "") isempty(token) && @warn "Telegram token is empty" return token end function chatid(client::TelegramClient) isempty(client.chat_id) || return client.chat_id chat_id = get(ENV, "TELEGRAM_BOT_CHAT_ID", "") return chat_id end ioify(elem::IO) = elem ioify(elem) = IOBuffer(elem) function ioify(elem::IOBuffer) seekstart(elem) return elem end pushfiles!(body, keyword, file) = push!(body, keyword => file) function pushfiles!(body, keyword, file::Pair) push!(body, keyword => HTTP.Multipart(file.first, ioify(file.second))) end process_params(x::AbstractString) = x process_params(x) = JSON3.write(x) function query(client::TelegramClient, method; params = Dict()) req_uri = client.ep * token(client) * "/" * method intersection = intersect(keys(params), DEFAULT_OPTS.upload_kw) if isempty(intersection) headers = ["Content-Type" => "application/json", "Connection" => "Keep-Alive"] json_params = JSON3.write(params) res = HTTP.post(req_uri, headers, json_params; readtimeout = DEFAULT_OPTS.timeout + 1) else body = Pair[] for (k, v) in params k in intersection && continue push!(body, k => process_params(v)) end for k in intersection pushfiles!(body, k, params[k]) end res = HTTP.post(req_uri, ["Connection" => "Keep-Alive"], HTTP.Form(body); readtimeout = DEFAULT_OPTS.timeout + 1) end response = JSON3.read(res.body) if response.ok return response.result else throw(TelegramError(response)) end end """ apiquery(method, client; kwargs...) Sends `method` request to the telegram. It is recommended to use only if some of Telegram API function is not wrapped already. # Arguments - `method::String`: method name from the Telegram API, for example "getMe" - `client::TelegramClient`: telegram client, can be omitted, in this case default client is used. """ function apiquery(method, client::TelegramClient = DEFAULT_OPTS.client; kwargs...) params = Dict{Symbol, Any}(kwargs) params[:chat_id] = get(params, :chat_id, chatid(client)) params[:parse_mode] = get(params, :parse_mode, client.parse_mode) query(client, method, params = params) end
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
code
2531
struct TelegramLogger <: AbstractLogger tg::TelegramClient fmt::Function min_level::LogLevel async::Bool silent_errors::Bool end """ TelegramLogger(tg::TelegramClient; fmt = tg_formatter, min_level = Logging.Info, async = true) Creates logger, which output log messages to Telegram channel. # Arguments - `tg`: telegram client, should have valid `chat_id` which will be used for outcome messages. - `fmt`: function which accepts (`level`, `_module`, `group`, `id`, `file`, `line`) arguments and outputs message prefix. More details can be found in [Logging](https://docs.julialang.org/en/v1/stdlib/Logging/#Logging.handle_message) module. By default each messages is prepended with uppercase level, e.g. "INFO: " and the like. - `min_level`: minimum level of log messages which is going to be processed. - `async`: send messages in `sync` or `async` mode. Since telegram messages can take some time to be send, it make sense to set this parameter to `true`, so messages is send in the background with little impact on main program. But since in one run scripts main julia process can be finished before async message is sent, it make sense to set this parameter to `false` - `silent_errors`: by default, if there was an error during sending a message, it will be printed in `stderr` channel. If you want to silence this output, set `silent_errors` to `true`. """ function TelegramLogger(tg::TelegramClient; fmt = tg_formatter, min_level = Info, async = true, silent_errors = false) return TelegramLogger(tg, fmt, min_level, async, silent_errors) end function tg_formatter(level, _module, group, id, file, line) return uppercase(string(level)) * ": " end function handle_message(tglogger::TelegramLogger, level, message, _module, group, id, filepath, line; kwargs...) iob = IOBuffer() prefix = tg_formatter(level, _module, group, id, filepath, line) print(iob, prefix, string(message)) for (key, val) in kwargs print(iob, key, " = ", val) end text = String(take!(iob)) if tglogger.async @async try sendMessage(tglogger.tg; text = text) catch err tglogger.silent_errors || error(err) end else try sendMessage(tglogger.tg; text = text) catch err tglogger.silent_errors || error(err) end end end shouldlog(tglogger::TelegramLogger, arg...) = true min_enabled_level(tglogger::TelegramLogger) = tglogger.min_level
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
code
125223
const TELEGRAM_API = [ (:getUpdates, """ getUpdates([tg::TelegramClient]; kwargs...) Use this method to receive incoming updates using long polling (wiki). Returns an Array of [Update](https://core.telegram.org/bots/api#update) objects. # Optional arguments - `offset`: (Integer) Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as [`getUpdates`](@ref) is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will be forgotten. - `limit`: (Integer) Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100. - `timeout`: (Integer) Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only. - `allowed_updates`: (Array of String) A JSON-serialized list of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See [Update](https://core.telegram.org/bots/api#update) for a complete list of available update types. Specify an empty list to receive all update types except chat_member (default). If not specified, the previous setting will be used.Please note that this parameter doesn't affect updates created before the call to the getUpdates, so unwanted updates may be received for a short period of time. Notes1. This method will not work if an outgoing webhook is set up.2. In order to avoid getting duplicate updates, recalculate offset after each server response. [Function documentation source](https://core.telegram.org/bots/api#getupdates) """), (:setWebhook, """ setWebhook([tg::TelegramClient]; kwargs...) Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized [Update](https://core.telegram.org/bots/api#update). In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success. If you'd like to make sure that the webhook was set by you, you can specify secret data in the parameter secret_token. If specified, the request will contain a header “X-Telegram-Bot-Api-Secret-Token” with the secret token as content. # Required arguments - `url`: (String) HTTPS URL to send updates to. Use an empty string to remove webhook integration # Optional arguments - `certificate`: (InputFile) Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details. - `ip_address`: (String) The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS - `max_connections`: (Integer) The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput. - `allowed_updates`: (Array of String) A JSON-serialized list of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See [Update](https://core.telegram.org/bots/api#update) for a complete list of available update types. Specify an empty list to receive all update types except chat_member (default). If not specified, the previous setting will be used.Please note that this parameter doesn't affect updates created before the call to the setWebhook, so unwanted updates may be received for a short period of time. - `drop_pending_updates`: (Boolean) Pass True to drop all pending updates - `secret_token`: (String) A secret token to be sent in a header “X-Telegram-Bot-Api-Secret-Token” in every webhook request, 1-256 characters. Only characters `A-Z`, `a-z`, `0-9`, `_` and `-` are allowed. The header is useful to ensure that the request comes from a webhook set by you. Notes1. You will not be able to receive updates using [`getUpdates`](@ref) for as long as an outgoing webhook is set up.2. To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please upload as InputFile, sending a String will not work.3. Ports currently supported for webhooks: 443, 80, 88, 8443. If you're having any trouble setting up webhooks, please check out this amazing guide to webhooks. [Function documentation source](https://core.telegram.org/bots/api#setwebhook) """), (:deleteWebhook, """ deleteWebhook([tg::TelegramClient]; kwargs...) Use this method to remove webhook integration if you decide to switch back to [`getUpdates`](@ref). Returns True on success. # Optional arguments - `drop_pending_updates`: (Boolean) Pass True to drop all pending updates [Function documentation source](https://core.telegram.org/bots/api#deletewebhook) """), (:getWebhookInfo, """ getWebhookInfo([tg::TelegramClient]; kwargs...) Use this method to get current webhook status. Requires no parameters. On success, returns a [WebhookInfo](https://core.telegram.org/bots/api#webhookinfo) object. If the bot is using [`getUpdates`](@ref), will return an object with the url field empty. [Function documentation source](https://core.telegram.org/bots/api#getwebhookinfo) """), (:getMe, """ getMe([tg::TelegramClient]; kwargs...) A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a [User](https://core.telegram.org/bots/api#user) object. [Function documentation source](https://core.telegram.org/bots/api#getme) """), (:logOut, """ logOut([tg::TelegramClient]; kwargs...) Use this method to log out from the cloud Bot API server before launching the bot locally. You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns True on success. Requires no parameters. [Function documentation source](https://core.telegram.org/bots/api#logout) """), (:close, """ close([tg::TelegramClient]; kwargs...) Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns True on success. Requires no parameters. [Function documentation source](https://core.telegram.org/bots/api#close) """), (:sendMessage, """ sendMessage([tg::TelegramClient]; kwargs...) Use this method to send text messages. On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `text`: (String) Text of the message to be sent, 1-4096 characters after entities parsing # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `parse_mode`: (String) Mode for parsing entities in the message text. See [formatting options](https://core.telegram.org/bots/api#formatting-options) for more details. - `entities`: (Array of MessageEntity) A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode - `disable_web_page_preview`: (Boolean) Disables link previews for links in this message - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. [Function documentation source](https://core.telegram.org/bots/api#sendmessage) """), (:forwardMessage, """ forwardMessage([tg::TelegramClient]; kwargs...) Use this method to forward messages of any kind. Service messages can't be forwarded. On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `from_chat_id`: (Integer or String) Unique identifier for the chat where the original message was sent (or channel username in the format `@channelusername`) - `message_id`: (Integer) Message identifier in the chat specified in from_chat_id # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the forwarded message from forwarding and saving [Function documentation source](https://core.telegram.org/bots/api#forwardmessage) """), (:copyMessage, """ copyMessage([tg::TelegramClient]; kwargs...) Use this method to copy messages of any kind. Service messages and invoice messages can't be copied. A quiz [poll](https://core.telegram.org/bots/api#poll) can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method [`forwardMessage`](@ref), but the copied message doesn't have a link to the original message. Returns the [MessageId](https://core.telegram.org/bots/api#messageid) of the sent message on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `from_chat_id`: (Integer or String) Unique identifier for the chat where the original message was sent (or channel username in the format `@channelusername`) - `message_id`: (Integer) Message identifier in the chat specified in from_chat_id # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `caption`: (String) New caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept - `parse_mode`: (String) Mode for parsing entities in the new caption. See [formatting options](https://core.telegram.org/bots/api#formatting-options) for more details. - `caption_entities`: (Array of MessageEntity) A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. [Function documentation source](https://core.telegram.org/bots/api#copymessage) """), (:sendPhoto, """ sendPhoto([tg::TelegramClient]; kwargs...) Use this method to send photos. On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `photo`: (InputFile or String) Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. [More information on Sending Files »](https://core.telegram.org/bots/api#sending-files) # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `caption`: (String) Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing - `parse_mode`: (String) Mode for parsing entities in the photo caption. See [formatting options](https://core.telegram.org/bots/api#formatting-options) for more details. - `caption_entities`: (Array of MessageEntity) A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode - `has_spoiler`: (Boolean) Pass True if the photo needs to be covered with a spoiler animation - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. [Function documentation source](https://core.telegram.org/bots/api#sendphoto) """), (:sendAudio, """ sendAudio([tg::TelegramClient]; kwargs...) Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. For sending voice messages, use the [`sendVoice`](@ref) method instead. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `audio`: (InputFile or String) Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. [More information on Sending Files »](https://core.telegram.org/bots/api#sending-files) # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `caption`: (String) Audio caption, 0-1024 characters after entities parsing - `parse_mode`: (String) Mode for parsing entities in the audio caption. See [formatting options](https://core.telegram.org/bots/api#formatting-options) for more details. - `caption_entities`: (Array of MessageEntity) A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode - `duration`: (Integer) Duration of the audio in seconds - `performer`: (String) Performer - `title`: (String) Track name - `thumbnail`: (InputFile or String) Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. [More information on Sending Files »](https://core.telegram.org/bots/api#sending-files) - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. [Function documentation source](https://core.telegram.org/bots/api#sendaudio) """), (:sendDocument, """ sendDocument([tg::TelegramClient]; kwargs...) Use this method to send general files. On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `document`: (InputFile or String) File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. [More information on Sending Files »](https://core.telegram.org/bots/api#sending-files) # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `thumbnail`: (InputFile or String) Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. [More information on Sending Files »](https://core.telegram.org/bots/api#sending-files) - `caption`: (String) Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing - `parse_mode`: (String) Mode for parsing entities in the document caption. See [formatting options](https://core.telegram.org/bots/api#formatting-options) for more details. - `caption_entities`: (Array of MessageEntity) A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode - `disable_content_type_detection`: (Boolean) Disables automatic server-side content type detection for files uploaded using multipart/form-data - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. [Function documentation source](https://core.telegram.org/bots/api#senddocument) """), (:sendVideo, """ sendVideo([tg::TelegramClient]; kwargs...) Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as [Document](https://core.telegram.org/bots/api#document)). On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `video`: (InputFile or String) Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. [More information on Sending Files »](https://core.telegram.org/bots/api#sending-files) # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `duration`: (Integer) Duration of sent video in seconds - `width`: (Integer) Video width - `height`: (Integer) Video height - `thumbnail`: (InputFile or String) Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. [More information on Sending Files »](https://core.telegram.org/bots/api#sending-files) - `caption`: (String) Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing - `parse_mode`: (String) Mode for parsing entities in the video caption. See [formatting options](https://core.telegram.org/bots/api#formatting-options) for more details. - `caption_entities`: (Array of MessageEntity) A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode - `has_spoiler`: (Boolean) Pass True if the video needs to be covered with a spoiler animation - `supports_streaming`: (Boolean) Pass True if the uploaded video is suitable for streaming - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. [Function documentation source](https://core.telegram.org/bots/api#sendvideo) """), (:sendAnimation, """ sendAnimation([tg::TelegramClient]; kwargs...) Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `animation`: (InputFile or String) Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. [More information on Sending Files »](https://core.telegram.org/bots/api#sending-files) # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `duration`: (Integer) Duration of sent animation in seconds - `width`: (Integer) Animation width - `height`: (Integer) Animation height - `thumbnail`: (InputFile or String) Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. [More information on Sending Files »](https://core.telegram.org/bots/api#sending-files) - `caption`: (String) Animation caption (may also be used when resending animation by file_id), 0-1024 characters after entities parsing - `parse_mode`: (String) Mode for parsing entities in the animation caption. See [formatting options](https://core.telegram.org/bots/api#formatting-options) for more details. - `caption_entities`: (Array of MessageEntity) A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode - `has_spoiler`: (Boolean) Pass True if the animation needs to be covered with a spoiler animation - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. [Function documentation source](https://core.telegram.org/bots/api#sendanimation) """), (:sendVoice, """ sendVoice([tg::TelegramClient]; kwargs...) Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as [Audio](https://core.telegram.org/bots/api#audio) or [Document](https://core.telegram.org/bots/api#document)). On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `voice`: (InputFile or String) Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. [More information on Sending Files »](https://core.telegram.org/bots/api#sending-files) # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `caption`: (String) Voice message caption, 0-1024 characters after entities parsing - `parse_mode`: (String) Mode for parsing entities in the voice message caption. See [formatting options](https://core.telegram.org/bots/api#formatting-options) for more details. - `caption_entities`: (Array of MessageEntity) A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode - `duration`: (Integer) Duration of the voice message in seconds - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. [Function documentation source](https://core.telegram.org/bots/api#sendvoice) """), (:sendVideoNote, """ sendVideoNote([tg::TelegramClient]; kwargs...) As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `video_note`: (InputFile or String) Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. [More information on Sending Files »](https://core.telegram.org/bots/api#sending-files). Sending video notes by a URL is currently unsupported # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `duration`: (Integer) Duration of sent video in seconds - `length`: (Integer) Video width and height, i.e. diameter of the video message - `thumbnail`: (InputFile or String) Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. [More information on Sending Files »](https://core.telegram.org/bots/api#sending-files) - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. [Function documentation source](https://core.telegram.org/bots/api#sendvideonote) """), (:sendMediaGroup, """ sendMediaGroup([tg::TelegramClient]; kwargs...) Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of [Messages](https://core.telegram.org/bots/api#message) that were sent is returned. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `media`: (Array of InputMediaAudio, InputMediaDocument, InputMediaPhoto and InputMediaVideo) A JSON-serialized array describing messages to be sent, must include 2-10 items # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `disable_notification`: (Boolean) Sends messages silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent messages from forwarding and saving - `reply_to_message_id`: (Integer) If the messages are a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found [Function documentation source](https://core.telegram.org/bots/api#sendmediagroup) """), (:sendLocation, """ sendLocation([tg::TelegramClient]; kwargs...) Use this method to send point on the map. On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `latitude`: (Float number) Latitude of the location - `longitude`: (Float number) Longitude of the location # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `horizontal_accuracy`: (Float number) The radius of uncertainty for the location, measured in meters; 0-1500 - `live_period`: (Integer) Period in seconds for which the location will be updated (see Live Locations, should be between 60 and 86400. - `heading`: (Integer) For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. - `proximity_alert_radius`: (Integer) For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. [Function documentation source](https://core.telegram.org/bots/api#sendlocation) """), (:sendVenue, """ sendVenue([tg::TelegramClient]; kwargs...) Use this method to send information about a venue. On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `latitude`: (Float number) Latitude of the venue - `longitude`: (Float number) Longitude of the venue - `title`: (String) Name of the venue - `address`: (String) Address of the venue # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `foursquare_id`: (String) Foursquare identifier of the venue - `foursquare_type`: (String) Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.) - `google_place_id`: (String) Google Places identifier of the venue - `google_place_type`: (String) Google Places type of the venue. (See supported types.) - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. [Function documentation source](https://core.telegram.org/bots/api#sendvenue) """), (:sendContact, """ sendContact([tg::TelegramClient]; kwargs...) Use this method to send phone contacts. On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `phone_number`: (String) Contact's phone number - `first_name`: (String) Contact's first name # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `last_name`: (String) Contact's last name - `vcard`: (String) Additional data about the contact in the form of a vCard, 0-2048 bytes - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. [Function documentation source](https://core.telegram.org/bots/api#sendcontact) """), (:sendPoll, """ sendPoll([tg::TelegramClient]; kwargs...) Use this method to send a native poll. On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `question`: (String) Poll question, 1-300 characters - `options`: (Array of String) A JSON-serialized list of answer options, 2-10 strings 1-100 characters each # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `is_anonymous`: (Boolean) True, if the poll needs to be anonymous, defaults to True - `type`: (String) Poll type, “quiz” or “regular”, defaults to “regular” - `allows_multiple_answers`: (Boolean) True, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to False - `correct_option_id`: (Integer) 0-based identifier of the correct answer option, required for polls in quiz mode - `explanation`: (String) Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing - `explanation_parse_mode`: (String) Mode for parsing entities in the explanation. See [formatting options](https://core.telegram.org/bots/api#formatting-options) for more details. - `explanation_entities`: (Array of MessageEntity) A JSON-serialized list of special entities that appear in the poll explanation, which can be specified instead of parse_mode - `open_period`: (Integer) Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with close_date. - `close_date`: (Integer) Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 600 seconds in the future. Can't be used together with open_period. - `is_closed`: (Boolean) Pass True if the poll needs to be immediately closed. This can be useful for poll preview. - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. [Function documentation source](https://core.telegram.org/bots/api#sendpoll) """), (:sendDice, """ sendDice([tg::TelegramClient]; kwargs...) Use this method to send an animated emoji that will display a random value. On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `emoji`: (String) Emoji on which the dice throw animation is based. Currently, must be one of “”, “”, “”, “”, “”, or “”. Dice can have values 1-6 for “”, “” and “”, values 1-5 for “” and “”, and values 1-64 for “”. Defaults to “” - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. [Function documentation source](https://core.telegram.org/bots/api#senddice) """), (:sendChatAction, """ sendChatAction([tg::TelegramClient]; kwargs...) Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success. Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use [`sendChatAction`](@ref) with action = upload_photo. The user will see a “sending photo” status for the bot. We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `action`: (String) Type of action to broadcast. Choose one, depending on what the user is about to receive: typing for [text messages](https://core.telegram.org/bots/api#sendmessage), upload_photo for [photos](https://core.telegram.org/bots/api#sendphoto), record_video or upload_video for [videos](https://core.telegram.org/bots/api#sendvideo), record_voice or upload_voice for [voice notes](https://core.telegram.org/bots/api#sendvoice), upload_document for [general files](https://core.telegram.org/bots/api#senddocument), choose_sticker for [stickers](https://core.telegram.org/bots/api#sendsticker), find_location for [location data](https://core.telegram.org/bots/api#sendlocation), record_video_note or upload_video_note for [video notes](https://core.telegram.org/bots/api#sendvideonote). # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread; supergroups only [Function documentation source](https://core.telegram.org/bots/api#sendchataction) """), (:getUserProfilePhotos, """ getUserProfilePhotos([tg::TelegramClient]; kwargs...) Use this method to get a list of profile pictures for a user. Returns a [UserProfilePhotos](https://core.telegram.org/bots/api#userprofilephotos) object. # Required arguments - `user_id`: (Integer) Unique identifier of the target user # Optional arguments - `offset`: (Integer) Sequential number of the first photo to be returned. By default, all photos are returned. - `limit`: (Integer) Limits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100. [Function documentation source](https://core.telegram.org/bots/api#getuserprofilephotos) """), (:getFile, """ getFile([tg::TelegramClient]; kwargs...) Use this method to get basic information about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a [File](https://core.telegram.org/bots/api#file) object is returned. The file can then be downloaded via the link `https://api.telegram.org/file/bot<token>/<file_path>`, where `<file_path>` is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling [`getFile`](@ref) again. # Required arguments - `file_id`: (String) File identifier to get information about Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received. [Function documentation source](https://core.telegram.org/bots/api#getfile) """), (:banChatMember, """ banChatMember([tg::TelegramClient]; kwargs...) Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless [unbanned](https://core.telegram.org/bots/api#unbanchatmember) first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target group or username of the target supergroup or channel (in the format `@channelusername`) - `user_id`: (Integer) Unique identifier of the target user # Optional arguments - `until_date`: (Integer) Date when the user will be unbanned, unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. Applied for supergroups and channels only. - `revoke_messages`: (Boolean) Pass True to delete all messages from the chat for the user that is being removed. If False, the user will be able to see messages in the group that were sent before the user was removed. Always True for supergroups and channels. [Function documentation source](https://core.telegram.org/bots/api#banchatmember) """), (:unbanChatMember, """ unbanChatMember([tg::TelegramClient]; kwargs...) Use this method to unban a previously banned user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target group or username of the target supergroup or channel (in the format `@channelusername`) - `user_id`: (Integer) Unique identifier of the target user # Optional arguments - `only_if_banned`: (Boolean) Do nothing if the user is not banned [Function documentation source](https://core.telegram.org/bots/api#unbanchatmember) """), (:restrictChatMember, """ restrictChatMember([tg::TelegramClient]; kwargs...) Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) - `user_id`: (Integer) Unique identifier of the target user - `permissions`: (ChatPermissions) A JSON-serialized object for new user permissions # Optional arguments - `use_independent_chat_permissions`: (Boolean) Pass True if chat permissions are set independently. Otherwise, the can_send_other_messages and can_add_web_page_previews permissions will imply the can_send_messages, can_send_audios, can_send_documents, can_send_photos, can_send_videos, can_send_video_notes, and can_send_voice_notes permissions; the can_send_polls permission will imply the can_send_messages permission. - `until_date`: (Integer) Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever [Function documentation source](https://core.telegram.org/bots/api#restrictchatmember) """), (:promoteChatMember, """ promoteChatMember([tg::TelegramClient]; kwargs...) Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `user_id`: (Integer) Unique identifier of the target user # Optional arguments - `is_anonymous`: (Boolean) Pass True if the administrator's presence in the chat is hidden - `can_manage_chat`: (Boolean) Pass True if the administrator can access the chat event log, chat statistics, message statistics in channels, see channel members, see anonymous administrators in supergroups and ignore slow mode. Implied by any other administrator privilege - `can_post_messages`: (Boolean) Pass True if the administrator can create channel posts, channels only - `can_edit_messages`: (Boolean) Pass True if the administrator can edit messages of other users and can pin messages, channels only - `can_delete_messages`: (Boolean) Pass True if the administrator can delete messages of other users - `can_manage_video_chats`: (Boolean) Pass True if the administrator can manage video chats - `can_restrict_members`: (Boolean) Pass True if the administrator can restrict, ban or unban chat members - `can_promote_members`: (Boolean) Pass True if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by him) - `can_change_info`: (Boolean) Pass True if the administrator can change chat title, photo and other settings - `can_invite_users`: (Boolean) Pass True if the administrator can invite new users to the chat - `can_pin_messages`: (Boolean) Pass True if the administrator can pin messages, supergroups only - `can_manage_topics`: (Boolean) Pass True if the user is allowed to create, rename, close, and reopen forum topics, supergroups only [Function documentation source](https://core.telegram.org/bots/api#promotechatmember) """), (:setChatAdministratorCustomTitle, """ setChatAdministratorCustomTitle([tg::TelegramClient]; kwargs...) Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) - `user_id`: (Integer) Unique identifier of the target user - `custom_title`: (String) New custom title for the administrator; 0-16 characters, emoji are not allowed [Function documentation source](https://core.telegram.org/bots/api#setchatadministratorcustomtitle) """), (:banChatSenderChat, """ banChatSenderChat([tg::TelegramClient]; kwargs...) Use this method to ban a channel chat in a supergroup or a channel. Until the chat is [unbanned](https://core.telegram.org/bots/api#unbanchatsenderchat), the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `sender_chat_id`: (Integer) Unique identifier of the target sender chat [Function documentation source](https://core.telegram.org/bots/api#banchatsenderchat) """), (:unbanChatSenderChat, """ unbanChatSenderChat([tg::TelegramClient]; kwargs...) Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `sender_chat_id`: (Integer) Unique identifier of the target sender chat [Function documentation source](https://core.telegram.org/bots/api#unbanchatsenderchat) """), (:setChatPermissions, """ setChatPermissions([tg::TelegramClient]; kwargs...) Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members administrator rights. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) - `permissions`: (ChatPermissions) A JSON-serialized object for new default chat permissions # Optional arguments - `use_independent_chat_permissions`: (Boolean) Pass True if chat permissions are set independently. Otherwise, the can_send_other_messages and can_add_web_page_previews permissions will imply the can_send_messages, can_send_audios, can_send_documents, can_send_photos, can_send_videos, can_send_video_notes, and can_send_voice_notes permissions; the can_send_polls permission will imply the can_send_messages permission. [Function documentation source](https://core.telegram.org/bots/api#setchatpermissions) """), (:exportChatInviteLink, """ exportChatInviteLink([tg::TelegramClient]; kwargs...) Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as String on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) Note: Each administrator in a chat generates their own invite links. Bots can't use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using [`exportChatInviteLink`](@ref) or by calling the [`getChat`](@ref) method. If your bot needs to generate a new primary invite link replacing its previous one, use [`exportChatInviteLink`](@ref) again. [Function documentation source](https://core.telegram.org/bots/api#exportchatinvitelink) """), (:createChatInviteLink, """ createChatInviteLink([tg::TelegramClient]; kwargs...) Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method [`revokeChatInviteLink`](@ref). Returns the new invite link as [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) # Optional arguments - `name`: (String) Invite link name; 0-32 characters - `expire_date`: (Integer) Point in time (Unix timestamp) when the link will expire - `member_limit`: (Integer) The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 - `creates_join_request`: (Boolean) True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified [Function documentation source](https://core.telegram.org/bots/api#createchatinvitelink) """), (:editChatInviteLink, """ editChatInviteLink([tg::TelegramClient]; kwargs...) Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `invite_link`: (String) The invite link to edit # Optional arguments - `name`: (String) Invite link name; 0-32 characters - `expire_date`: (Integer) Point in time (Unix timestamp) when the link will expire - `member_limit`: (Integer) The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 - `creates_join_request`: (Boolean) True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified [Function documentation source](https://core.telegram.org/bots/api#editchatinvitelink) """), (:revokeChatInviteLink, """ revokeChatInviteLink([tg::TelegramClient]; kwargs...) Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object. # Required arguments - `chat_id`: (Integer or String) Unique identifier of the target chat or username of the target channel (in the format `@channelusername`) - `invite_link`: (String) The invite link to revoke [Function documentation source](https://core.telegram.org/bots/api#revokechatinvitelink) """), (:approveChatJoinRequest, """ approveChatJoinRequest([tg::TelegramClient]; kwargs...) Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `user_id`: (Integer) Unique identifier of the target user [Function documentation source](https://core.telegram.org/bots/api#approvechatjoinrequest) """), (:declineChatJoinRequest, """ declineChatJoinRequest([tg::TelegramClient]; kwargs...) Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `user_id`: (Integer) Unique identifier of the target user [Function documentation source](https://core.telegram.org/bots/api#declinechatjoinrequest) """), (:setChatPhoto, """ setChatPhoto([tg::TelegramClient]; kwargs...) Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `photo`: (InputFile) New chat photo, uploaded using multipart/form-data [Function documentation source](https://core.telegram.org/bots/api#setchatphoto) """), (:deleteChatPhoto, """ deleteChatPhoto([tg::TelegramClient]; kwargs...) Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) [Function documentation source](https://core.telegram.org/bots/api#deletechatphoto) """), (:setChatTitle, """ setChatTitle([tg::TelegramClient]; kwargs...) Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `title`: (String) New chat title, 1-128 characters [Function documentation source](https://core.telegram.org/bots/api#setchattitle) """), (:setChatDescription, """ setChatDescription([tg::TelegramClient]; kwargs...) Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) # Optional arguments - `description`: (String) New chat description, 0-255 characters [Function documentation source](https://core.telegram.org/bots/api#setchatdescription) """), (:pinChatMessage, """ pinChatMessage([tg::TelegramClient]; kwargs...) Use this method to add a message to the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `message_id`: (Integer) Identifier of a message to pin # Optional arguments - `disable_notification`: (Boolean) Pass True if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels and private chats. [Function documentation source](https://core.telegram.org/bots/api#pinchatmessage) """), (:unpinChatMessage, """ unpinChatMessage([tg::TelegramClient]; kwargs...) Use this method to remove a message from the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) # Optional arguments - `message_id`: (Integer) Identifier of a message to unpin. If not specified, the most recent pinned message (by sending date) will be unpinned. [Function documentation source](https://core.telegram.org/bots/api#unpinchatmessage) """), (:unpinAllChatMessages, """ unpinAllChatMessages([tg::TelegramClient]; kwargs...) Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) [Function documentation source](https://core.telegram.org/bots/api#unpinallchatmessages) """), (:leaveChat, """ leaveChat([tg::TelegramClient]; kwargs...) Use this method for your bot to leave a group, supergroup or channel. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`) [Function documentation source](https://core.telegram.org/bots/api#leavechat) """), (:getChat, """ getChat([tg::TelegramClient]; kwargs...) Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a [Chat](https://core.telegram.org/bots/api#chat) object on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`) [Function documentation source](https://core.telegram.org/bots/api#getchat) """), (:getChatAdministrators, """ getChatAdministrators([tg::TelegramClient]; kwargs...) Use this method to get a list of administrators in a chat, which aren't bots. Returns an Array of [ChatMember](https://core.telegram.org/bots/api#chatmember) objects. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`) [Function documentation source](https://core.telegram.org/bots/api#getchatadministrators) """), (:getChatMemberCount, """ getChatMemberCount([tg::TelegramClient]; kwargs...) Use this method to get the number of members in a chat. Returns Int on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`) [Function documentation source](https://core.telegram.org/bots/api#getchatmembercount) """), (:getChatMember, """ getChatMember([tg::TelegramClient]; kwargs...) Use this method to get information about a member of a chat. The method is only guaranteed to work for other users if the bot is an administrator in the chat. Returns a [ChatMember](https://core.telegram.org/bots/api#chatmember) object on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`) - `user_id`: (Integer) Unique identifier of the target user [Function documentation source](https://core.telegram.org/bots/api#getchatmember) """), (:setChatStickerSet, """ setChatStickerSet([tg::TelegramClient]; kwargs...) Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in [`getChat`](@ref) requests to check if the bot can use this method. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) - `sticker_set_name`: (String) Name of the sticker set to be set as the group sticker set [Function documentation source](https://core.telegram.org/bots/api#setchatstickerset) """), (:deleteChatStickerSet, """ deleteChatStickerSet([tg::TelegramClient]; kwargs...) Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in [`getChat`](@ref) requests to check if the bot can use this method. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) [Function documentation source](https://core.telegram.org/bots/api#deletechatstickerset) """), (:getForumTopicIconStickers, """ getForumTopicIconStickers([tg::TelegramClient]; kwargs...) Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user. Requires no parameters. Returns an Array of [Sticker](https://core.telegram.org/bots/api#sticker) objects. [Function documentation source](https://core.telegram.org/bots/api#getforumtopiciconstickers) """), (:createForumTopic, """ createForumTopic([tg::TelegramClient]; kwargs...) Use this method to create a topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns information about the created topic as a [ForumTopic](https://core.telegram.org/bots/api#forumtopic) object. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) - `name`: (String) Topic name, 1-128 characters # Optional arguments - `icon_color`: (Integer) Color of the topic icon in RGB format. Currently, must be one of 7322096 (0x6FB9F0), 16766590 (0xFFD67E), 13338331 (0xCB86DB), 9367192 (0x8EEE98), 16749490 (0xFF93B2), or 16478047 (0xFB6F5F) - `icon_custom_emoji_id`: (String) Unique identifier of the custom emoji shown as the topic icon. Use [`getForumTopicIconStickers`](@ref) to get all allowed custom emoji identifiers. [Function documentation source](https://core.telegram.org/bots/api#createforumtopic) """), (:editForumTopic, """ editForumTopic([tg::TelegramClient]; kwargs...) Use this method to edit name and icon of a topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) - `message_thread_id`: (Integer) Unique identifier for the target message thread of the forum topic # Optional arguments - `name`: (String) New topic name, 0-128 characters. If not specified or empty, the current name of the topic will be kept - `icon_custom_emoji_id`: (String) New unique identifier of the custom emoji shown as the topic icon. Use [`getForumTopicIconStickers`](@ref) to get all allowed custom emoji identifiers. Pass an empty string to remove the icon. If not specified, the current icon will be kept [Function documentation source](https://core.telegram.org/bots/api#editforumtopic) """), (:closeForumTopic, """ closeForumTopic([tg::TelegramClient]; kwargs...) Use this method to close an open topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) - `message_thread_id`: (Integer) Unique identifier for the target message thread of the forum topic [Function documentation source](https://core.telegram.org/bots/api#closeforumtopic) """), (:reopenForumTopic, """ reopenForumTopic([tg::TelegramClient]; kwargs...) Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) - `message_thread_id`: (Integer) Unique identifier for the target message thread of the forum topic [Function documentation source](https://core.telegram.org/bots/api#reopenforumtopic) """), (:deleteForumTopic, """ deleteForumTopic([tg::TelegramClient]; kwargs...) Use this method to delete a forum topic along with all its messages in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_delete_messages administrator rights. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) - `message_thread_id`: (Integer) Unique identifier for the target message thread of the forum topic [Function documentation source](https://core.telegram.org/bots/api#deleteforumtopic) """), (:unpinAllForumTopicMessages, """ unpinAllForumTopicMessages([tg::TelegramClient]; kwargs...) Use this method to clear the list of pinned messages in a forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) - `message_thread_id`: (Integer) Unique identifier for the target message thread of the forum topic [Function documentation source](https://core.telegram.org/bots/api#unpinallforumtopicmessages) """), (:editGeneralForumTopic, """ editGeneralForumTopic([tg::TelegramClient]; kwargs...) Use this method to edit the name of the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have can_manage_topics administrator rights. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) - `name`: (String) New topic name, 1-128 characters [Function documentation source](https://core.telegram.org/bots/api#editgeneralforumtopic) """), (:closeGeneralForumTopic, """ closeGeneralForumTopic([tg::TelegramClient]; kwargs...) Use this method to close an open 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) [Function documentation source](https://core.telegram.org/bots/api#closegeneralforumtopic) """), (:reopenGeneralForumTopic, """ reopenGeneralForumTopic([tg::TelegramClient]; kwargs...) Use this method to reopen a closed 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically unhidden if it was hidden. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) [Function documentation source](https://core.telegram.org/bots/api#reopengeneralforumtopic) """), (:hideGeneralForumTopic, """ hideGeneralForumTopic([tg::TelegramClient]; kwargs...) Use this method to hide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically closed if it was open. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) [Function documentation source](https://core.telegram.org/bots/api#hidegeneralforumtopic) """), (:unhideGeneralForumTopic, """ unhideGeneralForumTopic([tg::TelegramClient]; kwargs...) Use this method to unhide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target supergroup (in the format `@supergroupusername`) [Function documentation source](https://core.telegram.org/bots/api#unhidegeneralforumtopic) """), (:answerCallbackQuery, """ answerCallbackQuery([tg::TelegramClient]; kwargs...) Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @BotFather and accept the terms. Otherwise, you may use links like `t.me/your_bot?start=XXXX` that open your bot with a parameter. # Required arguments - `callback_query_id`: (String) Unique identifier for the query to be answered # Optional arguments - `text`: (String) Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters - `show_alert`: (Boolean) If True, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false. - `url`: (String) URL that will be opened by the user's client. If you have created a [Game](https://core.telegram.org/bots/api#game) and accepted the conditions via @BotFather, specify the URL that opens your game - note that this will only work if the query comes from a [callback_game](https://core.telegram.org/bots/api#inlinekeyboardbutton) button.Otherwise, you may use links like `t.me/your_bot?start=XXXX` that open your bot with a parameter. - `cache_time`: (Integer) The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0. [Function documentation source](https://core.telegram.org/bots/api#answercallbackquery) """), (:setMyCommands, """ setMyCommands([tg::TelegramClient]; kwargs...) Use this method to change the list of the bot's commands. See this manual for more details about bot commands. Returns True on success. # Required arguments - `commands`: (Array of BotCommand) A JSON-serialized list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified. # Optional arguments - `scope`: (BotCommandScope) A JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to [BotCommandScopeDefault](https://core.telegram.org/bots/api#botcommandscopedefault). - `language_code`: (String) A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands [Function documentation source](https://core.telegram.org/bots/api#setmycommands) """), (:deleteMyCommands, """ deleteMyCommands([tg::TelegramClient]; kwargs...) Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, [higher level commands](https://core.telegram.org/bots/api#determining-list-of-commands) will be shown to affected users. Returns True on success. # Optional arguments - `scope`: (BotCommandScope) A JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to [BotCommandScopeDefault](https://core.telegram.org/bots/api#botcommandscopedefault). - `language_code`: (String) A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands [Function documentation source](https://core.telegram.org/bots/api#deletemycommands) """), (:getMyCommands, """ getMyCommands([tg::TelegramClient]; kwargs...) Use this method to get the current list of the bot's commands for the given scope and user language. Returns an Array of [BotCommand](https://core.telegram.org/bots/api#botcommand) objects. If commands aren't set, an empty list is returned. # Optional arguments - `scope`: (BotCommandScope) A JSON-serialized object, describing scope of users. Defaults to [BotCommandScopeDefault](https://core.telegram.org/bots/api#botcommandscopedefault). - `language_code`: (String) A two-letter ISO 639-1 language code or an empty string [Function documentation source](https://core.telegram.org/bots/api#getmycommands) """), (:setMyName, """ setMyName([tg::TelegramClient]; kwargs...) Use this method to change the bot's name. Returns True on success. # Optional arguments - `name`: (String) New bot name; 0-64 characters. Pass an empty string to remove the dedicated name for the given language. - `language_code`: (String) A two-letter ISO 639-1 language code. If empty, the name will be shown to all users for whose language there is no dedicated name. [Function documentation source](https://core.telegram.org/bots/api#setmyname) """), (:getMyName, """ getMyName([tg::TelegramClient]; kwargs...) Use this method to get the current bot name for the given user language. Returns [BotName](https://core.telegram.org/bots/api#botname) on success. # Optional arguments - `language_code`: (String) A two-letter ISO 639-1 language code or an empty string [Function documentation source](https://core.telegram.org/bots/api#getmyname) """), (:setMyDescription, """ setMyDescription([tg::TelegramClient]; kwargs...) Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty. Returns True on success. # Optional arguments - `description`: (String) New bot description; 0-512 characters. Pass an empty string to remove the dedicated description for the given language. - `language_code`: (String) A two-letter ISO 639-1 language code. If empty, the description will be applied to all users for whose language there is no dedicated description. [Function documentation source](https://core.telegram.org/bots/api#setmydescription) """), (:getMyDescription, """ getMyDescription([tg::TelegramClient]; kwargs...) Use this method to get the current bot description for the given user language. Returns [BotDescription](https://core.telegram.org/bots/api#botdescription) on success. # Optional arguments - `language_code`: (String) A two-letter ISO 639-1 language code or an empty string [Function documentation source](https://core.telegram.org/bots/api#getmydescription) """), (:setMyShortDescription, """ setMyShortDescription([tg::TelegramClient]; kwargs...) Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot. Returns True on success. # Optional arguments - `short_description`: (String) New short description for the bot; 0-120 characters. Pass an empty string to remove the dedicated short description for the given language. - `language_code`: (String) A two-letter ISO 639-1 language code. If empty, the short description will be applied to all users for whose language there is no dedicated short description. [Function documentation source](https://core.telegram.org/bots/api#setmyshortdescription) """), (:getMyShortDescription, """ getMyShortDescription([tg::TelegramClient]; kwargs...) Use this method to get the current bot short description for the given user language. Returns [BotShortDescription](https://core.telegram.org/bots/api#botshortdescription) on success. # Optional arguments - `language_code`: (String) A two-letter ISO 639-1 language code or an empty string [Function documentation source](https://core.telegram.org/bots/api#getmyshortdescription) """), (:setChatMenuButton, """ setChatMenuButton([tg::TelegramClient]; kwargs...) Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success. # Optional arguments - `chat_id`: (Integer) Unique identifier for the target private chat. If not specified, default bot's menu button will be changed - `menu_button`: (MenuButton) A JSON-serialized object for the bot's new menu button. Defaults to [MenuButtonDefault](https://core.telegram.org/bots/api#menubuttondefault) [Function documentation source](https://core.telegram.org/bots/api#setchatmenubutton) """), (:getChatMenuButton, """ getChatMenuButton([tg::TelegramClient]; kwargs...) Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns [MenuButton](https://core.telegram.org/bots/api#menubutton) on success. # Optional arguments - `chat_id`: (Integer) Unique identifier for the target private chat. If not specified, default bot's menu button will be returned [Function documentation source](https://core.telegram.org/bots/api#getchatmenubutton) """), (:setMyDefaultAdministratorRights, """ setMyDefaultAdministratorRights([tg::TelegramClient]; kwargs...) Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are free to modify the list before adding the bot. Returns True on success. # Optional arguments - `rights`: (ChatAdministratorRights) A JSON-serialized object describing new default administrator rights. If not specified, the default administrator rights will be cleared. - `for_channels`: (Boolean) Pass True to change the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be changed. [Function documentation source](https://core.telegram.org/bots/api#setmydefaultadministratorrights) """), (:getMyDefaultAdministratorRights, """ getMyDefaultAdministratorRights([tg::TelegramClient]; kwargs...) Use this method to get the current default administrator rights of the bot. Returns [ChatAdministratorRights](https://core.telegram.org/bots/api#chatadministratorrights) on success. # Optional arguments - `for_channels`: (Boolean) Pass True to get default administrator rights of the bot in channels. Otherwise, default administrator rights of the bot for groups and supergroups will be returned. [Function documentation source](https://core.telegram.org/bots/api#getmydefaultadministratorrights) """), (:editMessageText, """ editMessageText([tg::TelegramClient]; kwargs...) Use this method to edit text and [game](https://core.telegram.org/bots/api#games) messages. On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned. # Required arguments - `text`: (String) New text of the message, 1-4096 characters after entities parsing # Optional arguments - `chat_id`: (Integer or String) Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `message_id`: (Integer) Required if inline_message_id is not specified. Identifier of the message to edit - `inline_message_id`: (String) Required if chat_id and message_id are not specified. Identifier of the inline message - `parse_mode`: (String) Mode for parsing entities in the message text. See [formatting options](https://core.telegram.org/bots/api#formatting-options) for more details. - `entities`: (Array of MessageEntity) A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode - `disable_web_page_preview`: (Boolean) Disables link previews for links in this message - `reply_markup`: (InlineKeyboardMarkup) A JSON-serialized object for an inline keyboard. [Function documentation source](https://core.telegram.org/bots/api#editmessagetext) """), (:editMessageCaption, """ editMessageCaption([tg::TelegramClient]; kwargs...) Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned. # Optional arguments - `chat_id`: (Integer or String) Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `message_id`: (Integer) Required if inline_message_id is not specified. Identifier of the message to edit - `inline_message_id`: (String) Required if chat_id and message_id are not specified. Identifier of the inline message - `caption`: (String) New caption of the message, 0-1024 characters after entities parsing - `parse_mode`: (String) Mode for parsing entities in the message caption. See [formatting options](https://core.telegram.org/bots/api#formatting-options) for more details. - `caption_entities`: (Array of MessageEntity) A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode - `reply_markup`: (InlineKeyboardMarkup) A JSON-serialized object for an inline keyboard. [Function documentation source](https://core.telegram.org/bots/api#editmessagecaption) """), (:editMessageMedia, """ editMessageMedia([tg::TelegramClient]; kwargs...) Use this method to edit animation, audio, document, photo, or video messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned. # Required arguments - `media`: (InputMedia) A JSON-serialized object for a new media content of the message # Optional arguments - `chat_id`: (Integer or String) Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `message_id`: (Integer) Required if inline_message_id is not specified. Identifier of the message to edit - `inline_message_id`: (String) Required if chat_id and message_id are not specified. Identifier of the inline message - `reply_markup`: (InlineKeyboardMarkup) A JSON-serialized object for a new inline keyboard. [Function documentation source](https://core.telegram.org/bots/api#editmessagemedia) """), (:editMessageLiveLocation, """ editMessageLiveLocation([tg::TelegramClient]; kwargs...) Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to [`stopMessageLiveLocation`](@ref). On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned. # Required arguments - `latitude`: (Float number) Latitude of new location - `longitude`: (Float number) Longitude of new location # Optional arguments - `chat_id`: (Integer or String) Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `message_id`: (Integer) Required if inline_message_id is not specified. Identifier of the message to edit - `inline_message_id`: (String) Required if chat_id and message_id are not specified. Identifier of the inline message - `horizontal_accuracy`: (Float number) The radius of uncertainty for the location, measured in meters; 0-1500 - `heading`: (Integer) Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. - `proximity_alert_radius`: (Integer) The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. - `reply_markup`: (InlineKeyboardMarkup) A JSON-serialized object for a new inline keyboard. [Function documentation source](https://core.telegram.org/bots/api#editmessagelivelocation) """), (:stopMessageLiveLocation, """ stopMessageLiveLocation([tg::TelegramClient]; kwargs...) Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned. # Optional arguments - `chat_id`: (Integer or String) Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `message_id`: (Integer) Required if inline_message_id is not specified. Identifier of the message with live location to stop - `inline_message_id`: (String) Required if chat_id and message_id are not specified. Identifier of the inline message - `reply_markup`: (InlineKeyboardMarkup) A JSON-serialized object for a new inline keyboard. [Function documentation source](https://core.telegram.org/bots/api#stopmessagelivelocation) """), (:editMessageReplyMarkup, """ editMessageReplyMarkup([tg::TelegramClient]; kwargs...) Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned. # Optional arguments - `chat_id`: (Integer or String) Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `message_id`: (Integer) Required if inline_message_id is not specified. Identifier of the message to edit - `inline_message_id`: (String) Required if chat_id and message_id are not specified. Identifier of the inline message - `reply_markup`: (InlineKeyboardMarkup) A JSON-serialized object for an inline keyboard. [Function documentation source](https://core.telegram.org/bots/api#editmessagereplymarkup) """), (:stopPoll, """ stopPoll([tg::TelegramClient]; kwargs...) Use this method to stop a poll which was sent by the bot. On success, the stopped [Poll](https://core.telegram.org/bots/api#poll) is returned. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `message_id`: (Integer) Identifier of the original message with the poll # Optional arguments - `reply_markup`: (InlineKeyboardMarkup) A JSON-serialized object for a new message inline keyboard. [Function documentation source](https://core.telegram.org/bots/api#stoppoll) """), (:deleteMessage, """ deleteMessage([tg::TelegramClient]; kwargs...) Use this method to delete a message, including service messages, with the following limitations:- A message can only be deleted if it was sent less than 48 hours ago.- Service messages about a supergroup, channel, or forum topic creation can't be deleted.- A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.- Bots can delete outgoing messages in private chats, groups, and supergroups.- Bots can delete incoming messages in private chats.- Bots granted can_post_messages permissions can delete outgoing messages in channels.- If the bot is an administrator of a group, it can delete any message there.- If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there.Returns True on success. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `message_id`: (Integer) Identifier of the message to delete [Function documentation source](https://core.telegram.org/bots/api#deletemessage) """), (:sendSticker, """ sendSticker([tg::TelegramClient]; kwargs...) Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `sticker`: (InputFile or String) Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP or .TGS sticker using multipart/form-data. [More information on Sending Files »](https://core.telegram.org/bots/api#sending-files). Video stickers can only be sent by a file_id. Animated stickers can't be sent via an HTTP URL. # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `emoji`: (String) Emoji associated with the sticker; only for just uploaded stickers - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. [Function documentation source](https://core.telegram.org/bots/api#sendsticker) """), (:getStickerSet, """ getStickerSet([tg::TelegramClient]; kwargs...) Use this method to get a sticker set. On success, a [StickerSet](https://core.telegram.org/bots/api#stickerset) object is returned. # Required arguments - `name`: (String) Name of the sticker set [Function documentation source](https://core.telegram.org/bots/api#getstickerset) """), (:getCustomEmojiStickers, """ getCustomEmojiStickers([tg::TelegramClient]; kwargs...) Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of [Sticker](https://core.telegram.org/bots/api#sticker) objects. # Required arguments - `custom_emoji_ids`: (Array of String) List of custom emoji identifiers. At most 200 custom emoji identifiers can be specified. [Function documentation source](https://core.telegram.org/bots/api#getcustomemojistickers) """), (:uploadStickerFile, """ uploadStickerFile([tg::TelegramClient]; kwargs...) Use this method to upload a file with a sticker for later use in the [`createNewStickerSet`](@ref) and [`addStickerToSet`](@ref) methods (the file can be used multiple times). Returns the uploaded [File](https://core.telegram.org/bots/api#file) on success. # Required arguments - `user_id`: (Integer) User identifier of sticker file owner - `sticker`: (InputFile) A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See https://core.telegram.org/stickers for technical requirements. [More information on Sending Files »](https://core.telegram.org/bots/api#sending-files) - `sticker_format`: (String) Format of the sticker, must be one of “static”, “animated”, “video” [Function documentation source](https://core.telegram.org/bots/api#uploadstickerfile) """), (:createNewStickerSet, """ createNewStickerSet([tg::TelegramClient]; kwargs...) Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. Returns True on success. # Required arguments - `user_id`: (Integer) User identifier of created sticker set owner - `name`: (String) Short name of sticker set, to be used in `t.me/addstickers/` URLs (e.g., animals). Can contain only English letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in `"_by_<bot_username>"`. `<bot_username>` is case insensitive. 1-64 characters. - `title`: (String) Sticker set title, 1-64 characters - `stickers`: (Array of InputSticker) A JSON-serialized list of 1-50 initial stickers to be added to the sticker set - `sticker_format`: (String) Format of stickers in the set, must be one of “static”, “animated”, “video” # Optional arguments - `sticker_type`: (String) Type of stickers in the set, pass “regular”, “mask”, or “custom_emoji”. By default, a regular sticker set is created. - `needs_repainting`: (Boolean) Pass True if stickers in the sticker set must be repainted to the color of text when used in messages, the accent color if used as emoji status, white on chat photos, or another appropriate color based on context; for custom emoji sticker sets only [Function documentation source](https://core.telegram.org/bots/api#createnewstickerset) """), (:addStickerToSet, """ addStickerToSet([tg::TelegramClient]; kwargs...) Use this method to add a new sticker to a set created by the bot. The format of the added sticker must match the format of the other stickers in the set. Emoji sticker sets can have up to 200 stickers. Animated and video sticker sets can have up to 50 stickers. Static sticker sets can have up to 120 stickers. Returns True on success. # Required arguments - `user_id`: (Integer) User identifier of sticker set owner - `name`: (String) Sticker set name - `sticker`: (InputSticker) A JSON-serialized object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set isn't changed. [Function documentation source](https://core.telegram.org/bots/api#addstickertoset) """), (:setStickerPositionInSet, """ setStickerPositionInSet([tg::TelegramClient]; kwargs...) Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success. # Required arguments - `sticker`: (String) File identifier of the sticker - `position`: (Integer) New sticker position in the set, zero-based [Function documentation source](https://core.telegram.org/bots/api#setstickerpositioninset) """), (:deleteStickerFromSet, """ deleteStickerFromSet([tg::TelegramClient]; kwargs...) Use this method to delete a sticker from a set created by the bot. Returns True on success. # Required arguments - `sticker`: (String) File identifier of the sticker [Function documentation source](https://core.telegram.org/bots/api#deletestickerfromset) """), (:setStickerEmojiList, """ setStickerEmojiList([tg::TelegramClient]; kwargs...) Use this method to change the list of emoji assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success. # Required arguments - `sticker`: (String) File identifier of the sticker - `emoji_list`: (Array of String) A JSON-serialized list of 1-20 emoji associated with the sticker [Function documentation source](https://core.telegram.org/bots/api#setstickeremojilist) """), (:setStickerKeywords, """ setStickerKeywords([tg::TelegramClient]; kwargs...) Use this method to change search keywords assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success. # Required arguments - `sticker`: (String) File identifier of the sticker # Optional arguments - `keywords`: (Array of String) A JSON-serialized list of 0-20 search keywords for the sticker with total length of up to 64 characters [Function documentation source](https://core.telegram.org/bots/api#setstickerkeywords) """), (:setStickerMaskPosition, """ setStickerMaskPosition([tg::TelegramClient]; kwargs...) Use this method to change the [mask position](https://core.telegram.org/bots/api#maskposition) of a mask sticker. The sticker must belong to a sticker set that was created by the bot. Returns True on success. # Required arguments - `sticker`: (String) File identifier of the sticker # Optional arguments - `mask_position`: (MaskPosition) A JSON-serialized object with the position where the mask should be placed on faces. Omit the parameter to remove the mask position. [Function documentation source](https://core.telegram.org/bots/api#setstickermaskposition) """), (:setStickerSetTitle, """ setStickerSetTitle([tg::TelegramClient]; kwargs...) Use this method to set the title of a created sticker set. Returns True on success. # Required arguments - `name`: (String) Sticker set name - `title`: (String) Sticker set title, 1-64 characters [Function documentation source](https://core.telegram.org/bots/api#setstickersettitle) """), (:setStickerSetThumbnail, """ setStickerSetThumbnail([tg::TelegramClient]; kwargs...) Use this method to set the thumbnail of a regular or mask sticker set. The format of the thumbnail file must match the format of the stickers in the set. Returns True on success. # Required arguments - `name`: (String) Sticker set name - `user_id`: (Integer) User identifier of the sticker set owner # Optional arguments - `thumbnail`: (InputFile or String) A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animated-sticker-requirements for animated sticker technical requirements), or a WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-sticker-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. [More information on Sending Files »](https://core.telegram.org/bots/api#sending-files). Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail. [Function documentation source](https://core.telegram.org/bots/api#setstickersetthumbnail) """), (:setCustomEmojiStickerSetThumbnail, """ setCustomEmojiStickerSetThumbnail([tg::TelegramClient]; kwargs...) Use this method to set the thumbnail of a custom emoji sticker set. Returns True on success. # Required arguments - `name`: (String) Sticker set name # Optional arguments - `custom_emoji_id`: (String) Custom emoji identifier of a sticker from the sticker set; pass an empty string to drop the thumbnail and use the first sticker as the thumbnail. [Function documentation source](https://core.telegram.org/bots/api#setcustomemojistickersetthumbnail) """), (:deleteStickerSet, """ deleteStickerSet([tg::TelegramClient]; kwargs...) Use this method to delete a sticker set that was created by the bot. Returns True on success. # Required arguments - `name`: (String) Sticker set name [Function documentation source](https://core.telegram.org/bots/api#deletestickerset) """), (:answerInlineQuery, """ answerInlineQuery([tg::TelegramClient]; kwargs...) Use this method to send answers to an inline query. On success, True is returned.No more than 50 results per query are allowed. # Required arguments - `inline_query_id`: (String) Unique identifier for the answered query - `results`: (Array of InlineQueryResult) A JSON-serialized array of results for the inline query # Optional arguments - `cache_time`: (Integer) The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300. - `is_personal`: (Boolean) Pass True if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query. - `next_offset`: (String) Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don't support pagination. Offset length can't exceed 64 bytes. - `button`: (InlineQueryResultsButton) A JSON-serialized object describing a button to be shown above inline query results [Function documentation source](https://core.telegram.org/bots/api#answerinlinequery) """), (:answerWebAppQuery, """ answerWebAppQuery([tg::TelegramClient]; kwargs...) Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a [SentWebAppMessage](https://core.telegram.org/bots/api#sentwebappmessage) object is returned. # Required arguments - `web_app_query_id`: (String) Unique identifier for the query to be answered - `result`: (InlineQueryResult) A JSON-serialized object describing the message to be sent [Function documentation source](https://core.telegram.org/bots/api#answerwebappquery) """), (:sendInvoice, """ sendInvoice([tg::TelegramClient]; kwargs...) Use this method to send invoices. On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. # Required arguments - `chat_id`: (Integer or String) Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) - `title`: (String) Product name, 1-32 characters - `description`: (String) Product description, 1-255 characters - `payload`: (String) Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. - `provider_token`: (String) Payment provider token, obtained via @BotFather - `currency`: (String) Three-letter ISO 4217 currency code, see more on currencies - `prices`: (Array of LabeledPrice) Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `max_tip_amount`: (Integer) The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of `US\$ 1.45` pass `max_tip_amount = 145`. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0 - `suggested_tip_amounts`: (Array of Integer) A JSON-serialized array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. - `start_parameter`: (String) Unique deep-linking parameter. If left empty, forwarded copies of the sent message will have a Pay button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a URL button with a deep link to the bot (instead of a Pay button), with the value used as the start parameter - `provider_data`: (String) JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. - `photo_url`: (String) URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. - `photo_size`: (Integer) Photo size in bytes - `photo_width`: (Integer) Photo width - `photo_height`: (Integer) Photo height - `need_name`: (Boolean) Pass True if you require the user's full name to complete the order - `need_phone_number`: (Boolean) Pass True if you require the user's phone number to complete the order - `need_email`: (Boolean) Pass True if you require the user's email address to complete the order - `need_shipping_address`: (Boolean) Pass True if you require the user's shipping address to complete the order - `send_phone_number_to_provider`: (Boolean) Pass True if the user's phone number should be sent to provider - `send_email_to_provider`: (Boolean) Pass True if the user's email address should be sent to provider - `is_flexible`: (Boolean) Pass True if the final price depends on the shipping method - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup) A JSON-serialized object for an inline keyboard. If empty, one 'Pay `total price`' button will be shown. If not empty, the first button must be a Pay button. [Function documentation source](https://core.telegram.org/bots/api#sendinvoice) """), (:createInvoiceLink, """ createInvoiceLink([tg::TelegramClient]; kwargs...) Use this method to create a link for an invoice. Returns the created invoice link as String on success. # Required arguments - `title`: (String) Product name, 1-32 characters - `description`: (String) Product description, 1-255 characters - `payload`: (String) Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. - `provider_token`: (String) Payment provider token, obtained via BotFather - `currency`: (String) Three-letter ISO 4217 currency code, see more on currencies - `prices`: (Array of LabeledPrice) Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) # Optional arguments - `max_tip_amount`: (Integer) The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of `US\$ 1.45` pass `max_tip_amount = 145`. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0 - `suggested_tip_amounts`: (Array of Integer) A JSON-serialized array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. - `provider_data`: (String) JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. - `photo_url`: (String) URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. - `photo_size`: (Integer) Photo size in bytes - `photo_width`: (Integer) Photo width - `photo_height`: (Integer) Photo height - `need_name`: (Boolean) Pass True if you require the user's full name to complete the order - `need_phone_number`: (Boolean) Pass True if you require the user's phone number to complete the order - `need_email`: (Boolean) Pass True if you require the user's email address to complete the order - `need_shipping_address`: (Boolean) Pass True if you require the user's shipping address to complete the order - `send_phone_number_to_provider`: (Boolean) Pass True if the user's phone number should be sent to the provider - `send_email_to_provider`: (Boolean) Pass True if the user's email address should be sent to the provider - `is_flexible`: (Boolean) Pass True if the final price depends on the shipping method [Function documentation source](https://core.telegram.org/bots/api#createinvoicelink) """), (:answerShippingQuery, """ answerShippingQuery([tg::TelegramClient]; kwargs...) If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an [Update](https://core.telegram.org/bots/api#update) with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. # Required arguments - `shipping_query_id`: (String) Unique identifier for the query to be answered - `ok`: (Boolean) Pass True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible) # Optional arguments - `shipping_options`: (Array of ShippingOption) Required if ok is True. A JSON-serialized array of available shipping options. - `error_message`: (String) Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user. [Function documentation source](https://core.telegram.org/bots/api#answershippingquery) """), (:answerPreCheckoutQuery, """ answerPreCheckoutQuery([tg::TelegramClient]; kwargs...) Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an [Update](https://core.telegram.org/bots/api#update) with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. # Required arguments - `pre_checkout_query_id`: (String) Unique identifier for the query to be answered - `ok`: (Boolean) Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems. # Optional arguments - `error_message`: (String) Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user. [Function documentation source](https://core.telegram.org/bots/api#answerprecheckoutquery) """), (:setPassportDataErrors, """ setPassportDataErrors([tg::TelegramClient]; kwargs...) Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success. Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues. # Required arguments - `user_id`: (Integer) User identifier - `errors`: (Array of PassportElementError) A JSON-serialized array describing the errors [Function documentation source](https://core.telegram.org/bots/api#setpassportdataerrors) """), (:sendGame, """ sendGame([tg::TelegramClient]; kwargs...) Use this method to send a game. On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned. # Required arguments - `chat_id`: (Integer) Unique identifier for the target chat - `game_short_name`: (String) Short name of the game, serves as the unique identifier for the game. Set up your games via @BotFather. # Optional arguments - `message_thread_id`: (Integer) Unique identifier for the target message thread (topic) of the forum; for forum supergroups only - `disable_notification`: (Boolean) Sends the message silently. Users will receive a notification with no sound. - `protect_content`: (Boolean) Protects the contents of the sent message from forwarding and saving - `reply_to_message_id`: (Integer) If the message is a reply, ID of the original message - `allow_sending_without_reply`: (Boolean) Pass True if the message should be sent even if the specified replied-to message is not found - `reply_markup`: (InlineKeyboardMarkup) A JSON-serialized object for an inline keyboard. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game. [Function documentation source](https://core.telegram.org/bots/api#sendgame) """), (:setGameScore, """ setGameScore([tg::TelegramClient]; kwargs...) Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. # Required arguments - `user_id`: (Integer) User identifier - `score`: (Integer) New score, must be non-negative # Optional arguments - `force`: (Boolean) Pass True if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters - `disable_edit_message`: (Boolean) Pass True if the game message should not be automatically edited to include the current scoreboard - `chat_id`: (Integer) Required if inline_message_id is not specified. Unique identifier for the target chat - `message_id`: (Integer) Required if inline_message_id is not specified. Identifier of the sent message - `inline_message_id`: (String) Required if chat_id and message_id are not specified. Identifier of the inline message [Function documentation source](https://core.telegram.org/bots/api#setgamescore) """), (:getGameHighScores, """ getGameHighScores([tg::TelegramClient]; kwargs...) Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. Returns an Array of [GameHighScore](https://core.telegram.org/bots/api#gamehighscore) objects. This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and their neighbors are not among them. Please note that this behavior is subject to change. # Required arguments - `user_id`: (Integer) Target user id # Optional arguments - `chat_id`: (Integer) Required if inline_message_id is not specified. Unique identifier for the target chat - `message_id`: (Integer) Required if inline_message_id is not specified. Identifier of the sent message - `inline_message_id`: (String) Required if chat_id and message_id are not specified. Identifier of the inline message [Function documentation source](https://core.telegram.org/bots/api#getgamehighscores) """), ]
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
code
758
module TestTelegram using Test for file in sort([file for file in readdir(@__DIR__) if occursin(r"^test[_0-9]+.*\.jl$", file)]) m = match(r"test([0-9]+)_(.*).jl", file) filename = String(m[2]) testnum = string(parse(Int, m[1])) # with this test one can run only specific tests, for example # Pkg.test("Telegram", test_args = ["xxx"]) # or # Pkg.test("Telegram", test_args = ["1"]) if isempty(ARGS) || (filename in ARGS) || (testnum in ARGS) || (m[1] in ARGS) @testset "$filename" begin # Here you can optionally exclude some test files # VERSION < v"1.1" && file == "test_xxx.jl" && continue include(file) end end end end # module
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
code
228
module TestBasic using Telegram using Telegram.API using Test @testset "basic api call" begin tg = TelegramClient("xxx"; chat_id = "yyy") useglobally!(tg) @test Telegram.DEFAULT_OPTS.client === tg end end # module
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
docs
4704
# Telegram | **Documentation** | **Build Status** | |:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:| | [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://Arkoniak.github.io/Telegram.jl/stable)[![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://Arkoniak.github.io/Telegram.jl/dev) | [![Build](https://github.com/Arkoniak/Telegram.jl/workflows/CI/badge.svg)](https://github.com/Arkoniak/Telegram.jl/actions)[![Coverage](https://codecov.io/gh/Arkoniak/Telegram.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/Arkoniak/Telegram.jl) | Simple [Telegram Messaging](https://telegram.org/) SDK with logging and bot facilities. Package was built with first-class support of telegram as instant message backend for various notification and reporing systems. So, simpliest way to use this package is by doing something like this ```julia using Telegram, Telegram.API tg = TelegramClient("YOUR TOKEN", chat_id = "YOUR CHAT_ID") # Some lengthy calculation # ... sendMessage(text = "Calculation complete, result is $result") ``` Please refer to [documentation](https://Arkoniak.github.io/Telegram.jl/dev) to learn how to properly setup telegram credentials and use package in general. # Installation Package is registered so you can install it in a usual way ```julia julia> using Pkg julia> Pkg.add("Telegram") ``` # Usage ## Telegram Bot API Usage is straightforward, [Telegram Bot API methods](https://core.telegram.org/bots/api#available-methods) are in one to one correspondence with this Julia wrapper. You need to create connection and then simply call necessary methods ```julia julia> using Telegram, Telegram.API julia> token = "YOUR TELEGRAM BOT TOKEN" julia> TelegramClient(token) julia> getMe() JSON3.Object{Array{UInt8,1},SubArray{UInt64,1,Array{UInt64,1},Tuple{UnitRange{Int64}},true}} with 7 entries: :id => 123456789 :is_bot => true :first_name => "Awesome Bot" :username => "AwesomeBot" :can_join_groups => true :can_read_all_group_messages => false :supports_inline_queries => false ``` Mainly you need to set arguments, but `chat_id` can be set directly in `TelegramClient` ```julia julia> token = "YOUR TELEGRAM BOT TOKEN" julia> TelegramClient(token; chat_id = "YOUR TELEGRAM BOT CHAT_ID") julia> sendMessage(text = "Hello, world!") ``` You can send files and other `IO` objects ```julia julia> sendPhoto(photo = open("picture.jpg", "r")) julia> io = IOBuffer() julia> print(io, "Hello world!") julia> sendDocument(document = "hello.txt" => io) ``` ## Logging You can use [Telegram.jl](https://github.com/Arkoniak/Telegram.jl) together with [LoggingExtras.jl](https://github.com/oxinabox/LoggingExtras.jl) to create powerful logging with insta messaging in case of critical situations Put your credentials in `.env` ``` # .env TELEGRAM_BOT_TOKEN = <YOUR TELEGRAM BOT TOKEN> TELEGRAM_BOT_CHAT_ID = <YOUR TELEGRAM CHAT ID> ``` ```julia using Telegram using Logging, LoggingExtras using ConfigEnv dotenv() # populate ENV with the data from .env tg = TelegramClient() tg_logger = TelegramLogger(tg; async = false) demux_logger = TeeLogger( MinLevelLogger(tg_logger, Logging.Error), ConsoleLogger() ) global_logger(demux_logger) @warn "It is bad" # goes to console @info "normal stuff" # goes to console @error "THE WORSE THING" # goes to console and telegram @debug "it is chill" # goes to console ``` ## Bots You can create bot with the `run_bot` command. Here is for example Echo bot ``` # .env TELEGRAM_BOT_TOKEN = <YOUR TELEGRAM BOT TOKEN> ``` ```julia using Telegram, Telegram.API using ConfigEnv dotenv() # Echo bot run_bot() do msg sendMessage(text = msg.message.text, chat_id = msg.message.chat.id) end ```
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
docs
897
# Developer guide Please note, that bot api functions themselves are not written manually, but automatically generated by parsing [https://core.telegram.org/bots/api](https://core.telegram.org/bots/api) site. So, if you find any inconsistences, missing docstrings or missing methods please do not make changes to `src/telegram_api.jl` or `reference.md`. Instead you should change scraping script accordingly. This script can be found in `extras` directory and in order to build new docs and methods you should do the following ```sh sh> cd extras sh> julia julia> ] pkg> activate . (extras)> instantiate ``` After that you can exit julia session and run ```sh sh> julia --project=. make.jl ``` command. It will create two files: * `src/telegram_api.jl` which contains all methods names and corresponding docstrings * `docs/src/reference.md` which contains complete [API Reference](@ref) page.
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
docs
1267
```@meta CurrentModule = Telegram ``` # Telegram Simple [Telegram Messaging](https://telegram.org/) SDK with logging and bot facilities. Package was built with first-class support of telegram as instant message backend for various notification and reporing systems. So, simpliest way to use this package is by doing something like this Put your credentials in `.env` file ``` # .env TELEGRAM_BOT_TOKEN = <YOUR TELEGRAM BOT TOKEN> TELEGRAM_BOT_CHAT_ID = <YOUR TELEGRAM CHAT ID> ``` ```julia using Telegram, Telegram.API using ConfigEnv dotenv() # Some lengthy calculation # ... sendMessage(text = "Calculation complete, result is $result") ``` Of course you can manually provide secrets with the `TelegramClient` constructor ```julia tg = TelegramClient("your token"; chat_id = "your default chat_id") sendMessage(text = "Calculation complete") ``` or even ```julia sendMessage(tg; text = "Calculation complete") ``` ## Installation Package is registered so you can install it in a usual way ```julia julia> using Pkg julia> Pkg.add("Telegram") ``` ## General methods In addition to [API Reference](@ref) methods, there is a number of methods which add some julian functionality like bots and logging facilities. ```@autodocs Modules = [Telegram] ```
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
docs
9608
```@meta CurrentModule = Telegram ``` Word of caution: this documentation is generated automatically from [https://core.telegram.org/bots/api](https://core.telegram.org/bots/api) and can be incomplete or wrongly formatted. Also this documentation do not contain information about general principles of the Telegram API and response objects. So, if you have any doubts, consult original [api documentation](https://core.telegram.org/bots/api) and consider it as a ground truth. These docs were generated only for simpler navigation and better help hints in REPL and editors. Please notice that this package implements the [Bot API](https://core.telegram.org/api#bot-api). The Telegram Bot API is an API specifically for bots, which is simpler but less customisable. It acts as an intermediary between bots and the [Telegram API](https://core.telegram.org/api#telegram-api) which allow you to build your own customized Telegram clients. All API functions have [`TelegramClient`](@ref) as optional positional argument, which means that if it is not set explicitly, than global client is used, which is usually created during initial construction or by explicit call of [`useglobally!`](@ref) function. All arguments usually have `String`/`Boolean`/`Integer` types which is in one to one correspondence with julian types. Special arguments like `document`, `photo` and the like, which are intended for file sending, can accept either `IOStream` argument as in `open("picture.png", "r")` or `Pair{String, IO}` in case of in-memory `IO` objects without names. Read [Usage](@ref) for additional info. # API Reference ## Getting updates * [`Telegram.getUpdates`](@ref) * [`Telegram.setWebhook`](@ref) * [`Telegram.deleteWebhook`](@ref) * [`Telegram.getWebhookInfo`](@ref) ```@docs getUpdates ``` ```@docs setWebhook ``` ```@docs deleteWebhook ``` ```@docs getWebhookInfo ``` ## Available methods * [`Telegram.getMe`](@ref) * [`Telegram.logOut`](@ref) * [`Telegram.close`](@ref) * [`Telegram.sendMessage`](@ref) * [`Telegram.forwardMessage`](@ref) * [`Telegram.copyMessage`](@ref) * [`Telegram.sendPhoto`](@ref) * [`Telegram.sendAudio`](@ref) * [`Telegram.sendDocument`](@ref) * [`Telegram.sendVideo`](@ref) * [`Telegram.sendAnimation`](@ref) * [`Telegram.sendVoice`](@ref) * [`Telegram.sendVideoNote`](@ref) * [`Telegram.sendMediaGroup`](@ref) * [`Telegram.sendLocation`](@ref) * [`Telegram.sendVenue`](@ref) * [`Telegram.sendContact`](@ref) * [`Telegram.sendPoll`](@ref) * [`Telegram.sendDice`](@ref) * [`Telegram.sendChatAction`](@ref) * [`Telegram.getUserProfilePhotos`](@ref) * [`Telegram.getFile`](@ref) * [`Telegram.banChatMember`](@ref) * [`Telegram.unbanChatMember`](@ref) * [`Telegram.restrictChatMember`](@ref) * [`Telegram.promoteChatMember`](@ref) * [`Telegram.setChatAdministratorCustomTitle`](@ref) * [`Telegram.banChatSenderChat`](@ref) * [`Telegram.unbanChatSenderChat`](@ref) * [`Telegram.setChatPermissions`](@ref) * [`Telegram.exportChatInviteLink`](@ref) * [`Telegram.createChatInviteLink`](@ref) * [`Telegram.editChatInviteLink`](@ref) * [`Telegram.revokeChatInviteLink`](@ref) * [`Telegram.approveChatJoinRequest`](@ref) * [`Telegram.declineChatJoinRequest`](@ref) * [`Telegram.setChatPhoto`](@ref) * [`Telegram.deleteChatPhoto`](@ref) * [`Telegram.setChatTitle`](@ref) * [`Telegram.setChatDescription`](@ref) * [`Telegram.pinChatMessage`](@ref) * [`Telegram.unpinChatMessage`](@ref) * [`Telegram.unpinAllChatMessages`](@ref) * [`Telegram.leaveChat`](@ref) * [`Telegram.getChat`](@ref) * [`Telegram.getChatAdministrators`](@ref) * [`Telegram.getChatMemberCount`](@ref) * [`Telegram.getChatMember`](@ref) * [`Telegram.setChatStickerSet`](@ref) * [`Telegram.deleteChatStickerSet`](@ref) * [`Telegram.getForumTopicIconStickers`](@ref) * [`Telegram.createForumTopic`](@ref) * [`Telegram.editForumTopic`](@ref) * [`Telegram.closeForumTopic`](@ref) * [`Telegram.reopenForumTopic`](@ref) * [`Telegram.deleteForumTopic`](@ref) * [`Telegram.unpinAllForumTopicMessages`](@ref) * [`Telegram.editGeneralForumTopic`](@ref) * [`Telegram.closeGeneralForumTopic`](@ref) * [`Telegram.reopenGeneralForumTopic`](@ref) * [`Telegram.hideGeneralForumTopic`](@ref) * [`Telegram.unhideGeneralForumTopic`](@ref) * [`Telegram.answerCallbackQuery`](@ref) * [`Telegram.setMyCommands`](@ref) * [`Telegram.deleteMyCommands`](@ref) * [`Telegram.getMyCommands`](@ref) * [`Telegram.setMyName`](@ref) * [`Telegram.getMyName`](@ref) * [`Telegram.setMyDescription`](@ref) * [`Telegram.getMyDescription`](@ref) * [`Telegram.setMyShortDescription`](@ref) * [`Telegram.getMyShortDescription`](@ref) * [`Telegram.setChatMenuButton`](@ref) * [`Telegram.getChatMenuButton`](@ref) * [`Telegram.setMyDefaultAdministratorRights`](@ref) * [`Telegram.getMyDefaultAdministratorRights`](@ref) ```@docs getMe ``` ```@docs logOut ``` ```@docs close ``` ```@docs sendMessage ``` ```@docs forwardMessage ``` ```@docs copyMessage ``` ```@docs sendPhoto ``` ```@docs sendAudio ``` ```@docs sendDocument ``` ```@docs sendVideo ``` ```@docs sendAnimation ``` ```@docs sendVoice ``` ```@docs sendVideoNote ``` ```@docs sendMediaGroup ``` ```@docs sendLocation ``` ```@docs sendVenue ``` ```@docs sendContact ``` ```@docs sendPoll ``` ```@docs sendDice ``` ```@docs sendChatAction ``` ```@docs getUserProfilePhotos ``` ```@docs getFile ``` ```@docs banChatMember ``` ```@docs unbanChatMember ``` ```@docs restrictChatMember ``` ```@docs promoteChatMember ``` ```@docs setChatAdministratorCustomTitle ``` ```@docs banChatSenderChat ``` ```@docs unbanChatSenderChat ``` ```@docs setChatPermissions ``` ```@docs exportChatInviteLink ``` ```@docs createChatInviteLink ``` ```@docs editChatInviteLink ``` ```@docs revokeChatInviteLink ``` ```@docs approveChatJoinRequest ``` ```@docs declineChatJoinRequest ``` ```@docs setChatPhoto ``` ```@docs deleteChatPhoto ``` ```@docs setChatTitle ``` ```@docs setChatDescription ``` ```@docs pinChatMessage ``` ```@docs unpinChatMessage ``` ```@docs unpinAllChatMessages ``` ```@docs leaveChat ``` ```@docs getChat ``` ```@docs getChatAdministrators ``` ```@docs getChatMemberCount ``` ```@docs getChatMember ``` ```@docs setChatStickerSet ``` ```@docs deleteChatStickerSet ``` ```@docs getForumTopicIconStickers ``` ```@docs createForumTopic ``` ```@docs editForumTopic ``` ```@docs closeForumTopic ``` ```@docs reopenForumTopic ``` ```@docs deleteForumTopic ``` ```@docs unpinAllForumTopicMessages ``` ```@docs editGeneralForumTopic ``` ```@docs closeGeneralForumTopic ``` ```@docs reopenGeneralForumTopic ``` ```@docs hideGeneralForumTopic ``` ```@docs unhideGeneralForumTopic ``` ```@docs answerCallbackQuery ``` ```@docs setMyCommands ``` ```@docs deleteMyCommands ``` ```@docs getMyCommands ``` ```@docs setMyName ``` ```@docs getMyName ``` ```@docs setMyDescription ``` ```@docs getMyDescription ``` ```@docs setMyShortDescription ``` ```@docs getMyShortDescription ``` ```@docs setChatMenuButton ``` ```@docs getChatMenuButton ``` ```@docs setMyDefaultAdministratorRights ``` ```@docs getMyDefaultAdministratorRights ``` ## Updating messages * [`Telegram.editMessageText`](@ref) * [`Telegram.editMessageCaption`](@ref) * [`Telegram.editMessageMedia`](@ref) * [`Telegram.editMessageLiveLocation`](@ref) * [`Telegram.stopMessageLiveLocation`](@ref) * [`Telegram.editMessageReplyMarkup`](@ref) * [`Telegram.stopPoll`](@ref) * [`Telegram.deleteMessage`](@ref) ```@docs editMessageText ``` ```@docs editMessageCaption ``` ```@docs editMessageMedia ``` ```@docs editMessageLiveLocation ``` ```@docs stopMessageLiveLocation ``` ```@docs editMessageReplyMarkup ``` ```@docs stopPoll ``` ```@docs deleteMessage ``` ## Stickers * [`Telegram.sendSticker`](@ref) * [`Telegram.getStickerSet`](@ref) * [`Telegram.getCustomEmojiStickers`](@ref) * [`Telegram.uploadStickerFile`](@ref) * [`Telegram.createNewStickerSet`](@ref) * [`Telegram.addStickerToSet`](@ref) * [`Telegram.setStickerPositionInSet`](@ref) * [`Telegram.deleteStickerFromSet`](@ref) * [`Telegram.setStickerEmojiList`](@ref) * [`Telegram.setStickerKeywords`](@ref) * [`Telegram.setStickerMaskPosition`](@ref) * [`Telegram.setStickerSetTitle`](@ref) * [`Telegram.setStickerSetThumbnail`](@ref) * [`Telegram.setCustomEmojiStickerSetThumbnail`](@ref) * [`Telegram.deleteStickerSet`](@ref) ```@docs sendSticker ``` ```@docs getStickerSet ``` ```@docs getCustomEmojiStickers ``` ```@docs uploadStickerFile ``` ```@docs createNewStickerSet ``` ```@docs addStickerToSet ``` ```@docs setStickerPositionInSet ``` ```@docs deleteStickerFromSet ``` ```@docs setStickerEmojiList ``` ```@docs setStickerKeywords ``` ```@docs setStickerMaskPosition ``` ```@docs setStickerSetTitle ``` ```@docs setStickerSetThumbnail ``` ```@docs setCustomEmojiStickerSetThumbnail ``` ```@docs deleteStickerSet ``` ## Inline mode * [`Telegram.answerInlineQuery`](@ref) * [`Telegram.answerWebAppQuery`](@ref) ```@docs answerInlineQuery ``` ```@docs answerWebAppQuery ``` ## Payments * [`Telegram.sendInvoice`](@ref) * [`Telegram.createInvoiceLink`](@ref) * [`Telegram.answerShippingQuery`](@ref) * [`Telegram.answerPreCheckoutQuery`](@ref) ```@docs sendInvoice ``` ```@docs createInvoiceLink ``` ```@docs answerShippingQuery ``` ```@docs answerPreCheckoutQuery ``` ## Telegram Passport * [`Telegram.setPassportDataErrors`](@ref) ```@docs setPassportDataErrors ``` ## Games * [`Telegram.sendGame`](@ref) * [`Telegram.setGameScore`](@ref) * [`Telegram.getGameHighScores`](@ref) ```@docs sendGame ``` ```@docs setGameScore ``` ```@docs getGameHighScores ```
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
1.1.5
4ac524cb90051721afa82c8a6c999df35dafbecd
docs
10914
```@meta CurrentModule = Telegram ``` # Usage ## Setting up telegram token and chat\_id In all examples of this section, it is assumed for simplicity that you set telegram token and chat\_id in `TELEGRAM_BOT_TOKEN` and `TELEGRAM_BOT_CHAT_ID` environment variables correspondingly. Recommended way to do it, by using [ConfigEnv.jl](https://github.com/Arkoniak/ConfigEnv.jl). You should create file `.env` ``` # .env TELEGRAM_BOT_TOKEN = 123456:ababababababbabababababbababaab TELEGRAM_BOT_CHAT_ID = 1234567 ``` And at the beginning of the application, populate `ENV` with the `dotenv` function. `Telegram.jl` methods will use these variables automatically. Alternatively (but less secure) you can provide `token` and `chat_id` via `TelegramClient` constructor. In order to get token itself, you should follow [this instruction](https://core.telegram.org/bots#3-how-do-i-create-a-bot). Just talk to `BotFather` and after few simple questions you will receive the token. Easiest way to obtain chat\_id is through running simple print bot. ```julia using Telegram using ConfigEnv dotenv() run_bot() do msg println(msg) end ``` After running this script just open chat with your newly created bot and send it any message. You will receive something like this ``` { "update_id": 87654321, "message": { "message_id": 6789, "from": { "id": 123456789, "is_bot": false, "language_code": "en" }, "chat": { "id": 123456789, "type": "private" }, "date": 1592767594, "text": "Hello" } } ``` In this example, field `message.chat.id = 123456789` is necessary `chat_id` which shoud be stored in `TELEGRAM_BOT_CHAT_ID` variable. ## Initializing `TelegramClient` If you set `ENV` variables `TELEGRAM_BOT_TOKEN` and `TELEGRAM_BOT_CHAT_ID`, then telegram client use them to run all commands. Alternatively you can initialize client by passing required token parameter. ```julia using Telegram tg = TelegramClient("TELEGRAM BOT TOKEN") ``` Since [Telegram.jl](https://github.com/Arkoniak/Telegram.jl) was built with the first-class support of the Telegram as a notification system, you can pass `chat_id` variable, which will be used then by default in every function related to messaging ```julia using Telegram tg = TelegramClient("TELEGRAM BOT TOKEN"; chat_id = "DEFAULT TELEGRAM CHAT ID") Telegram.sendMessage(tg, text = "Hello world") # will send "Hello world" message # to chat defined in `tg.chat_id` ``` Also, by default new `TelegramClient` is used globally in all [API Reference](@ref) related functions, so you can run commands like ```julia using Telegram using ConfigEnv dotenv() Telegram.sendMessage(text = "Hello world") ``` which will send "Hello world" message to the chat defined by `ENV["TELEGRAM_BOT_CHAT_ID"]` variable with the bot defined by `ENV["TELEGRAM_BOT_TOKEN"]` variable. In order to override this behaviour you can set `use_globally` argument of [`TelegramClient`](@ref) function. To set previously defined client as a global, you should use [`useglobally!`](@ref). ## Using Telegram Bot API Due to the rather large number of functions defined in [API Reference](@ref), they are hidden behind module declaration, so by default they should be prefixed with `Telegram.` ```julia using Telegram using ConfigEnv dotenv() Telegram.getMe() # returns information about bot ``` If this is inconvenient for some reason, you can either introduce new and short constant name, like this ```julia using Telegram using ConfigEnv const TG = Telegram dotenv() TG.getMe() ``` or you can import all telegram Bot API by `using Telegram.API`, in this scenario you do not need to use any prefixes ```julia using Telegram using Telegram.API using ConfigEnv dotenv() getMe() ``` In what follows we will use latter approach. ## Sending messages If you set telegram client globally with `chat_id` as it is described in previous sections, then you can use message related function from [API Reference](@ref), omitting `chat_id` argument. For example, this is how you can use most basic `sendMessage` function ```julia using Telegram, Telegram.API using ConfigEnv dotenv() sendMessage(text = "Hello world") ``` Of course if you have more than one client or writing a bot which should communicate in multiple chats, you can add this parameters to function calls and they will override default values, for example ``` # .env TG_TOKEN = 123456:asdasd TG_TOKEN2 = 546789:zxczxc TG_CHAT_ID = 1234 ``` ```julia using Telegram, Telegram.API using ConfigEnv dotenv() tg1 = TelegramClient(ENV["TG_TOKEN"]; chat_id = ENV["TG_CHAT_ID"]) tg2 = TelegramClient(ENV["TG_TOKEN2"]) sendMessage(tg1, text = "I am bot number 1", chat_id = 12345) sendMessage(tg2, text = "I am bot number 2", chat_id = 54321) ``` will send messages from two different telegram bots to two different chats. It is useful for example, when you have telegram bot communicating with users and at the same time error logs of this bot is being sent to another chat by error reporting bot. In addition to text messages you can also send any sort of `IO` objects: images, audio, documents and so on. For example to send picture you can do something like this ```julia using Telegram, Telegram.API using ConfigEnv dotenv() open("picture.jpg", "r") do io sendPhoto(photo = io) end # or if you want it quick and dirty sendPhoto(photo = open("picture.jpg", "r")) ``` Data sending is not limited by files only, you can send memory objects as well, in this case you should give them name in the form of `Pair` ```julia using Telegram, Telegram.API using ConfigEnv dotenv() io = IOBuffer() print(io, "Hello world!") sendDocument(document = "hello.txt" => io) ``` ## Logging You can also use [Telegram.jl](https://github.com/Arkoniak/Telegram.jl) as a logging system, for this you are provided with special [`TelegramLogger`](@ref) structure. It accepts `TelegramClient` object which must have initialized `chat_id` parameter ```julia using Telegram using Logging using ConfigEnv dotenv() tg = TelegramClient() tg_logger = TelegramLogger(tg; async = false) with_logger(tg_logger) do @info "Hello from telegram logger!" end ``` But even better it is used together with [LoggingExtras.jl](https://github.com/oxinabox/LoggingExtras.jl) package, which can demux log messages and send critical messages to telegram backend without interrupting normal logging flow ```julia using Telegram using Logging, LoggingExtras using ConfigEnv dotenv() tg = TelegramClient() tg_logger = TelegramLogger(tg; async = false) demux_logger = TeeLogger( MinLevelLogger(tg_logger, Logging.Error), ConsoleLogger() ) global_logger(demux_logger) @warn "It is bad" # goes to console @info "normal stuff" # goes to console @error "THE WORSE THING" # goes to console and telegram @debug "it is chill" # goes to console ``` This way, just by adding few configuration lines, you can have unchanged logging system with telegram instant messaging if anything critically important happened. Also, take notion of `async` argument of `TelegramLogger`. There are two modes of operating, usual and asynchronous. Second is useful if you have long running program and you do not want it to pause and send telegram message, so usual scenario is like this ```julia while true try # do some stuff catch err @error err # process error end end ``` But asynchronous mode has it's drawbacks, consider this for example ```julia try sqrt(:a) catch err @error err end ``` if you run this snippet (with proper logger initialization) from command line, main thread stops before asynchronous message to telegram is sent. In such cases, it make sense to set `async = false` ## Bots ### Echo bot With the help of [`run_bot`](@ref) method it's quite simple to set up simple telegram bots. ```julia using Telegram, Telegram.API using ConfigEnv dotenv() # Echo bot run_bot() do msg sendMessage(text = msg.message.text, chat_id = msg.message.chat.id) end ``` ### Turtle graphics bot In this example we build more advanced bot, which is generating [turtle graphics](http://juliagraphics.github.io/Luxor.jl/stable/turtle/) with the help of [Luxor.jl](https://github.com/JuliaGraphics/Luxor.jl) package. In addition to previous echo bot, this can do the following 1. Generate and send images in memory, without storing them in file system 2. Generate virtual keyboard, which can be used by users to make input easier ```julia using Telegram, Telegram.API using ConfigEnv using Luxor dotenv() """ draw_turtle(angles::AbstractVector) Draw turtle graphics, where turtle is moving in spiral, on each step rotating on next angle from `angles` vector. Vector `angles` is repeated cyclically. """ function draw_turtle(angles) d = Drawing(600, 400, :png) origin() background("midnightblue") 🐢 = Turtle() # you can type the turtle emoji with \:turtle: Pencolor(🐢, "cyan") Penwidth(🐢, 1.5) n = 5.0 dn = 1.0/length(angles)*0.7 for i in 1:400 for angle in angles Forward(🐢, n) Turn(🐢, angle) n += dn end HueShift(🐢) end finish() return d end """ build_keyboard() Generates [telegram keyboard](https://core.telegram.org/bots#keyboards) in the form of 3x3 grid of buttons. """ function build_keyboard() keyboard = Vector{Vector{String}}() for x in 1:3 row = String[] for y in 1:3 s = join(string.(Int.(round.(rand(rand(1:4)) * 360))), " ") push!(row, s) end push!(keyboard, row) end return Dict(:keyboard => keyboard, :one_time_keyboard => true) end run_bot() do msg message = get(msg, :message, nothing) message === nothing && return nothing text = get(message, :text, "") chat = get(message, :chat, nothing) chat === nothing && return nothing chat_id = get(chat, :id, nothing) chat_id === nothing && return nothing if match(r"^[0-9 \.]+$", text) !== nothing angles = parse.(Float64, split(text, " ")) turtle = draw_turtle(angles) sendPhoto(photo = "turtle.png" => turtle.buffer, reply_markup = build_keyboard(), chat_id = chat_id) else sendMessage(text = "Unknown command, please provide turtle instructions in the form `angle1 angle2` or use keyboard", reply_markup = build_keyboard(), chat_id = chat_id, parse_mode = "MarkdownV2") end end ```
Telegram
https://github.com/Arkoniak/Telegram.jl.git
[ "MIT" ]
0.2.0
cf009244790d6ac5b0be9aa4d624490b32a3790c
code
716
using QuantumStatePlots using Documenter DocMeta.setdocmeta!(QuantumStatePlots, :DocTestSetup, :(using QuantumStatePlots); recursive=true) makedocs(; modules=[QuantumStatePlots], authors="JingYu Ning <[email protected]> and contributors", repo="https://github.com/foldfelis-QO/QuantumStatePlots.jl/blob/{commit}{path}#{line}", sitename="QuantumStatePlots.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://foldfelis-QO.github.io/QuantumStatePlots.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/foldfelis-QO/QuantumStatePlots.jl", devbranch="master", )
QuantumStatePlots
https://github.com/foldfelis-QO/QuantumStatePlots.jl.git
[ "MIT" ]
0.2.0
cf009244790d6ac5b0be9aa4d624490b32a3790c
code
2948
module QuantumStatePlots using Plots using QuantumStateBase export plot_real, plot_imag # ########## # # wigner # # ########## """ Plots.surface(w::WignerSurface; kwargv...) Plot Wigner function in surface. """ function Plots.surface(w::WignerSurface; kwargv...) lim = maximum(abs.(w.𝐰_surface)) default_kwargv = Dict([ :title => "Wigner Function", :xlabel => "X", :ylabel => "P", :zlabel => "Quasiprobability", :clim => (-lim, lim), :color => :coolwarm, :camera => (40, 30), ]) return surface(w.x_range, w.p_range, w.𝐰_surface'; merge(default_kwargv, kwargv)...) end """ Plots.heatmap(w::WignerSurface; kwargv...) Plot Wigner function in heatmap. """ function Plots.heatmap(w::WignerSurface; kwargv...) lim = maximum(abs.(w.𝐰_surface)) default_kwargv = Dict([ :title => "Wigner Function", :xlabel => "X", :ylabel => "P", :clim => (-lim, lim), :color => :coolwarm, :aspect_ratio => :equal, ]) return heatmap(w.x_range, w.p_range, w.𝐰_surface'; merge(default_kwargv, kwargv)...) end """ Plots.contour(w::WignerSurface; kwargv...) Plot Wigner function in contour. """ function Plots.contour(w::WignerSurface; kwargv...) lim = maximum(abs.(w.𝐰_surface)) default_kwargv = Dict([ :title => "Wigner Function", :xlabel => "X", :ylabel => "P", :clim => (-lim, lim), :color => :coolwarm, :aspect_ratio => :equal, :fill => true, :levels => 20, ]) return contour(w.x_range, w.p_range, w.𝐰_surface'; merge(default_kwargv, kwargv)...) end # ##### # # ρ # # ##### """ plot_real(ρ, [truncate::Integer]; kwargv...) Plot real part of a density matrix. ## Arguments * `truncate`: Truncate photon number """ function plot_real(ρ, truncate=0; kwargv...) return plot_ρ(real(ρ), truncate; merge(Dict([:title => "Density Matrux (real part)"]), kwargv)...) end """ plot_imag(ρ, [truncate::Integer]; kwargv...) Plot imag part of a density matrix. ## Arguments * `truncate`: Truncate photon number """ function plot_imag(ρ, truncate=0; kwargv...) return plot_ρ(imag(ρ), truncate; merge(Dict([:title => "Density Matrux (imag part)"]), kwargv)...) end function plot_ρ(ρ::AbstractMatrix, truncate::Integer; kwargv...) photon_number_range = Base.OneTo(size(ρ, 1)) if truncate > 0 photon_number_range = 1:truncate ρ = ρ[photon_number_range, photon_number_range] end photon_number_range = photon_number_range .- 1 # labels of m, n lim = maximum(abs.(ρ)) default_kwargv = Dict([ :title => "Density Matrux", :xlabel => "m", :ylabel => "n", :clim => (-lim, lim), :color => :coolwarm, :aspect_ratio => :equal, ]) return heatmap(photon_number_range, photon_number_range, ρ; merge(default_kwargv, kwargv)...) end end
QuantumStatePlots
https://github.com/foldfelis-QO/QuantumStatePlots.jl.git
[ "MIT" ]
0.2.0
cf009244790d6ac5b0be9aa4d624490b32a3790c
code
626
using QuantumStatePlots using Plots using QuantumStateBase using VisualRegressionTests using Test @testset "QuantumStatePlots.jl" begin ENV["GKSwstype"]="nul" ρ = SqueezedState(0.8, π/8, Matrix, dim=100) w = wigner(ρ, LinRange(-3, 3, 101), LinRange(-3, 3, 101)) # ########## # # wigner # # ########## @plottest begin surface(w) end "assets/surface.png" @plottest begin heatmap(w) end "assets/heatmap.png" @plottest begin contour(w) end "assets/contour.png" # ##### # # ρ # # ##### @plottest begin plot_real(ρ, 35) end "assets/real.png" @plottest begin plot_imag(ρ, 35) end "assets/imag.png" end
QuantumStatePlots
https://github.com/foldfelis-QO/QuantumStatePlots.jl.git
[ "MIT" ]
0.2.0
cf009244790d6ac5b0be9aa4d624490b32a3790c
docs
1573
# QuantumStatePlots [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://foldfelis-qo.github.io/QuantumStatePlots.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://foldfelis-qo.github.io/QuantumStatePlots.jl/dev) [![CI](https://github.com/foldfelis-QO/QuantumStatePlots.jl/actions/workflows/CI.yml/badge.svg)](https://github.com/foldfelis-QO/QuantumStatePlots.jl/actions/workflows/CI.yml) [![codecov](https://codecov.io/gh/foldfelis-QO/QuantumStatePlots.jl/branch/master/graph/badge.svg?token=6VKJECY4CX)](https://codecov.io/gh/foldfelis-QO/QuantumStatePlots.jl) ## Example The quantum state and its wigner function: ```julia julia> using QuantumStateBase julia> ρ = SqueezedState(0.8, π/8, Matrix, dim=100) julia> w = wigner(ρ, LinRange(-3, 3, 101), LinRange(-3, 3, 101)); ``` ### Wigner function **Surface** ```julia julia> using QuantumStatePlots, Plots julia> surface(w) ``` ![](docs/src/assets/surface.png) **Heatmap** ```julia julia> using QuantumStatePlots, Plots julia> heatmap(w) ``` ![](docs/src/assets/heatmap.png) **Contour** ```julia julia> using QuantumStatePlots, Plots julia> contour(w) ``` ![](docs/src/assets/contour.png) ### Density matrix **Real part** ```julia julia> using QuantumStatePlots, Plots julia> plot_real(ρ, 35) ``` ![](docs/src/assets/real.png) **Imag part** ```julia julia> using QuantumStatePlots, Plots julia> plot_imag(ρ, 35) ``` ![](docs/src/assets/imag.png) ## Reference * [Quantum mechanics as a statistical theory](https://doi.org/10.1017/S0305004100000487)
QuantumStatePlots
https://github.com/foldfelis-QO/QuantumStatePlots.jl.git
[ "MIT" ]
0.2.0
cf009244790d6ac5b0be9aa4d624490b32a3790c
docs
2264
```@meta CurrentModule = QuantumStatePlots ``` # QuantumStatePlots Documentation for [QuantumStatePlots](https://github.com/foldfelis-QO/QuantumStatePlots.jl). ## About ### Render Wigner function Based on the definition of Wigner function in Fock basis: ```math W_{mn}(x, p) = \frac{1}{2\pi} \int_{-\infty}^{\infty} dy \, e^{-ipy/h} \psi_m^*(x+\frac{y}{2}) \psi_n(x-\frac{y}{2}) ``` Owing to the fact that the Moyal function is a generalized Wigner function. We can therefore implies that ```math W(x, p) = \sum_{m, n} \rho_{m, n} W_{m, n}(x, p) ``` Here, ``\rho`` is the density matrix of the quantum state, defined as: ```math \rho = \sum_{m, n, i} \, p_i \, | n \rangle \langle n | \hat{\rho}_i | m \rangle \langle m | ``` ```math \hat{\rho}_i = | \psi_i \rangle \langle \psi_i | ``` ```math \hat{\rho}_i \, \text{is a density operator of pure state.} ``` And, ``W_{m, n}(x, p)`` is the generalized Wigner function ```math W_{m, n} = \{ \begin{array}{rcl} \frac{1}{\pi} exp[-(x^2 + y^2)] (-1)^m \sqrt{2^{n-m} \frac{m!}{n!}} (x-ip)^{n-m} L_m^{n-m} (2x^2 + 2p^2), \, n \geq m \\ \frac{1}{\pi} exp[-(x^2 + y^2)] (-1)^n \sqrt{2^{m-n} \frac{n!}{m!}} (x+ip)^{m-n} L_n^{m-n} (2x^2 + 2p^2), \, n < m \\ \end{array} ``` ### Example The quantum state and its wigner function: ```julia-repl julia> using QuantumStateBase julia> ρ = SqueezedState(0.8, π/8, Matrix, dim=100) julia> w = wigner(ρ, LinRange(-3, 3, 101), LinRange(-3, 3, 101)); ``` #### Wigner function **Surface** ```julia-repl julia> using QuantumStatePlots, Plots julia> surface(w) ``` ![](assets/surface.png) **Heatmap** ```julia-repl julia> using QuantumStatePlots, Plots julia> heatmap(w) ``` ![](assets/heatmap.png) **Contour** ```julia-repl julia> using QuantumStatePlots, Plots julia> contour(w) ``` ![](assets/contour.png) #### Density matrix **Real part** ```julia-repl julia> using QuantumStatePlots, Plots julia> plot_real(ρ, 35) ``` ![](assets/real.png) **Imag part** ```julia-repl julia> using QuantumStatePlots, Plots julia> plot_imag(ρ, 35) ``` ![](assets/imag.png) ### Reference * [Quantum mechanics as a statistical theory](https://doi.org/10.1017/S0305004100000487) ## Index ```@index ``` ## APIs ```@autodocs Modules = [QuantumStatePlots] ```
QuantumStatePlots
https://github.com/foldfelis-QO/QuantumStatePlots.jl.git
[ "MIT" ]
0.1.10
31b36161dc4aa42e56b3ece2377df71d3ebce1c0
code
303
module VlasiatorMakie using Vlasiator, StatsBase, Printf using Vlasiator: AxisUnit, ColorScale using Makie using Makie.LaTeXStrings: latexstring include("typerecipe.jl") include("fullrecipe.jl") include("interactive.jl") export vlheatmap, vlslice, vlslices, vdfvolume, vdfslice, vdfslices end
VlasiatorMakie
https://github.com/henry2004y/VlasiatorMakie.jl.git
[ "MIT" ]
0.1.10
31b36161dc4aa42e56b3ece2377df71d3ebce1c0
code
10146
# Full recipes for customized Vlasiator plots. """ viz(meta, var; args) Visualize Vlasiator output `var` in `meta` with various options: * `axisunit` - unit of axis of type `AxisUnit` * `colorscale` - scale of colormap of type `ColorScale` * `normal` - slice normal direction * `vmin` - minimum color value * `vmax` - maximum color value * `comp` - selection of vector components """ @recipe(Viz, meta, var) do scene Attributes(; # generic attributes colormap = :turbo, markersize = Makie.theme(scene, :markersize), colorrange = Makie.automatic, levels = 5, linewidth = 1.0, alpha = 1.0, # Vlasiator.jl attributes axisunit = EARTH, colorscale = Linear, normal = :y, # only works in 3D vmin = -Inf, vmax = Inf, comp = 0, origin = 0.0, ) end function Makie.plot!(vlplot::Viz) meta = vlplot[:meta][] var = vlplot[:var][] comp = vlplot.comp[] normal = vlplot.normal[] axisunit = vlplot.axisunit[] vmin = vlplot.vmin[] vmax = vlplot.vmax[] colorscale = vlplot.colorscale[] origin = vlplot.origin[] if ndims(meta) == 1 data = readvariable(meta, var) x = LinRange(meta.coordmin[1], meta.coordmax[1], meta.ncells[1]) lines!(vlplot, x, data) elseif ndims(meta) == 2 pArgs = Vlasiator.set_args(meta, var, axisunit) x, y = Vlasiator.get_axis(axisunit, pArgs.plotrange, pArgs.sizes) data = Vlasiator.prep2d(meta, var, comp) if var in ("fg_b", "fg_e", "vg_b_vol", "vg_e_vol") || endswith(var, "vg_v") rho_ = findfirst(endswith("rho"), meta.variable) if !isnothing(rho_) rho = readvariable(meta, meta.variable[rho_]) rho = reshape(rho, pArgs.sizes[1], pArgs.sizes[2]) mask = findall(==(0.0), rho) if ndims(data) == 2 @inbounds data[mask] .= NaN else ind = CartesianIndices((pArgs.sizes[1], pArgs.sizes[2])) for m in mask @inbounds data[:, ind[m][1], ind[m][2]] .= NaN end end end end if colorscale == Log # Logarithmic plot if any(<(0), data) throw(DomainError(data, "Nonpositive data detected: use linear scale instead!")) end datapositive = data[data .> 0.0] v1 = isinf(vmin) ? minimum(datapositive) : vmin v2 = isinf(vmax) ? maximum(x->isnan(x) ? -Inf : x, data) : vmax elseif colorscale == Linear v1 = isinf(vmin) ? minimum(x->isnan(x) ? +Inf : x, data) : vmin v2 = isinf(vmax) ? maximum(x->isnan(x) ? -Inf : x, data) : vmax nticks = 9 ticks = range(v1, v2, length=nticks) end vlplot.colorrange = [v1, v2] heatmap!(vlplot, x, y, data, colormap=vlplot.colormap) else # 3D pArgs = Vlasiator.set_args(meta, var, axisunit; normal, origin) x, y = Vlasiator.get_axis(axisunit, pArgs.plotrange, pArgs.sizes) data = Vlasiator.prep2dslice(meta, var, normal, comp, pArgs) heatmap!(vlplot, x, y, data, colormap=vlplot.colormap) end vlplot end function vlheatmap(meta::MetaVLSV, var::String; fig=nothing, addcolorbar::Bool=true, axisunit::AxisUnit=EARTH, kwargs...) pArgs = Vlasiator.set_args(meta, var, axisunit) isnothing(fig) && (fig = Figure()) c = viz(fig[1,1], meta, var; axisunit, kwargs...) c.axis.title = @sprintf "t= %4.1fs" meta.time # TODO: limitation in Makie 0.16.2: no conversion from initial String type c.axis.xlabel = pArgs.strx c.axis.ylabel = pArgs.stry c.axis.autolimitaspect = 1 if addcolorbar cbar = Colorbar(fig[1,2], c.plot, label=latexstring(pArgs.cb_title), tickalign=1) colgap!(fig.layout, 7) end fig end """ vlslices(meta::MetaVLSV, var; axisunit=SI, comp=0, origin=[0.0, 0.0, 0.0]) Three orthogonal slices of `var` from `meta`. """ function vlslices(meta::MetaVLSV, var::String; fig=nothing, axisunit::AxisUnit=SI, comp::Union{Symbol, Int}=0, origin::AbstractVector=[0.0, 0.0, 0.0], addcolorbar::Bool=false, colorscale::ColorScale=Linear, vmin::Real=-Inf, vmax::Real=Inf) if axisunit == EARTH unitx = " [Re]" origin .*= Vlasiator.RE else unitx = " [m]" end pArgs1 = Vlasiator.set_args(meta, var, axisunit; normal=:x, origin=origin[1]) pArgs2 = Vlasiator.set_args(meta, var, axisunit; normal=:y, origin=origin[2]) pArgs3 = Vlasiator.set_args(meta, var, axisunit; normal=:z, origin=origin[3]) x, y = Vlasiator.get_axis(axisunit, pArgs3.plotrange, pArgs3.sizes) x, z = Vlasiator.get_axis(axisunit, pArgs2.plotrange, pArgs2.sizes) d1 = Vlasiator.prep2dslice(meta, var, :x, comp, pArgs1) d2 = Vlasiator.prep2dslice(meta, var, :y, comp, pArgs2) d3 = Vlasiator.prep2dslice(meta, var, :z, comp, pArgs3) isnothing(fig) && (fig = Figure(fontsize=22)) ax = Axis3(fig[1,1], aspect=(1, 1, 1), elevation=pi/6, perspectiveness=0.5) ax.xlabel = "x"*unitx ax.ylabel = "y"*unitx ax.zlabel = "z"*unitx xlims!(ax, x[1], x[end]) ylims!(ax, y[1], y[end]) zlims!(ax, z[1], z[end]) vmin1, vmax1 = Vlasiator.set_lim(vmin, vmax, d1, colorscale) vmin2, vmax2 = Vlasiator.set_lim(vmin, vmax, d2, colorscale) vmin3, vmax3 = Vlasiator.set_lim(vmin, vmax, d3, colorscale) colormap = :turbo colorrange = (min(vmin1, vmin2, vmin3), max(vmax1, vmax2, vmax3)) h1 = heatmap!(ax, y, z, d1; colormap, colorrange, transformation=(:yz, origin[1])) h2 = heatmap!(ax, x, z, d2; colormap, colorrange, transformation=(:xz, origin[2])) h3 = heatmap!(ax, x, y, d3; colormap, colorrange, transformation=(:xy, origin[3])) if addcolorbar cbar = Colorbar(fig[1,2], h3, label=latexstring(pArgs1.cb_title), tickalign=1) colgap!(fig.layout, 7) end fig, ax end """ vdfvolume(meta, location; species="proton", unit=SI, flimit=-1.0, verbose=false) Meshscatter plot of VDFs in 3D. """ function vdfvolume(meta::MetaVLSV, location::AbstractVector; species::String="proton", unit::AxisUnit=SI, flimit::Real=-1.0, verbose::Bool=false, fig=nothing) if haskey(meta.meshes, species) vmesh = meta.meshes[species] else throw(ArgumentError("Unable to detect population $species")) end loc = unit == EARTH ? location .* Vlasiator.RE : location # Calculate cell ID from given coordinates cidReq = getcell(meta, loc) cidNearest = getnearestcellwithvdf(meta, cidReq, species) ccoords = getcellcoordinates(meta, cidNearest) if verbose @info "Species : $species" @info "Original coordinates: $loc" @info "Original cell : $cidReq" @info "Actual cell : $cidNearest" @info "Actual coordinates : $ccoords" end vcellids, vcellf = readvcells(meta, cidNearest; species) V = getvcellcoordinates(meta, vcellids; species) # Set sparsity threshold if flimit < 0 flimit = if hasvariable(meta, species*"/vg_effectivesparsitythreshold") readvariable(meta, species*"/vg_effectivesparsitythreshold", cidNearest) elseif hasvariable(meta, species*"/EffectiveSparsityThreshold") readvariable(meta, species*"/EffectiveSparsityThreshold", cidNearest) else 1f-16 end end # Drop velocity cells which are below the sparsity threshold findex_ = vcellf .≥ flimit fselect = vcellf[findex_] Vselect = V[findex_] cmap = resample_cmap(:turbo, 101; alpha=(0, 1)) isnothing(fig) && (fig = Figure(fontsize=22)) if unit == SI ax = Axis3(fig[1, 1], aspect=(1,1,1), title="VDF at $ccoords (m) in log scale", titlesize=26) elseif unit == EARTH coords = round.(ccoords ./ Vlasiator.RE, digits=1) ax = Axis3(fig[1, 1], aspect=(1,1,1), title="VDF at $coords (RE) in log scale", titlesize=26) end ax.xlabel = "vx [m/s]" ax.ylabel = "vy [m/s]" ax.zlabel = "vz [m/s]" plt = meshscatter!(ax, Vselect, color=log10.(fselect), marker=Rect3f(Vec3f(0), Vec3f(4*vmesh.dv[1])), colormap=cmap, transparency=true, shading=false) cbar = Colorbar(fig, plt, label="f(v)") fig[1, 2] = cbar fig, ax end struct LogMinorTicks end function Makie.get_minor_tickvalues(::LogMinorTicks, scale, tickvalues, vmin, vmax) vals = Float64[] extended_tickvalues = [ tickvalues[1] - (tickvalues[2] - tickvalues[1]); tickvalues; tickvalues[end] + (tickvalues[end] - tickvalues[end-1]); ] for (lo, hi) in zip( @view(extended_tickvalues[1:end-1]), @view(extended_tickvalues[2:end]) ) interval = hi - lo steps = log10.(LinRange(10^lo, 10^hi, 11)) append!(vals, steps[2:end-1]) end return filter(x -> vmin < x < vmax, vals) end custom_formatter(values) = map( v -> "10" * Makie.UnicodeFun.to_superscript(round(Int64, v)), values ) function vdfslice(meta, location; species="proton", unit=SI, unitv="km/s", slicetype=:default, vslicethick=0.0, center=:nothing, vmin=-Inf, vmax=Inf, weight=:particle, flimit=-1.0, verbose=false, fig=nothing) v1, v2, r1, r2, fweight, strx, stry, str_title = Vlasiator.prep_vdf(meta, location; species, unit, unitv, slicetype, vslicethick, center, weight, flimit, verbose) isinf(vmin) && (vmin = minimum(fweight)) isinf(vmax) && (vmax = maximum(fweight)) verbose && @info "Active f range is $vmin, $vmax" h = fit(Histogram, (v1, v2), weights(fweight), (r1, r2)) clims = (vmin, maximum(h.weights)) data = [isinf(x) ? NaN : x for x in log10.(h.weights)] isnothing(fig) && (fig = Figure()) ax, hm = heatmap(fig[1, 1], r1, r2, data; colormap=:turbo, colorrange=log10.(clims)) cb = Colorbar(fig[1, 2], hm; label="f(v)", tickformat=custom_formatter, minorticksvisible=true, minorticks=LogMinorTicks() ) ax.title = str_title ax.xlabel = strx ax.ylabel = stry fig, ax end
VlasiatorMakie
https://github.com/henry2004y/VlasiatorMakie.jl.git
[ "MIT" ]
0.1.10
31b36161dc4aa42e56b3ece2377df71d3ebce1c0
code
4101
# Interactive plots with Observables """ vlslice(meta, var; normal=:y, axisunit=SI, comp=0) Interactive 2D slice of 3D `var` in `normal` direction. """ function vlslice(meta::MetaVLSV, var::String; normal::Symbol=:y, axisunit::AxisUnit=SI, comp::Union{Symbol, Int}=0) dir, str1, str2 = if normal == :x 1, "y", "z" elseif normal == :y 2, "x", "z" else 3, "x", "y" end unitx = axisunit == EARTH ? " [Re]" : " [m]" dx = meta.dcoord[dir] / 2^meta.maxamr pArgs = Vlasiator.set_args(meta, var, axisunit; normal, origin=0.0) x, y = Vlasiator.get_axis(axisunit, pArgs.plotrange, pArgs.sizes) nsize = meta.ncells[dir] depth = nsize*2^meta.maxamr fig = Figure() ax = Axis(fig[1, 1], aspect=DataAspect()) ax.xlabel = str1*unitx ax.ylabel = str2*unitx lsgrid = SliderGrid(fig[2, 1], (label = "location in normal direction $(String(normal))", range=1:depth, format=x -> "$(x) cells"), ) sliderobservables = [s.value for s in lsgrid.sliders] slice = lift(sliderobservables...) do slvalues... begin origin = (slvalues[1]-1)*dx + meta.coordmin[dir] pArgs = Vlasiator.set_args(meta, var, axisunit; normal, origin) Vlasiator.prep2dslice(meta, var, normal, comp, pArgs) end end heatmap!(ax, x, y, slice, colormap=:turbo) set_close_to!(lsgrid.sliders[1], .5depth) fig, ax end """ vdfslices(meta, location; fmin=1f-16, species="proton", unit=SI, verbose=false) Three orthogonal slices of VDFs from `meta` at `location`. # Optional Arguments - `fmin`: minimum VDF threshold for plotting. - `species`: name of particle. - `unit`: unit of input `location`, `SI` or `EARTH`. """ function vdfslices(meta::MetaVLSV, location::AbstractVector; fmin::AbstractFloat=1f-16, species::String="proton", unit::AxisUnit=SI, verbose::Bool=false) if haskey(meta.meshes, species) vmesh = meta.meshes[species] else throw(ArgumentError("Unable to detect population $species")) end unit == EARTH && (location .*= Vlasiator.RE) # Calculate cell ID from given coordinates cidReq = getcell(meta, location) cidNearest = getnearestcellwithvdf(meta, cidReq) cellused = getcellcoordinates(meta, cidNearest) if verbose @info "Original coordinates : $location" @info "Original cell : $(getcellcoordinates(meta, cidReq))" @info "Nearest cell with VDF: $cellused" let x, y, z = getcellcoordinates(meta, cidNearest) @info "cellid $cidNearest, x = $x, y = $y, z = $z" end end vcellids, vcellf = readvcells(meta, cidNearest; species) f = Vlasiator.reconstruct(vmesh, vcellids, vcellf) fig = Figure() ax = Axis3(fig[1, 1], aspect=(1,1,1), title = "VDF at $cellused in log scale") ax.xlabel = "vx [m/s]" ax.ylabel = "vy [m/s]" ax.zlabel = "vz [m/s]" x = LinRange(vmesh.vmin[1], vmesh.vmax[1], vmesh.vblock_size[1]*vmesh.vblocks[1]) y = LinRange(vmesh.vmin[2], vmesh.vmax[2], vmesh.vblock_size[2]*vmesh.vblocks[2]) z = LinRange(vmesh.vmin[3], vmesh.vmax[3], vmesh.vblock_size[3]*vmesh.vblocks[3]) lsgrid = SliderGrid(fig[2, 1], (label="vx", range=1:length(x), format=i -> "$(round(x[i], digits=2))"), (label="vy", range=1:length(y), format=i -> "$(round(y[i], digits=2))"), (label="vz", range=1:length(z), format=i -> "$(round(z[i], digits=2))"), ) for i in eachindex(f) if f[i] < fmin f[i] = fmin end end data = log10.(f) plt = volumeslices!(ax, x, y, z, data, colormap=:viridis) #TODO: improve on colormap setup! cbar = Colorbar(fig, plt, label="f(v)", minorticksvisible=true) fig[1, 2] = cbar # connect sliders to volumeslices update methods sl_yz, sl_xz, sl_xy = lsgrid.sliders on(sl_yz.value) do v; plt[:update_yz][](v) end on(sl_xz.value) do v; plt[:update_xz][](v) end on(sl_xy.value) do v; plt[:update_xy][](v) end set_close_to!(sl_yz, .5length(x)) set_close_to!(sl_xz, .5length(y)) set_close_to!(sl_xy, .5length(z)) fig end
VlasiatorMakie
https://github.com/henry2004y/VlasiatorMakie.jl.git
[ "MIT" ]
0.1.10
31b36161dc4aa42e56b3ece2377df71d3ebce1c0
code
2144
# Type conversion from Vlasiator to Makie "Conversion for 1D plots" function Makie.convert_arguments(P::PointBased, meta::MetaVLSV, var::String) data = readvariable(meta, var) x = LinRange(meta.coordmin[1], meta.coordmax[1], meta.ncells[1]) ([Point2f(i, j) for (i, j) in zip(x, data)],) end "Conversion for 2D plots." function Makie.convert_arguments(P::SurfaceLike, meta::MetaVLSV, var::String, axisunit::AxisUnit=EARTH, comp::Union{Symbol, Int}=0, normal::Symbol=:y, origin::AbstractFloat=0.0) if meta.maxamr > 0 pArgs = Vlasiator.set_args(meta, var, axisunit; normal, origin) data = Vlasiator.prep2dslice(meta, var, normal, comp, pArgs) else pArgs = Vlasiator.set_args(meta, var, axisunit) data = Vlasiator.prep2d(meta, var, comp) end x, y = Vlasiator.get_axis(axisunit, pArgs.plotrange, pArgs.sizes) (x, y, data) end "Conversion for 3D plots." function Makie.convert_arguments(P::VolumeLike, meta::MetaVLSV, var::String, axisunit::AxisUnit=EARTH, comp::Union{Symbol, Int}=1) (;ncells, coordmin, coordmax) = meta # Scale the sizes to the highest refinement level sizes = ncells .<< meta.maxamr # data needs to be refined later if axisunit == EARTH x = LinRange(coordmin[1], coordmax[1], sizes[1]) ./ Vlasiator.RE y = LinRange(coordmin[2], coordmax[2], sizes[2]) ./ Vlasiator.RE z = LinRange(coordmin[3], coordmax[3], sizes[3]) ./ Vlasiator.RE else x = LinRange(coordmin[1], coordmax[1], sizes[1]) y = LinRange(coordmin[2], coordmax[2], sizes[2]) z = LinRange(coordmin[3], coordmax[3], sizes[3]) end if startswith(var, "fg") data = meta[var] if comp == 0 data = [√(data[1,i,j,k]^2 + data[2,i,j,k]^2 + data[3,i,j,k]^2) for k in axes(data, 4), j in axes(data, 3), i in axes(data, 2)] else data = data[comp,:,:,:] end else data, _ = Vlasiator.fillmesh(meta, var) # Select on the finest refinement level if comp == 0 data = data[1][end][1,:,:,:] else data = data[1][end][comp,:,:,:] end end (x, y, z, data) end
VlasiatorMakie
https://github.com/henry2004y/VlasiatorMakie.jl.git
[ "MIT" ]
0.1.10
31b36161dc4aa42e56b3ece2377df71d3ebce1c0
code
1459
using VlasiatorMakie, Vlasiator, LazyArtifacts using Test using Suppressor: @suppress_err using GLMakie @testset "VlasiatorMakie.jl" begin rootpath = artifact"testdata" files = joinpath.(rootpath, ("bulk.1d.vlsv", "bulk.2d.vlsv", "bulk.amr.vlsv")) meta1 = load(files[1]) meta2 = load(files[2]) meta3 = load(files[3]) var = "proton/vg_rho" fig, ax, plt = viz(meta1, var) @test plt isa Combined fig, ax, plt = viz(meta2, "vg_b_vol") @test plt isa Combined fig, ax, plt = viz(meta3, "proton/vg_rho") @test plt isa Combined fig, ax, plt = lines(meta1, var) @test plt isa Lines fig = vlheatmap(meta2, var) @test fig isa Figure fig, ax, plt = heatmap(meta2, var) @test plt isa Heatmap fig, ax, plt = heatmap(meta2, var, EARTH, 0, :z) @test plt isa Heatmap fig, ax = vlslice(meta3, var) @test fig isa Figure fig, ax = vlslices(meta3, var; addcolorbar=true) @test fig isa Figure fig = volume(meta3, "fg_b", EARTH, 3; algorithm=:iso, isovalue=0.0, isorange=1e-9) @test fig isa Makie.FigureAxisPlot location = [0.0, 0.0, 0.0] fig, ax = VlasiatorMakie.vdfslice(meta1, location) @test fig isa Figure fig = vdfslices(meta1, location) @test fig isa Figure @suppress_err begin fig, ax = vdfvolume(meta1, location; verbose=true) end @test fig isa Figure fig, ax = vdfvolume(meta1, location; unit=EARTH, verbose=false) @test fig isa Figure end
VlasiatorMakie
https://github.com/henry2004y/VlasiatorMakie.jl.git
[ "MIT" ]
0.1.10
31b36161dc4aa42e56b3ece2377df71d3ebce1c0
docs
3012
# VlasiatorMakie.jl [![Build Status](https://github.com/henry2004y/VlasiatorMakie.jl/workflows/CI/badge.svg)](https://github.com/henry2004y/VlasiatorMakie.jl/actions?query=workflow%3ACI+branch%3Amain) [![Coverage](https://codecov.io/gh/henry2004y/VlasiatorMakie.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/henry2004y/VlasiatorMakie.jl) Makie recipes for visualization of [Vlasiator.jl](https://github.com/henry2004y/Vlasiator.jl.git). ## Installation ```julia ] add VlasiatorMakie ``` ## Usage Both simple type conversion recipes for 1D and 2D data and full recipes for customized and interactive plots are provided. See more example outputs in [Vlasiator gallery](https://henry2004y.github.io/Vlasiator.jl/dev/gallery/#Makie) and detailed usages in the [manual](https://henry2004y.github.io/Vlasiator.jl/dev/manual/#Makie-Backend) and test scripts. Due to the current limitation of the full recipes from Makie, it is recommended to work with the simpler type recipes, i.e. identical plotting functions as in Makie but with the first two arguments being `meta` and `var`. ```julia using Vlasiator, VlasiatorMakie, GLMakie file = "bulk.0000001.vlsv" meta = load(file) heatmap(meta, "proton/vg_rho") ``` 3D isosurface: ```julia fig = volume(meta, "fg_b", EARTH, 3; algorithm=:iso, isovalue=0.0, isorange=1e-9) ``` Single figure contour plot: ```julia fig = Figure(resolution=(700, 600), fontsize=18) ga = fig[1,1] = GridLayout() ax = Axis(fig[1,1], aspect = DataAspect(), title = "t = $(round(meta.time, digits=1))s", xlabel = L"x [$R_E$]", ylabel = L"y [$R_E$]" ) hmap = heatmap!(meta, "proton/vg_rho", colormap=:turbo) cbar = Colorbar(fig, hmap, label=L"$\rho$ [amu/cc]", width=13, ticksize=13, tickalign=1, height=Relative(1)) fig[1,2] = cbar colgap!(ga, 1) ``` Multi-figure contour plots: ```julia fig = Figure(resolution=(1100, 800), fontsize=18) axes = [] v_str = ["CellID", "proton/vg_rho", "proton/vg_v", "vg_pressure", "vg_b_vol", "vg_e_vol"] c_str = ["", L"$\rho$ [amu/cc]", "[m/s]", "[Pa]", "[T]", "[V/m]"] c = 1 for i in 1:2, j in 1:2:5 ax = Axis(fig[i,j], aspect=DataAspect(), xgridvisible=false, ygridvisible=false, title = v_str[c], xlabel = L"x [$R_E$]", ylabel = L"y [$R_E$]") hmap = heatmap!(meta, v_str[c], colormap=:turbo) cbar = Colorbar(fig, hmap, label=c_str[c], width=13, ticksize=13, tickalign=1, height=Relative(1)) fig[i, j+1] = cbar c += 1 push!(axes, ax) # just in case you need them later. end fig[0, :] = Label(fig, "t = $(round(meta.time, digits=1))s") ``` Adjusting axis limits: ```julia location = [0, 0, 0] fig = VlasiatorMakie.vdfslice(meta, location) xlims!(fig.content[1], -1000, 1000) ylims!(fig.content[1], -1000, 1000) limits!(fig.content[1], 0, 10, 0, 10) # xmin, xmax, ymin, ymax ``` Saving figure: ```julia fig = vdfvolume(meta, location) save("output.png", fig) ``` The resolution is a property of the Figure object returned from the function.
VlasiatorMakie
https://github.com/henry2004y/VlasiatorMakie.jl.git
[ "MIT" ]
0.2.3
c886092ba2e14a4500a3e0b99b298d104fe60b46
code
427
module InteractiveGeodynamicsGLMakieExt import InteractiveGeodynamics: sill_intrusion_1D # We do not check `isdefined(Base, :get_extension)` as recommended since # Julia v1.9.0 does not load package extensions when their dependency is # loaded from the main environment. if VERSION >= v"1.9.1" using GLMakie else using ..GLMakie end include("../src/ThermalIntrusion_1D/ThermalCode_1D_GLMakie.jl") end # module
InteractiveGeodynamics
https://github.com/JuliaGeodynamics/InteractiveGeodynamics.jl.git
[ "MIT" ]
0.2.3
c886092ba2e14a4500a3e0b99b298d104fe60b46
code
815
module InteractiveGeodynamics # Rising sphere app include("./RisingSphere/RisingSphere_Dash.jl") using .RisingSphereTools export rising_sphere # rayleigh_taylor app include("./RayleighTaylorInstability/RTI_Dash.jl") using .RTITools export rayleigh_taylor # convection app include("./RayleighBenardConvection/Convection_Dash.jl") using .ConvectionTools export convection # free subduction app include("./FreeSubduction/FreeSubduction_Dash.jl") using .FreeSubductionTools export subduction # folding app include("./Folding/Folding_Dash.jl") using .FoldingTools export folding """ sill_intrusion_1D GUI to intrude magma-filles sills into the crust using a 1D thermal model. It requires you to load `GLMakie`. """ function sill_intrusion_1D end export sill_intrusion_1D end # module InteractiveGeodynamics
InteractiveGeodynamics
https://github.com/JuliaGeodynamics/InteractiveGeodynamics.jl.git
[ "MIT" ]
0.2.3
c886092ba2e14a4500a3e0b99b298d104fe60b46
code
19311
#module Dash_tools using DelimitedFiles using Dash, DashBootstrapComponents using PlotlyJS #export create_main_figure, get_data, get_trigger, read_colormaps, active_switch, has_pvd_file, # make_title, make_plot, make_plot_controls, make_id_label, make_time_card, make_menu, # make_accordion_item, make_rheological_parameters # various handy and reusable functions """ Creates the main figure plot. """ function create_main_figure(OutFile, cur_t, x=1:10, y=1:10, data=rand(10, 10), x_con=1:10, y_con=1:10, data_con=rand(10, 10) ; colorscale="batlow", field="phase", add_contours=true, add_velocity=false, contour_field="phase", session_id="", cmaps=[]) data_plot = [heatmap(x=x, y=y, z=data, colorscale=cmaps[Symbol(colorscale)], colorbar=attr(thickness=5, title=field, len=0.75), #zmin=zmin, zmax=zmax ) ] if add_contours == true push!(data_plot, ( contour(x=x_con, y=y_con, z=data_con, colorscale=cmaps[Symbol(colorscale)], contours_coloring="lines", line_width=2, colorbar=attr(thickness=5, title=contour_field, x=1.2, yanchor=0.5, len=0.75), #zmin=zmin, zmax=zmax ))) end if add_velocity == true user_dir = simulation_directory(session_id, clean=false) arrowhead, line = calculate_quiver(OutFile, cur_t, cmaps; colorscale="batlow", Dir=user_dir) push!(data_plot, arrowhead) push!(data_plot, line) end layout_data = (xaxis=attr( title="Width", tickfont_size=14, tickfont_color="rgb(100, 100, 100)", scaleanchor="y", scaleratio=1, autorange=false, automargin="top", range=[x[1],x[end]], showgrid=false, zeroline=false ), yaxis=attr( title="Depth", tickfont_size=14, tickfont_color="rgb(10, 10, 10)", autorange=false, automargin="top", autorangeoptions=attr(clipmax=0), range=[minimum(y),maximum(y)], showgrid=false, zeroline=false ), margin=attr(autoexpand="true", pad=1), ) # Specify size; since this does not always work you can set an autosize too (gives more white space) layout_data = merge(layout_data, (autosize=true,)); # Create plot pl = (id="fig_cross", data=data_plot, colorbar=Dict("orientation" => "v", "len" => 0.5), layout=layout_data, config=(edits = (shapePosition=true,)), ) return pl end """ x, z, data = get_data(OutFile::String, tstep::Int64=0, field::String="phase", Dir="") This loads the timestep `tstep` from a LaMEM simulation with field `field`. """ function get_data(OutFile::String, tstep::Int64=0, field_units::String="phase", Dir="") field = strip_units(field_units) data,time = read_LaMEM_timestep(OutFile, tstep, Dir) value = extract_data_fields(data, field) # get field; can handle tensors & vectors as well fields= String.(keys(data.fields)) fields_available = get_fields(fields) x = data.x.val[:,1,1] z = data.z.val[1,1,:] data2D = value[:,1,:]' return x, z, data2D, time[1], fields_available end """ Returns the trigger callback (simplifies code). """ function get_trigger() tr = callback_context().triggered; trigger = [] if !isempty(tr) trigger = callback_context().triggered[1] trigger = trigger[1] end return trigger end """ Add-ons to names for vector & tensors (used in dropdown menu). """ function vector_tensor() vector = [ "_$a" for a in ["x","y","z"]] tensor = [ "_$(b)$(a)" for a in ["x","y","z"], b in ["x","y","z"] ][:] scalar = [""] return scalar, vector, tensor end """ This extracts a LaMEM datafield and in case it is a tensor or scalar (and has _x, _z or so at the end). """ function extract_data_fields(data, field) _, vector, tensor = vector_tensor() if hasfield(typeof(data.fields),Symbol(field)) # scalar value = data.fields[Symbol(field)] else # vector/tensor extension = split(field,"_")[end] n = length(extension) name = field[1:end-n-1] if n==1 id = findall(vector.=="_"*extension)[1] else id = findall(tensor.=="_"*extension)[1] end value = data.fields[Symbol(name)][id] end return value end """ Returns a list with fields. In case the LaMEM field is a vector field, it adds _x, _y etc; im case of tensor, _xx, _xy etc. """ function get_fields(fields) scalar, vector, tensor = vector_tensor() fields_available= [] for f in fields if f=="velocity" add = vector elseif f=="strain_rate" || f=="stress" add = tensor else add = scalar end for a in add push!(fields_available, f*a) end end return fields_available end """ Functions building up to quiver plot """ function extract_velocity(OutFile, cur_t, Dir="") data, _ = read_LaMEM_timestep(OutFile, cur_t, Dir) Vx = data.fields.velocity[1][:,1,:] Vz = data.fields.velocity[3][:,1,:] x_vel = data.x.val[:,1,1] z_vel = data.z.val[1,1,:] return Vx, Vz, x_vel, z_vel end """ Interpolate velocities. """ function interpolate_velocities(x, z, Vx, Vz) # interpolate velocities to a quarter of original grid density itp_Vx = interpolate((x, z), Vx, Gridded(Linear())) itp_Vz = interpolate((x, z), Vz, Gridded(Linear())) interpolation_coords_x = LinRange(x[1], x[end], 15) interpolation_coords_z = LinRange(z[1], z[end], 15) Vx_interpolated = zeros(length(interpolation_coords_x) * length(interpolation_coords_z)) Vz_interpolated = zeros(length(interpolation_coords_x) * length(interpolation_coords_z)) itp_coords_x = zeros(length(interpolation_coords_x) * length(interpolation_coords_z)) itp_coords_z = zeros(length(interpolation_coords_x) * length(interpolation_coords_z)) itp_coords_x = repeat(interpolation_coords_x, outer=length(interpolation_coords_z)) itp_coords_z = repeat(interpolation_coords_z, inner=length(interpolation_coords_x)) for i in eachindex(itp_coords_x) Vx_interpolated[i] = itp_Vx(itp_coords_x[i], itp_coords_z[i]) Vz_interpolated[i] = itp_Vz(itp_coords_x[i], itp_coords_z[i]) end return Vx_interpolated, Vz_interpolated, itp_coords_x, itp_coords_z end """ Calculate angle between two vectors. """ function calculate_angle(Vx_interpolated, Vz_interpolated) angle = zeros(size(Vx_interpolated)) north = [1, 0] for i in eachindex(angle) angle[i] = asind((north[1] * Vx_interpolated[i] + north[2] * Vz_interpolated[i]) / (sqrt(north[1]^2 + north[2]^2) * sqrt(Vx_interpolated[i]^2 + Vz_interpolated[i]^2))) if isnan(angle[i]) == true angle[i] = 180.0 end if angle[i] < 90 && angle[i] > -90 && Vz_interpolated[i] < 0 angle[i] = 180.0 - angle[i] end end return angle end """ Calculate quiver. """ function calculate_quiver(OutFile, cur_t, cmaps; colorscale="batlow", Dir="") Vx, Vz, x, z = extract_velocity(OutFile, cur_t, Dir) Vx_interpolated, Vy_interpolated, interpolation_coords_x, interpolation_coords_z = interpolate_velocities(x, z, Vx, Vz) angle = calculate_angle(Vx_interpolated, Vy_interpolated) magnitude = sqrt.(Vx_interpolated .^ 2 .+ Vy_interpolated .^ 2) arrow_head = scatter( x=interpolation_coords_x, y=interpolation_coords_z, mode="markers", colorscale=cmaps[Symbol(colorscale)], marker=attr(size=15, color=magnitude, angle=angle, symbol="triangle-up"), colorbar=attr(title="Velocity", thickness=5, x=1.4), ) line = scatter( x=interpolation_coords_x, y=interpolation_coords_z, mode="markers", colorscale=cmaps[Symbol(colorscale)], marker=attr(size=10, color=magnitude, angle=angle, symbol="line-ns", line=attr(width=2, color=magnitude)), ) return arrow_head, line end """ This reads colormaps and transfers them into plotly format. The colormaps are supposed to be provided in ascii text format """ function read_colormaps(; dir_colormaps="" , scaling=256) #if isempty(dir_colormaps) # dir_colormaps=joinpath(pkgdir(InteractiveGeodynamics),"src/assets/colormaps/") #end # Read all colormaps colormaps = NamedTuple(); for map in readdir(dir_colormaps) data = readdlm(dir_colormaps*map) name_str = map[1:end-4] if contains(name_str,"reverse") reverse=true data = data[end:-1:1,:] else reverse=false end name = Symbol(name_str) # apply scaling data_rgb = Int64.(round.(data*scaling)) # Create the format that plotly wants: n = size(data,1) fac = range(0,1,n) data_col = [ [fac[i], "rgb($(data_rgb[i,1]),$(data_rgb[i,2]),$(data_rgb[i,3]))"] for i=1:n] col = NamedTuple{(name,)}((data_col,)) colormaps = merge(colormaps, col) end return colormaps end """ Returns a row containing the title of the page. """ function make_title(title_app::String) item = dbc_row(html_h1(title_app), style=Dict("margin-top" => 0, "textAlign" => "center")) return item end """ Returns a row containing the main plot. """ function make_plot(OutFile="",cmaps=[]; width="80vw", height="80vh") item = dbc_row([ dcc_graph(id="figure_main", figure=create_main_figure(OutFile, 0, cmaps=cmaps), #animate = false, #responsive=false, #clickData = true, #config = PlotConfig(displayModeBar=false, scrollZoom = false), style=attr(width=width, height=height) ) ]) return item end """ Returns a column containing all the media control buttons. """ function make_media_buttons() item = dbc_col([ dbc_button("<<", id="button-start", outline=true, color="primary", size="sg", class_name="me-md-1 col-2"), dbc_button("<", id="button-back", outline=true, color="primary", size="sg", class_name="me-md-1 col-1"), dbc_button("Play/Pause", id="button-play", outline=true, color="primary", size="sg", class_name="me-md-1 col-3"), dbc_button(">", id="button-forward", outline=true, color="primary", size="sg", class_name="me-md-1 col-1"), dbc_button(">>", id="button-last", outline=true, color="primary", size="sg", class_name="me-md-1 col-2"), ], class_name="d-grid gap-2 d-md-flex justify-content-md-center") return item end """ Retunrs an empty column. """ function make_empty_col() return dbc_col([]) end """ Retunrs an empty row. """ function make_empty_row() return dbc_row([]) end """ Returns a row containing the media buttons, each one in a column. """ function make_plot_controls() item = dbc_row([ #make_screenshot_button(), make_empty_col(), make_media_buttons(), make_empty_col(), ]) return item end """ Returns a column containing a screenshot button. """ function make_screenshot_button() item = dbc_col([ dbc_button("Save figure", id="button-save-fig", color="secondary", size="sg", class_name="col-4") ], class_name="d-grid gap-2 d-md-flex justify-content-md-center") return item end """ Return a row with the id of the current user session. """ function make_id_label() item = dbc_row([dbc_label("", id="label-id")]) return item end """ Returns a row containing a card with time information of the simulation. """ function make_time_card() item = dbc_row([ html_p(), dbc_card([ dbc_label(" Time: 0 Myrs", id="label-time"), dbc_label(" Timestep: 0", id="label-timestep" )], color="secondary", class_name="mx-auto col-11", outline=true), html_p()]) return item end """ Returns a row containing a label, a tooltip and a filling box. """ function make_accordion_item(label::String="param", idx::String="id", msg::String="Message", value::_T=1*one(_T), low=nothing, high=nothing) where _T <: Number low = _check_min(_T, low) high = _check_max(_T, high) item = dbc_row([ # domain width dbc_col([ dbc_label(label, id=idx*"_label", size="md"), dbc_tooltip(msg, target=idx*"_label") ]), dbc_col(dbc_input(id=idx, placeholder=string(value), value=value, type="number", min=low, size="md")) ]) return item end @inline _check_min(::Float64, ::Nothing) = 1e-10 @inline _check_min(::Int64, ::Nothing) = 2 @inline _check_min(::T, x) where T = x @inline _check_max(::Float64, ::Nothing) = 10000 @inline _check_max(::Int64, ::Nothing) = 10_000 @inline _check_max(::T, x) where T = x #= """ Returns a row containing a label, a tooltip and a filling box. """ function make_accordion_item(label::String="param", idx::String="id", msg::String="Message", value::Int64=2, mini::Int64=2, maxi::Int64=10_000) item = dbc_row([ # domain width dbc_col([ dbc_label(label, id=idx*"_label", size="md"), dbc_tooltip(msg, target=idx*"_label") ]), dbc_col(dbc_input(id=idx, placeholder=string(value), value=value, type="number", min=mini, size="md")) ]) return item end =# """ Returns an accordion menu containing the plotting parameters. """ function make_plotting_parameters(cmaps; show_field="phase") item = dbc_accordionitem(title="Plotting Parameters", [ dbc_row([ dbc_label("Select field to plot: ", size="md"), dcc_dropdown(id="plot_field", options = [show_field], value=show_field, className="col-12") ]), dbc_row(html_p()), dbc_row([ # color map dbc_col([ dbc_label("Colormap:", id="cmap", size="md"), dbc_tooltip(target="cmap", "Choose the colormap of the plot") ]), dbc_col(dcc_dropdown(id="color_map_option", options = String.(keys(cmaps)), value=String.(keys(cmaps))[1])) ]), dbc_row(html_p()), dbc_row(html_hr()), dbc_row([ dbc_checklist(options=["Overlap plot with contour:"], id="switch-contour", switch=true, ), dbc_row(html_p()), dbc_col(dcc_dropdown(id="contour_option" ,options = ["phase"], value="phase", disabled=true)) ]), dbc_row(html_p()), dbc_row(html_hr()), dbc_row([ dbc_checklist(options=["Overlap velocity"], id="switch-velocity", switch=true, ) ]), ]) return item end """ make_menu(cmaps; show_field="phase") Return a row containing the menu with the simulation, rheological and plotting parameters. """ function make_menu(cmaps; show_field="phase") if !isnothing(make_geometry_parameters()) item = dbc_row([ dbc_accordion(always_open=true, [ make_simulation_parameters(), make_geometry_parameters(), make_rheological_parameters(), make_plotting_parameters(cmaps, show_field=show_field), ]), ]) else item = dbc_row([ dbc_accordion(always_open=true, [ make_simulation_parameters(), make_rheological_parameters(), make_plotting_parameters(cmaps, show_field=show_field), ]), ]) end return item end """ Returns a row containing the RUN button. """ function make_run_button() item = dbc_row([ html_p(), dbc_button("RUN", id="button-run", size="lg", class_name="col-11 mx-auto"), html_p()]) return item end """ simulation_directory(session_id; clean=true ) Create a new directory named by session-id and optionally cleans it """ function simulation_directory(session_id; clean=true) base_dir = pwd(); dirname = String(session_id) if isdir("simulations") if isdir(joinpath("simulations" , dirname)) == false mkdir(joinpath("simulations" , dirname)) end else mkdir("simulations") mkdir(joinpath("simulations" , dirname)) end user_dir = joinpath("simulations" , dirname) if clean # clean directory cd(user_dir) clean_directory() # removes all existing LaMEM files cd(base_dir) end return user_dir end has_pvd_file(OutFile, user_dir) = isfile(joinpath(user_dir, OutFile * ".pvd")) """ active_switch = active_switch(switch) Returns true if the switch is on """ function active_switch(switch) active_switch_val=false; if !isnothing(switch) if !isempty(switch) active_switch_val = true end end return active_switch_val end """ fields_available_units = fields_available_units This adds units to the fields available in the LaMEM simulation """ function add_units(fields_available) fields_available_units = fields_available fields_available_units = replace(fields_available_units, "visc_total"=>"visc_total [log₁₀(Pas)]", "visc_creep"=>"visc_creep [log₁₀(Pas)]", "velocity_x"=>"velocity_x [cm/yr]", "velocity_z"=>"velocity_z [cm/yr]", "pressure"=>"pressure [MPa]", "temperature"=>"temperature [°C]", "j2_dev_stress"=>"j2_dev_stress [MPa]", "j2_strain_rate"=>"j2_strain_rate [1/s]", "density"=>"density [kg/m³]", ) return fields_available_units end function strip_units(fields_available_units) fields_available = fields_available_units fields_available = replace(fields_available, "visc_total [log₁₀(Pas)]"=>"visc_total", "visc_creep [log₁₀(Pas)]"=>"visc_creep", "velocity_x [cm/yr]"=>"velocity_x", "velocity_z [cm/yr]"=>"velocity_z", "pressure [MPa]"=>"pressure", "temperature [°C]"=>"temperature", "density [kg/m³]"=>"density", "j2_dev_stress [MPa]"=>"j2_dev_stress", "j2_strain_rate [1/s]"=>"j2_strain_rate", ) return fields_available end #end
InteractiveGeodynamics
https://github.com/JuliaGeodynamics/InteractiveGeodynamics.jl.git
[ "MIT" ]
0.2.3
c886092ba2e14a4500a3e0b99b298d104fe60b46
code
12490
module FoldingTools using Dash, DashBootstrapComponents using PlotlyJS using LaMEM using UUIDs using Interpolations using GeophysicalModelGenerator using HTTP export folding pkg_dir = Base.pkgdir(FoldingTools) @show pkg_dir include(joinpath(pkg_dir,"src/dash_tools.jl")) include(joinpath(pkg_dir,"src/Folding/dash_functions_Folding.jl")) include(joinpath(pkg_dir,"src/Folding/Setup.jl")) """ folding(; host = HTTP.Sockets.localhost, port=8050, wait=false, width="80vw", height="80vh", cores=1) This starts a folding GUI """ function folding(; host = HTTP.Sockets.localhost, port=8050, wait=false, width="80vw", height="80vh", cores=1) pkg_dir = Base.pkgdir(FoldingTools) GUI_version = "0.1.3" cmaps = read_colormaps(dir_colormaps=joinpath(pkg_dir,"src/assets/colormaps/")) title_app = "Viscous Folding" OutFile = "Folding" #app = dash(external_stylesheets=[dbc_themes.CYBORG]) app = dash(external_stylesheets = [dbc_themes.BOOTSTRAP, dbc_icons.BOOTSTRAP], prevent_initial_callbacks=false) app.title = title_app # Main code layout app.layout = html_div() do dbc_container(className="mxy-auto", fluid=true, [ make_title(title_app), dbc_row([ dbc_col([ make_plot("",cmaps), # show graph make_plot_controls(), # show media buttons make_id_label(), # show user id ]), dbc_col([ make_time_card(), # show simulation time info make_menu(cmaps), # show menu with simulation parameters, rheological parameters, and plotting parameters make_run_button() # show the run simulation button ]) ]), # Store a unique number of our session in the webpage dcc_store(id="session-id", data=""), # Store info related to the simulation and current timestep dcc_store(id="current_timestep", data="0"), dcc_store(id="last_timestep", data="0"), dcc_store(id="update_fig", data="0"), # Start an interval that updates the number every second dcc_interval(id="session-interval", interval=100, n_intervals=0, disabled=true) ]) end # This creates an initial session id that is unique for this session # it will run on first start callback!(app, Dash.Output("session-id", "data"), Dash.Output("label-id", "children"), Input("session-id", "data") ) do session_id session_id = UUIDs.uuid4() str = "id=$(session_id), v=$(GUI_version)" return String("$(session_id)"), str end # Call run button callback!(app, Dash.Output("session-interval", "disabled"), Input("button-run", "n_clicks"), Input("button-run", "disabled"), Input("button-play", "n_clicks"), State("thickness", "value"), State("width", "value"), State("nel_x", "value"), State("nel_z", "value"), State("nlayers", "value"), State("n_timesteps", "value"), State("ThicknessLayers", "value"), State("SpacingLayers", "value"), State("last_timestep", "data"), State("plot_field", "value"), State("session-id", "data"), State("viscosity_fold", "value"), State("viscosity_matrix", "value"), State("A0_rand", "value"), State("A0_sin", "value"), State("e_bg", "value"), prevent_initial_call=true ) do n_run, active_run, n_play, thickness, width, nel_x, nel_z, nlayers, n_timesteps, ThicknessLayers, SpacingLayers, last_timestep, plot_field, session_id, viscosity_fold,viscosity_matrix, A0_rand,A0_sin, e_bg # print(layers) # print(open_top) trigger = get_trigger() disable_interval = true if trigger == "button-run.n_clicks" cd(pkg_dir) cur_dir = pwd() base_dir = joinpath(pkgdir(FoldingTools),"src","FreeSubduction") η_fold = 10.0^viscosity_fold η_matrix = 10.0^viscosity_matrix ε = e_bg # We clicked the run button user_dir = simulation_directory(session_id, clean=true) cd(user_dir) # Create the setup model = create_model_setup(nx=nel_x, nz=nel_z, W=width/1e3, H=thickness/1e3, Number_layers=nlayers, H0=ThicknessLayers/1e3, Spacing=SpacingLayers/1e3, eta_matrix=η_matrix, eta_fold=η_fold, nstep_max=n_timesteps, A0_rand=A0_rand/1e3, A0_sin=A0_sin/1e3, ε=ε, ) run_lamem(model, cores, wait=wait) cd(cur_dir) # return to main directory disable_interval = false elseif trigger == "button-run.disabled" last_t = parse(Int, last_timestep) if active_run == true || last_t < n_timesteps disable_interval = false end elseif trigger == "button-play.n_clicks" last_t = parse(Int, last_timestep) # @show last_t disable_interval = false end return disable_interval end # deactivate the button callback!(app, Dash.Output("button-run", "disabled"), Dash.Output("button-run", "color"), Input("button-run", "n_clicks"), Input("session-interval", "n_intervals"), State("last_timestep", "data"), State("current_timestep", "data"), prevent_initial_call=true ) do n_run, n_inter, last_timestep, current_timestep cur_t = parse(Int, current_timestep) # current timestep last_t = parse(Int, last_timestep) # last timestep available on disk if cur_t < last_t button_run_disable = true button_color = "danger" else button_run_disable = false button_color = "primary" end return button_run_disable, button_color end # Check if *.pvd file on disk changed and a new timestep is available callback!(app, Dash.Output("last_timestep", "data"), Dash.Output("update_fig", "data"), Input("session-interval", "n_intervals"), Input("button-run", "n_clicks"), State("current_timestep", "data"), State("update_fig", "data"), State("session-id", "data"), prevent_initial_call=true ) do n_inter, n_run, current_timestep, update_fig, session_id trigger = get_trigger() user_dir = simulation_directory(session_id, clean=false) if trigger == "session-interval.n_intervals" if has_pvd_file(OutFile, user_dir) # Read LaMEM *.pvd file Timestep, _, Time = read_LaMEM_simulation(OutFile, user_dir) # Update the labels and data stored in webpage about the last timestep last_time = "$(Timestep[end])" update_fig = "$(parse(Int,update_fig)+1)" else last_time = "0" update_fig = "0" end elseif trigger == "button-run.n_clicks" last_time = "0" update_fig = "0" end return last_time, update_fig end # Update the figure if the signal is given to do so callback!(app, Dash.Output("label-timestep", "children"), Dash.Output("label-time", "children"), Dash.Output("current_timestep", "data"), Dash.Output("figure_main", "figure"), Dash.Output("plot_field", "options"), Dash.Output("contour_option", "options"), Input("update_fig", "data"), Input("current_timestep", "data"), Input("button-run", "n_clicks"), Input("button-start", "n_clicks"), Input("button-last", "n_clicks"), Input("button-forward", "n_clicks"), Input("button-back", "n_clicks"), Input("button-play", "n_clicks"), State("last_timestep", "data"), State("session-id", "data"), State("plot_field", "value"), State("switch-contour", "value"), State("contour_option", "value"), State("switch-velocity", "value"), State("color_map_option", "value"), State("e_bg", "value"), prevent_initial_call=true ) do update_fig, current_timestep, n_run, n_start, n_last, n_back, n_forward, n_play, last_timestep, session_id, plot_field, switch_contour, contour_field, switch_velocity, color_map_option, e_bg trigger = get_trigger() # Get info about timesteps cur_t = parse(Int, current_timestep) # current timestep last_t = parse(Int, last_timestep) # last timestep available on disk fig_cross = [] fields_available = ["phase"] if trigger == "current_timestep.data" || trigger == "update_fig.data" || trigger == "button-start.n_clicks" || trigger == "button-last.n_clicks" || trigger == "button-back.n_clicks" || trigger == "button-forward.n_clicks" || trigger == "button-play.n_clicks" user_dir = simulation_directory(session_id, clean=false) if has_pvd_file(OutFile, user_dir) Timestep, _, Time = read_LaMEM_simulation(OutFile, user_dir) # all timesteps id = findall(Timestep .== cur_t)[1] if trigger == "button-start.n_clicks" || trigger == "button-play.n_clicks" cur_t = 0 id = 1 elseif trigger == "button-last.n_clicks" cur_t = Timestep[end] id = length(Timestep) elseif (trigger == "button-forward.n_clicks") && (id < length(Timestep)) cur_t = Timestep[id+1] id = id + 1 elseif (trigger == "button-back.n_clicks") && (id > 1) cur_t = Timestep[id-1] id = id - 1 end # Load data x, y, data, time, fields_available = get_data(OutFile, cur_t, plot_field, user_dir) add_contours = active_switch(switch_contour) if add_contours x_con, y_con, data_con, _, _ = get_data(OutFile, cur_t, contour_field, user_dir) else x_con, y_con, data_con = x, y, data end # update the plot add_velocity = active_switch(switch_velocity) fig_cross = create_main_figure(OutFile, cur_t, x*1e3, y*1e3, data, x_con*1e3, y_con*1e3, data_con; add_contours=add_contours, contour_field=contour_field, add_velocity=add_velocity, colorscale=color_map_option, session_id=session_id, field=plot_field, cmaps=cmaps) if trigger == "current_timestep.data" || trigger == "update_fig.data" || trigger == "button-play.n_clicks" if cur_t < last_t cur_t = Timestep[id+1] # update current timestep end end else time = 0 end elseif trigger == "button-run.n_clicks" cur_t = 0 time = 0.0 end # update the labels label_timestep = "Timestep: $cur_t" label_time = "Time: $time Myrs" current_timestep = "$cur_t" # @show current_timestep println("Timestep ", current_timestep) return label_timestep, label_time, current_timestep, fig_cross, fields_available, fields_available end # callback!(app, Dash.Output("contour_option", "disabled"), Input("switch-contour", "value")) do switch_contour if !isnothing(switch_contour) if isempty(switch_contour) disable_contours = true else disable_contours = false end else disable_contours = true end return disable_contours end run_server(app, host, port, debug=false) end end
InteractiveGeodynamics
https://github.com/JuliaGeodynamics/InteractiveGeodynamics.jl.git