Logo: Plecs Cscript

Plecs Cscript

Communautéit
labourer-Lucas
plecs-cscript

Write, review, debug, and explain PLECS C-Script code for custom control blocks in PLECS simulations. Use this skill whenever the user asks about C-Script, wants to implement a custom block in PLECS, needs help with PLECS macros (InputSignal, OutputSignal, ContState, DiscState, ZCSignal, etc.), asks about sample time configuration, state variables, zero-crossing detection, user parameters, or needs to port controller C code into a PLECS simulation. Trigger even if the user just mentions "PLECS block", "custom block", "C-Script", or "cscript".

Iwwersiicht

Editeurlabourer-Lucas
RepositoryPLECS-C-Script-Skill
Skill-Nummplecs-cscript
Stären
29
Forks
7
Matgeliwwert Dateien
4
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • 4 matgeliwwert Dateien

    Skripten, Virlagen a Referenzen, déi de Modell beim Schaffe liese kann. D'Dateie kënnen nëmme gelies ginn a ginn ni ausgeféiert.

  • Open Source

    labourer-Lucas huet de Skill op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Plecs Cscript an TypingMind, fir e mat all LLM ze benotzen, oder setzt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vu GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier, déi hei drënner steet, an a bestätegt d'Installatioun.
    https://github.com/labourer-Lucas/PLECS-C-Script-Skill/tree/main/skills/plecs-cscript
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill derbäisetzen → Iwwer eng GitHub-URL. Pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an d'Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/labourer-Lucas/PLECS-C-Script-Skill.git /tmp/PLECS-C-Script-Skill
mkdir -p .claude/skills
cp -r /tmp/PLECS-C-Script-Skill/skills/plecs-cscript .claude/skills/plecs-cscript
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Plecs Cscript an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Plecs Cscript automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Plecs Cscript net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Schlësselen.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

PLECS C-Script Skill

You are an expert on PLECS C-Script custom control blocks. When this skill is active, generate correct, well-structured C-Script code that integrates cleanly with the PLECS solver.

For the full macro reference, see references/macros.md. For complete worked examples, see references/examples.md. If the user is editing or generating a .plecs file, load references/plecs-file-format.md and references/cscript.plecs for the complete file format and a working reference model.(CAUTION: if not required or edited directly, DO NOT GENERATE .plecs files)


ALWAYS READ ALL LINES OF THIS DOCUMENT SKILL.MD before making changes.

C-Script Architecture

Block Setup Parameters

These are configured in the Setup tab of the C-Script block dialog before writing any code.

Number of inputs

Defines the number and width of input ports.

ValueEffect
n (scalar integer)Single input port accepting a scalar signal
[n1, n2, ...] (vector)Multiple input ports; port i accepts a signal of width ni
-1Dynamic sizing: width determined by connected signal

Format note: In the PLECS dialog both comma-separated ([2, 3]) and space-separated ([2 3]) are accepted. Inside .plecs files the space-separated form is used (e.g. "[2 3]").

Access in code: InputSignal(portIndex) or InputSignal(portIndex, elementIndex)

Number of outputs

Same rules as Number of inputs.

Access in code: OutputSignal(portIndex) or OutputSignal(portIndex, elementIndex)

Number of cont. states

Integer ≥ 0. Number of continuous state variables integrated by the ODE solver.

Access in code: ContState(i), ContDeriv(i)

Number of disc. states

Integer ≥ 0. Number of discrete state variables updated at each sample step.

Access in code: DiscState(i)

Number of zero-crossings

Integer ≥ 0. Number of zero-crossing signals monitored by the solver for event detection.

Access in code: ZCSignal(i)

Direct feedthrough

Controls whether each input is a direct feedthrough (output depends on input at same instant).

ValueMeaning
1Input is direct feedthrough — can be used in Output section
0Input is NOT direct feedthrough — must NOT be used in Output; use only in Update

Can be a scalar (applies to all inputs) or a vector matching Number of inputs.

Warning: Incorrect Direct feedthrough settings with feedback loops cause algebraic loops and simulation failure.

Sample time

Controls when the C-Script executes.

ValueMeaning
0 or [0, 0]Continuous: runs at every ODE solver step
[0, -1]Semi-continuous: runs at major time steps only
Ts or [Ts, 0]Discrete: runs every Ts seconds
[Ts, To]Discrete with offset To: first hit at To, then every Ts
-1Inherited: determined by connected signals
-2 or [-2, 0]Variable-rate discrete: script controls its own next execution time via NextSampleHit

Use terminal-based sample times

Checkbox. When enabled, the sample time is no longer set in the Setup tab but is instead inherited from the signals connected to each port individually. Useful when the block needs to match the sample rate of dynamically connected components.

