licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
375
if Base.libllvm_version >= v"7.0" include(joinpath("gcn", "math.jl")) end include(joinpath("gcn", "indexing.jl")) include(joinpath("gcn", "assertion.jl")) include(joinpath("gcn", "synchronization.jl")) include(joinpath("gcn", "memory_static.jl")) include(joinpath("gcn", "memory_dynamic.jl")) include(joinpath("gcn", "hostcall.jl")) include(joinpath("gcn", "output.jl"))
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
1609
# copied from CUDAnative PR 422 # Gets a pointer to a global with a particular name. If the global # does not exist yet, then it is declared in the global memory address # space. @generated function get_global_pointer(::Val{global_name}, ::Type{T})::AMDGPUnative.DevicePtr{T} where {global_name, T} T_global = convert(LLVMType, T) T_result = convert(LLVMType, Ptr{T}) # Create a thunk that computes a pointer to the global. llvm_f, _ = create_function(T_result) mod = LLVM.parent(llvm_f) # Figure out if the global has been defined already. global_set = LLVM.globals(mod) global_name_string = String(global_name) if haskey(global_set, global_name_string) global_var = global_set[global_name_string] else # If the global hasn't been defined already, then we'll define # it in the global address space, i.e., address space one. global_var = GlobalVariable(mod, T_global, global_name_string, 1) linkage!(global_var, LLVM.API.LLVMExternalLinkage) extinit!(global_var, true) set_used!(mod, global_var) end # Generate IR that computes the global's address. Builder(JuliaContext()) do builder entry = BasicBlock(llvm_f, "entry", JuliaContext()) position!(builder, entry) # Cast the global variable's type to the result type. result = ptrtoint!(builder, global_var, T_result) ret!(builder, result) end # Call the function. quote AMDGPUnative.DevicePtr{T, AMDGPUnative.AS.Global}(convert(Csize_t, $(call_function(llvm_f, Ptr{T})))) end end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
411
# wrappers for LLVM-specific functionality @inline trap() = ccall("llvm.trap", llvmcall, Cvoid, ()) @inline debugtrap() = ccall("llvm.debugtrap", llvmcall, Cvoid, ()) @inline assume(cond::Bool) = Base.llvmcall(("declare void @llvm.assume(i1)", "%cond = icmp eq i8 %0, 1 call void @llvm.assume(i1 %cond) ret void"), Nothing, Tuple{Bool}, cond)
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
7037
# Pointers with address space information # Address spaces export AS, addrspace abstract type AddressSpace end module AS import ..AddressSpace struct Generic <: AddressSpace end struct Global <: AddressSpace end struct Region <: AddressSpace end struct Local <: AddressSpace end struct Constant <: AddressSpace end struct Private <: AddressSpace end end # module # Device pointer """ DevicePtr{T,A} """ DevicePtr if sizeof(Ptr{Cvoid}) == 8 primitive type DevicePtr{T,A} <: Ref{T} 64 end else primitive type DevicePtr{T,A} <: Ref{T} 32 end end # constructors DevicePtr{T,A}(x::Union{Int,UInt,Ptr,DevicePtr}) where {T,A<:AddressSpace} = Base.bitcast(DevicePtr{T,A}, x) DevicePtr{T}(ptr::Ptr{T}) where {T} = DevicePtr{T,AS.Generic}(ptr) DevicePtr(ptr::Ptr{T}) where {T} = DevicePtr{T,AS.Generic}(ptr) # getters Base.eltype(::Type{<:DevicePtr{T}}) where {T} = T addrspace(x::DevicePtr) = addrspace(typeof(x)) addrspace(::Type{DevicePtr{T,A}}) where {T,A} = A # conversions # to and from integers # pointer to integer Base.convert(::Type{T}, x::DevicePtr) where {T<:Integer} = T(UInt(x)) # integer to pointer Base.convert(::Type{DevicePtr{T,A}}, x::Union{Int,UInt}) where {T,A<:AddressSpace} = DevicePtr{T,A}(x) Int(x::DevicePtr) = Base.bitcast(Int, x) UInt(x::DevicePtr) = Base.bitcast(UInt, x) # between host and device pointers Base.convert(::Type{Ptr{T}}, p::DevicePtr) where {T} = Base.bitcast(Ptr{T}, p) Base.convert(::Type{DevicePtr{T,A}}, p::Ptr) where {T,A<:AddressSpace} = Base.bitcast(DevicePtr{T,A}, p) Base.convert(::Type{DevicePtr{T}}, p::Ptr) where {T} = Base.bitcast(DevicePtr{T,AS.Generic}, p) # between CPU pointers, for the purpose of working with `ccall` Base.unsafe_convert(::Type{Ptr{T}}, x::DevicePtr{T}) where {T} = reinterpret(Ptr{T}, x) # between device pointers Base.convert(::Type{<:DevicePtr}, p::DevicePtr) = throw(ArgumentError("cannot convert between incompatible device pointer types")) Base.convert(::Type{DevicePtr{T,A}}, p::DevicePtr{T,A}) where {T,A} = p Base.unsafe_convert(::Type{DevicePtr{T,A}}, p::DevicePtr) where {T,A} = Base.bitcast(DevicePtr{T,A}, p) # identical addrspaces Base.convert(::Type{DevicePtr{T,A}}, p::DevicePtr{U,A}) where {T,U,A} = Base.unsafe_convert(DevicePtr{T,A}, p) # convert to & from generic Base.convert(::Type{DevicePtr{T,AS.Generic}}, p::DevicePtr) where {T} = Base.unsafe_convert(DevicePtr{T,AS.Generic}, p) Base.convert(::Type{DevicePtr{T,A}}, p::DevicePtr{U,AS.Generic}) where {T,U,A} = Base.unsafe_convert(DevicePtr{T,A}, p) Base.convert(::Type{DevicePtr{T,AS.Generic}}, p::DevicePtr{T,AS.Generic}) where {T} = p # avoid ambiguities # unspecified, preserve source addrspace Base.convert(::Type{DevicePtr{T}}, p::DevicePtr{U,A}) where {T,U,A} = Base.unsafe_convert(DevicePtr{T,A}, p) # limited pointer arithmetic & comparison isequal(x::DevicePtr, y::DevicePtr) = (x === y) && addrspace(x) == addrspace(y) isless(x::DevicePtr{T,A}, y::DevicePtr{T,A}) where {T,A<:AddressSpace} = x < y Base.:(==)(x::DevicePtr, y::DevicePtr) = UInt(x) == UInt(y) && addrspace(x) == addrspace(y) Base.:(<)(x::DevicePtr, y::DevicePtr) = UInt(x) < UInt(y) Base.:(-)(x::DevicePtr, y::DevicePtr) = UInt(x) - UInt(y) Base.:(+)(x::DevicePtr, y::Integer) = oftype(x, Base.add_ptr(UInt(x), (y % UInt) % UInt)) Base.:(-)(x::DevicePtr, y::Integer) = oftype(x, Base.sub_ptr(UInt(x), (y % UInt) % UInt)) Base.:(+)(x::Integer, y::DevicePtr) = y + x # memory operations @static if Base.libllvm_version < v"7.0" # Old values (LLVM 6) Base.convert(::Type{Int}, ::Type{AS.Private}) = 0 Base.convert(::Type{Int}, ::Type{AS.Global}) = 1 Base.convert(::Type{Int}, ::Type{AS.Constant}) = 2 Base.convert(::Type{Int}, ::Type{AS.Local}) = 3 Base.convert(::Type{Int}, ::Type{AS.Generic}) = 4 Base.convert(::Type{Int}, ::Type{AS.Region}) = 5 else # New values (LLVM 7+) Base.convert(::Type{Int}, ::Type{AS.Generic}) = 0 Base.convert(::Type{Int}, ::Type{AS.Global}) = 1 Base.convert(::Type{Int}, ::Type{AS.Region}) = 2 Base.convert(::Type{Int}, ::Type{AS.Local}) = 3 Base.convert(::Type{Int}, ::Type{AS.Constant}) = 4 Base.convert(::Type{Int}, ::Type{AS.Private}) = 5 end function tbaa_make_child(name::String, constant::Bool=false; ctx::LLVM.Context=JuliaContext()) tbaa_root = MDNode([MDString("roctbaa", ctx)], ctx) tbaa_struct_type = MDNode([MDString("roctbaa_$name", ctx), tbaa_root, LLVM.ConstantInt(0, ctx)], ctx) tbaa_access_tag = MDNode([tbaa_struct_type, tbaa_struct_type, LLVM.ConstantInt(0, ctx), LLVM.ConstantInt(constant ? 1 : 0, ctx)], ctx) return tbaa_access_tag end tbaa_addrspace(as::Type{<:AddressSpace}) = tbaa_make_child(lowercase(String(as.name.name))) @generated function Base.unsafe_load(p::DevicePtr{T,A}, i::Integer=1, ::Val{align}=Val(1)) where {T,A,align} eltyp = convert(LLVMType, T) T_int = convert(LLVMType, Int) T_ptr = convert(LLVMType, DevicePtr{T,A}) T_actual_ptr = LLVM.PointerType(eltyp, convert(Int, A)) # create a function param_types = [T_ptr, T_int] llvm_f, _ = create_function(eltyp, param_types) # generate IR Builder(JuliaContext()) do builder entry = BasicBlock(llvm_f, "entry", JuliaContext()) position!(builder, entry) ptr = inttoptr!(builder, parameters(llvm_f)[1], T_actual_ptr) ptr = gep!(builder, ptr, [parameters(llvm_f)[2]]) ld = load!(builder, ptr) if A != AS.Generic metadata(ld)[LLVM.MD_tbaa] = tbaa_addrspace(A) end alignment!(ld, align) ret!(builder, ld) end call_function(llvm_f, T, Tuple{DevicePtr{T,A}, Int}, :((p, Int(i-one(i))))) end @generated function Base.unsafe_store!(p::DevicePtr{T,A}, x, i::Integer=1, ::Val{align}=Val(1)) where {T,A,align} eltyp = convert(LLVMType, T) T_int = convert(LLVMType, Int) T_ptr = convert(LLVMType, DevicePtr{T,A}) T_actual_ptr = LLVM.PointerType(eltyp, convert(Int, A)) # create a function param_types = [T_ptr, eltyp, T_int] llvm_f, _ = create_function(LLVM.VoidType(JuliaContext()), param_types) # generate IR Builder(JuliaContext()) do builder entry = BasicBlock(llvm_f, "entry", JuliaContext()) position!(builder, entry) ptr = inttoptr!(builder, parameters(llvm_f)[1], T_actual_ptr) ptr = gep!(builder, ptr, [parameters(llvm_f)[3]]) val = parameters(llvm_f)[2] st = store!(builder, val, ptr) if A != AS.Generic metadata(st)[LLVM.MD_tbaa] = tbaa_addrspace(A) end alignment!(st, align) ret!(builder) end call_function(llvm_f, Cvoid, Tuple{DevicePtr{T,A}, T, Int}, :((p, convert(T,x), Int(i-one(i))))) end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
4027
# ROCm-specific runtime libraries ## GPU runtime library # reset the runtime cache from global scope, so that any change triggers recompilation GPUCompiler.reset_runtime() # load or build the runtime for the most likely compilation job given a compute capability function load_runtime(dev_isa::String) target = GCNCompilerTarget(; dev_isa=dev_isa) dummy_source = FunctionSpec(()->return, Tuple{}) params = ROCCompilerParams() job = CompilerJob(target, dummy_source, params) GPUCompiler.load_runtime(job) end #@inline exception_flag() = ccall("extern julia_exception_flag", llvmcall, Ptr{Cvoid}, ()) function signal_exception() #= ptr = exception_flag() if ptr !== C_NULL unsafe_store!(convert(Ptr{Int}, ptr), 1) threadfence_system() else @rocprintf(""" WARNING: could not signal exception status to the host, execution will continue. Please file a bug. """) end =# return end function report_exception(ex) #= @rocprintf(""" ERROR: a %s was thrown during kernel execution. Run Julia on debug level 2 for device stack traces. """, ex) =# return end report_oom(sz) = nothing #@rocprintf("ERROR: Out of dynamic GPU memory (trying to allocate %i bytes)\n", sz) function report_exception_name(ex) #= @rocprintf(""" ERROR: a %s was thrown during kernel execution. Stacktrace: """, ex) =# return end function report_exception_frame(idx, func, file, line) #@rocprintf(" [%i] %s at %s:%i\n", idx, func, file, line) return end ## ROCm device library const libcache = Dict{String, LLVM.Module}() function load_device_libs(dev_isa) device_libs_path === nothing && return isa_short = replace(dev_isa, "gfx"=>"") device_libs = LLVM.Module[] bitcode_files = ( "hc.amdgcn.bc", "hip.amdgcn.bc", "irif.amdgcn.bc", "ockl.amdgcn.bc", "oclc_isa_version_$isa_short.amdgcn.bc", "opencl.amdgcn.bc", "ocml.amdgcn.bc", ) for file in bitcode_files ispath(joinpath(device_libs_path, file)) || continue name, ext = splitext(file) lib = get!(libcache, name) do file_path = joinpath(device_libs_path, file) open(file_path) do io parse(LLVM.Module, read(file_path), JuliaContext()) end end push!(device_libs, lib) end @assert !isempty(device_libs) "No device libs detected!" return device_libs end function link_device_libs!(mod::LLVM.Module, dev_isa::String, undefined_fns) libs::Vector{LLVM.Module} = load_device_libs(dev_isa) # TODO: only link if used # TODO: make these globally/locally configurable link_oclc_defaults!(mod, dev_isa) for lib in libs # override libdevice's triple and datalayout to avoid warnings triple!(lib, triple(mod)) datalayout!(lib, datalayout(mod)) end GPUCompiler.link_library!(mod, libs) end function link_oclc_defaults!(mod::LLVM.Module, dev_isa::String; finite_only=false, unsafe_math=false, correctly_rounded_sqrt=true, daz=false) # link in some defaults for OCLC knobs, to prevent undefined variable errors lib = LLVM.Module("OCLC") triple!(lib, triple(mod)) datalayout!(lib, datalayout(mod)) isa_short = replace(dev_isa, "gfx"=>"") for (name,value) in ( "__oclc_ISA_version"=>parse(Int32, isa_short), "__oclc_finite_only_opt"=>Int32(finite_only), "__oclc_unsafe_math_opt"=>Int32(unsafe_math), "__oclc_correctly_rounded_sqrt32"=>Int32(correctly_rounded_sqrt), "__oclc_daz_opt"=>Int32(daz)) gvtype = convert(LLVMType, typeof(value)) gv = GlobalVariable(lib, gvtype, name, 4) init = ConstantInt(Int32(0), JuliaContext()) initializer!(gv, init) unnamed_addr!(gv, true) constant!(gv, true) end link!(mod, lib) end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
10978
# Tools for implementing device functionality # which Julia types map to a given LLVM type const llvmtypes = Dict{Type,Symbol}( Nothing => :void, Int8 => :i8, Int16 => :i16, Int32 => :i32, Int64 => :i64, Float32 => :float, Float64 => :double, ) # which LLVM types map to a given Julia type const jltypes = Dict{Symbol,Type}( :void => Nothing, :i8 => Int8, :i16 => Int16, :i32 => Int32, :i64 => Int64, :float => Float32, :double => Float64 ) # which Julia types map to a given ROC lib type const fntypes = Dict{Type,Symbol}( Nothing => :void, Int8 => :i8, Int16 => :i16, Int32 => :i32, Int64 => :i64, Float16 => :f16, Float32 => :f32, Float64 => :f64 ) # Decode an expression of the form: # # function(arg::arg_type, arg::arg_type, ... arg::arg_type)::return_type # # Returns a tuple containing the function name, a vector of argument, a vector of argument # types and the return type (all in symbolic form). function decode_call(e) @assert e.head == :(::) # decode the return type expression: single symbol (the LLVM type), or a tuple of 2 # symbols (the LLVM and corresponding Julia type) retspec = e.args[2] if isa(retspec, Symbol) rettype = retspec else @assert retspec.head == :tuple @assert length(retspec.args) == 2 rettype = (retspec.args[1], retspec.args[2]) end call = e.args[1] @assert call.head == :call fn = Symbol(call.args[1]) args = Symbol[arg.args[1] for arg in call.args[2:end]] argtypes = Symbol[arg.args[2] for arg in call.args[2:end]] return fn, args, argtypes, rettype end # Generate a `llvmcall` statement calling an intrinsic specified as follows: # # intrinsic(arg::arg_type, arg::arg_type, ... arg::arg_type)::return_type [attr] # # The argument types should be valid LLVM type identifiers (eg. i32, float, double). # Conversions to the corresponding Julia type are automatically generated; make sure the # actual arguments are of the same type to make these conversions no-ops. The optional # argument `attr` indicates which LLVM function attributes (such as `readnone` or `nounwind`) # to add to the intrinsic declaration. # For example, the following call: # `@wrap __some_intrinsic(x::float, y::double)::float` # # will yield the following `llvmcall`: # ``` # Base.llvmcall(("declare float @__somme__intr(float, double)", # "%3 = call float @__somme__intr(float %0, double %1) # ret float %3"), # Float32, Tuple{Float32,Float64}, # convert(Float32,x), convert(Float64,y)) # ``` macro wrap(call, attrs="") intrinsic, args, argtypes, rettype = decode_call(call) # decide on intrinsic return type if isa(rettype, Symbol) # only LLVM return type specified, match against known LLVM/Julia type combinations llvm_ret_typ = rettype julia_ret_typ = jltypes[rettype] else # both specified (for when there is a mismatch, eg. i32 -> UInt32) llvm_ret_typ = rettype[1] julia_ret_typ = rettype[2] end llvm_args = String["%$i" for i in 0:length(argtypes)] if llvm_ret_typ == :void llvm_ret_asgn = "" llvm_ret = "void" else llvm_ret_var = "%$(length(argtypes)+1)" llvm_ret_asgn = "$llvm_ret_var = " llvm_ret = "$llvm_ret_typ $llvm_ret_var" end llvm_declargs = join(argtypes, ", ") llvm_defargs = join(("$t $arg" for (t,arg) in zip(argtypes, llvm_args)), ", ") julia_argtypes = (jltypes[t] for t in argtypes) julia_args = (:(convert($argtype, $(esc(arg)))) for (arg, argtype) in zip(args, julia_argtypes)) dest = ("""declare $llvm_ret_typ @$intrinsic($llvm_declargs)""", """$llvm_ret_asgn call $llvm_ret_typ @$intrinsic($llvm_defargs) ret $llvm_ret""") return quote Base.llvmcall($dest, $julia_ret_typ, Tuple{$(julia_argtypes...)}, $(julia_args...)) end end # julia.h: jl_datatype_align Base.@pure function datatype_align(::Type{T}) where {T} # typedef struct { # uint32_t nfields; # uint32_t alignment : 9; # uint32_t haspadding : 1; # uint32_t npointers : 20; # uint32_t fielddesc_type : 2; # } jl_datatype_layout_t; field = T.layout + sizeof(UInt32) unsafe_load(convert(Ptr{UInt16}, field)) & convert(Int16, 2^9-1) end # generalization of word-based primitives # extract bits from a larger value @inline function extract_word(val, ::Val{i}) where {i} extract_value(val, UInt32, Val(32*(i-1))) end @generated function extract_value(val, ::Type{sub}, ::Val{offset}) where {sub, offset} T_val = convert(LLVMType, val) T_sub = convert(LLVMType, sub) bytes = Core.sizeof(val) T_int = LLVM.IntType(8*bytes, JuliaContext()) # create function llvm_f, _ = create_function(T_sub, [T_val]) mod = LLVM.parent(llvm_f) # generate IR Builder(JuliaContext()) do builder entry = BasicBlock(llvm_f, "entry", JuliaContext()) position!(builder, entry) equiv = bitcast!(builder, parameters(llvm_f)[1], T_int) shifted = lshr!(builder, equiv, LLVM.ConstantInt(T_int, offset)) # extracted = and!(builder, shifted, 2^32-1) extracted = trunc!(builder, shifted, T_sub) ret!(builder, extracted) end call_function(llvm_f, UInt32, Tuple{val}, :( (val,) )) end # insert bits into a larger value @inline function insert_word(val, word::UInt32, ::Val{i}) where {i} insert_value(val, word, Val(32*(i-1))) end @generated function insert_value(val, sub, ::Val{offset}) where {offset} T_val = convert(LLVMType, val) T_sub = convert(LLVMType, sub) bytes = Core.sizeof(val) T_out_int = LLVM.IntType(8*bytes, JuliaContext()) # create function llvm_f, _ = create_function(T_val, [T_val, T_sub]) mod = LLVM.parent(llvm_f) # generate IR Builder(JuliaContext()) do builder entry = BasicBlock(llvm_f, "entry", JuliaContext()) position!(builder, entry) equiv = bitcast!(builder, parameters(llvm_f)[1], T_out_int) ext = zext!(builder, parameters(llvm_f)[2], T_out_int) shifted = shl!(builder, ext, LLVM.ConstantInt(T_out_int, offset)) inserted = or!(builder, equiv, shifted) orig = bitcast!(builder, inserted, T_val) ret!(builder, orig) end call_function(llvm_f, val, Tuple{val, sub}, :( (val, sub) )) end # split the invocation of a function `op` on a value `val` with non-struct eltype # into multiple smaller invocations on byte-sized partial values. @generated function split_value_invocation(op::Function, val, args...) # TODO: control of lower-limit ex = quote Base.@_inline_meta end # disassemble into words words = Symbol[] for i in 1:Core.sizeof(val)Γ·4 word = Symbol("word$i") push!(ex.args, :( $word = extract_word(val, Val($i)) )) push!(words, word) end # perform the operation for word in words push!(ex.args, :( $word = op($word, args...)) ) end # reassemble push!(ex.args, :( out = zero(val) )) for (i,word) in enumerate(words) push!(ex.args, :( out = insert_word(out, $word, Val($i)) )) end push!(ex.args, :( out )) return ex end # split the invocation of a function `op` on a value `val` # by invoking the function on each of its fields @generated function recurse_value_invocation(op::Function, val, args...) ex = quote Base.@_inline_meta end fields = fieldnames(val) if isempty(fields) push!(ex.args, :( split_value_invocation(op, val, args...) )) else ctor = Expr(:new, val) for field in fields push!(ctor.args, :( recurse_value_invocation(op, getfield(val, $(QuoteNode(field))), args...) )) end push!(ex.args, ctor) end return ex end # split the invocation of a function `op` on a pointer `ptr` with non-struct eltype # into multiple smaller invocations on any supported pointer as listed in `supported_ptrs`. @generated function split_pointer_invocation(op::Function, ptr, ::Type{supported_ptrs}, args...) where {supported_ptrs} T = eltype(ptr) elsize(x) = Core.sizeof(eltype(x)) supported_ptrs = reverse(Base.uniontypes(supported_ptrs)) ex = quote Base.@_inline_meta end # disassemble vals = Tuple{Symbol,Int,Type}[] offset = 0 while offset < Core.sizeof(T) val = Symbol("value.$(length(vals)+1)") # greedy selection of next pointer type remaining = Core.sizeof(T)-offset valid = filter(ptr->elsize(ptr)<=remaining, supported_ptrs) if isempty(valid) error("Cannot partition $T into values of $supported_typs") end ptr = first(sort(collect(valid); by=elsize, rev=true)) push!(vals, (val, offset, ptr)) offset += elsize(ptr) end # perform the operation for (val, offset, ptr) in vals subptr = :(convert($ptr, ptr+$offset)) push!(ex.args, :( $val = op($subptr, args...)) ) end # reassemble push!(ex.args, :( out = zero($T) )) for (val, offset, ptr) in vals push!(ex.args, :( out = insert_value(out, $val, Val($offset)) )) end push!(ex.args, :( out )) return ex end # split the invocation of a function `op` on a pointer `ptr` # by invoking the function on a pointer to each of its fields @generated function recurse_pointer_invocation(op::Function, ptr, ::Type{supported_ptrs}, args...) where {supported_ptrs} T = eltype(ptr) ex = quote Base.@_inline_meta end fields = fieldnames(T) if isempty(fields) push!(ex.args, :( split_pointer_invocation(op, ptr, supported_ptrs, args...) )) else ctor = Expr(:new, T) for (i,field) in enumerate(fields) field_typ = fieldtype(T, i) field_offset = fieldoffset(T, i) field_ptr_typ = :($(ptr.name.wrapper){$field_typ}) # NOTE: this ctor is a leap of faith subptr = :(convert($field_ptr_typ, ptr+$field_offset)) push!(ctor.args, :( recurse_pointer_invocation(op, $subptr, supported_ptrs, args...) )) end push!(ex.args, ctor) end return ex end # calculate the size of an LLVM type llvmsize(::LLVM.LLVMHalf) = sizeof(Float16) llvmsize(::LLVM.LLVMFloat) = sizeof(Float32) llvmsize(::LLVM.LLVMDouble) = sizeof(Float64) llvmsize(::LLVM.IntegerType) = div(Int(intwidth(GenericValue(LLVM.Int128Type(), -1))), 8) llvmsize(ty::LLVM.ArrayType) = length*llvmsize(eltype(ty)) # TODO: VectorType, StructType, PointerType llvmsize(ty) = error("Unknown size for type: $ty, typeof: $(typeof(ty))")
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
2776
# Assertion (B.19) export @rocassert """ @rocassert cond [text] Signal assertion failure if `cond` is `false`. Preferred syntax for writing assertions, mimicking `Base.@assert`. Message `text` is optionally displayed upon assertion failure. !!! warning A failed assertion will crash the GPU, so use sparingly as a debugging tool. Furthermore, the assertion might be disabled at various optimization levels, and thus should not cause any side-effects. """ macro rocassert(ex, msgs...) # message handling copied from Base.@assert msg = isempty(msgs) ? ex : msgs[1] if isa(msg, AbstractString) msg = msg # pass-through elseif !isempty(msgs) && (isa(msg, Expr) || isa(msg, Symbol)) # message is an expression needing evaluating msg = :(Main.Base.string($(esc(msg)))) elseif isdefined(Main, :Base) && isdefined(Main.Base, :string) && applicable(Main.Base.string, msg) msg = Main.Base.string(msg) else # string() might not be defined during bootstrap msg = :(Main.Base.string($(Expr(:quote,msg)))) end return :($(esc(ex)) ? $(nothing) : rocassert_fail($(Val(Symbol(msg))), $(Val(__source__.file)), $(Val(__source__.line)))) end assert_counter = 0 @generated function rocassert_fail(::Val{msg}, ::Val{file}, ::Val{line}) where {msg, file, line} T_void = LLVM.VoidType(JuliaContext()) T_int32 = LLVM.Int32Type(JuliaContext()) T_pint8 = LLVM.PointerType(LLVM.Int8Type(JuliaContext())) # create function llvm_f, _ = create_function() mod = LLVM.parent(llvm_f) # generate IR Builder(JuliaContext()) do builder entry = BasicBlock(llvm_f, "entry", JuliaContext()) position!(builder, entry) global assert_counter assert_counter += 1 message = globalstring_ptr!(builder, String(msg), "assert_message_$(assert_counter)") file = globalstring_ptr!(builder, String(file), "assert_file_$(assert_counter)") line = ConstantInt(T_int32, line) func = globalstring_ptr!(builder, "unknown", "assert_function_$(assert_counter)") charSize = ConstantInt(Csize_t(1), JuliaContext()) # invoke __assertfail and return # TODO: mark noreturn since we don't use ptxas? assertfail_typ = LLVM.FunctionType(T_void, [T_pint8, T_pint8, T_int32, T_pint8, llvmtype(charSize)]) assertfail = LLVM.Function(mod, "__assertfail", assertfail_typ) call!(builder, assertfail, [message, file, line, func, charSize]) ret!(builder) end call_function(llvm_f, Nothing, Tuple{}) end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
9958
import HSARuntime: HSASignal export HostCall, hostcall! const SENTINEL_COUNTER = Ref{Int}(2) const SENTINEL_LOCK = ReentrantLock() const DEFAULT_HOSTCALL_LATENCY = 0.01 """ HostCall{S,RT,AT} GPU-compatible struct for making hostcalls. """ struct HostCall{S,RT,AT} signal::S host_sentinel::Int device_sentinel::Int buf_ptr::DevicePtr{UInt8,AS.Global} buf_len::UInt end function HostCall(RT::Type, AT::Type{<:Tuple}, signal::S; agent=HSARuntime.get_default_agent()) where S @assert S == UInt64 # TODO: Just use atomic_add! host_sentinel, device_sentinel = lock(SENTINEL_LOCK) do host_sentinel = SENTINEL_COUNTER[] SENTINEL_COUNTER[] += 1 device_sentinel = SENTINEL_COUNTER[] SENTINEL_COUNTER[] += 1 if SENTINEL_COUNTER[] > typemax(Int64)-2 SENTINEL_COUNTER[] = 2 @debug "Sentinel counter wrapped around!" end return host_sentinel, device_sentinel end buf_len = 0 for T in AT.parameters @assert isbitstype(T) "Hostcall arguments must be bits-type" buf_len += sizeof(T) end buf_len = max(sizeof(UInt64), buf_len) # make room for return buffer pointer buf = Mem.alloc(agent, buf_len) buf_ptr = DevicePtr{UInt8,AS.Global}(Base.unsafe_convert(Ptr{UInt8}, buf)) HostCall{S,RT,AT}(signal, host_sentinel, device_sentinel, buf_ptr, buf_len) end ## device signal functions # TODO: device_signal_load, device_signal_add!, etc. @inline @generated function device_signal_store!(signal::UInt64, value::Int64) T_nothing = convert(LLVMType, Nothing) T_i32 = LLVM.Int32Type(JuliaContext()) T_i64 = LLVM.Int64Type(JuliaContext()) # create a function llvm_f, _ = create_function(T_nothing, [T_i64, T_i64]) mod = LLVM.parent(llvm_f) # generate IR Builder(JuliaContext()) do builder entry = BasicBlock(llvm_f, "entry", JuliaContext()) position!(builder, entry) T_signal_store = LLVM.FunctionType(T_nothing, [T_i64, T_i64, T_i32]) signal_store = LLVM.Function(mod, "__ockl_hsa_signal_store", T_signal_store) call!(builder, signal_store, [parameters(llvm_f)[1], parameters(llvm_f)[2], # __ATOMIC_RELEASE == 3 ConstantInt(Int32(3), JuliaContext())]) ret!(builder) end call_function(llvm_f, Nothing, Tuple{UInt64,Int64}, :((signal,value))) end @inline @generated function device_signal_wait(signal::UInt64, value::Int64) T_nothing = convert(LLVMType, Nothing) T_i32 = LLVM.Int32Type(JuliaContext()) T_i64 = LLVM.Int64Type(JuliaContext()) # create a function llvm_f, _ = create_function(T_nothing, [T_i64, T_i64]) mod = LLVM.parent(llvm_f) # generate IR Builder(JuliaContext()) do builder entry = BasicBlock(llvm_f, "entry", JuliaContext()) signal_match = BasicBlock(llvm_f, "signal_match", JuliaContext()) signal_miss = BasicBlock(llvm_f, "signal_miss", JuliaContext()) position!(builder, entry) br!(builder, signal_miss) position!(builder, signal_miss) T_sleep = LLVM.FunctionType(T_nothing, [T_i32]) sleep_f = LLVM.Function(mod, "llvm.amdgcn.s.sleep", T_sleep) call!(builder, sleep_f, [ConstantInt(Int32(1), JuliaContext())]) T_signal_load = LLVM.FunctionType(T_i64, [T_i64, T_i32]) signal_load = LLVM.Function(mod, "__ockl_hsa_signal_load", T_signal_load) loaded_value = call!(builder, signal_load, [parameters(llvm_f)[1], # __ATOMIC_ACQUIRE == 2 ConstantInt(Int32(2), JuliaContext())]) cond = icmp!(builder, LLVM.API.LLVMIntEQ, loaded_value, parameters(llvm_f)[2]) br!(builder, cond, signal_match, signal_miss) position!(builder, signal_match) ret!(builder) end call_function(llvm_f, Nothing, Tuple{UInt64,Int64}, :((signal,value))) end "Calls the host function stored in `hc` with arguments `args`." @inline @generated function hostcall!(hc::HostCall{UInt64,RT,AT}, args...) where {RT,AT} ex = Expr(:block) # Copy arguments into buffer # Modified from CUDAnative src/device/cuda/dynamic_parallelism.jl off = 1 for i in 1:length(args) T = args[i] sz = sizeof(T) # TODO: Should we do what CUDAnative does instead? ptr = :(Base.unsafe_convert(DevicePtr{$T,AS.Global}, hc.buf_ptr+$off-1)) push!(ex.args, :(Base.unsafe_store!($ptr, args[$i]))) off += sz end # Ring the doorbell push!(ex.args, :($device_signal_store!(hc.signal, hc.device_sentinel))) if RT === Nothing # Async hostcall push!(ex.args, :(nothing)) else # Wait on doorbell (hc.host_sentinel) push!(ex.args, :($device_signal_wait(hc.signal, hc.host_sentinel))) # Get return buffer and load first value ptr = :(Base.unsafe_convert(DevicePtr{DevicePtr{$RT,AS.Global},AS.Global}, hc.buf_ptr)) push!(ex.args, :(Base.unsafe_load(Base.unsafe_load($ptr)))) end return ex end ## hostcall @generated function _hostcall_args(hc::HostCall{UInt64,RT,AT}) where {RT,AT} ex = Expr(:tuple) # Copy arguments into buffer off = 1 for i in 1:length(AT.parameters) T = AT.parameters[i] sz = sizeof(T) # TODO: Should we do what CUDAnative does instead? ptr = :(Base.unsafe_convert(DevicePtr{$T,AS.Global}, hc.buf_ptr+$off-1)) # FIXME: We should not be using a device intrinsic here, even though it works... push!(ex.args, :(Base.unsafe_load($ptr))) off += sz end return ex end struct HostCallException <: Exception reason::String end """ HostCall(func, return_type::Type, arg_types::Type{Tuple}) -> HostCall Construct a `HostCall` that executes `func` with the arguments passed from the calling kernel. `func` must be passed arguments of types contained in `arg_types`, and must return a value of type `return_type`, or else the hostcall will fail with undefined behavior. Note: This API is currently experimental and is subject to change at any time. """ function HostCall(func, rettype, argtypes; return_task=false, agent=HSARuntime.get_default_agent(), maxlat=DEFAULT_HOSTCALL_LATENCY, continuous=false) signal = HSASignal() hc = HostCall(rettype, argtypes, signal.signal[].handle; agent=agent) tsk = @async begin ret_buf = Ref{Mem.Buffer}() try while true try _hostwait(signal.signal[], hc.device_sentinel; maxlat=maxlat) catch err throw(HostCallException("Hostcall: Error during hostwait")) end if length(argtypes.parameters) > 0 args = try _hostcall_args(hc) catch err throw(HostCallException("Hostcall: Error getting arguments")) end @debug "Hostcall: Got arguments of length $(length(args))" else args = () end ret = try func(args...,) catch err throw(HostCallException("Hostcall: Error executing host function")) end rettype === Nothing && return if typeof(ret) != rettype throw(HostCallException("Hostcall: Host function result of wrong type: $(typeof(ret)), expected $rettype")) end if !isbits(ret) throw(HostCallException("Hostcall: Host function result not isbits: $(typeof(ret))")) end @debug "Hostcall: Host function returning value of type $(typeof(ret))" try ret_len = sizeof(ret) ret_buf = Mem.alloc(agent, ret_len) ret_buf_ptr = Base.unsafe_convert(Ptr{typeof(ret)}, ret_buf) Base.unsafe_store!(ret_buf_ptr, ret) ret_buf_ptr = Base.unsafe_convert(Ptr{UInt64}, ret_buf) args_buf_ptr = convert(Ptr{UInt64}, hc.buf_ptr) Base.unsafe_store!(args_buf_ptr, ret_buf_ptr) HSA.signal_store_release(signal.signal[], hc.host_sentinel) catch err throw(HostCallException("Hostcall: Error returning hostcall result")) end @debug "Hostcall: Host function return completed" continuous || break end catch err @error "Hostcall error" exception=(err,catch_backtrace()) rethrow(err) finally # TODO: This is probably a bad idea to free while the kernel might # still hold a reference. We should probably have some way to # reference count these buffers from kernels (other than just # using a ROCArray, which can't currently be serialized to the # GPU). if isassigned(ret_buf) Mem.free(ret_buf) end Mem.free(hc.buf_ptr) end end if return_task return hc, tsk else return hc end end # CPU functions get_value(hc::HostCall{UInt64,RT,AT} where {RT,AT}) = HSA.signal_load_scacquire(HSA.Signal(hc.signal)) function _hostwait(signal, sentinel; maxlat=DEFAULT_HOSTCALL_LATENCY) @debug "Hostcall: Waiting on signal for sentinel: $sentinel" while true value = HSA.signal_load_scacquire(signal) if value == sentinel @debug "Hostcall: Signal triggered with sentinel: $sentinel" return end sleep(maxlat) end end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
5822
# Indexing and dimensions export workitemIdx, workgroupIdx, workgroupDim, gridDim, gridDimWG export threadIdx, blockIdx, blockDim @generated function _index(::Val{fname}, ::Val{name}, ::Val{range}) where {fname, name, range} T_int32 = LLVM.Int32Type(JuliaContext()) # create function llvm_f, _ = create_function(T_int32) mod = LLVM.parent(llvm_f) # generate IR Builder(JuliaContext()) do builder entry = BasicBlock(llvm_f, "entry", JuliaContext()) position!(builder, entry) # call the indexing intrinsic intr_typ = LLVM.FunctionType(T_int32) intr = LLVM.Function(mod, "llvm.amdgcn.$fname.id.$name", intr_typ) idx = call!(builder, intr) # attach range metadata range_metadata = MDNode([ConstantInt(Int32(range.start), JuliaContext()), ConstantInt(Int32(range.stop), JuliaContext())], JuliaContext()) metadata(idx)[LLVM.MD_range] = range_metadata ret!(builder, idx) end call_function(llvm_f, UInt32) end @generated function _dim(::Val{base}, ::Val{off}, ::Val{range}, ::Type{T}) where {base, off, range, T} T_int8 = LLVM.Int8Type(JuliaContext()) T_int32 = LLVM.Int32Type(JuliaContext()) _as = Base.libllvm_version < v"7.0" ? 2 : 4 T_ptr_i8 = LLVM.PointerType(T_int8, _as) T_ptr_i32 = LLVM.PointerType(T_int32, _as) T_ptr_T = LLVM.PointerType(convert(LLVMType, T), _as) # create function llvm_f, _ = create_function(T_int32) mod = LLVM.parent(llvm_f) # generate IR Builder(JuliaContext()) do builder entry = BasicBlock(llvm_f, "entry", JuliaContext()) position!(builder, entry) # get the kernel dispatch pointer intr_typ = LLVM.FunctionType(T_ptr_i8) intr = LLVM.Function(mod, "llvm.amdgcn.dispatch.ptr", intr_typ) ptr = call!(builder, intr) # load the index offset = base+((off-1)*sizeof(T)) idx_ptr_i8 = inbounds_gep!(builder, ptr, [ConstantInt(offset,JuliaContext())]) idx_ptr_T = bitcast!(builder, idx_ptr_i8, T_ptr_T) idx_T = load!(builder, idx_ptr_T) idx = zext!(builder, idx_T, T_int32) # attach range metadata range_metadata = MDNode([ConstantInt(T(range.start), JuliaContext()), ConstantInt(T(range.stop), JuliaContext())], JuliaContext()) metadata(idx_T)[LLVM.MD_range] = range_metadata ret!(builder, idx) end call_function(llvm_f, UInt32) end # TODO: look these up for the current agent/queue const max_block_size = (x=1024, y=1024, z=1024) const max_grid_size = (x=65535, y=65535, z=65535) for dim in (:x, :y, :z) # Workitem index fname = Symbol("workitem") fn = Symbol("workitemIdx_$dim") intr = Symbol("$dim") @eval @inline $fn() = Int(_index($(Val(fname)), $(Val(intr)), $(Val(0:max_block_size[dim])))) + 1 cufn = Symbol("threadIdx_$dim") @eval @inline $cufn() = $fn() # Workgroup index fname = Symbol("workgroup") fn = Symbol("workgroupIdx_$dim") intr = Symbol("$dim") @eval @inline $fn() = Int(_index($(Val(fname)), $(Val(intr)), $(Val(0:max_grid_size[dim])))) + 1 cufn = Symbol("blockIdx_$dim") @eval @inline $cufn() = $fn() end _packet_names = fieldnames(HSA.KernelDispatchPacket) _packet_offsets = fieldoffset.(HSA.KernelDispatchPacket, 1:length(_packet_names)) for (dim,off) in ((:x,1), (:y,2), (:z,3)) # Workitem dimension fn = Symbol("workgroupDim_$dim") base = _packet_offsets[findfirst(x->x==:workgroup_size_x,_packet_names)] @eval @inline $fn() = Int(_dim($(Val(base)), $(Val(off)), $(Val(0:max_block_size[dim])), UInt16)) cufn = Symbol("blockDim_$dim") @eval @inline $cufn() = $fn() # Grid dimension (in workitems) fn = Symbol("gridDim_$dim") base = _packet_offsets[findfirst(x->x==:grid_size_x,_packet_names)] @eval @inline $fn() = Int(_dim($(Val(base)), $(Val(off)), $(Val(0:max_grid_size[dim])), UInt32)) # Grid dimension (in workgroups) fn_wg = Symbol("gridDimWG_$dim") fn_wi_idx = Symbol("workitemIdx_$dim") @eval @inline $fn_wg() = $fn()/$fn_wi_idx() end """ workitemIdx()::ROCDim3 Returns the work item index within the work group. See also: [`threadIdx`](@ref) """ @inline workitemIdx() = (x=workitemIdx_x(), y=workitemIdx_y(), z=workitemIdx_z()) """ workgroupIdx()::ROCDim3 Returns the work group index. See also: [`blockIdx`](@ref) """ @inline workgroupIdx() = (x=workgroupIdx_x(), y=workgroupIdx_y(), z=workgroupIdx_z()) """ workgroupDim()::ROCDim3 Returns the size of each workgroup in workitems. See also: [`blockDim`](@ref) """ @inline workgroupDim() = (x=workgroupDim_x(), y=workgroupDim_y(), z=workgroupDim_z()) """ gridDim()::ROCDim3 Returns the size of the grid in workitems. This behaviour is different from CUDA where `gridDim` gives the size of the grid in blocks. """ @inline gridDim() = (x=gridDim_x(), y=gridDim_y(), z=gridDim_z()) """ gridDimWG()::ROCDim3 Returns the size of the grid in workgroups. This is equivalent to CUDA's `gridDim`. """ @inline gridDimWG() = (x=gridDimWG_x(), y=gridDimWG_y(), z=gridDimWG_z()) # For compat with CUDAnative et. al """ threadIdx()::ROCDim3 Returns the thread index within the block. See also: [`workitemIdx`](@ref) """ @inline threadIdx() = (x=threadIdx_x(), y=threadIdx_y(), z=threadIdx_z()) """ blockIdx()::ROCDim3 Returns the block index within the grid. See also: [`workgroupIdx`](@ref) """ @inline blockIdx() = (x=blockIdx_x(), y=blockIdx_y(), z=blockIdx_z()) """ blockDim()::ROCDim3 Returns the dimensions of the block. See also: [`workgroupDim`](@ref) """ @inline blockDim() = (x=blockDim_x(), y=blockDim_y(), z=blockDim_z())
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
4578
@generated function _intr(::Val{fname}, out_arg, inp_args...) where {fname,} inp_exprs = [:( inp_args[$i] ) for i in 1:length(inp_args)] inp_types = [inp_args...] out_type = convert(LLVMType, out_arg.parameters[1]) # create function param_types = LLVMType[convert.(LLVMType, inp_types)...] llvm_f, _ = create_function(out_type, param_types) mod = LLVM.parent(llvm_f) # generate IR Builder(JuliaContext()) do builder entry = BasicBlock(llvm_f, "entry", JuliaContext()) position!(builder, entry) # call the intrinsic intr_typ = LLVM.FunctionType(out_type, param_types) intr = LLVM.Function(mod, string(fname), intr_typ) value = call!(builder, intr, [parameters(llvm_f)...]) ret!(builder, value) end call_function(llvm_f, out_arg.parameters[1], Tuple{inp_args...}, Expr(:tuple, inp_exprs...)) end struct GCNIntrinsic jlname::Symbol rocname::Symbol isbroken::Bool # please don't laugh... isinverted::Bool # FIXME: Input/output types inp_args::Tuple out_arg::Type roclib::Symbol suffix::Symbol end GCNIntrinsic(jlname, rocname=jlname; isbroken=false, isinverted=false, inp_args=(), out_arg=(), roclib=:ocml, suffix=fntypes[first(inp_args)]) = GCNIntrinsic(jlname, rocname, isbroken, isinverted, inp_args, out_arg, roclib, suffix) const MATH_INTRINSICS = GCNIntrinsic[] for jltype in ( #= TODO: Float16 Broken due to being i16 in Julia=# Float32, Float64) append!(MATH_INTRINSICS, GCNIntrinsic.(( :sin, :cos, :tan, :asin, :acos, :atan, :atan2, :sinh, :cosh, :tanh, :asinh, :acosh, :atanh, :sinpi, :cospi, :tanpi, :sincospi, :asinpi, :acospi, :atanpi, :atan2pi, :sqrt, :rsqrt, :cbrt, :rcbrt, :recip, :log, :log2, :log10, :log1p, :logb, :ilogb, :exp, :exp2, :exp10, :expm1, :erf, :erfinv, :erfc, :erfcinv, :erfcx, # TODO: :brev, :clz, :ffs, :byte_perm, :popc, :isnormal, :nearbyint, :nextafter, :pow, :pown, :powr, :tgamma, :j0, :j1, :y0, :y1, ); inp_args=(jltype,), out_arg=jltype)) push!(MATH_INTRINSICS, GCNIntrinsic(:sin_fast, :native_sin; inp_args=(jltype,), out_arg=jltype)) push!(MATH_INTRINSICS, GCNIntrinsic(:cos_fast, :native_cos; inp_args=(jltype,), out_arg=jltype)) push!(MATH_INTRINSICS, GCNIntrinsic(:sqrt_fast, :native_sqrt; inp_args=(jltype,), out_arg=jltype)) push!(MATH_INTRINSICS, GCNIntrinsic(:rsqrt_fast, :native_rsqrt; inp_args=(jltype,), out_arg=jltype)) push!(MATH_INTRINSICS, GCNIntrinsic(:recip_fast, :native_recip; inp_args=(jltype,), out_arg=jltype)) push!(MATH_INTRINSICS, GCNIntrinsic(:log_fast, :native_log; inp_args=(jltype,), out_arg=jltype)) push!(MATH_INTRINSICS, GCNIntrinsic(:log2_fast, :native_log2; inp_args=(jltype,), out_arg=jltype)) push!(MATH_INTRINSICS, GCNIntrinsic(:log10_fast, :native_log10; inp_args=(jltype,), out_arg=jltype)) push!(MATH_INTRINSICS, GCNIntrinsic(:exp_fast, :native_exp; inp_args=(jltype,), out_arg=jltype)) push!(MATH_INTRINSICS, GCNIntrinsic(:exp2_fast, :native_exp2; inp_args=(jltype,), out_arg=jltype)) push!(MATH_INTRINSICS, GCNIntrinsic(:exp10_fast, :native_exp10; inp_args=(jltype,), out_arg=jltype)) push!(MATH_INTRINSICS, GCNIntrinsic(:abs, :fabs; inp_args=(jltype,), out_arg=jltype)) # TODO: abs(::Union{Int32,Int64}) # FIXME: Multi-argument functions #= push!(MATH_INTRINSICS, = map(intr->GCNIntrinsic(intr), ( :sincos, :frexp, :ldexp, :copysign, ))) =# #push!(MATH_INTRINSICS, GCNIntrinsic(:ldexp; inp_args=(jltype,), out_arg=(jltype, Int32), isinverted=true)) end let jltype=Float32 # TODO: Float64 is broken for some reason, try to re-enable on a newer LLVM push!(MATH_INTRINSICS, GCNIntrinsic(:isfinite; inp_args=(jltype,), out_arg=Int32)) push!(MATH_INTRINSICS, GCNIntrinsic(:isinf; inp_args=(jltype,), out_arg=Int32)) push!(MATH_INTRINSICS, GCNIntrinsic(:isnan; inp_args=(jltype,), out_arg=Int32)) push!(MATH_INTRINSICS, GCNIntrinsic(:signbit; inp_args=(jltype,), out_arg=Int32)) end for intr in MATH_INTRINSICS inp_vars = [gensym() for _ in 1:length(intr.inp_args)] inp_expr = [:($(inp_vars[idx])::$arg) for (idx,arg) in enumerate(intr.inp_args)] libname = Symbol("__$(intr.roclib)_$(intr.rocname)_$(intr.suffix)") @eval @inline function $(intr.jlname)($(inp_expr...)) y = _intr($(Val(libname)), $(intr.out_arg), $(inp_expr...)) return $(intr.isinverted ? :(1-y) : :y) end end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
64
export malloc # Stub implementation malloc(::Csize_t) = C_NULL
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
1439
export alloc_special "Allocates on-device memory statically from the specified address space." @generated function alloc_special(::Val{id}, ::Type{T}, ::Val{as}, ::Val{len}=Val(0)) where {id,T,as,len} eltyp = convert(LLVMType, T) # old versions of GPUArrays invoke _shmem with an integer id; make sure those are unique if !isa(id, String) || !isa(id, Symbol) id = "alloc_special_$id" end T_ptr = convert(LLVMType, DevicePtr{T,as}) # create a function llvm_f, _ = create_function(T_ptr) # create the global variable mod = LLVM.parent(llvm_f) gv_typ = LLVM.ArrayType(eltyp, len) gv = GlobalVariable(mod, gv_typ, string(id), convert(Int, as)) if len > 0 linkage!(gv, LLVM.API.LLVMInternalLinkage) #initializer!(gv, null(gv_typ)) end # by requesting a larger-than-datatype alignment, we might be able to vectorize. # TODO: Make the alignment configurable alignment!(gv, Base.max(32, Base.datatype_alignment(T))) # generate IR Builder(JuliaContext()) do builder entry = BasicBlock(llvm_f, "entry", JuliaContext()) position!(builder, entry) ptr_with_as = gep!(builder, gv, [ConstantInt(0, JuliaContext()), ConstantInt(0, JuliaContext())]) val = ptrtoint!(builder, ptr_with_as, T_ptr) ret!(builder, val) end call_function(llvm_f, DevicePtr{T,as}) end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
3937
export OutputContext, @rocprint, @rocprintln "Internal representation of a static string." struct DeviceStaticString{N} end Base.sizeof(dss::DeviceStaticString{N}) where N = N function Base.unsafe_load(ptr::DevicePtr{DeviceStaticString{N},AS.Global}) where N vec_ptr = convert(Ptr{UInt8}, ptr) vec_raw = Base.unsafe_wrap(Vector{UInt8}, vec_ptr, (N,)) idx = findfirst(x->x==0, vec_raw) idx = idx === nothing ? N : idx return vec_raw[1:idx-1] end Base.unsafe_store!(ptr::DevicePtr{<:DeviceStaticString}, x) = nothing struct OutputContext{HC} hostcall::HC end function OutputContext(io::IO=stdout; agent=get_default_agent(), buf_len=2^16, kwargs...) hc = HostCall(Int64, Tuple{DeviceStaticString{buf_len}}; agent=agent, continuous=true, kwargs...) do bytes print(io, String(bytes)) Int64(length(bytes)) end OutputContext(hc) end ### macros macro rocprint(oc, str) rocprint(oc, str) end macro rocprintln(oc, str) rocprint(oc, str, true) end ### parse-time helpers function rocprint(oc, str, nl=false) ex = Expr(:block) if !(str isa Expr) str = Expr(:string, str) end @assert str.head == :string for (idx,arg) in enumerate(str.args) if nl && idx == length(str.args) arg *= '\n' end N = rocprint!(ex, 1, oc, arg) N = rocprint!(ex, N, oc, '\0') dstr = DeviceStaticString{N}() push!(ex.args, :(hostcall!($(esc(oc)).hostcall, $dstr))) end return ex end function rocprint!(ex, N, oc, str::String) # TODO: push!(ex.args, :($rocprint!($(esc(oc)), $(Val(Symbol(str)))))) off = N ptr = :(Base.unsafe_convert(DevicePtr{UInt8,AS.Global}, $(esc(oc)).hostcall.buf_ptr)) for byte in codeunits(str) push!(ex.args, :(Base.unsafe_store!($ptr, $byte, $off))) off += 1 end return off end function rocprint!(ex, N, oc, char::Char) @assert char == '\0' "Non-null chars not yet implemented" byte = UInt8(char) ptr = :(Base.unsafe_convert(DevicePtr{UInt8,AS.Global}, $(esc(oc)).hostcall.buf_ptr)) push!(ex.args, :(Base.unsafe_store!($ptr, $byte, $N))) return N+1 end function rocprint!(ex, N, oc, iex::Expr) for arg in iex.args N = rocprint!(ex, N, oc, arg) end return N end #= TODO: Support printing arbitrary values? function rocprint!(ex, N, oc, sym::Symbol) push!(ex.args, :($rocprint!($(esc(oc)), $(QuoteNode(sym))))) return N+4 end =# ### runtime helpers #= TODO: LLVM hates me, but this should eventually work # FIXME: Pass N and offset oc.buf_ptr appropriately @inline @generated function rocprint!(oc::OutputContext, ::Val{str}) where str T_int1 = LLVM.Int1Type(JuliaContext()) T_int32 = LLVM.Int32Type(JuliaContext()) T_pint8 = LLVM.PointerType(LLVM.Int8Type(JuliaContext())) T_pint8_global = LLVM.PointerType(LLVM.Int8Type(JuliaContext()), convert(Int, AS.Global)) T_nothing = LLVM.VoidType(JuliaContext()) llvm_f, _ = create_function(T_nothing, [T_pint8_global]) mod = LLVM.parent(llvm_f) T_intr = LLVM.FunctionType(T_nothing, [T_pint8_global, T_pint8, T_int32, T_int32, T_int1]) intr = LLVM.Function(mod, "llvm.memcpy.p1i8.p0i8.i32", T_intr) Builder(JuliaContext()) do builder entry = BasicBlock(llvm_f, "entry", JuliaContext()) position!(builder, entry) str_ptr = globalstring_ptr!(builder, String(str)) buf_ptr = parameters(llvm_f)[1] # NOTE: There's a hidden alignment parameter (argument 4) that's not documented in the LangRef call!(builder, intr, [buf_ptr, str_ptr, ConstantInt(Int32(length(string(str))), JuliaContext()), ConstantInt(Int32(2), JuliaContext()), ConstantInt(T_int1, 0)]) ret!(builder) end Core.println(unsafe_string(LLVM.API.LLVMPrintValueToString(LLVM.ref(llvm_f)))) call_function(llvm_f, Nothing, Tuple{DevicePtr{UInt8,AS.Global}}, :((oc.hostcall.buf_ptr,))) end =#
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
198
export sync_workgroup """ sync_workgroup() Waits until all wavefronts in a workgroup have reached this call. """ @inline sync_workgroup() = ccall("llvm.amdgcn.s.barrier", llvmcall, Cvoid, ())
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
495
# OpenCL argument utilities # Argument accessors # __agocl_global_offset_x - OpenCL Global Offset X # __agocl_global_offset_y - OpenCL Global Offset Y # __agocl_global_offset_z - OpenCL Global Offset Z # __agocl_printf_addr - OpenCL address of printf buffer # __agocl_queue_addr - OpenCL address of virtual queue used by enqueue_kernel # __agocl_aqlwrap_addr - OpenCL address of AqlWrap struct used by enqueue_kernel # __agocl_multigrid - Pointer argument used for Multi-grid synchronization
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
2285
@testset "pointer" begin # inner constructors voidptr_a = Ptr{Cvoid}(Int(0xDEADBEEF)) generic_voidptr_a = AMDGPUnative.DevicePtr{Cvoid,AS.Generic}(voidptr_a) global_voidptr_a = AMDGPUnative.DevicePtr{Cvoid,AS.Global}(voidptr_a) local_voidptr_a = AMDGPUnative.DevicePtr{Cvoid,AS.Local}(voidptr_a) voidptr_b = Ptr{Cvoid}(Int(0xCAFEBABE)) generic_voidptr_b = AMDGPUnative.DevicePtr{Cvoid,AS.Generic}(voidptr_b) global_voidptr_b = AMDGPUnative.DevicePtr{Cvoid,AS.Global}(voidptr_b) local_voidptr_b = AMDGPUnative.DevicePtr{Cvoid,AS.Local}(voidptr_b) intptr_b = convert(Ptr{Int}, voidptr_b) generic_intptr_b = AMDGPUnative.DevicePtr{Int,AS.Generic}(intptr_b) global_intptr_b = AMDGPUnative.DevicePtr{Int,AS.Global}(intptr_b) local_intptr_b = AMDGPUnative.DevicePtr{Int,AS.Local}(intptr_b) # outer constructors @test AMDGPUnative.DevicePtr{Cvoid}(voidptr_a) == generic_voidptr_a @test AMDGPUnative.DevicePtr(voidptr_a) == generic_voidptr_a # getters @test eltype(generic_voidptr_a) == Cvoid @test eltype(global_intptr_b) == Int @test AMDGPUnative.addrspace(generic_voidptr_a) == AS.Generic @test AMDGPUnative.addrspace(global_voidptr_a) == AS.Global @test AMDGPUnative.addrspace(local_voidptr_a) == AS.Local # comparisons @test generic_voidptr_a != global_voidptr_a @test generic_voidptr_a != generic_intptr_b @testset "conversions" begin # between regular and device pointers @test convert(Ptr{Cvoid}, generic_voidptr_a) == voidptr_a @test convert(AMDGPUnative.DevicePtr{Cvoid}, voidptr_a) == generic_voidptr_a @test convert(AMDGPUnative.DevicePtr{Cvoid,AS.Global}, voidptr_a) == global_voidptr_a # between device pointers @test_throws ArgumentError convert(typeof(local_voidptr_a), global_voidptr_a) @test convert(typeof(generic_voidptr_a), generic_voidptr_a) == generic_voidptr_a @test convert(typeof(global_voidptr_a), global_voidptr_a) == global_voidptr_a @test Base.unsafe_convert(typeof(local_voidptr_a), global_voidptr_a) == local_voidptr_a @test convert(typeof(global_voidptr_a), global_intptr_b) == global_voidptr_b @test convert(typeof(generic_voidptr_a), global_intptr_b) == generic_voidptr_b @test convert(typeof(global_voidptr_a), generic_intptr_b) == global_voidptr_b @test convert(AMDGPUnative.DevicePtr{Cvoid}, global_intptr_b) == global_voidptr_b end end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
1235
using AMDGPUnative const AS = AMDGPUnative.AS using GPUCompiler using LLVM, LLVM.Interop using HSARuntime using InteractiveUtils using SpecialFunctions using Test agent_name = HSARuntime.get_name(get_default_agent()) agent_isa = get_first_isa(get_default_agent()) @info "Testing using device $agent_name with ISA $agent_isa" @testset "AMDGPUnative" begin @testset "Core" begin include("pointer.jl") end if AMDGPUnative.configured @test length(get_agents()) > 0 if length(get_agents()) > 0 include("synchronization.jl") include("trap.jl") @testset "Device" begin include("device/launch.jl") include("device/vadd.jl") include("device/memory.jl") include("device/indexing.jl") include("device/hostcall.jl") include("device/output.jl") include("device/globals.jl") if Base.libllvm_version >= v"7.0" include("device/math.jl") else @warn "Testing with LLVM 6; some tests will be disabled!" @test_skip "Math Intrinsics" end end end else @warn("AMDGPUnative.jl has not been configured; skipping on-device tests.") end end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
310
@testset "Synchronization" begin # TODO: Remove dummy argument once HSARuntime is fixed function synckern(x) sync_workgroup() nothing end iob = IOBuffer() AMDGPUnative.code_gcn(iob, synckern, Tuple{Int}; kernel=true) @test occursin("s_barrier", String(take!(iob))) end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
535
@testset "Trapping" begin # TODO: Remove dummy argument once HSARuntime is fixed function trapkern(x) AMDGPUnative.trap() nothing end function debugtrapkern(x) AMDGPUnative.debugtrap() nothing end iob = IOBuffer() AMDGPUnative.code_gcn(iob, trapkern, Tuple{Int}; kernel=true) @test occursin("s_trap 2", String(take!(iob))) iob = IOBuffer() AMDGPUnative.code_gcn(iob, debugtrapkern, Tuple{Int}; kernel=true) @test occursin("s_trap 3", String(take!(iob))) end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
515
@testset "Globals" begin function kernel(X) ptr = AMDGPUnative.get_global_pointer(Val(:myglobal), Float32) Base.unsafe_store!(ptr, 3f0) nothing end hk = AMDGPUnative.rocfunction(kernel, Tuple{Int32}) gbl = HSARuntime.get_global(hk.mod.exe, :myglobal) gbl_ptr = Base.unsafe_convert(Ptr{Float32}, gbl.ptr) @test Base.unsafe_load(gbl_ptr) == 0f0 Base.unsafe_store!(gbl_ptr, 2f0) @test Base.unsafe_load(gbl_ptr) == 2f0 wait(@roc groupsize=1 kernel(Int32(1))) @test Base.unsafe_load(gbl_ptr) == 3f0 end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
5104
@testset "Hostcall" begin @testset "Call: Async" begin function kernel(a,b,sig) hostcall!(sig) b[1] = a[1] nothing end A = ones(Float32, 1) B = zeros(Float32, 1) HA = HSAArray(A) HB = HSAArray(B) dref = Ref{Bool}(false) hc = HostCall(Nothing, Tuple{}) do dref[] = true end wait(@roc kernel(HA, HB, hc)) @test Array(HB)[1] == 1f0 sleep(1) @test dref[] == true end @testset "Call: Async error" begin function kernel(a,b,sig) hostcall!(sig) b[1] = a[1] nothing end A = ones(Float32, 1) B = zeros(Float32, 1) HA = HSAArray(A) HB = HSAArray(B) dref = Ref{Bool}(false) # This should throw an exception and the error message should be logged. @test_logs (:error, "Hostcall error") begin hc, hc_task = HostCall(Nothing, Tuple{}; return_task=true) do error("Some error") dref[] = true end wait(@roc kernel(HA, HB, hc)) sleep(1) @test Array(HB)[1] == 1f0 @test dref[] == false @test Base.istaskfailed(hc_task) end end @testset "Call: Sync (0 args)" begin function kernel(a,b,sig) inc = hostcall!(sig)::Float32 b[1] = a[1] + inc nothing end A = ones(Float32, 1) B = zeros(Float32, 1) HA = HSAArray(A) HB = HSAArray(B) hc = HostCall(Float32, Tuple{}) do 1f0 end wait(@roc kernel(HA, HB, hc)) sleep(1) @test Array(HB)[1] == 2f0 end @testset "Call: Sync (1 arg)" begin function kernel(a,b,sig) inc = hostcall!(sig, 42f0)::Float32 b[1] = a[1] + inc nothing end A = ones(Float32, 1) B = zeros(Float32, 1) HA = HSAArray(A) HB = HSAArray(B) hc = HostCall(Float32, Tuple{Float32}) do arg1 arg1 + 1f0 end wait(@roc kernel(HA, HB, hc)) sleep(1) @test Array(HB)[1] == 44f0 end @testset "Call: Sync (2 homogeneous args)" begin function kernel(a,b,sig) inc = hostcall!(sig, 42f0, 3f0)::Float32 b[1] = a[1] + inc nothing end A = ones(Float32, 1) B = zeros(Float32, 1) HA = HSAArray(A) HB = HSAArray(B) hc = HostCall(Float32, Tuple{Float32,Float32}) do arg1, arg2 arg1 + arg2 + 1f0 end wait(@roc kernel(HA, HB, hc)) sleep(1) @test Array(HB)[1] == 47f0 end @testset "Call: Sync (2 heterogeneous args)" begin function kernel(a,b,sig) inc = hostcall!(sig, 42f0, Int16(3))::Float32 b[1] = a[1] + inc nothing end A = ones(Float32, 1) B = zeros(Float32, 1) HA = HSAArray(A) HB = HSAArray(B) hc = HostCall(Float32, Tuple{Float32,Int16}) do arg1, arg2 arg1 + Float32(arg2) + 1f0 end wait(@roc kernel(HA, HB, hc)) sleep(1) @test Array(HB)[1] == 47f0 end @testset "Call: Sync (2 heterogeneous args, return homogeneous tuple)" begin function kernel(a,b,sig) inc1, inc2 = hostcall!(sig, 42f0, Int16(3))::Tuple{Float32,Float32} b[1] = a[1] + inc1 + inc2 nothing end A = ones(Float32, 1) B = zeros(Float32, 1) HA = HSAArray(A) HB = HSAArray(B) hc = HostCall(Tuple{Float32,Float32}, Tuple{Float32,Int16}) do arg1, arg2 (arg1 + Float32(arg2) + 1f0, 1f0) end wait(@roc kernel(HA, HB, hc)) sleep(1) @test Array(HB)[1] == 48f0 end @testset "Call: Sync (2 heterogeneous args, return heterogeneous tuple)" begin function kernel(a,b,sig) inc1, inc2 = hostcall!(sig, 42f0, Int16(3))::Tuple{Float32,Int64} b[1] = a[1] + inc1 + Float32(inc2) nothing end A = ones(Float32, 1) B = zeros(Float32, 1) HA = HSAArray(A) HB = HSAArray(B) hc = HostCall(Tuple{Float32,Int64}, Tuple{Float32,Int16}) do arg1, arg2 (arg1 + Float32(arg2) + 1f0, 1) end wait(@roc kernel(HA, HB, hc)) sleep(1) @test Array(HB)[1] == 48f0 end @testset "Call: Sync (2 hostcalls, 1 kernel)" begin function kernel(a,b,sig1,sig2) inc1 = hostcall!(sig1, 3f0)::Float32 inc2 = hostcall!(sig2, 4f0)::Float32 b[1] = a[1] + inc1 + inc2 nothing end A = ones(Float32, 1) B = zeros(Float32, 1) HA = HSAArray(A) HB = HSAArray(B) hc1 = HostCall(Float32, Tuple{Float32}) do arg1 arg1 + 1f0 end hc2 = HostCall(Float32, Tuple{Float32}) do arg1 arg1 + 2f0 end wait(@roc kernel(HA, HB, hc1, hc2)) sleep(1) @test Array(HB)[1] == 11f0 end @testset "Call: Sync (1 hostcall, 2 kernels)" begin function kernel(a,b,sig) inc = hostcall!(sig, 3f0)::Float32 b[1] = a[1] + inc nothing end A = ones(Float32, 1) B = zeros(Float32, 1) HA = HSAArray(A) HB = HSAArray(B) hc = HostCall(Float32, Tuple{Float32}; continuous=true) do arg1 arg1 + 1f0 end # FIXME: wait() hangs here, probably race condition? @roc kernel(HA, HB, hc) @roc kernel(HA, HB, hc) sleep(1) @test Array(HB)[1] == 5f0 end end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
694
@testset "Kernel Indexing" begin function idx_kern(X) X[1] = workitemIdx().x X[2] = workitemIdx().y X[3] = workitemIdx().z X[4] = workgroupIdx().x X[5] = workgroupIdx().y X[6] = workgroupIdx().z nothing end A = zeros(Int64, 6) HA = HSAArray(A) @roc groupsize=(1,2,3) gridsize=(4,5,6) idx_kern(HA) A = Array(HA) @test all(A .> 0) function dim_kern(X) X[1] = workgroupDim().x X[2] = workgroupDim().y X[3] = workgroupDim().z X[4] = gridDim().x X[5] = gridDim().y X[6] = gridDim().z nothing end A = zeros(Int64, 6) HA = HSAArray(A) wait(@roc groupsize=(1,2,3) gridsize=(4,5,6) dim_kern(HA)) A = Array(HA) @test A β‰ˆ [1,2,3,4,5,6] end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
789
@testset "Launch Configuration" begin kernel(x) = nothing device = AMDGPUnative.default_device() queue = AMDGPUnative.default_queue(device) # Group/grid size selection and aliases eval(:(@roc groupsize=2 $kernel(1))) eval(:(@roc groupsize=2 gridsize=4 $kernel(1))) eval(:(@roc gridsize=2 $kernel(1))) eval(:(@roc threads=2 $kernel(1))) eval(:(@roc blocks=4 $kernel(1))) eval(:(@roc threads=2 gridsize=4 $kernel(1))) # Device/queue selection and aliases eval(:(@roc device=$device $kernel(1))) eval(:(@roc device=$device queue=$queue $kernel(1))) eval(:(@roc queue=$queue $kernel(1))) eval(:(@roc agent=$device $kernel(1))) eval(:(@roc stream=$queue $kernel(1))) eval(:(@roc agent=$device queue=$queue $kernel(1))) end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
1441
@testset "Math Intrinsics" begin for intr in AMDGPUnative.MATH_INTRINSICS jlintr = intr.jlname if intr.isbroken || !(isdefined(Base, jlintr) || isdefined(SpecialFunctions, jlintr)) @test_skip "$jlintr()" continue end modname = (isdefined(Base, jlintr) ? Base : SpecialFunctions) # FIXME: Handle all input and output args T = intr.inp_args[1] intr_kern = Symbol("intr_$(jlintr)_$T") @eval begin function $intr_kern(a) i = threadIdx().x a[i] = AMDGPUnative.$jlintr(a[i]) return nothing end dims = (8,) a = rand($T, dims) if $(QuoteNode(jlintr)) == :acosh a .+= one($T) end d_a = HSAArray(a) len = prod(dims) @debug begin aspace = AMDGPUnative.AS.Global arrdims = ndims(a) arrT = ROCDeviceArray{Float32,arrdims,aspace} @debug "LLVM IR" AMDGPUnative.code_llvm($intr_kern, Tuple{arrT}; kernel=true) @debug "GCN Device Code" AMDGPUnative.code_gcn($intr_kern, Tuple{arrT}; kernel=true) "" end wait(@roc groupsize=len $intr_kern(d_a)) _a = Array(d_a) @test $modname.$jlintr.(a) β‰ˆ _a end end end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
794
@testset "Memory: Static" begin function memory_static_kernel(a,b) # Local ptr_local = alloc_special(Val(:local), Float32, Val(AS.Local), Val(1)) unsafe_store!(ptr_local, a[1]) b[1] = unsafe_load(ptr_local) # Region #= TODO: AMDGPU target cannot select ptr_region = alloc_special(Val(:region), Float32, Val(AS.Region), Val(1)) unsafe_store!(ptr_region, a[2]) b[2] = unsafe_load(ptr_region) =# # Private #= TODO ptr_private = alloc_special(Val(:private), Float32, Val(AS.Private), Val(1)) unsafe_store!(ptr_private, a[3]) b[3] = unsafe_load(ptr_private) =# nothing end A = ones(Float32, 1) B = zeros(Float32, 1) HA = HSAArray(A) HB = HSAArray(B) wait(@roc memory_static_kernel(HA, HB)) @test Array(HA) β‰ˆ Array(HB) end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
1171
@testset "Output" begin @testset "Plain, no newline" begin function kernel(oc) @rocprint oc "Hello World!" nothing end iob = IOBuffer() oc = OutputContext(iob) @roc kernel(oc) sleep(1) @test String(take!(iob)) == "Hello World!" end @testset "Plain, with newline" begin function kernel(oc) @rocprintln oc "Hello World!" nothing end iob = IOBuffer() oc = OutputContext(iob) @roc kernel(oc) sleep(1) @test String(take!(iob)) == "Hello World!\n" end @testset "Plain, multiple calls" begin function kernel(oc) @rocprint oc "Hello World!" @rocprintln oc "Goodbye World!" nothing end iob = IOBuffer() oc = OutputContext(iob) @roc kernel(oc) sleep(1) @test String(take!(iob)) == "Hello World!Goodbye World!\n" end #= TODO @testset "Interpolated string" begin inner_str = "to the" function kernel(oc) @rocprintln oc "Hello $inner_str World!" nothing end iob = IOBuffer() oc = OutputContext(iob) @roc kernel(oc) sleep(1) @test String(take!(iob)) == "Hello to the World!\n" end =# end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
1007
# The original test :) @testset "Vector Addition Kernel" begin function vadd(a,b,c) i = workitemIdx().x c[i] = a[i] + b[i] sync_workgroup() return nothing end dims = (8,) a = round.(rand(Float32, dims) * 100) b = round.(rand(Float32, dims) * 100) d_a = HSAArray(a) d_b = HSAArray(b) d_c = similar(d_a) len = prod(dims) @debug begin @show d_a.handle @show d_b.handle @show d_c.handle aspace = AMDGPUnative.AS.Global arrdims = ndims(a) arrT = ROCDeviceArray{Float32,arrdims,aspace} @debug "LLVM IR" AMDGPUnative.code_llvm(vadd, Tuple{arrT,arrT,arrT}; kernel=true) @debug "GCN Device Code" AMDGPUnative.code_gcn(vadd, Tuple{arrT,arrT,arrT}; kernel=true) "" end wait(@roc groupsize=len vadd(d_a, d_b, d_c)) @debug begin @show d_a @show d_b @show d_c "" end c = Array(d_c) @test a+b β‰ˆ c end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
docs
2587
# AMDGPUnative.jl *Support for compiling and executing native Julia kernels on AMD GPUs.* | **Documentation** | **Build Status** | |:---------------------------------------:|:-------------------------------------------------------------:| | [![][docs-master-img]][docs-master-url] | [![][gitlab-img]][gitlab-url] [![][codecov-img]][codecov-url] | [gitlab-img]: https://gitlab.com/JuliaGPU/AMDGPUnative.jl/badges/master/pipeline.svg [gitlab-url]: https://gitlab.com/JuliaGPU/AMDGPUnative.jl/commits/master [codecov-img]: https://codecov.io/gh/JuliaGPU/AMDGPUnative.jl/branch/master/graph/badge.svg [codecov-url]: https://codecov.io/gh/JuliaGPU/AMDGPUnative.jl [docs-master-img]: https://img.shields.io/badge/docs-master-blue.svg [docs-master-url]: https://juliagpu.gitlab.io/AMDGPUnative.jl/ ## Quick start The package can be installed with the Julia package manager. From the Julia REPL, type `]` to enter the Pkg REPL mode and run: ``` pkg> add AMDGPUnative ``` Or, equivalently, via the `Pkg` API: ```julia julia> import Pkg; Pkg.add("AMDGPUnative") ``` ## Project Status The package is tested against, and being developed for, Julia `1.3` and above. Only 64-bit Linux is supported and working at this time, until ROCm is ported to other platforms. It is recommended to use a version of Julia with LLVM 9.0 or higher. This package is under active maintenance and is reasonably complete, however not all features (and especially performance) are up to par with CUDAnative. ### Supported Functionality | Feature | Supported | Notes | |:---|:---:|:---| | Host-side kernel launches | :heavy_check_mark: | See #58 | | Dynamic parallelism | :x: | | Local (shared) memory | :x: | | Coarse-grained memory | :x: | | Page-locked (pinned) memory | :x: | ## Questions and Contributions Usage questions can be posted on the [Julia Discourse forum](https://discourse.julialang.org/c/domain/gpu) under the GPU domain and/or in the #gpu channel of the [Julia Slack](https://julialang.org/community/). Contributions are very welcome, as are feature requests and suggestions. Please open an [issue](https://github.com/JuliaGPU/AMDGPUnative.jl/issues) if you encounter any problems. ## Acknowledgment AMDGPUnative would not have been possible without the work by Tim Besard and contributors to [CUDAnative.jl](https://github.com/JuliaGPU/CUDAnative.jl) and [LLVM.jl](https://github.com/maleadt/LLVM.jl). ## License AMDGPUnative.jl is licensed under the [MIT License](LICENSE.md).
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
docs
574
# AMDGPUnative API Reference ## Kernel launching ```@docs @roc AMDGPUnative.AbstractKernel AMDGPUnative.HostKernel AMDGPUnative.rocfunction ``` ## Device code API ### Thread indexing #### HSA nomenclature ```@docs workitemIdx workgroupIdx workgroupDim gridDim gridDimWG ``` #### CUDA nomenclature Use these functions for compatibility with CUDAnative.jl. ```@docs threadIdx blockIdx blockDim ``` ### Synchronization ```@docs sync_workgroup ``` ### Pointers ```@docs AMDGPUnative.DevicePtr ``` ### Global Variables ```@docs AMDGPUnative.get_global_pointer ```
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
docs
3210
# Global Variables Most programmers are familiar with the concept of a "global variable": a variable which is globally accessible to any function in the user's program. In Julia, programmers are told to avoid using global variables (also known as "globals") because of their tendency to introduce type instabilities. However, they're often useful for sharing data between functions in distinct areas of the user's program. In the JuliaGPU ecosystem, globals in the Julia sense are not available unless their value is constant and inlinable into the function referencing them, as all GPU kernels must be statically compileable. However, a different sort of global variable is available which serves a very similar purpose. This variant of global variable is statically typed and sized, and is accessible from: all kernels with the same function signature (e.g. `mykernel(a::Int32, b::Float64)`), the CPU host, and other devices and kernels when accessed by pointer. Global variables can be created within kernels with the [`AMDGPUnative.get_global_pointer`](@ref) function, which both declares the global variable, and returns a pointer to it (specifically a [`AMDGPUnative.DevicePtr`](@ref)). Once a kernel which declares a global is compiled for GPU execution (either by [`@roc`](@ref) or [`rocfunction`](@ref)), the global is allocated memory and made available to the kernel (during the linking stage). Globals are unique by name, and so you shouldn't attempt to call `get_global_pointer` with the same name but a different type; if you do, undefined behavior will result. Like regular pointers in Julia, you can use functions like `Base.unsafe_load` and `Base.unsafe_store!` to read from and write to the global variable, respectively. As a concrete example of global variable usage, let's define a kernel which creates a global and uses its value to increment the indices of an array: ```julia function my_kernel(A) idx = workitemIdx().x ptr = AMDGPUnative.get_global_pointer(Val(:myglobal), Int64) A[idx] += Base.unsafe_load(ptr) nothing end ``` Now, let's compile this kernel and get a pointer to this newly-declared global variable. We'll also create an `HSAArray` that we intend to pass to the kernel: ```julia HA = HSAArray(ones(Float32, 4)) kern = rocfunction(my_kernel, Tuple{typeof(rocconvert(HA))}) gbl = HSARuntime.get_global(kern.mod.exe, :myglobal) gbl_ptr = Base.unsafe_convert(Ptr{Int64}, gbl.ptr) ``` And now `gbl_ptr` is a pointer (specifically a `Ptr{Int64}`) to the memory that represents the global variable `myglobal`. We can't guarantee the initial value of a newly-initialized global variable, so let's write a value to that global variable and then read it back: ```julia Base.unsafe_store!(gbl_ptr, 42) println(Base.unsafe_load(gbl_ptr)) ``` And now `myglobal` has the value 42, of type `Int64`. Now, let's invoke the kernel with `@roc` (keeping in mind that the kernel's signature must be the same as in our call to `rocfunction` above: ```julia wait(@roc groupsize=4 my_kernel(HA)) ``` We can then read the values of `HA` and see that it's what we expect: ```julia-repl julia> A = Array(HA) 4-element HSAArray{Float32,1}: 43.0 43.0 43.0 43.0 ```
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
docs
2541
# Programming AMD GPUs with Julia !!! tip This documentation assumes that you are familiar with the main concepts of GPU programming and mostly describes the specifics of running Julia code on AMD GPUs. For a much more gentle introduction to GPGPU with Julia consult the well-written [CUDA.jl documentation](https://juliagpu.gitlab.io/CUDA.jl). ## The ROCm stack ROCm (short for Radeon Open Compute platforM) is AMD's open-source GPU computing platform, supported by most modern AMD GPUs ([detailed hardware support](https://github.com/RadeonOpenCompute/ROCm#hardware-and-software-support)) and some AMD APUs. ROCm works solely on Linux and no plans to support either Windows or macOS have been announced by AMD. A necessary prerequisite to use this Julia package is to have a working ROCm stack installed. A quick way to verify this is to check the output of `rocminfo`. For more information, consult the official [installation guide](https://rocmdocs.amd.com/en/latest/Installation_Guide/Installation-Guide.html). Even though the only platforms officially supported by AMD are certain versions of Ubuntu, CentOS, RHEL, and SLES [^1], there are options to install ROCm on other Linux distributions, including: * Arch Linux - See the [rocm-arch](https://github.com/rocm-arch/rocm-arch) repository or the slightly older PKGBUILDs in the AUR. * Gentoo - Check Portage for the `rocr-runtime` package and [justxi's rocm repo](https://github.com/justxi/rocm) for unofficial ROCm package ebuilds. [^1]: <https://github.com/RadeonOpenCompute/ROCm/wiki#supported-operating-systems> Even though you don't need HIP to use Julia on AMDGPU, it might be wise to make sure that you can build and run simple HIP programs to ensure that your ROCm installation works properly before trying to use it from Julia. ## The Julia AMDGPU stack Julia support for programming AMD GPUs is currently provided by the following three packages: * [HSARuntime.jl](https://github.com/jpsamaroo/HSARuntime.jl) - Provides an interface for working with the HSA runtime API, necessary for launching compiled kernels and controlling the GPU. * [AMDGPUnative.jl](https://github.com/JuliaGPU/AMDGPUnative.jl) - Provides an interface for compiling and running kernels written in Julia through LLVM's AMDGPU backend. Uses and depends on HSARuntime.jl. * [ROCArrays.jl](https://github.com/jpsamaroo/ROCArrays.jl) - Implements the [GPUArrays.jl](https://github.com/JuliaGPU/GPUArrays.jl) interface, providing high-level array operations on top of AMDGPUnative.jl.
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
docs
5043
# Quick Start ## Installation After making sure that your ROCm stack is installed and working, simply add the required packages to your Julia environment: ```julia ]add HSARuntime, AMDGPUnative ``` If everything ran successfully, you can try loading the `AMDGPUnative` package and running the unit tests: ```julia using AMDGPUnative ]test AMDGPUnative ``` !!! warning If you get an error message along the lines of `GLIB_CXX_... not found`, it's possible that the C++ runtime used to build the ROCm stack and the one used by Julia are different. If you built the ROCm stack yourself this is very likely the case since Julia normally ships with its own C++ runtime. For more information, check out this [GitHub issue](https://github.com/JuliaLang/julia/issues/34276). A quick fix is to use the `LD_PRELOAD` environment variable to make Julia use the system C++ runtime library, for example: ```sh LD_PRELOAD=/usr/lib/libstdc++.so julia ``` Alternatively, you can build Julia from sources as described [here](https://github.com/JuliaLang/julia/blob/master/doc/build/build.md). You can quickly debug this issue by starting Julia and trying to load a ROCm library: ```julia using Libdl Libdl.dlopen("/opt/rocm/hsa/lib/libhsa-runtime64.so") ``` ## Running a simple kernel As a simple test, we will try to add two random vectors and make sure that the results from the CPU and the GPU are indeed the same. We can start by first performing this simple calculation on the CPU: ```julia N = 32 a = rand(Float64, N) b = rand(Float64, N) c_cpu = a + b ``` To do the same computation on the GPU, we first need to copy the two input arrays `a` and `b` to the device. Toward that end, we will use the `HSAArray` type from `HSARuntime` to represent our GPU arrays. We can create the two arrays by passing the host data to the constructor as follows: ```julia using HSARuntime, AMDGPUnative a_d = HSAArray(a) b_d = HSAArray(b) ``` We need to create one additional array `c_d` to store the results: ```julia c_d = similar(a_d) ``` !!! note `HSAArray` is a lightweight low-level array type, that does not support the GPUArrays.jl interface. Production code should instead use `ROCArray` once its ready, in a similar fashion to `CuArray`. In this example, the postfix `_d` distinguishes a device memory object from its host memory counterpart. This convention is completely arbitrary and you may name your device-side variables whatever you like; they are regular Julia variables. Next, we will define the GPU kernel that does the actual computation: ```julia function vadd!(c, a, b) i = workitemIdx().x c[i] = a[i] + b[i] return end ``` This simple kernel starts by getting the current thread ID using [`workitemIdx`](@ref) and then performs the addition of the elements from `a` and `b`, storing the result in `c`. Notice how we explicitly specify that this function does not return a value by adding the `return` statement. This is necessary for all GPU kernels and we can enforce it by adding a `return`, `return nothing`, or even `nothing` at the end of the kernel. If this statement is omitted, Julia will attempt to return the value of the last evaluated expression, in this case a `Float64`, which will cause a compilation failure as kernels cannot return values. The easiest way to launch a GPU kernel is with the [`@roc`](@ref) macro, specifying that we want a single work group with `N` work items and calling it like an ordinary function: ```julia @roc groupsize=N vadd!(c_d, a_d, b_d) ``` Keep in mind that kernel launches are asynchronous, meaning that you need to do some kind of synchronization before you use the result. For instance, you can call `wait()` on the returned HSA signal value: ```julia wait(@roc groupsize=N vadd!(c_d, a_d, b_d)) ``` !!! warning "Naming conventions" Throughout this example we use terms like "work group" and "work item". These terms are used by the Khronos consortium and their APIs including OpenCL and Vulkan, as well as the HSA foundation. NVIDIA, on the other hand, uses some different terms in their CUDA API, which might be confusing to some users porting their kernels from CUDAnative to AMDGPUnative. As a quick summary, here is a mapping of the most common terms: | AMDGPUnative | CUDAnative | |:---:|:---:| | [`workitemIdx`](@ref) | [`threadIdx`](@ref) | | [`workgroupIdx`](@ref) | [`blockIdx`](@ref) | | [`workgroupDim`](@ref) | [`blockDim`](@ref) | | [`gridDim`](@ref) | No equivalent | | [`gridDimWG`](@ref) | `gridDim` | | `groupsize` | `threads` | | `gridsize` | `blocks * threads` | | `queue` | `stream` | For compatibilty reasons, the symbols in the CUDAnative column (except for `gridDim`) are also supported by AMDGPUnative. Finally, we can make sure that the results match, by first copying the data to the host and then comparing it with the CPU results: ```julia c = Array(c_d) using Test @test isapprox(c, c_cpu) ```
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
383
using Documenter, TinyModia, ModiaPlot makedocs( #modules = [TinyModia], sitename = "TinyModia", authors = "Hilding Elmqvist (Mogram) and Martin Otter (DLR-SR)", format = Documenter.HTML(prettyurls = false), pages = [ "Home" => "index.md", "TinyModia Tutorial" => "Tutorial.md", "Functions" => "Functions.md", "Internal" => "Internal.md" ] )
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
3377
module CauerLowPassFilterModel using TinyModia using DifferentialEquations using ModiaPlot include("../models/Electric.jl") l1 = 1.304 l2 = 0.8586 c1 = 1.072*1u"F" c2 = 1/(1.704992^2*l1)*1u"F" c3 = 1.682*1u"F" c4 = 1/(1.179945^2*l2)*1u"F" c5 = 0.7262*1u"F" CauerLowPassOPVWithoutNodes(i=1) = Model( # Cauer low pass filter with operational amplifiers C1 = Capacitor | Map(C=c1 + c2), C2 = Capacitor | Map(C=c2, v=Var(init=nothing)), C3 = Capacitor | Map(C=l1*1u"F"), C4 = Capacitor | Map(C=c4*i, v=Var(init=nothing)), C5 = Capacitor | Map(C=c2, v=Var(init=nothing)), R1 = Resistor | Map(R=1u"Ξ©"), R2 = Resistor | Map(R=1u"Ξ©"), R3 = Resistor | Map(R=1u"Ξ©"), Op1 = IdealOpAmp3Pin, G = Ground, R4 = Resistor | Map(R=-1u"Ξ©"), R5 = Resistor | Map(R=-1u"Ξ©"), Op2 = IdealOpAmp3Pin, Op3 = IdealOpAmp3Pin, G1 = Ground, R6 = Resistor | Map(R=1u"Ξ©"), R7 = Resistor | Map(R=1u"Ξ©"), C6 = Capacitor | Map(C=c2 + c3 + c4, v=Var(init=nothing)), R8 = Resistor | Map(R=-1u"Ξ©"), R9 = Resistor | Map(R=-1u"Ξ©"), R10 = Resistor | Map(R=1u"Ξ©"), Op4 = IdealOpAmp3Pin, Op5 = IdealOpAmp3Pin, C7 = Capacitor | Map(C=l2*1u"F"), C8 = Capacitor | Map(C=c4, i=Var(start=0u"A")), C9 = Capacitor | Map(C=c4 + c5), R11 = Resistor | Map(R=1u"Ξ©"), G2 = Ground, G3 = Ground, G4 = Ground, V = ConstantVoltage | Map(V=1.0u"V"), Ground1 = Ground, connect = :[ (Op1.in_p, G.p) (G1.p, Op2.in_p) (R1.n, Op1.in_n, C2.n, R2.n, C1.p, R3.p) (R3.n, C1.n, Op1.out, R4.p, C5.p) (R4.n, Op2.in_n, C3.p, R5.n) (C2.p, R5.p, Op3.out, C6.n, R9.p, C8.p) (C3.n, Op2.out, R2.p, R7.p) (R7.n, Op3.in_n, C5.n, R6.n, C6.p, C4.n) (C4.p, R8.p, R11.n, C9.n, Op5.out) (R9.n, R8.n, Op4.in_n, C7.p) (R6.p, C7.n, Op4.out, R10.p) (G2.p, Op3.in_p) (R11.p, C9.p, R10.n, Op5.in_n, C8.n) (Op4.in_p, G3.p) (Op5.in_p, G4.p) (V.p, Ground1.p) (V.n, R1.p) ] ) println("Build array of Cauer low pass filters") @time Filters = Model( filters = [CauerLowPassOPVWithoutNodes(0.1*i) for i in 1:10] ) model = @instantiateModel(Filters, logDetails=false, logTiming=true, unitless=true) println("Simulate") @time simulate!(model, Tsit5(), stopTime = 60, requiredFinalStates = [-0.5000732186007855, -0.5002239998029879, 0.4996923410661849, -0.4996706636198064, -0.5000929741546876, -0.5001255383344897, -0.500147742207576, 0.49981113006573824, -0.4996196061432069, -0.5001392063603706, -0.5001815616147427, -0.5000459266587362, 0.49996685095395915, -0.49958392015463465, -0.5001886259176451, -0.5002389821958331, -0.4999173001411904, 0.5001611780149184, -0.49957016523210945, -0.5002393712119582, -0.5002944833191254, -0.49976183273648583, 0.5003940588092074, -0.49958591550449066, -0.5002887040151874, -0.500343478728503, -0.4995812991530469, 0.5006629055320556, -0.49963969356758026, -0.5003327561376948, -0.50037980690654, -0.49938004306850625, 0.5009615326279456, -0.4997407922705924, -0.5003662177501006, -0.500395375828166, -0.4991659724894459, 0.5012787730322307, -0.4998989295998676, -0.5003819572251011, -0.5003797586125351, -0.49895184523346914, 0.5015966895590688, -0.5001236602409048, -0.5003705619890064, -0.5003197458974357, -0.49875691633150787, 0.5018882791340892, -0.5004234377294563, -0.5003197904255381]) plot(model, ["filters_1.C9.v", "filters_2.C9.v", "filters_3.C9.v"]) println("Total") end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
2434
module FilterCircuit using TinyModia using DifferentialEquations using ModiaPlot setLogMerge(false) include("../models/Electric.jl") Filter = Model( R = Resistor | Map(R=0.5u"Ξ©"), C = Capacitor | Map(C=2.0u"F", v=Var(init=0.1u"V")), V = ConstantVoltage | Map(V=10.0u"V"), ground = Ground, connect = :[ (V.p, R.p) (R.n, C.p) (C.n, V.n, ground.p) ] ) model = @instantiateModel(Filter, log=false, aliasReduction=true, logCode=false) @time simulate!(model, Tsit5(), stopTime = 10) #plot(model, [("R.v", "C.v")]) println("Simulate once more with different R.R") @time simulate!(model, Tsit5(), stopTime = 10, merge = Map(R = Map(R = 5u"Ξ©")), requiredFinalStates = [6.3579935215716095]) plot(model, [("R.v", "C.v")]) # setLogMerge(true) println("Filter without ground and parameter propagation") Filter2 = Model( r = 2.0u"Ξ©", c = 1.0u"F", v = 10u"V", R = Resistor | Map(R=:r), C = Capacitor | Map(C=:c), V = ConstantVoltage | Map(V=:v), connect = :[ (V.p, R.p) (R.n, C.p) (C.n, V.n) ] ) # @showModel(Filter2) model = @instantiateModel(Filter2, log=false, aliasReduction=true, logCode=false) simulate!(model, Tsit5(), stopTime = 10, requiredFinalStates = [9.932620374719848]) plot(model, [("R.v", "C.v")]) println("Voltage divider by redeclaring capacitor to resistor") Cpar = Map(C = 5.0u"F") TwoFilters = Model( f1 = Filter | Map( R = Map(R = 10.0u"Ξ©"), C = Cpar), f2 = Filter) VoltageDividerAndFilter = TwoFilters | Map(f1 = Map(C = Redeclare | Resistor | (R = 20.0u"Ξ©", v = Var(start = 0u"V")))) model = @instantiateModel(VoltageDividerAndFilter, log=false, aliasReduction=true, logCode=false) simulate!(model, Tsit5(), stopTime = 10, requiredFinalStates = [9.999550454584188]) plot(model, [("f1.R.v", "f1.C.v"), ("f2.R.v", "f2.C.v")]) println("Build array of filters") Filters = Model( filters = [Filter | Map( R = Map(R = (10.0+5*i)*u"Ξ©")) for i in 1:10] ) setLogMerge(false) model = @instantiateModel(Filters, log=false, aliasReduction=true, logCode=false) simulate!(model, Tsit5(), stopTime = 10, requiredFinalStates = [2.9063400246452358, 2.2898722474751163, 1.8945655444974656, 1.6198309235728083, 1.4179087924692246, 1.2632806644107324, 1.1410907635368692, 1.0421095614435398, 0.9603029088053439, 0.8915602951695468]) plot(model, [("filters_1.R.v", "filters_1.C.v"), ("filters_2.R.v", "filters_2.C.v")]) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
1573
module FilterCircuit using TinyModia using DifferentialEquations using ModiaPlot using Unitful setLogMerge(true) include("../models/ElectricTest.jl") # res = Resistor # @showModel(res) @showModel(Capacitor) Filter = Model( R = Resistor | Map(R=0.5u"Ξ©"), C = Capacitor | Map(C=2.0u"F", v=Map(init=0.1u"V")), V = ConstantVoltage | Map(V=10.0u"V"), ground = Ground, connect = :[ (V.p, R.p) (R.n, C.p) (C.n, V.n, ground.p) ] ) @showModel(Filter) #= Filter2 = Model( r = 1.0u"Ξ©", c = 1.0u"F", v = 1.0u"V", R = Resistor | Map(R=:(up.r)), C = Capacitor | Map(C=:(up.c)), V = ConstantVoltage | Map(V=:(up.v)), ground = Ground, connect = :[ (V.p, R.p) (R.n, C.p) (C.n, V.n, ground.p) ] ) Cpar = Map(C = 5.0u"F") TwoFilters = Model( f1 = Filter | Map( R = Map(R = 10.0u"Ξ©"), C = Cpar), f2 = Filter) VoltageDividerAndFilter = TwoFilters | Map(f1 = Map(C = Redeclare | Resistor | (R = 20.0u"Ξ©", start = Map(v = 0u"V")))) println("Build") @time Filters = Model( filters = [Filter for i in 1:10] ) setLogMerge(false) model = @instantiateModel(Filters, logDetails=false, aliasReduction=false) println("Simulate") @time simulate!(model, Tsit5(), stopTime = 50, requiredFinalStates = [9.999999294887072, 9.999999294887072, 9.999999294887072, 9.999999294887072, 9.999999294887072, 9.999999294887072, 9.999999294887072, 9.999999294887072, 9.999999294887072, 9.999999294887072]) plot(model, [("filters_1.R.v", "filters_1.C.v"), ("filters_2.R.v", "filters_2.C.v")]) =# end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
5035
module MotorControl println("\nMotorControl: Demonstrating the ability to simulate hierarchical mixed domain models") include("../models/Blocks.jl") include("../models/Electric.jl") include("../models/Rotational.jl") using TinyModia using DifferentialEquations using ModiaPlot using Measurements export MotorControl2 MotorControl1 = Model( step = Step | Map(height=4.7*u"A", offset=0u"A"), feedback = Feedback, PI = PI | Map(T=0.005u"s", k=30, x = Var(init=0.0u"A")), firstOrder = FirstOrder | Map(k=1u"V/A", T=0.001u"s", x = Var(init=0.0u"V")), signalVoltage = SignalVoltage, resistor = Resistor | Map(R=13.8u"Ξ©"), inductor = Inductor | Map(L=0.061u"H"), emf = EMF | Map(k=1.016u"N*m/A"), ground = Ground, currentSensor = CurrentSensor, motorInertia = Inertia | Map(J=0.0025u"kg*m^2"), idealGear = IdealGear | Map(ratio=105), springDamper = SpringDamper | Map(c=5.0e5u"N*m/rad", d=500u"N*m*s/rad"), loadInertia = Inertia | Map(J=100u"kg*m^2"), tload = Torque, equations = :[ tload.tau = 0.0u"N*m", ], connect = :[ (step.y, feedback.u1) (feedback.y, PI.u) (PI.y, firstOrder.u) (firstOrder.y, signalVoltage.v) (signalVoltage.p, resistor.p) (resistor.n, inductor.p) (inductor.n, emf.p) (emf.n, ground.p, currentSensor.p) (currentSensor.n, signalVoltage.n) (currentSensor.i, feedback.u2) (emf.flange, motorInertia.flange_a) (motorInertia.flange_b, idealGear.flange_a) (idealGear.flange_b, springDamper.flange_a) (springDamper.flange_b, loadInertia.flange_a) (tload.flange, loadInertia.flange_b) ] ) model = @instantiateModel(MotorControl1, log=false) println("Simulate") @time simulate!(model, stopTime=0.1, tolerance=1e-6, log=false, requiredFinalStates = [3.487844601078223, 106.82874860310305, 4.616087152802267, 2.014120727821878, 41.98048886114646, 0.018332432934516536, 0.3725930536373392]) plot(model, [("currentSensor.i", "step.y"), "loadInertia.w"], figure=1) # Hierarchical model ControlledMotor = Model( refCurrent = input, feedback = Feedback, PI = PI | Map(T=0.005u"s", k=30, x = Var(init=0.0u"A")), firstOrder = FirstOrder | Map(k=1u"V/A", T=0.001u"s", x = Var(init=0.0u"V")), signalVoltage = SignalVoltage, resistor = Resistor | Map(R=13.8u"Ξ©"), inductor = Inductor | Map(L=0.061u"H"), emf = EMF | Map(k=1.016u"N*m/A"), ground = Ground, currentSensor = CurrentSensor, motorInertia = Inertia | Map(J=0.0025u"kg*m^2"), flange = Flange, connect = :[ (refCurrent, feedback.u1) (feedback.y, PI.u) (PI.y, firstOrder.u) (firstOrder.y, signalVoltage.v) (signalVoltage.p, resistor.p) (resistor.n, inductor.p) (inductor.n, emf.p) (emf.n, ground.p, currentSensor.p) (currentSensor.n, signalVoltage.n) (currentSensor.i, feedback.u2) (emf.flange, motorInertia.flange_a) (motorInertia.flange_b, flange) ] ) MotorControl2 = Model( step = Step | Map(height=4.7*u"A", offset=0u"A"), controlledMotor = ControlledMotor, idealGear = IdealGear | Map(ratio=105), springDamper = SpringDamper | Map(c=5.0e5u"N*m/rad", d=500u"N*m*s/rad"), loadInertia = Inertia | Map(J=100.0u"kg*m^2"), tload = Torque, equations = :[ tload.tau = 0.0u"N*m", ], connect = :[ (step.y, controlledMotor.refCurrent) (controlledMotor.flange, idealGear.flange_a) (idealGear.flange_b, springDamper.flange_a) (springDamper.flange_b, loadInertia.flange_a) (tload.flange, loadInertia.flange_b) ] ) model = @instantiateModel(MotorControl2) println("Simulate") @time simulate!(model, stopTime=0.1, tolerance=1e-6, log=false, requiredFinalStates = [3.487844601078223, 106.82874860310305, 4.616087152802267, 2.014120727821878, 41.98048886114646, 0.018332432934516536, 0.3725930536373392]) plot(model, [("controlledMotor.currentSensor.i", "step.y"), "loadInertia.w"], figure=1) # Model with uncertainties MotorControlWithUncertainties = MotorControl2 | Map( loadInertia = Map(J=(100.0 Β± 10)*u"kg*m^2"), controlledMotor = Map(PI = Map(k=30 Β± 3) ) ) model = @instantiateModel(MotorControlWithUncertainties, FloatType = Measurement{Float64}) println("Simulate") @time simulate!(model, stopTime=0.1, tolerance=1e-6, log=false) plot(model, [("controlledMotor.currentSensor.i", "step.y"), "loadInertia.w"], figure=1) end #= module MotorControlModuleMonteCarlo using ModiaBase.TinyModia using Unitful using Main.MotorControlModule include("../test/SimulateAndPlot.jl") using MonteCarloMeasurements # Model with Monte Carlo MotorControlWithUncertainties = MotorControl2 | Map( loadInertia = Map(J=(100.0 βˆ“ 10)), controlledMotor = Map(PI = Map(k=30 βˆ“ 3) ) ) model = @instantiateModel(MotorControlWithUncertainties, FloatType = StaticParticles{Float64,100}, unitless=true) println("Simulate") @time simulate!(model, stopTime=0.1, tolerance=1e-6, log=false) plot(model, [("controlledMotor.currentSensor.i", "step.y"), "loadInertia.w"], figure=1) end =#
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
4431
module ServoSystemSimulation println("\nServoSystem: Demonstrating the ability to simulate hierarchical mixed domain models") include("../models/Blocks.jl") include("../models/Electric.jl") include("../models/Rotational.jl") using TinyModia using DifferentialEquations using ModiaPlot #using Measurements using MonteCarloMeasurements setLogMerge(false) Gear = Model( flange_a = Flange, flange_b = Flange, gear = IdealGear_withSupport | Map(ratio = 105.0), fixed = Fixed, spring = Spring | Map(c=5.84e5u"N*m/rad"), damper1 = Damper | Map(d=500.0u"N*m*s/rad"), damper2 = Damper | Map(d=100.0u"N*m*s/rad"), connect = :[ (flange_a , gear.flange_a) (fixed.flange , gear.support, damper2.flange_b) (gear.flange_b, damper2.flange_a, spring.flange_a, damper1.flange_a) (flange_b , spring.flange_b, damper1.flange_b)] ) ControlledMotor = Model( refCurrent = input, flange = Flange, feedback = Feedback, PI = PI | Map(k=30, T=1.0u"s"), firstOrder = FirstOrder | Map(k=1.0, T=0.001u"s"), signalVoltage = UnitlessSignalVoltage, resistor = Resistor | Map(R=13.8u"Ξ©"), inductor = Inductor | Map(L=0.061u"H"), emf = EMF | Map(k=1.016u"N*m/A"), ground = Ground, currentSensor = UnitlessCurrentSensor, motorInertia = Inertia | Map(J=0.0025u"kg*m^2"), connect = :[ (refCurrent, feedback.u1) (feedback.y, PI.u) (PI.y, firstOrder.u) (firstOrder.y, signalVoltage.v) (signalVoltage.p, resistor.p) (resistor.n, inductor.p) (inductor.n, emf.p) (emf.n, ground.p, currentSensor.p) (currentSensor.n, signalVoltage.n) (currentSensor.i, feedback.u2) (emf.flange, motorInertia.flange_a) (motorInertia.flange_b, flange) ] ) SpeedController = Model( refSpeed = input, motorSpeed = input, refCurrent = output, gain = Gain | Map(k=105.0), PI = PI | Map(T=1.0u"s", k=1.0), feedback = Feedback, connect = :[ (refSpeed , gain.u) (gain.y , feedback.u1) (motorSpeed, feedback.u2) (feedback.y, PI.u) (PI.y , refCurrent)] ) Servo = Model( refSpeed = input, flange_b = Flange, speedController = SpeedController | Map(ks=1.0, Ts=1.0u"s", ratio=105.0), motor = ControlledMotor | Map(km=30.0, Tm=0.005u"s"), gear = Gear | Map(ratio=105.0), speedSensor1 = UnitlessSpeedSensor, speedSensor2 = UnitlessSpeedSensor, speedError = Feedback, connect = :[ (refSpeed , speedController.refSpeed, speedError.u1) (speedController.refCurrent, motor.refCurrent) (motor.flange , gear.flange_a, speedSensor1.flange) (speedSensor1.w , speedController.motorSpeed) (gear.flange_b , flange_b, speedSensor2.flange) (speedSensor2.w , speedError.u2)] ) TestServo = Model( ks = 0.8, Ts = 0.08u"s", ramp = Ramp | Map(duration=1.18u"s", height=2.95), servo = Servo | Map(ks=:(up.ks), Ts=:(up.Ts)), load = Inertia | Map(J=170u"kg*m^2"), equations =:[load.flange_b.tau = 0u"N*m"], connect = :[ (ramp.y , servo.refSpeed) (servo.flange_b, load.flange_a) ] ) plotVariables = [("ramp.y", "load.w"), "servo.speedError.y", "servo.motor.currentSensor.i"] model = @instantiateModel(TestServo) println("Simulate") @time simulate!(model, Tsit5(), stopTime=2.0, tolerance=1e-6, log=false, requiredFinalStates = [7.320842067204029, 9.346410309487013, 355.30389168655955, 2.792544498835712, 429.42665751348284, 311.7812493890421, 4.089776248793499, 2.969353608933471]) plot(model, plotVariables, figure=1) println("\nModel with uncertainties") #TestServoWithUncertainties = TestServo | Map( load = Map(J=(110.0 Β± 20)*u"kg*m^2") ) TestServoWithUncertainties = TestServo | Map( load = Map(J=(110.0 βˆ“ 20) ) ) # u"kg*m^2") ) #Map( ramp = Map(height=3 βˆ“ 1)) #model = @instantiateModel(TestServoWithUncertainties , FloatType = Measurement{Float64}) model = @instantiateModel(TestServoWithUncertainties , FloatType = StaticParticles{Float64,100}, unitless=true, log=false, logCode=false, logExecution=false) println("Simulate") @time simulate!(model, Tsit5(), stopTime=2.0, tolerance=1e-6, log=false) plot(model, plotVariables, figure=2) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
4394
module ServoSystemSimulation println("\nServoSystem: Demonstrating the ability to simulate hierarchical mixed domain models") include("../models/Blocks.jl") include("../models/Electric.jl") include("../models/Rotational.jl") using TinyModia using DifferentialEquations using ModiaPlot using Unitful #using Measurements using MonteCarloMeasurements setLogMerge(false) Gear = Model( flange_a = Flange, flange_b = Flange, gear = IdealGear_withSupport | Map(ratio = 105), fixed = Fixed, spring = Spring | Map(c=5.84e5u"N*m/rad"), damper1 = Damper | Map(d=500u"N*m*s/rad"), damper2 = Damper | Map(d=100u"N*m*s/rad"), connect = :[ (flange_a , gear.flange_a) (fixed.flange , gear.support, damper2.flange_b) (gear.flange_b, damper2.flange_a, spring.flange_a, damper1.flange_a) (flange_b , spring.flange_b, damper1.flange_b)] ) ControlledMotor = Model( inputs = :[refCurrent], flange = Flange, feedback = Feedback, PI = PI | Map(k=30, T=1.0u"s", init = Map(x=0.0u"A")), firstOrder = FirstOrder | Map(k=1u"V/A", T=0.001u"s", init = Map(x=0.0u"V")), signalVoltage = SignalVoltage, resistor = Resistor | Map(R=13.8u"Ξ©"), inductor = Inductor | Map(L=0.061u"H"), emf = EMF | Map(k=1.016u"N*m/A"), ground = Ground, currentSensor = CurrentSensor, motorInertia = Inertia | Map(J=0.0025u"kg*m^2"), connect = :[ (refCurrent, feedback.u1) (feedback.y, PI.u) (PI.y, firstOrder.u) (firstOrder.y, signalVoltage.v) (signalVoltage.p, resistor.p) (resistor.n, inductor.p) (inductor.n, emf.p) (emf.n, ground.p, currentSensor.p) (currentSensor.n, signalVoltage.n) (currentSensor.i, feedback.u2) (emf.flange, motorInertia.flange_a) (motorInertia.flange_b, flange) ] ) SpeedController = Model( inputs = :[refSpeed, motorSpeed], outputs = :[refCurrent], gain = Gain | Map(k=105), PI = PI | Map(T=1.0u"s", k=1.0u"A*s/rad", init = Map(x=0u"rad/s")), feedback = Feedback, connect = :[ (refSpeed , gain.u) (gain.y , feedback.u1) (motorSpeed, feedback.u2) (feedback.y, PI.u) (PI.y , refCurrent)] ) Servo = Model( inputs = :[refSpeed], flange_b = Flange, speedController = SpeedController | Map(ks=1.0u"A*s/rad", Ts=1.0u"s", ratio=105), motor = ControlledMotor | Map(km=30.0, Tm=0.005u"s"), gear = Gear | Map(ratio=105), speedSensor1 = SpeedSensor, speedSensor2 = SpeedSensor, speedError = Feedback, connect = :[ (refSpeed , speedController.refSpeed, speedError.u1) (speedController.refCurrent, motor.refCurrent) (motor.flange , gear.flange_a, speedSensor1.flange) (speedSensor1.w , speedController.motorSpeed) (gear.flange_b , flange_b, speedSensor2.flange) (speedSensor2.w , speedError.u2)] ) TestServo = Model( ks = 0.8u"A*s/rad", Ts = 0.08u"s", ramp = Ramp | Map(duration=1.18u"s", height=2.95u"rad/s", offset=0.0u"rad/s"), servo = Servo | Map(ks=:(up.ks), Ts=:(up.Ts)), load = Inertia | Map(J=170u"kg*m^2"), equations =:[load.flange_b.tau = 0u"N*m"], connect = :[ (servo.refSpeed, ramp.y) (load.flange_a, servo.flange_b) ] ) plotVariables = [("ramp.y", "load.w"), "servo.speedError.y", "servo.motor.currentSensor.i"] model = @instantiateModel(TestServo, log=false, logDetails=false) println("Simulate") @time simulate!(model, Tsit5(), stopTime=2.0, tolerance=1e-6, log=false) plot(model, plotVariables, figure=1) println("\nModel with uncertainties") #TestServoWithUncertainties = TestServo | Map( load = Map(J=(110.0 Β± 20)*u"kg*m^2") ) TestServoWithUncertainties = TestServo | Map( load = Map(J=(110.0 βˆ“ 20) ) ) # u"kg*m^2") ) #Map( ramp = Map(height=3 βˆ“ 1)) #model = @instantiateModel(TestServoWithUncertainties , FloatType = Measurement{Float64}) model = @instantiateModel(TestServoWithUncertainties , FloatType = StaticParticles{Float64,100}, unitless=true, log=false, logCode=false, logExecution=false) println("Simulate") @time simulate!(model, Tsit5(), stopTime=2.0, tolerance=1e-6, log=false) plot(model, plotVariables, figure=2) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
1952
module SimpleFilters using TinyModia using DifferentialEquations using ModiaPlot SimpleModel = Model( T = 0.2, x = Var(init=0.5), equation = :[T * der(x) + x = 2] ) # @showModel(SimpleModel) model = @instantiateModel(SimpleModel) simulate!(model, Tsit5(), stopTime = 5, requiredFinalStates = [1.9999996962023168]) plot(model, ["x"]) LowPassFilter = Model( T = 0.2, u = input, y = output | Var(:x), x = Var(init=0.0u"V"), equations = :[T * der(x) + x = u], ) # @showModel(LowPassFilter) HighPassFilter = LowPassFilter | Model( y = Var(:(-x + u)), ) # @showModel(HighPassFilter) # setLogMerge(true) LowAndHighPassFilter = LowPassFilter | Model( y = nothing, low = output | Var(:x), high = output | Var(:(-x + u)), ) setLogMerge(false) # @showModel(LowAndHighPassFilter) TestLowAndHighPassFilter = LowAndHighPassFilter | Model( u = :(sin( (time+1u"s")*u"1/s/s" * time)*u"V"), x = Var(init=0.2u"V") ) # @showModel(TestLowAndHighPassFilter) model = @instantiateModel(TestLowAndHighPassFilter, log=false, logCode=false) simulate!(model, Tsit5(), stopTime = 5, requiredFinalStates = [-0.22633046061014014]) plot(model, ["low", "high"]) TwoFilters = Model( high = HighPassFilter, low = LowPassFilter, ) # @showModel(TwoFilters) BandPassFilter = Model( u = input, y = output, high = HighPassFilter | Map(T=0.5, x=Var(init=0.1u"V")), low = LowPassFilter | Map(x=Var(init=0.2u"V")), equations = :[ high.u = u, low.u = high.y, y = low.y] ) # @showModel(BandPassFilter) TestBandPassFilter = BandPassFilter | Model( u = :(sin( (0.05*time+1u"s")*u"1/s/s" * time)*u"V"), ) # @showModel(TestBandPassFilter) setLogMerge(false) model = @instantiateModel(TestBandPassFilter, logDetails=false) simulate!(model, Tsit5(), stopTime = 50, requiredFinalStates = [-0.25968254453053435, -0.6065869606784539]) plot(model, ["u", "y"]) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
230
using Test @testset "TinyModia examples with simulation" begin include("SimpleFilters.jl") include("FilterCircuit.jl") include("CauerLowPassFilter.jl") include("MotorControl.jl") include("ServoSystem.jl") end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
68
include("Blocks.jl") include("Electric.jl") include("Rotational.jl")
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
3771
""" Modia module with block component models (inspired from Modelica Standard Library). * Developer: Hilding Elmqvist, Mogram AB, Martin Otter, DLR * Copyright (c) 2016-2021: Hilding Elmqvist, Martin Otter * License: MIT (expat) """ #module Blocks using TinyModia using Unitful #export Gain, FirstOrder, Feedback, PI, Step, Ramp # Sine, Switch, MIMO # Single-Input-Single-Output continuous control block SISO = Model( u = input, y = output ) # Gain Gain = SISO | Model( k = 1, # (info = "Gain") equations = :[ y = k*u ] ) # First-order transfer function block (= 1 pole) FirstOrder = SISO | Model( k = 1.0, T = 1.0*u"s", x = Var(init=0.0), equations = :[ der(x) = (k * u - x) / T y = x ] ) # Output difference between commanded and feedback input Feedback = Model( u1 = input | info"Input 1", u2 = input | info"Input 2", y = output | info"Output signal", equations = :[ y = u1 - u2 ] ) # Proportional-Integral controller PI = SISO | Model( k = 1.0, # (info = "Gain") T = 1.0u"s", # (min = 1E-10, info = "Time Constant (T>0 required)") x = Var(init=0.0), equations = :[ der(x) = u / T y = k * (x + u) ] ) # Single-Output continuous control block SO = Model( y = output ) # Base class for a continuous signal source SignalSource = SO | Model( offset = 0.0, # info = "Offset of output signal y" startTime = 0.0*u"s" # info = "Output y = offset for time < startTime") ) # Step signal Step = SignalSource | Model( height = 1.0, equations = :[ y = offset + (time < startTime ? 0*height : height) ] # 0*height is needed, if height has a unit ) # Ramp signal Ramp = SignalSource | Model( height = 1.0, duration = 2.0u"s", equations = :[ y = offset + (time < startTime ? 0.0*height : # 0*height is needed, if height has a unit (time < startTime + duration ? (time - startTime)*height/duration : height)) ] ) # Linear state space system StateSpace = Model( A = fill(0.0,0,0), B = fill(0.0,0,0), C = fill(0.0,0,0), D = fill(0.0,0,0), u = input, y = output, x = Var(init = zeros(0)), equations = :[ der(x) = A*x + B*u y = C*x + D*u ] ) # ------------------------------------------------------- #= # Sinusoidal signal @model Sine begin amplitude = Parameter(1.0, info = "Amplitude of sine wave") freqHz = Parameter(1.0,info = "Frequency of sine wave") phase = Parameter(0.0, info = "Phase of sine wave") offset = Parameter(0.0, info = "Offset of output signal y") startTime = Parameter(0.0, info = "Output y = offset for time < startTime") SO() equations y = offset + if time < startTime; 0 else amplitude*sin(2*pi*freqHz*(time - startTime) + phase) end end @model Sine2 begin # Generate sine signal amplitude = Parameter(1.0, info = "Amplitude of sine wave") freqHz = Parameter(1.0,info = "Frequency of sine wave") phase = Parameter(0.0, info = "Phase of sine wave") SignalSource() equations y = offset + if time < startTime; 0 else amplitude * sin(2 * pi * freqHz * (time - startTime) + phase) end end # Switch @model Switch begin sw = Input(Boolean(info = "Switch position (if `true`, use `u1`, else use `u2`)")) u1 = Input(info = "Input 1") u2 = Input(info = "Input 2") y = Output(info = "Output signal") equations y = if sw; u1 else u2 end end # ABCD model @model ABCD(A = -1, B = 1, C = 1, D = 0) begin u = Input(info = "Input signal"); y = Output(info = "Output signal") x = Float(start = 0) equations der(x) = A * x + B * u y = C * x + D * u end =# #end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
4430
""" Modia module with electric component models (inspired from Modelica Standard Library). * Developer: Hilding Elmqvist, Mogram AB * Copyright (c) 2016-2021: Hilding Elmqvist * License: MIT (expat) """ #module Electric using TinyModia using Unitful Pin = Model( v = potential, i = flow ) OnePort = Model( p = Pin, n = Pin, partialEquations = :[ v = p.v - n.v 0 = p.i + n.i i = p.i ] ) """ Resistor(R=1.0u"Ξ©") Electrical resistor `R` - Resistance Ξ© """ Resistor = OnePort | Model( R = 1.0u"Ξ©", equations = :[ R*i = v ] ) # @showModel(Resistor) Capacitor = OnePort | Model( C = 1.0u"F", v=Var(init=0.0u"V"), equations = :[ C*der(v) = i ] ) Inductor = OnePort | Model( L = 1.0u"H", i=Var(init=0.0u"A"), equations = :[ L*der(i) = v ] ) ConstantVoltage = OnePort | Model( V = 1.0u"V", equations = :[ v = V ] ) Ground = Model( p = Pin, equations = :[ p.v = 0.0u"V" ] ) # Ideal operational amplifier (norator-nullator pair), but 3 pins IdealOpAmp3Pin = Model( in_p = Pin, in_n = Pin, out = Pin, equations = :[ in_p.v = in_n.v in_p.i = 0u"A" in_n.i = 0u"A" ] ) # Partial generic voltage source using the input signal as source voltage PartialSignalVoltage = Model( v = input, p = Pin, n = Pin ) # Generic voltage source using the input signal (without and with unit) as source voltage SignalVoltage = PartialSignalVoltage | Model( equations = :[ p.v - n.v = v 0 = p.i + n.i i = p.i ] ) UnitlessSignalVoltage = PartialSignalVoltage | Model( equations = :[ p.v - n.v = v*u"V" 0 = p.i + n.i i = p.i ] ) # Partial sensor to measure the current in a branch PartialCurrentSensor = Model( i = output, p = Pin, # (info = "Positive pin") n = Pin, # (info = "Negative pin") ) # Sensor to measure the current in a branch CurrentSensor = PartialCurrentSensor | Model( equations = :[ p.v = n.v 0 = p.i + n.i i = p.i] ) UnitlessCurrentSensor = PartialCurrentSensor | Model( equations = :[ p.v = n.v 0 = p.i + n.i i = p.i/u"A"] ) #= # Step voltage source @model StepVoltage begin V = Parameter(1.0, start = 1.0, info = "Voltage") #, T = Unitful.V) startTime = Parameter(0.0, start = 0.0, info = "Start time") # , T = Unitful.s) OnePort() equations v = if time < startTime; 0 else V end end @model VoltageSource begin OnePort() offset = Par(0.0) # Voltage offset startTime = Par(0.0) # Time offset signalSource = SignalSource(offset=offset, startTime=startTime) equations v = signalSource.y end #= @model SineVoltage1 begin # Sine voltage source V = Parameter() # Amplitude of sine wave phase = Par(0.0) # Phase of sine wave freqHz = Parameter() # Frequency of sine wave VoltageSource(signalSource=Sine(amplitude=V, freqHz=freqHz, phase=phase)) end =# # Sinusoidal voltage source @model SineVoltage begin V = Parameter() # Amplitude of sine wave phase = Par(0.0) # Phase of sine wave freqHz = Parameter() # Frequency of sine wave VoltageSource() equations v = V*sin(10*time) end # Ideal diode @model IdealDiode begin # Ideal diode OnePort() Ron = Par(1.0E-2) # Forward state-on differential resistance (closed diode resistance) Goff = Par(1.0E-2) # Backward state-off conductance (opened diode conductance) Vknee = Par(0) # Forward threshold voltage # off = Variable(start=true) # Switching state s = Float(start=0.0) # Auxiliary variable for actual position on the ideal diode characteristic #= s = 0: knee point s < 0: below knee point, diode conducting s > 0: above knee point, diode locking =# equations # off := s < 0 # v = s * if !positive(s); 1 else Ron end + Vknee # i = s * if !positive(s); Goff else 1 end + Goff * Vknee v = s * if !(s>0); 1 else Ron end + Vknee i = s * if !(s>0); Goff else 1 end + Goff * Vknee end @model Diode begin OnePort() Ids=Par(1.e-6) # "Saturation current"; Vt=Par(0.04) # "Voltage equivalent of temperature (kT/qn)"; Maxexp = Par(15) # "Max. exponent for linear continuation"; R=Par(1.e8) # "Parallel ohmic resistance"; equations i = if v/Vt > Maxexp; Ids*(exp(Maxexp)*(1 + v/Vt - Maxexp) - 1) else Ids*(exp(v/Vt) - 1) end + v/R end =# #end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
5230
""" Modia module with electric component models (inspired from Modelica Standard Library). * Developer: Hilding Elmqvist, Mogram AB * Copyright (c) 2016-2021: Hilding Elmqvist * License: MIT (expat) """ #module Electric using TinyModia using Unitful Var(args...; kwargs...) = (;args..., kwargs...) Var(value::Union{Float64, Int64, Bool, String, Expr}, args...; kwargs...) = (;value = value, args..., kwargs...) parameter = :parameter => true input = :input => true output = :output => true potential = :potential => true flow = :flow => true v = Var(potential, nominal=10) @show v v = Var(5, parameter, min=0) @show v v = Var(potential, min=0, flow, nominal=10) @show v Pin = Model( v = Var(potential, nominal=10), i = Var(flow) ) @show Pin Input(; kwargs...) = (;input=true, kwargs...) Output(; kwargs...) = (;output=true, kwargs...) Potential(; kwargs...) = (;potential=true, kwargs...) Flow(; kwargs...) = (;flow=true, kwargs...) Pin = Model( v = Potential(nominal=10), i = Flow() ) @show Pin #Pin = Model( potentials = :[v], flows = :[i] ) Pin = Model( v = Var(;pot), i = Var(;flow) ) OnePort = Model( p = Pin, n = Pin, partialEquations = :[ v = p.v - n.v 0 = p.i + n.i i = p.i ] ) """ Resistor(R=1.0u"Ξ©") Electrical resistor `R` - Resistance Ξ© """ Resistor = OnePort | Model( R = 1.0u"Ξ©", equations = :[ R*i = v ] ) Capacitor = OnePort | Model( C = 1.0u"F", v = Map(init=0.0u"V"), equations = :[ C*der(v) = i ] ) Inductor = OnePort | Model( L = 1.0u"H", init=Map(i=0.0u"A"), equations = :[ L*der(i) = v ] ) ConstantVoltage = OnePort | Model( V = 1.0u"V", equations = :[ v = V ] ) Ground = Model( p = Pin, equations = :[ p.v = 0.0u"V" ] ) # Ideal operational amplifier (norator-nullator pair), but 3 pins IdealOpAmp3Pin = Model( in_p = Pin, in_n = Pin, out = Pin, equations = :[ in_p.v = in_n.v in_p.i = 0u"A" in_n.i = 0u"A" ] ) # Partial generic voltage source using the input signal as source voltage PartialSignalVoltage = Model( inputs = :[v], p = Pin, n = Pin ) # Generic voltage source using the input signal (without and with unit) as source voltage SignalVoltage = PartialSignalVoltage | Model( equations = :[ p.v - n.v = v 0 = p.i + n.i i = p.i ] ) UnitlessSignalVoltage = PartialSignalVoltage | Model( equations = :[ p.v - n.v = v*u"V" 0 = p.i + n.i i = p.i ] ) # Partial sensor to measure the current in a branch PartialCurrentSensor = Model( outputs = :[i], p = Pin, # (info = "Positive pin") n = Pin, # (info = "Negative pin") ) # Sensor to measure the current in a branch CurrentSensor = PartialCurrentSensor | Model( equations = :[ p.v = n.v 0 = p.i + n.i i = p.i] ) UnitlessCurrentSensor = PartialCurrentSensor | Model( equations = :[ p.v = n.v 0 = p.i + n.i i = p.i/u"A"] ) #= # Step voltage source @model StepVoltage begin V = Parameter(1.0, start = 1.0, info = "Voltage") #, T = Unitful.V) startTime = Parameter(0.0, start = 0.0, info = "Start time") # , T = Unitful.s) OnePort() equations v = if time < startTime; 0 else V end end @model VoltageSource begin OnePort() offset = Par(0.0) # Voltage offset startTime = Par(0.0) # Time offset signalSource = SignalSource(offset=offset, startTime=startTime) equations v = signalSource.y end #= @model SineVoltage1 begin # Sine voltage source V = Parameter() # Amplitude of sine wave phase = Par(0.0) # Phase of sine wave freqHz = Parameter() # Frequency of sine wave VoltageSource(signalSource=Sine(amplitude=V, freqHz=freqHz, phase=phase)) end =# # Sinusoidal voltage source @model SineVoltage begin V = Parameter() # Amplitude of sine wave phase = Par(0.0) # Phase of sine wave freqHz = Parameter() # Frequency of sine wave VoltageSource() equations v = V*sin(10*time) end # Ideal diode @model IdealDiode begin # Ideal diode OnePort() Ron = Par(1.0E-2) # Forward state-on differential resistance (closed diode resistance) Goff = Par(1.0E-2) # Backward state-off conductance (opened diode conductance) Vknee = Par(0) # Forward threshold voltage # off = Variable(start=true) # Switching state s = Float(start=0.0) # Auxiliary variable for actual position on the ideal diode characteristic #= s = 0: knee point s < 0: below knee point, diode conducting s > 0: above knee point, diode locking =# equations # off := s < 0 # v = s * if !positive(s); 1 else Ron end + Vknee # i = s * if !positive(s); Goff else 1 end + Goff * Vknee v = s * if !(s>0); 1 else Ron end + Vknee i = s * if !(s>0); Goff else 1 end + Goff * Vknee end @model Diode begin OnePort() Ids=Par(1.e-6) # "Saturation current"; Vt=Par(0.04) # "Voltage equivalent of temperature (kT/qn)"; Maxexp = Par(15) # "Max. exponent for linear continuation"; R=Par(1.e8) # "Parallel ohmic resistance"; equations i = if v/Vt > Maxexp; Ids*(exp(Maxexp)*(1 + v/Vt - Maxexp) - 1) else Ids*(exp(v/Vt) - 1) end + v/R end =# #end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
2166
#= Modia library with 1D heat transfer component models (inspired from Modelica Standard Library). Developer: Martin Otter, DLR-SR Copyright 2021, DLR Institute of System Dynamics and Control License: MIT (expat) =# using TinyModia using Unitful HeatPort = Model( T = potential, # Absolute temperature Q_flow = flow ) # Heat flow into the component FixedTemperature = Model( T = 293.15u"K", port = HeatPort, equations = :[port.T = T] ) FixedHeatFlow = Model( Q_flow = 0.0u"W", # Fixed heat flow into the connected component port = HeatPort, equations = :[port.Q_flow = -Q_flow] ) HeatCapacitor = Model( C = 1.0u"J/K", port = HeatPort, T = Var(init = 293.15u"K"), equations = :[T = port.T, der(T) = port.Q_flow/C] ) ThermalConductor = Model( G = 1.0u"W/K", port_a = HeatPort, port_b = HeatPort, equations = :[dT = port_a.T - port_b.T 0 = port_a.Q_flow + port_b.Q_flow port_a.Q_flow = G*dT] ) # Fully insulated rod with 1D heat transfer and port_a/port_b on left/right side T_grad1(T,Ta,dx,i) = i == 1 ? (Ta - T[1])/(dx/2) : (T[i-1] - T[i] )/dx T_grad2(T,Tb,dx,i) = i == length(T) ? (T[i] - Tb)/(dx/2) : (T[i] - T[i+1])/dx InsulatedRod = Model( L = 1.0u"m", # Length of rod A = 0.0004u"m^2", # Rod area rho = 7500.0u"kg/m^3", # Density of rod material lambda = 74.0u"W/(m*K)", # Thermal conductivity of rod material c = 450.0u"J/(kg*K)", # Specific heat capacity of rod material port_a = HeatPort, # Heat port on left side port_b = HeatPort, # Heat port on right side T = Map(init = fill(293.15u"K", 1)), # Initial temperature and number of nodes equations = :[ n = length(T) dx = L/n Ce = c*rho*A*dx k = lambda*A/Ce der(T) = k*[T_grad1(T,port_a.T,dx,i) - T_grad2(T,port_b.T,dx,i) for i in eachindex(T)] port_a.Q_flow = lambda*A*(port_a.T - T[1])/(dx/2) port_b.Q_flow = lambda*A*(port_b.T - T[n])/(dx/2) ] )
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
5177
""" Modia module with rotational component models (inspired from Modelica Standard Library). * Developer: Hilding Elmqvist, Mogram AB, Martin Otter, DLR * Copyright (c) 2016-2021: Hilding Elmqvist, Martin Otter * License: MIT (expat) """ #module Rotational #export Flange, Inertia, Spring, SpringDamper, EMF, IdealGear, Torque, CurrentSensor, Fixed, Damper, IdealGear_withSupport, SpeedSensor using TinyModia using Unitful # Connector for 1D rotational systems Flange = Model( phi = potential, tau = flow ) # Flange fixed in housing at a given angle #= Fixed = Model( flange = Flange, phi0 = 0.0u"rad", equations = :[ flange.phi = 0.0u"rad"] ) =# Fixed = Model( flange = Flange, equations = :[ flange.phi = 0.0] ) # 1D-rotational component with inertia Inertia = Model( flange_a = Flange, # (info = "Left flange of shaft") flange_b = Flange, # (info = "Right flange of shaft") J = 1.0u"kg*m^2", # (0, min=0, info = "Moment of inertia") #, T = u"kg*m^2") phi = Var(init=0.0u"rad"), w = Var(init=0.0u"rad/s"), equations = :[ phi = flange_a.phi phi = flange_b.phi w = der(phi) a = der(w) J * a = flange_a.tau + flange_b.tau ] ) # Partial model for the compliant connection of two rotational 1-dim. shaft flanges PartialCompliant = Model( flange_a = Flange, flange_b = Flange, partialEquations = :[ phi_rel = flange_b.phi - flange_a.phi flange_b.tau = tau flange_a.tau = -tau ] ) # Linear 1D rotational spring Spring = PartialCompliant | Model( c = 1.0u"N*m/rad", # (min = 0, info = "Spring constant") phi_rel0 = 0u"rad", # (info = "Unstretched spring angle") equations = :[ tau = c * (phi_rel - phi_rel0) ] ) # Linear 1D rotational spring with damper SpringDamper = PartialCompliant | Model( c = 1.0*u"N*m/rad", # (min = 0, info = "Spring constant") d = 0.0u"N*m*s/rad", # (info = "Damping constant") phi_rel0 = 0u"rad", # (info = "Unstretched spring angle") equations = :[ tau = c * (phi_rel - phi_rel0) + d * der(phi_rel) ] ) # Electromotoric force (electric/mechanic) transformer EMF = Model( k = 1.0u"N*m/A", # (info = "Transformation coefficient") p = Pin, n = Pin, flange = Flange, equations = :[ v = p.v - n.v 0 = p.i + n.i i = p.i phi = flange.phi w = der(phi) k * w = v flange.tau = -k * i ] ) # Ideal gear IdealGear = Model( flange_a = Flange, # "Left flange of shaft" flange_b = Flange, # "Right flange of shaft" ratio = 1.0, # "Transmission ratio (flange_a.phi/flange_b.phi)" equations = :[ phi_a = flange_a.phi phi_b = flange_b.phi phi_a = ratio * phi_b 0 = ratio * flange_a.tau + flange_b.tau ] ) # Ideal gear with support IdealGear_withSupport = Model( flange_a = Flange, # "Left flange of shaft" flange_b = Flange, # "Right flange of shaft" support = Flange, # "Support flange" ratio = 1.0, # "Transmission ratio" equations = :[ phi_a = flange_a.phi - support.phi phi_b = flange_b.phi - support.phi phi_a = ratio * phi_b 0 = ratio * flange_a.tau + flange_b.tau 0 = flange_a.tau + flange_b.tau + support.tau ] ) # Partial input signal acting as external torque on a flange PartialTorque = Model( tau = input, flange = Flange ) # Input signal acting as external torque on a flange Torque = PartialTorque | Model(equations = :[flange.tau = -tau]) UnitlessTorque = PartialTorque | Model(equations = :[flange.tau = -tau*u"N*m"]) #= # Partial model for the compliant connection of two rotational 1-dim. shaft flanges where the relative angle and speed are used as preferred states PartialCompliantWithRelativeStates = Model( flange_a = Flange, flange_b = Flange, init = Map(phi_rel=0.0u"rad", w_rel=0.0u"rad/s"), equations = :[ phi_rel = flange_b.phi - flange_a.phi w_rel = der(phi_rel) a_rel = der(w_rel) flange_b.tau = tau flange_a.tau = -tau ] ) # Linear 1D rotational damper Damper = PartialCompliantWithRelativeStates | Model( d = 1.0u"N*m*s/rad", # (info = "Damping constant"), equation = :[ tau = d * w_rel ] ) =# # Linear 1D rotational damper Damper = Model( flange_a = Flange, flange_b = Flange, phi_rel = Var(start=0.0u"rad"), d = 1.0u"N*m*s/rad", # (info = "Damping constant"), equation = :[ phi_rel = flange_b.phi - flange_a.phi w_rel = der(phi_rel) flange_b.tau = tau flange_a.tau = -tau tau = d * w_rel ] ) # Partial model to measure a single absolute flange variable PartialAbsoluteSensor = Model( flange = Flange, equation = :[flange.tau = 0] ) # Ideal sensor to measure the absolute flange angular velocity SpeedSensor = PartialAbsoluteSensor | Model(w = output, equations = :[w = der(flange.phi)]) UnitlessSpeedSensor = PartialAbsoluteSensor | Model(w = output, equations = :[w = der(flange.phi)*u"s/rad"]) #end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
20923
# License for this file: MIT (expat) # Copyright 2020-2021, DLR Institute of System Dynamics and Control using ModiaBase using Unitful using Measurements import MonteCarloMeasurements using DataStructures: OrderedDict, OrderedSet using DataFrames export SimulationModel, measurementToString, get_lastValue """ baseType(T) Return the base type of a type T. # Examples ``` baseType(Float32) # Float32 baseType(Measurement{Float64}) # Float64 ``` """ baseType(::Type{T}) where {T} = T baseType(::Type{Measurements.Measurement{T}}) where {T<:AbstractFloat} = T baseType(::Type{MonteCarloMeasurements.Particles{T,N}}) where {T<:AbstractFloat,N} = T baseType(::Type{MonteCarloMeasurements.StaticParticles{T,N}}) where {T<:AbstractFloat,N} = T """ str = measurementToString(v) Return variable `v::Measurements.Measurement{FloatType}` or a vector of such variables in form of a string will the full number of significant digits. """ measurementToString(v::Measurements.Measurement{FloatType}) where {FloatType} = string(Measurements.value(v)) * " Β± " * string(Measurements.uncertainty(v)) function measurementToString(v::Vector{Measurements.Measurement{FloatType}}) where {FloatType} str = string(typeof(v[1])) * "[" for (i,vi) in enumerate(v) if i > 1 str = str * ", " end str = str * measurementToString(vi) end str = str * "]" return str end """ simulationModel = SimulationModel{FloatType}( modelModule, modelName, getDerivatives!, equationInfo, x_startValues, parameters, variableNames; modelModule = nothing, vSolvedWithInitValuesAndUnit::OrderedDict{String,Any}(), vEliminated::Vector{Int}=Int[], vProperty::Vector{Int}=Int[], var_name::Function = v->nothing) # Arguments - `modelModule`: Module in which `@instantiateModel` is invoked (it is used for `Core.eval(modelModule, ...)`), that is evaluation of expressions in the environment of the user. - `modelName::String`: Name of the model - `getDerivatives::Function`: Function that is used to evaluate the model equations, typically generated with [`TinyModia.generate_getDerivatives!`]. - `equationInfo::ModiaBase.EquationInfo`: Information about the states and the equations. - `x_startValues`:: Deprecated (is no longer used). - `parameters`: A hierarchical NamedTuple of (key, value) pairs defining the parameter and init/start values. - variableNames: A vector of variable names. A name can be a Symbol or a String. """ mutable struct SimulationModel{FloatType} modelModule modelName::String getDerivatives!::Function equationInfo::ModiaBase.EquationInfo linearEquations::Vector{ModiaBase.LinearEquations{FloatType}} variables::OrderedDict{String,Int} # Dictionary of variables and their result indices (negated alias has negativ index) zeroVariables::OrderedSet{String} # Set of variables that are identically to zero vSolvedWithInitValuesAndUnit::OrderedDict{String,Any} # Dictionary of (names, init values with units) for all explicitly solved variables with init-values defined p::AbstractVector # Parameter and init/start values # (parameter values are used in getDerivatives!, # init/start values are extracted and stored in x_start) separateObjects::OrderedDict{Int,Any} # Dictionary of separate objects storeResult::Bool isInitial::Bool isTerminal::Bool time::FloatType nGetDerivatives::Int # Number of getDerivatives! calls x_start::Vector{FloatType} der_x::Vector{FloatType} result::Vector{Tuple} algorithmType::DataType # Type of integration algorithm (used in default-heading of plot) function SimulationModel{FloatType}(modelModule, modelName, getDerivatives!, equationInfo, x_startValues, parameters, variableNames; vSolvedWithInitValuesAndUnit::AbstractDict = OrderedDict{String,Any}(), vEliminated::Vector{Int} = Int[], vProperty::Vector{Int} = Int[], var_name::Function = v -> nothing) where {FloatType} # Construct result dictionaries variables = OrderedDict{String,Int}() zeroVariables = OrderedSet{String}() vSolvedWithInitValuesAndUnit2 = OrderedDict{String,Any}( [(string(key),vSolvedWithInitValuesAndUnit[key]) for key in keys(vSolvedWithInitValuesAndUnit)] ) # Store variables for (i, name) in enumerate(variableNames) variables[string(name)] = i end # Store eliminated variables for v in vEliminated name = var_name(v) if ModiaBase.isZero(vProperty, v) push!(zeroVariables, name) elseif ModiaBase.isAlias(vProperty, v) name2 = var_name( ModiaBase.alias(vProperty, v) ) variables[name] = variables[name2] else # negated alias name2 = var_name( ModiaBase.negAlias(vProperty, v) ) variables[name] = -variables[name2] end end # Construct parameter values that are copied into the code parameterValues = [eval(p) for p in values(parameters)] # Construct data structure for linear equations linearEquations = ModiaBase.LinearEquations{FloatType}[] for leq in equationInfo.linearEquations push!(linearEquations, ModiaBase.LinearEquations{FloatType}(leq...)) end # Construct dictionary for separate objects separateObjects = OrderedDict{Int,Any}() # Initialize execution flags isInitial = true isTerminal = false storeResult = false nGetDerivatives = 0 new(modelModule, modelName, getDerivatives!, equationInfo, linearEquations, variables, zeroVariables, vSolvedWithInitValuesAndUnit2, parameterValues, separateObjects, storeResult, isInitial, isTerminal, convert(FloatType, 0), nGetDerivatives, zeros(FloatType,0), zeros(FloatType,0), Tuple[]) end end """ floatType = getFloatType(simulationModel::SimulationModel) Return the floating point type with which `simulationModel` is parameterized (for example returns: `Float64, Float32, DoubleFloat, Measurements.Measurement{Float64}`). """ getFloatType(m::SimulationModel{FloatType}) where {FloatType} = FloatType """ hasParticles(value) Return true, if `value` is of type `MonteCarloMeasurements.StaticParticles` or `MonteCarloMeasurements.Particles`. """ hasParticles(value) = typeof(value) <: MonteCarloMeasurements.StaticParticles || typeof(value) <: MonteCarloMeasurements.Particles """ get_value(obj::NamedTuple, name::String) Return the value identified by `name` from the potentially hierarchically `NamedTuple obj`. If `name` is not in `obj`, the function returns `missing`. # Examples ```julia s1 = (a = 1, b = 2, c = 3) s2 = (v1 = s1, v2 = (d = 4, e = 5)) s3 = (v3 = s2, v4 = s1) @show get_value(s3, "v3.v1.b") # returns 2 @show get_value(s3, "v3.v2.e") # returns 5 @show get_value(s3, "v3.v1.e") # returns missing ``` """ function get_value(obj::NamedTuple, name::String) if length(name) == 0 || length(obj) == 0 return missing end j = findnext('.', name, 1) if isnothing(j) key = Symbol(name) return haskey(obj,key) ? obj[key] : missing elseif j == 1 return missing else key = Symbol(name[1:j-1]) if haskey(obj,key) && typeof(obj[key]) <: NamedTuple && length(name) > j get_value(obj[key], name[j+1:end]) else return missing end end end """ appendName(path::String, name::Symbol) Return `path` appended with `.` and `string(name)`. """ appendName(path, key) = path == "" ? string(key) : path * "." * string(key) """ get_names(obj::NamedTuple) Return `Vector{String}` containing all the names present in `obj` # Examples ```julia s1 = (a = 1, b = 2, c = 3) s2 = (v1 = s1, v2 = (d = 4, e = 5)) s3 = (v3 = s2, v4 = s1) @show get_names(s3) ``` """ function get_names(obj::NamedTuple) names = String[] get_names!(obj, names, "") return names end function get_names!(obj::NamedTuple, names::Vector{String}, path::String)::Nothing for (key,value) in zip(keys(obj), obj) name = appendName(path, key) if typeof(value) <: NamedTuple get_names!(value, names, name) else push!(names, name) end end return nothing end """ get_lastValue(model::SimulationModel, name::String; unit=true) Return the last stored value of variable `name` from `model`. If `unit=true` return the value with its unit, otherwise with stripped unit. If `name` is not known or no result values yet available, an info message is printed and the function returns `nothing`. """ function get_lastValue(m::SimulationModel, name::String; unit=true) if haskey(m.variables, name) if length(m.result) == 0 @info "get_lastValue(model,\"$name\"): No results yet available." return nothing end resIndex = m.variables[name] negAlias = false if resIndex < 0 resIndex = -resIndex negAlias = true end value = m.result[end][resIndex] if negAlias value = -value end elseif name in m.zeroVariables # Unit missing (needs to be fixed) value = 0.0 else value = get_value(m.p[1], name) if ismissing(value) @info "get_lastValue: $name is not known and is ignored." return nothing; end end return unit ? value : ustrip(value) end get_xe(x, xe_info) = xe_info.length == 1 ? x[xe_info.startIndex] : x[xe_info.startIndex:xe_info.startIndex + xe_info.length-1] function set_xe!(x, xe_info, value)::Nothing if xe_info.length == 1 x[xe_info.startIndex] = value else x[xe_info.startIndex:xe_info.startIndex + xe_info.length-1] = value end return nothing end """ success = init!(simulationModel, startTime, tolerance, merge, log, logParameters, logStates) Initialize `simulationModel::SimulationModel` at `startTime`. In particular: - Empty result data structure. - Merge parameter and init/start values into simulationModel. - Construct x_start. - Call simulationModel.getDerivatives! once with isInitial = true to compute and store all variables in the result data structure at `startTime` and initialize simulationModel.linearEquations. - Check whether explicitly solved variables that have init-values defined, have the required value after initialization (-> otherwise error). If initialization is successful return true, otherwise false. """ function init!(m::SimulationModel, startTime, tolerance, merge, log::Bool, logParameters::Bool, logStates::Bool)::Bool empty!(m.result) # Apply updates from merge Map and log parameters if isnothing(merge) if logParameters parameters = m.p[1] @showModel parameters end else m.p = [recursiveMerge(m.p[1], merge)] if logParameters updatedParameters = m.p[1] @showModel updatedParameters end end # Re-initialize dictionary of separate objects empty!(m.separateObjects) # Update startIndex, length in x_info and determine x_start FloatType = getFloatType(m) x_start = [] startIndex = 1 for xe_info in m.equationInfo.x_info xe_info.startIndex = startIndex # Determine init/start value in m.p[1] xe_value = get_value(m.p[1], xe_info.x_name) if ismissing(xe_value) error("Missing start/init value ", xe_info.x_name) end if hasParticles(xe_value) len = 1 push!(x_start, xe_value) else len = length(xe_value) push!(x_start, xe_value...) end if len != xe_info.length printstyled("Model error: ", bold=true, color=:red) printstyled("Length of ", xe_info.x_name, " shall be changed from ", xe_info.length, " to $len\n", "This is currently not support in TinyModia.", bold=true, color=:red) return false end startIndex += xe_info.length end nx = startIndex - 1 m.equationInfo.nx = nx # Temporarily remove units from x_start # (TODO: should first transform to the var_unit units and then remove) converted_x_start = convert(Vector{FloatType}, [ustrip(v) for v in x_start]) # ustrip.(x_start) does not work for MonteCarloMeasurements m.x_start = deepcopy(converted_x_start) if logStates # List init/start values x_table = DataFrames.DataFrame(state=String[], init=Any[], unit=String[], nominal=Float64[]) for xe_info in m.equationInfo.x_info xe_init = get_xe(m.x_start, xe_info) if hasParticles(xe_init) xe_init = string(minimum(xe_init)) * " .. " * string(maximum(xe_init)) end push!(x_table, (xe_info.x_name, xe_init, xe_info.unit, xe_info.nominal)) end show(stdout, x_table; allrows=true, allcols=true, rowlabel = Symbol("#"), summary=false, eltypes=false) println("\n") end m.der_x = zeros(FloatType, nx) # Initialize model, linearEquations and compute and store all variables at the initial time if log println(" Initialization at time = ", startTime, " s") end m.nGetDerivatives = 0 m.isInitial = true m.storeResult = true # m.getDerivatives!(m.der_x, m.x_start, m, startTime) Base.invokelatest(m.getDerivatives!, m.der_x, m.x_start, m, startTime) m.isInitial = false m.storeResult = false # Check vSolvedWithInitValuesAndUnit if length(m.vSolvedWithInitValuesAndUnit) > 0 names = String[] valuesBeforeInit = Any[] valuesAfterInit = Any[] for (name, valueBefore) in m.vSolvedWithInitValuesAndUnit valueAfterInit = get_lastValue(m, name, unit=false) valueBeforeInit = ustrip.(valueBefore) if !isnothing(valueAfterInit) && abs(valueBeforeInit - valueAfterInit) >= max(abs(valueBeforeInit),abs(valueAfterInit),0.01*tolerance)*tolerance push!(names, name) push!(valuesBeforeInit, valueBeforeInit) push!(valuesAfterInit , valueAfterInit) end end if length(names) > 0 v_table = DataFrames.DataFrame(name=names, beforeInit=valuesBeforeInit, afterInit=valuesAfterInit) #show(stderr, v_table; allrows=true, allcols=true, summary=false, eltypes=false) #print("\n\n") ioTemp = IOBuffer(); show(ioTemp, v_table; allrows=true, allcols=true, rowlabel = Symbol("#"), summary=false, eltypes=false) str = String(take!(ioTemp)) close(ioTemp) printstyled("Model error: ", bold=true, color=:red) printstyled("The following variables are explicitly solved for, have init-values defined\n", "and after initialization the init-values are not respected\n", "(remove the init-values in the model or change them to start-values):\n", str, bold=true, color=:red) return false end end return true end """ terminate!(m::SimulationModel, x, time) Terminate model. """ function terminate!(m::SimulationModel, x, t)::Nothing m.isTerminal = true Base.invokelatest(m.getDerivatives!, m.der_x, x, m, t) m.isTerminal = false return nothing end """ outputs!(x, t, integrator) DifferentialEquations FunctionCallingCallback function for `SimulationModel` that is used to store results at communication points. """ function outputs!(x, t, integrator)::Nothing m = integrator.p m.storeResult = true # m.getDerivatives!(m.der_x, x, m, t) Base.invokelatest(m.getDerivatives!, m.der_x, x, m, t) m.storeResult = false return nothing end """ derivatives!(derx, x, m, t) DifferentialEquations callback function to get the derivatives. """ function derivatives!(der_x, x, m, t)::Nothing # m.getDerivatives!(der_x, x, m, t) Base.invokelatest(m.getDerivatives!, der_x, x, m, t) return nothing end """ addToResult!(simulationModel, variableValues...) Add `variableValues...` to `simulationModel::SimulationModel`. It is assumed that the first variable in `variableValues` is `time`. """ function addToResult!(m::SimulationModel, variableValues...)::Nothing push!(m.result, variableValues) return nothing end """ code = generate_getDerivatives!(AST, equationInfo, parameters, variables, functionName; hasUnits=false) Return the code of the `getDerivatives!` function as `Expr` using the Symbol `functionName` as function name. By `eval(code)` or `fc = @RuntimeGeneratedFunction(code)` the function is compiled and can afterwards be called. # Arguments - `AST::Vector{Expr}`: Abstract Syntax Tree of the equations as vector of `Expr`. - `equationInfo::ModiaBase.EquationInfo`: Data structure returned by `ModiaBase.getSortedAndSolvedAST holding information about the states. - `parameters`: Vector of parameter names (as vector of symbols) - `variables`: Vector of variable names (as vector of symbols). The first entry is expected to be time, so `variables[1] = :time`. - `functionName::Function`: The name of the function that shall be generated. # Optional Arguments - `hasUnits::Bool`: = true, if variables have units. Note, the units of the state vector are defined in equationinfo. """ function generate_getDerivatives!(AST::Vector{Expr}, equationInfo::ModiaBase.EquationInfo, parameters, variables, functionName::Symbol; hasUnits=false) # Generate code to copy x to struct and struct to der_x x_info = equationInfo.x_info code_x = Expr[] code_der_x = Expr[] code_p = Expr[] if length(x_info) == 1 && x_info[1].x_name == "" && x_info[1].der_x_name == "" # Explicitly solved pure algebraic variables. Introduce dummy equation push!(code_der_x, :( _der_x[1] = -_x[1] )) else i1 = 0 i2 = 0 for (i, xe) in enumerate(x_info) i1 = i2 + 1 i2 = i1 + xe.length - 1 indexRange = i1 == i2 ? :($i1) : :( $i1:$i2 ) x_name = xe.x_name_julia der_x_name = xe.der_x_name_julia # x_name = Meta.parse("m."*xe.x_name) # der_x_name = Meta.parse("m."*replace(xe.der_x_name, r"der\(.*\)" => s"var\"\g<0>\"")) if !hasUnits || xe.unit == "" push!(code_x, :( $x_name = _x[$indexRange] ) ) else x_unit = xe.unit push!(code_x, :( $x_name = _x[$indexRange]*@u_str($x_unit)) ) end if hasUnits push!(code_der_x, :( _der_x[$indexRange] = ustrip( $der_x_name )) ) else push!(code_der_x, :( _der_x[$indexRange] = $der_x_name )) end end end for (i,pi) in enumerate(parameters) push!(code_p, :( $pi = _m.p[$i] ) ) end timeName = variables[1] if hasUnits code_time = :( $timeName = _time*u"s" ) else code_time = :( $timeName = _time ) end # Generate code of the function code = quote function $functionName(_der_x, _x, _m, _time)::Nothing _m.time = _time _m.nGetDerivatives += 1 simulationModel = _m $code_time $(code_p...) $(code_x...) $(AST...) $(code_der_x...) if _m.storeResult TinyModia.addToResult!(_m, $(variables...)) end return nothing end end return code end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
8812
""" Module to produce incidence plots * Developer: Hilding Elmqvist, Mogram AB * First version: December 2020 * License: MIT (expat) """ module IncidencePlot using GLMakie using AbstractPlotting using GeometryBasics using Colors # include("...ModiaBase/src/Tearing.jl") # using .Tearing export showIncidence removeBlock(ex) = ex function removeBlock(ex::Expr) if ex.head in [:block] ex.args[1] else Expr(ex.head, [removeBlock(arg) for arg in ex.args]...) end end AbstractPlotting.inline!(false) """ showIncidence(equations, unknowns, G, vActive, substitutions, assigned, assignedVar, blocks; sortVariables=false) Shows the incidence matrix using the plotting package Makie. If `assigned` is not [], the assigned variable is marked. `blocks` is a vector of vectors enabling showing of BLT-blocks. After each incidence matrix is output, the user is promted for a RETURN, not to immediately overwriting the plot. """ function showIncidence(equations, unknowns, G, vActive, substitutions, assigned, assignedVar, blocks; sortVariables=false) scene = Scene(camera = campixel!, show_axis = false, resolution = (1000, 800)) margin = 20 size = 600 nVar = length(unknowns) if sortVariables sortedVariables = fill(0, nVar) varCount = 0 for b in blocks for e in b varCount += 1 sortedVariables[varCount] = assignedVar[e] end end for i in 1:length(vActive) if ! vActive[i] varCount += 1 sortedVariables[varCount] = i end end else sortedVariables = 1:nVar end n=length(equations) m=length(unknowns) width = min(div(size, n), 20) height = min(div(size, m), 20) function drawText(s, row, column; align=:left, vertical=false) rot = if ! vertical; 0.0 else pi/2 end text!(scene, s, position = Vec(margin + column*width + width/2, margin + (n+1-row)*height + height/2), color = :green, textsize = 15, align = (align, :center), rotation = rot, show_axis = false) end # ----------------------------------------------------------------------------- # Draw matrix grid for i in 1:n+1 poly!([Point2f0(margin + width, margin + i*height), Point2f0(margin + (m+1)*width, margin + i*height)], strokecolor = :black) end for j in 1:m+1 poly!([Point2f0(margin + j*width, margin + height), Point2f0(margin + j*width, margin + (n+1)*height)], strokecolor = :black) end for j in 1:length(unknowns) # Draw variable number under matrix drawText(string(sortedVariables[j]), n+1, j, align=:right, vertical=true) # Draw variable names above matrix v = unknowns[sortedVariables[j]] var = string(v) if v in keys(substitutions) subs = replace(replace(replace(string(substitutions[v]), "(" => ""), ")" => ""), "--" => "") var *= " = " * subs end drawText(var, 0, j, vertical=true) end row = 0 for b in blocks for e in b row += 1 # Draw equation number to the left drawText(string(e), row, 0, align=:right) # Draw equation to the right equ = equations[e] Base.remove_linenums!(equ) equ = removeBlock(equ) equ = string(equ) equ = replace(equ, "\n" => ";") if equ != :(0 = 0) drawText(equ, row, m+1) end end end row = 0 for b in blocks if length(b) > 1 #= println("\nTearing of BLT block") @show b es::Array{Int64,1} = b vs = assignedVar[b] td = EquationTearing(G, length(unknowns)) (eSolved, vSolved, eResidue, vTear) = tearEquations!(td, (e,v) -> v in G[e], es, vs) @show eSolved vSolved eResidue vTear @show equations[eSolved] unknowns[vSolved] equations[eResidue] unknowns[vTear] b = vcat(eSolved, eResidue) @show b blocksVars = vcat(vSolved, vTear) =# color = :lightgrey poly!(Rect(Vec(margin + (row+1)*width, margin + (n+1-row)*height-length(b)*height), Vec(length(b)*width, length(b)*height)), color = color, strokecolor = :black, transperancy=true) end for e in b row += 1 incidence = fill(false, nVar) for v in G[e] if sortedVariables[v] > 0 incidence[sortedVariables[v]] = true end end col = 0 for v in sortedVariables col += 1 ins = if v == 0 || ! vActive[v]; 0 elseif sortedVariables[v] > 0 && ! incidence[sortedVariables[v]]; 0 elseif v > 0 && v<= length(assigned) && assigned[v] == e; 1 else 2 end if ins > 0 color = if ins == 1; :red else :blue end poly!(Rect(Vec(margin + col*width, margin + (n+1-row)*height), Vec(width, height)), color = color, strokecolor = :black) end end end end display(scene) println("Continue?") readline() end function testShowIncidence() # RCRL circuit equations = Expr[:(ground.p.v = V.n.v), :(V.p.v = Ri.n.v), :(Ri.p.v = R.p.v), :(R.n.v = C.p.v), :(C.n.v = ground.p.v), :(ground.p.i + V.n.i + C.n.i = 0), :(V.p.i + Ri.n.i = 0), :(Ri.p.i + R.p.i = 0), :(R.n.i + C.p.i = 0), :(Ri.v = Ri.p.v - Ri.n.v), :(0 = Ri.p.i + Ri.n.i), :(Ri.i = Ri.p.i), :(Ri.R * Ri.i = Ri.v), :(R.v = R.p.v - R.n.v), :(0 = R.p.i + R.n.i), :(R.i = R.p.i), :(R.R * R.i = R.v), :(C.v = C.p.v - C.n.v), :(0 = C.p.i + C.n.i), :(C.i = C.p.i), :(C.C * der(C.v) = C.i), :(V.v = V.p.v - V.n.v), :(0 = V.p.i + V.n.i), :(V.i = V.p.i), :(V.v = 10), :(ground.p.v = 0)] unknowns = Any[:(Ri.v), :(Ri.i), :(Ri.p.i), :(Ri.p.v), :(Ri.n.i), :(Ri.n.v), :(R.v), :(R.i), :(R.p.i), :(R.p.v), :(R.n.i), :(R.n.v), :(C.v), :(der(C.v)), :(C.i), :(C.p.i), :(C.p.v), :(C.n.i), :(C.n.v), :(V.v), :(V.i), :(V.p.i), :(V.p.v), :(V.n.i), :(V.n.v), :(ground.p.i), :(ground.p.v)] G = [[27, 25], [23, 6], [4, 10], [12, 17], [19, 27], [26, 24, 18], [22, 5], [3, 9], [11, 16], [1, 4, 6], [3, 5], [2, 3], [2, 1], [7, 10, 12], [9, 11], [8, 9], [8, 7], [13, 17, 19], [16, 18], [15, 16], [14, 15], [20, 23, 25], [22, 24], [21, 22], [20], [27]] vActive = Bool[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] substitutions = Dict{Any,Any}() assigned = Any[] assignedVar = Any[] blocks = [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26]] sortVariables = false showIncidence(equations, unknowns, G, vActive, substitutions, assigned, assignedVar, blocks, sortVariables=sortVariables) # RCRL equations = Expr[:(ground.p.v = V.n.v), :(V.p.v = Ri.n.v), :(Ri.p.v = R.p.v), :(R.n.v = C.p.v), :(C.n.v = ground.p.v), :(ground.p.i + V.n.i + C.n.i = 0), :(V.p.i + Ri.n.i = 0), :(Ri.p.i + R.p.i = 0), :(R.n.i + C.p.i = 0), :(Ri.v = Ri.p.v - Ri.n.v), :(0 = Ri.p.i + Ri.n.i), :(Ri.i = Ri.p.i), :(Ri.R * Ri.i = Ri.v), :(R.v = R.p.v - R.n.v), :(0 = R.p.i + R.n.i), :(R.i = R.p.i), :(R.R * R.i = R.v), :(C.v = C.p.v - C.n.v), :(0 = C.p.i + C.n.i), :(C.i = C.p.i), :(C.C * der(C.v) = C.i), :(V.v = V.p.v - V.n.v), :(0 = V.p.i + V.n.i), :(V.i = V.p.i), :(V.v = 10), :(ground.p.v = 0)] unknowns = Any[:(Ri.v), :(Ri.i), :(Ri.p.i), :(Ri.p.v), :(Ri.n.i), :(Ri.n.v), :(R.v), :(R.i), :(R.p.i), :(R.p.v), :(R.n.i), :(R.n.v), :(C.v), :(der(C.v)), :(C.i), :(C.p.i), :(C.p.v), :(C.n.i), :(C.n.v), :(V.v), :(V.i), :(V.p.i), :(V.p.v), :(V.n.i), :(V.n.v), :(ground.p.i), :(ground.p.v)] G = [[27, 25], [23, 6], [4, 10], [12, 17], [19, 27], [26, 24, 18], [22, 5], [3, 9], [11, 16], [1, 4, 6], [3, 5], [2, 3], [2, 1], [7, 10, 12], [9, 11], [8, 9], [8, 7], [13, 17, 19], [16, 18], [15, 16], [14, 15], [20, 23, 25], [22, 24], [21, 22], [20], [27]] vActive = Bool[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] substitutions = Dict{Any,Any}() assigned = [10, 13, 12, 3, 11, 2, 17, 16, 8, 14, 15, 4, 0, 21, 20, 9, 18, 19, 5, 25, 24, 7, 22, 23, 1, 6, 26] assignedVar = [25, 6, 4, 12, 19, 26, 22, 9, 16, 1, 5, 3, 2, 10, 11, 8, 7, 17, 18, 15, 14, 23, 24, 21, 20, 27, 0] blocks = [[26], [1], [25], [22], [2], [5], [18], [4], [10, 13, 12, 8, 16, 17, 14, 3], [11], [7], [23], [15], [9], [19], [6], [20], [21], [24]] sortVariables = true showIncidence(equations, unknowns, G, vActive, substitutions, assigned, assignedVar, blocks, sortVariables=sortVariables) end # testShowIncidence() end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
15685
#= Handles models defined as named tuples. * Developer: Hilding Elmqvist, Mogram AB * First version: January 2021 * License: MIT (expat) =# export mergeModels, recursiveMerge, Redeclare, showModel, @showModel, Model, Map, Par, Var, setLogMerge, constant, parameter, input, output, potential, flow, interval, @info_str using Base.Meta: isexpr using DataStructures: OrderedDict using Unitful using ModiaBase.Symbolic: removeBlock, prepend function stringifyDefinition(v) if typeof(v) in [Symbol, Expr] v = removeBlock(v) v = ":(" * string(v) * ")" end return v end function showModel(m, level=0) level += 1 # print(" "^(level-1)) if typeof(m) <: NamedTuple && haskey(m, :class) print(m.class) end println("(") for (k, v) in zip(keys(m), m) if typeof(v) <: NamedTuple print(" "^level, k, " = ") showModel(v, level) elseif k != :class println(" "^level, k, " = ", stringifyDefinition(v), ",") end end println(" "^(level-1), "),") end macro showModel(model) modelName = string(model) mod = :( print($modelName, " = "); showModel($model); println() ) return esc(mod) end global logMerge = false function setLogMerge(val) global logMerge logMerge = val end function mergeModels(m1::NamedTuple, m2::NamedTuple, env=Symbol()) mergedModels = OrderedDict{Symbol,Any}(pairs(m1)) for (k,v) in collect(pairs(m2)) if typeof(v) <: NamedTuple if k in keys(mergedModels) && ! (:_redeclare in keys(v)) if logMerge; print("In $k: ") end m = mergeModels(mergedModels[k], v, k) mergedModels[k] = m elseif :_redeclare in keys(v) if logMerge; println("Redeclaring: $k = $v") end mergedModels[k] = v elseif nothing in values(v) # TODO: Refine else if !(:_redeclare in keys(mergedModels)) if logMerge; print("Adding: $k = "); showModel(v, 2) end end mergedModels[k] = v end elseif v === nothing if logMerge; println("Deleting: $k") end delete!(mergedModels, k) else if logMerge if k in keys(mergedModels) if mergedModels[k] != v println("Changing: $k = $(stringifyDefinition(mergedModels[k])) to $k = $(stringifyDefinition(v))") end elseif !(:_redeclare in keys(mergedModels)) println("Adding: $k = $(stringifyDefinition(v))") end end mergedModels[k] = v end end # delete!(mergedModels, :class) return (; mergedModels...) # Transform OrderedDict to named tuple end Model(; kwargs...) = (; class = :Model, kwargs...) Map(; kwargs...) = (; class = :Map, kwargs...) Par(; kwargs...) = Map(; class = :Par, kwargs...) Var(;kwargs...) = (; class = :Var, kwargs...) Var(value; kwargs...) = (; class = :Var, value=value, kwargs...) Redeclare = ( _redeclare = true, ) constant = Var(constant = true) parameter = Var(parameter = true) input = Var(input = true) output = Var(output = true) potential = Var(potential = true) flow = Var(flow = true) interval(min, max) = Var(min=min, max=max) macro info_str(text) Var(info=text) end Base.:|(m::NamedTuple, n::NamedTuple) = mergeModels(m, n) # TODO: Chane to updated recursiveMerge Base.:|(m, n) = if !(typeof(n) <: NamedTuple); recursiveMerge(m, (; value=n)) else recursiveMerge(n, (value=m,)) end recursiveMerge(x, ::Nothing) = x recursiveMerge(x, y) = y #recursiveMerge(x::Expr, y::Expr) = begin dump(x); dump(y); Expr(x.head, x.args..., y.args...) end recursiveMerge(x::Expr, y::Tuple) = begin x = copy(x); xargs = x.args; xargs[y[2]] = y[3]; Expr(x.head, xargs...) end function recursiveMerge(nt1::NamedTuple, nt2::NamedTuple) all_keys = union(keys(nt1), keys(nt2)) # all_keys = setdiff(all_keys, [:class]) gen = Base.Generator(all_keys) do key v1 = get(nt1, key, nothing) v2 = get(nt2, key, nothing) key => recursiveMerge(v1, v2) end return (; gen...) end function unpackPath(path, sequence) if typeof(path) == Symbol push!(sequence, path) elseif isexpr(path, :.) unpackPath(path.args[1], sequence) push!(sequence, path.args[2].value) elseif isexpr(path, :ref) unpackPath(path.args[1], sequence) push!(sequence, path.args[2:end]...) end end function collectConnector(model) potentials = [] flows = [] for (k,v) in zip(keys(model), model) if typeof(v) <: NamedTuple && :class in keys(v) && v.class == :Var || typeof(v) <: NamedTuple && :variable in keys(v) && v.variable if :potential in keys(v) && v.potential push!(potentials, k) end if :flow in keys(v) && v.flow push!(flows, k) end end end return potentials, flows end function convertConnections!(connections, model, modelName, logging=false) # println("\nconvertConnections") # showModel(model) # @show connections # println() connectEquations = [] alreadyConnected = [] for i in 1:length(connections) c = connections[i] if c.head == :tuple connected = c.args potential1 = nothing inflow = 0 outflow = 0 signalFlow1 = nothing connectedOutput = nothing potentials1 = [] flows1 = [] for con in connected if con in alreadyConnected error("Already connected: $con, found in connection: $connected") end push!(alreadyConnected, con) sequence = [] unpackPath(con, sequence) mod = model for s in sequence[1:end-1] if s in keys(mod) mod = mod[s] else error("Invalid path $con: $s not found in $(keys(mod))") end end if sequence[end] in keys(mod) mod = mod[sequence[end]] if :input in keys(mod) && mod.input || :output in keys(mod) && mod.output signalFlow = con if signalFlow1 !== nothing push!(connectEquations, :($signalFlow1 = $signalFlow)) end signalFlow1 = signalFlow if :output in keys(mod) && mod.output if connectedOutput != nothing # TODO: refine logic concerning inner and outer inputs and outputs # error("It is not allowed to connect two outputs: ", connectedOutput, ", ", con) end connectedOutput = con end else potentials, flows = collectConnector(mod) # Deprecated if :potentials in keys(mod) potentials = vcat(potentials, mod.potentials.args) end if :flows in keys(mod) flows = vcat(flows, mod.flows.args) end if length(potentials1) > 0 && potentials != potentials1 error("Not compatible potential variables: $potentials1 != $potentials, found in connection: $connected") end for p in potentials potential = append(con, p) if potential1 != nothing push!(connectEquations, :($potential1 = $potential)) end potential1 = potential end potentials1 = potentials if length(flows1) > 0 && flows != flows1 error("Not compatible flow variables: $flows1 != $flows, found in connection: $connected") end for f in flows flowVar = append(con, f) if length(sequence) == 1 if inflow == 0 inflow = flowVar else inflow = :($inflow + $flowVar) end else if outflow == 0 outflow = flowVar else outflow = :($outflow + $flowVar) end end end flows1 = flows end else # Deprecated signalFlow = con if signalFlow1 !== nothing push!(connectEquations, :($signalFlow1 = $signalFlow)) end signalFlow1 = signalFlow end end if inflow != 0 || outflow != 0 push!(connectEquations, :($inflow = $outflow)) end end end if length(connectEquations) > 0 && logging println("Connect equations in $modelName:") for e in connectEquations println(" ", e) end end return connectEquations end function flattenModelTuple!(model, modelStructure, modelName; unitless = false, log=false) connections = [] extendedModel = merge(model, NamedTuple()) for (k,v) in zip(keys(model), model) # @show k v typeof(v) # Deprecated if k in [:inputs, :outputs, :potentials, :flows, :class] if k in [:inputs, :outputs, :potentials, :flows] printstyled(" Deprecated construct in model $modelName: ", color=:yellow) println("$k = $v\n Use: ... = $(string(k)[1:end-1]) ...") end elseif k == :init printstyled(" Deprecated construct in model $modelName: ", color=:yellow) println("$k = $v\n Use: ... = Var(init=...) ...") for (x,x0) in zip(keys(v), v) if x != :class if unitless && typeof(x0) != Expr x0 = ustrip(x0) end modelStructure.init[x] = x0 modelStructure.mappedParameters = (;modelStructure.mappedParameters..., x => x0) end end elseif k == :start printstyled(" Deprecated construct in model $modelName: ", color=:yellow) println("$k = $v\n Use: ... = Var(start=...) ...") for (s,s0) in zip(keys(v), v) if s != :class if unitless s0 = ustrip(s0) end modelStructure.start[s] = s0 modelStructure.mappedParameters = (;modelStructure.mappedParameters..., s => s0) end end elseif typeof(v) in [Int64, Float64] || typeof(v) <: Unitful.Quantity || typeof(v) in [Array{Int64,1}, Array{Int64,2}, Array{Float64,1}, Array{Float64,2}] || typeof(v) <: NamedTuple && :class in keys(v) && v.class == :Par || typeof(v) <: NamedTuple && :parameter in keys(v) && v.parameter if unitless && !(typeof(v) <: NamedTuple) v = ustrip(v) end modelStructure.parameters[k] = v modelStructure.mappedParameters = (;modelStructure.mappedParameters..., k => v) elseif (typeof(v) <: NamedTuple && :class in keys(v) && v.class in [:Par, :Var] || typeof(v) <: NamedTuple && :parameter in keys(v) && v.parameter) && :value in keys(v) v = v.value if typeof(v) in [Expr, Symbol] push!(modelStructure.equations, removeBlock(:($k = $v))) else modelStructure.parameters[k] = v modelStructure.mappedParameters = (;modelStructure.mappedParameters..., k => v) end elseif typeof(v) <: NamedTuple && :class in keys(v) && v.class in [:Var] || typeof(v) <: NamedTuple && :variable in keys(v) && v.variable if :init in keys(v) x0 = v.init if unitless && typeof(x0) != Expr x0 = ustrip(x0) end modelStructure.init[k] = x0 modelStructure.mappedParameters = (;modelStructure.mappedParameters..., k => x0) end if :start in keys(v) s0 = v.start if unitless && typeof(s0) != Expr s0 = ustrip(s0) end modelStructure.start[k] = s0 modelStructure.mappedParameters = (;modelStructure.mappedParameters..., k => s0) end elseif typeof(v) <: NamedTuple # instantiate subModelStructure = ModelStructure() flattenModelTuple!(v, subModelStructure, k; unitless, log) # println("subModelStructure") # printModelStructure(subModelStructure, k) mergeModelStructures(modelStructure, subModelStructure, k) elseif typeof(v) <:Array && length(v) > 0 && typeof(v[1]) <: NamedTuple # array of instances i = 0 for a in v i += 1 subModelStructure = ModelStructure() flattenModelTuple!(a, subModelStructure, k; unitless, log) mergeModelStructures(modelStructure, subModelStructure, Symbol(string(k)*"_"*string(i)) ) end elseif isexpr(v, :vect) || isexpr(v, :vcat) || isexpr(v, :hcat) arrayEquation = false for e in v.args if isexpr(e, :(=)) if unitless e = removeUnits(e) end push!(modelStructure.equations, removeBlock(e)) elseif isexpr(e, :tuple) push!(connections, e) else arrayEquation = true end end if arrayEquation push!(modelStructure.equations, removeBlock(:($k = $(prepend(v, :up))))) # push!(modelStructure.equations, removeBlock(:($k = $v))) end elseif isexpr(v, :(=)) # Single equation if unitless v = removeUnits(v) end push!(modelStructure.equations, removeBlock(v)) elseif v !== nothing # Binding expression # println("Binding expression") # @show k v typeof(v) if unitless v = removeUnits(v) end push!(modelStructure.equations, :($k = $(prepend(v, :up)))) # push!(modelStructure.equations, :($k = $v)) # @show modelStructure.equations end end # printModelStructure(modelStructure, "flattened") connectEquations = convertConnections!(connections, extendedModel, modelName, log) push!(modelStructure.equations, connectEquations...) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
15539
export simulate!, get_result using ModiaPlot using Measurements import MonteCarloMeasurements using Unitful using Test import DifferentialEquations #--------------------------------------------------------------------- # Simulation #--------------------------------------------------------------------- """ convertTimeVariable(t) The function returns variable `t` in a normalized form: 1. If `t` has a unit, it is transformed to u"s" and the unit is stripped off. 2. `t` is converted to `Float64`. """ convertTimeVariable(t) = typeof(t) <: Unitful.AbstractQuantity ? convert(Float64, ustrip(uconvert(u"s", t))) : convert(Float64, t) """ simulate!(model [, algorithm]; merge = nothing, tolerance = 1e-6, startTime = 0.0, stopTime = 1.0, interval = NaN, adaptive = true, log = true, logParameters = true, logStates = true, requiredFinalStates = nothing) Simulate `model::SimulationModel` with `algorithm` (= `alg` of [ODE Solvers of DifferentialEquations.jl](https://diffeq.sciml.ai/stable/solvers/ode_solve/)). If the `algorithm` argument is missing, a default algorithm will be chosen from DifferentialEquations (for details see [https://arxiv.org/pdf/1807.06430](https://arxiv.org/pdf/1807.06430), Figure 3). The simulation results stored in `model` can be plotted with ModiaPlot.plot and the result values can be retrieved with [`get_result`](@ref). # Optional Arguments - `merge`: Define parameters and init/start values that shall be merged with the previous values stored in `model`, before simulation is started. - `tolerance`: Relative tolerance. - `startTime`: Start time. If value is without unit, it is assumed to have unit [s]. - `stopTime`: Stop time. If value is without unit, it is assumed to have unit [s]. - `interval`: Interval to store result. If `interval=NaN`, it is internally selected as (stopTime-startTime)/500. If value is without unit, it is assumed to have unit [s]. - `adaptive`: = true, if the `algorithm` should use step-size control (if available). = false, if the `algorithm` should use a fixed step-size of `interval` (if available). - `log`: = true, to log the simulation. - `logParameters`: = true, to log the parameter and init/start values - `logStates` : = true, to log the states, its init/start values and its units. - `requiredFinalStates`: is not `nothing`: Check whether the ODE state vector at the final time instant with `@test` is in agreement to vector `requiredFinalStates` with respect to some tolerance. If this is not the case, print the final state vector (so that it can be included with copy-and-paste in the simulate!(..) call). # Examples ```julia using ModiaPlot using DifferentialEquations # Define model inputSignal(t) = sin(t) FirstOrder = Model( T = 0.2, x = Var(init=0.3), equations = :[u = inputSignal(time/u"s"), T * der(x) + x = u, y = 2*x] ) # Modify parameters and initial values of model FirstOrder2 = FirstOrder | Map(T = 0.4, x = Var(init=0.6)) # Instantiate model firstOrder = @instantiateModel(FirstOrder2, logCode=true) # Simulate with automatically selected algorithm and # modified parameter and initial values simulate!(firstOrder, stopTime = 1.0, merge = Map(T = 0.6, x = 0.9), logParameters=true) # Plot variables "x", "u" in diagram 1, "der(x)" in diagram 2, both diagrams in figure 3 plot(firstOrder, [("x","u"), "der(x)"], figure=3) # Retrieve "time" and "u" values: get_result(firstOrder, "time") get_result(firstOrder, "u") # Simulate with Runge-Kutta 5/4 with step-size control simulate!(firstOrder, Tsit5(), stopTime = 1.0) # Simulate with Runge-Kutta 4 with fixed step size simulate!(firstOrder, RK4(), stopTime = 1.0, adaptive=false) # Simulate with algorithm that switches between # Verners Runge-Kutta 6/5 algorithm if non-stiff region and # Rosenbrock 4 (= A-stable method) if stiff region with step-size control simulate!(firstOrder, AutoVern6(Rodas4()), stopTime = 1.0) # Simulate with Sundials CVODE (BDF method with variable order 1-5) with step-size control using Sundials simulate!(firstOrder, CVODE_BDF(), stopTime = 1.0) ``` """ function simulate!(m::Nothing, args...; kwargs...) @info "The call of simulate!(..) is ignored, since the first argument is nothing." return nothing end function simulate!(m::SimulationModel, algorithm=missing; tolerance = 1e-6, startTime = 0.0, stopTime = 1.0, interval = NaN, adaptive::Bool = true, log::Bool = false, logParameters::Bool = false, logStates::Bool = false, requiredFinalStates = nothing, merge=nothing) initialized = false #try m.algorithmType = typeof(algorithm) tolerance = convert(Float64, tolerance) startTime = convertTimeVariable(startTime) stopTime = convertTimeVariable(stopTime) interval = convertTimeVariable(interval) interval = isnan(interval) ? (stopTime - startTime)/500.0 : interval # Target type FloatType = getFloatType(m) # Initialize/re-initialize SimulationModel if log || logParameters || logStates println("... Simulate model ", m.modelName) end cpuStart::UInt64 = time_ns() cpuLast::UInt64 = cpuStart cpuStartIntegration::UInt64 = cpuStart success = init!(m, startTime, tolerance, merge, log, logParameters, logStates) if !success return nothing end initialized = true # Define problem and callbacks based on algorithm and model type tspan = (startTime, stopTime) tspan2 = startTime:interval:stopTime tdir = startTime <= stopTime ? 1 : -1 abstol = 0.1*tolerance problem = DifferentialEquations.ODEProblem(derivatives!, m.x_start, tspan, m) callback = DifferentialEquations.FunctionCallingCallback(outputs!, funcat=tspan2, tdir=tdir) # Initial step size (the default of DifferentialEquations is too large) + step-size of fixed-step algorithm dt = adaptive ? interval/10 : interval # initial step-size # Compute solution solution = ismissing(algorithm) ? DifferentialEquations.solve(problem, reltol=tolerance, abstol=abstol, save_everystep=false, save_start=false, save_end=true, callback=callback, adaptive=adaptive, dt=dt) : DifferentialEquations.solve(problem, algorithm, reltol=tolerance, abstol=abstol, save_everystep=false, save_start=false, save_end=true, callback=callback, adaptive=adaptive, dt=dt) if ismissing(algorithm) m.algorithmType = typeof(solution.alg) end # Terminate simulation finalStates = solution[:,end] terminate!(m, finalStates, solution.t[end]) if log cpuTimeInitialization = convert(Float64, (cpuStartIntegration - cpuStart) * 1e-9) cpuTimeIntegration = convert(Float64, (time_ns() - cpuStartIntegration) * 1e-9) cpuTime = cpuTimeInitialization + cpuTimeIntegration println(" Termination at time = ", solution.t[end], " s") println(" cpuTime = ", round(cpuTime, sigdigits=3), " s") #println(" cpuTime = ", round(cpuTime , sigdigits=3), " s (init: ", # round(cpuTimeInitialization, sigdigits=3), " s, integration: ", # round(cpuTimeIntegration , sigdigits=3), " s)") println(" algorithm = ", typeof(solution.alg)) println(" FloatType = ", FloatType) println(" interval = ", interval, " s") println(" tolerance = ", tolerance, " (relative tolerance)") println(" nEquations = ", length(m.x_start)) println(" nResults = ", length(m.result)) println(" nAcceptedSteps = ", solution.destats.naccept) println(" nRejectedSteps = ", solution.destats.nreject) println(" nGetDerivatives = ", m.nGetDerivatives, " (number of getDerivatives! calls)") println(" nf = ", solution.destats.nf, " (number of getDerivatives! calls from integrator)") println(" nJac = ", solution.destats.njacs, " (number of Jacobian computations)") println(" nErrTestFails = ", solution.destats.nreject) end if !isnothing(requiredFinalStates) if length(finalStates) != length(requiredFinalStates) success = false else success = finalStates == requiredFinalStates || isapprox(finalStates, requiredFinalStates, rtol=1e-3) end if success @test success else if length(requiredFinalStates) > 0 && typeof(requiredFinalStates[1]) <: Measurements.Measurement println( "\nrequiredFinalStates = ", measurementToString(requiredFinalStates)) printstyled("finalStates = ", measurementToString(finalStates), "\n\n", bold=true, color=:red) else println( "\nrequiredFinalStates = ", requiredFinalStates) printstyled("finalStates = ", finalStates, "\n\n", bold=true, color=:red) end @test finalStates == requiredFinalStates #|| isapprox(finalStates, requiredFinalStates, rtol=1e-3) end end return solution #= catch e if initialized terminate!(m, m.x_start, m.time) end if isa(e, ErrorException) printstyled("\nError from simulate!:\n", color=:red) printstyled(e.msg, "\n\n", color=:red) printstyled("Aborting simulate!\n\n", color=:red) empty!(m.result) else Base.rethrow() end end return nothing =# end #--------------------------------------------------------------------- # Provide ModiaPlot result access functions for SimulationModel #--------------------------------------------------------------------- """ ModiaPlot.hasSignal(model::SimulationModel, name::String) Return true if parameter or time-varying variable `name` (for example `a.b.c`) is defined in the TinyModia SimulationModel (generated with [`TinyModia.@instantiateModel`](@ref) that can be accessed and can be used for plotting. """ ModiaPlot.hasSignal(m::SimulationModel, name) = haskey(m.variables, name) || name in m.zeroVariables || !ismissing(get_value(m.p[1], name)) """ ModiaPlot.getNames(model::SimulationModel) Return the variable names (parameters, time-varying variables) of a TinyModia SimulationModel (generated with [`TinyModia.@instantiateModel`](@ref) that can be accessed and can be used for plotting. """ function ModiaPlot.getNames(m::SimulationModel) names = get_names(m.p[1]) append!(names, collect(m.zeroVariables)) append!(names, collect( keys(m.variables) ) ) return sort(names) end function ModiaPlot.getRawSignal(m::SimulationModel, name) if haskey(m.variables, name) resIndex = m.variables[name] negAlias = false if resIndex < 0 resIndex = -resIndex negAlias = true end value = m.result[1][resIndex] signal = Vector{typeof(value)}(undef, length(m.result)) for (i, value_i) in enumerate(m.result) signal[i] = value_i[resIndex] end if negAlias signal = -signal end return (false, signal) elseif name in m.zeroVariables return (true, 0.0) else value = get_value(m.p[1], name) if ismissing(value) error("ModiaPlot.getRawSignal: ", name, " not in result of model ", m.modelName) end return (true, value) end end """ leaveName = get_leaveName(pathName::String) Return the `leaveName` of `pathName`. """ get_leaveName(pathName::String) = begin j = findlast('.', pathName); typeof(j) == Nothing || j >= length(pathName) ? pathName : pathName[j+1:end] end function ModiaPlot.getDefaultHeading(m::SimulationModel) FloatType = get_leaveName( string( typeof( m.x_start[1] ) ) ) algorithmName = string(m.algorithmType) i1 = findfirst("CompositeAlgorithm", algorithmName) if !isnothing(i1) i2 = findfirst("Vern" , algorithmName) i3 = findfirst("Rodas", algorithmName) success = false if !isnothing(i2) && !isnothing(i3) i2b = findnext(',', algorithmName, i2[1]) i3b = findnext('{', algorithmName, i3[1]) if !isnothing(i2b) && !isnothing(i3b) algorithmName = algorithmName[i2[1]:i2b[1]-1] * "(" * algorithmName[i3[1]:i3b[1]-1] * "())" success = true end end if !success algorithmName = "CompositeAlgorithm" end else i1 = findfirst('{', algorithmName) if !isnothing(i1) algorithmName = algorithmName[1:i1-1] end i1 = findlast('.', algorithmName) if !isnothing(i1) algorithmName = algorithmName[i1+1:end] end end if FloatType == "Float64" heading = m.modelName * " (" * algorithmName * ")" else heading = m.modelName * " (" * algorithmName * ", " * FloatType * ")" end return heading end """ signal = get_result(model, name; unit=true) After a successful simulation of `model::SimulationModel`, return the result for the signal `name::String` as vector of points together with its unit. The time vector has path name `"time"`. If `unit=false`, the signal is returned, **without unit**. # Example ```julia using ModiaBase using Unitful include("\$(ModiaBase.path)/demos/models/Model_Pendulum.jl") using .Model_Pendulum pendulum = simulationModel(Pendulum) simulate!(pendulum, stopTime=7.0) time = get_result(pendulum, "time") # vector with unit u"s" phi = get_result(pendulum, "phi") # vector with unit u"rad" import PyPlot PyPlot.figure(4) # Change to figure 4 (or create it, if it does not exist) PyPlot.clf() # Clear current figure PyPlot.plot(ustrip(time), ustrip(phi), "b--", label="phi in " * string(unit(phi[1]))) PyPlot.xlabel("time in " * string(unit(time[1]))) PyPlot.legend() ``` """ function get_result(m::SimulationModel, name::String; unit=true) #(xsig, xsigLegend, ysig, ysigLegend, yIsConstant) = ModiaPlot.getPlotSignal(m, "time", name) (isConstant, ysig) = ModiaPlot.getRawSignal(m, name) ysig = unit ? ysig : ustrip.(ysig) #= if yIsConstant if ndims(ysig) == 1 ysig = fill(ysig[1], length(xsig)) else ysig = fill(ysig[1,:], length(xsig)) end end =# return ysig end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
33095
""" Main module of TinyModia. * Developer: Hilding Elmqvist, Mogram AB * First version: December 2020 * License: MIT (expat) """ module TinyModia using Reexport export instantiateModel, @instantiateModel using Base.Meta: isexpr using DataStructures: OrderedDict using ModiaBase.Symbolic using ModiaBase.Simplify using ModiaBase.BLTandPantelidesUtilities using ModiaBase.BLTandPantelides using ModiaBase.Differentiate using ModiaBase export ModiaBase # using RuntimeGeneratedFunctions # RuntimeGeneratedFunctions.init(@__MODULE__) @reexport using Unitful using Measurements import MonteCarloMeasurements include("NamedTupleModels.jl") include("CodeGeneration.jl") include("SimulateAndPlot.jl") # include("IncidencePlot.jl") # using .IncidencePlot const drawIncidence = false const path = dirname(dirname(@__FILE__)) # Absolute path of package directory const Version = "0.7.1" const Date = "2021-03-31" #println(" \n\nWelcome to Modia - Dynamic MODeling and Simulation in julIA") print(" \n\nWelcome to ") printstyled("Tiny", color=:light_black) print("Mod") printstyled("ia", bold=true, color=:red) print(" - ") printstyled("Dynamic ", color=:light_black) print("Mod") printstyled("eling and Simulation with Jul", color=:light_black) printstyled("ia", bold=true, color=:red) println() println("Version $Version ($Date)") function printArray(array, heading; order=1:length(array), log=false, number=true, indent=false, spacing=" ") if length(array) > 0 && log println(heading) n = 0 for v in array n += 1 if number print(lpad(order[n], 4), ": ") end if indent print(("|"*spacing)^(n-1)) end println(replace(replace(string(v), "\n" => " "), " " => " ")) end end end function performConsistencyCheck(G, Avar, vActive, parameters, unknowns, states, equations, log=false) nUnknowns = length(unknowns) - length(states) nEquations = length(equations) if nEquations > 0 && nUnknowns != nEquations printstyled("The number of unknowns ($nUnknowns) and equations ($nEquations) is not equal!\n", bold=true, color=:red) printArray(parameters, "Parameters:", log=true) printArray(states, "Potential states:", log=true) printArray(setdiff(unknowns,states), "Unknowns:", log=true) printArray(equations, "Equations:", log=true) end ok = nUnknowns == nEquations # Check consistency EG::Array{Array{Int,1},1} = [G; buildExtendedSystem(Avar)] assignEG = matching(EG, length(Avar)) # @assert all(assignEG .> 0) " The DAE is structurally singular\n $assignEG." assigned = [a > 0 for a in assignEG] if ! (all(assigned)) || ! ok if nUnknowns > nEquations missingEquations = nUnknowns - nEquations printstyled("\nThe DAE has no unique solution, because $missingEquations equation(s) missing!\n", bold=true, color=:red) elseif nEquations > nUnknowns tooManyEquations = nEquations - nUnknowns printstyled("\nThe DAE has no unique solution, because $tooManyEquations equation(s) too many\n", bold=true, color=:red) else printstyled("\nThe DAE has no unique solution, because it is structurally inconsistent\n" * " (the number of equations is identical to the number of unknowns)\n", bold=true, color=:red) end singular = true hequ = [] # Create dummy equations for printing: integrate(x, der(x)) = 0 for i in 1:length(Avar) a = Avar[i] if a > 0 n = unknowns[i] der = unknowns[a] push!(hequ, "integrate($n, $der) = 0") end end equationsEG = vcat(equations, hequ) println("\nAssigned equations after consistency check:") printAssignedEquations(equationsEG, unknowns, 1:length(EG), assignEG, Avar, fill(0, length(EG))) unassigned = [] for i in eachindex(assignEG) if assignEG[i] == 0 push!(unassigned, unknowns[i]) end end printArray(unassigned, "Not assigned variables after consistency check:", log=true) if nUnknowns > nEquations missingEquations = nUnknowns - nEquations error("Aborting, because $missingEquations equation(s) missing!") elseif nEquations > nUnknowns tooManyEquations = nEquations - nUnknowns error("Aborting, because $tooManyEquations equation(s) too many!") else error("Aborting, because DAE is structurally inconsistent") end elseif log println(" The DAE is structurally nonsingular.") end end function assignAndBLT(equations, unknowns, parameters, Avar, G, states, logDetails, log=false, logTiming=false) vActive = [a == 0 for a in Avar] if drawIncidence showIncidence(equations, unknowns, G, vActive, [], [], [], [[e] for e in 1:length(G)]) end if false # logAssignmentBeforePantelides @show G length(Avar) vActive assign = matching(G, length(Avar), vActive) @show assign println("\nAssigned equations:") Bequ = fill(0, length(G)) printAssignedEquations(equations, unknowns, 1:length(G), assign, Avar, Bequ) printUnassigned(equations, unknowns, assign, Avar, Bequ, vActive) end if logTiming println("\nCheck consistency of equations by matching extended equation set") @time performConsistencyCheck(G, Avar, vActive, parameters, unknowns, states, equations, log) else performConsistencyCheck(G, Avar, vActive, parameters, unknowns, states, equations, log) end if logTiming println("\nIndex reduction (Pantelides)") @time assign, Avar, Bequ = pantelides!(G, length(Avar), Avar) else assign, Avar, Bequ = pantelides!(G, length(Avar), Avar) end if logDetails @show assign Avar Bequ end moreVariables = length(Avar) > length(unknowns) unknowns = vcat(unknowns, fill(:x, length(Avar) - length(unknowns))) for i in 1:length(Avar) if Avar[i] > 0 unknowns[Avar[i]] = derivative(unknowns[i], keys(parameters)) end end moreEquations = length(Bequ) > length(equations) equations = vcat(equations, fill(:(a=b), length(Bequ) - length(equations))) for i in 1:length(Bequ) if Bequ[i] > 0 if log println("Differentiating: ", equations[i]) end equations[Bequ[i]] = derivative(equations[i], keys(parameters)) if log println(" Differentiated equation: ", equations[Bequ[i]]) end end end if moreVariables && log printArray(unknowns, "Unknowns after index reduction:", log=logDetails) end if moreEquations && log printArray(equations, "Equations after index reduction:", log=logDetails) end HG = Array{Array{Int64,1},1}() originalEquationIndex = [] highestDerivativeEquations = [] for i in 1:length(G) if Bequ[i] == 0 push!(HG, G[i]) push!(highestDerivativeEquations, equations[i]) push!(originalEquationIndex, i) end end vActive = [a == 0 for a in Avar] if logTiming println("Assign") @time assign = matching(HG, length(Avar), vActive) else assign = matching(HG, length(Avar), vActive) end if logTiming println("BLT") @time bltComponents = BLT(HG, assign) else bltComponents = BLT(HG, assign) end if logDetails @show HG @show bltComponents end if log println("\nSorted highest derivative equations:") printSortedEquations(highestDerivativeEquations, unknowns, bltComponents, assign, Avar, Bequ) end if drawIncidence assignedVar, unAssigned = invertAssign(assign) showIncidence(equations, unknowns, HG, vActive, [], assign, assignedVar, bltComponents, sortVariables=true) end for b in bltComponents if length(b) > 1 && logDetails println("\nTearing of BLT block") @show b es::Array{Int64,1} = b assignedVar, unAssigned = invertAssign(assign) vs = assignedVar[b] td = TearingSetup(HG, length(unknowns)) (eSolved, vSolved, eResidue, vTear) = tearEquations!(td, (e,v) -> v in HG[e], es, vs) @show vTear eResidue vSolved eSolved printArray(unknowns[vTear], "torn variables:", log=logDetails) printArray(equations[eResidue], "residue equations:", log=logDetails) printArray(unknowns[vSolved], "solved variables:", log=logDetails) printArray(equations[eSolved], "solved equations:", log=logDetails) end end blt = Vector{Int}[] # TODO: Change type for c in bltComponents push!(blt, originalEquationIndex[c]) end for i in eachindex(assign) if assign[i] != 0 assign[i] = originalEquationIndex[assign[i]] end end return (unknowns, equations, G, Avar, Bequ, assign, blt, parameters) end function setAvar(unknowns) Avar = fill(0, length(unknowns)) states = [] derivatives = [] for i in 1:length(unknowns) v = unknowns[i] if isexpr(v, :call) push!(derivatives, v) x = v.args[2] ix = findfirst(s -> s==x, unknowns) Avar[ix] = i push!(states, unknowns[ix]) end end return Avar, states, derivatives end mutable struct ModelStructure parameters::OrderedDict{Any,Any} mappedParameters::NamedTuple init::OrderedDict{Any,Any} start::OrderedDict{Any,Any} variables::OrderedDict{Any,Any} flows::OrderedDict{Any,Any} inputs::OrderedDict{Any,Any} outputs::OrderedDict{Any,Any} # components # extends equations::Array{Expr,1} end ModelStructure() = ModelStructure(OrderedDict(), (;), OrderedDict(), OrderedDict(), OrderedDict(), OrderedDict(), OrderedDict(), OrderedDict(), Expr[]) function printDict(label, d) if length(d) > 0 print(label) for (k,v) in d print(k) if v != nothing print(" => ", v) end print(", ") end println() end end function printModelStructure(m; label="", log=false) if log println("ModelStructure ", label) printDict(" parameters: ", m.parameters) println(" mappedParameters: ", m.mappedParameters) printDict(" init: ", m.init) printDict(" start: ", m.start) printDict(" variables: ", m.variables) printDict(" flows: ", m.flows) printDict(" inputs: ", m.inputs) printDict(" outputs: ", m.outputs) println(" equations: ") for e in m.equations println(" ", e) end end end prependDict(dict, prefix) = OrderedDict([prepend(k, prefix) => prepend(v, prefix) for (k,v) in dict]) function mergeModelStructures(parent::ModelStructure, child::ModelStructure, prefix) merge!(parent.parameters, prependDict(child.parameters, prefix)) if length(keys(child.parameters)) > 0 # @show parent.mappedParameters prefix typeof(prefix) child.mappedParameters child.parameters parent.mappedParameters = merge(parent.mappedParameters, (;prefix => (;child.mappedParameters...)) ) # @show parent.mappedParameters end merge!(parent.init, prependDict(child.init, prefix)) if length(keys(child.init)) > 0 # @show parent.mappedParameters prefix child.init parent.mappedParameters = recursiveMerge(parent.mappedParameters, (;prefix => (;child.mappedParameters...)) ) end merge!(parent.start, prependDict(child.start, prefix)) if length(keys(child.start)) > 0 parent.mappedParameters = recursiveMerge(parent.mappedParameters, (;prefix => (;child.mappedParameters...)) ) end merge!(parent.variables, prependDict(child.variables, prefix)) merge!(parent.flows, prependDict(child.flows, prefix)) merge!(parent.inputs, prependDict(child.inputs, prefix)) merge!(parent.outputs, prependDict(child.outputs, prefix)) push!(parent.equations, prepend(child.equations, prefix)...) end function replaceLinearIntegerEquations(Gint, eInt, GcInt, unknowns, equations) for i = 1:length(Gint) e = Gint[i] if length(e) > 0 # Construct equation rhs = 0 for j = 1:length(e) v = e[j] vc = GcInt[i][j] rhs = add(rhs, mult(vc, unknowns[v])) end equ = :(0 = $rhs) equations[eInt[i]] = equ else equations[eInt[i]] = :(0 = 0) end end end function performAliasReduction(unknowns, equations, Avar, logDetails, log) variablesIndices = OrderedDict(key => k for (k, key) in enumerate(unknowns)) linearVariables = [] nonlinearVariables = [] linearEquations = Vector{Int}() nonlinearEquations = [] G = Vector{Int}[] # Array{Array{Int64,1},1}() Gint = Array{Array{Int64,1},1}() GcInt = Array{Array{Int64,1},1}() for i in 1:length(equations) e = equations[i] nameIncidence, coefficients, rest, linear = getCoefficients(e) incidence = [variablesIndices[n] for n in nameIncidence if n in unknowns] unique!(incidence) push!(G, incidence) if linear && all([c == 1 || c == -1 for c in coefficients]) && rest == 0 && all(n in unknowns for n in nameIncidence) push!(linearVariables, nameIncidence...) push!(linearEquations, i) push!(Gint, incidence) push!(GcInt, coefficients) else push!(nonlinearVariables, nameIncidence...) push!(nonlinearEquations, e) end end if logDetails @show G @show Avar end unique!(linearVariables) unique!(nonlinearVariables) vSolveInLinearEquations = setdiff(linearVariables, nonlinearVariables) if logDetails printArray(linearVariables, "linearVariables:", number=false) printArray(equations[linearEquations], "linearEquations:", number=false) # printArray(nonlinearVariables, "nonlinearVariables:", number=false) # printArray(nonlinearEquations, "nonlinearEquations:", number=false) @show linearEquations vSolveInLinearEquations Gint GcInt end GCopy = deepcopy(G) AvarCopy = deepcopy(Avar) (vEliminated, vProperty, nvArbitrary, redundantEquations) = simplifyLinearIntegerEquations!(GCopy, linearEquations, GcInt, AvarCopy) if logDetails @show vEliminated vProperty nvArbitrary redundantEquations end if log printSimplifiedLinearIntegerEquations(GCopy, linearEquations, GcInt, vEliminated, vProperty, nvArbitrary, redundantEquations, v->string(unknowns[v]), printTest=false) end substitutions = OrderedDict() if length(vEliminated) - nvArbitrary > 0 for v in vEliminated[nvArbitrary+1:end] if isZero(vProperty, v) substitutions[unknowns[v]] = 0.0 elseif isAlias(vProperty, v) substitutions[unknowns[v]] = unknowns[alias(vProperty,v)] else substitutions[unknowns[v]] = :(- $(unknowns[negAlias(vProperty,v)])) end end end replaceLinearIntegerEquations(GCopy[linearEquations], linearEquations, GcInt, unknowns, equations) # printArray(equations, "new equations:", log=log) reducedEquations = [] for ei in 1:length(equations) e = equations[ei] if e != :(0 = 0) push!(reducedEquations, substitute(substitutions, e)) end end reducedUnknowns = [] for vi in 1:length(unknowns) if isNotEliminated(vProperty, vi) push!(reducedUnknowns, unknowns[vi]) end end reducedVariablesIndices = OrderedDict(key => k for (k, key) in enumerate(reducedUnknowns)) reducedG = Vector{Int}[] # Array{Array{Int64,1},1}() for i in 1:length(reducedEquations) e = reducedEquations[i] nameIncidence, coefficients, rest, linear = getCoefficients(e) incidence = [reducedVariablesIndices[n] for n in nameIncidence if n in reducedUnknowns] unique!(incidence) push!(reducedG, incidence) end reducedAvar, reducedStates, reducedDerivatives = setAvar(reducedUnknowns) return reducedEquations, reducedUnknowns, reducedAvar, reducedG, reducedStates, vEliminated, vProperty end function stateSelectionAndCodeGeneration(modelStructure, name, modelModule, FloatType, init, start, vEliminated, vProperty, unknownsWithEliminated, mappedParameters; unitless=false, logStateSelection=false, logCode=false, logExecution=false, logTiming=false) (unknowns, equations, G, Avar, Bequ, assign, blt, parameters) = modelStructure function getSolvedEquationAST(e, v) (solution, solved) = solveEquation(equations[e], unknowns[v]) equ = string(equations[e]) @assert solved "Equation not solved for $(unknowns[v]): $(equations[e])" # sol = string(solution) # solution = prepend(makeDerivativeVar(solution, components), :m) if false # solution = :(begin println("Executing: ", $sol); $solution end) if sol != equ solution = :(try $solution; catch e; println("\n\nFailure executing: ", $sol); println("Original equation: ", $equ, "\n\n"); rethrow(e) end) else solution = :(try $solution; catch e; println("\n\nFailure executing: ", $sol, "\n\n"); rethrow(e) end) end # solution = :(try $solution; catch e; println("Failure executing: ", $sol); println(sprint(showerror,e)); rethrow(e) end) # solution = :(try $solution; catch e; println("Failure executing: ", $sol); printstyled(stderr,"ERROR: ", bold=true, color=:red); # printstyled(stderr,sprint(showerror,e), color=:light_red); println(stderr); end) end solution = makeDerVar(solution, keys(parameters)) if logExecution var = string(unknowns[v]) return :($solution; println($var, " = ", upreferred.($(solution.args[1])))) else return solution end end function getResidualEquationAST(e, residualName) eq = equations[e] # prepend(makeDerivativeVar(equations[e], components), :m) resid = makeDerVar(:(ustrip($(eq.args[2]) - $(eq.args[1]))), keys(parameters)) residual = :($residualName = $resid) if false #logExecution return makeDerVar(:(dump($(makeDerVar(eq.args[2]))); dump($(makeDerVar(eq.args[1]))); $residual; println($residualName, " = ", upreferred.(($(eq.args[2]) - $(eq.args[1])))))) else return residual end end function isLinearEquation(e_original, v_original) equ = equations[e_original] var = unknowns[v_original] return isLinear(equ, var) end function isSolvableEquation(e_original, v_original) equ = equations[e_original] var = unknowns[v_original] (solution, solved) = solveEquation(equ, var) return solved end hasParticles(value) = typeof(value) <: MonteCarloMeasurements.StaticParticles || typeof(value) <: MonteCarloMeasurements.Particles function var_unit(v) var = unknowns[v] # @show var init[var] if var in keys(init) value = eval(init[var]) # value = 0.0 elseif var in keys(start) value = eval(start[var]) else value = 0.0 end if hasParticles(value) # Units not yet support for particles return "" end # if length(value) == 1 if ! (typeof(value) <: Array) un = unit(value) else un = unit.(value) # un = [unit(v) for v in value] # unit.(value) does not work for MonteCarloMeasurements @assert all([un[i] == un[1] for i in 2:length(un)]) "The unit of all elements of state vector must be equal: $var::$(value)" un = un[1] end return replace(string(un), " " => "*") # Fix since Unitful removes * in unit strings end function var_has_start(v_original) return unknowns[v_original] in keys(init) || unknowns[v_original] in keys(start) end function var_fixed(v_original) return unknowns[v_original] in keys(init) end function var_length(v_original) v = unknowns[v_original] if v in keys(init) value = eval(init[v]) # value = 0.0 len = hasParticles(value) ? 1 : length(value) else len = 1 end return len end function eq_equation(e) return replace(replace(string(equations[e]), "\n" => " "), " " => " ") end # ---------------------------------------------------------------------------- solvedAST = [] Gsolvable = copy(G) juliaVariables = [Symbol(u) for u in unknowns] stringVariables = [String(Symbol(v)) for v in unknowns] allEquations = equations # @show stringVariables equations G blt assign Avar Bequ Gsolvable stateSelectionFunctions = StateSelectionFunctions( var_name = v -> stringVariables[v], var_julia_name = v -> juliaVariables[v], var_unit = var_unit, var_has_start = var_has_start, var_fixed = var_fixed, var_nominal = v_original -> NaN, var_unbounded = v_original -> false, var_length = var_length, equation = eq_equation, isSolvableEquation = isSolvableEquation, isLinearEquation = isLinearEquation, getSolvedEquationAST = getSolvedEquationAST, getResidualEquationAST = getResidualEquationAST, showMessage = (message;severity=0,from="???",details="",variables=Int[],equations=Int[]) -> ModiaBase.showMessage(message, severity, from, details, stringVariables[variables], string.(allEquations[equations])) ) if length(equations) == 0 return nothing end if logTiming println("Get sorted and solved AST") @time (success,AST,equationInfo) = getSortedAndSolvedAST( G, Array{Array{Int64,1},1}(blt), assign, Avar, Bequ, stateSelectionFunctions; unitless, log = logStateSelection, modelName = name) else (success,AST,equationInfo) = getSortedAndSolvedAST( G, Array{Array{Int64,1},1}(blt), assign, Avar, Bequ, stateSelectionFunctions; unitless, log = logStateSelection, modelName = name) end # equationInfo.nz = nCrossingFunctions if ! success error("Aborting") end # @show AST # @show equationInfo selectedStates = [v.x_name_julia for v in equationInfo.x_info] startValues = [] for v in selectedStates v = Meta.parse(string(v)) if v in keys(init) value = eval(init[v]) # value = [0.0 0.0] # TODO: Fix # @show value if hasParticles(value) push!(startValues, value) else push!(startValues, value...) end elseif v in keys(start) value = eval(start[v]) if hasParticles(value) push!(startValues, value) else push!(startValues, value...) end else push!(startValues, 0.0) end end if logCode println("startValues = ", startValues) end vSolvedWithInit = equationInfo.vSolvedWithFixedTrue vSolvedWithInitValuesAndUnit = OrderedDict{String,Any}() for name in vSolvedWithInit nameAsExpr = Meta.parse(name) if haskey(init, nameAsExpr) vSolvedWithInitValuesAndUnit[name] = eval( init[nameAsExpr] ) else @warn "Internal issue of TinyModia: $name is assumed to have an init-value, but it is not found." end end # Generate code if logTiming println("Generate code") # @time code = generate_getDerivatives!(AST, equationInfo, Symbol.(keys(parameters)), vcat(:time, [Symbol(u) for u in unknowns]), :getDerivatives, hasUnits = !unitless) @time code = generate_getDerivatives!(AST, equationInfo, [:(_p)], vcat(:time, [Symbol(u) for u in unknowns]), :getDerivatives, hasUnits = !unitless) else # code = generate_getDerivatives!(AST, equationInfo, Symbol.(keys(parameters)), vcat(:time, [Symbol(u) for u in unknowns]), :getDerivatives, hasUnits = !unitless) code = generate_getDerivatives!(AST, equationInfo, [:(_p)], vcat(:time, [Symbol(u) for u in unknowns]), :getDerivatives, hasUnits = !unitless) end if logCode @show mappedParameters showCodeWithoutComments(code) end # Compile code # generatedFunction = @RuntimeGeneratedFunction(modelModule, code) #getDerivatives = Core.eval(modelModule, code) Core.eval(modelModule, code) getDerivatives = modelModule.getDerivatives # If generatedFunction is not packed inside a function, DifferentialEquations.jl crashes # getDerivatives(derx,x,m,time) = generatedFunction(derx, x, m, time) # Execute code if logExecution println("\nExecute getDerivatives") @show startValues end convertedStartValues = convert(Vector{FloatType}, [ustrip(v) for v in startValues]) # ustrip.(value) does not work for MonteCarloMeasurements model = SimulationModel{FloatType}(modelModule, name, getDerivatives, equationInfo, convertedStartValues, # parameters, vcat(:time, [Symbol(u) for u in unknowns]); OrderedDict(:(_p) => mappedParameters ), vcat(:time, [Symbol(u) for u in unknowns]); vSolvedWithInitValuesAndUnit, vEliminated, vProperty, var_name = (v)->string(unknownsWithEliminated[v])) if logExecution derx = deepcopy(convertedStartValues) # To get the same type as for x (deepcopy is needed for MonteCarloMeasurements) # @time getDerivatives(derx, convertedStartValues, model, convert(FloatType, 0.0)) Base.invokelatest(getDerivatives, derx, convertedStartValues, model, convert(FloatType, 0.0)) @show derx end return model end """ modelInstance = @instantiateModel(model; FloatType = Float64, aliasReduction=true, unitless=false, log=false, logModel=false, logDetails=false, logStateSelection=false, logCode=false, logExecution=false, logTiming=false) Instantiates a model, i.e. performs structural and symbolic transformations and generates a function for calculation of derivatives suitable for simulation. * `model`: model (declarations and equations) * `FloatType`: Variable type for floating point numbers, for example: Float64, Measurements{Float64}, StaticParticles{Float64,100}, Particles{Float64,2000} * `aliasReduction`: Perform alias elimination and remove singularities * `unitless`: Remove units (useful while debugging models and needed for MonteCarloMeasurements) * `log`: Log the different phases of translation * `logModel`: Log the variables and equations of the model * `logDetails`: Log internal data during the different phases of translation * `logStateSelection`: Log details during state selection * `logCode`: Log the generated code * `logExecution`: Log the execution of the generated code (useful for finding unit bugs) * `logTiming`: Log timing of different phases * `return modelInstance prepared for simulation` """ macro instantiateModel(model, kwargs...) modelName = string(model) code = :( instantiateModel($model; modelName=$modelName, modelModule=@__MODULE__, source=@__FILE__, $(kwargs...) ) ) return esc(code) end """ See documentation of macro @instatiateModel """ function instantiateModel(model; modelName="", modelModule=nothing, source=nothing, FloatType = Float64, aliasReduction=true, unitless=false, log=false, logModel=false, logDetails=false, logStateSelection=false, logCode=false, logExecution=false, logTiming=false) try println("\nInstantiating model $modelModule.$modelName") modelStructure = ModelStructure() if typeof(model) <: NamedTuple if logModel @showModel(model) end if logTiming println("Flatten") @time flattenModelTuple!(model, modelStructure, modelName; unitless, log) else flattenModelTuple!(model, modelStructure, modelName; unitless, log) end printModelStructure(modelStructure, log=logDetails) name = modelName else error("Invalid model format") end allVariables = Incidence[] if logTiming println("Find incidence") @time findIncidence!(modelStructure.equations, allVariables) else findIncidence!(modelStructure.equations, allVariables) end unique!(allVariables) # @show allVariables unknowns = setdiff(allVariables, keys(modelStructure.parameters), [:time]) Avar, states, derivatives = setAvar(unknowns) vActive = [a == 0 for a in Avar] if log println("Number of states: ", length(states)) println("Number of unknowns: ", length(unknowns)-length(states)) println("Number of equations: ", length(modelStructure.equations)) end printArray(modelStructure.parameters, "Parameters:", log=log) printArray(states, "Potential states:", log=log) printArray(setdiff(unknowns, states), "Unknowns:", log=log) printArray(modelStructure.equations, "Equations:", log=log) if logDetails @show modelStructure.parameters modelStructure.mappedParameters modelStructure.init modelStructure.start modelStructure.variables modelStructure.flows end unknownsWithEliminated = unknowns if aliasReduction if log || logTiming println("Perform alias elimination and remove singularities") end if logTiming @time equations, unknowns, Avar, G, states, vEliminated, vProperty = performAliasReduction(unknowns, modelStructure.equations, Avar, logDetails, log) println("Number of reduced unknowns: ", length(unknowns)-length(states)) println("Number of reduced equations: ", length(equations)) else equations, unknowns, Avar, G, states, vEliminated, vProperty = performAliasReduction(unknowns, modelStructure.equations, Avar, logDetails, log) end printArray(states, "States:", log=log) printArray(setdiff(unknowns, states), "Unknowns after alias reduction:", log=log) printArray(equations, "Equations after alias reduction:", log=log) else equations = modelStructure.equations G = Vector{Int}[] # Array{Array{Int64,1},1}() variablesIndices = OrderedDict(key => k for (k, key) in enumerate(unknowns)) for i in 1:length(equations) e = equations[i] nameIncidence, coefficients, rest, linear = getCoefficients(e) incidence = [variablesIndices[n] for n in nameIncidence if n in unknowns] unique!(incidence) push!(G, incidence) end vEliminated = Int[] vProperty = Int[] end modStructure = assignAndBLT(equations, unknowns, modelStructure.parameters, Avar, G, states, logDetails, log, logTiming) stateSelectionAndCodeGeneration(modStructure, name, modelModule, FloatType, modelStructure.init, modelStructure.start, vEliminated, vProperty, unknownsWithEliminated, modelStructure.mappedParameters; unitless, logStateSelection, logCode, logExecution, logTiming) catch e if isa(e, ErrorException) println() printstyled("Model error: ", bold=true, color=:red) printstyled(e.msg, "\n", bold=true, color=:red) printstyled("Aborting instantiateModel for $modelName in $modelModule\n", bold=true, color=:red) println() # Base.rethrow() else Base.rethrow() end end end end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
4779
module TestDeclarations using Unitful using BenchmarkTools struct Var var::NamedTuple Var(; kwargs...) = new((;kwargs...) ) end struct Model model::NamedTuple Model(; kwargs...) = new((;kwargs...) ) end struct Map map::NamedTuple Map(; kwargs...) = new((;kwargs...) ) end Pin = Model( v = Var(potential=true, nominal=10), i = Var(;flow=true) ) @show Pin Input(; kwargs...) = Var(;input=true, kwargs...) Output(; kwargs...) = Var(;output=true, kwargs...) Potential(; kwargs...) = Var(;potential=true, kwargs...) Flow(; kwargs...) = Var(;flow=true, kwargs...) using Base.Meta: isexpr using DataStructures: OrderedDict using Unitful using ModiaBase.Symbolic: removeBlock function showModel(m, level=0) println("(") level += 1 for (k, v) in zip(keys(m), m) if typeof(v) <: NamedTuple print(" "^level, k, " = ") showModel(v, level) else println(" "^level, k, " = ", removeBlock(v), ",") end end println(" "^(level-1), "),") end macro showModel(model) modelName = string(model) mod = :( print($modelName, " = Model"); showModel($model); println() ) return esc(mod) end global logMerge = true function setLogMerge(val) global logMerge logMerge = val end recursiveMerge(x, ::Nothing) = x recursiveMerge(x, y) = y recursiveMerge(x::Expr, y::Expr) = begin dump(x); dump(y); Expr(x.head, x.args..., y.args...) end recursiveMerge(x::Expr, y::Tuple) = begin x = copy(x); xargs = x.args; xargs[y[2]] = y[3]; Expr(x.head, xargs...) end function recursiveMerge(nt1::NamedTuple, nt2::NamedTuple) all_keys = union(keys(nt1), keys(nt2)) gen = Base.Generator(all_keys) do key v1 = get(nt1, key, nothing) v2 = get(nt2, key, nothing) key => recursiveMerge(v1, v2) end return (; gen...) end function mergeModels(m1::NamedTuple, m2::NamedTuple, env=Symbol()) mergedModels = OrderedDict{Symbol,Any}(pairs(m1)) for (k,v) in collect(pairs(m2)) if typeof(v) <: NamedTuple if k in keys(mergedModels) && ! (:_redeclare in keys(v)) if logMerge; print("In $k: ") end m = mergeModels(mergedModels[k], v, k) mergedModels[k] = m elseif :_redeclare in keys(v) if logMerge; println("Redeclaring: $k = $v") end mergedModels[k] = v elseif nothing in values(v) # TODO: Refine else if !(:_redeclare in keys(mergedModels)) if logMerge; println("Adding: $k = $v") end end mergedModels[k] = v end elseif v === nothing if logMerge; println("Deleting: $k") end delete!(mergedModels, k) else if logMerge if k in keys(mergedModels) println("Changing: $k = $(mergedModels[k]) to $k = $v") elseif !(:_redeclare in keys(mergedModels)) println("Adding: $k = $v") end end mergedModels[k] = v end end return (; mergedModels...) # Transform OrderedDict to named tuple end mergeModels(m1::Model, m2::Model, env=Symbol()) = recursiveMerge(m1.model, m2.model) mergeModels(m1::Model, m2::Map, env=Symbol()) = recursiveMerge(m1.model, m2.map) #Base.:|(m::Model, n::Model) = recursiveMerge(m.model, n.model) #Base.:|(m::Model, n::Map) = recursiveMerge(m.model, n.map) #Base.:|(m, n::Map) = recursiveMerge(m, n.map) Base.:|(m::Model, n::Model) = (:MergeModel, m.model, n.model) Base.:|(m::Model, n::Map) = (:MergeMap, m.model, n.map) Base.:|(m, n::Map) = (:MergeMap, m, n.map) Redeclare = ( _redeclare = true, ) Replace(i, e) = (:replace, i, e) Final(x) = x # ---------------------------------------------------------- @time Pin = Model( v = Potential(), i = Flow() ) OnePort = Model( p = Pin, n = Pin, equations = :[ v = p.v - n.v 0 = p.i + n.i i = p.i ] ) @showModel(OnePort.model) @time Resistor = OnePort | Model( R = Final(1.0u"Ξ©"), equations = Replace(1, :( R*i = v ) )) @showModel(Resistor) Capacitor = OnePort | Model( C = 1.0u"F", v = Map(init=0.0u"V"), equations = :[ C*der(v) = i ] ) Inductor = OnePort | Model( L = 1.0u"H", i = Map(init=0.0u"A"), equations = :[ L*der(i) = v ] ) ConstantVoltage = OnePort | Model( V = 1.0u"V", equations = :[ v = V ] ) Ground = Model( p = Pin, equations = :[ p.v = 0.0u"V" ] ) @time Filter = Model( R = Resistor | Map(R=0.5u"Ξ©"), C = Capacitor | Map(C=2.0u"F", v=Map(init=0.1u"V")), V = ConstantVoltage | Map(V=10.0u"V"), ground = Ground, connect = :[ (V.p, R.p) (R.n, C.p) (C.n, V.n, ground.p) ] ) @showModel(Filter.model) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
2138
module TestFilterCircuit using TinyModia using DifferentialEquations using ModiaPlot using Test setLogMerge(false) include("../models/Electric.jl") FilterCircuit = Model( R = Resistor | Map(R=0.5u"Ξ©"), C = Capacitor | Map(C=2.0u"F", v=Var(init=0.1u"V")), V = ConstantVoltage | Map(V=10.0u"V"), ground = Ground, connect = :[ (V.p, R.p) (R.n, C.p) (C.n, V.n, ground.p) ] ) filterCircuit = @instantiateModel(FilterCircuit) simulate!(filterCircuit, Tsit5(), stopTime = 10, merge = Map(R = Map(R = 5u"Ξ©"), C = Map(v = 3.0u"V")), logParameters = true, logStates = true, requiredFinalStates = [7.424843902110655]) # Test access functions @testset "Test variable access functions" begin @test ModiaPlot.getNames(filterCircuit) == ["C.C", "C.class", "C.i", "C.n.i", "C.n.v", "C.p.i", "C.p.v", "C.v", "C.v", "R.R", "R.class", "R.i", "R.n.i", "R.n.v", "R.p.i", "R.p.v", "R.v", "V.V", "V.i", "V.n.i", "V.n.v", "V.p.i", "V.p.v", "V.v", "class", "der(C.v)", "ground.p.i", "ground.p.v", "time"] @test ModiaPlot.hasSignal(filterCircuit, "R.v") @test ModiaPlot.hasSignal(filterCircuit, "C.n.v") @test ModiaPlot.hasSignal(filterCircuit, "R.R") @test ModiaPlot.hasSignal(filterCircuit, "ground.p.i") @test ModiaPlot.hasSignal(filterCircuit, "R.p.vv") == false @test isapprox(get_lastValue(filterCircuit, "R.v") , 2.5751560978893453u"V" ) @test isapprox(get_lastValue(filterCircuit, "C.n.v"), 0.0u"V") @test isapprox(get_lastValue(filterCircuit, "R.R") , 5.0u"Ξ©") @test isapprox(get_lastValue(filterCircuit, "ground.p.i"), 0.0) end # Test plotting of variables, zero variables, parameters plot(filterCircuit, [("R.v", "C.v"), ("R.R", "ground.p.i")], figure=1) # Simulate with lower precision filterCircuitLow = @instantiateModel(FilterCircuit, FloatType = Float32) simulate!(filterCircuitLow, RK4(), adaptive=false, stopTime=10.0, interval=0.01, merge = Map(R = Map(R = 5u"Ξ©"), C = Map(v = 3.0u"V")), requiredFinalStates = Float32[7.4248414]) plot(filterCircuitLow, [("R.v", "C.v"), ("R.R", "ground.p.i")], figure=2) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
570
module TestFirstOrder using TinyModia using DifferentialEquations using ModiaPlot # using RuntimeGeneratedFunctions # RuntimeGeneratedFunctions.init(@__MODULE__) inputSignal(t) = sin(t) FirstOrder = Model( T = 0.2, x = Var(init=0.3), equations = :[u = inputSignal(time/u"s"), T * der(x) + x = u, y = 2*x] ) firstOrder = @instantiateModel(FirstOrder, logCode=false) simulate!(firstOrder, Tsit5(), stopTime = 10, log=false, requiredFinalStates = [-0.3617373025974107]) plot(firstOrder, ["u", "x", "der(x)", "y"]) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
724
module TestFirstOrder2 using TinyModia using DifferentialEquations using ModiaPlot # using RuntimeGeneratedFunctions # RuntimeGeneratedFunctions.init(@__MODULE__) inputSignal(t) = sin(t) FirstOrder1 = Model( T = 0.2, x = Var(init=0.3), equations = :[u = inputSignal(time/u"s"), T * der(x) + x = u, y = 2*x] ) FirstOrder2 = FirstOrder1 | Map(T = 0.3, x = Var(init=0.6)) firstOrder = @instantiateModel(FirstOrder2, logCode=true) simulate!(firstOrder, Tsit5(), stopTime = 10, merge = Map(T = 0.4, x = 0.9), log=true, logParameters=true, logStates=true, requiredFinalStates = [-0.17964872595554535]) plot(firstOrder, [("u", "x"), "der(x)", "y"]) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
1158
module TestHeatTransfer using TinyModia using Unitful using ModiaPlot using DifferentialEquations include("$(TinyModia.path)/models/HeatTransfer.jl") SimpleRod = Model( fixedT = FixedTemperature | Map(T = 393.15u"K"), C = HeatCapacitor | Map(C = 200u"J/K"), G = ThermalConductor | Map(G = 100u"W/K"), connect = :[ (fixedT.port, G.port_a), (G.port_b , C.port) ] ) simpleRod = @instantiateModel(SimpleRod) simulate!(simpleRod, Tsit5(), stopTime = 15, requiredFinalStates = [393.09468783194814]) plot(simpleRod, ("fixedT.port.T", "C.T"), figure=1) HeatedRod = Model( fixedT = FixedTemperature | Map(T = 493.15u"K"), fixedQflow = FixedHeatFlow, rod = InsulatedRod | Map(T = Var(init = fill(293.15u"K", 5))), connect = :[ (fixedT.port, rod.port_a), (rod.port_b , fixedQflow.port) ] ) heatedRod = @instantiateModel(HeatedRod) simulate!(heatedRod, Tsit5(), stopTime = 1e5, requiredFinalStates = [492.9629728925529, 492.607421697723, 492.30480548105595, 492.0850627579106, 491.9694736486912]) plot(heatedRod, ("fixedT.port.T", "rod.T"), figure=2) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
204
module TestJSON import JSON mutable struct S a b end mutable struct T a b end s = S(1,T(10, 25)) JSON.print(s) n = (a=1, b=(a=10, b=25)) JSON.print(n) @show JSON.print(s) == JSON.print(n) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
2157
module TestMechanics println("TestMechanics: Tests how 3D mechanics could be combined with TinyModia.") using TinyModia using Unitful using ModiaPlot using DifferentialEquations using RuntimeGeneratedFunctions RuntimeGeneratedFunctions.init(@__MODULE__) # TinyModia models include("$(TinyModia.path)/models/Blocks.jl") include("$(TinyModia.path)/models/Electric.jl") include("$(TinyModia.path)/models/Rotational.jl") # Generic TinyModia3D model stubs (always available) RevoluteStub = Model( flange = Flange, equations = :[phi = flange.phi w = der(phi) der_w = der(w) tau = flange.tau] ) # Generic Modia3D definitions (always available) mutable struct SimulationModel3D # Internal memory of 3D model initial::Bool SimulationModel3D() = new(true) end # Function ..._f1 for 3D mechanics # function Pendulum_f1(_m::SimulationModel3D, phi::Float64, w::Float64, tau::Float64, # m::Float64, L::Float64, g::Float64) function Pendulum_f1(_m::TestMechanics.SimulationModel3D, phi, w, tau, m, L, g) #function Pendulum_f1(phi, w, tau, m, L, g) #= if _m.initial println("... SimplePendulum_f1 called during initialization") _m.initial = false end =# der_w = (tau - m*g*L*cos(phi))/m*L*L return der_w end # TinyModia model for the system Pendulum = Model( model3D = SimulationModel3D(), # Parameters m = 1.0u"kg", L = 0.5u"m", g = 9.81u"m/s^2", # 3D model stubs rev = RevoluteStub | Map(init = Map(phi=1.5u"rad", w=2u"rad/s")), # Standard TinyModia models damper = Damper | Map(d=0.4u"N*m*s/rad"), support = Fixed, connect = :[ (rev.flange , damper.flange_b), (damper.flange_a, support.flange)], equations = :(rev.der_w = Pendulum_f1(model3D, rev.phi, rev.w, rev.tau, m, L, g)) # equations = :(rev.der_w = Pendulum_f1(rev.phi, rev.w, rev.tau, m, L, g)) ) pendulum = @instantiateModel(Pendulum, logCode=true, logExecution=false, unitless=true) simulate!(pendulum, Tsit5(), stopTime=20.0, log=true) plot(pendulum, ["rev.phi", "rev.w"]) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
3079
module TestSingularLRRL using TinyModia using DifferentialEquations using ModiaPlot SingularLRRL = Model( v0 = 10, L1_L = 0.1, L2_L = 0.2, R1_R = 10, R2_R = 20, L2_p_i = Var(init = 0.1), R2_p_i = Var(start = 0.0), V_n_v = Var(start = 0.0), equations =:[ # Inductor 1 L1_v = L1_p_v - L1_n_v 0 = L1_p_i + L1_n_i L1_L*der(L1_p_i) = L1_v # Inductor 2 L2_v = L2_p_v - L2_n_v 0 = L2_p_i + L2_n_i L2_L*der(L2_p_i) = L2_v # Resistor 1 R1_v = R1_p_v - R1_n_v 0 = R1_p_i + R1_n_i R1_v = R1_R*R1_p_i # Resistor 2 R2_v = R2_p_v - R2_n_v 0 = R2_p_i + R2_n_i R2_v = R2_R*R2_p_i # Voltage source V_v = V_p_v - V_n_v 0 = V_p_i + V_n_i # Connect equations # connect(V.p, L1.p) # connect(L1.n, R1.p) # connect(L1.n, R2.p) # connect(R1.n, L2.p) # connect(R2.n, L2.p) # connect(L2.n, V.n) V_p_v = L1_p_v 0 = V_p_i + L1_p_i L1_n_v = R1_p_v L1_n_v = R2_p_v 0 = L1_n_i + R1_p_i + R2_p_i R1_n_v = L2_p_v R2_n_v = L2_p_v 0 = R1_n_i + R2_n_i + L2_p_i L2_n_v = V_n_v 0 = L2_n_i + V_n_i #+ ground_v_i #V_n_v = 0 V_v = v0 ] ) singularLRRL = @instantiateModel(SingularLRRL) simulate!(singularLRRL, Tsit5(), stopTime = 1.0, requiredFinalStates = [1.4999999937318995]) plot(singularLRRL, [("L1_p_i", "L2_p_i", "R1_p_i", "R2_p_i"), ("L1_v", "L2_v", "R1_v", "R2_v")]) include("../models/Electric.jl") setLogMerge(false) SingularLRRL2 = Model( R1 = Resistor | Map(R=10u"Ω"), R2 = Resistor | Map(R=20u"Ω", start = Map(v=0.0u"V")), L1 = Inductor | Map(L=0.1u"H", i = Var(init=nothing)), L2 = Inductor | Map(L=0.2u"H", start = Map(v=0.0u"V")), V = ConstantVoltage | Map(V=10u"V"), connections = :[ (V.p, L1.p) (L1.n, R1.p, R2.p) (L2.p, R1.n, R2.n) (L2.n, V.n) ] ) #= singularLRRL2 = @instantiateModel(SingularLRRL2, log=true, logCode=true, logExecution=true) simulate!(singularLRRL2, Tsit5(), stopTime = 1.0) plot(singularLRRL2, [("L1.p.i", "L2.p.i", "R1.p.i", "R2.p.i"), ("L1.v", "L2.v", "R1.v", "R2.v")]) =# SingularLRRL3 = Model( R1 = Resistor | Map(R=1), R2 = Resistor | Map(R=2), R3 = Resistor | Map(R=3), R4 = Resistor | Map(R=4), L1 = Inductor | Map(L=0.1), L2 = Inductor | Map(L=0.2, i = Var(init=nothing)), V = ConstantVoltage | Map(V=10), # ground = Ground, connections = :[ (V.p, L1.p) (L1.n, R1.p, R2.p) (R1.n, R2.n, R3.p, R4.p) (L2.p, R3.n, R4.n) (L2.n, V.n) ] #, ground.p) ] ) singularLRRL3 = @instantiateModel(SingularLRRL3, unitless=true, log=false, logDetails=false) simulate!(singularLRRL3, Tsit5(), stopTime = 1.0, requiredFinalStates = [4.198498632779839]) plot(singularLRRL3, [("L1.i", "L2.i", "R1.i", "R2.i", "R3.i", "R4.i"), ("L1.v", "L2.v", "R1.v", "R2.v", "R3.v", "R4.v")]) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
6851
module TestStateSelection using TinyModia using Test function checkStateSelection(model, x_names, linearEquations=[]) # Check names of the states for (i, state_i) in enumerate(model.equationInfo.x_info) @test state_i.x_name == x_names[i] end # Check linear equation systems if length(linearEquations) > 0 @test model.equationInfo.linearEquations == linearEquations end end @testset "\nTest ModiaBase/StateSelection.jl" begin @testset "... Test FirstOrder" begin FirstOrder = Model( T = 0.2, x = Var(init=0.3), equations = :[ u = 1.0 der(x) = (u - x)/T y = 2*x] ) firstOrder = @instantiateModel(FirstOrder) checkStateSelection(firstOrder, ["x"]) end @testset "... Test TwoCoupledInertias" begin TwoCoupledInertias = Model( J1_J = 1, J2_J = 1, J1_phi = Var(start=1.0), J1_w = Var(start=0.0), J2_phi = Var(start=0.0), J2_w = Var(start=0.0), equations = :[ J1_w = der(J1_phi) J1_J * der(J1_w) = J1_tau J2_w = der(J2_phi) J2_J * der(J2_w) = J2_tau J2_phi = J1_phi J2_tau + J1_tau = 0] ) twoCoupledInertias = @instantiateModel(TwoCoupledInertias) checkStateSelection(twoCoupledInertias, ["J1_w", "J1_phi"], [(["J1_tau"], [1], 1, 1)]) end @testset "... Test ODE with linear equations 1" begin ODEwithLinearEquations1 = Model( p1=4, p2=2, x6 = Var(start=1.0), equations = :[ x1 = sin(time) p2*x2 = p1*x1 2*x3 + 4*x4 = x1 x3 + x5 = 2*x2 4*x4 + 5*x5 = x1 + x2 der(x6) = -x5*x6] ) oDEwithLinearEquations1 = @instantiateModel(ODEwithLinearEquations1, unitless=true) checkStateSelection(oDEwithLinearEquations1, ["x6"], [(["x5"], [1], 1, 1)]) end @testset "... Test ODE with linear equations 2" begin ODEwithLinearEquations2 = Model( p1=4, p2=2, x6 = Var(start=1.0), equations = :[ x1 = sin(time) p2*x2 = p1*x1 p2*x3 + p1*x4 + 5*der(x6) = x1 x3 + x5 = 2*x2 4*x4 + 5*x5 = x1 + x2 3*der(x6) = -5*x3 - 2*x4] ) oDEwithLinearEquations2 = @instantiateModel(ODEwithLinearEquations2, unitless=true) checkStateSelection(oDEwithLinearEquations2, ["x6"], [(["x5"], [1], 1, 1)]) end @testset "... Test Multi-index DAE" begin MultiIndexDAE = Model( equations = :[ u1 = sin(1*time) u2 = sin(2*time) u3 = sin(3*time) u4 = sin(4*time) u5 = sin(5*time) u6 = sin(6*time) u7 = sin(7*time) 0 = u1 + x1 - x2 0 = u2 + x1 + x2 - x3 + der(x6) 0 = u3 + x1 + der(x3) - x4 x1d = der(x1) x2d = der(x2) x3d = der(x3) x6d = der(x6) x6dd = der(x6d) 0 = u4 + 2*der(x1d) + der(x2d) + der(x3d) + der(x4) + der(x6dd) 0 = u5 + 3*der(x1d) + 2*der(x2d) + x5 0 = u6 + 2*x6 + x7 0 = u7 + 3*x6 + 4*x7] ) multiIndexDAE = @instantiateModel(MultiIndexDAE, unitless=true) #@show multiIndexDAE.equationInfo.linearEquations checkStateSelection(multiIndexDAE, ["x2", "x2d"], [(["x7"], [1], 1, 1), (["der(x7)"], [1], 1, 1), (["der(der(x7))"], [1], 1, 1), (["der(der(der(x7)))"], [1], 1, 1), (["der(x2d)"], [1], 1, 1)]) end @testset "... Test free flying mass" begin FreeFlyingMass = Model( m =1.0, f=[1.0,2.0,3.0], r = Var(init=[0.1, 0.2, 0.3]), v = Var(init=[-0.1, -0.2, -0.3]), equations = :[ v = der(r) m*der(v) = f] ) freeFlyingMass = @instantiateModel(FreeFlyingMass) checkStateSelection(freeFlyingMass, ["v", "r"], []) end #= @testset "... Test sliding mass" begin SlidingMass = Model( m = 1.0, c = 1e4, d = 10.0, g = 9.81, n = [1.0, 1.0, 1.0], s = Var(init=1.0), equations = :[ r = n*s v = der(r) m*der(v) = f + m*g*[0,-1,0] + u 0 = n*f u = -(c*s + d*der(s))*n] ) slidingMass = @instantiateModel(SlidingMass, logStateSelection=true) @show slidingMass.equationInfo.linearEquations #checkStateSelection(slidingMass, ["x6"], [(["x5"], [1], 1, 1)]) end =# end using Unitful include("../models/AllModels.jl") #= Gear = Model( flange_a = Flange, flange_b = Flange, gear = IdealGear_withSupport | Map(ratio = 105.0), fixed = Fixed, spring = Spring | Map(c=5.84e5u"N*m/rad"), damper1 = Damper | Map(d=500.0u"N*m*s/rad"), damper2 = Damper | Map(d=100.0u"N*m*s/rad"), connect = :[ (flange_a , gear.flange_a) (fixed.flange , gear.support, damper2.flange_b) (gear.flange_b, damper2.flange_a, spring.flange_a, damper1.flange_a) (flange_b , spring.flange_b, damper1.flange_b)] ) Drive = Model( inertia1 = Inertia, inertia2 = Inertia, gear = Gear, equations = :[ inertia1.flange_a.tau = 0u"N*m" inertia2.flange_b.tau = 0u"N*m"], connect = :[ (inertia1.flange_b, gear.flange_a), (gear.flange_b , inertia2.flange_a) ] ) =# # Linear 1D rotational damper AbsoluteDamper = Model( flange = Flange, d = 1.0u"N*m*s/rad", # (info = "Damping constant"), phi = Var(init=0.0u"rad"), equation = :[ phi = flange.phi w = der(phi) flange.tau = d * w ] ) Drive = Model( inertia = Inertia, damper = AbsoluteDamper, equations = :[ inertia.flange_a.tau = 0u"N*m"], connect = :[ (inertia.flange_b, damper.flange)] ) Drive2 = Drive | Map(damper = Map(phi=Var(init=1.0u"rad"))) drive1 = @instantiateModel(Drive) drive2 = @instantiateModel(Drive2) using DifferentialEquations simulate!(drive1, Tsit5(), stopTime = 4.0) println("Next simulate! should result in an error:\n") simulate!(drive2, Tsit5(), stopTime = 4.0) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
1787
module TestStateSpace using TinyModia using ModiaPlot using DifferentialEquations include("$(TinyModia.path)/models/Blocks.jl") # Second order system: # w = 1.0 # D = 0.1 # k = 2.0 # der(x1) = x2 # der(x2) = -w^2*x1 - 2*D*w*x2 + w^2*u # y = k*x1 SecondOrder1 = Model( w = 20.0, D = 0.1, k = 2.0, sys = StateSpace | Map(A = :([ 0 1; -w^2 -2*D*w]), B = :([0; w^2]), C = :([k 0]), D = :(zeros(1)), x = Var(init = zeros(2)) ), equations = :[sys.u = 1.0] ) secondOrder1 = @instantiateModel(SecondOrder1, unitless=true) simulate!(secondOrder1, merge=Map(D=0.3), requiredFinalStates = [0.9974089572681231, 0.011808652820321723]) plot(secondOrder1, [("sys.u", "sys.y"); "sys.x"], figure = 1) SecondOrder2 = Model( sys = StateSpace | Map( A = [ 0.0 1.0; -100.0 -12.0], B = [0; 400.0], C = [2.0 0], D = zeros(1,1), x = Var(init = zeros(2))), equations = :[sys.u = 1.0] ) secondOrder2 = @instantiateModel(SecondOrder2, unitless=true) simulate!(secondOrder2, Tsit5(), merge=Map(sys=Map(A = [0.0 1.0; -400.0 -12.0])), requiredFinalStates = [0.9974089572681231, 0.011808652820321723]) plot(secondOrder2, [("sys.u", "sys.y"); "sys.x"], figure = 2) simulate!(secondOrder2, Tsit5(), merge=Map(sys=Map(x=[1.0,1.0])), logParameters=true, logStates=true, requiredFinalStates = [1.0000295203337868, 0.0022367686372974493]) plot(secondOrder2, [("sys.u", "sys.y"); "sys.x"], figure = 3) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
1362
module TestTwoInertiasAndIdealGear using TinyModia using DifferentialEquations using ModiaPlot using Unitful TwoInertiasAndIdealGearTooManyInits = Model( J1 = 0.0025, J2 = 170, r = 105, tau_max = 1, phi1 = Var(init = 0.0), w1 = Var(init = 1.0), phi2 = Var(init = 0.5), w2 = Var(init = 0.0), equations = :[ tau = if time < 1u"s"; tau_max elseif time < 2u"s"; 0 elseif time < 3u"s"; -tau_max else 0 end, # inertia1 w1 = der(phi1), J1*der(w1) = tau - tau1, # gear phi1 = r*phi2, r*tau1 = tau2, # inertia2] w2 = der(phi2), J2*der(w2) = tau2 ] ) TwoInertiasAndIdealGear = TwoInertiasAndIdealGearTooManyInits | Map(phi1 = Var(init=nothing), w1=Var(init=nothing)) twoInertiasAndIdealGearTooManyInits = @instantiateModel(TwoInertiasAndIdealGearTooManyInits) twoInertiasAndIdealGear = @instantiateModel(TwoInertiasAndIdealGear) println("Next simulate! should result in an error:\n") simulate!(twoInertiasAndIdealGearTooManyInits, Tsit5(), stopTime = 4.0, log=true) simulate!(twoInertiasAndIdealGear, Tsit5(), stopTime = 4.0, log=false, logParameters=true, logStates=true, requiredFinalStates=[1.5628074713622309, -6.878080753044174e-5]) plot(twoInertiasAndIdealGear, ["phi2", "w2"]) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
1323
module TestTwoInertiasAndIdealGearWithMonteCarlo using TinyModia using DifferentialEquations using ModiaPlot using MonteCarloMeasurements using Distributions using Unitful # The number of particles must be the same as for FloatType const nparticles = 100 uniform(vmin,vmax) = StaticParticles(nparticles,Distributions.Uniform(vmin,vmax)) TwoInertiasAndIdealGearWithMonteCarlo = Model( J1 = 0.0025, J2 = uniform(50, 170), r = 105, tau_max = 1, phi2 = Var(init = uniform(0.5,0.55)), w2 = Var(init = 0.0), equations = :[ tau = if time < 1u"s"; tau_max elseif time < 2u"s"; 0 elseif time < 3u"s"; -tau_max else 0 end, # inertia1 w1 = der(phi1), J1*der(w1) = tau - tau1, # gear phi1 = r*phi2, r*tau1 = tau2, # inertia2 w2 = der(phi2), J2*der(w2) = tau2 ] ) twoInertiasAndIdealGearWithMonteCarlo = @instantiateModel(TwoInertiasAndIdealGearWithMonteCarlo, FloatType = StaticParticles{Float64,nparticles}) simulate!(twoInertiasAndIdealGearWithMonteCarlo, Tsit5(), stopTime = 4.0, logParameters=true, logStates=true) plot(twoInertiasAndIdealGearWithMonteCarlo, ["phi2", "w2"], MonteCarloAsArea=false) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
1086
module TestTwoInertiasAndIdealGearWithUnits using TinyModia using DifferentialEquations using ModiaPlot using Unitful TwoInertiasAndIdealGearWithUnits = Model( J1 = 0.0025u"kg*m^2", J2 = 170u"kg*m^2", r = 105, tau_max = 1u"N*m", phi2 = Var(start = 0.5u"rad"), w2 = Var(start = 0.0u"rad/s"), tau2 = Var(start = 0u"N*m"), equations = :[ tau = if time < 1u"s"; tau_max elseif time < 2u"s"; 0u"N*m" elseif time < 3u"s"; -tau_max else 0u"N*m" end, # inertia1 w1 = der(phi1), J1*der(w1) = tau - tau1, # gear phi1 = r*phi2, r*tau1 = tau2, # inertia2 w2 = der(phi2), J2*der(w2) = tau2 ] ) twoInertiasAndIdealGearWithUnits = @instantiateModel(TwoInertiasAndIdealGearWithUnits) simulate!(twoInertiasAndIdealGearWithUnits, Tsit5(), stopTime = 4.0, logParameters=true, logStates=true, requiredFinalStates=[1.5628074713622309, -6.878080753044174e-5]) plot(twoInertiasAndIdealGearWithUnits, ["phi2", "w2", "der(w2)"]) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
1255
module TestTwoInertiasAndIdealGearWithUnitsAndMonteCarlo using TinyModia using DifferentialEquations using ModiaPlot using MonteCarloMeasurements using Distributions using Unitful # The number of particles must be the same as for FloatType const nparticles = 100 uniform(vmin,vmax) = StaticParticles(nparticles,Distributions.Uniform(vmin,vmax)) TwoInertiasAndIdealGearWithUnitsAndMonteCarlo = Model( J1 = 0.0025u"kg*m^2", J2 = uniform(50.0, 170.0)u"kg*m^2", r = 105.0, tau_max = 1.0u"N*m", start = Map(phi2 = 0.5u"rad", w2 = 0.0u"rad/s", tau2 = 0.0u"N*m", tau=0.0u"N*m"), equations = :[ tau = if time < 1u"s"; tau_max elseif time < 2u"s"; 0.0u"N*m" elseif time < 3u"s"; -tau_max else 0.0u"N*m" end, # inertia1 w1 = der(phi1), J1*der(w1) = tau - tau1, # gear phi1 = r*phi2, r*tau1 = tau2, # inertia2 w2 = der(phi2), J2*der(w2) = tau2 ] ) twoInertiasAndIdealGear = @instantiateModel(TwoInertiasAndIdealGearWithUnitsAndMonteCarlo, FloatType = StaticParticles{Float64,nparticles}) simulate!(twoInertiasAndIdealGear, Tsit5(), stopTime = 4.0) plot(twoInertiasAndIdealGear, ["phi2", "w2"]) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
1039
module TestTwoInertiasAndIdealGearWithUnitsAndUncertainties using TinyModia using DifferentialEquations using ModiaPlot using Measurements using Unitful TwoInertiasAndIdealGear = Model( J1 = 0.0025u"kg*m^2", J2 = (150.0 Β± 20.0)u"kg*m^2", r = 105.0, tau_max = 1u"N*m", phi2 = Var(start = (0.5 Β± 0.05)u"rad"), w2 = Var(start = 0.0u"rad/s"), tau2 = Var(start = 0u"N*m"), equations = :[ tau = if time < 1u"s"; tau_max elseif time < 2u"s"; 0u"N*m" elseif time < 3u"s"; -tau_max else 0u"N*m" end, # inertia1 w1 = der(phi1), J1*der(w1) = tau - tau1, # gear phi1 = r*phi2, r*tau1 = tau2, # inertia2 w2 = der(phi2), J2*der(w2) = tau2 ] ) twoInertiasAndIdealGear = @instantiateModel(TwoInertiasAndIdealGear, FloatType = Measurement{Float64}) simulate!(twoInertiasAndIdealGear, Tsit5(), stopTime = 4.0, logParameters=true, logStates=true) plot(twoInertiasAndIdealGear, ["phi2", "w2", "der(w2)"]) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
2007
module TestUncertainties using TinyModia using DifferentialEquations using ModiaPlot using Measurements TestModel = Model( T = 0.2 Β± 0.02, # Cannot convert a particle distribution to a float if not all particles are the same. u0 = 10 Β± 1, # Cannot convert a particle distribution to a float if not all particles are the same. k = 1 Β± 0.1, x = Var(init = 5 Β± 0.5), v = Var(init = 1 Β± 0.1), m = 10 Β± 1, F = 20 Β± 2, equations = :[ T*der(x) = u0 y = k*x F = m * a der(v) = a # Cannot convert a particle distribution to a float if not all particles are the same. ] ) model = @instantiateModel(TestModel, FloatType = Measurement{Float64}) simulate!(model, stopTime = 1.0, log=false, requiredFinalStates = Measurements.Measurement{Float64}[54.99999999999998 Β± 7.08872343937891, 2.999999999999999 Β± 0.3]) plot(model, ["T", "x", "der(x)", "y", "a", "der(v)"], figure=1) include("../models/Electric.jl") FilterCircuit = Model( R = Resistor | Map(R = (100Β±10)u"Ξ©"), C = Capacitor | Map(C = (0.01Β±0.001)u"F", v=Var(init=(0.0Β±1.0)u"V")), V = ConstantVoltage | Map(V = (10.0Β±1.0)u"V"), ground = Ground, connect = :[ (V.p, R.p) (R.n, C.p) (C.n, V.n, ground.p) ] ) filterCircuit = @instantiateModel(FilterCircuit, FloatType=Measurements.Measurement{Float64}) simulate!(filterCircuit, Tsit5(), stopTime = 3.0, logParameters = true, logStates = true) plot(filterCircuit, ("V.v", "C.v"), figure=2) Pendulum = Model( L = (0.8Β±0.1)u"m", m = (1.0Β±0.1)u"kg", d = (0.5Β±0.05)u"N*m*s/rad", g = 9.81u"m/s^2", phi = Var(init = (pi/2Β±0.1)*u"rad"), w = Var(init = 0u"rad/s"), equations = :[ w = der(phi) 0.0 = m*L^2*der(w) + d*w + m*g*L*sin(phi) ] ) pendulum = @instantiateModel(Pendulum, FloatType=Measurements.Measurement{Float64}) simulate!(pendulum, Tsit5(), stopTime = 10.0) plot(pendulum, "phi", figure=4) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
655
module TestUnits using TinyModia using DifferentialEquations using ModiaPlot using Test using Unitful UnitTest = Model( T = 0.2u"s", u0 = 8.5u"kg", k = 1u"kg^-1", m = 10u"kg", F = 20u"N", x = Var(init = 5500.0u"g"), v = Var(init = 1u"m/s"), equations = :[ T*der(x) + x = u0 y = x z = x*u"kg^-1" F = m * a der(v) = a ] ) model = @instantiateModel(UnitTest) simulate!(model, Tsit5(), stopTime = 1.0, requiredFinalStates = [5514.9625624219525, 2.9999999999999996]) #plot(model, ["T", "x", "der(x)", "y", "a", "der(v)"]) plot(model, ["x", "der(x)", "y", "a", "der(v)"]) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
670
module TestUnitsAndUncertainites using TinyModia using DifferentialEquations using ModiaPlot using Measurements using Unitful TestModel = Model( T = (0.2 Β± 0.02)u"s", u0 = 8.5u"kg" Β± 0.85u"kg", k = (1 Β± 0.1)u"kg^-1", m = (10 Β± 1)u"kg", F = (20 Β± 2)u"N", x = Var(init = (5.5 Β± 0.55)u"kg"), v = Var(init = (1 Β± 0.1)u"m/s"), r = Var(init = 1u"m/s"), equations = :[ T*der(x) + x = u0 y = x z = x*k F = m * a der(v) = a der(r) = v ] ) model = @instantiateModel(TestModel, FloatType = Measurement{Float64}) simulate!(model, Tsit5(), stopTime = 1.0) plot(model, ["T", "x", "der(x)", "y", "a", "v", "r"]) end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
1715
module TestVar using Measurements using StaticArrays Var(;kwargs...) = (;kwargs...) Var(value; kwargs...) = (;value=value, kwargs...) #Var(args...; kwargs...) = begin println("1"); (;args..., kwargs...) end #Var(value, args...; kwargs...) = typeof(value) <: NamedTuple ? begin println("2", value, args, kwargs); (;value..., args..., kwargs...) end : begin println("3"); (;value = value, args..., kwargs...) end xar(value, args...; kwargs...) = begin @show value args kwargs merge(value, args[1], args[2], (;kwargs...)) end var(value, args...; kwargs...) = typeof(value) <: NamedTuple ? begin println("2", value, args, kwargs); value end : #merge(value, args, kwargs ) end : begin println("3"); (;value = value, args..., kwargs...) end #Var(value, args...; kwargs...) = (;value = value, args..., kwargs...) #Var(value::Union{Number, String, Expr, AbstractArray}, args...; kwargs...) = (;value = value, args..., kwargs...) #NotPair = Union{Number, String, Expr, AbstractArray} # ..., ....} #Var(value::NotPair, args...; kwargs...) = (;value = value, args..., kwargs...) Model(; kwargs...) = (; kwargs...) constant = Var(constant = true) parameter = Var(parameter = true) input = Var(input = true) output = Var(output = true) potential = Var(potential = true) flow = Var(flow = true) # --------------------------------------------------------------------- #v = Var(potential, nominal=10) #@show v v = input | output | flow | Var(min=0, nominal=10) @show v v = parameter | Var(5, min=0) @show v v = parameter | Var(5, min=0) @show v Pin = Model( v = potential | Var(nominal=10), i = flow ) @show Pin v2 = Var(2.0) @show v2 v3 = Var(2.0 Β± 0.1) @show v3 v4 = Var(SVector(1.0,2.0,3.0)) @show v4 end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
3273
module TestVar using Measurements using StaticArrays using Unitful struct nnnVar var::NamedTuple Var(; kwargs...) = new((; kwargs...) ) end struct Model model::NamedTuple Model(; kwargs...) = new((; kwargs...) ) end struct Map map::NamedTuple Map(; kwargs...) = new((; kwargs...) ) end Var(;kwargs...) = (;kwargs...) Var(value; kwargs...) = (; value=value, kwargs...) #Var(args...; kwargs...) = begin println("1"); (;args..., kwargs...) end #Var(value, args...; kwargs...) = typeof(value) <: NamedTuple ? begin println("2", value, args, kwargs); (;value..., args..., kwargs...) end : begin println("3"); (;value = value, args..., kwargs...) end xar(value, args...; kwargs...) = begin @show value args kwargs merge(value, args[1], args[2], (;kwargs...)) end var(value, args...; kwargs...) = typeof(value) <: NamedTuple ? begin println("2", value, args, kwargs); value end : #merge(value, args, kwargs ) end : begin println("3"); (;value = value, args..., kwargs...) end #Var(value, args...; kwargs...) = (;value = value, args..., kwargs...) #Var(value::Union{Number, String, Expr, AbstractArray}, args...; kwargs...) = (;value = value, args..., kwargs...) #NotPair = Union{Number, String, Expr, AbstractArray} # ..., ....} #Var(value::NotPair, args...; kwargs...) = (;value = value, args..., kwargs...) Model(; kwargs...) = (; kwargs...) constant = Var(constant = true) parameter = Var(parameter = true) input = Var(input = true) output = Var(output = true) potential = Var(potential = true) flow = Var(flow = true) range(min, max) = Var(min=min, max=max) recursiveMerge(x, ::Nothing) = x recursiveMerge(x, y) = y recursiveMerge(x::Expr, y::Expr) = begin dump(x); dump(y); Expr(x.head, x.args..., y.args...) end recursiveMerge(x::Expr, y::Tuple) = begin x = copy(x); xargs = x.args; xargs[y[2]] = y[3]; Expr(x.head, xargs...) end function recursiveMerge(nt1::NamedTuple, nt2::NamedTuple) all_keys = union(keys(nt1), keys(nt2)) gen = Base.Generator(all_keys) do key v1 = get(nt1, key, nothing) v2 = get(nt2, key, nothing) key => recursiveMerge(v1, v2) end return Var(; gen...) end Base.:|(m::Model, n::Model) = recursiveMerge(m.model, n.model) Base.:|(m::Model, n::Map) = recursiveMerge(m.model, n.map) Base.:|(m, n::Map) = recursiveMerge(m, n.map) Base.:|(m, n) = if !(typeof(n) <: NamedTuple); recursiveMerge(m, (; value=n)) else recursiveMerge(n, (value=m,)) end #Base.:|(m::Model, n::Model) = (:MergeModel, m.model, n.model) #Base.:|(m::Model, n::Map) = (:MergeMap, m.model, n.map) #Base.:|(m, n::Map) = (:MergeMap, m, n.map) #Base.:|(m::Var, n::Var) = (:MergeModel, m.var, n.var) # --------------------------------------------------------------------- #v = Var(potential, nominal=10) #@show v v1 = input | output | flow | Var(min=0, nominal=10) @show v1 v2 = parameter | 5 @show v2 v3 = 10u"m/s" | parameter @show v3 v4 = parameter | 5.5 | Var(min=0) @show v4 v5 = parameter | Var(5, min=0) @show v5 Pin = Model( v = potential | Var(nominal=10), i = flow ) @show Pin v6 = Var(2.0) @show v6 v7 = Var(2.0 Β± 0.1) @show v7 v8 = Var(SVector(1.0,2.0,3.0)) @show v8 v9 = v4 | Var(parameter=false) @show v9 v10 = v4 | Var(parameter=nothing) @show v10 v11 = v4 | range(0,10) @show v11 end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
2309
module TestVar using Measurements using StaticArrays using Unitful struct Var var::NamedTuple Var(; kwargs...) = new((; kwargs...) ) end struct Model model::NamedTuple Model(; kwargs...) = new((; kwargs...) ) end struct Map map::NamedTuple Map(; kwargs...) = new((; kwargs...) ) end #Var(;kwargs...) = (;kwargs...) Var(value; kwargs...) = Var(;value=value, kwargs...) Model(; kwargs...) = (; kwargs...) constant = Var(constant = true) parameter = Var(parameter = true) input = Var(input = true) output = Var(output = true) potential = Var(potential = true) flow = Var(flow = true) recursiveMerge(x, ::Nothing) = x recursiveMerge(x, y) = y recursiveMerge(x::Expr, y::Expr) = begin dump(x); dump(y); Expr(x.head, x.args..., y.args...) end recursiveMerge(x::Expr, y::Tuple) = begin x = copy(x); xargs = x.args; xargs[y[2]] = y[3]; Expr(x.head, xargs...) end function recursiveMerge(nt1::NamedTuple, nt2::NamedTuple) all_keys = union(keys(nt1), keys(nt2)) gen = Base.Generator(all_keys) do key v1 = get(nt1, key, nothing) v2 = get(nt2, key, nothing) key => recursiveMerge(v1, v2) end return Var(; gen...) end Base.:|(m::Model, n::Model) = recursiveMerge(m.model, n.model) Base.:|(m::Model, n::Map) = recursiveMerge(m.model, n.map) Base.:|(m, n::Map) = recursiveMerge(m, n.map) Base.:|(m::Var, n::Var) = Var(recursiveMerge(m.var, n.var)) Base.:|(m, n) = if !(typeof(n) <: Var); recursiveMerge(m, Var(value=n)) else recursiveMerge(n, Var(value=m)) end #Base.:|(m::Model, n::Model) = (:MergeModel, m.model, n.model) #Base.:|(m::Model, n::Map) = (:MergeMap, m.model, n.map) #Base.:|(m, n::Map) = (:MergeMap, m, n.map) #Base.:|(m::Var, n::Var) = (:MergeModel, m.var, n.var) # --------------------------------------------------------------------- #v = Var(potential, nominal=10) #@show v v1 = input | output | flow | Var(min=0, nominal=10) @show v1 v2 = parameter | 5 @show v2 v3 = 10u"m/s" | parameter @show v3 v4 = parameter | 5.5 | Var(min=0) @show v4 v5 = parameter | Var(5, min=0) @show v5 Pin = Model( v = potential | Var(nominal=10), i = flow ) @show Pin v6 = Var(2.0) @show v6 v7 = Var(2.0 Β± 0.1) @show v7 v8 = Var(SVector(1.0,2.0,3.0)) @show v8 v9 = v4 | Var(parameter=false) @show v9 v10 = v4 | Var(parameter=nothing) @show v10 end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
1935
module TestVariables using TinyModia using ModiaPlot using Measurements using StaticArrays using Test @testset "... Test variable declarations" begin v1 = input | output | flow | Var(min=0, nominal=10, init=5) @test v1 == (class = :Var, input = true, output = true, flow = true, min = 0, nominal = 10, init = 5) v2 = parameter | 5 | Var(info="v2 info") @test v2 == (class = :Var, parameter = true, value = 5, info = "v2 info") v3 = "string value" | parameter | info"v3 info" @test v3 == (class = :Var, parameter = true, value = "string value", info = "v3 info") v4 = parameter | 5.5u"m/s" | Var(min=0) @test v4 == (class = :Var, parameter = true, value = 5.5u"m*s^-1", min = 0) v5 = parameter | Var(5, min=0) @test v5 == (class = :Var, parameter = true, value = 5, min = 0) Pin = Model( v = potential | Var(nominal=10), i = flow ) @test Pin == (class = :Model, v = (class = :Var, potential = true, nominal = 10), i = (class = :Var, flow = true,)) v6 = Var(2.0) @test v6 == (class = :Var, value = 2.0,) v7 = Var(2.0 Β± 0.1) @test v7 == (class = :Var, value = 2.0 Β± 0.1,) v8 = Var(SVector(1.0, 2.0, 3.0)) @test v8 == (class = :Var, value = [1.0, 2.0, 3.0],) v9 = v4 | Var(parameter=false) @test v9 == (class = :Var, parameter = false, value = 5.5u"m*s^-1", min = 0) v10 = v4 | Var(parameter=nothing) @test v10 == (class = :Var, value = 5.5u"m*s^-1", min = 0) v11 = v4 | interval(1,10) @test v11 == (class = :Var, parameter = true, value = 5.5u"m*s^-1", min = 1, max = 10) TestVar1 = Model( p = parameter | -1 | info"A parameter", s = parameter | "string value" | info"A string parameter", x = Var(init=0.1), y = Var(start=0.1), # Not used equations = :[ der(x) = p*x+1 ] ) #@showModel TestVar1 model = @instantiateModel(TestVar1, log=false, logCode=false) simulate!(model, merge=Map(p=-2, x=0.2), requiredFinalStates = [0.4593994150057028]) # x.init is not changed plot(model, "x") end end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
code
918
module Runtests using Test @testset "Test TinyModia with simulation" begin include("TestVariables.jl") include("TestFirstOrder.jl") include("TestFirstOrder2.jl") include("TestStateSelection.jl") include("TestFilterCircuit.jl") include("TestUnits.jl") include("TestUncertainties.jl") include("TestUnitsAndUncertainties.jl") include("TestTwoInertiasAndIdealGear.jl") include("TestTwoInertiasAndIdealGearWithUnits.jl") include("TestTwoInertiasAndIdealGearWithUnitsAndUncertainties.jl") include("TestTwoInertiasAndIdealGearWithMonteCarlo.jl") #include("TestTwoInertiasAndIdealGearWithUnitsAndMonteCarlo.jl") # MonteCarlo and Unitful not yet supported include("TestSingularLRRL.jl") include("TestStateSpace.jl") include("TestHeatTransfer.jl") include("../examples/runexamples.jl") end end
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
docs
2028
# TinyModia [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://modiasim.github.io/TinyModia.jl/stable/index.html) [![The MIT License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/ModiaSim/TinyModia.jl/blob/master/LICENSE.md) TinyModia is a minimalistic environment in form of a Julia package to model and simulate physical systems (electrical, mechanical, thermo-dynamical, etc.) described by differential and algebraic equations. A user defines a model on a high level with model components (like a mechanical body, an electrical resistance, or a pipe) that are physically connected together. A model component is constructed by "expression = expression" equations. The defined model is symbolically processed (for example, equations might be analytically differentiated) with algorithms from package [ModiaBase.jl](https://github.com/ModiaSim/ModiaBase.jl). From the transformed model a Julia function is generated that is used to simulate the model with integrators from [DifferentialEquations.jl](https://github.com/SciML/DifferentialEquations.jl). The basic type of the floating point variables in the generated function is usually `Float64`, but can be set to any type `T<:AbstractFloat`, for example `Float32, DoubleFloat, Measurement{Float64}, StaticParticles{Float64,100}`. ## Installation The package is registered and is installed with (Julia >= 1.5 is required): ```julia julia> ]add TinyModia ``` It is recommended to also add the following packages, in order that all tests and examples can be executed in your standard environment: ```julia julia> ]add ModiaPlot, Unitful, DifferentialEquations, Measurements, MonteCarloMeasurements, Distributions ``` ## Main Developers - [Hilding Elmqvist](mailto:[email protected]), [Mogram](http://www.mogram.net/). - [Martin Otter](https://rmc.dlr.de/sr/en/staff/martin.otter/), [DLR - Institute of System Dynamics and Control](https://www.dlr.de/sr/en). License: MIT (expat)
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
docs
1199
# Functions ```@meta CurrentModule = TinyModia ``` ## Instantiation ```@docs @instantiateModel instantiateModel ``` ## Simulation ```@docs simulate! ``` ## Plotting The results of a simulation of a model `instantiatedModel` can be visualized with function [ModiaPlot.plot](https://modiasim.github.io/ModiaPlot.jl/stable/Functions.html#ModiaPlot.plot) that produces line plots of the result time series. A variable `a.b.c` is identified by a String key `"a.b.c"`. The legends/labels of the plots are automatically constructed by the names and units of the variables. Example: ```julia using ModiaPlot instantiatedModel = @instantiatedModel(...) simulate!(instantiatedModel, ...) plot(instantiatedModel, [ ("phi", "r") ("phi", "phi2", "w"); ("w", "w2", "phi2") "w" ], heading="Matrix of plots") ``` generates the following plot: ![Matrix-of-Plots](../resources/images/matrix-of-plots.png) The underlying line plot is generated by [GLMakie](https://github.com/JuliaPlots/GLMakie.jl). ## Inquiries ```@meta CurrentModule = TinyModia ``` ```@docs get_result get_lastValue ``` ```@meta CurrentModule = ModiaPlot ``` ```@docs hasSignal getNames ```
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
docs
400
# Internal This chapter documents internal functions that are typically only for use of the developers of package TinyModia. ## Code Generation This section provides functions to **generate Julia code** of the transformed equations. ```@meta CurrentModule = TinyModia ``` ```@docs SimulationModel generate_getDerivatives! init! outputs! addToResult! getFloatType baseType measurementToString ```
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
docs
37966
# TinyModia Tutorial # 1 Introduction This tutorial gives an overview of package [TinyModia](https://github.com/ModiaSim/TinyModia.jl) to construct component-based and equation-based models with the **TinyModia language** on a high level, symbolically transforming these models into ODEs (Ordinary Differential Equations in state space form), simulating them and plotting result variables. # 2 Modeling ## 2.1 Equation oriented models A simple differential equation with $x(t) \in \R$ ```math T \cdot \frac{dx}{dt} + x = 2; \;\;\; x(t_0) = 0.5 ``` can be defined with a constructor `Model` taking a comma separated list of name/value pairs: ```julia using TinyModia SimpleModel = Model( T = 0.2, x = Var(init=0.5), equation = :[T * der(x) + x = 2], ) ``` The model consist of a definition of a parameter `T` with default value 0.2, constructor `Var` with an `init` key is used to define the initial condition 0.5 of the state `x`, and one equation. Equations can have a Julia expression on both sides of the equal sign and are given as a *quoted* array expression `:[ ]` assigned to a unique identifier such as `equation`. The equation will be symbolically solved for the derivative `der(x)` before simulation, so the following equation will be used for the integration: ```math \frac{dx}{dt} = (2 - x) / T ``` A low pass filter block with input `u` and output `y` ```math \begin{aligned} T \cdot \frac{dx}{dt} + x &= u\\ y &= x \\ x(t_0) &= 0 \end{aligned} ``` can be defined as: ```julia using ModiaBase LowPassFilter = Model( T = 0.2, u = input, y = output | Var(:x), x = Var(init=0), equation = :[T * der(x) + x = u], ) ``` The symbols `input` and `output` refer to predefined variable constructors to define the input and output variables. If an equation has just a unique variable in the left hand side, `y`, the right hand side can be given as a quoted expression in a Var-constructor `Var(:x)` after the `output` constructor combined with the merge operator, `|`, see below. ## 2.2 Merging models It is possible to combine models by merging. If we want to change the model to become a highpass filter, an alternative output equation ```math y = -x + u ``` is defined in an anonymous model `Model( y = :(-x + u) )`. This anonymous model is merged with `LowPassFilter` using the merge operator `|`: ```julia HighPassFilter = LowPassFilter | Model( y = :(-x + u) ) ``` The merging implies that the `output` property of `y` is kept, but the binding expression is changed from `:x` to `:(-x + u)`. In general, recursive merging is desired and TinyModia provides a `mergeModels` function for that (see appendix [A.3 MergeModels algorithm](@ref)). This function is invoked as a binary operator `|` (also used for merge in Python). Note, that the order of the arguments/operands are important. Generalizing the block to have two outputs for both low and high pass filtering would be done as follows: ```julia LowAndHighPassFilter = LowPassFilter | Model( y = nothing, low = output | Var(:x), high = output | Var(:(-x + u)), ) ``` The equation for `y` is removed by "assigning" `nothing` and two variables are defined and declared as outputs. Model `LowAndHighPassFilter` represents the following equations: ```math \begin{aligned} T \cdot \frac{dx}{dt} + x &= u\\ low &= x \\ high &= -x + u \\ x(t_0) &= 0 \end{aligned} ``` By turning on logging of merging `setLogMerge(true)`, the translator gives the log: ```julia Adding: value = :(x) Adding: value = :(-x + u) Deleting: y Adding: low = Var( output = true, value = :(x), ), Adding: high = Var( output = true, value = :(-x + u), ), ``` The resulting model is pretty printed by calling `@showModel(LowAndHighPassFilter)`: ```julia LowAndHighPassFilter = Model( T = 0.2, u = Var( input = true, ), x = Var( init = 0.0 V, ), equations = :([T * der(x) + x = u]), low = Var( output = true, value = :(x), ), high = Var( output = true, value = :(-x + u), ), ), ``` ## 2.3 Functions and tables In order to test an input/output block as defined in the previous section, an input needs to be defined. This can be made by adding an equation for `u`. Assume we want `u` to be sinousoidial with an increasing frequency: ```julia using Unitful TestLowAndHighPassFilter = LowAndHighPassFilter | Model( u = :(sin( (time+1u"s")*u"1/s/s" * time)*u"V"), x = Var(init=0.2u"V") ) ``` `time` is a reserved name for the independent variable. It has unit `s` for seconds. The Julia package [Unitful](https://painterqubits.github.io/Unitful.jl/stable/) provides a means for defining units and managing unit inference. Definition of units is done with a string macro `u"..."`. In this case, the input signal was given unit Volt. The state x must then also have consistent unit, that is Volt. If the model equations contain systems of simultaneous equations, then approximate guess values, optionally with units, must be given `start`: `i = Var(start=0.0u"A")`. The input signal can also be defined by interpolation in a table: ```julia using Interpolations table = CubicSplineInterpolation(0:0.5:2.0, [0.0, 0.7, 2.0, 1.8, 1.2]) TestLowAndHighPassFilter2 = TestLowAndHighPassFilter | Map(u = :(table(time*u"1/s"))*u"V" ``` A function cannot return more as one variable and a function cannot modify one of its arguments: ``` equations = :[ (y1, y1) = fc1(u1,u2) # Error: Two return arguments fc2!(u,y) # Error: Not known that fc2! computes y println("This is a test") # Fine ] ``` The first issue can be fixed by rewriting the function call: ``` equations = :[ v = fc1(u1,u2) y1 = v[1] y2 = v[2] ] ``` ## 2.4 Hierarchical modeling Sofar, the composition of models have resulted in named tuples with values being numeric values or quoted expressions. Hierarchical models are obtained if the values themself are named tuples. A model with two filters can, for example, be defined as follows: ```julia TwoFilters = ( high = HighPassFilter, low = LowPassFilter, ) ``` Note, that the previous definitions of HighPassFilter and LowPassFilter was used instead of making the defintions inline. A band pass filter is a series connection of a high pass filter and a low pass filter and can be described as: ```julia BandPassFilter = ( u = input, y = output, high = HighPassFilter | Map(T=0.5, x=Var(init=0.1u"V")), low = LowPassFilter | Map(x=Var(init=0.2u"V")), equations = :[ high.u = u, low.u = high.y, y = low.y] ) ``` A new input have been defined which is propagated to `high.u`. The series connection itself is obtained by the equation `low.u = high.y`. Note, that dot-notation is allowed in equations. The input and output for the BandPassFilter when using the same input definition as for the TestLowPassFilter is shown below: ![Band Pass Filter Plot](../resources/images/BandPassFilterPlot.png) The above examples are available in file `SimpleFilters.jl`. ## 2.5 Physically oriented modeling Sofar, only signal flow modeling has been used, i.e. input/output blocks coupled with equations between outputs and inputs. For object oriented modeling more high level constructs are neccessary. Coupling is then acausal and involves potentials such as electric potential, positions, pressure, etc. and flows such as electric current, forces and torques and mass flow rate. ### 2.5.1 Connectors Models which contain any flow variable, i.e. a variable having an attribute `flow=true`, are considered connectors. Connectors must have equal number of flow and potential variables, i.e. variables having an attribute `potential=true`, and have matching array sizes. Connectors may not have any equations. An example of an electrical connector with potential (in Volt) and current (in Ampere) is shown below. ```julia Pin = Model( v = potential, i = flow ) ``` `potential` is a shortcut for `Var(potential=true)` and similarly for `flow`. ### 2.5.2 Components Components are declared in a similar ways as blocks. However, the interfaces between components are defined using connector instances. An electrical resistor can be descibed as follows: ```julia Resistor = Model( R = 1.0u"Ξ©", p = Pin, n = Pin, equations = :[ 0 = p.i + n.i v = p.v - n.v i = p.i R*i = v ] ) ``` ### 2.5.3 Inheritance Various physical components sometimes share common properties. One mechanism to handle this is to use inheritance. In TinyModia, merging is used. Electrical components such as resistors, capacitors and inductors are categorized as oneports which have two pins. Common properties are: constraint on currents at the pins and definitions of voltage over the component and current through the component. ```julia OnePort = Model( p = Pin, n = Pin, partialEquations = :[ 0 = p.i + n.i v = p.v - n.v i = p.i ] ) ``` Having such a OnePort definition makes it convenient to define electrical component models by merging OnePort with specific parameter definitions with default values and equations: ```julia Resistor = OnePort | Model( R = 1.0u"Ξ©", equation = :[ R*i = v ], ) Capacitor = OnePort | Model( C = 1.0u"F", v=Map(init=0.0u"V"), equation = :[ C*der(v) = i ] ) Inductor = OnePort | Model( L = 1.0u"H", i=Map(init=0.0u"A"), equation = :[ L*der(i) = v ] ) ConstantVoltage = OnePort | Model( V = 1.0u"V", equation = :[ v = V ] ) ``` The merged `Resistor` is shown below: ```julia Resistor = Model( p = Model( v = Var( potential = true, ), i = Var( flow = true, ), ), n = Model( v = Var( potential = true, ), i = Var( flow = true, ), ), partialEquations = :([v = p.v - n.v; 0 = p.i + n.i; i = p.i]), R = 1.0 Ξ©, equations = :([R * i = v]), ), ``` ### 2.5.4 Connections Connections are described as an array of tuples listing the connectors that are connected: ```julia ( <connect reference 1>, <connect reference 2>, ... ) ``` A connect reference has either the form 'connect instance name' or 'component instance name'.'connect instance name' with 'connect instance name' being either a connector instance, input or output variable. Examples ```julia connect = :[ (V.p, R1.p) (R1.n, p) (C1.n, V.n, R2.p) ... ] ``` For connectors, all the potentials of the connectors in the same connect tuple are set equal and the sum of all incoming flows to the model are set equal to the sum of the flows into sub-components. ### 2.5.5 Connected models Having the above electrical component models, enables defining a filter ![Filter Circuit](../resources/images/Filter.png) by instanciating components, setting parameters and defining connections. ```julia Filter = ( R = Resistor | Map(R=0.5u"Ξ©"), C = Capacitor | Map(C=2.0u"F"), V = ConstantVoltage | Map(V=10.0u"V"), connect = :[ (V.p, R.p) (R.n, C.p) (C.n, V.n) ] ) ``` The connect tuples are translated to: ```julia V.p.v = R.p.v 0 = V.p.i + R.p.i R.n.v = C.p.v 0 = R.n.i + C.p.i C.n.v = V.n.v 0 = C.n.i + V.n.i ``` ### 2.5.6 Parameter propagation Hierarchical modification of parameters is powerful but sometimes a bit inconvenient. It is also possible to propagate parameters intoduced on a high level down in the hierarchy. The following Filter model defines three parameters, `r`, `c` and `v`. The `r` parameter is used to set the resistance of the resistor R: `Map(R=:r)`. ```julia Filter2 = Model( r = 2.0u"Ξ©", c = 1.0u"F", v = 10u"V", R = Resistor | Map(R=:r), C = Capacitor | Map(C=:c), V = ConstantVoltage | Map(V=:v), connect = :[ (V.p, R.p) (R.n, C.p) (C.n, V.n) ] ) ``` Two separate filters can then be defined with: ```julia TwoFilters = Model( f1 = Filter | Map( r = 10.0, c = 2.0), f2 = Filter ) ``` ### 2.5.7 Redeclarations It is possible to reuse a particular model topology by redeclaring the model of particular components. For example, changing the filter `f1` to a voltage divider by changing C from a Capacitor to a Resistor. A predefined model `Redeclare` is used for this purpose. ```julia VoltageDividerAndFilter = TwoFilters | Map(f1 = Map(C = Redeclare | Resistor | Map(R = 20.0))) ``` By using `Redeclare`, a new model based on a Resistor is used for `C` and the usual merge semantics with the previously defined model of `C` is not used. The above examples are available in file `FilterCircuit.jl`. ### 2.5.8 Drive train example A larger example that utilizes most of the previously described features of TinyModia is available as `$(TinyModia.path)/examples/ServoSystem.jl`. This is a textual (TinyModia) representation of a Modelica model ![ServoSystem](../resources/images/ServoSystem.png) and demonstrates how to build up a hierarchical, multi-domain model consisting of a servo-system with a load, where the servo-system consists of an electric motor with a current and speed controller, as well with a more detailed model of a gearbox. ## 2.6 Arrays Model parameters and variables can be arrays. For example a linear state space system with $\boldsymbol{x}(t) \in \R^{n_x}, \boldsymbol{u}(t) \in \R^{n_u}, \boldsymbol{y}(t) \in \R^{n_y}, \boldsymbol{A} \in \R^{n_x \times n_x}, \boldsymbol{B} \in \R^{n_x \times n_u}, \boldsymbol{C} \in \R^{n_y \times n_x}, \boldsymbol{D} \in \R^{n_y \times n_u}$ ```math \begin{aligned} \frac{d\boldsymbol{x}}{dt} &= \boldsymbol{A} \cdot \boldsymbol{x} + \boldsymbol{B} \cdot \boldsymbol{u}\\ \boldsymbol{y} &= \boldsymbol{C} \cdot \boldsymbol{x} + \boldsymbol{D} \cdot \boldsymbol{u} \end{aligned} ``` can be defined as: ```julia StateSpace = Model( A = fill(0.0,0,0), B = fill(0.0,0,0), C = fill(0.0,0,0), D = fill(0.0,0,0), u = input, y = output, x = Var(init = zeros(0)), equations = :[ der(x) = A*x + B*u y = C*x + D*u ] ) ``` and used as: ```julia col(args...) = hvcat(1, args...) # Construct a column matrix from a vector SecondOrder = Model( w = 20.0, D = 0.1, k = 2.0, sys = StateSpace | Map(A = :([ 0 1; -w^2 -2*D*w]), B = :(col([0; w^2])), C = :([k 0]), D = :(zeros(1,1)), x = Var(init = zeros(2)) ), equations = :[sys.u = [1.0]] ) ``` Variables `sys.u` and `sys.y` are vectors with one element each. Note, `[0; w^2]` is a vector in Julia and not a column matrix (see the discussion [here](https://discourse.julialang.org/t/construct-a-2-d-column-array/30617)). In order that `B` is defined as column matrix, the function `col(..)` is used. Array equations remain array equations during symbolic transformation and in the generated code, so the code is both compact and efficient. In order that this is reasonably possible, the definition of an array cannot be split in different statements: ```julia equations = :[ # error, vector v is not defined as one symbol m1*der(v[1]) = 2.0 m2*der(v[2]) = 3.0 ] ``` If scalar equations are needed in which arrays are used, then the arrays have to be first defined and then elements can be used. ```julia v = Var(init=zeros(2)), equations = :[ a = der(v) a1 = a[1] a2 = a[2] m1*a1 = 2.0 m2*a2 = 3.0 ] ``` ## 2.7 Model libraries TinyModia provides a small set of pre-defined model components in directory `$(TinyModia.path)/models`: - `AllModels.jl` - Include all model libraries - `Blocks.jl` - Input/output control blocks - `ELectric.jl` - Electric component models - `HeatTransfer.jl` - 1D heat transfer component models - `Rotational.jl` - 1D rotational, mechanical component models The circuit of section [2.5.5 Connected models](@ref) can be for example constructed with these libraries in the following way: ```julia using TinyModia include("$(TinyModia.path)/models/AllModels.jl") FilterCircuit = Model( R = Resistor | Map(R=0.5u"Ξ©"), C = Capacitor | Map(C=2.0u"F", v=Var(init=0.1u"V")), V = ConstantVoltage | Map(V=10.0u"V"), ground = Ground, connect = :[ (V.p, R.p) (R.n, C.p) (C.n, V.n, ground.p) ] ) filterCircuit = @instantiateModel(FilterCircuit) ``` It is planned to support a much larger set of predefined model components in the future. # 3 Simulation A particular model is instantiated, simulated and results plotted with the commands: ```julia using ModiaBase using ModiaPlot filter = @instantiateModel(Filter) simulate!(filter, stopTime=10.0) plot(filter, "y", figure=1) ``` ## 3.1 Instantiating The `@instantiateModel` macro takes additional arguments: ```julia modelInstance = @instantiateModel(model; FloatType = Float64, aliasReduction=true, unitless=false, log=false, logModel=false, logDetails=false, logStateSelection=false, logCode=false, logExecution=false, logTiming=false) ``` The macro performs structural and symbolic transformations, generates a function for calculation of derivatives suitable for use with [DifferentialEquations.jl](https://github.com/SciML/DifferentialEquations.jl) and returns `modelInstance::SimulationModel` that can be used in other functions, for example to simulate or plot results: * `model`: model (declarations and equations). * `FloatType`: Variable type for floating point numbers (see below). * `aliasReduction`: Perform alias elimination and remove singularities. * `unitless`: Remove units (useful while debugging models and needed for MonteCarloMeasurements). * `log`: Log the different phases of translation. * `logModel`: Log the variables and equations of the model. * `logDetails`: Log internal data during the different phases of translation. * `logStateSelection`: Log details during state selection. * `logCode`: Log the generated code. * `logExecution`: Log the execution of the generated code (useful for finding unit bugs). * `logTiming`: Log timing of different phases. * `return modelInstance prepared for simulation` ## 3.2 Simulating The [`simulate!`](@ref) function performs one simulation with [DifferentialEquations.jl](https://github.com/SciML/DifferentialEquations.jl) using the default integrator that this package automatically selects and stores the result in `modelInstance`. It is also possible to specify the integrator as second argument of `simulate!`: ```julia using ModiaBase using DifferentialEquations using ModiaPlot filter = @instantiateModel(Filter) simulate!(filter, Tsit5(), stopTime=10.0, merge=Map(T=0.5, x=0.8)) plot(filter, ["y", "x"], figure=1) ``` Integrator `DifferentialEquations.Tsit5` is an [adaptive Runge-Kutta method of order 5/4 from Tsitouras](https://www.sciencedirect.com/science/article/pii/S0898122111004706). There are > 100 ODE integrators provided. For details, see [here](https://docs.sciml.ai/stable/solvers/ode_solve/). Parameters and init/start values can be changed with the `merge` keyword. The effect is the same, as if the filter would have been instantiated with: ```julia filter = @instantiateModel(Filter | Map(T=0.5, x=Var(init=0.8)) ``` Note, with the `merge` keyword in simulate!, init/start values are directly given as a value (`x = 0.8`) and are not defined with `Var(..)`. Function `simulate!` returns the value that is returned by function [DifferentialEquations.solve](https://diffeq.sciml.ai/stable/features/ensemble/#Solving-the-Problem). Functions of `DifferentialEquations` that operate on this return argument can therefore also be used on the return argument of `simulate!`. ## 3.3 Plotting The [plot](https://modiasim.github.io/ModiaPlot.jl/stable/Functions.html#ModiaPlot.plot) function generates a line plot with [GLMakie](https://github.com/JuliaPlots/GLMakie.jl). A short overview of the most important plot commands is given in section section [Plotting](@ref) ## 3.4 State selection (DAEs) TinyModia has a sophisticated symbolic engine to transform high index DAEs (Differential Algebraic Equations) automatically to ODEs (Ordinary Differential Equations in state space form). During the transformation, equations might be analytically differentiated and code might be generated to solve linear equation systems numerically during simulation. The current engine **cannot** transform a DAE to ODE form, if the **DAE contains nonlinear algebraic equations**. There is an (internal) prototype available to transform nearly any DAE system to a special index 1 DAE system that can be solved with standard DAE integrators. After a clean-up phase, this engine will be made publicly available at some time in the future. Some of the algorithms used in TinyModia are described in [Otter and Elmqvist (2017)](https://modelica.org/events/modelica2017/proceedings/html/submissions/ecp17132565_OtterElmqvist.pdf). Some algorithms are not yet published. Usually, the symbolic engine is only visible to the modeler, when the model has errors, or when the number of ODE states is less than the number of DAE states. The latter case is discussed in this section. The following object diagram shows two rotational inertias that are connected by an ideal gear. One inertia is actuated with a sinusoidal torque: ![TwoInertiasAndIdealGear](../resources/images/TwoInertiasAndIdealGear.png) In order to most easily understand the issues, this model is provided in a compact, "flattened" form: ```julia TwoInertiasAndIdealGearTooManyInits = Model( J1 = 50, J2 = 100, ratio = 2, f = 3, # Hz phi1 = Var(init = 0.0), # Absolute angle of inertia1 w1 = Var(init = 0.0), # Absolute angular velocity of inertia1 phi2 = Var(init = 0.0), # Absolute angle of inertia2 w2 = Var(init = 0.0), # Absolute angular velocity of inertia2 equations = :[ tau = 2.0*sin(2*3.14*f*time/u"s") # inertia1 w1 = der(phi1) J1*der(w1) = tau - tau1 # ideal gear phi1 = ratio*phi2 ratio*tau1 = tau2 # inertia2 w2 = der(phi2) J2*der(w2) = tau2 ] ) drive1 = @instantiateModel(TwoInertiasAndIdealGearTooManyInits) simulate!(drive1, Tsit5(), stopTime = 1.0, logStates=true) plot(drive1, [("phi1", "phi2"), ("w1", "w2")]) ``` The option `logStates=true` results in the following output: ``` ... Simulate model TwoInertiasAndIdealGearTooManyInits β”‚ # β”‚ state β”‚ init β”‚ unit β”‚ nominal β”‚ β”œβ”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 1 β”‚ phi2 β”‚ 0.0 β”‚ β”‚ NaN β”‚ β”‚ 2 β”‚ w2 β”‚ 0.0 β”‚ β”‚ NaN β”‚ ``` This model translates and simulates without problems. Changing the init-value of `w2` to `1.0` and resimulating: ```julia simulate!(drive1, Tsit5(), stopTime = 1.0, logStates=true, merge = Map(w2=1.0)) ``` results in the following error: ``` ... Simulate model TwoInertiasAndIdealGearTooManyInits β”‚ # β”‚ state β”‚ init β”‚ unit β”‚ nominal β”‚ β”œβ”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 1 β”‚ phi2 β”‚ 0.0 β”‚ β”‚ NaN β”‚ β”‚ 2 β”‚ w2 β”‚ 1.0 β”‚ β”‚ NaN β”‚ Error from simulate!: The following variables are explicitly solved for, have init-values defined and after initialization the init-values are not respected (remove the init-values in the model or change them to start-values): β”‚ # β”‚ name β”‚ beforeInit β”‚ afterInit β”‚ β”œβ”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 1 β”‚ w1 β”‚ 0.0 β”‚ 2.0 β”‚ ``` The issue is the following: Every variable that is used in the `der` operator is a **potential ODE state**. When an `init` value is defined for such a variable, then TinyModia either utilizes this initial condition (so the variable has this value after initialization), or an error is triggered, as in the example above. The model contains the equation: ```julia phi1 = ratio*phi2 ``` So the potential ODE states `phi1` and `phi2` are constrained, and only one of them can be selected as ODE state, and the other variable is computed from this equation. Since parameter `ratio` can be changed before simulation is started, it can be changed also to a value of `ratio = 0`. Therefore, only when `phi2` is selected as ODE state, `phi1` can be uniquely computed from this equation. If `phi1` would be selected as ODE state, then a division by zero would occur, if `ratio = 0`, since `phi2 = phi1/ratio`. For this reason, TinyModia selects `phi2` as ODE state. This means the **`init` value of `phi1` has no effect**. This is uncritical, as long as initialization computes this init value from the constraint equation above, as done in the example above. When differentiating the equation above: ```julia der(phi1) = ratio*der(phi2) # differentiated constraint equation w1 = der(phi1) w2 = der(phi2) ``` it becomes obvious, that there is also a hidden constraint equation for `w1, w2`: ```julia w1 = ratio*w2 # hidden constraint equation ``` Again, TinyModia selects `w2` as ODE state, and ignores the `init` value of `w1`. In the second simulation, the `init` value of `w1` (= 0.0) is no longer consistent to the init value of `w2` (= 1.0). Therefore, an error occurs. The remedy is to remove the `init` values of `phi1, w1` from the model: ```julia drive2 = @instantiateModel(TwoInertiasAndIdealGearTooManyInits | Map(phi1 = Var(init=nothing), w1 = Var(init=nothing)) ) simulate!(drive2, Tsit5(), stopTime = 1.0, logStates=true, merge = Map(w2=1.0)) ``` and simulation is successful! TinyModia tries to respect `init` values during symbolic transformation. In cases as above, this is not possible and the reported issue occurs. In some cases, it might not be obvious, why TinyModia selects a particular variable as an ODE state. You can get more information by setting `logStateSelection=true`: ```julia drive1 = @instantiateModel(TwoInertiasAndIdealGearTooManyInits, logStateSelection=true) ``` # 4 Floating point types The types of the floating point numbers in a TinyModia model can be parameterized with argument `FloatType` of macro [`@instantiateModel`](@ref): ```julia filter = @instantiateModel(Filter; FloatType = Float64) ``` By default, a floating point number has type `Float64`. !!! warning Using another floating point type requires that a DifferentialEquations.jl integrator is used that is implemented in **native Julia**. An integrator that interfaces an integrator implemented in C (such as `CVODE_BDF()` the popular Sundials BDF method), cannot be used. ## 4.1 Lower and higher precision In principal, any floating point type of Julia (so any type that is derived from `AbstractFloat`) can be used in the model and the integrators. Examples | Type | Precision | Package | Usage | |:---------|:----------|:-------------|:------------------ | | Float32 | 7 digits | built-in | Embedded system | | Float64 | 16 digits | built-in | Offline simulation | | Double64 | 30 digits | [DoubleFloats](https://github.com/JuliaMath/DoubleFloats.jl) | High precision needed | | BigFloat | arbitrary | [built-in](https://docs.julialang.org/en/v1/manual/integers-and-floating-point-numbers/#Arbitrary-Precision-Arithmetic) | Very high precision needed (very slow) | - The `Float32` type might be used to test the execution and numerics of a model that shall later run on an embedded system target (there is no automatic way, yet, to translate a TinyModia model to `C`). - `Double64` is a type that is constructed from two Float64 types. The execution is much faster as the comparable Julia built-in type [BigFloat](https://docs.julialang.org/en/v1/manual/integers-and-floating-point-numbers/#Arbitrary-Precision-Arithmetic-1) when set to 128 bit precision. The `Double64` type might be used, when simulation with `Float64` fails due to numerical reasons (for example the model is very sensitive, or equation systems are close to singularity) or when very stringent relative tolerances are needed, for example relative tolerance = 1e-15 as needed for some space applications. In the following example, simulation is performed with a `Float32` floating point type used for model and integrator and utilizing a Runge-Kutta integrator of order 4 with a fixed step size of 0.01 s: ```julia filter = @instantiateModel(Filter, FloatType = Float32) simulate!(filter, RK4(), adaptive=false, stopTime=10.0, interval=0.01) ``` ## 4.2 Uncertainties Package [Measurements](https://github.com/JuliaPhysics/Measurements.jl) provides a floating point type designed for error propagation. A floating point number is defined with a nominal value and an uncertainty: ```julia using Measurements m1 = 2.1 Β± 0.4 m2 = 2*m1 # 4.2 Β± 0.8 m3 = m2 - m1 # 2.1 Β± 0.4 ``` The statement `m1 = 2.1 Β± 0.4` defines that `m1` has a nominal value of `2.1` with a [standard deviation](https://en.wikipedia.org/wiki/Standard_deviation) of `0.4`. This means that the probability is about 95 % that the value of `m1` is in the range `1.3 .. 2.9`. Package [Measurements](https://github.com/JuliaPhysics/Measurements.jl) computes the error propagation with first-order theory (so this is typically an **approximation**) by computing the partial derivatives of all variables with respect to all source error definitions and computing the propagated error with this information. The benefit is that the error bounds are typically reasonably propagated and the computation is reasonably fast. The drawback is that it is an approximation and will be not correct, if the uncertainty is too large and/or the signals change too quickly (for example are discontinuous). The following model defines a simple pendulum where a mass point is attached via a rod and a revolute joint to the environment. It is described by the equations ```math \begin{aligned} \frac{d\varphi}{dt} &= \omega \\ 0 &= m \cdot L^2 \cdot \frac{d\omega}{dt} + d \cdot \omega + m \cdot g \cdot L \cdot sin(\varphi) \end{aligned} ``` where ``\varphi`` is the rotation angle, ``\omega`` the angular velocity, ``m`` the mass, ``L`` the rod length, ``d`` a damping constant and ``g`` the gravity constant. This model can be defined with the commands: ```julia Pendulum = Model( L = (0.8Β±0.1)u"m", m = (1.0Β±0.1)u"kg", d = (0.5Β±0.05)u"N*m*s/rad", g = 9.81u"m/s^2", phi = Var(init = (pi/2Β±0.1)*u"rad"), w = Var(init = 0u"rad/s"), equations = :[ w = der(phi) 0.0 = m*L^2*der(w) + d*w + m*g*L*sin(phi) ] ) pendulum = @instantiateModel(Pendulum, FloatType=Measurements.Measurement{Float64}) simulate!(pendulum, Tsit5(), stopTime = 10.0) plot(pendulum, "phi") ``` and simulates the pendulum with uncertain parameter and init values and results in the following plot: ![PendulumWithUncertaintities](../resources/images/PendulumWithUncertaintities.png) The area around the nominal value of a variable characterizes the standard deviation. ## 4.3 Monte-Carlo Simulation The Julia package [MonteCarloMeasurements.jl](https://github.com/baggepinnen/MonteCarloMeasurements.jl) provides calculations with particles. A value can be defined with a distribution of say 2000 values randomly chosen according to a desired distribution and then all calculations are performed with 2000 values at the same time (corresponds to 2000 simulations that are carried out). In the example below, a modest form of 100 particles (100 simulations) with Uniform distributions of some parameters and init values are defined that correspond roughly to the definition with uncertainties of the previous section (but using uniform instead for normal distributions): ```julia using TinyModia using DifferentialEquations using ModiaPlot using MonteCarloMeasurements using Distributions using Unitful const nparticles = 100 uniform(vmin,vmax) = StaticParticles(nparticles,Distributions.Uniform(vmin,vmax)) Pendulum = Model( L = uniform(0.6, 1.0), m = uniform(0.8, 1.2), d = uniform(0.4, 0.6), g = 9.81, phi = Var(init = uniform(pi/2-0.2, pi/2+0.2)), w = Var(init = 0), equations = :[ w = der(phi) 0.0 = m*L^2*der(w) + d*w + m*g*L*sin(phi) ] ) pendulum = @instantiateModel(Pendulum,FloatType=StaticParticles{Float64,nparticles}) simulate!(pendulum, Tsit5(), stopTime = 10.0) plot(pendulum, "phi", MonteCarloAsArea=false) ``` The simulation result is shown in the next figure: ![PendulumWithMonteCarlo.png](../resources/images/PendulumWithMonteCarlo.png) Since plot option `MonteCarloAsArea=false` is used, all 100 simulations are shown in the plot, together with the mean value of all simulations. The default plot behavior is to show the mean value and the area in which all simulations are contained (this is useful, if there are much more simulations, because GLMakie crashes when there are too many curves in a diagram). There are currently a few restrictions, in particular units are not yet supported in the combination of TinyModia and MonteCarloMeasurements, so units are not defined in the model above. # Appendix A ## A.1 Var constructor The constructor `Var(..)` defines attributes of a variable with key/value pairs. In column 1 the keys are shown. The default is that none of the keys are defined (meaning `key = nothing`). Most of the keys are also provided as predefined constants as shown in column 2 and 3. These constants can be used as shortcuts: | Var key | ShortCut | Shortcut value | Description | |:---------- |:----------|:----------------------|:---------------------------------------------------| | parameter | parameter | Var(parameter = true) | If true, value is fixed during simulation | | input | input | Var(input = true) | If true, input signal | | output | output | Var(output = true) | If true, output signal | | potential | potential | Var(potential = true) | If true, potential variable | | flow | flow | Var(flow = true) | If true, flow variable | | init | -- | -- | Initial value of ODE state (defines unit and size) | | start | -- | -- | Start value of variable (defines unit and size) | Example: ```julia v = output | Var(start = zeros(3)u"N*m") # Same as: v = Var(output = true, start = zeros(3)u"N*m") ``` An attribute can be removed by using a value of `nothing`. Example: ```julia System1 = Model(v = input | Var(init = 1.0), ...) # System2 = Model(v = input, ...) System2 = System1 | Map(v = Var(init = nothing), ...) ``` The following attributes are also defined for constructor `Var`, but have **no effect yet**. Using `min, max, info` already now, might be useful for model libraries: | Var Key | Shortcut | Shortcut value | Description | |:--------- |:------------------|:----------------------|:---------------------------------| | constant | constant | Var(constant = true) | If true, value cannot be changed | | min, max | interval(a,b) | Var(min = a, max = b) | Allowed variable value range | | info | info"..." | Var(info="...") | Description | Example: ```julia v = output | interval(0.0,1.0) | Var(start = zeros(3)u"N*m") | info"An output variable" # Same as: v = Var(output = true, min = 0.0, max = 1.0, # start = zeros(3)u"N*m", info = "An output variable") ``` ## A.2 Named tuples and quoted expressions The fundamental mechanism for defining models in TinyModia are named tuples which is a list of key/value pairs enclosed in parentheses: ```julia julia> S=(p=5, q=10) (p = 5, q = 10) julia> typeof(S) NamedTuple{(:p, :q),Tuple{Int64,Int64}} ``` Named tuples are conceptually similar to dictionaries (Dict), but the constructor syntax is simpler. Note that if only one key/value pair is given, a comma must preceed the final parentheses: `(p = 5, )`. It is also possible to define named tuples using a keyword argument list, i.e. a list starting with a semi-colon: `z=(;p=5)`. The values can also be a quoted expression, i.e. an expression enclosed in `:( )`, an array of quoted expressions encloded in `:[ ]` or just a quoted symbol, `:x`. This mechanism is used to encode equations and expressions of the model which needs to be manipulated before the model can be simulated. Julia defines a very useful merge operation between named tuples (and dictionaries): ```julia julia> T=(q=100, r=200) (q = 100, r = 200) julia> merge(S, T) (p = 5, q = 100, r = 200) ``` If a key already exists `q` in the first named tuple, it's value is overwritten otherwise it's added, `r`. Such a merge semantics allows for unification of parameter modifications and inheritance as will be demonstrated below. ## A.3 MergeModels algorithm The `mergeModels` algorithm is defined as follows (without logging): ```julia function mergeModels(m1::NamedTuple, m2::NamedTuple, env=Symbol()) mergedModels = OrderedDict{Symbol,Any}(pairs(m1)) # Convert the named tuple m1 to an OrderedDict for (k,v) in collect(pairs(m2)) if typeof(v) <: NamedTuple if k in keys(mergedModels) && ! (:_redeclare in keys(v)) mergedModels[k] = mergeModels(mergedModels[k], v, k) else mergedModels[k] = v end elseif v === nothing delete!(mergedModels, k) else mergedModels[k] = v end end return (; mergedModels...) # Transform OrderedDict to named tuple end |(m::NamedTuple, n::NamedTuple) = mergeModels(m, n) Redeclare = ( _redeclare = true, ) ```
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
0.7.2
0d5e2ace5bfe11eca285388d831977baa90ada47
docs
2843
# TinyModia Documentation [TinyModia](https://github.com/ModiaSim/TinyModia.jl) is a minimalistic environment in form of a Julia package to model and simulate physical systems (electrical, mechanical, thermo-dynamical, etc.) described by differential and algebraic equations. A user defines a model on a high level with model components (like a mechanical body, an electrical resistance, or a pipe) that are physically connected together. A model component is constructed by "expression = expression" equations. The defined model is symbolically processed (for example, equations might be analytically differentiated) with algorithms from package [ModiaBase.jl](https://github.com/ModiaSim/ModiaBase.jl). From the transformed model a Julia function is generated that is used to simulate the model with integrators from [DifferentialEquations.jl](https://github.com/SciML/DifferentialEquations.jl). The basic type of the floating point variables is usually `Float64`, but can be set to any type `FloatType<:AbstractFloat` via `@instantiateModel(..., FloatType = xxx)`, for example it can be set to `Float32, DoubleFloat, Measurement{Float64}, StaticParticles{Float64,100}`. ## Installation The package is registered and is installed with (Julia >= 1.5 is required): ```julia julia> ]add TinyModia ``` It is recommended to also add the following packages, in order that all tests and examples can be executed in your standard environment: ```julia julia> ]add ModiaPlot, Unitful, DifferentialEquations, Measurements, MonteCarloMeasurements, Distributions ``` ## Release Notes ### Version 0.7.2 - Missing dependency of Test package added. ### Version 0.7.1 - Variable constructor `Var(...)` introduced. For example: `v = input | Var(init = 1.2u"m")`. For details see section [A.1 Var constructor](@ref). - Functions are called in the scope where macro [`@instantiateModel`](@ref) is called. - New arguments of function [`simulate!`](@ref): - Parameter and init/start values can be changed with argument `merge`. - A simulation can be checked with argument `requiredFinalStates`. - Argument `logParameters` lists the parameter and init/start values used for the simulation. - Argument `logStates` lists the states, init, and nominal values used for the simulation. - `end` in array ranges is supported, for example `v[2:end]`. - New (small) model library `TinyModia/models/HeatTransfer.jl`. - [TinyModia Tutorial](@ref) improved. - [Functions](@ref) docu improved. ### Version 0.7.0 - Initial version, based on code developed for Modia 0.6 and ModiaMath 0.6. ## Main developers - [Hilding Elmqvist](mailto:[email protected]), [Mogram](http://www.mogram.net/). - [Martin Otter](https://rmc.dlr.de/sr/en/staff/martin.otter/), [DLR - Institute of System Dynamics and Control](https://www.dlr.de/sr/en).
TinyModia
https://github.com/ModiaSim/TinyModia.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
779
using CmdStan, Documenter DOC_ROOT = rel_path_cmdstan("..", "docs") DocDir = joinpath(DOC_ROOT, "src") page_list = Array{Pair{String, Any}, 1}(); append!(page_list, [Pair("Introduction", "INTRO.md")]); append!(page_list, [Pair("Installation", "INSTALLATION.md")]); append!(page_list, [Pair("Walkthrough", "WALKTHROUGH.md")]); append!(page_list, [Pair("Versions", "VERSIONS.md")]); append!(page_list, [Pair("Functions", "index.md")]); makedocs( format = Documenter.HTML(prettyurls = haskey(ENV, "GITHUB_ACTIONS")), root = DOC_ROOT, modules = Module[], sitename = "CmdStan.jl", authors = "Rob J Goedman", pages = page_list, ) deploydocs( root = DOC_ROOT, repo = "github.com/StanJulia/CmdStan.jl.git", devbranch = "master", push_preview = true, )
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
12366
######### ARM Ch03: kid score example ########### using CmdStan, Test, Statistics ProjDir = dirname(@__FILE__) cd(ProjDir) do kid = " data { int<lower=0> N; vector[N] kid_score; vector[N] mom_hs; vector[N] mom_iq; } parameters { vector[3] beta; real<lower=0> sigma; } model { kid_score ~ normal(beta[1] + beta[2] * mom_hs + beta[3] * mom_iq, sigma); } " kiddata = Dict("N" => 434, "kid_score" => [65, 98, 85, 83, 115, 98, 69, 106, 102, 95, 91, 58, 84, 78, 102, 110, 102, 99, 105, 101, 102, 115, 100, 87, 99, 96, 72, 78, 77, 98, 69, 130, 109, 106, 92, 100, 107, 86, 90, 110, 107, 113, 65, 102, 103, 111, 42, 100, 67, 92, 100, 110, 56, 107, 97, 56, 95, 78, 76, 86, 79, 81, 79, 79, 56, 52, 63, 80, 87, 88, 92, 100, 94, 117, 102, 107, 99, 73, 56, 78, 94, 110, 109, 86, 92, 91, 123, 102, 105, 114, 96, 66, 104, 108, 84, 83, 83, 92, 109, 95, 93, 114, 106, 87, 65, 95, 61, 73, 112, 113, 49, 105, 122, 96, 97, 94, 117, 136, 85, 116, 106, 99, 94, 89, 119, 112, 104, 92, 86, 69, 45, 57, 94, 104, 89, 144, 52, 102, 106, 98, 97, 94, 111, 100, 105, 90, 98, 121, 106, 121, 102, 64, 99, 81, 69, 84, 104, 104, 107, 88, 67, 103, 94, 109, 94, 98, 102, 104, 114, 87, 102, 77, 109, 94, 93, 86, 97, 97, 88, 103, 87, 87, 90, 65, 111, 109, 87, 58, 87, 113, 64, 78, 97, 95, 75, 91, 99, 108, 95, 100, 85, 97, 108, 90, 100, 82, 94, 95, 119, 98, 100, 112, 136, 122, 126, 116, 98, 94, 93, 90, 70, 110, 104, 83, 99, 81, 104, 109, 113, 95, 74, 81, 89, 93, 102, 95, 85, 97, 92, 78, 104, 120, 83, 105, 68, 104, 80, 120, 94, 81, 101, 61, 68, 110, 89, 98, 113, 50, 57, 86, 83, 106, 106, 104, 78, 99, 91, 40, 42, 69, 84, 58, 42, 72, 80, 58, 52, 101, 63, 73, 68, 60, 69, 73, 75, 20, 56, 49, 71, 46, 54, 54, 44, 74, 58, 46, 76, 43, 60, 58, 89, 43, 94, 88, 79, 87, 46, 95, 92, 42, 62, 52, 101, 97, 85, 98, 94, 90, 72, 92, 75, 83, 64, 101, 82, 77, 101, 50, 90, 103, 96, 50, 47, 73, 62, 77, 64, 52, 61, 86, 41, 83, 64, 83, 116, 100, 42, 74, 76, 92, 98, 96, 67, 84, 111, 41, 68, 107, 82, 89, 83, 73, 74, 94, 58, 76, 61, 38, 100, 84, 99, 86, 94, 90, 50, 112, 58, 87, 76, 68, 110, 88, 87, 54, 49, 56, 79, 82, 80, 60, 102, 87, 42, 119, 84, 86, 113, 72, 104, 94, 78, 80, 67, 104, 96, 65, 64, 95, 56, 75, 91, 106, 76, 90, 108, 86, 85, 104, 87, 41, 106, 76, 100, 89, 42, 102, 104, 59, 93, 94, 76, 50, 88, 70], "mom_hs" => [1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1], "mom_iq" => [121.117528602603, 89.3618817100663, 115.443164881725, 99.4496394360723, 92.7457099982118, 107.901837758501, 138.893106071162, 125.145119475328, 81.6195261789843, 95.0730686206496, 88.5769977185567, 94.8597081943671, 88.9628008509596, 114.114297012333, 100.534071915245, 120.419145591086, 114.426876891447, 111.592357580831, 133.849227208159, 97.2648010634673, 110.09680614075, 126.72399416984, 97.9115903092628, 99.9257251603133, 97.5950080521511, 121.748013460479, 98.7480786989934, 97.9152543291671, 80.3585564632336, 114.307860633927, 109.138316302971, 101.817179733939, 117.965104313227, 108.633496913048, 96.528619145464, 92.8713754661642, 95.8981342875886, 107.015457730577, 87.1970117452858, 89.3618817100663, 102.530987846246, 130.166860235388, 83.4141025980336, 125.75346623026, 85.8103765615827, 126.520072628695, 79.203048104857, 113.165907175696, 110.33138786508, 99.4092237400546, 102.425526488872, 124.900437749856, 94.8597081943671, 92.3685645501674, 101.817179733939, 79.8335329627323, 96.226139267492, 82.3554723942338, 76.5756473159814, 110.013482886319, 111.592357580831, 113.657407368227, 101.164556773121, 101.341094009698, 101.698163476419, 98.8191545781969, 93.4981963041352, 87.2938898998626, 87.316028002806, 86.2094574206895, 89.8379674343074, 121.870014908527, 127.544378629405, 109.991344783376, 90.4463141892395, 88.8949026973177, 113.046890918176, 78.0131542683097, 95.3896508777613, 83.6164421099846, 86.2462806103944, 95.3896508777613, 111.252314499127, 127.014435946011, 89.951950871924, 99.2731021994947, 81.1655785576865, 110.52128746677, 136.493846917085, 123.862011656634, 134.602392343459, 91.0989371500582, 103.269371773029, 126.287072933559, 127.544378629405, 92.4738903034255, 84.7940885713045, 100.534071915245, 108.003012055173, 78.8071449713118, 121.117528602603, 103.056011346747, 100.437193760669, 88.5548596156134, 85.3055571716597, 119.448617651507, 90.5517755466136, 96.3340383364003, 127.644920803886, 119.856558886853, 112.018920897562, 92.5143059994432, 96.023799755541, 91.4168421288192, 103.07814944969, 100.243630139074, 89.8158293313641, 115.057361749322, 96.650620593512, 105.577950778248, 97.7216907075729, 131.835771186485, 101.817179733939, 93.4981963041352, 104.026539286327, 103.708634307566, 107.368863177393, 92.5511291891481, 94.4425837627742, 93.1447908573186, 83.4141025980336, 71.037405135663, 127.66705890683, 115.687846607198, 90.9762568726337, 132.865336903467, 72.5022963925581, 100.710609151823, 132.688799666889, 98.5457391870425, 115.665708504254, 117.062799760565, 136.493846917085, 106.548478717828, 134.126306619218, 104.657024144202, 99.3785635568688, 100.437193760669, 89.5253875551931, 120.92294779354, 113.143769072753, 126.414746875437, 122.737163481443, 115.375266728083, 91.6067417305091, 88.6603209729875, 107.178963575703, 104.969604023316, 103.8630334412, 110.09680614075, 88.4543174411322, 117.032139577379, 125.656588075683, 122.601041940883, 121.049630448962, 93.1447908573186, 99.3785635568688, 123.892807443936, 113.043226898272, 115.771169861628, 114.938345491802, 93.6208765815597, 121.748013460479, 90.3494360346627, 83.4104385781293, 99.4864626257772, 113.910375471188, 97.5950080521511, 89.8158293313641, 119.584739192066, 97.3816476258686, 84.8774118257353, 102.328648334295, 99.2731021994947, 99.0750497482455, 96.9277000045708, 108.313250636032, 100.534071915245, 99.4864626257772, 113.987614356911, 92.7702011694918, 88.0298361151122, 106.111557481547, 103.232548583324, 99.295240302438, 106.742042339422, 99.1725600250135, 102.447664591815, 92.8677114462598, 116.826136045524, 85.4245734291798, 115.565166329773, 113.174564860055, 106.861058596942, 95.8302361339468, 77.1092540192799, 89.2908058308629, 112.412742040396, 110.643967744195, 109.537397162078, 107.901837758501, 104.969604023316, 107.682765778157, 109.466321282875, 133.532644951047, 128.80901236506, 101.270018130495, 87.316028002806, 118.090769781179, 120.255639745959, 90.3457720147583, 79.9046088419358, 136.577170171515, 102.425526488872, 132.688799666889, 96.2972151466954, 118.209786038699, 118.090769781179, 101.504599854825, 94.3346846938659, 84.67140829388, 86.7688663993614, 129.245933601341, 127.781042344446, 106.861058596942, 105.754488014826, 117.032139577379, 119.35173949693, 102.765569570576, 108.205351567124, 126.414746875437, 101.90050298837, 99.1562556370934, 91.8127452623644, 84.1414656104858, 84.3548260367683, 79.1197248504261, 91.4168421288192, 90.4463141892395, 79.0007085929061, 109.263981770924, 76.7521845525589, 97.5950080521511, 128.80901236506, 113.657407368227, 114.206686337254, 112.513284214877, 75.3368157031739, 81.5226480244075, 102.638886915154, 101.186694876064, 112.222842438706, 123.408064035336, 86.5665268874105, 100.116947483653, 102.328648334295, 87.9465128606813, 80.2580142887524, 80.2580142887524, 91.0767990471149, 85.5789725628141, 113.165907175696, 112.05933659358, 101.270018130495, 81.8328866052668, 81.0945026784831, 81.3290844028133, 120.609045192776, 102.447664591815, 90.9762568726337, 103.708634307566, 102.328648334295, 121.870014908527, 88.6603209729875, 90.0291897576466, 83.5331188555537, 91.9206443312728, 87.1933477253815, 80.4640178206077, 84.3180028470634, 77.7397388771553, 82.272149139803, 77.3826694104343, 89.715287156883, 79.9046088419358, 82.1531328822829, 80.2616783086568, 77.3826694104343, 82.7836177401583, 89.2074825764321, 89.088466318912, 88.9872920222396, 118.923594151005, 83.8510238343148, 84.044587455909, 105.052927277747, 107.999348035269, 97.3816476258686, 103.791957561996, 97.5950080521511, 88.6603209729875, 107.246861729345, 89.8379674343074, 108.906912304203, 100.63953327262, 118.840270896574, 95.5123311551858, 84.7719504683612, 100.747432341528, 87.0034481236916, 77.8587551346754, 85.3018931517554, 92.7702011694918, 74.8607299789328, 115.248584072661, 107.372527197298, 102.202982866342, 97.9115903092628, 96.8566241253673, 111.465674925409, 109.466321282875, 82.2500110368597, 92.7702011694918, 115.568830349677, 84.044587455909, 116.199315207553, 99.295240302438, 87.1933477253815, 76.7117688565413, 80.6985995449379, 82.4633714631422, 85.1798917037074, 93.0737149781151, 88.5769977185567, 103.056011346747, 86.8767654682698, 97.9152543291671, 120.92294779354, 91.7294220079335, 87.5072503261452, 90.4463141892395, 84.1636037134291, 96.6542846134164, 95.703553478525, 88.7682200418959, 92.1397163116164, 108.003012055173, 80.3893522505354, 99.8030448828889, 90.0291897576466, 93.9387815603207, 103.708634307566, 77.1092540192799, 117.55716307788, 79.8335329627323, 83.6164421099846, 88.731396852191, 82.7836177401583, 86.8767654682698, 88.731396852191, 92.2408906082888, 90.5517755466136, 84.1414656104858, 93.0737149781151, 85.8348677328627, 98.8559777679018, 95.5123311551858, 101.067678618544, 85.9323780096308, 82.7836177401583, 98.6647554445626, 82.1494688623785, 85.6157957525191, 79.4376298291872, 75.3368157031739, 80.8921631665322, 115.771169861628, 97.1591040033394, 80.8921631665322, 79.505527982829, 98.0121324837439, 108.866496608185, 80.6985995449379, 100.747432341528, 91.0989371500582, 82.9859572521092, 89.715287156883, 131.010705519546, 124.514634617453, 91.6104057504134, 92.9903917236843, 91.8838211415678, 88.6909811561733, 126.093509311965, 84.9853108946437, 82.9859572521092, 101.795041630996, 100.243630139074, 110.013482886319, 88.5769977185567, 106.742042339422, 95.2921406009932, 108.313250636032, 110.33138786508, 116.829800065428, 86.6855431449306, 96.8566241253673, 90.2482617379903, 89.2908058308629, 74.2302451210575, 91.8838211415678, 96.4607209918222, 97.4037857288119, 131.533291308512, 78.2445582670783, 127.675716591188, 124.514634617453, 80.4640178206077, 74.8607299789328, 84.8774118257353, 92.9903917236843, 94.8597081943671, 96.8566241253673, 91.2533362836924], "mom_hs_new" => 1, "mom_iq_new" => 100) global stanmodel, rc, sim, sdf stanmodel = Stanmodel(name="kid", model=kid); rc, sim, cnames = stan(stanmodel, kiddata, ProjDir, CmdStanDir=CMDSTAN_HOME) if rc == 0 sdf = read_summary(stanmodel) @test sdf[sdf.parameters .== Symbol("beta[1]"), :mean][1] β‰ˆ 26.0 rtol=0.1 end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
878
######### CmdStan program example ########### using CmdStan ProjDir = @__DIR__ cd(ProjDir) do bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; observeddata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) # Preserve these variables outside cd/do block. global stanmodel, rc, samples, cnames, df stanmodel = Stanmodel(name="bernoulli", model=bernoullimodel, printsummary=false); rc, samples, cnames = stan(stanmodel, observeddata, ProjDir, CmdStanDir=CMDSTAN_HOME); if rc == 0 # Fetch cmdstan summary as a DataFrame df = read_summary(stanmodel) df |> display println() df[df.parameters .== :theta, [:mean, :ess, :r_hat]] |> display end end # cd block
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
595
#pkg"add CmdStan" using CmdStan, Statistics bm = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; data = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) sm = Stanmodel(name="bernoulli", model=bm, printsummary=false) sm |> display rc, samples, cnames = stan(sm, data; CmdStanDir=CMDSTAN_HOME) if rc == 0 nt = CmdStan.convert_a3d(samples, cnames, Val(:namedtuple)) mean(nt.theta, dims=1) |> display sdf = read_summary(sm) sdf |> display end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
872
######## CmdStan diagnose example ########### using CmdStan, Test, Statistics ProjDir = dirname(@__FILE__) cd(ProjDir) do bernoulli = " data { int<lower=0> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } " bernoullidata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) global stanmode, rc, diags, cnames stanmodel = Stanmodel( Diagnose(CmdStan.Gradient(epsilon=1e-6)), output_format=:array, name="bernoulli", model=bernoulli); rc, diags, cnames = stan(stanmodel, bernoullidata, ProjDir, CmdStanDir=CMDSTAN_HOME); if rc == 0 println() display(diags) println() tmp = diags[:error][1] println("Test round.(diags[:error], digits=6) β‰ˆ 0.0") @test round.(tmp, digits=6) β‰ˆ 0.0 end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
752
######### CmdStan program example ########### using CmdStan, Test, Statistics ProjDir = dirname(@__FILE__) cd(ProjDir) do bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } " observeddata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) global stanmodel, rc, sim stanmodel = Stanmodel(num_samples=1200, thin=2, name="bernoulli", output_format=:array, model=bernoullimodel); rc, sim, cnames = stan(stanmodel, observeddata, ProjDir, diagnostics=true, CmdStanDir=CMDSTAN_HOME); if rc == 0 @test -0.9 < round.(mean(sim[:, 8, :]), digits=2) < -0.7 end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
869
######### CmdStan program example ########### using CmdStan, Test, Statistics ProjDir = dirname(@__FILE__) cd(ProjDir) do bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } " bernoullidata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) inittheta = Dict("theta" => 0.60) global stanmodel, sdf stanmodel = Stanmodel(name="bernoulli", model=bernoullimodel, random=CmdStan.Random(seed=-1), num_warmup=1000, printsummary=false); global rc, sim rc, a3d, cnames = stan(stanmodel, bernoullidata, ProjDir, init=inittheta, CmdStanDir=CMDSTAN_HOME) if rc == 0 sdf = read_summary(stanmodel) @test sdf[sdf.parameters .== :theta, :mean][1] β‰ˆ 0.34 rtol=0.1 end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
967
######### CmdStan program example ########### using CmdStan, Test, Statistics ProjDir = dirname(@__FILE__) cd(ProjDir) do bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } " bernoullidata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) inittheta = [Dict("theta" => 0.6), Dict("theta" => 0.4), Dict("theta" => 0.2), Dict("theta" => 0.1)] global stanmodel stanmodel = Stanmodel(name="bernoulli2", model=bernoullimodel, output_format=:array, num_warmup=1000, random=CmdStan.Random(seed=-1)); global rc, sim rc, sim, cnames = stan(stanmodel, bernoullidata, ProjDir, init=inittheta, CmdStanDir=CMDSTAN_HOME, summary=false) if rc == 0 println() println("Test 0.2 <= mean(theta[1]) <= 0.5)") @test 0.2 <= round.(mean(sim[:,8,:]), digits=1) <= 0.5 end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
956
######### CmdStan program example ########### using CmdStan, Test, Statistics ProjDir = dirname(@__FILE__) cd(ProjDir) #do bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } " datatheta = rel_path_cmdstan("..", "examples", "BernoulliInitTheta", "bernoulli.data.R") inittheta = rel_path_cmdstan("..", "examples", "BernoulliInitTheta", "bernoulli.init.R") global stanmodel stanmodel = Stanmodel(name="bernoulli3", model=bernoullimodel, output_format=:array, random=CmdStan.Random(seed=-1)); global rc, sim rc, sim, cnames = stan(stanmodel, datatheta, ProjDir, init=inittheta, CmdStanDir=CMDSTAN_HOME, summary=false) if rc == 0 println() println("Test 0.2 <= mean(theta[1]) <= 0.5)") @test 0.2 <= round.(mean(sim[:,8,:]), digits=1) <= 0.5 end #end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
776
######### CmdStan program example ########### using CmdStan, NamedArrays, Test, Statistics ProjDir = dirname(@__FILE__) cd(ProjDir) do bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } " observeddata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) global stanmodel, rc, sim, cnames stanmodel = Stanmodel(num_samples=1200, thin=2, name="bernoulli", model=bernoullimodel, output_format=:namedarray); rc, sim, cnames = stan(stanmodel, observeddata, ProjDir, diagnostics=false, CmdStanDir=CMDSTAN_HOME); if rc == 0 @test round.(mean(sim[1][:, :theta]), digits=1) β‰ˆ 0.3 end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1271
######### CmdStan optimize program example ########### using CmdStan, Test, Statistics ProjDir = dirname(@__FILE__) cd(ProjDir) #do bernoulli = " data { int<lower=0> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } " bernoullidata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) global stanmodel, rc, optim, cnames stanmodel = Stanmodel(Optimize(), name="bernoulli", output_format=:array, model=bernoulli); rc, optim, cnames = stan(stanmodel, bernoullidata, ProjDir, CmdStanDir=CMDSTAN_HOME); if rc == 0 println() display(optim) println() println("Test round.(mean(optim[1][\"theta\"]), digits=1) β‰ˆ 0.3") @test round.(mean(optim["theta"]), digits=1) β‰ˆ 0.3 end # Same with saved iterations stanmodel = Stanmodel(Optimize(save_iterations=true), name="bernoulli", nchains=1,output_format=:array, model=bernoulli); rc, optim, cnames = stan(stanmodel, bernoullidata, ProjDir, CmdStanDir=CMDSTAN_HOME); if rc == 0 println() display(optim) println() println("""Test optim["theta"][end] β‰ˆ 0.3 rtol=0.1""") @test optim["theta"][end] β‰ˆ 0.3 rtol=0.1 end #end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
800
######### CmdStan program example ########### using CmdStan, Test, Statistics ProjDir = dirname(@__FILE__) cd(ProjDir) do bernoullimodel = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } " bernoullidata = Dict("N" => 1, "y" => [0]) global stanmodel, rc, sim stanmodel = Stanmodel(num_samples=1200, thin=2, name="bernoulli", output_format=:array, model=bernoullimodel); rc, sim, cnames = stan(stanmodel, bernoullidata, ProjDir, diagnostics=false, CmdStanDir=CMDSTAN_HOME); if rc == 0 println() println("Test round.(mean(theta), 1) β‰ˆ 0.3 rtol=0.1") @test round.(mean(sim[:,8,:]), digits=1) β‰ˆ 0.3 rtol=0.1 end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
749
######### CmndStan program example ########### using CmdStan, Test, Statistics ProjDir = dirname(@__FILE__) cd(ProjDir) do bernoulli = " data { int<lower=0> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } " bernoullidata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) global stanmodel, rc, chns, cnames stanmodel = Stanmodel(CmdStan.Variational(), name="bernoulli", model=bernoulli) rc, chns, cnames = stan(stanmodel, bernoullidata, ProjDir, CmdStanDir=CMDSTAN_HOME) if rc == 0 sdf = read_summary(stanmodel) @test sdf[sdf.parameters .== :theta, :mean][1] β‰ˆ 0.34 rtol=0.5 end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1227
## Binomial Example #### ## Note: Adapted from the Rate_4 example in Bayesian Cognitive Modeling ## https://github.com/stan-dev/example-models/tree/master/Bayesian_Cognitive_Modeling using CmdStan, Test, Statistics ProjDir = dirname(@__FILE__) cd(ProjDir) do binomialstanmodel = " // Inferring a Rate data { int<lower=1> n; int<lower=0> k; } parameters { real<lower=0,upper=1> theta; real<lower=0,upper=1> thetaprior; } model { // Prior Distribution for Rate Theta theta ~ beta(1, 1); thetaprior ~ beta(1, 1); // Observed Counts k ~ binomial(n, theta); } generated quantities { int<lower=0> postpredk; int<lower=0> priorpredk; postpredk <- binomial_rng(n, theta); priorpredk <- binomial_rng(n, thetaprior); } " global stanmodel, rc, sim stanmodel = Stanmodel(name="binomial", output_format=:array, model=binomialstanmodel) binomialdata = Dict("n" => 10, "k" => 5) rc, sim, cnames = stan(stanmodel, binomialdata, ProjDir, diagnostics=false, CmdStanDir=CMDSTAN_HOME) if rc == 0 println() println("Test round.(mean(theta[1]), digits=1) β‰ˆ 0.5") @test round.(mean(sim[:,8,:]), digits=1) β‰ˆ 0.5 end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
786
######### CmdStan program example ########### using CmdStan, Test, Statistics ProjDir = dirname(@__FILE__) cd(ProjDir) do binorm = " transformed data { matrix[2,2] Sigma; vector[2] mu; mu[1] <- 0.0; mu[2] <- 0.0; Sigma[1,1] <- 1.0; Sigma[2,2] <- 1.0; Sigma[1,2] <- 0.10; Sigma[2,1] <- 0.10; } parameters { vector[2] y; } model { y ~ multi_normal(mu,Sigma); } " global stanmodel, rc, sim stanmodel = Stanmodel(name="binormal", model=binorm, output_format=:array, Sample(save_warmup=false)); rc, sim, cnames = stan(stanmodel, CmdStanDir=CMDSTAN_HOME) if rc == 0 println() println("Test round.(mean(y[1]), 0) β‰ˆ 0.0") @test round.(mean(sim[:,8,:]), digits=0) β‰ˆ 0.0 end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
2410
@everywhere using Pkg @everywhere Pkg.activate(".") @everywhere using CmdStan, Distributions, Distributed, MCMCChains ProjDir = @__DIR__ @everywhere mutable struct Job name::AbstractString model::AbstractString data::Dict output_format::Symbol tmpdir::AbstractString nchains::Int num_samples::Int num_warmup::Int save_warmup::Bool delta::Float64 sm::Union{Nothing, Stanmodel} end function Job( name::AbstractString, model::AbstractString, data::Dict; output_format=:particles, tmpdir=pwd() ) nchains=4 num_samples=1000 num_warmup=1000 save_warmup=false delta=0.85 sm = Stanmodel( CmdStan.Sample( num_samples=num_samples, num_warmup=num_warmup, save_warmup=save_warmup, adapt=CmdStan.Adapt(delta=delta) ), name=name, model=model, nchains=nchains, tmpdir=tmpdir, output_format=:mcmcchains ) Job(name, model, data, output_format, tmpdir, nchains, num_samples, num_warmup, save_warmup, delta, sm) end # Assume we have 2 models, m1 & m2 m1 = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; m2 = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; # Assume we have 4 sets of data d = Vector{Dict}(undef, 4) d[1] = Dict("N" => 10, "y" => [0, 1, 0, 0, 0, 0, 0, 0, 0, 1]) d[2] = Dict("N" => 10, "y" => [0, 1, 0, 0, 0, 1, 1, 1, 0, 1]) d[3] = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) d[4] = Dict("N" => 10, "y" => [0, 1, 1, 1, 0, 1, 1, 1, 0, 1]) isdir("$(ProjDir)/tmp") && rm("$(ProjDir)/tmp", recursive=true) mkdir("$(ProjDir)/tmp") tmpdir = "$(ProjDir)/tmp/cmd" @everywhere jobs = Vector{Job}(undef, 4) jobs[1] = Job("m1.1", m1, d[1]; tmpdir=tmpdir*"1") jobs[2] = Job("m1.2", m1, d[2]; tmpdir=tmpdir*"2") jobs[3] = Job("m2.1", m2, d[3]; tmpdir=tmpdir*"3") jobs[4] = Job("m2.2", m2, d[4]; tmpdir=tmpdir*"4") @everywhere function runjob(i, jobs) p = [] rc, chn, _ = stan(jobs[i].sm, jobs[i].data) if rc == 0 push!(p, chn) println("Job $i completed") else println("Job[i] failed, adjust p indices accordingly.") end show(p) p end @time res = pmap(i -> runjob(i, jobs), 1:length(jobs)); for i in 1:length(jobs) res[i] end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
2301
# Use `julia -p auto` to activate mp. using Distributed @everywhere using CmdStan, Distributions, MCMCChains ProjDir = @__DIR__ @everywhere mutable struct Job name::AbstractString model::AbstractString data::Dict output_format::Symbol tmpdir::AbstractString nchains::Int num_samples::Int num_warmup::Int save_warmup::Bool delta::Float64 sm::Union{Nothing, Stanmodel} end function Job( name::AbstractString, model::AbstractString, data::Dict; output_format=:particles, tmpdir=pwd() ) nchains=4 num_samples=1000 num_warmup=1000 save_warmup=false delta=0.85 sm = Stanmodel( CmdStan.Sample( num_samples=num_samples, num_warmup=num_warmup, save_warmup=save_warmup, adapt=CmdStan.Adapt(delta=delta) ), name=name, model=model, nchains=nchains, tmpdir=tmpdir, output_format=:mcmcchains, printsummary=false ) Job(name, model, data, output_format, tmpdir, nchains, num_samples, num_warmup, save_warmup, delta, sm) end @everywhere M = 3 # No of models @everywhere D = 10 # No of data sets @everywhere N = 100 # No of Bernoulli trials isdir("$(ProjDir)/tmp") && rm("$(ProjDir)/tmp", recursive=true) # Assume we have M models model_template = " data { int<lower=1> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); y ~ bernoulli(theta); } "; m = repeat([model_template], M) # Assume we have D sets of data d = Vector{Dict}(undef, D) p = range(0.1, stop=0.9, length=D) for i in 1:D d[i] = Dict("N" => N, "y" => [Int(rand(Bernoulli(p[i]), 1)[1]) for j in 1:N]) end tmpdir = "$(ProjDir)/tmp" @everywhere jobs = Vector{Job}(undef, M*D) jobid = 0 for i in 1:M for j in 1:D global jobid += 1 jobs[jobid] = Job("m$(jobid)", m[i], d[j]; output_format=:mcmcchains, tmpdir=tmpdir) end end @everywhere function runjob(i, jobs) p = [] rc, chns, _ = stan(jobs[i].sm, jobs[i].data) if rc == 0 push!(p, (i, chns, jobs[i].sm)) println("Job $i completed") else println("Job $i failed.") end p end println("\nNo of jobs = $(length(jobs))\n") @time res = pmap(i -> runjob(i, jobs), 1:length(jobs)); for i in 1:length(jobs) display(mean(res[i][1][2])) end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1602
######### CmdStan batch program example ########### using CmdStan, Statistics, Test ProjDir = dirname(@__FILE__) cd(ProjDir) do dyes =" data { int BATCHES; int SAMPLES; real y[BATCHES, SAMPLES]; // vector[SAMPLES] y[BATCHES]; } parameters { real<lower=0> tau_between; real<lower=0> tau_within; real theta; real mu[BATCHES]; } transformed parameters { real sigma_between; real sigma_within; sigma_between <- 1/sqrt(tau_between); sigma_within <- 1/sqrt(tau_within); } model { theta ~ normal(0.0, 1E5); tau_between ~ gamma(.001, .001); tau_within ~ gamma(.001, .001); mu ~ normal(theta, sigma_between); for (n in 1:BATCHES) y[n] ~ normal(mu[n], sigma_within); } generated quantities { real sigmasq_between; real sigmasq_within; sigmasq_between <- 1 / tau_between; sigmasq_within <- 1 / tau_within; } " dyesdata = Dict("BATCHES" => 6, "SAMPLES" => 5, "y" => reshape([ [1545, 1540, 1595, 1445, 1595]; [1520, 1440, 1555, 1550, 1440]; [1630, 1455, 1440, 1490, 1605]; [1595, 1515, 1450, 1520, 1560]; [1510, 1465, 1635, 1480, 1580]; [1495, 1560, 1545, 1625, 1445] ], 6, 5) ) global stanmodel, rc, a3d, cnames stanmodel = Stanmodel(name="dyes", model=dyes); @time rc, a3d, cnames = stan(stanmodel, dyesdata, ProjDir, CmdStanDir=CMDSTAN_HOME) if rc == 0 sdf = read_summary(stanmodel) @test sdf[sdf.parameters .== :theta, :mean][1] β‰ˆ 1500 rtol=0.1 end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1458
######### CmdStan batch program example ########### # Note that this example needs StanMCMCChains. using CmdStan, Test ProjDir = dirname(@__FILE__) cd(ProjDir) do eightschools =" data { int<lower=0> J; // number of schools real y[J]; // estimated treatment effects real<lower=0> sigma[J]; // s.e. of effect estimates } parameters { real mu; real<lower=0> tau; real eta[J]; } transformed parameters { real theta[J]; for (j in 1:J) theta[j] <- mu + tau * eta[j]; } model { eta ~ normal(0, 1); y ~ normal(theta, sigma); } " schools8data = Dict("J" => 8, "y" => [28, 8, -3, 7, -1, 1, 18, 12], "sigma" => [15, 10, 16, 11, 9, 11, 10, 18], "tau" => 25 ) global stanmodel, rc, chn, chns, cnames, tmpdir tmpdir = mktempdir() stanmodel = Stanmodel(name="schools8", model=eightschools, tmpdir=tmpdir); rc, chn, cnames = stan(stanmodel, schools8data, ProjDir, CmdStanDir=CMDSTAN_HOME) if rc == 0 if rc == 0 sdf = read_summary(stanmodel) @test sdf[sdf.parameters .== Symbol("theta[1]"), :mean][1] β‰ˆ 11.6 rtol=0.1 # using StatsPlots if isdefined(Main, :StatsPlots) p1 = plot(chns) savefig(p1, joinpath(tmpdir, "traceplot.pdf")) df = DataFrame(chns, [:thetas]) p2 = plot(df[!, Symbol("theta[1]")]) savefig(p2, joinpath(tmpdir, "theta_1.pdf")) end end end end # cd
CmdStan
https://github.com/StanJulia/CmdStan.jl.git
[ "MIT" ]
6.6.0
6ed0a91233e7865924037b34ba17671ef1707ec5
code
1449
# Another way to include functions. # See Parse_and_Iterate_Example for the Stan way. using CmdStan, Distributions, Random ProjDir = @__DIR__ cd(ProjDir) function full_model(base_model, functions) initial_model = open(f->read(f, String), base_model) funcs = open(f->read(f, String), functions) "functions{\n$(funcs)}\n"*initial_model end function full_model(base_model, shared_functions, local_functions) initial_model = open(f->read(f, String), base_model) shared_funcs = open(f->read(f, String), shared_functions) local_funcs = open(f->read(f, String), local_functions) "functions{\n$(shared_funcs)\n$(local_funcs)}\n"*initial_model end model = full_model("bernoulli.stan", "shared_funcs.stan") stanmodel = Stanmodel(Sample(save_warmup=true, num_warmup=1000, num_samples=2000, thin=1), name="bernoulli", model=model, printsummary=false) observeddata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) rc, chn, cnames = stan(stanmodel, observeddata, ProjDir) if rc == 0 show(chn) end println("\nOn to model2\n") model2 = full_model("bernoulli2.stan", "shared_funcs.stan", "local_funcs.stan") stanmodel = Stanmodel(Sample(save_warmup=true, num_warmup=1000, num_samples=2000, thin=1), name="bernoulli2", model=model2, printsummary=false) observeddata = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]) rc, chn, cnames = stan(stanmodel, observeddata, ProjDir) if rc == 0 read_summary(stanmodel) end
CmdStan
https://github.com/StanJulia/CmdStan.jl.git