---
name: motorxp-engineering
description: Creates, reviews, validates, and troubleshoots MotorXP-PM and MotorXP-AFM MATLAB workflows, geometry templates, FEA studies, TSEMO optimization scenarios, Pareto analysis, resume logic, and design export. Use when working with .mxp or .mxa designs, MotorXP MATLAB APIs, JavaScript geometry scripts, JSON parameter maps, optimization runners/evaluators, MAT result files, or MotorXP validation and plotting tasks.
---

# MotorXP Engineering

## Core rules

1. Treat the installed `manual.pdf`, shipped MATLAB examples, and installed JSON maps as authoritative. Inspect them before inventing a parameter name, function signature, result field, or topology rule.
2. Use the user's base `.mxp` or `.mxa` design as the source of topology, winding layout, materials, temperatures, magnetization, stacking factors, and other settings not explicitly made variable.
3. Do not start an optimization, batch FEA run, or other long calculation unless the user explicitly requests execution. Script creation and validation do not imply permission to run.
4. Separate read-only diagnosis from implementation. Do not modify installed examples, base designs, result files, or product assets unless the user explicitly requests that exact change.
5. Preserve existing user changes. Create study-specific files and unique result names instead of overwriting a completed study.

## Confidentiality gate

Treat project inputs and results as confidential by default.

- Do not copy customer or employer names, personal names, project code names, operating points, exact dimensions, material selections, performance results, serial numbers, screenshots, proprietary paths, or MAT data into reusable skills, templates, examples, or general documentation.
- Replace sensitive content with neutral placeholders such as `[MOTORXP_ROOT]`, `[PROJECT_ROOT]`, `[BASE_DESIGN]`, `[TARGET_SPEED]`, `[TARGET_TORQUE]`, `[LOWER_BOUND]`, and `[UPPER_BOUND]`.
- Extract reusable algorithms and contracts, not project facts. Avoid browsing unrelated folders, correspondence, contracts, credentials, or licensing files.
- Before publishing a reusable artifact, scan it for names, email addresses, company identifiers, project paths, exact operating values, and copied result rows. Report uncertain items instead of guessing that they are safe.

## Locate the installation

Prefer a root supplied by the user. Otherwise read the product registry value without changing it:

- MotorXP-PM: `HKCU/Software/VepcoTech/MotorXP-PM/RootPathMatlab`
- MotorXP-AFM: `HKCU/Software/MotorXP LLC/MotorXP-AFM/RootPathMatlab`

Confirm the root contains `manual.pdf`, `CustomScripts`, `SimFiles`, and the expected API initialization function. Do not hardcode a version-specific folder when registry or user configuration is available.

## Product map

### MotorXP-PM

- Design file: `.mxp`
- Initialize: `initMXPscriptingAPI`
- Read: `readData`
- Public parameter access: `setParampm` and `getParampm`
- Assemble: `assembleMXP`; parallel family `initAssembleMXP_par`, `runAssembleMXP_par`, `getAssembleMXP_par`
- Magnetostatic FEA: `runMStimestepping`; parallel family uses the `_par` functions
- Optimization: `runTSEMOptimizationpm`, `plotPareto`, `plotParetoFromFile`

### MotorXP-AFM

- Design file: `.mxa`
- Initialize: `initMXAscriptingAPI`
- Read: `readDataafm`
- Public parameter access: `setParamafm` and `getParamafm`
- Assemble: `assembleMXA`; parallel family uses the MXA `_par` functions
- Magnetostatic FEA: `runMStimesteppingafm`; parallel family uses the AFM `_par` functions
- Optimization: `runTSEMOptimization`, `plotPareto`, `plotParetoFromFile`

Verify exact signatures in the installed manual and closest shipped example. Similar PM and AFM function names are not interchangeable.

## Parameter maps and geometry templates

### MotorXP-PM assets

Inspect `[MOTORXP_PM_ROOT]/bin/assets/scripts` when a task involves parameter discovery or custom geometry.

