Docs/Custom Components/Julia Component Code Conventions

Julia Component Code Conventions

Applies to: CoModel cloud modeling & simulation platform (v1.7+)

Target MTK version: ModelingToolkit.jl ≥ 11.0

1. Overview

The CoModel platform uses Julia / ModelingToolkit (MTK) as its underlying modeling language. Whether you write components in the Online Component Editor or import them via Uploading MTK Component Files, the source must follow the conventions in this document for the platform to parse, load, and simulate it correctly.

This document covers:

  • required MTK v11 syntax
  • the only supported form of component definition: @component function (@mtkmodel has been removed; see §2)
  • how to declare parameters, ports, and equations
  • things to watch out for in code generation and simulation

2. MTK v11 version constraints

CoModel's code generation and simulation environment is based on MTK v11. Make sure your component code uses these APIs:

Purpose ❌ Legacy (forbidden) ✅ Current (required)
Component definition macro @mtkmodel Name begin ... end @component function Name(; name, ...) ... end
Introduce independent variable t / differential operator D @independent_variables t using ModelingToolkit: t_nounits as t, D_nounits as D
System type ODESystem(eqs, t; ...) System(eqs, t; ...)
System simplification structural_simplify(model) mtkcompile(model) (called by the platform at the model level)
Composing subsystems compose(ODESystem(...), c1, c2) System(eqs, t; systems=[c1, c2], ...)
Differentiation Differential(t)(x) D(x)

Key point: do not create new independent variables with @independent_variables t. All standard library components are defined on t_nounits; mixing the two breaks connections. The @mtkmodel macro no longer exists in the MTK version of the current environment — files using it pass the basic upload validation but fail semantic parsing, and produce no ports.


3. Required imports

Every component file should start with:

using ModelingToolkit
using ModelingToolkit: t_nounits as t, D_nounits as D

If the component uses a Connector or component from the MTK standard library, also import the corresponding modules explicitly, e.g.:

using ModelingToolkitStandardLibrary.Electrical: Pin, Resistor, OnePort
using ModelingToolkitStandardLibrary.Mechanical.Translational: MechanicalPort, Mass, Spring
using ModelingToolkitStandardLibrary.Blocks: RealInput, RealOutput

4. Component definition form: @component function

Components are uniformly defined with @component function, and the function must return a System:

@component function MyResistor(; name, R = 1.0)
    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters begin
        R = R, [description = "Resistance"]
    end
    eqs = [
        v ~ R * i,
    ]
    return extend(System(eqs, t, [], pars; name), oneport)
end

4.1 Port rules (key)

The platform extracts a component's ports by introspection: connector instances in the top-level systems of the returned System are the component's external ports. With no ports, the component still parses as Parsed, but once dragged onto the canvas it has no pins to connect and cannot be modeled.

Two ways to produce ports:

Option 1: attach connectors directly — put connector instances such as Pin(), HeatPort(), MechanicalPort(), RealInput(), RealOutput() straight into systems (this is the form generated by graphical composite components):

@named p = Pin()
@named n = Pin()
return System(eqs, t, vars, pars; name, systems=[p, n])

Option 2: OnePort member + extend — standard library members like OnePort() and TwoPort() are not connectors themselves (their p, n pins live one level down), so putting them directly into systems produces no ports. Use extend to lift the member's inner connector to top-level ports; the member's equation variables come along with it:

@named oneport = OnePort()
@unpack v, i = oneport
eqs = [
    v ~ R * i,
]
return extend(System(eqs, t, [], pars; name), oneport)   # ports: p, n

extend accepts exactly one member at a time; to expose other connectors as well (e.g. a HeatPort), put them directly into the partial system's systems=[...], then extend the OnePort-type member separately. See §8 for a full example.


5. Parameter declaration

5.1 Basic syntax

@parameters begin
    R = 1.0, [description = "Resistance", unit = "Ω"]
    C = 1.0e-6, [description = "Capacitance", unit = "F"]
    use_thermal = false, [description = "Whether to enable the heat port"]
end

5.2 Parameter defaults

  • Parameters must provide default values so the platform can populate the parameter panel correctly.
  • Default values should be literals; avoid depending on variables only known at runtime.

5.3 Parameter types

The platform currently supports parameters of these types:

Julia type Example Front-end control
Float64 1.0 Number input
Int 10 Integer input
Bool true Toggle switch
String "constant" Text input

6. Port declaration

6.1 Physical ports (acausal)

Physical ports come from connector instances in the top-level systems (see §4.1). Two ways to write them:

# Option 1: attach connectors directly
@named p = Pin()
@named n = Pin()
# ... systems=[p, n]

# Option 2: OnePort member + extend lifts the inner Pins
@named oneport = OnePort()
# ... return extend(System(eqs, t, [], pars; name), oneport)

Common Connector types and their physical domains:

Connector type Physical domain Description
Pin electrical Electrical pin
HeatPort thermal Heat port
MechanicalPort mechanical_translational Translational mechanical port (formerly Flange)
RealInput / RealOutput signal/control Signal input / output
OnePort() — Not a connector — a member component wrapping two Pins, p and n; must go through extend to form ports
TwoPort() — Same, with four inner Pins

6.2 Signal ports (causal)