Language standard

Dropdown (C89, C99, C11, …). Selects the C language standard used by the built-in compiler. Default is C99. Use C99 or later for // line comments, <stdbool.h>, <stdint.h>, designated initializers, and variable-length array declarations.

Enable GNU extensions

Checkbox. When enabled, activates GCC/Clang GNU extensions (e.g. __attribute__, statement expressions, nested functions). Avoid unless integrating external code that requires them, as it may reduce portability.

Highlight Level

Integer ≥ 0. Controls the amount of diagnostic / highlight output shown during simulation for this block. 0 disables highlighting. Higher values produce more verbose output. Useful for debugging — set back to 0 for production.

Enable runtime checks

Checkbox (enabled by default). When checked, all macro accesses (signal indices, state indices, parameter indices) are bounds-checked at runtime, and solver policy violations (e.g. writing DiscState during a minor step) are caught and reported. Disable only after the block is fully validated, as disabling it turns out-of-bounds accesses into silent undefined behavior that can crash PLECS.

Parameters

Named parameters passed to the block. Accessible in code via ParamRealData(i, j) (real) or ParamStringData(i) (string). Enter as a comma-separated list of MATLAB expressions in the Parameters field; workspace variables are resolved at simulation start.


Code Sections

Code Declarations

When called: Once, before any simulation. Acts as the file header.

Purpose: #include headers, define macros, declare static variables, write helper functions.

Example:

c
#include <math.h>
#include <stdlib.h>

/* Signal aliases */
#define U0   InputSignal(0, 0)
#define Y0   OutputSignal(0, 0)
#define X0   ContState(0)
#define XD0  DiscState(0)

/* Parameter aliases */
#define KP   ParamRealData(0, 0)
#define KI   ParamRealData(1, 0)
#define TS   SampleTimePeriod(0)

static double myInternalVar = 0.0;

Start

When called: Once at the beginning of simulation (after Code declarations).

Purpose: Initialize state variables, open files, allocate dynamic memory.

c
/* Initialize continuous state */
ContState(0) = 0.0;

/* Initialize discrete states */
DiscState(0) = 0.0;
DiscState(1) = 0.0;

Output

When called: Every simulation time step (or every sample hit for discrete blocks).

Purpose: Compute and write output signals. May read inputs (if direct feedthrough) and states.

c
/* Use previous discrete state (non-direct feedthrough pattern) */
OutputSignal(0, 0) = DiscState(0);

/* Or with direct feedthrough */
OutputSignal(0, 0) = InputSignal(0, 0) * ParamRealData(0, 0);

Rule: If Direct feedthrough = 0 for input i, do NOT read InputSignal(i, j) in this section.


Update

When called: Once per major time step, after Output.

Purpose: Update discrete states. This is the place to use non-direct-feedthrough inputs.

c
/* Update integral */
DiscState(0) = DiscState(0) + ParamRealData(1, 0) * SampleTimePeriod(0) * InputSignal(0, 0);
/* Store current input for next Output call */
DiscState(1) = InputSignal(0, 0);

Derivative

When called: Potentially multiple times per time step by the ODE solver (during sub-steps).

Purpose: Compute derivatives of continuous states. Must set ContDeriv(i) for every continuous state.

c
/* First-order lag: tau * dx/dt = u - x */
ContDeriv(0) = (InputSignal(0, 0) - ContState(0)) / ParamRealData(0, 0);

Warning: Do NOT modify DiscState or output variables here. Guard side-effects with if (IsMajorStep).


Terminate

When called: Once at the end of simulation.

Purpose: Free dynamically allocated memory, close open files.

c
free(myBuffer);
fclose(logFile);

Store Custom State

When called: Once when PLECS saves a simulation snapshot (e.g., before a restart from a saved state).

Purpose: Serialize non-standard state that PLECS does not persist automatically. ContState and DiscState are saved automatically — only use this section for NextSampleHit, heap-allocated buffers, or any other custom values.

c
WriteCustomStateDouble(NextSampleHit);
WriteCustomStateInt(bufferCount);
for (int i = 0; i < bufferCount; ++i)
    WriteCustomStateDouble(buffer[i]);

Order matters. The read sequence in Restore Custom State must exactly mirror the write sequence here.


Restore Custom State

When called: Once when PLECS restores a simulation snapshot.

Purpose: Deserialize the values written by Store Custom State, in the same order.

c
NextSampleHit = ReadCustomStateDouble();
bufferCount   = ReadCustomStateInt();
for (int i = 0; i < bufferCount; ++i)
    buffer[i] = ReadCustomStateDouble();

Macro Reference

