Docs/Code-Based Modeling/Code ↔ Diagram Two-Way Sync

Code ↔ Diagram Two-Way Sync

The CoModel canvas and the Julia / MTK source describe the same model. Through two-way sync between Code and Diagram, you can hand-write equations in the code view and restore them as a diagram in one step, or drag connections on the canvas and have the system generate the corresponding source automatically.

Rendering after editing text and switching to the Diagram tab

Text → Diagram

When switching from the Code tab to the Diagram tab, if the text is newer than the current diagram, the platform first runs syntax validation, then parses the text into graphJson, and finally renders it with React Flow.

Parsing recognizes the following elements:

Element Description
Component instances Component calls such as @named r1 = Resistor(R=1.0)
Connection equations connect(...), a.p ~ b.p, a.i + b.i ~ 0
Input/Output endpoints RealInput / RealOutput, ports exposed by subsystems
@comodel: comments Preserve diagram metadata such as node positions, port layout, and connection relationships

Connection Equation Recognition

The platform maps three common connection forms to diagram edges:

Connection form Example Diagram mapping
connect call connect(r1.p, c1.p) Multi-port connections expand into multiple edges or multi-terminal connections
Endpoint equality r1.v ~ source.v An edge marked as equality
Endpoint zero-sum r1.i + r2.i ~ 0 An edge marked as sum-to-zero
using ModelingToolkit
using ModelingToolkit: t_nounits as t, D_nounits as D

@named constant = Constant(k=5.5)
@named source = Voltage()
@named r1 = Resistor(R=1)
@named c1 = Capacitor(C=1.0e-6)
@named ground = Ground()

eqs = [
    constant.output.u ~ source.V.u,
    connect(source.p, r1.p),
    connect(r1.n, c1.p),
    connect(c1.n, source.n),
    connect(source.n, ground.g)
]

Input/Output Endpoint Recognition

  • Causal ports (RealInput / RealOutput) render with directional markers on the shape.
  • Ports exposed by a subsystem System(...) map to the corresponding positions on the subsystem boundary.
  • Acausal physical ports and causal signal ports use distinct visual styles.

Automatic Layout

When the text is hand-written or comes from an external .jl, the platform applies a grid-tiling automatic layout to new shapes:

  • Nodes are placed one by one from a fixed origin using fixed node sizes and row/column spacing, so no two node bounding boxes overlap.
  • Elements that already have position comments keep their original coordinates and are not overwritten by the automatic layout.
  • Elements inside a subsystem are tiled separately within their container.

Component layout after automatic tiling

Elements Without a Graphical Counterpart (Opaque Segments)

Model-level custom equations, parameter expressions, macros, and similar may have no corresponding shape. For example, a function:

function opaque_fun1()
end

These elements are marked as opaque segments:

  • They always remain in the authoritative .jl source and are never dropped.
  • The diagram canvas shows a read-only banner at the top: "This model contains elements that can't be shown graphically (N). Switch to text to view the full code."
  • When the text is regenerated after diagram edits, CodeGen merges these opaque segments back in, so nothing is lost across round trips.

The opaque-segments banner

Diagram → Text

After you drag, connect, or edit parameters in the Diagram tab, the system generates text after about 800 ms of inactivity. The generated code contains the # @comodel: comment series for later high-fidelity restoration.

When switching to the Code tab:

  • If the text has unsaved changes, a confirmation dialog appears: "Switching will overwrite the current unsaved text with code generated from the diagram. Continue?"
  • After confirmation, the editor content, textBaseline, and graphSyncBaseline are all in agreement.

Diagram → Text sync result

Source-of-Truth State Machine

Sync is driven by three core states:

State Meaning
textContent The current content of the text editor
textBaseline The text content at the last persisted save
graphSyncBaseline Which text the current diagram was built from

Decision rules:

// Text → diagram
if (textContent === graphSyncBaseline) {
    // text unchanged; switch directly
} else {
    syncTextToGraph()   // validate → parse → rebuild the diagram
}

// Diagram → text
if (textDirty) {
    // confirm the overwrite in a dialog
}
syncTextFromGraph()    // generate the code and write it into the editor

Round-Trip Fidelity

The core guarantee of two-way sync is the # @comodel: comment series. The platform requires both of the following round trips to preserve semantics:

  1. Diagram → text → diagram: generating text from the diagram and parsing it back loses no nodes, edges, ports, or parameters.
  2. Text → diagram → text: valid text (with comments) parses into a diagram and regenerates text that is semantically equivalent; opaque segments are preserved.

For external .jl files without comments, the platform uses best-effort parsing plus automatic layout plus the opaque-segment fallback, ensuring no crashes and no lost code.