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.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
2147
#= 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 ModiaLang 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 = Var(init = fill(293.15u"K", 1)), # Temperatures at the internal 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) ] )
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
5367
""" 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 ModiaLang # 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, equations = :[ 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"), equations = :[ 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"), equations = :[ 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, equations = :[flange.tau = 0] ) # Ideal sensor to measure the absolute flange angular velocity AngleSensor = PartialAbsoluteSensor | Model(phi = output, equations = :[phi = flange.phi]) UnitlessAngleSensor = PartialAbsoluteSensor | Model(phi = output, equations = :[phi = flange.phi*u"1/rad"]) SpeedSensor = PartialAbsoluteSensor | Model(w = output, equations = :[w = der(flange.phi)]) UnitlessSpeedSensor = PartialAbsoluteSensor | Model(w = output, equations = :[w = der(flange.phi)*u"s/rad"]) #end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
2493
""" Modia module with translational component models (inspired from Modelica Standard Library). * Developer: Hilding Elmqvist, Mogram AB, Martin Otter, DLR * Copyright (c) 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 ModiaLang # Connector for 1D translational systems TranslationalFlange = Model( s = potential, # Absolute position of flange f = flow # Cut force directed into the flange ) # Flange fixed in housing at a given position FixedPosition = Model( flange = TranslationalFlange, equations = :[ flange.s = 0.0] ) # Rigid connection of two translational 1D flanges PartialRigid = Model( flange_a = TranslationalFlange, flange_b = TranslationalFlange, L = 0.0u"m", # Length of component, from left flange to right flange equations = :[ flange_a.s = s - L/2 flange_b.s = s + L/2] ) # 1D-translational mass TranslationalMass = PartialRigid | Model( flange_a = TranslationalFlange, # (info = "Left flange of mass") flange_b = TranslationalFlange, # (info = "Right flange of mass") m = 1.0u"kg", # Mass of sliding mass s = Var(init = 0.0u"m"), # Absolute position of center of component v = Var(init = 0.0u"m/s"), equations = :[ v = der(s) m*der(v) = flange_a.f + flange_b.f] ) # Partial input signal acting as external force on a flange PartialForce = Model( f = input, flange = TranslationalFlange ) # Input signal acting as external torque on a flange Force = PartialForce | Model(equations = :[flange.f = -f]) UnitlessForce = PartialForce | Model(equations = :[flange.f = -f*u"N"]) # Partial model to measure a single absolute flange variable PartialAbsoluteSensor = Model( flange = TranslationalFlange, equations = :[flange.f = 0] ) # Ideal sensor to measure the absolute flange position and velocity VelocitySensor = PartialAbsoluteSensor | Model(v = output, equations = :[v = der(flange.s)]) UnitlessVelocitySensor = PartialAbsoluteSensor | Model(v = output, equations = :[v = der(flange.s)*u"m/s"]) PositionSensor = PartialAbsoluteSensor | Model(s = output, equations = :[s = flange.s]) UnitlessPositionSensor = PartialAbsoluteSensor | Model(s = output, equations = :[s = flange.s*u"m"]) #end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
62776
# License for this file: MIT (expat) # Copyright 2020-2021, DLR Institute of System Dynamics and Control using OrderedCollections: OrderedDict, OrderedSet using DataFrames #= fieldnames(typeof(integrator)) = (:sol, :u, :du, :k, :t, :dt, :f, :p, :uprev, :uprev2, :duprev, :tprev, :alg, :dtcache, :dtchangeable, :dtpropose, :tdir, :eigen_est, :EEst, :qold, :q11, :erracc, :dtacc, :success_iter, :iter, :saveiter, :saveiter_dense, :cache, :callback_cache, :kshortsize, :force_stepfail, :last_stepfail, :just_hit_tstop, :do_error_check, :event_last_time, :vector_event_last_time, :last_event_error, :accept_step, :isout, :reeval_fsal, :u_modified, :reinitialize, :isdae, :opts, :destats, :initializealg, :fsalfirst, :fsallast) =# """ 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 Base.floatmax(::Type{MonteCarloMeasurements.Particles{T,N}}) where {T<:AbstractFloat,N} = Base.floatmax(T) Base.floatmax(::Type{MonteCarloMeasurements.StaticParticles{T,N}}) where {T<:AbstractFloat,N} = Base.floatmax(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 #= No longer needed function get_x_start!(FloatType, equationInfo, parameters) x_start = [] startIndex = 1 for xe_info in equationInfo.x_info xe_info.startIndex = startIndex # Determine init/start value in m.parameters xe_value = get_value(parameters, 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 ModiaLang.", bold=true, color=:red) return false end startIndex += xe_info.length end equationInfo.nx = startIndex - 1 # Temporarily remove units from x_start # (TODO: should first transform to the var_unit units and then remove) converted_x_start = convert(Vector{FloatType}, [stripUnit(v) for v in x_start]) # stripUnit.(x_start) does not work for MonteCarloMeasurements x_start2 = deepcopy(converted_x_start) return x_start2 end =# const BasicSimulationKeywordArguments = OrderedSet{Symbol}( [:merge, :tolerance, :startTime, :stopTime, :interval, :interp_points, :dtmax, :adaptive, :nlinearMinForDAE, :log, :logStates, :logEvents, :logProgress, :logTiming, :logParameters, :logEvaluatedParameters, :requiredFinalStates, :requiredFinalStates_rtol, :requiredFinalStates_atol, :useRecursiveFactorizationUptoSize]) const RegisteredExtraSimulateKeywordArguments = OrderedSet{Symbol}() function registerExtraSimulateKeywordArguments(keys)::Nothing for key in keys if key in BasicSimulationKeywordArguments @error "registerExtraSimulateKeywordArguments:\nKeyword $key is ignored, since standard keyword of simulate!(..) (use another keyword)\n\n" end push!(RegisteredExtraSimulateKeywordArguments, key) end return nothing end """ convertTimeVariable(TimeType, t) If `t` has a unit, it is transformed to u"s", the unit is stripped off, converted to `TimeType` and returned. Otherwise `t` is converted to `TimeType` and returned. # Example ```julia convertTimeVariable(Float32, 2.0u"hr") # = 7200.0f0 ``` """ convertTimeVariable(TimeType, t) = typeof(t) <: Unitful.AbstractQuantity ? convert(TimeType, stripUnit(t)) : convert(TimeType, t) struct SimulationOptions{FloatType,TimeType} merge::OrderedDict{Symbol,Any} tolerance::Float64 startTime::TimeType # u"s" stopTime::TimeType # u"s" interval::TimeType # u"s" desiredResultTimeUnit interp_points::Int dtmax::Float64 adaptive::Bool nlinearMinForDAE::Int log::Bool logStates::Bool logEvents::Bool logProgress::Bool logTiming::Bool logParameters::Bool logEvaluatedParameters::Bool requiredFinalStates::Union{Missing, Vector{FloatType}} requiredFinalStates_rtol::Float64 requiredFinalStates_atol::Float64 useRecursiveFactorizationUptoSize::Int extra_kwargs::OrderedDict{Symbol,Any} function SimulationOptions{FloatType,TimeType}(merge, errorMessagePrefix=""; _dummy=false, kwargs...) where {FloatType,TimeType} success = true adaptive = get(kwargs, :adaptive, true) tolerance = _dummy ? Inf : get(kwargs, :tolerance, 1e-6) if tolerance <= 0.0 printstyled(errorMessagePrefix, "tolerance (= $(tolerance)) must be > 0\n\n", bold=true, color=:red) success = false elseif tolerance < 100*eps(FloatType) && adaptive newTolerance = max(tolerance, 100*eps(FloatType)) printstyled("Warning from ModiaLang.simulate!(..):\n"* "tolerance (= $(tolerance)) is too small for FloatType = $FloatType (eps(FloatType) = $(eps(FloatType))).\n" * "tolerance changed to $newTolerance.\n\n", bold=true, color=:red) tolerance = newTolerance end startTime = convertTimeVariable(TimeType, get(kwargs, :startTime, 0.0) ) rawStopTime = get(kwargs, :stopTime, startTime) stopTime = convertTimeVariable(TimeType, rawStopTime) interval = convertTimeVariable(TimeType, get(kwargs, :interval , (stopTime - startTime)/500.0) ) dtmax = convert(Float64, get(kwargs, :dtmax, 100*getValue(interval))) desiredResultTimeUnit = unit(rawStopTime) interp_points = get(kwargs, :interp_points, 0) if interp_points < 0 printstyled(errorMessagePrefix, "interp_points (= $(interp_points)) must be > 0\n\n", bold=true, color=:red) success = false elseif interp_points == 1 # DifferentialEquations.jl crashes interp_points = 2 end nlinearMinForDAE = max(1, get(kwargs, :nlinearMinForDAE, 10)) # >= 10 adaptive = get(kwargs, :adaptive , true) log = get(kwargs, :log , false) logStates = get(kwargs, :logStates , false) logEvents = get(kwargs, :logEvents , false) logProgress = get(kwargs, :logProgress , false) logTiming = get(kwargs, :logTiming , false) logParameters = get(kwargs, :logParameters, false) logEvaluatedParameters = get(kwargs, :logEvaluatedParameters , false) requiredFinalStates = get(kwargs, :requiredFinalStates , missing) if isnothing(requiredFinalStates) requiredFinalStates = missing end requiredFinalStates_rtol = get(kwargs, :requiredFinalStates_rtol, 1e-3) requiredFinalStates_atol = get(kwargs, :requiredFinalStates_atol, 0.0) useRecursiveFactorizationUptoSize = get(kwargs, :useRecursiveFactorizationUptoSize, 0) extra_kwargs = OrderedDict{Symbol,Any}() for option in kwargs key = option.first if key in BasicSimulationKeywordArguments nothing; elseif key in RegisteredExtraSimulateKeywordArguments extra_kwargs[key] = option.second else printstyled(errorMessagePrefix, "simulate!(..., $key=$(option.second)): $key is unknown.\n\n", bold=true, color=:red) success = false end end # obj = new(isnothing(merge) ? NamedTuple() : merge, tolerance, startTime, stopTime, interval, desiredResultTimeUnit, interp_points, obj = new(ismissing(merge) || isnothing(merge) ? OrderedDict{Symbol,Any}() : merge, tolerance, startTime, stopTime, interval, desiredResultTimeUnit, interp_points, dtmax, adaptive, nlinearMinForDAE, log, logStates, logEvents, logProgress, logTiming, logParameters, logEvaluatedParameters, requiredFinalStates, requiredFinalStates_rtol, requiredFinalStates_atol, useRecursiveFactorizationUptoSize, extra_kwargs) return success ? obj : nothing end SimulationOptions{FloatType,TimeType}() where {FloatType,TimeType} = SimulationOptions{FloatType,TimeType}(OrderedDict{Symbol,Any}(); _dummy=true) end """ @enum ResultStore RESULT_VARS RESULT_X RESULT_DER_X RESULT_ZERO SimulationModel field name where result is stored: - RESULT_VARS : stored in `result_vars` - RESULT_X : stored in `result_x` (return argument of DifferentialEquations.solve(...)) - RESULT_DER_X: stored in `result_der_x` - RESULT_ZERO : value is zero """ @enum ResultStore RESULT_VARS RESULT_X RESULT_DER_X RESULT_ZERO struct ResultInfo store::ResultStore # Location where variable is stored index::Int # Index, depending on store-type # store = RESULT_VARS : result_vars[ti][index] # = RESULT_X : result_x[ti][ibeg:iend] # ibeg = equationInfo.x_info[index].startIndex # iend = ibeg + equationInfo.x_info[index].length-1 # = RESULT_DER_X: result_der_x[ti][ibeg:iend] # ibeg = equationInfo.x_info[index].startIndex # iend = ibeg + equationInfo.x_info[index].length-1 # = RESULT_ZERO : not stored (value is zero; index = 0) negate::Bool # = true, if result must be negated ResultInfo(store, index=0, negate=false) = new(store, index, negate) end struct LinearEquationsCopyInfoForDAEMode ileq::Int # Index of LinearEquations() index::Vector{Int} # Copy: leq.x[i] = dae_der_x[index[i]] # dae_residuals[index[i]] = leq.residuals[i] LinearEquationsCopyInfoForDAEMode(ileq) = new(ileq, Int[]) end """ simulationModel = SimulationModel{FloatType,TimeType}( modelModule, modelName, getDerivatives!, equationInfo, x_startValues, parameters, variableNames; 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 [`ModiaLang.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,TimeType} modelModule::Module modelName::String buildDict::OrderedDict{String,Any} timer::TimerOutputs.TimerOutput cpuFirst::UInt64 # cpu time of start of simulation cpuLast::UInt64 # Last time from time_ns() options::SimulationOptions{FloatType,TimeType} getDerivatives!::Function equationInfo::ModiaBase.EquationInfo linearEquations::Vector{ModiaBase.LinearEquations{FloatType}} eventHandler::EventHandler{FloatType,TimeType} vSolvedWithInitValuesAndUnit::OrderedDict{String,Any} # Dictionary of (names, init values with units) for all explicitly solved variables with init-values defined parameters::OrderedDict{Symbol,Any} evaluatedParameters::OrderedDict{Symbol,Any} previous::AbstractVector # previous[i] is the value of previous(...., i) nextPrevious::AbstractVector # nextPrevious[i] is the current value of the variable identified by previous(...., i) previous_names::Vector{String} # previous_names[i] is the name of previous-variable i previous_dict::OrderedDict{String,Int} # previous_dict[name] is the index of previous-variable name pre::AbstractVector nextPre::AbstractVector pre_names::Vector{String} pre_dict::OrderedDict{String,Int} hold::AbstractVector nextHold::AbstractVector hold_names::Vector{String} hold_dict::OrderedDict{String,Int} isInitial::Bool solve_leq::Bool # = true, if linear equations 0 = A*x-b shall be solved # = false, if leq.x is provided by DAE solver and leq.residuals is used by the DAE solver. odeMode::Bool # = false: copy der(x) into linear equation systems that have leq.odeMode=false and do not solve these equation systems storeResult::Bool time::TimeType nGetDerivatives::Int # Number of getDerivatives! calls nf::Int # Number of getDerivatives! calls from integrator (without zero-crossing calls) x_vec::Vector{Vector{FloatType}} # x_vec[i] holds the actual values of state vector element equationInfo.x_info[equationInfo.nxFixedLength+i] x_start::Vector{FloatType} # States x before first event iteration (before initialization) x_init::Vector{FloatType} # States x after initialization (and before integrator is started) der_x::Vector{FloatType} # Derivatives of states x or x_init odeIntegrator::Bool # = true , if ODE integrator used # = false, if DAE integrator used daeCopyInfo::Vector{LinearEquationsCopyInfoForDAEMode} # Info to efficiently copy between DAE and linear equation systems algorithmName::Union{String,Missing} # Name of integration algorithm as string (used in default-heading of plot) addEventPointsDueToDEBug::Bool # = true, if event points are explicitly stored for Sundials integrators, due to bug in DifferentialEquations # (https://github.com/SciML/Sundials.jl/issues/309) result_info::OrderedDict{String,ResultInfo} # key : Full path name of result variables # value: Storage location and index into the storage. result_vars::AbstractVector # result_vars[ti][j] is result of variable with index j at time instant ti result_x::Union{Any,Missing} # Return value of DifferentialEquations.solve(..) (is a struct) result_der_x::Vector{Vector{FloatType}} # result_der_x[ti][j] is der_x[j] at time instant ti success::Bool # = true, if after first outputs!(..) call and no error was triggered # = false, either before first outputs!(..) call or at first outputs!(..) after init!(..) and # an error was triggered and simulate!(..) should be returned with nothing. unitless::Bool # = true, if simulation is performed without units. function SimulationModel{FloatType,TimeType}(modelModule, modelName, buildDict, getDerivatives!, equationInfo, x_startValues, previousVars, preVars, holdVars, parameterDefinition, variableNames; unitless=true, nz::Int = 0, nAfter::Int = 0, vSolvedWithInitValuesAndUnit::AbstractDict = OrderedDict{String,Any}(), vEliminated::Vector{Int} = Int[], vProperty::Vector{Int} = Int[], var_name::Function = v -> nothing) where {FloatType,TimeType} # Construct result dictionary result_info = OrderedDict{String, ResultInfo}() vSolvedWithInitValuesAndUnit2 = OrderedDict{String,Any}( [(string(key),vSolvedWithInitValuesAndUnit[key]) for key in keys(vSolvedWithInitValuesAndUnit)] ) # Store x and der_x for (xe_index, xe_info) in enumerate(equationInfo.x_info) result_info[xe_info.x_name] = ResultInfo(RESULT_X , xe_index) result_info[xe_info.der_x_name] = ResultInfo(RESULT_DER_X, xe_index) end # Store variables for (i, name) in enumerate(variableNames) str_name = string(name) if !haskey(result_info, str_name) result_info[str_name] = ResultInfo(RESULT_VARS, i) end end # Store eliminated variables for v in vEliminated name = var_name(v) if ModiaBase.isZero(vProperty, v) result_info[name] = ResultInfo(RESULT_ZERO) elseif ModiaBase.isAlias(vProperty, v) name2 = var_name( ModiaBase.alias(vProperty, v) ) result_info[name] = result_info[name2] else # negated alias name2 = var_name( ModiaBase.negAlias(vProperty, v) ) info2 = result_info[name2] result_info[name] = ResultInfo(info2.store, info2.index, true) end end # Build previous-arrays previous = Vector{Any}(missing, length(previousVars)) previous_names = string.(previousVars) previous_dict = OrderedDict{String,Int}(zip(previous_names, 1:length(previousVars))) # Build pre-arrays pre = Vector{Any}(missing, length(preVars)) pre_names = string.(preVars) pre_dict = OrderedDict{String,Int}(zip(pre_names, 1:length(preVars))) # Build hold-arrays hold = Vector{Any}(missing, length(holdVars)) hold_names = string.(holdVars) hold_dict = OrderedDict{String,Int}(zip(hold_names, 1:length(holdVars))) # Construct parameter values that are copied into the code #parameterValues = [eval(p) for p in values(parameters)] #@show typeof(parameterValues) #@show parameterValues parameters = deepcopy(parameterDefinition) # Determine x_start and previous values evaluatedParameters = propagateEvaluateAndInstantiate!(FloatType, unitless, modelModule, parameters, equationInfo, previous_dict, previous, pre_dict, pre, hold_dict, hold) if isnothing(evaluatedParameters) return nothing end x_start = initialStateVector(equationInfo, FloatType) nx = length(x_start) nextPrevious = deepcopy(previous) nextPre = deepcopy(pre) nextHold = deepcopy(hold) # Provide storage for x_vec x_vec = [zeros(FloatType, equationInfo.x_info[i].length) for i in equationInfo.nxFixedLength+1:length(equationInfo.x_info)] # Construct data structure for linear equations linearEquations = ModiaBase.LinearEquations{FloatType}[] for leq in equationInfo.linearEquations push!(linearEquations, ModiaBase.LinearEquations{FloatType}(leq...)) end # Initialize execution flags eventHandler = EventHandler{FloatType,TimeType}(nz=nz, nAfter=nAfter) eventHandler.initial = true isInitial = true storeResult = false solve_leq = true nGetDerivatives = 0 nf = 0 new(modelModule, modelName, buildDict, TimerOutputs.TimerOutput(), UInt64(0), UInt64(0), SimulationOptions{FloatType,TimeType}(), getDerivatives!, equationInfo, linearEquations, eventHandler, vSolvedWithInitValuesAndUnit2, parameters, evaluatedParameters, previous, nextPrevious, previous_names, previous_dict, pre, nextPre, pre_names, pre_dict, hold, nextHold, hold_names, hold_dict, isInitial, solve_leq, true, storeResult, convert(TimeType, 0), nGetDerivatives, nf, x_vec, x_start, zeros(FloatType,nx), zeros(FloatType,nx), true, LinearEquationsCopyInfoForDAEMode[], missing, false, result_info, Tuple[], missing, Vector{FloatType}[], false, unitless) end function SimulationModel{FloatType,TimeType}(m::SimulationModel) where {FloatType,TimeType} # Construct data structure for linear equations linearEquations = ModiaBase.LinearEquations{FloatType}[] for leq in m.equationInfo.linearEquations push!(linearEquations, ModiaBase.LinearEquations{FloatType}(leq...)) end # Initialize execution flags eventHandler = EventHandler{FloatType,TimeType}() eventHandler.initial = true isInitial = true storeResult = false solve_leq = true nGetDerivatives = 0 nf = 0 nx = m.equationInfo.nx new(m.modelModule, m.modelName, deepcopy(m.buildDict), TimerOutputs.TimerOutput(), UInt64(0), UInt64(0), m.options, m.getDerivatives!, m.equationInfo, linearEquations, eventHandler, m.vSolvedWithInitValuesAndUnit, deepcopy(m.parameters), deepcopy(m.evaluatedParameters), deepcopy(m.previous), deepcopy(m.nextPrevious), m.previous_names, m.previous_dict, deepcopy(m.pre), deepcopy(m.nextPre), m.pre_names, m.pre_dict, deepcopy(m.hold), deepcopy(m.nextHold), m.hold_names, m.hold_dict, isInitial, solve_leq, true, storeResult, convert(TimeType, 0), nGetDerivatives, nf, deepcopy(m.x_vec), convert(Vector{FloatType}, m.x_start), zeros(FloatType,nx), zeros(FloatType,nx), true, LinearEquationsCopyInfoForDAEMode[], missing, false, m.result_info, Tuple[], missing, Vector{FloatType}[], false, m.unitless) end end # Default constructors SimulationModel{FloatType}(args...; kwargs...) where {FloatType} = SimulationModel{FloatType,FloatType}(args...; kwargs...) SimulationModel{Measurements.Measurement{T},}(args...; kwargs...) where {T} = SimulationModel{Measurements.Measurement{T},T}(args...; kwargs...) SimulationModel{MonteCarloMeasurements.Particles{T,N}}(args...; kwargs...) where {T,N,} = SimulationModel{MonteCarloMeasurements.Particles{T,N},T}(args...; kwargs...) SimulationModel{MonteCarloMeasurements.StaticParticles{T,N}}(args...; kwargs...) where {T,N} = SimulationModel{MonteCarloMeasurements.StaticParticles{T,N},T}(args...; kwargs...) timeType(m::SimulationModel{FloatType,TimeType}) where {FloatType,TimeType} = TimeType positive(m::SimulationModel, args...; kwargs...) = ModiaLang.positive!(m.eventHandler, args...; kwargs...) negative(m::SimulationModel, args...; kwargs...) = ModiaLang.negative!(m.eventHandler, args...; kwargs...) change( m::SimulationModel, args...; kwargs...) = ModiaLang.change!( m.eventHandler, args...; kwargs...) edge( m::SimulationModel, args...; kwargs...) = ModiaLang.edge!( m.eventHandler, args...; kwargs...) after( m::SimulationModel, args...; kwargs...) = ModiaLang.after!( m.eventHandler, args...; kwargs...) pre( m::SimulationModel, i) = m.pre[i] function emptyResult!(m::SimulationModel)::Nothing empty!(m.result_vars) empty!(m.result_der_x) m.result_x = missing return nothing end function get_xinfo(m::SimulationModel, x_index::Int)::Tuple{Int, Int, String} xinfo = m.equationInfo.x_info[x_index] ibeg = xinfo.startIndex iend = ibeg + xinfo.length-1 return (ibeg, iend, xinfo.unit) end """ v_zero = reinit(instantiatedModel, _x, j, v_new, _leqMode; v_threshold=0.01) Re-initialize state j with v_new, that is set x[i] = v_new, with i = instantiatedModel.equationInfo.x_info[j].startIndex. If v_new <= v_threshold, set x[i] to the floating point number that is closest to zero, so that x[i] > 0 and return v_zero = true. Otherwise return v_zero = false. An error is triggered if the function is not called during an event phase or if leqMode >= 0 (which means that reinit is called inside the for-loop to solve a linear equation system - this is not yet supported). # Implementation notes At the beginning of getDerivatives!(..), assignments of _x to appropriate variables are performed. Therefore, setting _x[i] afterwards via reinit, has no immediate effect on this model evaluation. With reinit, instantiatedModel.eventHandler.newEventIteration = true is set, to force a new event iteration. At the next event iteration, the new value v_new is copied from _x and therefore has then an effect. """ function reinit(m::SimulationModel, x, j, v_new, leqMode; v_threshold=0.01) if leqMode >= 0 error("reinit(..) of model ", m.modelName, " is called when solving a linear equation system (this is not supported)") elseif !isEvent(m) error("reinit(..) of model ", m.modelName, " is called outside of an event phase (this is not allowed)") end eh = m.eventHandler eh.restart = max(eh.restart, Restart) eh.newEventIteration = true i = m.equationInfo.x_info[j].startIndex if v_new <= v_threshold x[i] = nextfloat(convert(typeof(v_new), 0)) if eh.logEvents println(" State ", m.equationInfo.x_info[j].x_name, " reinitialized to ", x[i], " (reinit returns true)") end return true else x[i] = v_new if eh.logEvents println(" State ", m.equationInfo.x_info[j].x_name, " reinitialized to ", v_new, " (reinit returns false)") end return false 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,TimeType}) where {FloatType,TimeType} = 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, name::String) Return the value identified by `name` from the potentially hierarchically dictionary `obj`. If `name` is not in `obj`, the function returns `missing`. # Examples ```julia s1 = Map(a = 1, b = 2, c = 3) s2 = Map(v1 = s1, v2 = (d = 4, e = 5)) s3 = Map(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::OrderedDict, 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]) <: OrderedDict && 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) Return `Vector{String}` containing all the names present in `obj` # Examples ```julia s1 = Map(a = 1, b = 2, c = 3) s2 = Map(v1 = s1, v2 = (d = 4, e = 5)) s3 = Map(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 obj # zip(keys(obj), obj) if key != :_class name = appendName(path, key) if typeof(value) <: OrderedDict get_names!(value, names, name) else push!(names, name) end 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{FloatType,TimeType}, name::String; unit::Bool=true) where {FloatType,TimeType} if haskey(m.result_info, name) # Time varying variable stored in m.result_xxx resInfo = m.result_info[name] if ismissing(m.result_x) || length(m.result_x.t) == 0 @info "get_lastValue(model,\"$name\"): No results yet available." return nothing end if resInfo.store == RESULT_VARS value = m.result_vars[end][resInfo.index] if !unit value = stripUnit(value) end elseif resInfo.store == RESULT_X (ibeg,iend,xunit) = get_xinfo(m, resInfo.index) if ibeg==iend value = m.result_x[end][ibeg] else value = m.result_x[end][ibeg:iend] end if unit && !m.unitless && xunit != "" value = value*uparse(xunit) end elseif resInfo.store == RESULT_DER_X (ibeg,iend,xunit) = get_x_indices(m, resInfo.index) if ibeg==iend value = m.result_der_x[end][ibeg] else value = m.result_der_x[end][ibeg:iend] end if unit && !m.unitless if xunit == "" value = value/u"s" else value = value*(uparse(xunit)/u"s") end end elseif resInfo.store == RESULT_ZERO # Type, size and unit is not known (needs to be fixed) value = convert(FloatType, 0) else error("Bug in get_lastValue(...), name = $name, resInfo.store = $resInfo.store.") end if resInfo.negate value = -value end else # Parameter stored in m.evaluatedParameters value = get_value(m.evaluatedParameters, name) if ismissing(value) @info "get_lastValue: $name is not known and is ignored." return nothing; end end return value end """ get_extraSimulateKeywordArgumentsDict(instantiateModel) Return the dictionary, in which extra keyword arguments of the last `simulate!(instantiatedModel,...)` call are stored. """ get_extraSimulateKeywordArgumentsDict(m::SimulationModel) = m.options.extra_kwargs """ terminateEventIteration!(instantiatedModel) Return true, if event iteration shall be terminated and simulation started. Return false, if event iteration shall be continued. Reasons for continuing are: 1. pre != nextPre 2. positive(..), negative(..), change(..), edge(..) trigger a new iteration. 3. triggerEventAfterInitial = true Note - isInitial: When simulation shall be started, isInitial = true. When neither (1) nor (2) hold, isInitial = false and isInitial remains false for the rest of the simulation. - firstInitialOfAllSegments: When simulation shall be started, firstInitialOfAllSegments = true. After the first iteration, this flag is set to false. This flag can be used to initialize devices (e.g. renderer), that should be initialized once and not several times. - firstEventIteration: This flag is true during the first iteration at an event. - firstEventIterationDirectlyAfterInitial: This flag is true during the first iteration directly at the time event after initialization (at simulation startTime). """ function terminateEventIteration!(m::SimulationModel)::Bool h = m.eventHandler h.firstInitialOfAllSegments = false h.firstEventIteration = false h.firstEventIterationDirectlyAfterInitial = false # pre-iteration pre_iteration = false for i = 1:length(m.pre) if m.pre[i] != m.nextPre[i] if m.options.logEvents println(" ", m.pre_names[i], " changed from ", m.pre[i], " to ", m.nextPre[i]) end m.pre[i] = m.nextPre[i] pre_iteration = true end end if pre_iteration || h.newEventIteration h.newEventIteration = false return false # continue event iteration end if h.restart == Terminate || h.restart == FullRestart h.initial = false return true elseif h.triggerEventDirectlyAfterInitial h.triggerEventDirectlyAfterInitial = false if h.initial h.firstEventIterationDirectlyAfterInitial = true end h.initial = false return false # continue event iteration end h.initial = false return true end function eventIteration!(m::SimulationModel, x, t_event)::Nothing eh = m.eventHandler # Initialize event iteration initEventIteration!(eh, t_event) # Perform event iteration iter_max = 20 iter = 0 success = false eh.event = true while !success && iter <= iter_max iter += 1 #Base.invokelatest(m.getDerivatives!, m.der_x, x, m, t_event) invokelatest_getDerivatives_without_der_x!(x, m, t_event) eh.firstInitialOfAllSegments = false success = terminateEventIteration!(m) if eh.firstEventIterationDirectlyAfterInitial iter = 0 # reset iteration counter, since new event if m.options.logEvents println("\n Time event at time = ", eh.time, " s") end eh.nTimeEvents += 1 eh.nextEventTime = m.options.stopTime end end eh.event = false if !success error("Maximum number of event iterations (= $iter_max) reached") end return nothing end """ get_xNames(instantiatedModel) Return the names of the elements of the x-vector in a Vector{String}. """ get_xNames(m::SimulationModel) = ModiaBase.get_xNames(m.equationInfo) """ isInitial(instantiatedModel) Return true, if **initialization phase** of simulation. """ isInitial(m::SimulationModel) = m.eventHandler.initial initial( m::SimulationModel) = m.eventHandler.initial """ isTerminal(instantiatedModel) Return true, if **terminal phase** of simulation. """ isTerminal(m::SimulationModel) = m.eventHandler.terminal terminal( m::SimulationModel) = m.eventHandler.terminal """ isEvent(instantiatedModel) Return true, if **event phase** of simulation (including initialization). """ isEvent(m::SimulationModel) = m.eventHandler.event """ isFirstEventIteration(instantiatedModel) Return true, if **event phase** of simulation (including initialization) and during the first iteration of the event iteration. """ isFirstEventIteration(m::SimulationModel) = m.eventHandler.firstEventIteration """ isFirstEventIterationDirectlyAfterInitial(instantiatedModel) Return true, if first iteration directly after initialization where initial=true (so at the startTime of the simulation). """ isFirstEventIterationDirectlyAfterInitial(m::SimulationModel) = m.eventHandler.firstEventIterationDirectlyAfterInitial """ isAfterSimulationStart(instantiatedModel) Return true, if **after start of simulation** (returns false during initialization). """ isAfterSimulationStart(m::SimulationModel) = m.eventHandler.afterSimulationStart """ isZeroCrossing(instantiatedModel) Return true, if **event indicators (zero crossings) shall be computed**. """ isZeroCrossing(m::SimulationModel) = m.eventHandler.crossing """ storeResults(instantiatedModel) Return true, if **results shall be stored**. """ storeResults(m::SimulationModel) = m.storeResult isFirstInitialOfAllSegments(m::SimulationModel) = m.eventHandler.firstInitialOfAllSegments isTerminalOfAllSegments(m::SimulationModel) = m.eventHandler.isTerminalOfAllSegments """ setNextEvent!(instantiatedModel, nextEventTime) At an event instant, set the next time event to `nextEventTime`. """ setNextEvent!(m::SimulationModel{FloatType,TimeType}, nextEventTime) where {FloatType,TimeType} = setNextEvent!(m.eventHandler, convert(TimeType,nextEventTime)) """ tCurrent = getTime(instantiatedModel) Return current simulation time. """ getTime(m::SimulationModel) = m.time """ zStartIndex = addZeroCrossings(instantiatedModel, nz) Add nz new zero crossing functions and return the start index with respect to instantiatedModel.eventHandler.z. """ function addZeroCrossings(m::SimulationModel, nz::Int)::Int eh = m.eventHandler zStartIndex = eh.nz + 1 eh.nz += nz resize!(eh.z, eh.nz) resize!(eh.zPositive, eh.nz) return zStartIndex 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 import Printf invokelatest_getDerivatives_without_der_x!(x, m, t) = TimerOutputs.@timeit m.timer "ModiaLang getDerivatives!" begin if m.options.logProgress && m.cpuLast != UInt64(0) cpuNew = time_ns() if (cpuNew - m.cpuLast) * 1e-9 > 5.0 m.cpuLast = cpuNew Printf.@printf(" progress: integrated up to time = %.3g s (in cpu-time = %.3g s)\n", t, (cpuNew-m.cpuFirst)*1e-9) end end if length(m.x_vec) > 0 # copy vector-valued x-elements from x to m.x_vec eqInfo = m.equationInfo x_vec = m.x_vec j = 0 for i in eqInfo.nxFixedLength+1:length(eqInfo.x_info) j += 1 xe = eqInfo.x_info[i] x_vec[j] .= x[xe.startIndex:(xe.startIndex+xe.length-1)] end end empty!(m.der_x) Base.invokelatest(m.getDerivatives!, x, m, t) @assert(length(m.der_x) == m.equationInfo.nx) end invokelatest_getDerivatives!(der_x, x, m, t) = begin invokelatest_getDerivatives_without_der_x!(x, m, t) der_x .= m.der_x end """ success = init!(simulationModel) 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(simulationModel) = 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{FloatType,TimeType})::Bool where {FloatType,TimeType} emptyResult!(m) eh = m.eventHandler reinitEventHandler(eh, m.options.stopTime, m.options.logEvents) eh.firstInitialOfAllSegments = true # Apply updates from merge Map and propagate/instantiate/evaluate the resulting evaluatedParameters if length(m.options.merge) > 0 m.parameters = mergeModels(m.parameters, m.options.merge) m.evaluatedParameters = propagateEvaluateAndInstantiate!(FloatType, m.unitless, m.modelModule, m.parameters, m.equationInfo, m.previous_dict, m.previous, m.pre_dict, m.pre, m.hold_dict, m.hold) if isnothing(m.evaluatedParameters) return false end # Resize linear equation systems if dimensions of vector valued tearing variables changed resizeLinearEquations!(m, m.options.log) # Resize state vector memory m.x_start = updateEquationInfo!(m.equationInfo, FloatType) nx = length(m.x_start) resize!(m.x_init, nx) resize!(m.der_x, nx) eqInfo = m.equationInfo m.x_vec = [zeros(FloatType, eqInfo.x_info[i].length) for i in eqInfo.nxFixedLength+1:length(eqInfo.x_info)] end # Initialize auxiliary arrays for event iteration m.x_init .= 0 m.der_x .= 0 # Log parameters if m.options.logParameters parameters = m.parameters @showModel parameters end if m.options.logEvaluatedParameters evaluatedParameters = m.evaluatedParameters @showModel evaluatedParameters end if m.options.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 # Initialize model, linearEquations and compute and store all variables at the initial time if m.options.log println(" Initialization at time = ", m.options.startTime, " s") end # Perform initial event iteration m.nGetDerivatives = 0 m.nf = 0 m.isInitial = true eh.initial = 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) for i in eachindex(m.x_init) m.x_init[i] = deepcopy(m.x_start[i]) end eventIteration!(m, m.x_init, m.options.startTime) m.success = false # is set to true at the first outputs! call. eh.initial = false m.isInitial = false m.storeResult = false eh.afterSimulationStart = true return true end """ success = check_vSolvedWithInitValuesAndUnit(m::SimulationModel) Check that m.vSolvedWithInitValuesAndUnit is consistent to calculated values. If this is not the case, print an error message and return false. """ function check_vSolvedWithInitValuesAndUnit(m::SimulationModel)::Bool # Check vSolvedWithInitValuesAndUnit if length(m.vSolvedWithInitValuesAndUnit) > 0 names = String[] valuesBeforeInit = Any[] valuesAfterInit = Any[] tolerance = m.options.tolerance for (name, valueBefore) in m.vSolvedWithInitValuesAndUnit valueAfterInit = get_lastValue(m, name, unit=false) valueBeforeInit = stripUnit.(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) println("\n") return false end end return true end """ terminate!(m::SimulationModel, x, time) Terminate model. """ function terminate!(m::SimulationModel, x, t)::Nothing #println("... terminate! called at time = $t") eh = m.eventHandler eh.terminal = true invokelatest_getDerivatives_without_der_x!(x, m, t) eh.terminal = false return nothing end approxTime(t1,t2) = eps(typeof(t1)) """ 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 #println("... Store result at time = $t") if m.odeMode invokelatest_getDerivatives_without_der_x!(x, m, t) else if t==m.options.startTime m.der_x .= integrator.du # Since IDA gives an error for integrator(t, Val{1]}) at the initial time instant else integrator(m.der_x, t, Val{1}) # Compute derx end # Copy derx to linearEquations for copyInfo in m.daeCopyInfo leq = m.linearEquations[ copyInfo.ileq ] for i in 1:length(copyInfo.index) leq.x[i] = m.der_x[ copyInfo.index[i] ] end end m.solve_leq = false invokelatest_getDerivatives_without_der_x!(x, m, t) m.solve_leq = true end m.storeResult = false if !m.success m.result_x = integrator.sol m.success = check_vSolvedWithInitValuesAndUnit(m) if !m.success DifferentialEquations.terminate!(integrator) end elseif m.eventHandler.restart == Terminate DifferentialEquations.terminate!(integrator) end return nothing end #= """ affect_outputs!(integrator) DifferentialEquations PresetTimeCallback function for `SimulationModel` that is used to store results at communication points. """ function affect_outputs!(integrator)::Nothing m = integrator.p m.storeResult = true m.solve_leq = false getDerivatives!2(m.der_x, integrator.u, m, integrator.t) m.solve_leq = true m.storeResult = false if m.eventHandler.restart == Terminate DifferentialEquations.terminate!(integrator) end return nothing end =# """ derivatives!(derx, x, m, t) DifferentialEquations callback function to get the derivatives. """ derivatives!(der_x, x, m, t) = begin m.nf += 1 invokelatest_getDerivatives!(der_x, x, m, t) end """ DAEresidualsForODE!(residuals, derx, x, m, t) DifferentialEquations callback function for DAE integrator for ODE model """ function DAEresidualsForODE!(residuals, derx, x, m, t)::Nothing m.nf += 1 # Copy derx to linearEquations for copyInfo in m.daeCopyInfo leq = m.linearEquations[ copyInfo.ileq ] for i in 1:length(copyInfo.index) leq.x[i] = derx[ copyInfo.index[i] ] end end m.solve_leq = false invokelatest_getDerivatives_without_der_x!(x, m, t) m.solve_leq = true residuals .= m.der_x .- derx # Get residuals from linearEquations for copyInfo in m.daeCopyInfo leq = m.linearEquations[ copyInfo.ileq ] for i in 1:length(copyInfo.index) residuals[ copyInfo.index[i] ] = leq.residuals[i] end end return nothing end """ affectEvent!(integrator, stateEvent, eventIndex) Called when a time event (stateEvent=false) or state event (stateEvent=true) is triggered. In case of stateEvent, eventIndex is the index of the crossing function that triggered the event. """ function affectEvent!(integrator, stateEvent::Bool, eventIndex::Int)::Nothing m = integrator.p eh = m.eventHandler time = integrator.t #println("... begin affect: time = ", time, ", nextEventTime = ", eh.nextEventTime) if m.addEventPointsDueToDEBug push!(integrator.sol.t, deepcopy(integrator.t)) push!(integrator.sol.u, deepcopy(integrator.u)) end # Compute and store outputs before processing the event sol_t = integrator.sol.t sol_x = integrator.sol.u ilast = length(sol_t) for i = length(m.result_vars)+1:ilast # -1 outputs!(sol_x[i], sol_t[i], integrator) end # A better solution is needed. #if sol_t[ilast] == sol_t[ilast-1] # # Continuous time instant is present twice because "saveat" and "DiscreteCallback" occur at the same time instant # # Do not compute the model again # push!(m.result_vars , m.result_vars[end]) # push!(m.result_der_x, m.result_der_x[end]) #else # outputs!(sol_x[ilast], sol_t[ilast], integrator) #end if stateEvent # State event if eh.logEvents println("\n State event (zero-crossing) at time = ", time, " s (due to z[$eventIndex])") end eh.nStateEvents += 1 else # Time event if eh.logEvents println("\n Time event at time = ", time, " s") end eh.nTimeEvents += 1 end # Event iteration eventIteration!(m, integrator.u, time) if eh.restart == Restart || eh.restart == FullRestart eh.nRestartEvents += 1 end if eh.logEvents if eh.restart == Restart println(" restart = ", eh.restart) else printstyled(" restart = ", eh.restart, "\n", color=:red) end end # Compute outputs and store them after the event occurred if m.addEventPointsDueToDEBug push!(integrator.sol.t, deepcopy(integrator.t)) push!(integrator.sol.u, deepcopy(integrator.u)) end outputs!(integrator.u, time, integrator) if eh.restart == Terminate DifferentialEquations.terminate!(integrator) return nothing end # Adapt step size if eh.restart != NoRestart && supertype(typeof(integrator.alg)) == DifferentialEquations.OrdinaryDiffEq.OrdinaryDiffEqAdaptiveAlgorithm DifferentialEquations.auto_dt_reset!(integrator) DifferentialEquations.set_proposed_dt!(integrator, integrator.dt) end # Set next time event if abs(eh.nextEventTime - m.options.stopTime) < 1e-10 eh.nextEventTime = m.options.stopTime end #println("... end affect: time ", time,", nextEventTime = ", eh.nextEventTime) if eh.nextEventTime <= m.options.stopTime DifferentialEquations.add_tstop!(integrator, eh.nextEventTime) end return nothing end """ zeroCrossings!(z, x, t, integrator) Called by integrator to compute zero crossings """ function zeroCrossings!(z, x, t, integrator)::Nothing m = integrator.p eh = m.eventHandler eh.nZeroCrossings += 1 eh.crossing = true m.solve_leq = false # has only an effect for DAE integrators invokelatest_getDerivatives_without_der_x!(x, m, t) m.solve_leq = true eh.crossing = false for i = 1:eh.nz z[i] = eh.z[i] end #println("... t = $t, z = $z") #println("... time = ", t, ", z = ", z) return nothing end """ affectStateEvent!(integrator, event_index) Called by integrator when a state event is triggered """ affectStateEvent!(integrator, event_index) = affectEvent!(integrator, true, event_index) """ timeEventCondition!(u, t, integrator) Called by integrator to check if a time event occurred """ function timeEventCondition!(u, t, integrator)::Bool m = integrator.p eh = m.eventHandler if t >= eh.nextEventTime eh.nextEventTime = m.options.stopTime return true end return false end """ affectTimeEvent!(integrator) Called by integrator when a time event is triggered """ affectTimeEvent!(integrator) = affectEvent!(integrator, false, 0) """ leq = initLinearEquationsIteration!(m::SimulationModel, leq_index::Int) Initialize iteration over linear equations system of index `leq_index` and return a reference to it that can be used in the while-loop to construct and solve the linear equation system. """ initLinearEquationsIteration!(m::SimulationModel, leq_index::Int) = begin leq = m.linearEquations[leq_index] leq.mode = -3 return leq end """ resizeLinearEquations!(instantiatedModel) Inspect all linear equations inside the instantiatedModel and resize the internal storage, of the length of vector-valued elements of the iteration variables has changed due to changed parameter values. """ function resizeLinearEquations!(m::SimulationModel{FloatType}, log::Bool)::Nothing where {FloatType} for (i,leq) in enumerate(m.linearEquations) nx_vec = length(leq.x_names) - leq.nx_fixedLength if nx_vec > 0 j = 0 for i = leq.nx_fixedLength+1:length(leq.x_names) # Length of element is determined by start or init value xi_name = leq.x_names[i] xi_param = get_value(m.evaluatedParameters, xi_name) if ismissing(xi_param) @error "resizeLinearEquations!(instantiatedModel,$i): $xi_name is not part of the evaluated parameters." end leq.x_lengths[i] = length(xi_param) j += 1 if length(leq.x_vec[j]) != leq.x_lengths[i] if log println(" ModiaLang: Resize linear equations vector $xi_name from ", length(leq.x_vec[j]), " to ", leq.x_lengths[i] ) end resize!(leq.x_vec[j], leq.x_lengths[i]) end end nx = sum(leq.x_lengths) if length(leq.x) != nx # Resize internal arrays resize!(leq.x , nx) resize!(leq.b , nx) resize!(leq.pivots , nx) resize!(leq.residuals, nx) leq.A = zeros(FloatType,nx,nx) leq.useRecursiveFactorization = nx <= leq.useRecursiveFactorizationUptoSize end end end return nothing end """ addToResult!(simulationModel, der_x, 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_vars , variableValues) push!(m.result_der_x, deepcopy(m.der_x)) 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 - pre:Vector{Symbol}: pre-variable names - `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, previousVars, preVars, holdVars, functionName::Symbol; pre::Vector{Symbol} = 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 == "_dummy_x" && x_info[1].der_x_name == "der(_dummy_x)" # Explicitly solved pure algebraic variables. Introduce dummy equation push!(code_der_x, :( ModiaBase.appendVariable!(_m.der_x, -_x[1]) )) else i1 = 1 for i in 1:equationInfo.nxFixedLength xe = x_info[i] x_name = xe.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 xe.scalar # x-element is a scalar if !hasUnits || xe.unit == "" push!(code_x, :( $x_name = _x[$i1] ) ) else x_unit = xe.unit push!(code_x, :( $x_name = _x[$i1]*@u_str($x_unit)) ) end i1 += 1 else # x-element is a static vector i2 = i1 + xe.length - 1 v_length = xe.length if !hasUnits || xe.unit == "" push!(code_x, :( $x_name::ModiaBase.SVector{$v_length,_FloatType} = ModiaBase.SVector{$v_length,_FloatType}(_x[$i1:$i2])) ) else x_unit = xe.unit push!(code_x, :( $x_name = ModiaBase.SVector{$v_length,_FloatType}(_x[$i1:$i2])::ModiaBase.SVector{$v_length,_FloatType}*@u_str($x_unit)) ) end i1 = i2 + 1 end end i1 = 0 for i in equationInfo.nxFixedLength+1:length(equationInfo.x_info) # x-element is a dynamic vector (length can change before initialization) xe = x_info[i] x_name = xe.x_name_julia i1 += 1 if !hasUnits || xe.unit == "" push!(code_x, :( $x_name = _m.x_vec[$i1]) ) else x_unit = xe.unit push!(code_x, :( $x_name = _m.x_vec[$i1]*@u_str($x_unit)) ) end end for xe in equationInfo.x_info der_x_name = xe.der_x_name_julia if hasUnits push!(code_der_x, :( ModiaBase.appendVariable!(_m.der_x, ModiaLang.stripUnit( $der_x_name )) )) else push!(code_der_x, :( ModiaBase.appendVariable!(_m.der_x, $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*upreferred(u"s") ) else code_time = :( $timeName = _time ) end # Code for previous code_previous = [] if length(previousVars) > 0 code_previous2 = Expr[] for (i, value) in enumerate(previousVars) previousName = previousVars[i] push!(code_previous2, :( _m.nextPrevious[$i] = $previousName )) end code_previous3 = quote if ModiaLang.isFirstEventIteration(_m) && !ModiaLang.isInitial(_m) $(code_previous2...) end end push!(code_previous, code_previous3) end # Code for pre code_pre = Expr[] for (i, value) in enumerate(preVars) preName = preVars[i] push!(code_pre, :( _m.nextPre[$i] = $preName )) end # Code for deepcopy of vectors with pre-allocated memory code_copy = Expr[] for leq_tuple in equationInfo.linearEquations x_vec_julia_names = leq_tuple[2] for name in x_vec_julia_names push!(code_copy, :( $name = deepcopy($name) )) end end # Generate code of the function code = quote function $functionName(_x, _m::ModiaLang.SimulationModel{_FloatType,_TimeType}, _time)::Nothing where {_FloatType,_TimeType} _m.time = _TimeType(ModiaLang.getValue(_time)) _m.nGetDerivatives += 1 instantiatedModel = _m _p = _m.evaluatedParameters _leq_mode = nothing $code_time $(code_x...) $(AST...) $(code_der_x...) $(code_previous...) $(code_pre...) if _m.storeResult ModiaBase.TimerOutputs.@timeit _m.timer "ModiaLang addToResult!" begin $(code_copy...) ModiaLang.addToResult!(_m, $(variables...)) end end return nothing end end return code end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
13857
#= Recursively instantiate dependent objects and propagate value in hierarchical NamedTuples * Developer: Hilding Elmqvist, Mogram AB (initial version) * Martin Otter, DLR (instantiation of dependent objects added) * First version: March 2021 * License: MIT (expat) =# using OrderedCollections: OrderedDict subst(ex, environment, modelModule) = ex subst(ex::Symbol, environment, modelModule) = if length(environment) == 0; ex elseif ex in keys(environment[end]); environment[end][ex] else subst(ex, environment[1:end-1], modelModule) end subst(ex::Expr, environment, modelModule) = Expr(ex.head, [subst(a, environment, modelModule) for a in ex.args]...) subst(ex::Vector{Symbol}, environment, modelModule) = [subst(a, environment, modelModule) for a in ex] subst(ex::Vector{Expr} , environment, modelModule) = [Core.eval(modelModule, subst(a, environment, modelModule)) for a in ex] #= function propagate(model, environment=[]) #println("\n... Propagate: ", model) current = OrderedDict() for (k,v) in zip(keys(model), model) if k in [:_class, :_Type] current[k] = v elseif typeof(v) <: NamedTuple current[k] = propagate(v, vcat(environment, [current])) else evalv = v try evalv = eval(subst(v, vcat(environment, [current]))) catch e end if typeof(evalv) <: NamedTuple current[k] = v else current[k] = evalv end end end return (; current...) end =# appendKey(path, key) = path == "" ? string(key) : path * "." * string(key) """ map = propagateEvaluateAndInstantiate!(FloatType, unitless::Bool, modelModule::Module, parameters, eqInfo::ModiaBase.EquationInfo; log=false) Recursively traverse the hierarchical collection `parameters` and perform the following actions: - Propagate values. - Evaluate expressions in the context of `modelModule`. - Instantiate dependent objects. - Return the evaluated `parameters` if successfully evaluated, and otherwise return nothing, if an error occurred (an error message was printed). """ function propagateEvaluateAndInstantiate!(FloatType, unitless::Bool, modelModule, parameters, eqInfo, previous_dict, previous, pre_dict, pre, hold_dict, hold; log=false) x_found = fill(false, length(eqInfo.x_info)) map = propagateEvaluateAndInstantiate2!(FloatType, unitless, modelModule, parameters, eqInfo, x_found, previous_dict, previous, pre_dict, pre, hold_dict, hold, [], ""; log=log) if isnothing(map) return nothing end # Check that all values of x_start are set: #x_start_missing = [] #for (i, found) in enumerate(x_found) # if !found # push!(x_start_missing, eqInfo.x_info[i].x_name) # end #end # Check that all previous values are set: missingInitValues = false namesOfMissingValues = "" first = true for (name,index) in previous_dict if ismissing(previous[index]) missingInitValues = true if first first = false namesOfMissingValues *= "\n Variables from previous(..):" end namesOfMissingValues *= "\n " * name end end # Check that all pre values are set: first = true for (name,index) in pre_dict if ismissing(pre[index]) missingInitValues = true if first first = false namesOfMissingValues *= "\n Variables from pre(..):" end namesOfMissingValues *= "\n " * name end end # Check that all hold values are set: first = true for (name,index) in hold_dict if ismissing(hold[index]) missingInitValues = true if first first = false namesOfMissingValues *= "\n Variables from hold(..):" end namesOfMissingValues *= "\n " * name end end if missingInitValues printstyled("Model error: ", bold=true, color=:red) printstyled("Missing start/init values for variables: ", namesOfMissingValues, bold=true, color=:red) print("\n\n") return nothing end #if length(x_start_missing) > 0 # printstyled("Model error: ", bold=true, color=:red) # printstyled("Missing start/init values for variables: ", x_start_missing, # bold=true, color=:red) # print("\n\n") # return nothing #end return map end """ firstName(ex::Expr) If ex = :(a.b.c.d) -> firstName(ex) = :a """ function firstName(ex::Expr) if ex.head == :(.) if typeof(ex.args[1]) == Expr firstName(ex.args[1]) else return ex.args[1] end end end function changeDotToRef(ex) if ex.head == :(.) ex.head = :ref if typeof(ex.args[1]) == Expr changeDotToRef(ex.args[1]) end end return nothing end function propagateEvaluateAndInstantiate2!(FloatType, unitless::Bool, modelModule, parameters, eqInfo::ModiaBase.EquationInfo, x_found::Vector{Bool}, previous_dict, previous, pre_dict, pre, hold_dict, hold, environment, path::String; log=false) if log println("\n 1: !!! instantiate objects of $path: ", parameters) end current = OrderedDict{Symbol,Any}() # should be Map() # Determine, whether "parameters" has a ":_constructor" key and handle this specially constructor = nothing usePath = false if haskey(parameters, :_constructor) # For example: obj = (_class = :Par, _constructor = :(Modia3D.Object3D), _path = true, kwargs...) # or: rev = (_constructor = (_class = :Par, value = :(Modia3D.ModiaRevolute), _path=true), kwargs...) v = parameters[:_constructor] if typeof(v) <: OrderedDict constructor = v[:value] if haskey(v, :_path) usePath = v[:_path] end else constructor = v if haskey(parameters, :_path) usePath = parameters[:_path] end end elseif haskey(parameters, :value) # For example: p1 = (_class = :Var, parameter = true, value = 0.2) # or: p2 = (_class = :Var, parameter = true, value = :(2*p1)) v = parameters[:value] veval = Core.eval(modelModule, subst(v, vcat(environment, [current]), modelModule)) return veval end for (k,v) in parameters if log println(" 2: ... key = $k, value = $v") end if k == :_constructor || k == :_path || (k == :_class && !isnothing(constructor)) if log println(" 3: ... key = $k") end nothing elseif !isnothing(constructor) && (k == :value || k == :init || k == :start) error("value, init or start keys are not allowed in combination with a _constructor:\n$parameters") elseif typeof(v) <: OrderedDict if length(v) > 0 if haskey(v, :_class) && v[:_class] == :Par && haskey(v, :value) # For example: k = (_class = :Par, value = 2.0) -> k = 2.0 # or: k = (_class = :Par, value = :(2*Lx - 3)) -> k = eval( 2*Lx - 3 ) # or: k = (_class = :Par, value = :(bar.frame0)) -> k = ref(bar.frame0) if log println(" 4: v[:value] = ", v[:value], ", typeof(v[:value]) = ", typeof(v[:value])) println(" vcat(environment, [current]) = ", vcat(environment, [current])) end subv = subst(v[:value], vcat(environment, [current]), modelModule) if log println(" 5: _class & value: $k = $subv # before eval") end if typeof(subv) == Expr && subv.head == :(.) if typeof(firstName(subv)) <: AbstractDict changeDotToRef(subv) if log println(" 5b: _class & value: $k = $subv # before eval") end end end current[k] = Core.eval(modelModule, subv) if log println(" 6: $k = ", current[k]) end else if log println(" 7: ... key = $k, v = $v") end # For example: k = (a = 2.0, b = :(2*Lx)) value = propagateEvaluateAndInstantiate2!(FloatType, unitless, modelModule, v, eqInfo, x_found, previous_dict, previous, pre_dict, pre, hold_dict, hold, vcat(environment, [current]), appendKey(path, k); log=log) if log println(" 8: ... key = $k, value = $value") end if isnothing(value) return nothing end current[k] = value end end else if log println(" 9: else: typeof(v) = ", typeof(v)) end subv = subst(v, vcat(environment, [current]), modelModule) if log println(" 10: $k = $subv # before eval") end if typeof(subv) == Expr && subv.head == :(.) if typeof(firstName(subv)) <: AbstractDict changeDotToRef(subv) if log println(" 10b: _class & value: $k = $subv # before eval") end end end subv = Core.eval(modelModule, subv) if unitless && eltype(subv) <: Number # Remove unit subv = stripUnit(subv) end current[k] = subv if log println(" 11: $k = ", current[k]) end # Set x_start full_key = appendKey(path, k) if haskey(eqInfo.x_dict, full_key) #if log # println(" 12: (is stored in x_start)") #end j = eqInfo.x_dict[full_key] xe_info = eqInfo.x_info[j] x_value = current[k] len = hasParticles(x_value) ? 1 : length(x_value) if j <= eqInfo.nxFixedLength && 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 not possible because variable has a fixed length.", bold=true, color=:red) return nothing end x_found[j] = true xe_info.startOrInit = deepcopy(x_value) # Strip units from x_start #if xe_info.length == 1 # x_start[xe_info.startIndex] = deepcopy( convert(FloatType, stripUnit(x_value)) ) #else # ibeg = xe_info.startIndex - 1 # for i = 1:xe_info.length # x_start[ibeg+i] = deepcopy( convert(FloatType, stripUnit(x_value[i])) ) # end #end elseif haskey(previous_dict, full_key) previous[ previous_dict[full_key] ] = current[k] elseif haskey(pre_dict, full_key) pre[ pre_dict[full_key] ] = current[k] elseif haskey(hold_dict, full_key) hold[ hold_dict[full_key] ] = current[k] end end end if isnothing(constructor) return current # (; current...) else if usePath obj = Core.eval(modelModule, :(FloatType = $FloatType; $constructor(; path = $path, $current...))) else obj = Core.eval(modelModule, :(FloatType = $FloatType; $constructor(; $current...))) end if log println(" 13: +++ Instantiated $path: typeof(obj) = ", typeof(obj), ", obj = ", obj, "\n\n") end return obj end end """ splittedPath = spitPlath(path::Union{Symbol, Expr, Nothing})::Vector{Symbol} # Examples ``` splitPath(nothing) # = Symbol[] splitPath(:a) # = Symbol[:a] splitPath(:(a.b.c.d)) # = Symbol[:a, :b, :c, :d] ``` """ function splitPath(path::Union{Symbol, Expr, Nothing})::Vector{Symbol} splittedPath = Symbol[] if typeof(path) == Symbol push!(splittedPath, path) elseif typeof(path) == Expr while typeof(path.args[1]) == Expr pushfirst!(splittedPath, path.args[2].value) path = path.args[1] end pushfirst!(splittedPath, path.args[2].value) pushfirst!(splittedPath, path.args[1]) end return splittedPath end """ modelOfPath = getModelFromSplittedPath(model, splittedPath::Vector{Symbol}) Return reference to the sub-model characterized by `splittedPath`. # Examples ``` mymodel = Model(a = Model(b = Model(c = Model))) model_b = getModelFromSplittedPath(mymodel, Symbol["a", "b"]) # = mymodel[:a][:b] ``` """ function getModelFromSplittedPath(model, splittedPath::Vector{Symbol}) for name in splittedPath model = model[name] end return model end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
16069
# License for this file: MIT (expat) # Copyright 2017-2021, DLR Institute of System Dynamics and Control # Provide functions to handle time and state events """ @enum EventRestart NoRestart Restart FullRestart Terminate Define how to continue or restart integration after an event. Usually, `Restart` should be used. Only in special cases, the other flags are useful. - `NoRestart`, continue integration without restarting the integrator - `Restart`, restart integrator - `FullRestart`, restart integrator and simulation state (so dimensions may change) - `Terminate`, terminate integration """ @enum EventRestart NoRestart Restart FullRestart Terminate using ForwardDiff getValue(v) = v getValue(v::ForwardDiff.Dual) = v.value getValue(v::Measurements.Measurement) = Measurements.value(v) const nClock = 100 const nSample = 100 const nAfterDefault = 100 mutable struct EventHandler{FloatType,TimeType} stopTime::TimeType # stopTime of simulation # Logging logEvents::Bool # = true, if events shall be logged nZeroCrossings::Int # Number of zero crossing calls nRestartEvents::Int # Number of Restart events nStateEvents::Int # Number of state events nTimeEvents::Int # Number of time events # Input values for the event functions time::TimeType # Current simulation time initial::Bool # = true, if model is called at initialization # (if initial, event=true) terminal::Bool # = true, if model is called for termination (close files, streams, visualization, ...) event::Bool # = true, if model is called at an event afterSimulationStart::Bool # = true, if model is called after simulation start crossing::Bool # = true, if model is called to compute crossing function firstEventIterationDirectlyAfterInitial::Bool # = true, at the first event iteration directly after initial at model.options.startTime. triggerEventDirectlyAfterInitial::Bool # = true, if time event shall be triggered directly after initial at model.options.startTime # Values especially for simulations with several segments firstInitialOfAllSegments::Bool # = true, if model is called at initialization of the first simulation segment. terminalOfAllSegments::Bool # = true, if model is called for termination at the last simulation segment. # Computed by the event functions # For time events: maxTime::TimeType # Integrate at most up to maxTime # (if integrateToEvent == true, maxTime = nextEventTime, # otherwise maxTime > nextEventTime) nextEventTime::TimeType # Next time event instant (= realmax(Time) if no event) integrateToEvent::Bool # = true, if integrator shall integrate to nextEventTime # = false, if integrator can integrate beyond nextEventTime restart::EventRestart # Type of integrator restart at current event newEventIteration::Bool # = true, if another event iteration; = false, if no event iteration anymore firstEventIteration::Bool # = true, if first iteration at an event. # For state events: zEps::FloatType # Epsilon for zero-crossing hysteresis nz::Int # Number of event indicators z::Vector{FloatType} # Vector of event indicators (zero crossings). If one of z[i] passes # zero, that is beforeEvent(z[i])*z[i] < 0, an event is triggered # (allocated during instanciation according to nz). zPositive::Vector{Bool} # = true if z > 0 at the last event instant, otherwise false # For after time events: nafter::Int # Number of after time events after::Vector{Bool} # after[i] = time >= after(<variable i>) # For clocks (time events): clock::Vector{TimeType} sample::Vector{Any} function EventHandler{FloatType,TimeType}(; nz::Int=0, nAfter::Int=0, logEvents::Bool=false) where {FloatType,TimeType} @assert(nz >= 0) @assert(nAfter >= 0) nAfter = nAfter > 0 ? nAfter : nAfterDefault zEps = FloatType(1e-10) new(floatmax(TimeType), logEvents, 0, 0, 0, 0, convert(TimeType,0), false, false, false, false, false, false, false, false, false, floatmax(TimeType), floatmax(TimeType), true, NoRestart, false, false, zEps, nz, ones(FloatType,nz), fill(false, nz), nAfter, fill(false,nAfter), fill(convert(TimeType,0),nClock), Vector{Any}(undef, nSample)) end end # Default constructors #EventHandler( ; kwargs...) = EventHandler{Float64 ,Float64}(; kwargs...) #EventHandler{FloatType}(; kwargs...) where {FloatType} = EventHandler{FloatType,Float64}(; kwargs...) function reinitEventHandler(eh::EventHandler{FloatType,TimeType}, stopTime::TimeType, logEvents::Bool)::Nothing where {FloatType,TimeType} eh.logEvents = logEvents eh.nZeroCrossings = 0 eh.nRestartEvents = 0 eh.nStateEvents = 0 eh.nTimeEvents = 0 eh.time = convert(TimeType, 0) eh.initial = false eh.terminal = false eh.event = false eh.crossing = false eh.firstEventIterationDirectlyAfterInitial = false eh.triggerEventDirectlyAfterInitial = false eh.afterSimulationStart = false eh.firstInitialOfAllSegments = false eh.terminalOfAllSegments = false eh.stopTime = stopTime eh.maxTime = floatmax(TimeType) eh.nextEventTime = floatmax(TimeType) eh.integrateToEvent = false eh.restart = Restart eh.newEventIteration = false eh.firstEventIteration = true eh.z .= convert(FloatType, 0) eh.after .= false return nothing end positiveCrossingAsString(positive::Bool) = positive ? " became > 0" : " became <= 0" negativeCrossingAsString(negative::Bool) = negative ? " became < 0" : " became >= 0" function initEventIteration!(h::EventHandler{FloatType,TimeType}, t::TimeType)::Nothing where {FloatType,TimeType} h.time = t h.restart = NoRestart h.maxTime = floatmax(TimeType) h.nextEventTime = floatmax(TimeType) h.newEventIteration = false h.firstEventIteration = true return nothing end function setNextEvent!(h::EventHandler{FloatType,TimeType}, nextEventTime::TimeType; triggerEventDirectlyAfterInitial=false, integrateToEvent::Bool=true, restart::EventRestart=Restart)::Nothing where {FloatType,TimeType} #println("... setNextEvent!: time = ", h.time, ", nextEventTime = ", nextEventTime, ", restart = ", restart) if (h.event && nextEventTime > h.time) || (h.initial && nextEventTime >= h.time) if h.initial && triggerEventDirectlyAfterInitial && nextEventTime == h.time h.triggerEventDirectlyAfterInitial = true if nextEventTime < h.nextEventTime h.nextEventTime = nextEventTime if h.logEvents println(" nextEventTime = ", round(nextEventTime, sigdigits=6), " s") end end else if integrateToEvent h.maxTime = min(h.maxTime, nextEventTime) end if nextEventTime < h.nextEventTime h.nextEventTime = nextEventTime h.integrateToEvent = integrateToEvent if h.logEvents println(" nextEventTime = ", round(nextEventTime, sigdigits=6), " s, integrateToEvent = ", integrateToEvent ? "true" : "false") end end end h.restart = max(h.restart, restart) end return nothing end function after!(h::EventHandler{FloatType,TimeType}, nr::Int, t::Number, tAsString::String, leq::Union{Nothing,ModiaBase.LinearEquations{FloatType}}; restart::EventRestart=Restart)::Bool where {FloatType,TimeType} # time >= t (it is required that t is a discrete-time expression, but this cannot be checked) t2 = convert(TimeType,t) if h.initial h.after[nr] = h.time >= t2 if h.logEvents println(" after(", tAsString, " (= ", t2, ")) became ", h.after[nr] ? "true" : "false") end if t2 > h.time setNextEvent!(h, t2, restart = restart) end elseif h.event if abs(h.time - t2) < 1E-10 if h.logEvents && !h.after[nr] println(" after(", tAsString, " (= ", t2, ")) became true") end h.after[nr] = true elseif t2 > h.time setNextEvent!(h, t2, restart = restart) h.after[nr] = false else if h.logEvents && !h.after[nr] println(" after(", tAsString, " (= ", t2, ")) became true") end h.after[nr] = true end end return h.after[nr] end #positive!(h, nr, crossing, crossingAsString, leq_mode; restart=Restart) = positive!(h, nr, getValue(crossing), crossingAsString, leq_mode; restart=restart) function positive!(h::EventHandler{FloatType,TimeType}, nr::Int, crossing, crossingAsString::String, leq::Union{Nothing,ModiaBase.LinearEquations{FloatType}}; restart::EventRestart=Restart)::Bool where {FloatType,TimeType} crossing = getValue(crossing) if h.initial if !isnothing(leq) && leq.mode >= 0 # crossing has no meaningful value (called in algebraic loop with zero or unit vectors of unknowns). h.zPositive[nr] = false # set to an arbitrary value h.z[nr] = -h.zEps # set to an arbitrary value that is consistent to zPositive return h.zPositive[nr] end h.zPositive[nr] = crossing > convert(FloatType,0) if h.logEvents println(" ", crossingAsString, " (= ", crossing, ")", positiveCrossingAsString(h.zPositive[nr])) end elseif h.event if !isnothing(leq) && leq.mode >= 0 # crossing has no meaningful value (called in algebraic loop with zero or unit vectors of unknowns). return h.zPositive[nr] end new_zPositive = crossing > convert(FloatType,0) change = (h.zPositive[nr] && !new_zPositive) || (!h.zPositive[nr] && new_zPositive) h.zPositive[nr] = new_zPositive if change h.restart = max(h.restart, restart) if h.logEvents println(" ", crossingAsString, " (= ", crossing, ")", positiveCrossingAsString(h.zPositive[nr])) end if !isnothing(leq) && leq.mode == -1 # Solution of mixed linear equation system is not consistent to positve(..) leq.success = false if leq.niter > leq.niter_max push!(leq.inconsistentPositive, crossingAsString) end end end end h.z[nr] = crossing + (h.zPositive[nr] ? h.zEps : -h.zEps) return h.zPositive[nr] end function negative!(h::EventHandler{FloatType,TimeType}, nr::Int, crossing, crossingAsString::String, leq::Union{Nothing,ModiaBase.LinearEquations{FloatType}}; restart::EventRestart=Restart)::Bool where {FloatType,TimeType} crossing = getValue(crossing) if h.initial if !isnothing(leq) && leq.mode >= 0 # crossing has no meaningful value (called in algebraic loop with zero or unit vectors of unknowns). h.zPositive[nr] = true # set to an arbitrary value h.z[nr] = h.zEps # set to an arbitrary value that is consistent to zPositive return !h.zPositive[nr] end h.zPositive[nr] = !(crossing < convert(FloatType,0)) if h.logEvents println(" ", crossingAsStringg, " (= ", crossing, ")", negativeCrossingAsString(!h.zPositive[nr])) end elseif h.event if !isnothing(leq) && leq.mode >= 0 # crossing has no meaningful value (called in algebraic loop with zero or unit vectors of unknowns). return !h.zPositive[nr] end new_zPositive = !(crossing < convert(FloatType,0)) change = (h.zPositive[nr] && !new_zPositive) || (!h.zPositive[nr] && new_zPositive) h.zPositive[nr] = new_zPositive if change h.restart = max(h.restart, restart) if h.logEvents println(" ", crossingAsStringg, " (= ", crossing, ")", negativeCrossingAsString(!h.zPositive[nr])) end if !isnothing(leq) && leq.mode == -1 # Solution of mixed linear equation system is not consistent to negative(..) leq.success = false if leq.niter > leq.niter_max push!(leq.inconsistentNegative, crossingAsString) end end end end h.z[nr] = crossing + (h.zPositive[nr] ? h.zEps : -h.zEps) return !h.zPositive[nr] end #= function change!(h::EventHandler{FloatType,TimeType}, nr::Int, crossing::FloatType, crossingAsString::String, leq::Union{Nothing,ModiaBase.LinearEquations{FloatType}}; restart::EventRestart=Restart)::Bool where {FloatType,TimeType} if leq_mode >= 0 return crossing > convert(FloatType,0) end h.z[nr] = crossing if h.initial h.zPositive[nr] = crossing > convert(FloatType,0) if h.logEvents println(" ", crossingAsString, " (= ", crossing, ")", positiveCrossingAsString(h.zPositive[nr])) end return false elseif h.event new_zPositive = crossing > convert(FloatType,0) change = (h.zPositive[nr] && !new_zPositive) || (!h.zPositive[nr] && new_zPositive) h.zPositive[nr] = new_zPositive if change h.restart = max(h.restart, restart) if h.logEvents println(" ", crossingAsString, " (= ", crossing, ")", positiveCrossingAsString(h.zPositive[nr])) end h.newEventIteration = true return true end end return false end =# function edge!(h::EventHandler{FloatType,TimeType}, nr::Int, crossing, crossingAsString::String, leq::Union{Nothing,ModiaBase.LinearEquations{FloatType}}; restart::EventRestart=Restart)::Bool where {FloatType,TimeType} if !isnothing(leq) @error "edge(" * crossingAsString * ") is called in a linear system of equations with\n" * "iteration variables $(leq.vTear_names). This is not supported." end crossing = getValue(crossing) if h.initial h.zPositive[nr] = crossing > convert(FloatType,0) if h.logEvents println(" ", crossingAsString, " (= ", crossing, ")", positiveCrossingAsString(h.zPositive[nr])) end elseif h.event new_zPositive = crossing > convert(FloatType,0) edge = !h.zPositive[nr] && new_zPositive downEdge = h.zPositive[nr] && !new_zPositive h.zPositive[nr] = new_zPositive if edge h.restart = max(h.restart, restart) if h.logEvents println(" ", crossingAsString, " (= ", crossing, ") became > 0") end h.newEventIteration = true h.z[nr] = crossing + (h.zPositive[nr] ? h.zEps : -h.zEps) return true elseif downEdge h.restart = max(h.restart, NoRestart) if h.logEvents println(" ", crossingAsString, " (= ", crossing, ") became <= 0") end end end h.z[nr] = crossing + (h.zPositive[nr] ? h.zEps : -h.zEps) return false end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
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
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
5797
""" Encoding and decoding Modia models as JSON. * Developer: Hilding Elmqvist, Mogram AB * First version: August 2021 * License: MIT (expat) """ module JSONModel export modelToJSON, JSONToModel, cloneModel import JSON using ModiaLang using Unitful using OrderedCollections using ModiaBase.Symbolic: removeBlock using Measurements import MonteCarloMeasurements """ jModel = encodeModel(model, expressionsAsStrings=true) Encodes a model suitable to convert to a JSON string. * `model`: model (declarations and equations) * `expressionsAsStrings`: Julia expressions stored as strings or ast (Expr struct, etc) stored as dictionary * `return transformed model` """ function encodeModel(model, expressionsAsStrings=true) Base.remove_linenums!(model) model = removeBlock(model) if typeof(model) <: Quantity return Dict(:_value => ustrip.(model), :_unit=>string(unit(model))) elseif expressionsAsStrings && typeof(model) == Expr return Dict(:_Expr=>string(model)) elseif typeof(model) == Expr return Dict("head"=>model.head, "args"=>[encodeModel(a, expressionsAsStrings) for a in model.args]) elseif typeof(model) == Symbol return Dict(:_Symbol=>string(model)) elseif typeof(model) <: AbstractDict jModel = OrderedDict() for (n,v) in model jModel[n] = encodeModel(v, expressionsAsStrings) end return jModel elseif typeof(model) <: QuoteNode || typeof(model) <: Measurement || typeof(model) <: MonteCarloMeasurements.StaticParticles || typeof(model) <: MonteCarloMeasurements.Particles return Dict(:_type=>"$(typeof(model))", :_value => string(model)) elseif typeof(model) <: AbstractArray return [encodeModel(m, expressionsAsStrings) for m in model] else return model end end """ json = modelToJSON(model; expressionsAsStrings=true) Encodes a model as JSON. Expressions can be stored as strings or as ASTs. * `model`: model (declarations and equations) * `expressionsAsStrings`: Julia expressions stored as strings or Expr struct stored as dictionary * `return JSON string for the model` """ function modelToJSON(model; expressionsAsStrings=true) jModel = encodeModel(model, expressionsAsStrings) return JSON.json(jModel, 2) end """ model = decodeModel(jModel) Encodes a model suitable to convert to a JSON string. * `jmodel`: encoded model * `return model` """ function decodeModel(jModel) if typeof(jModel) <: AbstractDict && length(keys(jModel)) == 2 && "_value" in keys(jModel) && "_unit" in keys(jModel) unit = jModel["_unit"] unit = replace(unit, ' ' => '*') # Workaround for https://github.com/PainterQubits/Unitful.jl/issues/391 return jModel["_value"]*uparse(unit) elseif typeof(jModel) <: AbstractDict && length(keys(jModel)) == 1 && "_Expr" in keys(jModel) return Meta.parse(jModel["_Expr"]) elseif typeof(jModel) <: AbstractDict && length(keys(jModel)) == 1 && "_Symbol" in keys(jModel) return Symbol(jModel["_Symbol"]) elseif typeof(jModel) <: AbstractDict && length(keys(jModel)) == 2 && "head" in keys(jModel) && "args" in keys(jModel) ast = Expr(Symbol(jModel["head"]), decodeModel.(jModel["args"])...) return ast elseif typeof(jModel) <: AbstractDict && length(keys(jModel)) == 2 && "_type" in keys(jModel) && "_value" in keys(jModel) if jModel["_type"] == "QuoteNode" return QuoteNode(eval(Meta.parse(jModel["_value"]))) else return eval(Meta.parse(jModel["_value"])) end elseif typeof(jModel) <: AbstractDict model = OrderedDict() for (n,v) in jModel model[Symbol(n)] = decodeModel(v) end return model elseif typeof(jModel) <: AbstractArray return [decodeModel(m) for m in jModel] else return jModel end end """ jModel = JSONToModel(json) Decodes JSON string as model. * `json`: JSON string for the model * `return model` """ function JSONToModel(json) jModel = JSON.parse(json, dicttype=OrderedDict) model = decodeModel(jModel) end """ modelClone = cloneModel(model; expressionsAsStrings=true) Clones a model by encoding/decoding as JSON. * `model`: model * `expressionsAsStrings`: Julia expressions stored as strings or Expr struct stored as dictionary * `return modelClone` """ function cloneModel(model; expressionsAsStrings=true) # @showModel(model) jsonModel = modelToJSON(model, expressionsAsStrings=expressionsAsStrings) # @show jsonModel modelClone = JSONToModel(jsonModel) # @showModel(modelClone) return modelClone end # -------------------------------------------------------------------- #= function test() model = Model( p = 3u"m/s", q = 4.5, r = :(p+q), v = Var(min=0), s = "asdf qwerty", t = 1 ± 0.1, # u = 1 ∓ 0.1, equations = :[ 2*der(x) = -p*x y = 2*x ] ) model2 = Model( # t = 1 ± 0.1, # u = 1 ∓ 0.1, ) println("Original model:") @showModel(model) println() @instantiateModel(model, log=true) json = modelToJSON(model) println("JSON for model:") println(json) println() modelClone = JSONToModel(json) @show modelClone println("Cloned model:") @showModel(modelClone) @instantiateModel(modelClone, log=true) println() json = modelToJSON(modelClone) println("JSON for cloned model:") println(json) # ------------------------ Pin = Model( v = potential, i = flow ) Ground = Model( p = Pin, equations = :[ p.v = 0.0u"V" ] ) Gro = cloneModel(Ground) @showModel(Gro) @instantiateModel(Gro) end test() =# end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
21712
#= Handles models and variables defined as dictionaries. * Developer: Hilding Elmqvist, Mogram AB * First version: June 2021 * License: MIT (expat) =# export mergeModels, recursiveMerge, redeclare, outer, showModel, @showModel, drawModel, Model, Map, Par, Var, setLogMerge, constant, parameter, input, output, potential, flow, interval, @info_str, Boolean, Integ, @define, stringifyDefinition using Base.Meta: isexpr using OrderedCollections: OrderedDict using Unitful using ModiaBase.Symbolic: removeBlock, prepend #using Profile global logMerge = false function setLogMerge(val) global logMerge logMerge = val end function stringifyDefinition(v) if typeof(v) in [Symbol, Expr] v = removeBlock(v) v = ":(" * string(v) * ")" end return v end "Quote an expression; don't quote if the meaning in the AST is the same anyway." selquote(x) = x selquote(sym::Symbol) = Meta.quot(sym) function selquote(ex::Expr) if isexpr(ex, :kw) || isexpr(ex, :call) Expr(ex.head, [ex.args[1], [selquote(e) for e in ex.args[2:end]]...]...) else Expr(ex.head, [selquote(e) for e in ex.args]...) end end macro define(modelDef) modelName = modelDef.args[1] println(modelName) model = modelDef.args[2] model = selquote(model) dump(model) res = :($modelName = Meta.quot($model)) return esc(res) end isCollection(v) = (typeof(v) <: AbstractDict) && :_class in keys(v) showModel(m, level=0) = println(m) function showModel(m::OrderedDict, level=0) # @show m typeof(m) level += 1 if isCollection(m) print(m[:_class]) else print("OrderedDict") end println("(") for (k, v) in m if isCollection(v) print(" "^level, k, " = ") showModel(v, level) elseif k == :equations println(" "^level, "equations = :[") for e in v.args println(" "^(level+1), e) end println(" "^level, "]") elseif typeof(v) <: AbstractArray println(" "^level, k, " = [") for e in v print(" "^(level+1)) showModel(e, level+1) end println(" "^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 id = 1 function drawModel(name, m, level=0) this = Dict() children = [] ports = [] edges = [] level += 1 global id if typeof(m) <: AbstractDict && haskey(m, :_class) # print(m._class) end for (k, v) in zip(keys(m), m) if typeof(v) <: AbstractDict && level <= 1 child = drawModel(k, v, level) push!(children, child) elseif k in [:_class, :equations, :input, :output, :potential, :flow, :info] elseif k == :connect for conn in v.args conn = conn.args source = conn[1] target = conn[2:end] id += 1 edge = (; id, sources = [string(source)], targets=[string(target[1])]) push!(edges, edge) end elseif level <= 2 port = (; id=string(name) * "." * string(k), height=10, width=10) push!(ports, port) end end if length(children) > 0 && length(ports) > 0 this = (;id=name, height=100, width=100, labels=[(;text=name)], ports, children, edges) elseif length(children) > 0 this = (;id=name, height=100, width=100, labels=[(;text=name)], children, edges) elseif length(ports) > 0 this = (;id=name, height=100, width=100, labels=[(;text=name)], ports) else this = (;id=name, height=100, width=100, labels=[(;text=name)]) end return this end # --------------------------------------------------------- function mergeModels(m1::AbstractDict, m2::AbstractDict, env=Symbol()) # println("mergeModels") # @show m1 m2 result = deepcopy(m1) for (k,v) in m2 if k == :_class elseif typeof(v) <: AbstractDict if k in keys(result) && ! (:_redeclare in keys(v)) if logMerge; print("In $k: ") end # @show result[k] v k if typeof(result[k]) <: AbstractDict m = mergeModels(result[k], v, k) result[k] = m else # result[k] = v end elseif :_redeclare in keys(v) if logMerge; println("Redeclaring: $k = $v") end result[k] = v elseif nothing in values(v) # TODO: Refine else if !(:_redeclare in keys(result)) if logMerge; print("Adding: $k = "); showModel(v, 2) end end result[k] = v end elseif v === nothing if logMerge; println("Deleting: $k") end delete!(result, k) elseif k in keys(result) && k == :equations equa = copy(result[k]) push!(equa.args, v.args...) result[k] = equa if logMerge println("Adding equations: ", v) end else if logMerge if k in keys(result) if result[k] != v println("Changing: $k = $(stringifyDefinition(result[k])) to $k = $(stringifyDefinition(v))") end elseif !(:_redeclare in keys(result)) println("Adding: $k = $(stringifyDefinition(v))") end end result[k] = v end end # delete!(result, :_class) return result end function newCollection(kwargs, kind) m = OrderedDict{Symbol, Any}(kwargs) m[:_class] = kind m end Model(; kwargs...) = newCollection(kwargs, :Model) Map(; kwargs...) = newCollection(kwargs, :Map) Par(; kwargs...) = newCollection(kwargs, :Par) Var(;kwargs...) = newCollection(kwargs, :Var) function Var(values...; kwargs...) res = newCollection(kwargs, :Var) for v in values res = res | v end res end function Par(value; kwargs...) res = newCollection(kwargs, :Par) res[:value] = value res end Integ(;kwargs...) = Var(kwargs) Boolean(;kwargs...) = Var(kwargs) redeclare = Model( _redeclare = true) outer = Var( _outer = 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::AbstractDict, n::AbstractDict) = mergeModels(m, n) Base.:|(m::Symbol, n::AbstractDict) = mergeModels(eval(m), n) Base.:|(m, n) = if !(typeof(n) <: AbstractDict); mergeModels(m, Var(value=n)) else mergeModels(n, Var(value=m)) end #mergeModels(x, ::Nothing) = x #mergeModels(x, y) = y #recursiveMerge(x::Expr, y::Expr) = begin dump(x); dump(y); Expr(x.head, x.args..., y.args...) end #mergeModels(x::Expr, y::Tuple) = begin x = copy(x); xargs = x.args; xargs[y[2]] = y[3]; Expr(x.head, xargs...) end # ------------------------------------------------------------------------------- # Handling of connections """ Unpacks a path to a sequence. Example: :(a.b.c) => [:a, :b, :c] """ 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 isVar(v, kind) = isCollection(v) && v[:_class] == :Var && kind in keys(v) && v[kind] """ Collects potentials, flows, inputs and outputs from a Model. """ function collectConnector(name, model) potentials = [] flows = [] inputs = OrderedDict{Any,Any}() outputs = OrderedDict{Any,Any}() potentialPotentials = [] for (k,v) in model if isVar(v, :potential) push!(potentials, k) elseif isVar(v, :flow) push!(flows, k) push!(potentials, potentialPotentials...) elseif isVar(v, :input) inputs[prepend(k, name)] = v elseif isVar(v, :output) outputs[prepend(k, name)] = v elseif isCollection(v) && v[:_class] == :Var # println("Non potential or flow variable: $k = $v") push!(potentialPotentials, k) elseif isCollection(v) && v[:_class] == :Model subPotentials, subFlows = collectConnector(k, v) push!(potentials, [prepend(p, k) for p in subPotentials]...) push!(flows, [prepend(f, k) for f in subFlows]...) end end return potentials, flows, inputs, outputs end """ Merge connections referencing the same connector into the same tuple (similar as Modelica semantics of connections). For examples, see below. """ function mergeConnections!(connections) for i in 1:length(connections) for j in 1:i-1 con1 = connections[i] con2 = connections[j] if length(con1.args) > 0 && length(con2.args) > 0 && length(intersect(Set(con1.args), Set(con2.args))) > 0 connections[i] = Expr(:tuple, union(Set(con1.args), Set(con2.args))...) connections[j] = Expr(:tuple) # Empty tuple end end end end function testMergeConnections() connections = [ :((a, b)) :((b, c)) :((m1.b, m2.a)) :((m1.b, m3.a)) :((r,s,t)) :((s,t,u)) ] mergeConnections!(connections) @assert connections == Expr[:(()), :((a, b, c)), :(()), :((m1.b, m3.a, m2.a)), :(()), :((s, u, t, r))] end """ Convert connections to equations """ function convertConnections!(connections, model, modelName, logging=false) # println("\nconvertConnections") # showModel(model) mergeConnections!(connections) connectEquations = [] alreadyConnected = [] for i in 1:length(connections) c = connections[i] if c.head == :tuple connected = c.args inflows = [] outflows = [] first = true signalFlow1 = nothing connectedOutput = nothing potentials1 = nothing fullPotentials1 = [] flows1 = [] for con in connected if con in alreadyConnected error("Already connected: $con, found in connection: $connected") end push!(alreadyConnected, con) # @show connected 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] || :_class in keys(mod) && mod[:_class] == :Var 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 elseif :_class in keys(mod) && mod[:_class] == :Var if length(fullPotentials1) > 0 push!(connectEquations, :($(fullPotentials1[1]) = $con)) end push!(fullPotentials1, con) 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 potentials1 != nothing && potentials != potentials1 error("Not compatible potential variables: $potentials1 != $potentials, found in connection: $connected") end fullPotentials = [] for i in 1:length(potentials) p = potentials[i] potential = prepend(p, con) push!(fullPotentials, potential) if potentials1 != nothing push!(connectEquations, :($(fullPotentials1[i]) = $potential)) end end potentials1 = potentials fullPotentials1 = fullPotentials if first for i in 1:length(flows) push!(inflows, 0) push!(outflows, 0) end first = false end if length(flows1) > 0 && flows != flows1 error("Not compatible flow variables: $flows1 != $flows, found in connection: $connected") end for i in 1:length(flows) f = flows[i] flowVar = prepend(f, con) if length(sequence) == 1 if inflows[i] == 0 inflows[i] = flowVar else inflows[i] = :($(inflows[i]) + $flowVar) end else if outflows[i] == 0 outflows[i] = flowVar else outflows[i] = :($(outflows[i]) + $flowVar) end end end flows1 = flows end else # Deprecated signalFlow = con if signalFlow1 !== nothing push!(connectEquations, :($signalFlow1 = $signalFlow)) end signalFlow1 = signalFlow end end for i in 1:length(inflows) if inflows[i] != 0 || outflows[i] != 0 push!(connectEquations, :($(inflows[i]) = $(outflows[i]))) end end end end if length(connectEquations) > 0 && logging # testMergeConnections() println("Connect equations in $modelName:") for e in connectEquations println(" ", e) end end return connectEquations end # ---------------------------------------------------------------------------- # Flattening function flattenModelTuple!(model, modelStructure, modelName, to; unitless = false, log=false) # @show model connections = [] extendedModel = deepcopy(model) for (k,v) in model if typeof(modelName) == String subMod = k else subMod = :($modelName.$k) end if k in [:_class, :_redeclare] # skip them elseif typeof(v) <: Number || typeof(v) <: Unitful.Quantity || typeof(v) in [Array{Int64,1}, Array{Int64,2}, Array{Float64,1}, Array{Float64,2}] || isCollection(v) && v[:_class] == :Par # typeof(v) <: AbstractDict && :parameter in keys(v) && v.parameter # p = 5.0 if unitless && !isCollection(v) v = ustrip.(v) end modelStructure.parameters[subMod] = v modelStructure.mappedParameters[k] = v elseif (isCollection(v) && v[:_class] in [:Par, :Var] || isCollection(v) && :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[subMod] = v modelStructure.mappedParameters[k] = v end elseif isCollection(v) && v[:_class] in [:Var] || typeof(v) <: AbstractDict && :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[subMod] = x0 modelStructure.mappedParameters[k] = x0 end if :start in keys(v) s0 = v[:start] if unitless && typeof(s0) != Expr s0 = ustrip.(s0) end modelStructure.start[subMod] = s0 modelStructure.mappedParameters[k] = s0 end if :input in keys(v) && v[:input] modelStructure.inputs[subMod] = v end if :output in keys(v) && v[:output] modelStructure.outputs[subMod] = v end if :_outer in keys(v) && v[:_outer] push!(modelStructure.equations, :($k = $(prepend(k, :up)))) end if :hideResult in keys(v) push!(modelStructure.hideResults, subMod) end elseif isCollection(v) # || typeof(v) == Symbol # instantiate if typeof(v) == Symbol v = eval(eval(v)) end subModelStructure = ModelStructure() m = :($modelName.$k) if typeof(modelName) == String m = k end flattenModelTuple!(v, subModelStructure, m, to; unitless, log) #= println("subModelStructure") @show subModelStructure printModelStructure(subModelStructure, label=k) =# @timeit to "merge model structures" mergeModelStructures(modelStructure, subModelStructure, k) elseif typeof(v) <:Array && length(v) > 0 && (typeof(v[1]) <: AbstractDict || typeof(v[1]) <: AbstractDict) # array of instances i = 0 for a in v i += 1 subModelStructure = ModelStructure() name = Symbol(string(k)*"_"*string(i)) flattenModelTuple!(a, subModelStructure, name, to; unitless, log) @timeit to "merge model structures" mergeModelStructures(modelStructure, subModelStructure, name ) end elseif isexpr(v, :vect) || isexpr(v, :vcat) || isexpr(v, :hcat) arrayEquation = false for e in v.args if k == :equations && isexpr(e, :(=)) # Allow expressions without result if unitless e = removeUnits(e) end push!(modelStructure.equations, removeBlock(e)) elseif isexpr(e, :tuple) push!(connections, e) elseif isexpr(e, :call) && e.args[1] == :connect con = Expr(:tuple, e.args[2:end]... ) push!(connections, con) else arrayEquation = true end end if arrayEquation push!(modelStructure.equations, removeBlock(:($k = $(prepend(v, :up))))) # Needed for TestStateSpace.SecondOrder1 # push!(modelStructure.equations, removeBlock(:($k = $v))) # To handle assert 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)) # To fix Modelica_Electrical_Analog_Interfaces_ConditionalHeatPort # @show modelStructure.equations end end @timeit to "convert connections" connectEquations = convertConnections!(connections, extendedModel, modelName, log) push!(modelStructure.equations, connectEquations...) printModelStructure(modelStructure, "flattened", log=false) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
47508
""" Main module of ModiaLang. * Developer: Hilding Elmqvist, Mogram AB * First version: December 2020 * License: MIT (expat) """ module ModiaLang # Defalut switch settings logStatistics = false logExecution = false logCalculations = false useNewCodeGeneration = false experimentalTranslation = false using Reexport @reexport using Unitful # export Unitful symbols @reexport using DifferentialEquations # export DifferentialEquations symbols export ModiaBase export CVODE_BDF, IDA export ModiaBase export instantiateModel, @instantiateModel, assert, stringifyDefinition export stripUnit export simulate!, linearize!, get_result export @usingModiaPlot, usePlotPackage, usePreviousPlotPackage, currentPlotPackage export resultInfo, printResultInfo, rawSignal, getPlotSignal, defaultHeading export signalNames, timeSignalName, hasOneTimeSignal, hasSignal export SimulationModel, measurementToString, get_lastValue export positive, negative, previous, edge, after, reinit, pre export initial, terminal, isInitial, isTerminal, initLinearEquationsIteration! export get_xNames export registerExtraSimulateKeywordArguments export get_extraSimulateKeywordArgumentsDict import Sundials const CVODE_BDF = Sundials.CVODE_BDF const IDA = Sundials.IDA using Base.Meta: isexpr using OrderedCollections: OrderedDict using ModiaBase.Symbolic using ModiaBase.Simplify using ModiaBase.BLTandPantelidesUtilities using ModiaBase.BLTandPantelides using ModiaBase.Differentiate using ModiaBase import ModiaResult import ModiaResult: usePlotPackage, usePreviousPlotPackage, currentPlotPackage import ModiaResult: resultInfo, printResultInfo, rawSignal, getPlotSignal, defaultHeading import ModiaResult: signalNames, timeSignalName, hasOneTimeSignal, hasSignal import StaticArrays # Make StaticArrays available for the tests using Measurements import MonteCarloMeasurements using JSON #using Profile using TimerOutputs using InteractiveUtils global to = TimerOutput() Unitful.unit( v::MonteCarloMeasurements.AbstractParticles{T,N}) where {T,N} = unit(T) Unitful.upreferred(v::MonteCarloMeasurements.AbstractParticles{T,N}) where {T,N} = uconvert(upreferred(unit(v)), v) """ stripUnit(v) Convert the unit of `v` to the preferred units (default are the SI units), and then strip the unit. For details see `upreferred` and `preferunits` in [Unitful](https://painterqubits.github.io/Unitful.jl/stable/conversion/) The function is defined as: `stripUnit(v) = ustrip.(upreferred.(v))`. """ stripUnit(v) = ustrip.(upreferred.(v)) include("ModelCollections.jl") include("EvaluateParameters.jl") include("EventHandler.jl") include("CodeGeneration.jl") # include("GenerateGetDerivatives.jl") include("Synchronous.jl") include("SimulateAndPlot.jl") include("ReverseDiffInterface.jl") include("PathPlanning.jl") include("JSONModel.jl") # include("IncidencePlot.jl") # using .IncidencePlot # Base.Experimental.@optlevel 0 const drawIncidence = false const path = dirname(dirname(@__FILE__)) # Absolute path of package directory const Version = "0.11.3" const Date = "2022-02-28" #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 assert(condition, message) if ! condition println("ASSERTION: ", message) end end 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(model, modelName, modelModule, equations, unknowns, modelStructure, Avar, G, states, logDetails, log=false, logTiming=false) parameters = modelStructure.parameters 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") @timeit to "performConsistencyCheck" 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)") @timeit to "pantelides!" 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 vActive = [a == 0 for a in Avar] 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]] = simplify(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 if logTiming println("Assign") @timeit to "matching" assign = matching(HG, length(Avar), vActive) else assign = matching(HG, length(Avar), vActive) end if logTiming println("BLT") @timeit to "BLT" 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 experimentalTranslation return specialTranslation(model, modelName, modelModule, highestDerivativeEquations, unknowns, modelStructure, states, bltComponents, assign, Avar, Bequ) end if drawIncidence assignedVar, unAssigned = invertAssign(assign) showIncidence(equations, unknowns, HG, vActive, [], assign, assignedVar, bltComponents, sortVariables=true) 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) variablesIndices = OrderedDict(key => k for (k, key) in enumerate(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 = variablesIndices[x] Avar[ix] = i push!(states, unknowns[ix]) end end return Avar, states, derivatives end mutable struct ModelStructure parameters::OrderedDict{Any,Any} mappedParameters::OrderedDict{Symbol,Any} 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} hideResults::OrderedSet{Any} # Do not store these variables in the result data structure end ModelStructure() = ModelStructure(OrderedDict(), OrderedDict{Symbol,Any}(), OrderedDict(), OrderedDict(), OrderedDict(), OrderedDict(), OrderedDict(), OrderedDict(), Expr[], OrderedSet()) 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) printDict(" 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, child.parameters) parent.mappedParameters[prefix] = child.mappedParameters merge!(parent.init, child.init) parent.mappedParameters[prefix] = child.mappedParameters merge!(parent.start, child.start) parent.mappedParameters[prefix] = child.mappedParameters merge!(parent.variables, child.variables) merge!(parent.flows, child.flows) union!(parent.hideResults, child.hideResults) 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) @timeit to "enumerate(unknowns)" 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}() @timeit to "build graph information" 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 keys(variablesIndices)] unique!(incidence) push!(G, incidence) if linear && all([c == 1 || c == -1 for c in coefficients]) && rest == 0 && all(n in keys(variablesIndices) 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 @timeit to "unique!(linearVariables)" unique!(linearVariables) @timeit to "unique!(nonlinearVariables)" unique!(nonlinearVariables) @timeit to "setdiff" 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) @timeit to "simplifyLinearIntegerEquations!" (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() @timeit to "build substitutions" 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 @timeit to "replaceLinearIntegerEquations" replaceLinearIntegerEquations(GCopy[linearEquations], linearEquations, GcInt, unknowns, equations) # printArray(equations, "new equations:", log=log) reducedEquations = [] @timeit to "substitute" 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}() @timeit to "build reducedG" for i in 1:length(reducedEquations) e = reducedEquations[i] nameIncidence = Incidence[] findIncidence!(e, nameIncidence) incidence = [reducedVariablesIndices[n] for n in nameIncidence if n in keys(reducedVariablesIndices)] unique!(incidence) push!(reducedG, incidence) end reducedAvar, reducedStates, reducedDerivatives = setAvar(reducedUnknowns) return reducedEquations, reducedUnknowns, reducedAvar, reducedG, reducedStates, vEliminated, vProperty end function stateSelectionAndCodeGeneration(modStructure, Gexplicit, name, modelModule, buildDict, FloatType, TimeType, init, start, inputs, outputs, vEliminated, vProperty, unknownsWithEliminated, mappedParameters, hideResults; unitless=false, logStateSelection=false, logCode=false, logExecution=false, logCalculations=false, logTiming=false, evaluateParameters=false) (unknowns, equations, G, Avar, Bequ, assign, blt, parameters) = modStructure Goriginal = deepcopy(G) function getSolvedEquationAST(e, v) (solution, solved) = solveEquation(equations[e], unknowns[v]) unknown = solution.args[1] expr = solution.args[2] ### solution = :(_variables[$(v+1)] = $unknown = $expr) equ = string(equations[e]) @assert solved "Equation not solved for $(unknowns[v]): $(equations[e])" # sol = string(solution) # solution = prepend(makeDerivativeVar(solution, components), :m) solution = substituteForEvents(solution) 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, parameters, inputs, evaluateParameters) if logCalculations var = string(unknowns[v]) solutionString = string(solution) return :(println("Calculating: ", $solutionString); $solution; println(" Result: ", $var, " = ", upreferred.($(solution.args[1])))) else return solution end end function getResidualEquationAST(e, residualName) eq = equations[e] # prepend(makeDerivativeVar(equations[e], components), :m) lhs = eq.args[1] rhs = eq.args[2] if isexpr(rhs, :call) && rhs.args[1] == :_DUPLICATEEQUATION return nothing end if isexpr(lhs, :tuple) && all(a == 0 for a in lhs.args) || lhs == :(0) eq_rhs = makeDerVar(:($rhs), parameters, inputs, evaluateParameters) if unitless eqs = eq_rhs else eqs = :(ModiaLang.Unitful.ustrip.($eq_rhs)) end #elseif isexpr(lhs, :tuple) && isexpr(rhs, :call) && unitless # eq_rhs = makeDerVar(:($rhs), parameters, inputs, evaluateParameters) # eq_lhs = makeDerVar(:($lhs), parameters, inputs, evaluateParameters) # eqs = :( ($eq_rhs .-= $eq_lhs) ) else eq_rhs = makeDerVar(:($rhs), parameters, inputs, evaluateParameters) eq_lhs = makeDerVar(:($lhs), parameters, inputs, evaluateParameters) if unitless eqs = :( $eq_rhs .- $eq_lhs ) else eqs = :( ModiaLang.Unitful.ustrip.($eq_rhs) .- ModiaLang.Unitful.ustrip.($eq_lhs)) end end residual = :(ModiaBase.appendVariable!(_leq_mode.residuals, $eqs)) residString = string(eqs) if logCalculations return :(println("Calculating residual: ", $residString); $residualName = $eqs; println(" Residual: ", $residualName) ) # 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 (rest, factor, linear) = ModiaBase.linearFactor(equ, var) return linear && (typeof(factor) <: Number && factor != 0) end hasParticles(value) = typeof(value) <: MonteCarloMeasurements.StaticParticles || typeof(value) <: MonteCarloMeasurements.Particles invAvar = ModiaBase.revertAssociation(Avar) function var_unit(v) int_v = invAvar[v] if int_v > 0 # v is a derivative variable var = unknowns[int_v] else # v is a non-differentiated variable var = unknowns[v] end if var in keys(init) value = eval(init[var]) elseif var in keys(start) value = eval(start[var]) else value = 0.0 end if int_v > 0 value = value / u"s" end # if length(value) == 1 if ! (typeof(value) <: AbstractArray) un = unit(value) else un = unit.(value) @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_startInitFixed(v_original) v = unknowns[v_original] value::Any = nothing fixed::Bool = false if v in keys(init) value = eval(init[v]) fixed = true elseif v in keys(start) value = eval(start[v]) end return (value, fixed) 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_startInitFixed = var_startInitFixed, var_nominal = v_original -> NaN, var_unbounded = v_original -> false, 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") @timeit to "getSortedAndSolvedAST" (success,AST,equationInfo) = getSortedAndSolvedAST( Goriginal, Gexplicit, Array{Array{Int64,1},1}(blt), assign, Avar, Bequ, stateSelectionFunctions; unitless, log = logStateSelection, modelName = name) else (success,AST,equationInfo) = getSortedAndSolvedAST( Goriginal, Gexplicit, Array{Array{Int64,1},1}(blt), assign, Avar, Bequ, stateSelectionFunctions; unitless, log = logStateSelection, modelName = name) end if ! success error("Aborting") end if useNewCodeGeneration AST, newFunctions = prepareGenerateGetDerivatives(AST, modelModule, functionSize, juliaVariables) else newFunctions = Vector{Expr}() 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 ModiaLang: $name is assumed to have an init-value, but it is not found." end end # Generate code nCrossingFunctions, nAfter, nClocks, nSamples, previousVars, preVars, holdVars = getEventCounters() previousVars = Symbol.(previousVars) preVars = Symbol.(preVars) holdVars = Symbol.(holdVars) # Variables added to result extraResults = vcat(:time, setdiff([Symbol(u) for u in unknowns], [Symbol(h) for h in hideResults], Symbol[Symbol(xi_info.x_name_julia) for xi_info in equationInfo.x_info], Symbol[Symbol(xi_info.der_x_name_julia) for xi_info in equationInfo.x_info])) if true # logTiming # println("Generate code") if useNewCodeGeneration @timeit to "generate_getDerivativesNew!" code = generate_getDerivativesNew!(AST, newFunctions, modelModule, equationInfo, [:(_p)], vcat(:time, [Symbol(u) for u in unknowns]), previousVars, preVars, holdVars, :getDerivatives, hasUnits = !unitless) else @timeit to "generate_getDerivatives!" code = generate_getDerivatives!(AST, equationInfo, [:(_p)], extraResults, previousVars, preVars, holdVars, :getDerivatives, hasUnits = !unitless) end else # code = generate_getDerivatives!(AST, equationInfo, Symbol.(keys(parameters)), extraResults, :getDerivatives, hasUnits = !unitless) code = generate_getDerivativesNew!(AST, newFunctions, modelModule, equationInfo, [:(_p)], extraResults, previousVars, preVars, holdVars, :getDerivatives, hasUnits = !unitless) end if logCode #@show mappedParameters showCodeWithoutComments(code) end # Compile code # generatedFunction = @RuntimeGeneratedFunction(modelModule, code) #getDerivatives = Core.eval(modelModule, code) if logTiming println("eval code") @time @timeit to "eval(code)" Core.eval(modelModule, code) else Core.eval(modelModule, code) end getDerivatives = modelModule.getDerivatives # If generatedFunction is not packed inside a function, DifferentialEquations.jl crashes # getDerivatives(derx,x,m,time) = generatedFunction(derx, x, m, time) # convertedStartValues = convert(Vector{FloatType}, [ustrip(v) for v in startValues]) # ustrip.(value) does not work for MonteCarloMeasurements # @show mappedParameters x_startValues = initialStateVector(equationInfo, FloatType) # println("Build SimulationModel") model = @timeit to "build SimulationModel" SimulationModel{FloatType,TimeType}(modelModule, name, buildDict, getDerivatives, equationInfo, x_startValues, previousVars, preVars, holdVars, mappedParameters, extraResults; vSolvedWithInitValuesAndUnit, vEliminated, vProperty, var_name = (v)->string(unknownsWithEliminated[v]), nz=nCrossingFunctions, nAfter=nAfter, unitless=unitless) # Execute code if logExecution println("\nExecute getDerivatives") # @show startValues #derx = deepcopy(x_startValues) # deepcopy(convertedStartValues) # To get the same type as for x (deepcopy is needed for MonteCarloMeasurements) println("First executions of getDerivatives") @timeit to "execute getDerivatives" try #@time Base.invokelatest(getDerivatives, derx, x_startValues, model, convert(TimeType, 0.0)) #@time Base.invokelatest(getDerivatives, derx, x_startValues, model, convert(TimeType, 0.0)) @time init!(model) # getDerivatives is called #@time invokelatest_getDerivatives_without_der_x!(x_startValues, model, convert(TimeType, 0.0)) #@time invokelatest_getDerivatives_without_der_x!(x_startValues, model, convert(TimeType, 0.0)) # @show derx catch e error("Failed: ", e) return nothing end end return model end function duplicateMultiReturningEquations!(equations) duplicatedEquations = [] for e in equations if isexpr(e, :(=)) && isexpr(e.args[1], :tuple) || typeof(e.args[1]) <: NTuple lhs = e.args[1] if typeof(lhs) <: NTuple nargs = length(lhs) else nargs = length(lhs.args) end if e.args[2].args[1] != :implicitDependency func = :_DUPLICATEEQUATION else func = :_DUPLICATIMPLICITDEPENDENCY end nameIncidence = Incidence[] findIncidence!(e, nameIncidence, false) bandWidth = length(nameIncidence)-nargs+2 #@show length(nameIncidence) bandWidth for i in 1:(nargs-1) if false rhs = Expr(:call, :_DUPLICATEEQUATION, nameIncidence...) else indices =[] for j in 1:bandWidth push!(indices, mod(j+i-1,length(nameIncidence))+1) end rhs = Expr(:call, :_DUPLICATEEQUATION, nameIncidence[indices]...) end newE = :(0 = $rhs) push!(duplicatedEquations, newE) end end end append!(equations, duplicatedEquations) end appendSymbol(path::Nothing, name::Symbol) = name appendSymbol(path , name::Symbol) = :( $path.$name ) """ modifiedModel = buildSubModels!(model, modelModule, FloatType, TimeType, buildDict::OrderedDict) Traverse `model` and for every `<subModel>` that is a `Model(..)` and has a key-value pair `:_buildFunction = <buildFunction>` and optionally `:_buildOption=<buildOption>`, call ``` buildCode = <buildFunction>(<subModel>, modelModule, FloatType::Type, TimeType::Type, buildDict::OrderedDict{String,Any}, modelPath::Union{Expr,Symbol,Nothing}, buildOption = <buildOption>) ``` The`buildCode` is merged to the corresponding `<subModel>` in the calling environment. The arguments of `<buildFunction>`are: - `subModel`: The returned `buildCode` is merged to `submodel` - `FloatType`, `TimeType`: Types used when instantiating `SimulationModel{FloatType,TimeType}` - `modelPath`: Path upto `<subModel>`, such as: `:( a.b.c )`. - `buildDict`: Dictionary, that will be stored in the corresponding SimulationModel instance and that allows to store information about the build-process, typically with key `string(modelPath)` (if modelPath==Nothing, key="" is used). - `buildOption`: Option used for the generation of `buildCode`. Note, keys `_buildFunction` and `_buildOption` are deleted from the corresponding `<subModel>`. """ function buildSubModels!(model::AbstractDict, modelModule, FloatType::Type, TimeType::Type, buildDict::OrderedDict{String,Any}; path::Union{Expr,Symbol,Nothing}=nothing) if haskey(model, :_buildFunction) buildFunction = model[:_buildFunction] delete!(model, :_buildFunction) quotedPath = Meta.quot(path) if haskey(model, :_buildOption) buildOption = model[:_buildOption] delete!(model, :_buildOption) buildCode = Core.eval(modelModule, :($buildFunction($model, $FloatType, $TimeType, $buildDict, $quotedPath, buildOption=$buildOption)) ) else buildCode = Core.eval(modelModule, :($buildFunction($model, $FloatType, $TimeType, $buildDict, $quotedPath))) end return model | buildCode end for (key,value) in model if typeof(value) <: OrderedDict && haskey(value, :_class) && value[:_class] == :Model model[key] = buildSubModels!(value, modelModule, FloatType, TimeType, buildDict; path=appendSymbol(path,key)) end end return model end """ modelInstance = @instantiateModel(model; FloatType = Float64, aliasReduction=true, unitless=false, evaluateParameters=false, log=false, logModel=false, logDetails=false, logStateSelection=false, logCode=false,logExecution=logExecution, logCalculations=logCalculations, 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) * `evaluateParameters`: Use evaluated parameters in the generated code. * `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 timing compilation) * `logCalculations`: Log the calculations 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) source = string(__source__.file)*":"*string(__source__.line) code = :( instantiateModel($model; modelName=$modelName, modelModule=@__MODULE__, source=$source, $(kwargs...) ) ) return esc(code) end """ See documentation of macro [`@instantiateModel`] """ 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=logExecution, logCalculations=logCalculations, logTiming=false, evaluateParameters=false) #try # model = JSONModel.cloneModel(model, expressionsAsStrings=false) println("\nInstantiating model $modelName\n in module: $modelModule\n in file: $source") resetEventCounters() global to = TimerOutput() modelStructure = ModelStructure() if isexpr(model, :quote) model = eval(model) # model defined with macro end if typeof(model) <: NamedTuple || typeof(model) <: Dict || typeof(model) <: OrderedDict # Traverse model and execute functions _buildFunction(..), to include code into sub-models buildDict = OrderedDict{String,Any}() TimeType = if FloatType <: Measurements.Measurement || FloatType <: MonteCarloMeasurements.AbstractParticles; baseType(FloatType) else FloatType end # baseType(..) is defined in CodeGeneration.jl model = buildSubModels!(model, modelModule, FloatType, TimeType, buildDict) if logModel @showModel(model) end if false println("drawModel") jsonDiagram = drawModel(modelName, model) println() # println("jsonModel") # JSON.print(jsonDiagram, 2) end if logTiming println("Flatten") @timeit to "flatten" flattenModelTuple!(model, modelStructure, modelName, to; unitless, log) else flattenModelTuple!(model, modelStructure, modelName, to; unitless, log) end if experimentalTranslation interface = buildInterface(model, modelStructure) end pars = OrderedDict{Symbol, Any}([(Symbol(k),v) for (k,v) in modelStructure.parameters]) if length(modelStructure.equations) > 0 flatModel = Model() | pars | Model(equations = [removeBlock(e) for e in modelStructure.equations]) else flatModel = Model() | pars end printModelStructure(modelStructure, log=false) name = modelName else @show model error("Invalid model format") end duplicateMultiReturningEquations!(modelStructure.equations) allVariables = Incidence[] if logTiming println("Find incidence") @timeit to "findIncidence!" findIncidence!(modelStructure.equations, allVariables) else findIncidence!(modelStructure.equations, allVariables) end unique!(allVariables) if ! experimentalTranslation unknowns = setdiff(allVariables, keys(modelStructure.parameters), keys(modelStructure.inputs), [:time, :instantiatedModel, :_leq_mode, :_x]) else unknowns = setdiff(allVariables, keys(modelStructure.parameters), [:time, :instantiatedModel, :_leq_mode, :_x]) end Avar, states, derivatives = setAvar(unknowns) vActive = [a == 0 for a in Avar] if logStatistics || log println("Number of states: ", length(states)) if length(unknowns)-length(states) != length(modelStructure.equations) println("Number of unknowns: ", length(unknowns)-length(states)) end println("Number of equations: ", length(modelStructure.equations)) end printArray(modelStructure.parameters, "Parameters:", log=log) printArray(modelStructure.inputs, "Inputs:", log=log) printArray(modelStructure.outputs, "Outputs:", 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 modelStructure.inputs modelStructure.outputs end unknownsWithEliminated = unknowns if aliasReduction if log || logTiming println("Perform alias elimination and remove singularities") end # @show unknowns # @show keys(modelStructure.inputs) keys(modelStructure.outputs) ### nonInputAndOutputs = setdiff(unknowns, keys(modelStructure.inputs), keys(modelStructure.outputs)) if logTiming @timeit to "performAliasReduction" 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)) println("Build incidence matrix") unknownsSet = Set(unknowns) @timeit to "build incidence matrix" 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 unknownsSet] for n in nameIncidence if n in keys(variablesIndices) push!(incidence, variablesIndices[n]) end end unique!(incidence) push!(G, incidence) end vEliminated = Int[] vProperty = Int[] end modStructure = assignAndBLT(model, modelName, modelModule, equations, unknowns, modelStructure, Avar, G, states, logDetails, log, logTiming) (unknowns, equations, G, Avar, Bequ, assign, blt, parameters) = modStructure Gexplicit = Vector{Int}[] variablesIndices = OrderedDict(key => k for (k, key) in enumerate(unknowns)) @timeit to "build explicit incidence matrix" for i in 1:length(equations) e = equations[i] if isexpr(e.args[2], :call) && e.args[2].args[1] in [:implicitDependency, :_DUPLICATIMPLICITDEPENDENCY] if e.args[2].args[1] == :_DUPLICATIMPLICITDEPENDENCY e.args[2] = e.args[2].args[2] e.args[2].args[1] = :_DUPLICATEEQUATION else e.args[2] = e.args[2].args[2] end nameIncidence = Incidence[] findIncidence!(e, nameIncidence) incidence = [] # [variablesIndices[n] for n in nameIncidence if n in unknownsSet] for n in nameIncidence if n in keys(variablesIndices) push!(incidence, variablesIndices[n]) end end unique!(incidence) push!(Gexplicit, incidence) equations[i] = e else push!(Gexplicit, G[i]) end end if false println("Explicit equations:") for e in equations println(e) end @show G Gexplicit end if ! experimentalTranslation inst = stateSelectionAndCodeGeneration(modStructure, Gexplicit, name, modelModule, buildDict, FloatType, TimeType, modelStructure.init, modelStructure.start, modelStructure.inputs, modelStructure.outputs, vEliminated, vProperty, unknownsWithEliminated, modelStructure.mappedParameters, modelStructure.hideResults; unitless, logStateSelection, logCode, logExecution, logCalculations, logTiming, evaluateParameters) else interface[:equations] = modStructure[:equations] return interface end if logTiming show(to, compact=true) println() end inst #, flatModel #= 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($modelName,...) in $modelModule.\n", bold=true, color=:red) println() # Base.rethrow() else Base.rethrow() end if logTiming show(to, compact=true) println() end end =# end end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
20574
#= Handles models defined as named tuples. * Developer: Hilding Elmqvist, Mogram AB * First version: January 2021 * License: MIT (expat) =# export mergeModels, recursiveMerge, Redeclare, showModel, @showModel, drawModel, Model, Map, Par, Var, setLogMerge, constant, parameter, input, output, potential, flow, interval, @info_str, Boolean, Integ, @define using Base.Meta: isexpr using OrderedCollections: 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 "Quote an expression; don't quote if the meaning in the AST is the same anyway." selquote(x) = x selquote(sym::Symbol) = Meta.quot(sym) function selquote(ex::Expr) if isexpr(ex, :kw) || isexpr(ex, :call) Expr(ex.head, [ex.args[1], [selquote(e) for e in ex.args[2:end]]...]...) else Expr(ex.head, [selquote(e) for e in ex.args]...) end end macro define(modelDef) modelName = modelDef.args[1] println(modelName) model = modelDef.args[2] model = selquote(model) dump(model) res = :($modelName = Meta.quot($model)) return esc(res) 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 id = 1 function drawModel(name, m, level=0) this = Dict() children = [] ports = [] edges = [] level += 1 global id if typeof(m) <: NamedTuple && haskey(m, :class) # print(m.class) end for (k, v) in zip(keys(m), m) if typeof(v) <: NamedTuple && level <= 1 child = drawModel(k, v, level) push!(children, child) elseif k in [:class, :equations, :input, :output, :potential, :flow, :info] elseif k == :connect for conn in v.args conn = conn.args source = conn[1] target = conn[2:end] id += 1 edge = (; id, sources = [string(source)], targets=[string(target[1])]) push!(edges, edge) end elseif level <= 2 port = (; id=string(name) * "." * string(k), height=10, width=10) push!(ports, port) end end if length(children) > 0 && length(ports) > 0 this = (;id=name, height=100, width=100, labels=[(;text=name)], ports, children, edges) elseif length(children) > 0 this = (;id=name, height=100, width=100, labels=[(;text=name)], children, edges) elseif length(ports) > 0 this = (;id=name, height=100, width=100, labels=[(;text=name)], ports) else this = (;id=name, height=100, width=100, labels=[(;text=name)]) end return this end function mergeModels(m1::NamedTuple, m2::NamedTuple, env=Symbol()) # println("mergedModels") 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) elseif k in keys(mergedModels) && k == :equations equa = copy(mergedModels[k]) push!(equa.args, v.args...) mergedModels[k] = equa if logMerge println("Adding equations: ", v) end 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...) Map(; kwargs...) = (; kwargs...) Par(; kwargs...) = Map(; class = :Par, kwargs...) #Var(;kwargs...) = (; class = :Var, kwargs...) function Var(values...; kwargs...) res = (; class = :Var, kwargs...) for v in values res = res | v end res end Integ(;kwargs...) = (; class = :Var, kwargs...) Boolean(;kwargs...) = (; class = :Var, 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) = begin if !(typeof(n) <: NamedTuple); recursiveMerge(m, (; value=n)) else recursiveMerge(n, (value=m,)) end 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 #= Base.:|(x::Symbol, y::NamedTuple) = begin :(eval($x) | $y) end =# function recursiveMerge(nt1::NamedTuple, nt2::NamedTuple) # println("recursiveMerge") # @show nt1 nt2 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 # @show gen 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) elseif :flow in keys(v) && v.flow push!(flows, k) else push!(potentials, k) end end end return potentials, flows end function mergeConnections!(connections) for i in 1:length(connections) for j in 1:i-1 con1 = connections[i] con2 = connections[j] if length(con1.args) > 0 && length(con2.args) > 0 && length(intersect(Set(con1.args), Set(con2.args))) > 0 connections[i] = Expr(:tuple, union(Set(con1.args), Set(con2.args))...) connections[j] = Expr(:tuple) # Empty tuple # if :(OpI.n2) in con1.args || :(OpI.n2) in con2.args # For bug testing # @show i j con1.args con2.args # @show connections[i] connections[j] # end end end end end function convertConnections!(connections, model, modelName, logging=false) # println("\nconvertConnections") # showModel(model) mergeConnections!(connections) connectEquations = [] alreadyConnected = [] for i in 1:length(connections) c = connections[i] if c.head == :tuple connected = c.args inflow = 0 outflow = 0 signalFlow1 = nothing connectedOutput = nothing potentials1 = nothing fullPotentials1 = [] flows1 = [] for con in connected if con in alreadyConnected error("Already connected: $con, found in connection: $connected") end push!(alreadyConnected, con) # @show connected 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]] # @show mod[:class] if :input in keys(mod) && mod.input || :output in keys(mod) && mod.output || :class in keys(mod) && mod[:class] == :Var 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 elseif mod[:class] == :Var # println("\nConnect vars: ", connected) # dump(connected) if length(fullPotentials1) > 0 push!(connectEquations, :($(fullPotentials1[1]) = $con)) # println(:($(fullPotentials1[1]) = $con)) end push!(fullPotentials1, con) else # @show mod typeof(mod) 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 potentials1 != nothing && potentials != potentials1 error("Not compatible potential variables: $potentials1 != $potentials, found in connection: $connected") end fullPotentials = [] for i in 1:length(potentials) p = potentials[i] potential = append(con, p) push!(fullPotentials, potential) if potentials1 != nothing push!(connectEquations, :($(fullPotentials1[i]) = $potential)) end end potentials1 = potentials fullPotentials1 = fullPotentials 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) # @show model 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 if :input in keys(v) && v[:input] modelStructure.inputs[k] = v end if :output in keys(v) && v[:output] modelStructure.outputs[k] = v end elseif typeof(v) <: NamedTuple # || typeof(v) == Symbol # instantiate if typeof(v) == Symbol v = eval(eval(v)) end subModelStructure = ModelStructure() flattenModelTuple!(v, subModelStructure, k; unitless, log) #= println("subModelStructure") @show subModelStructure printModelStructure(subModelStructure, label=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) elseif isexpr(e, :call) && e.args[1] == :connect con = :( ( $(e.args[2]), $(e.args[3]) ) ) push!(connections, con) 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)) # To fix Modelica_Electrical_Analog_Interfaces_ConditionalHeatPort # @show modelStructure.equations end end # printModelStructure(modelStructure, "flattened") connectEquations = convertConnections!(connections, extendedModel, modelName, log) push!(modelStructure.equations, connectEquations...) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
17685
# License for this file: MIT (expat) # Copyright 2017-2021, DLR Institute of System Dynamics and Control export PTP_path, pathEndTime, getPosition!, getPosition, getIndex, getPath, plotPath using OrderedCollections using Unitful """ path = PTP_path(names; positions, v_max, a_max, startTime=0.0) Generate a new path object to move as fast as possible from positions[i,:] to positions[i+1,:]. The `positions[i,:]` can be a set of translational positions in [m], that is absolute distances, and/or rotational positions in [rad] that is angles. In robotics such a movement is called PTP (Point-To-Point). The signals are constructed in such a way that it is not possible to move faster, given the maximally allowed velocity `v_max[j]` and the maximally allowed acceleration `a_max[j]` for signal `names[j]` and have a velocity of zero at the given `positions`. If there are two or more signals (that is length(names) > 1) then the path is constructed such that all signals are in the same periods in the acceleration, constant velocity and deceleration phase. This means that only one of the signals is at its limits whereas the others are synchronized in such a way that the end point is reached at the same time instant. For example, this means that the signals have a velocity of zero at positions[1,:], one of the signals is accelerated with its maximally allowed acceleration until one of the signals reaches its maximally allowed velocity. At a proper time instant, one of the signals is decelerated with the negative value of its maximally allowed acceleration, so that all signals reach positions[2,:] with velocity zero. This element is useful to generate a reference signal for a controller which controls, e.g., a drive train, or to drive a flange according to a given acceleration. # Example ```julia using ModiaLang @usingModiaPlot const ptp_path = PTP_path(["angle1", "angle2", "angle3"], positions = [0.0 2.0 3.0; # angle1=0.0, angle2=2.0, angle3=3.0 0.5 3.0 4.0; 0.8 1.5 0.3; 0.2 1.5 0.8], startTime = 0.1, v_max = 2*ones(3), a_max = 3*ones(3)) angles = zeros(3) getPosition!(ptp_path, 0.5, angles) # angles = [0.12, 2.24, 3.24] path = getPath(ptp_path) plot(path, ["angle1", "angle2", "angle3"]) ``` """ mutable struct PTP_path{FloatType} names::Vector{AbstractString} startTime::FloatType v_max::Vector{FloatType} a_max::Vector{FloatType} positions::Matrix{FloatType} delta::Matrix{FloatType} hasPath::Vector{Bool} sd_max::Vector{FloatType} sdd_max::Vector{FloatType} Ta1::Vector{FloatType} Ta2::Vector{FloatType} noWphase::Vector{Bool} Tv::Vector{FloatType} Te::Vector{FloatType} Ta1s::Vector{FloatType} Ta2s::Vector{FloatType} Tvs::Vector{FloatType} Tes::Vector{FloatType} sd_max2::Vector{FloatType} s1::Vector{FloatType} s2::Vector{FloatType} s3::Vector{FloatType} Tend::FloatType posTemp::Vector{FloatType} # Temporary storage that can be used by the functions operation on PTP_path function PTP_path{FloatType}( names::AbstractVector; positions::Matrix{FloatType}, v_max::Vector{FloatType}, a_max::Vector{FloatType}, startTime =0.0) where {FloatType} startTime = convertTimeVariable(FloatType, startTime) #@assert(size(positions,1) > 1) #@assert(size(positions,2) == Base.length(names)) #@assert(Base.length(v_max) == Base.length(names)) #@assert(Base.length(a_max) == Base.length(names)) np = Base.length(names) npath = size(positions,1) - 1 # number of path points for i in eachindex(v_max) @assert(v_max[i] > convert(FloatType,0)) @assert(a_max[i] > convert(FloatType,0)) end delta = zeros(FloatType, npath, np) hasPath = fill(false,npath) sd_max = zeros(FloatType,npath) sdd_max = zeros(FloatType,npath) Ta1 = zeros(FloatType,npath) Ta2 = zeros(FloatType,npath) noWphase = fill(false,npath) Tv = zeros(FloatType,npath) Te = zeros(FloatType,npath) Ta1s = zeros(FloatType,npath) Ta2s = zeros(FloatType,npath) Tvs = zeros(FloatType,npath) Tes = zeros(FloatType,npath) sd_max2 = zeros(FloatType,npath) s1 = zeros(FloatType,npath) s2 = zeros(FloatType,npath) s3 = zeros(FloatType,npath) aux1 = zeros(FloatType,np) aux2 = zeros(FloatType,np) small = 1000*eps(FloatType) for i in 1:npath delta[i,:] = positions[i+1,:] - positions[i,:] for j in 1:np aux1[j] = delta[i,j]/v_max[j] aux2[j] = delta[i,j]/a_max[j] end sd_max_inv = maximum(abs.(aux1)) sdd_max_inv = maximum(abs.(aux2)) if sd_max_inv <= small || sdd_max_inv <= small hasPath[i] = false else hasPath[i] = true sd_max[i] = 1/sd_max_inv sdd_max[i] = 1/sdd_max_inv Ta1[i] = sqrt(1/sdd_max[i]) Ta2[i] = sd_max[i]/sdd_max[i] noWphase[i] = Ta2[i] >= Ta1[i] Tv[i] = noWphase[i] ? Ta1[i] : 1/sd_max[i] Te[i] = noWphase[i] ? Ta1[i] + Ta1[i] : Tv[i] + Ta2[i] Tbegin = i==1 ? startTime : Tes[i-1] Ta1s[i] = Ta1[i] + Tbegin Ta2s[i] = Ta2[i] + Tbegin Tvs[i] = Tv[i] + Tbegin Tes[i] = Te[i] + Tbegin sd_max2[i] = sdd_max[i]*Ta1[i] s1[i] = sdd_max[i]*(noWphase[i] ? Ta1[i]*Ta1[i] : Ta2[i]*Ta2[i])/2 s2[i] = s1[i] + (noWphase[i] ? sd_max2[i]*(Te[i] - Ta1[i]) - (sdd_max[i]/2)*(Te[i] - Ta1[i])^2 : sd_max[i]*(Tv[i] - Ta2[i])) s3[i] = s2[i] + sd_max[i]*(Te[i] - Tv[i]) - (sdd_max[i]/2)*(Te[i] - Tv[i])^2 end end Tend = Tes[end] new(names, startTime, v_max, a_max, positions, delta, hasPath, sd_max, sdd_max, Ta1, Ta2, noWphase, Tv, Te, Ta1s, Ta2s, Tvs, Tes, sd_max2, s1, s2, s3, Tend, zeros(FloatType,np)) end end PTP_path(args...; kwargs...) = PTP_path{Float64}(args...; kwargs...) """ Tend = pathEndTime(path) Given a `path::PTP_path` return the end time `Tend` of the path. """ pathEndTime(path::PTP_path) = path.Tend """ getPosition!(path, time, position) Given a `path::PTP_path` and a time instant `time`, return the actual position at time `time` in vector `position`. """ function getPosition!(path::PTP_path{FloatType}, time, position::Vector{FloatType}) where {FloatType} time = convertTimeVariable(FloatType, time) @assert(length(position) == size(path.positions,2)) npath = length(path.hasPath) np = length(position) # Search correct time interval i = 0 if time <= path.startTime i = 1 s = 0 else while i < npath i = i+1 if time <= path.Tes[i] break end end if time >= path.Tes[end] i = npath s = path.noWphase[i] ? path.s2[end] : path.s3[end] #println("... time=$time i=$i s=$s qbegin=", path.positions[i,1], ", qdelta = ", path.delta[i,1]) else Tbegin = i==1 ? path.startTime : path.Tes[i-1] if path.noWphase[i] if time < path.Ta1s[i] s = (path.sdd_max[i]/2)*(time - Tbegin)^2 elseif time < path.Tes[i] s = path.s1[i] + path.sd_max2[i]*(time - path.Ta1s[i]) - (path.sdd_max[i]/2)*(time - path.Ta1s[i])^2 else s = path.s2[i] end elseif time < path.Ta2s[i] s = (path.sdd_max[i]/2)*(time - Tbegin)^2 elseif time < path.Tvs[i] s = path.s1[i] + path.sd_max[i]*(time - path.Ta2s[i]) elseif time < path.Tes[i] s = path.s2[i] + path.sd_max[i]*(time - path.Tvs[i]) - (path.sdd_max[i]/2)*(time - path.Tvs[i])*(time - path.Tvs[i]) else s = path.s3[i] end end end for j in 1:np # println("... i = $i, j= $j, np = $np, s=$s, positions[i,1]=",path.positions[i,1]) position[j]= path.positions[i,j] + path.delta[i,j]*s end end """ getPosition!(path, time, position, velocity, acceleration) Given a `path::PTP_path` and a time instant `time`, return the actual position, velocity and acceleration at time `time` in vectors `position, velocity, acceleration`. """ function getPosition!(path::PTP_path{FloatType}, time, position::Vector{FloatType}, velocity::Vector{FloatType}, acceleration::Vector{FloatType})::Nothing where {FloatType} time = convertTimeVariable(FloatType, time) @assert(length(position) == size(path.positions,2)) @assert(length(velocity) == length(position)) @assert(length(acceleration) == length(acceleration)) npath = length(path.hasPath) np = length(position) s = convert(FloatType, 0) sd = convert(FloatType, 0) sdd = convert(FloatType, 0) # Search correct time interval i = 0 if time <= path.startTime i = 1 s = convert(FloatType, 0) sd = convert(FloatType, 0) sdd = convert(FloatType, 0) else while i < npath i = i+1 if time <= path.Tes[i] break end end if time >= path.Tes[end] i = npath s = path.noWphase[i] ? path.s2[end] : path.s3[end] sd = convert(FloatType, 0) sdd = convert(FloatType, 0) #println("... time=$time i=$i s=$s qbegin=", path.positions[i,1], ", qdelta = ", path.delta[i,1]) else Tbegin = i==1 ? path.startTime : path.Tes[i-1] if path.noWphase[i] if time < path.Ta1s[i] s = (path.sdd_max[i]/2)*(time - Tbegin)^2 sd = path.sdd_max[i]*(time - Tbegin) sdd = path.sdd_max[i] elseif time < path.Tes[i] s = path.s1[i] + path.sd_max2[i]*(time - path.Ta1s[i]) - (path.sdd_max[i]/2)*(time - path.Ta1s[i])^2 sd = path.sd_max2[i] - path.sdd_max[i]*(time - path.Ta1s[i]) sdd = -path.sdd_max[i] else s = path.s2[i] sd = convert(FloatType, 0) sdd = convert(FloatType, 0) end elseif time < path.Ta2s[i] s = (path.sdd_max[i]/2)*(time - Tbegin)^2 sd = path.sdd_max[i]*(time - Tbegin) sdd = path.sdd_max[i] elseif time < path.Tvs[i] s = path.s1[i] + path.sd_max[i]*(time - path.Ta2s[i]) sd = path.sd_max[i] sdd = convert(FloatType, 0) elseif time < path.Tes[i] s = path.s2[i] + path.sd_max[i]*(time - path.Tvs[i]) - (path.sdd_max[i]/2)*(time - path.Tvs[i])^2 sd = path.sd_max[i] - path.sdd_max[i]*(time - path.Tvs[i]) sdd = -path.sdd_max[i] else s = path.s3[i] sd = convert(FloatType, 0) sdd = convert(FloatType, 0) end end end for j in 1:np # println("... i = $i, j= $j, np = $np, s=$s, positions[i,1]=",path.positions[i,1]) position[j] = path.positions[i,j] + path.delta[i,j]*s velocity[j] = path.delta[i,j]*sd acceleration[j] = path.delta[i,j]*sdd end return nothing end """ pos = getPosition(path, index, time) Given a `path::PTP_path`, the `index` of a signal, and a time instant `time`, return the actual position at time `time`. """ function getPosition(path::PTP_path, index, time) getPosition!(path, time, path.posTemp) return path.posTemp[index] end """ index = getIndex(path, name) Return the index of `name` in `path` or trigger an error, if not present. """ function getIndex(path, name) index = findfirst(x -> x==name, path.names) if typeof(index) == Nothing error("getIndex(path,name): \"", name, "\" not in path") end return index end """ getPath(path; names=path.names, tend=1.1*path.Tend, ntime=101) Given a `path::PTP_path`, return a dictionary with the time series of the path over `time` up to `tend` for all `ntime` time points. """ function getPath(path::PTP_path{FloatType}; names=path.names, ntime=101, tend = 1.1*path.Tend, onlyPositions=false) where {FloatType} tend = convertTimeVariable(FloatType, tend) time = range(convert(FloatType,0)u"s",(tend)u"s",length=ntime) indices = indexin(names, path.names) names2 = deepcopy(names) for i in eachindex(indices) if typeof(i) == Nothing @warn "getPath(path, ...): \""*names[i]*"\" is ignored, because not in path" deleteat!(indices,i) deleteat!(names2,i) end end np = length(indices) q = zeros(FloatType,length(time), np) qt = zeros(FloatType,length(path.names)) series = OrderedDict{AbstractString,Any}() series["time"] = time if onlyPositions for i in eachindex(time) getPosition!(path, time[i], qt) q[i,:] = qt[indices] end for i in eachindex(names2) series[names2[i]] = q[:,i] end else der_names2 = "der(" .* names2 .* ")" der2_names2 = "der2(" .* names2 .* ")" qd = zeros(FloatType,length(time), np) qdd = zeros(FloatType,length(time), np) qtd = zeros(FloatType,length(path.names)) qtdd = zeros(FloatType,length(path.names)) for i in eachindex(time) getPosition!(path, stripUnit(time[i]), qt, qtd, qtdd) q[i,:] = qt[indices] qd[i,:] = qtd[indices] qdd[i,:] = qtdd[indices] end for i in eachindex(names2) series[names2[i]] = q[:,i] series[der_names2[i]] = qd[:,i] series[der2_names2[i]] = qdd[:,i] end end return series end """ plotPath(path, plot::Function; names=path.names, heading="PTP plots", tend=1.1*path.Tend, figure=1, ntime=101, onlyPositions=true) Given a `path::PTP_path`, plot the path over `time` up to `tend` for all points identified by the vector or tuple `names` to figure `figure` using `ntime` time points. # Example ```julia using ModiaLang @usingModiaPlot const ptp_path = PTP_path(["angle1", "angle2", "angle3"], positions = [0.0 2.0 3.0; # angle1=0.0, angle2=2.0, angle3=3.0 0.5 3.0 4.0; 0.8 1.5 0.3; 0.2 1.5 0.8], startTime = 0.1, v_max = 2*ones(3), a_max = 3*ones(3)) angles = zeros(3) getPosition!(ptp_path, 0.5, angles) # angles = [0.12, 2.24, 3.24] plotPath(ptp_path, plot) # use plot(..) defined with @usingModiaPlot ``` """ function plotPath(path::PTP_path{FloatType}, plot::Function; names=path.names, heading="PTP plots", figure=1, ntime=101, tend = 1.1*path.Tend, onlyPositions=true)::Nothing where {FloatType} time = range(0u"s",(tend)u"s",length=ntime) indices = indexin(names, path.names) names2 = deepcopy(names) for i in eachindex(indices) if isnothing(i) @warn "plotPath(path, ...): \""*names[i]*"\" is ignored, because not in path" deleteat!(indices,i) deleteat!(names2,i) end end np = length(indices) q = zeros(FloatType, length(time), np) qt = zeros(FloatType, length(path.names)) series = Dict{AbstractString,Any}() series["time"] = time if onlyPositions for i in eachindex(time) getPosition!(path, time[i], qt) q[i,:] = qt[indices] end for i in eachindex(names2) series[names2[i]] = q[:,i] end plot(series, Tuple(names2), heading=heading, figure=figure) else der_names2 = "der(" .* names2 .* ")" der2_names2 = "der2(" .* names2 .* ")" qd = zeros(FloatType, length(time), np) qdd = zeros(FloatType, length(time), np) qtd = zeros(FloatType, length(path.names)) qtdd = zeros(FloatType, length(path.names)) for i in eachindex(time) getPosition!(path, time[i], qt, qtd, qtdd) q[i,:] = qt[indices] qd[i,:] = qtd[indices] qdd[i,:] = qtdd[indices] end for i in eachindex(names2) series[names2[i]] = q[:,i] series[der_names2[i]] = qd[:,i] series[der2_names2[i]] = qdd[:,i] end plot(series, [Tuple(names2), Tuple(der_names2), Tuple(der2_names2)], heading=heading, figure=figure) end return nothing end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
4399
export ModiaProblem, ModiaSolve function ModiaProblem(m1::ModiaLang.SimulationModel{FloatType1,FloatType1}, m2::ModiaLang.SimulationModel{FloatType2,FloatType2}; p, merge=nothing, kwargs...) where {FloatType1,FloatType2} TimeType1 = FloatType1 TimeType2 = FloatType2 merge2 = Map(p = parameter | convert(Vector{FloatType2}, p)) if !isnothing(merge) merge2 = merge | merge2 end # Store states x of m1 at communication points in the DifferentialEquations result data structure solution m1.save_x_in_solution = true m2.save_x_in_solution = true # Save kwargs of ModiaProblem in simulation models empty!(m1.result) empty!(m2.result) options1 = SimulationOptions{FloatType1,TimeType1}(merge ; kwargs...) options2 = SimulationOptions{FloatType2,TimeType2}(merge2; kwargs...) if isnothing(options1) || isnothing(options2) return nothing end m1.options = options1 m2.options = options2 tspan = (options1.startTime, options1.stopTime) tspan_outputs = options1.startTime:options1.interval:options1.stopTime # Initialize/re-initialize SimulationModel if options1.log || options1.logParameters || options1.logEvaluatedParameters || options1.logStates println("... Construct simulation problem of DifferentialEquations.jl for ", m.modelName) end success1 = ModiaLang.init!(m1) if !success1|| m1.eventHandler.restart == ModiaLang.Terminate return nothing end success2 = ModiaLang.init!(m2) if !success2|| m2.eventHandler.restart == ModiaLang.Terminate return nothing end function p_derivatives!(der_x, x, p, t::FloatType1)::Nothing m1.evaluatedParameters.p .= p Base.invokelatest(m1.getDerivatives!, der_x, x, m1, t) return nothing end function p_derivatives!(der_x, x, p, t::FloatType2)::Nothing m2.evaluatedParameters.p .= p Base.invokelatest(m2.getDerivatives!, der_x, x, m2, t) return nothing end #= This call back gives an error: # type TrackedAffect has no field funciter function outputs!(x, t, integrator)::Nothing if eltype(integrator.p) == FloatType1 m1.storeResult = true p_derivatives!(m1.der_x, x, integrator.p, t) m1.storeResult = false end return nothing end callback = DifferentialEquations.FunctionCallingCallback(outputs!, funcat=tspan_outputs) =# function affect_outputs!(integrator)::Nothing if eltype(integrator.p) == FloatType1 m1.storeResult = true p_derivatives!(m1.der_x, integrator.u, integrator.p, integrator.t) m1.storeResult = false end return nothing end callback = DifferentialEquations.PresetTimeCallback(tspan_outputs, affect_outputs!) # Define problem and callbacks based on algorithm and model type abstol = 0.1*options1.tolerance return DifferentialEquations.ODEProblem(p_derivatives!, m1.x_init, tspan, p; # x_init reltol=options1.tolerance, abstol=abstol, callback = callback, modia_interval = options1.interval, modia_instantiatedModel = m1) end function ModiaSolve(problem, algorithm=missing; p, adaptive::Bool = true) startTime = problem.tspan[1] stopTime = problem.tspan[2] interval = problem.kwargs.data[:modia_interval] m = problem.kwargs.data[:modia_instantiatedModel] m.algorithmType = typeof(algorithm) # Define problem and callbacks based on algorithm and model type if abs(interval) < abs(stopTime-startTime) tspan = startTime:interval:stopTime else tspan = [startTime, stopTime] end # 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, p=p, saveat = tspan, adaptive=adaptive, dt=dt) : DifferentialEquations.solve(problem, algorithm, p=p, saveat = tspan, adaptive=adaptive, dt=dt) m.solution = solution return solution end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
40932
using Test import DataFrames import ForwardDiff import FiniteDiff macro usingModiaPlot() if haskey(ENV, "MODIA_PLOT") ModiaPlotPackage = ENV["MODIA_PLOT"] if !(ModiaPlotPackage in ModiaResult.AvailableModiaPlotPackages) @warn "ENV[\"MODIA_PLOT\"] = \"$ModiaPlotPackage\" is not supported!. Using \"NoPlot\"." @goto USE_NO_PLOT elseif ModiaPlotPackage == "NoPlot" @goto USE_NO_PLOT elseif ModiaPlotPackage == "SilentNoPlot" expr = :( import ModiaLang.ModiaResult.SilentNoPlot: plot, showFigure, saveFigure, closeFigure, closeAllFigures ) return esc( expr ) else ModiaPlotPackage = Symbol("ModiaPlot_" * ModiaPlotPackage) expr = :(using $ModiaPlotPackage) println("$expr") return esc( :(using $ModiaPlotPackage) ) end else @warn "No plot package activated. Using \"NoPlot\"." @goto USE_NO_PLOT end @label USE_NO_PLOT expr = :( import ModiaLang.ModiaResult.NoPlot: plot, showFigure, saveFigure, closeFigure, closeAllFigures ) println("$expr") return esc( expr ) end #--------------------------------------------------------------------- # Simulation #--------------------------------------------------------------------- function getAlgorithmName(algorithm)::String algorithmType = typeof(algorithm) if algorithmType == Missing return "???" end name = string(algorithmType) if algorithmType <: DifferentialEquations.OrdinaryDiffEq.QNDF if algorithm.kappa == tuple(0//1,0//1,0//1,0//1,0//1) name = replace(name, "QNDF" => "QBDF") end elseif algorithmType <: DifferentialEquations.OrdinaryDiffEq.QNDF1 || algorithmType <: DifferentialEquations.OrdinaryDiffEq.QNDF2 if algorithm.kappa == 0 name = replace(name, "QNDF" => "QBDF") end end return name end """ solution = simulate!(instantiatedModel [, algorithm]; merge = missing, # change parameter/init/start values tolerance = 1e-6, # relative tolerance startTime = 0.0, stopTime = 0.0, # stopTime >= startTime required interval = missing, # = (stopTime-startTime)/500 interp_points = 0, dtmax = missing, # = 100*interval adaptive = true, nlinearMinForDAE = 10, log = false, logStates = false, logEvents = false, logProgress = false, logTiming = false, logParameters = false, logEvaluatedParameters = false, requiredFinalStates = missing requiredFinalStates_rtol = 1e-3, requiredFinalStates_atol = 0.0, useRecursiveFactorizationUptoSize = 0) Simulate `instantiatedModel::SimulationModel` with `algorithm` (= `alg` of [ODE Solvers of DifferentialEquations.jl](https://diffeq.sciml.ai/stable/solvers/ode_solve/) or [DAE Solvers of DifferentialEquations.jl](https://diffeq.sciml.ai/stable/solvers/dae_solve/)). If the `algorithm` argument is missing, `algorithm=Sundials.CVODE_BDF()` is used, provided instantiatedModel has `FloatType = Float64`. Otherwise, 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 symbols `CVODE_BDF` and `IDA` are exported from ModiaLang, so that `simulate!(instantiatedModel, CVODE_BDF(), ...)` and `simulate!(instantiatedModel, IDA(), ...)` can be used (instead of `import Sundials; simulate!(instantiatedModel, Sundials.xxx(), ...)`). The simulation results are stored in `instantiatedModel` and can be plotted with `plot(instantiatedModel, ...)` and the result values can be retrieved with `rawSignal(..)` or `getPlotSignal(..)`. `printResultInfo(instantiatedModel)` prints information about the signals in the result file. For more details, see chapter [Results and Plotting](@ref)). The (optional) return argument `solution` is the return argument from `DifferentialEquations.solve(..)` and therefore all post-processing functionality from `DifferentialEqautions.jl` can be used. Especially, - solution.t[i] # time-instant at storage point i (solution.t[end] = stopTime) - solution.u[i] # states at storage point i A simulation run can be aborted with `<CTRL> C` (SIGINT). # Optional Arguments - `merge`: Define parameters and init/start values that shall be merged with the previous values stored in `model`, before simulation is started. If, say, an init value `phi = Var(init=1.0)` is defined in the model, a different init value can be provided with `merge = Map(phi=2.0)`. - `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=missing`, it is internally selected as (stopTime-startTime)/500. If value is without unit, it is assumed to have unit [s]. - `interp_points`: If crossing functions defined, number of additional interpolation points in one step. - `dtmax`: Maximum step size. If `dtmax==missing`, it is internally set to `100*interval`. - `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). - `nlinearMinForDAE`: If `algorithm` is a DAE integrator (e.g. `IDA()`) and the size of a linear equation system is `>= nlinearMinForDAE` and the iteration variables of this equation system are a subset of the DAE state derivatives, then during continuous integration (but not at events, including initialization) this equation system is not locally solved but is solved via the DAE integrator. Typically, for large linear equation systems, simulation efficiency is considerably improved in such a case.f - `log`: = true, to log the simulation. - `logStates`: = true, to log the states, its init/start values and its units. - `logEvents`: = true, to log events. - `logProgress` = true, to printout current simulation time every 5s. - `logTiming`: = true, to log the timing with `instantiatedModel.timer` which is an instance of [TimerOutputs](https://github.com/KristofferC/TimerOutputs.jl).TimerOutput. A user function can include its timing via\\ `TimerOutputs.@timeit instantiatedModel.timer "My Timing" <statement>`. - `logParameters`: = true, to log parameters and init/start values defined in model. - `logEvaluatedParameters`: = true, to log the evaluated parameter and init/start values that are used for initialization and during simulation. - `requiredFinalStates`: is not `missing`: Test with `@test` whether the ODE state vector at the final time instant is in agreement to vector `requiredFinalStates` with respect to some relative tolerance `requiredFinalStates_rtol`. 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). - `requiredFinalStates_rtol`: Relative tolerance used for `requiredFinalStates`. - `requiredFinalStates_atol`: Absolute tolerance used for `requiredFinalStates` (see atol in `?isapprox`) - `useRecursiveFactorizationUptoSize`: = 0: Linear equation systems A*v=b are solved with `RecursiveFactorization.jl` instead of the default `lu!(..)` and `ldiv!(..)`, if `length(v) <= useRecursiveFactorizationUptoSize`. According to `RecursiveFactorization.jl` docu, it is faster as `lu!(..)` with OpenBLAS, for `length(v) <= 500` (typically, more as a factor of two). Since there had been some cases where `lu!(..)!` was successful, but `RecursiveFactorization.jl` failed due to a singular system, the default is to use `lu!(..)!`. # Examples ```julia using Modia @usingModiaPlot # 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 (Sundials.CVODE_BDF()) # and modified parameter and initial values simulate!(firstOrder, stopTime = 1.0, merge = Map(T = 0.6, x = 0.9), logEvaluatedParameters=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: usig = getPlotSignal(firstOrder, "x") # usig.xsig : time vector # usig.xsigLegend: legend for time vector # usig.ysig : "x" vector # usig.ysigLegend: legend for "x" vector # usig.ysigType : ModiaResult.Continuous or ModiaResult.Clocked # 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) ``` """ function simulate!(m::Nothing, args...; kwargs...) @info "The call of simulate!(..) is ignored, since the first argument is nothing." @test false return nothing end function simulate!(m::SimulationModel{FloatType,TimeType}, algorithm=missing; merge=nothing, kwargs...) where {FloatType,TimeType} options = SimulationOptions{FloatType,TimeType}(merge; kwargs...) if isnothing(options) @test false return nothing end m.options = options solution = nothing #try if ismissing(algorithm) && FloatType == Float64 algorithm = Sundials.CVODE_BDF() end m.algorithmName = getAlgorithmName(algorithm) # Initialize/re-initialize SimulationModel if m.options.log || m.options.logEvaluatedParameters || m.options.logStates println("... Simulate model ", m.modelName) end useRecursiveFactorizationUptoSize = m.options.useRecursiveFactorizationUptoSize for leq in m.linearEquations leq.useRecursiveFactorization = length(leq.x) <= useRecursiveFactorizationUptoSize && length(leq.x) > 1 end #TimerOutputs.@timeit m.timer "ModiaLang.init!" success = init!(m) if m.options.log || m.options.logTiming @time (success = init!(m); if m.options.log || m.options.logTiming; print(" Initialization finished within") end) else success = init!(m) end if !success @test false return nothing end enable_timer!(m.timer) reset_timer!(m.timer) TimerOutputs.@timeit m.timer "ModiaLang.simulate!" begin sizesOfLinearEquationSystems = Int[length(leq.b) for leq in m.linearEquations] # Define problem and callbacks based on algorithm and model type interval = m.options.interval if abs(m.options.stopTime - m.options.startTime) <= 0 interval = 1.0 tspan2 = [m.options.startTime] elseif abs(m.options.interval) < abs(m.options.stopTime-m.options.startTime) tspan2 = m.options.startTime:m.options.interval:m.options.stopTime else tspan2 = [m.options.startTime, m.options.stopTime] end tspan = (m.options.startTime, m.options.stopTime) eh = m.eventHandler m.odeMode = true m.solve_leq = true if typeof(algorithm) <: DifferentialEquations.DiffEqBase.AbstractDAEAlgorithm # DAE integrator m.odeIntegrator = false nx = length(m.x_init) differential_vars = eh.nz > 0 ? fill(true, nx) : nothing # due to DifferentialEquations issue #549 TimerOutputs.@timeit m.timer "DifferentialEquations.DAEProblem" problem = DifferentialEquations.DAEProblem{true}(DAEresidualsForODE!, m.der_x, m.x_init, tspan, m, differential_vars = differential_vars) empty!(m.daeCopyInfo) if length(sizesOfLinearEquationSystems) > 0 && maximum(sizesOfLinearEquationSystems) >= options.nlinearMinForDAE # Prepare data structure to efficiently perform copy operations for DAE integrator x_info = m.equationInfo.x_info der_x_dict = m.equationInfo.der_x_dict der_x_names = keys(der_x_dict) for (ileq,leq) in enumerate(m.linearEquations) if sizesOfLinearEquationSystems[ileq] >= options.nlinearMinForDAE && length(intersect(leq.x_names,der_x_names)) == length(leq.x_names) # Linear equation shall be solved by DAE and all unknowns of the linear equation system are DAE derivatives leq.odeMode = false m.odeMode = false leq_copy = LinearEquationsCopyInfoForDAEMode(ileq) for ix in 1:length(leq.x_names) x_name = leq.x_names[ix] x_length = leq.x_lengths[ix] x_info_i = x_info[ der_x_dict[x_name] ] @assert(x_length == x_info_i.length) startIndex = x_info_i.startIndex endIndex = startIndex + x_length - 1 append!(leq_copy.index, startIndex:endIndex) end push!(m.daeCopyInfo, leq_copy) else leq.odeMode = true end end end else # ODE integrator m.odeIntegrator = true TimerOutputs.@timeit m.timer "DifferentialEquations.ODEProblem" problem = DifferentialEquations.ODEProblem{true}(derivatives!, m.x_init, tspan, m) end callback2 = DifferentialEquations.DiscreteCallback(timeEventCondition!, affectTimeEvent!) if eh.nz > 0 #println("\n!!! Callback set with crossing functions") # Due to DifferentialEquations bug https://github.com/SciML/DifferentialEquations.jl/issues/686 # FunctionalCallingCallback(outputs!, ...) is not correctly called when zero crossings are present. # The fix is to call outputs!(..) from the previous to the current event, when an event occurs. # (alternativey: callback4 = DifferentialEquations.PresetTimeCallback(tspan2, affect_outputs!) ) callback1 = DifferentialEquations.FunctionCallingCallback(outputs!, funcat=[m.options.startTime]) # call outputs!(..) at startTime callback3 = DifferentialEquations.VectorContinuousCallback(zeroCrossings!, affectStateEvent!, eh.nz, interp_points=m.options.interp_points, rootfind=DifferentialEquations.SciMLBase.RightRootFind) #callback4 = DifferentialEquations.PresetTimeCallback(tspan2, affect_outputs!) callbacks = DifferentialEquations.CallbackSet(callback1, callback2, callback3) #, callback4) else #println("\n!!! Callback set without crossing functions") callback1 = DifferentialEquations.FunctionCallingCallback(outputs!, funcat=tspan2) callbacks = DifferentialEquations.CallbackSet(callback1, callback2) end # Initial step size (the default of DifferentialEquations is too large) + step-size of fixed-step algorithm if !ismissing(algorithm) && (typeof(algorithm) <: Sundials.SundialsODEAlgorithm || typeof(algorithm) <: Sundials.SundialsDAEAlgorithm) sundials = true else sundials = false dt = m.options.adaptive ? m.options.interval/10 : m.options.interval # initial step-size end m.addEventPointsDueToDEBug = sundials # Compute solution abstol = 0.1*m.options.tolerance tstops = (m.eventHandler.nextEventTime,) m.cpuLast = time_ns() m.cpuFirst = m.cpuLast if ismissing(algorithm) TimerOutputs.@timeit m.timer "DifferentialEquations.solve" solution = DifferentialEquations.solve(problem, reltol=m.options.tolerance, abstol=abstol, save_everystep=false, callback=callbacks, adaptive=m.options.adaptive, saveat=tspan2, dt=dt, dtmax=m.options.dtmax, tstops = tstops, initializealg = DifferentialEquations.NoInit()) elseif sundials TimerOutputs.@timeit m.timer "DifferentialEquations.solve" solution = DifferentialEquations.solve(problem, algorithm, reltol=m.options.tolerance, abstol=abstol, save_everystep=false, callback=callbacks, adaptive=m.options.adaptive, saveat=tspan2, dtmax=m.options.dtmax, tstops = tstops, initializealg = DifferentialEquations.NoInit()) else TimerOutputs.@timeit m.timer "DifferentialEquations.solve" solution = DifferentialEquations.solve(problem, algorithm, reltol=m.options.tolerance, abstol=abstol, save_everystep=false, callback=callbacks, adaptive=m.options.adaptive, saveat=tspan2, dt=dt, dtmax=m.options.dtmax, tstops = tstops, initializealg = DifferentialEquations.NoInit()) end # Compute and store outputs from last event until final time sol_t = solution.t sol_x = solution.u m.storeResult = true for i = length(m.result_vars)+1:length(sol_t) invokelatest_getDerivatives_without_der_x!(sol_x[i], m, sol_t[i]) end m.storeResult = false # Final update of instantiatedModel m.result_x = solution if ismissing(algorithm) m.algorithmName = getAlgorithmName(solution.alg) end # Terminate simulation finalStates = solution.u[end] finalTime = solution.t[end] terminate!(m, finalStates, finalTime) # Raise an error, if simulation was not successful if !(solution.retcode == :Default || solution.retcode == :Success || solution.retcode == :Terminated) error("\nsolution = simulate!(", m.modelName, ", ...) failed with solution.retcode = :$(solution.retcode) at time = $finalTime.\n") end end disable_timer!(m.timer) if !m.success return nothing end if m.options.log useRecursiveFactorization = Bool[leq.useRecursiveFactorization for leq in m.linearEquations] println(" Termination of ", m.modelName, " at time = ", finalTime, " s") println(" cpuTime (without init.) = ", round(TimerOutputs.time(m.timer["ModiaLang.simulate!"])*1e-9, sigdigits=3), " s") println(" allocated (without init.) = ", round(TimerOutputs.allocated(m.timer["ModiaLang.simulate!"])/1048576.0, sigdigits=3), " MiB") println(" algorithm = ", get_algorithmName_for_heading(m)) println(" FloatType = ", FloatType) println(" interval = ", m.options.interval, " s") println(" tolerance = ", m.options.tolerance, " (relative tolerance)") println(" nStates = ", length(m.x_start)) println(" linearSystemSizes = ", sizesOfLinearEquationSystems) println(" useRecursiveFactorization = ", useRecursiveFactorization) println(" odeModeLinearSystems = ", Bool[leq.odeMode for leq in m.linearEquations]) println(" nResults = ", length(m.result_x.t)) println(" nGetDerivatives = ", m.nGetDerivatives, " (total number of getDerivatives! calls)") println(" nf = ", m.nf, " (number of getDerivatives! calls from integrator)") # solution.destats.nf println(" nZeroCrossings = ", eh.nZeroCrossings, " (number of getDerivatives! calls for zero crossing detection)") if sundials && (eh.nTimeEvents > 0 || eh.nStateEvents > 0) # statistics is wrong, due to a bug in the Sundials.jl interface println(" nJac = ??? (number of Jacobian computations)") println(" nAcceptedSteps = ???") println(" nRejectedSteps = ???") println(" nErrTestFails = ???") else println(" nJac = ", solution.destats.njacs, " (number of Jacobian computations)") println(" nAcceptedSteps = ", solution.destats.naccept) println(" nRejectedSteps = ", solution.destats.nreject) println(" nErrTestFails = ", solution.destats.nreject) end println(" nTimeEvents = ", eh.nTimeEvents) println(" nStateEvents = ", eh.nStateEvents) println(" nRestartEvents = ", eh.nRestartEvents) end if m.options.logTiming println("\n... Timings for simulation of ", m.modelName," (without initialization):") TimerOutputs.print_timer(TimerOutputs.flatten(m.timer), compact=true) end requiredFinalStates = m.options.requiredFinalStates if !ismissing(requiredFinalStates) rtol = m.options.requiredFinalStates_rtol atol = m.options.requiredFinalStates_atol if length(finalStates) != length(requiredFinalStates) success = false else success = isapprox(finalStates, requiredFinalStates, rtol=rtol, atol=atol) end if success @test success else println("\nrequiredFinalStates_rtol = $rtol") println("requiredFinalStates_atol = $atol") if length(requiredFinalStates) > 0 && typeof(requiredFinalStates[1]) <: Measurements.Measurement println( "\nrequiredFinalStates = ", measurementToString(requiredFinalStates)) printstyled("finalStates = ", measurementToString(finalStates), "\n\n", bold=true, color=:red) printstyled("difference = ", measurementToString(requiredFinalStates-finalStates), "\n\n", bold=true, color=:red) else println( "\nrequiredFinalStates = ", requiredFinalStates) printstyled("finalStates = ", finalStates, "\n\n", bold=true, color=:red) printstyled("difference = ", requiredFinalStates-finalStates, "\n\n", bold=true, color=:red) end @test isapprox(finalStates, requiredFinalStates, rtol=rtol, atol=atol) end end #= catch e if isa(e, ErrorException) println() printstyled("Error during simulation at time = $(m.time) s:\n\n", bold=true, color=:red) printstyled(e.msg, "\n", bold=true, color=:red) printstyled("\nAborting simulate!(..) for model $(m.modelName) instantiated in file\n$(m.modelFile).\n", bold=true, color=:red) println() m.lastMessage = deepcopy(e.msg) #@test false elseif isa(e, InterruptException) println() m.lastMessage = "<ctrl> C interrupt during simulation at time = $(m.time) s.\n" printstyled(m.lastMessage, bold=true, color=:red) printstyled("\nAborting simulate!(..) for model $(m.modelName) instantiated in file\n$(m.modelFile).", bold=true, color=:red) println() else println("... in else branch") Base.rethrow() end end =# return solution end #get_x_startIndexAndLength(m::SimulationModel, name) = ModiaBase.get_x_startIndexAndLength(m.equationInfo, name) #--------------------------------------------------------------------- # Linearization #--------------------------------------------------------------------- """ (A, finalStates) = linearize!(instantiatedModel [, algorithm]; stopTime = 0.0, analytic = false, <all other keyword arguments of simulate!>) Simulate until `stopTime` and linearize `instantiatedModel` at `finalStates`. The names of the state vector can be inquired by `get_xNames(instantiatedModel)`. By default, linearization is performed numerically with a central finite difference approximation using package [FiniteDiff](https://github.com/JuliaDiff/FiniteDiff.jl). When setting `analytic = true`, linearization is preformed analytically with package [ForwardDiff](https://github.com/JuliaDiff/ForwardDiff.jl), so is computed by symbolically differentiating the model. `ForwardDiff` might not be compatible with some floating point types, such as `Measurements` and Julia triggers an error that some overloaded operations are ambiguous. So `analytic=true` will not work in such cases. Analytic linearization returns matrix `A` in full precision whereas numeric linearization returns `A` in reduced precision (if FloatType = Float64, analytic linearization results in about 15 correct digits and numeric linearization in about 10 correct digits in the result). You can improve this situation, by using a larger `FloatType` for `instantiatedModel`, in case this is critical (see example below). # Output arguments - `A::Matrix`: Matrix A of the linear ODE: ``\\Delta \\dot{x} = A*\\Delta x``. - `finalStates::Vector`: Linearization point. # Example ```julia using ModiaLang using DoubleFloats using Measurements FirstOrder = Model( T = 0.4 ± 0.04, x = Var(init = 0.9 ± 0.09), equations = :[u = inputSignal(time/u"s"), T * der(x) + x = u] ) firstOrder1 = @instantiateModel(FirstOrder, FloatType = Measurement{Float64}) # Standard precision (A1, finalStates1) = linearize!(firstOrder1) # Higher precision firstOrder2 = SimulationModel{Measurement{Double64}}(firstOrder1) (A2, finalStates2) = linearize!(firstOrder2) # Show results with 15 digits (default print with Measurements shows 3 digits) println(IOContext(stdout, :error_digits=>15), "A1 = ", A1) println(IOContext(stdout, :error_digits=>15), "A2 = ", A2) ``` """ function linearize!(m::Nothing, args...; kwargs...) @info "The call of linearize!(..) is ignored, since the first argument is nothing." return nothing end function linearize!(m::SimulationModel{FloatType,TimeType}, algorithm=missing; merge = nothing, stopTime = 0.0, analytic = false, kwargs...) where {FloatType,TimeType} if analytic @info "linearize!(.., analytic=true) of model $(m.modelName) \nis modified to analytic=false, because analytic=true is currently not supported!" analytic = false end solution = simulate!(m, algorithm; merge=merge, stopTime=stopTime, kwargs...) finalStates = solution[:,end] # Function that shall be linearized function modelToLinearize!(der_x, x) invokelatest_getDerivatives!(der_x, x, m, m.options.startTime) return nothing end # Linearize if analytic der_x = zeros(FloatType, length(finalStates)) A = ForwardDiff.jacobian(modelToLinearize!, der_x, finalStates) else A = zeros(FloatType, length(finalStates), length(finalStates)) FiniteDiff.finite_difference_jacobian!(A, modelToLinearize!, finalStates) end return (A, finalStates) end #------------------------------------------------------------------------------------------------ # Provide the overloaded ModiaResult Abstract Interface for the results of SimulationModel #------------------------------------------------------------------------------------------------ ModiaResult.timeSignalName( m::SimulationModel) = "time" ModiaResult.hasOneTimeSignal(m::SimulationModel) = true """ hasSignal(instantiatedModel, name::AbstractString) Return true if parameter or time-varying variable `name` (for example `name = "a.b.c"`) is defined in the instantiateModel that can be accessed and can be used for plotting. """ ModiaResult.hasSignal(m::SimulationModel, name::AbstractString) = begin # m.save_x_in_solution ? name == "time" || haskey(m.equationInfo.x_dict, name) : if isnothing(m) || ismissing(m) || ismissing(m.result_x) || ismissing(m.result_vars) || ismissing(m.result_der_x) return false end haskey(m.result_info, name) || !ismissing(get_value(m.evaluatedParameters, name)) end """ signalNames(instantiatedModel) Return the variable names (parameters, time-varying variables) of an [`@instantiateModel`](@ref) that can be accessed and can be used for plotting. """ function ModiaResult.signalNames(m::SimulationModel) #if m.save_x_in_solution # names = ["time"] # append!(names, collect( keys(m.equationInfo.x_dict) )) #else all_names = get_names(m.evaluatedParameters) append!(all_names, setdiff(collect( keys(m.result_info) ), all_names) ) #end sort!(all_names) return all_names end #= import ChainRules function ChainRules.rrule(::typeof(ResultView), v, i) y = ResultView(v,i) function ResultView_pullback(ȳ) return ChainRules.NO_FIELDS, collect(y)... end return y, ResultView_pullback end =# function ModiaResult.rawSignal(m::SimulationModel, name::AbstractString) tsig = m.result_x.t if !m.unitless tsig = tsig*u"s" if !(m.options.desiredResultTimeUnit == NoUnits || m.options.desiredResultTimeUnit == u"s") tsig = uconvert.(m.options.desiredResultTimeUnit, tsig) end end if name == "time" return ([tsig], [tsig], ModiaResult.Independent) end if haskey(m.result_info, name) resInfo = m.result_info[name] if resInfo.store == RESULT_X (ibeg,iend,xunit) = get_xinfo(m, resInfo.index) if ibeg == iend xSig = [v[ibeg] for v in m.result_x.u] else xSig = [v[ibeg:iend] for v in m.result_x.u] end if resInfo.negate xSig *= -1 end if !m.unitless && xunit != "" xSig = xSig*uparse(xunit) end return ([tsig], [xSig], ModiaResult.Continuous) elseif resInfo.store == RESULT_DER_X (ibeg,iend,xunit) = get_xinfo(m, resInfo.index) if ibeg == iend derxSig = [v[ibeg] for v in m.result_der_x] else derxSig = [v[ibeg:iend] for v in m.result_der_x] end if resInfo.negate derxSig *= -1 end if !m.unitless if xunit == "" derxSig = derxSig/u"s" else derxSig = derxSig*(uparse(xunit)/u"s") end end return ([tsig], [derxSig], ModiaResult.Continuous) elseif resInfo.store == RESULT_VARS signal = ModiaResult.SignalView(m.result_vars, resInfo.index, resInfo.negate) if length(signal) != length(tsig) lens = length(signal) lent = length(tsig) error("Bug in SimulateAndPlot.jl (rawSignal(..)): name=\"$name\",\nlength(signal) = $lens, length(tsig) = $lent") end return ([tsig], [signal], ModiaResult.Continuous) elseif resInfo.store == RESULT_ZERO signal = ModiaResult.OneValueVector(0.0, length(tsig)) return ([tsig], [signal], ModiaResult.Continuous) else error("Bug in SimulateAndPlot.jl (rawSignal(..)): name=\"$name\", resInfo=$resInfo") end else value = get_value(m.evaluatedParameters, name) if ismissing(value) error("rawSignal: \"$name\" not in result of model $(m.modelName))") end signal = ModiaResult.OneValueVector(value, length(tsig)) return ([tsig], [signal], ModiaResult.Continuous) 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 get_algorithmName_for_heading(m::SimulationModel)::String if ismissing(m.algorithmName) algorithmName = "???" else algorithmName = m.algorithmName 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 end return algorithmName end function ModiaResult.defaultHeading(m::SimulationModel) FloatType = get_leaveName( string( typeof( m.x_start[1] ) ) ) algorithmName = get_algorithmName_for_heading(m) if FloatType == "Float64" heading = m.modelName * " (" * algorithmName * ")" else heading = m.modelName * " (" * algorithmName * ", " * FloatType * ")" end return heading end # For backwards compatibility """ signal = get_result(instantiatedModel, name; unit=true) dataFrame = get_result(instantiatedModel; onlyStates=false, extraNames=missing) - First form: After a successful simulation of `instantiatedModel`, 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**. - Second form: Return the **complete result** in form of a DataFrame object. Therefore, the whole functionality of package [DataFrames](https://dataframes.juliadata.org/stable/) can be used, including storing the result on file in different formats. Furthermore, also plot can be used on dataFrame. Parameters and zero-value variables are stored as ModiaResult.OneValueVector inside dataFrame (are treated as vectors, but actually only the value and the number of time points is stored). If `onlyStates=true`, then only the states and the signals identified with `extraNames::Vector{String}` are stored in `dataFrame`. If `onlyStates=false` and `extraNames` given, then only the signals identified with `extraNames` are stored in `dataFrame`. These keyword arguments are useful, if `dataFrame` shall be utilized as reference result used in compareResults(..). In both cases, a **view** on the internal result memory is provided (so result data is not copied). # Example ```julia using ModiaLang @usingModiaPlot using Unitful include("\$(ModiaBase.path)/demos/models/Model_Pendulum.jl") using .Model_Pendulum pendulum = simulationModel(Pendulum) simulate!(pendulum, stopTime=7.0) # Get one signal from the result and plot with the desired plot package 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(stripUnit(time), stripUnit(phi), "b--", label="phi in " * string(unit(phi[1]))) PyPlot.xlabel("time in " * string(unit(time[1]))) PyPlot.legend() # Get complete result and plot one signal result = get_result(pendulum) plot(result, "phi") # Get only states to be used as reference and compare result with reference reference = get_result(pendulum, onlyStates=true) (success, diff, diff_names, max_error, within_tolerance) = ModiaResult.compareResults(result, reference, tolerance=0.01) println("Check results: success = $success") ``` """ function get_result(m::SimulationModel, name::AbstractString; unit=true) #(xsig, xsigLegend, ysig, ysigLegend, yIsConstant) = ModiaResult.getPlotSignal(m, "time", name) #resIndex = m.variables[name] #ysig = ResultView(m.result, abs(resIndex), resIndex < 0) (tsig2, ysig2, ysigType) = ModiaResult.rawSignal(m, name) ysig = ysig2[1] ysig = unit ? ysig : stripUnit.(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 function setEvaluatedParametersInDataFrame!(obj::OrderedDict{Symbol,Any}, result_info, dataFrame::DataFrames.DataFrame, path::String, nResult::Int)::Nothing for (key,value) in zip(keys(obj), obj) name = appendName(path, key) if typeof(value) <: OrderedDict{Symbol,Any} setEvaluatedParametersInDataFrame!(value, result_info, dataFrame, name, nResult) elseif !haskey(result_info, name) dataFrame[!,name] = ModiaResult.OneValueVector(value,nResult) end end return nothing end function get_result(m::SimulationModel; onlyStates=false, extraNames=missing) dataFrame = DataFrames.DataFrame() (timeSignal, signal, signalType) = ModiaResult.rawSignal(m, "time") dataFrame[!,"time"] = timeSignal[1] if onlyStates || !ismissing(extraNames) if onlyStates for name in keys(m.equationInfo.x_dict) (timeSignal, signal, signalType) = ModiaResult.rawSignal(m, name) dataFrame[!,name] = signal[1] end end if !ismissing(extraNames) for name in extraNames (timeSignal, signal, signalType) = ModiaResult.rawSignal(m, name) dataFrame[!,name] = signal[1] end end else for name in keys(m.result_info) if name != "time" (timeSignal, signal, signalType) = ModiaResult.rawSignal(m, name) dataFrame[!,name] = signal[1] end end setEvaluatedParametersInDataFrame!(m.evaluatedParameters, m.result_info, dataFrame, "", length(timeSignal[1])) end return dataFrame end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
3059
#= Synchronous Modelica primitives Clock() Clock(intervalCounter::Int, resolution::Int=1) # Add version with rational number Clock(interval::Float64) Clock(condition::Bool, startInterval::Float64=0.0) Clock(c::Clock, solverMethod) previous(x) sample(u, c::Clock) sample(u) hold(u) = u subSample(u, factor::Int) superSample(u, factor::Int) shiftSample(u, shiftCounter::Int, resolution::Int=1) # Add version with rational number backSample(u, backCounter::Int, resolution::Int=1) # Add version with rational number noClock() interval(u) =# export Clock, sample, hold, previous Clock(interval, m::SimulationModel, nr::Int) = Clock(m.options.startTime, interval, m, nr) function Clock(startTime, interval, m::SimulationModel{FloatType,TimeType}, nr::Int)::Bool where {FloatType,TimeType} # Clock ticks at startTime, startTime + interval, startTime + 2*interval, ... # This is independent of the starTime of the simulation. Example: # if startTime = -3, interval = 1.5, m.options.startTime = 1.0 then # the clock ticks at 1.5, 3.0, 4.5, ... eh = m.eventHandler if isEvent(m) if isInitial(m) startTime2 = convert(TimeType, startTime) interval2 = convert(TimeType, interval) tFirst = startTime2 >= eh.time ? startTime2 : startTime2 + div(eh.time - startTime2, interval2, RoundUp)*interval2 if abs(eh.time - tFirst) < 1e-10 eh.clock[nr] = eh.time setNextEvent!(eh, eh.clock[nr], triggerEventDirectlyAfterInitial=true) else eh.clock[nr] = tFirst setNextEvent!(eh, eh.clock[nr]) end elseif isFirstEventIterationDirectlyAfterInitial(m) eh.clock[nr] = eh.time + convert(TimeType,interval) setNextEvent!(eh, eh.clock[nr]) return true elseif isFirstEventIteration(m) && isAfterSimulationStart(m) tick = abs(eh.time - eh.clock[nr]) < 1E-10 if tick eh.clock[nr] = eh.time + convert(TimeType,interval) setNextEvent!(eh, eh.clock[nr]) return true end setNextEvent!(eh, eh.clock[nr]) end end return false end @inline function sample(v, clock::Bool, m::SimulationModel{FloatType,TimeType}, nr::Int) where {FloatType,TimeType} eh = m.eventHandler if isInitial(m) || clock eh.sample[nr] = v end return eh.sample[nr] end @inline function previous(clock::Bool, m::SimulationModel, nr::Int) # m.previous[nr] is initialized with the start/init value of v before the first model evaluation if clock m.previous[nr] = m.nextPrevious[nr] end return m.previous[nr] end hold(v) = v @inline function hold(v, clock::Bool, m::SimulationModel, nr::Int) # m.hold[nr] is initialized with the start/init value of v before the first model evaluation if clock m.hold[nr] = v end return m.hold[nr] end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1402
module TestArrays using ModiaLang using ModiaLang.StaticArrays @usingModiaPlot LinearODE = Model( A = parameter | [-1.0 0.0; 0.0 -2.0], x = Var(init=[1.0, 2.0]), equations = :[der(x) = A*x] ) linearODE = @instantiateModel(LinearODE, logCode=true) simulate!(linearODE, stopTime = 2, log=false, logStates=false, requiredFinalStates=[0.13533533463680386, 0.036632273646086545]) plot(linearODE, ["x", "der(x)"], figure=1, heading="LinearODE with length(x)=2") simulate!(linearODE, stopTime = 2, log=false, logStates=false, requiredFinalStates=[0.14886882881582736, 0.038462894626776434, 0.00768439894426358], merge = Map(A = [-1.0 0.0 0.0; 0.0 -2.0 0.0; 0.0 0.0 -3.0], x=[1.1, 2.1, 3.1])) plot(linearODE, ["x", "der(x)"], figure=2, heading="LinearODE with length(x)=3") LinearODE2 = Model( A = parameter | SMatrix{2,2}([-1.0 0.0; 0.0 -2.0]), x = Var(init = SVector{2}(1.0, 2.0)), equations = :[der(x) = A*x] ) linearODE2 = @instantiateModel(LinearODE2, logCode=true) simulate!(linearODE2, stopTime = 2, log=false, logStates=false, requiredFinalStates=[0.13533533463680386, 0.036632273646086545]) @show typeof(linearODE2.evaluatedParameters[:A]) plot(linearODE2, ["x", "der(x)"], figure=3, heading="LinearODE2 with static arrays.") end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
2159
module TestAsynchronous #println("\nAsynchronousExamples: Demonstrating the ability to simulate models with asynchronous semantics") using ModiaLang @usingModiaPlot BooleanPulse1 = Model( startTime = parameter, width = parameter, equations = :[ y = after(startTime) && ! after(startTime + width) ] ) TestBooleanPulse1 = Model( pulse = BooleanPulse1 | Map(startTime=2u"s", width=2u"s"), ) model = @instantiateModel(TestBooleanPulse1, log=true, logCode=true) simulate!(model, Tsit5(), stopTime=10, log=true, logEvents=true) plot(model, [("pulse.y")], heading="TestBooleanPulse1", figure=1) BooleanPulse = Model( width = parameter | Map(value=50, min=0, max=100) | info"Width of pulse in % of period", period = parameter | Map(min=0) | info"Time for one period", startTime = parameter | info"Time instant of first pulse", pulseStart = Var(start=:(startTime)) | info"Start time of pulse", y = output, equations = :[ Twidth = period*width/100 clock1 = Clock(startTime, period) pulseStart = sample(if initial(); startTime else time end, clock1) y = after(pulseStart) && ! after(pulseStart + Twidth) ] ) TestBooleanPulse = Model( pulse = BooleanPulse | Map(startTime=2u"s", period=2u"s"), ) model = @instantiateModel(TestBooleanPulse, log=true, logCode=true) simulate!(model, Tsit5(), stopTime=10, log=true, logEvents=true) plot(model, [("pulse.y"), ("pulse.pulseStart")], heading="TestBooleanPulse", figure=2) # References: # http://osp.mans.edu.eg/cs212/Seq_circuits_Summary_FF-types.htm # https://www.kth.se/social/files/56124acff27654028dfc0f80/F12asyFSM1_eng.pdf SRFlipFlop = Model( Q = Var(init=false), equations = :[ Q = S || ! R && pre(Q) ] ) TestSRFlipFlop = Model( set = BooleanPulse | Map(startTime=2u"s", period=4u"s"), reset = BooleanPulse | Map(startTime=5u"s", period=4u"s"), sr = SRFlipFlop, equations = :[ connect(set.y, sr.S) connect(reset.y, sr.R) ] ) model = @instantiateModel(TestSRFlipFlop, log=true, logCode=true) simulate!(model, Tsit5(), stopTime=15, log=true, logEvents=true) plot(model, [("sr.S"), ("sr.R"), ("sr.Q")], heading="TestSRFlipFlop", figure=3) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1102
module TestBouncingBall using ModiaLang @usingModiaPlot # Does not work: edge(..) appears in a linear equation system BouncingBall = Model( e = 0.7, g = 9.81, h = Var(init = 1.0), v = Var(init = 0.0), flying = Var(start = true), # due to pre(flying) -> SimulationModel(....; pre_startValues = [true], ....) equations = :[ # desired: # flying = edge(-h) ? reinit(v, -e*v) : pre(flying) flying = edge(instantiatedModel, 1, -h, "-h", _leq_mode) ? !reinit(instantiatedModel, _x, 2, -e*v, _leq_mode) : pre(flying), der(h) = v, der(v) = flying ? -g : 0.0 ] ) model = @instantiateModel(BouncingBall, logCode=true) @show model.equationInfo.x_info # Temporary code, until edge, reinit and pre are supported in the Modia language eh = model.eventHandler eh.nz = 1 eh.z = ones(eh.nz) eh.zPositive = fill(false, eh.nz) model.pre = [true] simulate!(model, Tsit5(), stopTime = 3.0, log=true, logEvents=true) # requiredFinalStates = [-0.3617373025974107] plot(model, ["h", "v", "flying"]) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
4760
module TestDeclarations using ModiaLang 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 ModiaLang.OrderedCollections: OrderedDict 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
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1054
module TestExtraSimulateKeywordArguments using ModiaLang @usingModiaPlot # Register extra simulate! keyword arguments registerExtraSimulateKeywordArguments([:dummy1, :dummy2, :dummy3]) function inputSignal(instantiatedModel, t) if isInitial(instantiatedModel) dict = get_extraSimulateKeywordArgumentsDict(instantiatedModel) dummy1 = get(dict, :dummy1, 1.0) dummy2 = get(dict, :dummy2, true) dummy3 = get(dict, :dummy3, "this is dummy3") println("\nExtra simulate! keyword arguments: dummy1 = $dummy1, dummy2 = $dummy2, dummy3 = \"$dummy3\"\n") end sin(t) end FirstOrder = Model( T = 0.2, x = Var(init=0.3), equations = :[u = inputSignal(instantiatedModel, time/u"s"), T * der(x) + x = u, y = 2*x] ) firstOrder = @instantiateModel(FirstOrder, logCode=false) simulate!(firstOrder, Tsit5(), stopTime = 10, log=false, dummy1 = 2.0, dummy3 = "value changed", requiredFinalStates = [-0.3617373025974107]) plot(firstOrder, ["u", "y"]) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
2686
module TestFilterCircuit using ModiaLang @usingModiaPlot 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 (TestFilterCircuit.jl)" begin currentNames = signalNames(filterCircuit) requiredNames = String["C.C", "C.i", "C.n.i", "C.n.v", "C.p.i", "C.p.v", "C.v", "R.R", "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", "der(C.v)", "ground.p.i", "ground.p.v", "time"] @test sort!(currentNames) == sort!(requiredNames) @test hasSignal(filterCircuit, "R.v") @test hasSignal(filterCircuit, "C.n.v") @test hasSignal(filterCircuit, "R.R") @test hasSignal(filterCircuit, "ground.p.i") @test 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, unitless=true, FloatType = Float32) # unitless=true required, since Float32 not yet supported, if units are present simulate!(filterCircuitLow, RK4(), adaptive=false, stopTime=10.0, interval=0.01, merge = Map(R = Map(R = 5.0), C = Map(v = 3.0)), # 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) # Simulate with DAE integrator println("\n... Simulate with DAE integrator") filterCircuit2 = @instantiateModel(FilterCircuit) # Without a new @instantiateModel, this fails with a type error (will be fixed at a later time instant) simulate!(filterCircuit2, IDA(), stopTime = 10, merge = Map(R = Map(R = 5u"Ω"), C = Map(v = 3.0u"V")), requiredFinalStates = [7.424843902110655]) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
689
module TestFilterCircuit2 using ModiaLang @usingModiaPlot setLogMerge(false) include("../models/Electric.jl") FilterCircuit2 = Model( R = Resistor | Map(R=100u"Ω"), Ri = Resistor | Map(R=10u"Ω"), C = Capacitor | Map(C=2.5e-3u"F", v=Var(init=0.0u"V")), V = ConstantVoltage | Map(V=10.0u"V"), ground = Ground, connect = :[ (V.p, Ri.n) (Ri.p, R.p) (R.n, C.p) (C.n, V.n, ground.p) ] ) filterCircuit2 = @instantiateModel(FilterCircuit2, unitless=true, logCode=true) simulate!(filterCircuit2, Tsit5(), stopTime = 1.0, requiredFinalStates =[9.736520087687524]) plot(filterCircuit2, ("V.v", "Ri.v", "R.v", "C.v"), figure=1) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
461
module TestFirstOrder using ModiaLang @usingModiaPlot 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
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
2074
module TestFirstOrder2 using ModiaLang @usingModiaPlot using Test # 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=false) simulate!(firstOrder, Tsit5(), stopTime = 10, merge = Map(T = 0.4, x = 0.9), log=false, logParameters=true, logStates=true, requiredFinalStates = [-0.17964872595554535]) # Test get_result(instantiatedModel) println() result1 = get_result(firstOrder) @show(result1[1:10,:]) println() @show(result1[1:10, ["time", "u", "y"]]) println() result2 = get_result(firstOrder, onlyStates=true, extraNames=["y"]) @show(result2[1:10,:]) println() result3 = get_result(firstOrder, extraNames=["y"]) @show(result3[1:10,:]) # Linearize println("\n... Linearize at stopTime = 0 and 10:") (A_0 , x_0) = linearize!(firstOrder, analytic = true) (A_10, x_10) = linearize!(firstOrder, stopTime=10, analytic = true) (A_10_numeric, x_10_numeric) = linearize!(firstOrder, stopTime=10, analytic=false) xNames = get_xNames(firstOrder) @show xNames @show A_0 , x_0 @show A_10, x_10 @show A_10_numeric, x_10_numeric @test isapprox(A_0,[-1/0.4]) @test isapprox(A_0, A_10) plot(result1, [("u", "x"), "der(x)", "y"]) FirstOrder3 = Model( T = 2u"hr", x = Var(init=1.0), equations = :[u = if after(1.5u"hr"); 1.0 else 0.0 end, T * der(x) + x = u] ) firstOrder3 = @instantiateModel(FirstOrder3, logCode=false) simulate!(firstOrder3, Tsit5(), stopTime = 10u"hr") plot(firstOrder3, [("u", "x"), "der(x)"], figure=2) # Test all options firstOrder3b = @instantiateModel(FirstOrder3, evaluateParameters=true, log=true, logModel=true, logDetails=true, logStateSelection=true, logCode=true, logExecution=true, logCalculations=true, logTiming=true) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1139
module TestHeatTransfer using ModiaLang @usingModiaPlot using Test include("$(ModiaLang.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.15,5)u"K")), connect = :[ (fixedT.port, rod.port_a), (rod.port_b , fixedQflow.port) ] ) heatedRod = @instantiateModel(HeatedRod) simulate!(heatedRod, stopTime = 1e5, log=true, requiredFinalStates = [492.9629728925529, 492.607421697723, 492.30480548105595, 492.0850627579106, 491.9694736486912]) plot(heatedRod, [("fixedT.port.T", "rod.T"), "der(rod.T)"], figure=2) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
410
module TestInputOutput using ModiaLang @usingModiaPlot FirstOrder = Model( T = 0.2, u = input | Map(start=0), y = output, x = Var(init=0.3), equations = :[ T * der(x) + x = u, y = 2*x] ) firstOrder = @instantiateModel(FirstOrder) simulate!(firstOrder, Tsit5(), stopTime = 2, requiredFinalStates = [1.362130067500907e-5]) plot(firstOrder, ["u", "x", "der(x)", "y"]) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
496
module TestJSON using ModiaLang import ModiaLang.JSON mutable struct S a b end mutable struct T a b end s = S(1,T(10, 25)) println("JSON.print(s):") JSON.print(s) println() n = (a=1, b=(a=10, b=25)) println("JSON.print(n):") JSON.print(n) println() println("JSON.print(s) == JSON.print(n):") println(JSON.print(s) == JSON.print(n)) e = :(x = sin(time)*(a+1)) println() JSON.print(e) println() println() ej = JSON.json(e) @show ej println() ee = JSON.parse(ej) @show eval(ee) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
3649
module TestLinearEquationSystemWithUnitsAndMonteCarlo using ModiaLang using ModiaLang.MonteCarloMeasurements @usingModiaPlot include("../models/Electric.jl") ### With units FilterCircuit = Model( R1 = Resistor | Map(R=100.0u"Ω"), R2 = Resistor | Map(R=200.0u"Ω", i=Var(start=0.0u"A")), Ri = Resistor | Map(R=10.0u"Ω"), C = Capacitor | Map(C=2.5e-3u"F", v=Var(init=0.0u"V"), i=Var(start=0.0u"A")), V = ConstantVoltage | Map(V=10.0u"V"), ground = Ground, connect = :[ (V.p, Ri.n) (Ri.p, R1.p) (Ri.p, R2.p) (R1.n, R2.n, C.p) (C.n, V.n, ground.p) ] ) plotVariables = ("V.v", "Ri.v", "R1.v", "C.v") logCode = false # Units defined (and unitless=false and true) filterCircuit1 = @instantiateModel(FilterCircuit, unitless=true, logCode=logCode) simulate!(filterCircuit1, QBDF(autodiff=false), stopTime = 1.0, log=true) plot(filterCircuit1, plotVariables, figure=1) filterCircuit2 = @instantiateModel(FilterCircuit, unitless=false, logCode=logCode) simulate!(filterCircuit2, QBDF(autodiff=false), stopTime = 1.0, log=true) plot(filterCircuit2, plotVariables, figure=2) # Units and StaticParticles defined (and unitless=false and true) FilterCircuitStaticParticles = FilterCircuit | Map(R1=Map(R=(100.0∓10.0)u"Ω"), R2=Map(R=(200.0∓20.0)u"Ω"), C =Map(C=(2.5e-3∓1e-4)u"F") ) filterCircuit3 = @instantiateModel(FilterCircuitStaticParticles, unitless=true, FloatType=StaticParticles{Float64,100}, logCode=logCode) simulate!(filterCircuit3, QBDF(autodiff=false), stopTime = 1.0, log=true, merge = Map(R1=Map(R=(110.0∓10.0)u"Ω"), R2=Map(R=(220.0∓20.0)u"Ω"), C =Map(C=(2.6e-3∓1e-4)u"F") ) ) plot(filterCircuit3, plotVariables, figure=3) filterCircuit4 = @instantiateModel(FilterCircuitStaticParticles, unitless=false, FloatType=StaticParticles{Float64,100}, logCode=logCode) simulate!(filterCircuit4, QBDF(autodiff=false), stopTime = 1.0, log=true, merge = Map(R1=Map(R=(110.0∓10.0)u"Ω"), R2=Map(R=(220.0∓20.0)u"Ω"), C =Map(C=(2.6e-3∓1e-4)u"F") ) ) plot(filterCircuit4, plotVariables, figure=4) # Units and Particles defined (and unitless=false and true) FilterCircuitParticles = FilterCircuit | Map(R1=Map(R=(100.0±0.0)u"Ω"), R2=Map(R=(200.0±20.0)u"Ω"), C =Map(C=(2.5e-3±1e-4)u"F") ) filterCircuit5 = @instantiateModel(FilterCircuitParticles, unitless=true, FloatType=Particles{Float64,2000}, logCode=logCode) simulate!(filterCircuit5, QBDF(autodiff=false), stopTime = 1.0, log=true, merge = Map(R1=Map(R=(110.0±10.0)u"Ω"), R2=Map(R=(220.0±20.0)u"Ω"), C =Map(C=(2.6e-3±1e-4)u"F") ) ) plot(filterCircuit5, plotVariables, figure=5, MonteCarloAsArea=true) filterCircuit6 = @instantiateModel(FilterCircuitParticles, unitless=false, FloatType=Particles{Float64,2000}, logCode=logCode) simulate!(filterCircuit6, QBDF(autodiff=false), stopTime = 1.0, log=true, merge = Map(R1=Map(R=(110.0±10.0)u"Ω"), R2=Map(R=(220.0±20.0)u"Ω"), C =Map(C=(2.6e-3±1e-4)u"F") ) ) plot(filterCircuit6, plotVariables, figure=6, MonteCarloAsArea=true) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
2039
module TestMechanics println("TestMechanics: Tests how 3D mechanics could be combined with ModiaLang.") using ModiaLang @usingModiaPlot # ModiaLang models include("$(ModiaLang.path)/models/Blocks.jl") include("$(ModiaLang.path)/models/Electric.jl") include("$(ModiaLang.path)/models/Rotational.jl") # Generic ModiaLang3D 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 # ModiaLang 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 ModiaLang 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
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1976
module TestMultiReturningFunction using ModiaLang @usingModiaPlot include("$(ModiaLang.path)/models/Blocks.jl") include("$(ModiaLang.path)/models/Electric.jl") include("$(ModiaLang.path)/models/Rotational.jl") function twoCoupledInertias(J1,J2,derw1,derw2,tau0,tau1,tau2)::Array{Float64,1} r1 = J1*derw1 - tau0 + tau1 r2 = J2*derw2 - tau1 + tau2 return [r1,r2] end ThreeCoupledInertias = Model( J1 = 1.1, J2 = 1.2, J3 = 1.3, phi1 = Var(init=0.0), phi2 = Var(init=0.0), phi3 = Var(init=0.0), w1 = Var(init=0.0), w2 = Var(init=0.0), w3 = Var(init=0.0), tau1 = Var(start=0.0), tau2 = Var(start=0.0), # Same model with components from the Rotational.jl library inertia1 = Inertia | Map(J=:J1), inertia2 = Inertia | Map(J=:J2), inertia3 = Inertia | Map(J=:J3), connect = :[ (inertia1.flange_b, inertia2.flange_a) (inertia2.flange_b, inertia3.flange_a) ], equations = :[ tau0 = sin(time/u"s") w1 = der(phi1) w2 = der(phi2) w3 = der(phi3) phi2 = phi1 phi3 = phi2 (0,0) = twoCoupledInertias(J1,J2,der(w1),der(w2),tau0,tau1,tau2) J3*der(w3) = tau2 inertia1.flange_a.tau = tau0 inertia3.flange_b.tau = 0.0 ] ) threeCoupledInertias = @instantiateModel(ThreeCoupledInertias, unitless=true, log=false, logDetails=false, logCode=true, logStateSelection=false) simulate!(threeCoupledInertias, stopTime = 2.0, log=true, requiredFinalStates=[0.3029735305821086, 0.3933746028781303, 0.39337460287813036, 0.3029735305821086]) plot(threeCoupledInertias, [("phi1", "phi2", "phi3", "inertia1.phi"), ("w1","w2","w3", "inertia1.w"), ("tau0"), ("tau1", "inertia2.flange_a.tau"), ("tau2", "inertia3.flange_a.tau")]) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
3355
module TestMultiReturningFunction10 using ModiaLang.StaticArrays using ModiaLang @usingModiaPlot mutable struct MbsData phi1::Float64 w1::Float64 derw1::Float64 u1::Float64 phi2::Vector{Float64} w2::Vector{Float64} derw2::Vector{Float64} residuals2::Vector{Float64} function MbsData(; path = "", phi1=0.0, w1=0.0, phi2, equationInfo = missing, evaluatedParameters=missing) println(" TestMultiReturningFunction10: init Mbs with phi2=$phi2") ndof = length(phi2) obj = new(phi1, w1, 0.0, 0.0, phi2, zeros(ndof), zeros(ndof), zeros(ndof)) # get_sizes(evaluatedParameters, ...) # add_states(obj,equationInfo, copy_from_x, copy_to_der_x) return obj end end function myBuildFunction(model::AbstractDict, FloatType::Type, TimeType::Type, buildDict::AbstractDict, modelPath::Union{Expr,Symbol,Nothing}; buildOption = "Default") modelPathAsString = if isnothing(modelPath); "" else string(modelPath) end println(" TestMultiReturningFunction10: Test output from function myBuildFunction at modelPath = \"$modelPathAsString\":\n Code could be constructed here and merged to the model with buildOption=$buildOption") return nothing end MyModelWithBuild(; kwargs...) = Model(; _buildFunction = :myBuildFunction, kwargs...) Mbs(; kwargs...) = Par(; _constructor = :(MbsData), _path = true, kwargs...) function copy_from_x(mbs::MbsData, x, ibeg, iend) end function copy_to_der_x(mbs::MbsData, der_x, ibeg, iend) end function setStates(mbs::MbsData, phi1, w1)::MbsData mbs.phi1 = phi1 mbs.w1 = w1 return mbs end function setAccelerations1(mbs::MbsData,derw1)::MbsData mbs.derw1 = derw1 return mbs end function setAccelerations2(mbs::MbsData,derw2)::MbsData mbs.derw2 = derw2 return mbs end function computeForcesAndResiduals(mbs::MbsData,time) # m*L^2*derw + m*g*l*sin(phi) ) = u # m=L=g=1 # derw + sin(phi) = 0 mbs.u1 = mbs.derw1 + sin(mbs.phi1) mbs.residuals2 = (1+time)*mbs.derw2 + sin.(mbs.phi2) return mbs end function getForces(mbs::MbsData) return mbs.u1 end function getResiduals(mbs::MbsData) return mbs.residuals2 end Pendulum = MyModelWithBuild(_buildOption = "MyBuildOption", phi1 = Var(init=pi/2), w1 = Var(init=0.0), qdd = Var(start=zeros(2)), mbs = Mbs(phi2=[1.0,2.0]), mbs1 = Var(hideResult=true), mbs2 = Var(hideResult=true), mbs3 = Var(hideResult=true), mbs4 = Var(hideResult=true), equations = :[ w1 = der(phi1) mbs1 = setStates(mbs,phi1,w1) mbs2 = setAccelerations1(mbs1,der(w1)) mbs3 = setAccelerations2(mbs2,qdd) mbs4 = computeForcesAndResiduals(mbs3,time) tau1 = implicitDependency(getForces(mbs4), der(w1)) 0 = implicitDependency(getResiduals(mbs4), qdd) tau1 = -0.1*w1 ] ) pendulum = @instantiateModel(Pendulum , unitless=true, log=false, logDetails=false, logCode=true, logStateSelection=false) simulate!(pendulum, stopTime = 2.0, log=true) printResultInfo(pendulum) plot(pendulum, [("phi1", "w1"), "der(w1)", "qdd"]) simulate!(pendulum, stopTime = 2.0, log=true, merge=Map(mbs = Mbs(phi2=[10.0,20.0,30.0]), qdd = zeros(3))) plot(pendulum, [("phi1", "w1"), "der(w1)", "qdd"], figure=2) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1288
module TestMultiReturningFunction4A using ModiaBase.StaticArrays using ModiaLang @usingModiaPlot mutable struct Mbs derw1 derw2 end function twoCoupledInertias(mbs::Mbs,J1,J2,tau0) tau1 = tau0 - J1*mbs.derw1 tau2 = tau1 - J2*mbs.derw2 return (tau1,tau2) end ThreeCoupledInertias = Model( J1 = 1.1, J2 = 1.2, J3 = 1.3, phi1 = Var(init=0.0), phi2 = Var(init=0.0), phi3 = Var(init=0.0), w1 = Var(init=0.0), w2 = Var(init=0.0), w3 = Var(init=0.0), tau1 = Var(start=0.0), tau2 = Var(start=0.0), equations = :[ tau0 = sin(time/u"s") w1 = der(phi1) w2 = der(phi2) w3 = der(phi3) phi2 = phi1 phi3 = phi2 mbs = Mbs(der(w1), der(w2)) (tau1,tau2) = twoCoupledInertias(mbs,J1,J2,tau0) J3*der(w3) = tau2 ] ) threeCoupledInertias = @instantiateModel(ThreeCoupledInertias, unitless=true, log=false, logDetails=false, logCode=true, logStateSelection=false) simulate!(threeCoupledInertias, stopTime = 2.0, log=true, requiredFinalStates=[0.3933746028781301, 0.3029735305821084]) plot(threeCoupledInertias, [("phi1", "phi2", "phi3"), ("w1","w2","w3"), ("tau0", "tau1", "tau2")]) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1018
module TestMultiReturningFunction5A using ModiaLang @usingModiaPlot mutable struct Mbs phi w derw end function setStates(phi, w) return Mbs(phi,w,0.0) end function setAccelerations(mbs::Mbs,derw)::Mbs mbs.derw = derw return mbs end function getForces(mbs::Mbs) # m*L^2*derw + m*g*l*sin(phi) ) = u # m=L=g=1 # derw + sin(phi) = 0 u = mbs.derw + sin(mbs.phi) return u end Pendulum = Model( d = 1.0, # damping constant phi = Var(init=pi/2), w = Var(init=0.0), equations = :[ w = der(phi) mbs1 = setStates(phi,w) mbs2 = setAccelerations(mbs1,der(w)) u = implicitDependency(getForces(mbs2),der(w)) u = -d*w ] ) pendulum = @instantiateModel(Pendulum , unitless=true, log=false, logDetails=false, logCode=false, logStateSelection=true) simulate!(pendulum, stopTime = 10.0, log=true, requiredFinalStates= [-0.012169911296941314, 0.0024087599260249094]) plot(pendulum, ("phi", "w")) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1426
module TestMultiReturningFunction6 using ModiaBase.StaticArrays using ModiaLang @usingModiaPlot mutable struct Mbs phi1 w1 phi2 w2 derw1 derw2 Mbs() = new(0,0,0,0,0,0) end function setStates(mbs, phi1, w1, phi2, w2) mbs.phi1 = phi1 mbs.w1 = w1 mbs.phi2 = phi2 mbs.w2 = w2 return mbs end function setAccelerations(mbs::Mbs,derw1,derw2) mbs.derw1 = derw1 mbs.derw2 = derw2 return mbs end function getForces(mbs::Mbs) # m*L^2*derw + m*g*l*sin(phi) ) = u # m=L=g=1 # derw + sin(phi) = 0 u1 = mbs.derw1 + sin(mbs.phi1) u2 = mbs.derw2 + sin(mbs.phi2) return SVector(u1,u2) end implicitDependency(x...) = nothing Pendulum = Model( phi1 = Var(init=pi/2), w1 = Var(init=0.0), phi2 = Var(init=pi/4), w2 = Var(init=0.0), mbs = Mbs(), equations = :[ w1 = der(phi1) w2 = der(phi2) mbs1 = setStates(mbs,phi1,w1,phi2,w2) mbs2 = setAccelerations(mbs1,der(w1),der(w2)) (0,0) = implicitDependency(getForces(mbs2), mbs1,der(w1),der(w2)) ] ) pendulum = @instantiateModel(Pendulum , unitless=true, log=false, logDetails=false, logCode=false, logStateSelection=false) simulate!(pendulum, stopTime = 10.0, log=true,requiredFinalStates=[-1.0810242374611811, -0.9468374084033309, 0.13969589909383123, -0.7714994595239327]) plot(pendulum, ("phi1", "w1", "phi2", "w2")) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1340
module TestMultiReturningFunction7A using ModiaLang.StaticArrays using ModiaLang @usingModiaPlot mutable struct Mbs phi1 w1 phi2 w2 derw1 derw2 Mbs() = new(0,0,0,0,0,0) end function setStates(mbs, phi1, w1, phi2, w2) mbs.phi1 = phi1 mbs.w1 = w1 mbs.phi2 = phi2 mbs.w2 = w2 return mbs end function setAccelerations(mbs::Mbs,derw1,derw2) mbs.derw1 = derw1 mbs.derw2 = derw2 return mbs end function getForces(mbs::Mbs) # m*L^2*derw + m*g*l*sin(phi) ) = u # m=L=g=1 # derw + sin(phi) = 0 u1 = mbs.derw1 + sin(mbs.phi1) u2 = mbs.derw2 + sin(mbs.phi2) return SVector(u1,u2) end Pendulum = Model( phi1 = Var(init=pi/2), w1 = Var(init=0.0), phi2 = Var(init=pi/4), w2 = Var(init=0.0), mbs = Mbs(), equations = :[ w1 = der(phi1) w2 = der(phi2) mbs1 = setStates(mbs,phi1,w1,phi2,w2) (0,0) = getForces(setAccelerations(mbs1,der(w1),der(w2))) ] ) pendulum = @instantiateModel(Pendulum , unitless=true, log=false, logDetails=false, logCode=false, logStateSelection=false) simulate!(pendulum, stopTime = 2.0, log=true, requiredFinalStates=[-1.399248030722412, -0.20564002545046062, -0.7148846477289476, -0.2742354977425878]) plot(pendulum, ("phi1", "w1", "phi2", "w2")) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1730
module TestParameter using ModiaLang @usingModiaPlot using Test include("$(ModiaLang.path)/models/Blocks.jl") inputSignal(t) = sin(t) FirstOrder = Model( T = parameter | Var(value=0.2), x = Var(init=0.3), equations = :[u = inputSignal(time/u"s"), T * der(x) + x = u, y = 2*x] ) firstOrder = @instantiateModel(FirstOrder) simulate!(firstOrder, Tsit5(), stopTime = 10, log=false, logParameters=false, logEvaluatedParameters=false, requiredFinalStates = [-0.3617373025974107]) plot(firstOrder, ["u", "x", "der(x)", "y"], figure=1) # 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 SecondOrder = Model( w = 20.0, D = 0.1, k = 2.0, sys = StateSpace | Map(A = parameter | :([ 0 1; -w^2 -2*D*w]), B = parameter | :([0; w^2]), C = parameter | :([k 0]), D = parameter | :(zeros(1)), x = Var(init = zeros(2))), equations = :[sys.u = 1.0] ) @test_skip begin secondOrder = @instantiateModel(SecondOrder, unitless=true) simulate!(secondOrder, merge=Map(D=0.3), logParameters=true, logEvaluatedParameters=true, requiredFinalStates = [0.9974089572681231, 0.011808652820321723]) plot(secondOrder, [("sys.u", "sys.y"); "sys.x"], figure = 2) simulate!(secondOrder, merge=Map(w=100.0, D=0.1, k=1.1), logParameters=true, logEvaluatedParameters=true, requiredFinalStates = [0.9999806306477742, -0.00391695258236727]) plot(secondOrder, [("sys.u", "sys.y"); "sys.x"], figure = 3) end end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1991
module TestPath using ModiaLang using ModiaLang.Measurements @usingModiaPlot const ptp_path = PTP_path(["angle1", "angle2", "angle3"], positions = [0.0 2.0 3.0; # angle1=0.0, angle2=2.0, angle3=3.0 0.5 3.0 4.0; 0.8 1.5 0.3; 0.2 1.5 0.8], startTime = (0.1/60)u"minute", v_max = 2*ones(3), a_max = 3*ones(3)) angles = zeros(3) getPosition!(ptp_path, 0.5, angles) # angles = [0.12, 2.24, 3.24] path = getPath(ptp_path) printResultInfo(path) plot(path, [("angle1", "angle2", "angle3"), ("der(angle1)", "der(angle2)", "der(angle3)"), ("der2(angle1)", "der2(angle2)", "der2(angle3)")], figure=1) plotPath(ptp_path,plot,onlyPositions=false, heading="ptp_path", figure=2) nom(v) = measurement(v) err(v) = v ± (0.1*v) const ptp_path2 = PTP_path{Measurement{Float64}}( ["angle1", "angle2", "angle3"], positions = [nom(0.0) nom(2.0) nom(3.0); # angle1=0.0, angle2=2.0, angle3=3.0 err(0.5) err(3.0) err(4.0); err(0.8) err(1.5) err(0.3); err(0.2) err(1.5) err(0.8)], startTime = nom(0.1), v_max = fill(measurement(2.0),3), a_max = fill(measurement(3.0),3)) angles = zeros(Measurement{Float64}, 3) getPosition!(ptp_path2, nom(0.5), angles) # angles = [0.12, 2.24, 3.24] path2 = getPath(ptp_path2) printResultInfo(path2) plot(path2, [("angle1", "angle2", "angle3"), ("der(angle1)", "der(angle2)", "der(angle3)"), ("der2(angle1)", "der2(angle2)", "der2(angle3)")], figure=3) plotPath(ptp_path2,plot,onlyPositions=false, heading="ptp_path2", figure=4) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
609
module TestSimpleStateEvents using ModiaLang @usingModiaPlot SimpleStateEvents = Model( fmax = 1.5, m = 1.0, k = 1.0, d = 0.1, s = Var(init = 2.0), v = Var(init = 0.0), equations = :[ sPos = positive(s) f = if sPos; 0.0 else fmax end # or: f = sPos ? 0.0 : fmax v = der(s) m*der(v) + d*v + k*s = f ] ) model = @instantiateModel(SimpleStateEvents) simulate!(model, Tsit5(), stopTime = 10, log=false, logEvents=false, requiredFinalStates = [1.1756992201144405, -0.5351307571761175]) plot(model, ["s", "v", "sPos", "f"]) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
3081
module TestSingularLRRL using ModiaLang @usingModiaPlot 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, unitless=true) 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, unitless=true, 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
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
293
module TestSource using ModiaLang @usingModiaPlot SineSource = Model( f = 2.0, equations = :[y = sin(2*3.14*f*time)] ) sineSource = @instantiateModel(SineSource, unitless=true) simulate!(sineSource, Tsit5(), stopTime = 1.0, log=false, logStates=false) plot(sineSource, "y") end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
6983
module TestStateSelection using ModiaLang 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"], [(["der(J1_w)"], [], [1], 1, 1)]) end @testset "... Test ODE with linear equations 1" begin ODEwithLinearEquations1 = Model( p1 = 4.0, 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( x2 = Var(init = 0.0), x2d = Var(init = 0.0), 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 #= Does not yet work, because Pantelides does not yet support arrays @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 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"), equations = :[ 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) simulate!(drive1, Tsit5(), stopTime = 4.0) println("Next simulate! should result in an error:\n") simulate!(drive2, Tsit5(), stopTime = 4.0) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1801
module TestStateSpace using ModiaLang @usingModiaPlot include("$(ModiaLang.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, stopTime=1.0, 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(), stopTime=1.0, 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(), stopTime=1.0, 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
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
2011
module TestSynchronous #println("\nSynchronousExamples: Demonstrating the ability to simulate models with synchronous semantics") using ModiaLang @usingModiaPlot MassWithSpringDamper = Model( m = 1.0, k = 1.0, # spring constant d = 0.1, # damping coefficient x = Var(init=0.0), # Position v = Var(init=5.0), # Velocity equations = :[ der(x) = v m*der(v) = f - k*x - d*v ] ) SpeedControl = MassWithSpringDamper | Model( k = 0.0, K = 5.0, # Gain of speed P controller vref = 100.0, # Speed ref. vd = Var(start=0.0), u = Var(start=0.0), equations = :[ vd = sample(v, Clock(0.1)) # speed sensor u = K*(vref-vd) # P controller for speed f = hold(u, Clock(0.1)) # force actuator ] ) speedControl = @instantiateModel(SpeedControl) simulate!(speedControl, Tsit5(), stopTime=1.5, logEvents=false, requiredFinalStates = [133.3845202465569, 98.03694943140056] ) plot(speedControl, [("v", "vd"), ("u","f")], heading="SpeedControl", figure=1) SpeedControlPI = MassWithSpringDamper | Model( k = 0.0, K = 5.0, # Gain of speed P controller Ti = 2, # Integral time vref = 100.0, # Speed ref. dt = 0.1, # sampling interval vd = Var(start=0.0), u = Var(start=0.0), e = Var(start=0.0), intE = Var(start=10.0), # To check that previous(intE) is corrected initialized equations = :[ vd = sample(v, Clock(0.1)) # speed sensor # PI controller for speed e = vref-vd previous_intE = previous(intE, Clock(0.1)) intE = previous_intE + e u = K*(e + intE/Ti) # force actuator f = hold(u, Clock(0.1)) ] ) speedControlPI = @instantiateModel(SpeedControlPI) simulate!(speedControlPI, Tsit5(), stopTime=1.5, logEvents=false, requiredFinalStates = [145.828878491462, 99.95723678839984]) plot(speedControlPI, [("v", "vd"), ("u","f"), ("previous_intE", "intE")], heading="SpeedControlPI", figure=2) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
2052
module TestTwoInertiasAndIdealGear using ModiaLang @usingModiaPlot using Test 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, unitless=true) twoInertiasAndIdealGear = @instantiateModel(TwoInertiasAndIdealGear, unitless=true) println("Next simulate! should result in an error:\n") simulate!(twoInertiasAndIdealGearTooManyInits, Tsit5(), stopTime = 4.0, log=true) simulate!(twoInertiasAndIdealGear, Tsit5(), stopTime = 4.0, log=true, logParameters=true, logStates=true, requiredFinalStates=[1.5628074713622309, -6.878080753044174e-5]) plot(twoInertiasAndIdealGear, ["phi2", "w2"]) simulate!(twoInertiasAndIdealGear, stopTime = 4.0, useRecursiveFactorizationUptoSize = 500, log=true, logParameters=true, logStates=true, requiredFinalStates=missing) # Linearize println("\n... Linearize at stopTime = 0 and 4") (A_0, x_0) = linearize!(twoInertiasAndIdealGear, stopTime=0, analytic = true) (A_4, x_4) = linearize!(twoInertiasAndIdealGear, stopTime=4, analytic = true) (A_4_numeric, x_4_numeric) = linearize!(twoInertiasAndIdealGear, stopTime=4, analytic=false) xNames = get_xNames(twoInertiasAndIdealGear) @show xNames @show A_0, x_0 @show A_4, x_4 @show A_4_numeric, x_4_numeric @test isapprox(A_0,[0.0 1.0; 0.0 0.0]) @test isapprox(A_0, A_4) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1339
module TestTwoInertiasAndIdealGearWithMonteCarlo using ModiaLang @usingModiaPlot using ModiaLang.MonteCarloMeasurements using ModiaLang.MonteCarloMeasurements.Distributions # 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, unitless=true, FloatType = StaticParticles{Float64,nparticles}) simulate!(twoInertiasAndIdealGearWithMonteCarlo, Tsit5(), stopTime = 4.0, logParameters=true, logStates=true) plot(twoInertiasAndIdealGearWithMonteCarlo, ["phi2", "w2"], MonteCarloAsArea=false) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1458
module TestTwoInertiasAndIdealGearWithUnits using ModiaLang @usingModiaPlot using Test TwoInertiasAndIdealGearWithUnits = Model( J1 = 0.0025u"kg*m^2", J2 = 170u"kg*m^2", r = 105.0, 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, logCode=true) simulate!(twoInertiasAndIdealGearWithUnits, Tsit5(), stopTime = 4.0, logParameters=true, logStates=true, requiredFinalStates=[1.5628074713622309, -6.878080753044174e-5]) plot(twoInertiasAndIdealGearWithUnits, ["phi2", "w2", "der(w2)"]) # Linearize println("\n... Linearize at stopTime = 0 and 4") (A0, x0) = linearize!(twoInertiasAndIdealGearWithUnits, stopTime=0, analytic = true) (A1, x1) = linearize!(twoInertiasAndIdealGearWithUnits, stopTime=4, analytic = true) xNames = get_xNames(twoInertiasAndIdealGearWithUnits) @show xNames @show A0, x0 @show A1, x1 @test isapprox(A0,[0.0 1.0; 0.0 0.0]) @test isapprox(A0, A1) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1315
module TestTwoInertiasAndIdealGearWithUnitsAndMonteCarlo using ModiaLang @usingModiaPlot using ModiaLang.MonteCarloMeasurements using ModiaLang.MonteCarloMeasurements.Distributions # 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", 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"; 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}, logCode=true) simulate!(twoInertiasAndIdealGear, Tsit5(), stopTime = 4.0, logProgress=true) plot(twoInertiasAndIdealGear, ["phi2", "w2"]) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1825
module TestTwoInertiasAndIdealGearWithUnitsAndUncertainties using ModiaLang @usingModiaPlot using ModiaLang.Measurements 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)"]) # Linearize println("\n... Analytic linearization") (A1, x1) = linearize!(twoInertiasAndIdealGear, stopTime=4, analytic = true) xNames = get_xNames(twoInertiasAndIdealGear) @show xNames println(IOContext(stdout, :error_digits=>15), "A1 = ", A1, ", x1 = ", x1) println("\n... Numeric linearization with Float64") (A2, x2) = linearize!(twoInertiasAndIdealGear, stopTime=4, analytic=false) println(IOContext(stdout, :error_digits=>15), "A2 = ", A2, ", x2 = ", x2) #= DoubleFloats not defined using Test println("\n... Numeric linearization with Double64") using DoubleFloats twoInertiasAndIdealGear2 = SimulationModel{Measurement{Double64}}(twoInertiasAndIdealGear) (A3, x3) = linearize!(twoInertiasAndIdealGear2, stopTime=3, analytic=false) println(IOContext(stdout, :error_digits=>15), "A3 = ", A3, ", x3 = ", x3) =# end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1988
module TestUncertainties using ModiaLang @usingModiaPlot using ModiaLang.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
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
617
module TestUnits using ModiaLang @usingModiaPlot UnitTest = Model( T = 0.2u"s", u0 = 8.5u"kg", k = 1u"kg^-1", m = 10u"kg", F = 20u"N", x = Var(init = 5.5u"kg"), # 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 = [8.479786015016273, 2.999999999999999]) #plot(model, ["T", "x", "der(x)", "y", "a", "der(v)"]) plot(model, ["x", "der(x)", "y", "a", "der(v)"]) end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
638
module TestUnitsAndUncertainites using ModiaLang @usingModiaPlot using ModiaLang.Measurements 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
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1735
module TestVar using ModiaLang.Measurements using ModiaLang.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
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
3295
module TestVar using ModiaLang using ModiaLang.Measurements using ModiaLang.StaticArrays 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
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
2331
module TestVar using ModiaLang using ModiaLang.Measurements using ModiaLang.StaticArrays 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
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1955
module TestVariables using ModiaLang @usingModiaPlot using ModiaLang.Measurements using ModiaLang.StaticArrays using ModiaLang.Test @testset "... Test variable declarations" begin v1 = input | output | flow | Var(min=0, nominal=10, init=5) @test isequal(v1, Var(input = true, output = true, flow = true, min = 0, nominal = 10, init = 5)) v2 = parameter | 5 | Var(info="v2 info") @test isequal(v2, Var(parameter = true, value = 5, info = "v2 info")) v3 = "string value" | parameter | info"v3 info" @test v3 == Var(parameter = true, value = "string value", info = "v3 info") v4 = parameter | 5.5u"m/s" | Var(min=0) @test isequal(v4, Var(parameter = true, value = 5.5u"m*s^-1", min = 0)) v5 = parameter | Var(5, min=0) @test isequal(v5, Var(parameter = true, min = 0, value = 5)) Pin = Model( v = potential | Var(nominal=10), i = flow ) @test isequal(Pin, Model(v = Var(potential = true, nominal = 10), i = Var(flow = true))) v6 = Var(2.0) @test isequal(v6, Var(value = 2.0)) v7 = Var(2.0 ± 0.1) @test isequal(v7, Var(value = 2.0 ± 0.1)) v8 = Var(SVector(1.0, 2.0, 3.0)) @test isequal(v8, Var(value = [1.0, 2.0, 3.0])) v9 = v4 | Var(parameter=false) @test isequal(v9, Var(parameter = false, value = 5.5u"m*s^-1", min = 0)) v10 = v4 | Var(parameter=nothing) @test isequal(v10, Var(value = 5.5u"m*s^-1", min = 0)) v11 = v4 | interval(1,10) @test isequal(v11, 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", # Not used x = Var(init=0), y = Var(start=0), # Not used equations = :[ der(x) = p*x + 1 ] ) # @showModel TestVar1 model = @instantiateModel(TestVar1, logCode=true) simulate!(model, stopTime= 1, requiredFinalStates = [1-exp(-1)]) plot(model, "x") simulate!(model, stopTime= 1, merge=Map(p=-2, x=2), requiredFinalStates = [2-1.5*(1-exp(-2))]) plot(model, "x") end end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
1726
import ModiaLang import ModiaLang.Test Test.@testset "Test basic functionality" begin include("TestVariables.jl") include("TestFirstOrder.jl") include("TestFirstOrder2.jl") include("TestSource.jl") include("TestStateSelection.jl") include("TestFilterCircuit.jl") include("TestFilterCircuit2.jl") include("TestArrays.jl") end Test.@testset "Test units, uncertainties" begin include("TestUnits.jl") include("TestUncertainties.jl") include("TestUnitsAndUncertainties.jl") include("TestTwoInertiasAndIdealGear.jl") include("TestTwoInertiasAndIdealGearWithUnits.jl") include("TestTwoInertiasAndIdealGearWithUnitsAndUncertainties.jl") include("TestTwoInertiasAndIdealGearWithMonteCarlo.jl") include("TestTwoInertiasAndIdealGearWithUnitsAndMonteCarlo.jl") include("TestLinearEquationSystemWithUnitsAndMonteCarlo.jl") end Test.@testset "Test model components" begin include("TestSingularLRRL.jl") include("TestStateSpace.jl") include("TestParameter.jl") include("TestHeatTransfer.jl") end Test.@testset "Test events, etc." begin include("TestSimpleStateEvents.jl") include("TestSynchronous.jl") include("TestInputOutput.jl") include("TestPathPlanning.jl") include("TestExtraSimulateKeywordArguments.jl") #Test.@test_skip include("TestBouncingBall.jl") end Test.@testset "Test multi returning functions" begin include("TestMultiReturningFunction.jl") include("TestMultiReturningFunction4A.jl") include("TestMultiReturningFunction5A.jl") include("TestMultiReturningFunction6.jl") include("TestMultiReturningFunction7A.jl") include("TestMultiReturningFunction10.jl") end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
374
module Runtests # Run all tests with SilentNoPlot (so not plots) using ModiaLang using ModiaLang.Test const test_title = "Test ModiaLang (version=$(ModiaLang.Version) with SilentNoPlot)" println("\n... $test_title") @time @testset verbose=true "$test_title" begin usePlotPackage("SilentNoPlot") include("include_all.jl") usePreviousPlotPackage() end end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
code
264
module Runtests_withPlot using ModiaLang using ModiaLang.Test const test_title = "Test ModiaLang (version=$(ModiaLang.Version) with " * currentPlotPackage() * ")" println("\n... $test_title") @testset "$test_title" begin include("include_all.jl") end end
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
docs
1066
# ModiaLang.jl [![The MIT License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/ModiaSim/ModiaLang.jl/blob/master/LICENSE.md) ModiaLang is part of [ModiaSim](https://modiasim.github.io/docs/). ModiaLang is usually used via [Modia](https://github.com/ModiaSim/Modia.jl). ModiaLang provides the core equation-based language of Modia, transformation of a model to ODE form dx/dt = f(x,t) and a thin interface to [DifferentialEquations](https://github.com/SciML/DifferentialEquations.jl). ## Installation Typically, a user installs [Modia](https://github.com/ModiaSim/Modia.jl) and does not need to install ModiaLang separately. If needed, ModiaLang is installed with (Julia >= 1.5 is required): ```julia julia> ]add ModiaLang ``` ## 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)
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
0.11.3
2557b26a61b61ebcd34cbe0c36b160b707bbf5df
docs
14976
# ModiaLang Documentation [ModiaLang](https://github.com/ModiaSim/ModiaLang.jl) is an 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 ModiaLang is included in [Modia](https://github.com/ModiaSim/Modia.jl) and is available, when Modia was installed. A standalone ModiaLang version is installed with: ```julia julia> ]add ModiaLang ``` Furthermore, one or more of the following packages should be installed in order to be able to generate plots: ```julia julia> ]add ModiaPlot_PyPlot # if plotting with PyPlot desired add ModiaPlot_GLMakie # if plotting with GLMakie desired add ModiaPlot_WGLMakie # if plotting with WGLMakie desired add ModiaPlot_CairoMakie # if plotting with CairoMakie desired ``` ## Release Notes ### Version 0.11.3 - @instantiateModel(..): `Var(hideResult=true)` is no longer ignored if present in a sub-component. - simulate!(..): Unnecessary evaluation of the parameters dictionary is avoided (if merge = missing, nothing or has no elements). ### Version 0.11.2 - Minor (efficiency) improvement if states are SVectors. - Require ModiaBase 0.9.2 (to get rid of performance issues in Modia3D). - Replace ustrip(..) with ustrip.(..) at some places to get rid of warnings. ### Version 0.11.1 - Update of Manifest.toml file - Require ModiaBase 0.9.1 (with updated Manifest.toml file) ### Version 0.11.0 Non-backwards compatible changes - Equations can only be defined with key `equations` and no other key. - Parameter values in the code are now type cast to the type of the parameter value from the `@instantiatedModel(..)` call. The benefit is that access of parameter values in the code is type stable and operations with the parameter value are more efficient and at run-time no memory is allocated. Existing models can no longer be simulated, if parameter values provided via `simulate!(.., merge=xx)` are not type compatible to their definition. For example, an error is thrown if the @instantedModel(..) uses a Float64 value and the `simulate!(.., merge=xx)` uses a `Measurement{Float64}` value for the same parameter Other changes - Hierarchical names in function calls supported (e.g. `a.b.c.fc(..)`). - Functions can return multiple values, e.g. `(tau1,tau2) = generalizedForces(derw1, derw2)`. - Support for StaticArrays variables (the StaticArrays feature is kept in the generated AST). For an example, see `ModiaLang/test/TestArrays.jl`. - Support for Array variables (especially of state and tearing variables) where the dimension can change after `@instantiateModel(..)`. For examples, see `ModiaLang/test/TestArrays.jl` and `TestMultiReturningFunction10.jl`. - New keyword `Var(hideResult=true)` removes variable from the result (has no effect on states, derivative of states and parameters). For an example, see `ModiaLang/test/TestMultiReturningFunction10.jl` - New feature of @instantiatedModel(..): If a Model(..) has key `:_buildFunction`, call this function to merge additional code to the model. For details see the docu of function buildSubModels! in ModiaLang.jl. For examples, see `ModiaLang/test/TestMultiReturningFunction10.jl` and constructor `Model3D(..)` in `Modia3D/src/ModiaInterface/model3D.jl` and `Modia3D/src/ModiaInterface/buildModia3D.jl`. - Generalized connection semantics. - Functions converting model to/from JSON: `modelToJSON(model)`, `JSONtoModel(json_string)` - `simulate!(..):` - New option `logProgress=false` in function `simulate!(..)` to print current simulation time every 5s (cpu-time). - If tolerance is too small, a warning is prented and it is automatically enlarged to a meaningful value (e.g. tolerance = 1e-8 is not useful if `FloatType=Float32`) - Logging improved: If log=true or logTiming=true, then timing, memory allocation and compilation time is reported for initialization (ths includes compilation of the generated getDerivatives(..) function). The remaining log shows cpu-time and memory allocation **without** initialization (and without the resources needed to compile getDerivatives(..)). - Prefix messages of the timers with "ModiaLang" or "DifferentialEquations" to more clearly see the origin of a message in the timer log. - Large speedup of symbolic transformation, if function depends on many input (and output) arguments (includes new operator `implicitDependency(..)`). - Included DAE-Mode in solution of linear equation system (if DAE integrator is used and all unknowns of a linear equation system are part of the DAE states, solve the linear equation system during continuous integration via DAE solver (= usually large simulation speed-up, for larger linear equation systems) Bug fixes - If unitless=true, units in instantiatedModel.evaluatedParameters are removed. - The unit macro is kept in the generated code and is no longer expanded. For example, `u"N"`, is kept in the code that is displayed with `logCode=true` (previously, this was expanded and the unit was displayed in the code as `N` which is not correct Julia code). - Function `ModiaLang.firstInitialOfAllSegments(..)` now correctly returns true for the first call of the getDerivatives function during the simulation. ### Version 0.10.2 - Minor (efficiency) improvement if states are SVectors. - Require ModiaBase 0.9.2 (to get rid of performance issues in Modia3D). - Replace ustrip(..) with ustrip.(..) at some places to get rid of warnings. ### Version 0.10.1 - Update of Manifest.toml file - Require ModiaBase 0.9.1 (with updated Manifest.toml file). ### Version 0.10.0 - Require DifferentialEquations.jl version 7. - Cleanup of using/export - Cleanup of Project.toml/Manifest.toml.´ - @reexport using Unitful - @reexport using DifferentialEquations - Cleanup of test files (besides ModiaLang, no other package needed in the environment to run the tests). - Change `SimulationModel{FloatType,ParType,EvaluatedParType,TimeType}` to `SimulationModel{FloatType,TimeType}` ### Version 0.9.1 - New function plotPath to plot a PTP_path - Replace ustrip(..) with ustrip.(..) at some places to get rid of warnings. - Include time in error message, if simulation failed ### Version 0.9.0 - Require Julia 1.7 - Upgrade Manifest.toml to version 2.0 - Update Project.toml/Manifest.toml ### Version 0.8.7 - Packages used in test models, prefixed with ModiaLang. to avoid missing package errors. - Deactivating test with DoubleFloats, since not in Project.toml - Version/date updated ### Version 0.8.6 - Require ModiaResult, version 0.3.9 - Project.toml/Manifest.toml updated ### Version 0.8.5 - simulate!(..): - Trigger an error, if simulation is not successful (retcode is neither :Default nor :Success nor :Terminate) - Use RightRootFind for zero crossings (improves state events based on new DifferentialEquations option) - New keyword argument requiredFinalStates_atol=0.0. - Improve docu (e.g. add return argument solution). - Show correct integrator name QBDF in simulation log (instead of QNDF) - Raise an error, if (relative) tolerance is too small for FloatType - Use FloatType for zero crossing hysteresis, instead of Float64 - If log=true print info about end of initialization. - Support of MonteCarloMeasurements with units + new test model TestLinearEquationSystemWithUnitsAndMonteCarlo.jl - Fixing and activating the deactivated test TestTwoInertiasAndIdealGearWithUnitsAndMonteCarlo.jl. ### Version 0.8.4 - FloatType is included in the name space of Core.eval when evaluating parameters. - Version and Date updated - Included Version in printout of runtests.jl and runtests_withPlot.jl - Print difference of finalStates and requiredFinalStates in case they do not match with the given tolerance. ### Version 0.8.3 - Project.toml, Manifest.toml updated: Require newest version 0.7.7 of ModiaBase (containing a bug fix) - Minor correction of simulate!(log=true) output ### Version 0.8.2 - Issue with tearing fixed: Variables are only explicitly solved, if linear factor is a non-zero literal number (previously a division by zero could occur, if the linear factor became zero during simulation). - Issue with unit of tearing variable fixed, if it is a derivative of a variable (previously, the generated code for unitless=false was wrong, if the tearing variable was a derivative, since the unit was not taken into account). - simulate!(..): - Support DAE integrators, especially IDA() from Sundials. - New keyword `useRecursiveFactorizationUptoSize=0`: Linear equation systems A*v=b are solved with [RecursiveFactorization.jl](https://github.com/YingboMa/RecursiveFactorization.jl) instead of the default `lu!(..)` and `ldiv!(..)`, if `length(v) <= useRecursiveFactorizationUptoSize`. According to `RecursiveFactorization.jl` docu, it is faster as `lu!(..)` with OpenBLAS, for `length(v) <= 500` (typically, more as a factor of two). Since there had been some cases where `lu!(..)!` was successful, but `RecursiveFactorization.jl` failed due to a singular system, the default is to use `lu!(..)!`. - If log=true, sizes of linear equation systems are listed, as well as whether RecursiveFactorization.jl is used for the respective system. - Test for RecursiveFactorization.jl added in TestTwoInertiasAndIdealGear.jl - Some test models corrected (since leading to errors with the above changes). - Updated Project.toml and Manifest.toml with newest versions of packages (including MonteCarloMeasurements, version >= 1) and improved Project.toml file to reduce issues with package constraints ### Version 0.8.1 - Added a minimal documentation, including release notes. - No message anymore, when ModiaLang is started. - Fixed bug that `using ModiaResult` is needed, when calling `@usingModiaPlot`. ### Version 0.8.0 - Improved scalability by using OrderedDicts instead of named tuples for models, variables and parameter modifications. - Speed improvements for structural and symbolic algorithms. - Added support for state events, time events and synchronous operators. - Added support for mixed linear equation systems having Real and Boolean unknowns. - Added support for user-defined components defined by structs and functions (multibody modeling with Modia3D is based on this feature). This makes it possible to utilize algorithms specialized for a component. - Added support for numerical and analytic linearization. - Added support for propagation of parameters (e.g. deep in a model, the value of a parameter can be defined as a function of some top level parameter and this parameter is changed before simulation starts). - New small model libraries Translational.jl and PathPlanning.jl added. - Result storage changed: `sol = simulate!(...)` calls internally `sol = solve(..)` from DifferentialEquations.jl. `sol` contains time and the states at the communication time grid and at events. This is now kept in simulate(..), so the return value of simulate!(..) can be exactly used as if `solve(..)` would have been used directly. - The plot(..) command now supports the following underlying plot packages: [PyPlot](https://github.com/JuliaPy/PyPlot.jl), [GLMakie](https://github.com/JuliaPlots/GLMakie.jl), [WGLMakie](https://github.com/JuliaPlots/WGLMakie.jl), and [CairoMakie](https://github.com/JuliaPlots/CairoMakie.jl). It is also possible to select `NoPlot`, to ignore `plot(..)` calls or `SilenNoPlot` to ignore `plot(..)` calls silently. The latter is useful for `runtests.jl`. Note, often [PyPlot](https://github.com/JuliaPy/PyPlot.jl) is the best choice. Changes that are **not backwards compatible** to version 0.7.x: - Models are OrderedDicts and no longer NamedTuples. - simulate!(..): - If FloatType=Float64 and no algorithm is defined, then Sundials.CVODE\_BDF() is used instead of the default algorithm of DifferentialEquations as in 0.7. The reason is that Modia models are usually large and expensive to evaluate and have often stiff parts, so that multi-step methods are often by far the best choice. CVODE_BDF() seems to be a good choice in many applications (another algorithm should be used, if there are many events, highly oscillatory vibrations, or if all states are non-stiff). - The default value of `stopTime` is equal to `startTime` (which has a default value of 0.0 s), and is no longer 1.0 s. - Plotting is defined slightly differently (`@useModiaPlot`, instead of `using ModiaPlot`). ### Version 0.7.3 - Evaluation and propagation of parameter expressions (also in simulate!(..., merge=Map(...))). Propagation of start/init values of states is not yet supported. - State events supported. ### 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")`. - Functions are called in the scope where macro `@instantiateModel` is called. - New arguments of function `simulate!`: - 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 `Modia/models/HeatTransfer.jl`. - Modia Tutorial improved. - Functions 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).
ModiaLang
https://github.com/ModiaSim/ModiaLang.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
310
using Documenter, Dashboards makedocs( sitename = "Dashboards", format = Documenter.HTML(), modules = [Dashboards], doctest = false, pages = [ "index.md", "API Docs" => "api.md" ] ) deploydocs( repo = "github.com/waralex/Dashboards.jl.git", target = "build" )
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
434
import TOML using OrderedCollections using Conda using PyCall import YAML using Pkg.Artifacts import GitHub import GitHub: gh_get_json, DEFAULT_API using HTTP import JSON using ghr_jll include("generator/generator.jl") sources = TOML.parsefile(joinpath(@__DIR__, "Sources.toml")) build_dir = joinpath(@__DIR__, "build") artifact_file = joinpath(@__DIR__, "..", "Artifacts.toml") generate(ARGS, sources, build_dir, artifact_file)
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
5352
using JSON3 function process_components_meta(metafile) metadata = JSON3.read( read(metafile, String) ) result = [] for (file, props) in metadata name = split(split(string(file), "/")[end], ".")[1] push!(result, make_component_meta(name, props)) end return result end function make_component_meta(name, props) args = filter(filter_arg, props["props"]) regular_args = filter(collect(keys(args))) do name !endswith(string(name), "-*") end wild_args = filter(collect(keys(args))) do name endswith(string(name), "-*") end return OrderedDict( :name => Symbol(name), :args => regular_args, :wild_args => [Symbol(replace(string(a), "-*"=>"")) for a in wild_args], :docstr => docstring(name, args, props["description"]), ) end const _reserved_words = Set( ["baremodule", "begin", "break", "catch", "const", "continue", "do", "else", "elseif", "end", "export", "false", "finally", "for", "function", "global", "if", "import", "let", "local", "macro", "module", "quote", "return", "struct", "true", "try", "using", "while"] ) function is_reserved_world(w) return w in _reserved_words end function filter_arg(argpair) name, props = argpair is_reserved_world(name) && return false if haskey(props, "type") arg_type = props["type"]["name"] return !in(arg_type, ["func", "symbol", "instanceOf"]) end if "flowType" in props arg_type_name = props["flowType"]["name"] if arg_type_name == "signature" # This does the same as the PropTypes filter above, but "func" # is under "type" if "name" is "signature" vs just in "name" if !in("type", props["FlowType"]) || props["FlowType"]["type"] != "object" return false end end return true end return false end function docstring(name, props, description) article = lowercase(first(name)) in ['a', 'e', 'i', 'o', 'u'] ? "An " : "A " result = string( article, name, " component", "\n", description, "\n\n" ) if haskey(props, :children) result *= arg_docstring("children", props[:children]) * "\n" end if haskey(props, :id) result *= arg_docstring("id", props[:id]) * "\n" end other_props = sort( collect(filter(v->!in(v.first, [:children, :id]), props)), lt = (a, b) -> a[1] < b[1] ) result *= join(arg_docstring.(other_props), "\n") return result end _jl_type(::Val{:array}, type_object) = "Array" _jl_type(::Val{:bool}, type_object) = "Bool" _jl_type(::Val{:string}, type_object) = "String" _jl_type(::Val{:object}, type_object) = "Dict" _jl_type(::Val{:any}, type_object) = "Bool | Real | String | Dict | Array" _jl_type(::Val{:element}, type_object) = "dash component" _jl_type(::Val{:node}, type_object) = "a list of or a singular dash component, string or number" _jl_type(::Val{:enum}, type_object) = join( string.( getindex.(type_object["value"], :value) ), ", " ) function _jl_type(::Val{:union}, type_object) join( filter(a->!isempty(a), jl_type.(type_object["value"])), " | " ) end function _jl_type(::Val{:arrayOf}, type_object) result = "Array" if type_object["value"] != "" result *= string(" of ", jl_type(type_object["value"]), "s") end return result end _jl_type(::Val{:objectOf}, type_object) = string("Dict with Strings as keys and values of type ", jl_type(type_object["value"])) function _jl_type(::Val{:shape}, type_object) child_names = join(string.(keys(type_object["value"])), ", ") result = "lists containing elements $(child_names)" result *= join( [ arg_docstring(name, prop, prop["required"], get(prop, "description", ""), 1) for (name, prop) in type_object["value"] ] ) return result end _jl_type(::Val{:exact}, type_object) = _jl_type(Val(:shape), type_object) _jl_type(val, type_object) = "" jl_type(type_object) = _jl_type(Val(Symbol(type_object["name"])), type_object) arg_docstring(name_prop::Pair, indent_num = 0) = arg_docstring(name_prop[1], name_prop[2], indent_num) arg_docstring(name, prop, indent_num = 0) = arg_docstring( string(name), haskey(prop, "type") ? prop["type"] : prop["flowType"], prop["required"], prop["description"], indent_num ) function arg_docstring(prop_name, type_object, required, description, indent_num) typename = jl_type(type_object) indent_spacing = repeat(" ", indent_num) if occursin("\n", typename) return string( indent_spacing, "- `", prop_name, "` ", "(", required ? "required" : "optional", "):", description, ". ", prop_name, " has the following type: ", typename ) end return string( indent_spacing, "- `", prop_name, "` ", "(", isempty(typename) ? "" : string(typename, "; "), required ? "required" : "optional", ")", isempty(description) ? "" : string(": ", description) ) end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
4921
""" install_dash(url, tag) Clone python dash into `dash` folder and install (reinstall) it to current python environment """ function install_dash(url, tag) Conda.pip_interop(true) Conda.pip("uninstall -y", "dash") rm("dash", force = true, recursive = true) mkdir("dash") repo = clone(url, "dash") obj = try LibGit2.GitObject(repo, tag) catch LibGit2.GitObject(repo, "origin/$tag") end source_hash = LibGit2.string(LibGit2.GitHash(obj)) LibGit2.checkout!(repo, source_hash) cd("dash") do Conda.pip("install", "./") end dashmodule = pyimport("dash") println(dashmodule) return dashmodule.__version__ end dash_version() = VersionNumber(pyimport("dash").__version__) dash_module_dir() = dirname(pyimport("dash").__file__) function convert_deps_part(relative, external) result = Dict{Symbol, String}[] for i in eachindex(relative) d = OrderedDict{Symbol, String}() d[:relative_package_path] = relative[i] if !isnothing(external) d[:external_url] = external[i] end push!(result, d) end return result end function convert_deps(pyresources) relative_paths = pyresources["relative_package_path"] external_urls = get(pyresources, "external_url", nothing) result = OrderedDict{Symbol, Any}() result[:namespace] = pyresources["namespace"] if haskey(relative_paths, "prod") result[:prod] = convert_deps_part( relative_paths["prod"], isnothing(external_urls) ? nothing : external_urls["prod"] ) end if haskey(relative_paths, "dev") result[:dev] = convert_deps_part( relative_paths["dev"], isnothing(external_urls) ? nothing : external_urls["dev"] ) end return result end function _process_dist_part!(dict, resource, type) ns_symbol = Symbol(resource["namespace"]) if !haskey(dict, ns_symbol) dict[ns_symbol] = OrderedDict( :namespace => resource["namespace"], :resources => Dict[] ) end data = filter(v->v.first != "namespace", resource) data[:type] = type push!( dict[ns_symbol][:resources], data ) end function convert_resources(js_dist, css_dist) result = OrderedDict{Symbol, Any}() _process_dist_part!.(Ref(result), js_dist, :js) _process_dist_part!.(Ref(result), css_dist, :css) return collect(values(result)) end function deps_files(pyresources) relative_paths = pyresources["relative_package_path"] result = String[] if haskey(relative_paths, "prod") append!(result, relative_paths["prod"]) end if haskey(relative_paths, "dev") append!(result, relative_paths["dev"]) end return result end function resources_files(pyresources) result = String[] for res in pyresources if haskey(res, "relative_package_path") push!(result, res["relative_package_path"]) end if haskey(res, "dev_package_path") push!(result, res["dev_package_path"]) end end return result end function copy_files(resource_dir, files, dest_dir) for f in files full_path = joinpath(resource_dir, f) path_dir = dirname(f) mkpath(joinpath(dest_dir, path_dir)) if isfile(full_path) cp(full_path, joinpath(dest_dir, f); force = true) else @warn "File $f don't exists in $resource_dir, skipped" end end end function renderer_resources(module_name) m = pyimport(module_name) meta = OrderedDict( :version => m.__version__, :js_dist_dependencies => convert_deps(m._js_dist_dependencies[1]), :deps => convert_resources(m._js_dist, hasproperty(m, :_css_dist) ? m._css_dist : []) ) files = vcat(deps_files(m._js_dist_dependencies[1]), resources_files(m._js_dist)) return (dirname(m.__file__), meta, files) end function fill_components_deps!(deps::OrderedDict, files::Vector, module_name) m = pyimport(module_name) js_dist = hasproperty(m, :_js_dist) ? m._js_dist : [] css_dist = hasproperty(m, :_css_dist) ? m._css_dist : [] _process_dist_part!.(Ref(deps), js_dist, :js) _process_dist_part!.(Ref(deps), css_dist, :css) append!(files, vcat(resources_files(js_dist), resources_files(css_dist))) end function components_module_resources(module_name; name, prefix, metadata_file) m = pyimport(module_name) moduledir = dirname(m.__file__) metafile = joinpath(moduledir, metadata_file) if !isfile(metafile) error("meta file $(metadata_file) don't exists for module $(name)") end components = process_components_meta(metafile) meta = OrderedDict( :version => m.__version__, :name => name, :prefix => prefix, :components => components ) return meta end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
5396
function init_deploy_repo(deploy_repo, dest_dir) gh_auth = github_auth(;allow_anonymous=false) gh_username = gh_get_json(DEFAULT_API, "/user"; auth=gh_auth)["login"] try GitHub.repo(deploy_repo; auth=gh_auth) catch e error("Resources repo `$(deploy_repo)` don't exists.") end #Always do new clone if isdir(dest_dir) rm(dest_dir, force = true, recursive = true) end @info("Cloning resources repo from https://github.com/$(deploy_repo) into $(dest_dir)") with_gitcreds(gh_username, gh_auth.token) do creds LibGit2.clone("https://github.com/$(deploy_repo)", dest_dir; credentials=creds) end end function old_build_info(dest_dir) default_info = (dash_version = v"0.0.0", build = 0) meta_path = joinpath(resources_dir(dest_dir), "dash.yaml") !isfile(meta_path) && return default_info try meta = YAML.load_file(meta_path) v = VersionNumber(meta["version"]) build_n = meta["build"] (dash_version = v, build = build_n) catch e @error "error while loading dash.yaml" e return default_info end end function make_new_info(dash_version, old_info) if old_info.dash_version > dash_version error("You try to generate resources for dash $(dash_version), but $(deploy_repo) alredy contains version $(old_info.dash_version)") end build_n = old_info.dash_version == dash_version ? old_info.build + 1 : 0 return (dash_version = dash_version, build = build_n) end function cleanup_deploy(deploy_dir) end resources_dir(deploy_dir) = joinpath(deploy_dir, "resources") function fill_deploy_resources(sources, deploy_dir, info) resources_path = resources_dir(deploy_dir) #cleanup resources rm(resources_path, force = true, recursive = true) mkdir(resources_path) cd(resources_path) do @info "creating dash meta..." dash_meta = OrderedDict( :version => info.dash_version, :build => info.build, :embedded_components => Symbol.(collect(keys(sources["components"]))) ) dash_deps = OrderedDict{Symbol, Any}() dash_deps_files = Vector{String}() for (name, props) in sources["components"] fill_components_deps!(dash_deps, dash_deps_files, props["module"]) end dash_meta[:deps] = collect(values(dash_deps)) YAML.write_file("dash.yaml", dash_meta) mkdir("dash_deps") copy_files(dash_module_dir(), dash_deps_files, "dash_deps") @info "creating dash-renderer meta..." module_src, meta, files = renderer_resources( sources["dash_renderer"]["module"] ) resources_path = realpath( joinpath( module_src, get(sources["dash_renderer"], "resources_path", ".") ) ) YAML.write_file("dash_renderer.yaml", meta) @info "copying dash-renderer resource files..." mkdir("dash_renderer_deps") copy_files(resources_path, files, "dash_renderer_deps/") @info "dash-renderer done" @info "processing components modules..." for (name, props) in sources["components"] @info "processing $name meta..." meta = components_module_resources( props["module"]; name = name, prefix = props["prefix"], metadata_file = props["metadata_file"], ) YAML.write_file("$(name).yaml", meta) end end end deploy_version(info) = VersionNumber( info.dash_version.major, info.dash_version.minor, info.dash_version.patch, info.dash_version.prerelease, (info.build,) ) deploy_tagname(info) = string("v", deploy_version(info)) tarball_name(info) = string( "DashCoreResources.v", info.dash_version, ".tar.gz" ) function push_repo(repo_name, deploy_dir, tag) println("https://github.com/$(repo_name).git") gh_auth = github_auth(;allow_anonymous=false) gh_username = gh_get_json(DEFAULT_API, "/user"; auth=gh_auth)["login"] repo = LibGit2.GitRepo(deploy_dir) LibGit2.add!(repo, ".") commit = LibGit2.commit(repo, "dash core resources build $(tag)") with_gitcreds(gh_username, gh_auth.token) do creds refspecs = ["refs/heads/master"] # Fetch the remote repository, to have the relevant refspecs up to date. LibGit2.fetch( repo; refspecs=refspecs, credentials=creds, ) LibGit2.branch!(repo, "master", string(LibGit2.GitHash(commit)); track="master") LibGit2.push( repo; refspecs=refspecs, remoteurl="https://github.com/$(repo_name).git", credentials=creds, ) end end function upload_to_releases(repo_name, tag, tarball_path; attempts = 3) gh_auth = github_auth(;allow_anonymous=false) for attempt in 1:attempts try ghr() do ghr_path run(`$ghr_path -u $(dirname(repo_name)) -r $(basename(repo_name)) -t $(gh_auth.token) $(tag) $(tarball_path)`) end return catch @info("`ghr` upload step failed, beginning attempt #$(attempt)...") end end error("Unable to upload $(tarball_path) to GitHub repo $(repo_name) on tag $(tag)") end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
2655
include("gitutils.jl") include("github.jl") include("dash.jl") include("components.jl") include("deploy.jl") const HELP = """ Usage: generate.jl [--deploy] [--help] Options: --deploy Deploy resources to repo specified in `Sources.toml` --help Print out this message. """ function generate(ARGS, sources, build_dir, artifact_file) if "--help" in ARGS println(HELP) return nothing end is_deploy = "--deploy" in ARGS deploy_dir = joinpath(build_dir, "deploy") rm(build_dir, force = true, recursive = true) mkdir(build_dir) cd(build_dir) @info "cloning dash..." v = install_dash(sources["dash"]["url"], sources["dash"]["tag"]) dash_version = VersionNumber(v) @info "dash succefully installed" dash_version deploy_repo = sources["deploy"]["repo"] init_deploy_repo(deploy_repo, deploy_dir) old_info = old_build_info(deploy_dir) new_info = make_new_info(dash_version, old_info) @info "filling resources data..." fill_deploy_resources(sources, deploy_dir, new_info) @info "resources data filled" artifact_hash = create_artifact() do dir res_dir = resources_dir(deploy_dir) for name in readdir(res_dir) cp( joinpath(res_dir, name), joinpath(dir, name) ) end end @info "artifact created" artifact_hash if is_deploy @info "pushing repo to https://github.com/$(deploy_repo)..." push_repo(deploy_repo, deploy_dir, deploy_tagname(new_info)) @info "repo pushed" @info "creating tagball..." tarball_hash = archive_artifact(artifact_hash, joinpath(build_dir, tarball_name(new_info))) @info "tagball created" tarball_hash @info "binding artifact..." download_info = ( "https://github.com/$(deploy_repo)/releases/download/$(deploy_tagname(new_info))/$(tarball_name(new_info))", tarball_hash ) bind_artifact!(artifact_file, "dash_resources", artifact_hash, force = true, download_info = [download_info]) @info "artifact binding succefully to" artifact_file cd(deploy_dir) do upload_to_releases(deploy_repo, deploy_tagname(new_info), realpath(joinpath(build_dir, tarball_name(new_info))) ) end else unbind_artifact!(artifact_file, "dash_resources") bind_artifact!(artifact_file, "dash_resources", artifact_hash, force = true, download_info = nothing) @info "artifact binding succefully to" artifact_file end @info "resource generation done!" end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
4351
#= ================ Code copied from BinaryBuilder.jl ============== =# #= Since this code is not part of the public BinaryBuilder interface, it is safer to copy it than to use it directly by adding a dependency to BinaryBuider =# # This is a global github authentication token that is set the first time # we authenticate and then reused const _github_auth = Ref{GitHub.Authorization}() function github_auth(;allow_anonymous::Bool=true) if !isassigned(_github_auth) || !allow_anonymous && isa(_github_auth[], GitHub.AnonymousAuth) # If the user is feeding us a GITHUB_TOKEN token, use it! if length(get(ENV, "GITHUB_TOKEN", "")) >= 40 _github_auth[] = GitHub.authenticate(ENV["GITHUB_TOKEN"]) else if allow_anonymous _github_auth[] = GitHub.AnonymousAuth() else # If we're not allowed to return an anonymous authorization, # then let's create a token. _github_auth[] = GitHub.authenticate(obtain_token()) end end end return _github_auth[] end function obtain_token(; outs=stdout, github_api=GitHub.DEFAULT_API) println(outs) printstyled(outs, "Authenticating with GitHub\n", bold=true) @label retry headers = Dict{String, String}("User-Agent"=>"BinaryBuilder-jl", "Accept"=>"application/json") # Request device authentication flow for BinaryBuilder OAauth APP resp = HTTP.post("https://github.com/login/device/code", headers, "client_id=8c496f428c48a1015b9e&scope=public_repo") if resp.status != 200 GitHub.handle_response_error(resp) end reply = JSON.parse(HTTP.payload(resp, String)) println(outs, """ To continue, we need to authenticate you with GitHub. Please navigate to the following page in your browser and enter the code below: $(HTTP.URIs.unescapeuri(reply["verification_uri"])) ############# # $(reply["user_code"]) # ############# """) interval = reply["interval"] device_code = reply["device_code"] while true # Poll for completion sleep(interval) resp = HTTP.post("https://github.com/login/oauth/access_token", headers, "client_id=8c496f428c48a1015b9e&grant_type=urn:ietf:params:oauth:grant-type:device_code&device_code=$device_code") if resp.status != 200 GitHub.handle_response_error(resp) end token_reply = JSON.parse(HTTP.payload(resp, String)) if haskey(token_reply, "error") error_kind = token_reply["error"] if error_kind == "authorization_pending" continue elseif error_kind == "slow_down" @warn "GitHub Auth rate limit exceeded. Waiting 10s. (This shouldn't happen)" sleep(10) elseif error_kind == "expired_token" @error "Token request expired. Starting over!" @goto retry elseif error_kind == "access_denied" @error "Authentication request canceled by user. Starting over!" @goto retry elseif error_kind in ("unsupported_grant_type", "incorrect_client_credentials", "incorrect_device_code") error("Received error kind $(error_kind). Please file an issue.") else error("Unexpected GitHub login error $(error_kind)") end end token = token_reply["access_token"] print(outs, """ Successfully obtained GitHub authorization token! This token will be used for the rest of this BB session. You will have to re-authenticate for any future session. However, if you wish to bypass this step, you may create a personal access token at """) printstyled("https://github.com/settings/tokens"; bold=true) println("\n and add the token to the") printstyled(outs, "~/.julia/config/startup.jl"; bold=true) println(outs, " file as:") println(outs) printstyled(outs, " ENV[\"GITHUB_TOKEN\"] = <token>"; bold=true) println(outs) println(outs, "This token is sensitive, so only do this in a computing environment you trust.") println(outs) return token end end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
2105
using ProgressMeter import LibGit2 struct GitTransferProgress total_objects::Cuint indexed_objects::Cuint received_objects::Cuint local_objects::Cuint total_deltas::Cuint indexed_deltas::Cuint received_bytes::Csize_t end function transfer_progress(progress::Ptr{GitTransferProgress}, p::Any) progress = unsafe_load(progress) p.n = progress.total_objects if progress.total_deltas != 0 p.desc = "Resolving Deltas: " p.n = progress.total_deltas update!(p, Int(max(1, progress.indexed_deltas))) else update!(p, Int(max(1, progress.received_objects))) end return Cint(0) end """ clone(url::String, source_path::String) Clone a git repository hosted at `url` into `source_path`, with a progress bar displayed to stdout. """ function clone(url::String, source_path::String) # Clone with a progress bar p = Progress(0, 1, "Cloning: ") GC.@preserve p begin callbacks = LibGit2.RemoteCallbacks( transfer_progress=@cfunction( transfer_progress, Cint, (Ptr{GitTransferProgress}, Any) ), payload = p ) fetch_opts = LibGit2.FetchOptions(callbacks=callbacks) clone_opts = LibGit2.CloneOptions(fetch_opts=fetch_opts, bare = Cint(false)) return LibGit2.clone(url, source_path, clone_opts) end end """ with_gitcreds(f, username::AbstractString, password::AbstractString) Calls `f` with an `LibGit2.UserPasswordCredential` object as an argument, constructed from the `username` and `password` values. `with_gitcreds` ensures that the credentials object gets properly shredded after it's no longer necessary. E.g.: ```julia with_gitcreds(user, token) do creds LibGit2.clone("https://github.com/foo/bar.git", "bar"; credentials=creds) end ```` """ function with_gitcreds(f, username::AbstractString, password::AbstractString) creds = LibGit2.UserPasswordCredential(deepcopy(username), deepcopy(password)) try f(creds) finally Base.shred!(creds) end end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
768
function _validate_children(children::Union{Vector, Tuple}, ids::Set{Symbol}) for child in children _validate(child, ids) end end function _validate_children(children::Component, ids::Set{Symbol}) _validate(children, ids) end function _validate_children(children, ids::Set{Symbol}) end function _validate(comp::Component, ids::Set{Symbol}) if hasproperty(comp, :id) && !isnothing(comp.id) id = Symbol(comp.id) id in ids && error("Duplicate component id found in the initial layout: $(id)") push!(ids, id) end hasproperty(comp, :children) && _validate_children(comp.children, ids) end function _validate(non_comp, ids::Set{Symbol}) end function validate(comp::Component) _validate(comp, Set{Symbol}()) end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
3091
module Dash using DashBase import HTTP, JSON3, CodecZlib, MD5 using Sockets using Pkg.Artifacts const ROOT_PATH = realpath(joinpath(@__DIR__, "..")) #const RESOURCE_PATH = realpath(joinpath(ROOT_PATH, "resources")) include("exceptions.jl") include("Components.jl") include("HttpHelpers/HttpHelpers.jl") using .HttpHelpers export dash, Component, callback!, enable_dev_tools!, ClientsideFunction, run_server, PreventUpdate, no_update, @var_str, Input, Output, State, make_handler, callback_context, ALL, MATCH, ALLSMALLER, DashBase include("Contexts/Contexts.jl") include("env.jl") include("utils.jl") include("app.jl") include("resources/application.jl") include("handlers.jl") include("server.jl") include("init.jl") include("components_utils/_components_utils.jl") @doc """ module Dash Julia backend for [Plotly Dash](https://github.com/plotly/dash) # Examples ```julia using Dash app = dash(external_stylesheets=["https://codepen.io/chriddyp/pen/bWLwgP.css"]) do html_div() do dcc_input(id="graphTitle", value="Let's Dance!", type = "text"), html_div(id="outputID"), dcc_graph(id="graph", figure = ( data = [(x = [1,2,3], y = [3,2,8], type="bar")], layout = Dict(:title => "Graph") ) ) end end callback!(app, Output("outputID", "children"), Input("graphTitle","value"), State("graphTitle","type")) do value, type "You've entered: '\$(value)' into a '\$(type)' input control" end callback!(app, Output("graph", "figure"), Input("graphTitle", "value")) do value ( data = [ (x = [1,2,3], y = abs.(randn(3)), type="bar"), (x = [1,2,3], y = abs.(randn(3)), type="scatter", mode = "lines+markers", line = (width = 4,)) ], layout = (title = value,) ) end run_server(app, HTTP.Sockets.localhost, 8050) ``` """ Dash struct ComponentsInfo name::String version::VersionNumber end struct BuildInfo dash_version ::VersionNumber dash_renderer_version::VersionNumber embedded_components::Vector{ComponentsInfo} end function Base.show(io::IO, ::MIME"text/plain", info::BuildInfo) println(io, "Based on python `dash` version: ", info.dash_version) println(io, "\t`dash_renderer` version: ", info.dash_renderer_version) println(io, "Embedded components:") for comp in info.embedded_components println(io, "\t - `", comp.name, "` : ", comp.version) end end function build_info() dash_meta = load_meta("dash") renderer_meta = load_meta("dash_renderer") embedded = Vector{ComponentsInfo}() for name in dash_meta["embedded_components"] meta = load_meta(name) push!(embedded, ComponentsInfo(name, VersionNumber(meta["version"]))) end return BuildInfo( VersionNumber(dash_meta["version"]), VersionNumber(renderer_meta["version"]), embedded ) end @place_embedded_components const _metadata = load_all_metadata() function __init__() setup_renderer_resources() setup_dash_resources() end end # module
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
137
include("app/devtools.jl") include("app/supporttypes.jl") include("app/config.jl") include("app/dashapp.jl") include("app/callbacks.jl")
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
843
const DASH_ENV_PREFIX = "DASH_" dash_env_key(name::String; prefix = DASH_ENV_PREFIX) = prefix * uppercase(name) dash_env(name::String, default = nothing; prefix = DASH_ENV_PREFIX) = get(ENV, dash_env_key(name, prefix = prefix), default) function dash_env(t::Type{T}, name::String, default = nothing; prefix = DASH_ENV_PREFIX) where {T<:Number} key = dash_env_key(name, prefix = prefix) !haskey(ENV, key) && return default return parse(T, lowercase(get(ENV, key, ""))) end dash_env(t::Type{String}, name::String, default = nothing; prefix = DASH_ENV_PREFIX) = dash_env(name, default, prefix = prefix) macro env_default!(name, type = String, default = nothing) name_str = string(name) return esc(:( $name = isnothing($name) ? dash_env($type, $name_str, $default) : $name )) end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
198
struct InvalidCallbackReturnValue <: Exception msg::String end function Base.showerror(io::IO, ex::InvalidCallbackReturnValue) Base.write(io, "Invalid callback return value: ", ex.msg) end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
162
include("handler/index_page.jl") include("handler/state.jl") include("handler/misc.jl") include("handler/callback_context.jl") include("handler/make_handler.jl")
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
59
include("init/resources.jl") include("init/components.jl")
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
2856
""" run_server(app::DashApp, host = HTTP.Sockets.localhost, port = 8050; debug::Bool = false) Run Dash server #Arguments - `app` - Dash application - `host` - host - `port` - port - `debug::Bool = false` - Enable/disable all the dev tools #Examples ```jldoctest julia> app = dash() do html_div() do html_h1("Test Dashboard") end end julia> julia> run_server(handler, HTTP.Sockets.localhost, 8050) ``` """ function run_server(app::DashApp, host = dash_env("HOST", "127.0.0.1", prefix = ""), port = dash_env(Int64, "PORT", 8050, prefix = ""); debug = nothing, dev_tools_ui = nothing, dev_tools_props_check = nothing, dev_tools_serve_dev_bundles = nothing, dev_tools_hot_reload = nothing, dev_tools_hot_reload_interval = nothing, dev_tools_hot_reload_watch_interval = nothing, dev_tools_hot_reload_max_retry = nothing, dev_tools_silence_routes_logging = nothing, dev_tools_prune_errors = nothing ) @env_default!(debug, Bool, false) enable_dev_tools!(app, debug = debug, dev_tools_ui = dev_tools_ui, dev_tools_props_check = dev_tools_props_check, dev_tools_serve_dev_bundles = dev_tools_serve_dev_bundles, dev_tools_hot_reload = dev_tools_hot_reload, dev_tools_hot_reload_interval = dev_tools_hot_reload_interval, dev_tools_hot_reload_watch_interval = dev_tools_hot_reload_watch_interval, dev_tools_hot_reload_max_retry = dev_tools_hot_reload_max_retry, dev_tools_silence_routes_logging = dev_tools_silence_routes_logging, dev_tools_prune_errors = dev_tools_prune_errors ) start_server = () -> begin handler = make_handler(app); server = Sockets.listen(get_inetaddr(host, port)) task = @async HTTP.serve(handler, host, port; server = server) return (server, task) end if get_devsetting(app, :hot_reload) && !is_hot_restart_available() @warn "Hot reloading is disabled for interactive sessions. Please run your app using julia from the command line to take advantage of this feature." end if get_devsetting(app, :hot_reload) && is_hot_restart_available() hot_restart(start_server, check_interval = get_devsetting(app, :hot_reload_watch_interval)) else (server, task) = start_server() try wait(task) catch e close(server) if e isa InterruptException println("finished") return else rethrow(e) end end end end get_inetaddr(host::String, port::Integer) = Sockets.InetAddr(parse(IPAddr, host), port) get_inetaddr(host::IPAddr, port::Integer) = Sockets.InetAddr(host, port)
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
175
include("utils/misc.jl") include("utils/paths.jl") include("utils/fingerprint.jl") include("utils/parse_includes.jl") include("utils/poll.jl") include("utils/hot_restart.jl")
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
1655
module Contexts using DataStructures: Stack export TaskContextStorage, with_context, has_context, get_context mutable struct ContextItem{T} value::T ContextItem(value::T) where {T} = new{T}(value) end struct TaskContextStorage storage::Dict{UInt64, Stack{ContextItem}} guard::ReentrantLock TaskContextStorage() = new(Dict{UInt64, Stack{ContextItem}}(), ReentrantLock()) end #threads are runing as tasks too, so this id also unique for different threads curr_task_id() = objectid(current_task()) #thread unsafe should be used under locks get_curr_stack!(context::TaskContextStorage) = get!(context.storage, curr_task_id(), Stack{ContextItem}()) function Base.push!(context::TaskContextStorage, item::ContextItem) lock(context.guard) do push!(get_curr_stack!(context), item) end end function Base.pop!(context::TaskContextStorage) return lock(context.guard) do return pop!(get_curr_stack!(context)) end end function Base.isempty(context::TaskContextStorage) return lock(context.guard) do return isempty(get_curr_stack!(context)) end end function with_context(f, context::TaskContextStorage, item::ContextItem) push!(context, item) result = f() pop!(context) return result end with_context(f, context::TaskContextStorage, item) = with_context(f, context, ContextItem(item)) has_context(context::TaskContextStorage) = !isempty(context) function get_context(context::TaskContextStorage) return lock(context.guard) do isempty(context) && throw(ArgumentError("context is not set")) return first(get_curr_stack!(context)).value end end end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
195
module HttpHelpers export state_handler, exception_handling_handler, compress_handler, Route, Router, add_route!, handle import HTTP, CodecZlib include("handlers.jl") include("router.jl") end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
3341
struct RequestHandlerFunction <: HTTP.Handler func::Function # func(req) end (x::RequestHandlerFunction)(args...) = x.func(args...) function handle(h::RequestHandlerFunction, request::HTTP.Request, args...) h(request, args...) end function handle(handler::Function, request::HTTP.Request, args...) handler(request, args) end function handle(h::RequestHandlerFunction, request::HTTP.Request, state, args...) h(request, state, args...) end function handle(handler::Function, request::HTTP.Request, state, args...) handler(request, state, args) end function state_handler(base_handler, state) return RequestHandlerFunction( function(request::HTTP.Request, args...) response = handle(base_handler, request, state, args...) if response.status == 200 HTTP.defaultheader!(response, "Content-Type" => HTTP.sniff(response.body)) HTTP.defaultheader!(response, "Content-Length" => string(sizeof(response.body))) end return response end ) end state_handler(base_handler::Function, state) = state_handler(RequestHandlerFunction(base_handler), state) function check_mime(message::HTTP.Message, mime_list) !HTTP.hasheader(message, "Content-Type") && return false mime_type = split(HTTP.header(message, "Content-Type", ""), ';')[1] return mime_type in mime_list end const default_compress_mimes = ["text/plain", "text/html", "text/css", "text/xml", "application/json", "application/javascript", "application/css"] function compress_handler(base_handler; mime_types::Vector{String} = default_compress_mimes, compress_min_size = 500) return RequestHandlerFunction( function(request::HTTP.Request, args...) response = handle(base_handler, request, args...) if response.status == 200 && sizeof(response.body) >= compress_min_size && occursin("gzip", HTTP.header(request, "Accept-Encoding", "")) && check_mime(response, mime_types) HTTP.setheader(response, "Content-Encoding" => "gzip") response.body = transcode(CodecZlib.GzipCompressor, response.body) HTTP.setheader(response, "Content-Length" => string(sizeof(response.body))) end return response end ) end function compress_handler(base_handler::Function; mime_types::Vector{String} = default_compress_mimes, compress_min_size = 500) return compress_handler(RequestHandlerFunction(base_handler), mime_types = mime_types, compress_min_size = compress_min_size) end function exception_handling_handler(ex_handling_func, base_handler) return RequestHandlerFunction( function(request::HTTP.Request, args...) try return handle(base_handler, request, args...) catch e return ex_handling_func(e) end end ) end exception_handling_handler(ex_handling_func, base_handler::Function) = exception_handling_handler(ex_handling_func, RequestHandlerFunction(base_handler)) function request_logging_handler(base_handler; exclude = Regex[]) return RequestHandlerFunction( function(request::HTTP.Request, args...) response = handle(base_handler, request, args...) return response end ) end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
4715
abstract type AbstractRoute end struct StaticRoute <: AbstractRoute url ::String StaticRoute(url) = new(url) end struct DynamicRoute{ST,VT} <: AbstractRoute segments_length ::Int static_segments ::ST variables ::VT tailed::Bool DynamicRoute(segments_length, static_segments::ST, variables::VT, tailed) where {ST, VT} = new{ST, VT}(segments_length, static_segments, variables, tailed) end function DynamicRoute(url::AbstractString) parts = split(url, '/', keepempty = false) segments_vector = Tuple{Int, String}[] variables = Dict{Symbol, Int}() segments_count = 0 for part in parts segments_count += 1 if length(part) > 2 && part[1] == '<' && part[end] == '>' var_name = Symbol(part[2:end-1]) var_name in keys(variables) && ArgumentError("duplicated variable name $(var_name)") variables[var_name] = segments_count elseif part != "*" push!(segments_vector,(segments_count, String(part))) end end #Route is tailed if it url hasn't / at end and the last segment is dynamic tailed = false if url[end] != '/' && (isempty(segments_vector) || segments_vector[end][1] != length(parts)) tailed = true end return DynamicRoute( segments_count, (segments_vector...,), (;variables...), tailed ) end struct RouteHandler{RT <: AbstractRoute, FT <: Function} route::RT handler::FT RouteHandler(route::RT, handler::FT) where {RT <: AbstractRoute, FT <: Function} = new{RT, FT}(route, handler) end function try_handle(route_handler::RouteHandler{StaticRoute, FT}, path::AbstractString, request::HTTP.Request, args...) where {FT} route_handler.route.url != path && return nothing return route_handler.handler(request, args...) end function args_tuple(route::DynamicRoute{ST, NamedTuple{Names, T}}, parts) where {ST, Names, T} return NamedTuple{Names}(getindex.(Ref(parts), values(route.variables))) end function try_handle(route_handler::RouteHandler{<:DynamicRoute, FT}, path::AbstractString, request::HTTP.Request, args...) where {FT} route = route_handler.route parts_length = route.segments_length limit = route.tailed ? parts_length : 0 parts = split(lstrip(path, '/'), '/', limit = limit, keepempty = false) length(parts) != parts_length && return nothing for segment in route.static_segments parts[segment[1]] != segment[2] && return nothing end return route_handler.handler(request, args...;args_tuple(route, parts)...) end function _make_route(url::AbstractString) parts = split(url, '/', keepempty = false) for part in parts if part == "*" || (length(part) > 2 && part[1] == '<' && part[end] == '>') return DynamicRoute(url) end end return StaticRoute(url) end struct Route{RH} method ::Union{Nothing,String} route_handler ::RH Route(method, route_handler::RH) where {RH} = new{RH}(method, route_handler) end function Route(handler::Function, method, path::AbstractString) return Route( method, RouteHandler( _make_route(path), handler ) ) end Route(handler::Function, path::AbstractString) = Route(handler, nothing, path) function try_handle(route::Route, path::AbstractString, request::HTTP.Request, args...) (!isnothing(route.method) && route.method != request.method) && return nothing return try_handle(route.route_handler, path, request, args...) end @inline function _handle(route_tuple::Tuple, path::AbstractString, request::HTTP.Request, args...) res = try_handle(route_tuple[1], path, request, args...) return !isnothing(res) ? res : _handle(Base.tail(route_tuple), path, request, args...) end @inline function _handle(route_tuple::Tuple{}, path::AbstractString, request::HTTP.Request, args...) return HTTP.Response(404) end function handle(route_tuple::Tuple, path::AbstractString, request::HTTP.Request, args...)::HTTP.Response return _handle(route_tuple, path, request, args...) end mutable struct Router routes::Tuple Router() = new(()) Router(routes::Tuple{Vararg{Route}}) = new(routes) end function add_route!(router::Router, route::Route) router.routes = (router.routes..., route) end add_route!(handler::Function, router::Router, method, url) = add_route!(router, Route(handler, method, url)) add_route!(handler::Function, router::Router, url) = add_route!(handler, router, nothing, url) function handle(router::Router, request::HTTP.Request, args...) path = HTTP.URI(request.target).path return handle(router.routes, path, request, args...) end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
5940
dependency_id_string(id::NamedTuple) = sorted_json(id) dependency_id_string(id::String) = sorted_json(id) function dependency_string(dep::Dependency{Trait, String}) where {Trait} return "$(dep.id).$(dep.property)" end function dependency_string(dep::Dependency{Trait, <:NamedTuple}) where {Trait} id_str = replace( sorted_json(dep.id), "."=>"\\." ) return "$(id_str).$(dep.property)" end function output_string(deps::CallbackDeps) if deps.multi_out return ".." * join(dependency_string.(deps.output), "...") * ".." end return dependency_string(deps.output[1]) end """ function callback!(func::Union{Function, ClientsideFunction, String}, app::DashApp, output::Union{Vector{Output}, Output}, input::Union{Vector{Input}, Input}, state::Union{Vector{State}, State} = [] ) Create a callback that updates the output by calling function `func`. # Examples ```julia app = dash() do html_div() do dcc_input(id="graphTitle", value="Let's Dance!", type = "text"), dcc_input(id="graphTitle2", value="Let's Dance!", type = "text"), html_div(id="outputID"), html_div(id="outputID2") end end callback!(app, [Output("outputID2", "children"), Output("outputID", "children")], Input("graphTitle", "value"), State("graphTitle", "type") ) do inputValue, stateType return (stateType * "..." * inputValue, inputValue) end ``` """ function callback!(func::Union{Function, ClientsideFunction, String}, app::DashApp, output::Union{Vector{<:Output}, Output}, input::Union{Vector{<:Input}, Input}, state::Union{Vector{<:State}, State} = State[]; prevent_initial_call = nothing ) return _callback!(func, app, CallbackDeps(output, input, state), prevent_initial_call = prevent_initial_call) end """ function callback!(func::Union{Function, ClientsideFunction, String}, app::DashApp, deps... ) Create a callback that updates the output by calling function `func`. "Flat" version of `callback!` function, `deps` must be ``Output..., Input...[,State...]`` # Examples ```julia app = dash() do html_div() do dcc_input(id="graphTitle", value="Let's Dance!", type = "text"), dcc_input(id="graphTitle2", value="Let's Dance!", type = "text"), html_div(id="outputID"), html_div(id="outputID2") end end callback!(app, Output("outputID2", "children"), Output("outputID", "children"), Input("graphTitle", "value"), State("graphTitle", "type") ) do inputValue, stateType return (stateType * "..." * inputValue, inputValue) end ``` """ function callback!(func::Union{Function, ClientsideFunction, String}, app::DashApp, deps::Dependency...; prevent_initial_call = nothing ) output = Output[] input = Input[] state = State[] _process_callback_args(deps, (output, input, state)) return _callback!(func, app, CallbackDeps(output, input, state, length(output) > 1), prevent_initial_call = prevent_initial_call) end function _process_callback_args(args::Tuple{T, Vararg}, dest::Tuple{Vector{T}, Vararg}) where {T} push!(dest[1], args[1]) _process_callback_args(Base.tail(args), dest) end function _process_callback_args(args::Tuple{}, dest::Tuple{Vector{T}, Vararg}) where {T} end function _process_callback_args(args::Tuple, dest::Tuple{Vector{T}, Vararg}) where {T} _process_callback_args(args, Base.tail(dest)) end function _process_callback_args(args::Tuple, dest::Tuple{}) error("The callback method must received first all Outputs, then all Inputs, then all States") end function _process_callback_args(args::Tuple{}, dest::Tuple{}) end function _callback!(func::Union{Function, ClientsideFunction, String}, app::DashApp, deps::CallbackDeps; prevent_initial_call) check_callback(func, app, deps) out_symbol = Symbol(output_string(deps)) haskey(app.callbacks, out_symbol) && error("Multiple callbacks can not target the same output. Offending output: $(out_symbol)") callback_func = make_callback_func!(app, func, deps) push!( app.callbacks, out_symbol => Callback( callback_func, deps, isnothing(prevent_initial_call) ? get_setting(app, :prevent_initial_callbacks) : prevent_initial_call ) ) end make_callback_func!(app::DashApp, func::Union{Function, ClientsideFunction}, deps::CallbackDeps) = func function make_callback_func!(app::DashApp, func::String, deps::CallbackDeps) first_output = first(deps.output) namespace = replace("_dashprivate_$(first_output.id)", "\""=>"\\\"") function_name = replace("$(first_output.property)", "\""=>"\\\"") function_string = """ var clientside = window.dash_clientside = window.dash_clientside || {}; var ns = clientside["$namespace"] = clientside["$namespace"] || {}; ns["$function_name"] = $func; """ push!(app.inline_scripts, function_string) return ClientsideFunction(namespace, function_name) end function check_callback(func, app::DashApp, deps::CallbackDeps) isempty(deps.output) && error("The callback method requires that one or more properly formatted outputs are passed.") isempty(deps.input) && error("The callback method requires that one or more properly formatted inputs are passed.") args_count = length(deps.state) + length(deps.input) check_callback_func(func, args_count) end function check_callback_func(func::Function, args_count) !hasmethod(func, NTuple{args_count, Any}) && error("The arguments of the specified callback function do not align with the currently defined callback; please ensure that the arguments to `func` are properly defined.") end function check_callback_func(func, args_count) end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
674
struct DashConfig external_stylesheets ::Vector{ExternalSrcType} external_scripts ::Vector{ExternalSrcType} url_base_pathname ::Union{String, Nothing} #TODO This looks unused requests_pathname_prefix ::String routes_pathname_prefix ::String assets_folder ::String assets_url_path ::String assets_ignore ::String serve_locally ::Bool suppress_callback_exceptions ::Bool prevent_initial_callbacks ::Bool eager_loading ::Bool meta_tags ::Vector{Dict{String, String}} assets_external_path ::Union{String, Nothing} include_assets_files ::Bool show_undo_redo ::Bool compress ::Bool update_title ::String end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
13262
const default_index = """<!DOCTYPE html> <html> <head> {%metas%} <title>{%title%}</title> {%favicon%} {%css%} </head> <body> {%app_entry%} <footer> {%config%} {%scripts%} {%renderer%} </footer> </body> </html>""" """ struct DashApp <: Any Dash.jl's internal representation of a Dash application. This `struct` is not intended to be called directly; developers should create their Dash application using the `dash` function instead. """ mutable struct DashApp root_path ::String is_interactive ::Bool config ::DashConfig index_string ::Union{String, Nothing} title ::String layout ::Union{Nothing, Component, Function} devtools ::DevTools callbacks ::Dict{Symbol, Callback} inline_scripts ::Vector{String} DashApp(root_path, is_interactive, config, index_string, title = "Dash") = new(root_path, is_interactive, config, index_string, title, nothing, DevTools(dash_env(Bool, "debug", false)), Dict{Symbol, Callback}(), String[]) end #only name, index_string and layout are available to set function Base.setproperty!(app::DashApp, property::Symbol, value) property == :index_string && return set_index_string!(app, value) property == :layout && return set_layout!(app::DashApp, value) property == :title && return set_title!(app::DashApp, value) property in fieldnames(DashApp) && error("The property `$(property)` of `DashApp` is read-only") error("The property `$(property)` of `DashApp` does not exist.") end function set_title!(app::DashApp, title) setfield!(app, :title, title) end function set_layout!(app::DashApp, component::Union{Component,Function}) setfield!(app, :layout, component) end get_layout(app::DashApp) = app.layout function check_index_string(index_string::AbstractString) validate_index( "index_string", index_string, [ "{%app_entry%}"=>r"{%app_entry%}", "{%config%}"=>r"{%config%}", "{%scripts%}"=>r"{%scripts%}" ] ) end function set_index_string!(app::DashApp, index_string::AbstractString) check_index_string(index_string) setfield!(app, :index_string, index_string) end get_index_string(app::DashApp) = app.component.index_string """ Activate the dev tools, called by `run_server`. If a parameter can be set by an environment variable, that is listed as: env: `DASH_****` Values provided here take precedence over environment variables. Available dev_tools environment variables: - `DASH_DEBUG` - `DASH_UI` - `DASH_PROPS_CHECK` - `DASH_SERVE_DEV_BUNDLES` - `DASH_HOT_RELOAD` - `DASH_HOT_RELOAD_INTERVAL` - `DASH_HOT_RELOAD_WATCH_INTERVAL` - `DASH_HOT_RELOAD_MAX_RETRY` - `DASH_SILENCE_ROUTES_LOGGING` - `DASH_PRUNE_ERRORS` # Arguments - `debug::Bool` - Enable/disable all the dev tools unless overridden by the arguments or environment variables. Default is ``true`` when ``enable_dev_tools`` is called directly, and ``false`` when called via ``run_server``. env: ``DASH_DEBUG``. - `dev_tools_ui::Bool` - Show the dev tools UI. env: ``DASH_UI`` - `dev_tools_props_check::Bool` - Validate the types and values of Dash component props. env: ``DASH_PROPS_CHECK`` - `dev_tools_serve_dev_bundles::Bool` - Serve the dev bundles. Production bundles do not necessarily include all the dev tools code. env: ``DASH_SERVE_DEV_BUNDLES`` - `dev_tools_hot_reload::Bool` - Activate hot reloading when app, assets, and component files change. env: ``DASH_HOT_RELOAD`` - `dev_tools_hot_reload_interval::Float64` - Interval in seconds for the client to request the reload hash. Default 3. env: ``DASH_HOT_RELOAD_INTERVAL`` - `dev_tools_hot_reload_watch_interval::Float64` - Interval in seconds for the server to check asset and component folders for changes. Default 0.5. env: ``DASH_HOT_RELOAD_WATCH_INTERVAL`` - `dev_tools_hot_reload_max_retry::Int` - Maximum number of failed reload hash requests before failing and displaying a pop up. Default 8. env: ``DASH_HOT_RELOAD_MAX_RETRY`` """ function enable_dev_tools!(app::DashApp; debug = nothing, dev_tools_ui = nothing, dev_tools_props_check = nothing, dev_tools_serve_dev_bundles = nothing, dev_tools_hot_reload = nothing, dev_tools_hot_reload_interval = nothing, dev_tools_hot_reload_watch_interval = nothing, dev_tools_hot_reload_max_retry = nothing, dev_tools_silence_routes_logging = nothing, dev_tools_prune_errors = nothing) @env_default!(debug, Bool, true) setfield!(app, :devtools, DevTools( debug; ui = dev_tools_ui, props_check = dev_tools_props_check, serve_dev_bundles = dev_tools_serve_dev_bundles, hot_reload = dev_tools_hot_reload, hot_reload_interval = dev_tools_hot_reload_interval, hot_reload_watch_interval = dev_tools_hot_reload_watch_interval, hot_reload_max_retry = dev_tools_hot_reload_max_retry, silence_routes_logging = dev_tools_silence_routes_logging, prune_errors = dev_tools_prune_errors )) end get_devsetting(app::DashApp, name::Symbol) = getproperty(app.devtools, name) get_setting(app::DashApp, name::Symbol) = getproperty(app.config, name) get_assets_path(app::DashApp) = joinpath(app.root_path, get_setting(app, :assets_folder)) """ dash(; external_stylesheets, external_scripts, url_base_pathname, requests_pathname_prefix, routes_pathname_prefix, assets_folder, assets_url_path, assets_ignore, serve_locally, suppress_callback_exceptions, eager_loading , meta_tags, index_string, assets_external_path, include_assets_files, show_undo_redo, compress, update_title ) Dash is a framework for building analytical web applications. No JavaScript required. If a parameter can be set by an environment variable, that is listed as: env: `DASH_****` Values provided here take precedence over environment variables. # Arguments - `assets_folder::String` - a path, relative to the current working directory, for extra files to be used in the browser. Default `'assets'`. All .js and .css files will be loaded immediately unless excluded by `assets_ignore`, and other files such as images will be served if requested. - `assets_url_path::String` - The local urls for assets will be: ``requests_pathname_prefix * assets_url_path * "/" * asset_path`` where ``asset_path`` is the path to a file inside ``assets_folder``. Default ``'assets'`. - `assets_ignore::String` - [EXPERIMENTAL] A regex, as a string to pass to ``Regex``, for assets to omit from immediate loading. Ignored files will still be served if specifically requested. You cannot use this to prevent access to sensitive files. :type assets_ignore: string - `assets_external_path::String` - [EXPERIMENTAL] an absolute URL from which to load assets. Use with ``serve_locally=false``. Dash can still find js and css to automatically load if you also keep local copies in your assets folder that Dash can index, but external serving can improve performance and reduce load on the Dash server. env: `DASH_ASSETS_EXTERNAL_PATH` - `include_assets_files::Bool` - [EXPERIMENTAL] Default ``true``, set to ``false`` to prevent immediate loading of any assets. Assets will still be served if specifically requested. You cannot use this to prevent access to sensitive files. env: `DASH_INCLUDE_ASSETS_FILES` - `url_base_pathname::String`: A local URL prefix to use app-wide. Default ``nothing``. Both `requests_pathname_prefix` and `routes_pathname_prefix` default to `url_base_pathname`. env: `DASH_URL_BASE_PATHNAME` - `requests_pathname_prefix::String`: A local URL prefix for file requests. Defaults to `url_base_pathname`, and must end with `routes_pathname_prefix` env: `DASH_REQUESTS_PATHNAME_PREFIX` - `routes_pathname_prefix::String`: A local URL prefix for JSON requests. Defaults to ``url_base_pathname``, and must start and end with ``'/'``. env: `DASH_ROUTES_PATHNAME_PREFIX` - `serve_locally`: [EXPERIMENTAL] If `true` (default), assets and dependencies (Dash and Component js and css) will be served from local URLs. If `false` Dash will use CDN links where available. (Dash and Component js and css) will be served from local URLs. If ``false`` we will use CDN links where available. - `meta_tags::Vector{Dict{String, String}}`: html <meta> tags to be added to the index page. Each dict should have the attributes and values for one tag, eg: ``Dict("name"=>"description", "content" => "My App")`` - `index_string::String`: Override the standard Dash index page. Must contain the correct insertion markers to interpolate various content into it depending on the app config and components used. See https://dash.plotly.com/external-resources for details. - `external_scripts::Vector`: Additional JS files to load with the page. Each entry can be a String (the URL) or a Dict{String, String} with ``src`` (the URL) and optionally other ``<script>`` tag attributes such as ``integrity`` and ``crossorigin``. - `external_stylesheets::Vector`: Additional CSS files to load with the page. Each entry can be a String (the URL) or a Dict{String, String} with ``href`` (the URL) and optionally other ``<link>`` tag attributes such as ``rel``, ``integrity`` and ``crossorigin``. - `suppress_callback_exceptions::Bool`: Default ``false``: check callbacks to ensure referenced IDs exist and props are valid. Set to ``true`` if your layout is dynamic, to bypass these checks. env: `DASH_SUPPRESS_CALLBACK_EXCEPTIONS` - `prevent_initial_callbacks::Bool`: Default ``false``: Sets the default value of ``prevent_initial_call`` for all callbacks added to the app. Normally all callbacks are fired when the associated outputs are first added to the page. You can disable this for individual callbacks by setting ``prevent_initial_call`` in their definitions, or set it ``true`` here in which case you must explicitly set it ``false`` for those callbacks you wish to have an initial call. This setting has no effect on triggering callbacks when their inputs change later on. - `show_undo_redo::Bool`: Default ``false``, set to ``true`` to enable undo and redo buttons for stepping through the history of the app state. - `compress::Bool`: Default ``true``, controls whether gzip is used to compress files and data served by HTTP.jl when supported by the client. Set to ``false`` to disable compression completely. - `update_title::String`: Default ``Updating...``. Configures the document.title (the text that appears in a browser tab) text when a callback is being run. Set to '' if you don't want the document.title to change or if you want to control the document.title through a separate component or clientside callback. """ function dash(; external_stylesheets = ExternalSrcType[], external_scripts = ExternalSrcType[], url_base_pathname = dash_env("url_base_pathname"), requests_pathname_prefix = dash_env("requests_pathname_prefix"), routes_pathname_prefix = dash_env("routes_pathname_prefix"), assets_folder = "assets", assets_url_path = "assets", assets_ignore = "", serve_locally = true, suppress_callback_exceptions = dash_env(Bool, "suppress_callback_exceptions", false), prevent_initial_callbacks = false, eager_loading = false, meta_tags = Dict{Symbol, String}[], index_string = default_index, assets_external_path = dash_env("assets_external_path"), include_assets_files = dash_env(Bool, "include_assets_files", true), show_undo_redo = false, compress = true, update_title = "Updating..." ) check_index_string(index_string) config = DashConfig( external_stylesheets, external_scripts, pathname_configs( url_base_pathname, requests_pathname_prefix, routes_pathname_prefix )..., assets_folder, lstrip(assets_url_path, '/'), assets_ignore, serve_locally, suppress_callback_exceptions, prevent_initial_callbacks, eager_loading, meta_tags, assets_external_path, include_assets_files, show_undo_redo, compress, update_title ) result = DashApp(app_root_path(), isinteractive(), config, index_string) return result end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
1412
struct DevTools ui::Bool props_check::Bool serve_dev_bundles::Bool hot_reload::Bool hot_reload_interval::Float64 hot_reload_watch_interval::Float64 hot_reload_max_retry::Int silence_routes_logging::Bool prune_errors::Bool function DevTools(debug = false; ui = nothing, props_check = nothing, serve_dev_bundles = nothing, hot_reload = nothing, hot_reload_interval = nothing, hot_reload_watch_interval = nothing, hot_reload_max_retry = nothing, silence_routes_logging = nothing, prune_errors = nothing) @env_default!(ui, Bool, debug) @env_default!(props_check, Bool, debug) @env_default!(serve_dev_bundles, Bool, debug) @env_default!(hot_reload, Bool, debug) @env_default!(silence_routes_logging, Bool, debug) @env_default!(prune_errors, Bool, debug) @env_default!(hot_reload_interval, Float64, 3.) @env_default!(hot_reload_watch_interval, Float64, 0.5) @env_default!(hot_reload_max_retry, Int, 8) return new( ui, props_check, serve_dev_bundles, hot_reload, hot_reload_interval, hot_reload_watch_interval, hot_reload_max_retry, silence_routes_logging, prune_errors ) end end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
4240
struct Wildcard type ::Symbol end JSON3.StructTypes.StructType(::Type{Wildcard}) = JSON3.RawType() JSON3.rawbytes(wild::Wildcard) = string("[\"", wild.type, "\"]") const MATCH = Wildcard(:MATCH) const ALL = Wildcard(:ALL) const ALLSMALLER = Wildcard(:ALLSMALLER) is_wild(a::T) where {T<:Wildcard} = true is_wild(a) = false struct TraitInput end struct TraitOutput end struct TraitState end const IdTypes = Union{String,NamedTuple} struct Dependency{Trait, IdT<:IdTypes} id ::IdT property ::String Dependency{Trait}(id::T, property::String) where {Trait, T} = new{Trait, T}(id, property) end dep_id_string(dep::Dependency{Trait, String}) where {Trait} = dep.id dep_id_string(dep::Dependency{Trait, <:NamedTuple}) where {Trait} = sorted_json(dep.id) dependency_tuple(dep::Dependency) = (id = dep_id_string(dep), property = dep.property) const Input = Dependency{TraitInput} const State = Dependency{TraitState} const Output = Dependency{TraitOutput} JSON3.StructTypes.StructType(::Type{<:Dependency}) = JSON3.StructTypes.Struct() """ Base.==(a::Dependency, b::Dependency) We use "==" to denote two deps that refer to the same prop on the same component. In the case of wildcard deps, this means the same prop on *at least one* of the same components. """ function Base.:(==)(a::Dependency, b::Dependency) (a.property == b.property) && is_id_matches(a, b) end function Base.isequal(a::Dependency, b::Dependency) return a == b end #The regular unique works using Set and will not work correctly, because in our case "equal" dependencies have different hashes #This implementation is not algorithmically efficient (O(n^2)), but it is quite suitable for checking the uniqueness of outputs function check_unique(deps::Vector{<:Dependency}) tmp = Dependency[] for dep in deps dep in tmp && return false push!(tmp, dep) end return true end is_id_matches(a::Dependency{Trait1, String}, b::Dependency{Trait2, String}) where {Trait1, Trait2} = a.id == b.id is_id_matches(a::Dependency{Trait1, String}, b::Dependency{Trait2, <:NamedTuple}) where {Trait1, Trait2} = false is_id_matches(a::Dependency{Trait1, <:NamedTuple}, b::Dependency{Trait2, String}) where {Trait1, Trait2} = false function is_id_matches(a::Dependency{Trait1, <:NamedTuple}, b::Dependency{Trait2, <:NamedTuple}) where {Trait1, Trait2} (Set(keys(a.id)) != Set(keys(b.id))) && return false for key in keys(a.id) a_value = a.id[key] b_value = b.id[key] (a_value == b_value) && continue a_wild = is_wild(a_value) b_wild = is_wild(b_value) (!a_wild && !b_wild) && return false #Both not wild !(a_wild && b_wild) && continue #One wild, one not ((a_value == ALL) || (b_value == ALL)) && continue #at least one is ALL ((a_value == MATCH) || (b_value == MATCH)) && return false #one is MATCH and one is ALLSMALLER end return true end struct CallbackDeps output ::Vector{<:Output} input ::Vector{<:Input} state ::Vector{<:State} multi_out::Bool CallbackDeps(output, input, state, multi_out) = new(output, input, state, multi_out) CallbackDeps(output::Output, input, state = State[]) = new(output, input, state, false) CallbackDeps(output::Vector{<:Output}, input, state = State[]) = new(output, input, state, true) end Base.convert(::Type{Vector{<:Output}}, v::Output{<:IdTypes}) = [v] Base.convert(::Type{Vector{<:Input}}, v::Input{<:IdTypes}) = [v] Base.convert(::Type{Vector{<:State}}, v::State{<:IdTypes}) = [v] struct ClientsideFunction namespace ::String function_name ::String end JSON3.StructTypes.StructType(::Type{ClientsideFunction}) = JSON3.StructTypes.Struct() struct Callback func ::Union{Function, ClientsideFunction} dependencies ::CallbackDeps prevent_initial_call ::Bool end is_multi_out(cb::Callback) = cb.dependencies.multi_out == true get_output(cb::Callback) = cb.dependencies.output get_output(cb::Callback, i) = cb.dependencies.output[i] first_output(cb::Callback) = first(cb.dependencies.output) struct PreventUpdate <: Exception end struct NoUpdate end no_update() = NoUpdate() const ExternalSrcType = Union{String, Dict{String, String}}
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
49
include("express.jl") include("table_format.jl")
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
3032
import Base64 export dcc_send_file, dcc_send_string, dcc_send_bytes """ dbc_send_file(path::AbstractString, filename = nothing; type = nothing) Convert a file into the format expected by the Download component. # Arguments - `path` - path to the file to be sent - `filename` - name of the file, if not provided the original filename is used - `type` - type of the file (optional, passed to Blob in the javascript layer) """ function dcc_send_file(path, filename = nothing; type = nothing) filename = isnothing(filename) ? basename(path) : filename return dcc_send_bytes(read(path), filename, type = type) end """ dcc_send_bytes(src::AbstractVector{UInt8}, filename; type = nothing) dcc_send_bytes(writer::Function, data, filename; type = nothing) Convert vector of bytes into the format expected by the Download component. `writer` function must have signature `(io::IO, data)` # Examples Sending binary content ```julia file_data = read("path/to/file") callback!(app, Output("download", "data"), Input("download-btn", "n_clicks"), prevent_initial_call = true) do n_clicks return dcc_send_bytes(file_data, "filename.fl") end ``` Sending `DataFrame` in `Arrow` format ```julia using DataFrames, Arrow ... df = DataFrame(...) callback!(app, Output("download", "data"), Input("download-btn", "n_clicks"), prevent_initial_call = true) do n_clicks return dcc_send_bytes(Arrow.write, df, "df.arr") end ``` """ function dcc_send_bytes(src::AbstractVector{UInt8}, filename; type = nothing) return Dict( :content => Base64.base64encode(src), :filename => filename, :type => type, :base64 => true ) end function dcc_send_bytes(writer::Function, data, filename; type = nothing) io = IOBuffer() writer(io, data) return dcc_send_bytes(take!(io), filename, type = type) end """ dcc_send_data(src::AbstractString, filename; type = nothing) dcc_send_data(writer::Function, data, filename; type = nothing) Convert string into the format expected by the Download component. `writer` function must have signature `(io::IO, data)` # Examples Sending string content ```julia text_data = "this is the test" callback!(app, Output("download", "data"), Input("download-btn", "n_clicks"), prevent_initial_call = true) do n_clicks return dcc_send_string(text_data, "text.txt") end ``` Sending `DataFrame` in `CSV` format ```julia using DataFrames, CSV ... df = DataFrame(...) callback!(app, Output("download", "data"), Input("download-btn", "n_clicks"), prevent_initial_call = true) do n_clicks return dcc_send_string(CSV.write, df, "df.csv") end ``` """ function dcc_send_string(src::AbstractString, filename; type = nothing) return Dict( :content => src, :filename => filename, :type => type, :base64 => false ) end function dcc_send_string(writer::Function, data, filename; type = nothing) io = IOBuffer() writer(io, data) return dcc_send_string(String(take!(io)), filename, type = type) end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
9790
module TableFormat using JSON3 export Format, Align, Group, Padding, Prefix, Scheme, Sign, DSymbol, Trim struct NamedValue{Name, T} value::T NamedValue{Name}(value::T) where {Name, T} = new{Name, T}(value) end struct TupleWithNamedValues{Name, Keys} values::NamedTuple TupleWithNamedValues{Name, Keys}(values) where {Name, Keys} = new{Name, Keys}(values) end Base.getproperty(tp::TupleWithNamedValues, prop::Symbol) = getfield(tp, :values)[prop] function tuple_with_named_values(name::Symbol, t::NamedTuple{Names}) where {Names} return TupleWithNamedValues{name, Names}((;zip(Names, NamedValue{name}.(values(t)))...)) end function possible_values(::TupleWithNamedValues{Name, Keys}) where {Name, Keys} return join(string.(string(Name), ".", string.(Keys)), ", ") end const Align = tuple_with_named_values(:Align, ( default = "", left = "<", right = ">", center = "^", right_sign = "=" )) const Group = tuple_with_named_values(:Group, ( no = "", yes = "," )) const Padding = tuple_with_named_values(:Padding, (no = "", yes = 0)) const Prefix = tuple_with_named_values(:Prefix, ( yocto = 10 ^ -24, zepto = 10 ^ -21, atto = 10 ^ -18, femto = 10 ^ -15, pico = 10 ^ -12, nano = 10 ^ -9, micro = 10 ^ -6, milli = 10 ^ -3, none = nothing, kilo = 10 ^ 3, mega = 10 ^ 6, giga = 10 ^ 9, tera = 10 ^ 12, peta = 10 ^ 15, exa = 10 ^ 18, zetta = 10 ^ 21, yotta = 10 ^ 24 )) const Scheme = tuple_with_named_values(:Scheme, ( default = "", decimal = "r", decimal_integer = "d", decimal_or_exponent = "g", decimal_si_prefix = "s", exponent = "e", fixed = "f", percentage = "%", percentage_rounded = "p", binary = "b", octal = "o", lower_case_hex = "x", upper_case_hex = "X", unicode = "c", )) const Sign = tuple_with_named_values(:Sign, ( default = "", negative = "-", positive = "+", parantheses = "(", space = " " )) const DSymbol = tuple_with_named_values(:DSymbol, ( no = "", yes = "\$", binary = "#b", octal = "#o", hex = "#x" )) const Trim = tuple_with_named_values(:Trim, ( no = "", yes = "~" )) mutable struct Format locale nully prefix specifier function Format(; align = Align.default, fill = nothing, group = Group.no, padding = Padding.no, padding_width = nothing, precision = nothing, scheme = Scheme.default, sign = Sign.default, symbol = DSymbol.no, trim = Trim.no, symbol_prefix = nothing, symbol_suffix = nothing, decimal_delimiter = nothing, group_delimiter = nothing, groups = nothing, nully = "", si_prefix = Prefix.none ) result = new( Dict(), "", Prefix.none.value, Dict{Symbol, Any}() ) align!(result, align) fill!(result, fill) group!(result, group) padding!(result, padding) padding_width!(result, padding_width) precision!(result, precision) scheme!(result, scheme) sign!(result, sign) symbol!(result, symbol) trim!(result, trim) !isnothing(symbol_prefix) && symbol_prefix!(result, symbol_prefix) !isnothing(symbol_suffix) && symbol_suffix!(result, symbol_suffix) !isnothing(decimal_delimiter) && decimal_delimiter!(result, decimal_delimiter) !isnothing(group_delimiter) && group_delimiter!(result, group_delimiter) !isnothing(groups) && groups!(result, groups) !isnothing(nully) && nully!(result, nully) !isnothing(si_prefix) && si_prefix!(result, si_prefix) return result end end function check_named_value(t::TupleWithNamedValues{Name, Keys}, v::NamedValue{ValueName}) where {Name, ValueName, Keys} Name != ValueName && throw(ArgumentError("expected value to be one of $(possible_values(t))")) return true end function check_named_value(t::TupleWithNamedValues{Name, Keys}, v) where {Name, Keys} throw(ArgumentError("expected value to be one of $(possible_values(t))")) end check_char_value(v::Char) = string(v) function check_char_value(v::String) length(v) > 1 && throw(ArgumentError("expected char or string of length one")) return v end function check_char_value(v) throw(ArgumentError("expected char or string of length one")) end function check_int_value(v::Integer) v < 0 && throw(ArgumentError("expected value to be non-negative")) end function check_int_value(v) throw(ArgumentError("expected value to be Integer")) end function align!(f::Format, value) check_named_value(Align, value) f.specifier[:align] = value.value end function fill!(f::Format, value) if isnothing(value) f.specifier[:fill] = "" return end v = check_char_value(value) f.specifier[:fill] = v end function group!(f::Format, value) if value isa Bool value = value ? Group.yes : Group.no end check_named_value(Group, value) f.specifier[:group] = value.value end function padding!(f::Format, value) if value isa Bool value = value ? Padding.yes : Padding.no end check_named_value(Padding, value) f.specifier[:padding] = value.value end function padding_width!(f::Format, value) if isnothing(value) f.specifier[:width] = "" else check_int_value(value) f.specifier[:width] = value end end function precision!(f::Format, value) if isnothing(value) f.specifier[:precision] = "" else check_int_value(value) f.specifier[:precision] = ".$value" end end function scheme!(f::Format, value) check_named_value(Scheme, value) f.specifier[:type] = value.value end function sign!(f::Format, value) check_named_value(Sign, value) f.specifier[:sign] = value.value end function symbol!(f::Format, value) check_named_value(DSymbol, value) f.specifier[:symbol] = value.value end function trim!(f::Format, value) if value isa Bool value = value ? Trim.yes : Trim.no end check_named_value(Trim, value) f.specifier[:trim] = value.value end # Locale function symbol_prefix!(f::Format, value::AbstractString) if !haskey(f.locale, :symbol) f.locale[:symbol] = [value, ""] else f.locale[:symbol][1] = value end end function symbol_suffix!(f::Format, value::AbstractString) if !haskey(f.locale, :symbol) f.locale[:symbol] = ["", value] else f.locale[:symbol][2] = value end end function decimal_delimiter!(f::Format, value) v = check_char_value(value) f.locale[:decimal] = v end function group_delimiter!(f::Format, value) v = check_char_value(value) f.locale[:group] = v end function groups!(f::Format, value::Union{Vector{<:Integer}, <:Integer}) groups = value isa Integer ? [value] : value isempty(groups) && throw(ArgumentError("groups cannot be empty")) for g in groups g < 0 && throw(ArgumentError("group entry must be non-negative integer")) end f.locale[:grouping] = groups end # Nully function nully!(f::Format, value) f.nully = value end # Prefix function si_prefix!(f::Format, value) check_named_value(Prefix, value) f.prefix = value.value end JSON3.StructTypes.StructType(::Type{Format}) = JSON3.RawType() function JSON3.rawbytes(f::Format) aligned = f.specifier[:align] != Align.default.value fill = aligned ? f.specifier[:fill] : "" spec_io = IOBuffer() print(spec_io, aligned ? f.specifier[:fill] : "", f.specifier[:align], f.specifier[:sign], f.specifier[:symbol], f.specifier[:padding], f.specifier[:width], f.specifier[:group], f.specifier[:precision], f.specifier[:trim], f.specifier[:type] ) return JSON3.write( ( locale = f.locale, nully = f.nully, prefix = f.prefix, specifier = String(take!(spec_io)) ) ) end money(decimals, sign = Sign.default) = Format( group=Group.yes, precision=decimals, scheme=Scheme.fixed, sign=sign, symbol=Symbol.yes ) function percentage(decimals, rounded::Bool=false) scheme = rounded ? Scheme.percentage_rounded : Scheme.percentage return Format(scheme = scheme, precision = decimals) end end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
1835
using .Contexts const CallbackContextItems = Union{Nothing, Vector{NamedTuple}} const TriggeredParam = NamedTuple{(:prop_id, :value)} mutable struct CallbackContext response::HTTP.Response inputs::Dict{String, Any} states::Dict{String, Any} outputs_list::Vector{Any} inputs_list::Vector{Any} states_list::Vector{Any} triggered::Vector{TriggeredParam} function CallbackContext(response, outputs_list, inputs_list, states_list, changed_props) input_values = inputs_list_to_dict(inputs_list) state_values = inputs_list_to_dict(states_list) triggered = TriggeredParam[(prop_id = id, value = input_values[id]) for id in changed_props] return new(response, input_values, state_values, outputs_list, inputs_list, states_list, triggered) end end const _callback_context_storage = TaskContextStorage() function with_callback_context(f, context::CallbackContext) return with_context(f, _callback_context_storage, context) end """ callback_context()::CallbackContext Get context of current callback, available only inside callback processing function """ function callback_context() !has_context(_callback_context_storage) && error("callback_context() is only available from a callback processing function") return get_context(_callback_context_storage) end function inputs_list_to_dict(list::AbstractVector) result = Dict{String, Any}() _item_to_dict!.(Ref(result), list) return result end dep_id_string(id::AbstractDict) = sorted_json(id) dep_id_string(id::AbstractString) = String(id) function _item_to_dict!(target::Dict{String, Any}, item) target["$(dep_id_string(item.id)).$(item.property)"] = get(item, :value, nothing) end _item_to_dict!(target::Dict{String, Any}, item::AbstractVector) = _item_to_dict!.(Ref(target), item)
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
4762
function resource_url(app::DashApp, resource::AppRelativeResource) prefix = get_setting(app, :requests_pathname_prefix) return string(prefix, "_dash-component-suites/", resource.namespace, "/", build_fingerprint(resource.relative_path, resource.version, resource.ts) ) end #TODO move to somewhere function asset_path(app::DashApp, path::AbstractString) return string( get_setting(app, :requests_pathname_prefix), lstrip(get_setting(app, :assets_url_path), '/'), "/", path ) end resource_url(app::DashApp, resource::AppExternalResource) = resource.url function resource_url(app::DashApp, resource::AppAssetResource) return string( asset_path(app, resource.path), "?m=", resource.ts ) end make_css_tag(url::String) = """<link rel="stylesheet" href="$(url)">""" make_css_tag(app::DashApp, resource::AppCustomResource) = format_tag("link", resource.params, opened = true) make_css_tag(app::DashApp, resource::AppResource) = make_css_tag(resource_url(app, resource)) make_script_tag(url::String) = """<script src="$(url)"></script>""" make_script_tag(app::DashApp, resource::AppCustomResource) = format_tag("script", resource.params) make_script_tag(app::DashApp, resource::AppResource) = make_script_tag(resource_url(app, resource)) make_inline_script_tag(script::String) = """<script>$(script)</script>""" function metas_html(app::DashApp) meta_tags = app.config.meta_tags has_ie_compat = any(meta_tags) do tag get(tag, "http-equiv", "") == "X-UA-Compatible" end has_charset = any(tag -> haskey(tag, "charset"), meta_tags) result = String[] !has_ie_compat && push!(result, "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">") !has_charset && push!(result, "<meta charset=\"UTF-8\">") append!(result, format_tag.("meta", meta_tags, opened = true)) return join(result, "\n ") end function css_html(app::DashApp, resources::ApplicationResources) join( make_css_tag.(Ref(app), resources.css), "\n " ) end function scripts_html(app::DashApp, resources::ApplicationResources) include_string = join( vcat( make_script_tag.(Ref(app), resources.js), make_inline_script_tag.(app.inline_scripts) ), "\n " ) end app_entry_html() = """ <div id="react-entry-point"> <div class="_dash-loading"> Loading... </div> </div> """ function config_html(app::DashApp) config = Dict{Symbol, Any}( :url_base_pathname => get_setting(app, :url_base_pathname), :requests_pathname_prefix => get_setting(app, :requests_pathname_prefix), :ui => get_devsetting(app, :ui), :props_check => get_devsetting(app, :props_check), :show_undo_redo => get_setting(app, :show_undo_redo), :suppress_callback_exceptions => get_setting(app, :suppress_callback_exceptions), :update_title => get_setting(app, :update_title) ) if get_devsetting(app, :hot_reload) config[:hot_reload] = ( interval = trunc(Int, get_devsetting(app, :hot_reload_interval) * 1000), max_retry = get_devsetting(app, :hot_reload_max_retry) ) end return """<script id="_dash-config" type="application/json">$(JSON3.write(config))</script>""" end renderer_html() = """<script id="_dash-renderer" type="application/javascript">var renderer = new DashRenderer();</script>""" function favicon_html(app::DashApp, resources::ApplicationResources) favicon_url = if !isnothing(resources.favicon) asset_path(app, resources.favicon.path) else "$(get_setting(app, :requests_pathname_prefix))_favicon.ico?v=$(_metadata.dash["version"])" end return format_tag( "link", Dict( "rel" => "icon", "type" => "image/x-icon", "href" => favicon_url ), opened = true ) end function index_page(app::DashApp, resources::ApplicationResources) result = interpolate_string(app.index_string, metas = metas_html(app), title = app.title, favicon = favicon_html(app, resources), css = css_html(app, resources), app_entry = app_entry_html(), config = config_html(app), scripts = scripts_html(app, resources), renderer = renderer_html() ) validate_index("index", result, [ "#react-entry-point" => r"id=\"react-entry-point\"", "#_dash_config" => r"id=\"_dash-config\"", "dash-renderer" => r"src=\"[^\"]*dash[-_]renderer[^\"]*\"", "new DashRenderer" => r"id=\"_dash-renderer", ] ) return result end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
5784
include("processors/assets.jl") include("processors/callback.jl") include("processors/dependecies.jl") include("processors/index.jl") include("processors/layout.jl") include("processors/reload_hash.jl") include("processors/resource.jl") include("processors/default_favicon.jl") function start_reload_poll(state::HandlerState) folders = Set{String}() push!(folders, get_assets_path(state.app)) push!(folders, state.registry.dash_renderer.path) for pkg in values(state.registry.components) push!(folders, pkg.path) end initial_watched = init_watched(folders) state.reload.task = @async poll_folders(folders, initial_watched; interval = get_devsetting(state.app, :hot_reload_watch_interval)) do file, ts, deleted state.reload.hard = true state.reload.hash = generate_hash() assets_path = get_assets_path(state.app) if startswith(file, assets_path) state.cache.need_recache = true rel_path = lstrip( replace(relpath(file, assets_path), '\\'=>'/'), '/' ) push!(state.reload.changed_assets, ChangedAsset( asset_path(state.app, rel_path), trunc(Int, ts), endswith(file, "css") ) ) end end end validate_layout(layout::Component) = validate(layout) validate_layout(layout::Function) = validate_layout(layout()) validate_layout(layout) = error("The layout must be a component, tree of components, or a function which returns a component.") function stack_from_callback(full_stack; prune_errors) !prune_errors && return full_stack result = Base.StackTraces.StackFrame[] it = iterate(full_stack) while !isnothing(it) && it[1].func != :process_callback_call push!(result, it[1]) it = iterate(full_stack, it[2]) end return result end function exception_handling(ex; prune_errors) st = stack_from_callback(stacktrace(catch_backtrace()), prune_errors = prune_errors) @error "error handling request" exception = (ex, st) return HTTP.Response(500) end function debug_exception_handling(ex; prune_errors) response = HTTP.Response(500, ["Content-Type" => "text/html"]) io = IOBuffer() write(io, "<!DOCTYPE HTML><html>", "<head>", "<style type=\"text/css\">", """ div.debugger { text-align: left; padding: 12px; margin: auto; background-color: white; } h1 { font-size: 36px; margin: 0 0 0.3em 0; } div.detail { cursor: pointer; } div.detail p { margin: 0 0 8px 13px; font-size: 14px; white-space: pre-wrap; font-family: monospace; } div.plain { border: 1px solid #ddd; margin: 0 0 1em 0; padding: 10px; } div.plain p { margin: 0; } div.plain textarea, div.plain pre { margin: 10px 0 0 0; padding: 4px; background-color: #E8EFF0; border: 1px solid #D3E7E9; } div.plain textarea { width: 99%; height: 300px; } """, "</style>", "</head>", "<body style=\"background-color: #fff\">", "<div class=\"debugger\">", "<div class=\"detail\">", "<p class=\"errormsg\">") showerror(io, ex) write(io, "</p>", "</div>", "</div>", "<div class=\"plain\">", "<textarea cols=\"50\" rows=\"10\" name=\"code\" readonly>" ) st = stack_from_callback(stacktrace(catch_backtrace()), prune_errors = prune_errors) showerror(io, ex) write(io, "\n") Base.show_backtrace(io, st) write(io, "</textarea>") write(io, "</body></html>") response.body = take!(io) @error "error handling request" exception = (ex, st) return response end #For test purposes, with the ability to pass a custom registry function make_handler(app::DashApp, registry::ResourcesRegistry; check_layout = false) state = HandlerState(app, registry) prefix = get_setting(app, :routes_pathname_prefix) assets_url_path = get_setting(app, :assets_url_path) check_layout && validate_layout(get_layout(app)) router = Router() add_route!(process_layout, router, "$(prefix)_dash-layout") add_route!(process_dependencies, router, "$(prefix)_dash-dependencies") add_route!(process_reload_hash, router, "$(prefix)_reload-hash") add_route!(process_default_favicon, router, "$(prefix)_favicon.ico") add_route!(process_resource, router, "$(prefix)_dash-component-suites/<namespace>/<path>") add_route!(process_assets, router, "$(prefix)$(assets_url_path)/<file_path>") add_route!(process_callback, router, "POST", "$(prefix)_dash-update-component") add_route!(process_index, router, "$prefix/*") add_route!(process_index, router, "$prefix") handler = state_handler(router, state) if get_devsetting(app, :ui) handler = exception_handling_handler(handler) do ex debug_exception_handling(ex, prune_errors = get_devsetting(app, :prune_errors)) end else handler = exception_handling_handler(handler) do ex exception_handling(ex, prune_errors = get_devsetting(app, :prune_errors)) end end get_setting(app, :compress) && (handler = compress_handler(handler)) compile_request = HTTP.Request("GET", prefix) HTTP.setheader(compile_request, "Accept-Encoding" => "gzip") handle(handler, compile_request) #For handler precompilation get_devsetting(app, :hot_reload) && start_reload_poll(state) return handler end function make_handler(app::DashApp) return make_handler(app, main_registry(), check_layout = true) end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
216
function mime_by_path(path) endswith(path, ".js") && return "application/javascript" endswith(path, ".css") && return "text/css" endswith(path, ".map") && return "application/json" return nothing end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
2102
struct ChangedAsset url ::String modified ::Int is_css ::Bool end JSON3.StructTypes.StructType(::Type{ChangedAsset}) = JSON3.StructTypes.Struct() mutable struct StateReload hash::Union{String, Nothing} hard::Bool changed_assets::Vector{ChangedAsset} task ::Union{Nothing, Task} StateReload(hash) = new(hash, false, ChangedAsset[], nothing) end mutable struct StateCache resources::ApplicationResources index_string ::String dependencies_json ::String need_recache ::Bool StateCache(app, registry) = new(_cache_tuple(app, registry)..., false) end _dep_clientside_func(func::ClientsideFunction) = func _dep_clientside_func(func) = nothing function _dependencies_json(app::DashApp) result = map(values(app.callbacks)) do callback ( inputs = dependency_tuple.(callback.dependencies.input), state = dependency_tuple.(callback.dependencies.state), output = output_string(callback.dependencies), clientside_function = _dep_clientside_func(callback.func), prevent_initial_call = callback.prevent_initial_call ) end return JSON3.write(result) end function _cache_tuple(app::DashApp, registry::ResourcesRegistry) app_resources = ApplicationResources(app, registry) index_string::String = index_page(app, app_resources) dependencies_json = _dependencies_json(app) return (app_resources, index_string, dependencies_json) end struct HandlerState app::DashApp registry::ResourcesRegistry cache::StateCache reload::StateReload HandlerState(app, registry = main_registry()) = new(app, registry, StateCache(app, registry), make_reload_state(app)) end make_reload_state(app::DashApp) = get_devsetting(app, :hot_reload) ? StateReload(generate_hash()) : StateReload(nothing) get_cache(state::HandlerState) = state.cache function rebuild_cache!(state::HandlerState) cache = get_cache(state) (cache.resources, cache.index_string, cache.dependencies_json) = _cache_tuple(state.app, state.registry) cache.need_recache = false end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
497
function process_assets(request::HTTP.Request, state::HandlerState; file_path::AbstractString) app = state.app filename = joinpath(get_assets_path(app), file_path) try headers = Pair{String,String}[] mimetype = mime_by_path(filename) !isnothing(mimetype) && push!(headers, "Content-Type" => mimetype) file_contents = read(filename) return HTTP.Response(200, headers;body = file_contents) catch return HTTP.Response(404) end end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
4346
function split_single_callback_id(callback_id::AbstractString) parts = rsplit(callback_id, ".") return (id = parts[1], property = parts[2]) end function split_callback_id(callback_id::AbstractString) if startswith(callback_id, "..") result = [] push!.(Ref(result), split_single_callback_id.(split(callback_id[3:end-2], "...", keepempty = false))) return result end return split_single_callback_id(callback_id) end input_to_arg(input) = get(input, :value, nothing) input_to_arg(input::AbstractVector) = input_to_arg.(input) make_args(inputs, state) = vcat(input_to_arg(inputs), input_to_arg(state)) res_to_vector(res) = res res_to_vector(res::Vector) = res function _push_to_res!(res, value, out::AbstractVector) _push_to_res!.(Ref(res), value, out) end function _push_to_res!(res, value, out) if !(value isa NoUpdate) id = dep_id_string(out.id) prop = Symbol(out.property) dashval = DashBase.to_dash(value) if haskey(res, id) push!(res[id], prop => dashval) else push!(res, id => Dict{Symbol, Any}(prop => dashval)) end end end _single_element_vect(e::T) where {T} = T[e] function process_callback_call(app, callback_id, outputs, inputs, state) cb = app.callbacks[callback_id] res = cb.func(make_args(inputs, state)...) (res isa NoUpdate) && throw(PreventUpdate()) res_vector = is_multi_out(cb) ? res : _single_element_vect(res) validate_callback_return(outputs, res_vector, callback_id) response = Dict{String, Any}() _push_to_res!(response, res_vector, outputs) if length(response) == 0 throw(PreventUpdate()) end return Dict(:response=>response, :multi=>true) end outputs_to_vector(out, is_multi) = is_multi ? out : [out] function process_callback(request::HTTP.Request, state::HandlerState) app = state.app response = HTTP.Response(200, ["Content-Type" => "application/json"]) params = JSON3.read(String(request.body)) inputs = get(params, :inputs, []) state = get(params, :state, []) output = Symbol(params[:output]) try is_multi = is_multi_out(app.callbacks[output]) outputs_list = outputs_to_vector( get(params, :outputs, split_callback_id(params[:output])), is_multi) changedProps = get(params, :changedPropIds, []) context = CallbackContext(response, outputs_list, inputs, state, changedProps) cb_result = with_callback_context(context) do process_callback_call(app, output, outputs_list, inputs, state) end response.body = Vector{UInt8}(JSON3.write(cb_result)) catch e if isa(e,PreventUpdate) return HTTP.Response(204) else rethrow(e) end end return response end function validate_callback_return(outputs, value, callback_id) !(isa(value, Vector) || isa(value, Tuple)) && throw(InvalidCallbackReturnValue( """ The callback $callback_id is a multi-output. Expected the output type to be a list or tuple but got: $value """ )) (length(value) != length(outputs)) && throw(InvalidCallbackReturnValue( """ Invalid number of output values for $callback_id. Expected $(length(outputs)), got $(length(value)) """ )) validate_return_item.(callback_id, eachindex(outputs), value, outputs) end function validate_return_item(callback_id, i, value::Union{<:Vector, <:Tuple}, spec::Vector) length(value) != length(spec) && throw(InvalidCallbackReturnValue( """ Invalid number of output values for $callback_id item $i. Expected $(length(value)), got $(length(spec)) output spec: $spec output value: $value """ )) end function validate_return_item(callback_id, i, value, spec::Vector) throw(InvalidCallbackReturnValue( """ The callback $callback_id ouput $i is a wildcard multi-output. Expected the output type to be a list or tuple but got: $value. output spec: $spec """ )) end validate_return_item(callback_id, i, value, spec) = nothing
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
283
function process_default_favicon(request::HTTP.Request, state::HandlerState) ico_contents = read( joinpath(ROOT_PATH, "src", "favicon.ico") ) return HTTP.Response( 200, ["Content-Type" => "image/x-icon"], body = ico_contents ) end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
220
function process_dependencies(request::HTTP.Request, state::HandlerState) return HTTP.Response( 200, ["Content-Type" => "application/json"], body = state.cache.dependencies_json ) end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
260
function process_index(request::HTTP.Request, state::HandlerState) get_cache(state).need_recache && rebuild_cache!(state) return HTTP.Response( 200, ["Content-Type" => "text/html"], body = state.cache.index_string ) end
Dash
https://github.com/plotly/Dash.jl.git
[ "MIT" ]
1.5.0
826c9960644b38dcf0689115a86b57c3f1aa7f1d
code
304
layout_data(layout::Component) = layout layout_data(layout::Function) = layout() function process_layout(request::HTTP.Request, state::HandlerState) return HTTP.Response( 200, ["Content-Type" => "application/json"], body = JSON3.write(layout_data(state.app.layout)) ) end
Dash
https://github.com/plotly/Dash.jl.git