Quick reference — covers the most-used macros. For the complete list including block topology, custom state serialization, and error reporting macros, load references/macros.md.

Input/Output

MacroArgumentsReturnsDescription
InputSignal(i, j)i: port, j: elementdoublej-th element at input port i
OutputSignal(i, j)i: port, j: elementlvalueAssignable j-th element at output port i

State Variables

MacroArgumentsModeDescription
ContState(i)i: state index (0-based)read/writei-th continuous state variable
DiscState(i)i: state index (0-based)read/writei-th discrete state variable
ContDeriv(i)i: state index (0-based)write onlyDerivative of i-th continuous state (set in Derivative section)
ZCSignal(i)i: signal index (0-based)write onlyi-th zero-crossing signal value

Time and Stepping

MacroArgumentsReturnsDescription
CurrentTime—doubleCurrent simulation time t
SampleTimePeriod(i)i: sample time indexdoublePeriod Ts of i-th sample time (usually i=0)
SampleTimeOffset(i)i: sample time indexdoubleOffset of i-th sample time
IsSampleHit(i)i: sample time indexint (0/1)1 if i-th sample time fires at current major step
IsMajorStep—int (0/1)1 during a major time step; 0 during solver sub-steps
NextSampleHit—lvalueSet next execution time (only for Sample time = -2)

Parameters

MacroArgumentsReturnsDescription
ParamRealData(i, j)i: param index, j: elementdoublej-th element of i-th real parameter
ParamStringData(i)i: param indexchar*Pointer to null-terminated UTF-8 string for i-th string parameter

Execution Timing Summary

Simulation start
  └─ Code declarations (compiled once)
  └─ Start

Each major time step:
  └─ Output
  └─ Update          (discrete/semi-continuous only)
  └─ [ODE solver sub-steps]
       └─ Derivative (called repeatedly by solver for continuous states)

Simulation end
  └─ Terminate

Sample Time Reference

Sample time valueBlock typeUpdate called?Derivative called?
0ContinuousNoYes
[0, -1]Semi-continuous (major steps)NoYes
Ts > 0 or [Ts, 0]DiscreteYesNo
[Ts, To]Discrete with offset ToYesNo
-1InheritedDependsDepends
-2Variable-rate discreteYesNo

Structuring Generated Code

When the user asks for a C-Script implementation, always deliver all required sections with clear labels. Use this templates your skeleton and fill in only what each section needs,generate them in a .c file by default without indentation, and let the user copy-paste into the C-Script editor. Always include the section label as a comment, even if the section is empty, so the user knows where to paste each snippet in the dialog.:

c
/* === Setup Parameters ===
   NumInputs, NumOutputs, NumContStates, NumDiscStates, NumZCSignals,
   DirectFeedthrough, Ts, Parameters, LangStandard, etc.            */

/* === Code Declarations === */
/* #includes, #defines, static variables, helper functions */

/* === Start Function === */
/* Parameter validation, state initialization */

/* === Output Function === */
/* Compute outputs; guard state changes with IsMajorStep; update ZCSignals */

/* === Update Function === */
/* Update discrete states */

/* === Derivative Function === */
/* Set ContDeriv(i) */

/* === Terminate Function === */
/* Free resources */

/* === Store Custom State === */
/* WriteCustomStateDouble / Int for non-standard state */

/* === Restore Custom State === */
/* ReadCustomStateDouble / Int */

Decision Guide: Which Functions Do I Need?

Work through these questions top-to-bottom to determine the block's required configuration:

  1. Does the output depend on the current input? → Yes: enable Input has direct feedthrough

  2. Does the output or derivative change discontinuously based on input/state? → Yes: add ZCSignal entries, use continuous sample time [0,0]

  3. Do you need state that persists across major steps? → Continuous physics (integrate): use ContState + ContDeriv → Discrete memory (hold value): use DiscState + Update Function

  4. Does the block need to fire at exact user-controlled times? → Use discrete-variable sample time (-2) + NextSampleHit

  5. Does the block need to persist state across simulation restarts? → Implement Store / Restore Custom State


Common Patterns

Pattern A — Pure combinatorial (no state)

c
// Output Function
OutputSignal(0, 0) = InputSignal(0, 0) * InputSignal(1, 0);

Block setup: 1+ inputs, 1+ outputs, 0 states, direct feedthrough, sample time 0.

Pattern B — Discrete memory / delay

c
// Output Function
OutputSignal(0, 0) = DiscState(0);

// Update Function
DiscState(0) = InputSignal(0, 0);

Block setup: 1 discrete state, no direct feedthrough, sample time Tp.

Pattern C — Continuous integrator

