ModelingToolkitStandardLibrary.jl

repository·main·Indexed 41 days ago

https://github.com/sciml/modelingtoolkitstandardlibrary.jl

A standardized collection of physical components and basic blocks for complex system modeling within the SciML ecosystem. It provides libraries for Mechanical (Rotational, Translational, MultiBody2D), Electrical, Magnetic, Thermal, and Hydraulic (IsothermalCompressible) domains, as well as functional blocks for math, signal sources, and continuous controllers like PID.

Tokens
15.8K
Snippets
37
Records
60
Agent score
51%

What's inside ModelingToolkitStandardLibrary

  1. Overview of ModelingToolkitStandardLibrary Blocks

    main

    The ModelingToolkitStandardLibrary.Blocks module provides a collection of pre-defined functional blocks used to construct models. These blocks are categorized into several functional groups:

    • Utility Blocks: Define input/output constraints and system structures (e.g., SISO, MIMO).
    • Math Blocks: Implement standard mathematical operations, including arithmetic, trigonometry, and transcendental functions.
    • Source Blocks: Provide signal inputs such as constants, ramps, or periodic functions (e.g., Sine, Step).
    • Nonlinear Blocks: Implement non-linear signal processing like Limiter or DeadZone.
    • Continuous Blocks: Implement dynamic elements and controllers, such as Integrator, Derivative, and various PID controllers.
  2. Overview of Thermal Components in ModelingToolkitStandardLibrary

    main

    The ModelingToolkitStandardLibrary.Thermal module provides a collection of standardized thermal components, sensors, and sources for building thermal models. These components are designed to work within the ModelingToolkit ecosystem to simulate heat transfer, thermal mass, and temperature regulation.

    Key categories include:

    • Thermal Utilities: Fundamental building blocks like HeatPort and 1D elements.
    • Thermal Components: Passive elements such as resistors, conductors, and capacitors (e.g., ThermalResistor, HeatCapacitor).
    • Thermal Sensors: Components for measuring state variables like TemperatureSensor or HeatFlowSensor.
    • Thermal Sources: Active elements for prescribing heat flow or temperature (e.g., FixedTemperature, PrescribedHeatFlow).
  3. Use IsothermalCompressible hydraulic components

    main
    The ModelingToolkitStandardLibrary.Hydraulic.IsothermalCompressible module provides components for modeling hydraulic systems where the fluid is treated as an isothermal compressible medium. This module includes utility types, physical components (like tubes, valves, and actuators), and sources (like mass flow and pressure sources).
  4. Explore ModelingToolkitStandardLibrary libraries

    main

    The ModelingToolkit Standard Library is organized into several constituent libraries based on the type of physical domain being modeled:

    • Basic Blocks: Fundamental building blocks for modeling.
    • Mechanical Components: Components for mechanical systems.
    • Electrical Components: Components for electrical systems.
    • Magnetic Components: Components for magnetic systems.
    • Thermal Components: Components for thermal systems.
  5. Use Magnetic Components in ModelingToolkitStandardLibrary.jl

    main

    The ModelingToolkitStandardLibrary.Magnetic module provides components for modeling magnetic systems using a flux tube abstraction. The library is organized into three main categories:

    1. Flux Tube Utilities: Port definitions and multi-port connections.
    2. Basic Flux Tube Blocks: Fundamental building blocks like Ground, Short, Crossing, and EddyCurrent.
    3. Flux Tube Sources: Components that drive magnetic flux, such as ConstantMagneticFlux or ConstantMagneticPotentialDifference.

    Flux tubes are modeled within the ModelingToolkitStandardLibrary.Magnetic.FluxTubes module.

  6. Compare accuracy between Velocity and Position domains

    main

    When modeling physical systems, you can choose between a velocity-based domain or a position-based domain. Mathematically, both approaches solve the same underlying differential equations. For example, in a mass-spring-damper system, the velocity domain uses the spring stretch $\Delta s$ as a state, while the position domain uses the absolute position $s$ and calculates stretch as $\Delta s = s - s_{b_0} - l$.

    Numerical differences between these two formulations are negligible (typically much less than $10^{-9}$), meaning the choice between them is primarily a matter of modeling preference rather than accuracy.

    # Example of plotting the numerical difference between velocity and position domain solutions
    plot(title = "numerical difference: vel. vs. pos. domain", xlabel = "time [s]",
        ylabel = "solv[bv.v] .- solp[bp.v]")
    time = 0:0.1:10
    plot!(time, (solv(time)[bv.v] .- solp(time)[bp.v]), label = "")
  7. Compare Mechanical Translational Velocity vs. Position Domains

    main

    The ModelingToolkitStandardLibrary provides two ways to model mechanical translation. Choosing between them depends on whether your model requires absolute position information or just velocities.

    1. Velocity-based Domain (Mechanical.Translational)

    • Across Variable: Velocity ($v$).
    • Pros: Simpler initialization; lower-order equations.
    • Cons: Does not track absolute position ($s$) by default. To get position, you must either use a component that supports an initial position parameter or implement a sensor.
    • Usage: Use when the model is primarily concerned with forces, velocities, and accelerations.

    2. Position-based Domain (Mechanical.TranslationalPosition)

    • Across Variable: Position ($s$).
    • Pros: Provides direct access to absolute position states.
    • Cons: Requires more initial condition information (e.g., natural spring length, absolute fixed positions) to be properly defined.
    • Usage: Use when absolute position is a primary variable of interest in your simulation.
  8. Understand the Sign Convention for Input Components

    main

    The ModelingToolkitStandardLibrary.jl follows a sign convention (consistent with the Modelica Standard Library) to ensure physical consistency when connecting components.

    The Rule: An input component that specifies a through variable (e.g., force, current, mass flow) must be defined such that a positive value for that flow variable represents the accumulation of the associated across variable (e.g., velocity, voltage, pressure/density) over time in the connected component.

    Mathematically, the energy dissipation equation follows: $$\frac{\partial \text{across}}{\partial t} = \text{through input}$$

    Implementation Pattern: When defining an input component, you typically write an opposite equality for the connector's through variable to align the component and port connection. For example, if a force f is leaving a port, the equation should be port.f ~ -f.

    # Correct sign convention for a force input component
    @mtkmodel ConstantForce begin
        @parameters begin
            f = 0
        end
        @components begin
            flange = MechanicalPort()
        end
        @equations begin
            flange.f ~ -f # force is leaving the port
        end
    end
  9. Understand Through and Across Variables in Connectors

    main

    In acausal physical network modeling, every physical domain connector defines two types of variables: a Through variable and an Across variable. This relationship is fundamental to how energy dissipation and flow are modeled.

    • Through variable: Typically a time derivative of a conserved quantity (e.g., current, force).
    • Across variable: The conserved quantity itself (e.g., voltage, velocity, position).

    Mathematical Relationship

    For energy dissipation and flow, the relationship generally follows these patterns:

    Energy Dissipation (Storage): $$\frac{\partial \text{across}}{\partial t} \cdot c_1 = \text{through}$$

    Flow: $$\text{through} \cdot c_2 = \text{across}$$

    Domain Examples

    DomainAcross VariableThrough VariableNote
    ElectricalVoltageCurrentStandard
    Translational (Velocity-based)VelocityForceStandard
    Translational (Position-based)PositionForceRequires higher-order derivatives (acceleration) to relate position to force.
  10. Use Electrical Utilities in ModelingToolkitStandardLibrary

    main

    The ModelingToolkitStandardLibrary.Electrical module provides fundamental building blocks for electrical circuit modeling. Use the following utilities to define connection points and port behaviors:

    • Pin: Represents a physical connection point.
    • OnePort: A high-level abstraction for components with a single electrical port.
    • DigitalPin: A specialized pin for digital signal modeling.
    using ModelingToolkitStandardLibrary.Electrical
    # Access utilities via the Electrical module
  11. Compare methods for including discrete data in models

    main

    When deciding how to include discrete data in your ModelingToolkit model, consider the following trade-offs:

    MethodProsCons
    InterpolationHigh performance, easy to use.Data is structural; requires model rebuild to change data.
    ParametrizedInterpolationSupports remake and optimization (ForwardDiff).Slower than Interpolation.
    SampledDataReusable systems, valid observables, supports parallel solve().Requires careful parameter type management (tofloat=false).
    Custom Component (Ref)Highly flexible.Not recommended. Solution observables become invalid if data changes.
  12. How AnalysisPoints work for linear analysis

    main

    Linear analysis in ModelingToolkitStandardLibrary is performed by inserting an AnalysisPoint into a model. An AnalysisPoint acts as a probe or a break in the signal flow, allowing you to extract linearized representations of the system at specific locations.

    Creating Analysis Points

    You can create an analysis point in two ways:

    1. Automatically via connect: When connecting two causal components, pass a symbol as the middle argument. This creates a causal analysis point where the signal flows from the first argument to the third.
      connect(comp1.output, :analysis_point_name, comp2.input)
    2. Explicitly: Using the AnalysisPoint constructor.

    Important: Causality

    Analysis points are causal. The order of arguments in connect(out, :name, in) defines the direction of information flow. Reversing the order (connect(in, :name, out)) changes the directionality of the analysis point.

    # Automatic creation of an analysis point named :plant_output
    connect(P.output, :plant_output, C.input)