- `motorProps.json` maps public `setParampm`/`getParampm` names to fields for machine dimensions, winding, air gap, axial, and mesh data.
- `settingsMagnetostatic.json` maps public magnetostatic-setting names to internal fields.
- `Stator/*.js` and `Rotor/*.js` generate geometry. A same-basename `.json` maps template-specific public names to `motorProps.stator.scriptProps.*` or `motorProps.rotor.scriptProps.*`.
- `Stator/.stators.json` and `Rotor/.rotors.json` register templates, applicability, and preview/manual assets. Preserve the existing schema when adding or renaming a template.
- `sDraw.js`, `drawObj.js`, and `Matrix.js` are shared geometry helpers. Inspect them to understand available drawing objects and transformations; do not modify them for a routine template change.
- Preview images are UI assets, not geometry definitions.

When editing a PM template, keep the JavaScript filename, same-basename JSON map, registry entry, applicability, and preview references synchronized. Validate both inner- and outer-rotor applicability when relevant.

### MotorXP-AFM assets

Inspect `[MOTORXP_AFM_ROOT]/bin/assets/scripts`.

- `motorProps.json` and `settingsMagnetostatic.json` define the public parameter names used by `setParamafm` and `getParamafm`.
- `Stator/*.js` and `Rotor/*.js` are template generators; their same-basename JSON files map public names into the corresponding `scriptProps` structures.
- `Stator/.stators.json` and `Rotor/.rotors.json` register selectable templates and metadata.
- `Geometry.js` provides shared geometry generation and assembly behavior. Inspect it when tracing template loading or validation, but do not modify it for normal parameter changes.
- `WindingEndturns` contains end-winding geometry scripts and registration data. Treat end-winding geometry as a separate compatibility surface.
- Type declarations, helper scripts, and preview images support scripting and UI behavior; they do not replace the MATLAB API contract.

Validate AFM topology, yoke/yokeless construction, pole arrangement, stator/rotor template compatibility, winding type, magnet segmentation, and generated source geometry before FEA.

## Start every study with a design contract

Record the following before writing code:

- Product and installation root
- Base design and output folder
- Motor or generator mode and operating targets
- Fixed topology, slot/pole combination, winding layout, materials, temperatures, magnetization, and mesh
- Fixed package dimensions and dependent dimensions
- Ordered variables with definitions, units, bounds, and mapping rules
- Objectives with formulas, units, direction, and normalization basis
- Constraints and tolerances
- Required raw and auxiliary outputs, fixed column positions, and error-code meanings
- Parallel-process limit and available memory assumptions
- Initial sample size, batch size, iteration/evaluation limit, and deterministic seeds
- Unique MAT filename, run signature, resume policy, plotting requirements, and MXP/MXA export behavior
- Explicit instruction whether to validate only or execute

If a missing choice would materially change the formulation, stop and ask for it. Do not substitute an unstated operating point or geometry assumption.

## Choose the scenario type

### Geometry-specific absolute-dimension scenario

Use physical dimensions directly when the study targets one known size, topology, and manufacturing envelope. Start from the closest shipped absolute-dimension runner/evaluator pair and preserve its product-specific calling contract.

### Generalized normalized-variable scenario

Use ratios or normalized electromagnetic variables when the formulation must transfer across related sizes or topologies. Derive physical dimensions locally from the candidate geometry. Keep optional package dimensions absolute when required.

Do not mix unrelated categorical or discrete alternatives in one continuous run. Treat topology, slot/pole combination, winding layer/layout, material family, and similar choices as separate design spaces unless the optimizer and evaluator explicitly support those variable types. Compare design spaces by their validated Pareto fronts.

## Objective and constraint rules

- TSEMO objectives are minimized. Convert a maximization objective with a documented monotonic transformation, such as minimizing `1 - metric` when the metric range makes that valid.
- Prefer two or three clearly interpretable objectives. Use staged studies instead of hiding many unrelated objectives inside an arbitrary weighted sum.
- Keep objective units and normalization explicit. If losses are normalized to a target mechanical power, store the raw loss and the normalization basis separately.
- Make torque, power, current density, voltage, length, demagnetization, thermal, package, manufacturing, and geometry rules deterministic checks with tolerances and error codes.
- If a dimension is dependent, calculate it from an explicit formula, validate it, store it in a documented column, and use the stored value for later export.

## Implementation pattern

Create separate study-specific files when appropriate:

1. Problem/configuration function: targets, variables, bounds, labels, tolerances, error codes, paths, and run signature.
2. Preparation function: read the base design once, reconstruct the reference vector, and populate stable `Userdata`.
3. Runner: define editable optimizer sizes, seeds, process limit, unique result path, and safe resume.
4. Evaluator: map X rows to valid motor properties, assemble, run FEA, calculate objectives, and return diagnostics.
5. Validator: perform deterministic structural and numerical checks without starting the long optimization.
6. Plotter/export helper: add only when generic plotting or the normal export path cannot represent the study safely.

Keep MATLAB function names within MATLAB's identifier-length limit. Keep variable order identical in bounds, seeds, evaluator mapping, labels, signatures, and saved results.

## Evaluator pipeline

Implement the stages in this order:

1. Check row width, finite values, and requested bounds. Reject violations; never silently clip.
2. Reconstruct normalized or dependent geometry. Reject negative, zero, overlapping, non-fitting, or otherwise inconsistent dimensions before calling the geometry engine.
3. Start each row from an isolated copy of the prepared base state. Apply only intended variables, then reapply protected winding and mesh settings when the workflow requires it.
4. Assemble prevalidated designs in parallel. Retry isolated parallel failures once sequentially and preserve the original diagnostic.
5. Run the minimum solve needed for current, length, or operating-point sizing, then run the final multiposition analysis required by the objectives.
6. Verify formulation-specific tolerances on the final analysis.
7. Store raw physical results in `Ypareto` or another documented raw matrix. Apply finite optimizer penalties only to objective columns in `Y`.
8. Reject or replace NaN/Inf before returning to the optimizer, while preserving an explicit error code and message.

Use finite sentinels that are clearly worse than feasible values but remain numerically safe. Do not allow failed rows to appear as excellent physical designs.

## Export contract

Support the evaluator's `nargout == 2` path when `plotPareto` saves a selected design.

- Return a valid `motorProps` structure and empty objective output.
- Reconstruct only what export requires; do not start a new optimization.
- For a dependent dimension already saved in the result matrix, treat the saved value as authoritative. Attach an X-to-value lookup before plotting, require one unique match, and error on missing or ambiguous matches.
- Do not silently rerun FEA or recalculate a dependent value during export unless the user explicitly chose that behavior.
- Test export in a fresh MATLAB session.

## Safe MAT results and resume

- Use a unique result filename and a formulation/run signature.
- Save the function handle needed by `plotParetoFromFile`, base-design context, `motorProps`, settings, labels, `Userdata`, X, Y, raw results, reference result, and export lookup when applicable.
- Resume only when signatures, variable order, bounds, objective count, required fields, row counts, seeds, and saved auxiliary columns are compatible.
- Refuse to overwrite or resume an unsigned or incompatible MAT-file. Do not resume a partial initial batch unless the wrapper explicitly supports it.
- Keep X, Y, and raw-result rows aligned after every save and resume.

## Validation checklist

Before execution, verify:

- API initialization and base-design reading
- Reference-vector reconstruction and protected settings
- Variable order, units, bounds, and seed inclusion
- Geometry pre-screening with known valid and invalid rows
- Fixed/dependent quantities and final operating-point tolerances
- Objective formulas, raw-result columns, error codes, and finite penalties
- Parallel evaluation and one sequential fallback
- `nargout == 2` export without unintended assembly or FEA
- Unique result path, run signature, safe resume, and lookup persistence
- `plotParetoFromFile` from a fresh session

After a run, filter explicit failures and penalty sentinels before recomputing nondominated sets. State whether a plot is a full objective front or a lower-dimensional projection. Verify selected minimum, knee, or balanced designs against raw physical values before exporting them.

## Resource sizing and execution

Choose the process limit below the physical-core count and below the memory-based capacity measured from a representative simulation. Make initial sample size, sequential batch size, and iteration count easy to edit. Align batch size with available workers when practical.

During a long run, provide concise status from the MATLAB command line. Do not consume time by repeatedly rereading unchanged files or producing speculative summaries. On failure, stop orphaned workers only when authorized, preserve logs and partial results, diagnose the stage, and resume only through the validated wrapper.

## Codex working style

- Announce the skill and the immediate action in a concise commentary update.
- Inspect with `rg` and read-only commands first. Use `apply_patch` for local edits and preserve unrelated user changes.
- Ask before actions that expand scope, overwrite data, start lengthy FEA, or require new external authority.
- Lead the handoff with the achieved outcome, validation evidence, pending risks, and exact deliverable paths.