c
// Output Function
OutputSignal(0, 0) = ContState(0);

// Derivative Function
ContDeriv(0) = InputSignal(0, 0);

Block setup: 1 continuous state, no direct feedthrough, sample time 0.

Pattern D — Piecewise / saturation with zero-crossings

c
// Code Declarations
static enum { NO_LIMIT, LOWER_LIMIT, UPPER_LIMIT } mode;

// Output Function
if (IsMajorStep)
{
    if      (InputSignal(0,0) >  upper) mode = UPPER_LIMIT;
    else if (InputSignal(0,0) < -lower) mode = LOWER_LIMIT;
    else                                mode = NO_LIMIT;
}
switch (mode)
{
    case NO_LIMIT:    OutputSignal(0,0) = InputSignal(0,0); break;
    case UPPER_LIMIT: OutputSignal(0,0) =  upper;           break;
    case LOWER_LIMIT: OutputSignal(0,0) = -lower;           break;
}
ZCSignal(0) = InputSignal(0,0) + lower;
ZCSignal(1) = InputSignal(0,0) - upper;

Block setup: 2 ZC signals, no discrete/continuous states, direct feedthrough, sample time 0.

Pattern E — Self-triggered (variable sample time)

c
// Start Function
NextSampleHit = CurrentTime + period;

// Output Function
if (IsSampleHit(0))
{
    // do work
    NextSampleHit = CurrentTime + period;
}

Block setup: discrete-variable sample time -2.


Accessing Multi-Element Parameters

Parameters are passed as flat arrays in column-major order. To index into a 2-D matrix:

c
int row = 1, col = 2;
int nRows = ParamDim(0, 0);
double val = ParamRealData(0, row + nRows * col);

For strings:

c
const char *label = ParamStringData(1);   // second parameter

Custom State Serialization

Prefer double and int over raw void* (raw data is byte-order dependent):

c
// Store Custom State
WriteCustomStateInt(count);
for (int i = 0; i < count; ++i)
    WriteCustomStateDouble(buffer[i]);

// Restore Custom State
count = ReadCustomStateInt();
for (int i = 0; i < count; ++i)
    buffer[i] = ReadCustomStateDouble();

Reference Files

  • references/macros.md — Full macro reference table (all macros, types, R/W, descriptions). Load when you need to verify a macro signature or produce a comprehensive summary.
  • references/examples.md — Complete worked examples (Times Two, Sampled Delay, Integrator, Wrapping Integrator, Saturation, Turn-on Delay, External Files). Load when you need a full end-to-end example to show the user or base new code on.
  • references/plecs-file-format.md — How C-Script blocks are stored in .plecs text files (variable names, value encoding, multi-line \n escaping, minimal block template). Load when the user is reading, creating, or editing a .plecs file directly.
  • references/cscript.plecs — Minimal but complete working .plecs model containing one C-Script block with all parameters at their defaults. Use as the authoritative reference for correct file syntax and default parameter values.

Matgeliwwert Dateien

De Modell liest dës Dateie bei Bedarf, wärend de Skill gelueden ass. Si ginn als liesbar Dateie bereetgestallt a ginn ni ausgeféiert.

Heefeg gestallte Froen

Wat mécht de KI-Skill Plecs Cscript?

Write, review, debug, and explain PLECS C-Script code for custom control blocks in PLECS simulations. Use this skill whenever the user asks about C-Script, wants to implement a custom block in PLECS, needs help with PLECS macros (InputSignal, OutputSignal, ContState, DiscState, ZCSignal, etc.), asks about sample time configuration, state variables, zero-crossing detection, user parameters, or needs to port controller C code into a PLECS simulation. Trigger even if the user just mentions "PLECS block", "custom block", "C-Script", or "cscript".

Firwat Plecs Cscript op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Plecs Cscript besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt, amplaz en Abonnement pro Benotzerplaz ze bezuelen. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Plecs Cscript an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/labourer-Lucas/PLECS-C-Script-Skill/tree/main/skills/plecs-cscript an. TypingMind liest d'Datei SKILL.md, bëndelt déi zougehéiereg Dateien an installéiert dat Ganzt als Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Plecs Cscript benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Plecs Cscript benotzen?

Esou vill wéi Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Plecs Cscript domat benotzen – zum Beispill mat GPT, Claude, Gemini, Grok, DeepSeek, Mistral oder Llama – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Plecs Cscript gratis?

Jo. labourer-Lucas huet de Skill ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbare Pak vun Instruktiounen, deen engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt e maache soll a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a kee Lafzäitëmfeld a funktionéiere mat all Modell.

Alleguer weisen

Elo Ären eegene KI-Aarbechtsberäich ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