licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
2487
"A generic wrapper around `wasm_XXX_vec_t`" mutable struct WasmVec{T,S} <: AbstractVector{S} size::Csize_t data::Ptr{S} end wasm_vec_delete(wasm_vec::WasmVec{T,S}) where {T,S} = _get_delete_function(T)(wasm_vec) function WasmVec{T,S}(vector::Vector{S} = S[]) where {T,S} vec_size = length(vector) wasm_vec = WasmVec{T,S}(0, C_NULL) vec_uninitialized = _get_uninitialized_function(T) vec_uninitialized(wasm_vec, vec_size) src_ptr = pointer(vector) GC.@preserve vector unsafe_copyto!(wasm_vec.data, src_ptr, vec_size) finalizer(wasm_vec_delete, wasm_vec) end _get_delete_function(T) = getproperty(LibWasmtime, Symbol(string(nameof(T))[1:end-6] * "_vec_delete")) _get_uninitialized_function(T) = getproperty(LibWasmtime, Symbol(string(nameof(T))[1:end-6] * "_vec_new_uninitialized")) WasmVec(base_type::Type) = WasmVec(base_type[]) function WasmVec(vec::Vector{S}) where {S} vec_type = _get_wasm_vec_name(S) WasmVec{vec_type,S}(vec) end WasmPtrVec(base_type::Type) = WasmPtrVec(Ptr{base_type}[]) function WasmPtrVec(vec::Vector{Ptr{S}}) where {S} vec_type = _get_wasm_vec_name(S) WasmVec{vec_type,Ptr{S}}(vec) end _get_wasm_vec_name(::Type{Cchar}) = wasm_byte_vec_t _get_wasm_vec_name(::Type{UInt8}) = wasm_byte_vec_t function _get_wasm_vec_name(type::Type) @assert parentmodule(type) == LibWasmtime "$type should be a LibWasm type" type_name = string(nameof(type)) # "wasm_XXX_t" vec_type_sym = Symbol(replace(type_name, r"_t$" => "_vec_t")) # :wasm_XXX_vec_t getproperty(LibWasmtime, vec_type_sym) end Base.IndexStyle(::Type{WasmVec}) = IndexLinear() Base.length(vec::WasmVec) = vec.size Base.size(vec::WasmVec) = (length(vec),) function Base.getindex(vec::WasmVec, i::Int) @assert 1 <= i <= length(vec) BoundsError(vec, i) unsafe_load(vec.data, i) end function Base.setindex!(vec::WasmVec{T,S}, v::S, i::Int) where {T,S} @assert 1 <= i <= length(vec) BoundsError(vec, i) elsize = sizeof(S) ref = Ref(v) src_ptr = Base.unsafe_convert(Ptr{S}, ref) dest_ptr = Base.unsafe_convert(Ptr{S}, vec.data + elsize * (i - 1)) GC.@preserve ref unsafe_copyto!(dest_ptr, src_ptr, 1) v end Base.unsafe_convert(::Type{Ptr{T}}, vec::WasmVec{T,S}) where {T,S} = Base.unsafe_convert(Ptr{T}, pointer_from_objref(vec)) Base.unsafe_convert(::Type{Ptr{S}}, vec::WasmVec{T,S}) where {T,S} = vec.data const WasmByteVec = WasmVec{wasm_byte_vec_t,UInt8} const WasmName = WasmByteVec
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
5058
map_to_extern(extern_func::Ptr{wasm_func_t}) = wasm_func_as_extern(extern_func) map_to_extern(other) = error("Type $(typeof(other)) is not supported") mutable struct WasmInstance wasm_instance_ptr::Ptr{wasm_instance_t} wasm_module::WasmModule wasm_externs::WasmVec{wasm_extern_vec_t,Ptr{wasm_extern_t}} WasmInstance( wasm_instance_ptr::Ptr{wasm_instance_t}, wasm_module::WasmModule, wasm_externs = WasmVec{wasm_extern_vec_t,Ptr{wasm_extern_t}}(0, C_NULL), ) = finalizer(wasm_instance_delete, new(wasm_instance_ptr, wasm_module, wasm_externs)) end function WasmInstance(store::WasmStore, wasm_module::WasmModule) module_imports = imports(wasm_module) n_expected_imports = length(module_imports.wasm_imports) @assert n_expected_imports == 0 "No imports provided, expected $n_expected_imports" empty_imports = WasmPtrVec(wasm_extern_t) # TODO: pass trap here to get better error messages # See `wasmtime/wasi.jl` for an example wasm_instance_ptr = wasm_instance_new( store.wasm_store_ptr, wasm_module.wasm_module_ptr, empty_imports, C_NULL, ) @assert wasm_instance_ptr != C_NULL "Failed to create WASM instance" WasmInstance(wasm_instance_ptr, wasm_module) end function WasmInstance(store::WasmStore, wasm_module::WasmModule, host_imports) externs_vec = WasmPtrVec(map(map_to_extern, host_imports)) WasmInstance(store, wasm_module, externs_vec) end function WasmInstance( store::WasmStore, wasm_module::WasmModule, externs_vec::WasmVec{wasm_extern_vec_t,Ptr{wasm_extern_t}}, ) module_imports = imports(wasm_module) n_expected_imports = length(module_imports.wasm_imports) n_provided_imports = length(externs_vec) @assert n_expected_imports == n_provided_imports "$n_provided_imports imports provided, expected $n_expected_imports" wasm_trap_ptr = Ref(Ptr{wasm_trap_t}()) wasm_instance_ptr = wasm_instance_new( store.wasm_store_ptr, wasm_module.wasm_module_ptr, externs_vec, wasm_trap_ptr, ) if wasm_instance_ptr == C_NULL && wasm_trap_ptr[] != C_NULL trap_msg = WasmByteVec() wasm_trap_message(wasm_trap_ptr[], trap_msg) wasm_trap_delete(wasm_trap_ptr[]) error_message = unsafe_string(trap_msg.data, trap_msg.size) error(error_message) end @assert wasm_instance_ptr != C_NULL "Failed to create WASM instance" WasmInstance(wasm_instance_ptr, wasm_module, externs_vec) end Base.show(io::IO, ::WasmInstance) = print(io, "WasmInstance()") Base.unsafe_convert(::Type{Ptr{wasm_instance_t}}, instance::WasmInstance) = instance.wasm_instance_ptr # TODO: One for each exporttype_type? mutable struct WasmExport <: AbstractWasmExport # The wasm_exporttype_t refers to the export on the module side wasm_export_ptr::Ptr{wasm_exporttype_t} # The wasm_extern_t refers to the export on the instance side wasm_extern::WasmExtern wasm_instance::WasmInstance name::String function WasmExport( wasm_export_ptr::Ptr{wasm_exporttype_t}, wasm_extern_ptr::Ptr{wasm_extern_t}, wasm_instance::WasmInstance, ) owned_wasm_export_ptr = wasm_exporttype_copy(wasm_export_ptr) @assert owned_wasm_export_ptr != C_NULL "Failed to copy WASM export" owned_wasm_extern_ptr = wasm_extern_copy(wasm_extern_ptr) @assert owned_wasm_extern_ptr != C_NULL "Failed to copy WASM extern" name_vec_ptr = wasm_exporttype_name(owned_wasm_export_ptr) name_vec = Base.unsafe_load(name_vec_ptr) name = unsafe_string(name_vec.data, name_vec.size) wasm_name_delete(name_vec_ptr) # TODO: Extract type here finalizer( new( owned_wasm_export_ptr, WasmExtern(owned_wasm_extern_ptr), wasm_instance, name, ), ) do wasm_export wasm_extern_delete(wasm_export.wasm_extern) wasm_exporttype_delete(wasm_export.wasm_export_ptr) end end end name(we::WasmExport) = we.name function (wasm_export::WasmExport)(args...) wasm_externtype_ptr = wasm_exporttype_type(wasm_export.wasm_export_ptr) @assert wasm_externtype_ptr != C_NULL "Failed to get export type for export $(wasm_export.name)" wasm_externkind = wasm_externtype_kind(wasm_externtype_ptr) @assert wasm_externkind == WASM_EXTERN_FUNC "Called export '$(wasm_export.name)' is not a function" wasm_export.wasm_extern(args...) end function exports(wasm_instance::WasmInstance) exports = WasmPtrVec(wasm_exporttype_t) wasm_module_exports(wasm_instance.wasm_module.wasm_module_ptr, exports) externs = WasmPtrVec(wasm_extern_t) wasm_instance_exports(wasm_instance.wasm_instance_ptr, externs) @assert length(exports) == length(externs) exports_vector = map(a -> WasmExport(a..., wasm_instance), zip(exports, externs)) WasmExports{WasmInstance,WasmExport}(wasm_instance, exports_vector) end
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
4509
mutable struct WasmModule <: AbstractWasmModule wasm_module_ptr::Ptr{wasm_module_t} WasmModule(module_ptr::Ptr{wasm_module_t}) = finalizer(wasm_module_delete, new(module_ptr)) end function WasmModule(store::WasmStore, wasm_byte_vec::WasmByteVec) wasm_module_ptr = wasm_module_new(store, wasm_byte_vec) wasm_module_ptr == C_NULL && error("Failed to create wasm module") WasmModule(wasm_module_ptr) end Base.unsafe_convert(::Type{Ptr{wasm_module_t}}, wasm_module::WasmModule) = wasm_module.wasm_module_ptr mutable struct WasmMemory wasm_memory_ptr::Ptr{wasm_memory_t} end function WasmMemory(store::WasmStore, limits::Pair{UInt32,UInt32}) limits = wasm_limits_t(limits...) memory_type = GC.@preserve limits wasm_memorytype_new(pointer_from_objref(limits)) @assert memory_type != C_NULL "Failed to create memory type" wasm_memory_ptr = wasm_memory_new(store, memory_type) @assert wasm_memory_ptr != C_NULL "Failed to create memory" WasmMemory(wasm_memory_ptr) end map_to_extern(mem::WasmMemory) = wasm_memory_as_extern(mem) Base.show(io::IO, wasm_memory::WasmMemory) = print(io, "WasmMemory()") Base.unsafe_convert(::Type{Ptr{wasm_memory_t}}, wasm_memory::WasmMemory) = wasm_memory.wasm_memory_ptr function WasmFunc(store::WasmStore, func::Function, return_type, input_types) params_vec = WasmPtrVec(collect(Ptr{wasm_valtype_t}, map(julia_type_to_valtype, input_types))) results_vec = return_type == Nothing ? WasmPtrVec(wasm_valtype_t) : WasmPtrVec([julia_type_to_valtype(return_type)]) func_type = wasm_functype_new(params_vec, results_vec) @assert func_type != C_NULL "Failed to create functype" function jl_side_host( args::Ptr{wasm_val_vec_t}, results::Ptr{wasm_val_vec_t}, )::Ptr{wasm_trap_t} # TODO: support passing the arguments try res = func() wasm_res = Ref(convert(wasm_val_t, res)) data_ptr = unsafe_load(results).data wasm_val_copy(data_ptr, wasm_res) C_NULL catch err err_msg = string(err) wasmtime_trap_new(err_msg, sizeof(err_msg)) end end # Create a pointer to jl_side_host(args, results) func_ptr = Base.@cfunction( $jl_side_host, Ptr{wasm_trap_t}, (Ptr{wasm_val_vec_t}, Ptr{wasm_val_vec_t}) ) host_func = wasm_func_new(store, func_type, func_ptr) wasm_functype_delete(func_type) # Keep a reference to func_ptr in the store, so that it not garbage collected add_extern_func!(store, func_ptr) host_func end struct WasmFuncRef wasm_func_ptr::Ptr{wasm_func_t} end Base.unsafe_convert(::Type{Ptr{wasm_func_t}}, wasm_func::WasmFuncRef) = wasm_func.wasm_func_ptr function (wasm_func::WasmFuncRef)(args...) params_arity = wasm_func_param_arity(wasm_func) result_arity = wasm_func_result_arity(wasm_func) provided_params = length(args) if params_arity != provided_params error("Wrong number of argument to function, expected $params_arity, got $provided_params",) end converted_args = collect(wasm_val_t, map(arg -> convert(wasm_val_t, arg), args)) params_vec = WasmVec(converted_args) default_val = wasm_val_t(tuple(zeros(UInt8, 16)...)) results_vec = WasmVec([default_val for _ = 1:result_arity]) wasm_func_call(wasm_func, params_vec, results_vec) collect(results_vec) end mutable struct WasmExtern wasm_extern_ptr::Ptr{wasm_extern_t} end Base.unsafe_convert(::Type{Ptr{wasm_extern_t}}, wasm_extern::WasmExtern) = wasm_extern.wasm_extern_ptr function Base.show(io::IO, wasm_extern::WasmExtern) kind = wasm_extern_kind(wasm_extern) |> wasm_externkind_enum print(io, "WasmExtern($kind)") end function (wasm_extern::WasmExtern)(args...) extern_as_func = wasm_extern_as_func(wasm_extern) @assert extern_as_func != C_NULL "Can not use extern $wasm_extern as a function" WasmFuncRef(extern_as_func)(args...) end function name_vec_ptr_to_str(name_vec_ptr::Ptr{wasm_name_t}) @assert name_vec_ptr != C_NULL "Failed to convert wasm_name" name_vec = Base.unsafe_load(name_vec_ptr) name = unsafe_string(name_vec.data, name_vec.size) wasm_name_delete(name_vec_ptr) name end function imports(wasm_module::WasmModule) wasm_imports_vec = WasmPtrVec(wasm_importtype_t) wasm_module_imports(wasm_module, wasm_imports_vec) WasmImports(wasm_module, wasm_imports_vec) end
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
575
mutable struct WasmStore wasm_store_ptr::Ptr{wasm_store_t} externs_func::Vector{Base.CFunction} WasmStore(wasm_store_ptr::Ptr{wasm_store_t}) = finalizer(wasm_store_delete, new(wasm_store_ptr, [])) end WasmStore(wasm_engine::AbstractWasmEngine) = WasmStore(wasm_store_new(wasm_engine)) add_extern_func!(wasm_store::WasmStore, cfunc::Base.CFunction) = push!(wasm_store.externs_func, cfunc) Base.unsafe_convert(::Type{Ptr{wasm_store_t}}, wasm_store::WasmStore) = wasm_store.wasm_store_ptr Base.show(io::IO, ::WasmStore) = print(io, "WasmStore()")
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
1883
""" A wrapper for wasm_table_t specific to wasmtime, since the wasmtime c-api is currently missing wasm_ref_as_func() """ mutable struct WasmTable <: AbstractVector{WasmFuncRef} store::WasmStore wasm_table_ptr::Ptr{wasm_table_t} end function WasmTable(store::WasmStore, limits::Pair{Int,Int}) wasm_limits = wasm_limits_t(limits...) table_valtype = wasm_valtype_new(WASM_FUNCREF) @assert table_valtype != C_NULL "Failed to create table valtype" table_type = GC.@preserve wasm_limits wasm_tabletype_new( table_valtype, pointer_from_objref(wasm_limits), ) @assert table_type != C_NULL "Failed to create table type" wasm_table_ptr = wasm_table_new(store, table_type, C_NULL) @assert wasm_table_ptr != C_NULL "Failed to create table" # finalizer(wasm_table_delete, WasmTable(store, wasm_table_ptr)) WasmTable(store, wasm_table_ptr) end Base.unsafe_convert(::Type{Ptr{wasm_table_t}}, wasm_table::WasmTable) = wasm_table.wasm_table_ptr Base.IndexStyle(::Type{WasmTable}) = IndexLinear() Base.size(table::WasmTable) = (wasm_table_size(table) |> Int,) function Base.getindex(table::WasmTable, i::Int) wasm_val_ref = Ref(wasm_val_t(tuple((zero(UInt8) for _ = 1:16)...))) index = i - 1 wasmtime_context = @ccall libwasmtime.wasmtime_store_context(table.store::Ptr{wasm_store_t})::Ptr{Nothing} res = @ccall libwasmtime.wasmtime_table_get( wasmtime_context::Ptr{Nothing}, table::Ptr{wasm_table_t}, index::Cint, wasm_val_ref::Ptr{wasm_val_t}, )::Bool @assert res "Failed to access index $i" @assert wasm_val_ref[].kind == WASM_FUNCREF WasmFuncRef(wasm_func_ptr[]) end function Base.setindex!(table::WasmTable, v, i::Int) wasm_table_set(table, v, i - 1) # TODO: use result end map_to_extern(extern_table::WasmTable) = wasm_table_as_extern(extern_table)
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
504
function throw_error_message(wasm_error::Ptr{wasmtime_error_t}) message_buf = WasmByteVec() wasmtime_error_message( wasm_error, message_buf, ) error_msg = unsafe_string(message_buf.data, message_buf.size) @ccall libwasmtime.wasmtime_error_delete(wasm_error::Ptr{wasmtime_error_t})::Cvoid error(error_msg) end macro wt_check(call) quote wt_err = $(esc(call)) if wt_err != C_NULL throw_error_message(wt_err) end end end
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
10628
struct WasmtimeInstance # wasmtime instances are "just" a 64 bits identifier associated to a store, as such # they don't have an associated destructor of type wasmtime_delete_instance() # see the definition of wasmtime_instance_t in LibWasmtime for more info. identifier::wasmtime_instance store::WasmtimeStore end Base.unsafe_convert(::Type{Ptr{wasmtime_instance_t}}, instance::WasmtimeInstance) = Base.convert(Ptr{wasmtime_instance}, Base.pointer_from_objref(instance.identifier)) function WasmtimeInstance(store::WasmtimeStore, mod::WasmtimeModule) module_imports = imports(mod) n_expected_imports = length(module_imports.wasm_imports) @assert n_expected_imports == 0 "No imports provided, expected $n_expected_imports" instance = Ref(wasmtime_instance_t(0, 0)) wasm_trap_ptr = Ref(Ptr{wasm_trap_t}()) @wt_check wasmtime_instance_new( store, mod, C_NULL, 0, instance, wasm_trap_ptr, ) if wasm_trap_ptr[] != C_NULL trap_msg = WasmByteVec() wasm_trap_message(wasm_trap_ptr[], trap_msg) wasm_trap_delete(wasm_trap_ptr[]) error_message = unsafe_string(trap_msg.data, trap_msg.size) error(error_message) end WasmtimeInstance(instance[], store) end function WasmtimeInstance(linker::WasmtimeLinker, store::WasmtimeStore, mod::WasmtimeModule) instance = Ref(wasmtime_instance_t(0, 0)) wasm_trap_ptr = Ref(Ptr{wasm_trap_t}()) @wt_check GC.@preserve instance wasmtime_linker_instantiate( linker, store, mod, instance, wasm_trap_ptr, ) if wasm_trap_ptr[] != C_NULL trap_msg = WasmByteVec() wasm_trap_message(wasm_trap_ptr[], trap_msg) wasm_trap_delete(wasm_trap_ptr[]) error_message = unsafe_string(trap_msg.data, trap_msg.size) error(error_message) end WasmtimeInstance(instance[], store) end mutable struct WasmtimeInstanceExport <: AbstractWasmExport wasm_export_ptr::Ptr{wasm_exporttype_t} extern::Ref{wasmtime_extern} wasmtime_instance::WasmtimeInstance name::String end function wasmtime_valkind_to_julia(valkind::wasmtime_valkind_t)::Type if valkind == WASMTIME_I32 Int32 elseif valkind == WASMTIME_I64 Int64 elseif valkind == WASMTIME_F32 Float32 elseif valkind == WASMTIME_F64 Float64 elseif valkind == WASMTIME_FUNCREF wasmtime_func_t elseif valkind == WASMTIME_EXTERNREF Ptr{wasmtime_externref_t} elseif valkind == WASMTIME_V128 wasmtime_v128 else error("Invalid value kind $type") end end struct WasmtimeMemory <: AbstractVector{UInt8} export_::WasmtimeInstanceExport end "Page size of the memory" function memory_size(mem::WasmtimeMemory) extern = mem.export_.extern[] @assert extern.kind == WASM_EXTERN_MEMORY memory = Ref(extern.of.memory) store = mem.export_.wasmtime_instance.store sz = LibWasmtime.wasmtime_memory_size(store, memory) Int(sz) end function memory_max(mem::WasmtimeMemory) extern = mem.export_.extern[] @assert extern.kind == WASM_EXTERN_MEMORY memory = Ref(extern.of.memory) store = mem.export_.wasmtime_instance.store mem_type = LibWasmtime.wasmtime_memory_type(store, memory) max = Ref{UInt64}() hasmax = LibWasmtime.wasmtime_memorytype_maximum(mem_type, max) hasmax ? max[] : typemax(UInt64) end struct WasmtimeFunc export_::WasmtimeInstanceExport end function Base.size(mem::WasmtimeMemory) extern = mem.export_.extern[] @assert extern.kind == WASM_EXTERN_MEMORY memory = Ref(extern.of.memory) store = mem.export_.wasmtime_instance.store sz = LibWasmtime.wasmtime_memory_data_size(store, memory) (Int(sz),) end function Base.getindex(mem::WasmtimeMemory, r::UnitRange{Int}) extern = mem.export_.extern[] @assert extern.kind == WASM_EXTERN_MEMORY memory = Ref(extern.of.memory) store = mem.export_.wasmtime_instance.store 1 <= first(r) <= last(r) <= length(mem) || throw(BoundsError(mem, r)) values = Vector{UInt8}(undef, length(r)) data_ptr = LibWasmtime.wasmtime_memory_data(store, memory) |> Ptr{UInt8} @GC.preserve values mem unsafe_copyto!(pointer(values), data_ptr + first(r) - 1, length(r)) values end function Base.getindex(mem::WasmtimeMemory, i::Int) extern = mem.export_.extern[] @assert extern.kind == WASM_EXTERN_MEMORY memory = Ref(extern.of.memory) store = mem.export_.wasmtime_instance.store 1 <= i <= length(mem) || throw(BoundsError(mem, i)) data_ptr = LibWasmtime.wasmtime_memory_data(store, memory) |> Ptr{UInt8} unsafe_load(data_ptr, i) end function Base.setindex!(mem::WasmtimeMemory, v, i) extern = mem.export_.extern[] @assert extern.kind == WASM_EXTERN_MEMORY memory = Ref(extern.of.memory) store = mem.export_.wasmtime_instance.store 1 <= i <= length(mem) || throw("out of bounds $i") data_ptr = LibWasmtime.wasmtime_memory_data(store, memory) |> Ptr{UInt8} unsafe_store!(data_ptr, v, i) end function grow!(mem::WasmtimeMemory, delta) extern = mem.export_.extern[] @assert extern.kind == WASM_EXTERN_MEMORY memory = Ref(extern.of.memory) store = mem.export_.wasmtime_instance.store if delta + memory_size(mem) > memory_max(mem) max = memory_max(mem) sz = memory_size(mem) error("invalid delta $delta (maximum page size is $max, current $sz)") end prev_size = Ref{UInt64}() @wt_check wasmtime_memory_grow(store, memory, delta, prev_size) Int(prev_size[]) end function (func::WasmtimeFunc)(args...) wasmtime_export = func.export_ extern = wasmtime_export.extern[] @assert extern.kind == WASM_EXTERN_FUNC "Expected an exported function but got type $(extern.kind)" func = Ref(extern.of.func) functype = wasmtime_func_type(wasmtime_export.wasmtime_instance.store, func) wasm_params = Base.unsafe_convert(Ptr{WasmVec{wasm_valtype_vec_t,Ptr{wasm_valtype_t}}}, wasm_functype_params(functype)) |> Base.unsafe_load wasm_results = Base.unsafe_convert(Ptr{WasmVec{wasm_valtype_vec_t,Ptr{wasm_valtype_t}}}, wasm_functype_results(functype)) |> Base.unsafe_load @assert length(args) == length(wasm_params) "Expected $(wasm_params.size) arguments but got $(length(args))" params_kind = wasm_valtype_kind.(wasm_params) wasmtime_params = wasmtime_val[] for (i, (param, kind)) in enumerate(zip(args, params_kind)) jtype = typeof(param) etype = wasmtime_valkind_to_julia(kind) @assert jtype == etype "Parameter #$i is of type $jtype, expected $etype" valunion = Ref{wasmtime_valunion}(wasmtime_valunion(Tuple(zero(UInt8) for _ in 1:16))) GC.@preserve valunion begin ptr = Base.unsafe_convert(Ptr{wasmtime_valunion}, valunion) if jtype == Int32 ptr.i32 = param elseif jtype == Int64 ptr.i64 = param elseif jtype == Float32 ptr.f32 = param elseif jtype == Float64 ptr.f64 = param elseif kind == WASMTIME_V128 ptr.v128 = param else error("cannot use type $etype") end end push!(wasmtime_params, wasmtime_val(kind, valunion[])) end wasmtime_results = Vector{wasmtime_val}(undef, length(wasm_results)) trap = Ref(Ptr{wasm_trap_t}(C_NULL)) @wt_check wasmtime_func_call( wasmtime_export.wasmtime_instance.store, func, wasmtime_params, length(wasmtime_params), wasmtime_results, length(wasmtime_results), trap ) if trap[] != C_NULL bytes = WasmByteVec() wasm_trap_message(trap[], bytes) msg = unsafe_string(bytes.data, bytes.size) wasm_trap_delete(trap[]) error(msg) end results = map(wasmtime_results) do result if result.kind == WASMTIME_I32 result.of.i32 elseif result.kind == WASMTIME_I64 result.of.i64 elseif result.kind == WASMTIME_F32 result.of.f32 elseif result.kind == WASMTIME_F64 result.of.f64 elseif result.kind == WASMTIME_V128 result.of.v128 elseif result.kind == WASMTIME_FUNCREF result.of.funcref elseif result.kind == WASMTIME_EXTERNREF result.of.externref else error("Unknown value kind $(result.kind)") end end length(results) == 1 ? first(results) : results end function exports(instance::WasmtimeInstance) instance_type = wasmtime_instance_type(instance.store, instance) @assert instance_type != C_NULL "Failed to get module type from WasmtimeModule" wasm_exports = WasmPtrVec(wasm_exporttype_t) wasmtime_instancetype_exports(instance_type, wasm_exports) wasmtime_exports = map(enumerate(wasm_exports)) do (i, wasm_export_ptr) owned_wasm_export_ptr = wasm_exporttype_copy(wasm_export_ptr) @assert owned_wasm_export_ptr != C_NULL "Failed to copy WASM export" extern = wasmtime_extern( UInt8(0), wasmtime_extern_union(Tuple(UInt8(0xab) for _ = 1:16)), ) name_vec = Ref(wasm_name(0, Ptr{wasm_byte_t}())) char_ptr = Base.unsafe_convert( Ptr{Nothing}, Base.unsafe_convert(Ptr{wasm_byte_vec_t}, name_vec), ) + Base.sizeof(Csize_t) len_ptr = Base.unsafe_convert( Ptr{Csize_t}, Base.unsafe_convert(Ptr{wasm_byte_vec_t}, name_vec), ) exists = wasmtime_instance_export_nth( instance.store, instance, i - 1, char_ptr, len_ptr, Base.pointer_from_objref(extern), ) exists || error("Export #$i does not exists") name = unsafe_string(name_vec[].data, name_vec[].size) export_ = WasmtimeInstanceExport(wasm_export_ptr, extern, instance, name) if extern.kind == WASM_EXTERN_FUNC WasmtimeFunc(export_) elseif extern.kind == WASM_EXTERN_MEMORY WasmtimeMemory(export_) else # generic export, TODO: complete export_ end end WasmExports(instance, wasmtime_exports) end name(func::WasmtimeFunc) = func.export_.name name(mem::WasmtimeMemory) = mem.export_.name name(export_::WasmtimeInstanceExport) = export_.name
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
496
mutable struct WasmtimeLinker wasmtime_linker_ptr::Ptr{wasmtime_linker_t} WasmtimeLinker(ptr::Ptr{wasmtime_linker_t}) = finalizer(wasmtime_linker_delete, new(ptr)) end WasmtimeLinker(engine) = wasmtime_linker_new(engine) |> WasmtimeLinker Base.unsafe_convert(::Type{Ptr{wasmtime_linker_t}}, linker::WasmtimeLinker) = linker.wasmtime_linker_ptr Base.show(io::IO, ::WasmtimeLinker) = write(io, "WasmtimeLinker()") define_wasi!(linker) = (@wt_check wasmtime_linker_define_wasi(linker));
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
2147
mutable struct WasmtimeModule <: AbstractWasmModule wasmtime_module_ptr::Ptr{wasmtime_module_t} WasmtimeModule(ptr::Ptr{wasmtime_module_t}) = finalizer(wasmtime_module_delete, new(ptr)) end function WasmtimeModule(engine, code) mod_ptr = Ref{Ptr{wasmtime_module_t}}(Ptr{wasmtime_module_t}()) @wt_check GC.@preserve mod wasmtime_module_new( engine, code, length(code), Base.pointer_from_objref(mod_ptr), ) WasmtimeModule(mod_ptr[]) end Base.unsafe_convert(::Type{Ptr{wasmtime_module_t}}, mod::WasmtimeModule) = mod.wasmtime_module_ptr Base.show(io::IO, ::WasmtimeModule) = write(io, "WasmtimeModule()") function imports(mod::WasmtimeModule) module_type = wasmtime_module_type(mod) mod_imports = WasmPtrVec(wasm_importtype_t) wasmtime_moduletype_imports(module_type, mod_imports) WasmImports(mod, mod_imports) end mutable struct NotInstanciatedWasmExport <: AbstractWasmExport wasm_export_ptr::Ptr{wasm_exporttype_t} wasm_module::WasmtimeModule name::String function NotInstanciatedWasmExport( wasm_export_ptr::Ptr{wasm_exporttype_t}, mod::WasmtimeModule, ) owned_wasm_export_ptr = wasm_exporttype_copy(wasm_export_ptr) @assert owned_wasm_export_ptr != C_NULL "Failed to copy WASM export" name_vec_ptr = wasm_exporttype_name(owned_wasm_export_ptr) name_vec = Base.unsafe_load(name_vec_ptr) name = unsafe_string(name_vec.data, name_vec.size) wasm_name_delete(name_vec_ptr) finalizer(new(owned_wasm_export_ptr, mod, name)) do wasm_export wasm_exporttype_delete(wasm_export.wasm_export_ptr) end end end function exports(mod::WasmtimeModule) module_type = wasmtime_module_type(mod) @assert module_type != C_NULL "Failed to get module type from WasmtimeModule" wasm_exports = WasmPtrVec(wasm_exporttype_t) wasmtime_moduletype_exports(module_type, wasm_exports) exports_vector = map(a -> NotInstanciatedWasmExport(a, mod), wasm_exports) WasmExports{WasmtimeModule,NotInstanciatedWasmExport}(mod, exports_vector) end
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
1511
mutable struct WasmtimeStore wasmtime_store_ptr::Ptr{wasmtime_store_t} wasmtime_context_ptr::Ptr{wasmtime_context_t} WasmtimeStore(store_ptr::Ptr{wasmtime_store_t}, ctx_ptr::Ptr{wasmtime_context_t}) = finalizer(wasmtime_store_delete, new(store_ptr, ctx_ptr)) end function WasmtimeStore(engine) store = wasmtime_store_new(engine, C_NULL, C_NULL) context = wasmtime_store_context(store) WasmtimeStore(store, context) end Base.unsafe_convert(::Type{Ptr{wasmtime_store_t}}, store::WasmtimeStore) = store.wasmtime_store_ptr Base.unsafe_convert(::Type{Ptr{wasmtime_context_t}}, store::WasmtimeStore) = store.wasmtime_context_ptr Base.show(io::IO, ::WasmtimeStore) = write(io, "WasmtimeStore()") add_fuel!(store, β›½) = @wt_check wasmtime_context_add_fuel(store, β›½) function consume_fuel!(store, πŸ›») remaining = Ref(0) @wt_check GC.@preserve remaining wasmtime_context_consume_fuel(store, πŸ›», Base.pointer_from_objref(remaining)) remaining[] end function fuel_consumed(store) remaining = Ref(0) fuel_enabled = GC.@preserve remaining wasmtime_context_fuel_consumed(store, Base.pointer_from_objref(remaining)) if !fuel_enabled error("Fuel consumption is not enabled on the engine for this store") end remaining[] end function set_wasi!(store, wasi_config) @assert !wasi_config.owned "This WASI configuration is already used by anotherstore" @wt_check wasmtime_context_set_wasi(store, wasi_config) wasi_config.owned = true nothing end
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
799
mutable struct wasi_instance_t end mutable struct WasiConfig wasi_config_ptr::Ptr{wasi_config_t} program_name::String owned::Bool WasiConfig(wasi_config_ptr, name) = finalizer(new(wasi_config_ptr, name, false)) do config config.owned || wasi_config_delete(config) end end WasiConfig(program_name::String) = WasiConfig(wasi_config_new(), program_name) Base.unsafe_convert(::Type{Ptr{wasi_config_t}}, wasi_config::WasiConfig) = wasi_config.wasi_config_ptr function set_argv!(config::WasiConfig, argv) @assert !config.owned "This WASI configuration is already owned by a store, it can't be modified" arr_ptr = Base.unsafe_convert.(Cstring, argv) GC.@preserve arr_ptr argv wasi_config_set_argv(config, length(argv), pointer(arr_ptr)) end
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
215
function wat2wasm(wat::AbstractString) out = WasmByteVec() @wt_check wasmtime_wat2wasm( wat, length(wat), out, ) out end macro wat_str(wat::String) :(wat2wasm($wat)) end
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
3136
@testset "Import/Export" begin @testset "Import function" begin wasm_code = wat""" (module (func $host_function (import \"\" \"host_function\") (result i32)) (func $function (export \"guest_function\") (result i32) (call $host_function))) """ engine = WasmEngine() store = WasmStore(engine) wasm_module = WasmModule(store, wasm_code) @test_throws Any instance = WasmInstance(store, wasm_module) wasm_imports = imports(wasm_module) semaphore = Ref(32) function jl_side() # side effect on julia side semaphore[] = 42 # return values Int32(100) end func_type = WasmFunc(store, jl_side, Int32, ()) instance = WasmInstance(store, wasm_module, [func_type]) mod_exports = exports(instance) guest_function = mod_exports.guest_function res = guest_function() @test res[1].kind == Wasmtime.WASM_I32 @test res[1].of.i32 == 100 @test semaphore[] == 42 end @testset "WASI import" begin wasm_code = wat""" (module ;; Import the required fd_write WASI function which will write the given io vectors to stdout ;; The function signature for fd_write is: ;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written (import "wasi_unstable" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32))) (memory 1) (export "memory" (memory 0)) ;; Write 'hello world\n' to memory at an offset of 8 bytes ;; Note the trailing newline which is required for the text to appear (data (i32.const 8) "hello world\n") (func $main (export "_start") ;; Creating a new io vector within linear memory (i32.store (i32.const 0) (i32.const 8)) ;; iov.iov_base - This is a pointer to the start of the 'hello world\n' string (i32.store (i32.const 4) (i32.const 12)) ;; iov.iov_len - The length of the 'hello world\n' string (call $fd_write (i32.const 1) ;; file_descriptor - 1 for stdout (i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0 (i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one. (i32.const 20) ;; nwritten - A place in memory to store the number of bytes written ) drop ;; Discard the number of bytes written from the top of the stack ) ) """ engine = WasmEngine() store = WasmStore(engine) wasm_module = WasmModule(store, wasm_code) imports = Wasmtime.imports(wasm_module) @test length(imports.wasm_imports) == 1 @test imports.wasm_imports[1].import_module == "wasi_unstable" @test imports.wasm_imports[1].name == "fd_write" @test imports.wasm_imports[1].extern_kind == Wasmtime.WASM_EXTERN_FUNC end end
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
4765
using Wasmtime using Test @testset "Call foreign" begin engine = WasmEngine() store = Wasmtime.WasmtimeStore(engine) code = wat""" (module (func $add (param $lhs i32) (param $rhs i32) (result i32) local.get $lhs local.get $rhs i32.add) (export "add" (func $add)) ) """ modu = Wasmtime.WasmtimeModule(engine, code) instance = Wasmtime.WasmtimeInstance(store, modu) add = exports(instance).add res = add(Int32(1), Int32(2)) @test res == Int32(3) end const PAGE_SIZE = 65536 @testset "Memory" begin engine = WasmEngine() store = Wasmtime.WasmtimeStore(engine) code = wat""" (module (memory 42) (export "memory" (memory 0)) ) """ modu = Wasmtime.WasmtimeModule(engine, code) instance = Wasmtime.WasmtimeInstance(store, modu) mem = exports(instance).memory @test length(mem) == 42PAGE_SIZE code = wat""" (module (memory 0 1) (export "memory" (memory 0)) ) """ modu = Wasmtime.WasmtimeModule(engine, code) instance = Wasmtime.WasmtimeInstance(store, modu) mem = exports(instance).memory @test length(mem) == 0 Wasmtime.grow!(mem, 1) @test length(mem) == PAGE_SIZE # Cannot grow past max page size @test_throws ErrorException Wasmtime.grow!(mem, 1) code = wat""" (module (memory 1) (func (result i32) i32.const 0 i32.load ) (func (result f32) i32.const 0 f32.load ) (func (result f64) i32.const 0 f64.load ) (export "i32" (func 0)) (export "f32" (func 1)) (export "f64" (func 2)) (export "memory" (memory 0)) ) """ modu = Wasmtime.WasmtimeModule(engine, code) instance = Wasmtime.WasmtimeInstance(store, modu) mem = exports(instance).memory i32 = exports(instance).i32 f32 = exports(instance).f32 f64 = exports(instance).f64 i32_buf = reinterpret(Int32, mem) f32_buf = reinterpret(Float32, mem) f64_buf = reinterpret(Float64, mem) @test i32() === Int32(0) i32_buf[1] = 42 @test i32() === Int32(42) f32_buf[1] = 42f0 @test f32() === 42f0 f64_buf[1] = 42. @test f64() === 42. end @testset "passthrough" begin code = wat""" (module (func (param i32) (result i32) local.get 0) (func (param i64) (result i64) local.get 0) (func (param f32) (result f32) local.get 0) (func (param f64) (result f64) local.get 0) (export "i32" (func 0)) (export "i64" (func 1)) (export "f32" (func 2)) (export "f64" (func 3))) """ engine = WasmEngine() store = Wasmtime.WasmtimeStore(engine) modu = Wasmtime.WasmtimeModule(engine, code) instance = Wasmtime.WasmtimeInstance(store, modu) i32 = exports(instance).i32 i64 = exports(instance).i64 f32 = exports(instance).f32 f64 = exports(instance).f64 for (f,T) in zip((i32,i64,f32,f64), (Int32,Int64,Float32,Float64)) val = T(42) @test f(val) == val end end @testset "v128" begin code = wat""" (module (func (param v128) (result f32) local.get 0 f32x4.extract_lane 1) (func (param v128) (result f32) local.get 0 f32x4.extract_lane 0 local.get 0 f32x4.extract_lane 1 local.get 0 f32x4.extract_lane 2 local.get 0 f32x4.extract_lane 3 f32.add f32.add f32.add) (export "f32x4_extract_lane" (func 0)) (export "f32x4_sum" (func 1))) """ engine = WasmEngine() store = Wasmtime.WasmtimeStore(engine) module_ = Wasmtime.WasmtimeModule(engine, code) instance = Wasmtime.WasmtimeInstance(store, module_) f = exports(instance).f32x4_extract_lane fsum = exports(instance).f32x4_sum v = Wasmtime.f32x4(1f0, Float32(Ο€), 42f0, -32f0) out = f(v) @test Float32(Ο€) == out x₁,xβ‚‚,x₃,xβ‚„ = Wasmtime.f32x4(v) out = fsum(v) @test ((x₃+xβ‚„)+xβ‚‚)+x₁ == out end @testset "traps on unreachable" begin code = wat""" (module (func unreachable) (export "f" (func 0))) """ engine = WasmEngine() store = Wasmtime.WasmtimeStore(engine) module_ = Wasmtime.WasmtimeModule(engine, code) instance = Wasmtime.WasmtimeInstance(store, module_) f = exports(instance).f @test_throws ErrorException f() end # include("./table.jl") include("./import_export.jl") include("./wat2wasm.jl") include("./wasi.jl")
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
887
@testset "WasmTable" begin wasm_code = wat""" (module (import "js" "tbl" (table 2 anyfunc)) (func $f42 (result i32) i32.const 42) (func $f83 (result i32) i32.const 83) (elem (i32.const 0) $f42 $f83) )""" engine = WasmEngine() store = WasmStore(engine) wasm_module = WasmModule(store, wasm_code) table = Wasmtime.WasmTable(store, 2 => 5) @test Base.unsafe_convert(Ptr{Wasmtime.wasm_func_t}, table[1]) == C_NULL @test Base.unsafe_convert(Ptr{Wasmtime.wasm_func_t}, table[2]) == C_NULL instance = WasmInstance(store, wasm_module, [table]) @test Base.unsafe_convert(Ptr{Wasmtime.wasm_func_t}, table[1]) != C_NULL @test Base.unsafe_convert(Ptr{Wasmtime.wasm_func_t}, table[2]) != C_NULL @test Base.convert(Int32, table[1]()[1]) == 42 @test Base.convert(Int32, table[2]()[1]) == 83 end
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
1865
using Downloads @testset "WASI - Cowsay" begin mktempdir() do tmp_dir # TODO: Find a better way to provide the files location = joinpath(tmp_dir, "cowsay.wasm") Downloads.download( "https://registry-cdn.wapm.io/contents/_/cowsay/0.2.0/target/wasm32-wasi/release/cowsay.wasm", location, ) wasm_code = open(read, location, "r") |> Wasmtime.WasmVec engine = WasmEngine() store = Wasmtime.WasmtimeStore(engine) wasm_module = Wasmtime.WasmtimeModule(engine, wasm_code) msg = "Meuuuh!" stdin_path = joinpath(tmp_dir, "./stdin.txt") stdout_path = joinpath(tmp_dir, "./stdout.txt") open(stdin_path, "w") do file write(file, msg) end # TODO: Fix program name and argv's wasi_config = Wasmtime.WasiConfig("wasi_unstable") Wasmtime.wasi_config_inherit_stderr(wasi_config) Wasmtime.wasi_config_set_stdout_file(wasi_config, stdout_path) Wasmtime.wasi_config_set_stdin_file(wasi_config, stdin_path) Wasmtime.wasi_config_inherit_env(wasi_config) Wasmtime.wasi_config_set_argv(wasi_config, 1, ["cowsay"]) Wasmtime.set_wasi!(store, wasi_config) linker = Wasmtime.WasmtimeLinker(engine) Wasmtime.define_wasi!(linker) instance = Wasmtime.WasmtimeInstance(linker, store, wasm_module) instance_exports = exports(instance) main_func = instance_exports._start main_func() result = read(stdout_path, String) expected = raw""" _________ < Meuuuh! > --------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || """ @test result == expected end end
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
code
888
@testset "wat2wasm" begin exception = try wat"invalid wasm code" catch e e end exception_msg = string(exception) @test occursin("invalid wasm code", exception_msg) end @testset "Basic export" begin wasm_code = wat""" (module (type $sum_t (func (param i32 i32) (result i32))) (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32) local.get $x local.get $y i32.add) (export "sum" (func $sum_f))) """ engine = WasmEngine() store = WasmStore(engine) wasm_module = WasmModule(store, wasm_code) instance = WasmInstance(store, wasm_module) wasm_exports = exports(instance) sum_function = wasm_exports.sum result, = sum_function(Int32(2), Int32(2)) result = Base.convert(Int32, result) @test result == Int32(4) end
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.2.2
88c874db43a7c0f99347ee1013b2052e6cf23ac3
docs
1552
# Wasmtime.jl A Julia wrapper around the wasmtime runtime to run Web Assembly blobs and libraries from Julia. ## Examples ```julia julia> using Wasmtime julia> code = wat""" (module (memory 1) ;; adds two consecutive f32 located at ;; address $ptr in memory (func $sum (param $ptr i32) (result f32) local.get $ptr f32.load local.get 0 i32.const 4 i32.add f32.load f32.add ) (export "sum" (func $sum)) (export "memory" (memory 0)) ) """; julia> engine = WasmEngine(); store = Wasmtime.WasmtimeStore(engine); julia> module_ = Wasmtime.WasmtimeModule(engine, code); julia> instance = Wasmtime.WasmtimeInstance(store, module_); julia> (; memory, sum) = exports(instance); julia> buf = reinterpret(Float32, memory); # memory is an AbstractVector{UInt8} julia> buf[1] = 32.5f0; buf[2] = 3f0; julia> sum(Int32(0)) 35.5f0 julia> buf[1] + buf[2] 35.5f0 ``` ## Usage Wastime exposes two C api. The first one is the common Web Assembly runtime C api with names starting with `Wasm` in Wasmtime.jl. The second one is a wasmtime specific api which provides more functionality like WASI imports, fine-grained configuration of the store features like fuel. See the [`test` folder](https://github.com/Pangoraw/Wasmtime.jl/tree/main/test) for usage examples.
Wasmtime
https://github.com/Pangoraw/Wasmtime.jl.git
[ "MIT" ]
0.1.0
59fc4a35e686a96aec6dc24959836b8e8d7666ce
code
2765
""" SSHAgentSetup A tool to setup `ssh-agent`. # Usage ```julia import SSHAgentSetup SSHAgentSetup.setup() SSHAgentSetup.add_key(joinpath(homedir(), ".ssh", "id_rsa")) ``` """ module SSHAgentSetup """ parse_ssh_agent_variables(ssh_agent_output::AbstractString) :: Dict{String, String} Parses the result from command `ssh-agent -s` as variables `SSH_AUTH_SOCK` and `SSH_AGENT_PID`. # Example ```julia str = "SSH_AUTH_SOCK=/tmp/ssh-Spqsh9i4sw6Z/agent.4558; export SSH_AUTH_SOCK;\nSSH_AGENT_PID=4559; export SSH_AGENT_PID;\necho Agent pid 4559;" result = SSHAgentSetup.parse_ssh_agent_variables(str) @assert result["SSH_AUTH_SOCK"] == "/tmp/ssh-Spqsh9i4sw6Z/agent.4558" @assert result["SSH_AGENT_PID"] == "4559" ``` """ function parse_ssh_agent_variables(ssh_agent_output::AbstractString) :: Dict{String, String} rgx = r"SSH_AUTH_SOCK=(?<SSH_AUTH_SOCK>[^;]+)[\S\s]*SSH_AGENT_PID=(?<SSH_AGENT_PID>\d+)" m = match(rgx, ssh_agent_output) result = Dict{String, String}() for expected_key in (:SSH_AUTH_SOCK, :SSH_AGENT_PID) !haskey(m, expected_key) && error("Failed to parse `$expected_key` from `ssh-agent` output") result[string(expected_key)] = m[expected_key] end return result end """ is_agent_up() :: Bool Checks wether `ssh-agent` is running. Looks for `SSH_AUTH_SOCK` environment variable. """ function is_agent_up() :: Bool return get(ENV, "SSH_AUTH_SOCK", nothing) !== nothing end """ kill_agent(; quiet::Bool=false) Runs `ssh-agent -k` to kill the current agent, and unset env variables `SSH_AUTH_SOCK` and `SSH_AGENT_PID`. """ function kill_agent(; quiet::Bool=false) if is_agent_up() !quiet && @info("Killing ssh-agent") run(`ssh-agent -k`) delete!(ENV, "SSH_AUTH_SOCK") delete!(ENV, "SSH_AGENT_PID") end nothing end """ setup(; kill_agent_atexit::Bool=false, quiet::Bool=false) Runs `ssh-agent -s` and exports env variables `SSH_AUTH_SOCK` and `SSH_AGENT_PID` with the result from that command. """ function setup(; kill_agent_atexit::Bool=false, quiet::Bool=false) if is_agent_up() !quiet && @info("ssh-agent is already present") else !quiet && @info("starting ssh-agent") agent_data = parse_ssh_agent_variables(readchomp(`ssh-agent -s`)) for (k, v) in agent_data !quiet && @info("Exporting: `$k=$v`") ENV[k] = v end if kill_agent_atexit atexit(kill_agent) end end nothing end """ add_key(key_file::AbstractString) Runs `ssh-add \$key_file`. """ function add_key(key_file::AbstractString) @assert isfile(key_file) "Key file `$key_file` not found" run(`ssh-add $key_file`) end end # module SSHAgentSetup
SSHAgentSetup
https://github.com/felipenoris/SSHAgentSetup.jl.git
[ "MIT" ]
0.1.0
59fc4a35e686a96aec6dc24959836b8e8d7666ce
code
551
using Test import SSHAgentSetup @testset "parse_ssh_agent_variables" begin str = "SSH_AUTH_SOCK=/tmp/ssh-Spqsh9i4sw6Z/agent.4558; export SSH_AUTH_SOCK;\nSSH_AGENT_PID=4559; export SSH_AGENT_PID;\necho Agent pid 4559;" result = SSHAgentSetup.parse_ssh_agent_variables(str) expected_result = Dict{String, String}( "SSH_AUTH_SOCK" => "/tmp/ssh-Spqsh9i4sw6Z/agent.4558", "SSH_AGENT_PID" => "4559", ) for (k, v) in expected_result @test haskey(result, k) @test result[k] == v end end
SSHAgentSetup
https://github.com/felipenoris/SSHAgentSetup.jl.git
[ "MIT" ]
0.1.0
59fc4a35e686a96aec6dc24959836b8e8d7666ce
docs
245
# SSHAgentSetup.jl A tool to setup `ssh-agent`. # Usage ```julia import SSHAgentSetup # starts `ssh-agent` SSHAgentSetup.setup() # uses `ssh-add` to add user key to ssh agent SSHAgentSetup.add_key(joinpath(homedir(), ".ssh", "id_rsa")) ```
SSHAgentSetup
https://github.com/felipenoris/SSHAgentSetup.jl.git
[ "MIT" ]
0.2.1
75fdc4972dae0869b855af00ebe86f8f751b2c85
code
4745
## ODEProblem """ ODEProblem(env::AbstractEnv, f, x0, tspan; kwargs...) An API for DifferentialEquations.ODEProblem(f, x0, tspan; kwargs...). """ function DifferentialEquations.ODEProblem(env::AbstractEnv, f, x0, tspan; kwargs...) warn_is_registered(env) _x0 = raw(env, x0) _f(_x, p, t) = raw(env, f(readable(env, _x), p, t)) ODEProblem(_f, _x0, tspan; kwargs...) end function DifferentialEquations.ODEProblem(env::AbstractEnv, f, x0, tspan, p; kwargs...) warn_is_registered(env) _x0 = raw(env, x0) _f(_x, p, t) = raw(env, f(readable(env, _x), p, t)) ODEProblem(_f, _x0, tspan, p; kwargs...) end ## initial condition # automatic completion of initial condition """ initial_condition(env::AbstractEnv) Automatic completion of readable initial_condition if methods of its sub-environments are given. """ function initial_condition(env::AbstractEnv) env_names = names(env) values = env_names |> Map(name -> initial_condition(getfield(env, name))) return (; zip(env_names, values)...) # NamedTuple end ## register env """ @reg_env(env, x0) Register given environment. `x0` is an example of readable initial_condition for `env` so that `NestedEnvironments` infers the information of `env`. # Notes - Must be used in the global scope. - `x0` can be any dummy NamedTuple-collection. """ macro reg_env(env, x0) ex = quote if typeof($(env)) <: AbstractEnv local env_index_nt, env_size_nt = NestedEnvironments._preprocess($(env), $(x0)) # raw & readable NestedEnvironments.readable(env::typeof($(env)), _x) = NestedEnvironments._readable(_x, env_index_nt, env_size_nt) NestedEnvironments.raw(env::typeof($(env)), x) = NestedEnvironments._raw($(env), x) # register env push!(NestedEnvironments.__REGISTERED_ENVS, $(env), $(x0)) else error("Invalid environment") end end esc(ex) end # aux function Base.push!(__REGISTERED_ENVS::RegisteredEnvs, env::AbstractEnv, x0) num_of_already_reg_envs = __REGISTERED_ENVS.__envs |> Filter(__env -> typeof(__env) == typeof(env)) |> collect |> length if num_of_already_reg_envs == 0 push!(__REGISTERED_ENVS.__envs, env) push!(__REGISTERED_ENVS.__xs, x0) println("$(typeof(env)): registered") else println("$(typeof(env)): overwrite existing registered env") end end ## macros # macro for transformation from readable to raw """ @raw(env, x) A macro that transforms a readable (NamedTuple) value to raw (flattened array) value. """ macro raw(env, x) ex = quote if typeof($(env)) <: AbstractEnv _x = NestedEnvironments.raw($(env), $(x)) else error("Invalid environment") end end esc(ex) end # auto-completion """ @raw(x) A macro that transforms a readable (NamedTuple) value to raw (flattened array) value by corresponding an appropriate environment from the registered environments. """ macro raw(x) ex = quote local env_x_cands = zip(NestedEnvironments.__REGISTERED_ENVS.__envs, NestedEnvironments.__REGISTERED_ENVS.__xs) |> Transducers.Filter(env_x -> size(env_x[2]) == size($(x))) |> collect if length(env_x_cands) == 0 error("There is no matched registered envrionment") elseif length(env_x_cands) > 1 error("It is ambiguous; too many matched registered environments") else @raw(env_x_cands[1][1], $(x)) end end esc(ex) end # macro for transformation from raw to readable """ @readable(env, _x) A macro that transforms a raw (flattened array) value to readable (NamedTuple) value. """ macro readable(env, _x) ex = quote if typeof($(env)) <: AbstractEnv x = NestedEnvironments.readable($(env), $(_x)) else error("Invalid environment") end end esc(ex) end # auto-completion """ @readable(x) A macro that transforms a raw (flattened array) value to readable (NamedTuple) value by corresponding an appropriate environment from the registered environments. """ macro readable(_x) ex = quote local env_x_cands = zip(NestedEnvironments.__REGISTERED_ENVS.__envs, NestedEnvironments.__REGISTERED_ENVS.__xs) |> Transducers.Filter(env_x -> NestedEnvironments.flatten_length(env_x[2]) == NestedEnvironments.flatten_length($(_x))) |> collect if length(env_x_cands) == 0 error("There is no matched registered envrionment") elseif length(env_x_cands) > 1 error("It is ambiguous; too many matched registered environments") else @readable(env_x_cands[1][1], $(_x)) end end esc(ex) end
NestedEnvironments
https://github.com/JinraeKim/NestedEnvironments.jl.git
[ "MIT" ]
0.2.1
75fdc4972dae0869b855af00ebe86f8f751b2c85
code
328
module NestedEnvironments using DifferentialEquations using Transducers export AbstractEnv # types.jl # internalAPIs.jl export raw, readable, @reg_env, @raw, @readable # APIs.jl export BaseEnv, InputAffineQuadraticCostEnv # zoo.jl include("types.jl") include("internalAPIs.jl") include("APIs.jl") include("zoo.jl") end
NestedEnvironments
https://github.com/JinraeKim/NestedEnvironments.jl.git
[ "MIT" ]
0.2.1
75fdc4972dae0869b855af00ebe86f8f751b2c85
code
2731
## warning function warn_is_registered(env::AbstractEnv) is_registered = NestedEnvironments.__REGISTERED_ENVS.__envs |> Map(__env -> typeof(__env) == typeof(env)) |> collect |> any return is_registered ? nothing : error("Unregistered env: $(typeof(env))") end ## functions # env names function Base.names(env::AbstractEnv) return [name for name in fieldnames(typeof(env)) if typeof(getfield(env, name)) <: AbstractEnv] end # extend size for NamedTuple function Base.size(x0::NamedTuple) env_names = keys(x0) if env_names == [] return size(x0) else env_sizes = env_names |> Map(name -> size(x0[name])) return (; zip(env_names, env_sizes)...) # NamedTuple end end function flatten_length(x0::NamedTuple) env_names = keys(x0) if env_names == [] return prod(size(x0)) else return env_names |> Map(name -> flatten_length(x0[name])) |> sum end end flatten_length(x0) = prod(size(x0)) # get the index function _index(env::AbstractEnv, x0, _range) env_names = names(env) if env_names == [] return _range else env_accumulated_flatten_lengths = env_names |> Map(name -> flatten_length(x0[name])) |> Scan(+) |> collect range_first = first(_range) env_ranges_tmp = (range_first-1) .+ [0, env_accumulated_flatten_lengths...] |> Consecutive(length(env_accumulated_flatten_lengths); step=1) env_ranges = zip(env_ranges_tmp...) |> MapSplat((x, y) -> x+1:y) env_indices = zip(env_names, env_ranges) |> MapSplat((name, range) -> _index(getfield(env, name), x0[name], range)) return (; zip(env_names, env_indices)...) # NamedTuple end end # get env_index and env_isze function _preprocess(env::AbstractEnv, x0) env_size_nt = size(x0) env_flatten_length = flatten_length(x0) env_index_nt = _index(env, x0, 1:env_flatten_length) return env_index_nt, env_size_nt end ## main functions # transform readable to raw (flatten) function _raw(env::AbstractEnv, x) env_names = names(env) if env_names == [] return x else _x = env_names |> MapCat(name -> _raw(getfield(env, name), x[name])) |> collect return _x end end # transform raw (flatten) to readable function _readable(_x, env_index_nt, env_size_nt) if typeof(env_index_nt) <: AbstractRange if env_size_nt == () return _x[env_index_nt][1] # scalar else return reshape(_x[env_index_nt], env_size_nt...) end else index_names = keys(env_index_nt) processed_values = index_names |> Map(name -> _readable(_x, env_index_nt[name], env_size_nt[name])) return (; zip(index_names, processed_values)...) end end
NestedEnvironments
https://github.com/JinraeKim/NestedEnvironments.jl.git
[ "MIT" ]
0.2.1
75fdc4972dae0869b855af00ebe86f8f751b2c85
code
269
## basic # envs abstract type AbstractEnv end # registered envs mutable struct RegisteredEnvs __envs::Array{AbstractEnv, 1} __xs::Array{Any, 1} end __REGISTERED_ENVS = RegisteredEnvs([], []) # generic functions function readable end function raw end ## zoo
NestedEnvironments
https://github.com/JinraeKim/NestedEnvironments.jl.git
[ "MIT" ]
0.2.1
75fdc4972dae0869b855af00ebe86f8f751b2c85
code
1724
using LinearAlgebra using Parameters ########## Base Env ########## # BaseEnv struct BaseEnv <: AbstractEnv initial_state end BaseEnv(given_size::Tuple) = BaseEnv(zeros(given_size)) BaseEnv(args...) = BaseEnv(zeros(args...)) BaseEnv() = BaseEnv(0.0) # initial_condition NestedEnvironments.initial_condition(env::BaseEnv) = env.initial_state ########## InputAffineQuadraticCostEnv ########## """ An example of continuous-time nonlinear dynamical system introduced in several studies on approximate dynamic programming. # Reference [1] K. G. Vamvoudakis and F. L. Lewis, β€œOnline Actor-Critic Algorithm to Solve the Continuous-Time Infinite Horizon Optimal Control Problem,” Automatica, vol. 46, no. 5, pp. 878–888, 2010, doi: 10.1016/j.automatica.2010.02.018. [2] V. Nevistic and J. A. Primbs, β€œConstrained Nonlinear Optimal Control: a Converse HJB Approach,” 1996. """ @with_kw struct InputAffineQuadraticCostEnv <: AbstractEnv Q = Matrix(I, 2, 2) R = 1 P = [0.5 0; 0 1] end function f(env::InputAffineQuadraticCostEnv, x) x1 = x[1] x2 = x[2] f1 = -x1 + x2 f2 = -0.5*x1 -0.5*x2*(1-(cos(2*x1)+2)^2) return [f1, f2] end function g(env::InputAffineQuadraticCostEnv, x) x1 = x[1] g1 = 0 g2 = cos(2*x1) +2 return [g1, g2] end """ r(env, x, u) Calculate running cost, i.e., V = ∫r dt. """ function r(env::InputAffineQuadraticCostEnv, x, u) x'*env.Q*x + u'*env.R*u end function V_optimal(env::InputAffineQuadraticCostEnv, x) return x'*env.P*x end function u_optimal(env::InputAffineQuadraticCostEnv, x) _g = g(env, x) return -_g'*env.P*x end function xΜ‡(env::InputAffineQuadraticCostEnv, x, t, u) xΜ‡ = f(env, x) + g(env, x)*u return xΜ‡ end
NestedEnvironments
https://github.com/JinraeKim/NestedEnvironments.jl.git
[ "MIT" ]
0.2.1
75fdc4972dae0869b855af00ebe86f8f751b2c85
code
1955
using NestedEnvironments using DifferentialEquations using Transducers using Random using Plots ## envs struct Policy end command(policy::Policy, x::Array{Float64, 1}) = -5*sum(x) struct Env <: AbstractEnv iaqc::NestedEnvironments.InputAffineQuadraticCostEnv policy::Policy end function dynamics(env::Env) return function (x, p, t) a = p # zero-order-hold action (; iaqc = NestedEnvironments.ẋ(env.iaqc, x.iaqc, t, a)) end end # automatic completion of initial condition NestedEnvironments.initial_condition(env::NestedEnvironments.InputAffineQuadraticCostEnv) = 2*(rand(2) .- 0.5) # register envs __env = Env(NestedEnvironments.InputAffineQuadraticCostEnv(), Policy()) __x0 = NestedEnvironments.initial_condition(__env) @reg_env __env __x0 ## main function main() Random.seed!(1) env = Env(NestedEnvironments.InputAffineQuadraticCostEnv(), Policy()) x0 = NestedEnvironments.initial_condition(env) t0 = 0.0 tf = 10.0 Δt = 0.01 tspan = (t0, tf) ts = t0:Δt:tf prob = ODEProblem(env, dynamics(env), x0, tspan) function affect!(integrator) x = @readable env integrator.u # actually not necessary in this case but recommended integrator.p = command(env.policy, x.iaqc) end cb_policy = PresetTimeCallback(ts, affect!) saved_values = SavedValues(Float64, NamedTuple) cb_save = SavingCallback((u, t, integrator) -> (; state = @readable(env, integrator.u).iaqc, action = integrator.p), saved_values, saveat=ts) cb = CallbackSet(cb_policy, cb_save) @time sol = solve(prob, Tsit5(); p=0.0, callback=cb) xs = (hcat((saved_values.saveval |> Map(nt -> nt.state) |> collect)...))' actions = saved_values.saveval |> Map(nt -> nt.action) |> collect p_x = plot(ts, xs) log_dir = "data/agent" mkpath(log_dir) savefig(p_x, joinpath(log_dir, "x.png")) p_a = plot(ts, actions) savefig(p_a, joinpath(log_dir, "a.png")) end
NestedEnvironments
https://github.com/JinraeKim/NestedEnvironments.jl.git
[ "MIT" ]
0.2.1
75fdc4972dae0869b855af00ebe86f8f751b2c85
code
1085
using NestedEnvironments using DifferentialEquations using Transducers using Random using Plots using Test function dynamics(env::NestedEnvironments.InputAffineQuadraticCostEnv) return function (x, p, t) u = command(env, x) NestedEnvironments.ẋ(env, x, t, u) end end command(env, x) = NestedEnvironments.u_optimal(env, x) NestedEnvironments.initial_condition(env::NestedEnvironments.InputAffineQuadraticCostEnv) = 2*(rand(2) .- 0.5) # register envs __env = NestedEnvironments.InputAffineQuadraticCostEnv() __x0 = NestedEnvironments.initial_condition(__env) @reg_env __env __x0 function test() env = NestedEnvironments.InputAffineQuadraticCostEnv() x0 = NestedEnvironments.initial_condition(env) @show x0 @show _x0 = @raw(env, x0) @test _x0 == @raw x0 @test x0 == @readable(env, _x0) t0 = 0.0 tf = 10.0 Δt = 0.01 tspan = (t0, tf) ts = t0:Δt:tf prob = ODEProblem(env, dynamics(env), x0, tspan) @time sol = solve(prob, Tsit5(), saveat=ts) xs = sol.u |> Map(u -> @readable u) |> collect @show xs end
NestedEnvironments
https://github.com/JinraeKim/NestedEnvironments.jl.git
[ "MIT" ]
0.2.1
75fdc4972dae0869b855af00ebe86f8f751b2c85
code
154
using NestedEnvironments using DifferentialEquations struct IntegralRLEnv <: AbstractEnv env::InputAffineQuadraticCostEnv ∫r::IntegralRLEnv end
NestedEnvironments
https://github.com/JinraeKim/NestedEnvironments.jl.git
[ "MIT" ]
0.2.1
75fdc4972dae0869b855af00ebe86f8f751b2c85
code
2182
using NestedEnvironments using DifferentialEquations using Transducers using Test # `BaseEnv` is a kind of syntax sugar for definition of environment; provided by `src/zoo.jl`. # Note: `NestedEnvironments.initial_condition(env::BaseEnv) = env.initial_state` struct Env2 <: AbstractEnv env21::BaseEnv env22::BaseEnv end struct Env <: AbstractEnv env1::BaseEnv env2::Env2 gain::Float64 end # differential equations are regarded as nested envs (NamedTuple) function dynamics(env::Env) return function (x, p, t) x1 = x.env1 x21 = x.env2.env21 x22 = x.env2.env22 ẋ1 = -x1 - env.gain*sum(x21 + x22) ẋ21 = -x21 ẋ22 = -x22 (; env1 = ẋ1, env2 = (; env21 = ẋ21, env22 = ẋ22)) end end # for convenience function make_env() env21, env22 = BaseEnv(reshape(collect(1:8), 2, 4)), BaseEnv(reshape(collect(9:16), 2, 4)) env1 = BaseEnv(-1) env2 = Env2(env21, env22) gain = 2.0 env = Env(env1, env2, gain) env end # register env; do it in global scope __env = make_env() __x0 = NestedEnvironments.initial_condition(__env) @reg_env __env __x0 # test function test() env = make_env() # initial condition # if you extend `NestedEnvironments.initial_condition` for all sub environments, then `NestedEnvironments.initial_condition(env::Env)` will automatically complete a readable initial condition as NamedTuple. x0 = NestedEnvironments.initial_condition(env) # auto-completion of initial condition @show x0 # x0 = (env1 = -1, env2 = (env21 = [1 3 5 7; 2 4 6 8], env22 = [9 11 13 15; 10 12 14 16])) t0 = 0.0 tf = 10.0 tspan = (t0, tf) Δt = 0.01 # saveat; not numerical integration ts = t0:Δt:tf prob = ODEProblem(env, dynamics(env), x0, tspan) @time sol = solve(prob, Tsit5(), saveat=ts) # readable xs = sol.u |> Map(_x -> @readable _x) |> collect # nested states @test xs[1].env1 == x0.env1 @test xs[1].env2.env21 == x0.env2.env21 @test xs[1].env2.env22 == x0.env2.env22 # raw _x0 = @raw x0 @show _x0 # _x0 = [-1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] @test _x0 == sol.u[1] end
NestedEnvironments
https://github.com/JinraeKim/NestedEnvironments.jl.git
[ "MIT" ]
0.2.1
75fdc4972dae0869b855af00ebe86f8f751b2c85
code
1872
using NestedEnvironments using DifferentialEquations using Test ## user-defined nested environments struct SubSubEnv <: AbstractEnv end struct SubEnv <: AbstractEnv env21::SubSubEnv env22::SubSubEnv end struct Env <: AbstractEnv env1::SubSubEnv env2::SubEnv end # dynamics function f(x, p, t) ẋ1 = -x.env1 ẋ21 = -x.env2.env21 ẋ22 = -x.env2.env22 (; env1 = ẋ1, env2 = (; env21 = ẋ21, env22 = ẋ22)) end # initial condition function initial_condition(env::Env) (; env1 = 1, env2 = (; env21 = rand(4), env22 = rand(2, 7))) end # for register __env = Env(SubSubEnv(), SubEnv(SubSubEnv(), SubSubEnv())) __x0 = initial_condition(__env) @reg_env __env __x0 ## test function test1() env = Env(SubSubEnv(), SubEnv(SubSubEnv(), SubSubEnv())) x0 = initial_condition(env) @test x0 == @readable @raw x0 end function test2() env = Env(SubSubEnv(), SubEnv(SubSubEnv(), SubSubEnv())) x0 = initial_condition(env) _x0 = @raw env x0 x0_new = @readable env _x0 @test x0 == x0_new end function test3() env = Env(SubSubEnv(), SubEnv(SubSubEnv(), SubSubEnv())) x0 = initial_condition(env) t0 = 0.0 tf = 100.0 tspan = (t0, tf) ts = t0:0.01:tf prob = ODEProblem(env, f, x0, tspan) sol = solve(prob, Tsit5(), saveat=ts) @test sol.u[1] == @raw env x0 end function test4() env1 = BaseEnv() @test NestedEnvironments.initial_condition(env1) == 0.0 size_tuple = (1, 2) env2 = BaseEnv(size_tuple) @test NestedEnvironments.initial_condition(env2) == zeros(size_tuple) env3 = BaseEnv(size_tuple...) @test NestedEnvironments.initial_condition(env3) == zeros(size_tuple) x0 = reshape(collect(1:15), 3, 5) env4 = BaseEnv(x0) @test NestedEnvironments.initial_condition(env4) == x0 end function test() test1() test2() test3() test4() end
NestedEnvironments
https://github.com/JinraeKim/NestedEnvironments.jl.git
[ "MIT" ]
0.2.1
75fdc4972dae0869b855af00ebe86f8f751b2c85
code
1382
using NestedEnvironments using DifferentialEquations using Plots using Random using Transducers function dynamics(env::NestedEnvironments.InputAffineQuadraticCostEnv) return function (x, p, t) u = command(env, x) NestedEnvironments.ẋ(env, x, t, u) end end command(env, x) = NestedEnvironments.u_optimal(env, x) initial_condition(env::NestedEnvironments.InputAffineQuadraticCostEnv) = 2*(rand(2) .- 0.5) __env = NestedEnvironments.InputAffineQuadraticCostEnv() __x0 = initial_condition(__env) @reg_env __env __x0 ## main function single() Random.seed!(1) env = NestedEnvironments.InputAffineQuadraticCostEnv() x0 = initial_condition(env) t0 = 0.0 tf = 10.0 Δt = 0.01 tspan = (t0, tf) ts = t0:Δt:tf prob = ODEProblem(env, dynamics(env), x0, tspan) @time sol = solve(prob, Tsit5(), saveat=ts) plot(sol) end function parallel() Random.seed!(1) env = NestedEnvironments.InputAffineQuadraticCostEnv() num = 10 x0s = 1:num |> Map(i -> initial_condition(env)) t0 = 0.0 tf = 10.0 Δt = 0.01 tspan = (t0, tf) ts = t0:Δt:tf probs = x0s |> Map(x0 -> ODEProblem(env, dynamics(env), x0, tspan)) |> collect sols = probs |> Map(prob -> solve(prob, Tsit5(), saveat=ts)) |> tcollect p = plot() _ = sols |> Map(sol -> plot!(sol, label=nothing)) |> collect display(p) end
NestedEnvironments
https://github.com/JinraeKim/NestedEnvironments.jl.git
[ "MIT" ]
0.2.1
75fdc4972dae0869b855af00ebe86f8f751b2c85
docs
3848
# NestedEnvironments.jl This is an API for nested environments, compatible with [DifferentialEquations.jl](https://github.com/SciML/DifferentialEquations.jl). ## Terminology An environment may consist of nested environments. Each environment is a structure (e.g., `typeof(env) <: AbstractEnv`), which includes dynamical systems and additional information. ## Notes - Currently, only ODE is supported. See `src/API.jl` for more details. # Features ## Nested environments `NestedEnvironments.jl` supports nested environments API. The **dynamical equations** and **initial condition** are treated as structured forms (as NamedTuple). Compared to the original `DifferentialEquations.jl`, you don't need to match the index of derivative calculation. For example, ```julia function f(x, p, t) x1 = x.env1 # for example x2 = x.env2 # for example dx1 = x2 dx2 = -x1 (; x1 = dx1, x2 = dx2) # NamedTuple end ``` instead of ```julia function f(x, p, t) dx = zero(x) dx[1] = x[2] dx[2] = -x[1] dx end ``` . For more details, see the below example. ## Macros and auto-completion `NestedEnvironments.jl` provides convenient macros such as `@readable` and `@raw`. `@readable` makes an Array, compatible with `DifferentialEquations.jl`, (structured) NamedTuple. Conversely, `@raw` makes a NamedTuple, default structure of `NestedEnvironments.jl`, an Array compatible with `DifferentialEquations.jl`. ## Environment Zoo It provides some predefined environments. See `src/zoo.jl` for more information. # Usage ## Example ### Nested environments It is highly recommended to run the following code and practice how to use it. ```julia using NestedEnvironments using DifferentialEquations using Transducers using Test # `BaseEnv` is a kind of syntax sugar for definition of environment; provided by `src/zoo.jl`. # Note: `NestedEnvironments.initial_condition(env::BaseEnv) = env.initial_state` struct Env2 <: AbstractEnv env21::BaseEnv env22::BaseEnv end struct Env <: AbstractEnv env1::BaseEnv env2::Env2 gain::Float64 end # differential equations are regarded as nested envs (NamedTuple) function dynamics(env::Env) return function (x, p, t) x1 = x.env1 x21 = x.env2.env21 x22 = x.env2.env22 ẋ1 = -x1 - env.gain*sum(x21 + x22) ẋ21 = -x21 ẋ22 = -x22 (; env1 = ẋ1, env2 = (; env21 = ẋ21, env22 = ẋ22)) end end # for convenience function make_env() env21, env22 = BaseEnv(reshape(collect(1:8), 2, 4)), BaseEnv(reshape(collect(9:16), 2, 4)) env1 = BaseEnv(-1) env2 = Env2(env21, env22) gain = 2.0 env = Env(env1, env2, gain) env end # register env; do it in global scope __env = make_env() __x0 = NestedEnvironments.initial_condition(__env) @reg_env __env __x0 # test function test() env = make_env() # initial condition # if you extend `NestedEnvironments.initial_condition` for all sub environments, then `NestedEnvironments.initial_condition(env::Env)` will automatically complete a readable initial condition as NamedTuple. x0 = NestedEnvironments.initial_condition(env) # auto-completion of initial condition @show x0 # x0 = (env1 = -1, env2 = (env21 = [1 3 5 7; 2 4 6 8], env22 = [9 11 13 15; 10 12 14 16])) t0 = 0.0 tf = 10.0 tspan = (t0, tf) Δt = 0.01 # saveat; not numerical integration ts = t0:Δt:tf prob = ODEProblem(env, dynamics(env), x0, tspan) @time sol = solve(prob, Tsit5(), saveat=ts) # readable xs = sol.u |> Map(_x -> @readable _x) |> collect # nested states @test xs[1].env1 == x0.env1 @test xs[1].env2.env21 == x0.env2.env21 @test xs[1].env2.env22 == x0.env2.env22 # raw _x0 = @raw x0 @show _x0 # _x0 = [-1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] @test _x0 == sol.u[1] end ```
NestedEnvironments
https://github.com/JinraeKim/NestedEnvironments.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
749
using Documenter, SignalTables, SignalTablesInterface_PyPlot makedocs( sitename = "SignalTables", authors = "Martin Otter (DLR-SR)", format = Documenter.HTML(prettyurls = false), pages = [ "Home" => "index.md", #"Getting Started" => "GettingStarted.md", "Examples" => [ "Examples/Plots.md", "Examples/FileIO.md", ], "Functions" => [ "Functions/OverviewOfFunctions.md", "Functions/Signals.md", "Functions/SignalTables.md", "Functions/PlotPackages.md", "Functions/Plots.md", ], "Internal" => [ "Internal/AbstractSignalTableInterface.md", "Internal/AbstractPlotInterface.md", # "internal/UtilityFunctions.md" ], ] )
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
348
module CSV_ReadFromFile using SignalTables import CSV file = joinpath(SignalTables.path, "examples", "fileIO", "Rotational_First.csv") println("\n... Read csv file \"$file\"") sigTable = CSV.File(file) println("\n... Show csv file as signal table") showInfo(sigTable) println("\ntime[1:10] = ", getSignal(sigTable, "time")[:values][1:10]) end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
171
module JLD_HDF5_WriteToFile using SignalTables using FileIO sigTable = getSignalTableExample("VariousTypes") save( File(format"JLD", "VariousTypes.jld"), sigTable) end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
238
module JSON_WriteToFile using SignalTables sigTable = getSignalTableExample("VariousTypes") writeSignalTable("VariousTypes_prettyPrint.json", sigTable; indent=2, log=true) writeSignalTable("VariousTypes_compact.json" , sigTable) end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
129
module JSON_WriteToString using SignalTables str = signalTableToJSON( getSignalTableExample("VariousTypes") ) println(str) end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
66
include("JSON_WriteToFile.jl") include("JSON_WriteToString.jl")
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
234
module ConstantSignals using SignalTables @usingPlotPackage sigTable = getSignalTableExample("ConstantSignals") plot(sigTable, [("phi_max", "i_max", "open"), ("matrix3[2,2]", "matrix2[1,2:3]"), "matrix1"], heading="Constants") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
175
module MissingValues using SignalTables @usingPlotPackage sigTable = getSignalTableExample("MissingValues") plot(sigTable, [("sigC", "load.r[2:3]"), ("sigB", "sigD")]) end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
204
module OneMatrixSignal using SignalTables @usingPlotPackage sigTable = getSignalTableExample("OneMatrixSignal") plot(sigTable, ["matrix", "matrix[2,3]", "matrix[1,2:3]"], heading="Matrix signals") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
234
module OneMatrixSignalWithMatrixUnits using SignalTables @usingPlotPackage sigTable = getSignalTableExample("OneMatrixSignalWithMatrixUnits") plot(sigTable, ["matrix", "matrix[2,3]", "matrix[1,2:3]"], heading="Matrix signals") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
162
module OneScalarSignal using SignalTables @usingPlotPackage sigTable = getSignalTableExample("OneScalarSignal") plot(sigTable, "phi", heading="sine(time)") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
178
module OneScalarSignalWithUnit using SignalTables @usingPlotPackage sigTable = getSignalTableExample("OneScalarSignalWithUnit") plot(sigTable, "phi", heading="Sine(time)") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
206
module OneVectorSignalWithUnit using SignalTables @usingPlotPackage sigTable = getSignalTableExample("OneVectorSignalWithUnit") plot(sigTable, ["r", "r[2]", "r[2:3]"], heading="Plot vector signals") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
209
module VariousTypes using SignalTables @usingPlotPackage sigTable = getSignalTableExample("VariousTypes") plot(sigTable, ["load.r", ("motor.w", "wm", "motor.w_c", "ref.clock")], heading="VariousTypes") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
267
include("OneScalarSignal.jl") include("OneScalarSignalWithUnit.jl") include("OneVectorSignalWithUnit.jl") include("OneMatrixSignal.jl") include("OneMatrixSignalWithMatrixUnits.jl") include("ConstantSignals.jl") include("MissingValues.jl") include("VariousTypes.jl")
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
7435
# License for this file: MIT (expat) # Copyright 2020-2022, DLR Institute of System Dynamics and Control # # This file is part of module SignalTables (is included by the PlotPackage_xxxMakie packages). """ 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 """ plot(signalTable, names; heading = "", grid = true, xAxis = nothing, figure = 1, prefix = "", reuse = false, maxLegend = 10, minXaxisTickLabels = false, MonteCarloAsArea = true) Generate **plots** of selected signals of a signal table using the plot package defined with [`@usePlotPackage`]@ref`(xxx)`. Possible values for `xxx`: `"GLMakie", "WGLMakie", "CairoMakie", "PyPlot", "SilentNoPlot"`). `signalTable` is an instance of a type that supports the [Abstract Signal Table Interface](@ref). Argument `names` defines the diagrams to be drawn and the signals 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 signals) 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 signal table (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 using SignalTables using Unitful # Generate "using xxx" statement # (where "xxx" is from a previous SignalTables.usePlotPackage("xxx")) @usingPlotPackage # 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 | | SilentNoPlot | Call is ignored | # Example ```julia using SignalTables @usingPlotPackage ... 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/users/explain/backends.html) (usually: png, pdf, jpg, tiff, svg, ps, eps) | | SilentNoPlot | 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 using SignalTables @usingPlotPackage ... 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 """ closeAllFigures() Close all figures. """ function closeAllFigures end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
5011
# License for this file: MIT (expat) # Copyright 2022, DLR Institute of System Dynamics and Control (DLR-SR) # Developer: Martin Otter, DLR-SR # # This file is part of module SignalTables import Tables """ isSignalTable(obj)::Bool Returns true, if `obj` is a signal table and supports the functions of the [Abstract Signal Table Interface](@ref). """ isSignalTable(obj) = Tables.istable(obj) && Tables.columnaccess(obj) """ getIndependentSignalNames(signalTable)::Vector{String} Returns the names of the independent signals (often: ["time"]) from signalTable. """ function getIndependentSignalNames(obj) if Tables.istable(obj) && Tables.columnaccess(obj) return [string(Tables.columnnames(obj)[1])] else error("getIndependentSignalNames(obj) is not supported for typeof(obj) = " * string(typeof(obj))) end end """ getSignalNames(signalTable; getVar=true, getPar=true, getMap=true)::Vector{String} Returns a string vector of the signal names that are present in signalTable (including independent signal names). - If getVar=true, Var(..) variables are included. - If getPar=true, Par(..) variables are included. - If getMap=true, Map(..) variables are included. """ function getSignalNames(obj; getVar=true, getPar=true, getMap=true) if Tables.istable(obj) && Tables.columnaccess(obj) if !getVar return String[] else return string.(Tables.columnnames(obj)) end else error("getSignalNames(obj) is not supported for typeof(obj) = " * string(typeof(obj))) end end """ getSignal(signalTable, name::String) Returns signal `name` from `signalTable` (that is a [`Var`](@ref), a [`Par`](@ref) or a [`Map`](@ref)). If `name` does not exist, an error is raised. """ function getSignal(obj, name::String) if Tables.istable(obj) && Tables.columnaccess(obj) return Var(values= Tables.getcolumn(obj, Symbol(name))) else error("getSignal(obj, \"$name\") is not supported for typeof(obj) = " * string(typeof(obj))) end end # ----------- Functions that have a default implementation ---------------------------------------- """ hasSignal(signalTable, name::String) Returns `true` if signal `name` is present in `signalTable`. """ function hasSignal(signalTable, name::String)::Bool hasName = true try sig = getSignal(signalTable, name) catch hasName = false end return hasName end """ getSignalInfo(signalTable, name::String) Returns signal, but [`Var`](@ref) or [`Par`](@ref)) without :values or :value but instead with :_eltypeOrType (eltype of the values if AbstractArray, otherwise typeof the values) and :_size (if defined on the values) If `name` does not exist, an error is raised. This function is useful if only the attributes of a signal are needed, but not their values (returning the attributes might be a *cheap* operation, whereas returning the values might be an *expensive* operation). """ function getSignalInfo(signalTable, name::String)::SymbolDictType signal = getSignal(signalTable,name) signal2 = copy(signal) delete!(signal2, :values) delete!(signal2, :value) _eltypeOrType = nothing _size = nothing type_available = false size_available = false if isVar(signal) if haskey(signal, :values) type_available = true try sig = signal[:values] _eltypeOrType = eltypeOrType(sig) _size = size(sig) size_available = true catch size_available = false end end else if haskey(signal, :value) type_available = true try sig = signal[:value] _eltypeOrType = eltypeOrType(sig) _size = size(sig) size_available = true catch size_available = false end end end if type_available signal2[:_eltypeOrType] = _eltypeOrType end if size_available signal2[:_size] = _size end return signal2 end """ getIndependentSignalsSize(signalTable)::Dims Returns the lengths of the independent signals as Dims. E.g. for one independent signal of length 5 return (5,), or for two independent signals of length 5 and 7 return (5,7). """ function getIndependentSignalsSize(signalTable)::Dims sigLength = Int[] for name in getIndependentSignalNames(signalTable) sigSize = getSignalInfo(signalTable,name)[:_size] if length(sigSize) != 1 error("Independent signal $name has not one dimension but has size = $sigSize") end push!(sigLength, sigSize[1]) end return ntuple(i -> sigLength[i], length(sigLength)) end """ getDefaultHeading(signalTable, name::String)::String Returns the default heading for a plot. """ getDefaultHeading(signalTable)::String = ""
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
5099
# # This file contains a function with a set of example signal tables # """ getSignalTableExample(signalTableName::String; logTitle=true, logShowInfo=true) Return an example signal table. """ function getSignalTableExample(signalTableName::String; logTitle=true, logShowInfo=true)::SignalTable if logTitle println("\n... $signalTableName (from SignalTables/src/ExampleSignalTables.jl)") end if signalTableName == "OneScalarSignal" t = range(0.0, stop=10.0, length=100) sigTable = SignalTable( "time" => Var(values = t, independent=true), "phi" => Var(values = sin.(t)) ) elseif signalTableName == "OneScalarSignalWithUnit" t = range(0.0, stop=10.0, length=100) sigTable = SignalTable( "time" => Var(values = t, unit="s", independent=true), "phi" => Var(values = sin.(t), unit="rad") ) elseif signalTableName == "OneVectorSignalWithUnit" t = range(0.0, stop=10.0, length=100) sigTable = SignalTable( "time" => Var(values = t, unit="s", independent=true), "r" => Var(values = [0.4*cos.(t) 0.5*sin.(t) 0.3*cos.(t)], unit="m"), ) elseif signalTableName == "OneMatrixSignal" t = range(0.0, stop=1.0, length=10) offset = Float64[11 12 13; 21 22 23] matrix = Array{Float64,3}(undef,length(t),2,3) for i = 1:length(t), j = 1:2, k=1:3 matrix[i,j,k] = offset[j,k] + 0.3*sin(t[i]) end sigTable = SignalTable( "time" => Var(values = t, independent=true), "matrix" => Var(values = matrix) ) elseif signalTableName == "OneMatrixSignalWithMatrixUnits" t = range(0.0, stop=1.0, length=10) offset = Float64[11 12 13; 21 22 23] matrix = Array{Float64,3}(undef,length(t),2,3) for i = 1:length(t), j = 1:2, k=1:3 matrix[i,j,k] = offset[j,k] + 0.3*sin(t[i]) end sigTable = SignalTable( "time" => Var(values = t, unit="s", independent=true), "matrix" => Var(values = matrix, unit=["m" "m/s" "m/s^2"; "rad" "rad/s" "rad/s^2"]) ) elseif signalTableName == "ConstantSignals" t = range(0.0, stop=1.0, length=5) matrix = Float64[11 12 13; 21 22 23] sigTable = SignalTable( "time" => Var(values = t, unit="s", independent=true), "phi_max" => Par(value = 1.1f0, unit="rad"), "i_max" => Par(value = 2), "open" => Par(value = true), "file" => Par(value = "filename.txt"), "matrix1" => Par(value = matrix), "matrix2" => Par(alias="matrix1", unit="m/s"), "matrix3" => Par(alias="matrix1", unit=["m" "m/s" "m/s^2"; "rad" "rad/s" "rad/s^2"]) ) elseif signalTableName == "MissingValues" time1 = 0.0 : 0.1 : 3.0 time2 = 3.0 : 0.1 : 11.0 time3 = 11.0 : 0.1 : 15 t = vcat(time1,time2,time3) sigC = vcat(fill(missing,length(time1)), 0.6*cos.(time2.+0.5), fill(missing,length(time3))) function sigD(t, time1, time2) sig = Vector{Union{Missing,Float64}}(undef, length(t)) j = 1 for i = length(time1)+1:length(time1)+length(time2) if j == 1 sig[i] = 0.5*cos(t[i]) end j = j > 3 ? 1 : j+1 end return sig end sigTable = SignalTable( "time" => Var(values=t, unit="s", independent=true), "load.r" => Var(values=0.4*[sin.(t) cos.(t) sin.(t)], unit="m"), "sigA" => Var(values=0.5*sin.(t), unit="m"), "sigB" => Var(values=1.1*sin.(t), unit="m/s"), "sigC" => Var(values=sigC, unit="N*m"), "sigD" => Var(values=sigD(t, time1, time2), unit="rad/s", variability="clocked", info="Motor angular velocity") ) elseif signalTableName == "VariousTypes" t = 0.0:0.1:0.5 sigTable = SignalTable( "_attributes" => Map(experiment=Map(stoptime=0.5, interval=0.01)), "time" => Var(values= t, unit="s", independent=true), "load.r" => Var(values= [sin.(t) cos.(t) sin.(t)], unit="m"), "motor.angle" => Var(values= sin.(t), unit="rad", state=true, der="motor.w"), "motor.w" => Var(values= cos.(t), unit="rad/s", state=true, start=1.0u"rad/s"), "motor.w_ref" => Var(values= 0.9*[sin.(t) cos.(t)], unit = ["rad", "1/s"], info="Reference angle and speed"), "wm" => Var(alias = "motor.w"), "ref.clock" => Var(values= [true, missing, missing, true, missing, missing], variability="clock"), "motor.w_c" => Var(values= [0.6, missing, missing, 0.8, missing, missing], variability="clocked", clock="ref.clock"), "motor.inertia" => Par(value = 0.02f0, unit="kg*m/s^2"), "motor.data" => Par(value = "resources/motorMap.json") ) else error("getSignalTableExample(\"$signalTableName\"): unknown name.") end if logShowInfo showInfo(sigTable) println() end return sigTable end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
1073
# License for this file: MIT (expat) # Copyright 2021, DLR Institute of System Dynamics and Control module NoPlot export plot, showFigure, saveFigure, closeFigure, closeAllFigures include("AbstractPlotInterface.jl") plot(signalTable, 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() = println("... closeAllFigures(): Call is ignored, because of usePlotPackage(\"NoPlot\").") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
5720
isinstalled(pkg::String) = any(x -> x.name == pkg && x.is_direct_dep, values(Pkg.dependencies())) const AvailablePlotPackages = ["GLMakie", "WGLMakie", "CairoMakie", "PyPlot", "SilentNoPlot"] const PlotPackagesStack = String[] """ @usingPlotPackage() Execute `using XXX`, where `XXX` is the Plot package that was activated with `usePlotPackage(plotPackage)`. """ macro usingPlotPackage() if haskey(ENV, "SignalTablesPlotPackage") PlotPackage = ENV["SignalTablesPlotPackage"] if !(PlotPackage in AvailablePlotPackages) @info "ENV[\"SignalTablesPlotPackage\"] = \"$PlotPackage\" is not supported!. Using \"SilentNoPlot\"." @goto USE_NO_PLOT elseif PlotPackage == "NoPlot" @goto USE_NO_PLOT elseif PlotPackage == "SilentNoPlot" expr = :( using SignalTables.SilentNoPlot ) return esc( expr ) else PlotPackage = Symbol("SignalTablesInterface_" * PlotPackage) expr = :(using $PlotPackage) println("$expr") return esc( :(using $PlotPackage) ) end elseif haskey(ENV, "MODIA_PLOT_PACKAGE") PlotPackage = ENV["MODIA_PLOT_PACKAGE"] if !(PlotPackage in AvailablePlotPackages) @info "ENV[\"MODIA_PLOT_PACKAGE\"] = \"$PlotPackage\" is not supported!. Using \"SilentNoPlot\"." @goto USE_NO_PLOT elseif PlotPackage == "NoPlot" @goto USE_NO_PLOT elseif PlotPackage == "SilentNoPlot" expr = :( using SignalTables.SilentNoPlot ) return esc( expr ) else PlotPackage = Symbol("SignalTablesInterface_" * PlotPackage) expr = :(using $PlotPackage) println("$expr") return esc( :(using $PlotPackage) ) end else @info "No plot package activated. Using \"SilentNoPlot\"." @goto USE_NO_PLOT end @label USE_NO_PLOT expr = :( using SignalTables.SilentNoPlot ) println("$expr") return esc( expr ) end """ usePlotPackage(plotPackage::String) Define the plot package that shall be used by command `@usingPlotPackage`. If a PlotPackage package is already defined, save it on an internal stack (can be reactivated with `usePreviousPlotPackage()`. Possible values for `plotPackage`: - `"PyPlot"` - `"GLMakie"` - `"WGLMakie"` - `"CairoMakie"` - `"SilentNoPlot"` # Example ```julia using SignalTables usePlotPackage("GLMakie") module MyTest using SignalTables @usingPlotPackage 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" newPlot = true if pushPreviousOnStack if haskey(ENV, "SignalTablesPlotPackage") push!(PlotPackagesStack, ENV["SignalTablesPlotPackage"]) elseif haskey(ENV, "MODIA_PLOT_PACKAGE") push!(PlotPackagesStack, ENV["MODIA_PLOT_PACKAGE"]) newPlot=false end end if plotPackage == "NoPlot" if newPlot ENV["SignalTablesPlotPackage"] = "NoPlot" else ENV["MODIA_PLOT_PACKAGE"] = "NoPlot" end else if newPlot ENV["SignalTablesPlotPackage"] = "SilentNoPlot" else ENV["MODIA_PLOT_PACKAGE"] = "SilentNoPlot" end end else plotPackageName = "SignalTablesInterface_" * plotPackage if plotPackage in AvailablePlotPackages # Check that plotPackage is defined in current environment if isinstalled(plotPackageName) newPlot = true if pushPreviousOnStack if haskey(ENV, "SignalTablesPlotPackage") push!(PlotPackagesStack, ENV["SignalTablesPlotPackage"]) elseif haskey(ENV, "MODIA_PLOT_PACKAGE") push!(PlotPackagesStack, ENV["MODIA_PLOT_PACKAGE"]) newPlot=false end end if newPlot ENV["SignalTablesPlotPackage"] = plotPackage else ENV["MODIA_PLOT_PACKAGE"] = plotPackage end 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 $AvailablePlotPackages." success = false end end return success end """ usePreviousPlotPackage() Pop the last saved PlotPackage package from an internal stack and call `usePlotPackage(<popped PlotPackage package>)`. """ function usePreviousPlotPackage()::Bool if length(PlotPackagesStack) > 0 plotPackage = pop!(PlotPackagesStack) usePlotPackage(plotPackage, pushPreviousOnStack=false) end return true 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, "SignalTablesPlotPackage") ? ENV["SignalTablesPlotPackage"] : (haskey(ENV, "MODIA_PLOT_PACKAGE") ? ENV["MODIA_PLOT_PACKAGE"] : "" )
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
10956
""" sigTable = SignalTable(args...) Returns a new SignalTable dictionary. Arguments `args...` are dictionary pairs where `values` must be [`Var`](@ref)(...) and/or [`Par`](@ref)(...) and/or [`Map`](@ref)(...). Example: The *first* argument must define the *independent* signal, that is, `Var(values=..., independent=true), ...` and `values` must be an `AbstractVector`. Further added signals with a `:values` key, must have the same first dimension as the independent signal. Most dictionary operations can be applied on `sigTable`, as well as all functions of [Overview of Functions](@ref). # Examples ```julia using SignalTables using Unitful t = 0.0:0.1:0.5 sigTable = SignalTable( "time" => Var(values= t, unit="s", independent=true), "load.r" => Var(values= [sin.(t) cos.(t) sin.(t)], unit="m"), "motor.angle" => Var(values= sin.(t), unit="rad", state=true, der="motor.w"), "motor.w" => Var(values= cos.(t), unit="rad/s"), "motor.w_ref" => Var(values= 0.9*[sin.(t) cos.(t)], unit = ["rad", "1/s"], info="Reference angle and speed"), "wm" => Var(alias = "motor.w"), "ref.clock" => Var(values= [true, missing, missing, true, missing, missing], variability="clock"), "motor.w_c" => Var(values= [0.8, missing, missing, 1.5, missing, missing], variability="clocked", clock="ref.clock"), "motor.inertia"=> Par(value = 0.02f0, unit="kg*m/s^2"), "motor.data" => Par(value = "resources/motorMap.json"), "attributes" => Map(experiment=Map(stoptime=0.5, interval=0.01)) ) signalInfo(sigTable) ``` This results in the following output: ```julia name unit size eltypeOrType kind attributes ───────────────────────────────────────────────────────────────────────────────────────────────────────── time "s" [6] Float64 Var independent=true load.r "m" [6,3] Float64 Var motor.angle "rad" [6] Float64 Var state=true, der="motor.w" motor.w "rad/s" [6] Float64 Var motor.w_ref ["rad", "1/s"] [6,2] Float64 Var info="Reference angle and speed" wm "rad/s" [6] Float64 Var alias="motor.w" ref.clock [6] Union{Missing,Bool} Var variability="clock" motor.w_c [6] Union{Missing,Float64} Var variability="clocked", clock="ref.clock" motor.inertia "kg*m/s^2" Float32 Par motor.data String Par attributes Map experiment=Map(stoptime=0.5, interval=0.01) ``` The command `show(IOContext(stdout, :compact => true), sigTable)` results in the following output: ```julia SignalTable( "time" => Var(values=0.0:0.1:0.5, unit="s", independent=true), "load.r" => Var(values=[0.0 1.0 0.0; 0.0998334 0.995004 0.0998334; 0.198669 0.980067 0.198669; 0.29552 0.955336 0.29552; 0.389418 0.921061 0.389418; 0.479426 0.877583 0.479426], unit="m"), "motor.angle" => Var(values=[0.0, 0.0998334, 0.198669, 0.29552, 0.389418, 0.479426], unit="rad", state=true. der="motor.w"), "motor.w" => Var(values=[1.0, 0.995004, 0.980067, 0.955336, 0.921061, 0.877583], unit="rad/s"), "motor.w_ref" => Var(values=[0.0 0.9; 0.0898501 0.895504; 0.178802 0.88206; 0.265968 0.859803; 0.350477 0.828955; 0.431483 0.789824], unit=["rad", "1/s"], info="Reference angle and speed"), "wm" => Var(values=[1.0, 0.995004, 0.980067, 0.955336, 0.921061, 0.877583], unit="rad/s", alias="motor.w"), "ref.clock" => Var(values=Union{Missing, Bool}[true, missing, missing, true, missing, missing], variability="clock"), "ref.trigger" => Var(values=Union{Missing, Bool}[missing, missing, true, missing, true, true], variability="trigger"), "motor.w_c" => Var(values=Union{Missing, Float64}[0.8, missing, missing, 1.5, missing, missing], variability="clocked", clock="ref.clock"), "motor.inertia" => Par(value=0.02, unit="kg*m/s^2"), "motor.data" => Par(value="resources/motorMap.json"), "attributes" => Map(experiment=Map(stoptime=0.5, interval=0.01)), ) ``` """ struct SignalTable <: AbstractDict{String,Any} dict::StringDictType independendentSignalNames::Vector{String} independentSignalsSize::NTuple function SignalTable(args...) dict = new_signal_table() independendentSignalNames = String[] independentSignalLengths = Int[] k = 0 for (key, sig) in args if !isSignal(sig) error("SignalTable(\"$key\" => signal, ...): The added signal is neither a Var(..) nor a Par(..) nor a Map(...)\ntypeof(signal) = $(typeof(sig))!") end if isVar(sig) if haskey(sig, :values) sig_values = sig[:values] if !(typeof(sig_values) <: AbstractArray) error("SignalTable(\"$key\" => signal, ...): typeof(signal[:values]) = $(typeof(sig_values)) but must be an `<: AbstractArray`!") end if get(sig, :independent, false) k += 1 ndims_sig = ndims(sig_values) if ndims_sig != 1 error("SignalTable(.., $key => ..): Independent signal $key must have one dimension, but has $ndims_sig dimensions.") end push!(independendentSignalNames, key) push!(independentSignalLengths, length(sig_values)) else for (i,val) in enumerate(independentSignalLengths) if size(sig_values, i) != val error("SignalTable(\"$key\" => signal, ...): size(signal[:values],$i) = $(size(sig_values,i)) but must be $val (= length of independent signal)!") end end end else # Needs not have :values, e.g. alias # error("SignalTable(\"$key\" => signal, ...) is a Var(..) and has no key :values which is required!") end if haskey(sig, :alias) aliasName = sig[:alias] if haskey(sig,:values) error("SignalTable(\"$key\" => Var(values=.., alias=\"$aliasName\"...): not allowed to define values and alias together.") elseif !haskey(dict, aliasName) error("SignalTable(\"$key\" => Var(alias=\"$aliasName\"...): referenced signal does not exist.") end sigAlias = dict[aliasName] sig = merge(sigAlias,sig) end elseif isPar(sig) if haskey(sig, :alias) aliasName = sig[:alias] if haskey(sig,:value) error("SignalTable(\"$key\" => Par(values=.., alias=\"$aliasName\"...): not allowed to define values and alias together.") elseif !haskey(dict, aliasName) error("SignalTable(\"$key\" => Par(alias=\"$aliasName\"...): referenced signal does not exist.") end sigAlias = dict[aliasName] sig = merge(sigAlias,sig) end end dict[key] = sig end new(dict, independendentSignalNames, ntuple(i -> independentSignalLengths[i], length(independentSignalLengths))) end end Base.convert(::Type{StringDictType}, sig::SignalTable) = sig.dict Base.length(sigTable::SignalTable) = length(sigTable.dict) Base.iterate(sigTable::SignalTable) = Base.iterate(sigTable.dict) Base.iterate(sigTable::SignalTable, iter) = Base.iterate(sigTable.dict, iter) Base.haskey(signalTable::SignalTable, key::String) = Base.haskey(signalTable.dict, key) Base.getindex(signalTable::SignalTable, key...) = Base.getindex(signalTable.dict, key...) Base.get(signalTable::SignalTable, key::String, default) = Base.get(signalTable.dict, key, default) Base.get(f::Function, signalTable::SignalTable, key::String) = Base.get(f, signalTable.dict, key) Base.get!(signalTable::SignalTable, key::String, default) = Base.get!(signalTable.dict, key, default) Base.get!(f::Function, signalTable::SignalTable, key::String) = Base.get!(f, signalTable.dict, key) Base.keys(signalTable::SignalTable) = Base.keys(signalTable.dict) Base.values(signalTable::SignalTable) = Base.values(signalTable.dict) Base.setindex!(signalTable::SignalTable, value, key...) = Base.setindex!(signalTable.dict, value, key...) Base.getproperty(signalTable::SignalTable, key::String) = signalTable[key] Base.pop!(signalTable::SignalTable) = Base.pop!(signalTable.dict) Base.delete!(signalTable::SignalTable, key::String) = Base.delete!(signalTable.dict, key) function Base.show(io::IO, sigTable::SignalTable) print(io, "SignalTable(\n") for (key,sig) in sigTable if key != "_class" Base.print(io, " ") Base.show(io, key) Base.print(io, " => ") showSignal(io, sig) print(io, ",\n") end end println(io," )") end # Implementation of AbstractSignalTableInterface isSignalTable( sigTable::SignalTable) = true getIndependentSignalNames(sigTable::SignalTable) = sigTable.independendentSignalNames getIndependentSignalsSize(sigTable::SignalTable) = sigTable.independentSignalsSize getSignal( sigTable::SignalTable, name::String) = sigTable[name] hasSignal( sigTable::SignalTable, name::String) = haskey(sigTable, name) function getSignalNames(sigTable::SignalTable; getVar=true, getPar=true, getMap=true) if getVar && getPar && getMap sigNames = setdiff(String.(keys(sigTable)), ["_class"]) else sigNames = String[] for (key,value) in sigTable.dict if getVar && isVar(value) || getPar && isPar(value) || getMap && isMap(value) push!(sigNames, key) end end end return sigNames end function getDefaultHeading(sigTable::SignalTable)::String attr = get(sigTable, "attributes", "") if attr == "" return "" else return get(attr, :plotHeading, "") end end """ toSignalTable(signalTable)::SignalTable Returns a signalTable as instance of [`SignalTable`](@ref). """ function toSignalTable(sigTable)::SignalTable if !isSignalTable(sigTable) error("toSignalTable(obj): obj::$(typeof(sigTable)) is no signal table.") end sigTable2 = SignalTable() for name in getSignalNames(sigTable) sigTable2[name] = getSignal(sigTable,name) end return sigTable2 end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
31047
""" compactPaths(str::String) Returns a compacted string, where all paths with dots are reduced to their leaf name. Example: compactPaths("MonteCarloMeasurements.Particles") is reduced to "Particles". """ function compactPaths(str::String) i1 = findfirst("{", str) if isnothing(i1) i2 = findlast(".", str) else i2 = findprev(".", str, i1[1]) end if !isnothing(i2) && length(str) > i2[1] str = str[i2[1]+1:end] end str = replace(str, " " => "") # remove blanks return str end """ dictToString(dict:AbstractDict) """ function dictToString(dict::AbstractDict)::String io = IOBuffer() str = "" first = true for (key,value) in dict if first first = false else show(io, ", ") end print(io, key, "=") show(io, value) end str = String(take!(io)) return str end """ new_signal_table(args...)::OrderedDict{String,Any} Returns a new signal table, that is `OrderedDict{String,Any}("_class" => :SignalTable, args...)` """ new_signal_table(args...) = OrderedDict{String,Any}("_class" => :SignalTable, args...) """ getValues(signalTable, name) Returns the *values* of a [`Var`](@ref) signal name from signalTable. """ getValues(signalTable, name::String) = getSignal(signalTable, name)[:values] """ getValue(signalTable, name) Returns the *value* of a [`Par`](@ref) signal name from signalTable. """ getValue( signalTable, name::String) = getSignal(signalTable, name)[:value] """ getValuesWithUnit(signalTable, name) Returns the *values* of a [`Var`](@ref) signal name from signalTable including its unit. """ getValuesWithUnit(signalTable, name::String) = begin sig = getSignal(signalTable, name) sigUnit = get(sig, :unit, "") sigVal = sig[:values] if typeof(sigUnit) <: AbstractArray error("getValuesWithUnit(signalTable, $name) is not yet supported for unit arrays (= $sigUnit)") elseif sigUnit != "" sigVal = sigVal*uparse(sigUnit) end return sigVal end """ getValueWithUnit(signalTable, name) Returns the *value* of a [`Par`](@ref) signal name from signalTable including its unit. """ getValueWithUnit(signalTable, name::String) = begin sig = getSignal(signalTable, name) sigUnit = get(sig, :unit, "") sigVal = sig[:value] if typeof(sigUnit) <: AbstractArray error("getValueWithUnit(signalTable, $name) is not yet supported for unit arrays (= $sigUnit)") elseif sigUnit != "" sigVal = sigVal*uparse(sigUnit) end end const doNotShowAttributes = [:_class, :_eltypeOrType, :_size, :unit] function showMapValue(iostr,mapValue)::Nothing print(iostr, "Map(") first = true for (key,val) in mapValue if key in doNotShowAttributes continue end if first first = false else print(iostr, ", ") end print(iostr, key, "=") if isMap(val) showMap(iostr, val) end show(iostr,val) end print(iostr, ")") return nothing end """ showInfo([io::IO=stdout,] signalTable; sorted=false, showVar=true, showPar=true, showMap=true, showAttributes=true) Writes info about a signal table to the output stream. The keyword arguments define what information shall be printed or whether the names shall be sorted or presented in definition order. # Example ```julia using SignalTables using Unitful t = 0.0:0.1:0.5 sigTable = SignalTable( "time" => Var(values= t, unit="s", independent=true), "load.r" => Var(values= [sin.(t) cos.(t) sin.(t)], unit="m"), "motor.angle" => Var(values= sin.(t), unit="rad", state=true, der="motor.w"), "motor.w" => Var(values= cos.(t), unit="rad/s"), "motor.w_ref" => Var(values= 0.9*[sin.(t) cos.(t)], unit = ["rad", "1/s"], info="Reference angle and speed"), "wm" => Var(alias = "motor.w"), "ref.clock" => Var(values= [true, missing, missing, true, missing, missing], variability="clock"), "motor.w_c" => Var(values= [0.8, missing, missing, 1.5, missing, missing], variability="clocked", clock="ref.clock"), "motor.inertia"=> Par(value = 0.02f0, unit="kg*m/s^2"), "motor.data" => Par(value = "resources/motorMap.json"), "attributes" => Map(experiment=Map(stoptime=0.5, interval=0.01)) ) signalInfo(sigTable) ``` results in the following output ```julia name unit size eltypeOrType kind attributes ─────────────────────────────────────────────────────────────────────────────────────────────────────── time "s" [6] Float64 Var independent=true load.r "m" [6,3] Float64 Var motor.angle "rad" [6] Float64 Var state=true, der="motor.w" motor.w "rad/s" [6] Float64 Var motor.w_ref ["rad", "1/s"] [6,2] Float64 Var info="Reference angle and speed" wm "rad/s" [6] Float64 Var alias="motor.w" ref.clock [6] Union{Missing,Bool} Var variability="clock" motor.w_c [6] Union{Missing,Float64} Var variability="clocked", clock="ref.clock" motor.inertia "kg*m/s^2" Float32 Par motor.data String Par attributes Map experiment=Map(stoptime=0.5, interval=0.01) ``` """ function showInfo(io::IO, signalTable; sorted=false, showVar=true, showPar=true, showMap=true, showAttributes=true)::Nothing if isnothing(signalTable) @info "The call of showInfo(signalTable) is ignored, since the argument is nothing." return end name2 = String[] unit2 = String[] size2 = String[] eltypeOrType2 = String[] kind2 = String[] attr2 = String[] sigNames = getSignalNames(signalTable, getVar=showVar, getPar=showPar, getMap=showMap) if sorted sigNames = sort(sigNames) end iostr = IOBuffer() for name in sigNames signal = getSignalInfo(signalTable, name) kind = isVar(signal) ? "Var" : (isPar(signal) ? "Par" : "Map") if showVar && kind == "Var" || showPar && kind == "Par" || showMap && kind == "Map" first = true if kind == "Par" val = getValue(signalTable, name) if !ismutable(val) first = false print(iostr, "=") show(iostr, val) end end if showAttributes for (key,val) in signal if key in doNotShowAttributes continue end if first first = false else print(iostr, ", ") end print(iostr, key, "=") if isMap(val) showMapValue(iostr, val) else show(iostr, val) end end attr = String(take!(iostr)) end independent = get(signal, :independent, false) #println("$name: _type = ", get(signal, :_type, "notDefined")) valBaseType = string( get(signal, :_eltypeOrType, "") ) valBaseType = compactPaths(valBaseType) valSize = string( get(signal, :_size, "") ) valSize = replace(valSize, "()" => "", " " => "", ",)" => "]", "(" => "[", ")" => "]") valUnit = get(signal, :unit, "") if typeof(valUnit) <: AbstractString if valUnit != "" valUnit = "\"$valUnit\"" end else show(iostr, valUnit) valUnit = String(take!(iostr)) #valUnit = replace(valUnit, "; " => ";\n") end push!(name2 , name) push!(unit2 , valUnit) push!(size2 , valSize) push!(eltypeOrType2, valBaseType) push!(kind2 , kind) if showAttributes push!(attr2, attr) end end end if showAttributes infoTable = DataFrames.DataFrame(name=name2, unit=unit2, size=size2, eltypeOrType=eltypeOrType2, kind=kind2, attributes=attr2) else infoTable = DataFrames.DataFrame(name=name2, unit=unit2, size=size2, eltypeOrType=eltypeOrType2, kind=kind2) end show(io, infoTable, show_row_number=false, summary=false, allcols=true, eltypes=false, truncate=50) # rowlabel=Symbol("#") println(io) return nothing end showInfo(signalTable; kwargs...) = showInfo(stdout, signalTable; kwargs...) const TypesForPlotting = [Float64, Float32, Int] nameWithUnit(name::String, unit::String) = unit == "" ? name : string(name, " [", unit, "]") function nameWithArrayUnit(unit, indicesAsVector::Vector{Int})::String if unit == "" return "]" elseif typeof(unit) == String return string( "] [", unit, "]") else elementIndicesAsTuple = Tuple(i for i in indicesAsVector) elementUnit = unit[elementIndicesAsTuple...] return string("] [", elementUnit, "]") end end #TargetElType(::Type{T}) where {T} = T #TargetElType(::Type{Measurements.Measurement{T}}) where {T} = T #TargetElType(::Type{MonteCarloMeasurements.Particles{T,N}}) where {T,N} = T #TargetElType(::Type{MonteCarloMeasurements.StaticParticles{T,N}}) where {T,N} = T #= function eltypeOrTypeWithMeasurements(obj) if typeof(obj) <: AbstractArray obj1 = obj[1] if eltype(obj1) <: Real println("... is Real") Tobj1 = typeof(obj1) if hasfield(Tobj1, :particles) # MonteCarloMeasurements btype = eltype(obj1.particles) elseif hasfield(Tobj1, :val) && hasfield(Tobj1, :err) # Measurements btype = typeof(obj1.val) else btype = eltypeOrType(obj) end end else btype = eltypeOrType(obj) end #catch # btype = eltypeOrType(obj) #end return btype end function eltypeOrTypeWithMeasurements(obj) obj_eltype = eltype(obj) if obj_eltype <: Real if hasfield(obj_eltype, :particles) # MonteCarloMeasurements btype = eltype(obj1.particles) elseif hasfield(Tobj1, :val) && hasfield(Tobj1, :err) # Measurements btype = typeof(obj1.val) else btype = eltypeOrType(obj) end end else btype = eltypeOrType(obj) end #catch # btype = eltypeOrType(obj) #end return btype end =# function eltypeOrTypeWithMeasurements(obj) obj1 = typeof(obj) <: AbstractArray ? obj[1] : obj Tobj1 = typeof(obj1) if hasfield(Tobj1, :particles) # MonteCarloMeasurements btype = eltype(obj1.particles) elseif hasfield(Tobj1, :val) && hasfield(Tobj1, :err) # Measurements btype = typeof(obj1.val) else btype = eltypeOrType(obj) end return btype end function getValuesFromPar(signal, len::Int) sigValue = signal[:value] if typeof(sigValue) <: Number || typeof(sigValue) <: AbstractArray sigSize = (len,size(sigValue)...) sigValues2 = Array{eltype(sigValue),ndims(sigValue)+1}(undef, sigSize) if ndims(sigValue) == 0 for i = 1:len sigValues2[i] = sigValue end else nsig = prod(sigSize[i] for i=2:length(sigSize)) sig1 = reshape(sigValues2, (len, nsig)) sig2 = reshape(sigValue, nsig) for i = 1:len, j=1:nsig sig1[i,j] = sig2[j] end sigValues2 = reshape(sig1, sigSize) end return sigValues2 end return nothing end """ signal = getFlattenedSignal(signalTable, name; missingToNaN = true, targetInt = Int, targetFloat = Float64) Returns a copy of a signal where the *flattened* and *converted* values (e.g.: missing -> NaN) are stored as `signal[:flattenedValues]` and the legend as `signal[:legend]`. A flattened signal can be, for example, used for traditional plot functions or for traditional tables. `signal[:flattenedValues]` is a reshape of values into a vector or a matrix with optionally the following transformations: - `name` can be a signal name with or without array range indices (for example `name = "a.b.c[2,3:5]"`). - If `missingToNaN=true`, then missing values are replaced by NaN values. If NaN does not exist in the corresponding type, the values are first converted to `targetFloat`. - If targetInt is not nothing, Int-types are converted to targetInt - If targetFloat is not nothing, Float-types are converted to targetFloat - collect(..) is performed on the result. `flattenedSignal[:legend]` is a vector of strings that provides a description for every array column (e.g. if `"name=a.b.c[2,3:5]", unit="m/s"`, then `legend = ["a.b.c[2,3] [m/s]", "a.b.c[2,3] [m/s]", "a.b.c[2,5] [m/s]"]`. If the required transformation is not possible, a warning message is printed and `nothing` is returned. As a special case, if signal[:values] is a vector or signal[:value] is a scalar and an element of values or value is of type `Measurements{targetFloat}` or `MonteCarloMeasurements{targetFloat}`, then the signal is not transformed, so signal[:flattenedValues] = signal[:values]. """ function getFlattenedSignal(signalTable, name::String; missingToNaN = true, targetInt = Int, targetFloat = Float64) independentSignalsSize = getIndependentSignalsSize(signalTable) if length(independentSignalsSize) != 1 ni = length(independentSignalsSize) @info "getFlattenedSignal(.., \"$name\") supported for one independent signal,\nbut number of independent signals = $(ni)! Signal is ignored." return nothing end lenx = independentSignalsSize[1] sigPresent = false if hasSignal(signalTable,name) # name is a signal name without range signal = getSignal(signalTable,name) if isVar(signal) && haskey(signal, :values) sigValues = signal[:values] elseif isPar(signal) && haskey(signal, :value) sigValues = getValuesFromPar(signal, lenx) if isnothing(sigValues) @goto ERROR end else @goto ERROR end dims = size(sigValues) if dims[1] > 0 sigPresent = true if length(dims) > 2 # Reshape to a matrix sigValues = reshape(sigValues, dims[1], prod(dims[i] for i=2:length(dims))) end # Collect information for legend arrayName = name sigUnit = get(signal, :unit, "") if length(dims) == 1 arrayIndices = () nScalarSignals = 1 else varDims = dims[2:end] arrayIndices = Tuple(1:Int(ni) for ni in varDims) nScalarSignals = prod(i for i in varDims) 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(signalTable, arrayName) signal = getSignal(signalTable,arrayName) if isVar(signal) && haskey(signal, :values) sigValues = signal[:values] elseif isPar(signal) && haskey(signal, :value) sigValues = getValuesFromPar(signal, lenx) if isnothing(sigValues) @goto ERROR end else @goto ERROR end dims = size(sigValues) if dims[1] > 0 sigPresent = true # Determine indices as tuple arrayIndices = () try arrayIndices = eval( Meta.parse( "(" * indices * ",)" ) ) catch @goto ERROR end # Extract sub-array and collect info for legend sigValues = getindex(sigValues, (:, arrayIndices...)...) sigUnit = get(signal, :unit, "") dims = size(sigValues) nScalarSignals = length(dims) == 1 ? 1 : prod(i for i in dims[2:end]) if length(dims) > 2 # Reshape to a matrix sigValues = reshape(sigValues, dims[1], nScalarSignals) end end end end end end if !sigPresent @goto ERROR end # Transform sigValues sigElType = eltype(sigValues) eltypeOrType2 = eltypeOrTypeWithMeasurements(sigValues) hasMissing = isa(missing, sigElType) if (!isnothing(targetInt) && eltypeOrType2 == targetInt || !isnothing(targetFloat) && eltypeOrType2 == targetFloat) && !(missingToNaN && hasMissing) # Signal need not be converted - do nothing elseif hasMissing && missingToNaN && !isnothing(targetFloat) # sig contains missing or nothing - convert to targetFloat and replace missing by NaN sigNaN = convert(targetFloat, NaN) sigValues2 = Array{targetFloat, ndims(sigValues)}(undef, size(sigValues)) try for i = 1:length(sigValues) sigValues2[i] = ismissing(sigValues[i]) ? sigNaN : convert(targetFloat, sigValues[i]) end catch # Cannot be converted @info "\"$name\" is ignored, because its element type = $sigElType\nwhich cannot be converted to targetFloat = $targetFloat." return nothing end sigValues = sigValues2 elseif !hasMissing && sigElType <: Integer && !isnothing(targetInt) # Transform to targetInt sigValues2 = Array{targetInt, ndims(sigValues)}(undef, size(sigValues)) for i = 1:length(sigValues) sigValues2[i] = convert(targetInt, sigValues[i]) end sigValues = sigValues2 elseif !hasMissing && sigElType <: Real && !isnothing(targetFloat) # Transform to targetFloat sigValues2 = Array{targetFloat, ndims(sigValues)}(undef, size(sigValues)) for i = 1:length(sigValues) sigValues2[i] = convert(targetFloat, sigValues[i]) end sigValues = sigValues2 else @goto ERROR end # Build legend if arrayIndices == () # sig is a scalar variable legend = String[nameWithUnit(name, sigUnit)] else # sig is an array variable legend = [arrayName * "[" for i = 1:nScalarSignals] legendIndices = Vector{Vector{Int}}(undef, nScalarSignals) for i = 1:nScalarSignals legendIndices[i] = Int[] end i = 1 sizeLength = Int[] for j1 in eachindex(arrayIndices) push!(sizeLength, length(arrayIndices[j1])) i = 1 if j1 == 1 for j2 in 1:div(nScalarSignals, sizeLength[1]) for j3 in arrayIndices[1] legend[i] *= string(j3) push!(legendIndices[i], j3) # println("i = $i, j2 = $j2, j3 = $j3, legend[$i] = ", legend[i], ", legendIndices[$i] = ", legendIndices[i]) i += 1 end end else ncum = prod( sizeLength[1:j1-1] ) for j2 in arrayIndices[j1] for j3 = 1:ncum legend[i] *= "," * string(j2) push!(legendIndices[i], j2) # println("i = $i, j2 = $j2, j3 = $j3, legend[$i] = ", legend[i], ", legendIndices[$i] = ", legendIndices[i]) i += 1 end end end end for i = 1:nScalarSignals legend[i] *= nameWithArrayUnit(sigUnit, legendIndices[i]) end end signal = copy(signal) signal[:flattenedValues] = collect(sigValues) signal[:legend] = legend return signal @label ERROR @info "\"$name\" is ignored, because it is not defined or is not correct or has no values." return nothing end # Deprecated (provided to use the plot functions without any changes @enum SignalType Independent=1 Continuous=2 Clocked=3 function signalValuesForLinePlots(sigTable, name) signal = getFlattenedSignal(sigTable, name) if isnothing(signal) return (nothing, nothing, nothing) end sig = signal[:flattenedValues] sigLegend = signal[:legend] variability = get(signal, :variability, "") if variability == "independent" sigKind = Independent elseif variability == "clocked" || variability == "clock" || variability == "trigger" || get(signal, "interpolation", "") == "none" sigKind = Clocked else sigKind = Continuous end return (sig, sigLegend, sigKind) end function getPlotSignal(sigTable, ysigName::AbstractString; xsigName=nothing) (ysig, ysigLegend, ysigKind) = signalValuesForLinePlots(sigTable, ysigName) if isnothing(ysig) @goto ERROR end if isnothing(xsigName) xNames = getIndependentSignalNames(sigTable) if length(xNames) != 1 error("Plotting requires currently exactly one independent signal. However, getIndependentSignalNames = $getIndependentSignalNames") end xsigName2 = xNames[1] else xsigName2 = xsigName end (xsig, xsigLegend, xsigKind) = signalValuesForLinePlots(sigTable, xsigName2) if isnothing(xsig) @goto ERROR end # Check x-axis signal if ndims(xsig) != 1 @info "\"$xsigName\" does not characterize a scalar variable as needed for the x-axis." @goto ERROR #elseif !(typeof(xsigValue) <: Real || # typeof(xsigValue) <: Measurements.Measurement || # typeof(xsigValue) <: MonteCarloMeasurements.StaticParticles || # typeof(xsigValue) <: MonteCarloMeasurements.Particles ) # @info "\"$xsigName\" is of type " * string(typeof(xsigValue)) * " which is not supported for the x-axis." # @goto ERROR end return (xsig, xsigLegend[1], ysig, ysigLegend, ysigKind) @label ERROR return (nothing, nothing, nothing, nothing, nothing) end """ getHeading(signalTable, heading) Return `heading` if no empty string. Otherwise, return `defaultHeading(signalTable)`. """ getHeading(signalTable, heading::AbstractString) = heading != "" ? heading : getDefaultHeading(signalTable) # ------------------------------- File IO ------------------------------------------------------ # # Encoding and decoding Modia signal tables as JSON. # # Based on Modia/src/JSONModel.jl developed by Hilding Elmqvist # License: MIT (expat) import JSON const TypesWithoutEncoding = Set([Float64, Int64, Bool, String, Symbol]) appendNames(name1, name2) = name1 == "" ? name2 : name1 * "." * string(name2) """ jsigDict = encodeSignalTable(signalTable; signalNames = nothing) Encodes a SignalTable suitable to convert to JSON format. If a keyword signalNames with a vector of strings is provided, then only the corresponding signals are encoded. """ function encodeSignalTable(signalTable; signalNames=nothing, log=false) if isSignalTable(signalTable) jdict = OrderedDict{String,Any}("_class" => "SignalTable", "_classVersion" => version_SignalTable_JSON) if isnothing(signalNames) signalNames = getSignalNames(signalTable) end for name in signalNames signal = getSignal(signalTable, name) if haskey(signal, :alias) signal = copy(signal) delete!(signal, :values) delete!(signal, :value) end encodedSignal = encodeSignalTableElement(name, signal, log=log) if !isnothing(encodedSignal) jdict[name] = encodedSignal end end return jdict else error("encodeSignalTable(signalTable, ...): signalTable::$(typeof(signalTable)) is no signal table.") end end arrayElementBaseType(::Type{T}) where {T} = T arrayElementBaseType(::Type{Array{T,N}}) where {T,N} = arrayElementBaseType(T) arrayElementBaseType(::Type{Union{Missing,T}}) where {T} = T arrayElementBaseType(A::Type{<:AbstractArray}) = arrayElementBaseType(eltype(A)) """ jsigDict = encodeSignalTableElement(path, signalTableElement; log=false) Encodes a signal table element suitable to convert to JSON format. """ function encodeSignalTableElement(path, element; log=false) if isSignal(element) if isVar(element) jdict = OrderedDict{String,Any}("_class" => "Var") elseif isPar(element) jdict = OrderedDict{String,Any}("_class" => "Par") else jdict = OrderedDict{String,Any}("_class" => "Map") end available = false for (key,val) in element if key != :_class encodedSignal = encodeSignalTableElement(appendNames(path,key),val, log=log) if !isnothing(encodedSignal) available = true jdict[string(key)] = encodedSignal end end end if available return jdict else return nothing end else elementType = typeof(element) if elementType <: AbstractArray && (arrayElementBaseType(elementType) <: Number || arrayElementBaseType(elementType) <: String) if ndims(element) == 1 && arrayElementBaseType(elementType) in TypesWithoutEncoding return element else elunit = unitAsParseableString(element) if elunit == "" if ndims(element) == 1 jdict = OrderedDict{String,Any}("_class" => "Array", "eltype" => replace(string(eltype(element)), " " => ""), "size" => Int[i for i in size(element)], "values" => element ) else jdict = OrderedDict{String,Any}("_class" => "Array", "eltype" => replace(string(eltype(element)), " " => ""), "size" => Int[i for i in size(element)], "layout" => "column-major", "values" => reshape(element, length(element)) ) end else element = ustrip.(element) jdict = OrderedDict{String,Any}("_class" => "Array", "unit" => elunit, "eltype" => replace(string(eltype(element)), " " => ""), "size" => Int[i for i in size(element)], "layout" => "column-major", "values" => reshape(element, length(element))) end return jdict end elseif elementType in TypesWithoutEncoding return element elseif elementType <: Number elunit = unitAsParseableString(element) if elunit == "" jdict = OrderedDict{String,Any}("_class" => "Number", "type" => replace(string(typeof(element)), " " => ""), "value" => element) else element = ustrip.(element) jdict = OrderedDict{String,Any}("_class" => "Number", "unit" => elunit, "type" => replace(string(typeof(element)), " " => ""), "value" => element) end return jdict else @info "$path::$(typeof(element)) is ignored, because mapping to JSON not known" return nothing end end end """ json = signalTableToJSON(signalTable; signalNames = nothing) Returns a JSON string representation of signalTable If keyword signalNames with a Vector of strings is provided, then a signal table with the corresponding signals are returned as JSON string. """ function signalTableToJSON(signalTable; signalNames = nothing, log=false)::String jsignalTable = encodeSignalTable(signalTable; signalNames=signalNames, log=log) return JSON.json(jsignalTable) end """ writeSignalTable(filename::String, signalTable; signalNames=nothing, indent=nothing, log=false) Write signalTable in JSON format on file `filename`. If keyword signalNames with a Vector of strings is provided, then a signal table with the corresponding signals are stored on file. If indent=<number> is given, then <number> indentation is used (otherwise, compact representation) """ function writeSignalTable(filename::String, signalTable; signalNames = nothing, indent=nothing, log=false)::Nothing file = joinpath(pwd(), filename) if log println(" Write signalTable in JSON format on file \"$file\"") end jsignalTable = encodeSignalTable(signalTable; signalNames=signalNames, log=log) open(file, "w") do io JSON.print(io, jsignalTable, indent) end return nothing end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
1208
# Signal table interface for DataFrames isSignalTable( obj::DataFrames.DataFrame) = true getIndependentSignalNames( obj::DataFrames.DataFrame) = DataFrames.names(obj, 1)[1] getIndependentSignalsSize(obj::DataFrames.DataFrame) = [size(obj,1)] getSignalNames(obj::DataFrames.DataFrame) = DataFrames.names(obj) getSignal( obj::DataFrames.DataFrame, name::String) = Var(values = obj[!,name]) hasSignal( obj::DataFrames.DataFrame, name::String) = haskey(obj, name) """ df = signalTableToDataFrame(signalTable) Returns a signal table as [DataFrame](https://github.com/JuliaData/DataFrames.jl) object. """ function signalTableToDataFrame(sigTable)::DataFrames.DataFrame names = getSignalNames(sigTable; getPar=false, getMap=false) name = names[1] df = DataFrames.DataFrame(name = getSignal(sigTable,name)[:values]) for i in 2:length(names) name = names[i] sig = getSignal(sigTable,name) sigValues = sig[:values] if typeof(sigValues) <: AbstractVector df[!,name] = sig[:values] else @info "$name::$(typeof(sigValues)) is ignored, because no Vector" end end return df end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
1453
module SignalTables const path = dirname(dirname(@__FILE__)) const version = "0.4.2" const version_SignalTable_JSON = "0.4.2" # version tag to be stored in JSON files using OrderedCollections using Unitful using Test import DataFrames #import Measurements #import MonteCarloMeasurements import Pkg # Signals export SignalType, Var, Par, Map, isVar, isPar, isMap, isSignal, showSignal, eltypeOrType, quantity, unitAsParseableString # Abstract Signal Table Interface export isSignalTable, getIndependentSignalNames, getSignalNames, hasSignal, getSignal, getSignalInfo, getIndependentSignalsSize, getDefaultHeading # Signal table functions export new_signal_table, getValues, getValue, getValuesWithUnit, getValueWithUnit, getFlattenedSignal, showInfo, getHeading export signalTableToJSON, writeSignalTable # SignalTable export SignalTable, toSignalTable, signalTableToDataFrame # Plot Package export @usingPlotPackage, usePlotPackage, usePreviousPlotPackage, currentPlotPackage # Examples export getSignalTableExample include("Signals.jl") include("AbstractSignalTableInterface.jl") include("AbstractPlotInterface.jl") include("SignalTable.jl") include("SignalTableFunctions.jl") include("PlotPackageDefinition.jl") include("ExampleSignalTables.jl") include("NoPlot.jl") include("SilentNoPlot.jl") include("SignalTableInterface_DataFrames.jl") #include("SilentNoPlot.jl") #include("UserFunctions.jl") #include("OverloadedMethods.jl") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
12159
# License for this file: MIT (expat) # Copyright 2022, DLR Institute of System Dynamics and Control (DLR-SR) # Developer: Martin Otter, DLR-SR # # This file is part of module SignalTables """ const SymbolDictType = OrderedDict{Symbol,Any} Predefined dictionary type used for attributes. """ const SymbolDictType = OrderedDict{Symbol,Any} SymbolDict(; kwargs...) = SymbolDictType(kwargs) """ const StringDictType = OrderedDict{String,Any} Predefined dictionary type used for the signal dictionary. """ const StringDictType = OrderedDict{String,Any} StringDict(; kwargs...) = StringDictType(kwargs) elementBaseType(::Type{T}) where {T} = T elementBaseType(::Type{Union{Missing,T}}) where {T} = T """ eltypeOrType(obj) Returns eltype(obj), if obj is an AbstractArray and otherwise returns typeof(obj). """ eltypeOrType(array::AbstractArray) = eltype(array) eltypeOrType(obj) = typeof(obj) eltypeOrType(::Type{T}) where {T} = T <: AbstractArray ? eltype(T) : T # Copied from Modia/src/ModelCollections.jl (= newCollection) and adapted function newSignal(kwargs, kind)::OrderedDict{Symbol,Any} sig = OrderedDict{Symbol, Any}(:_class => kind, kwargs...) if kind == :Var && haskey(sig, :values) values = sig[:values] if !(typeof(values) <: AbstractArray) error("Var(values=..): typeof(values) = $(typeof(values)), but must be an Array") end if haskey(sig, :unit) sigUnit = sig[:unit] if typeof(sigUnit) <: AbstractArray && ndims(values) != ndims(sigUnit)+1 && ndims(values) < 2 && size(values)[2:end] != size(sigUnit) error("Var(values=..., unit=...): size(unit) = $(size(sigUnit)) and size(values)[2:end] = $(size(values)[2:end]) do not agree") end end elseif kind == :Par && haskey(sig, :value) value = sig[:value] if haskey(sig, :unit) sigUnit = sig[:unit] if typeof(sigUnit) <: AbstractArray && size(value) != size(sigUnit) error("Par(value=..., unit=...): size(unit) = $(size(sigUnit)) and size(value) = $(size(values)) do not agree") end end end return sig end """ signal = Var(; kwargs...)::OrderedDict{Symbol,Any} Returns a *variable* signal definition in form of a dictionary. `kwargs...` are key/value pairs of variable attributes. The *:values* key represents a *signal array* of any element type as function of the independent signal(s) (or is the k-th independent variable). A *signal array* has indices `[i1,i2,...,j1,j2,...]` to hold variable elements `[j1,j2,...]` at the `[i1,i2,...]` independent signal(s). If an element of a signal array is *not defined* it has a value of *missing*. Furthermore, additional attributes can be stored. The following keys are recognized (all are *optional* with exception of *:values* that must be either directly defined or via :alias): |key | value (of type String, if not obvious from context) | |:---------------|:------------------------------------------------------------------------------------------------------| |`:values` | Array{T,N}: `signal[:values][i1,i2,...j1,j2,...]` is value `[j1,j2,...]` at the `[i1,i2,...]` independent signal(s), or `signal[:values][i_k]` is value `[i_k]` of the k-th independent variable. | |`:unit` | String: Unit of all signal elements (parseable with `Unitful.uparse`), e.g., `"kg*m*s^2"`. Array{String,N}: `signal[:unit][j1,j2,...]` is unit of variable element `[j1,j2,...]`. | |`:info` | Short description of signal (= `description` of [FMI 3.0](https://fmi-standard.org/docs/3.0/) and of [Modelica](https://specification.modelica.org/maint/3.5/MLS.html)). | |`:independent` | = true, if independent variable (k-th independent variable is k-th Var insignal table) | |`:variability` | `"continuous", "clocked", "clock", "discrete",` or `"tunable"` (parameter). | |`:state` | = true, if signal is a (*continuous*, *clocked*, or *discrete*) state. | |`:der` | String: [`getSignal`](@ref)`(signalTable, signal[:der])[:values]` is the *derivative* of `signal[:values]`.| |`:clock` | String: [`getSignal`](@ref)`(signalTable, signal[:clock])[:values]` is the *clock* associated with `signal[:values]` (is only defined at clock ticks and otherwise is *missing*). If `Vector{String}`, a set of clocks is associated with the signal. | |`:alias` | String: `signal[:values]` is a *reference* to [`getSignal`](@ref)`(signalTable, signal[:alias])[:values]`. The *reference* is set and attributes are merged when the Var-signal is added to the signal table. | |`:interpolation`| Interpolation of signal points (`"linear", "none"`). If not provided, `interpolation` is deduced from `:variability` and otherwise interpolation is `"linear". | |`:extrapolation`| Extrapolation outside the values of the independent signal (`"none"`). | Additionally, any other signal attributes can be stored in `signal` with a desired key, such as *Variable Types* of [FMI 3.0](https://fmi-standard.org/docs/3.0/#definition-of-types). # Example ```julia using SignalTables t = (0.0:0.1:0.5) t_sig = Var(values = t, unit=u"s", independent=true) w_sig = Var(values = sin.(t), unit="rad/s", info="Motor angular velocity") c_sig = Var(values = [1.0, missing, missing, 4.0, missing, missing], variability="clocked") b_sig = Var(values = [false, true, true, false, false, true]) a_sig = Var(alias = "w_sig") ``` """ Var(;kwargs...) = newSignal(kwargs, :Var) """ signal = Par(; kwargs...)::OrderedDict{Symbol,Any} Returns a *parameter* signal definition in form of a dictionary. A parameter is a variable that is constant and is not a function of the independent variables. `kwargs...` are key/value pairs of parameter attributes. The value of a parameter variable is stored with key *:value* in `signal` and is an instance of any Julia type (number, string, array, tuple, dictionary, ...). The following keys are recognized (all are *optional*): | key | value (of type String, if not obvious from context) | |:---------|:------------------------------------------------------------------------------------------------------| | `:value` | `signal[:value]` is a constant value that holds for all values of the independent signals. | | `:unit` | String: Unit of all signal elements (parseable with `Unitful.uparse`), e.g., `"kg*m*s^2"`. Array{String,N}: `signal[:unit][j1,j2,...]` is unit of variable element `[j1,j2,...]`. | | `:info` | Short description of signal (= `description` of [FMI 3.0](https://fmi-standard.org/docs/3.0/) and of [Modelica](https://specification.modelica.org/maint/3.5/MLS.html)). | | `:alias` | String: `signal[:value]` is a *reference* to [`getSignal`](@ref)`(signalTable, signal[:alias])[:value]`. The *reference* is set and attributes are merged when the Par-signal is added to the signal table. | Additionally, any other signal attributes can be stored in `signal` with a desired key, such as *Variable Types* of [FMI 3.0](https://fmi-standard.org/docs/3.0/#definition-of-types). # Example ```julia using SignalTables J = Par(value = 0.02, unit=u"kg*m/s^2", info="Motor inertia") fileNames = Par(value = ["data1.json", "data2.json"]) J_alias = Par(alias = "J") ``` """ Par(; kwargs...) = newSignal(kwargs, :Par) """ signal = Map(; kwargs...)::OrderedDict{Symbol,Any} Returns a set of key/value pairs in form of a dictionary. A Map is used to associate a set of attributes to a Variable, Parameter or Signal Table. The following keys are recognized (all are *optional*): | key | value | |:---------|:-----------------------------------------------------| | `:info` | Short description. | Additionally, any other signal attributes can be stored in `signal` with a desired key, # Example ```julia using SignalTables sigTable = SignalTable( J = Par(value = 0.02), attributes = Map(author = "xyz") ) ``` """ Map(; kwargs...) = newSignal(kwargs, :Map) """ isVar(signal) Returns true, if signal is a [`Var`](@ref). """ isVar(signal) = typeof(signal) <: SymbolDictType && get(signal, :_class, :_) == :Var """ isPar(signal) Returns true, if signal is a [`Par`](@ref). """ isPar(signal) = typeof(signal) <: SymbolDictType && get(signal, :_class, :_) == :Par """ isMap(signal) Returns true, if signal is a [`Map`](@ref). """ isMap(signal) = typeof(signal) <: SymbolDictType && get(signal, :_class, :_) == :Map """ isSignal(signal) Returns true, if signal is a [`Var`](@ref) or a [`Par`](@ref) or a [`Map`](@ref) """ isSignal(signal) = isVar(signal) || isPar(signal) || isMap(signal) const doNotShow = [:_class] # [:_class, :_type, :_size] """ showSignal([io=stdout,] signal) Prints a [`Var`](@ref)(...) or [`Par`](@ref)(...) signal to io. """ function showSignal(io, sig) if isVar(sig) print(io, Var) elseif isPar(sig) print(io, Par) elseif isMap(sig) print(io, Map) else print(io, typeof(sig)) end print(io, "(") first = true for (key,val) in sig if key in doNotShow continue end if first first = false else print(io, ", ") end print(io, key, "=") show(io, val) end print(io, ")") end showSignal(sig) = showSignal(stdout, sig) """ quantityType = quantity(numberType, numberUnit::Unitful.FreeUnits) Returns Quantity from numberType and numberUnit, e.g. `quantity(Float64,u"m/s")` # Example ```julia using SignalTables using Unitful mutable struct Data{FloatType <: AbstractFloat} velocity::quantity(FloatType, u"m/s") end v = Data{Float64}(2.0u"mm/s") @show v # v = Data{Float64}(0.002 m s^-1) sig = Vector{Union{Missing,quantity(Float64,u"m/s")}}(missing,3) append!(sig, [1.0, 2.0, 3.0]u"m/s") append!(sig, fill(missing, 2)) @show sig # [missing, missing, missing, 1.0u"m/s", 2.0u"m/s", 3.0u"m/s", missing, missing] ``` """ quantity(numberType, numberUnit::Unitful.FreeUnits) = Quantity{numberType, dimension(numberUnit), typeof(numberUnit)} """ v_unit = unitAsParseableString(v::[Number|AbstractArray])::String Returns the unit of `v` as a string that can be parsed with `Unitful.uparse`. This allows, for example, to store a quantity with units into a JSON File and recover it when reading the file. This is not (easily) possible with current Unitful functionality, because `string(unit(v))` returns a string that cannot be parse with `uparse`. In Julia this is an unusual behavior because `string(something)` typically returns a string representation of something that can be again parsed by Julia. For more details, see [Unitful issue 412](https://github.com/PainterQubits/Unitful.jl/issues/412). Most likely, `unitAsParseableString(..)` cannot handle all occuring cases. # Examples ```julia using SignalTables using Unitful s = 2.1u"m/s" v = [1.0, 2.0, 3.0]u"m/s" s_unit = unitAsParseableString(s) # ::String v_unit = unitAsParseableString(v) # ::String s_unit2 = uparse(s_unit) # :: Unitful.FreeUnits{(m, s^-1), ..., nothing} v_unit2 = uparse(v_unit) # :: Unitful.FreeUnits{(m, s^-1), ..., nothing} @show s_unit # = "m*s^-1" @show v_unit # = "m*s^-1" @show s_unit2 # = "m s^-1" @show v_unit2 # = "m s^-1" ``` """ unitAsParseableString(sig)::String = "" unitAsParseableString(sigUnit::Unitful.FreeUnits)::String = replace(repr(sigUnit,context = Pair(:fancy_exponent,false)), " " => "*") unitAsParseableString(sigValue::Number)::String = unitAsParseableString(unit(sigValue)) unitAsParseableString(sigArray::AbstractArray)::String = unitAsParseableString(unit(eltypeOrType(sigArray)))
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
650
# License for this file: MIT (expat) # Copyright 2021, DLR Institute of System Dynamics and Control module SilentNoPlot export plot, showFigure, saveFigure, closeFigure, closeAllFigures include("AbstractPlotInterface.jl") plot(signalTable, 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() = nothing end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
11903
# License for this file: MIT (expat) # Copyright 2020-2022, DLR Institute of System Dynamics and Control # # This file is part of module SignalTables (is included by the SignalTablesInterface_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 == SignalTables.Continuous curve = lines!(axis, xsig, ysig, color=color) else curve = scatter!(axis, xsig, ysig, color=color, markersize = 5.0) 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) = SignalTables.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 = SignalTables.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, fontsize = 14) end if showFigureStringInDiagram figText = fig[1,1,TopLeft()] = Label(fig, "showFigure(" * string(figure) * ")", fontsize=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
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
1282
include("SignalTableFunctions/test_SignalTypes.jl") include("SignalTableFunctions/test_SignalTable.jl") include("SignalTableFunctions/test_DataFrames.jl") include("SignalTableFunctions/test_json.jl") include("../examples/plots/_include_all.jl") include("../examples/fileIO/_include_all.jl") #= include("LinePlots/test_06_OneScalarMeasurementSignal.jl") include("LinePlots/test_07_OneScalarMeasurementSignalWithUnit.jl") =# include("LinePlots/test_20_SeveralSignalsInOneDiagram.jl") include("LinePlots/test_21_VectorOfPlots.jl") include("LinePlots/test_22_MatrixOfPlots.jl") include("LinePlots/test_23_MatrixOfPlotsWithTimeLabelsInLastRow.jl") include("LinePlots/test_24_Reuse.jl") include("LinePlots/test_25_SeveralFigures.jl") include("LinePlots/test_26_TooManyLegends.jl") #= include("LinePlots/test_51_OneScalarMonteCarloMeasurementsSignal.jl") include("LinePlots/test_52_MonteCarloMeasurementsWithDistributions.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")
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
254
module Runtests # Run all tests with SilentNoPlot (so not plots) using SignalTables using SignalTables.Test @testset "Test SignalTables/test" begin usePlotPackage("SilentNoPlot") include("include_all.jl") usePreviousPlotPackage() end end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
435
module test_06_OneScalarMeasurementSignal using SignalTables using SignalTables.Unitful using SignalTables.Measurements @usingPlotPackage t = range(0.0, stop=10.0, length=100) c = ones(size(t,1)) sigTable = SignalTable( "time" => t "phi" => [sin(t[i]) Β± 0.1*c[i] for i in eachindex(t)] println("\n... test_06_OneScalarMeasurementSignal.jl:") showInfo(sigTable) plot(sigTable, "phi", heading="Sine(time) with Measurement") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
461
module test_07_OneScalarMeasurementSignalWithUnit using SignalTables using SignalTables.Unitful using SignalTables.Measurements @usingPlotPackage t = range(0.0, stop=10.0, length=100) c = ones(size(t,1)) sigTable = SignalTable( "time" => t*u"s" "phi" => [sin(t[i]) Β± 0.1*c[i] for i in eachindex(t)]*u"rad" println("\n... test_07_OneScalarMeasurementSignalWithUnit:") showInfo(sigTable) plot(sigTable, "phi", heading="Sine(time) with Measurement") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
632
module test_20_SeveralSignalsInOneDiagram using SignalTables @usingPlotPackage t = range(0.0, stop=10.0, length=100) sigTable = SignalTable( "time" => Var(values = t , unit="s", independent=true), "phi" => Var(values = sin.(t) , unit="rad"), "phi2" => Var(values = 0.5*sin.(t), unit="rad"), "w" => Var(values = cos.(t) , unit="rad/s"), "w2" => Var(values = 0.6*cos.(t), unit="rad/s"), "A" => Par(value = 0.6) ) println("\n... test_20_SeveralSignalsInOneDiagram:") showInfo(sigTable) plot(sigTable, ("phi", "phi2", "w", "w2", "A"), heading="Several signals in one diagram") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
546
module test_21_VectorOfPlots using SignalTables @usingPlotPackage t = range(0.0, stop=10.0, length=100) sigTable = SignalTable( "time" => Var(values=t, unit="s", independent=true), "phi" => Var(values=sin.(t), unit="rad"), "phi2" => Var(values=0.5 * sin.(t), unit="rad"), "w" => Var(values=cos.(t), unit="rad/s"), "w2" => Var(values=0.6 * cos.(t), unit="rad/s") ) println("\n... test_21_VectorOfPlots:") showInfo(sigTable) plot(sigTable, ["phi2", ("w",), ("phi", "phi2", "w", "w2")], heading="Vector of plots") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
694
module test_22_MatrixOfPlots using SignalTables @usingPlotPackage t = range(0.0, stop=10.0, length=100) sigTable = SignalTable( "time" => Var(values = t, unit="s", independent=true), "phi" => Var(values = sin.(t), unit="rad"), "phi2" => Var(values = 0.5 * sin.(t), unit="rad"), "w" => Var(values = cos.(t), unit="rad/s"), "w2" => Var(values = 0.6 * cos.(t), unit="rad/s"), "r" => Var(values = [0.4 * cos.(t) 0.5 * sin.(t) 0.3 * cos.(t)], unit="m") ) println("\n... test_22_MatrixOfPlots:") showInfo(sigTable) plot(sigTable, [ ("phi", "r") ("phi", "phi2", "w"); ("w", "w2", "phi2") "w" ], heading="Matrix of plots") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
856
module test_23_MatrixOfPlotsWithTimeLabelsInLastRow using SignalTables using SignalTables.Unitful @usingPlotPackage t = range(0.0, stop=10.0, length=100) sigTable = SignalTable( "time" => Var(values = t, unit="s", independent=true), "phi" => Var(values = sin.(t), unit="rad"), "phi2" => Var(values = 0.5 * sin.(t), unit="rad"), "w" => Var(values = cos.(t), unit="rad/s"), "w2" => Var(values = 0.6 * cos.(t), unit="rad/s"), "r" => Var(values = [0.4 * cos.(t) 0.5 * sin.(t) 0.3 * cos.(t)], unit="m") ) println("\n... test_23_MatrixOfPlotsWithTimeLabelsInLastRow:") showInfo(sigTable) plot(sigTable, [ ("phi", "r") ("phi", "phi2", "w"); ("w", "w2", "phi2") ("phi", "w") ], minXaxisTickLabels = true, heading="Matrix of plots with time labels in last row") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
682
module test_24_Reuse using SignalTables @usingPlotPackage t = range(0.0, stop=10.0, length=100) sigTable1 = SignalTable( "time" => Var(values=t, unit="s", independent=true), "phi" => Var(values=sin.(t), unit="rad"), "w" => Var(values=cos.(t), unit="rad/s") ) sigTable2 = SignalTable( "time" => Var(values=t, unit="s"), "phi" => Var(values=1.2*sin.(t), unit="rad", independent=true), "w" => Var(values=0.8*cos.(t), unit="rad/s") ) println("\n... test_24_Reuse:") showInfo(sigTable1) println() showInfo(sigTable2) plot(sigTable1, ("phi", "w"), prefix="Sim 1:", heading="Test reuse") plot(sigTable2, ("phi", "w"), prefix="Sim 2:", reuse=true) end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
767
module test_25_SeveralFigures using SignalTables @usingPlotPackage t = range(0.0, stop=10.0, length=100) sigTable = SignalTable( "time" => Var(values = t, unit="s", independent=true), "phi" => Var(values = sin.(t), unit="rad"), "phi2" => Var(values = 0.5 * sin.(t), unit="rad"), "w" => Var(values = cos.(t), unit="rad/s"), "w2" => Var(values = 0.6 * cos.(t), unit="rad/s"), "r" => Var(values = [0.4 * cos.(t) 0.5 * sin.(t) 0.3 * cos.(t)], unit="m") ) println("\n... test_25_SeveralFigures:") showInfo(sigTable) plot(sigTable, ("phi", "r") , heading="First figure" , figure=1) plot(sigTable, ["w", "w2", "r[2]"], heading="Second figure", figure=2) plot(sigTable, "r" , heading="Third figure" , figure=3) end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
651
module test_26_TooManyLegends using SignalTables @usingPlotPackage t = range(0.0, stop=10.0, length=100) sigTable = SignalTable( "time" => Var(values = t, unit="s", independent=true), "phi" => Var(values = sin.(t), unit="rad"), "phi2" => Var(values = 0.5 * sin.(t), unit="rad"), "w" => Var(values = cos.(t), unit="rad/s"), "w2" => Var(values = 0.6 * cos.(t), unit="rad/s"), "r" => Var(values = [0.4 * cos.(t) 0.5 * sin.(t) 0.3 * cos.(t)], unit="m") ) println("\n... test_26_TooManyLegends:") showInfo(sigTable) plot(sigTable, ("phi", "r", "w", "w2"), maxLegend = 5, heading = "Too many legends") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
510
module test_51_OneScalarMonteCarloMeasurementsSignal using SignalTables using SignalTables.Unitful using SignalTables.MonteCarloMeasurements @usingPlotPackage t = range(0.0, stop=10.0, length=100) c = ones(size(t,1)) sigTable = SignalTable( "time" => t*u"s" "phi" => [sin(t[i]) Β± 0.1*c[i] for i in eachindex(t)]*u"rad" println("\n... test_51_OneScalarMonteCarloMeasurementsSignal:") showInfo(sigTable) plot(sigTable, "phi", MonteCarloAsArea=true, heading="Sine(time) with MonteCarloMeasurements") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
1219
module test_52_MonteCarloMeasurementsWithDistributions using SignalTables using SignalTables.Unitful using SignalTables.MonteCarloMeasurements using SignalTables.MonteCarloMeasurements.Distributions @usingPlotPackage 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) sigTable = SignalTable( # βˆ“ are 100 StaticParticles uniform distribution "time" => t*u"s" sigTable["phi1"] = [sin(t[i]) + particles1*t[i]/10.0 for i in eachindex(t)]*u"rad" "phi2" => [sin(t[i]) + particles2*t[i]/10.0 for i in eachindex(t)]*u"rad" sigTable["phi3"] = [sin(t[i]) βˆ“ 0.4*t[i]/10.0 for i in eachindex(t)]*u"rad" println("\n... test_52_MonteCarloMeasurementsWithDistributions:") showInfo(sigTable) plot(sigTable, ["phi1", "phi2", "phi3"], figure=1, heading="Sine(time) with MonteCarloParticles/StaticParticles (plot area)") plot(sigTable, ["phi1", "phi2", "phi3"], figure=2, heading="Sine(time) with MonteCarloParticles/StaticParticles (plot all runs)") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
639
module test_71_Tables_Rotational_First using SignalTables using SignalTables.DataFrames using CSV SignalTables.@usingPlotPackage sigTable1 = CSV.File("$(SignalTables.path)/test/test_71_Tables_Rotational_First.csv") sigTable2 = DataFrames.DataFrame(sigTable1) println("\n... test_71_Tables_Rotational_First.jl:") println("CSV-Table (sigTable1 = CSV.File(fileName)):\n") showInfo(sigTable1) println("\nDataFrame-Table (sigTable2 = DataFrame(sigTable1)):\n") showInfo(sigTable2) plot(sigTable1, ["damper.w_rel", "inertia3.w"], prefix="sigTable1: ") plot(sigTable2, ["damper.w_rel", "inertia3.w"], prefix="sigTable2: ", reuse=true) end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
1306
module test_72_ResultDictWithMatrixOfPlots using SignalTables using SignalTables.Unitful SignalTables.@usingPlotPackage tr = [0.0, 15.0] t0 = (tr, tr, SignalTables.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 ], SignalTables.Continuous) sigB = ([t1] , [0.7*sin.(t1)u"m/s"], SignalTables.Continuous) sigC = ([t3] , [sin.(t3)u"N*m"] , SignalTables.Clocked) r = ([t2,t4] , [R2,R4] , SignalTables.Continuous) sigTable = SignalTables.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") showInfo(sigTable) plot(sigTable, [("sigA", "sigB", "sigC"), "r[2:3]"]) end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
1279
module test_72_ResultDictWithMatrixOfPlotsb using SignalTables using SignalTables.Unitful SignalTables.@usingPlotPackage tr = [0.0, 15.0] t0 = (tr, tr, SignalTables.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 ], SignalTables.Continuous) sigB = ([t1] , [0.7*sin.(t1)u"m/s"], SignalTables.Continuous) sigC = ([t3] , [sin.(t3)u"N*m"] , SignalTables.Clocked) r = ([t2,t4] , [R2,R4] , SignalTables.Continuous) sigTable = SignalTables.ResultDict("time" => t0, "sigA" => sigA, "sigB" => sigB, "sigC" => sigC, "r" => r, defaultHeading = "Segmented time signals", hasOneTimeSignal = false) println("\n... test_72_ResultDictWithMatrixOfPlots.jl:\n") showInfo(sigTable) plot(sigTable, [("sigA", "sigB", "sigC"), "r[2:3]"]) end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
927
module test_80_Warnings using SignalTables using SignalTables.Unitful SignalTables.@usingPlotPackage t = range(0.0, stop=10.0, length=100) t2 = range(0.0, stop=10.0, length=110) sigTable = SignalTable( "time" => t*u"s" "phi" => sin.(t)u"rad" "phi2" => 0.5 * sin.(t)u"rad" "w" => cos.(t)u"rad/s" "w2" => 0.6 * cos.(t)u"rad/s" "r" = [[0.4 * cos(t[i]), 0.5 * sin(t[i]), 0.3 * cos(t[i])] for i in eachindex(t)]*u"m" sigTable["nothingSignal"] = nothing sigTable["emptySignal"] = Float64[] sigTable["wrongSizeSignal"] = sin.(t2)u"rad" println("\n... test_40_Warnings") showInfo(sigTable) plot(sigTable, ("phi", "r", "signalNotDefined"), heading="Plot with warning 1" , figure=1) plot(sigTable, ("signalNotDefined", "nothingSignal", "emptySignal", "wrongSizeSignal"), heading="Plot with warning 2" , figure=2) end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
369
module test_81_SaveFigure import @usingPlotPackage SignalTables.@usingPlotPackage println("\n... test test_81_SaveFigure.jl:\n") t = range(0.0, stop=10.0, length=100) sigTable = Dict{String,Any}("time" => t, "phi" => sin.(t)) info = SignalTables.sigTableInfo(sigTable) showInfo(sigTable) plot(sigTable, "phi", figure=2) saveFigure(2, "test_saveFigure2.png") end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
464
module test_82_AllExportedFunctions import @usingPlotPackage SignalTables.@usingPlotPackage # Test the Figure operations println("\n... test test_82_AllExportedFunctions.jl:\n") t = range(0.0, stop=10.0, length=100) sigTable = Dict{String,Any}("time" => t, "phi" => sin.(t)) info = SignalTables.sigTableInfo(sigTable) showInfo(sigTable) plot(sigTable, "phi", figure=2) showFigure(2) saveFigure(2, "test_saveFigure.png") closeFigure(2) closeAllFigures() end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
2407
module test_90_CompareOneScalarSignal using SignalTables using SignalTables.DataFrames SignalTables.@usingPlotPackagePackage 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) sigTable1 = OrderedDict{String,Any}() sigTable2 = DataFrame() sigTable3 = DataFrame() sigTable4 = DataFrame() sigTable1["time"] = t1 sigTable1["phi"] = sin.(t1) sigTable2."time" = t2 sigTable2."phi" = sin.(t2) sigTable3[!,"time"] = t3 sigTable3[!,"phi"] = sin.(t3) sigTable4."time" = t4 sigTable4."phi" = sin.(t4.+0.01) # Check makeSameTimeAxis (sigTable1b, sigTable2b, sameTimeRange1) = SignalTables.makeSameTimeAxis(sigTable1, sigTable2, select=["phi", "w"]) println("sameTimeRange1 = ", sameTimeRange1) (sigTable1c, sigTable3b, sameTimeRange3) = SignalTables.makeSameTimeAxis(sigTable1, sigTable3) println("sameTimeRange3 = ", sameTimeRange3) (sigTable1d, sigTable4b, sameTimeRange4) = SignalTables.makeSameTimeAxis(sigTable1, sigTable4) println("sameTimeRange4 = ", sameTimeRange4) # check compareResults (success2, diff2, diff_names2, max_error2, within_tolerance2) = SignalTables.compareResults(sigTable1, sigTable2) println("success2 = $success2, max_error2 = $max_error2, within_tolerance2 = $within_tolerance2") (success3, diff3, diff_names3, max_error3, within_tolerance3) = SignalTables.compareResults(sigTable1, sigTable3) println("success3 = $success3, max_error3 = $max_error3, within_tolerance3 = $within_tolerance3") (success4, diff4, diff_names4, max_error4, within_tolerance4) = SignalTables.compareResults(sigTable1, sigTable4) println("success4 = $success4, max_error4 = $max_error4, within_tolerance4 = $within_tolerance4") plot(sigTable1, "phi", prefix="r1.") plot(sigTable2, "phi", prefix="r2.", reuse=true) plot(sigTable3, "phi", prefix="r3.", reuse=true) plot(sigTable4, "phi", prefix="r4.", reuse=true) plot(sigTable1b, "phi", prefix="r1b.", reuse=true) plot(sigTable2b, "phi", prefix="r2b.", reuse=true) plot(sigTable1c, "phi", prefix="r1c.", reuse=true) plot(sigTable3b, "phi", prefix="r3b.", reuse=true) plot(sigTable1d, "phi", prefix="r1d.", reuse=true) plot(sigTable4b, "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
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
1140
module test_91_CompareOneScalarSignalWithUnit using SignalTables using SignalTables.Unitful using SignalTables.DataFrames SignalTables.@usingPlotPackagePackage t = range(0.0, stop=10.0, length=100) sigTable1 = DataFrame() sigTable2 = DataFrame() sigTable3 = DataFrame() sigTable1."time" = t*u"s" sigTable1."w" => sin.(t)*u"rad/s" sigTable2."time" = t*u"s" sigTable2."w" => 0.0005*u"rad/s" .+ sin.(t)*u"rad/s" sigTable3."time" = t sigTable3."w" => sin.(t.+0.001) (success2, diff2, diff_names2, max_error2, within_tolerance2) = SignalTables.compareResults(sigTable1, sigTable2) println("success2 = $success2, max_error2 = $max_error2, within_tolerance2 = $within_tolerance2") (success3, diff3, diff_names3, max_error3, within_tolerance3) = SignalTables.compareResults(sigTable1, sigTable3) println("success3 = $success3, max_error3 = $max_error3, within_tolerance3 = $within_tolerance3") plot(sigTable1, "w", prefix="r1.") plot(sigTable2, "w", prefix="r2.", reuse=true) plot(sigTable3, "w", prefix="r3.", reuse=true) plot(diff2, "w", prefix="diff2_", figure=2) plot(diff3, "w", prefix="diff3_", figure=2, reuse=true) end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
439
module test_DataFrames using SignalTables import SignalTables.DataFrames println("\n... Convert DataFrame to SignalTable object") t = range(0.0, stop=10.0, length=10) df = DataFrames.DataFrame(time=t, phi=sin.(t)) @show df sigTable = toSignalTable(df) showInfo(sigTable) println("\n... Convert SignalTable to DataFrame object") sigTable2 = getSignalTableExample("VariousTypes") df2 = signalTableToDataFrame(sigTable2) @show df2 end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
1787
module test_SignalTables using SignalTables using SignalTables.Unitful using SignalTables.Test t = 0.0:0.1:0.5 sigTable = SignalTable( "time" => Var(values= t, unit="s", independent=true), "load.r" => Var(values= [sin.(t) cos.(t) sin.(t)], unit="m"), "motor.angle" => Var(values= sin.(t), unit="rad", state=true, der="motor.w"), "motor.w" => Var(values= cos.(t), unit="rad/s"), "motor.w_ref" => Var(values= 0.9*[sin.(t) cos.(t)], unit = ["rad", "1/s"], info="Reference angle and speed"), "wm" => Var(alias = "motor.w"), "ref.clock" => Var(values= [true, missing, missing, true, missing, missing], variability="clock"), "ref.trigger" => Var(values= [missing, missing, true, missing, true, true], variability="trigger"), "motor.w_c" => Var(values= [0.8, missing, missing, 1.5, missing, missing], variability="clocked", clock="ref.clock"), "motor.inertia"=> Par(value = 0.02f0, unit="kg*m/s^2"), "motor.data" => Par(value = "resources/motorMap.json"), "attributes" => Map(experiment=Map(stoptime=0.5, interval=0.01)) ) # Abstract Signal Tables Interface phi_m_sig = getSignal( sigTable, "motor.angle") # = Var(values=..., unit=..., ...) phi_m = getValuesWithUnit(sigTable, "motor.angle") # = [0.0, 0.0998, 0.1986, ...]u"rad" w_c = getValues( sigTable, "motor.w_c" ) # = [0.8, missing, missing, 1.5, ...] inertia = getValueWithUnit( sigTable, "motor.inertia") # = 0.02u"kg*m/s^2" motor_w = getValues(sigTable, "motor.w") wm = getValues(sigTable, "wm") @test motor_w === wm showInfo(sigTable) showInfo(sigTable, showPar=false, showAttributes=false) end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
1022
module test_SignalTypes using SignalTables using SignalTables.Unitful using SignalTables.Test @test eltypeOrType([1.0,2.0,3.0]) == Float64 @test eltypeOrType([1.0,missing,3.0]) == Union{Missing,Float64} @test eltypeOrType("abc") == String @test eltypeOrType((1,1.0,"abc")) == Tuple{Int64, Float64, String} s = 2.1u"m/s" v = [1.0, 2.0, 3.0]u"m/s" s_unit = unitAsParseableString(s) v_unit = unitAsParseableString(v) @test s_unit == "m*s^-1" @test v_unit == "m*s^-1" # Check that parsing the unit string works s_unit2 = uparse(s_unit) v_unit2 = uparse(s_unit) mutable struct Data{FloatType <: AbstractFloat} velocity::quantity(FloatType, u"m/s") end v = Data{Float64}(2.0u"mm/s") @show v # v = Data{Float64}(0.002 m s^-1) sig = Vector{Union{Missing,quantity(Float64,u"m/s")}}(missing,3) append!(sig, [1.0, 2.0, 3.0]u"m/s") append!(sig, fill(missing, 2)) @show sig # Union{Missing, Unitful.Quantity{xxx}}[missing, missing, missing, 1.0 m s^-1, 2.0 m s^-1, 3.0 m s^-1, missing, missing] end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
code
2268
module test_json using SignalTables println("\n... Write signal table in json format to file.") t = 0.0:0.1:0.5 signalTable1 = SignalTable( "time" => Var(values= t, unit="s", independent=true), "load.r" => Var(values= [sin.(t) cos.(t) sin.(t)], unit="m"), "motor.angle" => Var(values= sin.(t), unit="rad", state=true, der="motor.w"), "motor.w" => Var(values= cos.(t), unit="rad/s"), "motor.w_ref" => Var(values= 0.9*[sin.(t) cos.(t)], unit = ["rad", "1/s"], info="Reference angle and speed"), "wm" => Var(alias = "motor.w"), "ref.clock" => Var(values= [true, missing, missing, true, missing, missing], variability="clock"), "ref.trigger" => Var(values= [missing, missing, true, missing, true, true], variability="trigger"), "motor.w_c" => Var(values= [0.8, missing, missing, 1.5, missing, missing], variability="clocked", clock="ref.clock"), "motor.inertia"=> Par(value = 0.02f0, unit="kg*m/s^2"), "motor.data" => Par(value = "resources/motorMap.json"), "attributes" => Map(info = "This is a test signal table") ) writeSignalTable("test_json_signalTable1.json", signalTable1, log=true, indent=2) t = 0.0:0.1:10.0 tc = [rem(i,5) == 0 ? div(i,5)+1 : missing for i in 0:length(t)-1] sigTable2 = SignalTable( "_attributes" => Map(experiment=Map(stopTime=10.0, interval=0.1)), "time" => Var(values = t, unit="s", independent=true), "motor.angle" => Var(values = sin.(t), unit="rad", der="motor.w"), "motor.w" => Var(values = cos.(t), unit="rad/s"), "motor.w_ref" => Var(values = 0.9*cos.(t), unit="rad/s"), "baseClock" => Var(values = tc, variability="clock"), "motor.w_c" => Var(values = 1.2*cos.((tc.-1)/2), unit="rad/s", variability="clocked", clock="baseClock"), "motor.file" => Par(value = "motormap.json", info = "File name of motor characteristics") ) showInfo(sigTable2) @usingPlotPackage plot(sigTable2, ("motor.w", "motor.w_c"), figure=2) plot(sigTable2, "motor.w_c", xAxis="baseClock", figure=3) writeSignalTable("sigTable2.json", sigTable2, log=true, indent=2) end
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
docs
8775
# SignalTables [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://modiasim.github.io/SignalTables.jl/stable/index.html) [![The MIT License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/ModiaSim/SignalTables.jl/blob/master/LICENSE) Package [SignalTables](https://github.com/ModiaSim/SignalTables.jl) (see [docu](https://modiasim.github.io/SignalTables.jl/stable/index.html)) provides abstract and concrete types and functions for *signal tables*. A *signal table* is basically a table where the table columns can be multi-dimensional arrays with attributes. Typically, simulation results, reference signals, table-based input signals, measurement data, look-up tables can be represented by a signal table. A *signal table* is an *ordered dictionary* of *signals* with string keys. A *signal* can be defined in the following forms: - As [Var](https://modiasim.github.io/SignalTables.jl/stable/Functions/Signals.html#SignalTables.Var) *dictionary* that has a required *values* key (or an *alias* key) representing a *signal array* of any element type as function of the independent signal(s) (or is the k-th independent signal). A *signal array* is a *multi-dimensional array* with indices `[i1,i2,...,j1,j2,...]` to hold variable elements `[j1,j2,...]` at the `[i1,i2,...]` independent signal(s). If an element of a signal array is *not defined*, it has a value of *missing*. - As [Par](https://modiasim.github.io/SignalTables.jl/stable/Functions/Signals.html#SignalTables.Par) *dictionary* that has a required *value* key (or and *alias* key) representing a constant of any type. - As [Map](https://modiasim.github.io/SignalTables.jl/stable/Functions/Signals.html#SignalTables.Map) *dictionary* that has no required keys and collects attributes/meta-data that are associated with a Var, Par, Map, or signal table dictionary. In all these dictionaries, additional attributes can be stored, for example *unit*, *info*, *variability* (continuous, clocked, ...), *interpolation*, *extrapolation*, and user-defined attributes. This logical view is directly mapped to Julia data structures, but can be also mapped to data structures in other programming languages. It is then possible to use existing textual or binary persistent serialization formats (JSON, HDF5, BSON, MessagePack, ...) to store a signal table in these formats on file. Furthermore, a subset of a signal table can also be stored in traditional tables (Excel, CSV, pandas, DataFrames.jl, ...) by *flattening* the multi-dimensional arrays and not storing constants and attributes. ## Examples ```julia using SignalTables t = 0.0:0.1:0.5 sigTable = SignalTable( "time" => Var(values= t, unit="s", independent=true), "load.r" => Var(values= [sin.(t) cos.(t) sin.(t)], unit="m"), "motor.angle" => Var(values= sin.(t), unit="rad", state=true, der="motor.w"), "motor.w" => Var(values= cos.(t), unit="rad/s"), "motor.w_ref" => Var(values= 0.9*[sin.(t) cos.(t)], unit = ["rad", "1/s"], info="Reference angle and speed"), "wm" => Var(alias = "motor.w"), "ref.clock" => Var(values= [true, missing, missing, true, missing, missing], variability="clock"), "motor.w_c" => Var(values= [0.8, missing, missing, 1.5, missing, missing], variability="clocked", clock="ref.clock"), "motor.inertia"=> Par(value = 0.02f0, unit="kg*m/s^2"), "motor.data" => Par(value = "resources/motorMap.json"), "attributes" => Map(experiment=Map(stoptime=0.5, interval=0.01)) ) phi_m_sig = getSignal( sigTable, "motor.angle") # = Var(values=..., unit=..., ...) phi_m = getValuesWithUnit(sigTable, "motor.angle") # = [0.0, 0.0998, 0.1986, ...]u"rad" w_c = getValues( sigTable, "motor.w_c" ) # = [0.8, missing, missing, 1.5, ...] inertia = getValueWithUnit( sigTable, "motor.inertia") # = 0.02u"kg*m/s^2" getValues(sigTable, "motor.w") === getValues(sigTable, "wm") showInfo(sigTable) ``` Command `showInfo` generates the following output: ```julia name unit size eltypeOrType kind attributes ─────────────────────────────────────────────────────────────────────────────────────────────────────── time "s" [6] Float64 Var independent=true load.r "m" [6,3] Float64 Var motor.angle "rad" [6] Float64 Var state=true, der="motor.w" motor.w "rad/s" [6] Float64 Var motor.w_ref ["rad", "1/s"] [6,2] Float64 Var info="Reference angle and speed" wm "rad/s" [6] Float64 Var alias="motor.w" ref.clock [6] Union{Missing,Bool} Var variability="clock" motor.w_c [6] Union{Missing,Float64} Var variability="clocked", clock="ref.clock" motor.inertia "kg*m/s^2" Float32 Par motor.data String Par attributes Map experiment=Map(stoptime=0.5, interval=0.01) ``` The various Julia FileIO functions can be directly used to save a signal table in various formats, e.g. JSON or HDF5 (see [FileIO Examples](https://modiasim.github.io/SignalTables.jl/stable/Examples/FileIO.html), [json file of sigTable above](docs/resources/examples/fileIO/VariousTypes_prettyPrint.json) ). ```julia using SignalTable usePlotPackage("PyPlot") # or ENV["SignalTablesPlotPackage"] = "PyPlot" sigTable = getSignalTableExample("MissingValues") @usingPlotPackage # = using SignalTablesInterface_PyPlot plot(sigTable, [("sigC", "load.r[2:3]"), ("sigB", "sigD")]) # generate plots ``` generate the following plot: ![Plots of SigTable](https://modiasim.github.io/SignalTables.jl/resources/images/sigTable-line-plots.png) *Concrete implementations* of the [Abstract Signal Table Interface](https://modiasim.github.io/SignalTables.jl/stable/Internal/AbstractSignalTableInterface.html) are provided for: - [`SignalTable`](https://modiasim.github.io/SignalTables.jl/stable/Functions/SignalTables.html#SignalTables.SignalTable) (included in SignalTables.jl). - [Modia.jl](https://github.com/ModiaSim/Modia.jl) (a modeling and simulation environment; version >= 0.9.0) - [DataFrames.jl](https://github.com/JuliaData/DataFrames.jl) (tabular data; first column is independent variable; *only scalar variables*)) - [Tables.jl](https://github.com/JuliaData/Tables.jl) (abstract tables, e.g. [CSV](https://github.com/JuliaData/CSV.jl) tables; first column is independent variable; *only scalar variables*). *Concrete implementations* of the [Abstract Plot Interface](https://modiasim.github.io/SignalTables.jl/stable/Internal/AbstractPlotInterface.html) are provided for: - [PyPlot](https://github.com/JuliaPy/PyPlot.jl) (plots with [Matplotlib](https://matplotlib.org/stable/) from Python; via [SignalTablesInterface_PyPlot.jl](https://github.com/ModiaSim/SignalTablesInterface_PyPlot.jl)), - [GLMakie](https://github.com/JuliaPlots/GLMakie.jl) (interactive plots in an OpenGL window; via [SignalTablesInterface_GLMakie.jl](https://github.com/ModiaSim/SignalTablesInterface_GLMakie.jl)), - [WGLMakie](https://github.com/JuliaPlots/WGLMakie.jl) (interactive plots in a browser window; via [SignalTablesInterface_WGLMakie.jl](https://github.com/ModiaSim/SignalTablesInterface_WGLMakie.jl)), - [CairoMakie](https://github.com/JuliaPlots/CairoMakie.jl) (static plots on file with publication quality; via [SignalTablesInterface_CairoMakie.jl](https://github.com/ModiaSim/SignalTablesInterface_CairoMakie.jl)). Furthermore, there is a dummy implementation included in SignalTables that is useful when performing tests with runtests.jl, in order that no plot package needs to be loaded during the tests: - SilentNoPlot (= all plot calls are silently ignored). ## Installation ```julia julia> ]add SignalTables add SignalTablesInterface_PyPlot # if plotting with PyPlot desired add SignalTablesInterface_GLMakie # if plotting with GLMakie desired add SignalTablesInterface_WGLMakie # if plotting with WGLMakie desired add SignalTablesInterface_CairoMakie # if plotting with CairoMakie desired ``` If you have trouble installing `SignalTablesInterface_PyPlot`, see [Installation of PyPlot.jl](https://modiasim.github.io/SignalTables.jl/stable/index.html#Installation-of-PyPlot.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)
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
docs
13185
# SignalTables Documentation ```@meta CurrentModule = SignalTables ``` ## Overview Package [SignalTables](https://github.com/ModiaSim/SignalTables.jl) provides abstract and concrete types and functions for *signal tables*. A *signal table* is basically a table where the table columns can be multi-dimensional arrays with attributes. Typically, simulation results, reference signals, table-based input signals, measurement data, look-up tables can be represented by a signal table. A *signal table* is an *ordered dictionary* of *signals* with string keys. A *signal* can be defined in the following forms: - As [Var](https://modiasim.github.io/SignalTables.jl/stable/Functions/Signals.html#SignalTables.Var) *dictionary* that has a required *values* key (or an *alias* key) representing a *signal array* of any element type as function of the independent signal(s), or is the k-th independent signal. A *signal array* is a *multi-dimensional array* with indices `[i1,i2,...,j1,j2,...]` to hold variable elements `[j1,j2,...]` at the `[i1,i2,...]` independent signal(s). If an element of a signal array is *not defined*, it has a value of *missing*. - As [Par](https://modiasim.github.io/SignalTables.jl/stable/Functions/Signals.html#SignalTables.Par) *dictionary* that has a required *value* key (or and *alias* key) representing a constant of any type. - As [Map](https://modiasim.github.io/SignalTables.jl/stable/Functions/Signals.html#SignalTables.Map) *dictionary* that has no required keys and collects attributes/meta-data that are associated with a Var, Par, Map, or signal table dictionary. In all these dictionaries, additional attributes can be stored, for example *unit*, *info*, *variability* (continuous, clocked, ...), *interpolation*, *extrapolation*, and user-defined attributes. ## Examples ```julia using SignalTablesact t = 0.0:0.1:0.5 sigTable = SignalTable( "time" => Var(values= t, unit="s", independent=true), "load.r" => Var(values= [sin.(t) cos.(t) sin.(t)], unit="m"), "motor.angle" => Var(values= sin.(t), unit="rad", state=true, der="motor.w"), "motor.w" => Var(values= cos.(t), unit="rad/s"), "motor.w_ref" => Var(values= 0.9*[sin.(t) cos.(t)], unit = ["rad", "1/s"], info="Reference angle and speed"), "wm" => Var(alias = "motor.w"), "ref.clock" => Var(values= [true, missing, missing, true, missing, missing], variability="clock"), "motor.w_c" => Var(values= [0.8, missing, missing, 1.5, missing, missing], variability="clocked", clock="ref.clock"), "motor.inertia"=> Par(value = 0.02f0, unit="kg*m/s^2"), "motor.data" => Par(value = "resources/motorMap.json"), "attributes" => Map(experiment=Map(stoptime=0.5, interval=0.01)) ) phi_m_sig = getSignal( sigTable, "motor.angle") # = Var(values=..., unit=..., ...) phi_m = getValuesWithUnit(sigTable, "motor.angle") # = [0.0, 0.0998, 0.1986, ...]u"rad" w_c = getValues( sigTable, "motor.w_c" ) # = [0.8, missing, missing, 1.5, ...] inertia = getValueWithUnit( sigTable, "motor.inertia") # = 0.02u"kg*m/s^2" getValues(sigTable, "motor.w") === getValues(sigTable, "wm") showInfo(sigTable) ``` Command `showInfo` generates the following output: ```julia name unit size eltypeOrType kind attributes ─────────────────────────────────────────────────────────────────────────────────────────────────────── time "s" [6] Float64 Var independent=true load.r "m" [6,3] Float64 Var motor.angle "rad" [6] Float64 Var state=true, der="motor.w" motor.w "rad/s" [6] Float64 Var motor.w_ref ["rad", "1/s"] [6,2] Float64 Var info="Reference angle and speed" wm "rad/s" [6] Float64 Var alias="motor.w" ref.clock [6] Union{Missing,Bool} Var variability="clock" motor.w_c [6] Union{Missing,Float64} Var variability="clocked", clock="ref.clock" motor.inertia "kg*m/s^2" Float32 Par motor.data String Par attributes Map experiment=Map(stoptime=0.5, interval=0.01) ``` The various Julia FileIO functions can be directly used to save a signal table in various formats, e.g. JSON or HDF5 (see [FileIO Examples](@ref), [json file of sigTable above](../resources/examples/fileIO/VariousTypes_prettyPrint.json) ). The commands ```julia using SignalTable usePlotPackage("PyPlot") # or ENV["SignalTablesPlotPackage"] = "PyPlot" sigTable = getSignalTableExample("MissingValues") @usingPlotPackage # = using SignalTablesInterface_PyPlot plot(sigTable, [("sigC", "load.r[2:3]"), ("sigB", "sigD")]) ``` generate the following plot: ![Plots of SigTable](../resources/images/sigTable-line-plots.png) ## Abstract Interfaces *Concrete implementations* of the [Abstract Signal Table Interface](@ref) are provided for: - [`SignalTable`](@ref) (included in SignalTables.jl). - [Modia.jl](https://github.com/ModiaSim/Modia.jl) (a modeling and simulation environment; version >= 0.9.0) - [DataFrames.jl](https://github.com/JuliaData/DataFrames.jl) (tabular data; first column is independent variable; *only scalar variables*)) - [Tables.jl](https://github.com/JuliaData/Tables.jl) (abstract tables, e.g. [CSV](https://github.com/JuliaData/CSV.jl) tables; first column is independent variable; *only scalar variables*). *Concrete implementations* of the [Abstract Plot Interface](@ref) are provided for: - [PyPlot](https://github.com/JuliaPy/PyPlot.jl) (plots with [Matplotlib](https://matplotlib.org/stable/) from Python; via [SignalTablesInterface_PyPlot.jl](https://github.com/ModiaSim/SignalTablesInterface_PyPlot.jl)), - [GLMakie](https://github.com/JuliaPlots/GLMakie.jl) (interactive plots in an OpenGL window; via [SignalTablesInterface_GLMakie.jl](https://github.com/ModiaSim/SignalTablesInterface_GLMakie.jl)), - [WGLMakie](https://github.com/JuliaPlots/WGLMakie.jl) (interactive plots in a browser window; via [SignalTablesInterface_WGLMakie.jl](https://github.com/ModiaSim/SignalTablesInterface_WGLMakie.jl)), - [CairoMakie](https://github.com/JuliaPlots/CairoMakie.jl) (static plots on file with publication quality; via [SignalTablesInterface_CairoMakie.jl](https://github.com/ModiaSim/SignalTablesInterface_CairoMakie.jl)). Furthermore, there is a dummy implementation included in SignalTables.jl that is useful when performing tests with runtests.jl, in order that no plot package needs to be loaded during the tests: - SilentNoPlot (= all plot calls are silently ignored). ## Installation ```julia julia> ]add SignalTables add SignalTablesInterface_PyPlot # if plotting with PyPlot desired # once registration processs finished add SignalTablesInterface_GLMakie # if plotting with GLMakie desired add SignalTablesInterface_WGLMakie # if plotting with WGLMakie desired add SignalTablesInterface_CairoMakie # if plotting with CairoMakie desired ``` If you have trouble installing `SignalTablesInterface_PyPlot`, see [Installation of PyPlot.jl](https://modiasim.github.io/SignalTables.jl/stable/index.html#Installation-of-PyPlot.jl) ## Installation of PyPlot.jl `SignalTablesInterface_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 `SignalTablesInterface_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, `SignalTablesInterface_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.4 - Adapted to GLMakie 0.8 (`textsize` replaced by `fontsize` in src/makie.jl) ### Version 0.4.3 - Minor improvements when printing a SignalTable. ### Version 0.4.2 - Fix issue [#6](https://github.com/ModiaSim/SignalTables.jl/issues/6): signalTableToDataFrame(..) is now working if the first signal is not a Var(..). - Minor improvement in JSON generation. ### Version 0.4.1 - getSignalNames(signalTable; getVar=true, getPar=true, getMap=true): New keyword arguments getVar, getPar, getMap to only return names of the specified signal categories. - writeSignalTable(...): Some issues corrected. - @error replaced by error(..). ### Version 0.4.0 - New signal-type Map added (additionally to Var und Par signals) with two new functions Map(..), isMap(..). - Output of showInfo(..) improved. - Non-backwards compatible changes: Function showInfo(..) has optional keywords arguments showVar, showPar, showMap, showAttributes, instead of the previous Var, Par, attributes. ### Version 0.3.5 - @usingPlotPackage(): If SilentNoPlot selected, use "using SignalTables.SilentNoPlot" instead of "import SignalTables.SilentNoPlot: plot ..:". - writeSignalTable(..): Arrays get an additional key `layout = "column-major"` to clearly define that storage is in column-major order. Furthermore, if a signal has an *alias* key, then the *values* or *value* array is not stored on file. **Bug fixes** - writeSignalTable(..): If arrays or numbers have Unitful units, these units are stripped off and provided via key `unit` as a string. ### Version 0.3.4 - Bug fix in usePreviousPlotPackage() ### Version 0.3.3 - Bug fix: getValuesWithUnit(..) is now correctly returning the values vector, if no unit is defined. ### Version 0.3.2 - Add makie.jl to be used by Makie backends. - For backwards compatibilty to ModiaResult, also accept ENV["MODIA_PLOT_PACKAGE"] instead of ENV["SignalTablesPlotPackage"] to define plot package - at all places (some parts have been missing). ### Version 0.3.1 - writeSignalTable(..): Do not store elements, that cannot be mapped to JSON + add _classVersion to signal table on file. - For backwards compatibilty to ModiaResult, also accept ENV["MODIA_PLOT_PACKAGE"] instead of ENV["SignalTablesPlotPackage"] to define plot package. ### Version 0.3.0 - Slightly non-backwards compatible to 0.2.0. - Various new functions (e.g. storing a signal table in JSON format on file). - DataFrames.jl, Tables.jl are supported as signal tables. - Plotting/flattening: Support of Measurements.jl and MonteCarloMeasurements.jl - Docu improved. - Bug with PlotPackage "SilentNoPlot" fixed. - `SignalTables/test/runtests.jl` runs the tests with plot package *"SilentNoPlot"* (instead of the activated plot package). - New file `SignalTables/test/runtests_with_plot.jl` runs the tests with the activated plot package. ### Version 0.2.0 Version, based on [ModiaResult.jl](https://github.com/ModiaSim/ModiaResult.jl). Changes with respect to ModiaResult.jl: Underlying data format made much simpler, more general and more useful: - Dictionary of *multi-dimensional arrays* as function of one or more independent variables with potentially *missing values*. - Also parameters can be stored in the dictionary and are supported, e.g., for plotting. - Variables and parameters are dictionaries that store the actual values (e.g. arrays), and additional attributes. - Values are stored without units and the units are provided via the additional string attribute `:unit`. A unit can be either hold for all elements of an array, or an array of units can be provided defining the units for all variable elements. - A new function to *flatten* and convert a signal array for use in plots or traditional tables. - Since signals are arrays, all the Julia array operations can be directly used, e.g. for post-processing of simulation results. - write/save on JSON and JDL (HDF5) files. Furthermore - Documentation considerably improved and made more user-oriented. - The Abstract Interfaces defined more clearly. - Several annoying bugs of ModiaResult.jl are no longer present. ### Version 0.1.0 Initial version used for registration. ## 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)
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
docs
3862
# FileIO Examples ```@meta CurrentModule = SignalTables ``` ## JSON - Write to File ```julia using SignalTables sigTable = getSignalTableExample("VariousTypes") writeSignalTable("VariousTypes_prettyPrint.json", sigTable; indent=2, log=true) writeSignalTable("VariousTypes_compact.json" , sigTable) ``` results in the following files - [VariousTypes_prettyPrint.json](../../resources/examples/fileIO/VariousTypes_prettyPrint.json). - [VariousTypes_compact.json](../../resources/examples/fileIO/VariousTypes_compact.json). ## JSON - Write to String ```julia using SignalTables str = signalTableToJSON( getSignalTableExample("VariousTypes") ) println(str) ``` results in the following print output ```julia "{\"_class\":\"SignalTable\",\"time\":{\"_class\":\"Var\",\"values\":[0.0,0.1,0.2,0.3,0.4,0.5],\"unit\":\"s\",\"independent\":true},\"load.r\":{\"_class\":\"Var\",\"values\":{\"_class\":\"Array\",\"eltype\":\"Float64\",\"size\":[6,3],\"values\":[0.0,0.09983341664682815,0.19866933079506122,0.29552020666133955,0.3894183423086505,0.479425538604203,1.0,0.9950041652780258,0.9800665778412416,0.955336489125606,0.9210609940028851,0.8775825618903728,0.0,0.09983341664682815,0.19866933079506122,0.29552020666133955,0.3894183423086505,0.479425538604203]},\"unit\":\"m\"},\"motor.angle\":{\"_class\":\"Var\",\"values\":[0.0,0.09983341664682815,0.19866933079506122,0.29552020666133955,0.3894183423086505,0" β‹― 533 bytes β‹― ",\"info\":\"Reference angle and speed\"},\"wm\":{\"_class\":\"Var\",\"values\":[1.0,0.9950041652780258,0.9800665778412416,0.955336489125606,0.9210609940028851,0.8775825618903728],\"unit\":\"rad/s\",\"alias\":\"motor.w\"},\"ref.clock\":{\"_class\":\"Var\",\"values\":[true,null,null,true,null,null],\"variability\":\"clock\"},\"motor.w_c\":{\"_class\":\"Var\",\"values\":[0.6,null,null,0.8,null,null],\"variability\":\"clocked\",\"clock\":\"ref.clock\"},\"motor.inertia\":{\"_class\":\"Par\",\"value\":{\"_class\":\"Number\",\"type\":\"Float32\",\"value\":0.02},\"unit\":\"kg*m/s^2\"},\"motor.data\":{\"_class\":\"Par\",\"value\":\"resources/motorMap.json\"},\"attributes\":{\"_class\":\"Par\",\"info\":\"This is a test signal table\"}}" ``` Such a string could be communicated to a web browser. ## JLD (HDF5) - Write to File [JLD](https://github.com/JuliaIO/JLD.jl) stores Julia objects in HDF5 format, hereby additional attributes are stored to preserve type information. ```julia using SignalTables using FileIO sigTable = getSignalTableExample("VariousTypes") save( File(format"JLD", "VariousTypes.jld"), sigTable) ``` results in the following file: - [VariousTypes.jld](../../resources/examples/fileIO/VariousTypes.jld). ## CSV - Read from File All Julia tables that are derived from [Tables.jl](https://github.com/JuliaData/Tables.jl) are seen as signal tables. For example, a CSV Files is read from file and treated as signal Table: ```julia using SignalTables import CSV file = joinpath(SignalTables.path, "examples", "fileIO", "Rotational_First.csv") println("\n... Read csv file \"$file\"") sigTable = CSV.File(file) println("\n... Show csv file as signal table") showInfo(sigTable) println("\ntime[1:10] = ", getSignal(sigTable, "time")[:values][1:10]) ``` results in the following output: ```julia ... Read csv file "[...]\SignalTables\examples\fileIO\Rotational_First.csv" ... Show csv file as signal table name unit size eltypeOrType kind attributes ─────────────────────────────────────────────────────────────── time (2002,) Float64 Var damper.phi_rel (2002,) Float64 Var damper.w_rel (2002,) Float64 Var inertia3.phi (2002,) Float64 Var inertia3.w (2002,) Float64 Var time[1:10] = [0.0, 0.0005, 0.001, 0.0015, 0.002, 0.0025, 0.003, 0.0035, 0.004, 0.0045000000000000005] ```
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
docs
9835
# Plot Examples ```@meta CurrentModule = SignalTables ``` ## OneScalarSignal ```julia using SignalTables @usingPlotPackage t = range(0.0, stop=10.0, length=100) sigTable = SignalTable( "time" => Var(values = t, independent=true), "phi" => Var(values = sin.(t)) ) showInfo(sigTable) plot(sigTable, "phi", heading="sine(time)") ``` results in: ```julia name unit size eltypeOrType kind attributes ────────────────────────────────────────────────────────── time (100,) Float64 Var independent=true phi (100,) Float64 Var ``` ![OneScalarSignal](../../resources/examples/plots/OneScalarSignal.png) ## OneScalarSignalWithUnit ```julia using SignalTables @usingPlotPackage t = range(0.0, stop=10.0, length=100) sigTable = SignalTable( "time" => Var(values = t, unit="s", independent=true), "phi" => Var(values = sin.(t), unit="rad") ) showInfo(sigTable) plot(sigTable, "phi", heading="sine(time)") ``` results in: ```julia name unit size eltypeOrType kind attributes ─────────────────────────────────────────────────────────── time "s" (100,) Float64 Var independent=true phi "rad" (100,) Float64 Var ``` ![OneScalarSignalWithUnit](../../resources/examples/plots/OneScalarSignalWithUnit.png) ## OneVectorSignalWithUnit ```julia using SignalTables @usingPlotPackage t = range(0.0, stop=10.0, length=100) sigTable = SignalTable( "time" => Var(values = t, unit="s", independent=true), "r" => Var(values = [0.4*cos.(t) 0.5*sin.(t) 0.3*cos.(t)], unit="m"), ) showInfo(sigTable) plot(sigTable, "phi", heading="sine(time)") ``` results in: ```julia name unit size eltypeOrType kind attributes ─────────────────────────────────────────────────────────── time "s" (100,) Float64 Var independent=true r "m" (100,3) Float64 Var ``` ![OneVectorSignalWithUnit](../../resources/examples/plots/OneVectorSignalWithUnit.png) ## OneMatrixSignal ```julia using SignalTables @usingPlotPackage t = range(0.0, stop=1.0, length=10) offset = Float64[11 12 13; 21 22 23] matrix = Array{Float64,3}(undef,length(t),2,3) for i = 1:length(t), j = 1:2, k=1:3 matrix[i,j,k] = offset[j,k] + 0.3*sin(t[i]) end sigTable = SignalTable( "time" => Var(values = t, independent=true), "matrix" => Var(values = matrix) ) showInfo(sigTable) plot(sigTable, "phi", heading="sine(time)") ``` results in: ```julia name unit size eltypeOrType kind attributes ────────────────────────────────────────────────────────────── time (10,) Float64 Var independent=true matrix (10,2,3) Float64 Var ``` ![OneMatrixSignal](../../resources/examples/plots/OneMatrixSignal.png) ## OneMatrixSignalWithMatrixUnits ```julia using SignalTables @usingPlotPackage t = range(0.0, stop=1.0, length=10) offset = Float64[11 12 13; 21 22 23] matrix = Array{Float64,3}(undef,length(t),2,3) for i = 1:length(t), j = 1:2, k=1:3 matrix[i,j,k] = offset[j,k] + 0.3*sin(t[i]) end sigTable = SignalTable( "time" => Var(values = t, unit="s", independent=true), "matrix" => Var(values = matrix, unit=["m" "m/s" "m/s^2"; "rad" "rad/s" "rad/s^2"]) ) showInfo(sigTable) plot(sigTable, "phi", heading="sine(time)") ``` results in: ```julia name unit size eltypeOrType kind attributes ────────────────────────────────────────────────────────────────────────────────────────────────────── time "s" (10,) Float64 Var independent=true matrix ["m" "m/s" "m/s^2"; "rad" "rad/s" "rad/s^2"] (10,2,3) Float64 Var ``` ![OneMatrixSignalWithMatrixUnits](../../resources/examples/plots/OneMatrixSignalWithMatrixUnits.png) ## ConstantSignals ```julia using SignalTables @usingPlotPackage t = range(0.0, stop=1.0, length=5) matrix = Float64[11 12 13; 21 22 23] sigTable = SignalTable( "time" => Var(values = t, unit="s", independent=true), "phi_max" => Par(value = 1.1f0, unit="rad"), "i_max" => Par(value = 2), "open" => Par(value = true), "file" => Par(value = "filename.txt"), "matrix1" => Par(value = matrix), "matrix2" => Par(alias = "matrix1", unit="m/s"), "matrix3" => Par(alias = "matrix1", unit=["m" "m/s" "m/s^2"; "rad" "rad/s" "rad/s^2"]) ) showInfo(sigTable) plot(sigTable, "phi", heading="sine(time)") ``` results in: ```julia name unit size eltypeOrType kind attributes ──────────────────────────────────────────────────────────────────────────────────────────────────── time "s" (5,) Float64 Var independent=true phi_max "rad" () Float32 Par i_max () Int64 Par open () Bool Par file String Par matrix1 (2,3) Float64 Par matrix2 "m/s" (2,3) Float64 Par alias="matrix1" matrix3 ["m" "m/s" "m/s^2"; "rad" "rad/s" "rad/s^2"] (2,3) Float64 Par alias="matrix1" ``` ![ConstantSignals](../../resources/examples/plots/ConstantSignals.png) # MissingValues ```julia using SignalTables @usingPlotPackage time1 = 0.0 : 0.1 : 3.0 time2 = 3.0 : 0.1 : 11.0 time3 = 11.0 : 0.1 : 15 t = vcat(time1,time2,time3) sigC = vcat(fill(missing,length(time1)), 0.6*cos.(time2.+0.5), fill(missing,length(time3))) function sigD(t, time1, time2) sig = Vector{Union{Missing,Float64}}(undef, length(t)) j = 1 for i = length(time1)+1:length(time1)+length(time2) if j == 1 sig[i] = 0.5*cos(t[i]) end j = j > 3 ? 1 : j+1 end return sig end sigTable = SignalTable( "time" => Var(values=t, unit="s", independent=true), "load.r" => Var(values=0.4*[sin.(t) cos.(t) sin.(t)], unit="m"), "sigA" => Var(values=0.5*sin.(t), unit="m"), "sigB" => Var(values=1.1*sin.(t), unit="m/s"), "sigC" => Var(values=sigC, unit="N*m"), "sigD" => Var(values=sigD(t, time1, time2), unit="rad/s", variability="clocked", info="Motor angular velocity") ) showInfo(sigTable) plot(sigTable, [("sigC", "load.r[2:3]"), ("sigB", "sigD")]) ``` results in: ```julia name unit size eltypeOrType kind attributes ───────────────────────────────────────────────────────────────────────────────────────────────────────────── time "s" (153,) Float64 Var independent=true load.r "m" (153,3) Float64 Var sigA "m" (153,) Float64 Var sigB "m/s" (153,) Float64 Var sigC "N*m" (153,) Union{Missing,Float64} Var sigD "rad/s" (153,) Union{Missing,Float64} Var variability="clocked", info="Motor angular velocit… ``` ![MissingValues](../../resources/examples/plots/MissingValues.png) # VariousTypes ```julia using SignalTables @usingPlotPackage t = 0.0:0.1:0.5 sigTable = SignalTable( "time" => Var(values= t, unit="s", independent=true), "load.r" => Var(values= [sin.(t) cos.(t) sin.(t)], unit="m"), "motor.angle" => Var(values= sin.(t), unit="rad", state=true), "motor.w" => Var(values= cos.(t), unit="rad/s", integral="motor.angle"), "motor.w_ref" => Var(values= 0.9*[sin.(t) cos.(t)], unit = ["rad", "1/s"], info="Reference angle and speed"), "wm" => Var(alias = "motor.w"), "ref.clock" => Var(values= [true, missing, missing, true, missing, missing], variability="clock"), "motor.w_c" => Var(values= [0.6, missing, missing, 0.8, missing, missing], variability="clocked", clock="ref.clock"), "motor.inertia" => Par(value = 0.02f0, unit="kg*m/s^2"), "motor.data" => Par(value = "resources/motorMap.json"), "attributes" => Par(info = "This is a test signal table") ) showInfo(sigTable) plot(sigTable, ["load.r", ("motor.w", "wm", "motor.w_c", "ref.clock")], heading="VariousTypes") ``` results in: ```julia name unit size eltypeOrType kind attributes ────────────────────────────────────────────────────────────────────────────────────────────────────────────── time "s" (6,) Float64 Var independent=true load.r "m" (6,3) Float64 Var motor.angle "rad" (6,) Float64 Var state=true, der="motor.w" motor.w "rad/s" (6,) Float64 Var motor.w_ref ["rad", "1/s"] (6,2) Float64 Var info="Reference angle and speed" wm "rad/s" (6,) Float64 Var alias="motor.w" ref.clock (6,) Union{Missing,Bool} Var variability="clock" motor.w_c (6,) Union{Missing,Float64} Var variability="clocked", clock="ref.clock" motor.inertia "kg*m/s^2" () Float32 Par motor.data String Par attributes Par info="This is a test signal table" ``` ![VariousTypes](../../resources/examples/plots/VariousTypes.png)
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
docs
6737
# Overview of Functions ```@meta CurrentModule = SignalTables ``` This chapter documents functions that operate on signals and on signal tables A *signal table* is an *ordered dictionary* of *signals* with string keys that supports the [Abstract Signal Table Interface](@ref). The first k entries represent the k independent signals. A *signal* is either a - [`Var`](@ref) dictionary that has a required *:values* key representing a *signal array* of any element type as function of the independent signal(s) (or is the k-th independent variable), or a - [`Par`](@ref) dictionary that has an optional *:value* key representing a constant of any type. A *signal array* has indices `[i1,i2,...,j1,j2,...]` to hold variable elements `[j1,j2,...]` at the `[i1,i2,...]` independent signal(s). If an element of a signal array is *not defined* it has a value of *missing*. In both dictionaries, additional attributes can be stored, for example units, into texts, variability (continuous, clocked, ...), alias. Note, *FileIO* functions (e.g. JSON, HDF5) can be directly used, see [FileIO Examples](@ref). | Signal functions | Description | |:--------------------------------|:-------------------------------------------------------------------------------------------| | [`Var`](@ref) | Returns a variable signal definition in form of a dictionary. | | [`Par`](@ref) | Returns a parameter signal definition in form of a dictionary. | | [`isVar`](@ref) | Returns true, if signal is a [`Var`](@ref). | | [`isPar`](@ref) | Returns true, if signal is a [`Par`](@ref). | | [`isMap`](@ref) | Returns true, if signal is a [`Map`](@ref). | | [`isSignal`](@ref) | Returns true, if signal is a [`Var`](@ref), [`Par`](@ref) or [`Map`](@ref). | | [`showSignal`](@ref) | Prints a [`Var`](@ref), [`Par`](@ref) or [`Map`](@ref) signal to io. | | [`eltypeOrType`](@ref) | Returns eltype(..) of AbstractArray or otherwise typeof(..). | | [`quantity`](@ref) | Returns `Unitful.Quantity` from numberType and numberUnit, e.g. `quantity(Float64,u"m/s")` | | [`unitAsParseableString`](@ref) | Returns the unit as a String that can be parsed with `Unitful.uparse`, e.g. "m*s^-1" | | Signal table functions | Description | |:------------------------------------|:-----------------------------------------------------------------------------------------------| | [`SignalTable`](@ref) | Returns a new SignalTable dictionary. | | [`showInfo`](@ref) | Writes info about a signal table to the output stream. | | [`getIndependentSignalNames`](@ref) | Returns the names of the independent signals. | | [`getSignalNames`](@ref) | Returns a string vector of the signal names that are present in a signal table. | | [`hasSignal`](@ref) | Returns `true` if a signal is present in a signal table. | | [`getSignal`](@ref) | Returns signal from a signal table as [`Var`](@ref), [`Par`](@ref) or [`Map`](@ref). | | [`getSignalInfo`](@ref) | Returns signal with :\_typeof, :\_size keys instead of :values/:value keys. | | [`getIndependentSignalsSize`](@ref) | Returns the lengths of the independent signals as Dims. | | [`getValues`](@ref) | Returns the *values* of a [`Var`](@ref) signal from a signal table. | | [`getValuesWithUnit`](@ref) | Returns the *values* of a [`Var`](@ref) signal from a signal table including its unit. | | [`getValue`](@ref) | Returns the *value* of a [`Par`](@ref) signal from a signal table. | | [`getValueWithUnit`](@ref) | Returns the *value* of a [`Par`](@ref) signal from a signal table including its unit. | | [`getFlattenedSignal`](@ref) | Returns a copy of a signal where the values or the value are *flattened* and converted for use in plots or traditional tables. | | [`getDefaultHeading`](@ref) | Returns the default heading for a plot. | | [`signalTableToJSON`](@ref) | Returns a JSON string representation of a signal table. | | [`writeSignalTable`](@ref) | Write a signal table in JSON format on file. | | [`toSignalTable`](@ref) | Returns a signal table as [`SignalTable`](@ref) object. | | [`signalTableToDataFrame`](@ref) | Returns a signal table as [DataFrame](https://github.com/JuliaData/DataFrames.jl) object. | | Plot package functions | Description | |:---------------------------------|:----------------------------------------------------------| | [`@usingPlotPackage`](@ref) | Expands into `using PlotPackage_<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) | ```@meta CurrentModule = SignalTablesInterface_PyPlot ``` | Plot functions | Description | |:--------------------------|:---------------------------------------------------------------| | [`plot`](@ref) | Plot signals from a signal table 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) |
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
docs
2462
# Plot Packages ```@meta CurrentModule = SignalTables ``` Example to define the plot package to be used: ```julia using SignalTables usePlotPackage("PyPlot") # or ENV["SignalTablesPlotPackage"] = "PyPlot" ``` The following plot packages are supported: - `"PyPlot"` ([PyPlot](https://github.com/JuliaPy/PyPlot.jl) plots with Matplotlib from Python; via [SignalTablesInterface_PyPlot.jl](https://github.com/ModiaSim/SignalTablesInterface_PyPlot.jl)), - `"GLMakie"` ([GLMakie](https://github.com/JuliaPlots/GLMakie.jl) provides interactive plots in an OpenGL window; via [SignalTablesInterface_GLMakie.jl](https://github.com/ModiaSim/SignalTablesInterface_GLMakie.jl)), - `"WGLMakie"` ([WGLMakie](https://github.com/JuliaPlots/WGLMakie.jl) provides interactive plots in a browser window; via [SignalTablesInterface_WGLMakie.jl](https://github.com/ModiaSim/SignalTablesInterface_WGLMakie.jl)), - `"CairoMakie"` ([CairoMakie](https://github.com/JuliaPlots/CairoMakie.jl) provides static plots on file with publication quality; via [SignalTablesInterface_CairoMakie.jl](https://github.com/ModiaSim/SignalTablesInterface_CairoMakie.jl)). - `"SilentNoPlot"` (= all plot calls are silently ignored). Typically, runtests.jl is defined as: ```julia using SignalTables usePlotPackage("SilentNoPlot") # Define Plot Package (previously defined one is put on a stack) include("include_all.jl") # Include all tests that use a plot package usePreviousPlotPackage() # Use previously defined Plot package ``` The following functions are provided to define/inquire the current plot package. !!! note [SignalTables.jl](https://github.com/ModiaSim/SignalTables.jl) exports all symbols of this table.\ [Modia.jl](https://github.com/ModiaSim/Modia.jl) reexports all symbols. | Plot package functions | Description | |:---------------------------------|:----------------------------------------------------------| | [`@usingPlotPackage`](@ref) | Expands into `using PlotPackage_<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) | ```@docs @usingPlotPackage usePlotPackage usePreviousPlotPackage currentPlotPackage ```
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
docs
2059
# Plots ```@meta CurrentModule = SignalTablesInterface_PyPlot ``` The functions below are used to *plot* one or more signalTable signals in one or more *diagrams* within one or more *windows* (figures), and *save* a window (figure) in various *formats* on file (e.g. png, pdf). The functions below are available after ```julia using SignalTables # Make Symbols available usePlotPackage("PyPlot") # or ENV["SignalTablesPlotPackage"] = "PyPlot" # Other options: "GLMakie", "WGLMakie, "CairoMakie", "SilentNoPlot" @usingPlotPackage # expands into: using SignalTablesInterface_PyPlot ``` or ``` using Modia # Make Symbols available usePlotPackage("PyPlot") # or ENV["SignalTablesPlotPackage"] = "PyPlot" # Other options: "GLMakie", "WGLMakie, "CairoMakie", "SilentNoPlot" @usingPlotPackage # expands into: using SignalTablesInterface_PyPlot ``` have been executed. The documentation has been generated with [SignalTablesInterface_PyPlot](https://github.com/ModiaSim/SignalTablesInterface_PyPlot.jl). !!! note [SignalTables.jl](https://github.com/ModiaSim/SignalTables.jl) exports all symbols of the table.\ [Modia.jl](https://github.com/ModiaSim/Modia.jl) reexports all symbols and uses as *signalTable* argument `instantiatedModel`. | Plot functions | Description | |:--------------------------|:---------------------------------------------------------------| | [`plot`](@ref) | Plot signals from a signal table 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) | ```@docs plot saveFigure closeFigure closeAllFigures showFigure ```
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
docs
3619
# Signal Tables ```@meta CurrentModule = SignalTables ``` The functions below operate on a *signal table* that implements the [Abstract Signal Table Interface](@ref). !!! note [SignalTables.jl](https://github.com/ModiaSim/SignalTables.jl) exports all symbols of this table.\ [Modia.jl](https://github.com/ModiaSim/Modia.jl) reexports all symbols and uses `instantiatedModel` as *signalTable* argument. | Signal table functions | Description | |:-----------------------------------|:-----------------------------------------------------------------------------------------------| | [`new_signal_table`](@ref) | Returns a new signal table dictionary (= OrderedDict{String,Any}("_class" => :SignalTable)). | | [`SignalTable`](@ref) | Returns a new instance of type SignalTable. | | [`showInfo`](@ref) | Writes info about a signal table to the output stream. | | [`getIndependentSignalNames`](@ref)| Returns the names of the independent signals. | | [`getSignalNames`](@ref) | Returns a string vector of the signal names that are present in a signal table. | | [`hasSignal`](@ref) | Returns `true` if a signal is present in a signal table. | | [`getSignal`](@ref) | Returns signal from a signal table as [`Var`](@ref), [`Par`](@ref) or [`Map`](@ref). | | [`getSignalInfo`](@ref) | Returns signal with :\_typeof, :\_size keys instead of :values/:value keys. | | [`getIndependentSignalsSize`](@ref)| Returns the lengths of the independent signals as Dims. | | [`getValues`](@ref) | Returns the *values* of a [`Var`](@ref) signal from a signal table. | | [`getValuesWithUnit`](@ref) | Returns the *values* of a [`Var`](@ref) signal from a signal table including its unit. | | [`getValue`](@ref) | Returns the *value* of a [`Par`](@ref) signal from a signal table. | | [`getValueWithUnit`](@ref) | Returns the *value* of a [`Par`](@ref) signal from a signal table including its unit. | | [`getFlattenedSignal`](@ref) | Returns a copy of a signal where the values or the value are *flattened* and converted for use in plots or traditional tables. | | [`getDefaultHeading`](@ref) | Returns the default heading for a plot. | | [`signalTableToJSON`](@ref) | Returns a JSON string representation of a signal table. | | [`writeSignalTable`](@ref) | Write a signal table in JSON format on file. | | [`toSignalTable`](@ref) | Returns a signal table as instance of [`SignalTable`](@ref). | | [`signalTableToDataFrame`](@ref) | Returns a signal table as [DataFrame](https://github.com/JuliaData/DataFrames.jl) object. | ```@docs new_signal_table SignalTable showInfo getIndependentSignalNames getSignalNames hasSignal getSignal getSignalInfo getIndependentSignalsSize getValues getValuesWithUnit getValue getValueWithUnit getFlattenedSignal getDefaultHeading signalTableToJSON writeSignalTable toSignalTable signalTableToDataFrame ```
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
docs
2071
# Signals ```@meta CurrentModule = SignalTables ``` The functions below operate on *signals*. !!! note [SignalTables.jl](https://github.com/ModiaSim/SignalTables.jl) exports all symbols of this table.\ [Modia.jl](https://github.com/ModiaSim/Modia.jl) reexports all symbols. | Signal functions | Description | |:--------------------------------|:-------------------------------------------------------------------------------------------| | [`Var`](@ref) | Returns a variable signal definition in form of a dictionary. | | [`Par`](@ref) | Returns a parameter signal definition in form of a dictionary. | | [`Map`](@ref) | Returns an attribute signal definition in form of a dictionary. | | [`isVar`](@ref) | Returns true, if signal is a [`Var`](@ref). | | [`isPar`](@ref) | Returns true, if signal is a [`Par`](@ref). | | [`isMap`](@ref) | Returns true, if signal is a [`Map`](@ref). | | [`isSignal`](@ref) | Returns true, if signal is a [`Var`](@ref), [`Par`](@ref) or [`Map`](@ref). | | [`showSignal`](@ref) | Prints a [`Var`](@ref), [`Par`](@ref) or [`Map`](@ref) signal to io. | | [`eltypeOrType`](@ref) | Returns eltype of an array (but without Missing) and otherwise returns typeof. | | [`quantity`](@ref) | Returns `Unitful.Quantity` from numberType and numberUnit, e.g. `quantity(Float64,u"m/s")` | | [`unitAsParseableString`](@ref) | Returns the unit as a String that can be parsed with `Unitful.uparse`, e.g. "m*s^-1" | ```@docs Var Par Map isVar isPar isMap isSignal showSignal eltypeOrType quantity unitAsParseableString ```
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
docs
1342
# Abstract Plot Interface ```@meta CurrentModule = SignalTablesInterface_PyPlot ``` This chapter documents the *abstract plot interface* for which an implementation has to be provided, in order that the corresponding plot package can be used from the functions of SignalTables to provide plots in a convenient way. For every plot package `XXX.jl` an interface package `SignalTablesInterface_XXX.jl` has to be provided that implements the following functions (with exception of `plot`, all other functions can be just dummy functions; the docu below was generated with [SignalTablesInterface_PyPlot](https://github.com/ModiaSim/SignalTablesInterface_PyPlot.jl)). | Functions | Description | |:---------------------------|:----------------------------------------------------------| | [`plot`](@ref) | Plot signals of a signalTable in multiple diagrams within multiple windows/figures (*required*). | | [`saveFigure`](@ref) | Save figure in different formats on file (*required*). | | [`closeFigure`](@ref) | Close one figure (*required*) | | [`closeAllFigures`](@ref) | Close all figures (*required*) | | [`showFigure`](@ref) | Show figure in window (*required*) |
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.4.4
51d22822acd421c4b99c6c39345a4e3b0e52694e
docs
2435
# Abstract Signal Table Interface ```@meta CurrentModule = SignalTables ``` This chapter documents the *Abstract Signal Table Interface* for which an implementation has to be provided, in order that the functions (see [Overview of Functions](@ref)) of the SignalTables package can be used. A *signal table* is an *ordered dictionary* of *signals* with string keys. The first k entries represent the k independent signals. A *signal* is either a - [`Var`](@ref) dictionary that has a required *:values* key representing a *signal array* of any element type as function of the independent signal(s) (or is the k-th independent variable), or a - [`Par`](@ref) dictionary that has an optional *:value* key representing a constant of any type. A *signal array* has indices `[i1,i2,...,j1,j2,...]` to hold variable elements `[j1,j2,...]` at the `[i1,i2,...]` independent signal(s). If an element of a signal array is *not defined* it has a value of *missing*. In both dictionaries, additional attributes can be stored, for example units, into texts, variability (continuous, clocked, ...), alias. Functions that are marked as *required*, need to be defined for a new signal table type. Functions that are marked as *optional* have a default implementation. | Abstract functions | Description | |:-----------------------------------|:----------------------------------------------------------------------------------------| | [`getIndependentSignalNames`](@ref) | Returns a string vector of the names of the independent signals (*required*). | | [`getSignalNames`](@ref) | Returns a string vector of the signal names from a signal table (*required*). | | [`getSignal`](@ref) | Returns signal from a signal table as [`Var`](@ref) or as [`Par`](@ref) (*required*). | | [`getSignalInfo`](@ref) | Returns signal with :\_typeof, :\_size keys instead of :values/:value key (*optional*). | | [`getIndependentSignalsSize`](@ref)| Returns the lengths of the independent signals as Dims. (*optional*). | | [`getDefaultHeading`](@ref) | Returns the default heading for a plot. (*optional*). | | [`hasSignal`](@ref) | Returns true if signal name is present in signal table. (*optional*). |
SignalTables
https://github.com/ModiaSim/SignalTables.jl.git
[ "MIT" ]
0.2.0
a31133b7c2707f5f9216d3bf0c99c5f034d8342d
code
1932
module ColorBitstring export printbits, printlnbits, binarystring, parsebinary printred(io::IO, x) = print(io, "\x1b[31m" * x * "\x1b[0m") printgreen(io::IO, x) = print(io, "\x1b[32m" * x * "\x1b[0m") printblue(io::IO, x) = print(io, "\x1b[34m" * x * "\x1b[0m") function printbits(io::IO, x::Float16) bts = bitstring(x) printred(io, bts[1:1]) printgreen(io, bts[2:6]) printblue(io, bts[7:end]) end function printbits(io::IO, x::Float32) bts = bitstring(x) printred(io, bts[1:1]) printgreen(io, bts[2:2+8-1]) printblue(io, bts[2+8:end]) end function printbits(io::IO, x::Float64) bts = bitstring(x) printred(io, bts[1:1]) printgreen(io, bts[2:2+11-1]) printblue(io, bts[2+11:end]) end function printbits(io::IO, x::Signed) bts = bitstring(x) printred(io, bts[1:1]) printblue(io, bts[2:end]) end printbits(io::IO, x::Unsigned) = printblue(io, bitstring(x)) printbits(x) = printbits(stdout, x) function printlnbits(x) printbits(x) println() end # routines for other binary binarystring(x) = (signbit(x) ? "-" : "") * "(" * string(abs(x); base=2) * ")_2" function binarystring(x::AbstractFloat) S = precision(x)-1 j = exponent(x) str = string(BigInt(big(2)^S * significand(abs(x))); base=2) str = "2^$j * (" * str[1] * "." * str[2:end] * ")_2" s_str = if x β‰₯Β 0 "" else "-" end s_str * str end function binarystring(x::AbstractIrrational) str = binarystring(big(x)) str[1:end-3] * "…" * ")_2" end function parsebinary(T, str::String) if str[1] == '-' s = -1 str = str[2:end] else s = 1 end j = findfirst(isequal('.'), str) if isnothing(j) s*convert(T, parse(BigInt, str; base=2)) else intpart = parse(BigInt, str[1:j-1] * str[j+1:end]; base=2) convert(T, s * intpart/(big(2)^(length(str)-j))) end end end
ColorBitstring
https://github.com/dlfivefifty/ColorBitstring.jl.git
[ "MIT" ]
0.2.0
a31133b7c2707f5f9216d3bf0c99c5f034d8342d
code
2122
using ColorBitstring, Test @testset "ColorBitstring" begin io = IOBuffer() printbits(io, Float16(1)) @test String(take!(io)) == "\e[31m0\e[0m\e[32m01111\e[0m\e[34m0000000000\e[0m" printbits(io, Float32(1)) @test String(take!(io)) == "\e[31m0\e[0m\e[32m01111111\e[0m\e[34m00000000000000000000000\e[0m" printbits(io, 1.0) @test String(take!(io)) == "\e[31m0\e[0m\e[32m01111111111\e[0m\e[34m0000000000000000000000000000000000000000000000000000\e[0m" printbits(io, 1) end @testset "binarystring" begin @test binarystring(2) == "(10)_2" @test binarystring(-2) == "-(10)_2" @test binarystring(2.0) == "2^1 * (1.0000000000000000000000000000000000000000000000000000)_2" @test binarystring(Float16(2)) == "2^1 * (1.0000000000)_2" @test binarystring(-2.0) == "-2^1 * (1.0000000000000000000000000000000000000000000000000000)_2" @test binarystring(-Float16(2)) == "-2^1 * (1.0000000000)_2" @test binarystring(1/2.0) == "2^-1 * (1.0000000000000000000000000000000000000000000000000000)_2" @test binarystring(1/Float16(2)) == "2^-1 * (1.0000000000)_2" @test binarystring(-1/2.0) == "-2^-1 * (1.0000000000000000000000000000000000000000000000000000)_2" @test binarystring(-1/Float16(2)) == "-2^-1 * (1.0000000000)_2" end @testset "parsebinary" begin @test parsebinary(Float64, "1") ≑ 1.0 @test parsebinary(Float32, "1") ≑ 1.0f0 @test parsebinary(Float64, "-1") ≑ -1.0 @test parsebinary(Float32, "-1") ≑ -1.0f0 @test parsebinary(Float64, "10") ≑ 2.0 @test parsebinary(Float32, "10") ≑ 2.0f0 @test parsebinary(Float64, "-10") ≑ -2.0 @test parsebinary(Float32, "-10") ≑ -2.0f0 @test parsebinary(Float32, "1.") ≑ 1.0f0 @test parsebinary(Float32, "1.") ≑ 1.0f0 @test parsebinary(Float64, "1.001") ≑ 1.125 @test parsebinary(Float32, "1.001") ≑ 1.125f0 @test parsebinary(Float64, "10.001") ≑ 2.125 @test parsebinary(Float32, "10.001") ≑ 2.125f0 @test parsebinary(Float64, ".001") ≑ parsebinary(Float64, "0.001") ≑ 0.125 @test parsebinary(Float64, "-.001") ≑ parsebinary(Float64, "-0.001") ≑ -0.125 end
ColorBitstring
https://github.com/dlfivefifty/ColorBitstring.jl.git
[ "MIT" ]
0.2.0
a31133b7c2707f5f9216d3bf0c99c5f034d8342d
docs
160
# ColorBitstring.jl A Julia package for colorized version of bitstring <img src=https://github.com/dlfivefifty/ColorBitstring.jl/raw/main/images/example.png>
ColorBitstring
https://github.com/dlfivefifty/ColorBitstring.jl.git
[ "MIT" ]
0.1.1
e100c4b8fbd8394f8603216c87e0858959595558
code
361
module GNSSDecoder using DocStringExtensions, GNSSSignals, BitIntegers, ViterbiDecoder, CRC export decode, GPSL1DecoderState, GalileoE1BDecoderState, is_sat_healthy, GNSSDecoderState galCRC24 = crc(spec(24, 0x864cfb, 0x000000, false, false, 0x000000, 0xcde703)) include("gnss.jl") include("bit_fiddling.jl") include("gpsl1.jl") include("galileo_e1b.jl") end
GNSSDecoder
https://github.com/JuliaGNSS/GNSSDecoder.jl.git