⏳ This skill is pending AI review.
Scores will appear once the review pipeline completes.
mumax3
Write, review, debug, and parameterize MuMax3 .mx3 simulations, including geometry, materials, fields, initial states, OVF output, Python batch workflows, and paper-guided phenomenon reconstruction.
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
// README
MumaxWriter.skill
A Codex skill project for helping AI agents write, review, parameterize, and maintain mumax3 .mx3 simulation code.
This repository contains a MuMax3 agent skill, reusable worked examples, and separate evaluation prompts.
Repository Layout
MumaxWriter.skill/
README.md
README.zh-CN.md
README.ja.md
examples/
prompts/
expected_outputs/
catalog/
manual_evaluation_checklist.md
skills/
mumax3/
SKILL.md
agents/
openai.yaml
assets/
templates/
minimal_relax.mx3.template
thin_film_with_region.mx3.template
local_ac_field.mx3.template
references/
language_subset.md
anti_patterns.md
api_index.md
api_patterns.md
api_full.md
examples.md
structures.md
parameter_sweep.md
output_and_reproducibility.md
compatibility_notes.md
installation.md
worked_workflows.md
paper_reconstruction.md
case_status.md
examples/
hysteresis/
standard_problem4/
paper_edge_canting/
fmr/
scripts/
check_mx3_static.py
render_template.py
collect_case_status.py
analyze_tutorial.py
analyze_edge_canting.py
sync_local_skill.py
docs/
release_notes_v0.1.0.md
release_notes_v0.2.0.md
release_notes_v0.3.0.md
release_notes_v0.4.0.md
third_party_sources.md
troubleshooting.md
tests/
validate_release.py
What The Skill Does
The mumax3 skill helps an AI agent:
- Write valid mumax3
.mx3scripts instead of full Go code. - Review scripts for common mumax3 syntax and API mistakes.
- Parameterize mumax3 scripts for batch simulations.
- Structure scripts around mesh, geometry, materials, initial states, fields, damping, output, and run stages.
- Decide when to use Python to generate scripts, run mumax3, organize outputs, fit results, and plot figures.
- Keep concise principles for coordinating writers, traceable inputs, adequate evidence, and separation of automatic findings from human interpretation.
- Leave task schemas, background scheduling, storage/release protocols and agent assignments to project guidance; load technical references only for the requested work.
Installation For Local Use
Copy the skill folder into your Codex skills directory:
Copy-Item -Recurse .\skills\mumax3 C:\Users\<you>\.codex\skills\mumax3
Then invoke it explicitly with:
Use $mumax3 to write or review this mumax3 script.
For an existing installation, preview and apply an exact, backed-up synchronization:
python skills\mumax3\scripts\sync_local_skill.py --dry-run
python skills\mumax3\scripts\sync_local_skill.py --apply
The apply operation backs up the current .../skills/mumax3 tree before replacing it and verifies source/target hashes.
Install From Codex Marketplace
Install the standalone skill from GitHub with:
npx codex-marketplace add msjs2333/MumaxWriter.skill/skills/mumax3 --skill
Then invoke it explicitly with:
Use $mumax3 to write or review this mumax3 script.
MuMax3 simulator setup is separate from skill installation. See the short installation guide for environment checks, official binaries, WSL/source-build options, and agent-assisted setup.
Quick Example
Use $mumax3 to write a minimal mumax3 thin-film relaxation script with SI units, table output, and a final OVF save.
Sequential scans can use native MuMax3 loops; independent cases may use Python orchestration. The optional collect_case_status.py expects a documented case layout, not arbitrary .out directories; see its --help and the output reference.
Local Validation
Run local validation from the repository root:
python tests\validate_release.py
# Documentation-only change:
python tests\validate_release.py --scope docs
# Helper change (includes helper tests once):
python tests\validate_release.py --scope helpers
The validator uses only the Python standard library. The default full scope checks metadata/links, maintained-file privacy terms, helper behavior, templates, static warnings and available engine vet. Missing engine checks are reported as skipped, not passed. Documentation scopes do not run simulations or helper suites. Exact prose and project-name blacklists are not test contracts.
Current Status
The current release is v0.4.0. It includes installed worked workflows for continuous hysteresis, field-1 Standard Problem 4 and pulsed macrospin FMR, with table analysis and explicit acceptance limits. Evaluation prompts remain under examples/prompts/; copying skills/mumax3/ includes the teaching cases and analysis tool.
Version 0.4.0 adds paper-to-phenomenon reconstruction: start from a target figure, build a small model with brief assumptions, and adjust toward the observed effect. An installed DMI edge-canting example links a public paper to runnable input and spatial-profile analysis.
These contracts are generic guidance and a validation surface. A research repository must implement and test the applicable state, lock, decision, output, and retention behavior locally; this skill update does not claim to migrate project task code or project data.
The examples and static checks are intended for skill validation and script hygiene. They do not prove physical correctness, numerical convergence, or publication readiness.
Start with the relevant project instructions and active task source; do not require a particular project-context filename or read unrelated history in full.
Future Roadmap
Planned directions for later releases:
- Evaluate optional Python-side data handling workflows, including possible use of the Ubermag ecosystem and related analysis tools.
- Add mumax+ compatibility, with the long-term direction of making mumax+ the primary target while keeping mumax3 support.
- Provide assisted migration workflows from existing mumax3
.mx3scripts to mumax+, including API mapping notes, behavior differences, and validation checklists. - Expand postprocessing examples for OVF/table output, spectra, mode maps, texture tracking, and sweep summaries.
Documentation
- Release notes v0.4.0: exploratory paper reconstruction and the DMI edge-canting example.
- Release notes v0.3.0: parameter consistency, installed modeling/analysis cases and validation scope.
- Release notes v0.2.0: MuMax3 setup guidance and skill maintenance updates.
- Release notes v0.1.0: initial public snapshot scope, compatibility, validation status, and known limitations.
- Example catalog: prompts, expected outputs, and coverage map.
- Third-party sources: external source and provenance notes.
- Troubleshooting: common local validation and mumax3 issues.
License
Licensed under the Apache License 2.0.
// HOW IT'S BUILT
// FILES
34 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
skills/mumax3/SKILL.md3.9 KB95f9cb281edfupstream ↗
--- name: mumax3 description: Write, review, debug, and parameterize MuMax3 .mx3 simulations, including geometry, materials, fields, initial states, OVF output, Python batch workflows, and paper-guided phenomenon reconstruction. metadata: short-description: Write and parameterize mumax3 scripts --- # mumax3 Use native MuMax3 for `.mx3` simulations. Python can handle case generation, analysis and plotting when useful; keep existing workflows unless the request calls for a change. ## Start with the requested work Read the target script and relevant task instructions. Use current source and input records to resolve parameters; generic examples and historical plans are not evidence of what ran. Do not load an entire project history for a local edit. - **Edit or generate a script:** check the identifiers and patterns you need in [api_index.md](references/api_index.md) and [api_patterns.md](references/api_patterns.md), not both files in full by default. - **Syntax uncertainty:** use [language_subset.md](references/language_subset.md) and [anti_patterns.md](references/anti_patterns.md). MuMax3 is Go-like, not full Go. Do not redeclare built-ins such as `mu0`, `t`, `m`, or `B_ext`. - **Missing/disputed API:** search [api_full.md](references/api_full.md); consult [compatibility_notes.md](references/compatibility_notes.md) and the official API for version-sensitive behavior. Do not invent identifiers. - **Model-specific help:** choose [structures.md](references/structures.md) or [examples.md](references/examples.md). - **Rebuild a phenomenon from a paper or figure:** use [paper_reconstruction.md](references/paper_reconstruction.md); start with an exploratory model and the main trend. - **Complete modeling and analysis examples:** use [worked_workflows.md](references/worked_workflows.md) for continuous hysteresis, Standard Problem 4, and macrospin FMR, including output checks and parameter changes. - **Output or sampling design:** use [output_and_reproducibility.md](references/output_and_reproducibility.md). - **Parameter scans:** use [parameter_sweep.md](references/parameter_sweep.md) to choose native sequential sweeps or external case orchestration. - **Installation or missing engine/GPU:** use [installation.md](references/installation.md) for environment checks and an authorized MuMax3 setup; skip it for ordinary script work. ## Scientific and execution principles - **Single writer:** coordinate concurrent changes to the same output; independent outputs need not serialize. Use the project's existing mechanism when present. - **Traceable inputs:** keep reused inputs and derived results identifiable; content identity alone does not establish physical compatibility. - **Adequate evidence:** choose quantities and sampling for the scientific question. Orientation or switching may need vector evidence over a time window; a display image need not show every component. - **Human/automatic separation:** distinguish execution, automated findings and human interpretation; automatic results do not silently replace a human classification. ## Check the changed behavior For physical edits, check SI units, mesh/cell size, geometry and region assignments, field/mask interactions, and required outputs. Reused states should fit the mesh, geometry and physical role of the new stage. Scope the checks to what changed. `scripts/check_mx3_static.py path/to/file.mx3` provides conservative warnings, not proof of valid physics. Use engine `mumax3 -vet` when syntax/API changes warrant it; report unavailable checks. Numerical convergence and scientific acceptance require task-appropriate evidence, not a blanket checklist. ## Helpers - `scripts/render_template.py`: render `assets/templates/*.mx3.template` using JSON or `KEY=VALUE` parameters. Project-specific state schemas, monitoring schedules, storage/prune protocols, and agent assignments belong in project guidance, not in this skill's default workflow.skills/mumax3/examples/fmr/README.md3.0 KB2ae4133b0591upstream ↗
# Pulsed macrospin FMR: simulation to spectrum This is an isotropic, single-cell frequency check, not a thin-film Kittel or propagating-wave model. Demagnetization and anisotropy are disabled. A 0.1 T z bias prepares `m=(0,0,1)`; a 1 mT transverse pulse lasts 50 ps, then the free response is recorded for 10 ns at 5 ps cadence. During observation, fixed-step RK4 takes ten 0.5 ps integration steps per saved sample. Damping is 0.01 and `GammaLL=1.7595e11 rad/(T s)`. These model choices make the expected frequency analytically identifiable: the Gilbert equation for a uniform spin in constant field gives `f = GammaLL*B/(2*pi*(1+alpha^2))`, about 2.800 GHz. Use the [official MuMax3 API](https://mumax.github.io/api.html) for `GammaLL` units, dynamic fields, solver and demagnetization controls. The script and analysis are independently written; the analytic frequency is not estimated from a stored simulation fixture. From this folder, with a fresh output name: ```text mumax3 -http= -o fmr.out script.mx3 python ../../scripts/analyze_tutorial.py fmr fmr.out ``` ## Output and acceptance - Input: `script.mx3`, including all model/pulse/sampling constants. - Output: initial/final magnetization OVFs and 2001 table rows **after the pulse**, from 50 ps to 10.05 ns. The table records the actual bias, damping, gyromagnetic ratio, pulse duration, sample interval and observation duration used by the script. - Analysis: subtract the mean from `mx,my`, apply a Hann window, and calculate positive-frequency DFT power of both transverse components. `analysis/spectrum.csv` contains frequency in Hz and arbitrary power; `summary.json` records the measured peak, analytic value, bin width, tolerance and table hash. Plot the CSV to inspect the full spectrum, not only the largest bin. - Missing/irregular samples, non-finite values, no transverse signal, insufficient cycles/samples or a peak beyond `max(2/T, 2% of f)` fail. The default bin width is approximately 0.1 GHz. This finite-window tolerance checks the frequency, not linewidth, absolute susceptibility or damping fits. ## Modify and verify Change the bias and expect frequency to scale linearly; metadata and analytic comparison follow the script's table columns. Ensure at least ten cycles and ten samples per expected period. Change `nSamples` at fixed `samplePeriod` to improve frequency resolution; decreasing the sampling interval alone does not improve `1/T`. Halve pulse amplitude and verify an unchanged peak in the small-angle regime. The standard-library DFT is limited to 10000 saved rows (`nSamples <= 9999`, including the initial row); use an FFT implementation for larger studies. Adding anisotropy, demagnetization or spatial modes changes the dispersion: replace this analytic test with the applicable model instead of loosening its tolerance. Noise or truncated traces used in unit tests validate the analysis code only. Engine execution, analytic agreement, timestep convergence and model applicability are separate claims.skills/mumax3/examples/hysteresis/README.md3.0 KB6f83a4af82efupstream ↗
# Continuous hysteresis: state history matters This one-cell, zero-temperature uniaxial macrospin teaches continuation through metastable states. Demagnetization is disabled; `Ku1=50 kJ/m3`, `Msat=800 kA/m`, easy axis x give `B_k=2 Ku1/Msat=0.125 T`. A fixed 1 mT transverse field avoids exactly antiparallel zero torque. Sweep x from +0.2 to -0.2 T and back in 10 mT steps, carrying `m` between steps. Reinitializing `m` inside the loop changes the experiment. The [official MuMax3 hysteresis example](https://mumax.github.io/examples.html#Hysteresis) illustrates state continuation. This macrospin uses `Relax()` at every field step: energy minimization alone can stall near an unstable stationary state during reversal. `Minimize()` remains useful for neighboring states when its convergence is checked. This is an independently written macrospin model, not that example's film or its numerical reference curve. API units and anisotropy are documented in the [official API](https://mumax.github.io/api.html). From this folder, with a fresh output name: ```text mumax3 -http= -o hysteresis.out script.mx3 python ../../scripts/analyze_tutorial.py hysteresis hysteresis.out ``` The engine needs compatible NVIDIA/CUDA support. An existing output directory should be retained; use a new `-o` path rather than adding a force-clean option. ## Output and acceptance - Input: self-contained `script.mx3`; no external checkpoint or data file. - Output: `m_initial.ovf`, `m_final.ovf`, and 81 rows in `table.txt`, with normalized magnetization, actual applied field, branch identifier and model constants. `t` need not increase during minimization: the independent variable is field and branch. - Analysis: `analysis/curve.csv` preserves acquisition order; `summary.json` records both linearly interpolated `mx=0` crossing fields, the comparison value and the input-table hash. - For energy density `E=-Ku1 mx^2-Msat(Bx mx+By my)`, loss of a metastable minimum yields the Stoner-Wohlfarth astroid. With fixed `By`, the predicted switching magnitude is `B_k [1-(|By|/B_k)^(2/3)]^(3/2)`, about 0.1176 T here. This analytic value is derived for this macrospin energy, not a fitted reference from the simulation. - The checker requires complete ordered branches, saturation at the extremes, opposite switching signs, and each crossing within two field steps of that value. Missing reversal, truncated branches or non-finite data fail. These are tutorial tolerances, not universal accuracy targets. ## Modify and verify Change `fieldLimit` or `nIntervals` at the top; the script derives `fieldStep` and records it in the table. Halve the step and compare switching estimates (the uncertainty should shrink with the bracket). Change `Ku1`/`Msat` and retain `fieldLimit > B_k > |By| > 0`; the analysis uses the recorded `B_k`. Keep the transverse field small. Enabling demagnetization, adding cells or changing anisotropy invalidates this analytic contract and requires a new reference model. Independent parameter grids should instead restart each case from its specified preparation state.skills/mumax3/examples/paper_edge_canting/README.md5.0 KB631e5d18203cupstream ↗
# Paper reconstruction: DMI bends magnetization at an edge **Target:** the edge-canting phenomenon in Fig. 1 of S. Rohart and A. Thiaville, *Skyrmion confinement in ultrathin film nanostructures in the presence of Dzyaloshinskii–Moriya interaction*, Phys. Rev. B 88, 184422 (2013). Read the [public full text, Sections II and III A](https://arxiv.org/html/1310.0666v1) and [publication record](https://doi.org/10.1103/PhysRevB.88.184422). This example selects the edge profile, not the paper's later skyrmion results. The script, analysis and generated plot are original implementations; no paper figures or external code are bundled. ## What we take from the article Fig. 1(a) studies a 100 nm strip, uniform along y, initially magnetized along +z. Interfacial DMI tilts opposite edges in opposite x directions while the center stays nearly perpendicular. Section II uses exchange `A=16 pJ/m` and effective perpendicular anisotropy `K_eff=510 kJ/m³`; Fig. 1(a) uses `D=3 mJ/m²`. The local approximation absorbs the dipolar contribution into `K_eff`. That gives a minimal model: exchange + effective anisotropy + interfacial DMI, no applied field. Equation (8) gives the boundary scale `|mx| = |D|/(2 sqrt(A K_eff))`; the decay length is `sqrt(A/K_eff)`, about 5.6 nm. We use these to interpret the result, rather than to set a pass/fail threshold. ## Turn that into a short simulation `script.mx3` uses 128 x 1 x 1 cells across the 100 nm width, with periodic y and finite x. The chosen 0.78125 nm x spacing resolves the edge variation. The 1 nm y/z cell dimensions and damping 0.5 are demonstration choices; `Msat=1.1 MA/m` is borrowed from the paper's full-dipolar comparison. With demagnetization disabled and `Ku1=K_eff`, this is the paper's local-energy approximation, not that full-dipolar calculation. MuMax3's `Dind` convention has the opposite sign to the paper's Eq. (2), so the script uses **`Dind=-D_paper`**. Keep `OpenBC=false` to retain its DMI boundary treatment and avoid x periodicity, which would remove the target edges. The [official API](https://mumax.github.io/api.html) supplies the parameter names and units; the [DMI implementation](https://github.com/mumax/3/blob/6e5c98bb/cuda/dmi.cu) shows the derivative signs and treatment of missing neighbors. The protocol is simply `Uniform(0,0,1) → Relax → save profile`. Four independent preparations at paper-convention D = 0, 1.5, 3 and -3 mJ/m² give a zero-interaction control, a strength comparison and a sign reversal. Those extra controls are our teaching choices. A global `mx` average would almost cancel, so the observable comes from spatial OVFs. From this folder, using a new output name: ```text mumax3 -http= -o edge.out script.mx3 python ../../scripts/analyze_edge_canting.py edge.out ``` The run writes `table.txt` with the actual parameters and `m_case_0.ovf` through `m_case_3.ovf`. Analysis reads the text OVFs, prints edge/center values, and writes `analysis/profiles.csv` and `analysis/profiles.svg`. Open the SVG to compare `mx(x)` and `mz(x)`. Its x coordinates are cell centers measured from the left edge; the continuum expression refers to the boundary itself. ## Result note from an actual run - **Target/source:** Fig. 1 edge canting and its response to DMI strength/sign. - **Model:** reported A, K_eff and width; the local-energy approximation, chosen mesh/damping and extra controls above. - **Run/result:** MuMax3 3.12 (`6e5c98bb`, CUDA 12.9), RTX 5060 Laptop GPU, 2026-10-31; all four relaxations completed in 3.72 s. Rightmost-cell `mx` was 0, 0.24538, 0.49411 and -0.49411 respectively; the left edge had the opposite sign and central `mz` was approximately 1. The spatial profiles and controls recover the selected phenomenon. For context, continuum boundary magnitudes at positive D are 0.26255 and 0.52511; no figure digitization or quantitative fit was performed. - **Next adjustment:** if closer edge amplitudes matter, increase `nx` at fixed width and compare nearer-boundary samples. The first reconstruction already shows the intended shape and trend.  ## How to adapt when the picture differs - No edge signal: inspect the OVF rather than average `mx`; check `Dind`, finite x boundaries and `OpenBC` before increasing runtime. - Wrong tilt direction: compare the paper's DMI energy sign and the chosen +z initial state. Reverse D as a diagnostic. - Tilt too broad or narrow: vary A or K_eff using the `sqrt(A/K_eff)` length scale. Smaller K_eff broadens the edge region; increasing |D| increases tilt in this regime. - An entirely modulated state: reduce |D| first. The paper's quoted critical scale is about 3.6 mJ/m²; the simple near-uniform edge picture changes beyond it. For a full-dipolar extension, turn demagnetization on and replace effective anisotropy with the corresponding magnetocrystalline value, rather than counting the local shape contribution twice. That is a separate model change, not needed to obtain this first phenomenon reconstruction.skills/mumax3/examples/standard_problem4/README.md3.4 KB02d02d5266b2upstream ↗
# Standard Problem 4: reversal and numerical comparison This case implements **field 1** of [NIST muMAG Standard Problem 4](https://www.ctcms.nist.gov/~rdm/std4/spec4.html): a 500 x 125 x 3 nm Permalloy rectangle, `Msat=800 kA/m`, `Aex=13 pJ/m`, no crystalline anisotropy, damping 0.02, and applied flux density `(-24.6, 4.3, 0) mT`. It uses the compact S-state preparation in the [official MuMax3 example](https://mumax.github.io/examples.html): zero-field relaxation from `Uniform(1,0.1,0)`. Inspect `m_initial.ovf` to confirm the S-state; this is not a reproduction of the full saturation-and-ramp preparation suggested by NIST. From this folder, with a fresh output name: ```text mumax3 -http= -o sp4.out script.mx3 python ../../scripts/analyze_tutorial.py sp4 sp4.out ``` ## Output contract and comparison The self-contained input uses a 128 x 32 x 1 mesh and the engine default `GammaLL` (record the engine version when comparing trajectories). Fixed-step RK4 uses ten 0.1 ps integration steps per output sample. It records normalized average `mx,my,mz` every 1 ps from zero to 1 ns (1001 rows), applied field and energy in `table.txt`. It saves `m_initial.ovf`, `m_final.ovf`, and `m_crossing.ovf` at the first sampled `mx <= 0`, at most one sample after the true first crossing. Inspect the crossing field map to assess the reversal mechanism; a table alone cannot do this. The analysis emits `analysis/curve.csv` (`t_s,mx,my,mz`) and `summary.json` with an interpolated first-crossing time, sampled snapshot time and table hash. It fails on incomplete/irregular time coverage, non-finite data, missing reversal or snapshot. **Passing these checks establishes output/reversal behavior only**, not agreement with SP4 reference solutions or equilibrium at the final time. For quantitative comparison, obtain a documented field-1 solution from the [NIST solution collection](https://www.ctcms.nist.gov/~rdm/std4/results.html), convert its normalized components and time in seconds to `t_s,mx,my,mz` CSV, and preserve its source, mesh and preparation details. Then: ```text python ../../scripts/analyze_tutorial.py sp4 sp4.out --reference-csv reference.csv --tolerance 0.03 ``` The tool linearly interpolates a reference covering the whole interval and checks maximum absolute component error. `0.03` is an explicit tutorial comparison threshold, not an official NIST tolerance. It records the reference hash. Without that input, the summary explicitly says `reference_comparison: not_run`. A synthetic curve used in unit tests is not a benchmark reference. ## Modify and verify - For mesh convergence, change `nx,ny` to `256,64` at fixed physical dimensions, and consider thickness resolution separately; compare both trajectories and crossing maps. A refinement that changes the reversal mechanism needs investigation even if average curves look close. Do not label the default mesh converged without this comparison. - For integration convergence, halve `FixDt` and double the `Steps(10)` count per sample; `MaxErr` does not control a fixed timestep. For output-time resolution, halve `samplePeriod` while doubling `nSamples` to keep the observation window. Extend the window if equilibrium has not been reached. - Field 2 is `(-35.5,-6.3,0) mT`; use a new independent run from the same prepared S-state, never the field-1 final state. Compare against a field-2 reference. Changing material or geometry creates a different problem and must not retain the SP4 benchmark label.skills/mumax3/scripts/analyze_edge_canting.py6.1 KB7fea1a884eb2upstream ↗
#!/usr/bin/env python3 """Extract and plot the bundled paper example's 1D OVF profiles. Uses only the standard library. Reports observables, not a reproduction score. """ from __future__ import annotations import argparse import csv import math from pathlib import Path from analyze_tutorial import read_table, require def read_profile(path: Path) -> list[dict[str, float]]: """Read one rectangular OVF2 text vector field with ny=nz=1.""" header, vectors = {}, [] in_data = False completed = False for line in path.read_text(encoding="utf-8-sig").splitlines(): stripped = line.strip() if stripped.lower() == "# begin: data text": in_data = True elif stripped.lower() == "# end: data text": in_data = False completed = True elif in_data and stripped and not stripped.startswith("#"): values = [float(v) for v in stripped.split()] require(len(values) == 3 and all(math.isfinite(v) for v in values), "invalid OVF vector") vectors.append(values) elif stripped.startswith("#") and ":" in stripped: key, value = stripped[1:].split(":", 1) header[key.strip().lower()] = value.strip() require(completed, "expected an OVF text data block; use OutputFormat = OVF2_TEXT") nx = int(header["xnodes"]) require(nx >= 3 and int(header["ynodes"]) == int(header["znodes"]) == 1, "this example reader expects a 1D x profile (ny=nz=1)") require(int(header["valuedim"]) == 3 and len(vectors) == nx, "incomplete OVF vector field") base, step = float(header["xbase"]), float(header["xstepsize"]) require(math.isfinite(base) and math.isfinite(step) and step > 0, "invalid OVF coordinates") return [{"x_nm": (base+i*step)*1e9, "mx": v[0], "my": v[1], "mz": v[2]} for i, v in enumerate(vectors)] def extract(output: Path) -> tuple[list[dict], list[dict]]: profiles, summaries, seen = [], [], set() for row in read_table(output/"table.txt", min_rows=1): index = int(row["case_index"]) require(index == row["case_index"] and index >= 0 and index not in seen, "invalid/duplicate case index") seen.add(index) curve = read_profile(output/f"m_case_{index}.ovf") d, a, k = row["D_paper_J_m2"], row["A_J_m"], row["K_J_m3"] require(a > 0 and k > 0, "the edge-canting model needs positive A and K_eff") profiles.extend({"case_index": index, "D_paper_mJ_m2": d*1e3, **point} for point in curve) middle = curve[(len(curve)-1)//2:len(curve)//2+1] summaries.append({"case_index": index, "D_paper_mJ_m2": d*1e3, "left_mx": curve[0]["mx"], "right_mx": curve[-1]["mx"], "center_mx": sum(r["mx"] for r in middle)/len(middle), "center_mz": sum(r["mz"] for r in middle)/len(middle), "edge_scale": abs(d)/(2*math.sqrt(a*k)), "delta_nm": math.sqrt(a/k)*1e9}) return profiles, summaries def plot_svg(profiles: list[dict], summaries: list[dict]) -> str: """A dependency-free plot of the simulated cell-center profiles.""" left, right = min(r["x_nm"] for r in profiles), max(r["x_nm"] for r in profiles) colors = ("#555555", "#0072b2", "#d55e00", "#009e73") svg = ['<svg xmlns="http://www.w3.org/2000/svg" width="900" height="470" viewBox="0 0 900 470">', '<rect width="900" height="470" fill="white"/>', '<g font-family="sans-serif" font-size="14" fill="#222">', '<text x="60" y="25" font-size="18">DMI edge canting — simulated cell-center profiles</text>'] for panel, component in enumerate(("mx", "mz")): x0, y0, width, height = 60+430*panel, 70, 360, 300 svg.append(f'<text x="{x0}" y="55">{component}</text>') for tick in (-1, -.5, 0, .5, 1): y = y0+(1-tick)*height/2 svg.append(f'<path d="M{x0},{y}h{width}" stroke="#ddd"/>') svg.append(f'<text x="{x0-35}" y="{y+5}">{tick:g}</text>') for fraction in (0, .5, 1): x = x0+fraction*width svg.append(f'<text x="{x-12}" y="395">{left+(right-left)*fraction:.1f}</text>') svg.append(f'<text x="{x0+140}" y="420">x (nm)</text>') for number, summary in enumerate(summaries): curve = [r for r in profiles if r["case_index"] == summary["case_index"]] points = " ".join(f'{x0+(r["x_nm"]-left)/(right-left)*width:.2f},{y0+(1-r[component])*height/2:.2f}' for r in curve) svg.append(f'<polyline points="{points}" fill="none" stroke="{colors[number%len(colors)]}" stroke-width="2"/>') for number, summary in enumerate(summaries): x = 60+210*number svg.append(f'<text x="{x}" y="452" fill="{colors[number%len(colors)]}">D = {summary["D_paper_mJ_m2"]:g} mJ/m²</text>') return "\n".join(svg+["</g></svg>"]) def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("output_dir", type=Path) args = parser.parse_args() try: profiles, summaries = extract(args.output_dir) destination = args.output_dir/"analysis" destination.mkdir(exist_ok=True) with (destination/"profiles.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=list(profiles[0])) writer.writeheader() writer.writerows(profiles) (destination/"profiles.svg").write_text(plot_svg(profiles, summaries), encoding="utf-8") print("D_paper(mJ/m2) left_mx right_mx center_mz continuum_edge_scale") for row in summaries: print(f'{row["D_paper_mJ_m2"]:13g} {row["left_mx"]:8.5f} {row["right_mx"]:8.5f} {row["center_mz"]:9.6f} {row["edge_scale"]:.5f}') print(f'Spatial scale sqrt(A/K_eff): {summaries[0]["delta_nm"]:.3f} nm') print(f"Wrote {destination/'profiles.csv'} and profiles.svg") print("Compare the trend and shape; cell centers are inside the continuum boundary.") except (OSError, ValueError, KeyError) as exc: parser.exit(1, f"Cannot analyze edge profile: {exc}\n") return 0 if __name__ == "__main__": raise SystemExit(main())skills/mumax3/scripts/analyze_tutorial.py11 KB1333918b7f80upstream ↗
#!/usr/bin/env python3 """Analyze the three bundled tutorials using only the Python standard library. Checks apply to the documented tutorial models, not arbitrary simulations. No simulation is launched. Failed input/output contracts return a nonzero status. """ from __future__ import annotations import argparse import bisect import csv import hashlib import json import math from pathlib import Path def require(condition: bool, message: str) -> None: if not condition: raise ValueError(message) def read_table(path: Path, *, min_rows: int = 3) -> list[dict[str, float]]: lines = path.read_text(encoding="utf-8-sig").splitlines() require(bool(lines) and lines[0].startswith("#"), "missing MuMax table header") names = [part.strip().split(" (")[0] for part in lines[0].lstrip("# ").split("\t")] require(len(set(names)) == len(names), "duplicate table column names") rows = [] for number, line in enumerate(lines[1:], 2): if not line.strip() or line.startswith("#"): continue values = [float(v) for v in line.split()] require(len(values) == len(names), f"ragged table row {number}") require(all(math.isfinite(v) for v in values), f"non-finite table row {number}") rows.append(dict(zip(names, values))) require(len(rows) >= min_rows, f"need at least {min_rows} table rows") for row in rows: require(all(k in row for k in ("t", "mx", "my", "mz")), "missing time/magnetization columns") require(sum(row[k]**2 for k in ("mx", "my", "mz")) <= 1.01**2, "average normalized magnetization exceeds one") return rows def constant(rows: list[dict[str, float]], key: str) -> float: require(all(key in row for row in rows), f"missing column {key}") value = rows[0][key] require(all(math.isclose(row[key], value, rel_tol=1e-7, abs_tol=1e-30) for row in rows), f"{key} must be constant") return value def time_contract(rows: list[dict[str, float]], start: float) -> tuple[float, float]: period, duration = constant(rows, "sample_s"), constant(rows, "observe_s") require(period > 0 and duration > 0, "sample period and observation duration must be positive") require(abs(rows[0]["t"]-start) < period*1e-3, "missing initial time sample") require(abs(rows[-1]["t"]-start-duration) < period*1e-3, "incomplete observation window") require(all(abs(b["t"]-a["t"]-period) < period*1e-3 for a, b in zip(rows, rows[1:])), "time samples are duplicated, missing or irregular") return period, duration def crossing(rows: list[dict[str, float]], xkey: str) -> float: for left, right in zip(rows, rows[1:]): if left["mx"] * right["mx"] <= 0 and left["mx"] != right["mx"]: fraction = -left["mx"] / (right["mx"]-left["mx"]) return left[xkey] + fraction*(right[xkey]-left[xkey]) raise ValueError("no mx zero crossing in recorded branch/window") def hysteresis(rows: list[dict[str, float]]) -> tuple[dict, list[dict]]: limit = constant(rows, "field_limit_T") step = constant(rows, "field_step_T") hk = constant(rows, "anisotropy_field_T") transverse = abs(constant(rows, "transverse_T")) require(limit > hk > transverse > 0 and step > 0, "invalid near-easy-axis field range") intervals = round(2*limit/step) require(math.isclose(intervals*step, 2*limit), "field range is not an integer number of steps") require(len(rows) == 2*intervals+1, "incomplete hysteresis branch count") down, up = rows[:intervals+1], rows[intervals+1:] expected = [limit-i*step for i in range(intervals+1)] + [-limit+i*step for i in range(1, intervals+1)] for row, field in zip(rows, expected): require(abs(row["B_extx"]-field) < step*1e-4, "field order/step mismatch") require(all(row["branch"] == -1 for row in down) and all(row["branch"] == 1 for row in up), "branch labels do not match the continuation protocol") require(down[0]["mx"] > .9 and down[-1]["mx"] < -.9 and up[-1]["mx"] > .9, "saturation/reversal missing") negative, positive = crossing(down, "B_extx"), crossing(up, "B_extx") predicted = hk*(1-(transverse/hk)**(2/3))**1.5 require(negative < 0 < positive, "loop has the wrong branch switching signs") require(max(abs(abs(negative)-predicted), abs(positive-predicted)) <= 2*step, "switching field disagrees with the macrospin astroid by more than two field steps") curve = [{"branch": r["branch"], "B_x_T": r["B_extx"], "mx": r["mx"]} for r in rows] return {"descending_crossing_T": negative, "ascending_crossing_T": positive, "analytic_switching_magnitude_T": predicted, "tolerance_T": 2*step, "scope": "near-easy-axis, zero-temperature macrospin continuation"}, curve def sp4(rows: list[dict[str, float]]) -> tuple[dict, list[dict]]: period, duration = time_contract(rows, 0) require(rows[0]["mx"] > 0 and rows[-1]["mx"] < 0, "SP4 reversal not observed") time = crossing(rows, "t") recorded = rows[-1]["crossing_time_s"] require(time <= recorded <= time+period*1.01, "crossing snapshot time is inconsistent") curve = [{"t_s": r["t"], "mx": r["mx"], "my": r["my"], "mz": r["mz"]} for r in rows] return {"first_mx_zero_s": time, "snapshot_time_s": recorded, "duration_s": duration, "reference_comparison": "not_run", "scope": "SP4 output/reversal checks; not benchmark acceptance"}, curve def fmr(rows: list[dict[str, float]]) -> tuple[dict, list[dict]]: period, duration = time_contract(rows, constant(rows, "pulse_s")) bias, damping = constant(rows, "bias_T"), constant(rows, "damping") gamma = constant(rows, "gamma_rad_s_T") require(bias > 0 and gamma > 0 and 0 <= damping < .1, "invalid small-damping macrospin parameters") expected = gamma*bias/(2*math.pi*(1+damping*damping)) require(expected*duration >= 10 and expected*period <= .1, "need ten cycles and ten samples per expected period") require(max(math.hypot(r["mx"], r["my"]) for r in rows) > 1e-6, "no transverse FMR signal") count = len(rows) require(count <= 10000, "tutorial DFT is limited to 10000 samples; use an FFT for larger data") means = [sum(r[k] for r in rows)/count for k in ("mx", "my")] samples = [((r["mx"]-means[0])*w, (r["my"]-means[1])*w) for i, r in enumerate(rows) for w in [.5-.5*math.cos(2*math.pi*i/(count-1))]] spectrum = [] for index in range(1, count//2+1): angle = -2*math.pi*index/count phase_step = complex(math.cos(angle), math.sin(angle)) phase, sx, sy = 1+0j, 0j, 0j for x, y in samples: sx += x*phase sy += y*phase phase *= phase_step spectrum.append({"frequency_Hz": index/(count*period), "power_arb": (abs(sx)**2+abs(sy)**2)/count**2}) peak = max(spectrum, key=lambda r:r["power_arb"])["frequency_Hz"] tolerance = max(2/duration, .02*expected) require(abs(peak-expected) <= tolerance, "FMR peak outside finite-window analytic tolerance") return {"peak_Hz": peak, "analytic_Hz": expected, "bin_width_Hz": 1/(count*period), "tolerance_Hz": tolerance, "scope": "isotropic macrospin frequency only; not a thin-film dispersion test"}, spectrum def compare_reference(curve: list[dict], path: Path, tolerance: float) -> dict: with path.open(encoding="utf-8-sig", newline="") as handle: reference = [{k:float(r[k]) for k in ("t_s", "mx", "my", "mz")} for r in csv.DictReader(handle)] require(len(reference) >= 2 and all(math.isfinite(v) for r in reference for v in r.values()), "reference CSV needs finite t_s,mx,my,mz samples") times = [r["t_s"] for r in reference] require(all(b > a for a,b in zip(times,times[1:])), "reference times must increase") require(times[0] <= curve[0]["t_s"] and times[-1] >= curve[-1]["t_s"], "reference does not cover the full run") error = 0.0 for row in curve: index = max(1, min(bisect.bisect_left(times,row["t_s"]),len(times)-1)) a,b = reference[index-1],reference[index] weight = (row["t_s"]-a["t_s"])/(b["t_s"]-a["t_s"]) for key in ("mx", "my", "mz"): error = max(error,abs(row[key]-(a[key]+weight*(b[key]-a[key])))) require(error <= tolerance, f"reference max component error {error:.6g} exceeds {tolerance:g}") return {"reference_comparison": "passed_supplied_curve_tolerance", "max_component_error": error, "reference_sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "reference_tolerance": tolerance} def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("case", choices=("hysteresis", "sp4", "fmr")) parser.add_argument("output_dir", type=Path) parser.add_argument("--reference-csv", type=Path, help="SP4 only: independently sourced t_s,mx,my,mz curve") parser.add_argument("--tolerance", type=float, default=.03, help="SP4 max absolute normalized component error") args = parser.parse_args() try: require(args.tolerance > 0 and math.isfinite(args.tolerance), "tolerance must be positive and finite") require(args.reference_csv is None or args.case == "sp4", "reference CSV is for SP4 only") for name in ("m_initial.ovf", "m_final.ovf") + (("m_crossing.ovf",) if args.case == "sp4" else ()): with (args.output_dir/name).open("rb") as handle: require(handle.read(64).startswith(b"# OOMMF"), f"missing/invalid OVF header: {name}") table = args.output_dir/"table.txt" metrics, product = {"hysteresis":hysteresis, "sp4":sp4, "fmr":fmr}[args.case](read_table(table)) if args.reference_csv: metrics.update(compare_reference(product,args.reference_csv,args.tolerance)) metrics["table_sha256"] = hashlib.sha256(table.read_bytes()).hexdigest() destination = args.output_dir/"analysis" destination.mkdir(exist_ok=True) name = "spectrum.csv" if args.case == "fmr" else "curve.csv" with (destination/name).open("w",encoding="utf-8",newline="") as handle: writer = csv.DictWriter(handle,fieldnames=list(product[0])) writer.writeheader() writer.writerows(product) (destination/"summary.json").write_text(json.dumps(metrics,indent=2)+"\n",encoding="utf-8") print(json.dumps(metrics,indent=2)) except (OSError, ValueError, KeyError) as exc: parser.exit(1, f"Tutorial check failed: {exc}\n") return 0 if __name__ == "__main__": raise SystemExit(main())skills/mumax3/scripts/check_mx3_static.py7.8 KBa28f4e6841ccupstream ↗
#!/usr/bin/env python3 """Conservative static warnings for mumax3 .mx3 scripts. This checker catches common Go/mumax3 boundary mistakes. It does not parse mumax3 fully and does not prove that a script is semantically correct. """ from __future__ import annotations import argparse import re import sys from pathlib import Path FORBIDDEN_STATEMENTS = { "package": "mumax3 scripts are not Go packages", "import": "Go imports are not available in .mx3 scripts", "func": "custom Go function declarations are not supported", "type": "Go type declarations are not supported", "struct": "Go structs are not supported", "interface": "Go interfaces are not supported", "go": "goroutines are not supported", "chan": "channels are not supported", "select": "select statements are not supported", "switch": "switch statements are not supported", "range": "range loops are not supported", "return": "return statements are not supported", "break": "break statements are not supported", "continue": "continue statements are not supported", "defer": "defer is not supported", "goto": "goto is not supported", } GO_PACKAGE_SELECTORS = [ "fmt.", "math.", "os.", "strings.", "strconv.", "filepath.", "regexp.", "json.", "ioutil.", ] ASSIGN_RE = re.compile(r"(?<![<>=!:+*/%^-])(:=|=)(?!=)") SHORT_DECL_RE = re.compile(r"^\s*([A-Za-z_][A-Za-z0-9_]*)\s*:=") FOR_RE = re.compile(r"^\s*for\b") SET_SOLVER_EULER_RE = re.compile(r"\bsetsolver\s*\(\s*1\s*\)", re.IGNORECASE) FIXDT_ASSIGN_RE = re.compile(r"\bfixdt\s*=", re.IGNORECASE) EXT_API_RE = re.compile(r"\bext_[A-Za-z0-9_]*", re.IGNORECASE) TEMPLATE_PLACEHOLDER_RE = re.compile(r"\{\{\s*[A-Za-z_][A-Za-z0-9_]*\s*\}\}") PROTECTED_BUILTIN_IDENTIFIERS = { "aex", "alpha", "b_ext", "e_total", "false", "fixdt", "gamma", "gammall", "inf", "m", "maxangle", "msat", "mu0", "outputformat", "pi", "tableadd", "tableaddvar", "tablesave", "t", "true", } def strip_strings_and_comments(line: str, in_block_comment: bool) -> tuple[str, bool]: out: list[str] = [] i = 0 in_string = False quote = "" while i < len(line): ch = line[i] nxt = line[i + 1] if i + 1 < len(line) else "" if in_block_comment: if ch == "*" and nxt == "/": in_block_comment = False i += 2 else: i += 1 continue if in_string: if ch == "\\": i += 2 continue if ch == quote: in_string = False quote = "" out.append(" ") i += 1 continue if ch in ('"', "`"): in_string = True quote = ch out.append(" ") i += 1 continue if ch == "/" and nxt == "/": break if ch == "/" and nxt == "*": in_block_comment = True i += 2 continue out.append(ch) i += 1 return "".join(out), in_block_comment def warn(warnings: list[str], path: Path, line_no: int | None, message: str) -> None: loc = f"{path}:{line_no}" if line_no is not None else str(path) warnings.append(f"{loc}: warning: {message}") def check_text(path: Path, text: str) -> list[str]: warnings: list[str] = [] clean_lines: list[str] = [] in_block = False block_stack: list[bool] = [] euler_solver_lines: list[int] = [] template_mode = path.name.endswith(".mx3.template") or "{{" in text if template_mode: text = TEMPLATE_PLACEHOLDER_RE.sub("0", text) for line_no, raw in enumerate(text.splitlines(), start=1): clean, in_block = strip_strings_and_comments(raw, in_block) clean_lines.append(clean) stripped = clean.strip().lstrip("") if not stripped: continue leading_closes = len(stripped) - len(stripped.lstrip("}")) for _ in range(min(leading_closes, len(block_stack))): block_stack.pop() in_for_block = any(block_stack) first = re.match(r"^([A-Za-z_][A-Za-z0-9_]*)\b", stripped) if first and first.group(1) in FORBIDDEN_STATEMENTS: keyword = first.group(1) warn(warnings, path, line_no, f"`{keyword}`: {FORBIDDEN_STATEMENTS[keyword]}") clean_lower = clean.lower() for selector in GO_PACKAGE_SELECTORS: if selector in clean_lower: warn(warnings, path, line_no, f"`{selector}` looks like Go standard library usage; use mumax3 built-ins or Python orchestration") if "^" in clean: warn(warnings, path, line_no, "`^` is not power in mumax3 scripts; use `pow(x, y)`") short_decl = SHORT_DECL_RE.match(clean) if short_decl and short_decl.group(1).lower() in PROTECTED_BUILTIN_IDENTIFIERS: name = short_decl.group(1) warn(warnings, path, line_no, f"`{name}` is a mumax3 built-in identifier; do not redeclare it with `:=`") match = ASSIGN_RE.search(clean) if match: lhs = clean[: match.start()] if "," in lhs: warn(warnings, path, line_no, "multiple assignment is suspicious in mumax3 scripts") if "tableaddvar" in clean.lower() and in_for_block: warn(warnings, path, line_no, "`TableAddVar` adds table columns; avoid calling it inside loops, use `TableSave` for rows") if SET_SOLVER_EULER_RE.search(clean): euler_solver_lines.append(line_no) ext_match = EXT_API_RE.search(clean) if ext_match: warn(warnings, path, line_no, f"`{ext_match.group(0)}` is an extension API; confirm version-specific behavior against official docs and the local mumax3 build") is_for_open = bool(FOR_RE.match(stripped)) for ch in stripped[leading_closes:]: if ch == "{": block_stack.append(is_for_open) is_for_open = False elif ch == "}" and block_stack: block_stack.pop() clean_text = "\n".join(clean_lines) clean_text_lower = clean_text.lower() has_mesh = ("setgridsize" in clean_text_lower and "setcellsize" in clean_text_lower) or "setmesh" in clean_text_lower has_output = any(token in clean_text_lower for token in ("save(", "saveas(", "autosave(", "tableautosave(", "tablesave(", "snapshot(")) has_fixdt = bool(FIXDT_ASSIGN_RE.search(clean_text)) if not has_mesh: warn(warnings, path, None, "missing obvious mesh setup (`SetGridSize` + `SetCellSize`, or `SetMesh`)") if not has_output: warn(warnings, path, None, "missing obvious output pattern (`Save`, `SaveAs`, `AutoSave`, `TableAutoSave`, or `TableSave`)") if euler_solver_lines and not has_fixdt: for line_no in euler_solver_lines: warn(warnings, path, line_no, "`SetSolver(1)` selects Euler and requires an explicit `FixDt = ...`") return warnings def main(argv: list[str]) -> int: parser = argparse.ArgumentParser(description="Warn about common mumax3 script anti-patterns.") parser.add_argument("paths", nargs="+", help=".mx3 files to check") args = parser.parse_args(argv) all_warnings: list[str] = [] exit_code = 0 for name in args.paths: path = Path(name) try: text = path.read_text(encoding="utf-8") except OSError as exc: print(f"{path}: error: {exc}", file=sys.stderr) exit_code = 2 continue all_warnings.extend(check_text(path, text)) for item in all_warnings: print(item) if not all_warnings and exit_code == 0: print("No static warnings.") return exit_code if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))skills/mumax3/scripts/collect_case_status.py10 KBb4a7a5c75994upstream ↗
#!/usr/bin/env python3 """Collect conservative status information from mumax3 case folders. The script reports files, logs, and metadata that are present on disk. It does not claim that a simulation is physically correct or numerically converged. """ from __future__ import annotations import argparse import csv import json import sys from pathlib import Path from typing import Any FIELDNAMES = [ "case_id", "case_dir", "result_dir", "reported_status", "derived_status", "params_json", "manifest_json", "config_signature", "input_sha256", "dynamic_signature", "analysis_status", "manual_review_status", "provenance_state", "mx3_count", "out_dir_count", "ovf_count", "table_count", "stdout_log_count", "stderr_log_count", "stderr_nonempty", "error_message", ] def load_params(path: Path) -> tuple[dict[str, Any], str]: try: data = json.loads(path.read_text(encoding="utf-8")) except FileNotFoundError: return {}, "" except json.JSONDecodeError as exc: return {}, f"invalid params.json: {exc}" except UnicodeError as exc: return {}, f"cannot decode params.json as UTF-8: {exc}" except OSError as exc: return {}, f"cannot read params.json: {exc}" if not isinstance(data, dict): return {}, "params.json is not a JSON object" return data, "" def load_optional_json(path: Path) -> tuple[dict[str, Any], str]: try: data = json.loads(path.read_text(encoding="utf-8")) except FileNotFoundError: return {}, "" except json.JSONDecodeError as exc: return {}, f"invalid {path.name}: {exc}" except UnicodeError as exc: return {}, f"cannot decode {path.name} as UTF-8: {exc}" except OSError as exc: return {}, f"cannot read {path.name}: {exc}" if not isinstance(data, dict): return {}, f"{path.name} is not a JSON object" return data, "" def first_value(data: dict[str, Any], keys: tuple[str, ...]) -> str: for key in keys: value = data.get(key) if value not in (None, ""): return str(value) return "" def find_manifest(case_dir: Path, root: Path) -> Path | None: for path in ( case_dir / "manifest.json", case_dir / "case_manifest.json", root / "manifest.json", root / "case_manifest.json", ): if path.exists(): return path return None def find_case_dirs(root: Path, recursive: bool) -> list[Path]: if (root / "params.json").exists() or list(root.glob("*.mx3")): return [root] candidates = root.rglob("*") if recursive else root.iterdir() case_dirs: list[Path] = [] for path in candidates: if not path.is_dir(): continue if (path / "params.json").exists() or list(path.glob("*.mx3")): case_dirs.append(path) return sorted(set(case_dirs)) def count_nonempty(paths: list[Path]) -> int: count = 0 for path in paths: try: if path.stat().st_size > 0: count += 1 except OSError: continue return count def derive_status(row: dict[str, Any]) -> str: if row["error_message"] or row["stderr_nonempty"]: return "needs_review" if row["provenance_state"] == "stale": return "stale" if row["manual_review_status"] not in {"", "review_pending"}: return "review_recorded" if row["analysis_status"] == "analysis_fresh": return "analysis_present" if row["ovf_count"] or row["table_count"]: return "outputs_present" if row["out_dir_count"]: return "output_dirs_present" if row["mx3_count"]: return "prepared" return "unknown" def display_path(path: Path, root: Path) -> str: try: return str(path.resolve().relative_to(root.resolve().parent)) except ValueError: return str(path) def summarize_case(case_dir: Path, root: Path, result_root: Path | None = None) -> dict[str, Any]: params_path = case_dir / "params.json" params, error_message = load_params(params_path) try: relative_case = case_dir.resolve().relative_to(root.resolve()) except ValueError: relative_case = Path(case_dir.name) result_dir = result_root / relative_case if result_root else case_dir manifest_path = find_manifest(case_dir, root) manifest, manifest_error = load_optional_json(manifest_path) if manifest_path else ({}, "") run_record, run_record_error = load_optional_json(case_dir / "run_record.json") analysis_record, analysis_error = load_optional_json(result_dir / "analysis_record.json") manual_review, manual_review_error = load_optional_json(result_dir / "manual_review.json") optional_errors = [ message for message in (manifest_error, run_record_error, analysis_error, manual_review_error) if message ] config_signature = first_value( params, ("configuration_signature", "config_signature", "case_signature"), ) input_sha256 = first_value( params, ("checkpoint_sha256", "static_input_sha256", "input_sha256"), ) dynamic_signature = first_value(params, ("dynamic_signature",)) analysis_signature = first_value(analysis_record, ("analysis_signature", "signature")) analysis_dynamic = first_value(analysis_record, ("dynamic_signature",)) review_dynamic = first_value(manual_review, ("dynamic_signature",)) review_analysis = first_value(manual_review, ("analysis_signature",)) stale = False if dynamic_signature and analysis_dynamic and dynamic_signature != analysis_dynamic: stale = True if dynamic_signature and review_dynamic and dynamic_signature != review_dynamic: stale = True if analysis_signature and review_analysis and analysis_signature != review_analysis: stale = True if stale: provenance_state = "stale" elif config_signature or input_sha256 or dynamic_signature or manifest: provenance_state = "recorded" elif list(case_dir.glob("*.out/*.ovf")) or list(case_dir.glob("*.out/table.txt")): provenance_state = "unverified_outputs" else: provenance_state = "unrecorded" analysis_evidence_matches = bool(dynamic_signature and analysis_dynamic and dynamic_signature == analysis_dynamic) if analysis_record: if stale: analysis_status = "analysis_stale" elif analysis_evidence_matches: analysis_status = "analysis_fresh" else: analysis_status = "analysis_unverified" else: analysis_status = "" manual_review_status = first_value(manual_review, ("status", "classification")) or ( "review_pending" if analysis_record else "" ) out_dirs = [path for path in case_dir.glob("*.out") if path.is_dir()] stdout_logs = list(case_dir.glob("logs/*stdout*.txt")) stderr_logs = list(case_dir.glob("logs/*stderr*.txt")) row: dict[str, Any] = { "case_id": str(params.get("case_id") or case_dir.name), "case_dir": display_path(case_dir, root), "result_dir": str(result_dir), "reported_status": first_value(run_record, ("status",)) or str(params.get("status", "")), "derived_status": "", "params_json": "yes" if params_path.exists() else "no", "manifest_json": str(manifest_path) if manifest_path else "", "config_signature": config_signature, "input_sha256": input_sha256, "dynamic_signature": dynamic_signature, "analysis_status": analysis_status, "manual_review_status": manual_review_status, "provenance_state": provenance_state, "mx3_count": len(list(case_dir.glob("*.mx3"))), "out_dir_count": len(out_dirs), "ovf_count": len(list(case_dir.glob("*.out/*.ovf"))), "table_count": len(list(case_dir.glob("*.out/table.txt"))), "stdout_log_count": len(stdout_logs), "stderr_log_count": len(stderr_logs), "stderr_nonempty": count_nonempty(stderr_logs), "error_message": "; ".join( message for message in (error_message, str(params.get("error_message", "")), *optional_errors) if message ), } row["derived_status"] = derive_status(row) return row def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=FIELDNAMES) writer.writeheader() writer.writerows(rows) def write_json(path: Path, rows: list[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8") def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Collect conservative mumax3 case status rows.") parser.add_argument( "root", type=Path, help="case directory or directory containing case directories (a case has params.json or a top-level .mx3 file)", ) parser.add_argument("--recursive", action="store_true", help="scan nested directories for cases") parser.add_argument("--result-root", type=Path, help="parallel result root containing analysis and manual-review records") parser.add_argument("--csv", type=Path, help="write a CSV summary") parser.add_argument("--json", type=Path, help="write a JSON summary") return parser def main(argv: list[str]) -> int: args = build_parser().parse_args(argv) root = args.root if not root.exists(): print(f"{root}: does not exist", file=sys.stderr) return 2 if not root.is_dir(): print(f"{root}: expected a directory", file=sys.stderr) return 2 case_dirs = find_case_dirs(root, args.recursive) if not case_dirs: print( "No case directories matched; expected params.json or a top-level .mx3 file. " "An .out directory alone is not a case.", file=sys.stderr, ) rows = [summarize_case(case_dir, root, args.result_root) for case_dir in case_dirs] if args.csv: write_csv(args.csv, rows) print(f"Wrote {args.csv}") if args.json: write_json(args.json, rows) print(f"Wrote {args.json}") if not args.csv and not args.json: writer = csv.DictWriter(sys.stdout, fieldnames=FIELDNAMES) writer.writeheader() writer.writerows(rows) return 0 if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))skills/mumax3/scripts/render_template.py4.2 KB22b4ece116a2upstream ↗
#!/usr/bin/env python3 """Render simple {{placeholder}} mumax3 templates. This helper performs deterministic text substitution only. It does not validate mumax3 physics or prove that the rendered script is semantically correct. """ from __future__ import annotations import argparse import json import re import sys from pathlib import Path from typing import Any PLACEHOLDER_RE = re.compile(r"{{\s*([A-Za-z_][A-Za-z0-9_]*)\s*}}") def load_json_mapping(path: Path) -> dict[str, Any]: try: data = json.loads(path.read_text(encoding="utf-8")) except OSError as exc: raise SystemExit(f"{path}: error: {exc}") from exc except json.JSONDecodeError as exc: raise SystemExit(f"{path}: invalid JSON: {exc}") from exc if not isinstance(data, dict): raise SystemExit(f"{path}: expected a JSON object") return data def parse_set_value(item: str) -> tuple[str, str]: if "=" not in item: raise argparse.ArgumentTypeError("expected KEY=VALUE") key, value = item.split("=", 1) if not PLACEHOLDER_RE.fullmatch("{{" + key + "}}"): raise argparse.ArgumentTypeError(f"invalid placeholder name: {key!r}") return key, value def value_to_text(value: Any, key: str) -> str: if isinstance(value, bool): return "true" if value else "false" if isinstance(value, (int, float, str)): return str(value) raise SystemExit(f"{key}: unsupported value type {type(value).__name__}; use a string, number, or boolean") def render(template: str, values: dict[str, Any]) -> tuple[str, list[str]]: missing: list[str] = [] def replace(match: re.Match[str]) -> str: key = match.group(1) if key not in values: missing.append(key) return match.group(0) return value_to_text(values[key], key) return PLACEHOLDER_RE.sub(replace, template), sorted(set(missing)) def find_placeholders(template: str) -> list[str]: return sorted(set(PLACEHOLDER_RE.findall(template))) def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Render a mumax3 {{placeholder}} template.") parser.add_argument("template", type=Path, help="input .mx3.template file") parser.add_argument("-p", "--params", type=Path, help="JSON object with placeholder values") parser.add_argument("-s", "--set", action="append", default=[], type=parse_set_value, metavar="KEY=VALUE", help="override or add one placeholder value") parser.add_argument("-o", "--output", type=Path, help="output .mx3 path; stdout is used when omitted") parser.add_argument("--list", action="store_true", help="list placeholders and exit") parser.add_argument("--check", action="store_true", help="fail if placeholders are missing, but do not write output") parser.add_argument("--force", action="store_true", help="overwrite an existing output file") return parser def main(argv: list[str]) -> int: args = build_parser().parse_args(argv) try: template = args.template.read_text(encoding="utf-8") except OSError as exc: print(f"{args.template}: error: {exc}", file=sys.stderr) return 2 if args.list: for name in find_placeholders(template): print(name) return 0 values: dict[str, Any] = {} if args.params: values.update(load_json_mapping(args.params)) values.update(dict(args.set)) rendered, missing = render(template, values) if missing: print("missing placeholder values: " + ", ".join(missing), file=sys.stderr) return 1 if args.check: print("Template placeholders are fully resolved.") return 0 if args.output: if args.output.exists() and not args.force: print(f"{args.output}: already exists; use --force to overwrite", file=sys.stderr) return 1 args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(rendered, encoding="utf-8") print(f"Wrote {args.output}") else: print(rendered, end="") return 0 if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))skills/mumax3/scripts/sync_local_skill.py5.9 KB35d2cf6801daupstream ↗
#!/usr/bin/env python3 """Safely synchronize the maintained mumax3 skill into a local Codex install.""" from __future__ import annotations import argparse import hashlib import os import shutil import sys import uuid from datetime import datetime from pathlib import Path IGNORED_NAMES = {"__pycache__", ".pytest_cache"} IGNORED_SUFFIXES = {".pyc", ".pyo"} def default_source() -> Path: return Path(__file__).resolve().parents[1] def default_target() -> Path: codex_home = Path(os.environ.get("CODEX_HOME", Path.home() / ".codex")) return codex_home / "skills" / "mumax3" def include(path: Path) -> bool: return not any(part in IGNORED_NAMES for part in path.parts) and path.suffix not in IGNORED_SUFFIXES def file_manifest(root: Path) -> dict[str, str]: result: dict[str, str] = {} if not root.exists(): return result for path in sorted(root.rglob("*")): if not path.is_file(): continue relative = path.relative_to(root) if not include(relative): continue digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) result[relative.as_posix()] = digest.hexdigest() return result def validate_paths(source: Path, target: Path) -> None: if not (source / "SKILL.md").is_file(): raise SystemExit(f"{source}: source does not contain SKILL.md") resolved_target = target.resolve() if resolved_target.name.lower() != "mumax3" or resolved_target.parent.name.lower() != "skills": raise SystemExit(f"{target}: target must be an exact .../skills/mumax3 directory") if source.resolve() == resolved_target: raise SystemExit("source and target must be different directories") def changes(source_manifest: dict[str, str], target_manifest: dict[str, str]) -> tuple[list[str], list[str], list[str]]: added = sorted(source_manifest.keys() - target_manifest.keys()) removed = sorted(target_manifest.keys() - source_manifest.keys()) changed = sorted( name for name in source_manifest.keys() & target_manifest.keys() if source_manifest[name] != target_manifest[name] ) return added, changed, removed def print_plan(source: Path, target: Path, added: list[str], changed: list[str], removed: list[str]) -> None: print(f"Source: {source}") print(f"Target: {target}") for label, names in (("ADD", added), ("CHANGE", changed), ("REMOVE", removed)): for name in names: print(f"{label}: {name}") print(f"Summary: add={len(added)} change={len(changed)} remove={len(removed)}") def copy_source(source: Path, staging: Path) -> None: def ignore(_directory: str, names: list[str]) -> set[str]: return { name for name in names if name in IGNORED_NAMES or Path(name).suffix in IGNORED_SUFFIXES } shutil.copytree(source, staging, ignore=ignore) def apply_sync(source: Path, target: Path, backup_root: Path) -> Path | None: timestamp = datetime.now().strftime("%Y%m%d-%H%M%S") backup: Path | None = None if target.exists(): backup = backup_root / f"mumax3-{timestamp}" backup.parent.mkdir(parents=True, exist_ok=True) if backup.exists(): raise SystemExit(f"{backup}: backup path already exists") shutil.copytree(target, backup) target.parent.mkdir(parents=True, exist_ok=True) staging = target.parent / f".mumax3-sync-{uuid.uuid4().hex}" try: copy_source(source, staging) if target.exists(): shutil.rmtree(target) staging.replace(target) except BaseException: if staging.exists(): shutil.rmtree(staging) if backup and backup.exists() and not target.exists(): shutil.copytree(backup, target) raise source_manifest = file_manifest(source) target_manifest = file_manifest(target) if source_manifest != target_manifest: if backup and backup.exists(): if target.exists(): shutil.rmtree(target) shutil.copytree(backup, target) raise SystemExit("post-sync hash verification failed; restored backup") return backup def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source", type=Path, default=default_source(), help="maintained mumax3 skill source") parser.add_argument("--target", type=Path, default=default_target(), help="local .../skills/mumax3 target") parser.add_argument("--backup-root", type=Path, help="backup directory; defaults beside the target skill") mode = parser.add_mutually_exclusive_group() mode.add_argument("--dry-run", action="store_true", help="show changes without writing (default)") mode.add_argument("--apply", action="store_true", help="create a backup and apply the exact synchronization") return parser def main(argv: list[str]) -> int: args = build_parser().parse_args(argv) source = args.source.resolve() target = args.target.resolve() validate_paths(source, target) source_manifest = file_manifest(source) target_manifest = file_manifest(target) added, changed, removed = changes(source_manifest, target_manifest) print_plan(source, target, added, changed, removed) if not (added or changed or removed): print("Already synchronized.") return 0 if not args.apply: print("Dry run only. Re-run with --apply to synchronize.") return 0 backup_root = (args.backup_root or target.parent / ".mumax3-backups").resolve() backup = apply_sync(source, target, backup_root) print(f"Backup: {backup if backup else 'none (target did not exist)'}") print("Synchronization complete and hashes verified.") return 0 if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))skills/mumax3/references/anti_patterns.md4.2 KB048269fc65a9upstream ↗
# mumax3 Anti-Patterns Use this reference when reviewing scripts or when an implementation starts to look like normal Go instead of mumax3 input syntax. ## Full Go Constructs Do not generate or keep these in `.mx3` scripts: - `package` or `import`. - `func` declarations or custom Go helper functions. - `type`, structs, interfaces, methods, goroutines, channels, `select`, `defer`, `goto`, labels, or maps. - `switch`, `range`, `return`, `break`, and `continue`. - Multi-return idioms such as `x, err := ...`. mumax3 parses a Go-like subset and then interprets only supported statements and expressions. A fragment that is valid Go may still be invalid mumax3 script. ## Go Standard Library Misuse Avoid package selectors such as: - `fmt.Println(...)` - `math.Sin(...)`, `math.Pow(...)` - `os.MkdirAll(...)`, `filepath.Join(...)` - `strings.Contains(...)` - `strconv.ParseFloat(...)` Use exposed mumax3 functions directly instead: `Print`, `Sprintf`, `sin`, `pow`, `sqrt`, `Vector`, `SaveAs`, `TableAdd`, and so on. Use Python for filesystem work, CSV/JSON parsing, path joins, plotting, or batch orchestration. ## Invented API Names Do not invent convenience APIs such as: - `SetMaterial(...)` - `SetExternalField(...)` - `SetOutput(...)` - `SetDampingRegion(...)` - `RunSimulation(...)` - `CreateMask(...)` Check `api_index.md` first. If absent there, check `api_full.md` or the official API page before using a name. ## Arithmetic And Assignment Traps - Use `pow(x, y)` for powers. In Go-like syntax `^` is not exponentiation. - Prefer single assignment: `x := 1`, not `x, y := 1, 2`. - Do not redeclare mumax3 built-ins with `:=`. Names such as `mu0`/`Mu0`, `pi`, `t`, `m`, `Msat`, `B_ext`, `OutputFormat`, and solver/output quantities are already defined by mumax3. - Avoid `%` unless confirmed for the exact mumax3 version; prefer `mod(x, y)` or `remainder(x, y)` when a floating remainder is intended. - Do not store time-dependent expressions in ordinary variables unless one-time evaluation is intended. Correct dynamic field pattern: ```go B_ext.Add(mask, h0*sin(2*pi*f*t)) ``` Risky if a dynamic value was intended: ```go value := h0*sin(2*pi*f*t) B_ext.Add(mask, value) ``` ## Region And Output Traps - Regions are mutually exclusive cell labels. Later region definitions can overwrite earlier intent. - Save `regions` when debugging spatial assignments. - Do not use `.Region(...)`, `.Comp(...)`, or `Crop*` as substitutes for `DefRegion` or `SetGeom`; they select output or averages, not physical material regions. - Do not assume output files land in the working directory; mumax3 creates an output directory for a script run. - Include at least one final `Save`/`SaveAs` or an autosave/table schedule for scripts meant to produce data. - Treat `TableAdd` and `TableAddVar` as setup calls that add table columns. Do not use `TableAddVar` inside a hysteresis or parameter loop to record per-step scalar values; use `TableSave` inside the loop and compute derived columns from saved quantities during postprocessing. Risky: ```go for i:=0; i<=10; i++{ h := -0.1 + 0.02*i B_ext = Vector(h, 0, 0) Minimize() TableAddVar(h, "H", "T") TableSave() } ``` Safer: ```go TableAdd(B_ext) for i:=0; i<=10; i++{ h := -0.1 + 0.02*i B_ext = Vector(h, 0, 0) Minimize() TableSave() } ``` ## Run-Stage Traps - Do not use `Relax()` as a substitute for driven dynamics. Relaxation disables precession and does not advance simulation time. - Do not start `Minimize()` from a random or very high-energy state when `Relax()` is the robust first stage. - Do not select Euler with `SetSolver(1)` unless the script also sets an explicit `FixDt`. Risky: ```go m = RandomMag() Minimize() ``` Safer: ```go m = RandomMag() Relax() Minimize() ``` Risky: ```go SetSolver(1) Run(1e-9) ``` Safer: ```go SetSolver(1) FixDt = 1e-15 Run(1e-9) ``` ## Extension API Traps - Treat `ext_*` APIs as version-sensitive. Confirm them against the official API for the target mumax3 version and local executable before relying on them. - Do not hide an extension assumption in a generic helper name; keep the extension call visible in the script or metadata.skills/mumax3/references/api_full.md35 KBd1520aea2328upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/mumax3/references/api_index.md4.1 KBfdd2d5994d79upstream ↗
# mumax3 API Index Use this compact whitelist for normal script generation. It covers common, high-frequency identifiers only. If a needed identifier is not listed, check `api_full.md` or the official mumax3 API before using it. Source baseline: official mumax3.12 API, <https://mumax.github.io/api.html>. ## Syntax And Constants - `true`, `false` - `pi`, `inf` - `mu0`/`Mu0`, `GammaLL`, `t`, `step` - Math functions: `abs`, `ceil`, `floor`, `exp`, `log`, `log10`, `max`, `min`, `mod`, `pow`, `remainder`, `sin`, `cos`, `tan`, `sqrt`, `sinc`, `rand`, `randNorm`, `randSeed` - Formatting/printing: `Print`, `Printf`, `Sprintf` These names are built into mumax3. Use them directly; do not redeclare them with `:=`. Identifier lookup is case-insensitive in mumax3 scripts, so `mu0`, `Mu0`, and `MU0` refer to the same built-in constant. For less common names, search `api_full.md` before choosing a local variable name. ## Mesh And Geometry - `SetGridSize(nx, ny, nz)` - `SetCellSize(dx, dy, dz)` - `SetMesh(nx, ny, nz, dx, dy, dz, pbcx, pbcy, pbcz)` - `SetPBC(nx, ny, nz)` - `SetGeom(shape)` - `EdgeSmooth` Common shapes: - `Rect(x, y)`, `Square(size)` - `Circle(diameter)`, `Ellipse(x, y)` - `Cuboid(x, y, z)`, `Cylinder(diameter, height)`, `Ellipsoid(x, y, z)` - `XRange(x1, x2)`, `YRange(y1, y2)`, `ZRange(z1, z2)`, `Layer(k)`, `Layers(k1, k2)` - `Universe()`, `ImageShape(path)`, `Cell(i, j, k)` Common shape methods: - `Add`, `Sub`, `Intersect`, `Xor`, `Inverse` - `Transl`, `RotX`, `RotY`, `RotZ`, `Scale`, `Repeat` ## Regions - `DefRegion(region, shape)` - `DefRegionCell(region, i, j, k)` - `RedefRegion(old, new)` - `regions` - `NREGION` Quantity region methods commonly used in scripts: - `SetRegion(region, valueOrFunction)` - `Region(region)` - `GetRegion(region)` ## Magnetization And Initial States - `m` - `Uniform(mx, my, mz)` - `RandomMag()`, `RandomMagSeed(seed)` - `Vortex(circulation, polarization)`, `VortexWall(mxLeft, mxRight, circulation, polarization)` - `NeelSkyrmion(charge, polarization)`, `BlochSkyrmion(charge, polarization)` - `TwoDomain(...)` - `m.Set(config)`, `m.SetRegion(region, config)`, `m.SetInShape(shape, config)`, `m.LoadFile(path)` ## Material Parameters Common scalar parameters: - `Msat`, `Aex`, `alpha` - `Ku1`, `Ku2`, `Kc1`, `Kc2`, `Kc3` - `Dind`, `Dbulk` - `Temp` For thermal noise, `ThermSeed(seed)` sets its random seed; `randSeed(seed)` controls the general random functions instead. See `compatibility_notes.md` for version-sensitive use. Common vector parameters: - `anisU`, `anisC1`, `anisC2` Spin-torque/current parameters: - `J`, `Pol`, `xi`, `Lambda`, `EpsilonPrime` - `FixedLayer`, `FixedLayerPosition`, `FIXEDLAYER_TOP`, `FIXEDLAYER_BOTTOM`, `FreeLayerThickness` - `DisableZhangLiTorque`, `DisableSlonczewskiTorque` ## Fields And Excitation - `B_ext`, `B_ext.Add(mask, value)`, `B_ext.RemoveExtraTerms()` - `Vector(x, y, z)` - `NewVectorMask(nx, ny, nz)`, `NewScalarMask(nx, ny, nz)`, `NewSlice(ncomp, nx, ny, nz)` - `LoadFile(path)` ## Output Quantities Common spatial or table quantities: - `m`, `B_ext`, `B_eff`, `B_demag`, `B_exch`, `B_anis`, `B_therm`, `torque` - `E_total`, `E_demag`, `E_exch`, `E_anis`, `E_Zeeman`, `E_therm` - `MaxAngle`, `LastErr`, `NEval`, `NSteps`, `dt`, `t` - `Average(quantity)`, `Min(quantity)`, `Max(quantity)`, `Sum(quantity)`, `Crop(...)` ## Scheduling And Saving - `Save(quantity)`, `SaveAs(quantity, path)` - `AutoSave(quantity, period)` - `TableAdd(quantity)`, `TableAddVar(value, name, unit)` - `TableAutoSave(period)`, `TableSave()`, `TablePrint(...)` - `Snapshot(quantity)`, `SnapshotAs(quantity, path)` - `OutputFormat`, `TableAdd`, `TableAutoSave` Add table columns once during setup. `TableAdd` and `TableAddVar` define table columns; `TableSave` writes a row. Avoid calling `TableAddVar` inside a field loop to record changing values. Prefer table columns for existing quantities such as `B_ext` and `m`, or postprocess derived quantities in Python. ## Running And Solver Control - `Relax()`, `Minimize()` - `Run(seconds)`, `RunWhile(condition)` - `SetSolver(id)` - `FixDt`, `MinDt`, `MaxDt`, `MaxErr`, `Headroom` - `RelaxTorqueThreshold`, `RelaxWallClockTime`skills/mumax3/references/api_patterns.md14 KB8882faa43ac7upstream ↗
# mumax3 API Patterns Use this reference for common API combinations. It is not a full API list; check `api_index.md`, `api_full.md`, or the official API page when an identifier is not covered here. Source baseline: official mumax3.12 API, <https://mumax.github.io/api.html>. ## Mesh And Periodic Boundaries Prefer mesh dimensions that are powers of two, or at least products of small prime factors such as 2, 3, 5, and 7. Keep cell sizes in SI units and derive them from physical dimensions to avoid hidden unit conversions. ```go nx := 256 ny := 128 nz := 1 Lx := 512e-9 Ly := 256e-9 Lz := 2e-9 SetGridSize(nx, ny, nz) SetCellSize(Lx/nx, Ly/ny, Lz/nz) ``` Use `SetPBC(px, py, pz)` only when the model is physically periodic. A nonzero value enables wrap-around in that direction and controls how many repeated images the demag field sees; large values can make initialization slow. ```go SetPBC(4, 4, 0) // thin-film periodicity in x and y ``` Cross-check identifiers: `SetGridSize`, `SetCellSize`, `SetMesh`, and `SetPBC` are listed in `api_index.md#mesh-and-geometry` and `api_full.md#mesh-size-and-geometry`. ## Shape Composition Shapes are defined around the simulation-box center and use meters. Compose simple shapes first, then call `SetGeom` once unless a deliberate resize or geometry change is part of the experiment. ```go disk := Circle(160e-9) notch := Rect(30e-9, 80e-9).Transl(80e-9, 0, 0) wire := Rect(800e-9, 120e-9) SetGeom(wire.Sub(notch).Add(disk.Transl(-250e-9, 0, 0))) SaveAs(geom, "geom.ovf") ``` Common shape methods: `Add`, `Sub`, `Intersect`, `Xor`, `Inverse`, `Transl`, `RotX`, `RotY`, `RotZ`, `Scale`, and `Repeat`. Prefer named intermediate shapes over deeply nested expressions when reviewing or parameterizing scripts. Cross-check identifiers: `Rect`, `Circle`, `Cuboid`, `Cylinder`, range shapes, and shape methods are listed in `api_index.md#mesh-and-geometry` and `api_full.md#shapes`. ## Regions Regions are mutually exclusive cell labels. Each cell belongs to exactly one region, with region 0 as the default. Save `regions` when debugging spatial assignment, especially after overlapping shape definitions or cell-level edits. ```go core := Circle(80e-9) rim := Circle(140e-9).Sub(core) DefRegion(1, core) DefRegion(2, rim) SaveAs(regions, "regions.ovf") ``` Use `DefRegionCell` for sparse cell-index assignments, not for large masks that are easier to express as shapes. Use `RedefRegion(old, new)` when remapping existing labels is clearer than redefining shapes. ```go DefRegionCell(3, 0, 0, 0) RedefRegion(3, 2) ``` Cross-check identifiers: `DefRegion`, `DefRegionCell`, `RedefRegion`, `regions`, and `NREGION` are listed in `api_index.md#regions` and `api_full.md#material-regions`. ## Material And Quantity Region Values Assigning a quantity directly sets it globally. Use `SetRegion` only for region-specific values and keep region constants close to the region definition. ```go Msat = 800e3 Aex = 13e-12 alpha = 0.01 Msat.SetRegion(1, 580e3) alpha.SetRegion(2, 0.08) ``` Vector quantities also support region-specific assignment. ```go anisU = Vector(0, 0, 1) anisU.SetRegion(1, Vector(1, 0, 0)) B_ext.SetRegion(2, Vector(0, 5e-3, 0)) ``` Each cell has one region label. For local anisotropy lines or bands, save the region map before running and inspect whether later definitions overwrite an absorber or another material zone. If two independently varying properties must overlap, use deliberate combined regions or a mask/custom-quantity approach supported by the target mumax3 version. For magnetization, use `m.Set(...)` globally, `m.SetRegion(...)` by material region, or `m.SetInShape(...)` for geometric seeds independent of region labels. ```go m = Uniform(1, 0, 0) m.SetRegion(1, Vortex(1, 1)) m.SetInShape(Circle(40e-9), Uniform(0, 0, 1)) ``` Cross-check identifiers: material parameters and `m` methods are listed in `api_index.md#magnetization-and-initial-states`, `api_index.md#material-parameters`, and `api_full.md#material-parameters`. ## Relaxation And Dynamics Use `Relax()` for robust relaxation from arbitrary or noisy starting states. Turn off excitations first: temperature, current, and time-dependent fields should not be active during relaxation. During `Relax()`, precession is disabled and simulation time `t` does not advance. ```go B_ext = Vector(0, 0, 0) J = Vector(0, 0, 0) Temp = 0 Relax() SaveAs(m, "relaxed.ovf") ``` Use `Minimize()` for faster energy minimization when the state is already near a minimum, such as consecutive field steps in a hysteresis loop. It is less robust than `Relax()` for random or far-from-equilibrium initial states. ```go B := -50e-3 for i:=0; i<=20; i++{ B_ext = Vector(B, 0, 0) Minimize() TableSave() B += 5e-3 } ``` Use `Run(duration)` for time dynamics. Use `RunWhile(condition)` only when the stopping condition is itself part of the model, such as switching or a moving feature crossing a threshold. ```go TableAutoSave(2e-12) AutoSave(m, 50e-12) Run(2e-9) mx := m.Comp(0) RunWhile(mx.Average() < 0) ``` Cross-check identifiers: `Relax`, `Minimize`, `Run`, `RunWhile`, `Steps`, and time quantities are listed in `api_index.md#running-and-solver-control` and `api_full.md#running`. Official API guidance treats `Relax()` as a relaxation helper that disables precession and does not advance `t`, while `Minimize()` is recommended for hysteresis-style neighboring states. The official examples use `Relax()` for a random high-energy starting state, then `Minimize()` inside the hysteresis field loop. ## Solver Control The default adaptive solver is usually appropriate. Only set solver controls when the task needs a fixed-step method, tighter error control, or a documented reproduction of a previous run. ```go MaxErr = 1e-6 MinDt = 1e-16 MaxDt = 1e-12 Run(1e-9) ``` Use `SetSolver(4)` with `FixDt` for fixed-step RK4-style runs. Use Euler (`SetSolver(1)`) only for debugging or exceptional cases because it requires `FixDt` and ignores other accuracy settings. ```go SetSolver(4) FixDt = 1e-15 Run(200e-12) FixDt = 0 SetSolver(5) ``` Cross-check identifiers: `SetSolver`, `FixDt`, `MaxErr`, `MinDt`, `MaxDt`, `Headroom`, `LastErr`, and `dt` are listed in `api_index.md#running-and-solver-control` and `api_full.md#running`. ## Loading And Output Use `m.LoadFile(path)` to load a magnetization state into `m`. Use top-level `LoadFile(path)` when an API expects a `Slice`, such as mask or custom quantity work. ```go m.LoadFile("relaxed.ovf") mask := LoadFile("source_mask.ovf") ``` Use `Save` for conventional auto-named field output and `SaveAs` when later automation expects a stable filename. Use `AutoSave` for spatial snapshots and `TableAutoSave` for time series. `table.txt` includes time and average magnetization by default; add other quantities explicitly. ```go OutputFormat = OVF2_BINARY TableAdd(B_ext) TableAdd(E_total) TableAdd(MaxAngle) TableAdd(torque) TableAutoSave(5e-12) AutoSave(m, 100e-12) SaveAs(m, "m_final.ovf") SaveAs(B_eff, "B_eff_final.ovf") ``` `TableAdd` and `TableAddVar` are column-registration calls. Put them before the run or sweep loop, then use `TableSave()` inside the loop to append rows. If a derived value changes at each sweep point and is awkward to express as a mumax3 scalar function, save the underlying quantities and compute the derived column in Python. This follows the official hysteresis example: `TableAdd(B_ext)` is called once before the field loops, and each loop iteration updates `B_ext`, calls `Minimize()`, then calls `TableSave()`. Recommended field-loop pattern: ```go TableAdd(B_ext) TableAdd(E_total) for i:=0; i<=20; i++{ B_ext = Vector(-50e-3 + i*5e-3, 0, 0) Minimize() TableSave() } ``` Risky pattern: ```go for i:=0; i<=20; i++{ h := -50e-3 + i*5e-3 B_ext = Vector(h, 0, 0) Minimize() TableAddVar(h, "H", "T") TableSave() } ``` For region-specific output, call `.Region(region)` on quantities that support it, or `.Comp(component)` for vector components. ```go TableAdd(m.Region(1)) SaveAs(m.Comp(2), "mz_final.ovf") ``` Region/component/crop methods shape output and averages; they do not define material regions or change the simulated geometry. Use `DefRegion` and region-specific material assignments for physical regions, then use `.Region(...)`, `.Comp(...)`, or `Crop*` only to select what is saved or added to the table. Cross-check identifiers: `LoadFile`, `Save`, `SaveAs`, `AutoSave`, `TableAdd`, `TableAddVar`, `TableAutoSave`, and output quantities are listed in `api_index.md#scheduling-and-saving`, `api_index.md#output-quantities`, `api_full.md#scheduling-output`, and `api_full.md#output-quantities`. Cropping helpers are listed in `api_full.md#slicing-and-dicing-output`. ## Common Quantities To Monitor Use a small, purposeful output set instead of saving every quantity. - `m`: magnetization state; use table averages for aggregate response, or OVF for spatial analysis and state reuse. - `B_eff`: effective field; useful for diagnostics after relaxation. - `E_total`: scalar energy; useful in minimization and hysteresis checks. - `MaxAngle`: neighbor-spin angle; useful for mesh-quality and convergence diagnostics. - `torque` or `maxTorque`: useful for relaxation quality, but interpret in the context of solver settings and model scale. ```go TableAdd(E_total) TableAdd(MaxAngle) TableAdd(torque) TableAutoSave(10e-12) ``` Check `api_full.md#output-quantities` before using less common quantities such as `LLtorque`, `STTorque`, `Edens_*`, or extension-provided diagnostics. ## Time-Dependent Inputs When an API accepts a function, mumax3 can implicitly re-evaluate an expression over time. Do not store a time-dependent expression in an ordinary variable unless a one-time evaluation is intended. Correct dynamic assignment: ```go f := 10e9 h0 := 1e-3 B_ext = Vector(0, h0*sin(2*pi*f*t), 0) ``` Risky if the intent was dynamic: ```go drive := h0*sin(2*pi*f*t) B_ext = Vector(0, drive, 0) ``` For localized excitation, combine a mask with a scalar time function. ```go source := NewVectorMask(nx, ny, nz) for i:=0; i<nx; i++{ for j:=0; j<ny; j++{ if i < 8 { source.SetVector(i, j, 0, Vector(0, 0, 1)) } } } B_ext.Add(source, h0*sin(2*pi*f*t)) ``` Use `B_ext.RemoveExtraTerms()` before replacing added excitation terms in staged runs. Cross-check identifiers: `B_ext`, `NewVectorMask`, `NewScalarMask`, `Vector`, `sin`, `pi`, and `t` are listed in `api_index.md#fields-and-excitation` and `api_full.md#excitation`. ## Spin Currents Spin-current scripts are advanced enough to require official-API confirmation. Keep torque model choices explicit. For Zhang-Li-style current-driven dynamics, set `J`, `Pol`, and `xi`, and disable the Slonczewski torque if it should not contribute. ```go DisableSlonczewskiTorque = true J = Vector(1e12, 0, 0) Pol = 0.6 xi = 0.05 Run(1e-9) ``` For Slonczewski torque, define the fixed layer and geometry assumptions explicitly. ```go DisableZhangLiTorque = true J = Vector(0, 0, 8e11) Pol = 0.5 FixedLayer = Vector(0, 0, 1) FixedLayerPosition = FIXEDLAYER_TOP FreeLayerThickness = 1.2e-9 Lambda = 1 EpsilonPrime = 0.02 ``` When `J` varies in space, preserve the mask as a reproducible input artifact and state whether its values represent experimental charge-current density or an effective spin-current input. Save or hash the mask, and verify its grid and cell size against the loaded magnetization checkpoint. Cross-check in `api_full.md#spin-currents` and the official API before using spin-torque parameters. ## Moving Window Use moving-window helpers only for models where the physical feature can leave the simulation box, such as domain walls or bubbles. Add `TotalShift` to the table so downstream analysis can reconstruct absolute position. ```go ext_centerWall(0) ext_rmSurfaceCharge(0, -1, 1) TableAdd(TotalShift) Run(5e-9) ``` The default inserted edge magnetization is usually sufficient. Override `ShiftMagL`, `ShiftMagR`, `ShiftGeom`, `ShiftM`, or `ShiftRegions` only when the boundary behavior is part of the intended model. Cross-check in `api_full.md#moving-simulation-window` and the official API. Extension APIs can be version-sensitive. Treat every `ext_*` name as version-sensitive. Before using an extension in a generated script, confirm it in the official API for the target mumax3 version and make the modeling assumption explicit in the script or case metadata. ## Custom Quantities Custom quantities combine existing quantities point-wise. They are useful for diagnostics, derived fields, or saved postprocessing inputs. Keep the expression short and verify component/scalar dimensions before using it in analysis. ```go mx := m.Comp(0) my := m.Comp(1) mxy2 := Add(Mul(mx, mx), Mul(my, my)) SaveAs(mxy2, "mxy2.ovf") ``` For finite-difference expressions, make the stencil and cell-size assumptions visible in variable names and comments. Prefer built-in extension quantities when they exactly match the needed diagnostic. Cross-check in `api_full.md#custom-quantities` and the official API. ## Custom Effective Fields Custom field and energy terms directly affect dynamics and should be treated as model changes, not output conveniences. Define both the field term and matching energy density when energy accounting matters, then add diagnostics for `B_custom`, `E_custom`, or `Edens_custom`. ```go Ms := 800e3 K := 2e5 u := ConstVector(0, 0, 1) anisField := Mul(Const(2*K/Ms), Mul(Dot(u, m), u)) anisEdens := Mul(Const(-0.5*Ms), Dot(anisField, m)) AddFieldTerm(anisField) AddEdensTerm(anisEdens) TableAdd(E_custom) ``` Call `RemoveCustomFields()` or `RemoveCustomEnergies()` before replacing custom terms in staged scripts. Cross-check in `api_full.md#custom-effective-field-terms` and the official API. ## Magnetic Force Microscopy MFM output is a derived image-style diagnostic for 2D magnetization. Set the lift height explicitly and save `MFM` under a name that records that choice. ```go MFMLift = 50e-9 SaveAs(MFM, "mfm_lift_50nm.ovf") ``` Use `MFMDipole` only when the tip model needs a finite vertically magnetized section instead of the default point-monopole approximation. Cross-check in `api_full.md#magnetic-force-microscopy` and the official API.skills/mumax3/references/case_status.md1.8 KB64bf594e9443upstream ↗
# Optional case-status collector Use `scripts/collect_case_status.py` only for directories containing `params.json` or a top-level `.mx3`, with nested `*.out` outputs. It reports file presence and recorded metadata; it neither executes MuMax3 nor proves completion, convergence or physical validity. Existing project status tools take precedence. The collector accepts these optional records; none is required for ordinary scripts: | Record | Fields interpreted | | --- | --- | | `params.json` | `case_id`, `status`, `error_message`; `configuration_signature` / `config_signature` / `case_signature`; `checkpoint_sha256` / `static_input_sha256` / `input_sha256`; `dynamic_signature` | | `run_record.json` | `status` | | `analysis_record.json` | `analysis_signature` / `signature`, `dynamic_signature` | | `manual_review.json` | `status` / `classification`, `dynamic_signature`, `analysis_signature` | | `manifest.json` or `case_manifest.json` | Presence and JSON validity only, at case or selected root level | `--result-root` places analysis/review lookup under a parallel case tree; otherwise those records live in each case directory. Missing optional records are allowed; malformed ones are reported. Unrelated fields are ignored. Older stage-numbered signatures are no longer aliases: map them explicitly to the appropriate generic field when adopting this collector. Do not assume a stage number has the same meaning across projects. `analysis_fresh` means comparable recorded dynamic signatures agree, not that data hashes were recomputed or the analysis is correct. No comparable signature means `analysis_unverified`. `derived_status` remains separate from recorded run/review status. A plain `.out` directory without source/params is not discovered. Custom output paths require a project-specific adapter rather than a mandatory new directory layout.skills/mumax3/references/compatibility_notes.md3.4 KBbaa59bf88c7cupstream ↗
# Compatibility Notes Use this reference when a task touches advanced mumax3 features, version-sensitive behavior, or Python workflow boundaries. ## Version Baseline Runtime references in this skill target the official mumax3.12 API page. For older installations, confirm identifiers against the matching official API version before using advanced features. Official API: <https://mumax.github.io/api.html> Official examples: <https://mumax.github.io/examples.html> ## Verified Environment On 2026-05-12, the Phase 2 smoke examples and release-candidate expected-output scripts were checked in a Windows environment with: - `mumax3.exe` from `mumax3.12_windows_cuda12.9`. - `mumax3 -vet` accepted the tracked expected-output scripts used by the release validation. - Earlier short smoke runs produced expected `*.ovf`, `table.txt`, `log.txt`, and `references.bib` outputs. mumax3 reported a non-fatal CPU-info probe error in this environment, while GPU execution and output generation succeeded. ## Script Language Boundary mumax3 input syntax is Go-like and case-insensitive for API identifiers, but it is not a full Go runtime. Use host-side tools for filesystem/JSON/CSV processing, plotting and multiprocessing. Native loops are appropriate for sequential field steps; external orchestration is optional. ## Advanced Features Check `api_full.md` and official docs before using: - Spin currents and torque parameters. - Moving window controls. - Custom quantities and custom effective field terms. - MFM helpers. - Slicing/cropping helpers beyond simple `SaveAs`. - Thermal noise: `Temp` controls temperature and `ThermSeed(int)` seeds thermal noise; `randSeed(int)` seeds general random functions. Check solver/timestep suitability and reproducibility for the intended model and installed version. - Magnetoelastic or extension APIs. ## Official Semantic Anchors The following behavior is treated as baseline guidance for this skill: - Table output: official API documents `TableAdd` as adding a quantity column, `TableAddVar` as adding a user-defined variable column, and `TableSave` as appending one row. The official hysteresis example calls `TableAdd(B_ext)` before loops and `tablesave()` inside each field step. - Built-ins: official examples use built-ins such as `mu0`, `pi`, `t`, and runtime quantities directly. Do not redeclare these names with `:=`. - Running stages: official API describes `Relax()` as a relaxation helper where precession is disabled and simulation time `t` does not advance; `Minimize()` is well suited to nearby hysteresis states; `Run()` advances dynamics. - Solver control: Euler (`SetSolver(1)`) is only appropriate with an explicit fixed time step through `FixDt`. - Extension APIs: `ext_*` names are advanced/version-sensitive and should be checked against the exact installed mumax3 version before use. ## Python Ecosystem Boundary Default backend should remain native mumax3 execution. Python can orchestrate cases and analyze results. Ubermag, `discretisedfield`, `micromagneticdata`, or notebooks may help with data handling, but do not rewrite a native mumax3 workflow into another framework unless the user asks or a pilot proves feature coverage. ## Output Formats OVF output is the default field-data path for downstream analysis. Table output is appropriate for scalar or region-averaged time series. Confirm conversion tools and file readers before promising a specific postprocessing pipeline.skills/mumax3/references/examples.md2.2 KBa8da9a24aa53upstream ↗
# Runnable mumax3 Examples These examples are intentionally generic and original to this repository. They are smoke-test style starting points, not calibrated physical studies. ## Minimal Thin-Film Relaxation ```go // Output and mesh. OutputFormat = OVF2_TEXT nx := 128 ny := 64 nz := 1 Lx := 512e-9 Ly := 256e-9 Lz := 2e-9 SetGridSize(nx, ny, nz) SetCellSize(Lx/nx, Ly/ny, Lz/nz) // Geometry and material. SetGeom(Rect(Lx, Ly)) Msat = 800e3 Aex = 13e-12 alpha = 0.02 // Initial state, output, and run stage. m = Uniform(1, 0, 0) TableAdd(m) TableAutoSave(1e-12) Relax() SaveAs(m, "m_relaxed.ovf") TableSave() ``` ## Region-Based Bilayer Strip ```go OutputFormat = OVF2_TEXT nx := 128 ny := 64 nz := 2 Lx := 384e-9 Ly := 192e-9 Lz := 2e-9 SetGridSize(nx, ny, nz) SetCellSize(Lx/nx, Ly/ny, Lz/nz) SetGeom(Rect(Lx, Ly)) DefRegion(1, Layer(0)) DefRegion(2, Layer(1)) SaveAs(regions, "regions.ovf") Msat.SetRegion(1, 800e3) Msat.SetRegion(2, 650e3) Aex.SetRegion(1, 13e-12) Aex.SetRegion(2, 10e-12) alpha.SetRegion(1, 0.02) alpha.SetRegion(2, 0.03) m = Uniform(1, 0, 0) TableAdd(m.Region(1)) TableAdd(m.Region(2)) TableAutoSave(2e-12) Relax() SaveAs(m, "m_bilayer_relaxed.ovf") ``` ## Local AC Field Dynamics ```go OutputFormat = OVF2_TEXT nx := 256 ny := 64 nz := 1 Lx := 768e-9 Ly := 192e-9 Lz := 2e-9 SetGridSize(nx, ny, nz) SetCellSize(Lx/nx, Ly/ny, Lz/nz) SetGeom(Rect(Lx, Ly)) Msat = 800e3 Aex = 13e-12 alpha = 0.01 m = Uniform(1, 0, 0) Relax() SaveAs(m, "m_static.ovf") mask := NewVectorMask(nx, ny, nz) for i:=0; i<8; i++{ for j:=0; j<ny; j++{ mask.SetVector(i, j, 0, Vector(0, 1, 0)) } } h0 := 1e-3 f := 5e9 B_ext.Add(mask, h0*sin(2*pi*f*t)) TableAdd(m) TableAutoSave(5e-12) AutoSave(m, 20e-12) Run(2e-9) SaveAs(m, "m_dynamic_final.ovf") ``` ## Review Notes - Keep dimensions and parameters explicit near the top. - Use SI units. - Save `regions` when region layout matters. - Use direct time-dependent expressions in API calls that accept functions. - Use native loops when each step continues from the preceding state; use external orchestration for independent cases. See [worked workflows](worked_workflows.md) for complete examples and analysis.skills/mumax3/references/installation.md4.6 KB39eb2e3725c2upstream ↗
# Install MuMax3 Read this only when setting up MuMax3 or diagnosing a missing executable/GPU. Installing this agent skill does not install the simulator. This skill targets MuMax3 `.mx3` scripts; MuMax+ is a separate simulator with different installation and APIs, not a drop-in replacement. ## Check the environment first Identify the OS, architecture, existing MuMax3 path, GPU and driver. Use read-only checks before choosing a download: ```text nvidia-smi nvidia-smi --query-gpu=name,driver_version,compute_cap --format=csv ``` Locate MuMax3 with `Get-Command mumax3 -ErrorAction SilentlyContinue` in PowerShell or `command -v mumax3` on Linux. In WSL, check `wsl --status` and `wsl -l -v` from Windows, then check GPU access inside the selected distribution. Some WSL GPU queries are unavailable; use the GPU model and NVIDIA documentation if needed. MuMax3 3.12 requires an NVIDIA GPU with compute capability 5.0 or later and a compatible NVIDIA driver. The chosen binary's CUDA version can impose a higher GPU requirement: match all three in the [official download selector](https://mumax.github.io/download.html). An AMD/Intel-only or Apple Silicon machine needs access to a compatible NVIDIA host to run these simulations. Python is optional for MuMax3 itself and used separately by this skill's helpers. ## Prefer an official binary 1. Choose the native Windows or Linux archive matching the target OS, driver and GPU on the official download page. On Windows, prefer the native package unless an existing workflow needs Linux/WSL. 2. Download and extract it into a user-owned directory. Keep an existing working version until the replacement has been verified. These binaries do not require installing the full CUDA Toolkit, Go or a compiler. 3. Run the executable by its full path first. Add its containing directory to the user `PATH` if desired, then open a new terminal and confirm that it resolves to the intended installation. 4. In a scratch directory, run the official installation check, `mumax3 -test` (or `./mumax3 -test` on Linux before setting `PATH`). Record the exit code and reported version/GPU. This checks execution, not a scientific model. Use `mumax3 -vet path/to/script.mx3` for a subsequent script syntax check. If startup fails, compare the driver and GPU against the selected binary before changing the system. Prefer another compatible official build when appropriate; do not assume the newest CUDA build supports every GPU. The CUDA version shown by `nvidia-smi` describes driver capability, not an installed Toolkit. ## WSL 2, when needed Use a supported Windows host, WSL 2 with an updated kernel, a Linux distribution such as Ubuntu, and a compatible NVIDIA Windows driver. Follow [Microsoft's CUDA on WSL setup](https://learn.microsoft.com/en-us/windows/ai/directml/gpu-cuda-in-wsl) and [NVIDIA's WSL guide](https://docs.nvidia.com/cuda/wsl-user-guide/index.html), then install the Linux MuMax3 binary inside WSL. The Windows driver supplies GPU access to WSL: **do not install a Linux NVIDIA display driver inside WSL**. NVIDIA's WSL GPU requirements differ from native MuMax3's minimum; confirm support for the actual GPU. Only add a WSL-compatible CUDA Toolkit if compiling from source, avoiding packages that also install Linux drivers. ## Build from source only when necessary Use the [official MuMax3 build instructions](https://github.com/mumax/3#building-from-source) for a required patch or unsupported binary combination. Select a release/tag and follow its requirements: NVIDIA driver, supported CUDA Toolkit, Go and compatible C toolchain. The current instructions specify CUDA at most 12.9; recheck for the selected source version rather than blindly installing the newest Toolkit. Linux uses GCC/make; Windows has additional MSVC and Go C-toolchain requirements and a `deploy_windows.ps1` build route. Set GPU architecture and toolchain paths as instructed, then verify the resulting executable. ## Agent-assisted installation An agent can inspect the environment, select a compatible official package, explain the destination and proposed changes, and perform the installation when the user has authorized that scope. Reading this guide or asking for a script does not authorize software installation. Confirm any unapproved driver/Toolkit installation, administrator action, persistent environment change or reboot; continue within existing authorization without asking twice. Report the executable path, version, verification result and any remaining limitation. Example request: “Check my OS and NVIDIA GPU, propose a compatible MuMax3 installation, then install it in a user directory once the required changes are authorized.”skills/mumax3/references/language_subset.md1.6 KB03a53d766827upstream ↗
# mumax3 Script Language Subset mumax3 scripts are parsed with Go syntax but compiled by a small interpreter. A syntactically valid Go fragment may still be rejected by mumax3. ## Supported Basics - Case-insensitive API identifiers: `msat`, `Msat`, and `MSAT` refer to the same API object. - Variables: `x := ...` declares a new variable; `x = ...` assigns an existing variable. - Basic literals: integers, floats, strings, booleans through predefined `true` and `false`. - Blocks introduce scope. ## Supported Statements - Empty statements. - Expression statements: `Print(x)`, `Save(m)`. - Single assignment: `=`, `:=`, `+=`, `-=`. - Increment/decrement: `i++`, `i--`. - `if` / `else`. - Basic `for` loops, including omitted init/condition/post. Avoid `switch`, `select`, `range`, `return`, `defer`, `go`, `break`, `continue`, labels, and declarations. ## Supported Expressions - Identifiers. - Basic literals. - Binary expressions: `+`, `-`, `*`, `/`, comparisons, `&&`, `||`. - Unary expressions: `-x`, `!ok`. - Function calls and method calls. - Parenthesized expressions. - Index expressions for slices/arrays. Use `pow(x, y)` for powers. Use `mod` or `remainder` for remainder-like operations. ## Time-Dependent Values If an API accepts a function, mumax3 may implicitly convert an expression into a re-evaluated function. Do not store time-dependent expressions in ordinary variables unless a one-time evaluation is intended. Correct for dynamic material/field inputs: ```go B_ext.Add(mask, h0*sin(2*pi*f*t)) ``` Potentially static if evaluated first: ```go value := sin(2*pi*f*t) B_ext.Add(mask, h0*value) ```skills/mumax3/references/output_and_reproducibility.md5.2 KB79ff39fdbd0cupstream ↗
# Output And Reproducibility Use this reference when choosing outputs, sampling, or reused inputs. For scans, see `parameter_sweep.md`. ## Case Records Keep the `.mx3` source and inputs needed to reproduce the result. Independent cases need non-colliding outputs, not a prescribed directory or manifest schema. A self-contained script can hold its own parameters; generated cases may benefit from a separate parameter record and engine version/command. For checkpoint reuse, identify the actual input and its physical role: preparation field/protocol, material, geometry and mesh compatibility. A relaxed state may stay in memory when stages share one script; saving a checkpoint is useful for later reuse or analysis, not a mandatory stage boundary. SHA256 can verify reused content or cache identity when needed by the task. It cannot establish physical suitability. If a downstream decision relies on an earlier result, check the relevant evidence and acceptance criteria; project contracts may require ancestry checks, but ordinary scripts need no ancestor registry. ## Output Directories When a launcher, shared workspace, or multiple cases make output paths ambiguous, record the intended path and keep cases isolated. Prefer `mumax3 -o <stage>.out` when the installed version supports it. Without `-o`, a script named `stage.mx3` conventionally produces `stage.out`; reconcile the actual directory rather than guessing from similarly named paths. If the engine exits successfully but its output location is not yet confirmed, record that uncertainty and investigate before deciding whether to rerun. Record the command, working directory, output location, and return code to the degree needed to reproduce or diagnose the case. Output discovery is not a scientific-completeness check. `-f` can clean an existing output directory, so use it only when the requested overwrite policy permits removal of the old output. ## mumax3 Output Conventions - `Save(quantity)` writes a space-dependent quantity with an automatic name. - `SaveAs(quantity, "name.ovf")` writes a space-dependent quantity with a chosen name. - `AutoSave(quantity, period)` writes snapshots periodically. - `TableAdd(quantity)` adds table columns; `TableAutoSave(period)` schedules table output. - `TableSave()` appends a table row immediately. - `Snapshot`/`SnapshotAs` writes images when image output is desired. For scripts with region logic, `SaveAs(regions, "regions.ovf")` is a useful debug artifact. ## Sampling And Completion Select quantities, cadence and time window for the intended measurement. A global response can use averaged tables; spatial modes or texture motion may need fields. When a conclusion relies on a time sequence, check its relevant window for gaps or missing critical times. A frame-count percentage alone does not establish scientific completeness. Choose cadence from the analysis goal. Periodic or phase-sensitive analysis needs enough samples, phase coverage, and windows to support the intended inference; one fixed cadence or component set does not fit every problem. Estimate output size from the grid, quantities, frame plan, and product needs before a large run, using margins appropriate to the task. ## Optional Naming Convention - Include key scanned parameters in case IDs or folder names, not every output filename. - Prefer stable filenames inside a case folder: `m_initial.ovf`, `m_relaxed.ovf`, `m_final.ovf`, `regions.ovf`. - Avoid fixed filenames across a sweep unless each run has an isolated working directory. ## Derived Products Keep analysis inputs and relevant settings identifiable so a presentation change need not rerun dynamics. Repeated plotting can use a profile for units and normalization; a one-off plot needs no profile framework. Display choices and scientific evidence need not use the same quantities or order. ## Logs And Postprocessing - Capture stdout and stderr from the native `mumax3` process. - Store generated scripts next to parameters, not only templates. - Keep analysis scripts separate from raw simulation outputs. - Write derived tables with explicit units in column names or metadata. Project-specific backup, retention, release, and storage procedures belong in that project's documentation. ## Helper Script Invocations Render a repository template after listing the required placeholders: ```powershell python skills\mumax3\scripts\render_template.py skills\mumax3\assets\templates\minimal_relax.mx3.template --list python skills\mumax3\scripts\render_template.py skills\mumax3\assets\templates\minimal_relax.mx3.template --params params.json --output script.mx3 ``` Optional layout-specific status collector (not a general MuMax output scanner): ```powershell python skills\mumax3\scripts\collect_case_status.py runs\field_frequency_sweep --recursive --csv results\case_status.csv ``` The collector discovers cases containing `params.json` or a top-level `.mx3`, and expects nested `*.out` outputs. `--result-root` supports its conventional analysis/manual-review JSON records; see [case_status.md](case_status.md) for its optional schema before adopting those conventions. A standalone `.out` without source/params is not discovered. Reported freshness compares recorded signatures, not actual physics or file hashes. Use an existing task's status command when available.skills/mumax3/references/paper_reconstruction.md4.1 KB5099cd1b6ecdupstream ↗
# From a paper to a reproduced phenomenon Use this workflow when the task starts from a paper or a figure. Default to an **exploratory reconstruction**: make the main phenomenon and its trend appear in a small, understandable simulation. A useful first result is a working model and an explanation of what controls it. Use a quantitative comparison when the relevant parameters are available or the user asks for it. ## Read toward one observable Start with the target figure, its caption, and the methods or supplementary passages that explain it. Identify what changes, what is measured, and the preparation sequence. For a broad request, choose one central effect that the available backend can model and proceed. If the paper is unavailable, work from the supplied excerpt and identify the missing source briefly. Translate the target into an observable: edge canting needs a spatial magnetization profile; switching needs a time trace; a resonance needs a spectrum; texture motion needs positions over time. Match the axes and units before comparing shapes. An average can cancel the local effect you want to see. ## Build the smallest useful model Recover geometry, energy terms, material scales, boundaries, and the order **prepare → relax → drive → observe**. A static equilibrium figure may need only preparation and relaxation. Map terms to supported MuMax3 quantities using the existing API references. Keep the mechanism responsible for the effect; simplify dimensions, geometry or the parameter range when they are not the target. Use reported values where available. For a missing damping, mesh or drive duration, choose a reasonable starting value and state it briefly as an assumption. Derive useful scales such as `sqrt(A/K_eff)`, a precession period or a propagation time to choose cells and duration. A short note beside the parameters is usually enough; missing secondary details do not need a questionnaire before the first run. Ask only when a choice changes the target itself or the required physics has no suitable implementation. Reuse a nearby script or template, then change the model and protocol deliberately. Check SI units and order of magnitude, energy/sign conventions, and whether the saved quantity is actually the plotted observable. For example, do not add full demagnetization while keeping a reported effective anisotropy that already includes its local contribution. ## Run, inspect, adjust Start with one small case and a useful control, such as removing or reversing the driving interaction. Use native continuation if the effect depends on its previous state; reset the initial state for independent comparisons. Save just the trace or field maps needed for the target, and extract the observable with a short analysis step. Look first for the effect's existence, direction, spatial or temporal shape, and response to a control parameter. If it is absent, check preparation and relaxation, field/current direction, boundary conditions, and whether averaging hid it. If the shape is right but the scale differs, adjust the most relevant parameter or observation window. Change one physical explanation at a time with a few small runs, rather than launching a broad search. For an exploratory result, explain the observed trend without imposing a universal error threshold or a full convergence campaign. If a quantitative question emerges, use the available paper values and compare that observable more closely; refine the mesh, timestep or preparation where it could explain the discrepancy. ## Keep a short result note Four lines in the answer or example README are sufficient: - **Target/source:** paper section or figure and the chosen phenomenon. - **Model:** reported parameters plus the few assumptions or simplifications used. - **Run/result:** what actually ran, the observed feature and a useful number or plot. - **Next adjustment:** the most informative change, if the result still differs. Keep assumed values distinct from reported ones, and actual simulation output distinct from an analytic sketch or synthetic test. See the [DMI edge-canting example](../examples/paper_edge_canting/README.md) for a complete paper-to-script-to-profile reconstruction.skills/mumax3/references/parameter_sweep.md1.9 KB363d850a56a6upstream ↗
# Parameter Sweep Guidance Choose native MuMax3 loops for sequential parameter steps, such as a hysteresis sweep that continues from the previous state. External tools such as Python are useful for independent cases, parallel execution, fitting, and plotting; they are not required for every scan. ## Plan And Execute Define the parameters, units, case-selection rule, and expected analysis before generating a sweep. Begin with a small pilot when it can expose rendering, resource, or interpretation problems cheaply. Render each case's `.mx3` script from its chosen parameters when generating independent cases, capture useful engine logs, and make rerun behavior explicit rather than silently overwriting completed outputs. Use the case record and output/sampling guidance in `output_and_reproducibility.md` instead of maintaining a second required layout or metadata list. Isolate cases so their scripts and MuMax3 output directories cannot collide. ## Analyze For The Structure And Question Select measurements that match both the simulated structure and the scientific question. Crop absorbers or source near fields when they would bias a propagation or focusing metric, and retain the static reference and time window needed to interpret dynamic quantities. Examples include wall position for domain walls; core or texture trajectories for vortices and skyrmions; reference-relative dynamic components, spectra, mode maps, or propagation metrics for FMR and spin waves; and magnetization curves for hysteresis. These are options, not a mandatory evidence checklist. Save derived values with units and enough input provenance to reproduce the comparison. ## Python Tools `numpy`, `pandas`, `scipy`, and `matplotlib` cover many sweeps. `scikit-image` can help with contours; Ubermag, `discretisedfield`, and `micromagneticdata` can be useful for notebooks and field data. Choose libraries for the analysis need without rewriting an established MuMax3 workflow unnecessarily.skills/mumax3/references/structures.md2.7 KB3e93a809d1a4upstream ↗
# Micromagnetic Structure Patterns Use this reference to choose a compact modeling pattern for common structures. It is not a physics handbook; verify material constants, mesh resolution, and boundary conditions against the user's model. ## Thin Film Or Nanostrip - Use one or a few cells through thickness when the model is effectively two-dimensional. - Prefer mesh dimensions with small prime factors for GPU performance. - Start with `SetGeom(Rect(Lx, Ly))` or the full mesh box. - Choose table quantities for averages and field saves for spatial analysis or state reuse. ## Material Heterostructure - Define each material with `DefRegion(region, shape)` or `DefRegionCell`. - Assign material quantities per region with `Msat.SetRegion`, `Aex.SetRegion`, `alpha.SetRegion`, anisotropy, DMI, or spin-torque parameters as needed. - Save `regions` when inspecting or reusing a nontrivial region layout would help. - Remember that each cell has one region; overlapping shapes require deliberate ordering. ## Domain Wall - Use `TwoDomain(...)`, `m.SetInShape(...)`, or explicit left/right shapes to seed domains. - Keep wall initialization separate from material regions. - For propagation, use case-specific field or current parameters and table output that can locate the wall later. - If using absorbing boundaries, reserve non-conflicting region IDs and document which cells are absorbers. ## Vortex - Use disk or square geometry with `Circle`, `Cylinder`, `Square`, or `Rect`. - Initialize with `Vortex(circulation, polarization)` when the built-in configuration matches the task. - For core-motion studies, choose field snapshots or suitable table quantities for trajectory analysis. ## Skyrmion - Use `NeelSkyrmion` or `BlochSkyrmion` only when compatible with the intended DMI and material model. - Include DMI through `Dind` or `Dbulk` as appropriate. - Relax before applying current or dynamic fields unless the user asks for a deliberately non-equilibrium initial condition. ## FMR And Spin Waves - For response about equilibrium, prepare a relaxed static state; save it if needed for reuse or reference subtraction. - Apply a small uniform or local time-dependent field with `B_ext` or `B_ext.Add(mask, expression)`. - Keep the dynamic expression inline if it depends on `t`. - Use time-resolved averages for global response, and field snapshots when spatial modes or propagation are needed. Choose sampling and duration for the requested frequency range and resolution. ## Periodic Systems - Use `SetPBC(px, py, pz)` before or with mesh setup. - Keep PBC counts modest unless the demag approximation requires more images. - State which directions are periodic in comments and metadata.skills/mumax3/references/worked_workflows.md2.5 KB6252a522f850upstream ↗
# Worked workflows Choose a case by the decision it teaches. All files below are included when installing the `mumax3` skill; repository-level prompts remain separate evaluation material. | Question | Worked case | Evidence and limit | | --- | --- | --- | | Must each parameter step inherit the previous state? | [Continuous hysteresis](../examples/hysteresis/README.md) | Branch ordering and switching fields against a macrospin energy model; not an independent-case grid. | | Does a transient simulation reproduce a specified problem? | [Standard Problem 4](../examples/standard_problem4/README.md) | Reversal trajectory and first-crossing field snapshot; reference comparison and mesh convergence are separate checks. | | How do outputs become an observable? | [Pulsed macrospin FMR](../examples/fmr/README.md) | Time sampling, windowed spectrum and analytic frequency; not a spatial spin-wave model. | For a paper-driven task, start with [paper reconstruction](paper_reconstruction.md) and its [DMI edge-canting case](../examples/paper_edge_canting/README.md). That case uses a separate spatial-profile analyzer and a short result note, without a reproduction score. Read the selected case's assumptions and acceptance criteria before adapting it. Keep the initial state/protocol when comparing runs; change mesh at fixed physical dimensions for convergence, and change observation time at fixed cadence for frequency resolution. Parameter changes can invalidate an analytic comparison even if the script still runs. The companion `scripts/analyze_tutorial.py` reads native MuMax3 tables, verifies the documented output contract, and writes CSV plus a JSON summary. Analysis-specific scalar parameters are recorded by the `.mx3` into table columns, rather than separately copied into analysis defaults. Preserve the input script and engine version for the full model and solver settings. OVF checks establish file presence and header only; open the field maps separately to assess their contents. Its checks are deliberately specific to these three cases. Do not use a passing tutorial check as acceptance of an unrelated research model. Run cases in a new scratch directory. Scripts write `m_initial.ovf`, `m_final.ovf` and `table.txt`; SP4 also saves the first sampled reversal state. Read each README for commands and additional conditions. The analysis requires Python 3.10+ with the standard library. The actual engine, including ordinary `-vet`, initializes CUDA; CPU-only tests check generation and synthetic analysis without claiming an engine run.skills/mumax3/assets/templates/local_ac_field.mx3.template1.4 KB16ba43c23204upstream ↗
// Generic local AC-field dynamics template. // Replace all placeholder tokens before running with mumax3. // Output format. OutputFormat = OVF2_TEXT // Mesh. nx := {{nx}} ny := {{ny}} nz := {{nz}} cell_x := {{cell_x}} cell_y := {{cell_y}} cell_z := {{cell_z}} SetGridSize(nx, ny, nz) SetCellSize(cell_x, cell_y, cell_z) // Geometry. length_x := cell_x*nx length_y := cell_y*ny SetGeom(Rect(length_x, length_y)) // Material. Msat = {{Msat}} Aex = {{Aex}} alpha = {{alpha}} // Initial state. m = Uniform({{m_init_x}}, {{m_init_y}}, {{m_init_z}}) // Static field and relaxation stage. B_ext = Vector({{bias_Bx}}, {{bias_By}}, {{bias_Bz}}) TableAdd(m) TableAutoSave({{table_period}}) Relax() SaveAs(m, "{{static_state_ovf}}") // Local AC field. source := NewVectorMask(nx, ny, nz) for i:=0; i<nx; i++{ for j:=0; j<ny; j++{ for k:=0; k<nz; k++{ r := Index2Coord(i, j, k) x := r.X() if abs(x-({{source_center_x}})) < {{source_half_width}} { source.SetVector(i, j, k, Vector({{source_dir_x}}, {{source_dir_y}}, {{source_dir_z}})) } } } } B_ext.Add(source, {{source_amplitude}}*sin(2*pi*{{source_frequency}}*t)) // Output. AutoSave(m, {{snapshot_period}}) // Run stage. Run({{run_time}}) SaveAs(m, "{{final_state_ovf}}") TableSave()skills/mumax3/assets/templates/minimal_relax.mx3.template710 B77f99785db83upstream ↗
// Generic thin-film relaxation template. // Replace all placeholder tokens before running with mumax3. // Output format. OutputFormat = OVF2_TEXT // Mesh. nx := {{nx}} ny := {{ny}} nz := {{nz}} cell_x := {{cell_x}} cell_y := {{cell_y}} cell_z := {{cell_z}} SetGridSize(nx, ny, nz) SetCellSize(cell_x, cell_y, cell_z) // Geometry. length_x := cell_x*nx length_y := cell_y*ny SetGeom(Rect(length_x, length_y)) // Material. Msat = {{Msat}} Aex = {{Aex}} alpha = {{alpha}} // Initial state. m = Uniform({{m_init_x}}, {{m_init_y}}, {{m_init_z}}) // Output. TableAdd(m) TableAutoSave({{table_period}}) // Run stage. Relax() SaveAs(m, "{{relaxed_state_ovf}}") TableSave()skills/mumax3/assets/templates/thin_film_with_region.mx3.template1.2 KB4054d9dca602upstream ↗
// Generic region-aware thin-film relaxation template. // Replace all placeholder tokens before running with mumax3. // Output format. OutputFormat = OVF2_TEXT // Mesh. nx := {{nx}} ny := {{ny}} nz := {{nz}} cell_x := {{cell_x}} cell_y := {{cell_y}} cell_z := {{cell_z}} SetGridSize(nx, ny, nz) SetCellSize(cell_x, cell_y, cell_z) // Geometry. length_x := cell_x*nx length_y := cell_y*ny SetGeom(Rect(length_x, length_y)) // Regions. // region 1 is x < {{region_split_x}}; region 2 is x >= {{region_split_x}}. DefRegion(1, XRange(-length_x/2, {{region_split_x}})) DefRegion(2, XRange({{region_split_x}}, length_x/2)) SaveAs(regions, "{{regions_ovf}}") // Material. Msat.SetRegion(1, {{Msat_region1}}) Msat.SetRegion(2, {{Msat_region2}}) Aex.SetRegion(1, {{Aex_region1}}) Aex.SetRegion(2, {{Aex_region2}}) alpha.SetRegion(1, {{alpha_region1}}) alpha.SetRegion(2, {{alpha_region2}}) // Initial state. m = Uniform({{m_init_x}}, {{m_init_y}}, {{m_init_z}}) // Field. B_ext = Vector({{B_ext_x}}, {{B_ext_y}}, {{B_ext_z}}) // Output. TableAdd(m.Region(1)) TableAdd(m.Region(2)) TableAutoSave({{table_period}}) // Run stage. Relax() SaveAs(m, "{{relaxed_state_ovf}}") TableSave()skills/mumax3/agents/openai.yaml234 B655cfc6c8514upstream ↗
interface: display_name: "mumax3" short_description: "Write and parameterize mumax3 scripts" default_prompt: "Use $mumax3 to write or review a mumax3 .mx3 simulation script." policy: allow_implicit_invocation: trueskills/mumax3/examples/fmr/script.mx3885 B0afa9b50fc32upstream ↗
// Pulsed macrospin FMR with demagnetization and anisotropy disabled. SetGridSize(1, 1, 1) SetCellSize(5e-9, 5e-9, 5e-9) EnableDemag = false Msat = 800e3 Aex = 0 Ku1 = 0 alpha = 0.01 GammaLL = 1.7595e11 MaxErr = 1e-7 bias := 0.1 pulse := 1e-3 pulseDuration := 50e-12 samplePeriod := 5e-12 nSamples := 2000 B_ext = Vector(0, 0, bias) m = Uniform(0, 0, 1) Relax() SaveAs(m, "m_initial.ovf") B_ext = Vector(pulse, 0, bias) Run(pulseDuration) B_ext = Vector(0, 0, bias) TableAdd(B_ext) TableAddVar(bias, "bias_T", "T") TableAddVar(alpha.GetRegion(0), "damping", "1") TableAddVar(GammaLL, "gamma_rad_s_T", "rad/s/T") TableAddVar(pulseDuration, "pulse_s", "s") TableAddVar(samplePeriod, "sample_s", "s") TableAddVar(nSamples*samplePeriod, "observe_s", "s") SetSolver(4) FixDt = samplePeriod/10 TableSave() for i:=0; i<nSamples; i++{ Steps(10) TableSave() } SaveAs(m, "m_final.ovf")skills/mumax3/examples/hysteresis/script.mx31.0 KB76f47670ebceupstream ↗
// Continuous near-easy-axis macrospin loop; see README.md for its scope. SetGridSize(1, 1, 1) SetCellSize(5e-9, 5e-9, 5e-9) EnableDemag = false Msat = 800e3 Aex = 0 Ku1 = 50e3 anisU = Vector(1, 0, 0) alpha = 0.5 fieldLimit := 0.2 nIntervals := 40 fieldStep := 2*fieldLimit/nIntervals transverse := 0.001 // avoids an exactly collinear, zero-torque unstable state branch := -1 B_ext = Vector(fieldLimit, transverse, 0) m = Uniform(1, 0.02, 0) Relax() SaveAs(m, "m_initial.ovf") TableAdd(B_ext) TableAdd(E_total) TableAddVar(branch, "branch", "1") TableAddVar(fieldLimit, "field_limit_T", "T") TableAddVar(fieldStep, "field_step_T", "T") TableAddVar(transverse, "transverse_T", "T") TableAddVar(2*Ku1.GetRegion(0)/Msat.GetRegion(0), "anisotropy_field_T", "T") for i:=0; i<=nIntervals; i++{ B_ext = Vector(fieldLimit-i*fieldStep, transverse, 0) Relax() TableSave() } branch = 1 for i:=1; i<=nIntervals; i++{ B_ext = Vector(-fieldLimit+i*fieldStep, transverse, 0) Relax() TableSave() } SaveAs(m, "m_final.ovf")skills/mumax3/examples/paper_edge_canting/observed_profiles.svg16 KB6dc13817df43upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/mumax3/examples/paper_edge_canting/script.mx31.2 KBf0a318a87cd4upstream ↗
// Exploratory reconstruction of Rohart & Thiaville (2013), Fig. 1 / Sec. III A. // Local effective-anisotropy model, invariant along y; lengths in SI. OutputFormat = OVF2_TEXT nx := 128 width := 100e-9 SetGridSize(nx, 1, 1) SetCellSize(width/nx, 1e-9, 1e-9) SetPBC(0, 1, 0) EnableDemag = false OpenBC = false Msat = 1.1e6 Aex = 16e-12 Ku1 = 510e3 anisU = Vector(0, 0, 1) alpha = 0.5 B_ext = Vector(0, 0, 0) caseIndex := 0 dValue := 0.0 TableAddVar(caseIndex, "case_index", "1") TableAddVar(dValue, "D_paper_J_m2", "J/m2") TableAddVar(Aex.GetRegion(0), "A_J_m", "J/m") TableAddVar(Ku1.GetRegion(0), "K_J_m3", "J/m3") TableAddVar(Dind.GetRegion(0), "Dind_J_m2", "J/m2") TableAdd(E_total) for caseIndex = 0; caseIndex < 4; caseIndex++ { dValue = 0 if caseIndex == 1 { dValue = 1.5e-3 } if caseIndex == 2 { dValue = 3e-3 } if caseIndex == 3 { dValue = -3e-3 } // Match the sign of the paper's Eq. (2); MuMax3 uses the opposite convention. Dind = -dValue // Independent preparations, not a continuation sweep. m = Uniform(0, 0, 1) Relax() SaveAs(m, sprintf("m_case_%d.ovf", caseIndex)) TableSave() }skills/mumax3/examples/standard_problem4/script.mx3926 B3edaf4611210upstream ↗
// muMAG SP4, field 1. Parameters follow NIST; initialization follows MuMax3. nx := 128 ny := 32 nz := 1 SetGridSize(nx, ny, nz) SetCellSize(500e-9/nx, 125e-9/ny, 3e-9/nz) Msat = 800e3 Aex = 13e-12 Ku1 = 0 alpha = 0.02 MaxErr = 1e-6 B_ext = Vector(0, 0, 0) m = Uniform(1, 0.1, 0) Relax() SaveAs(m, "m_initial.ovf") // For field 2, use (-35.5e-3, -6.3e-3, 0) in a fresh independent run. B_ext = Vector(-24.6e-3, 4.3e-3, 0) samplePeriod := 1e-12 nSamples := 1000 crossingTime := -1.0 mx := m.Comp(0) TableAdd(B_ext) TableAdd(E_total) TableAddVar(samplePeriod, "sample_s", "s") TableAddVar(nSamples*samplePeriod, "observe_s", "s") TableAddVar(crossingTime, "crossing_time_s", "s") SetSolver(4) FixDt = samplePeriod/10 TableSave() for i:=0; i<nSamples; i++{ Steps(10) if crossingTime < 0 && mx.Average() <= 0 { crossingTime = t SaveAs(m, "m_crossing.ovf") } TableSave() } SaveAs(m, "m_final.ovf")
Plain-text copy, no login: /skill-bundles/msjs2333-mumaxwriter-skill-skills-mumax3.md