@component function MyGain(; name, k = 1.0)
    @named input = RealInput()
    @named output = RealOutput()
    pars = @parameters k = k
    eqs = [output.u ~ k * input.u]
    return System(eqs, t, [], pars; name, systems=[input, output])
end

6.3 Port names and icon anchors

The data-port attribute in an SVG icon must match the port names in the component code exactly. See Component Icons & Port Anchors.


7. Equations and the returned system

7.1 Equation block

eqs = Equation[
    v ~ R * i,
    D(v) ~ i / C,
]

7.2 Returning a System

The component function must return a System. Which form to return depends on the members:

# member ports are already in systems (connector instances are the ports)
return System(eqs, t, vars, pars; name, systems=[subsys1, subsys2])

# with OnePort-type members, use extend to lift the inner connector into ports
return extend(System(eqs, t, [], pars; name), oneport)

# mixed: connectors go in the partial system's systems, the OnePort-type member is extended separately
return extend(System(eqs, t, [], pars; name, systems=[heat_port]), oneport)

System constructor arguments:

Argument Description
eqs Equation array
t Independent variable; must be the t imported from t_nounits
vars State variable list; [] when there are none
pars Parameter list
name Component instance name; must be kept
systems Subsystem list; connector instances in it are the component's external ports

8. Complete examples

The following examples have all been verified in the current environment: they parse successfully, their ports are extracted correctly, and they can be dragged onto the canvas for modeling directly.

8.1 Resistor component (OnePort + extend)

using ModelingToolkit
using ModelingToolkit: t_nounits as t, D_nounits as D
using ModelingToolkitStandardLibrary.Electrical: OnePort

@component function MyResistor(; name, R = 1.0)
    @named oneport = OnePort()
    @unpack v, i = oneport
    pars = @parameters R = R [description = "Resistance"]
    eqs = [v ~ R * i]
    return extend(System(eqs, t, [], pars; name), oneport)   # ports: p, n
end

8.2 Spring-mass-damper (multiple members + exposed mechanical port)

using ModelingToolkit
using ModelingToolkit: t_nounits as t, D_nounits as D
using ModelingToolkitStandardLibrary.Mechanical.Translational:
    Mass, Spring, Damper, Fixed, MechanicalPort

@component function MySpringMassDamper(; name, m = 10.0, k = 1500.0, d = 50.0)
    @named mass = Mass(m = m)
    @named spring = Spring(k = k)
    @named damper = Damper(d = d)
    @named fixed = Fixed()
    @named flange = MechanicalPort()
    pars = @parameters begin
        m = m, [description = "Mass"]
        k = k, [description = "Stiffness"]
        d = d, [description = "Damping"]
    end
    eqs = [
        connect(flange, mass.flange, spring.flange_a, damper.flange_a)
        connect(spring.flange_b, damper.flange_b, fixed.flange)
    ]
    return System(eqs, t, [], pars; name, systems=[flange, mass, spring, damper, fixed])
end

8.3 Resistor with a heat port (mixed: systems + extend)

using ModelingToolkit
using ModelingToolkit: t_nounits as t, D_nounits as D
using ModelingToolkitStandardLibrary.Electrical: OnePort
using ModelingToolkitStandardLibrary.Thermal: HeatPort

@component function ThermalResistor(; name, R = 1.0)
    @named oneport = OnePort()
    @named heat_port = HeatPort()
    @unpack v, i = oneport
    pars = @parameters R = R [description = "Resistance"]
    eqs = [
        v ~ R * i,
        heat_port.Q_flow ~ v * i,
    ]
    return extend(System(eqs, t, [], pars; name, systems=[heat_port]), oneport)
end

9. Platform parsing behavior

The platform parses component source in two phases:

Phase Execution environment What is extracted
Phase 1: AST scan Inside the API process, based on the syntax tree mtk_name (@mtkmodel Name / @component function Name), description, module path, parameter preview (@parameters block / function signature kwargs)
Phase 2: MTK introspection A separate MTK subprocess that actually loads the source Exact port (acausal / input / output connectors) and parameter information

A few notes:

  • Phase 2 loads your component file together with the source of the other components visible to that user, so cross-file references (e.g. extend a type defined in another library file) resolve normally.
  • When Phase 2 succeeds, parameters are overwritten by the MTK introspection result — only real @parameters appear in the parameter panel, not plain non-MTK keyword arguments (e.g. N=10).
  • If Phase 2 introspection fails for one component, that component falls back to the information extracted in Phase 1; if semantic validation of the whole file fails, the file status is set to Failed, and the expanded row in the My MTK Components list shows the error details.
  • An empty port list does not affect parsing, but the component has no pins to connect once dragged onto the canvas — components meant for modeling should produce ports as described in §4.1.

10. Common errors

Error Cause Fix
@mtkmodel not defined The @mtkmodel macro has been removed from the current environment Define components with @component function instead
expected 'end' Missing block structure Check the begin ... end of @parameters / @variables and the function body's end
No component definition found The file has no @mtkmodel / @component Add at least one component definition
t_nounits not imported Missing using ModelingToolkit: t_nounits as t Add the import shown above
Port anchor fallback The SVG data-port does not match the port names in the code Fix the icon or the component port names
No ports after upload A connector was not placed in the top-level systems (e.g. a bare OnePort) Produce ports as in §4.1 — attach connectors directly or use extend
compile_error at simulation A third-party package that is not installed Remove it or ask the administrator to install it

11. Next steps